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
|
---|---|---|---|---|---|---|---|
adb4b70238eb9a971fa9577e38dce87010018eee
|
add missing semicolon
|
lib/AsyncDependenciesBlock.js
|
lib/AsyncDependenciesBlock.js
|
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const DependenciesBlock = require("./DependenciesBlock");
module.exports = class AsyncDependenciesBlock extends DependenciesBlock {
constructor(name, module, loc) {
super();
this.chunkName = name;
this.chunks = null;
this.module = module;
this.loc = loc;
}
get chunk() {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
set chunk(chunk) {
throw new Error("`chunk` was been renamed to `chunks` and is now an array");
}
updateHash(hash) {
hash.update(this.chunkName || "");
hash.update(this.chunks && this.chunks.map((chunk) => {
return typeof chunk.id === "number" ? chunk.id : "";
}).join(",") || "");
super.updateHash(hash);
}
disconnect() {
this.chunks = null;
super.disconnect();
}
unseal() {
this.chunks = null;
super.unseal();
}
sortItems() {
super.sortItems();
if(this.chunks) {
this.chunks.sort((a, b) => {
let i = 0;
while(true) { // eslint-disable-line no-constant-condition
if(!a.modules[i] && !b.modules[i]) return 0;
if(!a.modules[i]) return -1;
if(!b.modules[i]) return 1;
if(a.modules[i].id > b.modules[i].id) return 1;
if(a.modules[i].id < b.modules[i].id) return -1;
i++;
}
});
}
}
}
|
JavaScript
| 0.999999 |
@@ -1338,9 +1338,10 @@
%09%09%7D%0A%09%7D%0A%7D
+;
%0A
|
51479b1ef8d69de06b19589d226b1852ab7bd9b0
|
Update videos.js
|
demo/demoApp/videos.js
|
demo/demoApp/videos.js
|
(function () {
"use strict";
window.App.videos = [
{
title: 'Mjehanik.Voskrjeshenije.2016.D.BDRip 720p.mkv',
url: 'http://www.ex.ua/get/285854084',
type: 'vod'
},
{
title: 'Gotham.S02E18',
url: 'http://fs.to/get/dl/6jw62suuowh2h5cu1j110xqba.0.521872670.974127405.1461398148/Gotham.S02E18.1080p.rus.LostFilm.mkv',
type: 'vod'
},
{
title: 'Redbull',
url: 'http://live.iphone.redbull.de.edgesuite.net/webtvHD.m3u8',
type: 'hls'
}
];
})();
|
JavaScript
| 0 |
@@ -87,49 +87,49 @@
e: '
-Mjehanik.Voskrjeshenije.2016.D.BDRip 720p
+Narcos.S01E10.1080p.WEBRip.Rus.Eng.HDCLUB
.mkv
@@ -175,16 +175,16 @@
et/2
-85854084
+00021097
',%0A
|
c4f0eed38fb43ce2c0afa18676bde430f6ccc6b9
|
fix small typo in cli help menu
|
lib/commands/set-default-argv.js
|
lib/commands/set-default-argv.js
|
var optimist = require('optimist');
var log = require('db-migrate-shared').log;
module.exports = function(internals, isModule) {
var rc = require('rc');
var deepExtend = require('deep-extend');
var defaultConfig = {
verbose: false,
table: 'migrations',
'seeds-table': 'seeds',
'force-exit': false,
'sql-file': false,
'non-transactional': false,
config: internals.configFile || internals.cwd + '/database.json',
'migrations-dir': internals.cwd + '/migrations',
'vcseeder-dir': internals.cwd + '/VCSeeder',
'staticseeder-dir': internals.cwd + '/Seeder',
'ignore-completed-migrations': false
};
if(!isModule) {
internals.argv = optimist
.default(defaultConfig)
.usage(
'Usage: db-migrate [up|down|reset|sync|create|db|transition] ' +
'[[dbname/]migrationName|all] [options]'
)
.describe('env',
'The environment to run the migrations under (dev, test, prod).')
.alias('e', 'env')
.string('e')
.describe('migrations-dir', 'The directory containing your migration files.')
.alias('m', 'migrations-dir')
.string('m')
.describe('count', 'Max number of migrations to run.')
.alias('c', 'count')
.string('c')
.describe('dry-run', 'Prints the SQL but doesn\'t run it.')
.boolean('dry-run')
.describe('force-exit', 'Forcibly exit the migration process on completion.')
.boolean('force-exit')
.describe('verbose', 'Verbose mode.')
.alias('v', 'verbose')
.boolean('v')
.alias('h', 'help')
.alias('h', '?')
.boolean('h')
.describe('version', 'Print version info.')
.alias('i', 'version')
.boolean('version')
.describe('config', 'Location of the database.json file.')
.string('config')
.describe('sql-file',
'Automatically create two sql files for up and down statements in ' +
'/sqls and generate the javascript code that loads them.'
)
.boolean('sql-file')
.describe('coffee-file', 'Create a coffeescript migration file')
.boolean('coffee-file')
.describe('ignore-on-init',
'Create files that will run only if ignore-on-init in the env is set ' +
'to false (currently works onlt with SQL)'
).boolean('ignore-on-init')
.describe('migration-table',
'Set the name of the migration table, which stores the migration history.'
)
.alias('table', 'migration-table')
.alias('t', 'table')
.string('t')
.describe('seeds-table',
'Set the name of the seeds table, which stores the seed history.')
.string('seeds-table')
.describe('vcseeder-dir',
'Set the path to the Version Controlled Seeder directory.')
.string('vcseeder-dir')
.describe('staticseeder-dir', 'Set the path to the Seeder directory.')
.string('staticseeder-dir')
.describe('non-transactional', 'Explicitly disable transactions')
.boolean('non-transactional')
.describe('ignore-completed-migrations', 'Start at the first migration')
.boolean('ignore-completed-migrations')
.describe('log-level', 'Set the log-level, for example sql|warn')
.string('log-level');
}
else {
internals.argv = {
get argv() {
return defaultConfig;
}
};
}
var plugins = internals.plugins;
var plugin = plugins.hook('init:cli:config:hook');
var _config = internals.argv.argv.config;
if(plugin) {
plugin.forEach(function(plugin) {
var configs = plugin['init:cli:config:hook']();
if(!configs) return;
//hook not yet used, we look into migrating away from optimist first
return;
});
}
internals.argv = deepExtend(internals.argv.argv, rc('db-migrate', {}));
internals.argv.rcconfig = internals.argv.config;
internals.argv.config = _config;
if (internals.argv.version) {
console.log(internals.dbm.version);
process.exit(0);
}
if (!isModule && (internals.argv.help || internals.argv._.length === 0)) {
optimist.showHelp();
process.exit(1);
}
if (internals.argv['log-level']) {
log.setLogLevel(internals.argv['log-level']);
}
internals.ignoreCompleted = internals.argv['ignore-completed-migrations'];
internals.migrationTable = internals.argv.table;
internals.seedTable = internals.argv['seeds-table'];
internals.matching = '';
internals.verbose = internals.argv.verbose;
global.verbose = internals.verbose;
internals.notransactions = internals.argv['non-transactional'];
internals.dryRun = internals.argv['dry-run'];
global.dryRun = internals.dryRun;
if (internals.dryRun) {
log.info('dry run');
}
};
|
JavaScript
| 0.000094 |
@@ -2265,17 +2265,17 @@
orks onl
-t
+y
with SQ
|
2991651f7c513cbd4555b5f0be33c70fa56a77e5
|
remove log code
|
evently/tasks/_init/data.js
|
evently/tasks/_init/data.js
|
function(data){
var tasks = [];
for (r in data.rows)
{
tasks.push(data.rows[r]["value"]);
}
$.log(tasks);
return {"tasks": tasks};
}
|
JavaScript
| 0.000006 |
@@ -9,16 +9,56 @@
(data)%7B%0A
+ // restructure data for easier access%0A
var ta
@@ -141,24 +141,8 @@
%7D%0A
- $.log(tasks);%0A
re
|
d612cd6ce4b267677c40fd1ceea88820b382f5e4
|
FIX Firefox file upload
|
src/block_mixins/droppable.js
|
src/block_mixins/droppable.js
|
"use strict";
/* Adds drop functionaltiy to this block */
var _ = require('../lodash');
var $ = require('jquery');
var config = require('../config');
var utils = require('../utils');
var EventBus = require('../event-bus');
module.exports = {
mixinName: "Droppable",
valid_drop_file_types: ['File', 'Files', 'text/plain', 'text/uri-list'],
requireInputs: true,
initializeDroppable: function() {
utils.log("Adding droppable to block " + this.blockID);
this.drop_options = Object.assign({}, config.defaults.Block.drop_options, this.drop_options);
var drop_html = $(_.template(this.drop_options.html,
{ block: this, _: _ }));
this.$editor.hide();
this.$inputs.append(drop_html);
this.$dropzone = drop_html;
// Bind our drop event
this.$dropzone.dropArea()
.bind('drop', this._handleDrop.bind(this));
this.$inner.addClass('st-block__inner--droppable');
},
_handleDrop: function(e) {
e.preventDefault();
e = e.originalEvent;
var el = $(e.target),
types = e.dataTransfer.types;
el.removeClass('st-dropzone--dragover');
/*
Check the type we just received,
delegate it away to our blockTypes to process
*/
if (types &&
types.some(function(type) {
return this.valid_drop_file_types.includes(type);
}, this)) {
this.onDrop(e.dataTransfer);
}
EventBus.trigger('block:content:dropped', this.blockID);
}
};
|
JavaScript
| 0 |
@@ -1075,16 +1075,30 @@
types =
+this._toArray(
e.dataTr
@@ -1109,16 +1109,17 @@
er.types
+)
;%0A%0A e
@@ -1523,16 +1523,278 @@
ockID);%0A
+ %7D,%0A %0A _toArray: function(obj) %7B%0A if (Array.isArray(obj)) return obj;%0A %0A var array = %5B%5D;%0A %0A // iterate backwards ensuring that length is an UInt32%0A for (var i = obj.length %3E%3E%3E 0; i--;) %7B%0A array%5Bi%5D = obj%5Bi%5D;%0A %7D%0A %0A return array;%0A
%7D%0A%0A%7D;%0A
|
68741e92b5afc1fd1832a9a223bd37b75126263b
|
improve readability of hasValue in formField
|
packages/app-extensions/src/formField/formField.js
|
packages/app-extensions/src/formField/formField.js
|
import React from 'react'
import PropTypes from 'prop-types'
import _get from 'lodash/get'
import {StatedValue} from 'tocco-ui'
import {consoleLogger} from 'tocco-util'
import fromData from '../formData'
import typeEditables from './typeEditable'
const FormFieldWrapper = props => {
const hasValueOverwrite = props.typeEditable && props.typeEditable.hasValue
&& props.typeEditable.hasValue(props.formData.formValues, props.formField)
return <StatedValue
{...props}
dirty={props.formData.isDirty || props.dirty}
error={props.formData.errors || props.error}
hasValue={hasValueOverwrite || props.hasValue}
>
{React.cloneElement(props.children, {formData: props.formData})}
</StatedValue>
}
FormFieldWrapper.propTypes = {
typeEditable: PropTypes.object,
children: PropTypes.node,
formData: PropTypes.object,
formField: PropTypes.object,
dirty: PropTypes.bool,
error: PropTypes.object,
hasValue: PropTypes.bool
}
export const formFieldFactory = (mapping, data, resources = {}) => {
try {
const {
formDefinitionField,
modelField,
entityField,
id,
value,
dirty,
touched,
events,
error,
submitting,
readOnlyForm,
formName
} = data
const readOnly = (
readOnlyForm
|| formDefinitionField.readonly
|| submitting
|| !_get(entityField, 'writable', true)
)
const mandatory = !readOnly && _get(modelField, `validation.mandatory`, false)
const hasValue = value !== null && value !== undefined && value.length !== 0
const isDisplay = data.formDefinitionField.componentType === 'display' || readOnlyForm
const type = formDefinitionField.dataType
let requestedFromData
const typeEditable = typeEditables[type]
if (typeEditable && typeEditable.dataContainerProps) {
requestedFromData = typeEditable.dataContainerProps({formField: formDefinitionField, modelField, formName})
}
const fixLabel = typeEditable && typeEditable.fixLabel && typeEditable.fixLabel()
return (
<fromData.FormDataContainer {...requestedFromData}>
<FormFieldWrapper
typeEditable={typeEditable}
dirty={dirty}
error={error}
hasValue={hasValue}
id={id}
immutable={readOnly}
isDisplay={isDisplay}
key={id}
label={formDefinitionField.label}
mandatory={mandatory}
mandatoryTitle={resources.mandatoryTitle}
touched={touched}
fixLabel={fixLabel}
formField={formDefinitionField}
>
<ValueField
mapping={mapping}
formName={formName}
formField={formDefinitionField}
modelField={modelField}
value={value}
info={{id, readOnly, mandatory}}
events={events}
/>
</FormFieldWrapper>
</fromData.FormDataContainer>
)
} catch (exception) {
consoleLogger.logError('Error creating formField', exception)
return <span/>
}
}
const ValueField = props => {
const {mapping, formName, formField, modelField, value, info, events, formData} = props
const type = formField.dataType ? 'dataType' : 'componentType'
let typeFactory = mapping[formField[type]]
if (!typeFactory) {
consoleLogger.log(`FormType '${formField.dataType}' not present in typeFactoryMap`)
return <span/>
} else if (typeof typeFactory === 'object') {
typeFactory = typeFactory[modelField.type]
if (!typeFactory) {
consoleLogger.log(
`FormType '${formField.dataType}' not present in typeFactoryMap for model field type ${modelField.type}`
)
return <span/>
}
}
return typeFactory(formField, modelField, formName, value, info, events, formData)
}
|
JavaScript
| 0.000005 |
@@ -1544,24 +1544,25 @@
ndefined &&
+(
value.length
@@ -1566,13 +1566,42 @@
gth
-!== 0
+=== undefined %7C%7C value.length %3E 0)
%0A
|
58c9ea2fd1d9ab67ab19b17200002ee50a343d8f
|
Return promise for build
|
.task/tasks/build.js
|
.task/tasks/build.js
|
'use strict';
var wrench = require('wrench');
var bower = require('./bower');
var exec = require('../lib/execute');
var platforms = require('../../.setup/platform').platforms;
var environments = require('../../.setup/environment').environments;
var build = module.exports = Object.create(exec);
build.command = './node_modules/.bin/brunch';
// Generate alias for each build command combination
['once', 'watch', 'server'].forEach(function(type) {
if(!build[type]) {
build[type] = {};
}
platforms.forEach(function(platform) {
if(!build[type][platform]) {
build[type][platform] = {};
}
environments.forEach(function(environment) {
build[type][platform][environment] = function() {
build.run(type, platform, environment);
};
});
});
});
build.run = function(type, platform, environment) {
var env = platform + ':' + environment;
var self = this;
var args = ['-e', env];
// Determine which Brunch command to run
switch(type) {
case 'once':
args.unshift('build');
break;
case 'watch':
args.unshift('watch');
break;
case 'server':
args.unshift('watch', '-s');
break;
}
// Before running the brunch command let's clear the public folder
var config = require('../../brunch-config').config.overrides[env];
wrench.rmdirSyncRecursive(config.paths.public, function() {});
return bower.install().done(function() {
self.execute(args);
});
};
|
JavaScript
| 0 |
@@ -713,24 +713,31 @@
) %7B%0A
+return
build.run(ty
|
86b9d257fa0da2492f3df89a3842a653adbfbb52
|
add ability to override ajax async flag
|
backbone.nativeajax.js
|
backbone.nativeajax.js
|
// Backbone.NativeAjax.js 0.4.3
// ---------------
// (c) 2015 Adam Krebs, Paul Miller, Exoskeleton Project
// Backbone.NativeAjax may be freely distributed under the MIT license.
// For all details and documentation:
// https://github.com/akre54/Backbone.NativeAjax
(function (factory) {
if (typeof define === 'function' && define.amd) { define(factory);
} else if (typeof exports === 'object') { module.exports = factory();
} else { Backbone.ajax = factory(); }
}(function() {
// Make an AJAX request to the server.
// Usage:
// var req = Backbone.ajax({url: 'url', type: 'PATCH', data: 'data'});
// req.then(..., ...) // if Promise is set
var ajax = (function() {
var xmlRe = /^(?:application|text)\/xml/;
var jsonRe = /^application\/json/;
var getData = function(accepts, xhr) {
if (accepts == null) accepts = xhr.getResponseHeader('content-type');
if (xmlRe.test(accepts)) {
return xhr.responseXML;
} else if (jsonRe.test(accepts) && xhr.responseText !== '') {
return JSON.parse(xhr.responseText);
} else {
return xhr.responseText;
}
};
var isValid = function(xhr) {
return (xhr.status >= 200 && xhr.status < 300) ||
(xhr.status === 304) ||
(xhr.status === 0 && window.location.protocol === 'file:')
};
var end = function(xhr, options, promise, resolve, reject) {
return function() {
updatePromise(xhr, promise);
if (xhr.readyState !== 4) return;
var status = xhr.status;
var data = getData(options.headers && options.headers.Accept, xhr);
// Check for validity.
if (isValid(xhr)) {
if (options.success) options.success(data);
if (resolve) resolve(data);
} else {
var error = new Error('Server responded with a status of ' + status);
if (options.error) options.error(xhr, status, error);
if (reject) reject(xhr);
}
}
};
var updatePromise = function(xhr, promise) {
if (!promise) return;
var props = ['readyState', 'status', 'statusText', 'responseText',
'responseXML', 'setRequestHeader', 'getAllResponseHeaders',
'getResponseHeader', 'statusCode', 'abort'];
for (var i = 0; i < props.length; i++) {
var prop = props[i];
promise[prop] = typeof xhr[prop] === 'function' ?
xhr[prop].bind(xhr) :
xhr[prop];
}
return promise;
}
return function(options) {
if (options == null) throw new Error('You must provide options');
if (options.type == null) options.type = 'GET';
var resolve, reject, xhr = new XMLHttpRequest();
var PromiseFn = ajax.Promise || (typeof Promise !== 'undefined' && Promise);
var promise = PromiseFn && new PromiseFn(function(res, rej) {
resolve = res;
reject = rej;
});
if (options.contentType) {
if (options.headers == null) options.headers = {};
options.headers['Content-Type'] = options.contentType;
}
// Stringify GET query params.
if (options.type === 'GET' && typeof options.data === 'object') {
var query = '';
var stringifyKeyValuePair = function(key, value) {
return value == null ? '' :
'&' + encodeURIComponent(key) +
'=' + encodeURIComponent(value);
};
for (var key in options.data) {
query += stringifyKeyValuePair(key, options.data[key]);
}
if (query) {
var sep = (options.url.indexOf('?') === -1) ? '?' : '&';
options.url += sep + query.substring(1);
}
}
xhr.onreadystatechange = end(xhr, options, promise, resolve, reject);
xhr.open(options.type, options.url, true);
if(!(options.headers && options.headers.Accept)) {
var allTypes = "*/".concat("*");
var xhrAccepts = {
"*": allTypes,
text: "text/plain",
html: "text/html",
xml: "application/xml, text/xml",
json: "application/json, text/javascript"
};
xhr.setRequestHeader(
"Accept",
options.dataType && xhrAccepts[options.dataType] ?
xhrAccepts[options.dataType] + (options.dataType !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
xhrAccepts["*"]
);
}
if (options.headers) for (var key in options.headers) {
xhr.setRequestHeader(key, options.headers[key]);
}
if (options.beforeSend) options.beforeSend(xhr);
xhr.send(options.data);
options.originalXhr = xhr;
updatePromise(xhr, promise);
return promise ? promise : xhr;
};
})();
return ajax;
}));
|
JavaScript
| 0.000001 |
@@ -3845,11 +3845,30 @@
rl,
-tru
+options.async !== fals
e);%0A
|
37ba6c54573d829ec16acd166c421df742a16d57
|
fix leaderboard test
|
server/controllers/scores.test.js
|
server/controllers/scores.test.js
|
const request = require('superagent')
const expect = require('chai').expect
const config = require('../config')
const codes = require('../utils/codes')
const SCORES_URL = `localhost:${config.PORT}/api/scores/`
describe('Score API', function() {
describe('Update score', function() {
it('error without auth token', function(done) {
request
.put(SCORES_URL + global.testWordId)
.send({
direction: 'fromEnglish',
score: 1
})
.end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('missingAuthToken')
done()
})
})
it('error on invalid direction', function(done) {
request
.put(SCORES_URL + global.testWordId)
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'test',
score: 1
})
.end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('directionInvalid')
done()
})
})
it('error on score below 0', function(done) {
request
.put(SCORES_URL + global.testWordId)
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'fromEnglish',
score: -1
})
.end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('scoreInvalid')
done()
})
})
it('error on score above 6', function(done) {
request
.put(SCORES_URL + global.testWordId)
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'fromEnglish',
score: 7
})
.end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('scoreInvalid')
done()
})
})
it('error on invalid word id', function(done) {
request
.put(SCORES_URL + '123')
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'fromEnglish',
score: 1
})
.end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('wordIdInvalid')
done()
})
})
it('success on updated score fromEnglish', function(done) {
request
.put(SCORES_URL + global.testWordId)
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'fromEnglish',
score: 0
})
.end((err, resp) => {
expect(err).to.be.null
done()
})
})
it('success on update score fromPersian', function(done) {
request
.put(SCORES_URL + global.testWordId)
.set('Authorization', 'Bearer ' + global.testUserToken)
.send({
direction: 'fromPersian',
score: 6
})
.end((err, resp) => {
expect(err).to.be.null
done()
})
})
})
describe('Fetch scores', function() {
it('error on fetch scores with auth token', function(done) {
request.get(SCORES_URL).end((err, resp) => {
expect(err).to.not.be.null
expect(err.response.body.code).to.equal('missingAuthToken')
done()
})
})
it('success on fetch scores', function(done) {
request
.get(SCORES_URL)
.set('Authorization', 'Bearer ' + global.testUserToken)
.end((err, resp) => {
expect(err).to.be.null
expect(resp.body).to.have.lengthOf(1)
expect(resp.body[0].fromEnglish.score).to.equal(0)
expect(resp.body[0].fromPersian.score).to.equal(6)
done()
})
})
})
describe('Fetch leaderboard', function() {
it('success on fetching leaderboard', function(done) {
request
.get(`localhost:${config.PORT}/api/users/leaderboard`)
.end((err, resp) => {
expect(err).to.be.null
expect(resp.status).to.equal(200)
expect(resp.body).to.have.lengthOf(2)
expect(resp.body[1].quizzedWords).to.equal(1)
expect(resp.body[1].score).to.equal(6)
done()
})
})
})
})
|
JavaScript
| 0.000008 |
@@ -4131,16 +4131,97 @@
thOf(2)%0A
+ const testUser = resp.body.find(user =%3E (user.username = 'test_user'))%0A
@@ -4229,28 +4229,71 @@
expect(
-resp.body%5B1%5D
+testUser).to.not.be.undefined%0A expect(testUser
.quizzed
@@ -4332,20 +4332,16 @@
ect(
-resp.body%5B1%5D
+testUser
.sco
|
84f69eb27f646ee089901660252839cf143f6e87
|
Fix HTTP redirection for the extension
|
extensions/firefox/components/PdfStreamConverter.js
|
extensions/firefox/components/PdfStreamConverter.js
|
/* -*- Mode: Java; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */
/* vim: set shiftwidth=2 tabstop=2 autoindent cindent expandtab: */
'use strict';
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
const Cu = Components.utils;
const PDFJS_EVENT_ID = 'pdf.js.message';
const PDF_CONTENT_TYPE = 'application/pdf';
const NS_ERROR_NOT_IMPLEMENTED = 0x80004001;
const EXT_PREFIX = '[email protected]';
Cu.import('resource://gre/modules/XPCOMUtils.jsm');
Cu.import('resource://gre/modules/Services.jsm');
function log(aMsg) {
let msg = 'PdfStreamConverter.js: ' + (aMsg.join ? aMsg.join('') : aMsg);
Cc['@mozilla.org/consoleservice;1'].getService(Ci.nsIConsoleService)
.logStringMessage(msg);
dump(msg + '\n');
}
let application = Cc['@mozilla.org/fuel/application;1']
.getService(Ci.fuelIApplication);
let privateBrowsing = Cc['@mozilla.org/privatebrowsing;1']
.getService(Ci.nsIPrivateBrowsingService);
let inPrivateBrowswing = privateBrowsing.privateBrowsingEnabled;
// All the priviledged actions.
function ChromeActions() {
this.inPrivateBrowswing = privateBrowsing.privateBrowsingEnabled;
}
ChromeActions.prototype = {
download: function(data) {
Services.wm.getMostRecentWindow('navigator:browser').saveURL(data);
},
setDatabase: function(data) {
if (this.inPrivateBrowswing)
return;
application.prefs.setValue(EXT_PREFIX + '.database', data);
},
getDatabase: function() {
if (this.inPrivateBrowswing)
return '{}';
return application.prefs.getValue(EXT_PREFIX + '.database', '{}');
}
};
// Event listener to trigger chrome privedged code.
function RequestListener(actions) {
this.actions = actions;
}
// Receive an event and synchronously responds.
RequestListener.prototype.receive = function(event) {
var message = event.target;
var action = message.getUserData('action');
var data = message.getUserData('data');
var actions = this.actions;
if (!(action in actions)) {
log('Unknown action: ' + action);
return;
}
var response = actions[action].call(this.actions, data);
message.setUserData('response', response, null);
};
function PdfStreamConverter() {
}
PdfStreamConverter.prototype = {
// properties required for XPCOM registration:
classID: Components.ID('{6457a96b-2d68-439a-bcfa-44465fbcdbb1}'),
classDescription: 'pdf.js Component',
contractID: '@mozilla.org/streamconv;1?from=application/pdf&to=*/*',
QueryInterface: XPCOMUtils.generateQI([
Ci.nsISupports,
Ci.nsIStreamConverter,
Ci.nsIStreamListener,
Ci.nsIRequestObserver
]),
/*
* This component works as such:
* 1. asyncConvertData stores the listener
* 2. onStartRequest creates a new channel, streams the viewer and cancels
* the request so pdf.js can do the request
* Since the request is cancelled onDataAvailable should not be called. The
* onStopRequest does nothing. The convert function just returns the stream,
* it's just the synchronous version of asyncConvertData.
*/
// nsIStreamConverter::convert
convert: function(aFromStream, aFromType, aToType, aCtxt) {
return aFromStream;
},
// nsIStreamConverter::asyncConvertData
asyncConvertData: function(aFromType, aToType, aListener, aCtxt) {
if (!Services.prefs.getBoolPref('extensions.pdf.js.active'))
throw NS_ERROR_NOT_IMPLEMENTED;
// Store the listener passed to us
this.listener = aListener;
},
// nsIStreamListener::onDataAvailable
onDataAvailable: function(aRequest, aContext, aInputStream, aOffset, aCount) {
// Do nothing since all the data loading is handled by the viewer.
log('SANITY CHECK: onDataAvailable SHOULD NOT BE CALLED!');
},
// nsIRequestObserver::onStartRequest
onStartRequest: function(aRequest, aContext) {
// Setup the request so we can use it below.
aRequest.QueryInterface(Ci.nsIChannel);
// Cancel the request so the viewer can handle it.
aRequest.cancel(Cr.NS_BINDING_ABORTED);
// Create a new channel that is viewer loaded as a resource.
var ioService = Cc['@mozilla.org/network/io-service;1']
.getService(Ci.nsIIOService);
var channel = ioService.newChannel(
'resource://pdf.js/web/viewer.html', null, null);
// Keep the URL the same so the browser sees it as the same.
channel.originalURI = aRequest.originalURI;
channel.asyncOpen(this.listener, aContext);
// Setup a global listener waiting for the next DOM to be created and verfiy
// that its the one we want by its URL. When the correct DOM is found create
// an event listener on that window for the pdf.js events that require
// chrome priviledges.
var url = aRequest.originalURI.spec;
var gb = Services.wm.getMostRecentWindow('navigator:browser');
var domListener = function domListener(event) {
var doc = event.originalTarget;
var win = doc.defaultView;
if (doc.location.href === url) {
gb.removeEventListener('DOMContentLoaded', domListener);
var requestListener = new RequestListener(new ChromeActions());
win.addEventListener(PDFJS_EVENT_ID, function(event) {
requestListener.receive(event);
}, false, true);
}
};
gb.addEventListener('DOMContentLoaded', domListener, false);
},
// nsIRequestObserver::onStopRequest
onStopRequest: function(aRequest, aContext, aStatusCode) {
// Do nothing.
}
};
var NSGetFactory = XPCOMUtils.generateNSGetFactory([PdfStreamConverter]);
|
JavaScript
| 0.000458 |
@@ -4492,24 +4492,16 @@
Request.
-original
URI;%0A
@@ -4833,24 +4833,16 @@
Request.
-original
URI.spec
|
2f7860f17f89b2ec1fe518ec4fda659526338036
|
change config loading order
|
lib/core_modules/config/index.js
|
lib/core_modules/config/index.js
|
'use strict';
var Q = require('q'),
fs = require('fs'),
_ = require('lodash');
function mergeConfig(original, saved) {
var clean = {};
for (var index in saved) {
clean[index] = saved[index].value;
if (original[index]) {
original[index].value = saved[index].value;
} else {
original[index] = {
value: saved[index].value
};
}
original[index]['default'] = original[index]['default'] || saved[index]['default'];
}
return {
diff: original,
clean: clean
};
}
function loadConfig() {
// Load configurations
// Set the node environment variable if not set before
var configPath = process.cwd() + '/config/env';
process.env.NODE_ENV = ~fs.readdirSync(configPath).map(function(file) {
return file.slice(0, -3);
}).indexOf(process.env.NODE_ENV) ? process.env.NODE_ENV : 'development';
// Extend the base configuration in all.js with environment
// specific configuration
return _.extend(
require(configPath + '/all'),
require(configPath + '/' + process.env.NODE_ENV) || {}
);
}
function Config(defaultconfig) {
defaultconfig = defaultconfig || loadConfig();
this.verbose = {};
this.original = JSON.flatten(defaultconfig, {
default: true
});
this.clean = null;
this.diff = null;
this.flat = null;
this.createConfigurations(defaultconfig);
}
Config.prototype.loadSettings = function(defer) {
var Package = this.loadPackageModel(this.onPackageForSettingsLoaded.bind(this,defer));
};
Config.prototype.onPackageForSettingsLoaded = function(defer,Package){
if (!Package){
defer.resolve(this.original);
}
Package.findOne({
name: 'config'
}, this.onPackageRead.bind(this,defer));
};
Config.prototype.updateSettings = function(name, settings, callback) {
var Package = this.loadPackageModel(this.onPackageForUpdateLoaded.bind(this,callback,settings));
};
Config.prototype.onPackageForUpdateLoaded = function(callback,settings,Package){
if (!Package){
return callback ? callback(new Error('Failed to update settings')) : undefined;
}
Package.findOneAndUpdate({
name: name
}, {
$set: {
settings: settings,
updated: new Date()
}
}, {
upsert: true,
multi: false
}, function(err, doc) {
if (err) {
console.log(err);
return callback(new Error('Failed to update settings'));
}
return callback(null, doc);
});
};
Config.prototype.getSettings = function(name, callback) {
var Package = this.loadPackageModel();
if (!Package){
return callback ? callback(new Error('Failed to retrieve settings')) : undefined;
}
Package.findOne({
name: name
}, function(err, doc) {
if (err) {
console.log(err);
return callback(new Error('Failed to retrieve settings'));
}
return callback(null, doc);
});
};
Config.prototype.loadPackageModel = function(callback) {
var database = Config.Meanio.resolve('database',this.onDatabaseLoadPackageModel.bind(this,callback));
};
Config.prototype.onDatabaseLoadPackageModel = function(callback,database){
if (!database || !database.connection) {
callback(null);
return;
}
if (!database.connection.models.Package) {
require('./package')(database);
}
callback(database.connection.model('Package'));
};
Config.prototype.onPackageRead = function(defer,err,doc){
if (err) {
defer.resolve(err); //problematic, but the whole code needs to be changed to support err exception
return;
}
if(!(doc&&doc.settings)){
defer.resolve();
return;
}
this.createConfigurations(doc.settings);
defer.resolve();
};
Config.prototype.createConfigurations = function(config){
var saved = JSON.flatten(config, {});
var merged = mergeConfig(this.original, saved);
var clean = JSON.unflatten(merged.clean, {});
var diff = JSON.unflatten(merged.diff, {});
this.verbose = {
clean: clean,
diff: diff,
flat: merged
};
this.clean = clean;
this.diff = diff;
this.flat = merged;
};
Config.prototype.update = function(settings, callback) {
var Package = this.loadPackageModel();
if (!Package) return callback(new Error('failed to load data model'));
var defer = Q.defer();
Package.findOneAndUpdate({
name: 'config'
}, {
$set: {
settings: settings,
updated: new Date()
}
}, {
upsert: true,
new: true,
multi: false
}, this.onPackageRead.bind(this,defer));
defer.promise.then(callback);
};
function onInstance(Meanio,meanioinstance,defer){
Config.Meanio = meanioinstance;
meanioinstance.config = new Config();
meanioinstance.register('defaultconfig',meanioinstance.config);
meanioinstance.resolve('database',meanioinstance.config.loadSettings.bind(meanioinstance.config,defer));
}
function createConfig(Meanio){
Meanio.onInstance(onInstance.bind(null,Meanio));
Meanio.Config = Config;
}
module.exports = createConfig;
|
JavaScript
| 0.000001 |
@@ -140,16 +140,127 @@
n = %7B%7D;%0A
+ for (var index in original) %7B%0A if (!saved%5Bindex%5D) %7B%0A clean%5Bindex%5D = original%5Bindex%5D.value;%0A %7D%0A %7D%0A
for (v
|
89e77b68baff5391e93d141b0d57744c5d604ee6
|
Improve ordering
|
lib/get/get-full-source-space.js
|
lib/get/get-full-source-space.js
|
import Promise from 'bluebird'
import Listr from 'listr'
import verboseRenderer from 'listr-verbose-renderer'
import sortEntries from '../utils/sort-entries'
const MAX_ALLOWED_LIMIT = 1000
let pageLimit = MAX_ALLOWED_LIMIT
/**
* Gets all the content from a space via the management API. This includes
* content in draft state.
*/
export default function getFullSourceSpace ({
managementClient,
deliveryClient,
spaceId,
skipContentModel,
skipContent,
skipWebhooks,
skipRoles,
includeDrafts,
maxAllowedLimit,
listrOptions
}) {
pageLimit = maxAllowedLimit || MAX_ALLOWED_LIMIT
listrOptions = listrOptions || {
renderer: verboseRenderer
}
return new Listr([
{
title: 'Connecting to space',
task: (ctx) => {
return managementClient.getSpace(spaceId)
.then((space) => {
ctx.space = space
})
.catch((err) => {
console.error(`
The destination space was not found. This can happen for multiple reasons:
- If you haven't yet, you should create your space manually.
- If your destination space is in another organization, and your user from the source space does not have access to it, you'll need to specify separate sourceManagementToken and destinationManagementToken
Full error details below.
`)
throw err
})
}
},
{
title: 'Fetching content types data',
task: (ctx) => {
return pagedGet(ctx.space, 'getContentTypes')
.then(extractItems)
.then((items) => {
ctx.data.contentTypes = items
})
},
skip: () => skipContentModel
},
{
title: 'Fetching editor interfaces data',
task: (ctx) => {
return getEditorInterfaces(ctx.data.contentTypes)
.then((editorInterfaces) => {
ctx.data.editorInterfaces = editorInterfaces.filter((editorInterface) => {
return editorInterface !== null
})
})
},
skip: (ctx) => skipContentModel || (ctx.data.contentTypes.length === 0 && 'Skipped since no content types downloaded')
},
{
title: 'Fetching content entries data',
task: (ctx) => {
return pagedGet(ctx.space, 'getEntries')
.then(extractItems)
.then(sortEntries)
.then((items) => filterDrafts(items, includeDrafts))
.then((items) => {
ctx.data.entries = items
})
},
skip: () => skipContent
},
{
title: 'Fetching assets data',
task: (ctx) => {
return pagedGet(ctx.space, 'getAssets')
.then(extractItems)
.then((items) => {
ctx.data.assets = items
})
},
skip: () => skipContent
},
{
title: 'Fetching locales data',
task: (ctx) => {
return pagedGet(ctx.space, 'getLocales')
.then(extractItems)
.then((items) => {
ctx.data.locales = items
})
},
skip: () => skipContentModel
},
{
title: 'Fetching webhooks data',
task: (ctx) => {
return pagedGet(ctx.space, 'getWebhooks')
.then(extractItems)
.then((items) => {
ctx.data.webhooks = items
})
},
skip: () => skipWebhooks
},
{
title: 'Fetching roles data',
task: (ctx) => {
return pagedGet(ctx.space, 'getRoles')
.then(extractItems)
.then((items) => {
ctx.data.roles = items
})
},
skip: () => skipRoles
}
], listrOptions)
}
function getEditorInterfaces (contentTypes) {
const editorInterfacePromises = contentTypes.map((contentType) => {
// old contentTypes may not have an editor interface but we'll handle in a later stage
// but it should not stop getting the data process
return contentType.getEditorInterface().catch(() => {
return Promise.resolve(null)
})
})
return Promise.all(editorInterfacePromises)
}
/**
* Gets all the existing entities based on pagination parameters.
* The first call will have no aggregated response. Subsequent calls will
* concatenate the new responses to the original one.
*/
function pagedGet (space, method, skip = 0, aggregatedResponse = null) {
return space[method]({
skip: skip,
limit: pageLimit,
order: 'sys.createdAt'
})
.then((response) => {
if (!aggregatedResponse) {
aggregatedResponse = response
} else {
aggregatedResponse.items = aggregatedResponse.items.concat(response.items)
}
if (skip + pageLimit <= response.total) {
return pagedGet(space, method, skip + pageLimit, aggregatedResponse)
}
return aggregatedResponse
})
}
function extractItems (response) {
return response.items
}
function filterDrafts (items, includeDrafts) {
return includeDrafts ? items : items.filter((item) => !!item.sys.publishedVersion)
}
|
JavaScript
| 0 |
@@ -4293,16 +4293,23 @@
reatedAt
+,sys.id
'%0A %7D)%0A
|
9fff2d3941e648b4d54a8c39efa76e632c2f47f1
|
Reset related concepts when we run a new query. [rev: jon.soul]
|
find-core/src/main/public/static/js/find/app/page/search/input-view.js
|
find-core/src/main/public/static/js/find/app/page/search/input-view.js
|
define([
'backbone',
'jquery',
'underscore',
'find/app/util/string-blank',
'i18n!find/nls/bundle',
'text!find/templates/app/page/search/input-view.html',
'typeahead'
], function(Backbone, $, _, stringBlank, i18n, template) {
var html = _.template(template)({i18n: i18n});
var relatedConceptsTemplate = _.template(
'<span class="selected-related-concepts" data-id="<%-concept%>">' +
'<%-concept%> <i class="clickable hp-icon hp-fw hp-close concepts-remove-icon"></i>' +
'</span> '
);
return Backbone.View.extend({
events: {
'submit .find-form': function(event) {
event.preventDefault();
this.search(this.$input.typeahead('val'));
this.$input.typeahead('close');
},
'typeahead:select': function() {
this.search(this.$input.typeahead('val'));
},
'click .concepts-remove-icon': function(e) {
var id = $(e.currentTarget).closest("span").attr('data-id');
this.removeRelatedConcept(id);
},
'click .see-all-documents': function() {
this.search('*');
}
},
initialize: function(options) {
this.listenTo(this.model, 'change:inputText', this.updateText);
this.listenTo(this.model, 'change:relatedConcepts', this.updateRelatedConcepts);
this.search = _.debounce(function(query) {
options.model.set({inputText: query});
}, 500);
},
render: function() {
this.$el.html(html);
this.$input = this.$('.find-input');
this.$additionalConcepts = this.$('.additional-concepts');
this.$alsoSearchingFor = this.$('.also-searching-for');
this.$input.typeahead({
hint: false,
hightlight: true,
minLength: 1
}, {
async: true,
limit: 7,
source: function(query, sync, async) {
// Don't look for suggestions if the query is blank
if (stringBlank(query)) {
sync([]);
} else {
$.get('../api/public/typeahead', {
text: query
}, function(results) {
async(results);
});
}
}
});
this.updateText();
this.updateRelatedConcepts();
},
updateText: function() {
if (this.$input) {
this.$input.typeahead('val', this.model.get('inputText'));
this.$('.see-all-documents').toggleClass('disabled-clicks cursor-not-allowed', this.model.get('inputText') === '*');
}
},
updateRelatedConcepts: function() {
if (this.$additionalConcepts) {
this.$additionalConcepts.empty();
_.each(this.model.get('relatedConcepts'), function(concept) {
this.$additionalConcepts.append(relatedConceptsTemplate({
concept: concept
}))
}, this);
this.$alsoSearchingFor.toggleClass('hide', _.isEmpty(this.model.get('relatedConcepts')));
}
},
removeRelatedConcept: function(id){
var newConcepts = _.without(this.model.get('relatedConcepts'), id);
this.model.set('relatedConcepts', newConcepts);
}
});
});
|
JavaScript
| 0 |
@@ -1561,24 +1561,103 @@
et(%7B
-inputText: query
+%0A inputText: query,%0A relatedConcepts: %5B%5D%0A
%7D);%0A
@@ -3393,16 +3393,17 @@
%7D))
+;
%0A
|
2f5b49bbf0c02225f62b950b393bdcdd99c62a95
|
Fix two line input on cd.
|
javascript/react.js
|
javascript/react.js
|
var jQuery = require('jquery');
var Terminal = require('./compiled/Terminal');
var React = require('react');
var _ = require('lodash');
jQuery(document).ready(function () {
window.terminal = new Terminal(getDimensions());
jQuery(window).resize(function() {
terminal.resize(getDimensions());
});
React.render(<Board terminal={window.terminal}/>, document.getElementById('black-board'));
jQuery(document).keydown(function(event) {
focusLastInput(event);
});
});
var Board = React.createClass({
componentDidMount: function () {
this.props.terminal.on('invocation', this.forceUpdate.bind(this));
},
handleKeyDown: function (event) {
// Ctrl+l
if (event.ctrlKey && event.keyCode === 76) {
this.props.terminal.clearInvocations();
event.stopPropagation();
event.preventDefault();
}
},
render: function () {
var invocations = this.props.terminal.invocations.map(function (invocation) {
return (
<Invocation key={invocation.id} invocation={invocation}/>
)
});
return (
<div id="board" onKeyDown={this.handleKeyDown}>
<div id="invocations">
{invocations}
</div>
<StatusLine currentWorkingDirectory={this.props.terminal.currentDirectory}/>
</div>
);
}
});
var Invocation = React.createClass({
componentDidMount: function () {
this.props.invocation.on('data', function () {
this.setState({ canBeDecorated: this.props.invocation.canBeDecorated()});
}.bind(this));
},
componentDidUpdate: scrollToBottom,
getInitialState: function() {
return {
decorate: true,
canBeDecorated: this.props.invocation.canBeDecorated()
};
},
render: function () {
var buffer, decorationToggle;
if (this.state.decorate && this.state.canBeDecorated) {
buffer = this.props.invocation.decorate();
} else {
buffer = this.props.invocation.getBuffer().render();
}
if (this.props.invocation.canBeDecorated()) {
decorationToggle = <DecorationToggle invocation={this}/>;
}
return (
<div className="invocation">
<Prompt prompt={this.props.invocation.getPrompt()} status={this.props.invocation.status}/>
{decorationToggle}
{buffer}
</div>
);
}
});
var DecorationToggle = React.createClass({
getInitialState: function() {
return {enabled: this.props.invocation.state.decorate};
},
handleClick: function() {
var newState = !this.state.enabled;
this.setState({enabled: newState});
this.props.invocation.setState({decorate: newState});
},
render: function () {
var classes = ['decoration-toggle'];
if (!this.state.enabled) {
classes.push('disabled');
}
return (
<a href="#" className={classes.join(' ')} onClick={this.handleClick}>
<i className="fa fa-magic"></i>
</a>
);
}
});
var Prompt = React.createClass({
getInputNode: function () {
return this.refs.command.getDOMNode()
},
componentDidMount: function () {
this.getInputNode().focus();
},
handleKeyUp: function (event) {
this.props.prompt.buffer.setTo(event.target.innerText);
},
handleKeyDown: function (event) {
if (event.keyCode == 13) {
event.stopPropagation();
event.preventDefault();
this.props.prompt.send(event.target.innerText);
}
// Ctrl+P, ↑.
if ((event.ctrlKey && event.keyCode === 80) || event.keyCode === 38) {
var prevCommand = this.props.prompt.history.getPrevious();
if (typeof prevCommand != 'undefined') {
var target = event.target;
withCaret(target, function(){
target.innerText = prevCommand;
return target.innerText.length;
});
}
event.stopPropagation();
event.preventDefault();
}
// Ctrl+N, ↓.
if ((event.ctrlKey && event.keyCode === 78) || event.keyCode === 40) {
var command = this.props.prompt.history.getNext();
target = event.target;
withCaret(target, function(){
target.innerText = command || '';
return target.innerText.length;
});
event.stopPropagation();
event.preventDefault();
}
},
handleInput: function (event) {
var target = event.target;
withCaret(target, function(oldPosition){
// Do syntax highlighting.
//target.innerText = target.innerText.toUpperCase();
return oldPosition;
});
},
render: function () {
var classes = ['prompt', this.props.status].join(' ');
return (
<div className="prompt-wrapper">
<div className="prompt-decoration">
<div className="arrow"/>
</div>
<div className={classes}
onKeyDown={this.handleKeyDown}
onKeyUp={this.handleKeyUp}
onInput={this.handleInput}
type="text"
ref="command"
contentEditable="true" />
</div>
)
}
});
var StatusLine = React.createClass({
render: function () {
return (
<div id="status-line">
<CurrentDirectory currentWorkingDirectory={this.props.currentWorkingDirectory}/>
</div>
)
}
});
var CurrentDirectory = React.createClass({
render: function () {
return (
<div id="current-directory">{this.props.currentWorkingDirectory}</div>
)
}
});
function getDimensions() {
var letter = document.getElementById('sizes-calculation');
return {
columns: Math.floor(window.innerWidth / letter.clientWidth * 10),
rows: Math.floor(window.innerHeight / letter.clientHeight)
};
}
function scrollToBottom() {
jQuery('html body').animate({ scrollTop: jQuery(document).height() }, 0);
}
function focusLastInput(event) {
if (!_.contains(event.target.classList, 'prompt')) {
var target = _.last(document.getElementsByClassName('prompt'));
target.focus();
withCaret(target, function() { return target.innerText.length; });
}
}
function withCaret(target, callback) {
var selection = window.getSelection();
var range = document.createRange();
var offset = callback(selection.baseOffset);
if (target.childNodes.length) {
range.setStart(target.childNodes[0], offset);
} else {
range.setStart(target, 0);
}
range.collapse(true);
selection.removeAllRanges();
selection.addRange(range);
}
|
JavaScript
| 0.000028 |
@@ -3715,53 +3715,169 @@
-this.props.prompt.send(event.target.innerText
+// Prevent two-line input on cd.%0A var text = event.target.innerText;%0A setTimeout(function ()%7B this.props.prompt.send(text); %7D.bind(this), 0
);%0A
|
4b08ed872d29672d91a4cfa9625d164a8906b328
|
Update drag.js
|
javascripts/drag.js
|
javascripts/drag.js
|
var main = function(){
//To drag the pictures
$(".wallpic").draggable();
$(".wallsaying").draggable();
};
$(document).ready(main);
|
JavaScript
| 0.000001 |
@@ -45,36 +45,8 @@
res%0A
- $(%22.wallpic%22).draggable();%0A
$(%22
|
2f704828902cf1645640c3f155a01eed808e70f8
|
add copyright comment
|
jquery.bgAnimate.js
|
jquery.bgAnimate.js
|
(function($){
jQuery.fn.bgAnimate = function(option){
if(!option) option = {};
option = $.extend({
height : null,
duration : 200,
frame : 5,
loop : 0,
autoplay : false,
onPlay : function(){},
onStop : function(){},
onPause : function(){},
onComplete: function(){}
}, option);
return $(this).each(function(){
var $self = $(this);
var height = option.height || $self.height();
var i = 0;
var loop = option.loop;
var timer = null;
var complete = false;
var stopped = false;
var duration = null;
switch(typeof option.duration){
case 'function':
duration = option.duration;
break;
case 'object':
if(option.duration instanceof Array){
duration = function(i){ return option.duration[i%option.frame]; };
break;
}
case 'number':
default:
duration = function(i){ return option.duration; };
break;
}
var animate = {
play: function(){
if(timer) return;
if(complete){
i = 0;
complete = false;
}
stopped = false;
var nextFrame = function(){
clearTimeout(timer);
if(stopped) return;
if(++i>=option.frame){
i = 0;
if(!loop){
stopped = true;
timer = null;
complete = true;
option.onStop();
option.onComplete();
return;
}else if(loop>0){
loop--;
}
}
$self.css({ backgroundPosition:'0 '+String(-height*i)+'px' });
timer = setTimeout(nextFrame, duration(i));
};
timer = setTimeout(nextFrame, duration(i));
option.onPlay();
},
start: function(){
animate.play();
},
stop: function(){
clearTimeout(timer);
stopped = true;
timer = null;
i = 0;
option.onStop();
},
pause: function(){
clearTimeout(timer);
stopped = true;
timer = null;
option.onPause();
},
reset: function(){
animate.stop();
$self.css({ backgroundPosition:'0 0' });
}
};
if(option.autoplay) animate.start();
$self.data('bgAnimate', animate);
});
};
})(jQuery);
|
JavaScript
| 0 |
@@ -1,16 +1,97 @@
+/**%0A * jquery.bgAnimate.js%0A * %0A * @author tekiton%0A * @license MIT LICENSE :)%0A */%0A
(function($)%7B%0A%0A%09
|
c07aafeea6edf82749fd4c7bde01d7b245223f8d
|
fix click on modal propagation
|
jquery.the-modal.js
|
jquery.the-modal.js
|
/**
* The Modal jQuery plugin
*
* @author Alexander Makarov <[email protected]>
* @link https://github.com/samdark/the-modal
* @version 1.0
*/
;(function($, window, document, undefined) {
"use strict";
/*jshint smarttabs:true*/
var pluginNamespace = 'the-modal',
// global defaults
defaults = {
overlayClass: 'themodal-overlay',
closeOnEsc: true,
closeOnOverlayClick: true,
onClose: null,
onOpen: null
};
function getContainer() {
var container = 'body';
// IE < 8
if(document.all && !document.querySelector) {
container = 'html';
}
return $(container);
}
function init(els, options) {
var modalOptions = options;
if(els.length) {
els.each(function(){
$(this).data(pluginNamespace+'.options', modalOptions);
});
}
else {
$.extend(defaults, modalOptions);
}
return {
open: function(options) {
// close modal if opened
$.modal().close();
var el = els.get(0);
var localOptions = $.extend({}, defaults, $(el).data(pluginNamespace+'.options'), options);
getContainer().addClass('lock');
var modal = $('<div/>').addClass(localOptions.overlayClass).prependTo('body');
if(el) {
var cln = $(el).clone(true).appendTo(modal).show();
}
if(localOptions.closeOnEsc) {
$(document).bind('keyup.'+pluginNamespace, function(e){
if(e.keyCode === 27) {
$.modal().close();
}
});
}
if(localOptions.closeOnOverlayClick) {
cln.on('click.' + pluginNamespace, function(e){
return false;
});
$('.' + localOptions.overlayClass).on('click.' + pluginNamespace, function(e){
$.modal().close();
});
}
$(document).bind("touchmove",function(e){
if(!$(e).parents('.' + localOptions.overlayClass)) {
e.preventDefault();
}
});
if(localOptions.onOpen) {
localOptions.onOpen(cln, localOptions);
}
},
close: function() {
var localOptions = $.extend({}, defaults, $(el).data(), options);
var shim = $('.' + localOptions.overlayClass);
var el = shim.children().get(0);
shim.remove();
getContainer().removeClass('lock');
if(localOptions.closeOnEsc) {
$(document).unbind('keyup.'+pluginNamespace);
}
if(localOptions.onClose) {
localOptions.onClose(el, localOptions);
}
}
};
}
$.modal = function(options){
return init($, options);
};
$.fn.modal = function(options) {
return init(this, options);
};
})(jQuery, window, document);
|
JavaScript
| 0 |
@@ -1531,20 +1531,27 @@
%09%09%09%09
-return false
+e.stopPropagation()
;%0A%09%09
|
5439fab56cc339899be705a4790f942db44a6438
|
make shift squared
|
js/app/FurShader.js
|
js/app/FurShader.js
|
'use strict';
define(['framework/BaseShader'], function(BaseShader) {
class FurShader extends BaseShader {
fillCode() {
this.vertexShaderCode = '#version 300 es\r\n' +
'precision highp float;\r\n' +
'uniform mat4 view_proj_matrix;\r\n' +
'uniform float layerThickness;\r\n' +
'uniform float layersCount;\r\n' +
'uniform vec4 colorStart;\r\n' +
'uniform vec4 colorEnd;\r\n' +
'uniform float time;\r\n' +
'uniform float waveScale;\r\n' +
'\r\n' +
'in vec4 rm_Vertex;\r\n' +
'in vec2 rm_TexCoord0;\r\n' +
'in vec3 rm_Normal;\r\n' +
'\r\n' +
'out vec2 vTexCoord0;\r\n' +
'out vec4 vAO;\r\n' +
'\r\n' +
'const float PI2 = 6.2831852;\r\n' +
'const float RANDOM_COEFF_1 = 0.1376;\r\n' +
'const float RANDOM_COEFF_2 = 0.3726;\r\n' +
'const float RANDOM_COEFF_3 = 0.2546;\r\n' +
'\r\n' +
'void main( void )\r\n' +
'{\r\n' +
' float f = float(gl_InstanceID + 1) * layerThickness;\r\n' +
' float layerCoeff = float(gl_InstanceID) / layersCount;\r\n' +
' vec4 vertex = rm_Vertex + vec4(rm_Normal, 0.0) * vec4(f, f, f, 0.0);\r\n' +
' float timePi2 = time * PI2;\r\n' +
' float waveScaleFinal = waveScale * layerCoeff;\r\n' +
'\r\n' +
' vertex.x += sin(timePi2 + ((rm_Vertex.x+rm_Vertex.y+rm_Vertex.z) * RANDOM_COEFF_1)) * waveScaleFinal;\r\n' +
' vertex.y += cos(timePi2 + ((rm_Vertex.x-rm_Vertex.y+rm_Vertex.z) * RANDOM_COEFF_2)) * waveScaleFinal;\r\n' +
' vertex.z += sin(timePi2 + ((rm_Vertex.x+rm_Vertex.y-rm_Vertex.z) * RANDOM_COEFF_3)) * waveScaleFinal;\r\n' +
' gl_Position = view_proj_matrix * vertex;\r\n' +
' vTexCoord0 = vec2(rm_TexCoord0);\r\n' +
' vAO = mix(colorStart, colorEnd, layerCoeff);\r\n' +
'}';
this.fragmentShaderCode = '#version 300 es\r\n' +
'precision highp float;\r\n' +
'uniform sampler2D diffuseMap;\r\n' +
'uniform sampler2D alphaMap;\r\n' +
'in vec2 vTexCoord0;\r\n' +
'in vec4 vAO;\r\n' +
'out vec4 fragColor;\r\n' +
'\r\n' +
'void main()\r\n' +
'{\r\n' +
' vec4 diffuseColor = texture(diffuseMap, vTexCoord0);\r\n' +
' float alphaColor = texture(alphaMap, vTexCoord0).r;\r\n' +
' fragColor = diffuseColor * vAO;\r\n' +
' fragColor.a *= alphaColor;\r\n' +
'}';
}
fillUniformsAttributes() {
this.view_proj_matrix = this.getUniform('view_proj_matrix');
this.rm_Vertex = this.getAttrib('rm_Vertex');
this.rm_TexCoord0 = this.getAttrib('rm_TexCoord0');
this.rm_Normal = this.getAttrib('rm_Normal');
this.diffuseMap = this.getUniform('diffuseMap');
this.alphaMap = this.getUniform('alphaMap');
this.layerThickness = this.getUniform('layerThickness');
this.layersCount = this.getUniform('layersCount');
this.colorStart = this.getUniform('colorStart');
this.colorEnd = this.getUniform('colorEnd');
this.time = this.getUniform('time');
this.waveScale = this.getUniform('waveScale');
}
}
return FurShader;
});
|
JavaScript
| 0 |
@@ -1499,16 +1499,26 @@
mePi2 =
+0.2 * sin(
time * P
@@ -1519,16 +1519,17 @@
me * PI2
+)
;%5Cr%5Cn' +
@@ -1571,16 +1571,22 @@
eFinal =
+ 1.5 *
waveSca
@@ -1589,16 +1589,29 @@
eScale *
+ layerCoeff *
layerCo
|
9f1a52a7a6f2b95b2931447aa78060ae4e6ac5dc
|
Add more doge sayings
|
doge_xxyy.github.io.js
|
doge_xxyy.github.io.js
|
/*
Doge.js (Get your own at https://github.com/xxyy/doge.js/)
Copyright (C) 2014 Philipp Nowak / xxyy (xxyy.github.io)
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
var doges = ["wow", "such skill", "many pro", "wer r applause?!", "am hello", "9001% enkrip", "many gray",
"doge approve", ">2014", "such programmr", "many code", "so gud praktis", "Internet Explorer master race",
"such Mark Harmon", "many detodate", "such wam", "can i has codez?!?", "such literals", "wow",
"many Spagt", "rm -rf --no-preserve-root /", "such wow'; DROP TABLE `doges`; #--", "dat pro desine",
"#metro4lyfe", "such random", "many projectz", "many irc pls", "s/assert/vouch/", "o ok", "very celery",
"so tablete", "very metro", "~~~pro program~~~", "plz of the #lit on irc.spi.gt", "such physix", "im aktuli batman"];
var colors = ["#0040FF", "#2EFEF7", "#DF0101", "#088A08", "#CC2EFA", "#FFBF00"];
/**
* Builds a doge saying with color, text and position randomised.
*/
function buildDoge() {
//Need class for identification
return "<div class='doge' style='color: "
// Set font color to random entry of colors array
// Math.random returns a number between 0 and 1
+ colors[Math.floor(Math.random() * colors.length)]
+ "; left: "
// Set random distance from left screen edge in %
+ Math.floor(Math.random() * 95) //don't want overflow
+ "%; top: "
// Set random distance from left screen edge in %
+ Math.floor(Math.random() * 95) //don't want overflow
+ "%;'>"
// Set the text to a random doge saying from the doges array
+ doges[Math.floor(Math.random() * doges.length)]
+ "</div>";
}
/**
* Displays a random doge saying, with fade-in and fade-out animations.
* @see buildDoge()
*/
function showDoge() {
//Appends a new doge saying to the doge container (will be the body element in most cases)
$(".wow").append(buildDoge);
// Apply a fadeIn function to all doge sayings on the page with a duration of 2 seconds.
// fade in won't occur without calling hide() before:
$(".doge").hide().fadeIn(1500, function() {
//Once complete, fade all doge sayings out with a duration of 2 seconds.
$(".doge").fadeOut(2000, function() {
//Once that has completed too, remove all doge sayings from the page
$(".doge").remove();
//Recurse this function so a new saying is displayed
showDoge(); // wow such recurse
});
});
}
//Start doge saying display loop on load
$(window).on("load", function() {
showDoge();
});
|
JavaScript
| 0.000001 |
@@ -76,16 +76,23 @@
C) 2014
+- 2015
Philipp
@@ -953,17 +953,17 @@
%22, %22%3E201
-4
+5
%22, %22such
@@ -1472,16 +1472,121 @@
batman%22
+,%0A %22enter lynyx%22, %22so arch%22, %22many git%22, %22such twitr addict%22, %22very messed-up sleep schedule%22, %22amaze%22
%5D;%0Avar c
|
eb253fc50da7f811b7c68f2129a503160ddd126c
|
Exclude local-file tracks from exported configs.
|
js/export-config.js
|
js/export-config.js
|
/* -*- mode: javascript; c-basic-offset: 4; indent-tabs-mode: nil -*- */
//
// Dalliance Genome Explorer
// (c) Thomas Down 2006-2014
//
// export-config.js
//
if (typeof(require) !== 'undefined') {
var browser = require('./cbrowser');
var Browser = browser.Browser;
var utils = require('./utils');
var shallowCopy = utils.shallowCopy;
var sha1 = require('./sha1');
var hex_sha1 = sha1.hex_sha1;
var das = require('./das');
var copyStylesheet = das.copyStylesheet;
}
Browser.prototype.exportFullConfig = function(opts) {
opts = opts || {};
var config = {
chr: this.chr,
viewStart: this.viewStart|0,
viewEnd: this.viewEnd|0,
cookieKey: 'dalliance_' + hex_sha1(Date.now()),
coordSystem: this.coordSystem,
sources: this.exportSourceConfig(),
chains: this.exportChains()
};
if (this.prefix)
config.prefix = this.prefix;
return config;
}
Browser.prototype.exportChains = function() {
var cc = {};
var cs = this.chains || {};
for (var k in cs) {
cc[k] = cs[k].exportConfig();
}
return cc;
}
Browser.prototype.exportSourceConfig = function(opts) {
opts = opts || {};
var sourceConfig = [];
for (var ti = 0; ti < this.tiers.length; ++ti) {
var tier = this.tiers[ti];
var source = shallowCopy(tier.dasSource);
source.coords = undefined;
source.props = undefined;
if (!source.disabled)
source.disabled = undefined;
if (tier.config.stylesheet) {
source.style = tier.config.stylesheet.styles;
source.stylesheet_uri = undefined;
} else if (source.style) {
source.style = copyStylesheet({styles: source.style}).styles;
}
if (typeof(tier.config.name) === 'string') {
source.name = tier.config.name;
}
if (tier.config.height !== undefined) {
source.forceHeight = tier.config.height;
}
if (tier.config.forceMin !== undefined) {
source.forceMin = tier.config.forceMin;
}
if (tier.config.forceMinDynamic)
source.forceMinDynamic = tier.config.forceMinDynamic;
if (tier.config.forceMax !== undefined) {
source.forceMax = tier.config.forceMax;
}
if (tier.config.forceMaxDynamic)
source.forceMaxDynamic = tier.config.forceMaxDynamic;
sourceConfig.push(source);
}
return sourceConfig;
}
Browser.prototype.exportPageTemplate = function(opts) {
opts = opts || {};
var template = '<html>\n' +
' <head>\n' +
' <script language="javascript" src="' + this.resolveURL('$$dalliance-compiled.js') + '"></script>\n' +
' <script language="javascript">\n' +
' var dalliance_browser = new Browser(' + JSON.stringify(this.exportFullConfig(opts), null, 2) + ');\n' +
' </script>\n' +
' </head>\n' +
' <body>\n' +
' <div id="svgHolder">Dalliance goes here</div>\n' +
' </body>\n' +
'<html>\n';
return template;
}
|
JavaScript
| 0 |
@@ -1378,24 +1378,78 @@
dasSource);%0A
+%0A if (source.noPersist)%0A continue;%0A%0A
sour
|
559354ec067c7f8c76a9e7018f1f88c27d06f76b
|
remove console logging
|
js/isomer-nimbus.js
|
js/isomer-nimbus.js
|
/**
* Various changes, or additional features for Isomer
* @todo back port these
*
*/
/**
* Sets the color of a path
*/
Isomer.Path.prototype.setColor = function (color) {
this.color = color;
return this;
};
/**
* Sets the color of a shape, by setting the color of each path
*/
Isomer.Shape.prototype.setColor = function (color) {
var paths = this.paths;
for (i = 0; i < paths.length; i++) {
paths[i].color = color;
}
this.paths = paths
return this;
}
/**
* Returns a new path rotated along the Y axis by a given origin
*
* Simply a forward to Point#rotateY
*/
Isomer.Path.prototype.rotateY = function () {
var args = arguments;
return new Path(this.points.map(function (point) {
return point.rotateY.apply(point, args);
}));
};
/**
* Rotate about origin on the Y axis
*/
Isomer.Point.prototype.rotateY = function (origin, angle) {
var p = this.translate(-origin.x, -origin.y, -origin.z);
var x = p.x * Math.cos(angle) - p.z * Math.sin(angle);
var z = p.x * Math.sin(angle) + p.z * Math.cos(angle);
p.x = x;
p.z = z;
return p.translate(origin.x, origin.y, origin.z);
};
/**
* Returns a new path rotated along the X axis by a given origin
*
* Simply a forward to Point#rotateX
*/
Isomer.Path.prototype.rotateX = function () {
var args = arguments;
return new Path(this.points.map(function (point) {
return point.rotateX.apply(point, args);
}));
};
/**
* Rotate about origin on the X axis
*/
Isomer.Point.prototype.rotateX = function (origin, angle) {
var p = this.translate(-origin.x, -origin.y, -origin.z);
var z = p.z * Math.cos(angle) - p.y * Math.sin(angle);
var y = p.z * Math.sin(angle) + p.y * Math.cos(angle);
p.z = z;
p.y = y;
return p.translate(origin.x, origin.y, origin.z);
};
/**
* Build out a collection object which can contain lots of objects
*/
function Object3D(shapes) {
if (Object.prototype.toString.call(shapes) === '[object Array]') {
this.items = shapes;
} else {
this.items = Array.prototype.slice.call(arguments);
}
}
Object3D.prototype.push = function (item, color) {
if (Object.prototype.toString.call(item) == '[object Array]') {
for (var i = 0; i < item.length; i++) {
this.push(item[i], color);
}
} else {
if (color instanceof Isomer.Color) {
item.setColor(color);
}
this.items.push(item);
}
}
/**
* Translates a given object
*
* Simply a forward to Shape#translate
*/
Object3D.prototype.translate = function () {
var args = arguments;
console.log(args)
return new Object3D(this.items.map(function (shape) {
return shape.translate.apply(shape, args);
}));
}
Isomer.Object3D = Object3D;
/**
* Helpers
*/
function originMarker() {
var o = new Isomer.Object3D()
var x = new Path([
new Point(0, 0, 0),
new Point(1, 0, 0), // x
new Point(1, 0.01, 0), // x
new Point(0, 0.01, 0),
])
x.setColor(new Color(255, 0, 0))
var y = new Path([
new Point(0, 0, 0),
new Point(0, 1, 0), // y
new Point(0.01, 1, 0), // y
new Point(0.01, 0, 0),
])
y.setColor(new Color(0, 255, 0))
var z = new Path([
new Point(0, 0, 0),
new Point(0, 0, 1), // z
new Point(0.01, 0, 1), // z
new Point(0.01, 0, 0),
])
z.setColor(new Color(0, 0, 255))
o.push([x, y, z])
return o
}
|
JavaScript
| 0.000001 |
@@ -2521,28 +2521,8 @@
ts;%0A
- console.log(args)%0A
re
|
d7ae20f7d37fee9c5123432ee79765329308fa1e
|
Revert "Attach LogTracer Capitalize" (#81)
|
js/module/tracer.js
|
js/module/tracer.js
|
function Tracer(name) {
this.module = this.constructor;
this.capsule = this.tm.allocate(this);
$.extend(this, this.capsule);
this.setName(name);
return this.new;
}
Tracer.prototype = {
constructor: Tracer,
tm: null,
_setData: function () {
var args = Array.prototype.slice.call(arguments);
this.tm.pushStep(this.capsule, {type: 'setData', args: TracerUtil.toJSON(args)});
return this;
},
_clear: function () {
this.tm.pushStep(this.capsule, {type: 'clear'});
return this;
},
_wait: function () {
this.tm.newStep();
return this;
},
processStep: function (step, options) {
switch (step.type) {
case 'setData':
this.setData.apply(this, TracerUtil.fromJSON(step.args));
break;
case 'clear':
this.clear();
break;
}
},
setName: function (name) {
var $name;
if (this.new) {
$name = $('<span class="name">');
this.$container.append($name);
} else {
$name = this.$container.find('span.name');
}
$name.text(name || this.defaultName);
},
setData: function () {
var data = TracerUtil.toJSON(arguments);
if (!this.new && this.lastData == data) return true;
this.new = this.capsule.new = false;
this.lastData = this.capsule.lastData = data;
return false;
},
resize: function () {
},
refresh: function () {
},
clear: function () {
},
attach: function (tracer) {
if (tracer.module == LogTracer) {
this.LogTracer = tracer;
}
return this;
},
mousedown: function (e) {
},
mousemove: function (e) {
},
mouseup: function (e) {
},
mousewheel: function (e) {
}
};
|
JavaScript
| 0 |
@@ -1680,17 +1680,17 @@
this.
-L
+l
ogTracer
|
9216ae074785228b66f973337a7e14a085f44ed9
|
Use standard inherit as part of phetioInherit, see https://github.com/phetsims/phet-io/issues/410
|
js/phetioInherit.js
|
js/phetioInherit.js
|
// Copyright 2016, University of Colorado Boulder
/**
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Andrew Adare
*/
define( function( require ) {
'use strict';
// modules
var extend = require( 'PHET_CORE/extend' );
var phetioNamespace = require( 'PHET_IO/phetioNamespace' );
/**
* @param {function} supertype Constructor for the supertype.
* @param {string} typeName - the name for the type, used for logic (such as TVoid not needing a return, etc)
* @param {function} subtype Constructor for the subtype. Generally should contain supertype.call( this, ... )
* @param {Object} [methods] object containing properties that will be set on the prototype.
* @param {Object} [staticProperties] object containing properties that will be set on the constructor function itself
*/
var phetioInherit = function( supertype, typeName, subtype, methods, staticProperties ) {
assert && assert( typeof typeName === 'string', 'typename must be 2nd arg' );
assert && assert( typeof supertype === 'function' );
// Copy implementations to the prototype for ease of use, see #185
var prototypeMethods = {};
for ( var method in methods ) {
if ( methods.hasOwnProperty( method ) ) {
prototypeMethods[ method ] = methods[ method ].implementation;
}
}
function F() {}
F.prototype = supertype.prototype; // so new F().__proto__ === supertype.prototype
subtype.prototype = extend( // extend will combine the properties and constructor into the new F copy
new F(), // so new F().__proto__ === supertype.prototype, and the prototype chain is set up nicely
{ constructor: subtype }, // overrides the constructor properly
prototypeMethods // [optional] additional properties for the prototype, as an object.
);
//Copy the static properties onto the subtype constructor so they can be accessed 'statically'
extend( subtype, staticProperties );
subtype.typeName = typeName;
subtype.methods = methods;
subtype.supertype = supertype;
/**
* Look through the inheritance hierarchy to find the deepest (subtypiest) method declaration
*/
subtype.getMethodDeclaration = function( methodName ) {
if ( this.methods[ methodName ] ) {
return this.methods[ methodName ];
}
else if ( typeName === 'TObject' ) {
return null;
}
else {
return supertype.getMethodDeclaration( methodName );
}
};
subtype.allMethods = _.extend( {}, supertype.allMethods, methods );
// TODO: It would be so nice to abandon this parallel type definition and use actual instanceof etc.
// TODO: Can this be implemented without a name check? The name check seems susceptible to false positives.
subtype.hasType = function( type ) {
return !!( subtype.typeName === type.typeName || ( supertype && supertype.hasType && supertype.hasType( type ) ) );
};
return subtype; // pass back the subtype so it can be returned immediately as a module export
};
phetioNamespace.register( 'phetioInherit', phetioInherit );
return phetioInherit;
} );
|
JavaScript
| 0 |
@@ -196,22 +196,23 @@
s%0A var
-extend
+inherit
= requi
@@ -226,22 +226,23 @@
ET_CORE/
-extend
+inherit
' );%0A v
@@ -1330,612 +1330,53 @@
-function F() %7B%7D%0A%0A F.prototype = supertype.prototype; // so new F().__proto__ === supertype.prototype%0A%0A subtype.prototype = extend( // extend will combine the properties and constructor into the new F copy%0A new F(), // so new F().__proto__ === supertype.prototype, and the prototype chain is set up nicely%0A %7B constructor: subtype %7D, // overrides the constructor properly%0A prototypeMethods // %5Boptional%5D additional properties for the prototype, as an object.%0A );%0A%0A //Copy the static properties onto the subtype constructor so they can be accessed 'statically'%0A extend( subtype
+inherit( supertype, subtype, prototypeMethods
, st
|
59bfb993500fe26a85c6a0265039b1651252a091
|
FIX #110
|
src/compatibility/function.js
|
src/compatibility/function.js
|
/**
* @file Function methods polyfill
* @since 0.1.5
*/
/*#ifndef(UMD)*/
"use strict";
/*global _gpfInstallCompatibility*/ // Define and install compatible methods
/*exported _gpfJsCommentsRegExp*/ // Find all JavaScript comments
/*#endif*/
var _gpfArrayPrototypeSlice = Array.prototype.slice;
_gpfInstallCompatibility("Function", {
on: Function,
methods: {
// Introduced with JavaScript 1.8.5
bind: function (thisArg) {
var me = this,
prependArgs = _gpfArrayPrototypeSlice.call(arguments, 1);
return function () {
var args = _gpfArrayPrototypeSlice.call(arguments, 0);
me.apply(thisArg, prependArgs.concat(args));
};
}
}
});
//region Function name
// Get the name of a function if bound to the call
var _gpfJsCommentsRegExp = new RegExp("//.*$|/\\*(?:[^\\*]*|\\*[^/]*)\\*/", "gm");
function _gpfGetFunctionName () {
// Use simple parsing
/*jshint validthis:true*/
var functionSource = Function.prototype.toString.call(this), //eslint-disable-line no-invalid-this
functionKeywordPos = functionSource.indexOf("function"),
parameterListStartPos = functionSource.indexOf("(", functionKeywordPos);
return functionSource
.substr(functionKeywordPos + 9, parameterListStartPos - functionKeywordPos - 9)
.replace(_gpfJsCommentsRegExp, "") // remove comments
.trim();
}
// Handling function name properly
/* istanbul ignore if */ // NodeJS exposes Function.prototype.name
if ((function () {
/* istanbul ignore next */ // Will never be evaluated
function functionName () {}
return functionName.name !== "functionName";
})()) {
Function.prototype.compatibleName = _gpfGetFunctionName;
} else {
/**
* Return function name
*
* @return {String} Function name
* @since 0.1.5
*/
Function.prototype.compatibleName = function () {
return this.name;
};
}
//endregion
/*#ifndef(UMD)*/
gpf.internals._gpfGetFunctionName = _gpfGetFunctionName;
/*#endif*/
|
JavaScript
| 0 |
@@ -166,136 +166,618 @@
s%0A/*
-exported _gpfJsCommentsRegExp*/ // Find all JavaScript comments%0A/*#endif*/%0A%0Avar _gpfArrayPrototypeSlice = Array.prototype.slice;
+global _gpfFunc*/ // Create a new function using the source%0A/*global _gpfBuildFunctionParameterList*/ // Builds an array of parameters%0A/*exported _gpfJsCommentsRegExp*/ // Find all JavaScript comments%0A/*#endif*/%0A%0Avar _gpfArrayPrototypeSlice = Array.prototype.slice;%0A%0Afunction _generateBindBuilderSource (length) %7B%0A return %5B%0A %22var me = this;%22,%0A %22return function (%22 + _gpfBuildFunctionParameterList(length).join(%22, %22) + %22) %7B%22,%0A %22 var args = _gpfArrayPrototypeSlice.call(arguments, 0);%22,%0A %22 return me.apply(thisArg, prependArgs.concat(args));%22,%0A %22%7D;%22%0A %5D.join(%22%5Cn%22);%0A%7D
%0A%0A_g
@@ -1026,17 +1026,17 @@
ents, 1)
-;
+,
%0A
@@ -1044,56 +1044,159 @@
-return function () %7B%0A var args =
+ builderSource = _generateBindBuilderSource(Math.max(this.length - prependArgs.length, 0));%0A return _gpfFunc(%5B%22thisArg%22, %22prependArgs%22, %22
_gpf
@@ -1214,36 +1214,34 @@
ypeSlice
-.call(arguments, 0);
+%22%5D, builderSource)
%0A
@@ -1249,25 +1249,26 @@
-me.apply(
+.call(me,
thisArg,
@@ -1283,37 +1283,34 @@
Args
-.concat(args));%0A %7D
+, _gpfArrayPrototypeSlice)
;%0A
|
601d9cbedd8ba38a9480049a7b498d0e1c87e055
|
allow disabling form validation
|
src/component/aurelia-form.js
|
src/component/aurelia-form.js
|
import {bindable, customElement, children, inject} from 'aurelia-framework';
import {Configuration} from 'aurelia-config';
import {resolvedView} from 'aurelia-view-manager';
import {DOM} from 'aurelia-pal';
import {logger} from '../aurelia-form';
@resolvedView('spoonx/form', 'aurelia-form')
@customElement('aurelia-form')
@inject(Configuration.of('aurelia-form'), DOM.Element)
export class AureliaForm {
@bindable behavior = '';
@bindable classes = '';
@bindable options = {};
@bindable validationController;
@bindable entity;
@bindable buttonOptions;
@bindable buttonLabel;
@bindable buttonEnabled;
@children('form-group') formGroups = [];
mapped = {};
element;
validateTrigger;
constructor(config, element) {
this.config = config;
this.element = element;
this.buttonEnabled = config.submitButton.enabled;
this.buttonOptions = config.submitButton.options;
this.buttonLabel = config.submitButton.label;
let validation = config.validation;
if (validation) {
this.validationController = validation.controller.getController(this.mapped, validation.trigger);
this.validateTrigger = validation.controller.getTriggers();
}
}
submit() {
if (!this.validationController) {
return;
}
if (!this.entity) {
return logger.warn('Validation on forms requires a entity to validate.');
}
this.validate().then(result => {
if (result.valid) {
return this.emit('valid');
}
this.emit('invalid', result);
});
}
changed(trigger, event) {
let controller = this.validationController;
if (!controller) {
return true;
}
let setTrigger = controller.validateTrigger;
let triggers = this.validateTrigger;
if (setTrigger === triggers.manual) {
return true;
}
// Specific configured, something else triggered. Return.
if (setTrigger < triggers.changeOrBlur && triggers[trigger] !== setTrigger) {
return true;
}
this.validate(event.target.name);
return true;
}
validate(property) {
return this.validationController.validate({object: this.entity, propertyName: property});
}
emit(event, data = {}) {
this.element.dispatchEvent(DOM.createCustomEvent(event, {detail: data, bubbles: true}));
}
formGroupsChanged() {
this.updateFormGroups();
}
behaviorChanged() {
this.updateFormGroups();
}
updateFormGroups() {
if (this.formGroups.length === 0) {
return;
}
this.formGroups.forEach(group => {
group.behavior = this.behavior;
if (group.name) {
this.mapped[group.name] = group;
}
});
}
}
|
JavaScript
| 0 |
@@ -516,16 +516,47 @@
oller;%0A%0A
+ @bindable validated = true;%0A%0A
@binda
@@ -1291,32 +1291,51 @@
dationController
+ %7C%7C !this.validated
) %7B%0A return
@@ -1706,16 +1706,35 @@
ntroller
+ %7C%7C !this.validated
) %7B%0A
|
9b8e277c33cf1699c038f8a6cf975897d021dd07
|
Compute player scores by win ratio
|
src/components/RankingView.js
|
src/components/RankingView.js
|
import React, { PropTypes } from 'react'
import { connect } from 'react-redux'
import {
ListView,
View,
Text
} from 'react-native'
const RankingView = React.createClass({
getInitialState() {
return {
ranking: new ListView.DataSource({ rowHasChanged: (row1, row2) => row1 !== row2 })
.cloneWithRows(this.props.ranking)
}
},
componentWillReceiveProps(props) {
if (props.ranking !== this.props.ranking) {
this.state = {
ranking: this.state.ranking.cloneWithRows(props.ranking)
}
}
},
renderRow(item) {
return (
<View style={{flex: 1, flexDirection: 'row'}}>
<Text>{item.name}</Text>
<Text>{item.score}</Text>
</View>
)
},
render() {
return (
<ListView dataSource={this.state.ranking}
renderRow={this.renderRow}/>
)
}
})
function mapStateToProps(state) {
function addToScoreMap(player, scoreMap) {
if (!scoreMap[player.name]) {
scoreMap[player.name] = 0
}
scoreMap[player.name] += player.score
}
let scoreMap = {}
for (playedGame of state.playedGames) {
addToScoreMap(playedGame.team1.attacker, scoreMap)
addToScoreMap(playedGame.team1.defender, scoreMap)
addToScoreMap(playedGame.team2.attacker, scoreMap)
addToScoreMap(playedGame.team2.defender, scoreMap)
}
let scoreList = []
for (let name in scoreMap) {
if (scoreMap.hasOwnProperty(name)) {
scoreList.push({
name: name,
score: scoreMap[name]
})
}
}
return {
ranking: scoreList
}
}
export default connect(mapStateToProps)(RankingView)
|
JavaScript
| 0.999994 |
@@ -916,16 +916,21 @@
(player,
+ won,
scoreMa
@@ -1002,123 +1002,369 @@
%5D =
-0%0A %7D%0A scoreMap%5Bplayer.name%5D += player.score%0A %7D%0A let scoreMap = %7B%7D%0A for (playedGame of state.playedGames) %7B
+%7B%0A played: 0,%0A won: 0%0A %7D%0A %7D%0A scoreMap%5Bplayer.name%5D.played += 1%0A scoreMap%5Bplayer.name%5D.won += won%0A %7D%0A let scoreMap = %7B%7D%0A for (playedGame of state.playedGames) %7B%0A let team1Win = playedGame.team1.attacker.score + playedGame.team1.defender.score %3E%0A playedGame.team2.attacker.score + playedGame.team2.defender.score
%0A
@@ -1396,32 +1396,42 @@
.team1.attacker,
+ team1Win,
scoreMap)%0A a
@@ -1461,32 +1461,42 @@
.team1.defender,
+ team1Win,
scoreMap)%0A a
@@ -1534,16 +1534,27 @@
ttacker,
+ !team1Win,
scoreMa
@@ -1600,16 +1600,27 @@
efender,
+ !team1Win,
scoreMa
@@ -1791,16 +1791,44 @@
ap%5Bname%5D
+.won / scoreMap%5Bname%5D.played
%0A %7D
|
3d2f96280a3a61e86d0649e14b65b86ef97a4bc7
|
Tweak to pc.BasicMaterial docs.
|
src/scene/scene_basicmaterial.js
|
src/scene/scene_basicmaterial.js
|
pc.extend(pc, function () {
/**
* @name pc.BasicMaterial
* @class A Basic material is is for rendering unlit geometry, either using a constant color or a
* color map modulated with a color.
* @property {pc.Color} color The flat color of the material (RGBA, where each component is 0 to 1).
* @property {pc.Texture} colorMap The color map of the material. If specified, the color map is
* modulated by the color property.
* @author Will Eastcott
*/
var BasicMaterial = function () {
this.color = new pc.Color(1, 1, 1, 1);
this.colorMap = null;
this.vertexColors = false;
this.update();
};
BasicMaterial = pc.inherits(BasicMaterial, pc.Material);
pc.extend(BasicMaterial.prototype, {
/**
* @function
* @name pc.BasicMaterial#clone
* @description Duplicates a Basic material. All properties are duplicated except textures
* where only the references are copied.
* @returns {pc.BasicMaterial} A cloned Basic material.
*/
clone: function () {
var clone = new pc.BasicMaterial();
pc.Material.prototype._cloneInternal.call(this, clone);
clone.color.copy(this.color);
clone.colorMap = this.colorMap;
clone.vertexColors = this.vertexColors;
clone.update();
return clone;
},
update: function () {
this.clearParameters();
this.setParameter('uColor', this.color.data);
if (this.colorMap) {
this.setParameter('texture_diffuseMap', this.colorMap);
}
},
updateShader: function (device) {
var options = {
skin: !!this.meshInstances[0].skinInstance,
vertexColors: this.vertexColors,
diffuseMap: this.colorMap
};
var library = device.getProgramLibrary();
this.shader = library.getProgram('basic', options);
}
});
return {
BasicMaterial: BasicMaterial
};
}());
|
JavaScript
| 0 |
@@ -458,16 +458,417 @@
perty.%0D%0A
+ * @example%0D%0A * // Create a new Basic material%0D%0A * var material = new pc.BasicMaterial();%0D%0A *%0D%0A * // Set the material to have a texture map that is multiplied by a red color%0D%0A * material.color.set(1, 0, 0);%0D%0A * material.colorMap = diffuseMap;%0D%0A *%0D%0A * // Notify the material that it has been modified%0D%0A * material.update();%0D%0A *%0D%0A * @extends pc.Material%0D%0A
* @
|
0686fd5426f3573eac76abef2af4a21a78b2ca5f
|
increase setup.py timeout to 5000
|
lib/manager/pip_setup/extract.js
|
lib/manager/pip_setup/extract.js
|
const { exec } = require('child-process-promise');
const fs = require('fs-extra');
const { join } = require('upath');
const { isSkipComment } = require('../../util/ignore');
const { dependencyPattern } = require('../pip_requirements/extract');
module.exports = {
extractPackageFile,
extractSetupFile,
};
async function extractSetupFile(content, packageFile, config) {
const cwd = config.localDir;
// extract.py needs setup.py to be written to disk
if (!config.gitFs) {
const localFileName = join(config.localDir, packageFile);
await fs.outputFile(localFileName, content);
}
let cmd;
const args = [join(__dirname, 'extract.py'), packageFile];
// istanbul ignore if
if (config.binarySource === 'docker') {
logger.info('Running python via docker');
cmd = 'docker';
args.unshift(
'run',
'-i',
'--rm',
// volume
'-v',
`${cwd}:${cwd}`,
'-v',
`${__dirname}:${__dirname}`,
// cwd
'-w',
cwd,
// image
'renovate/pip',
'python'
);
} else {
logger.info('Running python via global command');
cmd = 'python';
}
logger.debug({ cmd, args }, 'python command');
const { stdout, stderr } = await exec(`${cmd} ${args.join(' ')}`, {
cwd,
shell: true,
timeout: 3000,
});
// istanbul ignore if
if (stderr) {
logger.warn({ stderr }, 'Error in read setup file');
}
return JSON.parse(stdout);
}
async function extractPackageFile(content, packageFile, config) {
logger.debug('pip_setup.extractPackageFile()');
let setup;
try {
setup = await extractSetupFile(content, packageFile, config);
} catch (err) {
logger.warn({ err }, 'Failed to read setup file');
return null;
}
const requires = [];
if (setup.install_requires) {
requires.push(...setup.install_requires);
}
if (setup.extras_require) {
for (const req of Object.values(setup.extras_require)) {
requires.push(...req);
}
}
const regex = new RegExp(`^${dependencyPattern}`);
const lines = content.split('\n');
const deps = requires
.map(req => {
const lineNumber = lines.findIndex(l => l.includes(req));
if (lineNumber === -1) {
return null;
}
const rawline = lines[lineNumber];
let dep = {};
const [, comment] = rawline.split('#').map(part => part.trim());
if (isSkipComment(comment)) {
dep.skipReason = 'ignored';
}
regex.lastIndex = 0;
const matches = regex.exec(req);
if (!matches) {
return null;
}
const [, depName, , currentValue] = matches;
dep = {
...dep,
depName,
currentValue,
lineNumber,
purl: 'pkg:pypi/' + depName,
versionScheme: 'pep440',
};
return dep;
})
.filter(Boolean);
if (!deps.length) {
return null;
}
return { deps };
}
|
JavaScript
| 0.000097 |
@@ -1295,9 +1295,9 @@
ut:
-3
+5
000,
@@ -1360,16 +1360,24 @@
r.warn(%7B
+ stdout,
stderr
|
323080d3cd743dda2e935530d023693c6fe23253
|
fix example 2 typo
|
examples/02-yql/app.js
|
examples/02-yql/app.js
|
require('iso-call/polyfill');
var yql = require('./yql');
var inner = function (D) {
var json = JSON.stringify(D, undefined, ' ');
return `
<input type="text" name="q" value="" />
<input type="submit" value="TEST" />
<hr/>
<h3>Result:</h3>
<textarea>${json}</textarea>
`;
};
var template = function (D) {
var R = inner(D);
return `
<form onsubmit="YQLConsole.renderInto(this);return false">
${R}
</form>
`;
};
module.exports = {
get: function (Q) {
return yql(Q).then(template, template);
},
getInner: function (Q) {
return yql(Q).then(inner, inner);
},
renderInto: function (form) {
this.get(form.elements.query.value).then(function (H) {
form.innerHTML = H;
});
}
};
|
JavaScript
| 0.000748 |
@@ -669,12 +669,8 @@
ts.q
-uery
.val
|
d904522bbdc1ed5ada1dfdf0894c8e99703eede8
|
remove throw again we will require this as part of the v2baseStandard and expect it to be there.
|
lib/methods/v2/translatestate.js
|
lib/methods/v2/translatestate.js
|
const Promise = require('bluebird');
const State = require('../../state');
const Chain = require('../../chain');
const Migrate = require('./migrate');
const methods = {
createTable: async (driver, [t], internals) => {
const mod = internals.modSchema;
const schema = mod.c[t];
await driver.createTable(t, schema);
Object.keys(schema).forEach(key => {
if (schema[key].foreignKey) {
delete mod.f[t][schema[key].foreignKey.name];
}
});
if (mod.i[t]) {
await Promise.resolve(Object.keys(mod.i[t])).each(i => {
const index = mod.i[t][i];
return driver.addIndex(t, i, index.c, index.u);
});
}
if (mod.f[t]) {
await Promise.resolve(Object.keys(mod.f[t])).each(f => {
const foreign = mod.f[t][f];
return driver.addForeignKey(
t,
foreign.rt,
foreign.k,
foreign.m,
foreign.r
);
});
}
},
addColumn: async (driver, [t, c], internals) => {
return driver.addColumn(t, c, internals.modSchema.c[t][c]);
},
changeColumn: async (driver, [t, c], internals) => {
return driver.changeColumn(t, c, internals.modSchema.c[t][c]);
}
};
async function processEntry (
context,
file,
driver,
internals,
{ t: type, a: action, c: args }
) {
let skip = false;
const isListed = driver.udriver._meta.signalColumns.indexOf(action) !== -1;
if (!isListed) {
throw new Error(
'This driver does not support signaling for known critical' +
` functions. ${action} can't be savely reversed without causing damage` +
` if proper signaling is not in place.`
);
}
if (
internals.rollback === true &&
internals.rollbackContinue !== true &&
isListed
) {
internals.rollbackContinue = true;
skip = driver.udriver._counter.previousSignal() === null;
}
if (!skip) {
const f = Object.assign(methods, context.reverse);
switch (type) {
case 0:
await driver[action].apply(driver, args);
break;
case 1:
await f[action](driver, args, internals);
break;
default:
throw new Error(`Invalid state record, of type ${type}`);
}
}
internals.modSchema.s.shift();
await State.update(context, file, internals.modSchema, internals);
}
module.exports = async (context, file, driver, internals) => {
const mod = internals.modSchema;
const chain = new Chain(context, file, driver, internals);
// chain.addChain(Learn);
chain.addChain(Migrate);
await Promise.resolve(mod.s.reverse()).each(args =>
processEntry(context, file, chain, internals, args)
);
await State.deleteState(context, file, internals);
};
|
JavaScript
| 0 |
@@ -1333,336 +1333,8 @@
lse;
-%0A const isListed = driver.udriver._meta.signalColumns.indexOf(action) !== -1;%0A%0A if (!isListed) %7B%0A throw new Error(%0A 'This driver does not support signaling for known critical' +%0A %60 functions. $%7Baction%7D can't be savely reversed without causing damage%60 +%0A %60 if proper signaling is not in place.%60%0A );%0A %7D
%0A%0A
@@ -1424,16 +1424,65 @@
-isListed
+driver.udriver._meta.signalColumns.indexOf(action) !== -1
%0A )
|
de896d6ca3bb88e91981d42aa78c0b8fff826e0d
|
rename all-zero-conf to none and add ETH support
|
lib/new-admin/config/accounts.js
|
lib/new-admin/config/accounts.js
|
const _ = require('lodash/fp')
const { COINS, ALL_CRYPTOS } = require('./coins')
const { BTC, BCH, DASH, ETH, LTC, ZEC } = COINS
const TICKER = 'ticker'
const WALLET = 'wallet'
const LAYER_2 = 'layer2'
const EXCHANGE = 'exchange'
const SMS = 'sms'
const ID_VERIFIER = 'idVerifier'
const EMAIL = 'email'
const ZERO_CONF = 'zeroConf'
const ALL_ACCOUNTS = [
{ code: 'bitpay', display: 'Bitpay', class: TICKER, cryptos: [BTC, BCH] },
{ code: 'kraken', display: 'Kraken', class: TICKER, cryptos: [BTC, ETH, LTC, DASH, ZEC, BCH] },
{ code: 'bitstamp', display: 'Bitstamp', class: TICKER, cryptos: [BTC, ETH, LTC, BCH] },
{ code: 'coinbase', display: 'Coinbase', class: TICKER, cryptos: [BTC, ETH, LTC, DASH, ZEC, BCH] },
{ code: 'itbit', display: 'itBit', class: TICKER, cryptos: [BTC, ETH] },
{ code: 'mock-ticker', display: 'Mock (Caution!)', class: TICKER, cryptos: ALL_CRYPTOS, dev: true },
{ code: 'bitcoind', display: 'bitcoind', class: WALLET, cryptos: [BTC] },
{ code: 'no-layer2', display: 'No Layer 2', class: LAYER_2, cryptos: ALL_CRYPTOS },
{ code: 'infura', display: 'Infura', class: WALLET, cryptos: [ETH] },
{ code: 'geth', display: 'geth (DEPRECATED)', class: WALLET, cryptos: [ETH], deprecated: true },
{ code: 'zcashd', display: 'zcashd', class: WALLET, cryptos: [ZEC] },
{ code: 'litecoind', display: 'litecoind', class: WALLET, cryptos: [LTC] },
{ code: 'dashd', display: 'dashd', class: WALLET, cryptos: [DASH] },
{ code: 'bitcoincashd', display: 'bitcoincashd', class: WALLET, cryptos: [BCH] },
{ code: 'bitgo', display: 'BitGo', class: WALLET, cryptos: [BTC, ZEC, LTC, BCH, DASH] },
{ code: 'bitstamp', display: 'Bitstamp', class: EXCHANGE, cryptos: [BTC, ETH, LTC, BCH] },
{ code: 'itbit', display: 'itBit', class: EXCHANGE, cryptos: [BTC, ETH] },
{ code: 'kraken', display: 'Kraken', class: EXCHANGE, cryptos: [BTC, ETH, LTC, DASH, ZEC, BCH] },
{ code: 'mock-wallet', display: 'Mock (Caution!)', class: WALLET, cryptos: ALL_CRYPTOS, dev: true },
{ code: 'no-exchange', display: 'No exchange', class: EXCHANGE, cryptos: ALL_CRYPTOS },
{ code: 'mock-exchange', display: 'Mock exchange', class: EXCHANGE, cryptos: ALL_CRYPTOS, dev: true },
{ code: 'mock-sms', display: 'Mock SMS', class: SMS, dev: true },
{ code: 'mock-id-verify', display: 'Mock ID verifier', class: ID_VERIFIER, dev: true },
{ code: 'twilio', display: 'Twilio', class: SMS },
{ code: 'mailgun', display: 'Mailgun', class: EMAIL },
{ code: 'all-zero-conf', display: 'Always 0-conf', class: ZERO_CONF, cryptos: [BTC, ZEC, LTC, DASH, BCH] },
{ code: 'no-zero-conf', display: 'Always 1-conf', class: ZERO_CONF, cryptos: [ETH] },
{ code: 'blockcypher', display: 'Blockcypher', class: ZERO_CONF, cryptos: [BTC] },
{ code: 'mock-zero-conf', display: 'Mock 0-conf', class: ZERO_CONF, cryptos: [BTC, ZEC, LTC, DASH, BCH, ETH], dev: true }
]
const devMode = require('minimist')(process.argv.slice(2)).dev
const ACCOUNT_LIST = devMode ? ALL_ACCOUNTS : _.filter(it => !it.dev)(ALL_ACCOUNTS)
module.exports = { ACCOUNT_LIST }
|
JavaScript
| 0.000004 |
@@ -2477,21 +2477,12 @@
e: '
-all-zero-conf
+none
', d
@@ -2494,21 +2494,12 @@
y: '
-Always 0-conf
+None
', c
@@ -2553,93 +2553,10 @@
BCH
-%5D %7D,%0A %7B code: 'no-zero-conf', display: 'Always 1-conf', class: ZERO_CONF, cryptos: %5B
+,
ETH%5D
|
dd242a565c232e0abafc3129364aee6603fab7f1
|
Update cli usage help.
|
lib/node_modules/sake/options.js
|
lib/node_modules/sake/options.js
|
var nomnom = require("nomnom"),
FS = require("fs"),
Path = require("path"),
sutil = require("sake/util"),
pkgFile = Path.join(__dirname, "..", "..", "..", "package.json"),
pkgJson = FS.readFileSync(pkgFile, "utf8"),
pkgInfo = JSON.parse(pkgJson),
wordwrap = require("wordwrap"),
nomArgs = [],
opts,
parsedOpts
;
//---------------------------------------------------------------------------
// Define our options
//---------------------------------------------------------------------------
opts = {
task: {
string: "[TASK]",
help: "Name of the task to run. Defaults to 'default'.",
position: 0,
default: "default"
},
taskArgs: {
string: "[ARGUMENTS ...]",
help: "Zero or more arguments to pass to the task invoked.",
position: 1
},
envArgs: {
string: "[ENV=VALUE ...]",
help: "Zero or more arguments to translate into environment variables.",
position: 2
},
sakefile: {
string: "-f, --sakefile PATH",
help: "PATH to Sakefile to run instead of searching for one."
},
dryrun: {
string: "-n, --dry-run",
help: "Do a dry run without executing actions.",
flag: true,
default: false
},
listTasks: {
string: "-T, --tasks",
help: "List tasks with descriptions and exit.",
flag: true,
default: false
},
listPrereqs: {
string: "-P, --prereqs",
help: "List tasks and their prerequisites and exit.",
flag: true,
default: false
},
requires: {
string: "-r, --require MODULE",
help: "Require MODULE before executing Sakefile and expose the " +
"MODULE under a sanitized namespace (i.e.: coffee-script => " +
"[sake.]coffeeScript).",
list: true,
default: []
},
sync: {
string: "-S, --sync",
help: "Make all standard tasks 'synchronous' by default.",
flag: true,
default: false
},
debug: {
string: "-d, --debug",
help: "Enable additional debugging output.",
flag: true,
default: false
},
quiet: {
string: "-q, --quiet",
help: "Suppress informational messages.",
flag: true,
default: false
},
version: {
string: "-V, --version",
help: "Print the version of sake and exit.",
flag: true,
callback: function () {
return "sake version " + pkgInfo.version;
}
},
help: {
string: "-h, --help",
help: "Print this help information and exit.",
flag: true,
default: false
}
};
//---------------------------------------------------------------------------
// Formatting Helpers
//---------------------------------------------------------------------------
function formatHelp (opts) {
var helpW = 60,
wrap = wordwrap(helpW),
optCols,
pad
;
optCols = Object.keys(opts).reduce(function (t, key) {
var optW = opts[key].string.length;
return optW > t ? optW : t;
}, 0);
pad = optCols + 7;
Object.keys(opts).forEach(function (key) {
var opt = opts[key];
if (!opt.hasOwnProperty("position")) {
opt.help = wrap(opt.help);
opt.help = opt.help.replace(/\n/g, "\n" + Array(pad).join(" "));
}
});
return opts;
}
//---------------------------------------------------------------------------
// Process Environment Arguments
//---------------------------------------------------------------------------
process.argv.slice(2).forEach(function (arg) {
var i, key, val;
if (~(i = arg.indexOf("="))) {
key = arg.slice(0, i);
val = sutil.jsonToValue(arg.slice(i+1));
process.env[key] = val;
}
else {
nomArgs.push(arg);
}
});
//---------------------------------------------------------------------------
// Parse the options
//---------------------------------------------------------------------------
parsedOpts = nomnom.
script(pkgInfo.name).
help(wordwrap(100)(
(pkgInfo.name[0].toUpperCase() + pkgInfo.name.slice(1)) + " will look " +
"within the current directory, and all parent directories, for the " +
"first `Sakefile` it can find, and then invoke the TASK. If no task " +
"is given, it will try to invoke the task named \"default\".\n\n" +
"`Sakefile` can be one of \"Sakefile\", \"sakefile\", \"Sakefile.js\", " +
"\"sakefile.js\", \"Sakefile.coffee\", or \"sakefile.coffee\""
)).
options(formatHelp(opts)).
parse(nomArgs);
// aliases for changed properties
Object.defineProperties(parsedOpts, {
synchronous: {
get: function () {
return parsedOpts.sync;
},
set: function (v) {
parsedOpts.sync = v;
},
enumerable: true,
configurable: false
},
prerequisites: {
value: parsedOpts.prereqs,
enumerable: true,
configurable: false
}
});
//---------------------------------------------------------------------------
// Export the parsed options
//---------------------------------------------------------------------------
module.exports = parsedOpts;
|
JavaScript
| 0 |
@@ -4882,16 +4882,19 @@
efile%5C%22,
+ or
%5C%22sakef
@@ -4904,72 +4904,56 @@
%5C%22,
-%5C%22Sakefile.js%5C%22, %22 +%0A %22%5C%22sakefile.js%5C%22, %5C%22Sakefile.coffee
+with an %22 +%0A %22optional extension of %5C%22.js
%5C%22,
@@ -4957,24 +4957,16 @@
%22, or %5C%22
-sakefile
.coffee%5C
|
68684d244c019cf321f7af534f74bb604c58dc4e
|
Add corrected logic for sync state message
|
src/selectors/temperatureSync.js
|
src/selectors/temperatureSync.js
|
/**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2020
*/
import moment from 'moment';
import { TEMPERATURE_SYNC_STATES } from '../reducers/TemperatureSyncReducer';
import { syncStrings } from '../localization';
const STATE_TO_MESSAGE = {
[TEMPERATURE_SYNC_STATES.SCANNING]: syncStrings.scanning_for_sensors,
[TEMPERATURE_SYNC_STATES.SCAN_ERROR]: syncStrings.error_scanning_for_sensors,
[TEMPERATURE_SYNC_STATES.DOWNLOADING_LOGS]: syncStrings.downloading_temperature_logs,
[TEMPERATURE_SYNC_STATES.DOWNLOADING_LOGS_ERROR]: syncStrings.error_downloading_temperature_logs,
[TEMPERATURE_SYNC_STATES.RESETTING_ADVERTISEMENT_FREQUENCY]: syncStrings.resetting_sensor,
[TEMPERATURE_SYNC_STATES.RESETTING_LOG_FREQUENCY]: syncStrings.resetting_sensor,
[TEMPERATURE_SYNC_STATES.ERROR_RESETTING_ADVERTISEMENT_FREQUENCY]:
syncStrings.error_resetting_sensor,
[TEMPERATURE_SYNC_STATES.ERROR_RESETTING_LOG_FREQUENCY]: syncStrings.error_resetting_sensor,
[TEMPERATURE_SYNC_STATES.SAVING_LOGS]: syncStrings.saving_temperature_logs,
[TEMPERATURE_SYNC_STATES.NO_SENSORS]: syncStrings.no_sensors,
[TEMPERATURE_SYNC_STATES.SYNCING]: syncStrings.syncing_temperatures,
};
export const selectTemperatureSyncMessage = ({ temperatureSync }) => {
const { syncState, syncError } = temperatureSync;
return STATE_TO_MESSAGE[syncState ?? syncError] ?? syncStrings.sync_complete;
};
export const selectTemperatureSyncLastSyncString = ({ temperatureSync }) => {
const { lastTemperatureSync } = temperatureSync;
return `${moment(lastTemperatureSync).format('H:mm MMMM D, YYYY ')}`;
};
export const selectCurrentSensorNameString = ({ temperatureSync }) => {
const { currentSensorName } = temperatureSync;
return currentSensorName ? `Syncing sensor: ${currentSensorName}` : null;
};
export const selectTemperatureSyncIsComplete = ({ temperatureSync }) => {
const { total, progress } = temperatureSync;
return total === progress;
};
export const selectTemperatureSyncStateMessage = ({ temperatureSync }) => {
const { syncState, syncError } = temperatureSync;
return (syncError && syncStrings.sync_error) || syncState
? syncStrings.sync_in_progress
: syncStrings.sync_enabled;
};
export const selectTemperatureModalIsOpen = ({ temperatureSync }) => {
const { modalIsOpen } = temperatureSync;
return modalIsOpen;
};
export const selectTemperatureSyncProgress = ({ temperatureSync }) => {
const { total, progress } = temperatureSync;
return { total, progress };
};
export const selectIsSyncingTemperatures = ({ temperatureSync }) => {
const { isSyncing } = temperatureSync;
return isSyncing;
};
|
JavaScript
| 0.000001 |
@@ -2048,32 +2048,53 @@
State, syncError
+, lastTemperatureSync
%7D = temperature
@@ -2090,32 +2090,104 @@
temperatureSync;
+%0A const formattedDate = moment(lastTemperatureSync).format('D.M.YYYY');
%0A%0A return (sync
@@ -2182,16 +2182,22 @@
return (
+%0A (
syncErro
@@ -2201,16 +2201,19 @@
rror &&
+%60$%7B
syncStri
@@ -2230,26 +2230,72 @@
rror
-) %7C%7C
+%7D. $%7B
syncSt
-ate%0A
+rings.last_sync%7D $%7BformattedDate%7D%60) %7C%7C%0A (syncState
? s
@@ -2321,20 +2321,16 @@
progress
-%0A
: syncS
@@ -2348,16 +2348,21 @@
_enabled
+)%0A )
;%0A%7D;%0A%0Aex
|
da29046417a9df6502a6a51673b65fd71af53b6c
|
Simplify code with destructuring
|
src/main/lib/math.js
|
src/main/lib/math.js
|
'use strict'
function iterationsToEscape(x0, y0, iterations) {
var x = x0
var y = y0
var i = 0
function iterate() {
i++
var tempY = 2 * x * y + y0
x = x * x - y * y + x0
y = tempY
}
while (x * x + y * y < 4) {
if (i === iterations) return -1
iterate()
}
return i
}
module.exports = {
iterationsToEscape: iterationsToEscape
}
|
JavaScript
| 0.000298 |
@@ -135,43 +135,18 @@
-var tempY = 2 * x * y + y0%0A x
+%5Bx, y%5D
=
+%5B
x *
@@ -163,22 +163,25 @@
+ x0
-%0A y = tempY
+, 2 * x * y + y0%5D
%0A %7D
|
e404c8a3a64d84b7af694ceb8f647a4b93bd77ad
|
Fix default Intl polyfill language (#1208)
|
internals/templates/app.js
|
internals/templates/app.js
|
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(System.import('intl'));
}))
.then(() => Promise.all([
System.import('intl/locale-data/jsonp/de.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
JavaScript
| 0 |
@@ -2887,18 +2887,18 @@
a/jsonp/
-d
e
+n
.js'),%0A
|
5f24cf459d0175c5ec77d8823cfcc8fe91892536
|
Add animationHelper
|
jquery.transitionHelper.js
|
jquery.transitionHelper.js
|
/*! jQuery.transitionHelper, v0.1 | MIT */
/**
* @fileOverview Micro plugin to help with CSS transitions
*
* @copyright Copyright (c) 2013 Urszula Ciaputa (http://urszula.ciaputa.com)
* @author Urszula Ciaputa <[email protected]>
*
* @version 0.1
* @license http://www.opensource.org/licenses/mit-license.php
*/
/*jslint unparam: true, browser: true */
/*global jQuery, Modernizr */
/**
* jQuery
*
* @name jQuery
* @namespace
*
* This just documents the function and classes that are added to jQuery
* by this plug-in.
* @see <a href="http://jquery.com/">jQuery Library</a>
*/
/**
* jQuery.fn
*
* @name fn
* @memberOf jQuery
* @namespace
*
* This just documents the function and classes that are added to jQuery
* by this plug-in.
* @see <a href="http://jquery.com/">jQuery Library</a>
*/
/**
* Modernizr
*
* @name Modernizr
* @namespace
*
* @see <a href="http://modernizr.com/">Modernizr Library</a>
*/
/**
* Modernizr.prefixed
*
* @name prefixed
* @memberOf Modernizr
* @function
*
* @see <a href="http://modernizr.com/docs/#prefixed">Modernizr.prefixed() Docs</a>
*/
;(function ($, window, undefined) {
"use strict";
var EVENTS = {
transitionend: {
'WebkitTransition' : 'webkitTransitionEnd',
'MozTransition' : 'transitionend',
'OTransition' : 'oTransitionEnd otransitionend',
'msTransition' : 'MSTransitionEnd',
'transition' : 'transitionend'
}[ Modernizr.prefixed('transition') ]
};
$.fn.transitionHelper = function (callback, off) {
callback = callback || function () {};
if (EVENTS.transitionend){
return (off ? this.off : this.on).call(this, EVENTS.transitionend + '.transitionHelper', function (ev) {
//ignore events bubbling from descendants
if (ev.target !== this) {
return ;
}
$(this).off(EVENTS.transitionend + '.transitionHelper').removeClass('transition-helper');
callback.call(this, ev);
}).toggleClass('transition-helper', !off);
} else {
callback.call(this);
return this;
}
};
}(jQuery, this));
|
JavaScript
| 0 |
@@ -25,17 +25,17 @@
per, v0.
-1
+2
%7C MIT *
@@ -1475,32 +1475,304 @@
') %5D
+,%0A
%0A%09%09
-%7D;%0A%0A%09$.fn.transitionH
+%09animationend: %7B%0A%09%09%09%09'WebkitAnimation' : 'webkitAnimationEnd',%0A%09%09%09%09'MozAnimation' : 'animationend',%0A%09%09%09%09'OAnimation' : 'oAnimationEnd oanimationend',%0A%09%09%09%09'msAnimation' : 'MSAnimationEnd',%0A%09%09%09%09'animation' : 'animationend'%0A%09%09%09%7D%5B Modernizr.prefixed('animation') %5D%0A%09%09%7D;%0A%0A%09var h
elpe
@@ -1785,16 +1785,23 @@
nction (
+event,
callback
@@ -1862,30 +1862,23 @@
(EVENTS
-.transitionend
+%5Bevent%5D
)%7B%0A%09%09%09re
@@ -1922,38 +1922,31 @@
this, EVENTS
-.transitionend
+%5Bevent%5D
+ '.transit
@@ -2095,22 +2095,15 @@
ENTS
-.transitionend
+%5Bevent%5D
+ '
@@ -2291,16 +2291,248 @@
%09%7D%0A%09%7D;%0A%0A
+%09$.fn.transitionHelper = function (callback, off) %7B%0A%09%09return helper.call(this, 'transitionend', callback, off);%0A%09%7D;%0A%0A%09$.fn.animationHelper = function (callback, off) %7B%0A%09%09return helper.call(this, 'animationend', callback, off);%0A%09%7D;%0A%0A
%7D(jQuery
|
2a995f18c030a34b24c914954b8676da3363cdae
|
Add support of analytics.js (GA) to switcher
|
js/all/counters-support.js
|
js/all/counters-support.js
|
/**
* This script will fix some counters to be used with Switcher.js.
*/
$(document).on('construct', function () {
// Google Analytics
//noinspection JSUnresolvedVariable
if (typeof _gaq == 'object' && typeof _gaq.push == 'function') {
//noinspection JSUnresolvedVariable
_gaq.push(['_trackPageview', switcher.url]);
}
// Yandex Metrika
for (var y in window) {
if (typeof( window[y] ) != 'object' || !y.match(/^yaCounter[0-9]*$/)) {
continue;
}
window[y].hit(switcher.url, document.title, document.referrer);
}
});
|
JavaScript
| 0 |
@@ -135,16 +135,32 @@
nalytics
+ (ga.js, legacy)
%0A%0A //
@@ -364,16 +364,263 @@
);%0A %7D
+%0A %0A // Google Analytics (analytics.js)%0A %0A //noinspection JSUnresolvedVariable%0A if (typeof ga == 'function') %7B%0A //noinspection JSUnresolvedVariable%0A ga('set', 'page', switcher.url);%0A ga('send', 'pageview');%0A %7D
%0A%0A //
|
8abe4d57e0832fe95f96e120be36bac41661c0b6
|
Fix issue with JSCS failing to report violations
|
gulp/tasks/jscs.js
|
gulp/tasks/jscs.js
|
'use strict';
var jscs = require('gulp-jscs');
var log = require('../utils/log');
module.exports = function(gulp, options) {
var config = require('../config')[options.key || 'jscs'];
return task;
function task() {
if (options.verbose) {
log('Running JSCS');
}
return gulp.src(config.src)
.pipe(jscs(config.rcFile));
}
};
|
JavaScript
| 0 |
@@ -181,16 +181,44 @@
scs'%5D;%0A%0A
+ console.log(config.src);%0A%0A
return
@@ -359,21 +359,64 @@
scs(
-config.rcFile
+%7BconfigPath: config.rcFile%7D))%0A .pipe(jscs.reporter(
));%0A
|
bfec50c1819c223b5bbf78ec28d5b1339c403184
|
Fix `PUT /motd` validation
|
src/validations.js
|
src/validations.js
|
import joi from 'joi';
const objectID = joi.string().length(24);
const userName = joi.string()
.min(3).max(32)
.regex(/^[^\s\n]+$/);
const userEmail = joi.string().email();
const userPassword = joi.string().min(6);
const newStylePagination = joi.object({
page: joi.object({
offset: joi.number().min(0),
limit: joi.number().min(0),
}),
});
const oldStylePagination = joi.object({
page: joi.number().min(0),
limit: joi.number().min(0),
});
const pagination = [
newStylePagination,
oldStylePagination,
];
// Validations for authentication routes:
export const register = joi.object({
body: joi.object({
email: userEmail.required(),
username: userName.required(),
password: userPassword.required(),
}),
});
export const login = joi.object({
body: joi.object({
email: userEmail.required(),
password: joi.string().required(),
}),
});
export const requestPasswordReset = joi.object({
body: joi.object({
email: userEmail.required(),
}),
});
export const passwordReset = joi.object({
body: joi.object({
email: userEmail.required(),
password: userPassword.required(),
}),
});
// Validations for booth routes:
export const skipBooth = joi.object({
body: joi.object({
reason: joi.string().allow(''),
userID: objectID,
remove: joi.bool(),
}).and('userID', 'reason'),
});
export const replaceBooth = joi.object({
body: joi.object({
userID: objectID.required(),
}),
});
export const favorite = joi.object({
body: joi.object({
playlistID: objectID.required(),
historyID: objectID.required(),
}),
});
export const getRoomHistory = joi.object({
query: pagination,
});
// Validations for chat routes:
export const deleteChatByUser = joi.object({
params: joi.object({
id: objectID.required(),
}),
});
export const deleteChatMessage = joi.object({
params: joi.object({
id: joi.string().required(),
}),
});
// Validations for MOTD routes:
export const setMotd = joi.object({
params: joi.object({
motd: joi.string().required(),
}),
});
// Validations for playlist routes:
const playlistParams = joi.object({
id: objectID.required(),
});
const playlistItemParams = joi.object({
id: objectID.required(),
itemID: objectID.required(),
});
export const createPlaylist = joi.object({
body: joi.object({
name: joi.string().required(),
}),
});
export const getPlaylist = joi.object({
params: playlistParams,
});
export const deletePlaylist = joi.object({
params: playlistParams,
});
export const updatePlaylist = joi.object({
params: playlistParams,
body: joi.object({
name: joi.string(),
shared: joi.bool(),
description: joi.string(),
}),
});
export const renamePlaylist = joi.object({
params: playlistParams,
body: joi.object({
name: joi.string().required(),
}),
});
export const sharePlaylist = joi.object({
params: playlistParams,
body: joi.object({
shared: joi.bool().required(),
}),
});
export const getPlaylistItems = joi.object({
params: playlistParams,
query: pagination,
});
export const addPlaylistItems = joi.object({
params: playlistParams,
body: joi.object({
items: joi.array().required(),
}),
});
export const removePlaylistItems = joi.object({
params: playlistParams,
body: joi.object({
items: joi.array().required(),
}),
});
export const movePlaylistItems = joi.object({
params: playlistParams,
body: joi.object({
items: joi.array().required(),
after: [
objectID, // Insert after ID
joi.number().valid(-1), // Prepend
],
}),
});
export const shufflePlaylistItems = joi.object({
params: playlistParams,
});
export const getPlaylistItem = joi.object({
params: playlistItemParams,
});
export const updatePlaylistItem = joi.object({
params: playlistItemParams,
body: joi.object({
artist: joi.string(),
title: joi.string(),
start: joi.number().min(0),
end: joi.number().min(0),
}),
});
export const removePlaylistItem = joi.object({
params: playlistItemParams,
});
// Validations for user routes:
const userParams = joi.object({
id: objectID.required(),
});
export const getUser = joi.object({
params: userParams,
});
export const muteUser = joi.object({
params: userParams,
body: joi.object({
time: joi.number().min(0).required(),
}),
});
export const unmuteUser = joi.object({
params: userParams,
});
export const setUserRole = joi.object({
params: userParams,
body: joi.object({
role: joi.number().min(0).max(4).required(),
}),
});
export const setUserName = joi.object({
params: userParams,
body: joi.object({
username: userName,
}),
});
export const setUserAvatar = joi.object({
params: userParams,
body: joi.object({
avatar: joi.string(),
}),
});
export const setUserStatus = joi.object({
params: userParams,
body: joi.object({
status: joi.number(),
}),
});
export const getUserHistory = joi.object({
params: userParams,
query: pagination,
});
// Validations for Waitlist routes:
export const joinWaitlist = joi.object({
body: joi.object({
userID: objectID.required(),
}),
});
export const moveWaitlist = joi.object({
body: joi.object({
userID: objectID.required(),
position: joi.number().min(0).required(),
}),
});
export const lockWaitlist = joi.object({
body: joi.object({
lock: joi.bool().required(),
}),
});
|
JavaScript
| 0.000069 |
@@ -1983,38 +1983,36 @@
joi.object(%7B%0A
-params
+body
: joi.object(%7B%0A
|
2c2d7ad6d5d32466f44f5763a0083ef8be5d457d
|
Update index.js
|
examples/using-router/pages/index.js
|
examples/using-router/pages/index.js
|
import React from 'react'
import Header from '../components/Header'
export default () => (
<div>
<Header />
<p>HOME PAGE is here!</p>
</div>
)
|
JavaScript
| 0.000002 |
@@ -1,30 +1,4 @@
-import React from 'react'%0A
impo
|
29806474973cb635f69bf134178cfed6e3f7355d
|
Clean up and code commenting
|
app/app.js
|
app/app.js
|
var express = require('express'),
bodyParser = require('body-parser'),
log4js = require('log4js');
fs = require('fs');
var app = express();
app.use(bodyParser.json());
log4js.configure({
appenders: [
{ type: 'console' },
{ type: 'file', filename: 'logs/eventgenerator.log' }
]
})
var logger = log4js.getLogger();
var lock;
app.get('/start',function(req,res){
logger.debug('GET /start - Starting app');
lock = true;
dotCounter();
res.sendStatus(200);
})
app.get('/stop',function(req,res){
logger.debug('GET /stop - Stopping app');
lock = false;
res.sendStatus(200);
})
app.listen(8001,function(err){
if(err) return console.error(err);
var man = '########################\n' +
'# EVENT GENERATOR #\n' +
'# By Mark Winteringham #\n' +
'########################\n\n' +
'This microservice, when started, will randomly create events between intervals and\n' +
'output the events to a log file and database that can then be monitored using the\n' +
'monitoring tool in this repo\n\n' +
'Using the app:\n' +
'- To start the app call http://localhost:8001/start to make the app create events\n' +
'- To stop the app call http://localhost:8001/stop';
console.log(man)
});
function dotCounter(){
var randomnumber = Math.floor(Math.random()*6);
switch(randomnumber){
case 0:
logger.trace('I\'ve been getting some interference on D channel.');
break;
case 1:
logger.debug('I think you know what the problem is just as well as I do');
break;
case 2:
logger.info('I know everything hasn\'t been quite right with me, but I can assure you now, very confidently, that it\'s going to be alright again');
break;
case 3:
logger.warn('Just what do you think you\'re doing, Dave?');
break;
case 4:
logger.error('Dave...Dave...my mind is going...I can feel it...I can feel it...my mind is going');
break;
case 5:
logger.fatal('Daisy, Daisy, give me your answer do. I\'m half crazy, all for the love of you.');
break;
}
setTimeout(function(){
if(lock){
dotCounter();
}
},1000);
}
|
JavaScript
| 0 |
@@ -148,27 +148,92 @@
var
-app = express();%0A
+logger = log4js.getLogger(),%0A app = express();%0A%0A// Configure express and log4js%0A%0A
app.
@@ -386,50 +386,62 @@
%7D)%0A%0A
-var logger = log4js.getLogger();%0Avar lock;
+%0A// Endpoints to turn on and off the app randomisation
%0A%0Aap
@@ -691,28 +691,75 @@
tatus(200);%0A
-
%7D)%0A%0A
+// Start the app up and console out app usage%0A%0A
app.listen(8
@@ -1463,16 +1463,62 @@
n)%0A%7D);%0A%0A
+// Randomisation method to create app events%0A%0A
function
|
399a369d45cdef5e03301cd7b136c8527fe6d307
|
Add comment
|
app/app.js
|
app/app.js
|
'use strict';
/* INJECT DEPENDENCIES */
angular.module('myApp', [
'myApp.services',
'ui.bootstrap',
'ui.bootstrap.tpls',
'ui.router'
])
.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider) {
$urlRouterProvider
.otherwise('/index');
$stateProvider
.state('index', {
url: "/index",
views: {
"state" : { templateUrl: "partials/main_state.html" },
}
})
.state('list', {
url: "/list",
views: {
"state" : { templateUrl: "partials/blog_list.html" },
}
})
.state('post', {
url: "/post",
views: {
"state" : {
templateUrl: "partials/blog_post.html" },
controller: 'PostCtrl',
}
})
}])
//------ INJECT STRICT CONTEXTUAL ESCAPING INTO VIEW CONTROLLER -----
.controller('PostCtrl', ['$scope', '$sce', '$anchorScroll', '$location', function($scope, $sce, $anchorScroll, $location) {
$scope.markup = $sce.trustAsHtml($scope.$parent.currentPost);
$location.hash('top');
$anchorScroll();
}])
.controller('ServiceCtrl', function($scope, $state, fetchBlogService) {
var handleSuccess = function(data, status) {
$scope.posts = data;
console.log('POSTS', $scope.posts);
};
function addRemoteDomain(payload) {
//--- PREPEND DOMAIN TO IMAGE URLs --------
var before1 = 'src="/';
var before2 = 'src="/sites/default/files/';
var after1 = 'src="http://woodylewis.com/';
var after2 = 'src="http://woodylewis.com/sites/default/files/';
var result1 = payload.split(before1).join(after1);
var result2 = result1.split(before2).join(after2);
return result2;
}
var handlePostSuccess = function(data, status) {
// PREPEND REMOTE DOMAIN TO IMAGE LINKS
$scope.currentPost = addRemoteDomain(data);
var postState = 'post';
$state.go(postState);
};
fetchBlogService.fetchBlog()
.success(handleSuccess);
$scope.showCurrentPost= function(nid) {
$scope.currentPost = fetchBlogService.fetchBlogPost(nid)
.success(handlePostSuccess);
};
});
|
JavaScript
| 0 |
@@ -1037,16 +1037,98 @@
tPost);%0A
+ //----- OLDER POSTS FURTHER DOWN THE LIST NEED TO BE SCROLLED TO THEIR TOP LINE%0A
$locat
|
fca72df1d9a5c9945fcc06f9bc591001dfa0131d
|
append .hex extension to output file
|
bin/cli.js
|
bin/cli.js
|
#!/usr/bin/env node
var avrpizza = require('../avrpizza');
var boards = require('../lib/boards');
var parseArgs = require('minimist');
var path = require('path');
var fs = require('fs');
var args = (process.argv.slice(2));
var argv = parseArgs(args, {});
var userAction = argv._[0];
var help = 'Usage:\n' +
' avrpizza compile -s <sketch filepath> -l <library dirpath> -a <arduino name> [-o <output path>]\n' +
' avrpizza help\n';
function showHelp() {
console.log(help);
}
function compile(options) {
options.sketch = path.resolve(process.cwd(), options.sketch);
options.libraries.forEach(function(l, i) {
options.libraries[i] = path.resolve(process.cwd(), l);
});
options.output = path.resolve(process.cwd(), options.output);
avrpizza.compile(options, function(error, hex) {
if (error) {
console.error(error);
process.exit(1);
} else {
var hexfilename = path.basename(options.sketch);
var savelocation = path.join(options.output, hexfilename);
// create write stream for entry file
var ws = fs.createWriteStream(savelocation);
//write file
ws.write(hex);
}
});
}
function handleInput(action, argz) {
switch (action) {
case 'compile': {
if (!argz.s || !argz.a) {
showHelp();
process.exit(1);
} else if (boards.indexOf(argz.a) === -1) {
console.error(new Error('Oops! That board is not supported, sorry.'));
process.exit(1);
} else {
// run compile function here if all is well
var options = {
libraries: argz.l || [],
sketch: argz.s,
board: argz.a,
version: argz.c || '',
output: argz.o || './',
debug: argz.v || false
};
compile(options);
}
break;
}
case 'help': {
showHelp();
process.exit();
break;
}
default: {
// Invalid or no argument specified, show help and exit with an error status
showHelp();
process.exit(9);
break;
}
}
}
handleInput(userAction, argv);
|
JavaScript
| 0.000003 |
@@ -993,16 +993,25 @@
filename
+ + '.hex'
);%0A
|
f099aeab61f5e3a6d53b2442e00d00b2a1567168
|
Fix casing
|
bin/cli.js
|
bin/cli.js
|
#!/usr/bin/env node
'use strict';
const path = require('path');
const argv = require('argh').argv;
const fsp = require('fs').promises;
const rimraf = require('rimraf');
const convertFromMinimap = require('../src/from-minimap.js');
const convertToMinimap = require('../src/to-minimap.js');
const generateBoundsFromMinimap = require('../src/generate-bounds-from-minimap.js');
const info = require('../package.json');
const emptyDirectory = (path) => {
return new Promise((resolve, reject) => {
rimraf(`${path}/*`, () => {
fsp.mkdir(path, { recursive: true }).then(() => {
resolve();
});
});
});
};
const main = async () => {
const excludeMarkers = argv['markers'] === false;
const overlayGrid = argv['overlay-grid'] === true;
if (process.argv.length == 2) {
console.log(`${info.name} v${info.version} - ${info.homepage}`);
console.log('\nUsage:\n');
console.log(`\t${info.name} --from-minimap=./minimap --output-dir=./data`);
console.log(`\t${info.name} --from-minimap=./minimap --output-dir=./data --markers-only`);
console.log(`\t${info.name} --from-data=./data --output-dir=./minimap --no-markers`);
console.log(`\t${info.name} --from-data=./data --output-dir=./minimap-grid --overlay-grid`);
console.log(`\t${info.name} --from-data=./data --extra=achievements,Orcsoberfest --output-dir=./minimap`);
process.exit(1);
}
if (argv['v'] || argv['version']) {
console.log(`v${info.version}`);
return process.exit(0);
}
if (!argv['from-minimap'] && !argv['from-data']) {
console.log('Missing `--from-minimap` or `--from-data` flag.');
return process.exit(1);
}
if (argv['from-minimap'] && argv['from-data']) {
console.log('Cannot combine `--from-minimap` with `--from-data`. Pick one.');
return process.exit(1);
}
if (argv['from-minimap']) {
if (argv['from-minimap'] === true) {
console.log('`--from-minimap` path not specified. Using the default, i.e. `minimap`.');
argv['from-minimap'] = 'minimap';
}
const mapsDirectory = path.resolve(String(argv['from-minimap']));
if (!argv['output-dir'] || argv['output-dir'] === true) {
console.log('`--output-dir` path not specified. Using the default, i.e. `data`.');
argv['output-dir'] = 'data';
}
const dataDirectory = path.resolve(String(argv['output-dir']));
const markersOnly = argv['markers-only'];
if (!markersOnly) {
await emptyDirectory(dataDirectory);
}
const bounds = await generateBoundsFromMinimap(mapsDirectory, dataDirectory, !markersOnly);
convertFromMinimap(
bounds, mapsDirectory, dataDirectory, !excludeMarkers, markersOnly
);
return;
}
if (argv['from-data']) {
if (argv['from-data'] === true) {
console.log('`--from-data` path not specified. Using the default, i.e. `data`.');
argv['from-data'] = 'data';
}
const dataDirectory = path.resolve(argv['from-data']);
if (!argv['output-dir'] || argv['output-dir'] === true) {
console.log('`--output-dir` path not specified. Using the default, i.e. `minimap-new`.');
argv['output-dir'] = 'minimap-new';
}
const extra = (() => {
if (!argv['extra'] || typeof argv['extra'] !== 'string') {
return false;
}
const ids = argv['extra'].split(',');
return ids.map(id => path.resolve(dataDirectory, '../extra/', id));
})();
const minimapDirectory = path.resolve(String(argv['output-dir']));
await emptyDirectory(minimapDirectory);
await convertToMinimap(dataDirectory, minimapDirectory, extra, !excludeMarkers, overlayGrid);
return;
}
};
main();
|
JavaScript
| 0.000002 |
@@ -1295,17 +1295,17 @@
vements,
-O
+o
rcsoberf
|
53c340133f28555f27572bdf576192aac0d720c1
|
Fix browser version is number
|
karma-sauce.conf.js
|
karma-sauce.conf.js
|
if (!process.env.SAUCE_USERNAME || !process.env.SAUCE_ACCESS_KEY) {
console.error('Make sure the SAUCE_USERNAME and SAUCE_ACCESS_KEY environment variables are set.')
process.exit(1)
}
const BROWSERS = {
chrome: [null],
firefox: [null]
}
const PLATFORMS = {
Windows: [
'7',
'8',
'8.1',
'10'
],
Mac: [
'10.9',
'10.10',
'10.11',
'10.12'
],
Linux: [null]
}
function createCustomLauncher(browser, version, platform) {
return {
base: 'SauceLabs',
browserName: browser,
version: version,
platform: platform
}
}
function combineBrowsersWithPlatforms() {
const customLaunchers = {}
for (const browser in BROWSERS) {
const browserVersions = BROWSERS[browser]
for (const browserVersion of browserVersions) {
for (const platform in PLATFORMS) {
const platformVersions = PLATFORMS[platform]
for (const platformVersion of platformVersions) {
const launcher = `sl_${browser}_${browserVersion || 'latest'}_${platform}_${platformVersion || 'latest'}`
const platformVersionString = platformVersion ? ` ${platformVersion}` : ''
customLaunchers[launcher] = createCustomLauncher(browser, browserVersion, `${platform}${platformVersionString}`)
}
}
}
}
return customLaunchers
}
module.exports = function(config) {
// Combine all cross-platform browsers and platforms above
const customLaunchers = combineBrowsersWithPlatforms()
// Safari
customLaunchers.sl_safari_8_Mac_10 = createCustomLauncher('safari', '8', 'Mac 10.10')
customLaunchers.sl_safari_9_Mac_11 = createCustomLauncher('safari', '9', 'Mac 10.11')
customLaunchers.sl_safari_9_Mac_11 = createCustomLauncher('safari', '10', 'Mac 10.11')
customLaunchers.sl_safari_10_Mac_12 = createCustomLauncher('safari', '10', 'Mac 10.12')
// IE
customLaunchers.sl_ie_9 = createCustomLauncher('internet explorer', 9, 'Windows 7')
customLaunchers.sl_ie_10 = createCustomLauncher('internet explorer', 'Windows 8')
customLaunchers.sl_ie_11_Windows_81 = createCustomLauncher('internet explorer', 'Windows 8.1')
customLaunchers.sl_ie_11_Windows_10 = createCustomLauncher('internet explorer', 'Windows 10')
// Edge
customLaunchers.sl_edge = createCustomLauncher('microsoftedge', '13')
customLaunchers.sl_edge = createCustomLauncher('microsoftedge', '14')
customLaunchers.sl_edge = createCustomLauncher('microsoftedge', '15')
config.set({
basePath: '',
frameworks: ['jasmine', '@angular/cli'],
plugins: [
require('karma-jasmine'),
require('karma-sauce-launcher'),
require('@angular/cli/plugins/karma')
],
client: {
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
angularCli: {
environment: 'dev'
},
reporters: ['dots', 'saucelabs'],
autoWatch: false,
sauceLabs: {
testName: 'Karma Test',
public: 'public'
},
customLaunchers: customLaunchers,
browsers: Object.keys(customLaunchers),
singleRun: true
})
}
|
JavaScript
| 0.001148 |
@@ -1912,17 +1912,19 @@
lorer',
-9
+'9'
, 'Windo
|
ca4d808d1fd3fedca84296f13d2dc3dc15ad7e06
|
Decrease concurrency in SauceLabs
|
karma.conf-sauce.js
|
karma.conf-sauce.js
|
// Karma configuration
module.exports = function(config) {
var customLaunchers = {
sl_chrome_latest: {
base: 'SauceLabs',
browserName: 'chrome',
version: 'latest'
},
sl_chrome_previous: {
base: 'SauceLabs',
browserName: 'chrome',
version: 'latest-1'
},
sl_firefox_latest: {
base: 'SauceLabs',
browserName: 'firefox',
version: 'latest'
},
sl_firefox_previous: {
base: 'SauceLabs',
browserName: 'firefox',
version: 'latest-1'
},
sl_edge_latest: {
base: 'SauceLabs',
browserName: 'microsoftedge',
platform: 'Windows 10',
version: 'latest'
},
sl_edge_previous: {
base: 'SauceLabs',
browserName: 'microsoftedge',
platform: 'Windows 10',
version: 'latest-1'
},
sl_safari_latest: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.12',
version: 'latest'
},
sl_safari_previous: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.12',
version: 'latest-1'
},
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '11.0'
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '10.0'
},
sl_ios_safari_latest: {
base: 'SauceLabs',
browserName: 'Safari',
appiumVersion: '1.7.1',
deviceName: 'iPhone 8 Simulator',
deviceOrientation: 'portrait',
platformVersion: '11.0',
platformName: 'iOS'
},
sl_ios_safari_previous: {
base: 'SauceLabs',
browserName: 'Safari',
appiumVersion: '1.7.1',
deviceName: 'iPhone 7 Simulator',
deviceOrientation: 'portrait',
platformVersion: '10.3',
platformName: 'iOS'
}
}
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha', 'fixture', 'sinon-chai', 'chai-dom', 'chai', 'calling'],
// list of files / patterns to load in the browser
files: [
'dist/scrollmarks.js',
'test/helpers/**/*',
'test/*.spec.js',
'test/fixtures/**/*'
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'dist/scrollmarks.js': ['eslint', 'coverage'],
'**/*.html': ['html2js']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['dots', 'saucelabs', 'coverage', 'coveralls'],
coverageReporter: {
type : 'lcov',
dir: 'coverage/'
},
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
sauceLabs: {
build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
startConnect: true,
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER
},
customLaunchers: customLaunchers,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: Object.keys(customLaunchers),
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: true,
// Concurrency level
// how many browser should be started simultaneous
concurrency: 4
})
}
|
JavaScript
| 0.00001 |
@@ -3636,9 +3636,9 @@
cy:
-4
+2
%0A%09%7D)
|
7cfaa3bad404db1abdac07ec6d406d3acb46124f
|
Remove use of deprecated APIs.
|
spec/menu_panel_spec.js
|
spec/menu_panel_spec.js
|
/** Tests for MenuPanel. */
/**
* Wrap the given menu in a panel
* and return the panel.
*/
var wrapPanel = function(menu) {
var panel = new Ext.form.FormPanel({
fullscreen: true,
layout: 'fit',
items: [
{
xtype: 'fieldset',
items: [menu]
}
]
});
return panel;
};
component('Stuff me', function() {
it('should do good stuff', function() {
expect(true).toBeTruthy();
});
});
component('MenuPanel', function() {
var panel;
beforeEach(function() {
panel = null;
});
afterEach(function() {
if(panel !== null)
{
panel.destroy();
panel = null;
}
});
it('Should construct correctly', function() {
var menu = new vrs.ux.touch.MenuPanel();
});
feature('menu item configuration', function() {
it('Should support rendering', function() {
var menu = new vrs.ux.touch.MenuPanel({
menuItems: [ {content: 'item1'}]
});
panel = wrapPanel(menu);
expect(menu.rendered).toBeTruthy();
expect(menu.getEl().is('.x-menu-panel')).toBeTruthy();
});
it('should support configuration of multiple rows', function() {
var menu = new vrs.ux.touch.MenuPanel({
menuItems: [
{content: 'item1'},
{content: 'item2'}
]
});
panel = wrapPanel(menu);
expect(panel.getEl().select('.x-menupanel-row').getCount()).toEqual(2);
});
it('should allow specifying left and right icons', function() {
var menu, left_src, right_src,
icon1 = 'resources/img/checked.png',
icon2 = 'resources/img/chevron.png';
menu = new vrs.ux.touch.MenuPanel({
menuItems: [
{leftIcon: icon1, content: 'item1', rightIcon: icon2}
]
});
panel = wrapPanel(menu);
left_src = panel.getEl().down('.x-menupanel-leftitem > img').getAttribute('src');
right_src = panel.getEl().down('.x-menupanel-rightitem > img').getAttribute('src');
expect(left_src).toEqual(icon1);
expect(right_src).toEqual(icon2);
});
it('should allow specifying left and right icon mask classes', function() {
var left_img, right_img, menu;
menu = new vrs.ux.touch.MenuPanel({
menuItems: [
{leftIconCls: 'lefty', content: 'item1', rightIconCls: 'righty'}
]
});
panel = wrapPanel(menu);
left_img = panel.getEl().down('.x-menupanel-leftitem > img');
right_img = panel.getEl().down('.x-menupanel-rightitem > img');
expect(left_img.is('.lefty')).toBeTruthy();
expect(left_img.is('.righty')).toBeFalsy();
expect(right_img.is('.righty')).toBeTruthy();
expect(right_img.is('.lefty')).toBeFalsy();
});
it('should support setting default values for menu items', function() {
var left_img, right_img, menu;
menu = new vrs.ux.touch.MenuPanel({
menuItemDefaults: {leftIconCls: 'lefty', rightIconCls: 'righty'},
menuItems: [
{content: 'item1'}
]
});
panel = wrapPanel(menu);
left_img = panel.getEl().down('.x-menupanel-leftitem > img');
right_img = panel.getEl().down('.x-menupanel-rightitem > img');
expect(left_img.is('.lefty')).toBeTruthy();
expect(right_img.is('.righty')).toBeTruthy();
});
});
feature('event management', function() {
// It should support itemtap
// It should support itemdoubletap
// It should support itemswipe
// It should support left and right item events
// It should support per item events (itemtap, itemdoubletap, itemswipe, etc)
});
});
/**
Required functionality:
Config and Structure:
* It should support simple configuration and specification of "rows"
* It should allow specifying lead icon and/or disclosure icon
* It should allow specifying a class that is used for mask styling instead
* It should use an item selector internally.
* It should support setting defaults for configuration (ex: right chevron for all items)
* It should support updating the configuration (in place?)
* It should support fast updating in place. (ie. no DOM changes)
Events:
* It should support events for when the lead/trail objects are tapped
* It should support itemtap
* It should support itemdoubletap
* It should support itemswipe
* It should support events callbacks getting an index of the item selected
* It should support per item events (itemtap, itemdoubletap, itemswipe)
* It should support custom events (per item) for the lead/trail objects tapped
Style:
* It should have a style for when an item is selected (pressedItemCls)
* It should be styled to look like part of a form
* It should support being used inside a fieldset
* It should allow setting a class that gets set for each row. (allows styling items)
- It should be able to be styled to look fine outside of a form
- It should support a style that looks iPhone-ish
future:
- It should support configuring with a component to use
- It should support fields in righthand side
*/
|
JavaScript
| 0 |
@@ -1100,23 +1100,23 @@
ct(menu.
-getEl()
+element
.is('.x-
@@ -1451,23 +1451,23 @@
t(panel.
-getEl()
+element
.select(
@@ -1950,39 +1950,39 @@
eft_src = panel.
-getEl()
+element
.down('.x-menupa
@@ -2042,39 +2042,39 @@
ght_src = panel.
-getEl()
+element
.down('.x-menupa
@@ -2563,39 +2563,39 @@
eft_img = panel.
-getEl()
+element
.down('.x-menupa
@@ -2635,39 +2635,39 @@
ght_img = panel.
-getEl()
+element
.down('.x-menupa
@@ -3294,39 +3294,39 @@
eft_img = panel.
-getEl()
+element
.down('.x-menupa
@@ -3378,15 +3378,15 @@
nel.
-getEl()
+element
.dow
|
2467275032b0e19eb11101eca36e2595e7a60c95
|
Remove value from instance input
|
src/components/login/index.js
|
src/components/login/index.js
|
import React, { Component } from 'react'
import { translate } from 'react-i18next'
import PropTypes from 'prop-types'
import { getInstances } from '../../utils/instances'
class Login extends Component {
constructor (props) {
super(props)
this.handleSubmit = this.handleSubmit.bind(this)
this.state = {
loading : true,
instances : []
}
}
async componentDidMount () {
const instances = await getInstances()
this.setState({
loading: false,
instances
})
}
handleSubmit (e) {
e.preventDefault()
const { onLogin } = this.props
onLogin(new FormData(e.target))
}
render () {
const { t } = this.props
const { loading, instances } = this.state
if (loading) {
return <div>
Loading...
</div>
}
return <form onSubmit={this.handleSubmit}>
<p>
<label htmlFor="username">
{t('username')}
</label>
<input id="username" type="text" name="username" />
</p>
<p>
<label htmlFor="password">
{t('password')}
</label>
<input id="password" type="password" name="password" />
</p>
<p>
<label htmlFor="instance">
{t('instance')}
</label>
<input
name="instance"
list="instances"
value="https://mastodon.social"
/>
<datalist id="instances">
{instances.map((instance, index) => {
return <option key={index}>
{instance}
</option>
})}
</datalist>
</p>
<button type="submit">
{t('submit')}
</button>
</form>
}
}
Login.propTypes = {
onLogin : PropTypes.func.isRequired
}
export default translate()(Login)
|
JavaScript
| 0.000002 |
@@ -1142,22 +1142,17 @@
%09%09%3Cinput
-%0A%09%09%09%09%09
+
name=%22in
@@ -1158,22 +1158,17 @@
nstance%22
-%0A%09%09%09%09%09
+
list=%22in
@@ -1179,50 +1179,9 @@
ces%22
-%0A%09%09%09%09%09value=%22https://mastodon.social%22%0A%09%09%09%09
+
/%3E%0A%09
|
3671375c6e5a12a160dbab8572a49c1fa3f3f6ca
|
Remove secret param from createRouter
|
src/server/routes/createRouter.js
|
src/server/routes/createRouter.js
|
import express from 'express';
import registerHooks from './registerHooks';
import registerMiddleware from './registerMiddleware';
export default function createRouter(hooks, secret) {
const router = express.Router();
registerMiddleware({ router, secret });
registerHooks({ router, hooks });
return router;
}
|
JavaScript
| 0.000001 |
@@ -125,16 +125,103 @@
ware';%0A%0A
+/**%0A * Creates the router%0A * @param %7BArray%7D hooks Hook entries%0A * @return %7BObject%7D%0A */%0A
export d
@@ -254,24 +254,16 @@
er(hooks
-, secret
) %7B%0A
@@ -330,16 +330,8 @@
uter
-, secret
%7D);
|
9a10c2991eb83a6f92f5b454105807196a633f82
|
use switch-case for performance-wise
|
lib/public/js/emoji_generator.js
|
lib/public/js/emoji_generator.js
|
const generateEmoji = (repoLength) => {
if (repoLength >= 100) {
return '💯 👍 😎 👏';
} else if (repoLength >= 75) {
return '👍 😎 👏';
} else if (repoLength >= 50) {
return '👍 😎';
} else if (repoLength >= 20) {
return '👍';
} else if (repoLength > 0) {
return '🙂';
} else if (repoLength === 0) {
return '😪';
}
return '';
};
module.exports = {
generateEmoji
};
|
JavaScript
| 0.000004 |
@@ -38,18 +38,22 @@
%3E %7B%0A
-if
+switch
(repoLe
@@ -60,23 +60,16 @@
ngth
- %3E= 100
) %7B%0A
@@ -68,45 +68,79 @@
- return '%F0%9F%92%AF %F0%9F%91%8D %F0%9F%98%8E %F0%9F%91%8F';%0A %7D else if (
+case repoLength %3E= 100: return '%F0%9F%92%AF %F0%9F%91%8D %F0%9F%98%8E %F0%9F%91%8F';%0A case repoLength %3C 100 &&
repo
@@ -151,27 +151,17 @@
th %3E= 75
-) %7B%0A
+:
return
@@ -169,35 +169,48 @@
%F0%9F%91%8D %F0%9F%98%8E %F0%9F%91%8F';%0A
-%7D else if (
+case repoLength %3C 75 &&
repoLength %3E
@@ -213,27 +213,17 @@
th %3E= 50
-) %7B%0A
+:
return
@@ -229,35 +229,48 @@
'%F0%9F%91%8D %F0%9F%98%8E';%0A
-%7D else if (
+case repoLength %3C 50 &&
repoLength %3E
@@ -273,27 +273,17 @@
th %3E= 20
-) %7B%0A
+:
return
@@ -295,44 +295,47 @@
-%7D else if (repoLength %3E 0) %7B%0A
+case repoLength %3C 20 && repoLength %3E 0:
ret
@@ -351,19 +351,13 @@
-%7D else if (
+case
repo
@@ -372,19 +372,9 @@
== 0
-) %7B%0A
+:
ret
@@ -390,14 +390,16 @@
-%7D%0A%0A
+default:
ret
@@ -406,16 +406,22 @@
urn '';%0A
+ %7D%0A
%7D;%0A%0Amodu
|
30d2f21ea117f69c991b90d3e3a5261d2febe6ea
|
Add listen to all events
|
src/watchfolder.js
|
src/watchfolder.js
|
const chokidar = require("chokidar");
const log = require("./services/logger.service");
const FileIndex = require("./util/fileIndex");
const FileRecognizer = require("./util/fileRecognizer");
const options = require("./util/cmdargs").parseArguments();
const Publisher = require("./amqp/publisher");
const Generator = require("./util/messageGenerator");
const fs = require("fs");
const generator = new Generator(options);
const publisher = new Publisher(options);
const fileindex = new FileIndex(options, new FileRecognizer(options), publisher, generator);
log.success('Watching folder: ' + options.folder);
chokidar.watch(options.folder,
{
ignored: (path) => {
// Ignore sub-folders
return RegExp(options.folder + '.+/').test(path)
},
awaitWriteFinish: {
stabilityThreshold: 2000,
pollInterval: 500
},
usePolling: true,
interval: 500,
binaryInterval: 500,
useFsEvents: true
})
.on('add', (path) => {
log.info('RECEIVED EVENT FOR FILE', path);
fileindex.add_file(path, fileindex.determine_file_type(path, options), options, publisher, generator);
})
.on('raw', (event, path, details) => {
console.log('Raw event info:', event, path, details);
});
|
JavaScript
| 0 |
@@ -1023,59 +1023,8 @@
%3E %7B%0A
- log.info('RECEIVED EVENT FOR FILE', path);%0A
@@ -1150,11 +1150,11 @@
on('
-raw
+all
', (
@@ -1164,25 +1164,16 @@
nt, path
-, details
) =%3E %7B%0A
@@ -1196,46 +1196,34 @@
og('
-Raw event info:', event, path, details
+ALL: ', event, ' - ', path
);%0A
|
ecfb942b21fb9e79e7e24fac82191b9d533cb747
|
call fetchPosts
|
src/components/posts_index.js
|
src/components/posts_index.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchPosts } from '../actions/index';
class PostsIndex extends Component {
componentWillMount() {
console.log('this would be a good time to call an action creator to fetch posts');
}
render() {
return (
<div>List of blog posts</div>
);
}
}
export default PostsIndex;
|
JavaScript
| 0.000003 |
@@ -238,91 +238,30 @@
%09
- console.log('this would be a good time to call an action creator to
+this.props.
fetch
- p
+P
osts
-'
+(
);%0A
@@ -336,23 +336,154 @@
%0A%7D%0A%0A
-export default
+function mapDispatchToProps(dispatch) %7B%0A%09return bindActionCreators(%7B fetchPosts %7D, dispatch);%0A%7D%0A%0Aexport default connect(null, mapDispatchToProps)(
Post
@@ -488,10 +488,11 @@
stsIndex
+)
;%0A
|
b0e2a46c8b7c27b7bed7b9099566d971cbc7f308
|
Fix lint errors for move-services-add-scripts
|
src/server/services/createUser.js
|
src/server/services/createUser.js
|
/*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
const readline = require('readline');
const bcrypt = require('bcryptjs');
const User = require('../models/User');
const log = require('../log');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
function askEmail() {
return new Promise((resolve, reject) => {
rl.question('Email: ', email => {
// See https://stackoverflow.com/a/46181/5116950
// eslint-disable-next-line
const regexEmail = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
if (regexEmail.test(email)) resolve(email);
else reject(email);
});
});
}
function askPassword(email) {
return new Promise(resolve => {
rl.question('Password: ', password => { resolve([email, password]); });
});
}
function terminateReadline(message) {
if (message) log(message);
rl.close();
process.exit(0);
}
(async () => {
let email;
let password;
// If there aren't enough args, go interactive.
let cmd_args = process.argv;
if (cmd_args.length !== 4) {
let emailResult;
try {
emailResult = await askEmail();
} catch (err) {
terminateReadline('Invalid email, no user created');
}
const output = await askPassword(emailResult);
email = output[0];
password = output[1];
} else {
email = cmd_args[2];
password = cmd_args[3];
}
if (password.length < 8) {
terminateReadline('Password must be at least eight characters, no user created');
}
const admin = new User(undefined, email, bcrypt.hashSync(password, 10));
try {
await admin.insert();
terminateReadline('User created');
} catch (err) {
terminateReadline('User already exists, no additional user created');
}
})();
|
JavaScript
| 0.000067 |
@@ -1225,17 +1225,18 @@
e.%0A%09
-le
+cons
t cmd
-_a
+A
rgs
@@ -1259,18 +1259,17 @@
%09if (cmd
-_a
+A
rgs.leng
@@ -1533,26 +1533,25 @@
%09email = cmd
-_a
+A
rgs%5B2%5D;%0A%09%09pa
@@ -1566,10 +1566,9 @@
cmd
-_a
+A
rgs%5B
|
3f743bf1b9c6d3609c84ec164bdb6bcce9410ecf
|
return the prev page attribute
|
src/models/model.js
|
src/models/model.js
|
'use strict';
import { debug } from './../logger';
import { DynamoDB } from 'aws-sdk';
import Joi from 'joi';
const dynamoConfig = {
region: process.env.AWS_REGION || 'us-east-1'
};
const db = new DynamoDB.DocumentClient(dynamoConfig);
class Model {
static save(item) {
debug('= Model.save', item);
const itemParams = {
TableName: this.tableName,
Item: item,
ReturnValues: 'ALL_OLD'
};
return this._client('put', itemParams);
}
static saveAll(items) {
debug('= Model.saveAll', items);
const itemsParams = {RequestItems: {}};
itemsParams.RequestItems[this.tableName] = items.map(item => {
return {PutRequest: {Item: item}};
});
return this._client('batchWrite', itemsParams);
}
static get(hash, range, options = {}) {
return new Promise((resolve, reject) => {
debug('= Model.get', hash, range);
const params = {
TableName: this.tableName,
Key: this._buildKey(hash, range)
};
if (options.attributes) {
const attributesMapping = options.attributes.reduce((acumm, attrName, i) => {
acumm[`#${attrName}`] = attrName;
return acumm;
}, {});
params.ExpressionAttributeNames = attributesMapping
params.ProjectionExpression = Object.keys(attributesMapping).join(',');
}
this._client('get', params).then(result => {
if (result.Item) {
resolve(result.Item);
} else {
resolve({});
}
})
.catch(err => reject(err));
});
}
static update(params, hash, range) {
return new Promise((resolve, reject) => {
debug('= Model.update', hash, range, JSON.stringify(params));
const dbParams = {
TableName: this.tableName,
Key: this._buildKey(hash, range),
AttributeUpdates: this._buildAttributeUpdates(params),
ReturnValues: 'ALL_NEW'
};
this._client('update', dbParams).then(result => resolve(result.Attributes))
.catch(err => reject(err));
});
}
static delete(hash, range) {
return new Promise((resolve, reject) => {
debug('= Model.delete', hash);
const params = {
TableName: this.tableName,
Key: this._buildKey(hash, range)
};
this._client('delete', params).then(() => resolve(true))
.catch(err => reject(err));
});
}
static allBy(key, value, options = {}) {
return new Promise((resolve, reject) => {
debug('= Model.allBy', key, value);
const params = {
TableName: this.tableName,
KeyConditionExpression: '#hkey = :hvalue',
ExpressionAttributeNames: {'#hkey': key},
ExpressionAttributeValues: {':hvalue': value}
};
if (options.limit) {
params.Limit = options.limit;
}
if (options.nextPage) {
params.ExclusiveStartKey = this.lastEvaluatedKey(options.nextPage);
}
this._client('query', params).then((result) => {
if (result.LastEvaluatedKey) {
resolve({
items: result.Items,
nextPage: this.nextPage(result.LastEvaluatedKey)
});
} else {
resolve({items: result.Items});
}
})
.catch(err => reject(err));
});
}
static countBy(key, value) {
return new Promise((resolve, reject) => {
debug('= Model.allBy', key, value);
const params = {
TableName: this.tableName,
KeyConditionExpression: '#hkey = :hvalue',
ExpressionAttributeNames: {'#hkey': key},
ExpressionAttributeValues: {':hvalue': value},
Select: 'COUNT'
};
this._client('query', params).then((result) => {
resolve(result.Count);
})
.catch(err => reject(err));
});
}
static increment(attribute, count, hash, range) {
debug('= Model.increment', hash, range, attribute, count);
const params = {
TableName: this.tableName,
Key: this._buildKey(hash, range),
AttributeUpdates: {}
};
params.AttributeUpdates[attribute] = {
Action: 'ADD',
Value: count
};
return this._client('update', params);
}
static nextPage(lastEvaluatedKey) {
return new Buffer(JSON.stringify(lastEvaluatedKey)).toString('base64');
}
static lastEvaluatedKey(nextPage) {
return JSON.parse(new Buffer(nextPage, 'base64').toString('utf-8'));
}
static get tableName() {
return null;
}
static get hashKey() {
return 'id';
}
static get rangeKey() {
return null;
}
static get maxRetries() {
return 10;
}
static get retryDelay() {
return 50;
}
static get schema() {
return null;
}
static isValid(object) {
debug('= Model.isValid');
return this._validateSchema(this.schema, object);
}
static _validateSchema(schema, campaign) {
if (!this.schema) return true;
const result = Joi.validate(campaign, schema);
return !result.error;
}
static _buildKey(hash, range) {
let key = {};
key[this.hashKey] = hash;
if (this.rangeKey) {
key[this.rangeKey] = range;
}
return key;
}
static _buildAttributeUpdates(params) {
let attrUpdates = {};
for (let key in params) {
if (key !== this.hashKey && key !== this.rangeKey) {
attrUpdates[key] = {
Action: 'PUT',
Value: params[key]
};
}
}
return attrUpdates;
}
static _client(method, params, retries = 0) {
return new Promise((resolve, reject) => {
debug('Model._client', JSON.stringify(params));
this._db()[method](params, (err, data) => {
if (err) {
debug('= Model._client', method, 'Error', err);
reject(err);
} else {
debug('= Model._client', method, 'Success');
if (data.UnprocessedItems && Object.keys(data.UnprocessedItems).length > 0 && retries < this.maxRetries) {
debug('= Model._client', method, 'Some unprocessed items... Retrying', JSON.stringify(data));
const retryParams = {RequestItems: data.UnprocessedItems};
const delay = this.retryDelay * Math.pow(2, retries);
setTimeout(() => {
resolve(this._client(method, retryParams, retries + 1));
}, delay);
} else {
debug('= Model._client', method, 'resolving', JSON.stringify(data));
resolve(data);
}
}
});
});
}
static _db() {
return db;
}
}
module.exports.Model = Model;
|
JavaScript
| 0.000019 |
@@ -3056,16 +3056,56 @@
.Items,%0A
+ prevPage: options.nextPage,%0A
@@ -3207,16 +3207,29 @@
esolve(%7B
+%0A
items: r
@@ -3239,16 +3239,67 @@
lt.Items
+,%0A prevPage: options.nextPage%0A
%7D);%0A
|
b2a4c1d3e58717f9fb5972067cc03ada12551205
|
remove alt
|
src/templates/result-template.js
|
src/templates/result-template.js
|
import React, { Fragment } from 'react'
import Helmet from 'react-helmet'
import { ResultPage, SEO } from 'Components'
const ResultTemplate = ({ data }) => {
const results = data.results.edges
const definitions = data.definitions.edges
const {
seotitle,
seodescription,
seokeywords,
seoimage
} = data.result.data
return (
<Fragment>
<SEO
uid={data.result.uid}
title={seotitle}
description={seodescription}
keywords={seokeywords}
image={seoimage.url}
/>
<ResultPage data={data.result} {...{results}} {...{definitions}}/>
</Fragment>
)
}
export default ResultTemplate
export const query = graphql`
query ResultTemplateQuery($slug: String!) {
result: prismicDocument(uid: {eq: $slug}) {
uid
data {
seotitle
seodescription
seokeywords
seoimage {
url
}
title {
text
}
quote {
text
}
image {
url
}
body {
slice_type
primary {
sectiontype
anchor
sectionname
header {
type
text
}
}
items {
header {
type
text
}
sectionimage {
url
alt
copyright
}
text {
type
text
spans {
type
start
end
data {
url
uid
}
}
}
list {
type
text
}
row {
type
text
}
}
}
}
}
results: allPrismicDocument(filter: {type: {eq: "result"}}) {
edges {
node {
uid
data {
title {
text
}
}
}
}
}
definitions: allPrismicDocument(filter: {type: {eq: "definition"}}) {
edges {
node {
uid
data {
title {
type
text
}
definition {
type
text
spans {
type
start
end
}
}
}
}
}
}
}
`
|
JavaScript
| 0.000004 |
@@ -1379,26 +1379,8 @@
url%0A
- alt%0A
|
c5d07f81fb83e46ac0149a2a57a411b216e96416
|
Add early return
|
lib/publishPluginReleaseEvent.js
|
lib/publishPluginReleaseEvent.js
|
const axios = require('axios');
const Program = require('commander');
const Chalk = require('chalk');
/**
* Create a release event object from a pluginInfo object.
*
* @param {Object} pluginInfo
* @return {Object}
*/
function getReleaseEventInfo(pluginInfo) {
return {
pluginName: pluginInfo.getName(),
pluginVersion: pluginInfo.getCurrentVersion(),
pluginLabel: {
de: pluginInfo.getLabel('de'),
en: pluginInfo.getLabel('en'),
},
pluginChangelog: {
de: pluginInfo.getChangelog('de', null),
en: pluginInfo.getChangelog('en', null),
},
};
}
/**
* If set call the release event endpoint.
*
* @param {Object} pluginInfo
* @return {Boolean}
*/
module.exports = async (pluginInfo) => {
if (Program.releaseEventURL) {
try {
await axios.post(Program.releaseEventURL, getReleaseEventInfo(pluginInfo));
console.log(Chalk.green.bold('Publish release event succeeded'));
} catch (err) {
console.log(Chalk.red.bold(`Publish release event failed: ${err.message}`));
}
}
return true;
};
|
JavaScript
| 0.000075 |
@@ -797,16 +797,17 @@
if (
+!
Program.
@@ -837,18 +837,32 @@
+return;%0A %7D%0A
try %7B%0A
-
@@ -937,28 +937,24 @@
uginInfo));%0A
-
cons
@@ -1011,28 +1011,24 @@
cceeded'));%0A
-
%7D catch
@@ -1039,28 +1039,24 @@
) %7B%0A
-
-
console.log(
@@ -1128,37 +1128,9 @@
- %7D%0A %7D%0A%0A return true;
+%7D
%0A%7D;%0A
|
184a3cd20556812dff60e04a67d050b2f89c8c70
|
Fix Export to Excel Fix #18
|
grails-app/assets/javascripts/angular/directives.js
|
grails-app/assets/javascripts/angular/directives.js
|
'use strict';
/* Directives */
angular.module('loki.directives', ["loki.services"])
/**
* dummy directive
*/
.directive("dummyDirective", ["$injector", "$log", function($injector, $log) {
return {
// require: "ngModel",
restrict: "A",
// transclude: true,
link: function(scope, element, attrs) {
$log.debug("log", scope, element, attrs);
}
}
}])
// Generate a Excel with the model information
.directive("lokiExport", [function() {
// Abstraction to create a Workbook
var Workbook = function() { this.Sheets = {}, this.SheetNames = []; }
Workbook.prototype.addSheet = function( name, worksheet ) {
this.Sheets[name] = worksheet;
this.SheetNames.push(name);
}
Workbook.prototype.save = function(filename) {
function s2ab(s) {
var buf = new ArrayBuffer(s.length);
var view = new Uint8Array(buf);
for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
return buf;
}
var wbout = XLSX.write(this, {bookType:'xlsx', bookSST:true, type: 'binary'});
saveAs(new Blob([s2ab(wbout)],{type:"application/octet-stream"}), filename);
}
// Abstraction to create a Worksheet
var Worksheet = function() { }
Worksheet.prototype.setCell = function( ref, value ) {
this[ref] = { v: value, t: "s" }
if(typeof value == "number") this[ref].t = "n"
}
function generateWorkbook(data) {
// Create a workbook with a worksheet
var workbook = new Workbook();
var worksheet = new Worksheet();
workbook.addSheet("Sheet1", worksheet);
// Set spreadsheet headers
worksheet.setCell( "A1", "Fecha" );
worksheet.setCell( "B1", "Horas" );
worksheet.setCell( "C1", "Usuario" );
worksheet.setCell( "D1", "Id Proyecto" );
worksheet.setCell( "E1", "Nombre Proyecto" );
// Send other Rows
for(var row = 0; row < data.length; row++ ) {
worksheet.setCell( "A" + (row+2), data[row].date );
worksheet.setCell( "B" + (row+2), data[row].hours );
worksheet.setCell( "C" + (row+2), data[row].username )
worksheet.setCell( "D" + (row+2), data[row].project.id )
worksheet.setCell( "E" + (row+2), data[row].project.name )
}
// Set spreedsheet range
worksheet["!ref"] = "A1:E" + (data.length+1);
// Download excel file
workbook.save("test.xlsx");
}
function linkFunction(scope, element, attrs) {
element.click(function() {
generateWorkbook(scope.lokiExport)
})
};
return {
scope: { lokiExport: "=" },
link: linkFunction
}
}])
;
|
JavaScript
| 0 |
@@ -1257,16 +1257,71 @@
ion() %7B
+this.UNEXPLICABLE_EXCEL_EPOCH = moment(%5B1899, 11, 30%5D);
%7D%0A W
@@ -1466,16 +1466,199 @@
t = %22n%22%0A
+ else if(typeof value == %22object%22) %7B%0A this%5Bref%5D.t = %22n%22;%0A this%5Bref%5D.v = value.diff(this.UNEXPLICABLE_EXCEL_EPOCH, %22days%22)%0A this%5Bref%5D.z = 'd-mmm-yy';%0A %7D%0A
%7D%0A%0A
|
bffdd3255081313c0b7a4a3c271b2a5c4964185b
|
Use promises for flatter code
|
src/models/users.js
|
src/models/users.js
|
import mongoose from 'mongoose'
import bcrypt from 'bcrypt'
const User = new mongoose.Schema({
type: { type: String, default: 'User' },
name: { type: String },
username: { type: String, required: true, unique: true },
password: { type: String, required: true },
salt: { type: String }
})
User.pre('save', function(next) {
const user = this
if(!user.isModified('password')) {
return next()
}
bcrypt.genSalt(10, (err, salt) => {
if(err) { return next(err) }
bcrypt.hash(user.password, salt, (err, hash) => {
if(err) { return next(err) }
user.password = hash
user.salt = salt
next()
})
})
})
User.methods.validatePassword = function(password) {
const user = this
return new Promise((resolve, reject) => {
bcrypt.compare(password, user.password, (err, isMatch) => {
if(err) { return reject(err) }
resolve(isMatch)
});
})
};
export default mongoose.model('user', User)
|
JavaScript
| 0 |
@@ -318,16 +318,24 @@
function
+ preSave
(next) %7B
@@ -360,16 +360,17 @@
is%0A%0A if
+
(!user.i
@@ -417,16 +417,55 @@
()%0A %7D%0A%0A
+ new Promise((resolve, reject) =%3E %7B%0A
bcrypt
@@ -494,26 +494,29 @@
t) =%3E %7B%0A
+
if
+
(err) %7B retu
@@ -510,35 +510,37 @@
(err) %7B return
-nex
+rejec
t(err) %7D%0A%0A bc
@@ -528,24 +528,71 @@
ject(err) %7D%0A
+ return salt%0A %7D)%0A %7D)%0A .then(salt =%3E %7B
%0A bcrypt.
@@ -638,32 +638,33 @@
%3E %7B%0A if
+
(err) %7B
return next(
@@ -651,27 +651,31 @@
(err) %7B
-return next
+throw new Error
(err) %7D%0A
@@ -735,20 +735,57 @@
-next()%0A %7D
+return user%0A %7D)%0A %7D)%0A .then(() =%3E %7B%0A next(
)%0A
@@ -831,16 +831,33 @@
function
+ validatePassword
(passwor
@@ -998,16 +998,17 @@
if
+
(err) %7B
@@ -1062,17 +1062,15 @@
%7D)
-;
%0A %7D)%0A%7D
-;
%0A%0Aex
|
1107e690ea4f119d072e6744433280d4862235c6
|
Use equality test and uppercase constants
|
lib/node_modules/@stdlib/math/base/utils/float32-exponent/test/test.js
|
lib/node_modules/@stdlib/math/base/utils/float32-exponent/test/test.js
|
'use strict';
// MODULES //
var tape = require( 'tape' );
var pinf = require( '@stdlib/math/constants/float32-pinf' );
var ninf = require( '@stdlib/math/constants/float32-ninf' );
var round = require( '@stdlib/math/base/special/round' );
var pow = require( '@stdlib/math/base/special/pow' );
var toFloat32 = require( '@stdlib/math/base/utils/float64-to-float32' );
var bits = require( '@stdlib/math/base/utils/float32-to-binary-string' );
var exponent = require( './../lib' );
// VARIABLES //
var BIAS = 127;
// TESTS //
tape( 'main export is a function', function test( t ) {
t.ok( true, __filename );
t.ok( typeof exponent === 'function', 'main export is a function' );
t.end();
});
tape( 'the function returns a number', function test( t ) {
t.equal( typeof exponent( toFloat32( 3.14e30 ) ), 'number', 'returns a number' );
t.end();
});
tape( 'the function returns an integer corresponding to the unbiased exponent of a single-precision floating-point number', function test( t ) {
var expected;
var actual;
var sign;
var frac;
var exp;
var x;
var b;
var i;
for ( i = 0; i < 5e3; i++ ) {
if ( Math.random() < 0.5 ) {
sign = -1;
} else {
sign = 1;
}
frac = Math.random() * 10;
exp = round( Math.random()*44 ) - 22;
x = sign * frac * pow( 10, exp );
x = toFloat32( x );
b = bits( x );
expected = parseInt( b.substring( 1, 9 ), 2 ) - BIAS;
actual = exponent( x );
t.equal( actual, expected, 'returns the unbiased exponent for ' + x );
}
t.end();
});
tape( 'the function returns the unbiased exponent for `+-0`', function test( t ) {
t.equal( exponent( 0 ), -BIAS, 'returns -127' );
t.equal( exponent( -0 ), -BIAS, 'returns -127' );
t.end();
});
tape( 'the function returns the unbiased exponent for `+infinity`', function test( t ) {
t.equal( exponent( pinf ), BIAS+1, 'returns 128' );
t.end();
});
tape( 'the function returns the unbiased exponent for `-infinity`', function test( t ) {
t.equal( exponent( ninf ), BIAS+1, 'returns 128' );
t.end();
});
tape( 'the function returns the unbiased exponent for `NaN`', function test( t ) {
t.equal( exponent( NaN ), BIAS+1, 'returns 128' );
t.end();
});
tape( 'the function returns the unbiased exponent for subnormals', function test( t ) {
t.equal( exponent( toFloat32( 3.14e-42 ) ), -BIAS, 'returns -127' );
t.end();
});
|
JavaScript
| 0.000067 |
@@ -57,20 +57,20 @@
);%0Avar
-pinf
+PINF
= requi
@@ -118,20 +118,20 @@
);%0Avar
-ninf
+NINF
= requi
@@ -506,16 +506,35 @@
S = 127;
+ // FIXME: constant
%0A%0A%0A// TE
@@ -627,18 +627,21 @@
e );%0A%09t.
-ok
+equal
( typeof
@@ -653,12 +653,9 @@
nent
- ===
+,
'fu
@@ -1829,20 +1829,20 @@
ponent(
-pinf
+PINF
), BIAS
@@ -1986,20 +1986,20 @@
ponent(
-ninf
+NINF
), BIAS
|
5117aef37715e3995700ffcd6eabd98bcf8c6aa6
|
Update collection for Document Conversion GA
|
client/read/read.controller.js
|
client/read/read.controller.js
|
angular.module('read-and-learn').controller('readController', function ($scope, $rootScope, $http, Upload, $timeout) {
$scope.documents = null;
var cluster_id = 'scf9b13b48_1835_48cf_ac7f_143b7bb8712b';
var config_id = 'example-config';
var collection_id = 'example-collection3';
getAllDocuments();
$scope.read = function(file) {
$scope.documents = null;
if (file)
$scope.file = 'data/' + file;
else
$scope.file = 'data/samplePDF.pdf';
// Call API to convert documents into normalized sets of answer units
$http({
method: 'POST',
url: '/api/document-conversion',
data: { 'file': $scope.file }
}).then(function successCallback(response) {
var author = getDocumentAuthor(response.data.metadata);
var answersToConvert = response.data.answer_units.length;
var answersConverted = 0;
for (var i = 0; i < response.data.answer_units.length; i++) {
var doc = {};
doc.id = author + ' ' + $scope.file + (i + 1); // TODO Improve solution to check if document is already readed
doc.author = author;
doc.bibliography = $scope.file;
doc.title = response.data.answer_units[i].title;
doc.body = response.data.answer_units[i].content[0].text;
// Add documents to a collection
$http({
method: 'POST',
url: '/api/retrieve-and-rank/'+cluster_id+'/'+config_id+'/'+collection_id,
data: {
'data': doc
}
}).then(function successCallback(response) {
answersConverted++;
if (answersConverted === answersToConvert)
getAllDocuments();
}, function errorCallback(response) {
// TODO Treat error
getAllDocuments();
});
}
}, function errorCallback(response) {
// TODO Treat error
getAllDocuments();
});
};
$scope.upload = function(files, errFiles) {
$scope.files = files;
$scope.errFiles = errFiles;
angular.forEach(files, function(file) {
file.upload = Upload.upload({
url: '/api/upload',
data: {
file: file
}
});
file.upload.then(function successCallback(response) {
$timeout(function () {
file.result = response.data;
// Convert document
$scope.read(response.config.data.file.name);
});
}, function errorCallback(response) {
if (response.status > 0)
$scope.errorMsg = response.status + ': ' + response.data;
}, function (evt) {
file.progress = Math.min(100, parseInt(100.0 * evt.loaded / evt.total));
});
});
};
function getAllDocuments() {
$http({
method: 'GET',
url: '/api/retrieve-and-rank/'+cluster_id+'/'+config_id+'/'+collection_id+'/documents'
}).then(function successCallback(response) {
if (response.data.docs.length > 0)
$scope.documents = [];
$scope.answers = 0;
// Count distinct documents
var currentDoc = null;
for (var i = 0; i < response.data.docs.length; i++) {
if (response.data.docs[i].bibliography[0] !== currentDoc) {
var doc = {
"id" : response.data.docs[i].id[0],
"author" : (response.data.docs[i].author) ? response.data.docs[i].author[0] : '',
"bibliography" : (response.data.docs[i].bibliography) ? response.data.docs[i].bibliography[0] : '',
"title" : (response.data.docs[i].title) ? response.data.docs[i].title[0] : '',
"body" : (response.data.docs[i].body) ? response.data.docs[i].body[0] : ''
};
$scope.documents.push(doc);
currentDoc = doc.bibliography;
}
}
// Count answer units
$scope.answers = response.data.numFound;
}, function errorCallback(response) {
// TODO Treat error
});
}
/**
* Find author information in document metadata
* @param {Object} metadata Metadata array
* @return {String} Author name
*
* @author [email protected]
* @since 2015-12-16
* @version 0.1.0
*/
function getDocumentAuthor(metadata) {
console.log(metadata);
if (metadata) {
for (var i = 0; i < metadata.length; i++) {
if (metadata[i].name === 'author')
return metadata[i].content;
return '';
}
}
return '';
}
});
|
JavaScript
| 0 |
@@ -261,23 +261,34 @@
n_id = '
-example
+read-and-learn-dev
-collect
@@ -290,17 +290,16 @@
llection
-3
';%0A%0A ge
@@ -4179,35 +4179,8 @@
) %7B%0A
- console.log(metadata);%0A
|
eda07f87ff3310ae378957e6ac7125741934c7a7
|
fix de-freifunk
|
i18n.js
|
i18n.js
|
var translations = {
'de-freifunk': {
'tr-introduction': 'Erst mit der Freifunk-Firmware wird dein Router zu einem Teil des Freifunk-Netzes. Sie ist fertig vorkonfiguriert, um Kontakt mit benachbarten Freifunk-Knoten aufzunehmen, ein offenes und anonymes Freifunk-WLAN auszusenden und dich dabei vor der Störerhaftung zu schützen.',
'tr-introduction-additional': 'Bitte verwende das <em>Erstinstallationsimage</em>, wenn Du deinen Router gerade erst gekauft hast und sich darauf noch keine Freifunk-/LEDE-/OpenWRT-Firmware befindet. Ist bereits eine Freifunk- oder LEDE-/OpenWRT-Firmware installiert, verwende bitte die mit <em>Upgrade</em> bezeichnete Version.',
'tr-different-versions': 'Diese Freifunk-Firmware bieten wir in verschiedenen Versionen an:',
},
'de': {
'tr-list-files': 'Liste aller Dateien',
'tr-loading': 'Bitte warten...',
'tr-show-table': 'Tabelle anzeigen',
'tr-select-firmware': 'Wähle deine Firmware',
'tr-introduction': 'Die Firmware installiert ein Linux-basiertes Betriebsystem auf den Router. Darauf kann verschiedene Software installiert werden.',
'tr-introduction-additional': 'Bitte verwende das <em>Erstinstallationsimage</em>, wenn Du deinen Router gerade erst gekauft hast und sich darauf noch keine LEDE-/OpenWRT-Firmware befindet. Ist bereits eine LEDE- oder OpenWRT-Firmware installiert, verwende bitte die mit <em>Upgrade</em> bezeichnete Version.',
'tr-different-versions': 'Diese Firmware bieten wir in verschiedenen Versionen an:',
'tr-experimental-warning': 'Vorsicht! Unsere experimentelle Firmware wurde <b>nicht</b> getestet und kann dein Gerät jederzeit und unangekündigt in einen Zustand versetzen, in dem du nur mit einem Lötkolben und dem Öffnen des Gehäuses weiter kommst. Verwende diese Version nur, wenn Du Dir darüber im Klaren bist!',
'tr-back-to-selection': 'Zurück zum Auswahlmenü',
'tr-list-files': 'Liste aller Dateien',
'tr-firmware': 'Firmware',
'tr-recommendation': 'Empfehlung',
'tr-stable-desciption': 'Gut getestet, zuverlässig und stabil.',
'tr-beta-desciption': 'Vorabtests neuer Stable-Kandidaten.',
'tr-experimental-desciption': 'Ungetestet, automatisch generiert.',
'tr-available-versions': 'Für das gewählte Routermodell sind folgende Versionen vorhanden:',
'tr-selection-consequences': 'Die Auswahl der passenden Version entscheidet über die Stablität des Routers und den potentiell anfallenden Wartungsaufwand.',
'tr-manufacturer': 'Hersteller',
'tr-model': 'Modell',
'tr-first-installation': 'Erstinstallation',
'tr-upgrade': 'Upgrade',
'tr-generic-error': 'Da ist was schiefgelaufen. Frage doch bitte einmal im Chat nach.',
'tr-select-manufacturer': '-- Hersteller wählen --',
'tr-select-model': '-- Modell wählen --',
'tr-select-revision': '-- Hardwarerevision wählen --',
'tr-factory': 'Erstinstallation',
'tr-sysupgrade': 'Upgrade',
'tr-rootfs': 'Root-Image',
'tr-kernel': 'Kernel-Image',
'tr-download-experimental': 'Download für Experimentierfreudige',
'tr-all': 'alle'
},
'en': {
'tr-list-files': 'List all files',
'tr-loading': 'Loading...',
'tr-show-table': 'Show table',
'tr-select-firmware': 'Select your image',
'tr-introduction': 'The firmware puts a Linux based operating system on your device. It allows you to install additional software.',
'tr-introduction-additional': 'If you have just bought the device, please choose the <em>first installation</em> image. If you have already installed LEDE/OpenWRT, use the <em>upgrade</em> images.',
'tr-different-versions': 'This firmware is available in different versions:',
'tr-experimental-warning': 'Attention! The following images were <b>not</b> tested und might cause your device to put it in state that might need soldering. Please use this version only if you know what you do!',
'tr-back-to-selection': 'Back to selection',
'tr-list-files': 'List all files',
'tr-firmware': 'Firmware',
'tr-recommendation': 'Recommendation',
'tr-stable-desciption': 'Well tested, reliable and stable.',
'tr-beta-desciption': 'Testing candidates for the next stable release.',
'tr-experimental-desciption': 'Untested, build automatically.',
'tr-available-versions': 'For the selected router model, the following router versions are available:',
'tr-selection-consequences': 'The selection of the model decides how stable the version will be and decides the potential maintenance requirements.',
'tr-manufacturer': 'Manufacturer',
'tr-model': 'Model',
'tr-first-installation': 'First installation',
'tr-upgrade': 'Upgrade',
'tr-select-manufacturer': '-- Select manufacturer --',
'tr-select-model': '-- Select model --',
'tr-select-revision': '-- Select revision --',
'tr-factory': 'First installation',
'tr-sysupgrade': 'Upgrade',
'tr-rootfs': 'Root-Image',
'tr-kernel': 'Kernel-Image',
'tr-download-experimental': 'Download for testers',
'tr-all': 'all'
}
}
// Complement translations based on other translations
translations['de-freifunk'] = Object.assign({}, translations['de-freifunk'], translations['de']);
|
JavaScript
| 0.000004 |
@@ -5162,25 +5162,16 @@
ions%5B'de
--freifunk
'%5D, tran
@@ -5182,13 +5182,22 @@
ions%5B'de
+-freifunk
'%5D);%0A
|
ee4bfb112e130e57fa23f92868458164d5d58797
|
Update debug text
|
lib/node_modules/@stdlib/plot/axis/lib/engines/svg/components/index.js
|
lib/node_modules/@stdlib/plot/axis/lib/engines/svg/components/index.js
|
'use strict';
// MODULES //
var debug = require( 'debug' )( 'axis:engine:components:main' );
var h = require( 'virtual-dom/h' );
var domain = require( './domain.js' );
var ticks = require( './ticks.js' );
// AXIS //
/**
* Axis component returned as a virtual DOM tree.
*
* @private
* @param {Object} ctx - context
* @returns {VTree} virtual tree
*/
function axis( ctx ) {
var children;
var opts;
opts = {
'namespace': 'http://www.w3.org/2000/svg',
'property': 'axis',
'className': 'axis',
'attributes': {
'fill': 'none',
'font-size': 10, // TODO: option
'font-family': 'sans-serif', // TODO: option
'text-anchor': ctx.textAnchor()
}
};
debug( 'Generating a virtual DOM node with following options: %s.', JSON.stringify( opts ) );
debug( 'Creating tick marks...' );
children = ticks( ctx );
debug( 'Adding a domain line...' );
children.unshift( domain( ctx ) );
return h( 'g', opts, children );
} // end FUNCTION axis()
// EXPORTS //
module.exports = axis;
|
JavaScript
| 0.000003 |
@@ -833,11 +833,13 @@
g( '
-Add
+Creat
ing
|
1e0ed7ee17a2a96919a6f3a9183fa5350c981739
|
Fix copy-throttling bug
|
lib/services/throttler-stream.js
|
lib/services/throttler-stream.js
|
'use strict';
const { Transform } = require('stream');
module.exports = class Throttler extends Transform {
constructor (pgstream, ...args) {
super(...args);
this.pgstream = pgstream;
this.sampleLength = global.settings.copy_from_maximum_slow_input_speed_interval || 15;
this.minimunBytesPerSecondThershold = global.settings.copy_from_minimum_input_speed || 0;
this.byteCount = 0;
this.bytesPerSecondHistory = [];
this._interval = setInterval(this._updateMetrics.bind(this), 1000);
}
_updateMetrics () {
this.bytesPerSecondHistory.push(this.byteCount);
this.byteCount = 0;
if (this.bytesPerSecondHistory > this.sampleLength) {
this.bytesPerSecondHistory.shift();
}
const doesNotReachThreshold = [];
for (const bytesPerSecond of this.bytesPerSecondHistory) {
if (bytesPerSecond <= this.minimunBytesPerSecondThershold) {
doesNotReachThreshold.push(true);
}
}
if (doesNotReachThreshold.length >= this.sampleLength) {
clearInterval(this._interval);
this.pgstream.emit('error', new Error('Connection closed by server: input data too slow'));
}
}
_transform (chunk, encoding, callback) {
this.byteCount += chunk.length;
callback(null, chunk);
}
_flush (callback) {
clearInterval(this._interval);
callback();
}
};
|
JavaScript
| 0.000001 |
@@ -695,16 +695,23 @@
dHistory
+.length
%3E this.
|
bd50cde426d847b554998e78f857f9a448f6f1c4
|
check cache firstly for blocker,improve the performance
|
jqc-blocker/jqc.blocker.js
|
jqc-blocker/jqc.blocker.js
|
/*
Copyright 2017 cmanlh
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.
*/
/**
* ui blocker
*
* Dependent on
* + jqc.baseElement.js
* + jqc.zindex.js
*/
(function ($) {
if (undefined == $.jqcBaseElement || undefined == $.jqcZindex) {
throw new Error("Need library : jqc.baseElement.js,jqc.zindex.js");
}
const BLOCKER_CACHE = [];
$.jqcBlocker = function (param) {
if (arguments.length > 0) {
$.jqcBaseElement.apply(this, arguments);
}
var that = BLOCKER_CACHE.pop();
if (that) {
return that;
}
that = this;
that.ui = $("<div style='display:none;position:absolute;background-color:#777777;opacity: 0.1;filter: alpha(opacity=10);top:0px;left:0px;'>");
$(window).on('resize.jqcBlocker', function (e) {
that.resize();
});
$('body').append(that.ui);
};
$.jqcBlocker.prototype = new $.jqcBaseElement();
$.jqcBlocker.prototype.constructor = $.jqcBlocker;
$.jqcBlocker.prototype.resize = function () {
var that = this;
that.ui.width(window.innerWidth);
that.ui.height(window.innerHeight);
};
$.jqcBlocker.prototype.show = function () {
var that = this;
that.zidex = $.jqcZindex.popupMgr.fetchIndex();
that.ui.css('z-index', that.zidex);
that.resize();
that.ui.show();
}
$.jqcBlocker.prototype.close = function () {
var that = this;
that.ui.hide();
$.jqcZindex.popupMgr.returnIndex(that.zidex);
BLOCKER_CACHE.push(that);
};
}(jQuery));
|
JavaScript
| 0 |
@@ -911,96 +911,67 @@
-if (arguments.length %3E 0) %7B%0A $.jqcBaseElement.apply(this, arguments);
+var that = BLOCKER_CACHE.pop();%0A if (that) %7B
%0A
%7D%0A%0A
@@ -970,95 +970,124 @@
- %7D%0A%0A
- var that = BLOCKER_CACHE.pop();%0A if (that) %7B%0A return that
+return that;%0A %7D%0A%0A if (arguments.length %3E 0) %7B%0A $.jqcBaseElement.apply(this, arguments)
;%0A
|
06ec07f55641de903a64ae915762064fb3016d26
|
Fix typo in error message
|
lib/solder/compressor/closure.js
|
lib/solder/compressor/closure.js
|
/*global exports: true, require: true */
/*jslint onevar: true, undef: true, nomen: true, eqeqeq: true, bitwise: true, newcap: true, immed: true */
var path = require('path'),
compressor = require('solder/compressor');
function Closure(type, options) {
this.type = type;
this.options = options;
this.args = options.args;
if (this.type !== 'js') {
throw new Error('Closure Compiler only supports JavaScrtipt');
}
if (!options.jar) {
throw new Error('Closure Compiler jar file not specified');
}
path.exists(options.jar, function (exists) {
if (!exists) {
throw new Error('Closure Compiler jar file not found: ' + options.jar);
}
});
}
Closure.prototype = compressor.createCompressor();
Closure.prototype.compress = function (input, callback) {
var command = 'java -jar {jar} --js {input} --js_output_file {output}';
this.compressFS(command, input, callback);
};
// -- Exports ----------------------------------------------------------------
exports.create = function (type, options) {
return new Closure(type, options);
};
|
JavaScript
| 0.001375 |
@@ -420,17 +420,16 @@
JavaScr
-t
ipt');%0A
|
01de0fca8c10b4fcf936f54395b495a736513008
|
Throw an error if we attempt to modify a different version of Leaflet.
|
public/js/patches.js
|
public/js/patches.js
|
// Modify Draggable to ignore shift key.
L.Draggable.prototype._onDown = function(e) {
this._moved = false;
if ((e.which !== 1) && (e.button !== 1) && !e.touches) { return; }
L.DomEvent.stopPropagation(e);
if (L.Draggable._disabled) { return; }
L.DomUtil.disableImageDrag();
L.DomUtil.disableTextSelection();
if (this._moving) { return; }
var first = e.touches ? e.touches[0] : e;
this._startPoint = new L.Point(first.clientX, first.clientY);
this._startPos = this._newPos = L.DomUtil.getPosition(this._element);
L.DomEvent
.on(document, L.Draggable.MOVE[e.type], this._onMove, this)
.on(document, L.Draggable.END[e.type], this._onUp, this);
};
|
JavaScript
| 0 |
@@ -1,8 +1,193 @@
+// Make sure we're modifying the correct version of Leaflet%0Aif (L.version !== '0.7.2') %7B%0A throw new Error('Attempting to patch Leaflet ' + L.version + '. Only 0.7.2 is supported');%0A%7D%0A%0A
// Modif
|
fe98be609d6755f2b41135b74c138e6fa0af4020
|
Fix ever changing Hamburk order of menu sections
|
service/scrapper/lokal-hamburk.js
|
service/scrapper/lokal-hamburk.js
|
'use strict'
let _ = require('lodash')
let xray = require('x-ray')
let moment = require('moment')
let helpers = require('../helpers')
module.exports = () => {
let x = xray()
let getItem = (lunchMenuItem) => {
let item = lunchMenuItem.item.replace(lunchMenuItem.allergens, '')
return _.trim(item)
.replace(/\s+/g, ' ') // remove extra spacing
.replace(/(,\s*)?\d+\s*g/, '') // remove amount from title
}
let getAmount = (lunchMenuItem) => {
let m = lunchMenuItem.item.match(/\d+\s*g/) // get amount from title
return m ? m[0] : '1ks'
}
let processMenu = (obj, options, next) => {
let items = []
// only interested in Polévky (1), Hlavní jídla (4)
let required = [1, 4]
for (let j = 0; j < required.length; j++) {
let lunchMenu = obj.menus[required[j]].menu
for (let i = 0; i < lunchMenu.length; i++) {
if (!lunchMenu[i].item) continue // not interested in headers
let item = {
item: getItem(lunchMenu[i]),
price: lunchMenu[i].price,
amount: getAmount(lunchMenu[i])
}
if (item.item.match(/^Expres/)) {
items.unshift(item) // Express first
} else {
items.push(item)
}
}
}
let out = [{
date: moment(obj.day.replace(/^\D+/, ''), 'D. M. YYYY').format('YYYY-MM-DD'),
items
}]
next(null, out)
}
let middleware = (req, res, next) => {
let options = {}
Object.assign(options, {
url: 'http://lokal-hamburk.ambi.cz/cz/menu?id=11615'
}, req.data)
x(options.url, 'div.menu', {
day: 'h2',
menus: x('table.menu-list', [{
menu: x('tr', [{
item: 'td.food',
allergens: 'span.allergens',
price: 'td:last-of-type'
}])
}])
})(helpers.createProcessMenu(processMenu)(options, res, next))
}
return {middleware}
}
|
JavaScript
| 0 |
@@ -641,91 +641,8 @@
%5B%5D%0A%0A
- // only interested in Pol%C3%A9vky (1), Hlavn%C3%AD j%C3%ADdla (4)%0A let required = %5B1, 4%5D%0A%0A
@@ -661,24 +661,25 @@
0; j %3C
-required
+obj.menus
.length;
@@ -696,25 +696,23 @@
let
-lunchMenu
+section
= obj.m
@@ -720,25 +720,137 @@
nus%5B
-required%5Bj%5D%5D.menu
+j%5D%0A if (section.name !== 'Pol%C3%A9vky' && section.name !== 'Hlavn%C3%AD j%C3%ADdla') continue // only in these sections we are interested%0A
%0A
@@ -872,22 +872,25 @@
0; i %3C
-lunchM
+section.m
enu.leng
@@ -913,22 +913,25 @@
if (!
-lunchM
+section.m
enu%5Bi%5D.i
@@ -1019,22 +1019,25 @@
getItem(
-lunchM
+section.m
enu%5Bi%5D),
@@ -1054,22 +1054,25 @@
price:
-lunchM
+section.m
enu%5Bi%5D.p
@@ -1105,22 +1105,25 @@
tAmount(
-lunchM
+section.m
enu%5Bi%5D)%0A
@@ -1687,24 +1687,44 @@
u-list', %5B%7B%0A
+ name: 'h2',%0A
menu
|
8e2746d9b8f67e6f2901df6e0c88e252a0351365
|
fix table initial selected state
|
lib/table/table-column-select.js
|
lib/table/table-column-select.js
|
import Column from './column.js'
import Checkbox from './checkbox'
export default {
name: 'VkTableColumnSelect',
extends: Column,
props: {
headerClass: {
type: String
},
cellClass: {
type: String
},
isSelected: {
type: Function,
default: () => false
}
},
headerRender (h) {
const rows = this.$parent.data
const isAllSelected = rows.filter(this.isSelected).length === rows.length
const checkbox = h(Checkbox, {
props: { checked: isAllSelected },
on: {
// as the state is not changed we must force update
click: e => this.$emit('select-all') && this.$parent.$forceUpdate()
}
})
return h('th', {
staticClass: this.headerClass,
class: 'uk-form uk-text-center uk-table-shrink',
scopedSlots: this.$scopedSlots
}, [
this._t('header', checkbox)
])
},
cellRender (h, { row }) {
const checkbox = h(Checkbox, {
props: { checked: this.isSelected(row) },
on: {
// as the state is not changed we must force update
click: e => this.$emit('select', row) && this.$parent.$forceUpdate()
}
})
return h('td', {
staticClass: this.cellClass,
class: 'uk-form uk-text-center vk-table-width-minimum',
scopedSlots: this.$scopedSlots
}, [
this._t('header', checkbox, { row })
])
},
created () {
this.$parent.$on('click-row', this.$parent.$forceUpdate)
}
}
|
JavaScript
| 0 |
@@ -371,22 +371,17 @@
const
-isAllS
+s
elected
@@ -410,16 +410,70 @@
elected)
+%0A const isAllSelected = selected.length && selected
.length
|
ae543e292ef799c5a4f9978eaf822cb36beb9ea3
|
add note
|
lib/template/scope/view/index.js
|
lib/template/scope/view/index.js
|
var protoclass = require("protoclass");
function View (node, context) {
this.node = node;
this.context = context;
this.bindings = [];
}
protoclass(View, {
render: function () {
return this.node;
},
remove: function () {
},
dispose: function () {
// put node back in scope
}
});
module.exports = View;
|
JavaScript
| 0 |
@@ -65,16 +65,209 @@
ntext) %7B
+%0A%0A // todo - check if node child length is %3E 1. If so, then%0A // create a section, otherwise don't.%0A // this.section = node.childNodes.length %3E 1 ? createSection() : singleSection(this.node);
%0A this.
|
8366d8b03b491a24e88b63d0a1e619e97ac3ddb7
|
use event delegation
|
public/js/spoiler.js
|
public/js/spoiler.js
|
/* globals define, app, ajaxify, bootbox, socket, templates, utils */
$(document).ready(function () {
'use strict';
require([
'translator'
], function (translator) {
var elements = {
MAIN : '.ns-spoiler',
BUTTON : '.ns-spoiler-control a',
CONTENT: '.ns-spoiler-content'
}, classes = {
OPEN_EYE : 'fa-eye',
CLOSE_EYE: 'fa-eye-slash'
};
$(window).on('action:topic.loading', function (e) {
addListener($(elements.BUTTON));
});
$(window).on('action:posts.loaded', function (e, data) {
data.posts.forEach(function (post, index) {
addListener($('[data-pid="' + post.pid + '"]').find(elements.BUTTON));
});
});
function addListener($button) {
$button.on('click', function (e) {
toggle($(this));
});
}
function getSpoiler($child) {
return $child.parents(elements.MAIN);
}
function toggle($button) {
var $spoiler = getSpoiler($button);
var open = $spoiler.attr('data-open') === 'true';
var icon = $button.find('i');
$spoiler.attr('data-open', !open);
if (!open) {
icon.removeClass(classes.OPEN_EYE).addClass(classes.CLOSE_EYE);
} else {
icon.removeClass(classes.CLOSE_EYE).addClass(classes.OPEN_EYE);
}
}
});
});
|
JavaScript
| 0.000002 |
@@ -507,32 +507,37 @@
%0A add
+Topic
Listener($(eleme
@@ -533,26 +533,8 @@
ner(
-$(elements.BUTTON)
);%0A
@@ -557,307 +557,102 @@
-$(window).on('action:posts.loaded', function (e, data) %7B%0A data.posts.forEach(function (post, index) %7B%0A addListener($('%5Bdata-pid=%22' + post.pid + '%22%5D').find(elements.BUTTON));%0A %7D);%0A %7D);%0A%0A function addListener($button) %7B%0A $button.on('click'
+function addTopicListener() %7B%0A $('%5Bcomponent=%22topic%22%5D').on(%22click%22, elements.BUTTON
, fu
@@ -651,33 +651,32 @@
TTON, function (
-e
) %7B%0A
|
748108afafe212cc8d575999face311d7787a111
|
Fix paths for type errors in relative subdirectory (without ../), see https://github.com/phetsims/chipper/issues/1247
|
js/scripts/absolute-tsc.js
|
js/scripts/absolute-tsc.js
|
// Copyright 2022, University of Colorado Boulder
/**
* The tsc type checker outputs type errors using relative paths only, which are not hyperlinked in WebStorm and IntelliJ.
* This thin wrapper uses a heuristic to convert the relative paths to absolute paths. Combined with an "output filter",
* this makes the type errors clickable in the tool output panel.
*
* Configure WebStorm with the following external tool:
* program: node
* arguments: perennial/js/scripts/absolute-tsc.js ${dir with a tsconfig, like chipper/tsconfig/all} ${path to replace, like ../../../}
* working dir: ${the root of the checkout, like /Users/samreid/apache-document-root/main/}
*
* IMPORTANT!!! This makes the files paths clickable in Webstorm:
* output filters: $FILE_PATH$\($LINE$\,$COLUMN$\)
*
* @author Sam Reid (PhET Interactive Simulations)
*/
const start = Date.now();
const execute = require( '../common/execute' );
const path = require( 'path' );
const args = process.argv.slice( 2 );
if ( !args || args.length === 0 ) {
console.log( 'usage: path to dir with a tsconfig file' );
}
( async () => {
const results = await execute( 'node', [ `${args[ 1 ]}/chipper/node_modules/typescript/bin/tsc` ], args[ 0 ], {
errors: 'resolve'
} );
// If there was a problem running tsc, report it here. The type errors are reported on stdout below.
if ( results.stderr.length > 0 ) {
console.log( results );
}
const end = Date.now();
const elapsed = end - start;
if ( results.stdout.trim().length === 0 ) {
console.log( `0 errors in ${elapsed}ms` );
}
else {
const lines = results.stdout.trim().split( '\n' );
const mapped = lines.map( line => {
return line.trim().split( args[ 1 ] ).join( process.cwd() + path.sep ).split( '/' ).join( path.sep );
} );
console.log( mapped.join( '\n' ) );
console.log( `${mapped.length} ${mapped.length === 1 ? 'error' : 'errors'} in ${elapsed}ms` );
}
} )();
|
JavaScript
| 0.000003 |
@@ -539,44 +539,9 @@
all%7D
- $%7Bpath to replace, like ../../../%7D
%0A
+
* w
@@ -911,16 +911,78 @@
path' );
+%0Aconst %7B resolve %7D = require( 'path' ); // eslint-disable-line
%0A%0Aconst
@@ -1178,19 +1178,33 @@
%60$%7B
-args%5B 1 %5D%7D/
+process.cwd()%7D$%7Bpath.sep%7D
chip
@@ -1730,109 +1730,374 @@
-return line.trim().split( args%5B 1 %5D ).join( process.cwd() + path.sep ).split( '/' ).jo
+if ( line.includes( '): error TS' ) ) %7B%0A const parenthesesIndex = line.indexOf( '(' );%0A%0A const linePath = line.substring( 0, parenthesesIndex );%0A const resolved = resolve( process.cwd() + path.sep + args%5B 0 %5D + path.sep + linePath );%0A return resolved + line.substr
in
+g
( pa
+ren
th
-.sep );
+esesIndex );%0A %7D%0A else %7B%0A return line;%0A %7D
%0A
|
07cc2dd602c1ab72aa3789cd8e7e342cba5e848a
|
Fix drag and drop
|
js/vendor/lvl-drag-drop.js
|
js/vendor/lvl-drag-drop.js
|
var module = angular.module("lvl.directives.dragdrop", ['lvl.services']);
module.directive('lvlDraggable', ['$rootScope', 'uuid', function ($rootScope, uuid) {
return {
restrict: 'A',
link: function (scope, el, attrs, controller) {
angular.element(el).attr("draggable", "true");
var id = angular.element(el).attr("id");
if (!id) {
id = uuid.new()
angular.element(el).attr("id", id);
}
el.bind("dragstart", function (e) {
e.dataTransfer.setData('text', id);
$rootScope.$emit("LVL-DRAG-START");
});
el.bind("dragend", function (e) {
$rootScope.$emit("LVL-DRAG-END");
});
}
};
}]);
module.directive('lvlDropTarget', ['$rootScope', 'uuid', function ($rootScope, uuid) {
return {
restrict: 'A',
scope: {
onDrop: '&'
},
link: function (scope, el, attrs, controller) {
var id = angular.element(el).attr("id");
if (!id) {
id = uuid.new();
angular.element(el).attr("id", id);
}
el.bind("dragover", function (e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
e.dataTransfer.dropEffect = 'move'; // See the section on the DataTransfer object.
return false;
});
el.bind("dragenter", function (e) {
// this / e.target is the current hover target.
angular.element(e.target).addClass('lvl-over');
});
el.bind("dragleave", function (e) {
angular.element(e.target).removeClass('lvl-over'); // this / e.target is previous target element.
});
el.bind("drop", function (e) {
if (e.preventDefault) {
e.preventDefault(); // Necessary. Allows us to drop.
}
if (e.stopPropagation) {
e.stopPropagation(); // Necessary. Allows us to drop.
}
var data = e.dataTransfer.getData("text");
var dest = document.getElementById(id);
var src = document.getElementById(data);
scope.onDrop({dragEl: data, dropEl: id});
angular.element(e.target).removeClass('lvl-over'); // this / e.target is previous target element.
});
$rootScope.$on("LVL-DRAG-START", function () {
var el = document.getElementById(id);
angular.element(el).addClass("lvl-target");
});
$rootScope.$on("LVL-DRAG-END", function () {
var el = document.getElementById(id);
angular.element(el).removeClass("lvl-target");
angular.element(el).removeClass("lvl-over");
});
}
};
}]);
|
JavaScript
| 0.000001 |
@@ -485,21 +485,9 @@
%7D%0A
-
%0A
+
@@ -540,32 +540,46 @@
e.
+originalEvent.
dataTransfer.set
@@ -1404,16 +1404,30 @@
e.
+originalEvent.
dataTran
@@ -2224,24 +2224,24 @@
%7D%0A
-
@@ -2257,16 +2257,30 @@
ata = e.
+originalEvent.
dataTran
|
de93aaa75ee0b58d29e70673d5b3c7010dc68c46
|
Add solution to Day 6b
|
6.js
|
6.js
|
require('./helpers').getFile(6, input => {
const counts = input.split('\n').reduce((acc, line) => {
line.split('').forEach((char, i) => {
acc[i][char] = acc[i][char] ? acc[i][char] + 1 : 1;
});
return acc;
}, [{}, {}, {}, {}, {}, {}, {}, {}]);
const countsArray = counts.reduce((word, letterCounts) => {
let countWinner = [0];
for (let letter in letterCounts) {
if (countWinner[0] < letterCounts[letter]) {
countWinner = [letterCounts[letter], letter];
}
}
word.push(countWinner[1]);
return word;
}, []);
console.log('The message is:', countsArray.join(''));
// zcreqgiv
});
|
JavaScript
| 0.000011 |
@@ -349,16 +349,46 @@
= %5B0%5D;%0A
+ let countLoser = %5B99999%5D;%0A
for
@@ -527,24 +527,135 @@
r%5D;%0A %7D%0A
+ if (countLoser%5B0%5D %3E letterCounts%5Bletter%5D) %7B%0A countLoser = %5BletterCounts%5Bletter%5D, letter%5D;%0A %7D%0A
%7D%0A wo
@@ -657,16 +657,23 @@
word.
+winner.
push(cou
@@ -694,28 +694,82 @@
-return word;%0A %7D, %5B%5D
+word.loser.push(countLoser%5B1%5D);%0A return word;%0A %7D, %7Bloser:%5B%5D,winner:%5B%5D%7D
);%0A%0A
@@ -813,16 +813,23 @@
tsArray.
+winner.
join('')
@@ -845,12 +845,95 @@
creqgiv%0A
+ console.log('The second message is:', countsArray.loser.join(''));%0A // pljvorrk%0A
%7D);%0A
|
3a8789b4875444c0ce33d313bc82290d2c38261e
|
Add reporter.panic in empty catch in load-themes (#29640)
|
packages/gatsby/src/bootstrap/load-themes/index.js
|
packages/gatsby/src/bootstrap/load-themes/index.js
|
const { createRequireFromPath } = require(`gatsby-core-utils`)
const path = require(`path`)
import { mergeGatsbyConfig } from "../../utils/merge-gatsby-config"
const Promise = require(`bluebird`)
const _ = require(`lodash`)
const debug = require(`debug`)(`gatsby:load-themes`)
import { preferDefault } from "../prefer-default"
import { getConfigFile } from "../get-config-file"
const { resolvePlugin } = require(`../load-plugins/load`)
const reporter = require(`gatsby-cli/lib/reporter`)
// get the gatsby-config file for a theme
const resolveTheme = async (
themeSpec,
configFileThatDeclaredTheme,
isMainConfig = false,
rootDir
) => {
const themeName = themeSpec.resolve || themeSpec
let themeDir
try {
const scopedRequire = createRequireFromPath(`${rootDir}/:internal:`)
// theme is an node-resolvable module
themeDir = path.dirname(scopedRequire.resolve(themeName))
} catch (e) {
let pathToLocalTheme
// only try to look for local theme in main site
// local themes nested in other themes is potential source of problems:
// because those are not hosted by npm, there is potential for multiple
// local themes with same name that do different things and name being
// main identifier that Gatsby uses right now, it's safer not to support it for now.
if (isMainConfig) {
pathToLocalTheme = path.join(path.resolve(`.`), `plugins`, themeName)
// is a local plugin OR it doesn't exist
try {
const { resolve } = resolvePlugin(themeName, rootDir)
themeDir = resolve
} catch (localErr) {
// catch shouldn't be empty :shrug:
}
}
if (!themeDir) {
const nodeResolutionPaths = module.paths.map(p => path.join(p, themeName))
reporter.panic({
id: `10226`,
context: {
themeName,
configFilePath: configFileThatDeclaredTheme,
pathToLocalTheme,
nodeResolutionPaths,
},
})
}
}
const { configModule, configFilePath } = await getConfigFile(
themeDir,
`gatsby-config`
)
const theme = preferDefault(configModule)
// if theme is a function, call it with the themeConfig
let themeConfig = theme
if (_.isFunction(theme)) {
themeConfig = theme(themeSpec.options || {})
}
return {
themeName,
themeConfig,
themeSpec,
themeDir,
parentDir: rootDir,
configFilePath,
}
}
// single iteration of a recursive function that resolve parent themes
// It's recursive because we support child themes declaring parents and
// have to resolve all the way `up the tree` of parent/children relationships
//
// Theoretically, there could be an infinite loop here but in practice there is
// no use case for a loop so I expect that to only happen if someone is very
// off track and creating their own set of themes
const processTheme = (
{ themeName, themeConfig, themeSpec, themeDir, configFilePath },
{ rootDir }
) => {
const themesList = themeConfig && themeConfig.plugins
// Gatsby themes don't have to specify a gatsby-config.js (they might only use gatsby-node, etc)
// in this case they're technically plugins, but we should support it anyway
// because we can't guarantee which files theme creators create first
if (themeConfig && themesList) {
// for every parent theme a theme defines, resolve the parent's
// gatsby config and return it in order [parentA, parentB, child]
return Promise.mapSeries(themesList, async spec => {
const themeObj = await resolveTheme(spec, configFilePath, false, themeDir)
return processTheme(themeObj, { rootDir: themeDir })
}).then(arr =>
arr.concat([
{ themeName, themeConfig, themeSpec, themeDir, parentDir: rootDir },
])
)
} else {
// if a theme doesn't define additional themes, return the original theme
return [{ themeName, themeConfig, themeSpec, themeDir, parentDir: rootDir }]
}
}
module.exports = async (config, { configFilePath, rootDir }) => {
const themesA = await Promise.mapSeries(
config.plugins || [],
async themeSpec => {
const themeObj = await resolveTheme(
themeSpec,
configFilePath,
true,
rootDir
)
return processTheme(themeObj, { rootDir })
}
).then(arr => _.flattenDeep(arr))
// log out flattened themes list to aid in debugging
debug(themesA)
// map over each theme, adding the theme itself to the plugins
// list in the config for the theme. This enables the usage of
// gatsby-node, etc in themes.
return (
Promise.mapSeries(
themesA,
({ themeName, themeConfig = {}, themeSpec, themeDir, parentDir }) => {
return {
...themeConfig,
plugins: [
...(themeConfig.plugins || []).map(plugin => {
return {
resolve: typeof plugin === `string` ? plugin : plugin.resolve,
options: plugin.options || {},
parentDir: themeDir,
}
}),
// theme plugin is last so it's gatsby-node, etc can override it's declared plugins, like a normal site.
{ resolve: themeName, options: themeSpec.options || {}, parentDir },
],
}
}
)
/**
* themes resolve to a gatsby-config, so here we merge all of the configs
* into a single config, making sure to maintain the order in which
* they were defined so that later configs, like the user's site and
* children, can override functionality in earlier themes.
*/
.reduce(mergeGatsbyConfig, {})
.then(newConfig => {
return {
config: mergeGatsbyConfig(newConfig, config),
themes: themesA,
}
})
)
}
|
JavaScript
| 0 |
@@ -1587,43 +1587,66 @@
-// catch shouldn't be empty :shrug:
+reporter.panic(%60Failed to resolve $%7BthemeName%7D%60, localErr)
%0A
|
1b8be26ccf2c3f9d5cbb07ff5ec9288a5d0badde
|
Add second where k is any other value
|
kth-to-last-linked-list.js
|
kth-to-last-linked-list.js
|
"use strict";
// FIND KTH TO LAST ELEMENT OF SINGLY LINKED LIST
// first create singly linked list
// define constructor
function Node(data) {
this.data = data;
this.next = null;
}
function LinkedList() {
this._length = 0; // assign number of nodes in linked list
this.head = null; // points to head of linked list (node at front of linked list)
}
// add node to linked list
LinkedList.prototype.add = function(val) {
var node = new Node(val), // create new instance of node
currentNode = this.head;
// first case: if linked list is initially empty
if (!currentNode) {
this.head = node; // make new node head of linked list
this._length++;
return node;
}
// second case: if list linked is initially not empty
while (currentNode.next) {
currentNode = currentNode.next; // iterate through entire non-empty linked list to get to end of linked list
}
currentNode.next = node; // add new node to end of linked list
this._length++;
return node;
};
// search nodes at specific positions in linked list
LinkedList.prototype.searchNodeAt = function(position) {
var currentNode = this.head,
length = this._length,
count = 1,
message = {failure: 'Failure: non-existent node in this list'};
// first case: invalid position
if (length === 0 || position < 1 || position > length) {
throw new Error(message.failure);
}
// second case: valid position
while (count < position) {
// go through entire linked list until currentNode is equal to position
currentNode = currentNode.next;
count++;
}
return currentNode; // here currentNode is equal to position
};
// remove node from linked list
LinkedList.prototype.remove = function(position) {
var currentNode = this.head,
length = this.length,
count = 0,
message = {failure: 'Failure: non-existent node in this list'},
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null;
// first case: invalid position
if (position < 0 || position > length) {
throw new Error(message.failure);
}
// second case: first node is removed
if (position === 1) {
this.head = currentNode.next; // head reassigned
deletedNode = currentNode;
currentNode = null;
this._length--;
return deletedNode;
}
// third case: any other node is removed
while (count < position) { // loop until we reach node at position we want to remove
beforeNodeToDelete = currentNode;
nodeToDelete = currentNode.next;
count++;
}
beforeNodeToDelete.next = nodeToDelete.next;
deletedNode = nodeToDelete;
nodeToDelete = null;
this._length--;
return deletedNode;
};
// return kth to last
LinkedList.prototype.kthToLast = function(k) {
var node = this.head,
i = 1,
kthNode,
message = {failure: 'Failure: non-existent node in this list'};
// first case: if k is less than 0 or greater than length of linked list
if (k <= 0 || k > this._length) {
throw new Error(message.failure);
}
}
|
JavaScript
| 0.000027 |
@@ -2902,14 +2902,215 @@
ure);%0A%09%7D
+%0A%0A%09// second case: if k is any other value%0A%09while (node) %7B%0A%09%09if (i == k) %7B%0A%09%09%09kthNode = this.head;%0A%09%09%7D else if (i-k %3E 0) %7B%0A%09%09%09kthNode = kthNode.next;%0A%09%09%7D%0A%09%09i++;%0A%0A%09%09node = node.next;%0A%09%7D%0A%09return kthNode;
%0A%7D%0A%0A%0A%0A
|
ead20b27ad79303f5d3a7283771e1b5e8f299ca4
|
Add first case where k is 0 or negative value
|
kth-to-last-linked-list.js
|
kth-to-last-linked-list.js
|
"use strict";
// FIND KTH TO LAST ELEMENT OF SINGLY LINKED LIST
// first create singly linked list
// define constructor
function Node(data) {
this.data = data;
this.next = null;
}
function LinkedList() {
this._length = 0; // assign number of nodes in linked list
this.head = null; // points to head of linked list (node at front of linked list)
}
// add node to linked list
LinkedList.prototype.add = function(val) {
var node = new Node(val), // create new instance of node
currentNode = this.head;
// first case: if linked list is initially empty
if (!currentNode) {
this.head = node; // make new node head of linked list
this._length++;
return node;
}
// second case: if list linked is initially not empty
while (currentNode.next) {
currentNode = currentNode.next; // iterate through entire non-empty linked list to get to end of linked list
}
currentNode.next = node; // add new node to end of linked list
this._length++;
return node;
};
// search nodes at specific positions in linked list
LinkedList.prototype.searchNodeAt = function(position) {
var currentNode = this.head,
length = this._length,
count = 1,
message = {failure: 'Failure: non-existent node in this list'};
// first case: invalid position
if (length === 0 || position < 1 || position > length) {
throw new Error(message.failure);
}
// second case: valid position
while (count < position) {
// go through entire linked list until currentNode is equal to position
currentNode = currentNode.next;
count++;
}
return currentNode; // here currentNode is equal to position
};
// remove node from linked list
LinkedList.prototype.remove = function(position) {
var currentNode = this.head,
length = this.length,
count = 0,
message = {failure: 'Failure: non-existent node in this list'},
beforeNodeToDelete = null,
nodeToDelete = null,
deletedNode = null;
// first case: invalid position
if (position < 0 || position > length) {
throw new Error(message.failure);
}
// second case: first node is removed
if (position === 1) {
this.head = currentNode.next; // head reassigned
deletedNode = currentNode;
currentNode = null;
this._length--;
return deletedNode;
}
// third case: any other node is removed
while (count < position) { // loop until we reach node at position we want to remove
beforeNodeToDelete = currentNode;
nodeToDelete = currentNode.next;
count++;
}
beforeNodeToDelete.next = nodeToDelete.next;
deletedNode = nodeToDelete;
nodeToDelete = null;
this._length--;
return deletedNode;
};
|
JavaScript
| 0.999976 |
@@ -2567,16 +2567,287 @@
deletedNode;%0A%7D;%0A
+%0A// return kth to last%0ALinkedList.prototype.kthToLast = function(k) %7B%0A%09var node = this.head,%0A%09%09i = 1,%0A%09%09kthNode,%0A%09%09message = %7Bfailure: 'Failure: non-existent node in this list'%7D;%0A%0A%09// first case: if k is 0 or negative value%0A%09if (k %3C= 0) %7B%0A%09%09return;%0A%09%7D%0A%7D%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A
|
442069719ab6e7e8e0fa2d4395b364a27e9a36a5
|
allow exiting of multi entry mode
|
js/alphabetizer.js
|
js/alphabetizer.js
|
//basis of alphabetization code from
//http://stackoverflow.com/a/25431980
//http://jsfiddle.net/albertmatyi/avvxuomb/
// still need to add:
//clearing all items
//more things
var alphabetizeOn = true;
var instantEntry = true;
var deleteOnClick = false;
var multiEntry = false;
var openOptions = false;
var shuffleData = false;
var alwaysShuffleData = false;
var clearData = false;
var items = new Array();
//code used for shuffling arrays
//from here http://stackoverflow.com/a/12646864
function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
var j = Math.floor(Math.random() * (i + 1));
var temp = array[i];
array[i] = array[j];
array[j] = temp;
}
return array;
};
///check if there are stored items from a previous session and load them into items
var replaceSavedItems = function(){
if (savedItems === true) {
items = savedItems;
};
};
//check if in multi-entry mode
//display items according to preset options
var displayItems = function() {
var $list = $('.list');
if (alphabetizeOn === true) {
items.sort(); //sort items
};
if (shuffleData === true ) {
shuffleArray(items); //shuffle data
if (alwaysShuffleData === false) {
shuffleData = false; //don't shuffle it next time
};
};
if (multiEntry === true) {
//only fires if it's true from the start, not if it's fired by key recognition
}
if (deleteOnClick === true) {
$list.addClass("deletable");
deleteFunc();//run the delete function
//figure out how to stop the delete function
};
$list.html(''); // clear the last content of .word-list
$.each(items, function (indexPosition) { // iterate through the words
$list.append('<li class="' + indexPosition + '">' + this + '</li>'); // append a list item for each word (this refers to the word in the array
});
};
//grab items from input
$('.css-input').on('keyup', function (event) { // listen to each keypress in the input box
if (event.which === 13 && !event.shiftKey) { // if enter is pressed
var $input = $(event.target); // take the reference to the inputbox
var item = $input.val(); // take the value of the input box
items.push(item); // add it to the array
$input.val(''); // clear the input box
//displayItems(); // show the words
}
if (event.which === 13 && event.shiftKey) { // if enter and shift are pressed
$('.css-input').addClass('multi-entry'); //Activate multi-entry mode
multiEntry = true;
}
else{
displayItems();
}
});
var deleteFunc = function(){
//delete items from array
$('ul.list').on('click', 'li', function () {
////save text from item
$(this).empty(); //make it dissapear
$(this).html('<a href="#undid">undo</a>');//add undo link
//remove from array
});
}
|
JavaScript
| 0 |
@@ -171,16 +171,69 @@
things%0A%0A
+//string logic%0A///tolowercase%0A///check for returns%0A%0A%0A
var alph
@@ -2696,24 +2696,360 @@
true;%0A %7D%0A
+ if (event.which === 27) %7B // if escape is pressed%0A $('.css-input').removeClass('multi-entry'); //de-activate multi-entry mode%0A multiEntry = false;%0A var $input = $(event.target); // take the reference to the inputbox%0A $input.val(''); // clear the input box%0A %7D%0A%0A
else%7B%0A
@@ -3074,16 +3074,17 @@
%0A %7D%0A%0A
+%0A
%7D);%0A%0Avar
|
5f4613e6b54be9f4cfed1ec1916c95e6091758a8
|
split `_exitIfInvalidMayaProject` to `_isValidMayaProject` and it.
|
src-server/cli/entry.js
|
src-server/cli/entry.js
|
import fs from "fs";
import path from "path";
// Check valid maya.js project
module.exports.exitIfInvalidMayaProject = function exitIfInvalidMayaProject(cwd) {
try {
const packageJson = require(path.join(cwd, "package.json"));
const deps = packageJson.dependencies;
const devDeps = packageJson.devDependencies;
if (deps && Object.keys(deps).indexOf("maya") !== -1) {
return;
}
if (devDeps && Object.keys(devDeps).indexOf("maya") !== -1) {
return;
}
console.error("\u001b[31mHere is not maya.js project. \n(reliance on maya.js can not be found in `dependencies` or `devDependencies`)\u001b[m");
}
catch (e) {
console.error("\u001b[31mHere is not maya.js project. \n(package.json not found.)\u001b[m");
}
process.exit(-1);
}
module.exports.run = function run() {
const cwd = process.cwd();
const [, , command, ...args] = process.argv;
switch (command) {
case "init":
require("./init")(args);
break;
case "cqc":
exitIfInvalidMayaProject(cwd);
require("./cqc")(args);
break;
case "_dev":
process.chdir(path.join(__dirname, "../../devapp"));
require("./cqc")(args);
break;
case "export":
exitIfInvalidMayaProject(cwd);
require("./export")(args);
break;
case "g":
case "generate":
exitIfInvalidMayaProject(cwd);
require("./generate")(args);
break;
case "h":
case "help":
default:
if (command !== undefined) {
console.log(`\u001b[31mCommand not found : ${command}\u001b[m\n`);
}
console.log(
`Usage :
maya <command> [<options>...]
Commands :
cqc\t\t\tStart maya.js server.
export\t\tExport maya.js components for other libraries.
generate(g)\t\tGenerate some components
help\t\tShow this help
`
);
process.exit(0);
}
};
|
JavaScript
| 0 |
@@ -86,25 +86,20 @@
exports.
-exitIfInv
+_isV
alidMaya
@@ -117,25 +117,20 @@
unction
-exitIfInv
+_isV
alidMaya
@@ -398,32 +398,37 @@
return
+ true
;%0A %7D%0A%0A
@@ -512,16 +512,21 @@
return
+ true
;%0A
@@ -522,32 +522,386 @@
rue;%0A %7D%0A%0A
+ return %22DEPENDENCY_NOT_FOUND%22;%0A %7D%0A catch (e) %7B%0A return %22PACKAGE_JSON_NOT_FOUND%22;%0A %7D%0A%7D;%0A%0A%0Amodule.exports._exitIfInvalidMayaProject = function _exitIfInvalidMayaProject(cwd) %7B%0A const valid = _isValidMayaProject(cwd);%0A%0A if (valid === true) %7B%0A return;%0A %7D%0A%0A switch (valid) %7B%0A case %22DEPENDENCY_NOT_FOUND%22:%0A
console.
@@ -1041,34 +1041,75 @@
%22);%0A
-%7D%0A catch (e) %7B%0A
+ break;%0A%0A case %22PACKAGE_JSON_NOT_FOUND%22:%0A
@@ -1197,24 +1197,43 @@
%5Cu001b%5Bm%22);%0A
+ break;%0A
%7D%0A%0A p
@@ -1496,32 +1496,33 @@
c%22:%0A
+_
exitIfInvalidMay
@@ -1761,32 +1761,33 @@
t%22:%0A
+_
exitIfInvalidMay
@@ -1915,16 +1915,17 @@
+_
exitIfIn
|
ca017090cb900a868b388888c32f4281b82d4615
|
Save commit messages between saves. Fixes #454
|
js/id/ui/commit.js
|
js/id/ui/commit.js
|
iD.ui.commit = function(map) {
var event = d3.dispatch('cancel', 'save', 'fix');
function zipSame(d) {
var c = [], n = -1;
for (var i = 0; i < d.length; i++) {
var desc = {
name: d[i].friendlyName(),
type: d[i].type,
count: 1,
tagText: iD.util.tagText(d[i])
};
if (c[n] &&
c[n].name == desc.name &&
c[n].tagText == desc.tagText) {
c[n].count++;
} else {
c[++n] = desc;
}
}
return c;
}
function commit(selection) {
function changesLength(d) { return changes[d].length; }
var changes = selection.datum(),
connection = changes.connection,
user = connection.user(),
header = selection.append('div').attr('class', 'header modal-section fillL'),
body = selection.append('div').attr('class', 'body');
var user_details = header
.append('div')
.attr('class', 'user-details');
var user_link = user_details
.append('div')
.append('a')
.attr('href', connection.url() + '/user/' +
user.display_name)
.attr('target', '_blank');
if (user.image_url) {
user_link
.append('img')
.attr('src', user.image_url)
.attr('class', 'user-icon');
}
user_link
.append('div')
.text(user.display_name);
header.append('h2').text('Save Changes');
header.append('p').text('The changes you upload will be visible on all maps that use OpenStreetMap data.');
// Comment Box
var comment_section = body.append('div').attr('class','modal-section fillD');
comment_section.append('textarea')
.attr('class', 'changeset-comment')
.attr('placeholder', 'Brief Description of your contributions');
// Confirm / Cancel Buttons
var buttonwrap = comment_section.append('div')
.attr('class', 'buttons cf')
.append('div')
.attr('class', 'button-wrap joined col4');
var savebutton = buttonwrap
.append('button')
.attr('class', 'save action col6 button')
.on('click.save', function() {
event.save({
comment: d3.select('textarea.changeset-comment').node().value
});
});
savebutton.append('span').attr('class','label').text('Save');
var cancelbutton = buttonwrap.append('button')
.attr('class', 'cancel col6 button')
.on('click.cancel', function() {
event.cancel();
});
cancelbutton.append('span').attr('class','icon close icon-pre-text');
cancelbutton.append('span').attr('class','label').text('Cancel');
var warnings = body.selectAll('div.warning-section')
.data(iD.validate(changes, map.history().graph()))
.enter()
.append('div').attr('class', 'modal-section warning-section fillL');
warnings.append('h3')
.text('Warnings');
var warning_li = warnings.append('ul')
.attr('class', 'changeset-list')
.selectAll('li')
.data(function(d) { return d; })
.enter()
.append('li');
warning_li.append('button')
.attr('class', 'minor')
.on('click', event.fix)
.append('span')
.attr('class', 'icon inspect');
warning_li.append('strong').text(function(d) {
return d.message;
});
var section = body.selectAll('div.commit-section')
.data(['modified', 'deleted', 'created'].filter(changesLength))
.enter()
.append('div').attr('class', 'commit-section modal-section fillL2');
section.append('h3').text(function(d) {
return d.charAt(0).toUpperCase() + d.slice(1);
})
.append('small')
.attr('class', 'count')
.text(changesLength);
var li = section.append('ul')
.attr('class','changeset-list')
.selectAll('li')
.data(function(d) { return zipSame(changes[d]); })
.enter()
.append('li');
li.append('strong').text(function(d) {
return (d.count > 1) ? d.type + 's ' : d.type + ' ';
});
li.append('span')
.text(function(d) { return d.name; })
.attr('title', function(d) { return d.tagText; });
li.filter(function(d) { return d.count > 1; })
.append('span')
.attr('class', 'count')
.text(function(d) { return d.count; });
}
return d3.rebind(commit, event, 'on');
};
|
JavaScript
| 0 |
@@ -2044,16 +2044,76 @@
utions')
+%0A .property('value', localStorage.comment %7C%7C '')
;%0A%0A
@@ -2513,48 +2513,19 @@
-event.save(%7B%0A
+var
comment
: d3
@@ -2520,17 +2520,18 @@
comment
-:
+ =
d3.sele
@@ -2575,16 +2575,131 @@
().value
+;%0A localStorage.comment = comment;%0A event.save(%7B%0A comment: comment
%0A
|
727eda71f291574bc1723ef4af2c460e937a0ae3
|
fix missing word in docblock
|
resources/assets/js/bootstrap.js
|
resources/assets/js/bootstrap.js
|
window._ = require('lodash');
window.Cookies = require('js-cookie');
/**
* We'll load jQuery and the Bootstrap jQuery plugin which provides support
* for JavaScript based Bootstrap features such as modals and tabs. This
* code may be modified to fit the specific needs of your application.
*/
window.$ = window.jQuery = require('jquery');
require('bootstrap-sass/assets/javascripts/bootstrap');
/**
* Vue is a modern JavaScript for building interactive web interfaces using
* reacting data binding and reusable components. Vue's API is clean and
* simple, leaving you to focus only on building your next great idea.
*/
window.Vue = require('vue');
require('vue-resource');
/**
* We'll register a HTTP interceptor to attach the "XSRF" header to each of
* the outgoing requests issued by this application. The CSRF middleware
* included with Laravel will automatically verify the header's value.
*/
Vue.http.interceptors.push(function (request, next) {
request.headers['X-XSRF-TOKEN'] = Cookies.get('XSRF-TOKEN');
next();
});
|
JavaScript
| 0 |
@@ -430,16 +430,26 @@
aScript
+framework
for buil
@@ -483,26 +483,26 @@
aces
+%0A *
using
-%0A *
reacti
-ng
+ve
dat
@@ -543,37 +543,38 @@
Vue
-'s API is clean and%0A * simple
+ has a simple and%0A * clean API
, le
|
a2f7162616f7ba75c5dcfa65a645e417446fa2a9
|
Update landing-page.js
|
js/landing-page.js
|
js/landing-page.js
|
function getTimeRemaining(endtime) {
var t = Date.parse(endtime) - Date.parse(new Date());
var seconds = Math.floor((t / 1000) % 60);
var minutes = Math.floor((t / 1000 / 60) % 60);
var hours = Math.floor((t / (1000 * 60 * 60)) % 24);
var days = Math.floor(t / (1000 * 60 * 60 * 24));
return {
'total': t,
'days': days,
'hours': hours,
'minutes': minutes,
'seconds': seconds
};
}
function initializeClock(id, endtime) {
var clock = document.getElementById(id);
var daysSpan = clock.querySelector('.days');
var hoursSpan = clock.querySelector('.hours');
var minutesSpan = clock.querySelector('.minutes');
var secondsSpan = clock.querySelector('.seconds');
function updateClock() {
var t = getTimeRemaining(endtime);
daysSpan.innerHTML = t.days;
hoursSpan.innerHTML = ('0' + t.hours).slice(-2);
minutesSpan.innerHTML = ('0' + t.minutes).slice(-2);
secondsSpan.innerHTML = ('0' + t.seconds).slice(-2);
if (t.total <= 0) {
clearInterval(timeinterval);
}
}
updateClock();
var timeinterval = setInterval(updateClock, 1000);
}
var wedding = moment.tz("2017-08-12 16:00", "America/New_York");
var deadline = new Date(Date.parse(wedding.format()));
initializeClock('clockdiv', deadline);
|
JavaScript
| 0.000001 |
@@ -1144,16 +1144,86 @@
;%0D%0A%7D%0D%0A%0D%0A
+moment.tz.add('America/New_York%7CEST EDT%7C50 40%7C0101%7C1Lz50 1zb0 Op0');%0D%0A
var wedd
@@ -1374,8 +1374,10 @@
adline);
+%0D%0A
|
b1d919069282b27002f514fa9777e28817f58346
|
Fix missing 'require'
|
resources/js/view/information.js
|
resources/js/view/information.js
|
"use strict";
var View = VAGABOND.VIEW.View;
var Information = Object.create(View);
Information.init = function(entity) {
this.selectedEntity = entity;
return this;
};
Information.setEntity = Information.init;
Information.toElement = function() {
var info = document.createElement("div");
info.className = "selected-info";
var entityInfo = this.selectedEntity.getInformation();
for (var traitKey in entityInfo) {
var traitElement = document.createElement("span");
traitElement.innerHTML = traitKey + ": " + entityInfo[traitKey];
info.appendChild(traitElement);
info.appendChild(document.createElement("br"));
}
return info;
};
module.exports = View;
|
JavaScript
| 0.999994 |
@@ -23,26 +23,25 @@
w =
-VAGABOND.VIEW.V
+require(%22./v
iew
+%22)
;%0A%0Av
|
93abed4ac317316b4bce0a54efc77a9df07bc190
|
Update mp3Worker.js
|
js/enc/mp3/mp3Worker.js
|
js/enc/mp3/mp3Worker.js
|
importScripts('libmp3lame.js');
var mp3codec;
var recLength = 0,
recBuffers = [];
//https://github.com/gypified/libmp3lame/blob/master/API
self.onmessage = function(e) {
switch (e.data.command) {
case 'init':
init(e.data.config);
break;
case 'encode':
encode(e);
break;
case 'finish':
finish();
break;
}
};
function init(config) {
if (!config) {
config = {};
}
mp3codec = Lame.init();
Lame.set_mode(mp3codec, config.mode || Lame.JOINT_STEREO);
Lame.set_num_channels(mp3codec, config.channels || 2);
Lame.set_out_samplerate(mp3codec, config.samplerate || 44100);
Lame.set_in_samplerate(mp3codec, config.in_samplerate || 44100);
/*The default is a J-Stereo, 44.1khz, 128kbps CBR mp3 file at quality 5.*/
Lame.set_bitrate(mp3codec, config.bitrate || 128);
//Lame.set_mode(mp3codec, 1);
//lame.set_quality(mp3codec,2); /* 2=high 5 = medium 7=low */
//Lame.set_num_samples(mp3codec, e.data.config.samples || -1);
Lame.init_params(mp3codec);
// console.log('Version :', Lame.get_version() + ' / ',
// 'Mode: ' + Lame.get_mode(mp3codec) + ' / ',
// 'Samples: ' + Lame.get_num_samples(mp3codec) + ' / ',
// 'Channels: ' + Lame.get_num_channels(mp3codec) + ' / ',
// 'Input Samplate: ' + Lame.get_in_samplerate(mp3codec) + ' / ',
// 'Output Samplate: ' + Lame.get_in_samplerate(mp3codec) + ' / ',
// 'Bitlate :' + Lame.get_bitrate(mp3codec) + ' / ',
// 'VBR :' + Lame.get_VBR(mp3codec));
}
function encode(e) {
var mp3data = Lame.encode_buffer_ieee_float(mp3codec, e.data.buf, e.data.buf);
self.postMessage({
command: 'data',
buf: mp3data.data
});
///console.log(mp3data.data.toString('hex'));
recBuffers.push(mp3data.data);
recLength += mp3data.data.length;
}
function finish() {
//console.log('recBuffers.length:' + recBuffers.length);
//console.log('recLength:' + recLength);
var mp3data = Lame.encode_flush(mp3codec);
recBuffers.push(mp3data.data);
recLength += mp3data.data.length;
self.postMessage({
command: 'data',
buf: mp3data.data
});
var buffer = mergeBuffers(recBuffers, recLength);
//buffer = new ArrayBuffer(buffer.length);
var view = new Uint8Array(buffer);
var audioBlob = new Blob([view], {
type: "audio/mp3"
});
self.postMessage({
command: 'mp3',
buf: audioBlob
});
Lame.close(mp3codec);
mp3codec = null;
recBuffers = [];
recLength = 0;
}
function mergeBuffers(recBuffers, recLength) {
//Float32Array
var result = new Float32Array(recLength);
var offset = 0;
for (var i = 0; i < recBuffers.length; i++) {
result.set(recBuffers[i], offset);
offset += recBuffers[i].length;
}
return result;
}
|
JavaScript
| 0 |
@@ -1552,24 +1552,26 @@
ata.buf);%0A%0A%09
+//
self.postMes
@@ -1570,32 +1570,34 @@
.postMessage(%7B%0A%09
+//
%09command: 'data'
@@ -1591,32 +1591,34 @@
mmand: 'data',%0A%09
+//
%09buf: mp3data.da
@@ -1617,24 +1617,26 @@
3data.data%0A%09
+//
%7D);%0A%0A%09///con
@@ -2644,12 +2644,13 @@
n result;%0A%0A%7D
+%0A
|
b995d860e9091264e60cf31c759eb00b579fba0c
|
Add classname in material
|
js/osg/Material.js
|
js/osg/Material.js
|
/**
* Material
* @class Material
*/
osg.Material = function () {
osg.StateAttribute.call(this);
this.ambient = [ 0.2, 0.2, 0.2, 1.0 ];
this.diffuse = [ 0.8, 0.8, 0.8, 1.0 ];
this.specular = [ 0.0, 0.0, 0.0, 1.0 ];
this.emission = [ 0.0, 0.0, 0.0, 1.0 ];
this.shininess = 12.5;
};
/** @lends osg.Material.prototype */
osg.Material.prototype = osg.objectInehrit(osg.StateAttribute.prototype, {
setEmission: function(a) { osg.Vec4.copy(a, this.emission); this._dirty = true; },
setAmbient: function(a) { osg.Vec4.copy(a, this.ambient); this._dirty = true; },
setSpecular: function(a) { osg.Vec4.copy(a, this.specular); this._dirty = true; },
setDiffuse: function(a) { osg.Vec4.copy(a, this.diffuse); this._dirty = true; },
setShininess: function(a) { this.shininess = a; this._dirty = true; },
getEmission: function() { return this.emission;},
getAmbient: function() { return this.ambient; },
getSpecular: function() { return this.specular;},
getDiffuse: function() { return this.diffuse;},
getShininess: function() { return this.shininess; },
attributeType: "Material",
cloneType: function() {return new osg.Material(); },
getType: function() { return this.attributeType;},
getTypeMember: function() { return this.attributeType;},
getOrCreateUniforms: function() {
if (osg.Material.uniforms === undefined) {
osg.Material.uniforms = { "ambient": osg.Uniform.createFloat4([ 0, 0, 0, 0], 'MaterialAmbient') ,
"diffuse": osg.Uniform.createFloat4([ 0, 0, 0, 0], 'MaterialDiffuse') ,
"specular": osg.Uniform.createFloat4([ 0, 0, 0, 0], 'MaterialSpecular') ,
"emission": osg.Uniform.createFloat4([ 0, 0, 0, 0], 'MaterialEmission') ,
"shininess": osg.Uniform.createFloat1([ 0], 'MaterialShininess')
};
var uniformKeys = [];
for (var k in osg.Material.uniforms) {
uniformKeys.push(k);
}
osg.Material.uniforms.uniformKeys = uniformKeys;
}
return osg.Material.uniforms;
},
apply: function(state)
{
var uniforms = this.getOrCreateUniforms();
uniforms.ambient.set(this.ambient);
uniforms.diffuse.set(this.diffuse);
uniforms.specular.set(this.specular);
uniforms.emission.set(this.emission);
uniforms.shininess.set([this.shininess]);
this._dirty = false;
},
// will contain functions to generate shader
_shader: {},
_shaderCommon: {},
generateShader: function(type) {
if (this._shader[type]) {
return this._shader[type].call(this);
}
return "";
}
});
osg.Material.prototype._shader[osg.ShaderGeneratorType.VertexInit] = function()
{
var str = [ "uniform vec4 MaterialAmbient;",
"uniform vec4 MaterialDiffuse;",
"uniform vec4 MaterialSpecular;",
"uniform vec4 MaterialEmission;",
"uniform float MaterialShininess;",
""].join('\n');
return str;
};
osg.Material.prototype._shader[osg.ShaderGeneratorType.FragmentInit] = function()
{
var str = [ "uniform vec4 MaterialAmbient;",
"uniform vec4 MaterialDiffuse;",
"uniform vec4 MaterialSpecular;",
"uniform vec4 MaterialEmission;",
"uniform float MaterialShininess;",
""].join('\n');
return str;
};
|
JavaScript
| 0.000001 |
@@ -412,16 +412,44 @@
otype, %7B
+%0A _className: 'Material',
%0A%0A se
|
e2b219b1ae7ad882eea96f821b3712163726504d
|
fix tab and space regression
|
js/plugins/tern.js
|
js/plugins/tern.js
|
/**
Copyright 2014 Gordon Williams ([email protected])
This Source Code is subject to the terms of the Mozilla Public
License, v2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at http://mozilla.org/MPL/2.0/.
------------------------------------------------------------------
Awesome Tern Autocomplete code
------------------------------------------------------------------
**/
"use strict";
(function(){
function init() {
function getURL(url, c) {
var xhr = new XMLHttpRequest();
xhr.open("get", url, true);
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState != 4) return;
if (xhr.status < 400) return c(null, xhr.responseText);
var e = new Error(xhr.responseText || "No response");
e.status = xhr.status;
c(e);
};
}
var server;
var espruinoJSON;
getURL(/*"http://ternjs.net/defs/ecma5.json"*/"/data/espruino.json", function(err, code) {
var codeMirror = Espruino.Core.EditorJavaScript.getCodeMirror();
if (err) throw new Error("Request for ecma5.json: " + err);
espruinoJSON = code;
server = new CodeMirror.TernServer({defs: [JSON.parse(espruinoJSON)]});
codeMirror.setOption("extraKeys", {
"Ctrl-Space": function(cm) { server.smartComplete(cm); },
"Ctrl-I": function(cm) { server.showType(cm); },
"Alt-.": function(cm) { server.jumpToDef(cm); },
"Alt-,": function(cm) { server.jumpBack(cm); },
"Ctrl-Q": function(cm) { server.rename(cm); },
"Ctrl-.": function(cm) { server.selectName(cm); }
})
codeMirror.on("cursorActivity", function(cm) { server.updateArgHints(cm); });
});
/* When we connect to a board and we load its description,
go through an add all the pins as variables so Tern cal autocomplete */
Espruino.addProcessor("boardJSONLoaded", function (data, callback) {
if (espruinoJSON !== undefined && "pins" in data) {
var defs = JSON.parse(espruinoJSON);
data.pins.forEach(function(pin) {
var functions = [];
for (var fn in pin.simplefunctions) {
if (["PWM","USART","SPI","I2C","DEVICE"].indexOf(fn)>=0)
functions = functions.concat(pin.simplefunctions[fn]);
else
functions.push(fn);
}
defs[pin["name"]] = {
"!type": "+Pin",
"!doc": functions.join(", "),
"!url": "http://www.espruino.com/Reference"+data["BOARD"]+"#"+pin["name"],
};
});
// reload tern server with new defs
server = new CodeMirror.TernServer({defs: [defs]});
}
callback(data);
});
}
Espruino.Plugins.Tern = {
init : init,
};
}());
|
JavaScript
| 0 |
@@ -1230,24 +1230,32 @@
N)%5D%7D);%0A
+ var k =
codeMirror.
@@ -1254,17 +1254,17 @@
eMirror.
-s
+g
etOption
@@ -1275,17 +1275,33 @@
traKeys%22
-,
+);%0A var nk =
%7B%0A
@@ -1652,17 +1652,107 @@
%0A %7D
-)
+;%0A for (var i in nk)%0A k%5Bi%5D = nk%5Bi%5D;%0A codeMirror.setOption(%22extraKeys%22, k);
%0A c
@@ -2928,8 +2928,9 @@
%7D;%0A%7D());
+%0A
|
39840d4821291a2d1c8f3cc59b0eb11c74225696
|
Update qalet_plugin.js
|
js/qalet_plugin.js
|
js/qalet_plugin.js
|
var _CALLBACK_ = function() {
$(document).ready(
function() {
function parse(v) {
var t = v.replace(/(“|”)/ig, '"');
return JSON.parse(t);
}
var v = $('QALET'), r={}, f=[];
for (var i = 0; i < v.length; i++) {
var data = $(v[i]).html();
if (!data) data = $(v[i]).attr('data');
var o = parse(data);
if (o.module) {
r[o.module] = true;
o.id = o.module + '_plugin_' + i;
f[f.length] = o;
$(v[i]).replaceWith('<div class="class_' + o.module +' '+o.id+'"></div>');
if (o.css) {
$('.'+o.id).hide();
(function(o){
function URL(url) {
var a = document.createElement('a');
a.href = url;
return a.cloneNode(false).href;
}
$.get(URL(o.css), function( data ) {
try {
console.log(data.replace(/\}([\;|\s]*)/g, '} '));
var v = UIQALET.css.parse(data.replace(/\}([\;|\s]*)/g, '} '));
console.log(v);
UIQALET.css.ruleSelect(v.stylesheet,o.id);
console.log(UIQALET.css.stringify(v));
$('head').append('<style>'+UIQALET.css.stringify(v)+'</style>');
} catch (err) {
console.log(err.message);
}
$('.'+o.id).show();
});
/*
$.get('/_x/cssrange/.'+ o.id +'/'+URL(o.css), function( data ) {
var v = data.match(/^\/\*ERR(.*)\*\//);
if (v) {
console.log(v[1]);
} else {
$('head').append('<style>'+data+'</style>');
$('.'+o.id).show();
}
});
*/
})(o);
}
}
}
for (var i=0; i<f.length; i++) {
if (typeof _QALET_[f[i].module] == 'function') {
_QALET_[f[i].module](f[i]);
} else {
console.log('=='+f[i].module+'==');
}
}
}
);
};
|
JavaScript
| 0.000001 |
@@ -991,16 +991,20 @@
lesheet,
+'.'+
o.id);%0A%09
|
55663382f3728079c8bb24ca19fd9999249fe853
|
add 'A' icon option
|
js/icon-setter/index.js
|
js/icon-setter/index.js
|
import React, {PureComponent} from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import LogoMenu from '../components/logo-menu';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { GridList, GridTile } from 'material-ui/GridList';
import RaisedButton from 'material-ui/RaisedButton';
import '../../css/app.less';
import '../../css/icon-setter.less';
// Required by Material-UI library.
injectTapEventPlugin();
darkBaseTheme.palette.textColor = '#ccc';
const icons = ['🐞', '🦋', '🍎', '🍄', '🌈', '⭐', '🚜', '✈', '⚽', '🍒', '🐟', '🐢', '🚀',
'🐿', '🐌', '🌼', '🐙', '🌵', '🦀', '🚁', '⛄', '🐝', '🔑', '💡', '🐍' ];
const nameServiceAddr = 0x1234;
const nameCharacteristicAddr = 0x2345;
const instr_start = 'Click "Connect" and select a Thermoscope to set its icon';
const instr_connected = 'Select a new icon for the Thermoscope and click "Set Icon"';
const instr_changed = 'Click "Disconnect" and turn the Thermoscope off and on again';
export class IconSetter extends PureComponent {
constructor(props) {
super(props);
this.state = {
connected: false,
iconChanged: false,
status: "not connected",
currentIcon: '',
selectedIcon: ''
};
this.iconCharacteristic = null;
this.decoder = new TextDecoder('utf-8');
this.encoder = new TextEncoder('utf-8');
this.connect = this.connect.bind(this);
this.disconnect = this.disconnect.bind(this);
this.selectIcon = this.selectIcon.bind(this);
this.setIcon = this.setIcon.bind(this);
}
connect() {
console.log("connect");
let request = navigator.bluetooth.requestDevice({
filters: [{ namePrefix: "Thermoscope" }],
optionalServices: [nameServiceAddr]
});
var component = this;
// Step 2: Connect to it
request.then(function(device) {
component.setState({
status: "connecting",
iconChanged: false
});
return device.gatt.connect();
})
// Step 3: Get the icon service
.then(function(server) {
component.setState({
status: "getting icon service"
});
window.server = server;
return server.getPrimaryService(nameServiceAddr);
})
.then(function(service){
component.setState({
status: "getting characteristic"
});
return service.getCharacteristic(nameCharacteristicAddr);
})
.then(function(characteristic){
component.iconCharacteristic = characteristic;
component.setState({
status: "reading characteristic"
});
return characteristic.readValue();
})
.then(function(value){
var iconVal = component.decoder.decode(value);
component.setState({
connected: true,
status: "current icon value: " + iconVal,
currentIcon: iconVal,
selectedIcon: iconVal
});
})
.catch(function(error) {
console.error('Connection failed!', error);
component.setState({
status: "connection failed"
});
});
}
disconnect() {
window.server.disconnect();
this.setState({
connected: false,
status: "disconnected"
});
}
selectIcon(event) {
var icon = event.target.value;
this.setState({
selectedIcon: icon
});
}
setIcon() {
var encoded = this.encoder.encode(this.state.selectedIcon);
this.iconCharacteristic.writeValue(encoded);
this.setState({
iconChanged: true,
status: "current icon value: " + this.state.selectedIcon,
currentIcon: this.state.selectedIcon
});
}
getInstructions() {
var newInstr = '';
if(!this.state.connected) {
newInstr = instr_start;
} else if(!this.state.iconChanged) {
newInstr = instr_connected;
} else {
newInstr = instr_changed;
}
return newInstr;
}
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<div className="app icon-setter">
<h1>Thermoscope Icon Setter</h1>
<LogoMenu scale="logo-menu"/>
<h3 id="instructions" className="message">
{this.getInstructions()}
</h3>
<div className="app-container">
<div>
{!this.state.connected && <RaisedButton id="connect" onClick={this.connect}>Connect</RaisedButton>}
{this.state.connected && <RaisedButton id="disconnect" onClick={this.disconnect}>Disconnect</RaisedButton>}
</div>
{this.state.connected && <div>
<select id="icon-select" value={this.state.selectedIcon} onChange={this.selectIcon} className="icons">
{icons.map((icon) => (
<option key={icon} value={icon}>
{icon}
</option>
))}
</select>
<RaisedButton id="set-icon" onClick={this.setIcon} className="button2"
disabled={this.state.selectedIcon == this.state.currentIcon}>
Set Icon</RaisedButton>
</div>}
</div>
<div id="status" className="message">{this.state.status}</div>
<div className="instructions">
<div>After the icon has been set, and the thermoscope power cycled, the device will still show up with the
wrong name on any computer or tablet that saw it with the wrong name. The device is saying "Hi, I'm device 12345,
my name is Thermoscope X". The operating system sees "12345" and ignores the rest, so it continues to show
the device with the name "Thermoscope". However, after a connection has been made to the device then the
operating system updates its name for "12345" to be "Thermoscope X"
</div>
</div>
</div>
</MuiThemeProvider>
);
}
}
ReactDOM.render(<IconSetter/>, document.getElementById('app'));
|
JavaScript
| 0.000001 |
@@ -814,16 +814,21 @@
'%F0%9F%92%A1', '%F0%9F%90%8D'
+, 'A'
%5D;%0A%0Acon
|
e9acf41819105c65dd39855628300f00f0c10157
|
Fix bugs
|
js/sensor-setup.js
|
js/sensor-setup.js
|
(function(exports){
$(document).ready(function(){
$('.modal-trigger').leanModal();
});
const GEOCODE_URL = 'https://maps.googleapis.com/maps/api/geocode/json?address=';
const API_KEY = '&key=AIzaSyAWlJoUn2DS8XUYilLXZE8dxYEXbo6dnaE';
const TOAST_DUR = 4000;
var userId = $.url().param('userId');
var sensorName = $('#sensor-name');
var sensorLocation = $('#sensor-location');
var sensorDescription = $('#sensor-description');
var sensorProject = $('#sensor-project');
var sensorCoords;
var gMap;
$('select').material_select();
$(window).load(function handleClientLoad() {
var auth = gapi.auth2.getAuthInstance();
if (!auth) {
return;
}
var loginBtn = $('#login-btn');
var accountBtn = $('#account-btn');
function btnState(isSignedIn) {
if (isSignedIn) {
var email = auth.currentUser.get().getBasicProfile().getEmail();
$.ajax({
url: API_URL + 'users?email=' + email,
dataType: 'jsonp'
})
.done(function(result) {
loginBtn.addClass('hide');
accountBtn.removeClass('hide');
accountBtn.attr('href', 'user-detail.html?userId=' + result.id);
})
.fail(function(err) {
console.error(err)
});
} else {
accountBtn.addClass('hide');
loginBtn.removeClass('hide');
}
}
btnState(auth.isSignedIn.get() || auth.currentUser.get().isSignedIn());
auth.isSignedIn.listen(btnState);
});
function onSignIn(googleUser) {
var userId = $('#user-id').val();
if (!userId) {
return;
}
var auth = googleUser.getAuthResponse();
var profile = googleUser.getBasicProfile();
var userData = {
// token: auth.access_token, Do we really need this?
id: userId,
name: profile.getName(),
email: profile.getEmail(),
picture: profile.getImageUrl()
};
//TODO: create user in DB and get user profile
$('#user-id').text();
$('#google-sign-in-modal').closeModal();
$.ajax({
type: 'POST',
url: API_URL + 'users',
data: userData,
dataType: 'jsonp'
})
.done(function() {
window.location = 'user-detail.html?userId=' + userId;
})
.fail(function(err) {
console.error(err)
});
}
$('#setup-sensor').click(function() {
if (!sensorCoords) {
Materialize.toast('Please check your address on the map', TOAST_DUR);
return;
}
var name = sensorName.val();
var projectKey = sensorProject.val();
$.post('projects/' + projectKey + '/sensors', {
userId: userId,
name: name,
description: sensorDescription.val(),
address: sensorLocation.val(),
// XXX: Need String type here.
coords: JSON.stringify(sensorCoords),
// TOOD: Please add the google token here.
token: 'Google token'
})
.done(function(result) {
if (result.result === 'success') {
window.location = './user-detail.html?userId=' + userId;
} else {
alert(result.message);
}
})
.fail(function(err) {
console.error(err)
});
});
$('#check-addr-btn').click(function() {
var address = sensorLocation.val();
if (!address) {
return;
}
var formattedAddr = address.split(' ').join('+');
$.ajax({
url: GEOCODE_URL + formattedAddr + API_KEY,
})
.done(function(data) {
if (!data.results[0]) {
return;
}
sensorCoords = data.results[0].geometry.location;
gMap = new google.maps.Map(document.getElementById('location-map'), {
zoom: 16,
center: sensorCoords
});
var gMapMarker = new google.maps.Marker({
position: sensorCoords,
map: gMap,
draggable:true,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(gMapMarker, 'dragend', function() {
sensorCoords = gMapMarker.getPosition().toJSON();
});
})
.fail(function(error) {
console.error(error);
});
});
function initMap() {
gMap = new google.maps.Map(document.getElementById('location-map'), {
zoom: 1,
center: {lat: 0, lng: 0}
});
}
exports.initMap = initMap;
exports.onSignIn = onSignIn;
})(window);
|
JavaScript
| 0.000004 |
@@ -2549,16 +2549,26 @@
$.post(
+API_URL +
'project
|
eaa23b63f6ae126e72d39716d13b65195094b6d5
|
Add rank type to thSortMenu
|
js/jquery.thSortMenu.js
|
js/jquery.thSortMenu.js
|
// thSortMenu plugin - support for server-side table sorting
;(function($, window, undefined) {
// Static variables, shared by all instances of this plugin on the page
var urlData = splitURL(window.location.href);
var path = urlData.path;
var qryData = urlData.data;
if ( qryData.sortCols !== undefined ) {
var sortColsArray = qryData.sortCols.split(" ");
var currentSortColName = sortColsArray[0];
var currentSortColType = coalesce(sortColsArray[1], 'ASC');
}
// The actual widget prototype
$.widget('qcode.thSortMenu', {
_create: function() {
// Constructor function
// Apply default column and sort type
if ( this.options.column === undefined ) {
this.options.column = this.element.parent('th').closest('table').find('col').eq( this.element.parent('th').index() );
}
if ( ! this.options.column.is('col') || this.options.column.length != 1 ) {
$.error('Invalid column for thSortMenu');
}
if ( this.options.type === undefined ) {
this.options.type = this.getColType(this.options.column);
}
// Bind events
this._on({
'click': this.menuShow
});
// Remember parent's background color
this.savedBackground = this.element.parent().css('background-color');
},
menuShow: function(target) {
// Show the menu. Target is the event or element to position against.
if ( this.menu === undefined ) {
this._menuCreate();
}
this.element.parent().css({
'background-color': "#ffffe9"
});
// Use jQuery UI position method
this.menu
.show()
.position({
'my': "left top",
'of': target,
'collision': "fit"
});
},
menuHide: function() {
// Hide the menu
this.menu.hide();
this.element.parent().css({
'background-color': this.savedBackground
});
},
getColType: function(col) {
// Get the sort type of the given column
if ( col.hasClass('number') || col.hasClass('money') ) {
return 'numeric';
} else if ( col.hasClass('date') ) {
return 'date';
} else {
return 'alpha';
}
},
_menuCreate: function() {
// Create the menu
var colName = this.options.column.attr('name');
var ascURL = urlSet(window.location.href, 'sortCols', colName + " " + "ASC");
var descURL = urlSet(window.location.href, 'sortCols', colName + " " + "DESC");
// Generate link text from sort type
var ascText;
var descText;
switch(this.options.type) {
case 'numeric':
ascText = "Sort Low to High";
descText = "Sort High to Low";
break;
case 'date':
ascText = "Sort Old to New";
descText = "Sort New to Old";
break;
default:
ascText = "Sort A-Z";
descText = "Sort Z-A";
}
// Create the links
var ascLink = $('<a>')
.attr( 'href', ascURL )
.html( ascText.replace(/\s/g, " ") )
.linkNoHistory();
var descLink = $('<a>')
.attr( 'href', descURL )
.html( descText.replace(/\s/g, " ") )
.linkNoHistory();
// Create the menu element
this.menu = $('<div>')
.addClass('th-sort-menu')
.appendTo($('body'))
.css({
'position': "absolute",
'display': "none",
'z-index': 3
});
// Add the required links to the menu
if ( colName === currentSortColName ) {
if ( currentSortColType == "ASC" ) {
this.menu.append(descLink);
} else {
this.menu.append(ascLink);
}
} else {
this.menu.append(ascLink).append(descLink);
}
// Add the menu to the widget and bind hover events
this.element.add(this.menu)
.delayedGroupHover({
inTime: 400,
outTime: 400,
hoverOut: this.menuHide.bind(this)
});
}
});
})(jQuery, window);
|
JavaScript
| 0.000001 |
@@ -1901,24 +1901,107 @@
mn%0A%09 if (
+ col.hasClass('rank') ) %7B%0A return 'ranking';%0A %7D else if (
col.hasClas
@@ -2545,24 +2545,173 @@
ons.type) %7B%0A
+ case 'ranking':%0A ascText = %22Sort Top to Bottom%22;%0A descText = %22Sort Bottom to Top%22;%0A break;%0A%0A
%09 case 'n
@@ -2789,24 +2789,25 @@
%22;%0A%09%09break;%0A
+%0A
%09 case 'd
@@ -2875,16 +2875,16 @@
o Old%22;%0A
-
%09%09break;
@@ -2884,16 +2884,17 @@
%09break;%0A
+%0A
%09 def
|
f62b37793fd1adb0ebb0bb9c71e490b8c7a45045
|
Add argument to toStateObject, see https://github.com/phetsims/phet-io-wrappers/issues/349
|
js/types/VoidIO.js
|
js/types/VoidIO.js
|
// Copyright 2018-2020, University of Colorado Boulder
/**
* IO Type use to signify a function has no return value.
*
* @author Sam Reid (PhET Interactive Simulations)
* @author Andrew Adare (PhET Interactive Simulations)
*/
import tandemNamespace from '../tandemNamespace.js';
import ObjectIO from './ObjectIO.js';
class VoidIO extends ObjectIO {
constructor( instance, phetioID ) {
assert && assert( false, 'should never be called' );
super( instance, phetioID );
}
/**
* @returns {undefined}
* @public
*/
static toStateObject() {
return undefined;
}
}
VoidIO.documentation = 'Type for which there is no instance, usually to mark functions without a return value';
/**
* We sometimes use VoidIO as a workaround to indicate that an argument is passed in the simulation side, but
* that it shouldn't be leaked to the PhET-iO client.
*
* @override
* @public
*/
VoidIO.validator = { isValidValue: () => true };
VoidIO.typeName = 'VoidIO';
ObjectIO.validateSubtype( VoidIO );
tandemNamespace.register( 'VoidIO', VoidIO );
export default VoidIO;
|
JavaScript
| 0 |
@@ -557,16 +557,24 @@
eObject(
+ object
) %7B%0A
|
d5ec59028a8fbcafbebedadb59c424fc42d72924
|
add loadParserSolc method to check parser, normalize solcVersion, & return parserSolc (compilerSupplier/index.js)
|
packages/truffle-compile/compilerSupplier/index.js
|
packages/truffle-compile/compilerSupplier/index.js
|
const path = require("path");
const fs = require("fs");
const semver = require("semver");
const { Docker, Local, Native, VersionRange } = require("./loadingStrategies");
class CompilerSupplier {
constructor(_config) {
_config = _config || {};
const defaultConfig = { version: "0.5.8" };
this.config = Object.assign({}, defaultConfig, _config);
this.strategyOptions = { version: this.config.version };
}
badInputError(userSpecification) {
const message =
`Could not find a compiler version matching ${userSpecification}. ` +
`compilers.solc.version option must be a string specifying:\n` +
` - a path to a locally installed solcjs\n` +
` - a solc version or range (ex: '0.4.22' or '^0.5.0')\n` +
` - a docker image name (ex: 'stable')\n` +
` - 'native' to use natively installed solc\n`;
return new Error(message);
}
async downloadAndCacheSolc(version) {
if (semver.validRange(version)) {
return await new VersionRange(this.strategyOptions).getSolcFromCacheOrUrl(
version
);
}
const message =
`You must specify a valid solc version to download` +
`Please ensure that the version you entered, ` +
`${version}, is valid.`;
throw new Error(message);
}
load() {
const userSpecification = this.config.version;
return new Promise(async (resolve, reject) => {
let strategy;
const useDocker = this.config.docker;
const useNative = userSpecification === "native";
const useSpecifiedLocal =
userSpecification && this.fileExists(userSpecification);
const isValidVersionRange = semver.validRange(userSpecification);
if (useDocker) {
strategy = new Docker(this.strategyOptions);
} else if (useNative) {
strategy = new Native(this.strategyOptions);
} else if (useSpecifiedLocal) {
strategy = new Local(this.strategyOptions);
} else if (isValidVersionRange) {
if (this.config.compilerRoots) {
this.strategyOptions.compilerRoots = this.config.compilerRoots;
}
strategy = new VersionRange(this.strategyOptions);
}
if (strategy) {
try {
const solc = await strategy.load(userSpecification);
resolve(solc);
} catch (error) {
reject(error);
}
} else {
reject(this.badInputError(userSpecification));
}
});
}
checkParser(parser) {
if (parser !== "solcjs")
throw new Error(
`Unsupported parser "${parser}" found in truffle-config.js`
);
}
fileExists(localPath) {
return fs.existsSync(localPath) || path.isAbsolute(localPath);
}
getDockerTags() {
return new Docker(this.strategyOptions).getDockerTags();
}
getReleases() {
return new VersionRange(this.strategyOptions)
.getSolcVersions()
.then(list => {
const prereleases = list.builds
.filter(build => build["prerelease"])
.map(build => build["longVersion"]);
const releases = Object.keys(list.releases);
return {
prereleases: prereleases,
releases: releases,
latestRelease: list.latestRelease
};
});
}
}
module.exports = CompilerSupplier;
|
JavaScript
| 0 |
@@ -2444,16 +2444,330 @@
);%0A %7D%0A%0A
+ async loadParserSolc(parser, solcVersion) %7B%0A if (parser) %7B%0A this.checkParser(parser);%0A const normalizedSolcVersion = semver.coerce(solcVersion).version;%0A return await new VersionRange(%7B version: normalizedSolcVersion %7D).load(%0A normalizedSolcVersion%0A );%0A %7D%0A return false;%0A %7D%0A%0A
checkP
|
f3ea8b0f0deee30dffdaf3414fb2958e1fac6435
|
Add Microsoft Edge 14 to CI
|
build/karma.ci.js
|
build/karma.ci.js
|
const path = require('path');
const istanbul = require('rollup-plugin-istanbul');
const baseConfig = require('./karma.base');
function getBuild() {
let id = `LIGHTY-PLUGIN-LEGACY - TRAVIS #${process.env.TRAVIS_BUILD_NUMBER}`;
id += ` (Branch: ${process.env.TRAVIS_BRANCH}`;
if (process.env.TRAVIS_PULL_REQUEST !== 'false') {
id += ` | PR: ${process.env.TRAVIS_PULL_REQUEST}`;
}
id += ')';
return id;
}
function getTunnel() {
return process.env.TRAVIS_JOB_NUMBER;
}
module.exports = function karma(config) {
const sauceBrowsers = {
// Chrome (last 2 versions)
sl_chrome_53: {
base: 'SauceLabs',
browserName: 'chrome',
version: '53.0',
platform: 'Windows 10',
},
sl_chrome_52: {
base: 'SauceLabs',
browserName: 'chrome',
version: '52.0',
platform: 'Windows 10',
},
// Firefox (last 2 versions)
sl_firefox_48: {
base: 'SauceLabs',
browserName: 'firefox',
version: '48.0',
platform: 'Windows 10',
},
sl_firefox_47: {
base: 'SauceLabs',
browserName: 'firefox',
version: '47.0',
platform: 'Windows 10',
},
// Edge
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
version: '13.10586',
platform: 'Windows 10',
},
// Internet Explorer (last 3 versions)
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '11.103',
platform: 'Windows 10',
},
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '10.0',
platform: 'Windows 8',
},
sl_ie_9: {
base: 'SauceLabs',
browserName: 'internet explorer',
version: '9.0',
platform: 'Windows 7',
},
// Safari (last 2 versions)
sl_safari_9: {
base: 'SauceLabs',
browserName: 'Safari',
version: '9.0',
platform: 'OS X 10.11',
},
sl_safari_8: {
base: 'SauceLabs',
browserName: 'Safari',
version: '8.0',
platform: 'OS X 10.10',
},
// iOS (last 2 major versions)
sl_ios_9: {
base: 'SauceLabs',
browserName: 'Safari',
appiumVersion: '1.5.3',
deviceName: 'iPhone Simulator',
deviceOrientation: 'portrait',
platformVersion: '9.3',
platformName: 'iOS',
},
sl_ios_8: {
base: 'SauceLabs',
browserName: 'Safari',
appiumVersion: '1.5.3',
deviceName: 'iPhone Simulator',
deviceOrientation: 'portrait',
platformVersion: '8.4',
platformName: 'iOS',
},
};
Object.assign(baseConfig, {
sauceLabs: {
testName: 'lighty-plugin-legacy',
build: getBuild(),
tunnelIdentifier: getTunnel(),
recordVideo: false,
recordScreenshots: false,
startConnect: false,
},
customLaunchers: sauceBrowsers,
browsers: Object.keys(sauceBrowsers),
reporters: ['dots', 'coverage', 'coveralls', 'saucelabs'],
coverageReporter: {
dir: path.join(__dirname, '../', 'coverage'),
reporters: [
{ type: 'text' },
{ type: 'lcov' },
],
},
concurrency: 1,
browserDisconnectTimeout: 10000,
browserDisconnectTolerance: 1,
browserNoActivityTimeout: 4 * 60 * 1000,
captureTimeout: 0,
singleRun: true,
});
baseConfig.rollupPreprocessor.plugins.unshift(istanbul({
exclude: ['node_modules/**/*.js', 'spec/**/*.js'],
}));
baseConfig.plugins.push(
'karma-sauce-launcher',
'karma-coverage',
'karma-coveralls'
);
config.set(baseConfig);
};
|
JavaScript
| 0.000013 |
@@ -1189,16 +1189,163 @@
sl_edge
+_14: %7B%0A base: 'SauceLabs',%0A browserName: 'MicrosoftEdge',%0A version: '14.14393',%0A platform: 'Windows 10',%0A %7D,%0A%0A sl_edge_13
: %7B%0A
|
48c0b064ac44157936f3a2acce695b72c8176002
|
add missing clumn
|
src/components/CreateTodos.js
|
src/components/CreateTodos.js
|
import React from 'react';
export default class CreateTodos extends React.Component {
render() {
return (
<form>
<input type="text" />
<button>Create</button>
</form>
)
}
}
|
JavaScript
| 0.999994 |
@@ -200,14 +200,15 @@
m%3E%0A )
+;
%0A %7D%0A%7D
|
5ec4d77d0eb6d56dfd5bd0ff9f98d0ca581239e1
|
set endpoint prop to not required
|
src/components/FetchSelect.js
|
src/components/FetchSelect.js
|
import React, { Component, PropTypes } from 'react'
import debounce from 'lodash/debounce'
import isFunction from 'lodash/isFunction'
import keys from 'lodash/keys'
import path from 'path'
import qs from 'qs'
import { DEFAULT_LANG } from '../utils/consts'
import Select from './Select'
import fetchJson from '../utils/fetch'
function composeFetchPath(endpoint, params = {}, searchTerm, termQuery) {
let fetchPath
let fetchParams = Object.assign({}, params)
if (searchTerm) {
if (!termQuery) throw new Error('Provide fetch.termQuery prop')
fetchParams = Object.assign(fetchParams, {
[termQuery]: searchTerm
})
}
if (keys(fetchParams)) {
fetchPath = path.join(endpoint, `?${qs.stringify(fetchParams)}`)
}
return fetchPath
}
class FetchSelect extends Component {
static defaultProps = {
search: {},
fetch: {
once: false,
requestDelay: 300,
termMinLength: 3,
}
}
static propTypes = {
error: PropTypes.oneOfType([PropTypes.string, PropTypes.bool]),
onSearchTermChange: PropTypes.func,
fetch: PropTypes.shape({
ajaxClient: PropTypes.func,
endpoint: PropTypes.string.isRequired,
minLength: PropTypes.number,
once: PropTypes.bool,
params: PropTypes.object,
requestDelay: PropTypes.number, // default: 300 (ms)
responseDataFormatter: PropTypes.func,
termQuery: PropTypes.string,
}).isRequired,
language: PropTypes.object,
search: PropTypes.object,
}
constructor(props) {
super(props)
const { fetch } = props
this.state = {
fetched: false,
error: false,
isPending: false,
options: [],
}
if (fetch.once) {
this._fetchOptions = this._fetch
} else {
this._fetchOptions = debounce(this._fetch, fetch.requestDelay)
}
this.language = this._composeLanguageObject()
}
componentDidMount = () => {
if (this.props.fetch.once) {
this._fetchOptions()
}
}
/**
* Proxy interface methods of Select component
*/
get value() {
return this.selectRef.value
}
clear() {
this.selectRef.clear()
}
_composeLanguageObject = () => {
const { language, fetch: { termMinLength: minLength = 3 } } = this.props
const lang = Object.assign({}, DEFAULT_LANG, language)
lang.minLength = lang.minLength.replace(/\$\{minLength\}/, minLength)
return lang
}
_fetch = searchTerm => {
const { fetch: { ajaxClient, endpoint, params, responseDataFormatter, termQuery, } } = this.props
if (!ajaxClient && endpoint !== 'string') {
throw new Error('You must provide endpoint to fetch options.')
}
const fetchClient = ajaxClient || fetchJson
const fetchPath = (endpoint && composeFetchPath(endpoint, params, searchTerm, termQuery)) || null
this.setState({
error: this.props.error || null,
fetched: true,
isPending: true,
})
fetchClient(fetchPath)
.then(data => {
let options = data
if (isFunction(responseDataFormatter)) {
options = data.map(responseDataFormatter)
}
this.setState({
options: this._setOptions(options),
error: false,
isPending: false,
})
})
.catch((error) => {
console.warn(error) // eslint-disable-line no-console
this.setState({
error: true,
isPending: false,
})
})
}
_getSelectRef = (node) => {
this.selectRef = node
}
_setOptions = (options) => {
this.selectRef.options = options
return options
}
_onSearchTermChange = (e) => {
const { fetch: { termMinLength = 3 }, onSearchTermChange } = this.props
const { target: { value: term } } = e
if (isFunction(onSearchTermChange)) {
onSearchTermChange(e)
}
if (term.length >= termMinLength) {
this._fetchOptions(term)
}
}
_getStatus = () => {
const { options, fetched, error, isPending } = this.state
const { fetch: { once } } = this.props
const {
minLength,
isPending: isPendingStatus,
serverError,
responseEmpty,
isEmpty
} = this.language
if (isPending) {
return isPendingStatus
}
if (!once) {
if (!fetched) {
return minLength
} else if (error) {
return serverError
}
return responseEmpty
}
if (!options.length) {
return isEmpty
}
return null
}
render() {
const { fetch: { once }, search, onSearchTermChange, ...props } = this.props // eslint-disable-line no-unused-vars
const status = this._getStatus()
return (
<Select ref={ this._getSelectRef }
search={ { show: !once, status, minimumResults: once ? search.minimumResults : undefined } }
onSearchTermChange={ this._onSearchTermChange }
{...props}/>
)
}
}
export default FetchSelect
|
JavaScript
| 0 |
@@ -1158,27 +1158,16 @@
s.string
-.isRequired
,%0A
|
6ef94a819245ecf3ebd9038fe964484d5c6366a2
|
Bring in PropTypes and and set prop type for portalTo prop
|
src/components/MXFocusTrap.js
|
src/components/MXFocusTrap.js
|
let traps = [];
const React = require('react');
const FocusTrap = require('focus-trap-react');
/**
* MXFocusTrap
*
* Why is this needed?
*
* FocusTrap does not un-pause the previous trap when the current trap is unmounted.
* This ensures that the previously trapped component is un-paused.
*/
class MXFocusTrap extends React.Component {
state = {
paused: false
}
componentWillMount () {
// FocusTrap does it's own pausing but these React components also need to be paused
traps.forEach(component => component.setState({ paused: true }));
traps.push(this);
}
componentWillUnmount () {
traps = traps.filter(component => component !== this);
const lastTrap = traps[traps.length - 1];
if (lastTrap) lastTrap.setState({ paused: false });
}
render () {
return (
<FocusTrap {...this.props} paused={this.state.paused}>
{this.props.children}
</FocusTrap>
);
}
}
module.exports = MXFocusTrap;
|
JavaScript
| 0 |
@@ -10,16 +10,57 @@
= %5B%5D;%0A%0A
+const PropTypes = require('prop-types');%0A
const Re
@@ -380,16 +380,75 @@
onent %7B%0A
+ static propTypes = %7B%0A portalTo: PropTypes.string%0A %7D%0A%0A
state
|
5c8d941cc20518aa61aefe75b3b726bb2d5b5e25
|
implement "abort"
|
httpinvoke-node.js
|
httpinvoke-node.js
|
var http = require('http');
var url = require('url');
var noop = function() {};
module.exports = function(uri, method, options) {
if(typeof method === 'undefined') {
method = 'GET';
options = {};
} else if(typeof options === 'undefined') {
if(typeof method === 'string') {
options = {};
} else {
options = method;
method = 'GET';
}
}
options = options || {};
var uploadProgressCb = options.uploading || noop;
var downloadProgressCb = options.downloading || noop;
var statusCb = options.gotStatus || noop;
var cb = options.finished || noop;
var deleteCallbacks = function() {
uploadProgressCb = null;
downloadProgressCb = null;
statusCb = null;
cb = null;
};
var input = options.input || null, inputLength = input === null ? 0 : input.length, inputHeaders = options.headers || [];
var output, outputLength, outputHeaders = {};
uri = url.parse(uri);
var req = http.request({
hostname: uri.hostname,
port: Number(uri.port),
path: uri.path,
method: method
}, function(res) {
if(cb === null) {
return;
}
uploadProgressCb(inputLength, inputLength);
statusCb(res.statusCode, res.headers);
if(typeof res.headers['content-length'] === 'undefined') {
downloadProgressCb(0, 0);
downloadProgressCb(0, 0);
cb(null, '');
return;
}
outputLength = Number(res.headers['content-length']);
downloadProgressCb(0, outputLength);
var output = '';
res.setEncoding('utf8');
res.on('data', function(chunk) {
if(cb === null) {
return;
}
downloadProgressCb(output.length, outputLength);
output += chunk;
});
res.on('end', function() {
if(cb === null) {
return;
}
downloadProgressCb(outputLength, outputLength);
cb(null, output);
});
});
setTimeout(function() {
uploadProgressCb(0, inputLength);
}, 0);
if(input !== null) {
req.write(input);
}
req.on('error', function(e) {
cb(e);
deleteCallbacks();
});
req.end();
return function() {
// TODO implement abort function
};
};
|
JavaScript
| 0.000001 |
@@ -646,166 +646,8 @@
op;%0A
- var deleteCallbacks = function() %7B%0A uploadProgressCb = null;%0A downloadProgressCb = null;%0A statusCb = null;%0A cb = null;%0A %7D;%0A
@@ -1972,32 +1972,88 @@
ut(function() %7B%0A
+ if(cb === null) %7B%0A return;%0A %7D%0A
uploadPr
@@ -2192,129 +2192,348 @@
-cb(e);%0A deleteCallbacks();%0A %7D);%0A req.end();%0A return function() %7B%0A // TODO impl
+if(cb === null) %7B%0A return;%0A %7D%0A cb(e);%0A cb = null;%0A %7D);%0A req.end();%0A return function() %7B%0A if(cb === null) %7B%0A return;%0A %7D%0A%0A // these stat
ement
+s
a
-bort function
+re in case %22abort%22 is called in %22finished%22 callback%0A var _cb = cb;%0A cb = null;%0A _cb(new Error('abort'));
%0A
|
bb5ad08067bad31c299e4a99d498cdf396b1e6ce
|
add lyric_engine back to functions
|
functions/api/lyric/get/[url].js
|
functions/api/lyric/get/[url].js
|
// const engine = require('../../../../lyric_engine_js');
// eslint-disable-next-line import/prefer-default-export
export async function onRequestGet({ params }) {
const { url } = params;
const out = {
lyric: `Failed to find lyric of ${url}`,
};
try {
// const lyric = await engine.get_full(url);
// out.lyric = lyric;
} catch (error) {
console.log(`something wrong, error: ${error}`);
}
// eslint-disable-next-line no-undef
return new Response(JSON.stringify(out));
}
|
JavaScript
| 0.000002 |
@@ -1,15 +1,12 @@
-//
const engine
@@ -258,19 +258,16 @@
ry %7B%0A
- //
const l
@@ -304,19 +304,16 @@
rl);%0A
- //
out.lyr
|
286a892bdd63e9f8c280dd7440bf2a0d8dba7f0c
|
set state on storymedia component
|
src/components/story_media.js
|
src/components/story_media.js
|
import React from "react";
import { render } from "react-dom";
import YouTube from "react-youtube";
class StoryMedia extends React.Component {
render () {
return (
<div id="story-media">
{this.renderImages()}
{this.renderVideo()}
</div>
);
}
renderImages () {
var images = [];
this.props.story.images.forEach((image, index) => (
images.push (
<div
className={"row media-row" + this.toggleMediaHiding(index)}
key={index}>
<img src={image} />
</div>
)));
return images;
}
toggleMediaHiding = (index) => index === 0 ? "" : "hidden";
renderVideo () {
if (this.props.story.video) {
return (
<div className="row media-row">
<YouTube
videoId={this.props.story.video}
className="video-container" />
</div>
);
}
}
}
export default StoryMedia;
|
JavaScript
| 0 |
@@ -277,16 +277,64 @@
);%0A %7D%0A%0A
+ static defaultProps = %7B%0A show: false%0A %7D;%0A%0A
render
@@ -490,16 +490,17 @@
edia-row
+
%22 + this
@@ -613,26 +613,202 @@
-return images;%0A %7D
+ images.splice(1, 0, this.showMoreButton());%0A return images;%0A %7D%0A%0A showMoreButton () %7B%0A return (%0A %3Cbutton onClick=%7B() =%3E this.setState(%7Bshow: true%7D)%7D%3EShow more!%3C/button%3E%0A );%0A %7D%0A
%0A%0A
|
af8e0c8f16ce604b6569aef275a3d7ac017d6f92
|
remove useless dependency from index to ngSanitize
|
share/nitweb/javascripts/index.js
|
share/nitweb/javascripts/index.js
|
/*
* Copyright 2016 Alexandre Terrasa <[email protected]>.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function() {
angular
.module('index', ['ngSanitize'])
.config(function($stateProvider, $locationProvider) {
$stateProvider
.state('index', {
url: '/',
templateUrl: 'views/index.html',
controller: 'IndexCtrl',
controllerAs: 'indexCtrl'
})
})
.factory('Catalog', [ '$http', function($http) {
return {
loadHightlighted: function(cb, cbErr) {
$http.get('/api/catalog/highlighted')
.success(cb)
.error(cbErr);
},
loadMostRequired: function(cb, cbErr) {
$http.get('/api/catalog/required')
.success(cb)
.error(cbErr);
},
loadByTags: function(cb, cbErr) {
$http.get('/api/catalog/bytags')
.success(cb)
.error(cbErr);
},
loadStats: function(cb, cbErr) {
$http.get('/api/catalog/stats')
.success(cb)
.error(cbErr);
},
loadContributors: function(cb, cbErr) {
$http.get('/api/catalog/contributors')
.success(cb)
.error(cbErr);
},
}
}])
.controller('IndexCtrl', function(Catalog, $sce, $scope, $location, $anchorScroll) {
this.loadHighlighted = function() {
Catalog.loadHightlighted(
function(data) {
$scope.highlighted = data;
}, function(err) {
$scope.error = err;
});
};
this.loadMostRequired = function() {
Catalog.loadMostRequired(
function(data) {
$scope.required = data;
}, function(err) {
$scope.error = err;
});
};
this.loadByTags = function() {
Catalog.loadByTags(
function(data) {
$scope.bytags = data;
}, function(err) {
$scope.error = err;
});
};
this.loadStats = function() {
Catalog.loadStats(
function(data) {
$scope.stats = data;
}, function(err) {
$scope.error = err;
});
};
this.loadContributors = function() {
Catalog.loadContributors(
function(data) {
$scope.contributors = data;
}, function(err) {
$scope.error = err;
});
};
this.scrollTo = function(hash) {
$anchorScroll(hash);
}
this.loadHighlighted();
this.loadStats();
this.loadContributors();
})
.directive('contributorList', function(Model) {
return {
restrict: 'E',
scope: {
listId: '@',
listTitle: '@',
listContributors: '='
},
templateUrl: '/directives/contributor-list.html'
};
})
})();
|
JavaScript
| 0 |
@@ -668,20 +668,8 @@
', %5B
-'ngSanitize'
%5D)%0A%0A
|
9df1a132b27b9a6aad1d3e2025d4d857eb2c0eda
|
change style
|
static/js/index.js
|
static/js/index.js
|
/**
* 页面ready方法
*/
$(document).ready(function() {
categoryDisplay();
generateContent();
backToTop();
});
/**
* 分类展示
* 点击右侧的分类展示时
* 左侧的相关裂变展开或者收起
* @return {[type]} [description]
*/
function categoryDisplay() {
if(location.hash){
var cate = location.hash;
$('.post-list-body>article[data-category!=' + cate + ']').hide();
$('.post-list-body>article[data-category=' + cate + ']').show();
}
/*show category when click categories list*/
$('.categories-list-item').click(function() {
var cate = $(this).attr('cate'); //get category's name
if(cate === 'All'){
$('.post-list-body article').show();
location.hash = '';
}else{
$('.post-list-body>article[data-category!=' + cate + ']').hide();
$('.post-list-body>article[data-category=' + cate + ']').show();
location.hash = cate;
}
});
}
/**
* 回到顶部
*/
function backToTop() {
//滚页面才显示返回顶部
$(window).scroll(function() {
if ($(window).scrollTop() > 100) {
$("#top").fadeIn(500);
} else {
$("#top").fadeOut(500);
}
});
//点击回到顶部
$("#top").click(function() {
$("body").animate({
scrollTop: "0"
}, 500);
});
//初始化tip
$(function() {
$('[data-toggle="tooltip"]').tooltip();
});
}
/**
* 侧边目录
*/
function generateContent() {
// console.log($('#markdown-toc').html());
if (typeof $('#markdown-toc').html() === 'undefined') {
// $('#content .content-text').html('<ul><li>文本较短,暂无目录</li></ul>');
$('#content').hide();
$('#myArticle').removeClass('col-sm-9').addClass('col-sm-12');
} else {
$('#content .content-text').html('<ul>' + $('#markdown-toc').html() + '</ul>');
/* //数据加载完成后,加固定边栏
$('#myAffix').attr({
'data-spy': 'affix',
'data-offset': '50'
});*/
}
}
|
JavaScript
| 0.000001 |
@@ -285,16 +285,32 @@
ion.hash
+.replace('#','')
;%0A
@@ -456,20 +456,16 @@
;%0A %7D%0A
-
%0A /*s
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.