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
|
---|---|---|---|---|---|---|---|
70344aca366c5dbde0a8331f221b1abf0b7c5d26
|
Remove unneeded concat
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var config = {
directory: "./",
js: "js/app.js",
css: "css/app.css",
icons: "node_modules/geomicons-open/icons/*.svg"
};
function build() {
var nunjucks = require('static-engine-renderer-nunjucks');
var render = require('static-engine-render');
var page;
nunjucks.configure('./templates/', {
autoescape: true
});
render.configure('./');
page = render('/index.html', nunjucks('index.html'));
return page([{}]);
}
function css(){
var autoprefixer = require('gulp-autoprefixer');
var uncss = require('gulp-uncss');
var minifycss = require('gulp-minify-css');
var glob = require('glob');
var rework = require('gulp-rework');
var concat = require('gulp-concat');
var calc = require('rework-calc');
var media = require('rework-custom-media');
var npm = require('rework-npm');
var vars = require('rework-vars');
var colors = require('rework-plugin-colors');
var tap = require('gulp-tap');
var cheerio = require('gulp-cheerio');
return gulp.src(config.css)
.pipe(rework(
npm(),
vars(),
media(),
calc,
colors()
))
.pipe(autoprefixer('> 1%', 'last 2 versions'))
.pipe(concat("index.css"))
.pipe(uncss({
html: glob.sync('index.html')
}))
.pipe(minifycss())
.pipe(tap(function(file){
return gulp.src('index.html')
.pipe(cheerio(function($){
$('head').append('<style type="text/css">'+file.contents+'</style>');
}))
.pipe(gulp.dest(config.directory));
}));
}
function js() {
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var tap = require('gulp-tap');
var cheerio = require('gulp-cheerio');
var browserify = require('gulp-browserify');
return gulp.src(config.js)
.pipe(browserify())
.pipe(concat("index.js"))
.pipe(uglify({
preserveComments: 'some'
}))
.pipe(tap(function(file){
return gulp.src('index.html')
.pipe(cheerio(function($){
$('body').append('<script>'+file.contents+'</script>');
}))
.pipe(gulp.dest(config.directory));
}));
}
function html(){
var htmlmin = require('gulp-htmlmin');
var cheerio = require('gulp-cheerio');
return gulp.src('index.html')
.pipe(htmlmin({
collapseWhitespace: true
}))
.pipe(cheerio(function ($) {
var uses = [];
$('use').each(function(){
uses.push($(this).attr('xlink:href'));
});
$('path[id]').each(function(){
if(uses.indexOf('#'+$(this).attr('id')) < 0) {
$(this).replaceWith('');
}
});
}))
.pipe(gulp.dest(config.directory));
}
function icons() {
var cheerio = require('gulp-cheerio');
var concat = require('gulp-concat');
var footer = require('gulp-footer');
var header = require('gulp-header');
return gulp.src(config.icons)
.pipe(cheerio(function ($) {
var $path = $('svg').children('path');
var id = $('svg').attr('id');
$path.attr('id', id);
$('svg').replaceWith($path[0]);
}))
.pipe(concat('icons.svg'))
.pipe(header(
'<svg xmlns="http://www.w3.org/2000/svg" width="0" height="0"><defs>'
))
.pipe(footer('</defs></svg>'))
.pipe(gulp.dest('templates/temp'));
}
gulp.task('default', gulp.series(icons, build, html, gulp.parallel(css, js)));
gulp.task('watch', function() {
gulp.watch(['css/**/**.css', 'js/**/**.js', 'templates/**/**.html'], 'default');
});
gulp.task('serve', gulp.parallel('default', 'watch', function(done){
var express = require('express');
var static = require('express-static');
var logger = require('express-log');
var app = express();
app.use(logger());
app.use(static(config.directory));
app.use(function(req, res, next){
res.redirect('/');
});
var server = app.listen(8080, function(){
console.log('server is running at %s', server.address().port);
});
done();
}));
|
JavaScript
| 0.000008 |
@@ -2005,42 +2005,8 @@
())%0A
- .pipe(concat(%22index.js%22))%0A
|
9c5524dfda86e96fbae39f0777883a9efaecf2e1
|
fix cssClasses in status component
|
app/assets/javascripts/vue_pipelines_index/status.js.es6
|
app/assets/javascripts/vue_pipelines_index/status.js.es6
|
/* global Vue, gl */
/* eslint-disable no-param-reassign */
((gl) => {
gl.VueStatusScope = Vue.extend({
props: [
'pipeline', 'svgs', 'match',
],
computed: {
cssClasses() {
const cssObject = {};
cssObject['ci-status'] = true;
cssObject[`ci-${this.pipeline.details.status.group}`] = true;
return cssObject;
},
svg() {
return this.svgs[this.match(this.pipeline.details.status.icon)];
},
detailsPath() {
const { status } = this.pipeline.details;
return status.has_details ? status.details_path : false;
},
},
template: `
<td class="commit-link">
<a
:class='cssClasses'
:href='detailsPath'
v-html='svg + pipeline.details.status.text'
>
</a>
</td>
`,
});
})(window.gl || (window.gl = {}));
|
JavaScript
| 0.000001 |
@@ -223,29 +223,9 @@
= %7B
-%7D;%0A cssObject%5B
+
'ci-
@@ -231,24 +231,24 @@
-status'
-%5D =
+:
true
+ %7D
;%0A
|
177728115aafe629e6cf5fbd613e9525bf389efb
|
Add SSO screens for socialOrDatabase mode
|
src/compound-mode/social-or-database/mode.js
|
src/compound-mode/social-or-database/mode.js
|
import Mode from '../../lock/mode';
import { initSocial } from '../../social/index';
import { getScreen, initDatabase } from '../../database/index';
import AskSocialNetworkOrLogin from '../../cred/or/ask_social_network_or_login';
import ResetPassword from '../../database/reset_password';
import SignUp from '../../database/sign_up';
import dict from './dict';
export default class SocialOrDatabaseMode extends Mode {
constructor() {
super("socialOrDatabase", dict);
}
didInitialize(model, options) {
model = model.set("forceRedirect", !options.popup);
model = initSocial(model, options);
model = initDatabase(model, options);
this.setModel(model);
}
render(lock) {
const screen = getScreen(lock);
switch(screen) {
case "login":
return new AskSocialNetworkOrLogin();
case "signUp":
return new SignUp();
case "resetPassword":
return new ResetPassword();
default: // TODO: show a crashed screen.
throw new Error("unknown screen");
}
}
}
|
JavaScript
| 0 |
@@ -138,24 +138,81 @@
ase/index';%0A
+import %7B renderSSOScreens %7D from '../../lock/sso/index';%0A
import AskSo
@@ -746,24 +746,108 @@
der(lock) %7B%0A
+ const ssoScreen = renderSSOScreens(lock);%0A if (ssoScreen) return ssoScreen;%0A%0A
const sc
|
a6cda286d86270153fc2449d4cd728c62d0027c6
|
Support running `firebase serve` from subdirectories. (#294)
|
commands/serve.js
|
commands/serve.js
|
'use strict';
var chalk = require('chalk');
var RSVP = require('rsvp');
var superstatic = require('superstatic').server;
var Command = require('../lib/command');
var FirebaseError = require('../lib/error');
var logger = require('../lib/logger');
var utils = require('../lib/utils');
var requireConfig = require('../lib/requireConfig');
var checkDupHostingKeys = require('../lib/checkDupHostingKeys');
var MAX_PORT_ATTEMPTS = 10;
var _attempts = 0;
var startServer = function(options) {
var config = options.config ? options.config.get('hosting') : {public: '.'};
var server = superstatic({
debug: true,
port: options.port,
host: options.host,
config: config,
stack: 'strict'
}).listen(function() {
if (config.public && config.public !== '.') {
logger.info(chalk.bold('Public Directory:'), config.public);
}
logger.info();
logger.info('Server listening at: ' + chalk.underline(chalk.bold('http://' + options.host + ':' + options.port)));
});
server.on('error', function(err) {
if (err.code === 'EADDRINUSE') {
var message = 'Port ' + options.port + ' is not available.';
if (_attempts < MAX_PORT_ATTEMPTS) {
utils.logWarning(message + ' Trying another port...');
options.port++;
_attempts++;
startServer(options);
} else {
utils.logWarning(message);
throw new FirebaseError('Could not find an open port for development server.', {exit: 1});
}
} else {
throw new FirebaseError('An error occurred while starting the development server:\n\n' + err.toString(), {exit: 1});
}
});
};
module.exports = new Command('serve')
.description('start a local server for your static assets')
.option('-p, --port <port>', 'the port on which to listen (default: 5000)', 5000)
.option('-o, --host <host>', 'the host on which to listen (default: localhost)', 'localhost')
.before(requireConfig)
.before(checkDupHostingKeys)
.action(function(options) {
logger.info('Starting Firebase development server...');
logger.info();
if (options.config) {
logger.info(chalk.bold('Project Directory:'), options.config.projectDir);
} else {
utils.logWarning('No Firebase project directory detected. Serving static content from ' + chalk.bold(options.cwd || process.cwd()));
}
startServer(options);
return new RSVP.Promise(function(resolve) {
process.on('SIGINT', function() {
logger.info('Shutting down...');
resolve();
});
});
});
|
JavaScript
| 0 |
@@ -153,24 +153,85 @@
/command');%0A
+var detectProjectRoot = require('../lib/detectProjectRoot');%0A
var Firebase
@@ -737,16 +737,57 @@
config,%0A
+ cwd: detectProjectRoot(options.cwd),%0A
stac
|
ea7a4bef94a22665f6f9bd979dc00b719d1c469b
|
change build files names from domc to dwayne.
|
gulpfile.js
|
gulpfile.js
|
const gulp = require('gulp');
const _ = require('lodash');
const webpack = require('webpack');
const webpackStream = require('webpack-stream');
const WebpackDevServer = require('webpack-dev-server');
const run = require('gulp-run');
const server = require('./server');
const webpackConfig = require('./webpack.config');
const serverConfig = require('./config.json');
const modules = [
'',
'D',
'Alphabet',
'Arr',
'BlobObject',
'Dat',
'Elem',
'Fetch',
'Func',
'Num',
'Promise',
'Router',
'Str',
'Super',
'Switcher'
];
gulp.task('default', (callback) => {
new WebpackDevServer(webpack(webpackConfig), {
stats: {
colors: true
}
}).listen(serverConfig.webpackDevServer.port, 'localhost', callback);
});
gulp.task('build', ['build:default', 'build:min']);
gulp.task('jsdoc', ['test-server', 'jsdoc:compile'], () => (
gulp.watch(['./lib/**/*.js'], ['jsdoc:compile'])
));
gulp.task('jsdoc:public', ['test-server', 'jsdoc:public:compile'], () => (
gulp.watch(['./lib/**/*.js'], ['jsdoc:public:compile'])
));
modules.forEach((module) => {
const taskName = `test${ module ? `:${ module }` : '' }`;
const deps = module === 'Fetch' || !module ? ['test-server'] : [];
gulp.task(taskName, deps, (callback) => {
const fileName = module || 'all';
const config = _.cloneDeep(webpackConfig);
config.entry = [
`mocha!./test/${ fileName }.js`,
'./browser.js'
];
new WebpackDevServer(webpack(config), {
stats: {
colors: true
}
}).listen(serverConfig.webpackTestServer.port, 'localhost', callback);
});
});
gulp.task('test-server', () =>
server(serverConfig.testServer.port)
);
gulp.task('build:default', () => {
const config = _.cloneDeep(webpackConfig);
delete config.devtool;
config.output.filename = 'domc.js';
return gulp.src('./browser.js')
.pipe(webpackStream(config))
.pipe(gulp.dest('./'));
});
gulp.task('build:min', () => {
const config = _.cloneDeep(webpackConfig);
delete config.devtool;
config.output.filename = 'domc.min.js';
config.plugins.push(new webpack.optimize.UglifyJsPlugin());
return gulp.src('./browser.js')
.pipe(webpackStream(config))
.pipe(gulp.dest('./'));
});
gulp.task('jsdoc:compile', () => (
run('./node_modules/jsdoc/jsdoc.js -c conf.json').exec()
));
gulp.task('jsdoc:public:compile', () => (
run('./node_modules/jsdoc/jsdoc.js -c conf.public.json').exec()
));
|
JavaScript
| 0 |
@@ -1767,34 +1767,8 @@
);%0A%0A
- delete config.devtool;%0A%0A
co
@@ -1792,19 +1792,21 @@
ame = 'd
-omc
+wayne
.js';%0A%0A
@@ -1985,34 +1985,8 @@
);%0A%0A
- delete config.devtool;%0A%0A
co
@@ -2014,11 +2014,13 @@
= 'd
-omc
+wayne
.min
|
2c8bb31190bc7c250847a48bf6da024cfb27e6e3
|
Update jquerytest.js
|
js/jquerytest.js
|
js/jquerytest.js
|
/*function jquerytest(){
var ww = $(window).width();
if(ww<0){
alert("This window is impossibly small");
}else{
alert("This is a jquery test. Would you like your " + ww + " pixel window washed?");
}
return ww;
};
*/
var logo = $('.site-avatar');
function tw(){
TweenMax.to(logo, 3, {
display:'block',
position:'relative',
'z-index':4,
left:'100%,
ease:Bounce.easeInOut
})
}
$('.site-info').click( function() {
tw();
});
|
JavaScript
| 0.000001 |
@@ -369,16 +369,17 @@
ft:'100%25
+'
,%0A%09%09ease
|
7e53a2fea4d88ea0ba7162fd878e9cf2d1bce9c1
|
Fix a typo
|
gulp-tasks/sync.js
|
gulp-tasks/sync.js
|
// JavaScript Document
// Scripts written by __gulp_init_author_name__ @ __gulp_init_author_company__
module.exports = {
sync(gulp, plugins, custom_notifier) {
// retrieve the version number
const BROWSERSYNC_VERSION = require("browser-sync/package.json").version;
// set up function for adding custom headers
const BROWSERSYNC_HEADER = (proxyReq) => {
proxyReq.setHeader("X-BrowserSync-Port", global.settings.browsersync.port);
proxyReq.setHeader("X-BrowserSync-Version", BROWSERSYNC_VERSION);
};
if (global.settings.browsersync.proxy !== false) {
// convert proxy to an object if it's a string
if (typeof global.settings.browsersync.proxy !== "object") {
global.settings.browsersync.proxy = {
"target": global.settings.browsersync.proxy,
};
}
// // if proxyReq is undefined, define it as an empty array
if (!("proxyReq" in global.settings.browsersync.proxy)) {
global.settings.browsersync.proxy.proxyReq = [];
}
// add the custom headers to the proxyReq array
global.settings.browsersync.proxy.proxyReq.push(BROWSERSYNC_HEADER);
// run BrowserSync
return plugins.browser_sync(global.settings.browsersync);
} else {
return gulp.src(".config/.bsconfig")
.pipe(plugins.notify({
appIcon: plugins.path.resolve("./src/assets/media/logo-favicon.png"),
title: "Error!",
message: "\x1b[31mNo proxy is defined in .bsconfig! Try running gulp config --browsersync",
notifier: process.env.BURNTTOAST === "true" ? custom_notifier : false,
}));
}
}
};
|
JavaScript
| 1 |
@@ -899,36 +899,32 @@
;%0A %7D%0A
-
%0A //
@@ -922,19 +922,16 @@
//
- //
if prox
@@ -1127,20 +1127,16 @@
%7D%0A
-
%0A
@@ -1269,28 +1269,16 @@
EADER);%0A
-
%0A
|
84161e30f98352652a8e2746431534287123ea06
|
Change MessageHandler options to messageHandlerOptions from messageHandler
|
lib/Nagato.js
|
lib/Nagato.js
|
const Eris = require("eris"),
Logger = require("./Logger"),
MessageHandler = require("./MessageHandler"),
reload = require("require-reload")(require);
class Nagato extends Eris.Client {
constructor(options) {
super(options.Token, options.Eris);
this.admins = options.Admins;
this.messageHandler = options.MessageHandler;
if(!this.messageHandler.allowedBots) this.messageHandler.allowedBots = [];
this.help = options.Help;
if (!this.help.helpCommands) this.help.helpCommands = ["help"];
this.log = new Logger(options.Logger);
this.messageHandler = new MessageHandler(this);
this.on("ready", () => {
this.messageHandler.start();
this.log.info("Bot is now Ready and Connected to Discord");
});
this.on("error", (error, id) => {
this.log.error(`Error: Shard ${id} - ${error.stack}`);
});
this.on("warn", (message, id) => {
this.log.warn(`Warning: Shard ${id} - ${message}`);
});
this.on("debug", (message, id) => {
this.log.debug(`Debug: ${id != null ? "Shard " + id + " - " : ""}${message}`);
})
this.on("shardReady", (id) => {
this.log.info(`Shard ${id} is Now Ready`)
});
this.on("shardDisconnect", (error, id) => {
this.log.warn(`Shard ${id} has Disconnected` + (error ? ": " + error.message : ""));
});
this.on("shardResume", (id) => {
this.log.warn(`Shard ${id} has Resumed`);
});
this.on("disconnect", () => {
this.log.error("Bot has now Disconnected from Discord");
});
}
loadCommands(commandsFolder) {
new(reload("./Utils/CommandLoader"))(this, commandsFolder).load().then((response) => {
this.commands = response.commands;
this.commandAliases = response.commandAliases;
}).catch(err => this.log.error(err));
}
reloadCommands(commandsFolder) {
reload.emptyCache("./Utils/CommandLoader");
this.commands = undefined;
this.commandAliases = undefined;
new(reload("./Utils/CommandLoader"))(this, commandsFolder).load().then((response) => {
this.commands = response.commands;
this.commandAliases = response.commandAliases;
}).catch(err => this.log.error(err));
}
loadEvents(eventsFolder) {
new(reload("./Utils/EventLoader"))(this, eventsFolder).load().then((response) => {
this.events = response;
for (var event in this.events) {
this.events[event].load();
}
}).catch(err => this.log.error(err));
}
reloadEvents(eventsFolder) {
reload.emptyCache("./Utils/EventLoader");
for (var event in this.events) {
this.events[event].remove();
}
this.events = undefined;
new(reload("./Utils/EventLoader"))(this, eventsFolder).load().then((response) => {
this.events = response;
for (var event in this.events) {
this.events[event].load();
}
}).catch(err => this.log.error(err));
}
}
module.exports = Nagato;
|
JavaScript
| 0 |
@@ -330,16 +330,23 @@
eHandler
+Options
= optio
@@ -387,32 +387,39 @@
s.messageHandler
+Options
.allowedBots) th
@@ -435,16 +435,23 @@
eHandler
+Options
.allowed
|
34bfdb8404d7ccab2cd88e96ee5b814e8a380220
|
Update setup to remove link
|
commands/setup.js
|
commands/setup.js
|
module.exports = {
name:'setup',
description:'Runs clone and then install to get your environment ready for action.',
cmd:cmd
}
function cmd(bosco, args) {
var clone = require('./clone');
var install = require('./install');
var team = require('./team');
var link = require('./link');
team.cmd(bosco, ['sync'], function() {
team.cmd(bosco, ['setup'], function() {
clone.cmd(bosco, [], function() {
link.cmd(bosco, [], function() {
install.cmd(bosco, args);
});
});
});
});
}
|
JavaScript
| 0 |
@@ -277,42 +277,8 @@
m');
-%0A var link = require('./link');
%0A%0A
@@ -397,33 +397,32 @@
%5B%5D, function() %7B
-%0A
link
@@ -421,45 +421,9 @@
-link.cmd(bosco, %5B%5D, function() %7B%0A
+%0A
@@ -455,17 +455,16 @@
, args);
-%0A
@@ -463,27 +463,24 @@
-%7D);
%0A %7D);
|
ace141d9a55e529dad64bd00620d326c8e3e91cc
|
return match as boolean
|
src/helper/compare.js
|
src/helper/compare.js
|
/*
* This File contains Helpers for Comparison of Objects.
*/
const logger = require('../logger');
const ObjectId = {
/**
* Compares a list of at least two ObjectIds to equal each other.
*
* @param {...ObjectId|String} args
* @returns {Boolean}
*/
equal(...args) {
if (!args || args.length < 2) throw new Error('could not compare less than two id\'s');
const [firstId, ...otherIds] = args;
const firstIdAsString = String(firstId);
if (!ObjectId.isValid(firstIdAsString)) {
logger.warning('received invalid object ids to compare', args);
return false;
}
return otherIds.every((id) => firstIdAsString === String(id));
},
/**
*
* @param {ObjectId|String} id
*/
isValid(id) {
const idAsString = typeof id === 'string' ? id : String(id);
return idAsString.match('^[0-9a-f]{24}$');
},
};
module.exports = { ObjectId };
|
JavaScript
| 0.999999 |
@@ -784,41 +784,40 @@
urn
-idAsString.match('%5E%5B0-9a-f%5D%7B24%7D$'
+/%5E%5B0-9a-f%5D%7B24%7D$/.test(idAsString
);%0A%09
|
408e1b7e2749bf201b934d52d875c25ead2484cb
|
fix for #711
|
src/components/forms/TextField.js
|
src/components/forms/TextField.js
|
import Input from '../../mixins/input'
export default {
name: 'text-field',
mixins: [Input],
data () {
return {
hasFocused: false,
inputHeight: null
}
},
props: {
autofocus: Boolean,
autoGrow: Boolean,
counter: Boolean,
fullWidth: Boolean,
id: String,
name: String,
maxlength: [Number, String],
max: [Number, String],
min: [Number, String],
step: [Number, String],
multiLine: Boolean,
prefix: String,
readonly: Boolean,
rows: {
default: 5
},
singleLine: Boolean,
suffix: String,
type: {
type: String,
default: 'text'
}
},
computed: {
classes () {
return {
'input-group--text-field': true,
'input-group--single-line': this.singleLine,
'input-group--multi-line': this.multiLine,
'input-group--full-width': this.fullWidth
}
},
hasError () {
return this.errorMessages.length > 0 ||
!this.counterIsValid() ||
!this.validateIsValid() ||
this.error
},
count () {
const inputLength = (this.inputValue && this.inputValue.toString() || '').length
let min = inputLength
if (this.counterMin !== 0 && inputLength < this.counterMin) {
min = this.counterMin
}
return `${min} / ${this.counterMax}`
},
counterMin () {
const parsedMin = Number.parseInt(this.min, 10)
return Number.isNaN(parsedMin) ? 0 : parsedMin
},
counterMax () {
const parsedMax = Number.parseInt(this.max, 10)
return Number.isNaN(parsedMax) ? 25 : parsedMax
},
inputValue: {
get () {
return this.value
},
set (val) {
if (this.modifiers.trim) {
val = val.trim()
}
if (this.modifiers.number) {
val = Number(val)
}
if (!this.modifiers.lazy) {
this.$emit('input', val)
}
this.lazyValue = val
}
},
isDirty () {
return this.lazyValue !== null &&
typeof this.lazyValue !== 'undefined' &&
this.lazyValue.toString().length > 0
}
},
watch: {
focused (val) {
this.hasFocused = true
!val && this.$emit('change', this.lazyValue)
},
value () {
this.lazyValue = this.value
this.validate()
this.multiLine && this.autoGrow && this.calculateInputHeight()
}
},
mounted () {
this.$vuetify.load(() => {
this.multiLine && this.autoGrow && this.calculateInputHeight()
this.autofocus && this.focus()
})
},
methods: {
calculateInputHeight () {
const height = this.$refs.input.scrollHeight
const minHeight = this.rows * 24
this.inputHeight = height < minHeight ? minHeight : height
},
onInput (e) {
this.inputValue = e.target.value
this.multiLine && this.autoGrow && this.calculateInputHeight()
},
blur (e) {
this.validate()
this.$nextTick(() => (this.focused = false))
this.$emit('blur', e)
},
focus (e) {
this.focused = true
this.$refs.input.focus()
this.$emit('focus', e)
},
genCounter () {
return this.$createElement('div', {
'class': {
'input-group__counter': true,
'input-group__counter--error': !this.counterIsValid()
}
}, this.count)
},
genInput () {
const tag = this.multiLine ? 'textarea' : 'input'
const data = {
style: {
'height': this.inputHeight && `${this.inputHeight}px`
},
domProps: {
disabled: this.disabled,
required: this.required,
value: this.lazyValue,
autofucus: this.autofocus
},
attrs: {
tabindex: this.tabindex,
readonly: this.readonly
},
on: {
blur: this.blur,
input: this.onInput,
focus: this.focus
},
ref: 'input'
}
if (this.placeholder) data.domProps.placeholder = this.placeholder
if (this.autocomplete) data.domProps.autocomplete = true
if (this.name) data.attrs.name = this.name
if (this.maxlength) data.attrs.maxlength = this.maxlength
if (this.id) data.domProps.id = this.id
if (this.step) data.attrs.step = this.step
if (!this.counter) {
if (this.max) data.attrs.max = this.max
if (this.min) data.attrs.min = this.min
}
if (this.multiLine) {
data.domProps.rows = this.rows
} else {
data.domProps.type = this.type
}
const children = [this.$createElement(tag, data)]
this.prefix && children.unshift(this.genFix('prefix'))
this.suffix && children.push(this.genFix('suffix'))
return children
},
genFix (type) {
return this.$createElement('span', {
'class': `input-group--text-field__${type}`
}, this[type])
},
counterIsValid: function counterIsValid () {
const val = (this.inputValue && this.inputValue.toString() || '')
return (!this.counter ||
(val.length >= this.counterMin && val.length <= this.counterMax)
)
},
validateIsValid () {
return (!this.required ||
(this.required &&
this.isDirty) ||
!this.hasFocused ||
(this.hasFocused && this.focused))
}
},
render () {
return this.genInputGroup(this.genInput(), { attrs: { tabindex: -1 }})
}
}
|
JavaScript
| 0 |
@@ -5442,10 +5442,13 @@
ex:
--1
+false
%7D%7D)
|
f82fabf6bcf161d62e2f89a603a60f0efc7b4c00
|
Update script.js
|
js/bin/script.js
|
js/bin/script.js
|
$(document).ready(function () {
$('.parallax').parallax();
$(".button-collapse").sideNav({edge:'right',closeOnClick: true });
$('.materialboxed').materialbox();
$('#about-me h6').css('line-height','25px');
$('#about-me h6, #projects .card-reveal p').addClass('pink-text text-darken-3');
$('#about-me a, #projects h2 a').addClass('grey-text text-darken-4');
$('footer a').addClass('grey-text text-lighten-4');
$('footer a').hover(function(){$(this).toggleClass('text-darken-4')});
$('#mobile-demo, body').css('background-color','#fcfcfc');
$('figure img').css('border','5px solid #ad1658');
$('#skills li').addClass('chip');
$('#about-me .chip').addClass('waves-effect');
$('.card').css('padding','0');
$('.scrollspy').scrollSpy({scrollOffset:0});
$('#pinpush').pushpin({ top:550});//550
$('#close-menu').click(function(){ $('#pinpush').fadeOut(); });
$('i').addClass('fa');
$('#header nav, span.badge, .floating, .page-footer, #pinpush, #mobile-demo').addClass('pink pink-lighten-3');
$('footer li a, footer p').addClass('grey-text text-lighten-3');
$('footer h5').addClass('white-text');
$('img').addClass('responsive-img');
$('.card-image').addClass('waves-effect waves-block waves-light');
$('.card-image img').addClass('activator');
});
|
JavaScript
| 0.000002 |
@@ -1032,27 +1032,12 @@
ss('
-pink pink-lighten-3
+blue
');%0A
@@ -1311,8 +1311,9 @@
r');%0A%7D);
+%0A
|
c5336833caf66510ab5df9b37becf51934069482
|
fix lint
|
src/components/legend/defaults.js
|
src/components/legend/defaults.js
|
/**
* Copyright 2012-2018, Plotly, Inc.
* All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var Registry = require('../../registry');
var Lib = require('../../lib');
var Template = require('../../plot_api/plot_template');
var attributes = require('./attributes');
var basePlotLayoutAttributes = require('../../plots/layout_attributes');
var helpers = require('./helpers');
module.exports = function legendDefaults(layoutIn, layoutOut, fullData) {
var containerIn = layoutIn.legend || {};
var legendTraceCount = 0;
var legendReallyHasATrace = false;
var defaultOrder = 'normal';
var defaultX, defaultY, defaultXAnchor, defaultYAnchor;
for(var i = 0; i < fullData.length; i++) {
var trace = fullData[i];
if(!trace.visible) continue;
// Note that we explicitly count any trace that is either shown or
// *would* be shown by default, toward the two traces you need to
// ensure the legend is shown by default, because this can still help
// disambiguate.
if(trace.showlegend || trace._dfltShowLegend) {
legendTraceCount++;
if(trace.showlegend) {
legendReallyHasATrace = true;
// Always show the legend by default if there's a pie,
// or if there's only one trace but it's explicitly shown
if(Registry.traceIs(trace, 'pie') ||
trace._input.showlegend === true
) {
legendTraceCount++;
}
}
}
if((Registry.traceIs(trace, 'bar') && layoutOut.barmode === 'stack') ||
['tonextx', 'tonexty'].indexOf(trace.fill) !== -1) {
defaultOrder = helpers.isGrouped({traceorder: defaultOrder}) ?
'grouped+reversed' : 'reversed';
}
if(trace.legendgroup !== undefined && trace.legendgroup !== '') {
defaultOrder = helpers.isReversed({traceorder: defaultOrder}) ?
'reversed+grouped' : 'grouped';
}
}
var showLegend = Lib.coerce(layoutIn, layoutOut,
basePlotLayoutAttributes, 'showlegend',
legendReallyHasATrace && legendTraceCount > 1);
if(showLegend === false) return;
var containerOut = Template.newContainer(layoutOut, 'legend');
function coerce(attr, dflt) {
return Lib.coerce(containerIn, containerOut, attributes, attr, dflt);
}
coerce('bgcolor', layoutOut.paper_bgcolor);
coerce('bordercolor');
coerce('borderwidth');
Lib.coerceFont(coerce, 'font', layoutOut.font);
coerce('orientation');
if(containerOut.orientation === 'h') {
var xaxis = layoutIn.xaxis;
if(xaxis && xaxis.rangeslider && xaxis.rangeslider.visible) {
defaultX = 0;
defaultXAnchor = 'left';
defaultY = 1.1;
defaultYAnchor = 'bottom';
}
else {
defaultX = 0;
defaultXAnchor = 'left';
defaultY = -0.1;
defaultYAnchor = 'top';
}
}
coerce('traceorder', defaultOrder);
if(helpers.isGrouped(layoutOut.legend)) coerce('tracegroupgap');
coerce('x', defaultX);
coerce('xanchor', defaultXAnchor);
coerce('y', defaultY);
coerce('yanchor', defaultYAnchor);
coerce('valign')
Lib.noneOrAll(containerIn, containerOut, ['x', 'y']);
};
|
JavaScript
| 0.000013 |
@@ -3439,16 +3439,17 @@
valign')
+;
%0A Lib
|
d9e8b1c5fc22e06d6dd4f403ebf9709a1b491a46
|
add smoothscroll to front page
|
js/bootswatch.js
|
js/bootswatch.js
|
$('a[rel=tooltip]').tooltip({
'placement': 'bottom'
});
$('.subnav a').smoothScroll();
(function ($) {
$(function(){
// fix sub nav on scroll
var $win = $(window),
$body = $('body'),
$nav = $('.subnav'),
navHeight = $('.navbar').first().height(),
subnavHeight = $('.subnav').first().height(),
subnavTop = $('.subnav').length && $('.subnav').offset().top - navHeight,
marginTop = parseInt($body.css('margin-top'), 10);
isFixed = 0;
processScroll();
$win.on('scroll', processScroll);
function processScroll() {
var i, scrollTop = $win.scrollTop();
if (scrollTop >= subnavTop && !isFixed) {
isFixed = 1;
$nav.addClass('subnav-fixed');
$body.css('margin-top', marginTop + subnavHeight + 'px');
} else if (scrollTop <= subnavTop && isFixed) {
isFixed = 0;
$nav.removeClass('subnav-fixed');
$body.css('margin-top', marginTop + 'px');
}
}
});
})(window.jQuery);
|
JavaScript
| 0.000001 |
@@ -55,16 +55,27 @@
);%0A%0A%0A$('
+.navbar a,
.subnav
|
09369fb624d07d09f93cfc0dcfd384d0bd8e64fa
|
Clean comments
|
lib/utils/tfsExec.js
|
lib/utils/tfsExec.js
|
/* global decodeURIComponent */
var utils = require('./common'),
vscode = require('vscode');
/**
* Execute a TFS command.
*
* @version 0.5.0
*
* @param {String} command TFS command to execute
* @param {Boolean} isGlobal Is this command for the entire workspace ?
*/
var tfsExec = function(command, isGlobal) {
isGlobal = !!isGlobal;
if (!isGlobal && !utils.getCurrentFilePath()) {
vscode.window.showErrorMessage('TFS: Either there is no current file opened or your current file has not been saved.');
return;
}
var itemspec = isGlobal ? utils.getCurrentWorkspacePath() : utils.getCurrentFilePath();
require('../tfs/' + command)([itemspec]);
}
module.exports = tfsExec;
|
JavaScript
| 0 |
@@ -1,37 +1,4 @@
-/* global decodeURIComponent */%0A%0A
var
|
b2a6fa1a1e6771a662029d3f52b6d57dcabc6ae2
|
Add missing Station super() call
|
src/icarus/station.js
|
src/icarus/station.js
|
import { EventEmitter } from 'events'
import PouchDB from 'pouchdb'
import Serial from '../serial'
import Classifier from './classifier'
import { parser, dataHandler } from './data-handler'
/**
* Handles everything a Station should.
* Brings Serial, data parsing and database saving together.
*/
export default class Station extends EventEmitter {
/**
* Sets up all relevant class instances (Serial, parsers...) and events listeners.
*/
constructor () {
/**
* Database instance, internal to the station.
*/
this.db = new PouchDB('station-db')
/**
* {@link Serial} instance with the {@link parser} attached
*/
this.serial = new Serial(parser())
/**
* {@link Classifier} instance.
*/
this.classifier = new Classifier()
// Handle incoming packets
this.serial.on('data', this::dataHandler)
}
}
|
JavaScript
| 0.000011 |
@@ -461,16 +461,29 @@
or () %7B%0A
+ super()%0A%0A
/**%0A
|
6da16e0f3a687445b36cbc9cf81780832dc04cad
|
Refactor require statements
|
lib/Routes.js
|
lib/Routes.js
|
"use strict";
var Router = require("routes/index.js");
function Routes() {
this._router = Router();
}
Routes.prototype._router = null;
Routes.prototype.add = function (route, fn) {
if (arguments.length < 2) {
fn = arguments[0];
route = "*";
}
this._router.addRoute.call(this._router, route, fn);
return this;
};
Routes.prototype.get = addByMethod("GET");
Routes.prototype.post = addByMethod("POST");
Routes.prototype.put = addByMethod("PUT");
Routes.prototype.delete = addByMethod("DELETE");
Routes.prototype.match = function (url) {
return this._router.match(url);
};
function addByMethod(method) {
return function (fn) {
return this.add(function checkMethod(req, res, next) {
if (req.method === method) {
fn.call(this, req, res, next);
}
});
};
}
module.exports = Routes;
|
JavaScript
| 0.00047 |
@@ -34,23 +34,11 @@
re(%22
-routes/index.js
+i40
%22);%0A
|
908f3c506bf2f6f78ebd0392196aebe52846627d
|
add support for dynamicTask
|
lib/Runner.js
|
lib/Runner.js
|
const { Boards } = require('boards');
const { Homefront } = require('homefront');
const path = require('path');
const boards = new Boards({ discovery: false });
class Runner {
constructor(config) {
this.boards = new Boards({ discovery: false });
this.config = config;
}
run(task, parameters) {
let instructions = this.config.tasks[task];
if (!instructions) {
throw new Error(`Instructions for task "${task}" not found.`);
}
if (!Array.isArray(instructions)) {
instructions = [instructions];
}
let previousTask = null;
return Promise.all(instructions.map(instruction => {
let runner;
if (previousTask) {
runner = previousTask.then(() => this.runTask(instruction, parameters));
previousTask = null;
} else {
runner = this.runTask(instruction, parameters);
}
if (instruction.sync) {
previousTask = runner;
}
return runner;
}));
}
prepareParams(method, params) {
const preparedParams = method(params);
if (typeof preparedParams === 'object') {
return preparedParams;
}
return params;
}
runTask(instruction, parameters) {
// Prepare for step. Copy parameters to not affect other tasks.
if (typeof instruction.prepare === 'function') {
parameters = this.prepareParams(instruction.prepare, Homefront.merge({}, parameters));
}
if (typeof instruction.definedTask !== 'undefined') {
if (typeof instruction.definedTask !== 'string') {
throw new Error(`definedTask must be a string. Got ${typeof instruction.definedTask}.`);
}
if (instruction.isolated && typeof instruction.prepare !== 'function') {
parameters = Homefront.merge({}, parameters);
}
return this.run(instruction.definedTask, parameters);
}
if (typeof instruction.task === 'function') {
return instruction.task(parameters, boards);
}
if (typeof this[instruction.task] !== 'function') {
throw new Error(`Invalid task "${instruction.task}" supplied`);
}
return this[instruction.task](instruction, parameters);
}
modify(instruction, parameters) {
return this.boards.generate('ModificationGenerator', Object.assign({}, parameters, {
sourceDirectory: this.config.appRoot,
targetDirectory: this.config.appRoot,
sourceFile : this.getTarget(instruction.target, parameters),
modify : { patch: instruction.patch }
}));
}
generate(instruction, parameters) {
const parsed = path.parse(this.getTarget(instruction.target, parameters));
return boards.generate('TemplateGenerator', Object.assign({}, parameters, {
sourceFile : instruction.template,
targetFile : parsed.base,
sourceDirectory: this.config.templateRoot,
targetDirectory: path.join(this.config.appRoot, parsed.dir)
}));
}
getTarget(target, parameters) {
if (typeof target === 'function') {
return target(parameters);
}
return target
.replace(/{{pascalCased}}/g, parameters.pascalCased)
.replace(/{{upperCased}}/g, parameters.upperCased)
.replace(/{{name}}/g, parameters.name);
}
}
module.exports.Runner = Runner;
|
JavaScript
| 0 |
@@ -350,54 +350,84 @@
= t
-his.config.tasks%5Btask%5D;%0A%0A if (!instructions
+ask;%0A%0A if (typeof task === 'string') %7B%0A if (!this.config.tasks%5Btask%5D
) %7B%0A
@@ -424,38 +424,56 @@
%5Btask%5D) %7B%0A
+
-throw
+ return Promise.reject(
new Error(%60Instr
@@ -511,16 +511,178 @@
found.%60)
+);%0A %7D%0A%0A instructions = this.config.tasks%5Btask%5D;%0A %7D%0A%0A if (!instructions) %7B%0A return Promise.reject(new Error(%60Invalid instructions provided.%60))
;%0A %7D%0A
@@ -1633,32 +1633,268 @@
eters));%0A %7D%0A%0A
+ // Allow dynamic tasks to be supplied.%0A if (typeof instruction.dynamicTask === 'function') %7B%0A return Promise.resolve(instruction.dynamicTask(parameters)).then(tasks =%3E %7B%0A this.run(tasks, parameters);%0A %7D);%0A %7D%0A%0A
if (typeof i
|
90e7de8790954ff00039d284d8da60fce6d86e0f
|
fix path
|
gulpfile.js
|
gulpfile.js
|
const pify = require('pify');
const fs = require('fs-jetpack');
const path = require('path');
const loadJsonFile = require('load-json-file');
const inline = pify(require('inline-source'));
const rollup = require('rollup').rollup;
const bowerResolve = require('rollup-plugin-bower-resolve');
const buble = require('rollup-plugin-buble');
let cache;
const browserSync = require('browser-sync').create();
const cssnext = require('postcss-cssnext');
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
const render = require('./util/render.js');
const footer = require('./bower_components/ftc-footer');
const config = require('./config.json');
const projectName = path.basename(process.env.cwd())
const deployDir = path.resolve(__dirname, `../ft-interact/static/${projectName}`);
const tmpDir = path.resolve(__dirname, '.tmp');
process.env.NODE_ENV = 'development';
// change NODE_ENV between tasks.
gulp.task('prod', function() {
return Promise.resolve(process.env.NODE_ENV = 'production');
});
gulp.task('dev', function(done) {
return Promise.resolve(process.env.NODE_ENV = 'development');
});
function buildPage(template, data) {
return render(template, data)
.then(html => {
if (process.env.NODE_ENV === 'production') {
return inline(html, {
compress: true,
rootpath: path.resolve(process.cwd(), '.tmp')
});
}
return html;
})
.catch(err => {
throw err;
});
}
gulp.task('html', () => {
const env = {
isProduction: process.env.NODE_ENV === 'production'
};
return loadJsonFile(`data/${project}.json`)
.then(json => {
const context = Object.assign(json, {
footer: footer,
env
});
return buildPage('numbers.html', context);
})
.then(html => {
return fs.writeAsync(`${tmpDir}/${project}.html`, html);
})
.then(() => {
browserSync.reload('*.html');
return Promise.resolve();
})
.catch(err => {
console.log(err);
});
});
// generate partial html files to be used on homepage widget.
function buildWidgets(sections) {
const promisedWidgets = sections.map(section => {
const dest = `${tmpDir}/${project}-${section.id}.html`;
return buildPage('widget.html', {section: section})
.then(html => {
return fs.writeAsync(dest, html);
})
.catch(err => {
throw err;
})
});
return Promise.all(promisedWidgets);
}
gulp.task('widgets', () => {
return loadJsonFile(`data/${project}.json`)
.then(json => {
return buildWidgets(json.sections);
})
.catch(err => {
console.log(err);
});
});
gulp.task('styles', function styles() {
const dest = `${tmpDir}/styles`;
return gulp.src('client/*.scss')
.pipe($.changed(dest))
.pipe($.plumber())
.pipe($.sourcemaps.init({loadMaps:true}))
.pipe($.sass({
outputStyle: 'expanded',
precision: 10,
includePaths: ['bower_components']
}).on('error', $.sass.logError))
.pipe($.postcss([
cssnext({
features: {
colorRgba: false
}
})
]))
.pipe($.sourcemaps.write('./'))
.pipe(gulp.dest(dest))
.pipe(browserSync.stream());
});
gulp.task('eslint', () => {
return gulp.src('client/js/*.js')
.pipe($.eslint())
.pipe($.eslint.format())
.pipe($.eslint.failAfterError());
});
gulp.task('scripts', () => {
return rollup({
entry: 'client/main.js',
plugins: [
bowerResolve({
// Use `module` field for ES6 module if possible
module: true
}),
// buble's option is no documented. Refer here.
buble({
include: ['client/**'],
// FTC components should be released together with a transpiled version. Do not transpile again here.
exclude: [
'bower_components/**',
'node_modules/**'
],
transforms: {
dangerousForOf: true
}
})
],
cache: cache
}).then(function(bundle) {
// Cache for later use
cache = bundle;
return bundle.write({
dest: `${tmpDir}/scripts/main.js`,
format: 'iife',
sourceMap: true
});
})
.then(() => {
browserSync.reload();
return Promise.resolve();
})
.catch(err => {
console.log(err);
});
});
// This task is used for backedn only.
gulp.task('watch', gulp.parallel('styles', 'scripts', () => {
gulp.watch('client/**/*.js', gulp.parallel('scripts'));
gulp.watch('client/**/*.scss', gulp.parallel('styles'));
}));
gulp.task('serve',
gulp.parallel(
'html', 'styles', 'scripts',
function serve() {
browserSync.init({
server: {
baseDir: [tmpDir, 'client'],
index: `${project}.html`,
routes: {
'/bower_components': 'bower_components'
}
}
});
gulp.watch('client/**/*.{csv,svg,png,jpg}', browserSync.reload);
gulp.watch('client/**/*.js', gulp.parallel('scripts'));
gulp.watch('client/**/*.scss', gulp.parallel('styles'));
gulp.watch(['views/**/*.html', 'data/*.json'], gulp.parallel('html', 'widgets'));
})
);
// For server only build frontend assets
gulp.task('build', gulp.series('prod', gulp.parallel('styles', 'scripts'), 'dev'));
gulp.task('deploy:widgets', () => {
const DEST = path.resolve(__dirname, config.widgets);
return gulp.src(`.tmp/${project}-*.html`)
.pipe($.htmlmin({
collapseWhitespace: true,
removeAttributeQuotes: true
}))
.pipe(gulp.dest(DEST));
});
gulp.task('images', function () {
const DEST = path.resolve(__dirname, config.assets);
console.log(`Copying images to ${DEST}`)
return gulp.src('client/**/*.{svg,png,jpg,jpeg,gif}')
.pipe($.imagemin({
progressive: true,
interlaced: true,
svgoPlugins: [{cleanupIDs: false}]
}))
.pipe(gulp.dest(DEST));
});
gulp.task('deploy', gulp.parallel('styles', 'scripts', 'images'));
// Currently we give up webpack as it is hard to configure.
/*
* To use webpack you should install those modules:
* `babel-core`, `babel-loader`, `babel-preset-latest`.
* `babel-loader` needs to be above 7.0 which is not released yet.
*/
// gulp.task('webpack', function() {
// if (process.env.NODE_ENV === 'production') {
// delete webpackConfig.watch;
// }
// return webpack(webpackConfig)
// .then(stats => {
// console.log(stats.toString({
// colors: true
// }));
// })
// .catch(err => {
// console.log(err);
// });
// });
|
JavaScript
| 0.000017 |
@@ -700,18 +700,15 @@
ess.
-env.
cwd())
+;
%0Acon
|
79236053fac55e596629b2f6bd6b5cc350469ee2
|
Remove transpile for ES2015 on development - Fix #79
|
gulpfile.js
|
gulpfile.js
|
'use strict';
/*********************************************************
* Modules
********************************************************/
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var templateCache = require('gulp-angular-templatecache');
var ngConstant = require('gulp-ng-constant');
var ngAnnotate = require('gulp-ng-annotate');
// Non-Gulp dependencies
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var watchify = require('watchify');
var fs = require('fs');
/*********************************************************
* Vars
********************************************************/
var projectPath = 'app/';
var outputPath = 'public/';
var configPath = 'config/';
/*********************************************************
* Angular Templates
********************************************************/
gulp.task('templates', function() {
return gulp.src(projectPath + '**/*.html')
.pipe(templateCache({
module: 'templateCache',
standalone: true,
transformUrl: function (url) {
return url.replace('custom/', '');
}
}))
.pipe(gulp.dest(outputPath + 'js'));
});
/*********************************************************
* JavaScript
********************************************************/
gulp.task('js:build', function() {
return browserify(projectPath + 'app.js', {
debug: false
})
.transform(babelify)
.bundle()
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(ngAnnotate())
.pipe(uglify())
.pipe(gulp.dest(outputPath + 'js'));
});
gulp.task('js:dev', function() {
return browserify(projectPath + 'app.js', {
debug: true
})
.transform(babelify)
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest(outputPath + 'js'));
});
gulp.task('js:watch', [], function() {
var bundler = browserify({
entries: [projectPath + 'app.js'],
extensions: ['.js'],
debug: true,
fullPaths: true,
cache: {},
packageCache: {}
})
.transform('babelify');
var rebundle = function() {
var startDate = new Date();
return bundler.bundle(function(err, buf) {
if (err) {
console.log('JS error: ' + err.toString());
} else {
console.log('JS bundle updated in ' + (new Date().getTime() - startDate.getTime()) + ' ms');
}
})
.pipe(source('bundle.js'))
.pipe(gulp.dest(outputPath + 'js'));
};
bundler.plugin(watchify);
bundler.on('update', rebundle);
return rebundle();
});
/*********************************************************
* Environment Config
********************************************************/
var configFunc = function(env) {
var config = './' + configPath + 'config.json';
var localConfig = './' + configPath + 'config.local.json';
var myConfig;
if (fs.existsSync(localConfig)) {
console.log('Using local config file: ' + localConfig);
myConfig = require(localConfig);
} else {
console.log('Using default config file: ' + config);
myConfig = require(config);
}
var envConfig = myConfig[env];
return ngConstant({
constants: envConfig,
stream: true
})
.pipe(gulp.dest(outputPath + 'js'));
};
gulp.task('config:dev', configFunc.bind(this, 'dev'));
gulp.task('config:staging', configFunc.bind(this, 'staging'));
gulp.task('config:build', configFunc.bind(this, 'production'));
|
JavaScript
| 0 |
@@ -1485,26 +1485,24 @@
false%0A %7D)%0A
-
.transform
@@ -1504,34 +1504,32 @@
sform(babelify)%0A
-
.bundle()%0A
@@ -1516,34 +1516,32 @@
fy)%0A .bundle()%0A
-
.pipe(source('
@@ -1551,26 +1551,24 @@
dle.js'))%0A
-
-
.pipe(buffer
@@ -1567,26 +1567,24 @@
e(buffer())%0A
-
.pipe(ngAn
@@ -1591,26 +1591,24 @@
notate())%0A
-
-
.pipe(uglify
@@ -1611,18 +1611,16 @@
lify())%0A
-
.pipe(
@@ -1759,35 +1759,8 @@
%7D)%0A
- .transform(babelify)%0A
.b
@@ -1767,18 +1767,16 @@
undle()%0A
-
.pipe(
@@ -1796,18 +1796,16 @@
e.js'))%0A
-
.pipe(
@@ -2054,36 +2054,8 @@
%7D)
-%0A .transform('babelify');
%0A%0A
@@ -2167,18 +2167,16 @@
%7B%0A
-
if (err)
@@ -2174,26 +2174,24 @@
if (err) %7B%0A
-
cons
@@ -2236,18 +2236,16 @@
;%0A
-
%7D else %7B
@@ -2245,18 +2245,16 @@
else %7B%0A
-
@@ -2356,23 +2356,17 @@
-
%7D%0A
-
-
%7D)%0A
-
@@ -2392,18 +2392,16 @@
e.js'))%0A
-
.pip
@@ -3168,26 +3168,24 @@
: true%0A %7D)%0A
-
.pipe(gulp
|
07ab3d900e2d7d523fa68dcf9ccfd77b5029d184
|
Make datetimetemplate a variable
|
timesketch/ui/static/components/explore/explore-filter-directive.js
|
timesketch/ui/static/components/explore/explore-filter-directive.js
|
/*
Copyright 2015 Google Inc. All rights reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
(function() {
var module = angular.module('timesketch.explore.filter.directive', []);
module.directive('tsFilter', function () {
/**
* Manage query filters.
* @param sketch - Sketch object.
* @param filter - Filter object.
* @param query - Query string.
* @param queryDsl - Query DSL JSON string.
* @param show-filters - Boolean value. If set to true the filter card will be shown.
* @param events - Array of events objects.
* @param meta - Events metadata object.
*/
return {
restrict: 'E',
templateUrl: '/static/components/explore/explore-filter.html',
scope: {
sketch: '=',
filter: '=',
query: '=',
queryDsl: '=',
showFilters: '=',
events: '=',
meta: '='
},
require: '^tsSearch',
link: function(scope, elem, attrs, ctrl) {
scope.applyFilter = function() {
scope.parseFilterDate(scope.filter.time_start)
ctrl.search(scope.query, scope.filter, scope.queryDsl)
};
scope.clearFilter = function() {
delete scope.filter.time_start;
delete scope.filter.time_end;
scope.showFilters = false;
ctrl.search(scope.query, scope.filter, scope.queryDsl)
};
scope.enableAllTimelines = function() {
scope.filter.indices = [];
for (var i = 0; i < scope.sketch.timelines.length; i++) {
scope.filter.indices.push(scope.sketch.timelines[i].searchindex.index_name)
}
ctrl.search(scope.query, scope.filter, scope.queryDsl)
};
scope.disableAllTimelines = function() {
scope.filter.indices = [];
scope.events = [];
scope.meta.es_total_count = 0;
scope.meta.es_time = 0;
scope.meta.noisy = false;
}
scope.parseFilterDate = function(datevalue){
if (datevalue != null) {
//Parse out 'T' date time seperator needed by ELK but not by moment.js
datevalue=datevalue.replace(/T/g,' ');
//Parse offset given by user. Eg. +-10m
var offsetRegexp = /(.*?)(-|\+|\+-|-\+)(\d+)(y|d|h|m|s|M|Q|w|ms)/g;
var match = offsetRegexp.exec(datevalue);
if (match != null) {
match[1] = moment(match[1],"YYYY-MM-DD HH:mm:ssZZ");
//calculate filter start and end datetimes
if (match[2] == '+') {
scope.filter.time_start = moment.utc(match[1]).format("YYYY-MM-DDTHH:mm:ss");
scope.filter.time_end = moment.utc(match[1]).add(match[3],match[4]).format("YYYY-MM-DDTHH:mm:ss");
}
if (match[2] == '-') {
scope.filter.time_start = moment.utc(match[1]).subtract(match[3],match[4]).format("YYYY-MM-DDTHH:mm:ss");
scope.filter.time_end = moment.utc(match[1]).format("YYYY-MM-DDTHH:mm:ss");
}
if (match[2] == '-+' || match[2] == '+-') {
scope.filter.time_start = moment.utc(match[1]).subtract(match[3],match[4]).format("YYYY-MM-DDTHH:mm:ss");
scope.filter.time_end = moment.utc(match[1]).add(match[3],match[4]).format("YYYY-MM-DDTHH:mm:ss");
}
} else {
scope.filter.time_end = scope.filter.time_start;
}
}
}
}
}
});
module.directive('tsTimelinePickerItem', function() {
/**
* Manage the timeline items to filter on.
*/
return {
restrict: 'E',
templateUrl: '/static/components/explore/explore-timeline-picker-item.html',
scope: {
timeline: '=',
query: '=',
queryDsl: '=',
filter: '='
},
require: '^tsSearch',
link: function(scope, elem, attrs, ctrl) {
scope.checkboxModel = {};
var index_name = scope.timeline.searchindex.index_name;
scope.toggleCheckbox = function () {
var index = scope.filter.indices.indexOf(index_name);
scope.checkboxModel.active = !scope.checkboxModel.active;
if (!scope.checkboxModel.active) {
if (index > -1) {
scope.filter.indices.splice(index, 1);
}
} else {
if (index == -1) {
scope.filter.indices.push(index_name);
}
}
ctrl.search(scope.query, scope.filter, scope.queryDsl);
};
scope.$watch("filter.indices", function(value) {
if (scope.filter.indices.indexOf(index_name) == -1) {
scope.colorbox = {'background-color': '#E9E9E9'};
scope.timeline_picker_title = {'color': '#D1D1D1', 'text-decoration': 'line-through'};
scope.checkboxModel.active = false;
} else {
scope.colorbox = {'background-color': "#" + scope.timeline.color};
scope.timeline_picker_title = {'color': '#333', 'text-decoration': 'none'};
scope.checkboxModel.active = true;
}
}, true);
}
}
});
})();
|
JavaScript
| 0.006046 |
@@ -2910,32 +2910,100 @@
alue != null) %7B%0A
+ var datetimetemplate=%22YYYY-MM-DDTHH:mm:ss%22;%0A
@@ -3144,17 +3144,16 @@
g,' ');%0A
-%0A
@@ -3366,17 +3366,16 @@
value);%0A
-%0A
@@ -3700,37 +3700,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
@@ -3826,37 +3826,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
@@ -4040,37 +4040,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
@@ -4143,37 +4143,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
@@ -4378,37 +4378,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
@@ -4504,37 +4504,32 @@
.format(
-%22YYYY-MM-DDTHH:mm:ss%22
+datetimetemplate
);%0A
|
dbe888cfd583a986ca0395277fc2468faf59241d
|
Fix a linter error
|
src/containers/AnalyticsContainer.js
|
src/containers/AnalyticsContainer.js
|
import { PropTypes, PureComponent } from 'react'
import { connect } from 'react-redux'
import { selectIsLoggedIn } from '../selectors/authentication'
import { selectAllowsAnalytics, selectAnalyticsId, selectCreatedAt } from '../selectors/profile'
export function addSegment(uid, createdAt) {
if (typeof window !== 'undefined') {
/* eslint-disable */
!function(){const analytics=window.analytics=window.analytics||[];if(!analytics.initialize)if(analytics.invoked)window.console&&console.error&&console.error("Segment snippet included twice.");else{analytics.invoked=!0;analytics.methods=["trackSubmit","trackClick","trackLink","trackForm","pageview","identify","reset","group","track","ready","alias","page","once","off","on"];analytics.factory=function(t){return function(){const e=Array.prototype.slice.call(arguments);e.unshift(t);analytics.push(e);return analytics}};for(let t=0;t<analytics.methods.length;t++){const e=analytics.methods[t];analytics[e]=analytics.factory(e)}analytics.load=function(t){const e=document.createElement("script");e.type="text/javascript";e.async=!0;e.src=("https:"===document.location.protocol?"https://":"http://")+"cdn.segment.com/analytics.js/v1/"+t+"/analytics.min.js";const n=document.getElementsByTagName("script")[0];n.parentNode.insertBefore(e,n)};
/* eslint-enable */
analytics.SNIPPET_VERSION = '3.1.0'
analytics.load(ENV.SEGMENT_WRITE_KEY)
if (uid) {
analytics.identify(uid, { createdAt })
}
} }();
}
}
export function doesAllowTracking() {
if (typeof window === 'undefined') { return false }
return !(
window.navigator.doNotTrack === '1' ||
window.navigator.msDoNotTrack === '1' ||
window.doNotTrack === '1' ||
window.msDoNotTrack === '1'
)
}
function mapStateToProps(state) {
return {
allowsAnalytics: selectAllowsAnalytics(state),
analyticsId: selectAnalyticsId(state),
createdAt: selectCreatedAt(state),
isLoggedIn: selectIsLoggedIn(state),
}
}
class AnalyticsContainer extends PureComponent {
static propTypes = {
allowsAnalytics: PropTypes.bool,
analyticsId: PropTypes.string,
createdAt: PropTypes.string,
isLoggedIn: PropTypes.bool.isRequired,
}
static defaultProps = {
allowsAnalytics: null,
analyticsId: null,
createdAt: null,
}
componentWillMount() {
this.hasLoadedTracking = false
}
componentDidMount() {
const { analyticsId, allowsAnalytics, createdAt, isLoggedIn } = this.props
if (this.hasLoadedTracking) { return }
if (!isLoggedIn && doesAllowTracking()) {
this.hasLoadedTracking = true
addSegment()
} else if (analyticsId && allowsAnalytics) {
this.hasLoadedTracking = true
addSegment(analyticsId, createdAt)
}
}
componentWillReceiveProps(nextProps) {
const { allowsAnalytics, analyticsId, createdAt } = nextProps
if (this.hasLoadedTracking) {
// identify the user if they didn't previously have an id to identify with
if (!this.props.analyticsId && analyticsId) {
window.analytics.identify(analyticsId, { createdAt })
}
} else if (this.props.analyticsId && analyticsId && allowsAnalytics) {
this.hasLoadedTracking = true
addSegment(analyticsId, createdAt)
}
}
render() {
return null
}
}
export default connect(mapStateToProps)(AnalyticsContainer)
|
JavaScript
| 0.000439 |
@@ -1293,24 +1293,26 @@
(e,n)%7D;%0A
+
/* eslint-en
@@ -1482,16 +1482,20 @@
%7D%0A %7D
+%0A
%7D();%0A
|
3b60e9f7aaf4e8b137a271ad144d18fd922c2483
|
Add attribution for the preventZoom function
|
src/javascript/app.js
|
src/javascript/app.js
|
/**
* Created by Evrim Persembe on 9/1/16.
*/
(function () {
"use strict";
var calculator = require("./calculator.js");
window.addEventListener("DOMContentLoaded", function() {
var ACTIVE_OPERATION_BUTTON_CLASS_NAME = "is-active-operation";
var OPERATION_BUTTON_CLASS_NAME = "calc-buttons-operation";
var displayPanel = document.querySelector(".calc-display .content");
var numberButtons = [
document.getElementById("zero-button"),
document.getElementById("one-button"),
document.getElementById("two-button"),
document.getElementById("three-button"),
document.getElementById("four-button"),
document.getElementById("five-button"),
document.getElementById("six-button"),
document.getElementById("seven-button"),
document.getElementById("eight-button"),
document.getElementById("nine-button")
];
var addButton = document.getElementById("add-button");
var subtractButton = document.getElementById("subtract-button");
var multiplyButton = document.getElementById("multiply-button");
var divideButton = document.getElementById("divide-button");
var percentButton = document.getElementById("percent-button");
var decimalButton = document.getElementById("decimal-button");
var changeSignButton = document.getElementById("change-sign-button");
var equalsButton = document.getElementById("equals-button");
var clearButton = document.getElementById("clear-button");
var buttons = document.querySelectorAll(".calc-buttons > button");
var operationButtons = [addButton, subtractButton, multiplyButton, divideButton];
document.addEventListener("touchstart", preventZoom);
calculator.initialize({
displayPanel: displayPanel,
numberButtons: numberButtons,
addButton: addButton,
subtractButton: subtractButton,
multiplyButton: multiplyButton,
divideButton: divideButton,
percentButton: percentButton,
decimalButton: decimalButton,
changeSignButton: changeSignButton,
equalsButton: equalsButton,
clearButton: clearButton,
onDisplayValueUpdate: displayValueUpdated,
onClearButtonFunctionalityChange: clearButtonFunctionalityChanged
});
for (var i = 0; i < buttons.length; i++) {
makeButtonSquare(buttons[i]);
attachHandlerForActiveOperation(buttons[i], operationButtons, changeSignButton, percentButton);
}
function displayValueUpdated(newValue) {
displayPanel.innerHTML = newValue;
fitDisplayValueToContainer();
}
function fitDisplayValueToContainer() {
var displayContainerSize = displayPanel.parentNode.offsetWidth;
var displayValueRightOffset = parseInt(window.getComputedStyle(displayPanel, null).getPropertyValue("right"));
var displayValueLeftOffset = displayValueRightOffset * 0.2;
displayContainerSize -= displayValueRightOffset + displayValueLeftOffset;
var displayValueSize = parseInt(displayPanel.clientWidth);
var scaleFactor = displayContainerSize / displayValueSize;
if (scaleFactor < 1) {
displayPanel.style.transform = "scale(" + scaleFactor + ")";
} else {
displayPanel.style.transform = "scale(1)";
}
}
function clearButtonFunctionalityChanged(newFunctionality) {
clearButton.innerHTML = newFunctionality;
}
function makeButtonSquare(button) {
if (button.id === "zero-button") return;
button.style.height = window.getComputedStyle(button, null).getPropertyValue("width");
}
function attachHandlerForActiveOperation(button, operationButtons, changeSignButton, percentButton) {
button.addEventListener("click", function() {
if (button === changeSignButton || button === percentButton) return;
var isOperationButton = button.classList.contains(OPERATION_BUTTON_CLASS_NAME);
for (var i = 0; i < operationButtons.length; i++) {
operationButtons[i].classList.remove(ACTIVE_OPERATION_BUTTON_CLASS_NAME);
}
if (isOperationButton) {
button.classList.add(ACTIVE_OPERATION_BUTTON_CLASS_NAME);
}
});
}
function preventZoom(e) {
var t2 = e.timeStamp;
var t1 = e.currentTarget.dataset.lastTouch || t2;
var dt = t2 - t1;
var fingers = e.originalEvent.touches.length;
e.currentTarget.dataset.lastTouch = t2;
if (!dt || dt > 500 || fingers > 1) return; // not double-tap
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
e.currentTarget.trigger('click').trigger('click');
}
});
}());
|
JavaScript
| 0 |
@@ -4158,32 +4158,89 @@
%7D);%0A %7D%0A%0A
+ // Adapted from: http://stackoverflow.com/a/10910547%0A
function pre
|
b5cf9424239bb88332fd34b57993c2162adc5e5f
|
fix gulpfile
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var concat = require('gulp-concat');
var fs = require('fs');
// compile sass and concatenate to single css file in build dir
gulp.task('convert-sass', function () {
return gulp.src([
'app/app.scss',
'node_modules/leaflet/dist/leaflet.css',
'node_modules/Leaflet.vector-markers/dist/leaflet-vector-markers.css',
'node_modules/leaflet.pm/dist/leaflet.pm.css'
])
.pipe(sass({
includePaths: [
'node_modules/roboto-fontface/css/roboto/sass',
'node_modules/idai-components-2/src/scss',
'node_modules/bootstrap/scss',
'node_modules/mdi/scss/'
], precision: 8
}))
.pipe(concat('app.css'))
.pipe(gulp.dest('app'));
});
gulp.task('copy-fonts-convert-sass', ['convert-sass'], function () {
// fonts
gulp.src([
'node_modules/roboto-fontface/fonts/**/*',
'node_modules/mdi/fonts/**/*'
])
.pipe(gulp.dest('fonts'));
});
// Creates config files if they do not exist already
//
gulp.task('create-configs', function (callback) {
fs.access('./config/Configuration.json', fs.F_OK, function(err) {
if (err) {
fs.createReadStream(path + '.template').pipe(fs.createWriteStream(path));
} else {
console.log('Will not create ' + path + ' from template because file already exists.');
}
});
});
|
JavaScript
| 0.000065 |
@@ -1170,18 +1170,19 @@
-fs.access(
+var path =
'./c
@@ -1206,16 +1206,37 @@
on.json'
+;%0A%0A fs.access(path
, fs.F_O
|
9685fd9fe5e8837b8bed660423a1fac3b927a327
|
Tweak comment.
|
assets/js/googlesitekit/widgets/components/WidgetRenderer.js
|
assets/js/googlesitekit/widgets/components/WidgetRenderer.js
|
/**
* WidgetRenderer component.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { string, object, func } from 'prop-types';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME } from '../datastore';
import Widget from './Widget';
const { useSelect } = Data;
const WidgetRenderer = ( { slug, gridClassName, activeWidgets, setActiveWidgets } ) => {
const widget = useSelect( ( select ) => select( STORE_NAME ).getWidget( slug ) );
if ( ! widget ) {
if ( activeWidgets[ slug ] ) {
setActiveWidgets( {
...activeWidgets,
[ slug ]: false,
} );
}
return null;
}
// Capitalize the "component" variable, as it is required by JSX.
const { component: Component, wrapWidget } = widget;
// Check if widget component will render `null` by calling directly. Maybe???
if ( typeof Component === 'function' && ! Component( {} ) ) {
if ( activeWidgets[ slug ] ) {
setActiveWidgets( {
...activeWidgets,
[ slug ]: false,
} );
}
return null;
}
if ( ! activeWidgets[ slug ] ) {
setActiveWidgets( {
...activeWidgets,
[ slug ]: true,
} );
}
let widgetComponent = <Component />;
if ( wrapWidget ) {
widgetComponent = <Widget slug={ slug }>{ widgetComponent }</Widget>;
}
if ( gridClassName ) {
widgetComponent = (
<div className={ gridClassName }>
{ widgetComponent }
</div>
);
}
return widgetComponent;
};
WidgetRenderer.propTypes = {
slug: string.isRequired,
gridClassName: string,
activeWidgets: object,
setActiveWidgets: func,
};
WidgetRenderer.defaultProps = {
activeWidgets: {},
setActiveWidgets: () => {},
};
export default WidgetRenderer;
|
JavaScript
| 0 |
@@ -1407,16 +1407,19 @@
calling
+it
directly
@@ -1423,17 +1423,8 @@
tly.
- Maybe???
%0A%09if
|
5eb62fc72da2f33b8d72d61a0b66a56d2e52e99c
|
Fix change log filename usage in chlg-init
|
lib/chlg-init.js
|
lib/chlg-init.js
|
'use strict';
var fs = require('fs');
var program = require('commander');
program
.option('-f, --file [filename]', 'Changelog filename', 'CHANGELOG.md')
.parse(process.argv);
function chlgInit(file) {
file = file || program.file;
fs.stat(program.file, function (err) {
if (!err || err.code !== 'ENOENT') {
console.error('chlg-init: cannot create file ‘' + program.file + '’: File exists');
process.exit(1);
}
fs.writeFile(program.file, [
'# Change Log',
'All notable changes to this project will be documented in this file.',
'This project adheres to [Semantic Versioning](http://semver.org/).',
'',
'## [Unreleased][unreleased]',
''
].join('\n'), {encoding: 'utf8'}, function (err) {
if (err) {
console.error('chlg-init: cannot create file ‘' + program.file + '’: ' + err.message);
process.exit(1);
}
});
})
}
if (require.main === module) {
chlgInit();
} else {
module.exports = chlgInit;
}
|
JavaScript
| 0.000001 |
@@ -244,24 +244,16 @@
fs.stat(
-program.
file, fu
@@ -360,32 +360,24 @@
e file %E2%80%98' +
-program.
file + '%E2%80%99: F
@@ -437,24 +437,16 @@
iteFile(
-program.
file, %5B%0A
@@ -807,24 +807,16 @@
le %E2%80%98' +
-program.
file + '
|
e3ec139d0dc17c216e5764cc72a8a5cb71c5d8e7
|
Fix examples by building non-minified version of draft again (#2359)
|
gulpfile.js
|
gulpfile.js
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';
var packageData = require('./package.json');
var moduleMap = require('./scripts/module-map');
var fbjsConfigurePreset = require('babel-preset-fbjs/configure');
var del = require('del');
var gulpCheckDependencies = require('fbjs-scripts/gulp/check-dependencies');
var gulp = require('gulp');
var babel = require('gulp-babel');
var cleanCSS = require('gulp-clean-css');
var concatCSS = require('gulp-concat-css');
var derequire = require('gulp-derequire');
var flatten = require('gulp-flatten');
var header = require('gulp-header');
var gulpif = require('gulp-if');
var rename = require('gulp-rename');
var gulpUtil = require('gulp-util');
var StatsPlugin = require('stats-webpack-plugin');
var through = require('through2');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');
var webpackStream = require('webpack-stream');
var paths = {
dist: 'dist',
lib: 'lib',
src: [
'src/**/*.js',
'!src/**/__tests__/**/*.js',
'!src/**/__mocks__/**/*.js',
],
css: ['src/**/*.css'],
};
var babelOptsJS = {
presets: [
fbjsConfigurePreset({
stripDEV: true,
rewriteModules: {map: moduleMap},
}),
],
plugins: [require('@babel/plugin-proposal-nullish-coalescing-operator')],
};
var babelOptsFlow = {
presets: [
fbjsConfigurePreset({
target: 'flow',
rewriteModules: {map: moduleMap},
}),
],
plugins: [require('@babel/plugin-proposal-nullish-coalescing-operator')],
};
var COPYRIGHT_HEADER = `/**
* Draft v<%= version %>
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
`;
var wpStream = null;
var buildDist = function(opts) {
if (wpStream !== null) {
return wpStream;
}
var webpackOpts = {
externals: {
immutable: {
root: 'Immutable',
commonjs2: 'immutable',
commonjs: 'immutable',
amd: 'immutable',
},
react: {
root: 'React',
commonjs2: 'react',
commonjs: 'react',
amd: 'react',
},
'react-dom': {
root: 'ReactDOM',
commonjs2: 'react-dom',
commonjs: 'react-dom',
amd: 'react-dom',
},
},
output: {
filename: opts.output,
libraryTarget: 'umd',
library: 'Draft',
},
plugins: [
new webpackStream.webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(
opts.debug ? 'development' : 'production',
),
}),
new webpackStream.webpack.LoaderOptionsPlugin({
debug: opts.debug,
}),
new StatsPlugin(`../meta/bundle-size-stats/${opts.output}.json`, {
chunkModules: true,
}),
],
};
if (!opts.debug) {
webpackOpts.plugins.push(new UglifyJsPlugin());
}
wpStream = webpackStream(webpackOpts, null, function(err, stats) {
if (err) {
throw new gulpUtil.PluginError('webpack', err);
}
if (stats.compilation.errors.length) {
gulpUtil.log('webpack', '\n' + stats.toString({colors: true}));
}
});
return wpStream;
};
gulp.task(
'clean',
gulp.series(function() {
return del([paths.dist, paths.lib]);
}),
);
gulp.task(
'modules',
gulp.series(function() {
return gulp
.src(paths.src)
.pipe(babel(babelOptsJS))
.pipe(flatten())
.pipe(gulp.dest(paths.lib));
}),
);
gulp.task(
'flow',
gulp.series(function() {
return gulp
.src(paths.src)
.pipe(babel(babelOptsFlow))
.pipe(flatten())
.pipe(rename({extname: '.js.flow'}))
.pipe(gulp.dest(paths.lib));
}),
);
gulp.task(
'css',
gulp.series(function() {
return (
gulp
.src(paths.css)
.pipe(
through.obj(function(file, encoding, callback) {
var contents = file.contents.toString();
var replaced = contents.replace(
// Regex based on MakeHasteCssModuleTransform: ignores comments,
// strings, and URLs
/\/\*.*?\*\/|'(?:\\.|[^'])*'|"(?:\\.|[^"])*"|url\([^)]*\)|(\.(?:public\/)?[\w-]*\/{1,2}[\w-]+)/g,
function(match, cls) {
if (cls) {
return cls.replace(/\//g, '-');
} else {
return match;
}
},
);
replaced = replaced.replace(
// MakeHasteCssVariablesTransform
/\bvar\(([\w-]+)\)/g,
function(match, name) {
var vars = {
'fig-secondary-text': '#9197a3',
'fig-light-20': '#bdc1c9',
};
if (vars[name]) {
return vars[name];
} else {
throw new Error('Unknown CSS variable ' + name);
}
},
);
file.contents = Buffer.from(replaced);
callback(null, file);
}),
)
.pipe(concatCSS('Draft.css'))
// Avoid rewriting rules *just in case*, just compress
.pipe(cleanCSS({advanced: false}))
.pipe(header(COPYRIGHT_HEADER, {version: packageData.version}))
.pipe(gulp.dest(paths.dist))
);
}),
);
gulp.task(
'dist',
gulp.series('modules', 'css', function() {
var opts = {
debug: true,
output: 'Draft.js',
};
return gulp
.src('./lib/Draft.js')
.pipe(buildDist(opts))
.pipe(derequire())
.pipe(
gulpif(
'*.js',
header(COPYRIGHT_HEADER, {version: packageData.version}),
),
)
.pipe(gulp.dest(paths.dist));
}),
);
gulp.task(
'dist:min',
gulp.series('modules', function() {
var opts = {
debug: false,
output: 'Draft.min.js',
};
return gulp
.src('./lib/Draft.js')
.pipe(buildDist(opts))
.pipe(
gulpif(
'*.js',
header(COPYRIGHT_HEADER, {version: packageData.version}),
),
)
.pipe(gulp.dest(paths.dist));
}),
);
gulp.task(
'check-dependencies',
gulp.series(function() {
return gulp.src('package.json').pipe(gulpCheckDependencies());
}),
);
gulp.task(
'watch',
gulp.series(function() {
gulp.watch(paths.src, gulp.parallel('modules'));
}),
);
gulp.task(
'dev',
gulp.series(function() {
gulp.watch(paths.src, gulp.parallel('dist'));
}),
);
gulp.task(
'default',
gulp.series(
'check-dependencies',
'clean',
gulp.parallel('modules', 'flow'),
gulp.parallel('dist', 'dist:min'),
),
);
|
JavaScript
| 0.000238 |
@@ -1878,30 +1878,8 @@
%60;%0A%0A
-var wpStream = null;%0A%0A
var
@@ -1911,60 +1911,8 @@
) %7B%0A
- if (wpStream !== null) %7B%0A return wpStream;%0A %7D%0A
va
@@ -2945,16 +2945,22 @@
;%0A %7D%0A
+const
wpStream
|
7e9e0ef66e1b97ddb640a3278ed865fd55517cac
|
change selectors according to latest changes in spotify (#140)
|
src/controllers/SpotifyController.js
|
src/controllers/SpotifyController.js
|
const config = {
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
playStateClass: 'playing',
nextSelector: '#next',
previousSelector: '#previous'
}
// New version of spotify
if (window.location.hostname === 'open.spotify.com') {
delete config.playStateClass;
config.playStateSelector = '.now-playing-bar .control-button[class*="spoticon-play"]';
config.playSelector = '.now-playing-bar .control-button[class*="spoticon-play"]';
config.pauseSelector = '.now-playing-bar .control-button[class*="spoticon-pause"]';
config.artworkImageSelector = '.now-playing-bar .cover-art-image';
config.artistSelector = '.now-playing-bar [href^="/artist"]';
config.titleSelector = '.now-playing-bar [href^="/album"]';
config.nextSelector = '.now-playing-bar .control-button[class*="spoticon-skip-forward"]';
config.previousSelector = '.now-playing-bar .control-button[class*="spoticon-skip-back"]';
controller = new BasicController(config);
controller.override('isPlaying', function () {
return this.doc().querySelector('.now-playing-bar .control-button[class*="spoticon-pause"]');
})
// The album image also links to `/album/...`. Take last link for the title
controller.override('getTitle', function () {
const titleNodes = [...this.doc().querySelectorAll('.now-playing-bar [href^="/album"]')]
return titleNodes.pop().textContent
})
// There may be multiple artists linked per title
controller.override('getArtist', function () {
// Spread into array because `map` does not work reliably over NodeList.
const artistNodes = [...this.doc().querySelectorAll(config.artistSelector)]
return artistNodes.map(artist => artist.textContent).join(', ');
})
} else {
if (document.querySelector('#app-player')) { // Old Player
config.artworkImageSelector = '#cover-art .sp-image-img';
config.frameSelector = '#app-player';
config.playStateSelector = '#play-pause';
config.playPauseSelector = '#play-pause';
config.titleSelector = '#track-name';
config.artistSelector = '#track-artist';
} else { // New Player
config.artworkImageSelector = '#large-cover-image';
config.frameSelector = '#main';
config.playStateSelector = '#play';
config.playPauseSelector = '#pause';
config.titleSelector = '.caption .track';
config.artistSelector = '.caption .artist';
}
controller = new BasicController(config);
}
controller.override('getAlbumArt', function () {
const img = this.doc().querySelector(this.artworkImageSelector);
return img && img.style.backgroundImage.slice(5, -2);
})
|
JavaScript
| 0 |
@@ -313,16 +313,114 @@
eClass;%0A
+%0A const i18nLabels = JSON.parse(%0A document.querySelector('#jsonTranslations').innerHTML%0A );%0A%0A
config
@@ -432,33 +432,33 @@
StateSelector =
-'
+%60
.now-playing-bar
@@ -463,47 +463,87 @@
ar .
+player-
control
--
+s__
button
-%5Bclass*=%22spoticon-
+s %5Baria-label=%22$%7Bi18nLabels%5B'playback-control.
play
+'%5D%7D
%22%5D
-'
+%60
;%0A
@@ -556,33 +556,33 @@
.playSelector =
-'
+%60
.now-playing-bar
@@ -587,47 +587,87 @@
ar .
+player-
control
--
+s__
button
-%5Bclass*=%22spoticon-
+s %5Baria-label=%22$%7Bi18nLabels%5B'playback-control.
play
+'%5D%7D
%22%5D
-'
+%60
;%0A
@@ -681,33 +681,33 @@
pauseSelector =
-'
+%60
.now-playing-bar
@@ -712,48 +712,88 @@
ar .
+player-
control
--
+s__
button
-%5Bclass*=%22spoticon-
+s %5Baria-label=%22$%7Bi18nLabels%5B'playback-control.
pause
+'%5D%7D
%22%5D
-'
+%60
;%0A
@@ -1001,33 +1001,33 @@
.nextSelector =
-'
+%60
.now-playing-bar
@@ -1032,40 +1032,77 @@
ar .
+player-
control
--
+s__
button
-%5Bclass*=%22spoticon-
+s %5Baria-label=%22$%7Bi18nLabels%5B'playback-control.
skip
@@ -1109,19 +1109,22 @@
-forward
+'%5D%7D
%22%5D
-'
+%60
;%0A conf
@@ -1137,33 +1137,33 @@
viousSelector =
-'
+%60
.now-playing-bar
@@ -1168,40 +1168,77 @@
ar .
+player-
control
--
+s__
button
-%5Bclass*=%22spoticon-
+s %5Baria-label=%22$%7Bi18nLabels%5B'playback-control.
skip
@@ -1242,19 +1242,22 @@
kip-back
+'%5D%7D
%22%5D
-'
+%60
;%0A%0A con
@@ -1356,16 +1356,18 @@
return
+!!
this.doc
@@ -1387,67 +1387,28 @@
tor(
-'.now-playing-bar .control-button%5Bclass*=%22spoticon-pause%22%5D'
+config.pauseSelector
);%0A
|
ff64b01d87bc6312c6d8a13e0af9a540c691e950
|
Add JSDoc in chlg-init
|
lib/chlg-init.js
|
lib/chlg-init.js
|
'use strict';
var fs = require('fs');
module.exports = function chlgInit(file, callback) {
if (typeof file === 'function') {
callback = file;
file = null;
}
file = file || 'CHANGELOG.md';
if (typeof file !== 'string') {
return callback(new Error('Parameter ‘file’ must be a string'));
}
fs.stat(file, function (err) {
if (!err || err.code !== 'ENOENT') {
return callback(new Error('Cannot create file ‘' + file + '’: File exists'));
}
fs.writeFile(file, [
'# Change Log',
'All notable changes to this project will be documented in this file.',
'This project adheres to [Semantic Versioning](http://semver.org/).',
'',
'## [Unreleased][unreleased]',
''
].join('\n'), {encoding: 'utf8'}, function (error) {
return callback(error ? new Error('Cannot create file ‘' + file + '’: ' + error.message) : null);
});
});
};
|
JavaScript
| 0 |
@@ -12,32 +12,382 @@
';%0A%0A
-var fs = require('fs');%0A
+/**%0A * @module chlg-init%0A */%0A%0Avar fs = require('fs');%0A%0A/**%0A * Initiliaze a new change log with a standard boilerplate.%0A *%0A * @see %7B@link http://keepachangelog.com/%7D%0A *%0A * @param %7Bstring%7D %5Bfile=CHANGELOG.md%5D - File name/path of the new change log%0A * @param %7BFunction%7D callback - Callback invoked with an optional error when the change log is initialized%0A */
%0Amod
|
1454c986fd586daf910ccaf50e1b8dc08dc79bb4
|
add tasks
|
gulpfile.js
|
gulpfile.js
|
JavaScript
| 0.999992 |
@@ -0,0 +1,383 @@
+'use strict';%0A%0Avar pkg = require('./package.json');%0Avar gulp = require('gulp');%0Avar plugins = require('gulp-load-plugins');%0A%0A/** Gulp dependencies */%0Avar autoprefixer = plugins.autoprefixer;%0Avar sass = plugins.sass;%0A%0A%0Agulp.task('default', %5B'build'%5D);%0A%0Agulp.task('build', %5B'build-scss', 'build-js'%5D);%0A%0Agulp.task('build-scss', function () %7B%7D);%0A%0Agulp.task('build-js', function () %7B%0A%7D);%0A
|
|
90ad5bf3a5c2f4e72d8b112679d4d7f87995fad0
|
Add some chalk logging
|
lib/cliHelper.js
|
lib/cliHelper.js
|
var configHelper = require('./config-helper');
var path = require('path');
var spawnHelper = require('./spawnHelper');
var buildCliCommand = function(configPath) {
var cliPath = path.join(
__dirname, '../node_modules/protractor-elementor/lib/cli.js');
return 'node ' + cliPath + ' ' +
'--elementExplorer true ' +
'--debuggerServerPort 6969 ' +
configPath;
};
var startProtractor = function(options) {
console.log('Creating protractor configuration file');
return configHelper.createProtractorConfig(options).then(function(configPath) {
var cliCommand = buildCliCommand(configPath);
console.log('Starting protractor with command: [%s]', cliCommand);
return spawnHelper.runCommand(cliCommand, 'Server listening on');
});
};
module.exports = {
startProtractor: startProtractor
};
|
JavaScript
| 0 |
@@ -1,12 +1,42 @@
+var chalk = require('chalk');%0A
var configHe
@@ -514,22 +514,29 @@
le');%0A
-return
+var promise =
configH
@@ -572,16 +572,34 @@
options)
+;%0A return promise
.then(fu
@@ -627,126 +627,106 @@
-var cliCommand = buildCliCommand(configPath);%0A console.log('Starting protractor with command: %5B%25s%5D', cliCommand
+console.log(chalk.blue('Starting protractor'));%0A var cliCommand = buildCliCommand(configPath
);%0A
-%0A
@@ -767,17 +767,17 @@
ommand,
-'
+/
Server l
@@ -787,17 +787,18 @@
ening on
-'
+/g
);%0A %7D);
|
78081ee4443e8331e459fa87311aad3c2a8d9e8b
|
Clean console
|
lib/asem51.js
|
lib/asem51.js
|
//ES6
'use strict';
const spawn = require('child_process').spawn;
const minimist = require('minimist');
const asembin_default = 'asem';
const options_default = '--columns';
class ASEM51 {
constructor() { }
static asyncAsem(args) {
let argv = minimist(args.slice(2), {
boolean: ['o', 'v'],
default: { v: false, o: false }
})
let asembin = process.env.ASEM51 || asembin_default;
let file = argv['_'][0];
let options = options_default;
let argopts = [];
console.log(argv);
argopts.push(options_default);
// TODO: should check long version option
if (argv['i']) {
options = argopts.push(`-i ${argv['i']}`);
}
if (argv['d']) {
options = argopts.push(`-d ${argv['d']}`);
}
argopts.push(file);
return new Promise((resolve, reject) => {
if (file != undefined) {
let asem = spawn(asembin, argopts);
asem.on('error', err => reject(err.toString()));
asem.stdout.on('data', (data) => {
resolve(data.toString());
});
asem.stderr.on('data', (data) => {
resolve(ASEM51.parseError(file, data.toString()));
});
} else {
let asem = spawn(asembin);
asem.on('error', err => reject(err.toString()));
asem.stdout.on('data', data => resolve(data.toString()));
asem.stderr.on('data', data => resolve(data.toString()));
}
})
}
static parseError(fileName, stderr) {
let errMessageArray = [];
let errAllArray = stderr.split('\n').filter(n => n != '');
let isError = errAllArray[0].split(' ').filter(n => n == '@@@@@');
if (isError.length > 1) {
errMessageArray.push({ "error": stderr });
} else {
errAllArray.forEach((element, index, array) => ASEM51.parseErrorElement(fileName, element, errMessageArray));
}
return errMessageArray;
}
static parseErrorElement(fileName, err, errMessageArray) {
let errAll = err.split(':');
let errMessage = errAll[1];
/**
* Parse error message with RegEx
* ex: "file.a51(1,10): error message" to ['1', '10]
*/
if (errAll[1]) {
let lineCols = errAll[0].match(/\((.*)\)/)[1];
let lineCol = lineCols.split(",");
let errMessageObj = {};
errMessageObj.file = fileName;
errMessageObj.line = lineCol[0];
errMessageObj.column = lineCol[1];
errMessageObj.message = errMessage;
errMessageArray.push(errMessageObj);
} else {
errMessageArray.push({ "error": err });
}
return errMessageArray;
}
}
module.exports = ASEM51;
|
JavaScript
| 0 |
@@ -542,36 +542,8 @@
%5D;%0A%0A
- console.log(argv);%0A%0A
|
022e3ad366b31ca73d5a448d7b70915024c575a9
|
Use Browser Sync in gulp
|
gulpfile.js
|
gulpfile.js
|
/********************************************************
* Options
*******************************************************/
var options = {
'folders': {
'app_package': 'public',
'source': '/sources',
'dest': '/distribution'
}
};
/********************************************************
* Gulp
*******************************************************/
var gulp = require('gulp');
var gutil = require('gulp-util');
var cssnano = require('gulp-cssnano');
var autoprefixer = require('gulp-autoprefixer');
var notify = require("gulp-notify");
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var source = require('vinyl-source-stream');
var buffer = require('vinyl-buffer');
var browserify = require('browserify');
var watchify = require('watchify');
var babelify = require('babelify');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var sassdoc = require('sassdoc');
var esdoc = require("gulp-esdoc");
var save = require('gulp-save');
var browserSync = require('browser-sync').create();
var folder_source = options.folders.app_package + options.folders.source;
var folder_dest = options.folders.app_package + options.folders.dest;
/********************************************************
* Tasks
*******************************************************/
gulp.task('default', ['css', 'js'], function () {
});
gulp.task('watch', function () {
browserSync.init({
ui: false,
ghostMode: false,
proxy: {
target: 'localhost:8000',
ws: true
}
});
gulp.watch(folder_source + '/scss/**/*.scss', ['css']);
gulp.watch(folder_source + '/javascript/**/*.js', ['js']);
gulp.watch(folder_dest + '/**/*').on('change', browserSync.reload);
//buildScript('index.js', true);
});
gulp.task('js', function () {
return buildScript('index.js', false);
});
gulp.task('css', function () {
return buildCss('app.scss');
});
/********************************************************
* Documentations
*******************************************************/
gulp.task('sassdoc', function () {
return gulp
.src(folder_source + '/scss/app.scss')
.pipe(sassdoc({
'dest': './Web/doc/sass'
}))
.resume();
});
gulp.task('jsdoc', function () {
return gulp.src(folder_source + '/javascript')
.pipe(esdoc({destination: "./Web/doc/js"}));
});
/********************************************************
* Asset build functions
*******************************************************/
function buildCss(file) {
var sassOptions = {
outputStyle: 'expanded'
};
var job = gulp.src(folder_source + '/scss/' + file)
.pipe(sass(sassOptions))
.pipe(autoprefixer('last 2 version', 'safari 5', 'ie 8', 'ie 9', 'opera 12.1', 'ios 6', 'android 4'))
.pipe(sass().on('error', sass.logError))
.pipe(save('before-minify'))
.pipe(cssnano())
.pipe(rename('app.min.css'))
.pipe(gulp.dest(folder_dest + '/css/'))
.pipe(save.restore('before-minify'))
.pipe(sourcemaps.init())
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(folder_dest + '/css'))
.pipe(notify('SASS completed.'));
return job;
}
function buildScript(file, watch) {
var props = {
entries: [folder_source + '/javascript/' + file],
debug: true,
transform: [[babelify, {presets: ["es2015"]}]]
};
var bundler = watch ? watchify(browserify(props)) : browserify(props);
function rebundle() {
var stream = bundler.bundle();
return stream
.on('error', handleErrors)
.pipe(source(file))
.pipe(buffer())
.pipe(save('before-uglify'))
.pipe(uglify())
.pipe(rename('app.min.js'))
.pipe(gulp.dest(folder_dest + '/javascript/'))
.pipe(save.restore('before-uglify'))
.pipe(rename('app.js'))
.pipe(sourcemaps.init({loadMaps: true}))
.pipe(sourcemaps.write('./'))
.pipe(gulp.dest(folder_dest + '/javascript/'))
.pipe(notify('Javascript completed.'));
}
bundler.on('update', function () {
rebundle();
gutil.log('Rebundle javascript...');
});
return rebundle();
}
function handleErrors() {
var args = Array.prototype.slice.call(arguments);
notify.onError({
title: 'Compile Error',
message: '<%= error.message %>'
}).apply(this, args);
this.emit('end'); // Keep gulp from hanging on this task
}
|
JavaScript
| 0 |
@@ -1,28 +1,57 @@
+require('dotenv').config();%0A%0A
/***************************
@@ -1583,13 +1583,28 @@
ost:
-8000'
+' + process.env.PORT
,%0A
|
16aef7f2bcbb26ac5c98e0a6d5442be1abc30c33
|
Update cursorhelp.js
|
js/cursorhelp.js
|
js/cursorhelp.js
|
/*
* CursorHelp v1.1 (24.8.14)
* http://ms27.github.io/CursorHelp/
*
* Copyright 2014, Magomedov Said.
* Free to use under the MIT license.
* http://www.opensource.org/licenses/mit-license.php
*/
$(document).ready(function (){
$('body').append('<div id="cursorTitle"><div class="TitleContent"></div><div class="TitleCorner true"></div></div>');
$('.cursorTitle').mouseenter(function(){ var CursorHelp = $('#cursorTitle'), CH_Title =$(this).attr('data-title'); CH_Config=$(this).attr('data-ch-config'); CursorHelp.find('.TitleContent').html( CH_Title ); if(CH_Config !== ''){ CursorHelp.addClass(CH_Config); } }).mousemove(function (e) { var CursorHelp = $('#cursorTitle'), windowH=$(window).height(), scrollTop = $(window).scrollTop(); var cursorMargin = 30; var CH_TitleWidth=CursorHelp.outerWidth(), CH_TitleHeight =CursorHelp.outerHeight(), CH_MyConfig=''; var CH_PosX = e.pageX-CH_TitleWidth/2, CH_PosY = e.pageY+cursorMargin, CH_CornerBox=CursorHelp.find('.TitleCorner'), CH_CornerBoxW = CH_CornerBox.outerWidth(); CursorHelp.css({left : CH_PosX + 'px', top: CH_PosY + 'px'}).addClass('visible'); CH_CornerBox.removeClass('top'); CH_CornerBox.css({right : CH_TitleWidth/2-CH_CornerBoxW/2+'px'}); if( (e.pageX+CH_TitleWidth/2) > $('body').width() ){ CursorHelp.css({left : CH_PosX+$('body').width()-(e.pageX+CH_TitleWidth/2) + 'px'}); CH_CornerBox.css({right : $('body').width()-e.pageX-CH_CornerBoxW/2 + 'px'}); if( $('body').width() - CH_CornerBox.offset().left - CH_CornerBoxW < 4){ CH_CornerBox.css({right : '2px'}); } } var CH_Left = CursorHelp.offset().left; if( CH_Left < 0 ){ CursorHelp.css({left : CH_PosX - CH_Left + 'px'}); CH_CornerBox.css({left : e.pageX-CH_CornerBoxW/2-2 + 'px'}); if(CH_CornerBox.offset().left < 4){ CH_CornerBox.css({left : '4px'}); } } if( CH_PosY+CH_TitleHeight > windowH ){ CursorHelp.css({top: CH_PosY-CH_TitleHeight-cursorMargin*2 + 'px'}); CH_CornerBox.position().top; CH_CornerBox.addClass('top'); } if (void 0 !== $(this).attr('data-sh-style')){ CH_MyConfig=$(this).attr('data-ch-style'); } if(CH_MyConfig !== ''){ var CH_OldStyle = CursorHelp.attr('style'); CursorHelp.attr('style', CH_OldStyle+CH_MyConfig); } CH_CornerBox.css({borderColor : CursorHelp.css('border-color'),backgroundColor:CursorHelp.css('background-color')}); }).mouseleave(function () { $('#cursorTitle').find('.TitleContent').html(''); $('#cursorTitle').find('.TitleCorner').attr('style',''); $('#cursorTitle').attr('style','').attr('class',''); }); });
|
JavaScript
| 0.000001 |
@@ -1810,16 +1810,26 @@
windowH
++scrollTop
)%7B Curs
|
9d7c48d65fac7a9bd7bdab41b81303d99a3edeee
|
remove `instanceof Array`
|
lib/assert.js
|
lib/assert.js
|
/**
* @author Toru Nagashima
* @copyright 2016 Toru Nagashima. All rights reserved.
* See LICENSE file in root directory for full license.
*/
"use strict"
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
const assert = require("assert")
//------------------------------------------------------------------------------
// Helpers
//------------------------------------------------------------------------------
const AIUEO = /^[aiueo]/i
const STARTS_WITH_FUNCTION = /^function /
/**
* Gets the proper article of the given name.
*
* @param {string} name - The name to get.
* @returns {string} The proper article of the name.
* @private
*/
function articleOf(name) {
if (name === "null" || name === "undefined") {
return ""
}
if (STARTS_WITH_FUNCTION.test(name)) {
return ""
}
return AIUEO.test(name) ? "an " : "a "
}
/**
* Gets the type name of the given value.
*
* @param {any} value - The value to get.
* @returns {string} The type name of the value.
* @private
*/
function typeNameOf(value) {
if (value === null) {
return "null"
}
if (Number.isInteger(value)) {
return "integer"
}
const type = typeof value
if (type === "object" &&
value.constructor &&
value.constructor.name &&
value.constructor.name !== "Object"
) {
return `${value.constructor.name} object`
}
if (type === "function") {
if (value.name) {
return `function ${JSON.stringify(value.name)}`
}
return "anonymous function"
}
return type
}
/**
* Gets the type name of the given value.
*
* @param {any} value - The value to get.
* @returns {string} The type name of the value.
* @private
*/
function typeOf(value) {
const type = typeNameOf(value)
return `${articleOf(type)}${type}`
}
//------------------------------------------------------------------------------
// Export
//------------------------------------------------------------------------------
module.exports = Object.assign(
(test, message) => {
assert(test, message)
},
assert,
{
boolean(value, name) {
assert(typeof value === "boolean", `'${name}' should be a boolean, but got ${typeOf(value)}.`)
},
number(value, name) {
assert(typeof value === "number", `'${name}' should be a number, but got ${typeOf(value)}.`)
},
string(value, name) {
assert(typeof value === "string", `'${name}' should be a string, but got ${typeOf(value)}.`)
},
object(value, name) {
assert(typeof value === "object" && value != null, `'${name}' should be an object, but got ${typeOf(value)}.`)
},
function(value, name) {
assert(typeof value === "function", `'${name}' should be a function, but got ${typeOf(value)}.`)
},
numberOrString(value, name) {
const type = typeof value
assert(type === "number" || type === "string", `'${name}' should be a number or a string, but got ${typeOf(value)}.`)
},
instanceOf(value, type, name) {
assert(value instanceof type, `'${name}' should be ${articleOf(type.name)}${type.name} object, but got ${typeOf(value)}.`)
},
integer(value, name) {
assert(Number.isInteger(value), `'${name}' should be an integer, but got ${typeOf(value)}.`)
},
gte(value, min, name) {
assert(value >= min, `'${name}' should be '>=${min}', but got ${value}.`)
},
lte(value, max, name) {
assert(value <= max, `'${name}' should be '<=${max}', but got ${value}.`)
},
range(value, min, max, name) {
assert(value >= min && value <= max, `'${name}' should be within '${min}..${max}', but got ${value}.`)
},
bitOffsetX8(value, accessorTypeName) {
this.integer(value, "bitOffset")
assert((value & 0x07) === 0, `'bitOffset' should be a multiple of 8 for '${accessorTypeName}', but got ${value}.`)
},
}
)
|
JavaScript
| 0.000001 |
@@ -3292,24 +3292,81 @@
assert(
+%0A type === Array ? Array.isArray(value) :
value instan
@@ -3375,16 +3375,32 @@
of type,
+%0A
%60'$%7Bnam
@@ -3475,32 +3475,45 @@
typeOf(value)%7D.%60
+%0A
)%0A %7D,%0A%0A
|
2b4486bedccaafa8382ebffb530f60a0ca07f59d
|
fix scope in ionAudioControls directive
|
src/directives/ion-audio-controls.js
|
src/directives/ion-audio-controls.js
|
angular.module('ionic-audio').directive('ionAudioControls', function() {
return {
restrict: 'EA',
require: ['ionAudioControls', '^^ionAudioTrack'],
controller: ['$scope', '$element', ionAudioControlsCtrl],
link: link
};
function ionAudioControlsCtrl($scope, $element) {
var spinnerElem = $element.find('ion-spinner'), hasLoaded, self = this;
spinnerElem.addClass('ng-hide');
this.toggleSpinner = function() {
spinnerElem.toggleClass('ng-hide');
};
this.play = function() {
if (!hasLoaded) {
self.toggleSpinner();
}
//$scope.track.play();
this.start();
};
var unbindStatusListener = $scope.$watch('track.status', function (status) {
switch (status) {
case 1: // Media.MEDIA_STARTING
hasLoaded = false;
break;
case 2: // Media.MEDIA_RUNNING
if (!hasLoaded) {
self.toggleSpinner();
hasLoaded = true;
}
break;
//case 3: // Media.MEDIA_PAUSED
// break;
case 0: // Media.MEDIA_NONE
case 4: // Media.MEDIA_STOPPED
hasLoaded = false;
break;
}
});
$scope.$on('$destroy', function() {
unbindStatusListener();
});
}
function link(scope, element, attrs, controllers) {
controllers[0].start = controllers[1].start;
}
});
|
JavaScript
| 0 |
@@ -246,20 +246,16 @@
%7D;%0A%0A
-
function
@@ -632,41 +632,8 @@
%7D%0A
- //$scope.track.play();%0A
@@ -707,16 +707,24 @@
$scope.$
+parent.$
watch('t
|
d65379f168c569209d073f3473ffcdb859f430b7
|
Fix Clock weekday to always return a time in the future
|
src/js/clock/clock.js
|
src/js/clock/clock.js
|
var Clock = module.exports;
Clock.weekday = function(weekday, hour, minute, seconds) {
return moment({ hour: hour, minute: minute, seconds: seconds }).day(weekday).unix();
};
|
JavaScript
| 0.000002 |
@@ -87,14 +87,42 @@
%7B%0A
-return
+var now = moment();%0A var target =
mom
@@ -187,16 +187,105 @@
weekday)
+;%0A if (moment.max(now, target) === now) %7B%0A target.add(1, 'week');%0A %7D%0A return target
.unix();
|
1552a305c2a710b239d8fff4bdf91af486d5157b
|
Update profile-content.js
|
containers/profile-content.js
|
containers/profile-content.js
|
'use strict'
/* @flow */
import React, { Component } from 'react'
import { style } from 'next/css'
import { connect } from 'react-redux'
import Alert from 'react-s-alert'
import fetchAccount from '../actions/fetch-account'
import confirmSummoner from '../actions/confirm-summoner'
import EmptyState from './../components/empty-state'
import Intro from './../components/intro'
import MySummoners from './../components/my-summoners'
import Loading from './../components/loading'
import ModalTutorial from './../components/modal-tutorial'
import { CONFIRM_SUMMONER_SUCCESS, CONFIRM_SUMMONER_ERROR } from './../constants'
class ProfileContent extends Component {
constructor () {
super()
this.handleConfirmSummoner = this.handleConfirmSummoner.bind(this)
this.state = {
modalTutorial: false,
profile: {
requested: false,
requesting: false
}
}
}
componentDidMount () {
this.props.fetchAccount()
}
componentWillReceiveProps(nextProps) {
this.setState({profile: nextProps.user})
}
handleConfirmSummoner (summoner) {
this.props.confirmSummoner(summoner)
.then(({ data, type }) => {
if (data) {
Alert.success('Invocador confirmado!', {position: 'top-right'})
this.props.fetchAccount()
} else {
Alert.error('Invocador não confimador ainda', {position: 'top-right'})
this.setState({ modalTutorial: true })
}
})
}
render() {
let profile = null
let summoners = null
if (this.props.profile.requested) {
const location = this.props.profile.data.user.country ? `${this.props.profile.data.user.city}, ${this.props.profile.data.user.state} ${this.props.profile.data.user.country}` : 'Adicionar Localização'
profile = <Intro name={this.props.profile.data.user.name} location={location}/>
if (this.props.profile.data.summoners.length > 0) {
summoners = <MySummoners summoners={this.props.profile.data.summoners} confirmSummoner={this.handleConfirmSummoner}/>
} else {
summoners = <EmptyState />
}
} else {
profile = <Loading />
}
return (
<div>
{profile}
{summoners}
<Alert effect="jelly" stack={{limit: 3}}/>
<ModalTutorial open={this.state.modalTutorial}/>
</div>
)
}
}
const mapStateToProps = state => {
return {
profile: state.account
}
}
const mapDispatchToProps = dispatch => {
return {
fetchAccount: () => dispatch(fetchAccount()),
confirmSummoner: summoner => dispatch(confirmSummoner(summoner))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ProfileContent)
|
JavaScript
| 0.000001 |
@@ -1358,16 +1358,52 @@
or ainda
+, tente novamente em alguns segundos
', %7Bposi
|
f08d7549e08b75a3121b249830e06b2940c32f5f
|
remove redundant dependency
|
src/stock-adjustment-creation/adjustment-creation.module.js
|
src/stock-adjustment-creation/adjustment-creation.module.js
|
/*
* This program is part of the OpenLMIS logistics management information system platform software.
* Copyright © 2017 VillageReach
*
* This program is free software: you can redistribute it and/or modify it under the terms
* of the GNU Affero General Public License as published by the Free Software Foundation, either
* version 3 of the License, or (at your option) any later version.
*
* 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 Affero General Public License for more details. You should have received a copy of
* the GNU Affero General Public License along with this program. If not, see
* http://www.gnu.org/licenses. For additional information contact [email protected].
*/
(function () {
'use strict';
angular.module('stock-adjustment-creation', [
'openlmis-date',
'stock-adjustment',
'stock-confirm-discard',
'stock-card-summaries',
'stock-orderable-group',
'stock-product-name',
'stock-constants',
'stock-valid-reason',
'referencedata-program',
'referencedata-facility',
'referencedata-orderable',
'stock-reasons'
]);
})();
|
JavaScript
| 0.000012 |
@@ -1241,43 +1241,8 @@
y',%0A
- 'referencedata-orderable',%0A
|
4b016139fa7f588a811bde246f4a57684e0f8e7c
|
Fix geo/time/genre in search list
|
src/js/home/search.js
|
src/js/home/search.js
|
(function() {
'use strict';
angular
.module('app.modules.search', ['app.services.config', 'app.services.subject'])
.directive('modSearch', SearchModule);
function SearchModule() {
var directive = {
restrict: 'A',
templateUrl: 'app/search.html',
replace: false,
scope: {},
controllerAs: 'vm',
controller: ['$scope', '$state', '$stateParams', '$timeout', '$rootScope', '$q', '$http', '$filter', 'gettext', 'gettextCatalog', 'Config', 'Lang', 'SubjectService', controller]
};
return directive;
}
function controller($scope, $state, $stateParams, $timeout, $rootScope, $q, $http, $filter, gettext, gettextCatalog, Config, Lang, SubjectService) {
/*jshint validthis: true */
var vm = this;
// vm.searchUrl = Config.skosmos.searchUrl;
vm.lang = Lang.language;
vm.defaultLang = Lang.defaultLanguage;
vm.vocab = ($stateParams.vocab && $stateParams.vocab != 'all') ? $stateParams.vocab : null;
// vm.formatRequest = formatRequest;
// vm.formatResult = formatResult;
vm.selectSubject = selectSubject;
vm.openSearcMenu = openSearcMenu;
vm.searchTruncation = searchTruncation;
vm.truncate = 0;
vm.query="";
vm.truncations = [gettext('Starting with'), gettext('Containing'), gettext('Ends with'), gettext('Exact match')];
vm.search = search;
vm.errorMsg = '';
vm.searchHistory = [];
activate();
////////////
function activate() {
vm.searchHistory = SubjectService.searchHistory;
SubjectService.onSubject($scope, function (subject) {
vm.searchHistory = SubjectService.searchHistory;
});
}
//Temporary solution until angucomplete gets a proper search-on-focus behaviour
function openSearcMenu() {
var query = document.getElementById('search_value');
angular.element(query).triggerHandler('input');
angular.element(query).triggerHandler('keyup');
}
function searchTruncation(truncate) {
vm.truncate = truncate;
openSearcMenu();
}
function formatRequest(str) {
var query;
switch(vm.truncate) {
case 0: //Starting
query = str + '*';
break;
case 1: //Contains
query = (str.length == 2) ? str : '*' + str + '*';
break;
case 2: //Ends
query = '*' + str;
break;
case 3: //Exact match
query = str;
break;
}
return {
query: query,
labellang: vm.lang,
vocab: vm.vocab
};
}
function matchResult(str,query) {
if (vm.truncate===0 && query == str.substr(0,query.length)) return "Starting with";
if (vm.truncate===1 && str.indexOf(query)>-1) return "Containing";
if (vm.truncate===2 && query == str.substr((str.length-query.length),query.length)) return "Ends with";
if (vm.truncate===3 && query == str) return "Exact Match";
return false;
}
function formatResult(response,query) {
//console.log('Got response',response);
var result = [];
//Remove duplicates and add matchedPreflabel and some notation where there is a match
response.results.forEach(function (value, key) {
var searchListIcon="";
// Add Geographics/Temporal/GenreForm to list
for (var i=0; i<value.type.length; i++) {
var str = value.type[i].split(":")[1];
if (str=="Geographic") {
searchListIcon ="<span><i class=\"glyphicon glyphicon-map-marker\"></i><em> "+gettextCatalog.getString(str)+"</em></span>";
break;
}
else if (str=="Temporal") {
searchListIcon ="<span><i class=\"glyphicon glyphicon-time\"></i><em> "+gettextCatalog.getString(str)+"</em></span>";
break;
}
else if (str=="GenreForm") {
searchListIcon ="<span><i class=\"glyphicon glyphicon-list-alt\"></i><em> "+gettextCatalog.getString(str)+"</em></span>";
break;
}
}
if (value.prefLabel!==undefined) {
//Check if match is on prefLabel
if (matchResult(value.prefLabel.toLocaleLowerCase(),query.toLocaleLowerCase())) {
//PrefLabel might exist from before
if (!$filter('filter')(result, {uri : value.uri}, true).length){
result.push({searchListIcon:searchListIcon,prefLabel:value.prefLabel,uri:value.uri});
}
}
//Or on matchedPrefLabel or altLabel
else {
if (value.matchedPrefLabel){
if (!$filter('filter')(result, {uri : value.uri}, true).length){
result.push({searchListIcon:searchListIcon,prefLabel:value.prefLabel,uri:value.uri,description:"("+value.matchedPrefLabel+")"});
}
}
else if (value.altLabel){
if (!$filter('filter')(result, {uri : value.uri}, true).length){
result.push({searchListIcon:searchListIcon,prefLabel:value.prefLabel,uri:value.uri,description:"("+value.altLabel+")"});
}
}
}
}
});
return result;
}
function search(query) {
vm.query=query;
var deferred = $q.defer();
//console.log('Searching with...',query);
vm.errorMsg = '';
$http({
method: 'GET',
cache: true,
url: Config.skosmos.searchUrl,
params: formatRequest(query),
ignoreLoadingBar: true // angular-loading-bar
}).
then(function(data){
vm.searchResults = data.data;
var processed = formatResult(vm.searchResults,query);
deferred.resolve(processed);
}, function(error, q){
if (error.status == -1) {
vm.errorMsg = gettext('No network connection');
} else {
vm.errorMsg = error.statusText;
}
deferred.resolve({results: []});
});
return deferred.promise;
}
function shortIdFromUri(uri) {
var s = uri.split('/'),
id = s.pop(),
vocab = s.pop();
return id;
}
function selectSubject(item) {
//console.log('selectSubject');
if (item) {
// console.log(item.originalObject.uri);
var subjectId = shortIdFromUri(item.originalObject.uri);
console.log('[SearchController] Selecting subject: ' + subjectId);
$state.go('subject.search', {
id: subjectId,
term: null
});
}
}
}
})();
|
JavaScript
| 0.998129 |
@@ -3204,17 +3204,17 @@
.split(%22
-:
+#
%22)%5B1%5D;%0A%0A
@@ -3228,26 +3228,21 @@
(str==%22
-Geographic
+Place
%22) %7B%0A%09%09%09
@@ -3409,23 +3409,19 @@
(str==%22T
-emporal
+ime
%22) %7B%0A%09%09%09
|
24405931e5b0c44e173e309fabed3be42d6a3c50
|
add `component.paths()` helper function
|
lib/component.js
|
lib/component.js
|
/**
* Module dependencies.
*/
var Package = require('./Package')
, mkdir = require('mkdirp')
, utils = require('./utils')
, fs = require('fs')
, path = require('path')
, exists = fs.existsSync
, request = require('superagent');
/**
* Remote.
*/
var remote = 'http://50.116.26.197/components'; // TODO: settings
/**
* Expose utils.
*/
exports.utils = utils;
/**
* Install the given `pkg` at `version`.
*
* @param {String} pkg
* @param {String} version
* @param {Object} options
* @return {Package}
* @api public
*/
exports.install = function(pkg, version, options){
return new Package(pkg, version, options);
};
/**
* Fetch info for the given `pkg` at `version`.
*
* @param {String} pkg
* @param {String} version
* @return {Package}
* @api public
*/
exports.info = function(pkg, version, fn){
pkg = new Package(pkg, version);
pkg.getJSON(fn);
};
/**
* Check if component `name` exists in ./components.
*
* @param {String} name
* @return {Boolean}
* @api public
*/
exports.exists = function(name){
name = name.replace('/', '-');
var file = path.join('components', name);
return exists(file);
};
/**
* Search with the given `query` and callback `fn(err, components)`.
*
* @param {String} query
* @param {Function} fn
* @api public
*/
exports.search = function(query, fn){
var url = query
? remote + '/search/' + encodeURIComponent(query)
: remote + '/all';
request.get(url, function(err, res){
if (err) return fn(err);
fn(null, res.body);
});
};
/**
* Register `username` and `project`.
*
* @param {String} username
* @param {String} project
* @param {Object} json config
* @param {Function} fn
* @api public
*/
exports.register = function(username, project, conf, fn){
var url = remote + '/component/' + username + '/' + project;
request
.post(url)
.send(conf)
.end(function(err, res){
if (err) return fn(err);
if (!res.ok) return fn(new Error('got ' + res.status + ' response ' + res.text));
fn();
});
};
/**
* Fetch readme docs for `pkg`.
*
* @param {String} pkg
* @param {Function} fn
* @api public
*/
exports.docs = function(pkg, fn){
var url = 'https://api.github.com/repos/' + pkg + '/readme';
request
.get(url)
.end(function(err, res){
if (err) return fn(err);
if (!res.ok) return fn();
fn(null, res.body);
});
};
/**
* Fetch `pkg` changelog.
*
* @param {String} pkg
* @param {Function} fn
* @api public
*/
exports.changes = function(pkg, fn){
// TODO: check changelog etc...
exports.file(pkg, 'History.md', fn);
};
/**
* Fetch `pkg`'s `file` contents.
*
* @param {String} pkg
* @param {String} file
* @param {Function} fn
* @api public
*/
exports.file = function(pkg, file, fn){
var url = 'https://api.github.com/repos/' + pkg + '/contents/' + file;
request
.get(url)
.end(function(err, res){
if (err) return fn(err);
if (!res.ok) return fn();
fn(null, res.body);
});
};
|
JavaScript
| 0.000001 |
@@ -375,16 +375,221 @@
utils;%0A%0A
+/**%0A * Return __COMPONENT_PATH__ values.%0A *%0A * @return %7BArray%7D%0A * @api public%0A */%0A%0Aexports.paths = function()%7B%0A return process.env.COMPONENT_PATH%0A ? process.env.COMPONENT_PATH.split(':')%0A : %5B%5D;%0A%7D;%0A%0A
/**%0A * I
|
d5521cb9c619bb28d80dff26b709ec3fc49088ff
|
Make profiling code more error-resistant
|
lib/component.js
|
lib/component.js
|
var path = require('path')
var mktemp = require('mktemp')
var RSVP = require('rsvp')
exports.Component = Component
function Component () {}
// Called before each build
Component.prototype.setup = function (options) {
var self = this
if (this._setupOptions != null) {
throw new Error(this + ' already set up. Did you insert it in more than one place? That is not (yet?) supported.')
}
this._setupOptions = {}
Object.keys(options).forEach(function (key) {
self._setupOptions[key] = options[key]
})
if (this._setupOptions.componentStack == null) {
// `componentStack` is shared between this component and all of its
// children, and is used for timing
this._setupOptions.componentStack = []
}
this._setupChildComponents(this._childComponents || [])
this._milliseconds = 0
}
// Called after each build
Component.prototype.teardown = function () {
this._setupOptions = null
this._teardownChildComponents(this._childComponents || [])
}
Component.prototype.addChildComponents = function (components) {
this._childComponents = (this._childComponents || []).concat(components)
if (this._setupOptions != null) this._setupChildComponents(components)
}
Component.prototype._setupChildComponents = function (components) {
for (var i = 0; i < components.length; i++) {
components[i].setup(this._setupOptions)
}
}
Component.prototype._teardownChildComponents = function (components) {
for (var i = 0; i < components.length; i++) {
components[i].teardown()
}
}
Component.prototype.toString = function () {
return '[object ' + (this.constructor && this.constructor.name || 'Object') + ']'
}
Component.prototype.friendlyName = function () {
return this.constructor && this.constructor.name || 'Object'
}
// Get the per-instance cache directory for this component
Component.prototype.getCacheDir = function () {
if (this._cacheDir == null) {
var cacheDirName = (this.constructor.name.toLowerCase() || 'component') + '-cache-XXXXXX.tmp'
this._cacheDir = mktemp.createDirSync(path.join(this._setupOptions.cacheDir, cacheDirName))
}
return this._cacheDir
}
// Make a new temporary directory, which will be removed when the build has
// finished
Component.prototype.makeTmpDir = function () {
var tmpDirName = (this.constructor.name.toLowerCase() || 'component') + '-XXXXXX.tmp'
return mktemp.createDirSync(path.join(this._setupOptions.tmpDir, tmpDirName))
}
// Component::withTimer is the main entry point to a horrible profiling
// implementation. The time until the value or promise returned from fn has
// resolved is added to the current component's timing. We might remove all of
// this in the future.
Component.prototype.withTimer = function (fn) {
var self = this
acquireTimer()
return RSVP.Promise.cast(fn()).finally(releaseTimer)
function acquireTimer () {
if (self._setupOptions.componentStack.length) {
self._setupOptions.componentStack[self._setupOptions.componentStack.length - 1]
._stopTimer()
}
self._setupOptions.componentStack.push(self)
self._startTimer()
}
function releaseTimer () {
var poppedComponent = self._setupOptions.componentStack.pop()
if (poppedComponent !== self) throw new Error('Expected to pop ' + self + ', got ' + poppedComponent)
self._stopTimer()
if (self._setupOptions.componentStack.length) {
self._setupOptions.componentStack[self._setupOptions.componentStack.length - 1]
._startTimer()
}
}
}
Component.prototype._startTimer = function () {
if (this._startTime != null) throw new Error(this + ': startTimer called twice')
this._startTime = Date.now()
}
Component.prototype._stopTimer = function () {
if (this._startTime == null) throw new Error(this + ': stopTimer called without startTimer')
this._milliseconds += Date.now() - this._startTime
this._startTime = null
}
Component.prototype._getTotalMilliseconds = function () {
var total = this._milliseconds
for (var i = 0; i < (this._childComponents || []).length; i++) {
total += this._childComponents[i]._getTotalMilliseconds()
}
return total
}
Component.prototype.formatTimings = function (indent) {
indent = indent || 0
var blanks = Array(indent + 1).join(' ')
var ownTimings = blanks + this.friendlyName() + ': ' + this._milliseconds + ' ms self'
if (this._childComponents && this._childComponents.length) {
ownTimings += ' (' + this._getTotalMilliseconds() + ' ms total)'
}
ownTimings += '\n'
var childComponents = (this._childComponents || []).sort(function (a, b) {
return b._getTotalMilliseconds() - a._getTotalMilliseconds()
})
var stop = false
var childTimings = childComponents.map(function (childComponent) {
if (stop) return ''
if (childComponent._getTotalMilliseconds() <= 1) {
stop = true
return Array(indent + 3).join(' ') + '...\n'
}
return childComponent.formatTimings(indent + 2)
})
return ownTimings + childTimings.join('')
}
|
JavaScript
| 0.000099 |
@@ -805,16 +805,41 @@
nds = 0%0A
+ this._startTime = null%0A
%7D%0A%0A// Ca
@@ -2785,16 +2785,154 @@
Timer()%0A
+ // Don't use .finally here, or releaseTimer will error when it's called at%0A // the wrong time, and the original error will be shadowed%0A
return
@@ -2956,23 +2956,20 @@
t(fn()).
-finally
+then
(release
|
7efd654feb911f4e4a262c61bd17ba4eda2e05ba
|
move no-lint into lint.js so it is properly versioned, https://github.com/phetsims/chipper/issues/726
|
js/grunt/lint.js
|
js/grunt/lint.js
|
// Copyright 2015, University of Colorado Boulder
/**
* Runs the lint rules on the specified files.
*
* @author Sam Reid (PhET Interactive Simulations)
*/
'use strict';
// modules
const eslint = require( 'eslint' );
const grunt = require( 'grunt' );
const md5 = require( 'md5' );
const path = require( 'path' );
const child_process = require( 'child_process' );
/**
* Lints the specified repositories.
* @public
*
* @param {Array.<string>} repos
* @param {boolean} cache
* @param {boolean} say - whether errors should be read out loud
* @returns {Object} - ESLint report object.
*/
module.exports = function( repos, cache, say = false ) {
const cli = new eslint.CLIEngine( {
cwd: path.dirname( process.cwd() ),
// Caching only checks changed files or when the list of rules is changed. Changing the implementation of a
// custom rule does not invalidate the cache. Caches are declared in .eslintcache files in the directory where
// grunt was run from.
cache: cache,
// Our custom rules live here
rulePaths: [ 'chipper/eslint/rules' ],
// Where to store the target-specific cache file
cacheFile: `chipper/eslint/cache/${md5( repos.join( ',' ) )}.eslintcache`,
// Files to skip for linting
ignorePattern: [
'**/.git',
'**/build',
'**/node_modules',
'**/snapshots',
'sherpa/**',
'**/js/parser/svgPath.js',
'**/templates/chipper-initialization.js',
'**/templates/chipper-strings.js',
'**/templates/sim-config.js',
'phet-io-website/root/assets/js/ua-parser-0.7.12.min.js',
'phet-io-website/root/assets/js/jquery-1.12.3.min.js',
'phet-io-website/root/assets/highlight.js-9.1.0/highlight.pack.js',
'phet-io-website/root/assets/highlight.js-9.1.0/highlight.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/npm.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.min.js',
'phet-io-website/root/assets/bootstrap-3.3.6-dist/js/bootstrap.js',
'phet-io-website/root/assets/js/phet-io-ga.js',
'installer-builder/temp/**'
]
} );
grunt.verbose.writeln( 'linting: ' + repos.join( ', ' ) );
// run the eslint step
const report = cli.executeOnFiles( repos );
// pretty print results to console if any
( report.warningCount || report.errorCount ) && grunt.log.write( cli.getFormatter()( report.results ) );
say && report.warningCount && child_process.execSync( 'say Lint warnings detected!' );
say && report.errorCount && child_process.execSync( 'say Lint errors detected!' );
report.warningCount && grunt.fail.warn( report.warningCount + ' Lint Warnings' );
report.errorCount && grunt.fail.fatal( report.errorCount + ' Lint Errors' );
return report;
};
|
JavaScript
| 0 |
@@ -212,24 +212,52 @@
'eslint' );%0A
+const fs = require( 'fs' );%0A
const grunt
@@ -391,16 +391,267 @@
ss' );%0A%0A
+// constants%0A// don't lint these repos%0Aconst NO_LINT_REPOS = %5B%0A 'babel',%0A 'eliot',%0A 'phet-android-app',%0A 'phet-info',%0A 'phet-io-wrapper-arithmetic',%0A 'phet-io-wrapper-hookes-law-energy',%0A 'phet-ios-app',%0A 'sherpa',%0A 'smithers',%0A 'tasks'%0A%5D;%0A%0A
/**%0A * L
@@ -928,16 +928,363 @@
se ) %7B%0A%0A
+ // filter out all unlintable repo. An unlintable repo is one that has no %60js%60 in it, so it will fail when trying to%0A // lint it. Also, if the user doesn't have some repos checked out, those should be skipped%0A const filteredRepos = repos.filter( repo =%3E %7B%0A return NO_LINT_REPOS.indexOf( repo ) %3C 0 && fs.existsSync( '../' + repo );%0A %7D );%0A%0A
const
@@ -1805,17 +1805,25 @@
/$%7Bmd5(
-r
+filteredR
epos.joi
@@ -2791,17 +2791,25 @@
ng: ' +
-r
+filteredR
epos.joi
@@ -2884,17 +2884,25 @@
nFiles(
-r
+filteredR
epos );%0A
|
b06adc0ba31a676baa497af668293e088021b5bc
|
add behavioral to client
|
lib/client.js
|
lib/client.js
|
var Hoek = require('hoek');
var Joi = require('joi');
var yarp = require('yarp');
var URL = require('url');
var defaultOptions = {
hostBase: '.vin.li',
protocol: 'https',
port: 443,
apiVersion: 'v1'
};
var groupPrefix = {
platform: 'platform',
auth: 'auth',
telemetry: 'telemetry',
event: 'events',
rule: 'rules',
trip: 'trips',
diagnostic: 'diagnostic',
safety: 'safety'
};
var Client = function(_options) {
Joi.assert(_options, Joi.object({
hostBase: Joi.string().regex(/^[-_\.\da-zA-Z]+$/),
protocol: Joi.string().allow([ 'http', 'https' ]),
port: Joi.number().integer().min(1),
apiVersion: Joi.string().allow([ 'v1' ]),
appId: Joi.string(),
secretKey: Joi.string(),
accessToken: Joi.string(),
serviceOrigins: Joi.object({
platform: Joi.string().uri().required(),
auth: Joi.string().uri().required(),
telemetry: Joi.string().uri().required(),
event: Joi.string().uri().required(),
rule: Joi.string().uri().required(),
trip: Joi.string().uri().required(),
diagnostic: Joi.string().uri().required(),
safety: Joi.string().uri().required()
}).optional()
}).required()
.and('appId', 'secretKey')
.xor('appId', 'accessToken')
.nand('hostBase', 'serviceOrigins')
.nand('protocol', 'serviceOrigins')
.nand('port', 'serviceOrigins'));
this.options = Hoek.applyToDefaults(defaultOptions, _options);
if (this.options.accessToken) {
this.authHeaders = {
authorization: 'Bearer ' + this.options.accessToken
};
} else {
this.authHeaders = {
authorization: 'Basic ' + (new Buffer(this.options.appId + ':' + this.options.secretKey, 'utf8')).toString('base64')
};
}
this.App = require('./app')(this);
this.User = require('./user')(this);
this.Auth = require('./auth')(this);
this.Device = require('./device')(this);
this.Vehicle = require('./vehicle')(this);
this.Trip = require('./trip')(this);
this.Code = require('./code')(this);
this.Event = require('./event')(this);
this.Subscription = require('./subscription')(this);
this.Rule = require('./rule')(this);
this.Collision = require('./collision')(this);
};
Client.prototype.originForGroup = function(group) {
if (this.options.serviceOrigins) {
return this.options.serviceOrigins[group];
}
return URL.format({
protocol: this.options.protocol,
hostname: groupPrefix[group] + this.options.hostBase,
port: this.options.port
});
};
Client.prototype.buildUrl = function(_group, _path, _query, _skipPrefix) {
return URL.resolve(
this.originForGroup(_group),
URL.format({
pathname: (_skipPrefix ? '' : ('/api/' + this.options.apiVersion)) + '/' + _path,
query: _query
})
);
};
Client.prototype.getRaw = function(url) {
return yarp({
url: url,
headers: this.authHeaders
});
};
Client.prototype.authGet = function(_path, _accessToken) {
return yarp({
url: this.buildUrl('auth', _path, { access_token: _accessToken }, true)
});
};
Client.prototype.get = function(_group, _path, _query) {
return this.getRaw(this.buildUrl(_group, _path, _query));
};
Client.prototype.post = function(_group, _path, _payload, _skipPrefix) {
return yarp({
url: this.buildUrl(_group, _path, {}, _skipPrefix),
method: 'POST',
json: _payload,
headers: this.authHeaders
});
};
Client.prototype.put = function(_group, _path, _payload) {
return yarp({
url: this.buildUrl(_group, _path),
method: 'PUT',
json: _payload,
headers: this.authHeaders
});
};
Client.prototype.delete = function(_group, _path) {
return yarp({
url: this.buildUrl(_group, _path),
method: 'DELETE',
headers: this.authHeaders
});
};
Client.prototype.getEntireStream = function(url, listName) {
var self = this;
return self.getRaw(url).then(function(data) {
if (data.meta.pagination.links.prior) {
return self.getEntireStream(data.meta.pagination.links.prior, listName).then(function(locs) {
return data[listName].concat(locs);
});
}
return data[listName];
});
};
Client.prototype.getEntireLocationStream = function(url) {
var self = this;
return self.getRaw(url).then(function(data) {
if (data.meta.pagination.links.prior) {
return self.getEntireLocationStream(data.meta.pagination.links.prior).then(function(locs) {
return data.locations.features.concat(locs);
});
}
return data.locations.features;
});
};
module.exports = Client;
|
JavaScript
| 0.000001 |
@@ -390,16 +390,44 @@
'safety'
+,%0A behavioral: 'behavioral'
%0A%7D;%0A%0Avar
@@ -1138,16 +1138,65 @@
safety:
+ Joi.string().uri().required(),%0A behavioral:
Joi.str
@@ -2261,16 +2261,68 @@
(this);%0A
+ this.ReportCard = require('./report_card')(this);%0A
%7D;%0A%0AClie
|
b66646bed1b7369291763c8ae64583da00a3ce65
|
Update attributeToBoolean.js
|
src/engine/src/attributeToBoolean.js
|
src/engine/src/attributeToBoolean.js
|
/**
*
* @description Convert attribute value to boolean value
* @param attribute
* @return {Boolean}
* @private
*/
export default function (attribute) {
let value = (attribute && attribute.value) || attribute;
return [true, 'true', 'on', '1', 1].indexOf(value) >= 0;
}
|
JavaScript
| 0.000001 |
@@ -245,16 +245,23 @@
', 'on',
+ 'yes',
'1', 1%5D
@@ -283,8 +283,9 @@
%3E= 0;%0A%7D
+%0A
|
42036b67506dab9b62891ede6729bca253f3a4b7
|
Update javascript.js
|
js/javascript.js
|
js/javascript.js
|
var i = 0;
while (i <= 20){
console.log("You have been Hacked!");
}
|
JavaScript
| 0.000001 |
@@ -27,19 +27,13 @@
)%7B%0A
-console.log
+alert
(%22Yo
|
74aeb628da70a4638e537e70d4f81d8a9bfc453f
|
Package fonts (glyphicon).
|
gulpfile.js
|
gulpfile.js
|
/* global __dirname */
(function (pkg, gulp, jshint, jscs, stylish, mocha, connect, less, requirejs, uglify, replace, header, yargs, rimraf, mkdirp, recursive) {
'use strict';
var environment = yargs.argv.env || 'development',
headerTemplate =
'/**\n' +
' * ${pkg.name}\n' +
' * ${pkg.description}\n' +
' * \n' +
' * @version ${pkg.version}\n' +
' * @link ${pkg.homepage}\n' +
' * @license ${pkg.license}\n' +
' */\n\n';
gulp.task(
'qa:lint',
function () {
return gulp
.src([
'*.js',
'public/app/**/*.js',
'test/**/*.js'
])
.pipe(jshint())
.pipe(jscs())
.pipe(stylish.combineWithHintResults())
.pipe(jshint.reporter('jshint-stylish'));
}
);
gulp.task(
'qa:test',
[
'qa:lint'
],
function () {
return gulp
.src('test/runner.html')
.pipe(mocha());
}
);
gulp.task(
'qa',
[
'qa:lint',
'qa:test'
]
);
gulp.task(
'build:clean',
function (callback) {
rimraf('public/css', callback);
}
);
gulp.task(
'build:less',
[
'build:clean'
],
function () {
return gulp
.src('public/less/main.less')
.pipe(less({
paths: [ 'public/less' ]
}))
.pipe(gulp.dest('public/css'));
}
);
gulp.task(
'build',
[
'build:clean',
'build:less'
]
);
gulp.task(
'package:clean',
function (callback) {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
rimraf('dist/' + environment, function () {
mkdirp('dist/' + environment, callback);
});
}
);
gulp.task(
'package:less',
[
'package:clean'
],
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/less/main.less')
.pipe(less({
paths: [ 'public/less' ],
optimize: true
}))
.pipe(gulp.dest('dist/' + environment));
}
);
gulp.task(
'package:javascript',
[
'package:clean'
],
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
// Dynamically generate the `include` list, because most of the modules are dynamically `require`d.
recursive('public/app', function (err, files) {
return gulp
.src('public/app/main.js')
.pipe(requirejs({
mainConfigFile: 'public/app/main.js',
name: '../lib/requirejs/require',
optimize: 'none',
out: 'application.js',
include: files.map(function (file) {
// Strip common path prefix; return .js files without extension, and others via text plugin.
file = file.replace(/^public\/app\//, '');
return file.match(/\.js$/) ? file.replace(/\.js$/, '') : 'text!' + file;
})
}))
.pipe(replace(/var environment = 'development';/g, 'var environment = "' + environment + '";'))
.pipe(uglify())
.pipe(header(headerTemplate, { pkg: pkg }))
.pipe(gulp.dest('dist/' + environment));
});
}
);
gulp.task(
'package:html',
[
'package:clean'
],
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/index.html')
.pipe(replace(/src="\/lib\/requirejs\/require\.js"/g, 'src="/application.js"'))
.pipe(replace(/href="\/css\/main\.css"/g, 'href="/main.css"'))
.pipe(gulp.dest('dist/' + environment));
}
);
gulp.task(
'package:images',
[
'package:clean'
],
function () {
if (environment === 'development') {
throw new Error('Cannot use "package" tasks in development environment');
}
return gulp
.src('public/images/**/*')
.pipe(gulp.dest('dist/' + environment + '/images'));
}
);
gulp.task(
'package',
[
'package:clean',
'package:less',
'package:javascript',
'package:html',
'package:images'
]
);
gulp.task(
'server',
function () {
connect.server({
port: 8888,
root: 'public',
fallback: 'public/index.html'
});
}
);
gulp.task(
'dist-server',
function () {
connect.server({
port: 8889,
root: 'dist/' + environment,
fallback: 'dist/' + environment + '/index.html'
});
}
);
gulp.task(
'watch:qa',
function () {
return gulp
.watch(
[
'*.js',
'public/app/**',
'test/**/*.js'
],
[
'qa'
]
);
}
);
gulp.task(
'watch:less',
function () {
return gulp
.watch(
[
'public/less/**/*.less',
'public/app/ui/**/*.less'
],
[
'build:less'
]
);
}
);
gulp.task(
'watch',
[
'watch:qa',
'watch:less'
]
);
gulp.task(
'default',
[
'qa',
'build',
'watch'
]
);
}(
require('./package.json'),
require('gulp'),
require('gulp-jshint'),
require('gulp-jscs'),
require('gulp-jscs-stylish'),
require('gulp-mocha-phantomjs'),
require('gulp-connect'),
require('gulp-less'),
require('gulp-requirejs-optimize'),
require('gulp-uglify'),
require('gulp-replace'),
require('gulp-header'),
require('yargs'),
require('rimraf'),
require('mkdirp'),
require('recursive-readdir')
));
|
JavaScript
| 0 |
@@ -5221,32 +5221,323 @@
%7D%0A );%0A%0A
+ gulp.task(%0A 'package:fonts',%0A %5B%0A 'package:clean'%0A %5D,%0A function () %7B%0A return gulp%0A .src('public/lib/bootstrap/fonts/**/*')%0A .pipe(gulp.dest('dist/' + environment + '/lib/bootstrap/fonts'));%0A %7D%0A );%0A%0A
gulp.task(%0A
@@ -5711,16 +5711,45 @@
:images'
+,%0A 'package:fonts'
%0A
|
6c5f6cc021222d70efbb1eb370b0d940d6167195
|
Make plans section less boring
|
applications/vpn-settings/src/app/components/sections/plans/PlansSection.js
|
applications/vpn-settings/src/app/components/sections/plans/PlansSection.js
|
import React, { useState, useEffect } from 'react';
import {
Button,
SubTitle,
useApi,
usePlans,
Loader,
useSubscription,
DowngradeModal,
useModals,
SubscriptionModal,
useLoading,
useEventManager,
useNotifications,
useUser,
useToggle
} from 'react-components';
import { c } from 'ttag';
import { DEFAULT_CURRENCY, DEFAULT_CYCLE } from 'proton-shared/lib/constants';
import { checkSubscription, deleteSubscription } from 'proton-shared/lib/api/payments';
import { mergePlansMap } from 'react-components/containers/payments/subscription/helpers';
import PlansTable from './PlansTable';
const PlansSection = () => {
const api = useApi();
const [{ isFree, isPaid }] = useUser();
const { call } = useEventManager();
const { createNotification } = useNotifications();
const { createModal } = useModals();
const [loading, withLoading] = useLoading();
const [currency, updateCurrency] = useState(DEFAULT_CURRENCY);
const [cycle, updateCycle] = useState(DEFAULT_CYCLE);
const { state: showPlans, toggle: togglePlans } = useToggle(isFree);
const [plans, loadingPlans] = usePlans();
const [subscription, loadingSubscription] = useSubscription();
const { CouponCode } = subscription || {};
const unsubscribe = async () => {
if (isFree) {
return createNotification({ type: 'error', text: c('Info').t`You already have a free account` });
}
await new Promise((resolve, reject) => {
createModal(<DowngradeModal onConfirm={resolve} onClose={reject} />);
});
await api(deleteSubscription());
await call();
createNotification({ text: c('Success').t`You have successfully unsubscribed` });
};
const handleSelectPlan = async (planName) => {
if (!planName) {
return unsubscribe();
}
const plansMap = mergePlansMap({ [planName]: 1 }, subscription);
const couponCode = CouponCode ? CouponCode : undefined; // From current subscription; CouponCode can be null
const PlanIDs = Object.entries(plansMap).reduce((acc, [planName, quantity]) => {
if (quantity) {
const { ID } = plans.find((plan) => plan.Name === planName);
acc[ID] = quantity;
}
return acc;
}, Object.create(null));
const { Coupon } = await api(
checkSubscription({
PlanIDs,
CouponCode: couponCode,
Currency: currency,
Cycle: cycle
})
);
const coupon = Coupon ? Coupon.Code : undefined; // Coupon can equals null
createModal(
<SubscriptionModal
subscription={subscription}
cycle={cycle}
currency={currency}
coupon={coupon}
plansMap={plansMap}
/>
);
};
useEffect(() => {
if (isFree) {
const [{ Currency } = {}] = plans || [];
updateCurrency(Currency);
}
}, [plans]);
useEffect(() => {
if (isPaid) {
const { Currency, Cycle } = subscription || {};
updateCurrency(Currency);
updateCycle(Cycle);
}
}, [subscription]);
if (loadingPlans || loadingSubscription) {
return (
<>
<SubTitle>{c('Title').t`Plans`}</SubTitle>
<Loader />
</>
);
}
return (
<>
<SubTitle>{c('Title').t`Plans`}</SubTitle>
<Button className="mb2" onClick={togglePlans}>
{showPlans ? c('Action').t`Hide plans` : c('Action').t`Show plans`}
</Button>
{showPlans ? (
<div className="scroll-horizontal-if-needed pt3">
<PlansTable
onSelect={(planName) => () => withLoading(handleSelectPlan(planName))}
loading={loading}
currency={currency}
cycle={cycle}
updateCurrency={updateCurrency}
updateCycle={updateCycle}
plans={plans}
subscription={subscription}
/>
</div>
) : null}
</>
);
};
export default PlansSection;
|
JavaScript
| 0.00012 |
@@ -54,16 +54,27 @@
mport %7B%0A
+ Alert,%0A
Butt
@@ -73,24 +73,24 @@
Button,%0A
-
SubTitle
@@ -510,24 +510,109 @@
/payments';%0A
+import %7B isBundleEligible, getPlans %7D from 'proton-shared/lib/helpers/subscription';%0A
import %7B mer
@@ -1322,24 +1322,221 @@
cription();%0A
+ const bundleEligible = isBundleEligible(subscription);%0A const names = getPlans(subscription)%0A .map((%7B Title %7D) =%3E Title)%0A .join(c('Separator, spacing is important').t%60 and %60);%0A
const %7B
@@ -1545,16 +1545,28 @@
uponCode
+, Plans = %5B%5D
%7D = sub
@@ -3897,32 +3897,391 @@
ns%60%7D%3C/SubTitle%3E%0A
+ %3CAlert%3E%0A %7BbundleEligible ? (%0A %3Cdiv%3E%7Bc('Info')%0A .t%60Get 20%25 bundle discount when you purchase ProtonMail and ProtonVPN together.%60%7D%3C/div%3E%0A ) : null%7D%0A %7BPlans.length ? %3Cdiv%3E%7Bc('Info').t%60You are currently subscribed to $%7Bnames%7D.%60%7D%3C/div%3E : null%7D%0A %3C/Alert%3E%0A
%3CBut
|
13e007bea8c51432fa4f7afc3a152e5a144d8d4b
|
Fix latched classes not respecting class: ''
|
src/foam/apploader/ClassLoader.js
|
src/foam/apploader/ClassLoader.js
|
/**
* @license
* Copyright 2018 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
/*
TODO:
- Remove foam.classloader classes
- Remove arequire, or change it to use classloader.load
- Make GENMODEL work when running without a classloader
- Fix WebSocketBox port autodetection to work when running with tomcat and also without
*/
foam.CLASS({
package: 'foam.apploader',
name: 'ClassLoader',
/* todo: [
`Don't register classes globally, register in a subcontext so we can
have multiple classloaders running alongside eachother`
],*/
requires: [
'foam.classloader.OrDAO'
],
properties: [
{
class: 'Map',
name: 'pending'
},
{
class: 'Map',
name: 'latched'
},
{
class: 'foam.dao.DAOProperty',
name: 'modelDAO'
}
],
methods: [
{
name: 'addClassPath',
code: function(modelDAO) {
if ( this.modelDAO ) {
modelDAO = this.OrDAO.create({
primary: this.modelDAO,
delegate: modelDAO
});
}
this.modelDAO = modelDAO;
}
},
{
name: 'load',
returns: 'Promise',
args: [ { class: 'String', name: 'id' } ],
code: function(id) {
return this.load_(id, []);
}
},
{
name: 'maybeLoad',
returns: 'Promise',
documentation: "Like load, but don't throw if not found.",
args: [ { name: 'id', of: 'String' } ],
code: function(id) {
return this.load(id).catch(function() { return null; });
}
},
{
name: 'maybeLoad_',
returns: 'Promise',
args: [ { name: 'id', of: 'String' },
{ name: 'path', of: 'Array' } ],
code: function(id, path) {
return this.load_(id, path).catch(function() { return null; });
}
},
{
name: 'latch',
returns: 'Promise',
args: [ { name: 'json' } ],
code: function(json) {
var id = json.package ?
json.package + '.' + json.name :
json.name;
this.latched[id] = json;
}
},
{
name: 'load_',
returns: 'Promise',
args: [ { class: 'String', name: 'id' },
{ class: 'StringArray', name: 'path' } ],
code: function(id, path) {
var self = this;
if ( foam.String.isInstance(id) ) {
// Prevent infinite loops, if we're loading this class as a
// dependency to something that this class depends upon then
// we can just resolve right away.
for ( var i = 0 ; i < path.length ; i++ ) {
if ( path[i].id === id ) return Promise.resolve();
}
if ( this.pending[id] ) return this.pending[id];
// Latched models come from when someone defines a class
// with foam.CLASS during regular execution (like a script
// tag). We hook into those so that they can still use the
// classloader to ensure any dependencies of that model are
// loaded before they use it.
if ( this.latched[id] ) {
var json = this.latched[id];
delete this.latched[id];
return this.pending[id] = Promise.all(foam.json.references(this.__context__, json)).then(function() {
return self.modelDeps_(foam.core.Model.create(json), path);
}).then(function() {
// Latched models will already be registered in the
// context via foam.CLASS as defined in EndBoot.js
return foam.lookup(id);
});
}
if ( foam.lookup(id, true) ) return Promise.resolve(foam.lookup(id));
return this.pending[id] = this.modelDAO.find(id).then(function(m) {
if ( ! m ) return Promise.reject(new Error('Class Not Found: ' + id));
return this.buildClass_(m, path);
}.bind(this), function() {
throw new Error("Failed to load class " + id);
});
}
if ( foam.core.Model.isInstance(id) ) {
return this.pending[id] = this.buildClass_(id, path);
}
throw new Error("Invalid parameter to ClassLoader.load_");
}
},
{
name: 'modelDeps_',
args: [ { name: 'model', of: 'foam.core.Model' },
{ name: 'path' } ],
code: function(model, path) {
var self = this;
// TODO: This can probably be a method on Model
var deps = model.requires ?
model.requires.map(function(r) { return self.maybeLoad_(r.path, path); }) :
[];
deps = deps.concat(model.implements ?
model.implements.map((function(i) { return self.maybeLoad_(i.path, path); })) :
[]);
if ( model.extends ) deps.push(self.maybeLoad_(model.extends, path));
return Promise.all(deps);
}
},
{
name: 'buildClass_',
args: [ { name: 'model', of: 'foam.core.Model' },
{ name: 'path', of: 'Array' } ],
code: function(model, path) {
var self = this;
path = path.concat(model);
var deps = this.modelDeps_(model, path);
return deps.then(function() {
model.validate();
cls = model.buildClass();
cls.validate();
if ( ! model.refines ) {
// Register class in global context.
foam.register(cls);
// Register the class in the global package path.
foam.package.registerClass(cls);
} else if ( model.name ) {
// Register refinement id in global context.
foam.register(cls, ( model.package || 'foam.core' ) + '.' + model.name);
}
// TODO(markdittmer): Identify and name anonymous refinements with:
// else {
// console.warn('Refinement without unique id', cls);
// debugger;
// }
return cls;
});
}
}
]
});
|
JavaScript
| 0.000005 |
@@ -3284,32 +3284,112 @@
en(function() %7B%0A
+ var cls = json.class ? foam.lookup(json.class) : foam.core.Model;%0A
re
@@ -3409,31 +3409,19 @@
elDeps_(
-foam.core.Model
+cls
.create(
|
7ad8f28ef22dbcafcd73a53e3f705f932e69bd5d
|
Improve formatting of DAOControllerView.initE.
|
src/foam/comics/DAOControllerView.js
|
src/foam/comics/DAOControllerView.js
|
/**
* @license
* Copyright 2016 Google Inc. All Rights Reserved.
* Copyright 2017 The FOAM Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.CLASS({
package: 'foam.comics',
name: 'DAOControllerView',
extends: 'foam.u2.View',
requires: [
'foam.comics.DAOController'
],
imports: [
'stack',
'data? as importedData'
],
exports: [
'data.selection as selection',
'data.data as dao'
],
properties: [
{
class: 'FObjectProperty',
of: 'foam.comics.DAOController',
name: 'data',
expression: function(importedData) { return importedData; },
},
{
name: 'cls',
expression: function(data) { return data.cls_; }
}
],
reactions: [
[ 'data', 'action,create', 'onCreate' ],
[ 'data', 'edit', 'onEdit' ],
[ 'data', 'action,findRelatedObject', 'onFindRelated' ],
[ 'data', 'finished', 'onFinished']
],
methods: [
function initE() {
this.
start('table').
start('tr').
start('td').add(this.cls.PREDICATE).end().
start('td').style({ 'vertical-align': 'top', 'width': '100%' }).
add(this.cls.FILTERED_DAO).end().
end().
start('tr').
show(this.mode$.map(function(m) { return m == foam.u2.DisplayMode.RW; })).
start('td').end().start('td').
add(this.cls.getAxiomsByClass(foam.core.Action)).
end();
}
],
listeners: [
function onCreate() {
this.stack.push({
class: 'foam.comics.DAOCreateControllerView'
}, this);
},
function onEdit(s, edit, id) {
this.stack.push({
class: 'foam.comics.DAOUpdateControllerView',
key: id
}, this);
},
function onFindRelated() {
var data = this.DAOController.create({
data: this.data.relationship.targetDAO,
mode: this.DAOController.MODE_SELECT,
relationship: this.data.relationship
});
this.stack.push({
class: 'foam.comics.DAOControllerView',
data: data
}, this);
},
function onFinished() {
this.stack.back();
}
],
});
|
JavaScript
| 0.000001 |
@@ -1517,32 +1517,34 @@
able').%0A
+
start('tr').%0A
@@ -1532,32 +1532,34 @@
start('tr').%0A
+
start(
@@ -1587,32 +1587,34 @@
EDICATE).end().%0A
+
start(
@@ -1676,32 +1676,34 @@
%7D).%0A
+
add(this.cls.FIL
@@ -1713,16 +1713,29 @@
ED_DAO).
+%0A
end().%0A
@@ -1733,39 +1733,43 @@
end().%0A
+
end().%0A
+
start('t
@@ -1765,32 +1765,34 @@
start('tr').%0A
+
show(t
@@ -1860,32 +1860,36 @@
W; %7D)).%0A
+
start('td').end(
@@ -1888,35 +1888,8 @@
d').
-end().start('td').%0A
add(
@@ -1933,16 +1933,39 @@
ction)).
+end().%0A end().
%0A
|
52723edd25c3eea53f365f4ede59a2ef1cdf1d39
|
Remove high relevance from javadoc.
|
src/languages/java.js
|
src/languages/java.js
|
/*
Language: Java
Author: Vsevolod Solovyov <[email protected]>
*/
function(hljs) {
var KEYWORDS =
'false synchronized int abstract float private char boolean static null if const ' +
'for true while long throw strictfp finally protected import native final return void ' +
'enum else break transient new catch instanceof byte super volatile case assert short ' +
'package default double public try this switch continue throws';
return {
aliases: ['jsp'],
keywords: KEYWORDS,
illegal: /<\//,
contains: [
{
className: 'javadoc',
begin: '/\\*\\*', end: '\\*/',
contains: [{
className: 'javadoctag', begin: '(^|\\s)@[A-Za-z]+'
}],
relevance: 10
},
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE,
hljs.QUOTE_STRING_MODE,
{
beginKeywords: 'protected public private', end: /[{;=]/,
keywords: KEYWORDS,
contains: [
{
className: 'class',
beginKeywords: 'class interface', endsWithParent: true, excludeEnd: true,
illegal: /[:"\[\]]/,
contains: [
{
beginKeywords: 'extends implements',
relevance: 10
},
hljs.UNDERSCORE_TITLE_MODE
]
},
{
begin: hljs.UNDERSCORE_IDENT_RE + '\\s*\\(', returnBegin: true,
contains: [
hljs.UNDERSCORE_TITLE_MODE
]
}
]
},
hljs.C_NUMBER_MODE,
{
className: 'annotation', begin: '@[A-Za-z]+'
}
]
};
}
|
JavaScript
| 0 |
@@ -621,16 +621,38 @@
'%5C%5C*/',%0A
+ relevance: 0,%0A
@@ -740,31 +740,8 @@
%7D%5D
-,%0A relevance: 10
%0A
|
d77c2293e6dd8d3a1939d7b877c0a74c6d6569d3
|
Change plugins directory.
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var _ = require('lodash');
var path = require('path');
var mkdirp = require('mkdirp');
var Rsync = require('rsync');
var Promise = require('bluebird');
var eslint = require('gulp-eslint');
var rimraf = require('rimraf');
var zip = require('gulp-zip');
var fs = require('fs');
var spawn = require('child_process').spawn;
var minimist = require('minimist');
var pkg = require('./package.json');
var packageName = pkg.name;
// in their own sub-directory to not interfere with Gradle
var buildDir = path.resolve(__dirname, 'build/gulp');
var targetDir = path.resolve(__dirname, 'target/gulp');
var buildTarget = path.resolve(buildDir, packageName);
var include = [
'*.json',
'LICENSE',
'README.md',
'index.js',
'init.js',
'server',
'public'
];
var knownOptions = {
string: 'kibanahomepath',
default: { kibanahomepath: '../kibi-internal' }
};
var options = minimist(process.argv.slice(2), knownOptions);
var kibanaPluginDir = path.resolve(__dirname, options.kibanahomepath + '/installedPlugins/' + packageName);
function syncPluginTo(dest, done) {
mkdirp(dest, function (err) {
if (err) return done(err);
Promise.all(include.map(function (name) {
var source = path.resolve(__dirname, name);
return new Promise(function (resolve, reject) {
var rsync = new Rsync();
rsync
.source(source)
.destination(dest)
.flags('uav')
.recursive(true)
.set('delete')
.output(function (data) {
process.stdout.write(data.toString('utf8'));
});
rsync.execute(function (err) {
if (err) {
console.log(err);
return reject(err);
}
resolve();
});
});
}))
.then(function () {
return new Promise(function (resolve, reject) {
mkdirp(path.join(buildTarget, 'node_modules'), function (err) {
if (err) return reject(err);
resolve();
});
});
})
.then(function () {
spawn('npm', ['install', '--production'], {
cwd: dest,
stdio: 'inherit'
})
.on('close', done);
})
.catch(done);
});
}
gulp.task('sync', function (done) {
syncPluginTo(kibanaPluginDir, done);
});
gulp.task('lint', function (done) {
return gulp.src([
'index.js',
'init.js',
'public/**/*.js',
'server/**/*.js',
'!**/webpackShims/**'
]).pipe(eslint())
.pipe(eslint.formatEach())
.pipe(eslint.failOnError());
});
gulp.task('clean', function (done) {
Promise.each([buildDir, targetDir], function (dir) {
return new Promise(function (resolve, reject) {
rimraf(dir, function (err) {
if (err) return reject(err);
resolve();
});
});
}).nodeify(done);
});
gulp.task('build', ['clean'], function (done) {
syncPluginTo(buildTarget, done);
});
gulp.task('package', ['build'], function (done) {
return gulp.src([
path.join(buildDir, '**', '*')
])
.pipe(zip(packageName + '.zip'))
.pipe(gulp.dest(targetDir));
});
gulp.task('dev', ['sync'], function (done) {
gulp.watch([
'index.js',
'init.js',
'*.json',
'public/**/*',
'server/**/*'
], ['sync', 'lint']);
});
gulp.task('test', ['sync'], function(done) {
spawn('grunt', ['test:server', '--grep=Sentinl'], {
cwd: options.kibanahomepath,
stdio: 'inherit'
}).on('close', done);
});
gulp.task('testdev', ['sync'], function(done) {
spawn('grunt', ['test:dev', '--browser=Chrome'], {
cwd: options.kibanahomepath,
stdio: 'inherit'
}).on('close', done);
});
gulp.task('coverage', ['sync'], function(done) {
spawn('grunt', ['test:coverage', '--grep=Sentinl'], {
cwd: options.kibanahomepath,
stdio: 'inherit'
}).on('close', done);
});
|
JavaScript
| 0 |
@@ -1019,18 +1019,9 @@
+ '/
-installedP
+p
lugi
|
250a6de348afd5b39150c42ef2c6160692b9b0e8
|
Simplify code
|
src/foam/comics/DAOControllerView.js
|
src/foam/comics/DAOControllerView.js
|
/**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.comics',
name: 'DAOControllerView',
extends: 'foam.u2.View',
requires: [
'foam.comics.DAOController',
'foam.comics.DAOUpdateControllerView',
'foam.u2.view.ScrollTableView'
],
imports: [
'stack',
'summaryView? as importedSummaryView',
'data? as importedData',
'window'
],
exports: [
'data.selection as selection',
'data.data as dao',
'dblclick'
],
// TODO: wrong class name, fix when ActionView fixed.
css: `
.middle-row {
display: flex;
}
.middle-row > *:not(:empty) {
margin-left: 10px;
}
.middle-row > *:last-child {
margin-right: 10px;
}
.middle-row .actions {
display: inline-block;
margin-bottom: 10px;
}
.middle-row .net-nanopay-ui-ActionView {
background: #59aadd;
color: white;
margin-right: 10px;
}
`,
properties: [
{
class: 'FObjectProperty',
of: 'foam.comics.DAOController',
name: 'data',
expression: function(importedData) { return importedData; }
},
{
name: 'cls',
expression: function(data) { return data.cls_; }
},
{
name: 'summaryView',
factory: function() {
return this.importedSummaryView$ ?
this.importedSummaryView :
{ class: 'foam.u2.view.ScrollTableView' };
}
},
{
class: 'String',
name: 'title',
expression: function(data$data$of) {
return 'Browse ' + data$data$of.name;
}
}
],
reactions: [
[ 'data', 'action.create', 'onCreate' ],
[ 'data', 'edit', 'onEdit' ],
[ 'data', 'action.findRelatedObject', 'onFindRelated' ],
[ 'data', 'finished', 'onFinished' ]
],
methods: [
function initE() {
var self = this;
this.
addClass(this.myClass()).
tag(this.data.topBorder$).
start().
addClass('middle-row').
tag(this.data.leftBorder).
start().
hide(self.data.searchHidden$).
enableClass('hide', self.data.filtersEnabled$, true).
add(self.cls.PREDICATE).
end().
start().
style({ 'overflow-x': 'auto' }).
start().
addClass('actions').
show(self.mode$.map((m) => m === foam.u2.DisplayMode.RW)).
start().add(self.cls.getAxiomsByClass(foam.core.Action)).end().
end().
start().
style({ 'overflow-x': 'auto' }).
tag(this.summaryView, { data$: this.data.filteredDAO$ }).
end().
end().
tag(this.data.rightBorder$).
end().
tag(this.data.bottomBorder$);
},
function dblclick(obj) {
this.onEdit(null, null, obj.id);
}
],
listeners: [
function onCreate() {
this.stack.push({
class: 'foam.comics.DAOCreateControllerView'
}, this);
},
function onEdit(s, edit, id) {
this.stack.push({
class: 'foam.comics.DAOUpdateControllerView',
key: id
}, this);
},
function onFindRelated() {
var data = this.DAOController.create({
data: this.data.relationship.targetDAO,
addEnabled: true,
relationship: this.data.relationship
});
this.stack.push({
class: 'foam.comics.DAOControllerView',
data: data
}, this);
},
function onFinished() {
this.stack.back();
}
]
});
|
JavaScript
| 0.041259 |
@@ -2171,28 +2171,13 @@
-enableClass('hide',
+show(
self
@@ -2201,14 +2201,8 @@
led$
-, true
).%0A
|
9d61e0793465cd7d9d91a2498847cc9823bea643
|
fix datenschutz link color
|
src/layouts/footer.js
|
src/layouts/footer.js
|
import React, { Component } from "react";
import styled from "styled-components";
import Link from "gatsby-link";
import SoftBricksLogo from "../components/softbricks-logo";
import ResponsiveContainer from "../components/responsive-container";
import Nav from "../components/nav";
import Text from "../components/text";
import Center from "../components/center";
import Inset from "../components/inset";
import Stack from "../components/stack";
import Toolbar from "../components/toolbar";
import colors from "../constants/colors";
const FooterContainer = styled.footer`
background-color: ${colors.black};
padding: 32px 0;
`;
const Copyright = styled(Text.Detail)`
padding: 32px 0 0;
color: ${colors.white5};
`;
const DatenschutzLink = styled(Link)`
text-decoration: none;
:visited {
color: ${colors.white3};
}
`
export default class Footer extends Component {
render() {
return (
<FooterContainer>
<ResponsiveContainer>
<Toolbar>
<SoftBricksLogo />
<div className="footer-links">
<Nav />
</div>
</Toolbar>
<Center>
<Stack alignItems="center" scale="xl">
<Copyright>© 2017 SoftBricks. All Rights Reserved | <DatenschutzLink to="/datenschutz">Datenschutzerklärung</DatenschutzLink></Copyright>
<a
href="https://www.contentful.com/"
rel="nofollow"
target="_blank"
>
<img
src="https://images.contentful.com/fo9twyrwpveg/7Htleo27dKYua8gio8UEUy/0797152a2d2f8e41db49ecbf1ccffdaa/PoweredByContentful_DarkBackground_MonochromeLogo.svg"
style={{ maxWidth: 100, width: '100%' }}
alt="Powered by Contentful"
/>
</a>
</Stack>
</Center>
</ResponsiveContainer>
</FooterContainer>
);
}
}
|
JavaScript
| 0 |
@@ -777,16 +777,43 @@
: none;%0A
+ color: $%7Bcolors.white5%7D;%0A
:visit
|
adf1d0da7a46db3a7f7725f1c9fb94fd6c4c0e30
|
Fix logic mistake
|
src/foam/comics/DAOControllerView.js
|
src/foam/comics/DAOControllerView.js
|
/**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
foam.CLASS({
package: 'foam.comics',
name: 'DAOControllerView',
extends: 'foam.u2.View',
requires: [
'foam.comics.SearchMode',
'foam.comics.DAOController',
'foam.comics.DAOUpdateControllerView',
'foam.u2.view.ScrollTableView',
'foam.u2.dialog.Popup'
],
imports: [
'data? as importedData',
'stack',
'summaryView? as importedSummaryView',
'updateView? as importedUpdateView',
'window'
],
exports: [
'as controllerView',
'data.selection as selection',
'data.data as dao',
'data.searchColumns as searchColumns',
'dblclick'
],
css: `
^ {
width: fit-content;
max-width: 100vw;
margin: auto;
}
^top-row {
display: flex;
justify-content: space-between;
align-items: flex-end;
margin-bottom: 10px;
}
^title-container > * {
display: inline-block;
margin: 0.67rem 0;
}
^title-container > * + * {
margin-left: 1rem;
}
^container {
display: flex;
}
^container > * + * {
margin-left: 10px;
}
^ .actions {
display: inline-block;
}
^ .actions .net-nanopay-ui-ActionView {
margin: 0 10px 10px 0;
}
^ .net-nanopay-ui-ActionView {
background: #59aadd;
color: white;
}
`,
properties: [
{
class: 'FObjectProperty',
of: 'foam.comics.DAOController',
name: 'data',
expression: function(importedData) {
return importedData;
}
},
{
name: 'cls',
expression: function(data) {
return data.cls_;
}
},
{
name: 'summaryView',
factory: function() {
var defaultView = { class: 'foam.u2.view.ScrollTableView' };
if (
Array.isArray(this.data.contextMenuActions) &&
this.data.contextMenuActions.length > 0
) {
defaultView.contextMenuActions = this.data.contextMenuActions;
}
return this.importedSummaryView ?
this.importedSummaryView :
defaultView;
}
},
{
name: 'updateView',
expression: function() {
return this.importedUpdateView ?
this.importedUpdateView :
{ class: 'foam.comics.DAOUpdateControllerView' };
}
}
],
reactions: [
['data', 'action.create', 'onCreate'],
['data', 'edit', 'onEdit'],
['data', 'action.findRelatedObject', 'onFindRelated'],
['data', 'finished', 'onFinished'],
['data', 'export', 'onExport']
],
methods: [
function initE() {
var self = this;
this.data.border.add(
this.E()
.addClass(this.myClass())
.start()
.addClass(this.myClass('top-row'))
.start()
.addClass(this.myClass('title-container'))
.start('h1')
.add(this.data.title$)
.end()
.add(this.data.subtitle$)
.end()
.callIf(this.data.primaryAction, function() {
this.startContext({ data: self })
.start()
.add(self.data.primaryAction)
.end()
.endContext();
})
.callIf(! this.data.primaryAction, function() {
this.start().add(self.cls.CREATE).end();
})
.end()
.start()
.addClass(this.myClass('container'))
.callIf(this.data.searchMode === this.SearchMode.FULL, function() {
this.start()
.hide(self.data.searchHidden$)
.add(self.cls.PREDICATE)
.end();
})
.start()
.style({ 'overflow-x': 'auto' })
.start()
.addClass('actions')
.show(self.mode$.map((m) => m === foam.u2.DisplayMode.RW))
.start()
.add(self.cls.getAxiomsByClass(foam.core.Action).filter((action) => {
var rtn = true;
if ( self.primaryAction ) {
rtn = rtn && action.name !== 'create';
}
if ( self.data.searchMode !== self.SearchMode.FULL ) {
rtn = rtn && action.name !== 'toggleFilters';
}
return rtn;
}))
.end()
.end()
.callIf(this.data.searchMode === this.SearchMode.SIMPLE, function() {
this.start().add(self.cls.PREDICATE).end();
})
.start()
.style({ 'overflow-x': 'auto' })
.tag(this.summaryView, { data$: this.data.filteredDAO$ })
.end()
.end()
.end());
this.add(this.data.border);
},
function dblclick(obj) {
this.onEdit(null, null, obj.id);
}
],
listeners: [
function onCreate() {
this.stack.push({
class: 'foam.comics.DAOCreateControllerView'
}, this);
},
function onEdit(s, edit, id) {
this.stack.push({
class: this.updateView.class,
key: id
}, this);
},
function onFindRelated() {
var data = this.DAOController.create({
data: this.data.relationship.targetDAO,
addEnabled: true,
relationship: this.data.relationship
});
this.stack.push({
class: 'foam.comics.DAOControllerView',
data: data
}, this);
},
function onFinished() {
this.stack.back();
},
function onExport(dao) {
this.add(this.Popup.create().tag({
class: 'foam.u2.ExportModal',
exportData: dao.src.filteredDAO
}));
}
]
});
|
JavaScript
| 0.99987 |
@@ -4145,24 +4145,26 @@
if (
+ !
self.primar
|
e25519068def4172d2dd37c537f8d2e88d9c3430
|
has midnight, black stars
|
CareWheels/www/js/individualStatus.js
|
CareWheels/www/js/individualStatus.js
|
/**
* CareWheels - Individual Status Controller
*
*/
angular.module('careWheels')
.controller('individualStatusController', function($scope){
$scope.getPings = function(time, type) {
switch(time) {
case 'midnight':
if (type === 'meals'){
//This is where you put the function call to get the pings for this time.
return "";
}
else if (type === 'meds'){
//This is where you put the function call to get the pings for this time.
return "* * * * * *";
}
//code block
//break;
case 'one':
//Do the same here
break;
default:
return 'error';
}
//if ( === 3){
// return "* * *";
//}
//else {
// return "boo";
//}
};
$scope.trevor = {
name: 'Trevor',
midnight: {
presence: {
status: 'yellow'
},
meals: {
status: 'yellow',
pings: ''
},
meds: {
status: 'yellow',
//pings = $scope.getPings(3)
pings: ''
}
},
one: {
presence: {
status: 'blue'
},
meals: {
status: 'yellow',
pings: ''
},
meds: {
status: 'blue',
pings: ''
}
},
two: {
presence: {
status: 'blue'
},
meals: {
status: 'yellow',
pings: ''
},
meds: {
status: 'blue',
pings: ''
}
},
three: {
presence: {
status: 'blue'
},
meals: {
status: 'blue',
pings: '* *'
},
meds: {
status: 'blue',
pings: ''
}
},
four: {
presence: {
status: 'blue'
},
meals: {
status: 'blue',
pings: '* * *'
},
meds: {
status: 'blue',
pings: ''
}
},
five: {
presence: {
status: 'blue'
},
meals: {
status: 'blue',
pings: ''
},
meds: {
status: 'red',
pings: ''
}
},
six: {
presence: {
status: 'grey'
},
meals: {
status: 'blue',
pings: ''
},
meds: {
status: 'red',
pings: ''
}
},
seven: {
presence: {
status: 'blue'
},
meals: {
status: 'blue',
pings: '*'
},
meds: {
status: 'blue',
pings: '*'
}
},
eight: {
presence: {
status: ''
},
meals: {
status: '',
pings: ''
},
meds: {
status: '',
pings: ''
}
},
nine: {
presence: {
status: ''
},
meals: {
status: '',
pings: ''
},
meds: {
status: '',
pings: ''
}
},
ten: {
presence: {
status: ''
},
meals: {
status: '',
pings: ''
},
meds: {
status: '',
pings: ''
}
},
eleven: {
presence: {
status: ''
},
meals: {
status: '',
pings: ''
},
meds: {
status: '',
pings: ''
}
},
twelve: {
presence: {
status: ''
},
meals: {
status: '',
pings: ''
},
meds: {
status: '',
pings: ''
}
}
};
});
|
JavaScript
| 0.999948 |
@@ -861,22 +861,20 @@
tatus: '
-yellow
+blue
'%0A
@@ -966,38 +966,36 @@
%09status: '
-yellow
+blue
',%0A //pin
@@ -1015,17 +1015,30 @@
etPings(
-3
+midnight, meds
)%0A
@@ -1031,32 +1031,34 @@
, meds)%0A
+//
pings: ''%0A
|
5794894b18da1e88d4151436c906a52d9eca7fec
|
use usage instead of allocation to get correct current usage on provider page
|
troposphere/static/js/components/providers/Stats.react.js
|
troposphere/static/js/components/providers/Stats.react.js
|
define(function (require) {
var React = require('react'),
Backbone = require('backbone'),
stores = require('stores');
return React.createClass({
propTypes: {
provider: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
//
// Helper Functions
//
_getIdentity: function(){
var provider = this.props.provider;
return this.props.identities.find(function(identity){
return identity.get('provider').id === provider.id;
});
},
//
// Render
//
renderStat: function(value, subText, moreInfo){
return (
<div className="col-md-3 provider-stat">
<div>
<span className="stat">{value}</span>
<span className="sub-text">{subText}</span>
</div>
<div className="more-info">{moreInfo}</div>
</div>
)
},
renderAllocationStat: function(allocationConsumedPercent, allocationConsumed, allocationTotal){
var allocationPercent = allocationConsumedPercent + "%";
var usedOverTotal = "(" + allocationConsumed + "/" + allocationTotal + ") AUs";
return this.renderStat(allocationPercent, usedOverTotal, "AUs currently used");
},
renderStats: function(identity, instances, sizes){
var allocation = identity.get('allocation');
var allocationConsumed = allocation.current;
var allocationTotal = allocation.threshold;
var allocationRemaining = allocationTotal - allocationConsumed;
var allocationConsumedPercent = Math.round(allocationConsumed/allocationTotal*100);
var instancesConsumingAllocation = identity.getInstancesConsumingAllocation(instances);
var allocationBurnRate = identity.getCpusUsed(instancesConsumingAllocation, sizes);
var timeRemaining = allocationRemaining/allocationBurnRate;
return (
<div className="row provider-info-section provider-stats">
{this.renderAllocationStat(allocationConsumedPercent, allocationConsumed, allocationTotal)}
{this.renderStat(instancesConsumingAllocation.length, "instances", "Number of instances consuming allocation")}
{this.renderStat(Math.round(timeRemaining), "hours", "Time remaining before allocation runs out")}
{this.renderStat(allocationBurnRate, "AUs/hour", "Rate at which AUs are being used")}
</div>
)
},
render: function () {
var provider = this.props.provider,
identity = stores.IdentityStore.findOne({'provider.id': provider.id}),
instances = stores.InstanceStore.findWhere({'provider.id': provider.id}),
sizes = stores.SizeStore.fetchWhere({
provider__id: provider.id,
page_size: 100
});
if(!provider || !identity || !instances || !sizes){
return (
<div className="loading"></div>
)
}
return this.renderStats(identity, instances, sizes);
}
});
});
|
JavaScript
| 0 |
@@ -1306,26 +1306,21 @@
ty.get('
-allocation
+usage
');%0A
@@ -2943,8 +2943,9 @@
%7D);%0A%0A%7D);
+%0A
|
2195ceb2ca5db9d78fb0e3110be01a4c0c9ed55d
|
throw an error message when using map exported in XML
|
src/level/TMXUtils.js
|
src/level/TMXUtils.js
|
/*
* MelonJS Game Engine
* Copyright (C) 2011 - 2016, Olivier Biot, Jason Oster, Aaron McLeod
* http://www.melonjs.org
*
* Tile QT 0.7.x format
* http://www.mapeditor.org/
*
*/
(function () {
/**
* a collection of TMX utility Function
* @final
* @memberOf me
* @ignore
*/
me.TMXUtils = (function () {
/*
* PUBLIC
*/
// hold public stuff in our singleton
var api = {};
/**
* set and interpret a TMX property value
* @ignore
*/
function setTMXValue(name, value) {
var match;
if (typeof(value) !== "string") {
// Value is already normalized
return value;
}
if (!value || value.isBoolean()) {
// if value not defined or boolean
value = value ? (value === "true") : true;
}
else if (value.isNumeric()) {
// check if numeric
value = Number(value);
}
else if (value.match(/^json:/i)) {
// try to parse it
match = value.split(/^json:/i)[1];
try {
value = JSON.parse(match);
}
catch (e) {
throw new me.Error("Unable to parse JSON: " + match);
}
}
else if (value.match(/^eval:/i)) {
// try to evaluate it
match = value.split(/^eval:/i)[1];
try {
value = eval(match);
}
catch (e) {
throw new me.Error("Unable to evaluate: " + match);
}
}
// normalize values
if (name.search(/^(ratio|anchorPoint)$/) === 0) {
// convert number to vector
if (typeof(value) === "number") {
value = {
"x" : value,
"y" : value
};
}
}
// return the interpreted value
return value;
}
function parseAttributes(obj, elt) {
// do attributes
if (elt.attributes && elt.attributes.length > 0) {
for (var j = 0; j < elt.attributes.length; j++) {
var attribute = elt.attributes.item(j);
if (typeof(attribute.name) !== "undefined") {
// DOM4 (Attr no longer inherit from Node)
obj[attribute.name] = attribute.value;
} else {
// else use the deprecated ones
obj[attribute.nodeName] = attribute.nodeValue;
}
}
}
}
/**
* Decode the given data
* @ignore
*/
api.decode = function (data, encoding, compression) {
compression = compression || "none";
encoding = encoding || "none";
switch (encoding) {
case "csv":
return me.utils.decodeCSV(data);
case "base64":
var decoded = me.utils.decodeBase64AsArray(data, 4);
return (
(compression === "none") ?
decoded :
me.utils.decompress(decoded, compression)
);
case "none":
return data;
default:
throw new me.Error("Unknown layer encoding: " + encoding);
}
};
/**
* Normalize TMX format to Tiled JSON format
* @ignore
*/
api.normalize = function (obj, item) {
var nodeName = item.nodeName;
switch (nodeName) {
case "data":
var data = api.parse(item);
obj.data = api.decode(data.text, data.encoding, data.compression);
obj.encoding = "none";
break;
case "imagelayer":
case "layer":
case "objectgroup":
var layer = api.parse(item);
layer.type = (nodeName === "layer" ? "tilelayer" : nodeName);
if (layer.image) {
layer.image = layer.image.source;
}
obj.layers = obj.layers || [];
obj.layers.push(layer);
break;
case "animation":
obj.animation = api.parse(item).frames;
break;
case "frame":
case "object":
var name = nodeName + "s";
obj[name] = obj[name] || [];
obj[name].push(api.parse(item));
break;
case "tile":
var tile = api.parse(item);
obj.tiles = obj.tiles || {};
obj.tiles[tile.id] = tile;
break;
case "tileset":
var tileset = api.parse(item);
if (tileset.image) {
tileset.imagewidth = tileset.image.width;
tileset.imageheight = tileset.image.height;
tileset.image = tileset.image.source;
}
obj.tilesets = obj.tilesets || [];
obj.tilesets.push(tileset);
break;
case "polygon":
case "polyline":
obj[nodeName] = [];
// Get a point array
var points = api.parse(item).points.split(" ");
// And normalize them into an array of vectors
for (var i = 0, v; i < points.length; i++) {
v = points[i].split(",");
obj[nodeName].push({
"x" : +v[0],
"y" : +v[1]
});
}
break;
case "properties":
obj.properties = api.parse(item);
break;
case "property":
var property = api.parse(item);
obj[property.name] = setTMXValue(property.name, property.value);
break;
default:
obj[nodeName] = api.parse(item);
break;
}
};
/**
* Parse a XML TMX object and returns the corresponding javascript object
* @ignore
*/
api.parse = function (xml) {
// Create the return object
var obj = {};
var text = "";
if (xml.nodeType === 1) {
// do attributes
parseAttributes(obj, xml);
}
// do children
if (xml.hasChildNodes()) {
for (var i = 0; i < xml.childNodes.length; i++) {
var item = xml.childNodes.item(i);
switch (item.nodeType) {
case 1:
api.normalize(obj, item);
break;
case 3:
text += item.nodeValue.trim();
break;
}
}
}
if (text) {
obj.text = text;
}
return obj;
};
/**
* Apply TMX Properties to the given object
* @ignore
*/
api.applyTMXProperties = function (obj, data) {
var properties = data.properties;
if (typeof(properties) !== "undefined") {
for (var name in properties) {
if (properties.hasOwnProperty(name)) {
// set the value
obj[name] = setTMXValue(name, properties[name]);
}
}
}
};
// return our object
return api;
})();
})();
|
JavaScript
| 0 |
@@ -3034,32 +3034,128 @@
sion %7C%7C %22none%22;%0A
+ // When no encoding is given, the tiles are stored as individual XML tile elements.%0A
enco
@@ -3174,20 +3174,19 @@
ing %7C%7C %22
-none
+xml
%22;%0A%0A
@@ -3666,16 +3666,135 @@
data;%0A%0A
+ case %22xml%22:%0A throw new me.Error(%22XML encoding is deprecated, use base64 instead%22);%0A%0A
|
f03ced1028a785da65b8142b1ce1b1f11a4c2793
|
Fix webpack-dev-server to work properly
|
gulpfile.js
|
gulpfile.js
|
var gulp = require("gulp"),
gutil = require("gulp-util"),
jshint = require("gulp-jshint"),
less = require("gulp-less"),
concat = require("gulp-concat"),
uglify = require("gulp-uglify"),
path = require("path"),
shell = require("gulp-shell"),
rename = require("gulp-rename"),
react = require("gulp-react"),
jsxcs = require("gulp-jsxcs"),
jest = require("gulp-jest"),
transform = require("vinyl-transform"),
fs = require("fs"),
es = require("event-stream"),
JSONStream = require("JSONStream"),
runSequence = require("run-sequence"),
_ = require("underscore"),
webpack = require("webpack"),
webpackConfig = require("./webpack.config.js"),
WebpackDevServer = require("webpack-dev-server");
// Lint Task
gulp.task("lint", function() {
return gulp.src("js/**/*.js")
.pipe(jsxcs().on("error", function(err) {
console.log(err.toString());
}))
.pipe(react({
harmony: true,
// Skip Flow type annotations!
stripTypes: true
}))
.pipe(jshint({
esnext: true
}))
.pipe(jshint.reporter("default"));
});
// Compile Our LESS
gulp.task("less", function() {
return gulp.src("./style/**/*.less")
.pipe(less({
paths: [ path.join(__dirname, "style") ]
}))
.pipe(gulp.dest("./build/css"));
});
// The react task should not normally be needed.
// This is only present if the errors from webpack and you
// want to only try running react.
gulp.task("react", function() {
return gulp.src(["./js/**/*.js"])
.pipe(react({
harmony: true,
// Skip Flow type annotations!
stripTypes: true
}))
.pipe(gulp.dest("./build"));
});
gulp.task("webpack", function(callback) {
var myConfig = Object.create(webpackConfig);
myConfig.debug = true;
webpack(myConfig, function(err, stats) {
if(err) {
throw new gutil.PluginError("webpack", err);
}
// Log filenames packed:
//gutil.log("[webpack]", stats.toString({
// output options
//}));
callback();
});
});
gulp.task("webpack-dev-server", function(callback) {
var myConfig = Object.create(webpackConfig);
myConfig.debug = true;
new WebpackDevServer(webpack(myConfig)).listen(8008, "localhost", function(err) {
if (err) {
throw new gutil.PluginError("webpack-dev-server", err);
}
// Server listening
gutil.log("[webpack-dev-server]", "http://localhost:8008/webpack-dev-server/index.html");
// keep the server alive or continue?
// callback();
});
});
gulp.task("package", function () {
return gulp.src("", {read: false})
.pipe(shell([
"./tools/package"
]))
});
// Concatenate & Minify JS
gulp.task("releasify", function() {
return gulp.src("build/**/*.js")
.pipe(concat("all.js"))
.pipe(gulp.dest("dist"))
.pipe(rename("all.min.js"))
.pipe(uglify())
.pipe(gulp.dest("dist"));
});
// Test
gulp.task("test", function() {
return gulp.src("__tests__").pipe(jest({
scriptPreprocessor: "./js/preprocessor.js",
unmockedModulePathPatterns: [
"node_modules/react"
],
testDirectoryName: "js",
testPathIgnorePatterns: [
"node_modules",
"js/preprocessor.js"
],
moduleFileExtensions: [
"js",
"json",
"react"
]
}));
});
// Watch Files For Changes
gulp.task("watch", function() {
gulp.watch("js/**/*.js", ["lint", "webpack"]);
gulp.watch("style/**/*.less", ["less"]);
});
// Default Task
// Not including Flow typechecking by default because it takes so painfully long.
// Maybe because of my code layout or otheriwse, needto figure it out before enabling by default.
gulp.task("default", function(cb) {
runSequence(["lint", "less", "webpack"], "package", cb);
});
|
JavaScript
| 0.000001 |
@@ -2329,25 +2329,24 @@
bug = true;%0A
-%0A
new Webp
@@ -2375,16 +2375,125 @@
yConfig)
+, %7B%0A publicPath: myConfig.output.publicPath,%0A stats: %7B%0A colors: true%0A %7D%0A %7D
).listen
|
9a8e4bb57162427fae48c103ce9137e6991dad29
|
Add init notification
|
lib/dark-mode.js
|
lib/dark-mode.js
|
'use babel';
import { CompositeDisposable } from 'atom';
import AmbientLight from './ambient-light';
import Config from './config';
let notificationsOptions = { icon: 'light-bulb' };
export default {
subscriptions: null,
config: Config,
lightTheme: null,
darkTheme: null,
currentTheme: null,
activate() {
this.subscriptions = new CompositeDisposable();
this.registerCommands();
this.registerCallbacks();
this.lightTheme = atom.config.get('dark-mode.lightProfile');
this.darkTheme = atom.config.get('dark-mode.darkProfile');
this.currentTheme = atom.config.get('core.themes').join(' ');
this.ambientLight = new AmbientLight(this.onLight.bind(this), this.onDark.bind(this));
this.ambientLight.activate();
},
registerCommands() {
this.subscriptions.add(atom.commands.add('atom-workspace', {
'dark-mode:toggle': () => this.toggle(),
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'dark-mode:Turn On Auto Mode': () => {
atom.config.set('dark-mode.ambientLight', true);
},
}));
this.subscriptions.add(atom.commands.add('atom-workspace', {
'dark-mode:Turn Off Auto Mode': () => {
atom.config.set('dark-mode.ambientLight', false);
},
}));
},
registerCallbacks() {
this.subscriptions.add(atom.config.onDidChange('dark-mode.ambientLight', ({newValue}) => {
this.ambientLight.activate();
if (newValue) {
atom.notifications.addInfo('Dark Mode: Automatic theme changes has been turn on', notificationsOptions);
} else {
atom.notifications.addInfo('Dark Mode: Automatic theme changes has been turn off', notificationsOptions);
}
}));
this.subscriptions.add(atom.config.onDidChange('dark-mode.ambientLightInterval', () => {
this.ambientLight.activate();
}));
this.subscriptions.add(atom.config.onDidChange('dark-mode.darkProfile', ({newValue}) => {
this.darkTheme = newValue;
}));
this.subscriptions.add(atom.config.onDidChange('dark-mode.lightProfile', ({newValue}) => {
this.lightTheme = newValue;
}));
this.subscriptions.add(atom.config.onDidChange('core.themes', ({newValue}) => {
this.currentTheme = newValue.join(' ');
}));
},
deactivate() {
this.subscriptions.dispose();
},
toggle() {
atom.config.set('dark-mode.ambientLight', false);
let next = (this.currentTheme == this.darkTheme ? this.lightTheme : this.darkTheme);
return this._changeTheme(next);
},
onLight() {
if (this.currentTheme != this.lightTheme) {
this._changeTheme(this.lightTheme);
atom.notifications.addSuccess('Dark Mode: Theme has been changed automatically', notificationsOptions);
}
},
onDark() {
if (this.currentTheme != this.darkTheme) {
this._changeTheme(this.darkTheme);
atom.notifications.addSuccess('Dark Mode: Theme has been changed automatically', notificationsOptions);
}
},
_changeTheme(theme) {
atom.config.set('core.themes', theme.split(' '));
}
};
|
JavaScript
| 0.000001 |
@@ -719,24 +719,368 @@
.activate();
+%0A%0A%09%09let turnOn = this.ambientLight.isTurnOn();%0A%09%09let state = turnOn ? 'ON' : 'OFF';%0A%0A%09%09atom.notifications.addInfo(%60Dark Mode: Automatic mode is $%7Bstate%7D%60, %7B%0A%09%09%09icon: 'light-bulb',%0A%09%09%09buttons: %5B%0A%09%09%09%09%7B%0A%09%09%09%09%09text: turnOn ? 'Disable' : 'Enable',%0A%0A%09%09%09%09%09onDidClick() %7B%0A%09%09%09%09%09%09atom.config.set('dark-mode.ambientLight', !turnOn);%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%5D%0A%09%09%7D);
%0A%09%7D,%0A%0A%09regis
@@ -1683,180 +1683,78 @@
%0A%09%09%09
-this.ambientLight.activate();%0A%0A%09%09%09if (newValue) %7B%0A%09%09%09%09atom.notifications.addInfo('Dark Mode: Automatic theme changes has been turn on', notificationsOptions);%0A%09%09%09%7D else %7B%0A%09
+let state = newValue ? 'ON' : 'OFF';%0A%09%09%09this.ambientLight.activate();%0A
%09%09%09a
@@ -1779,17 +1779,17 @@
addInfo(
-'
+%60
Dark Mod
@@ -1805,40 +1805,25 @@
tic
-theme changes has been turn off'
+mode is $%7Bstate%7D%60
, no
@@ -1843,21 +1843,16 @@
tions);%0A
-%09%09%09%7D%0A
%09%09%7D));%0A%0A
|
48b8615606cd74bbea7cd05a5365baadfa664bc1
|
Add the windows RELEASES files to the release
|
upload.js
|
upload.js
|
'use strict';
const _ = require('lodash');
const path = require('path');
const OSX_EXT = '.dmg';
const OSX_PATCH_EXT = '-mac.zip';
const WIN_EXT = '.exe';
const WIN64_EXT = '-x64.exe';
const WIN_NU_EXT = '-full.nupkg';
const WIN64_NU_EXT = 'x64-full.nupkg';
const WIN_NU_DELTA_EXT = '-delta.nupkg';
const WIN64_NU_DELTA_EXT = 'x64-delta.nupkg';
let NUCLEUS_PATH_GLOBAL;
const last = (string, num) => {
return string.substr(string.length - num);
};
const upload = (github, id, assetPath, name, suppressError) => {
console.log('Starting upload - ' + name); // eslint-disable-line
github.releases.uploadAsset({
owner: 'Nucleus-Player',
repo: 'Nucleus-Player-Releases',
id,
name,
filePath: path.resolve(NUCLEUS_PATH_GLOBAL + assetPath),
}, (err) => {
if (err && !suppressError) {
console.log('Something went wrong...'); // eslint-disable-line
console.error(err); // eslint-disable-line
} else if (err) {
console.log('!!! Upload Suppressed - ' + name); // eslint-disable-line
} else {
console.log('Upload Successfull - ' + name); // eslint-disable-line
}
});
};
module.exports = (NUCLEUS_PATH, RELEASE_TYPE, github, targetRelease) => {
let needOSX = RELEASE_TYPE === 'darwin';
let needOSXPatch = RELEASE_TYPE === 'darwin';
let needWin = RELEASE_TYPE !== 'darwin';
let needWin64 = RELEASE_TYPE !== 'darwin';
let needWinNu = RELEASE_TYPE !== 'darwin';
let needWin64Nu = RELEASE_TYPE !== 'darwin';
let needWinNuDelta = RELEASE_TYPE !== 'darwin';
let needWin64NuDelta = RELEASE_TYPE !== 'darwin';
NUCLEUS_PATH_GLOBAL = NUCLEUS_PATH;
_.forEach(targetRelease.assets || [], (asset) => {
if (last(asset.name, OSX_EXT.length) === OSX_EXT) {
needOSX = false;
} else if (last(asset.name, OSX_PATCH_EXT.length) === OSX_PATCH_EXT) {
needOSXPatch = false;
} else if (last(asset.name, WIN64_EXT.length) === WIN64_EXT) {
needWin64 = false;
} else if (last(asset.name, WIN_EXT.length) === WIN_EXT) {
needWin = false;
} else if (last(asset.name, WIN64_NU_EXT.length) === WIN64_NU_EXT) {
needWin64Nu = false;
} else if (last(asset.name, WIN_NU_EXT.length) === WIN_NU_EXT) {
needWinNu = false;
} else if (last(asset.name, WIN64_NU_DELTA_EXT.length) === WIN64_NU_DELTA_EXT) {
needWin64NuDelta = false;
} else if (last(asset.name, WIN_NU_DELTA_EXT.length) === WIN_NU_DELTA_EXT) {
needWinNuDelta = false;
}
});
const packageJSON = require(path.resolve(NUCLEUS_PATH + '/package.json'));
if (needWin) {
upload(github, targetRelease.id,
'/dist/build/installer32/Nucleus PlayerSetup.exe', 'Nucleus Player Setup.exe');
}
if (needWin64) {
upload(github, targetRelease.id,
'/dist/build/installer64/Nucleus PlayerSetup.exe', 'Nucleus Player Setup-x64.exe');
}
if (needWinNu) {
upload(github, targetRelease.id,
'/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
'NucleusPlayer-' + packageJSON.version + '-full.nupkg');
}
if (needWin64Nu) {
upload(github, targetRelease.id,
'/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-full.nupkg',
'NucleusPlayer-' + packageJSON.version + '-x64-full.nupkg');
}
if (needWinNuDelta) {
upload(github, targetRelease.id,
'/dist/build/installer32/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
'NucleusPlayer-' + packageJSON.version + '-delta.nupkg', true);
}
if (needWin64NuDelta) {
upload(github, targetRelease.id,
'/dist/build/installer64/NucleusPlayer-' + packageJSON.version + '-delta.nupkg',
'NucleusPlayer-' + packageJSON.version + '-x64-delta.nupkg', true);
}
// if (needWinNu) {
// pathToAsset = NUCLEUS_PATH + '/dist/built/win/Nuceleus Player Setup.exe';
// upload(github, targetRelease.id, pathToAsset, 'Nucleus Player Setup.exe');
// }
};
|
JavaScript
| 0 |
@@ -2664,32 +2664,36 @@
us Player Setup.
+win.
exe');%0A %7D%0A if
@@ -2821,16 +2821,20 @@
er Setup
+.win
-x64.exe
@@ -3715,16 +3715,286 @@
e);%0A %7D%0A
+ if (needWinNuDelta) %7B%0A upload(github, targetRelease.id,%0A '/dist/build/installer32/RELEASES',%0A 'RELEASES', true);%0A %7D%0A if (needWin64NuDelta) %7B%0A upload(github, targetRelease.id,%0A '/dist/build/installer64/RELEASES',%0A 'RELEASES-x64', true);%0A %7D%0A
// if
|
ce3dec48fe0364e198681976b568bd2327de2c5b
|
fix tests for lodash 4
|
test/unit/controllers/CommunityController.test.js
|
test/unit/controllers/CommunityController.test.js
|
var root = require('root-path')
require(root('test/setup'))
var factories = require(root('test/setup/factories'))
var Promise = require('bluebird')
var checkAndSetMembership = Promise.promisify(require(require('root-path')('api/policies/checkAndSetMembership')))
var CommunityController = require(root('api/controllers/CommunityController'))
describe('CommunityController', () => {
var req, res, user
before(() => {
user = factories.user()
return user.save()
})
beforeEach(() => {
req = factories.mock.request()
res = factories.mock.response()
})
describe('.findOne', () => {
var community
beforeEach(() => {
community = factories.community({beta_access_code: 'sekrit'})
return community.save()
.then(() => user.joinCommunity(community))
.then(() => {
req.params.communityId = community.id
req.session.userId = user.id
})
})
it('does not include the invitation code', () => {
return checkAndSetMembership(req, res)
.then(() => CommunityController.findOne(req, res))
.then(() => {
expect(res.ok).to.have.been.called()
expect(res.body).to.deep.equal({
id: community.id,
name: community.get('name'),
slug: community.get('slug'),
avatar_url: null,
banner_url: null,
description: null,
settings: {},
location: null
})
})
})
})
describe('.create', () => {
it('works', () => {
req.session.userId = user.id
_.extend(req.params, {name: 'Bar', slug: 'bar'})
return CommunityController.create(req, res)
.then(() => Community.find('bar', {withRelated: ['users', 'memberships', 'leader']}))
.then(community => {
expect(community).to.exist
expect(community.get('name')).to.equal('Bar')
expect(community.get('slug')).to.equal('bar')
expect(community.relations.leader.id).to.equal(user.id)
expect(community.relations.users.first().pivot.get('role')).to.equal(Membership.MODERATOR_ROLE)
})
})
})
describe('.validate', () => {
it('rejects non-whitelisted columns', () => {
req.params.column = 'foo'
CommunityController.validate(req, res)
.then(() => {
expect(res.badRequest).to.have.been.called()
expect(res.body).to.equal('invalid value "foo" for parameter "column"')
})
})
it('requires a value', () => {
req.params.column = 'name'
CommunityController.validate(req, res)
.then(() => {
expect(res.badRequest).to.have.been.called()
expect(res.body).to.equal('missing required parameter "value"')
})
})
it('requires a constraint', () => {
_.extend(req.params, {column: 'name', value: 'foo', constraint: 'foo'})
CommunityController.validate(req, res)
.then(() => {
expect(res.badRequest).to.have.been.called()
expect(res.body).to.equal('invalid value "foo" for parameter "constraint"')
})
})
describe('with an existing value', () => {
var community
before(() => {
community = factories.community()
return community.save()
})
it('fails a uniqueness check', () => {
_.extend(req.params, {column: 'name', value: community.get('name'), constraint: 'unique'})
return CommunityController.validate(req, res)
.then(() => {
expect(res.ok).to.have.been.called()
expect(res.body).to.deep.equal({unique: false})
})
})
it('passes an existence check', () => {
_.extend(req.params, {column: 'name', value: community.get('name'), constraint: 'exists'})
return CommunityController.validate(req, res)
.then(() => {
expect(res.ok).to.have.been.called()
expect(res.body).to.deep.equal({exists: true})
})
})
})
})
describe('.joinWithCode', () => {
var community
beforeEach(() => {
community = factories.community({beta_access_code: 'foo'})
return community.save()
})
it('works', () => {
req.params.code = 'foo'
req.login(user.id)
return CommunityController.joinWithCode(req, res)
.tap(() => Promise.join(
community.load(['posts', 'posts.relatedUsers']),
user.load('communities')
))
.then(() => {
var welcome = community.relations.posts.find(p => p.get('type') === 'welcome')
expect(welcome).to.exist
var relatedUser = welcome.relations.relatedUsers.first()
expect(relatedUser).to.exist
expect(relatedUser.id).to.equal(user.id)
expect(user.relations.communities.map(c => c.id)).to.contain(community.id)
})
})
})
describe('.findForNetwork', () => {
var network
before(done => {
network = new Network({name: 'N1', slug: 'n1'}).save()
return network
.then(network => {
return Promise.join({
c1: new Community({name: 'NC1', slug: 'nc1', network_id: network.get('id')}).save(),
c2: new Community({name: 'NC2', slug: 'nc2', network_id: network.get('id')}).save(),
c3: new Community({name: 'NC3', slug: 'nc3'}).save(),
n1: network
})
})
.then(() => done())
})
it('works with slug', () => {
req.params.networkId = 'n1'
req.login(user.id)
return CommunityController.findForNetwork(req, res)
.then(() => {
expect(res.body.length).to.equal(2)
expect(Number(res.body[0].memberCount)).to.equal(0)
var slugs = res.body.map(c => c.slug)
expect(!!_.contains(slugs, 'nc1')).to.equal(true)
expect(!!_.contains(slugs, 'nc2')).to.equal(true)
expect(!!_.contains(slugs, 'nc3')).to.equal(false)
})
})
it('works with paginate', () => {
req.params.networkId = 'n1'
req.params.paginate = true
req.params.offset = 1
req.params.limit = 1
req.login(user.id)
return CommunityController.findForNetwork(req, res)
.then(() => {
expect(res.body.communities_total).to.equal('2')
expect(res.body.communities.length).to.equal(1)
expect(res.body.communities[0].slug).to.equal('nc2')
expect(Number(res.body.communities[0].memberCount)).to.equal(0)
})
})
})
})
|
JavaScript
| 0 |
@@ -5627,39 +5627,39 @@
expect(!!_.
-contain
+include
s(slugs, 'nc1'))
@@ -5685,39 +5685,39 @@
expect(!!_.
-contain
+include
s(slugs, 'nc2'))
@@ -5751,23 +5751,23 @@
ect(!!_.
-contain
+include
s(slugs,
|
7484d40ede21f5b76a6245495a067503e8aa2a76
|
add 'clean' method and coerce input type number to set a 'number' value
|
ampersand-input-view.js
|
ampersand-input-view.js
|
var View = require('ampersand-view');
module.exports = View.extend({
template: [
'<label>',
'<span role="label"></span>',
'<input>',
'<div role="message-container" class="message message-below message-error">',
'<p role="message-text"></p>',
'</div>',
'</label>'
].join(''),
bindings: {
'name': {
type: 'attribute',
selector: 'input, textarea',
name: 'name'
},
'label': [
{
role: 'label'
},
{
type: 'toggle',
role: 'label'
}
],
'message': {
type: 'text',
role: 'message-text'
},
'showMessage': {
type: 'toggle',
role: 'message-container'
},
'placeholder': {
type: 'attribute',
selector: 'input, textarea',
name: 'placeholder'
},
'validityClass': {
type: 'class',
selector: 'input, textarea'
}
},
initialize: function (spec) {
this.tests = this.tests || spec.tests || [];
this.on('change:type', this.handleTypeChange, this);
this.handleBlur = this.handleBlur.bind(this);
this.handleInputChanged = this.handleInputChanged.bind(this);
this.startingValue = this.value;
this.on('change:valid change:value', this.reportToParent, this);
},
render: function () {
this.renderWithTemplate();
this.input = this.get('input') || this.get('textarea');
// switches out input for textarea if that's what we want
this.handleTypeChange();
this.initInputBindings();
this.setValue(this.value);
},
props: {
value: 'string',
startingValue: 'string',
name: 'string',
type: ['string', true, 'text'],
placeholder: ['string', true, ''],
label: ['string', true, ''],
required: ['boolean', true, true],
directlyEdited: ['boolean', true, false],
shouldValidate: ['boolean', true, false],
message: ['string', true, ''],
requiredMessage: ['string', true, 'This fields is required.'],
validClass: ['string', true, 'input-valid'],
invalidClass: ['string', true, 'input-invalid']
},
derived: {
valid: {
deps: ['value'],
fn: function () {
return !this.runTests();
}
},
showMessage: {
deps: ['message', 'shouldValidate'],
fn: function () {
return this.shouldValidate && this.message;
}
},
changed: {
deps: ['value', 'startingValue'],
fn: function () {
return this.value !== this.startingValue;
}
},
validityClass: {
deps: ['valid', 'validClass', 'invalidClass', 'shouldValidate', 'changed'],
fn: function () {
if (!this.shouldValidate || !this.changed) {
return '';
} else {
return this.valid ? this.validClass : this.invalidClass;
}
}
}
},
setValue: function () {
this.input.value = this.value;
if (!this.getErrorMessage(this.value)) {
this.shouldValidate = true;
}
},
getErrorMessage: function () {
var message = '';
if (this.required && !this.value) {
return this.requiredMessage;
} else {
(this.tests || []).some(function (test) {
message = test.call(this, this.value) || '';
return message;
}, this);
return message;
}
},
handleTypeChange: function () {
if (this.type === 'textarea' && this.input.tagName.toLowerCase() !== 'textarea') {
var parent = this.input.parentNode;
var textarea = document.createElement('textarea');
parent.replaceChild(textarea, this.input);
this.input = textarea;
this._applyBindingsForKey('');
} else {
this.input.type = this.type;
}
},
handleInputChanged: function () {
if (document.activeElement === this.input) {
this.directlyEdited = true;
}
this.value = this.input.value;
},
handleBlur: function () {
if (this.value && this.changed) {
this.shouldValidate = true;
}
this.runTests();
},
beforeSubmit: function () {
// at the point where we've tried
// to submit, we want to validate
// everything from now on.
this.shouldValidate = true;
this.runTests();
},
runTests: function () {
var message = this.getErrorMessage();
if (!message && this.value && this.changed) {
// if it's ever been valid,
// we want to validate from now
// on.
this.shouldValidate = true;
}
this.message = message;
return message;
},
initInputBindings: function () {
this.input.addEventListener('blur', this.handleBlur, false);
this.input.addEventListener('input', this.handleInputChanged, false);
},
remove: function () {
this.input.removeEventListener('input', this.handleInputChanged, false);
this.input.removeEventListener('blur', this.handleBlur, false);
View.prototype.remove.apply(this, arguments);
},
reportToParent: function () {
if (this.parent) this.parent.update(this);
}
});
|
JavaScript
| 0.000055 |
@@ -1841,30 +1841,27 @@
value: '
-string
+any
',%0A s
@@ -3345,38 +3345,163 @@
-this.input.value = this.value;
+if (!this.value) %7B%0A this.input.value = '';%0A %7D else %7B%0A this.input.value = String.prototype.toString.call(this.value);%0A %7D
%0A
@@ -4593,27 +4593,142 @@
= this.
-input.value
+clean(this.input.value);%0A %7D,%0A clean: function (val) %7B%0A return (this.type === 'number') ? Number(val) : val.trim()
;%0A %7D,
|
b6a6d9571a59a369d9bdfde2f6e7c2fc88ecb6bd
|
improve gulp
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp')
, connect = require('gulp-connect')
, stylus = require('gulp-stylus')
, prefix = require('gulp-autoprefixer');
gulp.task('connect', connect.server({
root: __dirname + '/document',
port: 1337,
open: { browser: 'Google Chrome'},
})
);
gulp.task('stylus', function() {
gulp.src('./source/ng-trans.styl')
.pipe(stylus())
.pipe(prefix("last 2 version", "> 1%", "ie 8"))
.pipe(gulp.dest('./'))
.pipe(gulp.dest('document/'))
});
gulp.task('watch', function () {
gulp.watch('source/*.styl', ['stylus']);
});
gulp.task('default', ['stylus'])
gulp.task('dev', function(){
gulp.run('connect', 'stylus');
gulp.watch('source/*.styl' , function(ev){
gulp.run('stylus')
});
});
|
JavaScript
| 0.000013 |
@@ -23,19 +23,19 @@
'gulp')%0A
-,
+var
connect
@@ -61,19 +61,19 @@
nnect')%0A
-,
+var
stylus
@@ -102,11 +102,11 @@
s')%0A
-,
+var
pre
@@ -146,160 +146,67 @@
');%0A
-%0A%0Agulp.task('connect', connect.server(%7B%0A root: __dirname + '/document',%0A port: 1337,%0A open: %7B browser: 'Google Chrome'%7D,%0A %7D)%0A);%0A%0Agulp.task('s
+var plumber = require('gulp-plumber');%0A%0Avar compileS
tylus
-',
+ =
fun
@@ -211,16 +211,19 @@
unction(
+src
) %7B%0A gu
@@ -233,32 +233,34 @@
src(
-'./source/ng-trans.styl'
+src)%0A .pipe(plumber()
)%0A
@@ -397,16 +397,228 @@
ment/'))
+;%0A%7D;%0A%0Agulp.task('connect', connect.server(%7B%0A root: __dirname + '/document',%0A port: 1337,%0A open: %7B browser: 'Google Chrome'%7D,%0A %7D)%0A);%0A%0Agulp.task('stylus', function() %7B%0A compileStylus('./source/ng-trans.styl');
%0A%7D);%0A%0Agu
@@ -728,17 +728,17 @@
tylus'%5D)
-%0A
+;
%0A%0Agulp.t
@@ -746,11 +746,13 @@
sk('
-dev
+serve
', f
@@ -824,17 +824,16 @@
/*.styl'
-
, functi
@@ -841,40 +841,136 @@
n(ev
+ent
)%7B%0A
- gulp.run('stylus')%0A
+console.log('File '+event.path+' was '+event.type+', running tasks...');%0A compileStylus('./source/ng-trans.styl');%0A
%7D)
|
90db91abe259d6dcc09bc66b8e3950952ad041d1
|
fix issues.
|
js/resupdater.js
|
js/resupdater.js
|
$(function () {
chrome.storage.local.get(function (result) {
if (Object.getOwnPropertyNames(result).length > 0) {
var siteUrl = result['siteUrl'],
type = result['type'],
sourceUrl = result['sourceUrl'],
replaceUrl = result['replaceUrl'];
var href = window.location.href;
if (href.indexOf(siteUrl) > -1) {
$('<button style="cursor: pointer; position: fixed; bottom: 0; right: 0; font-size: 20px; padding:10px 20px;">Update CSS</button>')
.appendTo('body').click(function () {
$('link').each(function () {
var $this = $(this);
if ($this.attr('href').indexOf(sourceUrl) > -1) {
var baseUrl = replaceUrl.split('?')[0];
$this.attr('href', baseUrl + '?_=' + Date.now());
sourceUrl = baseUrl;
}
});
});
}
}
});
});
|
JavaScript
| 0.000001 |
@@ -708,29 +708,8 @@
eUrl
- + '?_=' + Date.now()
);%0A%09
@@ -781,8 +781,9 @@
%09%7D);%0A%7D);
+%0A
|
886ac0890772a27019c280846dcfc5753187672f
|
fix es6 import script.js mimeType
|
utils/servers/simplehttpserver.js
|
utils/servers/simplehttpserver.js
|
/**
* a barebones HTTP server in JS
* to serve three.js easily
*
* @author zz85 https://github.com/zz85
*
* Usage: node simplehttpserver.js <port number>
*
* do not use in production servers
* and try
* npm install http-server -g
* instead.
*/
var port = 8000,
http = require('http'),
urlParser = require('url'),
fs = require('fs'),
path = require('path'),
currentDir = process.cwd();
port = process.argv[2] ? parseInt(process.argv[2], 0) : port;
function handleRequest(request, response) {
var urlObject = urlParser.parse(request.url, true);
var pathname = decodeURIComponent(urlObject.pathname);
console.log('[' + (new Date()).toUTCString() + '] ' + '"' + request.method + ' ' + pathname + '"');
var filePath = path.join(currentDir, pathname);
fs.stat(filePath, function(err, stats) {
if (err) {
response.writeHead(404, {});
response.end('File not found!');
return;
}
if (stats.isFile()) {
fs.readFile(filePath, function(err, data) {
if (err) {
response.writeHead(404, {});
response.end('Opps. Resource not found');
return;
}
response.writeHead(200, {});
response.write(data);
response.end();
});
} else if (stats.isDirectory()) {
fs.readdir(filePath, function(error, files) {
if (error) {
response.writeHead(500, {});
response.end();
return;
}
var l = pathname.length;
if (pathname.substring(l-1)!='/') pathname += '/';
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('<!DOCTYPE html>\n<html><head><meta charset="UTF-8"><title>' + filePath + '</title></head><body>');
response.write('<h1>' + filePath + '</h1>');
response.write('<ul style="list-style:none;font-family:courier new;">');
files.unshift('.', '..');
files.forEach(function(item) {
var urlpath = pathname + item,
itemStats = fs.statSync(currentDir + urlpath);
if (itemStats.isDirectory()) {
urlpath += '/';
item += '/';
}
response.write('<li><a href="'+ urlpath + '">' + item + '</a></li>');
});
response.end('</ul></body></html>');
});
}
});
}
http.createServer(handleRequest).listen(port);
require('dns').lookup(require('os').hostname(), function (err, addr, fam) {
console.log('Running at http://' + addr + ((port === 80) ? '' : ':') + port + '/');
});
console.log('Three.js server has started...');
console.log('Base directory at ' + currentDir);
|
JavaScript
| 0.000005 |
@@ -1109,37 +1109,167 @@
%09%09%09%09
-response.writeHead(200, %7B%7D
+var fileType = filePath.split('.').pop().toLowerCase();%0A%0A%09%09%09%09response.writeHead(200, %7B %0A%09%09%09%09%09%22Content-Type%22: mimeTypes%5BfileType%5D %7C%7C mimeTypes%5B'bin'%5D%0A%09%09%09%09%7D
);%0A
+%0A
%09%09%09%09
@@ -1310,16 +1310,17 @@
.end();%0A
+%0A
%09%09%09%7D);%0A%0A
|
427f2a7eeafc2aeb0d5fb9e0191ffc8fc887488c
|
fix gulp build
|
.webpack-dist.js
|
.webpack-dist.js
|
var webpack = require('webpack')
var path = require('path')
var BUILD_DIR = path.join(__dirname, 'build/jsx')
var DIST_DIR = path.join(__dirname, 'dist/assets/js')
var config = {
devtool: 'cheap-module-source-map',
entry: BUILD_DIR + '/script.js',
output: {
path: DIST_DIR,
filename: 'script.js'
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress:{
warnings: false
}
})
],
resolve: {
extensions: ['', '.js', '.jsx']
},
module: {
loaders: [{
test: /\.jsx?/,
include: BUILD_DIR,
loader: 'babel'
}]
}
}
module.exports = config
|
JavaScript
| 0.000001 |
@@ -244,16 +244,17 @@
cript.js
+x
',%0A out
@@ -304,16 +304,17 @@
cript.js
+x
'%0A %7D,%0A
|
8074ee9309a0f8b7bc178c730ccf18c55b9cc7d8
|
Add watch task
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp');
var karma = require('gulp-karma');
var jshint = require('gulp-jshint');
var path = require('path');
var fs = require('fs');
var browserify = require('browserify');
var jsRoot = path.join(__dirname);
var bundlePath = path.join('dist', 'bundle.js');
var mkdirp = require('mkdirp');
var glob = require('glob');
var source = require('vinyl-source-stream');
var sourceFiles = glob.sync('./src/*.js');
var testFiles = glob.sync('spec/*_spec.js');
gulp.task('lint', function() {
return gulp.src('src/*.js')
.pipe(jshint())
.pipe(jshint.reporter('default'));
});
gulp.task('scripts', function () {
mkdirp('dist', console.error);
return browserify(sourceFiles)
.on('error', console.error)
.bundle({debug: true})
.pipe(source('bundle.js'))
.pipe(gulp.dest('dist'));
});
gulp.task('spec', ['scripts'], function() {
gulp.src(testFiles)
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
})).on('error', function() { this.emit('end'); });
});
gulp.task('default', ['scripts', 'lint', 'spec']);
|
JavaScript
| 0.999877 |
@@ -409,29 +409,29 @@
iles
- = glob.sync(
+GlobString =
'./src/*
.js'
@@ -426,21 +426,23 @@
'./src/*
+*/*
.js'
-)
;%0Avar te
@@ -452,28 +452,31 @@
iles
- = glob.sync(
+GlobString =
'spec/*
+*/*
_spe
@@ -480,16 +480,116 @@
spec.js'
+;%0A%0Avar sourceFiles = glob.sync(sourceFilesGlobString);%0Avar testFiles = glob.sync(testFilesGlobString
);%0A%0Agulp
@@ -1118,32 +1118,142 @@
end'); %7D);%0A%7D);%0A%0A
+gulp.task('watch', function() %7B%0A gulp.watch(%5BsourceFilesGlobString, testFilesGlobString%5D, %5B'default'%5D);%0A%7D);%0A%0A
gulp.task('defau
|
59ad47aa54b15a420efea1b2bbc0f44a2e5e5b3e
|
Add personal areas to prevent merge conflicts.
|
gulpfile.js
|
gulpfile.js
|
var plugins = require('gulp-load-plugins')({
lazy: true
});
////////// TASKS ////////////
/**
* Prints out the list of available tasks.
*/
gulp.task('default', plugins.taskListing);
/////// ACCESSORY FUNCTIONS ////////
|
JavaScript
| 0 |
@@ -185,16 +185,116 @@
ing);%0A%0A%0A
+////// igonzalez tasks /////////////%0Agulp.task('analyze');%0A%0A////// fjfernandez tasks /////////////%0A%0A
%0A///////
|
9dab177626691c6f1f7f74863829f86fab1391eb
|
Update xc/yc parsing.
|
src/parsers/encode/adjust-spatial.js
|
src/parsers/encode/adjust-spatial.js
|
import {toSet} from 'vega-util';
var Skip = toSet(['rule']),
Swap = toSet(['group', 'image', 'rect'])
export default function(encode, marktype) {
var code = '';
if (Skip[marktype]) return code;
if (encode.x2) {
if (encode.x) {
if (Swap[marktype]) {
code += 'if(o.x>o.x2)$=o.x,o.x=o.x2,o.x2=$;';
}
code += 'o.width=o.x2-o.x;';
} else if (encode.width) {
code += 'o.x=o.x2-o.width;';
} else {
code += 'o.x=o.x2;';
}
}
if (encode.xc) {
if (encode.width) {
code += 'o.x=o.xc-o.width/2;';
} else {
code += 'o.x=o.xc;';
}
}
if (encode.y2) {
if (encode.y) {
if (Swap[marktype]) {
code += 'if(o.y>o.y2)$=o.y,o.y=o.y2,o.y2=$;';
}
code += 'o.height=o.y2-o.y;';
} else if (encode.height) {
code += 'o.y=o.y2-o.height;';
} else {
code += 'o.y=o.y2;';
}
}
if (encode.yc) {
if (encode.height) {
code += 'o.y=o.yc-o.height/2;';
} else {
code += 'o.y=o.yc;';
}
}
return code;
}
|
JavaScript
| 0 |
@@ -503,34 +503,8 @@
) %7B%0A
- if (encode.width) %7B%0A
@@ -525,67 +525,26 @@
.xc-
+(
o.width
+%7C%7C0)
/2;';%0A
- %7D else %7B%0A code += 'o.x=o.xc;';%0A %7D%0A
%7D%0A
@@ -851,35 +851,8 @@
) %7B%0A
- if (encode.height) %7B%0A
@@ -869,24 +869,25 @@
.y=o.yc-
+(
o.height
/2;';%0A
@@ -882,60 +882,18 @@
ight
+%7C%7C0)
/2;';%0A
- %7D else %7B%0A code += 'o.y=o.yc;';%0A %7D%0A
%7D%0A
|
989952c33162d40f7e7dcf0da5c1caa639136ee0
|
Update streetview.js
|
js/streetview.js
|
js/streetview.js
|
$(document).ready(function() {
function loadData() {
var $body = $('body');
var address = $('#input').val();
var streetViewUrl = 'https://maps.googleapis.com/maps/api/streetview?size=870x490&location=' + address + '&key=AIzaSyBc63fHmkGW4jWBUGgzHFVoQA_sTxW3TfM';
var myPic = "<img class="bgimg" alt="cant load the image" src=' + streetViewUrl + '>";
$('.top').css('background-image', 'url(' + streetViewUrl + ')');
}
$('form').submit(loadData);
}); //end ready
|
JavaScript
| 0.000001 |
@@ -135,17 +135,17 @@
ewUrl =
-'
+%22
https://
@@ -265,17 +265,17 @@
sTxW3TfM
-'
+%22
;%0D%0A%09%0D%0A%09v
|
2697746a0f9dc9d054be647bf923a64b7f163827
|
Simplify logic
|
src/js/components/notification.js
|
src/js/components/notification.js
|
var React = require('react');
var remote = window.require('remote');
var shell = remote.require('shell');
var Actions = require('../actions/actions');
var apiRequests = require('../utils/api-requests');
var SettingsStore = require('../stores/settings');
var NotificationItem = React.createClass({
getInitialState: function () {
return {
isRead: this.props.isRead
};
},
componentWillReceiveProps: function (nextProps) {
this.setState({
isRead: nextProps.isRead
});
},
pressTitle: function () {
var markOnClick = SettingsStore.getSettings().markOnClick;
if (markOnClick) {
this.openBrowser();
this.markAsRead();
} else {
this.openBrowser();
}
},
openBrowser: function () {
var url = this.props.notification.subject.url.replace('api.github.com/repos', 'www.github.com');
if (url.indexOf('/pulls/') != -1) {
url = url.replace('/pulls/', '/pull/');
}
shell.openExternal(url);
},
markAsRead: function () {
var self = this;
if (this.state.read) { return; }
apiRequests
.patchAuth('https://api.github.com/notifications/threads/' + this.props.notification.id)
.end(function (err, response) {
if (response && response.ok) {
// Notification Read
self.setState({
isRead: true
});
Actions.removeNotification(self.props.notification);
} else {
// Error - Show messages.
// Show appropriate message
self.setState({
isRead: false
});
}
});
},
render: function () {
var typeIconClass;
if (this.props.notification.subject.type == 'Issue') {
typeIconClass = 'octicon octicon-issue-opened';
} else if (this.props.notification.subject.type == 'PullRequest') {
typeIconClass = 'octicon octicon-git-pull-request';
} else if (this.props.notification.subject.type == 'Commit') {
typeIconClass = 'octicon octicon-git-commit';
} else {
typeIconClass = 'octicon octicon-question';
}
return (
<div className={this.state.isRead ? 'row notification read' : 'row notification'}>
<div className='col-xs-1'><span className={typeIconClass} /></div>
<div className='col-xs-10 subject' onClick={this.pressTitle}>
{this.props.notification.subject.title}
</div>
<div className='col-xs-1 check-wrapper'>
<span title="Mark as Read" className='octicon octicon-check' onClick={this.markAsRead} />
</div>
</div>
);
}
});
module.exports = NotificationItem;
|
JavaScript
| 0.033914 |
@@ -596,33 +596,8 @@
ck;%0A
- if (markOnClick) %7B%0A
@@ -624,39 +624,29 @@
+%0A
-this.markAsRead();%0A %7D else
+ if (markOnClick)
%7B%0A
@@ -651,35 +651,34 @@
%0A this.
-openBrowser
+markAsRead
();%0A %7D%0A
|
078accad1a826f1e5259f69ab983da251b31e6a6
|
fix bluebird promise warning about return value
|
src/kite/handleIncomingMessage.js
|
src/kite/handleIncomingMessage.js
|
import parse from 'try-json-parse'
import handleAuth from './auth'
import KiteError from './error'
import { Event } from '../constants'
export default function handleIncomingMessage(proto, message) {
this.emit(Event.debug, `Receiving: ${message}`)
const req = parse(message)
if (req == null) {
this.emit(Event.warning, new KiteError(`Invalid payload! (${message})`))
return
}
if (!isKiteReq(req)) {
this.emit(Event.debug, 'Handling a normal dnode message')
return proto.handle(req)
}
const { links, method, callbacks } = req
const {
withArgs = [],
authentication: auth,
responseCallback,
} = parseKiteReq(req)
this.emit(Event.debug, 'Authenticating request')
return handleAuth(this, method, auth, this.key)
.then(token => {
this.emit(Event.debug, 'Authentication passed')
// set this as the current token for the duration of the synchronous
// method call.
// NOTE: this mechanism may be changed at some point in the future.
this.currentToken = token
proto.handle(
toProtoReq({
method,
withArgs,
responseCallback,
links,
callbacks,
})
)
this.currentToken = null
})
.catch(err => {
this.emit(Event.debug, 'Authentication failed', err)
return proto.handle({
method: 'kite.echo',
arguments: [err, responseCallback],
links,
callbacks: mungeCallbacks(callbacks, 1),
})
})
}
const isKiteReq = req =>
req.arguments.length &&
req.arguments[0] &&
req.arguments[0].responseCallback &&
req.arguments[0].withArgs
const parseKiteReq = req => req.arguments[0]
const isResponseCallback = callback =>
Array.isArray(callback) && callback.join('.') === '0.responseCallback'
const mungeCallbacks = (callbacks, n) => {
// FIXME: this is an ugly hack; there must be a better way to implement it:
for (let key of Object.keys(callbacks || {})) {
const callback = callbacks[key]
if (isResponseCallback(callback)) {
callbacks[key] = [n]
}
if (callback[1] === 'withArgs') {
// since we're rewriting the protocol for the withArgs case,
// we need to remove everything up to withArgs
callbacks[key] = callback.slice(2)
}
}
return callbacks
}
const toProtoReq = ({
method,
withArgs,
responseCallback,
links,
callbacks,
}) => {
if (!Array.isArray(withArgs)) {
withArgs = [withArgs]
}
mungeCallbacks(callbacks, withArgs.length)
return {
method,
arguments: [...Array.from(withArgs), responseCallback],
links,
callbacks,
}
}
|
JavaScript
| 0.000001 |
@@ -1233,16 +1233,34 @@
= null%0A
+ return null%0A
%7D)%0A
|
9bd86dbd981c2954378ad8caac18d6a0e711a727
|
Remove PNLResult export
|
src/transactions/index.js
|
src/transactions/index.js
|
export { default as Transaction } from './Transaction/transaction.js'
export { default as Position } from './Positions/position.js'
export { default as PNLResult } from './PNLResult/PNLResult.js'
export { default as CashTransaction } from './Transaction/cashTransaction.js'
export { default as PositionPNL } from './PostionPNL/PositionPNL'
export { default as TransactionPNL } from './TransactionPNL/TransactionPNL'
|
JavaScript
| 0 |
@@ -129,72 +129,8 @@
js'%0A
-export %7B default as PNLResult %7D from './PNLResult/PNLResult.js'%0A
expo
|
f17b60c81a58abb1ed1818ed1fd01ae4c7795efd
|
Copy font-awesome font files assets
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglifyjs');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');
var config = {
bowerDir: './bower_components',
publicDir: './assets'
};
gulp.task('css', function() {
return gulp.src('css/style.scss')
.pipe(sourcemaps.init())
.pipe(sass({
outputStyle: 'compressed',
includePaths: [
config.bowerDir + '/bootstrap-sass/assets/stylesheets',
config.bowerDir + '/font-awsome/scss'
]
}))
.pipe(sourcemaps.write())
.pipe(gulp.dest(config.publicDir + '/css'));
});
gulp.task('js', function() {
browserify({
entries: './app/main.jsx',
debug: true
})
.transform("babelify", {presets: ["es2015", "react"]})
.bundle()
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.publicDir + '/js'));
return gulp.src([
config.bowerDir + '/jquery/dist/jquery.js',
config.bowerDir + '/bootstrap-sass/assets/javascripts/bootstrap.js',
config.bowerDir + '/react/react.js',
config.bowerDir + '/react/react-dom.js'
])
.pipe(uglify('vendor.bundle.js', {
compress: false,
outSourceMap: true
}))
.pipe(gulp.dest(config.publicDir + '/js'));
});
gulp.task('fonts', function() {
return gulp.src([
config.bowerDir + '/bootstrap-sass/assets/fonts/**/*'
])
.pipe(gulp.dest(config.publicDir + '/fonts'));
});
gulp.task('default', ['css', 'js', 'fonts']);
|
JavaScript
| 0 |
@@ -1457,16 +1457,62 @@
ts/**/*'
+,%0A config.bowerDir + '/font-awsome/fonts/*'
%0A %5D)%0A
|
c77fec2308bf7d1f23ddc352d21f4f53ee911c8d
|
Improve MBR speed
|
src/image/compute/extendedPoints.js
|
src/image/compute/extendedPoints.js
|
/**
* Allows to generate an array of points for a binary image (bit depth = 1)
* The points consider the beginning and the end of each pixel
* @memberof Image
* @instance
* @return {Array<Array<number>>} - an array of [x,y] corresponding to the set pixels in the binary image
*/
export default function extendedPoints() {
this.checkProcessable('extendedPoints', {
bitDepth: [1],
});
const pixels = [];
for (let y = 0; y < this.height; y++) {
for (let x = 0; x < this.width; x++) {
if (this.getBitXY(x, y) === 1) {
pixels.push([x, y]);
if (this.getBitXY(x + 1, y) !== 1) {
pixels.push([x + 1, y]);
pixels.push([x + 1, y + 1]);
if (this.getBitXY(x, y + 1) !== 1) {
pixels.push([x, y + 1]);
}
} else {
if (this.getBitXY(x, y + 1) !== 1) {
pixels.push([x, y + 1]);
pixels.push([x + 1, y + 1]);
}
}
}
}
}
return pixels;
}
|
JavaScript
| 0.00002 |
@@ -136,16 +136,79 @@
h pixel%0A
+ * This method is only used to calculate minimalBoundRectangle%0A
* @memb
@@ -218,16 +218,16 @@
f Image%0A
-
* @inst
@@ -624,24 +624,25 @@
sh(%5Bx, y%5D);%0A
+%0A
if (
@@ -978,32 +978,32 @@
x + 1, y + 1%5D);%0A
-
%7D%0A
@@ -1003,24 +1003,299 @@
%7D%0A %7D
+%0A%0A // this small optimization allows to reduce dramatically the number of points for MBR calculation%0A while (%0A x %3C this.width - 2 &&%0A this.getBitXY(x + 1, y) === 1 &&%0A this.getBitXY(x + 2, y) === 1%0A ) %7B%0A x++;%0A %7D
%0A %7D%0A
|
93eb7a713f65cd11ff989d5fb42caa570e36245b
|
update gulpfile
|
gulpfile.js
|
gulpfile.js
|
// gulpfile.js
'use strict';
// ----------------------------------
// available tasks:
// 'gulp'
// 'gulp clean'
// clean:cache
// 'gulp bower'
// bower:clean - bower:scss - bower:js
// 'gulp sass'
// sass:compile - sass:doc - sass:minifycss
// 'gulp nunjucks'
// nunjucks:render - nunjucks:inject
// 'gulp serve'
// 'gulp watch'
// ----------------------------------
// plugins:
// gulp, run-sequence, gulp-util, gulp-plumber
// gulp-load-plugins, gulp-load-subtasks
// gulp-nunjucks-render, gulp-changed,
// gulp-sass, gulp-sourcemaps, browser-sync
// gulp-prettify, gulp-newer, main-bower-files
// gulp-flatten, del, gulp-inject, gulp-cached
// gulp-autoprefixer, sassdoc, gulp-minify-css
// gulp-rename, lazypipe
// ----------------------------------
// main gulp plugins
var gulp = require('gulp'),
path = require('./gulp/paths.js'),
config = require('./gulp/config.js'),
sequence = require('run-sequence'),
$ = require('gulp-load-plugins')({
// used for all plugins type not just with gulp-*
pattern: '*'
});
// require all tasks : gulp-load-subtasks
$.loadSubtasks('./gulp/tasks/**/*.js', $, path, config);
// common tasks
gulp.task('default', function(cb) {
sequence(
// config.task.clean,
// config.task.clean + ':cache',
config.task.bower,
[
config.task.sass,
// config.task.sass + ':doc',
],
config.task.nunjucks,
config.task.browserSync,
'watch',
cb
)
});
// build tasks
gulp.task(config.task.build, function(cb) {
sequence(
// config.task.build + ':css',
// config.task.build + ':js',
config.task.build + ':html',
cb
)
});
|
JavaScript
| 0.000001 |
@@ -382,16 +382,35 @@
watch'%0A
+// 'gulp build'%0A
// -----
|
b942eac452366ca6d179d009fd37cddc22938bcb
|
fix linter error no-unused-vars
|
webapp/src/components/orthology/orthologyFilteredTable.js
|
webapp/src/components/orthology/orthologyFilteredTable.js
|
/* eslint-disable react/no-set-state */
/* set-state has to be used
because the state of the component is not shared
with the rest of the application
*/
import React, { Component, PropTypes } from 'react';
import OrthologyTable from './orthologyTable';
const caseInsensitiveCompare = (stringA, stringB) => {
const stringALowerCase = stringA.toLowerCase();
const stringBLowerCase = stringB.toLowerCase();
if (stringALowerCase < stringBLowerCase) {
return -1;
} else if (stringALowerCase > stringBLowerCase) {
return 1;
} else {
return 0;
}
};
const DEFAULT_FILTERS = {
filterScoreGreaterThan: 0,
filterMethod: null,
filterBest: false,
filterReverseBest: false,
filterSpecies: null,
filterConfidence: true
};
class OrthologyFilteredTable extends Component {
constructor(props) {
super(props);
this.state = DEFAULT_FILTERS;
}
isHighConfidence(dat) {
return (
dat.predictionMethodsMatched === 'ZFIN' ||
dat.predictionMethodsMatched === 'HGNC' ||
dat.predictionMethodsMatched.length > 2 ||
(dat.predictionMethodsMatched.length === 2 && dat.isBestScore && dat.isBestRevScore)
);
}
filterCallback(dat) {
const meetMethodFilter = this.state.filterMethod ?
dat.predictionMethodsMatched.indexOf(this.state.filterMethod) > -1 :
true;
return (
meetMethodFilter &&
dat.predictionMethodsMatched.length > this.state.filterScoreGreaterThan &&
(this.state.filterBest ? dat.isBestScore : true) &&
(this.state.filterReverseBest ? dat.isBestRevScore : true) &&
(this.state.filterSpecies ? dat.gene2SpeciesName === this.state.filterSpecies : true) &&
(this.state.filterConfidence ? this.isHighConfidence(dat) : true)
);
}
updateFilterMethod(event) {
this.setState({
filterMethod: event.target.value === 'all' ? null : event.target.value
});
}
updateBestScoreFilter(event) {
this.setState({
filterBest: event.target.checked
});
}
updateBestReverseScoreFilter(event) {
this.setState({
filterReverseBest: event.target.checked
});
}
updateFilterScoreGreaterThan(event) {
this.setState({
filterScoreGreaterThan: event.target.value
});
}
updateFilterSpecies(event) {
this.setState({
filterSpecies: event.target.value === 'all' ? null : event.target.value
});
}
updateFilterConfidence(event) {
this.setState({
filterConfidence: event.target.checked
});
}
resetFilters(event) {
this.setState(DEFAULT_FILTERS);
}
render() {
const filteredData = this.props.data.filter((dat) => this.filterCallback(dat));
const all_methods = this.props.data[0].predictionMethodsMatched.concat(
this.props.data[0].predictionMethodsNotCalled,
this.props.data[0].predictionMethodsNotMatched
).sort(caseInsensitiveCompare);
const labelStyle = {
margin: '0 1em 1em 0',
};
const inputStyle = {
margin: '0 0.5em'
};
return (
<div>
<div
className="card"
style={{
padding: '1em'
}}
>
<label style={labelStyle}>
Best Score Only:
<input
checked={this.state.filterBest}
onChange={(event) => this.updateBestScoreFilter(event)}
style={inputStyle}
type="checkbox"
/>
</label>
<label style={labelStyle}>
Best Reverse Score Only:
<input
checked={this.state.filterReverseBest}
onChange={(event) => this.updateBestReverseScoreFilter(event)}
style={inputStyle}
type="checkbox"
/>
</label>
<label style={labelStyle}>
Exclude low confidence matches:
<input
checked={this.state.filterConfidence}
onChange={(event) => this.updateFilterConfidence(event)}
style={inputStyle}
type="checkbox"
/>
</label>
<label style={labelStyle}>
Count:
<select
onChange={(event) => this.updateFilterScoreGreaterThan(event)}
style={inputStyle}
value={this.state.filterScoreGreaterThan}
>
<option value={0}>> 0</option>
{
all_methods.map((method, index) => {
const scoreGreaterThanValue = index + 1;
return <option key={scoreGreaterThanValue} value={scoreGreaterThanValue}>> {scoreGreaterThanValue}</option>;
})
}
</select>
</label>
<label style={labelStyle}>
Species:
<select
onChange={(event) => this.updateFilterSpecies(event)}
style={inputStyle}
value={this.state.filterSpecies || 'all'}
>
<option value="all">All</option>
{
this.props.data.reduce((all_species, dat) => {
if (all_species.indexOf(dat.gene2SpeciesName) === -1) {
return all_species.concat([dat.gene2SpeciesName]);
} else {
return all_species;
}
}, []).map((species) => (
<option key={species} value={species}>{species}</option>
))
}
</select>
</label>
<label>
Methods:
<select
onChange={(event) => this.updateFilterMethod(event)}
style={inputStyle}
value={this.state.filterMethod || 'all'}
>
<option value="all">All</option>
{
all_methods.map((method) => (
<option key={method} value={method}>{method}</option>
))
}
</select>
</label>
<br/>
<button
className="btn btn-primary"
onClick={(event) => this.resetFilters(event)}
>Reset filters</button>
</div>
{
filteredData.length > 0 ?
<OrthologyTable data={filteredData} /> :
<i className="text-muted">No ortholog matching your filter. Please try a less stringent filter.</i>
}
</div>
);
}
}
OrthologyFilteredTable.propTypes = {
// filterScoreGreaterThan: PropTypes.number,
// filterMethods: PropTypes.string,
// filterBest: PropTypes.bool,
// filterReverseBest: PropTypes.bool
data: PropTypes.arrayOf(
PropTypes.shape({
gene2AgrPrimaryId: PropTypes.string,
gene2Symbol: PropTypes.string,
gene2Species: PropTypes.number,
gene2SpeciesName: PropTypes.string,
predictionMethodsMatched: PropTypes.arrayOf(PropTypes.string),
predictionMethodsNotCalled: PropTypes.arrayOf(PropTypes.string),
predictionMethodsNotMatched: PropTypes.arrayOf(PropTypes.string),
isBestScore: PropTypes.bool,
isBestRevScore: PropTypes.bool,
})
)
};
export default OrthologyFilteredTable;
|
JavaScript
| 0.000018 |
@@ -2507,21 +2507,16 @@
Filters(
-event
) %7B%0A
@@ -6071,21 +6071,16 @@
Click=%7B(
-event
) =%3E thi
@@ -6094,21 +6094,16 @@
Filters(
-event
)%7D%0A
|
8af01d9d1f233dbb92d1198fe79a91fd29aad9e0
|
Set activeFile to null to differentiate not found. Add method for finding files by fileID.
|
website/app/application/services/project-files-service.js
|
website/app/application/services/project-files-service.js
|
/*
* The Projects service acts as a cache for projects and their files. It provides routines
* for manipulating the selected flag in the list of files in a project, as well as channel
* that controllers, directives and services can set to receive events on.
*/
Application.Services.factory('projectFiles', ['pubsub', projectFilesService]);
function projectFilesService(pubsub) {
var service = {
model: {
projects: {}
},
activeByProject: {},
activeFile: {},
activeDirectory: {},
isActive: function (projectID) {
if (!(projectID in service.activeByProject)) {
service.activeByProject[projectID] = false;
}
return service.activeByProject[projectID];
},
/*
* Clears the current set of projects.
*/
clear: function () {
service.model.projects = {};
},
// Sets up a list of files by mediatype. The type "all" is used to
// list all files in a project.
loadByMediaType: function (project) {
service.model.projects[project.id].byMediaType = {};
var byMediaType = service.model.projects[project.id].byMediaType;
byMediaType.all = [];
for (var mediatype in project.mediatypes) {
byMediaType[mediatype] = [];
}
byMediaType.unknown = [];
var treeModel = new TreeModel(),
root = treeModel.parse(service.model.projects[project.id].dir);
root.walk({strategy: 'pre'}, function(node) {
if (node.model.type !== "datadir") {
node.model.showDetails = false;
byMediaType.all.push(node.model);
if (node.model.mediatype === "") {
byMediaType.unknown.push(node.model);
} else if (!(node.model.mediatype in byMediaType)) {
byMediaType[node.model.mediatype] = [];
byMediaType[node.model.mediatype] = [];
byMediaType[node.model.mediatype].push(node.model);
} else {
byMediaType[node.model.mediatype].push(node.model);
}
}
});
},
setActiveFile: function (what) {
service.activeFile = what;
pubsub.send('activeFile.change');
},
getActiveFile: function () {
return service.activeFile;
},
setActiveDirectory: function (what) {
service.activeDirectory = what;
},
getActiveDirectory: function () {
return service.activeDirectory;
}
};
return service;
}
|
JavaScript
| 0 |
@@ -498,18 +498,20 @@
veFile:
-%7B%7D
+null
,%0A
@@ -2321,32 +2321,446 @@
%7D);%0A %7D,%0A%0A
+ findFileByID: function(projectID, fileID) %7B%0A var f = null;%0A var treeModel = new TreeModel(),%0A root = treeModel.parse(service.model.projects%5BprojectID%5D.dir);%0A root.walk(%7Bstrategy: 'pre'%7D, function(node) %7B%0A if (node.model.df_id == fileID) %7B%0A f = node.model;%0A %7D%0A %7D);%0A return f;%0A %7D,%0A%0A
setActiv
|
92c76077698948bd56406fddc53ad0509bf04eac
|
Write specific timings from loading benchmark.
|
benchmark/load.js
|
benchmark/load.js
|
#!/usr/bin/env node
/*
___ usage: en_US ___
usage: node load.js
All around tests for benchmarking Locket.
___ usage ___
*/
var advance = require('advance')
var splice = require('splice')
var cadence = require('cadence/redux')
var path = require('path')
var crypto = require('crypto')
var seedrandom = require('seedrandom')
var rimraf = require('rimraf')
var mkdirp = require('mkdirp')
var Strata = require('..')
var random = (function () {
var random = seedrandom(0)
return function (max) {
return Math.floor(random() * max)
}
})()
var runner = cadence(function (async) {
var directory = path.join(__dirname, 'tmp'), db, count = 0
var extractor = function (record) { return record.key }
var strata = new Strata({
directory: directory,
extractor: extractor,
leafSize: 256,
branchSize: 256,
writeStage: 'leaf'
})
async(function () {
rimraf(directory, async())
}, function () {
mkdirp(directory, async())
}, function () {
strata.create(async())
}, function () {
var batch = 0
var loop = async(function () {
if (batch++ == 7) return [ loop ]
var entries = []
var type, sha, buffer, value
for (var i = 0; i < 1024; i++) {
var value = random(1024)
sha = crypto.createHash('sha1')
buffer = new Buffer(4)
buffer.writeUInt32BE(value, 0)
sha.update(buffer)
entries.push({
key: sha.digest('hex'),
type: !! random(2) ? 'insert' : 'delete'
})
}
var iterator = advance(entries, function (record, callback) {
callback(null, record, record.key)
})
splice(function (incoming, existing) {
return incoming.record.type
}, strata, iterator, async())
})()
}, function () {
strata.close(async())
}, function () {
strata.open(async())
}, function () {
var records = []
async(function () {
strata.iterator(strata.left, async())
}, function (cursor) {
var loop = async(function (more) {
if (!more) {
async(function () {
cursor.unlock(async())
}, function () {
return [ loop, records ]
})
} else {
for (var i = cursor.offset, I = cursor.length; i < I; i++) {
records.push(cursor.get(i).record)
}
cursor.next(async())
}
})(true)
}, function () {
console.log('count', records.length)
strata.close(async())
})
})
})
require('arguable/executable')(module, cadence(function (async, options) {
runner(options, async())
return
AsyncProfile.profile(function () {
runner(options, function (error) { if (error) throw error })
})
}))
|
JavaScript
| 0 |
@@ -596,24 +596,54 @@
n (async) %7B%0A
+ var start, insert, gather%0A
var dire
@@ -689,24 +689,24 @@
, count = 0%0A
-
var extr
@@ -920,24 +920,558 @@
leaf'%0A %7D)
+%0A%0A var batches = %5B%5D%0A for (var j = 0; j %3C 7; j++) %7B%0A var entries = %5B%5D%0A var type, sha, buffer, value%0A for (var i = 0; i %3C 1024; i++) %7B%0A var value = random(1024)%0A sha = crypto.createHash('sha1')%0A buffer = new Buffer(4)%0A buffer.writeUInt32BE(value, 0)%0A sha.update(buffer)%0A entries.push(%7B%0A key: sha.digest('hex'),%0A type: !! random(2) ? 'insert' : 'delete'%0A %7D)%0A %7D%0A batches.push(entries)%0A %7D
%0A async(f
@@ -1587,32 +1587,59 @@
, function () %7B%0A
+ start = Date.now()%0A
strata.c
@@ -1695,28 +1695,17 @@
atch = 0
-%0A var
+,
loop =
@@ -1749,11 +1749,10 @@
atch
-++
+=
== 7
@@ -1789,528 +1789,41 @@
var
-entries = %5B%5D%0A var type, sha, buffer, value%0A for (var i = 0; i %3C 1024; i++) %7B%0A var value = random(1024)%0A sha = crypto.createHash('sha1')%0A buffer = new Buffer(4)%0A buffer.writeUInt32BE(value, 0)%0A sha.update(buffer)%0A entries.push(%7B%0A key: sha.digest('hex'),%0A type: !! random(2) ? 'insert' : 'delete'%0A %7D)%0A %7D%0A var iterator = advance(entries
+iterator = advance(batches%5Bbatch%5D
, fu
@@ -2045,32 +2045,52 @@
rator, async())%0A
+ batch++%0A
%7D)()%0A
@@ -2150,32 +2150,95 @@
, function () %7B%0A
+ insert = Date.now() - start%0A start = Date.now()%0A
strata.o
@@ -2985,77 +2985,162 @@
-console.log('count', records.length)%0A strata.close(async()
+strata.close(async())%0A %7D, function () %7B%0A gather = Date.now() - start%0A console.log('insert: ' + insert + ', gather: ' + gather
)%0A
|
70644bf30d0de067061da9697b29e926cf4151c5
|
remove comments
|
lib/flows/sms.js
|
lib/flows/sms.js
|
var machina = require('machina')
// TODO: add timeouts
var FsmExtend = machina.Fsm.extend
// green: {
// // _onEnter is a special handler that is invoked
// // immediately as the FSM transitions into the new state
// _onEnter: function() {
// this.timer = setTimeout( function() {
// this.handle( "timeout" );
// }.bind( this ), 30000 );
// this.emit( "vehicles", { status: "GREEN" } );
// },
// // If all you need to do is transition to a new state
// // inside an input handler, you can provide the string
// // name of the state in place of the input handler function.
// timeout: "green-interruptible",
// pedestrianWaiting: function() {
// this.deferUntilTransition( "green-interruptible" );
// },
// // _onExit is a special handler that is invoked just before
// // the FSM leaves the current state and transitions to another
// _onExit: function() {
// clearTimeout( this.timer );
// }
// },
var SmsFlow = new FsmExtend({
initialize: function (options) {
this.context = options.context
},
namespace: 'smsFlow',
initialState: 'initial',
states: {
initial: {
_onEnter: function () {
this.phone = null
this.securityCode = null
this.retries = 0
},
'start': 'askForPhone'
},
askForPhone: {
_onEnter: function () {
this.phone = null
this.emit('screen', {screen: 'registerPhone'})
},
phoneNumber: function (number) {
if (!number) this.transition('restart')
this.phone = number
this.transition('waitForSendCode')
}
},
waitForSendCode: {
_onEnter: function () {
this.securityCode = null
this.emit('sendCode', {phone: this.phone})
this.emit('screen', {screen: 'waitForSendCode'})
},
badPhoneNumber: 'badPhoneNumber',
networkError: 'networkError',
securityCode: function (code) {
this.securityCode = code
this.transition('waitForCode')
}
},
waitForCode: {
_onEnter: function () {
this.emit('screen', {screen: 'registerCode'})
},
securityCode: function (code) {
if (code === this.securityCode) {
return this.transition('success')
}
this.transition('badSecurityCode')
}
},
badPhoneNumber: {
_onEnter: function () {
this.phone = null
this._setTimer()
this.emit('screen', {screen: 'badPhoneNumber'})
},
badPhoneNumberOk: 'askForPhone',
timeout: 'restart',
_onExit: this._clearTimer
},
badSecurityCode: {
_onEnter: function () {
this._setTimer()
this.retries += 1
if (this.retries > 3) {
return this.transition('maxPhoneRetries')
}
this.emit('screen', {screen: 'badSecurityCode'})
},
badSecurityCodeOk: 'waitForSendCode',
timeout: 'restart',
_onExit: this._clearTimer
},
maxPhoneRetries: {
_onEnter: function () {
this._setTimer()
this.emit('screen', {screen: 'maxPhoneRetries'})
},
maxPhoneRetriesOk: 'restart',
timeout: 'restart',
_onExit: this._clearTimer
},
networkError: {
_onEnter: function () {
this._setTimer()
this.emit('screen', {screen: 'networkError'})
},
networkErrorOk: function () {
this.transition('restart')
},
timeout: 'restart',
_onExit: this._clearTimer
},
success: {
_onEnter: function () {
this.emit('success')
this.transition('initial')
}
},
restart: {
_onEnter: function () {
this.emit('idle')
this.transition('initial')
}
}
},
_setTimer: function () {
this.timer = setTimeout(function () { this.handle('timeout') }.bind(this), 30000)
},
_clearTimer: function () { clearTimeout(this.timer) }
})
module.exports = {
SmsFlow: SmsFlow
}
|
JavaScript
| 0 |
@@ -31,31 +31,8 @@
')%0A%0A
-// TODO: add timeouts%0A%0A
var
@@ -67,1101 +67,8 @@
nd%0A%0A
- // green: %7B%0A // // _onEnter is a special handler that is invoked%0A // // immediately as the FSM transitions into the new state%0A // _onEnter: function() %7B%0A // this.timer = setTimeout( function() %7B%0A // this.handle( %22timeout%22 );%0A // %7D.bind( this ), 30000 );%0A // this.emit( %22vehicles%22, %7B status: %22GREEN%22 %7D );%0A // %7D,%0A // // If all you need to do is transition to a new state%0A // // inside an input handler, you can provide the string%0A // // name of the state in place of the input handler function.%0A // timeout: %22green-interruptible%22,%0A // pedestrianWaiting: function() %7B%0A // this.deferUntilTransition( %22green-interruptible%22 );%0A // %7D,%0A // // _onExit is a special handler that is invoked just before%0A // // the FSM leaves the current state and transitions to another%0A // _onExit: function() %7B%0A // clearTimeout( this.timer );%0A // %7D%0A // %7D,%0A%0A
var
|
33afea37f6362ce35981c08b5edeec24ddc29948
|
Update plugin syntax to new gulp-svgmin version
|
gulpfile.js
|
gulpfile.js
|
/*global exports */
const { src, dest, series, parallel, watch } = require("gulp");
const concat = require("gulp-concat");
const sass = require("gulp-sass");
const sourcemaps = require("gulp-sourcemaps");
const minifyCSS = require("gulp-csso");
const terser = require("gulp-terser-js");
const svgmin = require("gulp-svgmin");
const jsSrc = [
'./html/js/display*.js',
'./html/js/product-multilingual.js',
'./html/js/search.js'
];
const sassSrc = "./scss/**/*.scss";
const sassOptions = {
errLogToConsole: true,
outputStyle: "expanded",
includePaths: ["./node_modules/foundation-sites/scss"]
};
function icons() {
return src("*.svg", { cwd: "./icons" }).
pipe(
svgmin({
plugins: [
{ removeMetadata: true },
{ removeTitle: true },
{ removeDimensions: true },
{ addClassesToSVGElement: { className: "icon" } },
{
addAttributesToSVGElement: {
attributes: [{ "aria-hidden": "true", focusable: "false" }]
}
}
]
})
).
pipe(dest("./html/images/icons/dist"));
}
function attributesIcons() {
return src("*.svg", { cwd: "./html/images/attributes/src" }).
pipe(
svgmin({
plugins: [
{ removeMetadata: true },
{ removeTitle: true },
]
})
).
pipe(dest("./html/images/attributes"));
}
function css() {
return src(sassSrc).
pipe(sourcemaps.init()).
pipe(sass(sassOptions).on("error", sass.logError)).
pipe(minifyCSS()).
pipe(sourcemaps.write(".")).
pipe(dest("./html/css/dist"));
}
function copyJs() {
return src(
[
"./node_modules/@webcomponents/**/webcomponentsjs/**/*.js",
"./node_modules/foundation-sites/js/vendor/*.js",
"./node_modules/foundation-sites/js/foundation.js",
"./node_modules/papaparse/papaparse.js",
"./node_modules/osmtogeojson/osmtogeojson.js",
"./node_modules/leaflet/dist/leaflet.js",
"./node_modules/leaflet.markercluster/dist/leaflet.markercluster.js",
"./node_modules/blueimp-tmpl/js/tmpl.js",
"./node_modules/blueimp-load-image/js/load-image.all.min.js",
"./node_modules/blueimp-canvas-to-blob/js/canvas-to-blob.js",
"./node_modules/blueimp-file-upload/js/*.js",
"./node_modules/@yaireo/tagify/dist/tagify.min.js",
"./node_modules/cropperjs/dist/cropper.js",
"./node_modules/jquery-cropper/dist/jquery-cropper.js",
"./node_modules/jquery-form/src/jquery.form.js",
"./node_modules/highcharts/highcharts.js",
"./node_modules/jvectormap-next/jquery-jvectormap.js",
"./node_modules/jvectormap-content/world-mill.js",
"./node_modules/select2/dist/js/select2.min.js"
]).
pipe(sourcemaps.init()).
pipe(terser()).
pipe(sourcemaps.write(".")).
pipe(dest("./html/js/dist"));
}
function buildJs() {
return src(jsSrc).
pipe(sourcemaps.init()).
pipe(terser()).
pipe(sourcemaps.write(".")).
pipe(dest("./html/js/dist"));
}
function buildjQueryUi() {
return src([
'./node_modules/jquery-ui/ui/version.js',
'./node_modules/jquery-ui/ui/widget.js',
'./node_modules/jquery-ui/ui/position.js',
'./node_modules/jquery-ui/ui/keycode.js',
'./node_modules/jquery-ui/ui/unique-id.js',
'./node_modules/jquery-ui/ui/safe-active-element.js',
'./node_modules/jquery-ui/ui/widgets/autocomplete.js',
'./node_modules/jquery-ui/ui/widgets/menu.js'
]).
pipe(sourcemaps.init()).
pipe(terser()).
pipe(concat('jquery-ui.js')).
pipe(sourcemaps.write(".")).
pipe(dest('./html/js/dist'));
}
function jQueryUiThemes() {
return src([
'./node_modules/jquery-ui/themes/base/core.css',
'./node_modules/jquery-ui/themes/base/autocomplete.css',
'./node_modules/jquery-ui/themes/base/menu.css',
'./node_modules/jquery-ui/themes/base/theme.css',
]).
pipe(sourcemaps.init()).
pipe(minifyCSS()).
pipe(concat('jquery-ui.css')).
pipe(sourcemaps.write(".")).
pipe(dest('./html/css/dist/jqueryui/themes/base'));
}
function copyCss() {
return src([
"./node_modules/leaflet/dist/leaflet.css",
"./node_modules/leaflet.markercluster/dist/MarkerCluster.css",
"./node_modules/leaflet.markercluster/dist/MarkerCluster.Default.css",
"./node_modules/@yaireo/tagify/dist/tagify.css",
"./html/css/product-multilingual.css",
"./node_modules/cropperjs/dist/cropper.css",
"./node_modules/jvectormap-next/jquery-jvectormap.css",
"./node_modules/select2/dist/css/select2.min.css"
]).
pipe(sourcemaps.init()).
pipe(minifyCSS()).
pipe(sourcemaps.write(".")).
pipe(dest("./html/css/dist"));
}
function copyImages() {
return src(["./node_modules/leaflet/dist/**/*.png"]).
pipe(dest("./html/css/dist"));
}
exports.copyJs = copyJs;
exports.buildJs = buildJs;
exports.css = css;
exports.icons = icons;
exports.attributesIcons = attributesIcons;
exports.default = parallel(copyJs, buildJs, buildjQueryUi, copyCss, copyImages, jQueryUiThemes, series(icons, attributesIcons, css));
exports.watch = function () {
watch(jsSrc, { delay: 500 }, buildJs);
watch(sassSrc, { delay: 500 }, css);
};
|
JavaScript
| 0 |
@@ -720,98 +720,73 @@
%7B
- removeMetadata: true %7D,%0A %7B removeTitle: true %7D,%0A %7B removeDimensions
+%0A name: %22addClassesToSVGElement%22,%0A active
: true
- %7D
,%0A
@@ -797,32 +797,14 @@
-%7B addClassesToSVGElement
+params
: %7B
@@ -822,22 +822,28 @@
%22icon%22 %7D
+%0A
%7D,%0A
-
@@ -854,18 +854,23 @@
-
+name: %22
addAttri
@@ -886,19 +886,42 @@
GElement
-: %7B
+%22,%0A active: true,
%0A
@@ -923,19 +923,25 @@
-
+params: %7B
attribu
@@ -996,25 +996,11 @@
%22 %7D%5D
-%0A
%7D%0A
-
@@ -1171,32 +1171,32 @@
%22 %7D).%0A pipe(%0A
+
svgmin(%7B%0A
@@ -1196,107 +1196,8 @@
min(
-%7B%0A plugins: %5B%0A %7B removeMetadata: true %7D,%0A %7B removeTitle: true %7D,%0A %5D%0A %7D
)%0A
|
9f44c67ffe1d78ef11a99936e6b593e4c5f6b25b
|
fix example
|
config.example.js
|
config.example.js
|
var config = {
host : "chat.freenode.net",
nick : "repltbot",
channel : "#test5566",
pingTimeout : 600 * 1000,
identifier : "*",
floodProtection : 1000,
saveFolder : "save",
saveName : "cm.json",
init : function (commandManager, helper) {
var path = require("path");
var chatLogPath = 'chatlog.json';
var regexConfigPath = 'regex.json';
var titleParserConfigPath = 'titleparse.json';
var mailboxPath = 'mailbox.json';
var CommandSay = require('./lib/commands/commandsay.js')
var CommandRainbow = require('./lib/commands/commandrainbow.js')
var CommandRainbow2 = require('./lib/commands/commandrainbow2.js')
var CommandLog = require('./lib/commands/commandlog.js')
var CommandUptime = require('./lib/commands/commanduptime.js')
var CommandPass = require('./lib/commands/commandpass.js')
var CommandLookup = require('./lib/commands/commandnslookup.js')
var CommandNotifyAll = require('./lib/commands/commandnotifyall.js')
var CommandRand = require('./lib/commands/commandrand.js')
var CommandReply = require('./lib/commands/commandreply.js')
var CommandFortune = require('./lib/commands/fortune')
var CommandRegex = require('./lib/commands/commandregex.js')
var CommandPython = require('./lib/commands/commandpy.js')
var CommandMorse = require('./lib/commands/commandmorse.js')
var CommandMe = require('./lib/commands/commandme.js')
var CommandMail = require('./lib/commands/commandmail.js')
var CommandMcStatus = require('./lib/commands/commandmcstatus.js');
commandManager.register ("say", new CommandSay, []);
commandManager.register ("rainbow", new CommandRainbow, []);
commandManager.register ("rainbow2", new CommandRainbow2, []);
commandManager.register ("log", new CommandLog(helper.createStorage(chatLogPath)), []);
commandManager.register ("uptime", new CommandUptime(), []);
commandManager.register ("pass", new CommandPass(), []);
commandManager.register ("notifyall", new CommandNotifyAll(), ['na']);
commandManager.register ("lookup", new CommandLookup(), []);
commandManager.register ("rand", new CommandRand(), []);
commandManager.register ("reply", new CommandReply(), []);
commandManager.register ("fortune", new CommandFortune(), []);
commandManager.register ("regex", new CommandRegex(helper.createStorage(regexConfigPath)), []);
commandManager.register ("python", new CommandPython(), ['py']);
commandManager.register ("morse", new CommandMorse(), []);
commandManager.register ("me", new CommandMe(), []);
commandManager.register ("mail", new CommandMail(helper.createStorage(mailboxPath)), []);
commandManager.register ("mcstatus", new CommandMcStatus(), ['mc']);
helper.safeLoad(function(){
var CommandTitle = require('./lib/commands/titleparser')
commandManager.register ("title", new CommandTitle(helper.createStorage(titleParserConfigPath)), []);
}, "title");
helper.safeLoad(function(){
var CommandTrace = require('./lib/commands/commandtrace.js')
commandManager.register ("trace", new CommandTrace(), ['t']);
}, "trace");
helper.safeLoad(function(){
var CommandPing = require('./lib/commands/commandping.js')
commandManager.register ("ping", new CommandPing(), ['p']);
}, "ping");
helper.safeLoad(function(){
var CommandFindFastestServer = require('./lib/commands/commandfindfastestserver.js')
commandManager.register ("findfastestserver", new CommandFindFastestServer(), ['ffs']);
}, "findFastestServer");
}
}
module.exports = config
|
JavaScript
| 0.0001 |
@@ -71,16 +71,17 @@
annel :
+%5B
%22#test55
@@ -84,16 +84,30 @@
st5566%22,
+ %22#text5577%22%5D,
%0A pingT
|
30d1c6c078785d6219d01cbd810a6afa64d36de0
|
fix remove return #gulpfile
|
gulpfile.js
|
gulpfile.js
|
var gulp = require("gulp");
var connect = require("gulp-connect");
var path = {
root: "public/",
html: "public/**/*.html",
md: "src/**/*.md"
};
gulp.task("build", function(){
return gulp.src(path["md"])
.pipe( require("gulp-plumber")() )
.pipe( require("gulp-front-matter")({remove: true}) )
.pipe( require("gulp-textlint")({formatterName: "pretty-error"}) )
.pipe( require("gulp-markdown")() )
.pipe( require("gulp-layout")(function(file){
var params = file.frontMatter;
var now = new Date;
params["year"] = now.getFullYear();
params["month"] = now.getMonth() + 1;
params["day"] = now.getDate();
return params;
}) )
.pipe( gulp.dest(path["root"]) );
});
gulp.task("html", function(){
return gulp.src(path["html"])
.pipe( connect.reload() )
});
gulp.task("livereload", function(){
connect.server({
port: 8000,
root: path["root"],
livereload: true
});
gulp.watch(path["md"],["build"]);
gulp.watch(path["html"],["html"]);
});
|
JavaScript
| 0.000003 |
@@ -170,39 +170,32 @@
, function()%7B%0A
-return
gulp.src(path%5B%22m
@@ -748,23 +748,16 @@
on()%7B%0A
-return
gulp.src
|
51538d9ec0ef2c14294fdf113e9780324b99512f
|
Put eslint no-process-exit back.
|
gulpfile.js
|
gulpfile.js
|
/* eslint-env node */
'use strict'
var bg = require('gulp-bg')
var eslint = require('gulp-eslint')
var gulp = require('gulp')
var harmonize = require('harmonize')
var jest = require('jest-cli')
var makeWebpackConfig = require('./webpack/makeconfig')
var runSequence = require('run-sequence')
var webpackBuild = require('./webpack/build')
var webpackDevServer = require('./webpack/devserver')
var yargs = require('yargs')
// Enables node's --harmony flag programmatically for jest.
harmonize()
var args = yargs
.alias('p', 'production')
.argv
gulp.task('env', function() {
process.env.NODE_ENV = args.production ? 'production' : 'development'
})
gulp.task('build-webpack-production', webpackBuild(makeWebpackConfig(false)))
gulp.task('build-webpack-dev', webpackDevServer(makeWebpackConfig(true)))
gulp.task('build-webpack', [args.production ? 'build-webpack-production' : 'build-webpack-dev'])
gulp.task('build', ['build-webpack'])
gulp.task('eslint', function() {
return gulp.src([
'gulpfile.js',
'src/**/*.{js,jsx}',
'webpack/*.js'
])
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failOnError())
})
gulp.task('jest', function(done) {
var rootDir = './src'
jest.runCLI({config: {
'rootDir': rootDir,
'scriptPreprocessor': '../node_modules/babel-jest',
'testFileExtensions': ['es6', 'js'],
'moduleFileExtensions': ['js', 'json', 'es6']
}}, rootDir, function(success) {
done(success ? null : 'jest failed')
process.on('exit', function() {
process.exit(success ? 0 : 1)
})
})
})
gulp.task('test', function(done) {
// Run test tasks serially, because it doesn't make sense to build when tests
// are not passing, and it doesn't make sense to run tests, if lint has failed.
// Gulp deps aren't helpful, because we want to run tasks without deps as well.
runSequence('eslint', 'jest', 'build-webpack-production', done)
})
gulp.task('server', ['env', 'build'], bg('node', 'src/server'))
gulp.task('default', ['server'])
|
JavaScript
| 0 |
@@ -1436,24 +1436,59 @@
(success) %7B%0A
+ /* eslint no-process-exit:0 */%0A
done(suc
|
72ea4ea8fc75ba249292b4a9e006b76bf9e70823
|
disable auto open browser
|
gulpfile.js
|
gulpfile.js
|
const
gulp = require('gulp'),
plumber = require('gulp-plumber'),
rename = require('gulp-rename'),
concat = require('gulp-concat'),
imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
svgSprite = require('gulp-svg-sprite'),
less = require('gulp-less'),
postcss = require('gulp-postcss'),
autoprefixer = require('autoprefixer'),
pixrem = require('gulp-pixrem'),
sourcemaps = require('gulp-sourcemaps'),
minifycss = require('gulp-minify-css'),
uglify = require('gulp-uglify'),
jade = require('gulp-jade-php'),
browserSync = require('browser-sync');
const
localhostURL = 'praha.dev'
pathToTemplate = 'wp-content/themes/template/';
gulp.task('images', function () {
return gulp.src(pathToTemplate + 'src/images/*')
.pipe(imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))
.pipe(gulp.dest(pathToTemplate + 'dist/images'));
});
gulp.task('svg', function () {
gulp.src(pathToTemplate + 'src/svg/**/*.svg')
.pipe(svgSprite({
mode: {
symbol: {
inline: true,
sprite: 'shapes'
}
}
}))
.pipe(gulp.dest(pathToTemplate + 'dist'))
.pipe(browserSync.stream())
})
gulp.task('styles', function () {
gulp.src([pathToTemplate + 'src/styles/styles.less'])
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}
}))
.pipe(less())
.pipe(sourcemaps.init())
.pipe(pixrem())
.pipe(postcss([autoprefixer({browsers: ['last 2 versions']})]))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(pathToTemplate + 'dist/'))
.pipe(rename({suffix: '.min'}))
.pipe(minifycss())
.pipe(gulp.dest(pathToTemplate + 'dist/'))
.pipe(browserSync.stream())
});
gulp.task('scripts', function () {
return gulp.src(pathToTemplate + 'src/scripts/**/*.js')
.pipe(plumber({
errorHandler: function (error) {
console.log(error.message);
this.emit('end');
}
}))
.pipe(concat('scripts.js'))
.pipe(gulp.dest(pathToTemplate + 'dist/'))
.pipe(rename({suffix: '.min'}))
.pipe(uglify())
.pipe(gulp.dest(pathToTemplate + 'dist/'))
.pipe(browserSync.stream())
});
gulp.task('templates', function() {
gulp.src(pathToTemplate + 'src/templates/*.jade')
.pipe(jade())
.pipe(gulp.dest(pathToTemplate))
.pipe(browserSync.stream())
});
gulp.task('compile', ['images','svg', 'styles', 'scripts','templates'])
gulp.task('default', ['compile'] , function () {
browserSync.init({
proxy: localhostURL
});
gulp.watch(pathToTemplate + 'src/images/**', ['images']);
gulp.watch(pathToTemplate + 'src/svg/**', ['svg']);
gulp.watch(pathToTemplate + 'src/styles/**/*.less', ['styles']);
gulp.watch(pathToTemplate + 'src/scripts/**/*.js', ['scripts']);
gulp.watch(pathToTemplate + 'src/templates/**/*.jade', ['templates']);
});
|
JavaScript
| 0.000001 |
@@ -3042,16 +3042,37 @@
lhostURL
+,%0A open: false
%0A %7D);
|
1c06c2e511e742f77ea4b9ebebe8a51c66cb4d7b
|
Print out error message if there's an error when running build:script
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
pkg = require('./package.json');
var aws = require('gulp-awspublish'),
browserify = require('browserify'),
connect = require('gulp-connect'),
compress = require('gulp-yuicompressor'),
karma = require('karma').Server,
less = require('gulp-less'),
minifyCss = require('gulp-minify-css'),
mocha = require('gulp-mocha'),
mochaPhantomJS = require('gulp-mocha-phantomjs'),
rename = require('gulp-rename'),
squash = require('gulp-remove-empty-lines'),
strip = require('gulp-strip-comments'),
through2 = require('through2');
gulp.task('default', ['build', 'connect', 'watch']);
gulp.task('connect', ['build',], function () {
return connect.server({
root: [ __dirname, 'test', 'test/unit', 'test/demo' ],
port: 9002
});
});
gulp.task('build', [
'build:script', 'build:minify-script',
'build:styles', 'build:minify-styles'
]);
gulp.task('watch', ['build', 'test:browserify'], function() {
gulp.watch([
'lib/**/*.js',
'gulpfile.js'
], ['build:minify-script', 'test:browserify']);
gulp.watch([
'lib/**/*.less',
'gulpfile.js'
], ['build:minify-styles']);
});
gulp.task('build:script', function(){
return gulp.src('./lib/index.js')
.pipe(through2.obj(function(file, enc, next){
browserify(file.path)
.bundle(function(err, res){
file.contents = res;
next(null, file);
});
}))
.pipe(strip({ line: true }))
.pipe(squash())
.pipe(rename(pkg.name + '.js'))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build:minify-script', ['build:script'], function(){
return gulp.src('./dist/' + pkg.name + '.js')
.pipe(compress({ type: 'js' }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./dist/'));
});
gulp.task('build:styles', function(){
gulp.src('./lib/styles/index.less')
.pipe(less())
.pipe(rename(pkg.name + '.css'))
.pipe(gulp.dest('./dist'));
});
gulp.task('build:minify-styles', ['build:styles'], function(){
gulp.src('./dist/' + pkg.name + '.css')
.pipe(minifyCss({ compatibility: 'ie9' }))
.pipe(rename({ suffix: '.min' }))
.pipe(gulp.dest('./dist/'));
});
// ---------------------
gulp.task('test:unit', ['test:phantom', 'test:mocha']);
gulp.task('test:browserify', function(){
return gulp.src('./test/unit/index.js')
.pipe(through2.obj(function(file, enc, next){
browserify(file.path)
.bundle(function(err, res){
file.contents = res;
next(null, file);
});
}))
.pipe(strip({ line: true }))
.pipe(squash())
.pipe(rename('browserified-tests.js'))
.pipe(gulp.dest('./test/unit/build'));
});
gulp.task('test:mocha', ['test:browserify'], function () {
return gulp.src('./test/unit/server.js', { read: false })
.pipe(mocha({
reporter: 'nyan',
timeout: 300 * 1000
}));
});
gulp.task('test:phantom', ['test:browserify'], function () {
return gulp.src('./test/unit/index.html')
.pipe(mochaPhantomJS({
mocha: {
reporter: 'nyan',
timeout: 300 * 1000
}
}))
.once('error', function () {
process.exit(1);
})
.once('end', function () {
process.exit();
});
});
gulp.task('test:karma', ['build', 'test:browserify'], function (done){
new karma({
configFile: __dirname + '/config-karma.js',
singleRun: true
}, done).start();
});
gulp.task('test:sauce', ['build', 'test:browserify'], function(done){
new karma({
configFile: __dirname + '/config-sauce.js',
singleRun: true
}, done).start();
});
// ---------------------
gulp.task('deploy', ['build', 'test:mocha', 'test:karma'], function() {
var cacheLife, publisher, headers;
if (!process.env.AWS_KEY || !process.env.AWS_SECRET) {
throw 'AWS credentials are required!';
}
cacheLife = (1000 * 60 * 60); // 1 hour (* 24 * 365)
headers = {
'Cache-Control': 'max-age=' + cacheLife + ', public'
};
publisher = aws.create({
'accessKeyId': process.env.AWS_KEY,
'secretAccessKey': process.env.AWS_SECRET,
'params': {
'Bucket': 'keen-js',
'Expires': new Date(Date.now() + cacheLife)
}
});
return gulp.src([
'./dist/' + pkg.name + '.js',
'./dist/' + pkg.name + '.min.js',
'./dist/' + pkg.name + '.css',
'./dist/' + pkg.name + '.min.css'
])
.pipe(rename(function(path) {
path.dirname += '/';
var name = pkg.name + '-' + pkg.version;
path.basename = (path.basename.indexOf('min') > -1) ? name + '.min' : name;
}))
.pipe(aws.gzip())
.pipe(publisher.publish(headers, { force: true }))
.pipe(publisher.cache())
.pipe(aws.reporter());
});
|
JavaScript
| 0.000233 |
@@ -1363,32 +1363,82 @@
tion(err, res)%7B%0A
+ if(err) %7B console.log(err.message); %7D%0A
file
|
d898d9275629184c05e449b447b26d4de8fce700
|
add path variables
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
autoprefixer = require('gulp-autoprefixer'),
argv = require('yargs').argv,
browserSync = require('browser-sync'),
concat = require('gulp-concat'),
del = require('del'),
gulpif = require('gulp-if'),
jade = require('gulp-jade'),
minifyCSS = require('gulp-minify-css');
reload = browserSync.reload,
rename = require('gulp-rename'),
runSequence = require('run-sequence'),
sass = require('gulp-sass'),
uglify = require('gulp-uglify'),
imagemin = require('gulp-imagemin'),
gulp.task('clean', function (cb) {
del(['./build/'], cb);
});
gulp.task('sass', function () {
return gulp.src(['./src/scss/*.scss', './src/scss/vendors/*.scss'])
.pipe(sass({errLogToConsole: true}))
.pipe(autoprefixer({
autoprefixer: {browsers: ['last 2 versions']}
}))
.pipe(gulpif(argv.production, rename({suffix: '.min'})))
.pipe(gulpif(argv.production, minifyCSS({keepBreaks:false})))
.pipe(gulp.dest('./build/css'))
.pipe(reload({stream: true}));
});
gulp.task('images', function () {
return gulp.src('./src/img/**/*.*')
.pipe(imagemin({
progressive: true,
optimizationLevel : 8
}))
.pipe(gulp.dest('./build/img'))
.pipe(reload({stream: true}));
});
gulp.task('javascript', function () {
return gulp.src(['./src/js/vendors/*.js', './src/js/**/*.js'], {base: 'src' })
.pipe(gulpif(argv.production, concat('js/app.js')))
.pipe(gulpif(argv.production, rename({suffix: '.min'})))
.pipe(gulpif(argv.production, uglify({preserveComments: 'some'}))) // Keep some comments
.pipe(gulp.dest('./build/'))
.pipe(reload({stream: true}));
});
gulp.task('templates', function() {
'use strict';
var YOUR_LOCALS = {};
return gulp.src('./src/jade/*.jade')
.pipe(jade({
locals: YOUR_LOCALS,
pretty: true
}))
.pipe(gulp.dest('./build/'))
.pipe(reload({ stream:true }));
});
gulp.task('dev',['builder'], function() {
browserSync({
server: {
baseDir: 'build'
}
});
gulp.watch('./src/jade/**/*.jade', ['templates']);
gulp.watch('./src/scss/**/*.scss', ['sass']);
gulp.watch('./src/js/**/*.js', ['copy']);
});
gulp.task('builder', ['clean'], function (cb) {
runSequence(['sass', 'javascript', 'templates', 'images'], cb);
});
|
JavaScript
| 0.000002 |
@@ -542,17 +542,422 @@
agemin')
-,
+;%0A%0Avar basePaths = %7B%0A src: 'src/',%0A dest: 'build/',%0A%7D;%0A%0Avar paths = %7B%0A styles: %7B%0A src: basePaths.src + 'scss/',%0A dest: basePaths.dest + 'css/'%0A %7D,%0A javascript: %7B%0A src: basePaths.src + 'js/',%0A dest: basePaths.dest + 'js/'%0A %7D,%0A images: %7B%0A src: basePaths.src + 'img/',%0A dest: basePaths.dest + 'img/'%0A %7D,%0A templates: %7B%0A src: basePaths.src + 'jade/',%0A dest: basePaths.dest%0A %7D%0A%7D
%0A%0Agulp.t
@@ -991,26 +991,30 @@
%7B%0A%09del(%5B
-'./build/'
+basePaths.dest
%5D, cb);%0A
@@ -1073,40 +1073,57 @@
rc(%5B
-'./src/scss/*.scss', './src/scss
+paths.styles.src + '*.scss', paths.styles.src + '
/ven
@@ -1402,21 +1402,27 @@
est(
-'./build/css'
+(paths.styles.dest)
))%0A
@@ -1514,18 +1514,28 @@
src(
-'./src/img
+paths.images.src + '
/**/
@@ -1636,21 +1636,25 @@
est(
-'./build/img'
+paths.images.dest
))%0A
@@ -1751,43 +1751,71 @@
rc(%5B
-'./src/js/vendors/*.js', './src/js/
+paths.javascript.src + 'vendors/*.js', paths.javascript.src + '
**/*
@@ -2055,34 +2055,38 @@
e(gulp.dest(
-'./build/'
+basePaths.dest
))%0A .pipe(r
@@ -2205,28 +2205,39 @@
ulp.src(
-'./src/jade/
+paths.templates.src + '
*.jade')
@@ -2322,18 +2322,22 @@
est(
-'./build/'
+basePaths.dest
))%0A
@@ -2387,17 +2387,21 @@
task('de
-v
+fault
',%5B'buil
@@ -2469,15 +2469,22 @@
ir:
-'build'
+basePaths.dest
%0A
@@ -2509,20 +2509,31 @@
tch(
-'./src/jade/
+paths.templates.src + '
**/*
@@ -2573,20 +2573,27 @@
tch(
-'./src/scss/
+paths.styles.src +'
**/*
@@ -2628,18 +2628,32 @@
tch(
-'./src/js/
+paths.javascript.src + '
**/*
@@ -2664,12 +2664,18 @@
, %5B'
-copy
+javascript
'%5D);
|
97b16c9ab6a5b825cef7cb03e04c444ced64db4b
|
Remove path to .maps files and write map coordinates directly in CSS's
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var autoprefixer = require('gulp-autoprefixer');
var server = require('gulp-express');
var input = './app/sass/*.scss';
var output = './app/css/';
var sassOptions = {
errLogToConsole: true,
outputStyle: 'expanded'
};
gulp.task('sass', function () {
return gulp
.src(input)
.pipe(sourcemaps.init())
.pipe(sass(sassOptions).on('error', sass.logError))
.pipe(sourcemaps.write('./app/css/maps'))
.pipe(autoprefixer())
.pipe(gulp.dest(output));
});
gulp.task('watch', function() {
return gulp
.watch(input, ['sass'])
.on('change', function(event) {
console.log('File ' + event.path + ' was ' + event.type + ', running tasks...');
});
});
gulp.task('copy', function() {
gulp.src([
'node_modules/angular-ui-bootstrap/ui-bootstrap.js',
'node_modules/angular-ui-bootstrap/ui-bootstrap-tpls.min.js',
'node_modules/angular-modal-service/dst/angular-modal-service.min.js',
'node_modules/angular-modal-service/dst/angular-modal-service.min.js.map',
'node_modules/angular/angular.min.js',
'node_modules/angular/angular.min.js.map',
'node_modules/angular-ui-router/release/angular-ui-router.min.js',
'node_modules/angular-cookies/angular-cookies.min.js',
'node_modules/angular-cookies/angular-cookies.min.js.map'
]).pipe(gulp.dest('build/libs/'));
gulp.src([
'node_modules/bootstrap/dist/**/*'
]).pipe(gulp.dest('build/bootstrap'));
});//End task copy
gulp.task('server', function () {
server.run(['server.js']);
});//End task server
gulp.task('default', ['sass','watch','copy','server']);
|
JavaScript
| 0 |
@@ -187,16 +187,33 @@
ess');%0A%0A
+//Sass variables%0A
var inpu
@@ -264,17 +264,16 @@
/css/';%0A
-%0A
var sass
@@ -502,24 +502,8 @@
ite(
-'./app/css/maps'
))%0A%09
@@ -549,21 +549,35 @@
output))
-;
%0A%7D);
+//End task sass
%0A%0Agulp.t
@@ -763,16 +763,33 @@
%09%7D);%0A%7D);
+//End tastk watch
%0A%0Agulp.t
|
94eefe5785ce303a96c33306148b700657fdc067
|
enable recovery key for 10% users
|
app/scripts/lib/experiments/grouping-rules/recovery-key.js
|
app/scripts/lib/experiments/grouping-rules/recovery-key.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/. */
'use strict';
const BaseGroupingRule = require('./base');
const GROUPS = ['control', 'treatment'];
module.exports = class RecoveryKeyGroupingRule extends BaseGroupingRule {
constructor() {
super();
this.name = 'recoveryKey';
this.ROLLOUT_RATE = 0;
}
choose(subject) {
if (! subject || ! subject.account || ! subject.uniqueUserId) {
return false;
}
// Is feature enabled explicitly? ex. from `?showAccountRecovery=true` feature flag?
if (subject.showAccountRecovery) {
return 'treatment';
}
if (this.isTestEmail(subject.account.get('email'))) {
return 'treatment';
}
// Are they apart of rollout?
if (this.bernoulliTrial(this.ROLLOUT_RATE, subject.uniqueUserId)) {
return this.uniformChoice(GROUPS, subject.uniqueUserId);
}
// Otherwise don't show panel
return false;
}
};
|
JavaScript
| 0 |
@@ -461,16 +461,18 @@
RATE = 0
+.1
;%0A %7D%0A%0A
|
22cd7e43b8b3a5a40b27898763c86f2f5b861051
|
Copy license during build
|
gulpfile.js
|
gulpfile.js
|
/* eslint-env node */
'use strict';
let del = require('del');
let gitRev = require('git-rev');
let path = require('path');
let osenv = require('osenv');
let gulp = require('gulp');
let shell = require('gulp-shell');
let symlink = require('gulp-symlink');
let replace = require('gulp-replace');
let zip = require('gulp-zip');
let metadata = require('./src/metadata.json');
let src = {
copy: [
'src/**/*',
'!src/**/*~',
'!src/schemas{,/**/*}',
'!src/metadata.json',
],
lib: [
'lib/**/*',
],
metadata: [
'src/metadata.json',
],
schemas: [
'src/schemas/**/*',
],
};
let install = {
local: path.join(
osenv.home(),
'.local/share/gnome-shell/extensions',
metadata.uuid
),
global: path.join(
'/usr/share/gnome-shell/extensions',
metadata.uuid
),
};
function isInt(value) {
if (isNaN(value)) {
return false;
}
var x = parseFloat(value);
return (x | 0) === x;
}
gulp.task('clean', function () {
return del.sync([
'build/',
'dist/',
]);
});
gulp.task('copy', function () {
return gulp.src(src.copy)
.pipe(gulp.dest('build'));
});
gulp.task('copy-lib', function () {
return gulp.src(src.lib)
.pipe(gulp.dest('build/lib'));
});
gulp.task('metadata', function () {
return gitRev.tag(function (commit) {
return gulp.src(src.metadata)
.pipe(replace('{{VERSION}}', commit))
.pipe(gulp.dest('build'));
});
});
gulp.task('schemas', shell.task([
'mkdir -p build/schemas',
'glib-compile-schemas --strict --targetdir build/schemas src/schemas/',
]));
gulp.task('build', [
'clean',
'metadata',
'schemas',
'copy',
'copy-lib',
]);
gulp.task('watch', [
'build',
], function () {
gulp.watch(src.copy, [ 'copy' ]);
gulp.watch(src.lib, [ 'copy-lib' ]);
gulp.watch(src.metadata, [ 'metadata' ]);
gulp.watch(src.schemas, [ 'schemas' ]);
});
gulp.task('reset-prefs', shell.task([
'dconf reset -f /org/gnome/shell/extensions/gravatar/',
]));
gulp.task('uninstall', function () {
return del.sync([
install.local,
install.global,
], {
force: true,
});
});
gulp.task('install-link', [
'uninstall',
'build',
], function () {
gulp.src([
'build',
]).pipe(symlink(install.local));
});
gulp.task('install', [
'uninstall',
'build',
], function () {
gulp.src([
'build/**',
]).pipe(gulp.dest(install.local));
});
gulp.task('install-global', [
'uninstall',
'build',
], function () {
gulp.src([
'build/**',
]).pipe(gulp.dest(install.global));
});
gulp.task('dist', [
'build',
], function () {
return gitRev.tag(function (commit) {
let versionStr = isInt(commit) ? 'v' + commit : commit;
let zipFile = metadata.uuid + '-' + versionStr + '.zip';
return gulp.src([
'build/**/*',
]).pipe(zip(zipFile))
.pipe(gulp.dest('dist'));
});
});
gulp.task('default', function () {
/* eslint-disable no-console, max-len */
console.log(
'\n' +
'Usage: gulp [COMMAND]\n' +
'\n' +
'Commands\n' +
'\n' +
' clean Cleans the build/ directory\n' +
' build Builds the extension\n' +
' watch Builds and watches the src/ directory for changes\n' +
' install Installs the extension to\n' +
' ~/.local/share/gnome-shell/extensions/\n' +
' install-link Installs as symlink to build/ directory\n' +
' install-global Installs the extension to\n' +
' /usr/share/gnome-shell/extensions/\n' +
' reset-prefs Resets extension preferences\n' +
' uninstall Uninstalls the extension\n'
);
/* eslint-esnable no-console, max-len */
});
|
JavaScript
| 0 |
@@ -1221,32 +1221,143 @@
ld/lib'));%0A%7D);%0A%0A
+gulp.task('copy-license', function () %7B%0A return gulp.src(%5B%0A 'LICENSE',%0A %5D).pipe(gulp.dest('build'));%0A%7D);%0A%0A
gulp.task('metad
@@ -1764,16 +1764,34 @@
y-lib',%0A
+ 'copy-license',%0A
%5D);%0A%0Agul
|
81291cae30555c0be5fcd06736fa9ea096ec54d0
|
Disable manual ip double submit on enter keypress (#3376)
|
app/src/components/AppSettings/AddManualIp/ManualIpForm.js
|
app/src/components/AppSettings/AddManualIp/ManualIpForm.js
|
// @flow //
import * as React from 'react'
import { connect } from 'react-redux'
import { getConfig, addManualIp } from '../../../config'
import { startDiscovery } from '../../../discovery'
import { Formik, Form, Field } from 'formik'
import IpField from './IpField'
import type { State, Dispatch } from '../../../types'
import type { DiscoveryCandidates } from '../../../config'
type OP = {||}
type SP = {| candidates: DiscoveryCandidates |}
type DP = {| addManualIp: (ip: string) => mixed |}
type Props = { ...SP, ...DP }
class IpForm extends React.Component<Props> {
inputRef: { current: null | HTMLInputElement }
constructor(props: Props) {
super(props)
this.inputRef = React.createRef()
}
render() {
return (
<Formik
initialValues={{ ip: '' }}
onSubmit={(values, actions) => {
this.props.addManualIp(values.ip)
const $input = this.inputRef.current
if ($input) $input.blur()
actions.resetForm()
}}
render={formProps => {
return (
<Form>
<Field name="ip" component={IpField} inputRef={this.inputRef} />
</Form>
)
}}
/>
)
}
}
function mapStateToProps(state: State): SP {
return {
candidates: getConfig(state).discovery.candidates,
}
}
function mapDispatchToProps(dispatch: Dispatch): DP {
return {
addManualIp: ip => {
dispatch(addManualIp(ip))
dispatch(startDiscovery())
},
}
}
export default connect<Props, OP, _, _, _, _>(
mapStateToProps,
mapDispatchToProps
)(IpForm)
|
JavaScript
| 0 |
@@ -822,24 +822,198 @@
tions) =%3E %7B%0A
+ // trim whitespace and carriage returns%0A const ip = values.ip.trim()%0A // guard against double submit on enter keypress%0A if (!ip) return%0A%0A
th
@@ -1033,23 +1033,16 @@
anualIp(
-values.
ip)%0A%0A
|
a195c67851d4986ce80ebbf2394ae0d60341dd8c
|
remove unused import
|
lib/git-blame.js
|
lib/git-blame.js
|
const GitTools = require('git-tools');
const Blamer = require('./util/blamer');
// reference to the Blamer instance created in initializeContext if this
// project is backed by a git repository.
var projectBlamer = null;
function activate() {
initializeContext();
// git-blame:blame
atom.workspaceView.command('git-blame:blame', function() {
return blame();
});
return;
}
function isPathInSubmodule(repo, path) {
var submodules = repo.submodules;
if (submodules) {
for (var submodulePath in submodules) {
var submoduleRegex = new RegExp('^' + submodulePath);
if (submoduleRegex.test(path)) {
return true;
}
}
}
return false;
}
function initializeContext() {
var editor = atom.workspace.activePaneItem;
var projectRepo = atom.project.getRepo();
// Ensure this project is backed by a git repository
if (!projectRepo) {
// TODO visually alert user
return console.error('Cant initialize blame! there is no git repo for this project');
}
projectBlamer = new Blamer(projectRepo);
}
function blame() {
var editor = atom.workspace.activePaneItem;
var filePath = editor.getPath();
// Nothing to do if projectBlamer isnt defined. Means this project is not
// backed by git.
if (!projectBlamer) {
return;
}
projectBlamer.blame(filePath, function(err, blame) {
if (err) {
console.error(err);
} else {
console.log('BLAME', blame);
}
});
}
module.exports = {
blame: blame,
activate: activate
};
|
JavaScript
| 0.000001 |
@@ -1,43 +1,4 @@
-const GitTools = require('git-tools');%0A
cons
|
8ccc56392cf947b7b36f66850360ede3187b16ae
|
add dividers to gulpfile
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var fs = require('fs');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
//setup for development use
gulp.task('setupDev', () => {
getDevPluginXML();
setIosNpmOrDev('dev');
})
//setup for npm deployment
gulp.task('setupNpm', () => {
genNpmPluginXML();
setIosNpmOrDev('npm');
});
gulp.task('build-npm', ['setupNpm', 'babel']);
//generate plugin.xml for use as a cordova plugin
//here we explode the contents of the frameworks
function genNpmPluginXML(){
var xml = fs.readFileSync('plugin.template.xml', 'utf-8');
var files = [];
var root = 'src/ios/dependencies/';
files = files.concat(emitFiles(root + 'Fabric/'));
files = files.concat(emitFiles(root + 'Branch-SDK/'));
files = files.concat(emitFiles(root + 'Branch-SDK/Requests/'));
var newLineIndent = '\n ';
xml = xml.replace('<!--[Branch Framework Reference]-->', newLineIndent
+ files.join(newLineIndent));
fs.writeFileSync('plugin.xml', xml);
};
//generate plugin.xml for local development
//here we reference the frameworks instead of all the files directly
function getDevPluginXML(){
var xml = fs.readFileSync('plugin.template.xml', 'utf-8');
xml = xml.replace('<!--[Branch Framework Reference]-->',
'<framework custom="true" src="src/ios/dependencies/Branch.framework" />');
fs.writeFileSync('plugin.xml', xml);
};
function setIosNpmOrDev(npmOrDev){
if(npmOrDev === 'npm'){
content = '#define BRANCH_NPM true';
}else if(npmOrDev === 'dev'){
content = '//empty';
}else{
throw new Error('expected deployed|local, not ' + deployedOrLocal);
}
fs.writeFileSync('src/ios/BranchNPM.h', content + '\n');
}
//emit array of cordova file references for all .h/.m files in path
function emitFiles(path){
var ret = [];
for(filename of fs.readdirSync(path)){
var fileType = null;
if(filename.match(/\.m$/)){
fileType = 'source';
}else if(filename.match(/\.h$/) || filename.match(/\.pch$/)){
fileType = 'header';
}
if(fileType){
ret.push('<' + fileType + '-file src="' + path + filename + '" />');
}
}
ret.push('');
return ret;
}
//copy resources and compile es6 from corresponding directory
babelTasks = []; //list of all babel tasks so we can build all of them
function babelize(taskName, dir){
babelTasks.push(taskName + '-babel');
if(!dir){
dir = taskName;
}
var srcDir = dir + '.es6/';
var srcPattern = dir + '.es6/**/*.js'
var destDir = dir + '/';
gulp.task(taskName + '-copy', () => {
return gulp.src(srcDir + '**/*.*').pipe(gulp.dest(destDir));
});
gulp.task(taskName + '-babel', [taskName + '-copy'], () => {
return gulp.src(srcPattern)
.pipe(sourcemaps.init())
.pipe(babel({
presets: ['es2015', 'stage-2'],
plugins: ['transform-runtime'] //needed for generators etc
}))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(destDir));
});
}
babelize('hooks');
babelize('www');
babelize('tests');
babelize('testbed', 'testbed/www/js');
gulp.task('babel', babelTasks);
|
JavaScript
| 0.000004 |
@@ -126,16 +126,153 @@
bel');%0A%0A
+gulp.task('build-npm', %5B'setupNpm', 'babel', 'lint'%5D);%0A%0A//------------------------------------------------------------------------------%0A
//setup
@@ -483,56 +483,8 @@
);%0A%0A
-gulp.task('build-npm', %5B'setupNpm', 'babel'%5D);%0A%0A
//ge
@@ -2257,16 +2257,97 @@
ret;%0A%7D%0A%0A
+//------------------------------------------------------------------------------%0A
//copy r
@@ -2398,17 +2398,19 @@
director
-y
+ies
%0AbabelTa
|
137ad92631baa36525143fc4ffb34b0346ada367
|
Fix to cleanup versioning
|
lib/common.js
|
lib/common.js
|
'use strict';
var fs = require('fs'),
edge = require('edge'),
path = require('path');
module.exports = {
addLicenseAndReleaseNotes: function (config, manifest) {
if (this.fileExists(config.dnn.pathToSupplementaryFiles + '/License.txt')) {
manifest.package[0].license = [{
"$": {
"src": "License.txt"
}
}];
}
if (this.fileExists(config.dnn.pathToSupplementaryFiles + '/ReleaseNotes.txt') | this.fileExists(config.dnn.pathToSupplementaryFiles + '/ReleaseNotes.md')) {
manifest.package[0].releaseNotes = [{
"$": {
"src": "ReleaseNotes.txt"
}
}];
}
return manifest;
},
addDependencyNode: function (config, manifest) {
var version = config.dnn.dnnDependency;
if (version == undefined) {
version = this.toNormalizedVersionString(this.getCoreReferenceVersion(config));
}
if (version !== '00.00.00') {
manifest.package[0].dependencies = [{
"dependency": [{
"_": version,
"$": {
"type": "CoreVersion"
}
}]
}];
}
return manifest;
},
addResourceComponent: function (config, manifest, basePath, fileName) {
if (basePath == undefined) { basePath = "DesktopModules/" + config.dnn.folder }
if (fileName == undefined) { fileName = "resources.zip" }
manifest.package[0].components[0].component.push({
"$": {
"type": "ResourceFile"
},
"resourceFiles": [{
"basePath": [
basePath
],
"resourceFile": [{
"name": [
fileName
]
}]
}]
});
return manifest;
},
addAssemblyComponent: function (config, manifest) {
var files = fs.readdirSync(config.dnn.pathToAssemblies);
if (files.length > 0) {
var component = {
"$": {
"type": "Assembly"
},
"assemblies": [{
"assembly": []
}]
}
for (var i in files) {
if (path.extname(files[i]) === ".dll") {
var assembly = {
"name": [
files[i]
],
"sourceFileName": [
files[i]
],
"version": [
this.getAssemblyVersion(config.dnn.pathToAssemblies + '/' + files[i], true)
]
};
component.assemblies[0].assembly.push(assembly);
}
}
manifest.package[0].components[0].component.push(component);
}
return manifest;
},
addScriptComponent: function (config, manifest) {
var files = fs.readdirSync(config.dnn.pathToScripts);
if (files.length > 0) {
var component = {
"$": {
"type": "Script"
},
"scripts": [{
"basePath": ["DesktopModules/" + config.dnn.folder],
"script": []
}]
}
var rgx = /(Install\.)?(\d\d)\.(\d\d)\.(\d\d)\.SqlDataProvider/;
files.forEach(function (el, i, arr) {
var m = rgx.exec(el);
if (m) {
var script = {
"$": {
"type": "Install"
},
"name": [el],
"version": [m[2] + '.' + m[3] + '.' + m[4]]
};
component.scripts[0].script.push(script);
}
if (el == 'Uninstall.SqlDataProvider') {
component.scripts[0].script.push({
"$": {
"type": "UnInstall"
},
"name": [el],
"version": [config.version]
});
}
});
manifest.package[0].components[0].component.push(component);
}
return manifest;
},
addCleanupComponents: function (config, manifest) {
var files = fs.readdirSync(config.dnn.pathToSupplementaryFiles);
if (files.length > 0) {
var rgx = /(\d\d)\.(\d\d)\.(\d\d)\.txt/;
files.forEach(function (el, i, arr) {
var m = rgx.exec(el);
if (m) {
var component = {
"$": {
"type": "Cleanup",
"version": [m[2] + '.' + m[3] + '.' + m[4]],
"fileName": [el]
}
}
manifest.package[0].components[0].component.push(component);
}
});
}
return manifest;
},
getCoreReferenceVersion: function (config) {
var refVersion = {
major: 0,
minor: 0,
build: 0
};
var files = fs.readdirSync(config.dnn.pathToAssemblies);
for (var i in files) {
if (path.extname(files[i]) === ".dll") {
var refs = this.getReferences(config.dnn.pathToAssemblies + '/' + files[i], true);
if (refs.DotNetNuke !== undefined) {
refVersion = this.getLargestVersion(refVersion, refs.DotNetNuke);
}
}
}
return refVersion;
},
getLargestVersion: function (baseVersion, testVersion) {
if (typeof testVersion === 'string') {
return this.getLargestVersion(baseVersion, this.getVersionObject(testVersion));
} else {
if (baseVersion.major > testVersion.major) {
return baseVersion;
} else if (baseVersion.major < testVersion.major) {
return testVersion;
} else {
if (baseVersion.minor > testVersion.minor) {
return baseVersion;
} else if (baseVersion.minor < testVersion.minor) {
return testVersion;
} else {
if (baseVersion.build > testVersion.build) {
return baseVersion;
} else if (baseVersion.build < testVersion.build) {
return testVersion;
} else {
return baseVersion;
}
}
}
}
},
getVersionObject: function (versionString) {
var rgx = /(\d+)\.(\d+)\.(\d+)(\.\d+)?/;
var m = rgx.exec(versionString);
if (m) {
return {
major: parseInt(m[1]),
minor: parseInt(m[2]),
build: parseInt(m[3])
}
} else {
return null;
}
},
toNormalizedVersionString: function (version) {
return this.pad(version.major, 2) + '.' + this.pad(version.minor, 2) + '.' + this.pad(version.build, 2);
},
pad: function (num, size) {
var s = "000000000" + num;
return s.substr(s.length - size);
},
getReferences: edge.func({
source: function (aFile) {
/*
using System.Reflection;
using System.Linq;
using System.Collections.Generic;
async(aFile) => {
var res = new Dictionary<string, string>();
var ass = Assembly.LoadFrom((string) aFile);
foreach (var an in ass.GetReferencedAssemblies() )
{
res.Add(an.Name, an.Version.ToString());
}
return res;
}
*/
}
}),
getAssemblyVersion: edge.func({
source: function (aFile) {
/*
using System.Diagnostics;
async(aFile) => {
return FileVersionInfo.GetVersionInfo((string) aFile).FileVersion;
}
*/
}
}),
fileExists: function (path) {
try {
var stats = fs.lstatSync(path);
return true;
} catch (e) {
return false;
}
},
fileDelete: function (path) {
if (this.fileExists(path)) {
fs.unlinkSync(path);
}
}
}
|
JavaScript
| 0 |
@@ -5052,32 +5052,45 @@
%22version%22: %5B
+m%5B1%5D + '.' +
m%5B2%5D + '.' + m%5B3
@@ -5090,29 +5090,16 @@
' + m%5B3%5D
- + '.' + m%5B4%5D
%5D,%0A
|
8450f3d881de3265b6e2382a3f42ef75a71c4171
|
Simplify package.json parsing in gulpfile
|
gulpfile.js
|
gulpfile.js
|
/* jshint node: true, undef: true, strict: false */
var fs = require('fs');
var gulp = require('gulp');
var karma = require('karma');
var concat = require('gulp-concat');
var jshint = require('gulp-jshint');
var header = require('gulp-header');
var rename = require('gulp-rename');
var del = require('del');
var uglify = require('gulp-uglify');
var config = {
pkg: JSON.parse(fs.readFileSync('./package.json')),
banner:
'/*!\n' +
' * <%= pkg.name %>\n' +
' * <%= pkg.homepage %>\n' +
' * Version: <%= pkg.version %> - <%= timestamp %>\n' +
' * License: <%= pkg.license %>\n' +
' */\n'
};
gulp.task('default', ['build','test']);
gulp.task('build', ['scripts']);
gulp.task('test', ['build', 'karma']);
gulp.task('watch', ['build','karma-watch'], function() {
gulp.watch(['src/**/*.{js,html}'], ['build']);
});
gulp.task('clean', function(done) {
del(['dist'], done);
});
gulp.task('scripts', ['clean'], function() {
return gulp.src(['src/**/*.js'])
.pipe(jshint())
.pipe(jshint.reporter('jshint-stylish'))
.pipe(jshint.reporter('fail'))
.pipe(concat('ngMomentInput.js'))
.pipe(header(config.banner, {
timestamp: (new Date()).toISOString(),
pkg: config.pkg
}))
.pipe(gulp.dest('dist'))
.pipe(uglify({preserveComments: 'some'}))
.pipe(rename({extname:'.min.js'}))
.pipe(gulp.dest('dist'));
});
gulp.task('karma', ['build'], function(done) {
runTests(true, done);
});
gulp.task('karma-watch', ['build'], function(done) {
runTests(false, done);
});
function runTests(singleRun, done) {
new karma.Server({
configFile: __dirname + '/karma.conf.js',
singleRun: singleRun,
autoWatch: !singleRun
}, function() {
done();
}).start();
}
|
JavaScript
| 0.000018 |
@@ -49,32 +49,8 @@
*/%0A
-var fs = require('fs');%0A
var
@@ -341,34 +341,15 @@
kg:
-JSON.parse(fs.readFileSync
+require
('./
@@ -362,17 +362,16 @@
e.json')
-)
,%0A bann
|
7b68196fe9099bd357c7207b46e0bbfa1bef055c
|
remove useless console.log in the @Computed test
|
tests/src/test/javascript/components/basic/computed.spec.js
|
tests/src/test/javascript/components/basic/computed.spec.js
|
import {expect} from 'chai'
import {
createAndMountComponent,
destroyComponent,
nextTick,
onGwtReady
} from '../../vue-gwt-tests-utils'
describe('@Computed', () => {
let component;
beforeEach(() => onGwtReady().then(() => {
component = createAndMountComponent(
'com.axellience.vuegwt.tests.client.components.basic.computed.ComputedTestComponent');
}));
afterEach(() => {
destroyComponent(component);
});
it('should work correctly at start', () => {
const computedPropertyEl = component.$el.firstElementChild;
console.log(component.$el);
expect(computedPropertyEl.innerText).to.equal('');
expect(computedPropertyEl.hasAttribute('data-value')).to.be.false;
});
it('should change its value when a depending value changes', () => {
const computedPropertyEl = component.$el.firstElementChild;
component.setData('test value');
return nextTick().then(() => {
expect(computedPropertyEl.innerText).to.equal('#test value#');
expect(computedPropertyEl.getAttribute('data-value')).to.equal('#test value#');
});
});
it('should work correctly at start for computed that are not getters', () => {
const computedPropertyNoGetEl = component.$el.firstElementChild.nextElementSibling;
expect(computedPropertyNoGetEl.innerText).to.equal('');
expect(computedPropertyNoGetEl.hasAttribute('data-value')).to.be.false;
});
it('should change its value when a depending value changes for computed that are not getters', () => {
const computedPropertyNoGetEl = component.$el.firstElementChild.nextElementSibling;
component.setData('test value');
return nextTick().then(() => {
expect(computedPropertyNoGetEl.innerText).to.equal('!test value!');
expect(computedPropertyNoGetEl.getAttribute('data-value')).to.equal('!test value!');
});
});
});
|
JavaScript
| 0 |
@@ -550,40 +550,8 @@
ld;%0A
- console.log(component.$el);%0A
|
2ed1bac762f24c2f65fb698bf08b75d9e27e2e83
|
Introduce line counter for feedback on parse error. Also callback if reading file enters error
|
lib/config.js
|
lib/config.js
|
var fs = require('fs');
var isObject = function(testObj) {
return typeof testObj == 'object';
}
var overrideProperty = function(obj, prop, value) {
if(!obj.hasOwnProperty(prop)) {
obj[prop] = value;
return;
}
/* deep override only when matching type object */
if(isObject(value) && isObject(obj[prop])) {
overrideObject(obj[prop], value);
return;
}
obj[prop] = value;
};
var overrideObject = function(obj) {
var i, prop, len, source;
for( i = 1, len = arguments.length; i < len; i++) {
source = arguments[i];
for(prop in source) {
overrideProperty(obj, prop, source[prop]);
}
}
};
var ini2json = function(filename, callback) {
fs.readFile(filename, 'utf8', function(err, data) {
var root = {}, lines, currentSection;
if(err) {
console.log(err);
}
lines = data.split("\n");
lines.forEach(function(line) {
var i, len, props, section, obj = (currentSection) ? root[currentSection] : root;
line = line.trim();
/* ; and # is comments */
if(line && line[0] != ';' && line[0] != '#') {
if(( section = line.match(/^\[(.+)\]$/))) {
if (currentSection) {
/* new section; reset obj to root */
obj = root;
}
currentSection = section[1];
obj[currentSection] = {};
return;
}
line = line.split('=');
if(line.length < 2) {
console.log('Error parsing config');
callback(new Error('Error parsing config. Check the config parsed so far in the result'), root);
return;
}
props = line[0].trim().split('.');
value = line.slice(1).join('=').trim();
for( i = 0, len = props.length - 1; i < len; i++) {
if(!obj[props[i]]) {
obj[props[i]] = {};
}
obj = obj[props[i]];
}
obj[props[i]] = unescapeIniValue(value);
}
});
callback(null, root);
});
};
var unescapeIniValue = function(value) {
return String(value).replace(/\\t/g, "\t").replace(/\\n/g, "\n").replace(/\\r/g, "\r");
}
var escapeIniValue = function(value) {
return String(value).replace(/\t/g, "\\t").replace(/\n/g, "\\n").replace(/\r/g, "\\r");
}
var json2ini = function(obj) {
var kv = [];
json2iniIterate('', '', obj, function(err, key, value) {
if(err) {
console.log(err);
return;
}
kv.push(key + '=' + escapeIniValue(value));
});
return kv.join("\n");
};
var json2iniIterate = function(prekey, key, value, donecb) {
prekey = prekey ? prekey + '.' + key : key;
if(isObject(value)) {
Object.keys(value).forEach(function(prop) {
json2iniIterate(prekey, prop, value[prop], donecb);
});
return;
}
donecb(null, prekey, value);
};
var Config = function(files, path) {
var self = this;
files.forEach(function(filename) {
if(path) {
filename = path + '/' + filename
}
var config = require(filename);
overrideObject(self, config);
});
};
module.exports = {
__namespace__ : 'config',
Config : Config,
overrideObject : overrideObject,
overrideProperty : overrideProperty,
ini2json : ini2json,
json2ini : json2ini
};
/** Implement later
var scanConfig = module.exports.scanDirConfig = function(path) {
var config = new Config();
if(!fs.existsSync(path)) {
throw new Error('Path does not exists');
}
var files = readdirSync(path);
files.forEach(function(filename) {
if(path.extname(filename) == '.js') {
addConfig(config, filename, path);
}
});
};
*/
|
JavaScript
| 0 |
@@ -740,16 +740,28 @@
tSection
+, lineNo = 0
;%0A%09%09if(e
@@ -766,39 +766,53 @@
(err) %7B%0A%09%09%09c
-onsole.log(err)
+allback(err, null);%0A%09%09%09return
;%0A%09%09%7D%0A%09%09line
@@ -951,16 +951,29 @@
: root;%0A
+%09%09%09lineNo++;%0A
%09%09%09line
@@ -1363,143 +1363,74 @@
%09%09%09c
-onsole.log('Error parsing config');%0A%09%09%09%09%09callback(new Error('Error parsing config. Check the config parsed so far in the result'), root
+allback(new Error('Error parsing config at line: ' + lineNo), null
);%0A%09
|
6011258eb1e26b13fd1a7865cddbfe41da04d3d6
|
Modify gulp webpack not to watch
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var replacements = require('./config/replacements.config');
var proxies = require('./config/proxies.config');
var paths = {
sass: ['./scss/**/*.scss'],
typescript: ['./src/**/*.ts']
};
/* tasks */
gulp.task('default', ['sass', 'webpack']);
gulp.task('watch', function () {
gulp.watch(paths.sass, ['sass']);
gulp.watch(paths.typescript, ['webpack']);
});
var del = require('del');
gulp.task('clean', function () {
del(['www/js/*.js', 'www/css/*.css', 'plugins', 'platforms', 'node_modules'])
});
var jsonEditor = require('gulp-json-editor');
var xmlEditor = require('gulp-xml-editor');
gulp.task('replace', function () {
var env = {};
replacements[process.env.ENV || 'debug'].map((value, index) => {
env[value.search] = value.replace;
});
gulp.src("./config.xml")
.pipe(xmlEditor([
{ path: '//xmlns:name', text: env["@@xmlns:name"] },
{ path: '//xmlns:access', attr: { origin: env["@@xmlns:access"] } },
{ path: '//xmlns:allow-intent', attr: { href: env["@@xmlns:allow-intent"] } },
{ path: '//xmlns:allow-navigation', attr: { href: env["@@xmlns:allow-navigation"] } },
{ path: '//xmlns:widget[@id]', attr: { id: env["@@xmlns:widget[@id]"], version: env["@@xmlns:widget[@version]"] } },
], 'http://www.w3.org/ns/widgets'))
.pipe(gulp.dest("./"));
gulp.src("./ionic.project")
.pipe(jsonEditor({
'proxies': proxies[process.env.ENV || 'debug']
}))
.pipe(gulp.dest("./"));
});
var webpack = require('gulp-webpack');
gulp.task('webpack', ['replace'], function () {
gulp.src(paths.typescript)
.pipe(webpack(require('./webpack.config.js')))
.pipe(gulp.dest('./'));
});
var Karma = require('karma').Server;
gulp.task('karma', function (done) {
new Karma({
configFile: __dirname + '/config/karma.conf.js',
singleRun: false
}).start();
});
var protractor = require("gulp-protractor").protractor;
gulp.task('protractor', function (done) {
gulp.src([])
.pipe(protractor({
configFile: "./config/protractor.config.js"
}))
.on('error', function (e) { throw e })
});
var gutil = require('gulp-util');
var sass = require('gulp-sass');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
gulp.task('sass', function (done) {
gulp.src('./scss/ionic.app.scss')
.pipe(process.env.ENV !== 'release' ? sourcemaps.init() : gutil.noop())
.pipe(sass({outputStyle: 'compressed'}))
.on('error', sass.logError)
.pipe(process.env.ENV !== 'release' ? sourcemaps.write() : gutil.noop())
.pipe(gulp.dest('./www/css/'))
.on('end', done);
});
var nodeCLI = require("shelljs-nodecli");
gulp.task('build', ['webpack'], function () {
var target = (process.env.TARGET === 'ios') ? 'ios' : 'android';
nodeCLI.exec("ionic", "build", target, function (code, output) {
// do after exec
});
});
gulp.task('run', ['webpack'], function () {
var target = (process.env.TARGET === 'ios') ? 'ios' : 'android';
nodeCLI.exec("ionic", "run", target, function (code, output) {
// do after exec
});
});
var sh = require('shelljs');
var bower = require('bower');
gulp.task('install', ['git-check'], function () {
return bower.commands.install()
.on('log', function (data) {
gutil.log('bower', gutil.colors.cyan(data.id), data.message);
});
});
gulp.task('git-check', function (done) {
if (!sh.which('git')) {
console.log(
' ' + gutil.colors.red('Git is not installed.'),
'\n Git, the version control system, is required to download Ionic.',
'\n Download git here:', gutil.colors.cyan('http://git-scm.com/downloads') + '.',
'\n Once git is installed, run \'' + gutil.colors.cyan('gulp install') + '\' again.'
);
process.exit(1);
}
done();
});
|
JavaScript
| 0.000001 |
@@ -340,53 +340,8 @@
%5D);%0A
- gulp.watch(paths.typescript, %5B'webpack'%5D);%0A
%7D);%0A
@@ -1521,24 +1521,275 @@
nction () %7B%0A
+ var config = require('./webpack.config.js');%0A config.watch = false;%0A gulp.src(paths.typescript)%0A .pipe(webpack(config))%0A .pipe(gulp.dest('./'));%0A%7D);%0Avar webpack = require('gulp-webpack');%0Agulp.task('webpackWatch', %5B'replace'%5D, function () %7B%0A
gulp.src(p
|
dd5327926ea4846e49e17f40df363b43d2019482
|
fix gulp eslint
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var path = require('path');
var gulp = require('gulp');
var eslint = require('gulp-eslint');
var excludeGitignore = require('gulp-exclude-gitignore');
var mocha = require('gulp-mocha');
var istanbul = require('gulp-istanbul');
var nsp = require('gulp-nsp');
var plumber = require('gulp-plumber');
gulp.task('static', function () {
return gulp.src('app/*.js')
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('nsp', function (cb) {
nsp({package: path.resolve('package.json')}, cb);
});
gulp.task('pre-test', function () {
return gulp.src('app/*.js')
.pipe(excludeGitignore())
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('test', ['pre-test'], function (cb) {
var mochaErr;
gulp.src('test/**/*.js')
.pipe(plumber())
.pipe(mocha({reporter: 'spec'}))
.on('error', function (err) {
mochaErr = err;
})
.pipe(istanbul.writeReports())
.on('end', function () {
cb(mochaErr);
});
});
gulp.task('watch', function () {
gulp.watch(['app/*.js', 'test/**'], ['test']);
});
gulp.task('prepublish', ['nsp']);
gulp.task('default', ['static', 'test']);
|
JavaScript
| 0.000009 |
@@ -344,38 +344,54 @@
%7B%0A return gulp
+%0A
.src('
+generators/
app/*.js')%0A .
@@ -432,16 +432,27 @@
(eslint(
+%7Bfix: true%7D
))%0A .
@@ -649,24 +649,29 @@
return gulp
+%0A
.src('app/*.
@@ -707,32 +707,39 @@
re())%0A .pipe(
+%0A
istanbul(%7B%0A
@@ -733,16 +733,18 @@
anbul(%7B%0A
+
in
@@ -767,18 +767,25 @@
rue%0A
-%7D)
+ %7D)%0A
)%0A .p
@@ -889,16 +889,21 @@
%0A%0A gulp
+%0A
.src('te
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.