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
66ca1e39198836fe3f41e14a6802852fe21d1c3a
fixed date problem 2
timer.js
timer.js
//new Date(year, month, day, hours, minutes, seconds, milliseconds) window.countDownDate = new Date(2019,3,30).getTime(); // Update the count down every 1 second var x = setInterval(function() { countDownDate = new Date(""); if (window.countDownDate !== undefined) { // Get todays date and time var now = new Date().getTime(); // Find the distance between now an the count down date var distance = window.countDownDate - now; // Time calculations for days, hours, minutes and seconds var days = Math.floor(distance / (1000 * 60 * 60 * 24)); var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60)); var seconds = Math.floor((distance % (1000 * 60)) / 1000); // Display the result in the element with id="demo" document.getElementById("demo").innerHTML = days + "d " + hours + "h " + minutes + "m " + seconds + "s "; // If the count down is finished, write some text if (distance < 0) { clearInterval(x); document.getElementById("demo").innerHTML = "EXPIRED"; } } }, 1000);
JavaScript
0.998352
@@ -115,16 +115,51 @@ Time();%0A +console.log(window.countDownDate);%0A %0A%0A// Upd @@ -228,42 +228,8 @@ () %7B -%0A countDownDate = new Date(%22%22); %0A%0A
e3f627aafaf256f8211cea547eb54392c570976d
clean up ast trap
traps.js
traps.js
function empty () { return "" } module.exports = function (namespace, names) { var obj = {}; for (var k in traps) obj[k] = (names.indexOf(k) !== -1 ? traps[k] : (k[0] === k[0].toUpperCase() ? empty : forwards[k])) .bind(null, namespace); return obj; } var traps = {}; var forwards = {}; //////////// // Others // //////////// traps.Ast = function (namespace, ast, url) { return namespace+".Ast("+ast+","+url+");" } traps.Strict = function (namespace, index) { return namespace+".Strict("+index+");" } traps.literal = function (namespace, value, index) { return namespace+".literal("+value+","+index+")" }; forwards.literal = function (_, value, _) { return value }; traps.unary = function (namespace, operator, value, index) { return namespace+".unary("+JSON.stringify(operator)+","+value+","+index+")" }; forwards.unary = function (_, operator, value, _) { return operator+"("+value+")" }; traps.binary = function (namespace, operator, left, right, index) { return namespace+".binary("+JSON.stringify(operator)+","+left+","+right+","+index+")" }; forwards.binary = function (_, operator, left, right, _) { return "("+left+" "+operator+" "+right+")" }; ///////////////// // Environment // ///////////////// traps.Declare = function (namespace, kind, variables, index) { return namespace+".Declare("+JSON.stringify(kind)+","+JSON.stringify(variables)+","+index+");" } traps.read = function (namespace, variable, index) { return namespace+".read("+JSON.stringify(variable)+","+variable+","+index+")" }; forwards.read = function (_, variable, _) { return variable }; traps.write = function (namespace, variable, value, index) { return "("+variable +"="+namespace+".write("+JSON.stringify(variable)+","+variable+","+value+","+index+"))" }; forwards.write = function (_, variable, value, _) { return "("+variable+"="+value+")" }; traps.Enter = function (namespace, index) { return namespace+".Enter("+index+");" }; traps.Leave = function (namespace, index) { return namespace+".Leave("+index+");" }; /////////// // Apply // /////////// traps.apply = function (namespace, fct, ths, args, idx) { return namespace+".apply("+fct+","+(ths||"void 0")+",["+args.join(",")+"],"+idx+")" }; forwards.apply = function (namespace, fct, ths, args, _) { return ths ? namespace+".__apply__("+fct+","+ths+",["+args.join(",")+"])" : "("+fct+"("+args.join(",")+"))"; }; traps.construct = function (namespace, constructor, arguments, index) { return namespace+".construct("+constructor+",["+arguments.join(",")+"],"+index+")" }; forwards.construct = function (_, constructor, arguments, _) { return "new "+constructor+"("+arguments.join(",")+")" }; traps.Arguments = function (namespace, index) { return namespace+".Arguments(arguments,"+index+");" }; traps.return = function (namespace, value, index) { return namespace+".return("+value+","+index+")" }; forwards.return = function (_, value, _) { return value }; traps.eval = function (namespace, arguments, index) { return "eval("+namespace+".eval(["+arguments.join(",")+"][0],"+index+"))" }; forwards.eval = function (_, arguments, _) { return "eval("+arguments.join(",")+")" }; //////////// // Object // //////////// traps.get = function (namespace, computed, object, property, index) { return namespace+".get("+object+","+(computed ? property : JSON.stringify(property))+","+index+")" }; forwards.get = function (_, computed, object, property, _) { return object+(computed ? "["+property+"]" : "."+property) }; traps.set = function (namespace, computed, object, property, value, index) { return namespace+".set("+object+","+(computed ? property : JSON.stringify(property))+","+value+","+index+")" }; forwards.set = function (_, computed, object, property, value, _) { return "("+object+(computed ? "["+property+"]" : "."+property)+"="+value+")" }; traps.delete = function (namespace, computed, object, property, index) { return namespace+".delete("+object+","+(computed ? property : JSON.stringify(property))+","+index+")" }; forwards.delete = function (_, computed, object, property, _) { return "delete "+object+(computed ? "["+property+"]" : "."+property) }; traps.enumerate = function (namespace, object, index) { return namespace+".enumerate("+object+","+index+")" }; forwards.enumerate = function (_, object, _) { return "(function(o){var ks=[];for(var k in o) ks[ks.length]=k;return ks;}("+object+"))" }; ///////////// // Control // ///////////// traps.test = function (namespace, value, index) { return namespace+".test("+value+","+index+")" }; forwards.test = function (_, value, _) { return value }; traps.Label = function (namespace, label, index) { return namespace+".Label("+JSON.stringify(label)+","+index+");" }; traps.Break = function (namespace, label, index) { return namespace+".Break("+JSON.stringify(label)+","+index+");" }; traps.throw = function (namespace, value, index) { return namespace+".throw("+value+","+index+")" }; forwards.throw = function (_, value, _) { return value }; traps.Try = function (namespace, index) { return namespace+".Try("+index+");" }; traps.catch = function (namespace, variable, index) { return namespace+".catch("+JSON.stringify(variable)+","+variable+","+index+");" }; forwards.catch = function (_, variable, _) { return variable }; traps.Finally = function (namespace, index) { return namespace+".Finally("+index+");" };
JavaScript
0.000001
@@ -355,98 +355,8 @@ //%0A%0A -traps.Ast = function (namespace, ast, url) %7B return namespace+%22.Ast(%22+ast+%22,%22+url+%22);%22 %7D%0A%0A trap
d7d27a0b23b4c872b21148f7f64ffddf6c4b05a9
change error message
tree1.js
tree1.js
// newick tree // console.log(JSON.stringify(tnt.tree.parse_newick(newick))) var newick = ""; var tree = tnt.tree(); var parsedObj = tnt.tree.parse_newick(newick); var newickInput = document.getElementById("userInput").value; var treeCreated = false; tree.on("click", function (node) { var root = tree.root(); //node.sort(function (node, node.parent()) {return 1}); var tempTree = root.subtree(node.get_all_leaves()); var nodeParent = node.parent(); tree.data(tempTree.data()); //tree.node_display(tree.node_display() //.size(10) //.fill("cyan")); tree.update(); }); function makeTree () { if (parsedObj != null) { treeCreated = true; } if (treeCreated = false) { throw 'Error reading Newick'; } document.getElementById("treemaker").innerHTML="" tree .data(parsedObj) .node_display(tree.node_display() .size(10) .fill("gray") ) .label (tnt.tree.label.text() .fontsize(12) .height(50) ) .layout(tnt.tree.layout.vertical() .width(300) .scale(false) ); tree(document.getElementById("treemaker")); } function submitNewick () { newick=document.getElementById("userInput").value; parsedObj=tnt.tree.parse_newick(newick); makeTree(); } function submitFile() { var reader=new FileReader (); reader.addEventListener("loadend", function() { // reader.result contains the contents of blob as a typed array document.getElementById("fileInput").innerText = reader.result; }); console.log(document.getElementById("fileInput").innerText); newick=reader.readAsText(reader.result); parsedObj=tnt.tree.parse_newick(newick); makeTree(); } function updateVertical() { tree.layout(tnt.tree.layout.vertical().width(300).scale(false)); tree.update(); } function updateRadial() { { tree.layout(tnt.tree.layout.radial().width(300).scale(false)); tree.update(); } }
JavaScript
0.000001
@@ -705,36 +705,45 @@ -throw 'Error reading Newick' +console.log(%22error should be thrown%22) ;%0A%7D%0A
b1636625525fe0f3ef444c603d54c977f5cfe4bd
add helpful comments ~:20
git-time-log.js
git-time-log.js
#!/usr/bin/env node /* global module, require, process, console */ var gitlog = require('gitlog'), _ = require('underscore'), moment = require('moment'), program = require('commander'); var GitTimeLog = function (opts) { opts = opts || {}; this._repo = opts['repo'] || '.'; this._author = opts['author']; this._number = opts['number'] || 9999999; this.formatTime = function (totalMins) { var duration = moment.duration({ minutes: totalMins }), hours = Math.floor(duration.asHours()), mins = totalMins - (hours * 60); // ensure mins is 2 characters in length if (mins.toString().length < 2) { mins = '0' + mins.toString(); } // allow hours to be an empty string hours = hours !== 0 ? hours.toString() : ''; return '~' + hours + ':' + mins; }; this.getTimeFromMessage = function (message) { var timeRegex = /~(\d?\d?):(\d\d)/, match = message.match(timeRegex), hours, minutes; hours = match ? match[1] : null; minutes = match ? match[2] : null; hours = parseInt(hours, 10) || 0; minutes = parseInt(minutes, 10) || 0; return { hours: hours, minutes: minutes }; }; this.getMinsFromMessage = function (message) { var messageTime = this.getTimeFromMessage(message); return (messageTime.hours * 60) + messageTime.minutes; }; this.parseCommits = function (parseFn) { gitlog({ repo: this._repo, author: this._author, fields: ['subject', 'authorEmail'], number: this._number }, function (err, commits) { if (err) { throw(err); } parseFn(commits); } ); }; this.minsByAuthor = function (done) { var self = this; this.parseCommits(function (commits) { // calculate the total time in commit messages var totalByUser = _.reduce(commits, function (totals, commit) { var userTotal = totals[commit.authorEmail] || 0, commitMins = self.getMinsFromMessage(commit.subject); // add to the totals totals[commit.authorEmail] = userTotal + commitMins; return totals; }, {}); done(totalByUser); }); }; this.totalMinutes = function (done) { var self = this; this.parseCommits(function (commits) { // calculate the total time in commit messages var total = _.reduce(commits, function (total, commit) { return total + self.getMinsFromMessage(commit.subject); }, 0); done(total); }); }; }; module.exports = GitTimeLog; // For command-line usage... program .version('0.0.1') .option('-d, --dir <path>', 'Set the path to parse. Defaults to current directory.') .option('-a, --author <author>', 'Returns only time for the given author.') .option('-n, --number <number>', 'Number of commits to parse.'); program .command('authors') .description('Returns time by author') .action(function(env){ var gtl = new GitTimeLog({ repo: program.dir, number: program.number }); gtl.minsByAuthor(function (results) { _.each(results, function (totalMins, author) { console.log(author + ': ' + gtl.formatTime(totalMins)); }); }); }); program .command('total') .description('Returns total time for repo') .action(function(env){ var gtl = new GitTimeLog({ repo: program.dir, author: program.author, number: program.number }); gtl.totalMinutes(function (mins) { console.log(gtl.formatTime(mins)); }); }); program.parse(process.argv);
JavaScript
0
@@ -366,16 +366,66 @@ 99999;%0A%0A + // formats minutes into tilde-based time format%0A this.f @@ -455,24 +455,24 @@ otalMins) %7B%0A - var dura @@ -861,32 +861,142 @@ ' + mins;%0A %7D;%0A%0A + // parses a commit message for a tilde-based time entry%0A // and returns an object with hours and minutes%0A this.getTimeFr @@ -1342,24 +1342,117 @@ es %7D;%0A %7D;%0A%0A + // parses a commit message for a tilde-based time entry%0A // and returns time as minutes%0A this.getMi @@ -1606,24 +1606,83 @@ utes;%0A %7D;%0A%0A + // applies parseFn to each commit (for %3Cnumber%3E commits)%0A this.parse @@ -1979,24 +1979,136 @@ );%0A %7D;%0A%0A + // parses the commits, then asynchronously calls done(), %0A // passing an array of %7B authorEmail: minutes %7D%0A this.minsB @@ -2610,24 +2610,159 @@ %7D);%0A %7D;%0A%0A + // parses the commits, then asynchronously calls done(), %0A // passing the total minutes logged (for %3Cnumber%3E commits by %3Cauthor%3E)%0A this.total
f627cdc5d9b2df3e6e60c21acd7d0b5eea51d2c1
Replace maintainerd link in log message
github/index.js
github/index.js
const fetch = require("node-fetch"); const qs = require("qs"); const { load } = require("js-yaml"); const { includes, find } = require("lodash"); const { getInstallationToken } = require("./installation-token"); const NEXT_ENTRY_MARKER = "<!-- log tail -->"; const timeStamp = () => new Date().toISOString(); const getNewLog = sha => getUpdatedLog(`[maintainerd](http://maintainerd.divmain.com/) logging is enabled for this repository. All actions related to rules and their enforcement will be logged here as a permanent record. --- <details> <summary>Click to view log...</summary> <p> ${NEXT_ENTRY_MARKER} </p></details> `, sha, "The pull request was created"); const getUpdatedLog = (oldLog, sha, entry) => oldLog.replace( NEXT_ENTRY_MARKER, ` - \`${timeStamp()}:${sha.slice(0, 7)}\`: ${entry}\n${NEXT_ENTRY_MARKER}` ); exports.GitHub = class GitHub { constructor (installationId) { this.installationId = installationId; } get (urlSegment) { return this.fetch("GET", urlSegment); } post (urlSegment, body) { return this.fetch("POST", urlSegment, JSON.stringify(body)); } patch (urlSegment, body) { return this.fetch("PATCH", urlSegment, JSON.stringify(body)); } async fetch (method, urlSegment, body) { const installationToken = await getInstallationToken(this.installationId); const headers = { "User-Agent": "divmain/maintainerd", "Accept": "application/vnd.github.machine-man-preview+json", "Authorization": `token ${installationToken}` }; const opts = { method, headers }; if (method === "POST" || method === "PATCH" || method === "PUT") { headers["Content-Type"] = "application/json"; opts.body = body; } return fetch(`https://api.github.com${urlSegment}`, opts); } getConfig (repoPath) { return this.get(`/repos/${repoPath}/contents/.maintainerd`) .then(response => response.json()) .then(json => Buffer.from(json.content, "base64").toString()) .then(yamlString => load(yamlString, "utf8")); } updateCommit (repoPath, sha, context, failureMessage) { const state = failureMessage ? "failure" : "success"; const description = failureMessage ? failureMessage : "maintainerd thanks you!"; const [ org, repo ] = repoPath.split("/"); const queryString = qs.stringify({ org, repo, sha }); return this.post(`/repos/${repoPath}/statuses/${sha}?${queryString}`, { state, description: description || "", context }); } async getPullRequest(repoPath, pullRequestNumber) { const response = await this.get(`/repos/${repoPath}/pulls/${pullRequestNumber}`); return response.json(); } updatePullRequest (pullRequestData, patchJson) { const { pullRequestNumber, repoPath } = pullRequestData; return this.patch(`/repos/${repoPath}/pulls/${pullRequestNumber}`, patchJson); } async getPullRequestCommits (repoPath, pullRequestNumber) { const response = await this.get(`/repos/${repoPath}/pulls/${pullRequestNumber}/commits`); return response.json(); } async postComment (repoPath, issueNumber, body) { const response = await this.post(`/repos/${repoPath}/issues/${issueNumber}/comments`, { body }); return response.json(); } async createLogPost (repoPath, pullRequestNumber, sha) { return this.postComment(repoPath, pullRequestNumber, getNewLog(sha)); } async getComments (repoPath, issueNumber) { const response = await this.get(`/repos/${repoPath}/issues/${issueNumber}/comments`); return response.json(); } async getLogComment (repoPath, issueNumber) { const comments = await this.getComments(repoPath, issueNumber); return find(comments, comment => includes(comment.body, NEXT_ENTRY_MARKER)); } async updateLogPost (repoPath, pullRequestNumber, sha, logEntry) { const logComment = await this.getLogComment(repoPath, pullRequestNumber); if (!logComment) { return; } const { id, body } = logComment; const newBody = getUpdatedLog(body, sha, logEntry); const response = await this.patch(`/repos/${repoPath}/issues/comments/${id}`, { body: newBody }); return response.json(); } };
JavaScript
0
@@ -368,35 +368,42 @@ http +s :// -maintainerd.divmain.com/ +github.com/divmain/maintainerd ) lo
c75b4fb15576656403f61a96e1d6473e029ed094
Move SessionsAPI to own type
types.js
types.js
/* @flow */ // The standard runnable actions export type Runnable<T> = { run: () => Promise<?T> }; export type ParticipantRole = 'HOST' | 'GUEST'; // Defines the options for new participants export type NewParticipant = { +display_name: string, +fee?: JSONFee, +role: ParticipantRole, +picture?: string, +state?: string }; // Defines the options for updating participants export type UpdateParticipant = { +display_name?: string, +fee?: JSONFee, +role?: ParticipantRole, +picture?: string, +state?: string }; // Defines the options for creating a new session export type SessionCreate = { session_name: string, start_time: string, end_time: string, picture?: string, participants?: Array<NewParticipant> }; // Defines the options for when updating an existing session export type SessionUpdate = { session_name: ?string, start_time: string, end_time: string, picture: ?string }; // Defines the options for when querying the sessions export type SessionPageQuery = {| page?: number, page_size?: number, start_time?: string, end_time?: string, included_canceled?: boolean |}; // The response from a paged query export type PagedResponse<T> = {| content: Array<T>, more: boolean, page: number, page_size: number |}; // Alias for the fee (this may be replaced at some point as it's currently stored as a JSON string) export type JSONFee = string; // The structure for the fee that is stored within the JSONFee string export type Fee = { amount: number, description: ?string, currency: string }; // The information for the participant in a call export type CallParticipant = {| client_id: string, deleted_at?: string, display_name: string, entry_url: string, fee?: JSONFee, participant_id: string, picture: ?string, role: ParticipantRole, session_id: string, state: ?string |}; // The information for a created call session export type CallSession = {| +session_id: string, +session_name: ?string, +start_time: string, +end_time: string, +picture: ?string, +team_id: string, +client_id: string, +participants: Array<CallParticipant> |}; export type CoviuClientSDK = {| sessions: { addParticipant: (sessionId: string, participant: NewParticipant) => Runnable<CallParticipant>, cancelSession: (sessionId: string) => Runnable<any>, createSession: (SessionCreate) => Runnable<?CallSession>, deleteParticipant: (participantId: string) => Runnable<any>, deleteSession: (sessionId: string) => Runnable<?any>, getParticipant: (participantId: string) => Runnable<CallParticipant>, getSession: (sessionId: string) => Runnable<CallSession>, getSessionParticipants: (sessionId: string) => Runnable<Array<CallParticipant>>, getSessions: (query: SessionPageQuery) => Runnable<PagedResponse<CallSession>>, updateParticipant: (participantId: string, update: UpdateParticipant) => Runnable<CallParticipant>, updateSession: (sessionId: string, update: SessionUpdate) => Runnable<CallSession>, } |};
JavaScript
0
@@ -2154,44 +2154,25 @@ ype -CoviuClientSDK = %7B%7C%0A sessions: %7B%0A +SessionsAPI = %7B%7C%0A ad @@ -2264,18 +2264,16 @@ ipant%3E,%0A - cancel @@ -2319,18 +2319,16 @@ e%3Cany%3E,%0A - create @@ -2379,18 +2379,16 @@ ssion%3E,%0A - delete @@ -2442,18 +2442,16 @@ e%3Cany%3E,%0A - delete @@ -2498,18 +2498,16 @@ %3C?any%3E,%0A - getPar @@ -2568,26 +2568,24 @@ icipant%3E,%0A - - getSession: @@ -2630,18 +2630,16 @@ ssion%3E,%0A - getSes @@ -2715,18 +2715,16 @@ nt%3E%3E,%0A - - getSessi @@ -2795,18 +2795,16 @@ sion%3E%3E,%0A - update @@ -2897,18 +2897,16 @@ ipant%3E,%0A - update @@ -2987,11 +2987,68 @@ n%3E,%0A - %7D +%7C%7D;%0A%0Aexport type CoviuClientSDK = %7B%7C%0A sessions: SessionsAPI %0A%7C%7D;
7843ac2262441f380e26e16146d0de7e4ae48434
Fix up comments
wecon.js
wecon.js
/* wecon -- Web Console emulator * https://github.com/CylonicRaider/wecon */ /* Hide implementation details in namespace */ this.Terminal = function() { /* Passive UTF-8 decoder */ function UTF8Dec() { this._buffered = []; this.replacement = "\ufffd"; } UTF8Dec.prototype = { /* String.fromCodePoint shim */ _fromCodePoint: (String.fromCodePoint) ? String.fromCodePoint.bind(String) : function(cp) { if (cp <= 0xFFFF) return String.fromCharCode(cp); if (cp > 0x10FFFF) throw RangeError('Bad code point: ' + cp); cp -= 0x10000; return String.fromCharCode(cp >>> 10 | 0xD800, cp & 0x3FF | 0xDC00); }, /* Return by how many bytes the end of the buffer is incomplete, or zero * if not */ _checkIncomplete: function(buffer) { var i, e = buffer.length - 9; if (e < 0) e = 0; for (i = buffer.length - 1; i >= e; i--) { /* Stop at ASCII bytes */ if (! (buffer[i] & 0x80)) break; /* Skip continuation bytes */ if ((buffer[i] & 0xC0) == 0x80) continue; /* Determine sequence length */ var sl = 2; while (sl <= 7 && buffer[i] >> (7 - sl) & 1) sl++; /* Done */ var ret = sl - (buffer.length - i); return (ret < 0) ? 0 : ret; } return 0; }, /* Actually decode */ _decode: function(codes) { var ret = "", i = 0, l = codes.length; while (i < l) { if ((codes[i] & 0x80) == 0x00) { /* ASCII byte */ ret += String.fromCharCode(codes[i++]); } else if ((codes[i] & 0xC0) == 0x80) { /* Orphan continuation byte */ ret += this.replacement; while ((codes[i] & 0xC0) == 0x80) i++; } else { /* Proper sequence */ var cl = 1, v = codes[i++]; /* Determine length */ while (cl <= 6 && v >> (6 - cl) & 1) cl++; var sl = cl + 1, cp = v & (1 << (6 - cl)) - 1; /* Handle truncated sequences */ if (l - i < cl) { ret += this.replacement; break; } /* Compose codepoint */ for (; cl; cl--) { v = codes[i++]; if (v & 0xC0 != 0xC0) break; cp = (cp << 6) | v & 0x3F; } /* Handle bad sequences */ if (cl) { ret += this.replacement; continue; } /* Add to output */ ret += this._fromCodePoint(cp); } } /* Done */ return ret; }, /* Decode the input or part of it, possibly buffering a codepoint */ decode: function(input) { var ret = "", i; /* Take care of buffered codepoint(s) */ if (this._buffered.length) { /* Scan for continuation bytes and buffer them */ for (i = 0; i < input.length; i++) { if ((input[i] & 0xC0) != 0x80) break; this._buffered.push(input[i]); } /* Check if the buffer is (still) incomplete */ if (! this._checkIncomplete(this._buffered)) { /* Flush buffer into return value; cut bytes off input */ ret += this.flush(); } input = input.slice(i); } /* Scan for incomplete sequences and buffer them */ i = this._checkIncomplete(input); if (i) { var e = input.length - i; var tail = Array.prototype.slice.apply(input.slice(e, input.length)); Array.prototype.splice.apply(this._buffered, [this._buffered.length, 0].concat(tail)); input = input.slice(0, e); } /* Decode rest of input */ ret += this._decode(input); return ret; }, /* Forcefully drain the decoder and return any characters left */ flush: function() { if (! this._buffered.length) return ""; /* buffered should only contain invalid sequences, but one can never * know */ var b = this._buffered; this._buffered = []; return this._decode(b); } }; /* Actual terminal emulator. options specifies parameters of the terminal: * width : The terminal should have the given (fixed) width; if not set, * it will adapt to the container. * height : Fixed height. * bell : An <audio> element (or anything having a play() method) that * should be invoked for a BEL character. * visualBell: If true, bells will be indicated by shortly flashing the * terminal output, independently from bell. * scrollback: Maximum length of the scrollback buffer. When not set, all * lines "above" the display area are immediately discarded; * when set to positive infinity, arbitrarily many lines are * stored. */ function Terminal(options) { this.width = options.width; this.height = options.height; this.bell = options.bell; this.visualBell = options.visualBell; this.scrollback = options.scrollback; } Terminal.prototype = { /* Text attribute bits */ ATTR_BOLD : 1, /* Bold */ ATTR_DIM : 2, /* Half-bright */ ATTR_ITALIC : 4, /* Italic */ ATTR_UNDERLINE: 8, /* Underlined */ ATTR_BLINK : 16, /* Blinking */ /* 6 is not assigned */ ATTR_REVERSE : 64, /* Reverse video */ ATTR_HIDDEN : 128, /* Text hidden */ ATTR_STRIKE : 256, /* Strikethrough */ /* Double underline is NYI */ }; /* Return export */ return Terminal; }();
JavaScript
0.000053
@@ -110,16 +110,14 @@ in -namespac +closur e */ @@ -3108,29 +3108,8 @@ alue -; cut bytes off input */%0A @@ -3141,32 +3141,75 @@ sh();%0A %7D%0A + /* Cut buffered bytes off input */%0A input =
213ae2889cc0d0acdcdaf324027127d8ab9f6316
Add AST to schema step in util
packages/idyll-document/src/utils/idl2ast.js
packages/idyll-document/src/utils/idl2ast.js
const compiler = require('idyll-compiler') const fs = require('fs') const { join } = require('path') fs.writeFileSync( join(__dirname, 'ast.json'), JSON.stringify( compiler(fs.readFileSync(join(__dirname, 'src.idl'), 'utf8')), null, 2 ), 'utf8' )
JavaScript
0.000001
@@ -93,16 +93,67 @@ ('path') +%0Aconst %7B splitAST, translate %7D = require('./index') %0A%0Afs.wri @@ -312,8 +312,239 @@ utf8'%0A)%0A +%0Afs.writeFileSync(%0A join(__dirname, 'schema.json'),%0A JSON.stringify(%0A translate(%0A splitAST(%0A JSON.parse(fs.readFileSync(join(__dirname, 'ast.json'), 'utf8'))%0A ).elements%0A ),%0A null,%0A 2%0A ),%0A 'utf8'%0A)%0A
085e8e51720c1f38a36b9cfc5f293349a3065789
add test for onType action
tests/unit/components/ember-selectize-test.js
tests/unit/components/ember-selectize-test.js
import { moduleForComponent, test } from 'ember-qunit'; moduleForComponent('ember-selectize', 'EmberSelectizeComponent'); test('it renders', function() { expect(2); // creates the component instance var component = this.subject(); equal(component._state, 'preRender'); // appends the component to the page this.append(); equal(component._state, 'inDOM'); });
JavaScript
0
@@ -374,8 +374,434 @@ ');%0A%7D);%0A +%0Atest('it sends onType action when changing filter', function() %7B%0A expect(1);%0A%0A var testText = 'dummy text';%0A var component = this.subject();%0A var targetObject = %7B%0A externalAction: function(query) %7B%0A equal(query, testText, 'externalAction was called with proper argument');%0A %7D%0A %7D;%0A%0A component.set('onType', 'externalAction');%0A component.set('targetObject', targetObject);%0A%0A component._onType(testText);%0A%7D);%0A
7f7c9f2a4b8ceba0a17415a88a28495d67a2fb1b
add toastr
config/environment.js
config/environment.js
/* jshint node: true */ module.exports = function(environment) { var ENV = { modulePrefix: 'console', podModulePrefix: 'console/pods', 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 }, contentSecurityPolicy: { 'default-src': "'none'", 'script-src': "'self' 'unsafe-eval' 'unsafe-inline'", 'font-src': "'self'", 'connect-src': "'self' dev.bridgeit.io", 'img-src': "'self' data: *", 'media-src': "'self' dev.bridgeit.io", 'style-src': "'self' 'unsafe-inline'" }, }; 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') { } return ENV; };
JavaScript
0.99896
@@ -830,16 +830,507 @@ ,%0A %7D;%0A%0A + ENV%5B'ember-toastr'%5D = %7B%0A injectAs: 'toast',%0A toastrOptions: %7B%0A closeButton: true,%0A debug: false,%0A newestOnTop: true,%0A progressBar: true,%0A positionClass: 'toast-bottom-left',%0A preventDuplicates: true,%0A onclick: null,%0A showDuration: '300',%0A hideDuration: '1000',%0A timeOut: '4000',%0A extendedTimeOut: '1000',%0A showEasing: 'swing',%0A hideEasing: 'linear',%0A showMethod: 'fadeIn',%0A hideMethod: 'fadeOut'%0A %7D%0A %7D;%0A%0A if (en
f66744311eb49532b4c31c878dadb44ac6df3c3e
Revert "Implemeted concurrency to Promise.map function to limit the number of request that the server is able to fire at the same time"
server/helpers/utils.js
server/helpers/utils.js
var Promise = require("bluebird"); var Vimeo = require("../integrations/vimeo/request-vimeo"); var filter = require("../integrations/vimeo/filter-vimeo"); var RequestApi = require('../models/model.js'); exports.makeRequest = function(category, callback){ // Create the query to fetch the Vimeo API var queryObj = { path : '/categories/' + category + '/videos', query : { page : 1, per_page : 20 } } // Request the Vimeo API Vimeo.request(queryObj, function (error, body, status_code, headers) { if (error) { console.log('error', error); } else { callback(false, body); } console.log('status code', status_code); console.log('headers', headers); console.log('category', category); }); } exports.multipleRequests = function(categories, resultJSON, res){ // Promisify the request function ========================= // var makeRequestAsync = Promise.promisify(exports.makeRequest); // Multiple Promisify requests ============================ // Promise.map(categories, function(gallery) { return makeRequestAsync(gallery) .then(function(data){ var dataFiltered = filter(data); // increase the number of galleries (categories) resultJSON.total++; // set the new gallery into the header resultJSON.header.push({'name': gallery}); // set the content for this gallery (category) resultJSON.content[gallery] = dataFiltered; // return the data (this data is not been used) return dataFiltered; }) .catch(function(e){ console.log('error:', e); }); }, {concurrency: 1}).then(function(dataArray) { // res.status(200).json({results: resultJSON}); var dataString = JSON.stringify(resultJSON); // Create the new request model var newRequestApi = new RequestApi({ data: dataString, api: 'Vimeo' }); // Fetch the Database to check if there's any request stored RequestApi.findOne({}, function(err, result){ if (err) { console.log('Failed to fecth the database'); } else { // If the request doesn't exist if (result === null) { // Create the new request model var newRequestApi = new RequestApi({ data: dataString, api: 'Vimeo' }); // Save the new model into the DB newRequestApi.save(function(err, result){ if (err) { console.log('Failed to SAVE the request in the Database'); } else { console.log('Request successfuly SAVED in the Database '); } }); } // If the request exists, just update with the new data else { // Update the data result.data = dataString; // Save it result.save(function(err, result){ if (err) { console.log('Failed to UPDATE the request in the Database'); } else { console.log('Request successfuly UPDATED in the Database '); } }) } } }) }).catch(SyntaxError, function(e) { console.log("Invalid JSON in file " + e.fileName + ": " + e.message); }); // ========================================================== // } exports.createJSON = function(req, res, categories, target){ // The JSON Object to send to the client var resultJSON = { total: 0, settings: { contentWidth: 295, contentHeight: 166 }, header: [], content: {} }; // Invoke all the requests exports.multipleRequests(categories, resultJSON, res); }; exports.updateRequest = function(){ // setInterval(fun); }
JavaScript
0
@@ -148,24 +148,159 @@ er-vimeo%22);%0A +%3C%3C%3C%3C%3C%3C%3C HEAD%0A=======%0A// var mongoose = require('mongoose');%0A%3E%3E%3E%3E%3E%3E%3E Created a MongoDB Database to store the request from the Vimeo API%0A var RequestA @@ -769,32 +769,35 @@ %7D%0A%09 + // console.log('st @@ -822,24 +822,25 @@ _code);%0A +%09 consol @@ -823,33 +823,34 @@ code);%0A%09 - +// console.log('he @@ -871,52 +871,8 @@ s);%0A -%09 console.log('category', category);%0A @@ -1838,26 +1838,8 @@ ;%0A -%7D, %7Bconcurrency: 1 %7D).t
d765a43166275bfcafb22706dcbb66c04fa9eb35
Update supported locales
locales/index.js
locales/index.js
/** * Languages Loader */ const fs = require('fs'); const yaml = require('js-yaml'); const merge = (...args) => args.reduce((a, c) => ({ ...a, ...c, ...Object.entries(a) .filter(([k]) => c && typeof c[k] === 'object') .reduce((a, [k, v]) => (a[k] = merge(v, c[k]), a), {}) }), {}); const languages = [ /*'cs-CZ', 'da-DK', 'de-DE', 'en-US', 'es-ES', 'fr-FR',*/ 'ja-JP', /*'ja-KS', 'ko-KR', 'nl-NL', 'pl-PL', 'zh-CN', 'zh-TW',*/ ]; const primaries = { 'en': 'US', 'ja': 'JP', 'zh': 'CN', }; const locales = languages.reduce((a, c) => (a[c] = yaml.safeLoad(fs.readFileSync(`${__dirname}/${c}.yml`, 'utf-8')) || {}, a), {}); module.exports = Object.entries(locales) .reduce((a, [k ,v]) => (a[k] = (() => { const [lang] = k.split('-'); switch (k) { case 'ja-JP': return v; case 'ja-KS': case 'en-US': return merge(locales['ja-JP'], v); default: return merge( locales['ja-JP'], locales['en-US'], locales[`${lang}-${primaries[lang]}`] || {}, v ); } })(), a), {});
JavaScript
0
@@ -309,17 +309,17 @@ s = %5B%0A%09/ -* +/ 'cs-CZ', @@ -320,16 +320,18 @@ s-CZ',%0A%09 +// 'da-DK', @@ -332,16 +332,18 @@ a-DK',%0A%09 +// 'de-DE', @@ -368,16 +368,18 @@ ',%0A%09 +// 'fr-FR', */%0A%09 @@ -374,18 +374,16 @@ 'fr-FR', -*/ %0A%09'ja-JP @@ -387,17 +387,17 @@ -JP',%0A%09/ -* +/ 'ja-KS', @@ -408,16 +408,18 @@ o-KR',%0A%09 +// 'nl-NL', @@ -420,16 +420,18 @@ l-NL',%0A%09 +// 'pl-PL', @@ -428,24 +428,26 @@ //'pl-PL',%0A%09 +// 'zh-CN',%0A%09'z @@ -448,16 +448,18 @@ ',%0A%09 +// 'zh-TW', */%0A%5D @@ -454,18 +454,16 @@ 'zh-TW', -*/ %0A%5D;%0A%0Acon
f26c8b035b0dd61b2bb0215b25db8ca348841fb9
Update Log Fix
assets/js/vendor/github.commits.widget.js
assets/js/vendor/github.commits.widget.js
(function(e){function t(t,n,r){this.element=t;this.options=n;this.callback=e.isFunction(r)?r:e.noop}t.prototype=function(){function t(t,n,r,i){e.ajax({url:"https://api.github.com/repos/"+t+"/"+n+"/commits?sha="+r,dataType:"jsonp",success:i})}function n(n){if(!n.options){n.element.append('<span class="error">Options for widget are not set.</span>');return}var r=n.callback;var i=n.element;var s=n.options.user;var o=n.options.repo;var u=n.options.branch;var a=n.options.avatarSize||20;var f=n.options.last===undefined?0:n.options.last;var l=n.options.limitMessageTo===undefined?0:n.options.limitMessageTo;t(s,o,u,function(t){function g(t,n){return e("<img>").attr("class","github-avatar").attr("src","https://www.gravatar.com/avatar/"+t+"?s="+n)}function y(t){return e("<a>").attr("href","https://github.com/"+t).text(t)}function b(t,n){var r=t;if(l>0&&t.length>l){t=t.substr(0,l)+"..."}var i=e('<a class="github-commit"></a>').attr("title",r).attr("href","https://github.com/"+s+"/"+o+"/commit/"+n).text(t);return i}function w(e){var t=(new Date(e)).getTime();var n=(new Date).getTime();var r=Math.floor((n-t)/(24*3600*1e3));if(r===0){var i=Math.floor((n-t)/(3600*1e3));if(i===0){var s=Math.floor((n-t)/(600*1e3));if(s===0){return"just now"}return"about "+s+" minutes ago"}return"about "+i+" hours ago"}else if(r==1){return"yesterday"}return r+" days ago"}var n=t.data;var u=f<n.length?f:n.length;i.empty();var c=e('<ul class="github-commits-list">').appendTo(i);for(var h=0;h<u;h++){var p=n[h];var d=e("<li>");var v=e('<span class="github-user">');if(p.author!==null){v.append(g(p.author.gravatar_id,a));v.append(y(p.author.login))}else{v.append(p.commit.committer.name)}d.append(v);var m=e("<span class=github-commit-date>");d.append(b(p.commit.message,p.sha));d.append(m.text(w(p.commit.committer.date)));c.append(d)}r(i)})}return{run:function(){n(this)}}}();e.fn.githubInfoWidget=function(n,r){this.each(function(){(new t(e(this),n,r)).run()});return this}})(jQuery)
JavaScript
0.000001
@@ -628,17 +628,17 @@ unction -g +n (t,n)%7Bre @@ -749,17 +749,17 @@ unction -y +u (t)%7Bretu @@ -814,16 +814,29 @@ .text(t) +.prepend(%22 %22) %7Dfunctio @@ -837,17 +837,17 @@ unction -b +c (t,n)%7Bva @@ -1014,16 +1014,43 @@ .text(t) +.append(%22 %22).prepend(%22 - %22) ;return @@ -1060,17 +1060,17 @@ unction -w +h (e)%7Bvar @@ -1395,17 +1395,17 @@ go%22%7Dvar -n +p =t.data; @@ -1412,13 +1412,13 @@ var -u=f%3Cn +d=f%3Cp .len @@ -1423,17 +1423,17 @@ ength?f: -n +p .length; @@ -1446,17 +1446,17 @@ y();var -c +v =e('%3Cul @@ -1466,22 +1466,12 @@ ss=%22 -github-commits +post -lis @@ -1500,25 +1500,25 @@ var -h=0;h%3Cu;h +m=0;m%3Cd;m ++)%7Bvar p=n%5B @@ -1517,20 +1517,20 @@ var -p=n%5Bh +g=p%5Bm %5D;var -d +y =e(%22 @@ -1536,25 +1536,25 @@ %22%3Cli%3E%22);var -v +b =e('%3Cspan cl @@ -1577,17 +1577,17 @@ %22%3E');if( -p +g .author! @@ -1594,25 +1594,25 @@ ==null)%7B -v +b .append( g(p.auth @@ -1607,11 +1607,11 @@ end( -g(p +n(g .aut @@ -1630,25 +1630,25 @@ _id,a)); -v +b .append( y(p.auth @@ -1643,11 +1643,11 @@ end( -y(p +u(g .aut @@ -1667,17 +1667,17 @@ lse%7B -v +b .append( p.co @@ -1672,17 +1672,17 @@ .append( -p +g .commit. @@ -1697,25 +1697,25 @@ r.name)%7D -d +y .append( v);var m @@ -1710,16 +1710,16 @@ end( -v +b );var -m +w =e(%22 @@ -1752,21 +1752,39 @@ date + style=float:right %3E%22); -d +y .append( b(p. @@ -1783,11 +1783,11 @@ end( -b(p +c(g .com @@ -1802,25 +1802,25 @@ age, -p +g .sha)); -d +y .append( m.te @@ -1819,18 +1819,18 @@ end( -m +w .text( -w(p +h(g .com @@ -1855,17 +1855,17 @@ ))); -c +v .append( d)%7Dr @@ -1860,17 +1860,17 @@ .append( -d +y )%7Dr(i)%7D)
1eb48af8030867d23044313a011429fc8f80bbb0
Fix for Time widget
cherryforms/static/js/widgets/Time.js
cherryforms/static/js/widgets/Time.js
define(['underscore', 'backbone', 'core', 'utils', 'moment', 'widgets/Text', 'datepicker'], function(_, Backbone, CherryForms, Utils, moment) { "use strict"; var Widgets = CherryForms.Widgets, Widget = Widgets.Widget, Fields = CherryForms.Fields, Events = CherryForms.Events, Templates = CherryForms.Templates, Field = Fields.Field, TextField = Fields.Text, TextWidget = Widgets.Text, MILLISECOND = 1, SECOND = MILLISECOND * 1000, MINUTE = SECOND * 60, HOUR = MINUTE * 60, DAY = HOUR * 24, WEEK = DAY * 7, DATE_FORMAT = 'YYYY-MM-DD HH:mm'; Fields.Time = Field.extend({ processValue: function () { var value = this.get('value'), ms = Number(value), m; if (ms instanceof Number) { m = moment(ms); } else if (_.isString(value)) { m = moment(value, DATE_FORMAT); } else { m = moment(); } this.value = m.format(DATE_FORMAT); this.moment = m; this.trigger(Events.FIELD_CHANGE, this); return undefined; }, dumpValue: function () { return this.moment.valueOf(); }, toJSON: function () { var re = Field.prototype.toJSON.call(this); re['value'] = this.value; re['now'] = moment().format(DATE_FORMAT); return re; } }); Templates.Time = _.template( '<div class="control-group">' + '<label for="{{ input_id }}">{{ label }}</label>' + '<input type="text" id="{{ input_id }}" value="{{ value }}" class="{{ input_class }}">' + '<span class="help-block">Date format: ' + DATE_FORMAT + '</span>' + '</div>'); Widgets.Time = TextWidget.extend({ FieldModel: Fields.Time, template: Templates.Time, _onValidate: function () { Widget.prototype._onValidate.apply(this, arguments); this.getInput().val(this.model.value); } }); return CherryForms; });
JavaScript
0
@@ -848,28 +848,20 @@ if ( -ms instanceof Number +!_.isNaN(ms) ) %7B%0A
46431817d91808b5163fb6151a9cb621493f15d7
Use updated image for sdl_core
server/lib/constants.js
server/lib/constants.js
module.exports = { //constant string values used throughout manticore strings: { manticoreServiceName: "manticore-service", coreServicePrefix: "core-service-", hmiServicePrefix: "hmi-service-", coreHmiJobPrefix: "core-hmi-", coreGroupPrefix: "core-group-", hmiGroupPrefix: "hmi-group-", coreTaskPrefix: "core-task-", hmiTaskPrefix: "hmi-task-", hmiAliveHealth: "hmi-alive", manticoreAliveHealth: "manticore-alive", baseImageSdlCore: "crokita/discovery-core", baseImageGenericHmi: "smartdevicelink/manticore-generic-hmi", imageTagMaster: ":master", imageTagDevelop: ":develop", imageTagManticore: ":manticore", }, //keys in the KV store keys: { //locations of pieces of data meant for a certain purpose request: "manticore/requests", waiting: "manticore/waiting", allocation: "manticore/allocations", //data keys store actual data related to users data: { request: "manticore/requests/data", waiting: "manticore/waiting/data", allocation: "manticore/allocations/data", haproxy: "haproxy/data" }, //filler keys that are kept next to a list so that we receive change notifications if the list is empty fillers: { request: "manticore/requests/filler", waiting: "manticore/waiting/filler", allocation: "manticore/allocations/filler" }, //information specific to the construction of the config file haproxy: { //port that reverse proxy opens to access manticore web app mainPort: "haproxy/mainPort", domainName: "haproxy/domainName", webApp: "haproxy/webAppAddresses", tcpMaps: "haproxy/data/tcpMaps", httpFront: "haproxy/data/httpFront", httpBack: "haproxy/data/httpBack" } } }
JavaScript
0
@@ -455,25 +455,37 @@ e: %22 -crokita/discovery +smartdevicelink/manticore-sdl -cor
3ea271b3cc4f82c3c435f4bd1bfd67b697614695
Update Gruntfile.js
app/templates/skeleton/Gruntfile.js
app/templates/skeleton/Gruntfile.js
/*jslint node: true */ 'use strict'; var pkg = require('./package.json'); //Using exclusion patterns slows down Grunt significantly //instead of creating a set of patterns like '**/*.js' and '!**/node_modules/**' //this method is used to create a set of inclusive patterns for all subdirectories //skipping node_modules, bower_components, dist, and any .dirs //This enables users to create any directory structure they desire. var createFolderGlobs = function(fileTypePatterns) { fileTypePatterns = Array.isArray(fileTypePatterns) ? fileTypePatterns : [fileTypePatterns]; var ignore = ['node_modules','bower_components','dist','temp','test','data','assets']; var fs = require('fs'); return fs.readdirSync(process.cwd()) .map(function(file){ if (ignore.indexOf(file) !== -1 || file.indexOf('.') === 0 || !fs.lstatSync(file).isDirectory()) { return null; } else { return fileTypePatterns.map(function(pattern) { return file + '/**/' + pattern; }); } }) .filter(function(patterns){ return patterns; }) .concat(fileTypePatterns); }; module.exports = function (grunt) { // load all grunt tasks require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ connect: { main: { options: { port: 9000, open: { target: 'http://localhost:9000/app', appName: 'Chrome' } } } }, watch: { main: { options: { livereload: true, livereloadOnError: false, spawn: false }, files: [createFolderGlobs(['*.js','*.less','*.html']),'!_SpecRunner.html','!.grunt'], tasks: [] //all the tasks are run dynamically during the watch event handler } }, jshint: { main: { options: { jshintrc: '.jshintrc' }, src: createFolderGlobs('*.js') } }, clean: { before:{ src:['dist','temp'] }, after: { src:['temp'] } }, less: { production: { options: { }, files: { 'temp/app.css': 'app/app.less' } } }, ngtemplates: { main: { options: { module: pkg.name, htmlmin:'<%%= htmlmin.main.options %>', url: function(url) { return url.replace('app/', ''); } }, src: [createFolderGlobs('*.html'),'!app/index.html','!_SpecRunner.html'], dest: 'temp/templates.js' } }, copy: { main: { files: [ {cwd: 'app', src: ['assets/**/*'], dest: 'dist/', expand: true} /*{src: ['bower_components/font-awesome/fonts/**'], dest: 'dist/',filter:'isFile',expand:true}, {src: ['bower_components/bootstrap/fonts/**'], dest: 'dist/',filter:'isFile',expand:true}*/ ] } }, dom_munger:{ read: { options: { read:[ {selector:'script[data-concat!="false"]',attribute:'src',writeto:'appjs',isPath:true}, {selector:'link[rel="stylesheet"][data-concat!="false"]',attribute:'href',writeto:'appcss'} ] }, src: 'app/index.html' }, update: { options: { remove: ['script[data-remove!="false"]','link[data-remove!="false"]'], append: [ {selector:'body',html:'<script src="app.full.min.js"></script>'}, {selector:'head',html:'<link rel="stylesheet" href="app.full.min.css">'} ] }, src:'app/index.html', dest: 'dist/index.html' } }, cssmin: { main: { src:['temp/app.css','<%%= dom_munger.data.appcss %>'], dest:'dist/app.full.min.css' } }, concat: { main: { src: ['<%%= dom_munger.data.appjs %>','<%%= ngtemplates.main.dest %>'], dest: 'temp/app.full.js' } }, ngAnnotate: { main: { src:'temp/app.full.js', dest: 'temp/app.full.js' } }, uglify: { main: { src: 'temp/app.full.js', dest:'dist/app.full.min.js' } }, htmlmin: { main: { options: { collapseBooleanAttributes: true, collapseWhitespace: true, removeAttributeQuotes: true, removeComments: true, removeEmptyAttributes: true, removeScriptTypeAttributes: true, removeStyleLinkTypeAttributes: true }, files: { 'dist/index.html': 'dist/index.html' } } }, //Imagemin has issues on Windows. //To enable imagemin: // - "npm install grunt-contrib-imagemin" // - Comment in this section // - Add the "imagemin" task after the "htmlmin" task in the build task alias //imagemin: { // main:{ // files: [{ // expand: true, cwd:'dist/', // src:['**/{*.png,*.jpg}'], // dest: 'dist/' // }] // } //}, /** * The Karma configurations. */ karma: { unit: { configFile: 'test/karma.conf.js', background: true }, continuous: { configFile: 'test/karma.conf.js', singleRun: true } }, /** * Protractor configuration */ protractor: { e2e: { options: { configFile: "test/protractor.conf.js", // Target-specific config file args: { // Arguments passed to the command } } } } }); grunt.registerTask('build', ['jshint', 'clean:before', 'less', 'dom_munger', 'ngtemplates', 'cssmin', 'concat', 'ngAnnotate', 'uglify', 'copy', 'htmlmin', 'clean:after']); grunt.registerTask('run', ['dom_munger:read', 'jshint', 'connect', 'watch']); grunt.registerTask('test', ['dom_munger:read', 'karma']); grunt.registerTask('e2e', ['dom_munger:read', 'protractor']); grunt.event.on('watch', function(action, filepath) { //https://github.com/gruntjs/grunt-contrib-watch/issues/156 var tasksToRun = []; if (filepath.lastIndexOf('.js') !== -1 && filepath.lastIndexOf('.js') === filepath.length - 3) { //lint the changed js file grunt.config('jshint.main.src', filepath); tasksToRun.push('jshint'); //find the appropriate unit test for the changed file var spec = filepath; if (filepath.lastIndexOf('-spec.js') === -1 || filepath.lastIndexOf('-spec.js') !== filepath.length - 8) { spec = filepath.substring(0,filepath.length - 3) + '-spec.js'; } //if the spec exists then lets run it if (grunt.file.exists(spec)) { var files = [].concat(grunt.config('dom_munger.data.appjs')); files.push('bower_components/angular-mocks/angular-mocks.js'); files.push(spec); grunt.config('karma.options.files', files); tasksToRun.push('karma:during_watch'); } } //if index.html changed, we need to reread the <script> tags so our next run of karma //will have the correct environment if (filepath === 'app/index.html') { tasksToRun.push('dom_munger:read'); } grunt.config('watch.main.tasks',tasksToRun); }); };
JavaScript
0
@@ -3274,16 +3274,28 @@ 'appcss' +,isPath:true %7D%0A
e86686aeaa0cc79ba45e844313c1a3a64e325b51
Fix skipped first tag
chrome/content/zotero/longTagFixer.js
chrome/content/zotero/longTagFixer.js
var Zotero_Long_Tag_Fixer = new function () { var _oldTag = window.arguments[0]; var _dataOut = window.arguments[1]; this.init = function () { document.getElementById('zotero-old-tag').value = _oldTag; var lastMode = Zotero.Prefs.get('lastLongTagMode'); if (!lastMode) { lastMode = 0; } this.switchMode(lastMode); } this.switchMode = function (index) { var dialog = document.getElementById('zotero-long-tag-fixer'); document.getElementById('zotero-new-tag-actions').selectedIndex = index; // TODO: localize switch (index) { case 0: var buttonLabel = "Save Tags"; this.updateTagList(); break; case 1: var buttonLabel = "Save Tag"; document.getElementById('zotero-new-tag-editor').value = _oldTag; this.updateEditLength(_oldTag.length) break; case 2: var buttonLabel = "Delete Tag"; dialog.getButton('accept').disabled = false; break; } document.getElementById('zotero-long-tag-fixer').getButton('accept').label = buttonLabel; window.sizeToContent(); Zotero.Prefs.set('lastLongTagMode', index); } /** * Split tags and populate list */ this.updateTagList = function () { var listbox = document.getElementById('zotero-new-tag-list'); while (listbox.childNodes.length) { listbox.removeChild(listbox.lastChild); } var delimiter = document.getElementById('zotero-old-tag-delimiter').value; if (delimiter) { var re = new RegExp("\\s*" + delimiter + "\\s*"); var tags = _oldTag.split(re); } var acceptButton = document.getElementById('zotero-long-tag-fixer').getButton('accept'); if (!delimiter || tags.length < 2) { acceptButton.disabled = true; return; } else { acceptButton.disabled = false; } tags.sort(); for (var i=0; i<tags.length; i++) { if (i==0 || tags[i] == tags[i-1]) { continue; } var li = listbox.appendItem(tags[i]); li.setAttribute('type', 'checkbox'); li.setAttribute('checked', 'true'); } } this.deselectAll = function () { var lis = document.getElementById('zotero-new-tag-list').getElementsByTagName('listitem'); for (var i=0; i<lis.length; i++) { lis[i].checked = false; } } this.selectAll = function () { var lis = document.getElementById('zotero-new-tag-list').getElementsByTagName('listitem'); for (var i=0; i<lis.length; i++) { lis[i].checked = true; } } this.updateEditLength = function (len) { document.getElementById('zotero-new-tag-character-count').value = len; var invalid = len == 0 || len > 255; document.getElementById('zotero-new-tag-characters').setAttribute('invalid', invalid); document.getElementById('zotero-long-tag-fixer').getButton('accept').disabled = invalid; } this.cancel = function () { _dataOut.result = false; } this.save = function () { try { var index = document.getElementById('zotero-new-tag-actions').selectedIndex; // Search for all matching tags across all libraries var sql = "SELECT tagID FROM tags WHERE name=?"; var oldTagIDs = Zotero.DB.columnQuery(sql, _oldTag); switch (index) { // Split case 0: // Get checked tags var listbox = document.getElementById('zotero-new-tag-list'); var len = Zotero.isFx3 ? listbox.childNodes.length : listbox.childElementCount; var newTags = []; for (var i=0; i<len; i++) { var li = listbox.childNodes[i]; if (li.getAttribute('checked') == 'true') { newTags.push(li.getAttribute('label')); } } Zotero.DB.beginTransaction(); // Add new tags to all items linked to each matching old tag for (var i=0; i<oldTagIDs.length; i++) { var tag = Zotero.Tags.get(oldTagIDs[i]); var items = tag.getLinkedItems(); if (items) { for (var j=0; j<items.length; j++) { items[j].addTags(newTags, tag.type); } } } // Remove old tags Zotero.Tags.erase(oldTagIDs); Zotero.Tags.purge(); Zotero.DB.commitTransaction(); break; // Edit case 1: var value = document.getElementById('zotero-new-tag-editor').value; Zotero.DB.beginTransaction(); for (var i=0; i<oldTagIDs.length; i++) { var tag = Zotero.Tags.get(oldTagIDs[i]); tag.name = value; tag.save(); } Zotero.DB.commitTransaction(); break; // Delete case 2: Zotero.DB.beginTransaction(); Zotero.Tags.erase(oldTagIDs); Zotero.Tags.purge(); Zotero.DB.commitTransaction(); break; } _dataOut.result = true; } catch (e) { Zotero.debug(e); throw (e); } } }
JavaScript
0.000001
@@ -1815,14 +1815,16 @@ f (i -==0 %7C%7C + != 0 && tag @@ -1863,16 +1863,54 @@ e;%0A%09%09%09%7D%0A +%09%09%09if (!tags%5Bi%5D) %7B%0A%09%09%09%09continue;%0A%09%09%09%7D%0A %09%09%09var l
ebedd359007f705ce15b99f2bdc4adeb56fac635
Interpolate url variable
server/methods/users.js
server/methods/users.js
Meteor.methods({ addUser (user) { // Add new user var userId = Accounts.createUser(user); return userId; }, addUsersAndSendEnrollmentEmails (enrollmentDocument) { // original example: https://stackoverflow.com/a/16098693/1191545 // Make sure mail configuration is present if (!process.env.MAIL_URL) { throw new Meteor.Error('MailConfigurationError', 'No mail settings available.') } // Set enrollment subject from document Accounts.emailTemplates.enrollAccount.subject = (user) => { return enrollmentDocument.subject; } // Set enrollment message from document Accounts.emailTemplates.enrollAccount.text = (user, url) => { return `${ enrollmentDocument.message } \n\n url`; } // Get emails from enrollment document const emailAddresses = enrollmentDocument.emailAddresses; // Create user and send enrollment email for each email address emailAddresses.forEach((emailAddress) => { // Create a user with current email address const userId = Accounts.createUser({ email: emailAddress }); // Send enrollment email to newly created user Accounts.sendEnrollmentEmail(userId); }); }, addUserToAdminRole (userId) { // Add user to admin role Roles.addUsersToRoles(userId, "admin"); }, deleteUser (user) { console.log(user); // Make sure user object provided with '_id' property check(user, Object); check(user._id, String); // Get current user id, for security check const currentUserId = this.userId; // Make sure current user has 'admin' role if (Roles.userIsInRole(currentUserId, 'admin')) { // Make sure user can't delete own Account if (currentUserId !== user._id) { // If safe, delete provided user Object Meteor.users.remove(user); } } }, editUserFormSubmit (user) { // Get user email var userEmail = user.email; var userId = user._id; // Edit user, setting first email Meteor.users.update(userId, {$set: {"emails.0.address": userEmail}}); return userId; }, removeUserFromAdminRole (userId) { // Add user to admin role Roles.removeUsersFromRoles(userId, "admin"); } });
JavaScript
0.000029
@@ -735,20 +735,26 @@ e %7D %5Cn%5Cn + $ %7B url + %7D %60;%0A %7D
5e6837699a4c19401defe442b06b80a2199efc9d
improve transfer list totals display
app/transferlist/transfer-totals.js
app/transferlist/transfer-totals.js
/* globals window $ document */ import { BaseScript, SettingsEntry } from '../core'; import './style/transfer-totals.scss'; export class TransferTotalsSettings extends SettingsEntry { static id = 'transfer-totals'; constructor() { super('transfer-totals', 'Transfer list totals', null); this.addSetting('Show transfer list totals', 'show-transfer-totals', true, 'checkbox'); } } class TransferTotals extends BaseScript { constructor() { super(TransferTotalsSettings.id); const MutationObserver = window.MutationObserver || window.WebKitMutationObserver; this._observer = new MutationObserver(this._mutationHandler.bind(this)); } activate(state) { super.activate(state); const obsConfig = { childList: true, characterData: true, attributes: false, subtree: true, }; setTimeout(() => { this._observer.observe($(document)[0], obsConfig); }, 0); } deactivate(state) { super.deactivate(state); this._observer.disconnect(); } _mutationHandler(mutationRecords) { const settings = this.getSettings(); mutationRecords.forEach((mutation) => { if ( $(mutation.target).find('.listFUTItem').length > 0 || $(mutation.target).find('.futbin').length > 0 ) { const controller = getAppMain() .getRootViewController() .getPresentedViewController() .getCurrentViewController() .getCurrentController(); if (!controller || !controller._listController) { return; } if (window.currentPage !== 'UTTransferListSplitViewController') { return; } if (!settings.isActive || settings['show-transfer-totals'].toString() !== 'true') { return; } const lists = $('.ut-transfer-list-view .itemList'); const items = controller._listController._viewmodel._collection; const listRows = $('.ut-transfer-list-view .listFUTItem'); lists.each((index, list) => { const totals = { futbin: 0, bid: 0, bin: 0, }; const listEl = $(list); if (!listEl.find('.listFUTItem').length) { return; } const firstIndex = $(list).find('.listFUTItem:first').index('.ut-transfer-list-view .listFUTItem'); const lastIndex = $(list).find('.listFUTItem:last').index('.ut-transfer-list-view .listFUTItem'); totals.futbin = items.slice(firstIndex, lastIndex + 1).reduce((sum, item, i) => { const futbin = parseInt( listRows.eq(i + firstIndex) .find('.auctionValue.futbin .coins.value') .text() .replace(/[,.]/g, ''), 10, ) || 0; return sum + futbin; }, 0); totals.bid = items.slice(firstIndex, lastIndex + 1) .reduce((sum, item) => { const { currentBid, startingBid } = item._auction; const actualBid = currentBid > 0 ? currentBid : startingBid; return sum + actualBid; }, 0); totals.bin = items.slice(firstIndex, lastIndex + 1) .reduce((sum, item) => sum + item._auction.buyNowPrice, 0); const totalsItem = listEl.prev('.transfer-totals'); if (!totalsItem.length) { $(`<div class="transfer-totals"> <div class="auction"> <div class="auctionValue futbin"> <span class="label">Futbin BIN</span> <span class="coins value total-futbin">0</span> </div> <div class="auctionStartPrice auctionValue">&nbsp;</div> <div class="auctionValue"> <span class="label">Bid Total</span> <span class="coins value total-bid">0</span> </div> <div class="auctionValue"> <span class="label">BIN Total</span> <span class="coins value total-bin">0</span> </div> </div> </div>`).insertBefore(listEl); } if (totals.futbin > 0) { totalsItem.find('.total-futbin').text(totals.futbin); totalsItem.find('.futbin').show(); } else { totalsItem.find('.futbin').hide(); } totalsItem.find('.total-bin').text(totals.bin); totalsItem.find('.total-bid').text(totals.bid); }); } }); } } new TransferTotals(); // eslint-disable-line no-new
JavaScript
0.000003
@@ -3643,79 +3643,8 @@ iv%3E%0A - %3Cdiv class=%22auctionStartPrice auctionValue%22%3E&nbsp;%3C/div%3E%0A
0d07368923e5f9132f852c24f9db4721aceed796
remove newline from the beginning of the template
template.js
template.js
'use static' module.exports = (name, path) => ` <template> <span class="mdi mdi-${name}"> <svg :width="width" :height="height" :viewBox="viewBox" :xmlns="xmlns" > <title>MDI ${name}</title> <path d="${path}" /> </svg> </span> </template> <script> export default { name: 'mdi-${name}', props: { width: { type: [Number, String], default: 24 }, height: { type: [Number, String], default: 24 }, viewBox: { type: [String], default: '0 0 24 24' }, xmlns: { type: String, default: 'xmlns="http://www.w3.org/2000/svg"' } } } </script> `
JavaScript
0
@@ -41,17 +41,16 @@ th) =%3E %60 -%0A %3Ctemplat
4b038cdfbf67388ef216e28817c178e9abb385f2
add additional log
example/gen-docs.js
example/gen-docs.js
#!/usr/bin/env node var vm = require('vm'); var fs = require('fs'); var _ = require('lodash'); var log = require('winston'); var rimraf = require('rimraf'); log.cli(); var myArgs = require('optimist') .usage('Usage: $0 path/to/config') .demand(1) .argv; // Load in the factories var fileReaderFactory = require('../lib/doc-extractor'); var docProcessorFactory = require('../lib/doc-processor'); var docRendererFactory = require('../lib/doc-renderer'); // Default configuration var config = { source: { files: [], extractors: require('../lib/doc-extractor/doc-extractors') }, processing: { plugins: require('../lib/doc-processor/plugins'), tagDefinitions: require('../lib/doc-processor/tag-defs') }, rendering: { templatePath: '', filters: require('../lib/doc-renderer/custom-filters'), tags: require('../lib/doc-renderer/custom-tags'), extra: {}, outputPath: '' }, logging: { level: 'warning', colorize: true } }; // Load in the config file and run it over the top of the default config var configFile = fs.readFileSync(myArgs._[0]); vm.runInNewContext(configFile, config, myArgs._[0]); log.cli(); log.remove(log.transports.Console); log.add(log.transports.Console, config.logging); log.info('Read config from "' + myArgs._[0] + '"'); // Create the processing functions from the factories and the configuration var readFiles = fileReaderFactory(config.source.extractors); var processDocs = docProcessorFactory(config.processing.plugins, config.processing.tagDefinitions); var renderDocs = docRendererFactory(config.rendering.templatePath, config.rendering.outputPath, config.rendering.filters, config.rendering.tags); // Delete the previous output folder rimraf.sync(config.rendering.outputPath); log.info('Removed previous output files from "' + config.rendering.outputPath + '"'); // Run the processing functions readFiles(config.source.files) .then(function(docs) { log.info('Read', docs.length, 'docs'); docs = processDocs(docs); return renderDocs(docs, config.rendering.extra); }) .done();
JavaScript
0.000003
@@ -2018,16 +2018,64 @@ (docs);%0A + log.info('Rendering', docs.length, 'docs');%0A retu
02a7a9d45af130d07ebba32af651fe980d5f0951
Update CLI test to reliably stop
test/cli.js
test/cli.js
'use strict'; import Fabric from '../'; const assert = require('assert'); const expect = require('chai').expect; describe('CLI', function () { it('should expose a constructor', function () { assert.equal(typeof Fabric.CLI, 'function'); }); it('should create an CLI smoothly', async function () { let cli = new Fabric.CLI(); try { await cli.start(); await cli.stop(); assert.ok(cli); } catch (E) { console.error(E); } }); });
JavaScript
0
@@ -431,24 +431,48 @@ catch (E) %7B%0A + await cli.stop();%0A consol
abd33586af0006e8492bbcdb1eb27a306359b03c
test coverage for the non-object case
test/cmp.js
test/cmp.js
var test = require('tape'); var equal = require('../'); test('equal', function (t) { t.ok(equal( { a : [ 2, 3 ], b : [ 4 ] }, { a : [ 2, 3 ], b : [ 4 ] } )); t.end(); }); test('not equal', function (t) { t.notOk(equal( { x : 5, y : [6] }, { x : 5, y : 6 } )); t.end(); }); test('nested nulls', function (t) { t.ok(equal([ null, null, null ], [ null, null, null ])); t.end(); }); test('strict equal', function (t) { t.notOk(equal( [ { a: 3 }, { b: 4 } ], [ { a: '3' }, { b: '4' } ], { strict: true } )); t.end(); }); test('arguments class', function (t) { t.ok(equal( (function(){return arguments})(1,2,3), (function(){return arguments})(1,2,3), "compares arguments" )); t.notOk(equal( (function(){return arguments})(1,2,3), [1,2,3], "differenciates array and arguments" )); t.end(); }); test('dates', function (t) { var d0 = new Date(1387585278000); var d1 = new Date('Fri Dec 20 2013 16:21:18 GMT-0800 (PST)'); t.ok(equal(d0, d1)); t.end(); });
JavaScript
0.000003
@@ -610,24 +610,234 @@ end();%0A%7D);%0A%0A +test('non-objects', function (t) %7B%0A t.ok(equal(3, 3));%0A t.ok(equal('beep', 'beep'));%0A t.ok(equal('3', 3));%0A t.notOk(equal('3', 3, %7B strict: true %7D));%0A t.notOk(equal('3', %5B3%5D));%0A t.end();%0A%7D);%0A%0A test('argume
dd17b0f6517c90dba84407c5e01926911a49304d
Add tests for rbind method
test/lfr.js
test/lfr.js
'use strict'; var assert = require('assert'); var sinon = require('sinon'); require('./fixture/sandbox.js'); describe('lfr', function() { describe('Abstract Method', function() { it('should throw errors for calling abstract methods', function() { assert.throws(function() { lfr.abstractMethod(); }, Error); }); }); describe('Bind', function() { it('should throw errors when binding with no function', function() { var TestClass = function() {}; TestClass.prototype.method = function() { this.innerVar = 1; }; var obj = new TestClass(); lfr.bind(obj.method, obj)(); assert.strictEqual(1, obj.innerVar); }); it('should work without Function.prototype.bind', function() { var bind = Function.prototype.bind; Function.prototype.bind = null; var TestClass = function() {}; TestClass.prototype.method = function() { this.innerVar = 1; }; var obj = new TestClass(); lfr.bind(obj.method, obj)(); assert.strictEqual(1, obj.innerVar); Function.prototype.bind = bind; }); it('should pass args without Function.prototype.bind', function() { var bind = Function.prototype.bind; Function.prototype.bind = null; var TestClass = function() {}; TestClass.prototype.method = function(arg1, arg2) { this.innerVar = 1; this.arg1 = arg1; this.arg2 = arg2; }; var obj = new TestClass(); lfr.bind(obj.method, obj, 2)(3); assert.strictEqual(1, obj.innerVar); assert.strictEqual(2, obj.arg1); assert.strictEqual(3, obj.arg2); Function.prototype.bind = bind; }); it('should throw errors when binding with no function', function() { assert.throws(function() { lfr.bind(); }, Error); }); }); describe('Inheritance', function() { it('should copy superclass prototype to subclass', function() { var TestSuperClass = function() {}; TestSuperClass.prototype.var1 = 1; TestSuperClass.prototype.func = function() {}; var TestClass = function() {}; lfr.inherits(TestClass, TestSuperClass); TestClass.prototype.var2 = 2; TestClass.prototype.func2 = function() {}; var obj = new TestClass(); assert.strictEqual(1, obj.var1); assert.strictEqual(2, obj.var2); assert.strictEqual(TestSuperClass.prototype.func, obj.func); assert.strictEqual(TestClass.prototype.func2, obj.func2); }); it('should override properties of the superclass', function() { var TestSuperClass = function() {}; TestSuperClass.prototype.var1 = 1; TestSuperClass.prototype.func = function() {}; var TestClass = function() {}; lfr.inherits(TestClass, TestSuperClass); TestClass.prototype.var1 = 2; TestClass.prototype.func = function() {}; var obj = new TestClass(); assert.strictEqual(2, obj.var1); assert.notStrictEqual(TestSuperClass.prototype.func, obj.func); }); it('should allow calling superclass functions', function() { var TestSuperClass = function() {}; TestSuperClass.prototype.func = sinon.stub(); var TestClass = function() {}; lfr.inherits(TestClass, TestSuperClass); TestClass.prototype.func = function() { TestClass.base(this, 'func'); }; var obj = new TestClass(); obj.func(); assert.strictEqual(1, TestSuperClass.prototype.func.callCount); }); it('should allow calling superclass constructor', function() { var called = false; var TestSuperClass = function() { called = true; }; var TestClass = function() { TestClass.base(this, 'constructor'); }; lfr.inherits(TestClass, TestSuperClass); new TestClass(); assert.ok(called); }); }); describe('Identity Function', function() { it('should return the first arg passed to identity function', function() { assert.strictEqual(1, lfr.identityFunction(1)); var obj = { a: 2 }; assert.strictEqual(obj, lfr.identityFunction(obj)); }); }); describe('Type Check', function() { it('should check if var is defined', function() { assert.ok(!lfr.isDef(undefined)); assert.ok(lfr.isDef(1)); assert.ok(lfr.isDef('')); assert.ok(lfr.isDef({})); assert.ok(lfr.isDef([])); assert.ok(lfr.isDef(function() {})); assert.ok(lfr.isDef(null)); }); it('should check if var is function', function() { assert.ok(!lfr.isFunction(1)); assert.ok(!lfr.isFunction('')); assert.ok(!lfr.isFunction({})); assert.ok(!lfr.isFunction([])); assert.ok(!lfr.isFunction(null)); assert.ok(!lfr.isFunction(undefined)); assert.ok(lfr.isFunction(function() {})); }); it('should check if var is string', function() { assert.ok(!lfr.isString(1)); assert.ok(!lfr.isString({})); assert.ok(!lfr.isString([])); assert.ok(!lfr.isString(function() {})); assert.ok(!lfr.isString(null)); assert.ok(!lfr.isString(undefined)); assert.ok(lfr.isString('')); }); }); describe('Null Function', function() { it('should not return anything', function() { assert.strictEqual(undefined, lfr.nullFunction()); }); }); });
JavaScript
0
@@ -5373,13 +5373,854 @@ );%0A %7D); +%0A%0A describe('RBind', function() %7B%0A it('should add additionally supplied parameters to the end of the arguments the function is executed with', function() %7B%0A var TestClass = function() %7B%7D;%0A TestClass.prototype.method = function(param1, param2) %7B%0A this.innerVar = 1;%0A%0A assert.strictEqual(param1, 'param1');%0A assert.strictEqual(param2, 'param2');%0A %7D;%0A%0A TestClass.prototype.method2 = function() %7B%0A assert.strictEqual(1, arguments.length);%0A %7D;%0A%0A var obj = new TestClass();%0A lfr.rbind(obj.method, obj, 'param2')('param1');%0A%0A assert.strictEqual(1, obj.innerVar);%0A%0A lfr.rbind(obj.method2, obj)('param1');%0A %7D);%0A%0A it('should throw errors when rbinding with no function', function() %7B%0A assert.throws(function() %7B%0A lfr.rbind();%0A %7D, Error);%0A %7D);%0A %7D); %0A%7D);%0A
d0601f6a6070fabd53074fcec6160cd5999dc0a9
Tidy `t/coverage/checksum-constructor.t.js`.
t/coverage/checksum-constructor.t.js
t/coverage/checksum-constructor.t.js
#!/usr/bin/env node require('./proof')(1, function (step, Strata, tmp, load, objectify, assert, say) { var fs = require('fs'), crypto = require('crypto'), strata step(function () { fs.writeFile(tmp + '/.ignore', '', 'utf8', step()) }, function () { strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3 }) strata.create(step()) }, function () { strata.close(step()) }, function () { strata = new Strata({ directory: tmp, leafSize: 3, branchSize: 3, checksum: function () { return crypto.createHash('sha1') } }) strata.open(step()) }, function () { strata.iterator('a', step()) }, function (cursor) { assert(cursor.length - cursor.offset, 0, 'empty') cursor.unlock() strata.close(step()) }) })
JavaScript
0
@@ -68,37 +68,15 @@ tmp, - load, objectify, assert -, say ) %7B%0A
2454e58da2dcc9644b66f712a0630c9c23fd1062
update kwizmeestert
kwizmeestert/src/components/PickCategories.js
kwizmeestert/src/components/PickCategories.js
import React, {Component, PropTypes} from 'react'; import ListItem from "./ListItem"; class PickCategories extends Component { componentDidMount() { this.props.fetchCategories(); } render() { const categories = this.props.categories.map((category) => ( <ListItem key={category.categoryName} checked={category.approved ? 'checked' : ''} name={category.categoryName} onClickHandler={this.props.onToggleCategory.bind(this, category)} />) ); return ( <div> <h1>Selecteer drie categorieën</h1> {categories} <button onClick={this.props.onStartRound}>Start ronde</button> </div> ) } } PickCategories.propTypes = { fetchCategories: PropTypes.func.isRequired, categories: PropTypes.array.isRequired, onToggleCategory: PropTypes.func.isRequired, onStartRound: PropTypes.func.isRequired }; export default PickCategories;
JavaScript
0
@@ -193,16 +193,228 @@ %0A %7D%0A%0A + hasSelectedCategory() %7B%0A const selectedCategories = this.props.categories.filter((category) =%3E %7B%0A return category.approved;%0A %7D);%0A%0A return selectedCategories.length %3E 0;%0A %7D%0A%0A rend @@ -887,16 +887,91 @@ gories%7D%0A + %7B%0A this.hasSelectedCategory() ?%0A @@ -1040,16 +1040,63 @@ /button%3E + :%0A ''%0A %7D %0A
8c58824efbc7de57908e7e84aa078cef0b82ba12
fix tests for previous app-tree tidy
usage/jsgui/src/test/javascript/specs/model/app-tree-spec.js
usage/jsgui/src/test/javascript/specs/model/app-tree-spec.js
define([ "model/app-tree" ], function (AppTree) { var apps = new AppTree.Collection apps.url = "fixtures/application-tree.json" apps.fetch({async:false}) describe("model/app-tree", function () { it("loads fixture data", function () { expect(apps.length).toBe(2) var app1 = apps.at(0) expect(app1.get("name")).toBe("test") expect(app1.get("id")).toBe("riBZUjMq") expect(app1.get("type")).toBe(null) expect(app1.get("children").length).toBe(1) expect(app1.get("children")[0].name).toBe("tomcat1") expect(app1.get("children")[0].type).toBe("brooklyn.entity.webapp.tomcat.TomcatServer") expect(apps.at(1).get("children").length).toBe(2) }) it("has working getDisplayName", function () { var app1 = apps.at(0) expect(app1.getDisplayName()).toBe("test:riBZUjMq") }) it("has working hasChildren method", function () { expect(apps.at(0).hasChildren()).toBeTruthy() }) it("returns AppTree.Collection for getChildren", function () { var app1 = apps.at(0), children = new AppTree.Collection(app1.get("children")) expect(children.length).toBe(1) expect(children.at(0).getDisplayName()).toBe("tomcat1:fXyyQ7Ap") }) }) })
JavaScript
0
@@ -922,17 +922,8 @@ test -:riBZUjMq %22)%0A @@ -1353,17 +1353,8 @@ cat1 -:fXyyQ7Ap %22)%0A
158adfb6fd180b2e526b6f85535ab08f8fae0405
disable loose for example builds
packages/picimo-demo-shell/webpack.config.js
packages/picimo-demo-shell/webpack.config.js
/* eslint-disable no-console */ /* eslint-disable @typescript-eslint/no-var-requires */ /* eslint-env node */ const path = require('path'); const colors = require('colors'); const emoji = require('node-emoji'); const isProd = process.env.NODE_ENV === 'production'; const root = process.env.PICIMO_PROJECT_DIR || process.cwd(); if (isProd) { console.log(emoji.get('package'), 'production build'); } else { console.log(emoji.get('construction'), 'development mode activated'); } console.log(emoji.get('circus_tent'), 'project dir', colors.green(root)); module.exports = { entry: path.join(root, 'src/index.js'), output: { path: path.resolve(root, 'public'), filename: 'bundle.js', }, mode: isProd ? 'production' : 'development', devtool: isProd ? false : 'eval', devServer: { port: 3000, contentBase: [path.join(root, 'public')], watchContentBase: true, compress: true, host: '0.0.0.0', useLocalIp: true, disableHostCheck: true, }, stats: 'minimal', module: { rules: [ { test: /\.(png|jpg|gif|svg)$/, loader: 'file-loader', options: { name: '[path][name].[hash].[ext]', publicPath: '/', }, }, { test: /\.css$/, use: [ 'style-loader', // creates style nodes from JS strings 'css-loader', // translates CSS into CommonJS ], }, { test: /\.scss$/, use: [ 'style-loader', // creates style nodes from JS strings 'css-loader', // translates CSS into CommonJS 'sass-loader', // compiles Sass to CSS ], }, { test: /\.[jt]sx?$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { rootMode: 'upward', cacheDirectory: true, presets: [ [ '@babel/preset-env', { debug: false, useBuiltIns: 'usage', corejs: {version: 3, proposals: true}, bugfixes: true, loose: true, }, ], ], }, }, }, { test: /\.js$/, use: ['source-map-loader'], enforce: 'pre', }, ], }, resolve: { extensions: ['.ts', '.js', '.tsx', '.jsx', '.json'], alias: { picimo: path.join(__dirname, '../picimo/src'), 'datgui-context-hook': path.join(__dirname, '../datgui-context-hook/src'), }, }, };
JavaScript
0
@@ -2124,27 +2124,28 @@ loose: -tru +fals e,%0A
aa3d06f605b20d2744e186e24f6371d5f2604d50
Fix react-native-web StyleSheet pre-rendering
packages/plugin-bundler-webpack/src/index.js
packages/plugin-bundler-webpack/src/index.js
import path from "path"; // import url from "url" // import pkg from "@phenomic/core/package.json" import findCacheDir from "find-cache-dir"; // import webpack, { BannerPlugin, optimize, DefinePlugin } from "webpack" import webpack, { BannerPlugin, optimize } from "webpack"; import webpackDevMiddleware from "webpack-dev-middleware"; import webpackHotMiddleware from "webpack-hot-middleware"; import webpackPromise from "./webpack-promise.js"; import validate from "./validate.js"; const debug = require("debug")("phenomic:plugin:webpack"); const { UglifyJsPlugin } = optimize; const cacheDir = findCacheDir({ name: "phenomic/webpack", create: true }); const requireSourceMapSupport = `require('${require .resolve("source-map-support/register") // windows support .replace(/\\/g, "/")}');`; const wrap = JSON.stringify; const isNotFoundError = e => e.code === "MODULE_NOT_FOUND"; const defaultExternals = [ // we could consider node_modules as externals deps // and so use something like // /^[A-Za-z0-9-_]/ // to not bundle all deps in the static build (for perf) // the problem is that if people rely on node_modules for stuff // like css, this breaks their build. // Glamor integration "glamor", "glamor/server", // Aprodite integration "aphrodite", "aphrodite/no-important" ]; const getWebpackConfig = (config: PhenomicConfig) => { let webpackConfig; try { webpackConfig = require(path.join(config.path, "webpack.config.js"))( config ); debug("webpack.config.js used"); } catch (e) { if (!isNotFoundError(e)) { throw e; } debug("webpack.config.js is failing", e.toString()); try { webpackConfig = require(path.join( config.path, "webpack.config.babel.js" ))(config); debug("webpack.config.babel.js used"); } catch (e) { if (!isNotFoundError(e)) { throw e; } debug("webpack.config.babel.js is failing", e.toString()); webpackConfig = require(path.join(__dirname, "webpack.config.js"))( config ); debug("default webpack config used"); } } validate(webpackConfig, config); debug(webpackConfig); return { ...webpackConfig, plugins: [ ...(webpackConfig.plugins || []), new webpack.DefinePlugin({ "process.env.NODE_ENV": wrap(process.env.NODE_ENV) }) ] }; }; export default function() { return { name: "@phenomic/plugin-bundler-webpack", addDevServerMiddlewares(config: PhenomicConfig) { debug("get middlewares"); const compiler = webpack(getWebpackConfig(config)); let assets = {}; compiler.plugin("done", stats => { assets = {}; const namedChunks = stats.compilation.namedChunks; Object.keys(namedChunks).forEach(chunkName => { const files = namedChunks[chunkName].files.filter( file => !file.endsWith(".hot-update.js") ); if (files.length) { assets = { ...assets, [chunkName]: files.shift() }; } }); }); return [ ( req: express$Request, res: express$Response, next: express$NextFunction ) => { res.locals.assets = assets; next(); }, webpackDevMiddleware(compiler, { stats: { chunkModules: false, assets: false } // @todo add this and output ourself a nice message for build status // noInfo: true, // quiet: true, }), webpackHotMiddleware(compiler, { reload: true // skip hot middleware logs if !verbose // log: config.verbose ? undefined : () => {}, }) ]; }, buildForPrerendering(config: PhenomicConfig) { debug("build for prerendering"); const webpackConfig = getWebpackConfig(config); const specialConfig = { ...webpackConfig, // only keep the entry we are going to use entry: { [config.bundleName]: webpackConfig.entry[config.bundleName] }, // adjust some config details to be node focused target: "node", // externals for package/relative name externals: [...(webpackConfig.externals || defaultExternals)], output: { publicPath: "/", // @todo make this dynamic path: cacheDir, filename: "[name].js", library: "app", libraryTarget: "commonjs2" }, plugins: [ // Remove UglifyJSPlugin from plugin stack ...(webpackConfig.plugins ? webpackConfig.plugins.filter( plugin => !(plugin instanceof UglifyJsPlugin) ) : []), // sourcemaps new BannerPlugin({ banner: requireSourceMapSupport, raw: true, entryOnly: false }) ], // sourcemaps devtool: "#source-map" }; return webpackPromise(specialConfig).then( () => require(path.join(cacheDir, config.bundleName)).default ); }, build(config: PhenomicConfig) { debug("build"); return webpackPromise(getWebpackConfig(config)).then( stats => stats.toJson().assetsByChunkName ); } }; }
JavaScript
0.000008
@@ -1310,16 +1310,39 @@ portant%22 +,%0A%0A %22react-native-web%22 %0A%5D;%0A%0Acon
7b60ff8504e240c14dd4ef5a9332acdbbe845416
Fix bug in reducer reset
reducer.js
reducer.js
import {INIT, PUSH, REPLACE, POP, DISMISS, RESET} from './actions'; function isNumeric(n) { return !isNaN(parseFloat(n)) && isFinite(n); } function clone(map){ var el = {}; for (var i in map) if (typeof(map[i])!='object') el[i] = map[i]; return el; } export default function reducer(state = { routes: [], currentRoute: null}, action) { switch (action.type) { case INIT: return { routes: [action.initial], currentRoute: action.initial }; case PUSH: return { mode: PUSH, routes: [...state.routes, action.name], currentRoute: action.name }; case REPLACE: return { mode: REPLACE, routes: [...state.routes.slice(0, state.routes.length - 1), action.name], currentRoute: action.name }; case POP: let num = isNumeric(action.data) ? action.data : 1; if (state.routes.length <= num) { throw new Error("Number of routes should be greater than pop() param: " + num); } return { mode: POP, routes: [...state.routes.slice(0, state.routes.length - num)], currentRoute: state.routes[state.routes.length - num - 1] }; case DISMISS: if (state.routes.length <= 1) { throw new Error("Number of routes should be greater than 1"); } return { mode: DISMISS, routes: [...state.routes.slice(0, state.routes.length - 1)], currentRoute: state.routes[state.routes.length - 2] }; case RESET: return { mode: RESET, routes: [action.initial], currentRoute: action.initial } default: return state; } };
JavaScript
0.000001
@@ -1887,36 +1887,31 @@ -currentRoute +initial : action.ini
f8a6f1c1291ea131ba5b8214471b7d03b4484a1d
Update default guide label format to support multi-line arrays. (#2456)
packages/vega-encode/src/ticks.js
packages/vega-encode/src/ticks.js
import {isLogarithmic, Time, UTC} from 'vega-scale'; import {timeFormat, timeInterval, utcFormat, utcInterval} from 'vega-time'; import {error, isNumber, isObject, isString, peek, span} from 'vega-util'; import {format as numberFormat, formatSpecifier} from 'd3-format'; /** * Determine the tick count or interval function. * @param {Scale} scale - The scale for which to generate tick values. * @param {*} count - The desired tick count or interval specifier. * @param {number} minStep - The desired minimum step between tick values. * @return {*} - The tick count or interval function. */ export function tickCount(scale, count, minStep) { var step; if (isNumber(count)) { if (scale.bins) { count = Math.max(count, scale.bins.length); } if (minStep != null) { count = Math.min(count, ~~(span(scale.domain()) / minStep) || 1); } } if (isObject(count)) { step = count.step; count = count.interval; } if (isString(count)) { count = scale.type === Time ? timeInterval(count) : scale.type == UTC ? utcInterval(count) : error('Only time and utc scales accept interval strings.'); if (step) count = count.every(step); } return count; } /** * Filter a set of candidate tick values, ensuring that only tick values * that lie within the scale range are included. * @param {Scale} scale - The scale for which to generate tick values. * @param {Array<*>} ticks - The candidate tick values. * @param {*} count - The tick count or interval function. * @return {Array<*>} - The filtered tick values. */ export function validTicks(scale, ticks, count) { var range = scale.range(), lo = Math.floor(range[0]), hi = Math.ceil(peek(range)); if (lo > hi) { range = hi; hi = lo; lo = range; } ticks = ticks.filter(function(v) { v = scale(v); return lo <= v && v <= hi; }); if (count > 0 && ticks.length > 1) { var endpoints = [ticks[0], peek(ticks)]; while (ticks.length > count && ticks.length >= 3) { ticks = ticks.filter(function(_, i) { return !(i % 2); }); } if (ticks.length < 3) { ticks = endpoints; } } return ticks; } /** * Generate tick values for the given scale and approximate tick count or * interval value. If the scale has a 'ticks' method, it will be used to * generate the ticks, with the count argument passed as a parameter. If the * scale lacks a 'ticks' method, the full scale domain will be returned. * @param {Scale} scale - The scale for which to generate tick values. * @param {*} [count] - The approximate number of desired ticks. * @return {Array<*>} - The generated tick values. */ export function tickValues(scale, count) { return scale.bins ? validTicks(scale, scale.bins) : scale.ticks ? scale.ticks(count) : scale.domain(); } /** * Generate a label format function for a scale. If the scale has a * 'tickFormat' method, it will be used to generate the formatter, with the * count and specifier arguments passed as parameters. If the scale lacks a * 'tickFormat' method, the returned formatter performs simple string coercion. * If the input scale is a logarithmic scale and the format specifier does not * indicate a desired decimal precision, a special variable precision formatter * that automatically trims trailing zeroes will be generated. * @param {Scale} scale - The scale for which to generate the label formatter. * @param {*} [count] - The approximate number of desired ticks. * @param {string} [specifier] - The format specifier. Must be a legal d3 * specifier string (see https://github.com/d3/d3-format#formatSpecifier) or * time multi-format specifier object. * @return {function(*):string} - The generated label formatter. */ export function tickFormat(scale, count, specifier, formatType, noSkip) { var type = scale.type, format = (type === Time || formatType === Time) ? timeFormat(specifier) : (type === UTC || formatType === UTC) ? utcFormat(specifier) : scale.tickFormat ? scale.tickFormat(count, specifier) : specifier ? numberFormat(specifier) : String; if (isLogarithmic(type)) { var logfmt = variablePrecision(specifier); format = noSkip || scale.bins ? logfmt : filter(format, logfmt); } return format; } function filter(sourceFormat, targetFormat) { return _ => sourceFormat(_) ? targetFormat(_) : ''; } function variablePrecision(specifier) { var s = formatSpecifier(specifier || ','); if (s.precision == null) { s.precision = 12; switch (s.type) { case '%': s.precision -= 2; break; case 'e': s.precision -= 1; break; } return trimZeroes( numberFormat(s), // number format numberFormat('.1f')(1)[1] // decimal point character ); } else { return numberFormat(s); } } function trimZeroes(format, decimalChar) { return function(x) { var str = format(x), dec = str.indexOf(decimalChar), idx, end; if (dec < 0) return str; idx = rightmostDigit(str, dec); end = idx < str.length ? str.slice(idx) : ''; while (--idx > dec) if (str[idx] !== '0') { ++idx; break; } return str.slice(0, idx) + end; }; } function rightmostDigit(str, dec) { var i = str.lastIndexOf('e'), c; if (i > 0) return i; for (i=str.length; --i > dec;) { c = str.charCodeAt(i); if (c >= 48 && c <= 57) return i + 1; // is digit } }
JavaScript
0
@@ -136,16 +136,25 @@ %7Berror, + isArray, isNumbe @@ -274,16 +274,115 @@ rmat';%0A%0A +const defaultFormatter = value =%3E isArray(value)%0A ? value.map(v =%3E String(v))%0A : String(value);%0A%0A /**%0A * D @@ -4235,22 +4235,32 @@ : -String +defaultFormatter ;%0A%0A if
4af9cf7707fa3bb32f402be461b16f0137518556
Change dev-port to 8081 (fix #53)
config/index.js
config/index.js
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'assets', assetsPublicPath: '/', publicPath: '/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'], // Run the build command with an extra argument to // View the bundle analyzer report after build finishes: // `npm run build --report` // Set to `true` or `false` to always turn it on or off bundleAnalyzerReport: process.env.npm_config_report }, dev: { env: require('./dev.env'), port: 8080, autoOpenBrowser: false, assetsSubDirectory: 'assets', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
JavaScript
0
@@ -999,17 +999,17 @@ ort: 808 -0 +1 ,%0A au
2f1c0e81f431b0e3e762c00513d09d1472bd0840
Reset assets public path
config/index.js
config/index.js
// see http://vuejs-templates.github.io/webpack for documentation. var path = require('path') module.exports = { build: { env: require('./prod.env'), index: path.resolve(__dirname, '../dist/index.html'), assetsRoot: path.resolve(__dirname, '../dist'), assetsSubDirectory: 'static', assetsPublicPath: 'http://avid.koser.us/assets/', productionSourceMap: true, // Gzip off by default as many popular static hosts such as // Surge or Netlify already gzip all static assets for you. // Before setting to `true`, make sure to: // npm install --save-dev compression-webpack-plugin productionGzip: false, productionGzipExtensions: ['js', 'css'] }, dev: { env: require('./dev.env'), port: 8080, assetsSubDirectory: 'static', assetsPublicPath: '/', proxyTable: {}, // CSS Sourcemaps off by default because relative paths are "buggy" // with this option, according to the CSS-Loader README // (https://github.com/webpack/css-loader#sourcemaps) // In our experience, they generally work as expected, // just be aware of this issue when enabling this option. cssSourceMap: false } }
JavaScript
0
@@ -321,35 +321,8 @@ h: ' -http://avid.koser.us/assets /',%0A
9ab908b4f77cbbf53664f8c591ea4f7e199aa638
Add SystemDefault to DEMO_REGISTRY
config/model.js
config/model.js
"use strict"; define(['settings'],function(settings){ function model(value,registry){ var DEFAULT_PAGE = 1; var DEFAULT_ITEM = 5; var __meta = {},__data = [],__uses=[],object = {meta:__meta,data:__data}; var registered = false; if(registry!=undefined){ DEMO_REGISTRY[registry.name] = {}; if(registry.uses){ var models = registry.uses; for(var i in models){ var endpoint = models[i]; require([settings.TEST_DIRECTORY+'/'+endpoint]); } } registered = true; } function list(){ var config = arguments[0]||{}; var page = config.page||DEFAULT_PAGE; var limit = __meta.limit||DEFAULT_ITEM; var keyword = config.keyword; var fields = config.fields; var index = limit=='less'?null:((page - 1) * limit); var data = __data; var __class = __meta.class; if(keyword&&fields){ var _d=[]; var regex = new RegExp(keyword, 'i'); for(var i in data){ var d = data[i]; var t = false; for(var ii in fields){ var f = fields[ii]; t = t || regex.test(d[f]); } if(t){ _d.push(d); } } data = _d; } var regEx = new RegExp('page|limit|keyword|fields'); for(var field in config){ var match = config[field]; if(!regEx.test(field)){ var _d=[]; for(var i in data){ var d = data[i]; var t = d[field]==match; if(!d.hasOwnProperty(field)) t = t && true; if(t){ _d.push(d); } } data = _d; } } var count = data.length; if(index!=null&&__class!="SystemDefault") data = data.slice(index,index+limit); var meta = __meta; meta.page = page; meta.limit = limit; if(__class!="SystemDefault"){ meta.count = count; meta.last = limit=='less'?1:Math.ceil(meta.count/limit); meta.next = page<meta.last?page+1:null; } meta.prev = page>1?page-1:null; return angular.copy({meta:meta,data:data}); }; function error(){ return angular.copy({meta:__meta}); }; function save(data){ var saved = false; if(!data.hasOwnProperty('id')){ data.id = __data.length; }else{ for(var i in __data){ var datum = __data[i]; if(datum.id==data.id){ for(var ii in data){ __data[i][ii] = data[ii]; } saved=true; break; } } } if(!saved){ __data.push(data); } if(registered) DEMO_REGISTRY[registry.name]=__data; return angular.copy({meta:__meta,data:data}); } function remove(data){ if(data.hasOwnProperty('id')){ for(var i in __data){ var datum = __data[i]; if(datum.id==data.id){ __data.splice(i,1); break; } } } if(registered) DEMO_REGISTRY[registry.name]=__data; return angular.copy({meta:__meta,data:data}); } function setMeta(meta){ __meta = meta; } function setData(data){ var __class = __meta.class; if(__class=="SystemDefault"){ __data = data; return; } for(var i in data){ var datum = data[i]; if( typeof datum=='object'){ if(!datum.hasOwnProperty('id')) datum.id= __data.length; __data.push(datum); }else{ __data[i] = datum; } } if(registered) DEMO_REGISTRY[registry.name]=__data; } object.GET = function(data){ return {success:list(data),error:error()}; } object.POST = function(data){ return {success:save(data),error:error()}; } object.DELETE = function(data){ return {success:remove(data),error:error()}; } object.PUT = function(data){ return {success:save(data),error:error()}; } object.save = save; object.remove = remove; if(value.hasOwnProperty('meta'))setMeta(value.meta); if(value.hasOwnProperty('data'))setData(value.data); return object; } return model; });
JavaScript
0
@@ -2934,16 +2934,77 @@ = data;%0A +%09%09%09%09if(registered)%0A%09%09%09%09%09DEMO_REGISTRY%5Bregistry.name%5D=__data;%0A %09%09%09%09retu
b0f0fc0fd84d923538b4f67a5ad5e11591ebf55c
Fix wiredep
config/watch.js
config/watch.js
module.exports = { bower : { files : ['bower.json'], tasks : ['bowerInstall'] }, js : { files : ['<%= config.app %>/scripts/**/*.js'], tasks : ['browserify'], options : { livereload : true } }, gruntfile : { files : ['Gruntfile.js'] }, styles : { files : ['<%= config.app %>/styles/{,*/}*.css'], tasks : ['newer:copy:styles', 'autoprefixer'] }, livereload : { options : { livereload : '<%= connect.options.livereload %>' }, files : [ '<%= config.app %>/{,*/}*.html', '.tmp/styles/{,*/}*.css', '<%= config.app %>/images/{,*/}*' ] } };
JavaScript
0.000002
@@ -85,20 +85,15 @@ : %5B' -bowerInstall +wiredep '%5D%0A
f51952d882b12c9e6160af8d2a538ed8407a8e3d
Remove comment
toolkits/landcover/test/helpers/test-image.js
toolkits/landcover/test/helpers/test-image.js
/** * @license * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ // Maximum number of constant images to fetch when processing test data // collections. var MAX_TEST_COLLECTION_SIZE = 15; /** * Returns a single constant ee.Image comprised of the bands and values in the * specified dictionary. * * @param {*} values A dictionary containing band names as keys and * corresponding numeric values. The values are used to build an ee.Image * with a single constant value in each respective band. * @param {string} startDate An optional start date for the image, in YYYY-MM-DD * format. * @returns {!ee.Image} */ var create = function(values, startDate) { var image = ee.Dictionary(values).toImage().int64(); if (startDate) { image = image.set('system:time_start', ee.Date(startDate).millis()); } return image; }; /** * Reduces the specified constant ee.Image to a dictionary with one key per * band. * * @param {!ee.Image} image A constant ee.Image (an image with a single value). * @returns {*} A dictionary keyed by band name. */ var reduceConstant = function(image) { // DO NOT MERGE - USE .sample() INSTEAD? return ee.Image(image) .reduceRegion(ee.Reducer.first(), ee.Geometry.Point(0, 0), 1); }; /** * Reduces a collection of constant ee.Image instances to a list of * dictionaries keyed by band. * * @param {!ee.ImageCollection} collection A collection containing only constant * ee.Image instances (images with a single value). * @returns {Array} An array of dictionaries keyed by band name. */ var reduceConstants = function(collection) { return collection.toList(MAX_TEST_COLLECTION_SIZE).map(reduceConstant); }; exports.create = create; exports.reduceConstant = reduceConstant; exports.reduceConstants = reduceConstants;
JavaScript
0
@@ -1646,51 +1646,8 @@ ) %7B%0A - // DO NOT MERGE - USE .sample() INSTEAD?%0A re
00b9097620e5e74e8789cd86dac50cd692e9d864
Reset default firebase config
src/admin/firebase_config/config.js
src/admin/firebase_config/config.js
const config = { apiKey: 'AIzaSyBTOhdIK1iBnmTSUXbIqYySeuqG8RwqAC4', authDomain: 'tamiat-dadae.firebaseapp.com', databaseURL: 'https://tamiat-dadae.firebaseio.com', projectId: 'tamiat-dadae', storageBucket: 'tamiat-dadae.appspot.com', messagingSenderId: '1013231925212' } export default config
JavaScript
0.000001
@@ -31,41 +31,41 @@ zaSy -BTOhdIK1iBnmTSUXbIqYySeuqG8RwqAC4 +DN6vYIk-89PI1y1gmI8P-33hvZ8NxT3iI ',%0A @@ -80,30 +80,27 @@ ain: 'tamiat --dadae +cms .firebaseapp @@ -136,22 +136,19 @@ //tamiat --dadae +cms .firebas @@ -177,22 +177,19 @@ 'tamiat --dadae +cms ',%0A sto @@ -211,14 +211,11 @@ miat --dadae +cms .app @@ -251,21 +251,19 @@ d: ' -1013231925212 +94963392700 '%0A%7D%0A
724df224cb887d04b579a26883e9641bbaabdcfb
correct generation logs
src/api/db/manage/generate/index.js
src/api/db/manage/generate/index.js
const { Report, db } = require('../../index.js')(process.env.MONGODB_URI); const mongoose = require('mongoose'); async function generateFromReports() { // Find all reports that start a list. const tailReports = await Report.find({ previous: { $exists: false }, }).exec(); const newLoos = []; for (const report of tailReports) { let root = report; // Traverse each linked report list to find the root report. while (root.next) { await root.populate('next').execPopulate(); root = root.next; } // Generate a loo from each root report and save it. const newLoo = await root.generateLoo(); newLoos.push(newLoo); await newLoo.save(); } return newLoos; } // use a main function so we can have await niceties async function main() { try { // check they're serious if (!process.argv.slice(2).includes('--confirm')) { throw Error( 'Please confirm that you want to drop the existing new-schema loos with --confirm.' ); } // drop existing loo collection console.warn('Dropping existing new-schema loo collection'); try { await db.dropCollection('newloos'); } catch (e) { // 26 is collection not found :-) a fresh db if (e.code !== 26) { throw e; } } // create set of new loos from new reports console.warn('Migrating loos across from new reports'); const newLoos = await generateFromReports(); console.error(newLoos.length + ' loos generated'); } catch (e) { console.error(e); process.exitCode = 1; } // tidy await mongoose.disconnect(); db.close(); } main();
JavaScript
0.00006
@@ -954,27 +954,16 @@ xisting -new-schema loos wit @@ -976,16 +976,16 @@ nfirm.'%0A + ); @@ -1067,19 +1067,8 @@ ing -new-schema loo @@ -1293,28 +1293,24 @@ w loos from -new reports%0A @@ -1321,17 +1321,17 @@ ole. -warn('Mig +log('Gene rati @@ -1342,23 +1342,12 @@ oos -across from new +from rep @@ -1416,21 +1416,19 @@ console. -error +log (newLoos
9df5638c8ec998161604728aa4cf76b751336af5
make linter happy - add missing trailing comma
src/autocomplete/CommandProvider.js
src/autocomplete/CommandProvider.js
/* Copyright 2016 Aviral Dasgupta Copyright 2017 Vector Creations Ltd Copyright 2017 New Vector Ltd 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. */ import React from 'react'; import { _t, _td } from '../languageHandler'; import AutocompleteProvider from './AutocompleteProvider'; import FuzzyMatcher from './FuzzyMatcher'; import {TextualCompletion} from './Components'; // TODO merge this with the factory mechanics of SlashCommands? // Warning: Since the description string will be translated in _t(result.description), all these strings below must be in i18n/strings/en_EN.json file const COMMANDS = [ { command: '/me', args: '<message>', description: _td('Displays action'), }, { command: '/ban', args: '<user-id> [reason]', description: _td('Bans user with given id'), }, { command: '/unban', args: '<user-id>', description: _td('Unbans user with given id'), }, { command: '/op', args: '<user-id> [<power-level>]', description: _td('Define the power level of a user'), }, { command: '/deop', args: '<user-id>', description: _td('Deops user with given id'), }, { command: '/invite', args: '<user-id>', description: _td('Invites user with given id to current room'), }, { command: '/join', args: '<room-alias>', description: _td('Joins room with given alias'), }, { command: '/part', args: '[<room-alias>]', description: _td('Leave room'), }, { command: '/topic', args: '<topic>', description: _td('Sets the room topic'), }, { command: '/kick', args: '<user-id> [reason]', description: _td('Kicks user with given id'), }, { command: '/nick', args: '<display-name>', description: _td('Changes your display nickname'), }, { command: '/ddg', args: '<query>', description: _td('Searches DuckDuckGo for results'), }, { command: '/tint', args: '<color1> [<color2>]', description: _td('Changes colour scheme of current room'), }, { command: '/verify', args: '<user-id> <device-id> <device-signing-key>', description: _td('Verifies a user, device, and pubkey tuple'), }, { command: '/ignore', args: '<user-id>', description: _td('Ignores a user, hiding their messages from you'), }, { command: '/unignore', args: '<user-id>', description: _td('Stops ignoring a user, showing their messages going forward'), }, { command: '/devtools', args: '', description: _td('Opens the Developer Tools dialog') }, // Omitting `/markdown` as it only seems to apply to OldComposer ]; const COMMAND_RE = /(^\/\w*)/g; export default class CommandProvider extends AutocompleteProvider { constructor() { super(COMMAND_RE); this.matcher = new FuzzyMatcher(COMMANDS, { keys: ['command', 'args', 'description'], }); } async getCompletions(query: string, selection: {start: number, end: number}) { let completions = []; const {command, range} = this.getCurrentCommand(query, selection); if (command) { completions = this.matcher.match(command[0]).map((result) => { return { completion: result.command + ' ', component: (<TextualCompletion title={result.command} subtitle={result.args} description={_t(result.description)} />), range, }; }); } return completions; } getName() { return '*️⃣ ' + _t('Commands'); } renderCompletions(completions: [React.Component]): ?React.Component { return <div className="mx_Autocomplete_Completion_container_block"> { completions } </div>; } }
JavaScript
0.000017
@@ -3306,16 +3306,17 @@ dialog') +, %0A %7D,%0A
71f5c9791df3a97ebe387025d19ddc9a2e6d3e07
replace switch with if-else chain
src/babel/build-external-helpers.js
src/babel/build-external-helpers.js
import buildHelpers from "./build-helpers"; import generator from "./generation"; import * as util from "./util"; import t from "./types"; function buildGlobal(namespace, builder) { var body = []; var container = t.functionExpression(null, [t.identifier("global")], t.blockStatement(body)); var tree = t.program([t.expressionStatement(t.callExpression(container, [util.template("self-global")]))]); body.push(t.variableDeclaration("var", [ t.variableDeclarator( namespace, t.assignmentExpression("=", t.memberExpression(t.identifier("global"), namespace), t.objectExpression([])) ) ])); builder(body); return tree; } function buildUmd(namespace, builder) { var body = []; body.push(t.variableDeclaration("var", [ t.variableDeclarator(namespace, t.identifier("global")) ])); builder(body); var container = util.template("umd-commonjs-strict", { FACTORY_PARAMETERS: t.identifier("global"), BROWSER_ARGUMENTS: t.assignmentExpression("=", t.memberExpression(t.identifier("root"), namespace), t.objectExpression({})), COMMON_ARGUMENTS: t.identifier("exports"), AMD_ARGUMENTS: t.arrayExpression([t.literal("exports")]), FACTORY_BODY: body, UMD_ROOT: t.identifier("this") }); return t.program([container]); } function buildVar(namespace, builder) { var body = []; body.push(t.variableDeclaration("var", [ t.variableDeclarator(namespace, t.objectExpression({})) ])); builder(body); return t.program(body); } export default function (whitelist, outputType = "global") { var namespace = t.identifier("babelHelpers"); var builder = function (body) { return buildHelpers(body, namespace, whitelist); }; var tree; switch (outputType) { case "global": tree = buildGlobal(namespace, builder); break; case "umd": tree = buildUmd(namespace, builder); break; case "var": tree = buildVar(namespace, builder); break; default: throw new Error("Unsupported output type"); } return generator(tree).code; };
JavaScript
0.000002
@@ -1747,14 +1747,10 @@ ;%0A -switch +if (ou @@ -1761,18 +1761,12 @@ Type -) %7B%0A case + === %22gl @@ -1770,17 +1770,19 @@ %22global%22 -: +) %7B %0A tre @@ -1824,30 +1824,42 @@ ;%0A - break;%0A case +%7D else if (outputType === %22umd%22 -: +) %7B %0A @@ -1902,30 +1902,42 @@ ;%0A - break;%0A case +%7D else if (outputType === %22var%22 -: +) %7B %0A @@ -1980,27 +1980,16 @@ ;%0A - break;%0A default: +%7D else %7B %0A
67b049f22dc6cab2b70d8e78bad699d286cc5b41
Update index.js
Leaderboard-Stats-Plugin/index.js
Leaderboard-Stats-Plugin/index.js
'use strict'; // dont touch var plugin = []; // dont touch plugin.command = []; // dont touch plugin.commandName = []; // dont touch plugin.gamemodeId = []; // dont touch plugin.gamemode = []; // dont touch plugin.addToHelp = []; // dont touch // [General] plugin.name = "Leaderboard Stats"; // Name of plugin REQUIRED plugin.author = "Andrews54757"; // author REQUIRED plugin.description = 'Adds stats to the end of the leaderboard'; // Desciprtion plugin.compatVersion = ''; // compatable with (todo) plugin.version = '1.0.0'; // version REQUIRED // [Extra Commands] plugin.commandName[0] = ""; // plugin add-on command names plugin.addToHelp[0] = ""; // help command add-on (adds this string to the help command) plugin.command[0] = ''; // extra command location // [Extra Gamemodes] plugin.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes plugin.gamemode[0] = ''; // gamemode location plugin.stage = 0; plugin.tick = 0; // [Functions] plugin.init = function (gameServer) { // init, Used to do stuff such as overriding things console.log("[LBStats] Started up and enabled"); }; plugin.onSecond = function (gameServer) { var lb = []; if (plugin.stage == 0) { var humans = 0; var bots = 0; var minions = 0; gameServer.getClients().forEach((client)=> { if ('_socket' in client) { humans++; } else if (!client.playerTracker.owner) { bots++; } else { minions ++; } }); var time = new Date().toISOString(); time.replace(/T/, ' ') // replace T with a space time.replace(/\..+/, '') lb[0] = "~~~~~~Stats~~~~~~"; lb[1] = "Players: " + humans; lb[2] = "Minions: " + minions; lb[3] = "Bots: " + bots + " Time: "; lb[4] = time; lb[5] = "~~~~~~~~~~~~~~~~~"; if (plugin.tick > 6) { plugin.tick = 0; plugin.stage = 1; } else { plugin.tick ++; } } else if (plugin.stage == 1) { lb[0] = "~~~~~~Stats~~~~~~"; lb[1] = "Highscore: " + Math.floor(gameServer.topscore); lb[2] = "By: " + gameServer.topusername; lb[3] = "Old HS Holder: " + Math.floor(gameServer.oldtopscores.score); lb[4] = "~~~~~~~~~~~~~~~~~"; if (plugin.tick > 6) { plugin.tick = 0; plugin.stage = 0; } else { plugin.tick ++; } } else { plugin.stage = 0; } gameServer.customLBEnd = lb; // called every second }; module.exports = plugin; // dont touch
JavaScript
0.000002
@@ -1785,33 +1785,33 @@ (plugin.tick %3E -6 +7 ) %7B%0A plugin.t @@ -1849,32 +1849,77 @@ %0A %7D else %7B%0A + if (isNaN(plugin.tick)) plugin.tick = 1;%0A plugin.tick @@ -2228,9 +2228,9 @@ k %3E -6 +7 ) %7B%0A
a5a8cf70af58fa36e5273b3284d823b28f3d1801
test updated and coverage improved
test/adapters/helpers/conversions.js
test/adapters/helpers/conversions.js
var libpath = process.env["JMX_COVERAGE"] ? "./../../../lib-cov" : "./../../../lib"; var assert = require("assert"), java = require("java"), conversions = require(libpath + "/adapters/helpers/conversions"); describe("conversions", function() { describe("#v8ToJavaClass", function() { [ // js objects [ "some string", "java.lang.String" ], [ false, "boolean" ], [ 1, "int" ], [ -2147483648, "int" ], [ -2147483649, "double" ], [ 4294967295, "int" ], [ 4294967296, "double" ], [ 1.5, "double" ], // java objects [ java.newInstanceSync("java.lang.String", "other string"), "java.lang.String" ], [ java.newInstanceSync("java.lang.Boolean", "false"), "boolean" ], [ java.newInstanceSync("java.lang.Integer", "2"), "int" ], [ java.newInstanceSync("java.lang.Long", "2"), "long" ], [ java.newInstanceSync("java.lang.Float", "2"), "int" ], [ java.newInstanceSync("java.lang.Float", "1.5"), "double" ], [ java.newInstanceSync("java.lang.Double", "2"), "int" ], [ java.newInstanceSync("java.lang.Double", "1.5"), "double" ], [ java.newInstanceSync("javax.management.Attribute", "name", "value"), "javax.management.Attribute" ] ].forEach(function(value) { var param = value[0]; var javaClass = value[1]; it("should return \"" + javaClass + "\" for argument value \"" + param + "\" and typeof \"" + typeof param + "\"", function() { assert.strictEqual(conversions.v8ToJavaClass(param), javaClass); }); }); }); });
JavaScript
0
@@ -340,16 +340,17 @@ string%22, + %22java.l @@ -383,24 +383,25 @@ se, + %22boolean%22 @@ -420,16 +420,17 @@ %5B 1, + @@ -479,16 +479,17 @@ 3648, + %22int%22 @@ -522,16 +522,17 @@ 7483649, + %22doub @@ -567,24 +567,25 @@ 4967295, + %22int%22 @@ -613,24 +613,25 @@ 4967296, + %22double%22 @@ -652,16 +652,17 @@ %5B 1.5, + @@ -685,16 +685,85 @@ %5D, +%0A %5B %5B %22an array%22 %5D, %22java.lang.Object%22 %5D, // TODO: test/fix this %0A%0A @@ -1912,16 +1912,1201 @@ %7D);%0A%0A + it(%22should throw an exception when the object cannot be converted%22, function() %7B%0A assert.throws(%0A function() %7B%0A conversions.v8ToJavaClass(undefined);%0A %7D,%0A /v8ToJavaClass%5B(%5D%5B)%5D: unknown object type/%0A );%0A %7D);%0A%0A %7D);%0A%0A describe(%22#isJavaPrimitiveClass%22, function() %7B%0A%0A %5B%0A %22byte%22,%0A %22short%22,%0A %22int%22,%0A %22long%22,%0A %22float%22,%0A %22double%22,%0A %22boolean%22,%0A %22char%22%0A %5D.forEach(function(className) %7B%0A it(%22should return true for %5C%22%22 + className + %22%5C%22%22, function() %7B%0A assert.strictEqual(conversions.isJavaPrimitiveClass(className), true);%0A %7D);%0A %7D);%0A%0A %5B%0A %22java.lang.Byte%22,%0A %22java.lang.Short%22,%0A %22java.lang.Integer%22,%0A %22java.lang.Long%22,%0A %22java.lang.Float%22,%0A %22java.lang.Double%22,%0A %22java.long.Boolean%22,%0A %22java.lang.String%22,%0A %22java.lang.Object%22,%0A java.newInstanceSync(%22javax.management.Attribute%22, %22name%22, %22value%22).getClassSync().getNameSync()%0A %5D.forEach(function(className) %7B%0A it(%22should return false for %5C%22%22 + className + %22%5C%22%22, function() %7B%0A assert.strictEqual(conversions.isJavaPrimitiveClass(className), false);%0A %7D);%0A %7D);%0A%0A %7D);%0A%0A%7D
6d6d3a2afa994b5f35719194762d111645cee718
Reorder functions and document shiftSlides method.
public/javascripts/presenter.js
public/javascripts/presenter.js
(function($){ /** * This class represents the actual presentation. It encapsulates the * logic for: * - setting/maintaining the states of all slides. * - showing any given slide. * - transitioning to the next or previous slide. * It can be controlled by a public interface but does not listen for any * global user control. It's kept as dumb as possible so that there can * potentially be several on a page at once. */ var Presenter = function(options) { this._$baseEl = $(options.baseEl); this._init(); }; $.extend(Presenter.prototype, { _$baseEl: null, _slideCount: null, _currentSlide: 0, _init: function() { this._slideCount = this._$getSlides().length; this.showSlide(this._currentSlide); // Don't want transitions to be applied until initial states are set. // Do this on the next tick to prevent Chrome from animating on initial // pageload. var self = this; setTimeout(function() {self._$baseEl.addClass('enable-transitions');}, 0); }, _updateSlideStates: function() { var self = this; this._$getSlides().each(function(i) { $(this).toggleClass('past', i < self._currentSlide); $(this).toggleClass('current', i === self._currentSlide); $(this).toggleClass('future', i > self._currentSlide); }); }, shiftSlides: function(proportion) { if (proportion === 0) { this._$getSlides().css({ '-webkit-transform': '', '-moz-transform': '', '-o-transform': '', 'transform': '' }); return; } var self = this; $.each([-1,0,1], function(i, n) { var offset = proportion*100 + n*100; var setting = 'translate(' + offset + '%, 0px)'; self._$getSlideByRelativeIndex(n).css({ '-webkit-transform': setting, '-moz-transform': setting, '-o-transform': setting, 'transform': setting }); }); }, _$getSlideByRelativeIndex: function(delta) { var slide = this._currentSlide + delta; if (slide > this._slideCount-1 || slide < 0) { return $([]); } return this._$baseEl.find('.slide:eq(' + slide + ')'); }, next: function() { this.showSlide(this._currentSlide + 1); }, previous: function() { this.showSlide(this._currentSlide - 1); }, showSlide: function(number) { if (number > this._slideCount-1 || number < 0) { return; } this._currentSlide = number; this._$baseEl.trigger('slidechange', number); this._updateSlideStates(); }, _$getSlides: function() { return this._$baseEl.find('.slide'); }, swipeStarted: function() { this._$baseEl.removeClass('enable-transitions'); }, swipeStopped: function() { this._$baseEl.addClass('enable-transitions'); } }); window.Presenter = Presenter; })(jQuery);
JavaScript
0
@@ -1512,830 +1512,8 @@ %7D,%0A%0A - shiftSlides: function(proportion) %7B%0A if (proportion === 0) %7B%0A this._$getSlides().css(%7B%0A '-webkit-transform': '',%0A '-moz-transform': '',%0A '-o-transform': '',%0A 'transform': ''%0A %7D);%0A return;%0A %7D%0A var self = this;%0A $.each(%5B-1,0,1%5D, function(i, n) %7B%0A var offset = proportion*100 + n*100;%0A var setting = 'translate(' + offset + '%25, 0px)';%0A self._$getSlideByRelativeIndex(n).css(%7B%0A '-webkit-transform': setting,%0A '-moz-transform': setting,%0A '-o-transform': setting,%0A 'transform': setting%0A %7D);%0A %7D);%0A %7D,%0A%0A @@ -1557,24 +1557,24 @@ on(delta) %7B%0A + @@ -1787,32 +1787,127 @@ ');%0A %7D,%0A%0A + _$getSlides: function() %7B%0A return this._$baseEl.find('.slide');%0A %7D,%0A%0A next: fu @@ -2363,36 +2363,233 @@ %7D,%0A%0A -_$ge +/**%0A * Shift slides left or right by proportion of screen width.%0A * This is used by the SwipeController to make the slides%0A * follow the swipe gesture.%0A */%0A%0A shif tSlides: functio @@ -2582,32 +2582,42 @@ lides: function( +proportion ) %7B%0A @@ -2620,42 +2620,759 @@ -return this._$baseEl.find('.slide' +if (proportion === 0) %7B%0A this._$getSlides().css(%7B%0A '-webkit-transform': '',%0A '-moz-transform': '',%0A '-o-transform': '',%0A 'transform': ''%0A %7D);%0A return;%0A %7D%0A var self = this;%0A $.each(%5B-1,0,1%5D, function(i, n) %7B%0A var offset = proportion*100 + n*100;%0A var setting = 'translate(' + offset + '%25, 0px)';%0A self._$getSlideByRelativeIndex(n).css(%7B%0A '-webkit-transform': setting,%0A '-moz-transform': setting,%0A '-o-transform': setting,%0A 'transform': setting%0A %7D);%0A %7D );%0A
5ab5ec57a032874b11852d535a870306de6c10ac
Update test/github/util/check-authorization to use ava assertions
test/github/util/check-authorization.js
test/github/util/check-authorization.js
import chai from 'chai' import chaiAsPromised from 'chai-as-promised' import requireInject from 'require-inject' import sinon from 'sinon' import test from 'ava' chai.use(chaiAsPromised) const expect = chai.expect test.beforeEach((t) => { const list = sinon.stub() const stubs = { ghissues: { createComment: sinon.spy(), list } } const util = requireInject('../../../src/github/util', stubs) t.context = { list, util } }) test('github.util.checkAuthorization: resolves if issues can be retrieved', (t) => { const {list, util} = t.context const authData = 'authorization data' list.yields() return expect(util.checkAuthorization(authData, 'program')) .to.eventually.equal(authData) }) test("github.util.checkAuthorization: rejects if issues list can't be retrieved", (t) => { const {list, util} = t.context list.yields(new Error('some error')) return expect(util.checkAuthorization('authorization data', 'program')) .to.be.rejected })
JavaScript
0
@@ -1,74 +1,4 @@ -import chai from 'chai'%0Aimport chaiAsPromised from 'chai-as-promised'%0A impo @@ -90,61 +90,8 @@ a'%0A%0A -chai.use(chaiAsPromised)%0Aconst expect = chai.expect%0A%0A test @@ -452,24 +452,24 @@ const -authData +expected = 'auth @@ -501,39 +501,32 @@ elds()%0A return -expect( util.checkAuthor @@ -533,24 +533,24 @@ ization( -authData +expected , 'progr @@ -557,43 +557,62 @@ am') -)%0A .to.eventually.equal(authData +.then((authData) =%3E %7B%0A t.is(authData, expected)%0A %7D )%0A%7D) @@ -785,22 +785,24 @@ return -expect +t.throws (util.ch @@ -856,27 +856,7 @@ '))%0A - .to.be.rejected%0A %7D)%0A
b57a3e6ab21f42a42f040aa26f35a063979baae5
Remove unused variables in test_logging.js
test/integration/server/test_logging.js
test/integration/server/test_logging.js
'use strict'; var fs = require('fs'); var path = require('path'); var supertest = require('supertest'); var expect = require('thehelp-test').expect; var util = require('./util'); var serverUtil = require('../../../src/server/util'); var logShim = require('thehelp-log-shim'); var logger = logShim('end-to-end:test'); var winston; try { winston = require('winston'); } catch (e) {} describe('winston creates expected log files', function() { var agent, child, logFiles; before(function(done) { agent = supertest.agent('http://localhost:3000'); util.emptyDir(util.logsDir, function(err) { if (err) { throw err; } child = util.startProcess( path.join(__dirname, '../../scenarios/end_to_end_cluster.js')); setTimeout(done, 1000); }); }); after(function(done) { this.timeout(10000); child.on('close', function() { done(); }); child.kill(); }); it('creates two log files on startup', function(done) { if (!winston) { return done(); } fs.readdir(util.logsDir, function(err, files) { if (err) { throw err; } expect(files).to.have.length(2); files = files.sort(); expect(files).to.have.deep.property('0').that.match(/master/); expect(files).to.have.deep.property('1').that.match(/worker/); logFiles = files; done(); }); }); it('root returns', function(done) { agent .get('/') .expect('X-Worker', '1') .expect('Connection', 'close') .expect(200, done); }); it('on async error, gets response with \'close connection\' header', function(done) { agent .get('/error') .expect('Connection', 'close') .expect('Content-Type', /text\/plain/) .expect('X-Worker', '1') .expect(/^error\!/) .expect(500, done); }); it('starts up another node', function(done) { this.timeout(5000); agent .get('/') .expect('X-Worker', '2') .expect('Connection', 'close') .expect(200, done); }); it('three log files now in directory', function(done) { if (!winston) { return done(); } fs.readdir(util.logsDir, function(err, files) { if (err) { throw err; } expect(files).to.have.length(3); files = files.sort(); expect(files).to.have.deep.property('0', logFiles[0]); expect(files).to.have.deep.property('1', logFiles[1]); expect(files).to.have.deep.property('2').that.match(/worker/); logFiles = files; done(); }); }); });
JavaScript
0.000002
@@ -178,147 +178,8 @@ l'); -%0Avar serverUtil = require('../../../src/server/util');%0A%0Avar logShim = require('thehelp-log-shim');%0Avar logger = logShim('end-to-end:test'); %0A%0Ava
29b688102c816eabe7904860c8e582bf63838c0e
fix tests for ReadableState based on new "tiime" element
test/js/components/ReadableDate-spec.js
test/js/components/ReadableDate-spec.js
import React from 'react'; import { assert } from 'chai'; import { shallow } from 'enzyme'; import { ReadableDate } from '../../../src/js/components'; describe("ReadableDate", () => { it("renders dash with no data", () => { const wrapper = shallow(<ReadableDate />); assert.equal(wrapper.containsMatchingElement( <span>-</span> ), true); }); it("renders dash with non-ISO-8601 date string", () => { const wrapper = shallow(<ReadableDate date="2016/06/06" />); assert.equal(wrapper.containsMatchingElement( <span>-</span> ), true); }); it("renders 'a few seconds ago' with current date", () => { const wrapper = shallow(<ReadableDate date={new Date().toISOString()} />); assert.equal(wrapper.containsMatchingElement( <span>a few seconds ago</span> ), true); }); it("renders 'an hour ago' with current date minus 60m", () => { const now = new Date(); const hourAgo = new Date(now.getTime() - 1000*60*60); const wrapper = shallow(<ReadableDate date={hourAgo.toISOString()} />); assert.equal(wrapper.containsMatchingElement( <span>an hour ago</span> ), true); }); });
JavaScript
0
@@ -804,91 +804,89 @@ per. -containsMatchingElement(%0A %3Cspan%3Ea few seconds ago%3C/span%3E%0A ), true +find('time').length, 1);%0A assert.equal(wrapper.text(), 'a few seconds ago' );%0A @@ -1055,17 +1055,16 @@ 60*60);%0A -%0A @@ -1169,85 +1169,83 @@ per. -containsMatchingElement(%0A %3Cspan%3Ean hour ago%3C/span%3E%0A ), true +find('time').length, 1);%0A assert.equal(wrapper.text(), 'an hour ago' );%0A
6c51050c22253cbade347f0a449e74dfca4e6910
fix loading spinner tests
test/spec/directives/loading-spinner.js
test/spec/directives/loading-spinner.js
'use strict'; describe('Directive: loadingSpinner', function () { // load the directive's module beforeEach(module('baubleApp')); var element, scope; beforeEach(inject(function ($rootScope) { scope = $rootScope.$new(); })); it('should make hidden element visible', inject(function ($compile) { element = angular.element('<loading-spinner></loading-spinner>'); element = $compile(element)(scope); expect(element.text()).toBe('this is the loadingSpinner directive'); })); });
JavaScript
0
@@ -61,16 +61,18 @@ n () %7B%0A%0A + // loa @@ -96,16 +96,18 @@ module%0A + before @@ -119,17 +119,17 @@ module(' -b +B aubleApp @@ -134,16 +134,18 @@ pp'));%0A%0A + var el @@ -163,16 +163,18 @@ scope;%0A%0A + before @@ -209,24 +209,28 @@ cope) %7B%0A + + scope = $roo @@ -248,16 +248,18 @@ ();%0A + %7D));%0A%0A it @@ -254,16 +254,18 @@ %7D));%0A%0A + it('sh @@ -273,35 +273,20 @@ uld -make hidden element visible +do something ', i @@ -309,24 +309,28 @@ $compile) %7B%0A + element @@ -349,16 +349,18 @@ ement('%3C +a loading- @@ -370,31 +370,29 @@ nner -%3E%3C/loading-spinner +=%22false%22%3E%3C/a %3E');%0A + @@ -430,16 +430,23 @@ pe);%0A + // expect( @@ -507,16 +507,18 @@ tive');%0A + %7D));%0A%7D
2a5726bd307b24a75c187a5c002ddf628643452e
Improve var ref test.
test/specs/parsing/performance.tests.js
test/specs/parsing/performance.tests.js
import { evaluateXPathToNumber, evaluateXPathToBoolean } from 'fontoxpath'; import slimdom from 'slimdom'; const cacheId = {}; describe('performance', () => { // Warm up the cache // Counting to 10 milion takes a couple of seconds. before(function () { this.timeout(100000); evaluateXPathToNumber('count(0 to 10000000)', document, null, {}, {cacheId}); }); it('can reuse cached results', function () { evaluateXPathToNumber('count(0 to 10000000)', document, null, {}, {cacheId}); }); it('can reuse cached sub-results', function () { chai.assert.isTrue(evaluateXPathToBoolean('10000001 = count(0 to 10000000)', document, null, {}, {cacheId})); }); }); function timeXPath (xpath, document) { const then = performance.now(); chai.assert(evaluateXPathToBoolean(xpath, document), `The passed XPath ${xpath} should resolve to true`); const now = performance.now(); return now - then; } function fillDocument (document, element, depth) { element.setAttribute('depth', depth); if (depth === 0) { return element; } var prototypeElement = element.appendChild( fillDocument( document, document.createElement('ele'), depth - 1)); for (let i = 1, l = 10; i < l; ++i) { element.appendChild(prototypeElement.cloneNode(true)); } return element; } function runTests (document) { let fullTraversalCost; before(function () { this.timeout(30000); fillDocument(document, document.appendChild(document.createElement('root')), 5); fullTraversalCost = timeXPath('/descendant::element() => count() > 10', document); }); it('Makes queries exit early by streaming them and only consuming the first item', function () { this.timeout(10000); chai.assert.isAtMost( timeXPath('(/descendant::element()["4" = @depth]) => head() => count() = 1', document), fullTraversalCost * 0.5, 'Revaluating a filtered xpath must not cost significantly more then an unfiltered one'); }); it('Makes sorting fast by skipping it in some queries', function () { this.timeout(10000); const timeWithoutExtraSteps = timeXPath('(/descendant::*) => count() > 10', document); // The extra steps should not add too much of a performance regression, since they do not have to be sorted chai.assert.isAtMost( timeXPath('(/child::*/child::*/child::*/child::*/child::*) => count()', document), timeWithoutExtraSteps * 1.3); }); it('Saves variable results', function () { this.timeout(10000); const timeWithoutExtraSteps = timeXPath('(/descendant::*) => count() > 10', document); // The extra steps should not add too much of a performance regression, since they do not have to be sorted chai.assert.isAtMost( timeXPath('let $c := (/descendant::*) => count() return $c + $c + $c', document), timeWithoutExtraSteps * 1.3); }); } describe('performance of descendant axis', () => { describe('in browser DOM', () => runTests(window.document.implementation.createDocument(null, null))); describe('in slimdom', () => runTests(slimdom.createDocument())); });
JavaScript
0
@@ -1920,56 +1920,29 @@ it(' -Makes sorting fast by skipping it in some querie +Saves variable result s', @@ -2076,527 +2076,60 @@ %09// -The extra steps should not add too much of a performance regression, since they do not have to be sorted%0A%09%09chai.assert.isAtMost(%0A%09%09%09timeXPath('(/child::*/child::*/child::*/child::*/child::*) =%3E count()', document),%0A%09%09%09timeWithoutExtraSteps * 1.3);%0A%09%7D);%0A%0A%09it('Saves variable results', function () %7B%0A%09%09this.timeout(10000);%0A%09%09const timeWithoutExtraSteps = timeXPath('(/descendant::*) =%3E count() %3E 10', document);%0A%09%09// The extra steps should not add too much of a performance regression, since they do not have to be sorted +Variables should only be evaluated once, not n times %0A%09%09c @@ -2217,16 +2217,31 @@ c + $c + + $c + $c + $c + $c', do @@ -2280,11 +2280,9 @@ s * -1.3 +2 );%0A%09
dfffdc4f88ed67c4dc06867cd147197b4888964f
Refactor preferences test.
test/tests/menu/negative/preferences.js
test/tests/menu/negative/preferences.js
'use strict'; const { Application } = require('spectron'); const { assert } = require('chai'); const APP_PATH = './dist/Negative-darwin-x64/Negative.app/Contents/MacOS/Negative'; const TIPS_ID = '#shouldShowTips'; describe('Negative > Preferences', function () { const app = new Application({ path: APP_PATH, env: { ELECTRON_ENABLE_LOGGING: true, ELECTRON_ENABLE_STACK_DUMPING: true, NEGATIVE_IGNORE_WINDOW_SETTINGS: true, NEGATIVE_SKIP_RESET_DIALOG: true, NODE_ENV: 'development' } }); this.timeout(60000); beforeEach(() => { return app.start(); }); afterEach(() => { if (app && app.isRunning()) { return app.stop(); } }); it('Should open', () => { return app.electron.ipcRenderer.send('test-preferences') .then(() => app.client.getWindowCount()) .then((count) => assert.strictEqual(count, 2)); }); it('Should toggle tips', () => { let windowHandles, originalIsChecked; // Focus the preferences window with `client.window` return app.electron.ipcRenderer.send('test-preferences') .then(() => app.client.windowHandles()) .then((handles) => { windowHandles = handles.value; app.client.window(windowHandles[1]) }) .then(() => { return app.client.selectorExecute(TIPS_ID, (elements) => { return elements[0].checked; }); }) .then((isChecked) => { originalIsChecked = isChecked; if (!isChecked) { return app.client.leftClick(TIPS_ID); } }) .then(() => app.client.window(windowHandles[0])) .then(() => { return app.client.selectorExecute('//body', (elements) => { return elements[0].classList.contains('no-tips'); }) }) .then((hasNoTipsClass) => assert.isFalse(hasNoTipsClass)) .then(() => app.client.window(windowHandles[1])) .then(() => app.client.leftClick(TIPS_ID)) .then(() => app.client.window(windowHandles[0])) .then(() => { return app.client.selectorExecute('//body', (elements) => { return elements[0].classList.contains('no-tips'); }) }) .then((hasNoTipsClass) => assert.isTrue(hasNoTipsClass)); }); // @TODO - Close should be tested here, but because it uses // `performSelector`, it cannot be properly tested until // Spectron supports testing menu item functionality. it('Close'); });
JavaScript
0
@@ -1150,16 +1150,59 @@ ue;%0A%09%09%09%09 +// Focus the Preferences window%0A%09%09%09%09return app.clie @@ -1228,16 +1228,17 @@ dles%5B1%5D) +; %0A%09%09%09%7D)%0A%09 @@ -1245,32 +1245,70 @@ %09%09.then(() =%3E %7B%0A +%09%09%09%09// Get %22Show tips%22 checkbox value%0A %09%09%09%09return app.c @@ -1393,17 +1393,16 @@ ;%0A%09%09%09%09%7D) -; %0A%09%09%09%7D)%0A%09 @@ -1434,120 +1434,129 @@ %09%09%09%09 -originalIsChecked = isChecked;%0A%09%09%09%09%0A%09%09%09%09if (!isChecked) %7B%0A%09%09%09%09%09return app.client.leftClick(TIPS_ID +return assert.isTrue(isChecked, '%22Show tips%22 checkbox should default to checked.' );%0A%09%09%09 -%09 %7D +) %0A%09%09%09 -%7D) +// Focus the Negative window %0A%09%09%09 @@ -1613,32 +1613,97 @@ %09%09.then(() =%3E %7B%0A +%09%09%09%09// Get the class that is toggled by the %22Show tips%22 checkbox%0A %09%09%09%09return app.c @@ -1803,32 +1803,33 @@ o-tips');%0A%09%09%09%09%7D) +; %0A%09%09%09%7D)%0A%09%09%09.then( @@ -1877,16 +1877,100 @@ ipsClass +, 'The body element should not have the .no-tips class when %22Show tips%22 is checked.' ))%0A%09%09%09.t @@ -2248,32 +2248,33 @@ o-tips');%0A%09%09%09%09%7D) +; %0A%09%09%09%7D)%0A%09%09%09.then( @@ -2321,16 +2321,96 @@ ipsClass +, 'The body element should have the .no-tips class when %22Show tips%22 is checked.' ));%0A%09%7D);
153ca55d94d810fcf1d0480b2085b65777d0eb33
fix SelectedFilters icon positioning issue on firefox
packages/web/src/styles/Button.js
packages/web/src/styles/Button.js
import { css } from 'emotion'; import styled from 'react-emotion'; import darken from 'polished/lib/color/darken'; const filters = css` margin: 0 -3px; max-width: 100%; a { margin: 2px 3px; padding: 5px 8px; font-size: 0.85rem; position: relative; span:first-child { max-width: 360px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-right: 26px; } span:last-child { display: flex; height: 100%; right: 8px; position: absolute; align-items: center; border-left: 1px solid #fff; padding-left: 8px; margin-left: 8px; } &:hover, &:focus { span:first-child { text-decoration: line-through; } } } `; const pagination = css` margin: 10px -3px; max-width: 100%; text-align: center; a { margin: 0 3px; } `; const toggleButtons = css` margin: 0 -3px; max-width: 100%; a { margin: 0 3px; } `; const numberBoxContainer = css` margin: 0 -5px; a { margin: 5px; } span { margin: 0 5px; } `; const primary = props => css` background-color: ${props.theme.primaryColor}; color: ${props.theme.primaryTextColor}; &:hover, &:focus { background-color: ${darken(0.1, props.theme.primaryColor)}; } `; const large = () => css` min-height: 40px; padding: 10px 20px; `; const disabled = css` background-color: #fafafa; color: #ccc cursor: not-allowed; &:hover, &:focus { background-color: #fafafa; } `; const Button = styled('a')` display: inline-flex; justify-content: center; align-items: center; border-radius: 3px; min-height: 30px; word-wrap: break-word; padding: 5px 12px; line-height: 1.2rem; background-color: #eee; color: #424242; cursor: pointer; user-select: none; transition: all 0.3s ease; &:hover, &:focus { background-color: #ccc; } ${props => (props.primary ? primary : null)}; ${props => (props.disabled ? disabled : null)}; ${props => props.large && large}; `; export { pagination, filters, toggleButtons, numberBoxContainer }; export default Button;
JavaScript
0
@@ -453,16 +453,27 @@ : 100%25;%0A +%09%09%09top: 0;%0A %09%09%09right
e0cae45bee83ad36c77124e2eec60bc8cfbc552f
make attachment funcs available in public API
packages/xod-project/src/index.js
packages/xod-project/src/index.js
export * from './project'; export { createPatch, duplicatePatch, getPatchPath, setPatchPath, getPatchDescription, setPatchDescription, getPatchAttachments, setPatchAttachments, hasImpl, getImpl, setImpl, removeImpl, nodeIdEquals, listNodes, getNodeById, getNodeByIdUnsafe, getPinByKey, getPinByKeyUnsafe, listPins, listInputPins, listOutputPins, isTerminalPatch, listLinks, linkIdEquals, getLinkById, getLinkByIdUnsafe, listLinksByNode, listLinksByPin, validateLink, assocLink, dissocLink, upsertLinks, omitLinks, assocNode, dissocNode, upsertNodes, canBindToOutputs, toposortNodes, getTopology, listComments, getCommentById, getCommentByIdUnsafe, assocComment, dissocComment, upsertComments, removeDebugNodes, getTopologyMap, applyNodeIdMap, resolveNodeTypesInPatch, listLibraryNamesUsedInPatch, computeVariadicPins, listVariadicValuePins, listVariadicAccPins, listVariadicSharedPins, validatePatchForVariadics, getArityStepFromPatch, isVariadicPatch, isAbstractPatch, validateAbstractPatch, isDeprecatedPatch, getDeprecationReason, isUtilityPatch, } from './patch'; export * from './node'; export * from './comment'; export { createPin, getPinType, getPinDirection, getPinKey, getPinLabel, getPinDefaultValue, getPinDescription, getPinOrder, isInputPin, isOutputPin, isTerminalPin, normalizePinLabels, isPinBindable, isPulsePin, } from './pin'; export * from './link'; export * from './constants'; export * from './optionalFieldsUtils'; export * from './utils'; export * from './func-tools'; export * from './types'; export { default as flatten } from './flatten'; export { default as extractBoundInputsToConstNodes, } from './extractBoundInputsToConstNodes'; export * from './patchPathUtils'; export * from './versionUtils'; export * from './xodball'; export * from './typeDeduction';
JavaScript
0
@@ -1185,16 +1185,166 @@ patch';%0A +export %7B%0A getFilename as getAttachmentFilename,%0A getContent as getAttachmentContent,%0A getEncoding as getAttachmentEncoding,%0A%7D from './attachment';%0A export *
61ba8a893703ef2beaadff716f6e3b491def6a5e
add next prev classes for dynamic container on init
src/responsive-carousel.dynamic-containers.js
src/responsive-carousel.dynamic-containers.js
/* * responsive-carousel dynamic containers extension * https://github.com/filamentgroup/responsive-carousel * * Copyright (c) 2012 Filament Group, Inc. * Licensed under the MIT, GPL licenses. */ (function($) { var pluginName = "carousel", initSelector = "." + pluginName, itemClass = pluginName + "-item", activeClass = pluginName + "-active", rowAttr = "data-" + pluginName + "-slide", $win = $( window ), dynamicContainers = { _assessContainers: function(){ var $self = $( this ), $rows = $self.find( "[" + rowAttr + "]" ), $activeItem = $rows.filter( "." + activeClass ).children( 0 ), $kids = $rows.children(), $nav = $self.find( "." + pluginName + "-nav" ), sets = []; if( !$rows.length ){ $kids = $( this ).find( "." + itemClass ); } else{ $kids.appendTo( $self ); $rows.remove(); } $kids .removeClass( itemClass + " " + activeClass ) .each(function(){ var prev = $( this ).prev(); if( !prev.length || $( this ).offset().top !== prev.offset().top ){ sets.push([]); } sets[ sets.length -1 ].push( $( this ) ); }); for( var i = 0; i < sets.length; i++ ){ var $row = $( "<div " + rowAttr + "></div>" ); for( var j = 0; j < sets[ i ].length; j++ ){ $row.append( sets[ i ][ j ] ); } $row.insertBefore( $nav ); } $self[ pluginName ]( "update" ) // initialize pagination .trigger( "goto." + pluginName ); $self.find( "." + itemClass ).eq( 0 ).addClass( activeClass ); }, _dynamicContainerEvents: function(){ var $self = $( this ), win_w = $win.width(), win_h = $win.height(), timeout; // on init $self[ pluginName ]( "_assessContainers" ); // and on resize $win.on( "resize", function( e ){ // IE wants to constantly run resize for some reason // Let’s make sure it is actually a resize event var win_w_new = $win.width(), win_h_new = $win.height(); if( win_w !== win_w_new || win_h !== win_h_new ) { // timer shennanigans clearTimeout(timeout); timeout = setTimeout( function(){ $self[ pluginName ]( "_assessContainers" ); }, 200 ); // Update the width and height win_w = win_w_new; win_h = win_h_new; } }); } }; // add methods $.extend( $.fn[ pluginName ].prototype, dynamicContainers ); // DOM-ready auto-init $( document ).on( "create." + pluginName, initSelector, function(){ $( this )[ pluginName ]( "_dynamicContainerEvents" ); } ); }(jQuery));
JavaScript
0
@@ -1452,16 +1452,61 @@ date%22 )%0A +%09%09%09%09%09%5B pluginName %5D( %22_addNextPrevClasses%22 )%0A %09%09%09%09%09//
0294ed455f1be4b931941f91b92aa12c1a4442d2
Check if the image exists to show the resize slider
src/sunstone/public/app/utils/disks-resize.js
src/sunstone/public/app/utils/disks-resize.js
/* -------------------------------------------------------------------------- */ /* Copyright 2002-2015, OpenNebula Project, OpenNebula Systems */ /* */ /* Licensed under the Apache License, Version 2.0 (the "License"); you may */ /* not use this file except in compliance with the License. You may obtain */ /* a copy of the License at */ /* */ /* http://www.apache.org/licenses/LICENSE-2.0 */ /* */ /* Unless required by applicable law or agreed to in writing, software */ /* distributed under the License is distributed on an "AS IS" BASIS, */ /* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */ /* See the License for the specific language governing permissions and */ /* limitations under the License. */ /* -------------------------------------------------------------------------- */ define(function(require){ var Locale = require('utils/locale'); var Config = require('sunstone-config'); var OpenNebula = require('opennebula'); var OpenNebulaImage = require('opennebula/image'); var UserInputs = require('utils/user-inputs'); var WizardFields = require('utils/wizard-fields'); var DisksResizeTemplate = require('hbs!./disks-resize/html'); return { 'insert': _insert, 'retrieve': _retrieve }; function _insert(template_json, disksContext) { var template_disk = template_json.VMTEMPLATE.TEMPLATE.DISK var disks = [] if ($.isArray(template_disk)) { disks = template_disk } else if (!$.isEmptyObject(template_disk)) { disks = [template_disk] } if (disks.length > 0) { disksContext.html(DisksResizeTemplate()); OpenNebula.Template.show({ data : { id: template_json.VMTEMPLATE.ID, extended: true }, success: function(request, extendedTemplateJSON) { var extendedTemplateDisk = extendedTemplateJSON.VMTEMPLATE.TEMPLATE.DISK; var extendedDisks = [] if ($.isArray(extendedTemplateDisk)) { extendedDisks = extendedTemplateDisk } else if (!$.isEmptyObject(extendedTemplateDisk)) { extendedDisks = [extendedTemplateDisk] } var disk_cost = template_json.VMTEMPLATE.TEMPLATE.DISK_COST; if (disk_cost == undefined) { disk_cost = Config.onedConf.DEFAULT_COST.DISK_COST; } if (disk_cost != 0 && Config.isFeatureEnabled("showback")) { $(".provision_create_template_disk_cost_div", disksContext).show(); disksContext.on("input", '.uinput-slider', function(){ var cost = 0; $('.uinput-slider-val', disksContext).each(function(){ if ($(this).val() > 0) { cost += $(this).val() * 1024 * disk_cost; } var diskContext = $(this).closest(".diskContainer"); cost += diskContext.data('disk_snapshot_total_cost'); }) $(".cost_value", disksContext).html(cost.toFixed(2)); }); } else { $(".provision_create_template_disk_cost_div", disksContext).hide(); } var diskContext; $(".disksContainer", disksContext).html(""); $.each(extendedDisks, function(disk_id, disk) { diskContext = $( '<div class="row diskContainer">'+ '<div class="small-12 columns">'+ '<label></label>'+ '</div>'+ '<div class="large-12 columns diskSlider">' + '</div>' + '</div>').appendTo($(".disksContainer", disksContext)); diskContext.data('template_disk', disks[disk_id]); var disk_snapshot_total_size = 0; if (disk.DISK_SNAPSHOT_TOTAL_SIZE != undefined) { disk_snapshot_total_size = parseInt(disk.DISK_SNAPSHOT_TOTAL_SIZE); } diskContext.data('disk_snapshot_total_size', disk_snapshot_total_size); diskContext.data('disk_snapshot_total_cost', disk_snapshot_total_size * disk_cost); var label = disk.IMAGE ? disk.IMAGE : Locale.tr("Volatile Disk"); $("label", diskContext).text(Locale.tr("DISK") + ' ' + disk_id + ': ' + label); var disabled = ( (disk.PERSISTENT && disk.PERSISTENT.toUpperCase() == "YES") || (disk.TYPE && OpenNebulaImage.TYPES[disk.TYPE] == OpenNebulaImage.TYPES.CDROM) ); var attr; if (disabled){ attr = UserInputs.parse("SIZE","O|fixed|"+label+"||"+disk.SIZE); } else { // Range from original size to size + 500GB var min = parseInt(disk.SIZE); var max = min + 512000; attr = UserInputs.parse( "SIZE", "O|range|"+label+"|"+min+".."+max+"|"+min); } UserInputs.insertAttributeInputMB(attr, $(".diskSlider", diskContext)); }) } }) } else { disksContext.html(""); } } function _retrieve(context) { var disks = []; var disk; $(".diskContainer", context).each(function(){ if ($(this).data("template_disk")) { disk = $(this).data("template_disk"); var fields = WizardFields.retrieve(this); if (fields.SIZE != undefined){ disk['SIZE'] = fields.SIZE; } } if (disk) { disks.push(disk); } }); return disks; } });
JavaScript
0.000001
@@ -4857,16 +4857,48 @@ attr;%0A%0A +%0A if (disk.SIZE) %7B%0A @@ -4912,24 +4912,26 @@ (disabled)%7B%0A + @@ -5001,32 +5001,34 @@ E);%0A + %7D else %7B%0A @@ -5012,32 +5012,34 @@ %7D else %7B%0A + // @@ -5080,16 +5080,18 @@ + 500GB%0A + @@ -5137,24 +5137,26 @@ + var max = mi @@ -5168,16 +5168,18 @@ 12000;%0A%0A + @@ -5229,16 +5229,18 @@ + + %22SIZE%22,%0A @@ -5235,16 +5235,18 @@ %22SIZE%22,%0A + @@ -5297,16 +5297,18 @@ %22+min);%0A + @@ -5305,33 +5305,49 @@ %7D%0A -%0A + %0A User @@ -5410,24 +5410,38 @@ kContext));%0A + %7D%0A %7D)
409feecf14a5cc0c4ddb4a1dd9173092b48cae1a
Add a few more tests
tests/unit/helpers/weather-icon-test.js
tests/unit/helpers/weather-icon-test.js
import { weatherIcon } from 'ember-cli-weather-icons/helpers/weather-icon'; module('WeatherIconHelper'); // Replace this with your real tests. test('it works', function() { var result = weatherIcon('sunny'); equal(result.toString(), '<i class="wi wi-sunny"></i>'); });
JavaScript
0.000001
@@ -106,59 +106,234 @@ );%0A%0A -// Replace this with your real tests.%0Atest('it work +test('it returns an icon with the correct sunny class', function() %7B%0A var result = weatherIcon('sunny');%0A equal(result.toString(), '%3Ci class=%22wi wi-sunny%22%3E%3C/i%3E');%0A%7D);%0A%0Atest('it returns an icon with the correct moon-full clas s', @@ -365,37 +365,41 @@ = weatherIcon(' -sunny +moon-full ');%0A equal(resu @@ -422,35 +422,39 @@ %3Ci class=%22wi wi- -sunny +moon-full %22%3E%3C/i%3E');%0A%7D);%0A
34bafdac249db81846af9a77967b168211ef94ce
Fix test after breaking it with the changes done to the job template
test/test-sample-folder-integrity.js
test/test-sample-folder-integrity.js
var assert = require ('assert'), path = require ('path'), fs = require ('fs'); describe ('sample folder integrity', function(){ var sampleFolder = path.join(process.cwd(), '/samples'); describe ('scaffold folder', function(){ describe ('config file', function(){ var dashboardFile = path.join(sampleFolder, 'project', 'config', 'atlasboard.json'); it('should be valid json', function(done){ JSON.parse(fs.readFileSync(dashboardFile)); done(); }); it('should have live logging disabled by default', function(done){ assert.equal(false, JSON.parse(fs.readFileSync(dashboardFile))["live-logging"].enabled); done(); }); }); describe ('dashboard file', function(){ var dashboardFile = path.join(sampleFolder, 'dashboard', 'default.json'); it('should be valid json', function(done){ JSON.parse(fs.readFileSync(dashboardFile)); done(); }); }); describe ('job file', function(){ var jobFile = path.join(sampleFolder, 'job', 'default.js'); it('should be valid executable', function(done){ var job = require(jobFile); job({},{}, function(err, data){ done(); }); }); }); }); describe ('project folder', function(){ var projectFolder = path.join(sampleFolder, 'project'); describe ('dashboard file', function(){ var dashboardFile = path.join(projectFolder, 'packages', 'demo', 'dashboards', 'myfirst_dashboard.json'); it('should be valid json', function(done){ JSON.parse(fs.readFileSync(dashboardFile)); done(); }); }); describe ('global config file', function(){ var globalConfigFile = path.join(projectFolder, 'config', 'dashboard_common.json'); it('should be valid json', function(done){ JSON.parse(fs.readFileSync(globalConfigFile)); done(); }); }); }); });
JavaScript
0.000001
@@ -1155,24 +1155,25 @@ bFile);%0A +%0A job(%7B%7D,%7B @@ -1168,39 +1168,345 @@ -job(%7B%7D,%7B%7D, function(err, data)%7B +// the default job uses easyRequest as example, so let's mock it%0A var mockedDependencies = %7B%0A easyRequest : %7B%0A HTML : function (options, cb) %7B%0A cb(null, 'hi!');%0A %7D%0A %7D%0A %7D;%0A%0A job(%7B%7D, mockedDependencies, function(err, data)%7B%0A assert.equal('hi!', data.html); %0A
1cb88be2d20aa34df8d5fbccccd33a89d2071477
Fix unit tests for composeWindow.getCurrentLang
test/units/ad/compose_window.test.js
test/units/ad/compose_window.test.js
/** * @jest-environment ./test/helpers/jest-thunderbird-environment.cjs */ import { ComposeWindow } from "./../../../addon/ad/compose_window"; import { LoggerStub } from './../../../addon/lib/logger_stub.js'; import { jest } from '@jest/globals' describe('ComposeWindow', () => { var factory = function () { return new ComposeWindow({ ad: { window: { id: 'stubbed-window-id' }, addEventListener: jest.fn() }, logger: LoggerStub, logo_url: 'stubbed-logo-url', notification_time: 4000 }); }; var eventEmitterFactory = function () { return { addListener: jest.fn(), addEventListener: jest.fn(), removeListener: jest.fn(), removeEventListener: jest.fn() } } beforeEach(() => { browser.compose_ext = { onLanguageChange: eventEmitterFactory(), onRecipientsChange: eventEmitterFactory(), showNotification: jest.fn(), setSpellCheckerLanguage: jest.fn(), canSpellCheck: jest.fn().mockResolvedValue(true) }; browser.compose = { onActiveDictionariesChanged: eventEmitterFactory() } browser.windows.onFocusChanged = eventEmitterFactory(); browser.windows.get = jest.fn().mockResolvedValue({ tabs: [{ id: 'stubbed-tab-id' }] }) }) describe('canManageWindow', () => { it("detects matching window locations", () => { var matching_urls = [ 'chrome://whatever/messengercompose.xul', 'chrome://whatever/messengercompose.xhtml' ] matching_urls.forEach((url) => { var window_stub = { document: { location: url } }; expect(ComposeWindow.canManageWindow(window_stub)).toBe(true); }) }); it('rejects other locations', () => { var rejected_urls = [ 'chrome://messenger/content/messenger.xhmtl', 'chrome://mozapps/content/extensions/aboutaddons.html' ]; rejected_urls.forEach((url) => { var window_stub = { document: { location: url } }; expect(ComposeWindow.canManageWindow(window_stub)).toBe(false); }) }); }); describe('setListeners', () => { it('sets listeners on compose_ext', () => { var compose_window = factory(); compose_window.setListeners(); expect(browser.compose.onActiveDictionariesChanged.addListener).toHaveBeenCalled() expect(browser.compose_ext.onRecipientsChange.addListener).toHaveBeenCalled() expect(browser.windows.onFocusChanged.addListener).toHaveBeenCalled(); }); }); describe('getCurrentLang', () => { it('returns what compose_ext returns', async () => { var compose_window = factory(); browser.compose_ext.getCurrentLanguage = jest.fn().mockReturnValue('ca') expect(await compose_window.getCurrentLang()).toBe('ca') expect(browser.compose_ext.getCurrentLanguage).toHaveBeenCalledWith('stubbed-tab-id') }) }); describe('recipients', () => { describe('when recipients is a single string', () => { it('returns the recipients from that tab', async () => { var details = { 'to': 'Joe' } var compose_window = factory(); browser.compose.getComposeDetails = jest.fn().mockResolvedValue(details); expect(compose_window.recipients()).resolves.toStrictEqual(['Joe']); }); }) describe('when recipients is an array of strings', () => { it('returns the recipients from that tab', async () => { var details = { 'to': ['Joe'] } var compose_window = factory(); browser.compose.getComposeDetails = jest.fn().mockResolvedValue(details); expect(compose_window.recipients()).resolves.toStrictEqual(['Joe']); }); }) describe('when recipients is an array of strings that needs to be normalized', () => { it('returns the recipients normalized', async () => { var details = { 'to': ['Joe <[email protected]>', 'Big band! <[email protected]'] } var compose_window = factory(); browser.compose.getComposeDetails = jest.fn().mockResolvedValue(details); expect(compose_window.recipients()).resolves.toStrictEqual( ['[email protected]', '[email protected]']); }); }) describe('when recipients is a compose recipients object', () => { //var composeRecipientsFactory = function() it('returns the recipients from that tab', async () => { var composeDetails = { to: [ { type: 'contact', id: 'contact-recipient-id' }, { type: 'mailingList', id: 'mailing-list-recipient-id' } ] } browser.compose.getComposeDetails = jest.fn().mockResolvedValue(composeDetails); browser.contacts.get = jest.fn().mockResolvedValue({ properties: { PrimaryEmail: '[email protected]' } }) browser.mailingLists.get = jest.fn().mockResolvedValue({ properties: { name: '[email protected]' } }); var compose_window = factory(); expect(await compose_window.recipients()).toStrictEqual( ["[email protected]", "[email protected]"]); expect(browser.compose.getComposeDetails).toHaveBeenCalledWith('stubbed-tab-id'); expect(browser.contacts.get).toHaveBeenCalledWith('contact-recipient-id'); expect(browser.mailingLists.get).toHaveBeenCalledWith('mailing-list-recipient-id') }); }) }); describe('changeLabel', () => { it('forwards to compose_ext', async () => { var compose_window = factory(); await compose_window.changeLabel('message') expect(browser.compose_ext.showNotification).toHaveBeenCalledWith( 'stubbed-tab-id', 'message', { logo_url: 'stubbed-logo-url', notification_time: 4000 } ) }) }); describe('changeLanguage', () => { it('sets spellchecker language via compose_ext', async () => { var compose_window = factory(); await compose_window.changeLanguage('en') expect(browser.compose_ext.setSpellCheckerLanguage).toHaveBeenCalledWith('stubbed-tab-id', 'en') }) }) describe('canSpellCheck', () => { it('returns true when spellchecker is available', async () => { var compose_window = factory(); expect(await compose_window.canSpellCheck()).toBe(true) expect(browser.compose_ext.canSpellCheck).toHaveBeenCalledWith('stubbed-tab-id') }) }) })
JavaScript
0.000001
@@ -2577,20 +2577,16 @@ compose -_ext returns @@ -2594,32 +2594,32 @@ , async () =%3E %7B%0A + var compos @@ -2661,39 +2661,38 @@ .compose -_ext.getCurrentLanguage +.getActiveDictionaries = jest. @@ -2712,20 +2712,37 @@ rnValue( -'ca' +%7Bca: true, en: false%7D )%0A%0A @@ -2831,31 +2831,30 @@ pose -_ext.getCurrentLanguage +.getActiveDictionaries ).to
3d2f554be9667d888b808ca4a674b28fc0b52dca
Use early return pattern
lib/cartodb/cache/named_map_provider_cache.js
lib/cartodb/cache/named_map_provider_cache.js
'use strict'; var _ = require('underscore'); var dot = require('dot'); var NamedMapMapConfigProvider = require('../models/mapconfig/provider/named-map-provider'); var templateName = require('../backends/template_maps').templateName; var LruCache = require("lru-cache"); const TEN_MINUTES_IN_MILLISECONDS = 1000 * 60 * 10; function NamedMapProviderCache( templateMaps, pgConnection, metadataBackend, userLimitsBackend, mapConfigAdapter, affectedTablesCache ) { this.templateMaps = templateMaps; this.pgConnection = pgConnection; this.metadataBackend = metadataBackend; this.userLimitsBackend = userLimitsBackend; this.mapConfigAdapter = mapConfigAdapter; this.affectedTablesCache = affectedTablesCache; this.providerCache = new LruCache({ max: 2000, maxAge: TEN_MINUTES_IN_MILLISECONDS }); } module.exports = NamedMapProviderCache; NamedMapProviderCache.prototype.get = function(user, templateId, config, authToken, params, callback) { var namedMapKey = createNamedMapKey(user, templateId); var namedMapProviders = this.providerCache.get(namedMapKey) || {}; var providerKey = createProviderKey(config, authToken, params); if (!namedMapProviders.hasOwnProperty(providerKey)) { namedMapProviders[providerKey] = new NamedMapMapConfigProvider( this.templateMaps, this.pgConnection, this.metadataBackend, this.userLimitsBackend, this.mapConfigAdapter, this.affectedTablesCache, user, templateId, config, authToken, params ); this.providerCache.set(namedMapKey, namedMapProviders); // early exit, if provider did not exist we just return it return callback(null, namedMapProviders[providerKey]); } var namedMapProvider = namedMapProviders[providerKey]; return callback(null, namedMapProvider); }; NamedMapProviderCache.prototype.invalidate = function(user, templateId) { this.providerCache.del(createNamedMapKey(user, templateId)); }; function createNamedMapKey(user, templateId) { return user + ':' + templateName(templateId); } var providerKey = '{{=it.authToken}}:{{=it.configHash}}:{{=it.format}}:{{=it.layer}}:{{=it.scale_factor}}'; var providerKeyTpl = dot.template(providerKey); function createProviderKey(config, authToken, params) { var tplValues = _.defaults({}, params, { authToken: authToken || '', configHash: NamedMapMapConfigProvider.configHash(config), layer: '', format: '', scale_factor: 1 }); return providerKeyTpl(tplValues); }
JavaScript
0.000002
@@ -1117,17 +1117,16 @@ %7C%7C %7B%7D;%0A -%0A var @@ -1189,16 +1189,17 @@ s);%0A +%0A if ( !nam @@ -1198,9 +1198,8 @@ if ( -! name @@ -1243,24 +1243,90 @@ Key)) %7B%0A + return callback(null, namedMapProviders%5BproviderKey%5D);%0A %7D%0A%0A namedMap @@ -1385,28 +1385,24 @@ er(%0A - this.templat @@ -1408,20 +1408,16 @@ teMaps,%0A - @@ -1439,28 +1439,24 @@ on,%0A - this.metadat @@ -1457,36 +1457,32 @@ etadataBackend,%0A - this.use @@ -1501,28 +1501,24 @@ nd,%0A - - this.mapConf @@ -1524,28 +1524,24 @@ figAdapter,%0A - this @@ -1574,22 +1574,14 @@ - - user,%0A - @@ -1600,28 +1600,24 @@ Id,%0A - config,%0A @@ -1616,28 +1616,24 @@ ig,%0A - - authToken,%0A @@ -1639,20 +1639,16 @@ - params%0A @@ -1654,19 +1654,12 @@ - - );%0A - +%0A @@ -1723,205 +1723,8 @@ - // early exit, if provider did not exist we just return it%0A return callback(null, namedMapProviders%5BproviderKey%5D);%0A %7D%0A%0A var namedMapProvider = namedMapProviders%5BproviderKey%5D;%0A%0A retu @@ -1757,16 +1757,30 @@ Provider +s%5BproviderKey%5D );%0A%7D;%0A%0AN
324e374758ef11bece4cc4cdadc91240c149596b
Fix for env file
lib/generators/templates/environments/test.js
lib/generators/templates/environments/test.js
//= require handlebars //= require ember //= require ember-data.prod
JavaScript
0.000001
@@ -60,10 +60,5 @@ data -.prod %0A
46f1b3b4bc2bd271601d987ee21b75a38f645312
Send processing status to client on db list request
utils/database.js
utils/database.js
var Promise = require('bluebird'), MongoClient = require('mongodb').MongoClient, dbServer = 'mongodb://localhost:27017/', archiver = require('archiver'), fs = require('fs'), async = require('async'), collUtils = require('./collection'), db = {}; module.exports = { list : List, setDb : SetDB, getDb : GetDB, connectAll : ConnectAll, connect : Connect, dbInfo : DbInfo, schemaVerified : SchemaVerified, validDB : ValidDB, initDB : InitDB, collectionInfo : CollectionInfo, collectionSchemaVerified : CollectionSchemaVerified, getDummyObj : GetDummyObj, compress : Compress }; function CollectionInfo(database,col_name){ return new Promise(function(resolve,reject){ db[database].collection(col_name).count(function(err,count){ resolve(count) }); }); } function CollectionSchemaVerified(database,col_name){ return new Promise(function(resolve,reject){ db[database].collection('__schema').findOne({'collection' : col_name},function(err,result){ if(err || !result) { resolve(false); return } resolve(true); }); }); } function List() { var databases = [], formatted = [], len = [], currDb, blackList = ['admin','test'], currObj = {}; return new Promise(function(resolve,reject){ db['test'].admin().listDatabases().then(function(data){ databases = data.databases || []; len = databases.length; while(len--) { currDb = databases[len].name; if(blackList.indexOf(currDb) >= 0){ continue; } currObj = {'database' : databases[len].name,'stats' : {}}; formatted.push(currObj); currObj = {}; } resolve(formatted); }); }); } function ConnectAll() { var len, currdbName; List() .then(function(databases){ len = databases.length; while(len--) { currdbName = databases[len].database; if(db[currdbName]) { continue; } Connect(currdbName); } }) .catch(function(err){ console.log('Error connecting multi database') console.log(err) }); } function Connect(database){ return new Promise(function(resolve,reject){ var url = dbServer + database; MongoClient.connect(url, function(err, connected) { console.log("Connected to the database",database); SetDB(database,connected); resolve(); }); }); } function SchemaVerified(database) { var verified = true; return new Promise(function(resolve,reject){ collUtils.list(database) .then(function(dbCols){ async.series(dbCols.map(function(currCol){ return function(cb) { collUtils.verified(database,currCol.s.name) .then(function(colVerified){ verified = verified && colVerified; cb(); }); } }),function(){ resolve(verified); }); }); }); } function DbInfo(database){ return new Promise(function(resolve,reject){ db[database].stats(function(err,data){ resolve({size : (data.dataSize/(1024 * 1024)), collections : data.collections}); }); }); } function SetDB(database_name , database) { db[database_name] = database; } function GetDB(database){ if(database) { return db[database]; } return db; } function ValidDB(database){ if(db[database]) { return true; } return false; } function InitDB(database) { return new Promise(function(resolve,reject){ db[database].collection('__schema').insertOne({},function(err,result){ if(err){ reject(err); } resolve(); }); }); } function GetDummyObj(fields){ var obj = {}, len = fields.length, defaults = { 'String' : 'demo', 'Number' : 1, 'Date' : new Date(), 'Boolean' : true, 'Array' : [], 'Object' : {} }; while(len--) { obj[fields[len].key] = defaults[fields[len].type]; } return obj; } function Compress(database){ return new Promise(function(resolve,reject){ var targetFile = database + '.zip', output = fs.createWriteStream(targetFile), cwd = 'dump/' + database, archive = archiver('zip'); output.on('close', function () { console.log('Done converting zip file for database',database); resolve(); }); archive.on('error', function(err){ reject(err); }); archive.pipe(output); archive.bulk([ { expand: true, cwd: cwd, src: ['**'], dest: database} ]); archive.finalize(); }); }
JavaScript
0
@@ -1665,16 +1665,36 @@ ts' : %7B%7D +,'processing' : true %7D;%0A
7650aceeb4c5217e8524f63a5d6c0919079ac17d
Fix to issue 369.
src/client/features/search/index.js
src/client/features/search/index.js
const React = require('react'); const h = require('react-hyperscript'); const Link = require('react-router-dom').Link; const Loader = require('react-loader'); const queryString = require('query-string'); const _ = require('lodash'); const classNames = require('classnames'); const Icon = require('../../common/components').Icon; const { ServerAPI } = require('../../services'); class Search extends React.Component { constructor(props) { super(props); const query = queryString.parse(props.location.search); this.state = { query: _.assign({ q: '', gt: 0, lt: 250, type: 'Pathway', datasource: [] }, query), searchResults: [], loading: false, showFilters: false, dataSources: [] }; ServerAPI.datasources() .then(result => { this.setState({ dataSources: Object.values(result) }); }); } getSearchResult() { const state = this.state; const query = state.query; if (query.q !== '') { this.setState({ loading: true }); ServerAPI.querySearch(query) .then(searchResults => { this.setState({ searchResults: searchResults, loading: false }); }); } } componentDidMount() { this.getSearchResult(); } onSearchValueChange(e) { // if the user presses enter, submit the query if (e.which && e.which === 13) { this.submitSearchQuery(e); } else { const newQueryState = _.assign({}, this.state.query); newQueryState.q = e.target.value; this.setState({ query: newQueryState }); } } setAndSubmitSearchQuery(query) { const state = this.state; if (!state.loading) { const newQueryState = _.assign({}, state.query, query); this.setState({ query: newQueryState }, () => this.submitSearchQuery()); } } submitSearchQuery() { const props = this.props; const state = this.state; const query = state.query; props.history.push({ pathname: '/search', search: queryString.stringify(query), state: {} }); this.getSearchResult(); } render() { const props = this.props; const state = this.state; let Example = props => h('span.search-example', { onClick: () => this.setAndSubmitSearchQuery({q: props.search}) }, props.search); const searchResults = state.searchResults.map(result => { const dsInfo = _.find(state.dataSources, ds => { return ds.uri === result.dataSource[0]; }); return h('div.search-item', [ h('div.search-item-icon',[ h('img', {src: dsInfo.iconUrl}) ]), h('div.search-item-content', [ h(Link, { to: { pathname: '/view', search: queryString.stringify({ uri: result.uri }) }, target: '_blank' }, [ h('h3.search-item-content-title', result.name || 'N/A'), ]), h('p.search-item-content-datasource', ` ${dsInfo.name}`), h('p.search-item-content-participants', `${result.numParticipants} Participants`) ]) ]); }); const searchTypeTabs = [ { name: 'Pathways', value: 'Pathway' }, // { name: 'Molecular Interactions', value: 'MolecularInteraction' }, // { name: 'Reactions', value: 'Control' }, // { name: 'Transcription/Translation', value: 'TemplateReactionRegulation' } ].map(searchType => { return h('div.search-option-item-container', [ h('div', { onClick: e => this.setAndSubmitSearchQuery({ type: searchType.value }), className: classNames('search-option-item', { 'search-option-item-disabled': state.loading }, { 'search-option-item-active': state.query.type === searchType.value }) }, [ h('a', searchType.name) ]) ]); }); const searchResultInfo = state.showFilters ? h('div.search-filters', [ h('select.search-datasource-filter', { value: state.query.datasource, onChange: e => this.setAndSubmitSearchQuery({ datasource: e.target.value }) }, [ h('option', { value: [] }, 'Any datasource')].concat( _.sortBy(state.dataSources, 'name').map(ds => h('option', { value: [ds.id] }, ds.name)) )), ]) : h('div.search-hit-counter', `${state.searchResults.length} result${state.searchResults.length === 1 ? '' : 's'}`); return h('div.search', [ h('div.search-header-container', [ h('div.search-header', [ h('div.search-branding', [ h('div.search-title', [ h('a', { className: 'search-pc-link', href: 'http://www.pathwaycommons.org/' } , [ h('i.search-logo') ]), ]), h('div.search-branding-descriptor', [ h('h2.search-pc-title', 'Pathway Commons'), h('h1.search-search-title', 'Search') ]) ]), h('div.search-searchbar-container', { ref: dom => this.searchBar = dom }, [ h('div.search-searchbar', [ h('input', { type: 'text', placeholder: 'Enter pathway name or gene names', value: state.query.q, onChange: e => this.onSearchValueChange(e), onKeyPress: e => this.onSearchValueChange(e) }), h('div.search-search-button', [ h('button', { onClick: e => this.submitSearchQuery(e) }, [ h(Icon, { icon: 'search' }) ]) ]) ]), h('div.search-suggestions', [ 'e.g. ', h(Example, {search: 'cell cycle'}), ', ', h(Example, {search: 'p53 MDM2'}), ', ', h(Example, {search: 'P04637'}) ]), h('div.search-tabs', searchTypeTabs.concat([ h('div', { className: classNames('search-option-item', 'search-option-item-tools', { 'search-option-item-tools-active': state.showFilters }), onClick: e => this.setState({ showFilters: !state.showFilters }) }, [ h('a', 'Tools') ]) ])) ]) ]) ]), h(Loader, { loaded: !state.loading, options: { left: '50%', color: '#16A085' } }, [ h('div.search-list-container', [ h('div.search-result-info', [searchResultInfo]), h('div.search-list', searchResults) ]) ]) ]); } } module.exports = Search;
JavaScript
0
@@ -917,16 +917,17 @@ %7D); + %0A %7D%0A%0A @@ -2460,24 +2460,109 @@ result =%3E %7B%0A + if(_.isEmpty(state.dataSources))%7B%0A return h('div');%0A %7D%0A else%7B%0A const @@ -3203,32 +3203,38 @@ %5D)%0A %5D);%0A + %7D%0A %7D);%0A%0A con
0515e5adc0a7635657e4cdb9334b308a0b8d72ba
Fix linter
packages/react-static/src/commands/create.js
packages/react-static/src/commands/create.js
import fs from 'fs-extra' import chalk from 'chalk' import path from 'path' import git from 'git-promise' import { execSync } from 'child_process' import inquirer from 'inquirer' import autoCompletePrompt from 'inquirer-autocomplete-prompt' import matchSorter from 'match-sorter' import downloadGitRepo from 'download-git-repo' import { promisify } from 'util' // import { ChalkColor, time, timeEnd } from '../utils' inquirer.registerPrompt('autocomplete', autoCompletePrompt) const typeLocal = 'Local Directory...' const typeGit = 'GIT Repository...' const typeExample = 'React Static Example' const examplesDir = path.resolve(__dirname, '../../libExamples') const examplesList = fs.readdirSync(examplesDir).filter(d => !d.startsWith('.')) export default (async function create({ name, template, isCLI }) { const isYarn = shouldUseYarn() const prompts = [] console.log('') const firstExamples = ['basic', 'blank'] const examples = [ ...firstExamples, ...examplesList.filter(d => !firstExamples.includes(d)), ] const exampleChoices = [...examples, typeLocal, typeGit] let templateType = typeExample // prompt if --name argument is not passed from CLI // warning: since name will be set as a function by commander by default // unless it's assigned as an argument from the CLI, we can't simply just // check for it's existence. if it's not been set by the CLI, we properly // set it to null for later conditional checks. if (isCLI && !name) { const answers = await inquirer.prompt({ type: 'input', name: 'name', message: 'What should we name this project?', default: 'my-static-site', }) name = answers.name } if (!name) { throw new Error( 'A project name is required. Please use options.name to define one.' ) } const dest = path.resolve(process.cwd(), name) if (fs.existsSync(dest)) { throw new Error( `Could not create project. Directory already exists at ${dest}!` ) } if (isCLI && !template) { const answers = await inquirer.prompt({ type: 'autocomplete', name: 'template', message: 'Select a template below...', source: async (answersSoFar, input) => !input ? exampleChoices : matchSorter(exampleChoices, input), }) template = answers.template } if (!template) { throw new Error( 'A project template is required. Please use options.template to define one.' ) } time(chalk.green(`=> [\u2713] Project "${name}" created`)) console.log('=> Creating new react-static project...') if (template === typeLocal) { templateType = typeLocal const { localDirectory } = await inquirer.prompt([ { type: 'input', name: 'localDirectory', message: `Enter an local directory's absolute location (~/Desktop/my-template)`, }, ]) template = localDirectory } if (template === typeGit) { templateType = typeGit const { githubRepoName } = await inquirer.prompt([ { type: 'input', name: 'githubRepoName', message: 'Enter a repository URL from GitHub, BitBucket, GitLab, or any other public repo. (https://github.com/ownerName/repoName.git)', }, ]) template = githubRepoName } console.log('') // GIT repositories if (templateType === typeGit) { if (template.startsWith('https://') || template.startsWith('git@')) { try { console.log(chalk.green(`Cloning Git template: ${template}`)) await git(`clone --recursive ${template} ${dest}`) } catch (err) { console.log(chalk.red(`Cloning Git template: ${template} failed!`)) throw err } } else if (template.startsWith('http://')) { // use download-git-repo to fetch remote repository const getGitHubRepo = promisify(downloadGitRepo) try { console.log(chalk.green(`Cloning Git template: ${template}`)) await getGitHubRepo(template, dest) } catch (err) { console.log(chalk.red(`Cloning Git template: ${template} failed!`)) throw err } } } else if (templateType === typeExample) { // React Static examples console.log(chalk.green(`Using React Static template: ${template}`)) try { await fs.copy( path.resolve(examplesDir, template), path.resolve(process.cwd(), dest) ) } catch (err) { console.log( chalk.red(`Copying React Static template: ${template} failed!`) ) throw err } } else { // Local templates try { console.log(chalk.green(`Using template from directory: ${template}`)) await fs.copy(path.resolve(process.cwd(), template), dest) } catch (err) { console.log( chalk.red(`Copying the template from directory: ${template} failed!`) ) throw err } } // Since npm packaging will clobber .gitignore files // We need to rename the gitignore file to .gitignore // See: https://github.com/npm/npm/issues/1862 if ( !fs.pathExistsSync(path.join(dest, '.gitignore')) && fs.pathExistsSync(path.join(dest, 'gitignore')) ) { await fs.move(path.join(dest, 'gitignore'), path.join(dest, '.gitignore')) } if (fs.pathExistsSync(path.join(dest, 'gitignore'))) { fs.removeSync(path.join(dest, 'gitignore')) } if (isCLI) { console.log( `=> Installing dependencies with: ${ isYarn ? chalk.hex(ChalkColor.yarn)('Yarn') : chalk.hex(ChalkColor.npm)('NPM') }...` ) // We install react-static separately to ensure we always have the latest stable release execSync(`cd ${name} && ${isYarn ? 'yarn' : 'npm install'}`) console.log('') } timeEnd(chalk.green(`=> [\u2713] Project "${name}" created`)) console.log(` ${chalk.green('=> To get started:')} cd ${name} ${ !isCLI ? `&& ${ isYarn ? chalk.hex(ChalkColor.yarn)('yarn') : chalk.hex(ChalkColor.npm)('npm install') }` : '' } ${ isYarn ? chalk.hex(ChalkColor.yarn)('yarn') : chalk.hex(ChalkColor.npm)('npm run') } start ${chalk.green('- Start the development server')} ${ isYarn ? chalk.hex(ChalkColor.yarn)('yarn') : chalk.hex(ChalkColor.npm)('npm run') } build ${chalk.green('- Build for production')} ${ isYarn ? chalk.hex(ChalkColor.yarn)('yarn') : chalk.hex(ChalkColor.npm)('npm run') } serve ${chalk.green('- Test a production build locally')} `) }) function shouldUseYarn() { try { execSync('yarnpkg --version', { stdio: 'ignore' }) return true } catch (e) { return false } }
JavaScript
0.000002
@@ -844,29 +844,8 @@ ()%0A%0A - const prompts = %5B%5D%0A co
14251ad11f9d99bd35ddc673ac69f166b8e0d29c
Resolve relative path
packages/mjml-core/src/index.js
packages/mjml-core/src/index.js
import { get, identity, map, omit, reduce } from 'lodash' import juice from 'juice' import { html as htmlBeautify } from 'js-beautify' import { minify as htmlMinify } from 'html-minifier' import MJMLParser from 'mjml-parser-xml' import MJMLValidator from 'mjml-validator' import components, { initComponent, registerComponent } from './components' import mergeOutlookConditionnals from './helpers/mergeOutlookConditionnals' import defaultSkeleton from './helpers/skeleton' import traverseMJML from './helpers/traverseMJML' class ValidationError extends Error { constructor(message, errors) { super(message) this.errors = errors } } export default function mjml2html(mjml, options = {}) { let content = '' let errors = [] if(typeof options.skeleton === 'string') { options.skeleton = require(options.skeleton) } const { beautify = false, fonts = { 'Open Sans': 'https://fonts.googleapis.com/css?family=Open+Sans:300,400,500,700', 'Droid Sans': 'https://fonts.googleapis.com/css?family=Droid+Sans:300,400,500,700', Lato: 'https://fonts.googleapis.com/css?family=Lato:300,400,500,700', Roboto: 'https://fonts.googleapis.com/css?family=Roboto:300,400,500,700', Ubuntu: 'https://fonts.googleapis.com/css?family=Ubuntu:300,400,500,700', }, keepComments, minify = false, skeleton = defaultSkeleton, validationLevel = 'soft', } = options const globalDatas = { breakpoint: '480px', classes: {}, classesDefault: {}, defaultAttributes: {}, fonts, inlineStyle: [], mediaQueries: {}, preview: '', style: [], title: '', } if (typeof mjml === 'string') { mjml = MJMLParser(mjml, { keepComments, components, }) } const validatorOptions = { components, } switch (validationLevel) { case 'skip': break case 'strict': errors = MJMLValidator(mjml, validatorOptions) if (errors.length > 0) { throw new ValidationError( `ValidationError: \n ${errors .map(e => e.formattedMessage) .join('\n')}`, errors, ) } break case 'soft': default: errors = MJMLValidator(mjml, validatorOptions) break } const mjBody = traverseMJML(mjml, child => child.tagName === 'mj-body') const mjHead = traverseMJML(mjml, child => child.tagName === 'mj-head') const processing = (node, context, parseMJML = identity) => { if (!node) { return } const component = initComponent({ name: node.tagName, initialDatas: { ...parseMJML(node), context, }, }) if (component !== null) { if ('handler' in component) { component.handler() } if ('render' in component) { return component.render() // eslint-disable-line consistent-return } } } const applyAttributes = mjml => { const parse = (mjml, parentMjClass='') => { const { attributes, tagName, children } = mjml const classes = get(mjml.attributes, 'mj-class', '').split(' ') const attributesClasses = reduce( classes, (acc, value) => ({ ...acc, ...globalDatas.classes[value], }), {}, ) const defaultAttributesForClasses = reduce( parentMjClass.split(' '), (acc, value) => ({ ...acc, ...get(globalDatas.classesDefault, `${value}.${tagName}`), }), {} ) const nextParentMjClass = get(attributes, 'mj-class', parentMjClass) return { ...mjml, attributes: { ...globalDatas.defaultAttributes[tagName], ...globalDatas.defaultAttributes['mj-all'], ...attributesClasses, ...defaultAttributesForClasses, ...omit(attributes, ['mj-class']), }, children: map( children, (mjml) => parse( mjml, nextParentMjClass ) ), } } return parse(mjml) } const bodyHelpers = { addMediaQuery(className, { parsedWidth, unit }) { globalDatas.mediaQueries[ className ] = `{ width:${parsedWidth}${unit} !important; }` }, processing: (node, context) => processing(node, context, applyAttributes), } const headHelpers = { add(attr, ...params) { if (Array.isArray(globalDatas[attr])) { globalDatas[attr].push(...params) } else if (globalDatas[attr]) { if (params.length > 1) { globalDatas[attr][params[0]] = params[1] } else { globalDatas[attr] = params[0] } } else { throw Error( `An mj-head element add an unkown head attribute : ${attr} with params ${Array.isArray( params, ) ? params.join('') : params}`, ) } }, } processing(mjHead, headHelpers) content = processing(mjBody, bodyHelpers, applyAttributes) if (globalDatas.inlineStyle.length > 0) { content = juice(content, { applyStyleTags: false, extraCss: globalDatas.inlineStyle.join(''), insertPreservedExtraCss: false, removeStyleTags: false, }) } content = skeleton({ content, ...globalDatas, }) content = beautify ? htmlBeautify(content, { indent_size: 2, wrap_attributes_indent_size: 2, max_preserve_newline: 0, preserve_newlines: false, }) : content content = minify ? htmlMinify(content, { collapseWhitespace: true, minifyCSS: true, removeEmptyAttributes: true, }) : content content = mergeOutlookConditionnals(content) return { html: content, errors, } } export { components, initComponent, registerComponent } export { BodyComponent, HeadComponent } from './createComponent'
JavaScript
0.000002
@@ -51,16 +51,39 @@ lodash'%0A +import path from 'path' %0Aimport @@ -837,16 +837,98 @@ require( +options.skeleton.charAt(0)=='.' ? path.resolve(process.cwd(), options.skeleton) : options.
1c8e3c4f90023614880ee048c58d511285e13010
add key for Breadcrumb elements
src/components/A10-UI/Breadcrumb.js
src/components/A10-UI/Breadcrumb.js
import React, { Component, PropTypes } from 'react'; import { Link } from 'react-router'; import { FIRST_BREADCRUMB } from '../../constants/breadcrumb'; export default class Breadcrumb extends Component { render() { let { data } = this.props; data = FIRST_BREADCRUMB.concat(data); return (<ol className="breadcrumb a10-breadcrumb">{ data.map((item,idx) => { let isLast = idx===data.length-1; let child = isLast ? [item.txt] : [<Link to={item.url}>{item.txt}</Link>]; if (!isLast) { child.push(<span className="a10-breadcrumb__divide" dangerouslySetInnerHTML={{__html:'&raquo;'}}></span>); } return <li>{child}</li>; }) }</ol>); } }; Breadcrumb.propTypes = { data: PropTypes.array }; Breadcrumb.defaultProps = { data: [] };
JavaScript
0.000038
@@ -463,16 +463,26 @@ : %5B%3CLink + key=%7Bidx%7D to=%7Bite
65427f1f77b565c91e9ba5d038eb1663fc833efe
Move reformatColumns to helpers/reformat
src/components/Budgets/CSVExport.js
src/components/Budgets/CSVExport.js
import flatten from 'flat'; import jsonexport from 'jsonexport'; import React, { Component } from 'react'; import { CSVLink } from 'react-csv'; class CSVExport extends Component { constructor(){ super(); this.exportFile = this.exportFile.bind(this); } convertFileType(data) { const options = { headers: this.props.columns.map((column) => (column.value)), rename: this.props.columns.map((column) => (column.label)), }; jsonexport(data, options, (err,csv) => { if(err) { return console.log(err); } return csv; }); } exportFile() { return this.reformatColumns(this.props.visibleItems); } reformatColumns(items) { const flatList = items.map((item) => flatten(item, { maxDepth: 2 })); // convert columns const reformattedList = flatList.map((item) => ({ ...item, // Put the hours in the right column [item['budgetHours.column']]: item['budgetHours.value'], total: item['budgetHours.value'], })); let concatObj = {}; const itemsByFeature = reformattedList.reduce((features, item) => { features[item.feature] = [ ...features[item.feature] || [], item, ]; return features; }, {}); console.log({ itemsByFeature, reformattedList }); // combine on feature reformattedList.map((item) => { // Feature isn't already in the object if (typeof concatObj[item.feature] === 'undefined') { concatObj[item.feature] = item; } else { // Add to existing feature for (const property in item) { if(Array.isArray(item[property])) { concatObj[item.feature][property] = [ ...concatObj[item.feature][property], ...item[property], ]; } else if(typeof item[property] === 'number') { // Sum the numbers concatObj[item.feature][property] = concatObj[item.feature][property] + item[property] || item[property]; } } } }); // convert concatObj from properties to array elements let concatList = []; for (const element in concatObj) { concatList = [...concatList, concatObj[element]]; } return concatList; } render() { return ( <div> <CSVLink data={this.exportFile()} headers={this.props.columns} filename={'Budget.csv'} className="btn btn-primary"> Export to CSV </CSVLink> </div> ); } } CSVExport.defaultProps = { columns: [{ key:'feature', value:'feature', label:'Page/Feature', },{ key:'t&m', value:'t&m', label:'T&M', },{ key:'Discovery', value:'Discovery', label:'Disc', },{ key:'Design', value:'Design', label:'Design', },{ key:'Dev', value:'Dev', label:'Dev', },{ key:'Testing', value:'Testing', label:'Testing', },{ key:'Remediation', value:'Remediation', label:'Remediation', },{ key:'Deploy', value:'Deploy', label:'Deploy', },{ key:'PM', value:'PM', label:'PM', },{ key:'total', value:'total', label:'Total', },{ key:'descriptions.budget', value:'descriptions.budget', label:'Description', },{ key:'descriptions.assumptions', value:'descriptions.assumptions', label:'Assumptions', },{ key:'descriptions.clientResponsibilities', value:'descriptions.clientResponsibilities', label:'Client Responsibilities', },{ key:'descriptions.exclusions', value:'descriptions.exclusions', label:'Exclusions', }, ] } export default CSVExport;
JavaScript
0
@@ -136,16 +136,74 @@ ct-csv'; +%0Aimport %7B reformatColumns %7D from '../../helpers/reformat'; %0A%0Aclass @@ -632,21 +632,16 @@ %09return -this. reformat @@ -682,1530 +682,8 @@ %09%7D%0A%0A -%09reformatColumns(items) %7B%0A%09%09const flatList = items.map((item) =%3E flatten(item, %7B maxDepth: 2 %7D));%0A%09%09%0A%09%09// convert columns%0A const reformattedList = flatList.map((item) =%3E (%7B%0A ...item,%0A // Put the hours in the right column%0A %5Bitem%5B'budgetHours.column'%5D%5D: item%5B'budgetHours.value'%5D,%0A total: item%5B'budgetHours.value'%5D,%0A %7D));%0A%0A%09%09let concatObj = %7B%7D;%0A%0A const itemsByFeature = reformattedList.reduce((features, item) =%3E %7B%0A features%5Bitem.feature%5D = %5B%0A ...features%5Bitem.feature%5D %7C%7C %5B%5D,%0A item,%0A %5D;%0A%0A return features;%0A %7D, %7B%7D);%0A%0A console.log(%7B itemsByFeature, reformattedList %7D);%0A%0A%09%09// combine on feature%0A%09%09reformattedList.map((item) =%3E %7B%0A // Feature isn't already in the object%0A%09%09%09if (typeof concatObj%5Bitem.feature%5D === 'undefined') %7B%0A%09%09%09%09concatObj%5Bitem.feature%5D = item;%0A%09%09%09%7D else %7B%0A // Add to existing feature%0A%09%09%09%09for (const property in item) %7B%0A%09%09%09%09%09if(Array.isArray(item%5Bproperty%5D)) %7B%0A concatObj%5Bitem.feature%5D%5Bproperty%5D = %5B%0A ...concatObj%5Bitem.feature%5D%5Bproperty%5D,%0A ...item%5Bproperty%5D,%0A %5D;%0A%09%09%09%09%09%7D else if(typeof item%5Bproperty%5D === 'number') %7B%0A // Sum the numbers%0A%09%09%09%09%09%09concatObj%5Bitem.feature%5D%5Bproperty%5D = concatObj%5Bitem.feature%5D%5Bproperty%5D + item%5Bproperty%5D %7C%7C item%5Bproperty%5D;%0A%09%09%09%09%09%7D %0A%09%09%09%09%7D%0A%09%09%09%7D%0A%09%09%7D);%0A%0A%09%09// convert concatObj from properties to array elements%0A%09%09let concatList = %5B%5D;%0A%09%09for (const element in concatObj) %7B%0A%09%09%09concatList = %5B...concatList, concatObj%5Belement%5D%5D;%0A%09%09%7D%0A%0A%09%09return concatList;%0A%09%7D%0A%0A %09ren
5a97e3870d023236c4f509fb000ec025107dc20f
Connect Form to Redux Store
src/components/Budgets/Item/Form.js
src/components/Budgets/Item/Form.js
import React, { Component } from 'react'; import nanoid from 'nanoid'; import flatten from 'flat'; export default class ItemForm extends Component { constructor(props) { super(props); this.state = { item: { ...flatten({ ...props.item }, { maxDepth: 2 }), }, }; this.onSubmit = this.onSubmit.bind(this); this.onChange = this.onChange.bind(this); this.onCancel = this.onCancel.bind(this); } onCancel() { this.props.onSubmit(this.props.item); } onChange(name, value) { this.setState({ item: { ...this.state.item, [name]: value, }, }); } onSubmit(event) { event.preventDefault(); // Unflatten this.props.onSubmit(flatten.unflatten({ ...this.state.item })); this.setState( ItemForm.defaultProps ); // Focus on the first input this.refs[this.props.fields[0].name].focus(); } render() { const { fields } = this.props; const submitBtnLabel = this.props.isEditing ? 'Save Edit' : 'Add Item'; return ( <div> <form onSubmit={this.onSubmit}> <div className="input-group input-group-sm"> {fields.map((field) => ( <div key={field.name}> <label htmlFor={field.name}>{field.label}</label> <input ref={field.name} onChange={e => this.onChange(field.name, e.target.value)} type={field.type} value={this.state.item[field.name]} required={field.required} /> </div> ))} <button type="submit" className="btn btn-primary">{submitBtnLabel}</button> {this.props.isEditing && ( <button onClick={this.onCancel} className="btn btn-primary">Cancel</button> )} </div> </form> </div> ) } } ItemForm.defaultProps = { item: { id: nanoid(), summary: "", phase: "", feature: "", budgetHours: { column: "", value: 0, }, descriptions: { workplan: [], budget: [], assumptions: [], exclusions: [], }, tags: "", 'budgetHours.column': "", 'budgetHours.value': 0, 'descriptions.workplan': [], 'descriptions.budget': [], 'descriptions.clientResponsibilities': [], 'descriptions.assumptions': [], 'descriptions.exclusions': [], }, isEditing: false, };
JavaScript
0
@@ -1,12 +1,40 @@ +import flatten from 'flat';%0A import React @@ -74,84 +74,47 @@ ort -nanoid from 'nanoid';%0Aimport flatten from 'flat';%0A%0Aexport default +%7B connect %7D from 'react-redux';%0A%0A class -Item Form @@ -751,16 +751,21 @@ em %7D));%0A + %0A this @@ -778,31 +778,93 @@ ate( - ItemForm.defaultProps +%7B %0A isEditing: Form.defaultProps.isEditing, %0A item: this.props.item, %0A %7D );%0A @@ -949,17 +949,18 @@ ocus();%0A -%09 + %7D%0A%0A%09rend @@ -1926,20 +1926,16 @@ )%0A%09%7D%0A%7D%0A%0A -Item Form.def @@ -1955,539 +1955,179 @@ %0A i -tem: %7B%0A id: nanoid(),%0A summary: %22%22,%0A phase: %22%22,%0A feature: %22%22,%0A budgetHours: %7B %0A column: %22%22,%0A value: 0,%0A %7D,%0A descriptions: %7B%0A workplan: %5B%5D,%0A budget: %5B%5D,%0A assumptions: %5B%5D,%0A exclusions: %5B%5D,%0A %7D,%0A tags: %22%22,%0A%0A 'budgetHours.column': %22%22,%0A 'budgetHours.value': 0,%0A 'descriptions.workplan': %5B%5D,%0A 'descriptions.budget': %5B%5D,%0A 'descriptions.clientResponsibilities': %5B%5D,%0A 'descriptions.assumptions': %5B%5D,%0A 'descriptions.exclusions': %5B%5D, %0A %7D,%0A isEditing: false,%0A%7D;%0A +sEditing: false,%0A%7D;%0A%0Aconst mapStateToProps = state =%3E (%7B%0A item: state.budgets.defaultItem,%0A fields: state.budgets.fields,%0A%7D);%0A%0Aexport default connect(mapStateToProps)(Form);
5589e09760f70a16737b582e9ef9d1d5552eb2f1
Add unlogged user menu
src/components/Navigation/Topnav.js
src/components/Navigation/Topnav.js
import React, { PropTypes } from 'react'; import { Link } from 'react-router'; import { Menu, Popover, Icon, Input } from 'antd'; import Avatar from '../Avatar'; import './Topnav.less'; const SubMenu = Menu.SubMenu; class Topnav extends React.Component { static propTypes = { username: PropTypes.string, }; constructor(props) { super(props); this.state = { notificationsVisible: false, }; } onNotificationChange(openKeys) { if (openKeys.indexOf('notifications') !== -1) { this.setState({ notificationsVisible: true }); } else { this.setState({ notificationsVisible: false }); } } render() { const { username } = this.props; return ( <div className="Topnav"> <div className="Topnav__container"> <span className="Topnav__brand">busy</span> <Input placeholder="Search..." className="Topnav__input" /> <div className="Topnav__menu-container"> <Menu className="Topnav__menu" mode="horizontal" onOpenChange={openKeys => this.onNotificationChange(openKeys)} > <Menu.Item key="user" className="Topnav__item"> <Link className="Topnav__user" to={`/@${username}`}> <Avatar username={username} size={36} /> <span>{username}</span> </Link> </Menu.Item> <SubMenu key="notifications" className="Topnav__item Topnav__item--dropdown" title={ <Popover visible={this.state.notificationsVisible} content={<span>Notifications</span>} title="Notifications"><span className="icon-beanie" /></Popover> } /> <SubMenu key="more" className="Topnav__item Topnav__item--dropdown" title={<Icon type="ellipsis" />}> <Menu.Item key="more:1">Option 1</Menu.Item> <Menu.Item key="more:2">Option 2</Menu.Item> </SubMenu> </Menu> </div> </div> </div> ); } } export default Topnav;
JavaScript
0.000001
@@ -690,219 +690,64 @@ ps;%0A +%0A -return (%0A %3Cdiv className=%22Topnav%22%3E%0A %3Cdiv className=%22Topnav__container%22%3E%0A %3Cspan className=%22Topnav__brand%22%3Ebusy%3C/span%3E%0A %3CInput placeholder=%22Search...%22 className=%22Topnav__input%22 /%3E +let content;%0A%0A if (username) %7B%0A content = ( %0A @@ -751,18 +751,16 @@ - %3Cdiv cla @@ -806,18 +806,14 @@ - %3CMenu%0A - @@ -845,18 +845,16 @@ __menu%22%0A - @@ -887,18 +887,16 @@ - onOpenCh @@ -964,14 +964,10 @@ - %3E%0A +%3E%0A @@ -1022,18 +1022,16 @@ _item%22%3E%0A - @@ -1105,18 +1105,16 @@ - %3CAvatar @@ -1162,18 +1162,16 @@ - %3Cspan%3E%7Bu @@ -1200,18 +1200,16 @@ - %3C/Link%3E%0A @@ -1216,26 +1216,24 @@ - %3C/Menu.Item%3E @@ -1225,34 +1225,32 @@ %3C/Menu.Item%3E%0A - %3CSub @@ -1268,18 +1268,16 @@ - key=%22not @@ -1294,34 +1294,32 @@ %22%0A - className=%22Topna @@ -1368,18 +1368,16 @@ - title=%7B%0A @@ -1372,18 +1372,16 @@ title=%7B%0A - @@ -1555,22 +1555,18 @@ - %7D%0A +%7D%0A @@ -1576,34 +1576,32 @@ /%3E%0A - %3CSubMenu key=%22mo @@ -1686,18 +1686,16 @@ s%22 /%3E%7D%3E%0A - @@ -1751,34 +1751,32 @@ %3E%0A - %3CMenu.Item key=%22 @@ -1816,18 +1816,16 @@ - %3C/SubMen @@ -1821,24 +1821,508 @@ %3C/SubMenu +%3E%0A %3C/Menu%3E%0A %3C/div%3E);%0A %7D else %7B%0A content = (%0A %3Cdiv className=%22Topnav__menu-container%22%3E%0A %3CMenu className=%22Topnav__menu%22 mode=%22horizontal%22%3E%0A %3CMenu.Item key=%22signin%22 className=%22Topnav__item%22%3E%0A %3CLink to=%22/signin%22%3E%0A Sign in%0A %3C/Link%3E%0A %3C/Menu.Item%3E%0A %3CMenu.Item key=%22signup%22 className=%22Topnav__item%22%3E%0A %3CLink to=%22/signup%22%3E%0A Sign up%0A %3C/Link %3E%0A @@ -2321,32 +2321,37 @@ %3C/Menu +.Item %3E%0A %3C/di @@ -2344,28 +2344,285 @@ %3C/ -div%3E +Menu%3E%0A %3C/div%3E);%0A %7D%0A%0A return (%0A %3Cdiv className=%22Topnav%22%3E%0A %3Cdiv className=%22Topnav__container%22%3E%0A %3Cspan className=%22Topnav__brand%22%3Ebusy%3C/span%3E%0A %3CInput placeholder=%22Search...%22 className=%22Topnav__input%22 /%3E%0A %7Bcontent%7D %0A %3C/d
a34e11aa6f61d6dcb83fa70c9c84d4e7bd5f5844
update story
src/components/qTip/qTip.stories.js
src/components/qTip/qTip.stories.js
import React from 'react'; import { addStoryInGroup, MID_LEVEL_BLOCKS } from '../../../.storybook/utils'; import { boolean } from '@storybook/addon-knobs'; import { Store, State } from '@sambego/storybook-state'; import { IconIdeaMediumOutline } from '@teamleader/ui-icons'; import { Island, Link, QTip, TextBody } from '../../index'; const store = new Store({ active: false, }); const updateState = () => { store.set({ active: !store.get('active') }); }; export default { component: QTip, title: addStoryInGroup(MID_LEVEL_BLOCKS, 'Q-tip'), parameters: { info: { propTablesExclude: [TextBody, Island, Link, State], }, }, }; export const defaultStory = () => ( <Island paddingHorizontal={0} paddingVertical={6} style={{ width: '500px' }}> <State store={store}> <QTip highlighted={boolean('Highlighted', false)} onChange={updateState} onEscKeyDown={updateState} onOverlayClick={updateState} icon={<IconIdeaMediumOutline />} > <TextBody color="teal"> Lorem ipsum dolor sit amet, consectetur{' '} <Link href="#" inherit={false}> adipiscing </Link>{' '} elit. </TextBody> </QTip> </State> </Island> ); defaultStory.story = { name: 'Default', };
JavaScript
0
@@ -103,58 +103,8 @@ s';%0A -import %7B boolean %7D from '@storybook/addon-knobs';%0A impo @@ -226,24 +226,16 @@ import %7B - Island, Link, Q @@ -490,107 +490,8 @@ p'), -%0A%0A parameters: %7B%0A info: %7B%0A propTablesExclude: %5BTextBody, Island, Link, State%5D,%0A %7D,%0A %7D, %0A%7D;%0A @@ -504,17 +504,17 @@ t const -d +D efaultSt @@ -524,97 +524,19 @@ = ( +args ) =%3E (%0A - %3CIsland paddingHorizontal=%7B0%7D paddingVertical=%7B6%7D style=%7B%7B width: '500px' %7D%7D%3E%0A %3CS @@ -559,18 +559,16 @@ e%7D%3E%0A - %3CQTip%0A @@ -575,56 +575,18 @@ - - highlighted=%7Bboolean('Highlighted', false)%7D%0A +%7B...args%7D%0A @@ -616,18 +616,16 @@ %7D%0A - onEscKey @@ -639,26 +639,24 @@ pdateState%7D%0A - onOver @@ -684,18 +684,16 @@ %7D%0A - - icon=%7B%3CI @@ -725,14 +725,10 @@ - %3E%0A +%3E%0A @@ -761,18 +761,16 @@ - Lorem ip @@ -814,18 +814,16 @@ - %3CLink hr @@ -856,18 +856,16 @@ - - adipisci @@ -867,18 +867,16 @@ piscing%0A - @@ -884,26 +884,24 @@ /Link%3E%7B' '%7D%0A - elit @@ -908,18 +908,16 @@ .%0A - %3C/TextBo @@ -924,18 +924,16 @@ dy%3E%0A - %3C/QTip%3E%0A @@ -934,18 +934,16 @@ QTip%3E%0A - - %3C/State%3E @@ -947,65 +947,7 @@ te%3E%0A - %3C/Island%3E%0A);%0A%0AdefaultStory.story = %7B%0A name: 'Default',%0A%7D +) ;%0A
6ba25accf7bd28c03ff7f55c989f2fb55b65ba9d
Replace `_site_id` with `_sid` to follow naming conventions
lib/follow.js
lib/follow.js
/** * Module dependencies. */ var debug = require('debug')('wpcom:like'); /** * Follow methods * * @param {String} site_id site id * @param {WPCOM} wpcom * @api public */ function Follow(site_id, wpcom){ if (!site_id) { throw new Error('`site id` is not correctly defined'); } if (!(this instanceof Follow)) return new Follow(site_id, wpcom); this.wpcom = wpcom; this._site_id = site_id; }; /** * :FOLLOW: * List a site's followers * in reverse-chronological * order * */ Follow.prototype.follows = Follow.prototype.followsList = function(query, fn) { var path = '/sites/' + this._site_id + '/follows/' this.wpcom.sendRequest(path, query, null, fn); }; /** * :FOLLOW: * Follow the site * */ Follow.prototype.follow = Follow.prototype.new = Follow.prototype.add = function(query, fn) { var path = '/sites/' + this._site_id + '/follows/new'; this.wpcom.sendRequest({method: 'POST', path: path}, query, null, fn); }; /** * :FOLLOW: * Unfollow the site * */ Follow.prototype.unfollow = Follow.prototype.remove = Follow.prototype.del = function(query, fn) { var path = '/sites/' + this._site_id + '/follows/mine/delete'; this.wpcom.sendRequest({method: 'POST', path: path}, query, null, fn); }; /** * :FOLLOW: * Get the follow status for current * user on current blog site * */ Follow.prototype.state = Follow.prototype.mine = function(query, fn) { var path = '/sites/' + this._site_id + '/follows/mine'; this.wpcom.sendRequest(path, query, null, fn); }; module.exports = Follow;
JavaScript
0.000094
@@ -391,20 +391,16 @@ this._s -ite_ id = sit @@ -405,16 +405,16 @@ ite_id;%0A + %7D;%0A%0A/**%0A @@ -600,36 +600,32 @@ ites/' + this._s -ite_ id + '/follows/' @@ -838,36 +838,32 @@ ites/' + this._s -ite_ id + '/follows/n @@ -1111,36 +1111,32 @@ ites/' + this._s -ite_ id + '/follows/m @@ -1378,32 +1378,32 @@ on(query, fn) %7B%0A + var path = '/s @@ -1418,20 +1418,16 @@ this._s -ite_ id + '/f
54bd2a5d978be0d13cb1d1b82e54a16ace79815a
Add text-transform on mj-text component
packages/mjml-text/src/index.js
packages/mjml-text/src/index.js
import { MJMLElement } from 'mjml-core' import merge from 'lodash/merge' import React, { Component } from 'react' const tagName = 'mj-text' const defaultMJMLDefinition = { content: '', attributes: { 'align': 'left', 'color': '#000000', 'font-family': 'Ubuntu, Helvetica, Arial, sans-serif', 'font-size': '13px', 'line-height': '22px', 'padding': '10px 25px' } } const endingTag = true const columnElement = true const baseStyles = { div: { cursor: 'auto' } } @MJMLElement class Text extends Component { styles = this.getStyles() getStyles () { const { mjAttribute, defaultUnit } = this.props return merge({}, baseStyles, { div: { color: mjAttribute('color'), fontFamily: mjAttribute('font-family'), fontSize: defaultUnit(mjAttribute('font-size'), "px"), fontStyle: mjAttribute('font-style'), fontWeight: mjAttribute('font-weight'), lineHeight: defaultUnit(mjAttribute('line-height'), "px"), textDecoration: mjAttribute('text-decoration') } }) } render () { const { mjContent } = this.props return ( <div dangerouslySetInnerHTML={{ __html: mjContent() }} style={this.styles.div} /> ) } } Text.tagName = tagName Text.defaultMJMLDefinition = defaultMJMLDefinition Text.endingTag = endingTag Text.columnElement = columnElement Text.baseStyles = baseStyles export default Text
JavaScript
0
@@ -1047,16 +1047,70 @@ ration') +,%0A textTransform: mjAttribute('text-transform') %0A %7D
20bb82b907b019e66e4d013aa7ef708cf1497b72
Use more useful variable names than 'data'.
lib/person.js
lib/person.js
var Person = function(userId){ this._userId = userId; this._minId = 0; this._lastImage = null; this.username = null; this.lastUpdate = null; }; var P = Person.prototype; P.getLatestUpdate = function(client, callback){ var self = this; client.getUserMedia(this._userId, this._minId, function(err, data){ if (err) { callback(err, null); return; } if (data.hasOwnProperty('data') && data.data.length > 0) { self.receivedUpdates(data.data, callback); } else { callback(null, null); } }); }; P.receivedUpdates = function(data, callback){ var i, self = this; this._minId = data[0].id; for (i = 0; i < data.length; i++) { if (data[i].type == 'image') { self.updatePublicData(data[i]); callback(null, self); return; } } callback(null, null); }; P.updatePublicData = function(data){ this._lastImage = data; this.username = data.user.username; this.lastUpdate = { created_at: data.created_time, username: data.user.username, comment_count: data.comments.count, like_count: data.likes.count, tags: data.tags, location: data.location, images: data.images, caption_text: data.caption ? data.caption.text : null, link: data.link }; }; exports.fromUserIds = function(userIds){ var i, result = []; for (i = 0; i < userIds.length; i++) { result.push(new Person(userIds[i])); } return result; }; exports.Person = Person;
JavaScript
0.000026
@@ -305,20 +305,25 @@ on(err, -data +resultSet )%7B%0A i @@ -387,20 +387,25 @@ if ( -data +resultSet .hasOwnP @@ -423,20 +423,25 @@ ta') && -data +resultSet .data.le @@ -479,20 +479,25 @@ Updates( -data +resultSet .data, c @@ -883,20 +883,21 @@ unction( -data +entry )%7B%0A thi @@ -911,20 +911,21 @@ Image = -data +entry ;%0A this @@ -936,20 +936,21 @@ rname = -data +entry .user.us @@ -998,20 +998,21 @@ _at: -data +entry .created @@ -1037,20 +1037,21 @@ e: -data +entry .user.us @@ -1077,20 +1077,21 @@ _count: -data +entry .comment @@ -1118,20 +1118,21 @@ unt: -data +entry .likes.c @@ -1156,20 +1156,21 @@ -data +entry .tags,%0A @@ -1187,20 +1187,21 @@ n: -data +entry .locatio @@ -1222,20 +1222,21 @@ -data +entry .images, @@ -1255,20 +1255,21 @@ _text: -data +entry .caption @@ -1271,20 +1271,21 @@ ption ? -data +entry .caption @@ -1317,20 +1317,21 @@ -data +entry .link%0A
cde1ae00efcf21bf3e5a066a71943b64e8563edf
fix link 2
Easy-Rent/read.js
Easy-Rent/read.js
var path_591 = 'https://rent.591.com.tw/' console.log('Start loading data from 591') //var searchPath = path_591 + '/index.php?module=search&action=rslist&is_new_list=1&type=1&searchtype=1&region=1&listview=img&option=cold,hotwater,bed,wardrobe&kind=2&rentprice=3&order=area&orderType=desc&other=cook'; var searchPath = path_591 + 'index.php?module=search&action=rslist&is_new_list=1&type=1&searchtype=1&region=1&rentprice=3&area=1&kind=2&option=cold,icebox,hotwater,washer,bed,wardrobe&other=balcony_1,cook&order=area&orderType=desc'; $.get(searchPath, function(response){ console.log('Get data from 591'); response = JSON.parse(response); console.log(response) $('#container .body_591').html(response.main); $('#container .body_591 a').each(function(){ var $this = $(this); $this.attr('src', path_591 + $this.attr('src')); }); });
JavaScript
0
@@ -641,103 +641,51 @@ );%0A%09 -console.log(response)%0A%09$('#container .body_591').html(response.main);%0A%09$('#container .body_591 +var $data = $(response.main);%0A%09$data.find(' a'). @@ -738,19 +738,20 @@ s.attr(' -src +href ', path_ @@ -772,11 +772,12 @@ tr(' -src +href ')); @@ -782,13 +782,55 @@ );%0A%09%7D);%0A +%09$('#container .body_591').append($data);%0A %7D);%0A%0A
fca66b1ef5603f95a41a553a003453811c953665
Switch Button to TouchableWithoutFeedback
src/button.js
src/button.js
import React from './React' const { PropTypes, View } = React import ps from 'react-native-ps' import Uranium from 'uranium' import Color from 'color' import connectTheme from './connectTheme' import Shadows from './styles/Shadows' import { Breakpoints } from './styles/Grid' import { Body1 } from 'carbon-ui/lib/Type' import Ripple from './Ripple' const Button = ({ children, style, disabled, flat, raised, fab, icon, theme, }) => { // Themed styles const tStyles = styles(theme) // Uppercase and style if the child is a string // Otherwise it's probably an icon or image, so let it through const formattedChildren = typeof children === 'string' ? <Body1>{children.toUpperCase()}</Body1> : children return ( <View style={tStyles.touchable}> <View css={[ tStyles.base, flat && tStyles.flat, raised && tStyles.raised, fab && tStyles.fab, icon && tStyles.icon, disabled && flat && tStyles.flat.disabled, disabled && raised && tStyles.raised.disabled, disabled && fab && tStyles.fab.disabled, disabled && icon && tStyles.icon.disabled, style, ]}> {formattedChildren} <Ripple /> </View> </View> ) } Button.propTypes = { children: PropTypes.node, style: PropTypes.object, disabled: PropTypes.bool, flat: PropTypes.bool, raised: PropTypes.bool, fab: PropTypes.bool, icon: PropTypes.bool, theme: PropTypes.object.isRequired, } const styles = theme => ps({ touchable: { padding: 12, }, base: { height: 36, paddingHorizontal: 16, paddingVertical: 10, marginHorizontal: 8, [Breakpoints.ml]: { height: 32, }, }, flat: { color: theme.primary, active: { backgroundColor: theme.button.flat.pressed, }, disabled: { backgroundColor: theme.button.flat.disabled, }, }, raised: { minWidth: 88, ...Shadows.dp2, active: { ...Shadows.dp4, }, focus: { backgroundColor: Color(theme.primary).darken(0.12).hexString(), }, disabled: { color: theme.button.raised.disabledText, backgroundColor: theme.button.raised.disabled, }, [Breakpoints.ml]: { ...Shadows.none, hover: { ...Shadows.dp2, }, }, }, fab: { }, icon: { width: 40, height: 40, paddingVertical: 12, fontSize: 16, lineHeight: 16, textAlign: 'center', [Breakpoints.ml]: { height: 40, paddingVertical: 16, fontSize: 16, lineHeight: 16, }, }, web: { base: { cursor: 'pointer', }, }, }) export default connectTheme(Uranium(Button))
JavaScript
0
@@ -9,57 +9,108 @@ eact +, %7B PropTypes %7D from ' -./R +r eact'%0A -const %7B PropTypes, View %7D = React +import %7B TouchableWithoutFeedback, View %7D from 'react-native-universal' %0Aimp @@ -490,16 +490,28 @@ theme,%0A + ...other,%0A %7D) =%3E %7B%0A @@ -816,51 +816,38 @@ %3C -View style=%7BtStyles.touchable%7D%3E%0A %3CView +TouchableWithoutFeedback%0A css @@ -1226,16 +1226,139 @@ %5D%7D +%0A style=%7BtStyles.touchable%7D%0A hitSlop=%7B%7B top: 12, right: 12, bottom: 12, left: 12 %7D%7D%0A %7B...other%7D%3E%0A %3CView %3E%0A @@ -1414,28 +1414,48 @@ View%3E%0A %3C/ -View +TouchableWithoutFeedback %3E%0A )%0A%7D%0A%0ABut @@ -1695,16 +1695,16 @@ red,%0A%7D%0A%0A + const st @@ -1728,46 +1728,8 @@ s(%7B%0A - touchable: %7B%0A padding: 12,%0A %7D,%0A%0A ba
999b9e22750ed64302a2880fce2e1fbcb99ba250
Use destroy instead of remove for vuejs (#1583)
apps/vue-editor/src/mixin/option.js
apps/vue-editor/src/mixin/option.js
const editorEvents = [ 'load', 'change', 'caretChange', 'focus', 'blur', 'keydown', 'keyup', 'beforePreviewRender', 'beforeConvertWysiwygToMarkdown', ]; const defaultValueMap = { initialEditType: 'markdown', initialValue: '', height: '300px', previewStyle: 'vertical', }; export const optionsMixin = { data() { const eventOptions = {}; editorEvents.forEach((event) => { eventOptions[event] = (...args) => { this.$emit(event, ...args); }; }); const options = { ...this.options, initialEditType: this.initialEditType, initialValue: this.initialValue, height: this.height, previewStyle: this.previewStyle, events: eventOptions, }; Object.keys(defaultValueMap).forEach((key) => { if (!options[key]) { options[key] = defaultValueMap[key]; } }); return { editor: null, computedOptions: options }; }, methods: { invoke(methodName, ...args) { let result = null; if (this.editor[methodName]) { result = this.editor[methodName](...args); } return result; }, }, destroyed() { editorEvents.forEach((event) => { this.editor.off(event); }); this.editor.remove(); }, };
JavaScript
0
@@ -1244,14 +1244,15 @@ tor. -remove +destroy ();%0A
5555aec74b0f4894731de61eb3d3cd36b77028c8
Fix for broken @import errors
web/ember-cli-build.js
web/ember-cli-build.js
/*jshint node:true*/ /* global require, module */ var EmberApp = require('ember-cli/lib/broccoli/ember-app'); module.exports = function(defaults) { var app = new EmberApp(defaults, { lessOptions: { paths: [ "bower_components", "bower_components/bootstrap/less", ] } }); app.import('bower_components/moment-duration-format/lib/moment-duration-format.js'); app.import("bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.eot", { destDir: 'fonts' }) app.import("bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.svg", { destDir: 'fonts' }) app.import("bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.ttf", { destDir: 'fonts' }) app.import("bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff", { destDir: 'fonts' }) app.import("bower_components/bootstrap/dist/fonts/glyphicons-halflings-regular.woff2", { destDir: 'fonts' }) // Use `app.import` to add additional libraries to the generated // output files. // // If you need to use different assets in different // environments, specify an object as the first parameter. That // object's keys should be the environment name and the values // should be the asset to use in that environment. // // If the library that you are including contains AMD or ES6 // modules that you would like to import into your application // please specify an object with the list of modules as keys // along with the exports of each module as its value. return app.toTree(); };
JavaScript
0.000001
@@ -292,16 +292,94 @@ %5D%0A + %7D,%0A minifyCSS: %7B%0A options: %7B%0A processImport: false%0A %7D%0A %7D%0A
1034cca153501d9e8bf5392562eed842c2f2365c
Fix formatting, re#6542
arches/app/media/js/views/search.js
arches/app/media/js/views/search.js
define([ 'jquery', 'underscore', 'knockout', 'knockout-mapping', 'arches', 'viewmodels/alert', 'search-components', 'views/base-manager', 'views/components/simple-switch' ], function($, _, ko, koMapping, arches, AlertViewModel, SearchComponents, BaseManagerView) { // a method to track the old and new values of a subscribable // from https://github.com/knockout/knockout/issues/914 // // use case: // var sub1 = this.FirstName.subscribeChanged(function (newValue, oldValue) { // this.NewValue1(newValue); // this.OldValue1(oldValue); // }, this); ko.subscribable.fn.subscribeChanged = function(callback, context) { var savedValue = this.peek(); return this.subscribe(function(latestValue) { var oldValue = savedValue; savedValue = latestValue; callback.call(context, latestValue, oldValue); }); }; var getQueryObject = function() { var query = _.chain(decodeURIComponent(location.search).slice(1).split('&')) // Split each array item into [key, value] // ignore empty string if search is empty .map(function(item) { if (item) return item.split('='); }) // Remove undefined in the case the search is empty .compact() // Turn [key, value] arrays into object parameters .object() // Return the value of the chain operation .value(); return query; }; var CommonSearchViewModel = function() { this.filters = {}; this.filtersList = _.sortBy(SearchComponents, function(filter) { return filter.sortorder; }, this); SearchComponents.forEach(function(component) { this.filters[component.componentname] = ko.observable(null); }, this); var firstEnabledFilter = _.find(this.filtersList, function(filter) { return filter.type === 'filter' && filter.enabled === true; }, this); this.selectedTab = ko.observable(firstEnabledFilter.componentname); this.selectedPopup = ko.observable(''); this.resultsExpanded = ko.observable(true); this.query = ko.observable(getQueryObject()); this.clearQuery = function(){ Object.values(this.filters).forEach(function(value){ if (value()){ if (value().clear){ value().clear(); } } }, this); }; this.filterApplied = ko.pureComputed(function(){ var notFilters = ['paging-filter', 'related-resources-filter', 'saved-searches', 'search-export', 'search-result-details', 'search-results']; var trueFilters = Object.keys(this.filters).filter(function(f){ return notFilters.indexOf(f) === -1; }) var res = trueFilters.filter(function(f){ return this.query()[f]; }, this) return res.length > 0; }, this); this.mouseoverInstanceId = ko.observable(); this.mapLinkData = ko.observable(null); this.userIsReviewer = ko.observable(false); this.userid = null; this.searchResults = {'timestamp': ko.observable()}; this.selectPopup = function(componentname) { if(this.selectedPopup() !== '' && componentname === this.selectedPopup()) { this.selectedPopup(''); } else { this.selectedPopup(componentname); } }; this.isResourceRelatable = function(graphId) { var relatable = false; if (this.graph) { relatable = _.contains(this.graph.relatable_resource_model_ids, graphId); } return relatable; }; this.toggleRelationshipCandidacy = function() { var self = this; return function(resourceinstanceid){ var candidate = _.contains(self.relationshipCandidates(), resourceinstanceid); if (candidate) { self.relationshipCandidates.remove(resourceinstanceid); } else { self.relationshipCandidates.push(resourceinstanceid); } }; }; }; var SearchView = BaseManagerView.extend({ initialize: function(options) { this.viewModel.sharedStateObject = new CommonSearchViewModel(); this.viewModel.total = ko.observable(); _.extend(this, this.viewModel.sharedStateObject); this.viewModel.sharedStateObject.total = this.viewModel.total; this.viewModel.sharedStateObject.loading = this.viewModel.loading; this.queryString = ko.computed(function() { return JSON.stringify(this.query()); }, this); this.queryString.subscribe(function() { this.doQuery(); }, this); BaseManagerView.prototype.initialize.call(this, options); this.doQuery(); }, doQuery: function() { var queryString = JSON.parse(this.queryString()); if (this.updateRequest) { this.updateRequest.abort(); } this.viewModel.loading(true); this.updateRequest = $.ajax({ type: "GET", url: arches.urls.search_results, data: queryString, context: this, success: function(response) { _.each(this.viewModel.sharedStateObject.searchResults, function(value, key, results) { if (key !== 'timestamp') { delete this.viewModel.sharedStateObject.searchResults[key]; } }, this); _.each(response, function(value, key, response) { if (key !== 'timestamp') { this.viewModel.sharedStateObject.searchResults[key] = value; } }, this); this.viewModel.sharedStateObject.searchResults.timestamp(response.timestamp); this.viewModel.sharedStateObject.userIsReviewer(response.reviewer); this.viewModel.sharedStateObject.userid = response.userid; this.viewModel.total(response.total_results); this.viewModel.alert(false); }, error: function(response, status, error) { if(this.updateRequest.statusText !== 'abort'){ this.viewModel.alert(new AlertViewModel('ep-alert-red', arches.requestFailed.title, response.responseText)); } }, complete: function(request, status) { this.viewModel.loading(false); this.updateRequest = undefined; window.history.pushState({}, '', '?' + $.param(queryString).split('+').join('%20')); } }); } }); return new SearchView(); });
JavaScript
0.000007
@@ -2924,32 +2924,33 @@ ;%0A %7D) +; %0A var @@ -3048,16 +3048,17 @@ %7D, this) +; %0A
86a3eb1601348e7a609bd6dc3fa4060fee6013af
fix test name
test/test_channel_security_token_live_time.js
test/test_channel_security_token_live_time.js
"use strict"; require("requirish")._(module); var OPCUAServer = require("lib/server/opcua_server").OPCUAServer; var OPCUAClient = require("lib/client/opcua_client").OPCUAClient; var should = require("should"); var assert = require("better-assert"); var async = require("async"); var util = require("util"); var opcua = require("lib/nodeopcua"); var debugLog = require("lib/misc/utils").make_debugLog(__filename); var StatusCodes = require("lib/datamodel/opcua_status_code").StatusCodes; var browse_service = require("lib/services/browse_service"); var BrowseDirection = browse_service.BrowseDirection; var os =require("os"); var _ = require("underscore"); var port = 4000; describe("Testing ChannelSecurityToken lifetime",function(){ this.timeout(100000); var server , client; var endpointUrl ; beforeEach(function(done){ port+=1; server = new OPCUAServer({ port: port}); // we will connect to first server end point endpointUrl = server.endpoints[0].endpointDescriptions()[0].endpointUrl; debugLog("endpointUrl",endpointUrl); opcua.is_valid_endpointUrl(endpointUrl).should.equal(true); client = new OPCUAClient({ defaultSecureTokenLifetime: 100 // very short live time ! }); server.start(function() { setImmediate(done); }); }); afterEach(function(done){ setImmediate(function(){ client.disconnect(function(){ server.shutdown(function() { done(); }); }); }); }); it("ZZ A secure channel should raise a event to notify its client that its token is at 75% of its livetime",function(done){ client.connect(endpointUrl,function(err){ should(err).equal(undefined); }); client._secureChannel.once("lifetime_75",function(){ debugLog(" received lifetime_75"); done(); }); }); it("A secure channel should raise a event to notify its client that a token about to expired has been renewed",function(done){ client.connect(endpointUrl,function(err){should(err).equal(undefined); }); client._secureChannel.on("security_token_renewed",function(){ debugLog(" received security_token_renewed"); done(); }); }); it("A client should periodically renew the expiring security token",function(done){ client.connect(endpointUrl,function(err){should(err).equal(undefined); }); var security_token_renewed_counter = 0; client._secureChannel.on("security_token_renewed",function(){ debugLog(" received security_token_renewed"); security_token_renewed_counter+=1; }); var waitingTime = 1000; if ( os.arch() === "arm" ) { // give more time for slow raspberry to react */ waitingTime+=4000; } setTimeout(function(){ security_token_renewed_counter.should.be.greaterThan(3); done(); },waitingTime); }); });
JavaScript
0.000546
@@ -1609,11 +1609,8 @@ it(%22 -ZZ A se
81b991a6e8211d6abfb773cba427518873500189
Update the path to Amanda in the ‘exclusiveMaximum.js’ file
tests/validators/exclusiveMaximum.js
tests/validators/exclusiveMaximum.js
// Load dependencies var amanda = require('../../src/amanda.js'); /** * Test #1 */ exports['Test #1'] = function(test) { var count = 0; var schema = { required: true, type: 'number', maximum: 10, exclusiveMaximum: true }; [ 11, 100, 10, {}, null, [], function() {}, 'Hello!' ].forEach(function(input) { amanda.validate(input, schema, function(error) { count += 1; test.ok(error); }); }); amanda.validate(2, schema, function(error) { count += 1; test.equal(error, undefined); }); test.equal(count, 9); test.done(); };
JavaScript
0
@@ -46,18 +46,19 @@ /../ -src/amanda +dist/latest .js'
ca6b91ac4281f9c426c40b69c72a0e280bb7ec1e
move BADGES_ENABLED checks to checkOrGrant
troposphere/static/js/actions/BadgeActions.js
troposphere/static/js/actions/BadgeActions.js
define(function (require) { var Utils = require('./Utils'), $ = require('jquery'), Router = require('../Router'), stores = require('stores'), globals = require('globals'), Badge = require('models/Badge'), BadgeConstants = require('constants/BadgeConstants'), Badges = require("Badges"), NotificationController = require('controllers/NotificationController'); return { mixins: [Router.State], checkInstanceBadges: function(){ var instanceCount = stores.InstanceHistoryStore.getAll().meta.count; if(instanceCount >= 1){ this.checkOrGrant(Badges.LAUNCH_1_INSTANCE_BADGE); } if(instanceCount >= 10){ this.checkOrGrant(Badges.LAUNCH_10_INSTANCES_BADGE); } }, checkBookmarkBadges: function(){ var favoritedImageCount = stores.ImageBookmarkStore.getAll().meta.count; if(favoritedImageCount >= 1){ this.checkOrGrant(Badges.FAVORITE_1_IMAGE_BADGE); } if(favoritedImageCount >= 5){ this.checkOrGrant(Badges.FAVORITE_5_IMAGES_BADGE); } }, checkOrGrant: function(badgeId){ if(!stores.MyBadgeStore.get(badgeId)){ this.grant({badge: stores.BadgeStore.get(badgeId)}); } }, getCookie: function(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i = 0; i < cookies.length; i++) { var cookie = $.trim(cookies[i]); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) == (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; }, clearNotifications: function(){ Router.getInstance().transitionTo("my-badges"); NotificationController.clear(); }, grant: function(params){ try{ var badge = params.badge, email = stores.ProfileStore.get().get('email'), system = globals.BADGE_SYSTEM, secret = globals.BADGE_SECRET, csrftoken = this.getCookie('csrftoken'), badgeSlug = badge.get('slug'); } catch(err) { console.log(err); return; } $.ajax({ url: globals.BADGE_HOST, type: "POST", dataType: 'json', contentType: 'application/json', headers: {'X-CSRFToken': csrftoken}, data: JSON.stringify({ email: email, system: system, badgeSlug: badgeSlug, secret: secret }), success: function(response){ badge.attributes.assertionUrl = response.instance.assertionUrl; badge.attributes.issuedOn = response.instance.issuedOn; NotificationController.success("You have earned a badge!", badge.get('name'), {timeOut: 5000, onclick: this.clearNotifications}); Utils.dispatch(BadgeConstants.GRANT_BADGE, {badge: badge}) }.bind(this), error: function(response){ console.log("failed", response); } }); } }; });
JavaScript
0
@@ -444,20 +444,16 @@ State%5D,%0A - %0A che @@ -532,31 +532,49 @@ istoryStore. -getAll( +fetchWhere(%7Bunique: true%7D ).meta.count @@ -990,17 +990,16 @@ _BADGE); - %0A %7D @@ -1156,16 +1156,42 @@ if( +globals.BADGES_ENABLED && !stores. @@ -2336,36 +2336,8 @@ ) %7B%0A - console.log(err);%0A
b5e4db8fdfda1808b12fd97e119178feedbbe5e6
fix admin delete article acceptance test for new selectors
tests/acceptance/admin-delete-article-test.js
tests/acceptance/admin-delete-article-test.js
import { test } from 'qunit'; import moduleForAcceptance from 'adlet/tests/helpers/module-for-acceptance'; import { authenticateSession } from 'adlet/tests/helpers/ember-simple-auth'; import Ember from 'ember'; let s3Mock = Ember.Service.extend({ listAll(){ return [ {Key: "Article1", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]}, {Key: "Article2", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]} ]; }, find(){ return {Key: "Article1", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]}; }, delete() { return {Key: "Article1", Body: [77,121,32,83,101,120,121,32,66,101,97,99,104,32,66,111,100,121,33,33,33,33]}; } }); moduleForAcceptance('Acceptance | admin delete article', { beforeEach() { this.application.register('service:s3Mock', s3Mock); this.application.inject('adapter', 's3', 'service:s3Mock'); } }); test('visiting /admin/articles/Article1 and deleting it', function(assert) { authenticateSession(this.application, {data: "meh"}); visit('/admin/articles/Article1'); andThen(function() { assert.equal(currentURL(), '/admin/articles/Article1'); }); click(".admin-article__delete"); });
JavaScript
0
@@ -1239,20 +1239,37 @@ (%22.a -dmin-a rticle +-edit__header__controls __de
37a9f5046b0395df0cda76178dc6ebae72512b95
Add replace option
esm/mount.js
esm/mount.js
import { getEl } from './util.js'; import { doUnmount } from './unmount.js'; const hookNames = ['onmount', 'onremount', 'onunmount']; const shadowRootAvailable = typeof window !== 'undefined' && 'ShadowRoot' in window; export const mount = (parent, child, before) => { const parentEl = getEl(parent); let childEl = getEl(child); if (child === childEl && childEl.__redom_view) { // try to look up the view if not provided child = childEl.__redom_view; } if (child !== childEl) { childEl.__redom_view = child; } const wasMounted = childEl.__redom_mounted; const oldParent = childEl.parentNode; if (wasMounted && (oldParent !== parentEl)) { doUnmount(child, childEl, oldParent); } if (before != null) { parentEl.insertBefore(childEl, getEl(before)); } else { parentEl.appendChild(childEl); } doMount(child, childEl, parentEl, oldParent); return child; }; const doMount = (child, childEl, parentEl, oldParent) => { const hooks = childEl.__redom_lifecycle || (childEl.__redom_lifecycle = {}); const remount = (parentEl === oldParent); let hooksFound = false; for (const hookName of hookNames) { if (!remount) { // if already mounted, skip this phase if (child !== childEl) { // only Views can have lifecycle events if (hookName in child) { hooks[hookName] = (hooks[hookName] || 0) + 1; } } } if (hooks[hookName]) { hooksFound = true; } } if (!hooksFound) { childEl.__redom_mounted = true; return; } let traverse = parentEl; let triggered = false; if (remount || (traverse && traverse.__redom_mounted)) { trigger(childEl, remount ? 'onremount' : 'onmount'); triggered = true; } while (traverse) { const parent = traverse.parentNode; const parentHooks = traverse.__redom_lifecycle || (traverse.__redom_lifecycle = {}); for (const hook in hooks) { parentHooks[hook] = (parentHooks[hook] || 0) + hooks[hook]; } if (triggered) { break; } else { if (traverse === document || (shadowRootAvailable && (traverse instanceof window.ShadowRoot)) || (parent && parent.__redom_mounted) ) { trigger(traverse, remount ? 'onremount' : 'onmount'); triggered = true; } traverse = parent; } } }; export const trigger = (el, eventName) => { if (eventName === 'onmount' || eventName === 'onremount') { el.__redom_mounted = true; } else if (eventName === 'onunmount') { el.__redom_mounted = false; } const hooks = el.__redom_lifecycle; if (!hooks) { return; } const view = el.__redom_view; let hookCount = 0; view && view[eventName] && view[eventName](); for (const hook in hooks) { if (hook) { hookCount++; } } if (hookCount) { let traverse = el.firstChild; while (traverse) { const next = traverse.nextSibling; trigger(traverse, eventName); traverse = next; } } };
JavaScript
0.000017
@@ -257,16 +257,25 @@ , before +, replace ) =%3E %7B%0A @@ -743,24 +743,111 @@ != null) %7B%0A + if (replace) %7B%0A parentEl.replaceChild(childEl, getEl(before));%0A %7D else %7B%0A parentEl @@ -885,16 +885,22 @@ fore));%0A + %7D%0A %7D else
cc3e762b1155fbae12de6291225cf98884a35de7
Fix in case the user has not signed in
gcf/functions/index.js
gcf/functions/index.js
/** * Copyright 2015 Google Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * For more information on setting up and running this sample code, see * https://developers.google.com/firebase/docs/cloud-functions/writing-functions */ 'use strict'; // [START imports] var Firebase = require('firebase'); var env = require('./env'); var ref = new Firebase(env.get('firebase.database.url')); // [END imports] // [START function] // Makes all new messages ALL UPPERCASE. exports.makeuppercase = function(context, data) { // Read the Firebase database object that triggered the function. var messageRef = ref.child(data.path); console.log('Reading firebase object at path: ' + messageRef.toString()); messageRef.once('value', function(messageData) { // Retrieved the message and uppercase it. console.log('Retrieved message content: ' + JSON.stringify(messageData.val())); var uppercased = messageData.val().text.toUpperCase(); // Saving the uppercased message to DB. console.log('Saving uppercased message: ' + uppercased); messageRef.update({text: uppercased}, context.done); }, context.done); }; // [END function] // [START auth_user] // Makes all new messages ALL UPPERCASE. // We impersonate the user who has made the change that triggered the function. exports.makeuppercaseuserauth = function(context, data) { // Authorize to the Firebase Database as the user. ref.authWithCustomToken(data.authToken, function(error, result) { if (error) { context.done(error); } else { console.log('Authorized successfully with payload: ', result.auth); // Now we access the Database as an authenticated user. exports.makeuppercase(context, data); } }); }; // [END auth_user] // [START auth_admin] // Makes all new messages ALL UPPERCASE. // We authorize to the database as an admin. exports.makeuppercaseadminauth = function(context, data) { // Authorize to the Firebase Database with admin rights. ref.authWithCustomToken(env.get('firebase.database.secret'), function(error, result) { if (error) { context.done(error); } else { console.log('Authorized successfully with admin rights'); // Now we access the Database as an admin. exports.makeuppercase(context, data); } }); }; // [END auth_admin]
JavaScript
0.000115
@@ -1946,18 +1946,172 @@ the user -.%0A + unless he has not signed it.%0A if (!data.authToken) %7B%0A%0A console.log('User has not signed in.');%0A exports.makeuppercase(context, data);%0A%0A %7D else %7B%0A ref.au @@ -2144,32 +2144,33 @@ hToken, function + (error, result) @@ -2163,32 +2163,34 @@ rror, result) %7B%0A + if (error) %7B @@ -2188,32 +2188,34 @@ (error) %7B%0A + context.done(err @@ -2215,32 +2215,34 @@ one(error);%0A + + %7D else %7B%0A c @@ -2226,32 +2226,34 @@ %0A %7D else %7B%0A + console.lo @@ -2307,24 +2307,26 @@ ult.auth);%0A%0A + // Now @@ -2373,32 +2373,34 @@ ted user.%0A + exports.makeuppe @@ -2421,32 +2421,40 @@ data);%0A -%7D%0A + %7D%0A %7D);%0A + %7D%0A %7D;%0A// %5BEND a @@ -2765,32 +2765,24 @@ nction(error -, result ) %7B%0A if (
51f2f1bcbbff7f9a71df79c0da97e8b5f16c5f1f
allow running under chrome but not web app
core/config.js
core/config.js
/** Copyright 2014 Gordon Williams ([email protected]) This Source Code is subject to the terms of the Mozilla Public License, v2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ------------------------------------------------------------------ Central place to store and retrieve Options To use this, on your plugin's `init` function, do something like the following: Espruino.Core.Config.add("MAX_FOOBARS", { section : "Communications", // Heading this will come under in the config screen name : "Foobars", // Nice name description : "How many foobars?", // More detail about this type : "int"/"boolean"/"string"/{ value1:niceName, value2:niceName }, defaultValue : 20, onChange : function(newValue) { ... } }); * onChange will be called whenever the value changes from the default (including when it is loaded) Then use: Espruino.Config.MAX_FOOBARS in your code ------------------------------------------------------------------ **/ "use strict"; (function() { /** See addSection and getSections */ var builtinSections = {}; function _get(callback) { if (typeof chrome !== 'undefined') { chrome.storage.sync.get( "CONFIGS", function (data) { var value = data["CONFIGS"]; console.log("GET chrome.storage.sync = "+JSON.stringify(value)); callback(value); }); } else { callback({}); } } function _set(data) { if (typeof chrome !== 'undefined') { console.log("SET chrome.storage.sync = "+JSON.stringify(data)); chrome.storage.sync.set({ CONFIGS : data }); } } function loadConfiguration(callback) { _get(function (value) { for (var key in value) { if (key=="set") continue; Espruino.Config[key] = value[key]; if (Espruino.Core.Config.data[key] !== undefined && Espruino.Core.Config.data[key].onChange !== undefined) Espruino.Core.Config.data[key].onChange(value[key]); } if (callback!==undefined) callback(); }); } function init() { addSection("General", { sortOrder:100, description: "General Web IDE Settings" }); addSection("Communications", { sortOrder:200, description: "Settings for communicating with the Espruino Board" }); addSection("Board", { sortOrder:300, description: "Settings for the Espruino Board itself" }); } function add(name, options) { Espruino.Core.Config.data[name] = options; if (Espruino.Config[name] === undefined) Espruino.Config[name] = options.defaultValue; } /** Add a section (or information on the page). * options = { * sortOrder : int, // a number used for sorting * description : "", * getHTML : function(callback(html)) // optional * }; */ function addSection(name, options) { options.name = name; builtinSections[name] = options; } /** Get an object containing the information on a section used in configs */ function getSection(name) { if (builtinSections[name]!==undefined) return builtinSections[name]; // not found - but we warned about this in getSections return { name : name }; } /** Get an object containing information on all 'sections' used in all the configs */ function getSections() { var sections = []; // add sections we know about for (var name in builtinSections) sections.push(builtinSections[name]); // add other sections for (var i in Espruino.Core.Config.data) { var c = Espruino.Core.Config.data[i]; var found = false; for (var s in sections) if (sections[s].name == c.section) found = true; if (!found) { console.warn("Section named "+c.section+" was not added with Config.addSection"); sections[c.section] = { name : c.section, sortOrder : 0 }; } } // Now sort by sortOrder sections.sort(function (a,b) { return a.sortOrder - b.sortOrder; }); return sections; } Espruino.Config = {}; Espruino.Config.set = function (key, value) { if (Espruino.Config[key] != value) { Espruino.Config[key] = value; // Do the callback if (Espruino.Core.Config.data[key] !== undefined && Espruino.Core.Config.data[key].onChange !== undefined) Espruino.Core.Config.data[key].onChange(value); // Save to synchronized storage... var data = {}; for (var key in Espruino.Config) if (key != "set") data[key] = Espruino.Config[key]; _set(data); } }; function clearAll() { // clear all settings _set({}); for (var name in Espruino.Core.Config.data) { var options = Espruino.Core.Config.data[name]; Espruino.Config[name] = options.defaultValue; } } Espruino.Core.Config = { loadConfiguration : loadConfiguration, // special - called before init init : init, add : add, data : {}, addSection : addSection, getSection : getSection, getSections : getSections, clearAll : clearAll, // clear all settings }; })();
JavaScript
0.000001
@@ -1254,32 +1254,50 @@ !== 'undefined' + && chrome.storage ) %7B%0A chrome @@ -1595,16 +1595,34 @@ defined' + && chrome.storage ) %7B%0A
06565e805223a8a4048c3edc93550eed13984ce1
create user token id
chrome-stress-aid/static/js/background.js
chrome-stress-aid/static/js/background.js
chrome.runtime.onMessage.addListener(function (msg, sender) { // First, validate the message's structure if ((msg.from === 'content')) { alert(msg.subject); var http = new XMLHttpRequest(); var url = "http://104.198.249.148:5000/updatetemp"; var params = JSON.stringify({ 'account_id': 456, 'message': msg.subject }); http.open("POST", url, true); //Send the proper header information along with the request http.setRequestHeader("Content-type", "application/json"); http.onreadystatechange = function() {//Call a function when the state changes. if(http.readyState == 4 && http.status == 200) { alert(http.responseText); } } http.send(params); } });
JavaScript
0.000002
@@ -735,8 +735,1411 @@ %0A %7D%0A%7D); +%0A%0A%0Afunction getRandomToken() %7B%0A // E.g. 8 * 32 = 256 bits token%0A var randomPool = new Uint8Array(32);%0A crypto.getRandomValues(randomPool);%0A var hex = '';%0A for (var i = 0; i %3C randomPool.length; ++i) %7B%0A hex += randomPool%5Bi%5D.toString(16);%0A %7D%0A // E.g. db18458e2782b2b77e36769c569e263a53885a9944dd0a861e5064eac16f1a%0A return hex;%0A%7D%0A%0Achrome.storage.sync.get('userid', function(items) %7B%0A var userid = items.userid;%0A console.log(userid);%0A if (!userid) %7B%0A userid = getRandomToken();%0A console.log(userid);%0A chrome.storage.sync.set(%7Buserid: userid%7D, function() %7B%0A useToken(userid);%0A %7D);%0A %7D%0A function useToken(userid) %7B%0A // TODO: Use user id for authentication or whatever you want.%0A // Create user on backend%0A var http = new XMLHttpRequest();%0A var url = %22http://104.198.249.148:5000/insertuser%22;%0A var params = JSON.stringify(%7B%0A 'user_id': userid%0A %7D);%0A http.open(%22POST%22, url, true);%0A%0A //Send the proper header information along with the request%0A http.setRequestHeader(%22Content-type%22, %22application/json%22);%0A%0A http.onreadystatechange = function() %7B//Call a function when the state changes.%0A if(http.readyState == 4 && http.status == 200) %7B%0A alert(http.responseText);%0A %7D%0A %7D%0A http.send(params);%0A %7D%0A%7D);
da2aa10757682723a3330fea79afd1a142f69cd0
correct GAE login fields
Dashboard/tests/casperjs/lib/loginGAE.js
Dashboard/tests/casperjs/lib/loginGAE.js
// login module // exports.login = function(username, password) { casper.test.comment("Login in with username \"" + username + "\", password \"" + password + "\""); casper.start(casper.cli.get("url") + "/login", function() { return this.test.assertExists('form#gaia_login', 'FLOW GAE Login Found'); }); casper.then(function() { this.fill('form#gaia_loginform', { username: '[email protected]', password: 'R4inDr0p!' }, true); casper.this.getPasses(); // casper.testrail.postResults(); // this.sendKeys("input[name=username]", username); // this.sendKeys("input[name=password]", password); // return this.click("input[type=submit]"); }); return casper.then(function() {}); };
JavaScript
0.000001
@@ -419,24 +419,31 @@ %7B%0A%09%09%09%09%09 +Email: username : 'akvoq @@ -438,36 +438,16 @@ name -: '[email protected]' ,%0A%09%09%09%09%09 -p +P assw
85a7c745be1170332d21bb80e83cef1f1302e262
Add getAll in config
src/config.js
src/config.js
import fs from 'fs'; import u from 'url'; class Config { _cache = {}; constructor() { this._dir = process.env.NODE_CONFIG_DIR || process.cwd() + '/config'; } // Set config dir set dir(dir) { this._dir = dir; } // Get config get(arg) { if (!this._cache[arg]) { if (Number.isInteger(arg)) { // support id in filename (ex: configfile-<id>.js) this._cache[arg] = this._getById(arg); } else if (arg.indexOf('http') !== -1) { // support url (will look for the url property in all config files) this._cache[arg] = this._getByUrl(arg); } else if (arg.indexOf('/') !== -1) { // support full path of file (ex: /home/user/config.js) this._cache[arg] = this._parse(arg); } else { // support recursive search for config file in dir. return first found (ex: configfile.js) this._cache[arg] = this._getByFile(arg); } } return this._cache[arg]; } // Get config by id. Match id with all files found in _getFiles _getById(id) { this._init(); for (let file of this._files) { let match = file.match(/-(\d+)\./); if (match && match[1] == id) { return this._parse(file); } } return false; } // Get config by filename. Match file with all files found in _getFiles _getByFile(file) { this._init(); for (let f of this._files) { if (f.indexOf(file) > -1) { return this._parse(f); } } return false; } // Get config by url. Open all files found in _getFiles and look at the url property _getByUrl(url) { this._init(); let hostname = u.parse(url).hostname; for (let file of this._files) { let config = this._parse(file); if (config && config.url && hostname == u.parse(config.url).hostname) { return config; } } return false; } // Get filenames _init() { if (!this._files) { this._files = this._getFiles(this._dir); } } // Open and parse file _parse(file) { var match = file.match(/.*\.([^.]*)$/); if (match[1] == 'json') { return JSON.parse(fs.readFileSync(file).toString()); } else if (match[1] == 'js') { return require(file); } else { return false; } } // Recursivly find all filenames _getFiles(dir) { let files = []; for (let file of fs.readdirSync(dir)) { if (fs.statSync(dir + '/' + file).isDirectory()) { files = files.concat(this._getFiles(dir + '/' + file)); } else { files.push(dir + '/' + file); } }; return files; } } const config = new Config(); export default config;
JavaScript
0.000001
@@ -1022,32 +1022,425 @@ he%5Barg%5D;%0A %7D%0A%0A + // Get config%0A getAll() %7B%0A if (!this._cache.all) %7B%0A this._init();%0A let all = %5B%5D;%0A for (let file of this._files) %7B%0A let config = this._parse(file);%0A if (config) %7B%0A all.push(config);%0A %7D%0A %7D%0A this._cache.all = all;%0A %7D%0A return this._cache.all;%0A %7D%0A%0A // Get confi
d4f60c6f69ecc2e2d8b5c899ea0ff6dd45f28258
Update consts.js
src/consts.js
src/consts.js
var globals = require('./globals'); var consts = module.exports = {}; consts.encodingTypes = [X, Y, ROW, COL, SIZE, SHAPE, COLOR, ALPHA, TEXT]; consts.dataTypes = {"O": O, "Q": Q, "T": T}; consts.dataTypeNames = ["O","Q","T"].reduce(function(r,x) { r[consts.dataTypes[x]] = x; return r; },{}); consts.DEFAULTS = { //small multiples cellHeight: 200, // will be overwritten by bandWidth cellWidth: 200, // will be overwritten by bandWidth cellPadding: 0.1, cellBackgroundColor: "#fdfdfd", xAxisMargin: 80, yAxisMargin: 0, textCellWidth: 90, // marks bandSize: 21, bandPadding: 1, strokeWidth: 2, // scales timeScaleNice: "day", timeScaleLabelLength: 3 };
JavaScript
0
@@ -636,32 +636,8 @@ les%0A - timeScaleNice: %22day%22,%0A ti @@ -660,8 +660,9 @@ th: 3%0A%7D; +%0A
e5d841d8d5969af4dae1c0952bd6c63ba8bcab93
allow slashes(/) in Product names
offenerhaushalt/static/js/budget.js
offenerhaushalt/static/js/budget.js
$(function(){ var site = JSON.parse($('#site-config').html()), embedTemplate = Handlebars.compile($('#embed-template').html()); $embedCode = $('#embed-code') baseFilters = {}; $.each(site.filters, function(i, f) { baseFilters[f.field] = f.default; }); var $hierarchyMenu = $('#hierarchy-menu'), $infobox = $('#infobox'), $parent = $('#parent'), $filterValues = $('.site-filters .value'), treemap = new OSDE.TreeMap('#treemap'), table = new OSDE.Table('#table'); function getData(drilldown, cut) { var cutStr = $.map(cut, function(v, k) { if((v+'').length) { return site.keyrefs[k] + ':' + v; }}); var drilldowns = [site.keyrefs[drilldown]] if (site.keyrefs[drilldown] != site.labelrefs[drilldown]) { drilldowns.push(site.labelrefs[drilldown]); } return $.ajax({ url: site.api + '/aggregate', data: { drilldown: drilldowns.join('|'), cut: cutStr.join('|'), order: site.aggregate + ':desc', page: 0, pagesize: 500 }, dataType: 'json', cache: true }); } $('#infobox-toggle').click(function(e) { var $e = $(e.target); if ($e.hasClass('active')) { $e.removeClass('active'); $infobox.slideUp(); } else { $e.addClass('active'); $infobox.slideDown(); } return false; }); function parsePath(hash) { var path = {}, location = hash.split('/'), levels = location.slice(1, location.length-1); path.hierarchyName = location[0]; path.hierarchy = site.hierarchies[path.hierarchyName]; path.hierarchy.cuts = path.hierarchy.cuts || {}; path.level = levels.length; path.root = path.level == 0; path.bottom = path.level >= (path.hierarchy.drilldowns.length - 1); path.drilldown = path.hierarchy.drilldowns[path.level]; path.args = OSDE.parseArgs(location[location.length-1]); $.each(levels, function(i, val) { path.args[path.hierarchy.drilldowns[i]] = decodeURIComponent(val); }); return path; } function parentUrl(path) { if (path.level < 1) { return makeUrl(path, null); } var p = $.extend(true, {}, path); $.each(p.hierarchy.drilldowns, function(i, drilldown) { if (i >= (p.level-1) ) { delete p.args[drilldown]; } }); return makeUrl(p, {}); } function makeUrl(path, modifiers) { var args = $.extend({}, path.args, modifiers), url = '#' + path.hierarchyName + '/'; if (!modifiers) args = {}; $.each(path.hierarchy.drilldowns, function(i, drilldown) { if (args[drilldown]) { url += args[drilldown] + '/'; delete args[drilldown]; } }); return url + OSDE.mergeArgs(args); } function update() { var rawPath = window.location.hash.substring(1); if (!rawPath.length) { rawPath = site.default + '/' } var path = parsePath(rawPath), rootDimension = path.hierarchy.drilldowns[0], rootColor = null; color = d3.scale.ordinal().range(OSDE.categoryColors), cuts = $.extend({}, baseFilters, path.hierarchy.cuts || {}, path.args); $hierarchyMenu.find('.btn').removeClass('active'); $hierarchyMenu.find('.btn.' + path.hierarchyName).addClass('active'); $parent.unbind(); if (path.root) { $parent.hide(); } else { $parent.show(); $parent.attr('href', parentUrl(path)); } $filterValues.removeClass('active'); $filterValues.each(function(i, f) { var $f = $(f), field = $f.data('field'), value = $f.data('value'), modifiers = {}; modifiers[field] = value; $f.attr('href', makeUrl(path, modifiers)); if (cuts[field] == value) { $f.addClass('active'); } }); $.each(site.filters, function(i, f) { var val = cuts[f.field], label = val; $.each(f.values, function(j, v) { if (v.key == val) { label = v.label; } }); $('.site-filters strong[data-field="' + f.field + '"]').html(label || 'Alle'); }); var baseCuts = $.extend({}, baseFilters, path.hierarchy.cuts); getData(rootDimension, baseCuts).done(function(base) { $.each(base.cells, function(i, drilldown) { drilldown._color = color(i); var rootRef = site.keyrefs[rootDimension]; if (cuts[rootDimension] && cuts[rootDimension] == drilldown[rootRef]) { rootColor = d3.rgb(drilldown._color); } }); getData(path.drilldown, cuts).done(function(data) { var dimension = path.drilldown; if (dimension != rootDimension) { color = d3.scale.linear(); color = color.interpolate(d3.interpolateRgb) color = color.range([rootColor.brighter(), rootColor.darker().darker()]); color = color.domain([data.total_cell_count, 0]); } data.summary._value = data.summary[site.aggregate]; data.summary._value_fmt = OSDE.amount(data.summary._value); $.each(data.cells, function(e, cell) { cell._current_label = cell[site.labelrefs[dimension]]; cell._current_key = cell[site.keyrefs[dimension]]; cell._value = cell[site.aggregate]; cell._value_fmt = OSDE.amount(cell._value); cell._percentage = cell[site.aggregate] / data.summary[site.aggregate]; cell._small = cell._percentage < 0.01; cell._percentage_fmt = (cell._percentage * 100).toFixed(2) + '%'; cell._percentage_fmt = cell._percentage_fmt.replace('.', ','); if (!path.bottom) { var modifiers = {}; modifiers[dimension] = cell._current_key; cell._url = makeUrl(path, modifiers); } else { cell._no_url = true; } cell._color = color(e); }); treemap.render(data, path.drilldown); table.render(data, path.drilldown); }); }); $embedCode.text(embedTemplate({ name: site.name, baseurl: document.location.href.split('#')[0], url: document.location.href, hash: document.location.hash, })); } hashtrack.onhashchange(update); });
JavaScript
0.000027
@@ -2660,16 +2660,35 @@ illdown%5D +.replace('/','%252F') + '/';%0A
8cbd4cdb45c854937a45b1d1c437b6bccf634ce5
Version number change, primarily for meeting clarity.
CareWheels/www/js/app.js
CareWheels/www/js/app.js
// Ionic Starter App // angular.module is a global place for creating, registering and retrieving Angular modules // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html) // the 2nd parameter is an array of 'requires' angular.module('careWheels', [ 'ionic', 'ui.router', 'ngCordova', 'FredrikSandell.worker-pool', 'angularMoment', 'careWheels.fileloggermodule' ]) //contant definition for endpoint base url .constant('BASE_URL', 'https://carewheels.cecs.pdx.edu:8443') // change the version number here .constant('VERSION_NUMBER', '0.03') .run(function ($rootScope, $ionicPlatform, $ionicHistory, $state, $window, User) { // window.localStorage['loginCredentials'] = null; $rootScope.$on('$stateChangeStart', function (event, next, nextParams, fromState) { console.log('state change'); if (User.credentials() === null) { if (next.name !== 'login') { event.preventDefault(); $state.go('login'); } } }); $ionicPlatform.registerBackButtonAction(function (event) { console.log("in registerbackbutton"); console.log($ionicHistory.backTitle()); $state.go($ionicHistory.backTitle()); }, 100); $ionicPlatform.ready(function () { if (window.cordova && window.cordova.plugins.Keyboard) { cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true); cordova.plugins.Keyboard.disableScroll(true); } if (window.StatusBar) { StatusBar.styleDefault(); } }); }) // API factory for making all php endpoints globally accessible. .factory('API', function (BASE_URL) { var api = { userAndGroupInfo: BASE_URL + '/userandgroupmemberinfo.php', userInfo: BASE_URL + '/userinfo.php', updateUserReminders: BASE_URL + '/updateuserreminders.php', groupMemberInfo: BASE_URL + '/groupmemberinfo.php', updateLastOwnership: BASE_URL + '/updatelastownershiptakentime.php', creditUser: BASE_URL + '/credituser.php', updateSettings:BASE_URL + '/updatesettings.php' }; return api; }) .controller('menu', function ($scope, $state, VERSION_NUMBER) { $scope.versionNumber = VERSION_NUMBER; $scope.clickGroup = function () { $state.go('app.groupStatus'); }; $scope.clickReminders = function () { $state.go('app.reminders'); }; $scope.clickSettings = function () { $state.go('app.settings'); }; $scope.clickTests = function () { $state.go('app.tests'); }; });
JavaScript
0
@@ -592,17 +592,17 @@ R', '0.0 -3 +4 ')%0A%0A.run
cb33a14b3ddd1a1d84d35521a353c2872dad4cee
remove version from src code
src/cookie.js
src/cookie.js
define(function(require, exports) { // Cookie // ------------- // Thanks to: // - http://www.nczonline.net/blog/2009/05/05/http-cookies-explained/ // - http://developer.yahoo.com/yui/3/cookie/ var Cookie = exports; Cookie.version = '1.0.2'; var decode = decodeURIComponent; var encode = encodeURIComponent; /** * Returns the cookie value for the given name. * * @param {String} name The name of the cookie to retrieve. * * @param {Function|Object} options (Optional) An object containing one or * more cookie options: raw (true/false) and converter (a function). * The converter function is run on the value before returning it. The * function is not used if the cookie doesn't exist. The function can be * passed instead of the options object for conveniently. When raw is * set to true, the cookie value is not URI decoded. * * @return {*} If no converter is specified, returns a string or undefined * if the cookie doesn't exist. If the converter is specified, returns * the value returned from the converter. */ Cookie.get = function(name, options) { validateCookieName(name); if (typeof options === 'function') { options = { converter: options }; } else { options = options || {}; } var cookies = parseCookieString(document.cookie, !options['raw']); return (options.converter || same)(cookies[name]); }; /** * Sets a cookie with a given name and value. * * @param {string} name The name of the cookie to set. * * @param {*} value The value to set for the cookie. * * @param {Object} options (Optional) An object containing one or more * cookie options: path (a string), domain (a string), * expires (number or a Date object), secure (true/false), * and raw (true/false). Setting raw to true indicates that the cookie * should not be URI encoded before being set. * * @return {string} The created cookie string. */ Cookie.set = function(name, value, options) { validateCookieName(name); options = options || {}; var expires = options['expires']; var domain = options['domain']; var path = options['path']; if (!options['raw']) { value = encode(String(value)); } var text = name + '=' + value; // expires var date = expires; if (typeof date === 'number') { date = new Date(); date.setDate(date.getDate() + expires); } if (date instanceof Date) { text += '; expires=' + date.toUTCString(); } // domain if (isNonEmptyString(domain)) { text += '; domain=' + domain; } // path if (isNonEmptyString(path)) { text += '; path=' + path; } // secure if (options['secure']) { text += '; secure'; } document.cookie = text; return text; }; /** * Removes a cookie from the machine by setting its expiration date to * sometime in the past. * * @param {string} name The name of the cookie to remove. * * @param {Object} options (Optional) An object containing one or more * cookie options: path (a string), domain (a string), * and secure (true/false). The expires option will be overwritten * by the method. * * @return {string} The created cookie string. */ Cookie.remove = function(name, options) { options = options || {}; options['expires'] = new Date(0); return this.set(name, '', options); }; function parseCookieString(text, shouldDecode) { var cookies = {}; if (isString(text) && text.length > 0) { var decodeValue = shouldDecode ? decode : same; var cookieParts = text.split(/;\s/g); var cookieName; var cookieValue; var cookieNameValue; for (var i = 0, len = cookieParts.length; i < len; i++) { // Check for normally-formatted cookie (name-value) cookieNameValue = cookieParts[i].match(/([^=]+)=/i); if (cookieNameValue instanceof Array) { try { cookieName = decode(cookieNameValue[1]); cookieValue = decodeValue(cookieParts[i] .substring(cookieNameValue[1].length + 1)); } catch (ex) { // Intentionally ignore the cookie - // the encoding is wrong } } else { // Means the cookie does not have an "=", so treat it as // a boolean flag cookieName = decode(cookieParts[i]); cookieValue = ''; } if (cookieName) { cookies[cookieName] = cookieValue; } } } return cookies; } // Helpers function isString(o) { return typeof o === 'string'; } function isNonEmptyString(s) { return isString(s) && s !== ''; } function validateCookieName(name) { if (!isNonEmptyString(name)) { throw new TypeError('Cookie name must be a non-empty string'); } } function same(s) { return s; } })();
JavaScript
0.000001
@@ -240,38 +240,8 @@ rts; -%0A Cookie.version = '1.0.2'; %0A%0A
2b3a2c0b847acfff72edea2c7df79f282a4ec500
fix typo
src/cursor.js
src/cursor.js
// @flow import EventEmitter from 'events'; import * as dom from './dom'; import { Css } from './consts'; import logger from './logger'; import HighlightMarkers from './highlightmarkers'; import type { ScrollToCallback } from './typedefs'; export type IterableQueries = string | Array<string>; /** * Class responsible for managing the state of the highlight cursor * * Emits the following events: * * - clear: cursor position is cleared * - setiterable: allowable iterable queries set or cleared * - update: cursor position mutated */ class Cursor extends EventEmitter { markers: HighlightMarkers; index: number; iterableQueries: Array<string> | null; total: number; /** * Class constructor * * @param {HighlightMarkers} markers - Reference to highlight markers object */ constructor(markers: HighlightMarkers) { super(); this.markers = markers; this.index = -1; this.iterableQueries = null; this.total = 0; this.setIterableQueries(null); } /** * Clear the current cursor state and recalculate number of total iterable highlights */ clear(): void { this.clearActive_(); this.index = -1; this.update(true); this.emit('clear'); } /** * Set or clear the query sets that the cursor can move through * * When one or more query sets are specified, cursor movement is restricted to the specified * query sets. When setting the cursor offset, the offset will then apply within the context of * the active iterable query sets. * * The restriction can be lifted at any time by passing `null` to the method. * * @param {IterableQueries | null} queries - An array (or string) containing the query set names * or `null` if all query-sets active. */ setIterableQueries(queries: IterableQueries | null): void { if (queries == null) { this.iterableQueries = null; } else if (typeof queries === 'string') { this.iterableQueries = [queries]; } else { this.iterableQueries = queries.slice(); } this.clear(); this.emit('setiterable', queries); } /** * Update the total of iterable highlights * * Causes recomputation of the total available number of highlights and the update event to be * produced if this number changes. The event can be forcefully produced it `force` is set to * `true`. * * @param { boolean } force - When `true` causes the "update" event to always be emitted */ update(force: boolean = false): void { const total = this.markers.calculateTotal(this.iterableQueries); if (force || total !== this.total) { this.total = total; this.emit('update', this.index, this.total); } } /** * Set cursor to query referenced by absolute query index * * @param {number} index - Virtual cursor index * @param {boolean} dontRecurse - When `true` instructs the method not to employ recursion * @param {ScrollToCallback} scrollTo - Optional custom function to invoke if highlight being * moved to is not visible on the page * * @returns {boolean} `true` if move occurred */ set(index: number, dontRecurse: boolean, scrollTo?: ScrollToCallback): boolean { if (index < 0) { throw new Error('Invalid cursor index specified: ' + index); } const marker = this.markers.find(index, this.iterableQueries); // If index overflown, set to first highlight if (marker == null) { if (!dontRecurse) { return this.set(0, true); } return false; } // Clear currently active highlight, if any, and set requested highlight active this.clearActive_(); const coll = dom.getHighlightElements(marker.id); // Scroll viewport if element not visible if (coll.length > 0) { dom.addClass(coll, Css.enabled); const first = coll[0]; if (scrollTo === 'function') { try { scrollTo(first); } catch (x) { logger.error('failed to scroll to highlight:', x); } } else if (!dom.isInView(first)) { dom.scrollIntoView(first); } } if (this.index === index) { return false; } this.index = index; this.emit('update', index, this.total); return true; } /** * Move cursor position to the previous query in the active query set * * If the cursor moves past the first query in the active query set, the active query set moves * to the previous available one and the cursor position to its last query. If the current query * set is the first in the collection and thus it is not possible to move to the previous query * set, the last query set is made active instead, thus ensuring that the cursor always rolls * over. */ prev(): void { if (this.total > 0) { this.set((this.index < 1 ? this.total : this.index) - 1, false); } } /** * Move cursor position to the next query in the active query set * * If the cursor moves past the last query in the active query set, the active query set moves to * the next available one and the cursor position to its first query. If the current query set * is the last in the collection and thus it is not possible to move to the next query set, the * first query set is made active instead, thus ensuring that the cursor always rolls over. */ next(): void { this.set(this.index + 1, false); } // Private interface // ----------------- /** * Clear the currently active cursor highlight * * The active cursor highlight is the element or elements at the current cursor position. * @access private */ clearActive_(): void { const { enabled: cssEnabled } = Css; for (const el of dom.getAllHighlightElements(cssEnabled)) { dom.removeClass(el, cssEnabled); } } } export default Cursor;
JavaScript
0.999999
@@ -3843,16 +3843,23 @@ if ( +typeof scrollTo
f3ffa4fb62c2d941ce32f019ae277375b003a061
Set Custos RootStaffPos updates pname/oct
src/custos.js
src/custos.js
/* Copyright (C) 2011 by Gregory Burlet, Alastair Porter 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. */ /** * Creates a new custos * * @class Models a custos, a neume at the end of a staff that represents the first * note in the next staff. * @param {String} pname pitch name of the next note * @param {Integer} oct octave of the next note */ Toe.Model.Custos = function(pname, oct, options) { this.props = { interact: true }; $.extend(this.props, options); this.pname = pname; this.oct = oct; // the integer pitch difference relative to the clef // this is set when the custos is mounted on a staff this.rootStaffPos = null; // initialize bounding box this.zone = new Object(); // set by server or MEI so null by default this.id = null; // reference to the staff this custos is mounted on this.staff = null; } Toe.Model.Custos.prototype.constructor = Toe.Model.Custos; /** * Sets the bounding box of the custos * * @methodOf Toe.Model.Custos * @param {Array} bb [ulx, uly, lrx, lry] */ Toe.Model.Custos.prototype.setBoundingBox = function(bb) { if(!Toe.validBoundingBox(bb)) { throw new Error("Division: invalid bounding box"); } bb = $.map(bb, Math.round); this.zone.ulx = bb[0]; this.zone.uly = bb[1]; this.zone.lrx = bb[2]; this.zone.lry = bb[3]; } /** * Sets the id of the custos element. * * @methodOf Toe.Model.Custos * @param {String} id */ Toe.Model.Custos.prototype.setID = function(cid) { this.id = cid; } Toe.Model.Custos.prototype.setStaff = function(staff) { if (!(staff instanceof Toe.Model.Staff)) { throw new Error("Custos: invalid staff reference"); } this.staff = staff; } /** * Sets the pitch name and octave of the custos * * @methodOf Toe.Model.Custos * @param {String} pname pitch name * @param {Integer} oct octave */ Toe.Model.Custos.prototype.setRootNote = function(pname, oct) { this.pname = pname; this.oct = oct; } /** * Sets the pitch difference of the custos in relation to the clef of the staff the * custos is mounted on */ Toe.Model.Custos.prototype.setRootStaffPos = function(staffPos) { // only redraw the glyph if it needs to be redrawn if (this.rootStaffPos == staffPos) { return; } // reset staff position of custos this.rootStaffPos = staffPos; $(this).trigger("vUpdateStaffPosition", [this]); } /** * Select custos on the drawing surface */ Toe.Model.Custos.prototype.selectDrawing = function() { $(this).trigger("vSelectDrawing"); } /** * Erase the custos on the drawing surface */ Toe.Model.Custos.prototype.eraseDrawing = function() { $(this).trigger("vEraseDrawing"); }
JavaScript
0
@@ -3365,16 +3365,220 @@ ffPos;%0A%0A + var actingClef = this.staff.getActingClefByEle(this);%0A var pitchInfo = this.staff.calcPitchFromStaffPos(this.rootStaffPos, actingClef);%0A this.setRootNote(pitchInfo%5B%22pname%22%5D, pitchInfo%5B%22oct%22%5D);%0A%0A $(th @@ -3622,17 +3622,16 @@ this%5D);%0A -%0A %7D%0A%0A/**%0A
cb64c22792587791ad34c76a3e15ace175215756
stop requesting when there is no data received last time
infinitescroll.js
infinitescroll.js
(function($){ $.fn.infinitescroll = function(options) { var states = { curPage: 1, processing: false } var options = $.extend({ thresholdPx: 100, ajaxType: "POST", url: "", dataType: "html", data: {}, callback: function(data, textStatus, jqXHR) { this.append(data) } }, options) this.scroll(function(e){ var scrollHeight = $(e.target).scrollTop() var height = $(e.target).height() if (height - scrollHeight < options.thresholdPx && !states.processing ) { states.curPage = states.curPage + 1 $.ajax({ url: options.url, type: options.ajaxType, dataType: options.dataType, data: $.extend({page: states.curPage}, options.data), beforeSend: function() { states.processing = true }, complete: function() { states.processing = false }, success: options.callback }) } }) } }(jQuery))
JavaScript
0
@@ -107,25 +107,49 @@ ssing: false +,%0A lastPage: false, %0A - %7D%0A%0A v @@ -573,16 +573,35 @@ cessing +&& !states.lastPage ) %7B%0A @@ -977,16 +977,17 @@ = false%0A +%0A @@ -1009,16 +1009,153 @@ success: + %5Bfunction(data, textStatus, jqXHR) %7B%0A if (data.length == 0) %7B%0A states.lastPage = true%0A %7D%0A %7D, options @@ -1163,16 +1163,17 @@ callback +%5D %0A
d254a30240fff0151a849f75e97d6af12011be94
Streamline deploy:rollback
src/deploy.js
src/deploy.js
var DeployMutex = require('./deploy-mutex'); var deployMutex = new DeployMutex(); module.exports = function(robot) { robot.respond(/deploy pending ([^\s]+) ([^\s]+)$/i, function(chat) { if (deployMutex.hasJob()) { chat.send('Deploy job can not be started because ' + (deployMutex.getJob()) + ' is in progress'); return; } var app = chat.match[1]; var env = chat.match[2]; chat.send('Getting changes…'); var job = pulsarApi.createJob(app, env, 'deploy:pending'); deployMutex.setJob(job, chat); job.on('success', function() { return chat.send('Pending changes for ' + this.app + ' ' + this.env + ':\n' + this.data.stdout); }).on('error', function(error) { chat.send('Pending changes failed: ' + (JSON.stringify(error))); if (this.data.url) { return chat.send('More info: ' + this.data.url); } }); pulsarApi.runJob(job); }); robot.respond(/deploy ([^\s]+) ([^\s]+)$/i, function(chat) { if (!robot.userHasRole(chat, 'deployer')) { return; } if (deployMutex.hasJob()) { chat.send('Deploy job can not be started because ' + (deployMutex.getJob()) + ' is in progress'); return; } var app = chat.match[1]; var env = chat.match[2]; chat.send('Getting changes…'); var deployJob = pulsarApi.createJob(app, env, 'deploy'); deployMutex.setJob(deployJob, chat); deployJob.on('create', function() { return chat.send('Deployment started: ' + this.data.url); }).on('success', function() { return chat.send('Deployment finished.'); }).on('error', function(error) { return chat.send('Deployment failed: ' + (JSON.stringify(error))); }); var pendingJob = pulsarApi.createJob(app, env, 'deploy:pending'); pendingJob.on('success', function() { deployJob.taskVariables = { revision: this.taskVariables.revision }; chat.send('Pending changes for ' + this.app + ' ' + this.env + ':\n' + this.data.stdout); return chat.send('Say "CONFIRM DEPLOY" or "CANCEL DEPLOY".'); }).on('error', function(error) { deployJob.emit('error', error); if (this.data.url) { return chat.send('More info: ' + this.data.url); } }); var showNextRevisionJob = pulsarApi.createJob(app, env, 'deploy:show_next_revision'); showNextRevisionJob.on('success', function() { var revision; if (!this.data.stdout || !this.data.stdout.trim()) { this.emit('error', new Error('Cannot retrieve revision number.')); return; } revision = this.data.stdout.trim(); pendingJob.taskVariables = { revision: revision }; return pulsarApi.runJob(pendingJob); }).on('error', function(error) { deployJob.emit('error', error); if (this.data.url) { return chat.send('More info: ' + this.data.url); } }); pulsarApi.runJob(showNextRevisionJob); }); robot.respond(/confirm deploy$/i, function(chat) { if (!robot.userHasRole(chat, 'deployer')) { return; } var job = deployMutex.getJob(); if (!job || 'deploy' != job.task) { chat.send('No deploy job to confirm'); return; } pulsarApi.runJob(job); chat.send('Deployment confirmed.'); }); robot.respond(/cancel deploy$/i, function(chat) { if (!robot.userHasRole(chat, 'deployer')) { return; } var job = deployMutex.getJob(); if (!job || 'deploy' != job.task) { chat.send('No deploy job to cancel'); return; } chat.send('Deployment cancelled.'); deployMutex.removeJob(); }); robot.respond(/deploy rollback ([^\s]+) ([^\s]+)$/i, function(chat) { var app = chat.match[1]; var env = chat.match[2]; if (deployMutex.hasJob()) { chat.send("Deploy rollback can not be started because " + (deployMutex.getJob()) + " is in progress"); return; } chat.send("Rolling back the previous deploy…"); var job = pulsarApi.createJob(app, env, 'deploy:rollback'); job.on('success', function() { chat.send("Successfully rolled back deploy for " + this.app + " " + this.env); if (this.data.stdout) { return chat.send("" + this.data.stdout); } }) .on('error', function(error) { chat.send("Deploy rollback failed: " + (JSON.stringify(error))); if (this.data.url) { return chat.send("More info: " + this.data.url); } }); pulsarApi.runJob(job); }); };
JavaScript
0
@@ -3685,24 +3685,92 @@ ion(chat) %7B%0A + if (!robot.userHasRole(chat, 'deployer')) %7B%0A return;%0A %7D%0A var app @@ -4090,24 +4090,59 @@ rollback');%0A + deployMutex.setJob(job, chat);%0A job.on('
2654d8ce8f61b77083929556be748941e6101146
Fix localization
activities/Abacus.activity/js/activity.js
activities/Abacus.activity/js/activity.js
define(["sugar-web/activity/activity",'easeljs','tweenjs','activity/game','activity/standardabacus','activity/standardabacuscolumn','activity/abacusbead','activity/onecolumnabacus','activity/posnegcolumn'], function (act) { // Manipulate the DOM only when it is ready. requirejs(['domReady!'], function (doc) { // Initialize the activity. requirejs(["sugar-web/env","sugar-web/datastore","fraction","activity/abacuspalette","activity/custompalette","tutorial","webL10n"], function(env,datastore,fraction,abacuspalette,custompalette,tutorial,webL10n) { act.setup(); env.getEnvironment(function(err, environment) { currentenv = environment; // Set current language to Sugarizer var defaultLanguage = (typeof chrome != 'undefined' && chrome.app && chrome.app.runtime) ? chrome.i18n.getUILanguage() : navigator.language; var language = environment.user ? environment.user.language : defaultLanguage; webL10n.language.code = language; }); act.getXOColor(function (error, colors) { runactivity(act,doc,colors,env,datastore,fraction,abacuspalette,custompalette,tutorial); }); }); }); }); function runactivity(act,doc,colors,env,datastore,fraction,abacuspalette,custompalette,tutorial){ var canvas; var stage; var g; var e; function init(){ canvas = document.getElementById('actualcanvas'); canvas.width = window.innerWidth; canvas.height = window.innerHeight-55; stage = new createjs.Stage(canvas); stage.update(); stage.mouseEventsEnabled = true; createjs.Touch.enable(stage); createjs.Ticker.setFPS(30); createjs.Ticker.addEventListener("tick", handleTick); function handleTick() { stage.update(); } var g = new Game(act,stage,colors,fraction,doc,abacuspalette,custompalette,datastore); setTimeout(function(){ g.init(); }, 500); window.addEventListener('activityStop', function (eve) { eve.preventDefault(); g.stop(); }); document.getElementById('fullscreen-button').addEventListener('click', () => { document.getElementById("main-toolbar").style.opacity = 0; document.getElementById("canvas").style.top = "0px"; document.getElementById("unfullscreen-button").style.visibility = "visible"; resizeCanvas(); }); document.getElementById("unfullscreen-button").addEventListener('click', () => { document.getElementById("main-toolbar").style.opacity = 1; document.getElementById("canvas").style.top = "55px"; document.getElementById("unfullscreen-button").style.visibility = "hidden"; resizeCanvas(); }); window.addEventListener('resize', resizeCanvas, false); function resizeCanvas() { if (document.getElementById("unfullscreen-button").style.visibility === "hidden") { canvas.width = window.innerWidth; canvas.height = window.innerHeight-55; g.resize(); } else { canvas.width = window.innerWidth; canvas.height = window.innerHeight; g.resize(); } } var clearButton = doc.getElementById("clear-button"); clearButton.addEventListener('click', function (a) { g.clear(); }); var copyButton = doc.getElementById("copy-button"); copyButton.addEventListener('click', function (a) { g.copy(); }); // Launch tutorial document.getElementById("help-button").addEventListener('click', function(e) { tutorial.start(); }); } init(); }
JavaScript
0.000001
@@ -923,16 +923,140 @@ ge;%0A%09%09%09%09 +window.addEventListener('localized', function(e) %7B%0A%09%09%09%09%09if (e.language != language) %7B%0A%09%09%09%09%09%09setTimeout(function() %7B%0A%09%09%09%09%09%09 webL10n. @@ -1081,16 +1081,45 @@ nguage;%0A +%09%09%09%09%09%09%7D, 50);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D);%0A %09%09%09%7D);%0A%09
6ef15806dd51bafd0a52cb9726c64ced798cb151
Fix #211: keep undo states (#212)
src/editor.js
src/editor.js
import * as monaco from 'monaco-editor/esm/vs/editor/editor.api'; import PropTypes from 'prop-types'; import React from 'react'; import { processSize } from './utils' function noop() { } class MonacoEditor extends React.Component { constructor(props) { super(props); this.containerElement = undefined; this.__current_value = props.value; } componentDidMount() { this.initMonaco(); } componentDidUpdate(prevProps) { if (this.props.value !== this.__current_value) { // Always refer to the latest value this.__current_value = this.props.value; // Consider the situation of rendering 1+ times before the editor mounted if (this.editor) { this.__prevent_trigger_change_event = true; this.editor.setValue(this.__current_value); this.__prevent_trigger_change_event = false; } } if (prevProps.language !== this.props.language) { monaco.editor.setModelLanguage(this.editor.getModel(), this.props.language); } if (prevProps.theme !== this.props.theme) { monaco.editor.setTheme(this.props.theme); } if ( this.editor && (this.props.width !== prevProps.width || this.props.height !== prevProps.height) ) { this.editor.layout(); } if (prevProps.options !== this.props.options) { this.editor.updateOptions(this.props.options) } } componentWillUnmount() { this.destroyMonaco(); } assignRef = (component) => { this.containerElement = component; }; destroyMonaco() { if (typeof this.editor !== 'undefined') { this.editor.dispose(); } } initMonaco() { const value = this.props.value !== null ? this.props.value : this.props.defaultValue; const { language, theme, options } = this.props; if (this.containerElement) { // Before initializing monaco editor Object.assign(options, this.editorWillMount()); this.editor = monaco.editor.create(this.containerElement, { value, language, ...options }); if (theme) { monaco.editor.setTheme(theme); } // After initializing monaco editor this.editorDidMount(this.editor); } } editorWillMount() { const { editorWillMount } = this.props; const options = editorWillMount(monaco); return options || {}; } editorDidMount(editor) { this.props.editorDidMount(editor, monaco); editor.onDidChangeModelContent((event) => { const value = editor.getValue(); // Always refer to the latest value this.__current_value = value; // Only invoking when user input changed if (!this.__prevent_trigger_change_event) { this.props.onChange(value, event); } }); } render() { const { width, height } = this.props; const fixedWidth = processSize(width); const fixedHeight = processSize(height); const style = { width: fixedWidth, height: fixedHeight }; return <div ref={this.assignRef} style={style} className="react-monaco-editor-container" />; } } MonacoEditor.propTypes = { width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), value: PropTypes.string, defaultValue: PropTypes.string, language: PropTypes.string, theme: PropTypes.string, options: PropTypes.object, editorDidMount: PropTypes.func, editorWillMount: PropTypes.func, onChange: PropTypes.func }; MonacoEditor.defaultProps = { width: '100%', height: '100%', value: null, defaultValue: '', language: 'javascript', theme: null, options: {}, editorDidMount: noop, editorWillMount: noop, onChange: noop }; export default MonacoEditor;
JavaScript
0
@@ -159,17 +159,18 @@ ./utils' +; %0A - %0Afunctio @@ -762,37 +762,240 @@ tor. -setValue(this.__current_value +pushUndoStop();%0A this.editor.executeEdits('', %5B%7B%0A range: this.editor.getModel().getFullModelRange(),%0A text: this.__current_value%0A %7D%5D, %5Bnew monaco.Range(1, 1, 1, 1)%5D);%0A this.editor.pushUndoStop( );%0A @@ -1512,24 +1512,24 @@ .options) %7B%0A - this.e @@ -1567,16 +1567,17 @@ options) +; %0A %7D%0A
d979db81769f6440eac0b1d6050b3fa604a732ab
Fix fd-diagram-edit-form controller init without super
addon/controllers/fd-diagram-edit-form.js
addon/controllers/fd-diagram-edit-form.js
import EditFormController from 'ember-flexberry/controllers/edit-form'; export default EditFormController.extend({ parentRoute: 'fd-diagram-list-form', init: function() { } });
JavaScript
0
@@ -152,33 +152,8 @@ m',%0A - init: function() %7B%0A %7D%0A %7D);%0A
2857d44a1135c1a225812720694dbc633c1b277d
Update garbage.js
cron/garbage.js
cron/garbage.js
const CronJob = require('cron').CronJob; const TimeDate = require('time').Date; const garbageList = require('../data/garbage.json'); const TIME_ZONE = 'Asia/Tokyo'; const garbageType = () => { "use strict"; const date = new TimeDate(); date.setTimezone(TIME_ZONE); const day = date.getDay(); return garbageList[day]; }; module.exports = bot => { "use strict"; new CronJob('0 0 7 * * 1-5', () => { bot.say({ text: 'おはようございます。本日は「'+ garbageType() + '」の収集日です。', channel: process.env.CHANNEL_ID }); }, null, true, TIME_ZONE); };
JavaScript
0.000001
@@ -452,9 +452,9 @@ %E3%81%84%E3%81%BE%E3%81%99%E3%80%82 -%E6%9C%AC +%E4%BB%8A %E6%97%A5%E3%81%AF%E3%80%8C'
43be2fd9144406785c7da4b375176da9322c85fd
add progress to upgrade script
upgrades/mentions_delete_mentions_set_zset.js
upgrades/mentions_delete_mentions_set_zset.js
'use strict'; const db = module.parent.require('./database'); const batch = module.parent.require('./batch'); module.exports = { name: 'Delete mentions:sent:<pid> sorted sets', timestamp: Date.UTC(2021, 10, 2), method: async function () { const nextPid = await db.getObjectField('global', 'nextPid'); const allPids = []; for (let pid = 1; pid < nextPid; ++ pid) { allPids.push(pid); } await batch.processArray(allPids, async (pids) => { await db.deleteAll(pids.map(pid => `mentions:sent:${pid}`)); }, { batch: 500, }); }, };
JavaScript
0
@@ -233,24 +233,59 @@ nction () %7B%0A + const %7B progress %7D = this;%0A cons @@ -522,16 +522,56 @@ s) =%3E %7B%0A + progress.incr(pids.length);%0A
d96292c8bc0933ce202a6de4a1a4c938aa267a72
typos man
ProcessesingScripts/lynximport.js
ProcessesingScripts/lynximport.js
var templatehandler = require("../engine/templateHanler.js"); exports.Process = function(page){ var jsdom = require('jsdom').jsdom; var serializer = require('jsdom').serializeDocument; var document = jsdom(page); var list = document.getElementsByTagName("lynximport"); for(var i =0 ; i<list.length; i++){ debugger; var path = list[i].getAttribute("path"); path = templatehandler.fePath + path; try{ var replacement = fs.readFileSync(path); try{ replacement = replacement.toString(); replacement = jsdom(replacement); list[i].parentNode.replaceChild(replacement, list[i]); }catch(err){ console.log("Couldn't make html from loaded file"); debugger; } }catch(err){ console.log("Couldn't find file: " + path.toString()); debugger; } } return serializer(document); }
JavaScript
0.999566
@@ -45,16 +45,17 @@ plateHan +d ler.js%22)
a1d91dfa87f55fd92012998b6ea3c2399e81bbad
Fix ContainerComponentEditor quill formats
app/assets/javascripts/components/ContainerComponentEditor.js
app/assets/javascripts/components/ContainerComponentEditor.js
/* eslint-disable class-methods-use-this */ /* eslint-disable react/no-multi-comp */ import React from 'react'; import PropTypes from 'prop-types'; import { OverlayTrigger, Popover } from 'react-bootstrap'; import ReactQuill from './react_quill/ReactQuill'; import QuillToolbarDropdown from './react_quill/QuillToolbarDropdown'; import QuillToolbarIcon from './react_quill/QuillToolbarIcon'; import DynamicTemplateCreator from './analyses_toolbar/DynamicTemplateCreator'; import { sampleAnalysesMacros, defaultMacroDropdown, defaultMacroToolbar } from './utils/quillToolbarSymbol'; sampleAnalysesMacros.ndash.icon = ( <span className="fa fa-minus" /> ); sampleAnalysesMacros['h-nmr'].icon = ( <span>H</span> ); sampleAnalysesMacros['c-nmr'].icon = ( <span>C</span> ); const editTemplate = () => { console.log('ad'); }; const autoFormat = () => { console.log('autoFormat'); }; const extractMacros = (macros) => { const tKeys = Object.keys(macros); return tKeys.reduce(([iData, ddData], tKey) => { const macroNames = macros[tKey]; /* eslint-disable no-param-reassign */ if (tKey === '_toolbar') { macroNames.forEach((name) => { iData[name] = sampleAnalysesMacros[name]; }); } else { const data = {}; macroNames.forEach((name) => { data[name] = sampleAnalysesMacros[name]; }); ddData[tKey] = data; } /* eslint-enable no-param-reassign */ return [iData, ddData]; }, [{}, {}]); }; export default class ContainerComponentEditor extends React.Component { constructor(props) { super(props); // this.state = { editorDelta: {} }; this.toolbarId = `_${Math.random().toString(36).substr(2, 9)}`; this.modules = { toolbar: { container: `#${this.toolbarId}`, handlers: { editTemplate, autoFormat } }, }; this.handleChange = this.handleChange.bind(this); this.selectDropdown = this.selectDropdown.bind(this); this.iconOnClick = this.iconOnClick.bind(this); } handleChange(delta) { // this.setState({ editorDelta: delta }); } selectDropdown(key, value) { console.log(`select Dropdown ${key} - ${value}`); } toolbarOnClick() { console.log('toolbar onclick'); } iconOnClick(macro) { console.log(macro); } render() { let { macros } = this.props; if (Object.keys(macros).length === 0) { macros = { _toolbar: defaultMacroToolbar, MS: defaultMacroDropdown }; } const [iconMacros, ddMacros] = extractMacros(macros); const templateCreatorPopover = ( <Popover id="popover-positioned-top" title="Custom toolbar" className="analyses-template-creator" > <DynamicTemplateCreator iconMacros={iconMacros} dropdownMacros={ddMacros} predefinedMacros={sampleAnalysesMacros} /> </Popover> ); const autoFormatIcon = <span className="fa fa-magic" />; return ( <div> <div id={this.toolbarId}> <select className="ql-header" defaultValue="" onChange={e => e.persist()}> <option value="1" /> <option value="2" /> <option value="3" /> <option value="4" /> <option value="5" /> <option value="6" /> <option /> </select> <button className="ql-bold" /> <button className="ql-italic" /> <button className="ql-underline" /> <button className="ql-list" value="ordered" /> <button className="ql-list" value="bullet" /> <button className="ql-script" value="sub" /> <button className="ql-script" value="super" /> <QuillToolbarIcon icon={autoFormatIcon} onClick={autoFormat} /> {Object.keys(iconMacros).map((name) => { const val = iconMacros[name]; const onClick = () => this.iconOnClick(val); return ( <QuillToolbarIcon key={`${this.toolbarId}_icon_${name}`} icon={val.icon ? val.icon : name} onClick={onClick} /> ); })} {Object.keys(ddMacros).map((label) => { const items = {}; Object.keys(ddMacros[label]).forEach((k) => { items[k.toUpperCase()] = k; }); return ( <QuillToolbarDropdown key={`${this.toolbarId}_dd_${label}`} label={label} items={items} onSelect={this.selectDropdown} /> ); })} <OverlayTrigger trigger="click" placement="top" overlay={templateCreatorPopover} > <span className="ql-formats"> <button className="ql-editTemplate"> <span className="fa fa-cog" /> </button> </span> </OverlayTrigger> </div> <ReactQuill modules={this.modules} theme="snow" /> </div> ); } } ContainerComponentEditor.propTypes = { // eslint-disable-next-line react/forbid-prop-types macros: PropTypes.object, }; ContainerComponentEditor.defaultProps = { macros: {}, };
JavaScript
0.000001
@@ -778,16 +778,128 @@ an%3E%0A);%0A%0A +const toolbarOptions = %5B%0A 'header',%0A 'bold',%0A 'italic',%0A 'underline',%0A 'script',%0A 'list',%0A 'bullet',%0A%5D;%0A%0A const ed @@ -1705,49 +1705,8 @@ ps); -%0A // this.state = %7B editorDelta: %7B%7D %7D; %0A%0A @@ -2282,70 +2282,8 @@ %7D%0A%0A - toolbarOnClick() %7B%0A console.log('toolbar onclick');%0A %7D%0A%0A ic @@ -5146,16 +5146,89 @@ =%22snow%22%0A + formats=%7BtoolbarOptions%7D%0A style=%7B%7B height: '120px' %7D%7D%0A