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
|
---|---|---|---|---|---|---|---|
b935eceb061cdef57fef9be93db64f4078d5dae5
|
Add plugin blankie and crumb cookie options
|
server/manifest.js
|
server/manifest.js
|
/**
* Created by Omnius on 18/07/2016.
*/
'use strict';
const Confidence = require('confidence');
const defaultCriteria = {
env: process.env.NODE_ENV
};
const manifest = {
server: {
app: {},
connections: {
routes: {
files: {relativeTo: process.cwd() + '/views'}
},
router: {
isCaseSensitive: false,
stripTrailingSlash: true
}
}
},
connections: [
{
host: 'localhost',
// $lab:coverage:off$
port: process.env.PORT || 8088,
// $lab:coverage:on$
labels: ['web']
}
],
registrations: [
// Templates, views, UI-related
{plugin: 'inert'},
{plugin: 'vision'},
{
plugin: {
register: 'visionary',
options: {
path: 'views/layouts',
partialsPath: 'views/layouts/partials',
engines: {mustache: 'handlebars'}
}
}
},
// Auuthentication, CSP's, headers, and user-agent-related
{plugin: 'hapi-auth-basic'},
{plugin: 'hapi-auth-hawk'},
{plugin: './auth/basic/basicLoginAuth.js'},
// customLoginAuth.js for showing custom plugin demo only
{plugin: './auth/custom/customLoginAuth.js'},
{plugin: './auth/hawk/hawkAuth.js'},
// {
// plugin: {
// register: 'blankie',
// options: {
// defaultSrc: 'self'
// }
// }
// },
// {
// plugin: {
// register: 'crumb',
// options: {
// key: 'crumb',
// size: 43,
// restful: false,
// autoGenerate: true,
// addToViewContext: true,
// cookieOptions: {clearInvalid: true}
// }
// }
// },
{plugin: 'scooter'},
// Routes, handlers, methods auto-injection-related
{
plugin: {
register: 'acquaint',
options: {
routes: [
{
includes: ['server/routes/**/*.js'],
ignores: ['server/routes/preauth/*.js', 'server/routes/schemas/*.js']
}
],
handlers: [
{includes: ['server/handlers/**/*.js']}
],
methods: [
{
prefix: 'dao',
includes: ['server/methods/dao/*.js']
}
]
}
}
},
// Params, query, and payload-related
{
plugin: {
register: 'disinfect',
options: {
deleteEmpty: true,
deleteWhitespace: true,
disinfectQuery: true,
disinfectParams: true,
disinfectPayload: true
}
}
},
// Cache and database-related
{
plugin: {
register: 'hapi-ioredis',
options: {
url: 'redis://127.0.0.1:6379'
}
}
},
// Logs-related
{
plugin: {
register: 'good',
options: {
ops: {interval: 3600 * 1000},
reporters: {
console: [
{
module: 'good-squeeze',
name: 'Squeeze',
args: [{
ops: '*',
log: '*',
error: '*',
response: '*'
}]
},
{module: 'good-console'},
'stdout'
]
}
}
}
}
]
};
const store = new Confidence.Store(manifest);
exports.get = (key, criteria) => {
return store.get(key, criteria || defaultCriteria);
};
|
JavaScript
| 0 |
@@ -1448,35 +1448,32 @@
th.js'%7D,%0A
- //
%7B%0A //
@@ -1458,35 +1458,32 @@
%7B%0A
- //
plugin: %7B%0A
@@ -1480,35 +1480,32 @@
lugin: %7B%0A
- //
registe
@@ -1517,35 +1517,32 @@
lankie',%0A
- //
options
@@ -1544,35 +1544,32 @@
tions: %7B%0A
- //
def
@@ -1583,35 +1583,32 @@
: 'self'%0A
- //
%7D%0A
@@ -1601,35 +1601,32 @@
%7D%0A
- //
%7D%0A /
@@ -1615,35 +1615,32 @@
%7D%0A
- //
%7D,%0A // %7B
@@ -1634,19 +1634,16 @@
%0A
- //
%7B%0A
@@ -1640,27 +1640,24 @@
%7B%0A
- //
plugin:
@@ -1658,35 +1658,32 @@
lugin: %7B%0A
- //
registe
@@ -1693,35 +1693,32 @@
'crumb',%0A
- //
options
@@ -1720,35 +1720,32 @@
tions: %7B%0A
- //
key
@@ -1744,32 +1744,33 @@
key: 'crumb
+z
',%0A //
@@ -1756,34 +1756,32 @@
rumbz',%0A
-//
siz
@@ -1776,17 +1776,16 @@
-
size: 43
@@ -1786,34 +1786,32 @@
ze: 43,%0A
-//
res
@@ -1810,22 +1810,25 @@
- restful: fals
+autoGenerate: tru
e,%0A
@@ -1825,35 +1825,32 @@
e: true,%0A
- //
aut
@@ -1843,35 +1843,39 @@
a
-utoGenerate
+ddToViewContext
: true,%0A
@@ -1870,34 +1870,32 @@
: true,%0A
-//
add
@@ -1890,38 +1890,29 @@
- addToViewContext: tru
+restful: fals
e,%0A
@@ -1906,34 +1906,32 @@
false,%0A
-//
coo
@@ -1926,17 +1926,16 @@
-
cookieOp
@@ -1946,27 +1946,256 @@
s: %7B
-clearInvalid: true%7D
+%0A ttl: 1000,%0A isSecure: false,%0A isHttpOnly: true,%0A clearInvalid: true,%0A domain: '127.0.0.1',%0A encoding: 'none'
%0A
@@ -2195,26 +2195,24 @@
ne'%0A
-//
%7D%0A
@@ -2200,32 +2200,35 @@
+
%7D%0A //
@@ -2225,15 +2225,30 @@
-//
+
+ %7D%0A
%7D%0A
@@ -2252,19 +2252,16 @@
%0A
- //
%7D,%0A
|
be7429a40d5436d9f6e019ba0e75917cc41f3d32
|
Add extent and filter types in custom.js.
|
public/javascripts/custom.js
|
public/javascripts/custom.js
|
/*
* Copyright 2016 Ali Moghnieh
*
* 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.
*/
$(function() {
$('[data-toggle="tooltip"]').tooltip()
})
//--- cards -------------------------------------
$('.card-primary,.card-success,.card-info,.card-danger,.card-warning').addClass('card-colored');
var types = {
array: {href: "/types#Array & List"}
,boolean: {href: "/types#Boolean"}
,float: {href: "/types#Float"}
,int: {href: "/types#Integer"}
,integer: {href: "/types#Integer"}
,string: {href: "/types#String"}
,vector: {href: "/types#Vector"}
,duration: {href: "/types#Duration"}
};
var modules = {
'extents': {
href: "/modules/extents"
}, 'boolean': {
href: "/types#Boolean"
}
};
$('mark,code').each(function (item) {
var e = $(this);
var text = e.text();
// Terminate as this is most likely a block of code, rather than just a type name.
if (text.length > 64) {
return;
}
var classToAdd = 'data-type';
var foundType = types[text.trim().toLowerCase()];
if (!foundType) {
foundType = modules[text.trim().toLowerCase()];
classToAdd = 'module-type';
}
if (foundType) {
e.text(""); // Remove original text
var anchor = document.createElement("a");
anchor.href = foundType.href;
anchor.innerHTML = text; // add original text in the anchor tag
e.addClass(classToAdd);
e.append(anchor);
}
});
$(function(){
$('pre code').each(function() {
var lines = $(this).text().split('\s').length - 1;
var $numbering = $('<ul/>').addClass('pre-numbering');
$(this)
.addClass('has-numbering')
.parent()
.append($numbering);
for(i=1;i<=lines;i++){
$numbering.append($('<li/>').text(i));
}
});
});
|
JavaScript
| 0 |
@@ -1118,16 +1118,91 @@
ration%22%7D
+%0A%0A ,extent: %7Bhref: %22/types#Extent%22%7D%0A ,filter: %7Bhref: %22/types#Filter%22%7D
%0A%7D;%0Avar
|
d0501b8317684c033afe01b711547ad9829cbe5c
|
fix path seperator
|
lib/file-emitter.js
|
lib/file-emitter.js
|
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('util');
var events = require('events');
var minimatch = require('minimatch');
var File = require('./file');
/**
* file-emitter
*
* **opt_options**
* - `{string} mode` The mode of operation; `stats`, `buffer`, defaults to `buffer`
* - `{boolean} autorun` ..., defaults to `true`
* - `{RegExp} pattern` Test files before emitting/reading, defaults to `false`
* - `{Array<string>} ignore` An array of glob patterns to ignore
* - `{boolean} followSymLinks` ..., defaults to `false`
* - `{number} maxFDs` The maximum number of open fds, defaults to `Infinity`
* - `{number} maxFileSize` The max size for a file to buffer, defaults to `10485760` (=10MiB)
*
* @param {string} folder
* @param {?Object} opt_options
*
* @constructor
*/
function FileEmitter(folder, opt_options) {
if (!(this instanceof FileEmitter)) {
return new FileEmitter(folder, opt_options);
}
events.EventEmitter.call(this);
opt_options = opt_options || {};
this.root = path.resolve(process.cwd(), folder);
this.mode = opt_options.mode || 'buffer';
this.followSymLinks = opt_options.followSymLinks || false;
this.pattern = opt_options.pattern || false;
this.ignore = opt_options.ignore || false;
this.maxFileSize = opt_options.maxFileSize || 10485760; // 10 MiB
// @type {Array<string>}
this._readdirQueue = [''];
// @type {Array<string>}
this._statQueue = [];
// @type {Array<Object>}
this._readQueue = [];
this._hadError = false;
this._maxFDs = opt_options.maxFDs || Infinity;
this._numFDs = 0;
var self = this;
if (opt_options.autorun !== false) {
setImmediate(function() {
self.run();
});
}
}
util.inherits(FileEmitter, events.EventEmitter);
module.exports = FileEmitter;
FileEmitter.prototype.isIgnored = function(file) {
var i;
if (this.ignore) {
file = file.substr(1); // cut off leading slash
for (i = 0; i < this.ignore.length; ++i) {
if (minimatch(file, this.ignore[i])) {
return true;
}
}
}
return false;
};
/**
* @param {string} action
* @param {string|Object} item
* @param {?Error=} opt_err
*/
FileEmitter.prototype._return = function(action, item, opt_err) {
var queue;
--this._numFDs;
switch (action) {
case 'readdir':
queue = this._readdirQueue;
break;
case 'stat':
queue = this._statQueue;
break;
case 'read':
queue = this._readQueue;
break;
}
if (opt_err) {
// maximum number of file descriptors exceeded, see `ulimit -n`
if (opt_err.code === 'EMFILE') {
queue.unshift(item); // re-add item
if (this._maxFDs > this._numFDs) {
this._maxFDs = this._numFDs;
} else {
this._maxFDs = Math.max(--this._maxFDs, 1); // ensure > 0
}
} else {
this._hadError = true;
this.emit('error', opt_err, item);
}
}
this.run();
};
/**
* @param {string} directory
* @return {void}
*/
FileEmitter.prototype._readdir = function(directory) {
var self = this;
var absolutePath = this.root + directory;
fs.readdir(absolutePath, function(err, files) {
if (err) {
return self._return('readdir', directory, err);
}
var i, file;
for (i = 0; i < files.length; ++i) {
file = directory + '/' + files[i];
if (!self.isIgnored(file)) {
self._statQueue.push(file);
}
}
self._return('readdir', directory);
});
};
/**
* @param {string} file The
* @return {void}
*/
FileEmitter.prototype._stat = function(file) {
var self = this;
var absolutePath = this.root + file;
var obj;
fs.lstat(absolutePath, function(err, stats) {
if (err) {
return self._return('stat', file, err);
}
if (stats.isSymbolicLink() && !self.followSymLinks) {
// TODO: maybe emit an event that we ignored a symlink
return self._return('stat', file);
}
if (stats.isDirectory()) {
self._readdirQueue.push(file);
} else if (stats.isFile() && (!self.pattern || self.pattern.test(file))) {
obj = new File(self, file, stats);
if (self.mode === 'buffer' && stats.size <= self.maxFileSize) {
self._readQueue.push(obj);
} else {
self.emit('file', obj);
}
}
self._return('stat', file);
});
};
/**
* @param {Object} item
* @return {void}
*/
FileEmitter.prototype._read = function(item) {
var self = this;
var absolutePath = this.root + item.name;
fs.readFile(absolutePath, function(err, data) {
if (err) {
return self._return('read', item, err);
}
item.buffer = data;
self.emit('file', item);
self._return('read', item);
});
};
FileEmitter.prototype.run = function() {
var i, limit;
var x = 0;
limit = Math.min(this._maxFDs - this._numFDs, this._readdirQueue.length);
if (limit > 0) {
for (i = 0; i < limit; ++i) {
++this._numFDs;
this._readdir(this._readdirQueue.shift());
}
x += limit;
}
limit = Math.min(this._maxFDs - this._numFDs, this._statQueue.length);
if (limit > 0) {
for (i = 0; i < limit; ++i) {
++this._numFDs;
this._stat(this._statQueue.shift());
}
x += limit;
}
limit = Math.min(this._maxFDs - this._numFDs, this._readQueue.length);
if (limit > 0) {
for (i = 0; i < limit; ++i) {
++this._numFDs;
this._read(this._readQueue.shift());
}
x += limit;
}
if (x + this._numFDs === 0) {
this.emit('end', this._hadError);
}
};
|
JavaScript
| 0.000199 |
@@ -3345,11 +3345,16 @@
y +
-'/'
+path.sep
+ f
|
6f2f808920e80def610ebde4cb985365cad99339
|
fix bug on unsupported platform
|
lib/find_process.js
|
lib/find_process.js
|
/*
* @Author: zoujie.wzj
* @Date: 2016-01-23 18:25:37
* @Last Modified by: zoujie.wzj
* @Last Modified time: 2016-10-13 15:18:00
*/
'use strict'
const path = require('path')
const utils = require('./utils')
function matchName (text, name) {
if (!name) {
return true
}
return text.match(name)
}
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]) {
return matchName(column[4], cond.name)
} else {
return false
}
})
let list = columns.map(column => {
let cmd = String(column[4]).split(' ', 1)[0]
return {
pid: column[0],
ppid: column[1],
uid: column[2],
gid: column[3],
name: path.basename(cmd),
cmd: column[4]
}
})
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'
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('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 {
return matchName(row.CommandLine, cond.name)
}
})
.map(row => ({
pid: row.ProcessId,
ppid: row.ParentProcessId,
uid: null,
gid: null,
name: row.Name,
cmd: row.CommandLine
}))
resolve(list)
})
})
}
}
function findProcess (cond) {
let platform = process.platform
return new Promise((resolve, reject) => {
if (!(platform in finders)) {
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.000001 |
@@ -2979,24 +2979,31 @@
s)) %7B%0A
+return
reject(new E
|
7f544f2bca3ae48b8dc0d041fc81578c4f30da6f
|
Disable source maps + blackboxing (#490)
|
public/js/clients/firefox.js
|
public/js/clients/firefox.js
|
const { DebuggerClient } = require("devtools-sham/shared/client/main");
const { DebuggerTransport } = require("devtools-sham/transport/transport");
const WebSocketDebuggerTransport = require("devtools/shared/transport/websocket-transport");
const { TargetFactory } = require("devtools-sham/client/framework/target");
const defer = require("../utils/defer");
const { getValue } = require("../feature");
const { Tab } = require("../types");
const { setupCommands, clientCommands } = require("./firefox/commands");
const { setupEvents, clientEvents } = require("./firefox/events");
let debuggerClient = null;
let threadClient = null;
let tabTarget = null;
function getThreadClient() {
return threadClient;
}
function setThreadClient(client) {
threadClient = client;
}
function getTabTarget() {
return tabTarget;
}
function setTabTarget(target) {
tabTarget = target;
}
function lookupTabTarget(tab) {
const options = { client: debuggerClient, form: tab, chrome: false };
return TargetFactory.forRemoteTab(options);
}
function createTabs(tabs) {
return tabs.map(tab => {
return Tab({
title: tab.title,
url: tab.url,
id: tab.actor,
tab,
browser: "firefox"
});
});
}
function connectClient() {
const deferred = defer();
let isConnected = false;
const useProxy = !getValue("firefox.webSocketConnection");
const portPref = useProxy ? "firefox.proxyPort" : "firefox.webSocketPort";
const webSocketPort = getValue(portPref);
const socket = new WebSocket(`ws://${document.location.hostname}:${webSocketPort}`);
const transport = useProxy ?
new DebuggerTransport(socket) : new WebSocketDebuggerTransport(socket);
debuggerClient = new DebuggerClient(transport);
// TODO: the timeout logic should be moved to DebuggerClient.connect.
setTimeout(() => {
if (isConnected) {
return;
}
deferred.resolve([]);
}, 1000);
debuggerClient.connect().then(() => {
isConnected = true;
return debuggerClient.listTabs().then(response => {
deferred.resolve(createTabs(response.tabs));
});
}).catch(err => {
console.log(err);
deferred.reject();
});
return deferred.promise;
}
function connectTab(tab) {
return new Promise((resolve, reject) => {
window.addEventListener("beforeunload", () => {
getTabTarget() && getTabTarget().destroy();
});
lookupTabTarget(tab).then(target => {
tabTarget = target;
target.activeTab.attachThread({}, (res, _threadClient) => {
threadClient = _threadClient;
threadClient.resume();
resolve();
});
});
});
}
function initPage(actions) {
tabTarget = getTabTarget();
threadClient = getThreadClient();
setupCommands({ threadClient, tabTarget });
tabTarget.on("will-navigate", actions.willNavigate);
tabTarget.on("navigate", actions.navigate);
// Listen to all the requested events.
setupEvents({ threadClient, actions });
Object.keys(clientEvents).forEach(eventName => {
threadClient.addListener(eventName, clientEvents[eventName]);
});
// In Firefox, we need to initially request all of the sources which
// makes the server iterate over them and fire individual
// `newSource` notifications. We don't need to do anything with the
// response since `newSource` notifications are fired.
threadClient.getSources();
}
module.exports = {
connectClient,
connectTab,
clientCommands,
getThreadClient,
setThreadClient,
getTabTarget,
setTabTarget,
initPage
};
|
JavaScript
| 0 |
@@ -3061,24 +3061,114 @@
e%5D);%0A %7D);%0A%0A
+ threadClient.reconfigure(%7B%0A %22useSourceMaps%22: false,%0A %22autoBlackBox%22: false%0A %7D);%0A%0A
// In Fire
|
12bfe07efc9fab5d1590aa136ded6bb9e0c5d74b
|
tag github request metrics by installationId and method
|
lib/github-queue.js
|
lib/github-queue.js
|
const Queue = require('promise-queue')
const env = require('./env')
const dbs = require('../lib/dbs')
const Log = require('gk-log')
const statsd = require('./statsd')
const getToken = require('./get-token')
const Github = require('../lib/github')
const writeQueue = new Queue(1, Infinity)
const readQueue = new Queue(50, Infinity)
module.exports = function (installationId) {
return {
write: write.bind(null, installationId),
read: read.bind(null, installationId)
}
}
function setupLog () {
const logs = dbs.getLogsDb()
const log = Log({logsDb: logs, context: 'github-queue'})
return log
}
function reportStats (stats) {
const waitingInQueue = stats.started - stats.queued
const waitingForToken = stats.tokenized - stats.started
const waitingForResponse = stats.done - stats.tokenized
const waitingForNetwork = stats.done - stats.started
const total = stats.done - stats.queued
statsd.gauge(`queues.github_${stats.type}_requests_time_in_queue`, waitingInQueue)
statsd.gauge(`queues.github_${stats.type}_requests_time_to_token`, waitingForToken)
statsd.gauge(`queues.github_${stats.type}_requests_time_to_response`, waitingForResponse)
statsd.gauge(`queues.github_${stats.type}_requests_time_in_network`, waitingForNetwork)
statsd.gauge(`queues.github_${stats.type}_requests_time_total`, total)
}
function write (installationId, gen) {
statsd.increment('queues.github_write_requests')
const stats = {
type: 'write',
queued: Date.now()
}
try {
return writeQueue.add(() => {
return Promise.delay(env.NODE_ENV === 'testing' ? 0 : 1000)
.then(() => {
stats.started = Date.now()
return getToken(installationId)
})
.then(({token}) => {
stats.tokenized = Date.now()
const github = Github()
github.authenticate({ type: 'token', token })
return gen(github)
})
.then(response => {
stats.done = Date.now()
reportStats(stats)
return response.data
})
})
} catch (e) {
statsd.increment('queues.github_write_failures')
const log = setupLog()
log.warn('github: write exception', { installationId, exception: e })
throw e
}
}
function read (installationId, gen) {
statsd.increment('queues.github_read_requests')
const stats = {
type: 'read',
queued: Date.now()
}
try {
return readQueue.add(() => {
stats.started = Date.now()
return getToken(installationId)
.then(({token}) => {
stats.tokenized = Date.now()
const github = Github()
github.authenticate({ type: 'token', token })
return gen(github)
})
.then(response => {
stats.done = Date.now()
reportStats(stats)
if (response.data) {
return response.data
}
// some responses don’t have .data, let’s find out which
// https://rollbar.com/neighbourhoodie/gk-jobs/items/2969/
var logs = dbs.getLogsDB()
const log = Log({logsDb: logs, accountId: 'github', repoSlug: 'queue', context: 'github-queue'})
log.warn('github: response.data is `undefined`', { installationId, response })
})
})
} catch (e) {
statsd.increment('queues.github_read_failures')
const log = setupLog()
log.warn('github: read exception', { installationId, exception: e })
throw e
}
}
if (env.NODE_ENV !== 'testing') {
setInterval(
function collectGitHubQueueStats () {
statsd.gauge('queues.github-write', writeQueue.getQueueLength())
statsd.gauge('queues.github-read', readQueue.getQueueLength())
},
5000
)
}
|
JavaScript
| 0 |
@@ -1329,24 +1329,139 @@
, total)%0A%7D%0A%0A
+function getGitHubMethod (gen) %7B%0A const %5B match %5D = gen.toString().match(/github%5C.%5B%5E(%5D+/)%0A return match %7C%7C ''%0A%7D%0A%0A
function wri
@@ -1528,32 +1528,72 @@
_write_requests'
+, %5BinstallationId, getGitHubMethod(gen)%5D
)%0A const stats
@@ -2475,16 +2475,56 @@
equests'
+, %5BinstallationId, getGitHubMethod(gen)%5D
)%0A cons
|
4c018915a3d3a8ff94e47dc157e15cffb1affd50
|
add fields to interactivity rendering
|
servers/Tile.bones
|
servers/Tile.bones
|
var path = require('path'),
tilelive = require('tilelive'),
settings = Bones.plugin.config;
server = Bones.Server.extend({});
server.prototype.initialize = function() {
_.bindAll(this, 'load', 'grid', 'layer', 'getArtifact');
this.get('/1.0.0/:id/:z/:x/:y.:format(png8|png|jpeg[\\d]+|jpeg)', this.load, this.getArtifact);
this.get('/1.0.0/:id/:z/:x/:y.:format(grid.json)', this.load, this.grid, this.getArtifact);
this.get('/1.0.0/:id/layer.json', this.load, this.layer);
};
server.prototype.load = function(req, res, next) {
res.project = new models.Project({id: req.param('id')});
res.project.fetch({
success: function(model, resp) {
res.projectMML = resp;
next();
},
error: function(model, resp) {
next(resp);
}
});
};
server.prototype.getArtifact = function(req, res, next) {
// This is the cache key in tilelive-mapnik, so make sure it
// contains the mtime with _updated.
var id = req.params.id;
var uri = {
protocol: 'mapnik:',
slashes: true,
pathname: path.join(settings.files, 'project', id, id + '.mml'),
search: '_updated=' + res.projectMML._updated,
data: res.projectMML
};
tilelive.load(uri, function(err, source) {
if (err) return next(err);
var z = req.params.z, x = +req.params.x, y = +req.params.y;
// The interface is still TMS.
y = (1 << z) - 1 - y;
var fn = req.params.format === 'grid.json' ? 'getGrid' : 'getTile';
source[fn](z, x, y, function(err, tile, headers) {
if (err) return next(err);
headers['max-age'] = 3600;
res.send(tile, headers);
});
});
};
server.prototype.grid = function(req, res, next) {
// Early exit. tilelive-mapnik would catch that too.
if (!res.project.get('interactivity')) {
return next(new Error.HTTP('Not found.', 404));
}
// Force jsonp.
req.query.callback = 'grid';
next();
};
server.prototype.layer = function(req, res, next) {
if (!res.project.get('formatter') && !res.project.get('legend')) {
next(new Error.HTTP('Not found.', 404));
} else {
req.query.callback = 'grid'; // Force jsonp.
res.send({
formatter: res.project.get('formatter'),
legend: res.project.get('legend')
});
}
};
|
JavaScript
| 0.000001 |
@@ -2012,16 +2012,155 @@
'grid';
+%0A%0A var interactivity = res.project.get('interactivity');%0A res.projectMML.interactivity.fields = models.Project.fields(interactivity);
%0A nex
|
8cd544eebbeb7b358614066c932332762f520716
|
Fix condition of completion
|
src/EditorPane/codemirror-hint-extension.js
|
src/EditorPane/codemirror-hint-extension.js
|
import CodeMirror from 'codemirror';
import 'codemirror/addon/hint/anyword-hint';
const anywordHint = CodeMirror.hint.anyword;
CodeMirror.hint.javascript = (instance, options) => {
const cursor = instance.getCursor();
const token = instance.getTokenAt(cursor);
const from = { line: cursor.line, ch: token.start };
const to = { line: cursor.line, ch: cursor.ch };
const empty = { list: [], from, to };
if (/[\;\=\)\,]$|^\s*$|^\($/.test(token.string)) {
return empty;
}
const result = anywordHint(instance, options) || empty;
if (token.type === 'string') {
const left = instance.getLine(cursor.line)
.substr(0, cursor.ch)
.substr(token.start + 1);
const moduleNames = options.files
.filter(file => file.moduleName.indexOf(left) === 0)
.map(file => ({
text: file.moduleName,
from: { line: from.line, ch: from.ch + 1 },
}));
result.list = moduleNames.concat(result.list);
}
return result;
};
|
JavaScript
| 0.000006 |
@@ -418,30 +418,20 @@
if (
+!
/%5B
-%5C;%5C=%5C)%5C,%5D$%7C%5E%5Cs*$%7C%5E%5C(
+A-Za-z%5C.%5D
$/.t
|
d94aadd61a0e4f2994af63bd28e806a8c1aad43f
|
separate stdout and stderr
|
service_manager.js
|
service_manager.js
|
var childProcess = require('child_process');
var spawn = childProcess.spawn;
var rimraf = require('rimraf');
var config = require('./config');
var services = {};
var debugServerChild = null;
var promisify = require('promisify-node');
var fs = promisify('fs');
var _ = require('lodash');
var forever = require('forever-monitor');
var unusedDebugPort = 5000;
var serviceIDs = 0;
function createDir(dir) {
return fs.mkdir(dir).catch(function(err) {
if (err && err.code === 'EEXIST') {
return;
}
throw new Error(err);
});
}
var ServiceManager = {
serviceExists: function(serviceID) {
return serviceID in services;
},
getServiceWithoutChild: function(service) {
return _.omit(service, ['child']);
},
listProcesses: function() {
return _.mapValues(services, this.getServiceWithoutChild);
},
getProcessInfo: function(serviceID) {
if (!this.serviceExists(serviceID)) {
return Promise.reject('Service #' + serviceID + ' does not exist.');
}
return fs.readFile(config.logsDir + '/' + serviceID + '/stdout.log', 'utf8').then(function(log) {
return {
service: this.getServiceWithoutChild(services[serviceID]),
log: log
};
}.bind(this));
},
addService: function(entryPoint) {
if (!fs.existsSync(config.servicesDir + '/' + entryPoint)) {
return Promise.reject("Entry point doesn't exist");
}
var serviceID = serviceIDs++;
services[serviceID] = {
id: serviceID,
status: 0,
start: -1,
kill: -1,
child: null,
debugPort: null,
entryPoint: entryPoint
};
return createDir(config.logsDir).then(function() {
return createDir(config.logsDir + '/' + serviceID);
}).then(function() {
return serviceID;
});
},
getFilepath: function(serviceID) {
return config.servicesDir + '/' + serviceID + '/index.js';
},
spawnProcess: function(serviceID) {
if (!this.serviceExists(serviceID)) {
throw new Error('Service #' + serviceID + ' not found.');
}
var service = services[serviceID];
var serviceFile = config.servicesDir + '/' + service.entryPoint;
var logFile = config.logsDir + '/' + serviceID + '/stdout.log';
fs.writeFile(logFile, '');
var debugPort = unusedDebugPort++;
var child = spawn('node', ['--debug=' + debugPort, serviceFile]);
service.start = new Date().getTime();
service.status = 1;
service.child = child;
service.debugPort = debugPort;
services[serviceID] = service;
child.stdout.on('data', function (data) {
fs.appendFile(logFile, data.toString());
console.log(child.pid, data.toString());
});
child.stderr.on('data', function (data) {
fs.appendFile(logFile, data.toString());
console.log(child.pid, data.toString());
});
child.on('close', function(exit_code) {
var runningService = services[serviceID];
if (runningService) {
runningService.status = 0;
runningService.kill = new Date().getTime();
}
console.log('Closed before stop: Closing code: ', exit_code);
});
return child.pid;
},
killProcess: function(serviceID) {
var runningService = services[serviceID];
if (runningService) {
console.log('kill process');
runningService.child.kill('SIGKILL');
runningService.status = 0;
runningService.kill = new Date().getTime();
}
},
removeProcess: function(serviceID, cb) {
var runningService = services[serviceID];
if (runningService) {
this.killProcess(serviceID);
delete services[serviceID];
}
},
startDebugServer: function() {
if (debugServerChild) {
console.log('Debug server was already started.');
return;
}
console.log('Starting debug server on port ' +
config.NODE_INSPECTOR_WEB_PORT+ '...');
var inspectorPath = './node_modules/node-inspector/bin/inspector.js';
var child = new (forever.Monitor)(
inspectorPath,
{
max : 100,
silent : true,
args: [
'--web-port', config.NODE_INSPECTOR_WEB_PORT,
'--save-live-edit', 'true'
]
}
);
child.start();
debugServerChild = child;
child.on('restart', function() {
console.log("Debug server was restarted automatically");
})
child.on('stdout', function (data) {
console.log(child.pid, data.toString());
});
child.on('stderr', function (data) {
console.log(child.pid, data.toString());
});
child.on('exit', function(exit_code) {
console.log('Closed before stop: Closing code: ', exit_code);
});
process.on('exit', function() {
debugServerChild.kill('SIGKILL');
});
},
shutdownDebugServer: function() {
if (debugServerChild) {
console.log('kill debug server');
debugServerChild.kill('SIGKILL');
debugServerChild = null;
}
}
};
module.exports = ServiceManager;
|
JavaScript
| 0.99856 |
@@ -1000,16 +1000,36 @@
return
+Promise.all(%5B%0A
fs.readF
@@ -1089,16 +1089,100 @@
'utf8')
+,%0A fs.readFile(config.logsDir + '/' + serviceID + '/stderr.log', 'utf8')%0A %5D)
.then(fu
@@ -1191,16 +1191,17 @@
tion(log
+s
) %7B%0A
@@ -1290,16 +1290,48 @@
-log
+stdout: logs%5B0%5D,%0A stderr
: log
+s%5B1%5D
%0A
@@ -2285,19 +2285,22 @@
var
-log
+stdout
File = c
@@ -2356,24 +2356,132 @@
-fs.writeFile(log
+var stderrFile = config.logsDir + '/' + serviceID + '/stderr.log';%0A fs.writeFile(stdoutFile, '');%0A fs.writeFile(stderr
File
@@ -2821,35 +2821,38 @@
fs.appendFile(
-log
+stdout
File, data.toStr
@@ -2981,19 +2981,22 @@
endFile(
-log
+stderr
File, da
@@ -4579,22 +4579,23 @@
ally%22);%0A
-
%7D)
+;
%0A%0A ch
|
ef993141781c6b3c2558c52aaa8d18a5bdd892d6
|
Swap property names.
|
db/model.js
|
db/model.js
|
'use strict'
let sql = require('sql')
let Query = require('./query')
class Model {
constructor (data) {
this.constructor.defineProperties()
this.data = new Map()
for (let key in data) if (this.properties[key]) this[key] = data[key]
}
get db () {
return this.constructor.db
}
get table () {
return this.constructor.table
}
get tableName () {
return this.constructor.tableName
}
get colunns () {
return this.constructor.columns
}
get relations () {
return this.constructor.relations
}
get properties () {
return this.constructor.properties
}
slice () {
let result = {}
for (let key of arguments) result[key] = this[key]
return result
}
update (values) {
for (let key in values) this[key] = values[key]
return new Query(this.constructor)
.where({id: this.id})
.update(this.slice.apply(this, Object.keys(values)))
}
destroy () {
return new Query(this.constructor).where({id: this.id}).delete()
}
static get table () {
if (!this._table) {
this._table = sql.define({name: this.tableName, columns: this.columns})
}
return this._table
}
static get properties () {
if (!this._properties) {
this._properties = {}
for (let column of this.table.columns) {
this._properties[column.property] = column
}
}
return this._properties
}
static get relations () {
if (!this._relations) this._relations = {}
return this._relations
}
static create (values) {
return new Query(this).insert(values)
}
static hasMany (name, options) {
options.many = true
this.relations[name] = options
}
static belongsTo (name, options) {
options.many = false
this.relations[name] = options
}
static defineProperties () {
if (this._propsDefined) return
this._propsDefined = true
for (let column of this.table.columns) {
if (Object.getOwnPropertyDescriptor(this.prototype, column.property)) {
continue
}
Object.defineProperty(this.prototype, column.property, {
get: function () { return this.data.get(column.name) },
set: function (value) { this.data.set(column.name, value) }
})
}
}
}
// Attach Query methods to Model
let queryMethods = [
'all',
'find',
'include',
'limit',
'match',
'offset',
'order',
'where'
]
for (let method of queryMethods) {
Model[method] = function () {
let query = new Query(this)
return query[method].apply(query, arguments)
}
}
module.exports = Model
|
JavaScript
| 0 |
@@ -2112,16 +2112,26 @@
ion () %7B
+%0A
return
@@ -2155,13 +2155,25 @@
umn.
-name)
+property)%0A
%7D,%0A
@@ -2203,16 +2203,26 @@
value) %7B
+%0A
this.da
@@ -2239,20 +2239,32 @@
umn.
-name, value)
+property, value)%0A
%7D%0A
|
d788e89038098f33d997e5ecc1af3687eccf3f96
|
Use appropriate promise
|
services/matrix.js
|
services/matrix.js
|
'use strict';
// Dependencies
const matrix = require('matrix-js-sdk');
// Fabric Types
const Entity = require('../types/entity');
const Interface = require('../types/interface');
// TODO: compare API against {@link Service}
const Service = require('../types/service');
// Local Values
const COORDINATORS = [
'!pPjIUAOkwmgXeICrzT:fabric.pub' // Primary Coordinator
];
/**
* Service for interacting with Matrix.
* @module services/matrix
*/
class Matrix extends Interface {
/**
* Create an instance of a Matrix client, connect to the
* network, and relay messages received from therein.
* @param {Object} [settings] Configuration values.
*/
constructor (settings = {}) {
super(settings);
// Assign defaults
this.settings = Object.assign({
name: '@fabric/matrix',
homeserver: 'https://fabric.pub',
coordinator: COORDINATORS[0]
}, settings);
this.client = matrix.createClient(this.settings.homeserver);
this._state = {
status: 'READY',
channels: COORDINATORS,
messages: []
};
return this;
}
get status () {
return this._state[`status`];
}
set status (value = this.status) {
switch (value) {
case 'READY':
this._state[`status`] = value;
break;
default:
return false;
}
return true;
}
/**
* Getter for {@link State}.
*/
get state () {
// TODO: remove old use of `@data` while internal to Fabric
return this._state['@data'];
}
async _listPublicRooms () {
let rooms = await this.client.publicRooms();
return rooms;
}
async _registerActor (actor) {
const password = 'f00b4r';
const available = false;
try {
available = await this._checkUsernameAvailable(actor.pubkey);
} catch (exception) {
// this.emit('error', 'Username already registered.');
}
if (available) {
try {
await this.register(actor.pubkey, actor.privkeyhash || password);
} catch (exception) {
}
try {
await this.login(actor.pubkey, actor.privkeyhash || password);
} catch (exception) {
}
} else {
try {
await this.login(actor.pubkey, actor.privkeyhash || password);
} catch (exception) {
}
}
try {
await this.client.joinRoom(this.settings.coordinator);
} catch (exception) {
this.emit('error', `Could not join coordinator: ${exception}`);
}
}
async _send (msg) {
const service = this;
const content = {
'body': (msg && msg.object) ? msg.object.content : msg.object,
'msgtype': 'm.text'
};
try {
this.client.sendEvent(this.settings.coordinator, 'm.room.message', content, '', (err, res) => {
if (err) return service.emit('error', `Could not send message to service: ${err}`);
});
} catch (exception) {
this.emit('error', `Could not send message: ${exception}`);
}
}
async login (username, password) {
return this.client.login('m.login.password', { user: username, password: password });
}
async register (username, password) {
const self = this;
const promise = new Promise((resolve, reject) => {
this.emit('message', `Trying registration: ${username}:${password}`);
result = this.client.registerRequest({
username: username,
password: password,
auth: {
type: 'm.login.dummy'
}
}).then((output) => {
resolve(output);
});
});
return result;
}
async _checkUsernameAvailable (username) {
const self = this;
return new Promise(async (resolve, reject) => {
try {
const available = await self.client.isUsernameAvailable(username);
return resolve(available);
} catch (exception) {
return reject('Username not available.');
}
});
}
async _handleMatrixMessage (msg) {
if (msg.getType() !== 'm.room.message') {
return; // only use messages
}
this.emit('message', {
actor: msg.event.sender,
object: {
content: msg.event.content.body
},
target: '/messages'
});
}
/**
* Start the service, including the initiation of an outbound connection
* to any peers designated in the service's configuration.
*/
async start () {
this.status = 'STARTING';
this.emit('message', '[SERVICES:MATRIX] Starting...');
// this.log('[SERVICES:MATRIX]', 'Starting...');
await this.client.startClient({ initialSyncLimit: 10 });
this.status = 'STARTED';
this.emit('message', '[SERVICES:MATRIX] Started!');
// this.log('[SERVICES:MATRIX]', 'Started!');
}
/**
* Stop the service.
*/
async stop () {
this.status = 'STOPPING';
// this.log('[SERVICES:MATRIX]', 'Stopping...');
this.status = 'STOPPED';
// this.log('[SERVICES:MATRIX]', 'Stopped!');
}
}
module.exports = Matrix;
|
JavaScript
| 0.998982 |
@@ -3191,28 +3191,28 @@
=%3E %7B%0A
-this
+self
.emit('messa
@@ -3508,22 +3508,23 @@
return
-result
+promise
;%0A %7D%0A%0A
@@ -3638,24 +3638,87 @@
eject) =%3E %7B%0A
+ self.emit('message', %60Checking username: $%7Busername%7D%60);%0A%0A
try %7B%0A
|
c3da505a1986c5b4ac868c9e91984cb2eb27a48c
|
fix space issues and ES6
|
public/src/inverted-index.js
|
public/src/inverted-index.js
|
/** @class representing an Index. */
module.exports = class Index {
/**
* Creates Index constructor.
*/
constructor(){
this.container = {};
}
/**
* @method checks file
* @param {string} fileContents
*/
fileCheck(fileContents) {
if (fileContents.files === undefined) {
return this.message = {
type: "fileEmpty",
status: false,
message: fileContents.name + "is empty!"
};
}
if (typeof fileContents === "object") {
return this.message = {
type: "fileValid",
status: true,
message: fileContents.name + " has been indexed successfully."
};
}
let x = stringify(fileContents);
if ((JSON.parse(x)) === false) {
return this.message = {
type: "invalidFormat",
status: false,
message: fileContents.name + "Invalid format."
};
}
}
/**
* sanitizes input
*
* @method sanitizeInput
* @param {string} content
* @return {string} return characters
*/
sanitizeInput (content) {
let characters = content.trim().replace(/[.[,\]/#!$%\^&\*;:@{}=\-_`~()]/g, '').toLowerCase().split(' ');
return characters;
}
/**
* method that creates object of indices and check
* if word has been indexed before
* @param {array} words
* @param {string} file
* @param {object} source
* @param {number} id
*/
checkIndex (words , file , source , id ) {
words.forEach( (word) => {
let the = this.sanitizeInput(word);
if (this.container[file][the] === undefined) {
this.container[file][the] = {};
this.container[file][the][id] = {
source: source,
file:file
};
}
this.container[file][the][id] = {
source: source,
file: file
};
});
}
/**
* method that creates indices
* @param{json} fileContents
*/
createIndex(fileContents) {
let check = this.fileCheck(fileContents);
if(check.type === "fileEmpty") {
return check;
}
else if(check.type === "invalidFormat") {
alert("It looks like the file is in bad format.");
}
else if (check.type === "fileValid") {
let indFiles = fileContents.files;
let arr = [];
this.container[fileContents.name] = {
uploadedFile: ( () => {
for (let i = 0; i < indFiles.length; i++) {
arr.push(i);
}
return arr;
})()
};
for (let i = 0; i < indFiles.length; i++) {
let doc = indFiles[i];
let splittedTitle = doc.title.split(" ");
this.checkIndex(splittedTitle, fileContents.name, doc, i);
let splittedText = doc.text.split(" ");
this.checkIndex(splittedText, fileContents.name, doc, i);
}
return check;
}
}
/**
* method return index of files in container object
*
* @param{string} name
*/
getIndex (name) {
if (name && typeof name === "string") {
return this.container[name];
} else {
return this.container;
}
}
/**
* takes terms of array and fetch result of each token.
*
* @param{array} termsArray
* @param{object} name
* @param{object} searchResults
*
*/
searchFeedback (termsArray ,name) {
const searchResults = {};
termsArray.forEach((i ,j) =>{
if (name.hasOwnProperty(i)){
searchResults[termsArray[j]] = name[i];
}
else {
alert("Sorry , but nothing matched your search.");
}
});
return searchResults;
}
/**
* looks for search term in file return indices
*
*/
searchIndex (currFile ,...searchTerm) {
const searchResults = {};
let termsArray = [];
if (typeof(searchTerm) === "string") {
termsArray = this.sanitizeInput(searchTerm);
}
else {
termsArray = searchTerm;
}
if (!currFile) {
for (let i in this.container) {
searchResults[i] = this.searchFeedback(termsArray , this.container[i]);
}
}
else {
try {
let file = this.container[currFile];
searchResults[file] = this.searchFeedback(termsArray , file);
}
catch(e) {
return null;
}
}
return searchResults;
}
};
|
JavaScript
| 0 |
@@ -79,32 +79,59 @@
* C
-reates Index constructor
+onstructor initializes container to an empty object
.%0A
@@ -151,16 +151,17 @@
ructor()
+
%7B%0A th
@@ -290,16 +290,17 @@
if (
+!
fileCont
@@ -309,30 +309,16 @@
ts.files
- === undefined
) %7B%0A
@@ -1689,16 +1689,20 @@
let the
+word
= this.
@@ -1732,16 +1732,17 @@
if (
+!
this.con
@@ -1761,23 +1761,13 @@
%5Bthe
-%5D === undefined
+word%5D
) %7B
@@ -1802,16 +1802,20 @@
ile%5D%5Bthe
+word
%5D = %7B%7D;
@@ -1841,32 +1841,36 @@
tainer%5Bfile%5D%5Bthe
+word
%5D%5Bid%5D = %7B%0A
@@ -1959,16 +1959,20 @@
ile%5D%5Bthe
+word
%5D%5Bid%5D =
@@ -2235,32 +2235,97 @@
pty%22) %7B %0A
+alert(%22It looks like you uploaded an empty JSON file.%22);%0A //
return check;%0A
@@ -2427,24 +2427,46 @@
format.%22);%0A
+ //return check;%0A
%7D%0A el
@@ -3747,24 +3747,53 @@
= name%5Bi%5D;%0A
+ console.log(name%5Bi%5D)%0A
%7D%0A
|
8711f7fe6000fe69a095301e9576d86935b36337
|
Update map defaults
|
public/src/js/map/options.js
|
public/src/js/map/options.js
|
/**
* public/src/js/map/options.js - delish
*
* Licensed under MIT license.
* Copyright (C) 2017 Karim Alibhai.
*/
export default {
/**
* Default zoom of 16 allows user to see streets.
*/
zoom: 17,
/**
* Just a dummy center. This will be updated to a geolocation.
*/
center: { lat: 45.4286821, lng: -75.6898986 },
/**
* See styles file for info on styles.
*/
styles: require('./styles'),
/**
* Gets rid of the UI provided by Google Maps, with
* the exception of their terms of use and logo.
*/
disableDefaultUI: true,
/**
* We disable default keyboard shortcuts so all keyboard
* shortcuts can be handled by the application.
*/
keyboardShortcuts: false,
/**
* The zoom control is a nice part of the UI, it helps
* users control the zoom in more ways than just by using
* their mouse & scroll.
*/
zoomControl: true
}
|
JavaScript
| 0 |
@@ -205,17 +205,17 @@
zoom: 1
-7
+8
,%0A%0A /**
@@ -224,206 +224,360 @@
*
-Just a dummy center. This will be updated to a geolocation.%0A */%0A center: %7B lat: 45.4286821, lng: -75.6898986 %7D,%0A%0A /**%0A * See styles file for info on styles.%0A */%0A styles: require('./styles')
+Further than 14 shows more than just the current%0A * city typically, so it's useless to the application.%0A */%0A minZoom: 14,%0A%0A /**%0A * See styles file for info on styles.%0A */%0A styles: require('./styles/hybrid'),%0A%0A /**%0A * The combination of these two properties allows%0A * a much more interesting view.%0A */%0A mapTypeId: 'hybrid',%0A tilt: 45
,%0A%0A
@@ -737,133 +737,62 @@
We
-disable default keyboard shortcuts so all keyboard%0A * shortcuts can be handled by the application.%0A */%0A keyboardShortcut
+want custom windows for markers.%0A */%0A clickableIcon
s: f
|
828aa722737fa7494dbd6a3bf5931a2f2a77c641
|
Fix regression, pause when adding to queue (#789)
|
lib/launch-video.js
|
lib/launch-video.js
|
const tabs = require('sdk/tabs');
const qs = require('sdk/querystring');
const prefs = require('sdk/simple-prefs').prefs;
const store = require('sdk/simple-storage').storage;
const getVideoId = require('get-video-id');
const isAudio = require('./is-audio');
const windowUtils = require('./window-utils');
const getRandomId = require('./get-random-id');
const youtubeHelpers = require('./youtube-helpers');
const sendMetricsData = require('./send-metrics-data');
const getLocaleStrings = require('./get-locale-strings');
module.exports = launchVideo;
// Pass in a video URL as opts.src or pass in a video URL lookup function as opts.getUrlFn
function launchVideo(opts) {
// UpdateWindow might create a new panel, so do the remaining launch work
// asynchronously.
windowUtils.updateWindow();
windowUtils.whenReady(() => {
const getUrlFn = opts.getUrlFn;
const action = opts.action;
delete opts.getUrlFn;
delete opts.action;
windowUtils.show();
// send some initial data to open the loading view
// before we fetch the media source
windowUtils.send('set-video', opts = Object.assign({
id: getRandomId(),
width: prefs.width,
height: prefs.height,
videoId: getVideoId(opts.url) ? getVideoId(opts.url).id : '',
strings: getLocaleStrings(opts.domain, (isAudio(opts.url))),
tabId: tabs.activeTab.id,
launchUrl: opts.url,
currentTime: 0,
playing: action === 'play',
keyShortcutsEnabled: prefs['keyShortcutsEnabled'],
confirm: false,
confirmContent: '{}'
}, opts));
// YouTube playlist handling
if (opts.domain === 'youtube.com' && !!~opts.url.indexOf('list')) {
if (!!~opts.url.indexOf('watch?v')) {
const parsed = qs.parse(opts.url.substr(opts.url.indexOf('?') + 1));
youtubeHelpers.getPlaylistMeta({
videoId: parsed.v,
playlistId: parsed.list,
}, (meta) => {
opts.confirmContent = meta;
opts.confirmContent.action = action;
opts.confirmContent = JSON.stringify(opts.confirmContent);
sendMetricsData({
object: 'playlist',
method: `launch:video:${action}`,
domain: opts.domain
});
windowUtils.send('set-video', Object.assign(opts, {
confirm: true,
error: false,
queue: JSON.stringify(store.queue),
history: JSON.stringify(store.history)
}));
});
} else {
// only playlist handling
const parsed = qs.parse(opts.url.substr(opts.url.indexOf('?') + 1));
youtubeHelpers.getPlaylist({playlistId: parsed.list}, playlist => {
if (action === 'play') {
store.queue = playlist.concat(store.queue);
} else store.queue = store.queue.concat(playlist);
const response = {
trackAdded: (action === 'add-to-queue') && (store.queue.length > 1),
error: false,
queue: JSON.stringify(store.queue),
history: JSON.stringify(store.history)
};
sendMetricsData({
object: 'playlist',
method: `launch:${action}`,
domain: opts.domain
});
if (action === 'play') response.playing = true;
windowUtils.send('set-video', response);
});
}
} else {
// fetch the media source and set it
getUrlFn(opts, function(item) {
if (item.err) console.error('LaunchVideo failed to get the streamUrl: ', item.err); // eslint-disable-line no-console
if (isAudio(item.url)) item.player = 'audio';
if (action === 'play') store.queue.unshift(item);
else store.queue.push(item);
const videoOptions = {
trackAdded: (action === 'add-to-queue') && (store.queue.length > 1),
error: item.err ? item.err : false,
queue: JSON.stringify(store.queue),
history: JSON.stringify(store.history)
};
if (action === 'play') videoOptions.playing = true;
windowUtils.send('set-video', videoOptions);
});
}
});
}
|
JavaScript
| 0 |
@@ -941,24 +941,72 @@
ts.action;%0A%0A
+ if (action === 'play') opts.action = true;%0A%0A
windowUt
@@ -1468,42 +1468,8 @@
0,%0A
- playing: action === 'play',%0A
|
def2f75df94a07481c0b6573e21db6103692606f
|
fix printing for arrays
|
lib/modules/tree.js
|
lib/modules/tree.js
|
utils = require('../utils');
//see http://en.wikipedia.org/wiki/Box-drawing_characters
exports.plugin = function(cli)
{
//┌──
//├──
//└──
var branch = utils.repeat('─',1),
tabs = utils.repeat(' ',branch.length+2);
cli.drawTree = cli.tree = function(tree, ops, tab)
{
if(!ops) ops = {};
if(!tab) tab = '';
var n = utils.objectSize(tree),
i = 0,
printedBreak = false;
for(var index in tree)
{
var childrenOrValue = tree[index],
toc = typeof childrenOrValue,
//tol = typeof labelOrIndex,
edge = i < n-1 ? '├' : '└';
console.log('%s%s%s %s', tab, edge, branch, toc == 'string' ? index + ': ' + childrenOrValue : index);
if(toc == 'object')
{
printedBreak = cli.drawTree(childrenOrValue, ops, n > 1 && i < n-1 ? tab + '|' + tabs.substr(1) : tab + tabs);
}
/*else
if(toc == 'string' || toc == 'number')
{
}*/
i++;
}
//add extra breaks for folders - a little more readable
if(!printedBreak)
{
console.log('%s',tab);
printedBreak = true;
}
return printedBreak;
}
}
|
JavaScript
| 0.000002 |
@@ -807,13 +807,11 @@
%0A%09%09%09
-//
to
-l
+i
= t
@@ -820,16 +820,9 @@
eof
-labelOrI
+i
ndex
@@ -857,24 +857,219 @@
'%E2%94%94';
+ %0A%09%09%09 %0A%09%09%09 %0A%09%09%09var value = !isNaN(Number(index)) ? childrenOrValue : index + ': ' + childrenOrValue; %0A%09%09%09
%0A%09%09%09
@@ -1262,39 +1262,13 @@
' ?
-index + ': ' + childrenOrV
+v
alue
-
: in
|
8e1d49acef69b1130d7d438c488599bda055ea51
|
Support custom loggers
|
lib/oauth2server.js
|
lib/oauth2server.js
|
/**
* Copyright 2013-present NightWorld.
*
* 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.
*/
var error = require('./error'),
AuthCodeGrant = require('./authCodeGrant'),
Authorise = require('./authorise'),
Grant = require('./grant');
module.exports = OAuth2Server;
/**
* Constructor
*
* @param {Object} config Configuration object
*/
function OAuth2Server (config) {
if (!(this instanceof OAuth2Server)) return new OAuth2Server(config);
config = config || {};
if (!config.model) throw new Error('No model supplied to OAuth2Server');
this.model = config.model;
this.grants = config.grants || [];
this.debug = config.debug || false;
this.passthroughErrors = config.passthroughErrors;
this.continueAfterResponse = config.continueAfterResponse;
this.accessTokenLifetime = config.accessTokenLifetime !== undefined ?
config.accessTokenLifetime : 3600;
this.refreshTokenLifetime = config.refreshTokenLifetime !== undefined ?
config.refreshTokenLifetime : 1209600;
this.authCodeLifetime = config.authCodeLifetime || 30;
this.regex = {
clientId: config.clientIdRegex || /^[a-z0-9-_]{3,40}$/i,
grantType: new RegExp('^(' + this.grants.join('|') + ')$', 'i')
};
}
/**
* Authorisation Middleware
*
* Returns middleware that will authorise the request using oauth,
* if successful it will allow the request to proceed to the next handler
*
* @return {Function} middleware
*/
OAuth2Server.prototype.authorise = function () {
var self = this;
return function (req, res, next) {
new Authorise(self, req, next);
};
};
/**
* Grant Middleware
*
* Returns middleware that will grant tokens to valid requests.
* This would normally be mounted at '/oauth/token' e.g.
*
* `app.all('/oauth/token', oauth.grant());`
*
* @return {Function} middleware
*/
OAuth2Server.prototype.grant = function () {
var self = this;
return function (req, res, next) {
new Grant(self, req, res, next);
};
};
/**
* Code Auth Grant Middleware
*
* @param {Function} check Function will be called with req to check if the
* user has authorised the request.
* @return {Function} middleware
*/
OAuth2Server.prototype.authCodeGrant = function (check) {
var self = this;
return function (req, res, next) {
new AuthCodeGrant(self, req, res, next, check);
};
};
/**
* OAuth Error Middleware
*
* Returns middleware that will catch OAuth errors and ensure an OAuth
* complaint response
*
* @return {Function} middleware
*/
OAuth2Server.prototype.errorHandler = function () {
var self = this;
return function (err, req, res, next) {
if (!(err instanceof error) || self.passthroughErrors) return next(err);
if (self.debug) console.log(err.stack || err);
delete err.stack;
if (err.headers) res.set(err.headers);
delete err.headers;
res.send(err.code, err);
};
};
/**
* Lockdown
*
* When using the lockdown patter, this function should be called after
* all routes have been declared.
* It will search through each route and if it has not been explitly bypassed
* (by passing oauth.bypass) then authorise will be inserted.
* If oauth.grant has been passed it will replace it with the proper grant
* middleware
* NOTE: When using this method, you must PASS the method not CALL the method,
* e.g.:
*
* `
* app.all('/oauth/token', app.oauth.grant);
*
* app.get('/secrets', function (req, res) {
* res.send('secrets');
* });
*
* app.get('/public', app.oauth.bypass, function (req, res) {
* res.send('publci');
* });
*
* app.oauth.lockdown(app);
* `
*
* @param {Object} app Express app
*/
OAuth2Server.prototype.lockdown = function (app) {
var self = this;
var lockdown = function (route) {
// Check if it's a grant route
var pos = route.callbacks.indexOf(self.grant);
if (pos !== -1) {
route.callbacks[pos] = self.grant();
return;
}
// Check it's not been explitly bypassed
pos = route.callbacks.indexOf(self.bypass);
if (pos === -1) {
route.callbacks.unshift(self.authorise());
} else {
route.callbacks.splice(pos, 1);
}
};
for (var method in app.routes) {
app.routes[method].forEach(lockdown);
}
};
/**
* Bypass
*
* This is used as placeholder for when using the lockdown pattern
*
* @return {Function} noop
*/
OAuth2Server.prototype.bypass = function () {};
|
JavaScript
| 0 |
@@ -1160,13 +1160,101 @@
%7C%7C f
-alse;
+unction () %7B%7D;%0A if (typeof(this.debug) !== 'function') %7B%0A this.debug = console.log;%0A %7D
%0A t
@@ -3312,20 +3312,16 @@
);%0A%0A
-if (
self.deb
@@ -3326,21 +3326,8 @@
ebug
-) console.log
(err
|
e689a7dac7c54d9d0773a4c2ca7cab4fc4882b99
|
Add trailing new line.
|
lib/packet-queue.js
|
lib/packet-queue.js
|
var setInterval = require('timers').setInterval;
var clearInterval = require('timers').clearInterval;
var Buffer = require('buffer').Buffer;
/*
The MIT License (MIT)
Copyright (c) 2014 Voxer IP LLC. All rights reserved.
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.
*/
module.exports = PacketQueue;
/// Coalesce metrics packets.
///
/// send(buffer, offset, length)
/// options - (optional)
/// * block - Integer, maximum block size
/// * flush - Integer, millisecond flush interval
///
function PacketQueue(send, options) {
if (!(this instanceof PacketQueue)) {
return new PacketQueue(send, options);
}
options = options || {};
this._send = send;
this._blockSize = options.block || 1440;
this._queue = null;
this._writePos = null;
this._reset();
// Don't let stuff queue forever.
var self = this;
this._interval = setInterval(function() {
if (self._queue.length) {
self._sendPacket();
}
}, options.flush || 1000);
this._interval.unref();
}
PacketQueue.prototype.destroy = function() {
clearInterval(this._interval);
}
PacketQueue.prototype._reset = function() {
this._queue = [];
this._writePos = 0;
}
PacketQueue.prototype.write = function(str) {
if (this._writePos + str.length >= this._blockSize) {
this._sendPacket();
}
this._queue.push(str);
this._writePos += str.length + 1;
}
PacketQueue.prototype._sendPacket = function() {
var buf = new Buffer(this._queue.join('\n'));
this._send(buf, 0, buf.length);
this._reset();
}
|
JavaScript
| 0 |
@@ -2487,16 +2487,23 @@
in('%5Cn')
+ + '%5Cn'
);%0A t
|
7db23a48e2a4153fa40d5dcdd28121aa4772958d
|
use destructuring for the constructor params
|
source/BindInput.js
|
source/BindInput.js
|
import $ from 'jquery';
import logger from './helpers/logger';
/*
* plugin constructor
*/
export default function BindInput( params ) {
var element = params.element,
options = params.options || {},
loggerObj = params.loggerObj || logger();
if ( typeof element === 'undefined' ) {
return;
}
this.element$ = $(element);
this.options = options;
this.loggerObj = loggerObj;
this.init();
}
/*
* plugin prototype
* init
*/
BindInput.prototype.init = function () {
/*
* receiver field is mandatory
*/
if ( ! this.options.receiver ) {
this.loggerObj.log('You must bind an input to some other receiver in options');
return false;
}
this
.setReceiver()
.setListeners();
return this;
};
/*
* setting receiver
*/
BindInput.prototype.setReceiver = function() {
this.receiver$ = this.options.receiver instanceof $ ?
this.options.receiver :
$(this.options.receiver);
return this;
};
/*
* setting field listeners
*/
BindInput.prototype.setListeners = function() {
$(document).ready( $.proxy(this.matchFields, this) );
/*
* and for every change
*/
this.element$.on( 'change', $.proxy(this.matchFields, this) );
};
/**
*
*/
BindInput.prototype.matchFields = function() {
if ( ! this.receiver$ ) {
return this;
}
/*
* set the same option on receiver
*/
var value = this.element$.val();
this.receiver$.val( value );
if ( this.element$.val() !== this.receiver$.val() ) {
// fallback to text if option not found
let receiverOption$ = this.receiver$.find('option').filter(
function findCurrentOption() {
return $(this).text() === value;
}
);
receiverOption$.prop('selected', true);
}
return this;
};
|
JavaScript
| 0.000001 |
@@ -149,81 +149,26 @@
var
-element = params.element,%0A options = params.options %7C%7C %7B%7D,%0A
+%7Belement, options,
log
@@ -173,16 +173,17 @@
oggerObj
+%7D
= param
@@ -187,30 +187,8 @@
rams
-.loggerObj %7C%7C logger()
;%0A%0A
@@ -250,24 +250,93 @@
rn; %0A %7D
+%0A%0A options = options %7C%7C %7B%7D;%0A loggerObj = loggerObj %7C%7C logger();
%0A %0A th
|
c895d6b3077a446e06c607d9ae2b081bf05dbe7d
|
Set a plain text version too on cut/copy
|
source/Clipboard.js
|
source/Clipboard.js
|
/*jshint strict:false, undef:false, unused:false */
var onCut = function ( event ) {
var clipboardData = event.clipboardData;
var range = this.getSelection();
var node = this.createElement( 'div' );
var body = this._body;
var self = this;
// Save undo checkpoint
this.saveUndoState( range );
// Edge only seems to support setting plain text as of 2016-03-11.
if ( !isEdge && clipboardData ) {
moveRangeBoundariesUpTree( range, body );
node.appendChild( deleteContentsOfRange( range, body ) );
clipboardData.setData( 'text/html', node.innerHTML );
event.preventDefault();
} else {
setTimeout( function () {
try {
// If all content removed, ensure div at start of body.
self._ensureBottomLine();
} catch ( error ) {
self.didError( error );
}
}, 0 );
}
this.setSelection( range );
};
var onCopy = function ( event ) {
var clipboardData = event.clipboardData;
var range = this.getSelection();
var node = this.createElement( 'div' );
// Edge only seems to support setting plain text as of 2016-03-11.
if ( !isEdge && clipboardData ) {
node.appendChild( range.cloneContents() );
clipboardData.setData( 'text/html', node.innerHTML );
event.preventDefault();
}
};
var onPaste = function ( event ) {
var clipboardData = event.clipboardData,
items = clipboardData && clipboardData.items,
fireDrop = false,
hasImage = false,
plainItem = null,
self = this,
l, item, type, types, data;
// Current HTML5 Clipboard interface
// ---------------------------------
// https://html.spec.whatwg.org/multipage/interaction.html
// Edge only provides access to plain text as of 2016-03-11.
if ( !isEdge && items ) {
event.preventDefault();
l = items.length;
while ( l-- ) {
item = items[l];
type = item.type;
if ( type === 'text/html' ) {
/*jshint loopfunc: true */
item.getAsString( function ( html ) {
self.insertHTML( html, true );
});
/*jshint loopfunc: false */
return;
}
if ( type === 'text/plain' ) {
plainItem = item;
}
if ( /^image\/.*/.test( type ) ) {
hasImage = true;
}
}
// Treat image paste as a drop of an image file.
if ( hasImage ) {
this.fireEvent( 'dragover', {
dataTransfer: clipboardData,
/*jshint loopfunc: true */
preventDefault: function () {
fireDrop = true;
}
/*jshint loopfunc: false */
});
if ( fireDrop ) {
this.fireEvent( 'drop', {
dataTransfer: clipboardData
});
}
} else if ( plainItem ) {
item.getAsString( function ( text ) {
self.insertPlainText( text, true );
});
}
return;
}
// Old interface
// -------------
// Safari (and indeed many other OS X apps) copies stuff as text/rtf
// rather than text/html; even from a webpage in Safari. The only way
// to get an HTML version is to fallback to letting the browser insert
// the content. Same for getting image data. *Sigh*.
//
// Firefox is even worse: it doesn't even let you know that there might be
// an RTF version on the clipboard, but it will also convert to HTML if you
// let the browser insert the content. I've filed
// https://bugzilla.mozilla.org/show_bug.cgi?id=1254028
types = clipboardData && clipboardData.types;
if ( !isEdge && types && (
indexOf.call( types, 'text/html' ) > -1 || (
!isGecko &&
indexOf.call( types, 'text/plain' ) > -1 &&
indexOf.call( types, 'text/rtf' ) < 0 )
)) {
event.preventDefault();
// Abiword on Linux copies a plain text and html version, but the HTML
// version is the empty string! So always try to get HTML, but if none,
// insert plain text instead.
if (( data = clipboardData.getData( 'text/html' ) )) {
this.insertHTML( data, true );
} else if (( data = clipboardData.getData( 'text/plain' ) )) {
this.insertPlainText( data, true );
}
return;
}
// No interface. Includes all versions of IE :(
// --------------------------------------------
this._awaitingPaste = true;
var body = this._body,
range = this.getSelection(),
startContainer = range.startContainer,
startOffset = range.startOffset,
endContainer = range.endContainer,
endOffset = range.endOffset,
startBlock = getStartBlockOfRange( range );
// We need to position the pasteArea in the visible portion of the screen
// to stop the browser auto-scrolling.
var pasteArea = this.createElement( 'DIV', {
style: 'position: absolute; overflow: hidden; top:' +
( body.scrollTop +
( startBlock ? startBlock.getBoundingClientRect().top : 0 ) ) +
'px; right: 150%; width: 1px; height: 1px;'
});
body.appendChild( pasteArea );
range.selectNodeContents( pasteArea );
this.setSelection( range );
// A setTimeout of 0 means this is added to the back of the
// single javascript thread, so it will be executed after the
// paste event.
setTimeout( function () {
try {
// IE sometimes fires the beforepaste event twice; make sure it is
// not run again before our after paste function is called.
self._awaitingPaste = false;
// Get the pasted content and clean
var html = '',
next = pasteArea,
first, range;
// #88: Chrome can apparently split the paste area if certain
// content is inserted; gather them all up.
while ( pasteArea = next ) {
next = pasteArea.nextSibling;
detach( pasteArea );
// Safari and IE like putting extra divs around things.
first = pasteArea.firstChild;
if ( first && first === pasteArea.lastChild &&
first.nodeName === 'DIV' ) {
pasteArea = first;
}
html += pasteArea.innerHTML;
}
range = self._createRange(
startContainer, startOffset, endContainer, endOffset );
self.setSelection( range );
if ( html ) {
self.insertHTML( html, true );
}
} catch ( error ) {
self.didError( error );
}
}, 0 );
};
|
JavaScript
| 0 |
@@ -595,32 +595,111 @@
de.innerHTML );%0A
+ clipboard.setData( 'text/plain', node.innerText %7C%7C node.textContent );%0A
event.pr
@@ -1413,32 +1413,111 @@
de.innerHTML );%0A
+ clipboard.setData( 'text/plain', node.innerText %7C%7C node.textContent );%0A
event.pr
|
6202b75688016345389dddb1cd49d201c5a7d7bc
|
Trim UTF-8 BOM marker
|
lib/previous-map.js
|
lib/previous-map.js
|
var mozilla = require('source-map');
var Base64 = require('js-base64').Base64;
var path = require('path');
var fs = require('fs');
// Detect previous map
class PreviousMap {
constructor(root, opts, id) {
this.file = opts.from || id;
this.loadAnnotation(root);
var inlinePrefix = '# sourceMappingURL=data:';
this.inline = this.startWith(this.annotation, inlinePrefix);
var text = this.loadMap(opts.map ? opts.map.prev : undefined);
if ( text ) this.text = text;
}
// Return SourceMapConsumer object to read map
consumer() {
if ( !this.consumerCache ) {
this.consumerCache = new mozilla.SourceMapConsumer(this.text);
}
return this.consumerCache;
}
// Is map has sources content
withContent() {
return !!(this.consumer().sourcesContent &&
this.consumer().sourcesContent.length > 0);
}
// Is `string` is starting with `start`
startWith(string, start) {
if ( !string ) return false;
return string.substr(0, start.length) == start;
}
// Load for annotation comment from previous compilation step
loadAnnotation(root) {
var last = root.last;
if ( !last ) return;
if ( last.type != 'comment' ) return;
if ( this.startWith(last.text, '# sourceMappingURL=') ) {
this.annotation = last.text;
}
}
// Encode different type of inline
decodeInline(text) {
var uri = '# sourceMappingURL=data:application/json,';
var base64 = '# sourceMappingURL=data:application/json;base64,';
if ( this.startWith(text, uri) ) {
return decodeURIComponent( text.substr(uri.length) );
} else if ( this.startWith(text, base64) ) {
return Base64.decode( text.substr(base64.length) );
} else {
var encoding = text.match(/ata:application\/json;([^,]+),/)[1];
throw new Error('Unsupported source map encoding ' + encoding);
}
}
// Load previous map
loadMap(prev) {
if ( prev === false ) return;
if ( prev ) {
if ( typeof(prev) == 'string' ) {
return prev;
} else if ( prev instanceof mozilla.SourceMapConsumer ) {
return mozilla.SourceMapGenerator
.fromSourceMap(prev).toString();
} else if ( prev instanceof mozilla.SourceMapGenerator ) {
return prev.toString();
} else if ( typeof(prev) == 'object' && prev.mappings ) {
return JSON.stringify(prev);
} else {
throw new Error('Unsupported previous source map format: ' +
prev.toString());
}
} else if ( this.inline ) {
return this.decodeInline(this.annotation);
} else if ( this.annotation ) {
var map = this.annotation.replace('# sourceMappingURL=', '');
if ( this.file ) map = path.join(path.dirname(this.file), map);
this.root = path.dirname(map);
if ( fs.existsSync && fs.existsSync(map) ) {
return fs.readFileSync(map, 'utf-8').toString();
}
}
}
}
module.exports = PreviousMap;
|
JavaScript
| 0.000005 |
@@ -3217,32 +3217,39 @@
f-8').toString()
+.trim()
;%0A %7D%0A
|
a71a009c5ee02fda21af420cb1bec3e55711c80a
|
fix bug with parsing nested markdown blocks
|
source/jsx_block.js
|
source/jsx_block.js
|
import { JSX_OPEN_TAG_PARSER, JSX_CLOSE_TAG_PARSER, JSX_SELF_CLOSE_TAG_PARSER } from './jsxParser'
import transformJSX from './transformJSX'
function parseMarkdownContent(state, startIndent, startLine, maxLine) {
var pos, max, lineText, blkIndent, indent
var nextLine = startLine
for (; nextLine < maxLine; nextLine++) {
indent = state.sCount[nextLine]
pos = state.bMarks[nextLine] + state.tShift[nextLine];
max = state.eMarks[nextLine];
lineText = state.src.slice(pos, max);
if (lineText === '') continue;
if (indent < startIndent) return;
if (blkIndent === undefined) {
blkIndent = indent
}
else if (lineText.slice(0, '</markdown>'.length) === '</markdown>' && state.sCount[nextLine] === startIndent) {
return {
key: '$$mdx_block_'+Math.random().toString(36).substring(7),
contentStart: startLine,
contentEnd: nextLine,
blkIndent: blkIndent || 0,
}
}
else if (indent < blkIndent) {
return
}
}
}
export default function jsx_block(state, startLine, endLine, silent) {
var i, nextLine, token, lineText, result, type,
pos = state.bMarks[startLine] + state.tShift[startLine],
max = state.eMarks[startLine];
if (state.src.charCodeAt(pos) !== 0x3C/* < */) { return false; }
lineText = state.src.slice(pos, max);
result = JSX_OPEN_TAG_PARSER.parse(lineText.trim());
if (!result.status) { return false; }
type = result.value.value
if (silent) {
// true if this sequence can be a terminator, false otherwise
return true;
}
nextLine = startLine + 1;
// If we are here - we detected HTML block.
// Let's roll down till block end.
const isSingleLine =
JSX_SELF_CLOSE_TAG_PARSER.parse(lineText).status ||
JSX_CLOSE_TAG_PARSER.parse(lineText.slice(1)).status
let content
let js
let cumulative = lineText
let markdownContents = []
if (!isSingleLine) {
for (; nextLine < endLine; nextLine++) {
if (state.sCount[nextLine] < state.blkIndent) { break; }
pos = state.bMarks[nextLine] + state.tShift[nextLine];
max = state.eMarks[nextLine];
lineText = state.src.slice(pos, max);
if (lineText === '<markdown>') {
const markdownContent = parseMarkdownContent(state, state.sCount[nextLine], nextLine + 1, endLine)
if (markdownContent) {
markdownContents.push(markdownContent)
nextLine = markdownContent.contentEnd
continue
}
}
cumulative += lineText
const closeResult = JSX_CLOSE_TAG_PARSER.parse(lineText)
const selfCloseResult = JSX_SELF_CLOSE_TAG_PARSER.parse(cumulative)
if (selfCloseResult || closeResult.value === type) {
let line = startLine;
const codes = []
for (let { key, contentStart, contentEnd, blkIndent } of markdownContents) {
codes.push(
state.getLines(line, contentStart - 1, state.blkIndent, true).trim(),
`{${key}}`
)
line = contentEnd + 1
}
codes.push(state.getLines(line, nextLine + 1, state.blkIndent, true).trim())
const code = codes.join('\n')
js = transformJSX(code)
if (js) {
nextLine++
break
}
}
}
}
if (!js) {
markdownContents = []
content = state.getLines(startLine, nextLine, state.blkIndent, true)
js = transformJSX(content)
}
if (!js) {
return false
}
state.line = nextLine;
if (!silent) {
if (markdownContents.length === 0) {
token = state.push('jsx', '', 0);
token.map = [ startLine, nextLine ];
token.content = js;
}
else {
const originalBlkIndent = state.blkIndent
let line = 0
const jsLines = js.split('\n')
let first = 1
for (let { key, contentStart, contentEnd, blkIndent } of markdownContents) {
let startLine = line
while (jsLines[line].indexOf(key) === -1) {
line++
}
if (startLine !== line) {
token = state.push('jsx', '', first);
token.content = jsLines.slice(startLine, line).join('\n').replace(/,$/, '')
}
first = 0
line++
token = state.push('jsx', '', 1);
token.content = 'wrapper({}'
state.blkIndent = blkIndent
state.md.block.tokenize(state, contentStart, contentEnd);
token = state.push('jsx', '', -1);
token.content = ')'
}
state.originalBlkIndent = originalBlkIndent
token = state.push('jsx', '', first - 1);
token.content = jsLines.slice(line).join('\n')
}
}
return true;
};
|
JavaScript
| 0 |
@@ -4308,16 +4308,58 @@
er(%7B%7D'%0A%0A
+ const oldLineMax = state.lineMax%0A%0A
@@ -4382,24 +4382,59 @@
= blkIndent%0A
+ state.lineMax = contentEnd%0A
stat
@@ -4484,24 +4484,60 @@
ntentEnd);%0A%0A
+ state.lineMax = oldLineMax%0A%0A
toke
|
11be28cc4c35a9eee1492d6d6e3447cc83933e83
|
fix bug with renderbuffer initialization from radius
|
lib/renderbuffer.js
|
lib/renderbuffer.js
|
var check = require('./util/check')
var values = require('./util/values')
var GL_RENDERBUFFER = 0x8D41
var GL_RGBA4 = 0x8056
var GL_RGB5_A1 = 0x8057
var GL_RGB565 = 0x8D62
var GL_DEPTH_COMPONENT16 = 0x81A5
var GL_STENCIL_INDEX8 = 0x8D48
var GL_DEPTH_STENCIL = 0x84F9
var GL_SRGB8_ALPHA8_EXT = 0x8C43
var GL_RGBA32F_EXT = 0x8814
var GL_RGBA16F_EXT = 0x881A
var GL_RGB16F_EXT = 0x881B
module.exports = function (gl, extensions, limits, stats) {
var formatTypes = {
'rgba4': GL_RGBA4,
'rgb565': GL_RGB565,
'rgb5 a1': GL_RGB5_A1,
'depth': GL_DEPTH_COMPONENT16,
'stencil': GL_STENCIL_INDEX8,
'depth stencil': GL_DEPTH_STENCIL
}
if (extensions.ext_srgb) {
formatTypes['srgba'] = GL_SRGB8_ALPHA8_EXT
}
if (extensions.ext_color_buffer_half_float) {
formatTypes['rgba16f'] = GL_RGBA16F_EXT
formatTypes['rgb16f'] = GL_RGB16F_EXT
}
if (extensions.webgl_color_buffer_float) {
formatTypes['rgba32f'] = GL_RGBA32F_EXT
}
var renderbufferCount = 0
var renderbufferSet = {}
function REGLRenderbuffer (renderbuffer) {
this.id = renderbufferCount++
this.refCount = 1
this.renderbuffer = renderbuffer
this.format = GL_RGBA4
this.width = 0
this.height = 0
}
REGLRenderbuffer.prototype.decRef = function () {
if (--this.refCount === 0) {
destroy(this)
}
}
function destroy (rb) {
var handle = rb.renderbuffer
check(handle, 'must not double destroy renderbuffer')
gl.bindRenderbuffer(GL_RENDERBUFFER, null)
gl.deleteRenderbuffer(handle)
rb.renderbuffer = null
rb.refCount = 0
delete renderbufferSet[rb.id]
stats.renderbufferCount--
}
function createRenderbuffer (a, b) {
var renderbuffer = new REGLRenderbuffer(gl.createRenderbuffer())
renderbufferSet[renderbuffer.id] = renderbuffer
stats.renderbufferCount++
function reglRenderbuffer (a, b) {
var w = 0
var h = 0
var format = GL_RGBA4
if (typeof a === 'object' && a) {
var options = a
if ('shape' in options) {
var shape = options.shape
check(Array.isArray(shape) && shape.length >= 2,
'invalid renderbuffer shape')
w = shape[0] | 0
h = shape[1] | 0
} else {
if ('radius' in options) {
w = h = options.radius | 0
}
if ('width' in options) {
w = options.width | 0
}
if ('height' in options) {
h = options.height | 0
}
}
if ('format' in options) {
check.parameter(options.format, formatTypes,
'invalid renderbuffer format')
format = formatTypes[options.format]
}
} else if (typeof a === 'number') {
w = a | 0
if (typeof b === 'number') {
h = b | 0
} else {
w = h
}
} else if (!a) {
w = h = 1
} else {
check.raise('invalid arguments to renderbuffer constructor')
}
// check shape
check(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
if (w === renderbuffer.width &&
h === renderbuffer.height &&
format === renderbuffer.format) {
return
}
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
renderbuffer.format = format
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, format, w, h)
return reglRenderbuffer
}
reglRenderbuffer(a, b)
function resize (w_, h_) {
var w = w_ | 0
var h = (h_ | 0) || w
if (w === renderbuffer.width && h === renderbuffer.height) {
return
}
// check shape
check(
w > 0 && h > 0 &&
w <= limits.maxRenderbufferSize && h <= limits.maxRenderbufferSize,
'invalid renderbuffer size')
reglRenderbuffer.width = renderbuffer.width = w
reglRenderbuffer.height = renderbuffer.height = h
gl.bindRenderbuffer(GL_RENDERBUFFER, renderbuffer.renderbuffer)
gl.renderbufferStorage(GL_RENDERBUFFER, renderbuffer.format, w, h)
return reglRenderbuffer
}
reglRenderbuffer.resize = resize
reglRenderbuffer._reglType = 'renderbuffer'
reglRenderbuffer._renderbuffer = renderbuffer
reglRenderbuffer.destroy = function () {
renderbuffer.decRef()
}
return reglRenderbuffer
}
return {
create: createRenderbuffer,
clear: function () {
values(renderbufferSet).forEach(destroy)
}
}
}
|
JavaScript
| 0 |
@@ -2857,21 +2857,21 @@
-w = h
+h = w
%0A
@@ -3644,36 +3644,8 @@
%7D%0A%0A
- reglRenderbuffer(a, b)%0A%0A
@@ -4274,24 +4274,52 @@
ffer%0A %7D%0A%0A
+ reglRenderbuffer(a, b)%0A%0A
reglRend
|
a4f8f195fdc9f4e1a49c016a5ba9fe9dfa4d182a
|
Revert "Fixes getCandidatesFromMapping on windows"
|
lib/revvedfinder.js
|
lib/revvedfinder.js
|
'use strict';
var debug = require('debug')('revvedfinder');
var path = require('path');
var _ = require('lodash');
// Allow to find, on disk, the revved version of a furnished file
//
// +locator+ : this is either:
// - a hash mapping files with their revved versions
// - a function that will return a list of file matching a given pattern (for example grunt.file.expand)
//
var RevvedFinder = module.exports = function (locator) {
if (_.isFunction(locator)) {
debug('using function locator');
this.expandfn = locator;
} else {
debug('using file locator %s', locator);
this.mapping = locator;
}
};
var regexpQuote = function (str) {
return (str + '').replace(/([.?*+\^$\[\]\\(){}|\-])/g, '\\$1');
};
RevvedFinder.prototype.getCandidatesFromMapping = function(file, searchPaths) {
var dirname = path.dirname(file);
var candidates = [];
var self = this;
searchPaths.forEach(function(sp) {
var key = path.normalize(path.join(sp, file)).replace(/\\/g, '/');
debug('Looking at mapping for %s (from %s/%s)',key, sp, file);
if (self.mapping[key]) {
// We need to transform the actual file to a form that matches the one we received
// For example if we received file 'foo/images/test.png' with searchPaths == ['dist'],
// and found in mapping that 'dist/foo/images/test.png' has been renamed
// 'dist/foo/images/test.1234.png' by grunt-rev, then we need to return
// 'foo/images/test.1234.png'
var cfile = path.basename(self.mapping[key]);
candidates.push(dirname + '/' + cfile);
debug('Found a candidate: %s/%s',dirname, cfile);
}
});
return candidates;
}
;
RevvedFinder.prototype.getCandidatesFromFS = function(file, searchPaths) {
var extname = path.extname(file);
var basename = path.basename(file, extname);
var dirname = path.dirname(file);
var hex = '[0-9a-fA-F]+';
var regPrefix = '(' + hex + '\\.' + regexpQuote(basename) + ')';
var regSuffix = '('+ regexpQuote(basename) + '\\.' + hex + regexpQuote(extname) + ')';
var revvedRx = new RegExp(regPrefix + '|' + regSuffix);
var candidates = [];
var self = this;
searchPaths.forEach(function(sp) {
var searchString = path.join(sp, dirname, basename + '.*' + extname);
var prefixSearchString = path.join(sp, dirname, '*.' + basename + extname);
if (searchString.indexOf('#') === 0) {
// patterns starting with # are treated as comments by the glob implementation which returns undefined,
// which would cause an unhandled exception in self.expandfn below so the file is never written
return;
}
debug('Looking for %s and %s on disk', searchString, prefixSearchString);
var files = self.expandfn([searchString, prefixSearchString]);
debug('Found ', files);
// Keep only files that look like a revved file
var goodFiles = files.filter(function(f) { return f.match(revvedRx); });
// We must now remove the search path from the beginning, and add them to the
// list of candidates
goodFiles.forEach(function(gf) {
var goodFileName = path.basename(gf);
if (!file.match(/\//)) {
// We only get a file (i.e. no dirs), so let's send back
// what we found
debug('Adding %s to candidates', goodFileName);
candidates.push(goodFileName);
} else {
debug('Adding %s / %s to candidates', dirname, goodFileName);
candidates.push(dirname + '/' + goodFileName);
}
});
});
return(candidates);
};
// Finds out candidates for file in the furnished searchPaths.
// It should return an array of candidates that are in the same format as the
// furnished file.
// For example, when given file 'images/test.png', and searchPaths of ['dist']
// the returned array should be something like ['images/test.1234.png']
//
RevvedFinder.prototype.getRevvedCandidates = function(file, searchPaths) {
var candidates;
// Our strategy depends on what we get at creation time: either a mapping, and we "just"
// need to do look-up in the mapping, or an expand function and we need to find relevant files
// on the disk
// FIXME:
if (this.mapping) {
debug('Looking at mapping');
candidates = this.getCandidatesFromMapping(file, searchPaths);
} else {
debug('Looking on disk');
candidates = this.getCandidatesFromFS(file, searchPaths);
}
return candidates;
};
//
// Find a revved version of +ofile+ (i.e. a file which name is ending with +ofile+), relatively
// to the furnished +searchDirs+.
// Let's imagine you have the following directory structure:
// + build
// | |
// | +- css
// | |
// | + style.css
// + images
// |
// + pic.2123.png
//
// and that somehow style.css is referencing '../../images/pic.png'
// When called like that:
// revvedFinder.find('../../images/pic.png', 'build/css');
// the function must return
// '../../images/pic.2123.png'
//
// Note that +ofile+ should be a relative path to the looked for file
// (i.e. if it's an absolue path -- starting with / -- or an external one -- containing :// -- then
// the original file is returned)
//
// It returns an object with 2 attributes:
// name: which is the filename
// base: which is the directory from searchDirs where we found the file
//
RevvedFinder.prototype.find = function find(ofile, searchDirs) {
var file = ofile;
var searchPaths = searchDirs;
var absolute;
var prefix;
if (_.isString(searchDirs)) {
searchPaths = [searchDirs];
}
debug('Looking for revved version of %s in ', ofile, searchPaths);
//do not touch external files or the root
// FIXME: Should get only relative files
if (ofile.match(/:\/\//) || ofile === '') {
return ofile;
}
if (file[0] === '/') {
// We need to remember this is an absolute file, but transform it
// to a relative one
absolute = true;
file = file.replace(/^(\/+)/, function(match, header) { prefix = header; return '';});
}
var filepaths = this.getRevvedCandidates(file, searchPaths);
var filepath = filepaths[0];
debug('filepath is now ', filepath);
// not a file in temp, skip it
if (!filepath) {
return ofile;
}
// var filename = path.basename(filepath);
// handle the relative prefix (with always unix like path even on win32)
// if (dirname !== '.') {
// filename = [dirname, filename].join('/');
// }
if (absolute) {
filepath = prefix + filepath;
}
debug('Let\'s return %s', filepath);
return filepath;
};
|
JavaScript
| 0 |
@@ -976,28 +976,8 @@
le))
-.replace(/%5C%5C/g, '/')
;%0A
|
23cf7ca735e300c3d935e9e05cc7d6c095efa153
|
allow changing URL without creating history entries
|
lib/search/index.js
|
lib/search/index.js
|
'use strict';
var angular = require('camunda-bpm-sdk-js/vendor/angular');
var SearchFactory = [ '$location', '$rootScope', function($location, $rootScope) {
var silent = false;
$rootScope.$on('$routeUpdate', function(e, lastRoute) {
if (silent) {
silent = false;
} else {
$rootScope.$broadcast('$routeChanged', lastRoute);
}
});
$rootScope.$on('$routeChangeSuccess', function(e, lastRoute) {
silent = false;
});
var search = function() {
var args = Array.prototype.slice(arguments);
return $location.search.apply($location, arguments);
}
search.updateSilently = function(params) {
var oldPath = $location.absUrl();
angular.forEach(params, function(value, key) {
$location.search(key, value);
});
var newPath = $location.absUrl();
if (newPath != oldPath) {
silent = true;
}
};
return search;
}];
var searchModule = angular.module('camunda.common.search', []);
searchModule.factory('search', SearchFactory);
module.exports = searchModule;
|
JavaScript
| 0 |
@@ -664,16 +664,29 @@
n(params
+, replaceFlag
) %7B%0A
@@ -923,24 +923,86 @@
rue;%0A %7D
+%0A%0A if(replaceFlag) %7B%0A $location.replace();%0A %7D
%0A %7D;%0A%0A
|
b78364e299c63a443cd37f0d92fbab24bc3bd400
|
add key to h
|
h/index.js
|
h/index.js
|
var isArray = require("x-is-array")
var isString = require("x-is-string")
var VNode = require("../vtree/vnode.js")
var VText = require("../vtree/vtext.js")
var isVNode = require("../vtree/is-vnode")
var isVText = require("../vtree/is-vtext")
var isWidget = require("../vtree/is-widget")
var parseTag = require("./parse-tag")
module.exports = h
function h(tagName, properties, children) {
var tag, props, childNodes
if (!children) {
if (isChildren(properties)) {
children = properties
properties = undefined
}
}
tag = parseTag(tagName, properties)
if (!isString(tag)) {
props = tag.properties
tag = tag.tagName
} else {
props = properties
}
if (isArray(children)) {
var len = children.length
for (var i = 0; i < len; i++) {
var child = children[i]
if (isString(child)) {
children[i] = new VText(child)
}
}
childNodes = children
} else if (isString(children)) {
childNodes = [new VText(children)]
} else if (isChild(children)) {
childNodes = [children]
}
return new VNode(tag, props, childNodes)
}
function isChild(x) {
return isVNode(x) || isVText(x) || isWidget(x)
}
function isChildren(x) {
return isArray(x) || isString(x) || isChild(x)
}
|
JavaScript
| 0.000001 |
@@ -415,16 +415,21 @@
ildNodes
+, key
%0A%0A if
@@ -1166,24 +1166,115 @@
ren%5D%0A %7D%0A%0A
+ if (props && %22key%22 in props) %7B%0A key = props.key%0A delete props.key%0A %7D%0A%0A
return n
@@ -1304,16 +1304,21 @@
ildNodes
+, key
)%0A%7D%0A%0Afun
|
51c8fd535b936c81ec4a820887d5eb46ebf7379e
|
move some user.js stuff around
|
home/firefox/.mozilla/firefox/profile/user.js
|
home/firefox/.mozilla/firefox/profile/user.js
|
// temporary
// =========
// disable Hello, removing in FF49
user_pref('loop.enabled', false)
user_pref('loop.do_not_disturb', true)
// user interface
// ==============
// search
user_pref('browser.search.suggest.enabled', false)
user_pref('browser.urlbar.suggest.searches', false)
// "fixing" urls
user_pref('keyword.enabled', false) // don't submit mistyped URLs to Google
user_pref('browser.fixup.alternate.enabled', false) // http://example should not try http://example.com
user_pref('browser.urlbar.filter.javascript', true) // javascript: URLs are evil
// new tab page
user_pref('browser.newtab.preload', false)
user_pref('browser.newtabpage.enabled', false)
user_pref('browser.newtabpage.enhanced', false)
// disable about:home tips
user_pref('browser.aboutHomeSnippets.updateUrl', '')
// url bar
user_pref('browser.urlbar.trimURLs', false) // show me the full URL
// disable warnings
user_pref('browser.tabs.warnOnClose', false)
user_pref('browser.tabs.warnOnCloseOtherTabs', false)
user_pref('browser.tabs.warnOnOpen', false)
user_pref('browser.warnOnQuit', false)
user_pref('general.warnOnAboutConfig', false)
user_pref('network.warnOnAboutNetworking', false)
// disable some browser features
user_pref('reader.parse-on-load.enabled', false) // reader
user_pref('extensions.pocket.enabled', false) // Pocket
user_pref('pdfjs.disabled', false) // PDF reader
// okay, i've already seen these things
user_pref('browser.newtabpage.introShown', true)
// disable clipboard silliness Linux
user_pref('clipboard.autocopy', false)
user_pref('middlemouse.contentLoadURL', false)
user_pref('middlemouse.paste', false)
// html
// ====
// things to disable and enable
user_pref('beacon.enabled', false) // beacon API
user_pref('browser.send_pings.require_same_host', true) // probably redundant with below
user_pref('browser.send_pings', false) // <a ping>
user_pref('device.sensors.enabled', false) // navigator.sensor API
user_pref('dom.battery.enabled', false) // battery API
user_pref('dom.disable_beforeunload', false) // "are you sure you want to leave this page"
user_pref('dom.enable_performance', false) // navigation timing API
user_pref('dom.event.clipboardevents.enabled', false) // clipboard events API
user_pref('dom.gamepad.enabled', false) // gamepad API
user_pref('dom.indexedDB.enabled', false) // indexedDB
user_pref('dom.netinfo.enabled', false) // network info API
user_pref('dom.vr.cardboard.enabled', false) // VR + Cardboard
user_pref('dom.vr.enabled', false) // VR API
user_pref('dom.vr.oculus.enabled', false) // VR + Oculus
user_pref('dom.vr.oculus050.enabled', false) // VR + Oculus
user_pref('dom.webnotifications.enabled', false) // notifications
user_pref('geo.enabled', false) // geolocation API
user_pref('geo.wifi.uri', '') // geolocation API
user_pref('javascript.options.asmjs', false) // asm
user_pref('javascript.options.wasm', false) // WebAssembly
user_pref('media.getusermedia.screensharing.allowed_domains', '') // screen sharing
user_pref('media.getusermedia.screensharing.enabled', false) // screen sharing
user_pref('media.peerconnection.enabled', false) // webRTC
user_pref('media.webspeech.recognition.enable', false) // speech recognition
user_pref('network.manage-offline-status', false) // navigator.onLine
user_pref('webgl.disabled', true) // webGL
// remove transitions around fullscreen API
user_pref('full-screen-api.transition-duration.enter', '0 0')
user_pref('full-screen-api.transition-duration.leave', '0 0')
// set defaults for unspecified fonts, etc
user_pref('browser.display.background_color', '#f6f6f6')
// ask to activate Flash
user_pref('plugin.state.flash', 1)
// obliterate Java
user_pref('plugin.state.java', 0)
user_pref('network.jar.block-remote-files', true)
user_pref('network.jar.open-unsafe-types', false)
// privacy
// =======
// tracking protection
user_pref('privacy.trackingprotection.enabled', true)
user_pref('privacy.trackingprotection.pbmode.enabled', true)
user_pref('privacy.trackingprotection.introCount', false) // don't give me the intro
// disable "safe browsing" so that Google might not know everything i see
user_pref('browser.safebrowsing.enabled', false)
user_pref('browser.safebrowsing.downloads.enabled', false)
user_pref('browser.safebrowsing.malware.enabled', false)
// DNT header
user_pref('privacy.donottrackheader.enabled', true)
user_pref('privacy.donottrackheader.value', 1)
// not sure what this is exactly, but i am disabling it
user_pref('camera.control.face_detection.enabled', false)
// extensions
// ==========
// https everywhere
user_pref('extensions.https_everywhere._observatory.enabled', false)
user_pref('extensions.https_everywhere._observatory.popup_shown', true)
user_pref('extensions.https_everywhere.toolbar_hint_shown', true)
|
JavaScript
| 0 |
@@ -165,16 +165,279 @@
======%0A%0A
+// disable some browser features%0Auser_pref('general.smoothScroll', false) // smooth scrolling%0Auser_pref('reader.parse-on-load.enabled', false) // reader%0Auser_pref('extensions.pocket.enabled', false) // Pocket%0Auser_pref('pdfjs.disabled', false) // PDF reader%0A%0A
// searc
@@ -1444,209 +1444,8 @@
e)%0A%0A
-// disable some browser features%0Auser_pref('reader.parse-on-load.enabled', false) // reader%0Auser_pref('extensions.pocket.enabled', false) // Pocket%0Auser_pref('pdfjs.disabled', false) // PDF reader%0A%0A
// o
|
1d851a859ca3ebf6a40fb49388998275c57e4096
|
Stop Cucumber at the first error
|
cucumber.js
|
cucumber.js
|
module.exports = {
"default": "--compiler ls:livescript -r features --strict --snippet-syntax node_modules/cucumber-snippets-livescript"
}
|
JavaScript
| 0.000001 |
@@ -63,16 +63,28 @@
eatures
+--fail-fast
--strict
|
c07278740d92e5c3e9912b4a5cfee65cb76d5739
|
update Dropdown
|
src/Dropdown/Dropdown.js
|
src/Dropdown/Dropdown.js
|
/**
* @file Dropdown component
* @author liangxiaojun([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import {findDOMNode} from 'react-dom';
import classNames from 'classnames';
import RaisedButton from '../RaisedButton';
import Popup from '../Popup';
import Theme from '../Theme';
import Position from '../_statics/Position';
import Util from '../_vendors/Util';
import DropdownCalculation from '../_vendors/DropdownCalculation';
class Dropdown extends Component {
static Theme = Theme;
static Position = Position;
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
popupVisible: false,
isAbove: false
};
}
/**
* public
*/
startRipple = e => {
this.refs.trigger && this.refs.trigger.startRipple(e);
};
/**
* public
*/
endRipple = () => {
this.refs.trigger && this.refs.trigger.endRipple();
};
/**
* public
*/
triggerRipple = e => {
this.refs.trigger && this.refs.trigger.triggerRipple(e);
};
/**
* public
*/
resetPopupPosition = () => {
this.refs.popup && this.refs.popup.resetPosition();
};
/**
* public
*/
closePopup = e => {
this.setState({
popupVisible: false
}, () => {
const {onClosePopup, onBlur} = this.props;
onClosePopup && onClosePopup(e);
onBlur && onBlur(e);
});
};
togglePopup = e => {
const popupVisible = !this.state.popupVisible;
this.setState({
popupVisible
}, () => {
const {onTriggerClick, onFocus, onBlur, onOpenPopup} = this.props;
onTriggerClick && onTriggerClick(popupVisible);
if (popupVisible) {
onFocus && onFocus(e);
onOpenPopup && onOpenPopup(e);
} else {
onBlur && onBlur(e);
}
});
};
popupRenderHandler = popupEl => {
if (this.props.position) {
return;
}
const isAbove = DropdownCalculation.isAbove(this.dropdownEl, this.triggerEl, findDOMNode(popupEl));
if (isAbove !== this.state.isAbove) {
this.setState({
isAbove
});
}
};
componentDidMount() {
this.dropdownEl = this.refs.dropdown;
this.triggerEl = findDOMNode(this.refs.trigger);
}
render() {
const {
children,
className, triggerClassName, popupClassName, style, triggerStyle, popupStyle, theme, popupTheme,
position, iconCls, triggerValue, title, rightIconCls, disabled, disableTouchRipple, autoPopupWidth,
// events
onMouseOver, onMouseOut
} = this.props,
{popupVisible, isAbove} = this.state,
isAboveFinally = position === Position.TOP || position === Position.TOP_LEFT
|| position === Position.TOP_RIGHT || (!position && isAbove),
dropdownClassName = classNames('dropdown', {
activated: popupVisible,
[className]: className
}),
buttonClassName = classNames('dropdown-trigger', isAboveFinally ? 'above' : 'blow', {
activated: popupVisible,
[triggerClassName]: triggerClassName
}),
dropdownPopupClassName = classNames('dropdown-popup', isAboveFinally ? 'above' : 'blow', {
[popupClassName]: popupClassName
}),
dropdownPopupStyle = Object.assign({
width: this.triggerEl && this.triggerEl.offsetWidth
}, popupStyle);
return (
<div ref="dropdown"
className={dropdownClassName}
style={style}>
<RaisedButton ref="trigger"
className={buttonClassName}
style={triggerStyle}
theme={theme}
value={triggerValue}
title={title}
iconCls={iconCls}
rightIconCls={`${rightIconCls} dropdown-trigger-icon`}
disabled={disabled}
disableTouchRipple={disableTouchRipple}
onMouseOver={onMouseOver}
onMouseOut={onMouseOut}
onClick={this.togglePopup}/>
<Popup ref="popup"
className={dropdownPopupClassName}
style={autoPopupWidth ? dropdownPopupStyle : popupStyle}
theme={popupTheme}
visible={popupVisible}
triggerEl={this.triggerEl}
hasTriangle={false}
position={position ? position : (isAbove ? Position.TOP_LEFT : Position.BOTTOM_LEFT)}
shouldPreventContainerScroll={false}
onRender={this.popupRenderHandler}
onRequestClose={this.closePopup}>
{children}
</Popup>
</div>
);
}
}
Dropdown.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* The class name of the trigger element.
*/
triggerClassName: PropTypes.string,
/**
* The class name of the popup element.
*/
popupClassName: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* Override the styles of the trigger element.
*/
triggerStyle: PropTypes.object,
/**
* Override the styles of the popup element.
*/
popupStyle: PropTypes.object,
/**
* The theme.
*/
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The popup theme.
*/
popupTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
position: PropTypes.oneOf(Util.enumerateValue(Position)),
/**
* The value of the dropDown trigger.
*/
triggerValue: PropTypes.any,
iconCls: PropTypes.string,
rightIconCls: PropTypes.string,
title: PropTypes.string,
/**
* If true, the dropDown will be disabled.
*/
disabled: PropTypes.bool,
disableTouchRipple: PropTypes.bool,
/**
* Whether following the trigger width or not.
*/
autoPopupWidth: PropTypes.bool,
/**
* If true,the dropdown box automatically closed after selection.
*/
autoClose: PropTypes.bool,
shouldPreventContainerScroll: PropTypes.bool,
/**
* Callback function fired when the popup is open.
*/
onOpenPopup: PropTypes.func,
/**
* Callback function fired when the popup is close.
*/
onClosePopup: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onMouseOver: PropTypes.func,
onMouseOut: PropTypes.func,
onTriggerClick: PropTypes.func
};
Dropdown.defaultProps = {
theme: Theme.DEFAULT,
popupTheme: Theme.DEFAULT,
rightIconCls: 'fas fa-angle-down',
disabled: false,
disableTouchRipple: false,
autoPopupWidth: true,
autoClose: true,
shouldPreventContainerScroll: true
};
export default Dropdown;
|
JavaScript
| 0.000001 |
@@ -803,33 +803,42 @@
startRipple =
-e
+(e, props)
=%3E %7B%0A th
@@ -879,32 +879,39 @@
er.startRipple(e
+, props
);%0A %7D;%0A%0A /
@@ -1077,17 +1077,26 @@
ipple =
-e
+(e, props)
=%3E %7B%0A
@@ -1155,16 +1155,23 @@
Ripple(e
+, props
);%0A %7D
|
f5db3362861362326b44341315f319084390eb7b
|
Add Content-Type request header for xhr send
|
lib/trans-sender.js
|
lib/trans-sender.js
|
/*
* ***** BEGIN LICENSE BLOCK *****
* Copyright (c) 2011-2012 VMware, Inc.
*
* For the license see COPYING.
* ***** END LICENSE BLOCK *****
*/
var BufferedSender = function() {};
BufferedSender.prototype.send_constructor = function(sender) {
var that = this;
that.send_buffer = [];
that.sender = sender;
};
BufferedSender.prototype.doSend = function(message) {
var that = this;
that.send_buffer.push(message);
if (!that.send_stop) {
that.send_schedule();
}
};
// For polling transports in a situation when in the message callback,
// new message is being send. If the sending connection was started
// before receiving one, it is possible to saturate the network and
// timeout due to the lack of receiving socket. To avoid that we delay
// sending messages by some small time, in order to let receiving
// connection be started beforehand. This is only a halfmeasure and
// does not fix the big problem, but it does make the tests go more
// stable on slow networks.
BufferedSender.prototype.send_schedule_wait = function() {
var that = this;
var tref;
that.send_stop = function() {
that.send_stop = null;
clearTimeout(tref);
};
tref = utils.delay(25, function() {
that.send_stop = null;
that.send_schedule();
});
};
BufferedSender.prototype.send_schedule = function() {
var that = this;
if (that.send_buffer.length > 0) {
var payload = '[' + that.send_buffer.join(',') + ']';
that.send_stop = that.sender(that.trans_url, payload, function(success, abort_reason) {
that.send_stop = null;
if (success === false) {
that.ri._didClose(1006, 'Sending error ' + abort_reason);
} else {
that.send_schedule_wait();
}
});
that.send_buffer = [];
}
};
BufferedSender.prototype.send_destructor = function() {
var that = this;
if (that._send_stop) {
that._send_stop();
}
that._send_stop = null;
};
var jsonPGenericSender = function(url, payload, callback) {
var that = this;
if (!('_send_form' in that)) {
var form = that._send_form = _document.createElement('form');
var area = that._send_area = _document.createElement('textarea');
area.name = 'd';
form.style.display = 'none';
form.style.position = 'absolute';
form.method = 'POST';
form.enctype = 'application/x-www-form-urlencoded';
form.acceptCharset = "UTF-8";
form.appendChild(area);
_document.body.appendChild(form);
}
var form = that._send_form;
var area = that._send_area;
var id = 'a' + utils.random_string(8);
form.target = id;
form.action = url + '/jsonp_send?i=' + id;
var iframe;
try {
// ie6 dynamic iframes with target="" support (thanks Chris Lambacher)
iframe = _document.createElement('<iframe name="'+ id +'">');
} catch(x) {
iframe = _document.createElement('iframe');
iframe.name = id;
}
iframe.id = id;
form.appendChild(iframe);
iframe.style.display = 'none';
try {
area.value = payload;
} catch(e) {
utils.log('Your browser is seriously broken. Go home! ' + e.message);
}
form.submit();
var completed = function(e) {
if (!iframe.onerror) return;
iframe.onreadystatechange = iframe.onerror = iframe.onload = null;
// Opera mini doesn't like if we GC iframe
// immediately, thus this timeout.
utils.delay(500, function() {
iframe.parentNode.removeChild(iframe);
iframe = null;
});
area.value = '';
// It is not possible to detect if the iframe succeeded or
// failed to submit our form.
callback(true);
};
iframe.onerror = iframe.onload = completed;
iframe.onreadystatechange = function(e) {
if (iframe.readyState == 'complete') completed();
};
return completed;
};
var createAjaxSender = function(AjaxObject) {
return function(url, payload, callback) {
var xo = new AjaxObject('POST', url + '/xhr_send', payload);
xo.onfinish = function(status, text) {
callback(status === 200 || status === 204,
'http status ' + status);
};
return function(abort_reason) {
callback(false, abort_reason);
};
};
};
|
JavaScript
| 0 |
@@ -4139,24 +4139,132 @@
callback) %7B%0A
+ var opt = %7B%7D;%0A if (typeof payload === 'string') opt.headers = %7B'Content-type':'text/plain'%7D;%0A
var
@@ -4317,16 +4317,21 @@
payload
+, opt
);%0A
|
16016bd07ad306b7b68590e17ebb3aba7efd587e
|
Correct XML Content-Type header
|
api/odk/controllers/get-osm-submissions.js
|
api/odk/controllers/get-osm-submissions.js
|
var aggregateOsm = require('../osm/aggregate-osm');
var getOsmSubmissionsDirs = require('../helpers/get-osm-submissions-dirs');
/**
* Aggregates together all of the OSM submissions
* from ODK Collect / OpenMapKit Android to the
* file system for the given form.
*/
module.exports = function (req, res, next) {
var formName = req.params.formName;
getOsmSubmissionsDirs(formName, null, function (err, osmDirs) {
if (err) {
res.status(err.status || 500).json(err);
return;
}
aggregate(osmDirs, req, res);
});
};
/**
* Calls aggregate-osm middleware to read OSM edit files
* and concatenate into a single OSM XML aggregation.
*
* @param osmDirs - submission dirs with array of osm files
* @param req - the http request
* @param res - the http response
*/
function aggregate(osmDirs, req, res) {
var osmFiles = [];
for (var i in osmDirs) {
osmFiles = osmFiles.concat(osmDirs[i].files);
}
//We filter by the query parameters of the request
aggregateOsm(osmFiles, req.query, function (err, osmXml) {
if (err) {
if (!res._headerSent) { // prevents trying to send multiple error responses on a single request
res.status(500).json({
status: 500,
msg: 'There was a problem with aggregating OSM JOSM editor files in the submissions directory.',
err: err
});
}
return;
}
res.set('Content-Type', 'text/xml').status(200).end(osmXml);
});
}
|
JavaScript
| 0.000032 |
@@ -1549,12 +1549,19 @@
', '
-text
+application
/xml
|
f535aa6546c7423ccb13661dbe829e4b69ee04b1
|
use consistent capitalization
|
lib/types/Pubsub.js
|
lib/types/Pubsub.js
|
var inherits = require('util').inherits,
DuplexStream = require('stream').Duplex,
EventEmitter = require('events').EventEmitter;
var Xfer = require('xfer');
var utils = require('../utils');
var TYPE_PUB = 0x00,
TYPE_PUB_NOSER = 0x01,
EMPTY_READFN = function(n) {};
function PubSub(opts) {
if (!(this instanceof PubSub))
return new PubSub();
if (opts && typeof opts.highWaterMark === 'number')
DuplexStream.call(this, { highWaterMark: opts.highWaterMark });
else
DuplexStream.call(this);
var self = this;
this.xfer = new Xfer(opts);
this.xfer.on('*', function(type, stream) {
if (!stream || (type !== TYPE_PUB && type !== TYPE_PUB_NOSER)) {
stream && stream.resume();
return;
}
self._parse(type, stream);
});
this.xfer.on('data', function(d) {
self.push(d);
});
this.events = new EventEmitter();
this.events._emit = this.events.emit;
this.events.emit = function() {
self.send.apply(self, arguments);
};
this.events._broadcast = 0;
this.on('newListener', function(ev, fn) {
if (ev === '*')
++self.events._broadcast;
});
this.on('removeListener', function(ev, fn) {
if (ev === '*')
--self.events._broadcast;
});
this.serialize = (opts && typeof opts.serialize === 'boolean'
? opts.serialize
: true);
this.debug = (opts && typeof opts.debug === 'function' ? opts.debug : false);
this._read = EMPTY_READFN;
}
inherits(PubSub, DuplexStream);
PubSub.prototype.send = function() {
if (arguments.length === 0)
throw new Error('Missing event name');
var ev = arguments[0],
args = [],
typeinfo;
for (var i = 1, len = arguments.length; i < len; ++i)
args.push(arguments[i]);
var type, payload;
if (args.length
&& this.serialize
&& (typeinfo = utils.serializeArgs(args)).length) {
type = TYPE_PUB;
payload = JSON.stringify([ev, typeinfo, args]);
} else {
type = TYPE_PUB;
if (args.length)
payload = JSON.stringify([ev, args]);
else
payload = JSON.stringify([ev]);
}
return this.xfer.send(type, payload);
};
PubSub.prototype._write = function(chunk, encoding, cb) {
this.xfer.write(chunk, encoding, cb);
};
PubSub.prototype._parse = function(type, stream) {
var buf = '', self = this;
stream.setEncoding('utf8');
stream.on('data', function(d) {
buf += d;
});
stream.on('end', function() {
var obj = JSON.parse(buf), ev, argslen = 0, args, typeinfo;
ev = obj[0];
if (obj.length === 2) {
args = obj[1];
argslen = args.length;
} else if (obj.length === 3) {
typeinfo = obj[1];
args = obj[2];
argslen = args.length;
}
if (argslen && type === TYPE_PUB && typeinfo)
utils.unserializeArgs(typeinfo, args);
if (argslen === 0) {
self.events._emit(ev);
self.events._broadcast && self.emit('*', ev);
} else if (argslen === 1) {
self.events._emit(ev, args[0]);
self.events._broadcast && self.emit('*', ev, args[0]);
} else if (argslen === 2) {
self.events._emit(ev, args[0], args[1]);
self.events._broadcast && self.emit('*', ev, args[0], args[1]);
} else if (argslen === 3) {
self.events._emit(ev, args[0], args[1], args[2]);
self.events._broadcast && self.emit('*', ev, args[0], args[1], args[2]);
} else {
args.unshift(ev);
self.events._emit.apply(self.events.emit, args);
if (self.events._broadcast) {
args.unshift('*');
self.emit.apply(self.events.emit, args);
}
}
});
};
module.exports = PubSub;
|
JavaScript
| 0.009214 |
@@ -290,17 +290,17 @@
tion Pub
-S
+s
ub(opts)
@@ -329,17 +329,17 @@
ceof Pub
-S
+s
ub))%0A
@@ -353,17 +353,17 @@
new Pub
-S
+s
ub();%0A%0A
@@ -1480,17 +1480,17 @@
rits(Pub
-S
+s
ub, Dupl
@@ -1500,25 +1500,25 @@
tream);%0A%0APub
-S
+s
ub.prototype
@@ -2140,33 +2140,33 @@
ayload);%0A%7D;%0A%0APub
-S
+s
ub.prototype._wr
@@ -2250,17 +2250,17 @@
%0A%7D;%0A%0APub
-S
+s
ub.proto
@@ -3616,13 +3616,13 @@
ts = Pub
-S
+s
ub;%0A
|
da56a025027715f9f5dc2ae09d6d46962d3afe0d
|
fix variable names
|
lib/util/compile.js
|
lib/util/compile.js
|
module.exports = exports;
var fs = require('fs')
, tar = require('tar')
, path = require('path')
, zlib = require('zlib')
, log = require('npmlog')
, semver = require('semver')
, request = require('request')
, win = process.platform == 'win32'
, os = require('os')
, existsAsync = fs.exists || path.exists
, cp = require('child_process')
module.exports.run_gyp = function(args,callback) {
var shell_cmd = 'node-gyp';
if (win) {
shell_cmd = 'node-gyp.cmd';
}
var cmd = cp.spawn(shell_cmd,args, {cwd: undefined, env: process.env, customFds: [ 0, 1, 2]});
cmd.on('error', function (err) {
if (err) {
return callback(new Error("Failed to execute '" + shell_cmd + ' ' + shell_args.join(' ') + "' (" + err + ")"));
}
callback();
});
cmd.on('close', function (err, stdout, stderr) {
if (err) {
return callback(new Error("Failed to execute '" + shell_cmd + ' ' + shell_args.join(' ') + "' (" + err + ")"));
}
callback();
});
}
|
JavaScript
| 0.998822 |
@@ -722,38 +722,32 @@
ell_cmd + ' ' +
-shell_
args.join(' ') +
@@ -958,22 +958,16 @@
+ ' ' +
-shell_
args.joi
|
b4cfe7ddefb80b239851b11b20d3a85d6b1e7b0b
|
Improve console namespace
|
lib/util/console.js
|
lib/util/console.js
|
class Console {
constructor(namespace = null) {
this._namespace = namespace;
this.codes = {
badRequest: 400,
unauthorized: 401,
forbidden: 403,
notFound: 404,
conflict: 409,
internalServerError: 500,
notImplemented: 501,
serviceUnavailable: 502
};
Object.freeze(this.codes);
}
typeOf(variable) {
let string = typeof variable;
if (variable && variable.constructor) {
string += " / Class " + variable.constructor.name;
}
return "Type " + string + " given";
}
buildError(message, code) {
const error = new Error(message);
if (code) {
error.statusCode = code;
}
return error;
}
namespace(namespace) {
this._namespace = namespace;
return this;
}
getPrefix(level) {
if (this._namespace) {
return level + " " + this._namespace + ": ";
} else {
return level + ": ";
}
}
print(...args) {
console.log(...args);
}
log(...args) {
console.log(this.getPrefix("Log"), ...args);
}
debug(...args) {
console.debug(this.getPrefix("Debug"), ...args);
}
info(...args) {
console.info(this.getPrefix("Info"), ...args);
}
warn(...args) {
console.warn(this.getPrefix("Warn"), ...args);
}
error(...args) {
console.error(this.getPrefix("Error"), ...args);
}
table(...args) {
console.table(...args);
}
time(...args) {
console.time(...args);
}
timeEnd(...args) {
console.timeEnd(...args);
}
timeLog(...args) {
console.timeLog(...args);
}
trace(...args) {
console.trace(...args);
}
}
module.exports = Console;
|
JavaScript
| 0.000048 |
@@ -985,16 +985,19 @@
evel + %22
+ in
%22 + thi
|
7bac62eb90d5acaafbd997daafb4e30c7b9b01c6
|
add better type detection
|
lib/util/receive.js
|
lib/util/receive.js
|
var crypto = require("crypto")
var lob = require('lob-enc');
var handshake_collect = require("./handshake").collect;
var log = require("./log")("Receive")
module.exports = {
handshake : receive_handshake,
channel : receive_channel,
type : receive_type,
decloak : receive_decloak
}
function receive_type(packet, pipe){
if(!packet || !pipe)
return new Error('invalid mesh.receive args',typeof packet,typeof pipe);
return (packet.head.length === 0) ? "channel"
: (packet.head.length === 1) ? "handshake"
: "unknown";
}
function receive_decloak(packet, pipe){
if(!lob.isPacket(packet) && !(packet = lob.decloak(packet)))
return new Error('invalid packet ' + typeof packet);
if(packet.cloaked)
pipe.cloaked = true;
return packet;
}
function receive_channel(mesh, packet, pipe){
var token = packet.body.slice(0,16).toString('hex');
var link = mesh.index[token];
if(!link)
{
var route = mesh.routes[token];
if(route)
{
log.debug('routing packet to',route.path);
var dupid = crypto.createHash('sha256').update(packet).digest('hex');
if(dedup[dupid]) return log.debug('dropping duplicate');
dedup[dupid] = true;
return route.send(packet, undefined, function(){});
}
log.debug('dropping unknown channel packet to',token);
return;
}
var inner = link.x.receive(packet);
if(!inner)
{
log.debug('error receiving channel packet',link.x.err);
return;
}
// this pipe is valid, if it hasn't been seen yet, we need to resync
if(!link.seen[pipe.uid])
{
log.debug('never seen pipe',pipe.uid,pipe.path)
link.addPipe(pipe,true); // must see it first
process.nextTick(link.sync); // full resync in the background
}
// if channel exists, handle it
var chan = link.x.channels[inner.json.c];
if(chan)
{
if(chan.state == 'gone') return log.debug('incoming channel is gone');
return chan.receive(inner);
}
// new channel open, valid?
if(inner.json.err || typeof inner.json.type != 'string') return log.debug('invalid channel open',inner.json,link.hashname);
// do we handle this type
log.debug('new channel open',inner.json);
// error utility for any open handler problems
function bouncer(err)
{
if(!err) return;
var json = {err:err};
json.c = inner.json.c;
log.debug('bouncing open',json);
link.x.send({json:json});
}
// check all the extensions for any handlers of this type
var args = {pipe:pipe};
for(var i=0;i<mesh.extended.length;i++)
{
if(typeof mesh.extended[i].open != 'object') continue;
var handler = mesh.extended[i].open[inner.json.type];
if(typeof handler != 'function') continue;
// set the link to be 'this' and be done
handler.call(link, args, inner, bouncer);
return;
}
// default bounce if not handled
return bouncer('unknown type');
};
// cache incoming handshakes to aggregate them
var hcache = {};
setInterval(function hcachet(){hcache={}},60*1000);
function receive_handshake(mesh, packet, pipe){
var inner = mesh.self.decrypt(packet);
if(!inner)
{
log.debug('message decryption failed',this.self);
return;
}
log.debug('inner',inner.json,inner.body)
// process the handshake info to find a link
var token = crypto.createHash('sha256').update(packet.body.slice(0,16)).digest().slice(0,16);
var link = handshake_collect(mesh, token.toString('hex'), inner, pipe, packet);
if(!link || !link.x)
return; // can't respond w/o an exchange
var atOld = link.x.at();
var sync = link.x.sync(packet, inner);
var atNew = link.x.at();
log.debug('handshake sync',sync,atOld,atNew);
// always send handshake back if not in sync
if(!sync) link.x.sending(link.handshake(),pipe);
// new outgoing sync
if(atNew > atOld)
{
log.debug('new outgoing sync');
link.syncedAt = Date.now();
}
// when in sync or we sent a newer at, trust pipe
if(atNew >= atOld) link.addPipe(pipe, true);
// if the senders token changed, we need to reset
if(link.x.session && link.sid != link.x.session.token.toString('hex'))
{
link.sid = link.x.session.token.toString('hex');
log.debug('new session',link.sid);
link.x.flush(); // any existing channels can resend
link.setStatus(); // we're up
}
}
|
JavaScript
| 0.000008 |
@@ -289,24 +289,25 @@
_decloak%0A%7D%0A%0A
+%0A
function rec
@@ -433,17 +433,126 @@
pipe);%0A%0A
-%0A
+ try %7B%0A var head = JSON.parse(packet.head)%0A return (head.json.type %7C%7C %22unknown json%22)%0A %7D catch (e)%7B%0A
return
@@ -591,16 +591,18 @@
hannel%22%0A
+
:
@@ -650,16 +650,18 @@
%0A
+
: %22unkno
@@ -666,11 +666,21 @@
nown
-%22;%0A
+ binary%22;%0A %7D
%0A%7D%0A%0A
|
7252da2814af48c6421422dbf03d19b3a59dcfff
|
add ToDo comment
|
lib/utils/deeper.js
|
lib/utils/deeper.js
|
module.exports = (list, key, value, walk) => {
let i = 0
let depth = 1
let ref = {}
// optimize the shallowness as much as possible
while (i < walk.length) {
if (!list[walk[i]]) {
i = 2 * depth
depth++
} else {
ref = list[walk[i]]
i++
}
}
if (!ref.dependencies) ref.dependencies = {}
ref.dependencies[key] = value
}
|
JavaScript
| 0 |
@@ -133,16 +133,60 @@
ossible%0A
+ // @ToDo should check the version as well%0A
while
|
2a31c1345536f56cf3b26cf7c5484994b4810478
|
Fix callback in readdir, remove trace
|
lib/volume/index.js
|
lib/volume/index.js
|
var FSError = require( '../error' )
var ExFAT = require( '../exfat' )
var debug = require( 'debug' )( 'exfat:volume' )
/**
* ExFAT Volume
* @constructor
* @param {Object} partition
* @return {Volume}
*/
function Volume( partition ) {
if( !(this instanceof Volume) )
return new Volume( partition )
this.partition = partition
this.vbr = new Volume.BootRecord()
this.allocTable = new Volume.AllocationTable( this )
this.root = new ExFAT.Node()
// Node compatible fs API
// this.fs = new ExFAT.FileSystem( this )
}
/**
* Volume Boot Record (VBR)
* @type {Function}
*/
Volume.BootRecord = require( './boot-record' )
Volume.AllocationTable = require( './allocation-table' )
/**
* Volume prototype
* @type {Object}
*/
Volume.prototype = {
constructor: Volume,
get sectorSize() {
return 1 << this.vbr.sectorBits
},
get clusterSize() {
return this.sectorSize << this.vbr.spcBits
},
readVBR: function( lba, callback ) {
var self = this
var done = callback.bind( this )
debug( 'read_vbr' )
this.partition.readBlocks( lba, lba + 1, null,
function( error, buffer, bytesRead ) {
if( error != null ) { return done( error ) }
try { self.vbr.parse( buffer ) }
catch( err ) { error = err }
done( error )
}
)
},
readAllocTable: function( callback ) {
var self = this
var done = callback.bind( this )
var from = this.vbr.fatSectorStart
var to = from + this.vbr.fatSectorCount
debug( 'read_alloc_table', from, to )
this.partition.readBlocks( from, to, function( error, buffer, bytesRead ) {
if( error ) return done( error )
var expected = ( self.vbr.fatSectorCount * self.partition.device.blockSize )
if( bytesRead !== expected ) {
debug( 'read_alloc_table', `read ${bytesRead}, expected ${expected}` )
return done( new FSError( FSError.EIO, `Bytes read mismatch (read ${bytesRead}, expected ${expected})` ) )
}
self.allocTable.parse( buffer )
debug( 'read_alloc_table', self.allocTable )
done()
})
},
readCluster: function( cluster, callback ) {
var self = this
var done = callback.bind( this )
// TODO: Cluster -> Sector number translation (necessary?)
var from = this.vbr.clusterSectorStart + cluster
var to = from + ( this.clusterSize / this.sectorSize )
debug( 'read_cluster', from, to )
console.trace( 'read_cluster' )
this.partition.readBlocks( from, to, function( error, buffer, bytesRead ) {
if( error ) return done( error )
done( error, buffer )
})
},
readRootDir: function( callback ) {
var self = this
var done = callback.bind( this )
this.root.startCluster = this.vbr.rootDirCluster
this.root.fptrCluster = this.root.startCluster
this.root.name = '\0'
this.root.size = 0
var clusters = 0
var maxClusters = this.vbr.clusterCount
var rootCluster = this.vbr.rootDirCluster
debug( 'read_root_dir', rootCluster )
this.readdir( this.vbr.clusterSectorStart, function( error, buffer ) {
if( error ) return done( error )
// hex( buffer.slice( 0, 512 ) )
done()
})
// if( this.root.size === 0 ) {
// return done( new FSError( FSError.EIO, 'Invalid root directory size' ) )
// }
// TODO
// done()
},
readdir: function( cluster, callback ) {
debug( 'readdir', cluster )
this.readCluster( this.vbr.clusterSectorStart + cluster, function( error, buffer ) {
if( error ) {
return callback( error )
}
// var cluster = this.vbr.clusterSectorStart
var offset = 0
var contiguous = false // ?!
var continuations = 0
var chunk, entry
var entries = []
while( offset < this.clusterSize ) {
entry = null
chunk = buffer.slice( offset, offset += 32 )
try { entry = ExFAT.Entry.parse( chunk ) }
catch( e ) { console.log( e.message ) }
entry && entries.push( entry )
}
this.root.entries = entries
done( error, entries )
})
},
mount: function( callback ) {
var self = this
var done = callback.bind( this )
// TODO: Callback hell avoidance maneuver
this.readVBR( 0, function( error ) {
if( error ) return done( error )
this.readAllocTable( function( error ) {
if( error ) return done( error )
this.readRootDir( function( error ) {
if( error ) return done( error )
// this.readdir( 12345678, function( error ) {
// if( error ) return done( error )
// done()
// })
done()
})
})
})
},
}
// Exports
module.exports = Volume
|
JavaScript
| 0.000001 |
@@ -2497,44 +2497,8 @@
o )%0A
- console.trace( 'read_cluster' )%0A
@@ -4215,28 +4215,32 @@
%0A
-done
+callback
( error, ent
|
b2b0601fdcc4d70e114380304a7d80504e2965b4
|
Test branch throws if branch already exists
|
spec/branch.spec.js
|
spec/branch.spec.js
|
var fs = require('fs');
var ga = require('../src/gitlet-api');
var testUtil = require('./test-util');
describe('branch', function() {
beforeEach(testUtil.createEmptyRepo);
beforeEach(testUtil.pinDate);
afterEach(testUtil.unpinDate);
it('should throw if not in repo', function() {
expect(function() { ga.branch(); })
.toThrow("fatal: Not a gitlet repository (or any of the parent directories): .gitlet");
});
it('should throw if master has not been created', function() {
ga.init();
expect(function() { ga.branch("woo"); })
.toThrow("fatal: Not a valid object name: 'master'.");
});
it('should create new branch pointed at HEAD when call branch w branch name', function() {
ga.init();
testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
ga.add("1/filea");
ga.commit({ m: "first" });
ga.branch("woo");
testUtil.expectFile(".gitlet/refs/heads/woo", "48946d55");
});
it('should should leave master pointed at orig hash after branching', function() {
ga.init();
testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
ga.add("1/filea");
ga.commit({ m: "first" });
testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
ga.branch("woo");
testUtil.expectFile(".gitlet/refs/heads/master", "48946d55");
});
it('should return list of branches when called with no args', function() {
ga.init();
testUtil.createFilesFromTree({ "1": { "filea": "filea"}});
ga.add("1/filea");
ga.commit({ m: "first" });
ga.branch("woo");
ga.branch("boo");
expect(ga.branch()).toEqual(" boo\n* master\n woo\n");
});
});
|
JavaScript
| 0.000001 |
@@ -1631,13 +1631,352 @@
);%0A %7D);
+%0A%0A it('should prevent branching if branch already exists', function() %7B%0A ga.init();%0A testUtil.createFilesFromTree(%7B %221%22: %7B %22filea%22: %22filea%22%7D%7D);%0A ga.add(%221/filea%22);%0A ga.commit(%7B m: %22first%22 %7D);%0A ga.branch(%22woo%22);%0A expect(function() %7B ga.branch(%22woo%22) %7D)%0A .toThrow(%22fatal: A branch named 'woo' already exists.%22);%0A %7D);
%0A%7D);%0A
|
527db0fb6a140244f2b9d8d7f0d4fc1396c31c48
|
add spec
|
spec/common.spec.js
|
spec/common.spec.js
|
import chai from 'chai'
import { CharacterData, EventTarget, Node, XMLSerializer } from '../lib/dom'
import {
CharacterDataAssembler,
EventTargetAssembler,
NodeAssembler,
DocumentAssembler,
attr, comment, doctype, element,
fragment, instruction, text
} from '../lib'
const { assert } = chai
const serializer = new XMLSerializer
describe('Common', () => {
describe('CharacterDataAssembler', () => {
it('static interface', () => {
assert.equal(CharacterDataAssembler.interface, CharacterData)
})
})
describe('EventTargetAssembler', () => {
it('static interface', () => {
assert.equal(EventTargetAssembler.interface, EventTarget)
})
})
describe('NodeAssembler', () => {
it('static interface', () => {
assert.equal(NodeAssembler.interface, Node)
})
})
describe('DocumentAssembler', () => {
let $attr, $doctype, $fragment, $instruction, $element, $comment, $text
const $document = new DocumentAssembler([
$doctype = doctype('example'),
$fragment = fragment([
$instruction = instruction({
target : 'xml-stylesheet',
attrset : { href : './example.css' }
}),
$element = element({
localName : 'example',
attributes : $attr = attr({
name : 'role',
value : 'application'
}),
childNodes : [
$comment = comment('Version 1.0.0'),
$text = text('Hello world!')
]
})
])
])
it('serializeToString(dom)', () => {
const sample = '<!DOCTYPE example><?xml-stylesheet href="./example.css"?><example role="application"><!--Version 1.0.0-->Hello world!</example>'
assert.equal(serializer.serializeToString($document.node), sample)
})
it('index', () => {
assert.equal($document.index, -1)
assert.equal($document.firstChild.index, 0)
assert.equal($document.lastChild.index, 2)
})
it('documentElement', () => {
assert.equal($document.documentElement, $element)
})
it('doctype', () => {
assert.equal($document.doctype, $doctype)
})
it('nextSibling', () => {
assert.equal($comment.nextSibling, $text)
})
it('previousSibling', () => {
assert.equal($element.previousSibling, $instruction)
})
it('fragment.parentNode', () => {
assert.isNull($fragment.parentNode)
})
it('fragment.node.hasChildNodes()', () => {
assert.isFalse($fragment.node.hasChildNodes())
})
it('attr.ownerElement', () => {
assert.equal($attr.ownerElement, $element)
})
})
describe('ChildNodeAssembler.remove()', () => {
let $element
const $root = element([
text('foobar'),
comment('example'),
$element = element(),
instruction('test')
])
const node = $root.node
$element.remove()
it('node.childNodes.length', () => {
assert.equal(node.childNodes.length, 3)
})
it('serializeToString(node)', () => {
const xml = serializer.serializeToString(node)
const sample = '<element>foobar<!--example--><?instruction test?></element>'
assert.equal(xml, sample)
})
})
describe('element(element())', () => {
let child
const parent = element(child = element())
it('parent.firstElementChild', () => {
assert.equal(parent.firstElementChild, child)
})
it('parent.lastElementChild', () => {
assert.equal(parent.lastElementChild, child)
})
it('removeChild(child); node.hasChildNodes', () => {
parent.removeChild(child)
assert.isFalse(parent.node.hasChildNodes())
})
})
describe('element({ textContent })', () => {
const test = element({ textContent : 'foobar' })
it('parent.textContent', () => {
assert.equal(test.textContent, 'foobar')
})
it('serializeToString(node)', () => {
const xml = serializer.serializeToString(test.node)
assert.equal(xml, '<element>foobar</element>')
})
})
})
|
JavaScript
| 0.000001 |
@@ -165,34 +165,55 @@
-NodeAssembler,%0A Documen
+DocumentAssembler,%0A NodeAssembler,%0A Targe
tAss
@@ -369,16 +369,16 @@
alizer%0A%0A
-
describe
@@ -392,24 +392,197 @@
n', () =%3E %7B%0A
+ describe('new TargetAssembler', () =%3E %7B%0A const fn = () =%3E new TargetAssembler%0A it('throws', () =%3E %7B%0A assert.throws(fn, Error)%0A %7D)%0A %7D)%0A
describe
|
4681a1dc7bfeed964cb960cc36e947d8b0a51752
|
correct object referenced in tests
|
spec/create.spec.js
|
spec/create.spec.js
|
/**
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
*/
var cli = require("../src/create.js"),
Q = require('q'),
cordova_lib = require('cordova-lib'),
plugman = cordova_lib.plugman,
cordova = cordova_lib.cordova;
describe("cordova cli", function () {
beforeEach(function () {
// Event registration is currently process-global. Since all jasmine
// tests in a directory run in a single process (and in parallel),
// logging events registered as a result of the "--verbose" flag in
// CLI testing below would cause lots of logging messages printed out by other specs.
spyOn(cordova, "on");
spyOn(plugman, "on");
});
describe("Create Module", function () {
describe("parseConfig", function() {
it("should be defined", function () {
expect(cdvclicreate.parseConfig).toEqual(jasmine.any(Function));
});
});
describe("create", function() {
it("should be defined", function () {
expect(cdvclicreate.create).toEqual(jasmine.any(Function));
});
});
});
};
|
JavaScript
| 0.000001 |
@@ -817,16 +817,22 @@
%0Avar cli
+create
= requi
@@ -1024,24 +1024,25 @@
nction () %7B%0A
+%0A
beforeEa
@@ -1606,35 +1606,32 @@
expect(
-cdv
clicreate.parseC
@@ -1822,11 +1822,8 @@
ect(
-cdv
clic
@@ -1828,22 +1828,19 @@
icreate.
-create
+run
).toEqua
@@ -1907,10 +1907,11 @@
%7D);%0A%7D
+)
;%0A
|
937d21421a8f82b76187bd89512e9f5b29a098bf
|
Remove deprecated Ember.K
|
addon/components/reveal-presentation/component.js
|
addon/components/reveal-presentation/component.js
|
/* global Reveal, hljs */
import Ember from 'ember';
import layout from './template';
import EmberWormhole from 'ember-wormhole/components/ember-wormhole';
import { EKMixin, keyUp } from 'ember-keyboard';
const { computed, get, set, observer, isBlank, isPresent, on } = Ember;
export default EmberWormhole.extend(EKMixin, {
layout,
keyboard: Ember.inject.service(),
emberRevealJs: Ember.inject.service(),
isSpeakerNotes: computed.alias('emberRevealJs.isSpeakerNotes'),
isMainWindow: computed.not('isSpeakerNotes'),
isPrintingPdf: computed.alias('emberRevealJs.printPdf'),
presentationWidth: computed.alias('emberRevealJs.presentationWidth'),
presentationHeight: computed.alias('emberRevealJs.presentationHeight'),
// presentation-class - passed in
transition: 'slide', // none|fade|slide|convex|concave|zoom
backgroundTransition: 'fade', // none/fade/slide/convex/concave/zoom
progress: true,
controls: computed.alias('emberRevealJs.controls'),
center: true,
// theme - passed in
themePreference: computed.alias('emberRevealJs.themePreference'),
computedTheme: computed('theme', 'themePreference', function() {
return get(this, 'themePreference') || get(this, 'theme') || 'black';
}),
// Specify ember-wormhole destinationElement of body to escape the
// application view element, as reveal.js requires 100% height and width
destinationElement: computed(function() {
if (typeof document !== 'undefined') {
return document.body;
}
}),
didInsertElement() {
this._super();
this._initializeReveal();
this.set('keyboardActivated', true);
},
speakerNotesUrl() {
let ss = 'r=true';
let s = location.search;
let qs = isBlank(s) ? `?${ss}` : `${s}&${ss}`;
return ['//', location.host, location.pathname, qs].join('');
},
launchSpeakerNotes: on(keyUp('s'), function() {
if (get(this, 'isSpeakerNotes')) {
return;
}
window.open(this.speakerNotesUrl(), 'reveal.js - Notes', 'width=1100,height=700');
}),
_initializeReveal() {
if (get(this, 'isSpeakerNotes')) {
return;
}
Reveal.initialize(this._revealOptions());
Reveal.addEventListener('slidechanged', this._revealSlideChanged);
Reveal.addEventListener('overviewshown', this._revealOverviewShown);
Reveal.addEventListener('overviewhidden', this._revealOverviewHidden);
Reveal.addEventListener('paused', this._revealPaused);
Reveal.addEventListener('resumed', this._revealResumed);
let self = this;
Ember.subscribe('emberRevealJs.message', {
before: Ember.K,
after(name, timestamp, payload) {
self._syncRevealState(payload);
}
});
this._setRevealState();
window.RevealMarkdown.convertSlides();
hljs.initHighlightingOnLoad();
},
presentationStateDidChange: observer(
'emberRevealJs.presentationState',
function() {
this._setRevealState();
}
),
_revealOptions() {
let revealOptions = {
history: false, // Don't interfere with Ember's routing
transition: get(this, 'transition'),
backgroundTransition: get(this, 'backgroundTransition'),
progress: get(this, 'progress'),
controls: get(this, 'controls'),
center: get(this, 'center')
};
if (get(this, 'presentationWidth')) {
revealOptions.width = get(this, 'presentationWidth');
}
if (get(this, 'presentationHeight')) {
revealOptions.height = get(this, 'presentationHeight');
}
return revealOptions;
},
_revealSlideChanged(event) {
Ember.instrument('emberRevealJs.message', event);
},
_revealOverviewShown(event) {
event.overview = true;
Ember.instrument('emberRevealJs.message', event);
},
_revealOverviewHidden(event) {
event.overview = false;
Ember.instrument('emberRevealJs.message', event);
},
_revealPaused(event) {
event.paused = true;
Ember.instrument('emberRevealJs.message', event);
},
_revealResumed(event) {
event.paused = false;
Ember.instrument('emberRevealJs.message', event);
},
_syncRevealState(state) {
set(this, 'emberRevealJs.indexh', state.indexh);
set(this, 'emberRevealJs.indexv', state.indexv);
if (isPresent(state.paused)) {
set(this, 'emberRevealJs.paused', !!state.paused);
}
if (isPresent(state.overview)) {
set(this, 'emberRevealJs.overview', !!state.overview);
}
},
_setRevealState() {
let state = get(this, 'emberRevealJs.presentationState');
if (state) {
Reveal.setState(state);
}
}
});
|
JavaScript
| 0.000002 |
@@ -2566,17 +2566,13 @@
fore
-: Ember.K
+() %7B%7D
,%0A
|
52865fab8c88d7bf01f64b5032f230396f5ab8b1
|
add comments
|
measurement/js/measurement_demo.js
|
measurement/js/measurement_demo.js
|
/**
* Created by kelvinzhang on 5/29/17.
*/
var canvas;
var bgCanvas;
var robotX;
var robotY;
var senseCircle = 0;
var senseRadius = 150;
var nLasers = 36;
var scanned = false;
var robotDir = 0;
var dirOffset = 0;
//Results of laser scan
var z = new Array(nLasers);
function click()
{
var coor = getClickLoc(event);
robotX = coor.x;
robotY = coor.y;
// senseCircle = 0;
scanned = false;
update();
draw(canvas.getContext('2d'));
}
function scan()
{
//Radian between each laser
for(var i = 0; i < nLasers; i ++)
{
var dir = Math.PI*2 * i / nLasers;
var s1 = new Point(robotX, robotY);
var t1 = new Point(robotX + cos(dir)*senseRadius, robotY + sin(dir)*senseRadius);
//If dir is 90 degrees
//if i = 1/nLasers or i = (3/4) * nLasers
//cos(dir) should be 0 in these cases,
if(i * 4 === nLasers || i * 4 === nLasers * 3)
t1.x = robotX;
else if(i * 2 === nLasers)
t1.y = robotY;
z[i] = senseRadius + 100;
for(var j = 0; j < map.length; j ++)
{
if(doIntersect(s1, t1, map[j].s, map[j].t))
{
// z[i] = senseRadius;
var p = intersectionPoint(s1, t1, map[j].s, map[j].t);
var dist = p.distanceTo(new Point(robotX, robotY));
z[i] = min(z[i], dist);
}
}
}
}
function update()
{
if(!scanned)
{
scan();
scanned = true;
}
// senseCircle++;
// senseCircle %= senseRadius;
}
function draw(ctx)
{
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.strokeStyle = 'black';
ctx.drawRobot(robotX, robotY, robotDir, 20);
//Radian between each laser
var rad = Math.PI*2/nLasers;
for(var index = 0; index < nLasers/2; index ++)
{
var i = (index + dirOffset + nLasers - nLasers/4) % nLasers;
var dir = i * rad;
var laserLen = senseCircle;
if(z[i] > senseRadius)
{
ctx.strokeStyle = 'grey';
}else
{
laserLen = min(laserLen, z[i]);
ctx.strokeStyle = 'red';
ctx.fillStyle = 'red';
ctx.beginPath();
ctx.arc(robotX + cos(dir)*z[i], robotY + sin(dir)*z[i], 5, 0, Math.PI*2);
ctx.fill();
}
ctx.beginPath();
ctx.moveTo(robotX, robotY);
ctx.lineTo(robotX + cos(dir)*laserLen, robotY + sin(dir)*laserLen);
ctx.stroke();
}
}
function frame()
{
var ctx = canvas.getContext('2d');
update();
draw(ctx);
requestAnimationFrame(frame);
}
function parameterChanged(event)
{
senseRadius = Number(event.target.value)/0.02;
}
function mouseMotion(event)
{
var coor = getClickLoc(event);
var x = coor.x;
var y = coor.y;
robotDir = atan2(y-robotY, x-robotX);
dirOffset = round(robotDir/Math.PI/2 * nLasers);
}
function init()
{
canvas = document.getElementById('canvas');
bgCanvas = document.getElementById('background');
//Draw the map
var map = getMapForCanvas(canvas);
drawMap(map, bgCanvas.getContext('2d'));
robotX = floor(random()*canvas.width);
robotY = floor(random()*canvas.height);
//Listen to mouse click events
background.addEventListener('click', click);
background.onmousemove = mouseMotion;
senseRadius = getValue('fogOfWar')/0.02;
senseCircle = senseRadius;
requestAnimationFrame(frame);
}
|
JavaScript
| 0 |
@@ -1840,32 +1840,227 @@
index ++)%0A %7B%0A
+ //dirOffset is the direction the user's mouse%0A //is point at, -nLasers/4 to offset it by 90 degrees,%0A //so that laser scan is centered at where the user%0A //points to%0A
var i =
@@ -2082,17 +2082,17 @@
set
-+
+-
nLasers
- n
@@ -2087,26 +2087,76 @@
nLasers
- -
+/4);%0A%0A //get i stay in bound%0A i = (i +
nLasers
/4) %25 nL
@@ -2147,18 +2147,16 @@
nLasers
-/4
) %25 nLas
@@ -2156,24 +2156,25 @@
%25 nLasers;%0A
+%0A
var
|
86fd4c25a9e91782c714742321d9cea267661fe5
|
Test can add remote to bare repo
|
spec/remote.spec.js
|
spec/remote.spec.js
|
var fs = require("fs");
var g = require("../src/gitlet");
var testUtil = require("./test-util");
describe("remote", function() {
beforeEach(testUtil.initTestDataDir);
it("should throw if not in repo", function() {
expect(function() { g.remote(); })
.toThrow("not a Gitlet repository");
});
it("should throw if try to remove origin", function() {
g.init();
expect(function() { g.remote("remove"); }).toThrow("unsupported");
});
it("should store url when add origin", function() {
g.init();
g.remote("add", "origin", "git@origin");
var configFileLines = fs.readFileSync(".gitlet/config", "utf8").split("\n");
expect(configFileLines[0]).toEqual("[remote \"origin\"]");
expect(configFileLines[1]).toEqual(" url = git@origin");
});
it("should store remote branch ref location when add origin", function() {
g.init();
g.remote("add", "origin", "git@origin");
var configFileLines = fs.readFileSync(".gitlet/config", "utf8").split("\n");
expect(configFileLines[0]).toEqual("[remote \"origin\"]");
});
it("should return newline when successfully add remote", function() {
g.init();
expect(g.remote("add", "origin", "git@origin")).toEqual("\n");
var configFileLines = fs.readFileSync(".gitlet/config", "utf8").split("\n");
expect(configFileLines[0]).toEqual("[remote \"origin\"]");
});
it("should be able to store more than one remote", function() {
g.init();
g.remote("add", "origin", "git@origin");
g.remote("add", "heroku", "git@heroku");
g.remote("add", "server", "git@server");
var configFileLines = fs.readFileSync(".gitlet/config", "utf8").split("\n");
expect(configFileLines[0]).toEqual("[remote \"origin\"]");
expect(configFileLines[2]).toEqual("[remote \"heroku\"]");
expect(configFileLines[4]).toEqual("[remote \"server\"]");
});
it("should throw if origin already exists", function() {
g.init();
g.remote("add", "origin", "git@origin");
expect(function() { g.remote("add", "origin", "git@heroku"); })
.toThrow("remote origin already exists");
});
});
|
JavaScript
| 0 |
@@ -770,32 +770,373 @@
rigin%22);%0A %7D);%0A%0A
+ it(%22should be able to add remote to bare repo%22, function() %7B%0A g.init(%7B bare: true %7D);%0A g.remote(%22add%22, %22origin%22, %22git@origin%22);%0A var configFileLines = fs.readFileSync(%22config%22, %22utf8%22).split(%22%5Cn%22);%0A expect(configFileLines%5B0%5D).toEqual(%22%5Bremote %5C%22origin%5C%22%5D%22);%0A expect(configFileLines%5B1%5D).toEqual(%22 url = git@origin%22);%0A %7D);%0A%0A
it(%22should sto
|
26157058adc9f938b2ef2708ffe011347cf7dbcf
|
Add hostname and hostnamef filters
|
app/assets/javascripts/angular/filters/filters.js
|
app/assets/javascripts/angular/filters/filters.js
|
angular.module("Prometheus.filters").filter('toPercent', function() {
return function(input) {
return parseFloat(input, 10) * 100 + "%";
}
});
angular.module("Prometheus.filters").filter('toPercentile', function() {
return function(input) {
return parseFloat(input, 10) * 100 + "th";
}
});
angular.module("Prometheus.filters").filter('hostname', function() {
return function(input) {
var a = document.createElement("a");
a.href = input;
return a.host;
}
});
angular.module("Prometheus.filters").filter('regex', function() {
return function(input, regex, replace) {
return input.replace(new RegExp(regex, "g"), replace);
}
});
|
JavaScript
| 0.999992 |
@@ -354,16 +354,20 @@
hostname
+Fqdn
', funct
@@ -482,32 +482,234 @@
.host;%0A %7D%0A%7D);%0A%0A
+angular.module(%22Prometheus.filters%22).filter('hostname', function() %7B%0A return function(input) %7B%0A var a = document.createElement(%22a%22);%0A a.href = input;%0A return a.host.split(%22.%22, 1)%5B0%5D;%0A %7D%0A%7D);%0A%0A
angular.module(%22
|
fec84ca0d27ede788dfaa2275a4589288447ef1d
|
queue name will be node_js
|
app/assets/javascripts/app/controllers/sidebar.js
|
app/assets/javascripts/app/controllers/sidebar.js
|
Travis.Controllers.Sidebar = SC.Object.extend({
cookie: 'sidebar_minimized',
init: function() {
Travis.Controllers.Workers.create();
Travis.Controllers.Jobs.create({ queue: 'builds.common' });
Travis.Controllers.Jobs.create({ queue: 'builds.rails' });
Travis.Controllers.Jobs.create({ queue: 'builds.erlang' });
Travis.Controllers.Jobs.create({ queue: 'builds.php' });
Travis.Controllers.Jobs.create({ queue: 'builds.node' });
$(".slider").click(function() { this.toggle(); }.bind(this));
if($.cookie(this.cookie) === 'true') { this.minimize(); }
this.persist();
},
toggle: function() {
this.isMinimized() ? this.maximize() : this.minimize();
this.persist();
},
isMinimized: function() {
return $('#right').hasClass('minimized');
},
minimize: function() {
$('#right').addClass('minimized');
$('#main').addClass('maximized');
},
maximize: function() {
$('#right').removeClass('minimized');
$('#main').removeClass('maximized');
},
persist: function() {
$.cookie(this.cookie, this.isMinimized());
}
});
|
JavaScript
| 0.999998 |
@@ -444,16 +444,19 @@
lds.node
+_js
' %7D);%0A%0A
|
2bd3bad7cfab0acbd9d740f6a3eebb0680de9e3d
|
include css into main js build
|
webpack.config-helper.js
|
webpack.config-helper.js
|
'use strict'
const Path = require('path')
const Webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const ExtractSASS = new ExtractTextPlugin('styles/bundle.css')
module.exports = options => {
const webpackConfig = {
devtool: options.devtool,
entry: [
`webpack-dev-server/client?http://localhost:${options.port}`,
'webpack/hot/dev-server',
'./src/main.js'
],
output: {
path: Path.join(__dirname, 'dist'),
filename: 'd3-playbooks.base.min.js'
},
plugins: [
new Webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(options.isProduction ? 'production' : 'development')
}
}),
new HtmlWebpackPlugin({
template: './src/index.html'
})
],
module: {
loaders: [{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel',
query: {
presets: ['es2015']
}
}]
}
}
if (options.isProduction) {
webpackConfig.entry = ['./src/main.js']
// external dependencies
webpackConfig.externals = {
d3: 'd3',
Papa: 'papaparse'
}
webpackConfig.plugins.push(
new Webpack.optimize.OccurenceOrderPlugin(),
new Webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
}),
ExtractSASS
)
webpackConfig.module.loaders.push({
test: /\.scss$/i,
loader: ExtractSASS.extract(['css', 'sass'])
})
} else {
webpackConfig.plugins.push(
new Webpack.HotModuleReplacementPlugin(),
new Webpack.ProvidePlugin({d3: 'd3'})
)
webpackConfig.module.loaders.push({
test: /\.scss$/i,
loaders: ['style', 'css', 'sass']
}, {
test: /\.js$/,
loader: 'eslint',
exclude: /node_modules/
})
webpackConfig.devServer = {
contentBase: './dist',
hot: true,
port: options.port,
inline: true,
progress: true
}
}
return webpackConfig
}
|
JavaScript
| 0.000329 |
@@ -131,136 +131,8 @@
in')
-%0Aconst ExtractTextPlugin = require('extract-text-webpack-plugin')%0Aconst ExtractSASS = new ExtractTextPlugin('styles/bundle.css')
%0A%0Amo
@@ -760,16 +760,95 @@
ers: %5B%7B%0A
+ test: /%5C.scss$/i,%0A loaders: %5B'style', 'css', 'sass'%5D%0A %7D, %7B%0A
@@ -1396,155 +1396,13 @@
%7D)
-,
%0A
- ExtractSASS%0A )%0A%0A webpackConfig.module.loaders.push(%7B%0A test: /%5C.scss$/i,%0A loader: ExtractSASS.extract(%5B'css', 'sass'%5D)%0A %7D
)%0A%0A
@@ -1586,81 +1586,8 @@
h(%7B%0A
- test: /%5C.scss$/i,%0A loaders: %5B'style', 'css', 'sass'%5D%0A %7D, %7B%0A
|
85ee384026924ee7f80dbac9b701e59a70ebb0c0
|
Remove visits from locs during migration
|
migration/versions/v11v12/index.js
|
migration/versions/v11v12/index.js
|
/* eslint-disable max-lines */
// In this version increase:
// 1. set schema version to 12
// 2. Remove orphan event i.e. entry events whose entry has been deleted.
// Do this to simplify entry event refactor.
// 3. Drop possible 'attachments' collections from earlier failed migration.
// 4. refactor entries and entry events
// 5. refactor locations by adding published prop
// 6. refactor locations by adding createdAt prop
// 7. select thumbnails for each location and add thumbnail prop
// 8. remove visits-related user properties
// 9. add activeAt property to entries
//
// Also, new indices were made and thus 'npm run migrate' is needed.
const db = require('georap-db');
const asyn = require('async');
const clone = require('clone');
const schema = require('../../lib/schema');
const iter = require('../../lib/iter');
const removeOrphanEvents = require('./removeOrphanEvents');
const migrateEntry = require('./migrateEntry');
const getThumbnail = require('./getThumbnail');
const addActiveAt = require('./addActiveAt');
const removeVisitStatistics = require('./removeVisitStatistics');
const FROM_VERSION = 11;
const TO_VERSION = FROM_VERSION + 1;
// Steps to be executed with asyn.eachSeries in the given order.
// The parameter 'nextStep' is function (err) that must be called in the end of
// each step.
const substeps = [
function updateSchema(nextStep) {
console.log('1. Updating schema version tag...');
schema.setVersion(TO_VERSION, (err) => {
if (err) {
return nextStep(err);
}
console.log(' Schema version tag created:', TO_VERSION);
return nextStep(null);
});
},
function removeOrphan(nextStep) {
console.log('2. Remove orphan events...');
removeOrphanEvents((err, numRemoved) => {
if (err) {
return nextStep(err);
}
console.log(' ' + numRemoved + ' orphan entry events were removed.');
return nextStep();
});
},
function dropFailed(nextStep) {
console.log('3. Drop possible attachments collection...');
db.get().dropCollection('attachments', (err, wasDropped) => {
if (err) {
return nextStep(err);
}
if (wasDropped) {
console.log(' The attachments collection was dropped successfully.');
} else {
console.log(' No need to drop collections.');
}
return nextStep();
});
},
function refactorEntries(nextStep) {
console.log('4. Refactor entries and create attachments...');
db.collection('entries')
.find()
.project({
_id: 1,
})
.toArray((err, entryIds) => {
if (err) {
return nextStep(err);
}
asyn.eachSeries(entryIds, (wrappedEntryId, eachNext) => {
migrateEntry(wrappedEntryId._id, eachNext);
}, (eachErr) => {
if (eachErr) {
return nextStep(eachErr);
}
console.log(' ' + entryIds.length + ' entries were migrated.');
return nextStep();
});
});
},
function migrateLocations(nextStep) {
console.log('5. Add published prop and ensure visits prop in locations...');
const coll = db.collection('locations');
iter.updateEach(coll, (origLoc, iterNext) => {
const loc = clone(origLoc);
loc.visits = [];
loc.published = false;
return iterNext(null, loc);
}, (err, iterResults) => {
if (err) {
return nextStep(err);
}
console.log(' ' + iterResults.numDocuments + ' locations processed ' +
'successfully.');
console.log(' ' + iterResults.numUpdated + ' locations updated, ' +
(iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
'need an update');
return nextStep();
});
},
function addCreatedAt(nextStep) {
console.log('6. Add createdAt prop to each location...');
const coll = db.collection('locations');
iter.updateEach(coll, (origLoc, iterNext) => {
db.collection('events').findOne({
locationId: origLoc._id,
type: 'location_created',
}, (err, locEv) => {
if (err) {
return iterNext(err);
}
if (!locEv) {
const msg = 'Missing location_created event for ' + origLoc._id;
return iterNext(new Error(msg));
}
const loc = clone(origLoc);
loc.createdAt = locEv.time;
return iterNext(null, loc);
});
}, (err, iterResults) => {
if (err) {
return nextStep(err);
}
console.log(' ' + iterResults.numDocuments + ' locations processed ' +
'successfully.');
console.log(' ' + iterResults.numUpdated + ' locations updated, ' +
(iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
'need an update');
return nextStep();
});
},
function addThumbnail(nextStep) {
console.log('7. Add thumbnail to each location...');
const coll = db.collection('locations');
iter.updateEach(coll, (origLoc, iterNext) => {
getThumbnail(origLoc._id, (err, attachment) => {
if (err) {
return iterNext(err);
}
const loc = clone(origLoc);
if (attachment) {
loc.thumbnail = attachment.key;
} else {
// No image attachment. Default path.
loc.thumbnail = null;
}
return iterNext(null, loc);
});
}, (err, iterResults) => {
if (err) {
return nextStep(err);
}
console.log(' ' + iterResults.numDocuments + ' locations processed ' +
'successfully.');
console.log(' ' + iterResults.numUpdated + ' locations updated, ' +
(iterResults.numDocuments - iterResults.numUpdated) + ' did not ' +
'need an update');
return nextStep();
});
},
// Remove outdated statistics from users
removeVisitStatistics,
// Add activeAt property to entries
addActiveAt,
];
exports.run = (callback) => {
// Parameters
// callback
// function (err)
console.log();
console.log('### Step v' + FROM_VERSION + ' to v' + TO_VERSION + ' ###');
asyn.series(substeps, (err) => {
if (err) {
console.error(err);
return callback(err);
}
return callback();
});
};
|
JavaScript
| 0 |
@@ -3105,13 +3105,13 @@
and
-ensur
+remov
e vi
@@ -3273,24 +3273,31 @@
Loc);%0A
+delete
loc.visits =
@@ -3298,13 +3298,8 @@
sits
- = %5B%5D
;%0A
|
8f1c90f3726c90c88cfdd7c0956f072cf1316b5b
|
Remove dead wood
|
notifications.js
|
notifications.js
|
const _ = require('lodash');
// const marked = require('marked');
// this file is in the front end part of the code. This We should create a place for code that is required by both the front end and the back end, to avoid me inadvertently breaking this module when working on the frontend
// const { getCreatedBy, getContent } = require( './client/src/shared/requestUtils');
const { newCommentEmailBody, newIssueEmailBody, closedIssueEmailBody, reopenedIssueEmailBody } = require( './emailBodies');
const processIssues = (action, issue, projectName, requestLink) => {
switch (action) {
case 'opened':
return {
subject: `Re: ${issue.title}`,
content: newIssueEmailBody(issue, requestLink)
};
break;
case 'closed':
return {
subject: `Re: ${issue.title}`,
content: closedIssueEmailBody(issue, requestLink)
};
break;
case 'reopened':
return {
subject: `Re: ${issue.title}`,
content: reopenedIssueEmailBody(issue, requestLink)
// (
// `
// <p>Your request for <b>${projectName}</b>:</p>
// <p><a href="${requestLink}">${issue.title}</a></p>
// <p>has been reopened.<p>`
// )
};
break;
default:
console.log(`RequestApp: unsupported action: ${action}`);
return { }
break;
}
};
const processComment = (action, issue, comment, projectName, requestLink) => {
switch (action) {
case 'created':
return {
subject: `Re: ${issue.title}`,
content: newCommentEmailBody(issue, comment, requestLink)
};
break;
default:
console.log(`RequestApp: unsupported action: ${action}`);
return { }
break;
}
};
const getNotificationText = (eventType, payload, projectName, requestLink) => {
if (eventType === 'issues') {
return processIssues(payload.action, payload.issue, projectName, requestLink);
} else if (eventType === 'issue_comment') {
return processComment(payload.action, payload.issue, payload.comment, projectName, requestLink);
} else {
throw new Error(`invalid eventType:${eventType} only "issues" and "issue_comment" are currently supported.`);
}
};
const getRequestUrl = (issueNumber, project, appRootUrl) => {
return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}/${issueNumber}`;
};
const getAppUrl = (project, appRootUrl) => {
return `${appRootUrl}/requests/${project.organisation}/${project.repository}/${encodeURIComponent(project.label)}`;
};
const findProject = (payload, projects) => {
const organisation = payload.organization.login;
const repo = payload.repository.name;
const labels = payload.issue.labels.map(issue => issue.name);
const project = _.find(projects, p => p.organisation === organisation && p.repository === repo);
if (!project) {
throw new Error(`Unable to find a matching project for issue: ${payload.issue.html_url}, organisation ${organisation}, repo, ${repo}, labels ${JSON.stringify(labels)}. Available projects: ${JSON.stringify(projects)}`);
}
return project;
};
module.exports = {
findProject,
getRequestUrl,
getNotificationText
};
|
JavaScript
| 0.000011 |
@@ -26,354 +26,8 @@
');%0A
-// const marked = require('marked');%0A// this file is in the front end part of the code. This We should create a place for code that is required by both the front end and the back end, to avoid me inadvertently breaking this module when working on the frontend%0A// const %7B getCreatedBy, getContent %7D = require( './client/src/shared/requestUtils');%0A
cons
@@ -678,182 +678,8 @@
nk)%0A
-// (%0A// %60%0A// %3Cp%3EYour request for %3Cb%3E$%7BprojectName%7D%3C/b%3E:%3C/p%3E%0A// %3Cp%3E%3Ca href=%22$%7BrequestLink%7D%22%3E$%7Bissue.title%7D%3C/a%3E%3C/p%3E%0A// %3Cp%3Ehas been reopened.%3Cp%3E%60%0A// )%0A
|
f5b3082718e1557ba190d38eda1cc25fe97f598b
|
fix updateChart condition for lower values of x
|
webserver/public/main.js
|
webserver/public/main.js
|
var WEBSOCKET_ADDRESS = 'ws://localhost:8887';
var HISTOGRAM_T = 10;
/**
* Attempt to establish new websockets connection
* @param {Function} messageCB onmessage function callback.
*/
function connectWS(messageCB) {
// Init websockets with globally defined address.
ws = new WebSocket(WEBSOCKET_ADDRESS);
ws.onopen = function() {
// Print a message when connection opens.
console.log('open on ' + WEBSOCKET_ADDRESS);
};
ws.onclose = function() {
initDone = false;
// Print a message when connection closes.
console.log('Websocket closed. Trying to reconnect.');
// Call this function again (try to reconnect).
setTimeout(function() {
connectWS(messageCB);
}, 1000);
};
// Set passed function as onmessage callback.
ws.onmessage = messageCB;
}
/**
* Websocket onmessage callback function.
* @param {Object} e Event (with `data`) passed from server.
*/
function messageRecieved(e) {
var data = JSON.parse(e.data);
if (data.message && data.message === 'init' && !initDone) {
saveChartToImg();
saveWon();
colors = data.colors;
probabilities = data.p;
displayProbabilites(probabilities, colors);
initChart(colors);
ws.send('init-ok');
initDone = true;
} else if (data.message && data.message === 'chart') {
// drawWonChart(data.value);
} else if (chart && !data.message) {
updateChart(data);
}
}
function initDatapoints() {
if (datapoints) {
for (var i = 0; i < datapoints.length; i++) {
datapoints[i].splice(0);
}
}
}
function initChart(colors) {
datapoints = [];
var chartData = [];
for (var i = 0; i < 10; i++) {
datapoints.push([]);
chartData.push({
type: "line",
dataPoints: datapoints[i],
markerType: "none"
});
}
initDatapoints();
CanvasJS.addColorSet("graphColors", colors);
chart = new CanvasJS.Chart("chartContainer", {
title: {
text: "Delež barv"
},
colorSet: "graphColors",
height: 500,
axisX: {
title: "čas [iteracije]",
minimum: 0
},
axisY: {
title: "verjetnost",
minimum: 0,
maximum: 1.0
},
data: chartData
});
return chart;
}
function saveWon() {
try {
if (datapoints) {
var i;
for (i = 0; i < datapoints.length; i++) {
var y = datapoints[i][datapoints[i].length - 1];
if (y === 1) {
break;
}
}
wonIndices.push(i);
}
} catch (e) {}
}
function drawWonChart(newData) {
// if (wonIndices.length === HISTOGRAM_T) {
// var numWon = wonIndices.splice(0)
// .filter(function(e) {
// // if color at index 0 won
// return e === 0;
// })
// .length / HISTOGRAM_T;
// wonChartData.push({
// x: wonChartData.length + 1,
// y: Math.log(numWon / (1 - numWon))
// });
// wonChartData.push(newData);
//
// if(!histogram) {
// histogram = new CanvasJS.Chart('wonChartContainer', {
// title: {
// text: 'Razmerje zmag'
// },
// data: [{
// type: 'column',
// dataPoints: wonChartData
// }]
// });
// }
// histogram.render();
}
function saveChartToImg() {
try {
if (datapoints) {
var canvas = document.querySelector("#chartContainer canvas");
var img = canvas.toDataURL("image/png");
var imageContainer = document.getElementById("slike");
var newImage = new Image();
newImage.src = img;
imageContainer.appendChild(newImage);
}
} catch (e) {}
}
function updateChart(data) {
var d = data[0],
lastD = datapoints[0][datapoints[0].length - 1];
if (d && lastD && d.x < lastD.x) {
initDatapoints();
}
data.map(function(e, i) {
datapoints[i].push(e);
});
chart.render();
}
function displayProbabilites(data, colors) {
valuesEl.empty();
for (var i = 0; i < data.length; i++) {
var p = data[i];
var c = colors[i];
valuesEl.append($('<span>')
.addClass('value')
.text(p)
.css('border', '8px solid ' + c));
}
}
$(function() {
chart = null;
histogram = null;
wonIndices = [];
wonChartData = [];
valuesEl = $('#values');
initDone = false;
connectWS(messageRecieved);
});
|
JavaScript
| 0 |
@@ -3559,17 +3559,21 @@
%7B%0A var
-d
+color
= data%5B
@@ -3584,17 +3584,21 @@
last
-D
+Color
= datap
@@ -3643,17 +3643,21 @@
if (
-d
+color
&& last
D &&
@@ -3656,31 +3656,43 @@
last
-D && d
+Color && color
.x %3C
+=
last
-D
+Color
.x) %7B%0A
-%0A
|
819f00694e14acb7eb85fd5b75a586d64e4cf67e
|
Return index for the found item.
|
website/app/util/util.js
|
website/app/util/util.js
|
function isImage(mime) {
switch (mime) {
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
case "image/x-ms-bmp":
case "image/bmp":
return true;
default:
return false;
}
}
function numberWithCommas(n) {
n = n.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(n)) {
n = n.replace(pattern, "$1,$2");
}
return n;
}
function bytesToSizeStr(bytes) {
if(bytes === 0) return '0 Byte';
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function _add_json_callback(url) {
return url + "&callback=JSON_CALLBACK";
}
function _add_json_callback2(url) {
var qIndex = url.indexOf("?");
var argSeparator = "&";
if (qIndex == -1) {
argSeparator = "?";
}
return url + argSeparator + "callback=JSON_CALLBACK";
}
function differenceById(from, others) {
var idsFrom = from.map(function(entry) {
return entry.id;
});
var idsOthers = others.map(function(entry) {
return entry.id;
});
var diff = _.difference(idsFrom, idsOthers);
return from.filter(function(entry) {
return _.indexOf(diff, function(e) {
return e == entry.id;
}) !== -1;
});
}
function removeById(from, what) {
var i = _.indexOf(from, function(item) {
return item.id === what.id;
});
if (i !== -1) {
from.splice(i, 1);
}
}
String.prototype.capitalize = function () {
return this.replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
};
// save a reference to the core implementation
var indexOfValue = _.indexOf;
// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({
// return the index of the first array element passing a test
indexOf: function (array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}
//contains: function(list, value, fromIndex) {
// return _.includes(list, value, fromIndex);
//}
});
|
JavaScript
| 0 |
@@ -1692,24 +1692,39 @@
i, 1);%0A %7D
+%0A%0A return i;
%0A%7D%0A%0AString.p
|
787a133974ea37f58a2118a175f44d77d6b7f896
|
Substitute icon with glyphicon
|
modoboa/static/js/dynamic_input.js
|
modoboa/static/js/dynamic_input.js
|
(function($) {
var DynamicInput = function(element, options) {
this.$element = $(element);
this.options = $.extend({}, $.fn.dynamic_input.defaults, options);
this.nextid = 1;
this.baseid = this.$element.attr("id");
this.basename = this.$element.attr("name").split("_")[0];
this.$element.keyup($.proxy(this.checknotempty, this));
for (var cpt = 1; true; cpt++) {
var $input = $("#" + this.baseid + "_" + cpt);
if (!$input.length) {
break;
}
$input.after(this.addrmlink($input));
$input.focusout(this.checkempty);
this.nextid++;
}
};
DynamicInput.prototype = {
constructor: DynamicInput,
addrmlink: function(input) {
var $rmlink = $('<a href="#"'
+ 'id="' + input.attr("id") + '_rmbtn' + '"'
+ '"><i class="icon-remove"></i></a>');
$rmlink.click($.proxy(this.removeinput, $rmlink));
return $rmlink;
},
addinput: function() {
var id = this.baseid + '_' + this.nextid;
var name = this.basename + '_' + this.nextid;
var $ninput = $('<input type="text"'
+ 'id="' + id + '" '
+ 'name="' + name + '"'
+ '/>');
var $rmlink = this.addrmlink($ninput);
$ninput.focusout(this.checkempty);
$ninput.val(this.$element.val());
this.$element.val(this.options.emptylabel);
this.$element.after($ninput, $rmlink);
this.nextid++;
},
removeinput: function(evt, force) {
evt.preventDefault();
var id = "#" + this.attr("id").replace("_rmbtn", "");
var $input = $(id);
if ($input.val() == "" && (force == undefined || !force)) {
return;
}
$input.remove();
this.remove();
},
checknotempty: function(evt) {
if (evt.keyCode != 13) {
return;
}
if (this.$element.val() == "") {
return;
}
this.addinput();
},
checkempty: function(evt) {
var $input = $(evt.target);
if ($input.val() == "") {
$("#" + $input.attr("id") + "_rmbtn").trigger("click", true);
}
}
};
$.fn.dynamic_input = function(method) {
return this.each(function() {
var $this = $(this),
data = $this.data('dynamic_input'),
options = typeof method === "object" && method;
if (!data) {
$this.data('dynamic_input', new DynamicInput(this, options));
}
if (typeof method === "string") {
data[method]();
}
});
};
/*
* Allow an external access to the constructor (for inheritance)
*/
$.fn.dynamic_input.Constructor = DynamicInput;
$.fn.dynamic_input.defaults = {
emptylabel: ""
};
})(jQuery);
|
JavaScript
| 0.000001 |
@@ -926,16 +926,31 @@
class=%22
+glyphicon glyph
icon-rem
|
b22220c207856c50d18a602de238deffd652a763
|
Add proptypes to GithubButton
|
src/components/GithubButton/GithubButton.js
|
src/components/GithubButton/GithubButton.js
|
import React from 'react';
export default function GithubButton({user, repo, type, width, height, count, large}) {
let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`;
if (count) src += '&count=true';
if (large) src += '&size=large';
return (
<iframe
src={src}
frameBorder="0"
allowTransparency="true"
scrolling="0"
width={width}
height={height}
style={{border: 'none', width: width, height: height}}></iframe>
);
}
|
JavaScript
| 0.000001 |
@@ -25,45 +25,50 @@
';%0A%0A
-export default function GithubButton(
+const GithubButton = (props) =%3E %7B%0A const
%7Buse
@@ -114,12 +114,17 @@
rge%7D
-) %7B%0A
+ = props;
%0A l
@@ -510,10 +510,387 @@
e%3E%0A );%0A
-
%7D
+;%0A%0AGithubButton.propTypes = %7B%0A user: React.PropTypes.string.isRequired,%0A repo: React.PropTypes.string.isRequired,%0A type: React.PropTypes.oneOf(%5B'star', 'watch', 'fork', 'follow'%5D).isRequired,%0A width: React.PropTypes.number.isRequired,%0A height: React.PropTypes.number.isRequired,%0A count: React.PropTypes.bool,%0A large: React.PropTypes.bool%0A%7D;%0A%0Aexport default GithubButton;
%0A
|
ad655b3f8358ac3ec7fce9d799aa65e05fc7a304
|
remove data after pikaday destroy - fixes #382
|
plugins/pikaday.jquery.js
|
plugins/pikaday.jquery.js
|
/*!
* Pikaday jQuery plugin.
*
* Copyright © 2013 David Bushell | BSD & MIT license | https://github.com/dbushell/Pikaday
*/
(function (root, factory)
{
'use strict';
if (typeof exports === 'object') {
// CommonJS module
factory(require('jquery'), require('../pikaday'));
} else if (typeof define === 'function' && define.amd) {
// AMD. Register as an anonymous module.
define(['jquery', 'pikaday'], factory);
} else {
// Browser globals
factory(root.jQuery, root.Pikaday);
}
}(this, function ($, Pikaday)
{
'use strict';
$.fn.pikaday = function()
{
var args = arguments;
if (!args || !args.length) {
args = [{ }];
}
return this.each(function()
{
var self = $(this),
plugin = self.data('pikaday');
if (!(plugin instanceof Pikaday)) {
if (typeof args[0] === 'object') {
var options = $.extend({}, args[0]);
options.field = self[0];
self.data('pikaday', new Pikaday(options));
}
} else {
if (typeof args[0] === 'string' && typeof plugin[args[0]] === 'function') {
plugin[args[0]].apply(plugin, Array.prototype.slice.call(args,1));
}
}
});
};
}));
|
JavaScript
| 0 |
@@ -1345,16 +1345,140 @@
rgs,1));
+%0A%0A if (args%5B0%5D === 'destroy') %7B%0A self.removeData('pikaday');%0A %7D
%0A
|
7042469876c0446c8558bffcfa93a91d163a01a1
|
support falsy/empty string values for ngOptions
|
src/helpers/parse-options.js
|
src/helpers/parse-options.js
|
'use strict';
angular.module('mgcrea.ngStrap.helpers.parseOptions', [])
.provider('$parseOptions', function() {
var defaults = this.defaults = {
regexp: /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/
};
this.$get = function($parse, $q) {
function ParseOptionsFactory(attr, config) {
var $parseOptions = {};
// Common vars
var options = angular.extend({}, defaults, config);
$parseOptions.$values = [];
// Private vars
var match, displayFn, valueName, keyName, groupByFn, valueFn, valuesFn;
$parseOptions.init = function() {
$parseOptions.$match = match = attr.match(options.regexp);
displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]);
};
$parseOptions.valuesFn = function(scope, controller) {
return $q.when(valuesFn(scope, controller))
.then(function(values) {
$parseOptions.$values = values ? parseValues(values, scope) : {};
return $parseOptions.$values;
});
};
// Private functions
function parseValues(values, scope) {
return values.map(function(match, index) {
var locals = {}, label, value;
locals[valueName] = match;
label = displayFn(scope, locals);
value = valueFn(scope, locals) || index;
return {label: label, value: value, index: index};
});
}
$parseOptions.init();
return $parseOptions;
}
return ParseOptionsFactory;
};
});
|
JavaScript
| 0.000002 |
@@ -1690,17 +1690,8 @@
als)
- %7C%7C index
;%0A
|
cc28b827dd3c783bfaa282435ecb09501ba4f7e4
|
fix #375, part 2
|
plugins/tradingAdvisor.js
|
plugins/tradingAdvisor.js
|
var util = require('../core/util');
var _ = require('lodash');
var fs = require('fs');
var config = util.getConfig();
var dirs = util.dirs();
var log = require(dirs.core + '/log');
var CandleBatcher = require(dirs.core + 'candleBatcher');
var moment = require('moment');
var Actor = function(done) {
_.bindAll(this);
this.done = done;
this.batcher = new CandleBatcher(config.tradingAdvisor.candleSize);
var mode = util.gekkoMode();
if(mode === 'realtime')
this.prepareHistoricalData(this.init);
else if(mode === 'backtest')
this.init();
}
util.makeEventEmitter(Actor);
Actor.prototype.init = function(done) {
var methodName = config.tradingAdvisor.method;
if(!fs.existsSync(dirs.methods + methodName + '.js'))
util.die('Gekko doesn\'t know the method ' + methodName);
log.info('\t', 'Using the trading method: ' + methodName);
var method = require(dirs.methods + methodName);
// bind all trading method specific functions
// to the Consultant.
var Consultant = require(dirs.core + 'baseTradingMethod');
_.each(method, function(fn, name) {
Consultant.prototype[name] = fn;
});
this.method = new Consultant;
this.batcher
.on('candle', this.processCustomCandle)
this.method
.on('advice', this.relayAdvice);
this.done();
}
Actor.prototype.prepareHistoricalData = function(done) {
// - step 1: check oldest trade reachable by API
// - step 2: check most recent stored candle window
// - step 3: see if overlap
// - step 4: feed candle stream into CandleBatcher
if(config.tradingAdvisor.historySize === 0)
return done();
var requiredHistory = config.tradingAdvisor.candleSize * config.tradingAdvisor.historySize * 60;
var Reader = require(dirs.plugins + config.tradingAdvisor.adapter + '/reader');
var reader = new Reader;
log.debug(
'The trading method requests',
requiredHistory,
'seconds of historic data. Checking availablity..'
);
// TODO: refactor cb hell
this.checkExchangeTrades(requiredHistory, function(err, window) {
log.debug(
'Exchange has data spanning',
window.to - window.from,
'seconds, we need at least',
requiredHistory,
'seconds.'
);
if(window.to - window.from > requiredHistory) {
// calc new required history
var dif = window.to - window.from;
requiredHistory = Math.floor(dif / 60 / config.tradingAdvisor.candleSize);
log.debug(
'Exchange returns more data than we need,',
'shift required history to',
requiredHistory,
'.'
);
util.setConfigProperty(
'tradingAdvisor',
'historySize',
requiredHistory
);
return done();
}
// We need more data
var exchangeTo = moment.unix(window.to).startOf('minute').unix();
var exchangeFrom = moment.unix(window.from).subtract(1, 'm').startOf('minute').unix();
var optimalFrom = exchangeTo - requiredHistory;
reader.mostRecentWindow(exchangeFrom, optimalFrom, function(result) {
if(!result) {
log.info(
'\t',
'Unable to seed the trading method',
'with locally stored historical candles',
'(Gekko needs more time before it can give advice).'
);
return done();
}
if(result === optimalFrom) {
log.debug(
'Full history locally available.',
'Seeding the trading method with all required historical candles.'
);
} else {
log.debug(
'Partial history locally available. But',
result - optimalFrom,
'seconds are missing. Seeding the trading method with',
'partial historical data (Gekko needs more time before',
'it can give advice).'
);
}
reader.get(result, exchangeFrom, 'full', function(rows) {
// todo: do this in proper place
rows = rows.map(row => {
row.start = moment.unix(row.start);
return row;
});
this.batcher.write(rows);
reader.close();
done();
}.bind(this));
}.bind(this));
}.bind(this));
}
Actor.prototype.checkExchangeTrades = function(requiredHistory, next) {
var provider = config.watch.exchange.toLowerCase();
var DataProvider = require(util.dirs().gekko + 'exchanges/' + provider);
var exchangeChecker = require(util.dirs().core + 'exchangeChecker');
var exchangeSettings = exchangeChecker.settings(config.watch)
var watcher = new DataProvider(config.watch);
if(exchangeSettings.maxHistoryFetch)
var since = exchangeSettings.maxHistoryFetch;
else if(exchangeSettings.providesHistory === 'date')
// NOTE: uses current time
var since = moment()
.subtract(requiredHistory, 'seconds')
.subtract(config.tradingAdvisor.candleSize, 'minutes');
else if(exchangeSettings.providesHistory)
// NOTE: specific to btc-e atm
var since = exchangeSettings.providesHistory;
util.setConfigProperty(
'tradingAdvisor',
'firstFetchSince',
since
);
watcher.getTrades(since, function(e, d) {
if(_.isEmpty(d))
return util.die(
`Gekko tried to retrieve data since ${since.format('YYYY-MM-DD HH:mm:ss')}, however
${provider} did not return any trades. Try to raise the tradingAdviser.historySize.`
);
next(e, {
from: _.first(d).date,
to: _.last(d).date
})
});
}
// HANDLERS
// process the 1m candles
Actor.prototype.processCandle = function(candle, done) {
this.batcher.write([candle]);
done();
}
// propogate a custom sized candle to the trading method
Actor.prototype.processCustomCandle = function(candle) {
this.method.tick(candle);
}
// pass through shutdown handler
Actor.prototype.finish = function(done) {
this.method.finish(done);
}
// EMITTERS
Actor.prototype.relayAdvice = function(advice) {
this.emit('advice', advice);
}
module.exports = Actor;
|
JavaScript
| 0 |
@@ -3830,16 +3830,21 @@
unction(
+err,
rows) %7B%0A
@@ -3904,17 +3904,20 @@
s =
-rows
+_
.map(
+rows,
row
|
ac021c18a65fed9cd56afa0fa56335b04bfa584d
|
fix example
|
src/connectors/clear-all/connectClearAll.js
|
src/connectors/clear-all/connectClearAll.js
|
import {
checkRendering,
getRefinements,
clearRefinementsFromState,
clearRefinementsAndSearch,
} from '../../lib/utils.js';
const usage = `Usage:
var customClearAll = connectClearAll(function render(params, isFirstRendering) {
// params = {
// refine,
// hasRefinements,
// createURL,
// instantSearchInstance,
// widgetParams,
// }
});
search.addWidget(
customClearAll({
[ excludeAttributes = [] ],
[ clearsQuery = false ]
})
);
Full documentation available at https://community.algolia.com/instantsearch.js/connectors/connectClearAll.html
`;
const refine = ({helper, clearAttributes, hasRefinements, clearsQuery}) => () => {
if (hasRefinements) {
clearRefinementsAndSearch(helper, clearAttributes, clearsQuery);
}
};
/**
* @typedef {Object} CustomClearAllWidgetOptions
* @property {string[]} excludeAttributes Every attributes that should not be removed when calling `refine()`.
* @property {boolean} clearsQuery Should calling `refine()` also clears the active search query.
*/
/**
* @typedef {Object} ClearAllRenderingOptions
* @property {function} refine Trigger the clear of all the currently refined values.
* @property {boolean} hasRefinements Indicate if search state is refined.
* @property {function} createURL Create a url for the next state when refinements are cleared.
* @property {InstantSearch} instantSearchInstance Instance of instantsearch on which the widget is attached.
* @property {Object} widgetParams All original `CustomClearAllWidgetOptions` forwarded to the `renderFn`.
*/
/**
* **ClearAll** connector provides the logic to build a custom widget that will give the user the ability to reset the search state.
* This connector provides a `ClearAllRenderingOptions.refine()` function to remove the current refined facets.
* @type {Connector}
* @param {function(ClearAllRenderingOptions, boolean)} renderFn Rendering function for the custom **ClearAll** widget.
* @return {function(CustomClearAllWidgetOptions)} Re-usable widget factory for a custom **ClearAll** widget.
* @example
* var $ = window.$;
* var instantsearch = window.instantsearch;
*
* // custom `renderFn` to render the custom ClearAll widget
* function renderFn(ClearAllRenderingOptions) {
* if (ClearAllRenderingOptions.isFirstRendering === true) {
* var markup = $('<button id="custom-clear-all">Clear All</button>');
* containerNode.append(markup);
*
* markup.on('click', function(event) {
* event.preventDefault();
* ClearAllRenderingOptions.refine();
* })
* }
*
* var clearAllCTA = containerNode.find('#custom-clear-all');
* clearAllCTA.attr('disabled', !ClearAllRenderingOptions.hasRefinements)
* };
*
* // connect `renderFn` to ClearAll logic
* var customClearAllWidget = instantsearch.connectors.connectClearAll(renderFn);
*
* // mount widget on the page
* search.addWidget(
* customClearAllWidget({
* containerNode: $('#custom-clear-all-container'),
* })
* );
*/
export default function connectClearAll(renderFn) {
checkRendering(renderFn, usage);
return (widgetParams = {}) => {
const {excludeAttributes = [], clearsQuery = false} = widgetParams;
return {
// Provide the same function to the `renderFn` so that way the user
// has to only bind it once when `isFirstRendering` for instance
_refine() {},
_cachedRefine() { this._refine(); },
init({helper, instantSearchInstance, createURL}) {
this._cachedRefine = this._cachedRefine.bind(this);
const clearAttributes = getRefinements({}, helper.state)
.map(one => one.attributeName)
.filter(one => excludeAttributes.indexOf(one) === -1);
const hasRefinements = clearAttributes.length !== 0;
const preparedCreateURL = () => createURL(clearRefinementsFromState(helper.state, [], clearsQuery));
this._refine = refine({helper, clearAttributes, hasRefinements, clearsQuery});
renderFn({
refine: this._cachedRefine,
hasRefinements,
createURL: preparedCreateURL,
instantSearchInstance,
widgetParams,
}, true);
},
render({results, state, createURL, helper, instantSearchInstance}) {
const clearAttributes = getRefinements(results, state)
.map(one => one.attributeName)
.filter(one => excludeAttributes.indexOf(one) === -1);
const hasRefinements = clearAttributes.length !== 0;
const preparedCreateURL = () => createURL(clearRefinementsFromState(state, [], clearsQuery));
this._refine = refine({helper, clearAttributes, hasRefinements, clearsQuery});
renderFn({
refine: this._cachedRefine,
hasRefinements,
createURL: preparedCreateURL,
instantSearchInstance,
widgetParams,
}, false);
},
};
};
}
|
JavaScript
| 0 |
@@ -2254,46 +2254,39 @@
ions
-) %7B%0A * if (ClearAllRenderingOptions.
+, isFirstRendering) %7B%0A * if (
isFi
@@ -2384,32 +2384,70 @@
tton%3E');%0A *
+ClearAllRenderingOptions.widgetParams.
containerNode.ap
@@ -2600,24 +2600,24 @@
)%0A * %7D%0A *%0A
-
* var cle
@@ -2627,16 +2627,54 @@
llCTA =
+ClearAllRenderingOptions.widgetParams.
containe
|
5178ec192a2f790c3d873881c84de580626cb829
|
Fix in-memory cache driver
|
src/deep-cache/lib/Driver/InMemoryDriver.js
|
src/deep-cache/lib/Driver/InMemoryDriver.js
|
/**
* Created by AlexanderC on 6/16/15.
*/
'use strict';
import {AbstractDriver} from './AbstractDriver';
/**
* In memory driver implementation
*/
export class InMemoryDriver extends AbstractDriver {
constructor() {
super();
this._storage = {};
}
/**
* @returns {Object}
*/
get storage() {
return this._storage;
}
/**
* @param {String} key
* @param {Function} callback
*/
_has(key, callback = () => {}) {
if (this._storage.hasOwnProperty(key) || this._storage[key][1] === false) {
callback(null, false);
return;
}
let result = this._storage[key][1] < InMemoryDriver._now;
if (!result) {
this._invalidate(key);
callback(null, false);
return;
}
callback(null, result);
}
/**
* @param {String} key
* @param {Function} callback
*/
_get(key, callback = () => {}) {
callback(null, this._storage[key]);
}
/**
* @param {String} key
* @param {*} value
* @param {Number} ttl
* @param {Function} callback
* @returns {Boolean}
*/
_set(key, value, ttl = 0, callback = () => {}) {
this._storage[key] = [value, ttl <= 0 ? false : (InMemoryDriver._now + ttl)];
callback(null, true);
}
/**
* @param {String} key
* @param {Number} timeout
* @param {Function} callback
*/
_invalidate(key, timeout = 0, callback = () => {}) {
if (timeout <= 0) {
delete this._storage[key];
callback(null, true);
return;
}
this._storage[key][1] = InMemoryDriver._now + timeout;
callback(null, true);
}
/**
* @param {Function} callback
* @returns {AbstractDriver}
*/
_flush(callback = () => {}) {
this._storage = {};
callback(null, true);
}
/**
* @returns {Number}
* @private
*/
static get _now() {
return new Date().getTime();
}
}
|
JavaScript
| 0.000005 |
@@ -457,16 +457,17 @@
if (
+!
this._st
|
f1d1f128cf07eecc1da3b2b5101c78aec682bd46
|
support highlight_modified_tabs setting
|
.gulp/components/options/underline_modified_tabs.js
|
.gulp/components/options/underline_modified_tabs.js
|
const mixins = require('../../mixins.js');
module.exports = function (values) {
const c = values.colors;
const stOpts = values.options;
return [
// Default Thickness
...mixins.createComponentVariations((lumin, palette) => {
return {
class: 'tab_control',
settings: [stOpts.underlineDirtyTabs],
attributes: ['dirty'],
parents: [
{
attributes: [lumin],
},
],
'layer2.tint': palette('gray'),
};
}),
{
class: 'tab_control',
settings: [stOpts.underlineDirtyTabs],
attributes: ['dirty', 'selected'],
'layer2.opacity': 1, // Border - Bottom
},
// Thick Thickness
{
class: 'tab_control',
settings: [stOpts.underlineDirtyTabs, stOpts.underlineDirtyTabsThick],
attributes: ['dirty'],
'layer2.inner_margin': [0, 0, 0, 2],
},
];
};
|
JavaScript
| 0.000001 |
@@ -840,24 +840,827 @@
%5B'dirty'%5D,%0A%0A
+ 'layer2.inner_margin': %5B0, 0, 0, 2%5D,%0A %7D,%0A%0A /* support for highlight_modified_tabs setting */%0A%0A // Default Thickness%0A ...mixins.createComponentVariations((lumin, palette) =%3E %7B%0A return %7B%0A class: 'tab_control',%0A settings: %5B'highlight_modified_tabs'%5D,%0A attributes: %5B'dirty'%5D,%0A%0A parents: %5B%0A %7B%0A attributes: %5Blumin%5D,%0A %7D,%0A %5D,%0A%0A 'layer2.tint': palette('gray'),%0A %7D;%0A %7D),%0A%0A %7B%0A class: 'tab_control',%0A settings: %5B'highlight_modified_tabs'%5D,%0A attributes: %5B'dirty', 'selected'%5D,%0A%0A 'layer2.opacity': 1, // Border - Bottom%0A %7D,%0A%0A // Thick Thickness%0A %7B%0A class: 'tab_control',%0A settings: %5B'highlight_modified_tabs', stOpts.underlineDirtyTabsThick%5D,%0A attributes: %5B'dirty'%5D,%0A%0A
'layer
|
cd18527e7768b3f1a29442094f10c65f823c1bf1
|
Fix breaking of PickerAndroid when child is null. (#23748)
|
Libraries/Components/Picker/PickerAndroid.android.js
|
Libraries/Components/Picker/PickerAndroid.android.js
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow strict-local
*/
'use strict';
const AndroidDropdownPickerNativeComponent = require('AndroidDropdownPickerNativeComponent');
const AndroidDialogPickerNativeComponent = require('AndroidDialogPickerNativeComponent');
const React = require('React');
const StyleSheet = require('StyleSheet');
const processColor = require('processColor');
const REF_PICKER = 'picker';
const MODE_DROPDOWN = 'dropdown';
import type {SyntheticEvent} from 'CoreEventTypes';
import type {TextStyleProp} from 'StyleSheet';
type PickerAndroidChangeEvent = SyntheticEvent<
$ReadOnly<{|
position: number,
|}>,
>;
type PickerAndroidProps = $ReadOnly<{|
children?: React.Node,
style?: ?TextStyleProp,
selectedValue?: ?(number | string),
enabled?: ?boolean,
mode?: ?('dialog' | 'dropdown'),
onValueChange?: ?(itemValue: ?(string | number), itemIndex: number) => mixed,
prompt?: ?string,
testID?: string,
|}>;
type Item = $ReadOnly<{|
label: string,
value: ?(number | string),
color?: ?number,
|}>;
type PickerAndroidState = {|
selectedIndex: number,
items: $ReadOnlyArray<Item>,
|};
/**
* Not exposed as a public API - use <Picker> instead.
*/
class PickerAndroid extends React.Component<
PickerAndroidProps,
PickerAndroidState,
> {
static getDerivedStateFromProps(
props: PickerAndroidProps,
): PickerAndroidState {
let selectedIndex = 0;
const items = React.Children.map(props.children, (child, index) => {
if (child.props.value === props.selectedValue) {
selectedIndex = index;
}
const childProps = {
value: child.props.value,
label: child.props.label,
};
if (child.props.color) {
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
childProps.color = processColor(child.props.color);
}
return childProps;
});
return {selectedIndex, items};
}
state = PickerAndroid.getDerivedStateFromProps(this.props);
render() {
const Picker =
this.props.mode === MODE_DROPDOWN
? AndroidDropdownPickerNativeComponent
: AndroidDialogPickerNativeComponent;
const nativeProps = {
enabled: this.props.enabled,
items: this.state.items,
mode: this.props.mode,
onSelect: this._onChange,
prompt: this.props.prompt,
selected: this.state.selectedIndex,
testID: this.props.testID,
style: [styles.pickerAndroid, this.props.style],
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was found
* when making Flow check .android.js files. */
accessibilityLabel: this.props.accessibilityLabel,
};
return <Picker ref={REF_PICKER} {...nativeProps} />;
}
_onChange = (event: PickerAndroidChangeEvent) => {
if (this.props.onValueChange) {
const position = event.nativeEvent.position;
if (position >= 0) {
const children = React.Children.toArray(this.props.children);
const value = children[position].props.value;
/* $FlowFixMe(>=0.78.0 site=react_native_android_fb) This issue was
* found when making Flow check .android.js files. */
this.props.onValueChange(value, position);
} else {
this.props.onValueChange(null, position);
}
}
// The picker is a controlled component. This means we expect the
// on*Change handlers to be in charge of updating our
// `selectedValue` prop. That way they can also
// disallow/undo/mutate the selection of certain values. In other
// words, the embedder of this component should be the source of
// truth, not the native component.
if (
this.refs[REF_PICKER] &&
this.state.selectedIndex !== event.nativeEvent.position
) {
this.refs[REF_PICKER].setNativeProps({
selected: this.state.selectedIndex,
});
}
};
}
const styles = StyleSheet.create({
pickerAndroid: {
// The picker will conform to whatever width is given, but we do
// have to set the component's height explicitly on the
// surrounding view to ensure it gets rendered.
// TODO would be better to export a native constant for this,
// like in iOS the RCTDatePickerManager.m
height: 50,
},
});
module.exports = PickerAndroid;
|
JavaScript
| 0.000366 |
@@ -1641,24 +1641,76 @@
index) =%3E %7B%0A
+ if (child === null) %7B%0A return;%0A %7D%0A
if (ch
|
42a5183fbfde51330d8d8468a48f4e49d0ea4c4a
|
Clean up Identity widget.
|
widgets/identity/main.js
|
widgets/identity/main.js
|
/**
* # Widget `identity`
*
* This widget is identified as `identity@hull`
* Use it to indicate whether the user is logged in or not, and display login buttons if not.
*
*/
define({
type: "Hull",
/**
* @name Templates
* #### `identity/identity`
*
* Displays login buttons or the name of the user, depending on its logged in state
*
*/
templates: ['identity'],
// Which events to refresh the widget on.
refreshEvents: ['model.hull.me.change'],
initialize: function() {
this.authServices = _.map(this.sandbox.config.services.types.auth, function(s) { return s.replace(/_app$/, ''); })
if (_.isEmpty(this.authServices)) {
console.error("No Auth services configured. please add one to be able to authenticate users.");
}
},
/**
* Process the resolved datasources before sending them to the template
*
* @param {Object} data The resolved requests from the `datasources` object
* @return {Object|Promise|undefined} The data after you processed it.
* @name beforeRender
*/
beforeRender: function(data) {
data.authServices = this.authServices || [];
return data;
}
});
|
JavaScript
| 0 |
@@ -6,227 +6,106 @@
* #
-Widget %60i
+I
dentity
-%60
%0A *%0A *
-This widget is identified as %60identity@hull%60 %0A * Use it to indicate whether the user is logged in or not, and display login buttons if not.%0A *%0A */%0A%0A%0A%0Adefine(%7B%0A type: %22Hull%22,%0A %0A /**%0A * @name
+Allow users to log in with auth services that you have hooked on your app.%0A *%0A * ##
Tem
@@ -113,19 +113,16 @@
late
-s
%0A
- * ####
+*%0A * -
%60id
@@ -131,42 +131,20 @@
tity
-/identity%60%0A * %0A * Displays
+%60: Show
log
+g
in b
@@ -154,76 +154,95 @@
ons
-or the name of the user, depending on its logged in stat
+if the user isn't logged, display his nam
e%0A
+*
-*%0A */
+ if he is.%0A */%0Adefine(%7B%0A type: 'Hull',%0A
%0A t
@@ -252,16 +252,21 @@
lates: %5B
+%0A
'identit
@@ -271,56 +271,15 @@
ity'
+%0A
%5D,%0A%0A
- // Which events to refresh the widget on.%0A
re
@@ -429,16 +429,22 @@
ion(s) %7B
+%0A
return
@@ -470,11 +470,17 @@
'');
+%0A
%7D)
+;%0A
%0A
@@ -536,17 +536,17 @@
e.error(
-%22
+'
No Auth
@@ -618,9 +618,9 @@
ers.
-%22
+'
);%0A
@@ -634,278 +634,8 @@
%7D,%0A%0A
- /**%0A * Process the resolved datasources before sending them to the template%0A *%0A * @param %7BObject%7D data The resolved requests from the %60datasources%60 object%0A * @return %7BObject%7CPromise%7Cundefined%7D The data after you processed it.%0A * @name beforeRender%0A */%0A
be
|
1f12484b01ffc056cdad3c2b37f45f26132ea6f2
|
fix edit link after referral creation
|
referly/static/js/referly.js
|
referly/static/js/referly.js
|
// Custom JS
// create referral via ajax request
function createReferral(){
var dataString = $('form#referral_create').serialize();
console.log(dataString);
$.ajax({
type: "POST",
url: "/apiv1/referrals/",
data: dataString,
success: function(data) {
console.log(data);
var html ='<tr><td>'+ data.title +'</td><td>'+ data.slug +'</td><td>'+ data.clicks +'</td><td><a href="#">Edit</a></td><td><a href="#">Delete</a></td></tr>';
$('.table tbody').append(html);
var message_html = '<div class="alert alert-info"><a class="close" data-dismiss="alert">×</a><span>' + 'New referral added.' + '</span></div>'
$('#messages').append(message_html);
}
});
return false;
}
// remove referral via ajax request
function removeReferral(referral_id){
var el = 'form#' + referral_id
var dataString = $(el).serializeArray();
$.ajax({
type: "DELETE",
url: "/apiv1/referral/" + referral_id,
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRFToken", dataString[0]['value']);
},
success: function(response) {
var old_el = '#id-' + referral_id
$(old_el).remove();
}
});
return false;
}
|
JavaScript
| 0 |
@@ -438,49 +438,112 @@
ef=%22
-#%22%3EEdit%3C/a%3E%3C/td%3E%3Ctd%3E%3Ca href=%22#%22%3E
+/referrals/'+ data.slug +'%22%3EEdit%3C/a%3E%3C/td%3E%3Ctd%3E%3Cinput class=%22btn btn-danger%22 type=%22submit%22 value=%22
Delete
-%3C/a
+%22/
%3E%3C/t
|
c39648b00f9759a8e6b78303cc16f569e4a9b4f7
|
Update index.js
|
Name-Block/index.js
|
Name-Block/index.js
|
'use strict'; // dont touch
const fs = require('fs');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch
// [General]
this.name = "Name-Block"; // Name of plugin REQUIRED
this.author = "Andrews54757"; // author REQUIRED
this.description = 'blocks certian nicknames'; // Desciprtion
this.compatVersion = ''; // compatable with (optional)
this.version = '1.0.0'; // version REQUIRED
this.gameServer;
// [Extra Commands]
this.commandName[0] = "nameblock"; // plugin add-on command names
this.addToHelp[0] = "nameblock : Nameblock plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = function (gameServer, split, power) {
var c = split[1];
if (c == power) {
if (gameServer.nameblock) {
gameServer.nameblock = false;
console.log("[Console] Turned off plugin");
return;
} else {
gameServer.nameblock = true;
console.log("[Console] Turned on plugin");
return;
}
}
if (!gameServer.nameblock) {
console.log("[Console] Turn on plugin first");
return;
}
if (c == 'reload') {
var load = '';
try {
load = fs.readFileSync('./blockednames.txt', 'utf8').split(/[\r\n]+/).filter(function (x) {
return x != ''; // filter empty names
});
} catch (e) {
fs.writeFileSync('blockednames.txt', '');
}
gameServer.blockednames = load;
console.log("[Console] Reloaded blocked names");
} else if (c == 'add') {
if (!split[2]) {
console.log("[Console] Please specify a name");
return;
}
gameServer.blockednames.push(split[2]);
console.log("[Console] Added " + split[2] + " to the blocked name list");
} else {
console.log("[Console] Please specify a command, reload, power, add");
}
}; // extra command location
// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location
this.blockednames;
// [Configs]
this.config = {
preservecase: 0,
};
this.configfile = 'config.ini';
// [Functions]
this.init = function (gameServer, config) {
gameServer.nameblock = true;
this.config = config;
gameServer.preservec = this.config.preservecase;
this.gameServer = gameServer;
var load = '';
try {
load = fs.readFileSync('./blockednames.txt', 'utf8').split(/[\r\n]+/).filter(function (x) {
return x != ''; // filter empty names
});
} catch (e) {
fs.writeFileSync('blockednames.txt', '');
}
gameServer.blockednames = load;
// init, Used to do stuff such as overriding things
console.log("[NameBlock] Loaded and file is in src/blockednames.txt");
};
this.beforespawn = function (player) {
if (!this.gameServer.nameblock) return true;
if (!player.name) return true;
if (this.gameServer.preservec == 1) {
for (var i in this.gameServer.blockednames) {
if (player.name.indexOf(this.gameServer.blockednames[i]) != -1) return false;
}
} else {
var n = player.name.toLowerCase();
for (var i in this.gameServer.blockednames) {
if (n.indexOf(this.gameServer.blockednames[i]) != -1) return false;
}
}
return true;
};
this.onSecond = function (gameServer) {
// called every second
};
module.exports = this; // dont touch
|
JavaScript
| 0.000002 |
@@ -775,23 +775,16 @@
r, split
-, power
) %7B%0A va
@@ -810,21 +810,23 @@
f (c ==
+'
power
+'
) %7B%0A if
|
ccd6551d1fe8d7157ad11bf39f28fddbe6b70b1c
|
remove redundant ';' character
|
src/forces.html5.constraintValidationAPI.js
|
src/forces.html5.constraintValidationAPI.js
|
/*
forces Constraint Validation API
helpers for the HTML5 constraint validation API
*/
if ( jQuery !== 'undefined' ) {
(function( $ ){
'use strict';
// http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
// 1*( atext / "." ) "@" ldh-str 1*( "." ldh-str )
var REXP_EMAIL = /^[A-Za-z0-9!#$%&'*+\-\/=\?\^_`\{\|\}~\.]+@[A-Za-z0-9\-]+(\.[A-Za-z0-9\-]+)*$/,
// fields that validate
candidateForValidation = 'input, select, textarea',
// for feature detection
input = $( '<input>' ),
// polyfill test
polyfill = typeof input[ 0 ].validity !== 'object',
// new 'invalid' event
invalidEvent = function() {
var invalid = $.Event( 'invalid' );
// invalid events do not bubble
invalid.stopImmediatePropagation();
return invalid;
},
// manage validity state object
validityState = function( typeMismatch, valueMissing, customError, message, patternMismatch ) {
if ( typeof message === 'string' ) {
customError = !! message;
}
return {
customError: customError,
typeMismatch: !! typeMismatch,
patternMismatch: !! patternMismatch,
valueMissing: !! valueMissing,
valid: ! valueMissing && ! customError && ! typeMismatch && ! patternMismatch
};
},
validateField = function( message ) {
var $this = $( this ),
valueMissing = !! $this.attr( 'required' ),
invalidEmail = this.getAttribute( 'type' ) === 'email' && !! this.value && ! REXP_EMAIL.test( this.value ),
patternMismatch,
pattern;
;
// if required, check for missing value
if ( valueMissing ) {
if ( /^select$/i.test( this.nodeName )) {
valueMissing = this.selectedIndex === 0 && this.options[ 0 ].value === '';
// radio buttons
} else if ( this.type === 'radio' ) {
valueMissing = $( this.form.elements[ this.name ] ).filter( ':checked' ).length === 0;
} else {
valueMissing = ! this.value;
}
}
if ( !! this.getAttribute( 'pattern' ) ) {
if ( this.value.length > 0 ) {
// http://www.whatwg.org/specs/web-apps/current-work/multipage/common-input-element-attributes.html#compiled-pattern-regular-expression
pattern = new RegExp( '^(?:' + this.getAttribute( 'pattern' ) + ')$' );
patternMismatch = ! pattern.test( this.value );
} else {
patternMismatch = false;
}
}
// set .validityState
this.validity = validityState( invalidEmail, valueMissing, this.validity.customError || false, message, patternMismatch );
// set .validationMessage
if ( this.validity.valid ) {
this.validationMessage = '';
} else if ( this.validity.customError && typeof message === 'string' ) {
this.validationMessage = message;
} else if ( this.validity.valueMissing ) {
this.validationMessage = 'Please answer this question';
} else if ( this.validity.typeMismatch ) {
this.validationMessage = 'Please type an email address';
}
return this.disabled || this.validity.valid;
},
changeHandler = function( event ) {
var target = event.target;
validateField.call( target );
if ( target.type === 'radio' ) {
$( target.form.elements[ this.name ] ).each(function() {
this.validity = target.validity;
this.validationMessage = target.validationMessage;
});
}
},
submitHandler = function( event ) {
var form = $( this ),
novalidate = !! form.attr( 'novalidate' ),
invalid = false
;
// polyfill validation?
if ( polyfill ) {
// check fields
form.find( candidateForValidation ).each(function() {
invalid = ! validateField.call( this );
// unless @novalidate
if ( ! novalidate ) {
// if invalid
if ( invalid ) {
// trigger invalid
$( this ).trigger( invalidEvent() );
}
}
});
}
// NOTE the code below runs in all browsers to polyfill implementation bugs
// e.g. Opera 11 on OSX fires submit event even when fields are invalid
// correct implementations will not invoke this submit handler until all fields are valid
// unless @novalidate
// if there are invalid fields
if ( ! novalidate && form.find( candidateForValidation ).filter(function() {
return ! ( this.disabled || this.validity.valid );
}).length > 0 ) {
// abort submit
event.stopImmediatePropagation();
event.preventDefault();
return false;
}
},
initConstraintValidationAPI = function() {
var candidates = $( candidateForValidation );
// INPUT validityState
if ( typeof input[ 0 ].validity !== 'object' ) {
// set us up the API
candidates.filter(function() {
return typeof this.validity !== 'object';
}).each(function() {
this.validity = validityState( false, false, false, '', false );
this.validationMessage = '';
});
// check validity on change
candidates
.unbind( 'change.constraintValidationAPI' )
.bind( 'change.constraintValidationAPI', changeHandler )
;
}
// INPUT validitationMessage
if ( typeof input[ 0 ].validationMessage !== 'string' ) {
// set us up the API
candidates.filter(function() {
return typeof this.validationMessage !== 'string';
}).each(function() {
this.validationMessage = '';
});
}
// INPUT checkValidity
if ( typeof input[ 0 ].checkValidity !== 'function' ) {
// set us up the API
candidates.filter(function() {
return typeof this.checkValidity !== 'function';
}).each(function() {
var domElement = this,
$this = $( this );
this.checkValidity = function() {
// TODO is this breaking .setCustomValidity() by passing NULL as 'message'
var valid = validateField.call( domElement );
// if invalid, and unless novalidate
if ( ! valid && ! $this.closest( 'form' ).attr( 'novalidate' )) {
// fire invalid event
$this.trigger( invalidEvent() );
}
return valid;
};
});
}
// INPUT setCustomValidity
if ( typeof input[ 0 ].setCustomValidity !== 'function' ) {
// set us up the API
candidates.filter(function() {
return typeof this.setCustomValidity !== 'function';
}).each(function() {
var that = this;
this.setCustomValidity = function( message ) {
validateField.call( that, message );
};
});
}
// check validity on submit
// this should be bound before all other submit handlers bound to the same form
// otherwise they will execute before this handler can cancel submit (oninvalid)
$( 'form' )
.unbind( 'submit.constraintValidationAPI' )
.bind( 'submit.constraintValidationAPI', submitHandler )
;
}
;
// run immediately and ondocumentready
initConstraintValidationAPI();
$( initConstraintValidationAPI );
// expose init function
window.initConstraintValidationAPI = initConstraintValidationAPI;
}( jQuery ));
}
|
JavaScript
| 0.999999 |
@@ -1598,17 +1598,16 @@
%09pattern
-;
%0D%0A%09%09%09;%0D%0A
|
7b8f120160effc066f1fa4d736f3b116f423264f
|
fix log message
|
poker-engine/game-loop.js
|
poker-engine/game-loop.js
|
'use strict';
const config = require('../config');
const logger = require('../storage/logger');
const save = require('../storage/storage').save;
const gameStatus = require('./domain/tournament-status');
const playerStatus = require('./domain/player-status');
const runSetupTasks = require('./setup-tasks');
const runTeardownTasks = require('./teardown-tasks');
const play = require('./bet-loop');
exports = module.exports = function* dealer(gs){
function sleep(time) {
return new Promise(res => setTimeout(res, time));
}
function waitResume() {
return new Promise(function(res, rej) {
const time = setInterval(function() {
if (gs.tournamentStatus == gameStatus.play){
res(clearInterval(time));
}
}, 5000);
});
}
while (gs.tournamentStatus != gameStatus.stop){
const activePlayers = gs.activePlayers;
const foldedPlayers = gs.players.filter(player => player.status == playerStatus.folded);
// when before a new hand starts,
// there is only one active player
// the current game is finished.
if (activePlayers.length + foldedPlayers.length === 1){
// each player takes points
// on the basis of their rank...
// then eventually a new game starts.
const playerCount = gs.gameChart.unshift(activePlayers[0].name);
const points = config.AWARDS[playerCount-2];
const finalGameChart = gs.gameChart.map((playerName, i) => ({ name: playerName, pts: points[i] }));
logger.info('Final ranks for game %d: %s', gs.gameProgressiveId, getRankingLogMessage(finalGameChart), { tag: gs.handUniqueId })
yield save({ type: 'points', tournamentId: gs.tournamentId, gameId: gs.gameProgressiveId, rank: finalGameChart });
// restore players' initial conditions
gs.players.forEach(player => { player.status = playerStatus.active; player.chips = config.BUYIN; });
gs.gameChart = null;
if (gs.tournamentStatus == gameStatus.latest || gs.gameProgressiveId == config.MAX_GAMES){
gs.tournamentStatus = gameStatus.stop;
continue;
}
// warm up
if (config.WARMUP){
if (gs.gameProgressiveId <= config.WARMUP.GAME){
yield sleep(config.WARMUP.WAIT);
}
}
// start a new game
gs.handProgressiveId = 1;
gs.gameProgressiveId++;
}
gs.handUniqueId = `${gs.pid}_${gs.tournamentId}_${gs.gameProgressiveId}-${gs.handProgressiveId}`;
logger.info('Starting hand %d/%d', gs.gameProgressiveId, gs.handProgressiveId, { tag: gs.handUniqueId });
//
// break here until the tournament is resumed
if (gs.tournamentStatus == gameStatus.pause){
logger.info('Pause on hand %d/%d', gs.gameProgressiveId, gs.handProgressiveId, { tag: gs.handUniqueId });
yield waitResume();
}
if (gs.tournamentStatus == gameStatus.play || gs.tournamentStatus == gameStatus.latest){
if (config.HANDWAIT){
yield sleep(config.HANDWAIT);
}
// setup the hand:
// restore the initial condition for a new hand, pot,
// blinds, ante, cards ...
runSetupTasks(gs);
yield save({ type: 'setup', handId: gs.handUniqueId, pot: gs.pot, sb: gs.sb, ante: gs.ante || 0, players: gs.players });
// play the game
// each player will be asked to make a bet,
// until only one player remains active, or
// the hand arrive to the "river" session
yield* play(gs);
// find the winner of the hand, eliminated players, ...
// and updates accordingly the gamestate
yield* runTeardownTasks(gs);
}
//
// this is the gs.handProgressiveId° hand played
// this info is important to compute the blinds level
gs.handProgressiveId++;
}
};
/**
* @private
* @function
* @name getRankingLogMessage
* @desc
* return a log of the final rankings
*
* @param {Array} players
* sorted list of the players, and points
*
* @returns {String}
*/
function getRankingLogMessage(ranking){
return ranking.reduce(function(msg, player) {
return msg += `${player.name}: ${player.pts}`, msg;
}, '').trim().slice(0,-1);
}
|
JavaScript
| 0.00001 |
@@ -4130,16 +4130,18 @@
yer.pts%7D
+,
%60, msg;%0A
|
a6a0bdff71339356352e21fc0ab02eccd9e76cbf
|
Fix select()
|
database.js
|
database.js
|
const pg = require('pg');
pg.defaults.ssl = true;
const db = new pg.Pool({
connectionString: process.env.DATABASE_URL,
});
class Predicate {
constructor(key, operator, value) {
this.key = key;
this.operator = operator;
this.value = value;
this.adjoined = [];
}
and(other) {
this.adjoined.push({
conj: 'AND',
obj: other,
});
return other;
}
or(other) {
this.adjoined.push({
conj: 'OR',
obj: other,
});
return other;
}
compile() {
let strVal = `&$${this.operator}$&$`;
const params = [this.key, this.value];
for (const adjoined of this.adjoined) {
const compiled = adjoined.compile();
if (adjoined.obj.adjoined.length > 0) {
strVal += ` ${adjoined.conj} (${compiled.strVal})`;
} else {
strVal += ` ${adjoined.conj} ${compiled.strVal}}`;
}
for (const param of compiled.params) {
params.push(param);
}
}
return {
strVal: strVal,
params: params,
source: this,
};
}
}
class QueryBuilder {
constructor(table, fields) {
this.table = table;
this.fields = fields;
this.predicate = null;
}
where(predicate) {
this.predicate = predicate;
return this;
}
execute() {
let query = `SELECT ${this.fields.map((f, i) => `$${i}`).join(', ')}` +
` FROM ${this.table.name}`;
if (this.predicate) {
const compiled = this.predicate.compile();
for (const param of compiled) {
this.fields.push(param);
}
let i = this.fields.length + 1;
compiled.strVal = compiled.strVal.replace('&$', () => i++);
query += ` WHERE ${compiled.strVal}`;
}
return this.table.db.query(query, this.fields);
}
}
class Table {
constructor(db, name) {
this.db = db;
this.name = name;
}
select(fields) {
return new QueryBuilder(this, fields);
}
insert(values) {
return this.db.query(`INSERT INTO ${this.name}` +
` VALUES(${values.map((p, i) => `$${i}`).join(', ')})`, values);
}
}
function getTable(name) {
return new Table(db, name);
}
const tables = ['users', 'sets', 'notes'].reduce((acc, cur) => {
acc[cur] = getTable(cur);
return acc;
}, {});
module.exports = {
Table: Table,
QueryBuilder: QueryBuilder,
Predicate: Predicate,
tables: tables,
db: db,
};
|
JavaScript
| 0 |
@@ -1883,20 +1883,63 @@
der(
-this, fields
+%0A this, Array.isArray(fields) ? fields : %5Bfields%5D)
);%0A
|
3b8ebf13a3190d4e3467d9799218c7d8512e77ee
|
disable ember/no-controller-access-in-routes
|
tests/dummy/app/routes/vr/360-image-gallery.js
|
tests/dummy/app/routes/vr/360-image-gallery.js
|
import Route from '@ember/routing/route';
import { scheduleOnce } from '@ember/runloop';
export default Route.extend({
_updateSrc(src) {
this.controller.set('skySrc', src);
},
actions: {
updateSrc(src) {
scheduleOnce('afterRender', this, this._updateSrc, src);
}
}
});
|
JavaScript
| 0 |
@@ -129,24 +129,93 @@
eSrc(src) %7B%0A
+ // eslint-disable-next-line ember/no-controller-access-in-routes%0A
this.con
|
4834a93ad5effbc4af086e2a5ff31db8d1219ca5
|
Update NotificationNode.js
|
NotificationNode.js
|
NotificationNode.js
|
define([ "dojo/text", "dojo/_base/declare", "dijit/_WidgetBase", "dijit/_TemplatedMixin", "dojo/dom-construct", "dGrowl/NotificationNode", "dojo/dom-class", "dojo/_base/event", "dojo/_base/lang"],
function(t, declare, base, templated, domCon, NotificationNode, domClass, event, lang)
{
return declare('dGrowl',
[base, templated],
{
'templateString':dojo.cache('dGrowl', 'NotificationNode.html'),
'title':'',
'message':'',
'duration':5000,
'sticky':false,
'stickyClass':'',
'constructor':function(a)
{
if(a.channel == undefined)
console.error('NotificationNode requires a "channel" definition!');
if(a.sticky === true)
this.stickyClass = 'dGrowl-notification-sticky';
},
'postCreate':function()
{
this.inherited(arguments);
if(this.sticky === false)
setTimeout(lang.hitch(this, this.killme), this.duration);
},
'show':function()
{
var v = this.domNode.clientHeight; // trigger reflow so transition animates... hack!!!!!!!
domClass.add(this.domNode, 'dGrowl-visible');
this.onShow(this);
},
'onShow':function(){},
'onHide':function(){},
'killme':function(evt)
{
if(evt)
event.stop(evt);
// delay on destroy for animation to do its thing...
domClass.remove(this.domNode, 'dGrowl-visible');
setTimeout(lang.hitch(this, this.destroy),1100);
this.onHide(this);
}
});
});
|
JavaScript
| 0.000001 |
@@ -187,16 +187,53 @@
se/lang%22
+, %22dojo/text!./NotificationNode.html%22
%5D,%0A%09 f
@@ -316,16 +316,32 @@
nt, lang
+, templateString
)%0A%7B%0A%09ret
@@ -408,53 +408,22 @@
ng':
-dojo.cache('dGrowl', 'NotificationNode.html')
+templateString
,%0A%09%09
|
01a7158f05dbce623c5f31a5e21e0316f2ba4403
|
Remove debug prints
|
app/scripts/groonga-client/response/table-list.js
|
app/scripts/groonga-client/response/table-list.js
|
'use strict';
(function() {
function TableList(rawData) {
GroongaClient.Response.Base.call(this, rawData);
}
GroongaClient.Response.TableList = TableList;
TableList.prototype = Object.create(GroongaClient.Response.Base.prototype);
TableList.prototype.constructor = TableList;
TableList.prototype.parameters = function() {
return this.body()[0].map(function(parameter) {
return {
name: parameter[0],
type: parameter[1]
};
});
};
TableList.prototype.tables = function() {
var parameters = this.parameters();
console.log(this.body());
console.log(this.body()[1]);
console.log(this.body().slice(1));
return this.body().slice(1).map(function(tableProperties) {
var table = {};
parameters.forEach(function(parameter, index) {
table[parameter.name] = tableProperties[index];
});
return table;
});
};
})();
|
JavaScript
| 0.000001 |
@@ -567,110 +567,8 @@
();%0A
- console.log(this.body());%0A console.log(this.body()%5B1%5D);%0A console.log(this.body().slice(1));%0A
|
99c38244ddba3342425dbe50332f216a62c97ecc
|
Fix bug in Delving search. Filter on viewport can now be turned off.
|
app/scripts/plugins/delving/delving-collection.js
|
app/scripts/plugins/delving/delving-collection.js
|
define(['backbone', 'backbone.pageable.collection', 'config', 'models/marker'],
function(Backbone, PageableCollection, Config, ResultModel) {
var DelvingResultModel = ResultModel.extend({
parse: function(res) {
var fields = res.item.fields;
var f = {
title: fields.dc_title,
description: fields.dc_description,
latitude: fields.delving_locationLat,
longitude: fields.delving_locationLong
};
// Image
var img = _.find( fields.delving_resourceUri, function( resource ) {
var imageRegex = /.*\.(jpg|jpeg)$/;
return imageRegex.test(resource);
});
if (img) f.image = img;
// Youtube
var youtube = _.find( fields.delving_resourceUri, function( resource ) {
var reg = /youtube\.com/;
return reg.test(resource);
});
if (youtube) {
var reg = /v=([^&]*)/;
if ( youtube.match(reg ) ) {
f.image = "http://img.youtube.com/vi/" + youtube.match(reg)[1] + "/0.jpg";
f.youtubeid = youtube.match( reg )[1];
}
f.youtube = youtube;
}
return f;
}
});
return PageableCollection.extend({
hasPrevious: function() {
return this.hasPreviousPage();
},
hasNext: function() {
return this.hasNextPage();
},
model: DelvingResultModel,
queryParams: {
currentPage: null,
pageSize: null,
format: 'json',
pt: function() {
return this.state.lat + ',' + this.state.lng;
},
d: function() {
return Math.round(this.state.searchDistance);
},
sfield: "delving_locationLatLong_location",
query: function() {
return this.state.terms;
},
start: function() {
return (this.state.currentPage - this.state.firstPage) * this.state.pageSize;
}
},
parseRecords: function(resp) {
return resp.result.items;
},
parseState: function(resp) {
return {
pagination: resp.result.pagination,
facets: resp.result.facets,
totalRecords: resp.result.pagination.numFound
}
},
state: {
d: 100,
firstPage: 1,
terms: "*"
},
url: Config.delving.uri + '/search'
});
});
|
JavaScript
| 0 |
@@ -1553,32 +1553,91 @@
return
+ _.isNumber(this.state.lat) && _.isNumber(this.state.lat) ?
this.state.lat
@@ -1658,16 +1658,23 @@
tate.lng
+ : null
;%0A
@@ -1718,16 +1718,56 @@
return
+ _.isNumber(this.state.searchDistance) ?
Math.ro
@@ -1796,16 +1796,23 @@
istance)
+ : null
;%0A
|
83070eb394cf8464f7da355887f7ef91149205b2
|
Change image size when fitting to container.
|
source/edgecase.js
|
source/edgecase.js
|
Edgecase = new JS.Module('Edgecase', {
include: Ojay.Observable,
_visible: true,
setElement: function(element) {
this._element = Ojay(element);
return this;
},
setContainer: function(container) {
this._container = container ? Ojay(container) : null;
return this;
},
setAspectRatio: function(ratio) {
this._aspectRatio = ratio;
return this;
},
getAspectRatio: function() {
return this._aspectRatio;
},
setup: function() {
Ojay(window).on('resize', function() {
if (this._visible) {
this.fitToContainer();
}
}, this);
this.fitToContainer();
this.notifyObservers('load', this);
return this;
},
show: function() {
if (this._visible) return;
this.fitToContainer();
this._element.show();
this._visible = true;
this.notifyObservers('show', this);
return this;
},
hide: function() {
if (!this._visible) return;
this._element.hide();
this._visible = false;
this.notifyObservers('hide', this);
return this;
},
getHTML: function() {
return this._element;
},
fitToContainer: function() {
if (this._container) {
this.fitToContainerXY(this._container.getWidth(), this._container.getHeight());
} else {
this.fitToViewport();
}
return this;
},
fitToViewport: function() {
var portsize = Ojay.getViewportSize();
this.fitToContainerXY(portsize.width, portsize.height);
return this;
},
fitToContainerXY: function(containerWidth, containerHeight) {
var containerAspectRatio = containerWidth / containerHeight,
style = {display: 'block', position: 'absolute'},
x, y;
if (containerAspectRatio > this.getAspectRatio()) {
y = containerWidth / this.getAspectRatio();
style.width = containerWidth + 'px';
style.height = Math.ceil(y) + 'px';
style.left = 0;
style.top = Math.ceil((containerHeight - y) / 2) + 'px';
} else {
x = containerHeight * this.getAspectRatio();
style.width = Math.ceil(x) + 'px';
style.height = containerHeight + 'px';
style.left = Math.ceil((containerWidth - x) / 2) + 'px';
style.top = 0;
}
this._element.setStyle(style);
}
});
Edgecase.Concrete = new JS.Class('Edgecase.Concrete', {
include: Edgecase,
initialize: function(image, options) {
var ratio, html, x, y;
options = options || {};
this.setElement(image);
this.setContainer(options.container);
this.getHTML().setStyle({display: 'block'});
if (options.aspectRatio) {
ratio = options.aspectRatio;
} else {
html = this.getHTML();
x = html.getWidth();
y = html.getHeight();
ratio = x / y;
}
this.setAspectRatio(ratio);
}
});
|
JavaScript
| 0 |
@@ -427,32 +427,72 @@
ratio;%0A %0A
+ this.fitToContainer();%0A %0A
return t
|
ffc73854bf71434c3a673dbdad22467057d32f2c
|
fix value month
|
src/garment-master-plan/weekly-plan-item.js
|
src/garment-master-plan/weekly-plan-item.js
|
'use strict';
var BaseModel = require('model-toolkit').BaseModel;
module.exports = class WeeklyPlanItem extends BaseModel {
constructor(source, type) {
super(type || 'weekly-plan-item', '1.0.0');
this.weekNumber = {};
this.startDate = new Date();
this.endDate = new Date();
this.month = 1;
this.copy(source);
}
};
|
JavaScript
| 0.000001 |
@@ -326,17 +326,17 @@
month =
-1
+0
;%0A
|
8ba12c9d0dac87514354b1f0e5251e08fa6aee2d
|
remove js for removed elements
|
website/static/landing.js
|
website/static/landing.js
|
"use strict";
if (location.hash.slice(1).startsWith(encodeURIComponent("{"))) {
location.pathname = "/playground/";
}
window.addEventListener("load", () => {
// We don't have access to a unique body css attribute for just the homepage
// so instead it is set on load. It's only really visible on a vertical overscroll
document.body.style.backgroundColor = "rgb(24, 32, 37)";
const logoWrapper = document.querySelector(".animatedLogoWrapper");
const logo = document.querySelector(".prettier-logo-wide");
const lastDash = logo.querySelector("g:last-of-type path:last-of-type");
function handleLogoDrag(event) {
logo.classList.add("rolling");
event.preventDefault();
}
logoWrapper.setAttribute("draggable", "true");
logoWrapper.addEventListener("touchstart", handleLogoDrag);
logoWrapper.addEventListener("dragstart", handleLogoDrag);
lastDash.addEventListener("animationend", (event) => {
if (/roll/.test(event.animationName)) {
logo.classList.remove("rolling");
}
});
const yarnButton = document.querySelector(".showYarnButton");
const npmButton = document.querySelector(".showNpmButton");
const getStartedSection = document.querySelector(".getStartedSection");
npmButton.addEventListener("click", (event) => {
event.preventDefault();
npmButton.classList.add("active");
yarnButton.classList.remove("active");
getStartedSection.classList.add("getStartedSection--npm");
});
yarnButton.addEventListener("click", (event) => {
event.preventDefault();
yarnButton.classList.add("active");
npmButton.classList.remove("active");
getStartedSection.classList.remove("getStartedSection--npm");
});
});
|
JavaScript
| 0.000001 |
@@ -1019,674 +1019,8 @@
%7D);
-%0A%0A const yarnButton = document.querySelector(%22.showYarnButton%22);%0A const npmButton = document.querySelector(%22.showNpmButton%22);%0A const getStartedSection = document.querySelector(%22.getStartedSection%22);%0A%0A npmButton.addEventListener(%22click%22, (event) =%3E %7B%0A event.preventDefault();%0A npmButton.classList.add(%22active%22);%0A yarnButton.classList.remove(%22active%22);%0A getStartedSection.classList.add(%22getStartedSection--npm%22);%0A %7D);%0A yarnButton.addEventListener(%22click%22, (event) =%3E %7B%0A event.preventDefault();%0A yarnButton.classList.add(%22active%22);%0A npmButton.classList.remove(%22active%22);%0A getStartedSection.classList.remove(%22getStartedSection--npm%22);%0A %7D);
%0A%7D);
|
c34db47c0cf405207a2385bf2fba567c75a50bb2
|
fix prettier loading
|
website/static/worker2.js
|
website/static/worker2.js
|
/* eslint-env worker */
/* eslint no-var: off, strict: off */
// "Polyfills" in order for all the code to run
self.global = self;
self.util = {};
self.path = {};
self.Buffer = {
isBuffer: function() {
return false;
}
};
self.constants = {};
// eslint-disable-next-line
module$1 = module = path = os = crypto = {};
self.fs = { readFile: function() {} };
// eslint-disable-next-line no-undef
os.homedir = function() {
return "/home/prettier";
};
self.process = { argv: [], env: { PRETTIER_DEBUG: true }, version: "v8.5.0" };
self.assert = { ok: function() {}, strictEqual: function() {} };
self.require = function require(path) {
if (path === "stream") {
return { PassThrough() {} };
}
if (path === "./third-party") {
return {};
}
if (~path.indexOf("parser-")) {
var parser = path.replace(/.+-/, "");
if (!parsersLoaded[parser]) {
importScripts("lib/parser-" + parser + ".js");
parsersLoaded[parser] = true;
}
return self[parser];
}
return self[path];
};
importScripts("lib/index.js");
var prettier = index; // eslint-disable-line
var parsersLoaded = {};
self.onmessage = function(event) {
var uid = event.data.uid;
var message = event.data.message;
switch (message.type) {
case "meta":
self.postMessage({
uid: uid,
message: {
type: "meta",
supportInfo: prettier.getSupportInfo("1.9.0"),
version: prettier.version
}
});
break;
case "format":
var options = message.options || {};
delete options.ast;
delete options.doc;
delete options.output2;
self.postMessage({
uid: uid,
message: {
formatted: formatCode(message.code, options)
}
});
break;
}
};
function formatCode(text, options) {
try {
return prettier.format(text, options);
} catch (e) {
return String(e);
}
}
|
JavaScript
| 0.000002 |
@@ -1010,16 +1010,30 @@
h%5D;%0A%7D;%0A%0A
+var prettier;%0A
importSc
@@ -1055,19 +1055,149 @@
x.js%22);%0A
-var
+if (typeof prettier === %22undefined%22) %7B%0A prettier = module.exports; // eslint-disable-line%0A%7D%0Aif (typeof prettier === %22undefined%22) %7B%0A
prettie
@@ -1229,16 +1229,18 @@
ble-line
+%0A%7D
%0A%0Avar pa
|
af37db0d88d0157cdace75036e2fde4c62f20807
|
support newer formSelect() method
|
app/assets/javascripts/materialize-form.js
|
app/assets/javascripts/materialize-form.js
|
window.materializeForm = {
init: function() {
this.initSelect()
this.initCheckbox()
this.initDate()
},
initSelect: function() {
$('select[multiple="multiple"] option[value=""]').attr('disabled', true)
$('select').material_select()
},
initCheckbox: function() {
$('input[type=checkbox]').addClass('filled-in')
},
initDate: function() {
$('input.date').pickadate({
selectMonths: true,
selectYears: 100
});
}
}
$(document).ready(function() {
window.materializeForm.init()
});
$(document).ajaxSuccess(function() {
window.materializeForm.init()
});
|
JavaScript
| 0 |
@@ -224,37 +224,151 @@
-$('select').material_select()
+if (typeof $('select').material_select === %22function%22) %7B%0A $('select').material_select()%0A %7D else %7B%0A $('select').formSelect()%0A %7D%0A
%0A %7D
|
8b0d37ca9e75f33c359fcf3b63532f3a76e50e5e
|
rename `log geth` cmd to log blockchain
|
src/lib/modules/blockchain_process/index.js
|
src/lib/modules/blockchain_process/index.js
|
const async = require('async');
const utils = require('../../utils/utils.js');
const constants = require('../../constants');
const BlockchainProcessLauncher = require('./blockchainProcessLauncher');
class BlockchainModule {
constructor(embark, options) {
this.logger = embark.logger;
this.events = embark.events;
this.blockchainConfig = embark.config.blockchainConfig;
this.contractsConfig = embark.config.contractsConfig;
this.embark = embark;
this.locale = options.locale;
this.isDev = options.isDev;
this.ipc = options.ipc;
this.client = options.client;
this.registerBlockchainProcess();
}
registerBlockchainProcess() {
const self = this;
this.events.request('processes:register', 'blockchain', (cb) => {
self.assertNodeConnection(true, (connected) => {
if (connected) return cb();
self.startBlockchainNode(cb);
this.listenToCommands();
this.registerConsoleCommands();
});
});
if (!this.ipc.isServer()) return;
self.ipc.on('blockchain:node', (_message, cb) => {
cb(null, utils.buildUrlFromConfig(self.contractsConfig.deployment));
});
}
listenToCommands() {
this.events.setCommandHandler('logs:ethereum:turnOn', (cb) => {
this.events.emit('logs:ethereum:enable');
return cb(null, 'Enabling Geth logs');
});
this.events.setCommandHandler('logs:ethereum:turnOff', (cb) => {
this.events.emit('logs:ethereum:disable');
return cb(null, 'Disabling Geth logs');
});
}
registerConsoleCommands() {
const self = this;
self.embark.registerConsoleCommand((cmd, _options) => {
return {
match: () => cmd === 'log geth on',
process: (cb) => self.events.request('logs:ethereum:turnOn', cb)
};
});
self.embark.registerConsoleCommand((cmd, _options) => {
return {
match: () => cmd === 'log geth off',
process: (cb) => self.events.request('logs:ethereum:turnOff', cb)
};
});
}
assertNodeConnection(noLogs, cb) {
if (typeof noLogs === 'function') {
cb = noLogs;
noLogs = false;
}
const self = this;
async.waterfall([
function checkWeb3State(next) {
self.events.request("blockchain:web3:isReady", (connected) => {
if (connected) {
return next(connected);
}
next();
});
},
function pingEndpoint(next) {
if (!self.contractsConfig || !self.contractsConfig.deployment || !self.contractsConfig.deployment.host) {
return next();
}
const {host, port, type, protocol} = self.contractsConfig.deployment;
utils.pingEndpoint(host, port, type, protocol, self.blockchainConfig.wsOrigins.split(',')[0], next);
}
], function(err) {
if (err === true || err === undefined) {
return cb(true);
}
return cb(false);
});
}
startBlockchainNode(callback) {
const self = this;
let blockchainProcess = new BlockchainProcessLauncher({
events: self.events,
logger: self.logger,
normalizeInput: utils.normalizeInput,
blockchainConfig: self.blockchainConfig,
locale: self.locale,
client: self.client,
isDev: self.isDev,
embark: this.embark
});
blockchainProcess.startBlockchainNode();
self.events.once(constants.blockchain.blockchainReady, () => {
callback();
});
self.events.once(constants.blockchain.blockchainExit, () => {
callback();
});
}
}
module.exports = BlockchainModule;
|
JavaScript
| 0.000341 |
@@ -1695,20 +1695,26 @@
== 'log
-geth
+blockchain
on',%0A
@@ -1915,12 +1915,18 @@
log
-geth
+blockchain
off
|
0fe441729dfdbc18f0394cb0658b10a5bb70d6fc
|
Remove empty stop array check
|
source/ratp/api.js
|
source/ratp/api.js
|
const TOKEN = "FvChCBnSetVgTKk324rO";
const API_HOST = "http://apixha.ixxi.net";
import RatpApiError from "~/common/errors/RatpApiError";
import BogusRatpApiResponseError from "~/common/errors/BogusRatpApiResponseError";
let promisify = require("promisify-node");
let _ = require("lodash");
let needle = promisify(require("needle"));
let moduleLogger = log.child({ component: "ratp/api" });
const ONE_SECOND = 1000;
const TTL = 5 * ONE_SECOND;
let cache = {};
let addToCache = (url, response) => {
let now = new Date();
cache[url] = {
promise: Promise.resolve(response),
date: now,
validUntil: new Date(now.getTime() + TTL),
};
};
let validateNextStops = (nextStops) => {
let now = new Date();
if (!Array.isArray(nextStops)) {
let err = new BogusRatpApiResponseError("nextStops isn't an array?!?");
moduleLogger.warn({ nextStops }, err);
throw err;
}
// the API sometimes returns an empty array for some reason
if (!nextStops.length && now.getHours() > 6) {
let err = new BogusRatpApiResponseError("No trains but there should be");
moduleLogger.debug(err);
throw err;
}
nextStops.forEach((stop) => {
if (stop.waitingTime == null) {
return;
}
if (stop.waitingTimeRaw === "Service termine"
|| stop.waitingTimeRaw === "Train arrete") {
return;
}
if (stop.waitingTime < -60) {
moduleLogger.debug({ stop }, "Bogus data from the RATP API: waitingTime < -60");
throw new BogusRatpApiResponseError("waitingTime < -60");
}
let stopTime = new Date(stop.nextStopTime).getTime();
let minutesUntilStop = Math.ceil((stopTime - now) / 1000 / 60);
if (minutesUntilStop < -1 || minutesUntilStop > 120) {
moduleLogger.debug({ stop }, "Bogus data from the RATP API: impossible nextStopTime");
throw new BogusRatpApiResponseError("impossible nextStopTime");
}
});
};
let ratpApi = {
async query(details, validateFn = () => {}) {
const url = `${API_HOST}/APIX?keyapp=${TOKEN}` +
"&" + details +
`&withText=true&apixFormat=json`;
let logger = moduleLogger.child({ url });
if (cache[url] && new Date().getTime() < cache[url].validUntil.getTime()) {
return cache[url].promise;
}
if (cache[url] && new Date().getTime() > cache[url].validUntil.getTime()) {
delete cache[url];
}
try {
let response = await needle.get(url);
logger = logger.child({ response: response.body });
let data;
try {
data = JSON.parse(response.body);
} catch (error) {
error.message = "Failed to parse response: " + error.message;
logger.error({ error, response }, "Failed to parse response");
return Promise.reject(error);
}
if (!data) {
logger.error("No data returned from the RATP API");
return Promise.reject(new BogusRatpApiResponseError("no data returned"));
}
if (data.errorMsg) {
logger.error({ error: data.errorMsg }, "The RATP API returned an error");
return Promise.reject(new RatpApiError(data.errorMsg));
}
validateFn(data);
addToCache(url, data);
return data;
} catch (error) {
logger.error(error, "Failed to query the RATP API");
error.statusCode = 503;
return Promise.reject(error);
}
},
async queryNextStops(stationId, lineId, directionId) {
let now = new Date().getTime();
let response = await ratpApi.query(`cmd=getNextStopsRealtime` +
`&stopArea=${stationId}&line=${lineId}&direction=${directionId}`,
data => validateNextStops(data.nextStopsOnLines[0].nextStops));
let stops = response.nextStopsOnLines[0].nextStops
.filter((stop) => stop.bStopInStation && stop.waitingTime != null && stop.nextStopTime
&& stop.waitingTimeRaw !== "Service termine"
&& stop.waitingTimeRaw !== "Train arrete")
.map((stop) => {
let stopTime = new Date(stop.nextStopTime).getTime();
let minutesUntilStop = Math.ceil((stopTime - now) / 1000 / 60);
let message = minutesUntilStop + " min";
if (message === "1 mins") {
message = "1 min";
}
if (stop.waitingTimeRaw === "Train a l'approche"
|| stop.waitingTime === -60
|| message === "0 mins") {
message = "< 1 min";
}
if (stop.waitingTimeRaw === "Train a quai"
|| stop.waitingTimeRaw === "A l'arret"
|| stop.waitingTimeRaw === "A quai") {
message = "À quai";
}
if (stop.waitingTimeRaw === "Train retarde") {
message += " +";
}
return {
destination: stop.destinationName,
waitingTime: stop.waitingTime,
nextStopTime: stop.nextStopTime,
rawMessage: stop.waitingTimeRaw,
message,
delayed: stop.waitingTimeRaw === "Train retarde",
};
});
return stops;
},
async queryIssues(query = "networkType=all&category=all") {
let events = await ratpApi.query(`cmd=getTrafficSituation&${query}`);
let issues = [];
events.events
.filter((event) => !!event.incidents)
.forEach((event) => {
issues = _.union(issues, event.incidents);
}) || [];
return issues;
},
};
export default ratpApi;
|
JavaScript
| 0 |
@@ -889,245 +889,8 @@
%7D%0A
- // the API sometimes returns an empty array for some reason%0A if (!nextStops.length && now.getHours() %3E 6) %7B%0A let err = new BogusRatpApiResponseError(%22No trains but there should be%22);%0A moduleLogger.debug(err);%0A throw err;%0A %7D%0A
ne
|
38feed2328ad5cda296a2009ccb089fe8613ed51
|
remove erroneous quotes in tryCatch documentation (#2765)
|
source/tryCatch.js
|
source/tryCatch.js
|
import _arity from './internal/_arity';
import _concat from './internal/_concat';
import _curry2 from './internal/_curry2';
/**
* `tryCatch` takes two functions, a `tryer` and a `catcher`. The returned
* function evaluates the `tryer`; if it does not throw, it simply returns the
* result. If the `tryer` *does* throw, the returned function evaluates the
* `catcher` function and returns its result. Note that for effective
* composition with this function, both the `tryer` and `catcher` functions
* must return the same type of results.
*
* @func
* @memberOf R
* @since v0.20.0
* @category Function
* @sig (...x -> a) -> ((e, ...x) -> a) -> (...x -> a)
* @param {Function} tryer The function that may throw.
* @param {Function} catcher The function that will be evaluated if `tryer` throws.
* @return {Function} A new function that will catch exceptions and send then to the catcher.
* @example
*
* R.tryCatch(R.prop('x'), R.F)({x: true}); //=> true
* R.tryCatch(() => { throw 'foo'}, R.always('catched'))('bar') // => 'catched'
* R.tryCatch(R.times(R.identity), R.always([]))('s') // => []
`` */
var tryCatch = _curry2(function _tryCatch(tryer, catcher) {
return _arity(tryer.length, function() {
try {
return tryer.apply(this, arguments);
} catch (e) {
return catcher.apply(this, _concat([e], arguments));
}
});
});
export default tryCatch;
|
JavaScript
| 0 |
@@ -1126,11 +1126,8 @@
%5B%5D%0A
- %60%60
*/%0A
|
cf7364384822c4f7fe400c0d560de8a76eafc11a
|
add comments
|
app/controllers/timestampHandler.server.js
|
app/controllers/timestampHandler.server.js
|
'use strict';
module.exports = function (req, res) {
var timestamp = {
unix: null,
natural: null
};
var param = decodeURIComponent(req.url.substring(1)); //ignore leading /
var num = Number(param);
var re = /^([a-z]+) ([0-9]+), ([0-9]+)$/i;
var date;
if ((num || num === 0) && Number.isSafeInteger(num)) {
date = new Date(num);
timestamp.unix = date.valueOf();
timestamp.natural = dateToString(date);
} else if (re.test(param)) {
date = new Date(0);
var array = re.exec(param);
var monthVal = monthToInt(array[1]);
if(monthVal !== -1) {
date.setUTCFullYear(array[3], monthVal, array[2]);
timestamp.unix = date.valueOf();
timestamp.natural = dateToString(date);
}
}
res.json(timestamp);
};
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/*
Returns the month value of a string. Uses the month array and ignores case.
Returns -1 if the string does not equal any month.
*/
function monthToInt (str) {
for(var i = 0; i < month.length; i++){
if(str.toUpperCase() == month[i].toUpperCase()) {
return i;
}
}
return -1;
}
/*
Returns a natural language date string (example: January 1, 2016).
*/
function dateToString(date) {
return month[date.getUTCMonth()] + " " + date.getUTCDate() + ", " + date.getUTCFullYear();
}
|
JavaScript
| 0 |
@@ -350,24 +350,64 @@
ger(num)) %7B%0A
+ //param is a unix timetimestamp%0A
date
@@ -551,24 +551,67 @@
t(param)) %7B%0A
+ //param is a natural language date%0A
date
|
7ba4c5802e31e125b939f03437c2eed7f0104613
|
add comment
|
app/controllers/timestampHandler.server.js
|
app/controllers/timestampHandler.server.js
|
'use strict';
module.exports = function (req, res) {
var timestamp = {
unix: null,
natural: null
};
var param = decodeURIComponent(req.url.substring(1));
var num = Number(param);
var re = /^([a-z]+) ([0-9]+), ([0-9]+)$/i;
var date;
if ((num || num === 0) && Number.isSafeInteger(num)) {
date = new Date(num);
timestamp.unix = date.valueOf();
timestamp.natural = dateToString(date);
} else if (re.test(param)) {
date = new Date(0);
var array = re.exec(param);
var monthVal = monthToInt(array[1]);
if(monthVal !== -1) {
date.setUTCFullYear(array[3], monthVal, array[2]);
timestamp.unix = date.valueOf();
timestamp.natural = dateToString(date);
}
}
res.json(timestamp);
};
var month = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
/*
Returns the month value of a string. Uses the month array and ignores case.
Returns -1 if the string does not equal any month.
*/
function monthToInt (str) {
for(var i = 0; i < month.length; i++){
if(str.toUpperCase() == month[i].toUpperCase()) {
return i;
}
}
return -1;
}
/*
Returns a natural language date string (example: January 1, 2016).
*/
function dateToString(date) {
return month[date.getUTCMonth()] + " " + date.getUTCDate() + ", " + date.getUTCFullYear();
}
|
JavaScript
| 0 |
@@ -180,16 +180,35 @@
ing(1));
+ //ignore leading /
%0A var
|
262ee2e45a0393395c22fc4961532544afc6f8ad
|
Fix MySQLDatabaseManager#truncateDb to include ignoreTables
|
lib/MySqlDatabaseManager.js
|
lib/MySqlDatabaseManager.js
|
var DatabaseManager = require('./DatabaseManager').default
, classUtils = require('./class-utils')
, mysql = require('mysql')
, Promise = require('bluebird')
, _ = require('lodash');
/**
* @constructor
* @extends DatabaseManager
*
* Notes:
* - Even though the method signature implicates that _masterConnectionUrl returns
* an URL string, it actually returns an object because MySQL node lib
* assumes that the database name is defined in the URL format.
*
*/
function MySqlDatabaseManager() {
DatabaseManager.apply(this, arguments);
this._masterClient = null;
this._cachedTableNames = null;
}
classUtils.inherits(MySqlDatabaseManager, DatabaseManager);
/**
* @Override
*/
MySqlDatabaseManager.prototype.createDbOwnerIfNotExist = function() {
return this._masterQuery("CREATE USER IF NOT EXISTS ?@'%' IDENTIFIED BY ?", [this.config.knex.connection.user, this.config.knex.connection.password])
};
/**
* @Override
*/
MySqlDatabaseManager.prototype.createDb = function(databaseName) {
databaseName = databaseName || this.config.knex.connection.database;
var collate = this.config.dbManager.collate;
var owner = this.config.knex.connection.user;
var self = this;
var promise = Promise.reject();
if (_.isEmpty(collate)) {
promise = promise.catch(function () {
return self._masterQuery("CREATE DATABASE ?? DEFAULT CHARACTER SET utf8 DEFAULT COLLATE utf8_general_ci", [databaseName]);
});
} else {
// Try to create with each collate. Use the first one that works. This is kind of a hack
// but seems to be the only reliable way to make this work with both windows and unix.
_.each(collate, function(locale) {
promise = promise.catch(function() {
return self._masterQuery("CREATE DATABASE ?? DEFAULT CHARACTER SET utf8 DEFAULT COLLATE ?", [databaseName, locale]);
});
});
}
promise = promise.then(function () {
return self._masterQuery('GRANT ALL PRIVILEGES ON ??.* TO ??', [databaseName, owner]);
});
return promise;
};
/**
* Drops database with name if db exists.
*
* @Override
*/
MySqlDatabaseManager.prototype.dropDb = function(databaseName) {
databaseName = databaseName || this.config.knex.connection.database;
return this._masterQuery("DROP DATABASE IF EXISTS ??", [databaseName]);
};
/**
* @Override
*/
MySqlDatabaseManager.prototype.truncateDb = function(ignoreTables) {
var knex = this.knexInstance();
var config = this.config;
if (!this._cachedTableNames) {
this._updateTableNameCache(knex, config);
}
return this._cachedTableNames.then(function (tableNames) {
if (!_.isEmpty(tableNames)) {
return knex.transaction(function(trx) {
return knex.raw('SET FOREIGN_KEY_CHECKS = 0').transacting(trx)
.then(function() {
return Promise.map(tableNames, function(tableName) {
return knex.table(tableName).truncate().transacting(trx);
}, {concurrency: 1});
});
});
}
});
};
/**
* @private
*/
MySqlDatabaseManager.prototype._updateTableNameCache = function(knex, config) {
this._cachedTableNames = knex('information_schema.tables')
.select('table_name')
.where('table_schema', config.knex.connection.database)
.then(function (tables) {
return _.without(_.map(tables, 'table_name'), config.knex.migrations.tableName);
});
};
/**
* @Override
*/
MySqlDatabaseManager.prototype.close = function() {
var disconnectAll = [this.closeKnex()];
if (this._masterClient) {
disconnectAll.push(this._masterClient.then(function(client) {
client.end();
}));
this._masterClient = null;
}
return Promise.all(disconnectAll);
};
/**
* @private
* @returns {Promise}
*/
MySqlDatabaseManager.prototype._masterQuery = function(query, params) {
var self = this;
if (!this._masterClient) {
this._masterClient = this.create_masterClient();
}
return this._masterClient.then(function(client) {
return self.perform_masterQuery(client, query, params);
});
};
/**
* @private
* @returns {Promise}
*/
MySqlDatabaseManager.prototype.create_masterClient = function() {
var self = this;
return new Promise(function(resolve, reject) {
var client = mysql.createConnection(self._masterConnectionUrl());
client.connect(function(err) {
if (err) {
reject(err);
} else {
resolve(client);
}
});
});
};
/**
* @private
* @returns {Promise}
*/
MySqlDatabaseManager.prototype.perform_masterQuery = function(client, query, params) {
return new Promise(function(resolve, reject) {
if (params) {
query = mysql.format(query, params);
}
client.query(query, function(err, result) {
if (err) {
reject(err);
} else {
resolve(result);
}
});
});
};
/**
* @private
* @returns {String}
*/
MySqlDatabaseManager.prototype._masterConnectionUrl = function() {
return {
host : this.config.knex.connection.host,
port : this.config.knex.connection.port || 3306,
user : this.config.dbManager.superUser,
password : this.config.dbManager.superPassword
};
};
module.exports = {
default: MySqlDatabaseManager,
MySqlDatabaseManager: MySqlDatabaseManager
};
|
JavaScript
| 0.000001 |
@@ -2784,32 +2784,177 @@
en(function() %7B%0A
+ // ignore the tables based on %60ignoreTables%60%0A var filteredTables = _.differenceWith(tableNames, ignoreTables, _.isEqual);%0A
retu
@@ -2968,24 +2968,28 @@
ise.map(
-tableNam
+filteredTabl
es, func
|
9229b6ff89b8bf7a341bf890e841bd5a3e4c7e49
|
Add missing self
|
app/geobox/web/static/js/widgets/filter.js
|
app/geobox/web/static/js/widgets/filter.js
|
gbi.widgets = gbi.widgets || {};
gbi.widgets.Filter = function(editor, options) {
var self = this;
this.options = $.extend({}, options);
this.element = $('#' + this.options.element);
this.editor = editor;
this.render();
$(gbi).on('gbi.layermanager.layer.active', function() {
self.render();
});
};
gbi.widgets.Filter.prototype = {
render: function() {
var self = this
self.element.empty().append(tmpl(gbi.widgets.Filter.template, {srs: self.options.srs}));
var layer = self.editor.layerManager.active()
if(layer) {
if(layer._filterWidget !== undefined) {
self.fillFields(layer._filterWidget['attr'], layer._filterWidget['value']);
}
$('#setFilter').click(function() {
var attr = $('#filterAttr').val();
var value = $('#filterValue').val();
self.setFilter(attr, value);
$(layer).on('gbi.layer.vector.unstoredFeature', self.clearFields)
});
} else {
$('#setFilter').attr('disabled', 'disabled');
}
},
fillFields: function(attr, value) {
var self = this;
self.element.find('#filterAttr').val(attr);
self.element.find('#filterValue').val(value);
},
clearFields: function(event, layer) {
self.element.find('#filterAttr').val('');
self.element.find('#filterValue').val('');
delete layer._filterWidget;
},
setFilter: function(attr, value) {
var self = this;
var layer = self.editor.layerManager.active();
layer.clearStoredFeatures();
layer.selectByPropertyValue(attr, value);
layer._filterWidget = {'attr': attr, 'value': value};
return false;
}
};
var filterLabel = {
'key': OpenLayers.i18n('key'),
'val': OpenLayers.i18n('value'),
'loadFilter': OpenLayers.i18n('loadFilter')
}
gbi.widgets.Filter.template = '\
<form class="form-horizontal"> \
<div class="control-group">\
<label for="filterAttr" class="control-label">'+filterLabel.key + ':</label>\
<div class="controls"> \
<input type="text" id="filterAttr" class="input-small" />\
</div>\
</div>\
<div class="control-group">\
<label for="filterValue" class="control-label">'+filterLabel.val + ':</label>\
<div class="controls"> \
<input type="text" id="filterValue" class="input-small" />\
</div>\
</div>\
<button id="setFilter" class="btn btn-small" type="button">'+filterLabel.loadFilter+'</button>\
</div>\
</form>\
';
|
JavaScript
| 0.99904 |
@@ -1339,32 +1339,57 @@
event, layer) %7B%0A
+ var self = this;%0A
self.ele
|
24b2c60beb73ff932b9539587e162283e99fd35d
|
Fix icons having an image role (#20600)
|
app/javascript/mastodon/components/icon.js
|
app/javascript/mastodon/components/icon.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class Icon extends React.PureComponent {
static propTypes = {
id: PropTypes.string.isRequired,
className: PropTypes.string,
fixedWidth: PropTypes.bool,
};
render () {
const { id, className, fixedWidth, ...other } = this.props;
return (
<i role='img' className={classNames('fa', `fa-${id}`, className, { 'fa-fw': fixedWidth })} {...other} />
);
}
}
|
JavaScript
| 0 |
@@ -386,19 +386,8 @@
%3Ci
- role='img'
cla
|
d15b0f0d56630d4d076345cac955c73564f302b4
|
fix lint-error in translations JS
|
app/javascript/src/locale/fr_FR/timeago.js
|
app/javascript/src/locale/fr_FR/timeago.js
|
module.exports = (number, index) => [
["à l'instant", 'dans un instant'],
['il y a %s secondes', 'dans %s secondes'],
['il y a 1 minute', 'dans 1 minute'],
['il y a %s minutes', 'dans %s minutes'],
['il y a 1 heure', 'dans 1 heure'],
['il y a %s heures', 'dans %s heures'],
['il y a 1 jour', 'dans 1 jour'],
['il y a %s jours', 'dans %s jours'],
['il y a 1 semaine', 'dans 1 semaine'],
['il y a %s semaines', 'dans %s semaines'],
['il y a 1 mois', 'dans 1 mois'],
['il y a %s mois', 'dans %s mois'],
['il y a 1 an', 'dans 1 an'],
['il y a %s ans', 'dans %s ans'],
][index];
|
JavaScript
| 0.000119 |
@@ -38,20 +38,21 @@
%0A %5B
-%22
+'
%C3%A0 l
+%5C
'instant
%22, '
@@ -51,9 +51,9 @@
tant
-%22
+'
, 'd
|
0b6523ba214f6fa9d6d1a2d46dae7591af46cffc
|
add config arg to constructor
|
lib/ServiceProviderMixin.js
|
lib/ServiceProviderMixin.js
|
/* jslint node: true, esnext: true */
"use strict";
const rgm = require('./RegistrarMixin');
/**
* provide services and hold service configuration
*/
module.exports = (superclass) => class extends superclass {
constructor() {
super();
rgm.defineRegistrarProperties(this, 'service');
}
/**
* adds a pre configured service
*/
addService(service) {
this.services[service.name] = service;
if (service.autostart) {
service.start();
}
return service;
}
};
|
JavaScript
| 0.000004 |
@@ -222,16 +222,22 @@
tructor(
+config
) %7B%0A%09%09su
@@ -240,16 +240,22 @@
%09%09super(
+config
);%0A%09%09rgm
|
486c2012b4d6c07cee76e1abedf2fd2d4adce2ab
|
Change to print meaningless results with strict '=' prefix
|
app/main/plugins/hain-plugin-math/index.js
|
app/main/plugins/hain-plugin-math/index.js
|
'use strict';
const lo_isNumber = require('lodash.isnumber');
const lo_isString = require('lodash.isstring');
const lo_isObject = require('lodash.isobject');
const lo_has = require('lodash.has');
const math = require('mathjs');
module.exports = (context) => {
const app = context.app;
const clipboard = context.clipboard;
const toast = context.toast;
const indexer = context.indexer;
function startup() {
indexer.set('math', (query) => {
const answer = calculate(query);
if (!answer)
return;
return makeResultItem('primaryText', query, answer);
});
}
function search(query, res) {
const answer = calculate(query);
if (!answer)
return;
res.add(makeResultItem('title', query, answer));
}
function makeResultItem(titleKey, query, answer) {
const result = {};
result[titleKey] = `${query.trim()} = ${answer}`;
result.group = 'Math';
result.payload = answer;
return result;
}
function calculate(query) {
try {
const ans = math.eval(query);
if (lo_isNumber(ans) || lo_isString(ans) || (lo_isObject(ans) && lo_has(ans, 'value'))) {
const ansString = ans.toString();
if (ansString.trim() !== query.trim())
return ansString;
}
} catch (e) { }
}
function execute(id, payload) {
app.setQuery(`=${payload}`);
clipboard.writeText(payload);
toast.enqueue(`${payload} has copied into clipboard`);
}
return { startup, search, execute };
};
|
JavaScript
| 0.00002 |
@@ -481,27 +481,34 @@
culate(query
+, false
);%0A
-
if (!a
@@ -664,24 +664,30 @@
culate(query
+, true
);%0A if (!
@@ -1002,16 +1002,37 @@
te(query
+, showRedundantResult
) %7B%0A
@@ -1219,18 +1219,42 @@
-if
+const isResultMeaningful =
(ansStr
@@ -1281,16 +1281,72 @@
.trim())
+;%0A if (isResultMeaningful %7C%7C showRedundantResult)
%0A
|
d890571d77f7ad8c840f9f2d7ca7189f61547534
|
Fix for #2327
|
lib/associations/has-one.js
|
lib/associations/has-one.js
|
'use strict';
var Utils = require('./../utils')
, Helpers = require('./helpers')
, Transaction = require('../transaction');
module.exports = (function() {
var HasOne = function(srcDAO, targetDAO, options) {
this.associationType = 'HasOne';
this.source = srcDAO;
this.target = targetDAO;
this.options = options;
this.isSingleAssociation = true;
this.isSelfAssociation = (this.source === this.target);
this.as = this.options.as;
if (Utils._.isObject(this.options.foreignKey)) {
this.foreignKeyAttribute = this.options.foreignKey;
this.foreignKey = this.foreignKeyAttribute.name || this.foreignKeyAttribute.fieldName;
} else {
this.foreignKeyAttribute = {};
this.foreignKey = this.options.foreignKey;
}
if (this.as) {
this.isAliased = true;
this.options.name = {
singular: this.as
};
} else {
this.as = this.target.options.name.singular;
this.options.name = this.target.options.name;
}
if (!this.options.foreignKey) {
this.options.foreignKey = Utils._.camelizeIf(
[
Utils._.underscoredIf(Utils.singularize(this.source.name), this.target.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
}
this.identifier = this.foreignKey || Utils._.camelizeIf(
[
Utils._.underscoredIf(this.source.options.name.singular, this.source.options.underscored),
this.source.primaryKeyAttribute
].join('_'),
!this.source.options.underscored
);
this.sourceIdentifier = this.source.primaryKeyAttribute;
this.associationAccessor = this.as;
this.options.useHooks = options.useHooks;
// Get singular name, trying to uppercase the first letter, unless the model forbids it
var singular = Utils.uppercaseFirst(this.options.name.singular);
this.accessors = {
get: 'get' + singular,
set: 'set' + singular,
create: 'create' + singular
};
};
// the id is in the target table
HasOne.prototype.injectAttributes = function() {
var newAttributes = {}
, keyType = this.source.rawAttributes[this.sourceIdentifier].type;
newAttributes[this.identifier] = Utils._.defaults(this.foreignKeyAttribute, { type: this.options.keyType || keyType });
Utils.mergeDefaults(this.target.rawAttributes, newAttributes);
if (this.options.constraints !== false) {
this.options.onDelete = this.options.onDelete || 'SET NULL';
this.options.onUpdate = this.options.onUpdate || 'CASCADE';
}
Helpers.addForeignKeyConstraints(this.target.rawAttributes[this.identifier], this.source, this.target, this.options);
// Sync attributes and setters/getters to DAO prototype
this.target.refreshAttributes();
Helpers.checkNamingCollision(this);
return this;
};
HasOne.prototype.injectGetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.get] = function(params) {
var where = {};
params = params || {};
params.where = (params.where && [params.where]) || [];
where[association.identifier] = this.get(association.sourceIdentifier);
params.where.push(where);
params.where = new Utils.and(params.where);
return association.target.find(params);
};
return this;
};
HasOne.prototype.injectSetter = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.set] = function(associatedInstance, options) {
var instance = this;
return instance[association.accessors.get](options).then(function(oldInstance) {
if (oldInstance) {
oldInstance[association.identifier] = null;
return oldInstance.save(Utils._.extend({}, options, {
fields: [association.identifier],
allowNull: [association.identifier],
association: true
}));
}
}).then(function() {
if (associatedInstance) {
if (!(associatedInstance instanceof association.target.Instance)) {
var tmpInstance = {};
tmpInstance[association.target.primaryKeyAttribute] = associatedInstance;
associatedInstance = association.target.build(tmpInstance, {
isNewRecord: false
});
}
associatedInstance.set(association.identifier, instance.get(association.sourceIdentifier));
return associatedInstance.save(options);
}
return null;
});
};
return this;
};
HasOne.prototype.injectCreator = function(instancePrototype) {
var association = this;
instancePrototype[this.accessors.create] = function(values, options) {
var instance = this;
options = options || {};
values[association.identifier] = instance.get(association.sourceIdentifier);
if (options.fields) options.fields.push(association.identifier);
return association.target.create(values, options);
};
return this;
};
return HasOne;
})();
|
JavaScript
| 0 |
@@ -4793,16 +4793,45 @@
= this;%0A
+ values = values %7C%7C %7B%7D;%0A
op
|
37f61c479e3d79eebff6049b0e980ff6d82b4ec2
|
Handle className properly on SVG nodes
|
src/browser/ui/dom/HTMLDOMPropertyConfig.js
|
src/browser/ui/dom/HTMLDOMPropertyConfig.js
|
/**
* Copyright 2013-2014 Facebook, Inc.
*
* 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.
*
* @providesModule HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = require('DOMProperty');
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var MUST_USE_PROPERTY = DOMProperty.injection.MUST_USE_PROPERTY;
var HAS_BOOLEAN_VALUE = DOMProperty.injection.HAS_BOOLEAN_VALUE;
var HAS_SIDE_EFFECTS = DOMProperty.injection.HAS_SIDE_EFFECTS;
var HAS_NUMERIC_VALUE = DOMProperty.injection.HAS_NUMERIC_VALUE;
var HAS_POSITIVE_NUMERIC_VALUE =
DOMProperty.injection.HAS_POSITIVE_NUMERIC_VALUE;
var HAS_OVERLOADED_BOOLEAN_VALUE =
DOMProperty.injection.HAS_OVERLOADED_BOOLEAN_VALUE;
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
className: MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
frameBorder: MUST_USE_ATTRIBUTE,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: null,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scrollLeft: MUST_USE_PROPERTY,
scrolling: null,
scrollTop: MUST_USE_PROPERTY,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: null,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
autoCorrect: null, // Supported in Mobile Safari for keyboard hints
itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
property: null // Supports OG in meta tags
},
DOMAttributeNames: {
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
|
JavaScript
| 0 |
@@ -720,16 +720,76 @@
perty');
+%0Avar ExecutionEnvironment = require('ExecutionEnvironment');
%0A%0Avar MU
@@ -1282,16 +1282,299 @@
VALUE;%0A%0A
+var hasSVG;%0Aif (ExecutionEnvironment.canUseDOM) %7B%0A var implementation = document.implementation;%0A hasSVG = (%0A implementation &&%0A implementation.hasFeature &&%0A implementation.hasFeature(%0A 'http://www.w3.org/TR/SVG11/feature#BasicStructure',%0A '1.1'%0A )%0A );%0A%7D%0A%0A%0A
var HTML
@@ -2242,25 +2242,418 @@
UE,%0A
-className
+// To set className on SVG elements, it's necessary to use .setAttribute;%0A // this works on HTML elements too in all browsers except IE8. Conveniently,%0A // IE8 doesn't support SVG and so we can simply use the attribute in%0A // browsers that support SVG and the property in browsers that don't,%0A // regardless of whether the element is HTML or SVG.%0A className: hasSVG ? MUST_USE_ATTRIBUTE
: MUST_U
|
36428e304dd0bde0d21f2215d99db90479349a3e
|
add CC and VPRS series
|
src/client/temp/data/2017-ncnca-serieses.js
|
src/client/temp/data/2017-ncnca-serieses.js
|
/*eslint-disable */
//last id 40001
export default [
{ "id": "ser-40001", "name": "2017 USAC National Championships", "url": "http://www.ncnca.org/ncncaseries/2017-usac-national-championships", "shortName": "UNC" },
]
|
JavaScript
| 0 |
@@ -212,10 +212,290 @@
UNC%22 %7D,%0A
+ %7B %22id%22: %22ser-40002%22, %22name%22: %222017 Cal Cup%22, %22url%22: %22http://www.ncnca.org/ncncaseries/2017-cal-cup%22, %22shortName%22: %22CC%22 %7D,%0A %7B %22id%22: %22ser-40003%22, %22name%22: %222017 Velo Promo Road Series%22, %22url%22: %22http://www.ncnca.org/ncncaseries/2017-velo-promo-road-series%22, %22shortName%22: %22VPRS%22 %7D,%0A
%5D%0A
|
43aad8b23d299b1d42de7750e52c6527fea6c676
|
Fix bug, firefox thinks "watch" property is a duplicate
|
app/scripts/services/dice-words-service.js
|
app/scripts/services/dice-words-service.js
|
/**
* The MIT License (MIT)
* Copyright (c) 2016 Krypto Fin ry and the FIMK Developers
*
* 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.
* */
(function () {
'use strict';
var module = angular.module('fim.base');
module.factory('diceWords', function ($q, $http, $rootScope) {
var cached = {};
var diceWords = {
getAvailableSets: function () {
return ['en','fi'/*,'de', 'fr','it','jp','nl','pl','sv'*/];
},
resolveURL: function (fileName) {
if (isNodeJS) { return 'dice-words/' + fileName; }
return window.location.protocol + '//' + window.location.hostname + ':' + window.location.port + '/dice-words/' + fileName
},
getWords: function (key) {
var deferred = $q.defer();
if (cached[key]) {
deferred.resolve(cached[key]);
}
else {
var sets = this.getAvailableSets();
if (sets.indexOf(key)==-1) {
key = 'en';
}
var file = key+'.txt';
$http({
url: this.resolveURL(file),
method: 'GET'
}).
success(function(data) {
var words = data.match(/[^\r\n]+/g);
if (hasDuplicates(words)) {
console.log('Word list ['+file+'] contains duplicates');
deferred.reject();
}
else {
cached[key] = words;
deferred.resolve(cached[key]);
}
}.bind(this)).
error(function(err) {
console.log(err);
deferred.reject();
});
}
return deferred.promise;
}
};
function hasDuplicates(array) {
var duplicates = {}, key;
for (var i=0; i<array.length; i++) {
key = array[i];
if (duplicates[key]) {
console.log('Duplicate: '+key);
return true;
}
duplicates[key] = 1;
}
}
return diceWords;
});
})();
|
JavaScript
| 0.000001 |
@@ -2713,21 +2713,36 @@
plicates
-%5Bkey%5D
+.hasOwnProperty(key)
) %7B%0A
|
71a910d2c0ecf1d0f74de5b2d21350f7eb1d1903
|
add trigger for replay
|
app/services/repos/landscape-repository.js
|
app/services/repos/landscape-repository.js
|
import Ember from 'ember';
const {Service, Evented} = Ember;
/**
* TODO
*
* @class Landscape-Repository-Service
* @extends Ember.Service
*/
export default Service.extend(Evented, {
latestLandscape: null,
latestApplication: null,
replayLandscape: null,
replayApplication:null,
triggerUpdate(){
this.trigger("updated", this.get("latestLandscape"));
}
});
|
JavaScript
| 0 |
@@ -361,16 +361,74 @@
ape%22));%0A
+ this.trigger(%22updated%22, this.get(%22replayLandscape%22));%0A
%7D%0A%0A%7D);
|
446c0e092f1c725a4afc6933ad5d8c8dece08437
|
Clean up the error pages.
|
lib/components/ErrorPage.js
|
lib/components/ErrorPage.js
|
import ErrorStore from '../stores/ErrorStore'
import React from 'react'
export default class ErrorPage extends React.Component {
constructor() {
this.state = ErrorStore.getState()
this._onChange = () => {
this.setState(ErrorStore.getState())
}
}
componentDidMount() {
ErrorStore.listen(this._onChange)
}
componentDidUnmount() {
ErrorStore.unlisten(this._onChange)
}
render() {
return <div>
<h1>{this.state.status}</h1>
<p>{this.state.message}</p>
{this.state.stack
? <pre>{this.state.stack}</pre>
: null}
</div>
}
}
|
JavaScript
| 0 |
@@ -1,12 +1,46 @@
+import Centered from './Centered'%0A
import Error
@@ -98,16 +98,48 @@
'react'
+%0Aimport Spinner from './Spinner'
%0A%0Aexport
@@ -498,23 +498,99 @@
rn %3C
-div%3E%0A %3Ch1%3E
+Centered ver%3E%0A%0A %3CSpinner dir=%22up%22 /%3E%0A%0A %3Ch1 className=%22with-subtitle%22%3EFilePizza -
%7Bthi
@@ -618,16 +618,37 @@
%3Cp
+ className=%22subtitle%22
%3E%7Bthis.s
@@ -757,11 +757,16 @@
%3C/
-div
+Centered
%3E%0A
|
fb54874b19e8f0529b7ceb275c41ed92849e1dc7
|
improve unlock screen (#33)
|
src/component/lockedState/UnlockAppAlert.js
|
src/component/lockedState/UnlockAppAlert.js
|
import React from'React'
import { View, TextInput, TouchableOpacity, Text } from 'react-native'
import DefaultText from '../DefaultText'
import Colors from '@Colors/colors'
import merge from '../../util/merge'
import style from './UnlockAppAlertStyle'
import { unlockCharNo } from '../../store/reducer/login'
export const maxAttempts = 3;
const passwordValid = (password) => password && password.indexOf(' ') === -1 && password.length === unlockCharNo
class UnlockAppAlert extends React.Component {
constructor() {
super()
this.state = {
pass: ''
}
}
_onChangeText (value) {
this.setState({pass: value })
}
render() {
return (
<View style={style.wrapper}>
<View style={style.container}>
<Text style={style.instructionText}>
To protect your privacy, we have locked the login area.
To unlock, please enter the last {unlockCharNo} characters of your password. Or chose "Logout" to just browse
</Text>
{ this.props.error &&
<View>
<Text style={merge(style.errorText, { paddingTop: 10 })}>
You have {maxAttempts - this.props.failedAttempts} attempts left.
</Text>
<Text style={merge(style.errorText, { paddingBottom: 10 })}>
The characters entered don't match.
</Text>
</View>
}
<View style={style.form}/>
<TextInput
placeholder={'Unlock code'}
autoFocus={true}
value={this.state.pass}
accessibilityLabel={'Password'}
style={style.input}
placeholderTextColor={Colors.gray4}
secureTextEntry={true}
underlineColorAndroid={Colors.transparent}
onChangeText={(value) => this._onChangeText(value)}>
</TextInput>
<View style={{flexDirection: 'row'}}>
<TouchableOpacity
style={merge(style.buttonContainer, { backgroundColor: Colors.primaryBlue, flex: 1, marginRight: 2 })}
onPress={() => this.props.logout && this.props.logout()}>
<DefaultText style={merge(style.buttonText, { color: 'white' })}>
Logout
</DefaultText>
</TouchableOpacity>
<TouchableOpacity
style={merge(style.buttonContainer, { flex: 1, marginLeft: 2, backgroundColor: passwordValid(this.state.pass) ? Colors.primaryBlue : Colors.offWhite})}
onPress={() => passwordValid(this.state.pass) && this.props.checkPass(this.state.pass)}>
<DefaultText style={merge(style.buttonText, { color: passwordValid(this.state.pass) ? 'white' : 'black' })}>
Unlock
</DefaultText>
</TouchableOpacity>
</View>
</View>
</View>
)
}
}
export default UnlockAppAlert
|
JavaScript
| 0 |
@@ -1843,16 +1843,65 @@
e.pass%7D%0A
+ maxLength=%7BunlockCharNo%7D%0A
@@ -1941,16 +1941,19 @@
l=%7B'
-Password
+Unlock code
'%7D%0A
|
809744b9758c4c55927791fee2086b826ca8f49a
|
resolve bug in show opacity slider
|
src/components/GlobalFilter/GlobalFilter.js
|
src/components/GlobalFilter/GlobalFilter.js
|
import React from 'react'
import Place from './Place'
const GlobalFilter = ({
places,
mapProperties,
onPlaceClick,
onOpacityChange,
onContourChange,
onKeyUpSearch,
}) => {
let input
// treat opacity tooltip value
let opacity
if (!mapProperties) {
opacity = .5
} else {
opacity = mapProperties.opacity
}
if(isNaN(opacity)) {
opacity = .5
}
opacity *= 100
const handleOpacityChange = (e) => {
onOpacityChange(e.target.value)
}
const handleTypeChange = (e) => {
onContourChange(e.target.value)
}
const handleKeyUpSearch = (val) => {
onKeyUpSearch(val)
}
return (
<div className="global-filter">
<form>
<fieldset className="global-filter-form">
<p className="global-filter-form--title">Busca detalhada</p>
<fieldset className="global-filter-form--inpusearch">
<input
id="searchField"
type="search"
placeholder="Insira o nome da área"
ref={node => {input = node;}}
onKeyUp={() => {
handleKeyUpSearch(input.value)
}}
/>
<label htmlFor="searchField"><i className="fa fa-search"></i></label>
</fieldset>
<fieldset className="global-filter-form--selectiontype">
<label>Tipo de seleção:</label>
<label htmlFor="selectionType1" className="input-checkopacity" for="">
<input
name="selectionType"
type="radio"
id="selectionType1"
value="borda"
defaultChecked="checked"
onClick={(e) => handleTypeChange(e)} />
<span>Demarcada</span>
</label>
<label htmlFor="selectionType2" className="input-checkopacity">
<input
name="selectionType"
type="radio"
id="selectionType2"
value="opaco"
onClick={(e) => handleTypeChange(e)} />
<span>Isolada</span>
</label>
</fieldset>
<fieldset className="global-filterform--selectopacity">
<label> Opacidade da seleção
<input className="opacitySelection" type="range" min="0" max="10" defaultValue="5" onChange={(e) => handleOpacityChange(e)}></input>
</label>
<p>{opacity}%</p>
</fieldset>
</fieldset>
</form>
<div className="global-filter-places">
<p className="global-filter-places--title">Áreas dos CRAAIs</p>
<div className="list-crais">
{places? places.map(p => <Place onPlaceClick={onPlaceClick} key={p.id} place={p}/>) : null}
</div>
</div>
</div>
)
}
export default GlobalFilter
|
JavaScript
| 0 |
@@ -3025,16 +3025,17 @@
+
%3Cp%3E%7Bopac
|
a4644c204dc24352fd5313f81c16fc3570ab5249
|
add shadow style props to Image styles
|
src/components/Image/ImageStylePropTypes.js
|
src/components/Image/ImageStylePropTypes.js
|
import BorderPropTypes from '../../propTypes/BorderPropTypes';
import ColorPropType from '../../propTypes/ColorPropType';
import ImageResizeMode from './ImageResizeMode';
import LayoutPropTypes from '../../propTypes/LayoutPropTypes';
import { PropTypes } from 'react';
import TransformPropTypes from '../../propTypes/TransformPropTypes';
const hiddenOrVisible = PropTypes.oneOf([ 'hidden', 'visible' ]);
module.exports = {
...BorderPropTypes,
...LayoutPropTypes,
...TransformPropTypes,
backfaceVisibility: hiddenOrVisible,
backgroundColor: ColorPropType,
resizeMode: PropTypes.oneOf(Object.keys(ImageResizeMode)),
/**
* @platform web
*/
boxShadow: PropTypes.string,
opacity: PropTypes.number,
overflow: hiddenOrVisible,
/**
* @platform web
*/
visibility: hiddenOrVisible
};
|
JavaScript
| 0 |
@@ -262,16 +262,79 @@
react';%0A
+import ShadowPropTypes from '../../propTypes/ShadowPropTypes';%0A
import T
@@ -521,24 +521,46 @@
tPropTypes,%0A
+ ...ShadowPropTypes,%0A
...Transfo
|
f3a408d27ed8ad8a2990f9597b38c5192294cd40
|
Update to be stateless component
|
src/components/common/ConfirmationDialog.js
|
src/components/common/ConfirmationDialog.js
|
import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import DialogActions from '@material-ui/core/DialogActions';
import DialogContent from '@material-ui/core/DialogContent';
import AppButton from './AppButton';
import { intlIfObject } from '../../lib/stringUtil';
class ConfirmationDialog extends React.Component {
handleOk = () => {
const { onOk } = this.props;
onOk();
}
handleCancel = () => {
const { onCancel } = this.props;
onCancel();
}
render() {
const { open, title, children, okText } = this.props;
const { formatMessage } = this.props.intl;
const actions = [
<AppButton
key={1}
label="Cancel"
onClick={this.handleCancel}
/>,
<AppButton
key={2}
label={intlIfObject(formatMessage, okText)}
primary
onClick={this.handleOk}
/>,
];
return (
<div>
<Dialog
className="app-dialog"
open={open}
onClose={this.handleCancel}
>
<DialogTitle>{intlIfObject(formatMessage, title)}</DialogTitle>
<DialogContent>
{children}
</DialogContent>
<DialogActions>{actions}</DialogActions>
</Dialog>
</div>
);
}
}
ConfirmationDialog.propTypes = {
// from composition
intl: PropTypes.object.isRequired,
children: PropTypes.node.isRequired,
// from parent
open: PropTypes.bool.isRequired,
title: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
okText: PropTypes.oneOfType([PropTypes.string, PropTypes.object]).isRequired,
onOk: PropTypes.func.isRequired,
onCancel: PropTypes.func.isRequired,
};
export default injectIntl(ConfirmationDialog);
|
JavaScript
| 0.000004 |
@@ -417,503 +417,245 @@
l';%0A
-%0Aclass ConfirmationDialog extends React.Component %7B%0A handleOk = () =%3E %7B%0A const %7B onOk %7D = this.props;%0A onOk();%0A %7D%0A%0A handleCancel = () =%3E %7B%0A const %7B onCancel %7D = this.props;%0A onCancel();%0A %7D%0A%0A render() %7B%0A const %7B open, title, children, okText %7D = this.props;%0A const %7B formatMessage %7D = this.props.intl;%0A const actions = %5B%0A %3CAppButton%0A key=%7B1%7D%0A label=%22Cancel%22%0A onClick=%7Bthis.handleCancel%7D%0A /%3E,%0A %3CAppButton%0A key=%7B2%7D%0A label=
+import messages from '../../resources/messages';%0A%0Aconst ConfirmationDialog = (%7B open, title, children, okText, onCancel, onOk, intl %7D) =%3E (%0A %3CDialog%0A className=%22app-dialog%22%0A open=%7Bopen%7D%0A onClose=%7BonCancel%7D%0A %3E%0A %3CDialogTitle%3E
%7Bint
@@ -656,32 +656,37 @@
e%3E%7BintlIfObject(
+intl.
formatMessage, o
@@ -688,208 +688,176 @@
ge,
-okText)%7D%0A primary%0A onClick=%7Bthis.handleOk%7D%0A /%3E,%0A %5D;%0A return (%0A %3Cdiv%3E%0A %3CDialog%0A className=%22app-dialog%22%0A open=%7Bopen%7D%0A onClose=%7Bthis.handle
+title)%7D%3C/DialogTitle%3E%0A %3CDialogContent%3E%0A %7Bchildren%7D%0A %3C/DialogContent%3E%0A %3CDialogActions%3E%0A %3CAppButton%0A label=%7Bmessages.cancel%7D%0A onClick=%7Bon
Canc
@@ -870,18 +870,17 @@
-
+/
%3E%0A
@@ -875,33 +875,41 @@
%3E%0A
- %3CDialogTitle%3E
+%3CAppButton%0A label=
%7BintlIfO
@@ -914,16 +914,21 @@
fObject(
+intl.
formatMe
@@ -938,140 +938,69 @@
ge,
-title)%7D%3C/DialogTitle%3E%0A %3CDialogContent%3E%0A %7Bchildren%7D%0A %3C/DialogContent%3E%0A %3CDialogActions%3E%7Bactions%7D
+okText)%7D%0A primary%0A onClick=%7BonOk%7D%0A /%3E%0A
%3C/Di
@@ -1012,22 +1012,16 @@
ctions%3E%0A
-
%3C/Dial
@@ -1028,33 +1028,10 @@
og%3E%0A
- %3C/div%3E%0A );%0A %7D%0A%7D
+);
%0A%0ACo
|
a452307bcff9fa37436c5f178c5f654f1d580c5d
|
Make toggle work on list component
|
src/components/streams/StreamRenderables.js
|
src/components/streams/StreamRenderables.js
|
import React from 'react'
import { camelize } from 'humps'
import * as api from '../../networking/api'
import { getLinkArray } from '../base/json_helper'
import PostParser from '../parsers/PostParser'
import CommentParser from '../parsers/CommentParser'
import { parseNotification } from '../parsers/NotificationParser'
import PostsAsGrid from '../posts/PostsAsGrid'
import { HeartIcon, RepostIcon } from '../posts/PostIcons'
import UserAvatar from '../users/UserAvatar'
import UserAvatars from '../users/UserAvatars'
import UserCard from '../users/UserCard'
import UserGrid from '../users/UserGrid'
import UserInvitee from '../users/UserInvitee'
import UserList from '../users/UserList'
import Preference from '../../components/forms/Preference'
import TreeButton from '../../components/navigation/TreeButton'
import { preferenceToggleChanged } from '../../components/base/junk_drawer'
// TODO: convert these into react components (@see UserVitals)
// to hopefully get better errors out of rendering streams
export function usersAsCards(users) {
return (
<div className="Cards">
{users.data.map((user, i) =>
<UserCard ref={ `userCard_${i}` } user={ user } key={ i } />
)}
</div>
)
}
export function usersAsGrid(users) {
return (
<div className="Users asGrid">
{users.data.map((user, i) =>
<UserGrid ref={ `userGrid_${i}` } user={ user } key={ i } />
)}
</div>
)
}
export function usersAsList(users) {
return (
<div className="Users asList">
{users.data.map((user, i) =>
<UserList ref={ `userList_${i}` } user={ user } key={ i } />
)}
</div>
)
}
export function usersAsInviteeList(invitations, json) {
return (
<div className="Users asInviteeList">
{invitations.data.map((invitation, i) =>
<UserInvitee
ref={ `userInvite${i}` }
invitation={ invitation }
json={ json }
key={ i }
/>
)}
</div>
)
}
export function usersAsInviteeGrid(invitations, json) {
return (
<div className="Users asInviteeGrid">
{invitations.data.map((invitation, i) =>
<UserInvitee
className="UserInviteeGrid"
ref={ `userInvite${i}` }
invitation={ invitation }
json={ json }
key={ i }
/>
)}
</div>
)
}
export function postsAsGrid(posts, json, currentUser, gridColumnCount) {
return (
<PostsAsGrid
posts={posts.data}
json={json}
currentUser={currentUser}
gridColumnCount={gridColumnCount}
/>
)
}
export function postsAsList(posts) {
return (
<div className="Posts asList">
{posts.data.map((post) =>
<article ref={ `postList_${post.id}` } key={ post.id } className="Post PostList">
<PostParser post={post} isGridLayout={false} />
</article>
)}
</div>
)
}
export function postDetail(posts, json) {
const post = posts.data[0]
let comments = getLinkArray(post, 'comments', json) || []
comments = comments.concat(posts.nestedData)
const avatarDrawers = []
if (Number(post.lovesCount) > 0) {
avatarDrawers.push(
<UserAvatars
endpoint={ api.postLovers(post) }
icon={ <HeartIcon /> }
key={ `lovers_${post.id}` }
resultKey="lovers"
/>
)
}
if (Number(post.repostsCount) > 0) {
avatarDrawers.push(
<UserAvatars
endpoint={ api.postReposters(post) }
icon={ <RepostIcon /> }
key={ `reposters_${post.id}` }
resultKey="reposters"
/>
)
}
return (
<div className="PostDetails Posts asList">
<article ref={ `postList_${post.id}` } key={ post.id } className="Post PostList">
<PostParser post={post} isGridLayout={false} />
{avatarDrawers}
<section className="Comments">
{comments.map((comment) =>
<div ref={ `commentList_${comment.id}` } key={ comment.id } className="CommentList">
<CommentParser comment={comment} isGridLayout={false} />
</div>
)}
</section>
</article>
</div>
)
}
export function commentsAsList(comments) {
return (
<div>
{comments.data.map(comment =>
<CommentParser key={`CommentParser_${comment.id}`} comment={comment} isGridLayout={false} />
)}
</div>
)
}
export function notificationList(notifications, json, currentUser) {
return (
<div className="Notifications">
{notifications.data.map((notification) =>
parseNotification(notification, json, currentUser)
)}
</div>
)
}
export function userAvatars(users) {
return (
users.data.map((user) =>
<UserAvatar user={user} key={`userAvatar_${user.id}`}/>
)
)
}
export function profileToggles(categories, json, currentUser) {
return (
categories.data.map((category, index) => {
if (category.label.toLowerCase().indexOf('push') === 0) { return null }
const arr = [<TreeButton key={`categoryLabel${index}`}>{category.label}</TreeButton>]
arr.push(
<div className="TreePanel" key={`categoryItems${index}`}>
{
category.items.map((item) =>
<Preference
definition={{ term: item.label, desc: item.info }}
id={ item.key }
key={ item.key }
isChecked={ currentUser[camelize(item.key)] }
isDisabled={ !currentUser.isPublic && item.key === 'has_sharing_enabled' }
onToggleChange={ preferenceToggleChanged }
/>
)
}
</div>
)
return arr
})
)
}
|
JavaScript
| 0.000001 |
@@ -2833,32 +2833,64 @@
dLayout=%7Bfalse%7D
+showComments=%7Bpost.showComments%7D
/%3E%0A %3C/art
|
f2b203a826589550b1cf1aea1bf5237ab75e32d7
|
Fix issue with VictoryZoom>VictoryChart child events
|
src/components/victory-zoom/victory-zoom.js
|
src/components/victory-zoom/victory-zoom.js
|
import React, {Component, PropTypes} from "react";
import { assign, groupBy, isEqual } from "lodash";
import ChartHelpers from "../victory-chart/helper-methods";
import ZoomHelpers from "./helper-methods";
import {VictoryClipContainer, Helpers, PropTypes as CustomPropTypes, Timer} from "victory-core";
const fallbackProps = {
width: 450,
height: 300,
padding: 50
};
class VictoryZoom extends Component {
static displayName = "VictoryZoom";
static role = "zoom";
static propTypes = {
children: PropTypes.node,
zoomDomain: PropTypes.shape({
x: CustomPropTypes.domain,
y: CustomPropTypes.domain
}),
onDomainChange: PropTypes.func,
clipContainerComponent: PropTypes.element.isRequired,
allowZoom: PropTypes.bool
}
static childContextTypes = {
getTimer: React.PropTypes.func
}
static defaultProps = {
clipContainerComponent: <VictoryClipContainer/>,
allowZoom: true
}
constructor(props) {
super(props);
const chart = React.Children.only(this.props.children);
const [rangex1, rangex0] = Helpers.getRange(
Helpers.modifyProps(chart.props, {}, "chart"), // TODO: Don't presume chart role
"x"
);
this.plottableWidth = rangex0 - rangex1;
this.width = chart.props.width || fallbackProps.width;
this.state = { domain: props.zoomDomain || this.getDataDomain() };
this.events = this.getEvents(props.allowZoom);
this.clipDataComponents = this.clipDataComponents.bind(this);
this.getTimer = this.getTimer.bind(this);
}
getChildContext() {
return {
getTimer: this.getTimer
};
}
getTimer() {
if (!this.timer) {
this.timer = new Timer();
}
return this.timer;
}
componentWillMount() {
this.getChartRef = (chart) => { this.chartRef = chart; };
}
componentWillUnmount() {
this.getTimer().stop();
}
componentWillReceiveProps({allowZoom: nextAllowZoom, zoomDomain: nextDomain}) {
const {allowZoom, zoomDomain} = this.props;
if (!isEqual(zoomDomain, nextDomain)) {
this.setState({domain: nextDomain});
}
if (allowZoom !== nextAllowZoom) {
this.events = this.getEvents(nextAllowZoom);
}
}
getDataDomain() {
const chart = React.Children.only(this.props.children);
const chartChildren = React.Children.toArray(chart);
return {
x: ChartHelpers.getDomain(chart.props, "x", chartChildren)
};
}
getEvents(allowZoom) {
return [{
target: "parent",
eventHandlers: {
onMouseDown: (evt) => {
this.targetBounds = this.chartRef.getSvgBounds();
const x = evt.clientX - this.targetBounds.left;
this.isPanning = true;
this.startX = x;
this.lastDomain = this.state.domain;
},
onMouseUp: () => { this.isPanning = false; },
onMouseLeave: () => { this.isPanning = false; },
onMouseMove: (evt) => {
const clientX = evt.clientX;
if (this.isPanning) {
requestAnimationFrame(() => { // eslint-disable-line no-undef
const domain = this.getDataDomain();
const delta = this.startX - (clientX - this.targetBounds.left);
const calculatedDx = delta / this.getDomainScale();
const nextXDomain = ZoomHelpers.pan(this.lastDomain.x, domain.x, calculatedDx);
this.setDomain({x: nextXDomain});
this.setState({domain: {x: nextXDomain}});
});
}
},
...allowZoom && {onWheel: (evt) => {
evt.preventDefault();
const deltaY = evt.deltaY;
requestAnimationFrame(() => { // eslint-disable-line no-undef
const {x} = this.state.domain;
const xBounds = this.getDataDomain().x;
// TODO: Check scale factor
const nextXDomain = ZoomHelpers.scale(x, xBounds, 1 + (deltaY / 300));
this.setDomain({x: nextXDomain});
});
}}
}
}];
}
setDomain(domain) {
const {onDomainChange} = this.props;
this.getTimer().bypassAnimation();
this.setState({domain}, () => this.getTimer().resumeAnimation());
if (onDomainChange) { onDomainChange(domain); }
}
getDomainScale() {
const {x: [from, to]} = this.lastDomain;
const ratio = this.targetBounds.width / this.width;
const absoluteAxisWidth = ratio * this.plottableWidth;
return absoluteAxisWidth / (to - from);
}
clipDataComponents(children, props) {
const {data, axes = []} = groupBy(children, (child) => {
return child.type.displayName === "VictoryAxis"
? "axes"
: "data";
});
const [rangex0, rangex1] = Helpers.getRange(props, "x");
return [
React.cloneElement(this.props.clipContainerComponent, {
key: "ZoomClipContainer",
clipWidth: rangex1 - rangex0,
clipHeight: fallbackProps.height,
translateX: rangex0,
children: data
}),
...axes
];
}
renderChart(chartElement, props) {
return React.cloneElement(chartElement, props);
}
render() {
const chart = React.Children.only(this.props.children);
const nextProps = assign({}, chart.props, {
events: chart.props.events ? chart.props.events.unshift(...this.events) : this.events,
domain: this.state.domain,
ref: this.getChartRef,
modifyChildren: this.clipDataComponents
});
return this.renderChart(chart, nextProps);
}
}
export default VictoryZoom;
|
JavaScript
| 0 |
@@ -5153,131 +5153,167 @@
nst
-nextProps = assign(%7B%7D, chart.props, %7B%0A events: chart.props.events ? chart.props.events.unshift(...this.events) : this.
+events = chart.props.events%0A ? (this.events %7C%7C %5B%5D).concat(chart.props.events)%0A : this.events;%0A%0A const nextProps = assign(%7B%7D, chart.props, %7B%0A
even
|
4a5dd9398c43ec4cba7cf41cb09a5a56b18ec412
|
Add extra is visible check to see if it solves firefox issue
|
src/content/devices/input-output/js/test.js
|
src/content/devices/input-output/js/test.js
|
/*
* Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
*
* Use of this source code is governed by a BSD-style license
* that can be found in the LICENSE file in the root of the source
* tree.
*/
'use strict';
// This is a basic test file for use with testling.
// The test script language comes from tape.
var test = require('tape');
var webdriver = require('selenium-webdriver');
var seleniumHelpers = require('../../../../../test/selenium-lib');
test('Fake device selection and check video element dimensions ' +
'in input-output demo',
function(t) {
// FIXME: use env[SELENIUM_BROWSER] instead?
var driver = seleniumHelpers.buildDriver();
var browser = process.env.BROWSER;
driver.get('file://' + process.cwd() +
'/src/content/devices/input-output/index.html')
.then(function() {
t.pass('Page loaded');
// Making sure we can select the 1st audio device.
// TODO: Select more devices if Firefox adds a 2nd fake A&V device and
// Chrome adds another fake video device.
t.pass('Selecting 1st audio device');
return driver.wait(webdriver.until.elementLocated(
webdriver.By.css('#audioSource>option')));
})
.then(function(element) {
return new webdriver.ActionSequence(driver).
doubleClick(element).perform();
})
// Check enumerateDevices has returned an id.
.then(function() {
return driver.findElement(webdriver.By.css(
'#audioSource>option')).getAttribute('value');
})
.then(function(deviceId) {
t.ok(deviceId, 'Device/source id: ' + deviceId);
})
.then(function() {
// Making sure we can select the 1st video device.
// TODO: Select more devices if Firefox adds a 2nd fake A/V device and
// Chrome adds another fake video device.
t.pass('Selecting 1st video device');
return driver.wait(webdriver.until.elementLocated(
webdriver.By.css('#videoSource>option')));
})
.then(function(element) {
return new webdriver.ActionSequence(driver).
doubleClick(element).perform();
})
// Check enumerateDevices has returned an id.
.then(function() {
return driver.findElement(webdriver.By.css(
'#videoSource>option')).getAttribute('value');
})
.then(function(deviceId) {
t.ok(deviceId !== '', 'Device/source id: ' + deviceId);
})
.then(function() {
// Make sure the stream is ready.
return driver.wait(function() {
return driver.executeScript('return window.stream !== undefined;');
}, 30 * 1000);
})
// Check for a fake audio device label (Chrome only).
.then(function() {
return driver.executeScript('return stream.getAudioTracks()[0].label');
})
.then(function(deviceLabel) {
// TODO: Improve this once Firefox has added labels for fake devices.
var fakeAudioDeviceName = (browser === 'chrome') ?
'Fake Audio 1' : '';
t.ok(fakeAudioDeviceName === deviceLabel,
'Fake audio device found with label: ' + deviceLabel);
})
// Check for a fake video device label (Chrome only).
.then(function() {
return driver.executeScript('return stream.getVideoTracks()[0].label');
})
.then(function(deviceLabel) {
// TODO: Improve this once Firefox has added labels for fake devices.
var fakeVideoDeviceName = (browser === 'chrome') ?
'fake_device_0' : '';
// TODO: Remove match() method once http://crbug.com/526633 is fixed.
t.ok(fakeVideoDeviceName === deviceLabel.match(fakeVideoDeviceName)[0],
'Fake video device found with label: ' +
deviceLabel.match(fakeVideoDeviceName)[0]);
})
// Check that there is a video element and it is displaying something.
.then(function() {
return driver.findElement(webdriver.By.id('video'));
})
.then(function(videoElement) {
t.pass('Found video element');
var width = 0;
var height = 0;
return new webdriver.promise.Promise(function(resolve) {
videoElement.getAttribute('videoWidth').then(function(w) {
width = w;
t.pass('Got videoWidth ' + w);
if (width && height) {
resolve([width, height]);
}
});
videoElement.getAttribute('videoHeight').then(function(h) {
height = h;
t.pass('Got videoHeight ' + h);
if (width && height) {
resolve([width, height]);
}
});
});
})
.then(function(dimensions) {
t.pass('Got video dimensions ' + dimensions.join('x'));
})
.then(function() {
t.end();
})
.then(null, function(err) {
t.fail(err);
t.end();
});
});
|
JavaScript
| 0 |
@@ -1170,32 +1170,34 @@
ated(%0A
+
webdriver.By.css
@@ -1256,32 +1256,131 @@
tion(element) %7B%0A
+ return driver.wait(webdriver.until.elementIsVisible(element))%0A .then(function() %7B%0A
return n
@@ -1415,32 +1415,17 @@
driver).
-%0A doubleC
+c
lick(ele
@@ -1433,32 +1433,44 @@
ent).perform();%0A
+ %7D);%0A
%7D)%0A /
@@ -2224,24 +2224,9 @@
er).
-%0A doubleC
+c
lick
|
7471352c880d5edc4749cbeaa37c283c8ce6a759
|
Remove unnecessary comment
|
lib/ensure/symlink-paths.js
|
lib/ensure/symlink-paths.js
|
'use strict'
const path = require('path')
// path.isAbsolute shim for Node.js 0.10 support
const fs = require('graceful-fs')
/**
* Function that returns two types of paths, one relative to symlink, and one
* relative to the current working directory. Checks if path is absolute or
* relative. If the path is relative, this function checks if the path is
* relative to symlink or relative to current working directory. This is an
* initiative to find a smarter `srcpath` to supply when building symlinks.
* This allows you to determine which path to use out of one of three possible
* types of source paths. The first is an absolute path. This is detected by
* `path.isAbsolute()`. When an absolute path is provided, it is checked to
* see if it exists. If it does it's used, if not an error is returned
* (callback)/ thrown (sync). The other two options for `srcpath` are a
* relative url. By default Node's `fs.symlink` works by creating a symlink
* using `dstpath` and expects the `srcpath` to be relative to the newly
* created symlink. If you provide a `srcpath` that does not exist on the file
* system it results in a broken symlink. To minimize this, the function
* checks to see if the 'relative to symlink' source file exists, and if it
* does it will use it. If it does not, it checks if there's a file that
* exists that is relative to the current working directory, if does its used.
* This preserves the expectations of the original fs.symlink spec and adds
* the ability to pass in `relative to current working direcotry` paths.
*/
function symlinkPaths (srcpath, dstpath, callback) {
if (path.isAbsolute(srcpath)) {
return fs.lstat(srcpath, (err, stat) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
'toCwd': srcpath,
'toDst': srcpath
})
})
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
return fs.exists(relativeToDst, exists => {
if (exists) {
return callback(null, {
'toCwd': relativeToDst,
'toDst': srcpath
})
} else {
return fs.lstat(srcpath, (err, stat) => {
if (err) {
err.message = err.message.replace('lstat', 'ensureSymlink')
return callback(err)
}
return callback(null, {
'toCwd': srcpath,
'toDst': path.relative(dstdir, srcpath)
})
})
}
})
}
}
function symlinkPathsSync (srcpath, dstpath) {
let exists
if (path.isAbsolute(srcpath)) {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('absolute srcpath does not exist')
return {
'toCwd': srcpath,
'toDst': srcpath
}
} else {
const dstdir = path.dirname(dstpath)
const relativeToDst = path.join(dstdir, srcpath)
exists = fs.existsSync(relativeToDst)
if (exists) {
return {
'toCwd': relativeToDst,
'toDst': srcpath
}
} else {
exists = fs.existsSync(srcpath)
if (!exists) throw new Error('relative srcpath does not exist')
return {
'toCwd': srcpath,
'toDst': path.relative(dstdir, srcpath)
}
}
}
}
module.exports = {
symlinkPaths,
symlinkPathsSync
}
|
JavaScript
| 0 |
@@ -40,57 +40,8 @@
h')%0A
-// path.isAbsolute shim for Node.js 0.10 support%0A
cons
|
fc2284573122d7a5417954c5d3e6117a0b5c088f
|
Use `res.serverError` to display view errors, if it exists.
|
lib/hooks/views/res.view.js
|
lib/hooks/views/res.view.js
|
/**
* Module dependencies
*/
var path = require('path'),
_ = require('lodash');
/**
* Adds res.view() method (an enhanced version of res.render) to response object.
* `res.view()` automatically renders the appropriate view based on the calling middleware's source route
* Note: the original function is still accessible via res.render()
*
* @param {Request} req
* @param {Response} res
* @param {Function} next
*/
module.exports = function _addResViewMethod(req, res, next) {
var sails = req._sails;
/**
* res.view([specifiedPath|locals], [locals])
*
* @param {String} specifiedPath
* -> path to the view file to load (minus the file extension)
* relative to the app's `views` directory
* @param {Object} locals
* -> view locals (data that is accessible in the view template)
* @param {Function} cb_view(err)
* -> called when the view rendering is complete (response is already sent, or in the process)
* (probably should be @api private)
* @api public
*/
res.view = function(specifiedPath, locals, cb_view) {
sails.log.verbose('Running res.view(' + (specifiedPath ? specifiedPath : '') + ')...');
// By default, generate a path to the view using what we know about the controller+action
var relPathToView;
// Ensure req.target is an object, then merge it into req.options
// (this helps ensure backwards compatibility for users who were relying
// on `req.target` in previous versions of Sails)
req.options = _.defaults(req.options, req.target || {});
// Try to guess the view by looking at the controller/action
if (!req.options.view) {
relPathToView = req.options.controller + '/' + req.options.action;
}
// Use the new view config
else relPathToView = req.options.view;
// Now we have a reasonable guess in `relPathToView`
// If the path to a view was explicitly specified, use that
// Serve the view specified
//
// If first arg is not an object, treat it like the path
if (specifiedPath && !_.isObject(specifiedPath)) {
relPathToView = specifiedPath;
}
// If first arg ISSSSS AN object, treat it like locals
else if (_.isObject(specifiedPath)) {
// If the "locals" argument is actually the "specifiedPath"
// give em the old switcheroo
relPathToView = locals || relPathToView;
locals = specifiedPath;
}
// Ensure specifiedPath is a string (important)
relPathToView = '' + relPathToView + '';
// Ensure `locals` is an object
locals = _.isObject(locals) ? locals : {};
// Mixin locals from req.options
if (req.options.locals) {
locals = _.merge(locals, req.options.locals);
}
// Merge with config views locals
if (sails.config.views.locals) {
_.merge(locals, sails.config.views.locals, _.defaults);
}
// If the path was specified, but invalid
// else if (specifiedPath) {
// return res.serverError(new Error('Specified path for view (' + specifiedPath + ') is invalid!'));
// }
// Trim trailing slash
if (relPathToView[(relPathToView.length - 1)] === '/') {
relPathToView = relPathToView.slice(0, -1);
}
// if local `layout` is set to true or unspecified
// fall back to global config
var layout = locals.layout;
if (locals.layout === undefined || locals.layout === true) {
layout = sails.config.views.layout;
}
// Disable sails built-in layouts for all view engine's except for ejs
if (sails.config.views.engine.ext !== 'ejs') {
layout = false;
}
// Allow `res.locals.layout` to override if it was set:
if (typeof res.locals.layout !== 'undefined') {
layout = res.locals.layout;
}
var pathToViews = sails.config.paths.views;
var absPathToView = path.join(pathToViews, relPathToView);
var absPathToLayout;
var relPathToLayout;
// Ensure layout is a string by this point
if (typeof layout !== 'string') {
layout = false;
}
// Set layout file if enabled (using ejs-locals)
if (layout) {
// Solve relative path to layout from the view itself
// (required by ejs-locals module)
absPathToLayout = path.join(pathToViews, layout);
relPathToLayout = path.relative(path.dirname(absPathToView), absPathToLayout);
// If a layout was specified, set view local so it will be used
res.locals._layoutFile = relPathToLayout;
sails.log.silly('Using layout at: ', absPathToLayout);
}
// Locals passed in to `res.view()` override app and route locals.
_.each(locals, function(local, key) {
res.locals[key] = local;
});
// Provide access to view metadata in locals
// (for convenience)
res.locals.view = res.locals.view || {
path: relPathToView,
absPath: absPathToView,
pathFromViews: relPathToView,
pathFromApp: path.join(path.relative(sails.config.appPath, sails.config.paths.views), relPathToView),
ext: sails.config.views.engine.ext
};
// In development, provide access to complete path to view via `__dirname` local.
if (sails.config.environment !== 'production') {
res.locals.__dirname = res.locals.__dirname ||
absPathToView + '.' + sails.config.views.engine.ext;
}
// Render the view
if (specifiedPath) {
sails.log.silly('View override argument passed to res.view(): ', specifiedPath);
}
sails.log.silly('Serving view at rel path: ', relPathToView);
sails.log.silly('View root: ', sails.config.paths.views);
return res.render(relPathToView, locals, function renderView(err, renderedViewStr) {
// if a template error occurred, don't rely on any of the Sails request/response methods
// (since they may not exist yet at this point in the request lifecycle.)
if (err) {
sails.log.error('Error rendering view at ::', absPathToView);
sails.log.error('with layout located at ::', absPathToLayout);
sails.log.error(err && err.message);
if (process.env.NODE_ENV === 'development') {
return res.json(500, err);
} else return res.send(500);
}
if (layout) {
sails.log.verbose('Using layout: ', absPathToLayout);
}
sails.log.verbose('Rendering view ::', relPathToView, '(located @ ' + absPathToView + ')');
// Backwards compatibility:
// trigger `res.view` callback if specified
// (before sending the response)
if (cb_view) {
sails.log.warn(
'Callback function of `res.view([relativePathToView], [options], [cb])`',
' will be deprecated in an upcoming release.'
);
cb_view(err);
}
// Finally, send the view down to the client
res.send(renderedViewStr);
// Express version updates should be closely monitored.
// Express is a "hard" dependency.
//
// While unlikely this will change, it's worth noting that this implementation
// relies on express's private implementation of res.render() here:
// https://github.com/visionmedia/express/blob/master/lib/response.js#L799
//
// To be safe, the version of the Express dependency in package.json will remain locked
// until it can be verified that each subsequent version is compatible. Even patch releases!!
});
};
next();
};
|
JavaScript
| 0 |
@@ -6062,16 +6062,109 @@
if
+(res.serverError) %7B%0A return res.serverError(err.message);%0A %7D%0A else if
(process
|
931129a37459315f3ee9f1885b4da504c16d877c
|
test on Mojave
|
.min-wd.js
|
.min-wd.js
|
/* Note: Firefox tests work up until version 58. After that, Selenium has a problem:
POST /session/14641de4c7f12c2f9b2eaf307a0955edf23dc59b/timeouts/async_script did not match a known command
No combination of browserstack.geckodriver and browserstack.selenium_version that worked was found.
The solution is to call mochify with `--async-polling false`. */
const travisBuild = process.env.TRAVIS_BUILD_NUMBER
const build = travisBuild ? `travis/${travisBuild.padStart(5, '0')}` : `manual ${new Date().toISOString()}`
console.log(`build: ${build}`)
const capabilitiesBase = {
project: 'Toryt contracts',
build: build,
'browserstack.console': 'verbose',
'browserstack.user': process.env.BROWSERSTACK_USERNAME,
'browserstack.key': process.env.BROWSERSTACK_ACCESS_KEY
}
const osVersion = {
'OS X': 'High Sierra',
Windows: '10'
}
/* We only test the last version of every combination, by not specifying any version.
By running the tests every week, we stay compatible. */
/* NOTE:
Safari eats stack traces in Web Driver mode (not when tested manually), and skips stack frames in general.
Safari on iOS does very weird things with sometimes not setting a prototype property on new (non arrow) functions,
or setting them 'late'. Some workarounds in tests are provided for this.
Firefox only works with with `--async-polling false`.
In general, runs on all browsers are more stable with `--async-polling false` (though a tad slower).
Edge has trouble with the contract function name (test workaround)
*/
const desktop = [
{ browser: 'Chrome', os: 'OS X' },
{ browser: 'Safari', os: 'OS X' },
{ browser: 'Firefox', os: 'OS X' },
{ browser: 'Chrome', os: 'Windows' },
{ browser: 'Edge', os: 'Windows' },
{ browser: 'Firefox', os: 'Windows' }
].map(d => ({
name: `${d.browser} - ${d.os}`,
capabilities: Object.assign(d, capabilitiesBase, {
os_version: osVersion[d.os]
})
}))
const mobile = ['Samsung Galaxy S9', 'Samsung Galaxy Note 4', 'iPhone X', 'iPad Pro'].map(m => ({
name: m,
capabilities: Object.assign(
{
device: m,
real_mobile: true
},
capabilitiesBase
)
}))
const definitions = desktop.concat(mobile)
console.log(`${definitions.length}:`, definitions.map(d => d.name).join(', '))
module.exports = {
hostname: 'hub-cloud.browserstack.com',
port: 80,
browsers: definitions
}
|
JavaScript
| 0.000001 |
@@ -834,19 +834,14 @@
': '
-High Sierra
+Mojave
',%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.