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
|
---|---|---|---|---|---|---|---|
79ae4607f562cf2ab1e7d1a936c2ed78c45b2eeb | Fix issues | polyocat.js | polyocat.js | async function main() {
const REGEXP = {
"/ year": /\/ year$/,
"/ month": /\/ month$/,
"N open": /^([\d,]+) Open$/,
"N closed": /^([\d,]+) Closed$/,
"N files": /^([\d,]+) files?$/,
"N forks": /^([\d,]+) forks?$/,
"N stars": /^([\d,]+) stars?$/,
"N comments": /^([\d,]+) comments?$/,
"N remaining": /^([\d,]+) remaining$/,
"N languages": /^([\d,]+) languages?$/,
"N applications": /^([\d,]+) applications?$/,
"N repositories": /^([\d,]+) repositories?$/,
"N stars today": /^([\d,]+) stars today$/,
"N stars this week": /^([\d,]+) stars this week$/,
"N stars this month": /^([\d,]+) stars this month$/,
"N contributions": /^([\d,]+) contributions?$/,
"N contributions in the last year": /^([\d,]+) contributions in the last year$/,
"month day": /^(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d+)$/,
"on month day": /^on (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d+)$/,
"on month day, year": /^on (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d+), (\d{4})$/,
"View USER on GitHub": /View (\w+) on GitHub/,
"Your next charge will be on date": /Your next charge will be on (\d{4}-\d{2}-\d{2})./
}
let page = where()
let lang = language()
let dict = await translation(lang)
let observer = new MutationObserver(mutations => {
mutations
.filter(mutation =>
(mutation.type === 'childList' && mutation.addedNodes.length) ||
(mutation.type === 'attributes' && mutation.attributeName === 'placeholder')
)
.forEach(mutation => translate(mutation.target))
})
observer.observe(document.body, {
attributes: true,
childList: true,
subtree: true
})
translateTitle()
translate(document.body)
function find(str) {
if (page && dict[page][str]) return ` ${dict[page][str]} `
if (dict.global[str]) return ` ${dict.global[str]} `
for (let key in REGEXP) {
let reg = REGEXP[key]
if (reg.test(str)) {
str = str
.replace(reg, dict.regexp[key])
.replace(/(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)/, (match, p1) => dict.global.m2n[p1])
return ` ${str} `
}
}
return ''
}
function where() {
if (location.host === 'gist.github.com') return 'gist'
let pathname = location.pathname
if (pathname === '/' || pathname === '/dashboard') return 'homepage'
if (pathname === '/new') return 'new'
if (pathname === '/trending') return 'trending'
if (/^\/watching/.test(pathname)) return 'watching'
if (/^\/notifications/.test(pathname)) return 'notifications'
if (/^\/settings\/.+$/.test(pathname)) return 'settings'
if (/^\/\w+\/?$/.test(pathname)) return 'profile'
if (/^\/\w+\/.+$/.test(pathname)) return 'repository'
}
function language() {
return localStorage.getItem('polyocat-lang') || navigator.language || navigator.languages[0]
}
async function translation(lang) {
let url = chrome.extension.getURL(`translations/${lang}.json`)
let res = await fetch(url)
return await res.json()
}
function translate(node) {
translateNode(node)
if (node.id === 'readme' || node.id === 'files' || /personal-access-tokens-group/.test(node.className)) return
if (node.className === 'file') return translate(node.firstElementChild)
node.childNodes.forEach(translate)
}
function translateNode(node) {
if (node.nodeType === Node.TEXT_NODE) return translateTextNode(node)
if (node.nodeType === Node.ELEMENT_NODE) return translateElement(node)
}
function translateTitle() {
let title = document.title.trim()
let value = find(title)
if (value) document.title = value
}
function translateTextNode(node) {
if (!node || node.nodeValue == null) return
let text = node.nodeValue.replace(/[\n\s]+/g, ' ').trim()
let tran = find(text)
if (tran) node.nodeValue = tran
}
function translateElement(elem) {
if ((elem.tagName === 'INPUT' || elem.tagName === 'TEXTAREA') && elem.placeholder) {
elem.placeholder = find(elem.placeholder) || elem.placeholder
}
if (elem.tagName === 'INPUT' && elem.type === 'submit') {
elem.value = find(elem.value) || elem.value
}
if (elem.tagName === 'OPTGROUP' && elem.label) {
elem.label = find(elem.label) || elem.label
}
if ((elem.tagName === 'RELATIVE-TIME' || elem.tagName === 'TIME-AGO') && elem.innerText) {
elem.innerText = elem.innerText.replace(
/(\d+|a|an) (day|days|hour|hours|minute|minutes|second|seconds|month|months|year|years) (ago)/,
(match, p1, p2, p3) => `${find(p1) || p1} ${find(p2).trim()}${find(p3).trim()}`
)
}
if (elem.hasAttribute('aria-label')) {
let label = find(elem.getAttribute('aria-label'))
if (label) elem.setAttribute('aria-label', label)
}
}
console.log(page, lang, dict)
}
main() | JavaScript | 0.000002 | @@ -494,12 +494,17 @@
itor
+(?:y%7C
ies
-?
+)
$/,%0A
@@ -1717,27 +1717,8 @@
%7D)%0A%0A
- translateTitle()%0A
tr
@@ -3563,147 +3563,8 @@
%0A %7D
-%0A%0A function translateTitle() %7B%0A let title = document.title.trim()%0A let value = find(title)%0A if (value) document.title = value%0A %7D
%0A %0A
@@ -3909,21 +3909,20 @@
%7B%0A
-e
le
-m.
+t
placehol
@@ -3949,25 +3949,59 @@
eholder)
- %7C%7C elem.
+%0A if (placeholder) elem.placeholder =
placehol
@@ -4079,21 +4079,20 @@
%7B%0A
-e
le
-m.
+t
value =
@@ -4107,25 +4107,47 @@
m.value)
- %7C%7C elem.
+%0A if (value) elem.value =
value%0A
@@ -4210,21 +4210,20 @@
%7B%0A
-e
le
-m.
+t
label =
@@ -4238,25 +4238,47 @@
m.label)
- %7C%7C elem.
+%0A if (label) elem.label =
label%0A
|
b6688a349c558d5e723513fe27045206c0e5480c | bring Vector export up to speed with recent changes | lib/vector.js | lib/vector.js | /**
* Vector: One dimensional array.
* Extends upon the Array datatype to do some serious number crunching.
* @author Fredrick Galoso
*/
Array.prototype.asc = function(a, b) {
return a - b;
};
Array.prototype.desc = function(a, b) {
return b - a;
};
/* Returns a clone of the Vector object */
Array.prototype.clone = function(callback) {
var object = (this instanceof Array) ? [] : {};
for (i in this) {
if (i === 'clone') continue;
if (this[i] && typeof this[i] === 'object') {
object[i] = this[i].clone();
} else object[i] = this[i]
}
if (callback)
return callback(object);
else
return object;
};
/* Returns a copy of the values in a Vector object */
Array.prototype.copy = function(callback) {
var values = this.slice(0);
if (callback)
return callback(values);
else
return values;
}
Array.prototype.sum = function(callback) {
for (var i = 0, sum = 0.0; i < this.length;) {
sum += this[i++];
}
if (callback)
return callback(sum);
else
return sum;
};
Array.prototype.mean = function(callback) {
var mean = this.sum() / this.length;
if (callback)
return callback(mean);
else
return mean;
};
Array.prototype.median = function(callback) {
var buffer = this.copy()
buffer.sort(this.asc);
var median = (this.length % 2 === 0) ?
(buffer[this.length / 2 - 1] + buffer[this.length / 2]) / 2 :
buffer[parseInt(this.length / 2)];
if (callback)
return callback(median);
else
return median;
};
Array.prototype.mode = function(callback) {
var map = {};
var count = 1;
var modes = [this[0]];
for (var i = 0; i < this.length; i++) {
var e = this[i];
if (map[e] == null)
map[e] = 1;
else
map[e]++;
if (map[e] > count) {
modes = [e];
count = map[e];
} else if (map[e] == count) {
modes.push(e);
count = map[e];
}
}
if (modes.length === 1)
modes = modes[0];
if (callback)
return callback(modes);
else
return modes;
}
Array.prototype.range = function(callback) {
var range = this.max() - this.min();
if (callback)
return callback(range);
else
return range;
}
Array.prototype.variance = function(callback) {
for (var i = 0, variance = 0.0; i < this.length;) {
variance += Math.pow((this[i++] - this.mean()), 2);
}
variance /= this.length;
if (callback)
return callback(variance);
else
return variance;
};
Array.prototype.stdev = function(percentile, callback) {
var stdev = 0.0;
if (!percentile)
stdev = Math.sqrt(this.variance());
else
return this.density(percentile).stdev();
if (callback)
return callback(stdev);
else
return stdev;
};
/* Returns the frequency of an element in the array */
Array.prototype.frequency = function(element, callback) {
var freq = 0;
/*TODO if element is not given, display frequency distribution*/
if (this.indexOf(element) !== -1) {
var buffer = this.copy()
buffer.sort(this.asc);
freq = buffer.lastIndexOf(element) - buffer.indexOf(element) + 1;
}
if (callback)
return callback(freq);
else
return freq;
};
/* Returns an element from an array given a percentile */
Array.prototype.percentile = function(percent, callback) {
var buffer = this.copy()
buffer.sort(this.asc);
var percentile = buffer[0];
if (percent > 0)
percentile = buffer[Math.ceil(this.length * percent) - 1];
if (callback)
return callback(percentile);
else
return percentile;
};
/**
* Returns a Vector (Array) of values within a given percent density
*
* Example:
* this.density(0.50); would return an array consisting of the values
* between the 25% and 75% percentile of the population
*/
Array.prototype.density = function(percent, callback) {
var slice;
var buffer = this.copy()
buffer.sort(this.asc);
if (percent == 1)
return buffer;
else {
var begin = Math.round(this.length * (0.5 - percent / 2) - 1);
var end = Math.round(this.length * (0.5 + percent / 2) - 1);
slice = buffer.slice(begin, end);
}
if (callback)
return callback(slice);
else
return slice;
};
/**
* Returns an Object containing the distribution of values within the array
* @param format Override distribution format with Percent Distribution. Default: Raw count
*/
Array.prototype.distribution = function(format, callback) {
var buffer = this.copy()
buffer.sort(this.asc);
var map = function (array, index, format, distribution) {
if (index === array.length)
return distribution;
else {
distribution[array[index]] = (format === 'relative') ?
array.frequency(array[index]) / array.length : array.frequency(array[index]);
return map(array, array.lastIndexOf(array[index]) + 1, format, distribution);
}
}
var result = (format === 'relative') ? map(buffer, 0, 'relative', {}) : map(buffer, 0, 'raw', {});
if (callback)
return callback(result);
else
return result;
};
Array.prototype.quantile = function(quantity, callback) {
var buffer = this.copy()
buffer.sort(this.asc);
var increment = 1.0 / quantity;
var results = [];
if (quantity > this.length)
throw new RangeError('Subset quantity is greater than the Vector length');
for (var i = increment; i < 1; i += increment) {
var index = Math.round(buffer.length * i) - 1;
if (index < buffer.length - 1)
results.push(buffer[index]);
}
if (callback)
return callback(results);
else
return results;
};
Array.prototype.max = function(callback) {
var max = Math.max.apply({},this);
if (callback)
return callback(max);
else
return max;
};
Array.prototype.min = function(callback) {
var min = Math.min.apply({},this);
if (callback)
return callback(min);
else
return min;
};
exports.Vector = Array;
| JavaScript | 0 | @@ -6289,15 +6289,25 @@
orts
-.Vector
+ = module.exports
= A
@@ -6312,9 +6312,8 @@
Array;%0A
-%0A
|
e2cfa4444191f2e790f0ade6671578e0172886f7 | change sql and fixed minor bugs | libs/stats.js | libs/stats.js | var pg = require('pg');
var sql = new pg.Client('postgres://netscout:dbadmin@localhost/pgsql_stealth_db');
var isSqlReady = true;
var moment = require('moment');
var reg_ex = {
ipv4: new RegExp(/^([1-9][0-9]{0,2})\.([0-9]{1,3}\.){2}([0-9]{1,3})$/i),
community_id: new RegExp(/^(0)\.([0-9]{1,3}\.){2}([0-9]{1,3})$/i),
hour: new RegExp(/^([1-9]|10|11|12)\s?(am|pm)/i)
}
sql.on('drain', sql.end.bind(sql)); //disconnect client when all queries are finished
sql.on('error', function(err) {
isSqlReady = false;
console.log('SQL ERROR: ', err);
});
sql.connect();
function queryServerStats(params, cb) {
var query;
if (typeof params === 'function') return params(new Error('Missing params'));
//if (!isSqlReady) return cb(new Error('SQL Server is not connected'));
buildServerStatsQuery(params, cb);
}
function buildServerStatsQuery(params, cb) {
/* params: [ipv4|community name] [date] [hour] [Timezone] */
var query;
var temp, name, ip, date, hour, tz = undefined;
var defaultQuery = "select \
ksi.targettime, ksi.toserveroctets, ksi.fromserveroctet, ksi.clientaddress, ksi.activesessions, comm.name \
inner join lu_communities as comm on ksi.clientaddress = comm.clientaddress \
where ksi.clientaddress != '0.0.0.0' \
order by ksi.targettime desc \
limit 5";
if (!params || params.length <= 0) query = defaultQuery;
else {
console.log('1 PARAMS: ', params)
ip = params.shift();
date = params.shift();
/* process date argument */
if (date) {
console.log('2 DATE: ', date)
var matches, t, h, x, fdate;
fdate = moment(new Date(date)).format('YYYY-MM-DD');
x = parseInt(new Date().getFullYear()) - parseInt(fdate.split('-').shift()); //get the formatted year
if (x > 2) fdate = moment(new Date(date)).year(new Date().getFullYear()).format('YYYY-MM-DD'); //if the user didn't provide a year, reformat with the current year as default
console.log('3 FDATE: ', fdate)
if (hour = params.shift()) {
matches = hour.match(reg_ex.hour);
if (hour) {
matches.shift() //get rid of the whole string
h = parseInt(matches.shift());
t = matches.shift().toLowerCase().trim();
if (!isNaN(h) && t === 'pm' && h <= 12) h += 12;
hour = moment({hour: h, minute: 0}).format('HH:mm:ss');
console.log('4 HOUR: ', hour)
}
}
if (tz = params.shift()) tz = '(' + tz.toUpperCase() + ')';
}
/* process first argument, should be: ip or community name */
if (ip) {
if (reg_ex.ipv4.test(ip) || reg_ex.community_id.test(ip)) { //is IP address or community id in the form of ipv4
ip = ip;
console.log('6 IP: ', ip)
getRecords(ip, date, hour, cb);
}
else { //it is a community name
name = ip.toUpperCase();
console.log('7 NAME: ', name)
sql.query("select clientaddress, name from lu_communities where name like '%"+name+"%' limit 1")
.on('row', function(row, results) { results.addRow(row); })
.on('end', function(results) {
ip = results.rows[0].clientaddress;
getRecords(ip, date, hour, cb);
})
.on('error', function(err) { return cb(err); })
}
}
}
function getRecords(ip, date, hour, cb) {
var query = "select \
ksi.targettime, ksi.toserveroctets, ksi.fromserveroctet, ksi.clientaddress, ksi.activesessions, comm.name \
inner join lu_communities as comm on ksi.clientaddress = comm.clientaddress \
where ksi.clientaddress != '0.0.0.0' \
and ksi.clientaddress = '" + ip + "' \
and ksi.targettime like '" + date + " " + hour + "%' \
order by ksi.targettime desc \
limit 5";
console.log('5 QUERY: ', query)
sql.query(query)
.on('row', function(row, results) { results.addRow(row); })
.on('end', function(results) { return cb(null, results); })
.on('error', function(err) { return cb(err); });
}
}
module.exports = {
queryServerStats: queryServerStats
}
| JavaScript | 0 | @@ -369,16 +369,18 @@
)/i)%0A%7D%0A%0A
+//
sql.on('
@@ -457,16 +457,16 @@
inished%0A
-
sql.on('
@@ -1096,32 +1096,33 @@
.fromserveroctet
+s
, ksi.clientaddr
@@ -1150,32 +1150,73 @@
ns, comm.name %5C%0A
+ from ksi_hourly as ksi %5C%0A
@@ -2525,16 +2525,18 @@
HH:mm:ss
+ZZ
');%0A
@@ -2957,32 +2957,33 @@
getRecords(ip,
+f
date, hour, cb);
@@ -3395,32 +3395,33 @@
getRecords(ip,
+f
date, hour, cb);
@@ -3705,32 +3705,71 @@
ns, comm.name %5C%0A
+ from ksi_hourly as ksi %5C%0A
in
@@ -3983,20 +3983,17 @@
gettime
-like
+=
'%22 + da
@@ -4011,17 +4011,16 @@
hour + %22
-%25
' %5C%0A
|
3d47b8a0206b5ba2ad505f2e8750fb6f100b3f0b | Add jake watch task | Jakefile.js | Jakefile.js | var build = require('./build/build.js'),
lint = require('./build/hint.js'),
fs = require('fs');
var COPYRIGHT = fs.readFileSync('src/copyright.js', 'utf8');
desc('Check Raphael Layer 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('\t No errors found.');
}
});
desc('Combine and compress Raphael Layer source files');
task('build', ['lint'], function(compsBase32, buildName) {
var pathPart = 'dist/rlayer' + (buildName ? '-' + buildName : ''),
srcPath = pathPart + '.js',
path = pathPart + '.min.js';
var files = build.getFiles(compsBase32);
console.log('Concatenating ' + files.length + ' files...');
var content = build.combineFiles(files);
var oldSrc = build.load(srcPath),
newSrc = COPYRIGHT + content,
srcDelta = build.getSizeDelta(newSrc, oldSrc);
console.log('\tUncompressed size: ' + newSrc.length + ' bytes (' + srcDelta + ')');
if(newSrc == oldSrc) {
console.log('\tNo changes.');
} else {
build.save(srcPath, newSrc);
console.log('\tSaved to ' + srcPath);
}
console.log('Compressing...');
var oldCompressed = build.load(path),
newCompressed = COPYRIGHT + build.uglify(content),
delta = build.getSizeDelta(newCompressed, oldCompressed);
console.log('\tCompressed size: ' + newCompressed.length + ' bytes (' + delta + ')');
if(newCompressed === oldCompressed) {
console.log('\tNo changes.');
} else {
build.save(path, newCompressed);
console.log('\tSaved to ' + path);
}
});
task('default', ['build']);
| JavaScript | 0.000002 | @@ -1668,16 +1668,168 @@
%09%7D%0A%7D);%0A%0A
+desc('Watch src directory and build on any changes');%0AwatchTask(%5B'build'%5D, function () %7B%0A this.watchFiles.include(%5B%0A './src/**/*.js'%0A %5D);%0A%7D);%0A%0A
task('de
|
65ff5b5319b595a962ff710959c8fd0a225027fc | fix datables in ranking | games/azureStar-new/ranking.js | games/azureStar-new/ranking.js | function RankingOnline() {
Parse.initialize("L2h9j8kembYZqb5zFNrlw3yV2R7dgxVgeb0s5jq4", "ZjngB69wiAeqYygsEukF45ahWfa5tF9XtcLWcZBj");
this.ipAddress = "unknown";
this.country = "World";
}
RankingOnline.prototype = {
enviar: function (nome) {
var Score = Parse.Object.extend("Score");
var score = new Score();
score.save({pontuacao: pontuacao, jogador: nome, pais: this.country}).then(function(object) {
swal("Thanks " + nome + "!", "Your score was saved in our ranking!", "success");
});
this.listar();
},
listar: function () {
var Score = Parse.Object.extend("Score");
var query = new Parse.Query(Score);
query.descending("pontuacao");
query.find({
success: function(results) {
var table = document.getElementById("azureRanking").tBodies[0];
while(table.rows.length > 0) {
table.deleteRow(0);
}
for (var i = 0; i < results.length; i++) {
var object = results[i];
adicionarNoRanking({
posicao: i + 1,
nome: object.get('jogador'),
pontos: object.get('pontuacao'),
data: object.createdAt.toLocaleDateString('pt-BR'),
pais: object.get('pais')
});
}
$('#azureRanking').DataTable({searching: false, lengthChange: false});
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
},
connected: function () {
var Conexao = Parse.Object.extend('Conexao');
var conexao = new Conexao();
conexao.save({ip: this.ipAddress, country: this.country});
},
ip: function (json ){
this.ipAddress = json.ip || this.ip;
this.country = json.country || this.country;
}
}; | JavaScript | 0.000016 | @@ -1173,19 +1173,16 @@
%09%09 %7D%0A
-
%09%09%09$('#a
@@ -1206,16 +1206,32 @@
aTable(%7B
+retrieve: true,
searchin
|
a798aca5d2b9c72878595b35dde2c22a66cd2af8 | update Syncing storybook entry | stories/containers/syncing.stories.js | stories/containers/syncing.stories.js | import React from 'react'
import { storiesOf } from '@storybook/react'
import { linkTo } from '@storybook/addon-links'
import { State, Store } from '@sambego/storybook-state'
import { Modal } from 'components/UI'
import { Syncing } from 'components/Syncing'
import { boolean, number, select } from '@storybook/addon-knobs'
import { Window } from '../helpers'
const store = new Store({
address: '2MxZ2z7AodL6gxEgwL5tkq2imDBhkBMq2Jc',
blockHeight: 123123,
neutrinoBlockHeight: 1000,
neutrinoCfilterHeight: 100,
isLoading: false,
})
const setIsWalletOpen = () => ({})
const showNotification = () => ({})
storiesOf('Containers.Syncing', module)
.addParameters({ info: { disable: true } })
.addDecorator(story => <Window>{story()}</Window>)
.addDecorator(story => (
<Modal hasHeader onClose={linkTo('Containers.Home', 'Home')} pb={0} px={0}>
{story()}
</Modal>
))
.add('Syncing', () => {
const hasSynced = boolean('Has synced', false)
const syncPercentage = number('Sync Percentage', 30)
const syncStatus = select('Sync Status', ['waiting', 'in-progress', 'complete'], 'in-progress')
return (
<State store={store}>
{state => (
<Syncing
// State
address={state.address}
blockHeight={state.blockHeight}
hasSynced={hasSynced}
isLoading={state.isLoading}
neutrinoBlockHeight={state.neutrinoBlockHeight}
neutrinoCfilterHeight={state.neutrinoCfilterHeight}
setIsWalletOpen={setIsWalletOpen}
showNotification={showNotification}
// Dispatch
syncPercentage={syncPercentage}
syncStatus={syncStatus}
/>
)}
</State>
)
})
| JavaScript | 0.999991 | @@ -116,64 +116,8 @@
ks'%0A
-import %7B State, Store %7D from '@sambego/storybook-state'%0A
impo
@@ -160,18 +160,16 @@
port
- %7B
Syncing
%7D f
@@ -164,18 +164,16 @@
Syncing
- %7D
from 'c
@@ -269,216 +269,134 @@
t %7B
-Window %7D from '../helpers'%0A%0Aconst store = new Store(%7B%0A address: '2MxZ2z7AodL6gxEgwL5tkq2imDBhkBMq2Jc',%0A blockHeight: 123123,%0A neutrinoBlockHeight: 1000,%0A neutrinoCfilterHeight: 100,%0A isLoading: false,%0A%7D)
+neutrinoSelectors %7D from 'reducers/neutrino'%0Aimport %7B Provider, store %7D from '../Provider'%0Aimport %7B Window %7D from '../helpers'
%0A%0Aco
@@ -604,16 +604,71 @@
indow%3E)%0A
+ .addDecorator(story =%3E %3CProvider story=%7Bstory()%7D /%3E)%0A
.addDe
@@ -826,16 +826,51 @@
() =%3E %7B%0A
+ const state = store.getState()%0A
cons
@@ -1077,75 +1077,161 @@
-return (%0A %3CState store=%7Bstore%7D%3E%0A %7Bstate =%3E (%0A
+const recoveryPercentage = number('Recovery Percentage', 30)%0A const network = select('Network', %5B'mainnet', 'testnet'%5D, 'mainnet')%0A return (%0A
-
%3CSyn
@@ -1247,61 +1247,54 @@
- // State%0A address=%7Bstate.address%7D%0A
+address=%222MxZ2z7AodL6gxEgwL5tkq2imDBhkBMq2Jc%22%0A
@@ -1310,21 +1310,33 @@
Height=%7B
-state
+neutrinoSelectors
.blockHe
@@ -1331,32 +1331,39 @@
tors.blockHeight
+(state)
%7D%0A ha
@@ -1356,20 +1356,16 @@
-
hasSynce
@@ -1390,44 +1390,90 @@
- isLoading=%7Bstate.isLoading%7D%0A
+isLightningGrpcActive=%7Bstate.lnd.isLightningGrpcActive%7D%0A network=%7Bnetwork%7D%0A
@@ -1489,37 +1489,49 @@
inoBlockHeight=%7B
-state
+neutrinoSelectors
.neutrinoBlockHe
@@ -1530,30 +1530,33 @@
oBlockHeight
-%7D%0A
+(state)%7D%0A
neut
@@ -1574,21 +1574,33 @@
Height=%7B
-state
+neutrinoSelectors
.neutrin
@@ -1613,22 +1613,154 @@
erHeight
+(state)
%7D%0A
+ neutrinoRecoveryHeight=%7BneutrinoSelectors.neutrinoRecoveryHeight(state)%7D%0A recoveryPercentage=%7BrecoveryPercentage%7D%0A
@@ -1793,20 +1793,16 @@
etOpen%7D%0A
-
@@ -1841,36 +1841,8 @@
on%7D%0A
- // Dispatch%0A
@@ -1881,28 +1881,24 @@
ge%7D%0A
-
syncStatus=%7B
@@ -1909,20 +1909,16 @@
Status%7D%0A
-
/%3E
@@ -1922,34 +1922,8 @@
/%3E%0A
- )%7D%0A %3C/State%3E%0A
|
367b842bb8cabb9796d52714172451f2fffb17ec | Remove no longer needed jquery references. | ui/webpack.config.js | ui/webpack.config.js | const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { VueLoaderPlugin } = require('vue-loader')
const { DefinePlugin, ProvidePlugin } = require('webpack')
const CompressionPlugin = require('compression-webpack-plugin')
const src = path.resolve(__dirname, 'src')
const wwwroot = path.resolve(__dirname, 'wwwroot')
const nodeModules = path.resolve(__dirname, 'node_modules')
module.exports = (env, argv) => {
const isProduction = argv.mode === 'production'
return {
entry: {
app: [ 'app/main' ],
splash: [ 'app/splash' ]
},
module: {
rules: [
{ test: /\.ts$/i, loader: 'ts-loader', options: { appendTsSuffixTo: [/\.vue$/] }, exclude: nodeModules },
{ test: /\.vue$/i, loader: 'vue-loader', exclude: nodeModules },
{ test: /\.html$/i, loader: 'vue-template-loader', options: { transformAssetUrls: { img: 'src' } } },
{ test: /\.scss$/i, use: [ 'style-loader', 'css-loader', 'postcss-loader', 'sass-loader' ] },
{ test: /\.(svg)$/i, loader: 'file-loader' },
{ test: /\.(gif|png|jpe?g)$/i, use: [ { loader: 'file-loader' }, { loader: 'image-webpack-loader', options: { optipng: { optimizationLevel: 8 } } } ] },
{ test: /\.(woff|woff2|eot|ttf|otf)$/i, loader: 'file-loader' }
]
},
resolve: {
extensions: ['.ts', '.js'],
modules: [src, nodeModules]
},
output: {
filename: isProduction ? '[name]-[hash].js' : '[name]-bundle.js',
path: wwwroot,
devtoolModuleFilenameTemplate: './[resource-path]'
},
performance: { hints: false },
plugins: [
new DefinePlugin({ APPLICATIONMODE: JSON.stringify(isProduction ? 'Production' : 'Development') }),
new CleanWebpackPlugin(),
new ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
Popper: 'popper.js',
Promise: 'bluebird'
}),
new VueLoaderPlugin(),
new HtmlWebpackPlugin({
template: path.resolve(src, 'index.ejs'),
favicon: path.resolve(src, 'favicon.ico'),
chunks: [ 'splash', 'app' ],
chunksSortMode: 'manual',
minify: isProduction ? { collapseWhitespace: true, collapseInlineTagWhitespace: true } : false
}),
new CompressionPlugin({ test: /\.(js|html)$/, threshold: 1024 })
],
devtool: !isProduction ? 'source-map' : undefined,
devServer: {
contentBase: wwwroot,
port: 3000,
historyApiFallback: true,
proxy: { '/api': 'http://localhost:5000' }
}
}
}
| JavaScript | 0 | @@ -1854,55 +1854,8 @@
n(%7B%0A
- $: 'jquery',%0A jQuery: 'jquery',%0A
|
3048c01175e93e0eaf45b16ffb0643d72b1ea0a3 | fix undefined 'session_id' member in kernel.js | IPython/frontend/html/notebook/static/js/kernel.js | IPython/frontend/html/notebook/static/js/kernel.js | //----------------------------------------------------------------------------
// Copyright (C) 2008-2011 The IPython Development Team
//
// Distributed under the terms of the BSD License. The full license is in
// the file COPYING, distributed as part of this software.
//----------------------------------------------------------------------------
//============================================================================
// Kernel
//============================================================================
var IPython = (function (IPython) {
var utils = IPython.utils;
var Kernel = function () {
this.kernel_id = null;
this.base_url = "/kernels";
this.kernel_url = null;
this.shell_channel = null;
this.iopub_channel = null;
this.running = false;
if (typeof(WebSocket) !== 'undefined') {
this.WebSocket = WebSocket
} else if (typeof(MozWebSocket) !== 'undefined') {
this.WebSocket = MozWebSocket
} else {
alert('Your browser does not have WebSocket support, please try Chrome, Safari or Firefox 6. Firefox 4 and 5 are also supported by you have to enable WebSockets in about:config.');
};
};
Kernel.prototype.get_msg = function (msg_type, content) {
var msg = {
header : {
msg_id : utils.uuid(),
username : "username",
session: this.session_id,
msg_type : msg_type
},
content : content,
parent_header : {}
};
return msg;
}
Kernel.prototype.start = function (notebook_id, callback) {
var that = this;
if (!this.running) {
var qs = $.param({notebook:notebook_id});
$.post(this.base_url + '?' + qs,
function (kernel_id) {
that._handle_start_kernel(kernel_id, callback);
},
'json'
);
};
};
Kernel.prototype.restart = function (callback) {
IPython.kernel_status_widget.status_restarting();
var url = this.kernel_url + "/restart";
var that = this;
if (this.running) {
this.stop_channels();
$.post(url,
function (kernel_id) {
that._handle_start_kernel(kernel_id, callback);
},
'json'
);
};
};
Kernel.prototype._handle_start_kernel = function (json, callback) {
this.running = true;
this.kernel_id = json.kernel_id;
this.ws_url = json.ws_url;
this.kernel_url = this.base_url + "/" + this.kernel_id;
this.start_channels();
callback();
IPython.kernel_status_widget.status_idle();
};
Kernel.prototype.start_channels = function () {
this.stop_channels();
var ws_url = this.ws_url + this.kernel_url;
console.log("Starting WS:", ws_url);
this.shell_channel = new this.WebSocket(ws_url + "/shell");
this.iopub_channel = new this.WebSocket(ws_url + "/iopub");
};
Kernel.prototype.stop_channels = function () {
if (this.shell_channel !== null) {
this.shell_channel.close();
this.shell_channel = null;
};
if (this.iopub_channel !== null) {
this.iopub_channel.close();
this.iopub_channel = null;
};
};
Kernel.prototype.execute = function (code) {
var content = {
code : code,
silent : false,
user_variables : [],
user_expressions : {}
};
var msg = this.get_msg("execute_request", content);
this.shell_channel.send(JSON.stringify(msg));
return msg.header.msg_id;
}
Kernel.prototype.complete = function (line, cursor_pos) {
var content = {
text : '',
line : line,
cursor_pos : cursor_pos
};
var msg = this.get_msg("complete_request", content);
this.shell_channel.send(JSON.stringify(msg));
return msg.header.msg_id;
}
Kernel.prototype.interrupt = function () {
if (this.running) {
$.post(this.kernel_url + "/interrupt");
};
};
Kernel.prototype.kill = function () {
if (this.running) {
this.running = false;
var settings = {
cache : false,
type : "DELETE",
};
$.ajax(this.kernel_url, settings);
};
};
IPython.Kernel = Kernel;
return IPython;
}(IPython));
| JavaScript | 0.000062 | @@ -809,32 +809,126 @@
unning = false;%0A
+ %0A this.username = %22username%22;%0A this.session_id = utils.uuid();%0A %0A
if (type
@@ -1501,25 +1501,29 @@
rname :
-%22
+this.
username
%22,%0A
@@ -1514,17 +1514,16 @@
username
-%22
,%0A
@@ -1539,16 +1539,17 @@
session
+
: this.s
|
cfba3408d008b75f30509d07f9d8bb36435fc0c7 | Fix bug where interval is not correctly cleared | templates/scripts/libs/base-object.js | templates/scripts/libs/base-object.js | //*****************************************************************
// A core object that all other objects inherit from.
//
// Currently only used to provide nice timeout management. You can
// add or remove named timeouts. If they are removed before
// triggering, they disappear.
//****************************************************************
//Internal function do not use.
function __createObject(obj){
return $$(obj);
}
BaseObject = __createObject({
timeouts: {},
_autoId: 0,
_initialized:false,
//Uses for extending an object. Syntax is
//var prop = BaseObject.create({prop1,: 1, prop2: 2});
create:function(properties){
var x = properties || {};
var self = $$(this,x);
return self;
},
_init: function(){
this.init();
},
init:function(){
//do nothing by default.
},
//Generates a unique (bare threading issues) id that can be used on the dom for id="";
generateId: function(){
BaseObject._autoId = BaseObject._autoId + 1;
return BaseObject._autoId;
},
addTimeout: function(name, fn, time) {
var self = this;
// Due to prototypal inheritance, timeouts is shared amongs all objects. Make sure timeout names are unique
name += '_' + this._id;
if (!this.timeouts[name]) {
var self = this;
this.timeouts[name] = window.setTimeout(function(){
fn.apply(self);
//clear the timeout after it has run
self.timeouts[name] = null;
}, time);
}
},
removeTimeout: function(name) {
// Due to prototypal inheritance, timeouts is shared amongs all objects. Make sure timeout names are unique
name += '_' + this._id;
if (this.timeouts[name]) {
window.clearTimeout(this.timeouts[name]);
this.timeouts[name] = null;
}
},
setInterval: function(name, fn, time) {
var self = this;
// Due to prototypal inheritance, timeouts is shared amongs all objects. Make sure timeout names are unique
name += '_' + this._id;
if (!this.timeouts[name]) {
var self = this;
this.timeouts[name] = window.setInterval(function(){
fn.apply(self);
//clear the timeout after it has run
self.timeouts[name] = null;
}, time);
}
},
_removeAllTimeouts:function(){
for(var i in this.timeouts){
this.removeTimeout(i);
}
}
});
| JavaScript | 0.000001 | @@ -1647,123 +1647,35 @@
-if (
this.
-timeouts%5Bname%5D) %7B%0A window.clearTimeout(this.timeouts%5B
+_removeTimeout(
name
-%5D
);%0A
- this.timeouts%5Bname%5D = null;%0A %7D%0A
%7D,
@@ -2026,96 +2026,123 @@
- //clear the timeout after it has run%0A self.timeouts%5Bname%5D = null;%0A %7D, time
+%7D, time);%0A %7D%0A %7D,%0A%0A _removeAllTimeouts:function()%7B%0A for(var i in this.timeouts)%7B%0A this._removeTimeout(i
);%0A
@@ -2157,36 +2157,33 @@
,%0A%0A _remove
-All
Timeout
-s
:
+
function()%7B%0A
@@ -2179,36 +2179,80 @@
unction(
+name
)%7B%0A
-for(var i in
+if (this.timeouts%5Bname%5D) %7B%0A window.clearTimeout(
this.tim
@@ -2248,34 +2248,40 @@
ut(this.timeouts
-)%7B
+%5Bname%5D);
%0A this.remo
@@ -2276,32 +2276,37 @@
this.
-removeTimeout(i)
+timeouts%5Bname%5D = null
;%0A %7D%0A
|
d8ad15e8e8b97ee84fc505dcbd4f5c0aa4017217 | fix unit tests | test/components/change-sex-buttons.js | test/components/change-sex-buttons.js | import ChangeSexButtons from '../../src/code/components/change-sex-buttons';
describe.skip("<ChangeSexButtons />", function(){
it("should create a <div> tag with appropriate classes", function() {
const wrapper = shallow(<ChangeSexButtons sex='male' onChange={function() {}}/>);
assert(wrapper.find('div').at(1).hasClass('geniblocks'), "Should create a <div> with 'geniblocks' class");
assert(wrapper.find('div').at(1).hasClass('change-sex-buttons'), "Should create a <div> with 'change-sex-buttons' class");
assert(wrapper.find('div').at(1).hasClass('male-selected'), "Should create a <div> with 'male-selected' class");
assert(!wrapper.find('div').at(1).hasClass('female-selected'), "Should create a <div> without 'female-selected' class");
});
it("should create a <div> tag with appropriate classes", function() {
const wrapper = shallow(<ChangeSexButtons sex='female' onChange={function() {}}/>);
assert(wrapper.find('div').at(1).hasClass('geniblocks'), "Should create a <div> with 'geniblocks' class");
assert(wrapper.find('div').at(1).hasClass('change-sex-buttons'), "Should create a <div> with 'change-sex-buttons' class");
assert(!wrapper.find('div').at(1).hasClass('male-selected'), "Should create a <div> without 'male-selected' class");
assert(wrapper.find('div').at(1).hasClass('female-selected'), "Should create a <div> with 'female-selected' class");
});
it("should create a <div> tag for the label when requested", function() {
const labelWrapper = shallow(<ChangeSexButtons sex='male' species="Drake" showLabel={true} onChange={function() {}}/>),
noLabelWrapper = shallow(<ChangeSexButtons sex='male' showLabel={false} onChange={function() {}}/>),
labelDivs = labelWrapper.find('div').length,
noLabelDivs = noLabelWrapper.find('div').length;
assert.equal(labelDivs, noLabelDivs + 1, "'showLabel' prop adds one 'div'");
});
it("clicking the male button should trigger the onChange handler", function() {
let sex = 'female';
function handleChange(iSex) { sex = iSex; }
const wrapper = mount(<ChangeSexButtons sex={sex} onChange={handleChange} />);
wrapper.find('div.change-sex-buttons').simulate('click', { clientX: 90 });
assert.equal(sex, 'male', "an appropriate click should change the sex to 'male'");
});
it("clicking the female button should trigger the onChange handler", function() {
let sex = 'male';
function handleChange(iSex) { sex = iSex; }
const wrapper = mount(<ChangeSexButtons sex={sex} onChange={handleChange} />);
wrapper.find('div.change-sex-buttons').simulate('click', { clientX: 10 });
assert.equal(sex, 'female', "an appropriate click should change the sex to 'female'");
});
});
| JavaScript | 0.000001 | @@ -83,13 +83,8 @@
ribe
-.skip
(%22%3CC
@@ -116,16 +116,16 @@
tion()%7B%0A
+
%0A it(%22s
@@ -239,22 +239,32 @@
ons sex=
-'male'
+%7BBioLogica.MALE%7D
onChang
@@ -894,24 +894,34 @@
ons sex=
-'female'
+%7BBioLogica.FEMALE%7D
onChang
@@ -1560,22 +1560,32 @@
ons sex=
-'male'
+%7BBioLogica.MALE%7D
species
@@ -1696,22 +1696,32 @@
ons sex=
-'male'
+%7BBioLogica.MALE%7D
showLab
@@ -2058,24 +2058,32 @@
t sex =
-'female'
+BioLogica.FEMALE
;%0A fu
@@ -2308,22 +2308,30 @@
al(sex,
-'male'
+BioLogica.MALE
, %22an ap
@@ -2486,22 +2486,30 @@
t sex =
-'male'
+BioLogica.MALE
;%0A fu
@@ -2734,24 +2734,32 @@
al(sex,
-'female'
+BioLogica.FEMALE
, %22an ap
|
a3adb6316c6c9b5daedab823e9c885a9520c8c14 | Revert response to old version. Needs to be updated still | test/fixtures/transaction_response.js | test/fixtures/transaction_response.js | /**
* Avalara © 2017
* file: test/fixtures/transaction_response.js
*/
export default {
"id": 26964607,
"code": "d99acf3d-3b2b-407b-8123-8d2d18c468c8",
"companyId": 123456,
"date": "2017-01-10",
"taxDate": "2017-01-10T00:00:00",
"paymentDate": "1900-01-01T00:00:00",
"status": "Committed",
"type": "SalesInvoice",
"batchCode": "",
"currencyCode": "USD",
"customerUsageType": "",
"customerVendorCode": "ABC",
"exemptNo": "",
"reconciled": false,
"purchaseOrderNo": "2017-01-10-001",
"salespersonCode": "",
"taxOverrideType": "None",
"taxOverrideAmount": 0,
"taxOverrideReason": "",
"totalAmount": 100,
"totalExempt": 100,
"totalTax": 0,
"totalTaxable": 0,
"totalTaxCalculated": 0,
"adjustmentReason": "NotAdjusted",
"adjustmentDescription": "",
"locked": false,
"region": "CA",
"country": "US",
"version": 1,
"softwareVersion": "16.12.0.10",
"originAddressId": 690759508,
"destinationAddressId": 690759508,
"exchangeRateEffectiveDate": "2017-01-10",
"exchangeRate": 1,
"isSellerImporterOfRecord": false,
"description": "Yarn",
"modifiedDate": "2017-01-24T03:13:04.57",
"modifiedUserId": 541115,
"lines": [{
"id": 987654321,
"transactionId": 78987654321,
"lineNumber": "1",
"boundaryOverrideId": 0,
"customerUsageType": "",
"description": "Yarn",
"destinationAddressId": 690759508,
"originAddressId": 690759508,
"discountAmount": 0,
"exemptAmount": 100,
"exemptCertId": 0,
"exemptNo": "",
"isItemTaxable": true,
"isSSTP": false,
"itemCode": "Y0001",
"lineAmount": 100,
"quantity": 1,
"ref1": "",
"ref2": "",
"reportingDate": "2017-01-10",
"revAccount": "",
"sourcing": "Origin",
"tax": 0,
"taxableAmount": 0,
"taxCalculated": 0,
"taxCode": "PS081282",
"taxCodeId": 38007,
"taxDate": "2017-01-10",
"taxEngine": "",
"taxOverrideType": "None",
"taxOverrideAmount": 0,
"taxOverrideReason": "",
"taxIncluded": false,
"details": [{
"id": 175044561,
"transactionLineId": 97207324,
"transactionId": 26964607,
"addressId": 690759508,
"country": "US",
"region": "CA",
"stateFIPS": "06",
"exemptAmount": 0,
"exemptReasonId": 6,
"inState": true,
"jurisCode": "06",
"jurisName": "CALIFORNIA",
"jurisdictionId": 5000531,
"signatureCode": "AGAM",
"stateAssignedNo": "",
"jurisType": "STA",
"nonTaxableAmount": 100,
"nonTaxableRuleId": 0,
"nonTaxableType": "NexusRule",
"rate": 0,
"rateRuleId": 0,
"rateSourceId": 0,
"serCode": " ",
"sourcing": "Origin",
"tax": 0,
"taxableAmount": 0,
"taxType": "Sales",
"taxName": "CA STATE TAX",
"taxAuthorityTypeId": 45,
"taxRegionId": 2127863,
"taxCalculated": 0,
"taxOverride": 0,
"rateType": "General",
"taxableUnits": 0,
"nonTaxableUnits": 100,
"exemptUnits": 0,
"unitOfBasis": "PerCurrencyUnit"
}],
"parameters": {}
}],
"addresses": [{
"id": 690759508,
"transactionId": 26964607,
"boundaryLevel": "Zip5",
"line1": "123 Main Street",
"line2": "",
"line3": "",
"city": "Irvine",
"region": "CA",
"postalCode": "92615",
"country": "US",
"taxRegionId": 2127863
}],
"summary": [{
"country": "US",
"region": "CA",
"jurisType": "State",
"jurisCode": "06",
"jurisName": "CALIFORNIA",
"taxAuthorityType": 45,
"stateAssignedNo": "",
"taxType": "Sales",
"taxName": "CA STATE TAX",
"rateType": "General",
"taxable": 0,
"rate": 0,
"tax": 0,
"taxCalculated": 0,
"nonTaxable": 100,
"exemption": 0
}],
"parameters": {}
}
| JavaScript | 0 | @@ -196,19 +196,28 @@
17-01-10
+T00:00:00
%22,%0A
-
%22taxDa
@@ -1015,24 +1015,33 @@
%222017-01-10
+T00:00:00
%22,%0A %22exchan
@@ -1700,32 +1700,41 @@
te%22: %222017-01-10
+T00:00:00
%22,%0A %22revAccou
@@ -1877,24 +1877,24 @@
Id%22: 38007,%0A
-
%22taxDate
@@ -1907,16 +1907,25 @@
17-01-10
+T00:00:00
%22,%0A %22
|
e463dc1949e2b7be5f8be4d4554ad04358b16e18 | fix 名称大小写 | test/leaflet/overlay/MapVLayerSpec.js | test/leaflet/overlay/MapVLayerSpec.js | require('../../../src/leaflet/overlay/mapVLayer');
var mapv = require('mapv');
window.mapv = mapv;
var url = GlobeParameter.ChinaURL;
describe('leaflet_MapVLayer', function () {
var originalTimeout;
var testDiv, map, mapvLayer;
beforeAll(function () {
testDiv = document.createElement("div");
testDiv.setAttribute("id", "map");
testDiv.style.styleFloat = "left";
testDiv.style.marginLeft = "8px";
testDiv.style.marginTop = "50px";
testDiv.style.width = "500px";
testDiv.style.height = "500px";
document.body.appendChild(testDiv);
map = L.map('map', {
center: [32, 109],
zoom: 4,
});
L.supermap.tiledMapLayer(url).addTo(map);
});
beforeEach(function () {
var randomCount = 1000;
var data = [];
var citys = ["北京", "天津", "上海", "重庆", "石家庄", "太原", "呼和浩特", "哈尔滨", "长春", "沈阳", "济南",
"南京", "合肥", "杭州", "南昌", "福州", "郑州", "武汉", "长沙", "广州", "南宁", "西安", "银川", "兰州",
"西宁", "乌鲁木齐", "成都", "贵阳", "昆明", "拉萨", "海口"];
// 构造数据
while (randomCount--) {
var cityCenter = mapv.utilCityCenter.getCenterByCityName(citys[parseInt(Math.random() * citys.length)]);
data.push({
geometry: {
type: 'Point',
coordinates: [cityCenter.lng - 2 + Math.random() * 4, cityCenter.lat - 2 + Math.random() * 4]
},
count: 30 * Math.random()
});
}
var dataSet = new mapv.DataSet(data);
var options = {
fillStyle: 'rgba(55, 50, 250, 0.8)',
shadowColor: 'rgba(255, 250, 50, 1)',
shadowBlur: 20,
max: 100,
size: 50,
label: {
show: true,
fillStyle: 'white',
},
globalAlpha: 0.5,
gradient: {0.25: "rgb(0,0,255)", 0.55: "rgb(0,255,0)", 0.85: "yellow", 1.0: "rgb(255,0,0)"},
draw: 'honeycomb'
};
//创建MapV图层
mapvLayer = L.supermap.mapVLayer(dataSet, options).addTo(map);
originalTimeout = jasmine.DEFAULT_TIMEOUT_INTERVAL;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 50000;
});
afterEach(function () {
jasmine.DEFAULT_TIMEOUT_INTERVAL = originalTimeout;
mapvLayer.remove();
});
afterAll(function () {
document.body.removeChild(testDiv);
map.remove();
mapv = null;
});
it('constructor test', function (done) {
expect(mapvLayer).not.toBeNull();
expect(mapvLayer.mapVOptions.shadowBlur).toEqual(20);
expect(mapvLayer.mapVOptions.draw).toBe("honeycomb");
//判断是否返回期望的maplayer
expect(mapvLayer.renderer).not.toBeNull();
expect(mapvLayer.renderer.context).toBe("2d");
expect(mapvLayer.renderer.canvasLayer).not.toBeNull();
done();
});
it('adddata test',function () {
var data = [{
geometry: {
type: 'Point',
coordinates: [109, 32]
},
count: 111
}];
var dataset = new mapv.DataSet(data);
var tempoption = {
shadowBlur: 30
}
mapvLayer.addData(dataset,tempoption);
expect(mapvLayer.dataSet).not.toBeNull();
expect(mapvLayer.dataSet._data[1000].count).toEqual(111);
expect(mapvLayer.dataSet._data[1000].geometry.coordinates[0]).toEqual(109);
expect(mapvLayer.dataSet._data[1000].geometry.coordinates[1]).toEqual(32);
expect(mapvLayer.mapVOptions.shadowBlur).toEqual(30);
});
it('getData test',function () {
var dataset = mapvLayer.getData()
expect(dataset._data.length).toEqual(1000);
});
xit('removeData test',function (done) {
var filter = function(data){
//if( mapvLayer.dataSet._data.indexOf(data) === 2){
if(data.count = 7.439562169122387){
return true
}
return false;
}
mapvLayer.removeData(filter);
setTimeout(function () {
expect(mapvLayer.dataSet._data.length).toEqual(999);
done();
},6000);
});
it('update test',function () {
var data = [{
geometry: {
type: 'Point',
coordinates: [109, 32]
},
count: 111
}];
var dataset = new mapv.DataSet(data);
var tempoption = {
shadowBlur: 40
}
var opt = {data: dataset, options: tempoption};
mapvLayer.update(opt);
expect(mapvLayer.dataSet._data.length).toEqual(1);
expect(mapvLayer.dataSet._data[0].count).toEqual(111);
expect(mapvLayer.dataSet._data[0].geometry.coordinates[0]).toEqual(109);
expect(mapvLayer.dataSet._data[0].geometry.coordinates[1]).toEqual(32);
expect(mapvLayer.mapVOptions.shadowBlur).toEqual(40);
});
it('clearData test',function () {
mapvLayer.clearData();
expect(mapvLayer.dataSet._data.length).toEqual(0);
});
it('draw redraw test',function () {
mapvLayer.draw();
expect(mapvLayer.canvas.width).toEqual(500);
expect(mapvLayer.canvas.style.width).toBe('500px');
mapvLayer.redraw();
expect(mapvLayer.canvas.width).toEqual(500);
expect(mapvLayer.canvas.style.width).toBe('500px');
});
it('setZIndex test',function () {
mapvLayer.setZIndex(2);
expect(mapvLayer.canvas.style.zIndex).toEqual('2');
});
it('getCanvas test',function () {
var canvas = mapvLayer.getCanvas();
expect(canvas).not.toBeNull();
expect(mapvLayer.canvas.width).toEqual(500);
expect(mapvLayer.canvas.height).toEqual(500);
});
it('getContainer test',function () {
var container = mapvLayer.getContainer();
expect(container).not.toBeNull();
});
it('getTopLeft test',function () {
var topLeft = mapvLayer.getTopLeft();
expect(topLeft).not.toBeNull();
expect(topLeft.lng).toEqual(87.01171875);
expect(topLeft.lat).toEqual(48.63290858589535);
});
}); | JavaScript | 0.000058 | @@ -31,17 +31,17 @@
overlay/
-m
+M
apVLayer
|
4f1dda07468d8aa7d16690a61663b6e52fccc893 | Correct signature | test/mocha/BackendCallHandler-Test.js | test/mocha/BackendCallHandler-Test.js | var assert = require("assert");
var bus = require('../../dist/EventBus');
var jrpc = require('../../dist/JsonRpc');
var handler = require('../../dist/BackendCallHandler');
var sample = require('../extra/wsrpc_registry_classes').wsrpc_registry_classes;
handler.DEBUG = true;
var mockClient = {
callCount: 0,
jsonRpcMessage: null,
send: function(data) {
this.callCount ++;
console.log('MOCK SEND ' + '(' + this.callCount + '), data = ' + data);
this.jsonRpcMessage = data;
},
result: function() {
return JSON.parse(this.jsonRpcMessage).result;
},
error: function() {
return JSON.parse(this.jsonRpcMessage).error;
}
};
var mockServer = {
clients: [mockClient, mockClient]
};
describe('BackendCallHandler execute tests', function () {
var _handler = new handler.BackendCallHandler();
_handler.singleton('compteur', sample.Compteur);
_handler.singleton('chatroom', sample.Chatroom);
_handler.stateless('dateutil', sample.DateUtil);
describe('execute: on singleton', function () {
it('call execute: increment on singleton object', function () {
var registry = _handler.getRegistry('compteur');
_handler.execute(mockClient, 'compteur', 'increment', null, 'INC');
assert.equal(1, mockClient.result());
_handler.execute(mockClient, 'compteur', 'increment', null, 'INC');
assert.equal(2, mockClient.result());
_handler.execute(mockClient, 'compteur', 'increment', null, 'INC');
assert.equal(3, mockClient.result());
var v = registry.invoke('compteur', 'increment', null);
assert.equal(4, v);
v = registry.invoke('compteur', 'increment', null);
assert.equal(5, v);
})
});
describe('execute: on stateless', function () {
it('call execute: increment on stateless object', function () {
var registry = _handler.getRegistry('dateutil');
var h = registry.invoke('dateutil', 'getHour', null);
_handler.execute(mockClient, 'dateutil', 'getHour', null, 'HOUR');
assert.equal(h, mockClient.result());
_handler.execute(mockClient, 'dateutil', 'getHour', null, 'HOUR');
assert.equal(h, mockClient.result());
_handler.execute(mockClient, 'dateutil', 'getHour', null, 'HOUR');
assert.equal(h, mockClient.result());
})
});
});
describe('BackendCallHandler sendResponseToOrigin tests', function () {
var _handler = new handler.BackendCallHandler();
describe('sendResponseToOrigin', function () {
it('send response json to the corresponding client', function () {
mockClient.callCount = 0;
_handler.broadcastExecute(mockServer, mockClient, 'compteur', 'increment', null, 'INC_1');
assert.equal(2, mockClient.callCount);
mockClient.callCount = 0;
var message = '{"jsonrpc":"2.0","result":100,"id":"INC_1"}';
var rpc = new jrpc.RPC(JSON.parse(message));
_handler.sendResponseToOrigin(rpc.getId(), rpc.getResult());
assert.equal(1, mockClient.callCount);
assert.equal(100, mockClient.result());
assert.equal(mockClient, _handler.getClientResponseWithId('INC_1'));
})
});
});
describe('BackendCallHandler sendErrorToOrigin tests', function () {
var _handler = new handler.BackendCallHandler();
describe('send error json to the corresponding client', function () {
it('call sendErrorToOrigin', function () {
mockClient.callCount = 0;
_handler.broadcastExecute(mockServer, mockClient, 'compteur', 'incrementation', null, 'INC_2');
assert.equal(2, mockClient.callCount);
mockClient.callCount = 0;
var message = '{"jsonrpc":"2.0","error":{"code":-32601,"message":"RPC client instance named null not found."},"id":"INC_2"}';
var rpc = new jrpc.RPC(JSON.parse(message));
_handler.sendErrorToOrigin(rpc.getId(), rpc.getCode(), rpc.getErrorMessage());
assert.equal(1, mockClient.callCount);
assert.equal(-32601, mockClient.error().code);
assert.equal(mockClient, _handler.getClientResponseWithId('INC_2'));
})
});
});
describe('BackendCallHandler useResponse tests', function () {
var _handler = new handler.BackendCallHandler();
describe('fire response to eventBus', function () {
it('call useResponse', function () {
var done = false;
var data = null;
var eventBus = bus.EventBus.getSharedEventBus();
eventBus.on('INC_3', function(x) {
done = true;
data = x;
});
_handler.useResponse('INC_3', { RESULT: 'DONE' });
assert.equal(true, done);
assert.equal('DONE', data.RESULT);
})
});
}); | JavaScript | 0.000323 | @@ -3089,32 +3089,104 @@
arse(message));%0A
+ var client = _handler.getClientResponseWithId(rpc.getId());%0A
_han
@@ -3203,32 +3203,40 @@
esponseToOrigin(
+client,
rpc.getId(), rpc
@@ -4131,32 +4131,104 @@
arse(message));%0A
+ var client = _handler.getClientResponseWithId(rpc.getId());%0A
_han
@@ -4250,16 +4250,24 @@
oOrigin(
+client,
rpc.getI
|
19520e0e14f229692496001e697852cd6ff97070 | clean up | test/spec/filters/regexFilter.spec.js | test/spec/filters/regexFilter.spec.js | 'use strict';
describe("Unit Testing: regex filters", function () {
var filt;
var dummyList = [{
'name': 'msajc003'
}, {
'name': 'msajc010'
}, {
'name': 'msajc012'
}, {
'name': 'msajc015'
}, {
'name': 'msajc022'
}, {
'name': 'msajc023'
}, {
'name': 'msajc057'
}];
// load the module
beforeEach(module('emulvcApp'));
// load filter function into variable
beforeEach(inject(function ($filter) {
filt = $filter('regex');
}));
// test regex filter
it('should filter dummyarray with regex: ', function () {
expect(filt).not.toEqual(null);
expect(filt(dummyList, '01').length).toEqual(3);
expect(filt(dummyList, 'msajc003').length).toEqual(1);
expect(filt(dummyList, 'asdf').length).toEqual(0);
})
}); | JavaScript | 0.000001 | @@ -62,16 +62,17 @@
on () %7B%0A
+%0A
var fi
@@ -76,17 +76,16 @@
filt;%0A%0A
-%0A
var du
@@ -478,24 +478,117 @@
');%0A %7D));%0A%0A
+ it('should have a regex filter: ', function () %7B%0A expect(filt).not.toEqual(null);%0A %7D)%0A%0A
// test re
@@ -639,16 +639,25 @@
th regex
+ properly
: ', fun
@@ -674,37 +674,55 @@
%0A expect(filt
-).not
+(dummyList, '').length)
.toEqual(null);%0A
@@ -710,28 +710,25 @@
th).toEqual(
-null
+7
);%0A expec
@@ -889,12 +889,13 @@
0);%0A %7D)
+;
%0A%7D);
|
7b2ac2fc8dcc29a2f8c64fc1ec5fbf8a34ddfe52 | comment out failing tests that need rewrite | test/unit/responsive-carousel_test.js | test/unit/responsive-carousel_test.js | /*global QUnit:false, module:false, test:false, asyncTest:false, expect:false*/
/*global start:false, stop:false ok:false, equal:false, notEqual:false, deepEqual:false*/
/*global notDeepEqual:false, strictEqual:false, notStrictEqual:false, raises:false*/
(function($) {
/*
======== A Handy Little QUnit Reference ========
http://docs.jquery.com/QUnit
Test methods:
expect(numAssertions)
stop(increment)
start(decrement)
Test assertions:
ok(value, [message])
equal(actual, expected, [message])
notEqual(actual, expected, [message])
deepEqual(actual, expected, [message])
notDeepEqual(actual, expected, [message])
strictEqual(actual, expected, [message])
notStrictEqual(actual, expected, [message])
raises(block, [expected], [message])
*/
// DOM readiness needed for all tests
$(function(){
test( "Carousel initializes automatically on DOM ready", function() {
ok( $( "[data-carousel]" ).is( ".carousel" ) );
});
test( "Carousel child-items have carousel-item class", function() {
ok( $( "[data-carousel] [data-carousel-item]" ).is( ".carousel-item" ) );
});
module("Testing goTo");
QUnit.testStart = function(name){
$( ".carousel" ).carousel( "goTo", 1 );
};
test( "Carousel contain width is set based upon the amount of carousel-items there are" , function() {
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$contain = $( ".carousel-contain" ),
$carousel = $( ".carousel" ),
width = Math.round($contain.width()/$carousel.width());
equal( width, amt, "The width is correctly set" );
});
test( "goTo sets margin according to which position it is in" , function(){
stop();
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$contain = $( ".carousel-contain" ),
$carousel = $( ".carousel" ),
position = 1;
$( ".carousel" ).carousel( "goTo", position );
setTimeout(function(){
var marg = parseFloat($contain.css( "margin-left" ), 10),
carouselWidth = $carousel.width(),
actual = Math.round(Math.abs(marg/carouselWidth)+1);
equal( actual, position, "The margin is at the correct position" );
start();
}, 200);
});
test( "goTo sets margin according to which position it is in" , function(){
stop();
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$contain = $( ".carousel-contain" ),
$carousel = $( ".carousel" ),
position = 2;
$( ".carousel" ).carousel( "goTo", position );
setTimeout(function(){
var marg = parseFloat($contain.css( "margin-left" ), 10),
carouselWidth = $carousel.width(),
actual = Math.round(Math.abs(marg/carouselWidth)+1);
equal( actual, position, "The margin is at the correct position" );
start();
}, 200);
});
test( "next sets margin to next spot according to the current margin" , function(){
$( ".carousel" ).carousel( "goTo", 1 );
stop();
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$contain = $( ".carousel-contain" ),
expectedMargin = -100;
$( ".carousel" ).carousel( "next" );
setTimeout(function(){
var marg = parseFloat($contain.css( "marginLeft" ), 10),
actualMargin = Math.round(marg/$(window).width()) * 100;
equal( actualMargin, expectedMargin, "The margin is at the correct position" );
start();
}, 200);
});
test( "if current slide is the last, next should do nothing" , function(){
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$carousel = $( ".carousel" );
$carousel.carousel( "goTo", amt-1 );
stop();
var $contain = $( ".carousel-contain" ),
expectedMargin = (amt-1)*(-100);
$carousel.carousel( "next" );
setTimeout(function(){
var marg = parseFloat($contain.css( "marginLeft" ), 10),
winWidth = $(window).width() || 1000,
x = Math.round(marg/winWidth) * 100;
equal( x, expectedMargin, "The margin is at the correct position" );
start();
}, 200);
});
test( "if current slide is last, next link should not be showing", function(){
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$carousel = $( ".carousel" );
$carousel.carousel( "goTo", amt-1 );
stop();
setTimeout(function(){
ok( $( "[href='#next']" ).is( ".disabled" ), "The next button is disabled" );
start();
}, 200);
});
test( "prev sets margin to prev spot according to the current margin" , function(){
$( ".carousel" ).carousel( "goTo", 2 );
stop();
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$contain = $( ".carousel-contain" ),
expectedMargin = 0;
$( ".carousel" ).carousel( "prev" );
setTimeout(function(){
var marg = parseFloat($contain.css( "marginLeft" ), 10),
winWidth = $(window).width() || 1000,
x = Math.round(marg/winWidth) * 100;
equal( x, expectedMargin, "The margin is at the correct position" );
start();
}, 200);
});
test( "if current slide is first, prev should do nothing" , function(){
var $items = $( "[data-carousel] [data-carousel-item]" ),
amt = $items.length,
$carousel = $( ".carousel" );
$carousel.carousel( "goTo", 1 );
stop();
var $contain = $( ".carousel-contain" ),
expectedMargin = 0;
$carousel.carousel( "prev" );
setTimeout(function(){
var marg = parseFloat($contain.css( "marginLeft" ), 10),
winWidth = $(window).width() || 1000,
x = Math.round(marg/winWidth) * 100;
equal( x, expectedMargin, "The margin is at the correct position" );
start();
}, 200);
});
test( "if current slide is first, prev link should not be showing", function(){
var $carousel = $( ".carousel" );
$carousel.carousel( "goTo", 1 );
stop();
setTimeout(function(){
ok( $( "[href='#prev']" ).is( ".disabled" ), "The previous button is disabled" );
start();
}, 200);
});
});
}(jQuery));
| JavaScript | 0 | @@ -772,18 +772,16 @@
sage%5D)%0A%09
-*/
%0A%0A// DOM
@@ -5902,16 +5902,18 @@
);%0A%7D);%0A%0A
+*/
%0A%7D(jQuer
|
92eee35b7f4fd64982d2c803748e1e1a0d527cb0 | Fix jshint | addon/components/power-select-typeahead/trigger.js | addon/components/power-select-typeahead/trigger.js | import Ember from 'ember';
import layout from '../../templates/components/power-select-typeahead/trigger';
const { isBlank, run, get } = Ember;
export default Ember.Component.extend({
layout: layout,
tagName: '',
// Lifecycle hooks
didUpdateAttrs({ oldAttrs, newAttrs }) {
this._super(...arguments);
if (newAttrs.lastSearchedText !== oldAttrs.lastSearchedText) {
if (isBlank(newAttrs.lastSearchedText)) {
run.schedule('actions', null, newAttrs.select.actions.close, null, true);
} else {
run.schedule('actions', null, newAttrs.select.actions.open)
}
} else if (!isBlank(newAttrs.lastSearchedText) && get(this, 'options.length') === 0 && this.get('loading')) {
run.schedule('actions', null, newAttrs.select.actions.close, null, true);
}
},
// Actions
actions: {
stopPropagation(e) {
e.stopPropagation();
},
handleKeydown(e) {
let isLetter = e.keyCode >= 48 && e.keyCode <= 90 || e.keyCode === 32; // Keys 0-9, a-z or SPACE
let isSpecialKeyWhileClosed = !isLetter && !this.get('select.isOpen') && [13, 27, 38, 40].indexOf(e.keyCode) > -1;
if (isLetter || isSpecialKeyWhileClosed) {
e.stopPropagation();
}
}
}
});
| JavaScript | 0.000114 | @@ -587,16 +587,17 @@
ns.open)
+;
%0A %7D
|
30fd0caf5effacf63a863a5b157ca96aadf15303 | Add todo comment to find a better solution to bind the className to the parent | addon/pods/components/frost-list-item/component.js | addon/pods/components/frost-list-item/component.js | /* global $ */
import Ember from 'ember'
import _ from 'lodash/lodash'
import FrostList from '../frost-list/component'
export default Ember.Component.extend({
classNameBindings: ['isSelected', 'frost-list-item'],
initContext: Ember.on('init', function () {
this.set('_frostList', this.nearestOfType(FrostList))
}),
isSelected: Ember.computed('model.isSelected', function () {
let modelIsSelect = this.get('model.isSelected')
modelIsSelect ? $(this.get('element')).parent().addClass('is-selected')
: $(this.get('element')).parent().removeClass('is-selected')
return modelIsSelect
}),
onclick: Ember.on('click', function (event) {
if (!(Ember.ViewUtils.isSimpleClick(event) || event.shiftKey || event.metaKey || event.ctrlKey)) {
return true
}
event.preventDefault()
event.stopPropagation()
if (_.isFunction(this.get('_frostList.onSelect'))) {
let isTargetSelectionIndicator = Ember.$(event.target).hasClass('frost-list-selection-indicator')
if (event.shiftKey && (!this.get('_frostList.persistedClickState.isSelected')) && !this.get('isSelected')) {
this.get('_frostList.onShiftSelect').call(this.get('_frostList'), {
secondClickedRecord: this.get('model'),
isTargetSelectionIndicator: isTargetSelectionIndicator
})
if (window.getSelection) {
window.getSelection().removeAllRanges()
} else if (document.selection) { // IE
document.selection.empty()
}
} else {
this.get('_frostList.onSelect')({
record: this.get('model'),
isSelected: !this.get('model.isSelected'),
isTargetSelectionIndicator: isTargetSelectionIndicator,
isShiftSelect: false,
isCtrlSelect: (event.metaKey || event.ctrlKey) && (!this.get('_frostList.persistedClickState.isSelected')) &&
!this.get('isSelected')
})
}
this.set('_frostList.persistedClickState', {clickedRecord: this.get('model'), isSelected: this.get('isSelected')})
}
})
})
| JavaScript | 0 | @@ -380,24 +380,100 @@
nction () %7B%0A
+ // TODO: Find a better solution for binding the className to the parent%0A
let mode
|
4a7347e35b8ab58cc1e83081610ef1fdeefc49ff | fix error messages in new course page | administration/static/js/new-course/controllers.js | administration/static/js/new-course/controllers.js | (function(angular){
var app = angular.module('new-course');
app.controller('CourseEditController',
['$scope', 'Course', '$filter', 'youtubePlayerApi', 'VideoData',
function($scope, Course, $filter, youtubePlayerApi, VideoData) {
$scope.errors = {};
$scope.alert = {
hidden : true,
reset: function(){
this.title = '';
this.type = '';
this.messages = [];
this.showControls= true;
}
};
$scope.alert.reset();
$scope.course = new Course({'status':'draft','intro_video': {'youtube_id':''}});
// vv como faz isso de uma formula angular ?
var match = document.location.href.match(/courses\/([0-9]+)/);
if( match ) {
$scope.course.$get({id:match[1]})
.catch(function(resp){
$scope.alert.reset();
$scope.alert.showControls = false;
$scope.alert.type = 'danger';
if( resp.status === 404) {
$scope.alert.title = 'Curso com não existe!';
} else if( resp.status === 403) {
$scope.alert.title = 'Você não tem permissão para editar cursos!';
} else {
$scope.alert.title = 'Ocorreu um erro não esperado.';
}
$scope.alert.hidden = false;
});
}
// ^^ como faz isso de uma formula angular ?
$scope.statusList = {
'draft': 'Rascunho',
'listed': 'Listado',
'published': 'Publicados'
};
var player;
youtubePlayerApi.$watch('playerId', function(){
youtubePlayerApi.videoId = $scope.course.intro_video.youtube_id;
youtubePlayerApi.playerWidth = '100%';
youtubePlayerApi.playerHeight = '475px';
youtubePlayerApi.loadPlayer().then(function(p){
player = p;
});
});
$scope.$watch('course.intro_video.youtube_id', function(vid){
if(!vid) return;
if(player) player.cueVideoById(vid);
VideoData.load(vid).then(function(data){
$scope.course.intro_video.name = data.entry.title.$t;
});
});
$scope.saveCourse = function() {
if(!$scope.course.hasVideo()){
delete $scope.course.intro_video;
}
if(!$scope.course.slug){
$scope.course.slug = $filter('slugify')($scope.course.name);
}
$scope.course.$save()
.then(function(){
$scope.alert.reset();
$scope.alert.showControls = false;
$scope.alert.type = 'success';
$scope.alert.title = 'Suas alterações salvas!';
$scope.alert.hidden = false;
setTimeout(function(){
$scope.alert.hidden = true;
$scope.$apply();
}, 2000);
})
.catch(function(response){
$scope.errors = response.data;
$scope.alert.reset();
$scope.alert.type = 'danger';
$scope.alert.title = 'Encontramos alguns erros! Verifique os campos abaixo:';
for(var att in response.data) {
var label = (Course.fields[att]||{}).label ? Course.fields[att].label : att;
$scope.alert.messages.push(
label + ': ' + response.data[att]
);
}
$scope.alert.hidden = false;
}
);
};
}
]);
})(window.angular);
| JavaScript | 0 | @@ -3844,48 +3844,85 @@
var
-label = (Course.fields%5Batt%5D%7C%7C%7B%7D).label ?
+message = response.data%5Batt%5D;%0A if(Course.fields &&
Cou
@@ -3940,21 +3940,11 @@
att%5D
-.label : att;
+) %7B
%0A
@@ -3972,130 +3972,157 @@
-$scope.alert.messages.push(%0A label + ': ' + response.data%5Batt%5D%0A
+ message = Course.fields%5Batt%5D.label + ': ' + message;%0A %7D%0A $scope.alert.messages.push(message
);%0A
|
937134b46881251df63ef086634004e4d928b429 | fix caesar_cipher | algorithm/cryptography/caesar_cipher/basic/code.js | algorithm/cryptography/caesar_cipher/basic/code.js | function getPosUp(pos) {
return (pos === alphabet.length - 1) ? 0 : pos + 1;
}
function getPosDown(pos) {
return (pos === 0) ? alphabet.length - 1 : pos - 1;
}
function getNextChar(currChar, direction) {
var pos = alphabetMap[currChar];
var nextPos = direction === 'up' ? getPosUp(pos) : getPosDown(pos);
var nextChar = alphabet.charAt(nextPos);
logger._print(currChar + ' -> ' + nextChar);
return nextChar;
}
function cipher(str, rotation, direction, cipherTracer) {
if (!str) return '';
for (var i = 0; i < str.length; i++) {
cipherTracer._wait();
var currChar = str.charAt(i);
var r = rotation;
logger._print('Rotating ' + currChar + ' ' + direction + ' ' + rotation + ' times');
cipherTracer._notify(i)._wait();
// perform given amount of rotations in the given direction
while (--r > 0) {
currChar = getNextChar(currChar, direction);
cipherTracer._notify(i, currChar)._wait();
}
str = str.substring(0, i) + currChar + str.substring(i + 1);
logger._print('Current result: ' + str);
}
cipherTracer._select(0, i);
return str;
}
function encrypt(str, rotation) {
logger._print('Encrypting: ' + str);
return cipher(str, rotation, 'down', encryptTracer);
}
function decrypt(str, rotation) {
logger._print('Decrypting: ' + str);
return cipher(str, rotation, 'up', decryptTracer);
}
var encrypted = encrypt(string, rotation);
logger._print('Encrypted result: ' + encrypted);
decryptTracer._setData(encrypted);
var decrypted = decrypt(encrypted, rotation);
logger._print('Decrypted result: ' + decrypted);
| JavaScript | 0.001513 | @@ -351,19 +351,17 @@
xtPos);%0A
-
%0A
+
logger
@@ -571,21 +571,17 @@
wait();%0A
-
%0A
+
var
@@ -835,11 +835,11 @@
le (
+r
--
-r
%3E 0
@@ -948,20 +948,16 @@
;%0A %7D%0A
-
%0A str
|
eab7246218a757faa18a43530beaa394add53a8c | Clear component data window before merging it | app/assets/javascripts/app/models/app/component.js | app/assets/javascripts/app/models/app/component.js | class Component extends Item {
constructor(json_obj) {
super(json_obj);
if(!this.componentData) {
this.componentData = {};
}
if(!this.disassociatedItemIds) {
this.disassociatedItemIds = [];
}
if(!this.associatedItemIds) {
this.associatedItemIds = [];
}
}
mapContentToLocalProperties(content) {
super.mapContentToLocalProperties(content)
/* Legacy */
this.url = content.url || content.hosted_url;
/* New */
this.local_url = content.local_url;
this.hosted_url = content.hosted_url || content.url;
this.offlineOnly = content.offlineOnly;
if(content.valid_until) {
this.valid_until = new Date(content.valid_until);
}
this.name = content.name;
this.autoupdateDisabled = content.autoupdateDisabled;
this.package_info = content.package_info;
// the location in the view this component is located in. Valid values are currently tags-list, note-tags, and editor-stack`
this.area = content.area;
this.permissions = content.permissions;
if(!this.permissions) {
this.permissions = [];
}
this.active = content.active;
// custom data that a component can store in itself
this.componentData = content.componentData || {};
// items that have requested a component to be disabled in its context
this.disassociatedItemIds = content.disassociatedItemIds || [];
// items that have requested a component to be enabled in its context
this.associatedItemIds = content.associatedItemIds || [];
}
handleDeletedContent() {
super.handleDeletedContent();
this.active = false;
}
structureParams() {
var params = {
url: this.url,
hosted_url: this.hosted_url,
local_url: this.local_url,
valid_until: this.valid_until,
offlineOnly: this.offlineOnly,
name: this.name,
area: this.area,
package_info: this.package_info,
permissions: this.permissions,
active: this.active,
autoupdateDisabled: this.autoupdateDisabled,
componentData: this.componentData,
disassociatedItemIds: this.disassociatedItemIds,
associatedItemIds: this.associatedItemIds,
};
_.merge(params, super.structureParams());
return params;
}
toJSON() {
return {uuid: this.uuid}
}
get content_type() {
return "SN|Component";
}
isEditor() {
return this.area == "editor-editor";
}
isTheme() {
return this.content_type == "SN|Theme" || this.area == "themes";
}
isDefaultEditor() {
return this.getAppDataItem("defaultEditor") == true;
}
setLastSize(size) {
this.setAppDataItem("lastSize", size);
}
getLastSize() {
return this.getAppDataItem("lastSize");
}
keysToIgnoreWhenCheckingContentEquality() {
return ["active"].concat(super.keysToIgnoreWhenCheckingContentEquality());
}
/*
An associative component depends on being explicitly activated for a given item, compared to a dissaciative component,
which is enabled by default in areas unrelated to a certain item.
*/
static associativeAreas() {
return ["editor-editor"];
}
isAssociative() {
return Component.associativeAreas().includes(this.area);
}
associateWithItem(item) {
this.associatedItemIds.push(item.uuid);
}
isExplicitlyEnabledForItem(item) {
return this.associatedItemIds.indexOf(item.uuid) !== -1;
}
isExplicitlyDisabledForItem(item) {
return this.disassociatedItemIds.indexOf(item.uuid) !== -1;
}
}
| JavaScript | 0 | @@ -47,24 +47,309 @@
json_obj) %7B%0A
+ // If making a copy of an existing component (usually during sign in if you have a component active in the session),%0A // which may have window set, you may get a cross-origin exception since you'll be trying to copy the window. So we clear it here.%0A json_obj.window = null;%0A%0A
super(js
|
f814f8e2eddf8fab97a63ef4fd373fdda48aaaf0 | Fix updatePosition uncaught error | packages/strapi-plugin-content-manager/admin/src/components/RelationPreviewList/RelationPreviewTooltip.js | packages/strapi-plugin-content-manager/admin/src/components/RelationPreviewList/RelationPreviewTooltip.js | import React, { useState, useEffect, useCallback, useRef, useLayoutEffect } from 'react';
import { Text, Padded } from '@buffetjs/core';
import { LoadingIndicator, request } from 'strapi-helper-plugin';
import PropTypes from 'prop-types';
import getRequestUrl from '../../utils/getRequestUrl';
import Tooltip from '../Tooltip';
import getDisplayedValue from '../CustomTable/Row/utils/getDisplayedValue';
const RelationPreviewTooltip = ({ tooltipId, rowId, mainField, name }) => {
const [isLoading, setIsLoading] = useState(true);
const [relationData, setRelationData] = useState([]);
const tooltipRef = useRef();
const { endPoint } = mainField.queryInfos;
const fetchRelationData = useCallback(
async signal => {
const requestURL = getRequestUrl(`${endPoint}/${rowId}/${name}`);
try {
const { results } = await request(requestURL, {
method: 'GET',
signal,
});
setRelationData(results);
setIsLoading(false);
} catch (err) {
console.error({ err });
setIsLoading(false);
}
},
[endPoint, name, rowId]
);
useEffect(() => {
const abortController = new AbortController();
const { signal } = abortController;
const timeout = setTimeout(() => {
fetchRelationData(signal);
}, 500);
return () => {
clearTimeout(timeout);
abortController.abort();
};
}, [fetchRelationData]);
const getValueToDisplay = useCallback(
item => {
return getDisplayedValue(mainField.schema.type, item[mainField.name], mainField.name);
},
[mainField]
);
// Used to update the position after the loader
useLayoutEffect(() => {
if (!isLoading && tooltipRef.current) {
tooltipRef.current.updatePosition();
}
}, [isLoading]);
return (
<Tooltip ref={tooltipRef} id={tooltipId}>
<div>
{isLoading ? (
<Padded left right size="sm">
<LoadingIndicator small />
</Padded>
) : (
<>
{relationData.map(item => (
<Padded key={item.id} top bottom size="xs">
<Text ellipsis color="white">
{getValueToDisplay(item)}
</Text>
</Padded>
))}
{relationData.length > 10 && <Text color="white">[...]</Text>}
</>
)}
</div>
</Tooltip>
);
};
RelationPreviewTooltip.propTypes = {
tooltipId: PropTypes.string.isRequired,
mainField: PropTypes.shape({
name: PropTypes.string.isRequired,
schema: PropTypes.object.isRequired,
queryInfos: PropTypes.object.isRequired,
}).isRequired,
name: PropTypes.string.isRequired,
rowId: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
};
export default RelationPreviewTooltip;
| JavaScript | 0 | @@ -1733,44 +1733,269 @@
-tooltipRef.current.updatePosition();
+// A react-tooltip uncaught error is triggered when updatePosition is called in firefox.%0A // https://github.com/wwayne/react-tooltip/issues/619%0A try %7B%0A tooltipRef.current.updatePosition();%0A %7D catch (err) %7B%0A console.log(err);%0A %7D
%0A
|
c804c11c871a07a538958cf6c6dd202ae325e9f6 | Change order of unit column in Pathways | app/javascript/app/data/data-explorer-constants.js | app/javascript/app/data/data-explorer-constants.js | export const DATA_EXPLORER_BLACKLIST = [
'id',
'iso_code3',
'iso_code2',
'emissions'
];
export const DATA_EXPLORER_FIRST_TABLE_HEADERS = [
'region',
'data_source',
'sector',
'gwp',
'gas',
'unit',
'location',
'model',
'scenario',
'category',
'subcategory',
'indicator',
'definition'
];
export const DATA_EXPLORER_SECTIONS = {
'historical-emissions': {
label: 'historical_emissions',
moduleName: 'ghg-emissions'
},
'ndc-sdg-linkages': {
label: 'ndc_sdg',
moduleName: 'ndcs-sdg'
},
'emission-pathways': {
label: 'emission_pathways',
moduleName: 'pathways'
},
'ndc-content': {
label: 'ndc_content',
moduleName: 'ndcs-content'
}
};
export const DATA_EXPLORER_METHODOLOGY_SOURCE = {
'historical-emissions': {
PIK: ['historical_emissions_pik'],
CAIT: ['historical_emissions_cait'],
UNFCCC: ['historical_emissions_unfccc']
},
'ndc-sdg-linkages': ['ndc_sdc_all indicators'],
'ndc-content': ['ndc_cait', 'ndc_wb'],
'emission-pathways': [null] // model, scenario and indicator related metadata
};
export const DATA_EXPLORER_FILTERS = {
'historical-emissions': ['regions', 'source', 'sectors', 'gases'],
'ndc-sdg-linkages': ['countries', 'goals', 'targets', 'sectors'],
'emission-pathways': [
'locations',
'models',
'scenarios',
'categories',
'subcategories',
'indicators'
],
'ndc-content': ['countries', 'categories', 'indicators', 'sectors']
};
export const DATA_EXPLORER_DEPENDENCIES = {
'emission-pathways': {
models: ['locations'],
scenarios: ['models', 'locations'],
categories: ['scenarios', 'models', 'locations'],
subcategories: ['categories', 'scenarios', 'models', 'locations'],
indicators: [
'subcategories',
'categories',
'scenarios',
'models',
'locations'
]
}
};
export const DATA_EXPLORER_EXTERNAL_PREFIX = 'external';
export const DATA_EXPLORER_TO_MODULES_PARAMS = {
'historical-emissions': {
data_sources: { key: 'source' },
gwps: { key: 'version' }
},
'ndc-sdg-linkages': {
goals: {
key: 'goal',
idLabel: 'number'
}
},
'ndc-content': {},
'emission-pathways': {
locations: {
key: 'currentLocation',
idLabel: 'id',
currentId: 'iso_code'
},
models: {
key: 'model'
},
scenarios: {
key: 'scenario'
},
indicators: {
key: 'indicator'
},
categories: {
key: 'category'
}
}
};
export const MULTIPLE_LEVEL_SECTION_FIELDS = {
'ndc-content': [{ key: 'sectors' }, { key: 'categories' }]
};
export const GROUPED_SELECT_FIELDS = {
'historical-emissions': [
{
key: 'regions',
label: 'Countries and Regions',
groups: [
{ groupId: 'regions', title: 'Regions' },
{ groupId: 'countries', title: 'Countries' }
]
}
]
};
export const DATA_EXPLORER_PER_PAGE = 200;
export const SECTION_NAMES = {
pathways: 'emission-pathways',
historicalEmissions: 'historical-emissions'
};
export const FILTER_NAMES = {
models: 'models',
scenarios: 'scenarios',
indicators: 'indicators',
categories: 'categories',
subcategories: 'subcategories'
};
export const FILTERED_FIELDS = {
'historical-emissions': {
sectors: [
{
parent: 'source',
id: 'data_source_id'
}
]
},
'ndc-sdg-linkages': {
targets: [
{
parent: 'goals',
parentId: 'id',
id: 'goal_id'
}
]
},
'ndc-content': {
indicators: [
{
parent: FILTER_NAMES.categories,
parentId: 'id',
id: 'category_ids'
}
]
},
'emission-pathways': {
scenarios: [
{
parent: 'models',
idObject: 'model',
id: 'id'
}
],
indicators: [
{
parent: FILTER_NAMES.categories,
idObject: 'category',
id: 'id'
},
{
parent: 'scenarios',
parentId: 'indicator_ids',
id: 'id'
}
]
}
};
export const NON_COLUMN_KEYS = ['start_year', 'end_year'];
export const POSSIBLE_LABEL_FIELDS = [
'name',
'full_name',
'value',
'wri_standard_name',
'cw_title',
'title',
'slug',
'number'
];
export const POSSIBLE_VALUE_FIELDS = ['iso_code', 'iso_code3', 'id', 'value'];
export default {
DATA_EXPLORER_BLACKLIST,
DATA_EXPLORER_FIRST_TABLE_HEADERS,
DATA_EXPLORER_SECTIONS,
DATA_EXPLORER_METHODOLOGY_SOURCE,
DATA_EXPLORER_DEPENDENCIES,
DATA_EXPLORER_EXTERNAL_PREFIX,
DATA_EXPLORER_TO_MODULES_PARAMS,
MULTIPLE_LEVEL_SECTION_FIELDS,
GROUPED_SELECT_FIELDS,
DATA_EXPLORER_PER_PAGE,
POSSIBLE_LABEL_FIELDS,
POSSIBLE_VALUE_FIELDS
};
| JavaScript | 0 | @@ -203,18 +203,8 @@
s',%0A
- 'unit',%0A
'l
@@ -284,16 +284,26 @@
cator',%0A
+ 'unit',%0A
'defin
@@ -2478,16 +2478,69 @@
tegory'%0A
+ %7D,%0A subcategories: %7B%0A key: 'subcategory'%0A
%7D%0A
|
cb87aa8e84e2557ab31a9dbf892f256535ff880f | fix bug: undefined nodeName | Redirector.safariextension/redirector.js | Redirector.safariextension/redirector.js | function getTarget(element) {
if (element.nodeName == 'LINK' && element.type == 'text/css'){
return 'style';
}else{
return element.nodeName.toLowerCase();
}
}
safari.self.addEventListener("message", function(event){
console.log(evnet);
}, false);
document.addEventListener("beforeload", function(event){
var element = event.target;
var target = getTarget(element);
//check url
if (target == 'style' || target == 'script') {
response = safari.self.tab.canLoad(event, {
name : "checkUrl",
url : event.url,
type : target,
});
if (response.type == 'redirect'){
console.warn(target + ":" + event.url + " is redirected to " + response.to);
if (target == 'style') {
element.href = response.to;
event.preventDefault();
}else if (target == 'script'){
var script = document.createElement('script')
script.innerHTML = response.data;
document.head.insertBefore(script, document.head.firstChild);
event.preventDefault();
}
}
}
return;
}, true); | JavaScript | 0.00021 | @@ -363,16 +363,51 @@
target;%0A
+ if (!element.nodeName) return;%0A
var
@@ -439,13 +439,8 @@
t);%0A
- %0A
|
dd7be7687bb0057fbe038a54edb9a34718c8a2fc | Use initial input value if set | Resources/public/js/adapter/fancytree.js | Resources/public/js/adapter/fancytree.js | /**
* A tree browser adapter for the Fancytree library.
*
* @author Wouter J <wouter@wouterj.nl>
* @see https://github.com/mar10/fancytree
*/
var FancytreeAdapter = function (dataUrl) {
if (!window.jQuery || !jQuery.fn.fancytree) {
throw 'The FancytreeAdapter requires both jQuery and the FancyTree library.';
}
var requestNodeToFancytreeNode = function (requestNode) {
var fancytreeNode = {
// fixme: remove ugly replacing by just not putting stuff like this in the JSON response
title: requestNode.data.replace(' (not editable)', ''),
// fixme: also put the current node name in the JSON response, not just the complete path
key: requestNode.attr.id.match(/\/([^\/]+)$/)[1]
};
// fixme: have more descriptive JSON keys to determine if it has children
if (null != requestNode.state) {
fancytreeNode.folder = true;
}
if ('closed' == requestNode.state) {
fancytreeNode.lazy = true;
}
return fancytreeNode;
};
// FancyTree instance
var tree;
// jQuery instance of the tree output element
var $tree;
return {
bindToElement: function ($elem) {
if (!$elem instanceof jQuery) {
throw 'FancytreeAdapter can only be adapted to a jQuery object.';
}
$tree = $elem;
$tree.fancytree({
// the start data (root node + children)
source: { url: dataUrl },
// lazy load the children when a node is collapsed
lazyLoad: function (event, data) {
data.result = {
url: dataUrl,
data: { root: data.node.getKeyPath() }
};
},
// transform the JSON response into a data structure that's supported by FancyTree
postProcess: function (event, data) {
if (null == data.error) {
data.result = []
data.response.forEach(function (node) {
var sourceNode = requestNodeToFancytreeNode(node);
if (node.children) {
sourceNode.children = [];
node.children.forEach(function (leaf) {
sourceNode.children.push(requestNodeToFancytreeNode(leaf));
});
}
data.result.push(sourceNode);
});
} else {
data.result = {
// todo: maybe use a more admin friendly error message in prod?
error: 'An error occured while retrieving the nodes: ' + data.error
};
}
},
// always show the active node
activeVisible: true
});
tree = $tree.fancytree('getTree');
},
bindToInput: function ($input) {
// output active node to input field
$tree.fancytree('option', 'activate', function(event, data) {
$input.val(data.node.getKeyPath());
});
// change active node when the value of the input field changed
var tree = this.tree;
$input.on('change', function (e) {
tree.loadKeyPath($(this).val(), function (node, status) {
if ('ok' == status) {
node.setExpanded();
node.setActive();
}
});
});
}
};
};
| JavaScript | 0.000015 | @@ -3385,137 +3385,21 @@
-// change active node when the value of the input field changed%0A var tree = this.tree;%0A $input.on('change',
+var showKey =
fun
@@ -3405,17 +3405,19 @@
nction (
-e
+key
) %7B%0A
@@ -3449,21 +3449,11 @@
ath(
-$(this).val()
+key
, fu
@@ -3638,32 +3638,386 @@
%7D);%0A
+ %7D;%0A%0A // use initial input value as active node%0A $tree.bind('fancytreeinit', function (event, data) %7B%0A showKey($input.val());%0A %7D);%0A%0A // change active node when the value of the input field changed%0A $input.on('change', function (e) %7B%0A showKey($(this).val());%0A
%7D);%0A
|
302a85b8e97043ad521d2fbd07d1d9c4700ad097 | Fix cursor position on panel hide/show - not perfect, but easy. | js/chrome/splitter.js | js/chrome/splitter.js | $.fn.splitter = function () {
var $document = $(document),
$blocker = $('<div class="block"></div>'),
$body = $('body');
// blockiframe = $blocker.find('iframe')[0];
var splitterSettings = JSON.parse(localStorage.getItem('splitterSettings') || '[]');
return this.each(function () {
var $el = $(this),
guid = $.fn.splitter.guid++,
$parent = $el.parent(),
$prev = $el.prev(),
$handle = $('<div class="resize"></div>'),
dragging = false,
width = $parent.width(),
left = $parent.offset().left,
props = {
x: {
currentPos: $parent.offset().left,
multiplier: 1,
cssProp: 'left',
otherCssProp: 'right',
size: $parent.width(),
sizeProp: 'width',
moveProp: 'pageX',
init: {
top: 0,
bottom: 0,
width: 8,
'margin-left': '-5px',
height: '100%',
left: 'auto',
right: 'auto',
opacity: 0,
position: 'absolute',
cursor: 'ew-resize',
// border: 0,
// 'border-left': '1px solid rgba(218, 218, 218, 0.5)',
'z-index': 99999
}
},
y: {
currentPos: $parent.offset().top,
multiplier: -1,
size: $parent.height(),
cssProp: 'bottom',
otherCssProp: 'top',
size: $parent.height(),
sizeProp: 'height',
moveProp: 'pageY',
init: {
top: 'auto',
cursor: 'ns-resize',
bottom: 'auto',
height: 8,
width: '100%',
left: 0,
right: 0,
opacity: 0,
position: 'absolute',
border: 0,
'border-top': '1px solid rgba(218, 218, 218, 0.5)',
'z-index': 99999
}
}
},
type = 'x',
refreshTimer = null,
settings = splitterSettings[guid] || {};
var tracker = {
down: { x: null, y: null },
delta: { x: null, y: null },
track: false
};
$handle.bind('mousedown', function (event) {
tracker.down.x = event.pageX;
tracker.down.y = event.pageY;
tracker.delta = { x: null, y: null };
tracker.target = $handle[type == 'x' ? 'height' : 'width']() * 0.2;
});
/* Disable dynamic splitters for now - RS March 28, 2012 */
$document.bind('mousemove', function (event) {
if (dragging) {
tracker.delta.x = tracker.down.x - event.pageX;
tracker.delta.y = tracker.down.y - event.pageY;
var targetType = type == 'x' ? 'y' : 'x';
if (Math.abs(tracker.delta[targetType]) > tracker.target) {
$handle.trigger('change', targetType, event[props[targetType].moveProp]);
}
}
});
function moveSplitter(pos) {
var v = pos - props[type].currentPos,
split = 100 / props[type].size * v,
delta = (pos - settings[type]) * props[type].multiplier,
prevSize = $prev[props[type].sizeProp](),
elSize = $el[props[type].sizeProp]();
if (type === 'y') {
split = 100 - split;
}
// if prev panel is too small and delta is negative, block
if (prevSize < 100 && delta < 0) {
// ignore
} else if (elSize < 100 && delta > 0) {
// ignore
} else {
// allow sizing to happen
$el.css(props[type].cssProp, split + '%');
$prev.css(props[type].otherCssProp, (100 - split) + '%');
var css = {};
css[props[type].cssProp] = split + '%';
$handle.css(css);
settings[type] = pos;
splitterSettings[guid] = settings;
localStorage.setItem('splitterSettings', JSON.stringify(splitterSettings));
$document.trigger('sizeeditors');
}
}
$document.bind('mouseup touchend', function () {
dragging = false;
$blocker.remove();
$handle.css('opacity', '0');
$body.removeClass('dragging');
}).bind('mousemove touchmove', function (event) {
if (dragging) {
moveSplitter(event[props[type].moveProp] || event.originalEvent.touches[0][props[type].moveProp]);
}
});
$blocker.bind('mousemove touchmove', function (event) {
if (dragging) {
moveSplitter(event[props[type].moveProp] || event.originalEvent.touches[0][props[type].moveProp]);
}
});
$handle.bind('mousedown touchstart', function (e) {
dragging = true;
$body.append($blocker).addClass('dragging');
props[type].size = $parent[props[type].sizeProp]();
props[type].currentPos = 0; // is this really required then?
$prev = type === 'x' ? $handle.prevAll(':visible:first') : $handle.nextAll(':visible:first');;
e.preventDefault();
}).hover(function () {
$handle.css('opacity', '1');
}, function () {
if (!dragging) {
$handle.css('opacity', '0');
}
});
$handle.bind('init', function (event, x) {
$handle.css(props[type].init);
$blocker.css('cursor', type == 'x' ? 'ew-resize' : 'ns-resize');
if (type == 'y') {
$el.css('border-right', 0);
$prev.css('border-right', 0);
$prev.css('border-top', '1px solid #ccc');
} else {
// $el.css('border-right', '1px solid #ccc');
$el.css('border-top', 0);
$prev.css('border-right', '1px solid #ccc');
}
if ($el.is(':hidden')) {
$handle.hide();
} else {
$el.css('border-' + props[type].cssProp, '1px solid #ccc');
moveSplitter(x !== undefined ? x : $el.offset()[props[type].cssProp]);
}
}); //.trigger('init', settings.x || $el.offset().left);
$handle.bind('change', function (event, toType, value) {
$el.css(props[type].cssProp, '0');
$prev.css(props[type].otherCssProp, '0');
$el.css('border-' + props[type].cssProp, '0');
type = toType;
// if (type == 'y') {
// FIXME $prev should check visible
var $tmp = $el;
$el = $prev;
$prev = $tmp;
// } else {
// }
$el.css(props[type].otherCssProp, '0');
$prev.css(props[type].cssProp, '0');
// TODO
// reset top/bottom positions
// reset left/right positions
$handle.trigger('init', value || $el.offset()[props[type].cssProp] || props[type].size / 2);
});
$prev.css('width', 'auto');
$prev.css('height', 'auto');
$el.data('splitter', $handle);
$el.before($handle);
});
};
$.fn.splitter.guid = 0;
| JavaScript | 0 | @@ -3930,16 +3930,107 @@
ings));%0A
+%0A // todo: wait until animations have completed!%0A setTimeout(function () %7B%0A
@@ -4059,24 +4059,41 @@
eeditors');%0A
+ %7D, 120);%0A
%7D%0A
|
68e3a778f856bdb60098502eec11f3948a3fdabb | support latest in the url | BlazarUI/app/scripts/data/RepoBuildApi.js | BlazarUI/app/scripts/data/RepoBuildApi.js | /*global config*/
import Resource from '../services/ResourceProvider';
import Q from 'q';
import { findWhere, map, extend } from 'underscore';
import humanizeDuration from 'humanize-duration';
function _parse(resp) {
if (resp.startTimestamp && resp.endTimestamp) {
resp.duration = humanizeDuration(resp.endTimestamp - resp.startTimestamp, {round: true});
}
return resp;
}
function _fetchModuleNames(params) {
const moduleNamesPromise = new Resource({
url: `${config.apiRoot}/branches/${params.branchId}/modules`,
type: 'GET'
}).send();
return moduleNamesPromise;
}
function _fetchModuleNamesById(branchId) {
const moduleNamesPromise = new Resource({
url: `${config.apiRoot}/branches/${branchId}/modules`,
type: 'GET'
}).send();
return moduleNamesPromise;
}
function _fetchBranchBuildHistory(params) {
const branchBuildHistoryPromise = new Resource({
url: `${config.apiRoot}/builds/history/branch/${params.branchId}`,
type: 'GET'
}).send();
return branchBuildHistoryPromise;
}
function fetchRepoBuild(params, cb) {
return _fetchBranchBuildHistory(params).then((resp) => {
const repoBuild = findWhere(resp, {buildNumber: parseInt(params.buildNumber, 10)});
const repoBuildPromise = new Resource({
url: `${config.apiRoot}/branches/builds/${repoBuild.id}`,
type: 'GET'
}).send();
return repoBuildPromise.then((resp) => {
return cb(_parse(resp));
});
});
}
function fetchRepoBuildById(repoBuildId, cb) {
const repoBuildPromise = new Resource({
url: `${config.apiRoot}/branches/builds/${repoBuildId}`,
type: 'GET'
}).send();
return repoBuildPromise.then((resp) => {
return cb(_parse(resp));
});
}
function fetchModuleBuilds(params, cb) {
return _fetchBranchBuildHistory(params).then((resp) => {
const repoBuild = findWhere(resp, {buildNumber: parseInt(params.buildNumber, 10)});
const moduleBuildsPromise = new Resource({
url: `${config.apiRoot}/branches/builds/${repoBuild.id}/modules`,
type: 'GET'
}).send();
const moduleInfoPromise = _fetchModuleNames(params);
Q.spread([moduleInfoPromise, moduleBuildsPromise],
(moduleInfos, moduleBuilds) => {
const moduleBuildsWithNames = map(moduleBuilds, (build) => {
const moduleInfo = findWhere(moduleInfos, {id: build.moduleId});
const moduleInfoExtended = {
name: moduleInfo.name,
blazarPath: `/builds/branch/${params.branchId}/build/${params.buildNumber}/module/${moduleInfo.name}`
};
return extend(build, moduleInfoExtended);
});
cb(moduleBuildsWithNames);
});
});
}
function fetchModuleBuildsById(branchId, repoBuildId, buildNumber, cb) {
const moduleBuildsPromise = new Resource({
url: `${config.apiRoot}/branches/builds/${repoBuildId}/modules`,
type: 'GET'
}).send();
const moduleInfoPromise = _fetchModuleNamesById(branchId);
Q.spread([moduleInfoPromise, moduleBuildsPromise],
(moduleInfos, moduleBuilds) => {
const moduleBuildsWithNames = map(moduleBuilds, (build) => {
const moduleInfo = findWhere(moduleInfos, {id: build.moduleId});
const moduleInfoExtended = {
name: moduleInfo.name,
blazarPath: `/builds/branch/${branchId}/build/${buildNumber}/module/${moduleInfo.name}`
};
return extend(build, moduleInfoExtended);
});
cb(moduleBuildsWithNames);
});
}
function cancelBuild(params) {
return _fetchBranchBuildHistory(params).then((resp) => {
const repoBuild = findWhere(resp, {buildNumber: parseInt(params.buildNumber, 10)});
const cancelPromise = new Resource({
url: `${config.apiRoot}/branches/builds/${repoBuild.id}/cancel`,
type: 'POST'
}).send();
cancelPromise.error((error) => {
console.warn(error); // TODO: be better
});
});
}
export default {
fetchRepoBuild: fetchRepoBuild,
fetchRepoBuildById: fetchRepoBuildById,
fetchModuleBuilds: fetchModuleBuilds,
fetchModuleBuildsById: fetchModuleBuildsById,
cancelBuild: cancelBuild
}; | JavaScript | 0 | @@ -114,16 +114,21 @@
, extend
+, max
%7D from
@@ -141,16 +141,16 @@
score';%0A
-
import h
@@ -1128,37 +1128,185 @@
(resp) =%3E %7B%0A
-const
+let repoBuild;%0A%0A if (params.buildNumber === 'latest') %7B%0A repoBuild = max(resp, (build) =%3E %7B return build.buildNumber; %7D);%0A %7D%0A%0A else %7B%0A
repoBuild = fin
@@ -1360,32 +1360,39 @@
dNumber, 10)%7D);%0A
+ %7D%0A%0A
const repoBu
@@ -1967,37 +1967,185 @@
(resp) =%3E %7B%0A
-const
+let repoBuild;%0A%0A if (params.buildNumber === 'latest') %7B%0A repoBuild = max(resp, (build) =%3E %7B return build.buildNumber; %7D);%0A %7D%0A%0A else %7B%0A
repoBuild = fin
@@ -2199,32 +2199,39 @@
dNumber, 10)%7D);%0A
+ %7D%0A%0A
const module
@@ -2803,22 +2803,25 @@
build/$%7B
-params
+repoBuild
.buildNu
@@ -4200,17 +4200,16 @@
);%0A %7D);
-
%0A%7D%0A%0Aexpo
@@ -4412,10 +4412,11 @@
elBuild%0A
-
%7D;
+%0A
|
b83814b40617db82dfd1eca9889c5c889b221e55 | Update ValueDesc_Other.js | CNN/Unpacker/ValueDesc/ValueDesc_Other.js | CNN/Unpacker/ValueDesc/ValueDesc_Other.js | export { channelCount1_pointwise1Before };
export { Pointwise_HigherHalfDifferent };
export { Depthwise_HigherHalfDifferent };
export { AvgMax_Or_ChannelMultiplier };
export { WhetherShuffleChannel };
import { Int } from "./ValueDesc_Base.js";
/** Describe id, range, name of channelCount1_pointwise1Before.
*
* Convert number value into integer between [ -5, ( 10 * 1024 ) ] representing operation:
* - -5: ONE_INPUT_HALF_THROUGH
* - -4: ONE_INPUT_HALF_THROUGH_EXCEPT_DEPTHWISE1
* - -3: TWO_INPUTS_CONCAT_POINTWISE21_INPUT1
* - -2: ONE_INPUT_TWO_DEPTHWISE
* - -1: ONE_INPUT_ADD_TO_OUTPUT
* - 0: ONE_INPUT
* - [ 1, ( 10 * 1024 ) ]: TWO_INPUTS with the second input channel count between 1 and 10240 (inclusive). (without names defined.)
*/
class channelCount1_pointwise1Before extends Int {
constructor() {
super( -5, ( 10 * 1024 ), [
"ONE_INPUT_HALF_THROUGH", // (-5) ShuffleNetV2_ByMobileNetV1's body/tail
"ONE_INPUT_HALF_THROUGH_EXCEPT_DEPTHWISE1", // (-4) ShuffleNetV2_ByMobileNetV1's head
"TWO_INPUTS_CONCAT_POINTWISE21_INPUT1", // (-3) ShuffleNetV2's body/tail
"ONE_INPUT_TWO_DEPTHWISE", // (-2) ShuffleNetV2's head (and ShuffleNetV2_ByPointwise22's head) (simplified)
"ONE_INPUT_ADD_TO_OUTPUT", // (-1) MobileNetV2
"ONE_INPUT", // ( 0) MobileNetV1 (General Pointwise1-Depthwise1-Pointwise2)
// "TWO_INPUTS_1", "TWO_INPUTS_2", ..., "TWO_INPUTS_10240".
//
// ShuffleNetV2's (and ShuffleNetV2_ByPointwise22's) body/tail
//
// (2021/07/13 Remarked) Do not define these names because they will occupy too many memory.
//
//... [ ... new Array( 10 * 1024 ).keys() ].map( x => "TWO_INPUTS_" + ( x + 1 ) )
] );
}
}
/** The only one ValueDesc.channelCount1_pointwise1Before instance. */
channelCount1_pointwise1Before.Singleton = new channelCount1_pointwise1Before;
/** Describe id, range, name of the processing mode of pointwise convolution's higher half channels.
*
* Convert number value into integer between [ 0, 4 ] representing:
* - 0: NONE
* - 1: HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH
* - 2: HIGHER_HALF_COPY_LOWER_HALF
* - 3: HIGHER_HALF_POINTWISE22
* - 4: HIGHER_HALF_PASS_THROUGH
*/
class Pointwise_HigherHalfDifferent extends Int {
constructor() {
super( 0, 4, [
"NONE", // (0) (for normal poitwise convolution. no higher half different.)
"HIGHER_HALF_COPY_LOWER_HALF__LOWER_HALF_PASS_THROUGH", // (1) (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head)
"HIGHER_HALF_COPY_LOWER_HALF", // (2) (for pointwise1 of ShuffleNetV2_ByMopbileNetV1's head)
"HIGHER_HALF_POINTWISE22", // (3) (for pointwise2 of ShuffleNetV2_ByMopbileNetV1's head)
"HIGHER_HALF_PASS_THROUGH", // (4) (for pointwise1/pointwise2 of ShuffleNetV2_ByMopbileNetV1's body/tail)
] );
}
}
/** The only one ValueDesc.Pointwise_HigherHalfDifferent instance. */
Pointwise_HigherHalfDifferent.Singleton = new Pointwise_HigherHalfDifferent;
//!!! ...unfinished... (2021/12/23) Depthwise_HigherHalfDifferent
/** Describe id, range, name of the processing mode of depthwise convolution's higher half channels.
*
* Convert number value into integer between [ 0, 4 ] representing:
* - 0: NONE
* - 1: HIGHER_HALF_DEPTHWISE2
* - 2: HIGHER_HALF_PASS_THROUGH
*/
class Depthwise_HigherHalfDifferent extends Int {
constructor() {
super( 0, 2, [
"NONE", // (0) (for normal depthwise convolution. no higher half different.)
"HIGHER_HALF_DEPTHWISE2", // (1) (for depthwise1 of ShuffleNetV2_ByMopbileNetV1's head)
"HIGHER_HALF_PASS_THROUGH", // (2) (for depthwise1 of ShuffleNetV2_ByMopbileNetV1's body/tail)
] );
}
}
/** The only one ValueDesc.Depthwise_HigherHalfDifferent instance. */
Depthwise_HigherHalfDifferent.Singleton = new Depthwise_HigherHalfDifferent;
/** Describe depthwise operation's id, range, name.
*
* Convert number value into integer between [ -2, 32 ] representing depthwise operation:
* - -2: average pooling. (AVG)
* - -1: maximum pooling. (MAX)
* - 0: no depthwise operation. (NONE)
* - [ 1, 32 ]: depthwise convolution with channel multiplier between 1 and 32 (inclusive).
*/
class AvgMax_Or_ChannelMultiplier extends Int {
constructor() {
super( -2, 32, [ "AVG", "MAX", "NONE" ] );
}
}
/** The only one ValueDesc.AvgMax_Or_ChannelMultiplier instance. */
AvgMax_Or_ChannelMultiplier.Singleton = new AvgMax_Or_ChannelMultiplier;
/** Describe id, range, name of WhetherShuffleChannel.
*
* Convert number value into integer between [ 0, 3 ] representing operation:
* - 0: NONE (i.e. NotShuffleNet_NotMobileNet, or MobileNetV2)
* - 1: BY_POINTWISE22 (i.e. ShuffleNetV2_ByPointwise22)
* - 2: BY_CHANNEL_SHUFFLER (i.e. ShuffleNetV2)
- 3: BY_MOBILE_NET_V1 (i.e. ShuffleNetV2_ByMobileNetV1)
*/
class WhetherShuffleChannel extends Int {
constructor() {
super( 0, 2, [
"NONE", // (0)
"BY_CHANNEL_SHUFFLER", // (1)
"BY_POINTWISE22", // (2)
"BY_MOBILE_NET_V1", // (3)
] );
}
}
/** The only one ValueDesc.WhetherShuffleChannel instance. */
WhetherShuffleChannel.Singleton = new WhetherShuffleChannel;
| JavaScript | 0.000001 | @@ -3229,74 +3229,8 @@
;%0A%0A%0A
-//!!! ...unfinished... (2021/12/23) Depthwise_HigherHalfDifferent%0A
/**
@@ -3371,33 +3371,33 @@
er between %5B 0,
-4
+2
%5D representing:
|
832bf227e89c32c489eb58b57fabf51c22d502fd | disable cool animations for a while since it's already laggy | js/post-hover-tree.js | js/post-hover-tree.js | /**
* post-hover-tree.js
*
* Post hover tree. Because post-hover.js isn't russian enough.
*
* Usage:
* $config['additional_javascript'][] = 'js/jquery.min.js';
* $config['additional_javascript'][] = 'js/settings.js';
* $config['additional_javascript'][] = 'js/post-hover-tree.js';
*
*/
$(document).ready(function () {
if (settings.postHover) {
var hovering = false;
var id;
function init_hover_tree() {
$("div.body > a, .mentioned > a").hover(function() {
hovering = true;
if(id = $(this).text().match(/^>>(\d+)$/)) {
$("#reply_" + id[1]).clone().addClass("hover").css({'position': 'absolute', 'top': $(this).offset().top+20, 'left': $(this).offset().left+20 }).hide().appendTo("body").fadeIn(200);
} else {
return;
}
}, function() {
hovering = true;
$(".hover").hover(function() {
hovering = true;
$("#reply_" + id[1]).trigger(init_hover_tree());
}, function() {
hovering = false;
})
});
$("body").mousemove(function() {
if (!(hovering) && ($(".hover").is(":visible"))) {
$(".hover").fadeOut(200);
setTimeout(function() {
$(".hover").remove();
}, 500);
}
})
}
init_hover_tree(document);
// allow to work with auto-reload.js, etc.
$(document).bind('new_post', function(e, post) {
init_hover_tree(post);
});
}
}) | JavaScript | 0 | @@ -768,15 +768,8 @@
%7D).
-hide().
appe
@@ -784,20 +784,8 @@
dy%22)
-.fadeIn(200)
;%0A
@@ -1288,54 +1288,8 @@
) %7B%0A
- $(%22.hover%22).fadeOut(200);%0A
|
f036c722289a75c513807cda969360071b068f5f | Modify FPS Stats presentation | js/stats_bootstrap.js | js/stats_bootstrap.js | head.js("lib/js/stats.js", function() {
var stats = new Stats();
stats.setMode(0); // 0: fps, 1: ms
// Align top-left
stats.domElement.style.position = 'absolute';
stats.domElement.style.left = '0px';
stats.domElement.style.top = '0px';
document.body.appendChild( stats.domElement );
window.stats = stats;
setInterval( function () {
stats.update();
}, 1000 / 60 );
});
| JavaScript | 0 | @@ -195,21 +195,22 @@
yle.
-left = '0px';
+zIndex = 100;%0A
%0A s
@@ -229,25 +229,194 @@
ent.
-style.top = '0px'
+children%5B 0 %5D.children%5B 0 %5D.style.color = %22#aaa%22;%0A stats.domElement.children%5B 0 %5D.style.background = %22transparent%22;%0A stats.domElement.children%5B 0 %5D.children%5B 1 %5D.style.display = %22none%22
;%0A%0A
|
2bcf1a7c537fa31aa772005b5d4d5b5420371cd0 | Correct client key for production | js/wrangler-config.js | js/wrangler-config.js | wrangler.clientKey = "58E26CE2-C218-11E4-A971-4464D61CF0AC"; // "0F03372E-1078-11E5-BCFA-5FDDE71C24E1";
wrangler.anonECI = "85255500-0b65-0130-243c-00163ebcdddd";
wrangler.callbackURL = "http://devtools.picolabs.io/code.html";
wrangler.host = "kibdev.kobj.net"; // change to cs.kobj.net when in production
wrangler.login_server = "kibdev.kobj.net"; // change to accounts.kobj.net when in production
wrangler.eventPath = 'sky/event';
wrangler.functionPath ='sky/cloud';
// oAuth key and eci for local jekyll development.
/*wrangler.clientKey = "84920CCC-1082-11E5-BAFA-BC3F2D0A6675";
wrangler.anonECI = "85255500-0b65-0130-243c-00163ebcdddd";
wrangler.callbackURL = "http://0.0.0.0:4000/code.html";
wrangler.host = "kibdev.kobj.net"; // change to cs.kobj.net when in production
wrangler.login_server = "kibdev.kobj.net"; // change to accounts.kobj.net when in production
*/
| JavaScript | 0.000001 | @@ -1,107 +1,164 @@
-wrangler.clientKey = %2258E26CE2-C218-11E4-A971-4464D61CF0AC%22; // %220F03372E-1078-11E5-BCFA-5FDDE71C24E1%22;
+// This is the client key for devtools (in pjw account)%0Awrangler.clientKey = %2263D2ED70-A81D-11E5-AE52-D18AE71C24E1%22; // %2258E26CE2-C218-11E4-A971-4464D61CF0AC%22;
%0Awra
|
52599f16ad4b1c36fb0a9f4ab414c46e23648ea7 | Bump copyright date. | awx/ui/client/lib/components/components.strings.js | awx/ui/client/lib/components/components.strings.js | function ComponentsStrings (BaseString) {
BaseString.call(this, 'components');
const { t } = this;
const ns = this.components;
ns.REPLACE = t.s('REPLACE');
ns.REVERT = t.s('REVERT');
ns.ENCRYPTED = t.s('ENCRYPTED');
ns.OPTIONS = t.s('OPTIONS');
ns.SHOW = t.s('SHOW');
ns.HIDE = t.s('HIDE');
ns.message = {
REQUIRED_INPUT_MISSING: t.s('Please enter a value.'),
INVALID_INPUT: t.s('Invalid input for this type.')
};
ns.file = {
PLACEHOLDER: t.s('CHOOSE A FILE')
};
ns.form = {
SUBMISSION_ERROR_TITLE: t.s('Unable to Submit'),
SUBMISSION_ERROR_MESSAGE: t.s('Unexpected server error. View the console for more information'),
SUBMISSION_ERROR_PREFACE: t.s('Unexpected Error')
};
ns.group = {
UNSUPPORTED_ERROR_PREFACE: t.s('Unsupported input type')
};
ns.label = {
PROMPT_ON_LAUNCH: t.s('Prompt on launch')
};
ns.select = {
UNSUPPORTED_TYPE_ERROR: t.s('Unsupported display model type'),
EMPTY_PLACEHOLDER: t.s('NO OPTIONS AVAILABLE')
};
ns.textarea = {
SSH_KEY_HINT: t.s('HINT: Drag and drop an SSH private key file on the field below.')
};
ns.lookup = {
NOT_FOUND: t.s('That value was not found. Please enter or select a valid value.')
};
ns.truncate = {
DEFAULT: t.s('Copy full revision to clipboard.'),
COPIED: t.s('Copied to clipboard.')
};
ns.layout = {
CURRENT_USER_LABEL: t.s('Logged in as'),
VIEW_DOCS: t.s('View Documentation'),
LOGOUT: t.s('Logout'),
DASHBOARD: t.s('Dashboard'),
JOBS: t.s('Jobs'),
SCHEDULES: t.s('Schedules'),
PORTAL_MODE: t.s('Portal Mode'),
PROJECTS: t.s('Projects'),
CREDENTIALS: t.s('Credentials'),
CREDENTIAL_TYPES: t.s('Credential Types'),
INVENTORIES: t.s('Inventories'),
TEMPLATES: t.s('Templates'),
ORGANIZATIONS: t.s('Organizations'),
USERS: t.s('Users'),
TEAMS: t.s('Teams'),
INVENTORY_SCRIPTS: t.s('Inventory Scripts'),
NOTIFICATIONS: t.s('Notifications'),
MANAGEMENT_JOBS: t.s('Management Jobs'),
INSTANCES: t.s('Instances'),
INSTANCE_GROUPS: t.s('Instance Groups'),
APPLICATIONS: t.s('Applications'),
SETTINGS: t.s('Settings'),
FOOTER_ABOUT: t.s('About'),
FOOTER_COPYRIGHT: t.s('Copyright © 2017 Red Hat, Inc.')
};
ns.relaunch = {
DEFAULT: t.s('Relaunch using the same parameters'),
HOSTS: t.s('Relaunch using host parameters'),
DROPDOWN_TITLE: t.s('Relaunch On'),
ALL: t.s('All'),
FAILED: t.s('Failed')
};
ns.list = {
DEFAULT_EMPTY_LIST: t.s('Please add items to this list.')
};
}
ComponentsStrings.$inject = ['BaseStringService'];
export default ComponentsStrings;
| JavaScript | 0 | @@ -2456,9 +2456,9 @@
201
-7
+8
Red
|
33211dc39f4ff171fe9604709e676671b3587398 | fix integration test | tests/integration/integration.test.js | tests/integration/integration.test.js | /* eslint-disable no-console */
import chai from 'chai';
import dirty from 'dirty-chai';
import sinonChai from 'sinon-chai';
import sinon from 'sinon';
import fs from 'fs';
import path from 'path';
import shell from 'shelljs';
import electron from 'electron';
import { Application } from 'spectron';
import mockery from 'mockery';
import paths from '../helpers/paths';
import meteorDesktop from '../../lib/index';
shell.config.fatal = true;
chai.use(sinonChai);
chai.use(dirty);
const { describe, it } = global;
const { expect } = chai;
/**
* This is first experimental integration test.
*/
let appDir = '';
/**
* Waits until a promise from a function finally returns true.
* @param {Function} functionReturningPromise - function to test
* @param {number} ms - expiration timeout in milliseconds
* @returns {Promise}
*/
function waitFor(functionReturningPromise, ms = 10000) {
return new Promise((resolve, reject) => {
let invokerTimeout;
let timeout;
const invokeFunction = () =>
functionReturningPromise()
.then((result) => {
console.log(result);
if (result) {
clearTimeout(invokerTimeout);
clearTimeout(timeout);
resolve();
} else {
invokerTimeout = setTimeout(invokeFunction, 500);
}
})
.catch(() => {
invokerTimeout = setTimeout(invokeFunction, 500);
});
invokeFunction();
timeout = setTimeout(() => {
clearTimeout(invokerTimeout);
reject('timeout expired on waitFor');
}, ms);
});
}
/**
* Waits for the app to load and appear.
* @param {Object} app - test app
* @returns {{app: (Application|*), window: *}}
*/
async function waitForApp(app) {
await app.client.waitUntilWindowLoaded();
const window = app.browserWindow;
// Wait for the main window for max 30seconds. Adjust to your app.
await waitFor(window.isVisible, 30000);
expect(await app.client.getWindowCount()).to.equal(1);
await app.client.waitUntil(
async () => await app.client.execute(
() => document.readyState === 'complete'
)
);
return { app, window };
}
describe('desktop', () => {
let MeteorDesktop;
before(() => {
appDir = path.join(paths.testsTmpPath, 'test-desktop');
});
beforeEach(() => {
try {
fs.unlinkSync('meteor.log');
} catch (e) {
// No worries...
}
});
describe('add to scripts', () => {
let exitStub;
before(() => {
mockery.registerMock('path', {
resolve: dir => dir,
join: () => `${appDir}${path.sep}package.json`
});
mockery.enable({
warnOnReplace: false,
warnOnUnregistered: false
});
});
after(() => {
mockery.deregisterMock('path');
mockery.disable();
exitStub.restore();
});
it('should add a `desktop` entry in package.json', () => {
exitStub = sinon.stub(process, 'exit');
require('../../lib/scripts/addToScripts'); // eslint-disable-line
const packageJson = JSON.parse(fs.readFileSync(path.join(appDir, 'package.json'), 'utf8'));
expect(exitStub).to.have.callCount(0);
expect(packageJson.scripts.desktop).to.be.equal('meteor-desktop');
});
});
describe('build with params --init -b', () => {
let exitStub;
let app;
after(async () => {
exitStub.restore();
if (app && app.isRunning()) {
await app.stop();
}
});
it('should create a build', async () => {
exitStub = sinon.stub(process, 'exit', () => {
try {
console.log(fs.readFileSync('meteor.log', 'utf8'));
} catch (e) {
// Nothing to do.
}
process.exit(1);
});
// Load plugins directly from the package instead of those published to atmosphere.
process.env.METEOR_PACKAGE_DIRS = path.resolve(path.join(__dirname, '..', '..', 'plugins'));
MeteorDesktop = meteorDesktop(
appDir,
appDir,
{ ddpUrl: 'http://127.0.0.1:3080', init: true, build: true }
);
// Build the app.
await MeteorDesktop.build();
// Run it.
app = new Application({
path: electron,
args: [path.join(appDir, '.meteor', 'desktop-build')],
requireName: 'electronRequire',
env: { NODE_ENV: 'test', ELECTRON_ENV: 'test', METEOR_DESKTOP_NO_SPLASH_SCREEN: 1 }
});
await app.start();
await waitForApp(app);
const title = await app.client.getTitle();
expect(title).to.equal('test-desktop');
const text = await app.client.getText('h1');
expect(text).to.equal('Welcome to Meteor!');
}).timeout(10 * 60000);
});
});
| JavaScript | 0 | @@ -3674,20 +3674,24 @@
arams --
-init
+scaffold
-b', ()
@@ -4584,12 +4584,16 @@
0',
-init
+scaffold
: tr
|
9b9cb14a629de5bb6bda12d613b3372fedf8ffd3 | Make root kill timeout configurable. | listen.bin.js | listen.bin.js | #!/usr/bin/env node
/*
___ usage ___ en_US ___
usage: olio <socket> [command] <args>
--help display this message
--socket <string> socket
___ $ ___ en_US ___
unknown argument:
unknown argument: %s
___ . ___
*/
require('arguable')(module, function (program, callback) {
// Convert an HTTP request into a raw socket.
var Downgrader = require('downgrader')
// Contextualized callbacks and event handlers.
var Operation = require('operation')
var http = require('http')
var delta = require('delta')
var Descendent = require('descendent')
var logger = require('prolific.logger').createLogger('olio')
var Destructible = require('destructible')
// TODO This ought to be configurable.
var destructible = new Destructible(5000, 'olio/listen.bin')
program.on('shutdown', destructible.destroy.bind(destructible))
var Shuttle = require('prolific.shuttle')
var shuttle = Shuttle.shuttle(program, logger)
destructible.destruct.wait(shuttle, 'close')
destructible.completed.wait(callback)
var children = program.argv.map(JSON.parse.bind(JSON))
program.required('socket')
var descendent = new Descendent(process)
destructible.destruct.wait(descendent, 'destroy')
var cadence = require('cadence')
var Listener = require('./listener')
cadence(function (async) {
async(function () {
destructible.monitor('listener', Listener, descendent, program.ultimate.socket, async())
}, function (listener) {
var downgrader = new Downgrader
downgrader.on('socket', Operation([ listener, 'socket' ]))
var server = http.createServer(listener.reactor.middleware)
server.on('upgrade', Operation([ downgrader, 'upgrade' ]))
destructible.destruct.wait(server, 'close')
// Passing sockets around makes it hard for us to ensure that we are
// going to destroy them. They could be in a pipe on the way down to a
// child that exits before getting the message. I've not seen evidence
// that delivery is guaranteed. When I leave a listener outside of my
// Descendent module to see if I can catch the straggling message, I
// don't see it and we exit with an exception thrown from within
// Node.js, assertion failures from within the C++. We `unref` here to
// surrender any socket handles in the process of being passed to
// children.
//
// We should always have a child of some kind so we don't have to worry
// about this unref'ed server causing us to exit early.
server.unref()
async(function () {
server.listen(program.ultimate.socket, async())
}, function () {
listener.children(children)
program.ready.unlatch()
})
})
})(destructible.monitor('initialize', true))
})
| JavaScript | 0 | @@ -103,18 +103,17 @@
--help
-
+%0A
@@ -137,16 +137,125 @@
message%0A
+%0A --kill %3Cnumber%3E%0A number of milliseconds to wait before declaring child processess hung%0A%0A
@@ -275,17 +275,55 @@
ing%3E
+%0A
-socket
+ path for UNIX domain socket server
%0A%0A
@@ -844,27 +844,23 @@
var
-Destructibl
+coalesc
e = requ
@@ -868,65 +868,171 @@
re('
-destructible
+extant
')%0A
+%0A
-// TODO This ought to be configurable.
+var kill = +coalesce(program.ultimate.kill, 5000)%0A program.assert(kill, 'kill must be an integer')%0A%0A var Destructible = require('destructible')
%0A
@@ -1068,20 +1068,20 @@
uctible(
-5000
+kill
, 'olio/
|
d9de32f802d26608517496fcb8c89f1072f2b659 | Fix inconsistent quotes | tests/js/app/modules/testMediaCard.js | tests/js/app/modules/testMediaCard.js | const Endless = imports.gi.Endless;
const Gtk = imports.gi.Gtk;
const InstanceOfMatcher = imports.tests.InstanceOfMatcher;
const CssClassMatcher = imports.tests.CssClassMatcher;
const Utils = imports.tests.utils;
Utils.register_gresource();
const MediaObjectModel = imports.search.mediaObjectModel;
const MediaCard = imports.app.modules.mediaCard;
Gtk.init(null);
describe ('Media Infobox', function () {
let imageObject;
beforeEach(function () {
jasmine.addMatchers(CssClassMatcher.customMatchers);
jasmine.addMatchers(InstanceOfMatcher.customMatchers);
Utils.register_gresource();
imageObject = new MediaObjectModel.ImageObjectModel({
caption: "foo",
license: "bar",
copyright_holder: "baz",
get_content_stream: () => null,
content_type: 'image/jpeg',
});
});
it ('hides separator when caption or attribution not visible', function () {
let noCaption = new MediaObjectModel.ImageObjectModel({
license: "bar",
copyright_holder: "baz",
get_content_stream: () => null,
content_type: 'image/jpeg',
});
let noAttribution = new MediaObjectModel.ImageObjectModel({
caption: "foo",
get_content_stream: () => null,
content_type: 'image/jpeg',
});
let media_card = new MediaCard.MediaCard({
model: imageObject,
});
expect(media_card._separator.visible).toBe(true);
media_card = new MediaCard.MediaCard({
model: noCaption,
});
expect(media_card._separator.visible).toBe(false);
media_card = new MediaCard.MediaCard({
model: noAttribution,
});
expect(media_card._separator.visible).toBe(false);
});
it('has labels that understand Pango markup', function () {
let card = new MediaCard.MediaCard({
model: new MediaObjectModel.ImageObjectModel({
copyright_holder: '!!!',
caption: '@@@',
get_content_stream: () => null,
}),
});
expect(Gtk.test_find_label(card, '*!!!*').use_markup).toBeTruthy();
expect(Gtk.test_find_label(card, '*@@@*').use_markup).toBeTruthy();
});
describe ('Attribution button', function () {
let card;
let license_shortname;
let copyright_holder = 'Bruce Lee';
let attribution;
let attribution_button;
it ('displays license file when license is known', function () {
license_shortname = 'CC BY 4.0';
let license_description = Endless.get_license_display_name(license_shortname);
card = new MediaCard.MediaCard({
model: new MediaObjectModel.ImageObjectModel({
license: license_shortname,
copyright_holder: copyright_holder,
get_content_stream: () => null,
}),
});
attribution = (license_description + ' - ' + copyright_holder).toUpperCase();
attribution_button = Gtk.test_find_label(card, attribution).get_parent();
expect(attribution_button.sensitive).toBe(true);
});
it ('does not display license file when license is unknown', function () {
license_shortname = 'Bogus License';
card = new MediaCard.MediaCard({
model: new MediaObjectModel.ImageObjectModel({
license: license_shortname,
copyright_holder: copyright_holder,
get_content_stream: () => null,
}),
});
attribution = ('Bruce Lee').toUpperCase();
attribution_button = Gtk.test_find_label(card, attribution).get_parent();
expect(attribution_button.sensitive).toBe(false);
});
});
});
| JavaScript | 0 | @@ -689,37 +689,37 @@
caption:
-%22foo%22
+'foo'
,%0A li
@@ -717,37 +717,37 @@
license:
-%22bar%22
+'bar'
,%0A co
@@ -754,37 +754,37 @@
pyright_holder:
-%22baz%22
+'baz'
,%0A ge
@@ -1044,13 +1044,13 @@
se:
-%22bar%22
+'bar'
,%0A
@@ -1081,13 +1081,13 @@
er:
-%22baz%22
+'baz'
,%0A
@@ -1274,13 +1274,13 @@
on:
-%22foo%22
+'foo'
,%0A
|
9db0b67b6d0957327a473a13321f829763dd12e5 | Test 3 | webpack/webpack.config.production.babel.js | webpack/webpack.config.production.babel.js | const webpack = require('webpack');
const baseConfig = require('./webpack.config.base.babel');
module.exports = {
...baseConfig,
devtool: 'source-map',
plugins: [
...baseConfig.plugins,
new webpack.optimize.ModuleConcatenationPlugin(),
new webpack.DefinePlugin({
__DEV__: false,
'process.env.NODE_ENV': JSON.stringify('production'),
'process.env.HOT': JSON.stringify(null)
})
]
};
| JavaScript | 0.000001 | @@ -194,62 +194,8 @@
ns,%0A
- new webpack.optimize.ModuleConcatenationPlugin(),%0A
|
c35678bb3e64657e7c9bb56c4265395658392122 | add 1 sat buffer to fee limits | utils/crypto.js | utils/crypto.js | import get from 'lodash/get'
import { address } from 'bitcoinjs-lib'
import lightningRequestReq from 'bolt11'
import coininfo from 'coininfo'
export const networks = {
bitcoin: {
mainnet: coininfo.bitcoin.main.toBitcoinJS(),
testnet: coininfo.bitcoin.test.toBitcoinJS(),
regtest: coininfo.bitcoin.regtest.toBitcoinJS(),
},
litecoin: {
mainnet: coininfo.litecoin.main.toBitcoinJS(),
testnet: coininfo.litecoin.test.toBitcoinJS(),
},
}
export const coinTypes = {
bitcoin: {
mainnet: 'bitcoin',
testnet: 'testnet',
regtest: 'regtest',
},
litecoin: {
mainnet: 'litecoin',
testnet: 'litecoin_testnet',
},
}
/**
* decodePayReq - Decodes a payment request.
*
* @param {string} payReq Payment request
* @param {boolean} addDefaults Boolean indicating whether to inject default values (default=true)
* @returns {*} Decoded payment request
*/
export const decodePayReq = (payReq, addDefaults = true) => {
const data = lightningRequestReq.decode(payReq)
const expiry = data.tags.find(t => t.tagName === 'expire_time')
if (addDefaults && !expiry) {
data.tags.push({
tagName: 'expire_time',
data: 3600,
})
data.timeExpireDate = data.timestamp + 3600
data.timeExpireDateString = new Date(data.timeExpireDate * 1000).toISOString()
}
return data
}
/**
* formatValue - Turns parsed number into a string.
*
* @param {number|string} integer Integer part
* @param {number|string} fractional Fractional part
* @returns {*} Formatted value
*/
export const formatValue = (integer, fractional) => {
let value
if (fractional && fractional.length > 0) {
value = `${integer}.${fractional}`
} else {
// Empty string means `XYZ.` instead of just plain `XYZ`.
if (fractional === '') {
value = `${integer}.`
} else {
value = `${integer}`
}
}
return value
}
/**
* parseNumber - Splits number into integer and fraction.
*
* @param {number|string} _value Value to parse
* @param {number} precision Decimal precision
* @returns {Array} Parsed value
*/
export const parseNumber = (_value, precision) => {
let value = String(_value || '')
if (typeof _value === 'string') {
value = _value.replace(/[^0-9.]/g, '')
}
let integer = null
let fractional = null
if (value * 1.0 < 0) {
value = '0.0'
}
// pearse integer and fractional value so that we can reproduce the same string value afterwards
// [0, 0] === 0.0
// [0, ''] === 0.
// [0, null] === 0
if (value.match(/^[0-9]*\.[0-9]*$/)) {
;[integer, fractional] = value.toString().split(/\./)
if (!fractional) {
fractional = ''
}
} else {
integer = value
}
// Limit fractional precision to the correct number of decimal places.
if (fractional && fractional.length > precision) {
fractional = fractional.substring(0, precision)
}
return [integer, fractional]
}
/**
* isOnchain - Test to see if a string is a valid on-chain address.
*
* @param {string} input Value to check
* @param {string} chain Chain name
* @param {string} network Network name
* @returns {boolean} Boolean indicating whether the address is a valid on-chain address
*/
export const isOnchain = (input, chain, network) => {
if (!input || !chain || !network) {
return false
}
try {
address.toOutputScript(input, networks[chain][network])
return true
} catch (e) {
return false
}
}
/**
* isLn - Test to see if a string is a valid lightning address.
*
* @param {string} input Value to check
* @param {string} chain Chain name
* @param {string} network Network name
* @returns {boolean} Boolean indicating whether the address is a lightning address
*/
export const isLn = (input, chain = 'bitcoin', network = 'mainnet') => {
if (!input || typeof input !== 'string') {
return false
}
try {
const decoded = lightningRequestReq.decode(input)
if (decoded.coinType !== get(coinTypes, `${chain}.${network}`)) {
throw new Error('Invalid coin type')
}
return true
} catch (e) {
return false
}
}
/**
* getNodeAlias - Get a nodes alias.
*
* @param {string} pubkey pubKey of node to fetch alias for.
* @param {Array} nodes listof nodes to search.
* @returns {string} Node alias, if found
*/
export const getNodeAlias = (pubkey, nodes = []) => {
if (!pubkey) {
return null
}
const node = nodes.find(n => n.pub_key === pubkey)
if (node && node.alias.length) {
return node.alias
}
return null
}
/**
* getMinFee - Given a list of routest, find the minimum fee.
*
* @param {*} routes List of routes
* @returns {number} minimum fee rounded up to the nearest satoshi
*/
export const getMinFee = (routes = []) => {
if (!routes || !routes.length) {
return null
}
return routes.reduce((min, b) => Math.min(min, b.total_fees), routes[0].total_fees)
}
/**
* getMaxFee - Given a list of routest, find the maximum fee.
*
* @param {*} routes List of routes
* @returns {number} maximum fee
*/
export const getMaxFee = routes => {
if (!routes || !routes.length) {
return null
}
return routes.reduce((max, b) => Math.max(max, b.total_fees), routes[0].total_fees)
}
/**
* getFeeRange - Given a list of routest, find the maximum and maximum fee.
*
* @param {*} routes List of routes
* @returns {{min:number, max:number}} object with keys `min` and `max`
*/
export const getFeeRange = (routes = []) => ({
min: getMinFee(routes),
max: getMaxFee(routes),
})
| JavaScript | 0 | @@ -4758,38 +4758,43 @@
turn null%0A %7D%0A
-return
+const fee =
routes.reduce((
@@ -4846,32 +4846,132 @@
s%5B0%5D.total_fees)
+%0A%0A // Add one to the fee to add room for accuracy error when using as a fee limit.%0A return fee + 1
%0A%7D%0A%0A/**%0A * getMa
@@ -5194,22 +5194,27 @@
l%0A %7D%0A
-return
+const fee =
routes.
@@ -5282,16 +5282,116 @@
al_fees)
+%0A%0A // Add one to the fee to add room for accuracy error when using as a fee limit.%0A return fee + 1
%0A%7D%0A%0A/**%0A
|
8c62efe870fd2b7e71873d403adcf2ff69fddd0e | make TaskQueue a real class | src/common/TaskQueue.js | src/common/TaskQueue.js |
function TaskQueue() {
var _this = this;
var isPaused = false;
var isRunning = 0;
var q = [];
$.extend(this, EmitterMixin);
this.queue = function(/* taskFunc, taskFunc... */) {
q.push.apply(q, arguments); // append
tryStart();
};
this.pause = function() {
isPaused = true;
};
this.resume = function() {
isPaused = false;
tryStart();
};
function tryStart() {
if (!isRunning && !isPaused && q.length) {
isRunning = true;
_this.trigger('start');
runNext();
}
}
function runNext() { // does not check for empty q
var taskFunc = q.shift();
var res = taskFunc();
if (res && res.then) {
res.then(done);
}
else {
done();
}
function done() {
if (!isPaused && q.length) {
runNext();
}
else {
isRunning = false;
_this.trigger('stop');
}
}
}
}
FC.TaskQueue = TaskQueue;
| JavaScript | 0.000292 | @@ -1,17 +1,12 @@
%0A
-function
+var
TaskQue
@@ -11,45 +11,60 @@
ueue
-() %7B%0A%09var _this = this;%0A%09var
+ = Class.extend(EmitterMixin, %7B%0A%0A%09q: null,%0A%09
isPaused
= f
@@ -63,23 +63,18 @@
used
- =
+:
false
-;
+,
%0A%09
-var
isRu
@@ -82,73 +82,74 @@
ning
- = 0;%0A%09var q = %5B%5D;%0A%0A%09$.extend(this, EmitterMixin);%0A%0A%09this.
+: false,%0A%0A%0A%09constructor: function() %7B%0A%09%09this.q = %5B%5D;%0A%09%7D,%0A%0A%0A%09
queue
- =
+:
fun
@@ -187,16 +187,21 @@
*/) %7B%0A%09%09
+this.
q.push.a
@@ -205,16 +205,21 @@
h.apply(
+this.
q, argum
@@ -237,16 +237,21 @@
ppend%0A%09%09
+this.
tryStart
@@ -260,24 +260,19 @@
;%0A%09%7D
-;
+,%0A
%0A%0A%09
-this.
pause
- =
+:
fun
@@ -275,32 +275,37 @@
function() %7B%0A%09%09
+this.
isPaused = true;
@@ -311,25 +311,20 @@
;%0A%09%7D
-;
+,%0A
%0A%0A%09
-this.
resume
- =
+:
fun
@@ -335,16 +335,21 @@
n() %7B%0A%09%09
+this.
isPaused
@@ -360,16 +360,21 @@
alse;%0A%09%09
+this.
tryStart
@@ -383,55 +383,206 @@
;%0A%09%7D
-;%0A%0A%09function try
+,%0A%0A%0A%09tryStart: function() %7B%0A%09%09if (this.can
Start()
+)
%7B%0A%09%09
-if (!isRunning && !
+%09this.start();%0A%09%09%7D%0A%09%7D,%0A%0A%0A%09canStart: function() %7B%0A%09%09return !this.isRunning && this.canRunNext();%0A%09%7D,%0A%0A%0A%09canRunNext: function() %7B%0A%09%09return !this.
isPa
@@ -585,32 +585,37 @@
isPaused &&
+this.
q.length
) %7B%0A%09%09%09isRun
@@ -602,23 +602,79 @@
q.length
-) %7B%0A%09%09%09
+;%0A%09%7D,%0A%0A%0A%09start: function() %7B // does not check canStart%0A%09%09this.
isRunnin
@@ -685,18 +685,16 @@
true;%0A%09%09
-%09_
this.tri
@@ -710,17 +710,21 @@
rt');%0A%09%09
-%09
+this.
runNext(
@@ -731,32 +731,31 @@
);%0A%09
-%09%7D%0A%09%7D%0A%0A%09function runNext
+%7D,%0A%0A%0A%09runNext: function
() %7B
@@ -791,32 +791,156 @@
q%0A%09%09
-var taskFunc = q.shift()
+this.runTask(this.q.shift());%0A%09%7D,%0A%0A%0A%09runTask: function(task) %7B%0A%09%09this.runTaskFunc(task);%0A%09%7D,%0A%0A%0A%09runTaskFunc: function(taskFunc) %7B%0A%09%09var _this = this
;%0A%09%09
@@ -1066,37 +1066,34 @@
if (
-!isPaused && q.length
+_this.canRunNext()
) %7B%0A%09%09%09%09
runN
@@ -1088,16 +1088,22 @@
) %7B%0A%09%09%09%09
+_this.
runNext(
@@ -1124,16 +1124,22 @@
e %7B%0A%09%09%09%09
+_this.
isRunnin
@@ -1188,17 +1188,20 @@
%0A%09%09%7D%0A%09%7D%0A
-%7D
+%0A%7D);
%0A%0AFC.Tas
|
c784c50b656500cfc379bb29589ce050b868a370 | add an internal variable to handle setting the canvas width and height | src/common/container.js | src/common/container.js |
d3.ma = {};
/*
return element: Most of methods return svg canvas object for easy chaining
E.G: d3.ma.container('body').margin({top: 80, left: 80}).box(600, 500)
var container = d3.ma.container('#vis'),
canvas = container.canvas().chart("LabeledCirclesChart");
d3.ma.container(selector) is absolutely required, others are optional.
container() will take a css selector, which will be the container to contain the svg element
margin() is optional, to set/get margin object, must take an object as value, e.g. {top: 80}, normally come before box()
box() is optional, by default, it will take the container width and height. to set/get/retrieve the svg/container width and height, if only one value provide, width and height would be the same
canvasW() and canvasH() is optional, will set/get the canvas width and height. Normally, do not need to set explicitly, Use box() will auto set the canvas width and height as properly
*/
d3.ma.container = function(selector) {
var selection = d3.select(selector);
var margin = {top: 30, right: 20, bottom: 20, left: 30},
containerW = selection[0][0].clientWidth || document.body.clientWidth || 960,
containerH = selection[0][0].clientHeight || document.body.clientHeight || 540,
canvasW,
canvasH,
container = selection.append('svg'), // Create container, append svg element to the selection
// Create a new group element append to svg
// Set the canvas layout with a good amount of offset, has canvas class for easy targeting
g = container.append('g').classed('canvas', true);
container.canvasW = function(_width, boxCalled) {
if (!arguments.length) return g.attr("width");
if(boxCalled) _width = parseInt(_width) - margin.left - margin.right;
g.attr('width', _width);
return container;
};
container.canvasH = function(_height, boxCalled) {
if(!arguments.length) return g.attr("height");
if(boxCalled) _height = parseInt(_height) - margin.top - margin.bottom;
g.attr('height', _height);
return container;
};
container.box = function(_width, _height) {
if(!arguments.length) {
var m = container.margin();
return {
'containerWidth': container.canvasW() + m.left + m.right,
'containerHeight': container.canvasH() + m.top + m.bottom
};
}
// When arguments are more than one, set svg and container width & height
var h = (_height) ? _height : _width;
container.canvasW(_width, true);
container.canvasH(h, true);
container.attr({
'width': _width,
'height': h
});
gTransform();
return container;
};
container.margin = function(_) {
if (!arguments.length) return margin;
margin.top = typeof _.top != 'undefined' ? _.top : margin.top;
margin.right = typeof _.right != 'undefined' ? _.right : margin.right;
margin.bottom = typeof _.bottom != 'undefined' ? _.bottom : margin.bottom;
margin.left = typeof _.left != 'undefined' ? _.left : margin.left;
// After set the new margin, and maintain svg container width and height, container width and height ratio
container.box(containerW, containerH);
return container;
};
// Return the canvas object for easy chaining
container.canvas = function(){
return container.select('g');
};
// Set the canvas transform attr, call it when needed
function gTransform () {
g.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
}
// Set the svg container width and height
// Set the container width and height, and its transform values
container.box(containerW, containerH);
return container;
};
| JavaScript | 0 | @@ -1551,24 +1551,38 @@
', true);%0A%0A%09
+var canvasW =
container.ca
@@ -1615,24 +1615,24 @@
oxCalled) %7B%0A
-
%09%09if (!argum
@@ -1785,32 +1785,46 @@
ontainer;%0A%09%7D;%0A%0A%09
+var canvasH =
container.canvas
@@ -2171,26 +2171,16 @@
Width':
-container.
canvasW(
@@ -2224,26 +2224,16 @@
eight':
-container.
canvasH(
@@ -2383,26 +2383,16 @@
dth;%0A%0A%09%09
-container.
canvasW(
@@ -2408,26 +2408,16 @@
rue);%0A%09%09
-container.
canvasH(
|
9de14c41146b1f556fcbe63046cc827054eb9ecd | add radix | website/src/components/markdown/Heading.js | website/src/components/markdown/Heading.js | /** @jsx jsx */
import React from 'react'; // eslint-disable-line no-unused-vars
import reactAddonsTextContent from 'react-addons-text-content';
import snakeCase from 'lodash.snakecase';
import { jsx } from '@emotion/core';
import { colors, gridSize } from '@arch-ui/theme';
import { LinkIcon } from '@arch-ui/icons';
import { mq } from '../../utils/media';
function dashcase(children) {
// this matches the IDs that are used for links naturally by remark
return snakeCase(reactAddonsTextContent(children)).replace(/_/g, '-');
}
const Heading = ({ as: Tag, children, ...props }) => {
const id = dashcase(children);
const iconSize = 24;
const depth = parseInt(Tag.slice(1));
const hasLink = depth > 1 && depth < 5;
const link = hasLink && (
<a
href={`#${id}`}
css={{
alignItems: 'center',
color: colors.N40,
display: 'flex',
fontSize: '1rem',
height: iconSize,
justifyContent: 'center',
marginTop: -iconSize / 2,
opacity: 0,
overflow: 'visible',
paddingRight: gridSize / 2,
position: 'absolute',
top: '50%',
transform: 'translateX(-100%)',
width: iconSize,
'&:hover': {
color: colors.primary,
},
}}
>
<LinkIcon width={24} />
</a>
);
return (
<Tag
css={{
color: colors.N100,
lineHeight: 1,
marginBottom: '0.66em',
position: 'relative',
'&:hover a': {
opacity: 1,
},
}}
id={id}
{...props}
>
{link}
{children}
</Tag>
);
};
export const H1 = props => (
<Heading
css={mq({
fontSize: ['2.4rem', '3.2rem'],
marginTop: 0,
})}
{...props}
as="h1"
/>
);
export const H2 = props => (
<Heading
{...props}
css={mq({
fontSize: ['1.8rem', '2.4rem'],
fontWeight: 300,
marginTop: '1.33em',
})}
as="h2"
/>
);
export const H3 = props => (
<Heading
css={mq({
fontSize: ['1.4rem', '1.6rem'],
fontWeight: 500,
marginTop: '1.5em',
})}
{...props}
as="h3"
/>
);
export const H4 = props => <Heading css={{ fontSize: '1.2rem' }} {...props} as="h4" />;
export const H5 = props => <Heading {...props} css={{ fontSize: '1rem' }} as="h5" />;
export const H6 = props => <Heading {...props} css={{ fontSize: '0.9rem' }} as="h6" />;
export default Heading;
| JavaScript | 0.000262 | @@ -678,16 +678,20 @@
slice(1)
+, 10
);%0A con
|
5f22a100b3b76b5394ad8915a876cf44de540f67 | add extra space | tests/server/fixtures/userFixtures.js | tests/server/fixtures/userFixtures.js | const { encryptPassword } = require('../../../server/utils/validate');
module.exports = {
_id: 1,
email: 'test@xyz.io',
password: encryptPassword('shoes2231'),
first_name: 'Tony',
last_name: 'Tiger',
dob: '2017-10-1',
};
| JavaScript | 0.00076 | @@ -84,16 +84,17 @@
rts = %7B%0A
+
_id: 1,
@@ -94,16 +94,17 @@
_id: 1,%0A
+
email:
@@ -118,16 +118,17 @@
yz.io',%0A
+
passwor
@@ -160,16 +160,17 @@
2231'),%0A
+
first_n
@@ -182,16 +182,17 @@
'Tony',%0A
+
last_na
@@ -204,16 +204,17 @@
Tiger',%0A
+
dob: '2
|
64ef98fa8e0fe35ebcce7f3070637c622799da02 | Change route . | router/index.js | router/index.js | var render = require('../application/render');
var Backbone = require('backbone');
var ArgumentNullException = require('../exception/ArgumentNullException');
var message = require('../message');
var userHelper = require('../user');
module.exports = Backbone.Router.extend({
noRoleRoute: 'home',
route(route, name, callback) {
var router = this;
if (!callback){
callback = this[name];
}
if(callback === undefined || callback === null){
throw new ArgumentNullException(`The route callback seems to be undefined, please check your router file for your route: ${name}`);
}
var customWrapperAroundCallback = ()=>{
var currentRoute = route;
//The default route is the noRoleRoute by default
if(currentRoute === ''){
currentRoute = router.noRoleRoute;
}
var routeName = '';//siteDescriptionBuilder.findRouteName(currentRoute);
var routeDescciption = {roles: ['DEFAULT_ROLE']};//siteDescriptionBuilder.getRoute(routeName);
if((routeDescciption === undefined && currentRoute !== '') || !userHelper.hasRole(routeDescciption.roles)){
message.addErrorMessage('application.noRights');
return Backbone.history.navigate('', true);
}else {
//Rendre all the notifications in the stack.
backboneNotification.renderNotifications();
}
//console.log('routeObject', siteDescriptionBuilder.getRoute(n));
callback.apply(router, arguments);
};
return Backbone.Router.prototype.route.call(this, route, name, customWrapperAroundCallback);
},
/**
* Render the compoennt into the page content.
*/
_pageContent(component, options){
return render(component, '[data-focus="page-content"]', options);
}
});
| JavaScript | 0 | @@ -670,24 +670,76 @@
te = route;%0A
+ console.log(%60Route change: $%7BcurrentRoute%7D%60);%0A
//The
|
8eb17eca054d669888235d8cd54d5653db350798 | Fix prettier error #775 | tests/unit/services/head-data-test.js | tests/unit/services/head-data-test.js | /* eslint-disable prettier/prettier */
import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
module('Unit | Service | head-data', function(hooks) {
setupTest(hooks);
// TODO: Replace this with your real tests.
test('it exists', function(assert) {
let service = this.owner.lookup('service:head-data');
assert.ok(service);
});
});
| JavaScript | 0.000004 | @@ -1,43 +1,4 @@
-/* eslint-disable prettier/prettier */%0A
impo
@@ -118,16 +118,17 @@
function
+
(hooks)
@@ -196,16 +196,16 @@
tests.%0A
-
test('
@@ -224,16 +224,17 @@
function
+
(assert)
|
9e88f223bfab0f1f57df274e516ab2d706307ccf | Disable broken Twitter connection | routes/index.js | routes/index.js | // -*- coding: utf-8 -*-
// Copyright 2010-2012 Felix E. Klee <felix.klee@inka.de>
//
// 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.
/*jslint node: true, maxerr: 50, maxlen: 79, nomen: true */
'use strict';
var Twitter = require('ntwitter'),
config = require('../separate/config.json'),
twitter,
realityBuilderVersion = '1-10-0',
adminPassword;
twitter = new Twitter(config.twitter);
twitter.verifyCredentials(function (errorMessage) {
if (errorMessage) {
console.log('Verifying Twitter credentials failed: ' + errorMessage);
process.exit(1);
}
});
adminPassword = config.adminPassword;
// Home page.
/*jslint unparam:true */
exports.index = function (req, res) {
/*jslint unparam:false */
res.render('index', {
title: 'Reality Builder',
realityBuilderVersion: realityBuilderVersion,
stillImagesBaseUrl: config.stillImagesBaseUrl
});
};
// Returns true, iff the process runs in a production enviroment and the
// request was via HTTP.
function httpReqInProductionEnv(req) {
return (typeof process.env.NODE_ENV !== 'undefined' &&
process.env.NODE_ENV === 'production' &&
req.headers.hasOwnProperty('x-forwarded-proto') &&
req.headers['x-forwarded-proto'] === 'http');
}
function userIsAdmin(req) {
return (typeof req.session.userIsAdmin !== 'undefined' &&
req.session.userIsAdmin);
}
function logOutRequested(req) {
return typeof req.query.log_out !== 'undefined';
}
function logOutUser(req) {
delete req.session.userIsAdmin;
}
// Redirects to the same page but behind SSL.
function redirectToHttps(req, res) {
res.redirect('https://' + req.header('Host') + req.url);
}
// Administration interface.
exports.admin = function (req, res) {
if (httpReqInProductionEnv(req)) {
redirectToHttps(req, res); // force HTTPS in production
} else if (logOutRequested(req)) {
logOutUser(req);
res.redirect(req.route.path);
} else if (!userIsAdmin(req)) {
res.render('admin_password_prompt', {
wrongPassword: typeof req.query.wrong_password !== 'undefined'
});
} else {
res.render('admin', {
title: 'Reality Builder Administration',
realityBuilderVersion: realityBuilderVersion,
stillImagesBaseUrl: config.stillImagesBaseUrl
});
}
};
exports.verifyAdminPassword = function (req, res) {
if (req.body.password && req.body.password === adminPassword) {
req.session.userIsAdmin = true;
res.redirect(req.route.path);
} else {
res.redirect(req.route.path + '?wrong_password');
}
};
// Linked to from (as of early 2012):
//
// <url:http://prezi.com/3rglon2gvazu/reality-builder/?auth_key=772126086aa01
// bb98733b87b6295b6baac03ca72>
exports.presentation = function (req, res) {
res.render('presentation');
};
// Twitters a tweet via Twitter.
/*jslint unparam:true */
exports.twitter = function (req, res) {
/*jslint unparam:false */
twitter.updateStatus(
req.body.status,
function (errorMessage) {
if (errorMessage) {
console.log('Tweeting failed: ' + errorMessage);
}
}
);
res.end();
};
| JavaScript | 0.000014 | @@ -891,16 +891,27 @@
ord;%0D%0A%0D%0A
+/* BROKEN%0D%0A
twitter
@@ -1136,16 +1136,20 @@
%7D%0D%0A%7D);%0D
+%0A*/%0D
%0A%0D%0Aadmin
@@ -3671,24 +3671,35 @@
false */%0D%0A%0D%0A
+/* BROKEN%0D%0A
twitter.
@@ -3906,16 +3906,20 @@
%0A );%0D
+%0A*/%0D
%0A%0D%0A r
|
7cbf086e8ece5ab3965574e8a2d3e821a87bfd81 | Changed city to title | routes/index.js | routes/index.js | var express = require('express');
var router = express.Router();
var request = require('request');
var _ = require('lodash');
router.get('/', function(req, res) {
var url = "https://seeclickfix.com/api/v2/issues?place_url=hampton-city&state=VA&per_page=10&page=1";
request(url, function(err, response, body) {
if(err){
console.error(err);
}
var list = JSON.parse(body).issues;
var metadata = JSON.parse(body).metadata;
var per_page = metadata.pagination.per_page;
var city = 'hampton';
var pages = list.length;
var lat = _.pluck(list,'lat');
var lng = _.pluck(list, 'lng');
var start = 0;
var summary = _.pluck(list, 'summary');
res.render('index', { title: 'Hampton', list: list, lat:lat, lng:lng, summary:summary, per_page:pages, start:start,pages:pages, city:city});
});
});
router.get('/:city', function(req, res) {
var city = req.params.city;
res.redirect('/' + city + '/1');
// var city = req.params.city;
// var url = "https://seeclickfix.com/api/v2/issues?place_url="+ city +"&state=VA&per_page=20&page=1";
// request(url, function(err, response, body) {
// if(err){
// console.error(err);
// }
// var list = JSON.parse(body).issues;
// var metadata = JSON.parse(body).metadata;
// var per_page = metadata.pagination.per_page;
// var lat = _.pluck(list,'lat');
// var lng = _.pluck(list, 'lng');
// var summary = _.pluck(list, 'summary');
// if (city == 'newport-news') {
// city = "newport news";
// } else if (city == 'virginia-beach') {
// city = "virginia beach";
// }
// else {
// city = city.split('-');
// city = city[0];
// }
// res.render('index', { title: city, list: list, lat:lat, lng:lng, summary:summary, per_page:per_page });
// });
});
router.get('/:city/:id',function(req,res) {
var city = req.params.city;
var id = req.params.id;
var url = "https://seeclickfix.com/api/v2/issues?place_url="+ city +"&state=VA&per_page=20&page=" + id;
request(url, function(err, response, body) {
if(err) {
console.error(err);
}
var list = JSON.parse(body).issues;
var metadata = JSON.parse(body).metadata;
var per_page = metadata.pagination.per_page;
var pages = metadata.pagination.pages;
var lat = _.pluck(list,'lat');
var lng = _.pluck(list, 'lng');
var summary = _.pluck(list, 'summary');
var start = 0;
var next_page = 2;
console.log('This is how many pages ', pages);
if (id <= pages) {
start = per_page * (id-1);
}
if(id < pages) {
next_page = (Number(id)+1);
}
if (city == 'newport-news') {
title = "newport news";
} else if (city == 'virginia-beach') {
title = "virginia beach";
}
else {
title = city.split('-');
title = city[0];
}
res.render('index', { title: title, list: list, lat:lat, lng:lng, summary:summary, per_page:per_page, pages:pages,
start:start, city:city, next_page:next_page });
});
});
router.post('/',function(req,res){
//req.body.city = city name from drop down
var city = req.body.city;
var url = "https://seeclickfix.com/api/v2/issues?place_url=" + city + "&state=VA"; //insert city in this link
request(url, function(err, response, body) {
if(err){
console.error(err);
}
var list = JSON.parse(body).issues;
var lat = _.pluck(list,'lat');
var lng = _.pluck(list, 'lng');
var summary = _.pluck(list, 'summary');
res.render('index', { title: city, list:list, lat:lat, lng:lng, summary:summary });
});
});
module.exports = router;
| JavaScript | 0.999406 | @@ -2737,48 +2737,80 @@
%7D
-%0A
else
-%7B%0A title = city.split('-');
+if(city == 'hampton-city') %7B%0A title = 'hampton';%0A %7D else %7B
%0A
@@ -2822,19 +2822,16 @@
e = city
-%5B0%5D
;%0A %7D%0A
|
3874885de65d887d433b420f18e0fa99f089a6ff | Update index.js | routes/index.js | routes/index.js | const express = require('express');
const router = express.Router();
const Geetest = require('../gt-sdk');
const websiteDao = require('../dao/websiteDao');
const usersDao = require('../dao/usersDao');
const blogsDao = require('../dao/blogsDao');
const tagsDao = require('../dao/tagsDao');
const dbDao = require('../dao/dbDao');
const util = require('../common/util');
/* website install */
router.get('/start', function (req, res) {
var start = false;
var website;
dbDao.createUsers()
.then(function () {
return dbDao.createClassify();
})
.then(function () {
return dbDao.createBlogs();
})
.then(function () {
return dbDao.createTags();
})
.then(function () {
return dbDao.createComments();
})
.then(function () {
return dbDao.createReplayComments();
})
.then(function () {
return dbDao.createWebsite();
})
.then(function () {
return dbDao.createFriends();
})
.then(function () {
return dbDao.initWebsite();
})
.then(function () {
return dbDao.initClassify();
})
.then(function () {
return websiteDao.getWebSite();
})
.then(function (result) {
if (result[0].state == 0) {
start = true;
}
else {
website = result[0];
}
})
.then(function () {
if (start) {
res.render('front/start', { title: '初号机神经同步' });
}
else {
res.redirect('/');
}
})
.catch(function (err) {
console.log(err);
res.render('error', { message: '数据表创建失败,请联系作者' });
})
});
/* 首页 */
router.get('/', function (req, res) {
var website, blogs;
websiteDao.getWebSite()
.then(function (result) {
website = result[0];
return blogsDao.getStick();
})
.then(function (result) {
blogs = result;
return blogsDao.getBlogByPage(0, 9);
})
.then(function (result) {
blogs = blogs.concat(result);
res.render('front/index', { website: website, blogs: blogs });
})
.catch(function (error) {
res.render('error', { message: '404', error: error });
})
});
/* 加载更多文章 */
router.post('/loadmoreav', function (req, res, next) {
var page = parseInt(req.body.page);
blogsDao.getBlogByPage(page * 10, 10)
.then(function (result) {
res.send({ type: true, blogs: result });
})
.catch(function (error) {
res.send({ type: false, error: error })
})
});
/* 获取文章 */
router.get('/article/av*', function (req, res) {
var reg = /\/article\/av\d+/gi;
var flag = true;
var url = req.originalUrl, article_id, website, blogs, prev, next;
article_id = reg.exec(url);
if (article_id) {
article_id = article_id[0].substr(11);
}
else {
flag = false;
}
if (flag) {
websiteDao.getWebSite()
.then(function (result) {
website = result[0];
return blogsDao.getPrev(article_id);
})
.then(function (result) {
prev = result;
return blogsDao.getNext(article_id);
})
.then(function (result) {
next = result;
return blogsDao.addViewNum(article_id);
})
.then(function (result) {
return blogsDao.getBlogByID(article_id, false);
})
.then(function (result) {
if (result.length == 0) {
throw new Error('404');
}
else {
res.renderPjax('front/article', { website: website, blog: result[0], blogs: blogs, prev: prev, next: next });
}
})
.catch(function (error) {
res.render('error', { message: 404, error: error });
});
}
else {
var error = {};
error.status = '400';
error.stack = '';
res.render('error', { message: 400, error: error });
}
});
/* login */
router.get('/login', function (req, res, next) {
websiteDao.getWebSite()
.then(function (result) {
res.render('front/login', { title: 'Login', website: result[0] });
})
});
/* 开通站点 */
router.post('/start', function (req, res) {
var date = util.formatDate(new Date());
var img = '/images/pic/head.jpg';
websiteDao.startWebSite(req.body.website, req.body.email, date, req.body.domain)
.then(function (result) {
if (result) {
return usersDao.regUser(req.body.username, req.body.password, req.body.email, img, date, 0, 0);
}
})
.finally(function () {
res.send(true);
res.end();
});
});
/* 登陆 */
router.post('/ulogin', function (req, res, next) {
var date = util.formatDate(new Date());
var user;
var type = 0;
usersDao.login(req.body.email, req.body.password)
.then(function (result) {
if (result.length != 0) {
user = result[0];
delete user.password;
delete user.state;
delete user.reg_date;
return usersDao.loginDate(user.id, date);
}
else {
type = 1;
return false;
}
})
.then(function (result) {
if (type == 0) {
user.token = result;
res.send({ type: 0, user: user })
}
else {
res.send({ type: 1 });
}
res.end();
}, function (err) {
res.send({ type: 1 });
});
});
/* 留言板 */
router.get('/messageboard', function (req, res, next) {
websiteDao.getWebSite()
.then(function (result) {
res.renderPjax('front/messageboard', { website: result[0] });
})
.catch(function (error) {
res.render('error', { message: 404, error: error });
});
});
/* 友人帐 */
router.get('/friendslink', function (req, res) {
var website;
websiteDao.getWebSite()
.then(function (result) {
website = result[0];
return friendsDao.getFriends();
})
.then(function (result) {
res.renderPjax('front/friendslink', { website: website, friends: result });
})
.catch(function (error) {
res.render('error', { message: 404, error: error });
});
});
/* 获取标签 */
router.post('/tags', function (req, res){
tagsDao.getAllTags()
.then(function (result) {
res.send({ type: true, tags: result});
})
.catch(function (error) {
res.send({ type: false });
});
});
module.exports = router;
| JavaScript | 0.000002 | @@ -65,46 +65,8 @@
r();
-%0Aconst Geetest = require('../gt-sdk');
%0A%0Aco
|
c0df2fe52f7dcbea8b2c5cf552eaaba5adb8228c | Fix calculation | routes/index.js | routes/index.js | const _ = require('lodash');
const Bluebird = require('bluebird');
const express = require('express');
const Feed = require('../src/feed');
const helper = require('../src/helper');
const router = express.Router();
const ua = require('universal-analytics');
const tracking = require("../src/tracking");
router.get('/', function (req, res, next) {
if (req.headers.accept.includes('text/html')) {
handleHtmlRequest(req, res, next);
} else {
handleJsonRequest(req, res, next);
}
});
module.exports = router;
function getYesterday() {
let date = new Date();
date.setDate(date.getDate() - 1);
return date;
}
async function handleHtmlRequest(req, res, next) {
const sections = [
'introduction',
'usage',
'options',
'hosting',
'development',
'caching',
'analytics'
];
const supportRequestsTillNextAd = tracking.isReady() && JSON.parse(await tracking.get('feedr-ads', 'requestsSinceLastAd'));
res.render('index', {
title: 'FeedrApp',
sections,
tracking: {
today: await tracking.getDataFor(new Date()),
yesterday: await tracking.getDataFor(getYesterday()),
supportRequestsTillNextAd: supportRequestsTillNextAd || 0
}
});
}
function handleJsonRequest(req, res, next) {
getResponseData(req).then(function (feed) {
if (req.query.callback) {
res.set('Content-Type', 'text/javascript; charset=utf-8');
res.send(`${req.query.callback}(${JSON.stringify(feed)});`);
} else {
res.json(feed);
}
})
.then(() => trackRequest(req));
}
function getResponseData(req) {
const feedUrl = req.query.q;
const feedOptions = _.pick(req.query, ['num']);
if (feedUrl) {
return new Feed(feedUrl).read(feedOptions).then((feed) => {
return { responseStatus: 200, responseDetails: null, responseData: { feed } };
}).catch((error) => {
console.error({ feedUrl, error });
return helper.badRequest({ message: 'Parsing the provided feed url failed.' });
});
} else {
return Bluebird.resolve(helper.badRequest({
message: 'No q param found!',
details: 'Please add a query parameter "q" to the request URL which points to a feed!'
}));
}
}
function trackRequest(req) {
// ua('UA-100419142-1', { https: true })
// .pageview(req.originalUrl)
// .send();
}
| JavaScript | 0.000174 | @@ -1162,16 +1162,23 @@
NextAd:
+250 - (
supportR
@@ -1199,16 +1199,17 @@
tAd %7C%7C 0
+)
%0A %7D%0A
|
9e6f19001bf83de68140d70976f5b1fa7412300d | comment out the res.send at end of route file | routes/index.js | routes/index.js | import keystone from 'keystone';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import path from 'path';
import express from 'express';
import config from '../webpack.config.js';
import createTemplate from './utils/createTemplate';
const isDeveloping = process.env.NODE_ENV !== 'production';
const importRoutes = keystone.importer(__dirname);
const compiler = webpack(config);
import React from 'react';
import { renderToString } from 'react-dom/server';
import { match, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import store from '../app/src/store/store.js';
import { routes } from '../app/src/utils/routes.jsx';
const serverApiRoutes = {
api: importRoutes('./api')
};
if (isDeveloping) {
keystone.pre('routes', webpackMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
keystone.pre('routes', webpackHotMiddleware(compiler, {
log: console.log // eslint-disable-line
}));
}
exports = module.exports = function (app) {
app.use(webpackMiddleware(compiler, {
noInfo: true,
publicPath: config.output.publicPath
}));
app.use(webpackHotMiddleware(compiler, {
log: console.log, // eslint-disable-line
path: '/__webpack_hmr',
heartbeat: 10 * 1000
}));
if (isDeveloping) {
app.all('*', (req, res, next) => {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET, POST');
res.header('Access-Control-Allow-Headers', 'Content-Type');
next();
});
}
app.all('/api*', keystone.middleware.api);
app.get('/api/posts/list', serverApiRoutes.api.posts.getAll);
app.all('/api/posts/create', serverApiRoutes.api.posts.create);
app.get('/api/posts/:id', serverApiRoutes.api.posts.getOne);
app.all('/api/posts/:id/update', serverApiRoutes.api.posts.update);
app.get('/api/posts/:id/remove', serverApiRoutes.api.posts.remove);
app.all('/api/contact/create', serverApiRoutes.api.contact.create);
app.use(express.static('./public'));
app.use((req, res) => {
match({ routes, location: req.url },
(error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (renderProps) {
const body = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
);
res.status(200)
.send(createTemplate(body, store.getState()));
} else {
res.status(400).send('Not Found 🤔');
}
});
});
app.get('/*', (req, res) => {
res.sendFile(path.join(__dirname, 'public/index.html'));
});
};
| JavaScript | 0 | @@ -2792,24 +2792,27 @@
%7D);%0A %7D);%0A
+ //
app.get('/*
@@ -2831,16 +2831,19 @@
) =%3E %7B%0A
+ //
res.s
@@ -2891,20 +2891,23 @@
x.html'));%0A
+ //
%7D);%0A%7D;%0A
|
e0474d19980b08c0f9ff26e3a821c8932dd38a36 | add category to route directory of category routes to define properly category routes, add delete param routes to index routes, indent properly for readability category routes | routes/index.js | routes/index.js |
var express = require('express');
var router = express.Router();
var userRoutes = require('./user');
var sessionRoutes = require('./session');
var homeRoutes = require('./home');
var fashionRoutes = require('./fashion');
var categoryRoutes = require('./category');
var roleRoutes = require('./role');
var sizeRoutes = require('./size');
function isLoggedIn(req, res, next) {
if(req.isAuthenticated()){
return next();
}
req.session.returnTo = req.path;
res.redirect('/login');
}
function isAdmin(req, res, next) {
if(req.isAuthenticated()){
if(req.user.role == 'admin'){
return next();
}
}
req.session.returnTo = req.path;
res.redirect('/login');
}
router.get('/', homeRoutes.index);
/*
* @user routes
*/
router.get('/register', userRoutes.new);
router.post('/signup', userRoutes.create);
/*
* @session routes
*/
router.get('/login', sessionRoutes.new);
router.post('/login', sessionRoutes.create);
router.get('/logout', sessionRoutes.delete);
/*
* @session routes
*/
router.get('/admin/fashions', fashionRoutes.index);
router.get('/user/item', fashionRoutes.single);
//router.get('/admin/index/new', fashionRoutes.new);
//router.post('/admin/create', fashionRoutes.add);
router.get('/admin/create', fashionRoutes.new);
router.post('/admin/fashions', fashionRoutes.add);
router.post('/admin/update', fashionRoutes.update);
//router.get('/admin/index/edit', fashionRoutes.edit);
router.get('/admin/delete', fashionRoutes.delete);
router.post('/admin/another', fashionRoutes.addsize);
/*
* @category Routes
*/
router.get('/admin/add', categoryRoutes.index);
router.get('/admin/new', categoryRoutes.new);
//router.get('/admin/categoty', categoryRoutes.get);
router.post('/admin/add', categoryRoutes.add);
/*
* @size Routes
*/
router.get('/admin/another', sizeRoutes.index);
router.get('/admin/newer', sizeRoutes.new);
//router.get('/admin/categoty', categoryRoutes.get);
router.post('/admin/another', sizeRoutes.add);
/*
* @Role routes
*/
router.get('/admin/assign/:username/:role', roleRoutes.assign);
router.get('/admin/role/:role', roleRoutes.create);
module.exports=router;
| JavaScript | 0 | @@ -1704,37 +1704,53 @@
ter.get('/admin/
-add',
+category/index',
categoryRoutes.
@@ -1776,21 +1776,37 @@
'/admin/
-new',
+category/new',
categor
@@ -1811,34 +1811,32 @@
oryRoutes.new);%0A
-//
router.get('/adm
@@ -1836,36 +1836,43 @@
t('/admin/catego
-ty',
+ries',
categoryRou
@@ -1905,32 +1905,112 @@
min/
-add', categoryRoutes.add
+category/add', categoryRoutes.add);%0Arouter.get('/admin/category/delete/:id', categoryRoutes.delete
);%0A%0A
|
f1da9f35647cd44ee8bd898593da8f35b7e7cb02 | Remove temporary file after upload | routes/media.js | routes/media.js | const db = require('../lib/db')
const mongoose = db.goose
const conn = db.rope
const fs = require('fs')
const router = require('koa-router')()
const File = require('../lib/models/file')
const grid = require('gridfs-stream')
const gfs = grid(conn.db, mongoose.mongo)
router.get('/', function *() {
try {
var results = yield File.find()
} catch (err) {
throw err
}
for (var file in results) {
results[file] = results[file].toObject()
}
yield this.render('media', {
pageTitle: 'Media',
list: true,
files: results
})
})
router.post('/upload', function *(next) {
const file = this.request.body.files.file
const writestream = gfs.createWriteStream({
filename: file.name,
root: 'media',
content_type: file.type
})
const content = fs.createReadStream(file.path)
content.pipe(writestream)
try {
yield new Promise(function (resolve) {
writestream.on('close', () => resolve())
})
} catch (err) {
throw err
}
this.body = file.name + ' was written to DB'
yield next
})
module.exports = router
| JavaScript | 0 | @@ -1044,16 +1044,85 @@
eld next
+%0A%0A fs.unlink(file.path, function (err) %7B%0A if (err) throw err%0A %7D)
%0A%7D)%0A%0Amod
|
fe8546ad7e32b1d2323e1da24176875566e0fac0 | Fix relative path check | routes/music.js | routes/music.js | var mongoose = require('mongoose'),
db = mongoose.connection,
fs = require('fs'),
settings = require('../settings.json');
exports.index = function(req, res){
var id = req.params.id,
Track = mongoose.model('track');
Track.findOne({ _id : id }, function (err, track) {
if (err) {
console.error(err);
} else if (track) {
fs.exists(track.path, function(exists){
if (exists && settings.scanner.path.indexOf(track.path) === 0){
res.sendfile(track.path);
}else{
console.warn('Path "'+track.path+'" invalid for track '+id);
res.send(404);
}
});
} else {
res.send(404);
}
});
}; | JavaScript | 0.000003 | @@ -77,16 +77,41 @@
('fs'),%0A
+%09path = require('path'),%0A
%09setting
@@ -402,65 +402,123 @@
%09%09%09%09
-if (exists && settings.scanner.path.indexOf(track.path) =
+var relativepath = path.relative(settings.scanner.path, track.path);%0A%09%09%09%09if (exists && relativepath.indexOf('..') !
== 0
|
23d82f07c6455daaaf4e98e6529f1885fa329cd7 | Add missing return annotations | tools/browserify/bundle/lib/bundle.js | tools/browserify/bundle/lib/bundle.js | 'use strict';
// MODULES //
var debug = require( 'debug' )( 'browserify:bundle' );
var writeFile = require( 'fs' ).writeFile;
var browserify = require( 'browserify' );
// MAIN //
/**
* Bundles files into a single file using `browserify`.
*
* @param {StringArray} files - files to bundle
* @param {string} [dest] - output file path
* @param {Callback} clbk - callback to invoke after creating a bundle
*
* @example
* var files = [ '/foo/bar.js', '/beep/boop.js' ];
*
* bundle( files, clbk );
*
* function clbk( error, bundle ) {
* if ( error ) {
* throw error;
* }
* console.log( bundle.toString() );
* }
*/
function bundle( files, dest, clbk ) {
var opts;
var out;
var cb;
var b;
if ( arguments.length < 3 ) {
cb = dest;
} else {
out = dest;
cb = clbk;
}
opts = {
'transform': [ 'envify' ],
'plugin': [ 'proxyquire-universal' ]
};
debug( 'Browserify options: %s', JSON.stringify( opts ) );
b = browserify( files, opts );
debug( 'Creating a bundle...' );
b.bundle( onBundle );
/**
* Callback invoked upon creating a bundle.
*
* @private
* @param {(Error|null)} error - error object
* @param {Buffer} bundle - bundle
*/
function onBundle( error, bundle ) {
var opts;
if ( error ) {
debug( 'Encountered an error when creating a bundle: %s', error.message );
return cb( error );
}
debug( 'Successfully created a bundle.' );
if ( out === void 0 ) {
return cb( null, bundle );
}
debug( 'Writing bundle to file...' );
opts = {
'encoding': 'utf8'
};
writeFile( out, bundle, opts, onWrite );
} // end FUNCTION onBundle()
/**
* Callback invoked upon writing a file.
*
* @private
* @param {(Error|null)} error - error object
*/
function onWrite( error ) {
if ( error ) {
debug( 'Encountered an error when writing bundle to file: %s', error.message );
return cb( error );
}
debug( 'Successfully wrote bundle to file.' );
cb();
} // end FUNCTION onWrite()
} // end FUNCTION bundle()
// EXPORTS //
module.exports = bundle;
| JavaScript | 0.000221 | @@ -1166,16 +1166,35 @@
bundle%0A
+%09* @returns %7Bvoid%7D%0A
%09*/%0A%09fun
@@ -1725,16 +1725,35 @@
object%0A
+%09* @returns %7Bvoid%7D%0A
%09*/%0A%09fun
|
f6a15880273b078c5922f69545546eb1fda1aea2 | Rename dialog: select notebook name instead of dir | public/ipython/notebook/js/savewidget.js | public/ipython/notebook/js/savewidget.js | // Copyright (c) IPython Development Team.
// Distributed under the terms of the Modified BSD License.
define([
'base/js/namespace',
'jquery',
'base/js/utils',
'base/js/dialog',
'base/js/keyboard',
'moment',
], function(IPython, $, utils, dialog, keyboard, moment) {
"use strict";
var SaveWidget = function (selector, options) {
/**
* TODO: Remove circular ref.
*/
this.notebook = undefined;
this.selector = selector;
this.events = options.events;
this._checkpoint_date = undefined;
this.keyboard_manager = options.keyboard_manager;
if (this.selector !== undefined) {
this.element = $(selector);
this.bind_events();
}
};
SaveWidget.prototype.bind_events = function () {
var that = this;
this.element.find('span.filename').click(function () {
that.rename_notebook({notebook: that.notebook});
});
this.events.on('notebook_loaded.Notebook', function () {
that.update_notebook_name();
that.update_document_title();
});
this.events.on('notebook_saved.Notebook', function () {
that.update_notebook_name();
that.update_document_title();
});
this.events.on('notebook_renamed.Notebook', function () {
that.update_notebook_name();
that.update_document_title();
that.update_address_bar();
});
this.events.on('notebook_save_failed.Notebook', function () {
that.set_save_status('Autosave Failed!');
});
this.events.on('notebook_read_only.Notebook', function () {
that.set_save_status('(read only)');
// disable future set_save_status
that.set_save_status = function () {};
});
this.events.on('checkpoints_listed.Notebook', function (event, data) {
that._set_last_checkpoint(data[0]);
});
this.events.on('checkpoint_created.Notebook', function (event, data) {
that._set_last_checkpoint(data);
});
this.events.on('set_dirty.Notebook', function (event, data) {
that.set_autosaved(data.value);
});
};
SaveWidget.prototype.rename_notebook = function (options) {
options = options || {};
var that = this;
var dialog_body = $('<div/>').append(
$("<p/>").addClass("rename-message")
.text('New notebook name:')
).append(
$("<br/>")
).append(
$('<input/>').attr('type','text').attr('size','25').addClass('form-control').addClass('notebook-name')
.val(options.notebook.get_notebook_name())
).append(
$("<br/>")
).append(
$("<p/>").addClass("rename-message")
.text('New notebook directory:')
).append(
$("<br/>")
).append(
$('<input/>').attr('type','text').attr('size','25').addClass('form-control').addClass('notebook-dir')
.val(options.notebook.get_notebook_dir())
);
var d = dialog.modal({
title: "Rename/move Notebook",
body: dialog_body,
notebook: options.notebook,
keyboard_manager: this.keyboard_manager,
buttons : {
"OK": {
class: "btn-primary",
click: function () {
var new_name = d.find('input.notebook-name').val();
var new_dir = d.find('input.notebook-dir').val();
if (!options.notebook.test_notebook_name(new_name)) {
d.find('.rename-message').text(
"Invalid notebook name. Notebook names must "+
"have 1 or more characters and can contain any characters " +
"except :/\\. Please enter a new notebook name:"
);
return false;
} else {
d.find('.rename-message').text("Renaming...");
d.find('input[type="text"]').prop('disabled', true);
that.notebook.rename(new_name, new_dir).then(
function () {
d.modal('hide');
}, function (error) {
d.find('.rename-message').text(error.message || 'Unknown error');
d.find('input[type="text"]').prop('disabled', false).focus().select();
}
);
return false;
}
}
},
"Cancel": {}
},
open : function () {
/**
* Upon ENTER, click the OK button.
*/
d.find('input[type="text"]').keydown(function (event) {
if (event.which === keyboard.keycodes.enter) {
d.find('.btn-primary').first().click();
return false;
}
});
d.find('input[type="text"]').focus().select();
}
});
};
SaveWidget.prototype.update_notebook_name = function () {
var nbname = this.notebook.get_notebook_name();
this.element.find('span.filename').text(nbname);
};
SaveWidget.prototype.update_document_title = function () {
var nbname = this.notebook.get_notebook_name();
document.title = nbname;
};
SaveWidget.prototype.update_address_bar = function(){
var base_url = this.notebook.base_url;
var path = this.notebook.notebook_path;
var state = {path : path};
window.history.replaceState(state, "", utils.url_join_encode(
base_url,
"notebooks",
path)
);
};
SaveWidget.prototype.set_save_status = function (msg) {
this.element.find('span.autosave_status').text(msg);
};
SaveWidget.prototype._set_last_checkpoint = function (checkpoint) {
if (checkpoint) {
this._checkpoint_date = new Date(checkpoint.last_modified);
} else {
this._checkpoint_date = null;
}
this._render_checkpoint();
};
SaveWidget.prototype._render_checkpoint = function () {
/** actually set the text in the element, from our _checkpoint value
called directly, and periodically in timeouts.
*/
this._schedule_render_checkpoint();
var el = this.element.find('span.checkpoint_status');
if (!this._checkpoint_date) {
el.text('').attr('title', 'no checkpoint');
return;
}
var chkd = moment(this._checkpoint_date);
var long_date = chkd.format('llll');
var human_date;
var tdelta = Math.ceil(new Date() - this._checkpoint_date);
if (tdelta < utils.time.milliseconds.d){
// less than 24 hours old, use relative date
human_date = chkd.fromNow();
} else {
// otherwise show calendar
// <Today | yesterday|...> at hh,mm,ss
human_date = chkd.calendar();
}
el.text('Last Checkpoint: ' + human_date).attr('title', long_date);
};
SaveWidget.prototype._schedule_render_checkpoint = function () {
/** schedule the next update to relative date
periodically updated, so short values like 'a few seconds ago' don't get stale.
*/
if (!this._checkpoint_date) {
return;
}
if ((this._checkpoint_timeout)) {
clearTimeout(this._checkpoint_timeout);
}
var dt = Math.ceil(new Date() - this._checkpoint_date);
this._checkpoint_timeout = setTimeout(
$.proxy(this._render_checkpoint, this),
utils.time.timeout_from_dt(dt)
);
};
SaveWidget.prototype.set_autosaved = function (dirty) {
if (dirty) {
this.set_save_status("(unsaved changes)");
} else {
this.set_save_status("(autosaved)");
}
};
// Backwards compatibility.
IPython.SaveWidget = SaveWidget;
return {'SaveWidget': SaveWidget};
});
| JavaScript | 0 | @@ -5381,16 +5381,30 @@
=%22text%22%5D
+.notebook-name
').focus
|
84432d74fd5fd0184a1c5c38a880c31f2fbe3e69 | fix dirname default for “name” within `create` cmd | packages/cli/lib/commands/create.js | packages/cli/lib/commands/create.js | const ora = require('ora');
const glob = require('glob');
const gittar = require('gittar');
const fs = require('fs.promised');
const { green } = require('chalk');
const { resolve } = require('path');
const { prompt } = require('inquirer');
const { promisify } = require('bluebird');
const isValidName = require('validate-npm-package-name');
const { info, isDir, hasCommand, error, trim, warn } = require('../util');
const { addScripts, install, initGit, isMissing } = require('../lib/setup');
const ORG = 'preactjs-templates';
const RGX = /\.(woff2?|ttf|eot|jpe?g|ico|png|gif|mp4|mov|ogg|webm)(\?.*)?$/i;
const isMedia = str => RGX.test(str);
const capitalize = str => str.charAt(0).toUpperCase() + str.substring(1);
module.exports = async function (repo, dest, argv) {
// Prompt if incomplete data
if (!repo || !dest) {
warn('Insufficient arguments! Prompting...');
info('Alternatively, run `preact create --help` for usage info.');
let questions = isMissing(argv);
let response = await prompt(questions);
Object.assign(argv, response);
repo = repo || response.template;
dest = dest || response.dest;
}
let cwd = resolve(argv.cwd);
let target = resolve(cwd, dest);
let isYarn = argv.yarn && hasCommand('yarn');
let exists = isDir(target);
if (exists && !argv.force) {
return error('Refusing to overwrite current directory! Please specify a different destination or use the `--force` flag', 1);
}
if (exists && argv.force) {
let { enableForce } = await prompt({
type: 'confirm',
name: 'enableForce',
message: `You are using '--force'. Do you wish to continue?`,
default: false
});
if (enableForce) {
info('Initializing project in the current directory!');
} else {
return error('Refusing to overwrite current directory!', 1);
}
}
// Use `--name` value or `dest` dir's name
argv.name = argv.name || argv.dest;
let { errors } = isValidName(argv.name);
if (errors) {
errors.unshift(`Invalid package name: ${argv.name}`);
return error(errors.map(capitalize).join('\n ~ '), 1);
}
if (!repo.includes('/')) {
repo = `${ORG}/${repo}`;
info(`Assuming you meant ${repo}...`);
}
// Attempt to fetch the `template`
let archive = await gittar.fetch(repo).catch(err => {
err = err || { message:'An error occured while fetching template.' };
return error(err.code === 404 ? `Could not find repository: ${repo}` : err.message, 1);
});
let spinner = ora({
text: 'Creating project',
color: 'magenta'
}).start();
// Extract files from `archive` to `target`
// TODO: read & respond to meta/hooks
let keeps=[];
await gittar.extract(archive, target, {
strip: 2,
filter(path, obj) {
if (path.includes('/template/')) {
obj.on('end', () => {
if (obj.type === 'File' && !isMedia(obj.path)) {
keeps.push(obj.absolute);
}
});
return true;
}
}
});
if (keeps.length) {
// eslint-disable-next-line
let dict = new Map();
// TODO: concat author-driven patterns
['name'].forEach(str => {
// if value is defined
if (argv[str] !== void 0) {
dict.set(new RegExp(`{{\\s?${str}\\s}}`, 'g'), argv[str]);
}
});
// Update each file's contents
let buf, entry, enc='utf8';
for (entry of keeps) {
buf = await fs.readFile(entry, enc);
dict.forEach((v, k) => {
buf = buf.replace(k, v);
});
await fs.writeFile(entry, buf, enc);
}
} else {
return error(`No \`template\` directory found within ${ repo }!`, 1);
}
spinner.text = 'Parsing `package.json` file';
// Validate user's `package.json` file
let pkgData, pkgFile=resolve(target, 'package.json');
if (pkgFile) {
pkgData = JSON.parse(await fs.readFile(pkgFile));
// Write default "scripts" if none found
pkgData.scripts = pkgData.scripts || (await addScripts(pkgData, target, isYarn));
} else {
warn('Could not locate `package.json` file!');
}
// Update `package.json` key
if (pkgData) {
spinner.text = 'Updating `name` within `package.json` file';
pkgData.name = argv.name.toLowerCase().replace(/\s+/g, '_');
}
// Find a `manifest.json`; use the first match, if any
let files = await promisify(glob)(target + '/**/manifest.json');
let manifest = files[0] && JSON.parse(await fs.readFile(files[0]));
if (manifest) {
spinner.text = 'Updating `name` within `manifest.json` file';
manifest.name = manifest.short_name = argv.name;
// Write changes to `manifest.json`
await fs.writeFile(files[0], JSON.stringify(manifest, null, 2));
if (argv.name.length > 12) {
// @see https://developer.chrome.com/extensions/manifest/name#short_name
process.stdout.write('\n');
warn('Your `short_name` should be fewer than 12 characters.');
}
}
if (pkgData) {
// Assume changes were made ¯\_(ツ)_/¯
await fs.writeFile(pkgFile, JSON.stringify(pkgData, null, 2));
}
if (argv.install) {
spinner.text = 'Installing dependencies';
await install(target, isYarn);
}
spinner.succeed('Done!\n');
if (argv.git) {
await initGit(target);
}
let pfx = isYarn ? 'yarn' : 'npm run';
return trim(`
To get started, cd into the new directory:
${ green('cd ' + dest) }
To start a development live-reload server:
${ green(pfx + ' start') }
To create a production build (in ./build):
${ green(pfx + ' build') }
To start a production HTTP/2 server:
${ green(pfx + ' serve') }
`) + '\n';
};
| JavaScript | 0 | @@ -1859,21 +1859,16 @@
name %7C%7C
-argv.
dest;%0A%0A
|
383b1b2f179119ea97c22931633f56ace2b98ae0 | Use synchronous dialog to fix cmd+q | packages/desktop/src/main/launch.js | packages/desktop/src/main/launch.js | import path from "path";
import { shell, BrowserWindow, dialog } from "electron";
let launchIpynb;
export function getPath(url) {
const nUrl = url.substring(url.indexOf("static"), path.length);
return path.join(__dirname, "..", "..", nUrl.replace("static/", ""));
}
export function deferURL(event, url) {
event.preventDefault();
if (!url.startsWith("file:")) {
shell.openExternal(url);
} else if (url.endsWith(".ipynb")) {
launchIpynb(getPath(url));
}
}
const iconPath = path.join(__dirname, "..", "static", "icon.png");
const initContextMenu = require("electron-context-menu");
// Setup right-click context menu for all BrowserWindows
initContextMenu();
export function launch(filename) {
let win = new BrowserWindow({
width: 800,
height: 1000,
icon: iconPath,
title: "nteract"
});
const index = path.join(__dirname, "..", "static", "index.html");
win.loadURL(`file://${index}`);
let actuallyExit = false;
win.on("close", e => {
if (!actuallyExit) {
e.preventDefault();
dialog.showMessageBox(
{
type: "question",
buttons: ["Yes", "No"],
title: "Confirm",
message: "Unsaved data will be lost. Are you sure you want to quit?"
},
function(response) {
if (response === 0) {
e.returnValue = false;
actuallyExit = true;
win.close();
}
}
);
}
});
win.webContents.on("did-finish-load", () => {
if (filename) {
win.webContents.send("main:load", filename);
}
win.webContents.send("main:load-config");
});
win.webContents.on("will-navigate", deferURL);
// Emitted when the window is closed.
win.on("closed", () => {
win = null;
});
return win;
}
launchIpynb = launch;
export function launchNewNotebook(kernelSpec) {
const win = launch();
win.webContents.on("did-finish-load", () => {
win.webContents.send("main:new", kernelSpec);
});
return win;
}
| JavaScript | 0.000001 | @@ -934,116 +934,51 @@
%0A%0A
-let actuallyExit = false;%0A%0A win.on(%22close%22, e =%3E %7B%0A if (!actuallyExit) %7B%0A e.preventDefault();%0A
+win.on(%22close%22, e =%3E %7B%0A const response =
dia
@@ -1000,23 +1000,10 @@
Box(
+%7B
%0A
- %7B%0A
@@ -1028,20 +1028,16 @@
,%0A
-
-
buttons:
@@ -1058,20 +1058,16 @@
,%0A
-
title: %22
@@ -1076,20 +1076,16 @@
nfirm%22,%0A
-
me
@@ -1159,50 +1159,12 @@
- %7D,%0A function(response) %7B%0A
+%7D);%0A
@@ -1182,11 +1182,10 @@
e ==
-= 0
+ 1
) %7B%0A
@@ -1194,123 +1194,25 @@
-
-
e.
+p
re
-turnValue = false;%0A actuallyExit = true;%0A win.close();%0A %7D%0A %7D%0A
+ventDefault(
);%0A
|
b5f3cd0c574333aa75f5c3ebcf5635c97770d8ac | Remove possibility to have slashes in id | nuserv/app/repository/repositories.js | nuserv/app/repository/repositories.js | var app = angular.module('repositoryApp.controllers', [
function() {
}
]);
app.factory('repositoryListViewModelFactory', ['$rootScope', function($rootScope) {
var repository = function (atts) {
var childScope = $rootScope.$new(true);
childScope.repository = {};
var self = childScope.repository;
var initialSettings = atts || {};
//initial settings if passed in
for (var setting in initialSettings) {
if (initialSettings.hasOwnProperty(setting))
self[setting] = initialSettings[setting];
};
if (self.isNew) {
childScope.$watch('repository.Name', function () {
childScope.repository.Id = childScope.repository.Name.replace(/[^A-Za-z0-9\/]/g, '-').replace(/\/{2,}/, '/').replace(/^\/+|\/+$/g, '').toLowerCase();
});
}
return self;
};
return {
create: repository
};
}]);
app.controller('RepositoriesController', [
'$scope', '$http', 'repositoryListViewModelFactory', function ($scope, $http, repositoryListViewModelFactory) {
//We define the model
$scope.model = {};
//We define the allMessages array in the model
//that will contain all the messages sent so far
$scope.model.repositories = [];
$scope.model.repositoryRows = [];
$scope.$watch('model.repositories', function () {
var reps = []; //$scope.model.repositories.slice(0);
angular.forEach($scope.model.repositories, function(repository) {
var repositoryListViewModel = repositoryListViewModelFactory.create(repository);
repositoryListViewModel.isNew = false;
reps.push(repositoryListViewModel);
});
//Add new repository
reps.push(repositoryListViewModelFactory.create({ Id: '', Name: '', Description: '', isNew: true }));
var result = [];
for (var i = 0; i < reps.length; i += 4) {
var row = [];
for (var j = 0; j < 4; ++j) {
if (reps[i + j]) {
// Add isNew property
if (typeof reps[i + j].isNew === 'undefined') {
reps[i + j].isNew = false;
}
row.push(reps[i + j]);
}
}
result.push(row);
}
$scope.model.repositoryRows = result;
}, true);
//The error if any
$scope.model.errorMessage = undefined;
//We initially load data so set the isAjaxInProgress = true;
$scope.model.isAjaxInProgress = true;
//Load all the messages
$http({
url: '/api/repository',
method: "GET"
}).
success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
$scope.model.repositories = data;
//We are done with AJAX loading
$scope.model.isAjaxInProgress = false;
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
$scope.model.errorMessage = "Error occurred status:" + status;
//We are done with AJAX loading
$scope.model.isAjaxInProgress = false;
});
$scope.save = function (repository) {
repository.errorName = '';
repository.errorDescription = '';
if (repository.Name.length < 3) {
repository.errorName = "Name is to short";
}
if (repository.Description.length < 1) {
repository.errorDescription = "Description is to short";
}
$http({
url: '/api/repository',
method: "POST",
data: repository
}).success(function (data, status, headers, config) {
repository.isNew = false;
}).error(function (data, status, headers, config) {
$scope.errorName = status;
});
};
$scope.delete = function(repository) {
$http({
url: '/api/repository',
method: "DELETE",
data: repository.Id
}).success(function (data, status, headers, config) {
var index = $scope.model.repositories.indexOf(repository);
repository.splice(index, 1);
}).error(function (data, status, headers, config) {
$scope.errorName = status;
});
};
}
]); | JavaScript | 0.000001 | @@ -814,18 +814,16 @@
-Za-z0-9
-%5C/
%5D/g, '-'
@@ -828,57 +828,8 @@
-').
-replace(/%5C/%7B2,%7D/, '/').replace(/%5E%5C/+%7C%5C/+$/g, '').
toLo
|
8a8d703d1b9ce60b6e6f34d36bac518a45994ef7 | Put what it looks like before how it works | src/components/About.js | src/components/About.js | import React from 'react'
import { Heading, Container, Flex, Box, Image, Text, Subhead } from 'rebass'
import Icon from './Icon'
import { colors, cx, mx, mm, wk } from '../theme'
const defaultBackgroundColor = cx('gray.1')
const Base = Container.extend.attrs({
maxWidth: '100%',
mt: 64 * -3,
pt: 64 * 3.5,
pb: 64 * 2.5,
pw: 64,
w: 1
})`
position: relative;
&:before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: -64px;
z-index: -1;
${wk('clip-path: polygon(0% 0%, 100% 0, 100% 75%, 0 100%)')}
background-color: ${props => props.backgroundcolor || defaultBackgroundColor};
background-size: auto 100%;
background-position-x: .5rem;
}
`
const BannerImage = Image.extend.attrs({
p: 16,
w: 500,
h: 350
})`
display: inline-block;
${mx[3]} {
transform: translate(0, 64px);
}
`
const Section = Container.extend.attrs({
maxWidth: 48 * 16
})`
display: inline-block;
text-align: left;
`
const CenteringContainer = Container.extend.attrs({
mx: 'auto',
maxWidth: 'none'
})`
text-align: center;
`
const TextBlock = Text.extend.attrs({
f: 4,
my: 16
})`
${mm[1]} {
font-size: 16px !important;
}
`
const Bold = Text.extend.attrs({
is: 'span',
bold: true
})``
export default ({ ...props }) => (
<Base id="about" {...props}>
<CenteringContainer>
<Section id="section">
<TextBlock>
<Bold>How it works.</Bold> You, a student who knows how to code, get
1 - 2 others to start a Hack Club. You apply, we accept you, you use
the community's open source materials and remote office hours with the
staff to get your club started.
</TextBlock>
<TextBlock>
<Bold>What it looks like.</Bold> Every week, you and around 20 other
students come together to build. Meetings are like mini-hackathons.
People are working on projects, you lead workshops to introduce new
technologies, you and your co-leads are constantly mentoring. Your
members start with no experience.
</TextBlock>
<TextBlock>
<Bold>Our philosophy.</Bold> We think people learn best when they take
control of their own education. At Hack Club, there are no teachers.
No lectures. Your job is to facilitate and provide guidance through
mentoring. Hack Club is heavily inspired by unschooling.
</TextBlock>
</Section>
<BannerImage src="/about_hacking.jpg" />
</CenteringContainer>
</Base>
)
| JavaScript | 0.000002 | @@ -1417,330 +1417,8 @@
ck%3E%0A
- %3CBold%3EHow it works.%3C/Bold%3E You, a student who knows how to code, get%0A 1 - 2 others to start a Hack Club. You apply, we accept you, you use%0A the community's open source materials and remote office hours with the%0A staff to get your club started.%0A %3C/TextBlock%3E%0A %3CTextBlock%3E%0A
@@ -1802,32 +1802,354 @@
%3CTextBlock%3E%0A
+ %3CBold%3EHow it works.%3C/Bold%3E You, a student who knows how to code, get%0A 1 - 2 others to start a Hack Club. You apply, we accept you, you use%0A the community's open source materials and remote office hours with the%0A staff to get your club started.%0A %3C/TextBlock%3E%0A %3CTextBlock%3E%0A
%3CBold%3E
|
28df4f7258df6930b0fa5892becde4c8962c6017 | Add simple location to Geolocation package | packages/geolocation/geolocation.js | packages/geolocation/geolocation.js | var locationDep = new Deps.Dependency();
var location = null;
var locationRefresh = false;
var options = {
enableHighAccuracy: true,
maximumAge: 0
};
var errCallback = function () {
// do nothing
};
var callback = function (newLocation) {
location = newLocation;
locationDep.changed();
};
var enableLocationRefresh = function () {
if (! locationRefresh && navigator.geolocation) {
navigator.geolocation.watchPosition(callback, errCallback, options);
locationRefresh = true;
}
};
Geolocation = {
currentLocation: function () {
enableLocationRefresh();
locationDep.depend();
return location;
}
}; | JavaScript | 0 | @@ -624,14 +624,270 @@
cation;%0A
+ %7D,%0A // simple version of location; just lat and lng%0A latLng: function () %7B%0A var loc = Geolocation.currentLocation();%0A%0A if (loc) %7B%0A return %7B%0A lat: loc.coords.latitude,%0A lng: loc.coords.longitude%0A %7D;%0A %7D%0A%0A return null;%0A
%7D%0A%7D;
|
427d3ae7f91670d6176e15286b3de4a0f3005022 | Add some margin to the output value of a Brick | src/components/Brick.js | src/components/Brick.js | import React, { PropTypes, Component } from 'react'
import { Group, Text } from 'react-art'
import Rectangle from 'react-art/lib/Rectangle.art'
import composeBrick from './composeBrick'
import { getConstant } from './constants'
import { getFillColor } from '../utils'
import {
BindingPropTypes,
PositionPropTypes,
SizePropTypes,
SlotPropTypes
} from '../propTypes'
import { ERROR } from '../utils/evalUtils'
class Brick extends Component {
constructor(props) {
super(props)
this.startDrag = this.startDrag.bind(this)
}
startDrag(mouseEvent) {
const { handleMouseDown, id, position } = this.props
handleMouseDown(id, mouseEvent, position)
}
render() {
const {
componentName,
binding,
name,
outputSlots,
size
} = this.props
const midHeight = size.height / 2 - 7
const outputSlotId = Object.keys(outputSlots)[0]
const { outputElementIds } = outputSlots[outputSlotId]
const slotHeight = getConstant(componentName, 'slotHeight')
const slotWidth = getConstant(componentName, 'slotWidth')
return (
<Group
onMouseDown={ this.startDrag }
y={ slotHeight }
>
<Rectangle
height={ size.height }
width={ size.width }
stroke={ getConstant(componentName, 'strokeColor') }
fill={ getConstant(componentName, 'fillColor') }
/>
<Text
alignment={ getConstant(componentName, 'alignment') }
fill={ getConstant(componentName, 'textColor') }
font={ getConstant(componentName, 'font') }
x={ size.width / 2 }
y={ midHeight }
>
{ name }
</Text>
{ outputElementIds.length == 0 && binding.type &&
<Text
fill={ getFillColor(binding.type, binding.value) }
font={ getConstant(componentName, 'outputFont') }
x={ ((size.width - slotWidth) / 2) + slotWidth }
y={ size.height }
>
{ binding.value }
</Text>
}
</Group>
)
}
}
Brick.propTypes = {
componentName: PropTypes.string.isRequired,
binding: BindingPropTypes,
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
position: PositionPropTypes.isRequired,
outputSlots: SlotPropTypes.isRequired,
size: SizePropTypes.isRequired
}
export default composeBrick(Brick)
| JavaScript | 0.001527 | @@ -1937,24 +1937,28 @@
+ slotWidth
++ 3
%7D%0A
@@ -1967,32 +1967,36 @@
y=%7B size.height
++ 2
%7D%0A %3E%0A
|
af56a39be34c4c42ffffbcf9f5dff5bba268bb8a | Add close icon to modal window | src/components/Modal.js | src/components/Modal.js | import React from 'react'
import styled from 'styled-components'
const Modal = props =>
props.isOpen ? (
<ModalContainer>
<ModalContent>{props.children}</ModalContent>
</ModalContainer>
) : (
<div />
)
const ModalContainer = styled.div`
display: flex;
justify-content: center;
align-items: center;
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(0, 0, 0, 0.5);
z-index: 999;
padding: 50px;
`
const ModalContent = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
align-items: center;
width: 100%;
max-width: 600px;
min-height: 200px;
border-radius: 4px;
background-color: ${props => props.theme.paletteTertiary};
box-shadow: rgba(25, 17, 34, 0.05) 0px 3px 10px;
padding: 5rem 2rem;
`
export default Modal
| JavaScript | 0 | @@ -57,16 +57,61 @@
ponents'
+%0Aimport Close from 'react-icons/lib/md/close'
%0A%0Aconst
@@ -187,16 +187,83 @@
Content%3E
+%0A %3CCloseIcon onClick=%7B() =%3E props.handleClose()%7D /%3E%0A
%7Bprops.c
@@ -270,16 +270,23 @@
hildren%7D
+%0A
%3C/ModalC
@@ -392,16 +392,42 @@
: flex;%0A
+ flex-direction: column;%0A
justif
@@ -934,17 +934,209 @@
ng:
-5rem 2rem
+2rem 2rem 5rem 2rem;%0A%60%0A%0Aconst CloseIcon = styled(Close)%60%0A width: 2rem;%0A height: 2rem;%0A cursor: pointer;%0A color: $%7Bprops =%3E props.theme.paletteFontPrimary%7D;%0A padding-left: 80%25;%0A margin: 0 0 4rem 0
;%0A%60%0A
|
c212e62ed53015800e8dfc2c5d663b44746d23eb | add AudioListener to camera in sound component. #801 #356 | src/components/sound.js | src/components/sound.js | var debug = require('../utils/debug');
var diff = require('../utils').diff;
var registerComponent = require('../core/component').registerComponent;
var THREE = require('../lib/three');
var warn = debug('components:sound:warn');
/**
* Sound component.
*
* @param {bool} [autoplay=false]
* @param {string} on
* @param {bool} [loop=false]
* @param {number} [volume=1]
*/
module.exports.Component = registerComponent('sound', {
schema: {
src: { default: '' },
on: { default: 'click' },
autoplay: { default: false },
loop: { default: false },
volume: { default: 1 }
},
init: function () {
this.listener = null;
this.sound = null;
},
update: function (oldData) {
var data = this.data;
var diffData = diff(oldData || {}, data);
var el = this.el;
var sound = this.sound;
var src = data.src;
var srcChanged = 'src' in diffData;
// Create new sound if not yet created or changing `src`.
if (srcChanged) {
if (!src) {
warn('Audio source was not specified with `src`');
return;
}
sound = this.setupSound();
}
if (srcChanged || 'autoplay' in diffData) {
sound.autoplay = data.autoplay;
}
if (srcChanged || 'loop' in diffData) {
sound.setLoop(data.loop);
}
if (srcChanged || 'volume' in diffData) {
sound.setVolume(data.volume);
}
if ('on' in diffData) {
if (oldData && oldData.on) {
el.removeEventListener(oldData.on);
}
el.addEventListener(data.on, this.play.bind(this));
}
// All sound values set. Load in `src.
if (srcChanged) {
sound.load(src);
}
},
remove: function () {
this.el.removeObject3D('sound');
this.sound.remove();
this.listener.remove();
this.listener.context.close();
},
/**
* Removes current sound object, creates new sound object, adds to entity.
*
* @returns {object} sound
*/
setupSound: function () {
var el = this.el;
var listener;
var sound = this.sound;
if (sound) {
this.stop();
el.removeObject3D('sound');
}
listener = this.listener = new THREE.AudioListener();
sound = this.sound = new THREE.Audio(listener);
el.setObject3D('sound', sound);
return sound;
},
play: function () {
if (this.sound.source.buffer) {
this.sound.play();
}
},
stop: function () {
this.sound.stop();
},
pause: function () {
this.sound.pause();
}
});
| JavaScript | 0 | @@ -2162,24 +2162,61 @@
Listener();%0A
+ el.sceneEl.camera.add(listener);%0A
sound =
|
fbd516d44813f226fd5e32b9370b1e609590e7d7 | Update tmhDynamicLocale.js | src/tmhDynamicLocale.js | src/tmhDynamicLocale.js | (function (root, factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module unless amdModuleId is set
define([], function () {
return (factory());
});
} else if (typeof exports === 'object') {
// Node. Does not work with strict CommonJS, but
// only CommonJS-like environments that support module.exports,
// like Node.
module.exports = factory();
} else {
factory();
}
}(this, function () {
'use strict';
angular.module('tmh.dynamicLocale', []).config(['$provide', function($provide) {
function makeStateful($delegate) {
$delegate.$stateful = true;
return $delegate;
}
$provide.decorator('dateFilter', ['$delegate', makeStateful]);
$provide.decorator('numberFilter', ['$delegate', makeStateful]);
$provide.decorator('currencyFilter', ['$delegate', makeStateful]);
}])
.constant('tmhDynamicLocale.STORAGE_KEY', 'tmhDynamicLocale.locale')
.provider('tmhDynamicLocale', ['tmhDynamicLocale.STORAGE_KEY', function(STORAGE_KEY) {
var defaultLocale,
localeLocationPattern = 'angular/i18n/angular-locale_{{locale}}.js',
storageFactory = 'tmhDynamicLocaleStorageCache',
storage,
storageKey = STORAGE_KEY,
promiseCache = {},
activeLocale;
/**
* Loads a script asynchronously
*
* @param {string} url The url for the script
@ @param {function} callback A function to be called once the script is loaded
*/
function loadScript(url, callback, errorCallback, $timeout) {
var script = document.createElement('script'),
body = document.getElementsByTagName('body')[0],
removed = false;
script.type = 'text/javascript';
if (script.readyState) { // IE
script.onreadystatechange = function () {
if (script.readyState === 'complete' ||
script.readyState === 'loaded') {
script.onreadystatechange = null;
$timeout(
function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
}, 30, false);
}
};
} else { // Others
script.onload = function () {
if (removed) return;
removed = true;
body.removeChild(script);
callback();
};
script.onerror = function () {
if (removed) return;
removed = true;
body.removeChild(script);
errorCallback();
};
}
script.src = url;
script.async = false;
body.appendChild(script);
}
/**
* Loads a locale and replaces the properties from the current locale with the new locale information
*
* @param {string} localeUrl The path to the new locale
* @param {Object} $locale The locale at the curent scope
* @param {string} localeId The locale id to load
* @param {Object} $rootScope The application $rootScope
* @param {Object} $q The application $q
* @param {Object} localeCache The current locale cache
* @param {Object} $timeout The application $timeout
*/
function loadLocale(localeUrl, $locale, localeId, $rootScope, $q, localeCache, $timeout) {
function overrideValues(oldObject, newObject) {
if (activeLocale !== localeId) {
return;
}
angular.forEach(oldObject, function(value, key) {
if (!newObject[key]) {
delete oldObject[key];
} else if (angular.isArray(newObject[key])) {
oldObject[key].length = newObject[key].length;
}
});
angular.forEach(newObject, function(value, key) {
if (angular.isArray(newObject[key]) || angular.isObject(newObject[key])) {
if (!oldObject[key]) {
oldObject[key] = angular.isArray(newObject[key]) ? [] : {};
}
overrideValues(oldObject[key], newObject[key]);
} else {
oldObject[key] = newObject[key];
}
});
}
if (promiseCache[localeId]) return promiseCache[localeId];
var cachedLocale,
deferred = $q.defer();
if (localeId === activeLocale) {
deferred.resolve($locale);
} else if ((cachedLocale = localeCache.get(localeId))) {
activeLocale = localeId;
$rootScope.$evalAsync(function() {
overrideValues($locale, cachedLocale);
storage.put(storageKey, localeId);
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
deferred.resolve($locale);
});
} else {
activeLocale = localeId;
promiseCache[localeId] = deferred.promise;
loadScript(localeUrl, function() {
// Create a new injector with the new locale
var localInjector = angular.injector(['ngLocale']),
externalLocale = localInjector.get('$locale');
overrideValues($locale, externalLocale);
localeCache.put(localeId, externalLocale);
delete promiseCache[localeId];
$rootScope.$apply(function() {
storage.put(storageKey, localeId);
$rootScope.$broadcast('$localeChangeSuccess', localeId, $locale);
deferred.resolve($locale);
});
}, function() {
delete promiseCache[localeId];
$rootScope.$apply(function() {
if (activeLocale === localeId) {
activeLocale = $locale.id;
}
$rootScope.$broadcast('$localeChangeError', localeId);
deferred.reject(localeId);
});
}, $timeout);
}
return deferred.promise;
}
this.localeLocationPattern = function(value) {
if (value) {
localeLocationPattern = value;
return this;
} else {
return localeLocationPattern;
}
};
this.useStorage = function(storageName) {
storageFactory = storageName;
};
this.useCookieStorage = function() {
this.useStorage('$cookieStore');
};
this.defaultLocale = function(value) {
defaultLocale = value;
};
this.storageKey = function(value) {
if (value) {
storageKey = value;
return this;
} else {
return storageKey;
}
};
this.$get = ['$rootScope', '$injector', '$interpolate', '$locale', '$q', 'tmhDynamicLocaleCache', '$timeout', function($rootScope, $injector, interpolate, locale, $q, tmhDynamicLocaleCache, $timeout) {
var localeLocation = interpolate(localeLocationPattern);
storage = $injector.get(storageFactory);
$rootScope.$evalAsync(function() {
var initialLocale;
if ((initialLocale = (storage.get(storageKey) || defaultLocale))) {
loadLocaleFn(initialLocale);
}
});
return {
/**
* @ngdoc method
* @description
* @param {string} value Sets the locale to the new locale. Changing the locale will trigger
* a background task that will retrieve the new locale and configure the current $locale
* instance with the information from the new locale
*/
set: loadLocaleFn,
/**
* @ngdoc method
* @description Returns the configured locale
*/
get: function() {
return activeLocale;
}
};
function loadLocaleFn(localeId) {
return loadLocale(localeLocation({locale: localeId, version: angular.version.full}), locale, localeId, $rootScope, $q, tmhDynamicLocaleCache, $timeout);
}
}];
}]).provider('tmhDynamicLocaleCache', function() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('tmh.dynamicLocales');
}];
}).provider('tmhDynamicLocaleStorageCache', function() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('tmh.dynamicLocales.store');
}];
}).run(['tmhDynamicLocale', angular.noop]);
return 'tmh.dynamicLocale';
}));
| JavaScript | 0 | @@ -7153,17 +7153,24 @@
caleId,
-v
+angularV
ersion:
|
a8abb720a1d887a42469bb6d29ae3b6304dc451f | Add user, server, and channel registration functions to savefile.js | src/tracker/savefile.js | src/tracker/savefile.js | /*
* SAVEFILE STRUCTURE
* ==================
*
* {
* meta: {
* users: {
* <discord user id>: {
* name: <user name>
* }, ...
* },
*
* // the user index is an array of discord user ids,
* // these indexes are used in the message objects to save space
* userindex: [
* <discord user id>, ...
* ],
*
* servers: [
* {
* name: <server name>,
* type: <"SERVER"|"DM">
* }, ...
* ],
*
* channels: {
* <discord channel id>: {
* server: <server index in the meta.servers array>,
* name: <channel name>
* }, ...
* }
* },
*
* data: {
* <discord channel id>: {
* <discord message id>: {
* u: <user index of the sender>,
* t: <message timestamp>,
* m: <message content>,
* f: <message flags>, // bit 1 = edited, bit 2 = has user mentions (omit for no flags),
* e: [ // omit for no embeds
* {
* url: <embed url>,
* type: <embed type>
* }, ...
* ],
* a: [ // omit for no attachments
* {
* url: <attachment url>
* }, ...
* ]
* }, ...
* }, ...
* }
* }
*
*
* TEMPORARY OBJECT STRUCTURE
* ==========================
*
* {
* userlookup: {
* <discord user id>: <user index in the meta.userindex array>
* }
* }
*/
var SAVEFILE = function(){
this.meta = {};
this.meta.users = {};
this.meta.userindex = [];
this.meta.servers = [];
this.meta.channels = {};
this.data = {};
this.tmp = {};
this.tmp.userlookup = {};
};
};
SAVEFILE.prototype.toJson = function(){
return JSON.stringify({
meta: this.meta,
data: this.data
});
};
| JavaScript | 0 | @@ -1668,16 +1668,1083 @@
= %7B%7D;%0A%7D;
+%0A%0ASAVEFILE.prototype.findOrRegisterUser = function(userId, userName)%7B%0A if (!(userId in this.meta.users))%7B%0A this.meta.users%5BuserId%5D = %7B%0A name: userName%0A %7D;%0A %0A this.meta.userindex.push(userId);%0A return this.tmp.userlookup%5BuserId%5D = this.meta.userindex.length-1;%0A %7D%0A else%7B%0A return this.tmp.userlookup%5BuserId%5D;%0A %7D%0A%7D;%0A%0ASAVEFILE.prototype.findOrRegisterServer = function(serverName, serverType)%7B%0A var index = this.meta.servers.findIndex(server =%3E server.name === serverName && server.type === serverType);%0A %0A if (index === -1)%7B%0A this.meta.servers.push(%7B%0A name: serverName,%0A type: serverType%0A %7D);%0A %0A return this.meta.servers.length-1;%0A %7D%0A else%7B%0A return index;%0A %7D%0A%7D;%0A%0ASAVEFILE.prototype.tryRegisterChannel = function(serverIndex, channelId, channelName)%7B%0A if (!this.meta.servers%5BserverIndex%5D)%7B%0A return undefined;%0A %7D%0A else if (channelId in this.meta.channels)%7B%0A return false;%0A %7D%0A else%7B%0A this.meta.channels%5BchannelId%5D = %7B%0A server: serverIndex,%0A name: channelName%0A %7D;%0A %0A return true;%0A %7D
%0A%7D;%0A%0ASAV
|
11672d104f419b4fa5351d1b689a1a0da487b031 | Align #include to the left. | src/util/PaperScript.js | src/util/PaperScript.js | var PaperScript = new function() {
//TODO: Make sure there are all the correct copyrights for the inlined
//parse-js:
//#include "../../lib/parse-js-min.js"
// Handle Math Operators
var operators = {
'+': 'add',
'-': 'subtract',
'*': 'multiply',
'/': 'divide',
'%': 'modulo',
'==': 'equals',
'!=': 'equals'
};
function $operator(left, operator, right) {
var handler = operators[operator];
if (left && left[handler]) {
var res = left[handler](right);
return operator == '!=' ? !res : res;
}
switch (operator) {
case '+': return left + right;
case '-': return left - right;
case '*': return left * right;
case '/': return left / right;
case '%': return left % right;
case '==': return left == right;
case '!=': return left != right;
default:
throw new Error('Implement Operator: ' + operator);
}
};
// Handle Sign Operators
var signs = {
'-': 'negate'
};
function $sign(operator, value) {
var handler = signs[operator];
if (value && value[handler]) {
return value[handler]();
}
switch (operator) {
case '+': return +value;
case '-': return -value;
default:
throw new Error('Implement Sign Operator: ' + operator);
}
}
// AST Helpers
function isDynamic(exp) {
var type = exp[0];
return type != 'num' && type != 'string';
}
function handleOperator(operator, left, right) {
// Only replace operators with calls to $operator if the left hand side
// is potentially an object.
if (operators[operator] && isDynamic(left)) {
// Replace with call to $operator(left, operator, right):
return ['call', ['name', '$operator'],
[left, ['string', operator], right]];
}
}
function compile(code) {
// Use parse-js to translate the code into a AST structure which is then
// walked and parsed for operators to overload. The resulting AST is
// translated back to code and evaluated.
var ast = parse_js.parse(code),
walker = parse_js.walker(),
walk = walker.walk;
ast = walker.with_walkers({
'binary': function(operator, left, right) {
// Handle simple mathematical operators here:
return handleOperator(operator, left = walk(left),
right = walk(right))
// Always return something since we're walking left and
// right for the handleOperator() call already.
|| [this[0], operator, left, right];
},
'assign': function(operator, left, right) {
// Handle assignments like +=, -=, etc:
// Check if the assignment operator needs to be handled by paper
// if so, convert the assignment to a simple = and use result of
// of handleOperator on the right hand side.
var res = handleOperator(operator, left = walk(left),
right = walk(right));
if (res)
return [this[0], true, left, res];
// Always return something for the same reason as in binary
return [this[0], operator, left, right];
},
'unary-prefix': function(operator, exp) {
if (signs[operator] && isDynamic(exp)) {
return ['call', ['name', '$sign'],
[['string', operator], walk(exp)]];
}
}
}, function() {
return walk(ast);
});
return parse_js.stringify(ast, true);
}
function run(code) {
// Use paper.extend() to create a paper scope within which the code is
// evaluated.
with (paper.extend()) {
var tool = /onMouse(?:Up|Down|Move|Drag)/.test(code) && new Tool();
var res = eval(compile(code));
if (tool) {
Base.each(['onEditOptions', 'onOptions', 'onSelect',
'onDeselect', 'onReselect', 'onMouseDown', 'onMouseUp',
'onMouseDrag', 'onMouseMove'], function(key) {
try {
tool[key] = eval(key);
} catch (e) {
}
});
}
return res;
}
}
//#ifdef BROWSER
// Code borrowed from Coffee Script:
function load(url) {
var xhr = new (window.ActiveXObject || XMLHttpRequest)('Microsoft.XMLHTTP');
xhr.open('GET', url, true);
if ('overrideMimeType' in xhr) {
xhr.overrideMimeType('text/plain');
}
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
return run(xhr.responseText);
}
};
return xhr.send(null);
}
function runScripts() {
var scripts = document.getElementsByTagName('script');
for (var i = 0, l = scripts.length; i < l; i++) {
var script = scripts[i];
if (script.type === 'text/paperscript') {
// If a canvas id is provided, create a document for it now, so
// the active document is defined.
var canvas = script.getAttribute('canvas');
if (canvas && (canvas = document.getElementById(canvas))) {
new Document(canvas);
}
if (script.src) {
load(script.src);
} else {
run(script.innerHTML);
}
}
}
return null;
}
if (window.addEventListener) {
addEventListener('load', runScripts, false);
} else {
attachEvent('onload', runScripts);
}
//#endif // BROWSER
return {
compile: compile,
run: run
};
};
| JavaScript | 0 | @@ -28,17 +28,16 @@
ion() %7B%0A
-%09
//TODO:
@@ -98,20 +98,17 @@
inlined
-%0A%09//
+
parse-js
@@ -109,17 +109,16 @@
rse-js:%0A
-%09
//#inclu
|
e2b99ff82d464b5a8be4e856c34f737184b9b326 | Fix redirect to old dashboard version if user is logged in to another account | src/utils/RoutesUtil.js | src/utils/RoutesUtil.js | import _ from 'lodash';
import Cookies from 'js-cookie';
import localStorage from 'local-storage-fallback';
import URI from 'urijs';
import auth from '../apps/Account/auth';
import NewLibConnection from '../apps/Session/NewLibConnection';
import SessionStore from '../apps/Session/SessionStore';
import SessionActions from '../apps/Session/SessionActions';
import AuthStore from '../apps/Account/AuthStore';
const RoutesUtil = {
checkActiveSubscriptions(nextState, replace, callback) {
const connection = NewLibConnection.get();
const token = localStorage.getItem('token');
if (token) {
connection.setAccountKey(token);
}
return connection
.Profile
.please()
.get()
.then(({ status }) => {
const redirectRoute = {
no_active_subscription: '/expired/',
free_limits_exceeded: '/free-limits-exceeded/',
hard_limit_reached: '/hard-limits-reached/',
overdue_invoices: '/failed-payment/'
}[status];
redirectRoute && replace(redirectRoute);
callback();
});
},
checkInstanceActiveSubscription(nextState, replace, callback) {
const connection = NewLibConnection.get();
const token = localStorage.getItem('token');
const { instanceName } = nextState.params;
if (token) {
connection.setAccountKey(token);
}
if (instanceName) {
let currentUserEmail;
return connection
.Account
.getUserDetails()
.then(({ email }) => {
currentUserEmail = email;
})
.then(() => (
connection
.Instance
.please()
.get({ name: instanceName })
))
.then(({ owner }) => {
if (owner.email === currentUserEmail) {
return RoutesUtil.checkActiveSubscriptions(nextState, replace, callback);
}
return callback();
})
.catch(console.error);
}
return callback();
},
isInstanceAvailable(instanceName) {
const connection = NewLibConnection.get();
return connection
.Instance
.please()
.get({ name: instanceName });
},
onAppEnter(nextState, replace) {
const uri = new URI();
const originalUri = uri.normalize().toString();
let pathname = decodeURIComponent(nextState.location.pathname).replace('//', '/');
const query = _.extend({}, uri.search(true), nextState.location.query);
if (Cookies.get('redirectMode')) {
if (!localStorage.getItem('token')) {
localStorage.setItem('token', Cookies.get('token'));
}
localStorage.removeItem('lastPathname');
localStorage.removeItem('lastInstanceName');
Cookies.remove('redirectMode', { domain: APP_CONFIG.SYNCANO_BASE_DOMAIN });
Cookies.remove('token', { domain: APP_CONFIG.SYNCANO_BASE_DOMAIN });
SessionActions.fetchUser();
}
SessionStore.setUTMData(nextState.location.query);
// remove trailing slash
if (pathname.length > 1 && pathname.match('/$') !== null) {
pathname = pathname.slice(0, -1);
}
uri.search(query);
uri.hash(`${pathname}${uri.search()}`);
uri.search('');
const normalizedUri = uri.normalize().toString();
if (originalUri !== normalizedUri) {
location.href = normalizedUri;
return null;
}
let name = 'app';
const names = nextState.routes.map((route) => route.name).filter((routeName) => typeof routeName !== 'undefined');
if (names.length > 0) {
name = names[names.length - 1];
}
if (name === 'login' || name === 'signup') {
window.analytics.page(`Dashboard ${_.capitalize(name)}`, {
path: nextState.location.pathname
});
} else {
window.analytics.page('Dashboard', {
Page: name,
path: nextState.location.pathname,
category: 'Dashboard',
label: name
});
}
if (nextState.location.query.invitation_key) {
return AuthStore.acceptInvitationFromUrl();
}
if (auth.loggedIn() && nextState.location.pathname === '/' && !query.token) {
return this.redirectToLastPathname(nextState, replace);
}
return null;
},
onDashboardChange(prevState, nextState, replace) {
localStorage.setItem('lastPathname', nextState.location.pathname);
if (nextState.location.pathname === '/') {
this.redirectToLastInstance(nextState, replace);
}
},
onDashboardEnter(nextState, replace) {
const { signUpMode } = nextState.location.query;
if (!signUpMode) {
this.redirectToSyn4Instance(nextState);
}
if (!auth.loggedIn() && !signUpMode) {
return this.redirectToLogin(nextState, replace);
}
return null;
},
redirectToDashboard(nextState, replace) {
if (auth.loggedIn()) {
replace({ pathname: '/' });
}
},
redirectToLastInstance(nextState, replace) {
const lastInstanceName = localStorage.getItem('lastInstanceName');
if (lastInstanceName) {
this.isInstanceAvailable(lastInstanceName).then(() => replace({
pathname: `/instances/${lastInstanceName}/my-sockets/`
}));
}
},
redirectToLastPathname(nextState, replace) {
const lastPathname = localStorage.getItem('lastPathname');
if (lastPathname && lastPathname !== '/') {
return replace({ pathname: lastPathname });
}
return null;
},
redirectToLogin(nextState, replace) {
const query = _.omit(nextState.location.query, 'next');
if (nextState.location.query.next) {
return replace({
name: 'login',
state: { nextPathname: nextState.location.pathname },
query: _.merge({ next: nextState.location.pathname }, query)
});
}
Cookies.remove('logged_in', { domain: APP_CONFIG.SYNCANO_BASE_DOMAIN });
return replace({ name: 'login', query: _.merge({ next: nextState.location.pathname }, query) });
},
redirectToSyn4Instance(nextState) {
const lastInstanceName = nextState.params.instanceName;
return this.isInstanceAvailable(lastInstanceName)
.then((instance = {}) => {
const instanceCreatedAt = Date.parse(instance.created_at);
const releaseDate = Number(APP_CONFIG.SYNCANO5_RELEASE_DATE);
if (instanceCreatedAt < releaseDate && !instance.metadata.testInstance) {
Cookies.set('token', localStorage.getItem('token'), {
domain: APP_CONFIG.SYNCANO_BASE_DOMAIN,
expires: 365
});
Cookies.set('redirectMode', true, {
domain: APP_CONFIG.SYNCANO_BASE_DOMAIN,
expires: 365
});
window.location = `${APP_CONFIG.SYNCANO_OLD_DASHBOARD}/#/instances/${instance.name}`;
}
});
},
onInstanceEnter(nextState, replace, cb) {
this.checkInstanceActiveSubscription(nextState, replace, cb);
this.redirectToSyn4Instance(nextState);
}
};
export default RoutesUtil;
| JavaScript | 0 | @@ -2484,54 +2484,8 @@
) %7B%0A
- if (!localStorage.getItem('token')) %7B%0A
@@ -2538,24 +2538,16 @@
oken'));
-%0A %7D
%0A%0A
|
d02638066fb9e0761591fc57f0b42f2d52715f75 | fix syntax | src/utils/date-utils.js | src/utils/date-utils.js | import moment from 'moment';
var generateShortMonths = function(startingMonth) {
const shortMonths = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun',
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'];
return shortMonths.slice(startingMonth)
.concat(shortMonths.slice(0, startingMonth));
}
var generateAllDates = function(startingDate, endDate) {
let allDates = [];
let [yearStartingDate, monthStartingDate, dayStartingDate] = startingDate.split('-');
let [yearEndDate, monthEndDate, dayEndDate] = endDate.split('-');
allDates = allDates.concat(generateDatesMonth(yearStartingDate, monthStartingDate, parseInt(dayStartingDate)));
let monthsAndYearToGenerate = getMonthsAndYear(monthStartingDate, yearStartingDate);
let otherDates = monthsAndYearToGenerate.map(([month, year]) => {
return generateDatesMonth(year, month, 1);
});
allDates = allDates.concat(_.flatten(otherDates));
//allDates = allDates.concat(this.generateDatesMonth(yearEndDate, monthEndDate, parseInt(dayEndDate) + 1));
return allDates;
}
var getMonthsAndYear: function(startingMonth, startingYear) {
let i = 0;
let res = [];
let currentValMonth = parseInt(startingMonth) + 1;
let currentValYear = parseInt(startingYear);
while (i < 11) {
res.push([currentValMonth.toString(), currentValYear.toString()]);
if (parseInt(currentValMonth) + 1 > 12) {
currentValMonth = '01';
currentValYear = parseInt(currentValYear) + 1
} else {
currentValMonth = getIntValAsString((parseInt(currentValMonth) + 1).toString());
}
i++;
}
return res;
}
var getIntValAsString = function(val) {
if (val.length === 1) {
return '0' + val;
} else {
return val.toString();
}
}
var generateDatesMonth = function(_year, _month, fromDay) {
let res = [];
const numDaysInMonths = {'01': 31, '02': 28, '03': 31, '04': 30, '05': 31, '06': 30,
'07': 31, '08': 31, '09': 30, '10': 31, '11': 30, '12': 31};
let numDays = numDaysInMonths[_month];
for (var i=fromDay; i<numDays+1; i++) {
res.push(_year + '-' + _month + '-' + getIntValAsString(i.toString()));
}
return res;
}
var getDaysBackToClosestSunday = function(firstDate) {
let res = [];
let indexDayOfWeek = moment(firstDate).day();
if (indexDayOfWeek > 0) {
for (var i=1; i<=indexDayOfWeek; i++) {
res.push([moment(firstDate).subtract(i, 'days').format('YYYY-MM-DD'), 0]);
}
}
return res;
}
module.exports = {
generateAllDates: generateAllDates,
generateShortMonths: generateShortMonths,
getDaysBackToClosestSunday: getDaysBackToClosestSunday
}
| JavaScript | 0.000023 | @@ -1107,17 +1107,18 @@
sAndYear
-:
+ =
functio
|
1d2b9a5f93742dc037852141f57687f3fc26f023 | add keys to search query string | src/utils/query.util.js | src/utils/query.util.js | "use strict";
import _ from 'lodash';
function parseQueryStringObject (queryStringObject) {
return _.flatten(_.map(queryStringObject, parseQueryStringElement));
}
function parseQueryStringElement(values, key) {
return values.split('|').map((value, i)=> {
return {
value,
type: key,
index: key + value + i,
cql: key + '=' + value
}
})
}
function stateToQuery(state) {
let query = {}
state.each((element)=>{
query[element.key] = query[element.key] || [];
query[element.key].push(value);
});
return query.map((element) => element.join('|')).join('&');
}
export default {
queryToState: parseQueryStringObject,
stateToQuery
} | JavaScript | 0.000003 | @@ -424,19 +424,22 @@
%7D%0A
-state
+_
.each(
+state,
(ele
@@ -465,19 +465,20 @@
element.
-key
+type
%5D = quer
@@ -487,19 +487,20 @@
element.
-key
+type
%5D %7C%7C %5B%5D;
@@ -522,18 +522,27 @@
ent.
-key
+type
%5D.push(
+element.
valu
@@ -564,30 +564,50 @@
urn
-query.map((element) =%3E
+_.map(query, (element, key) =%3E key + %22=%22 +
ele
|
254a3a85d6ca2e769949c7062bb6035dcfd9cd11 | Fix single event class bindings | addon/components/ilios-calendar-event.js | addon/components/ilios-calendar-event.js | import Ember from 'ember';
import { default as CalendarEvent } from 'el-calendar/components/calendar-event';
import layout from '../templates/components/ilios-calendar-event';
import moment from 'moment';
const {computed, Handlebars} = Ember;
const {SafeString} = Handlebars;
export default CalendarEvent.extend({
layout,
event: null,
timeFormat: 'h:mma',
classNames: ['event', 'event-pos', 'ilios-calendar-event', 'event.eventClass', 'day'],
tooltipContent: computed('event', function(){
let str = this.get('event.location') + '<br />' +
moment(this.get('event.startDate')).format(this.get('timeFormat')) + ' - ' +
moment(this.get('event.endDate')).format(this.get('timeFormat')) + '<br />' +
this.get('event.name');
return str;
}),
style: computed(function() {
let escape = Handlebars.Utils.escapeExpression;
return new SafeString(
`top: ${escape(this.calculateTop())}%;
height: ${escape(this.calculateHeight())}%;
left: ${escape(this.calculateLeft())}%;
width: ${escape(this.calculateWidth())}%;`
);
}),
click(){
this.sendAction('action', this.get('event'));
}
});
| JavaScript | 0.000057 | @@ -372,13 +372,21 @@
Name
+Binding
s: %5B'
+:
even
@@ -386,24 +386,25 @@
%5B':event', '
+:
event-pos',
@@ -404,16 +404,17 @@
-pos', '
+:
ilios-ca
@@ -449,16 +449,17 @@
lass', '
+:
day'%5D,%0A
|
05295cf14967fc04c4dffba1a487134949b6a037 | Add controller function to retrieve list of view data for heat map | api/controllers/ViewSessionController.js | api/controllers/ViewSessionController.js | /**
* ViewSessionController
*
* @description :: Server-side logic for managing video view sessions to calculate statistics
* @help :: See http://links.sailsjs.org/docs/controllers
*/
module.exports = {
/**
* Default routes generated using blueprints
* :::::::::::::::::::::::::::::::::::::::::::::::::::::::
* GET /viewsession -> Returns all the view sessions
* GET /viewsession/:id -> Returns view session with specified id
* DELETE /viewsession/:id -> Delete and returns the view session with specified id
*/
// List of overridden and custom routes
/**
* `ViewSessionController.create()`
* Usage: POST /api/viewsession
* Description: Create a video view session for the specified video
*/
create: function (req, res) {
if (!req.body.sessionId || !req.body.videoId || !req.body.coordinates || !req.body.width || !req.body.videoTime) {
return res.json({
error: 'Required fields are not entered.'
});
}
// need video id, check if videoId exist
Video.findOne({
id: req.body.videoId
}).exec(function (err, video) {
if (err) throw err;
if (!video) {
// no matched video id, return video not found
return res.status(404).notFound('VideoNotFound');
}
// create a new session if sessionId does not exist
ViewSession.findOne({
sessionId: req.body.sessionId
}).exec(function (err, session) {
if (err) throw err;
if (!session) {
// no matched session id, create a new view session first
ViewSession.create({
sessionId: req.body.sessionId,
videoId: req.body.videoId
}).exec(function (err, session) {
if (err) throw err;
// create viewData object and update into ViewSession
createViewData(session, req, res);
});
}
else {
// a match, create viewData object and update into ViewSession
createViewData(session, req, res);
}
});
});
}
};
// List of common functions
/* Function to create view data object */
function createViewData(session, req, res) {
ViewData.create({
coordinates: req.body.coordinates,
width: req.body.width,
videoTime: req.body.videoTime,
sessionObj: session.id
}).exec(function (err, data) {
if (err) throw err;
res.json(data);
});
};
| JavaScript | 0 | @@ -2050,16 +2050,773 @@
%7D);%0A
+ %7D,%0A%0A /**%0A * %60ViewSessionController.getVideoStat()%60%0A * Usage: GET /api/viewsession/getVideoStat/:id%0A * Description: Get list of video data for specified video id%0A */%0A getVideoStat: function (req, res) %7B%0A ViewSession.find(%7B%0A videoId: req.param('id')%0A %7D).populate('viewLogs').exec(function (err, sessions) %7B%0A if (err) return res.negotiate(err);%0A%0A if (!sessions) %7B%0A // no session for matched video id, return empty array%0A return res.json(%5B%5D);%0A %7D%0A%0A // get viewdata objects%0A var viewDataList = %5B%5D;%0A sessions.forEach(function (session) %7B%0A session.viewLogs.forEach(function (viewdata) %7B%0A viewDataList.push(viewdata);%0A %7D)%0A %7D);%0A return res.json(viewDataList);%0A %7D)%0A
%7D%0A%7D;%0A%0A
|
2737bb11a92f22c710824d1c3b36dab289beeb67 | add _requireSignedOut method to router | app/assets/javascripts/routers/router.js | app/assets/javascripts/routers/router.js | Maildog.Routers.Router = Backbone.Router.extend({
initialize: function(options) {
this.$rootEl = options.$rootEl;
this.$flashEl = options.$flashEl;
this.flashMessages = new Maildog.Views.FlashMessageList();
this.$flashEl.html(this.flashMessages.render().$el);
},
routes: {
"session/new": "signIn",
"": "inbox",
"inbox": "inbox",
"emails/:id": "showEmailThead"
},
signIn: function(callback) {
if (!this._requireSignedOut(callback)) {
return;
}
var signInView = new Maildog.Views.SignIn({
callback: callback
});
this._swapView(signInView);
},
inbox: function() {
this._removeFlashes();
Maildog.inboxEmails.fetch();
this.trigger("folderLinkClick");
var view = new Maildog.Views.EmailList({ collection: Maildog.inboxEmails });
this._swapView(view);
},
showEmailThead: function(id) {
this._removeFlashes();
var thread = new Maildog.Collections.EmailThreads({ id: id });
thread.fetch();
this.trigger("showEmailMessageOptions", thread);
var view = new Maildog.Views.ShowEmailThread({ collection: thread });
this._swapView(view);
},
addFlash: function(message) {
this.flashMessages.addMessage(message);
},
_removeFlashes: function() {
this.flashMessages.removeMessages();
},
_swapView: function(newView) {
this._currentView && this._currentView.remove();
this._currentView = newView;
this.$rootEl.html(newView.render().$el);
}
});
| JavaScript | 0 | @@ -846,16 +846,224 @@
;%0A %7D,%0A%0A
+ _requireSignedOut: function(callback) %7B%0A if (Maildog.currentUser.isSignedIn()) %7B%0A callback = callback %7C%7C this._goHome.bind(this);%0A callback();%0A return false;%0A %7D%0A%0A return true;%0A %7D,%0A%0A
showEm
|
2d676bb12f40c298806f064909d07239864231a2 | update on delete | app/controllers/wh/content/type/index.js | app/controllers/wh/content/type/index.js | export default Ember.ArrayController.extend({
type: null,
cmsControls: null,
controlsChanged: function () {
this.set('cmsControls', this.get('contentType.controls').filterBy('showInCms'));
this._updateItemControls();
}.observes('contentType.controls.@each.showInCms'),
contentChanged: function () {
this._updateItemControls();
}.observes('@each'),
_updateItemControls: function () {
this.get('content').forEach(function (item) {
var cmsControls = Ember.A([]);
this.get('cmsControls').forEach(function (control) {
cmsControls.pushObject({
value: item.get('data')[control.get('name')],
controlType: control.get('controlType')
});
});
item.set('cmsControls', cmsControls);
}, this);
},
actions: {
deleteItem: function (item) {
item.destroyRecord();
},
toggleShowInCms: function (control) {
control.toggleProperty('showInCms');
this.get('contentType').save();
}
}
});
| JavaScript | 0 | @@ -854,16 +854,93 @@
Record()
+.then(function () %7B%0A window.ENV.sendBuildSignal();%0A %7D.bind(this))
;%0A %7D,
|
834e9759427ae21fd489b4b31f8663e701638d4e | remove console log from expenses | app/js/Controllers/ExpensesController.js | app/js/Controllers/ExpensesController.js | expenseTrackerAppModule.controller('expenseTracker.ExpensesController', function ($scope, $location, $routeParams, $rootScope, UserModel, ExpensesModel, CategoriesModel, CurrenciesModel) {
'use strict';
var now,
currentCategoryId,
v,
infiniteValue = 0,
up = 0,
down = 0,
$ival = $('div.ival');
$scope.categories = CategoriesModel.listCategories();
$scope.categoryColors = CategoriesModel.getAvailableColors();
if ($location.$$path === '/expenses/add') {
$scope.currentExpense = ExpensesModel.initNewExpense();
now = new Date();
$scope.currentExpense.date = now.toDateString();
$scope.currentExpense.time = now.toLocaleTimeString();
} else if ($location.$$path.indexOf('/expenses/remove/') != -1) {
ExpensesModel.removeExpenseFromCollection($routeParams.id);
$location.path('/feed');
} else {
$scope.currentExpense = ExpensesModel.getCurrentExpense();
}
$scope.amount = ExpensesModel.getAmount();
currentCategoryId = ExpensesModel.getCategory();
$scope.selectedCategory = CategoriesModel.getCategoryById(currentCategoryId);
$scope.userCurrency = CurrenciesModel.getCurrencyById(UserModel.getCurrency());
$scope.chooseCategory = function (categoryId) {
ExpensesModel.setCategory(categoryId);
$location.path('/expenses/add/details');
};
$scope.saveExpense = function () {
//console.log( "saveExpense" );
ExpensesModel.addExpenseToCollection();
$location.path('/feed');
};
$scope.updateValue = function (value) {
ExpensesModel.setAmount(value);
$scope.amount = ExpensesModel.getAmount();
$scope.$digest();
};
// Example of infinite knob, iPod click wheel
var incr = function () {
infiniteValue++;
$ival.html(infiniteValue);
$scope.updateValue(infiniteValue);
},
decr = function () {
if (ExpensesModel.getAmount() !== 0) {
infiniteValue--;
$ival.html(infiniteValue);
$scope.updateValue(infiniteValue);
}
};
// init jQuery knob
$('.infinite').knob({
min: 0,
max: 30,
width: 230,
height: 230,
stopper: false,
cursor: 30,
inline: false,
fgColor: '#0fb2be',
bgColor: '#e6e6e7',
displayInput: false,
change: function () {
if (v > this.cv) {
if (up) {
decr();
up = 0;
} else {
up = 1;
down = 0;
}
} else {
if (v < this.cv) {
if (down) {
incr();
down = 0;
} else {
down = 1;
up = 0;
}
}
}
v = this.cv;
}
});
}); | JavaScript | 0.000001 | @@ -1352,45 +1352,8 @@
) %7B%0A
-%09%09//console.log( %22saveExpense%22 );%0A%09%09%0A
%09%09Ex
|
108cc837079959cbe55ce333f978f4c53c15097e | Add comment about an encoding issue in resource | app/js/arethusa.core/resource.service.js | app/js/arethusa.core/resource.service.js | "use strict";
// A service that acts like a factory. The create functions spawns new resource
// objects, that are a wrapper around ngResource
angular.module('arethusa.core').service('resource', function($resource, $location) {
var paramsToObj = function(params) {
return arethusaUtil.inject({}, params, function(obj, param, i) {
obj[param] = $location.search()[param];
});
};
this.create = function(conf) {
var obj = {
// Our custom get function reads params from the route as specified in the
// configuration of a resource and takes additional params if need be.
get: function(otherParams) {
var params = angular.extend(paramsToObj(obj.params), otherParams || {});
return obj.resource.get(params).$promise;
}
};
obj.route = conf.route;
obj.params = conf.params || [];
obj.resource = $resource(obj.route, null, {
// This might look exceedingly stupid, but it is not:
// We override the usual get method ngResource, so that we can handle
// xml here as well, something the original struggles a bit with, as it
// always awaits a JSON response. In the transformResponse function we
// have access to the real response data - we set this right onto a new
// object together with the original headers.
// This way the xml string of the http call is not mangled up by angular.
// We'll see if this leads to troubles with real JSON calls. If it does,
// we just add a configuration setting of xml: true, which triggers this
// behaviour.
// The only downside is, that we have to call res.data instead of just res
// in the callback, but that is something we can live with.
'get' : {
method: 'GET',
transformResponse: function(data, headers) {
var res = {};
res.data = data;
res.headers = headers;
return res;
}
}
});
return obj;
};
});
| JavaScript | 0 | @@ -137,16 +137,411 @@
esource%0A
+//%0A// Note that this approach right now doesn't work with totally freeform URL passed%0A// as route, because ngResource will always encode slashes.%0A// There is a pending issue for this https://github.com/angular/angular.js/issues/1388%0A//%0A// As it's not a top priority right now, we don't do anything. The quickest workaround%0A// (apart from patching angular) would be to fall back to $http.get()%0A//
%0Aangular
@@ -2124,13 +2124,11 @@
-'
get
-'
: %7B
|
e2e21ff5d2708491c9d16bf965f8fade3a6b6461 | Write the direct image URL instead of the cors-anywhere proxied URL to the database | ui/js/controllers/dashboard_qna_image.js | ui/js/controllers/dashboard_qna_image.js | import find from 'lodash/collection/find';
import uniq from 'lodash/array/uniq';
import reduce from 'lodash/collection/reduce';
import map from 'lodash/collection/map';
import nlp from 'nlp_compromise';
import poweredByBingImg from '../../images/powered_by_bing';
export default class {
constructor($scope, $http, prefetchImage, toast) {
'ngInject';
let $searchInput = angular.element(document.querySelector('.search > input')),
tokenizeQuestion = function() {
let {question, answers} = $scope.image;
$scope.tokens = uniq(reduce(
nlp.pos(`${question} ${map(answers, 'answer').join(' ')}`, {dont_combine: true}).sentences,
function(result, sentence) {
sentence.tokens.forEach(function(token) {
result.push(token.normalised);
});
return result;
},
[]
));
},
init = function() {
tokenizeQuestion();
if ($scope.image.url) {
prefetchImage($scope.image.url, $scope.corsPort).then(function(url) {
$scope.images.push(url);
}).catch(function() {
return toast.show('Unable to get image');
});
}
};
Object.assign($scope, {
poweredByBingImg,
query: '',
images: [],
previous() {
$scope.i--;
$scope.search(true);
},
next() {
$scope.i++;
$scope.search();
},
search(previous) {
Object.assign($scope, {
loading: true,
lastQuery: $scope.query,
i: $scope.query === $scope.lastQuery ? $scope.i : 0
});
$http.get('image', {params: {index: $scope.i, query: $scope.query}}).then(function({data}) {
prefetchImage(data, $scope.corsPort).then(function(url) {
$scope.images[0] = url;
Object.assign($scope, {
currentImage: url,
loading: false
});
}).catch(function() {
previous ? $scope.previous() : $scope.next();
});
}).catch(function() {
$scope.loading = false;
toast.show('Unable to get image');
});
},
tokenClicked(e) {
let text = angular.element(e.target).text().trim(),
searchContainsToken = find(
nlp.pos($scope.query, {dont_combine: true}).sentences,
function({tokens}) {
return find(tokens, 'normalised', text);
}
);
if (!searchContainsToken) {
$scope.query += ($scope.query.length < 1 ? '' : ' ') + text;
}
$searchInput.focus();
},
leave() {
$scope.tabs.i = 0;
$scope.image.question = null;
},
save() {
$scope.image.url = $scope.currentImage;
$scope.leave();
}
});
init();
}
} | JavaScript | 0.000001 | @@ -2319,19 +2319,20 @@
tImage:
-url
+data
,%0A
|
8bbf89e8e92e0a1acdbda89297aeffa2ba676073 | use capture to intercept trigger before checking for focus returning | packages/veui/src/managers/focus.js | packages/veui/src/managers/focus.js | import { remove, findIndex, keys } from 'lodash'
import { focusIn } from '../utils/dom'
import Vue from 'vue'
class FocusContext {
/**
*
* @param {Element} root Root element for focus context
* @param {FocusManager} env FocusManager instance that creates this context
* @param {=Element} source Previous focused element
* @param {=Boolean} trap Whether focus should be trapped inside root
* @param {=Element} preferred Where we should start searching for focusable elements
*/
constructor (root, env, { source, trap = false, preferred }) {
if (!root) {
throw new Error('Root must be specified to create a FocusContext instance.')
}
this.root = root
this.env = env
this.source = source
this.trap = trap
this.preferred = preferred
this.outsideStartHandler = () => {
this.focusAt(-2, true)
}
this.outsideEndHandler = () => {
this.focusAt(1, true)
}
this.init()
}
/**
* Initalize a focus context:
* 1. trap focus events inside `root`
* 2. focus `root` by default
*/
init () {
if (this.trap) {
let before = document.createElement('div')
before.tabIndex = 0
let after = before.cloneNode()
before.addEventListener('focus', this.outsideStartHandler, true)
after.addEventListener('focus', this.outsideEndHandler, true)
this.root.insertBefore(before, this.root.firstChild)
this.root.appendChild(after)
this.wardBefore = before
this.wardAfter = after
}
// skip wardBefore if trapping
this.focusAt(this.trap ? 1 : 0)
}
focusAt (index = 0, ignoreAutofocus) {
Vue.nextTick(() => {
if (!focusIn(this.preferred || this.root, index, ignoreAutofocus)) {
this.root.focus()
}
})
}
destroy () {
let { trap, source, wardBefore, wardAfter } = this
if (trap) {
wardBefore.removeEventListener('focus', this.outsideStartHandler, true)
wardAfter.removeEventListener('focus', this.outsideEndHandler, true)
this.root.removeChild(wardBefore)
this.root.removeChild(wardAfter)
}
if (source) {
this.source = null
// restore focus in a macro task to prevent
// triggering events on the original focus
if (typeof source.focus === 'function' && this.env.trigger !== 'pointer') {
setTimeout(() => {
source.focus()
}, 0)
}
}
this.preferred = null
this.root = null
}
}
export class FocusManager {
/**
* Global focus history stack
* @type Array.<FocusContext>
* @private
*/
stack = []
triggerHandlers = {
keydown: () => {
this.trigger = 'keyboard'
},
mousedown: () => {
this.trigger = 'pointer'
},
touchstart: () => {
this.trigger = 'pointer'
}
}
initTriggerHandlers () {
keys(this.triggerHandlers).forEach(type => {
document.addEventListener(type, this.triggerHandlers[type], false)
})
}
destroyTriggerHandlers () {
keys(this.triggerHandlers).forEach(type => {
document.removeEventListener(type, this.triggerHandlers[type], false)
})
}
createContext (root, options = {}) {
if (!this.stack.length) {
this.initTriggerHandlers()
}
let context = new FocusContext(root, this, options)
this.stack.push(context)
return context
}
toTop (context) {
this.detach(context)
this.stack.push(context)
}
detach (context) {
let stack = this.stack
let i = findIndex(stack, context)
if (i === -1) {
return
}
if (i < stack.length - 1) {
stack[i + 1].source = context.source
}
remove(this.stack, item => item === context)
return context
}
remove (context) {
this.detach(context)
context.destroy()
if (!this.stack.length) {
this.destroyTriggerHandlers()
}
}
}
export default new FocusManager()
| JavaScript | 0 | @@ -2592,16 +2592,111 @@
k = %5B%5D%0A%0A
+ /**%0A * Latest interaction is triggered by pointer or keyboard%0A */%0A trigger = 'pointer'%0A%0A
trigge
@@ -2709,16 +2709,16 @@
ers = %7B%0A
-
keyd
@@ -2827,70 +2827,8 @@
er'%0A
- %7D,%0A touchstart: () =%3E %7B%0A this.trigger = 'pointer'%0A
@@ -2968,36 +2968,35 @@
Handlers%5Btype%5D,
-fals
+tru
e)%0A %7D)%0A %7D%0A%0A
@@ -3142,20 +3142,19 @@
%5Btype%5D,
-fals
+tru
e)%0A %7D
|
1044bf187b26a441c4745d3f9a7e794e7b1d5ac6 | Update aggregation column too on layer change | lib/assets/javascripts/cartodb3/editor/widgets-form/schemas/data/widgets-form-category-data-schema-model.js | lib/assets/javascripts/cartodb3/editor/widgets-form/schemas/data/widgets-form-category-data-schema-model.js | var cdb = require('cartodb.js');
module.exports = cdb.core.Model.extend({
defaults: {
schema: {}
},
initialize: function (attrs, opts) {
if (!opts.widgetDefinitionModel) throw new Error('layerDefinitionsCollection is required');
if (!opts.layerDefinitionsCollection) throw new Error('layerDefinitionsCollection is required');
this.widgetDefinitionModel = opts.widgetDefinitionModel;
this._layerDefinitionsCollection = opts.layerDefinitionsCollection;
this._setAttributes();
this.on('change:layer_id', this._onChangeLayerId, this);
},
updateSchema: function () {
var layers = this._layers();
var columns = this._columnsForSelectedLayer();
this.schema = {
title: {
type: 'Text',
validators: ['required']
},
layer_id: {
type: 'Select',
label: 'Source layer',
options: layers
},
column: {
type: 'Select',
label: 'Value',
options: columns,
editorAttrs: {
disabled: columns[0].disabled
}
},
aggregation: {
type: 'Select',
options: ['sum', 'count']
},
aggregation_column: {
type: 'Select',
options: [].concat(this.get('aggregation_column') || this.get('column'))
},
suffix: {
type: 'Text'
},
prefix: {
type: 'Text'
}
};
this.trigger('changeSchema');
},
updateDefinitionModel: function () {
this.widgetDefinitionModel.set({
layer_id: this.get('layer_id'),
title: this.get('title'),
options: {
column: this.get('column'),
aggregation: this.get('aggregation'),
aggregation_column: this.get('aggregation_column'),
suffix: this.get('suffix'),
prefix: this.get('prefix')
}
});
this.widgetDefinitionModel.widgetModel.update(this.attributes);
},
_setAttributes: function () {
var m = this.widgetDefinitionModel;
var o = m.get('options');
this.set({
layer_id: m.get('layer_id'),
title: m.get('title'),
column: o.column,
aggregation: o.aggregation,
aggregation_column: o.aggregation_column,
suffix: o.suffix,
prefix: o.prefix
});
},
_layers: function () {
return this._layerDefinitionsCollection
.chain()
.filter(function (m) {
return m.getTableModel();
})
.map(function (m) {
return {
val: m.id,
label: m.get('options').table_name
};
})
.value();
},
_columnsForSelectedLayer: function () {
var layerDefModel = this._layerDefinitionsCollection.get(this.get('layer_id'));
var tableModel = layerDefModel.getTableModel();
if (tableModel.get('complete')) {
return tableModel
.columnsCollection
.map(function (m) {
var columnName = m.get('name');
return {
val: m.id,
label: columnName
};
});
} else {
// Missing columns, fetch the table data and show a unselectable loading indicator for the time being
tableModel.fetch({
success: this.updateSchema.bind(this)
});
return [{
label: 'loading…',
disabled: true
}];
}
},
_onChangeLayerId: function () {
this.set('column', null);
this.updateSchema();
}
});
| JavaScript | 0 | @@ -1221,71 +1221,89 @@
ns:
-%5B%5D.concat(this.get('aggregation_column') %7C%7C this.get('column'))
+columns,%0A editorAttrs: %7B%0A disabled: columns%5B0%5D.disabled%0A %7D
%0A
|
652ec02a791c9bfbe4d3cb6e1f7133529445fa92 | remove not used , close #98 | app/scripts/directives/map_controller.js | app/scripts/directives/map_controller.js | /**
* @ngdoc directive
* @name MapController
* @requires $scope
* @property {Hash} controls collection of Controls initiated within `map` directive
* @property {Hash} markersi collection of Markers initiated within `map` directive
* @property {Hash} shapes collection of shapes initiated within `map` directive
* @property {MarkerClusterer} markerClusterer MarkerClusterer initiated within `map` directive
*/
/*jshint -W089*/
ngMap.MapController = function($scope) {
this.map = null;
this._objects = [];
/**
* Add a marker to map and $scope.markers
* @memberof MapController
* @name addMarker
* @param {Marker} marker google map marker
*/
this.addMarker = function(marker) {
/**
* marker and shape are initialized before map is initialized
* so, collect _objects then will init. those when map is initialized
* However the case as in ng-repeat, we can directly add to map
*/
if (this.map) {
this.map.markers = this.map.markers || {};
marker.setMap(this.map);
if (marker.centered) {
this.map.setCenter(marker.position);
}
var len = Object.keys(this.map.markers).length;
this.map.markers[marker.id || len] = marker;
} else {
this._objects.push(marker);
}
};
/**
* Add a shape to map and $scope.shapes
* @memberof MapController
* @name addShape
* @param {Shape} shape google map shape
*/
this.addShape = function(shape) {
if (this.map) {
this.map.shapes = this.map.shapes || {};
shape.setMap(this.map);
var len = Object.keys(this.map.shapes).length;
this.map.shapes[shape.id || len] = shape;
} else {
this._objects.push(shape);
}
};
this.addObject = function(groupName, obj) {
if (this.map) {
this.map[groupName] = this.map[groupName] || {};
var len = Object.keys(this.map[groupName]).length;
this.map[groupName][obj.id || len] = obj;
if (groupName != "infoWindows" && obj.setMap) { //infoWindow.setMap works like infoWindow.open
obj.setMap(this.map);
}
} else {
obj.groupName = groupName;
this._objects.push(obj);
}
}
/**
* Add a shape to map and $scope.shapes
* @memberof MapController
* @name addShape
* @param {Shape} shape google map shape
*/
this.addObjects = function(objects) {
for (var i=0; i<objects.length; i++) {
var obj=objects[i];
if (obj instanceof google.maps.Marker) {
this.addMarker(obj);
} else if (obj instanceof google.maps.Circle ||
obj instanceof google.maps.Polygon ||
obj instanceof google.maps.Polyline ||
obj instanceof google.maps.Rectangle ||
obj instanceof google.maps.GroundOverlay) {
this.addShape(obj);
} else {
this.addObject(obj.groupName, obj);
}
}
};
};
| JavaScript | 0.000001 | @@ -458,22 +458,16 @@
unction(
-$scope
) %7B %0A%0A
|
86cbf95fd4f695e4d662ec13dd3ebf7b0d2d2efa | improve the code | server/api/package/package.controller.js | server/api/package/package.controller.js | 'use strict';
var _ = require('lodash');
var Package = require('./package.model');
var logger = require('../../components/logger');
var sanitize = require('sanitize-filename');
var path = require('path');
var fs = require('fs');
var tar = require('tar');
// Get list of packages
exports.index = function (req, res) {
Package.findQ({})
.then(function (packages) {
if (!packages) {
res.status(404).end();
}
else {
res.status(200).json(packages);
}
})
.catch(function (err) {
logger.error({err: err, req: req});
res.status(500).end();
});
};
// Get a single package
exports.show = function (req, res) {
Package.findOneQ({name: req.params.name})
.then(function (pkg) {
if (!pkg) {
res.status(404).end();
}
else {
res.status(200).json(pkg);
}
})
.catch(function (err) {
logger.error({err: err, req: req});
res.status(500).end();
});
};
// Creates a new package in the DB.
exports.create = function (req, res) {
var newPackage = new Package(req.body);
newPackage.saveQ()
.then(function (pkg) {
if (!pkg) {
res.status(500).end();
}
else {
res.status(201).json(pkg);
}
})
.catch(function (err) {
logger.error({err: err, req: req});
res.status(500).end();
});
};
// Updates an existing package in the DB.
exports.update = function (req, res) {
var data = _.pick(req.body, ['name', 'repo']);
Package.findOneQ({name: req.params.name})
.then(function (pkg) {
if (!pkg) {
res.status(404).end();
}
else {
pkg.set(data);
return pkg.saveQ();
}
})
.then(function () {
res.status(200).end();
})
.catch(function (err) {
logger.error({err: err, req: req});
res.status(500).end();
});
};
// Deletes a package from the DB.
exports.destroy = function (req, res) {
Package.findOneAndRemoveQ({name: req.params.name})
.then(function (pkg) {
if (!pkg) {
res.status(404).end();
}
else {
res.status(204).end();
}
})
.catch(function (err) {
logger.error({err: err, req: req});
res.status(500).end();
});
};
exports.tarballDownload = function (req, res, next) {
var pkgName = sanitize(req.params.name);
var fileName = path.join('tarballs', pkgName + '.tgz');
var readStream = fs.createReadStream(fileName);
readStream.on('error', function (err) {
return next(err);
});
res.attachment(fileName);
readStream.pipe(res);
};
exports.tarballUpload = function (req, res) {
var pkgName = sanitize(req.params.name);
var fileName = path.join('tarballs', pkgName + '.tgz');
// TODO: create/update model
var mainDir = path.join(path.dirname(require.main.filename), '..');
var tarball = path.join(mainDir, req.file.path);
fs.createReadStream(tarball).pipe(tar.Parse()).on('error', function () {
fs.unlink(tarball, function () {
res.status(400).send();
});
}).on('readable', function () {
fs.rename(tarball, path.join(mainDir, fileName), function (err) {
if (err) {
logger.error({err: err, req: req});
fs.unlink(tarball, function () {
res.status(500).send();
});
}
res.end();
});
});
}; | JavaScript | 0.999983 | @@ -2785,106 +2785,17 @@
var
-mainDir = path.join(path.dirname(require.main.filename), '..');%0A var tarball = path.join(mainDir,
+tarball =
req
@@ -2804,17 +2804,16 @@
ile.path
-)
;%0A%0A fs.
@@ -2837,16 +2837,21 @@
tarball)
+%0A
.pipe(ta
@@ -2860,16 +2860,21 @@
Parse())
+%0A
.on('err
@@ -2888,24 +2888,26 @@
nction () %7B%0A
+
fs.unlin
@@ -2929,32 +2929,34 @@
tion () %7B%0A
+
res.status(400).
@@ -2967,22 +2967,26 @@
();%0A
+
%7D);%0A
+
+
%7D).on('r
@@ -3013,16 +3013,18 @@
) %7B%0A
+
fs.renam
@@ -3037,27 +3037,8 @@
all,
- path.join(mainDir,
fil
@@ -3042,17 +3042,16 @@
fileName
-)
, functi
@@ -3063,24 +3063,26 @@
rr) %7B%0A
+
if (err) %7B%0A
@@ -3072,32 +3072,34 @@
if (err) %7B%0A
+
logger.e
@@ -3131,24 +3131,26 @@
);%0A%0A
+
+
fs.unlink(ta
@@ -3172,32 +3172,34 @@
() %7B%0A
+
res.status(500).
@@ -3210,24 +3210,26 @@
();%0A
+
+
%7D);%0A %7D%0A
@@ -3230,11 +3230,15 @@
+
%7D%0A%0A
+
@@ -3254,20 +3254,24 @@
();%0A
+
%7D);%0A
+
%7D);%0A%7D;
|
75795b81069c029a1c8430dbd990ce02d653a6af | Improve socket and ping handling | server/backends/irc/connectionManager.js | server/backends/irc/connectionManager.js | #!/usr/bin/env node --harmony
//
// Copyright 2014 Ilkka Oksanen <iao@iki.fi>
//
// 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';
// Minimal connection manager that keeps TCP sockets alive even if
// rest of the system is restarted. Allows nondistruptive updates.
require('../../lib/init')('irc-connman');
var net = require('net'),
carrier = require('carrier'),
isUtf8 = require('is-utf8'),
iconv = require('iconv-lite'),
conf = require('../../lib/conf'),
log = require('../../lib/log'),
courier = require('../../lib/courier').createEndPoint('connectionmanager');
var sockets = {};
const IDENTD_PORT = 113;
courier.sendNoWait('ircparser', 'restarted');
// Start IDENT server
if (conf.get('irc:identd')) {
net.createServer(handleIdentConnection).listen(IDENTD_PORT);
}
function handleIdentConnection(conn) {
var timer = setTimeout(function() {
if (conn) {
conn.destroy();
}
}, 3000);
carrier.carry(conn, function(line) {
var ports = line.split(',');
var localPort = parseInt(ports[0]);
var remotePort = parseInt(ports[1]);
var prefix = localPort + ', ' + remotePort;
var found = false;
var resp;
if (!isNaN(localPort) && !isNaN(remotePort)) {
for (var userId in sockets) {
if (sockets[userId].localPort === localPort &&
sockets[userId].remotePort === remotePort &&
sockets[userId].remoteAddress === conn.remoteAddress) {
found = true;
resp = prefix + ' : USERID : UNIX : ' + sockets[userId].nick + '\r\n';
break;
}
}
if (!found) {
resp = prefix + ' : ERROR : NO-USER\r\n';
}
}
clearTimeout(timer);
if (resp) {
conn.write(resp);
}
conn.end();
log.info('Ident request from ' + conn.remoteAddress + ', req: ' + line +', resp: ' + resp);
});
}
// Connect
courier.on('connect', function(params) {
var userId = params.userId;
var network = params.network;
var options = {
port: params.port,
host: params.host
};
var client = net.connect(options);
client.nick = params.nick;
client.setKeepAlive(true, 2 * 60 * 1000); // 2 minutes
client.on('connect', function() {
courier.sendNoWait('ircparser', {
type: 'connected',
userId: userId,
network: network
});
});
var buffer = '';
client.on('data', function(data) {
// IRC protocol doesn't have character set concept, we need to guess.
// Algorithm is simple. If received binary data is valid utf8 then use
// that. Else assume that the character set is iso-8859-15.
data = isUtf8(data) ? data.toString() : iconv.decode(data, 'iso-8859-15');
data = buffer + data;
var lines = data.split(/\r\n/);
buffer = lines.pop(); // Save the potential partial line to buffer
lines.forEach(function(line) {
courier.sendNoWait('ircparser', {
type: 'data',
userId: userId,
network: network,
line: line
});
});
});
client.on('end', function() {
log.info(userId, 'IRC connection closed by the server.');
courier.sendNoWait('ircparser', {
type: 'disconnected',
userId: userId,
network: network,
reason: 'connection closed by peer'
});
});
client.on('error', function(err) {
log.info(userId, 'IRC connection error: ' + err);
courier.sendNoWait('ircparser', {
type: 'disconnected',
userId: userId,
network: network,
reason: err.code
});
});
sockets[userId + ':' + network] = client;
});
// Disconnect
courier.on('disconnect', function(params) {
var userId = params.userId;
var network = params.network;
sockets[userId + ':' + network].end();
delete sockets[userId + ':' + network];
});
// Write
courier.on('write', function(params) {
var userId = params.userId;
var network = params.network;
var data = params.line;
if (!sockets[userId + ':' + network]) {
log.warn(userId, 'Non-existent socket');
return;
}
if (typeof(data) === 'string') {
data = [data];
}
for (var i = 0; i < data.length; i++) {
sockets[userId + ':' + network].write(data[i] + '\r\n');
}
});
courier.start();
| JavaScript | 0.000001 | @@ -2683,32 +2683,51 @@
params.network;%0A
+ var pingTimer;%0A
var options
@@ -2922,16 +2922,103 @@
inutes%0A%0A
+ function sendPing() %7B%0A client.write('PING ' + params.host + '%5Cr%5Cn');%0A %7D%0A%0A
clie
@@ -3180,32 +3180,87 @@
work%0A %7D);
+%0A%0A pingTimer = setInterval(sendPing, 60 * 1000);
%0A %7D);%0A%0A va
@@ -4029,19 +4029,21 @@
ent.on('
-end
+close
', funct
@@ -4038,32 +4038,41 @@
lose', function(
+had_error
) %7B%0A log.
@@ -4120,16 +4120,27 @@
e server
+ or network
.');%0A
@@ -4294,326 +4294,121 @@
on:
-'connection closed by peer'%0A %7D);%0A %7D);%0A%0A client.on('error', function(err) %7B%0A log.info(userId, 'IRC connection error: ' + err);%0A courier.sendNoWait('ircparser', %7B%0A type: 'disconnected',%0A userId: userId,%0A network: network,%0A reason: err.code%0A %7D
+had_error ? 'transmission error' : 'connection closed by the server'%0A %7D);%0A%0A clearInterval(pingTimer
);%0A
|
475982c0f14212d8b00386eb693efdaa2e94de29 | fix middlewares appling | lib/createRouter.js | lib/createRouter.js | const { flatten, concat } = require('ramda');
const ExpressPromiseRouter = require('express-promise-router');
const requireTree = require('require-tree');
const { methodsNames } = require('./methods');
const createValidationMiddleware = require('./createValidationMiddleware');
const createController = require('./createController');
const DEFAULT_CONFIGURATION = {
routePrefix: null,
onValidationError: error => error,
onReply: data => ({ data }),
middlewaresSequence: ({
PARAMS_VALIDATION,
QUERY_VALIDATION,
BODY_VALIDATION,
ROUTER_MIDDLEWARES,
}) => [
PARAMS_VALIDATION,
QUERY_VALIDATION,
BODY_VALIDATION,
ROUTER_MIDDLEWARES,
],
};
const ROUTER_MIDDLEWARES = Symbol('ROUTER_MIDDLEWARES');
const PARAMS_VALIDATION = Symbol('PARAMS_VALIDATION');
const QUERY_VALIDATION = Symbol('QUERY_VALIDATION');
const BODY_VALIDATION = Symbol('BODY_VALIDATION');
const composeMiddlewares = (middlewares, middlewaresSequence) =>
flatten(middlewaresSequence.map(middleware =>
(typeof middleware === 'symbol'
? middlewares[middleware]
: middleware)));
module.exports = (config = {}) => {
const router = ExpressPromiseRouter();
const {
routePrefix,
routesPath,
middlewaresSequence: middlewaresSequenceFn,
onReply,
onValidationError,
} = Object.assign({}, DEFAULT_CONFIGURATION, config);
const middlewaresSequence = middlewaresSequenceFn({
PARAMS_VALIDATION,
QUERY_VALIDATION,
BODY_VALIDATION,
ROUTER_MIDDLEWARES,
});
Object
.values(requireTree(routesPath))
.reduce(concat)
.forEach(({
method,
path: routePath,
controller: routeController,
middlewares: routeMiddlewares,
validation: {
params,
query,
body,
},
}) => {
const MIDDLEWARES = {
[ROUTER_MIDDLEWARES]: routeMiddlewares || [],
[PARAMS_VALIDATION]: createValidationMiddleware.bind(null, 'params', onValidationError, params),
[QUERY_VALIDATION]: createValidationMiddleware.bind(null, 'query', onValidationError, query),
[BODY_VALIDATION]: createValidationMiddleware.bind(null, 'body', onValidationError, body),
};
const methodName = methodsNames[method];
const methodFn = router[methodName];
const middlewares = composeMiddlewares(MIDDLEWARES, middlewaresSequence);
const controller = createController(onReply, routeController);
methodFn.apply(router, [
`${routePrefix ? `/${routePrefix}` : ''}${routePath}`,
...middlewares,
controller,
]);
});
return router;
};
| JavaScript | 0.000009 | @@ -1923,28 +1923,17 @@
ddleware
-.bind(null,
+(
'params'
@@ -2016,28 +2016,17 @@
ddleware
-.bind(null,
+(
'query',
@@ -2110,20 +2110,9 @@
ware
-.bind(null,
+(
'bod
|
b87e99c8fd6e1e978bb613543bdbbab9b47acc11 | Fix bug in rate calculation in progress bar | lib/document/Bar.js | lib/document/Bar.js | /*
Terminal Kit
Copyright (c) 2009 - 2021 Cédric Ronvel
The MIT License (MIT)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
"use strict" ;
const Element = require( './Element.js' ) ;
const builtinBarChars = require( '../spChars.js' ).bar ;
function Bar( options ) {
// Clone options if necessary
options = ! options ? {} : options.internal ? options : Object.create( options ) ;
options.internal = true ;
Element.call( this , options ) ;
this.minValue = + options.minValue || 0 ;
this.maxValue = options.maxValue !== undefined ? + options.maxValue || 0 : 1 ;
this.value = + options.value || 0 ;
if ( this.value < this.minValue ) { this.value = this.minValue ; }
else if ( this.value > this.maxValue ) { this.value = this.maxValue ; }
this.borderAttr = options.borderAttr || { bold: true } ;
this.bodyAttr = options.bodyAttr || { color: 'blue' } ;
this.barChars = builtinBarChars.classic ;
if ( typeof options.barChars === 'object' ) {
this.barChars = options.barChars ;
}
else if ( typeof options.barChars === 'string' && builtinBarChars[ options.barChars ] ) {
this.barChars = builtinBarChars[ options.barChars ] ;
}
this.overTextFullAttr = options.overTextFullAttr || { bgColor: 'blue' } ;
this.overTextEmptyAttr = options.overTextEmptyAttr || { bgColor: 'default' } ;
// Only draw if we are not a superclass of the object
if ( this.elementType === 'Bar' && ! options.noDraw ) { this.draw() ; }
}
module.exports = Bar ;
Bar.prototype = Object.create( Element.prototype ) ;
Bar.prototype.constructor = Bar ;
Bar.prototype.elementType = 'Bar' ;
Bar.prototype.preDrawSelf = function() {
var index , x , fullCells , emptyCells , partialCellRate ,
fullContent , fullContentWidth = 0 , emptyContent , emptyContentWidth = 0 ,
noPartialCell = false ,
partialCell = null ,
innerSize = this.outputWidth - 2 ,
rate = this.value - this.minValue / ( this.maxValue - this.minValue ) ;
if ( ! rate || rate < 0 ) { rate = 0 ; }
else if ( rate > 1 ) { rate = 1 ; }
fullCells = Math.floor( rate * innerSize ) ;
partialCellRate = rate * innerSize - fullCells ;
if ( this.content ) {
if ( partialCellRate < 0.5 ) {
fullContent = Element.truncateContent( this.content , fullCells , this.contentHasMarkup ) ;
fullContentWidth = Element.getLastTruncateWidth() ;
if ( fullContentWidth < this.contentWidth ) { noPartialCell = true ; }
}
else {
fullContent = Element.truncateContent( this.content , fullCells + 1 , this.contentHasMarkup ) ;
fullContentWidth = Element.getLastTruncateWidth() ;
if ( fullContentWidth < this.contentWidth || fullContentWidth === fullCells + 1 ) {
noPartialCell = true ;
fullCells ++ ;
}
}
}
if ( ! noPartialCell && fullCells < innerSize ) {
if ( this.barChars.body.length <= 2 ) {
// There is no chars for partial cells
if ( partialCellRate >= 0.5 ) { fullCells ++ ; }
}
else if ( this.barChars.body.length === 3 ) {
partialCell = this.barChars.body[ 1 ] ;
}
else if ( this.barChars.body.length === 4 ) {
partialCell = this.barChars.body[ partialCellRate < 0.5 ? 1 : 2 ] ;
}
else {
index = Math.floor( 1.5 + partialCellRate * ( this.barChars.body.length - 3 ) ) ;
partialCell = this.barChars.body[ index ] ;
}
}
emptyCells = innerSize - fullCells - ( partialCell ? 1 : 0 ) ;
if ( this.content && fullContentWidth < this.contentWidth ) {
emptyContent = Element.truncateContent( this.content.slice( fullContent.length ) , emptyCells , this.contentHasMarkup ) ;
emptyContentWidth = Element.getLastTruncateWidth() ;
}
// Rendering...
x = this.outputX ;
this.outputDst.put( {
x: x ++ , y: this.outputY , attr: this.borderAttr , markup: true
} , this.barChars.border[ 0 ] ) ;
if ( fullContentWidth ) {
this.outputDst.put( {
x: x , y: this.outputY , attr: this.overTextFullAttr , markup: true
} , fullContent ) ;
x += fullContentWidth ;
}
if ( fullCells - fullContentWidth > 0 ) {
this.outputDst.put( {
x: x , y: this.outputY , attr: this.bodyAttr , markup: true
} , this.barChars.body[ 0 ].repeat( fullCells - fullContentWidth ) ) ;
x += fullCells - fullContentWidth ;
}
if ( partialCell ) {
this.outputDst.put( {
x: x ++ , y: this.outputY , attr: this.bodyAttr , markup: true
} , partialCell ) ;
}
if ( emptyContentWidth ) {
this.outputDst.put( {
x: x , y: this.outputY , attr: this.overTextEmptyAttr , markup: true
} , emptyContent ) ;
x += emptyContentWidth ;
}
if ( emptyCells - emptyContentWidth > 0 ) {
this.outputDst.put( {
x: x , y: this.outputY , attr: this.bodyAttr , markup: true
} , this.barChars.body[ this.barChars.body.length - 1 ].repeat( emptyCells - emptyContentWidth ) ) ;
x += emptyCells - emptyContentWidth ;
}
this.outputDst.put( {
x: x , y: this.outputY , attr: this.borderAttr , markup: true
} , this.barChars.border[ 1 ] ) ;
} ;
Bar.prototype.getValue = function() { return this.value ; } ;
Bar.prototype.setValue = function( value , internalAndNoDraw ) {
this.value = + value || 0 ;
if ( this.value < this.minValue ) { this.value = this.minValue ; }
else if ( this.value > this.maxValue ) { this.value = this.maxValue ; }
if ( ! internalAndNoDraw ) { this.draw() ; }
} ;
| JavaScript | 0.000001 | @@ -2852,24 +2852,25 @@
,%0A%09%09rate =
+(
this.value -
@@ -2883,16 +2883,17 @@
minValue
+)
/ ( thi
|
99d1026dd54243992afad42b0112df5ae3f0e132 | use symbol instead of string | lib/extend/logic.js | lib/extend/logic.js | const Validator = require('think-validator');
const helper = require('think-helper');
let validatorsRuleAdd = false;
module.exports = {
/**
* combine scope and rules
*/
getCombineRules(scope, rules) {
if (helper.isObject(scope)) {
rules = helper.extend({}, scope, rules);
}
return rules;
},
/**
* validate rules
*/
validate(rules, msgs) {
if (helper.isEmpty(rules)) return;
this['INVOKED'] = true;
// add user defined rules
if (!validatorsRuleAdd) {
validatorsRuleAdd = true;
const rules = think.app.validators.rules || {};
for (const key in rules) {
Validator.addRule(key, rules[key]);
}
}
const instance = new Validator(this.ctx);
msgs = Object.assign({}, think.app.validators.messages, msgs);
rules = this.getCombineRules(this.scope, rules);
const ret = instance.validate(rules, msgs);
if (!helper.isEmpty(ret)) {
this.validateErrors = ret;
return false;
}
return true;
},
/**
* after magic method
*/
__after() {
// This will be removed in the future (>think-logic@1.2.0)
// check request method is allowed
let allowMethods = this.allowMethods;
if (!helper.isEmpty(allowMethods)) {
if (helper.isString(allowMethods)) {
allowMethods = allowMethods.split(',').map(e => {
return e.toUpperCase();
});
}
const method = this.method;
if (allowMethods.indexOf(method) === -1) {
this.fail(this.config('validateDefaultErrno'), 'METHOD_NOT_ALLOWED');
return false;
}
}
// check rules
if (!this['INVOKED']) {
this.rules = this.getCombineRules(this.scope, this.rules);
if (!helper.isEmpty(this.rules)) {
const flag = this.validate(this.rules);
if (!flag) {
this.fail(this.config('validateDefaultErrno'), this.validateErrors);
return false;
}
}
}
}
};
| JavaScript | 0.001418 | @@ -78,16 +78,52 @@
elper');
+%0A%0Aconst INVOKED = Symbol('invoked');
%0Alet val
@@ -457,25 +457,23 @@
this%5B
-'
INVOKED
-'
%5D = true
@@ -1667,17 +1667,15 @@
his%5B
-'
INVOKED
-'
%5D) %7B
|
6c14c6074cffcf67a27a975e45ad0ab2d8c6686e | fix #30 | lib/find_process.js | lib/find_process.js | /*
* @Author: zoujie.wzj
* @Date: 2016-01-23 18:25:37
* @Last Modified by: Ayon Lee
* @Last Modified on: 2018-10-19
*/
'use strict'
const path = require('path')
const utils = require('./utils')
function matchName (text, name) {
if (!name) {
return true
}
return text.match(name)
}
function fetchBin (cmd) {
const pieces = cmd.split(path.sep)
const last = pieces[pieces.length - 1]
if (last) {
pieces[pieces.length - 1] = last.split(' ')[0]
}
const fixed = []
for (const part of pieces) {
const optIdx = part.indexOf(' -')
if (optIdx >= 0) {
// case: /aaa/bbb/ccc -c
fixed.push(part.substring(0, optIdx).trim())
break
} else if (part.endsWith(' ')) {
// case: node /aaa/bbb/ccc.js
fixed.push(part.trim())
break
}
fixed.push(part)
}
return fixed.join(path.sep)
}
function fetchName (fullpath) {
if (process.platform === 'darwin') {
const idx = fullpath.indexOf('.app/')
if (idx >= 0) {
return path.basename(fullpath.substring(0, idx))
}
}
return path.basename(fullpath)
}
const finders = {
darwin (cond) {
return new Promise((resolve, reject) => {
let cmd
if ('pid' in cond) {
cmd = `ps -p ${cond.pid} -ww -o pid,ppid,uid,gid,args`
} else {
cmd = `ps ax -ww -o pid,ppid,uid,gid,args`
}
utils.exec(cmd, function (err, stdout, stderr) {
if (err) {
if ('pid' in cond) {
// when pid not exists, call `ps -p ...` will cause error, we have to
// ignore the error and resolve with empty array
resolve([])
} else {
reject(err)
}
} else {
err = stderr.toString().trim()
if (err) {
reject(err)
return
}
let data = utils.stripLine(stdout.toString(), 1)
let columns = utils.extractColumns(data, [0, 1, 2, 3, 4], 5).filter(column => {
if (column[0] && cond.pid) {
return column[0] === String(cond.pid)
} else if (column[4] && cond.name) {
return matchName(column[4], cond.name)
} else {
return !!column[0]
}
})
let list = columns.map(column => {
const cmd = String(column[4])
const bin = fetchBin(cmd)
return {
pid: parseInt(column[0], 10),
ppid: parseInt(column[1], 10),
uid: parseInt(column[2], 10),
gid: parseInt(column[3], 10),
name: fetchName(bin),
bin: bin,
cmd: column[4]
}
})
if (cond.strict && cond.name) {
list = list.filter(item => item.name === cond.name)
}
resolve(list)
}
})
})
},
linux: 'darwin',
sunos: 'darwin',
freebsd: 'darwin',
win32 (cond) {
return new Promise((resolve, reject) => {
const cmd = 'WMIC path win32_process get Name,Processid,ParentProcessId,Commandline,ExecutablePath'
const lines = []
const proc = utils.spawn('cmd', ['/c', cmd], { detached: false, windowsHide: true })
proc.stdout.on('data', data => {
lines.push(data.toString())
})
proc.on('close', code => {
if (code !== 0) {
return reject(new Error('Command \'' + cmd + '\' terminated with code: ' + code))
}
let list = utils.parseTable(lines.join('\n'))
.filter(row => {
if ('pid' in cond) {
return row.ProcessId === String(cond.pid)
} else if (cond.name) {
if (cond.strict) {
return row.Name === cond.name || (row.Name.endsWith('.exe') && row.Name.slice(0, -4) === cond.name)
} else {
// fix #9
return matchName(row.CommandLine || row.Name, cond.name)
}
} else {
return true
}
})
.map(row => ({
pid: parseInt(row.ProcessId, 10),
ppid: parseInt(row.ParentProcessId, 10),
// uid: void 0,
// gid: void 0,
bin: row.ExecutablePath,
name: row.Name,
cmd: row.CommandLine
}))
resolve(list)
})
})
},
android (cond) {
return new Promise((resolve, reject) => {
let cmd = 'ps'
utils.exec(cmd, function (err, stdout, stderr) {
if (err) {
if ('pid' in cond) {
// when pid not exists, call `ps -p ...` will cause error, we have to
// ignore the error and resolve with empty array
resolve([])
} else {
reject(err)
}
} else {
err = stderr.toString().trim()
if (err) {
reject(err)
return
}
let data = utils.stripLine(stdout.toString(), 1)
let columns = utils.extractColumns(data, [0, 3], 4).filter(column => {
if (column[0] && cond.pid) {
return column[0] === String(cond.pid)
} else if (column[1] && cond.name) {
return matchName(column[1], cond.name)
} else {
return !!column[0]
}
})
let list = columns.map(column => {
const cmd = String(column[1])
const bin = fetchBin(cmd)
return {
pid: parseInt(column[0], 10),
// ppid: void 0,
// uid: void 0,
// gid: void 0,
name: fetchName(bin),
bin,
cmd
}
})
if (cond.strict && cond.name) {
list = list.filter(item => item.name === cond.name)
}
resolve(list)
}
})
})
}
}
function findProcess (cond) {
let platform = process.platform
return new Promise((resolve, reject) => {
if (!(platform in finders)) {
return reject(new Error(`platform ${platform} is unsupported`))
}
let find = finders[platform]
if (typeof find === 'string') {
find = finders[find]
}
find(cond).then(resolve, reject)
})
}
module.exports = findProcess
| JavaScript | 0.998812 | @@ -261,17 +261,90 @@
rue%0A %7D%0A
-%0A
+ // make sure text.match is valid, fix #30%0A if (text && text.match) %7B%0A
return
@@ -361,16 +361,35 @@
h(name)%0A
+ %7D%0A return false%0A
%7D%0A%0Afunct
|
998763d87d1b28c7bf9994d041c1f4086635d1b8 | Add activity.js | lib/models/index.js | lib/models/index.js | 'use strict';
module.exports = {
Page: require('./page'),
User: require('./user'),
Revision: require('./revision'),
Bookmark: require('./bookmark'),
Comment: require('./comment'),
Attachment: require('./attachment'),
UpdatePost: require('./updatePost'),
Notification: require('./notification'),
};
| JavaScript | 0.000002 | @@ -305,11 +305,46 @@
tion'),%0A
+ Activity: require('./activity'),%0A
%7D;%0A
|
ba1072340cdbcf205502e58f293756a948dc0aab | prepare last last beta - beta.11 | SpotifyAPI.Docs/src/install_instructions.js | SpotifyAPI.Docs/src/install_instructions.js | import CodeBlock from '@theme/CodeBlock';
import TabItem from '@theme/TabItem';
import Tabs from '@theme/Tabs';
import React from 'react';
// Will be removed after beta releases
const VERSION = '6.0.0-beta.10';
const installCodeNuget = `Install-Package SpotifyAPI.Web -Version ${VERSION}
# Optional Auth module, which includes an embedded HTTP Server for OAuth2
Install-Package SpotifyAPI.Web.Auth -Version ${VERSION}
`;
const installReference = `<PackageReference Include="SpotifyAPI.Web" Version="${VERSION}" />
<!-- Optional Auth module, which includes an embedded HTTP Server for OAuth2 -->
<PackageReference Include="SpotifyAPI.Web.Auth" Version="${VERSION}" />
`;
const installCodeCLI = `dotnet add package SpotifyAPI.Web --version ${VERSION}
# Optional Auth module, which includes an embedded HTTP Server for OAuth2
dotnet add package SpotifyAPI.Web.Auth --version ${VERSION}
`;
const InstallInstructions = () => {
return (
<div style={{ padding: '30px' }}>
<Tabs
defaultValue="cli"
values={[
{ label: '.NET CLI', value: 'cli' },
{ label: 'Package Manager', value: 'nuget' },
{ label: 'Package Reference', value: 'reference' },
]}
>
<TabItem value="cli">
<CodeBlock metastring="shell" className="shell">
{installCodeCLI}
</CodeBlock>
</TabItem>
<TabItem value="nuget">
<CodeBlock metastring="shell" className="shell">
{installCodeNuget}
</CodeBlock>
</TabItem>
<TabItem value="reference">
<CodeBlock metastring="xml" className="xml">
{installReference}
</CodeBlock>
</TabItem>
</Tabs>
</div>
);
};
export default InstallInstructions;
| JavaScript | 0 | @@ -201,17 +201,17 @@
0-beta.1
-0
+1
';%0A%0Acons
|
5ac1077cfe25c2958ee67ab563d99352d0df816c | prepare beta.5 | SpotifyAPI.Docs/src/install_instructions.js | SpotifyAPI.Docs/src/install_instructions.js | import React from "react";
import CodeBlock from '@theme/CodeBlock'
import Tabs from '@theme/Tabs'
import TabItem from '@theme/TabItem'
const installCodeNuget =
`Install-Package SpotifyAPI.Web -Version 6.0.0-beta.4
# Optional Auth module, which includes an embedded HTTP Server for OAuth2
Install-Package SpotifyAPI.Web.Auth -Version 6.0.0-beta.4
`;
const installReference =
`<PackageReference Include="SpotifyAPI.Web" Version="6.0.0-beta.4" />
<!-- Optional Auth module, which includes an embedded HTTP Server for OAuth2 -->
<PackageReference Include="SpotifyAPI.Web.Auth" Version="6.0.0-beta.4" />
`;
const installCodeCLI =
`dotnet add package SpotifyAPI.Web --version 6.0.0-beta.4
# Optional Auth module, which includes an embedded HTTP Server for OAuth2
dotnet add package SpotifyAPI.Web.Auth --version 6.0.0-beta.4
`;
const InstallInstructions = () => {
return (<div style={{ padding: '30px' }}>
<Tabs
defaultValue="cli"
values={[
{ label: '.NET CLI', value: 'cli' },
{ label: 'Package Manager', value: 'nuget' },
{ label: 'Package Reference', value: 'reference' }
]}>
<TabItem value="cli">
<CodeBlock metastring="shell" className="shell">
{installCodeCLI}
</CodeBlock>
</TabItem>
<TabItem value="nuget">
<CodeBlock metastring="shell" className="shell">
{installCodeNuget}
</CodeBlock>
</TabItem>
<TabItem value="reference">
<CodeBlock metastring="xml" className="xml">
{installReference}
</CodeBlock>
</TabItem>
</Tabs>
</div>);
}
export default InstallInstructions;
| JavaScript | 0 | @@ -130,16 +130,88 @@
bItem'%0A%0A
+// Will be removed after beta releases%0Aconst VERSION = '6.0.0-beta.5';%0A%0A
const in
@@ -266,36 +266,34 @@
eb -Version
-6.0.0-beta.4
+$%7BVERSION%7D
%0A# Optional
@@ -396,36 +396,34 @@
th -Version
-6.0.0-beta.4
+$%7BVERSION%7D
%0A%60;%0A%0Aconst i
@@ -491,36 +491,34 @@
b%22 Version=%22
-6.0.0-beta.4
+$%7BVERSION%7D
%22 /%3E%0A%3C!-- Op
@@ -648,28 +648,26 @@
ersion=%22
-6.0.0-beta.4
+$%7BVERSION%7D
%22 /%3E%0A%60;%0A
@@ -737,28 +737,26 @@
version
-6.0.0-beta.4
+$%7BVERSION%7D
%0A# Optio
@@ -875,20 +875,18 @@
ion
-6.0.0-beta.4
+$%7BVERSION%7D
%0A%60;%0A
|
8db8513921a3c466639f15def689036dcf8c9ef8 | Add a timeout param to FeedsService.wait_for | src/app/components/feed/feeds.service.js | src/app/components/feed/feeds.service.js | /*
* Copyright (C) 2015 SUSE Linux
*
* This software may be modified and distributed under the terms
* of the MIT license. See the LICENSE.txt file for details.
*/
(function () {
'use strict';
angular.module('janusHangouts')
.service('FeedsService', FeedsService);
FeedsService.$inject = ['$q'];
function FeedsService($q) {
this.mainFeed = null;
this.feeds = {};
this.find = find;
this.findMain = findMain;
this.add = add;
this.destroy = destroy;
this.allFeeds = allFeeds;
this.publisherFeeds = publisherFeeds;
this.localScreenFeeds = localScreenFeeds;
this.speakingFeed = speakingFeed;
this.waitFor = waitFor;
function find(id) {
return (this.feeds[id] || null);
}
function findMain() {
return this.mainFeed;
}
/**
* Find a feed but, if not found, waits until it appears
*
* @param {string} id Feed's id
* @param {number} attempts Max number of attempts
* @return {Object} Promise to be resolved when the feed is found.
*/
function waitFor(id, attempts) {
var deferred = $q.defer();
var feed = this.find(id);
var that = this;
attempts = attempts || 3;
if (feed === null) { // If feed is not found, set an interval to check again.
var interval = setInterval(function () {
feed = that.find(id);
if (feed === null) { // The feed was not found this time
attempts -= 1;
} else { // The feed was finally found
clearInterval(interval);
deferred.resolve(feed);
}
if (attempts === 0) { // No more attempts left and feed was not found
clearInterval(interval);
deferred.reject("feed with id " + id + " was not found");
}
}, 2000);
} else {
deferred.resolve(feed);
}
return deferred.promise;
}
function add(feed, options) {
this.feeds[feed.id] = feed;
if (options && options.main) {
this.mainFeed = feed;
}
}
function destroy(id) {
delete this.feeds[id];
if (this.mainFeed && (id === this.mainFeed.id)) {
this.mainFeed = null;
}
}
function allFeeds() {
return _.values(this.feeds);
}
function publisherFeeds() {
return _.filter(this.allFeeds(), function (f) {
return f.isPublisher;
});
}
function localScreenFeeds() {
return _.filter(this.allFeeds(), function (f) {
return f.isLocalScreen;
});
}
function speakingFeed() {
return _.detect(this.allFeeds(), function (f) {
return f.getSpeaking();
});
}
}
}());
| JavaScript | 0.000007 | @@ -976,16 +976,87 @@
ttempts%0A
+ * @param %7Bnumber%7D timeout Time (in miliseconds) between attempts%0A
* @
@@ -1167,16 +1167,25 @@
attempts
+, timeout
) %7B%0A
@@ -1301,9 +1301,43 @@
%7C%7C
-3
+10;%0A timeout = timeout %7C%7C 1000
;%0A%0A
@@ -1942,12 +1942,15 @@
%7D,
-2000
+timeout
);%0A
|
6e5f6930355837de5947774b28f663f0d7e2a969 | Update license links to thirdparty libraries | ZRHome/App/viewmodels/license.js | ZRHome/App/viewmodels/license.js | define(['services/logger'], function (logger) {
var license = {
title: 'License',
description: 'Photos, source code and articles published on this website, that are not explicitly mentioned otherwise, are licensed under <a target="_blank" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US">Creative Commons Attribution-NonCommercial 3.0 Unported</a> license.',
terms: [
{ term: 'Attribution' },
{ term: 'Non-Commercial' }
],
creativeCommons: '<a rel="license" target="_blank" href="http://creativecommons.org/licenses/by-nc/3.0/deed.en_US"><img alt="Creative Commons License" style="border-width:0" src="./Content/images/cc_attribution_nocommercial_88x31.png" /></a>',
termsOverride: 'If any section of this website mentions it\'s own licensing terms, that will override the terms mentioned here.',
commercial: {
heading: 'Commercial',
description: 'If you want a higher quality photo published on this website for commercial use, please <a href="#contact">contact me</a>.'
},
thirdParty: {
heading: 'Third Party Licenses',
description: 'This website uses the following awesome libraries:',
libraries: [
{ library: 'Durandal JS', license: 'MIT', url: 'https://raw.github.com/BlueSpire/Durandal/master/License.txt' },
{ library: 'Knockout JS', license: 'MIT', url: 'https://github.com/knockout/knockout#license' },
{ library: 'Bootstrap', license: 'Apache', url: 'https://github.com/twbs/bootstrap/blob/master/LICENSE' },
{ library: 'Isotope', license: 'MIT / Commercial', url: 'http://isotope.metafizzy.co/docs/license.html' },
{ library: 'Require JS', license: 'MIT / "New" BSD', url: 'https://github.com/jrburke/requirejs/blob/master/LICENSE' },
{ library: 'Lazy Load Plugin for JQuery', license: 'MIT', url: 'https://github.com/tuupola/jquery_lazyload#license' },
{ library: 'fancyBox', license: 'MIT', url: 'http://www.fancyapps.com/fancybox/#license' }
],
},
activate: activate
};
return license;
function activate() {
}
}); | JavaScript | 0 | @@ -1346,12 +1346,8 @@
s://
-raw.
gith
@@ -1372,16 +1372,21 @@
urandal/
+blob/
master/L
@@ -1496,24 +1496,36 @@
knockout
-#license
+/blob/master/LICENSE
' %7D,%0A
@@ -1741,13 +1741,8 @@
.co/
-docs/
lice
|
0519e5a131f3597d2630ba19fdd817ca043e0a3a | make continue message 60s up from 5s | client/views/messages/message/plain-message.es6.js | client/views/messages/message/plain-message.es6.js | /**
* Creates the timestamp popup
* @param target is a dom element to show the popup on
* @param timestamp is the timestamp to use for the popup
*/
function createTimestampPopup(target, timestamp) {
const m = moment(timestamp);
$(target).popup({
title: m.fromNow(),
content: m.format("dddd, MMMM Do YYYY"),
position: "top right"
}).popup('show');
}
Template.plainMessage.helpers({
hasEdits() {
return this.lastedited;
},
lastEditTime() {
if (!this.lastedited) {
return;
}
return moment(this.lastedited).format("h:mm:ss a");
},
showTimestamp() {
const m = moment(new Date(this.timestamp));
const user = Meteor.users.findOne({_id: Meteor.userId()}, {fields: {"profile.use24HrTime": 1}});
return user && user.profile && user.profile.use24HrTime ? m.format("HH:mm:ss") : m.format("hh:mm:ss a");
},
isUnderEdit() {
return Session.get('editingId') === this._id;
},
canEdit() {
return this.authorId === Meteor.userId();
},
hasMention() {
return this.authorId !== Meteor.userId() && MessageLib.hasUserMentions(this.message) ? "has-mention" : "";
},
finalMessageBody() {
return MessageLib.renderMessage(this.message);
},
starIcon() {
return _(this.likedBy).contains(Meteor.userId()) ? "fa-star" : "fa-star-o";
},
fontSizePercent() {
const parentContext = Template.instance().parentTemplate();
if (parentContext && parentContext.supressStarSizing) {
return 100;
}
if (this.likedBy.length === 0) {
return 100;
}
const room = Rooms.findOne({_id: this.roomId}, {fields: {users: 1}});
if (!room || !room.users || room.users.length < 1) {
return 100;
}
switch (this.likedBy.length || 0) {
case 0:
return 100;
case 1:
return 166;
case 2:
return 232;
default:
return 300;
}
},
continuedMessage() {
const user = Meteor.users.findOne({_id: Meteor.userId()}, {fields: {"profile.continueMessages": 1}});
return user &&
user.profile &&
user.profile.continueMessages &&
Template.instance().continuedMessage.get();
}
});
Template.plainMessage.events({
'click .likeMessageLink'(event, template) {
event.preventDefault();
if (!_(this.likedBy).contains(Meteor.userId())) {
Meteor.call('likeMessage', template.data._id, AlertFeedback);
}
else {
Meteor.call('unlikeMessage', template.data._id, AlertFeedback);
}
},
'dblclick, click .editMessageButton'(event, template) {
if (template.data.authorId === Meteor.userId()) {
Client.editMessage(template.data._id);
}
},
'submit .editForm'(event, template) {
event.preventDefault();
const newMessage = template.find('input[name=newMessageText]').value;
Meteor.call('editMessage', {_id: template.data._id, message: newMessage});
Client.stopEditing();
},
'click .cancelEditSubmit'() {
Client.stopEditing();
},
'mouseenter .message-timestamp'(event, template) {
createTimestampPopup(event.target, template.data.timestamp);
},
'mouseenter .message-user-mention'(event, template) {
const userId = $(event.target).data("userid");
Client.showPopup(event.target, "userProfileCard", userId);
},
'mouseenter .likeMessageLink'(event, template) {
Client.showPopup(event.target, "starredByListPopup", template.data._id);
},
'click .removeMessageButton'(event, template) {
event.preventDefault();
if (confirm("Are you sure you want to delete this message?")) {
Meteor.call('removeMessage', template.data._id);
}
},
'mouseenter .user-popup'(event, template) {
Client.showPopup(event.target, "userProfileCard", template.data.authorId);
},
'keydown .editForm'(event, template) {
if (event.keyCode === 27) {
Client.stopEditing();
event.preventDefault();
}
}
});
function shouldContinue(message, previousMessageId) {
const prevMessage = Messages.findOne({_id: previousMessageId});
return prevMessage && message && prevMessage.authorId === message.authorId &&
(message.timestamp - prevMessage.timestamp) < 5000;
}
Template.plainMessage.onCreated(function () {
this.continuedMessage = new ReactiveVar(false);
});
Template.plainMessage.onRendered(function () {
this.$('.ui.accordion').accordion();
Meteor.defer(() => {
const prevId = this.$('.comment').prev().attr("id");
this.continuedMessage.set(shouldContinue(this.data, prevId));
});
});
| JavaScript | 0.000001 | @@ -4536,9 +4536,10 @@
) %3C
-5
+60
000;
|
9fefa5901df2685c292a0871774aa29598f46322 | Update inviteHandler | test-client/test-server/inviteHandler.js | test-client/test-server/inviteHandler.js | const Wreck = require('wreck');
const config = require('../src/config');
const fs = require('fs');
const path = require('path');
const getAccessToken = require('./getAccessToken');
const wreck = Wreck.defaults({
baseUrl: 'http://localhost:9000',
json: true,
});
const clientId = config.clientId;
const scope = 'openid email app_metadata profile';
module.exports = (request, reply) => {
const options = {};
options.payload = {};
options.payload.email = request.payload.email;
options.payload.client_id = clientId;
options.payload.redirect_uri = 'https://sso-client.dev:3000/';
options.payload.scope = scope;
options.payload.app_name = 'Test Client';
options.headers = {};
if (request.payload.useTemplate) {
options.payload.template = fs.readFileSync(path.join(__dirname, './templates/custom-email.hbs'), 'utf8');
}
getAccessToken().then(tkn => {
options.headers.Authorization = `Bearer ${tkn}`;
console.log('Submitting API request for user invite.');
wreck.post('/api/invite', options, (error, response, payload) => {
if (error) {
console.log('Error while inviting user.');
console.log(error);
reply(error);
} else {
console.log('User invite successful.');
reply(payload);
}
});
}).catch(error => {
reply(error);
});
}
| JavaScript | 0.000001 | @@ -238,17 +238,17 @@
host:900
-0
+1
',%0A jso
@@ -578,11 +578,12 @@
ent.
-dev
+test
:300
@@ -609,21 +609,29 @@
oad.
-sco
+response_ty
pe
-
=
-scope
+'code'
;%0A
@@ -650,32 +650,21 @@
oad.
-app_name = 'Test Client'
+scope = scope
;%0A
|
b9df73685aa86043b620a5d9644186167fca240f | Fix test and test-dashboard | test-dashboard/toolpanel-dashboard/ui.js | test-dashboard/toolpanel-dashboard/ui.js | 'use strict';
var Plotly = window.Plotly;
var ToolPanel = window.ToolPanel;
var divs = [];
function createRemoveButton () {
var removeButton = document.createElement('button');
removeButton.innerHTML = 'remove toolpanel';
removeButton.id = 'removeButton';
document.body.appendChild(removeButton);
removeButton.onclick = function () {
divs[0].toolPanel.remove();
};
}
function createPlot (divId) {
var containerDiv = document.getElementById('main');
var graphDiv = document.createElement('div');
var toolDiv = document.createElement('div');
containerDiv.style.width = '100%';
containerDiv.style.height = '100%';
containerDiv.style.clear = 'both';
graphDiv.id = divId;
graphDiv.style.width = '80%';
graphDiv.style.display = 'inline-block';
graphDiv.style.margin = '0px';
graphDiv.style.position = 'relative';
graphDiv.style.verticalAlign = 'top';
toolDiv.style.verticalAlign = 'top';
toolDiv.style.width = '130px';
toolDiv.style.display = 'inline-block';
containerDiv.appendChild(toolDiv);
containerDiv.appendChild(graphDiv);
var trace1 = {
x: [1, 2, 3, 4],
y: [10, 15, 13, 17],
type: 'scatter'
};
var trace2 = {
x: [1, 2, 3, 4],
y: [16, 5, 11, 9],
type: 'scatter'
};
var data = [trace1, trace2];
Plotly.newPlot(divId, data);
graphDiv.toolPanel = new ToolPanel(Plotly, graphDiv, {
standalone: true,
popoverContainer: containerDiv
});
graphDiv.toolPanel.makeMenu({
toolMenuContainer: toolDiv
});
divs.push(graphDiv, toolDiv);
}
['one'].forEach(function (index) {
createPlot(index);
});
createRemoveButton();
| JavaScript | 0.000001 | @@ -1365,16 +1365,35 @@
trace2%5D;
+%0A var toolPanel;
%0A%0A Pl
@@ -1444,16 +1444,28 @@
lPanel =
+ toolPanel =
new Too
@@ -1561,24 +1561,68 @@
iv%0A %7D);%0A%0A
+ window.toolPanel = graphDiv.toolPanel;%0A%0A
graphDiv
@@ -1674,24 +1674,24 @@
er: toolDiv%0A
-
%7D);%0A%0A
@@ -1683,24 +1683,445 @@
iv%0A %7D);%0A%0A
+ toolPanel.createMenuMultiButton(%5B%0A %7B%0A labelContent: 'Undo',%0A iconClass: 'icon-rotate-left',%0A handler: toolPanel.undo%0A %7D,%0A %7B%0A labelContent: 'Redo',%0A iconClass: 'icon-rotate-right',%0A handler: toolPanel.redo%0A %7D%0A %5D);%0A%0A toolPanel.createMenuSpacer();%0A%0A toolPanel.createMenuButtonGroup(toolPanel.getPanelButtonSpecs());%0A%0A
divs.pus
|
3701008f0c0c5587407f4e0a5a6da2be0aee1faf | Fix modal dimmer | addon/components/modal-dialog.js | addon/components/modal-dialog.js | /**
@module ember-flexberry
*/
import Ember from 'ember';
/**
ModalDialog component for Semantic UI.
@example
```handlebars
{{#modal-dialog
title='Title'
sizeClass='large'
close='removeModalDialog'
created='createdModalDialog'
useOkButton=false
useCloseButton=false
}}
{{outlet 'modal-content'}}
{{/modal-dialog}}
```
@class ModalDialog
@extends <a href="http://emberjs.com/api/classes/Ember.Component.html">Ember.Component</a>
*/
export default Ember.Component.extend({
/**
Size of Semantic UI modal.
Possible variants:
- 'small'
- 'large'
- 'fullscreen'
@property sizeClass
@type String
@default 'small'
*/
sizeClass: 'small',
/**
Flag indicates whether an image content is viewed at modal dialog or not.
@property viewImageContent
@type Boolean
@default false
*/
viewImageContent: false,
/**
Flag indicates whether to show apply button or not.
@property useOkButton
@type Boolean
@default true
*/
useOkButton: true,
/**
Flag indicates whether to show close button or not.
@property useCloseButton
@type Boolean
@default true
*/
useCloseButton: true,
/**
Flag indicates toolbar visibility, `true` if at least one of buttons is visible.
@property toolbarVisible
@type Boolean
@readOnly
*/
toolbarVisible: Ember.computed('useOkButton', 'useCloseButton', function () {
return this.get('useOkButton') || this.get('useCloseButton');
}),
/**
Semantic UI Modal settings, [more info here](http://semantic-ui.com/modules/modal.html#settings).
@property settings
@type Object
@default {}
*/
settings: {},
/**
Service that triggers lookup events.
@property lookupEventsService
@type Service
*/
lookupEventsService: Ember.inject.service('lookup-events'),
/**
Used to identify lookup on the page.
@property componentName
@type String
*/
componentName: undefined,
/**
Initializes DOM-related component's logic.
*/
didInsertElement() {
let _this = this;
let componentName = this.get('componentName');
let modalSettings = Ember.$.extend({
observeChanges: true,
detachable: false,
allowMultiple: true,
onApprove: function () {
// Call to 'lookupDialogOnHiddenTrigger' causes asynchronous animation, so Ember.run is necessary.
Ember.run(() => {
_this.sendAction('ok');
_this.get('lookupEventsService').lookupDialogOnHiddenTrigger(componentName);
});
},
onDeny: function () {
// Call to 'lookupDialogOnHiddenTrigger' causes asynchronous animation, so Ember.run is necessary.
Ember.run(() => {
_this.sendAction('close');
_this.get('lookupEventsService').lookupDialogOnHiddenTrigger(componentName);
});
},
onHidden: function () {
Ember.run(() => {
_this.sendAction('close');
// IE doesn't support "this.remove()", that's why "Ember.$(this).remove()" is used.
Ember.$(this).remove();
_this.get('lookupEventsService').lookupDialogOnHiddenTrigger(componentName);
});
},
onVisible: function () {
// Handler of 'created' action causes asynchronous animation, so Ember.run is necessary.
Ember.run(() => {
_this.sendAction('created', Ember.$(this));
});
}
},
_this.get('settings'));
this.$('.ui.modal').modal(modalSettings).modal('show');
},
});
| JavaScript | 0.000001 | @@ -2303,24 +2303,77 @@
tiple: true,
+%0A context: '.ember-application %3E .ember-view',
%0A%0A on
|
e0c4c1a6a3292b536755f379e8d1b86ef4f97407 | fix ReviewButton | apps/app/src/pages/Build/ReviewButton.js | apps/app/src/pages/Build/ReviewButton.js | import * as React from "react";
import { x } from "@xstyled/styled-components";
import {
Alert,
Button,
Menu,
MenuButton,
MenuItem,
useMenuState,
MenuButtonArrow,
useTooltipState,
TooltipAnchor,
Tooltip,
} from "@argos-ci/app/src/components";
import { gql, useMutation } from "@apollo/client";
import { StatusIcon } from "../../containers/Status";
import { hasWritePermission } from "../../modules/permissions";
export const ReviewButtonBuildFragment = gql`
fragment ReviewButtonBuildFragment on Build {
id
status
type
}
`;
export const ReviewButtonRepositoryFragment = gql`
fragment ReviewButtonRepositoryFragment on Repository {
permissions
private
}
`;
export const ReviewButtonOwnerFragment = gql`
fragment ReviewButtonOwnerFragment on Owner {
consumptionRatio
}
`;
export function ReviewButtonContent({ repository, disabled }) {
const { id, status } = repository.build;
const menu = useMenuState({ placement: "bottom-end", gutter: 4 });
const [setValidationStatus, { loading, error }] = useMutation(gql`
mutation setValidationStatus(
$buildId: ID!
$validationStatus: ValidationStatus!
) {
setValidationStatus(
buildId: $buildId
validationStatus: $validationStatus
) {
id
...ReviewButtonBuildFragment
}
}
${ReviewButtonBuildFragment}
`);
if (!hasWritePermission(repository)) {
return null;
}
return (
<x.div display="flex" flexDirection="column" flex={1}>
<MenuButton
as={Button}
state={menu}
disabled={disabled || loading}
alignSelf="end"
>
Review changes
<MenuButtonArrow state={menu} />
</MenuButton>
<Menu aria-label="Review changes" state={menu}>
<MenuItem
state={menu}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setValidationStatus({
variables: { buildId: id, validationStatus: "accepted" },
});
menu.hide();
}}
disabled={status === "accepted"}
>
<StatusIcon status="accepted" />
Approve changes
</MenuItem>
<MenuItem
state={menu}
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
setValidationStatus({
variables: { buildId: id, validationStatus: "rejected" },
});
menu.hide();
}}
disabled={status === "rejected"}
>
<StatusIcon status="rejected" />
Reject changes
</MenuItem>
</Menu>
{error ? (
<Alert severity="error" mt={2} w="fit-content" alignSelf="end">
Something went wrong. Please try again.
</Alert>
) : null}
</x.div>
);
}
function DisabledReviewButton({ repository }) {
const tooltip = useTooltipState();
return (
<>
<TooltipAnchor state={tooltip}>
<ReviewButtonContent repository={repository} disabled />
</TooltipAnchor>
<Tooltip state={tooltip}>
You have hit 100% of your screenshots usage. Please upgrade to unlock
build reviews.
</Tooltip>
</>
);
}
export function ReviewButton({ repository }) {
if (
!["accepted", "rejected", "diffDetected"].includes(repository.build.status)
) {
return null;
}
if (repository.private && repository.owner.consumptionRatio >= 1) {
return <DisabledReviewButton repository={repository} />;
}
return <ReviewButtonContent repository={repository} />;
}
| JavaScript | 0.000348 | @@ -113,22 +113,8 @@
nu,%0A
- MenuButton,%0A
Me
@@ -203,16 +203,38 @@
ooltip,%0A
+ HeadlessMenuButton,%0A
%7D from %22
@@ -1527,24 +1527,32 @@
%7B1%7D%3E%0A %3C
+Headless
MenuButton%0A
@@ -1730,24 +1730,32 @@
/%3E%0A %3C/
+Headless
MenuButton%3E%0A
|
ad0c23263fdab943f9bd7044d2ea3141ae02c7be | Make sure the binding is still there | src/dce-plugin/index.js | src/dce-plugin/index.js | 'use strict';
module.exports = ({ Plugin, types: t }) => {
const removeReferenceVisitor = {
ReferencedIdentifier(path) {
if (!this.bindingsToReplace[path.node.name]) {
return;
}
const { replacement, markReplaced, scope } = this.bindingsToReplace[path.node.name];
if ((t.isClass(replacement) || t.isFunction(replacement))
&& scope !== path.scope) {
return;
}
t.toExpression(replacement);
path.replaceWith(replacement);
markReplaced();
},
};
return {
visitor: {
// remove side effectless statement
ExpressionStatement(path) {
if (path.get('expression').isPure() && !path.isCompletionRecord()) {
path.remove();
}
},
// Remove bindings with no references.
Scope(path) {
if (path.isProgram()) {
return;
}
const { scope } = path;
const bindingsToReplace = Object.create(null);
for (let name in scope.bindings) {
let binding = scope.bindings[name];
if (!binding.referenced && binding.kind !== 'param' && binding.kind !== 'module') {
if (binding.path.isVariableDeclarator()) {
// Can't remove if in a for in statement `for (var x in wat)`.
if (binding.path.parentPath.parentPath && binding.path.parentPath.parentPath.isForInStatement()) {
continue;
}
if (binding.path.node.init && !scope.isPure(binding.path.node.init)) {
if (binding.path.parentPath.node.declarations.length === 1) {
binding.path.parentPath.replaceWith(binding.path.node.init);
scope.removeBinding(name);
}
continue;
}
} else if (!scope.isPure(binding.path.node)) {
continue;
} else if (binding.path.isFunctionExpression()) {
// `bar(function foo() {})` foo is not referenced but it's used.
continue;
}
scope.removeBinding(name);
binding.path.remove();
} else if (binding.constant) {
if (binding.path.isFunctionDeclaration() ||
(binding.path.isVariableDeclarator() && binding.path.get('init').isFunction())) {
const fun = binding.path.isFunctionDeclaration() ? binding.path : binding.path.get('init');
let allInside = true;
for (let ref of binding.referencePaths) {
if (!ref.find(p => p.node === fun.node)) {
allInside = false;
break;
}
}
if (allInside) {
scope.removeBinding(name);
binding.path.remove();
continue;
}
}
if (binding.references === 1 && binding.kind !== 'param' && binding.kind !== 'module' && binding.constant) {
let replacement = binding.path.node;
if (t.isVariableDeclarator(replacement)) {
replacement = replacement.init;
}
if (!replacement) {
continue;
}
if (!scope.isPure(replacement, true)) {
continue;
}
bindingsToReplace[name] = {
scope,
replacement,
markReplaced() {
scope.removeBinding(name);
binding.path.remove();
},
};
}
}
}
if (Object.keys(bindingsToReplace).length) {
path.traverse(removeReferenceVisitor, {bindingsToReplace});
}
},
// Remove unreachable code.
BlockStatement(path) {
const paths = path.get('body');
let purge = false;
for (let i = 0; i < paths.length; i++) {
const p = paths[i];
if (!purge && p.isCompletionStatement()) {
purge = true;
continue;
}
if (purge && !p.isFunctionDeclaration()) {
p.remove();
}
}
},
// Remove return statements that have no semantic meaning
ReturnStatement(path) {
const { node } = path;
if (node.argument || !path.inList) {
return;
}
// Not last in it's block? (See BlockStatement visitor)
if (path.container.length - 1 !== path.key) {
throw new Error('Unexpected dead code');
}
let noNext = true;
let parentPath = path.parentPath;
while (parentPath && !parentPath.isFunction() && noNext) {
const nextPath = parentPath.getSibling(parentPath.key + 1);
if (nextPath.node) {
if (nextPath.isReturnStatement()) {
nextPath.pushContext(path.context);
nextPath.visit();
nextPath.popContext();
if (parentPath.getSibling(parentPath.key + 1).node) {
noNext = false;
break;
}
} else {
noNext = false;
break;
}
}
parentPath = parentPath.parentPath;
}
if (noNext) {
path.remove();
}
},
},
};
};
| JavaScript | 0 | @@ -1052,16 +1052,17 @@
%5Bname%5D;%0A
+%0A
@@ -3486,32 +3486,55 @@
+ if (binding.path.node)
binding.path.re
|
168a7a58a8f9959f13d8ea07108e2827232eac89 | fix conflict | packages/bitcore-client/lib/wallet.js | packages/bitcore-client/lib/wallet.js | const fs = require('fs');
const Bcrypt = require('bcrypt');
const Encrypter = require('./encryption');
const Mnemonic = require('bitcore-mnemonic');
const bitcoreLib = require('bitcore-lib');
const Client = require('./client');
const Storage = require('./storage');
const txProvider = require('../lib/providers/tx-provider');
const util = require('util');
const accessAsync = util.promisify(fs.access);
class Wallet {
constructor(params) {
Object.assign(this, params);
if (!this.masterKey) {
return new Wallet(this.create(params));
}
this.baseUrl = this.baseUrl || `http://127.0.0.1:3000/api/${this.chain}/${this.network}`;
}
saveWallet() {
this.lock();
return this.storage.saveWallet({ wallet: this });
}
static async create(params) {
const { chain, network, name, phrase, password, path } = params;
if (!chain || !network || !name || !path) {
throw new Error('Missing required parameter');
}
const mnemonic = new Mnemonic(phrase);
const privateKey = mnemonic.toHDPrivateKey(password);
const pubKey = privateKey.hdPublicKey.publicKey.toString();
const walletEncryptionKey = Encrypter.generateEncryptionKey();
const keyObj = Object.assign(privateKey.toObject(), privateKey.hdPublicKey.toObject());
const encryptionKey = Encrypter.encryptEncryptionKey(walletEncryptionKey, password);
const encPrivateKey = Encrypter.encryptPrivateKey(JSON.stringify(keyObj), pubKey, walletEncryptionKey);
const storage = new Storage({
path,
errorIfExists: true,
createIfMissing: true
});
const wallet = Object.assign(params, {
encryptionKey,
masterKey: encPrivateKey,
password: await Bcrypt.hash(password, 10),
xPubKey: keyObj.xpubkey,
pubKey
});
await storage.saveWallet({ wallet });
const loadedWallet = await this.loadWallet({ path, storage });
await loadedWallet.unlock(password);
await loadedWallet.register();
return loadedWallet;
}
static async loadWallet(params) {
const { path } = params;
try {
await accessAsync(path, fs.constants.F_OK | fs.constants.R_OK);
await accessAsync(path + '/LOCK' || path + 'LOCK', fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK);
await accessAsync(path + '/LOG' || path + 'LOG', fs.constants.F_OK | fs.constants.R_OK | fs.constants.W_OK);
} catch (err) {
return console.error('Invalid wallet path');
}
const storage = params.storage || new Storage({ path, errorIfExists: false, createIfMissing: false });
const loadedWallet = await storage.loadWallet();
return new Wallet(Object.assign(loadedWallet, { storage }));
}
lock() {
this.unlocked = undefined;
}
async unlock(password) {
const encMasterKey = this.masterKey;
let validPass = await Bcrypt.compare(password, this.password).catch(() => false);
if (!validPass) {
throw new Error('Incorrect Password');
}
const encryptionKey = await Encrypter.decryptEncryptionKey(this.encryptionKey, password);
const masterKeyStr = await Encrypter.decryptPrivateKey(encMasterKey, this.pubKey, encryptionKey);
const masterKey = JSON.parse(masterKeyStr);
this.unlocked = {
encryptionKey,
masterKey
};
this.client = new Client({
baseUrl: this.baseUrl,
authKey: this.getAuthSigningKey()
});
return this;
}
async register(params = {}) {
const { baseUrl } = params;
if (baseUrl) {
this.baseUrl = baseUrl;
await this.saveWallet();
}
const payload = {
name: this.name,
pubKey: this.unlocked.masterKey.xpubkey,
path: this.derivationPath,
network: this.network,
chain: this.chain
};
return this.client.register({ payload });
}
getAuthSigningKey() {
return new bitcoreLib.HDPrivateKey(this.unlocked.masterKey.xprivkey).deriveChild('m/2').privateKey;
}
getBalance() {
const { masterKey } = this.unlocked;
return this.client.getBalance({ pubKey: masterKey.xpubkey });
}
getUtxos() {
const { masterKey } = this.unlocked;
return this.client.getCoins({
pubKey: masterKey.xpubkey,
includeSpent: false
});
}
async newTx(params) {
const utxos = params.utxos || (await this.getUtxos(params));
const payload = {
network: this.network,
chain: this.chain,
addresses: params.addresses,
amount: params.amount,
change: params.change,
fee: params.fee,
utxos
};
return txProvider.create(payload);
}
async broadcast(params) {
const payload = {
network: this.network,
chain: this.chain,
rawTx: params.tx
};
return this.client.broadcast({ payload });
}
async importKeys(params) {
const { keys } = params;
const { encryptionKey } = this.unlocked;
for (const key of keys) {
let keyToSave = { key, encryptionKey };
await this.storage.addKey(keyToSave);
}
const addedAddresses = keys.map(key => {
return { address: key.address };
});
if (this.unlocked) {
return this.client.importAddresses({
pubKey: this.xPubKey,
payload: addedAddresses
});
}
}
async signTx(params) {
let { tx } = params;
const utxos = params.utxos || (await this.getUtxos(params));
const payload = {
chain: this.chain,
network: this.network,
tx,
utxos
};
const { encryptionKey } = this.unlocked;
let inputAddresses = txProvider.getSigningAddresses(payload);
let keyPromises = inputAddresses.map(address => {
return this.storage.getKey({
address,
encryptionKey
});
});
let keys = await Promise.all(keyPromises);
return txProvider.sign({ ...payload, keys });
}
}
module.exports = Wallet;
| JavaScript | 0.031708 | @@ -395,16 +395,50 @@
access);
+%0Aconst config = ('../lib/config');
%0A%0Aclass
@@ -1847,24 +1847,52 @@
wallet %7D);%0A
+ config.addWallet(path);%0A
const lo
@@ -2459,24 +2459,19 @@
-return console.e
+throw new E
rror
|
d8dc324dadd0164dc9cb6b318248db1ec109461e | add missing prop type | packages/core/entity-list/src/main.js | packages/core/entity-list/src/main.js | import _isEmpty from 'lodash/isEmpty'
import _isEqual from 'lodash/isEqual'
import _pickBy from 'lodash/pickBy'
import PropTypes from 'prop-types'
import {
appFactory,
notification,
errorLogging,
actionEmitter,
externalEvents,
actions,
formData
} from 'tocco-app-extensions'
import SimpleFormApp from 'tocco-simple-form/src/main'
import {scrollBehaviourPropType} from 'tocco-ui'
import {react, reducer as reducerUtil, navigationStrategy} from 'tocco-util'
import EntityList from './components/EntityList'
import customActions from './customActions'
import {getDispatchActions, getReloadOption, reloadOptions} from './input'
import {reloadData, reloadAll} from './modules/entityList/actions'
import {refresh} from './modules/list/actions'
import reducers, {sagas} from './modules/reducers'
import {searchFormTypePropTypes} from './util/searchFormTypes'
import {selectionStylePropType} from './util/selectionStyles'
const packageName = 'entity-list'
const EXTERNAL_EVENTS = [
'onRowClick',
'emitAction',
'onSelectChange',
'onStoreCreate',
'onSearchChange',
'onSearchFormCollapsedChange'
]
const initApp = (id, input, events = {}, publicPath) => {
const content = <EntityList />
let store = input.store
const allCustomActions = {
...customActions(input),
...(input.customActions || {})
}
const context = {
viewName: 'list',
formName: input.formName,
...(input.contextParams || {})
}
if (!store) {
store = appFactory.createStore(reducers, sagas, input, packageName)
externalEvents.addToStore(store, events)
actionEmitter.addToStore(store, events.emitAction)
errorLogging.addToStore(store, false)
notification.addToStore(store, false)
actions.addToStore(store, {
formApp: SimpleFormApp,
listApp: EntityListApp,
customActions: allCustomActions,
appComponent: input.actionAppComponent,
navigationStrategy: input.navigationStrategy,
context
})
formData.addToStore(store, {listApp: EntityListApp, navigationStrategy: input.navigationStrategy})
store.dispatch(externalEvents.fireExternalEvent('onStoreCreate', store))
} else {
store.dispatch(refresh())
}
const app = appFactory.createApp(packageName, content, store, {
input,
events,
actions: getDispatchActions(input),
publicPath,
textResourceModules: ['component', 'common']
})
if (module.hot) {
module.hot.accept('./modules/reducers', () => {
const hotReducers = require('./modules/reducers').default
reducerUtil.hotReloadReducers(app.store, hotReducers)
})
}
return app
}
;(() => {
if (__DEV__ && __PACKAGE_NAME__ === 'entity-list') {
const input = require('./dev/input.json')
if (!__NO_MOCK__) {
const fetchMock = require('fetch-mock').default
fetchMock.config.overwriteRoutes = false
const setupFetchMocks = require('./dev/fetchMocks').default
setupFetchMocks(packageName, fetchMock)
fetchMock.spy()
}
const app = initApp('id', input)
appFactory.renderApp(app.component)
} else {
appFactory.registerAppInRegistry(packageName, initApp)
}
})()
const EntityListApp = props => {
const {component, setApp, store} = appFactory.useApp({
initApp,
props,
packageName: props.id,
externalEvents: EXTERNAL_EVENTS
})
const prevProps = react.usePrevious(props)
react.useDidUpdate(() => {
const changedProps = _pickBy(props, (value, key) => !_isEqual(value, prevProps[key]))
if (changedProps.store && typeof prevProps.store !== 'undefined') {
/**
* Whenever the store gets explicitly changed from outside
* the entity-list needs to be re-initialized in order to show correct information.
* - e.g. docs-browser: start a search, navigate to folder and then go back to search
* However this should not happen, whenever the entity-list has not been initialized before.
* - e.g. admin: loading preferences (e.g. searchFormCollapsed) and set prop to entity-list
* while being in initialization phase
* Therefore only re-init when store has been set already.
*/
setApp(initApp(props.id, props, appFactory.getEvents(EXTERNAL_EVENTS, props)))
} else if (!_isEmpty(changedProps)) {
getDispatchActions(changedProps).forEach(action => {
store.dispatch(action)
})
const reloadOption = getReloadOption(changedProps)
if (reloadOption === reloadOptions.ALL) {
store.dispatch(reloadAll())
} else if (reloadOption === reloadOptions.DATA) {
store.dispatch(reloadData())
}
}
}, [props])
return component
}
EntityListApp.propTypes = {
id: PropTypes.string.isRequired,
entityName: PropTypes.string.isRequired,
formName: PropTypes.string.isRequired,
searchListFormName: PropTypes.string,
store: PropTypes.object,
limit: PropTypes.number,
searchFormType: searchFormTypePropTypes,
searchFormPosition: PropTypes.oneOf(['top', 'left']),
searchFilters: PropTypes.arrayOf(PropTypes.string),
constriction: PropTypes.string,
preselectedSearchFields: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
PropTypes.arrayOf(PropTypes.number),
PropTypes.arrayOf(PropTypes.string)
]),
hidden: PropTypes.bool
})
),
tql: PropTypes.string,
keys: PropTypes.arrayOf(PropTypes.string),
simpleSearchFields: PropTypes.string,
onSelectChange: PropTypes.func,
selectionStyle: selectionStylePropType,
scrollBehaviour: scrollBehaviourPropType,
tableMinHeight: PropTypes.string,
selection: PropTypes.arrayOf(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
...EXTERNAL_EVENTS.reduce((propTypes, event) => {
propTypes[event] = PropTypes.func
return propTypes
}, {}),
selectOnRowClick: PropTypes.bool,
parent: PropTypes.shape({
id: PropTypes.string,
value: PropTypes.string
}),
actionAppComponent: PropTypes.func,
navigationStrategy: navigationStrategy.propTypes,
contextParams: PropTypes.object,
searchFormCollapsed: PropTypes.bool,
modifyFormDefinition: PropTypes.func
}
export default EntityListApp
export {selectionStylePropType, searchFormTypePropTypes}
| JavaScript | 0.000003 | @@ -6028,16 +6028,44 @@
g%0A %7D),%0A
+ showLink: PropTypes.bool,%0A
action
|
68f8564c4020bc529f7c2c839d0d2049a44ca1f5 | Remove trailing commas | src/defaultPropTypes.js | src/defaultPropTypes.js | import PropTypes from 'prop-types';
export default {
message: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]).isRequired,
action: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.string,
PropTypes.node,
]),
onClick: PropTypes.func,
style: PropTypes.bool,
actionStyle: PropTypes.object,
titleStyle: PropTypes.object,
barStyle: PropTypes.object,
activeBarStyle: PropTypes.object,
dismissAfter: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.number,
]),
onDismiss: PropTypes.func,
className: PropTypes.string,
activeClassName: PropTypes.string,
isActive: PropTypes.bool,
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node,
]),
};
| JavaScript | 0.999987 | @@ -123,18 +123,17 @@
.element
-,
%0A
+
%5D).isR
@@ -229,25 +229,24 @@
opTypes.node
-,
%0A %5D),%0A onC
@@ -501,17 +501,16 @@
s.number
-,
%0A %5D),%0A
@@ -708,15 +708,13 @@
node
-,
%0A %5D)
-,
%0A%7D;%0A
|
77eded6d2b227842e7bb3b31ed120acf32e0733d | Fix indentation | src/commands/assign/createRequestBody.js | src/commands/assign/createRequestBody.js | import env from './assignConfig';
import {config} from '../../utils';
const createRequestBody = () => ({
projects: env.ids
.reduce((acc, id) => acc
.concat(config.languages
.map(language => ({project_id: id, language}))), []),
});
export default createRequestBody;
| JavaScript | 0.017244 | @@ -154,18 +154,16 @@
c%0A
-
.concat(
@@ -179,18 +179,16 @@
nguages%0A
-
|
0e684a7dbba8f0a0adbf23ff200f73e9a998404c | Fix #4161 (nomailize currentIndex in timelinechanged event) | src/component/timeline/timelineAction.js | src/component/timeline/timelineAction.js | /**
* @file Timeilne action
*/
define(function(require) {
var echarts = require('../../echarts');
echarts.registerAction(
{type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
function (payload, ecModel) {
var timelineModel = ecModel.getComponent('timeline');
if (timelineModel && payload.currentIndex != null) {
timelineModel.setCurrentIndex(payload.currentIndex);
if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
timelineModel.setPlayState(false);
}
}
ecModel.resetOption('timeline');
}
);
echarts.registerAction(
{type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
function (payload, ecModel) {
var timelineModel = ecModel.getComponent('timeline');
if (timelineModel && payload.playState != null) {
timelineModel.setPlayState(payload.playState);
}
}
);
}); | JavaScript | 0 | @@ -97,16 +97,63 @@
harts');
+%0A var zrUtil = require('zrender/core/util');
%0A%0A ec
@@ -694,38 +694,220 @@
-ecModel.resetOption('timeline'
+// Set normalized currentIndex to payload.%0A ecModel.resetOption('timeline');%0A%0A return zrUtil.defaults(%7B%0A currentIndex: timelineModel.option.currentIndex%0A %7D, payload
);%0A
|
da5f6525cdd4c8c4346ff7e6ab104e4e7f927df6 | Fix forgot password screen copy | src/engine/automatic.js | src/engine/automatic.js | import Base from '../index';
import Login from './automatic/login';
import SignUp from './automatic/sign_up_screen';
import ResetPassword from '../connection/database/reset_password';
import { renderSSOScreens } from '../core/sso/index';
import {
authWithUsername,
defaultDatabaseConnection,
defaultDatabaseConnectionName,
getScreen,
initDatabase
} from '../connection/database/index';
import {
defaultEnterpriseConnection,
defaultEnterpriseConnectionName,
initEnterprise,
isADEnabled,
isEnterpriseDomain,
isHRDActive,
isInCorpNetwork,
isSingleHRDConnection,
quickAuthConnection
} from '../connection/enterprise';
import { initSocial } from '../connection/social/index';
import { setEmail } from '../field/email';
import { setUsername } from '../field/username';
import * as l from '../core/index';
import KerberosScreen from '../connection/enterprise/kerberos_screen';
import HRDScreen from '../connection/enterprise/hrd_screen';
import EnterpriseQuickAuthScreen from '../connection/enterprise/quick_auth_screen';
import { hasSkippedQuickAuth } from '../quick_auth';
import { lastUsedConnection } from '../core/sso/index';
import LoadingScreen from '../core/loading_screen';
import LastLoginScreen from '../core/sso/last_login_screen';
import { hasSyncStatus, isLoading, isSuccess } from '../remote_data';
import * as c from '../field/index';
import { swap, updateEntity } from '../store/index';
export function isSSOEnabled(m) {
return isEnterpriseDomain(
m,
usernameStyle(m) === "username" ? c.username(m) : c.email(m)
);
}
export function usernameStyle(m) {
return authWithUsername(m) && !isADEnabled(m) ? "username" : "email";
}
class Automatic {
static SCREENS = {
login: Login,
forgotPassword: ResetPassword,
signUp: SignUp
};
constructor(...args) {
this.dict = dict;
this.mode = "classic";
}
didInitialize(model, options) {
model = initSocial(model, options);
model = initDatabase(model, options);
model = initEnterprise(model, options);
const { email, username } = options.prefill || {};
if (typeof email === "string") model = setEmail(model, email);
if (typeof username === "string") model = setUsername(model, username);
swap(updateEntity, "lock", l.id(model), _ => model);
}
didReceiveClientSettings(m) {
const anyDBConnection = l.hasSomeConnections(m, "database");
const anySocialConnection = l.hasSomeConnections(m, "social");
const anyEnterpriseConnection = l.hasSomeConnections(m, "enterprise");
if (!anyDBConnection && !anySocialConnection && !anyEnterpriseConnection) {
// TODO: improve message
throw new Error("At least one database, enterprise or social connection needs to be available.");
}
if (defaultDatabaseConnectionName(m) && !defaultDatabaseConnection(m)) {
l.warn(m, `The provided default database connection "${defaultDatabaseConnectionName(m)}" is not enabled.`);
}
if (defaultEnterpriseConnectionName(m) && !defaultEnterpriseConnection(m)) {
l.warn(m, `The provided default enterprise connection "${defaultEnterpriseConnectionName(m)}" is not enabled or does not allow email/password authentication.`);
}
}
render(m) {
// TODO: remove some details
if (!hasSyncStatus(m, "sso") || isLoading(m, "sso") || m.get("isLoadingPanePinned")) {
return new LoadingScreen();
}
if (!hasSkippedQuickAuth(m) && l.ui.rememberLastLogin(m)) {
if (isInCorpNetwork(m)) {
return new KerberosScreen();
}
const conn = lastUsedConnection(m);
if (conn && isSuccess(m, "sso")) {
if (l.hasConnection(m, conn.get("name"))) {
return new LastLoginScreen();
}
}
}
if (quickAuthConnection(m)) {
return new EnterpriseQuickAuthScreen();
}
if (isHRDActive(m) || isSingleHRDConnection(m)) {
return new HRDScreen();
}
const Screen = Automatic.SCREENS[getScreen(m)];
if (Screen) return new Screen();
throw new Error("unknown screen");
}
}
const dict = {
enterpriseQuickAuth: {
headerText: "Login with your corporate credentials.",
loginTo: "Login at {domain}"
},
forgotPassword: {
emailInputPlaceholder: "yours@example.com",
headerText: "Please enter your email and the new password. We will send you an email to confirm the password change.",
},
hrd: {
headerText: "Please enter your coorporate credentials at {domain}.",
passwordInputPlaceholder: "your password",
usernameInputPlaceholder: "your username"
},
kerberos: {
headerText: "You are connected from your corporate network…",
buttonLabel: "Windows Authentication",
skipLastLoginLabel: "Not your account?"
},
lastLogin: {
headerText: "Last time you logged in with",
skipLastLoginLabel: "Not your account?"
},
login: {
emailInputPlaceholder: "yours@example.com",
forgotPasswordLabel: "Don't remember your password?",
headerText: "",
loginTabLabel: "Login",
loginWith: "Login with {idp}",
passwordInputPlaceholder: "your password",
separatorText: "or",
signUpTabLabel: "Sign Up",
smallSocialButtonsHeader: "Login with",
ssoEnabled: "Single Sign-on enabled",
usernameInputPlaceholder: "your username"
},
signUp: {
emailInputPlaceholder: "yours@example.com",
headerText: "",
loginTabLabel: "Login",
passwordInputPlaceholder: "your password",
passwordStrength: {
containsAtLeast: "Contain at least %d of the following %d types of characters:",
identicalChars: "No more than %d identical characters in a row (e.g., \"%s\" not allowed)",
nonEmpty: "Non-empty password required",
numbers: "Numbers (i.e. 0-9)",
lengthAtLeast: "At least %d characters in length",
lowerCase: "Lower case letters (a-z)",
shouldContain: "Should contain:",
specialCharacters: "Special characters (e.g. !@#$%^&*)",
upperCase: "Upper case letters (A-Z)"
},
separatorText: "or",
signUpTabLabel: "Sign Up",
signUpWith: "Sign up with {idp}",
ssoEnabled: "Single Sign-on enabled",
terms: "",
usernameInputPlaceholder: "your username",
},
signedIn: {
success: "Thanks for logging in."
},
signedUp: {
success: "Thanks for signing up."
}
};
export default new Automatic();
| JavaScript | 0 | @@ -4299,27 +4299,14 @@
il a
-nd the new password
+ddress
. We
@@ -4336,19 +4336,18 @@
to
-confirm the
+reset your
pas
@@ -4355,18 +4355,10 @@
word
- change
.%22
-,
%0A %7D
|
273262b8f20b43385d2448bb2042e4835d1d53e7 | remove QRcode to string method, it's not implemeted fully | src/ethereumQrPlugin.js | src/ethereumQrPlugin.js | import QRCode from 'qrcode';
import DEFAULTS from './defaults';
import { encodeEthereumUri, decodeEthereumUri } from './uri_processor';
/**
* Main plugin logic
*/
class EthereumQRplugin {
/**
*
* Generates a data encode string
*
* @public
* @param {Object} config
* @returns String
*/
toAddressString(config) {
return this.produceEncodedValue(config);
}
/**
*
* Draws QR code to canvas tag inside specified DOM selector
*
* @public
* @param {Object} config
* @returns Promise
*/
toCanvas(config) {
const generatedValue = this.produceEncodedValue(config);
const parentEl = document.querySelector(config.selector);
if (!config.selector || parentEl === null) {
throw new Error('The canvas element parent selector is required when calling `toCanvas`');
}
return new Promise((resolve, reject) => {
QRCode.toCanvas(generatedValue, this.options, (err, canvas) => {
if (err) reject(err);
resolve({
value: generatedValue,
});
parentEl.appendChild(canvas);
canvas.setAttribute('style', `width: ${this.size}px`);
});
});
}
/**
*
* Generates DataURL for a QR code
*
* @public
* @param {Object} config
* @returns Promise
*/
toDataUrl(config) {
const generatedValue = this.produceEncodedValue(config);
return new Promise((resolve, reject) => {
QRCode.toDataURL(generatedValue, this.options, (err, url) => {
if (err) reject(err);
resolve({
dataURL: url,
value: generatedValue,
});
});
});
}
/**
* implements backwards transformation encode query string to JSON
*
* @param {String} valueString
*/
readStringToJSON(valueString) {
return decodeEthereumUri(valueString);
}
/**
* may use https://github.com/edi9999/jsqrcode for readng the canvas data to JSON
* @param {*} dataURl
*/
/*
readImageToJSON(dataURl){
const qr = new QrCode();
qr.callback = function(error, result) {
if(error) {
console.log(error)
return;
}
console.log(result)
}
qr.decode(dataURl);
}
*/
getJSON() {
return JSON.stringify(this.readStringToJSON());
}
produceEncodedValue(config) {
this.assignPluguinValues(config);
// todo split parameters of URI and parameters of image generation, it is much more natural
return encodeEthereumUri(config);
}
assignPluguinValues(request) {
this.toJSON = !!request.toJSON;
this.size = (request.size && parseInt(request.size, 10) > 0) ? parseInt(request.size, 10) : DEFAULTS.size;
this.imgUrl = request.imgUrl || false;
this.options = Object.assign(DEFAULTS.qrCodeOptions, request.options);
}
}
export default EthereumQRplugin;
| JavaScript | 0.000008 | @@ -1878,437 +1878,8 @@
%7D%0A
- /**%0A * may use https://github.com/edi9999/jsqrcode for readng the canvas data to JSON%0A * @param %7B*%7D dataURl%0A */%0A /*%0A readImageToJSON(dataURl)%7B%0A const qr = new QrCode();%0A qr.callback = function(error, result) %7B%0A if(error) %7B%0A console.log(error)%0A return;%0A %7D%0A console.log(result)%0A %7D%0A qr.decode(dataURl);%0A %7D%0A */%0A
%0A g
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.