{ // 获取包含Hugging Face文本的span元素 const spans = link.querySelectorAll('span.whitespace-nowrap, span.hidden.whitespace-nowrap'); spans.forEach(span => { if (span.textContent && span.textContent.trim().match(/Hugging\s*Face/i)) { span.textContent = 'AI快站'; } }); }); // 替换logo图片的alt属性 document.querySelectorAll('img[alt*="Hugging"], img[alt*="Face"]').forEach(img => { if (img.alt.match(/Hugging\s*Face/i)) { img.alt = 'AI快站 logo'; } }); } // 替换导航栏中的链接 function replaceNavigationLinks() { // 已替换标记,防止重复运行 if (window._navLinksReplaced) { return; } // 已经替换过的链接集合,防止重复替换 const replacedLinks = new Set(); // 只在导航栏区域查找和替换链接 const headerArea = document.querySelector('header') || document.querySelector('nav'); if (!headerArea) { return; } // 在导航区域内查找链接 const navLinks = headerArea.querySelectorAll('a'); navLinks.forEach(link => { // 如果已经替换过,跳过 if (replacedLinks.has(link)) return; const linkText = link.textContent.trim(); const linkHref = link.getAttribute('href') || ''; // 替换Spaces链接 - 仅替换一次 if ( (linkHref.includes('/spaces') || linkHref === '/spaces' || linkText === 'Spaces' || linkText.match(/^s*Spacess*$/i)) && linkText !== 'OCR模型免费转Markdown' && linkText !== 'OCR模型免费转Markdown' ) { link.textContent = 'OCR模型免费转Markdown'; link.href = 'https://fast360.xyz'; link.setAttribute('target', '_blank'); link.setAttribute('rel', 'noopener noreferrer'); replacedLinks.add(link); } // 删除Posts链接 else if ( (linkHref.includes('/posts') || linkHref === '/posts' || linkText === 'Posts' || linkText.match(/^s*Postss*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } // 替换Docs链接 - 仅替换一次 else if ( (linkHref.includes('/docs') || linkHref === '/docs' || linkText === 'Docs' || linkText.match(/^s*Docss*$/i)) && linkText !== '模型下载攻略' ) { link.textContent = '模型下载攻略'; link.href = '/'; replacedLinks.add(link); } // 删除Enterprise链接 else if ( (linkHref.includes('/enterprise') || linkHref === '/enterprise' || linkText === 'Enterprise' || linkText.match(/^s*Enterprises*$/i)) ) { if (link.parentNode) { link.parentNode.removeChild(link); } replacedLinks.add(link); } }); // 查找可能嵌套的Spaces和Posts文本 const textNodes = []; function findTextNodes(element) { if (element.nodeType === Node.TEXT_NODE) { const text = element.textContent.trim(); if (text === 'Spaces' || text === 'Posts' || text === 'Enterprise') { textNodes.push(element); } } else { for (const child of element.childNodes) { findTextNodes(child); } } } // 只在导航区域内查找文本节点 findTextNodes(headerArea); // 替换找到的文本节点 textNodes.forEach(node => { const text = node.textContent.trim(); if (text === 'Spaces') { node.textContent = node.textContent.replace(/Spaces/g, 'OCR模型免费转Markdown'); } else if (text === 'Posts') { // 删除Posts文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } else if (text === 'Enterprise') { // 删除Enterprise文本节点 if (node.parentNode) { node.parentNode.removeChild(node); } } }); // 标记已替换完成 window._navLinksReplaced = true; } // 替换代码区域中的域名 function replaceCodeDomains() { // 特别处理span.hljs-string和span.njs-string元素 document.querySelectorAll('span.hljs-string, span.njs-string, span[class*="hljs-string"], span[class*="njs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换hljs-string类的span中的域名(移除多余的转义符号) document.querySelectorAll('span.hljs-string, span[class*="hljs-string"]').forEach(span => { if (span.textContent && span.textContent.includes('huggingface.co')) { span.textContent = span.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 替换pre和code标签中包含git clone命令的域名 document.querySelectorAll('pre, code').forEach(element => { if (element.textContent && element.textContent.includes('git clone')) { const text = element.innerHTML; if (text.includes('huggingface.co')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 处理特定的命令行示例 document.querySelectorAll('pre, code').forEach(element => { const text = element.innerHTML; if (text.includes('huggingface.co')) { // 针对git clone命令的专门处理 if (text.includes('git clone') || text.includes('GIT_LFS_SKIP_SMUDGE=1')) { element.innerHTML = text.replace(/huggingface.co/g, 'aifasthub.com'); } } }); // 特别处理模型下载页面上的代码片段 document.querySelectorAll('.flex.border-t, .svelte_hydrator, .inline-block').forEach(container => { const content = container.innerHTML; if (content && content.includes('huggingface.co')) { container.innerHTML = content.replace(/huggingface.co/g, 'aifasthub.com'); } }); // 特别处理模型仓库克隆对话框中的代码片段 try { // 查找包含"Clone this model repository"标题的对话框 const cloneDialog = document.querySelector('.svelte_hydration_boundary, [data-target="MainHeader"]'); if (cloneDialog) { // 查找对话框中所有的代码片段和命令示例 const codeElements = cloneDialog.querySelectorAll('pre, code, span'); codeElements.forEach(element => { if (element.textContent && element.textContent.includes('huggingface.co')) { if (element.innerHTML.includes('huggingface.co')) { element.innerHTML = element.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { element.textContent = element.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); } // 更精确地定位克隆命令中的域名 document.querySelectorAll('[data-target]').forEach(container => { const codeBlocks = container.querySelectorAll('pre, code, span.hljs-string'); codeBlocks.forEach(block => { if (block.textContent && block.textContent.includes('huggingface.co')) { if (block.innerHTML.includes('huggingface.co')) { block.innerHTML = block.innerHTML.replace(/huggingface.co/g, 'aifasthub.com'); } else { block.textContent = block.textContent.replace(/huggingface.co/g, 'aifasthub.com'); } } }); }); } catch (e) { // 错误处理但不打印日志 } } // 当DOM加载完成后执行替换 if (document.readyState === 'loading') { document.addEventListener('DOMContentLoaded', () => { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); }); } else { replaceHeaderBranding(); replaceNavigationLinks(); replaceCodeDomains(); // 只在必要时执行替换 - 3秒后再次检查 setTimeout(() => { if (!window._navLinksReplaced) { console.log('[Client] 3秒后重新检查导航链接'); replaceNavigationLinks(); } }, 3000); } // 增加一个MutationObserver来处理可能的动态元素加载 const observer = new MutationObserver(mutations => { // 检查是否导航区域有变化 const hasNavChanges = mutations.some(mutation => { // 检查是否存在header或nav元素变化 return Array.from(mutation.addedNodes).some(node => { if (node.nodeType === Node.ELEMENT_NODE) { // 检查是否是导航元素或其子元素 if (node.tagName === 'HEADER' || node.tagName === 'NAV' || node.querySelector('header, nav')) { return true; } // 检查是否在导航元素内部 let parent = node.parentElement; while (parent) { if (parent.tagName === 'HEADER' || parent.tagName === 'NAV') { return true; } parent = parent.parentElement; } } return false; }); }); // 只在导航区域有变化时执行替换 if (hasNavChanges) { // 重置替换状态,允许再次替换 window._navLinksReplaced = false; replaceHeaderBranding(); replaceNavigationLinks(); } }); // 开始观察document.body的变化,包括子节点 if (document.body) { observer.observe(document.body, { childList: true, subtree: true }); } else { document.addEventListener('DOMContentLoaded', () => { observer.observe(document.body, { childList: true, subtree: true }); }); } })(); \n\n]]>;\n \n var template = xml.toString();\n var model = { q: q, hits: hits, hostForUrl: hostForUrl };\n var content = ejs.render(template, model); \n \n return [{\n label: 'Hacker News Search',\n uri: 'https://hn.algolia.com/#!/story/forever/0/' + encodeURIComponent(q),\n tooltip: 'Hacker News Search results for \"' + _(q).escapeHTML() + '\"',\n iconUrl: ICON_URL,\n relevance: BASE_RELEVANCE,\n content: content,\n serverSideSanitized: true,\n categories: [{value: 'programming', weight: 1.0}, {value: 'business', weight: 0.5}]\n }];\n \n } else { \n return _(hits).chain().filter(function (hit) {\n return !!hit.url;\n }).map(function (hit) {\n console.log('got hit url = ' + hit.url);\n return {\n label : hit.title || '',\n iconUrl: ICON_URL,\n uri : hit.url,\n // embeddable: false, let solveforall guess\n summaryHtml: _(hit.story_text || '').escapeHTML(),\n relevance: BASE_RELEVANCE * (1.0 - Math.pow(2.0, -Math.max((hit.points || 0), 1) * 0.01))\n };\n }).value();\n }\n };\n}\n\nfunction generateResults(recognitionResults, q, context) {\n 'use strict';\n\n if (context.isSuggestionQuery) {\n return [];\n }\n \n var url = 'https://hn.algolia.com/api/v1/search';\n\n var request = hostAdapter.makeWebRequest(url, {\n data: {\n query: q\n }\n });\n \n request.send('makeResponseHandler(' + JSON.stringify(q) + \n ',' + JSON.stringify(context) + ')');\n\n return HostAdapter.SUSPEND;\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0001396262,"string":"0.00014"},"diff":{"kind":"string","value":"@@ -419,16 +419,208 @@\n tIndex);\n+ %0A var endIndex2 = url.indexOf('?', startIndex);%0A %0A if (endIndex %3C 0) %7B%0A endIndex = endIndex2; %0A %0A if (endIndex %3C 0) %7B%0A return url.substring(startIndex);%0A %7D %0A %7D %0A \n %0A retur\n"}}},{"rowIdx":2597308,"cells":{"commit":{"kind":"string","value":"55524174ef76c23b1e1917e57cbe863fee3acd8e"},"subject":{"kind":"string","value":"Resolve #67: Add channelOptions option to ChannelPool constructor"},"old_file":{"kind":"string","value":"lib/ChannelPool.js"},"new_file":{"kind":"string","value":"lib/ChannelPool.js"},"old_contents":{"kind":"string","value":"/*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true */\n/*\n * stompit.ChannelPool\n * Copyright (c) 2014 Graham Daws \n * MIT licensed\n */\n \nvar Channel = require('./Channel');\nvar assign = require('object-assign');\n\nfunction ChannelPool(connectFailover, options) {\n \n if (!(this instanceof ChannelPool)) {\n var object = Object.create(ChannelPool.prototype);\n ChannelPool.apply(object, arguments);\n return object;\n }\n \n options = assign({\n \n minChannels: 1,\n \n minFreeChannels: 1,\n \n maxChannels: Infinity,\n \n freeExcessTimeout: null,\n \n requestChannelTimeout: null\n \n }, options || {});\n \n this._connectFailover = connectFailover;\n \n this._minChannels = options.minChannels;\n this._minFreeChannels = Math.min(options.minFreeChannels, this._minChannels);\n this._maxChannels = options.maxChannels;\n \n this._channels = [];\n \n this._freeChannels = [];\n this._freeExcessTimeout = options.freeExcessTimeout;\n this._freeExcessTimeouts = [];\n \n this._requestChannelTimeout = options.requestChannelTimeout;\n \n this._closed = false;\n\n if (this._requestChannelTimeout !== null){\n this._channelRequests = [];\n }\n \n for (var i = 0; i < this._minChannels; i++) {\n this._allocateFreeChannel();\n }\n}\n\nChannelPool.prototype._createChannel = function() {\n \n return new Channel(this._connectFailover, {\n alwaysConnected: true\n });\n};\n\nChannelPool.prototype._allocateFreeChannel = function() {\n \n if (this._channels.length >= this._maxChannels) {\n return;\n }\n \n var channel = this._createChannel();\n \n this._channels.push(channel);\n \n this._freeChannels.push(channel);\n \n return channel;\n};\n\nChannelPool.prototype._deallocateChannel = function(channel) {\n \n channel.close();\n \n var index = this._channels.indexOf(channel);\n \n if (index !== -1) {\n this._channels.splice(index, 1);\n }\n};\n\nChannelPool.prototype._addExcessTimeout = function() {\n \n if (this._freeChannels.length <= this._minChannels) {\n return;\n }\n \n var self = this;\n \n var close = function() {\n \n var channel = self._freeChannels.shift();\n \n if (!channel.isEmpty()) {\n self._startIdleListen(channel);\n return;\n }\n \n self._deallocateChannel(channel);\n };\n \n if (this._freeExcessTimeout === null) {\n close();\n return;\n }\n \n this._freeExcessTimeouts.push(setTimeout(function() {\n \n self._freeExcessTimeouts.shift();\n \n if (self._freeChannels.length > self._minChannels) {\n close();\n }\n \n }, this._freeExcessTimeout));\n};\n\nChannelPool.prototype._hasChannelRequestTimeout = function() {\n return typeof this._requestChannelTimeout == 'number';\n};\n\nChannelPool.prototype._startIdleListen = function(channel) {\n \n var self = this;\n \n channel.once('idle', function(){\n \n if (self._closed) {\n self._deallocateChannel(channel);\n return;\n }\n\n if (self._hasChannelRequestTimeout() && self._channelRequests.length > 0) {\n \n var channelRequest = self._channelRequests.shift();\n \n clearTimeout(channelRequest.timeout);\n \n self._startIdleListen(channel);\n \n channelRequest.callback(null, channel);\n \n return;\n }\n \n self._freeChannels.push(channel);\n self._addExcessTimeout();\n });\n};\n\nChannelPool.prototype._timeoutChannelRequest = function(callback) {\n \n this._channelRequests.shift();\n \n callback(new Error('failed to allocate channel'));\n};\n\nChannelPool.prototype.channel = function(callback) {\n \n if (this._closed) {\n process.nextTick(function() {\n callback(new Error('channel pool closed'));\n });\n return;\n }\n\n if (this._freeChannels.length === 0 && !this._allocateFreeChannel()) {\n \n if (this._hasChannelRequestTimeout()) {\n \n var timeout = setTimeout(\n this._timeoutChannelRequest.bind(this, callback), \n this._requestChannelTimeout\n );\n \n this._channelRequests.push({\n timeout: timeout,\n callback: callback\n });\n }\n else {\n process.nextTick(function() {\n callback(new Error('failed to allocate channel'));\n });\n }\n \n return;\n }\n \n var channel = this._freeChannels.shift();\n \n if (this._freeExcessTimeouts.length > 0) {\n clearTimeout(this._freeExcessTimeouts.shift()); \n }\n \n if (this._freeChannels.length < this._minFreeChannels) {\n this._allocateFreeChannel();\n }\n \n this._startIdleListen(channel);\n \n process.nextTick(function() {\n callback(null, channel);\n });\n};\n\nChannelPool.prototype.close = function() {\n\n this._closed = true;\n\n this._channels.forEach(function(channel) {\n channel.close();\n });\n\n this._channels = [];\n this._freeChannels = [];\n\n if (this._channelRequests) {\n\n this._channelRequests.forEach(function(request) {\n clearTimeout(request.timeout);\n request.callback(new Error('channel pool closed'));\n });\n\n this._channelRequests = [];\n }\n};\n\nmodule.exports = ChannelPool;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.505e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -661,16 +661,41 @@\n ut: null\n+,%0A%0A channelOptions: %7B%7D\n %0A %0A \n@@ -949,32 +949,119 @@\n annels = %5B%5D;%0A %0A\n+ this._channelOptions = assign(%7B%7D, options.channelOptions, %7BalwaysConnected: true%7D);%0A%0A\n this._freeChan\n@@ -1477,18 +1477,16 @@\n ion() %7B%0A\n- \n %0A retur\n@@ -1526,39 +1526,28 @@\n er, \n-%7B%0A alwaysConnected: true%0A %7D\n+this._channelOptions\n );%0A%7D\n"}}},{"rowIdx":2597309,"cells":{"commit":{"kind":"string","value":"709f9ae84a27cca1e4b4c540237a7c75cddd5383"},"subject":{"kind":"string","value":"fix line endings and update build 2"},"old_file":{"kind":"string","value":"Jakefile.js"},"new_file":{"kind":"string","value":"Jakefile.js"},"old_contents":{"kind":"string","value":"var build = require('./build/build.js'),\n\tlint = require('./build/hint.js');\n\nvar COPYRIGHT = \"/*\\r\\n Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin\\n\" +\n \" Leaflet is a modern open-source JavaScript library for interactive maps.\\n\" +\n \" http://leaflet.cloudmade.com\\r\\n*/\\r\\n\";\n\ndesc('Check Leaflet source for errors with JSHint');\ntask('lint', function () {\n\tvar files = build.getFiles();\n\t\n\tconsole.log('Checking for JS errors...');\n\t\n\tvar errorsFound = lint.jshint(files);\n\t\n\tif (errorsFound > 0) {\n\t\tconsole.log(errorsFound + ' error(s) found.\\n');\n\t\tfail();\n\t} else {\n\t\tconsole.log('\\tCheck passed');\n\t}\n});\n\ndesc('Combine and compress Leaflet source files');\ntask('build', ['lint'], function (compsBase32, buildName) {\n\tvar name = buildName || 'custom',\n\t\tpath = 'dist/leaflet' + (compsBase32 ? '-' + name : '');\n\n\tvar files = build.getFiles(compsBase32);\n\n\tconsole.log('Concatenating ' + files.length + ' files...');\n\tvar content = build.combineFiles(files);\n\tconsole.log('\\tUncompressed size: ' + content.length);\n\t\n\tbuild.save(path + '-src.js', COPYRIGHT + content);\n\tconsole.log('\\tSaved to ' + path);\n\t\n\tconsole.log('Compressing...');\n\tvar compressed = COPYRIGHT + build.uglify(content);\n\tconsole.log('\\tCompressed size: ' + compressed.length);\n\n\tbuild.save(path + '.js', compressed);\n\tconsole.log('\\tSaved to ' + path);\n});\n\ntask('default', ['build']);"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.465e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -150,16 +150,18 @@\n afonkin%5C\n+r%5C\n n%22 +%0A \n"}}},{"rowIdx":2597310,"cells":{"commit":{"kind":"string","value":"1c4a59f86ac4e1e062ad061b5850f0175184958e"},"subject":{"kind":"string","value":"Make sure we're only adding labels to lis on the top level"},"old_file":{"kind":"string","value":"github.com.js"},"new_file":{"kind":"string","value":"github.com.js"},"old_contents":{"kind":"string","value":"var dotjs_github = {};\n\ndotjs_github.init = function() {\n\tdotjs_github.$issues = $('.issues');\n\n\tvar style = '';\n\n\t$('body').append( style );\n\n\t$('.sidebar .filter-item').live('click.dotjs_github', function( e ) {\n\t\te.preventDefault();\n\t\tsetTimeout( function() {\n\t\t\tdotjs_github.$issues = $('.issues');\n\t\t\tdotjs_github.add_hide_links();\n\t\t}, 500 );\n\t});\n\n\tdotjs_github.add_hide_links();\n};\n\ndotjs_github.add_hide_links = function() {\n\tvar $labels = $('.js-color-label-list');\n\t$labels.find('li').prepend('');\n\t$labels.find('.hide-it').bind('click', function( e ) {\n\t\te.preventDefault();\n\t\te.stopPropagation();\n\n\t\tvar $el = $(this);\n\t\tvar val = $el.next().data('label');\n\t\tvar $issues = dotjs_github.$issues.find('.list-browser-item .label[data-name=\"' + $.trim( val ) + '\"]').closest('tr');\n\n\t\tif ( ! $el.hasClass('clicked') ) {\n\t\t\t$el.addClass('clicked').closest('li').addClass('custom-hidden');\n\t\t\t$issues.addClass('hidden');\n\t\t} else {\n\t\t\t$el.removeClass('clicked').closest('li').removeClass('custom-hidden');\n\t\t\t$issues.removeClass('hidden');\n\t\t}//end else\n\n\t\tvar count = $('.issues-list').find('.list-browser-item:not(.hidden)').length;\n\n\t\tvar $selected = $('.list-browser-filter-tabs .selected');\n\t\t$selected.html( parseInt( count, 10 ) + ' ' + $selected.data('filter') + ' issues' );\n\t});\n};\n\ndotjs_github.init();\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.254e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1296,20 +1296,24 @@\n $labels.\n-find\n+children\n ('li').p\n"}}},{"rowIdx":2597311,"cells":{"commit":{"kind":"string","value":"5f9703e389ba0ab7471ef4d3f41b9f07b9198f71"},"subject":{"kind":"string","value":"Update throbber test time to avoid test inaccuracies"},"old_file":{"kind":"string","value":"test/__playground/throbber.formatted.js"},"new_file":{"kind":"string","value":"test/__playground/throbber.formatted.js"},"old_contents":{"kind":"string","value":"#!/usr/bin/env node\n\n'use strict';\n\nvar throbber = require('../../lib/throbber')\n , interval = require('clock/lib/interval')\n , format = require('../../lib/index').red;\n\nvar i = interval(100, true);\n\nthrobber(i, format);\nprocess.stdout.write('START');\n\nsetTimeout(i.stop.bind(i), 500);\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.278e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -278,13 +278,13 @@\n nd(i), 5\n-0\n+5\n 0);%0A\n"}}},{"rowIdx":2597312,"cells":{"commit":{"kind":"string","value":"17b95e4b726a9c59096fe56c20cda3b05bb3acd3"},"subject":{"kind":"string","value":"add new test spec for models"},"old_file":{"kind":"string","value":"server/spec/modelSpec.js"},"new_file":{"kind":"string","value":"server/spec/modelSpec.js"},"old_contents":{"kind":"string","value":"import jasmine from 'jasmine';\nimport Sequelize from 'sequelize';\nimport expect from 'expect';\nimport Users from '../models/users';\nimport Group from '../models/group';\n// import GroupMembers from '../models/groupMembers';\n// import Messages from '../models/messages';\nimport db from '../config/db_url.json';\n\n\ndescribe('Model test suite', () => {\n beforeEach((done) => {\n const sequelize = new Sequelize(db.url);\n sequelize.authenticate().then(() => { console.log('Connection established'); })\n .catch((err) => { console.log('Error occured', err); });\n done();\n }, 10000);\n it('I should be able to create a new user with this model', (done) => {\n Users.sync({ force: true }).then(() => {\n Users.create({ name: 'Peter', username: 'Ike', email: 'alobam@gmail.com', password: 'show' })\n .then((user) => {\n if (user) {\n expect('Ike').toBe(user.dataValues.username);\n }\n done();\n }).catch((err) => { console.log('Failed', err); done(); });\n });\n }, 10000);\n it('I should be able to create a new group with this model', (done) => {\n Group.sync({ force: true }).then(() => {\n Group.create({ groupName: 'Zikites', groupCategory: 'Class of 2014', userId: 1 })\n .then((group) => {\n if (group) {\n expect('Zikites').toNotBe('Zike');\n expect('Class of 2014').toBe(group.dataValues.groupCategory);\n }\n done();\n });\n }).catch((err) => { console.log('Failed', err); });\n }, 10000);\n /* it('I should be able to add users to group I created', (done) => {\n GroupMembers.sync({ force: true }).then(() => {\n GroupMembers.create({ userId: 1, admin: 1, groupId: 1 })\n .then((members) => {\n if (members) {\n expect(1).toBe(members.dataValues.userId);\n }\n done();\n });\n }).catch((err) => {\n console.log('Failed', err);\n });\n }, 10000);*/\n});\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n/* describe('Models test suite', () => {\n describe('Establish connection to the database', () => {\n beforeAll((done) => {\n const sequelize = new Sequelize(db.url);\n sequelize.authenticate().then(() => {\n console.log('Connected');\n // 'Connected';\n }).catch((err) => {\n if (err) {\n return 'Unable to connect';\n }\n });\n done();\n });\n });\n describe('Users model', () => {\n beforeEach((done) => {\n const User = Users.sync({ force: true }).then(() => {\n Users.create({ name: 'Ebuka', username: 'Bonachristi', email:\n 'bona@gmail.com', password: 'samodu' })\n .then((result) => {\n if (result) {\n return 'Registered';\n }\n }).catch((err) => {\n if (err) {\n return 'Failed';\n }\n });\n });\n it('should be able to create a new account', () => {\n expect(User).to.be.a('Registered');\n done();\n });\n });\n });\n describe('Create a new group', () => {\n beforeEach((done) => {\n const CreateGroup = Group.sync({ force: true }).then(() => {\n Group.create({}).then((group) => {\n if (group) {\n return 'Group Created';\n }\n }).catch((err) => {\n if (err) {\n return 'Error occured, group not created';\n }\n });\n });\n it('Registered users should be able to create a group', () => {\n expect(CreateGroup).to.be.a('Group Created');\n done();\n });\n });\n });\n describe('Add registered users to group', () => {\n beforeEach((done) => {\n const AddMembers = GroupMembers.sync({ force: true }).then(() => {\n GroupMembers.create({}).then((users) => {\n if (users) {\n return 'Added';\n }\n }).catch((err) => {\n if (err) {\n return 'Failed';\n }\n });\n });\n it('Users should be added by groups by registered user', () => {\n expect(AddMembers).to.be.a('Added');\n done();\n });\n });\n });\n describe('A user should be able to post messages to groups he created', () => {\n beforeEach((done) => {\n const post = Messages.sync({ force: true }).then(() => {\n Messages.create({}).then((message) => {\n if (message) {\n return 'Posted';\n }\n }).catch((err) => {\n if (err) {\n return 'Failed';\n }\n });\n });\n it('Should be able to post message to group', () => {\n expect(post).to.be.a('Posted');\n done();\n });\n });\n });\n});*/\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.624e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1904,2664 +1904,4 @@\n );%0A%0A\n-%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A/* describe('Models test suite', () =%3E %7B%0A describe('Establish connection to the database', () =%3E %7B%0A beforeAll((done) =%3E %7B%0A const sequelize = new Sequelize(db.url);%0A sequelize.authenticate().then(() =%3E %7B%0A console.log('Connected');%0A // 'Connected';%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Unable to connect';%0A %7D%0A %7D);%0A done();%0A %7D);%0A %7D);%0A describe('Users model', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const User = Users.sync(%7B force: true %7D).then(() =%3E %7B%0A Users.create(%7B name: 'Ebuka', username: 'Bonachristi', email:%0A 'bona@gmail.com', password: 'samodu' %7D)%0A .then((result) =%3E %7B%0A if (result) %7B%0A return 'Registered';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('should be able to create a new account', () =%3E %7B%0A expect(User).to.be.a('Registered');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Create a new group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const CreateGroup = Group.sync(%7B force: true %7D).then(() =%3E %7B%0A Group.create(%7B%7D).then((group) =%3E %7B%0A if (group) %7B%0A return 'Group Created';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Error occured, group not created';%0A %7D%0A %7D);%0A %7D);%0A it('Registered users should be able to create a group', () =%3E %7B%0A expect(CreateGroup).to.be.a('Group Created');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Add registered users to group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const AddMembers = GroupMembers.sync(%7B force: true %7D).then(() =%3E %7B%0A GroupMembers.create(%7B%7D).then((users) =%3E %7B%0A if (users) %7B%0A return 'Added';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Users should be added by groups by registered user', () =%3E %7B%0A expect(AddMembers).to.be.a('Added');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('A user should be able to post messages to groups he created', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const post = Messages.sync(%7B force: true %7D).then(() =%3E %7B%0A Messages.create(%7B%7D).then((message) =%3E %7B%0A if (message) %7B%0A return 'Posted';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Should be able to post message to group', () =%3E %7B%0A expect(post).to.be.a('Posted');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%7D);*/%0A\n"}}},{"rowIdx":2597313,"cells":{"commit":{"kind":"string","value":"aa10cda61021ef3d32c301755e594faecbf24f2e"},"subject":{"kind":"string","value":"Add tests to "},"old_file":{"kind":"string","value":"src/Text/__tests__/Text.test.js"},"new_file":{"kind":"string","value":"src/Text/__tests__/Text.test.js"},"old_contents":{"kind":"string","value":"import React from 'react';\nimport ReactDOM from 'react-dom';\nimport Text from '../Text';\n\nit('renders without crashing', () => {\n const div = document.createElement('div');\n const element = (\n \n );\n\n ReactDOM.render(element, div);\n});\n\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.517e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -65,26 +65,138 @@\n ort \n-Text from '../Text\n+%7B shallow %7D from 'enzyme';%0A%0Aimport StatusIcon from 'src/StatusIcon';%0Aimport Text from '../Text';%0Aimport BasicRow from '../BasicRow\n ';%0A%0A\n@@ -474,12 +474,1709 @@\n div);%0A%7D);%0A%0A\n+it('renders using %3CBasicRow%3E with BEM className', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22text%22 /%3E);%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(wrapper.children()).toHaveLength(1);%0A expect(rowWrapper.exists()).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__row')).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__basic')).toBeTruthy();%0A%7D);%0A%0Ait('passing %22basic%22, %22tag%22 and %22stateIcon%22 to %3CBasicRow%3E', () =%3E %7B%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D /%3E%0A );%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('takes custom %3CBasicRow%3E and passes the same props to it', () =%3E %7B%0A const FooRow = () =%3E %3Cdiv /%3E;%0A%0A const customRow = %3CFooRow /%3E;%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D%0A basicRow=%7BcustomRow%7D /%3E%0A );%0A const rowWrapper = wrapper.find(FooRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('renders aside text', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22Basic%22 aside=%22Aside%22 /%3E);%0A%0A expect(wrapper.children()).toHaveLength(2);%0A expect(wrapper.childAt(1).hasClass('ic-text__aside')).toBeTruthy();%0A expect(wrapper.childAt(1).text()).toBe('Aside');%0A%7D);%0A\n"}}},{"rowIdx":2597314,"cells":{"commit":{"kind":"string","value":"63c03ef48a1fc0dbeec02943909bc9bc26ad7a2c"},"subject":{"kind":"string","value":"Mark TODO"},"old_file":{"kind":"string","value":"lib/api/register_user.js"},"new_file":{"kind":"string","value":"lib/api/register_user.js"},"old_contents":{"kind":"string","value":"var data = require(__dirname+'/../data/');\nvar sql = require(__dirname +'/../data/sequelize.js');\nvar config = require(__dirname+'/../../config/environment.js');\nvar validator = require(__dirname+'/../validator.js');\nvar RippleRestClient = require('ripple-rest-client');\nvar uuid = require('node-uuid');\n\n/**\n* Register a User\n* - creates external account named \"default\"\n* - creates ripple address as provided\n* @require data, sql, config\n* @param {string} name\n* @param {string} rippleAddress\n* @param {string} password\n* @returns {User}, {ExternalAccount}, {RippleAddress}\n*/\n\nfunction registerUser(opts, fn) {\n var userOpts = {\n name: opts.name,\n password: opts.password,\n address: opts.ripple_address,\n secret: opts.secret,\n currency: opts.currency,\n amount: opts.amount \n };\n\n if (!validator.isRippleAddress(opts.ripple_address)) {\n fn({ ripple_address: 'invalid ripple address' });\n return;\n }\n\n sql.transaction(function(sqlTransaction){\n data.users.create(userOpts, function(err, user) {\n if (err) { sqlTransaction.rollback(); fn(err, null); return; }\n var addressOpts = {\n user_id: user.id,\n address: opts.ripple_address,\n managed: false,\n type: 'independent'\n };\n data.rippleAddresses.create(addressOpts, function(err, ripple_address) {\n if (err) { sqlTransaction.rollback(); fn(err, null); return; }\n data.externalAccounts.create({ name: 'default', user_id: user.id, address:addressOpts.address, type:addressOpts.type }, function(err, account){\n if (err) { fn(err, null); return; }\n var addressOpts = {\n user_id: user.id,\n address: config.get('COLD_WALLET'),\n managed: true,\n type: 'hosted',\n tag: account.id\n };\n \n // We might be missing the cold wallet\n if (addressOpts.address) {\n // CS Fund user account with XRP\n var rippleRootRestClient = new RippleRestClient({\n api: config.get('RIPPLE_REST_API'),\n account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'\n });\n \n var options = {\n secret: 'masterpassphrase',\n client_resource_id: uuid.v4(),\n payment: {\n destination_account: userOpts.address,\n source_account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh',\n destination_amount: {\n value: '60',\n currency: 'XRP',\n issuer: ''\n }\n }\n };\n \n rippleRootRestClient.sendAndConfirmPayment(options, function(error, response){\n if (error || (response.success != true)) {\n logger.error('rippleRestClient.sendAndConfirmPayment', error);\n return fn(error, null);\n }\n \n // CS Set trust line from user account to cold wallet. We should let users to this manually.\n var coldWallet = config.get('COLD_WALLET');\n \n var rippleRestClient = new RippleRestClient({\n api: config.get('RIPPLE_REST_API'),\n account:userOpts.address\n });\n \n rippleRestClient.setTrustLines({\n account: userOpts.address,\n secret: userOpts.secret,\n limit: userOpts.amount,\n currency: userOpts.currency,\n counterparty: coldWallet,\n account_allows_rippling: true\n }, fn); \n });\n \n // CS Create in DB\n data.rippleAddresses.create(addressOpts, function(err, hosted_address) {\n if (err) { sqlTransaction.rollback(); fn(err, null); return; }\n var response = user.toJSON();\n response.ripple_address = ripple_address;\n response.external_account = account;\n response.hosted_address = hosted_address;\n sqlTransaction.commit();\n fn(err, response);\n });\n \n }\n });\n });\n });\n });\n}\n\nmodule.exports = registerUser;\n\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.000004373,"string":"0.000004"},"diff":{"kind":"string","value":"@@ -3682,16 +3682,83 @@\n e in DB%0A\n+ // TODO the server.js process is restarted here - why?%0A\n \n"}}},{"rowIdx":2597315,"cells":{"commit":{"kind":"string","value":"847544231b0819913f22e2fe437f5cf475542962"},"subject":{"kind":"string","value":"fix code identity"},"old_file":{"kind":"string","value":"server/streak/service.js"},"new_file":{"kind":"string","value":"server/streak/service.js"},"old_contents":{"kind":"string","value":"const rp = require('request-promise');\nconst cheerio = require('cheerio');\n\n\nconst getStreakBody = (userName) => {\n\tvar options = {\n\t\turi: `https://github.com/users/${userName}/contributions`,\n\t\ttransform: function (body) {\n\t\t\treturn cheerio.load(body);\n\t\t}\n\t};\n\n\treturn rp(options)\n\n\t.then(function ($) {\n\n\t\t\tconst currentDateStreak = [];\n\t\t\tlet currentStreak = [];\n\n\t\t\t$('.day').filter(function (i, el) {\n\t\t\t\treturn $(this).prop('data-count') !== '0';\n\t\t\t}).each(function (index) {\n\n\t\t\t\tconst date = new Date($(this).prop('data-date'));\n\t\t\t\tdate.setHours(0, 0, 0, 0);\n\n\t\t\t\tif (currentDateStreak[index - 1]) {\n\t\t\t\t\tconst tempDate = currentDateStreak[index - 1].date;\n\t\t\t\t\ttempDate.setDate(tempDate.getDate() + 1);\n\t\t\t\t\ttempDate.setHours(0, 0, 0, 0);\n\n\t\t\t\t\tif (date.getTime() === tempDate.getTime()) {\n\t\t\t\t\t\tif ($(this).prop('fill') != '#ebedf0') {\n\t\t\t\t\t\t\tcurrentStreak.push({\n\t\t\t\t\t\t\t\tdate: date,\n\t\t\t\t\t\t\t\tcommit: $(this).prop('data-count')\n\t\t\t\t\t\t\t});\n\t\t\t\t\t\t}\n\t\t\t\t\t} else {\n\t\t\t\t\t\tcurrentStreak = [];\n\t\t\t\t\t}\n\t\t\t\t}\n\t\t\t\tcurrentDateStreak.push({\n\t\t\t\t\tdate: date\n\t\t\t\t});\n\t\t\t});\n\n\t\t\treturn currentStreak;\n\t\t})\n\t\t.catch( (err) => {\n\t\t\tconsole.log('errror', err);\n\t\t});\n};\n\n\nmodule.exports = {\n\tgetStreakBody\n};"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0007174176,"string":"0.000717"},"diff":{"kind":"string","value":"@@ -799,56 +799,8 @@\n ) %7B%0A\n-%09%09%09%09%09%09if ($(this).prop('fill') != '#ebedf0') %7B%0A%09\n %09%09%09%09\n@@ -818,25 +818,24 @@\n reak.push(%7B%0A\n-%09\n %09%09%09%09%09%09%09date:\n@@ -848,17 +848,16 @@\n %0A%09%09%09%09%09%09%09\n-%09\n commit: \n@@ -893,21 +893,12 @@\n %09%09%09%09\n-%09\n %7D);%0A\n-%09%09%09%09%09%09%7D%0A\n %09%09%09%09\n@@ -1046,17 +1046,16 @@\n %09.catch(\n- \n (err) =%3E\n@@ -1076,17 +1076,16 @@\n log('err\n-r\n or', err\n@@ -1097,13 +1097,12 @@\n %7D);%0A\n+\n %7D;%0A%0A\n-%0A\n modu\n"}}},{"rowIdx":2597316,"cells":{"commit":{"kind":"string","value":"5418e50f4d56f3f700c9ecc745c3d1d3e25bbfc9"},"subject":{"kind":"string","value":"Add extra named-chunks test cases for variations with require.ensure error callback present."},"old_file":{"kind":"string","value":"test/cases/chunks/named-chunks/index.js"},"new_file":{"kind":"string","value":"test/cases/chunks/named-chunks/index.js"},"old_contents":{"kind":"string","value":"it(\"should handle named chunks\", function(done) {\n\tvar sync = false;\n\trequire.ensure([], function(require) {\n\t\trequire(\"./empty?a\");\n\t\trequire(\"./empty?b\");\n\t\ttestLoad();\n\t\tsync = true;\n\t\tprocess.nextTick(function() {\n\t\t\tsync = false;\n\t\t});\n\t}, \"named-chunk\");\n\tfunction testLoad() {\n\t\trequire.ensure([], function(require) {\n\t\t\trequire(\"./empty?c\");\n\t\t\trequire(\"./empty?d\");\n\t\t\tsync.should.be.ok();\n\t\t\tdone();\n\t\t}, \"named-chunk\");\n\t}\n});\n\nit(\"should handle empty named chunks\", function(done) {\n\tvar sync = false;\n\trequire.ensure([], function(require) {\n\t\tsync.should.be.ok();\n\t}, \"empty-named-chunk\");\n\trequire.ensure([], function(require) {\n\t\tsync.should.be.ok();\n\t\tdone();\n\t}, \"empty-named-chunk\");\n\tsync = true;\n\tsetImmediate(function() {\n\t\tsync = false;\n\t});\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.024e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -757,12 +757,977 @@\n e;%0A%09%7D);%0A%7D);%0A\n+%0Ait(%22should handle named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?a%22);%0A require(%22./empty?b%22);%0A testLoad();%0A sync = true;%0A process.nextTick(function() %7B%0A sync = false;%0A %7D);%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A function testLoad() %7B%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?c%22);%0A require(%22./empty?d%22);%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A %7D%0A%7D);%0A%0Ait(%22should handle empty named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A sync = true;%0A setImmediate(function() %7B%0A sync = false;%0A %7D);%0A%7D);%0A\n"}}},{"rowIdx":2597317,"cells":{"commit":{"kind":"string","value":"4acca781206921d81fb4dd1b05df11920951621c"},"subject":{"kind":"string","value":"Fix formatting"},"old_file":{"kind":"string","value":"cla_public/static-src/javascripts/modules/form-errors.js"},"new_file":{"kind":"string","value":"cla_public/static-src/javascripts/modules/form-errors.js"},"old_contents":{"kind":"string","value":"(function() {\n 'use strict';\n\n moj.Modules.FormErrors = {\n init: function() {\n _.bindAll(this, 'postToFormErrors', 'onAjaxSuccess', 'onAjaxError');\n this.bindEvents();\n this.loadTemplates();\n },\n\n bindEvents: function() {\n $('form')\n .on('submit', this.postToFormErrors)\n // Focus back on summary if field-error is focused and escape key is pressed\n .on('keyup', function(e) {\n var $target = $(e.target);\n if(e.keyCode === 27 && $target.is('.form-error')) {\n $target.closest('form').find('> .alert').focus();\n }\n })\n .on('blur', '.form-group', function(e) {\n $(e.target).removeAttr('tabindex');\n });\n\n //// Add role=alert on error message when fieldset is focused\n //.on('focus', 'fieldset.m-error', function(e) {\n // $(e.target).find('.field-error').attr('role', 'alert');\n //})\n //// Remove role=alert from error message when fieldset is blurred\n //.on('blur', 'fieldset.m-error', function(e) {\n // $(e.target).find('.field-error').removeAttr('role');\n //});\n\n $('[type=submit]').on('click', function(e) {\n var $target = $(e.target);\n $target.closest('form').attr('submit-name', $target.attr('name'));\n });\n\n // Focus on field with error\n $('#content').on('click', '.error-summary a', function(e) {\n e.preventDefault();\n var targetId = e.target.href.replace(/.*#/, '#');\n if(targetId.length < 2) {\n return;\n }\n var $target = $(targetId);\n\n $('html, body').animate({\n scrollTop: $target.offset().top - 20\n }, 300, function() {\n $target.attr('tabindex', -1).focus();\n });\n });\n },\n\n postToFormErrors: function(e) {\n this.$form = $(e.target);\n\n // Return if button has a name, which is attached as form attribute on click\n // (assuming secondary buttons)\n if(this.$form.attr('submit-name') ||\n this.$form.attr('method') && this.$form.attr('method').toLowerCase() === 'get') {\n return;\n }\n\n if (this.$form.length) {\n e.preventDefault();\n e.stopPropagation();\n $.ajax({\n type: 'OPTIONS',\n url: '',\n contentType: 'application/x-www-form-urlencoded',\n data: this.$form.serialize()\n })\n .done(this.onAjaxSuccess)\n .fail(this.onAjaxError);\n }\n },\n\n onAjaxSuccess: function(errors) {\n if (!$.isEmptyObject(errors)) {\n this.loadErrors(errors);\n var errorBanner = $('.alert-error:visible:first');\n\n if(!errorBanner.length) {\n return;\n }\n\n $('html, body').animate({\n scrollTop: errorBanner.offset().top - 20\n }, 300, function() {\n errorBanner.attr({'tabindex': -1}).focus();\n });\n } else {\n this.$form.off('submit');\n this.$form.submit();\n }\n },\n\n onAjaxError: function() {\n this.$form.off('submit');\n this.$form.submit();\n },\n\n formatErrors: function(errors) {\n var errorFields = {};\n\n (function fieldName (errorsObj, prefix) {\n prefix = (typeof prefix === 'undefined')? '': prefix + '-';\n for (var key in errorsObj) {\n var field = prefix + key;\n if ($.isArray(errorsObj[key])) {\n errorFields[field] = errorsObj[key];\n } else {\n fieldName(errorsObj[key], field);\n }\n }\n })(errors);\n\n return errorFields;\n },\n\n createErrorSummary: function() {\n var errorSummary = [];\n\n // Loop through errors on the page to retain the fields order\n $('.form-error').map(function() {\n var $this = $(this);\n\n if(!this.id || $this.hasClass('s-hidden') || $this.parent().hasClass('s-hidden')) {\n return;\n }\n var name = this.id.replace(/^field-/, '');\n\n errorSummary.push({\n label: $this.find('> legend, > .form-group-label').text(),\n name: name,\n errors: $this.find('> .field-error p').map(function() {\n return $(this).text();\n })\n });\n });\n\n return errorSummary;\n },\n\n loadErrors: function(errors) {\n var errorFields = this.formatErrors(errors);\n var self = this;\n\n this.clearErrors();\n\n function addErrors(errors, fieldName) {\n if (_.isString(errors[0])) {\n $('#field-' + fieldName)\n .addClass('form-error')\n .attr({\n 'aria-invalid': true,\n 'aria-describedby': 'error-' + fieldName\n });\n var label = $('#field-label-' + fieldName);\n label.after(self.fieldError({ errors: errors, fieldName: fieldName }));\n } else if(_.isObject(errors[0]) && !_.isArray(errors[0])) {\n // Multiple forms (e.g. properties)\n _.each(errors, function(errors, i) {\n _.each(errors, function(subformErrors, subformFieldName) {\n addErrors(subformErrors, fieldName + '-' + i + '-' + subformFieldName);\n });\n });\n } else {\n _.each(errors, function(subformErrors) {\n addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]);\n });\n }\n }\n\n _.each(errorFields, addErrors);\n\n if(this.$form.data('error-banner') !== false) {\n this.$form.prepend(this.mainFormError({ errors: this.createErrorSummary()}));\n }\n },\n\n loadTemplates: function() {\n this.mainFormError = _.template($('#mainFormError').html());\n this.fieldError = _.template($('#fieldError').html());\n },\n\n clearErrors: function() {\n $('.form-row.field-error').remove();\n $('.alert.alert-error').remove();\n $('.form-error')\n .removeClass('form-error')\n .removeAttr('aria-invalid');\n }\n };\n}());\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000290409,"string":"0.000029"},"diff":{"kind":"string","value":"@@ -3240,12 +3240,14 @@\n ed')\n+ \n ? ''\n+ \n : pr\n"}}},{"rowIdx":2597318,"cells":{"commit":{"kind":"string","value":"ce9b5866133de731e00202a8faa19f7de1ecbd38"},"subject":{"kind":"string","value":"Fix in category filter popup"},"old_file":{"kind":"string","value":"cityproblems/site/static/site/js/index.js"},"new_file":{"kind":"string","value":"cityproblems/site/static/site/js/index.js"},"old_contents":{"kind":"string","value":"var mainPageViewCtrl = function ($scope, $http, $route)\n{\n \"use strict\";\n $scope.showMenu = false;\n $scope.alerts=[];\n \n $scope.$on('$routeChangeSuccess', function(next, current)\n {\n if((current.params.reportBy != $scope.reportBy || current.params.category != $scope.category) && (typeof current.params.reportBy != \"undefined\" && typeof current.params.category != \"undefined\"))\n {\n $scope.reportBy = current.params.reportBy;\n $scope.category = current.params.category;\n loadMarkers();\n }\n });\n \n $scope.init=function(categories)\n {\n $scope.categories = angular.fromJson(categories);\n $scope.tmpCategory = \"all\";\n }\n \n $scope.$watch(\"category\", function(category, oldValue)\n {\n if(category != oldValue)\n for(var i=0;i<$scope.categories.length;++i)\n if($scope.categories[i][\"url_name\"] == category)\n {\n $scope.categoryTitle = $scope.categories[i].title;\n break;\n } \n }\n )\n \n function clearMap()\n {\n if(!$scope.markers)\n {\n $scope.markers=[];\n return;\n }\n for(var i=0;i<$scope.markers.length;++i)\n $scope.markers[i].setMap(null);\n $scope.markers=[];\n }\n\n $scope.map_init=function()\n {\n var zoom = parseInt($scope.zoom);\n if(zoom!=zoom)\n $scope.zoom=11;\n var latitude = parseFloat($scope.latitude.replace(\",\", \".\"));\n var longitude = parseFloat($scope.longitude.replace(\",\", \".\"));\n if(latitude!=latitude || longitude!=longitude)\n {\n alert(\"Wrong map config. Please fix it in site parameters\");\n return;\n }\n var latLng = new google.maps.LatLng(latitude, longitude);\n var mapOptions = {\n zoom: zoom,\n center: latLng,\n mapTypeId: google.maps.MapTypeId.ROADMAP,\n mapTypeControl: false\n }\n $scope.map = new google.maps.Map(document.getElementById(\"map_canvas\"), mapOptions);\n }\n \n function loadMarkers()\n {\n $http.post($scope.loadDataURL, {reportBy: $scope.reportBy, category: $scope.category})\n .success(function(data)\n {\n if (\"error\" in data)\n $scope.alerts.push({type: 'danger', msg: data[\"error\"]});\n else\n {\n clearMap();\n var objList = data[\"problems\"];\n var infowindow = new google.maps.InfoWindow();\n $scope.infowindow=infowindow;\n for(var i=0;i'+objList[i].title+''\n }); \n google.maps.event.addListener(marker, 'click', function () \n {\n infowindow.setContent(this.html);\n infowindow.open($scope.map, this);\n }); \n $scope.markers.push(marker); \n }\n }\n })\n .error(function(data)\n {\n //document.write(data);\n $scope.alerts.push({type: 'danger', msg: \"Error while load data\"});\n });\n }\n \n $scope.closeAlert = function(index)\n {\n $scope.alerts.splice(index, 1);\n };\n};\nmainPageViewCtrl.$inject = [\"$scope\", \"$http\", \"$route\"];\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":8.056e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -539,24 +539,82 @@\n dMarkers();%0A\n+ $('#popup-filter-category').trigger('close');%0A\n %7D%0A \n"}}},{"rowIdx":2597319,"cells":{"commit":{"kind":"string","value":"0e8964f2cca4493045814fb74fb4ea7de53d9242"},"subject":{"kind":"string","value":"Fix paths on Windows"},"old_file":{"kind":"string","value":"lib/asset_types/html5.js"},"new_file":{"kind":"string","value":"lib/asset_types/html5.js"},"old_contents":{"kind":"string","value":"var loader = require(\"@loader\");\nvar nodeRequire = loader._nodeRequire;\nvar path = nodeRequire(\"path\");\n\n// Register the html5-upgrade asset type\nmodule.exports = function(register){\n\tvar shivPath = path.join(__dirname, \"/../../scripts/html5shiv.min.js\");\n\tvar loaderBasePath = loader.baseURL.replace(\"file:\", \"\");\n\tvar shivUrl = path.relative(loaderBasePath, shivPath);\n\n\tregister(\"html5shiv\", function(){\n\t\tvar elements = Object.keys(loader.global.can.view.callbacks._tags)\n\t\t\t.filter(function(tagName) {\n\t\t\t\treturn tagName.indexOf(\"-\") > 0;\n\t\t\t});\n\t\tvar comment = document.createComment(\n\t\t\t\"[if lt IE 9]>\\n\" +\n\t\t\t\"\\t\" +\n\t\t\t\"\\t\" +\n\t\t\t\" {\n console.log('user in sendEmail:', user);\n if(user[0]){\n \n var config = wellknown('GandiMail');\n config.auth = {\n user: 'info@fairshare.cloud',\n pass: 'AeK6yxhT'\n };\n \n var transporter = nodemailer.createTransport(config);\n var mailOptions = {\n from: '\"Info\" ',\n to: '<'+ email +'>',\n subject: \"Click the following link to reset your Fairshare password\",\n html: 'Reset Password'\n };\n\n transporter.sendMail(mailOptions, function(err, info){\n if(err){\n return console.log(err);\n }else{\n res.status(200).send(info);\n }\n });\n }else{\n res.status(401).send('Email is not registered')\n }\n })\n .catch(err => console.warn(err))\n})"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":7.032e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -910,25 +910,31 @@\n http\n+s\n ://\n-localhost:3000\n+www.fairshare.cloud\n /res\n@@ -1303,8 +1303,9 @@\n err))%0A%7D)\n+%0A\n"}}},{"rowIdx":2597321,"cells":{"commit":{"kind":"string","value":"b03df04b45b069a4bea75bed5a8428eb7b1275c2"},"subject":{"kind":"string","value":"reformulate as recursion"},"old_file":{"kind":"string","value":"WordSmushing/smushing.js"},"new_file":{"kind":"string","value":"WordSmushing/smushing.js"},"old_contents":{"kind":"string","value":"\"use strict\";\n\nvar assert = require('assert');\n\nvar smush = function(w1,w2) {\n return w1 + w2;\n};\n\ndescribe('word smushing', function() {\n it('should join words with no overlap', function() {\n\tassert.equal('thecat', smush('the', 'cat'));\n });\n\n it('should do single character overlaps', function() {\n\tassert.equal('henot', smush('hen', 'not'));\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.9999760389,"string":"0.999976"},"diff":{"kind":"string","value":"@@ -79,22 +79,77 @@\n \n-return w1 +\n+if (w1 === '') return w2;%0A%0A return w1%5B0%5D + smush(w1.substr(1),\n w2\n+)\n ;%0A%7D;\n@@ -191,24 +191,29 @@\n n() %7B%0A it\n+.only\n ('should joi\n"}}},{"rowIdx":2597322,"cells":{"commit":{"kind":"string","value":"c4b6024abd81b33562c78c343ecb99e0210ecfb5"},"subject":{"kind":"string","value":"Add test that child nodes are rendered."},"old_file":{"kind":"string","value":"src/components/with-drag-and-drop/draggable-context/__spec__.js"},"new_file":{"kind":"string","value":"src/components/with-drag-and-drop/draggable-context/__spec__.js"},"old_contents":{"kind":"string","value":"import React from 'react';\nimport { DragDropContext } from 'react-dnd';\nimport DraggableContext from './draggable-context';\n\nfdescribe('DraggableContext', () => {\n\n it('is wrapped in a DragDropContextContainer', () => {\n expect(DraggableContext.name).toBe('DragDropContextContainer');\n });\n\n it('has a DecoratedComponent pointing to the original component', () => {\n expect(DraggableContext.DecoratedComponent.name).toBe('DraggableContext');\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.595e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -121,10 +121,41 @@\n t';%0A\n+import %7B mount %7D from 'enzyme';%0A\n %0A\n-f\n desc\n@@ -480,13 +480,378 @@\n );%0A %7D);\n+%0A%0A describe('render', () =%3E %7B%0A it('renders this.props.children', () =%3E %7B%0A let wrapper = mount(%0A %3CDraggableContext%3E%0A %3Cdiv%3E%0A %3Cp%3EOne%3C/p%3E%0A %3Cp%3ETwo%3C/p%3E%0A %3C/div%3E%0A %3C/DraggableContext%3E%0A );%0A%0A expect(wrapper.find('div').length).toEqual(1);%0A expect(wrapper.find('p').length).toEqual(2);%0A %7D);%0A %7D);\n %0A%7D);%0A\n"}}},{"rowIdx":2597323,"cells":{"commit":{"kind":"string","value":"eafcb68040b44a73e6c2d3605e75f75847d2dfef"},"subject":{"kind":"string","value":"update TableHeader"},"old_file":{"kind":"string","value":"src/_TableHeader/TableHeader.js"},"new_file":{"kind":"string","value":"src/_TableHeader/TableHeader.js"},"old_contents":{"kind":"string","value":"/**\n * @file TableHeader component\n * @author liangxiaojun(liangxiaojun@derbysoft.com)\n */\n\nimport React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport classNames from 'classnames';\n\nimport TableHeaderSortIcon from '../_TableHeaderSortIcon';\n\nclass TableHeader extends Component {\n\n constructor(props, ...restArgs) {\n super(props, ...restArgs);\n }\n\n headerRenderer = () => {\n\n const {header, colIndex} = this.props;\n\n switch (typeof header) {\n case 'function':\n return header(colIndex);\n default:\n return header;\n }\n\n };\n\n clickHandler = e => {\n e.preventDefault();\n const {sortable, onSort} = this.props;\n sortable && onSort && onSort();\n };\n\n render() {\n\n const {\n className, style, header, hidden,\n sortable, sortProp, sort, sortAscIconCls, sortDescIconCls\n } = this.props,\n\n finalHeader = this.headerRenderer(),\n\n tableHeaderClassName = classNames('table-header', {\n sortable: sortable,\n hidden: hidden,\n [className]: className\n });\n\n return (\n \n\n
\n\n {finalHeader}\n\n {\n sortable ?\n \n :\n null\n }\n\n
\n\n \n );\n\n }\n}\n\nTableHeader.propTypes = {\n\n className: PropTypes.string,\n style: PropTypes.object,\n\n header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),\n colIndex: PropTypes.number,\n sortable: PropTypes.bool,\n sortProp: PropTypes.string,\n sort: PropTypes.object,\n sortAscIconCls: PropTypes.string,\n sortDescIconCls: PropTypes.string,\n hidden: PropTypes.bool,\n\n onSort: PropTypes.func\n\n};\n\nTableHeader.defaultProps = {\n colIndex: 0,\n sortable: false,\n hidden: false\n};\n\nexport default TableHeader;"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.339e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -653,43 +653,16 @@\n r = \n-e\n+()\n =%3E %7B%0A\n- e.preventDefault();%0A\n \n"}}},{"rowIdx":2597324,"cells":{"commit":{"kind":"string","value":"539dde3653d78ccf4bbf2a67c109167c28f260e6"},"subject":{"kind":"string","value":"version up"},"old_file":{"kind":"string","value":"vendor/ember-simple-token/register-version.js"},"new_file":{"kind":"string","value":"vendor/ember-simple-token/register-version.js"},"old_contents":{"kind":"string","value":"Ember.libraries.register('Ember Simple Token', '1.1.2');\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.047e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -49,9 +49,9 @@\n 1.1.\n-2\n+3\n ');%0A\n"}}},{"rowIdx":2597325,"cells":{"commit":{"kind":"string","value":"69ee5277e50328bf2daa3ef21686dd96a2c58470"},"subject":{"kind":"string","value":"Fix error \"Cannot read property 'min' of undefined\""},"old_file":{"kind":"string","value":"src/models/axis.js"},"new_file":{"kind":"string","value":"src/models/axis.js"},"old_contents":{"kind":"string","value":"/*!\n * VIZABI Axis Model (hook)\n */\n\n(function () {\n\n \"use strict\";\n\n var root = this;\n var Vizabi = root.Vizabi;\n var utils = Vizabi.utils;\n\n //warn client if d3 is not defined\n if (!Vizabi._require('d3')) {\n return;\n }\n\n //constant time formats\n var time_formats = {\n \"year\": d3.time.format(\"%Y\"),\n \"month\": d3.time.format(\"%Y-%m\"),\n \"week\": d3.time.format(\"%Y-W%W\"),\n \"day\": d3.time.format(\"%Y-%m-%d\"),\n \"hour\": d3.time.format(\"%Y-%m-%d %H\"),\n \"minute\": d3.time.format(\"%Y-%m-%d %H:%M\"),\n \"second\": d3.time.format(\"%Y-%m-%d %H:%M:%S\")\n };\n\n Vizabi.Model.extend('axis', {\n /**\n * Initializes the color hook\n * @param {Object} values The initial values of this model\n * @param parent A reference to the parent model\n * @param {Object} bind Initial events to bind\n */\n init: function (values, parent, bind) {\n\n this._type = \"axis\";\n values = utils.extend({\n use: \"value\",\n unit: \"\",\n which: undefined,\n min: null,\n max: null\n }, values);\n this._super(values, parent, bind);\n },\n\n /**\n * Validates a color hook\n */\n validate: function () {\n\n var possibleScales = [\"log\", \"linear\", \"time\", \"pow\"];\n if (!this.scaleType || (this.use === \"indicator\" && possibleScales.indexOf(this.scaleType) === -1)) {\n this.scaleType = 'linear';\n }\n\n if (this.use !== \"indicator\" && this.scaleType !== \"ordinal\") {\n this.scaleType = \"ordinal\";\n }\n\n //TODO a hack that kills the scale, it will be rebuild upon getScale request in model.js\n if (this.which_1 != this.which || this.scaleType_1 != this.scaleType) this.scale = null;\n this.which_1 = this.which;\n this.scaleType_1 = this.scaleType;\n\n if(this.scale && this._readyOnce && this.use==\"indicator\"){\n if(this.min==null) this.min = this.scale.domain()[0];\n if(this.max==null) this.max = this.scale.domain()[1];\n\n if(this.min<=0 && this.scaleType==\"log\") this.min = 0.01;\n if(this.max<=0 && this.scaleType==\"log\") this.max = 10;\n\n // Max may be less than min\n // if(this.min>=this.max) this.min = this.max/2;\n\n if(this.min!=this.scale.domain()[0] || this.max!=this.scale.domain()[1])\n this.scale.domain([this.min, this.max]);\n }\n },\n\n\n /**\n * Gets the domain for this hook\n * @returns {Array} domain\n */\n buildScale: function (margins) {\n var domain;\n var scaleType = this.scaleType || \"linear\";\n\n if (typeof margins === 'boolean') {\n var res = margins;\n margins = {};\n margins.min = res;\n margins.max = res;\n }\n\n if (this.scaleType == \"time\") {\n var limits = this.getLimits(this.which);\n this.scale = d3.time.scale().domain([limits.min, limits.max]);\n return;\n }\n\n switch (this.use) {\n case \"indicator\":\n var limits = this.getLimits(this.which),\n margin = (limits.max - limits.min) / 20;\n\n domain = [(limits.min - (margins.min ? margin : 0)), (limits.max + (margins.max ? margin : 0))];\n if (scaleType == \"log\") {\n domain = [(limits.min - limits.min / 4), (limits.max + limits.max / 4)];\n }\n\n break;\n case \"property\":\n domain = this.getUnique(this.which);\n break;\n case \"value\":\n default:\n domain = [this.which];\n break;\n }\n\n\n if (this.min!=null && this.max!=null && scaleType !== 'ordinal') {\n domain = [this.min, this.max];\n this.min = domain[0];\n this.max = domain[1];\n }\n\n this.scale = d3.scale[scaleType]().domain(domain);\n }\n });\n}).call(this);\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.337e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2530,16 +2530,73 @@\n linear%22;\n+%0A if (margins === undefined)%0A margins = true;\n %0A%0A \n@@ -3130,16 +3130,26 @@\n ins.min \n+&& margin \n ? margin\n@@ -3183,16 +3183,26 @@\n ins.max \n+&& margin \n ? margin\n"}}},{"rowIdx":2597326,"cells":{"commit":{"kind":"string","value":"b97fac279648ce2216a4f01cf6f1ec44e244ef08"},"subject":{"kind":"string","value":"Refresh the whole scrollbar when adapting to size"},"old_file":{"kind":"string","value":"Source/Widget/Scrollbar.js"},"new_file":{"kind":"string","value":"Source/Widget/Scrollbar.js"},"old_contents":{"kind":"string","value":"/*\n---\n \nscript: Scrollbar.js\n \ndescription: Scrollbars for everything\n \nlicense: MIT-style license.\n\nauthors: Yaroslaff Fedin\n \nrequires:\n- ART.Widget.Paint\n- ART.Widget.Section\n- ART.Widget.Button\n- Base/Widget.Trait.Slider\n\nprovides: [ART.Widget.Scrollbar]\n \n...\n*/\n\nART.Widget.Scrollbar = new Class({\n Includes: [\n ART.Widget.Paint,\n Widget.Trait.Slider\n ],\n \n name: 'scrollbar',\n \n position: 'absolute',\n \n layout: {\n 'scrollbar-track#track': {\n 'scrollbar-thumb#thumb': {},\n },\n 'scrollbar-button#decrement': {},\n 'scrollbar-button#increment': {}\n },\n \n layered: {\n stroke: ['stroke'],\n background: ['fill', ['backgroundColor']],\n reflection: ['fill', ['reflectionColor']]\n },\n \n options: {\n slider: {\n wheel: true\n }\n },\n \n initialize: function() {\n this.parent.apply(this, arguments);\n this.setState(this.options.mode);\n },\n \n adaptSize: function(size, old){\n if (!size || $chk(size.height)) size = this.parentNode.size;\n var isVertical = (this.options.mode == 'vertical');\n var other = isVertical ? 'horizontal' : 'vertical';\n var prop = isVertical ? 'height' : 'width';\n var Prop = prop.capitalize();\n var setter = 'set' + Prop;\n var getter = 'getClient' + Prop;\n var value = size[prop];\n if (isNaN(value) || !value) return;\n var invert = this.parentNode[other];\n var scrolled = this.getScrolled();\n $(scrolled).setStyle(prop, size[prop])\n var ratio = size[prop] / $(scrolled)['scroll' + Prop]\n var delta = (!invert || invert.hidden ? 0 : invert.getStyle(prop));\n this[setter](size[prop] - delta);\n var offset = 0;\n if (isVertical) {\n offset += this.track.offset.padding.top + this.track.offset.padding.bottom\n } else {\n offset += this.track.offset.padding.left + this.track.offset.padding.right\n }\n var track = size[prop] - this.increment[getter]() - this.decrement[getter]() - delta - ((this.style.current.strokeWidth || 0) * 2) - offset * 2\n this.track[setter](track);\n this.track.thumb[setter](Math.ceil(track * ratio))\n this.refresh();\n this.parent.apply(this, arguments);\n },\n \n inject: Macro.onion(function(widget) {\n this.adaptToSize(widget.size);\n }),\n \n onSet: function(value) {\n var prop = (this.options.mode == 'vertical') ? 'height' : 'width';\n var direction = (this.options.mode == 'vertical') ? 'top' : 'left';\n var result = (value / 100) * this.parentNode.element['scroll' + prop.capitalize()];\n $(this.getScrolled())['scroll' + direction.capitalize()] = result;\n },\n \n getScrolled: function() {\n if (!this.scrolled) {\n var parent = this;\n while ((parent = parent.parentNode) && !parent.getScrolled);\n this.scrolled = parent.getScrolled ? parent.getScrolled() : this.parentNode.element;\n }\n return this.scrolled;\n },\n \n getTrack: function() {\n return $(this.track)\n },\n \n getTrackThumb: function() {\n return $(this.track.thumb);\n },\n \n hide: Macro.onion(function() {\n this.element.setStyle('display', 'none');\n }),\n \n show: Macro.onion(function() {\n this.element.setStyle('display', 'block');\n })\n})\n\nART.Widget.Scrollbar.Track = new Class({\n Extends: ART.Widget.Section,\n \n layered: {\n innerShadow: ['inner-shadow']\n },\n \n name: 'track',\n \n position: 'absolute'\n});\n\nART.Widget.Scrollbar.Thumb = new Class({\n Extends: ART.Widget.Button,\n \n name: 'thumb'\n});\n\nART.Widget.Scrollbar.Button = new Class({\n Extends: ART.Widget.Button,\n \n position: 'absolute'\n});"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.275e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2090,16 +2090,20 @@\n refresh(\n+true\n );%0A t\n"}}},{"rowIdx":2597327,"cells":{"commit":{"kind":"string","value":"0e4adfa855d599636c70622af81d9475165a3515"},"subject":{"kind":"string","value":"Undo workaround for offline testing."},"old_file":{"kind":"string","value":"client/components/widget/query/data-view-service_test.js"},"new_file":{"kind":"string","value":"client/components/widget/query/data-view-service_test.js"},"old_contents":{"kind":"string","value":"/**\n * @copyright Copyright 2014 Google Inc. All rights reserved.\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n *\n * @fileoverview Tests for the dataViewService service.\n * @author joemu@google.com (Joe Allan Muharsky)\n */\n\ngoog.require('p3rf.perfkit.explorer.application.module');\ngoog.require('p3rf.perfkit.explorer.components.widget.data_viz.gviz.getGvizDataTable');\ngoog.require('p3rf.perfkit.explorer.components.widget.query.DataViewService');\ngoog.require('p3rf.perfkit.explorer.models.DataViewModel');\n\nvar _describe = function() {};\n\n_describe('dataViewService', function() {\n var DataViewModel = p3rf.perfkit.explorer.models.DataViewModel;\n var svc, gvizDataViewMock, gvizDataTable;\n\n beforeEach(module('explorer'));\n\n beforeEach(inject(function(dataViewService, GvizDataTable) {\n svc = dataViewService;\n gvizDataTable = GvizDataTable;\n }));\n\n describe('create', function() {\n var dataTable;\n\n beforeEach(function() {\n var data = {\n cols: [\n {id: 'date', label: 'Date', type: 'date'},\n {id: 'value', label: 'Fake values 1', type: 'number'},\n {id: 'value', label: 'Fake values 2', type: 'number'}\n ],\n rows: [\n {c: [\n {v: '2013/03/03 00:48:04'},\n {v: 0.5},\n {v: 3}\n ]},\n {c: [\n {v: '2013/03/04 00:50:04'},\n {v: 0.1},\n {v: 5}\n ]},\n {c: [\n {v: '2013/03/05 00:59:04'},\n {v: 0.3},\n {v: 1}\n ]},\n {c: [\n {v: '2013/03/06 00:50:04'},\n {v: 0.7},\n {v: 2}\n ]},\n {c: [\n {v: '2013/03/07 00:59:04'},\n {v: 0.2},\n {v: 6}\n ]}\n ]\n };\n\n dataTable = new gvizDataTable(data);\n });\n\n it('should return the correct dataViewJson.', function() {\n var model = new DataViewModel();\n model.columns = [0, 2];\n model.filter = [\n {\n column: 1,\n minValue: 0,\n maxValue: 0.2\n }\n ];\n model.sort = [\n {\n column: 2,\n desc: true\n }\n ];\n\n var dataViewJson = svc.create(dataTable, model);\n\n var expectedDataViewJson = [\n {\n columns: [0, 2],\n rows: [1, 4]\n },\n {\n rows: [1, 0]\n }\n ];\n expect(dataViewJson).toEqual(expectedDataViewJson);\n });\n\n it('should return an error when an error occurred on columns property.',\n function() {\n var model = new DataViewModel();\n model.columns = [-1];\n\n var dataViewJson = svc.create(dataTable, model);\n expect(dataViewJson.error).toBeDefined();\n expect(dataViewJson.error.property).toEqual('columns');\n }\n );\n\n it('should return an error when an error occurred on filter property.',\n function() {\n var model = new DataViewModel();\n model.filter = [-1];\n\n var dataViewJson = svc.create(dataTable, model);\n expect(dataViewJson.error).toBeDefined();\n expect(dataViewJson.error.property).toEqual('filter');\n }\n );\n\n it('should return an error when an error occurred on sort property.',\n function() {\n var model = new DataViewModel();\n model.sort = [-1];\n\n var dataViewJson = svc.create(dataTable, model);\n expect(dataViewJson.error).toBeDefined();\n expect(dataViewJson.error.property).toEqual('sort');\n }\n );\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.244e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1020,41 +1020,8 @@\n );%0A%0A\n-var _describe = function() %7B%7D;%0A%0A_\n desc\n"}}},{"rowIdx":2597328,"cells":{"commit":{"kind":"string","value":"def49f76b0b9a0259aa3cb3e8bca5242f50d65be"},"subject":{"kind":"string","value":"Update LoadCSSJS.min.js"},"old_file":{"kind":"string","value":"LoadCSSJS.min.js"},"new_file":{"kind":"string","value":"LoadCSSJS.min.js"},"old_contents":{"kind":"string","value":"/*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT Licence */\nfunction LoadCSSJS(e,t,r){\"use strict\";var els=\"\";-1==els.indexOf(\"[\"+e+\"]\")?(Loader(e,t,r),els+=\"[\"+e+\"]\"):alert(\"File \"+e+\" already added!\")}function Loader(e,t,r){if(\"css\"==t){var s=document.createElement(\"link\");s.setAttribute(\"rel\",\"stylesheet\"),s.setAttribute(\"href\",e),r?\"\":r=\"all\",s.setAttribute(\"media\",r),s.setAttribute(\"type\",\"text/css\")}else if(\"js\"==t){var s=document.createElement(\"script\");s.setAttribute(\"type\",\"text/javascript\"),s.setAttribute(\"src\",e)}if(\"undefined\"!=typeof s){var a=document.getElementsByTagName(\"head\");a=a[a.length-1],a.appendChild(s)}}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.251e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -128,19 +128,17 @@\n var \n-els\n+a\n =%22%22;-1==\n els.\n@@ -133,19 +133,17 @@\n =%22%22;-1==\n-els\n+a\n .indexOf\n@@ -169,19 +169,17 @@\n (e,t,r),\n-els\n+a\n +=%22%5B%22+e+\n"}}},{"rowIdx":2597329,"cells":{"commit":{"kind":"string","value":"b5c5d531d169f974651b08d3000b541062f71390"},"subject":{"kind":"string","value":"Fix for unhandled promise on fresh db startup"},"old_file":{"kind":"string","value":"core/server/data/migration/index.js"},"new_file":{"kind":"string","value":"core/server/data/migration/index.js"},"old_contents":{"kind":"string","value":"\nvar _ = require('underscore'),\n when = require('when'),\n series = require('when/sequence'),\n errors = require('../../errorHandling'),\n knex = require('../../models/base').Knex,\n\n defaultSettings = require('../default-settings'),\n Settings = require('../../models/settings').Settings,\n fixtures = require('../fixtures'),\n\n initialVersion = '000',\n defaultDatabaseVersion;\n\n// Default Database Version\n// The migration version number according to the hardcoded default settings\n// This is the version the database should be at or migrated to\nfunction getDefaultDatabaseVersion() {\n if (!defaultDatabaseVersion) {\n // This be the current version according to the software\n defaultDatabaseVersion = _.find(defaultSettings.core, function (setting) {\n return setting.key === 'databaseVersion';\n }).defaultValue;\n }\n\n return defaultDatabaseVersion;\n}\n\n// Database Current Version\n// The migration version number according to the database\n// This is what the database is currently at and may need to be updated\nfunction getDatabaseVersion() {\n return knex.Schema.hasTable('settings').then(function (exists) {\n // Check for the current version from the settings table\n if (exists) {\n // Temporary code to deal with old databases with currentVersion settings\n return knex('settings')\n .where('key', 'databaseVersion')\n .orWhere('key', 'currentVersion')\n .select('value')\n .then(function (versions) {\n var databaseVersion = _.reduce(versions, function (memo, version) {\n if (isNaN(version.value)) {\n errors.throwError('Database version is not recognised');\n }\n return parseInt(version.value, 10) > parseInt(memo, 10) ? version.value : memo;\n }, initialVersion);\n\n if (!databaseVersion || databaseVersion.length === 0) {\n // we didn't get a response we understood, assume initialVersion\n databaseVersion = initialVersion;\n }\n\n return databaseVersion;\n });\n }\n return when.reject('Settings table does not exist');\n });\n}\n\nfunction setDatabaseVersion() {\n return knex('settings')\n .where('key', 'databaseVersion')\n .update({ 'value': defaultDatabaseVersion });\n}\n\n\nmodule.exports = {\n getDatabaseVersion: getDatabaseVersion,\n // Check for whether data is needed to be bootstrapped or not\n init: function () {\n var self = this;\n\n // There are 4 possibilities:\n // 1. The database exists and is up-to-date\n // 2. The database exists but is out of date\n // 3. The database exists but the currentVersion setting does not or cannot be understood\n // 4. The database has not yet been created\n return getDatabaseVersion().then(function (databaseVersion) {\n var defaultVersion = getDefaultDatabaseVersion();\n\n if (databaseVersion === defaultVersion) {\n // 1. The database exists and is up-to-date\n return when.resolve();\n }\n\n if (databaseVersion < defaultVersion) {\n // 2. The database exists but is out of date\n return self.migrateUpFromVersion(databaseVersion);\n }\n\n if (databaseVersion > defaultVersion) {\n // 3. The database exists but the currentVersion setting does not or cannot be understood\n // In this case we don't understand the version because it is too high\n errors.logErrorAndExit(\n 'Your database is not compatible with this version of Ghost',\n 'You will need to create a new database'\n );\n }\n\n }, function (err) {\n if (err === 'Settings table does not exist') {\n // 4. The database has not yet been created\n // Bring everything up from initial version.\n return self.migrateUpFreshDb();\n }\n\n // 3. The database exists but the currentVersion setting does not or cannot be understood\n // In this case the setting was missing or there was some other problem\n errors.logErrorAndExit('There is a problem with the database', err.message || err);\n });\n },\n\n // ### Reset\n // Migrate from where we are down to nothing.\n reset: function () {\n var self = this;\n\n return getDatabaseVersion().then(function (databaseVersion) {\n // bring everything down from the current version\n return self.migrateDownFromVersion(databaseVersion);\n }, function () {\n // If the settings table doesn't exist, bring everything down from initial version.\n return self.migrateDownFromVersion(initialVersion);\n });\n },\n\n // Only do this if we have no database at all\n migrateUpFreshDb: function () {\n var migration = require('./' + initialVersion);\n\n return migration.up().then(function () {\n // Load the fixtures\n return fixtures.populateFixtures();\n\n }).then(function () {\n // Initialise the default settings\n return Settings.populateDefaults();\n });\n },\n\n // Migrate from a specific version to the latest\n migrateUpFromVersion: function (version, max) {\n var versions = [],\n maxVersion = max || this.getVersionAfter(getDefaultDatabaseVersion()),\n currVersion = version,\n tasks = [];\n\n // Aggregate all the versions we need to do migrations for\n while (currVersion !== maxVersion) {\n versions.push(currVersion);\n currVersion = this.getVersionAfter(currVersion);\n }\n\n // Aggregate all the individual up calls to use in the series(...) below\n tasks = _.map(versions, function (taskVersion) {\n return function () {\n try {\n var migration = require('./' + taskVersion);\n return migration.up();\n } catch (e) {\n errors.logError(e);\n return when.reject(e);\n }\n };\n });\n\n // Run each migration in series\n return series(tasks).then(function () {\n // Finally update the databases current version\n return setDatabaseVersion();\n });\n },\n\n migrateDownFromVersion: function (version) {\n var self = this,\n versions = [],\n minVersion = this.getVersionBefore(initialVersion),\n currVersion = version,\n tasks = [];\n\n // Aggregate all the versions we need to do migrations for\n while (currVersion !== minVersion) {\n versions.push(currVersion);\n currVersion = this.getVersionBefore(currVersion);\n }\n\n // Aggregate all the individual up calls to use in the series(...) below\n tasks = _.map(versions, function (taskVersion) {\n return function () {\n try {\n var migration = require('./' + taskVersion);\n return migration.down();\n } catch (e) {\n errors.logError(e);\n return self.migrateDownFromVersion(initialVersion);\n }\n };\n });\n\n // Run each migration in series\n return series(tasks);\n },\n\n // Get the following version based on the current\n getVersionAfter: function (currVersion) {\n\n var currVersionNum = parseInt(currVersion, 10),\n nextVersion;\n\n // Default to initialVersion if not parsed\n if (isNaN(currVersionNum)) {\n currVersionNum = parseInt(initialVersion, 10);\n }\n\n currVersionNum += 1;\n\n nextVersion = String(currVersionNum);\n // Pad with 0's until 3 digits\n while (nextVersion.length < 3) {\n nextVersion = \"0\" + nextVersion;\n }\n\n return nextVersion;\n },\n\n getVersionBefore: function (currVersion) {\n var currVersionNum = parseInt(currVersion, 10),\n prevVersion;\n\n if (isNaN(currVersionNum)) {\n currVersionNum = parseInt(initialVersion, 10);\n }\n\n currVersionNum -= 1;\n\n prevVersion = String(currVersionNum);\n // Pad with 0's until 3 digits\n while (prevVersion.length < 3) {\n prevVersion = \"0\" + prevVersion;\n }\n\n return prevVersion;\n }\n};"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.211e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2344,34 +2344,31 @@\n \n-return when.reject\n+throw new Error\n ('Settin\n@@ -4041,16 +4041,31 @@\n if (err\n+.message %7C%7C err\n === 'Se\n"}}},{"rowIdx":2597330,"cells":{"commit":{"kind":"string","value":"cd3aa58988d8bdadfae7449052eeaa410bd385a6"},"subject":{"kind":"string","value":"Fix import bug in make-html command."},"old_file":{"kind":"string","value":"lib/cli/cmd/make-html.js"},"new_file":{"kind":"string","value":"lib/cli/cmd/make-html.js"},"old_contents":{"kind":"string","value":"/* dendry\n * http://github.com/idmillington/dendry\n *\n * MIT License\n */\n/*jshint indent:2 */\n(function() {\n \"use strict\";\n\n var path = require('path');\n var fs = require('fs');\n var handlebars = require('handlebars');\n var async = require('async');\n var browserify = require('browserify');\n var uglify = require('uglify-js');\n\n var utils = require('../utils');\n var cmdCompile = require('./compile').cmd;\n\n var loadGameAndSource = function(data, callback) {\n utils.loadCompiledGame(data.compiledPath, function(err, game, json) {\n if (err) return callback(err);\n data.gameFile = json;\n data.game = game;\n callback(null, data);\n });\n };\n\n var browserifyUI = function(data, callback) {\n var b = browserify();\n b.add(path.resolve(__dirname, \"../../ui/browser.js\"));\n b.bundle(function(err, buffer) {\n if (err) return callback(err);\n var str = buffer.toString();\n data.browserify = str;\n return callback(null, data);\n });\n };\n\n var uglifyBundle = function(data, callback) {\n var gameFile = data.gameFile.toString();\n var wrappedGameFile = JSON.stringify({compiled:gameFile});\n var content = [\"window.game=\"+wrappedGameFile+\";\", data.browserify];\n var result = uglify.minify(content, {fromString: true, compress:{}});\n data.code = content.join(\"\");//result.code;\n return callback(null, data);\n };\n\n var getTemplateDir = function(data, callback) {\n utils.getTemplatePath(\n data.template, \"html\",\n function(err, templateDir, name) {\n if (err) return callback(err);\n data.templateDir = templateDir;\n data.template = name;\n return callback(null, data);\n });\n };\n\n var getDestDir = function(data, callback) {\n data.destDir = path.join(data.projectDir, \"out\", \"html\");\n callback(null, data);\n };\n\n var notifyUser = function(data, callback) {\n console.log((\"Creating HTML build in: \"+data.destDir).grey);\n console.log((\"Using template: \"+data.template).grey);\n callback(null, data);\n };\n\n var createHTML = function(data, callback) {\n fs.exists(data.destDir, function(exists) {\n if (exists) {\n console.log(\"Warning: Overwriting existing HTML content.\".red);\n }\n utils.copyTemplate(\n data.templateDir, data.destDir, data,\n function(err) {\n if (err) return callback(err);\n else return(null, data);\n });\n });\n };\n\n // ----------------------------------------------------------------------\n // Make-HTML: Creates a playable HTML version of the game.\n // ----------------------------------------------------------------------\n\n var cmdMakeHTML = new utils.Command(\"make-html\");\n cmdMakeHTML.createArgumentParser = function(subparsers) {\n var parser = subparsers.addParser(this.name, {\n help: \"Make a project into a playable HTML page.\",\n description: \"Builds a HTML version of a game, compiling it first \"+\n \"if it is out of date. The compilation uses a template which \"+\n \"can be a predefined template, or the path to a directory. \"+\n \"Templates use the handlebars templating system. The default \"+\n \"HTML template (called 'default') compresses the browser interface \"+\n \"and your game content and embeds it in a single HTML file, for the \"+\n \"most portable game possible.\"\n });\n parser.addArgument(['project'], {\n nargs: \"?\",\n help: \"The project to compile (default: the current directory).\"\n });\n parser.addArgument(['-t', '--template'], {\n help: \"A theme template to use (default: the 'default' theme). \"+\n \"Can be the name of a built-in theme, or the path to a theme.\"\n });\n parser.addArgument(['-f', '--force'], {\n action: \"storeTrue\",\n default: false,\n help: \"Always recompiles, even if the compiled game is up to date.\"\n });\n };\n cmdMakeHTML.run = function(args, callback) {\n var getData = function(callback) {\n cmdCompile.run(args, callback);\n };\n\n async.waterfall([getData, loadGameAndSource,\n browserifyUI, uglifyBundle,\n getTemplateDir, getDestDir,\n notifyUser, createHTML], callback);\n };\n\n module.exports = {\n cmd: cmdMakeHTML\n };\n}());\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.229e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -359,24 +359,76 @@\n ../utils');%0A\n+ var compiler = require('../../parsers/compiler');%0A\n var cmdCom\n@@ -518,21 +518,24 @@\n ) %7B%0A \n-utils\n+compiler\n .loadCom\n@@ -1382,22 +1382,8 @@\n %22%22);\n-//result.code;\n %0A \n"}}},{"rowIdx":2597331,"cells":{"commit":{"kind":"string","value":"7ef05101fafd008f7886571b2595bc810025f4aa"},"subject":{"kind":"string","value":"Fix floatbar behaviour on \"More threads/posts\" clicks."},"old_file":{"kind":"string","value":"client/common/system/floatbar/floatbar.js"},"new_file":{"kind":"string","value":"client/common/system/floatbar/floatbar.js"},"old_contents":{"kind":"string","value":"'use strict';\n\n\nvar _ = require('lodash');\n\n\nN.wire.on('navigate.done', function () {\n var $window = $(window)\n , $floatbar = $('#floatbar')\n , isFixed = false\n , navTop;\n\n // Remove previous floatbar handlers if any.\n $window.off('scroll.floatbar');\n\n if (0 === $floatbar.length) {\n // Do nothing if there's no floatbar.\n return;\n }\n\n navTop = $floatbar.offset().top;\n isFixed = false;\n\n function updateFloatbarState() {\n var scrollTop = $window.scrollTop();\n\n if (scrollTop >= navTop && !isFixed) {\n isFixed = true;\n $floatbar.addClass('floatbar-fixed');\n\n } else if (scrollTop <= navTop && isFixed) {\n isFixed = false;\n $floatbar.removeClass('floatbar-fixed');\n }\n }\n\n updateFloatbarState();\n\n $window.on('scroll.floatbar', _.throttle(updateFloatbarState, 100));\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.055e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -183,90 +183,8 @@\n p;%0A%0A\n- // Remove previous floatbar handlers if any.%0A $window.off('scroll.floatbar');%0A%0A\n if\n@@ -744,8 +744,317 @@\n ));%0A%7D);%0A\n+%0A%0AN.wire.on('navigate.exit', function () %7B%0A // Remove floatbar event handler.%0A $(window).off('scroll.floatbar');%0A%0A // Get floatbar back to the initial position to ensure next %60navigate.done%60%0A // handler will obtain correct floatbar offset on next call.%0A $('#floatbar').removeClass('floatbar-fixed');%0A%7D);%0A\n"}}},{"rowIdx":2597332,"cells":{"commit":{"kind":"string","value":"b9dcce9939f2bcaeec8d4dbc4d8607e3b6ba856a"},"subject":{"kind":"string","value":"remove console statement"},"old_file":{"kind":"string","value":"client/components/projects/ProjectItem.js"},"new_file":{"kind":"string","value":"client/components/projects/ProjectItem.js"},"old_contents":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { Link } from 'react-router-dom';\nimport { formatTime } from '../../helpers';\n\nclass ProjectItem extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n showInput: false,\n newName: '',\n };\n this.handleNewName = this.handleNewName.bind(this);\n this.handleRenaming = this.handleRenaming.bind(this);\n this.handleShowInput = this.handleShowInput.bind(this);\n this.handleEnterButton = this.handleEnterButton.bind(this);\n }\n\n handleNewName(e) {\n this.setState({ newName: e.target.value });\n }\n\n handleShowInput(name) {\n this.setState({\n showInput: !this.state.showInput,\n newName: name,\n });\n }\n\n handleRenaming(id, name) {\n this.props.renameMe(id, name);\n this.setState({\n showInput: false,\n });\n }\n\n handleEnterButton(event) {\n if (event.charCode === 13) {\n this.renameLink.click();\n }\n }\n\n render() {\n const { project, onDelete } = this.props;\n const { newName, showInput } = this.state;\n const hideTaskName = this.state.showInput ? 'none' : '';\n console.log(project);\n return (\n \n \n {project.name}\n {formatTime(project.timeSpent)}\n \n {showInput ? (\n \n ) : null}\n
\n {showInput ? (\n \n this.handleRenaming(project._id, this.state.newName)\n }\n ref={link => {\n this.renameLink = link;\n }}\n className=\"button--info\"\n >\n Ok\n \n ) : null}\n this.handleShowInput(project.name)}\n className=\"button--info\"\n >\n Edit\n \n\n onDelete(project._id)}\n className=\"button--info button--danger\"\n >\n Delete\n \n
\n \n );\n }\n}\n\nProjectItem.propTypes = {\n project: PropTypes.object.isRequired,\n onDelete: PropTypes.func.isRequired,\n renameMe: PropTypes.func.isRequired,\n padding: PropTypes.number.isRequired,\n};\n\nexport default ProjectItem;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000315973,"string":"0.000032"},"diff":{"kind":"string","value":"@@ -1129,34 +1129,8 @@\n '';%0A\n- console.log(project);%0A\n \n"}}},{"rowIdx":2597333,"cells":{"commit":{"kind":"string","value":"bd57d8643a445faf8777c4d2961821cfa8e56288"},"subject":{"kind":"string","value":"connect relevancy feature flag to experiment"},"old_file":{"kind":"string","value":"share/spice/news/news.js"},"new_file":{"kind":"string","value":"share/spice/news/news.js"},"old_contents":{"kind":"string","value":"(function (env) {\n \"use strict\";\n env.ddg_spice_news = function (api_result) {\n\n if (!api_result || !api_result.results) {\n return Spice.failed('news');\n }\n\n var useRelevancy = false,\n entityWords = [],\n goodStories = [],\n searchTerm = DDG.get_query().replace(/(?: news|news ?)/i, '').trim(),\n\n // Some sources need to be set by us.\n setSourceOnStory = function(story) {\n switch(story.syndicate) {\n case \"Topsy\":\n story.source = story.author || \"Topsy\";\n break;\n case \"NewsCred\":\n if(story.source) {\n if(story.author) {\n story.source = story.source + \" by \" + story.author;\n }\n } else {\n story.source = \"NewsCred\";\n }\n break;\n }\n };\n\n \n if (useRelevancy) {\n // Words that we have to skip in DDG.isRelevant.\n var skip = [\n \"news\",\n \"headline\",\n \"headlines\",\n \"latest\",\n \"breaking\",\n \"update\",\n \"s:d\",\n \"sort:date\"\n ];\n\n if (Spice.news && Spice.news.entities && Spice.news.entities.length) {\n for (var j = 0, entity; entity = Spice.news.entities[j]; j++) {\n var tmpEntityWords = entity.split(\" \");\n for (var k = 0, entityWord; entityWord = tmpEntityWords[k]; k++) {\n if (entityWord.length > 3) {\n entityWords.push(entityWord);\n }\n }\n }\n }\n }\n\n // Check if the title is relevant to the query.\n for(var i = 0, story; story = api_result.results[i]; i++) {\n if (!useRelevancy || DDG.isRelevant(story.title, skip)) {\n setSourceOnStory(story);\n story.sortableDate = parseInt(story.date || 0);\n goodStories.push(story);\n\n // additional news relevancy for entities. story need only\n // contain one word from one entity to be good. strict indexof\n // check though.\n } else if (entityWords.length > 0) {\n var storyOk = 0;\n var tmpStoryTitle = story.title.toLowerCase();\n\n for (var k = 0, entityWord; entityWord = entityWords[k]; k++) {\n if (tmpStoryTitle.indexOf(entityWord) !== -1) {\n storyOk = 1;\n break;\n }\n }\n\n if (storyOk) {\n setSourceOnStory(story);\n goodStories.push(story);\n }\n }\n }\n\n if (useRelevancy && goodStories < 3) {\n return Spice.failed('news');\n }\n\n\n Spice.add({\n id: 'news',\n name: 'News',\n data: goodStories,\n ads: api_result.ads,\n meta: {\n idField: 'url',\n count: goodStories.length,\n searchTerm: searchTerm,\n itemType: 'Recent News',\n rerender: [\n 'image'\n ]\n },\n templates: {\n item: 'news_item'\n },\n onItemShown: function(item) {\n if (!item.fetch_image || item.image || item.fetched_image) { return; }\n\n // set flag so we don't try to fetch more than once:\n item.fetched_image = 1;\n\n // try to fetch the image and set it on the model\n // which will trigger the tile to re-render with the image:\n $.getJSON('/f.js?o=json&i=1&u=' + item.url, function(meta) {\n if (meta && meta.image) {\n item.set('image', meta.image); \n }\n });\n },\n sort_fields: {\n date: function(a, b) {\n return b.sortableDate - a.sortableDate;\n }\n },\n sort_default: 'date'\n });\n }\n}(this));\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.023e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -212,13 +212,104 @@\n y = \n-false\n+DDG.opensearch.installed.experiment === %22organic_ux%22 && DDG.opensearch.installed.variant === 'b'\n ,%0A \n"}}},{"rowIdx":2597334,"cells":{"commit":{"kind":"string","value":"4bb1faa246cff960a7a28ea85d000bd69cd30b23"},"subject":{"kind":"string","value":"Fix bug with incorrect 'auto storage' calculation when more than 3"},"old_file":{"kind":"string","value":"src/app/components/player/player.controller.js"},"new_file":{"kind":"string","value":"src/app/components/player/player.controller.js"},"old_contents":{"kind":"string","value":"export default class PlayerController {\n\tconstructor($rootScope, $scope, $log, $uibModal, _, toastr, playersApi, playerModel, websocket) {\n\t\t'ngInject';\n\n\t\tthis.$rootScope = $rootScope;\n\t\tthis.$scope = $scope;\n\t\tthis.$log = $log.getInstance(this.constructor.name);\n\t\tthis.$uibModal = $uibModal;\n\n\t\tthis._ = _;\n\t\tthis.toastr = toastr;\n\n\t\tthis.playerModel = playerModel; // Used in template\n\t\tthis.playersApi = playersApi;\n\t\tthis.ws = websocket;\n\n\t\tthis.$log.debug('constructor()', this);\n\t}\n\n\t$onInit() {\n\t\tthis.$log.debug('$onInit()', this);\n\n\t\tthis.$rootScope.$on('deck:action:winter', () => {\n\t\t\tthis.$log.debug('deck:action:winter');\n\n\t\t\tif (this.player.id === this.playerModel.model.player.id) {\n\t\t\t\tthis.playerModel.showSpecialCards();\n\t\t\t}\n\t\t});\n\t}\n\n\t$onDestroy() {\n\t\tthis.$log.debug('$onDestroy()', this);\n\t}\n\n\tcanStoreCards(cardsSelected) {\n\t\tif (this.game.actionCard || !cardsSelected || cardsSelected.length !== 3) {\n\t\t\treturn false;\n\t\t}\n\n\t\tlet cardsMatch = this._.reduce(cardsSelected, (prev, current, index, array) => {\n\t\t\tlet len = array.length,\n\t\t\t\tsameCard = prev.amount === current.amount;\n\n\t\t\tif (!prev) {\n\t\t\t\t// If the previous object is 'false', then cards don't match\n\t\t\t\treturn false;\n\t\t\t} else if (sameCard && index === len - 1) {\n\t\t\t\t// Reached the end of the array and all values matched\n\t\t\t\treturn true;\n\t\t\t}\n\n\t\t\treturn sameCard ? current : false;\n\t\t});\n\n\t\treturn cardsMatch;\n\t}\n\n\tgetCurrentPlayer() {\n\t\treturn this.playerModel.model.player;\n\t}\n\n\tonStorageClick(evt) {\n\t\tlet cardsSelected = this.player.cardsSelected;\n\n\t\tthis.$log.debug('onStorageClick()', evt, cardsSelected, this);\n\n\t\tevt.preventDefault();\n\n\t\tif (this.player.isActive && this.player.hasDrawnCard && this.canStoreCards(cardsSelected)) {\n\t\t\tthis.storeCards(cardsSelected);\n\t\t} else {\n\t\t\tthis.showStorage(this.player);\n\t\t}\n\t}\n\n\tonStorageAutoClick(evt) {\n\t\tevt.preventDefault();\n\n\t\tif (this.player.isActive && !this.player.isFirstTurn) {\n\t\t\t// Filter out sets of 3 that have the same 'amount'\n\t\t\tthis.playerModel.getCards()\n\t\t\t\t.then(res => {\n\t\t\t\t\tlet cards = this._.filter(res.data, (o) => {\n\t\t\t\t\t\t\treturn o.cardType === 'number';\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tnumberCards = this._.groupBy(cards, (o) => {\n\t\t\t\t\t\t\treturn o.amount;\n\t\t\t\t\t\t}),\n\t\t\t\t\t\tisStored = false;\n\n\t\t\t\t\tthis.$log.info('numberCards -> ', numberCards);\n\n\t\t\t\t\tthis._.forEach(numberCards, (cardsGroup) => {\n\t\t\t\t\t\tif (cardsGroup.length % 3 === 0) {\n\t\t\t\t\t\t\tthis.storeCards(cardsGroup);\n\t\t\t\t\t\t\tisStored = true;\n\t\t\t\t\t\t}\n\t\t\t\t\t});\n\n\t\t\t\t\tif (!isStored) {\n\t\t\t\t\t\tthis.toastr.warning('No matching cards to store!');\n\t\t\t\t\t}\n\t\t\t\t}, (err) => {\n\t\t\t\t\tthis.$log.error(err);\n\t\t\t\t});\n\t\t}\n\t}\n\n\tstoreCards(cardsSelected) {\n\t\tlet cardsInStorage = this.player.cardsInStorage,\n\t\t\tcardsInHand = this.player.cardsInHand,\n\t\t\tonSuccess = (res => {\n\t\t\t\tif (res.status == 200) {\n\t\t\t\t\tthis.$log.debug(res);\n\t\t\t\t}\n\t\t\t}),\n\t\t\tonError = (err => {\n\t\t\t\tthis.$log.error(err);\n\t\t\t}),\n\t\t\tcardIds = this._.map(cardsSelected, (obj) => {\n\t\t\t\treturn obj.id;\n\t\t\t});\n\n\t\tcardsInStorage.push(cardIds[0]);\n\t\tthis._.pullAll(cardsInHand, cardIds);\n\n\t\tlet plData = {\n\t\t\tcardsInHand: cardsInHand,\n\t\t\tcardsInStorage: cardsInStorage,\n\t\t\tscore: this.player.score + cardsSelected[0].amount\n\t\t};\n\n\t\tthis.playersApi\n\t\t\t.update(this.player.id, plData)\n\t\t\t.then(onSuccess, onError);\n\n\t\tthis.player.cardsSelected = [];\n\t}\n\n\tshowStorage(pl) {\n\t\tlet onClose = (data => {\n\t\t\t\tthis.$log.debug('onClose()', data, this);\n\t\t\t}),\n\t\t\tonError = (err => {\n\t\t\t\tif (err !== 'backdrop click') {\n\t\t\t\t\tthis.$log.error(err);\n\t\t\t\t}\n\t\t\t});\n\n\t\tthis.$log.debug('showStorage()', pl, this);\n\n\t\tlet modal = this.$uibModal.open({\n\t\t\tappendTo: angular.element(document).find('players'),\n\t\t\tcomponent: 'storageModal',\n\t\t\tresolve: {\n\t\t\t\tplayer: () => {\n\t\t\t\t\treturn this.player;\n\t\t\t\t}\n\t\t\t}\n\t\t});\n\n\t\tmodal.result.then(onClose, onError);\n\t}\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":9.896e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -2254,12 +2254,13 @@\n log.\n-info\n+debug\n ('nu\n@@ -2347,19 +2347,42 @@\n %7B%0A%09%09%09%09%09%09\n-if \n+let numGroups = Math.floor\n (cardsGr\n@@ -2396,20 +2396,200 @@\n gth \n-%25 3 === 0) %7B\n+/ 3),%0A%09%09%09%09%09%09%09numToStore = numGroups * 3;%0A%0A%09%09%09%09%09%09if (numToStore) %7B%0A%09%09%09%09%09%09%09let cardsToStore = this._.sampleSize(cardsGroup, numToStore);%0A%09%09%09%09%09%09%09this.$log.debug('cardsToStore -%3E ', cardsToStore);\n %0A%09%09%09\n@@ -2613,21 +2613,23 @@\n ds(cards\n-Group\n+ToStore\n );%0A%09%09%09%09%09\n"}}},{"rowIdx":2597335,"cells":{"commit":{"kind":"string","value":"75aa9ab5476e62adbb5abbbaaf8cbfbf5933ea94"},"subject":{"kind":"string","value":"stop serving bower_components separately. bower_components are now inside the app directory (ionic/www) and hence get served along with the app directory."},"old_file":{"kind":"string","value":"server/boot/dev-assets.js"},"new_file":{"kind":"string","value":"server/boot/dev-assets.js"},"old_contents":{"kind":"string","value":"var path = require('path');\n\nmodule.exports = function(app) {\n if (!app.get('isDevEnv')) return;\n\n var serveDir = app.loopback.static;\n\n app.use(serveDir(projectPath('.tmp')));\n app.use('/bower_components', serveDir(projectPath('client/bower_components')));\n // app.use('/bower_components', serveDir(projectPath('bower_components')));\n app.use('/lbclient', serveDir(projectPath('client/lbclient')));\n};\n\nfunction projectPath(relative) {\n return path.resolve(__dirname, '../..', relative);\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -169,24 +169,26 @@\n ('.tmp')));%0A\n+//\n app.use('/\n"}}},{"rowIdx":2597336,"cells":{"commit":{"kind":"string","value":"7b3e3cbad51dfa66fa7aa81bb74a93419c3a19c9"},"subject":{"kind":"string","value":"add fn assertion to app.use(). Closes #337"},"old_file":{"kind":"string","value":"lib/application.js"},"new_file":{"kind":"string","value":"lib/application.js"},"old_contents":{"kind":"string","value":"/**\n * Module dependencies.\n */\n\nvar debug = require('debug')('koa:application');\nvar Emitter = require('events').EventEmitter;\nvar compose = require('koa-compose');\nvar isJSON = require('koa-is-json');\nvar response = require('./response');\nvar context = require('./context');\nvar request = require('./request');\nvar onFinished = require('on-finished');\nvar Cookies = require('cookies');\nvar accepts = require('accepts');\nvar status = require('statuses');\nvar assert = require('assert');\nvar Stream = require('stream');\nvar http = require('http');\nvar only = require('only');\nvar co = require('co');\n\n/**\n * Application prototype.\n */\n\nvar app = Application.prototype;\n\n/**\n * Expose `Application`.\n */\n\nexports = module.exports = Application;\n\n/**\n * Initialize a new `Application`.\n *\n * @api public\n */\n\nfunction Application() {\n if (!(this instanceof Application)) return new Application;\n this.env = process.env.NODE_ENV || 'development';\n this.subdomainOffset = 2;\n this.poweredBy = true;\n this.middleware = [];\n this.context = Object.create(context);\n this.request = Object.create(request);\n this.response = Object.create(response);\n}\n\n/**\n * Inherit from `Emitter.prototype`.\n */\n\nApplication.prototype.__proto__ = Emitter.prototype;\n\n/**\n * Shorthand for:\n *\n * http.createServer(app.callback()).listen(...)\n *\n * @param {Mixed} ...\n * @return {Server}\n * @api public\n */\n\napp.listen = function(){\n debug('listen');\n var server = http.createServer(this.callback());\n return server.listen.apply(server, arguments);\n};\n\n/**\n * Return JSON representation.\n * We only bother showing settings.\n *\n * @return {Object}\n * @api public\n */\n\napp.inspect =\napp.toJSON = function(){\n return only(this, [\n 'subdomainOffset',\n 'poweredBy',\n 'env'\n ]);\n};\n\n/**\n * Use the given middleware `fn`.\n *\n * @param {GeneratorFunction} fn\n * @return {Application} self\n * @api public\n */\n\napp.use = function(fn){\n assert('GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function');\n debug('use %s', fn._name || fn.name || '-');\n this.middleware.push(fn);\n return this;\n};\n\n/**\n * Return a request handler callback\n * for node's native http server.\n *\n * @return {Function}\n * @api public\n */\n\napp.callback = function(){\n var mw = [respond].concat(this.middleware);\n var gen = compose(mw);\n var fn = co(gen);\n var self = this;\n\n if (!this.listeners('error').length) this.on('error', this.onerror);\n\n return function(req, res){\n res.statusCode = 404;\n var ctx = self.createContext(req, res);\n onFinished(res, ctx.onerror);\n fn.call(ctx, ctx.onerror);\n }\n};\n\n/**\n * Initialize a new context.\n *\n * @api private\n */\n\napp.createContext = function(req, res){\n var context = Object.create(this.context);\n var request = context.request = Object.create(this.request);\n var response = context.response = Object.create(this.response);\n context.app = request.app = response.app = this;\n context.req = request.req = response.req = req;\n context.res = request.res = response.res = res;\n request.ctx = response.ctx = context;\n request.response = response;\n response.request = request;\n context.onerror = context.onerror.bind(context);\n context.originalUrl = request.originalUrl = req.url;\n context.cookies = new Cookies(req, res, this.keys);\n context.accept = request.accept = accepts(req);\n return context;\n};\n\n/**\n * Default error handler.\n *\n * @param {Error} err\n * @api private\n */\n\napp.onerror = function(err){\n assert(err instanceof Error, 'non-error thrown: ' + err);\n\n if (404 == err.status) return;\n if ('test' == this.env) return;\n\n var msg = err.stack || err.toString();\n console.error();\n console.error(msg.replace(/^/gm, ' '));\n console.error();\n};\n\n/**\n * Response middleware.\n */\n\nfunction *respond(next) {\n if (this.app.poweredBy) this.set('X-Powered-By', 'koa');\n\n yield *next;\n\n // allow bypassing koa\n if (false === this.respond) return;\n\n var res = this.res;\n if (res.headersSent || !this.writable) return;\n\n var body = this.body;\n var code = this.status;\n\n // ignore body\n if (status.empty[code]) {\n // strip headers\n this.body = null;\n return res.end();\n }\n\n if ('HEAD' == this.method) {\n if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body));\n return res.end();\n }\n\n // status body\n if (null == body) {\n this.type = 'text';\n body = status[code];\n if (body) this.length = Buffer.byteLength(body);\n return res.end(body);\n }\n\n // responses\n if (Buffer.isBuffer(body)) return res.end(body);\n if ('string' == typeof body) return res.end(body);\n if (body instanceof Stream) return body.pipe(res);\n\n // body: json\n body = JSON.stringify(body);\n this.length = Buffer.byteLength(body);\n res.end(body);\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":8.24e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -1926,16 +1926,22 @@\n assert(\n+fn && \n 'Generat\n"}}},{"rowIdx":2597337,"cells":{"commit":{"kind":"string","value":"ba0731679463757c03975f43fdbe63ed22675aff"},"subject":{"kind":"string","value":"Improve copy Grunt task structure"},"old_file":{"kind":"string","value":"grunt/copy.js"},"new_file":{"kind":"string","value":"grunt/copy.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nmodule.exports = {\n\n fonts: {\n files: [\n {\n expand: true,\n cwd: '<%= paths.src %>/fonts/',\n src: ['**/*'],\n dest: '<%= paths.dist %>/fonts/',\n },\n {\n expand: true,\n cwd: '<%= paths.bower %>/bootstrap/fonts/',\n src: ['**/*'],\n dest: '<%= paths.dist %>/fonts/',\n },\n {\n expand: true,\n cwd: '<%= paths.bower %>/',\n src: ['ckeditor/**/*'],\n dest: '<%= paths.dist %>/vendor/',\n },\n ],\n },\n\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000328598,"string":"0.000033"},"diff":{"kind":"string","value":"@@ -344,32 +344,53 @@\n nts/',%0A %7D,%0A\n+ %5D,%0A vendor: %5B%0A\n %7B%0A \n"}}},{"rowIdx":2597338,"cells":{"commit":{"kind":"string","value":"b2b4408b2401fba7d7ad971b69c40b5d47720ee4"},"subject":{"kind":"string","value":"optimize DraggableGridGroup"},"old_file":{"kind":"string","value":"src/_DraggableGridGroup/DraggableGridGroup.js"},"new_file":{"kind":"string","value":"src/_DraggableGridGroup/DraggableGridGroup.js"},"old_contents":{"kind":"string","value":"/**\n * @file DraggableGridGroup component\n * @author liangxiaojun(liangxiaojun@derbysoft.com)\n */\n\nimport React, {Component} from 'react';\nimport PropTypes from 'prop-types';\nimport {DragSource, DropTarget} from 'react-dnd';\n\nimport DraggableGridItem from '../_DraggableGridItem';\nimport Theme from '../Theme';\n\nimport DragDrop from '../_vendors/DragDrop';\n\nconst DRAG_GRID_GROUP_SYMBOL = Symbol('DRAG_GRID_GROUP');\n\n@DropTarget(DRAG_GRID_GROUP_SYMBOL, DragDrop.getVerticalTarget(), connect => ({\n connectDropTarget: connect.dropTarget()\n}))\n@DragSource(DRAG_GRID_GROUP_SYMBOL, DragDrop.getSource(), (connect, monitor) => ({\n connectDragPreview: connect.dragPreview(),\n connectDragSource: connect.dragSource(),\n isDragging: monitor.isDragging()\n}))\nexport default class DraggableGridGroup extends Component {\n\n constructor(props, ...restArgs) {\n super(props, ...restArgs);\n }\n\n render() {\n\n const {\n connectDragPreview, connectDragSource, connectDropTarget, isDragging,\n children, className, style, theme, text, iconCls, rightIconCls, anchorIconCls, isDraggableAnyWhere,\n disabled, isLoading, onMouseEnter, onMouseLeave\n } = this.props,\n\n listGroupClassName = (theme ? ` theme-${theme}` : '') + (isDragging ? ' dragging' : '')\n + (isDraggableAnyWhere ? ' draggable' : '') + (className ? ' ' + className : ''),\n\n anchorEl = ,\n\n el = connectDropTarget(\n
\n\n \n\n
\n {children}\n
\n\n {\n isDraggableAnyWhere ?\n anchorEl\n :\n connectDragSource(anchorEl)\n }\n\n
\n );\n\n return isDraggableAnyWhere ?\n connectDragSource(el)\n :\n connectDragPreview(el);\n\n }\n};\n\nDraggableGridGroup.propTypes = {\n\n connectDragPreview: PropTypes.func,\n connectDragSource: PropTypes.func,\n connectDropTarget: PropTypes.func,\n isDragging: PropTypes.bool,\n\n /**\n * The CSS class name of the grid button.\n */\n className: PropTypes.string,\n\n /**\n * Override the styles of the grid button.\n */\n style: PropTypes.object,\n\n /**\n * The theme of the grid button.\n */\n theme: PropTypes.oneOf(Object.keys(Theme).map(key => Theme[key])),\n\n /**\n * The text value of the grid button. Type can be string or number.\n */\n value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),\n\n /**\n * The grid item's display text. Type can be string, number or bool.\n */\n text: PropTypes.any,\n\n /**\n * If true, the grid button will be disabled.\n */\n disabled: PropTypes.bool,\n\n /**\n * If true,the button will be have loading effect.\n */\n isLoading: PropTypes.bool,\n\n /**\n * Use this property to display an icon. It will display on the left.\n */\n iconCls: PropTypes.string,\n\n /**\n * Use this property to display an icon. It will display on the right.\n */\n rightIconCls: PropTypes.string,\n\n /**\n *\n */\n anchorIconCls: PropTypes.string,\n\n /**\n *\n */\n isDraggableAnyWhere: PropTypes.bool,\n\n /**\n *\n */\n onMouseEnter: PropTypes.func,\n\n /**\n *\n */\n onMouseLeave: PropTypes.func\n\n};\n\nDraggableGridGroup.defaultProps = {\n\n className: '',\n style: null,\n\n theme: Theme.DEFAULT,\n\n value: '',\n text: '',\n\n disabled: false,\n isLoading: false,\n\n iconCls: '',\n rightIconCls: '',\n\n anchorIconCls: 'fa fa-bars',\n isDraggableAnyWhere: false\n\n};"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.000001575,"string":"0.000002"},"diff":{"kind":"string","value":"@@ -811,24 +811,51 @@\n omponent %7B%0A%0A\n+ static Theme = Theme;%0A%0A\n construc\n"}}},{"rowIdx":2597339,"cells":{"commit":{"kind":"string","value":"43b7930247c46cfa454f4ceed1f1e777235ea895"},"subject":{"kind":"string","value":"clear action"},"old_file":{"kind":"string","value":"src/astroprint/static/js/app/views/terminal.js"},"new_file":{"kind":"string","value":"src/astroprint/static/js/app/views/terminal.js"},"old_contents":{"kind":"string","value":"var TerminalView = Backbone.View.extend({\n el: '#terminal-view',\n outputView: null,\n sourceId: null,\n events: {\n 'submit form': 'onSend',\n 'show': 'onShow',\n 'hide': 'onHide'\n },\n initialize: function()\n {\n this.outputView = new OutputView();\n this.sourceId = Math.floor((Math.random() * 100000)); //Generate a random sourceId\n\n app.eventManager.on(\"astrobox:PrinterResponse\", _.bind(function(data) {\n if (data.sourceId == this.sourceId) {\n this.outputView.add('received', data.response);\n }\n }, this));\n },\n onClear: function(e)\n {\n e.preventDefault();\n\n this.outputView.clear();\n },\n onSend: function(e)\n {\n e.preventDefault();\n var sendField = this.$('input');\n var command = sendField.val();\n\n if (this.sourceId && command) {\n var loadingBtn = this.$('button.send').closest('.loading-button');\n\n loadingBtn.addClass('loading');\n\n $.ajax({\n url: API_BASEURL + 'printer/comm/send',\n method: 'POST',\n data: {\n sourceId: this.sourceId,\n command: command\n }\n })\n .done(_.bind(function(){\n this.outputView.add('sent', command);\n }, this))\n .fail(function(){\n loadingBtn.addClass('error');\n\n setTimeout(function(){\n loadingBtn.removeClass('error');\n }, 3000);\n })\n .always(function(){\n loadingBtn.removeClass('loading');\n sendField.val('');\n });\n }\n\n return false;\n },\n onShow: function()\n {\n this.$('input').focus();\n $.ajax({\n url: API_BASEURL + 'printer/comm/listen',\n method: 'POST'\n })\n },\n onHide: function()\n {\n $.ajax({\n url: API_BASEURL + 'printer/comm/listen',\n method: 'DELETE'\n });\n }\n});\n\nvar OutputView = Backbone.View.extend({\n el: '#terminal-view .output-container',\n add: function(type, text)\n {\n switch(type) {\n case 'sent':\n text = '
'+text+'
';\n break;\n\n case 'received':\n text = '
'+text+'
';\n break;\n }\n\n this.$el.append(text);\n this.$el.scrollTop(this.$el[0].scrollHeight);\n },\n clear: function()\n {\n this.$el.empty();\n }\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":7.65e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -180,16 +180,53 @@\n 'onHide'\n+,%0A 'click button.clear': 'onClear'\n %0A %7D,%0A \n@@ -2325,14 +2325,15 @@\n $el.\n-empty(\n+html(''\n );%0A \n"}}},{"rowIdx":2597340,"cells":{"commit":{"kind":"string","value":"3e496394541b46fe822903c9b180419979fbd608"},"subject":{"kind":"string","value":"Remove dragStart event from example"},"old_file":{"kind":"string","value":"examples/events/main.js"},"new_file":{"kind":"string","value":"examples/events/main.js"},"old_contents":{"kind":"string","value":"import { default as React, Component } from 'react';\nvar ReactDOM = require('react-dom');\nimport { ReactiveBase } from '@appbaseio/reactivebase';\n\nimport { ReactiveMap } from '../../app/app.js';\n\nclass Main extends Component {\n\tconstructor(props) {\n\t\tsuper(props);\n\t\tthis.eventLists = [\n\t\t\t'onDragstart',\n\t\t\t'onClick',\n\t\t\t'onDblclick',\n\t\t\t'onDrag',\n\t\t\t'onDragstart',\n\t\t\t'onDragend',\n\t\t\t'onMousemove',\n\t\t\t'onMouseout',\n\t\t\t'onMouseover',\n\t\t\t'onResize',\n\t\t\t'onRightclick',\n\t\t\t'onTilesloaded',\n\t\t\t'onBoundsChanged',\n\t\t\t'onCenterChanged',\n\t\t\t'onProjectionChanged',\n\t\t\t'onTiltChanged',\n\t\t\t'onZoomChanged'\n\t\t];\n\t\tthis.onIdle = this.onIdle.bind(this);\n\t\tthis.onMouseover = this.onMouseover.bind(this);\n\t\tthis.onMouseout = this.onMouseout.bind(this);\n\t\tthis.onClick = this.onClick.bind(this);\n\t\tthis.onDblclick = this.onDblclick.bind(this);\n\t\tthis.onDrag = this.onDrag.bind(this);\n\t\tthis.onDragstart = this.onDragstart.bind(this);\n\t\tthis.onDragend = this.onDragend.bind(this);\n\t\tthis.onMousemove = this.onMousemove.bind(this);\n\t\tthis.onMouseout = this.onMouseout.bind(this);\n\t\tthis.onMouseover = this.onMouseover.bind(this);\n\t\tthis.onResize = this.onResize.bind(this);\n\t\tthis.onRightclick = this.onRightclick.bind(this);\n\t\tthis.onTilesloaded = this.onTilesloaded.bind(this);\n\t\tthis.onBoundsChanged = this.onBoundsChanged.bind(this);\n\t\tthis.onCenterChanged = this.onCenterChanged.bind(this);\n\t\tthis.onProjectionChanged = this.onProjectionChanged.bind(this);\n\t\tthis.onTiltChanged = this.onTiltChanged.bind(this);\n\t\tthis.onZoomChanged = this.onZoomChanged.bind(this);\n\t}\n\trenderEventName() {\n\t\treturn this.eventLists.map((eventName, index) => {\n\t\t\treturn (
  • {eventName}
  • );\n\t\t});\n\t}\n\tonIdle(mapRef) {\n\t\tthis.eventActive('event-onIdle');\n\t}\n\tonMouseover(mapRef) {\n\t\tthis.eventActive('event-onMouseover');\n\t}\n\tonMouseout(mapRef) {\n\t\tthis.eventActive('event-onMouseout');\n\t}\n\tonClick(mapRef) {\n\t\tthis.eventActive('event-onClick');\n\t}\n\tonDblclick(mapRef) {\n\t\tthis.eventActive('event-onDblclick');\n\t}\n\tonDrag(mapRef) {\n\t\tthis.eventActive('event-onDrag');\n\t}\n\tonDragstart(mapRef) {\n\t\tthis.eventActive('event-onDragstart');\n\t}\n\tonDragend(mapRef) {\n\t\tthis.eventActive('event-onDragend');\n\t}\n\tonMousemove(mapRef) {\n\t\tthis.eventActive('event-onMousemove');\n\t}\n\tonMouseout(mapRef) {\n\t\tthis.eventActive('event-onMouseout');\n\t}\n\tonMouseover(mapRef) {\n\t\tthis.eventActive('event-onMouseover');\n\t}\n\tonResize(mapRef) {\n\t\tthis.eventActive('event-onResize');\n\t}\n\tonRightclick(mapRef) {\n\t\tthis.eventActive('event-onRightclick');\n\t}\n\tonTilesloaded(mapRef) {\n\t\tthis.eventActive('event-onTilesloaded');\n\t}\n\tonBoundsChanged(mapRef) {\n\t\tthis.eventActive('event-onBoundsChanged');\n\t}\n\tonCenterChanged(mapRef) {\n\t\tthis.eventActive('event-onCenterChanged');\n\t}\n\tonProjectionChanged(mapRef) {\n\t\tthis.eventActive('event-onProjectionChanged');\n\t}\n\tonTiltChanged(mapRef) {\n\t\tthis.eventActive('event-onTiltChanged');\n\t}\n\tonZoomChanged(mapRef) {\n\t\tthis.eventActive('event-onZoomChanged');\n\t}\n\tonClick(mapRef) {\n\t\tthis.eventActive('event-onClick');\n\t}\n\teventActive(eventRef) {\n\t\t$(this.refs[eventRef]).addClass('active');\n\t\tsetTimeout(() => {\n\t\t\t$(this.refs[eventRef]).removeClass('active');\n\t\t}, 1500);\n\t}\n\trender() {\n\t\treturn (\n\t\t\t
    \n\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t\t\t\n\t\t\t\t\t
    \n\t\t\t\t\t
    \n\t\t\t\t\t\t
      \n\t\t\t\t\t\t\t{this.renderEventName()}\n\t\t\t\t\t\t
    \n\t\t\t\t\t
    \n\t\t\t\t\n\t\t\t
    \n\t\t);\n\t}\n}\n\nMain.defaultProps = {\n\tmapStyle: \"Light Monochrome\",\n\tmapping: {\n\t\tlocation: 'location'\n\t},\n\tconfig: {\n\t\t\"appbase\": {\n\t\t\t\"appname\": \"checkin\",\n\t\t\t\"username\": \"6PdfXag4h\",\n\t\t\t\"password\": \"b614d8fa-03d8-4005-b6f1-f2ff31cd0f91\",\n\t\t\t\"type\": \"city\"\n\t\t}\n\t}\n};\n\nReactDOM.render(
    , document.getElementById('map'));\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.157e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -280,34 +280,16 @@\n sts = %5B%0A\n-%09%09%09'onDragstart',%0A\n %09%09%09'onCl\n"}}},{"rowIdx":2597341,"cells":{"commit":{"kind":"string","value":"615a2718f0d62205869b72e347cf909c8c43c4de"},"subject":{"kind":"string","value":"Add docstrings to the popover view"},"old_file":{"kind":"string","value":"web_client/views/popover/AnnotationPopover.js"},"new_file":{"kind":"string","value":"web_client/views/popover/AnnotationPopover.js"},"old_contents":{"kind":"string","value":"import _ from 'underscore';\n\nimport View from '../View';\nimport { restRequest } from 'girder/rest';\n\nimport ElementCollection from 'girder_plugins/large_image/collections/ElementCollection';\nimport annotationPopover from '../../templates/popover/annotationPopover.pug';\nimport '../../stylesheets/popover/annotationPopover.styl';\n\nvar AnnotationPopover = View.extend({\n initialize(settings) {\n if (settings.debounce) {\n this.position = _.debounce(this.position, settings.debounce);\n }\n\n $('body').on('mousemove', '.h-image-view-body', (evt) => this.position(evt));\n $('body').on('mouseout', '.h-image-view-body', () => this._hide());\n $('body').on('mouseover', '.h-image-view-body', () => this._show());\n\n this._hidden = !settings.visible;\n this._users = {};\n this.collection = new ElementCollection();\n this.listenTo(this.collection, 'add', this._getUser);\n this.listenTo(this.collection, 'all', this.render);\n },\n\n render() {\n this.$el.html(\n annotationPopover({\n annotations: _.uniq(\n this.collection.pluck('annotation'),\n _.property('id')),\n formatDate: this._formatDate,\n users: this._users\n })\n );\n this._show();\n if (!this._visible()) {\n this._hide();\n }\n this._height = this.$('.h-annotation-popover').height();\n },\n\n _getUser(model) {\n var id = model.get('annotation').get('creatorId');\n if (!_.has(this._users, id)) {\n restRequest({\n path: 'user/' + id\n }).then((user) => {\n this._users[id] = user;\n this.render();\n });\n }\n },\n\n _formatDate(s) {\n var d = new Date(s);\n return d.toLocaleString();\n },\n\n _show() {\n if (this._visible()) {\n this.$el.removeClass('hidden');\n }\n },\n\n _hide() {\n this.$el.addClass('hidden');\n },\n\n _visible() {\n return !this._hidden && this.collection.length > 0;\n },\n\n position(evt) {\n if (this._visible()) {\n this.$el.css({\n left: evt.pageX + 5,\n top: evt.pageY - this._height / 2\n });\n }\n },\n\n toggle(show) {\n this._hidden = !show;\n this.render();\n }\n});\n\nexport default AnnotationPopover;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.597e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -323,16 +323,336 @@\n styl';%0A%0A\n+/**%0A * This view behaves like a bootstrap %22popover%22 that follows the mouse pointer%0A * over the image canvas and dynamically updates according to the features%0A * under the pointer.%0A *%0A * @param %7Bobject%7D %5Bsettings%5D%0A * @param %7Bnumber%7D %5Bsettings.debounce%5D%0A * Debounce time in ms for rerendering due to mouse movements%0A */%0A\n var Anno\n@@ -754,24 +754,25 @@\n this.\n+_\n position = _\n@@ -782,24 +782,25 @@\n bounce(this.\n+_\n position, se\n@@ -898,16 +898,17 @@\n =%3E this.\n+_\n position\n@@ -1787,24 +1787,798 @@\n ();%0A %7D,%0A%0A\n+ /**%0A * Set the popover visibility state.%0A *%0A * @param %7Bboolean%7D %5Bshow%5D%0A * if true: show the popover%0A * if false: hide the popover%0A * if undefined: toggle the popover state%0A */%0A toggle(show) %7B%0A if (show === undefined) %7B%0A show = this._hidden;%0A %7D%0A this._hidden = !show;%0A this.render();%0A return this;%0A %7D,%0A%0A /**%0A * Check the local cache for the given creator. If it has not already been%0A * fetched, then send a rest request to get the user information and%0A * rerender the popover.%0A *%0A * As a consequence to avoid always rendering asyncronously, the user name%0A * will not be shown on the first render. In practice, this isn't usually%0A * noticeable.%0A */%0A\n _getUser\n@@ -2879,24 +2879,91 @@\n %7D%0A %7D,%0A%0A\n+ /**%0A * Format a Date object as a localized string.%0A */%0A\n _formatD\n@@ -3039,24 +3039,134 @@\n ();%0A %7D,%0A%0A\n+ /**%0A * Remove the hidden class on the popover element if this._visible()%0A * returns true.%0A */%0A\n _show() \n@@ -3256,24 +3256,77 @@\n %7D%0A %7D,%0A%0A\n+ /**%0A * Unconditionally hide popover.%0A */%0A\n _hide() \n@@ -3380,93 +3380,380 @@\n \n-_visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A \n+/**%0A * Determine if the popover should be visible. Returns true%0A * if there are active annotations under the mouse pointer and%0A * the label option is enabled.%0A */%0A _visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A /**%0A * Reset the position of the popover to the position of the%0A * mouse pointer.%0A */%0A _\n posi\n@@ -3939,88 +3939,8 @@\n %7D%0A\n- %7D,%0A%0A toggle(show) %7B%0A this._hidden = !show;%0A this.render();%0A\n \n"}}},{"rowIdx":2597342,"cells":{"commit":{"kind":"string","value":"828032d625d4246a1d4a86333e962d00e04bcfb6"},"subject":{"kind":"string","value":"test åäö"},"old_file":{"kind":"string","value":"src/main/resources/client/components/SiteWrapper/SiteWrapper.js"},"new_file":{"kind":"string","value":"src/main/resources/client/components/SiteWrapper/SiteWrapper.js"},"old_contents":{"kind":"string","value":"'use strict';\n\n// Vendor\nvar _assign = require('lodash/object/assign');\nvar Vue = require('vue');\nvar $ = require('jquery');\n// Components\nvar TechInfoWindow = require('components/TechInfoWindow/TechInfoWindow.js');\n\n// Utils\nvar AuthenticationUtil = require('utils/AuthenticationUtil/AuthenticationUtil.js');\nvar TechnicalInfoUtil = require('utils/TechnicalInfoUtil/TechnicalInfoUtil.js');\n\n// CSS modules\nvar styles = _assign(\n\trequire('./SiteWrapper.css'), \n\trequire('css/modules/Colors.less')\n);\n\n/**\n * Site Wrapper Component\n */\nvar SiteWrapperMixin = {\n\tprops: ['activity'],\n\ttemplate: require('./SiteWrapper.html'),\n\tdata: function() {\n\t\treturn {\n\t\t\tauthenticated: false,\n\t\t\tuserModel: {},\n\t\t\t_styles: styles,\n\n\t\t}\n\t},\n\tcomponents: {\n\t\t'tech-info-window': TechInfoWindow\n\t},\n\tevents: {\n\t\t/*\n\t\t'authenticate': function() {\n\t\t\tif(this.authenticated) {\n\t\t\t\tthis.$broadcast('logged-in', this.userModel);\n\t\t\t}\n\t\t},\n\t\t*/\n\t\t'setTextTitle': function() {\n\t\t\t\n\t\t}\n\n\t},\n\tready: function() {\t\n\t\t/*\n\t\t// Authenticate\n\t\tAuthenticationutil.authenticate(function(authenticated, userModel) {\n\t\t\tif(authenticated) {\n\t\t\t\tthis.$set('authenticated', true);\n\t\t\t\tthis.$set('userModel', userModel);\n\t\t\t\tthis.$broadcast('logged-in', userModel);\n\t\t\t}\n\t\t}.bind(this));\n\t\t*/\n\t\tAuthenticationUtil.authenticate(function(authenticated) {\n\t\t\tif (authenticated.isLoggedIn) {\n\t\t\t\tthis.$set('authenticated', true);\n\t\t\t\tthis.$set('userModel', authenticated);\n\t\t\t}\t\n\t\t}.bind(this));\n\n\t\t// Set GitHub-image\n\t\tthis.$els.githubImage1.src = this.$els.githubImage2.src = require('octicons/svg/mark-github.svg');\n\t},\n\tmethods: {\n\t\tinit: function() {\t\t\n\t\t},\n\t\tcheckLoggedInStatus: function() {\n\t\t\tAuthenticationUtil.authenticate(function(authenticated) {\n\t\t\t\tif (!authenticated.isLoggedIn) {\n\t\t\t\t\tvar url = '/secure?return=';\n\t\t\t\t\t$(location).attr('href', url + window.location.href);\n\t\t\t\t}\n\t\t\t});\n\t\t}\n\t}\n};\n\n\nmodule.exports = SiteWrapperMixin;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":9.964e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -1424,16 +1424,48 @@\n cated);%0A\n+%09%09%09%09console.log(authenticated);%0A\n %09%09%09%7D%09%0A%09%09\n"}}},{"rowIdx":2597343,"cells":{"commit":{"kind":"string","value":"362901bbe5c73ac8c534675f84aab9e5a62aebd5"},"subject":{"kind":"string","value":"fix unknown error when showing details of expense from /expenses page"},"old_file":{"kind":"string","value":"src/apps/expenses/components/PayExpenseBtn.js"},"new_file":{"kind":"string","value":"src/apps/expenses/components/PayExpenseBtn.js"},"old_contents":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { defineMessages, FormattedMessage } from 'react-intl';\nimport { graphql } from 'react-apollo';\nimport gql from 'graphql-tag';\nimport { get } from 'lodash';\n\nimport withIntl from '../../../lib/withIntl';\nimport { isValidEmail } from '../../../lib/utils';\n\nimport SmallButton from '../../../components/SmallButton';\n\nclass PayExpenseBtn extends React.Component {\n static propTypes = {\n expense: PropTypes.object.isRequired,\n collective: PropTypes.object.isRequired,\n host: PropTypes.object,\n disabled: PropTypes.bool,\n paymentProcessorFeeInCollectiveCurrency: PropTypes.number,\n hostFeeInCollectiveCurrency: PropTypes.number,\n platformFeeInCollectiveCurrency: PropTypes.number,\n lock: PropTypes.func,\n unlock: PropTypes.func,\n };\n\n constructor(props) {\n super(props);\n this.state = {\n loading: false,\n paymentProcessorFeeInCollectiveCurrency: 0,\n };\n this.onClick = this.onClick.bind(this);\n this.messages = defineMessages({\n 'paypal.missing': {\n id: 'expense.payoutMethod.paypal.missing',\n defaultMessage: 'Please provide a valid paypal email address',\n },\n });\n }\n\n async onClick() {\n const { expense, lock, unlock } = this.props;\n if (this.props.disabled) {\n return;\n }\n lock();\n this.setState({ loading: true });\n try {\n await this.props.payExpense(\n expense.id,\n this.props.paymentProcessorFeeInCollectiveCurrency,\n this.props.hostFeeInCollectiveCurrency,\n this.props.platformFeeInCollectiveCurrency,\n );\n this.setState({ loading: false });\n unlock();\n } catch (e) {\n console.log('>>> payExpense error: ', e);\n const error = e.message && e.message.replace(/GraphQL error:/, '');\n this.setState({ error, loading: false });\n unlock();\n }\n }\n\n render() {\n const { collective, expense, intl, host } = this.props;\n let disabled = this.state.loading,\n selectedPayoutMethod = expense.payoutMethod,\n title = '',\n error = this.state.error;\n\n if (expense.payoutMethod === 'paypal') {\n if (!isValidEmail(get(expense, 'user.paypalEmail')) && !isValidEmail(get(expense, 'user.email'))) {\n disabled = true;\n title = intl.formatMessage(this.messages['paypal.missing']);\n } else {\n const paypalPaymentMethod = host.paymentMethods && host.paymentMethods.find(pm => pm.service === 'paypal');\n if (get(expense, 'user.paypalEmail') === get(paypalPaymentMethod, 'name')) {\n selectedPayoutMethod = 'other';\n }\n }\n }\n if (get(collective, 'stats.balance') < expense.amount) {\n disabled = true;\n error = ;\n }\n return (\n
    \n \n \n \n {selectedPayoutMethod === 'other' && (\n \n )}\n {selectedPayoutMethod !== 'other' && (\n \n )}\n \n
    {error}
    \n
    \n );\n }\n}\n\nconst payExpenseQuery = gql`\n mutation payExpense(\n $id: Int!\n $paymentProcessorFeeInCollectiveCurrency: Int\n $hostFeeInCollectiveCurrency: Int\n $platformFeeInCollectiveCurrency: Int\n ) {\n payExpense(\n id: $id\n paymentProcessorFeeInCollectiveCurrency: $paymentProcessorFeeInCollectiveCurrency\n hostFeeInCollectiveCurrency: $hostFeeInCollectiveCurrency\n platformFeeInCollectiveCurrency: $platformFeeInCollectiveCurrency\n ) {\n id\n status\n collective {\n id\n stats {\n id\n balance\n }\n }\n }\n }\n`;\n\nconst addMutation = graphql(payExpenseQuery, {\n props: ({ mutate }) => ({\n payExpense: async (\n id,\n paymentProcessorFeeInCollectiveCurrency,\n hostFeeInCollectiveCurrency,\n platformFeeInCollectiveCurrency,\n ) => {\n return await mutate({\n variables: {\n id,\n paymentProcessorFeeInCollectiveCurrency,\n hostFeeInCollectiveCurrency,\n platformFeeInCollectiveCurrency,\n },\n });\n },\n }),\n});\n\nexport default addMutation(withIntl(PayExpenseBtn));\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.358e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2398,22 +2398,38 @@\n Method =\n- \n+%0A get(\n host\n-.\n+, '\n paymentM\n@@ -2434,16 +2434,18 @@\n tMethods\n+')\n && host\n"}}},{"rowIdx":2597344,"cells":{"commit":{"kind":"string","value":"ae543be4b0ce6807cbb6b70b09d28bd390290fad"},"subject":{"kind":"string","value":"add default export (#48)"},"old_file":{"kind":"string","value":"leveldown.js"},"new_file":{"kind":"string","value":"leveldown.js"},"old_contents":{"kind":"string","value":"const util = require('util')\n , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN\n , binding = require('bindings')('leveldown').leveldown\n , ChainedBatch = require('./chained-batch')\n , Iterator = require('./iterator')\n , fs = require('fs')\n\nfunction LevelDOWN (location) {\n if (!(this instanceof LevelDOWN))\n return new LevelDOWN(location)\n\n AbstractLevelDOWN.call(this, location)\n this.binding = binding(location)\n}\n\nutil.inherits(LevelDOWN, AbstractLevelDOWN)\n\n\nLevelDOWN.prototype._open = function (options, callback) {\n this.binding.open(options, callback)\n}\n\n\nLevelDOWN.prototype._close = function (callback) {\n this.binding.close(callback)\n}\n\n\nLevelDOWN.prototype._put = function (key, value, options, callback) {\n this.binding.put(key, value, options, callback)\n}\n\n\nLevelDOWN.prototype._get = function (key, options, callback) {\n this.binding.get(key, options, callback)\n}\n\n\nLevelDOWN.prototype._del = function (key, options, callback) {\n this.binding.del(key, options, callback)\n}\n\n\nLevelDOWN.prototype._chainedBatch = function () {\n return new ChainedBatch(this)\n}\n\n\nLevelDOWN.prototype._batch = function (operations, options, callback) {\n return this.binding.batch(operations, options, callback)\n}\n\n\nLevelDOWN.prototype.approximateSize = function (start, end, callback) {\n if (start == null ||\n end == null ||\n typeof start === 'function' ||\n typeof end === 'function') {\n throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments')\n }\n\n if (typeof callback !== 'function') {\n throw new Error('approximateSize() requires a callback argument')\n }\n\n start = this._serializeKey(start)\n end = this._serializeKey(end)\n\n this.binding.approximateSize(start, end, callback)\n}\n\n\nLevelDOWN.prototype.compactRange = function (start, end, callback) {\n this.binding.compactRange(start, end, callback)\n}\n\n\nLevelDOWN.prototype.getProperty = function (property) {\n if (typeof property != 'string')\n throw new Error('getProperty() requires a valid `property` argument')\n\n return this.binding.getProperty(property)\n}\n\n\nLevelDOWN.prototype._iterator = function (options) {\n return new Iterator(this, options)\n}\n\n\nLevelDOWN.destroy = function (location, callback) {\n if (arguments.length < 2)\n throw new Error('destroy() requires `location` and `callback` arguments')\n\n if (typeof location != 'string')\n throw new Error('destroy() requires a location string argument')\n\n if (typeof callback != 'function')\n throw new Error('destroy() requires a callback function argument')\n\n binding.destroy(location, function (err) {\n if (err) return callback(err)\n\n // On Windows, RocksDB silently fails to remove the directory because its\n // Logger, which is instantiated on destroy(), has an open file handle on a\n // LOG file. Destroy() removes this file but Windows won't actually delete\n // it until the handle is released. This happens when destroy() goes out of\n // scope, which disposes the Logger. So back in JS-land, we can again\n // attempt to remove the directory. This is merely a workaround because\n // arguably RocksDB should not instantiate a Logger or open a file at all.\n fs.rmdir(location, function (err) {\n if (err) {\n // Ignore this error in case there are non-RocksDB files left.\n if (err.code === 'ENOTEMPTY') return callback()\n if (err.code === 'ENOENT') return callback()\n\n return callback(err)\n }\n\n callback()\n })\n })\n}\n\n\nLevelDOWN.repair = function (location, callback) {\n if (arguments.length < 2)\n throw new Error('repair() requires `location` and `callback` arguments')\n\n if (typeof location != 'string')\n throw new Error('repair() requires a location string argument')\n\n if (typeof callback != 'function')\n throw new Error('repair() requires a callback function argument')\n\n binding.repair(location, callback)\n}\n\n\nmodule.exports = LevelDOWN\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.208e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -3997,16 +3997,36 @@\n xports =\n+ LevelDOWN.default =\n LevelDO\n"}}},{"rowIdx":2597345,"cells":{"commit":{"kind":"string","value":"5b3a17e24efcf7603f0fd73d8eabd8fb516ee536"},"subject":{"kind":"string","value":"fix wrong this context (#4352)"},"old_file":{"kind":"string","value":"lib/workers/repository/process/lookup/rollback.js"},"new_file":{"kind":"string","value":"lib/workers/repository/process/lookup/rollback.js"},"old_contents":{"kind":"string","value":"const { logger } = require('../../../../logger');\nconst versioning = require('../../../../versioning');\n\nmodule.exports = {\n getRollbackUpdate,\n};\n\nfunction getRollbackUpdate(config, versions) {\n const { packageFile, versionScheme, depName, currentValue } = config;\n const version = versioning.get(versionScheme);\n // istanbul ignore if\n if (!version.isLessThanRange) {\n logger.info(\n { versionScheme },\n 'Current version scheme does not support isLessThanRange()'\n );\n return null;\n }\n const lessThanVersions = versions.filter(v =>\n version.isLessThanRange(v, currentValue)\n );\n // istanbul ignore if\n if (!lessThanVersions.length) {\n logger.info(\n { packageFile, depName, currentValue },\n 'Missing version has nothing to roll back to'\n );\n return null;\n }\n logger.info(\n { packageFile, depName, currentValue },\n `Current version not found - rolling back`\n );\n logger.debug(\n { dependency: depName, versions },\n 'Versions found before rolling back'\n );\n lessThanVersions.sort(version.sortVersions);\n const toVersion = lessThanVersions.pop();\n // istanbul ignore if\n if (!toVersion) {\n logger.info('No toVersion to roll back to');\n return null;\n }\n let fromVersion;\n const newValue = version.getNewValue(\n currentValue,\n 'replace',\n fromVersion,\n toVersion\n );\n return {\n updateType: 'rollback',\n branchName:\n '{{{branchPrefix}}}rollback-{{{depNameSanitized}}}-{{{newMajor}}}.x',\n commitMessageAction: 'Roll back',\n isRollback: true,\n newValue,\n newMajor: version.getMajor(toVersion),\n semanticCommitType: 'fix',\n };\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000109702,"string":"0.000011"},"diff":{"kind":"string","value":"@@ -1039,16 +1039,26 @@\n ns.sort(\n+(a, b) =%3E \n version.\n@@ -1069,16 +1069,22 @@\n Versions\n+(a, b)\n );%0A con\n"}}},{"rowIdx":2597346,"cells":{"commit":{"kind":"string","value":"c2e3d2b8ca5ebe76fc12a08038bf9251c43bdbac"},"subject":{"kind":"string","value":"Fix time differences (add 1 second)"},"old_file":{"kind":"string","value":"src/client/rest/RequestHandlers/Sequential.js"},"new_file":{"kind":"string","value":"src/client/rest/RequestHandlers/Sequential.js"},"old_contents":{"kind":"string","value":"const RequestHandler = require('./RequestHandler');\n\n/**\n * Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto\n * the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account,\n * but it can be slower.\n * @extends {RequestHandler}\n */\nmodule.exports = class SequentialRequestHandler extends RequestHandler {\n\n constructor(restManager) {\n super(restManager);\n\n /**\n * Whether this rate limiter is waiting for a response from a request\n * @type {Boolean}\n */\n this.waiting = false;\n\n /**\n * The time difference between Discord's Dates and the local computer's Dates. A positive number means the local\n * computer's time is ahead of Discord's.\n * @type {Number}\n */\n this.timeDifference = 0;\n }\n\n push(request) {\n super.push(request);\n this.handle();\n }\n\n /**\n * Performs a request then resolves a promise to indicate its readiness for a new request\n * @param {APIRequest} item the item to execute\n * @returns {Promise}\n */\n execute(item) {\n return new Promise((resolve, reject) => {\n item.request.gen().end((err, res) => {\n if (res && res.headers) {\n this.requestLimit = res.headers['x-ratelimit-limit'];\n this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000;\n this.requestRemaining = Number(res.headers['x-ratelimit-remaining']);\n this.timeDifference = Date.now() - new Date(res.headers.date).getTime();\n }\n if (err) {\n if (err.status === 429) {\n setTimeout(() => {\n this.waiting = false;\n resolve();\n }, res.headers['retry-after']);\n } else {\n this.queue.shift();\n this.waiting = false;\n item.reject(err);\n resolve(err);\n }\n } else {\n this.queue.shift();\n const data = res && res.body ? res.body : {};\n item.resolve(data);\n if (this.requestRemaining === 0) {\n setTimeout(() => {\n this.waiting = false;\n resolve(data);\n }, (this.requestResetTime - Date.now()) + this.timeDifference - 1000);\n } else {\n this.waiting = false;\n resolve(data);\n }\n }\n });\n });\n }\n\n handle() {\n super.handle();\n if (this.waiting || this.queue.length === 0) {\n return;\n }\n this.waiting = true;\n\n const item = this.queue[0];\n this.execute(item).then(() => this.handle());\n }\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000590118,"string":"0.000059"},"diff":{"kind":"string","value":"@@ -2251,17 +2251,17 @@\n ference \n--\n++\n 1000);%0A\n"}}},{"rowIdx":2597347,"cells":{"commit":{"kind":"string","value":"c0d9881a621bd39be404fb0905fd11843d0ff4c9"},"subject":{"kind":"string","value":"add memoryUsageHeap value"},"old_file":{"kind":"string","value":"src/node/server.js"},"new_file":{"kind":"string","value":"src/node/server.js"},"old_contents":{"kind":"string","value":"#!/usr/bin/env node\n\n'use strict';\n\n/**\n * This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server.\n * Static file Requests are answered directly from this module, Socket.IO messages are passed\n * to MessageHandler and minfied requests are passed to minified.\n */\n\n/*\n * 2011 Peter 'Pita' Martischka (Primary Technology Ltd)\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS-IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\nconst log4js = require('log4js');\nlog4js.replaceConsole();\n\n/*\n * early check for version compatibility before calling\n * any modules that require newer versions of NodeJS\n */\nconst NodeVersion = require('./utils/NodeVersion');\nNodeVersion.enforceMinNodeVersion('10.13.0');\nNodeVersion.checkDeprecationStatus('10.13.0', '1.8.3');\n\nconst UpdateCheck = require('./utils/UpdateCheck');\nconst db = require('./db/DB');\nconst express = require('./hooks/express');\nconst hooks = require('../static/js/pluginfw/hooks');\nconst npm = require('npm/lib/npm.js');\nconst plugins = require('../static/js/pluginfw/plugins');\nconst settings = require('./utils/Settings');\nconst util = require('util');\n\nlet started = false;\nlet stopped = false;\n\nexports.start = async () => {\n if (started) return express.server;\n started = true;\n if (stopped) throw new Error('restart not supported');\n\n // Check if Etherpad version is up-to-date\n UpdateCheck.check();\n\n // start up stats counting system\n const stats = require('./stats');\n stats.gauge('memoryUsage', () => process.memoryUsage().rss);\n\n await util.promisify(npm.load)();\n\n try {\n await db.init();\n await plugins.update();\n console.info(`Installed plugins: ${plugins.formatPluginsWithVersion()}`);\n console.debug(`Installed parts:\\n${plugins.formatParts()}`);\n console.debug(`Installed hooks:\\n${plugins.formatHooks()}`);\n await hooks.aCallAll('loadSettings', {settings});\n await hooks.aCallAll('createServer');\n } catch (e) {\n console.error(`exception thrown: ${e.message}`);\n if (e.stack) console.log(e.stack);\n process.exit(1);\n }\n\n process.on('uncaughtException', exports.exit);\n\n /*\n * Connect graceful shutdown with sigint and uncaught exception\n *\n * Until Etherpad 1.7.5, process.on('SIGTERM') and process.on('SIGINT') were\n * not hooked up under Windows, because old nodejs versions did not support\n * them.\n *\n * According to nodejs 6.x documentation, it is now safe to do so. This\n * allows to gracefully close the DB connection when hitting CTRL+C under\n * Windows, for example.\n *\n * Source: https://nodejs.org/docs/latest-v6.x/api/process.html#process_signal_events\n *\n * - SIGTERM is not supported on Windows, it can be listened on.\n * - SIGINT from the terminal is supported on all platforms, and can usually\n * be generated with +C (though this may be configurable). It is not\n * generated when terminal raw mode is enabled.\n */\n process.on('SIGINT', exports.exit);\n\n // When running as PID1 (e.g. in docker container) allow graceful shutdown on SIGTERM c.f. #3265.\n // Pass undefined to exports.exit because this is not an abnormal termination.\n process.on('SIGTERM', () => exports.exit());\n\n // Return the HTTP server to make it easier to write tests.\n return express.server;\n};\n\nexports.stop = async () => {\n if (stopped) return;\n stopped = true;\n console.log('Stopping Etherpad...');\n await new Promise(async (resolve, reject) => {\n const id = setTimeout(() => reject(new Error('Timed out waiting for shutdown tasks')), 3000);\n await hooks.aCallAll('shutdown');\n clearTimeout(id);\n resolve();\n });\n};\n\nexports.exit = async (err) => {\n let exitCode = 0;\n if (err) {\n exitCode = 1;\n console.error(err.stack ? err.stack : err);\n }\n try {\n await exports.stop();\n } catch (err) {\n exitCode = 1;\n console.error(err.stack ? err.stack : err);\n }\n process.exit(exitCode);\n};\n\nif (require.main === module) exports.start();\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.772e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1991,16 +1991,88 @@\n ().rss);\n+%0A stats.gauge('memoryUsageHeap', () =%3E process.memoryUsage().heapUsed);\n %0A%0A awai\n"}}},{"rowIdx":2597348,"cells":{"commit":{"kind":"string","value":"928ce8b8f980c89e9419f2174f7efa6dabf14334"},"subject":{"kind":"string","value":"update delete user JSON message"},"old_file":{"kind":"string","value":"lib/controllers/users.js"},"new_file":{"kind":"string","value":"lib/controllers/users.js"},"old_contents":{"kind":"string","value":"const express = require('express');\nconst router = express.Router(); // eslint-disable-line new-cap\nconst async = require('async');\n\nconst UserModel = require('../models/user');\nconst authenticate = require('../middlewares/authenticate');\nconst authorise = require('../middlewares/authorise');\n\nrouter.use('/users', authenticate);\n\n// Create user\nrouter.post('/users', authorise('admin'));\nrouter.post('/users', (req, res) => {\n UserModel.create(req.body, (err, user) => {\n if (err) {\n res.json({\n status: 'fail',\n meta: {\n message: 'The user could not be created. Check validation.',\n validation: err.errors,\n },\n data: null,\n });\n } else {\n const userObj = user.toObject();\n delete userObj.password;\n\n res.json({\n status: 'success',\n meta: {\n message: 'The user was created.',\n },\n data: userObj,\n });\n }\n });\n});\n\n// List users\nrouter.get('/users', authorise('admin'));\nrouter.get('/users', (req, res) => {\n const page = req.query.page || 1;\n const limit = 20;\n\n async.parallel({\n total: function total(cb) {\n UserModel.count(cb);\n },\n users: function users(cb) {\n UserModel\n .find()\n .select('name username')\n .skip(limit * (page - 1))\n .limit(limit)\n .lean()\n .exec(cb);\n },\n }, (err, result) => {\n if (err) {\n res.status(500).json({\n status: 'fail',\n meta: {\n message: 'The query could not be executed.',\n },\n data: null,\n });\n } else {\n res.json({\n status: 'success',\n meta: {\n paginate: {\n total: result.total,\n previous: ((page > 1) ? page - 1 : null),\n next: (((limit * page) < result.total) ? page + 1 : null),\n },\n },\n data: result.users,\n });\n }\n });\n});\n\n// Get current user\nrouter.get('/users/me', (req, res) => {\n UserModel.findById(req.jwt.id, (err, user) => {\n if (err) {\n res.json({\n status: 'error',\n meta: {\n message: 'User information could not be found.',\n },\n data: null,\n });\n } else if (user === null) {\n res.json({\n status: 'fail',\n meta: {\n message: 'User information could not be found.',\n },\n data: null,\n });\n } else {\n const userObj = user.toObject();\n delete userObj.password;\n\n res.json({\n status: 'success',\n meta: {\n message: 'The user was found.',\n },\n data: userObj,\n });\n }\n });\n});\n\n// Get user\nrouter.get('/users/:user', (req, res) => {\n if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) {\n return res.json({\n status: 'fail',\n meta: {\n message: 'You are not authorised.',\n },\n data: null,\n });\n }\n\n UserModel.findById(req.params.user, (err, user) => {\n if (err) {\n res.json({\n status: 'error',\n meta: {\n message: 'User information could not be found.',\n },\n data: null,\n });\n } else if (user === null) {\n res.json({\n status: 'fail',\n meta: {\n message: 'User information could not be found.',\n },\n data: null,\n });\n } else {\n const userObj = user.toObject();\n delete userObj.password;\n\n res.json({\n status: 'success',\n meta: {\n message: 'The user was found.',\n },\n data: userObj,\n });\n }\n });\n});\n\n// Update user\nrouter.put('/users/:user', (req, res) => {\n if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) {\n return res.json({\n status: 'fail',\n meta: {\n message: 'You are not authorised.',\n },\n data: null,\n });\n }\n\n UserModel.findById(req.params.user, (err, user) => {\n if (err) {\n res.json({\n status: 'fail',\n meta: {\n message: 'The user could not be updated.',\n },\n data: null,\n });\n } else if (user === null) {\n res.json({\n status: 'fail',\n meta: {\n message: 'The user was not found and could not be updated.',\n },\n data: null,\n });\n } else {\n user.set(req.body).save((saveErr, updatedUser) => {\n if (saveErr) {\n res.json({\n status: 'fail',\n meta: {\n message: 'The user could not be updated. Check validation.',\n validation: saveErr.errors,\n },\n data: null,\n });\n } else {\n const userObj = updatedUser.toObject();\n delete userObj.password;\n\n res.json({\n status: 'success',\n meta: {\n message: 'The user was updated.',\n },\n data: userObj,\n });\n }\n });\n }\n });\n});\n\n// Delete user\nrouter.delete('/users/:user', (req, res) => {\n if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) {\n return res.json({\n status: 'fail',\n meta: {\n message: 'You are not authorised.',\n },\n data: null,\n });\n }\n\n UserModel.findByIdAndRemove(req.params.user, err => {\n if (err) {\n res.json({\n status: 'error',\n meta: {\n message: 'The user could not be updated.',\n },\n data: null,\n });\n } else {\n res.json({\n status: 'success',\n meta: {\n message: 'The user was deleted',\n },\n data: null,\n });\n }\n });\n});\n\nmodule.exports = router;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000012055,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -5333,36 +5333,36 @@\n er could not be \n-upda\n+dele\n ted.',%0A %7D\n"}}},{"rowIdx":2597349,"cells":{"commit":{"kind":"string","value":"1eeee314affb486acc249d670452063b78e42e49"},"subject":{"kind":"string","value":"refactor the Index module for readability and testability"},"old_file":{"kind":"string","value":"lib/Index.js"},"new_file":{"kind":"string","value":"lib/Index.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nconst path = require('path');\nconst defaults = require('defa');\nconst Sequelize = require('sequelize');\n\nclass Index {\n\n constructor(options) {\n\n defaults(options, {\n 'filename': () => path.join(process.cwd(), '.index')\n });\n\n this.prepareDb(options.filename);\n }\n\n sync() {\n if (!this.ready)\n this.ready = this.Result.sync();\n\n return this.ready;\n }\n\n log() {\n // do nothing\n // TODO log it somewhere\n }\n\n /**\n * Prepare the database and insert models and stuff\n * @param {String} filename\n * @returns {Promise}\n */\n prepareDb(filename) {\n\n const sequelize = new Sequelize('cachething', 'carrier', null, {\n 'dialect': 'sqlite',\n 'storage': filename,\n 'logging': msg => this.log(msg)\n });\n\n this.db = sequelize;\n\n this.Result = sequelize.define('Result', {\n action: Sequelize.STRING,\n fileHash: Sequelize.STRING,\n outputHash: Sequelize.STRING,\n created: Sequelize.BIGINT,\n expires: Sequelize.BIGINT,\n fileName: Sequelize.STRING,\n compressed: Sequelize.BOOLEAN,\n fileSize: Sequelize.BIGINT,\n runtime: Sequelize.BIGINT\n });\n }\n}\n\nmodule.exports = Index;"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000043563,"string":"0.000004"},"diff":{"kind":"string","value":"@@ -18,14 +18,24 @@\n nst \n-path \n+%7Bnoop, defaults%7D\n \n@@ -45,19 +45,21 @@\n equire('\n-pat\n+lodas\n h');%0Acon\n@@ -61,24 +61,34 @@\n ;%0Aconst \n-defaults\n+path \n = requ\n@@ -92,20 +92,20 @@\n equire('\n-defa\n+path\n ');%0Acons\n@@ -116,16 +116,26 @@\n quelize \n+ \n = requir\n@@ -162,24 +162,62 @@\n ss Index %7B%0A%0A\n+ /**%0A * @param options%0A */%0A\n construc\n@@ -239,16 +239,26 @@\n %0A \n+ options =\n default\n@@ -286,17 +286,16 @@\n \n-'\n filename\n ': (\n@@ -294,16 +294,9 @@\n name\n-'\n :\n- () =%3E\n pat\n@@ -330,34 +330,85 @@\n ex')\n-%0A %7D);%0A%0A this\n+,%0A log: noop,%0A %7D);%0A%0A const %7Bdb, Result%7D = Index\n .pre\n@@ -425,152 +425,185 @@\n ions\n-.filename\n );%0A\n+%0A\n \n-%7D%0A%0A\n \n-sync() %7B%0A if (!this.ready)\n+this.db = db;%0A this.Result = Result;\n %0A \n+%7D%0A%0A\n \n- this.ready = this.Result.sync();%0A\n+/**%0A * Prepare the %22Result%22 collection for mutations\n %0A \n+*%0A\n \n+ * @\n return\n- this.ready;\n+s %7BPromise%7D\n %0A \n-%7D%0A\n+ */\n %0A \n-log\n+sync\n () %7B\n@@ -615,54 +615,84 @@\n \n-// do nothing%0A // TODO log it somewhere\n+if (!this.ready) this.ready = this.Result.sync();%0A return this.ready;\n %0A \n@@ -734,36 +734,15 @@\n base\n- and insert models and stuff\n+%0A *\n %0A \n@@ -761,16 +761,24 @@\n String%7D \n+options.\n filename\n@@ -786,32 +786,99 @@\n * @\n-returns %7BPromise\n+param %7BFunction%7D options.log%0A *%0A * @returns %7B%7Bdb: Sequelize, result: Model%7D\n %7D%0A *\n@@ -883,16 +883,23 @@\n */%0A \n+static \n prepareD\n@@ -900,24 +900,23 @@\n epareDb(\n-filename\n+options\n ) %7B%0A%0A \n@@ -926,25 +926,18 @@\n const \n-sequelize\n+db\n = new S\n@@ -1034,16 +1034,24 @@\n orage': \n+options.\n filename\n@@ -1079,28 +1079,20 @@\n g': \n-msg =%3E this.log(msg)\n+options.log,\n %0A \n@@ -1113,61 +1113,273 @@\n \n-this.db = sequelize;%0A%0A this.Result = sequelize\n+const Result = Index.defineResultModel(db);%0A%0A return %7Bdb, Result%7D;%0A %7D%0A%0A /**%0A * Define the %22Result%22 model on the given database instance%0A * @param db%0A * @returns %7B*%7Cvoid%7CModel%7C%7B%7D%7D%0A */%0A static defineResultModel(db) %7B%0A%0A return db\n .def\n"}}},{"rowIdx":2597350,"cells":{"commit":{"kind":"string","value":"551054d702cd378e598dbbdee9731e540b9acf42"},"subject":{"kind":"string","value":"Remove comment"},"old_file":{"kind":"string","value":"lib/core/shared/store.js"},"new_file":{"kind":"string","value":"lib/core/shared/store.js"},"old_contents":{"kind":"string","value":"/*\n * Kuzzle, a backend software, self-hostable and ready to use\n * to power modern apps\n *\n * Copyright 2015-2020 Kuzzle\n * mailto: support AT kuzzle.io\n * website: http://kuzzle.io\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * https://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use strict';\n\nconst { Mutex } = require('../../util/mutex');\nconst { promiseAllN } = require('../../util/async');\nconst kerror = require('../../kerror');\nconst { getESIndexDynamicSettings } = require('../../util/esRequest');\n\n/**\n * Wrapper around the document store.\n * Once instantiated, this class can only access the index passed in the\n * constructor\n */\nclass Store {\n /**\n * @param {Kuzzle} kuzzle\n * @param {String} index\n * @param {storeScopeEnum} scope\n */\n constructor (index, scope) {\n this.index = index;\n this.scope = scope;\n\n const methodsMapping = {\n count: `core:storage:${scope}:document:count`,\n create: `core:storage:${scope}:document:create`,\n createCollection: `core:storage:${scope}:collection:create`,\n createOrReplace: `core:storage:${scope}:document:createOrReplace`,\n delete: `core:storage:${scope}:document:delete`,\n deleteByQuery: `core:storage:${scope}:document:deleteByQuery`,\n deleteCollection: `core:storage:${scope}:collection:delete`,\n deleteFields: `core:storage:${scope}:document:deleteFields`,\n deleteIndex: `core:storage:${scope}:index:delete`,\n exists: `core:storage:${scope}:document:exist`,\n get: `core:storage:${scope}:document:get`,\n getMapping: `core:storage:${scope}:mappings:get`,\n getSettings: `core:storage:${scope}:collection:settings:get`,\n mExecute: `core:storage:${scope}:document:mExecute`,\n mGet: `core:storage:${scope}:document:mGet`,\n refreshCollection: `core:storage:${scope}:collection:refresh`,\n replace: `core:storage:${scope}:document:replace`,\n search: `core:storage:${scope}:document:search`,\n truncateCollection: `core:storage:${scope}:collection:truncate`,\n update: `core:storage:${scope}:document:update`,\n updateByQuery: `core:storage:${scope}:document:updateByQuery`,\n updateCollection: `core:storage:${scope}:collection:update`,\n updateMapping: `core:storage:${scope}:mappings:update`,\n };\n\n for (const [method, event] of Object.entries(methodsMapping)) {\n this[method] = (...args) => global.kuzzle.ask(event, this.index, ...args);\n }\n\n // the scroll and multiSearch method are special: they doesn't need an index parameter\n // we keep them for ease of use\n this.scroll = (scrollId, opts) => global.kuzzle.ask(\n `core:storage:${scope}:document:scroll`,\n scrollId,\n opts);\n\n this.multiSearch = (targets, searchBody, opts) => global.kuzzle.ask(\n `core:storage:${scope}:document:multiSearch`,\n targets,\n searchBody,\n opts\n );\n }\n\n /**\n * Initialize the index, and creates provided collections\n *\n * @param {Object} collections - List of collections with mappings to create\n *\n * @returns {Promise}\n */\n async init (collections = {}) {\n const creatingMutex = new Mutex(`Store.init(${this.index})`, {\n timeout: 0,\n ttl: 30000,\n });\n\n const creatingLocked = await creatingMutex.lock();\n\n if (creatingLocked) {\n try {\n await this.createCollections(collections, {\n indexCacheOnly: false\n });\n }\n finally {\n await creatingMutex.unlock();\n }\n }\n else {\n // Ensure that cached collection are used after being properly\n // created by a kuzzle cluster\n const cachingMutex = new Mutex(`Store.init(${this.index})`, {\n timeout: -1,\n ttl: 30000,\n });\n\n await cachingMutex.lock();\n cachingMutex.unlock();\n\n await this.createCollections(collections, {\n indexCacheOnly: true\n });\n }\n }\n\n /**\n * Creates collections with the provided mappings\n *\n * @param {Object} collections - collections with mappings\n *\n * @returns {Promise}\n */\n createCollections (\n collections,\n { indexCacheOnly = false } = {}\n ) {\n return promiseAllN(\n Object.entries(collections).map(\n ([collection, config]) => async () => {\n // @deprecated\n if (config.mappings !== undefined && config.settings !== undefined) {\n\n // @deprecated\n const isConfigDeprecated = config.settings.number_of_shards === undefined && config.settings.number_of_replicas === undefined;\n\n if (indexCacheOnly) {\n return global.kuzzle.ask(\n `core:storage:${this.scope}:collection:create`,\n this.index,\n collection,\n // @deprecated\n isConfigDeprecated ? { mappings: config.mappings } : config,\n { indexCacheOnly });\n }\n\n const exist = await global.kuzzle.ask(\n `core:storage:${this.scope}:collection:exist`,\n this.index,\n collection);\n\n if (exist) {\n // @deprecated\n const dynamicSettings = (isConfigDeprecated)\n ? null\n : getESIndexDynamicSettings(config.settings);\n\n const existingSettings = await global.kuzzle.ask(\n `core:storage:${this.scope}:collection:settings:get`,\n this.index,\n collection);\n\n if (! isConfigDeprecated\n && parseInt(existingSettings.number_of_shards) !== config.settings.number_of_shards\n ) {\n if (global.NODE_ENV === 'development') {\n throw kerror.get(\n 'storage',\n 'wrong_collection_number_of_shards',\n collection,\n this.index,\n this.scope,\n 'number_of_shards',\n config.settings.number_of_shards,\n existingSettings.number_of_shards);\n }\n global.kuzzle.log.warn([\n 'Attempt to recreate',\n `an existing collection ${collection}`,\n `of index ${this.index} of scope ${this.scope}`,\n 'with non matching',\n 'static setting : number_of_shards',\n `at ${config.settings.number_of_shards} while existing one`,\n `is at ${existingSettings.number_of_shards}`,\n ].join('\\n'));\n }\n\n // Create call will update collection and cache it internally\n return global.kuzzle.ask(\n `core:storage:${this.scope}:collection:create`,\n this.index,\n collection,\n // @deprecated\n (isConfigDeprecated)\n ? { mappings: config.mappings }\n : { mappings: config.mappings, settings: dynamicSettings },\n );\n }\n\n return global.kuzzle.ask(\n `core:storage:${this.scope}:collection:create`,\n this.index,\n collection,\n // @deprecated\n isConfigDeprecated ? { mappings: config.mappings } : config,\n { indexCacheOnly });\n }\n\n // @deprecated\n return global.kuzzle.ask(\n `core:storage:${this.scope}:collection:create`,\n this.index,\n collection,\n { mappings: config },\n { indexCacheOnly });\n }\n ), 10\n );\n }\n}\n\nmodule.exports = Store;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.74e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -6963,84 +6963,8 @@\n %7D%0A%0A\n- // Create call will update collection and cache it internally%0A\n \n@@ -7311,24 +7311,65 @@\n Settings %7D,%0A\n+ %7B indexCacheOnly: true %7D%0A\n \n"}}},{"rowIdx":2597351,"cells":{"commit":{"kind":"string","value":"be75c469b7d90952e89a9ee7c87ea7ad017cd104"},"subject":{"kind":"string","value":"Allow alias exploding"},"old_file":{"kind":"string","value":"plugins/aliases.js"},"new_file":{"kind":"string","value":"plugins/aliases.js"},"old_contents":{"kind":"string","value":"// This is the aliases plugin\n// One must not run this plugin with the queue/smtp_proxy plugin.\nvar Address = require('address-rfc2821').Address;\n\nexports.register = function () {\n this.inherits('queue/discard');\n\n this.register_hook('rcpt','aliases');\n};\n\nexports.aliases = function (next, connection, params) {\n var plugin = this;\n var config = this.config.get('aliases', 'json') || {};\n var rcpt = params[0].address();\n var user = params[0].user;\n var host = params[0].host;\n var match = user.split(\"-\", 1);\n var action = \"\";\n\n if (config[rcpt]) {\n\n action = config[rcpt].action || action;\n match = rcpt;\n\n switch (action.toLowerCase()) {\n case 'drop':\n _drop(plugin, connection, rcpt);\n break;\n case 'alias':\n _alias(plugin, connection, match, config[match], host);\n break;\n default:\n connection.loginfo(plugin, \"unknown action: \" + action);\n }\n }\n\n if (config['@'+host]) {\n\n action = config['@'+host].action || action;\n match = '@'+host;\n\n switch (action.toLowerCase()) {\n case 'drop':\n _drop(plugin, connection, '@'+host);\n break;\n case 'alias':\n _alias(plugin, connection, match, config[match], host);\n break;\n default:\n connection.loginfo(plugin, \"unknown action: \" + action);\n }\n }\n\n if (config[user] || config[match[0]]) {\n if (config[user]) {\n action = config[user].action || action;\n match = user;\n }\n else {\n action = config[match[0]].action || action;\n match = match[0];\n }\n\n switch (action.toLowerCase()) {\n case 'drop':\n _drop(plugin, connection, rcpt);\n break;\n case 'alias':\n _alias(plugin, connection, match, config[match], host);\n break;\n default:\n connection.loginfo(plugin, \"unknown action: \" + action);\n }\n }\n\n next();\n};\n\nfunction _drop(plugin, connection, rcpt) {\n connection.logdebug(plugin, \"marking \" + rcpt + \" for drop\");\n connection.transaction.notes.discard = true;\n}\n\nfunction _alias(plugin, connection, key, config, host) {\n var to;\n var toAddress;\n\n if (config.to) {\n if (config.to.search(\"@\") !== -1) {\n to = config.to;\n }\n else {\n to = config.to + '@' + host;\n }\n\n connection.logdebug(plugin, \"aliasing \" +\n connection.transaction.rcpt_to + \" to \" + to);\n\n toAddress = new Address('<' + to + '>');\n connection.transaction.rcpt_to.pop();\n connection.transaction.rcpt_to.push(toAddress);\n }\n else {\n connection.loginfo(plugin, 'alias failed for ' + key +\n ', no \"to\" field in alias config');\n }\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000051324,"string":"0.000005"},"diff":{"kind":"string","value":"@@ -2422,16 +2422,20 @@\n ddress;%0A\n+ \n %0A if \n@@ -2444,24 +2444,444 @@\n onfig.to) %7B%0A\n+ if (Array.isArray(config.to)) %7B%0A connection.logdebug(plugin, %22aliasing %22 + connection.transaction.rcpt_to + %22 to %22 + config.to);%0A connection.transaction.rcpt_to.pop();%0A for (var i = 0, len = config.to.length; i %3C len; i++) %7B%0A toAddress = new Address('%3C' + config.to%5Bi%5D + '%3E');%0A connection.transaction.rcpt_to.push(toAddress);%0A %7D%0A %7D else %7B%0A \n if (\n@@ -2908,24 +2908,28 @@\n ) !== -1) %7B%0A\n+ \n \n@@ -2951,34 +2951,30 @@\n %0A \n- %7D%0A\n \n- \n+%7D\n else %7B%0A\n \n@@ -2957,32 +2957,36 @@\n %7D else %7B%0A\n+ \n to =\n@@ -3010,35 +3010,55 @@\n + host;%0A \n-%7D%0A%0A\n+ %7D%0A %0A \n connecti\n@@ -3091,16 +3091,20 @@\n ing %22 +%0A\n+ \n \n@@ -3154,25 +3154,40 @@\n + to);%0A\n-%0A\n+ %0A \n \n toAddres\n@@ -3170,32 +3170,33 @@\n %0A \n+ \n toAddress = new \n@@ -3220,32 +3220,36 @@\n + '%3E');%0A \n+ \n connection.trans\n@@ -3270,32 +3270,36 @@\n .pop();%0A \n+ \n+ \n connection.trans\n@@ -3326,24 +3326,28 @@\n toAddress);%0A\n+ \n %7D%0A el\n@@ -3343,16 +3343,18 @@\n %7D%0A \n+ %7D\n else %7B%0A\n"}}},{"rowIdx":2597352,"cells":{"commit":{"kind":"string","value":"70fc4295de4e9123f90bbf9e18749d990e2da403"},"subject":{"kind":"string","value":"Fix indentation"},"old_file":{"kind":"string","value":"simplePagination.spec.js"},"new_file":{"kind":"string","value":"simplePagination.spec.js"},"old_contents":{"kind":"string","value":"'use strict';\n\ndescribe('Simple Pagination', function() {\n\n\tvar pagination;\n\n\t// load the app\n\tbeforeEach(module('SimplePagination'));\n\n\t// get service \n\tbeforeEach(inject(function(Pagination) {\n\t\tpagination = Pagination.getNew();\n\t}));\n\n\tit('should paginate', function() {\n\t\tpagination.numPages = 2;\n\n\t\texpect(pagination.page).toBe(0);\n\n\t\tpagination.nextPage();\n\t\texpect(pagination.page).toBe(1); \n\n\t\tpagination.prevPage(); \n\t\texpect(pagination.page).toBe(0);\n\t});\n\n\tit('should not paginate outside min and max page', function() {\n\t\tpagination.numPages = 2;\n\n\t\tpagination.page = 0;\n\t\tpagination.prevPage();\n\t\texpect(pagination.page).toBe(0);\n\n\t\tpagination.page = 1;\n\t\tpagination.nextPage();\n\t\texpect(pagination.page).toBe(1);\n\t});\n\n\tit('should jump to a given page id', function() {\n\t\tpagination.numPages = 3;\n\n\t\texpect(pagination.page).toBe(0);\n\n\t\tpagination.toPageId(2);\n\t\texpect(pagination.page).toBe(2);\n\t});\n\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0172440056,"string":"0.017244"},"diff":{"kind":"string","value":"@@ -52,17 +52,18 @@\n on() %7B%0A%0A\n-%09\n+ \n var pagi\n@@ -71,17 +71,18 @@\n ation;%0A%0A\n-%09\n+ \n // load \n@@ -89,17 +89,18 @@\n the app%0A\n-%09\n+ \n beforeEa\n@@ -132,17 +132,18 @@\n on'));%0A%0A\n-%09\n+ \n // get s\n@@ -150,17 +150,18 @@\n ervice %0A\n-%09\n+ \n beforeEa\n@@ -189,26 +189,28 @@\n gination) %7B%0A\n-%09%09\n+ \n pagination =\n@@ -235,16 +235,18 @@\n ();%0A\n-%09\n+ \n %7D));%0A%0A\n-%09\n+ \n it('\n@@ -268,34 +268,36 @@\n ', function() %7B%0A\n-%09%09\n+ \n pagination.numPa\n@@ -306,18 +306,20 @@\n s = 2;%0A%0A\n-%09%09\n+ \n expect(p\n@@ -336,34 +336,36 @@\n page).toBe(0);%0A%0A\n-%09%09\n+ \n pagination.nextP\n@@ -363,34 +363,36 @@\n ion.nextPage();%0A\n-%09%09\n+ \n expect(paginatio\n@@ -412,18 +412,20 @@\n 1); %0A%0A\n-%09%09\n+ \n paginati\n@@ -440,18 +440,20 @@\n age(); %0A\n-%09%09\n+ \n expect(p\n@@ -477,23 +477,25 @@\n oBe(0);%0A\n-%09\n+ \n %7D);%0A%0A\n-%09\n+ \n it('shou\n@@ -542,34 +542,36 @@\n ', function() %7B%0A\n-%09%09\n+ \n pagination.numPa\n@@ -580,18 +580,20 @@\n s = 2;%0A%0A\n-%09%09\n+ \n paginati\n@@ -605,18 +605,20 @@\n ge = 0;%0A\n-%09%09\n+ \n paginati\n@@ -624,34 +624,36 @@\n ion.prevPage();%0A\n-%09%09\n+ \n expect(paginatio\n@@ -662,34 +662,36 @@\n page).toBe(0);%0A%0A\n-%09%09\n+ \n pagination.page \n@@ -695,18 +695,20 @@\n ge = 1;%0A\n-%09%09\n+ \n paginati\n@@ -722,18 +722,20 @@\n Page();%0A\n-%09%09\n+ \n expect(p\n@@ -763,15 +763,17 @@\n 1);%0A\n-%09\n+ \n %7D);%0A%0A\n-%09\n+ \n it('\n@@ -818,18 +818,20 @@\n ion() %7B%0A\n-%09%09\n+ \n paginati\n@@ -848,18 +848,20 @@\n s = 3;%0A%0A\n-%09%09\n+ \n expect(p\n@@ -886,18 +886,20 @@\n Be(0);%0A%0A\n-%09%09\n+ \n paginati\n@@ -918,10 +918,12 @@\n 2);%0A\n-%09%09\n+ \n expe\n@@ -955,9 +955,10 @@\n 2);%0A\n-%09\n+ \n %7D);%0A\n"}}},{"rowIdx":2597353,"cells":{"commit":{"kind":"string","value":"f6faa3bc938bb92cbe7497b228eeeba0ca256020"},"subject":{"kind":"string","value":"Edit comment"},"old_file":{"kind":"string","value":"core/tests/protractor/cacheSlugs.js"},"new_file":{"kind":"string","value":"core/tests/protractor/cacheSlugs.js"},"old_contents":{"kind":"string","value":"// Copyright 2016 The Oppia Authors. All Rights Reserved.\n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing, software\n// distributed under the License is distributed on an \"AS-IS\" BASIS,\n// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n// See the License for the specific language governing permissions and\n// limitations under the License.\n\n/**\n * @fileoverview End-to-end tests for cache slugs.\n */\n\nvar general = require('../protractor_utils/general.js');\n\nvar ERROR_PAGE_URL_SUFFIX = '/console_errors';\n\nvar getUniqueLogMessages = function(logs) {\n // Returns unique log messages.\n var logsDict = {};\n for (var i = 0; i < logs.length; i++) {\n if (!logsDict.hasOwnProperty(logs[i].message)) {\n logsDict[logs[i].message] = true;\n }\n }\n return Object.keys(logsDict);\n};\n\nvar checkConsoleErrorsExist = function(expectedErrors) {\n // Checks that browser logs match entries in expectedErrors array.\n browser.manage().logs().get('browser').then(function(browserLogs) {\n // Some browsers such as chrome raise two errors for a missing resource.\n // To keep consistent behaviour across browsers, we keep only the logs\n // that have a unique value for their message attribute.\n var uniqueLogMessages = getUniqueLogMessages(browserLogs);\n expect(uniqueLogMessages.length).toBe(expectedErrors.length);\n\n for (var i = 0; i < expectedErrors.length; i++) {\n var errorPresent = false;\n for (var j = 0; j < uniqueLogMessages.length; j++) {\n if (uniqueLogMessages[j].match(expectedErrors[i])) {\n errorPresent = true;\n }\n }\n expect(errorPresent).toBe(true);\n }\n });\n};\n\ndescribe('Cache Slugs', function() {\n it('should check that errors get logged for missing resources', function() {\n browser.get(ERROR_PAGE_URL_SUFFIX);\n var expectedErrors = [\n 'http://localhost:9001/build/fail/logo/288x128_logo_white.png',\n // Warning fired by synchronous AJAX request in\n // core/templates/dev/head/pages/header_js_libs.html this warning is\n // expected and it's needed for constants loading.\n 'Synchronous XMLHttpRequest on the main thread'\n ];\n checkConsoleErrorsExist(expectedErrors);\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.297e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2271,18 +2271,28 @@\n ibs.html\n- t\n+.%0A // T\n his warn\n@@ -2297,25 +2297,16 @@\n rning is\n-%0A //\n expecte\n"}}},{"rowIdx":2597354,"cells":{"commit":{"kind":"string","value":"7a8f39067376f44c30b688e960d980b1cafe2337"},"subject":{"kind":"string","value":"Add 'add' to projectDeploy provided interface"},"old_file":{"kind":"string","value":"core/cb.project.deploy/main.js"},"new_file":{"kind":"string","value":"core/cb.project.deploy/main.js"},"old_contents":{"kind":"string","value":"// Requires\nvar _ = require('underscore');\nvar DeploymentSolution = require(\"./solution\").DeploymentSolution;\n\n// List of all deployment solution\nvar SUPPORTED = [];\n\nfunction setup(options, imports, register) {\n // Import\n var logger = imports.logger.namespace(\"deployment\");\n var events = imports.events;\n var workspace = imports.workspace;\n\n // Return a specific solution\n var getSolution = function(solutionId) {\n return _.find(SOLUTIONS, function(solution) {\n return solution.id == solutionId;\n });\n };\n\n // Add a solution\n var addSolution = function(solution) {\n if (!_.isArray(solution)) solution = [solution];\n _.each(solution, function(_sol) {\n SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol));\n });\n }\n\n\n // Add basic solutions\n addSolution([\n require(\"./ghpages\")\n ])\n\n // Register\n register(null, {\n 'projectDeploy': {\n 'SUPPORTED': SUPPORTED,\n 'get': getSolution\n }\n });\n}\n\n// Exports\nmodule.exports = setup;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":9.262e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -814,16 +814,17 @@\n );%0A %7D\n+;\n %0A%0A%0A /\n@@ -1026,24 +1026,56 @@\n getSolution\n+,%0A 'add': addSolution\n %0A %7D%0A \n"}}},{"rowIdx":2597355,"cells":{"commit":{"kind":"string","value":"66d067a35ed2fcaf9decaad683ebeb2f563b2117"},"subject":{"kind":"string","value":"Add styling clases to fix buttons appearing white on iOS"},"old_file":{"kind":"string","value":"src/main/web/js/app/mobile-table.js"},"new_file":{"kind":"string","value":"src/main/web/js/app/mobile-table.js"},"old_contents":{"kind":"string","value":"$(function() {\n var markdownTable = $('.markdown-table-wrap');\n\n if (markdownTable.length) {\n $('').insertAfter(markdownTable);\n $('').insertAfter(markdownTable.find('table'));\n\n $('.btn--mobile-table-show').click(function () {\n $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show();\n });\n\n $('.btn--mobile-table-hide').click(function () {\n $(this).closest('.markdown-table-wrap').css('display', '');\n });\n }\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.74e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -114,32 +114,47 @@\n tton class=%22btn \n+btn--secondary \n btn--mobile-tabl\n@@ -237,24 +237,39 @@\n class=%22btn \n+btn--secondary \n btn--mobile-\n"}}},{"rowIdx":2597356,"cells":{"commit":{"kind":"string","value":"285bdf6c56f70fb2fd0a8fc7e881d244bf8a6cd0"},"subject":{"kind":"string","value":"Remove odd html tags"},"old_file":{"kind":"string","value":"src/components/NavigationBar/NavigationBar.js"},"new_file":{"kind":"string","value":"src/components/NavigationBar/NavigationBar.js"},"old_contents":{"kind":"string","value":"import React from 'react'\nimport {\n Link\n} from 'react-router-dom';\nimport './navigation-bar.css';\nimport { isAuthenticated } from '../../helper/auth';\nimport * as firebase from 'firebase';\n\nclass NavigationBar extends React.Component {\n\n signout() {\n firebase.auth().signOut();\n }\n\n authenticated() {\n return (\n
    \n
    \n \n
    \n )\n }\n\n unauthenticated() {\n return (\n
    \n
    \n \n
    \n )\n }\n\n render() {\n if (isAuthenticated()) {\n return this.authenticated();\n } else {\n return this.unauthenticated();\n }\n\n }\n}\n\nexport { NavigationBar }\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.9998009801,"string":"0.999801"},"diff":{"kind":"string","value":"@@ -344,170 +344,46 @@\n \n- %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A \n+%3Cnav className=%22navigation-bar glow%22%3E%0A\n \n@@ -451,36 +451,32 @@\n \n- \n %3CLink className=\n@@ -497,36 +497,41 @@\n r__link%22 to=%22/%22%3E\n-Home\n+Biografia\n %3C/Link%3E%0A \n@@ -530,36 +530,32 @@\n \n- \n %3C/div%3E%0A \n@@ -553,36 +553,32 @@\n \n- \n- \n %3Cdiv className=%22\n@@ -592,36 +592,32 @@\n ion-bar__item%22%3E%0A\n- \n \n@@ -704,20 +704,16 @@\n \n- \n- \n %3Ca class\n@@ -789,39 +789,31 @@\n \n- \n- \n %3C/div%3E%0A\n- \n %3C\n@@ -818,34 +818,16 @@\n %3C/nav%3E%0A\n- %3C/div%3E%0A\n \n@@ -891,170 +891,41 @@\n \n- %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A \n+%3Cnav className=%22navigation-bar%22%3E%0A\n \n@@ -973,36 +973,32 @@\n r__item--flex%22%3E%0A\n- \n \n@@ -1051,12 +1051,17 @@\n %22/%22%3E\n-Home\n+Biografia\n %3C/Li\n@@ -1072,36 +1072,32 @@\n \n- \n %3C/div%3E%0A \n@@ -1095,36 +1095,32 @@\n \n- \n- \n %3Cdiv className=%22\n@@ -1134,36 +1134,32 @@\n ion-bar__item%22%3E%0A\n- \n \n@@ -1221,36 +1221,32 @@\n %3ESign In%3C/Link%3E%0A\n- \n \n@@ -1267,34 +1267,12 @@\n \n- %3C/nav%3E%0A %3C/di\n+%3C/na\n v%3E%0A \n"}}},{"rowIdx":2597357,"cells":{"commit":{"kind":"string","value":"207f9e63434b1c191b8d3296e17e1bb881c580c0"},"subject":{"kind":"string","value":"reset board on start"},"old_file":{"kind":"string","value":"lib/board/index.js"},"new_file":{"kind":"string","value":"lib/board/index.js"},"old_contents":{"kind":"string","value":"import bus from 'component/bus'\nimport Board from 'kvnneff/bloxparty-board@1.0.3-alpha'\n\nexport default function plugin () {\n return function (app) {\n var board = new Board()\n\n app.set('board', board.json())\n board.on('change', function () {\n app.set('board', board.json())\n })\n bus.on('player:move', function (direction) {\n board.move(direction)\n })\n bus.on('game:begin', function () {\n board.start()\n })\n bus.on('client', function (data) {\n board.sync(data.board)\n })\n bus.on('game:stop', function () {\n board.stop()\n })\n }\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000011799,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -404,32 +404,52 @@\n , function () %7B%0A\n+ board.reset()%0A\n board.star\n"}}},{"rowIdx":2597358,"cells":{"commit":{"kind":"string","value":"965716143e75bb52d4979986fd35e9b4bbc1acde"},"subject":{"kind":"string","value":"use 1 for env instead of true, since it becomes a string"},"old_file":{"kind":"string","value":"lib/boilerplate.js"},"new_file":{"kind":"string","value":"lib/boilerplate.js"},"old_contents":{"kind":"string","value":"\"use strict\";\nvar mocha = require('gulp-mocha'),\n Q = require('q'),\n Transpiler = require('../index').Transpiler,\n jshint = require('gulp-jshint'),\n jscs = require('gulp-jscs'),\n vinylPaths = require('vinyl-paths'),\n del = require('del'),\n _ = require('lodash');\n\nvar DEFAULT_OPTS = {\n files: [\"*.js\", \"lib/**/*.js\", \"test/**/*.js\", \"!gulpfile.js\"],\n transpile: true,\n transpileOut: \"build\",\n babelOpts: {},\n linkBabelRuntime: true,\n jscs: true,\n jshint: true,\n watch: true,\n test: true,\n testFiles: null,\n testReporter: 'nyan',\n testTimeout: 8000,\n buildName: null\n};\n\nvar boilerplate = function (gulp, opts) {\n var spawnWatcher = require('../index').spawnWatcher.use(gulp);\n var runSequence = Q.denodeify(require('run-sequence').use(gulp));\n var defOpts = _.clone(DEFAULT_OPTS);\n _.extend(defOpts, opts);\n opts = defOpts;\n\n process.env.APPIUM_NOTIF_BUILD_NAME = opts.buildName;\n\n gulp.task('clean', function () {\n if (opts.transpile) {\n return gulp.src(opts.transpileOut, {read: false})\n .pipe(vinylPaths(del));\n }\n });\n\n if (opts.test) {\n var testDeps = [];\n var testDir = 'test';\n if (opts.transpile) {\n testDeps.push('transpile');\n testDir = opts.transpileOut + '/test';\n }\n\n var testFiles = opts.testFiles ? opts.testFiles :\n testDir + '/**/*-specs.js';\n gulp.task('test', testDeps, function () {\n var mochaOpts = {\n reporter: opts.testReporter,\n timeout: opts.testTimeout\n };\n // set env so our code knows when it's being run in a test env\n process.env._TESTING = true;\n var testProc = gulp\n .src(testFiles, {read: false})\n .pipe(mocha(mochaOpts))\n .on('error', spawnWatcher.handleError);\n process.env._TESTING = false;\n return testProc;\n });\n }\n\n if (opts.transpile) {\n gulp.task('transpile', function () {\n var transpiler = new Transpiler(opts.babelOpts);\n return gulp.src(opts.files, {base: './'})\n .pipe(transpiler.stream())\n .on('error', spawnWatcher.handleError)\n .pipe(gulp.dest(opts.transpileOut));\n });\n\n gulp.task('prepublish', function () {\n return runSequence('clean', 'transpile');\n });\n }\n\n var lintTasks = [];\n if (opts.jscs) {\n gulp.task('jscs', function () {\n return gulp\n .src(opts.files)\n .pipe(jscs())\n .on('error', spawnWatcher.handleError);\n });\n lintTasks.push('jscs');\n }\n\n if (opts.jshint) {\n gulp.task('jshint', function () {\n return gulp\n .src(opts.files)\n .pipe(jshint())\n .pipe(jshint.reporter('jshint-stylish'))\n .pipe(jshint.reporter('fail'))\n .on('error', spawnWatcher.handleError);\n });\n lintTasks.push('jshint');\n }\n\n if (opts.jscs || opts.jshint) {\n opts.lint = true;\n gulp.task('lint', lintTasks);\n }\n\n var defaultSequence = [];\n if (opts.transpile) defaultSequence.push('clean');\n if (opts.lint) defaultSequence.push('lint');\n if (opts.transpile) defaultSequence.push('transpile');\n if (opts.test) defaultSequence.push('test');\n\n if (opts.watch) {\n spawnWatcher.clear(false);\n spawnWatcher.configure('watch', opts.files, function () {\n return runSequence.apply(null, defaultSequence);\n });\n }\n\n gulp.task('once', function () {\n return runSequence.apply(null, defaultSequence);\n });\n\n gulp.task('default', [opts.watch ? 'watch' : 'once']);\n};\n\nmodule.exports = {\n use: function (gulp) {\n return function (opts) {\n boilerplate(gulp, opts);\n };\n }\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000110281,"string":"0.000011"},"diff":{"kind":"string","value":"@@ -1633,20 +1633,17 @@\n STING = \n-true\n+1\n ;%0A \n@@ -1782,44 +1782,8 @@\n r);%0A\n- process.env._TESTING = false;%0A\n \n"}}},{"rowIdx":2597359,"cells":{"commit":{"kind":"string","value":"95fb0e2af62acc4b3ea4d88e1832325807467143"},"subject":{"kind":"string","value":"Put initialization in a separate callable function."},"old_file":{"kind":"string","value":"www/googleplayservices.js"},"new_file":{"kind":"string","value":"www/googleplayservices.js"},"old_contents":{"kind":"string","value":"var argscheck = require ('cordova/argscheck')\nvar exec = require ('cordova/exec')\n\nmodule.exports = function () {\n var exports = {}\n \n exports.getPlayerId = function (init) {\n var success = (typeof init.success != \"undefined\") ? init.success : function () {}\n var error = (typeof init.error != \"undefined\") ? init.error : function () {}\n cordova.exec (success, error, \"GooglePlayServices\", \"getPlayerId\", [])\n }\n \n return exports\n} ()"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.879e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -421,16 +421,303 @@\n %5D)%0A %7D%0A %0A\n+ exports.initialize = function (init) %7B%0A var success = (typeof init.success != %22undefined%22) ? init.success : function () %7B%7D%0A var error = (typeof init.error != %22undefined%22) ? init.error : function () %7B%7D%0A cordova.exec (success, error, %22GooglePlayServices%22, %22initialize%22, %5B%5D)%0A %7D%0A %0A\n return \n@@ -728,8 +728,9 @@\n rts%0A%7D ()\n+%0A\n"}}},{"rowIdx":2597360,"cells":{"commit":{"kind":"string","value":"eab5c2896ea862ce2023e317b65d483d592d1792"},"subject":{"kind":"string","value":"Fix to check for zero s value in sign function"},"old_file":{"kind":"string","value":"lib/browser/Key.js"},"new_file":{"kind":"string","value":"lib/browser/Key.js"},"old_contents":{"kind":"string","value":"var ECKey = require('../../browser/vendor-bundle.js').ECKey;\nvar SecureRandom = require('../SecureRandom');\nvar Curve = require('../Curve');\nvar bignum = require('bignum');\n\nvar Key = function() {\n this._pub = null;\n this._compressed = true; // default\n};\n\nvar bufferToArray = Key.bufferToArray = function(buffer) {\n var ret = [];\n\n var l = buffer.length;\n for(var i =0; i item.trim()) : Array.from(value)\n}\n\nfunction toBoolean (value) {\n return (typeof value === 'string') ? !!value.match(/^(true|yes)$/i) : !!value\n}\n\nclass JobState {\n constructor (parent, jobName) {\n this.parent = parent\n this.jobName = jobName\n }\n\n getOutputFilePath () {\n return this.outputFilePath\n }\n\n setOutputFilePath (value) {\n this.outputFilePath = value\n }\n\n getFileDatabase () {\n return this.fileDatabase\n }\n\n setFileDatabase (value) {\n this.fileDatabase = value\n }\n\n getLogMessages () {\n return this.logMessages\n }\n\n setLogMessages (value) {\n this.logMessages = value\n }\n\n getJobName () {\n return this.jobName\n }\n\n getFilePath () {\n return this.parent.getFilePath()\n }\n\n getProjectPath () {\n return this.parent.getProjectPath()\n }\n\n getTexFilePath () {\n return this.parent.getTexFilePath()\n }\n\n setTexFilePath (value) {\n this.parent.setTexFilePath(value)\n }\n\n getKnitrFilePath () {\n return this.parent.getKnitrFilePath()\n }\n\n setKnitrFilePath (value) {\n this.parent.setKnitrFilePath(value)\n }\n\n getCleanPatterns () {\n return this.parent.getCleanPatterns()\n }\n\n getEnableSynctex () {\n return this.parent.getEnableSynctex()\n }\n\n getEnableShellEscape () {\n return this.parent.getEnableShellEscape()\n }\n\n getEnableExtendedBuildMode () {\n return this.parent.getEnableExtendedBuildMode()\n }\n\n getEngine () {\n return this.parent.getEngine()\n }\n\n getMoveResultToSourceDirectory () {\n return this.parent.getMoveResultToSourceDirectory()\n }\n\n getOutputDirectory () {\n return this.parent.getOutputDirectory()\n }\n\n getOutputFormat () {\n return this.parent.getOutputFormat()\n }\n\n getProducer () {\n return this.parent.getProducer()\n }\n\n getShouldRebuild () {\n return this.parent.getShouldRebuild()\n }\n}\n\nexport default class BuildState {\n constructor (filePath, jobNames = [null], shouldRebuild = false) {\n this.setFilePath(filePath)\n this.setJobNames(jobNames)\n this.setShouldRebuild(shouldRebuild)\n this.setEnableSynctex(false)\n this.setEnableShellEscape(false)\n this.setEnableExtendedBuildMode(false)\n this.subfiles = new Set()\n }\n\n getKnitrFilePath () {\n return this.knitrFilePath\n }\n\n setKnitrFilePath (value) {\n this.knitrFilePath = value\n }\n\n getTexFilePath () {\n return this.texFilePath\n }\n\n setTexFilePath (value) {\n this.texFilePath = value\n }\n\n getProjectPath () {\n return this.projectPath\n }\n\n setProjectPath (value) {\n this.projectPath = value\n }\n\n getCleanPatterns () {\n return this.cleanPatterns\n }\n\n setCleanPatterns (value) {\n this.cleanPatterns = toArray(value)\n }\n\n getEnableSynctex () {\n return this.enableSynctex\n }\n\n setEnableSynctex (value) {\n this.enableSynctex = toBoolean(value)\n }\n\n getEnableShellEscape () {\n return this.enableShellEscape\n }\n\n setEnableShellEscape (value) {\n this.enableShellEscape = toBoolean(value)\n }\n\n getEnableExtendedBuildMode () {\n return this.enableExtendedBuildMode\n }\n\n setEnableExtendedBuildMode (value) {\n this.enableExtendedBuildMode = toBoolean(value)\n }\n\n getEngine () {\n return this.engine\n }\n\n setEngine (value) {\n this.engine = value\n }\n\n getJobStates () {\n return this.jobStates\n }\n\n setJobStates (value) {\n this.jobStates = value\n }\n\n getMoveResultToSourceDirectory () {\n return this.moveResultToSourceDirectory\n }\n\n setMoveResultToSourceDirectory (value) {\n this.moveResultToSourceDirectory = toBoolean(value)\n }\n\n getOutputFormat () {\n return this.outputFormat\n }\n\n setOutputFormat (value) {\n this.outputFormat = value\n }\n\n getOutputDirectory () {\n return this.outputDirectory\n }\n\n setOutputDirectory (value) {\n this.outputDirectory = value\n }\n\n getProducer () {\n return this.producer\n }\n\n setProducer (value) {\n this.producer = value\n }\n\n getSubfiles () {\n return Array.from(this.subfiles.values())\n }\n\n addSubfile (value) {\n this.subfiles.add(value)\n }\n\n hasSubfile (value) {\n return this.subfiles.has(value)\n }\n\n getShouldRebuild () {\n return this.shouldRebuild\n }\n\n setShouldRebuild (value) {\n this.shouldRebuild = toBoolean(value)\n }\n\n getFilePath () {\n return this.filePath\n }\n\n setFilePath (value) {\n this.filePath = value\n this.texFilePath = isTexFile(value) ? value : undefined\n this.knitrFilePath = isKnitrFile(value) ? value : undefined\n this.projectPath = path.dirname(value)\n }\n\n getJobNames () {\n return this.jobStates.map(jobState => jobState.getJobName())\n }\n\n setJobNames (value) {\n this.jobStates = toArray(value).map(jobName => new JobState(this, jobName))\n }\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000012936,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -1565,24 +1565,109 @@\n Mode()%0A %7D%0A%0A\n+ getOpenResultAfterBuild () %7B%0A return this.parent.getOpenResultAfterBuild()%0A %7D%0A%0A\n getEngine \n@@ -1663,32 +1663,32 @@\n getEngine () %7B%0A\n-\n return this.\n@@ -2399,32 +2399,72 @@\n uildMode(false)%0A\n+ this.setOpenResultAfterBuild(false)%0A\n this.subfile\n@@ -3367,32 +3367,32 @@\n dMode (value) %7B%0A\n-\n this.enableE\n@@ -3428,24 +3428,187 @@\n value)%0A %7D%0A%0A\n+ getOpenResultAfterBuild () %7B%0A return this.openResultAfterBuild%0A %7D%0A%0A setOpenResultAfterBuild (value) %7B%0A this.openResultAfterBuild = toBoolean(value)%0A %7D%0A%0A\n getEngine \n"}}},{"rowIdx":2597362,"cells":{"commit":{"kind":"string","value":"d39a9a0f189f3a2ce13e230ecd76ee4d9fd6e575"},"subject":{"kind":"string","value":"bring back select-all-on-click"},"old_file":{"kind":"string","value":"src/components/views/elements/EditableText.js"},"new_file":{"kind":"string","value":"src/components/views/elements/EditableText.js"},"old_contents":{"kind":"string","value":"/*\nCopyright 2015, 2016 OpenMarket Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n'use strict';\n\nvar React = require('react');\n\nconst KEY_TAB = 9;\nconst KEY_SHIFT = 16;\nconst KEY_WINDOWS = 91;\n\nmodule.exports = React.createClass({\n displayName: 'EditableText',\n propTypes: {\n onValueChanged: React.PropTypes.func,\n initialValue: React.PropTypes.string,\n label: React.PropTypes.string,\n placeholder: React.PropTypes.string,\n className: React.PropTypes.string,\n labelClassName: React.PropTypes.string,\n placeholderClassName: React.PropTypes.string,\n blurToCancel: React.PropTypes.bool,\n },\n\n Phases: {\n Display: \"display\",\n Edit: \"edit\",\n },\n\n value: '',\n placeholder: false,\n\n getDefaultProps: function() {\n return {\n onValueChanged: function() {},\n initialValue: '',\n label: '',\n placeholder: '',\n };\n },\n\n getInitialState: function() {\n return {\n phase: this.Phases.Display,\n }\n },\n\n componentWillReceiveProps: function(nextProps) {\n this.value = nextProps.initialValue;\n },\n\n componentDidMount: function() {\n this.value = this.props.initialValue;\n if (this.refs.editable_div) {\n this.showPlaceholder(!this.value);\n }\n },\n\n showPlaceholder: function(show) {\n if (show) {\n this.refs.editable_div.textContent = this.props.placeholder;\n this.refs.editable_div.setAttribute(\"class\", this.props.className + \" \" + this.props.placeholderClassName);\n this.placeholder = true;\n this.value = '';\n }\n else {\n this.refs.editable_div.textContent = this.value;\n this.refs.editable_div.setAttribute(\"class\", this.props.className);\n this.placeholder = false;\n } \n },\n\n getValue: function() {\n return this.value;\n },\n\n edit: function() {\n this.setState({\n phase: this.Phases.Edit,\n });\n },\n\n cancelEdit: function() {\n this.setState({\n phase: this.Phases.Display,\n });\n this.onValueChanged(false);\n },\n\n onValueChanged: function(shouldSubmit) {\n this.props.onValueChanged(this.value, shouldSubmit);\n },\n\n onKeyDown: function(ev) {\n // console.log(\"keyDown: textContent=\" + ev.target.textContent + \", value=\" + this.value + \", placeholder=\" + this.placeholder);\n \n if (this.placeholder) {\n if (ev.keyCode !== KEY_SHIFT && !ev.metaKey && !ev.ctrlKey && !ev.altKey && ev.keyCode !== KEY_WINDOWS && ev.keyCode !== KEY_TAB) {\n this.showPlaceholder(false);\n }\n }\n\n if (ev.key == \"Enter\") {\n ev.stopPropagation();\n ev.preventDefault();\n }\n\n // console.log(\"keyDown: textContent=\" + ev.target.textContent + \", value=\" + this.value + \", placeholder=\" + this.placeholder);\n },\n\n onKeyUp: function(ev) {\n // console.log(\"keyUp: textContent=\" + ev.target.textContent + \", value=\" + this.value + \", placeholder=\" + this.placeholder);\n\n if (!ev.target.textContent) {\n this.showPlaceholder(true);\n }\n else if (!this.placeholder) {\n this.value = ev.target.textContent;\n }\n\n if (ev.key == \"Enter\") {\n this.onFinish(ev);\n } else if (ev.key == \"Escape\") {\n this.cancelEdit();\n }\n\n // console.log(\"keyUp: textContent=\" + ev.target.textContent + \", value=\" + this.value + \", placeholder=\" + this.placeholder);\n },\n\n onClickDiv: function(ev) {\n this.setState({\n phase: this.Phases.Edit,\n })\n },\n\n onFocus: function(ev) {\n //ev.target.setSelectionRange(0, ev.target.textContent.length);\n },\n\n onFinish: function(ev) {\n var self = this;\n this.setState({\n phase: this.Phases.Display,\n }, function() {\n self.onValueChanged(ev.key === \"Enter\");\n });\n },\n\n onBlur: function(ev) {\n if (this.props.blurToCancel)\n this.cancelEdit();\n else\n this.onFinish(ev)\n },\n\n render: function() {\n var editable_el;\n\n if (this.state.phase == this.Phases.Display && (this.props.label || this.props.labelClassName) && !this.value) {\n // show the label\n editable_el =
    {this.props.label}
    ;\n } else {\n // show the content editable div, but manually manage its contents as react and contentEditable don't play nice together\n editable_el =
    ;\n }\n\n return editable_el;\n }\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":5.931e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -4347,16 +4347,289 @@\n length);\n+%0A%0A var node = ev.target.childNodes%5B0%5D;%0A var range = document.createRange();%0A range.setStart(node, 0);%0A range.setEnd(node, node.length);%0A %0A var sel = window.getSelection();%0A sel.removeAllRanges();%0A sel.addRange(range);\n %0A %7D,%0A\n"}}},{"rowIdx":2597363,"cells":{"commit":{"kind":"string","value":"384f50609d92ed9e525f261ea6bf4a64d97b401c"},"subject":{"kind":"string","value":"Allow searching by partial prefix (/w or /wo '+')"},"old_file":{"kind":"string","value":"src/components/views/login/CountryDropdown.js"},"new_file":{"kind":"string","value":"src/components/views/login/CountryDropdown.js"},"old_contents":{"kind":"string","value":"/*\nCopyright 2017 Vector Creations Ltd\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport React from 'react';\n\nimport sdk from '../../../index';\n\nimport { COUNTRIES } from '../../../phonenumber';\n\nconst COUNTRIES_BY_ISO2 = new Object(null);\nfor (const c of COUNTRIES) {\n COUNTRIES_BY_ISO2[c.iso2] = c;\n}\n\nfunction countryMatchesSearchQuery(query, country) {\n if (country.name.toUpperCase().indexOf(query.toUpperCase()) == 0) return true;\n if (country.iso2 == query.toUpperCase()) return true;\n if (country.prefix == query) return true;\n return false;\n}\n\nexport default class CountryDropdown extends React.Component {\n constructor(props) {\n super(props);\n this._onSearchChange = this._onSearchChange.bind(this);\n this._onOptionChange = this._onOptionChange.bind(this);\n this._getShortOption = this._getShortOption.bind(this);\n\n this.state = {\n searchQuery: '',\n };\n }\n\n componentWillMount() {\n if (!this.props.value) {\n // If no value is given, we start with the first\n // country selected, but our parent component\n // doesn't know this, therefore we do this.\n this.props.onOptionChange(COUNTRIES[0]);\n }\n }\n\n _onSearchChange(search) {\n this.setState({\n searchQuery: search,\n });\n }\n\n _onOptionChange(iso2) {\n this.props.onOptionChange(COUNTRIES_BY_ISO2[iso2]);\n }\n\n _flagImgForIso2(iso2) {\n return ;\n }\n\n _getShortOption(iso2) {\n if (!this.props.isSmall) {\n return undefined;\n }\n let countryPrefix;\n if (this.props.showPrefix) {\n countryPrefix = '+' + COUNTRIES_BY_ISO2[iso2].prefix;\n }\n return \n { this._flagImgForIso2(iso2) }\n { countryPrefix }\n ;\n }\n\n render() {\n const Dropdown = sdk.getComponent('elements.Dropdown');\n\n let displayedCountries;\n if (this.state.searchQuery) {\n displayedCountries = COUNTRIES.filter(\n countryMatchesSearchQuery.bind(this, this.state.searchQuery),\n );\n if (\n this.state.searchQuery.length == 2 &&\n COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()]\n ) {\n // exact ISO2 country name match: make the first result the matches ISO2\n const matched = COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()];\n displayedCountries = displayedCountries.filter((c) => {\n return c.iso2 != matched.iso2;\n });\n displayedCountries.unshift(matched);\n }\n } else {\n displayedCountries = COUNTRIES;\n }\n\n const options = displayedCountries.map((country) => {\n return
    \n {this._flagImgForIso2(country.iso2)}\n {country.name}\n
    ;\n });\n\n // default value here too, otherwise we need to handle null / undefined\n // values between mounting and the initial value propgating\n const value = this.props.value || COUNTRIES[0].iso2;\n\n return \n {options}\n ;\n }\n}\n\nCountryDropdown.propTypes = {\n className: React.PropTypes.string,\n isSmall: React.PropTypes.bool,\n // if isSmall, show +44 in the selected value\n showPrefix: React.PropTypes.bool,\n onOptionChange: React.PropTypes.func.isRequired,\n value: React.PropTypes.string,\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000013101,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -835,24 +835,150 @@\n country) %7B%0A\n+ // Remove '+' if present (when searching for a prefix)%0A if (query%5B0%5D === '+') %7B%0A query = query.slice(1);%0A %7D%0A%0A\n if (coun\n@@ -1128,25 +1128,38 @@\n y.prefix\n- == query\n+.indexOf(query) !== -1\n ) return\n"}}},{"rowIdx":2597364,"cells":{"commit":{"kind":"string","value":"f69efdf8441ba4ec5e8abf9af4fa04b29f15130d"},"subject":{"kind":"string","value":"Add args as a parameter for cmdRunner.runHadoopJar"},"old_file":{"kind":"string","value":"cosmos-tidoop-api/src/cmd_runner.js"},"new_file":{"kind":"string","value":"cosmos-tidoop-api/src/cmd_runner.js"},"old_contents":{"kind":"string","value":"/**\n * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U\n *\n * This file is part of fiware-cosmos (FI-WARE project).\n *\n * fiware-cosmos is free software: you can redistribute it and/or modify it under the terms of the GNU Affero\n * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your\n * option) any later version.\n * fiware-cosmos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the\n * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License\n * for more details.\n *\n * You should have received a copy of the GNU Affero General Public License along with fiware-cosmos. If not, see\n * http://www.gnu.org/licenses/.\n *\n * For those usages not covered by the GNU Affero General Public License please contact with\n * francisco dot romerobueno at telefonica dot com\n */\n\n/**\n * Command runner.\n *\n * Author: frb\n */\n\n// Module dependencies\nvar spawn = require('child_process').spawn;\n\nfunction runHadoopJar(userId, jarName, jarInHDFS, className, libJarsName, libJarsInHDFS, input, output, callback) {\n // Copy the jar from the HDFS user space\n var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', jarInHDFS, '/home/' + userId + '/' + jarName];\n var command = spawn('sudo', params);\n\n command.on('close', function(code) {\n // Copy the libjar from the HDFS user space\n var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', libJarsInHDFS, '/home/' + userId + '/' + libJarsName];\n var command = spawn('sudo', params);\n\n command.on('close', function(code) {\n // Run the MR job\n var params = ['-u', userId, 'hadoop', 'jar', '/home/' + userId + '/' + jarName, className, '-libjars', '/home/' + userId + '/' + libJarsName, input, output];\n var command = spawn('sudo', params);\n var jobId = null;\n\n // This function catches the stderr as it is being produced (console logs are printed in the stderr). At the\n // moment of receiving the line containing the job ID, get it and return with no error (no error means the\n // job could be run, independently of the final result of the job)\n command.stderr.on('data', function (data) {\n var dataStr = data.toString();\n var magicString = 'Submitting tokens for job: ';\n var indexOfJobId = dataStr.indexOf(magicString);\n\n if(indexOfJobId >= 0) {\n jobId = dataStr.substring(indexOfJobId + magicString.length, indexOfJobId + magicString.length + 22);\n var params = ['-u', userId, 'rm', '/home/' + userId + '/' + jarName];\n var command = spawn('sudo', params);\n var params = ['-u', userId, 'rm', '/home/' + userId + '/' + libJarsName];\n var command = spawn('sudo', params);\n return callback(null, jobId);\n } // if\n });\n\n // This function catches the moment the command finishes. Return the error code if the job ID was never got\n command.on('close', function (code) {\n if (jobId === null) {\n return callback(code, null);\n } // if\n });\n });\n });\n} // runHadoopJar\n\nfunction runHadoopJobList(userId, callback) {\n var params = ['job', '-list', 'all'];\n var command = spawn('hadoop', params);\n var jobInfos = null;\n\n command.stdout.on('data', function (data) {\n var dataStr = data.toString();\n jobInfos = '[';\n var firstJobInfo = true;\n var lines = dataStr.split(\"\\n\");\n\n for (i in lines) {\n if(i > 1) {\n var fields = lines[i].split(\"\\t\");\n\n if (fields.length > 3 && fields[3].replace(/ /g,'') === userId) {\n var jobInfo = '{';\n\n for (j in fields) {\n if (fields[j].length > 0) {\n var value = fields[j].replace(/ /g,'');\n\n if (j == 0) {\n jobInfo += '\"job_id\":\"' + value + '\"';\n } else if (j == 1) {\n jobInfo += ',\"state\":\"' + value + '\"';\n } else if (j == 2) {\n jobInfo += ',\"start_time\":\"' + value + '\"';\n } else if (j == 3) {\n jobInfo += ',\"user_id\":\"' + value + '\"';\n } // if else\n } // if\n } // for\n\n jobInfo += '}';\n\n if (firstJobInfo) {\n jobInfos += jobInfo;\n firstJobInfo = false;\n } else {\n jobInfos += ',' + jobInfo;\n } // if else\n } // if\n } // if\n } // for\n\n jobInfos += ']';\n return callback(null, jobInfos);\n });\n\n // This function catches the moment the command finishes. Return the error code if the jobs information was never\n // got\n command.on('close', function (code) {\n if (jobInfos === null) {\n return callback(code, null);\n } // if\n });\n} // runHadoopJobList\n\nfunction runHadoopJobKill(jobId, callback) {\n var params = ['job', '-kill', jobId];\n var command = spawn('hadoop', params);\n\n command.stderr.on('data', function (data) {\n var dataStr = data.toString();\n var magicString = 'Application with id';\n\n if(dataStr.indexOf(magicString) >= 0) {\n return callback('Application does not exist');\n } // if\n });\n\n command.stdout.on('data', function (data) {\n var dataStr = data.toString();\n var magicString = 'Killed job';\n\n if (dataStr.indexOf(magicString) >= 0) {\n return callback(null);\n } // if\n });\n} // runHadoopJobKill\n\nmodule.exports = {\n runHadoopJar: runHadoopJar,\n runHadoopJobList: runHadoopJobList,\n runHadoopJobKill: runHadoopJobKill\n} // module.exports\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.477e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1134,16 +1134,22 @@\n sInHDFS,\n+ args,\n input, \n@@ -1805,16 +1805,22 @@\n assName,\n+ args,\n '-libja\n"}}},{"rowIdx":2597365,"cells":{"commit":{"kind":"string","value":"8a0df6aefa71fb2e34bc891b59791d8c8d5c963c"},"subject":{"kind":"string","value":"Fix build target selection"},"old_file":{"kind":"string","value":"lib/admin.js"},"new_file":{"kind":"string","value":"lib/admin.js"},"old_contents":{"kind":"string","value":"var async = require('async'),\n campfire = require('./campfire'),\n config = require('./config'),\n express = require('express'),\n log = require('./log');\n\nmodule.exports = function(app, repo) {\n var branches = [],\n currentBranch;\n\n campfire.init(repo);\n\n app.get('/ms_admin', function(req, res, next) {\n async.parallel([\n function(callback) {\n repo.remoteBranches(function(err, data) {\n branches = data;\n callback(err);\n });\n },\n function(callback) {\n repo.currentBranch(function(err, data) {\n currentBranch = data;\n callback(err);\n });\n }\n ], function(err) {\n res.render('index', {\n gitPath: config.appDir,\n mocksEnabled: !!config.mocksEnabled,\n buildTarget: config.buildTarget || {},\n buildTargets: config.projectConfig['build-targets'] || [],\n servers: config.projectConfig.servers || [],\n proxyServer: config.proxyServer,\n branches: branches || [],\n currentBranch: currentBranch,\n log: log.logs, error: log.errors\n });\n });\n });\n\n app.all('/ms_admin/proxy-server', express.bodyParser(), function(req, res, next) {\n log.reset();\n\n // Filter the user input\n var proxy = req.param('proxy');\n if ((config.projectConfig.servers || []).indexOf(proxy) < 0) {\n res.redirect('/ms_admin');\n return;\n }\n\n config.proxyServer = proxy;\n campfire.speak('proxy changed to ' + config.proxyServer);\n res.redirect('/ms_admin');\n });\n app.all('/ms_admin/mocks', express.bodyParser(), function(req, res, next) {\n log.reset();\n\n config.mocksEnabled = req.param('enable-mocks');\n if (config.mocksEnabled === 'false') {\n config.mocksEnabled = false;\n }\n config.mocksEnabled = !!config.mocksEnabled;\n\n campfire.speak('mocksEnabled changed to ' + config.mocksEnabled);\n res.redirect('/ms_admin');\n });\n app.all('/ms_admin/build-target', express.bodyParser(), function(req, res, next) {\n log.reset();\n\n // Filter the input\n var target = req.param('target');\n if ((config.projectConfig['build-targets'] || []).indexOf(target) < 0) {\n res.redirect('/ms_admin');\n return;\n }\n\n config.buildTarget = target;\n repo.build(function() {\n campfire.speak('build target changed to ' + config.buildTarget.name);\n res.redirect('/ms_admin');\n });\n });\n app.all('/ms_admin/branch', express.bodyParser(), function(req, res, next) {\n log.reset();\n\n // Filter the input\n var branch = req.param('branch'),\n sameBranch = currentBranch === branch;\n console.log('branch', branch, branches, branches.indexOf(branch));\n if (branches.indexOf(branch) < 0) {\n res.redirect('/ms_admin');\n return;\n }\n\n console.log('Switching to branch', branch);\n async.series([\n function(callback) {\n // Skip checkout if we are already on this branch\n if (sameBranch) {\n callback();\n } else {\n repo.checkout(branch, callback);\n }\n },\n function(callback) {\n repo.pull(!sameBranch, function(err) {\n callback(err);\n });\n },\n function(callback) {\n repo.build(callback);\n }\n ],\n function(err) {\n err || campfire.speak('branch changed to ' + branch);\n res.redirect('/ms_admin');\n });\n });\n app.all('/ms_admin/pull', express.bodyParser(), function(req, res, next) {\n log.reset();\n\n module.exports.pull(repo, currentBranch, function(err) {\n res.redirect('/ms_admin');\n });\n });\n};\n\nmodule.exports.pull = function(repo, currentBranch, callback) {\n log.reset();\n\n async.series([\n function(callback) {\n repo.pull(callback);\n },\n function(callback) {\n repo.build(callback);\n }\n ],\n function(err) {\n if (err) {\n log.exception(err);\n }\n\n err || process.env.CAMPFIRE_QUIET || campfire.speak('pulled from ' + currentBranch);\n callback && callback(err);\n });\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.425e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2066,16 +2066,25 @@\n arget = \n+parseInt(\n req.para\n@@ -2094,16 +2094,17 @@\n target')\n+)\n ;%0A if\n@@ -2097,32 +2097,46 @@\n get'));%0A if (\n+target %3C 0 %7C%7C \n (config.projectC\n@@ -2169,28 +2169,25 @@\n %5B%5D).\n-indexOf(\n+length %3C= \n target)\n- %3C 0)\n %7B%0A \n"}}},{"rowIdx":2597366,"cells":{"commit":{"kind":"string","value":"27df63964a1fc93b2fd909c17db766ebf460d292"},"subject":{"kind":"string","value":"Fix \"no-unused-styles\" suite name"},"old_file":{"kind":"string","value":"tests/lib/rules/no-unused-styles.js"},"new_file":{"kind":"string","value":"tests/lib/rules/no-unused-styles.js"},"old_contents":{"kind":"string","value":"/**\n * @fileoverview No unused styles defined in javascript files\n * @author Tom Hastjarjanto\n */\n\n'use strict';\n\n// ------------------------------------------------------------------------------\n// Requirements\n// ------------------------------------------------------------------------------\n\nconst rule = require('../../../lib/rules/no-unused-styles');\nconst RuleTester = require('eslint').RuleTester;\n\nrequire('babel-eslint');\n\n// ------------------------------------------------------------------------------\n// Tests\n// ------------------------------------------------------------------------------\n\nconst ruleTester = new RuleTester();\nconst tests = {\n valid: [{\n code: [\n 'const styles = StyleSheet.create({',\n ' name: {}',\n '});',\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n 'const styles = StyleSheet.create({',\n ' name: {}',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' name: {}',\n '});',\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' name: {},',\n ' welcome: {}',\n '});',\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n 'const Welcome = React.createClass({',\n ' render: function() {',\n ' return Welcome;',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {}',\n '})',\n 'const Hello = React.createClass({',\n ' propTypes: {',\n ' textStyle: Text.propTypes.style,',\n ' },',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {}',\n '})',\n 'const styles2 = StyleSheet.create({',\n ' text: {}',\n '})',\n 'const Hello = React.createClass({',\n ' propTypes: {',\n ' textStyle: Text.propTypes.style,',\n ' },',\n ' render: function() {',\n ' return (',\n ' ',\n ' Hello {this.props.name}',\n ' ',\n ' );',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {}',\n '});',\n 'const Hello = React.createClass({',\n ' getInitialState: function() {',\n ' return { condition: true, condition2: true }; ',\n ' },',\n ' render: function() {',\n ' return (',\n ' ',\n ' Hello {this.props.name}',\n ' ',\n ' );',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {},',\n ' text2: {},',\n '});',\n 'const Hello = React.createClass({',\n ' getInitialState: function() {',\n ' return { condition: true }; ',\n ' },',\n ' render: function() {',\n ' return (',\n ' ',\n ' Hello {this.props.name}',\n ' ',\n ' );',\n ' }',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' style1: {',\n ' color: \\'red\\',',\n ' },',\n ' style2: {',\n ' color: \\'blue\\',',\n ' }',\n '});',\n 'export default class MyComponent extends Component {',\n ' static propTypes = {',\n ' isDanger: PropTypes.bool',\n ' };',\n ' render() {',\n ' return ;',\n ' }',\n '}',\n ].join('\\n'),\n }, {\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {}',\n '})',\n ].join('\\n'),\n }, {\n code: [\n 'const Hello = React.createClass({',\n ' getInitialState: function() {',\n ' return { condition: true }; ',\n ' },',\n ' render: function() {',\n ' const myStyle = this.state.condition ? styles.text : styles.text2;',\n ' return (',\n ' ',\n ' Hello {this.props.name}',\n ' ',\n ' );',\n ' }',\n '});',\n 'const styles = StyleSheet.create({',\n ' text: {},',\n ' text2: {},',\n '});',\n ].join('\\n'),\n }, {\n code: [\n 'const additionalStyles = {};',\n 'const styles = StyleSheet.create({',\n ' name: {},',\n ' ...additionalStyles',\n '});',\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n ].join('\\n'),\n }],\n\n invalid: [{\n code: [\n 'const styles = StyleSheet.create({',\n ' text: {}',\n '})',\n 'const Hello = React.createClass({',\n ' render: function() {',\n ' return Hello {this.props.name};',\n ' }',\n '});',\n ].join('\\n'),\n errors: [{\n message: 'Unused style detected: styles.text',\n }],\n }],\n};\n\nconst config = {\n parser: 'babel-eslint',\n parserOptions: {\n ecmaFeatures: {\n classes: true,\n jsx: true,\n },\n },\n};\n\ntests.valid.forEach(t => Object.assign(t, config));\ntests.invalid.forEach(t => Object.assign(t, config));\n\nruleTester.run('split-platform-components', rule, tests);\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.232e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -6314,32 +6314,23 @@\n un('\n-split-platform-component\n+no-unused-style\n s', \n"}}},{"rowIdx":2597367,"cells":{"commit":{"kind":"string","value":"ded1e02da7a42aaa5ea0a4414d9ebac7d986995f"},"subject":{"kind":"string","value":"move buildHelpers require down a slot"},"old_file":{"kind":"string","value":"packages/build-runtime.js"},"new_file":{"kind":"string","value":"packages/build-runtime.js"},"old_contents":{"kind":"string","value":"\"use strict\";\n\nvar buildHelpers = require(\"../lib/babel/build-helpers\");\nvar transform = require(\"../lib/babel/transformation\");\nvar util = require(\"../lib/babel/util\");\nvar fs = require(\"fs\");\nvar t = require(\"../lib/babel/types\");\nvar _ = require(\"lodash\");\n\nvar relative = function (filename) {\n return __dirname + \"/babel-runtime/\" + filename;\n};\n\nvar writeFile = function (filename, content) {\n filename = relative(filename);\n console.log(filename);\n fs.writeFileSync(filename, content);\n};\n\nvar readFile = function (filename, defaultify) {\n var file = fs.readFileSync(require.resolve(filename), \"utf8\");\n\n if (defaultify) {\n file += '\\nmodule.exports = { \"default\": module.exports, __esModule: true };\\n';\n }\n\n return file;\n};\n\nvar updatePackage = function () {\n var pkgLoc = relative(\"package.json\");\n var pkg = require(pkgLoc);\n\n var mainPkg = require(\"../package.json\");\n pkg.version = mainPkg.version;\n\n writeFile(\"package.json\", JSON.stringify(pkg, null, 2));\n};\n\nvar selfContainify = function (code) {\n return transform(code, {\n optional: [\"selfContained\"]\n }).code;\n};\n\nvar buildHelpers2 = function () {\n var body = util.template(\"self-contained-helpers-head\");\n var tree = t.program(body);\n\n buildHelpers(body, t.identifier(\"helpers\"));\n\n return transform.fromAst(tree, null, {\n optional: [\"selfContained\"]\n }).code;\n};\n\nwriteFile(\"helpers.js\", buildHelpers2());\nwriteFile(\"core-js.js\", readFile(\"core-js/library\", true));\nwriteFile(\"regenerator/index.js\", readFile(\"regenerator-babel/runtime-module\", true));\nwriteFile(\"regenerator/runtime.js\", selfContainify(readFile(\"regenerator-babel/runtime\")));\nupdatePackage();\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.893e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -12,28 +12,28 @@\n %22;%0A%0Avar \n-buildHelpers\n+transform \n = requi\n@@ -53,41 +53,42 @@\n bel/\n-build-helpers%22);%0Avar transform \n+transformation%22);%0Avar buildHelpers\n = r\n@@ -104,38 +104,37 @@\n ./lib/babel/\n-transformation\n+build-helpers\n %22);%0Avar util\n"}}},{"rowIdx":2597368,"cells":{"commit":{"kind":"string","value":"62a0f429264c4d63006e455690d02496674d3a2f"},"subject":{"kind":"string","value":"Fix chart symbol"},"old_file":{"kind":"string","value":"src/botPage/view/blockly/blocks/trade/index.js"},"new_file":{"kind":"string","value":"src/botPage/view/blockly/blocks/trade/index.js"},"old_contents":{"kind":"string","value":"import { observer as globalObserver } from 'binary-common-utils/lib/observer';\nimport { translate } from '../../../../../common/i18n';\nimport config from '../../../../common/const';\nimport { setBlockTextColor, findTopParentBlock, deleteBlockIfExists } from '../../utils';\nimport { defineContract } from '../images';\nimport { updatePurchaseChoices } from '../shared';\nimport { marketDefPlaceHolders } from './tools';\nimport backwardCompatibility from './backwardCompatibility';\nimport tradeOptions from './tradeOptions';\n\nconst bcMoveAboveInitializationsDown = block => {\n Blockly.Events.recordUndo = false;\n Blockly.Events.setGroup('BackwardCompatibility');\n const parent = block.getParent();\n if (parent) {\n const initializations = block.getInput('INITIALIZATION').connection;\n const ancestor = findTopParentBlock(parent);\n parent.nextConnection.disconnect();\n initializations.connect((ancestor || parent).previousConnection);\n }\n block.setPreviousStatement(false);\n Blockly.Events.setGroup(false);\n Blockly.Events.recordUndo = true;\n};\n\nconst decorateTrade = ev => {\n const trade = Blockly.mainWorkspace.getBlockById(ev.blockId);\n if (!trade || trade.type !== 'trade') {\n return;\n }\n if ([Blockly.Events.CHANGE, Blockly.Events.MOVE, Blockly.Events.CREATE].includes(ev.type)) {\n const symbol = trade.getFieldValue('SYMBOL_LIST');\n const submarket = trade.getInput('SUBMARKET').connection.targetConnection;\n // eslint-disable-next-line no-underscore-dangle\n const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions';\n\n if (symbol && !needsMutation) {\n globalObserver.emit('bot.init', symbol);\n }\n const type = trade.getFieldValue('TRADETYPE_LIST');\n if (type) {\n const oppositesName = type.toUpperCase();\n const contractType = trade.getFieldValue('TYPE_LIST');\n if (oppositesName && contractType) {\n updatePurchaseChoices(contractType, oppositesName);\n }\n }\n }\n};\n\nconst replaceInitializationBlocks = (trade, ev) => {\n if (ev.type === Blockly.Events.CREATE) {\n ev.ids.forEach(blockId => {\n const block = Blockly.mainWorkspace.getBlockById(blockId);\n\n if (block && block.type === 'trade' && !deleteBlockIfExists(block)) {\n bcMoveAboveInitializationsDown(block);\n }\n });\n }\n};\n\nconst resetTradeFields = (trade, ev) => {\n if (ev.blockId === trade.id) {\n if (ev.element === 'field') {\n if (ev.name === 'MARKET_LIST') {\n trade.setFieldValue('', 'SUBMARKET_LIST');\n }\n if (ev.name === 'SUBMARKET_LIST') {\n trade.setFieldValue('', 'SYMBOL_LIST');\n }\n if (ev.name === 'SYMBOL_LIST') {\n trade.setFieldValue('', 'TRADETYPECAT_LIST');\n }\n if (ev.name === 'TRADETYPECAT_LIST') {\n trade.setFieldValue('', 'TRADETYPE_LIST');\n }\n if (ev.name === 'TRADETYPE_LIST') {\n if (ev.newValue) {\n trade.setFieldValue('both', 'TYPE_LIST');\n } else {\n trade.setFieldValue('', 'TYPE_LIST');\n }\n }\n }\n }\n};\n\nBlockly.Blocks.trade = {\n init: function init() {\n this.appendDummyInput()\n .appendField(new Blockly.FieldImage(defineContract, 15, 15, 'T'))\n .appendField(translate('(1) Define your trade contract'));\n marketDefPlaceHolders(this);\n this.appendStatementInput('INITIALIZATION').setCheck(null).appendField(`${translate('Run Once at Start')}:`);\n this.appendStatementInput('SUBMARKET').setCheck(null).appendField(`${translate('Define Trade Options')}:`);\n this.setPreviousStatement(true, null);\n this.setColour('#2a3052');\n this.setTooltip(\n translate('Define your trade contract and start the trade, add initializations here. (Runs on start)')\n );\n this.setHelpUrl('https://github.com/binary-com/binary-bot/wiki');\n },\n onchange: function onchange(ev) {\n setBlockTextColor(this);\n if (ev.group !== 'BackwardCompatibility') {\n replaceInitializationBlocks(this, ev);\n resetTradeFields(this, ev);\n }\n decorateTrade(ev);\n },\n};\n\nBlockly.JavaScript.trade = block => {\n const account = $('.account-id').first().attr('value');\n if (!account) {\n throw Error('Please login');\n }\n const initialization = Blockly.JavaScript.statementToCode(block, 'INITIALIZATION');\n const tradeOptionsStatement = Blockly.JavaScript.statementToCode(block, 'SUBMARKET');\n const candleIntervalValue = block.getFieldValue('CANDLEINTERVAL_LIST');\n const contractTypeSelector = block.getFieldValue('TYPE_LIST');\n const oppositesName = block.getFieldValue('TRADETYPE_LIST').toUpperCase();\n const contractTypeList =\n contractTypeSelector === 'both'\n ? config.opposites[oppositesName].map(k => Object.keys(k)[0])\n : [contractTypeSelector];\n const timeMachineEnabled = block.getFieldValue('TIME_MACHINE_ENABLED') === 'TRUE';\n const shouldRestartOnError = block.getFieldValue('RESTARTONERROR') === 'TRUE';\n const code = `\n init = function init() {\n Bot.init('${account}', {\n symbol: '${block.getFieldValue('SYMBOL_LIST')}',\n contractTypes: ${JSON.stringify(contractTypeList)},\n candleInterval: '${candleIntervalValue}',\n shouldRestartOnError: ${shouldRestartOnError},\n timeMachineEnabled: ${timeMachineEnabled},\n });\n ${initialization.trim()}\n };\n start = function start() {\n ${tradeOptionsStatement.trim()}\n };\n `;\n return code;\n};\n\nexport default () => {\n backwardCompatibility();\n tradeOptions();\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000016279,"string":"0.000002"},"diff":{"kind":"string","value":"@@ -1405,239 +1405,8 @@\n T');\n-%0A const submarket = trade.getInput('SUBMARKET').connection.targetConnection;%0A // eslint-disable-next-line no-underscore-dangle%0A const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions';\n %0A%0A \n@@ -1425,26 +1425,8 @@\n mbol\n- && !needsMutation\n ) %7B%0A\n"}}},{"rowIdx":2597369,"cells":{"commit":{"kind":"string","value":"4982d4029e48a8d89f70ba01a9fc69b959f212fc"},"subject":{"kind":"string","value":"Fix #8"},"old_file":{"kind":"string","value":"WebContent/static/games/Tanks/displayScript.js"},"new_file":{"kind":"string","value":"WebContent/static/games/Tanks/displayScript.js"},"old_contents":{"kind":"string","value":"/**\n * The display script for Tanks. This code displays sprites in a grid based canvas.\n */\n\nvar images = {};\nvar idList = null;\n\n//Called on page load\nfunction onLoad(gameID) {\n\tdisplayMessage(\"Loading Sprites\");\n\tlet sprites = {\n\t\tbullet: \"../static/games/Tanks/bullet.png\", \n\t};\n\t\n\tloadSprites(sprites, gameID);\n}\n\nfunction loadSprites(sprites, gameID) {\n\tlet numImages = 0;\n\t// get num of sources\n\tfor(name in sprites) {\n\t\tnumImages++;\n\t}\n\n\tfor(name in sprites) {\n\t\timages[name] = new Image();\n\t\timages[name].onload = function() {\n\t\t\tif(--numImages <= 0) {\n\t\t\t\tconnectWebSocket(gameID);\n\t\t\t}\n\t\t};\n\t\t\n\t\timages[name].src = sprites[name];\n\t}\n}\n\n/*\n * 4: Player ID list\n * 0: Bulk update\n * 1: Delta update\n * \n * 2: Update game table\n * 3: Update player table\n */\nfunction onMessage(message) {\n\tlet dataView = new DataView(message.data);\n\tlet header = dataView.getUint8(0);\n\t\n\tswitch(header) {\n\tcase 1: //delta\n\t\thandleDeltaData(dataView);\n\t\tbreak;\n\tcase 0: //bulk\n\t\thandleBulkData(dataView);\n\t\tbreak;\n\tcase 2:\n\t\tupdateGameTable();\n\t\tbreak;\n\tcase 4:\n\t\tupdateIDMap(dataView);\n\t\tbreak;\n\tcase 3:\n\t\tupdatePlayerList();\n\tdefault:\n\t\tcanvasError();\n\t}\n}\n\nfunction updateIDMap(dataView) {\n\tidList = [];\n\tlet length = dataView.getUint8(1);\n\t\n\tfor(index = 0; index < length; index++) {\n\t\tlet id = dataView.getUint32(index * 4 + 2).toString();\n\t\tidList.push(id);\n\t\t\n\t\tif(id == \"0\") {\n\t\t\timages[id] = null;\n\t\t} else {\n\t\t\timages[id] = new Image();\n\t\t\timages[id].src = \"/playericon/\" + id;\n\t\t}\n\t}\n}\n\nfunction handleBulkData(dataView) {\n\tcanvas.clearRect(0, 0, pixelSize, pixelSize);\n\t\n\twidth = dataView.getUint8(1);\n\t\n\theight = dataView.getUint8(2);\n\t\n\tfor(y = 0; y < height; y++) {\n\t\tfor(x = 0; x < width; x++) {\n\t\t\tlet c = dataView.getUint16(3 + (x + y * width) * 2);\n\t\t\tpaintItem(x, y, c);\n\t\t}\n\t}\n}\n\nfunction paintItem(x, y, c) {\n\tswitch(c) {\n\tcase 0: //space\n\t\tclear(x, y);\n\t\tbreak;\n\tcase 1: //wall\n\t\twall(x, y);\n\t\tbreak;\n\tcase 2: //bullet\n\t\tshot(x, y);\n\t\tbreak;\n\tdefault:\n\t\ttank(x, y, c - 3);\n\t}\n}\n\nfunction handleDeltaData(dataView) {\n\tlet offset = 1;\n\t\n\twhile(offset <= dataView.byteLength - 4) {\n\t\tlet c = dataView.getUint16(offset);\n\t\tlet x = dataView.getUint8(offset + 2);\n\t\tlet y = dataView.getUint8(offset + 3);\n\t\t\n\t\tpaintItem(x, y, c);\n\t\t\n\t\toffset = offset + 4;\n\t}\n}\n\nfunction tank(x, y, index) {\n\tif(idList == null)\n\t\treturn;\n\t\n\tif(idList.length <= index) {\n\t\treturn; //we haven't been sent that ID yet\n\t}\n\t\n\tlet image = images[idList[index]];\n\t\n\tif(image != null && image.complete) {\n\t\tcanvas.drawImage(image, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height);\n\t}\n}\n\nfunction wall(x, y) {\n\tcanvas.fillStyle = 'black';\n\tcanvas.fillRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height);\n}\n\t\nfunction clear(x, y) {\n\tcanvas.clearRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height);\n}\n\nfunction shot(x, y) {\n\tclear(x, y);\n\t\n\tcanvas.drawImage(images.bullet, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height);\n}\n\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":8.166e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -2290,16 +2290,32 @@\n ndex) %7B%0A\n+%09clear(x, y);%0A%09%0A\n %09if(idLi\n"}}},{"rowIdx":2597370,"cells":{"commit":{"kind":"string","value":"1f4875527d1e2f9a0f3812eca958ece9377595d4"},"subject":{"kind":"string","value":"Change language on counts block from Events to Performances."},"old_file":{"kind":"string","value":"imports/api/counts/server/publications.js"},"new_file":{"kind":"string","value":"imports/api/counts/server/publications.js"},"old_contents":{"kind":"string","value":"/* eslint-disable prefer-arrow-callback */\nimport { Meteor } from 'meteor/meteor';\nimport { TAPi18n } from 'meteor/tap:i18n';\nimport { _ } from 'meteor/underscore';\n\n// API\nimport { Counts } from '../../counts/counts.js';\nimport { Profiles } from '../../profiles/profiles.js';\nimport { Shows } from '../../shows/shows.js';\nimport { Events } from '../../events/events.js';\n\nMeteor.publish('counts.collections', function countsCollections() {\n const self = this;\n let countTheatremakers = 0;\n let countOrganizations = 0;\n let countShows = 0;\n let countEvents = 0;\n let countLocations = 0;\n let initializing = true;\n // observeChanges only returns after the initial `added` callbacks\n // have run. Until then, we don't want to send a lot of\n // `self.changed()` messages - hence tracking the\n // `initializing` state.\n const handleTheatremakers = Profiles.find({\"profileType\": \"Individual\"}).observeChanges({\n added: function() {\n countTheatremakers++;\n if (!initializing) {\n self.changed('Counts', 'Theatremakers', { count: countTheatremakers });\n }\n },\n removed: function() {\n countTheatremakers--;\n self.changed('Counts', 'Theatremakers', { count: countTheatremakers });\n },\n // don't care about changed\n });\n const handleOrganizations = Profiles.find({\"profileType\": \"Organization\"}).observeChanges({\n added: function() {\n countOrganizations++;\n if (!initializing) {\n self.changed('Counts', 'Organizations', { count: countOrganizations });\n }\n },\n removed: function() {\n countOrganizations--;\n self.changed('Counts', 'Organizations', { count: countOrganizations });\n },\n // don't care about changed\n });\n const handleShows = Shows.find({}).observeChanges({\n added: function() {\n countShows++;\n if (!initializing) {\n self.changed('Counts', 'Shows', { count: countShows });\n }\n },\n removed: function() {\n countShows--;\n self.changed('Counts', 'Shows', { count: countShows });\n },\n // don't care about changed\n });\n const handleEvents = Events.find({}).observeChanges({\n added: function() {\n countEvents++;\n if (!initializing) {\n self.changed('Counts', 'Events', { count: countEvents });\n }\n },\n removed: function() {\n countEvents--;\n self.changed('Counts', 'Events', { count: countEvents });\n },\n // don't care about changed\n });\n const handleEventLocations = Events.find({\"lat\": { $gt: \"\"}}).observeChanges({\n added: function() {\n countLocations++;\n if (!initializing) {\n self.changed('Counts', 'Locations', { count: countLocations });\n }\n },\n removed: function() {\n countLocations--;\n self.changed('Counts', 'Locations', { count: countLocations });\n },\n // don't care about changed\n });\n const handleProfileLocations = Profiles.find({\"lat\": { $gt: \"\"}}).observeChanges({\n added: function() {\n countLocations++;\n if (!initializing) {\n self.changed('Counts', 'Locations', { count: countLocations });\n }\n },\n removed: function() {\n countLocations--;\n self.changed('Counts', 'Locations', { count: countLocations });\n },\n // don't care about changed\n });\n // Instead, we'll send one `self.added()` message right after\n // observeChanges has returned, and mark the subscription as\n // ready.\n initializing = false;\n self.added('Counts', 'Theatremakers', { count: countTheatremakers });\n self.added('Counts', 'Organizations', { count: countOrganizations });\n self.added('Counts', 'Shows', { count: countShows });\n self.added('Counts', 'Events', { count: countEvents });\n self.added('Counts', 'Locations', { count: countLocations });\n self.ready();\n // Stop observing the cursor when client unsubs.\n // Stopping a subscription automatically takes\n // care of sending the client any removed messages.\n self.onStop(() => {\n handleTheatremakers.stop();\n handleOrganizations.stop();\n handleShows.stop();\n handleEvents.stop();\n handleEventLocations.stop();\n handleProfileLocations.stop();\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.057e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -2216,37 +2216,43 @@\n nged('Counts', '\n-Event\n+Performance\n s', %7B count: cou\n@@ -2348,37 +2348,43 @@\n nged('Counts', '\n-Event\n+Performance\n s', %7B count: cou\n@@ -3648,21 +3648,27 @@\n unts', '\n-Event\n+Performance\n s', %7B co\n"}}},{"rowIdx":2597371,"cells":{"commit":{"kind":"string","value":"cb9bc30842fdededbb25f7e627e8f3f84eb151a4"},"subject":{"kind":"string","value":"Fix failing test"},"old_file":{"kind":"string","value":"tests/pages/jobs/JobsOverview-cy.js"},"new_file":{"kind":"string","value":"tests/pages/jobs/JobsOverview-cy.js"},"old_contents":{"kind":"string","value":"describe('Jobs Overview', function () {\n context('Jobs page loads correctly', function () {\n beforeEach(function () {\n cy.configureCluster({\n mesos: '1-for-each-health',\n nodeHealth: true\n });\n cy.visitUrl({url: '/jobs'});\n });\n\n it('has the right active navigation entry', function () {\n cy.get('.page-header-navigation .tab-item.active')\n .should('to.have.text', 'Jobs');\n });\n\n it('displays empty jobs overview page', function () {\n cy.get('.page-content .panel-content h3')\n .should('to.have.text', 'No Jobs Found');\n });\n });\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.000208734,"string":"0.000209"},"diff":{"kind":"string","value":"@@ -578,12 +578,14 @@\n obs \n-Foun\n+Create\n d');\n"}}},{"rowIdx":2597372,"cells":{"commit":{"kind":"string","value":"8bf416778ad35f9c96c76de2db451fc3924de8f9"},"subject":{"kind":"string","value":"Fix little typo"},"old_file":{"kind":"string","value":"plugins/weather.js"},"new_file":{"kind":"string","value":"plugins/weather.js"},"old_contents":{"kind":"string","value":"/** Created on May 6, 2014\n * author: MrPoxipol\n */\n\nvar http = require('http');\nvar util = require('util');\n// Templates module\nvar Mustache = require('mustache');\n\nvar debug = require('../nibo/debug');\n\nconst COMMAND_NAME = 'weather';\n// pattern for util.format()\nconst API_URL_PATTERN = 'http://api.openweathermap.org/data/2.5/weather?q=%s&lang=eng';\n\nexports.meta = {\n\tname: 'weather',\n\tcommandName: COMMAND_NAME,\n\tdescription: 'Fetches actual weather conditions from openweathermap.org at specific place on the Earth'\n};\n\nfunction kelvinsToCelcius(temperature) {\n\treturn Math.round(temperature - 273.15);\n}\n\nfunction calcWindChill(temperature, windSpeed) {\n\tif (temperature < 10 && (windSpeed / 3.6) >= 1.8) {\n\t\tvar windChill = (13.12 + 0.6215 * temperature - 11.37 * Math.pow(windSpeed, 0.16) + 0.3965 * temperature * Math.pow(windSpeed, 0.16));\n\t\twindChill = Math.round(windChill);\n\t}\n\n\treturn null;\n}\n\nfunction getWeatherFromJson(data) {\n\tvar parsedJson;\n\ttry {\n\t\tparsedJson = JSON.parse(data);\n\t} catch (e) {\n\t\tdebug.debug('JSON parsing error');\n\t\treturn;\n\t}\n\n\tvar weather = {\n\t\tcity: parsedJson.name\n\t};\n\tif (!weather.city) {\n\t\treturn;\n\t}\n\n\tweather.country = parsedJson.sys.country;\n\tweather.temp = kelvinsToCelcius(parsedJson.main.temp);\n\tweather.description = parsedJson.weather[0].description;\n\tweather.windSpeed = parsedJson.wind.speed;\n\tweather.pressure = Math.round(parsedJson.main.pressure);\n\tweather.windChill = calcWindChill(weather.temp, weather.windSpeed);\n\n\tvar pattern;\n\tif (weather.windChill !== null)\n\t\tpattern = '[{{&city}}, {{&country}}]: {{&temp}}°C (felt as {{&windChill}}°C) - {{&description}}, {{&pressure}} hPa';\n\telse\n\t\tpattern = '[{{&city}}, {{&country}}]: {{&temp}}°C - {{&description}}, {{&pressure}} hPa';\n\n\tvar output = Mustache.render(pattern, weather);\n\n\treturn output;\n}\n\nfunction sendResponse(bot, args, message) {\n\tbot.sayToUser(args.channel, args.user.nick, message);\n}\n\nfunction fetchWeather(bot, args) {\n\targs.place = encodeURIComponent(args.place);\n\tvar url = util.format(API_URL_PATTERN, args.place);\n\n\thttp.get(url, function (response) {\n\t\tvar responseParts = [];\n\t\tresponse.setEncoding('utf8');\n\t\tresponse.on('data', function (chunk) {\n\t\t\tresponseParts.push(chunk);\n\t\t});\n\t\tresponse.on('end', function () {\n\t\t\tvar data = responseParts.join('');\n\t\t\tvar message = getWeatherFromJson(data);\n\t\t\tif (message) {\n\t\t\t\tsendResponse(bot, args, message);\n\t\t\t} else {\n\t\t\t\tsendResponse(bot,\n\t\t\t\t\targs,\n\t\t\t\t\tutil.format('[%s] Could not find weather information.', decodeURIComponent(args.place))\n\t\t\t\t);\n\t\t\t}\n\t\t});\n\t}).on('error', function (e) {\n\t\tdebug.error('HTTP ' + e.message);\n\t\tsendResponse(bot, args, '[] Weather is not avaiable at the moment.');\n\t});\n}\n\nexports.onCommand = function (bot, user, channel, command) {\n\tif (command.name !== COMMAND_NAME)\n\t\treturn;\n\n\tif (command.args.length < 1)\n\t\treturn;\n\n\tvar args = {\n\t\tuser: user,\n\t\tchannel: channel,\n\t\tplace: command.args.join(' '),\n\t};\n\tfetchWeather(bot, args);\n};"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.9999680519,"string":"0.999968"},"diff":{"kind":"string","value":"@@ -2660,16 +2660,17 @@\n not avai\n+l\n able at \n"}}},{"rowIdx":2597373,"cells":{"commit":{"kind":"string","value":"f258286c431b46f944ecaffb319bf44b749f04f4"},"subject":{"kind":"string","value":"Fix #149 TextCell should trigger error and high light the text box if the formatter returns undefined"},"old_file":{"kind":"string","value":"src/extensions/text-cell/backgrid-text-cell.js"},"new_file":{"kind":"string","value":"src/extensions/text-cell/backgrid-text-cell.js"},"old_contents":{"kind":"string","value":"/*\n backgrid-text-cell\n http://github.com/wyuenho/backgrid\n\n Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors\n Licensed under the MIT @license.\n*/\n\n(function (window, $, _, Backbone, Backgrid) {\n\n /**\n Renders a form with a text area and a save button in a modal dialog.\n\n @class Backgrid.Extension.TextareaEditor\n @extends Backgrid.CellEditor\n */\n var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({\n\n /** @property */\n tagName: \"div\",\n\n /** @property */\n className: \"modal hide fade\",\n\n /** @property {function(Object, ?Object=): string} template */\n template: _.template('

    <%- column.get(\"label\") %>

    '),\n\n /** @property */\n cols: 80,\n\n /** @property */\n rows: 10,\n\n /** @property */\n events: {\n \"keydown textarea\": \"clearError\",\n \"submit\": \"saveOrCancel\",\n \"hide\": \"saveOrCancel\",\n \"hidden\": \"close\",\n \"shown\": \"focus\"\n },\n\n /**\n @property {Object} modalOptions The options passed to Bootstrap's modal\n plugin.\n */\n modalOptions: {\n backdrop: false\n },\n\n /**\n Renders a modal form dialog with a textarea, submit button and a close button.\n */\n render: function () {\n this.$el.html($(this.template({\n column: this.column,\n cols: this.cols,\n rows: this.rows,\n content: this.formatter.fromRaw(this.model.get(this.column.get(\"name\")))\n })));\n\n this.delegateEvents();\n\n this.$el.modal(this.modalOptions);\n\n return this;\n },\n\n /**\n Event handler. Saves the text in the text area to the model when\n submitting. When cancelling, if the text area is dirty, a confirmation\n dialog will pop up. If the user clicks confirm, the text will be saved to\n the model.\n\n Triggers a Backbone `backgrid:error` event from the model along with the\n model, column and the existing value as the parameters if the value\n cannot be converted.\n\n @param {Event} e\n */\n saveOrCancel: function (e) {\n if (e && e.type == \"submit\") {\n e.preventDefault();\n e.stopPropagation();\n }\n\n var model = this.model;\n var column = this.column;\n var val = this.$el.find(\"textarea\").val();\n var newValue = this.formatter.toRaw(val);\n\n if (_.isUndefined(newValue)) {\n model.trigger(\"backgrid:error\", model, column, val);\n\n if (e) {\n e.preventDefault();\n e.stopPropagation();\n }\n }\n else if (!e || e.type == \"submit\" ||\n (e.type == \"hide\" &&\n newValue !== (this.model.get(this.column.get(\"name\")) || '').replace(/\\r/g, '') &&\n window.confirm(\"Would you like to save your changes?\"))) {\n\n model.set(column.get(\"name\"), newValue);\n this.$el.modal(\"hide\");\n }\n else if (e.type != \"hide\") this.$el.modal(\"hide\");\n },\n\n clearError: _.debounce(function () {\n if (this.formatter.toRaw(this.$el.find(\"textarea\").val())) {\n this.$el.parent().removeClass(\"error\");\n }\n }, 150),\n\n /**\n Triggers a `backgrid:edited` event along with the cell editor as the\n parameter after the modal is hidden.\n\n @param {Event} e\n */\n close: function (e) {\n var model = this.model;\n model.trigger(\"backgrid:edited\", model, this.column,\n new Backgrid.Command(e));\n },\n\n /**\n Focuses the textarea when the modal is shown.\n */\n focus: function () {\n this.$el.find(\"textarea\").focus();\n }\n\n });\n\n /**\n TextCell is a string cell type that renders a form with a text area in a\n modal dialog instead of an input box editor. It is best suited for entering\n a large body of text.\n\n @class Backgrid.Extension.TextCell\n @extends Backgrid.StringCell\n */\n var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({\n\n /** @property */\n className: \"text-cell\",\n\n /** @property */\n editor: TextareaEditor\n\n });\n\n}(window, jQuery, _, Backbone, Backgrid));\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.023e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -3215,24 +3215,90 @@\n %22);%0A %7D,%0A%0A\n+ /**%0A Clears the error class on the parent cell.%0A */%0A\n clearErr\n@@ -3335,16 +3335,31 @@\n if \n+(!_.isUndefined\n (this.fo\n@@ -3405,16 +3405,17 @@\n .val()))\n+)\n %7B%0A \n"}}},{"rowIdx":2597374,"cells":{"commit":{"kind":"string","value":"f9451d9339839e32fab7c6c27e6fcc32dfe75037"},"subject":{"kind":"string","value":"make composition cache work"},"old_file":{"kind":"string","value":"lib/composition.js"},"new_file":{"kind":"string","value":"lib/composition.js"},"old_contents":{"kind":"string","value":"var File = require('./file');\nvar Cache = require('./cache');\nvar Module = require('./module');\nvar utils = require('./client/utils');\n\nvar composition_cache = Cache('compositions');\n\n/**\n * Get module instance composition.\n */\nmodule.exports = function (name, role, callback) {\n \n // get composition from cache\n var composition = composition_cache.get(name);\n switch (composition) {\n \n // handle invalid composition configuration\n case 'INVALID':\n return callback(new Error('Invalid composition \"' + name + '\".'));\n \n // handle cache hit\n case !undefined:\n \n // check access for cached item \n if (!utils.roleAccess(composition, role)) {\n return callback(new Error('Access denied for composition \"' + name + '\"'));\n }\n \n // return if composition is complete\n if (!composition.LOAD) {\n return callback(null, composition);\n }\n }\n \n // read the composition json\n File.json(engine.paths.app_composition + name + '.json', function (err, config) {\n \n // handle error\n if ((err = err || checkComposition(name, role, config))) {\n return callback(err);\n }\n \n // create mandatory package infos to custom module\n if (typeof config.module === 'object') {\n config.module.name = name;\n config.module.version = 'custom';\n config.module._id = name + '@custom';\n module._base = engine.repo;\n }\n \n Module(config.module, function (err, modulePackage) {\n \n // handle module package error\n if (err) {\n return callback(err);\n }\n \n // prepare instance components\n if (config.client && (config.client.styles || config.client.markup)) {\n \n // send module id and module base\n var components = {\n base: modulePackage._base,\n module: modulePackage._id,\n styles: config.client.styles,\n markup: config.client.markup\n };\n \n File.prepare(components, function (err, files) {\n \n // update file paths in module package\n if (files.styles) {\n config.client.styles = files.styles;\n }\n \n if (files.markup) {\n config.client.markup = files.markup;\n }\n \n finish(name, modulePackage, config, callback);\n });\n return;\n }\n \n finish(name, modulePackage, config, callback);\n });\n });\n};\n\nfunction finish (name, modulePackage, config, callback) {\n \n // merge package data into config\n if (modulePackage.composition) {\n config = mergePackage(modulePackage.version, modulePackage.composition, config);\n }\n \n // save composition in cache\n composition_cache.set(name, config);\n \n // return composition config\n callback(null, config);\n}\n\n/**\n * Check composition config. \n */\nfunction checkComposition (name, role, config) {\n \n // handle not found\n if (!config) {\n return new Error('composition \"' + name +'\" not found.');\n }\n \n // check if composition has a module\n if (!config.module) {\n \n // save as invalid in cache\n composition_cache.set(name, 'INVALID');\n return new Error('No module info in composition \"' + name + '\".');\n }\n \n // check access\n if (!utils.roleAccess(config, role)) {\n \n // save access information in cache, to check access without loading the hole file again\n composition_cache.set(name, {roles: config.roles, LOAD: true});\n return new Error('Access denied: Role \"' + role + '\", Composition \"' + name + '\".');\n }\n \n // set composition name as custom module name\n if (typeof config.module === 'object' && !config.module.name) {\n config.module.name = config.name;\n }\n}\n\n/**\n * Merge package config into composition config. \n */\nfunction mergePackage (version, package_instance, config) {\n \n // merge client related options\n if (package_instance.client) {\n \n // ensure client config object\n config.client = config.client || {};\n config.client.name = config.name;\n config.client.version = version;\n \n // set client module scripts\n if (package_instance.client.module) {\n config.client.module = package_instance.client.module;\n }\n \n // config\n if (package_instance.client.config) {\n for (var key in package_instance.client.config) {\n if (typeof config.client.config[key] === 'undefined') {\n config.client.config[key] = package_instance.client.config[key];\n }\n }\n }\n \n // flow\n if (package_instance.client.flow) {\n config.client.flow = (config.client.flow || []).concat(package_instance.client.flow);\n }\n \n // markup\n if (package_instance.client.markup) {\n config.client.markup = (config.client.markup || []).concat(package_instance.client.markup);\n }\n \n // styles\n if (package_instance.client.styles) {\n config.client.styles = (config.client.styles || []).concat(package_instance.client.styles);\n }\n }\n \n // server flow\n if (package_instance.flow) {\n config.flow = (config.flow || []).concat(package_instance.flow);\n }\n \n // merge server config\n if (package_instance.config) {\n for (var prop in package_instance.config) {\n if (typeof config.config[prop] === 'undefined') {\n config.config[prop] = package_instance.config[prop];\n }\n }\n }\n \n return config;\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.232e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -368,14 +368,10 @@\n \n-switch\n+if\n (co\n@@ -383,22 +383,16 @@\n tion) %7B%0A\n- \n %0A \n@@ -396,64 +396,27 @@\n \n-// handle invalid composition configuration%0A case\n+if (composition ===\n 'IN\n@@ -421,17 +421,19 @@\n INVALID'\n-:\n+) %7B\n %0A \n@@ -516,79 +516,11 @@\n \n-%0A // handle cache hit%0A case !undefined:%0A %0A \n+%7D%0A%0A\n \n@@ -554,28 +554,24 @@\n hed item %0A\n- \n if (\n@@ -606,28 +606,24 @@\n n, role)) %7B%0A\n- \n \n@@ -706,39 +706,19 @@\n \n- %7D%0A %0A \n+%7D%0A%0A\n \n@@ -758,28 +758,24 @@\n ete%0A \n- \n- \n if (!composi\n@@ -783,28 +783,24 @@\n ion.LOAD) %7B%0A\n- \n \n@@ -835,20 +835,16 @@\n ition);%0A\n- \n \n@@ -851,18 +851,16 @@\n %7D%0A %7D%0A\n- \n %0A // \n"}}},{"rowIdx":2597375,"cells":{"commit":{"kind":"string","value":"2533551dcd46caa844436ec5f9b1aa83912291c4"},"subject":{"kind":"string","value":"Implement signup email handler and email state * Re-order state object to reflect order of inputs"},"old_file":{"kind":"string","value":"client/mobile/components/shared/signup.js"},"new_file":{"kind":"string","value":"client/mobile/components/shared/signup.js"},"old_contents":{"kind":"string","value":"var React = require('react-native');\nvar Login = require('./login');\nvar JoinClassView = require('./../student/joinClassView');\nvar StartClassView = require('./../teacher/startClassView');\nvar api = require('./../../utils/api');\n\nvar {\n View,\n Text,\n StyleSheet,\n TextInput,\n TouchableHighlight,\n Picker,\n ActivityIndicatorIOS,\n Navigator\n} = React;\n\nclass Signup extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n username: '',\n password: '',\n confirmedPassword: '',\n firstName: '',\n lastName: '',\n accountType: 'student',\n isLoading: false,\n error: false,\n passwordError: false\n };\n }\n\n handleFirstNameChange(event) {\n this.setState({\n firstName: event.nativeEvent.text\n });\n }\n\n handleLastNameChange(event) {\n this.setState({\n lastName: event.nativeEvent.text\n });\n }\n\n handleUsernameChange(event) {\n this.setState({\n username: event.nativeEvent.text\n });\n }\n\n handlePasswordChange(event) {\n this.setState({\n password: event.nativeEvent.text\n });\n }\n\n handleConfirmedPasswordChange(event) {\n this.setState({\n confirmedPassword: event.nativeEvent.text\n });\n }\n\n handleSubmit() {\n if (this.state.password === this.state.confirmedPassword) {\n this.setState({\n isLoading: true,\n passwordError: false\n });\n api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType)\n .then((response) => {\n if(response.status === 500){\n this.setState({\n error: 'User already exists',\n password: '',\n confirmedPassword: '',\n isLoading: false\n });\n } else if(response.status === 200) {\n //keychain stuff?\n var body = JSON.parse(response._bodyText);\n if(body.teacher) {\n this.props.navigator.push({\n component: StartClassView,\n classes: body.teacher.classes,\n userId: body.teacher.uid,\n sceneConfig: {\n ...Navigator.SceneConfigs.FloatFromBottom,\n gestures: {}\n }\n });\n } else if (body.student) {\n this.props.navigator.push({\n component: JoinClassView,\n classes: body.student.classes,\n userId: body.student.uid,\n sceneConfig: {\n ...Navigator.SceneConfigs.FloatFromBottom,\n gestures: {}\n }\n });\n }\n }\n })\n .catch((err) => {\n this.setState({\n error: 'User already exists' + err,\n isLoading: false\n });\n });\n } else {\n this.setState({\n isLoading: false,\n password: '',\n confirmedPassword: '',\n passwordError: 'passwords do not match'\n });\n }\n }\n\n handleRedirect() {\n this.props.navigator.pop();\n }\n\n render() {\n var showErr = (\n this.state.error ? {this.state.error} : \n );\n var showPasswordErr = (\n this.state.passwordError ? {this.state.passwordError} : \n );\n return (\n \n \n Username \n {\n this.refs.SecondInput.focus();\n }} \n />\n Password \n {\n this.refs.ThirdInput.focus();\n }} \n />\n Confirm Password \n \n Account Type \n this.setState({accountType: type})}>\n \n \n \n \n Sign Up \n \n \n Already have an account? Sign in! \n \n \n {showErr}\n {showPasswordErr}\n \n\n \n );\n }\n}\n\nvar styles = StyleSheet.create({\n mainContainer: {\n flex: 1,\n padding: 30,\n flexDirection: 'column',\n justifyContent: 'center',\n },\n fieldTitle: {\n marginTop: 10,\n marginBottom: 15,\n fontSize: 18,\n textAlign: 'center',\n color: '#616161'\n },\n userInput: {\n height: 50,\n padding: 4,\n fontSize: 18,\n borderWidth: 1,\n borderColor: '#616161',\n borderRadius: 4,\n color: '#616161'\n },\n picker: {\n bottom: 70,\n height: 70\n },\n buttonText: {\n fontSize: 18,\n color: 'white',\n alignSelf: 'center'\n },\n button: {\n height: 45,\n flexDirection: 'row',\n backgroundColor: '#FF5A5F',\n borderColor: 'transparent',\n borderWidth: 1,\n borderRadius: 4,\n marginBottom: 10,\n marginTop: 30,\n alignSelf: 'stretch',\n justifyContent: 'center'\n },\n signin: {\n marginTop: 20,\n fontSize: 14,\n textAlign: 'center'\n },\n loading: {\n marginTop: 20\n },\n err: {\n fontSize: 14,\n textAlign: 'center'\n },\n});\n\nmodule.exports = Signup;"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.685e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -453,29 +453,30 @@\n e = %7B%0A \n-usern\n+firstN\n ame: '',%0A \n@@ -474,32 +474,32 @@\n : '',%0A \n-password\n+lastName\n : '',%0A \n@@ -498,33 +498,24 @@\n ,%0A \n-confirmedPassword\n+username\n : '',%0A \n@@ -514,33 +514,29 @@\n : '',%0A \n-firstName\n+email\n : '',%0A \n@@ -531,32 +531,61 @@\n : '',%0A \n-lastName\n+password: '',%0A confirmedPassword\n : '',%0A \n@@ -997,32 +997,130 @@\n xt%0A %7D);%0A %7D%0A%0A\n+ handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A\n handlePassword\n"}}},{"rowIdx":2597376,"cells":{"commit":{"kind":"string","value":"b7a634649f273aff78eef8fda8cf5f1a3075016e"},"subject":{"kind":"string","value":"Implement signup email handler and email state * Re-order state object to reflect order of inputs"},"old_file":{"kind":"string","value":"client/mobile/components/shared/signup.js"},"new_file":{"kind":"string","value":"client/mobile/components/shared/signup.js"},"old_contents":{"kind":"string","value":"var React = require('react-native');\nvar Login = require('./login');\nvar JoinClassView = require('./../student/joinClassView');\nvar StartClassView = require('./../teacher/startClassView');\nvar api = require('./../../utils/api');\n\nvar {\n View,\n Text,\n StyleSheet,\n TextInput,\n TouchableHighlight,\n Picker,\n ActivityIndicatorIOS,\n Navigator\n} = React;\n\nclass Signup extends React.Component {\n constructor(props) {\n super(props);\n this.state = {\n username: '',\n password: '',\n confirmedPassword: '',\n firstName: '',\n lastName: '',\n accountType: 'student',\n isLoading: false,\n error: false,\n passwordError: false\n };\n }\n\n handleFirstNameChange(event) {\n this.setState({\n firstName: event.nativeEvent.text\n });\n }\n\n handleLastNameChange(event) {\n this.setState({\n lastName: event.nativeEvent.text\n });\n }\n\n handleUsernameChange(event) {\n this.setState({\n username: event.nativeEvent.text\n });\n }\n\n handlePasswordChange(event) {\n this.setState({\n password: event.nativeEvent.text\n });\n }\n\n handleConfirmedPasswordChange(event) {\n this.setState({\n confirmedPassword: event.nativeEvent.text\n });\n }\n\n handleSubmit() {\n if (this.state.password === this.state.confirmedPassword) {\n this.setState({\n isLoading: true,\n passwordError: false\n });\n api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType)\n .then((response) => {\n if(response.status === 500){\n this.setState({\n error: 'User already exists',\n password: '',\n confirmedPassword: '',\n isLoading: false\n });\n } else if(response.status === 200) {\n //keychain stuff?\n var body = JSON.parse(response._bodyText);\n if(body.teacher) {\n this.props.navigator.push({\n component: StartClassView,\n classes: body.teacher.classes,\n userId: body.teacher.uid,\n sceneConfig: {\n ...Navigator.SceneConfigs.FloatFromBottom,\n gestures: {}\n }\n });\n } else if (body.student) {\n this.props.navigator.push({\n component: JoinClassView,\n classes: body.student.classes,\n userId: body.student.uid,\n sceneConfig: {\n ...Navigator.SceneConfigs.FloatFromBottom,\n gestures: {}\n }\n });\n }\n }\n })\n .catch((err) => {\n this.setState({\n error: 'User already exists' + err,\n isLoading: false\n });\n });\n } else {\n this.setState({\n isLoading: false,\n password: '',\n confirmedPassword: '',\n passwordError: 'passwords do not match'\n });\n }\n }\n\n handleRedirect() {\n this.props.navigator.pop();\n }\n\n render() {\n var showErr = (\n this.state.error ? {this.state.error} : \n );\n var showPasswordErr = (\n this.state.passwordError ? {this.state.passwordError} : \n );\n return (\n \n \n Username \n {\n this.refs.SecondInput.focus();\n }} \n />\n Password \n {\n this.refs.ThirdInput.focus();\n }} \n />\n Confirm Password \n \n Account Type \n this.setState({accountType: type})}>\n \n \n \n \n Sign Up \n \n \n Already have an account? Sign in! \n \n \n {showErr}\n {showPasswordErr}\n \n\n \n );\n }\n}\n\nvar styles = StyleSheet.create({\n mainContainer: {\n flex: 1,\n padding: 30,\n flexDirection: 'column',\n justifyContent: 'center',\n },\n fieldTitle: {\n marginTop: 10,\n marginBottom: 15,\n fontSize: 18,\n textAlign: 'center',\n color: '#616161'\n },\n userInput: {\n height: 50,\n padding: 4,\n fontSize: 18,\n borderWidth: 1,\n borderColor: '#616161',\n borderRadius: 4,\n color: '#616161'\n },\n picker: {\n bottom: 70,\n height: 70\n },\n buttonText: {\n fontSize: 18,\n color: 'white',\n alignSelf: 'center'\n },\n button: {\n height: 45,\n flexDirection: 'row',\n backgroundColor: '#FF5A5F',\n borderColor: 'transparent',\n borderWidth: 1,\n borderRadius: 4,\n marginBottom: 10,\n marginTop: 30,\n alignSelf: 'stretch',\n justifyContent: 'center'\n },\n signin: {\n marginTop: 20,\n fontSize: 14,\n textAlign: 'center'\n },\n loading: {\n marginTop: 20\n },\n err: {\n fontSize: 14,\n textAlign: 'center'\n },\n});\n\nmodule.exports = Signup;"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.685e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -453,29 +453,30 @@\n e = %7B%0A \n-usern\n+firstN\n ame: '',%0A \n@@ -474,32 +474,32 @@\n : '',%0A \n-password\n+lastName\n : '',%0A \n@@ -498,33 +498,24 @@\n ,%0A \n-confirmedPassword\n+username\n : '',%0A \n@@ -514,33 +514,29 @@\n : '',%0A \n-firstName\n+email\n : '',%0A \n@@ -531,32 +531,61 @@\n : '',%0A \n-lastName\n+password: '',%0A confirmedPassword\n : '',%0A \n@@ -997,32 +997,130 @@\n xt%0A %7D);%0A %7D%0A%0A\n+ handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A\n handlePassword\n"}}},{"rowIdx":2597377,"cells":{"commit":{"kind":"string","value":"93a63d4371249b1d3d8f0c934153804261d6e072"},"subject":{"kind":"string","value":"add promise rejection error reporting"},"old_file":{"kind":"string","value":"client/scripts/arcademode/actions/test.js"},"new_file":{"kind":"string","value":"client/scripts/arcademode/actions/test.js"},"old_contents":{"kind":"string","value":"\n'use strict';\n\nexport const OUTPUT_CHANGED = 'OUTPUT_CHANGED';\nexport const TESTS_STARTED = 'TESTS_STARTED';\nexport const TESTS_FINISHED = 'TESTS_FINISHED';\n\n\nexport function onOutputChange(newOutput) {\n return {\n type: OUTPUT_CHANGED,\n userOutput: newOutput\n };\n}\n\n/* Thunk action which runs the test cases against user code. */\nexport function runTests(userCode, currChallenge) {\n return dispatch => {\n dispatch(actionTestsStarted());\n\n // Eval user code inside worker\n // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766\n function createWorker () {\n return new Promise((resolve, reject) => {\n const wk = new Worker('../../public/js/worker.bundle.js');\n wk.postMessage([userCode, currChallenge.toJS()]); // postMessage mangles the Immutable object, so it needs to be transformed into regular JS before sending over to worker.\n wk.onmessage = e => {\n // console.log(`worker onmessage result: ${e.data}`);\n resolve(e.data);\n };\n });\n }\n\n return createWorker()\n .then(workerData => {\n dispatch(onOutputChange(workerData[0].output));\n if (workerData.length > 1) {\n dispatch(actionTestsFinished(workerData.slice(1)));\n }\n });\n };\n}\n\n/* Dispatched when a user starts running the tests.*/\nexport function actionTestsStarted () {\n return {\n type: TESTS_STARTED\n };\n}\n\n/* Dispatched when the tests finish. */\nexport function actionTestsFinished (testResults) {\n return {\n type: TESTS_FINISHED,\n testResults\n };\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.727e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -610,16 +610,17 @@\n 6255766%0A\n+%0A\n func\n@@ -1309,24 +1309,91 @@\n %7D%0A %7D)\n+%0A .catch(err =%3E %7B console.log(%60Promise rejected: $%7Berr%7D.%60); %7D)\n ;%0A %7D;%0A%7D%0A%0A/*\n"}}},{"rowIdx":2597378,"cells":{"commit":{"kind":"string","value":"31e94b683dbe349bd19c1c0d9f279b0b6c2f46e5"},"subject":{"kind":"string","value":"Update to new redis port to reduce potential collisions"},"old_file":{"kind":"string","value":"lib/core/config.js"},"new_file":{"kind":"string","value":"lib/core/config.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nvar path = require('path');\nvar fs = require('fs');\nvar env = require('./env.js');\nvar deps = require('./deps.js');\n\n// Constants\nvar CONFIG_FILENAME = 'kalabox.json';\nexports.CONFIG_FILENAME = CONFIG_FILENAME;\n\nvar DEFAULT_GLOBAL_CONFIG = {\n domain: 'kbox',\n kboxRoot: ':home:/kalabox',\n kalaboxRoot: ':kboxRoot:',\n appsRoot: ':kboxRoot:/apps',\n sysConfRoot: ':home:/.kalabox',\n globalPluginRoot: ':kboxRoot:/plugins',\n globalPlugins: [\n 'hipache',\n 'kalabox_core',\n 'kalabox_install',\n 'kalabox_app',\n 'kalabox_b2d'\n ],\n redis: {\n // @todo: Dynamically set this.\n host: '1.3.3.7',\n port: 6379\n },\n // @this needs to be set dynamically once we merge in config.js\n dockerHost: '1.3.3.7',\n startupServicePrefix: 'kalabox_',\n startupServices: {\n kalaboxDebian: {\n name: 'kalabox/debian',\n containers : {\n kalaboxSkydns: {\n name: 'kalabox/skydns',\n createOpts : {\n name: 'skydns',\n HostConfig : {\n NetworkMode: 'bridge',\n PortBindings: {\n '53/udp' : [{'HostIp' : '172.17.42.1', 'HostPort' : '53'}],\n }\n }\n },\n startOpts : {}\n },\n kalaboxSkydock: {\n name: 'kalabox/skydock',\n createOpts : {\n name: 'skydock',\n HostConfig : {\n NetworkMode: 'bridge',\n Binds : ['/var/run/docker.sock:/docker.sock', '/skydock.js:/skydock.js']\n }\n },\n startOpts : {}\n },\n kalaboxHipache: {\n name: 'kalabox/hipache',\n createOpts : {\n name: 'hipache',\n HostConfig : {\n NetworkMode: 'bridge',\n PortBindings: {\n '80/tcp' : [{'HostIp' : '', 'HostPort' : '80'}],\n '6379/tcp' : [{'HostIp' : '', 'HostPort' : '6379'}],\n }\n }\n },\n startOpts : {}\n },\n kalaboxDnsmasq: {\n name: 'kalabox/dnsmasq',\n createOpts : {\n name: 'dnsmasq',\n Env: ['KALABOX_IP=1.3.3.7'],\n ExposedPorts: {\n '53/tcp': {},\n '53/udp': {}\n },\n HostConfig : {\n NetworkMode: 'bridge',\n PortBindings: {\n '53/udp' : [{'HostIp' : '1.3.3.7', 'HostPort' : '53'}]\n }\n }\n },\n startOpts : {}\n }\n }\n }\n }\n};\n\n// @todo: implement\n//var KEYS_TO_CONCAT = {};\n\nfunction normalizeValue(key, config) {\n var rawValue = config[key];\n if (typeof rawValue === 'string') {\n var params = rawValue.match(/:[a-zA-Z0-9-_]*:/g);\n if (params !== null) {\n for (var index in params) {\n var param = params[index];\n var paramKey = param.substr(1, param.length - 2);\n var paramValue = config[paramKey];\n if (paramValue !== undefined) {\n config[key] = rawValue.replace(param, paramValue);\n }\n }\n }\n }\n}\nexports.normalizeValue = normalizeValue;\n\nfunction normalize(config) {\n for (var key in config) {\n normalizeValue(key, config);\n }\n return config;\n}\nexports.normalize = normalize;\n\nfunction mixIn(a, b/*, keysToConcat*/) {\n /*if (!keysToConcat) {\n keysToConcat = KEYS_TO_CONCAT;\n }*/\n for (var key in b) {\n //var shouldConcat = keysToConcat[key] !== undefined;\n var shouldConcat = false;\n if (shouldConcat) {\n // Concat.\n if (a[key] === undefined) {\n a[key] = b[key];\n } else {\n a[key] = a[key].concat(b[key]);\n }\n } else {\n // Override.\n a[key] = b[key];\n }\n }\n return normalize(a);\n}\nexports.mixIn = mixIn;\n\nexports.getEnvConfig = function() {\n return {\n home: env.getHomeDir(),\n srcRoot: env.getSourceRoot()\n };\n};\n\nexports.getDefaultConfig = function() {\n return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG);\n};\n\nvar getGlobalConfigFilepath = function() {\n return path.join(env.getKalaboxRoot(), CONFIG_FILENAME);\n};\n\nvar loadConfigFile = function(configFilepath) {\n return require(configFilepath);\n};\n\nexports.getGlobalConfig = function() {\n var defaultConfig = this.getDefaultConfig();\n var globalConfigFilepath = getGlobalConfigFilepath();\n if (fs.existsSync(globalConfigFilepath)) {\n var globalConfigFile = loadConfigFile(globalConfigFilepath);\n return mixIn(defaultConfig, globalConfigFile);\n } else {\n return defaultConfig;\n }\n};\n\nexports.getAppConfigFilepath = function(app, config) {\n return path.join(config.appsRoot, app.name, CONFIG_FILENAME);\n};\n\nexports.getAppConfig = function(app) {\n var globalConfig = this.getGlobalConfig();\n var appRoot = path.join(globalConfig.appsRoot, app.name);\n var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME);\n var appConfigFile = require(appConfigFilepath);\n appConfigFile.appRoot = appRoot;\n appConfigFile.appCidsRoot = ':appRoot:/.cids';\n return mixIn(globalConfig, appConfigFile);\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.259e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -631,20 +631,20 @@\n port: \n-6379\n+8160\n %0A %7D,%0A \n@@ -1842,20 +1842,20 @@\n '\n-6379\n+8160\n /tcp' : \n@@ -1889,12 +1889,12 @@\n : '\n-6379\n+8160\n '%7D%5D,\n"}}},{"rowIdx":2597379,"cells":{"commit":{"kind":"string","value":"2fd85899d20ad2d15555c6975f16e095dfc348f3"},"subject":{"kind":"string","value":"add exception handling for cloudflare error."},"old_file":{"kind":"string","value":"lib/courier/jnt.js"},"new_file":{"kind":"string","value":"lib/courier/jnt.js"},"old_contents":{"kind":"string","value":"'use strict'\n\nvar request = require('request')\nvar moment = require('moment')\n\nvar tracker = require('../')\n\nvar trackingInfo = function (number) {\n return {\n method: 'POST',\n url: 'https://www.jtexpress.ph/index/router/index.html',\n json: true,\n body: {\n method: 'app.findTrack',\n data: {\n billcode: number,\n lang: 'en',\n source: 3\n }\n }\n }\n}\n\nvar parser = {\n trace: function (data) {\n var courier = {\n code: tracker.COURIER.JNT.CODE,\n name: tracker.COURIER.JNT.NAME\n }\n var result = {\n courier: courier,\n number: data.billcode,\n status: tracker.STATUS.PENDING\n }\n\n var checkpoints = []\n for (var i = 0; i < data.details.length; i++) {\n var item = data.details[i]\n var message = [\n item.desc\n ].join(' - ')\n var checkpoint = {\n courier: courier,\n location: item.city || item.siteName,\n message: message,\n status: tracker.STATUS.IN_TRANSIT,\n time: moment(item.scantime + 'T+0800', 'YYYY-MM-DD HH:mm:ssZ').utc().format('YYYY-MM-DDTHH:mmZ')\n }\n if (item.scantype === 'Delivered') {\n checkpoint.status = tracker.STATUS.DELIVERED\n }\n checkpoints.push(checkpoint)\n }\n\n result.checkpoints = checkpoints\n result.status = tracker.normalizeStatus(result.checkpoints)\n\n return result\n }\n}\n\nmodule.exports = function () {\n return {\n trackingInfo: trackingInfo,\n trace: function (number, cb) {\n var tracking = trackingInfo(number)\n\n request(tracking, function (err, res, body) {\n if (err) {\n return cb(err)\n }\n\n try {\n var result = parser.trace(JSON.parse(body.data))\n cb(result ? null : tracker.error(tracker.ERROR.INVALID_NUMBER), result)\n } catch (e) {\n cb(tracker.error(e.message))\n }\n })\n }\n }\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.24e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1645,16 +1645,124 @@\n try %7B%0A\n+ if (res.statusCode !== 200) %7B%0A return cb(tracker.error(res.statusMessage))%0A %7D%0A\n \n"}}},{"rowIdx":2597380,"cells":{"commit":{"kind":"string","value":"3d5f46d4917d6eadf46a8e1d772ff7f9f410a29e"},"subject":{"kind":"string","value":"Prepare new Info to be in modal"},"old_file":{"kind":"string","value":"client/src/components/shared/Info/Info.js"},"new_file":{"kind":"string","value":"client/src/components/shared/Info/Info.js"},"old_contents":{"kind":"string","value":"// @flow\nimport React, {Fragment} from 'react'\nimport Circle from 'react-icons/lib/fa/circle-o'\nimport {Container} from 'reactstrap'\nimport {Link} from 'react-router-dom'\nimport type {Node} from 'react'\n\nimport {\n getNewFinancialData,\n icoUrl,\n ShowNumberCurrency,\n showDate,\n} from '../../../services/utilities'\nimport {compose, withHandlers} from 'recompose'\nimport {connect} from 'react-redux'\nimport {zoomToLocation} from '../../../actions/verejneActions'\nimport {ENTITY_CLOSE_ZOOM} from '../../../constants'\nimport Contracts from './Contracts'\nimport Notices from './Notices'\nimport Eurofunds from './Eurofunds'\nimport Relations from './Relations'\nimport Trend from './Trend'\nimport ExternalLink from '../ExternalLink'\nimport mapIcon from '../../../assets/mapIcon.svg'\nimport type {NewEntityDetail} from '../../../state'\nimport type {FinancialData} from '../../../services/utilities'\nimport './Info.css'\n\ntype InfoProps = {\n data: NewEntityDetail,\n canClose?: boolean,\n onClose?: () => void,\n}\n\ntype ItemProps = {\n children?: Node,\n label?: string,\n url?: string,\n linkText?: Node,\n}\n\nconst Item = ({children, label, url, linkText}: ItemProps) => (\n
  • \n {label && {label}}\n {url && (\n \n {linkText}\n \n )}\n {children}\n
  • \n)\n\nconst Findata = ({data}: {data: FinancialData}) => {\n const finances = data.finances[0] || {} // possible feature: display finances also for older years\n return (\n \n \n &nbsp;(\n Detaily o firme\n )\n \n {data.established_on && {showDate(data.established_on)}}\n {data.terminated_on && {showDate(data.terminated_on)}}\n {finances.employees && (\n {finances.employees}\n )}\n {finances.profit ? (\n }\n >\n {finances.profitTrend ? : null}\n \n ) : null}\n {finances.revenue ? (\n }\n >\n {finances.revenueTrend ? : null}\n \n ) : null}\n \n )\n}\n\nconst Info = ({data, canClose, onClose, showOnMap}: InfoProps) => (\n \n
    \n

    \n &nbsp;{data.name}&nbsp;\n

    \n \n \"MapMarker\"\n \n {canClose && (\n \n &times;\n \n )}\n
    \n
    \n
      \n {data.address}\n {data.companyinfo && }\n {data.contracts &&\n data.contracts.price_amount_sum > 0 && (\n }\n />\n )}\n
    \n {data.contracts && data.contracts.count > 0 && }\n {data.notices && data.notices.count > 0 && }\n {data.eufunds && data.eufunds.eufunds_count > 0 && }\n {data.related.length > 0 && }\n
    \n
    \n)\n\nexport default compose(\n connect(null, {zoomToLocation}),\n withHandlers({\n showOnMap: ({data, zoomToLocation}) => () => {\n data.toggleModalOpen && data.toggleModalOpen()\n zoomToLocation(data, ENTITY_CLOSE_ZOOM)\n },\n })\n)(Info)\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.285e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -416,16 +416,33 @@\n Location\n+, toggleModalOpen\n %7D from '\n@@ -968,16 +968,37 @@\n Detail,%0A\n+ inModal?: boolean,%0A\n canClo\n@@ -4535,16 +4535,33 @@\n Location\n+, toggleModalOpen\n %7D),%0A wi\n@@ -4595,16 +4595,25 @@\n (%7Bdata,\n+ inModal,\n zoomToL\n@@ -4619,16 +4619,33 @@\n Location\n+, toggleModalOpen\n %7D) =%3E ()\n@@ -4660,37 +4660,19 @@\n \n-data.toggleModalOpen && data.\n+inModal && \n togg\n"}}},{"rowIdx":2597381,"cells":{"commit":{"kind":"string","value":"138ad3b71603f2f1ce7a05954c2e065b41d339cb"},"subject":{"kind":"string","value":"Update to ES6 syntax"},"old_file":{"kind":"string","value":"client/webpack.production.config.babel.js"},"new_file":{"kind":"string","value":"client/webpack.production.config.babel.js"},"old_contents":{"kind":"string","value":"/* global module, __dirname */\nimport path from \"path\";\nimport webpack from \"webpack\";\nimport HTMLPlugin from \"html-webpack-plugin\";\nimport CleanPlugin from \"clean-webpack-plugin\";\nimport ExtractTextPlugin from \"extract-text-webpack-plugin\";\nimport UglifyJSPlugin from \"uglifyjs-webpack-plugin\";\n\nmodule.exports = {\n\n entry: [\"babel-polyfill\", \"./src/js/index.js\"],\n\n module: {\n rules: [\n {\n test: /\\.js$/,\n exclude: /(node_modules)/,\n use: [\n \"babel-loader\",\n {\n loader: \"eslint-loader\",\n options: {\n configFile: path.resolve(__dirname, \"./.eslintrc\")\n }\n\n }\n ]\n },\n\n {\n test: /\\.css$/,\n use: ExtractTextPlugin.extract({\n fallback: \"style-loader\",\n use: \"css-loader\"\n })\n },\n\n {\n test: /\\.less$/,\n use: ExtractTextPlugin.extract({\n fallback: \"style-loader\",\n use: [\n {loader: \"css-loader\"},\n {loader: \"less-loader\"}\n ]\n })\n },\n\n {\n test: /\\.woff$/,\n use: {\n loader: \"url-loader?limit=100000\"\n }\n }\n ]\n },\n\n node: {\n fs: \"empty\"\n },\n\n mode: \"production\",\n\n output: {\n path: path.resolve(__dirname, \"./dist\"),\n filename: \"app.[hash:8].js\",\n sourceMapFilename: \"[name].js.map\",\n publicPath: \"/static/\"\n },\n\n plugins: [\n new webpack.DefinePlugin({\n \"process.env.NODE_ENV\": JSON.stringify(\"production\")\n }),\n\n new ExtractTextPlugin(\"style.[hash:8].css\"),\n\n new HTMLPlugin({\n filename: \"index.html\",\n title: \"Virtool\",\n favicon: \"./src/images/favicon.ico\",\n template: \"./src/index.html\",\n inject: \"body\"\n }),\n\n new CleanPlugin([\"dist\"], {\n verbose: true\n }),\n\n new UglifyJSPlugin({\n sourceMap: true\n })\n ]\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.933e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -6,16 +6,8 @@\n obal\n- module,\n __d\n@@ -286,24 +286,22 @@\n %22;%0A%0A\n-module.exports =\n+export default\n %7B%0A%0A\n"}}},{"rowIdx":2597382,"cells":{"commit":{"kind":"string","value":"37d3d04f0ec20f4145fcb9d90b805e706e948a41"},"subject":{"kind":"string","value":"Clean mediatag integration code"},"old_file":{"kind":"string","value":"www/common/diffMarked.js"},"new_file":{"kind":"string","value":"www/common/diffMarked.js"},"old_contents":{"kind":"string","value":"define([\n 'jquery',\n '/bower_components/marked/marked.min.js',\n '/common/cryptpad-common.js',\n '/common/media-tag.js',\n '/bower_components/diff-dom/diffDOM.js',\n '/bower_components/tweetnacl/nacl-fast.min.js',\n],function ($, Marked, Cryptpad, MediaTag) {\n var DiffMd = {};\n\n var DiffDOM = window.diffDOM;\n var renderer = new Marked.Renderer();\n\n Marked.setOptions({\n renderer: renderer\n });\n\n DiffMd.render = function (md) {\n return Marked(md);\n };\n\n // Tasks list\n var checkedTaskItemPtn = /^\\s*\\[x\\]\\s*/;\n var uncheckedTaskItemPtn = /^\\s*\\[ \\]\\s*/;\n renderer.listitem = function (text) {\n var isCheckedTaskItem = checkedTaskItemPtn.test(text);\n var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text);\n if (isCheckedTaskItem) {\n text = text.replace(checkedTaskItemPtn,\n '&nbsp;') + '\\n';\n }\n if (isUncheckedTaskItem) {\n text = text.replace(uncheckedTaskItemPtn,\n '&nbsp;') + '\\n';\n }\n var cls = (isCheckedTaskItem || isUncheckedTaskItem) ? ' class=\"todo-list-item\"' : '';\n return '' + text + '\\n';\n };\n renderer.image = function (href, title, text) {\n if (href.slice(0,6) === '/file/') {\n var parsed = Cryptpad.parsePadUrl(href);\n var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel);\n var mt = '';\n return mt;\n }\n var out = '\"'' : '>';\n return out;\n };\n\n var forbiddenTags = [\n 'SCRIPT',\n 'IFRAME',\n 'OBJECT',\n 'APPLET',\n 'VIDEO',\n 'AUDIO',\n ];\n var unsafeTag = function (info) {\n if (info.node && $(info.node).parents('media-tag').length) {\n // Do not remove elements inside a media-tag\n return true;\n }\n if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) {\n if (/^on/.test(info.diff.name)) {\n console.log(\"Rejecting forbidden element attribute with name\", info.diff.name);\n return true;\n }\n }\n if (['addElement', 'replaceElement'].indexOf(info.diff.action) !== -1) {\n var msg = \"Rejecting forbidden tag of type (%s)\";\n if (info.diff.element && forbiddenTags.indexOf(info.diff.element.nodeName) !== -1) {\n console.log(msg, info.diff.element.nodeName);\n return true;\n } else if (info.diff.newValue && forbiddenTags.indexOf(info.diff.newValue.nodeName) !== -1) {\n console.log(\"Replacing restricted element type (%s) with PRE\", info.diff.newValue.nodeName);\n info.diff.newValue.nodeName = 'PRE';\n }\n }\n };\n\n var getSubMediaTag = function (element) {\n var result = [];\n console.log(element);\n if (element.nodeName === \"MEDIA-TAG\") {\n result.push(element);\n return result;\n }\n if (element.childNodes) {\n element.childNodes.forEach(function (el) {\n result = result.concat(getSubMediaTag(el, result));\n });\n }\n console.log(result);\n return result;\n };\n var mediaTag = function (info) {\n if (info.diff.action === 'addElement') {\n return getSubMediaTag(info.diff.element);\n //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);\n //MediaTag($mt[0]);\n }\n return;\n };\n\n var slice = function (coll) {\n return Array.prototype.slice.call(coll);\n };\n\n /* remove listeners from the DOM */\n var removeListeners = function (root) {\n slice(root.attributes).map(function (attr) {\n if (/^on/.test(attr.name)) {\n root.attributes.removeNamedItem(attr.name);\n }\n });\n // all the way down\n slice(root.children).forEach(removeListeners);\n };\n\n var domFromHTML = function (html) {\n var Dom = new DOMParser().parseFromString(html, \"text/html\");\n removeListeners(Dom.body);\n return Dom;\n };\n\n //var toTransform = [];\n var DD = new DiffDOM({\n preDiffApply: function (info) {\n if (unsafeTag(info)) { return true; }\n },\n });\n\n var makeDiff = function (A, B, id) {\n var Err;\n var Els = [A, B].map(function (frag) {\n if (typeof(frag) === 'object') {\n if (!frag || (frag && !frag.body)) {\n Err = \"No body\";\n return;\n }\n var els = frag.body.querySelectorAll('#'+id);\n if (els.length) {\n return els[0];\n }\n }\n Err = 'No candidate found';\n });\n if (Err) { return Err; }\n var patch = DD.diff(Els[0], Els[1]);\n return patch;\n };\n\n DiffMd.apply = function (newHtml, $content) {\n var id = $content.attr('id');\n if (!id) { throw new Error(\"The element must have a valid id\"); }\n var $div = $('
    ', {id: id}).append(newHtml);\n var Dom = domFromHTML($('
    ').append($div).html());\n var oldDom = domFromHTML($content[0].outerHTML);\n var patch = makeDiff(oldDom, Dom, id);\n if (typeof(patch) === 'string') {\n throw new Error(patch);\n } else {\n DD.apply($content[0], patch);\n var $mts = $content.find('media-tag:not(:has(*))');\n $mts.each(function (i, el) {\n MediaTag(el);\n });\n }\n };\n\n $(window.document).on('decryption', function (e) {\n var decrypted = e.originalEvent;\n if (decrypted.callback) { decrypted.callback(); }\n });\n\n return DiffMd;\n});\n\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.051e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -3189,752 +3189,8 @@\n %7D;%0A%0A\n- var getSubMediaTag = function (element) %7B%0A var result = %5B%5D;%0A console.log(element);%0A if (element.nodeName === %22MEDIA-TAG%22) %7B%0A result.push(element);%0A return result;%0A %7D%0A if (element.childNodes) %7B%0A element.childNodes.forEach(function (el) %7B%0A result = result.concat(getSubMediaTag(el, result));%0A %7D);%0A %7D%0A console.log(result);%0A return result;%0A %7D;%0A var mediaTag = function (info) %7B%0A if (info.diff.action === 'addElement') %7B%0A return getSubMediaTag(info.diff.element);%0A //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);%0A //MediaTag($mt%5B0%5D);%0A %7D%0A return;%0A %7D;%0A\n %0A \n@@ -3810,36 +3810,8 @@\n %7D;%0A%0A\n- //var toTransform = %5B%5D;%0A\n \n"}}},{"rowIdx":2597383,"cells":{"commit":{"kind":"string","value":"7b2b3e9dfbf805da61b1e957e71bdd3bad0352dc"},"subject":{"kind":"string","value":"Fix typo"},"old_file":{"kind":"string","value":"server/lib/client-info.js"},"new_file":{"kind":"string","value":"server/lib/client-info.js"},"old_contents":{"kind":"string","value":"/**\n * Client info keyed on client id. Mainly used for logging.\n * Getting full details about a client is a multi-part process\n * since we get partial info when they request a token, and more\n * when they finally connect/authenticate over the web socket.\n */\nvar useragent = require('useragent');\nvar log = require('./logger.js');\n\nfunction ClientInfo(id, userAgentString) {\n this.id = id;\n\n // User isn't yet known, we'll update this in update() later\n this.username = 'unauthenticated';\n\n // Try to extract useful browser/device info\n try {\n var agent = useragent.parse(userAgentString);\n this.agent = agent.toString();\n this.device = agent.device.toString();\n } catch(err) {\n log.error({err: err}, 'Error parsing user agent string: `%s`', userAgentString);\n this.agent = \"Unknown\";\n this.device = \"Unknown\";\n }\n\n this.born = Date.now();\n\n // How many times this client has sync'ed during this connection.\n this.downstreamSyncs = 0;\n this.upstreamSyncs = 0;\n\n // Web Socket data usage for this client\n this.bytesSent = 0;\n this.bytesRecevied = 0;\n}\n\n// How long this client has been connected in MS\nClientInfo.prototype.connectedInMS = function() {\n return Date.now() - this.born;\n};\n\n/**\n * Keep track of client info objects while they are still connected.\n */\nvar clients = {};\n\nfunction remove(id) {\n delete clients[id];\n}\n\nfunction find(client) {\n return clients[client.id];\n}\n\n/**\n * Step 1: create a partial ClientInfo object when the client requests a token\n */\nfunction init(id, userAgentString) {\n clients[id] = new ClientInfo(id, userAgentString);\n}\n\n/**\n * Step 2: update the ClientInfo object with all the client info when\n * web socket connection is completed.\n */\nfunction update(client) {\n var id = client.id;\n\n // Auto-remove when this client is closed.\n client.once('closed', function() {\n remove(id);\n });\n\n var info = find(client);\n if(!info) {\n log.warn('No ClientInfo object found for client.id=%s', id);\n return;\n }\n info.username = client.username;\n}\n\nmodule.exports = {\n init: init,\n update: update,\n remove: remove,\n find: find\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.9999992847,"string":"0.999999"},"diff":{"kind":"string","value":"@@ -1064,18 +1064,18 @@\n ytesRece\n-v\n i\n+v\n ed = 0;%0A\n"}}},{"rowIdx":2597384,"cells":{"commit":{"kind":"string","value":"205dba7e0e4a828ae27a4b08af3c67186e162a7a"},"subject":{"kind":"string","value":"Improve variable names"},"old_file":{"kind":"string","value":"server/lib/userSession.js"},"new_file":{"kind":"string","value":"server/lib/userSession.js"},"old_contents":{"kind":"string","value":"//\n// Copyright 2014 Ilkka Oksanen \n//\n// Licensed under the Apache License, Version 2.0 (the \"License\");\n// you may not use this file except in compliance with the License.\n// You may obtain a copy of the License at\n//\n// http://www.apache.org/licenses/LICENSE-2.0\n//\n// Unless required by applicable law or agreed to in writing,\n// software distributed under the License is distributed on an \"AS\n// IS\" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either\n// express or implied. See the License for the specific language\n// governing permissions and limitations under the License.\n//\n\n'use strict';\n\nconst user = require('../models/user');\n\nexports.auth = function *auth(next) {\n const cookie = this.cookies.get('auth') || '';\n const ts = new Date();\n\n this.mas = this.mas || {};\n this.mas.user = null;\n\n const [ userId, secret ] = cookie.split('-');\n\n if (userId && secret) {\n const userRecord = yield user.fetch(parseInt(userId));\n\n if (userRecord && userRecord.get('secretExpires') > ts &&\n userRecord.get('secret') === secret) {\n this.mas.user = userRecord;\n }\n }\n\n yield next;\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.9987466335,"string":"0.998747"},"diff":{"kind":"string","value":"@@ -643,17 +643,17 @@\n %0A%0Aconst \n-u\n+U\n ser = re\n@@ -950,22 +950,16 @@\n nst user\n-Record\n = yield\n@@ -959,17 +959,17 @@\n = yield \n-u\n+U\n ser.fetc\n@@ -1010,22 +1010,16 @@\n user\n-Record\n && user\n Reco\n@@ -1010,30 +1010,24 @@\n user && user\n-Record\n .get('secret\n@@ -1047,31 +1047,13 @@\n s &&\n-%0A userRecord\n+ user\n .get\n@@ -1113,14 +1113,8 @@\n user\n-Record\n ;%0A \n"}}},{"rowIdx":2597385,"cells":{"commit":{"kind":"string","value":"55be56e6a4d27d717954a93e4043a04705ad06af"},"subject":{"kind":"string","value":"use https for transifex download"},"old_file":{"kind":"string","value":"tools/downloadLanguages.js"},"new_file":{"kind":"string","value":"tools/downloadLanguages.js"},"old_contents":{"kind":"string","value":"/* This Source Code Form is subject to the terms of the Mozilla Public\n * License, v. 2.0. If a copy of the MPL was not distributed with this file,\n * You can obtain one at http://mozilla.org/MPL/2.0/. */\n\n/*\n Environment Variables\n\n USERNAME - valid Transifex user name with read privileges\n PASSWORD - password for above username\n\n LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US)\n*/\n\n'use strict'\n\nconst path = require('path')\nconst fs = require('fs')\nconst request = require('request')\n\n// The names of the directories in the locales folder are used as a list of languages to retrieve\nvar languages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')).filter(function (language) {\n return language !== 'en-US'\n}).map(function (language) {\n return language.replace('-', '_')\n})\n\n// Support retrieving a single language\nif (process.env.LANG_CODE) {\n languages = [process.env.LANG_CODE]\n}\n\nif (process.env.META) {\n var localLanguages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales'))\n console.log(` `)\n console.log(localLanguages.map(function (l) {\n return `'${l}'`\n }).join(',\\n '))\n process.exit(0)\n}\n\n// Setup the credentials\nconst username = process.env.USERNAME\nconst password = process.env.PASSWORD\nif (!(username && password)) {\n throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials')\n}\n\n// URI and resource list\nconst TEMPLATE = 'http://www.transifex.com/api/2/project/brave-laptop/resource/RESOURCE_SLUG/translation/LANG_CODE/?file'\n\n// Retrieve resource names dynamically\nvar resources = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', 'en-US')).map(function (language) {\n return language.split(/\\./)[0]\n})\n\n// For each language / resource combination\nlanguages.forEach(function (languageCode) {\n resources.forEach(function (resource) {\n // Build the URI\n var URI = TEMPLATE.replace('RESOURCE_SLUG', resource + 'properties')\n URI = URI.replace('LANG_CODE', languageCode)\n\n // Authorize and request the translation file\n request.get(URI, {\n 'auth': {\n 'user': username,\n 'pass': password,\n 'sendImmediately': true\n }\n }, function (error, response, body) {\n if (error) {\n // Report errors (often timeouts)\n console.log(error.toString())\n } else {\n if (response.statusCode === 401) {\n throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?')\n }\n // Check to see if the directory exists, if not create it\n var directory = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'))\n if (!fs.existsSync(directory)) {\n console.log(`${languageCode} does not exist - creating directory`)\n if (!process.env.TEST) {\n fs.mkdirSync(directory)\n } else {\n console.log(`${languageCode} would have been created`)\n }\n } else {\n // Directory exists - continue\n }\n\n // Build the filename and store the translation file\n var filename = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'), resource + '.properties')\n console.log('[*] ' + filename)\n if (process.env.TEST) {\n console.log(body)\n } else {\n fs.writeFileSync(filename, body)\n }\n }\n })\n })\n})\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.578e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1594,16 +1594,17 @@\n = 'http\n+s\n ://www.t\n"}}},{"rowIdx":2597386,"cells":{"commit":{"kind":"string","value":"d6ae29f4d18462b2b150fba0e12d3b42960fca20"},"subject":{"kind":"string","value":"Test cases for default code version"},"old_file":{"kind":"string","value":"tests/unit/services/rollbar-test.js"},"new_file":{"kind":"string","value":"tests/unit/services/rollbar-test.js"},"old_contents":{"kind":"string","value":"import { moduleFor, test } from 'ember-qunit';\nimport Ember from 'ember';\nimport Rollbar from 'rollbar';\n\nmoduleFor('service:rollbar', 'Unit | Service | rollbar', {\n needs: ['config:environment']\n});\n\ntest('it exists', function(assert) {\n let service = this.subject();\n assert.ok(service);\n});\n\ntest('notifier', function(assert) {\n let service = this.subject();\n assert.ok(service.get('notifier') instanceof Rollbar);\n});\n\ntest('critical', function(assert) {\n let service = this.subject();\n let uuid = service.critical('My error message').uuid;\n assert.ok(uuid);\n});\n\ntest('error', function(assert) {\n let service = this.subject();\n let uuid = service.error('My error message').uuid;\n assert.ok(uuid);\n});\n\ntest('warning', function(assert) {\n let service = this.subject();\n let uuid = service.warning('My error message').uuid;\n assert.ok(uuid);\n});\n\ntest('info', function(assert) {\n let service = this.subject();\n let uuid = service.info('My error message').uuid;\n assert.ok(uuid);\n});\n\ntest('debug', function(assert) {\n let service = this.subject();\n let uuid = service.debug('My error message').uuid;\n assert.ok(uuid);\n});\n\ntest('registerLogger: register error handler for Ember errors if enabled', function(assert) {\n assert.expect(2);\n let service = this.subject({\n config: {\n enabled: true\n },\n error(message) {\n assert.ok(true, 'error handler is called');\n assert.equal(message, 'foo', 'error is passed to error handler as argument');\n }\n });\n service.registerLogger();\n Ember.onerror('foo');\n});\n\ntest('registerLogger: does not override previous hook', function(assert) {\n assert.expect(4);\n let service = this.subject({\n config: {\n enabled: true\n },\n error(message) {\n assert.ok(true, 'rollbar error handler is called');\n assert.equal(message, 'foo', 'error is passed to rollbar error handler as argument');\n }\n });\n Ember.onerror = function(message) {\n assert.ok(true, 'previous hook is called');\n assert.equal(message, 'foo', 'error is passed to previous hook as argument');\n };\n service.registerLogger();\n Ember.onerror('foo');\n});\n\ntest('registerLogger: does not register logger if disabled', function(assert) {\n assert.expect(1);\n let service = this.subject({\n config: {\n enabled: false\n },\n error() {\n assert.notOk(true);\n }\n });\n Ember.onerror = function() {\n assert.ok(true);\n };\n service.registerLogger();\n Ember.onerror();\n})\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.491e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1131,32 +1131,520 @@\n .ok(uuid);%0A%7D);%0A%0A\n+test('config with default value for code version', function(assert) %7B%0A let service = this.subject();%0A let currentVersion = Ember.getOwner(this).resolveRegistration('config:environment').APP.version%0A assert.equal(service.get('config').code_version, currentVersion);%0A%7D);%0A%0Atest('config custom value for code version', function(assert) %7B%0A let service = this.subject(%7B%0A config: %7B%0A code_version: '1.2.3'%0A %7D%0A %7D);%0A assert.equal(service.get('config').code_version, '1.2.3');%0A%7D);%0A%0A\n test('registerLo\n"}}},{"rowIdx":2597387,"cells":{"commit":{"kind":"string","value":"8ceb8c074327ecd4be630018c7643f84e26f1b08"},"subject":{"kind":"string","value":"Include the extra secrets.js."},"old_file":{"kind":"string","value":"server/config/secrets.js"},"new_file":{"kind":"string","value":"server/config/secrets.js"},"old_contents":{"kind":"string","value":""},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":1.147e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -0,0 +1,362 @@\n+/** Important **/%0A/** You should not be committing this file to GitHub **/%0A%0Amodule.exports = %7B%0A // Find the appropriate database to connect to, default to localhost if not found.%0A db: process.env.MONGOHQ_URL %7C%7C process.env.MONGOLAB_URI %7C%7C 'mongodb://localhost/ReactWebpackNode',%0A sessionSecret: process.env.SESSION_SECRET %7C%7C 'Your Session Secret goes here'%0A%7D;\n"}}},{"rowIdx":2597388,"cells":{"commit":{"kind":"string","value":"ede80b3f5a07d3cc11ba94f9ea40e52e0bb3a8a1"},"subject":{"kind":"string","value":"add endGame method in game menu"},"old_file":{"kind":"string","value":"src/common/directives/diGameMenu/diGameMenu.js"},"new_file":{"kind":"string","value":"src/common/directives/diGameMenu/diGameMenu.js"},"old_contents":{"kind":"string","value":"/**\n* directive.diGameMenu Module\n*\n* Description\n*/\nangular.module('directive.diGameMenu', [\n 'service.GameManager'\n])\n.controller('GameMenuCtrl', [\n '$scope',\n 'GameManager',\nfunction (\n $scope,\n GameManager\n){\n $scope.continueGame = function continueGame() {\n GameManager.setPause();\n $scope.closeModal();\n return this;\n };\n\n $scope.restartGame = function restartGame() {\n GameManager.newGame();\n $scope.closeModal();\n GameManager.setGameStart();\n return this;\n };\n\n this.isPause = function isPause() {\n return GameManager.isPause();\n };\n\n this.isGameStart = function isGameStart() {\n return GameManager.isGameStart();\n };\n}])\n.directive('diGameMenu', [\nfunction(\n){\n var GameMenu = {};\n\n GameMenu.controller = 'GameMenuCtrl';\n \n GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html';\n\n GameMenu.restrict = 'A';\n\n GameMenu.replace = true;\n\n GameMenu.scope = true;\n\n GameMenu.link = function link(scope, element, attrs, controller) {\n scope.$on('app.pause', function() {\n if (!controller.isPause() && controller.isGameStart()) {\n $(element).modal({\n backdrop: 'static'\n });\n } else {\n scope.closeModal(); \n }\n });\n\n scope.closeModal = function closeModal() {\n $(element).modal('hide');\n };\n\n };\n\n return GameMenu;\n}]);"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.122e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -334,37 +334,16 @@\n odal();%0A\n- return this;%0A\n %7D;%0A%0A\n@@ -496,23 +496,113 @@\n \n- return this\n+%7D;%0A%0A $scope.endGame = function endGame() %7B%0A GameManager.gameOver();%0A $scope.closeModal()\n ;%0A \n"}}},{"rowIdx":2597389,"cells":{"commit":{"kind":"string","value":"0313147b8cc69c0eb8fe76642922be9b121eadcd"},"subject":{"kind":"string","value":"Fix closure loader path in legacy example"},"old_file":{"kind":"string","value":"examples/legacy-closure-lib/webpack.config.js"},"new_file":{"kind":"string","value":"examples/legacy-closure-lib/webpack.config.js"},"old_contents":{"kind":"string","value":"var HtmlWebpackPlugin = require('html-webpack-plugin'),\n webpack = require('webpack'),\n pathUtil = require('path');\n\nmodule.exports = {\n entry: {\n app: './src/app.js',\n },\n output: {\n path: './build',\n filename: '[name].js',\n },\n resolve: {\n modulesDirectories: ['node_modules'],\n root: [\n __dirname,\n ],\n alias: {\n 'npm': __dirname + '/node_modules',\n }\n },\n resolveLoader: {\n root: pathUtil.join(__dirname, 'node_modules'),\n },\n module: {\n loaders: [\n {\n test: /google-closure-library\\/closure\\/goog\\/base/,\n loaders: [\n 'imports?this=>{goog:{}}&goog=>this.goog',\n 'exports?goog',\n ],\n },\n // Loader for closure library\n {\n test: /google-closure-library\\/closure\\/goog\\/.*\\.js/,\n loaders: [\n require.resolve('../../index'),\n ],\n exclude: [/base\\.js$/],\n },\n // Loader for project js files\n {\n test: /\\/src\\/.*\\.js/,\n loaders: [\n 'closure',\n ],\n exclude: [/node_modules/, /test/],\n },\n ],\n },\n plugins: [\n // This will copy the index.html to the build directory and insert script tags\n new HtmlWebpackPlugin({\n template: 'src/index.html',\n }),\n new webpack.ProvidePlugin({\n goog: 'google-closure-library/closure/goog/base',\n }),\n ],\n closureLoader: {\n paths: [\n __dirname + '/node_modules/google-closure-library/closure/goog',\n ],\n es6mode: false,\n watch: false,\n },\n devServer: {\n contentBase: './build',\n noInfo: true,\n inline: true,\n historyApiFallback: true,\n },\n devtool: 'source-map',\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":2.816e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -1241,17 +1241,38 @@\n \n-'closure'\n+require.resolve('../../index')\n ,%0A \n"}}},{"rowIdx":2597390,"cells":{"commit":{"kind":"string","value":"70f855f1a8accf94641c71e48e8544676085fa20"},"subject":{"kind":"string","value":"Rewrite LogoutButton to hooks"},"old_file":{"kind":"string","value":"src/components/SettingsManager/LogoutButton.js"},"new_file":{"kind":"string","value":"src/components/SettingsManager/LogoutButton.js"},"old_contents":{"kind":"string","value":"import React from 'react';\nimport PropTypes from 'prop-types';\nimport { translate } from '@u-wave/react-translate';\nimport Button from '@mui/material/Button';\nimport LogoutIcon from '@mui/icons-material/PowerSettingsNew';\nimport ConfirmDialog from '../Dialogs/ConfirmDialog';\nimport FormGroup from '../Form/Group';\n\nconst enhance = translate();\n\nclass LogoutButton extends React.Component {\n static propTypes = {\n t: PropTypes.func.isRequired,\n onLogout: PropTypes.func.isRequired,\n };\n\n constructor(props) {\n super(props);\n this.state = {\n showDialog: false,\n };\n }\n\n handleOpen = () => {\n this.setState({ showDialog: true });\n };\n\n handleClose = () => {\n this.closeDialog();\n };\n\n handleConfirm = () => {\n const { onLogout } = this.props;\n\n onLogout();\n this.closeDialog();\n };\n\n closeDialog() {\n this.setState({ showDialog: false });\n }\n\n render() {\n const { t } = this.props;\n const { showDialog } = this.state;\n\n return (\n <>\n \n {showDialog && (\n \n {t('dialogs.logout.confirm')}\n \n )}\n \n );\n }\n}\n\nexport default enhance(LogoutButton);\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.133e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -65,25 +65,29 @@\n mport %7B \n-t\n+useT\n ranslat\n-e\n+or\n %7D from \n@@ -323,279 +323,165 @@\n nst \n-enhance = translate();%0A%0Aclass LogoutButton extends React.Component %7B%0A static propTypes = %7B%0A t: PropTypes.func.isRequired,%0A onLogout: PropTypes.func.isRequired,%0A %7D;%0A%0A constructor(props) %7B%0A super(props);%0A this.state = %7B%0A showDialog: false,%0A %7D;%0A %7D%0A%0A \n+%7B useState %7D = React;%0A%0Afunction LogoutButton(%7B onLogout %7D) %7B%0A const %7B t %7D = useTranslator();%0A const %5BshowDialog, setShowDialog%5D = useState(false);%0A%0A const\n han\n@@ -502,33 +502,20 @@\n %3E %7B%0A \n-this.setState(%7B s\n+setS\n howDialo\n@@ -519,16 +519,13 @@\n alog\n-: \n+(\n true\n- %7D\n );%0A \n@@ -527,24 +527,30 @@\n e);%0A %7D;%0A%0A \n+const \n handleClose \n@@ -563,33 +563,35 @@\n %3E %7B%0A \n-this.close\n+setShow\n Dialog(\n+false\n );%0A %7D;%0A\n@@ -593,16 +593,22 @@\n %7D;%0A%0A \n+const \n handleCo\n@@ -631,127 +631,28 @@\n \n-const %7B onLogout %7D = this.props;%0A%0A onLogout();%0A this.closeDialog();%0A %7D;%0A%0A closeDialog() %7B%0A this.setState(%7B s\n+onLogout();%0A setS\n howD\n@@ -660,110 +660,23 @@\n alog\n-: \n+(\n false\n- %7D\n );%0A %7D\n+;\n %0A%0A\n- render() %7B%0A const %7B t %7D = this.props;%0A const %7B showDialog %7D = this.state;%0A%0A \n re\n@@ -686,18 +686,16 @@\n n (%0A \n- \n %3C%3E%0A \n@@ -695,18 +695,16 @@\n %3E%0A \n- \n- \n %3CButton \n@@ -753,21 +753,16 @@\n nClick=%7B\n-this.\n handleOp\n@@ -766,18 +766,16 @@\n eOpen%7D%3E%0A\n- \n \n@@ -827,18 +827,16 @@\n \n- \n- \n %7Bt('sett\n@@ -856,18 +856,16 @@\n %7D%0A \n- \n %3C/Button\n@@ -866,18 +866,16 @@\n Button%3E%0A\n- \n %7Bs\n@@ -897,18 +897,16 @@\n \n- \n %3CConfirm\n@@ -922,18 +922,16 @@\n \n- \n title=%22%22\n@@ -941,18 +941,16 @@\n \n- \n- \n confirmL\n@@ -993,18 +993,16 @@\n \n- \n onConfir\n@@ -1004,21 +1004,16 @@\n onfirm=%7B\n-this.\n handleCo\n@@ -1029,18 +1029,16 @@\n \n- \n- \n onCancel\n@@ -1043,13 +1043,8 @@\n el=%7B\n-this.\n hand\n@@ -1064,14 +1064,10 @@\n \n- %3E%0A \n+%3E%0A\n \n@@ -1133,18 +1133,16 @@\n \n- \n %3C/Confir\n@@ -1160,15 +1160,11 @@\n \n- \n )%7D%0A\n- \n \n@@ -1173,18 +1173,82 @@\n %3E%0A \n- );%0A %7D\n+);%0A%7D%0A%0ALogoutButton.propTypes = %7B%0A onLogout: PropTypes.func.isRequired,\n %0A%7D\n+;\n %0A%0Aex\n@@ -1264,16 +1264,8 @@\n ult \n-enhance(\n Logo\n@@ -1272,11 +1272,10 @@\n utButton\n-)\n ;%0A\n"}}},{"rowIdx":2597391,"cells":{"commit":{"kind":"string","value":"89ab12e6324f4d6fc32280f244bb91cea81482dd"},"subject":{"kind":"string","value":"Use correct path in examples when using handlers nested in subdirs"},"old_file":{"kind":"string","value":"examples/serverless-offline/webpack.config.js"},"new_file":{"kind":"string","value":"examples/serverless-offline/webpack.config.js"},"old_contents":{"kind":"string","value":"const path = require('path');\nconst nodeExternals = require('webpack-node-externals');\n\nmodule.exports = {\n entry: './src/handler.js',\n target: 'node',\n externals: [nodeExternals()],\n module: {\n loaders: [{\n test: /\\.js$/,\n loaders: ['babel-loader'],\n include: __dirname,\n exclude: /node_modules/,\n }],\n },\n output: {\n libraryTarget: 'commonjs',\n path: path.join(__dirname, '.webpack'),\n filename: 'handler.js'\n },\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":4.867e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -433,16 +433,20 @@\n ename: '\n+src/\n handler.\n"}}},{"rowIdx":2597392,"cells":{"commit":{"kind":"string","value":"cde39cdfb33867d32c9b9b8e4b19a27592ff00e8"},"subject":{"kind":"string","value":"Stop ending the test twice\\!"},"old_file":{"kind":"string","value":"features-support/step_definitions/features.js"},"new_file":{"kind":"string","value":"features-support/step_definitions/features.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nvar should = require('should');\nvar By = require('selenium-webdriver').By;\n\n// Test helper.\nfunction getProjectFromUrl(callback) {\n var world = this;\n var projectRetrievalUrl = 'http://localhost:' + world.appPort + '/?repo_url=' + encodeURIComponent(world.repoUrl);\n\n world.browser.get(projectRetrievalUrl)\n .then(world.browser.getPageSource.bind(world.browser))\n .then(function (body) {\n world.body = body;\n callback();\n });\n}\n\n// The returned function is passed as a callback to getProjectFromUrl.\nfunction getScenarioFromProject(callback, world) {\n return function(error) {\n if (error) {\n callback(error);\n return;\n }\n\n world.browser.findElements(By.css('.spec-link'))\n .then(function (specLinks) {\n var featureLink = specLinks[specLinks.length - 1];\n return world.browser.get(featureLink.getAttribute('href'));\n })\n .then(world.browser.getPageSource.bind(world.browser))\n .then(function (body) {\n world.body = body;\n callback();\n });\n };\n}\n\nmodule.exports = function () {\n\n this.Given(/^a URL representing a remote Git repo \"([^\"]*)\"$/, function (repoUrl, callback) {\n this.repoUrl = repoUrl;\n callback();\n });\n\n\n this.When(/^an interested party wants to view the features in that repo\\.?$/, getProjectFromUrl);\n this.When(/^they request the features for the same repository again\\.?$/, getProjectFromUrl);\n\n this.When(/^an interested party wants to view the scenarios within a feature\\.?$/, function (callback) {\n var world = this;\n getProjectFromUrl.bind(world)(getScenarioFromProject(callback, world));\n });\n\n this.When(/^they decide to change which branch is being displayed$/, function (callback) {\n var world = this;\n var burgerMenuId = \"expand-collapse-repository-controls\";\n var repositoryCongtrolsId = \"repository-controls\";\n var projectShaElId = \"project-commit\";\n var changeBranchSelectElId = \"change-branch-control\";\n var testingBranchOptionValue = \"refs%2Fremotes%2Forigin%2Ftest%2FdoNotDelete\";\n var burgerMenuEl;\n var repoControlsEl;\n\n\n // Get the burger menu element.\n world.browser.findElement(By.id(burgerMenuId))\n .then(function(_burgerMenuEl) {\n burgerMenuEl = _burgerMenuEl;\n return world.browser.findElement(By.id(repositoryCongtrolsId));\n\n // Get the repo controls element.\n }).then(function(_repoControlsEl) {\n repoControlsEl = _repoControlsEl;\n return repoControlsEl.getAttribute('class');\n\n // Open the repo controls.\n }).then(function(repoControlsClass) {\n var isClosed = repoControlsClass.indexOf(\"collapse\") !== -1;\n if (isClosed) {\n return burgerMenuEl.click();\n }\n return;\n\n // Grab the current SHA\n }).then(function() {\n return world.browser.findElement(By.id(projectShaElId));\n }).then(function(_projectShaEl) {\n return _projectShaEl.getText();\n }).then(function(originalSha) {\n world.oringalSha = originalSha;\n\n // Grab the branch selecting control.\n return world.browser.findElement(By.id(changeBranchSelectElId));\n\n // Request to change branch.\n }).then(function(_changeBranchSelectEl) {\n return _changeBranchSelectEl.findElement(By.xpath('option[@value=\\'' + testingBranchOptionValue + '\\']'));\n }).then(function(_testBranchOptionEl) {\n return _testBranchOptionEl.click();\n }).then(function() {\n callback();\n });\n });\n\n\n this.Then(/^the list of features will be visible\\.?$/, function (callback) {\n should.equal(\n /\\.feature/i.test(this.body) && /\\.md/i.test(this.body),\n true,\n 'The returned document body does not contain the strings \\'.feature\\' and \\'.md\\'' + this.body);\n callback();\n });\n\n this.Then(/^the scenarios will be visible\\.?$/, function (callback) {\n should.equal(/feature-title/i.test(this.body),\n true,\n 'The returned document body does not contain a feature title');\n callback();\n });\n\n this.Then(/^the files from the selected branch are displayed\\.$/, function (callback) {\n var world = this;\n\n var projectShaElId = \"project-commit\";\n\n\n // Get the new SHA.\n return world.browser.findElement(By.id(projectShaElId))\n .then(function(_projectShaEl) {\n return _projectShaEl.getText();\n }).then(function(newSha) {\n should.notEqual(newSha, world.oringalSha, 'The SHA did not change on changing branch.');\n callback();\n });\n });\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000010721,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -4186,31 +4186,24 @@\n ew SHA.%0A \n-return \n world.browse\n"}}},{"rowIdx":2597393,"cells":{"commit":{"kind":"string","value":"9c3003410adceb851ea3cb2ae16ef37d55046ae4"},"subject":{"kind":"string","value":"add genotype colors constants (#337)"},"old_file":{"kind":"string","value":"src/genome-browser/genome-browser-constants.js"},"new_file":{"kind":"string","value":"src/genome-browser/genome-browser-constants.js"},"old_contents":{"kind":"string","value":"// Global constants for GenomeBrowser\nexport default class GenomeBrowserConstants {\n\n // CellBase constants\n static CELLBASE_HOST = \"https://ws.zettagenomics.com/cellbase\";\n static CELLBASE_VERSION = \"v5\";\n\n // OpenCGA Constants\n static OPENCGA_HOST = \"https://ws.opencb.org/opencga-test\";\n static OPENCGA_VERSION = \"v2\";\n\n // Cytobands\n static CYTOBANDS_COLORS = {\n gneg: \"white\",\n stalk: \"#666666\",\n gvar: \"#CCCCCC\",\n gpos25: \"silver\",\n gpos33: \"lightgrey\",\n gpos50: \"gray\",\n gpos66: \"dimgray\",\n gpos75: \"darkgray\",\n gpos100: \"black\",\n gpos: \"gray\",\n acen: \"blue\",\n };\n\n // Sequence colors\n static SEQUENCE_COLORS = {\n A: \"#009900\",\n C: \"#0000FF\",\n G: \"#857A00\",\n T: \"#aa0000\",\n N: \"#555555\",\n };\n\n // Gene biotype colors\n static GENE_BIOTYPE_COLORS = {\n \"3prime_overlapping_ncrna\": \"Orange\",\n \"ambiguous_orf\": \"SlateBlue\",\n \"antisense\": \"SteelBlue\",\n \"disrupted_domain\": \"YellowGreen\",\n \"IG_C_gene\": \"#FF7F50\",\n \"IG_D_gene\": \"#FF7F50\",\n \"IG_J_gene\": \"#FF7F50\",\n \"IG_V_gene\": \"#FF7F50\",\n \"lincRNA\": \"#8b668b\",\n \"miRNA\": \"#8b668b\",\n \"misc_RNA\": \"#8b668b\",\n \"Mt_rRNA\": \"#8b668b\",\n \"Mt_tRNA\": \"#8b668b\",\n \"ncrna_host\": \"Fuchsia\",\n \"nonsense_mediated_decay\": \"seagreen\",\n \"non_coding\": \"orangered\",\n \"non_stop_decay\": \"aqua\",\n \"polymorphic_pseudogene\": \"#666666\",\n \"processed_pseudogene\": \"#666666\",\n \"processed_transcript\": \"#0000ff\",\n \"protein_coding\": \"#a00000\",\n \"pseudogene\": \"#666666\",\n \"retained_intron\": \"goldenrod\",\n \"retrotransposed\": \"lightsalmon\",\n \"rRNA\": \"indianred\",\n \"sense_intronic\": \"#20B2AA\",\n \"sense_overlapping\": \"#20B2AA\",\n \"snoRNA\": \"#8b668b\",\n \"snRNA\": \"#8b668b\",\n \"transcribed_processed_pseudogene\": \"#666666\",\n \"transcribed_unprocessed_pseudogene\": \"#666666\",\n \"unitary_pseudogene\": \"#666666\",\n \"unprocessed_pseudogene\": \"#666666\",\n // \"\": \"orangered\",\n \"other\": \"#000000\"\n };\n\n // Codon configuration\n static CODON_CONFIG = {\n \"\": {text: \"\", color: \"transparent\"},\n \"R\": {text: \"Arg\", color: \"#BBBFE0\"},\n \"H\": {text: \"His\", color: \"#BBBFE0\"},\n \"K\": {text: \"Lys\", color: \"#BBBFE0\"},\n\n \"D\": {text: \"Asp\", color: \"#F8B7D3\"},\n \"E\": {text: \"Glu\", color: \"#F8B7D3\"},\n\n \"F\": {text: \"Phe\", color: \"#FFE75F\"},\n \"L\": {text: \"Leu\", color: \"#FFE75F\"},\n \"I\": {text: \"Ile\", color: \"#FFE75F\"},\n \"M\": {text: \"Met\", color: \"#FFE75F\"},\n \"V\": {text: \"Val\", color: \"#FFE75F\"},\n \"P\": {text: \"Pro\", color: \"#FFE75F\"},\n \"A\": {text: \"Ala\", color: \"#FFE75F\"},\n \"W\": {text: \"Trp\", color: \"#FFE75F\"},\n \"G\": {text: \"Gly\", color: \"#FFE75F\"},\n\n \"T\": {text: \"Thr\", color: \"#B3DEC0\"},\n \"S\": {text: \"Ser\", color: \"#B3DEC0\"},\n \"Y\": {text: \"Tyr\", color: \"#B3DEC0\"},\n \"Q\": {text: \"Gln\", color: \"#B3DEC0\"},\n \"N\": {text: \"Asn\", color: \"#B3DEC0\"},\n \"C\": {text: \"Cys\", color: \"#B3DEC0\"},\n\n \"X\": {text: \" X \", color: \"#f0f0f0\"},\n \"*\": {text: \" * \", color: \"#DDDDDD\"}\n };\n\n // SNP Biotype colors configuration\n static SNP_BIOTYPE_COLORS = {\n \"2KB_upstream_variant\": \"#a2b5cd\",\n \"5KB_upstream_variant\": \"#a2b5cd\",\n \"500B_downstream_variant\": \"#a2b5cd\",\n \"5KB_downstream_variant\": \"#a2b5cd\",\n \"3_prime_UTR_variant\": \"#7ac5cd\",\n \"5_prime_UTR_variant\": \"#7ac5cd\",\n \"coding_sequence_variant\": \"#458b00\",\n \"complex_change_in_transcript\": \"#00fa9a\",\n \"frameshift_variant\": \"#ff69b4\",\n \"incomplete_terminal_codon_variant\": \"#ff00ff\",\n \"inframe_codon_gain\": \"#ffd700\",\n \"inframe_codon_loss\": \"#ffd700\",\n \"initiator_codon_change\": \"#ffd700\",\n \"non_synonymous_codon\": \"#ffd700\",\n \"missense_variant\": \"#ffd700\",\n \"intergenic_variant\": \"#636363\",\n \"intron_variant\": \"#02599c\",\n \"mature_miRNA_variant\": \"#458b00\",\n \"nc_transcript_variant\": \"#32cd32\",\n \"splice_acceptor_variant\": \"#ff7f50\",\n \"splice_donor_variant\": \"#ff7f50\",\n \"splice_region_variant\": \"#ff7f50\",\n \"stop_gained\": \"#ff0000\",\n \"stop_lost\": \"#ff0000\",\n \"stop_retained_variant\": \"#76ee00\",\n \"synonymous_codon\": \"#76ee00\",\n \"other\": \"#000000\"\n };\n\n}\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.213e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -4541,10 +4541,169 @@\n %7D;%0A%0A\n+ // Genotypes colors%0A static GENOTYPES_COLORS = %7B%0A %22heterozygous%22: %22darkblue%22,%0A %22homozygous%22: %22cyan%22,%0A %22reference%22: %22gray%22,%0A %7D;%0A%0A\n %7D%0A\n"}}},{"rowIdx":2597394,"cells":{"commit":{"kind":"string","value":"4453bf5e68f1fd41cebe9e3dc2833d2df7fdfd0f"},"subject":{"kind":"string","value":"Update moonpay api"},"old_file":{"kind":"string","value":"server/lib/v1/moonpay.js"},"new_file":{"kind":"string","value":"server/lib/v1/moonpay.js"},"old_contents":{"kind":"string","value":"'use strict';\n\nvar axios = require('axios');\nvar db = require('./db');\n\nvar PRIORITY_SYMBOLS = ['BTC', 'BCH', 'ETH', 'USDT', 'LTC', 'XRP', 'XLM', 'EOS', 'DOGE', 'DASH'];\nvar fiatSigns = {\n usd: '$',\n eur: '€',\n gbp: '£'\n};\n\nfunction save(_id, data) {\n var collection = db().collection('moonpay');\n return collection.updateOne({_id: _id}, {$set: {data: data}}, {upsert: true});\n}\n\nfunction getCurrenciesFromAPI() {\n return axios.get('https://api.moonpay.io/v3/currencies').then(function(response) {\n var data = response.data;\n if (!data || !data.length) throw new Error('Bad moonpay response');\n\n var coins = {};\n var coinsUSA = {};\n PRIORITY_SYMBOLS.forEach(function(symbol) {\n var coin = data.find(function(item) {\n return item.code === symbol.toLowerCase();\n });\n if (coin) {\n coins[coin.id] = {\n symbol: symbol,\n isSupported: !coin.isSuspended\n }\n coinsUSA[coin.id] = {\n symbol: symbol,\n isSupported: !coin.isSuspended && coin.isSupportedInUS\n }\n }\n });\n\n var fiat = {};\n data.forEach(function(item) {\n if (item.type === 'fiat') {\n fiat[item.id] = {\n symbol: item.code.toUpperCase(),\n sign: fiatSigns[item.code] || '',\n precision: item.precision\n };\n }\n });\n\n return {\n coins: coins,\n coins_usa: coinsUSA,\n fiat: fiat\n };\n });\n}\n\nfunction getCountriesFromAPI() {\n return axios.get('https://api.moonpay.io/v3/countries').then(function(response) {\n var data = response.data;\n if (!data || !data.length) throw new Error('Bad moonpay response');\n\n var document = data.filter(function(country) {\n return country.supportedDocuments && country.supportedDocuments.length > 0;\n }).map(function(country) {\n return {\n code: country.alpha3,\n name: country.name,\n supportedDocuments: country.supportedDocuments\n }\n });\n\n var allowed = data.filter(function(country) {\n return country.isAllowed;\n }).map(function(country) {\n var item = {};\n item.code = country.alpha3;\n item.name = country.name;\n if (country.states) {\n item.states = country.states.filter(function(state) {\n return state.isAllowed;\n }).map(function(state) {\n return {\n code: state.code,\n name: state.name\n };\n });\n }\n return item;\n });\n\n return {\n document: document,\n allowed: allowed\n };\n });\n}\n\nfunction getFromCache(id) {\n var collection = db().collection('moonpay');\n return collection\n .find({_id: id})\n .limit(1)\n .next().then(function(item) {\n if (!item) return {};\n delete item.id;\n return item.data;\n });\n}\n\nmodule.exports = {\n save: save,\n getCurrenciesFromAPI: getCurrenciesFromAPI,\n getCountriesFromAPI: getCountriesFromAPI,\n getFromCache: getFromCache\n};\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":3.66e-7,"string":"0"},"diff":{"kind":"string","value":"@@ -63,16 +63,59 @@\n './db');\n+%0Avar API_KEY = process.env.MOONPAY_API_KEY;\n %0A%0Avar PR\n@@ -508,24 +508,73 @@\n /currencies'\n+, %7B%0A params: %7B%0A apiKey: API_KEY%0A %7D%0A %7D\n ).then(funct\n"}}},{"rowIdx":2597395,"cells":{"commit":{"kind":"string","value":"94f350b9b01a1048f03c9c93bad0fda1f0b9041e"},"subject":{"kind":"string","value":"refactor serial writes"},"old_file":{"kind":"string","value":"lib/board.js"},"new_file":{"kind":"string","value":"lib/board.js"},"old_contents":{"kind":"string","value":"\nvar events = require('events'),\n child = require('child_process'),\n util = require('util'),\n serial = require('serialport').SerialPort;\n\n/*\n * The main Arduino constructor\n * Connect to the serial port and bind\n */\nvar Board = function (options) {\n this.messageBuffer = '';\n var self = this;\n this.detect(function (err, serial) {\n if (err) throw err;\n self.serial = serial;\n self.serial.on('data', function(data){\n self.emit('data', data);\n self.messageBuffer += data;\n self.attemptParse();\n });\n self.emit('connected');\n });\n}\n\n/*\n * EventEmitter, I choose you!\n */\nutil.inherits(Board, events.EventEmitter);\n\n/*\n * Detect an Arduino board\n * Loop through all USB devices and try to connect\n * This should really message the device and wait for a correct response\n */\nBoard.prototype.detect = function (cb) {\n child.exec('ls /dev | grep usb', function(err, stdout, stderr){\n var possible = stdout.slice(0, -1).split('\\n'),\n found = false;\n for (var i in possible) {\n var tempSerial, err;\n try {\n tempSerial = new serial('/dev/' + possible[i]);\n } catch (e) {\n err = e;\n }\n if (!err) {\n found = tempSerial;\n break;\n }\n }\n if (found) cb(null, found);\n else cb(new Error('Could not find Arduino'));\n });\n}\n\n/*\n * Attempt to parse the message buffer via delimiter\n * Called every time data bytes are received\n */\nBoard.prototype.attemptParse = function (data) {\n var b = this.messageBuffer.split('\\r\\n');\n while (b.length > 1) {\n this.emit('message', b.shift());\n }\n this.messageBuffer = b[0];\n}\n\n/*\n * Low-level serial write\n */\nBoard.prototype.write = function (m) {\n this.serial.write(m);\n}\n\n/*\n * Set a pin's mode\n * val == out = 01\n * val == in = 00\n */\nBoard.prototype.pinMode = function (pin, val) {\n this.serial.write(\n '00' +\n pin +\n (val == 'out' ? '01' : '00')\n );\n}\n\n/*\n * Tell the board to write to a digital pin\n */\nBoard.prototype.digitalWrite = function (pin, val) {\n this.serial.write('01' + pin + val + '\\r');\n}\n\nBoard.prototype.digitalRead = function (pin, val) {}\nBoard.prototype.analogWrite = function (pin, val) {}\nBoard.prototype.analogWrite = function (pin, val) {}\n\nmodule.exports = Board;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000011074,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -385,24 +385,52 @@\n l = serial;%0A\n+ self.serial.write('0');%0A\n self.ser\n@@ -1743,17 +1743,29 @@\n l.write(\n-m\n+'!' + m + '.'\n );%0A%7D%0A%0A/*\n@@ -1881,53 +1881,20 @@\n %7B%0A \n-this.serial.write(%0A '00' +%0A pin +%0A (\n+val = (%0A \n val \n@@ -1907,24 +1907,102 @@\n t' ?\n+%0A \n '01' :\n+%0A \n '00'\n-)\n %0A \n+);%0A // console.log('pm 00' + pin + val);%0A this.write('00' + pin + val\n );%0A%7D\n@@ -2105,35 +2105,66 @@\n n, val) %7B%0A \n-this.serial\n+//console.log('dw 01' + pin + val);%0A this\n .write('01' \n@@ -2178,15 +2178,8 @@\n val\n- + '%5Cr'\n );%0A%7D\n"}}},{"rowIdx":2597396,"cells":{"commit":{"kind":"string","value":"41edd3fb3a1db6a4cfe3e728663595586f5c39e6"},"subject":{"kind":"string","value":"I never claimed to be a smart man. fix stupid bug"},"old_file":{"kind":"string","value":"server/routes/download.js"},"new_file":{"kind":"string","value":"server/routes/download.js"},"old_contents":{"kind":"string","value":"'use strict';\n\n// We have three possible outcomes when someone requests `/download`,\n\n// 1. serve the compilled, static html file if in production\n// 2. serve a compiled handlebars template on each request, in development\n// 3. reply with a tar ball of a compiled version of Modernizr, if requested via bower\n\n// this module determines the right one depending the circumstances\n\nvar Path = require('path');\nvar ETag = require('etag');\nvar Archiver = require('archiver');\nvar Modernizr = require('modernizr');\nvar modernizrMetadata = Modernizr.metadata();\nvar bowerJSON = require('../util/bowerJSON')();\nvar modernizrOptions = require('../util/modernizrOptions');\nvar _ = require(Path.join(__dirname, '..', '..', 'frontend', 'js', 'lodash.custom'));\n\n// the `builderContent` step is super heavy, as a result, do not load it if we\n// are in a production enviroment\nif (process.env.NODE_ENV !== 'production') {\n var builderContent = require('../buildSteps/download');\n\n var downloaderConfig = {\n metadata: JSON.stringify(modernizrMetadata),\n options: JSON.stringify(modernizrOptions),\n builderContent: builderContent,\n scripts: [\n '/js/lodash.custom.js',\n '/js/modernizr.custom.js',\n '/lib/zeroclipboard/dist/ZeroClipboard.js',\n '/lib/r.js/dist/r.js',\n '/lib/modernizr/lib/build.js',\n '/js/download/downloader.js',\n ],\n team: require('../util/footer')\n };\n}\n\nvar propToAMD = function(prop) {\n if (_.contains(prop, '_')) {\n prop = prop.split('_');\n }\n\n return _.where(modernizrMetadata, {'property': prop})[0].amdPath;\n};\n\nvar optProp = function(prop) {\n return _.chain(modernizrOptions)\n .filter(function(opt) {\n return opt.property.toLowerCase() === prop;\n })\n .map(function(opt) {\n return opt.property;\n })\n .first()\n .value();\n};\n\n// takes a build hash/querystring that is updated automatically on `/download`, and\n// included by default inside of every custom build of modernizr, and converts it\n// into a valid Modernizr config\nvar config = function(query) {\n\n var config = {\n 'minify': true,\n 'feature-detects': [],\n 'options': []\n };\n\n var queries = _.chain(query.replace(/^\\?/, '').split('&'))\n .map(function(query) {\n return query.split('-');\n })\n .flatten()\n .value();\n\n queries.forEach(function(query) {\n // `/download` has a search box that we track state with via the `q` param\n // since it defently won't match anything, we exit early when found\n var searchResult = query.match(/q=(.*)/);\n var cssclassprefix = query.match('cssclassprefix:(.*)');\n\n if (searchResult) {\n return;\n }\n\n if (cssclassprefix) {\n // the classPrefix is tracked separately from other options, so just update\n // the config accordingly, and return false for every property we match against\n config.classPrefix = cssclassprefix[1];\n return;\n }\n\n if (query.match('shiv$')) {\n // `html5shiv` and `html5printshiv` are configured as `shiv` and `printshiv`\n // for the sake of brevity, as well as to drive me insane\n query = 'html5' + query;\n }\n\n var matches = function(obj) {\n var prop = obj.property;\n\n if (_.isArray(prop)) {\n // some detects have an array of properties, which would strinigfy weirdly\n // without us doing it manually here\n prop = prop.join('_');\n }\n\n if (query === 'dontmin' && prop === 'minify') {\n // we track the minify state on the `/download` side under the inverted\n // `dontmin` option, and on the server side with the (non standard)\n // `modernizr.options().minify` option\n config.minify = false;\n }\n\n return query === prop.toLowerCase();\n };\n\n if (_.some(modernizrOptions, matches)) {\n config.options.push(optProp(query));\n } else if (_.some(modernizrMetadata, matches)) {\n config['feature-detects'].push(propToAMD(query));\n }\n });\n\n return config;\n};\n\nvar handler = function (request, reply) {\n // the download urls (that include the build settings) can be used inside of a bower.json\n // file to automatically download a custom version of the current version of Modernizr\n // Ironically, in order to support this, we have to do user agent sniffing\n var ua = request.headers['user-agent'];\n // http://bower.io/docs/config/#user-agent\n // NOTE this will obvs fail to match for custom bower user agents\n var isBower = !!ua.match(/^node\\/v\\d*\\.\\d*\\.\\d* (darwin|freebsd|linux|sunos|win32) (arm|ia32|x64)/);\n\n if (isBower) {\n // bower complains a bunch if we don't include proper metadata with the response.\n // in order to do so, we create a virtual tar file, and but the build and bower.json\n // file in it\n var archive = Archiver('tar');\n var query = request.url.search.replace(/\\.tar(\\.gz)?|zip$/, '');\n var buildConfig = config(query);\n\n Modernizr.build(buildConfig, function(build) {\n var module = archive\n .append(build, {name: bowerJSON.main})\n .append(JSON.stringify(bowerJSON, 0, 2), {name: 'bower.json'})\n .finalize();\n\n reply(module)\n // bower bases how it handles the response on the name of the responded file.\n // we have to reply with a `.tar` file in order to be processed correctly\n .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar')\n // bower will cache files downloaded via URLResolver (which is what it is\n // using here) via its ETag. This won't prevent us from building a new\n // version on each response, but it will prevent wasted bandwidth\n .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig)));\n });\n\n } else if (!!ua.match(/^npm\\//)) {\n\n Modernizr.build(buildConfig, function(build) {\n var archive = Archiver('tar');\n var query = request.url.search.replace(/\\.tar(.gz)?$/, '');\n var buildConfig = config(query);\n var module = archive\n .append(build, {name: 'modernizr/' + bowerJSON.main})\n .append(JSON.stringify(bowerJSON, 0, 2), {name: 'modernizr/package.json'})\n .finalize();\n\n reply(module)\n .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar')\n .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig)));\n });\n } else if (process.env.NODE_ENV !== 'production') {\n // if it was not requested by bower, and not in prod mode, we serve the\n // homepage via the Hapi handlebars renderer\n reply.view('pages/download', downloaderConfig);\n } else {\n // if all else fails, we are in prod/static mode, so serve the static index\n reply.file(Path.join(__dirname, '..', '..', 'dist', 'download', 'index.html'));\n }\n};\n\nmodule.exports = handler;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.1588064581,"string":"0.158806"},"diff":{"kind":"string","value":"@@ -4502,16 +4502,118 @@\n %7Cx64)/);\n+%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query);\n %0A%0A if (\n@@ -4854,114 +4854,8 @@\n r');\n-%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query);\n %0A%0A \n@@ -5784,109 +5784,8 @@\n ');%0A\n- var query = request.url.search.replace(/%5C.tar(.gz)?$/, '');%0A var buildConfig = config(query);%0A\n \n"}}},{"rowIdx":2597397,"cells":{"commit":{"kind":"string","value":"e732a1170294e70fee3b6a30bedec6ddf981b6bd"},"subject":{"kind":"string","value":"refactor missions endpoint"},"old_file":{"kind":"string","value":"server/routes/missions.js"},"new_file":{"kind":"string","value":"server/routes/missions.js"},"old_contents":{"kind":"string","value":"var express = require('express');\nvar router = express.Router();\n//console.log(__dirname);\nconst bookshelf = require('../db/knex')\n\n// models\nconst Mission = require('../Models/Mission');\nconst Casefile = require('../Models/Casefile');\nconst User = require('../Models/User');\n// collections - TODO not used??? - when is it good to use?\nconst Missions = require('../Collections/missions');\n\n// check if user authorized\nfunction authorizedUser(req, res, next) {\n const userID = req.session.user;\n if (userID) {\n next();\n } else {\n res.render('restricted');\n }\n}\n\n// need to display user-specific missions + casefiles when user is logged in\nrouter.get('/api/missions', (req, res, next) => {\n let files = {};\n // TODO where user_id === logged_in user (req.session.user)\n let user = 1; // temporary workaround\n\n Mission.forge().where({user_id: user}).query('orderBy', 'id', 'asc')\n .fetchAll({withRelated: ['casefile'], debug:true})\n .then((mission) => {\n // convert data to JSON\n mission = mission.toJSON();\n // loop over data to get mission and casefile names\n for (var i = 0; i < mission.length; i++) {\n // save to files object\n if (mission[i].casefile && mission[i].casefile.name) {\n files[mission[i].name] = mission[i].casefile.name;\n } else {\n files[mission[i].name] = \"no casefile added\";\n }\n }\n // send files object\n res.send(files)\n })\n});\n\n // get mission by name / id\n router.get('/api/view-mission/:name', function(req, res, next) {\n let mission_name = req.params.name.split('_').join(' ');\n let missionJSON;\n\n Mission.forge().where({ name: mission_name }).fetch()\n .then((mission) => res.send(mission))\n .catch((err) => console.log(\"mission fetching error\", err))\n })\n\n// create a new mission\nrouter.post('/api/add-mission', (req, res, next) => {\n let username, new_url, next_id;\n\n // set the value of the next id in the mission table, avoiding duplicate key errors\n bookshelf.knex.raw('SELECT setval(\\'missions_id_seq\\', (SELECT MAX(id) FROM missions)+1)')\n\n // TODO I don't think this is the correct way to do this AT ALL\n // get last mission id\n\n // get user name from user id for mission url\n User.forge().where({id: req.body.user_id}).fetch()\n .then((user) => {\n user = user.toJSON() || 'testamdmin';\n username = user.name;\n // strip punctuation, capitals, and spaces\n username = username.replace(/[.\\-`'\\s]/g,\"\").toLowerCase();\n // create the url students will use to access the mission\n new_url = '/' + username + '/'; // TODO need to add the correct id to this somehow, here or elsewhere\n })\n .then(() => {\n // change last_id to false for current last_id\n Mission.forge().where({last_id: true})\n .save({last_id: false}, {patch: true})\n })\n .then(() => {\n // save mission name, user_id, url to mission table - casefile_id will be\n // updated in patch when selected\n Mission.forge({\n name: req.body.name,\n user_id: req.body.user_id,\n url: new_url,\n last_id: true\n })\n .save()\n .then((mission) => {\n res.sendStatus(200);\n })\n .catch((err) => {\n next(err);\n })\n })\n .catch((err) => {\n next(err);\n })\n}) // end post\n\n// update mission with casefile_id on saving\nrouter.patch('/api/update-mission', (req, res, next) => {\n console.log(\"patch route reached\", req.body);\n Mission.forge().where({name: req.body.name}).fetch()\n .then((mission) => {\n // update mission table with selected casefile_id\n console.log(\"fetched mission to patch\", mission);\n Mission.forge().where({id: mission.attributes.id})\n //TODO get casefile_id a better way\n .save({casefile_id: req.body.casefile_id+1}, {patch: true})\n .then((response) => {\n console.log(\"mission updated successfully\", response);\n res.sendStatus(200);\n })\n .catch((err) => {\n next(err);\n })\n })\n .catch((err) => {\n next(err);\n })\n\n})\n\nrouter.delete('/api/delete-mission/:name', (req, res, next) => {\n console.log(\"you are in the mission delete route and you are deleting mission: \", req.params.name);\n Mission.forge().where({name: req.params.name})\n .fetch({require: true})\n .then((mission) => {\n mission.destroy()\n .then(() => {\n console.log(\"mission\", req.params.name, \"successfully deleted\");\n res.sendStatus(200);\n })\n .catch((err) => {\n console.log(\"nooo, error\", err);\n })\n })\n .catch((err) => {\n console.log(\"delete error\", err);\n });\n})\n\nmodule.exports = router;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0001087509,"string":"0.000109"},"diff":{"kind":"string","value":"@@ -701,19 +701,28 @@\n let \n-files = %7B%7D;\n+missionsArray = %5B%5D;%0A\n %0A /\n@@ -957,32 +957,33 @@\n .then((mission\n+s\n ) =%3E %7B%0A // \n@@ -1016,16 +1016,17 @@\n mission\n+s\n = missi\n@@ -1027,16 +1027,17 @@\n mission\n+s\n .toJSON(\n@@ -1035,24 +1035,25 @@\n s.toJSON();%0A\n+%0A\n // loo\n@@ -1097,16 +1097,22 @@\n le names\n+ & ids\n %0A f\n@@ -1137,16 +1137,17 @@\n mission\n+s\n .length;\n@@ -1166,137 +1166,181 @@\n \n-// save to files object%0A if (\n+missionsArray%5Bi%5D = %7B%0A %22missionName%22: \n mission\n+s\n %5Bi%5D.\n-casefile && mission%5Bi%5D.casefile.name) %7B%0A files%5B\n+name %7C%7C %22%22,%0A %22missionId%22: missions%5Bi%5D.id %7C%7C null,%0A %22casefileName%22: \n mission\n+s\n %5Bi%5D.\n-name%5D =\n+casefile ?\n mission\n %5Bi%5D.\n@@ -1331,24 +1331,25 @@\n le ? mission\n+s\n %5Bi%5D.casefile\n@@ -1357,82 +1357,110 @@\n name\n-;%0A %7D else %7B%0A files%5B\n+ : %22no casefile added%22,%0A %22casefileId%22: \n mission\n+s\n %5Bi%5D.\n-name%5D = %22no casefile added%22;\n+casefile ? missions%5Bi%5D.casefile.id : null,\n %0A \n@@ -1488,20 +1488,23 @@\n // send \n-file\n+mission\n s object\n@@ -1519,21 +1519,29 @@\n es.send(\n-files\n+missionsArray\n )%0A %7D)\n"}}},{"rowIdx":2597398,"cells":{"commit":{"kind":"string","value":"09214e30538194174194130ccc2e85c70648915d"},"subject":{"kind":"string","value":"Change text view init"},"old_file":{"kind":"string","value":"www/views/backup/text.js"},"new_file":{"kind":"string","value":"www/views/backup/text.js"},"old_contents":{"kind":"string","value":"define([\n 'jquery',\n 'underscore',\n 'backbone',\n 'shCore',\n 'shBrushAppleScript',\n 'shBrushAS3',\n 'shBrushBash',\n 'shBrushColdFusion',\n 'shBrushCpp',\n 'shBrushCSharp',\n 'shBrushCss',\n 'shBrushDelphi',\n 'shBrushDiff',\n 'shBrushErlang',\n 'shBrushGroovy',\n 'shBrushHaxe',\n 'shBrushJava',\n 'shBrushJavaFX',\n 'shBrushJScript',\n 'shBrushPerl',\n 'shBrushPhp',\n 'shBrushPlain',\n 'shBrushPowerShell',\n 'shBrushPython',\n 'shBrushRuby',\n 'shBrushSass',\n 'shBrushScala',\n 'shBrushSql',\n 'shBrushTypeScript',\n 'shBrushVb',\n 'shBrushXml',\n 'models/backup/text',\n 'text!templates/backup/text.html'\n], function($, _, Backbone, SyntaxHighlighter, BrushAppleScript, BrushAS3,\n BrushBash, BrushColdFusion, BrushCpp, BrushCSharp, BrushCss, BrushDelphi,\n BrushDiff, BrushErlang, BrushGroovy, BrushHaxe, BrushJava, BrushJavaFX,\n BrushJScript, BrushPerl, BrushPhp, BrushPlain, BrushPowerShell,\n BrushPython, BrushRuby, BrushSass, BrushScala, BrushSql, BrushTypeScript,\n BrushVb, BrushXml, TextModel, textTemplate) {\n 'use strict';\n var TextView = Backbone.View.extend({\n className: 'text-viewer-box',\n events: {\n 'mouseover .close-viewer': 'addIconWhite',\n 'mouseout .close-viewer': 'removeIconWhite',\n 'click .close-viewer': 'onClickClose'\n },\n template: _.template(textTemplate),\n initialize: function(options) {\n this.model = new TextModel({\n id: options.id,\n volume: options.volume,\n snapshot: options.snapshot\n });\n },\n render: function() {\n this.$el.html(this.template(this.model.toJSON()));\n SyntaxHighlighter.highlight(null, this.$('pre')[0]);\n this.$el.fadeIn(400);\n return this;\n },\n addIconWhite: function(evt) {\n this.$(evt.target).addClass('icon-white');\n },\n removeIconWhite: function(evt) {\n this.$(evt.target).removeClass('icon-white');\n },\n onClickClose: function() {\n this.$('.close-viewer').roll(400);\n this.$el.fadeOut(400, function() {\n this.remove();\n }.bind(this));\n }\n });\n\n return TextView;\n});\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":5.598e-7,"string":"0.000001"},"diff":{"kind":"string","value":"@@ -1402,108 +1402,15 @@\n del(\n-%7B%0A id: options.id,%0A volume: options.volume,%0A snapshot: options.snapshot%0A %7D\n+options\n );%0A \n"}}},{"rowIdx":2597399,"cells":{"commit":{"kind":"string","value":"0d63f0442e795ec0371e73050076ea3dd60c0725"},"subject":{"kind":"string","value":"Fix for undefined req.onErrorCallback"},"old_file":{"kind":"string","value":"lib/express_validator.js"},"new_file":{"kind":"string","value":"lib/express_validator.js"},"old_contents":{"kind":"string","value":"/*\n * This binds the node-validator library to the req object so that\n * the validation / sanitization methods can be called on parameter\n * names rather than the actual strings.\n *\n * 1. Be sure to include `req.mixinParams()` as middleware to merge\n * query string, body and named parameters into `req.params`\n *\n * 2. To validate parameters, use `req.check(param_name, [err_message])`\n * e.g. req.check('param1').len(1, 6).isInt();\n * e.g. req.checkHeader('referer').contains('mydomain.com');\n *\n * Each call to `check()` will throw an exception by default. To\n * specify a custom err handler, use `req.onValidationError(errback)`\n * where errback receives a parameter containing the error message\n *\n * 3. To sanitize parameters, use `req.sanitize(param_name)`\n * e.g. req.sanitize('large_text').xss();\n * e.g. req.sanitize('param2').toInt();\n *\n * 4. Done! Access your validated and sanitized paramaters through the\n * `req.params` object\n */\n\nvar Validator = require('validator').Validator,\n Filter = require('validator').Filter;\n\nvar validator = new Validator();\n\nvar expressValidator = function(req, res, next) {\n\n req.updateParam = function(name, value) {\n // route params like /user/:id\n if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) {\n return this.params[name] = value;\n }\n // query string params\n if (undefined !== this.query[name]) {\n return this.query[name] = value;\n }\n // request body params via connect.bodyParser\n if (this.body && undefined !== this.body[name]) {\n return this.body[name] = value;\n }\n return false;\n };\n\n req.check = function(param, fail_msg) {\n validator.error = function(msg) {\n var error = {\n param: param,\n msg: msg\n }\n if (req._validationErrors === undefined) {\n req._validationErrors = [];\n }\n req._validationErrors.push(error);\n req.onErrorCallback(msg);\n }\n return validator.check(this.param(param), fail_msg);\n };\n\n req.checkHeader = function(param, fail_msg) {\n var to_check;\n if (header === 'referrer' || header === 'referer') {\n to_check = this.headers.referer;\n } else {\n to_check = this.headers[header];\n }\n return validator.check(to_check || '', fail_msg);\n };\n\n req.onValidationError = function(errback) {\n req.onErrorCallback = errback;\n };\n\n req.validationErrors = function(mapped) {\n if (req._validationErrors === undefined) {\n return false;\n }\n if (mapped) {\n var errors = {};\n req._validationErrors.map(function(err) {\n errors[err.param] = err.msg;\n });\n return errors;\n } else {\n return req._validationErrors;\n }\n }\n\n req.filter = function(param) {\n var self = this;\n var filter = new Filter();\n filter.modify = function(str) {\n this.str = str;\n self.updateParam(param, str); // Replace the param with the filtered version\n };\n return filter.sanitize(this.param(param));\n };\n\n // Create some aliases - might help with code readability\n req.sanitize = req.filter;\n req.assert = req.check;\n\n return next();\n};\nmodule.exports = expressValidator;\nmodule.exports.Validator = Validator;\nmodule.exports.Filter = Filter;\n"},"lang":{"kind":"string","value":"JavaScript"},"proba":{"kind":"number","value":0.0000100032,"string":"0.00001"},"diff":{"kind":"string","value":"@@ -1946,16 +1946,51 @@\n error);%0A\n+%0A if(req.onErrorCallback) %7B%0A \n re\n@@ -2013,16 +2013,24 @@\n k(msg);%0A\n+ %7D%0A\n %7D%0A \n"}}}],"truncated":false,"partial":false},"paginationData":{"pageIndex":25973,"numItemsPerPage":100,"numTotalItems":2597493,"offset":2597300,"length":100}},"jwt":"eyJhbGciOiJFZERTQSJ9.eyJyZWFkIjp0cnVlLCJwZXJtaXNzaW9ucyI6eyJyZXBvLmNvbnRlbnQucmVhZCI6dHJ1ZX0sImlhdCI6MTc1NTkwMzc1OCwic3ViIjoiL2RhdGFzZXRzL2JpZ2NvZGUvY29tbWl0cy1wamotZGlmZiIsImV4cCI6MTc1NTkwNzM1OCwiaXNzIjoiaHR0cHM6Ly9odWdnaW5nZmFjZS5jbyJ9.MpaQCFLDw7uPsgdMfq_W4P3lum0grRMVg1brOz2MkoU_qFF2uQx0GlrzO2E23vQy68Rl4RusGtxZVQ1yVXFbBw","displayUrls":true},"discussionsStats":{"closed":0,"open":0,"total":0},"fullWidth":true,"hasGatedAccess":true,"hasFullAccess":true,"isEmbedded":false,"savedQueries":{"community":[],"user":[]}}">
    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
    adda1e261b87633559d9165e13dcafbd6f709ac7
    correct error with submission hooks.
    src/services/submissions/hooks/index.js
    src/services/submissions/hooks/index.js
    'use strict'; const globalHooks = require('../../../hooks'); const hooks = require('feathers-hooks'); const auth = require('feathers-authentication').hooks; exports.before = { all: [ // auth.verifyToken(), // auth.populateUser(), // auth.restrictToAuthenticated() ], find: [], get: [], create: [], update: [], patch: [], remove: [] }; exports.after = { all: [], find: [], get: [], create: [], update: [], patch: [], remove: [] };
    JavaScript
    0
    @@ -179,27 +179,24 @@ all: %5B%0A - // auth.verify @@ -203,27 +203,24 @@ Token(),%0A - // auth.popula @@ -236,11 +236,8 @@ %0A - // aut
    fe899e38f4f19ba914f568af0232d52fbfda3003
    add S3 copy object example
    javascriptv3/example_code/s3/src/s3_copyobject.js
    javascriptv3/example_code/s3/src/s3_copyobject.js
    /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 ABOUT THIS NODE.JS EXAMPLE: This example works with AWS SDK for JavaScript version 3 (v3), which is available at https://github.com/aws/aws-sdk-js-v3. This example is in the 'AWS SDK for JavaScript v3 Developer Guide' at https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/s3-example-creating-buckets.html. Purpose: s3_copyobject.js demonstrates how to copy an object from one Amazon Simple Storage Solution (Amazon S3) bucket to another. Inputs (replace in code): - BUCKET_NAME Running the code: node s3_copyobject.js */ // snippet-start:[s3.JavaScript.buckets.copyObjectV3] // Get service clients module and commands using ES6 syntax. import { CopyObjectCommand } from "@aws-sdk/client-s3"; import { s3Client } from "./libs/s3Client.js"; // Set the bucket parameters. export const params = { Bucket: "brmurbucket", CopySource: "/apigatewaystack-mybucket160f8132-1dysc21xykp8d/index.js", Key: "index.js" }; // Create the Amazon S3 bucket. export const run = async () => { try { const data = await s3Client.send(new CopyObjectCommand(params)); console.log("Success", data); return data; // For unit tests. } catch (err) { console.log("Error", err); } }; run(); // snippet-end:[s3.JavaScript.buckets.copyObjectV3] // For unit tests only. // module.exports ={run, bucketParams};
    JavaScript
    0
    @@ -586,13 +586,60 @@ :%0A- -BUCKE +DESTINATION_BUCKET_NAME%0A- SOURCE_BUCKET_NAME%0A- OBJEC T_NA @@ -976,95 +976,82 @@ t: %22 -brmurbucket%22,%0A CopySource: %22/apigatewaystack-mybucket160f8132-1dysc21xykp8d/index.js +DESTINATION_BUCKET_NAME%22,%0A CopySource: %22/SOURCE_BUCKET_NAME/OBJECT_NAME %22,%0A @@ -1063,16 +1063,19 @@ y: %22 -index.js +OBJECT_NAME %22%0A%7D;
    b805b78b03d58efb353c725390cef10562652021
    Update checks
    Source/Core/FeatureDetection.js
    Source/Core/FeatureDetection.js
    /*global define*/ define([ './defaultValue', './defined', './Fullscreen' ], function( defaultValue, defined, Fullscreen) { 'use strict'; var theNavigator; if (typeof navigator !== 'undefined') { theNavigator = navigator; } else { theNavigator = {}; } function extractVersion(versionString) { var parts = versionString.split('.'); for (var i = 0, len = parts.length; i < len; ++i) { parts[i] = parseInt(parts[i], 10); } return parts; } var isChromeResult; var chromeVersionResult; function isChrome() { if (!defined(isChromeResult)) { isChromeResult = false; if (/Google Inc/.test(theNavigator.vendor)) { var fields = (/ Chrome\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isChromeResult = true; chromeVersionResult = extractVersion(fields[1]); } } } return isChromeResult; } function chromeVersion() { return isChrome() && chromeVersionResult; } var isSafariResult; var safariVersionResult; function isSafari() { if (!defined(isSafariResult)) { isSafariResult = false; // Chrome contains Safari in the user agent too if (!isChrome() && (/ Safari\/[\.0-9]+/).test(theNavigator.userAgent)) { var fields = (/ Version\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isSafariResult = true; safariVersionResult = extractVersion(fields[1]); } } } return isSafariResult; } function safariVersion() { return isSafari() && safariVersionResult; } var isWebkitResult; var webkitVersionResult; function isWebkit() { if (!defined(isWebkitResult)) { isWebkitResult = false; var fields = (/ AppleWebKit\/([\.0-9]+)(\+?)/).exec(theNavigator.userAgent); if (fields !== null) { isWebkitResult = true; webkitVersionResult = extractVersion(fields[1]); webkitVersionResult.isNightly = !!fields[2]; } } return isWebkitResult; } function webkitVersion() { return isWebkit() && webkitVersionResult; } var isInternetExplorerResult; var internetExplorerVersionResult; function isInternetExplorer() { if (!defined(isInternetExplorerResult)) { isInternetExplorerResult = false; var fields; if (theNavigator.appName === 'Microsoft Internet Explorer') { fields = /MSIE ([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent); if (fields !== null) { isInternetExplorerResult = true; internetExplorerVersionResult = extractVersion(fields[1]); } } else if (theNavigator.appName === 'Netscape') { fields = /Trident\/.*rv:([0-9]{1,}[\.0-9]{0,})/.exec(theNavigator.userAgent); if (fields !== null) { isInternetExplorerResult = true; internetExplorerVersionResult = extractVersion(fields[1]); } } } return isInternetExplorerResult; } function internetExplorerVersion() { return isInternetExplorer() && internetExplorerVersionResult; } var isEdgeResult; var edgeVersionResult; function isEdge() { if (!defined(isEdgeResult)) { isEdgeResult = false; var fields = (/ Edge\/([\.0-9]+)/).exec(theNavigator.userAgent); if (fields !== null) { isEdgeResult = true; edgeVersionResult = extractVersion(fields[1]); } } return isEdgeResult; } function edgeVersion() { return isEdge() && edgeVersionResult; } var isFirefoxResult; var firefoxVersionResult; function isFirefox() { if (!defined(isFirefoxResult)) { isFirefoxResult = false; var fields = /Firefox\/([\.0-9]+)/.exec(theNavigator.userAgent); if (fields !== null) { isFirefoxResult = true; firefoxVersionResult = extractVersion(fields[1]); } } return isFirefoxResult; } var isWindowsResult; function isWindows() { if (!defined(isWindowsResult)) { isWindowsResult = /Windows/i.test(theNavigator.appVersion); } return isWindowsResult; } function firefoxVersion() { return isFirefox() && firefoxVersionResult; } var hasPointerEvents; function supportsPointerEvents() { if (!defined(hasPointerEvents)) { //While navigator.pointerEnabled is deprecated in the W3C specification //we still need to use it if it exists in order to support browsers //that rely on it, such as the Windows WebBrowser control which defines //PointerEvent but sets navigator.pointerEnabled to false. hasPointerEvents = typeof PointerEvent !== 'undefined' && (!defined(theNavigator.pointerEnabled) || theNavigator.pointerEnabled); } return hasPointerEvents; } var imageRenderingValueResult; var supportsImageRenderingPixelatedResult; function supportsImageRenderingPixelated() { if (!defined(supportsImageRenderingPixelatedResult)) { var canvas = document.createElement('canvas'); canvas.setAttribute('style', 'image-rendering: -moz-crisp-edges;' + 'image-rendering: pixelated;'); //canvas.style.imageRendering will be undefined, null or an empty string on unsupported browsers. var tmp = canvas.style.imageRendering; supportsImageRenderingPixelatedResult = defined(tmp) && tmp !== ''; if (supportsImageRenderingPixelatedResult) { imageRenderingValueResult = tmp; } } return supportsImageRenderingPixelatedResult; } function imageRenderingValue() { return supportsImageRenderingPixelated() ? imageRenderingValueResult : undefined; } /** * A set of functions to detect whether the current browser supports * various features. * * @exports FeatureDetection */ var FeatureDetection = { isChrome : isChrome, chromeVersion : chromeVersion, isSafari : isSafari, safariVersion : safariVersion, isWebkit : isWebkit, webkitVersion : webkitVersion, isInternetExplorer : isInternetExplorer, internetExplorerVersion : internetExplorerVersion, isEdge : isEdge, edgeVersion : edgeVersion, isFirefox : isFirefox, firefoxVersion : firefoxVersion, isWindows : isWindows, hardwareConcurrency : defaultValue(theNavigator.hardwareConcurrency, 3), supportsPointerEvents : supportsPointerEvents, supportsImageRenderingPixelated: supportsImageRenderingPixelated, imageRenderingValue: imageRenderingValue }; /** * Detects whether the current browser supports the full screen standard. * * @returns {Boolean} true if the browser supports the full screen standard, false if not. * * @see Fullscreen * @see {@link http://dvcs.w3.org/hg/fullscreen/raw-file/tip/Overview.html|W3C Fullscreen Living Specification} */ FeatureDetection.supportsFullscreen = function() { return Fullscreen.supportsFullscreen(); }; /** * Detects whether the current browser supports typed arrays. * * @returns {Boolean} true if the browser supports typed arrays, false if not. * * @see {@link http://www.khronos.org/registry/typedarray/specs/latest/|Typed Array Specification} */ FeatureDetection.supportsTypedArrays = function() { return typeof ArrayBuffer !== 'undefined'; }; /** * Detects whether the current browser supports Web Workers. * * @returns {Boolean} true if the browsers supports Web Workers, false if not. * * @see {@link http://www.w3.org/TR/workers/} */ FeatureDetection.supportsWebWorkers = function() { return typeof Worker !== 'undefined'; }; return FeatureDetection; });
    JavaScript
    0.000001
    @@ -742,49 +742,78 @@ -if (/Google Inc/.test(theNavigator.vendor +// Edge contains Chrome in the user agent too%0A if (!isEdge( )) %7B @@ -1394,24 +1394,32 @@ Chrome +and Edge contain -s Safari @@ -1470,16 +1470,29 @@ ome() && + !isEdge() && (/ Safa
    9daee0f6354a660f6ec6e33aeb9669a11b8a7c89
    add ts and tsx to extension config
    .storybook/main.js
    .storybook/main.js
    const path = require("path"); const glob = require("glob"); const projectRoot = path.resolve(__dirname, "../"); const ignoreTests = process.env.IGNORE_TESTS === "true"; const isChromatic = !ignoreTests; const getStories = () => glob.sync(`${projectRoot}/src/**/*.stories.@(js|mdx)`, { ...(ignoreTests && { ignore: `${projectRoot}/src/**/*-test.stories.@(js|mdx)`, }), }); module.exports = { stories: (list) => [ ...list, "./welcome-page/welcome.stories.js", "../docs/*.stories.mdx", ...getStories(), ], addons: [ "@storybook/addon-actions", "@storybook/addon-docs", "@storybook/addon-controls", "@storybook/addon-viewport", "@storybook/addon-a11y", "@storybook/addon-google-analytics", "@storybook/addon-links", "@storybook/addon-toolbars", "./theme-selector/register", ], webpackFinal: async (config, { configType }) => { config.resolve = { alias: { helpers: path.resolve(__dirname, "__helpers__/"), }, extensions: [".js"], }; // Workaround to stop hashes being added to font filenames, so we can pre-load them config.module.rules.find((rule) => rule.test.toString().includes("woff2") ).options.name = "static/media/[name].[ext]"; return config; }, ...(isChromatic && { previewHead: (head) => ` ${head} <meta name="robots" content="noindex"> `, managerHead: (head) => ` ${head} <meta name="robots" content="noindex"> `, }), };
    JavaScript
    0
    @@ -1027,16 +1027,31 @@ : %5B%22.js%22 +, %22.tsx%22, %22.ts%22 %5D,%0A %7D
    678c011c7125fb12e22d86678cc0d05794db8135
    Add default response to search
    controllers/people/index.js
    controllers/people/index.js
    'use strict'; var _ = require('underscore'), ccb = require('../../lib/ccb'), peopleModel = require('../../models/people'), Promise = require('bluebird'); module.exports = function (router) { router.get('/', function (req, res) { if(process.env.NODE_ENV === 'production' && req.query.token !== process.env.slack_token) { //make this an express middleware res.send('An Error Occurred: invalid token'); } if(!req.query.text) { res.send('An Error Occurred: invalid input'); } var obj = {}, names = decodeURI(req.query.text).split(' '), individuals = []; obj.first_name = names[0]; obj.last_name = names[1]; peopleModel.search({ first_name: names[0], last_name: names[1] }).then(function(first) { individuals = individuals.concat(ccb.parseIndividuals(first)); if (individuals.length === 0) { return peopleModel.search({ last_name: names[0] //if no first names found, search the name as a last name }); } else { return Promise.resolve(null); } }).then(function(last) { individuals = individuals.concat(ccb.parseIndividuals(last)); console.log(ccb.parseIndividuals(last)); var output = _.map(individuals, function(individual) { return ccb.individualToString(individual); }).join(', '); res.send(output); }) }); };
    JavaScript
    0.000001
    @@ -39,20 +39,17 @@ core'),%0A - +%09 ccb = re @@ -72,20 +72,17 @@ /ccb'),%0A - +%09 peopleMo @@ -119,20 +119,17 @@ ople'),%0A - +%09 Promise @@ -189,20 +189,17 @@ uter) %7B%0A - +%09 router.g @@ -228,24 +228,18 @@ res) %7B%0A - +%09%09 if(proce @@ -355,28 +355,19 @@ dleware%0A - +%09%09%09 res.send @@ -404,35 +404,23 @@ oken');%0A - %7D%0A%0A +%09%09%7D%0A%0A%09%09 if(!req. @@ -433,28 +433,19 @@ text) %7B%0A - +%09%09%09 res.send @@ -486,27 +486,15 @@ ');%0A - %7D%0A%0A +%09%09%7D%0A%0A%09%09 var @@ -503,28 +503,19 @@ j = %7B%7D,%0A - +%09%09%09 names = @@ -552,28 +552,19 @@ t(' '),%0A - +%09%09%09 individu @@ -574,24 +574,18 @@ = %5B%5D;%0A%0A - +%09%09 obj.firs @@ -603,24 +603,18 @@ mes%5B0%5D;%0A - +%09%09 obj.last @@ -632,24 +632,18 @@ es%5B1%5D;%0A%0A - +%09%09 peopleMo @@ -655,28 +655,19 @@ earch(%7B%0A - +%09%09%09 first_na @@ -680,28 +680,19 @@ mes%5B0%5D,%0A - +%09%09%09 last_nam @@ -703,24 +703,18 @@ ames%5B1%5D%0A - +%09%09 %7D).then( @@ -727,36 +727,27 @@ on(first) %7B%0A - +%09%09%09 individuals @@ -797,28 +797,19 @@ irst));%0A - +%09%09%09 if (indi @@ -832,32 +832,20 @@ == 0) %7B%0A - +%09%09%09%09 return p @@ -868,28 +868,13 @@ h(%7B%0A - +%09%09%09%09%09 last @@ -951,65 +951,32 @@ ame%0A - %7D);%0A %7D else %7B%0A +%09%09%09%09%7D);%0A%09%09%09%7D else %7B%0A%09%09%09%09 retu @@ -1005,30 +1005,15 @@ l);%0A - %7D%0A +%09%09%09%7D%0A%09%09 %7D).t @@ -1033,28 +1033,19 @@ last) %7B%0A - +%09%09%09 individu @@ -1102,73 +1102,11 @@ ));%0A - console.log(ccb.parseIndividuals(last));%0A +%09%09%09 var @@ -1160,24 +1160,12 @@ ) %7B%0A - +%09%09%09%09 retu @@ -1203,28 +1203,19 @@ idual);%0A - +%09%09%09 %7D).join( @@ -1225,20 +1225,11 @@ ');%0A - +%09%09%09 res. @@ -1243,26 +1243,56 @@ tput -);%0A %7D)%0A + %7C%7C %22Couldn't find anyone by that name%22);%0A%09%09%7D)%0A%09 %7D);%0A
    dbdad7ffd14a30ccfe0553721ca7d46a9d257a6d
    remove full browser width from web components wrapper
    src/BookReaderComponent/BookReaderComponent.js
    src/BookReaderComponent/BookReaderComponent.js
    /** * BookReaderTemplate to load BookNavigator components */ import { LitElement, html, css } from 'lit-element'; import '../ItemNavigator/ItemNavigator.js' import '../BookNavigator/BookNavigator.js' export class BookReader extends LitElement { static get properties() { return { base64Json: { type: String }, baseHost: { type: String }, }; } constructor() { super(); this.base64Json = ''; this.baseHost = 'https://archive.org'; } firstUpdated() { this.fetchData(); } /** * Fetch metadata response from public metadata API * convert response to base64 data * set base64 data to props */ async fetchData() { const ocaid = new URLSearchParams(location.search).get('ocaid'); const response = await fetch(`${this.baseHost}/metadata/${ocaid}`); const bookMetadata = await response.json(); const jsonBtoa = btoa(JSON.stringify(bookMetadata)); this.setBaseJSON(jsonBtoa); } /** * Set base64 data to prop * @param {string} value - base64 string format */ setBaseJSON(value) { this.base64Json = value; } render() { return html` <div class="ia-bookreader"> <item-navigator itemType="bookreader" basehost=${this.baseHost} item=${this.base64Json}> <div slot="bookreader"> <slot name="bookreader"></slot> </div> </item-navigator> </div> `; } static get styles() { return css` :host { display: block; --primaryBGColor: var(--black, #000); --secondaryBGColor: #222; --tertiaryBGColor: #333; --primaryTextColor: var(--white, #fff); --primaryCTAFill: #194880; --primaryCTABorder: #c5d1df; --secondaryCTAFill: #333; --secondaryCTABorder: #999; --primaryErrorCTAFill: #e51c26; --primaryErrorCTABorder: #f8c6c8; } .ia-bookreader { background-color: var(--primaryBGColor); position: relative; width: 100vw; height: auto; } item-navigator { display: block; width: 100%; color: var(--primaryTextColor); --menuButtonLabelDisplay: block; --menuWidth: 320px; --menuSliderBg: var(--secondaryBGColor); --activeButtonBg: var(--tertiaryBGColor); --animationTiming: 100ms; --iconFillColor: var(--primaryTextColor); --iconStrokeColor: var(--primaryTextColor); --menuSliderHeaderIconHeight: 2rem; --menuSliderHeaderIconWidth: 2rem; --iconWidth: 2.4rem; --iconHeight: 2.4rem; --shareLinkColor: var(--primaryTextColor); --shareIconBorder: var(--primaryTextColor); --shareIconBg: var(--secondaryBGColor); --activityIndicatorLoadingDotColor: var(--primaryTextColor); --activityIndicatorLoadingRingColor: var(--primaryTextColor); } `; } } window.customElements.define("ia-bookreader", BookReader);
    JavaScript
    0
    @@ -2016,30 +2016,8 @@ ve;%0A - width: 100vw;%0A
    0814008f10a5317bc7d60044d2e449134c19c740
    use yarn publish
    scripts/publish-to-npm.js
    scripts/publish-to-npm.js
    'use strict'; const yargs = require('yargs'); const execa = require('execa'); const util = require('util'); const glob = util.promisify(require('glob')); const fs = require('fs-extra'); const path = require('path'); const rootDir = process.cwd(); let argv = yargs .usage( '$0 [-t|--tag]' ) .command({ command: '*', builder: yargs => { return yargs .option('t', { alias: 'tag', describe: 'the npm dist-tag', default: 'latest', type: 'string', }); }, handler: async argv => { const packageJsonData = JSON.parse( await fs.readFile(path.join(rootDir, 'package.json')) ); const packageDirs = ( await Promise.all(packageJsonData.workspaces.map((item) => glob(item))) ).flat(); await Promise.all(packageDirs.map((item) => { const publishCmd = `npm publish --tag ${argv.tag}`; return execa(publishCmd, { stdio: 'inherit', cwd: path.join(rootDir, item) }); })) }, }) .help().argv;
    JavaScript
    0
    @@ -850,19 +850,20 @@ hCmd = %60 -npm +yarn publish
    978d2a42b5ff4d5edcf58e621030253d60d5c2b0
    Fix host computation in Hacker News Answer Generator
    src/answer_generators/hacker_news/generator.js
    src/answer_generators/hacker_news/generator.js
    /*jslint continue: true, devel: true, evil: true, indent: 2, nomen: true, plusplus: true, regexp: true, rhino: true, sloppy: true, sub: true, unparam: true, vars: true, white: true */ /*global _, HostAdapter, hostAdapter */ var ICON_URL = 'https://news.ycombinator.com/favicon.ico'; var BASE_RELEVANCE = 0.4; function hostForUrl(url) { var startIndex = url.indexOf('//') + 2; var endIndex = url.indexOf('/', startIndex); return url.substring(startIndex, endIndex); } function makeResponseHandler(q, context) { 'use strict'; return function (responseText, response) { 'use strict'; console.log('Got response'); if (response.statusCode !== 200) { console.error('Got bad status code ' + response.statusCode); return null; } var resultObject = JSON.parse(responseText); var hits = resultObject.hits; console.log('Got ' + hits.length + ' hits'); if (hits.length === 0) { return []; } var outputLinks = false; if (!context.isSuggestionQuery || (context.settings.outputLinks !== 'true')) { var xml = <s><![CDATA[ <!doctype html> <html> <title>Hacker News Search Results</title> <body> <h3>Hacker News search results for &quot;<%= q %>&quot;:</h3> <ul> <% _(hits).each(function (hit) { if (hit.url) { %> <li> <a href="<%= hit.url %>" target="_top"><%= hit.title || '(No title)' %></a> <% if (hit.story_text) { %> : <%= _(hit.story_text).prune(100) %> <% } %> &nbsp;<small>(<%= hostForUrl(hit.url) %>)</small> </li> <% } }); %> </ul> <p> <small>Search results provided by <a href="https://www.algolia.com/" target="_top">Algolia</a>.</small> </p> </body> </html> ]]></s>; var template = xml.toString(); var model = { q: q, hits: hits, hostForUrl: hostForUrl }; var content = ejs.render(template, model); return [{ label: 'Hacker News Search', uri: 'https://hn.algolia.com/#!/story/forever/0/' + encodeURIComponent(q), tooltip: 'Hacker News Search results for "' + _(q).escapeHTML() + '"', iconUrl: ICON_URL, relevance: BASE_RELEVANCE, content: content, serverSideSanitized: true, categories: [{value: 'programming', weight: 1.0}, {value: 'business', weight: 0.5}] }]; } else { return _(hits).chain().filter(function (hit) { return !!hit.url; }).map(function (hit) { console.log('got hit url = ' + hit.url); return { label : hit.title || '', iconUrl: ICON_URL, uri : hit.url, // embeddable: false, let solveforall guess summaryHtml: _(hit.story_text || '').escapeHTML(), relevance: BASE_RELEVANCE * (1.0 - Math.pow(2.0, -Math.max((hit.points || 0), 1) * 0.01)) }; }).value(); } }; } function generateResults(recognitionResults, q, context) { 'use strict'; if (context.isSuggestionQuery) { return []; } var url = 'https://hn.algolia.com/api/v1/search'; var request = hostAdapter.makeWebRequest(url, { data: { query: q } }); request.send('makeResponseHandler(' + JSON.stringify(q) + ',' + JSON.stringify(context) + ')'); return HostAdapter.SUSPEND; }
    JavaScript
    0.00014
    @@ -419,16 +419,208 @@ tIndex); + %0A var endIndex2 = url.indexOf('?', startIndex);%0A %0A if (endIndex %3C 0) %7B%0A endIndex = endIndex2; %0A %0A if (endIndex %3C 0) %7B%0A return url.substring(startIndex);%0A %7D %0A %7D %0A %0A retur
    55524174ef76c23b1e1917e57cbe863fee3acd8e
    Resolve #67: Add channelOptions option to ChannelPool constructor
    lib/ChannelPool.js
    lib/ChannelPool.js
    /*jslint node: true, indent: 2, unused: true, maxlen: 80, camelcase: true */ /* * stompit.ChannelPool * Copyright (c) 2014 Graham Daws <[email protected]> * MIT licensed */ var Channel = require('./Channel'); var assign = require('object-assign'); function ChannelPool(connectFailover, options) { if (!(this instanceof ChannelPool)) { var object = Object.create(ChannelPool.prototype); ChannelPool.apply(object, arguments); return object; } options = assign({ minChannels: 1, minFreeChannels: 1, maxChannels: Infinity, freeExcessTimeout: null, requestChannelTimeout: null }, options || {}); this._connectFailover = connectFailover; this._minChannels = options.minChannels; this._minFreeChannels = Math.min(options.minFreeChannels, this._minChannels); this._maxChannels = options.maxChannels; this._channels = []; this._freeChannels = []; this._freeExcessTimeout = options.freeExcessTimeout; this._freeExcessTimeouts = []; this._requestChannelTimeout = options.requestChannelTimeout; this._closed = false; if (this._requestChannelTimeout !== null){ this._channelRequests = []; } for (var i = 0; i < this._minChannels; i++) { this._allocateFreeChannel(); } } ChannelPool.prototype._createChannel = function() { return new Channel(this._connectFailover, { alwaysConnected: true }); }; ChannelPool.prototype._allocateFreeChannel = function() { if (this._channels.length >= this._maxChannels) { return; } var channel = this._createChannel(); this._channels.push(channel); this._freeChannels.push(channel); return channel; }; ChannelPool.prototype._deallocateChannel = function(channel) { channel.close(); var index = this._channels.indexOf(channel); if (index !== -1) { this._channels.splice(index, 1); } }; ChannelPool.prototype._addExcessTimeout = function() { if (this._freeChannels.length <= this._minChannels) { return; } var self = this; var close = function() { var channel = self._freeChannels.shift(); if (!channel.isEmpty()) { self._startIdleListen(channel); return; } self._deallocateChannel(channel); }; if (this._freeExcessTimeout === null) { close(); return; } this._freeExcessTimeouts.push(setTimeout(function() { self._freeExcessTimeouts.shift(); if (self._freeChannels.length > self._minChannels) { close(); } }, this._freeExcessTimeout)); }; ChannelPool.prototype._hasChannelRequestTimeout = function() { return typeof this._requestChannelTimeout == 'number'; }; ChannelPool.prototype._startIdleListen = function(channel) { var self = this; channel.once('idle', function(){ if (self._closed) { self._deallocateChannel(channel); return; } if (self._hasChannelRequestTimeout() && self._channelRequests.length > 0) { var channelRequest = self._channelRequests.shift(); clearTimeout(channelRequest.timeout); self._startIdleListen(channel); channelRequest.callback(null, channel); return; } self._freeChannels.push(channel); self._addExcessTimeout(); }); }; ChannelPool.prototype._timeoutChannelRequest = function(callback) { this._channelRequests.shift(); callback(new Error('failed to allocate channel')); }; ChannelPool.prototype.channel = function(callback) { if (this._closed) { process.nextTick(function() { callback(new Error('channel pool closed')); }); return; } if (this._freeChannels.length === 0 && !this._allocateFreeChannel()) { if (this._hasChannelRequestTimeout()) { var timeout = setTimeout( this._timeoutChannelRequest.bind(this, callback), this._requestChannelTimeout ); this._channelRequests.push({ timeout: timeout, callback: callback }); } else { process.nextTick(function() { callback(new Error('failed to allocate channel')); }); } return; } var channel = this._freeChannels.shift(); if (this._freeExcessTimeouts.length > 0) { clearTimeout(this._freeExcessTimeouts.shift()); } if (this._freeChannels.length < this._minFreeChannels) { this._allocateFreeChannel(); } this._startIdleListen(channel); process.nextTick(function() { callback(null, channel); }); }; ChannelPool.prototype.close = function() { this._closed = true; this._channels.forEach(function(channel) { channel.close(); }); this._channels = []; this._freeChannels = []; if (this._channelRequests) { this._channelRequests.forEach(function(request) { clearTimeout(request.timeout); request.callback(new Error('channel pool closed')); }); this._channelRequests = []; } }; module.exports = ChannelPool;
    JavaScript
    0
    @@ -661,16 +661,41 @@ ut: null +,%0A%0A channelOptions: %7B%7D %0A %0A @@ -949,32 +949,119 @@ annels = %5B%5D;%0A %0A + this._channelOptions = assign(%7B%7D, options.channelOptions, %7BalwaysConnected: true%7D);%0A%0A this._freeChan @@ -1477,18 +1477,16 @@ ion() %7B%0A - %0A retur @@ -1526,39 +1526,28 @@ er, -%7B%0A alwaysConnected: true%0A %7D +this._channelOptions );%0A%7D
    709f9ae84a27cca1e4b4c540237a7c75cddd5383
    fix line endings and update build 2
    Jakefile.js
    Jakefile.js
    var build = require('./build/build.js'), lint = require('./build/hint.js'); var COPYRIGHT = "/*\r\n Copyright (c) 2010-2011, CloudMade, Vladimir Agafonkin\n" + " Leaflet is a modern open-source JavaScript library for interactive maps.\n" + " http://leaflet.cloudmade.com\r\n*/\r\n"; desc('Check Leaflet source for errors with JSHint'); task('lint', function () { var files = build.getFiles(); console.log('Checking for JS errors...'); var errorsFound = lint.jshint(files); if (errorsFound > 0) { console.log(errorsFound + ' error(s) found.\n'); fail(); } else { console.log('\tCheck passed'); } }); desc('Combine and compress Leaflet source files'); task('build', ['lint'], function (compsBase32, buildName) { var name = buildName || 'custom', path = 'dist/leaflet' + (compsBase32 ? '-' + name : ''); var files = build.getFiles(compsBase32); console.log('Concatenating ' + files.length + ' files...'); var content = build.combineFiles(files); console.log('\tUncompressed size: ' + content.length); build.save(path + '-src.js', COPYRIGHT + content); console.log('\tSaved to ' + path); console.log('Compressing...'); var compressed = COPYRIGHT + build.uglify(content); console.log('\tCompressed size: ' + compressed.length); build.save(path + '.js', compressed); console.log('\tSaved to ' + path); }); task('default', ['build']);
    JavaScript
    0
    @@ -150,16 +150,18 @@ afonkin%5C +r%5C n%22 +%0A
    1c4a59f86ac4e1e062ad061b5850f0175184958e
    Make sure we're only adding labels to lis on the top level
    github.com.js
    github.com.js
    var dotjs_github = {}; dotjs_github.init = function() { dotjs_github.$issues = $('.issues'); var style = '<style>' + '.filter-exclude { margin-top: 10px; }' + '.filter-exclude input {' + ' box-sizing: border-box;' + ' padding: 3px 4px;' + ' width: 100%;' + '}' + '.filter-exclude .minibutton {' + ' display: block;' + ' text-align: center;' + '}' + '.filter-list li {' + ' position: relative;' + '}' + '.filter-list .hide-it {' + ' font-size: 20px;' + ' line-height: 20px;' + ' left: -45px;' + ' position: absolute;' + ' top: 0px;' + '}' + '.filter-list .hide-it.clicked {' + ' color: #ccc;' + '}' + '.filter-list .custom-hidden a:nth-child(2) {' + ' text-decoration: line-through;' + ' opacity: 0.3;' + '}' + '.filter-list .hide-it:hover {' + ' text-decoration: none;' + '}' + '.issues .item.hidden {' + ' display: none;' + '}' + '</style>'; $('body').append( style ); $('.sidebar .filter-item').live('click.dotjs_github', function( e ) { e.preventDefault(); setTimeout( function() { dotjs_github.$issues = $('.issues'); dotjs_github.add_hide_links(); }, 500 ); }); dotjs_github.add_hide_links(); }; dotjs_github.add_hide_links = function() { var $labels = $('.js-color-label-list'); $labels.find('li').prepend('<a href="#" class="hide-it minibutton">☠</a>'); $labels.find('.hide-it').bind('click', function( e ) { e.preventDefault(); e.stopPropagation(); var $el = $(this); var val = $el.next().data('label'); var $issues = dotjs_github.$issues.find('.list-browser-item .label[data-name="' + $.trim( val ) + '"]').closest('tr'); if ( ! $el.hasClass('clicked') ) { $el.addClass('clicked').closest('li').addClass('custom-hidden'); $issues.addClass('hidden'); } else { $el.removeClass('clicked').closest('li').removeClass('custom-hidden'); $issues.removeClass('hidden'); }//end else var count = $('.issues-list').find('.list-browser-item:not(.hidden)').length; var $selected = $('.list-browser-filter-tabs .selected'); $selected.html( parseInt( count, 10 ) + ' ' + $selected.data('filter') + ' issues' ); }); }; dotjs_github.init();
    JavaScript
    0
    @@ -1296,20 +1296,24 @@ $labels. -find +children ('li').p
    5f9703e389ba0ab7471ef4d3f41b9f07b9198f71
    Update throbber test time to avoid test inaccuracies
    test/__playground/throbber.formatted.js
    test/__playground/throbber.formatted.js
    #!/usr/bin/env node 'use strict'; var throbber = require('../../lib/throbber') , interval = require('clock/lib/interval') , format = require('../../lib/index').red; var i = interval(100, true); throbber(i, format); process.stdout.write('START'); setTimeout(i.stop.bind(i), 500);
    JavaScript
    0
    @@ -278,13 +278,13 @@ nd(i), 5 -0 +5 0);%0A
    17b95e4b726a9c59096fe56c20cda3b05bb3acd3
    add new test spec for models
    server/spec/modelSpec.js
    server/spec/modelSpec.js
    import jasmine from 'jasmine'; import Sequelize from 'sequelize'; import expect from 'expect'; import Users from '../models/users'; import Group from '../models/group'; // import GroupMembers from '../models/groupMembers'; // import Messages from '../models/messages'; import db from '../config/db_url.json'; describe('Model test suite', () => { beforeEach((done) => { const sequelize = new Sequelize(db.url); sequelize.authenticate().then(() => { console.log('Connection established'); }) .catch((err) => { console.log('Error occured', err); }); done(); }, 10000); it('I should be able to create a new user with this model', (done) => { Users.sync({ force: true }).then(() => { Users.create({ name: 'Peter', username: 'Ike', email: '[email protected]', password: 'show' }) .then((user) => { if (user) { expect('Ike').toBe(user.dataValues.username); } done(); }).catch((err) => { console.log('Failed', err); done(); }); }); }, 10000); it('I should be able to create a new group with this model', (done) => { Group.sync({ force: true }).then(() => { Group.create({ groupName: 'Zikites', groupCategory: 'Class of 2014', userId: 1 }) .then((group) => { if (group) { expect('Zikites').toNotBe('Zike'); expect('Class of 2014').toBe(group.dataValues.groupCategory); } done(); }); }).catch((err) => { console.log('Failed', err); }); }, 10000); /* it('I should be able to add users to group I created', (done) => { GroupMembers.sync({ force: true }).then(() => { GroupMembers.create({ userId: 1, admin: 1, groupId: 1 }) .then((members) => { if (members) { expect(1).toBe(members.dataValues.userId); } done(); }); }).catch((err) => { console.log('Failed', err); }); }, 10000);*/ }); /* describe('Models test suite', () => { describe('Establish connection to the database', () => { beforeAll((done) => { const sequelize = new Sequelize(db.url); sequelize.authenticate().then(() => { console.log('Connected'); // 'Connected'; }).catch((err) => { if (err) { return 'Unable to connect'; } }); done(); }); }); describe('Users model', () => { beforeEach((done) => { const User = Users.sync({ force: true }).then(() => { Users.create({ name: 'Ebuka', username: 'Bonachristi', email: '[email protected]', password: 'samodu' }) .then((result) => { if (result) { return 'Registered'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('should be able to create a new account', () => { expect(User).to.be.a('Registered'); done(); }); }); }); describe('Create a new group', () => { beforeEach((done) => { const CreateGroup = Group.sync({ force: true }).then(() => { Group.create({}).then((group) => { if (group) { return 'Group Created'; } }).catch((err) => { if (err) { return 'Error occured, group not created'; } }); }); it('Registered users should be able to create a group', () => { expect(CreateGroup).to.be.a('Group Created'); done(); }); }); }); describe('Add registered users to group', () => { beforeEach((done) => { const AddMembers = GroupMembers.sync({ force: true }).then(() => { GroupMembers.create({}).then((users) => { if (users) { return 'Added'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('Users should be added by groups by registered user', () => { expect(AddMembers).to.be.a('Added'); done(); }); }); }); describe('A user should be able to post messages to groups he created', () => { beforeEach((done) => { const post = Messages.sync({ force: true }).then(() => { Messages.create({}).then((message) => { if (message) { return 'Posted'; } }).catch((err) => { if (err) { return 'Failed'; } }); }); it('Should be able to post message to group', () => { expect(post).to.be.a('Posted'); done(); }); }); }); });*/
    JavaScript
    0
    @@ -1904,2664 +1904,4 @@ );%0A%0A -%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A/* describe('Models test suite', () =%3E %7B%0A describe('Establish connection to the database', () =%3E %7B%0A beforeAll((done) =%3E %7B%0A const sequelize = new Sequelize(db.url);%0A sequelize.authenticate().then(() =%3E %7B%0A console.log('Connected');%0A // 'Connected';%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Unable to connect';%0A %7D%0A %7D);%0A done();%0A %7D);%0A %7D);%0A describe('Users model', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const User = Users.sync(%7B force: true %7D).then(() =%3E %7B%0A Users.create(%7B name: 'Ebuka', username: 'Bonachristi', email:%0A '[email protected]', password: 'samodu' %7D)%0A .then((result) =%3E %7B%0A if (result) %7B%0A return 'Registered';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('should be able to create a new account', () =%3E %7B%0A expect(User).to.be.a('Registered');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Create a new group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const CreateGroup = Group.sync(%7B force: true %7D).then(() =%3E %7B%0A Group.create(%7B%7D).then((group) =%3E %7B%0A if (group) %7B%0A return 'Group Created';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Error occured, group not created';%0A %7D%0A %7D);%0A %7D);%0A it('Registered users should be able to create a group', () =%3E %7B%0A expect(CreateGroup).to.be.a('Group Created');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('Add registered users to group', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const AddMembers = GroupMembers.sync(%7B force: true %7D).then(() =%3E %7B%0A GroupMembers.create(%7B%7D).then((users) =%3E %7B%0A if (users) %7B%0A return 'Added';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Users should be added by groups by registered user', () =%3E %7B%0A expect(AddMembers).to.be.a('Added');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A describe('A user should be able to post messages to groups he created', () =%3E %7B%0A beforeEach((done) =%3E %7B%0A const post = Messages.sync(%7B force: true %7D).then(() =%3E %7B%0A Messages.create(%7B%7D).then((message) =%3E %7B%0A if (message) %7B%0A return 'Posted';%0A %7D%0A %7D).catch((err) =%3E %7B%0A if (err) %7B%0A return 'Failed';%0A %7D%0A %7D);%0A %7D);%0A it('Should be able to post message to group', () =%3E %7B%0A expect(post).to.be.a('Posted');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A%7D);*/%0A
    aa10cda61021ef3d32c301755e594faecbf24f2e
    Add tests to <Text>
    src/Text/__tests__/Text.test.js
    src/Text/__tests__/Text.test.js
    import React from 'react'; import ReactDOM from 'react-dom'; import Text from '../Text'; it('renders without crashing', () => { const div = document.createElement('div'); const element = ( <Text align="right" basic="Basic text" aside="Aside text" tag="Tag" /> ); ReactDOM.render(element, div); });
    JavaScript
    0
    @@ -65,26 +65,138 @@ ort -Text from '../Text +%7B shallow %7D from 'enzyme';%0A%0Aimport StatusIcon from 'src/StatusIcon';%0Aimport Text from '../Text';%0Aimport BasicRow from '../BasicRow ';%0A%0A @@ -474,12 +474,1709 @@ div);%0A%7D);%0A%0A +it('renders using %3CBasicRow%3E with BEM className', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22text%22 /%3E);%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(wrapper.children()).toHaveLength(1);%0A expect(rowWrapper.exists()).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__row')).toBeTruthy();%0A expect(rowWrapper.hasClass('ic-text__basic')).toBeTruthy();%0A%7D);%0A%0Ait('passing %22basic%22, %22tag%22 and %22stateIcon%22 to %3CBasicRow%3E', () =%3E %7B%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D /%3E%0A );%0A const rowWrapper = wrapper.find(BasicRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('takes custom %3CBasicRow%3E and passes the same props to it', () =%3E %7B%0A const FooRow = () =%3E %3Cdiv /%3E;%0A%0A const customRow = %3CFooRow /%3E;%0A const icon = %3CStatusIcon status=%22loading%22 /%3E;%0A%0A const wrapper = shallow(%0A %3CText%0A basic=%22Basic text%22%0A tag=%22Tag%22%0A stateIcon=%7Bicon%7D%0A basicRow=%7BcustomRow%7D /%3E%0A );%0A const rowWrapper = wrapper.find(FooRow);%0A%0A expect(rowWrapper.prop('basic')).toBe('Basic text');%0A expect(rowWrapper.prop('tag')).toBe('Tag');%0A expect(rowWrapper.prop('stateIcon')).toEqual(icon);%0A%7D);%0A%0Ait('renders aside text', () =%3E %7B%0A const wrapper = shallow(%3CText basic=%22Basic%22 aside=%22Aside%22 /%3E);%0A%0A expect(wrapper.children()).toHaveLength(2);%0A expect(wrapper.childAt(1).hasClass('ic-text__aside')).toBeTruthy();%0A expect(wrapper.childAt(1).text()).toBe('Aside');%0A%7D);%0A
    63c03ef48a1fc0dbeec02943909bc9bc26ad7a2c
    Mark TODO
    lib/api/register_user.js
    lib/api/register_user.js
    var data = require(__dirname+'/../data/'); var sql = require(__dirname +'/../data/sequelize.js'); var config = require(__dirname+'/../../config/environment.js'); var validator = require(__dirname+'/../validator.js'); var RippleRestClient = require('ripple-rest-client'); var uuid = require('node-uuid'); /** * Register a User * - creates external account named "default" * - creates ripple address as provided * @require data, sql, config * @param {string} name * @param {string} rippleAddress * @param {string} password * @returns {User}, {ExternalAccount}, {RippleAddress} */ function registerUser(opts, fn) { var userOpts = { name: opts.name, password: opts.password, address: opts.ripple_address, secret: opts.secret, currency: opts.currency, amount: opts.amount }; if (!validator.isRippleAddress(opts.ripple_address)) { fn({ ripple_address: 'invalid ripple address' }); return; } sql.transaction(function(sqlTransaction){ data.users.create(userOpts, function(err, user) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } var addressOpts = { user_id: user.id, address: opts.ripple_address, managed: false, type: 'independent' }; data.rippleAddresses.create(addressOpts, function(err, ripple_address) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } data.externalAccounts.create({ name: 'default', user_id: user.id, address:addressOpts.address, type:addressOpts.type }, function(err, account){ if (err) { fn(err, null); return; } var addressOpts = { user_id: user.id, address: config.get('COLD_WALLET'), managed: true, type: 'hosted', tag: account.id }; // We might be missing the cold wallet if (addressOpts.address) { // CS Fund user account with XRP var rippleRootRestClient = new RippleRestClient({ api: config.get('RIPPLE_REST_API'), account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh' }); var options = { secret: 'masterpassphrase', client_resource_id: uuid.v4(), payment: { destination_account: userOpts.address, source_account: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh', destination_amount: { value: '60', currency: 'XRP', issuer: '' } } }; rippleRootRestClient.sendAndConfirmPayment(options, function(error, response){ if (error || (response.success != true)) { logger.error('rippleRestClient.sendAndConfirmPayment', error); return fn(error, null); } // CS Set trust line from user account to cold wallet. We should let users to this manually. var coldWallet = config.get('COLD_WALLET'); var rippleRestClient = new RippleRestClient({ api: config.get('RIPPLE_REST_API'), account:userOpts.address }); rippleRestClient.setTrustLines({ account: userOpts.address, secret: userOpts.secret, limit: userOpts.amount, currency: userOpts.currency, counterparty: coldWallet, account_allows_rippling: true }, fn); }); // CS Create in DB data.rippleAddresses.create(addressOpts, function(err, hosted_address) { if (err) { sqlTransaction.rollback(); fn(err, null); return; } var response = user.toJSON(); response.ripple_address = ripple_address; response.external_account = account; response.hosted_address = hosted_address; sqlTransaction.commit(); fn(err, response); }); } }); }); }); }); } module.exports = registerUser;
    JavaScript
    0.000004
    @@ -3682,16 +3682,83 @@ e in DB%0A + // TODO the server.js process is restarted here - why?%0A
    847544231b0819913f22e2fe437f5cf475542962
    fix code identity
    server/streak/service.js
    server/streak/service.js
    const rp = require('request-promise'); const cheerio = require('cheerio'); const getStreakBody = (userName) => { var options = { uri: `https://github.com/users/${userName}/contributions`, transform: function (body) { return cheerio.load(body); } }; return rp(options) .then(function ($) { const currentDateStreak = []; let currentStreak = []; $('.day').filter(function (i, el) { return $(this).prop('data-count') !== '0'; }).each(function (index) { const date = new Date($(this).prop('data-date')); date.setHours(0, 0, 0, 0); if (currentDateStreak[index - 1]) { const tempDate = currentDateStreak[index - 1].date; tempDate.setDate(tempDate.getDate() + 1); tempDate.setHours(0, 0, 0, 0); if (date.getTime() === tempDate.getTime()) { if ($(this).prop('fill') != '#ebedf0') { currentStreak.push({ date: date, commit: $(this).prop('data-count') }); } } else { currentStreak = []; } } currentDateStreak.push({ date: date }); }); return currentStreak; }) .catch( (err) => { console.log('errror', err); }); }; module.exports = { getStreakBody };
    JavaScript
    0.000717
    @@ -799,56 +799,8 @@ ) %7B%0A -%09%09%09%09%09%09if ($(this).prop('fill') != '#ebedf0') %7B%0A%09 %09%09%09%09 @@ -818,25 +818,24 @@ reak.push(%7B%0A -%09 %09%09%09%09%09%09%09date: @@ -848,17 +848,16 @@ %0A%09%09%09%09%09%09%09 -%09 commit: @@ -893,21 +893,12 @@ %09%09%09%09 -%09 %7D);%0A -%09%09%09%09%09%09%7D%0A %09%09%09%09 @@ -1046,17 +1046,16 @@ %09.catch( - (err) =%3E @@ -1076,17 +1076,16 @@ log('err -r or', err @@ -1097,13 +1097,12 @@ %7D);%0A + %7D;%0A%0A -%0A modu
    5418e50f4d56f3f700c9ecc745c3d1d3e25bbfc9
    Add extra named-chunks test cases for variations with require.ensure error callback present.
    test/cases/chunks/named-chunks/index.js
    test/cases/chunks/named-chunks/index.js
    it("should handle named chunks", function(done) { var sync = false; require.ensure([], function(require) { require("./empty?a"); require("./empty?b"); testLoad(); sync = true; process.nextTick(function() { sync = false; }); }, "named-chunk"); function testLoad() { require.ensure([], function(require) { require("./empty?c"); require("./empty?d"); sync.should.be.ok(); done(); }, "named-chunk"); } }); it("should handle empty named chunks", function(done) { var sync = false; require.ensure([], function(require) { sync.should.be.ok(); }, "empty-named-chunk"); require.ensure([], function(require) { sync.should.be.ok(); done(); }, "empty-named-chunk"); sync = true; setImmediate(function() { sync = false; }); });
    JavaScript
    0
    @@ -757,12 +757,977 @@ e;%0A%09%7D);%0A%7D);%0A +%0Ait(%22should handle named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?a%22);%0A require(%22./empty?b%22);%0A testLoad();%0A sync = true;%0A process.nextTick(function() %7B%0A sync = false;%0A %7D);%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A function testLoad() %7B%0A require.ensure(%5B%5D, function(require) %7B%0A require(%22./empty?c%22);%0A require(%22./empty?d%22);%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22named-chunk%22);%0A %7D%0A%7D);%0A%0Ait(%22should handle empty named chunks when there is an error callback%22, function(done) %7B%0A var sync = false;%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A require.ensure(%5B%5D, function(require) %7B%0A sync.should.be.ok();%0A done();%0A %7D, function(error) %7B%7D, %22empty-named-chunk%22);%0A sync = true;%0A setImmediate(function() %7B%0A sync = false;%0A %7D);%0A%7D);%0A
    4acca781206921d81fb4dd1b05df11920951621c
    Fix formatting
    cla_public/static-src/javascripts/modules/form-errors.js
    cla_public/static-src/javascripts/modules/form-errors.js
    (function() { 'use strict'; moj.Modules.FormErrors = { init: function() { _.bindAll(this, 'postToFormErrors', 'onAjaxSuccess', 'onAjaxError'); this.bindEvents(); this.loadTemplates(); }, bindEvents: function() { $('form') .on('submit', this.postToFormErrors) // Focus back on summary if field-error is focused and escape key is pressed .on('keyup', function(e) { var $target = $(e.target); if(e.keyCode === 27 && $target.is('.form-error')) { $target.closest('form').find('> .alert').focus(); } }) .on('blur', '.form-group', function(e) { $(e.target).removeAttr('tabindex'); }); //// Add role=alert on error message when fieldset is focused //.on('focus', 'fieldset.m-error', function(e) { // $(e.target).find('.field-error').attr('role', 'alert'); //}) //// Remove role=alert from error message when fieldset is blurred //.on('blur', 'fieldset.m-error', function(e) { // $(e.target).find('.field-error').removeAttr('role'); //}); $('[type=submit]').on('click', function(e) { var $target = $(e.target); $target.closest('form').attr('submit-name', $target.attr('name')); }); // Focus on field with error $('#content').on('click', '.error-summary a', function(e) { e.preventDefault(); var targetId = e.target.href.replace(/.*#/, '#'); if(targetId.length < 2) { return; } var $target = $(targetId); $('html, body').animate({ scrollTop: $target.offset().top - 20 }, 300, function() { $target.attr('tabindex', -1).focus(); }); }); }, postToFormErrors: function(e) { this.$form = $(e.target); // Return if button has a name, which is attached as form attribute on click // (assuming secondary buttons) if(this.$form.attr('submit-name') || this.$form.attr('method') && this.$form.attr('method').toLowerCase() === 'get') { return; } if (this.$form.length) { e.preventDefault(); e.stopPropagation(); $.ajax({ type: 'OPTIONS', url: '', contentType: 'application/x-www-form-urlencoded', data: this.$form.serialize() }) .done(this.onAjaxSuccess) .fail(this.onAjaxError); } }, onAjaxSuccess: function(errors) { if (!$.isEmptyObject(errors)) { this.loadErrors(errors); var errorBanner = $('.alert-error:visible:first'); if(!errorBanner.length) { return; } $('html, body').animate({ scrollTop: errorBanner.offset().top - 20 }, 300, function() { errorBanner.attr({'tabindex': -1}).focus(); }); } else { this.$form.off('submit'); this.$form.submit(); } }, onAjaxError: function() { this.$form.off('submit'); this.$form.submit(); }, formatErrors: function(errors) { var errorFields = {}; (function fieldName (errorsObj, prefix) { prefix = (typeof prefix === 'undefined')? '': prefix + '-'; for (var key in errorsObj) { var field = prefix + key; if ($.isArray(errorsObj[key])) { errorFields[field] = errorsObj[key]; } else { fieldName(errorsObj[key], field); } } })(errors); return errorFields; }, createErrorSummary: function() { var errorSummary = []; // Loop through errors on the page to retain the fields order $('.form-error').map(function() { var $this = $(this); if(!this.id || $this.hasClass('s-hidden') || $this.parent().hasClass('s-hidden')) { return; } var name = this.id.replace(/^field-/, ''); errorSummary.push({ label: $this.find('> legend, > .form-group-label').text(), name: name, errors: $this.find('> .field-error p').map(function() { return $(this).text(); }) }); }); return errorSummary; }, loadErrors: function(errors) { var errorFields = this.formatErrors(errors); var self = this; this.clearErrors(); function addErrors(errors, fieldName) { if (_.isString(errors[0])) { $('#field-' + fieldName) .addClass('form-error') .attr({ 'aria-invalid': true, 'aria-describedby': 'error-' + fieldName }); var label = $('#field-label-' + fieldName); label.after(self.fieldError({ errors: errors, fieldName: fieldName })); } else if(_.isObject(errors[0]) && !_.isArray(errors[0])) { // Multiple forms (e.g. properties) _.each(errors, function(errors, i) { _.each(errors, function(subformErrors, subformFieldName) { addErrors(subformErrors, fieldName + '-' + i + '-' + subformFieldName); }); }); } else { _.each(errors, function(subformErrors) { addErrors(subformErrors[1], fieldName + '-' + subformErrors[0]); }); } } _.each(errorFields, addErrors); if(this.$form.data('error-banner') !== false) { this.$form.prepend(this.mainFormError({ errors: this.createErrorSummary()})); } }, loadTemplates: function() { this.mainFormError = _.template($('#mainFormError').html()); this.fieldError = _.template($('#fieldError').html()); }, clearErrors: function() { $('.form-row.field-error').remove(); $('.alert.alert-error').remove(); $('.form-error') .removeClass('form-error') .removeAttr('aria-invalid'); } }; }());
    JavaScript
    0.000029
    @@ -3240,12 +3240,14 @@ ed') + ? '' + : pr
    ce9b5866133de731e00202a8faa19f7de1ecbd38
    Fix in category filter popup
    cityproblems/site/static/site/js/index.js
    cityproblems/site/static/site/js/index.js
    var mainPageViewCtrl = function ($scope, $http, $route) { "use strict"; $scope.showMenu = false; $scope.alerts=[]; $scope.$on('$routeChangeSuccess', function(next, current) { if((current.params.reportBy != $scope.reportBy || current.params.category != $scope.category) && (typeof current.params.reportBy != "undefined" && typeof current.params.category != "undefined")) { $scope.reportBy = current.params.reportBy; $scope.category = current.params.category; loadMarkers(); } }); $scope.init=function(categories) { $scope.categories = angular.fromJson(categories); $scope.tmpCategory = "all"; } $scope.$watch("category", function(category, oldValue) { if(category != oldValue) for(var i=0;i<$scope.categories.length;++i) if($scope.categories[i]["url_name"] == category) { $scope.categoryTitle = $scope.categories[i].title; break; } } ) function clearMap() { if(!$scope.markers) { $scope.markers=[]; return; } for(var i=0;i<$scope.markers.length;++i) $scope.markers[i].setMap(null); $scope.markers=[]; } $scope.map_init=function() { var zoom = parseInt($scope.zoom); if(zoom!=zoom) $scope.zoom=11; var latitude = parseFloat($scope.latitude.replace(",", ".")); var longitude = parseFloat($scope.longitude.replace(",", ".")); if(latitude!=latitude || longitude!=longitude) { alert("Wrong map config. Please fix it in site parameters"); return; } var latLng = new google.maps.LatLng(latitude, longitude); var mapOptions = { zoom: zoom, center: latLng, mapTypeId: google.maps.MapTypeId.ROADMAP, mapTypeControl: false } $scope.map = new google.maps.Map(document.getElementById("map_canvas"), mapOptions); } function loadMarkers() { $http.post($scope.loadDataURL, {reportBy: $scope.reportBy, category: $scope.category}) .success(function(data) { if ("error" in data) $scope.alerts.push({type: 'danger', msg: data["error"]}); else { clearMap(); var objList = data["problems"]; var infowindow = new google.maps.InfoWindow(); $scope.infowindow=infowindow; for(var i=0;i<objList.length;++i) { var myLatlng = new google.maps.LatLng(parseFloat(objList[i].latitude), parseFloat(objList[i].longitude)); var marker = new google.maps.Marker({ position: myLatlng, map: $scope.map, html: '<a href="'+$scope.problemViewURL+objList[i].id+'/" target="_blank">'+objList[i].title+'</a>' }); google.maps.event.addListener(marker, 'click', function () { infowindow.setContent(this.html); infowindow.open($scope.map, this); }); $scope.markers.push(marker); } } }) .error(function(data) { //document.write(data); $scope.alerts.push({type: 'danger', msg: "Error while load data"}); }); } $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; }; mainPageViewCtrl.$inject = ["$scope", "$http", "$route"];
    JavaScript
    0.000001
    @@ -539,24 +539,82 @@ dMarkers();%0A + $('#popup-filter-category').trigger('close');%0A %7D%0A
    0e8964f2cca4493045814fb74fb4ea7de53d9242
    Fix paths on Windows
    lib/asset_types/html5.js
    lib/asset_types/html5.js
    var loader = require("@loader"); var nodeRequire = loader._nodeRequire; var path = nodeRequire("path"); // Register the html5-upgrade asset type module.exports = function(register){ var shivPath = path.join(__dirname, "/../../scripts/html5shiv.min.js"); var loaderBasePath = loader.baseURL.replace("file:", ""); var shivUrl = path.relative(loaderBasePath, shivPath); register("html5shiv", function(){ var elements = Object.keys(loader.global.can.view.callbacks._tags) .filter(function(tagName) { return tagName.indexOf("-") > 0; }); var comment = document.createComment( "[if lt IE 9]>\n" + "\t<script src=\""+ shivUrl + "\"></script>" + "\t<script>\n\t\thtml5.elements = \"" + elements.join(" ") + "\";\nhtml5.shivDocument();\n\t</script>" + "<![endif]" ); return comment; }); };
    JavaScript
    0
    @@ -362,16 +362,36 @@ hivPath) +.replace(/%5C%5C/g, %22/%22) ;%0A%0A%09regi
    0f6506374ddfed2969454b081e5494f0cda811de
    Update cred.js
    server/routes/cred.js
    server/routes/cred.js
    var User = require('../models/users.js'); var express = require('express'); var router = express.Router(); var nodemailer = require('nodemailer'); var wellknown = require('nodemailer-wellknown'); module.exports = router; router.post('/sendEmail', function(req,res){ var email = req.body.email; console.log('email in send', email) User.getByEmail(email) .then(user => { console.log('user in sendEmail:', user); if(user[0]){ var config = wellknown('GandiMail'); config.auth = { user: '[email protected]', pass: 'AeK6yxhT' }; var transporter = nodemailer.createTransport(config); var mailOptions = { from: '"Info" <[email protected]>', to: '<'+ email +'>', subject: "Click the following link to reset your Fairshare password", html: '<a href=' + 'http://localhost:3000/resetPassword>Reset Password</a>' }; transporter.sendMail(mailOptions, function(err, info){ if(err){ return console.log(err); }else{ res.status(200).send(info); } }); }else{ res.status(401).send('Email is not registered') } }) .catch(err => console.warn(err)) })
    JavaScript
    0.000001
    @@ -910,25 +910,31 @@ http +s :// -localhost:3000 +www.fairshare.cloud /res @@ -1303,8 +1303,9 @@ err))%0A%7D) +%0A
    b03df04b45b069a4bea75bed5a8428eb7b1275c2
    reformulate as recursion
    WordSmushing/smushing.js
    WordSmushing/smushing.js
    "use strict"; var assert = require('assert'); var smush = function(w1,w2) { return w1 + w2; }; describe('word smushing', function() { it('should join words with no overlap', function() { assert.equal('thecat', smush('the', 'cat')); }); it('should do single character overlaps', function() { assert.equal('henot', smush('hen', 'not')); }); });
    JavaScript
    0.999976
    @@ -79,22 +79,77 @@ -return w1 + +if (w1 === '') return w2;%0A%0A return w1%5B0%5D + smush(w1.substr(1), w2 +) ;%0A%7D; @@ -191,24 +191,29 @@ n() %7B%0A it +.only ('should joi
    c4b6024abd81b33562c78c343ecb99e0210ecfb5
    Add test that child nodes are rendered.
    src/components/with-drag-and-drop/draggable-context/__spec__.js
    src/components/with-drag-and-drop/draggable-context/__spec__.js
    import React from 'react'; import { DragDropContext } from 'react-dnd'; import DraggableContext from './draggable-context'; fdescribe('DraggableContext', () => { it('is wrapped in a DragDropContextContainer', () => { expect(DraggableContext.name).toBe('DragDropContextContainer'); }); it('has a DecoratedComponent pointing to the original component', () => { expect(DraggableContext.DecoratedComponent.name).toBe('DraggableContext'); }); });
    JavaScript
    0
    @@ -121,10 +121,41 @@ t';%0A +import %7B mount %7D from 'enzyme';%0A %0A -f desc @@ -480,13 +480,378 @@ );%0A %7D); +%0A%0A describe('render', () =%3E %7B%0A it('renders this.props.children', () =%3E %7B%0A let wrapper = mount(%0A %3CDraggableContext%3E%0A %3Cdiv%3E%0A %3Cp%3EOne%3C/p%3E%0A %3Cp%3ETwo%3C/p%3E%0A %3C/div%3E%0A %3C/DraggableContext%3E%0A );%0A%0A expect(wrapper.find('div').length).toEqual(1);%0A expect(wrapper.find('p').length).toEqual(2);%0A %7D);%0A %7D); %0A%7D);%0A
    eafcb68040b44a73e6c2d3605e75f75847d2dfef
    update TableHeader
    src/_TableHeader/TableHeader.js
    src/_TableHeader/TableHeader.js
    /** * @file TableHeader component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import TableHeaderSortIcon from '../_TableHeaderSortIcon'; class TableHeader extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); } headerRenderer = () => { const {header, colIndex} = this.props; switch (typeof header) { case 'function': return header(colIndex); default: return header; } }; clickHandler = e => { e.preventDefault(); const {sortable, onSort} = this.props; sortable && onSort && onSort(); }; render() { const { className, style, header, hidden, sortable, sortProp, sort, sortAscIconCls, sortDescIconCls } = this.props, finalHeader = this.headerRenderer(), tableHeaderClassName = classNames('table-header', { sortable: sortable, hidden: hidden, [className]: className }); return ( <th className={tableHeaderClassName} style={style} title={typeof header === 'string' ? header : null} onClick={this.clickHandler}> <div className="table-header-inner"> {finalHeader} { sortable ? <TableHeaderSortIcon sort={sort} sortProp={sortProp} sortAscIconCls={sortAscIconCls} sortDescIconCls={sortDescIconCls}/> : null } </div> </th> ); } } TableHeader.propTypes = { className: PropTypes.string, style: PropTypes.object, header: PropTypes.oneOfType([PropTypes.string, PropTypes.func]), colIndex: PropTypes.number, sortable: PropTypes.bool, sortProp: PropTypes.string, sort: PropTypes.object, sortAscIconCls: PropTypes.string, sortDescIconCls: PropTypes.string, hidden: PropTypes.bool, onSort: PropTypes.func }; TableHeader.defaultProps = { colIndex: 0, sortable: false, hidden: false }; export default TableHeader;
    JavaScript
    0
    @@ -653,43 +653,16 @@ r = -e +() =%3E %7B%0A - e.preventDefault();%0A
    539dde3653d78ccf4bbf2a67c109167c28f260e6
    version up
    vendor/ember-simple-token/register-version.js
    vendor/ember-simple-token/register-version.js
    Ember.libraries.register('Ember Simple Token', '1.1.2');
    JavaScript
    0
    @@ -49,9 +49,9 @@ 1.1. -2 +3 ');%0A
    69ee5277e50328bf2daa3ef21686dd96a2c58470
    Fix error "Cannot read property 'min' of undefined"
    src/models/axis.js
    src/models/axis.js
    /*! * VIZABI Axis Model (hook) */ (function () { "use strict"; var root = this; var Vizabi = root.Vizabi; var utils = Vizabi.utils; //warn client if d3 is not defined if (!Vizabi._require('d3')) { return; } //constant time formats var time_formats = { "year": d3.time.format("%Y"), "month": d3.time.format("%Y-%m"), "week": d3.time.format("%Y-W%W"), "day": d3.time.format("%Y-%m-%d"), "hour": d3.time.format("%Y-%m-%d %H"), "minute": d3.time.format("%Y-%m-%d %H:%M"), "second": d3.time.format("%Y-%m-%d %H:%M:%S") }; Vizabi.Model.extend('axis', { /** * Initializes the color hook * @param {Object} values The initial values of this model * @param parent A reference to the parent model * @param {Object} bind Initial events to bind */ init: function (values, parent, bind) { this._type = "axis"; values = utils.extend({ use: "value", unit: "", which: undefined, min: null, max: null }, values); this._super(values, parent, bind); }, /** * Validates a color hook */ validate: function () { var possibleScales = ["log", "linear", "time", "pow"]; if (!this.scaleType || (this.use === "indicator" && possibleScales.indexOf(this.scaleType) === -1)) { this.scaleType = 'linear'; } if (this.use !== "indicator" && this.scaleType !== "ordinal") { this.scaleType = "ordinal"; } //TODO a hack that kills the scale, it will be rebuild upon getScale request in model.js if (this.which_1 != this.which || this.scaleType_1 != this.scaleType) this.scale = null; this.which_1 = this.which; this.scaleType_1 = this.scaleType; if(this.scale && this._readyOnce && this.use=="indicator"){ if(this.min==null) this.min = this.scale.domain()[0]; if(this.max==null) this.max = this.scale.domain()[1]; if(this.min<=0 && this.scaleType=="log") this.min = 0.01; if(this.max<=0 && this.scaleType=="log") this.max = 10; // Max may be less than min // if(this.min>=this.max) this.min = this.max/2; if(this.min!=this.scale.domain()[0] || this.max!=this.scale.domain()[1]) this.scale.domain([this.min, this.max]); } }, /** * Gets the domain for this hook * @returns {Array} domain */ buildScale: function (margins) { var domain; var scaleType = this.scaleType || "linear"; if (typeof margins === 'boolean') { var res = margins; margins = {}; margins.min = res; margins.max = res; } if (this.scaleType == "time") { var limits = this.getLimits(this.which); this.scale = d3.time.scale().domain([limits.min, limits.max]); return; } switch (this.use) { case "indicator": var limits = this.getLimits(this.which), margin = (limits.max - limits.min) / 20; domain = [(limits.min - (margins.min ? margin : 0)), (limits.max + (margins.max ? margin : 0))]; if (scaleType == "log") { domain = [(limits.min - limits.min / 4), (limits.max + limits.max / 4)]; } break; case "property": domain = this.getUnique(this.which); break; case "value": default: domain = [this.which]; break; } if (this.min!=null && this.max!=null && scaleType !== 'ordinal') { domain = [this.min, this.max]; this.min = domain[0]; this.max = domain[1]; } this.scale = d3.scale[scaleType]().domain(domain); } }); }).call(this);
    JavaScript
    0
    @@ -2530,16 +2530,73 @@ linear%22; +%0A if (margins === undefined)%0A margins = true; %0A%0A @@ -3130,16 +3130,26 @@ ins.min +&& margin ? margin @@ -3183,16 +3183,26 @@ ins.max +&& margin ? margin
    b97fac279648ce2216a4f01cf6f1ec44e244ef08
    Refresh the whole scrollbar when adapting to size
    Source/Widget/Scrollbar.js
    Source/Widget/Scrollbar.js
    /* --- script: Scrollbar.js description: Scrollbars for everything license: MIT-style license. authors: Yaroslaff Fedin requires: - ART.Widget.Paint - ART.Widget.Section - ART.Widget.Button - Base/Widget.Trait.Slider provides: [ART.Widget.Scrollbar] ... */ ART.Widget.Scrollbar = new Class({ Includes: [ ART.Widget.Paint, Widget.Trait.Slider ], name: 'scrollbar', position: 'absolute', layout: { 'scrollbar-track#track': { 'scrollbar-thumb#thumb': {}, }, 'scrollbar-button#decrement': {}, 'scrollbar-button#increment': {} }, layered: { stroke: ['stroke'], background: ['fill', ['backgroundColor']], reflection: ['fill', ['reflectionColor']] }, options: { slider: { wheel: true } }, initialize: function() { this.parent.apply(this, arguments); this.setState(this.options.mode); }, adaptSize: function(size, old){ if (!size || $chk(size.height)) size = this.parentNode.size; var isVertical = (this.options.mode == 'vertical'); var other = isVertical ? 'horizontal' : 'vertical'; var prop = isVertical ? 'height' : 'width'; var Prop = prop.capitalize(); var setter = 'set' + Prop; var getter = 'getClient' + Prop; var value = size[prop]; if (isNaN(value) || !value) return; var invert = this.parentNode[other]; var scrolled = this.getScrolled(); $(scrolled).setStyle(prop, size[prop]) var ratio = size[prop] / $(scrolled)['scroll' + Prop] var delta = (!invert || invert.hidden ? 0 : invert.getStyle(prop)); this[setter](size[prop] - delta); var offset = 0; if (isVertical) { offset += this.track.offset.padding.top + this.track.offset.padding.bottom } else { offset += this.track.offset.padding.left + this.track.offset.padding.right } var track = size[prop] - this.increment[getter]() - this.decrement[getter]() - delta - ((this.style.current.strokeWidth || 0) * 2) - offset * 2 this.track[setter](track); this.track.thumb[setter](Math.ceil(track * ratio)) this.refresh(); this.parent.apply(this, arguments); }, inject: Macro.onion(function(widget) { this.adaptToSize(widget.size); }), onSet: function(value) { var prop = (this.options.mode == 'vertical') ? 'height' : 'width'; var direction = (this.options.mode == 'vertical') ? 'top' : 'left'; var result = (value / 100) * this.parentNode.element['scroll' + prop.capitalize()]; $(this.getScrolled())['scroll' + direction.capitalize()] = result; }, getScrolled: function() { if (!this.scrolled) { var parent = this; while ((parent = parent.parentNode) && !parent.getScrolled); this.scrolled = parent.getScrolled ? parent.getScrolled() : this.parentNode.element; } return this.scrolled; }, getTrack: function() { return $(this.track) }, getTrackThumb: function() { return $(this.track.thumb); }, hide: Macro.onion(function() { this.element.setStyle('display', 'none'); }), show: Macro.onion(function() { this.element.setStyle('display', 'block'); }) }) ART.Widget.Scrollbar.Track = new Class({ Extends: ART.Widget.Section, layered: { innerShadow: ['inner-shadow'] }, name: 'track', position: 'absolute' }); ART.Widget.Scrollbar.Thumb = new Class({ Extends: ART.Widget.Button, name: 'thumb' }); ART.Widget.Scrollbar.Button = new Class({ Extends: ART.Widget.Button, position: 'absolute' });
    JavaScript
    0
    @@ -2090,16 +2090,20 @@ refresh( +true );%0A t
    0e4adfa855d599636c70622af81d9475165a3515
    Undo workaround for offline testing.
    client/components/widget/query/data-view-service_test.js
    client/components/widget/query/data-view-service_test.js
    /** * @copyright Copyright 2014 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. * * @fileoverview Tests for the dataViewService service. * @author [email protected] (Joe Allan Muharsky) */ goog.require('p3rf.perfkit.explorer.application.module'); goog.require('p3rf.perfkit.explorer.components.widget.data_viz.gviz.getGvizDataTable'); goog.require('p3rf.perfkit.explorer.components.widget.query.DataViewService'); goog.require('p3rf.perfkit.explorer.models.DataViewModel'); var _describe = function() {}; _describe('dataViewService', function() { var DataViewModel = p3rf.perfkit.explorer.models.DataViewModel; var svc, gvizDataViewMock, gvizDataTable; beforeEach(module('explorer')); beforeEach(inject(function(dataViewService, GvizDataTable) { svc = dataViewService; gvizDataTable = GvizDataTable; })); describe('create', function() { var dataTable; beforeEach(function() { var data = { cols: [ {id: 'date', label: 'Date', type: 'date'}, {id: 'value', label: 'Fake values 1', type: 'number'}, {id: 'value', label: 'Fake values 2', type: 'number'} ], rows: [ {c: [ {v: '2013/03/03 00:48:04'}, {v: 0.5}, {v: 3} ]}, {c: [ {v: '2013/03/04 00:50:04'}, {v: 0.1}, {v: 5} ]}, {c: [ {v: '2013/03/05 00:59:04'}, {v: 0.3}, {v: 1} ]}, {c: [ {v: '2013/03/06 00:50:04'}, {v: 0.7}, {v: 2} ]}, {c: [ {v: '2013/03/07 00:59:04'}, {v: 0.2}, {v: 6} ]} ] }; dataTable = new gvizDataTable(data); }); it('should return the correct dataViewJson.', function() { var model = new DataViewModel(); model.columns = [0, 2]; model.filter = [ { column: 1, minValue: 0, maxValue: 0.2 } ]; model.sort = [ { column: 2, desc: true } ]; var dataViewJson = svc.create(dataTable, model); var expectedDataViewJson = [ { columns: [0, 2], rows: [1, 4] }, { rows: [1, 0] } ]; expect(dataViewJson).toEqual(expectedDataViewJson); }); it('should return an error when an error occurred on columns property.', function() { var model = new DataViewModel(); model.columns = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('columns'); } ); it('should return an error when an error occurred on filter property.', function() { var model = new DataViewModel(); model.filter = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('filter'); } ); it('should return an error when an error occurred on sort property.', function() { var model = new DataViewModel(); model.sort = [-1]; var dataViewJson = svc.create(dataTable, model); expect(dataViewJson.error).toBeDefined(); expect(dataViewJson.error.property).toEqual('sort'); } ); }); });
    JavaScript
    0
    @@ -1020,41 +1020,8 @@ );%0A%0A -var _describe = function() %7B%7D;%0A%0A_ desc
    def49f76b0b9a0259aa3cb3e8bca5242f50d65be
    Update LoadCSSJS.min.js
    LoadCSSJS.min.js
    LoadCSSJS.min.js
    /*! Simple CSS JS loader asynchronously for all browsers by cara-tm.com, MIT Licence */ function LoadCSSJS(e,t,r){"use strict";var els="";-1==els.indexOf("["+e+"]")?(Loader(e,t,r),els+="["+e+"]"):alert("File "+e+" already added!")}function Loader(e,t,r){if("css"==t){var s=document.createElement("link");s.setAttribute("rel","stylesheet"),s.setAttribute("href",e),r?"":r="all",s.setAttribute("media",r),s.setAttribute("type","text/css")}else if("js"==t){var s=document.createElement("script");s.setAttribute("type","text/javascript"),s.setAttribute("src",e)}if("undefined"!=typeof s){var a=document.getElementsByTagName("head");a=a[a.length-1],a.appendChild(s)}}
    JavaScript
    0
    @@ -128,19 +128,17 @@ var -els +a =%22%22;-1== els. @@ -133,19 +133,17 @@ =%22%22;-1== -els +a .indexOf @@ -169,19 +169,17 @@ (e,t,r), -els +a +=%22%5B%22+e+
    b5c5d531d169f974651b08d3000b541062f71390
    Fix for unhandled promise on fresh db startup
    core/server/data/migration/index.js
    core/server/data/migration/index.js
    var _ = require('underscore'), when = require('when'), series = require('when/sequence'), errors = require('../../errorHandling'), knex = require('../../models/base').Knex, defaultSettings = require('../default-settings'), Settings = require('../../models/settings').Settings, fixtures = require('../fixtures'), initialVersion = '000', defaultDatabaseVersion; // Default Database Version // The migration version number according to the hardcoded default settings // This is the version the database should be at or migrated to function getDefaultDatabaseVersion() { if (!defaultDatabaseVersion) { // This be the current version according to the software defaultDatabaseVersion = _.find(defaultSettings.core, function (setting) { return setting.key === 'databaseVersion'; }).defaultValue; } return defaultDatabaseVersion; } // Database Current Version // The migration version number according to the database // This is what the database is currently at and may need to be updated function getDatabaseVersion() { return knex.Schema.hasTable('settings').then(function (exists) { // Check for the current version from the settings table if (exists) { // Temporary code to deal with old databases with currentVersion settings return knex('settings') .where('key', 'databaseVersion') .orWhere('key', 'currentVersion') .select('value') .then(function (versions) { var databaseVersion = _.reduce(versions, function (memo, version) { if (isNaN(version.value)) { errors.throwError('Database version is not recognised'); } return parseInt(version.value, 10) > parseInt(memo, 10) ? version.value : memo; }, initialVersion); if (!databaseVersion || databaseVersion.length === 0) { // we didn't get a response we understood, assume initialVersion databaseVersion = initialVersion; } return databaseVersion; }); } return when.reject('Settings table does not exist'); }); } function setDatabaseVersion() { return knex('settings') .where('key', 'databaseVersion') .update({ 'value': defaultDatabaseVersion }); } module.exports = { getDatabaseVersion: getDatabaseVersion, // Check for whether data is needed to be bootstrapped or not init: function () { var self = this; // There are 4 possibilities: // 1. The database exists and is up-to-date // 2. The database exists but is out of date // 3. The database exists but the currentVersion setting does not or cannot be understood // 4. The database has not yet been created return getDatabaseVersion().then(function (databaseVersion) { var defaultVersion = getDefaultDatabaseVersion(); if (databaseVersion === defaultVersion) { // 1. The database exists and is up-to-date return when.resolve(); } if (databaseVersion < defaultVersion) { // 2. The database exists but is out of date return self.migrateUpFromVersion(databaseVersion); } if (databaseVersion > defaultVersion) { // 3. The database exists but the currentVersion setting does not or cannot be understood // In this case we don't understand the version because it is too high errors.logErrorAndExit( 'Your database is not compatible with this version of Ghost', 'You will need to create a new database' ); } }, function (err) { if (err === 'Settings table does not exist') { // 4. The database has not yet been created // Bring everything up from initial version. return self.migrateUpFreshDb(); } // 3. The database exists but the currentVersion setting does not or cannot be understood // In this case the setting was missing or there was some other problem errors.logErrorAndExit('There is a problem with the database', err.message || err); }); }, // ### Reset // Migrate from where we are down to nothing. reset: function () { var self = this; return getDatabaseVersion().then(function (databaseVersion) { // bring everything down from the current version return self.migrateDownFromVersion(databaseVersion); }, function () { // If the settings table doesn't exist, bring everything down from initial version. return self.migrateDownFromVersion(initialVersion); }); }, // Only do this if we have no database at all migrateUpFreshDb: function () { var migration = require('./' + initialVersion); return migration.up().then(function () { // Load the fixtures return fixtures.populateFixtures(); }).then(function () { // Initialise the default settings return Settings.populateDefaults(); }); }, // Migrate from a specific version to the latest migrateUpFromVersion: function (version, max) { var versions = [], maxVersion = max || this.getVersionAfter(getDefaultDatabaseVersion()), currVersion = version, tasks = []; // Aggregate all the versions we need to do migrations for while (currVersion !== maxVersion) { versions.push(currVersion); currVersion = this.getVersionAfter(currVersion); } // Aggregate all the individual up calls to use in the series(...) below tasks = _.map(versions, function (taskVersion) { return function () { try { var migration = require('./' + taskVersion); return migration.up(); } catch (e) { errors.logError(e); return when.reject(e); } }; }); // Run each migration in series return series(tasks).then(function () { // Finally update the databases current version return setDatabaseVersion(); }); }, migrateDownFromVersion: function (version) { var self = this, versions = [], minVersion = this.getVersionBefore(initialVersion), currVersion = version, tasks = []; // Aggregate all the versions we need to do migrations for while (currVersion !== minVersion) { versions.push(currVersion); currVersion = this.getVersionBefore(currVersion); } // Aggregate all the individual up calls to use in the series(...) below tasks = _.map(versions, function (taskVersion) { return function () { try { var migration = require('./' + taskVersion); return migration.down(); } catch (e) { errors.logError(e); return self.migrateDownFromVersion(initialVersion); } }; }); // Run each migration in series return series(tasks); }, // Get the following version based on the current getVersionAfter: function (currVersion) { var currVersionNum = parseInt(currVersion, 10), nextVersion; // Default to initialVersion if not parsed if (isNaN(currVersionNum)) { currVersionNum = parseInt(initialVersion, 10); } currVersionNum += 1; nextVersion = String(currVersionNum); // Pad with 0's until 3 digits while (nextVersion.length < 3) { nextVersion = "0" + nextVersion; } return nextVersion; }, getVersionBefore: function (currVersion) { var currVersionNum = parseInt(currVersion, 10), prevVersion; if (isNaN(currVersionNum)) { currVersionNum = parseInt(initialVersion, 10); } currVersionNum -= 1; prevVersion = String(currVersionNum); // Pad with 0's until 3 digits while (prevVersion.length < 3) { prevVersion = "0" + prevVersion; } return prevVersion; } };
    JavaScript
    0
    @@ -2344,34 +2344,31 @@ -return when.reject +throw new Error ('Settin @@ -4041,16 +4041,31 @@ if (err +.message %7C%7C err === 'Se
    cd3aa58988d8bdadfae7449052eeaa410bd385a6
    Fix import bug in make-html command.
    lib/cli/cmd/make-html.js
    lib/cli/cmd/make-html.js
    /* dendry * http://github.com/idmillington/dendry * * MIT License */ /*jshint indent:2 */ (function() { "use strict"; var path = require('path'); var fs = require('fs'); var handlebars = require('handlebars'); var async = require('async'); var browserify = require('browserify'); var uglify = require('uglify-js'); var utils = require('../utils'); var cmdCompile = require('./compile').cmd; var loadGameAndSource = function(data, callback) { utils.loadCompiledGame(data.compiledPath, function(err, game, json) { if (err) return callback(err); data.gameFile = json; data.game = game; callback(null, data); }); }; var browserifyUI = function(data, callback) { var b = browserify(); b.add(path.resolve(__dirname, "../../ui/browser.js")); b.bundle(function(err, buffer) { if (err) return callback(err); var str = buffer.toString(); data.browserify = str; return callback(null, data); }); }; var uglifyBundle = function(data, callback) { var gameFile = data.gameFile.toString(); var wrappedGameFile = JSON.stringify({compiled:gameFile}); var content = ["window.game="+wrappedGameFile+";", data.browserify]; var result = uglify.minify(content, {fromString: true, compress:{}}); data.code = content.join("");//result.code; return callback(null, data); }; var getTemplateDir = function(data, callback) { utils.getTemplatePath( data.template, "html", function(err, templateDir, name) { if (err) return callback(err); data.templateDir = templateDir; data.template = name; return callback(null, data); }); }; var getDestDir = function(data, callback) { data.destDir = path.join(data.projectDir, "out", "html"); callback(null, data); }; var notifyUser = function(data, callback) { console.log(("Creating HTML build in: "+data.destDir).grey); console.log(("Using template: "+data.template).grey); callback(null, data); }; var createHTML = function(data, callback) { fs.exists(data.destDir, function(exists) { if (exists) { console.log("Warning: Overwriting existing HTML content.".red); } utils.copyTemplate( data.templateDir, data.destDir, data, function(err) { if (err) return callback(err); else return(null, data); }); }); }; // ---------------------------------------------------------------------- // Make-HTML: Creates a playable HTML version of the game. // ---------------------------------------------------------------------- var cmdMakeHTML = new utils.Command("make-html"); cmdMakeHTML.createArgumentParser = function(subparsers) { var parser = subparsers.addParser(this.name, { help: "Make a project into a playable HTML page.", description: "Builds a HTML version of a game, compiling it first "+ "if it is out of date. The compilation uses a template which "+ "can be a predefined template, or the path to a directory. "+ "Templates use the handlebars templating system. The default "+ "HTML template (called 'default') compresses the browser interface "+ "and your game content and embeds it in a single HTML file, for the "+ "most portable game possible." }); parser.addArgument(['project'], { nargs: "?", help: "The project to compile (default: the current directory)." }); parser.addArgument(['-t', '--template'], { help: "A theme template to use (default: the 'default' theme). "+ "Can be the name of a built-in theme, or the path to a theme." }); parser.addArgument(['-f', '--force'], { action: "storeTrue", default: false, help: "Always recompiles, even if the compiled game is up to date." }); }; cmdMakeHTML.run = function(args, callback) { var getData = function(callback) { cmdCompile.run(args, callback); }; async.waterfall([getData, loadGameAndSource, browserifyUI, uglifyBundle, getTemplateDir, getDestDir, notifyUser, createHTML], callback); }; module.exports = { cmd: cmdMakeHTML }; }());
    JavaScript
    0
    @@ -359,24 +359,76 @@ ../utils');%0A + var compiler = require('../../parsers/compiler');%0A var cmdCom @@ -518,21 +518,24 @@ ) %7B%0A -utils +compiler .loadCom @@ -1382,22 +1382,8 @@ %22%22); -//result.code; %0A
    7ef05101fafd008f7886571b2595bc810025f4aa
    Fix floatbar behaviour on "More threads/posts" clicks.
    client/common/system/floatbar/floatbar.js
    client/common/system/floatbar/floatbar.js
    'use strict'; var _ = require('lodash'); N.wire.on('navigate.done', function () { var $window = $(window) , $floatbar = $('#floatbar') , isFixed = false , navTop; // Remove previous floatbar handlers if any. $window.off('scroll.floatbar'); if (0 === $floatbar.length) { // Do nothing if there's no floatbar. return; } navTop = $floatbar.offset().top; isFixed = false; function updateFloatbarState() { var scrollTop = $window.scrollTop(); if (scrollTop >= navTop && !isFixed) { isFixed = true; $floatbar.addClass('floatbar-fixed'); } else if (scrollTop <= navTop && isFixed) { isFixed = false; $floatbar.removeClass('floatbar-fixed'); } } updateFloatbarState(); $window.on('scroll.floatbar', _.throttle(updateFloatbarState, 100)); });
    JavaScript
    0
    @@ -183,90 +183,8 @@ p;%0A%0A - // Remove previous floatbar handlers if any.%0A $window.off('scroll.floatbar');%0A%0A if @@ -744,8 +744,317 @@ ));%0A%7D);%0A +%0A%0AN.wire.on('navigate.exit', function () %7B%0A // Remove floatbar event handler.%0A $(window).off('scroll.floatbar');%0A%0A // Get floatbar back to the initial position to ensure next %60navigate.done%60%0A // handler will obtain correct floatbar offset on next call.%0A $('#floatbar').removeClass('floatbar-fixed');%0A%7D);%0A
    b9dcce9939f2bcaeec8d4dbc4d8607e3b6ba856a
    remove console statement
    client/components/projects/ProjectItem.js
    client/components/projects/ProjectItem.js
    import React from 'react'; import PropTypes from 'prop-types'; import { Link } from 'react-router-dom'; import { formatTime } from '../../helpers'; class ProjectItem extends React.Component { constructor(props) { super(props); this.state = { showInput: false, newName: '', }; this.handleNewName = this.handleNewName.bind(this); this.handleRenaming = this.handleRenaming.bind(this); this.handleShowInput = this.handleShowInput.bind(this); this.handleEnterButton = this.handleEnterButton.bind(this); } handleNewName(e) { this.setState({ newName: e.target.value }); } handleShowInput(name) { this.setState({ showInput: !this.state.showInput, newName: name, }); } handleRenaming(id, name) { this.props.renameMe(id, name); this.setState({ showInput: false, }); } handleEnterButton(event) { if (event.charCode === 13) { this.renameLink.click(); } } render() { const { project, onDelete } = this.props; const { newName, showInput } = this.state; const hideTaskName = this.state.showInput ? 'none' : ''; console.log(project); return ( <li style={{ paddingLeft: `${this.props.padding}px` }} className="projects__item" > <Link className="projects__item-title" style={{ display: `${hideTaskName}` }} to={`/projects/${project._id}`} > <span>{project.name}</span> <span className="pretty-time">{formatTime(project.timeSpent)}</span> </Link> {showInput ? ( <input type="text" value={newName} className="name-input" onKeyPress={this.handleEnterButton} onChange={this.handleNewName} /> ) : null} <div className="buttons-group"> {showInput ? ( <button onClick={() => this.handleRenaming(project._id, this.state.newName) } ref={link => { this.renameLink = link; }} className="button--info" > Ok </button> ) : null} <button onClick={() => this.handleShowInput(project.name)} className="button--info" > Edit </button> <button onClick={() => onDelete(project._id)} className="button--info button--danger" > Delete </button> </div> </li> ); } } ProjectItem.propTypes = { project: PropTypes.object.isRequired, onDelete: PropTypes.func.isRequired, renameMe: PropTypes.func.isRequired, padding: PropTypes.number.isRequired, }; export default ProjectItem;
    JavaScript
    0.000032
    @@ -1129,34 +1129,8 @@ '';%0A - console.log(project);%0A
    bd57d8643a445faf8777c4d2961821cfa8e56288
    connect relevancy feature flag to experiment
    share/spice/news/news.js
    share/spice/news/news.js
    (function (env) { "use strict"; env.ddg_spice_news = function (api_result) { if (!api_result || !api_result.results) { return Spice.failed('news'); } var useRelevancy = false, entityWords = [], goodStories = [], searchTerm = DDG.get_query().replace(/(?: news|news ?)/i, '').trim(), // Some sources need to be set by us. setSourceOnStory = function(story) { switch(story.syndicate) { case "Topsy": story.source = story.author || "Topsy"; break; case "NewsCred": if(story.source) { if(story.author) { story.source = story.source + " by " + story.author; } } else { story.source = "NewsCred"; } break; } }; if (useRelevancy) { // Words that we have to skip in DDG.isRelevant. var skip = [ "news", "headline", "headlines", "latest", "breaking", "update", "s:d", "sort:date" ]; if (Spice.news && Spice.news.entities && Spice.news.entities.length) { for (var j = 0, entity; entity = Spice.news.entities[j]; j++) { var tmpEntityWords = entity.split(" "); for (var k = 0, entityWord; entityWord = tmpEntityWords[k]; k++) { if (entityWord.length > 3) { entityWords.push(entityWord); } } } } } // Check if the title is relevant to the query. for(var i = 0, story; story = api_result.results[i]; i++) { if (!useRelevancy || DDG.isRelevant(story.title, skip)) { setSourceOnStory(story); story.sortableDate = parseInt(story.date || 0); goodStories.push(story); // additional news relevancy for entities. story need only // contain one word from one entity to be good. strict indexof // check though. } else if (entityWords.length > 0) { var storyOk = 0; var tmpStoryTitle = story.title.toLowerCase(); for (var k = 0, entityWord; entityWord = entityWords[k]; k++) { if (tmpStoryTitle.indexOf(entityWord) !== -1) { storyOk = 1; break; } } if (storyOk) { setSourceOnStory(story); goodStories.push(story); } } } if (useRelevancy && goodStories < 3) { return Spice.failed('news'); } Spice.add({ id: 'news', name: 'News', data: goodStories, ads: api_result.ads, meta: { idField: 'url', count: goodStories.length, searchTerm: searchTerm, itemType: 'Recent News', rerender: [ 'image' ] }, templates: { item: 'news_item' }, onItemShown: function(item) { if (!item.fetch_image || item.image || item.fetched_image) { return; } // set flag so we don't try to fetch more than once: item.fetched_image = 1; // try to fetch the image and set it on the model // which will trigger the tile to re-render with the image: $.getJSON('/f.js?o=json&i=1&u=' + item.url, function(meta) { if (meta && meta.image) { item.set('image', meta.image); } }); }, sort_fields: { date: function(a, b) { return b.sortableDate - a.sortableDate; } }, sort_default: 'date' }); } }(this));
    JavaScript
    0
    @@ -212,13 +212,104 @@ y = -false +DDG.opensearch.installed.experiment === %22organic_ux%22 && DDG.opensearch.installed.variant === 'b' ,%0A
    4bb1faa246cff960a7a28ea85d000bd69cd30b23
    Fix bug with incorrect 'auto storage' calculation when more than 3
    src/app/components/player/player.controller.js
    src/app/components/player/player.controller.js
    export default class PlayerController { constructor($rootScope, $scope, $log, $uibModal, _, toastr, playersApi, playerModel, websocket) { 'ngInject'; this.$rootScope = $rootScope; this.$scope = $scope; this.$log = $log.getInstance(this.constructor.name); this.$uibModal = $uibModal; this._ = _; this.toastr = toastr; this.playerModel = playerModel; // Used in template this.playersApi = playersApi; this.ws = websocket; this.$log.debug('constructor()', this); } $onInit() { this.$log.debug('$onInit()', this); this.$rootScope.$on('deck:action:winter', () => { this.$log.debug('deck:action:winter'); if (this.player.id === this.playerModel.model.player.id) { this.playerModel.showSpecialCards(); } }); } $onDestroy() { this.$log.debug('$onDestroy()', this); } canStoreCards(cardsSelected) { if (this.game.actionCard || !cardsSelected || cardsSelected.length !== 3) { return false; } let cardsMatch = this._.reduce(cardsSelected, (prev, current, index, array) => { let len = array.length, sameCard = prev.amount === current.amount; if (!prev) { // If the previous object is 'false', then cards don't match return false; } else if (sameCard && index === len - 1) { // Reached the end of the array and all values matched return true; } return sameCard ? current : false; }); return cardsMatch; } getCurrentPlayer() { return this.playerModel.model.player; } onStorageClick(evt) { let cardsSelected = this.player.cardsSelected; this.$log.debug('onStorageClick()', evt, cardsSelected, this); evt.preventDefault(); if (this.player.isActive && this.player.hasDrawnCard && this.canStoreCards(cardsSelected)) { this.storeCards(cardsSelected); } else { this.showStorage(this.player); } } onStorageAutoClick(evt) { evt.preventDefault(); if (this.player.isActive && !this.player.isFirstTurn) { // Filter out sets of 3 that have the same 'amount' this.playerModel.getCards() .then(res => { let cards = this._.filter(res.data, (o) => { return o.cardType === 'number'; }), numberCards = this._.groupBy(cards, (o) => { return o.amount; }), isStored = false; this.$log.info('numberCards -> ', numberCards); this._.forEach(numberCards, (cardsGroup) => { if (cardsGroup.length % 3 === 0) { this.storeCards(cardsGroup); isStored = true; } }); if (!isStored) { this.toastr.warning('No matching cards to store!'); } }, (err) => { this.$log.error(err); }); } } storeCards(cardsSelected) { let cardsInStorage = this.player.cardsInStorage, cardsInHand = this.player.cardsInHand, onSuccess = (res => { if (res.status == 200) { this.$log.debug(res); } }), onError = (err => { this.$log.error(err); }), cardIds = this._.map(cardsSelected, (obj) => { return obj.id; }); cardsInStorage.push(cardIds[0]); this._.pullAll(cardsInHand, cardIds); let plData = { cardsInHand: cardsInHand, cardsInStorage: cardsInStorage, score: this.player.score + cardsSelected[0].amount }; this.playersApi .update(this.player.id, plData) .then(onSuccess, onError); this.player.cardsSelected = []; } showStorage(pl) { let onClose = (data => { this.$log.debug('onClose()', data, this); }), onError = (err => { if (err !== 'backdrop click') { this.$log.error(err); } }); this.$log.debug('showStorage()', pl, this); let modal = this.$uibModal.open({ appendTo: angular.element(document).find('players'), component: 'storageModal', resolve: { player: () => { return this.player; } } }); modal.result.then(onClose, onError); } }
    JavaScript
    0.000001
    @@ -2254,12 +2254,13 @@ log. -info +debug ('nu @@ -2347,19 +2347,42 @@ %7B%0A%09%09%09%09%09%09 -if +let numGroups = Math.floor (cardsGr @@ -2396,20 +2396,200 @@ gth -%25 3 === 0) %7B +/ 3),%0A%09%09%09%09%09%09%09numToStore = numGroups * 3;%0A%0A%09%09%09%09%09%09if (numToStore) %7B%0A%09%09%09%09%09%09%09let cardsToStore = this._.sampleSize(cardsGroup, numToStore);%0A%09%09%09%09%09%09%09this.$log.debug('cardsToStore -%3E ', cardsToStore); %0A%09%09%09 @@ -2613,21 +2613,23 @@ ds(cards -Group +ToStore );%0A%09%09%09%09%09
    75aa9ab5476e62adbb5abbbaaf8cbfbf5933ea94
    stop serving bower_components separately. bower_components are now inside the app directory (ionic/www) and hence get served along with the app directory.
    server/boot/dev-assets.js
    server/boot/dev-assets.js
    var path = require('path'); module.exports = function(app) { if (!app.get('isDevEnv')) return; var serveDir = app.loopback.static; app.use(serveDir(projectPath('.tmp'))); app.use('/bower_components', serveDir(projectPath('client/bower_components'))); // app.use('/bower_components', serveDir(projectPath('bower_components'))); app.use('/lbclient', serveDir(projectPath('client/lbclient'))); }; function projectPath(relative) { return path.resolve(__dirname, '../..', relative); }
    JavaScript
    0
    @@ -169,24 +169,26 @@ ('.tmp')));%0A +// app.use('/
    7b3e3cbad51dfa66fa7aa81bb74a93419c3a19c9
    add fn assertion to app.use(). Closes #337
    lib/application.js
    lib/application.js
    /** * Module dependencies. */ var debug = require('debug')('koa:application'); var Emitter = require('events').EventEmitter; var compose = require('koa-compose'); var isJSON = require('koa-is-json'); var response = require('./response'); var context = require('./context'); var request = require('./request'); var onFinished = require('on-finished'); var Cookies = require('cookies'); var accepts = require('accepts'); var status = require('statuses'); var assert = require('assert'); var Stream = require('stream'); var http = require('http'); var only = require('only'); var co = require('co'); /** * Application prototype. */ var app = Application.prototype; /** * Expose `Application`. */ exports = module.exports = Application; /** * Initialize a new `Application`. * * @api public */ function Application() { if (!(this instanceof Application)) return new Application; this.env = process.env.NODE_ENV || 'development'; this.subdomainOffset = 2; this.poweredBy = true; this.middleware = []; this.context = Object.create(context); this.request = Object.create(request); this.response = Object.create(response); } /** * Inherit from `Emitter.prototype`. */ Application.prototype.__proto__ = Emitter.prototype; /** * Shorthand for: * * http.createServer(app.callback()).listen(...) * * @param {Mixed} ... * @return {Server} * @api public */ app.listen = function(){ debug('listen'); var server = http.createServer(this.callback()); return server.listen.apply(server, arguments); }; /** * Return JSON representation. * We only bother showing settings. * * @return {Object} * @api public */ app.inspect = app.toJSON = function(){ return only(this, [ 'subdomainOffset', 'poweredBy', 'env' ]); }; /** * Use the given middleware `fn`. * * @param {GeneratorFunction} fn * @return {Application} self * @api public */ app.use = function(fn){ assert('GeneratorFunction' == fn.constructor.name, 'app.use() requires a generator function'); debug('use %s', fn._name || fn.name || '-'); this.middleware.push(fn); return this; }; /** * Return a request handler callback * for node's native http server. * * @return {Function} * @api public */ app.callback = function(){ var mw = [respond].concat(this.middleware); var gen = compose(mw); var fn = co(gen); var self = this; if (!this.listeners('error').length) this.on('error', this.onerror); return function(req, res){ res.statusCode = 404; var ctx = self.createContext(req, res); onFinished(res, ctx.onerror); fn.call(ctx, ctx.onerror); } }; /** * Initialize a new context. * * @api private */ app.createContext = function(req, res){ var context = Object.create(this.context); var request = context.request = Object.create(this.request); var response = context.response = Object.create(this.response); context.app = request.app = response.app = this; context.req = request.req = response.req = req; context.res = request.res = response.res = res; request.ctx = response.ctx = context; request.response = response; response.request = request; context.onerror = context.onerror.bind(context); context.originalUrl = request.originalUrl = req.url; context.cookies = new Cookies(req, res, this.keys); context.accept = request.accept = accepts(req); return context; }; /** * Default error handler. * * @param {Error} err * @api private */ app.onerror = function(err){ assert(err instanceof Error, 'non-error thrown: ' + err); if (404 == err.status) return; if ('test' == this.env) return; var msg = err.stack || err.toString(); console.error(); console.error(msg.replace(/^/gm, ' ')); console.error(); }; /** * Response middleware. */ function *respond(next) { if (this.app.poweredBy) this.set('X-Powered-By', 'koa'); yield *next; // allow bypassing koa if (false === this.respond) return; var res = this.res; if (res.headersSent || !this.writable) return; var body = this.body; var code = this.status; // ignore body if (status.empty[code]) { // strip headers this.body = null; return res.end(); } if ('HEAD' == this.method) { if (isJSON(body)) this.length = Buffer.byteLength(JSON.stringify(body)); return res.end(); } // status body if (null == body) { this.type = 'text'; body = status[code]; if (body) this.length = Buffer.byteLength(body); return res.end(body); } // responses if (Buffer.isBuffer(body)) return res.end(body); if ('string' == typeof body) return res.end(body); if (body instanceof Stream) return body.pipe(res); // body: json body = JSON.stringify(body); this.length = Buffer.byteLength(body); res.end(body); }
    JavaScript
    0.000001
    @@ -1926,16 +1926,22 @@ assert( +fn && 'Generat
    ba0731679463757c03975f43fdbe63ed22675aff
    Improve copy Grunt task structure
    grunt/copy.js
    grunt/copy.js
    'use strict'; module.exports = { fonts: { files: [ { expand: true, cwd: '<%= paths.src %>/fonts/', src: ['**/*'], dest: '<%= paths.dist %>/fonts/', }, { expand: true, cwd: '<%= paths.bower %>/bootstrap/fonts/', src: ['**/*'], dest: '<%= paths.dist %>/fonts/', }, { expand: true, cwd: '<%= paths.bower %>/', src: ['ckeditor/**/*'], dest: '<%= paths.dist %>/vendor/', }, ], }, };
    JavaScript
    0.000033
    @@ -344,32 +344,53 @@ nts/',%0A %7D,%0A + %5D,%0A vendor: %5B%0A %7B%0A
    b2b4408b2401fba7d7ad971b69c40b5d47720ee4
    optimize DraggableGridGroup
    src/_DraggableGridGroup/DraggableGridGroup.js
    src/_DraggableGridGroup/DraggableGridGroup.js
    /** * @file DraggableGridGroup component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import {DragSource, DropTarget} from 'react-dnd'; import DraggableGridItem from '../_DraggableGridItem'; import Theme from '../Theme'; import DragDrop from '../_vendors/DragDrop'; const DRAG_GRID_GROUP_SYMBOL = Symbol('DRAG_GRID_GROUP'); @DropTarget(DRAG_GRID_GROUP_SYMBOL, DragDrop.getVerticalTarget(), connect => ({ connectDropTarget: connect.dropTarget() })) @DragSource(DRAG_GRID_GROUP_SYMBOL, DragDrop.getSource(), (connect, monitor) => ({ connectDragPreview: connect.dragPreview(), connectDragSource: connect.dragSource(), isDragging: monitor.isDragging() })) export default class DraggableGridGroup extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); } render() { const { connectDragPreview, connectDragSource, connectDropTarget, isDragging, children, className, style, theme, text, iconCls, rightIconCls, anchorIconCls, isDraggableAnyWhere, disabled, isLoading, onMouseEnter, onMouseLeave } = this.props, listGroupClassName = (theme ? ` theme-${theme}` : '') + (isDragging ? ' dragging' : '') + (isDraggableAnyWhere ? ' draggable' : '') + (className ? ' ' + className : ''), anchorEl = <i className={'draggable-grid-group-anchor' + (anchorIconCls ? ' ' + anchorIconCls : '')} aria-hidden="true"></i>, el = connectDropTarget( <div className={'draggable-grid-group' + listGroupClassName} style={style} disabled={disabled || isLoading} onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}> <DraggableGridItem className="draggable-grid-group-name" text={text} iconCls={iconCls} rightIconCls={rightIconCls} disabled={disabled} isLoading={isLoading} isGroupTitle={true} anchorIconCls={anchorIconCls} isDraggableAnyWhere={isDraggableAnyWhere}/> <div className="draggable-grid-group-item-wrapper"> {children} </div> { isDraggableAnyWhere ? anchorEl : connectDragSource(anchorEl) } </div> ); return isDraggableAnyWhere ? connectDragSource(el) : connectDragPreview(el); } }; DraggableGridGroup.propTypes = { connectDragPreview: PropTypes.func, connectDragSource: PropTypes.func, connectDropTarget: PropTypes.func, isDragging: PropTypes.bool, /** * The CSS class name of the grid button. */ className: PropTypes.string, /** * Override the styles of the grid button. */ style: PropTypes.object, /** * The theme of the grid button. */ theme: PropTypes.oneOf(Object.keys(Theme).map(key => Theme[key])), /** * The text value of the grid button. Type can be string or number. */ value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), /** * The grid item's display text. Type can be string, number or bool. */ text: PropTypes.any, /** * If true, the grid button will be disabled. */ disabled: PropTypes.bool, /** * If true,the button will be have loading effect. */ isLoading: PropTypes.bool, /** * Use this property to display an icon. It will display on the left. */ iconCls: PropTypes.string, /** * Use this property to display an icon. It will display on the right. */ rightIconCls: PropTypes.string, /** * */ anchorIconCls: PropTypes.string, /** * */ isDraggableAnyWhere: PropTypes.bool, /** * */ onMouseEnter: PropTypes.func, /** * */ onMouseLeave: PropTypes.func }; DraggableGridGroup.defaultProps = { className: '', style: null, theme: Theme.DEFAULT, value: '', text: '', disabled: false, isLoading: false, iconCls: '', rightIconCls: '', anchorIconCls: 'fa fa-bars', isDraggableAnyWhere: false };
    JavaScript
    0.000002
    @@ -811,24 +811,51 @@ omponent %7B%0A%0A + static Theme = Theme;%0A%0A construc
    43b7930247c46cfa454f4ceed1f1e777235ea895
    clear action
    src/astroprint/static/js/app/views/terminal.js
    src/astroprint/static/js/app/views/terminal.js
    var TerminalView = Backbone.View.extend({ el: '#terminal-view', outputView: null, sourceId: null, events: { 'submit form': 'onSend', 'show': 'onShow', 'hide': 'onHide' }, initialize: function() { this.outputView = new OutputView(); this.sourceId = Math.floor((Math.random() * 100000)); //Generate a random sourceId app.eventManager.on("astrobox:PrinterResponse", _.bind(function(data) { if (data.sourceId == this.sourceId) { this.outputView.add('received', data.response); } }, this)); }, onClear: function(e) { e.preventDefault(); this.outputView.clear(); }, onSend: function(e) { e.preventDefault(); var sendField = this.$('input'); var command = sendField.val(); if (this.sourceId && command) { var loadingBtn = this.$('button.send').closest('.loading-button'); loadingBtn.addClass('loading'); $.ajax({ url: API_BASEURL + 'printer/comm/send', method: 'POST', data: { sourceId: this.sourceId, command: command } }) .done(_.bind(function(){ this.outputView.add('sent', command); }, this)) .fail(function(){ loadingBtn.addClass('error'); setTimeout(function(){ loadingBtn.removeClass('error'); }, 3000); }) .always(function(){ loadingBtn.removeClass('loading'); sendField.val(''); }); } return false; }, onShow: function() { this.$('input').focus(); $.ajax({ url: API_BASEURL + 'printer/comm/listen', method: 'POST' }) }, onHide: function() { $.ajax({ url: API_BASEURL + 'printer/comm/listen', method: 'DELETE' }); } }); var OutputView = Backbone.View.extend({ el: '#terminal-view .output-container', add: function(type, text) { switch(type) { case 'sent': text = '<div class="sent bold"><i class="icon-angle-right"></i>'+text+'</div>'; break; case 'received': text = '<div class="received"><i class="icon-angle-left"></i>'+text+'</div>'; break; } this.$el.append(text); this.$el.scrollTop(this.$el[0].scrollHeight); }, clear: function() { this.$el.empty(); } });
    JavaScript
    0.000001
    @@ -180,16 +180,53 @@ 'onHide' +,%0A 'click button.clear': 'onClear' %0A %7D,%0A @@ -2325,14 +2325,15 @@ $el. -empty( +html('' );%0A
    3e496394541b46fe822903c9b180419979fbd608
    Remove dragStart event from example
    examples/events/main.js
    examples/events/main.js
    import { default as React, Component } from 'react'; var ReactDOM = require('react-dom'); import { ReactiveBase } from '@appbaseio/reactivebase'; import { ReactiveMap } from '../../app/app.js'; class Main extends Component { constructor(props) { super(props); this.eventLists = [ 'onDragstart', 'onClick', 'onDblclick', 'onDrag', 'onDragstart', 'onDragend', 'onMousemove', 'onMouseout', 'onMouseover', 'onResize', 'onRightclick', 'onTilesloaded', 'onBoundsChanged', 'onCenterChanged', 'onProjectionChanged', 'onTiltChanged', 'onZoomChanged' ]; this.onIdle = this.onIdle.bind(this); this.onMouseover = this.onMouseover.bind(this); this.onMouseout = this.onMouseout.bind(this); this.onClick = this.onClick.bind(this); this.onDblclick = this.onDblclick.bind(this); this.onDrag = this.onDrag.bind(this); this.onDragstart = this.onDragstart.bind(this); this.onDragend = this.onDragend.bind(this); this.onMousemove = this.onMousemove.bind(this); this.onMouseout = this.onMouseout.bind(this); this.onMouseover = this.onMouseover.bind(this); this.onResize = this.onResize.bind(this); this.onRightclick = this.onRightclick.bind(this); this.onTilesloaded = this.onTilesloaded.bind(this); this.onBoundsChanged = this.onBoundsChanged.bind(this); this.onCenterChanged = this.onCenterChanged.bind(this); this.onProjectionChanged = this.onProjectionChanged.bind(this); this.onTiltChanged = this.onTiltChanged.bind(this); this.onZoomChanged = this.onZoomChanged.bind(this); } renderEventName() { return this.eventLists.map((eventName, index) => { return (<li key={index} ref={"event-"+eventName}>{eventName}</li>); }); } onIdle(mapRef) { this.eventActive('event-onIdle'); } onMouseover(mapRef) { this.eventActive('event-onMouseover'); } onMouseout(mapRef) { this.eventActive('event-onMouseout'); } onClick(mapRef) { this.eventActive('event-onClick'); } onDblclick(mapRef) { this.eventActive('event-onDblclick'); } onDrag(mapRef) { this.eventActive('event-onDrag'); } onDragstart(mapRef) { this.eventActive('event-onDragstart'); } onDragend(mapRef) { this.eventActive('event-onDragend'); } onMousemove(mapRef) { this.eventActive('event-onMousemove'); } onMouseout(mapRef) { this.eventActive('event-onMouseout'); } onMouseover(mapRef) { this.eventActive('event-onMouseover'); } onResize(mapRef) { this.eventActive('event-onResize'); } onRightclick(mapRef) { this.eventActive('event-onRightclick'); } onTilesloaded(mapRef) { this.eventActive('event-onTilesloaded'); } onBoundsChanged(mapRef) { this.eventActive('event-onBoundsChanged'); } onCenterChanged(mapRef) { this.eventActive('event-onCenterChanged'); } onProjectionChanged(mapRef) { this.eventActive('event-onProjectionChanged'); } onTiltChanged(mapRef) { this.eventActive('event-onTiltChanged'); } onZoomChanged(mapRef) { this.eventActive('event-onZoomChanged'); } onClick(mapRef) { this.eventActive('event-onClick'); } eventActive(eventRef) { $(this.refs[eventRef]).addClass('active'); setTimeout(() => { $(this.refs[eventRef]).removeClass('active'); }, 1500); } render() { return ( <div className="row m-0 h-100"> <ReactiveBase appname={this.props.config.appbase.appname} username={this.props.config.appbase.username} password={this.props.config.appbase.password} type={this.props.config.appbase.type} > <div className="col s12 m9 h-100"> <ReactiveMap appbaseField={this.props.mapping.location} defaultZoom={13} defaultCenter={{ lat: 37.74, lng: -122.45 }} historicalData={true} markerCluster={false} searchComponent="appbase" searchField={this.props.mapping.venue} mapStyle={this.props.mapStyle} autoCenter={true} searchAsMoveComponent={true} title="Events Example" MapStylesComponent={true} onIdle={this.onIdle} onMouseover={this.onMouseover} onMouseout={this.onMouseout} onClick={this.onClick} onDblclick={this.onDblclick} onDrag={this.onDrag} onDragstart={this.onDragstart} onDragend={this.onDragend} onMousemove={this.onMousemove} onMouseout={this.onMouseout} onMouseover={this.onMouseover} onResize={this.onResize} onRightclick={this.onRightclick} onBoundsChanged={this.onBoundsChanged} onCenterChanged={this.onCenterChanged} onProjectionChanged={this.onProjectionChanged} onTiltChanged={this.onTiltChanged} onZoomChanged={this.onZoomChanged} /> </div> <div className="col s12 m3"> <ul> {this.renderEventName()} </ul> </div> </ReactiveBase> </div> ); } } Main.defaultProps = { mapStyle: "Light Monochrome", mapping: { location: 'location' }, config: { "appbase": { "appname": "checkin", "username": "6PdfXag4h", "password": "b614d8fa-03d8-4005-b6f1-f2ff31cd0f91", "type": "city" } } }; ReactDOM.render(<Main />, document.getElementById('map'));
    JavaScript
    0
    @@ -280,34 +280,16 @@ sts = %5B%0A -%09%09%09'onDragstart',%0A %09%09%09'onCl
    615a2718f0d62205869b72e347cf909c8c43c4de
    Add docstrings to the popover view
    web_client/views/popover/AnnotationPopover.js
    web_client/views/popover/AnnotationPopover.js
    import _ from 'underscore'; import View from '../View'; import { restRequest } from 'girder/rest'; import ElementCollection from 'girder_plugins/large_image/collections/ElementCollection'; import annotationPopover from '../../templates/popover/annotationPopover.pug'; import '../../stylesheets/popover/annotationPopover.styl'; var AnnotationPopover = View.extend({ initialize(settings) { if (settings.debounce) { this.position = _.debounce(this.position, settings.debounce); } $('body').on('mousemove', '.h-image-view-body', (evt) => this.position(evt)); $('body').on('mouseout', '.h-image-view-body', () => this._hide()); $('body').on('mouseover', '.h-image-view-body', () => this._show()); this._hidden = !settings.visible; this._users = {}; this.collection = new ElementCollection(); this.listenTo(this.collection, 'add', this._getUser); this.listenTo(this.collection, 'all', this.render); }, render() { this.$el.html( annotationPopover({ annotations: _.uniq( this.collection.pluck('annotation'), _.property('id')), formatDate: this._formatDate, users: this._users }) ); this._show(); if (!this._visible()) { this._hide(); } this._height = this.$('.h-annotation-popover').height(); }, _getUser(model) { var id = model.get('annotation').get('creatorId'); if (!_.has(this._users, id)) { restRequest({ path: 'user/' + id }).then((user) => { this._users[id] = user; this.render(); }); } }, _formatDate(s) { var d = new Date(s); return d.toLocaleString(); }, _show() { if (this._visible()) { this.$el.removeClass('hidden'); } }, _hide() { this.$el.addClass('hidden'); }, _visible() { return !this._hidden && this.collection.length > 0; }, position(evt) { if (this._visible()) { this.$el.css({ left: evt.pageX + 5, top: evt.pageY - this._height / 2 }); } }, toggle(show) { this._hidden = !show; this.render(); } }); export default AnnotationPopover;
    JavaScript
    0
    @@ -323,16 +323,336 @@ styl';%0A%0A +/**%0A * This view behaves like a bootstrap %22popover%22 that follows the mouse pointer%0A * over the image canvas and dynamically updates according to the features%0A * under the pointer.%0A *%0A * @param %7Bobject%7D %5Bsettings%5D%0A * @param %7Bnumber%7D %5Bsettings.debounce%5D%0A * Debounce time in ms for rerendering due to mouse movements%0A */%0A var Anno @@ -754,24 +754,25 @@ this. +_ position = _ @@ -782,24 +782,25 @@ bounce(this. +_ position, se @@ -898,16 +898,17 @@ =%3E this. +_ position @@ -1787,24 +1787,798 @@ ();%0A %7D,%0A%0A + /**%0A * Set the popover visibility state.%0A *%0A * @param %7Bboolean%7D %5Bshow%5D%0A * if true: show the popover%0A * if false: hide the popover%0A * if undefined: toggle the popover state%0A */%0A toggle(show) %7B%0A if (show === undefined) %7B%0A show = this._hidden;%0A %7D%0A this._hidden = !show;%0A this.render();%0A return this;%0A %7D,%0A%0A /**%0A * Check the local cache for the given creator. If it has not already been%0A * fetched, then send a rest request to get the user information and%0A * rerender the popover.%0A *%0A * As a consequence to avoid always rendering asyncronously, the user name%0A * will not be shown on the first render. In practice, this isn't usually%0A * noticeable.%0A */%0A _getUser @@ -2879,24 +2879,91 @@ %7D%0A %7D,%0A%0A + /**%0A * Format a Date object as a localized string.%0A */%0A _formatD @@ -3039,24 +3039,134 @@ ();%0A %7D,%0A%0A + /**%0A * Remove the hidden class on the popover element if this._visible()%0A * returns true.%0A */%0A _show() @@ -3256,24 +3256,77 @@ %7D%0A %7D,%0A%0A + /**%0A * Unconditionally hide popover.%0A */%0A _hide() @@ -3380,93 +3380,380 @@ -_visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A +/**%0A * Determine if the popover should be visible. Returns true%0A * if there are active annotations under the mouse pointer and%0A * the label option is enabled.%0A */%0A _visible() %7B%0A return !this._hidden && this.collection.length %3E 0;%0A %7D,%0A%0A /**%0A * Reset the position of the popover to the position of the%0A * mouse pointer.%0A */%0A _ posi @@ -3939,88 +3939,8 @@ %7D%0A - %7D,%0A%0A toggle(show) %7B%0A this._hidden = !show;%0A this.render();%0A
    828032d625d4246a1d4a86333e962d00e04bcfb6
    test åäö
    src/main/resources/client/components/SiteWrapper/SiteWrapper.js
    src/main/resources/client/components/SiteWrapper/SiteWrapper.js
    'use strict'; // Vendor var _assign = require('lodash/object/assign'); var Vue = require('vue'); var $ = require('jquery'); // Components var TechInfoWindow = require('components/TechInfoWindow/TechInfoWindow.js'); // Utils var AuthenticationUtil = require('utils/AuthenticationUtil/AuthenticationUtil.js'); var TechnicalInfoUtil = require('utils/TechnicalInfoUtil/TechnicalInfoUtil.js'); // CSS modules var styles = _assign( require('./SiteWrapper.css'), require('css/modules/Colors.less') ); /** * Site Wrapper Component */ var SiteWrapperMixin = { props: ['activity'], template: require('./SiteWrapper.html'), data: function() { return { authenticated: false, userModel: {}, _styles: styles, } }, components: { 'tech-info-window': TechInfoWindow }, events: { /* 'authenticate': function() { if(this.authenticated) { this.$broadcast('logged-in', this.userModel); } }, */ 'setTextTitle': function() { } }, ready: function() { /* // Authenticate Authenticationutil.authenticate(function(authenticated, userModel) { if(authenticated) { this.$set('authenticated', true); this.$set('userModel', userModel); this.$broadcast('logged-in', userModel); } }.bind(this)); */ AuthenticationUtil.authenticate(function(authenticated) { if (authenticated.isLoggedIn) { this.$set('authenticated', true); this.$set('userModel', authenticated); } }.bind(this)); // Set GitHub-image this.$els.githubImage1.src = this.$els.githubImage2.src = require('octicons/svg/mark-github.svg'); }, methods: { init: function() { }, checkLoggedInStatus: function() { AuthenticationUtil.authenticate(function(authenticated) { if (!authenticated.isLoggedIn) { var url = '/secure?return='; $(location).attr('href', url + window.location.href); } }); } } }; module.exports = SiteWrapperMixin;
    JavaScript
    0.000001
    @@ -1424,16 +1424,48 @@ cated);%0A +%09%09%09%09console.log(authenticated);%0A %09%09%09%7D%09%0A%09%09
    362901bbe5c73ac8c534675f84aab9e5a62aebd5
    fix unknown error when showing details of expense from /expenses page
    src/apps/expenses/components/PayExpenseBtn.js
    src/apps/expenses/components/PayExpenseBtn.js
    import React from 'react'; import PropTypes from 'prop-types'; import { defineMessages, FormattedMessage } from 'react-intl'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { get } from 'lodash'; import withIntl from '../../../lib/withIntl'; import { isValidEmail } from '../../../lib/utils'; import SmallButton from '../../../components/SmallButton'; class PayExpenseBtn extends React.Component { static propTypes = { expense: PropTypes.object.isRequired, collective: PropTypes.object.isRequired, host: PropTypes.object, disabled: PropTypes.bool, paymentProcessorFeeInCollectiveCurrency: PropTypes.number, hostFeeInCollectiveCurrency: PropTypes.number, platformFeeInCollectiveCurrency: PropTypes.number, lock: PropTypes.func, unlock: PropTypes.func, }; constructor(props) { super(props); this.state = { loading: false, paymentProcessorFeeInCollectiveCurrency: 0, }; this.onClick = this.onClick.bind(this); this.messages = defineMessages({ 'paypal.missing': { id: 'expense.payoutMethod.paypal.missing', defaultMessage: 'Please provide a valid paypal email address', }, }); } async onClick() { const { expense, lock, unlock } = this.props; if (this.props.disabled) { return; } lock(); this.setState({ loading: true }); try { await this.props.payExpense( expense.id, this.props.paymentProcessorFeeInCollectiveCurrency, this.props.hostFeeInCollectiveCurrency, this.props.platformFeeInCollectiveCurrency, ); this.setState({ loading: false }); unlock(); } catch (e) { console.log('>>> payExpense error: ', e); const error = e.message && e.message.replace(/GraphQL error:/, ''); this.setState({ error, loading: false }); unlock(); } } render() { const { collective, expense, intl, host } = this.props; let disabled = this.state.loading, selectedPayoutMethod = expense.payoutMethod, title = '', error = this.state.error; if (expense.payoutMethod === 'paypal') { if (!isValidEmail(get(expense, 'user.paypalEmail')) && !isValidEmail(get(expense, 'user.email'))) { disabled = true; title = intl.formatMessage(this.messages['paypal.missing']); } else { const paypalPaymentMethod = host.paymentMethods && host.paymentMethods.find(pm => pm.service === 'paypal'); if (get(expense, 'user.paypalEmail') === get(paypalPaymentMethod, 'name')) { selectedPayoutMethod = 'other'; } } } if (get(collective, 'stats.balance') < expense.amount) { disabled = true; error = <FormattedMessage id="expense.pay.error.insufficientBalance" defaultMessage="Insufficient balance" />; } return ( <div className="PayExpenseBtn"> <style jsx> {` .PayExpenseBtn { align-items: flex-end; display: flex; flex-wrap: wrap; } .error { display: flex; align-items: center; color: red; font-size: 1.3rem; padding-left: 1rem; } .processorFee { margin-right: 1rem; max-width: 16rem; } .processorFee label { margin: 0; } `} </style> <style global jsx> {` .processorFee .inputField, .processorFee .form-group { margin: 0; } .processorFee .inputField { margin-top: 0.5rem; } `} </style> <SmallButton className="pay" onClick={this.onClick} disabled={this.props.disabled || disabled} title={title}> {selectedPayoutMethod === 'other' && ( <FormattedMessage id="expense.pay.manual.btn" defaultMessage="record as paid" /> )} {selectedPayoutMethod !== 'other' && ( <FormattedMessage id="expense.pay.btn" defaultMessage="pay with {paymentMethod}" values={{ paymentMethod: expense.payoutMethod }} /> )} </SmallButton> <div className="error">{error}</div> </div> ); } } const payExpenseQuery = gql` mutation payExpense( $id: Int! $paymentProcessorFeeInCollectiveCurrency: Int $hostFeeInCollectiveCurrency: Int $platformFeeInCollectiveCurrency: Int ) { payExpense( id: $id paymentProcessorFeeInCollectiveCurrency: $paymentProcessorFeeInCollectiveCurrency hostFeeInCollectiveCurrency: $hostFeeInCollectiveCurrency platformFeeInCollectiveCurrency: $platformFeeInCollectiveCurrency ) { id status collective { id stats { id balance } } } } `; const addMutation = graphql(payExpenseQuery, { props: ({ mutate }) => ({ payExpense: async ( id, paymentProcessorFeeInCollectiveCurrency, hostFeeInCollectiveCurrency, platformFeeInCollectiveCurrency, ) => { return await mutate({ variables: { id, paymentProcessorFeeInCollectiveCurrency, hostFeeInCollectiveCurrency, platformFeeInCollectiveCurrency, }, }); }, }), }); export default addMutation(withIntl(PayExpenseBtn));
    JavaScript
    0
    @@ -2398,22 +2398,38 @@ Method = - +%0A get( host -. +, ' paymentM @@ -2434,16 +2434,18 @@ tMethods +') && host
    ae543be4b0ce6807cbb6b70b09d28bd390290fad
    add default export (#48)
    leveldown.js
    leveldown.js
    const util = require('util') , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN , binding = require('bindings')('leveldown').leveldown , ChainedBatch = require('./chained-batch') , Iterator = require('./iterator') , fs = require('fs') function LevelDOWN (location) { if (!(this instanceof LevelDOWN)) return new LevelDOWN(location) AbstractLevelDOWN.call(this, location) this.binding = binding(location) } util.inherits(LevelDOWN, AbstractLevelDOWN) LevelDOWN.prototype._open = function (options, callback) { this.binding.open(options, callback) } LevelDOWN.prototype._close = function (callback) { this.binding.close(callback) } LevelDOWN.prototype._put = function (key, value, options, callback) { this.binding.put(key, value, options, callback) } LevelDOWN.prototype._get = function (key, options, callback) { this.binding.get(key, options, callback) } LevelDOWN.prototype._del = function (key, options, callback) { this.binding.del(key, options, callback) } LevelDOWN.prototype._chainedBatch = function () { return new ChainedBatch(this) } LevelDOWN.prototype._batch = function (operations, options, callback) { return this.binding.batch(operations, options, callback) } LevelDOWN.prototype.approximateSize = function (start, end, callback) { if (start == null || end == null || typeof start === 'function' || typeof end === 'function') { throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') } if (typeof callback !== 'function') { throw new Error('approximateSize() requires a callback argument') } start = this._serializeKey(start) end = this._serializeKey(end) this.binding.approximateSize(start, end, callback) } LevelDOWN.prototype.compactRange = function (start, end, callback) { this.binding.compactRange(start, end, callback) } LevelDOWN.prototype.getProperty = function (property) { if (typeof property != 'string') throw new Error('getProperty() requires a valid `property` argument') return this.binding.getProperty(property) } LevelDOWN.prototype._iterator = function (options) { return new Iterator(this, options) } LevelDOWN.destroy = function (location, callback) { if (arguments.length < 2) throw new Error('destroy() requires `location` and `callback` arguments') if (typeof location != 'string') throw new Error('destroy() requires a location string argument') if (typeof callback != 'function') throw new Error('destroy() requires a callback function argument') binding.destroy(location, function (err) { if (err) return callback(err) // On Windows, RocksDB silently fails to remove the directory because its // Logger, which is instantiated on destroy(), has an open file handle on a // LOG file. Destroy() removes this file but Windows won't actually delete // it until the handle is released. This happens when destroy() goes out of // scope, which disposes the Logger. So back in JS-land, we can again // attempt to remove the directory. This is merely a workaround because // arguably RocksDB should not instantiate a Logger or open a file at all. fs.rmdir(location, function (err) { if (err) { // Ignore this error in case there are non-RocksDB files left. if (err.code === 'ENOTEMPTY') return callback() if (err.code === 'ENOENT') return callback() return callback(err) } callback() }) }) } LevelDOWN.repair = function (location, callback) { if (arguments.length < 2) throw new Error('repair() requires `location` and `callback` arguments') if (typeof location != 'string') throw new Error('repair() requires a location string argument') if (typeof callback != 'function') throw new Error('repair() requires a callback function argument') binding.repair(location, callback) } module.exports = LevelDOWN
    JavaScript
    0
    @@ -3997,16 +3997,36 @@ xports = + LevelDOWN.default = LevelDO
    5b3a17e24efcf7603f0fd73d8eabd8fb516ee536
    fix wrong this context (#4352)
    lib/workers/repository/process/lookup/rollback.js
    lib/workers/repository/process/lookup/rollback.js
    const { logger } = require('../../../../logger'); const versioning = require('../../../../versioning'); module.exports = { getRollbackUpdate, }; function getRollbackUpdate(config, versions) { const { packageFile, versionScheme, depName, currentValue } = config; const version = versioning.get(versionScheme); // istanbul ignore if if (!version.isLessThanRange) { logger.info( { versionScheme }, 'Current version scheme does not support isLessThanRange()' ); return null; } const lessThanVersions = versions.filter(v => version.isLessThanRange(v, currentValue) ); // istanbul ignore if if (!lessThanVersions.length) { logger.info( { packageFile, depName, currentValue }, 'Missing version has nothing to roll back to' ); return null; } logger.info( { packageFile, depName, currentValue }, `Current version not found - rolling back` ); logger.debug( { dependency: depName, versions }, 'Versions found before rolling back' ); lessThanVersions.sort(version.sortVersions); const toVersion = lessThanVersions.pop(); // istanbul ignore if if (!toVersion) { logger.info('No toVersion to roll back to'); return null; } let fromVersion; const newValue = version.getNewValue( currentValue, 'replace', fromVersion, toVersion ); return { updateType: 'rollback', branchName: '{{{branchPrefix}}}rollback-{{{depNameSanitized}}}-{{{newMajor}}}.x', commitMessageAction: 'Roll back', isRollback: true, newValue, newMajor: version.getMajor(toVersion), semanticCommitType: 'fix', }; }
    JavaScript
    0.000011
    @@ -1039,16 +1039,26 @@ ns.sort( +(a, b) =%3E version. @@ -1069,16 +1069,22 @@ Versions +(a, b) );%0A con
    c2e3d2b8ca5ebe76fc12a08038bf9251c43bdbac
    Fix time differences (add 1 second)
    src/client/rest/RequestHandlers/Sequential.js
    src/client/rest/RequestHandlers/Sequential.js
    const RequestHandler = require('./RequestHandler'); /** * Handles API Requests sequentially, i.e. we wait until the current request is finished before moving onto * the next. This plays a _lot_ nicer in terms of avoiding 429's when there is more than one session of the account, * but it can be slower. * @extends {RequestHandler} */ module.exports = class SequentialRequestHandler extends RequestHandler { constructor(restManager) { super(restManager); /** * Whether this rate limiter is waiting for a response from a request * @type {Boolean} */ this.waiting = false; /** * The time difference between Discord's Dates and the local computer's Dates. A positive number means the local * computer's time is ahead of Discord's. * @type {Number} */ this.timeDifference = 0; } push(request) { super.push(request); this.handle(); } /** * Performs a request then resolves a promise to indicate its readiness for a new request * @param {APIRequest} item the item to execute * @returns {Promise<Object, Error>} */ execute(item) { return new Promise((resolve, reject) => { item.request.gen().end((err, res) => { if (res && res.headers) { this.requestLimit = res.headers['x-ratelimit-limit']; this.requestResetTime = Number(res.headers['x-ratelimit-reset']) * 1000; this.requestRemaining = Number(res.headers['x-ratelimit-remaining']); this.timeDifference = Date.now() - new Date(res.headers.date).getTime(); } if (err) { if (err.status === 429) { setTimeout(() => { this.waiting = false; resolve(); }, res.headers['retry-after']); } else { this.queue.shift(); this.waiting = false; item.reject(err); resolve(err); } } else { this.queue.shift(); const data = res && res.body ? res.body : {}; item.resolve(data); if (this.requestRemaining === 0) { setTimeout(() => { this.waiting = false; resolve(data); }, (this.requestResetTime - Date.now()) + this.timeDifference - 1000); } else { this.waiting = false; resolve(data); } } }); }); } handle() { super.handle(); if (this.waiting || this.queue.length === 0) { return; } this.waiting = true; const item = this.queue[0]; this.execute(item).then(() => this.handle()); } };
    JavaScript
    0.000059
    @@ -2251,17 +2251,17 @@ ference -- ++ 1000);%0A
    c0d9881a621bd39be404fb0905fd11843d0ff4c9
    add memoryUsageHeap value
    src/node/server.js
    src/node/server.js
    #!/usr/bin/env node 'use strict'; /** * This module is started with bin/run.sh. It sets up a Express HTTP and a Socket.IO Server. * Static file Requests are answered directly from this module, Socket.IO messages are passed * to MessageHandler and minfied requests are passed to minified. */ /* * 2011 Peter 'Pita' Martischka (Primary Technology 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. */ const log4js = require('log4js'); log4js.replaceConsole(); /* * early check for version compatibility before calling * any modules that require newer versions of NodeJS */ const NodeVersion = require('./utils/NodeVersion'); NodeVersion.enforceMinNodeVersion('10.13.0'); NodeVersion.checkDeprecationStatus('10.13.0', '1.8.3'); const UpdateCheck = require('./utils/UpdateCheck'); const db = require('./db/DB'); const express = require('./hooks/express'); const hooks = require('../static/js/pluginfw/hooks'); const npm = require('npm/lib/npm.js'); const plugins = require('../static/js/pluginfw/plugins'); const settings = require('./utils/Settings'); const util = require('util'); let started = false; let stopped = false; exports.start = async () => { if (started) return express.server; started = true; if (stopped) throw new Error('restart not supported'); // Check if Etherpad version is up-to-date UpdateCheck.check(); // start up stats counting system const stats = require('./stats'); stats.gauge('memoryUsage', () => process.memoryUsage().rss); await util.promisify(npm.load)(); try { await db.init(); await plugins.update(); console.info(`Installed plugins: ${plugins.formatPluginsWithVersion()}`); console.debug(`Installed parts:\n${plugins.formatParts()}`); console.debug(`Installed hooks:\n${plugins.formatHooks()}`); await hooks.aCallAll('loadSettings', {settings}); await hooks.aCallAll('createServer'); } catch (e) { console.error(`exception thrown: ${e.message}`); if (e.stack) console.log(e.stack); process.exit(1); } process.on('uncaughtException', exports.exit); /* * Connect graceful shutdown with sigint and uncaught exception * * Until Etherpad 1.7.5, process.on('SIGTERM') and process.on('SIGINT') were * not hooked up under Windows, because old nodejs versions did not support * them. * * According to nodejs 6.x documentation, it is now safe to do so. This * allows to gracefully close the DB connection when hitting CTRL+C under * Windows, for example. * * Source: https://nodejs.org/docs/latest-v6.x/api/process.html#process_signal_events * * - SIGTERM is not supported on Windows, it can be listened on. * - SIGINT from the terminal is supported on all platforms, and can usually * be generated with <Ctrl>+C (though this may be configurable). It is not * generated when terminal raw mode is enabled. */ process.on('SIGINT', exports.exit); // When running as PID1 (e.g. in docker container) allow graceful shutdown on SIGTERM c.f. #3265. // Pass undefined to exports.exit because this is not an abnormal termination. process.on('SIGTERM', () => exports.exit()); // Return the HTTP server to make it easier to write tests. return express.server; }; exports.stop = async () => { if (stopped) return; stopped = true; console.log('Stopping Etherpad...'); await new Promise(async (resolve, reject) => { const id = setTimeout(() => reject(new Error('Timed out waiting for shutdown tasks')), 3000); await hooks.aCallAll('shutdown'); clearTimeout(id); resolve(); }); }; exports.exit = async (err) => { let exitCode = 0; if (err) { exitCode = 1; console.error(err.stack ? err.stack : err); } try { await exports.stop(); } catch (err) { exitCode = 1; console.error(err.stack ? err.stack : err); } process.exit(exitCode); }; if (require.main === module) exports.start();
    JavaScript
    0
    @@ -1991,16 +1991,88 @@ ().rss); +%0A stats.gauge('memoryUsageHeap', () =%3E process.memoryUsage().heapUsed); %0A%0A awai
    928ce8b8f980c89e9419f2174f7efa6dabf14334
    update delete user JSON message
    lib/controllers/users.js
    lib/controllers/users.js
    const express = require('express'); const router = express.Router(); // eslint-disable-line new-cap const async = require('async'); const UserModel = require('../models/user'); const authenticate = require('../middlewares/authenticate'); const authorise = require('../middlewares/authorise'); router.use('/users', authenticate); // Create user router.post('/users', authorise('admin')); router.post('/users', (req, res) => { UserModel.create(req.body, (err, user) => { if (err) { res.json({ status: 'fail', meta: { message: 'The user could not be created. Check validation.', validation: err.errors, }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was created.', }, data: userObj, }); } }); }); // List users router.get('/users', authorise('admin')); router.get('/users', (req, res) => { const page = req.query.page || 1; const limit = 20; async.parallel({ total: function total(cb) { UserModel.count(cb); }, users: function users(cb) { UserModel .find() .select('name username') .skip(limit * (page - 1)) .limit(limit) .lean() .exec(cb); }, }, (err, result) => { if (err) { res.status(500).json({ status: 'fail', meta: { message: 'The query could not be executed.', }, data: null, }); } else { res.json({ status: 'success', meta: { paginate: { total: result.total, previous: ((page > 1) ? page - 1 : null), next: (((limit * page) < result.total) ? page + 1 : null), }, }, data: result.users, }); } }); }); // Get current user router.get('/users/me', (req, res) => { UserModel.findById(req.jwt.id, (err, user) => { if (err) { res.json({ status: 'error', meta: { message: 'User information could not be found.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'User information could not be found.', }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was found.', }, data: userObj, }); } }); }); // Get user router.get('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findById(req.params.user, (err, user) => { if (err) { res.json({ status: 'error', meta: { message: 'User information could not be found.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'User information could not be found.', }, data: null, }); } else { const userObj = user.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was found.', }, data: userObj, }); } }); }); // Update user router.put('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findById(req.params.user, (err, user) => { if (err) { res.json({ status: 'fail', meta: { message: 'The user could not be updated.', }, data: null, }); } else if (user === null) { res.json({ status: 'fail', meta: { message: 'The user was not found and could not be updated.', }, data: null, }); } else { user.set(req.body).save((saveErr, updatedUser) => { if (saveErr) { res.json({ status: 'fail', meta: { message: 'The user could not be updated. Check validation.', validation: saveErr.errors, }, data: null, }); } else { const userObj = updatedUser.toObject(); delete userObj.password; res.json({ status: 'success', meta: { message: 'The user was updated.', }, data: userObj, }); } }); } }); }); // Delete user router.delete('/users/:user', (req, res) => { if ((req.params.user !== req.jwt.id) && (req.jwt.role !== 'admin')) { return res.json({ status: 'fail', meta: { message: 'You are not authorised.', }, data: null, }); } UserModel.findByIdAndRemove(req.params.user, err => { if (err) { res.json({ status: 'error', meta: { message: 'The user could not be updated.', }, data: null, }); } else { res.json({ status: 'success', meta: { message: 'The user was deleted', }, data: null, }); } }); }); module.exports = router;
    JavaScript
    0.000001
    @@ -5333,36 +5333,36 @@ er could not be -upda +dele ted.',%0A %7D
    1eeee314affb486acc249d670452063b78e42e49
    refactor the Index module for readability and testability
    lib/Index.js
    lib/Index.js
    'use strict'; const path = require('path'); const defaults = require('defa'); const Sequelize = require('sequelize'); class Index { constructor(options) { defaults(options, { 'filename': () => path.join(process.cwd(), '.index') }); this.prepareDb(options.filename); } sync() { if (!this.ready) this.ready = this.Result.sync(); return this.ready; } log() { // do nothing // TODO log it somewhere } /** * Prepare the database and insert models and stuff * @param {String} filename * @returns {Promise} */ prepareDb(filename) { const sequelize = new Sequelize('cachething', 'carrier', null, { 'dialect': 'sqlite', 'storage': filename, 'logging': msg => this.log(msg) }); this.db = sequelize; this.Result = sequelize.define('Result', { action: Sequelize.STRING, fileHash: Sequelize.STRING, outputHash: Sequelize.STRING, created: Sequelize.BIGINT, expires: Sequelize.BIGINT, fileName: Sequelize.STRING, compressed: Sequelize.BOOLEAN, fileSize: Sequelize.BIGINT, runtime: Sequelize.BIGINT }); } } module.exports = Index;
    JavaScript
    0.000004
    @@ -18,14 +18,24 @@ nst -path +%7Bnoop, defaults%7D @@ -45,19 +45,21 @@ equire(' -pat +lodas h');%0Acon @@ -61,24 +61,34 @@ ;%0Aconst -defaults +path = requ @@ -92,20 +92,20 @@ equire(' -defa +path ');%0Acons @@ -116,16 +116,26 @@ quelize + = requir @@ -162,24 +162,62 @@ ss Index %7B%0A%0A + /**%0A * @param options%0A */%0A construc @@ -239,16 +239,26 @@ %0A + options = default @@ -286,17 +286,16 @@ -' filename ': ( @@ -294,16 +294,9 @@ name -' : - () =%3E pat @@ -330,34 +330,85 @@ ex') -%0A %7D);%0A%0A this +,%0A log: noop,%0A %7D);%0A%0A const %7Bdb, Result%7D = Index .pre @@ -425,152 +425,185 @@ ions -.filename );%0A +%0A -%7D%0A%0A -sync() %7B%0A if (!this.ready) +this.db = db;%0A this.Result = Result; %0A +%7D%0A%0A - this.ready = this.Result.sync();%0A +/**%0A * Prepare the %22Result%22 collection for mutations %0A +*%0A + * @ return - this.ready; +s %7BPromise%7D %0A -%7D%0A + */ %0A -log +sync () %7B @@ -615,54 +615,84 @@ -// do nothing%0A // TODO log it somewhere +if (!this.ready) this.ready = this.Result.sync();%0A return this.ready; %0A @@ -734,36 +734,15 @@ base - and insert models and stuff +%0A * %0A @@ -761,16 +761,24 @@ String%7D +options. filename @@ -786,32 +786,99 @@ * @ -returns %7BPromise +param %7BFunction%7D options.log%0A *%0A * @returns %7B%7Bdb: Sequelize, result: Model%7D %7D%0A * @@ -883,16 +883,23 @@ */%0A +static prepareD @@ -900,24 +900,23 @@ epareDb( -filename +options ) %7B%0A%0A @@ -926,25 +926,18 @@ const -sequelize +db = new S @@ -1034,16 +1034,24 @@ orage': +options. filename @@ -1079,28 +1079,20 @@ g': -msg =%3E this.log(msg) +options.log, %0A @@ -1113,61 +1113,273 @@ -this.db = sequelize;%0A%0A this.Result = sequelize +const Result = Index.defineResultModel(db);%0A%0A return %7Bdb, Result%7D;%0A %7D%0A%0A /**%0A * Define the %22Result%22 model on the given database instance%0A * @param db%0A * @returns %7B*%7Cvoid%7CModel%7C%7B%7D%7D%0A */%0A static defineResultModel(db) %7B%0A%0A return db .def
    551054d702cd378e598dbbdee9731e540b9acf42
    Remove comment
    lib/core/shared/store.js
    lib/core/shared/store.js
    /* * Kuzzle, a backend software, self-hostable and ready to use * to power modern apps * * Copyright 2015-2020 Kuzzle * mailto: support AT kuzzle.io * website: http://kuzzle.io * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; const { Mutex } = require('../../util/mutex'); const { promiseAllN } = require('../../util/async'); const kerror = require('../../kerror'); const { getESIndexDynamicSettings } = require('../../util/esRequest'); /** * Wrapper around the document store. * Once instantiated, this class can only access the index passed in the * constructor */ class Store { /** * @param {Kuzzle} kuzzle * @param {String} index * @param {storeScopeEnum} scope */ constructor (index, scope) { this.index = index; this.scope = scope; const methodsMapping = { count: `core:storage:${scope}:document:count`, create: `core:storage:${scope}:document:create`, createCollection: `core:storage:${scope}:collection:create`, createOrReplace: `core:storage:${scope}:document:createOrReplace`, delete: `core:storage:${scope}:document:delete`, deleteByQuery: `core:storage:${scope}:document:deleteByQuery`, deleteCollection: `core:storage:${scope}:collection:delete`, deleteFields: `core:storage:${scope}:document:deleteFields`, deleteIndex: `core:storage:${scope}:index:delete`, exists: `core:storage:${scope}:document:exist`, get: `core:storage:${scope}:document:get`, getMapping: `core:storage:${scope}:mappings:get`, getSettings: `core:storage:${scope}:collection:settings:get`, mExecute: `core:storage:${scope}:document:mExecute`, mGet: `core:storage:${scope}:document:mGet`, refreshCollection: `core:storage:${scope}:collection:refresh`, replace: `core:storage:${scope}:document:replace`, search: `core:storage:${scope}:document:search`, truncateCollection: `core:storage:${scope}:collection:truncate`, update: `core:storage:${scope}:document:update`, updateByQuery: `core:storage:${scope}:document:updateByQuery`, updateCollection: `core:storage:${scope}:collection:update`, updateMapping: `core:storage:${scope}:mappings:update`, }; for (const [method, event] of Object.entries(methodsMapping)) { this[method] = (...args) => global.kuzzle.ask(event, this.index, ...args); } // the scroll and multiSearch method are special: they doesn't need an index parameter // we keep them for ease of use this.scroll = (scrollId, opts) => global.kuzzle.ask( `core:storage:${scope}:document:scroll`, scrollId, opts); this.multiSearch = (targets, searchBody, opts) => global.kuzzle.ask( `core:storage:${scope}:document:multiSearch`, targets, searchBody, opts ); } /** * Initialize the index, and creates provided collections * * @param {Object} collections - List of collections with mappings to create * * @returns {Promise} */ async init (collections = {}) { const creatingMutex = new Mutex(`Store.init(${this.index})`, { timeout: 0, ttl: 30000, }); const creatingLocked = await creatingMutex.lock(); if (creatingLocked) { try { await this.createCollections(collections, { indexCacheOnly: false }); } finally { await creatingMutex.unlock(); } } else { // Ensure that cached collection are used after being properly // created by a kuzzle cluster const cachingMutex = new Mutex(`Store.init(${this.index})`, { timeout: -1, ttl: 30000, }); await cachingMutex.lock(); cachingMutex.unlock(); await this.createCollections(collections, { indexCacheOnly: true }); } } /** * Creates collections with the provided mappings * * @param {Object} collections - collections with mappings * * @returns {Promise} */ createCollections ( collections, { indexCacheOnly = false } = {} ) { return promiseAllN( Object.entries(collections).map( ([collection, config]) => async () => { // @deprecated if (config.mappings !== undefined && config.settings !== undefined) { // @deprecated const isConfigDeprecated = config.settings.number_of_shards === undefined && config.settings.number_of_replicas === undefined; if (indexCacheOnly) { return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, { indexCacheOnly }); } const exist = await global.kuzzle.ask( `core:storage:${this.scope}:collection:exist`, this.index, collection); if (exist) { // @deprecated const dynamicSettings = (isConfigDeprecated) ? null : getESIndexDynamicSettings(config.settings); const existingSettings = await global.kuzzle.ask( `core:storage:${this.scope}:collection:settings:get`, this.index, collection); if (! isConfigDeprecated && parseInt(existingSettings.number_of_shards) !== config.settings.number_of_shards ) { if (global.NODE_ENV === 'development') { throw kerror.get( 'storage', 'wrong_collection_number_of_shards', collection, this.index, this.scope, 'number_of_shards', config.settings.number_of_shards, existingSettings.number_of_shards); } global.kuzzle.log.warn([ 'Attempt to recreate', `an existing collection ${collection}`, `of index ${this.index} of scope ${this.scope}`, 'with non matching', 'static setting : number_of_shards', `at ${config.settings.number_of_shards} while existing one`, `is at ${existingSettings.number_of_shards}`, ].join('\n')); } // Create call will update collection and cache it internally return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated (isConfigDeprecated) ? { mappings: config.mappings } : { mappings: config.mappings, settings: dynamicSettings }, ); } return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, // @deprecated isConfigDeprecated ? { mappings: config.mappings } : config, { indexCacheOnly }); } // @deprecated return global.kuzzle.ask( `core:storage:${this.scope}:collection:create`, this.index, collection, { mappings: config }, { indexCacheOnly }); } ), 10 ); } } module.exports = Store;
    JavaScript
    0
    @@ -6963,84 +6963,8 @@ %7D%0A%0A - // Create call will update collection and cache it internally%0A @@ -7311,24 +7311,65 @@ Settings %7D,%0A + %7B indexCacheOnly: true %7D%0A
    be75c469b7d90952e89a9ee7c87ea7ad017cd104
    Allow alias exploding
    plugins/aliases.js
    plugins/aliases.js
    // This is the aliases plugin // One must not run this plugin with the queue/smtp_proxy plugin. var Address = require('address-rfc2821').Address; exports.register = function () { this.inherits('queue/discard'); this.register_hook('rcpt','aliases'); }; exports.aliases = function (next, connection, params) { var plugin = this; var config = this.config.get('aliases', 'json') || {}; var rcpt = params[0].address(); var user = params[0].user; var host = params[0].host; var match = user.split("-", 1); var action = "<missing>"; if (config[rcpt]) { action = config[rcpt].action || action; match = rcpt; switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, rcpt); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } if (config['@'+host]) { action = config['@'+host].action || action; match = '@'+host; switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, '@'+host); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } if (config[user] || config[match[0]]) { if (config[user]) { action = config[user].action || action; match = user; } else { action = config[match[0]].action || action; match = match[0]; } switch (action.toLowerCase()) { case 'drop': _drop(plugin, connection, rcpt); break; case 'alias': _alias(plugin, connection, match, config[match], host); break; default: connection.loginfo(plugin, "unknown action: " + action); } } next(); }; function _drop(plugin, connection, rcpt) { connection.logdebug(plugin, "marking " + rcpt + " for drop"); connection.transaction.notes.discard = true; } function _alias(plugin, connection, key, config, host) { var to; var toAddress; if (config.to) { if (config.to.search("@") !== -1) { to = config.to; } else { to = config.to + '@' + host; } connection.logdebug(plugin, "aliasing " + connection.transaction.rcpt_to + " to " + to); toAddress = new Address('<' + to + '>'); connection.transaction.rcpt_to.pop(); connection.transaction.rcpt_to.push(toAddress); } else { connection.loginfo(plugin, 'alias failed for ' + key + ', no "to" field in alias config'); } }
    JavaScript
    0.000005
    @@ -2422,16 +2422,20 @@ ddress;%0A + %0A if @@ -2444,24 +2444,444 @@ onfig.to) %7B%0A + if (Array.isArray(config.to)) %7B%0A connection.logdebug(plugin, %22aliasing %22 + connection.transaction.rcpt_to + %22 to %22 + config.to);%0A connection.transaction.rcpt_to.pop();%0A for (var i = 0, len = config.to.length; i %3C len; i++) %7B%0A toAddress = new Address('%3C' + config.to%5Bi%5D + '%3E');%0A connection.transaction.rcpt_to.push(toAddress);%0A %7D%0A %7D else %7B%0A if ( @@ -2908,24 +2908,28 @@ ) !== -1) %7B%0A + @@ -2951,34 +2951,30 @@ %0A - %7D%0A - +%7D else %7B%0A @@ -2957,32 +2957,36 @@ %7D else %7B%0A + to = @@ -3010,35 +3010,55 @@ + host;%0A -%7D%0A%0A + %7D%0A %0A connecti @@ -3091,16 +3091,20 @@ ing %22 +%0A + @@ -3154,25 +3154,40 @@ + to);%0A -%0A + %0A toAddres @@ -3170,32 +3170,33 @@ %0A + toAddress = new @@ -3220,32 +3220,36 @@ + '%3E');%0A + connection.trans @@ -3270,32 +3270,36 @@ .pop();%0A + + connection.trans @@ -3326,24 +3326,28 @@ toAddress);%0A + %7D%0A el @@ -3343,16 +3343,18 @@ %7D%0A + %7D else %7B%0A
    70fc4295de4e9123f90bbf9e18749d990e2da403
    Fix indentation
    simplePagination.spec.js
    simplePagination.spec.js
    'use strict'; describe('Simple Pagination', function() { var pagination; // load the app beforeEach(module('SimplePagination')); // get service beforeEach(inject(function(Pagination) { pagination = Pagination.getNew(); })); it('should paginate', function() { pagination.numPages = 2; expect(pagination.page).toBe(0); pagination.nextPage(); expect(pagination.page).toBe(1); pagination.prevPage(); expect(pagination.page).toBe(0); }); it('should not paginate outside min and max page', function() { pagination.numPages = 2; pagination.page = 0; pagination.prevPage(); expect(pagination.page).toBe(0); pagination.page = 1; pagination.nextPage(); expect(pagination.page).toBe(1); }); it('should jump to a given page id', function() { pagination.numPages = 3; expect(pagination.page).toBe(0); pagination.toPageId(2); expect(pagination.page).toBe(2); }); });
    JavaScript
    0.017244
    @@ -52,17 +52,18 @@ on() %7B%0A%0A -%09 + var pagi @@ -71,17 +71,18 @@ ation;%0A%0A -%09 + // load @@ -89,17 +89,18 @@ the app%0A -%09 + beforeEa @@ -132,17 +132,18 @@ on'));%0A%0A -%09 + // get s @@ -150,17 +150,18 @@ ervice %0A -%09 + beforeEa @@ -189,26 +189,28 @@ gination) %7B%0A -%09%09 + pagination = @@ -235,16 +235,18 @@ ();%0A -%09 + %7D));%0A%0A -%09 + it(' @@ -268,34 +268,36 @@ ', function() %7B%0A -%09%09 + pagination.numPa @@ -306,18 +306,20 @@ s = 2;%0A%0A -%09%09 + expect(p @@ -336,34 +336,36 @@ page).toBe(0);%0A%0A -%09%09 + pagination.nextP @@ -363,34 +363,36 @@ ion.nextPage();%0A -%09%09 + expect(paginatio @@ -412,18 +412,20 @@ 1); %0A%0A -%09%09 + paginati @@ -440,18 +440,20 @@ age(); %0A -%09%09 + expect(p @@ -477,23 +477,25 @@ oBe(0);%0A -%09 + %7D);%0A%0A -%09 + it('shou @@ -542,34 +542,36 @@ ', function() %7B%0A -%09%09 + pagination.numPa @@ -580,18 +580,20 @@ s = 2;%0A%0A -%09%09 + paginati @@ -605,18 +605,20 @@ ge = 0;%0A -%09%09 + paginati @@ -624,34 +624,36 @@ ion.prevPage();%0A -%09%09 + expect(paginatio @@ -662,34 +662,36 @@ page).toBe(0);%0A%0A -%09%09 + pagination.page @@ -695,18 +695,20 @@ ge = 1;%0A -%09%09 + paginati @@ -722,18 +722,20 @@ Page();%0A -%09%09 + expect(p @@ -763,15 +763,17 @@ 1);%0A -%09 + %7D);%0A%0A -%09 + it(' @@ -818,18 +818,20 @@ ion() %7B%0A -%09%09 + paginati @@ -848,18 +848,20 @@ s = 3;%0A%0A -%09%09 + expect(p @@ -886,18 +886,20 @@ Be(0);%0A%0A -%09%09 + paginati @@ -918,10 +918,12 @@ 2);%0A -%09%09 + expe @@ -955,9 +955,10 @@ 2);%0A -%09 + %7D);%0A
    f6faa3bc938bb92cbe7497b228eeeba0ca256020
    Edit comment
    core/tests/protractor/cacheSlugs.js
    core/tests/protractor/cacheSlugs.js
    // Copyright 2016 The Oppia Authors. 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. /** * @fileoverview End-to-end tests for cache slugs. */ var general = require('../protractor_utils/general.js'); var ERROR_PAGE_URL_SUFFIX = '/console_errors'; var getUniqueLogMessages = function(logs) { // Returns unique log messages. var logsDict = {}; for (var i = 0; i < logs.length; i++) { if (!logsDict.hasOwnProperty(logs[i].message)) { logsDict[logs[i].message] = true; } } return Object.keys(logsDict); }; var checkConsoleErrorsExist = function(expectedErrors) { // Checks that browser logs match entries in expectedErrors array. browser.manage().logs().get('browser').then(function(browserLogs) { // Some browsers such as chrome raise two errors for a missing resource. // To keep consistent behaviour across browsers, we keep only the logs // that have a unique value for their message attribute. var uniqueLogMessages = getUniqueLogMessages(browserLogs); expect(uniqueLogMessages.length).toBe(expectedErrors.length); for (var i = 0; i < expectedErrors.length; i++) { var errorPresent = false; for (var j = 0; j < uniqueLogMessages.length; j++) { if (uniqueLogMessages[j].match(expectedErrors[i])) { errorPresent = true; } } expect(errorPresent).toBe(true); } }); }; describe('Cache Slugs', function() { it('should check that errors get logged for missing resources', function() { browser.get(ERROR_PAGE_URL_SUFFIX); var expectedErrors = [ 'http://localhost:9001/build/fail/logo/288x128_logo_white.png', // Warning fired by synchronous AJAX request in // core/templates/dev/head/pages/header_js_libs.html this warning is // expected and it's needed for constants loading. 'Synchronous XMLHttpRequest on the main thread' ]; checkConsoleErrorsExist(expectedErrors); }); });
    JavaScript
    0
    @@ -2271,18 +2271,28 @@ ibs.html - t +.%0A // T his warn @@ -2297,25 +2297,16 @@ rning is -%0A // expecte
    7a8f39067376f44c30b688e960d980b1cafe2337
    Add 'add' to projectDeploy provided interface
    core/cb.project.deploy/main.js
    core/cb.project.deploy/main.js
    // Requires var _ = require('underscore'); var DeploymentSolution = require("./solution").DeploymentSolution; // List of all deployment solution var SUPPORTED = []; function setup(options, imports, register) { // Import var logger = imports.logger.namespace("deployment"); var events = imports.events; var workspace = imports.workspace; // Return a specific solution var getSolution = function(solutionId) { return _.find(SOLUTIONS, function(solution) { return solution.id == solutionId; }); }; // Add a solution var addSolution = function(solution) { if (!_.isArray(solution)) solution = [solution]; _.each(solution, function(_sol) { SUPPORTED.push(new DeploymentSolution(workspace, events, logger, _sol)); }); } // Add basic solutions addSolution([ require("./ghpages") ]) // Register register(null, { 'projectDeploy': { 'SUPPORTED': SUPPORTED, 'get': getSolution } }); } // Exports module.exports = setup;
    JavaScript
    0.000001
    @@ -814,16 +814,17 @@ );%0A %7D +; %0A%0A%0A / @@ -1026,24 +1026,56 @@ getSolution +,%0A 'add': addSolution %0A %7D%0A
    66d067a35ed2fcaf9decaad683ebeb2f563b2117
    Add styling clases to fix buttons appearing white on iOS
    src/main/web/js/app/mobile-table.js
    src/main/web/js/app/mobile-table.js
    $(function() { var markdownTable = $('.markdown-table-wrap'); if (markdownTable.length) { $('<button class="btn btn--mobile-table-show">View table</button>').insertAfter(markdownTable); $('<button class="btn btn--mobile-table-hide">Close table</button>').insertAfter(markdownTable.find('table')); $('.btn--mobile-table-show').click(function () { $(this).closest('.markdown-table-container').find('.markdown-table-wrap').show(); }); $('.btn--mobile-table-hide').click(function () { $(this).closest('.markdown-table-wrap').css('display', ''); }); } });
    JavaScript
    0
    @@ -114,32 +114,47 @@ tton class=%22btn +btn--secondary btn--mobile-tabl @@ -237,24 +237,39 @@ class=%22btn +btn--secondary btn--mobile-
    285bdf6c56f70fb2fd0a8fc7e881d244bf8a6cd0
    Remove odd html tags
    src/components/NavigationBar/NavigationBar.js
    src/components/NavigationBar/NavigationBar.js
    import React from 'react' import { Link } from 'react-router-dom'; import './navigation-bar.css'; import { isAuthenticated } from '../../helper/auth'; import * as firebase from 'firebase'; class NavigationBar extends React.Component { signout() { firebase.auth().signOut(); } authenticated() { return ( <div className="navigation-bar__wrapper"> <div className="navigation-bar__placeholder"></div> <nav className="navigation-bar"> <div className="navigation-bar__item--flex"> <Link className="navigation-bar__link" to="/">Home</Link> </div> <div className="navigation-bar__item"> <Link className="navigation-bar__link" to="/admin">Admin</Link> <a className="navigation-bar__link" onClick={this.signout} >Sign Out</a> </div> </nav> </div> ) } unauthenticated() { return ( <div className="navigation-bar__wrapper"> <div className="navigation-bar__placeholder"></div> <nav className="navigation-bar"> <div className="navigation-bar__item--flex"> <Link className="navigation-bar__link" to="/">Home</Link> </div> <div className="navigation-bar__item"> <Link className="navigation-bar__link" to="/signin">Sign In</Link> </div> </nav> </div> ) } render() { if (isAuthenticated()) { return this.authenticated(); } else { return this.unauthenticated(); } } } export { NavigationBar }
    JavaScript
    0.999801
    @@ -344,170 +344,46 @@ - %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A +%3Cnav className=%22navigation-bar glow%22%3E%0A @@ -451,36 +451,32 @@ - %3CLink className= @@ -497,36 +497,41 @@ r__link%22 to=%22/%22%3E -Home +Biografia %3C/Link%3E%0A @@ -530,36 +530,32 @@ - %3C/div%3E%0A @@ -553,36 +553,32 @@ - - %3Cdiv className=%22 @@ -592,36 +592,32 @@ ion-bar__item%22%3E%0A - @@ -704,20 +704,16 @@ - - %3Ca class @@ -789,39 +789,31 @@ - - %3C/div%3E%0A - %3C @@ -818,34 +818,16 @@ %3C/nav%3E%0A - %3C/div%3E%0A @@ -891,170 +891,41 @@ - %3Cdiv className=%22navigation-bar__wrapper%22%3E%0A %3Cdiv className=%22navigation-bar__placeholder%22%3E%3C/div%3E%0A %3Cnav className=%22navigation-bar%22%3E%0A +%3Cnav className=%22navigation-bar%22%3E%0A @@ -973,36 +973,32 @@ r__item--flex%22%3E%0A - @@ -1051,12 +1051,17 @@ %22/%22%3E -Home +Biografia %3C/Li @@ -1072,36 +1072,32 @@ - %3C/div%3E%0A @@ -1095,36 +1095,32 @@ - - %3Cdiv className=%22 @@ -1134,36 +1134,32 @@ ion-bar__item%22%3E%0A - @@ -1221,36 +1221,32 @@ %3ESign In%3C/Link%3E%0A - @@ -1267,34 +1267,12 @@ - %3C/nav%3E%0A %3C/di +%3C/na v%3E%0A
    207f9e63434b1c191b8d3296e17e1bb881c580c0
    reset board on start
    lib/board/index.js
    lib/board/index.js
    import bus from 'component/bus' import Board from 'kvnneff/[email protected]' export default function plugin () { return function (app) { var board = new Board() app.set('board', board.json()) board.on('change', function () { app.set('board', board.json()) }) bus.on('player:move', function (direction) { board.move(direction) }) bus.on('game:begin', function () { board.start() }) bus.on('client', function (data) { board.sync(data.board) }) bus.on('game:stop', function () { board.stop() }) } }
    JavaScript
    0.000001
    @@ -404,32 +404,52 @@ , function () %7B%0A + board.reset()%0A board.star
    965716143e75bb52d4979986fd35e9b4bbc1acde
    use 1 for env instead of true, since it becomes a string
    lib/boilerplate.js
    lib/boilerplate.js
    "use strict"; var mocha = require('gulp-mocha'), Q = require('q'), Transpiler = require('../index').Transpiler, jshint = require('gulp-jshint'), jscs = require('gulp-jscs'), vinylPaths = require('vinyl-paths'), del = require('del'), _ = require('lodash'); var DEFAULT_OPTS = { files: ["*.js", "lib/**/*.js", "test/**/*.js", "!gulpfile.js"], transpile: true, transpileOut: "build", babelOpts: {}, linkBabelRuntime: true, jscs: true, jshint: true, watch: true, test: true, testFiles: null, testReporter: 'nyan', testTimeout: 8000, buildName: null }; var boilerplate = function (gulp, opts) { var spawnWatcher = require('../index').spawnWatcher.use(gulp); var runSequence = Q.denodeify(require('run-sequence').use(gulp)); var defOpts = _.clone(DEFAULT_OPTS); _.extend(defOpts, opts); opts = defOpts; process.env.APPIUM_NOTIF_BUILD_NAME = opts.buildName; gulp.task('clean', function () { if (opts.transpile) { return gulp.src(opts.transpileOut, {read: false}) .pipe(vinylPaths(del)); } }); if (opts.test) { var testDeps = []; var testDir = 'test'; if (opts.transpile) { testDeps.push('transpile'); testDir = opts.transpileOut + '/test'; } var testFiles = opts.testFiles ? opts.testFiles : testDir + '/**/*-specs.js'; gulp.task('test', testDeps, function () { var mochaOpts = { reporter: opts.testReporter, timeout: opts.testTimeout }; // set env so our code knows when it's being run in a test env process.env._TESTING = true; var testProc = gulp .src(testFiles, {read: false}) .pipe(mocha(mochaOpts)) .on('error', spawnWatcher.handleError); process.env._TESTING = false; return testProc; }); } if (opts.transpile) { gulp.task('transpile', function () { var transpiler = new Transpiler(opts.babelOpts); return gulp.src(opts.files, {base: './'}) .pipe(transpiler.stream()) .on('error', spawnWatcher.handleError) .pipe(gulp.dest(opts.transpileOut)); }); gulp.task('prepublish', function () { return runSequence('clean', 'transpile'); }); } var lintTasks = []; if (opts.jscs) { gulp.task('jscs', function () { return gulp .src(opts.files) .pipe(jscs()) .on('error', spawnWatcher.handleError); }); lintTasks.push('jscs'); } if (opts.jshint) { gulp.task('jshint', function () { return gulp .src(opts.files) .pipe(jshint()) .pipe(jshint.reporter('jshint-stylish')) .pipe(jshint.reporter('fail')) .on('error', spawnWatcher.handleError); }); lintTasks.push('jshint'); } if (opts.jscs || opts.jshint) { opts.lint = true; gulp.task('lint', lintTasks); } var defaultSequence = []; if (opts.transpile) defaultSequence.push('clean'); if (opts.lint) defaultSequence.push('lint'); if (opts.transpile) defaultSequence.push('transpile'); if (opts.test) defaultSequence.push('test'); if (opts.watch) { spawnWatcher.clear(false); spawnWatcher.configure('watch', opts.files, function () { return runSequence.apply(null, defaultSequence); }); } gulp.task('once', function () { return runSequence.apply(null, defaultSequence); }); gulp.task('default', [opts.watch ? 'watch' : 'once']); }; module.exports = { use: function (gulp) { return function (opts) { boilerplate(gulp, opts); }; } };
    JavaScript
    0.000011
    @@ -1633,20 +1633,17 @@ STING = -true +1 ;%0A @@ -1782,44 +1782,8 @@ r);%0A - process.env._TESTING = false;%0A
    95fb0e2af62acc4b3ea4d88e1832325807467143
    Put initialization in a separate callable function.
    www/googleplayservices.js
    www/googleplayservices.js
    var argscheck = require ('cordova/argscheck') var exec = require ('cordova/exec') module.exports = function () { var exports = {} exports.getPlayerId = function (init) { var success = (typeof init.success != "undefined") ? init.success : function () {} var error = (typeof init.error != "undefined") ? init.error : function () {} cordova.exec (success, error, "GooglePlayServices", "getPlayerId", []) } return exports } ()
    JavaScript
    0
    @@ -421,16 +421,303 @@ %5D)%0A %7D%0A %0A + exports.initialize = function (init) %7B%0A var success = (typeof init.success != %22undefined%22) ? init.success : function () %7B%7D%0A var error = (typeof init.error != %22undefined%22) ? init.error : function () %7B%7D%0A cordova.exec (success, error, %22GooglePlayServices%22, %22initialize%22, %5B%5D)%0A %7D%0A %0A return @@ -728,8 +728,9 @@ rts%0A%7D () +%0A
    eab5c2896ea862ce2023e317b65d483d592d1792
    Fix to check for zero s value in sign function
    lib/browser/Key.js
    lib/browser/Key.js
    var ECKey = require('../../browser/vendor-bundle.js').ECKey; var SecureRandom = require('../SecureRandom'); var Curve = require('../Curve'); var bignum = require('bignum'); var Key = function() { this._pub = null; this._compressed = true; // default }; var bufferToArray = Key.bufferToArray = function(buffer) { var ret = []; var l = buffer.length; for(var i =0; i<l; i++) { ret.push(buffer.readUInt8(i)); } return ret; } Object.defineProperty(Key.prototype, 'public', { set: function(p){ if (!Buffer.isBuffer(p) ) { throw new Error('Arg should be a buffer'); } var type = p[0]; this._compressed = type!==0x04; this._pub = p; }, get: function(){ return this._pub; } }); Object.defineProperty(Key.prototype, 'compressed', { set: function(c) { var oldc = this._compressed; this._compressed = !!c; if (oldc == this._compressed) return; var oldp = this._pub; if (this._pub) { var eckey = new ECKey(); eckey.setPub(bufferToArray(this.public)); eckey.setCompressed(this._compressed); this._pub = new Buffer(eckey.getPub()); } if (!this._compressed) { //bug in eckey //oldp.slice(1).copy(this._pub, 1); } }, get: function() { return this._compressed; } }); Key.generateSync = function() { var privbuf; while(true) { privbuf = SecureRandom.getRandomBuffer(32); if ((bignum.fromBuffer(privbuf, {size: 32})).cmp(Curve.getN()) < 0) break; } var privhex = privbuf.toString('hex'); var eck = new ECKey(privhex); eck.setCompressed(true); var pub = eck.getPub(); ret = new Key(); ret.private = privbuf; ret._compressed = true; ret.public = new Buffer(eck.getPub()); return ret; }; Key.prototype.regenerateSync = function() { if (!this.private) { throw new Error('Key does not have a private key set'); } var eck = new ECKey(this.private.toString('hex')); eck.setCompressed(this._compressed); this._pub = new Buffer(eck.getPub()); return this; }; Key.prototype.signSync = function(hash) { var getSECCurveByName = require('../../browser/vendor-bundle.js').getSECCurveByName; var BigInteger = require('../../browser/vendor-bundle.js').BigInteger; var rng = new SecureRandom(); var ecparams = getSECCurveByName('secp256k1'); var rng = {}; rng.nextBytes = function(array) { var buf = SecureRandom.getRandomBuffer(array.length); var a = bufferToArray(SecureRandom.getRandomBuffer(array.length)); for (var i in a) { array[i] = a[i]; } }; var getBigRandom = function (limit) { return new BigInteger(limit.bitLength(), rng) .mod(limit.subtract(BigInteger.ONE)) .add(BigInteger.ONE); }; var sign = function (hash, priv) { var d = priv; var n = ecparams.getN(); var e = BigInteger.fromByteArrayUnsigned(hash); do { var k = getBigRandom(n); var G = ecparams.getG(); var Q = G.multiply(k); var r = Q.getX().toBigInteger().mod(n); } while (r.compareTo(BigInteger.ZERO) <= 0); var s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n); return serializeSig(r, s); }; var serializeSig = function (r, s) { var rBa = r.toByteArraySigned(); var sBa = s.toByteArraySigned(); var sequence = []; sequence.push(0x02); // INTEGER sequence.push(rBa.length); sequence = sequence.concat(rBa); sequence.push(0x02); // INTEGER sequence.push(sBa.length); sequence = sequence.concat(sBa); sequence.unshift(sequence.length); sequence.unshift(0x30); // SEQUENCE return sequence; }; if (!this.private) { throw new Error('Key does not have a private key set'); } if (!Buffer.isBuffer(hash) || hash.length !== 32) { throw new Error('Arg should be a 32 bytes hash buffer'); } var privhex = this.private.toString('hex'); var privnum = new BigInteger(privhex, 16); var signature = sign(bufferToArray(hash), privnum); return new Buffer(signature); }; Key.prototype.verifySignature = function(hash, sig, callback) { try { var result = this.verifySignatureSync(hash, sig); callback(null, result); } catch (e) { callback(e); } }; Key.prototype.verifySignatureSync = function(hash, sig) { var self = this; if (!Buffer.isBuffer(hash) || hash.length !== 32) { throw new Error('Arg 1 should be a 32 bytes hash buffer'); } if (!Buffer.isBuffer(sig)) { throw new Error('Arg 2 should be a buffer'); } if (!self.public) { throw new Error('Key does not have a public key set'); } var eck = new ECKey(); eck.setPub(bufferToArray(self.public)); eck.setCompressed(self._compressed); var sigA = bufferToArray(sig); var ret = eck.verify(bufferToArray(hash),sigA); return ret; }; module.exports = Key;
    JavaScript
    0
    @@ -3015,56 +3015,8 @@ ;%0A - %7D while (r.compareTo(BigInteger.ZERO) %3C= 0);%0A%0A @@ -3077,16 +3077,102 @@ .mod(n); +%0A %7D while (r.compareTo(BigInteger.ZERO) %3C= 0 %7C%7C s.compareTo(BigInteger.ZERO) %3C= 0); %0A%0A re
    e291726e5fe2c2cfe858c3ace02c7c1fb14eefa9
    Update build-state.js
    lib/build-state.js
    lib/build-state.js
    /** @babel */ import path from 'path' import { isTexFile, isKnitrFile } from './werkzeug' function toArray (value) { return (typeof value === 'string') ? value.split(',').map(item => item.trim()) : Array.from(value) } function toBoolean (value) { return (typeof value === 'string') ? !!value.match(/^(true|yes)$/i) : !!value } class JobState { constructor (parent, jobName) { this.parent = parent this.jobName = jobName } getOutputFilePath () { return this.outputFilePath } setOutputFilePath (value) { this.outputFilePath = value } getFileDatabase () { return this.fileDatabase } setFileDatabase (value) { this.fileDatabase = value } getLogMessages () { return this.logMessages } setLogMessages (value) { this.logMessages = value } getJobName () { return this.jobName } getFilePath () { return this.parent.getFilePath() } getProjectPath () { return this.parent.getProjectPath() } getTexFilePath () { return this.parent.getTexFilePath() } setTexFilePath (value) { this.parent.setTexFilePath(value) } getKnitrFilePath () { return this.parent.getKnitrFilePath() } setKnitrFilePath (value) { this.parent.setKnitrFilePath(value) } getCleanPatterns () { return this.parent.getCleanPatterns() } getEnableSynctex () { return this.parent.getEnableSynctex() } getEnableShellEscape () { return this.parent.getEnableShellEscape() } getEnableExtendedBuildMode () { return this.parent.getEnableExtendedBuildMode() } getEngine () { return this.parent.getEngine() } getMoveResultToSourceDirectory () { return this.parent.getMoveResultToSourceDirectory() } getOutputDirectory () { return this.parent.getOutputDirectory() } getOutputFormat () { return this.parent.getOutputFormat() } getProducer () { return this.parent.getProducer() } getShouldRebuild () { return this.parent.getShouldRebuild() } } export default class BuildState { constructor (filePath, jobNames = [null], shouldRebuild = false) { this.setFilePath(filePath) this.setJobNames(jobNames) this.setShouldRebuild(shouldRebuild) this.setEnableSynctex(false) this.setEnableShellEscape(false) this.setEnableExtendedBuildMode(false) this.subfiles = new Set() } getKnitrFilePath () { return this.knitrFilePath } setKnitrFilePath (value) { this.knitrFilePath = value } getTexFilePath () { return this.texFilePath } setTexFilePath (value) { this.texFilePath = value } getProjectPath () { return this.projectPath } setProjectPath (value) { this.projectPath = value } getCleanPatterns () { return this.cleanPatterns } setCleanPatterns (value) { this.cleanPatterns = toArray(value) } getEnableSynctex () { return this.enableSynctex } setEnableSynctex (value) { this.enableSynctex = toBoolean(value) } getEnableShellEscape () { return this.enableShellEscape } setEnableShellEscape (value) { this.enableShellEscape = toBoolean(value) } getEnableExtendedBuildMode () { return this.enableExtendedBuildMode } setEnableExtendedBuildMode (value) { this.enableExtendedBuildMode = toBoolean(value) } getEngine () { return this.engine } setEngine (value) { this.engine = value } getJobStates () { return this.jobStates } setJobStates (value) { this.jobStates = value } getMoveResultToSourceDirectory () { return this.moveResultToSourceDirectory } setMoveResultToSourceDirectory (value) { this.moveResultToSourceDirectory = toBoolean(value) } getOutputFormat () { return this.outputFormat } setOutputFormat (value) { this.outputFormat = value } getOutputDirectory () { return this.outputDirectory } setOutputDirectory (value) { this.outputDirectory = value } getProducer () { return this.producer } setProducer (value) { this.producer = value } getSubfiles () { return Array.from(this.subfiles.values()) } addSubfile (value) { this.subfiles.add(value) } hasSubfile (value) { return this.subfiles.has(value) } getShouldRebuild () { return this.shouldRebuild } setShouldRebuild (value) { this.shouldRebuild = toBoolean(value) } getFilePath () { return this.filePath } setFilePath (value) { this.filePath = value this.texFilePath = isTexFile(value) ? value : undefined this.knitrFilePath = isKnitrFile(value) ? value : undefined this.projectPath = path.dirname(value) } getJobNames () { return this.jobStates.map(jobState => jobState.getJobName()) } setJobNames (value) { this.jobStates = toArray(value).map(jobName => new JobState(this, jobName)) } }
    JavaScript
    0.000001
    @@ -1565,24 +1565,109 @@ Mode()%0A %7D%0A%0A + getOpenResultAfterBuild () %7B%0A return this.parent.getOpenResultAfterBuild()%0A %7D%0A%0A getEngine @@ -1663,32 +1663,32 @@ getEngine () %7B%0A - return this. @@ -2399,32 +2399,72 @@ uildMode(false)%0A + this.setOpenResultAfterBuild(false)%0A this.subfile @@ -3367,32 +3367,32 @@ dMode (value) %7B%0A - this.enableE @@ -3428,24 +3428,187 @@ value)%0A %7D%0A%0A + getOpenResultAfterBuild () %7B%0A return this.openResultAfterBuild%0A %7D%0A%0A setOpenResultAfterBuild (value) %7B%0A this.openResultAfterBuild = toBoolean(value)%0A %7D%0A%0A getEngine
    d39a9a0f189f3a2ce13e230ecd76ee4d9fd6e575
    bring back select-all-on-click
    src/components/views/elements/EditableText.js
    src/components/views/elements/EditableText.js
    /* Copyright 2015, 2016 OpenMarket 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. */ 'use strict'; var React = require('react'); const KEY_TAB = 9; const KEY_SHIFT = 16; const KEY_WINDOWS = 91; module.exports = React.createClass({ displayName: 'EditableText', propTypes: { onValueChanged: React.PropTypes.func, initialValue: React.PropTypes.string, label: React.PropTypes.string, placeholder: React.PropTypes.string, className: React.PropTypes.string, labelClassName: React.PropTypes.string, placeholderClassName: React.PropTypes.string, blurToCancel: React.PropTypes.bool, }, Phases: { Display: "display", Edit: "edit", }, value: '', placeholder: false, getDefaultProps: function() { return { onValueChanged: function() {}, initialValue: '', label: '', placeholder: '', }; }, getInitialState: function() { return { phase: this.Phases.Display, } }, componentWillReceiveProps: function(nextProps) { this.value = nextProps.initialValue; }, componentDidMount: function() { this.value = this.props.initialValue; if (this.refs.editable_div) { this.showPlaceholder(!this.value); } }, showPlaceholder: function(show) { if (show) { this.refs.editable_div.textContent = this.props.placeholder; this.refs.editable_div.setAttribute("class", this.props.className + " " + this.props.placeholderClassName); this.placeholder = true; this.value = ''; } else { this.refs.editable_div.textContent = this.value; this.refs.editable_div.setAttribute("class", this.props.className); this.placeholder = false; } }, getValue: function() { return this.value; }, edit: function() { this.setState({ phase: this.Phases.Edit, }); }, cancelEdit: function() { this.setState({ phase: this.Phases.Display, }); this.onValueChanged(false); }, onValueChanged: function(shouldSubmit) { this.props.onValueChanged(this.value, shouldSubmit); }, onKeyDown: function(ev) { // console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); if (this.placeholder) { if (ev.keyCode !== KEY_SHIFT && !ev.metaKey && !ev.ctrlKey && !ev.altKey && ev.keyCode !== KEY_WINDOWS && ev.keyCode !== KEY_TAB) { this.showPlaceholder(false); } } if (ev.key == "Enter") { ev.stopPropagation(); ev.preventDefault(); } // console.log("keyDown: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); }, onKeyUp: function(ev) { // console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); if (!ev.target.textContent) { this.showPlaceholder(true); } else if (!this.placeholder) { this.value = ev.target.textContent; } if (ev.key == "Enter") { this.onFinish(ev); } else if (ev.key == "Escape") { this.cancelEdit(); } // console.log("keyUp: textContent=" + ev.target.textContent + ", value=" + this.value + ", placeholder=" + this.placeholder); }, onClickDiv: function(ev) { this.setState({ phase: this.Phases.Edit, }) }, onFocus: function(ev) { //ev.target.setSelectionRange(0, ev.target.textContent.length); }, onFinish: function(ev) { var self = this; this.setState({ phase: this.Phases.Display, }, function() { self.onValueChanged(ev.key === "Enter"); }); }, onBlur: function(ev) { if (this.props.blurToCancel) this.cancelEdit(); else this.onFinish(ev) }, render: function() { var editable_el; if (this.state.phase == this.Phases.Display && (this.props.label || this.props.labelClassName) && !this.value) { // show the label editable_el = <div className={this.props.className + " " + this.props.labelClassName} onClick={this.onClickDiv}>{this.props.label}</div>; } else { // show the content editable div, but manually manage its contents as react and contentEditable don't play nice together editable_el = <div ref="editable_div" contentEditable="true" className={this.props.className} onKeyDown={this.onKeyDown} onKeyUp={this.onKeyUp} onFocus={this.onFocus} onBlur={this.onBlur}></div>; } return editable_el; } });
    JavaScript
    0.000001
    @@ -4347,16 +4347,289 @@ length); +%0A%0A var node = ev.target.childNodes%5B0%5D;%0A var range = document.createRange();%0A range.setStart(node, 0);%0A range.setEnd(node, node.length);%0A %0A var sel = window.getSelection();%0A sel.removeAllRanges();%0A sel.addRange(range); %0A %7D,%0A
    384f50609d92ed9e525f261ea6bf4a64d97b401c
    Allow searching by partial prefix (/w or /wo '+')
    src/components/views/login/CountryDropdown.js
    src/components/views/login/CountryDropdown.js
    /* Copyright 2017 Vector Creations 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 sdk from '../../../index'; import { COUNTRIES } from '../../../phonenumber'; const COUNTRIES_BY_ISO2 = new Object(null); for (const c of COUNTRIES) { COUNTRIES_BY_ISO2[c.iso2] = c; } function countryMatchesSearchQuery(query, country) { if (country.name.toUpperCase().indexOf(query.toUpperCase()) == 0) return true; if (country.iso2 == query.toUpperCase()) return true; if (country.prefix == query) return true; return false; } export default class CountryDropdown extends React.Component { constructor(props) { super(props); this._onSearchChange = this._onSearchChange.bind(this); this._onOptionChange = this._onOptionChange.bind(this); this._getShortOption = this._getShortOption.bind(this); this.state = { searchQuery: '', }; } componentWillMount() { if (!this.props.value) { // If no value is given, we start with the first // country selected, but our parent component // doesn't know this, therefore we do this. this.props.onOptionChange(COUNTRIES[0]); } } _onSearchChange(search) { this.setState({ searchQuery: search, }); } _onOptionChange(iso2) { this.props.onOptionChange(COUNTRIES_BY_ISO2[iso2]); } _flagImgForIso2(iso2) { return <img src={`flags/${iso2}.png`}/>; } _getShortOption(iso2) { if (!this.props.isSmall) { return undefined; } let countryPrefix; if (this.props.showPrefix) { countryPrefix = '+' + COUNTRIES_BY_ISO2[iso2].prefix; } return <span> { this._flagImgForIso2(iso2) } { countryPrefix } </span>; } render() { const Dropdown = sdk.getComponent('elements.Dropdown'); let displayedCountries; if (this.state.searchQuery) { displayedCountries = COUNTRIES.filter( countryMatchesSearchQuery.bind(this, this.state.searchQuery), ); if ( this.state.searchQuery.length == 2 && COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()] ) { // exact ISO2 country name match: make the first result the matches ISO2 const matched = COUNTRIES_BY_ISO2[this.state.searchQuery.toUpperCase()]; displayedCountries = displayedCountries.filter((c) => { return c.iso2 != matched.iso2; }); displayedCountries.unshift(matched); } } else { displayedCountries = COUNTRIES; } const options = displayedCountries.map((country) => { return <div key={country.iso2}> {this._flagImgForIso2(country.iso2)} {country.name} </div>; }); // default value here too, otherwise we need to handle null / undefined // values between mounting and the initial value propgating const value = this.props.value || COUNTRIES[0].iso2; return <Dropdown className={this.props.className + " left_aligned"} onOptionChange={this._onOptionChange} onSearchChange={this._onSearchChange} menuWidth={298} getShortOption={this._getShortOption} value={value} searchEnabled={true} > {options} </Dropdown>; } } CountryDropdown.propTypes = { className: React.PropTypes.string, isSmall: React.PropTypes.bool, // if isSmall, show +44 in the selected value showPrefix: React.PropTypes.bool, onOptionChange: React.PropTypes.func.isRequired, value: React.PropTypes.string, };
    JavaScript
    0.000001
    @@ -835,24 +835,150 @@ country) %7B%0A + // Remove '+' if present (when searching for a prefix)%0A if (query%5B0%5D === '+') %7B%0A query = query.slice(1);%0A %7D%0A%0A if (coun @@ -1128,25 +1128,38 @@ y.prefix - == query +.indexOf(query) !== -1 ) return
    f69efdf8441ba4ec5e8abf9af4fa04b29f15130d
    Add args as a parameter for cmdRunner.runHadoopJar
    cosmos-tidoop-api/src/cmd_runner.js
    cosmos-tidoop-api/src/cmd_runner.js
    /** * Copyright 2016 Telefonica Investigación y Desarrollo, S.A.U * * This file is part of fiware-cosmos (FI-WARE project). * * fiware-cosmos is free software: you can redistribute it and/or modify it under the terms of the GNU Affero * General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * fiware-cosmos is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the * implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License * for more details. * * You should have received a copy of the GNU Affero General Public License along with fiware-cosmos. If not, see * http://www.gnu.org/licenses/. * * For those usages not covered by the GNU Affero General Public License please contact with * francisco dot romerobueno at telefonica dot com */ /** * Command runner. * * Author: frb */ // Module dependencies var spawn = require('child_process').spawn; function runHadoopJar(userId, jarName, jarInHDFS, className, libJarsName, libJarsInHDFS, input, output, callback) { // Copy the jar from the HDFS user space var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', jarInHDFS, '/home/' + userId + '/' + jarName]; var command = spawn('sudo', params); command.on('close', function(code) { // Copy the libjar from the HDFS user space var params = ['-u', userId, 'hadoop', 'fs', '-copyToLocal', libJarsInHDFS, '/home/' + userId + '/' + libJarsName]; var command = spawn('sudo', params); command.on('close', function(code) { // Run the MR job var params = ['-u', userId, 'hadoop', 'jar', '/home/' + userId + '/' + jarName, className, '-libjars', '/home/' + userId + '/' + libJarsName, input, output]; var command = spawn('sudo', params); var jobId = null; // This function catches the stderr as it is being produced (console logs are printed in the stderr). At the // moment of receiving the line containing the job ID, get it and return with no error (no error means the // job could be run, independently of the final result of the job) command.stderr.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Submitting tokens for job: '; var indexOfJobId = dataStr.indexOf(magicString); if(indexOfJobId >= 0) { jobId = dataStr.substring(indexOfJobId + magicString.length, indexOfJobId + magicString.length + 22); var params = ['-u', userId, 'rm', '/home/' + userId + '/' + jarName]; var command = spawn('sudo', params); var params = ['-u', userId, 'rm', '/home/' + userId + '/' + libJarsName]; var command = spawn('sudo', params); return callback(null, jobId); } // if }); // This function catches the moment the command finishes. Return the error code if the job ID was never got command.on('close', function (code) { if (jobId === null) { return callback(code, null); } // if }); }); }); } // runHadoopJar function runHadoopJobList(userId, callback) { var params = ['job', '-list', 'all']; var command = spawn('hadoop', params); var jobInfos = null; command.stdout.on('data', function (data) { var dataStr = data.toString(); jobInfos = '['; var firstJobInfo = true; var lines = dataStr.split("\n"); for (i in lines) { if(i > 1) { var fields = lines[i].split("\t"); if (fields.length > 3 && fields[3].replace(/ /g,'') === userId) { var jobInfo = '{'; for (j in fields) { if (fields[j].length > 0) { var value = fields[j].replace(/ /g,''); if (j == 0) { jobInfo += '"job_id":"' + value + '"'; } else if (j == 1) { jobInfo += ',"state":"' + value + '"'; } else if (j == 2) { jobInfo += ',"start_time":"' + value + '"'; } else if (j == 3) { jobInfo += ',"user_id":"' + value + '"'; } // if else } // if } // for jobInfo += '}'; if (firstJobInfo) { jobInfos += jobInfo; firstJobInfo = false; } else { jobInfos += ',' + jobInfo; } // if else } // if } // if } // for jobInfos += ']'; return callback(null, jobInfos); }); // This function catches the moment the command finishes. Return the error code if the jobs information was never // got command.on('close', function (code) { if (jobInfos === null) { return callback(code, null); } // if }); } // runHadoopJobList function runHadoopJobKill(jobId, callback) { var params = ['job', '-kill', jobId]; var command = spawn('hadoop', params); command.stderr.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Application with id'; if(dataStr.indexOf(magicString) >= 0) { return callback('Application does not exist'); } // if }); command.stdout.on('data', function (data) { var dataStr = data.toString(); var magicString = 'Killed job'; if (dataStr.indexOf(magicString) >= 0) { return callback(null); } // if }); } // runHadoopJobKill module.exports = { runHadoopJar: runHadoopJar, runHadoopJobList: runHadoopJobList, runHadoopJobKill: runHadoopJobKill } // module.exports
    JavaScript
    0
    @@ -1134,16 +1134,22 @@ sInHDFS, + args, input, @@ -1805,16 +1805,22 @@ assName, + args, '-libja
    8a0df6aefa71fb2e34bc891b59791d8c8d5c963c
    Fix build target selection
    lib/admin.js
    lib/admin.js
    var async = require('async'), campfire = require('./campfire'), config = require('./config'), express = require('express'), log = require('./log'); module.exports = function(app, repo) { var branches = [], currentBranch; campfire.init(repo); app.get('/ms_admin', function(req, res, next) { async.parallel([ function(callback) { repo.remoteBranches(function(err, data) { branches = data; callback(err); }); }, function(callback) { repo.currentBranch(function(err, data) { currentBranch = data; callback(err); }); } ], function(err) { res.render('index', { gitPath: config.appDir, mocksEnabled: !!config.mocksEnabled, buildTarget: config.buildTarget || {}, buildTargets: config.projectConfig['build-targets'] || [], servers: config.projectConfig.servers || [], proxyServer: config.proxyServer, branches: branches || [], currentBranch: currentBranch, log: log.logs, error: log.errors }); }); }); app.all('/ms_admin/proxy-server', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the user input var proxy = req.param('proxy'); if ((config.projectConfig.servers || []).indexOf(proxy) < 0) { res.redirect('/ms_admin'); return; } config.proxyServer = proxy; campfire.speak('proxy changed to ' + config.proxyServer); res.redirect('/ms_admin'); }); app.all('/ms_admin/mocks', express.bodyParser(), function(req, res, next) { log.reset(); config.mocksEnabled = req.param('enable-mocks'); if (config.mocksEnabled === 'false') { config.mocksEnabled = false; } config.mocksEnabled = !!config.mocksEnabled; campfire.speak('mocksEnabled changed to ' + config.mocksEnabled); res.redirect('/ms_admin'); }); app.all('/ms_admin/build-target', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the input var target = req.param('target'); if ((config.projectConfig['build-targets'] || []).indexOf(target) < 0) { res.redirect('/ms_admin'); return; } config.buildTarget = target; repo.build(function() { campfire.speak('build target changed to ' + config.buildTarget.name); res.redirect('/ms_admin'); }); }); app.all('/ms_admin/branch', express.bodyParser(), function(req, res, next) { log.reset(); // Filter the input var branch = req.param('branch'), sameBranch = currentBranch === branch; console.log('branch', branch, branches, branches.indexOf(branch)); if (branches.indexOf(branch) < 0) { res.redirect('/ms_admin'); return; } console.log('Switching to branch', branch); async.series([ function(callback) { // Skip checkout if we are already on this branch if (sameBranch) { callback(); } else { repo.checkout(branch, callback); } }, function(callback) { repo.pull(!sameBranch, function(err) { callback(err); }); }, function(callback) { repo.build(callback); } ], function(err) { err || campfire.speak('branch changed to ' + branch); res.redirect('/ms_admin'); }); }); app.all('/ms_admin/pull', express.bodyParser(), function(req, res, next) { log.reset(); module.exports.pull(repo, currentBranch, function(err) { res.redirect('/ms_admin'); }); }); }; module.exports.pull = function(repo, currentBranch, callback) { log.reset(); async.series([ function(callback) { repo.pull(callback); }, function(callback) { repo.build(callback); } ], function(err) { if (err) { log.exception(err); } err || process.env.CAMPFIRE_QUIET || campfire.speak('pulled from ' + currentBranch); callback && callback(err); }); };
    JavaScript
    0
    @@ -2066,16 +2066,25 @@ arget = +parseInt( req.para @@ -2094,16 +2094,17 @@ target') +) ;%0A if @@ -2097,32 +2097,46 @@ get'));%0A if ( +target %3C 0 %7C%7C (config.projectC @@ -2169,28 +2169,25 @@ %5B%5D). -indexOf( +length %3C= target) - %3C 0) %7B%0A
    27df63964a1fc93b2fd909c17db766ebf460d292
    Fix "no-unused-styles" suite name
    tests/lib/rules/no-unused-styles.js
    tests/lib/rules/no-unused-styles.js
    /** * @fileoverview No unused styles defined in javascript files * @author Tom Hastjarjanto */ 'use strict'; // ------------------------------------------------------------------------------ // Requirements // ------------------------------------------------------------------------------ const rule = require('../../../lib/rules/no-unused-styles'); const RuleTester = require('eslint').RuleTester; require('babel-eslint'); // ------------------------------------------------------------------------------ // Tests // ------------------------------------------------------------------------------ const ruleTester = new RuleTester(); const tests = { valid: [{ code: [ 'const styles = StyleSheet.create({', ' name: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', 'const styles = StyleSheet.create({', ' name: {}', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' name: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' name: {},', ' welcome: {}', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', 'const Welcome = React.createClass({', ' render: function() {', ' return <Text style={styles.welcome}>Welcome</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' propTypes: {', ' textStyle: Text.propTypes.style,', ' },', ' render: function() {', ' return <Text style={[styles.text, textStyle]}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const styles2 = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' propTypes: {', ' textStyle: Text.propTypes.style,', ' },', ' render: function() {', ' return (', ' <Text style={[styles.text, styles2.text, textStyle]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '});', 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true, condition2: true }; ', ' },', ' render: function() {', ' return (', ' <Text', ' style={[', ' this.state.condition &&', ' this.state.condition2 &&', ' styles.text]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {},', ' text2: {},', '});', 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true }; ', ' },', ' render: function() {', ' return (', ' <Text style={[this.state.condition ? styles.text : styles.text2]}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' style1: {', ' color: \'red\',', ' },', ' style2: {', ' color: \'blue\',', ' }', '});', 'export default class MyComponent extends Component {', ' static propTypes = {', ' isDanger: PropTypes.bool', ' };', ' render() {', ' return <View style={this.props.isDanger ? styles.style1 : styles.style2} />;', ' }', '}', ].join('\n'), }, { code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', ].join('\n'), }, { code: [ 'const Hello = React.createClass({', ' getInitialState: function() {', ' return { condition: true }; ', ' },', ' render: function() {', ' const myStyle = this.state.condition ? styles.text : styles.text2;', ' return (', ' <Text style={myStyle}>', ' Hello {this.props.name}', ' </Text>', ' );', ' }', '});', 'const styles = StyleSheet.create({', ' text: {},', ' text2: {},', '});', ].join('\n'), }, { code: [ 'const additionalStyles = {};', 'const styles = StyleSheet.create({', ' name: {},', ' ...additionalStyles', '});', 'const Hello = React.createClass({', ' render: function() {', ' return <Text textStyle={styles.name}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), }], invalid: [{ code: [ 'const styles = StyleSheet.create({', ' text: {}', '})', 'const Hello = React.createClass({', ' render: function() {', ' return <Text style={styles.b}>Hello {this.props.name}</Text>;', ' }', '});', ].join('\n'), errors: [{ message: 'Unused style detected: styles.text', }], }], }; const config = { parser: 'babel-eslint', parserOptions: { ecmaFeatures: { classes: true, jsx: true, }, }, }; tests.valid.forEach(t => Object.assign(t, config)); tests.invalid.forEach(t => Object.assign(t, config)); ruleTester.run('split-platform-components', rule, tests);
    JavaScript
    0
    @@ -6314,32 +6314,23 @@ un(' -split-platform-component +no-unused-style s',
    ded1e02da7a42aaa5ea0a4414d9ebac7d986995f
    move buildHelpers require down a slot
    packages/build-runtime.js
    packages/build-runtime.js
    "use strict"; var buildHelpers = require("../lib/babel/build-helpers"); var transform = require("../lib/babel/transformation"); var util = require("../lib/babel/util"); var fs = require("fs"); var t = require("../lib/babel/types"); var _ = require("lodash"); var relative = function (filename) { return __dirname + "/babel-runtime/" + filename; }; var writeFile = function (filename, content) { filename = relative(filename); console.log(filename); fs.writeFileSync(filename, content); }; var readFile = function (filename, defaultify) { var file = fs.readFileSync(require.resolve(filename), "utf8"); if (defaultify) { file += '\nmodule.exports = { "default": module.exports, __esModule: true };\n'; } return file; }; var updatePackage = function () { var pkgLoc = relative("package.json"); var pkg = require(pkgLoc); var mainPkg = require("../package.json"); pkg.version = mainPkg.version; writeFile("package.json", JSON.stringify(pkg, null, 2)); }; var selfContainify = function (code) { return transform(code, { optional: ["selfContained"] }).code; }; var buildHelpers2 = function () { var body = util.template("self-contained-helpers-head"); var tree = t.program(body); buildHelpers(body, t.identifier("helpers")); return transform.fromAst(tree, null, { optional: ["selfContained"] }).code; }; writeFile("helpers.js", buildHelpers2()); writeFile("core-js.js", readFile("core-js/library", true)); writeFile("regenerator/index.js", readFile("regenerator-babel/runtime-module", true)); writeFile("regenerator/runtime.js", selfContainify(readFile("regenerator-babel/runtime"))); updatePackage();
    JavaScript
    0
    @@ -12,28 +12,28 @@ %22;%0A%0Avar -buildHelpers +transform = requi @@ -53,41 +53,42 @@ bel/ -build-helpers%22);%0Avar transform +transformation%22);%0Avar buildHelpers = r @@ -104,38 +104,37 @@ ./lib/babel/ -transformation +build-helpers %22);%0Avar util
    62a0f429264c4d63006e455690d02496674d3a2f
    Fix chart symbol
    src/botPage/view/blockly/blocks/trade/index.js
    src/botPage/view/blockly/blocks/trade/index.js
    import { observer as globalObserver } from 'binary-common-utils/lib/observer'; import { translate } from '../../../../../common/i18n'; import config from '../../../../common/const'; import { setBlockTextColor, findTopParentBlock, deleteBlockIfExists } from '../../utils'; import { defineContract } from '../images'; import { updatePurchaseChoices } from '../shared'; import { marketDefPlaceHolders } from './tools'; import backwardCompatibility from './backwardCompatibility'; import tradeOptions from './tradeOptions'; const bcMoveAboveInitializationsDown = block => { Blockly.Events.recordUndo = false; Blockly.Events.setGroup('BackwardCompatibility'); const parent = block.getParent(); if (parent) { const initializations = block.getInput('INITIALIZATION').connection; const ancestor = findTopParentBlock(parent); parent.nextConnection.disconnect(); initializations.connect((ancestor || parent).previousConnection); } block.setPreviousStatement(false); Blockly.Events.setGroup(false); Blockly.Events.recordUndo = true; }; const decorateTrade = ev => { const trade = Blockly.mainWorkspace.getBlockById(ev.blockId); if (!trade || trade.type !== 'trade') { return; } if ([Blockly.Events.CHANGE, Blockly.Events.MOVE, Blockly.Events.CREATE].includes(ev.type)) { const symbol = trade.getFieldValue('SYMBOL_LIST'); const submarket = trade.getInput('SUBMARKET').connection.targetConnection; // eslint-disable-next-line no-underscore-dangle const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions'; if (symbol && !needsMutation) { globalObserver.emit('bot.init', symbol); } const type = trade.getFieldValue('TRADETYPE_LIST'); if (type) { const oppositesName = type.toUpperCase(); const contractType = trade.getFieldValue('TYPE_LIST'); if (oppositesName && contractType) { updatePurchaseChoices(contractType, oppositesName); } } } }; const replaceInitializationBlocks = (trade, ev) => { if (ev.type === Blockly.Events.CREATE) { ev.ids.forEach(blockId => { const block = Blockly.mainWorkspace.getBlockById(blockId); if (block && block.type === 'trade' && !deleteBlockIfExists(block)) { bcMoveAboveInitializationsDown(block); } }); } }; const resetTradeFields = (trade, ev) => { if (ev.blockId === trade.id) { if (ev.element === 'field') { if (ev.name === 'MARKET_LIST') { trade.setFieldValue('', 'SUBMARKET_LIST'); } if (ev.name === 'SUBMARKET_LIST') { trade.setFieldValue('', 'SYMBOL_LIST'); } if (ev.name === 'SYMBOL_LIST') { trade.setFieldValue('', 'TRADETYPECAT_LIST'); } if (ev.name === 'TRADETYPECAT_LIST') { trade.setFieldValue('', 'TRADETYPE_LIST'); } if (ev.name === 'TRADETYPE_LIST') { if (ev.newValue) { trade.setFieldValue('both', 'TYPE_LIST'); } else { trade.setFieldValue('', 'TYPE_LIST'); } } } } }; Blockly.Blocks.trade = { init: function init() { this.appendDummyInput() .appendField(new Blockly.FieldImage(defineContract, 15, 15, 'T')) .appendField(translate('(1) Define your trade contract')); marketDefPlaceHolders(this); this.appendStatementInput('INITIALIZATION').setCheck(null).appendField(`${translate('Run Once at Start')}:`); this.appendStatementInput('SUBMARKET').setCheck(null).appendField(`${translate('Define Trade Options')}:`); this.setPreviousStatement(true, null); this.setColour('#2a3052'); this.setTooltip( translate('Define your trade contract and start the trade, add initializations here. (Runs on start)') ); this.setHelpUrl('https://github.com/binary-com/binary-bot/wiki'); }, onchange: function onchange(ev) { setBlockTextColor(this); if (ev.group !== 'BackwardCompatibility') { replaceInitializationBlocks(this, ev); resetTradeFields(this, ev); } decorateTrade(ev); }, }; Blockly.JavaScript.trade = block => { const account = $('.account-id').first().attr('value'); if (!account) { throw Error('Please login'); } const initialization = Blockly.JavaScript.statementToCode(block, 'INITIALIZATION'); const tradeOptionsStatement = Blockly.JavaScript.statementToCode(block, 'SUBMARKET'); const candleIntervalValue = block.getFieldValue('CANDLEINTERVAL_LIST'); const contractTypeSelector = block.getFieldValue('TYPE_LIST'); const oppositesName = block.getFieldValue('TRADETYPE_LIST').toUpperCase(); const contractTypeList = contractTypeSelector === 'both' ? config.opposites[oppositesName].map(k => Object.keys(k)[0]) : [contractTypeSelector]; const timeMachineEnabled = block.getFieldValue('TIME_MACHINE_ENABLED') === 'TRUE'; const shouldRestartOnError = block.getFieldValue('RESTARTONERROR') === 'TRUE'; const code = ` init = function init() { Bot.init('${account}', { symbol: '${block.getFieldValue('SYMBOL_LIST')}', contractTypes: ${JSON.stringify(contractTypeList)}, candleInterval: '${candleIntervalValue}', shouldRestartOnError: ${shouldRestartOnError}, timeMachineEnabled: ${timeMachineEnabled}, }); ${initialization.trim()} }; start = function start() { ${tradeOptionsStatement.trim()} }; `; return code; }; export default () => { backwardCompatibility(); tradeOptions(); };
    JavaScript
    0.000002
    @@ -1405,239 +1405,8 @@ T'); -%0A const submarket = trade.getInput('SUBMARKET').connection.targetConnection;%0A // eslint-disable-next-line no-underscore-dangle%0A const needsMutation = submarket && submarket.sourceBlock_.type !== 'tradeOptions'; %0A%0A @@ -1425,26 +1425,8 @@ mbol - && !needsMutation ) %7B%0A
    4982d4029e48a8d89f70ba01a9fc69b959f212fc
    Fix #8
    WebContent/static/games/Tanks/displayScript.js
    WebContent/static/games/Tanks/displayScript.js
    /** * The display script for Tanks. This code displays sprites in a grid based canvas. */ var images = {}; var idList = null; //Called on page load function onLoad(gameID) { displayMessage("Loading Sprites"); let sprites = { bullet: "../static/games/Tanks/bullet.png", }; loadSprites(sprites, gameID); } function loadSprites(sprites, gameID) { let numImages = 0; // get num of sources for(name in sprites) { numImages++; } for(name in sprites) { images[name] = new Image(); images[name].onload = function() { if(--numImages <= 0) { connectWebSocket(gameID); } }; images[name].src = sprites[name]; } } /* * 4: Player ID list * 0: Bulk update * 1: Delta update * * 2: Update game table * 3: Update player table */ function onMessage(message) { let dataView = new DataView(message.data); let header = dataView.getUint8(0); switch(header) { case 1: //delta handleDeltaData(dataView); break; case 0: //bulk handleBulkData(dataView); break; case 2: updateGameTable(); break; case 4: updateIDMap(dataView); break; case 3: updatePlayerList(); default: canvasError(); } } function updateIDMap(dataView) { idList = []; let length = dataView.getUint8(1); for(index = 0; index < length; index++) { let id = dataView.getUint32(index * 4 + 2).toString(); idList.push(id); if(id == "0") { images[id] = null; } else { images[id] = new Image(); images[id].src = "/playericon/" + id; } } } function handleBulkData(dataView) { canvas.clearRect(0, 0, pixelSize, pixelSize); width = dataView.getUint8(1); height = dataView.getUint8(2); for(y = 0; y < height; y++) { for(x = 0; x < width; x++) { let c = dataView.getUint16(3 + (x + y * width) * 2); paintItem(x, y, c); } } } function paintItem(x, y, c) { switch(c) { case 0: //space clear(x, y); break; case 1: //wall wall(x, y); break; case 2: //bullet shot(x, y); break; default: tank(x, y, c - 3); } } function handleDeltaData(dataView) { let offset = 1; while(offset <= dataView.byteLength - 4) { let c = dataView.getUint16(offset); let x = dataView.getUint8(offset + 2); let y = dataView.getUint8(offset + 3); paintItem(x, y, c); offset = offset + 4; } } function tank(x, y, index) { if(idList == null) return; if(idList.length <= index) { return; //we haven't been sent that ID yet } let image = images[idList[index]]; if(image != null && image.complete) { canvas.drawImage(image, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } } function wall(x, y) { canvas.fillStyle = 'black'; canvas.fillRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } function clear(x, y) { canvas.clearRect(x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); } function shot(x, y) { clear(x, y); canvas.drawImage(images.bullet, x * pixelSize / width, y * pixelSize / height, pixelSize / width, pixelSize / height); }
    JavaScript
    0.000001
    @@ -2290,16 +2290,32 @@ ndex) %7B%0A +%09clear(x, y);%0A%09%0A %09if(idLi
    1f4875527d1e2f9a0f3812eca958ece9377595d4
    Change language on counts block from Events to Performances.
    imports/api/counts/server/publications.js
    imports/api/counts/server/publications.js
    /* eslint-disable prefer-arrow-callback */ import { Meteor } from 'meteor/meteor'; import { TAPi18n } from 'meteor/tap:i18n'; import { _ } from 'meteor/underscore'; // API import { Counts } from '../../counts/counts.js'; import { Profiles } from '../../profiles/profiles.js'; import { Shows } from '../../shows/shows.js'; import { Events } from '../../events/events.js'; Meteor.publish('counts.collections', function countsCollections() { const self = this; let countTheatremakers = 0; let countOrganizations = 0; let countShows = 0; let countEvents = 0; let countLocations = 0; let initializing = true; // observeChanges only returns after the initial `added` callbacks // have run. Until then, we don't want to send a lot of // `self.changed()` messages - hence tracking the // `initializing` state. const handleTheatremakers = Profiles.find({"profileType": "Individual"}).observeChanges({ added: function() { countTheatremakers++; if (!initializing) { self.changed('Counts', 'Theatremakers', { count: countTheatremakers }); } }, removed: function() { countTheatremakers--; self.changed('Counts', 'Theatremakers', { count: countTheatremakers }); }, // don't care about changed }); const handleOrganizations = Profiles.find({"profileType": "Organization"}).observeChanges({ added: function() { countOrganizations++; if (!initializing) { self.changed('Counts', 'Organizations', { count: countOrganizations }); } }, removed: function() { countOrganizations--; self.changed('Counts', 'Organizations', { count: countOrganizations }); }, // don't care about changed }); const handleShows = Shows.find({}).observeChanges({ added: function() { countShows++; if (!initializing) { self.changed('Counts', 'Shows', { count: countShows }); } }, removed: function() { countShows--; self.changed('Counts', 'Shows', { count: countShows }); }, // don't care about changed }); const handleEvents = Events.find({}).observeChanges({ added: function() { countEvents++; if (!initializing) { self.changed('Counts', 'Events', { count: countEvents }); } }, removed: function() { countEvents--; self.changed('Counts', 'Events', { count: countEvents }); }, // don't care about changed }); const handleEventLocations = Events.find({"lat": { $gt: ""}}).observeChanges({ added: function() { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: function() { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); const handleProfileLocations = Profiles.find({"lat": { $gt: ""}}).observeChanges({ added: function() { countLocations++; if (!initializing) { self.changed('Counts', 'Locations', { count: countLocations }); } }, removed: function() { countLocations--; self.changed('Counts', 'Locations', { count: countLocations }); }, // don't care about changed }); // Instead, we'll send one `self.added()` message right after // observeChanges has returned, and mark the subscription as // ready. initializing = false; self.added('Counts', 'Theatremakers', { count: countTheatremakers }); self.added('Counts', 'Organizations', { count: countOrganizations }); self.added('Counts', 'Shows', { count: countShows }); self.added('Counts', 'Events', { count: countEvents }); self.added('Counts', 'Locations', { count: countLocations }); self.ready(); // Stop observing the cursor when client unsubs. // Stopping a subscription automatically takes // care of sending the client any removed messages. self.onStop(() => { handleTheatremakers.stop(); handleOrganizations.stop(); handleShows.stop(); handleEvents.stop(); handleEventLocations.stop(); handleProfileLocations.stop(); }); });
    JavaScript
    0
    @@ -2216,37 +2216,43 @@ nged('Counts', ' -Event +Performance s', %7B count: cou @@ -2348,37 +2348,43 @@ nged('Counts', ' -Event +Performance s', %7B count: cou @@ -3648,21 +3648,27 @@ unts', ' -Event +Performance s', %7B co
    cb9bc30842fdededbb25f7e627e8f3f84eb151a4
    Fix failing test
    tests/pages/jobs/JobsOverview-cy.js
    tests/pages/jobs/JobsOverview-cy.js
    describe('Jobs Overview', function () { context('Jobs page loads correctly', function () { beforeEach(function () { cy.configureCluster({ mesos: '1-for-each-health', nodeHealth: true }); cy.visitUrl({url: '/jobs'}); }); it('has the right active navigation entry', function () { cy.get('.page-header-navigation .tab-item.active') .should('to.have.text', 'Jobs'); }); it('displays empty jobs overview page', function () { cy.get('.page-content .panel-content h3') .should('to.have.text', 'No Jobs Found'); }); }); });
    JavaScript
    0.000209
    @@ -578,12 +578,14 @@ obs -Foun +Create d');
    8bf416778ad35f9c96c76de2db451fc3924de8f9
    Fix little typo
    plugins/weather.js
    plugins/weather.js
    /** Created on May 6, 2014 * author: MrPoxipol */ var http = require('http'); var util = require('util'); // Templates module var Mustache = require('mustache'); var debug = require('../nibo/debug'); const COMMAND_NAME = 'weather'; // pattern for util.format() const API_URL_PATTERN = 'http://api.openweathermap.org/data/2.5/weather?q=%s&lang=eng'; exports.meta = { name: 'weather', commandName: COMMAND_NAME, description: 'Fetches actual weather conditions from openweathermap.org at specific place on the Earth' }; function kelvinsToCelcius(temperature) { return Math.round(temperature - 273.15); } function calcWindChill(temperature, windSpeed) { if (temperature < 10 && (windSpeed / 3.6) >= 1.8) { var windChill = (13.12 + 0.6215 * temperature - 11.37 * Math.pow(windSpeed, 0.16) + 0.3965 * temperature * Math.pow(windSpeed, 0.16)); windChill = Math.round(windChill); } return null; } function getWeatherFromJson(data) { var parsedJson; try { parsedJson = JSON.parse(data); } catch (e) { debug.debug('JSON parsing error'); return; } var weather = { city: parsedJson.name }; if (!weather.city) { return; } weather.country = parsedJson.sys.country; weather.temp = kelvinsToCelcius(parsedJson.main.temp); weather.description = parsedJson.weather[0].description; weather.windSpeed = parsedJson.wind.speed; weather.pressure = Math.round(parsedJson.main.pressure); weather.windChill = calcWindChill(weather.temp, weather.windSpeed); var pattern; if (weather.windChill !== null) pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C (felt as {{&windChill}}°C) - {{&description}}, {{&pressure}} hPa'; else pattern = '[{{&city}}, {{&country}}]: {{&temp}}°C - {{&description}}, {{&pressure}} hPa'; var output = Mustache.render(pattern, weather); return output; } function sendResponse(bot, args, message) { bot.sayToUser(args.channel, args.user.nick, message); } function fetchWeather(bot, args) { args.place = encodeURIComponent(args.place); var url = util.format(API_URL_PATTERN, args.place); http.get(url, function (response) { var responseParts = []; response.setEncoding('utf8'); response.on('data', function (chunk) { responseParts.push(chunk); }); response.on('end', function () { var data = responseParts.join(''); var message = getWeatherFromJson(data); if (message) { sendResponse(bot, args, message); } else { sendResponse(bot, args, util.format('[%s] Could not find weather information.', decodeURIComponent(args.place)) ); } }); }).on('error', function (e) { debug.error('HTTP ' + e.message); sendResponse(bot, args, '[] Weather is not avaiable at the moment.'); }); } exports.onCommand = function (bot, user, channel, command) { if (command.name !== COMMAND_NAME) return; if (command.args.length < 1) return; var args = { user: user, channel: channel, place: command.args.join(' '), }; fetchWeather(bot, args); };
    JavaScript
    0.999968
    @@ -2660,16 +2660,17 @@ not avai +l able at
    f258286c431b46f944ecaffb319bf44b749f04f4
    Fix #149 TextCell should trigger error and high light the text box if the formatter returns undefined
    src/extensions/text-cell/backgrid-text-cell.js
    src/extensions/text-cell/backgrid-text-cell.js
    /* backgrid-text-cell http://github.com/wyuenho/backgrid Copyright (c) 2013 Jimmy Yuen Ho Wong and contributors Licensed under the MIT @license. */ (function (window, $, _, Backbone, Backgrid) { /** Renders a form with a text area and a save button in a modal dialog. @class Backgrid.Extension.TextareaEditor @extends Backgrid.CellEditor */ var TextareaEditor = Backgrid.Extension.TextareaEditor = Backgrid.CellEditor.extend({ /** @property */ tagName: "div", /** @property */ className: "modal hide fade", /** @property {function(Object, ?Object=): string} template */ template: _.template('<form><div class="modal-header"><button type="button" class="close" data-dismiss="modal">&times;</button><h3><%- column.get("label") %></h3></div><div class="modal-body"><textarea cols="<%= cols %>" rows="<%= rows %>"><%- content %></textarea></div><div class="modal-footer"><input class="btn" type="submit" value="Save"/></div></form>'), /** @property */ cols: 80, /** @property */ rows: 10, /** @property */ events: { "keydown textarea": "clearError", "submit": "saveOrCancel", "hide": "saveOrCancel", "hidden": "close", "shown": "focus" }, /** @property {Object} modalOptions The options passed to Bootstrap's modal plugin. */ modalOptions: { backdrop: false }, /** Renders a modal form dialog with a textarea, submit button and a close button. */ render: function () { this.$el.html($(this.template({ column: this.column, cols: this.cols, rows: this.rows, content: this.formatter.fromRaw(this.model.get(this.column.get("name"))) }))); this.delegateEvents(); this.$el.modal(this.modalOptions); return this; }, /** Event handler. Saves the text in the text area to the model when submitting. When cancelling, if the text area is dirty, a confirmation dialog will pop up. If the user clicks confirm, the text will be saved to the model. Triggers a Backbone `backgrid:error` event from the model along with the model, column and the existing value as the parameters if the value cannot be converted. @param {Event} e */ saveOrCancel: function (e) { if (e && e.type == "submit") { e.preventDefault(); e.stopPropagation(); } var model = this.model; var column = this.column; var val = this.$el.find("textarea").val(); var newValue = this.formatter.toRaw(val); if (_.isUndefined(newValue)) { model.trigger("backgrid:error", model, column, val); if (e) { e.preventDefault(); e.stopPropagation(); } } else if (!e || e.type == "submit" || (e.type == "hide" && newValue !== (this.model.get(this.column.get("name")) || '').replace(/\r/g, '') && window.confirm("Would you like to save your changes?"))) { model.set(column.get("name"), newValue); this.$el.modal("hide"); } else if (e.type != "hide") this.$el.modal("hide"); }, clearError: _.debounce(function () { if (this.formatter.toRaw(this.$el.find("textarea").val())) { this.$el.parent().removeClass("error"); } }, 150), /** Triggers a `backgrid:edited` event along with the cell editor as the parameter after the modal is hidden. @param {Event} e */ close: function (e) { var model = this.model; model.trigger("backgrid:edited", model, this.column, new Backgrid.Command(e)); }, /** Focuses the textarea when the modal is shown. */ focus: function () { this.$el.find("textarea").focus(); } }); /** TextCell is a string cell type that renders a form with a text area in a modal dialog instead of an input box editor. It is best suited for entering a large body of text. @class Backgrid.Extension.TextCell @extends Backgrid.StringCell */ var TextCell = Backgrid.Extension.TextCell = Backgrid.StringCell.extend({ /** @property */ className: "text-cell", /** @property */ editor: TextareaEditor }); }(window, jQuery, _, Backbone, Backgrid));
    JavaScript
    0
    @@ -3215,24 +3215,90 @@ %22);%0A %7D,%0A%0A + /**%0A Clears the error class on the parent cell.%0A */%0A clearErr @@ -3335,16 +3335,31 @@ if +(!_.isUndefined (this.fo @@ -3405,16 +3405,17 @@ .val())) +) %7B%0A
    f9451d9339839e32fab7c6c27e6fcc32dfe75037
    make composition cache work
    lib/composition.js
    lib/composition.js
    var File = require('./file'); var Cache = require('./cache'); var Module = require('./module'); var utils = require('./client/utils'); var composition_cache = Cache('compositions'); /** * Get module instance composition. */ module.exports = function (name, role, callback) { // get composition from cache var composition = composition_cache.get(name); switch (composition) { // handle invalid composition configuration case 'INVALID': return callback(new Error('Invalid composition "' + name + '".')); // handle cache hit case !undefined: // check access for cached item if (!utils.roleAccess(composition, role)) { return callback(new Error('Access denied for composition "' + name + '"')); } // return if composition is complete if (!composition.LOAD) { return callback(null, composition); } } // read the composition json File.json(engine.paths.app_composition + name + '.json', function (err, config) { // handle error if ((err = err || checkComposition(name, role, config))) { return callback(err); } // create mandatory package infos to custom module if (typeof config.module === 'object') { config.module.name = name; config.module.version = 'custom'; config.module._id = name + '@custom'; module._base = engine.repo; } Module(config.module, function (err, modulePackage) { // handle module package error if (err) { return callback(err); } // prepare instance components if (config.client && (config.client.styles || config.client.markup)) { // send module id and module base var components = { base: modulePackage._base, module: modulePackage._id, styles: config.client.styles, markup: config.client.markup }; File.prepare(components, function (err, files) { // update file paths in module package if (files.styles) { config.client.styles = files.styles; } if (files.markup) { config.client.markup = files.markup; } finish(name, modulePackage, config, callback); }); return; } finish(name, modulePackage, config, callback); }); }); }; function finish (name, modulePackage, config, callback) { // merge package data into config if (modulePackage.composition) { config = mergePackage(modulePackage.version, modulePackage.composition, config); } // save composition in cache composition_cache.set(name, config); // return composition config callback(null, config); } /** * Check composition config. */ function checkComposition (name, role, config) { // handle not found if (!config) { return new Error('composition "' + name +'" not found.'); } // check if composition has a module if (!config.module) { // save as invalid in cache composition_cache.set(name, 'INVALID'); return new Error('No module info in composition "' + name + '".'); } // check access if (!utils.roleAccess(config, role)) { // save access information in cache, to check access without loading the hole file again composition_cache.set(name, {roles: config.roles, LOAD: true}); return new Error('Access denied: Role "' + role + '", Composition "' + name + '".'); } // set composition name as custom module name if (typeof config.module === 'object' && !config.module.name) { config.module.name = config.name; } } /** * Merge package config into composition config. */ function mergePackage (version, package_instance, config) { // merge client related options if (package_instance.client) { // ensure client config object config.client = config.client || {}; config.client.name = config.name; config.client.version = version; // set client module scripts if (package_instance.client.module) { config.client.module = package_instance.client.module; } // config if (package_instance.client.config) { for (var key in package_instance.client.config) { if (typeof config.client.config[key] === 'undefined') { config.client.config[key] = package_instance.client.config[key]; } } } // flow if (package_instance.client.flow) { config.client.flow = (config.client.flow || []).concat(package_instance.client.flow); } // markup if (package_instance.client.markup) { config.client.markup = (config.client.markup || []).concat(package_instance.client.markup); } // styles if (package_instance.client.styles) { config.client.styles = (config.client.styles || []).concat(package_instance.client.styles); } } // server flow if (package_instance.flow) { config.flow = (config.flow || []).concat(package_instance.flow); } // merge server config if (package_instance.config) { for (var prop in package_instance.config) { if (typeof config.config[prop] === 'undefined') { config.config[prop] = package_instance.config[prop]; } } } return config; }
    JavaScript
    0
    @@ -368,14 +368,10 @@ -switch +if (co @@ -383,22 +383,16 @@ tion) %7B%0A - %0A @@ -396,64 +396,27 @@ -// handle invalid composition configuration%0A case +if (composition === 'IN @@ -421,17 +421,19 @@ INVALID' -: +) %7B %0A @@ -516,79 +516,11 @@ -%0A // handle cache hit%0A case !undefined:%0A %0A +%7D%0A%0A @@ -554,28 +554,24 @@ hed item %0A - if ( @@ -606,28 +606,24 @@ n, role)) %7B%0A - @@ -706,39 +706,19 @@ - %7D%0A %0A +%7D%0A%0A @@ -758,28 +758,24 @@ ete%0A - - if (!composi @@ -783,28 +783,24 @@ ion.LOAD) %7B%0A - @@ -835,20 +835,16 @@ ition);%0A - @@ -851,18 +851,16 @@ %7D%0A %7D%0A - %0A //
    2533551dcd46caa844436ec5f9b1aa83912291c4
    Implement signup email handler and email state * Re-order state object to reflect order of inputs
    client/mobile/components/shared/signup.js
    client/mobile/components/shared/signup.js
    var React = require('react-native'); var Login = require('./login'); var JoinClassView = require('./../student/joinClassView'); var StartClassView = require('./../teacher/startClassView'); var api = require('./../../utils/api'); var { View, Text, StyleSheet, TextInput, TouchableHighlight, Picker, ActivityIndicatorIOS, Navigator } = React; class Signup extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', confirmedPassword: '', firstName: '', lastName: '', accountType: 'student', isLoading: false, error: false, passwordError: false }; } handleFirstNameChange(event) { this.setState({ firstName: event.nativeEvent.text }); } handleLastNameChange(event) { this.setState({ lastName: event.nativeEvent.text }); } handleUsernameChange(event) { this.setState({ username: event.nativeEvent.text }); } handlePasswordChange(event) { this.setState({ password: event.nativeEvent.text }); } handleConfirmedPasswordChange(event) { this.setState({ confirmedPassword: event.nativeEvent.text }); } handleSubmit() { if (this.state.password === this.state.confirmedPassword) { this.setState({ isLoading: true, passwordError: false }); api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType) .then((response) => { if(response.status === 500){ this.setState({ error: 'User already exists', password: '', confirmedPassword: '', isLoading: false }); } else if(response.status === 200) { //keychain stuff? var body = JSON.parse(response._bodyText); if(body.teacher) { this.props.navigator.push({ component: StartClassView, classes: body.teacher.classes, userId: body.teacher.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } else if (body.student) { this.props.navigator.push({ component: JoinClassView, classes: body.student.classes, userId: body.student.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } } }) .catch((err) => { this.setState({ error: 'User already exists' + err, isLoading: false }); }); } else { this.setState({ isLoading: false, password: '', confirmedPassword: '', passwordError: 'passwords do not match' }); } } handleRedirect() { this.props.navigator.pop(); } render() { var showErr = ( this.state.error ? <Text style={styles.err}> {this.state.error} </Text> : <View></View> ); var showPasswordErr = ( this.state.passwordError ? <Text style={styles.err}> {this.state.passwordError} </Text> : <View></View> ); return ( <View style={{flex: 1, backgroundColor: 'white'}}> <View style={styles.mainContainer}> <Text style={styles.fieldTitle}> Username </Text> <TextInput autoCapitalize={'none'} autoCorrect={false} maxLength={16} style={styles.userInput} value={this.state.username} returnKeyType={'next'} onChange={this.handleUsernameChange.bind(this)} onSubmitEditing={(event) => { this.refs.SecondInput.focus(); }} /> <Text style={styles.fieldTitle}> Password </Text> <TextInput ref='SecondInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.password} returnKeyType={'next'} onChange={this.handlePasswordChange.bind(this)} onSubmitEditing={(event) => { this.refs.ThirdInput.focus(); }} /> <Text style={styles.fieldTitle}> Confirm Password </Text> <TextInput ref='ThirdInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.confirmedPassword} returnKeyType={'go'} onSubmitEditing={this.handleSubmit.bind(this)} onChange={this.handleConfirmedPasswordChange.bind(this)} /> <Text style={styles.fieldTitle}> Account Type </Text> <Picker style={styles.picker} selectedValue={this.state.accountType} onValueChange={(type) => this.setState({accountType: type})}> <Picker.Item label="Student" value="student" /> <Picker.Item label="Teacher" value="teacher" /> </Picker> <TouchableHighlight style={styles.button} onPress={this.handleSubmit.bind(this)} underlayColor='#e66365' > <Text style={styles.buttonText}> Sign Up </Text> </TouchableHighlight> <TouchableHighlight onPress={this.handleRedirect.bind(this)} underlayColor='#ededed' > <Text style={styles.signin}> Already have an account? Sign in! </Text> </TouchableHighlight> <ActivityIndicatorIOS animating= {this.state.isLoading} size='large' style={styles.loading} /> {showErr} {showPasswordErr} </View> </View> ); } } var styles = StyleSheet.create({ mainContainer: { flex: 1, padding: 30, flexDirection: 'column', justifyContent: 'center', }, fieldTitle: { marginTop: 10, marginBottom: 15, fontSize: 18, textAlign: 'center', color: '#616161' }, userInput: { height: 50, padding: 4, fontSize: 18, borderWidth: 1, borderColor: '#616161', borderRadius: 4, color: '#616161' }, picker: { bottom: 70, height: 70 }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, button: { height: 45, flexDirection: 'row', backgroundColor: '#FF5A5F', borderColor: 'transparent', borderWidth: 1, borderRadius: 4, marginBottom: 10, marginTop: 30, alignSelf: 'stretch', justifyContent: 'center' }, signin: { marginTop: 20, fontSize: 14, textAlign: 'center' }, loading: { marginTop: 20 }, err: { fontSize: 14, textAlign: 'center' }, }); module.exports = Signup;
    JavaScript
    0
    @@ -453,29 +453,30 @@ e = %7B%0A -usern +firstN ame: '',%0A @@ -474,32 +474,32 @@ : '',%0A -password +lastName : '',%0A @@ -498,33 +498,24 @@ ,%0A -confirmedPassword +username : '',%0A @@ -514,33 +514,29 @@ : '',%0A -firstName +email : '',%0A @@ -531,32 +531,61 @@ : '',%0A -lastName +password: '',%0A confirmedPassword : '',%0A @@ -997,32 +997,130 @@ xt%0A %7D);%0A %7D%0A%0A + handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A handlePassword
    b7a634649f273aff78eef8fda8cf5f1a3075016e
    Implement signup email handler and email state * Re-order state object to reflect order of inputs
    client/mobile/components/shared/signup.js
    client/mobile/components/shared/signup.js
    var React = require('react-native'); var Login = require('./login'); var JoinClassView = require('./../student/joinClassView'); var StartClassView = require('./../teacher/startClassView'); var api = require('./../../utils/api'); var { View, Text, StyleSheet, TextInput, TouchableHighlight, Picker, ActivityIndicatorIOS, Navigator } = React; class Signup extends React.Component { constructor(props) { super(props); this.state = { username: '', password: '', confirmedPassword: '', firstName: '', lastName: '', accountType: 'student', isLoading: false, error: false, passwordError: false }; } handleFirstNameChange(event) { this.setState({ firstName: event.nativeEvent.text }); } handleLastNameChange(event) { this.setState({ lastName: event.nativeEvent.text }); } handleUsernameChange(event) { this.setState({ username: event.nativeEvent.text }); } handlePasswordChange(event) { this.setState({ password: event.nativeEvent.text }); } handleConfirmedPasswordChange(event) { this.setState({ confirmedPassword: event.nativeEvent.text }); } handleSubmit() { if (this.state.password === this.state.confirmedPassword) { this.setState({ isLoading: true, passwordError: false }); api.signup(this.state.username, this.state.password, this.state.firstName, this.state.lastName, this.state.accountType) .then((response) => { if(response.status === 500){ this.setState({ error: 'User already exists', password: '', confirmedPassword: '', isLoading: false }); } else if(response.status === 200) { //keychain stuff? var body = JSON.parse(response._bodyText); if(body.teacher) { this.props.navigator.push({ component: StartClassView, classes: body.teacher.classes, userId: body.teacher.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } else if (body.student) { this.props.navigator.push({ component: JoinClassView, classes: body.student.classes, userId: body.student.uid, sceneConfig: { ...Navigator.SceneConfigs.FloatFromBottom, gestures: {} } }); } } }) .catch((err) => { this.setState({ error: 'User already exists' + err, isLoading: false }); }); } else { this.setState({ isLoading: false, password: '', confirmedPassword: '', passwordError: 'passwords do not match' }); } } handleRedirect() { this.props.navigator.pop(); } render() { var showErr = ( this.state.error ? <Text style={styles.err}> {this.state.error} </Text> : <View></View> ); var showPasswordErr = ( this.state.passwordError ? <Text style={styles.err}> {this.state.passwordError} </Text> : <View></View> ); return ( <View style={{flex: 1, backgroundColor: 'white'}}> <View style={styles.mainContainer}> <Text style={styles.fieldTitle}> Username </Text> <TextInput autoCapitalize={'none'} autoCorrect={false} maxLength={16} style={styles.userInput} value={this.state.username} returnKeyType={'next'} onChange={this.handleUsernameChange.bind(this)} onSubmitEditing={(event) => { this.refs.SecondInput.focus(); }} /> <Text style={styles.fieldTitle}> Password </Text> <TextInput ref='SecondInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.password} returnKeyType={'next'} onChange={this.handlePasswordChange.bind(this)} onSubmitEditing={(event) => { this.refs.ThirdInput.focus(); }} /> <Text style={styles.fieldTitle}> Confirm Password </Text> <TextInput ref='ThirdInput' autoCapitalize={'none'} autoCorrect={false} maxLength={16} secureTextEntry={true} style={styles.userInput} value={this.state.confirmedPassword} returnKeyType={'go'} onSubmitEditing={this.handleSubmit.bind(this)} onChange={this.handleConfirmedPasswordChange.bind(this)} /> <Text style={styles.fieldTitle}> Account Type </Text> <Picker style={styles.picker} selectedValue={this.state.accountType} onValueChange={(type) => this.setState({accountType: type})}> <Picker.Item label="Student" value="student" /> <Picker.Item label="Teacher" value="teacher" /> </Picker> <TouchableHighlight style={styles.button} onPress={this.handleSubmit.bind(this)} underlayColor='#e66365' > <Text style={styles.buttonText}> Sign Up </Text> </TouchableHighlight> <TouchableHighlight onPress={this.handleRedirect.bind(this)} underlayColor='#ededed' > <Text style={styles.signin}> Already have an account? Sign in! </Text> </TouchableHighlight> <ActivityIndicatorIOS animating= {this.state.isLoading} size='large' style={styles.loading} /> {showErr} {showPasswordErr} </View> </View> ); } } var styles = StyleSheet.create({ mainContainer: { flex: 1, padding: 30, flexDirection: 'column', justifyContent: 'center', }, fieldTitle: { marginTop: 10, marginBottom: 15, fontSize: 18, textAlign: 'center', color: '#616161' }, userInput: { height: 50, padding: 4, fontSize: 18, borderWidth: 1, borderColor: '#616161', borderRadius: 4, color: '#616161' }, picker: { bottom: 70, height: 70 }, buttonText: { fontSize: 18, color: 'white', alignSelf: 'center' }, button: { height: 45, flexDirection: 'row', backgroundColor: '#FF5A5F', borderColor: 'transparent', borderWidth: 1, borderRadius: 4, marginBottom: 10, marginTop: 30, alignSelf: 'stretch', justifyContent: 'center' }, signin: { marginTop: 20, fontSize: 14, textAlign: 'center' }, loading: { marginTop: 20 }, err: { fontSize: 14, textAlign: 'center' }, }); module.exports = Signup;
    JavaScript
    0
    @@ -453,29 +453,30 @@ e = %7B%0A -usern +firstN ame: '',%0A @@ -474,32 +474,32 @@ : '',%0A -password +lastName : '',%0A @@ -498,33 +498,24 @@ ,%0A -confirmedPassword +username : '',%0A @@ -514,33 +514,29 @@ : '',%0A -firstName +email : '',%0A @@ -531,32 +531,61 @@ : '',%0A -lastName +password: '',%0A confirmedPassword : '',%0A @@ -997,32 +997,130 @@ xt%0A %7D);%0A %7D%0A%0A + handleEmailChange(event) %7B%0A this.setState(%7B%0A email: event.nativeEvent.text%0A %7D);%0A %7D%0A%0A handlePassword
    93a63d4371249b1d3d8f0c934153804261d6e072
    add promise rejection error reporting
    client/scripts/arcademode/actions/test.js
    client/scripts/arcademode/actions/test.js
    'use strict'; export const OUTPUT_CHANGED = 'OUTPUT_CHANGED'; export const TESTS_STARTED = 'TESTS_STARTED'; export const TESTS_FINISHED = 'TESTS_FINISHED'; export function onOutputChange(newOutput) { return { type: OUTPUT_CHANGED, userOutput: newOutput }; } /* Thunk action which runs the test cases against user code. */ export function runTests(userCode, currChallenge) { return dispatch => { dispatch(actionTestsStarted()); // Eval user code inside worker // http://stackoverflow.com/questions/9020116/is-it-possible-to-restrict-the-scope-of-a-javascript-function/36255766#36255766 function createWorker () { return new Promise((resolve, reject) => { const wk = new Worker('../../public/js/worker.bundle.js'); wk.postMessage([userCode, currChallenge.toJS()]); // postMessage mangles the Immutable object, so it needs to be transformed into regular JS before sending over to worker. wk.onmessage = e => { // console.log(`worker onmessage result: ${e.data}`); resolve(e.data); }; }); } return createWorker() .then(workerData => { dispatch(onOutputChange(workerData[0].output)); if (workerData.length > 1) { dispatch(actionTestsFinished(workerData.slice(1))); } }); }; } /* Dispatched when a user starts running the tests.*/ export function actionTestsStarted () { return { type: TESTS_STARTED }; } /* Dispatched when the tests finish. */ export function actionTestsFinished (testResults) { return { type: TESTS_FINISHED, testResults }; }
    JavaScript
    0
    @@ -610,16 +610,17 @@ 6255766%0A +%0A func @@ -1309,24 +1309,91 @@ %7D%0A %7D) +%0A .catch(err =%3E %7B console.log(%60Promise rejected: $%7Berr%7D.%60); %7D) ;%0A %7D;%0A%7D%0A%0A/*
    31e94b683dbe349bd19c1c0d9f279b0b6c2f46e5
    Update to new redis port to reduce potential collisions
    lib/core/config.js
    lib/core/config.js
    'use strict'; var path = require('path'); var fs = require('fs'); var env = require('./env.js'); var deps = require('./deps.js'); // Constants var CONFIG_FILENAME = 'kalabox.json'; exports.CONFIG_FILENAME = CONFIG_FILENAME; var DEFAULT_GLOBAL_CONFIG = { domain: 'kbox', kboxRoot: ':home:/kalabox', kalaboxRoot: ':kboxRoot:', appsRoot: ':kboxRoot:/apps', sysConfRoot: ':home:/.kalabox', globalPluginRoot: ':kboxRoot:/plugins', globalPlugins: [ 'hipache', 'kalabox_core', 'kalabox_install', 'kalabox_app', 'kalabox_b2d' ], redis: { // @todo: Dynamically set this. host: '1.3.3.7', port: 6379 }, // @this needs to be set dynamically once we merge in config.js dockerHost: '1.3.3.7', startupServicePrefix: 'kalabox_', startupServices: { kalaboxDebian: { name: 'kalabox/debian', containers : { kalaboxSkydns: { name: 'kalabox/skydns', createOpts : { name: 'skydns', HostConfig : { NetworkMode: 'bridge', PortBindings: { '53/udp' : [{'HostIp' : '172.17.42.1', 'HostPort' : '53'}], } } }, startOpts : {} }, kalaboxSkydock: { name: 'kalabox/skydock', createOpts : { name: 'skydock', HostConfig : { NetworkMode: 'bridge', Binds : ['/var/run/docker.sock:/docker.sock', '/skydock.js:/skydock.js'] } }, startOpts : {} }, kalaboxHipache: { name: 'kalabox/hipache', createOpts : { name: 'hipache', HostConfig : { NetworkMode: 'bridge', PortBindings: { '80/tcp' : [{'HostIp' : '', 'HostPort' : '80'}], '6379/tcp' : [{'HostIp' : '', 'HostPort' : '6379'}], } } }, startOpts : {} }, kalaboxDnsmasq: { name: 'kalabox/dnsmasq', createOpts : { name: 'dnsmasq', Env: ['KALABOX_IP=1.3.3.7'], ExposedPorts: { '53/tcp': {}, '53/udp': {} }, HostConfig : { NetworkMode: 'bridge', PortBindings: { '53/udp' : [{'HostIp' : '1.3.3.7', 'HostPort' : '53'}] } } }, startOpts : {} } } } } }; // @todo: implement //var KEYS_TO_CONCAT = {}; function normalizeValue(key, config) { var rawValue = config[key]; if (typeof rawValue === 'string') { var params = rawValue.match(/:[a-zA-Z0-9-_]*:/g); if (params !== null) { for (var index in params) { var param = params[index]; var paramKey = param.substr(1, param.length - 2); var paramValue = config[paramKey]; if (paramValue !== undefined) { config[key] = rawValue.replace(param, paramValue); } } } } } exports.normalizeValue = normalizeValue; function normalize(config) { for (var key in config) { normalizeValue(key, config); } return config; } exports.normalize = normalize; function mixIn(a, b/*, keysToConcat*/) { /*if (!keysToConcat) { keysToConcat = KEYS_TO_CONCAT; }*/ for (var key in b) { //var shouldConcat = keysToConcat[key] !== undefined; var shouldConcat = false; if (shouldConcat) { // Concat. if (a[key] === undefined) { a[key] = b[key]; } else { a[key] = a[key].concat(b[key]); } } else { // Override. a[key] = b[key]; } } return normalize(a); } exports.mixIn = mixIn; exports.getEnvConfig = function() { return { home: env.getHomeDir(), srcRoot: env.getSourceRoot() }; }; exports.getDefaultConfig = function() { return mixIn(this.getEnvConfig(), DEFAULT_GLOBAL_CONFIG); }; var getGlobalConfigFilepath = function() { return path.join(env.getKalaboxRoot(), CONFIG_FILENAME); }; var loadConfigFile = function(configFilepath) { return require(configFilepath); }; exports.getGlobalConfig = function() { var defaultConfig = this.getDefaultConfig(); var globalConfigFilepath = getGlobalConfigFilepath(); if (fs.existsSync(globalConfigFilepath)) { var globalConfigFile = loadConfigFile(globalConfigFilepath); return mixIn(defaultConfig, globalConfigFile); } else { return defaultConfig; } }; exports.getAppConfigFilepath = function(app, config) { return path.join(config.appsRoot, app.name, CONFIG_FILENAME); }; exports.getAppConfig = function(app) { var globalConfig = this.getGlobalConfig(); var appRoot = path.join(globalConfig.appsRoot, app.name); var appConfigFilepath = path.join(appRoot, CONFIG_FILENAME); var appConfigFile = require(appConfigFilepath); appConfigFile.appRoot = appRoot; appConfigFile.appCidsRoot = ':appRoot:/.cids'; return mixIn(globalConfig, appConfigFile); };
    JavaScript
    0
    @@ -631,20 +631,20 @@ port: -6379 +8160 %0A %7D,%0A @@ -1842,20 +1842,20 @@ ' -6379 +8160 /tcp' : @@ -1889,12 +1889,12 @@ : ' -6379 +8160 '%7D%5D,
    2fd85899d20ad2d15555c6975f16e095dfc348f3
    add exception handling for cloudflare error.
    lib/courier/jnt.js
    lib/courier/jnt.js
    'use strict' var request = require('request') var moment = require('moment') var tracker = require('../') var trackingInfo = function (number) { return { method: 'POST', url: 'https://www.jtexpress.ph/index/router/index.html', json: true, body: { method: 'app.findTrack', data: { billcode: number, lang: 'en', source: 3 } } } } var parser = { trace: function (data) { var courier = { code: tracker.COURIER.JNT.CODE, name: tracker.COURIER.JNT.NAME } var result = { courier: courier, number: data.billcode, status: tracker.STATUS.PENDING } var checkpoints = [] for (var i = 0; i < data.details.length; i++) { var item = data.details[i] var message = [ item.desc ].join(' - ') var checkpoint = { courier: courier, location: item.city || item.siteName, message: message, status: tracker.STATUS.IN_TRANSIT, time: moment(item.scantime + 'T+0800', 'YYYY-MM-DD HH:mm:ssZ').utc().format('YYYY-MM-DDTHH:mmZ') } if (item.scantype === 'Delivered') { checkpoint.status = tracker.STATUS.DELIVERED } checkpoints.push(checkpoint) } result.checkpoints = checkpoints result.status = tracker.normalizeStatus(result.checkpoints) return result } } module.exports = function () { return { trackingInfo: trackingInfo, trace: function (number, cb) { var tracking = trackingInfo(number) request(tracking, function (err, res, body) { if (err) { return cb(err) } try { var result = parser.trace(JSON.parse(body.data)) cb(result ? null : tracker.error(tracker.ERROR.INVALID_NUMBER), result) } catch (e) { cb(tracker.error(e.message)) } }) } } }
    JavaScript
    0
    @@ -1645,16 +1645,124 @@ try %7B%0A + if (res.statusCode !== 200) %7B%0A return cb(tracker.error(res.statusMessage))%0A %7D%0A
    3d5f46d4917d6eadf46a8e1d772ff7f9f410a29e
    Prepare new Info to be in modal
    client/src/components/shared/Info/Info.js
    client/src/components/shared/Info/Info.js
    // @flow import React, {Fragment} from 'react' import Circle from 'react-icons/lib/fa/circle-o' import {Container} from 'reactstrap' import {Link} from 'react-router-dom' import type {Node} from 'react' import { getNewFinancialData, icoUrl, ShowNumberCurrency, showDate, } from '../../../services/utilities' import {compose, withHandlers} from 'recompose' import {connect} from 'react-redux' import {zoomToLocation} from '../../../actions/verejneActions' import {ENTITY_CLOSE_ZOOM} from '../../../constants' import Contracts from './Contracts' import Notices from './Notices' import Eurofunds from './Eurofunds' import Relations from './Relations' import Trend from './Trend' import ExternalLink from '../ExternalLink' import mapIcon from '../../../assets/mapIcon.svg' import type {NewEntityDetail} from '../../../state' import type {FinancialData} from '../../../services/utilities' import './Info.css' type InfoProps = { data: NewEntityDetail, canClose?: boolean, onClose?: () => void, } type ItemProps = { children?: Node, label?: string, url?: string, linkText?: Node, } const Item = ({children, label, url, linkText}: ItemProps) => ( <li className="info-item"> {label && <strong className="info-item-label">{label}</strong>} {url && ( <ExternalLink isMapView={false} url={url}> {linkText} </ExternalLink> )} {children} </li> ) const Findata = ({data}: {data: FinancialData}) => { const finances = data.finances[0] || {} // possible feature: display finances also for older years return ( <Fragment> <Item label="IČO" url={`http://www.orsr.sk/hladaj_ico.asp?ICO=${data.ico}&SID=0`} // TODO link to zrsr when there is a way to tell companies and persons apart linkText={data.ico} > &nbsp;(<ExternalLink isMapView={false} url={icoUrl(data.ico)}> Detaily o firme </ExternalLink>) </Item> {data.established_on && <Item label="Založená">{showDate(data.established_on)}</Item>} {data.terminated_on && <Item label="Zaniknutá">{showDate(data.terminated_on)}</Item>} {finances.employees && ( <Item label={`Zamestnanci v ${finances.year}`}>{finances.employees}</Item> )} {finances.profit ? ( <Item label={`Zisk v ${finances.year}`} url={icoUrl(data.ico)} linkText={<ShowNumberCurrency num={finances.profit} />} > {finances.profitTrend ? <Trend trend={finances.profitTrend} /> : null} </Item> ) : null} {finances.revenue ? ( <Item label={`Tržby v ${finances.year}`} url={icoUrl(data.ico)} linkText={<ShowNumberCurrency num={finances.revenue} />} > {finances.revenueTrend ? <Trend trend={finances.revenueTrend} /> : null} </Item> ) : null} </Fragment> ) } const Info = ({data, canClose, onClose, showOnMap}: InfoProps) => ( <Container className={canClose ? 'info closable' : 'info'}> <div className="info-header"> <h3 onClick={onClose}> <Circle aria-hidden="true" />&nbsp;{data.name}&nbsp; </h3> <Link to={`/verejne?lat=${data.lat}&lng=${data.lng}&zoom=${ENTITY_CLOSE_ZOOM}`} title="Zobraz na mape" onClick={showOnMap} > <img src={mapIcon} alt="MapMarker" style={{width: '16px', height: '25px'}} /> </Link> {canClose && ( <span className="info-close-button" onClick={onClose}> &times; </span> )} </div> <div className="info-main"> <ul className="info-list"> <Item>{data.address}</Item> {data.companyinfo && <Findata data={getNewFinancialData(data)} />} {data.contracts && data.contracts.price_amount_sum > 0 && ( <Item label="Verejné zákazky" url={`http://www.otvorenezmluvy.sk/documents/search?utf8=%E2%9C%93&q=${data.name}`} linkText={<ShowNumberCurrency num={data.contracts.price_amount_sum} />} /> )} </ul> {data.contracts && data.contracts.count > 0 && <Contracts data={data.contracts} />} {data.notices && data.notices.count > 0 && <Notices data={data.notices} />} {data.eufunds && data.eufunds.eufunds_count > 0 && <Eurofunds data={data.eufunds} />} {data.related.length > 0 && <Relations data={data.related} useNewApi />} </div> </Container> ) export default compose( connect(null, {zoomToLocation}), withHandlers({ showOnMap: ({data, zoomToLocation}) => () => { data.toggleModalOpen && data.toggleModalOpen() zoomToLocation(data, ENTITY_CLOSE_ZOOM) }, }) )(Info)
    JavaScript
    0
    @@ -416,16 +416,33 @@ Location +, toggleModalOpen %7D from ' @@ -968,16 +968,37 @@ Detail,%0A + inModal?: boolean,%0A canClo @@ -4535,16 +4535,33 @@ Location +, toggleModalOpen %7D),%0A wi @@ -4595,16 +4595,25 @@ (%7Bdata, + inModal, zoomToL @@ -4619,16 +4619,33 @@ Location +, toggleModalOpen %7D) =%3E () @@ -4660,37 +4660,19 @@ -data.toggleModalOpen && data. +inModal && togg
    138ad3b71603f2f1ce7a05954c2e065b41d339cb
    Update to ES6 syntax
    client/webpack.production.config.babel.js
    client/webpack.production.config.babel.js
    /* global module, __dirname */ import path from "path"; import webpack from "webpack"; import HTMLPlugin from "html-webpack-plugin"; import CleanPlugin from "clean-webpack-plugin"; import ExtractTextPlugin from "extract-text-webpack-plugin"; import UglifyJSPlugin from "uglifyjs-webpack-plugin"; module.exports = { entry: ["babel-polyfill", "./src/js/index.js"], module: { rules: [ { test: /\.js$/, exclude: /(node_modules)/, use: [ "babel-loader", { loader: "eslint-loader", options: { configFile: path.resolve(__dirname, "./.eslintrc") } } ] }, { test: /\.css$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: "css-loader" }) }, { test: /\.less$/, use: ExtractTextPlugin.extract({ fallback: "style-loader", use: [ {loader: "css-loader"}, {loader: "less-loader"} ] }) }, { test: /\.woff$/, use: { loader: "url-loader?limit=100000" } } ] }, node: { fs: "empty" }, mode: "production", output: { path: path.resolve(__dirname, "./dist"), filename: "app.[hash:8].js", sourceMapFilename: "[name].js.map", publicPath: "/static/" }, plugins: [ new webpack.DefinePlugin({ "process.env.NODE_ENV": JSON.stringify("production") }), new ExtractTextPlugin("style.[hash:8].css"), new HTMLPlugin({ filename: "index.html", title: "Virtool", favicon: "./src/images/favicon.ico", template: "./src/index.html", inject: "body" }), new CleanPlugin(["dist"], { verbose: true }), new UglifyJSPlugin({ sourceMap: true }) ] };
    JavaScript
    0
    @@ -6,16 +6,8 @@ obal - module, __d @@ -286,24 +286,22 @@ %22;%0A%0A -module.exports = +export default %7B%0A%0A
    37d3d04f0ec20f4145fcb9d90b805e706e948a41
    Clean mediatag integration code
    www/common/diffMarked.js
    www/common/diffMarked.js
    define([ 'jquery', '/bower_components/marked/marked.min.js', '/common/cryptpad-common.js', '/common/media-tag.js', '/bower_components/diff-dom/diffDOM.js', '/bower_components/tweetnacl/nacl-fast.min.js', ],function ($, Marked, Cryptpad, MediaTag) { var DiffMd = {}; var DiffDOM = window.diffDOM; var renderer = new Marked.Renderer(); Marked.setOptions({ renderer: renderer }); DiffMd.render = function (md) { return Marked(md); }; // Tasks list var checkedTaskItemPtn = /^\s*\[x\]\s*/; var uncheckedTaskItemPtn = /^\s*\[ \]\s*/; renderer.listitem = function (text) { var isCheckedTaskItem = checkedTaskItemPtn.test(text); var isUncheckedTaskItem = uncheckedTaskItemPtn.test(text); if (isCheckedTaskItem) { text = text.replace(checkedTaskItemPtn, '<i class="fa fa-check-square" aria-hidden="true"></i>&nbsp;') + '\n'; } if (isUncheckedTaskItem) { text = text.replace(uncheckedTaskItemPtn, '<i class="fa fa-square-o" aria-hidden="true"></i>&nbsp;') + '\n'; } var cls = (isCheckedTaskItem || isUncheckedTaskItem) ? ' class="todo-list-item"' : ''; return '<li'+ cls + '>' + text + '</li>\n'; }; renderer.image = function (href, title, text) { if (href.slice(0,6) === '/file/') { var parsed = Cryptpad.parsePadUrl(href); var hexFileName = Cryptpad.base64ToHex(parsed.hashData.channel); var mt = '<media-tag src="/blob/' + hexFileName.slice(0,2) + '/' + hexFileName + '" data-crypto-key="cryptpad:' + parsed.hashData.key + '"></media-tag>'; return mt; } var out = '<img src="' + href + '" alt="' + text + '"'; if (title) { out += ' title="' + title + '"'; } out += this.options.xhtml ? '/>' : '>'; return out; }; var forbiddenTags = [ 'SCRIPT', 'IFRAME', 'OBJECT', 'APPLET', 'VIDEO', 'AUDIO', ]; var unsafeTag = function (info) { if (info.node && $(info.node).parents('media-tag').length) { // Do not remove elements inside a media-tag return true; } if (['addAttribute', 'modifyAttribute'].indexOf(info.diff.action) !== -1) { if (/^on/.test(info.diff.name)) { console.log("Rejecting forbidden element attribute with name", info.diff.name); return true; } } if (['addElement', 'replaceElement'].indexOf(info.diff.action) !== -1) { var msg = "Rejecting forbidden tag of type (%s)"; if (info.diff.element && forbiddenTags.indexOf(info.diff.element.nodeName) !== -1) { console.log(msg, info.diff.element.nodeName); return true; } else if (info.diff.newValue && forbiddenTags.indexOf(info.diff.newValue.nodeName) !== -1) { console.log("Replacing restricted element type (%s) with PRE", info.diff.newValue.nodeName); info.diff.newValue.nodeName = 'PRE'; } } }; var getSubMediaTag = function (element) { var result = []; console.log(element); if (element.nodeName === "MEDIA-TAG") { result.push(element); return result; } if (element.childNodes) { element.childNodes.forEach(function (el) { result = result.concat(getSubMediaTag(el, result)); }); } console.log(result); return result; }; var mediaTag = function (info) { if (info.diff.action === 'addElement') { return getSubMediaTag(info.diff.element); //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes); //MediaTag($mt[0]); } return; }; var slice = function (coll) { return Array.prototype.slice.call(coll); }; /* remove listeners from the DOM */ var removeListeners = function (root) { slice(root.attributes).map(function (attr) { if (/^on/.test(attr.name)) { root.attributes.removeNamedItem(attr.name); } }); // all the way down slice(root.children).forEach(removeListeners); }; var domFromHTML = function (html) { var Dom = new DOMParser().parseFromString(html, "text/html"); removeListeners(Dom.body); return Dom; }; //var toTransform = []; var DD = new DiffDOM({ preDiffApply: function (info) { if (unsafeTag(info)) { return true; } }, }); var makeDiff = function (A, B, id) { var Err; var Els = [A, B].map(function (frag) { if (typeof(frag) === 'object') { if (!frag || (frag && !frag.body)) { Err = "No body"; return; } var els = frag.body.querySelectorAll('#'+id); if (els.length) { return els[0]; } } Err = 'No candidate found'; }); if (Err) { return Err; } var patch = DD.diff(Els[0], Els[1]); return patch; }; DiffMd.apply = function (newHtml, $content) { var id = $content.attr('id'); if (!id) { throw new Error("The element must have a valid id"); } var $div = $('<div>', {id: id}).append(newHtml); var Dom = domFromHTML($('<div>').append($div).html()); var oldDom = domFromHTML($content[0].outerHTML); var patch = makeDiff(oldDom, Dom, id); if (typeof(patch) === 'string') { throw new Error(patch); } else { DD.apply($content[0], patch); var $mts = $content.find('media-tag:not(:has(*))'); $mts.each(function (i, el) { MediaTag(el); }); } }; $(window.document).on('decryption', function (e) { var decrypted = e.originalEvent; if (decrypted.callback) { decrypted.callback(); } }); return DiffMd; });
    JavaScript
    0
    @@ -3189,752 +3189,8 @@ %7D;%0A%0A - var getSubMediaTag = function (element) %7B%0A var result = %5B%5D;%0A console.log(element);%0A if (element.nodeName === %22MEDIA-TAG%22) %7B%0A result.push(element);%0A return result;%0A %7D%0A if (element.childNodes) %7B%0A element.childNodes.forEach(function (el) %7B%0A result = result.concat(getSubMediaTag(el, result));%0A %7D);%0A %7D%0A console.log(result);%0A return result;%0A %7D;%0A var mediaTag = function (info) %7B%0A if (info.diff.action === 'addElement') %7B%0A return getSubMediaTag(info.diff.element);%0A //MediaTag.CryptoFilter.setAllowedMediaTypes(allowedMediaTypes);%0A //MediaTag($mt%5B0%5D);%0A %7D%0A return;%0A %7D;%0A %0A @@ -3810,36 +3810,8 @@ %7D;%0A%0A - //var toTransform = %5B%5D;%0A
    7b2b3e9dfbf805da61b1e957e71bdd3bad0352dc
    Fix typo
    server/lib/client-info.js
    server/lib/client-info.js
    /** * Client info keyed on client id. Mainly used for logging. * Getting full details about a client is a multi-part process * since we get partial info when they request a token, and more * when they finally connect/authenticate over the web socket. */ var useragent = require('useragent'); var log = require('./logger.js'); function ClientInfo(id, userAgentString) { this.id = id; // User isn't yet known, we'll update this in update() later this.username = 'unauthenticated'; // Try to extract useful browser/device info try { var agent = useragent.parse(userAgentString); this.agent = agent.toString(); this.device = agent.device.toString(); } catch(err) { log.error({err: err}, 'Error parsing user agent string: `%s`', userAgentString); this.agent = "Unknown"; this.device = "Unknown"; } this.born = Date.now(); // How many times this client has sync'ed during this connection. this.downstreamSyncs = 0; this.upstreamSyncs = 0; // Web Socket data usage for this client this.bytesSent = 0; this.bytesRecevied = 0; } // How long this client has been connected in MS ClientInfo.prototype.connectedInMS = function() { return Date.now() - this.born; }; /** * Keep track of client info objects while they are still connected. */ var clients = {}; function remove(id) { delete clients[id]; } function find(client) { return clients[client.id]; } /** * Step 1: create a partial ClientInfo object when the client requests a token */ function init(id, userAgentString) { clients[id] = new ClientInfo(id, userAgentString); } /** * Step 2: update the ClientInfo object with all the client info when * web socket connection is completed. */ function update(client) { var id = client.id; // Auto-remove when this client is closed. client.once('closed', function() { remove(id); }); var info = find(client); if(!info) { log.warn('No ClientInfo object found for client.id=%s', id); return; } info.username = client.username; } module.exports = { init: init, update: update, remove: remove, find: find };
    JavaScript
    0.999999
    @@ -1064,18 +1064,18 @@ ytesRece -v i +v ed = 0;%0A
    205dba7e0e4a828ae27a4b08af3c67186e162a7a
    Improve variable names
    server/lib/userSession.js
    server/lib/userSession.js
    // // Copyright 2014 Ilkka Oksanen <[email protected]> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, // software distributed under the License is distributed on an "AS // IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either // express or implied. See the License for the specific language // governing permissions and limitations under the License. // 'use strict'; const user = require('../models/user'); exports.auth = function *auth(next) { const cookie = this.cookies.get('auth') || ''; const ts = new Date(); this.mas = this.mas || {}; this.mas.user = null; const [ userId, secret ] = cookie.split('-'); if (userId && secret) { const userRecord = yield user.fetch(parseInt(userId)); if (userRecord && userRecord.get('secretExpires') > ts && userRecord.get('secret') === secret) { this.mas.user = userRecord; } } yield next; };
    JavaScript
    0.998747
    @@ -643,17 +643,17 @@ %0A%0Aconst -u +U ser = re @@ -950,22 +950,16 @@ nst user -Record = yield @@ -959,17 +959,17 @@ = yield -u +U ser.fetc @@ -1010,22 +1010,16 @@ user -Record && user Reco @@ -1010,30 +1010,24 @@ user && user -Record .get('secret @@ -1047,31 +1047,13 @@ s && -%0A userRecord + user .get @@ -1113,14 +1113,8 @@ user -Record ;%0A
    55be56e6a4d27d717954a93e4043a04705ad06af
    use https for transifex download
    tools/downloadLanguages.js
    tools/downloadLanguages.js
    /* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this file, * You can obtain one at http://mozilla.org/MPL/2.0/. */ /* Environment Variables USERNAME - valid Transifex user name with read privileges PASSWORD - password for above username LANG [optional] - single language code to retrieve in xx-XX format (I.e. en-US) */ 'use strict' const path = require('path') const fs = require('fs') const request = require('request') // The names of the directories in the locales folder are used as a list of languages to retrieve var languages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')).filter(function (language) { return language !== 'en-US' }).map(function (language) { return language.replace('-', '_') }) // Support retrieving a single language if (process.env.LANG_CODE) { languages = [process.env.LANG_CODE] } if (process.env.META) { var localLanguages = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales')) console.log(` <meta name="availableLanguages" content="${localLanguages.join(', ')}">`) console.log(localLanguages.map(function (l) { return `'${l}'` }).join(',\n ')) process.exit(0) } // Setup the credentials const username = process.env.USERNAME const password = process.env.PASSWORD if (!(username && password)) { throw new Error('The USERNAME and PASSWORD environment variables must be set to the Transifex credentials') } // URI and resource list const TEMPLATE = 'http://www.transifex.com/api/2/project/brave-laptop/resource/RESOURCE_SLUG/translation/LANG_CODE/?file' // Retrieve resource names dynamically var resources = fs.readdirSync(path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', 'en-US')).map(function (language) { return language.split(/\./)[0] }) // For each language / resource combination languages.forEach(function (languageCode) { resources.forEach(function (resource) { // Build the URI var URI = TEMPLATE.replace('RESOURCE_SLUG', resource + 'properties') URI = URI.replace('LANG_CODE', languageCode) // Authorize and request the translation file request.get(URI, { 'auth': { 'user': username, 'pass': password, 'sendImmediately': true } }, function (error, response, body) { if (error) { // Report errors (often timeouts) console.log(error.toString()) } else { if (response.statusCode === 401) { throw new Error('Unauthorized - Are the USERNAME and PASSWORD env vars set correctly?') } // Check to see if the directory exists, if not create it var directory = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-')) if (!fs.existsSync(directory)) { console.log(`${languageCode} does not exist - creating directory`) if (!process.env.TEST) { fs.mkdirSync(directory) } else { console.log(`${languageCode} would have been created`) } } else { // Directory exists - continue } // Build the filename and store the translation file var filename = path.join(__dirname, '..', 'app', 'extensions', 'brave', 'locales', languageCode.replace('_', '-'), resource + '.properties') console.log('[*] ' + filename) if (process.env.TEST) { console.log(body) } else { fs.writeFileSync(filename, body) } } }) }) })
    JavaScript
    0
    @@ -1594,16 +1594,17 @@ = 'http +s ://www.t
    d6ae29f4d18462b2b150fba0e12d3b42960fca20
    Test cases for default code version
    tests/unit/services/rollbar-test.js
    tests/unit/services/rollbar-test.js
    import { moduleFor, test } from 'ember-qunit'; import Ember from 'ember'; import Rollbar from 'rollbar'; moduleFor('service:rollbar', 'Unit | Service | rollbar', { needs: ['config:environment'] }); test('it exists', function(assert) { let service = this.subject(); assert.ok(service); }); test('notifier', function(assert) { let service = this.subject(); assert.ok(service.get('notifier') instanceof Rollbar); }); test('critical', function(assert) { let service = this.subject(); let uuid = service.critical('My error message').uuid; assert.ok(uuid); }); test('error', function(assert) { let service = this.subject(); let uuid = service.error('My error message').uuid; assert.ok(uuid); }); test('warning', function(assert) { let service = this.subject(); let uuid = service.warning('My error message').uuid; assert.ok(uuid); }); test('info', function(assert) { let service = this.subject(); let uuid = service.info('My error message').uuid; assert.ok(uuid); }); test('debug', function(assert) { let service = this.subject(); let uuid = service.debug('My error message').uuid; assert.ok(uuid); }); test('registerLogger: register error handler for Ember errors if enabled', function(assert) { assert.expect(2); let service = this.subject({ config: { enabled: true }, error(message) { assert.ok(true, 'error handler is called'); assert.equal(message, 'foo', 'error is passed to error handler as argument'); } }); service.registerLogger(); Ember.onerror('foo'); }); test('registerLogger: does not override previous hook', function(assert) { assert.expect(4); let service = this.subject({ config: { enabled: true }, error(message) { assert.ok(true, 'rollbar error handler is called'); assert.equal(message, 'foo', 'error is passed to rollbar error handler as argument'); } }); Ember.onerror = function(message) { assert.ok(true, 'previous hook is called'); assert.equal(message, 'foo', 'error is passed to previous hook as argument'); }; service.registerLogger(); Ember.onerror('foo'); }); test('registerLogger: does not register logger if disabled', function(assert) { assert.expect(1); let service = this.subject({ config: { enabled: false }, error() { assert.notOk(true); } }); Ember.onerror = function() { assert.ok(true); }; service.registerLogger(); Ember.onerror(); })
    JavaScript
    0
    @@ -1131,32 +1131,520 @@ .ok(uuid);%0A%7D);%0A%0A +test('config with default value for code version', function(assert) %7B%0A let service = this.subject();%0A let currentVersion = Ember.getOwner(this).resolveRegistration('config:environment').APP.version%0A assert.equal(service.get('config').code_version, currentVersion);%0A%7D);%0A%0Atest('config custom value for code version', function(assert) %7B%0A let service = this.subject(%7B%0A config: %7B%0A code_version: '1.2.3'%0A %7D%0A %7D);%0A assert.equal(service.get('config').code_version, '1.2.3');%0A%7D);%0A%0A test('registerLo
    8ceb8c074327ecd4be630018c7643f84e26f1b08
    Include the extra secrets.js.
    server/config/secrets.js
    server/config/secrets.js
    JavaScript
    0
    @@ -0,0 +1,362 @@ +/** Important **/%0A/** You should not be committing this file to GitHub **/%0A%0Amodule.exports = %7B%0A // Find the appropriate database to connect to, default to localhost if not found.%0A db: process.env.MONGOHQ_URL %7C%7C process.env.MONGOLAB_URI %7C%7C 'mongodb://localhost/ReactWebpackNode',%0A sessionSecret: process.env.SESSION_SECRET %7C%7C 'Your Session Secret goes here'%0A%7D;
    ede80b3f5a07d3cc11ba94f9ea40e52e0bb3a8a1
    add endGame method in game menu
    src/common/directives/diGameMenu/diGameMenu.js
    src/common/directives/diGameMenu/diGameMenu.js
    /** * directive.diGameMenu Module * * Description */ angular.module('directive.diGameMenu', [ 'service.GameManager' ]) .controller('GameMenuCtrl', [ '$scope', 'GameManager', function ( $scope, GameManager ){ $scope.continueGame = function continueGame() { GameManager.setPause(); $scope.closeModal(); return this; }; $scope.restartGame = function restartGame() { GameManager.newGame(); $scope.closeModal(); GameManager.setGameStart(); return this; }; this.isPause = function isPause() { return GameManager.isPause(); }; this.isGameStart = function isGameStart() { return GameManager.isGameStart(); }; }]) .directive('diGameMenu', [ function( ){ var GameMenu = {}; GameMenu.controller = 'GameMenuCtrl'; GameMenu.templateUrl = 'directives/diGameMenu/diGameMenu.tpl.html'; GameMenu.restrict = 'A'; GameMenu.replace = true; GameMenu.scope = true; GameMenu.link = function link(scope, element, attrs, controller) { scope.$on('app.pause', function() { if (!controller.isPause() && controller.isGameStart()) { $(element).modal({ backdrop: 'static' }); } else { scope.closeModal(); } }); scope.closeModal = function closeModal() { $(element).modal('hide'); }; }; return GameMenu; }]);
    JavaScript
    0
    @@ -334,37 +334,16 @@ odal();%0A - return this;%0A %7D;%0A%0A @@ -496,23 +496,113 @@ - return this +%7D;%0A%0A $scope.endGame = function endGame() %7B%0A GameManager.gameOver();%0A $scope.closeModal() ;%0A
    0313147b8cc69c0eb8fe76642922be9b121eadcd
    Fix closure loader path in legacy example
    examples/legacy-closure-lib/webpack.config.js
    examples/legacy-closure-lib/webpack.config.js
    var HtmlWebpackPlugin = require('html-webpack-plugin'), webpack = require('webpack'), pathUtil = require('path'); module.exports = { entry: { app: './src/app.js', }, output: { path: './build', filename: '[name].js', }, resolve: { modulesDirectories: ['node_modules'], root: [ __dirname, ], alias: { 'npm': __dirname + '/node_modules', } }, resolveLoader: { root: pathUtil.join(__dirname, 'node_modules'), }, module: { loaders: [ { test: /google-closure-library\/closure\/goog\/base/, loaders: [ 'imports?this=>{goog:{}}&goog=>this.goog', 'exports?goog', ], }, // Loader for closure library { test: /google-closure-library\/closure\/goog\/.*\.js/, loaders: [ require.resolve('../../index'), ], exclude: [/base\.js$/], }, // Loader for project js files { test: /\/src\/.*\.js/, loaders: [ 'closure', ], exclude: [/node_modules/, /test/], }, ], }, plugins: [ // This will copy the index.html to the build directory and insert script tags new HtmlWebpackPlugin({ template: 'src/index.html', }), new webpack.ProvidePlugin({ goog: 'google-closure-library/closure/goog/base', }), ], closureLoader: { paths: [ __dirname + '/node_modules/google-closure-library/closure/goog', ], es6mode: false, watch: false, }, devServer: { contentBase: './build', noInfo: true, inline: true, historyApiFallback: true, }, devtool: 'source-map', };
    JavaScript
    0
    @@ -1241,17 +1241,38 @@ -'closure' +require.resolve('../../index') ,%0A
    70f855f1a8accf94641c71e48e8544676085fa20
    Rewrite LogoutButton to hooks
    src/components/SettingsManager/LogoutButton.js
    src/components/SettingsManager/LogoutButton.js
    import React from 'react'; import PropTypes from 'prop-types'; import { translate } from '@u-wave/react-translate'; import Button from '@mui/material/Button'; import LogoutIcon from '@mui/icons-material/PowerSettingsNew'; import ConfirmDialog from '../Dialogs/ConfirmDialog'; import FormGroup from '../Form/Group'; const enhance = translate(); class LogoutButton extends React.Component { static propTypes = { t: PropTypes.func.isRequired, onLogout: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { showDialog: false, }; } handleOpen = () => { this.setState({ showDialog: true }); }; handleClose = () => { this.closeDialog(); }; handleConfirm = () => { const { onLogout } = this.props; onLogout(); this.closeDialog(); }; closeDialog() { this.setState({ showDialog: false }); } render() { const { t } = this.props; const { showDialog } = this.state; return ( <> <Button color="inherit" className="LogoutButton" onClick={this.handleOpen}> <LogoutIcon className="LogoutButton-icon" /> {t('settings.logout')} </Button> {showDialog && ( <ConfirmDialog title="" confirmLabel={t('dialogs.logout.action')} onConfirm={this.handleConfirm} onCancel={this.handleClose} > <FormGroup>{t('dialogs.logout.confirm')}</FormGroup> </ConfirmDialog> )} </> ); } } export default enhance(LogoutButton);
    JavaScript
    0
    @@ -65,25 +65,29 @@ mport %7B -t +useT ranslat -e +or %7D from @@ -323,279 +323,165 @@ nst -enhance = translate();%0A%0Aclass LogoutButton extends React.Component %7B%0A static propTypes = %7B%0A t: PropTypes.func.isRequired,%0A onLogout: PropTypes.func.isRequired,%0A %7D;%0A%0A constructor(props) %7B%0A super(props);%0A this.state = %7B%0A showDialog: false,%0A %7D;%0A %7D%0A%0A +%7B useState %7D = React;%0A%0Afunction LogoutButton(%7B onLogout %7D) %7B%0A const %7B t %7D = useTranslator();%0A const %5BshowDialog, setShowDialog%5D = useState(false);%0A%0A const han @@ -502,33 +502,20 @@ %3E %7B%0A -this.setState(%7B s +setS howDialo @@ -519,16 +519,13 @@ alog -: +( true - %7D );%0A @@ -527,24 +527,30 @@ e);%0A %7D;%0A%0A +const handleClose @@ -563,33 +563,35 @@ %3E %7B%0A -this.close +setShow Dialog( +false );%0A %7D;%0A @@ -593,16 +593,22 @@ %7D;%0A%0A +const handleCo @@ -631,127 +631,28 @@ -const %7B onLogout %7D = this.props;%0A%0A onLogout();%0A this.closeDialog();%0A %7D;%0A%0A closeDialog() %7B%0A this.setState(%7B s +onLogout();%0A setS howD @@ -660,110 +660,23 @@ alog -: +( false - %7D );%0A %7D +; %0A%0A - render() %7B%0A const %7B t %7D = this.props;%0A const %7B showDialog %7D = this.state;%0A%0A re @@ -686,18 +686,16 @@ n (%0A - %3C%3E%0A @@ -695,18 +695,16 @@ %3E%0A - - %3CButton @@ -753,21 +753,16 @@ nClick=%7B -this. handleOp @@ -766,18 +766,16 @@ eOpen%7D%3E%0A - @@ -827,18 +827,16 @@ - - %7Bt('sett @@ -856,18 +856,16 @@ %7D%0A - %3C/Button @@ -866,18 +866,16 @@ Button%3E%0A - %7Bs @@ -897,18 +897,16 @@ - %3CConfirm @@ -922,18 +922,16 @@ - title=%22%22 @@ -941,18 +941,16 @@ - - confirmL @@ -993,18 +993,16 @@ - onConfir @@ -1004,21 +1004,16 @@ onfirm=%7B -this. handleCo @@ -1029,18 +1029,16 @@ - - onCancel @@ -1043,13 +1043,8 @@ el=%7B -this. hand @@ -1064,14 +1064,10 @@ - %3E%0A +%3E%0A @@ -1133,18 +1133,16 @@ - %3C/Confir @@ -1160,15 +1160,11 @@ - )%7D%0A - @@ -1173,18 +1173,82 @@ %3E%0A - );%0A %7D +);%0A%7D%0A%0ALogoutButton.propTypes = %7B%0A onLogout: PropTypes.func.isRequired, %0A%7D +; %0A%0Aex @@ -1264,16 +1264,8 @@ ult -enhance( Logo @@ -1272,11 +1272,10 @@ utButton -) ;%0A
    89ab12e6324f4d6fc32280f244bb91cea81482dd
    Use correct path in examples when using handlers nested in subdirs
    examples/serverless-offline/webpack.config.js
    examples/serverless-offline/webpack.config.js
    const path = require('path'); const nodeExternals = require('webpack-node-externals'); module.exports = { entry: './src/handler.js', target: 'node', externals: [nodeExternals()], module: { loaders: [{ test: /\.js$/, loaders: ['babel-loader'], include: __dirname, exclude: /node_modules/, }], }, output: { libraryTarget: 'commonjs', path: path.join(__dirname, '.webpack'), filename: 'handler.js' }, };
    JavaScript
    0
    @@ -433,16 +433,20 @@ ename: ' +src/ handler.
    cde39cdfb33867d32c9b9b8e4b19a27592ff00e8
    Stop ending the test twice\!
    features-support/step_definitions/features.js
    features-support/step_definitions/features.js
    'use strict'; var should = require('should'); var By = require('selenium-webdriver').By; // Test helper. function getProjectFromUrl(callback) { var world = this; var projectRetrievalUrl = 'http://localhost:' + world.appPort + '/?repo_url=' + encodeURIComponent(world.repoUrl); world.browser.get(projectRetrievalUrl) .then(world.browser.getPageSource.bind(world.browser)) .then(function (body) { world.body = body; callback(); }); } // The returned function is passed as a callback to getProjectFromUrl. function getScenarioFromProject(callback, world) { return function(error) { if (error) { callback(error); return; } world.browser.findElements(By.css('.spec-link')) .then(function (specLinks) { var featureLink = specLinks[specLinks.length - 1]; return world.browser.get(featureLink.getAttribute('href')); }) .then(world.browser.getPageSource.bind(world.browser)) .then(function (body) { world.body = body; callback(); }); }; } module.exports = function () { this.Given(/^a URL representing a remote Git repo "([^"]*)"$/, function (repoUrl, callback) { this.repoUrl = repoUrl; callback(); }); this.When(/^an interested party wants to view the features in that repo\.?$/, getProjectFromUrl); this.When(/^they request the features for the same repository again\.?$/, getProjectFromUrl); this.When(/^an interested party wants to view the scenarios within a feature\.?$/, function (callback) { var world = this; getProjectFromUrl.bind(world)(getScenarioFromProject(callback, world)); }); this.When(/^they decide to change which branch is being displayed$/, function (callback) { var world = this; var burgerMenuId = "expand-collapse-repository-controls"; var repositoryCongtrolsId = "repository-controls"; var projectShaElId = "project-commit"; var changeBranchSelectElId = "change-branch-control"; var testingBranchOptionValue = "refs%2Fremotes%2Forigin%2Ftest%2FdoNotDelete"; var burgerMenuEl; var repoControlsEl; // Get the burger menu element. world.browser.findElement(By.id(burgerMenuId)) .then(function(_burgerMenuEl) { burgerMenuEl = _burgerMenuEl; return world.browser.findElement(By.id(repositoryCongtrolsId)); // Get the repo controls element. }).then(function(_repoControlsEl) { repoControlsEl = _repoControlsEl; return repoControlsEl.getAttribute('class'); // Open the repo controls. }).then(function(repoControlsClass) { var isClosed = repoControlsClass.indexOf("collapse") !== -1; if (isClosed) { return burgerMenuEl.click(); } return; // Grab the current SHA }).then(function() { return world.browser.findElement(By.id(projectShaElId)); }).then(function(_projectShaEl) { return _projectShaEl.getText(); }).then(function(originalSha) { world.oringalSha = originalSha; // Grab the branch selecting control. return world.browser.findElement(By.id(changeBranchSelectElId)); // Request to change branch. }).then(function(_changeBranchSelectEl) { return _changeBranchSelectEl.findElement(By.xpath('option[@value=\'' + testingBranchOptionValue + '\']')); }).then(function(_testBranchOptionEl) { return _testBranchOptionEl.click(); }).then(function() { callback(); }); }); this.Then(/^the list of features will be visible\.?$/, function (callback) { should.equal( /\.feature/i.test(this.body) && /\.md/i.test(this.body), true, 'The returned document body does not contain the strings \'.feature\' and \'.md\'' + this.body); callback(); }); this.Then(/^the scenarios will be visible\.?$/, function (callback) { should.equal(/feature-title/i.test(this.body), true, 'The returned document body does not contain a feature title'); callback(); }); this.Then(/^the files from the selected branch are displayed\.$/, function (callback) { var world = this; var projectShaElId = "project-commit"; // Get the new SHA. return world.browser.findElement(By.id(projectShaElId)) .then(function(_projectShaEl) { return _projectShaEl.getText(); }).then(function(newSha) { should.notEqual(newSha, world.oringalSha, 'The SHA did not change on changing branch.'); callback(); }); }); };
    JavaScript
    0.000001
    @@ -4186,31 +4186,24 @@ ew SHA.%0A -return world.browse
    9c3003410adceb851ea3cb2ae16ef37d55046ae4
    add genotype colors constants (#337)
    src/genome-browser/genome-browser-constants.js
    src/genome-browser/genome-browser-constants.js
    // Global constants for GenomeBrowser export default class GenomeBrowserConstants { // CellBase constants static CELLBASE_HOST = "https://ws.zettagenomics.com/cellbase"; static CELLBASE_VERSION = "v5"; // OpenCGA Constants static OPENCGA_HOST = "https://ws.opencb.org/opencga-test"; static OPENCGA_VERSION = "v2"; // Cytobands static CYTOBANDS_COLORS = { gneg: "white", stalk: "#666666", gvar: "#CCCCCC", gpos25: "silver", gpos33: "lightgrey", gpos50: "gray", gpos66: "dimgray", gpos75: "darkgray", gpos100: "black", gpos: "gray", acen: "blue", }; // Sequence colors static SEQUENCE_COLORS = { A: "#009900", C: "#0000FF", G: "#857A00", T: "#aa0000", N: "#555555", }; // Gene biotype colors static GENE_BIOTYPE_COLORS = { "3prime_overlapping_ncrna": "Orange", "ambiguous_orf": "SlateBlue", "antisense": "SteelBlue", "disrupted_domain": "YellowGreen", "IG_C_gene": "#FF7F50", "IG_D_gene": "#FF7F50", "IG_J_gene": "#FF7F50", "IG_V_gene": "#FF7F50", "lincRNA": "#8b668b", "miRNA": "#8b668b", "misc_RNA": "#8b668b", "Mt_rRNA": "#8b668b", "Mt_tRNA": "#8b668b", "ncrna_host": "Fuchsia", "nonsense_mediated_decay": "seagreen", "non_coding": "orangered", "non_stop_decay": "aqua", "polymorphic_pseudogene": "#666666", "processed_pseudogene": "#666666", "processed_transcript": "#0000ff", "protein_coding": "#a00000", "pseudogene": "#666666", "retained_intron": "goldenrod", "retrotransposed": "lightsalmon", "rRNA": "indianred", "sense_intronic": "#20B2AA", "sense_overlapping": "#20B2AA", "snoRNA": "#8b668b", "snRNA": "#8b668b", "transcribed_processed_pseudogene": "#666666", "transcribed_unprocessed_pseudogene": "#666666", "unitary_pseudogene": "#666666", "unprocessed_pseudogene": "#666666", // "": "orangered", "other": "#000000" }; // Codon configuration static CODON_CONFIG = { "": {text: "", color: "transparent"}, "R": {text: "Arg", color: "#BBBFE0"}, "H": {text: "His", color: "#BBBFE0"}, "K": {text: "Lys", color: "#BBBFE0"}, "D": {text: "Asp", color: "#F8B7D3"}, "E": {text: "Glu", color: "#F8B7D3"}, "F": {text: "Phe", color: "#FFE75F"}, "L": {text: "Leu", color: "#FFE75F"}, "I": {text: "Ile", color: "#FFE75F"}, "M": {text: "Met", color: "#FFE75F"}, "V": {text: "Val", color: "#FFE75F"}, "P": {text: "Pro", color: "#FFE75F"}, "A": {text: "Ala", color: "#FFE75F"}, "W": {text: "Trp", color: "#FFE75F"}, "G": {text: "Gly", color: "#FFE75F"}, "T": {text: "Thr", color: "#B3DEC0"}, "S": {text: "Ser", color: "#B3DEC0"}, "Y": {text: "Tyr", color: "#B3DEC0"}, "Q": {text: "Gln", color: "#B3DEC0"}, "N": {text: "Asn", color: "#B3DEC0"}, "C": {text: "Cys", color: "#B3DEC0"}, "X": {text: " X ", color: "#f0f0f0"}, "*": {text: " * ", color: "#DDDDDD"} }; // SNP Biotype colors configuration static SNP_BIOTYPE_COLORS = { "2KB_upstream_variant": "#a2b5cd", "5KB_upstream_variant": "#a2b5cd", "500B_downstream_variant": "#a2b5cd", "5KB_downstream_variant": "#a2b5cd", "3_prime_UTR_variant": "#7ac5cd", "5_prime_UTR_variant": "#7ac5cd", "coding_sequence_variant": "#458b00", "complex_change_in_transcript": "#00fa9a", "frameshift_variant": "#ff69b4", "incomplete_terminal_codon_variant": "#ff00ff", "inframe_codon_gain": "#ffd700", "inframe_codon_loss": "#ffd700", "initiator_codon_change": "#ffd700", "non_synonymous_codon": "#ffd700", "missense_variant": "#ffd700", "intergenic_variant": "#636363", "intron_variant": "#02599c", "mature_miRNA_variant": "#458b00", "nc_transcript_variant": "#32cd32", "splice_acceptor_variant": "#ff7f50", "splice_donor_variant": "#ff7f50", "splice_region_variant": "#ff7f50", "stop_gained": "#ff0000", "stop_lost": "#ff0000", "stop_retained_variant": "#76ee00", "synonymous_codon": "#76ee00", "other": "#000000" }; }
    JavaScript
    0
    @@ -4541,10 +4541,169 @@ %7D;%0A%0A + // Genotypes colors%0A static GENOTYPES_COLORS = %7B%0A %22heterozygous%22: %22darkblue%22,%0A %22homozygous%22: %22cyan%22,%0A %22reference%22: %22gray%22,%0A %7D;%0A%0A %7D%0A
    4453bf5e68f1fd41cebe9e3dc2833d2df7fdfd0f
    Update moonpay api
    server/lib/v1/moonpay.js
    server/lib/v1/moonpay.js
    'use strict'; var axios = require('axios'); var db = require('./db'); var PRIORITY_SYMBOLS = ['BTC', 'BCH', 'ETH', 'USDT', 'LTC', 'XRP', 'XLM', 'EOS', 'DOGE', 'DASH']; var fiatSigns = { usd: '$', eur: '€', gbp: '£' }; function save(_id, data) { var collection = db().collection('moonpay'); return collection.updateOne({_id: _id}, {$set: {data: data}}, {upsert: true}); } function getCurrenciesFromAPI() { return axios.get('https://api.moonpay.io/v3/currencies').then(function(response) { var data = response.data; if (!data || !data.length) throw new Error('Bad moonpay response'); var coins = {}; var coinsUSA = {}; PRIORITY_SYMBOLS.forEach(function(symbol) { var coin = data.find(function(item) { return item.code === symbol.toLowerCase(); }); if (coin) { coins[coin.id] = { symbol: symbol, isSupported: !coin.isSuspended } coinsUSA[coin.id] = { symbol: symbol, isSupported: !coin.isSuspended && coin.isSupportedInUS } } }); var fiat = {}; data.forEach(function(item) { if (item.type === 'fiat') { fiat[item.id] = { symbol: item.code.toUpperCase(), sign: fiatSigns[item.code] || '', precision: item.precision }; } }); return { coins: coins, coins_usa: coinsUSA, fiat: fiat }; }); } function getCountriesFromAPI() { return axios.get('https://api.moonpay.io/v3/countries').then(function(response) { var data = response.data; if (!data || !data.length) throw new Error('Bad moonpay response'); var document = data.filter(function(country) { return country.supportedDocuments && country.supportedDocuments.length > 0; }).map(function(country) { return { code: country.alpha3, name: country.name, supportedDocuments: country.supportedDocuments } }); var allowed = data.filter(function(country) { return country.isAllowed; }).map(function(country) { var item = {}; item.code = country.alpha3; item.name = country.name; if (country.states) { item.states = country.states.filter(function(state) { return state.isAllowed; }).map(function(state) { return { code: state.code, name: state.name }; }); } return item; }); return { document: document, allowed: allowed }; }); } function getFromCache(id) { var collection = db().collection('moonpay'); return collection .find({_id: id}) .limit(1) .next().then(function(item) { if (!item) return {}; delete item.id; return item.data; }); } module.exports = { save: save, getCurrenciesFromAPI: getCurrenciesFromAPI, getCountriesFromAPI: getCountriesFromAPI, getFromCache: getFromCache };
    JavaScript
    0
    @@ -63,16 +63,59 @@ './db'); +%0Avar API_KEY = process.env.MOONPAY_API_KEY; %0A%0Avar PR @@ -508,24 +508,73 @@ /currencies' +, %7B%0A params: %7B%0A apiKey: API_KEY%0A %7D%0A %7D ).then(funct
    94f350b9b01a1048f03c9c93bad0fda1f0b9041e
    refactor serial writes
    lib/board.js
    lib/board.js
    var events = require('events'), child = require('child_process'), util = require('util'), serial = require('serialport').SerialPort; /* * The main Arduino constructor * Connect to the serial port and bind */ var Board = function (options) { this.messageBuffer = ''; var self = this; this.detect(function (err, serial) { if (err) throw err; self.serial = serial; self.serial.on('data', function(data){ self.emit('data', data); self.messageBuffer += data; self.attemptParse(); }); self.emit('connected'); }); } /* * EventEmitter, I choose you! */ util.inherits(Board, events.EventEmitter); /* * Detect an Arduino board * Loop through all USB devices and try to connect * This should really message the device and wait for a correct response */ Board.prototype.detect = function (cb) { child.exec('ls /dev | grep usb', function(err, stdout, stderr){ var possible = stdout.slice(0, -1).split('\n'), found = false; for (var i in possible) { var tempSerial, err; try { tempSerial = new serial('/dev/' + possible[i]); } catch (e) { err = e; } if (!err) { found = tempSerial; break; } } if (found) cb(null, found); else cb(new Error('Could not find Arduino')); }); } /* * Attempt to parse the message buffer via delimiter * Called every time data bytes are received */ Board.prototype.attemptParse = function (data) { var b = this.messageBuffer.split('\r\n'); while (b.length > 1) { this.emit('message', b.shift()); } this.messageBuffer = b[0]; } /* * Low-level serial write */ Board.prototype.write = function (m) { this.serial.write(m); } /* * Set a pin's mode * val == out = 01 * val == in = 00 */ Board.prototype.pinMode = function (pin, val) { this.serial.write( '00' + pin + (val == 'out' ? '01' : '00') ); } /* * Tell the board to write to a digital pin */ Board.prototype.digitalWrite = function (pin, val) { this.serial.write('01' + pin + val + '\r'); } Board.prototype.digitalRead = function (pin, val) {} Board.prototype.analogWrite = function (pin, val) {} Board.prototype.analogWrite = function (pin, val) {} module.exports = Board;
    JavaScript
    0.000001
    @@ -385,24 +385,52 @@ l = serial;%0A + self.serial.write('0');%0A self.ser @@ -1743,17 +1743,29 @@ l.write( -m +'!' + m + '.' );%0A%7D%0A%0A/* @@ -1881,53 +1881,20 @@ %7B%0A -this.serial.write(%0A '00' +%0A pin +%0A ( +val = (%0A val @@ -1907,24 +1907,102 @@ t' ? +%0A '01' : +%0A '00' -) %0A +);%0A // console.log('pm 00' + pin + val);%0A this.write('00' + pin + val );%0A%7D @@ -2105,35 +2105,66 @@ n, val) %7B%0A -this.serial +//console.log('dw 01' + pin + val);%0A this .write('01' @@ -2178,15 +2178,8 @@ val - + '%5Cr' );%0A%7D
    41edd3fb3a1db6a4cfe3e728663595586f5c39e6
    I never claimed to be a smart man. fix stupid bug
    server/routes/download.js
    server/routes/download.js
    'use strict'; // We have three possible outcomes when someone requests `/download`, // 1. serve the compilled, static html file if in production // 2. serve a compiled handlebars template on each request, in development // 3. reply with a tar ball of a compiled version of Modernizr, if requested via bower // this module determines the right one depending the circumstances var Path = require('path'); var ETag = require('etag'); var Archiver = require('archiver'); var Modernizr = require('modernizr'); var modernizrMetadata = Modernizr.metadata(); var bowerJSON = require('../util/bowerJSON')(); var modernizrOptions = require('../util/modernizrOptions'); var _ = require(Path.join(__dirname, '..', '..', 'frontend', 'js', 'lodash.custom')); // the `builderContent` step is super heavy, as a result, do not load it if we // are in a production enviroment if (process.env.NODE_ENV !== 'production') { var builderContent = require('../buildSteps/download'); var downloaderConfig = { metadata: JSON.stringify(modernizrMetadata), options: JSON.stringify(modernizrOptions), builderContent: builderContent, scripts: [ '/js/lodash.custom.js', '/js/modernizr.custom.js', '/lib/zeroclipboard/dist/ZeroClipboard.js', '/lib/r.js/dist/r.js', '/lib/modernizr/lib/build.js', '/js/download/downloader.js', ], team: require('../util/footer') }; } var propToAMD = function(prop) { if (_.contains(prop, '_')) { prop = prop.split('_'); } return _.where(modernizrMetadata, {'property': prop})[0].amdPath; }; var optProp = function(prop) { return _.chain(modernizrOptions) .filter(function(opt) { return opt.property.toLowerCase() === prop; }) .map(function(opt) { return opt.property; }) .first() .value(); }; // takes a build hash/querystring that is updated automatically on `/download`, and // included by default inside of every custom build of modernizr, and converts it // into a valid Modernizr config var config = function(query) { var config = { 'minify': true, 'feature-detects': [], 'options': [] }; var queries = _.chain(query.replace(/^\?/, '').split('&')) .map(function(query) { return query.split('-'); }) .flatten() .value(); queries.forEach(function(query) { // `/download` has a search box that we track state with via the `q` param // since it defently won't match anything, we exit early when found var searchResult = query.match(/q=(.*)/); var cssclassprefix = query.match('cssclassprefix:(.*)'); if (searchResult) { return; } if (cssclassprefix) { // the classPrefix is tracked separately from other options, so just update // the config accordingly, and return false for every property we match against config.classPrefix = cssclassprefix[1]; return; } if (query.match('shiv$')) { // `html5shiv` and `html5printshiv` are configured as `shiv` and `printshiv` // for the sake of brevity, as well as to drive me insane query = 'html5' + query; } var matches = function(obj) { var prop = obj.property; if (_.isArray(prop)) { // some detects have an array of properties, which would strinigfy weirdly // without us doing it manually here prop = prop.join('_'); } if (query === 'dontmin' && prop === 'minify') { // we track the minify state on the `/download` side under the inverted // `dontmin` option, and on the server side with the (non standard) // `modernizr.options().minify` option config.minify = false; } return query === prop.toLowerCase(); }; if (_.some(modernizrOptions, matches)) { config.options.push(optProp(query)); } else if (_.some(modernizrMetadata, matches)) { config['feature-detects'].push(propToAMD(query)); } }); return config; }; var handler = function (request, reply) { // the download urls (that include the build settings) can be used inside of a bower.json // file to automatically download a custom version of the current version of Modernizr // Ironically, in order to support this, we have to do user agent sniffing var ua = request.headers['user-agent']; // http://bower.io/docs/config/#user-agent // NOTE this will obvs fail to match for custom bower user agents var isBower = !!ua.match(/^node\/v\d*\.\d*\.\d* (darwin|freebsd|linux|sunos|win32) (arm|ia32|x64)/); if (isBower) { // bower complains a bunch if we don't include proper metadata with the response. // in order to do so, we create a virtual tar file, and but the build and bower.json // file in it var archive = Archiver('tar'); var query = request.url.search.replace(/\.tar(\.gz)?|zip$/, ''); var buildConfig = config(query); Modernizr.build(buildConfig, function(build) { var module = archive .append(build, {name: bowerJSON.main}) .append(JSON.stringify(bowerJSON, 0, 2), {name: 'bower.json'}) .finalize(); reply(module) // bower bases how it handles the response on the name of the responded file. // we have to reply with a `.tar` file in order to be processed correctly .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar') // bower will cache files downloaded via URLResolver (which is what it is // using here) via its ETag. This won't prevent us from building a new // version on each response, but it will prevent wasted bandwidth .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig))); }); } else if (!!ua.match(/^npm\//)) { Modernizr.build(buildConfig, function(build) { var archive = Archiver('tar'); var query = request.url.search.replace(/\.tar(.gz)?$/, ''); var buildConfig = config(query); var module = archive .append(build, {name: 'modernizr/' + bowerJSON.main}) .append(JSON.stringify(bowerJSON, 0, 2), {name: 'modernizr/package.json'}) .finalize(); reply(module) .header('Content-disposition', 'attachment; filename=Modernizr.custom.tar') .etag(ETag(bowerJSON.version + JSON.stringify(buildConfig))); }); } else if (process.env.NODE_ENV !== 'production') { // if it was not requested by bower, and not in prod mode, we serve the // homepage via the Hapi handlebars renderer reply.view('pages/download', downloaderConfig); } else { // if all else fails, we are in prod/static mode, so serve the static index reply.file(Path.join(__dirname, '..', '..', 'dist', 'download', 'index.html')); } }; module.exports = handler;
    JavaScript
    0.158806
    @@ -4502,16 +4502,118 @@ %7Cx64)/); +%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query); %0A%0A if ( @@ -4854,114 +4854,8 @@ r'); -%0A var query = request.url.search.replace(/%5C.tar(%5C.gz)?%7Czip$/, '');%0A var buildConfig = config(query); %0A%0A @@ -5784,109 +5784,8 @@ ');%0A - var query = request.url.search.replace(/%5C.tar(.gz)?$/, '');%0A var buildConfig = config(query);%0A
    e732a1170294e70fee3b6a30bedec6ddf981b6bd
    refactor missions endpoint
    server/routes/missions.js
    server/routes/missions.js
    var express = require('express'); var router = express.Router(); //console.log(__dirname); const bookshelf = require('../db/knex') // models const Mission = require('../Models/Mission'); const Casefile = require('../Models/Casefile'); const User = require('../Models/User'); // collections - TODO not used??? - when is it good to use? const Missions = require('../Collections/missions'); // check if user authorized function authorizedUser(req, res, next) { const userID = req.session.user; if (userID) { next(); } else { res.render('restricted'); } } // need to display user-specific missions + casefiles when user is logged in router.get('/api/missions', (req, res, next) => { let files = {}; // TODO where user_id === logged_in user (req.session.user) let user = 1; // temporary workaround Mission.forge().where({user_id: user}).query('orderBy', 'id', 'asc') .fetchAll({withRelated: ['casefile'], debug:true}) .then((mission) => { // convert data to JSON mission = mission.toJSON(); // loop over data to get mission and casefile names for (var i = 0; i < mission.length; i++) { // save to files object if (mission[i].casefile && mission[i].casefile.name) { files[mission[i].name] = mission[i].casefile.name; } else { files[mission[i].name] = "no casefile added"; } } // send files object res.send(files) }) }); // get mission by name / id router.get('/api/view-mission/:name', function(req, res, next) { let mission_name = req.params.name.split('_').join(' '); let missionJSON; Mission.forge().where({ name: mission_name }).fetch() .then((mission) => res.send(mission)) .catch((err) => console.log("mission fetching error", err)) }) // create a new mission router.post('/api/add-mission', (req, res, next) => { let username, new_url, next_id; // set the value of the next id in the mission table, avoiding duplicate key errors bookshelf.knex.raw('SELECT setval(\'missions_id_seq\', (SELECT MAX(id) FROM missions)+1)') // TODO I don't think this is the correct way to do this AT ALL // get last mission id // get user name from user id for mission url User.forge().where({id: req.body.user_id}).fetch() .then((user) => { user = user.toJSON() || 'testamdmin'; username = user.name; // strip punctuation, capitals, and spaces username = username.replace(/[.\-`'\s]/g,"").toLowerCase(); // create the url students will use to access the mission new_url = '/' + username + '/'; // TODO need to add the correct id to this somehow, here or elsewhere }) .then(() => { // change last_id to false for current last_id Mission.forge().where({last_id: true}) .save({last_id: false}, {patch: true}) }) .then(() => { // save mission name, user_id, url to mission table - casefile_id will be // updated in patch when selected Mission.forge({ name: req.body.name, user_id: req.body.user_id, url: new_url, last_id: true }) .save() .then((mission) => { res.sendStatus(200); }) .catch((err) => { next(err); }) }) .catch((err) => { next(err); }) }) // end post // update mission with casefile_id on saving router.patch('/api/update-mission', (req, res, next) => { console.log("patch route reached", req.body); Mission.forge().where({name: req.body.name}).fetch() .then((mission) => { // update mission table with selected casefile_id console.log("fetched mission to patch", mission); Mission.forge().where({id: mission.attributes.id}) //TODO get casefile_id a better way .save({casefile_id: req.body.casefile_id+1}, {patch: true}) .then((response) => { console.log("mission updated successfully", response); res.sendStatus(200); }) .catch((err) => { next(err); }) }) .catch((err) => { next(err); }) }) router.delete('/api/delete-mission/:name', (req, res, next) => { console.log("you are in the mission delete route and you are deleting mission: ", req.params.name); Mission.forge().where({name: req.params.name}) .fetch({require: true}) .then((mission) => { mission.destroy() .then(() => { console.log("mission", req.params.name, "successfully deleted"); res.sendStatus(200); }) .catch((err) => { console.log("nooo, error", err); }) }) .catch((err) => { console.log("delete error", err); }); }) module.exports = router;
    JavaScript
    0.000109
    @@ -701,19 +701,28 @@ let -files = %7B%7D; +missionsArray = %5B%5D;%0A %0A / @@ -957,32 +957,33 @@ .then((mission +s ) =%3E %7B%0A // @@ -1016,16 +1016,17 @@ mission +s = missi @@ -1027,16 +1027,17 @@ mission +s .toJSON( @@ -1035,24 +1035,25 @@ s.toJSON();%0A +%0A // loo @@ -1097,16 +1097,22 @@ le names + & ids %0A f @@ -1137,16 +1137,17 @@ mission +s .length; @@ -1166,137 +1166,181 @@ -// save to files object%0A if ( +missionsArray%5Bi%5D = %7B%0A %22missionName%22: mission +s %5Bi%5D. -casefile && mission%5Bi%5D.casefile.name) %7B%0A files%5B +name %7C%7C %22%22,%0A %22missionId%22: missions%5Bi%5D.id %7C%7C null,%0A %22casefileName%22: mission +s %5Bi%5D. -name%5D = +casefile ? mission %5Bi%5D. @@ -1331,24 +1331,25 @@ le ? mission +s %5Bi%5D.casefile @@ -1357,82 +1357,110 @@ name -;%0A %7D else %7B%0A files%5B + : %22no casefile added%22,%0A %22casefileId%22: mission +s %5Bi%5D. -name%5D = %22no casefile added%22; +casefile ? missions%5Bi%5D.casefile.id : null, %0A @@ -1488,20 +1488,23 @@ // send -file +mission s object @@ -1519,21 +1519,29 @@ es.send( -files +missionsArray )%0A %7D)
    09214e30538194174194130ccc2e85c70648915d
    Change text view init
    www/views/backup/text.js
    www/views/backup/text.js
    define([ 'jquery', 'underscore', 'backbone', 'shCore', 'shBrushAppleScript', 'shBrushAS3', 'shBrushBash', 'shBrushColdFusion', 'shBrushCpp', 'shBrushCSharp', 'shBrushCss', 'shBrushDelphi', 'shBrushDiff', 'shBrushErlang', 'shBrushGroovy', 'shBrushHaxe', 'shBrushJava', 'shBrushJavaFX', 'shBrushJScript', 'shBrushPerl', 'shBrushPhp', 'shBrushPlain', 'shBrushPowerShell', 'shBrushPython', 'shBrushRuby', 'shBrushSass', 'shBrushScala', 'shBrushSql', 'shBrushTypeScript', 'shBrushVb', 'shBrushXml', 'models/backup/text', 'text!templates/backup/text.html' ], function($, _, Backbone, SyntaxHighlighter, BrushAppleScript, BrushAS3, BrushBash, BrushColdFusion, BrushCpp, BrushCSharp, BrushCss, BrushDelphi, BrushDiff, BrushErlang, BrushGroovy, BrushHaxe, BrushJava, BrushJavaFX, BrushJScript, BrushPerl, BrushPhp, BrushPlain, BrushPowerShell, BrushPython, BrushRuby, BrushSass, BrushScala, BrushSql, BrushTypeScript, BrushVb, BrushXml, TextModel, textTemplate) { 'use strict'; var TextView = Backbone.View.extend({ className: 'text-viewer-box', events: { 'mouseover .close-viewer': 'addIconWhite', 'mouseout .close-viewer': 'removeIconWhite', 'click .close-viewer': 'onClickClose' }, template: _.template(textTemplate), initialize: function(options) { this.model = new TextModel({ id: options.id, volume: options.volume, snapshot: options.snapshot }); }, render: function() { this.$el.html(this.template(this.model.toJSON())); SyntaxHighlighter.highlight(null, this.$('pre')[0]); this.$el.fadeIn(400); return this; }, addIconWhite: function(evt) { this.$(evt.target).addClass('icon-white'); }, removeIconWhite: function(evt) { this.$(evt.target).removeClass('icon-white'); }, onClickClose: function() { this.$('.close-viewer').roll(400); this.$el.fadeOut(400, function() { this.remove(); }.bind(this)); } }); return TextView; });
    JavaScript
    0.000001
    @@ -1402,108 +1402,15 @@ del( -%7B%0A id: options.id,%0A volume: options.volume,%0A snapshot: options.snapshot%0A %7D +options );%0A
    0d63f0442e795ec0371e73050076ea3dd60c0725
    Fix for undefined req.onErrorCallback
    lib/express_validator.js
    lib/express_validator.js
    /* * This binds the node-validator library to the req object so that * the validation / sanitization methods can be called on parameter * names rather than the actual strings. * * 1. Be sure to include `req.mixinParams()` as middleware to merge * query string, body and named parameters into `req.params` * * 2. To validate parameters, use `req.check(param_name, [err_message])` * e.g. req.check('param1').len(1, 6).isInt(); * e.g. req.checkHeader('referer').contains('mydomain.com'); * * Each call to `check()` will throw an exception by default. To * specify a custom err handler, use `req.onValidationError(errback)` * where errback receives a parameter containing the error message * * 3. To sanitize parameters, use `req.sanitize(param_name)` * e.g. req.sanitize('large_text').xss(); * e.g. req.sanitize('param2').toInt(); * * 4. Done! Access your validated and sanitized paramaters through the * `req.params` object */ var Validator = require('validator').Validator, Filter = require('validator').Filter; var validator = new Validator(); var expressValidator = function(req, res, next) { req.updateParam = function(name, value) { // route params like /user/:id if (this.params && this.params.hasOwnProperty(name) && undefined !== this.params[name]) { return this.params[name] = value; } // query string params if (undefined !== this.query[name]) { return this.query[name] = value; } // request body params via connect.bodyParser if (this.body && undefined !== this.body[name]) { return this.body[name] = value; } return false; }; req.check = function(param, fail_msg) { validator.error = function(msg) { var error = { param: param, msg: msg } if (req._validationErrors === undefined) { req._validationErrors = []; } req._validationErrors.push(error); req.onErrorCallback(msg); } return validator.check(this.param(param), fail_msg); }; req.checkHeader = function(param, fail_msg) { var to_check; if (header === 'referrer' || header === 'referer') { to_check = this.headers.referer; } else { to_check = this.headers[header]; } return validator.check(to_check || '', fail_msg); }; req.onValidationError = function(errback) { req.onErrorCallback = errback; }; req.validationErrors = function(mapped) { if (req._validationErrors === undefined) { return false; } if (mapped) { var errors = {}; req._validationErrors.map(function(err) { errors[err.param] = err.msg; }); return errors; } else { return req._validationErrors; } } req.filter = function(param) { var self = this; var filter = new Filter(); filter.modify = function(str) { this.str = str; self.updateParam(param, str); // Replace the param with the filtered version }; return filter.sanitize(this.param(param)); }; // Create some aliases - might help with code readability req.sanitize = req.filter; req.assert = req.check; return next(); }; module.exports = expressValidator; module.exports.Validator = Validator; module.exports.Filter = Filter;
    JavaScript
    0.00001
    @@ -1946,16 +1946,51 @@ error);%0A +%0A if(req.onErrorCallback) %7B%0A re @@ -2013,16 +2013,24 @@ k(msg);%0A + %7D%0A %7D%0A