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
|
---|---|---|---|---|---|---|---|
c54a33af6d3a1afdbb13bfcf2ca571fb89fd25e9
|
Disable debug in demo mode
|
lib/config.js
|
lib/config.js
|
/*jslint evil: true, expr: true, regexdash: true, bitwise: true, trailing: false, sub: true, eqeqeq: true,
forin: true, freeze: true, loopfunc: true, laxcomma: true, indent: false, white: true, nonew: true, newcap: true,
undef: true, unused: true, globalstrict: true, node: true */
"use strict";
var fs = require("fs"),
path = require("path"),
chalk = require("chalk"),
log = require("./log.js"),
config,
defaults = [
'{',
' "debug" : false,',
' "useTLS" : false,',
' "useSPDY" : false,',
' "useHSTS" : false,',
' "listenHost" : "0.0.0.0",',
' "listenPort" : 8989,',
' "readInterval" : 250,',
' "keepAlive" : 20000,',
' "linkLength" : 3,',
' "logLevel" : 2,',
' "maxOpen" : 256,',
' "zipLevel" : 1,',
' "noLogin" : false,',
' "demoMode" : false,',
' "timestamps" : true,',
' "db" : "./db.json",',
' "filesDir" : "./files/",',
' "incomingDir" : "./temp/incoming/",',
' "resDir" : "./res/",',
' "srcDir" : "./src/",',
' "tls" : {',
' "key" : "./key.pem",',
' "cert" : "./cert.pem",',
' "ca" : ["./ca1.pem", "./ca2.pem"]',
' }',
'}'
].join("\n");
module.exports = function (configFile) {
// Read & parse config.json, create it if necessary
try {
fs.statSync(configFile);
config = JSON.parse(fs.readFileSync(configFile));
} catch (error) {
if (error.code === "ENOENT") {
log.info("Creating ", chalk.magenta(path.basename(configFile)), "...");
fs.writeFileSync(configFile, defaults);
} else {
log.error("Error reading ", configFile, ":\n", error);
process.exit(1);
}
}
// Add any missing options
if (!config) config = {};
defaults = JSON.parse(defaults);
config = mergeDefaults(config, defaults);
fs.writeFileSync(configFile, JSON.stringify(config, null, 4));
// Change relative paths to absolutes during runtime
["db", "filesDir", "incomingDir", "resDir", "srcDir"].forEach(function (prop) {
if (config[prop][0] === ".") {
config[prop] = path.join(process.cwd() + config[prop].substring(1));
}
});
["cert", "key", "ca"].forEach(function (prop) {
if (config.tls[prop][0] === ".") {
config.tls[prop] = path.join(process.cwd() + config.tls[prop].substring(1));
}
});
// Special config for droppy's demo
if (process.env.NODE_ENV === "droppydemo") {
return {
"debug" : true,
"useTLS" : false,
"useSPDY" : false,
"useHSTS" : false,
"listenHost" : "0.0.0.0",
"listenPort" : 8080,
"readInterval" : 250,
"keepAlive" : 20000,
"linkLength" : 3,
"logLevel" : 3,
"maxOpen" : 256,
"zipLevel" : 1,
"demoMode" : true,
"noLogin" : true,
"timestamps" : false,
"db" : "./db.json",
"filesDir" : "./files/",
"incomingDir" : "./temp/incoming/",
"resDir" : "./res/",
"srcDir" : "./src/",
"tls" : {
"key" : "",
"cert" : "",
"ca" : "",
}
};
} else {
return config;
}
};
function mergeDefaults(options, defaults) {
for (var p in defaults) {
if (defaults.hasOwnProperty(p)) {
try {
if (typeof defaults[p] === "object" && !Array.isArray(defaults[p])) {
options[p] = mergeDefaults(options[p], defaults[p]);
} else if (options[p] === undefined) {
options[p] = defaults[p];
}
} catch (e) {
options[p] = defaults[p];
}
}
}
return options;
}
|
JavaScript
| 0.000001 |
@@ -2817,35 +2817,36 @@
debug%22 :
-tru
+fals
e,%0A %22
|
b779f8b733e254bcf04224bdf7dc40b74deaa4a1
|
fix fixed slug for order model
|
models/Order.js
|
models/Order.js
|
/* global process */
const keystone = require('keystone');
const {Types} = keystone.Field;
const {numberToMoney} = require('./my-lib/format');
const moment = require('moment');
/**
* Order Model
* ==========
*/
const Order = new keystone.List('Order', {
autokey: {
from: 'name',
path: 'slug',
unique: true
},
defaultSort: '-createdAt'
});
Order.add({
// link to products
link: {type: Types.Url, noedit: true, 'default': ''},
// product name
name: {type: String, initial: true, required: true, index: true, 'default': ''},
// user info
user: {
firstName: {type: String},
lastName: {type: String},
email: {type: String}
},
// address info
phone: {type: String},
country: {type: String},
region: {type: String},
town: {type: String},
address: {type: Types.Textarea},
postcode: {type: String},
// additional order data
additional: {type: Types.Textarea},
// product list
products: {type: Types.TextArray},
// basket items
basketItems: {type: Types.Textarea, noedit: true},
state: {
type: Types.Select,
options: [
{value: 'state-0', label: 'state 0'},
{value: 'state-1', label: 'state 1'},
{value: 'state-2', label: 'state 2'}
],
'default': 'state-0'
},
// date of create product
createdAt: {type: Date, 'default': Date.now}
});
Order.schema.pre('save', function createLink(next) {
const model = this; // eslint-disable-line no-invalid-this
const {slug} = model;
if (slug) {
model.link = keystone.get('locals').host + 'order/' + slug;
}
next();
});
Order.schema
.virtual('fullPrice')
.get(function getFullPrice() {
const order = this; // eslint-disable-line no-invalid-this
const fullPrice = JSON.parse(order.basketItems)
.reduce((accumulator, item) => accumulator + item.count * item.price, 0);
return numberToMoney(fullPrice);
});
Order.schema
.virtual('createdAtFormat')
.get(function getCreatedAtFormat() {
return moment(this.createdAt).format('DD / MM / YYYY'); // eslint-disable-line no-invalid-this
});
// disable mongo db auto index
// see https://github.com/keystonejs/keystone/wiki/Deployment-Checklist
Order.schema.set('autoIndex', process.env.IS_DEVELOPMENT); // eslint-disable-line no-process-env
/**
* Registration
*/
Order.defaultColumns = 'name user.email createdAt';
Order.register();
|
JavaScript
| 0 |
@@ -325,16 +325,37 @@
unique:
+ true,%0A fixed:
true%0A
|
6804e8d91d773ad1467b6d6919b49f0ca4215c2e
|
Remove ; symbol from lib/config module
|
lib/config.js
|
lib/config.js
|
var dcopy = require('deep-copy');
// oauth scope transform
exports.scope = function (provider, options) {
var scope = options.scope||provider.scope;
provider.scope = (scope instanceof Array)
? scope.join(provider.scope_delimiter||',')
: scope;
if (provider.linkedin) {
// LinkedIn accepts an extended "scope" parameter when obtaining a request.
// Unfortunately, it wants this as a URL query parameter, rather than encoded
// in the POST body (which is the more established and supported mechanism of
// extending OAuth).
provider.request_url = provider.request_url.replace(/(.*)\?scope=.*/,'$1');
provider.request_url += '?scope='+provider.scope;
}
}
exports.transform = function (provider, options) {
this.scope(provider, options)
}
exports.override = function (provider, options) {
var override = dcopy(provider)
for (var key in options) {
if (!options[key]) continue
override[key] = options[key]
}
return override
}
exports.dynamic = function (provider, options) {
var override = this.override(provider, options)
this.transform(override, options)
return override
}
exports.init = function (config) {
config = config||{};
// oauth configuration
var oauth = require('../config/oauth.json');
// generated below
var result = {};
// generate provider options
for (var key in oauth) {
// oauth provider settings
var provider = dcopy(oauth[key]);
// oauth application options
var options = config[key]||{};
// provider shortcuts
provider[key] = true;
provider.name = key;
provider.key = options.key;
provider.secret = options.secret;
// server options
provider.protocol = options.protocol||config.server.protocol;
provider.host = options.host||config.server.host;
provider.callback = options.callback||config.server.callback;
// oauth state
provider.state = options.state;
// custom
if (provider.google) {
provider.access_type = options.access_type;
}
if (provider.reddit) {
provider.duration = options.duration;
}
if (provider.trello) {
provider.expiration = options.expiration;
}
// overrides
var overrides = {};
for (var key in options) {
if (key != 'scope' && 'object'===typeof options[key]) {
overrides[key] = this.override(provider, options[key]);
this.transform(overrides[key], options[key]);
}
}
this.transform(provider, options);
provider.overrides = overrides;
result[provider.name] = provider;
}
return result;
}
|
JavaScript
| 0 |
@@ -26,17 +26,16 @@
p-copy')
-;
%0A%0A%0A// oa
@@ -140,25 +140,24 @@
ovider.scope
-;
%0A%0A provider
@@ -249,17 +249,16 @@
: scope
-;
%0A%0A if (
@@ -625,17 +625,16 @@
*/,'$1')
-;
%0A pro
@@ -678,17 +678,16 @@
er.scope
-;
%0A %7D%0A%7D%0A%0A
@@ -1186,17 +1186,16 @@
nfig%7C%7C%7B%7D
-;
%0A // oa
@@ -1257,17 +1257,16 @@
h.json')
-;
%0A // ge
@@ -1296,17 +1296,16 @@
ult = %7B%7D
-;
%0A%0A%0A //
@@ -1420,25 +1420,24 @@
(oauth%5Bkey%5D)
-;
%0A // oaut
@@ -1491,17 +1491,16 @@
key%5D%7C%7C%7B%7D
-;
%0A%0A //
@@ -1543,17 +1543,16 @@
%5D = true
-;
%0A pro
@@ -1567,17 +1567,16 @@
me = key
-;
%0A pro
@@ -1598,17 +1598,16 @@
ions.key
-;
%0A pro
@@ -1635,17 +1635,16 @@
s.secret
-;
%0A%0A //
@@ -1723,17 +1723,16 @@
protocol
-;
%0A pro
@@ -1776,17 +1776,16 @@
ver.host
-;
%0A pro
@@ -1841,17 +1841,16 @@
callback
-;
%0A%0A //
@@ -1896,17 +1896,16 @@
ns.state
-;
%0A%0A //
@@ -1987,17 +1987,16 @@
ess_type
-;
%0A %7D%0A
@@ -2059,25 +2059,24 @@
ons.duration
-;
%0A %7D%0A i
@@ -2143,17 +2143,16 @@
piration
-;
%0A %7D%0A%0A
@@ -2190,17 +2190,16 @@
des = %7B%7D
-;
%0A for
@@ -2342,25 +2342,24 @@
ptions%5Bkey%5D)
-;
%0A thi
@@ -2399,17 +2399,16 @@
ns%5Bkey%5D)
-;
%0A %7D
@@ -2451,17 +2451,16 @@
options)
-;
%0A pro
@@ -2486,17 +2486,16 @@
verrides
-;
%0A%0A re
@@ -2524,17 +2524,16 @@
provider
-;
%0A %7D%0A%0A
@@ -2549,8 +2549,7 @@
sult
-;
%0A%7D%0A
|
50992b57a11b13f7be25b4aaedeedf86e9b96eaf
|
add a new Topic type
|
models/Topic.js
|
models/Topic.js
|
var keystone = require('arch-keystone');
var transform = require('model-transform');
var Types = keystone.Field.Types;
var Topic = new keystone.List('Topic', {
autokey: { from: 'name', path: 'key', unique: true },
track: true,
sortable: true,
});
Topic.add({
name: { label: '專題名稱', type: String, required: true },
subtitle: { label: '副標', type: String, require: false },
state: { label: '狀態', type: Types.Select, options: 'draft, published', default: 'draft', index: true },
brief: { label: '前言', type: Types.Html, wysiwyg: true, height: 150 },
heroImage: { label: '專題主圖', type: Types.ImageRelationship, ref: 'Image' },
leading: { label: '標頭樣式', type: Types.Select, options: 'video, slideshow, image', index: true },
sections: { label: '分區', type: Types.Relationship, ref: 'Section', many: true },
heroVideo: { label: 'Leading Video', type: Types.Relationship, ref: 'Video', dependsOn: { leading: 'video' } },
heroImage: { label: '首圖', type: Types.ImageRelationship, ref: 'Image', dependsOn: { leading: 'image' } },
heroImageSize: { label: '首圖尺寸', type: Types.Select, options: 'extend, normal, small', default: 'normal', dependsOn: { heroImage: {'$regex': '.+/i'}}},
og_title: { label: 'FB分享標題', type: String, require: false},
og_description: { label: 'FB分享說明', type: String, require: false},
og_image: { label: 'FB分享縮圖', type: Types.ImageRelationship, ref: 'Image' },
isFeatured: { label: '置頂', type: Boolean, index: true },
title_style: { label: '專題樣式', type: Types.Select, options: 'feature, wide', default: 'feature', index: true },
type: { label: '型態', type: Types.Select, options: 'list, timeline, group, portrait wall', default: 'list' },
source: { label: '資料來源', type: Types.Select, options: 'posts, activities', dependsOn: { type: 'timeline' } },
sort: { label: '時間軸排序', type: Types.Select, options: 'asc, desc', dependsOn: { type: 'timeline' } },
style: { label: 'CSS', type: Types.Textarea },
tags: { label: '標籤', type: Types.Relationship, ref: 'Tag', many: true },
javascript: { label: 'javascript', type: Types.Textarea },
dfp: { label: 'DFP code', type: String, require: false},
mobile_dfp: { label: 'Mobile DFP code', type: String, require: false},
});
Topic.relationship({ ref: 'Post', refPath: 'topics' });
transform.toJSON(Topic);
Topic.register();
|
JavaScript
| 0.000001 |
@@ -1657,16 +1657,22 @@
ait wall
+, wide
', defau
|
d9255c82fd0e2816ec3063b74a90f5408a2114f4
|
Revert "Allow port to be configured by env var without prefix"
|
lib/config.js
|
lib/config.js
|
// Shamelessly stolen from JS Bin
// See http://git.io/-6YTsA
var fs = require('fs')
var path = require('path')
var _ = require('lodash')
var config = require('../config.default.json')
var md = require('markdown-it')()
var localConfig = ''
if(process.env.GKNET_CONFIG)
localConfig = path.resolve(process.cwd(), process.env.GKNET_CONFIG)
if(!fs.existsSync(localConfig))
localConfig = path.resolve(process.cwd(), 'config.local.json')
if(fs.existsSync(localConfig))
_.merge(config, require(localConfig))
function importEnvVars(collection, envPrefix) {
_.forOwn(collection, function(value, key) {
var envKey = (/port/.test(key) ? key : envPrefix + '_' + key).toUpperCase().replace(/[^a-z0-9_]+/gi, '_')
var envVal = process.env[envKey]
if(_.isNumber(value) || _.isString(value) || _.isBoolean(value) || value == null) {
if(envVal && _.isString(envVal)) {
if(/^\s*(true|on)\s*$/i.test(envVal))
envVal = true
else if(/^\s*(false|off)\s*$/i.test(envVal))
envVal = false
collection[key] = envVal
}
} else if(value && _.isPlainObject(value) && key !== 'blacklist') {
importEnvVars(value, envKey)
}
})
}
function autoRenderMarkdown(collection, shouldRender) {
_.forOwn(collection, function(value, key) {
if(shouldRender && _.isString(value))
collection[key] = md.renderInline(value)
else if(value && _.isPlainObject(value) && key !== 'blacklist')
autoRenderMarkdown(value, shouldRender || key === 'messages')
})
}
importEnvVars(config, 'GKNET')
autoRenderMarkdown(config)
module.exports = config
|
JavaScript
| 0.000001 |
@@ -658,34 +658,8 @@
ey =
- (/port/.test(key) ? key :
env
@@ -676,17 +676,16 @@
_' + key
-)
.toUpper
|
746f61e945dbe67e5c4052020dd82221908c9571
|
Update gulpfile with arrow functions.
|
gulpfile.js
|
gulpfile.js
|
'use strict';
const PORT = process.env.PORT || 3000;
const SOURCE_DIR = './src';
const BUILD_DIR = 'dist';
const _ = require('lodash');
const babelify = require('babelify');
const brfs = require( 'brfs' );
const browserify = require('browserify');
const browserSync = require('browser-sync').create();
const del = require('del');
const runSequence = require('run-sequence');
const source = require('vinyl-source-stream');
const watchify = require('watchify');
const gulp = require('gulp');
const $ = require('gulp-load-plugins')();
function onError(error) {
$.util.log(error.message);
this.emit('end');
}
gulp.task('browser-sync', function() {
return browserSync.init({
browser: [],
port: PORT,
server: {
baseDir: './' + BUILD_DIR
}
});
});
gulp.task('js', function() {
const bundler = watchify(browserify(SOURCE_DIR + '/js/index.js',
_.assign({
debug: true
}, watchify.args)));
bundler
.transform(babelify)
.transform(brfs);
function rebundle() {
return bundler.bundle()
.on('error', onError)
.pipe(source('bundle.js'))
.pipe(gulp.dest(BUILD_DIR))
.pipe(browserSync.reload({stream: true}));
}
bundler
.on('log', $.util.log)
.on('update', rebundle);
return rebundle();
});
gulp.task('html', function() {
return gulp.src(SOURCE_DIR + '/*.html')
.pipe(gulp.dest(BUILD_DIR))
.pipe(browserSync.reload({stream: true}));
});
gulp.task('watch', function() {
gulp.watch([SOURCE_DIR + '/*.html'], ['html']);
});
gulp.task('clean', del.bind(null, [BUILD_DIR]));
gulp.task('default', ['clean'], function(cb) {
return runSequence(
['html', 'js'],
['browser-sync', 'watch'],
cb
);
});
|
JavaScript
| 0 |
@@ -634,26 +634,21 @@
-sync',
-function()
+() =%3E
%7B%0A ret
@@ -782,26 +782,21 @@
k('js',
-function()
+() =%3E
%7B%0A con
@@ -1286,26 +1286,21 @@
'html',
-function()
+() =%3E
%7B%0A ret
@@ -1435,128 +1435,111 @@
sk('
-watch', function() %7B%0A gulp.watch(%5BSOURCE_DIR + '/*.html'%5D, %5B'html'%5D);%0A%7D);%0A%0Agulp.task('clean', del.bind(null, %5BBUILD_DIR
+clean', () =%3E del(%5BBUILD_DIR%5D));%0A%0Agulp.task('watch', () =%3E gulp.watch(%5BSOURCE_DIR + '/*.html'%5D, %5B'html'
%5D));
@@ -1576,20 +1576,13 @@
'%5D,
-function(cb)
+cb =%3E
%7B%0A
|
7b3e04cfcca898d796035a43e1eae24bd4c3746e
|
fix houndci error
|
gulpfile.js
|
gulpfile.js
|
const gulp = require('gulp'),
eslint = require('gulp-eslint'),
spawn = require('child_process').spawn,
connect = require('gulp-connect');
const paths = {
jsFiles: ['./src/inverted-index.js'],
htmlFiles: '*.html',
cssFiles: 'public/css/*.css',
scriptFiles: 'public/js/*.js',
testFiles: 'jasmine/spec/inverted-index-test.js',
specRunner: 'jasmine/specRunner.html'
};
// lint
gulp.task('lint', () => {
gulp.src(paths.jsFiles)
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
// serve
gulp.task('serve', () => {
const options = {
root: './',
livereload: true,
port: process.env.port || 3000
};
connect.server(options);
});
// watch
gulp.task('watch', () => {
gulp.watch(paths.jsFiles, ['reloadServer']);
gulp.watch(paths.htmlFiles, ['reloadServer']);
gulp.watch(paths.cssFiles, ['reloadServer']);
gulp.watch(paths.scriptFiles, ['reloadServer']);
});
// reload
gulp.task('reloadServer', () => {
gulp.src(['*.html', 'public/css/*.css', 'public/js/*.js', 'src/*.js'])
.pipe(connect.reload());
});
// test
gulp.task('test', () => {
spawn('node_modules/karma/bin/karma', ['start', '--single-run'], {
stdio: 'inherit'
}).on('close', process.exit);
});
gulp.task('testWatch', () => {
gulp.watch(paths.testFiles, ['testReload']);
});
gulp.task('testReload', () => {
gulp.src(paths.specRunner)
.pipe(connect.reload());
});
gulp.task('default', ['reloadServer', 'testWatch', 'testReload', 'serve', 'watch']);
|
JavaScript
| 0.000001 |
@@ -25,21 +25,22 @@
lp'),%0A
-eslin
+connec
t = requ
@@ -49,21 +49,22 @@
e('gulp-
-eslin
+connec
t'),%0A s
@@ -100,30 +100,29 @@
').spawn,%0A
-connec
+eslin
t = require(
@@ -127,22 +127,21 @@
e('gulp-
-connec
+eslin
t');%0A%0Aco
|
d18cbd41361ac0894934a19c401b9d5db402d703
|
remove unused logic
|
lib/config.js
|
lib/config.js
|
'use strict'
var os = require('os')
var bool = require('normalize-bool')
var OPTS_MATRIX = [
['appId', 'APP_ID'],
['organizationId', 'ORGANIZATION_ID'],
['secretToken', 'SECRET_TOKEN'],
['active', 'ACTIVE', true],
['logLevel', 'LOG_LEVEL', 'info'],
['hostname', 'HOSTNAME', os.hostname()],
['stackTraceLimit', 'STACK_TRACE_LIMIT', Infinity],
['captureExceptions', 'CAPTURE_EXCEPTIONS', true],
['exceptionLogLevel', 'EXCEPTION_LOG_LEVEL', 'fatal'],
['filterHttpHeaders', 'FILTER_HTTP_HEADERS', true],
['captureTraceStackTraces', 'CAPTURE_TRACE_STACK_TRACES', true],
['logBody', 'LOG_BODY', false],
['timeout', 'TIMEOUT', true],
['timeoutErrorThreshold', 'TIMEOUT_ERROR_THRESHOLD', 25000],
['instrument', 'INSTRUMENT', true],
['ff_captureFrame', 'FF_CAPTURE_FRAME', false]
]
var BOOL_OPTS = [
'active',
'captureExceptions',
'filterHttpHeaders',
'captureTraceStackTraces',
'logBody',
'timeout',
'instrument',
'ff_captureFrame'
]
module.exports = function (opts) {
opts = opts || {}
var result = {
ignoreUrlStr: [],
ignoreUrlRegExp: [],
ignoreUserAgentStr: [],
ignoreUserAgentRegExp: [],
_apiHost: opts._apiHost || 'intake.opbeat.com',
_apiPort: opts._apiPort,
_apiSecure: opts._apiSecure
}
OPTS_MATRIX.forEach(function (opt) {
var key = opt[0]
var env, val
if (opt[1]) env = 'OPBEAT_' + opt[1]
if (key in opts) {
val = opts[key]
} else if (env && env in process.env) {
val = process.env[env]
} else if (typeof opt[2] === 'function') {
val = opt[2](result)
} else if (opt.length === 3) {
val = opt[2]
}
if (~BOOL_OPTS.indexOf(key)) val = bool(val)
if (val !== undefined) result[key] = val
})
if (opts.ignoreUrls) {
opts.ignoreUrls.forEach(function (ptn) {
if (typeof ptn === 'string') result.ignoreUrlStr.push(ptn)
else result.ignoreUrlRegExp.push(ptn)
})
}
if (opts.ignoreUserAgents) {
opts.ignoreUserAgents.forEach(function (ptn) {
if (typeof ptn === 'string') result.ignoreUserAgentStr.push(ptn)
else result.ignoreUserAgentRegExp.push(ptn)
})
}
return result
}
|
JavaScript
| 0.000587 |
@@ -1338,34 +1338,8 @@
var
- env, val%0A%0A if (opt%5B1%5D)
env
@@ -1359,16 +1359,28 @@
+ opt%5B1%5D
+%0A var val
%0A%0A if
@@ -1441,15 +1441,8 @@
env
-&& env
in p
@@ -1488,82 +1488,8 @@
nv%5D%0A
- %7D else if (typeof opt%5B2%5D === 'function') %7B%0A val = opt%5B2%5D(result)%0A
|
5b642e5702bcccf50626e23130a7c3a74b1215d6
|
Add PHP running to gulp
|
gulpfile.js
|
gulpfile.js
|
"use strict";
var fs = require("fs");
var gulp = require("gulp");
var plugins = require("gulp-load-plugins")();
var json = JSON.parse(fs.readFileSync("./package.json"));
var browserSync = require('browser-sync');
var reload = browserSync.reload;
var args = require('yargs').argv;
var config = (function () {
var appName = json.name;
var path = {
bower: "./bower_components/",
assets: "./assets",
static: "./static"
};
return {
path: path,
scss: {
input: [ path.assets + "/scss/style.scss" ],
include: [
path.bower + "/bootstrap-sass/assets/stylesheets",
path.bower + "/font-awesome/scss",
path.assets + "/scss/"
],
output: path.static + "/css",
watch: [ path.assets + "/scss/**.scss" ]
},
fonts: {
input: [
path.bower + "/font-awesome/fonts/**.*",
path.assets + "/fonts/**/*.*"
],
output: path.static + "/fonts"
},
script: {
input: [
path.bower + "/jquery/dist/jquery.js",
path.bower + "/imagesloaded/imagesloaded.pkgd.js",
path.bower + "/masonry/dist/masonry.pkgd.js",
path.bower + "/bootstrap-sass/assets/javascripts/bootstrap.js",
path.assets + "/js/*.js"
],
output: {
dir: path.static + "/js",
filename: "script.js"
},
watch: [ path.assets + "/js/*.js" ]
},
images: {
input: [ path.assets + "/images/**" ],
output: path.static + "/images",
watch: [ path.assets + "/images/**" ]
}
};
}());
gulp.task("bower", function () {
return plugins.bower(config.path.bower);
});
gulp.task("fonts", function () {
return gulp.src(config.fonts.input)
.pipe(require('gulp-debug')())
.pipe(gulp.dest(config.fonts.output));
});
gulp.task("js", function () {
return gulp.src(config.script.input)
.pipe(plugins.concat(config.script.output.filename))
.pipe(gulp.dest(config.script.output.dir))
.pipe(reload({ stream:true }))
.pipe(plugins.uglify())
.pipe(plugins.rename({extname: ".min.js"}))
.pipe(gulp.dest(config.script.output.dir))
.pipe(reload({ stream:true }))
});
gulp.task("scss", function () {
return gulp.src(config.scss.input)
.pipe(plugins.sass({
style: "expanded",
includePaths: config.scss.include
}))
.pipe(plugins.autoprefixer())
.pipe(gulp.dest(config.scss.output))
.pipe(reload({ stream:true }))
.pipe(plugins.rename({extname: ".min.css"}))
.pipe(plugins.minifyCss())
.pipe(gulp.dest(config.scss.output))
.pipe(reload({ stream:true }));
});
gulp.task('images', function (){
return gulp.src(config.images.input)
.pipe(plugins.imagemin())
.pipe(gulp.dest(config.images.output))
.pipe(reload({ stream:true }));
});
gulp.task('serve', function (){
browserSync({
proxy: args.host || 'localhost:8000'
});
});
gulp.task('config', function (){
console.log(config);
})
gulp.task("watch", ['serve'], function () {
config.scss.watch.forEach(function (path) {
gulp.watch(path, ["scss"]);
});
config.script.watch.forEach(function (path) {
gulp.watch(path, ["js"]);
});
config.images.watch.forEach(function (path) {
gulp.watch(path, ["images"]);
});
});
gulp.task("build", ["bower", "fonts", "js", "scss", "images"])
gulp.task("default", ["js", "scss", "watch"]);
|
JavaScript
| 0.000001 |
@@ -273,16 +273,60 @@
).argv;%0A
+var spawn = require('child_process').spawn;%0A
%0A%0Avar co
@@ -2654,16 +2654,17 @@
k('serve
+r
', funct
@@ -2671,16 +2671,255 @@
ion ()%7B%0A
+%09var host = args.host %7C%7C 'localhost:8015';%0A%09spawn('php', %5B'-S', host, '-t', '.'%5D, %7B%0A%09%09detached: false,%0A%09%09stdio: 'inherit',%0A%09%09env: process.env%0A%09%7D);%0A%7D);%0A%0Agulp.task('proxy', %5B'server'%5D, function ()%7B%0A%09var host = args.host %7C%7C 'localhost:8015';%0A
%09browser
@@ -2960,18 +2960,18 @@
lhost:80
-00
+15
'%0A%09%7D);%0A%7D
@@ -3053,21 +3053,21 @@
tch%22, %5B'
-serve
+proxy
'%5D, func
|
b51cb1c2097fe01026522554d0d7e02ecc692096
|
rename auto_reconnect
|
models/index.js
|
models/index.js
|
var config = require("config");
var mongoose = require("mongoose");
/**
* 连接数据库。
*/
function connectDB(callback)
{
mongoose.connect(
config.db,
{
server: {
auto_reconnect: config.autoReconnect,
poolSize: config.poolSize
},
},
callback
);
}
/**
* 检查是否已连接数据库。
*/
function connected()
{
return mongoose.connection.db != null;
}
exports.connected = connected;
exports.connectDB = connectDB;
exports.Story = require("./story");
|
JavaScript
| 0.000003 |
@@ -232,9 +232,10 @@
auto
-R
+_r
econ
|
be2a49610679b75f30f0a2e18b2e6caf80862d7f
|
Fix path coverage
|
gulpfile.js
|
gulpfile.js
|
/* eslint-env node */
/* eslint strict: ["error", "global"] */
'use strict';
var coveralls = require('gulp-coveralls'),
eslint = require('gulp-eslint'),
excludeGitignore = require('gulp-exclude-gitignore'),
gulp = require('gulp'),
istanbul = require('gulp-istanbul'),
mocha = require('gulp-mocha'),
nsp = require('gulp-nsp'),
path = require('path'),
plumber = require('gulp-plumber');
gulp.task('eslint', function() {
return gulp.src([
'**/*.js',
'!app/templates/gulpfile.js',
'!app/templates/src/scripts/settings/call_plugins.js'
])
.pipe(excludeGitignore())
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
});
gulp.task('nsp', function(cb) {
return nsp({package: path.resolve('package.json')}, cb);
});
gulp.task('istanbul', function() {
return gulp.src('app/index.js')
.pipe(excludeGitignore())
.pipe(istanbul({
includeUntested: true
}))
.pipe(istanbul.hookRequire());
});
gulp.task('mocha', ['istanbul'], 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('coveralls', ['mocha'], function() {
console.log(process.env);
if (!process.env.CI) {
return;
}
return gulp.src(path.join(__dirname, 'coverage/lcov.info'))
.pipe(coveralls());
});
gulp.task('test', ['nsp', 'eslint', 'mocha', 'coveralls']);
gulp.task('watch-test', function() {
gulp.watch(['app/index.js', 'test/**/*.js'], ['mocha']);
});
|
JavaScript
| 0.000006 |
@@ -1431,38 +1431,8 @@
) %7B%0A
- console.log(process.env);%0A
@@ -1501,29 +1501,8 @@
src(
-path.join(__dirname,
'cov
@@ -1518,17 +1518,16 @@
v.info')
-)
%0A .pi
|
27a7d1e87184a445c33faee3919259f91ad6b125
|
modify task name
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp'),
ghPages = require('gulp-gh-pages'),
webserver = require('gulp-webserver');
gulp.task('server', function() {
gulp.src('./src/')
.pipe(webserver({
livereload: true,
open: true
}));
});
// Rerun the task when a file changes
gulp.task('watch', function() {
gulp.watch(['src/js/**/*.js','src/index.html']);
});
gulp.task('gh-pages', () => {
return gulp.src('./src/**/*')
.pipe(ghPages({
remoteUrl: "https://github.com/naoyashiga/my-dying-message"
}));
});
gulp.task('default', ['watch','server']);
|
JavaScript
| 0.99999 |
@@ -380,24 +380,22 @@
p.task('
-gh-pages
+deploy
', () =%3E
|
86be7e5a09a123cb5a4024ec6bc218fe5400ca11
|
optimise templating, add data file
|
gulpfile.js
|
gulpfile.js
|
'use strict';
var gulp = require('gulp'),
$ = require('gulp-load-plugins')({pattern: '*'}),
del = require('del'),
runSequence = require('run-sequence'),
browserSync = require('browser-sync'),
reload = browserSync.reload;
// file source and destination variables
// HTML & nunjucks files
var nunjucksSrc = 'source/pages/**/*.+(html|nunjucks)';
// Images
var imgSrc = 'source/img/**/*';
var imgDest = 'build/img';
// Stylesheets
var cssSrc = 'source/stylus/*.styl';
var cssDest = 'build/css';
// Sripts
var jsSrc = 'source/js/*.js';
var jsDest = 'build/js';
var jsVendorSrc = 'source/js/vendor/*.js';
var jsVendorDest = 'build/js/vendor';
// Handle errors
function handleError(err) {
console.log(err.toString());
this.emit('end');
}
var AUTOPREFIXER_BROWSERS = [
'ie >= 10',
'ie_mob >= 10',
'ff >= 30',
'chrome >= 34',
'safari >= 7',
'opera >= 23',
'ios >= 7',
'android >= 4.4',
'bb >= 10'
];
// Static Server + watching stylus/html/js/image files
gulp.task('serve', ['build'], function() {
browserSync.init({
notify: false,
server: "./build"
});
gulp.watch("source/img/**/*", ['images'], reload);
gulp.watch("source/stylus/**/*.styl", ['css']);
gulp.watch("source/pages/*.+(html|nunjucks)", ['nunjucks']);
gulp.watch("source/templates/*.+(html|nunjucks)", ['nunjucks']);
gulp.watch("source/js/*.js", ['scripts']);
gulp.watch("source/js/vendor/*.js", ['scripts-vendor']);
});
// Compile Stylus into CSS, add vendor prefixes & auto-inject into browser
gulp.task('css', function() {
return gulp.src(cssSrc)
.pipe($.plumber({errorHandler: handleError}))
.pipe($.newer(cssDest))
.pipe($.stylus({
compress: true,
paths: ['source/stylus']
}))
.pipe($.autoprefixer({browsers: AUTOPREFIXER_BROWSERS}))
.pipe($.rename('master.css'))
.pipe(gulp.dest(cssDest))
.pipe(browserSync.stream());
});
// Concatenate scripts (we don't minify these)
gulp.task('scripts', function() {
return gulp.src(jsSrc)
.pipe($.newer(jsSrc))
.pipe($.concat('main.js')) // concat pulls all our files together before minifying them
.pipe(gulp.dest(jsDest))
.pipe(reload({
stream: true
}));
});
// Copy and optimise images from source to build
gulp.task('images', function() {
return gulp.src(imgSrc)
.pipe($.newer(imgDest))
.pipe($.imagemin({
optimizationLevel: 7,
progressive: true,
interlaced: true,
multipass: true,
svgoPlugins: [{
removeViewBox: true
}]
}))
.pipe(gulp.dest(imgDest))
.pipe($.size({
title: 'images'
}));
});
// Copy changed vendor scripts to build dir
gulp.task('scripts-vendor', function() {
return gulp.src(jsVendorSrc)
.pipe($.newer(jsVendorDest))
.pipe(gulp.dest(jsVendorDest))
.pipe($.browserSync.reload({
stream: true
}));
});
// compile nunjucks templates
$.nunjucksRender.nunjucks.configure(['source/templates/'], {watch: false});
gulp.task('nunjucks', function() {
return gulp.src(nunjucksSrc)
.pipe($.plumber({errorHandler: handleError}))
.pipe($.nunjucksRender())
.pipe(gulp.dest('build'))
.pipe($.browserSync.reload({
stream: true
}));
});
// gulp.task('clean', function() {
// $.del(['build/'] );
// });
gulp.task('clean', del.bind(null, 'build/*', {
dot: true
}));
gulp.task('build', function(callback) {
runSequence('clean', ['nunjucks', 'images', 'scripts', 'scripts-vendor', 'css'],
callback);
});
gulp.task('default', ['serve']);
|
JavaScript
| 0 |
@@ -1308,32 +1308,20 @@
pages/*.
-+(
html
-%7Cnunjucks)
%22, %5B'nun
@@ -1363,31 +1363,24 @@
lates/*.
-+(html%7C
nunjucks
)%22, %5B'nu
@@ -1371,17 +1371,16 @@
nunjucks
-)
%22, %5B'nun
@@ -2918,16 +2918,17 @@
);%0A%7D);%0A%0A
+%0A
// compi
@@ -3133,32 +3133,144 @@
handleError%7D))%0A
+ // add data nunjucksRender%0A .pipe($.data(function() %7B%0A return require('./source/data.json')%0A %7D))%0A
.pipe($.nunj
|
1ab62e534829b2cc692bb0ab26f38bf58adb4bf4
|
Fix gulp docs task
|
gulpfile.js
|
gulpfile.js
|
/* jshint node: true */
"use strict";
var gulp = require("gulp");
var jshint = require("gulp-jshint");
var jscs = require("gulp-jscs");
var plumber = require("gulp-plumber");
var purescript = require("gulp-purescript");
var run = require("gulp-run");
var rimraf = require("rimraf");
var sources = [
"src/**/*.purs",
"bower_components/purescript-*/src/**/*.purs"
];
var foreigns = [
"src/**/*.js",
"bower_components/purescript-*/src/**/*.js"
];
var testSources = ["tests/Tests.purs"].concat(sources);
var testForeigns = ["tests/Tests.js"].concat(foreigns);
gulp.task("clean-docs", function (cb) {
rimraf("docs", cb);
});
gulp.task("clean-output", function (cb) {
rimraf("output", cb);
});
gulp.task("clean", ["clean-docs", "clean-output"]);
gulp.task("make", ["lint"], function() {
return purescript.psc({ src: sources, ffi: foreigns });
});
gulp.task("test", ["test-make"], function() {
require("./tmp/index");
});
gulp.task("test-make", ["test-copy"], function() {
return purescript.psc({ src: testSources, ffi: testForeigns });
});
gulp.task("test-copy", function() {
gulp.src("output/**/*js")
.pipe(gulp.dest("tmp/node_modules/"));
gulp.src("js/index.js")
.pipe(gulp.dest("tmp/"));
});
gulp.task("docs", ["clean-docs"], function () {
return gulp.src(sources)
.pipe(plumber())
.pipe(purescript.pscDocs({
docgen: {
"Data.DOM.Simple.Ajax" : "docs/Data/DOM/Simple/Ajax.md",
"Data.DOM.Simple.Document" : "docs/Data/DOM/Simple/Document.md",
"Data.DOM.Simple.Element" : "docs/Data/DOM/Simple/Element.md",
"Data.DOM.Simple.Encode" : "docs/Data/DOM/Simple/Encode.md",
"Data.DOM.Simple.Events" : "docs/Data/DOM/Simple/Events.md",
"Data.DOM.Simple.Navigator" : "docs/Data/DOM/Simple/Navigator.md",
"Data.DOM.Simple.NodeList" : "docs/Data/DOM/Simple/NodeList.md",
"Data.DOM.Simple.Sugar" : "docs/Data/DOM/Simple/Sugar.md",
"Data.DOM.Simple.Types" : "docs/Data/DOM/Simple/Types.md",
"Data.DOM.Simple.Window" : "docs/Data/DOM/Simple/Window.md",
"Data.DOM.Simple.Unsafe.Ajax" : "docs/Data/DOM/Simple/Unsafe/Ajax.md",
"Data.DOM.Simple.Unsafe.Document" : "docs/Data/DOM/Simple/Unsafe/Document.md",
"Data.DOM.Simple.Unsafe.Element" : "docs/Data/DOM/Simple/Unsafe/Element.md",
"Data.DOM.Simple.Unsafe.Events" : "docs/Data/DOM/Simple/Unsafe/Events.md",
"Data.DOM.Simple.Unsafe.Navigator" : "docs/Data/DOM/Simple/Unsafe/Navigator.md",
"Data.DOM.Simple.Unsafe.NodeList" : "docs/Data/DOM/Simple/Unsafe/NodeList.md",
"Data.DOM.Simple.Unsafe.Sugar" : "docs/Data/DOM/Simple/Unsafe/Sugar.md",
"Data.DOM.Simple.Unsafe.Window" : "docs/Data/DOM/Simple/Unsafe/Window.md"
}
}));
});
gulp.task("dotpsci", function () {
return gulp.src(sources)
.pipe(plumber())
.pipe(purescript.dotPsci());
});
gulp.task("lint", function() {
return gulp.src("src/**/*.js")
.pipe(jshint())
.pipe(jshint.reporter())
.pipe(jscs());
});
gulp.task("default", ["make", "test", "docs", "dotpsci"]);
|
JavaScript
| 0.003267 |
@@ -1287,57 +1287,8 @@
urn
-gulp.src(sources)%0A .pipe(plumber())%0A .pipe(
pure
@@ -1303,16 +1303,36 @@
scDocs(%7B
+%0A src: sources,
%0A d
@@ -2858,17 +2858,16 @@
%7D%0A %7D)
-)
;%0A%7D);%0A%0Ag
|
43a7e7daea08474785da4867db5cf26769b7a887
|
Remove unneccessary comma
|
gulpfile.js
|
gulpfile.js
|
/*
* Copyright (C) 2022 con terra GmbH ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
const gulp = require("gulp");
const mapapps = require('ct-mapapps-gulp-js');
mapapps.registerTasks({
/* A detailed description of available setting is available at https://www.npmjs.com/package/ct-mapapps-gulp-js */
/* a list of themes inside this project */
themes: [/*"sample-theme"*/],
/* state that the custom theme will be dependant from map.apps everlasting theme that provides the base styles */
hasBaseThemes: true,
/* state that we want to support vuetify components and therefore need the vuetify core styles*/
hasVuetify: true,
/*themeChangeTargets: {
"vuetify": [
"sample_theme"
]
}*/
});
gulp.task("default",
gulp.series(
"copy-resources",
"themes-copy",
gulp.parallel(
//"js-lint",
//"style-lint",
"js-transpile",
"themes-compile"
)
)
);
gulp.task("compress",
gulp.series(
"default",
"themes-compress"
)
);
|
JavaScript
| 0.999993 |
@@ -1180,25 +1180,24 @@
uetify: true
-,
%0A /*theme
|
d73c91a3fbb88c932708e5f5773c8f25efca27b5
|
Change concat module to use plugins namespace
|
gulpfile.js
|
gulpfile.js
|
/*jslint node: true */
'use strict';
// Gulp
var gulp = require('gulp'),
plugins = require('gulp-load-plugins')({
rename: {
'gulp-compile-handlebars' : 'handlebars',
'gulp-sass-generate-contents' : 'sgc'
}
}),
gulpif = require('gulp-if'),
// Utilities
argv = require('yargs').argv,
// zip = require('gulp-zip'),
// sourcemaps = require('gulp-sourcemaps'),
runSeq = require('run-sequence'),
// rename = require('gulp-rename'),
concat = require('gulp-concat'),
// Javascript
uglify = require('gulp-uglify'),
jshint = require('gulp-jshint'),
// Templates
// handlebars = require('gulp-compile-handlebars'),
// CSS
minifyCss = require('gulp-minify-css'),
autoprefixer = require('autoprefixer-core'),
// sgc = require('gulp-sass-generate-contents'),
postcss = require('gulp-postcss'),
pixrem = require('gulp-pixrem'),
// Images
// imagemin = require('gulp-imagemin'),
pngquant = require('imagemin-pngquant'),
// Configuration
config = require('./_config/project.json'),
templateDataJson = require('./_config/templateData.json'),
templateHelpers = require('./_config/templateHelpers.js')(),
jshintConfig = require('./_config/jshint.json'),
creds = require('./_config/creds.json'),
itcss = require('./_config/itcss'),
destStyles = config.src + '/' + config.dirs.styles;
/* ============================================================ *\
SCRIPTS JS / lint, concat and minify scripts
\* ============================================================ */
gulp.task('scripts', function(){
return gulp.src([config.src + '/' + config.dirs.scripts + '/**/*.js'])
.pipe(gulpif(argv.prod, jshint(jshintConfig))) //Default only
.pipe(concat('bundle.js'))
.pipe(gulpif(argv.prod, uglify())) //Production only
.pipe(gulp.dest(config.dest + '/' + config.dirs.scripts));
});
/* ============================================================ *\
GENERATE SASS IMPORTS AND
\* ============================================================ */
gulp.task('sass-generate-contents', function () {
return gulp.src(itcss())
.pipe(plugins.sgc(destStyles + '/main.scss', creds))
.pipe(gulp.dest(destStyles));
});
/* ============================================================ *\
STYLES / SCSS
\* ============================================================ */
gulp.task('sass', function () {
return gulp.src(destStyles + '/main.scss')
.pipe(gulpif(!argv.prod, plugins.sourcemaps.init())) //Default only
.pipe(plugins.sass({ errLogToConsole: true, includePaths: [config.dirs.components], outputStyle: 'compact' }))
.pipe(postcss([autoprefixer({ browsers: ['> 5%', 'Android 3'] })]))
.pipe(plugins.pixrem(config.pixelBase))
.pipe(gulpif(!argv.prod, plugins.sourcemaps.write('.'))) //Default only
.pipe(plugins.pixrem(config.pixelBase))
.pipe(gulpif(argv.prod, minifyCss())) //Production only
.pipe(gulp.dest(config.dest + '/' + config.dirs.styles));
});
/* ============================================================ *\
IMAGES / minify images
\* ============================================================ */
gulp.task('imagemin', function () {
return gulp.src(config.src + '/' + config.dirs.images + '/**/*')
.pipe(gulpif(argv.prod, plugins.imagemin({
progressive: true,
svgoPlugins: [{removeViewBox: false}],
use: [pngquant()]
}))) //Production only
.pipe(gulp.dest(config.dest + '/' + config.dirs.images));
});
/* ============================================================ *\
MOVE / Copy files
\* ============================================================ */
gulp.task('copy:fonts', function(){
return gulp.src([config.src + '/' + config.dirs.fonts + '/**/*'])
.pipe(gulp.dest(config.dest + '/' + config.dirs.fonts));
})
gulp.task('copy', function(){
return gulp.src(['!' + config.dest + '/styles', '!' + config.dest + '/styles/*.map', config.dest + '/**/*'])
.pipe(gulp.dest(config.build));
})
/* ============================================================ *\
PACKAGE THE FOLDER UP
\* ============================================================ */
gulp.task('package-release', function () {
var d = new Date();
var packageName = creds.packageName + '' + d.getDay() + '.' + d.getMonth() + '.' + d.getFullYear() + '_' + d.getHours() + '.' + d.getMinutes();
return gulp.src('build/**/*')
.pipe(plugins.zip(packageName + '.zip'))
.pipe(gulp.dest('release'));
});
/* ============================================================ *\
COMPILE TEMPLATES / HTML
\* ============================================================ */
gulp.task('compile-html', function () {
var templateData = {
data: templateDataJson
},
options = {
batch : ['./views/_partials'],
helpers: templateHelpers
}
return gulp.src(['./views/*.hbs'])
.pipe(plugins.handlebars(templateData, options))
.pipe(plugins.rename({extname: '.html'}))
.pipe(gulp.dest('build'));
});
/* ============================================================ *\
MAIN TASKS
\* ============================================================ */
gulp.task('watch:sass', function () {
gulpif(!argv.prod, gulp.watch([config.src + '/' + config.dirs.styles + '/**/*.scss', config.dirs.components + '/**/*.scss'], ['sass']));
});
gulp.task('watch:js', function () {
gulpif(!argv.prod, gulp.watch([config.src + '/' + config.dirs.scripts + '/**/*.js', config.dirs.components + '/**/*.js'], ['scripts']));
});
gulp.task('watch', function (cb) {
runSeq(['watch:sass', 'watch:js'], cb);
});
gulp.task('build', function (cb) {
runSeq(['default'], ['copy'], ['compile-html'], cb);
});
gulp.task('release', function (cb) {
runSeq(['build'], ['package-release'], cb);
});
gulp.task('default', function (cb) {
runSeq(['sass-generate-contents'],['sass', 'scripts', 'copy:fonts', 'imagemin'], cb);
});
|
JavaScript
| 0 |
@@ -555,16 +555,19 @@
ame'),%0A%09
+//
concat
@@ -1920,16 +1920,24 @@
%09%09.pipe(
+plugins.
concat('
|
132bf484c15d1f24681d32bee49ae1ffd0c095d0
|
Fix position is out of bounds on edges
|
models/pixel.js
|
models/pixel.js
|
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');
var colourPieceValidator = function(c) {
return Number.isInteger(c) && c >= 0 && c <= 255;
}
var PixelSchema = new Schema({
xPos: {
type: Number,
required: true,
validate: {
validator: Number.isInteger,
message: '{VALUE} is not an integer value'
}
},
yPos: {
type: Number,
required: true,
validate: {
validator: Number.isInteger,
message: '{VALUE} is not an integer value'
}
},
editorID: {
type: Schema.ObjectId,
required: true
},
lastModified: {
type: Date,
required: true
},
colourR: {
type: Number,
required: true,
validate: {
validator: colourPieceValidator,
message: '{VALUE} is not a valid colour'
}
},
colourG: {
type: Number,
required: true,
validate: {
validator: colourPieceValidator,
message: '{VALUE} is not a valid colour'
}
},
colourB: {
type: Number,
required: true,
validate: {
validator: colourPieceValidator,
message: '{VALUE} is not a valid colour'
}
}
});
PixelSchema.methods.toInfo = function() {
return {
point: {
x: this.xPos,
y: this.yPos
},
editorID: this.editorID,
modified: this.lastModified,
colour: {
r: this.colourR,
g: this.colourG,
b: this.colourB
}
}
}
PixelSchema.statics.addPixel = function(colour, x, y, userID, callback) {
x = parseInt(x), y = parseInt(y);
if(isNaN(x) || isNaN(y)) return callback(null, { message: "Invalid positions provided." });
// TODO: Get actual position below:
if(x <= 0 || y <= 0 || x > 999 || y > 999) return callback(null, { message: "Position is out of bounds." });
this.findOneAndUpdate({
xPos: x,
yPos: y
}, {
editorID: userID,
colourR: colour.r,
colourG: colour.g,
colourB: colour.b,
lastModified: Date()
}, {
upsert: true
}, function(err, pixel) {
if (err) return callback(null, { message: "An error occurred while trying to place the pixel." });
var wasIdentical = colour.r == 255 && colour.g == 255 && colour.b == 255; // set to identical if pixel was white
if(pixel) { // we have data from the old pixel
wasIdentical = pixel.colourR == colour.r && pixel.colourG == colour.g && pixel.colourB; // set to identical if colour matched old pixel
}
return callback(!wasIdentical, null);
});
}
PixelSchema.methods.getInfo = function() {
return new Promise((resolve, reject) => {
require("./user").findById(this.editorID).then(user => {
let info = this.toInfo();
info.editor = user.toInfo();
resolve(info);
}).catch(err => reject(err));
})
}
PixelSchema.statics.getAllPixels = function() {
return new Promise((resolve, reject) => {
this.find({}, function(err, pixels) {
if (!pixels) return reject(err);
let info = pixels.map(pixel => pixel.toInfo())
resolve(info)
});
});
}
module.exports = mongoose.model('Pixel', PixelSchema);
|
JavaScript
| 0.000047 |
@@ -1933,17 +1933,16 @@
if(x %3C
-=
0 %7C%7C y
@@ -1942,17 +1942,16 @@
0 %7C%7C y %3C
-=
0 %7C%7C x
@@ -1955,23 +1955,27 @@
x %3E
- 999
+= 1000
%7C%7C y %3E
- 999
+= 1000
) re
|
a8dd85d21e0852f94b449679e6d5b7571a95bd0e
|
Fix keep nick setting nick to undefined on socket close
|
src/plugins/irc-events/connection.js
|
src/plugins/irc-events/connection.js
|
"use strict";
const _ = require("lodash");
const log = require("../../log");
const Msg = require("../../models/msg");
const Chan = require("../../models/chan");
const Helper = require("../../helper");
module.exports = function(irc, network) {
const client = this;
network.channels[0].pushMessage(
client,
new Msg({
text: "Network created, connecting to " + network.host + ":" + network.port + "...",
}),
true
);
irc.on("registered", function() {
if (network.irc.network.cap.enabled.length > 0) {
network.channels[0].pushMessage(
client,
new Msg({
text: "Enabled capabilities: " + network.irc.network.cap.enabled.join(", "),
}),
true
);
}
// Always restore away message for this network
if (network.awayMessage) {
irc.raw("AWAY", network.awayMessage);
// Only set generic away message if there are no clients attached
} else if (client.awayMessage && _.size(client.attachedClients) === 0) {
irc.raw("AWAY", client.awayMessage);
}
let delay = 1000;
if (Array.isArray(network.commands)) {
network.commands.forEach((cmd) => {
setTimeout(function() {
client.input({
target: network.channels[0].id,
text: cmd,
});
}, delay);
delay += 1000;
});
}
network.channels.forEach((chan) => {
if (chan.type !== Chan.Type.CHANNEL) {
return;
}
setTimeout(function() {
network.irc.join(chan.name, chan.key);
}, delay);
delay += 1000;
});
});
irc.on("socket connected", function() {
network.prefixLookup = {};
irc.network.options.PREFIX.forEach(function(mode) {
network.prefixLookup[mode.mode] = mode.symbol;
});
network.channels[0].pushMessage(
client,
new Msg({
text: "Connected to the network.",
}),
true
);
sendStatus();
});
irc.on("close", function() {
network.channels[0].pushMessage(
client,
new Msg({
text:
"Disconnected from the network, and will not reconnect. Use /connect to reconnect again.",
}),
true
);
});
let identSocketId;
irc.on("raw socket connected", function(socket) {
let ident = client.name || network.username;
if (Helper.config.useHexIp) {
ident = Helper.ip2hex(client.config.browser.ip);
}
identSocketId = client.manager.identHandler.addSocket(socket, ident);
});
irc.on("socket close", function(error) {
if (identSocketId > 0) {
client.manager.identHandler.removeSocket(identSocketId);
identSocketId = 0;
}
network.channels.forEach((chan) => {
chan.users = new Map();
chan.state = Chan.State.PARTED;
});
if (error) {
network.channels[0].pushMessage(
client,
new Msg({
type: Msg.Type.ERROR,
text: `Connection closed unexpectedly: ${error}`,
}),
true
);
}
if (network.keepNick) {
// We disconnected without getting our original nick back yet, just set it back locally
irc.options.nick = irc.user.nick = network.keepNick;
network.setNick(network.keepNick);
network.keepNick = null;
this.emit("nick", {
network: network.uuid,
nick: network.nick,
});
}
sendStatus();
});
if (Helper.config.debug.ircFramework) {
irc.on("debug", function(message) {
log.debug(
`[${client.name} (${client.id}) on ${network.name} (${network.uuid}]`,
message
);
});
}
if (Helper.config.debug.raw) {
irc.on("raw", function(message) {
network.channels[0].pushMessage(
client,
new Msg({
self: !message.from_server,
type: Msg.Type.RAW,
text: message.line,
}),
true
);
});
}
irc.on("socket error", function(err) {
network.channels[0].pushMessage(
client,
new Msg({
type: Msg.Type.ERROR,
text: "Socket error: " + err,
}),
true
);
});
irc.on("reconnecting", function(data) {
network.channels[0].pushMessage(
client,
new Msg({
text:
"Disconnected from the network. Reconnecting in " +
Math.round(data.wait / 1000) +
" seconds… (Attempt " +
data.attempt +
" of " +
data.max_retries +
")",
}),
true
);
});
irc.on("ping timeout", function() {
network.channels[0].pushMessage(
client,
new Msg({
text: "Ping timeout, disconnecting…",
}),
true
);
});
irc.on("server options", function(data) {
network.prefixLookup = {};
data.options.PREFIX.forEach((mode) => {
network.prefixLookup[mode.mode] = mode.symbol;
});
if (data.options.CHANTYPES) {
network.serverOptions.CHANTYPES = data.options.CHANTYPES;
}
if (network.serverOptions.PREFIX) {
network.serverOptions.PREFIX = data.options.PREFIX.map((p) => p.symbol);
}
network.serverOptions.NETWORK = data.options.NETWORK;
client.emit("network:options", {
network: network.uuid,
serverOptions: network.serverOptions,
});
});
function sendStatus() {
const status = network.getNetworkStatus();
status.network = network.uuid;
client.emit("network:status", status);
}
};
|
JavaScript
| 0 |
@@ -2988,20 +2988,22 @@
ll;%0A%0A%09%09%09
-this
+client
.emit(%22n
|
cd7da3f6d283b6918c0acf941b09b574d77c1b8f
|
Add Swagger version and disallow empty objects (ref #22)
|
jsonprocessor.js
|
jsonprocessor.js
|
/**
* Convert an array into a map
* @param {array[object]} object The array to convert.
* @param {string} keyField The name of the field is stored in within each
* object in the array.
* @return {object} The map converted from the array.
*/
function arrayToMap (object, keyField) {
const newObject = {};
object.forEach((objFuncParam) => {
const obj = objFuncParam;
const key = obj[keyField];
delete obj[keyField];
newObject[key] = obj;
});
return newObject;
}
/**
* @param {object} object The form value
* @return {object} A corrected version of the output. This should be a
* valid Swagger spec.
*/
module.exports = function processJSON (objectFuncParam) {
const object = JSON.parse(JSON.stringify(objectFuncParam));
if (object.security && object.security.length > 0) {
object.security = arrayToMap(object.security, 'key');
/*
* Put the `value` field of each security object as the actual value of the
* object.
*/
Object.keys(object.security).forEach((key) => {
object.security[key] = object.security[key].value;
});
} else {
object.security = {};
}
if (object.paths && object.paths.length > 0) {
object.paths = arrayToMap(object.paths, 'path');
/*
* Take all elements in the methods array and put them in the parent path
* element with `methodName` as the key and the method object as the value.
*/
Object.keys(object.paths).forEach((key) => {
const path = object.paths[key];
path.methods = arrayToMap(path.methods, 'method');
Object.keys(path.methods).forEach((methodName) => {
path[methodName] = path.methods[methodName];
path[methodName].responses = arrayToMap(
path[methodName].responses, 'statusCode');
});
// Delete the old list as it isn't actually a part of the Swagger spec
delete path.methods;
});
} else {
object.paths = {};
}
return object;
};
|
JavaScript
| 0 |
@@ -536,16 +536,1255 @@
ect;%0A%7D%0A%0A
+function isEmpty (object) %7B%0A if (object === undefined) %7B%0A return true;%0A %7D else if (Array.isArray(object)) %7B%0A if (object.length === 0) %7B%0A return true;%0A %7D%0A let empty = true;%0A object.forEach((child) =%3E %7B%0A if (!isEmpty(child)) %7B%0A empty = false;%0A return true;%0A %7D%0A return false;%0A %7D);%0A return empty;%0A %7D else if (typeof object === 'object') %7B%0A let empty = true;%0A Object.keys(object).forEach((key) =%3E %7B%0A if (!isEmpty(object%5Bkey%5D)) %7B%0A empty = false;%0A return true;%0A %7D%0A return false;%0A %7D);%0A return empty;%0A %7D else if (typeof object === 'string') %7B%0A return object.length === 0;%0A %7D%0A return false;%0A%7D%0A%0Afunction deleteEmptyChildren (objectFuncParam) %7B%0A const object = objectFuncParam;%0A if (Array.isArray(object)) %7B%0A object.forEach((child, index) =%3E %7B%0A if (isEmpty(child)) %7B%0A object.pop(index);%0A %7D else %7B%0A object%5Bindex%5D = deleteEmptyChildren(child);%0A %7D%0A %7D);%0A %7D else if (typeof object === 'object') %7B%0A Object.keys(object).forEach((key) =%3E %7B%0A if (isEmpty(object%5Bkey%5D)) %7B%0A delete object%5Bkey%5D;%0A %7D else %7B%0A object%5Bkey%5D = deleteEmptyChildren(object%5Bkey%5D);%0A %7D%0A %7D);%0A %7D%0A return object;%0A%7D%0A%0A
/**%0A * @
@@ -2003,36 +2003,34 @@
tFuncParam) %7B%0A
-cons
+le
t object = JSON.
@@ -2070,16 +2070,250 @@
ram));%0A%0A
+ object = deleteEmptyChildren(object);%0A%0A // Hardcoded Swagger version%0A object.swagger = '2.0';%0A%0A object.host = object.info.host;%0A delete object.info.host;%0A object.basePath = object.info.basePath;%0A delete object.info.basePath;%0A%0A
if (ob
@@ -2590,58 +2590,185 @@
-object.security%5Bkey%5D = object.security%5Bkey%5D.value;
+if (%7B%7D.hasOwnProperty.call(object.security%5Bkey%5D, 'value')) %7B%0A object.security%5Bkey%5D = object.security%5Bkey%5D.value;%0A %7D else %7B%0A object.security%5Bkey%5D = %5B%5D;%0A %7D
%0A
@@ -2783,24 +2783,31 @@
else %7B%0A
+delete
object.secur
@@ -2809,21 +2809,16 @@
security
- = %7B%7D
;%0A %7D%0A%0A
|
38c05738dc83effb8750ffeb7136b41915583d6b
|
Revert "Revert "<Errors> component's props.errors must be an array""
|
src/javascripts/components/errors.js
|
src/javascripts/components/errors.js
|
var React = require("react")
export default class Errors extends React.Component {
displayName = "FriggingBootstrap.Errors"
static defaultProps = require("../default_props.js")
render() {
return (
<div>
{
(this.props.errors||[]).map((error) => {
return (
<div className="col-xs-12" key={`error-${error}`}>
<div className="frigb-error" ref={`error-${error}`}>
<div className="alert alert-danger">
<i className="fa fa-exclamation-circle"/>
<span className="sr-only">Error:</span>
{` ${error}`}
<div className="clearfix"/>
</div>
</div>
</div>
)
})
}
</div>
)
}
}
|
JavaScript
| 0 |
@@ -183,18 +183,124 @@
%0A%0A
-render() %7B
+static propTypes = %7B%0A errors: React.PropTypes.array.isRequired,%0A %7D%0A%0A render() %7B%0A const %7Berrors%7D = this.props
%0A
@@ -345,31 +345,14 @@
-(this.props.
errors
-%7C%7C%5B%5D)
.map
@@ -366,34 +366,9 @@
) =%3E
- %7B%0A return (%0A
+%0A
@@ -418,34 +418,32 @@
ror-$%7Berror%7D%60%7D%3E%0A
-
%3Cd
@@ -501,34 +501,32 @@
-
-
%3Cdiv className=%22
@@ -546,18 +546,16 @@
anger%22%3E%0A
-
@@ -624,18 +624,16 @@
-
%3Cspan cl
@@ -682,18 +682,16 @@
-
-
%7B%60 $%7Berr
@@ -696,18 +696,16 @@
rror%7D%60%7D%0A
-
@@ -746,33 +746,8 @@
%22/%3E%0A
- %3C/div%3E%0A
@@ -798,17 +798,22 @@
-)
+%3C/div%3E
%0A
@@ -815,17 +815,16 @@
-%7D
)%0A
@@ -850,11 +850,10 @@
)%0A %7D%0A
-%0A
%7D%0A
|
ea6dd0a466ec04e6a9dd66af8b177d559f40a543
|
fix issue dashboard
|
src/js/controllers/dashboard-ctrl.js
|
src/js/controllers/dashboard-ctrl.js
|
/**
* Alerts Controller
*/
angular
.module('RDash')
.config(['ChartJsProvider', function (ChartJsProvider) {
// Configure all charts
ChartJsProvider.setOptions({
chartColors: ['#FF5252', '#FF8A80'],
responsive: false
});
// Configure all line charts
ChartJsProvider.setOptions('line', {
showLines: false
});
}])
.controller('DashboardCtrl', ['$scope', '$http','$state','$timeout','$rootScope', function ($scope,$http,$state,$timeout,$rootScope) {
console.log("dashboard page");
$scope.labels = [];
$scope.series = ['Series A', 'Series B'];
$scope.data = [];
//get widget sales//
$rootScope.isLoading = true;
$http.get(base_url+"api/"+api_key+"/dashboards/saleswidget")
.then(function(response) {
$rootScope.isLoading = false;
$scope.daily = response.data[0].DailySales;
$scope.weekly = response.data[0].WeeklySales;
$scope.monthly = response.data[0].MonthlySales;
console.log(response.data);
});
//----//
//get grafik dashboard//
$http.get(base_url+"api/"+api_key+"/dashboards/graphic/daily")
.then(function(response) {
$rootScope.isLoading = false;
var i=1;
console.log("response",response.data)
for(var x = 0;x<=response.data.length;x++){
var item = response.data[x];
console.log("item",item)
$scope.labels.push(item.label);
$scope.data.push(item.value);
i++;
}
/* for(var x = 1;x<=response.data.length;x++){
$scope.labels.push(x);
$scope.data.push(response.data[x]);
}*/
});
//----//
//get peringatan stok dashboard//
$http.get(base_url+"api/"+api_key+"/dashboards/stock")
.then(function(response) {
$rootScope.isLoading = false;
$scope.data_stok = response.data;
console.log(response.data);
});
//----//
$scope.onClick = function (points, evt) {
console.log(points, evt);
};
}])
;
|
JavaScript
| 0.000001 |
@@ -1118,21 +1118,21 @@
graphic/
-daily
+month
%22)%0A .
|
b0187d202c11cdaf50de0e9130c744da2a255f5c
|
update port
|
config/default.js
|
config/default.js
|
require('dotenv').config();
module.exports = {
'host': 'localhost',
'port': 3030,
'public': '../public/',
'postgres': process.env.DB_URL,
'authentication': {
'secret': 'this is a very good secret',
'strategies': [
'jwt'
],
'path': '/authentication',
'service': 'users',
'jwt': {
'header': {
'type': 'access'
},
'subject': 'anonymous',
'issuer': 'feathers',
'algorithm': 'HS256',
'expiresIn': '1d'
}
}
};
|
JavaScript
| 0 |
@@ -78,12 +78,24 @@
t':
-3030
+process.env.PORT
,%0A
|
5614c042c9485fbf084d5e42cce497d07d123dd1
|
Fix inconsistency with form that caused validation error
|
models/tutor.js
|
models/tutor.js
|
var mongoose = require('mongoose')
var bcrypt = require('bcryptjs')
var crypto = require('crypto')
var emailRegex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
var phoneRegex = /^[6, 8, 9]\d{7}$/
var TutorSchema = new mongoose.Schema({
email: {
type: String,
required: [
true,
'an email address is required'
],
unique: true,
lowercase: true,
match: [
emailRegex,
'that email address is not valid'
]
},
name: {
type: String,
unique: true,
minlength: [
3,
'your user name must be between 3 and 40 characters long'
],
maxlength: [
40,
'your user name must be between 3 and 40 characters long'
]
},
phone: {
type: String,
unique: true,
match: [
phoneRegex,
'that phone number is not valid'
],
required: [
true,
'a valid phone number is required'
]
},
gender: {
type: String,
enum: ['male', 'female'],
required: [
true,
'please provide your gender'
]
},
age: {
type: String,
enum: [
'16 to 25',
'26 to 35',
'36 to 45',
'46 to 55',
'56 to 65',
'Above 66'
],
required: [
true,
'please specify your age range'
]
},
experience: {
type: String,
maxlength: [
500,
'please specify your experience within 500 characters'
]
},
startDate: {
type: Date,
required: [
true,
'please specify when you joined ReadAble'
]
},
password: {
type: String,
required: [
true,
'a password is required'
],
minlength: [
8,
'your password must be between 8 and 30 characters'
],
maxlength: [
30,
'your password must be between 8 and 30 characters'
]
},
resetPasswordToken: {
type: String
},
resetPasswordExpires: {
type: Date
},
userType: {
type: String,
enum: ['catchPlus', 'tutor'],
required: true,
default: 'tutor'
},
admin: {
type: Boolean,
required: true
},
attendance: [
{
date: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Saturdate',
required: [
true,
'please specify the date of attendance'
]
},
attending: {
type: Boolean,
required: [
true,
'please specify if you are attending on this date'
]
}
}
]
})
TutorSchema.pre('save', function (next) {
var tutor = this
if (!tutor.isModified('password')) return next()
var hash = bcrypt.hashSync(tutor.password, 10)
tutor.password = hash
next()
})
TutorSchema.post('findOneAndUpdate', function (result, next) {
var tutor = this
if (!result) return next()
crypto.randomBytes(20, function (err, buf) {
var token = buf.toString('hex')
tutor.model.update({
email: result.email
}, {
$set: {
resetPasswordToken: token
}
}).exec()
next()
})
})
TutorSchema.post('save', function(error, doc, next) {
if (error.name === 'MongoError' && error.code === 11000) {
next(new Error('the email, name, and/or phone number you provided is/are already in use'))
} else {
next(error)
}
})
TutorSchema.methods.validPassword = function (password) {
return bcrypt.compareSync(password, this.password)
}
TutorSchema.options.toJSON = {
transform: function (doc, ret, options) {
delete ret.password
return ret
}
}
var Tutor = mongoose.model('Tutor', TutorSchema)
module.exports = Tutor
|
JavaScript
| 0.000028 |
@@ -1284,16 +1284,16 @@
'
-A
+a
bove 6
-6
+5
'%0A
|
efd06f1e1af520ec9858ab0cc6360c0594459a2f
|
add AWS credentials to make add user work
|
src/js/drivers/awsCognitoIdentity.js
|
src/js/drivers/awsCognitoIdentity.js
|
// Cognoto user identity pools
// Non federated auth with login/out in app
/*
// this is failing to work so are loaded as global scripts in asssit.html
require("script!./vendor/jsbn.js")
require("script!./vendor/jsbn2.js")
require("script!./vendor/sjcl.js")
require("script!./vendor/moment.min.js")
require("script!./vendor/aws-cognito-sdk.min.js")
require("script!./vendor/amazon-cognito-identity.min.js")
//require("script!../aws-sdk-2.3.5.min.js")
*/
/* global AWS, AWSCognito */
/* eslint-disable immutable/no-mutation */
function addUser () {
AWS.config.region = 'us-east-1' // Region
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:9127624e-b818-45ed-99da-b1a2016dd8a3' // your identity pool id here
})
AWSCognito.config.region = 'us-east-1'
AWSCognito.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: 'us-east-1:9127624e-b818-45ed-99da-b1a2016dd8a3' // your identity pool id here
})
/* eslint-enable immutable/no-mutation */
const poolData = {
UserPoolId: 'us-east-1_4suI6ClSV',
ClientId: '3mn5hcp6edn2li2hgksl44nst2'
}
const userPool = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserPool(poolData)
const dataName = {
Name: 'given_name',
Value: 'Fred'
}
const attributeName = new AWSCognito.CognitoIdentityServiceProvider.CognitoUserAttribute(dataName)
const attributeList = [attributeName]
userPool.signUp('username', 'password', attributeList, null, (err, result) => {
if (err) {
alert(err)
return
}
const cognitoUser = result.user
console.log('user name is ' + cognitoUser.getUsername())
})
}
export default addUser
|
JavaScript
| 0 |
@@ -1016,16 +1016,178 @@
ion */%0A%0A
+ // need these dummy credentials - though enabling unauthorised access also works%0A AWSCognito.config.update(%7BaccessKeyId: 'dummy', secretAccessKey: 'dummy'%7D)%0A%0A
const
|
e394993281a36619b354f89bbb7e6fcdd8d69b77
|
Add link for TagsService example
|
src/popup/js/services/TagsService.js
|
src/popup/js/services/TagsService.js
|
angular.module('Shazam2Spotify').factory('TagsService', function(BackgroundService) {
return TagsService;
});
|
JavaScript
| 0 |
@@ -80,16 +80,74 @@
ice) %7B%0A%09
+// Tags list : http://stackoverflow.com/a/18569690/1160800
%0A%09%0A%09retu
|
44bd18192c93c07806122d1d8dcb9883733f2baa
|
fix daemon
|
lib/daemon.js
|
lib/daemon.js
|
const cp = require('child_process');
const fs = require('fs-promise');
const path = require('path');
exports.start = function() {
return fs.readFile('pid', 'utf-8')
.catch(err => null)
.then(pid => {
try {
process.kill(pid - 0, 0);
return true;
} catch(err) {}
return false;
})
.then(exists => {
if (exists) {
console.warn('Found existing pid, please stop first');
process.exit(2);
return;
}
return fs.writeFile('pid', 'TEST');
.catch(err => {
console.warn('Unable to write pid file, service not started');
process.exit(2);
})
.then(() => {
const child = cp.spawn(process.argv[0], [process.argv[1], 'guard'], {
detached: true,
stdio: ['ignore']
});
child.unref();
fs.writeFile('pid', child.pid + '')
.then(() => {
console.log('Daemon started: pid =', child.pid);
})
.catch(err => {
child.kill('SIGINT');
console.warn('Unable to write pid file, will terminate');
process.exit(2);
});
})
};
exports.guard = function() {
process.on('SIGHUP', () => { });
var child;
startProcess();
function startProcess() {
child = cp.fork(path.join(__dirname, 'cli.js'));
child.on('close', code => {
setTimeout(startProcess, 500);
});
}
};
exports.stop = function() {
return fs.readFile('pid', 'utf-8')
.then(pid => {
try {
process.kill(pid - 0, 'SIGINT');
console.log('Process ' + pid + ' killed');
} catch(err) {
console.log('Process ' + pid + ' may not exist anymore');
}
return fs.unlink('pid').catch(err => null)
})
.catch(err => {
console.log('No pid file found');
})
};
|
JavaScript
| 0.000002 |
@@ -608,17 +608,27 @@
'TEST')
-;
+%0A %7D)
%0A
|
b888ffe52cf73c45d76553df7f60c9d8765e3db4
|
Simplify functions
|
src/main/webapp/authentication.js
|
src/main/webapp/authentication.js
|
// 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.
/* eslint-disable no-unused-vars */
import {createElement} from './menu-script.js';
const CLIENT_ID =
'764525537710-crtrm9pdut61dgijldb591jjjl5c2rfq.apps.googleusercontent.com';
const SCOPE = 'profile email';
const DISCOVERY_DOCS = [];
/**
* Loads the profile data associated with the currently logged in user.
*/
async function getLoginStatus() {
const response = await fetch('/add-user');
const loginStatus = await response.json();
return gapi.auth2.getAuthInstance().isSignedIn.get() && loginStatus;
}
/**
* Initializes the GoogleAuth object and checks if the user is on the
* right page based on their login status. If not, redirects them to
* the appropriate page.
*/
async function initClient() {
await initGoogleAuthObject();
}
/**
* Initializes the JavaScript object and loads the gapi.auth2 module
* to perform OAuth.
*/
async function initGoogleAuthObject() {
await gapi.auth2.init({
'clientId': CLIENT_ID,
'discoveryDocs': DISCOVERY_DOCS,
'scope': SCOPE,
'prompt': 'select_account',
});
}
/**
* Loads the required Google APIs modules and initializes the client.
*/
function loadClient() {
gapi.load('client:auth2', initClient);
}
/**
* Loads the profile data associated with the currently logged in user.
*/
async function loadProfileData() {
const googleAuth = gapi.auth2.getAuthInstance();
if (!googleAuth.isSignedIn.get()) {
return;
}
const userProfile = googleAuth.currentUser.get().getBasicProfile();
const menuElement = document.getElementById('menu');
const profilePicture = createElement('img', 'profile-picture', '');
profilePicture.src = userProfile.getImageUrl();
menuElement.prepend(profilePicture);
}
/**
* Sets a cookie with the given name and value.
* @param {String} cookieName The cookie name.
* @param {String} cookieValue The cookie value.
*/
function setCookie(cookieName, cookieValue) {
document.cookie = cookieName + '=' + encodeURIComponent(cookieValue);
}
/**
* Signs in the user, updates the authorization status and redirects them
* to the home page (only if they also provide the authorization needed).
*/
async function signIn() {
const googleAuth = gapi.auth2.getAuthInstance();
const authResult = await googleAuth.signIn();
if (googleAuth.isSignedIn.get()) {
const idToken = authResult.getAuthResponse().id_token;
setCookie('id_token', idToken);
await fetch('/add-user', {method: 'POST'});
window.location.href = 'home-page.html';
}
}
/**
* Signs out the user, deletes the cookie and redirects them to the start page.
*/
function signOut() {
const googleAuth = gapi.auth2.getAuthInstance();
googleAuth.signOut();
document.cookie = 'id_token=; expires=Thu, 01 Jan 1970 00:00:00 UTC;';
window.location.href = 'index.html';
}
export {getLoginStatus, initClient, initGoogleAuthObject, loadClient, loadProfileData, signIn, signOut};
|
JavaScript
| 0.00003 |
@@ -1847,38 +1847,32 @@
ed in user.%0A */%0A
-async
function loadPro
@@ -3174,35 +3174,16 @@
ut() %7B%0A
- const googleAuth =
gapi.au
@@ -3207,22 +3207,8 @@
ce()
-;%0A googleAuth
.sig
|
305b385753d00c25bec3797c6dd11a9a2b9ab9c5
|
Validate against special characters (#6733)
|
src/js/letters/utils/validations.js
|
src/js/letters/utils/validations.js
|
import { isValidUSZipCode } from '../../common/utils/validations';
import { ADDRESS_TYPES, MILITARY_CITIES } from './constants';
const requiredMessage = 'Please enter a valid address'; // Change me!
/**
* Ensures the input isn't blank
*/
const requiredValidator = (input, fullAddress, message = requiredMessage) => {
if (!input) {
return message;
}
// Could return anything that isn't a string, really
return true;
};
/**
* The signature of all validation functions is always the following
*
* @param {Mixed} input - The value of the field that was changed
* @param {Object} fullAddress - An object that contains the whole address with the modified
* field and updated address type
* @return {String|Mixed} - If the validation fails, return the error message to display
* If the validation passes, return anything else (we only care
* if an error message is returned)
*/
export const addressOneValidations = [
(input, fullAddress) => requiredValidator(input, fullAddress, 'Please enter a street address')
];
export const postalCodeValidations = [
// Require zip for US addresses
(postalCode, fullAddress) => {
if (fullAddress.countryName === 'USA' && !postalCode) {
return 'Please enter a Zip code';
}
return true;
},
// Check for valid US zip codes
(postalCode, fullAddress) => {
if (fullAddress.countryName === 'USA' && !isValidUSZipCode(postalCode)) {
return 'Please enter a valid Zip code';
}
return true;
}
];
export const stateValidations = [
// Require a state for US addresses
(state, fullAddress) => {
if (fullAddress.countryName === 'USA' && !state) {
return 'Please select a state';
}
return true;
}
];
export const countryValidations = [
(countryName, fullAddress) => {
// Country is required for domestic and international, but not military
if (fullAddress.type !== ADDRESS_TYPES.military && !countryName) {
return 'Please select a country';
}
return true;
}
];
export const cityValidations = [
(city, fullAddress) => requiredValidator(city, fullAddress, 'Please enter a city'),
(city, fullAddress) => {
if (fullAddress.type === ADDRESS_TYPES.military && !MILITARY_CITIES.has(city)) {
return 'Please enter APO, FPO, or DPO';
}
return true;
}
];
|
JavaScript
| 0.00001 |
@@ -430,16 +430,224 @@
ue;%0A%7D;%0A%0A
+const specialCharacterValidator = (input) =%3E %7B%0A if (/%5B%5EA-Za-z0-9 #%25&'()+,./:@%5D/.test(input)) %7B%0A return %22Please only use letters, numbers, and the special characters #%25&'()+,./:@%22;%0A %7D%0A%0A return true;%0A%7D;%0A%0A
%0A/**%0A *
@@ -1338,16 +1338,45 @@
ddress')
+,%0A specialCharacterValidator
%0A%5D;%0A%0Aexp
|
d5ef3f52349b74216b1d6777988724ccb03894bd
|
refresh button add lint
|
src/refresh_button/refresh_button.js
|
src/refresh_button/refresh_button.js
|
/**
* @file Refresh button control
* @copyright Digital Living Software Corp. 2014-2016
*/
/* global angular */
(function () {
'use strict';
var thisModule = angular.module("pipRefreshButton", ['ngMaterial']);
thisModule.directive('pipRefreshButton',
function($parse) {
return {
restrict: 'EA',
scope: false,
template: String()
+ '<md-button class="pip-refresh-button" tabindex="-1" ng-click="onClick($event)" aria-label="REFRESH">'
+ '<md-icon md-svg-icon="icons:refresh"></md-icon>'
+ ' <span class="pip-refresh-text"></span>'
+ '</md-button>',
replace: false,
link: function ($scope, $element, $attrs) {
var
textGetter = $parse($attrs.pipText),
visibleGetter = $parse($attrs.pipVisible),
refreshGetter = $parse($attrs.pipRefresh),
$button = $element.children('.md-button'),
$text = $button.children('.pip-refresh-text');
var show = function() {
// Set a new text
var text = textGetter($scope);
$text.text(text);
// Show button
$button.show();
// Adjust position
var width = $button.width();
$button.css('margin-left', '-' + (width / 2) + 'px');
};
function hide() {
$button.hide();
};
$scope.onClick = function(event) {
refreshGetter($scope);
};
$scope.$watch(visibleGetter, function(newValue) {
if (newValue == true) show();
else hide();
});
$scope.$watch(textGetter, function(newValue) {
$text.text(newValue);
});
}
}
}
);
})();
|
JavaScript
| 0.000001 |
@@ -92,30 +92,8 @@
*/%0A%0A
-/* global angular */%0A%0A
(fun
@@ -99,16 +99,23 @@
nction (
+angular
) %7B%0A
@@ -165,17 +165,17 @@
.module(
-%22
+'
pipRefre
@@ -182,17 +182,17 @@
shButton
-%22
+'
, %5B'ngMa
@@ -247,18 +247,16 @@
Button',
-
%0A
@@ -264,16 +264,17 @@
function
+
($parse)
@@ -393,16 +393,18 @@
String()
+ +
%0A
@@ -407,30 +407,24 @@
- +
'%3Cmd-button
@@ -514,16 +514,18 @@
FRESH%22%3E'
+ +
%0A
@@ -532,22 +532,16 @@
- +
'%3Cmd-ic
@@ -582,16 +582,18 @@
d-icon%3E'
+ +
%0A
@@ -605,16 +605,9 @@
- + '
+'
%3Cspa
@@ -641,16 +641,18 @@
%3C/span%3E'
+ +
%0A
@@ -663,14 +663,8 @@
- +
'%3C/
@@ -791,16 +791,35 @@
var
+ width, text, show,
%0A
@@ -1165,20 +1165,16 @@
-var
show = f
@@ -1180,16 +1180,17 @@
function
+
() %7B%0A
@@ -1252,20 +1252,16 @@
-var
text = t
@@ -1405,32 +1405,8 @@
();%0A
-
%0A
@@ -1465,28 +1465,24 @@
-var
width = $but
@@ -1551,17 +1551,16 @@
, '-' +
-(
width /
@@ -1560,17 +1560,16 @@
idth / 2
-)
+ 'px')
@@ -1671,18 +1671,16 @@
.hide();
-
%0A
@@ -1685,33 +1685,32 @@
%7D
-;
%0A%0A
@@ -1744,14 +1744,10 @@
tion
+
(
-event
) %7B%0A
@@ -1792,18 +1792,16 @@
$scope);
-
%0A
@@ -1866,32 +1866,33 @@
Getter, function
+
(newValue) %7B%0A
@@ -1928,17 +1928,39 @@
alue
- == true)
+) %7B%0A
sho
@@ -1991,21 +1991,79 @@
+ %7D
else
-hide();
+%7B%0A hide();%0A %7D
%0A
@@ -2138,16 +2138,17 @@
function
+
(newValu
@@ -2245,32 +2245,33 @@
%7D%0A %7D
+;
%0A %7D%0A )
@@ -2276,12 +2276,26 @@
);%0A%0A%7D)(
+window.angular
);%0A%0A
|
1af68c0cb4b60759c214c658b14a9da35c9309a4
|
Update device.js
|
lib/device.js
|
lib/device.js
|
var stream = require('stream')
, util = require('util')
, exec = require('child_process').exec
, SunCalc = require('suncalc'),
child;
require('date-utils');
// Give our device a stream interface
util.inherits(Device,stream);
// Export it
module.exports=Device;
/**
* Creates a new Device Object
*
* @property {Boolean} readable Whether the device emits data
* @property {Boolean} writable Whether the data can be actuated
*
* @property {Number} G - the channel of this device
* @property {Number} V - the vendor ID of this device
* @property {Number} D - the device ID of this device
*
* @property {Function} write Called when data is received from the Ninja Platform
*
* @fires data - Emit this when you wish to send data to the Ninja Platform
*/
function Device(opts) {
var self = this;
// This device will emit data
this.readable = true;
// This device can be actuated
this.writeable = false;
this.G = "0"; // G is a string a represents the channel
this.V = 0; // 0 is Ninja Blocks' device list
this.D = 1; // 2000 is a generic Ninja Blocks sandbox device
this.name = "Daylight counter"
process.nextTick(function() {
setInterval(function() {
//Get location from configuration options
var longitude = parseFloat(opts.longitude);
var latitude = parseFloat(opts.latitude);
//Get today and tomorrow dates
var now = new Date();
var tomorrow = new Date.tomorrow();
//Get sunrise and sunset times from SunCalc
var times = SunCalc.getTimes(now, latitude, longitude);
var times_tomorrow = SunCalc.getTimes(tomorrow, latitude, longitude);
//Update sunset and sunrise times with Daylight Savings offset
var sunrise_today = times.sunriseEnd;
var sunrise_tomorrow = times_tomorrow.sunriseEnd;
var sunset_today = times.sunsetStart;
sunrise_today.addMinutes(-now.getTimezoneOffset());
sunrise_tomorrow.addMinutes(-tomorrow.getTimezoneOffset());
sunset_today.addMinutes(-now.getTimezoneOffset());
//Define counter value
//Day: value = minutes to sunset
if(Date.compare(now , sunrise_today)>0 && Date.compare(now, sunset_today)<0){
var counter = sunset_today.getHours() *60 + sunset_today.getMinutes() -
now.getHours()*60 - now.getMinutes();
}
//Night: value = - minutes to sunrise
else {
if (Date.compare(now, sunset_today)>=0) {
var counter = - sunrise_tomorrow.getHours() *60 - sunrise_tomorrow.getMinutes() +
now.getHours()*60 + now.getMinutes() - 24*60;
}
if (Date.compare(now, sunrise_today)<=0) {
var counter = - sunrise_today.getHours() *60 - sunrise_today.getMinutes() +
now.getHours()*60 + now.getMinutes();
}
}
if (counter >= 1440) counter = counter - 1440;
//console.log("Sunrise is at " + sunrise_today);
//console.log("Sunset is at " + sunset_today);
//console.log("Counter = " + counter);
self.emit('data',counter);
}, 600000);
});
};
Device.prototype.write = function(data) {
};
|
JavaScript
| 0.000001 |
@@ -2844,11 +2844,12 @@
ter
-%3E
+%3C
=
+-
1440
@@ -2868,17 +2868,17 @@
counter
--
++
1440;%0A
|
7f35393108714b2fc4add93745f5ffc951d961b1
|
Add type to mock registry components
|
mocks/registry.js
|
mocks/registry.js
|
module.exports = [
{
"name": "mock-overdrive",
"description": "Mock Overdrive",
"version": "0.1.3",
"main": "index.js",
"repo": "mock/mock-overdrive",
"license": "MIT",
"scripts": [
"index.js"
],
"keywords": [
"mock",
"web audio api",
"overdrive"
],
"stars": 4,
"web-audio": {
}
},
{
"name": "mock-delay",
"description": "Mock Delay",
"version": "0.1.4",
"main": "index.js",
"repo": "mock/mock-delay",
"license": "MIT",
"scripts": [
"index.js"
],
"keywords": [
"mock",
"web audio api",
"delay"
],
"stars": 2,
"web-audio": {
}
},
{
"name": "not-an-audio-component",
"description": "Not an Audio Component",
"version": "0.2.0",
"main": "index.js",
"repo": "mock/not-audio",
"license": "MIT",
"scripts": [
"index.js"
],
"keywords": [
"mock",
"not audio"
],
"stars": 2
}
]
|
JavaScript
| 0 |
@@ -336,32 +336,55 @@
%22web-audio%22: %7B%0A
+ %22type%22 : %22effect%22
%0A %7D%0A %7D,%0A %7B%0A
@@ -695,16 +695,39 @@
dio%22: %7B%0A
+ %22type%22 : %22effect%22
%0A %7D%0A
|
9c2267bb068b896c1c393ae1ae0bbeb2b14c93e0
|
Add category for expenses
|
src/reports/category/_application.js
|
src/reports/category/_application.js
|
angular.module('gnucash-reports-view.reports.category', ['gnucash-reports-view.reports.base',
'nvd3'])
.config(['ReportsManagementProvider', function(provider) {
provider.addTemplate('account_usage_categories', 'src/reports/category/category.html');
}]);
|
JavaScript
| 0.000002 |
@@ -314,16 +314,107 @@
html');%0A
+ provider.addTemplate('expenses_categories', 'src/reports/category/category.html');%0A
%7D%5D);
|
55b75dac886866b957a9f450a1db7daa31528a68
|
Revert to 7.8, unminified
|
assets/javascripts/auth0.js
|
assets/javascripts/auth0.js
|
/* global Auth0Lock */
(function () {
function appendScript(src, callback) {
var new_script = document.createElement('script');
new_script.setAttribute('src',src);
new_script.onload = callback;
document.head.appendChild(new_script);
}
var lock;
var script_url = '//cdn.auth0.com/js/lock-6.2.min.js';
appendScript(script_url, function () {
var checkInterval = setInterval(function () {
if (!Discourse.SiteSettings) {
return;
}
clearInterval(checkInterval);
if (!Discourse.SiteSettings.auth0_client_id) {
return;
}
var client_id = Discourse.SiteSettings.auth0_client_id;
var domain = Discourse.SiteSettings.auth0_domain;
lock = new Auth0Lock(client_id, domain);
}, 300);
});
Discourse.ApplicationRoute.reopen({
actions: {
showLogin: function() {
if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
return this._super();
}
lock.show({
popup: true,
responseType: 'code',
callbackURL: Discourse.SiteSettings.auth0_callback_url
});
this.controllerFor('login').resetForm();
},
showCreateAccount: function () {
if (!Discourse.SiteSettings.auth0_client_id || Discourse.SiteSettings.auth0_connection !== '') {
return this._super();
}
var createAccountController = Discourse.__container__.lookup('controller:createAccount');
if (createAccountController && createAccountController.accountEmail) {
if (lock) {
lock.hide();
Discourse.Route.showModal(this, 'createAccount');
} else {
this._super();
}
} else {
lock.show({
mode: 'signup',
popup: true,
responseType: 'code',
callbackURL: Discourse.SiteSettings.auth0_callback_url
});
}
}
}
});
})();
|
JavaScript
| 0.999999 |
@@ -310,15 +310,11 @@
ock-
-6.2.min
+7.8
.js'
|
e36efdf971ddbb89a44c16403d6711cf7cf129a4
|
Add describe block for action test.
|
assets/js/googlesitekit/modules/datastore/settings.test.js
|
assets/js/googlesitekit/modules/datastore/settings.test.js
|
/**
* `googlesitekit/modules` datastore: settings tests.
*
* 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.
*/
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import Modules from 'googlesitekit-modules';
import { STORE_NAME } from './constants';
import { createTestRegistry } from '../../../../../tests/js/utils';
describe( 'core/modules store changes', () => {
let registry;
const slug = 'test-module';
const nonExistentModuleSlug = 'not-module';
const moduleStoreName = `modules/${ slug }`;
const controlReturn = 'dummy_return_value';
const DUMMY_ACTION = 'DUMMY_ACTION';
let moduleCanSubmitChanges = false;
let submittingChanges = false;
beforeEach( () => {
const storeDefinition = Modules.createModuleStore( moduleStoreName );
const canSubmitChanges = () => moduleCanSubmitChanges;
const isDoingSubmitChanges = () => {
return submittingChanges;
};
registry = createTestRegistry();
registry.registerStore( moduleStoreName, Data.combineStores(
storeDefinition,
{
actions: {
*submitChanges() {
const result = yield {
payload: {},
type: DUMMY_ACTION,
};
return result;
},
},
selectors: {
canSubmitChanges,
isDoingSubmitChanges,
},
controls: {
[ DUMMY_ACTION ]: () => controlReturn,
},
}
) );
} );
describe( 'actions', () => {
it( 'it proxies the selector call to the module with the given slug', async () => {
const expectedError = { error: `'modules/${ nonExistentModuleSlug }' does not have a submitChanges() action.` };
expect( await registry.dispatch( STORE_NAME ).submitChanges( nonExistentModuleSlug ) ).toEqual( expectedError );
expect( await registry.dispatch( STORE_NAME ).submitChanges( nonExistentModuleSlug ) ).toEqual( expectedError );
const expectedErrorNoSlug = { error: "'modules/' does not have a submitChanges() action." };
expect( await registry.dispatch( STORE_NAME ).submitChanges() ).toEqual( expectedErrorNoSlug );
expect( await registry.dispatch( STORE_NAME ).submitChanges( slug ) ).toBe( controlReturn );
} );
} );
describe( 'selectors', () => {
describe( 'isDoingSubmitChanges', () => {
it( 'it proxies the selector call to the module with the given slug', async () => {
expect( registry.select( STORE_NAME ).isDoingSubmitChanges( nonExistentModuleSlug ) ).toBe( false );
expect( registry.select( STORE_NAME ).isDoingSubmitChanges( slug ) ).toBe( false );
submittingChanges = true;
expect( registry.select( STORE_NAME ).isDoingSubmitChanges( slug ) ).toBe( true );
} );
} );
describe( 'canSubmitChanges', () => {
it( 'it proxies the selector call to the module with the given slug', () => {
expect( registry.select( STORE_NAME ).canSubmitChanges( slug ) ).toBe( false );
moduleCanSubmitChanges = true;
expect( registry.select( STORE_NAME ).canSubmitChanges( slug ) ).toBe( true );
expect( registry.select( STORE_NAME ).canSubmitChanges( nonExistentModuleSlug ) ).toBe( false );
} );
} );
} );
} );
|
JavaScript
| 0 |
@@ -1928,16 +1928,54 @@
() =%3E %7B%0A
+%09%09describe( 'submitChanges', () =%3E %7B%0A%09
%09%09it( 'i
@@ -2052,16 +2052,17 @@
() =%3E %7B%0A
+%09
%09%09%09const
@@ -2168,24 +2168,25 @@
ion.%60 %7D;%0A%09%09%09
+%09
expect( awai
@@ -2283,24 +2283,25 @@
edError );%0A%0A
+%09
%09%09%09expect( a
@@ -2408,16 +2408,17 @@
);%0A%0A%09%09%09
+%09
const ex
@@ -2502,16 +2502,17 @@
on.%22 %7D;%0A
+%09
%09%09%09expec
@@ -2606,16 +2606,17 @@
);%0A%0A%09%09%09
+%09
expect(
@@ -2696,24 +2696,32 @@
olReturn );%0A
+%09%09%09%7D );%0A
%09%09%7D );%0A%09%7D );
|
9e81a472783bda007cfc67f83d39d0dca6eaf345
|
fix comments
|
example/modules/app/controllers/appTest.es6
|
example/modules/app/controllers/appTest.es6
|
angular.module('App')
//you can use $scope or controllerAs methods, anyway
.controller('App.controllers.appTest', ['PropertyBinder.services.binder', 'App.factories.users',
function(bind, userFactory){
// old method - just create a reference with the factory property
// this.users = userFactory.users;
this.message = '';
bind('users'/*could take an array of properties*/)
.from(userFactory)
.to(this /*or $scope*/)
.apply();
// the service can be used to create a reference on a primitive data type like integer or float
bind('nbToLoad')
.from(userFactory)
.to(this)
.apply()
//bind an an event triggered when the property is updated from this reference
.onchange((newVal, oldVal) => {
console.log('property updated', newVal, oldVal);
userFactory.load();
});
// bind(['users','fu', 'bar']).from(userFactory).to(this /*or $scope*/).apply();
// you can also give an alias to your property
// in this case the property will be accessible by this.userAlias
var binding = bind('users').as('usersAlias').from(userFactory).to(this /*or $scope*/).apply();
// var binding = bind(['users','fu', 'bar']).as({ 'users':'usersAlias','fu':'fub', 'bar':'bars'}).from(userFactory).to(this /*or $scope*/).apply();
// if you want to keep secure the factory data you can also seal the reference
binding.seal();
binding.unseal();
// binding.destroy()
// you can even bind a function in order to keep the scope
bind('load').to(this).from(userFactory).apply();
// this.load = userFactory.load;
userFactory.load();
}]);
|
JavaScript
| 0.000001 |
@@ -64,17 +64,9 @@
hods
-, anyway
%0A
+
%09.co
@@ -343,12 +343,10 @@
'/*c
-ould
+an
tak
@@ -600,16 +600,16 @@
apply()%0A
+
%09%09%09//bin
@@ -613,19 +613,16 @@
bind an
-an
event tr
|
f6efd18d7b90e54ed5f17cf0959073b922af1ca2
|
work around edge case with creating a new tag
|
api/models/TagFollow.js
|
api/models/TagFollow.js
|
/* eslint-disable camelcase */
module.exports = bookshelf.Model.extend({
tableName: 'tag_follows',
community: function () {
return this.belongsTo(Community)
},
tag: function () {
return this.belongsTo(Tag)
},
user: function () {
return this.belongsTo(User)
}
}, {
create (attrs, { transacting } = {}) {
return this.forge(Object.assign({created_at: new Date()}, attrs))
.save({}, {transacting})
},
// toggle is used by hylo-redux
toggle: function (tagId, userId, communityId) {
return TagFollow.where({
community_id: communityId,
tag_id: tagId,
user_id: userId
}).fetch()
.then(tagFollow => tagFollow
? TagFollow.remove({tagId, userId, communityId})
: TagFollow.add({tagId, userId, communityId}))
},
// subscribe is used by hylo-evo
subscribe: function (tagId, userId, communityId, isSubscribing) {
return TagFollow.where({community_id: communityId, tag_id: tagId, user_id: userId})
.fetch()
.then(tagFollow => {
if (tagFollow && !isSubscribing) {
return TagFollow.remove({tagId, userId, communityId})
} else if (!tagFollow && isSubscribing) {
return TagFollow.add({tagId, userId, communityId})
}
})
},
add: function ({tagId, userId, communityId, transacting}) {
const attrs = {
tag_id: tagId,
community_id: communityId,
user_id: userId
}
return new TagFollow(attrs).save(null, {transacting})
.tap(() => CommunityTag.query(q => {
q.where('community_id', communityId)
q.where('tag_id', tagId)
}).query().increment('num_followers').transacting(transacting))
},
remove: function ({tagId, userId, communityId, transacting}) {
const attrs = {
tag_id: tagId,
community_id: communityId,
user_id: userId
}
return TagFollow.where(attrs)
.fetch()
.then(tagFollow => tagFollow &&
tagFollow.destroy({transacting})
.tap(() => CommunityTag.query(q => {
q.where('community_id', attrs.community_id)
q.where('tag_id', attrs.tag_id)
}).query().decrement('num_followers').transacting(transacting)))
},
findFollowers: function (community_id, tag_id, limit = 3) {
return TagFollow.query(q => {
q.where({community_id, tag_id})
q.limit(limit)
})
.fetchAll({withRelated: ['user', 'user.tags']})
.then(tagFollows => {
return tagFollows.models.map(tf => tf.relations.user)
})
}
})
|
JavaScript
| 0.000003 |
@@ -1422,16 +1422,174 @@
return
+TagFollow.where(%7B%0A community_id: communityId,%0A tag_id: tagId,%0A user_id: userId%0A %7D).fetch(%7Btransacting%7D)%0A .then(follow =%3E follow %7C%7C%0A
new TagF
@@ -1627,24 +1627,26 @@
cting%7D)%0A
+
.tap(() =%3E C
@@ -1662,32 +1662,34 @@
ag.query(q =%3E %7B%0A
+
q.where('c
@@ -1717,24 +1717,26 @@
tyId)%0A
+
q.where('tag
@@ -1744,24 +1744,26 @@
id', tagId)%0A
+
%7D).query
@@ -1817,16 +1817,17 @@
acting))
+)
%0A %7D,%0A%0A
|
218a1780c684737c23fc236fcd080acb9b718dc3
|
remove callback
|
lib/driver.js
|
lib/driver.js
|
"use strict";
var Cylon = require("cylon");
var Driver = module.exports = function Driver(opts) {
Driver.__super__.constructor.apply(this, arguments);
opts = opts || {};
// Include a list of commands that will be made available to external APIs.
this.commands = {
// This is how you register a command function for the API;
// the command should be added to the prototype, see below.
hello: this.hello,
forward : this.forward,
backward : this.backward,
left : this.left,
right : this.right,
up : this.up,
down : this.down,
light : this.light,
fire : this.fire,
};
this.commandData = {
forward : "7100028080808001",
backward : "7100828080808002",
left : "7100808280808008",
right : "7100800280808004",
down : "7100808002808010",
up : "7100808082808020",
light : "7100808080800240",
fire : "7100808080808280"
};
};
Cylon.Utils.subclass(Driver, Cylon.Driver);
Driver.prototype.start = function(callback) {
callback();
};
Driver.prototype.halt = function(callback) {
callback();
};
Driver.prototype.hello = function() {
Cylon.Logger.info("Hello World!");
};
Driver.prototype.forward = function(callback) {
this.connection.sendCommand(this.commandData.forward);
callback();
};
Driver.prototype.backward = function(callback) {
this.connection.sendCommand(this.commandData.backward);
callback();
};
Driver.prototype.left = function(callback) {
this.connection.sendCommand(this.commandData.left);
callback();
};
Driver.prototype.right = function(callback) {
this.connection.sendCommand(this.commandData.right);
callback();
};
Driver.prototype.up = function(callback) {
this.connection.sendCommand(this.commandData.up);
callback();
};
Driver.prototype.down = function(callback) {
this.connection.sendCommand(this.commandData.down);
callback();
};
Driver.prototype.fire = function(callback) {
this.connection.sendCommand(this.commandData.fire);
callback();
};
Driver.prototype.light = function(callback) {
this.connection.sendCommand(this.commandData.light);
callback();
};
|
JavaScript
| 0.000001 |
@@ -1212,32 +1212,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1273,38 +1273,24 @@
a.forward);%0A
- callback();%0A
%7D;%0A%0ADriver.p
@@ -1314,32 +1314,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1380,30 +1380,16 @@
kward);%0A
- callback();%0A
%7D;%0A%0ADriv
@@ -1413,32 +1413,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1471,38 +1471,24 @@
Data.left);%0A
- callback();%0A
%7D;%0A%0ADriver.p
@@ -1509,32 +1509,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1572,30 +1572,16 @@
right);%0A
- callback();%0A
%7D;%0A%0ADriv
@@ -1603,32 +1603,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1663,30 +1663,16 @@
ta.up);%0A
- callback();%0A
%7D;%0A%0ADriv
@@ -1696,32 +1696,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1758,30 +1758,16 @@
.down);%0A
- callback();%0A
%7D;%0A%0ADriv
@@ -1791,32 +1791,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1853,30 +1853,16 @@
.fire);%0A
- callback();%0A
%7D;%0A%0ADriv
@@ -1887,32 +1887,24 @@
= function(
-callback
) %7B%0A this.c
@@ -1950,25 +1950,11 @@
light);%0A
- callback();%0A
%7D;%0A
|
e96455d31ce0f308e40bc8815f575ca80c89eccf
|
fix scroll with long list
|
src/web/containers/App.js
|
src/web/containers/App.js
|
import React, { Component } from 'react';
import Board from '../components/Board'
import Header from '../components/Header'
import { connect } from 'react-redux'
import * as LamaActions from '../../common/actions'
import { bindActionCreators } from 'redux'
import HTML5Backend from 'react-dnd-html5-backend';
import {DragDropContext} from 'react-dnd';
import _ from 'lodash'
import ConnectionStatus from '../components/ConnectionStatus'
import {sort} from '../../common/utils'
class App extends Component {
// TODO authentication
componentDidMount() {
const {fetchData, getConnectionStatus} = this.props.actions
fetchData()
getConnectionStatus()
}
render() {
const style = {
fontFamily: 'Helvetica, Arial, sans-serif',
backgroundColor: 'rgb(0, 121, 191)',
position: 'fixed',
height: '100%',
width: '100%',
top: 0,
left: 0
}
const {main, actions} = this.props
const sortedBoards = sort(main.boards, 'boardIndex')
return (
<div style={style}>
{main.connected?null:<ConnectionStatus />}
<Header main={main} actions={actions}/>
<div style={{display:'flex', flexDirection:'row'}}>
<div>
{_.map(sortedBoards, board => main.selectedBoard === board.id ? <Board key={board.id} boardId={board.id} board={board}/>:null)}
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
main: state.main,
})
const mapDispatchToProps = dispatch =>({
actions: bindActionCreators(LamaActions,dispatch)
})
App = DragDropContext(HTML5Backend)(App)
export default connect(mapStateToProps,mapDispatchToProps)(App)
|
JavaScript
| 0.000003 |
@@ -820,51 +820,39 @@
-height: '100%25',%0A width: '100%25'
+top: 0,%0A bottom: 0
,%0A
top:
@@ -839,35 +839,36 @@
ottom: 0,%0A
-top
+left
: 0,%0A left:
@@ -862,23 +862,62 @@
,%0A
-left: 0
+overflowY: 'scroll',%0A overflowX: 'scroll'
%0A %7D%0A%09
|
d20dc78ad126b003042e9452f864579aa37aac69
|
Revert folderpicker.js to devevlop version
|
website/static/js/folderpicker.js
|
website/static/js/folderpicker.js
|
/**
* A simple folder picker plugin built on HGrid.
* Takes the same options as HGrid and additionally requires an
* `onPickFolder` option (the callback executed when a folder is selected).
*
* Usage:
*
* $('#myPicker').folderpicker({
* data: // Array of HGrid-formatted data or URL to fetch data
* onPickFolder: function(evt, folder) {
* // do something with folder
* }
* });
*/
'use strict';
var $ = require('jquery');
var m = require('mithril');
var Treebeard = require('treebeard');
function treebeardToggleCheck(item) {
return ((typeof item.data.hasChildren === 'undefined') || item.data.hasChildren);
}
function treebeardResolveToggle(item) {
if ((typeof item.data.hasChildren !== 'undefined') && item.data.hasChildren === false) {
return '';
}
return item.open ?
m('i.fa.fa-minus', ' '):
m('i.fa.fa-plus', ' ');
}
// Returns custom icons for OSF
function treebeardResolveIcon(item) {
return item.open ?
m('i.fa.fa-folder-open-o', ' '):
m('i.fa.fa-folder-o', ' ');
}
var INPUT_NAME = '-folder-select';
function treebeardTitleColumn(item, col) {
var tb = this; // jshint ignore: line
var cls = '';
var onclick = function() {};
if (typeof item.data.hasChildren === 'undefined' || item.data.hasChildren) {
cls = 'hasChildren';
onclick = function() {
tb.updateFolder(null, item);
};
}
return m('span', {
className: cls,
onclick: onclick
}, item.data.name);
}
/**
* Returns the folder select button for a single row.
*/
function treebeardSelectView(item) {
var tb = this; // jshint ignore: line
var setTempPicked = function() {
this._tempPicked = item.id;
};
var templateChecked = m('input', {
type: 'radio',
checked: 'checked',
name: '#' + tb.options.divID + INPUT_NAME,
value: item.id
}, ' ');
var templateUnchecked = m('input', {
type: 'radio',
onclick: setTempPicked.bind(tb),
onchange: function(evt) {
tb.options.onPickFolder(evt, item);
},
name: '#' + tb.options.divID + INPUT_NAME
}, ' ');
if (tb._tempPicked) {
if (tb._tempPicked === item.id) {
return templateChecked;
}
return templateUnchecked;
}
if (item.data.path === tb.options.folderPath || (tb.options.folderArray && tb.options.folderArray[tb.options.folderArray.length - 1] === item.data.name)) {
return templateChecked;
}
return templateUnchecked;
}
function treebeardColumnTitle() {
return [{
title: 'Folders',
width: '75%',
sort: false
}, {
title: 'Select',
width: '25%',
sort: false
}];
}
function treebeardResolveRows(item) {
// this = treebeard;
item.css = '';
return [{
data: 'name', // Data field name
folderIcons: true,
filter: false,
custom: treebeardTitleColumn
}, {
sortInclude: false,
css: 'p-l-xs',
custom: treebeardSelectView
}];
}
function treebeardOnload() {
var tb = this; // jshint ignore: line
tb.options.folderIndex = 0;
if (tb.options.folderPath) {
tb.options.folderArray = tb.options.folderPath.split('/');
if (tb.options.folderArray.length > 1) {
tb.options.folderArray.splice(0, 1);
}
} else {
tb.options.folderArray = [''];
}
var node = tb.treeData.children[0];
if ((typeof node.data.hasChildren === 'undefined') || node.data.hasChildren) {
tb.updateFolder(null, tb.treeData.children[0]);
}
tb.options.folderPickerOnload();
}
function treebeardLazyLoadOnLoad(item) {
var tb = this; // jshint ignore: line
for (var i = 0; i < item.children.length; i++) {
if ((typeof item.data.hasChildren !== 'undefined') && item.data.hasChildren === false) {
return;
}
if (item.children[i].data.name === tb.options.folderArray[tb.options.folderIndex]) {
tb.updateFolder(null, item.children[i]);
tb.options.folderIndex++;
return;
}
}
}
// Default Treebeard options
var defaults = {
columnTitles: treebeardColumnTitle,
resolveRows: treebeardResolveRows,
resolveIcon: treebeardResolveIcon,
togglecheck: treebeardToggleCheck,
resolveToggle: treebeardResolveToggle,
ondataload: treebeardOnload,
lazyLoadOnLoad: treebeardLazyLoadOnLoad,
// Disable uploads
uploads: false,
showFilter : false,
resizeColumns : false,
rowHeight : 35,
resolveRefreshIcon : function() {
return m('i.fa.fa-refresh.fa-spin');
}
};
function FolderPicker(selector, opts) {
var self = this;
self.selector = selector;
self.checkedRowId = null;
// Custom Treebeard action to select a folder that uses the passed in
// "onChooseFolder" callback
if (!opts.onPickFolder) {
throw new Error('FolderPicker must have the "onPickFolder" option defined');
}
self.options = $.extend({}, defaults, opts);
self.options.divID = selector.substring(1);
self.options.initialFolderName = opts.initialFolderName;
self.options.folderPath = opts.initialFolderPath;
self.options.rootName = opts.rootName;
// Start up the grid
self.grid = new Treebeard(self.options).tbController;
}
// Augment jQuery
$.fn.folderpicker = function(options) {
this.each(function() {
// Treebeard must take an ID as a selector if using as a jQuery plugin
if (!this.id) {
throw new Error('FolderPicker must have an ID if initializing with jQuery.');
}
var selector = '#' + this.id;
var tb = new FolderPicker(selector, options);
$.fn.folderpicker.prototype.destroy = function() {
tb.grid.destroy();
};
this._tb = tb;
});
return this;
};
FolderPicker.selectView = treebeardSelectView;
module.exports = FolderPicker;
|
JavaScript
| 0 |
@@ -5769,24 +5769,22 @@
-var tb =
+return
new Fol
@@ -5821,156 +5821,14 @@
- $.fn.folderpicker.prototype.destroy = function() %7B%0A tb.grid.destroy();%0A %7D;%0A this._tb = tb;%0A %7D);%0A return this
+%7D)
;%0A%7D;
-
%0A%0A%0AF
|
2921800521fcef3a9ec8eb4ca9039f2f970db685
|
Fix undefined reference to "result" in basic auth strategy callback.
|
api/routes/api/oauth.js
|
api/routes/api/oauth.js
|
var oauth2orize = require('oauth2orize');
var uid = require('uid');
var crypto = require('crypto');
var passport = require('passport');
var BasicStrategy = require('passport-http').BasicStrategy;
var ClientPasswordStrategy = require('passport-oauth2-client-password').Strategy;
var BearerStrategy = require('passport-http-bearer').Strategy;
var keystone = require('keystone');
var App = keystone.list('App'),
AccessToken = keystone.list('AccessToken');
var server = oauth2orize.createServer();
server.exchange(oauth2orize.exchange.clientCredentials(function(client, scope, done) {
var token = uid(256);
var tokenHash = crypto.createHash('sha1').update(token).digest('hex');
var expiresIn = 1800;
var expirationDate = new Date(new Date().getTime() + (expiresIn * 1000));
var accessToken = AccessToken.model({
token: tokenHash,
expirationDate: expirationDate,
client: client.id,
scope: scope
});
accessToken.save((err, accessToken) => {
if (err) {
return done(err);
}
return done(null, token, {expires_in: expiresIn});
});
}));
passport.use("clientBasic", new BasicStrategy((clientId, clientSecret, done) => {
App.model.findById(clientId).exec((err, app) => {
if (err) {
return done(err);
}
if (!app) {
return done(null, false);
}
if (clientSecret == app.secret) {
return done(null, result ? app : false);
}
});
}));
passport.use("clientPassword", new ClientPasswordStrategy((clientId, clientSecret, done) => {
App.model.findById(clientId).exec((err, app) => {
if (err) {
return done(err);
}
if (!app) {
return done(null, false);
}
if (app.secret == clientSecret) {
return done(null, app);
} else {
return done(null, false);
}
});
}));
/**
* This strategy is used to authenticate users based on an access token (aka a
* bearer token).
*/
passport.use("accessToken", new BearerStrategy((accessToken, done) => {
var accessTokenHash = crypto.createHash('sha1').update(accessToken).digest('hex');
AccessToken.model.findOne({token: accessTokenHash}, (err, token) => {
if (err) {
return done(err);
}
if (!token) {
return done(null, false);
}
if (new Date() > token.expirationDate) {
token.remove((err) => done(err));
} else {
App.model.findById(token.client).exec((err, app) => {
if (err) {
return done(err);
}
if (!app) {
return done(null, false);
}
// no use of scopes for now
var info = { scope: '*' };
return done(null, app, info);
});
}
})
}));
exports.checkAccessToken = function(req, res, next) {
passport.authenticate('accessToken', { session: false })(req, res, next);
}
exports.token = [
passport.authenticate(['clientBasic', 'clientPassword'], { session: false }),
server.token(),
server.errorHandler()
]
|
JavaScript
| 0 |
@@ -1470,14 +1470,11 @@
ll,
-result
+app
? a
|
77fc4b054306ecf0a0db45999c5868f542e67c53
|
Update models/Contact.js
|
models/Contact.js
|
models/Contact.js
|
var keystone = require('twreporter-keystone');
var transform = require('model-transform');
var Types = keystone.Field.Types;
var Contact = new keystone.List('Contact');
Contact.add({
name: { type: String, required: true, index: true },
email: { type: Types.Email, initial: true, index: true },
image: { type: Types.CloudinaryImage },
homepage: { type: Types.Url, index: false },
facebook: { type: Types.Url, index: false },
twitter: { type: Types.Url, index: false },
instantgram: { type: Types.Url, index: true },
address: { type: Types.Location, collapse: true },
bio: { type: Types.Markdown, collapse: true },
});
transform.toJSON(Contact);
Contact.defaultColumns = 'name, email, favouriteFlavour, birthday, homepage';
Contact.register();
|
JavaScript
| 0 |
@@ -317,23 +317,39 @@
pes.
-Cloudinary
+ImageRelationship, ref: '
Image
+'
%7D,%0A
|
c1b202ea9d85ea61a4e1e773795e384c6780a8e6
|
fix LookupTableIterator
|
src/lib/collections/lookup-table.js
|
src/lib/collections/lookup-table.js
|
import Grouping from './grouping';
import Iterator from '../iteration/iterator';
import EqualityComparer from './equality-comparer';
import resize from '../utils/resize';
import forOf from '../utils/for-of';
import extend from '../utils/extend';
import mixin from '../utils/mixin';
var emptyGrouping = new Grouping(null, []);
export default function LookupTable(comparer) {
this.size = 0;
this.slots = new Array(7);
this.buckets = new Array(7);
this.comparer = EqualityComparer.from(comparer);
}
mixin(LookupTable.prototype, {
add: function (key, value) {
this.getGrouping(key, value, true);
},
get: function (key) {
return this.getGrouping(key, null, false) || emptyGrouping;
},
contains: function (key) {
return this.getGrouping(key, null, false) !== null;
},
entries: function () {
var arr = new Array(this.size),
index = 0;
for (var i = 0, count = this.slots.length; i < count; i++) {
arr[index++] = this.slots[i].grouping;
}
return arr;
},
getGrouping: function (key, value, create) {
var comparer = this.comparer,
hash = comparer.hash(key) & 0x7FFFFFFF,
bucket = hash % this.buckets.length,
index = this.buckets[bucket],
grouping = null,
slot = null;
while (index !== undefined) {
slot = this.slots[index];
if (slot.hash === hash && comparer.equals(slot.grouping.key, key)) {
grouping = slot.grouping;
break;
}
index = slot.next;
}
if (create === true) {
if (grouping === null) {
if (this.size === this.slots.length) {
this.resize();
bucket = hash % this.buckets.length;
}
index = this.size;
this.size++;
grouping = new Grouping(key, [value]);
this.slots[index] = new LookupTableSlot(hash, grouping, this.buckets[bucket]);
this.buckets[bucket] = index;
}
else {
grouping.elements.push(value);
}
}
return grouping;
},
resize: function () {
var size = this.size,
newSize = resize(size),
slot = null,
bucket = 0;
this.slots.length = newSize;
this.buckets.length = newSize;
// rehash values & update buckets and slots
for (var index = 0; index < size; index++) {
slot = this.slots[index];
bucket = slot.hash % newSize;
slot.next = this.buckets[bucket];
this.buckets[bucket] = index;
}
},
'@@iterator': function () {
return new LookupTableIterator(this);
}
});
mixin(LookupTable, {
create: function (source, keySelector, comparer) {
var lookup = new LookupTable(comparer);
forOf(source, function (element) {
lookup.add(keySelector(element), element);
});
return lookup;
}
});
export function LookupTableIterator(lookup) {
var index = -1,
size = lookup.size,
slots = lookup.slots;
Iterator.call(this, function () {
if (++index < size) {
return {
value: slots[index++].grouping,
done: false
};
}
return {
done: true
};
});
}
extend(LookupTableIterator, Iterator);
function LookupTableSlot(hash, grouping, next) {
this.hash = hash;
this.next = next;
this.grouping = grouping;
}
|
JavaScript
| 0 |
@@ -3397,18 +3397,16 @@
ts%5Bindex
-++
%5D.groupi
|
0ed53170d4bc9574f53cf093ab4b261e6220346f
|
Fix error inserting snippets
|
assets/js/pages-snippets.js
|
assets/js/pages-snippets.js
|
/*
* Handles snippet operations on the Pages main page
*/
+function ($) { "use strict";
if ($.oc.pages === undefined)
$.oc.pages = {}
var SnippetManager = function ($masterTabs) {
this.$masterTabs = $masterTabs
var self = this
$(document).on('hidden.oc.inspector', '.redactor-box [data-snippet]', function(){
self.syncEditorCode(this)
})
$(document).on('init.oc.richeditor', '.redactor-box textarea', function(ev, $editor){
self.initSnippets($editor)
})
$(document).on('syncBefore.oc.richeditor', '.redactor-box textarea', function(ev, container){
self.syncPageMarkup(ev, container)
})
$(document).on('keydown.oc.richeditor', '.redactor-box textarea', function(ev, originalEv, $editor, $textarea){
self.editorKeyDown(ev, originalEv, $editor, $textarea)
})
$(document).on('click', '[data-snippet]', function(){
$(this).inspector()
return false
})
}
SnippetManager.prototype.onSidebarSnippetClick = function($sidebarItem) {
var $pageForm = $('div.tab-content > .tab-pane.active form[data-object-type=page]', this.$masterTabs)
if (!$pageForm.length) {
alert('Snippets can only be added to Pages. Please open or create a Page first.')
return
}
var $activeEditorTab = $('.control-tabs.secondary .tab-pane.active', $pageForm),
$textarea = $activeEditorTab.find('[data-control="richeditor"] textarea'),
$richeditorNode = $textarea.closest('[data-control="richeditor"]'),
$snippetNode = $('<figure contenteditable="false" data-inspector-css-class="hero" />'),
componentClass = $sidebarItem.attr('data-component-class'),
snippetCode = $sidebarItem.data('snippet')
if (!$textarea.length) {
alert('Snippets can only be added to page Content or HTML placeholders.')
return
}
if (componentClass) {
$snippetNode.attr({
'data-component': componentClass,
'data-inspector-class': componentClass
})
// If a component-based snippet was added, make sure that
// its code is unique, as it will be used as a component
// alias.
snippetCode = this.generateUniqueComponentSnippetCode(componentClass, snippetCode, $pageForm)
}
$snippetNode.attr({
'data-snippet': snippetCode,
'data-name': $sidebarItem.data('snippet-name'),
'tabindex': '0',
'data-ui-block': 'true'
})
$snippetNode.get(0).contentEditable = false
var redactor = $textarea.redactor('core.getObject'),
current = redactor.selection.getCurrent()
if (current === false)
redactor.focus.setStart()
current = redactor.selection.getCurrent()
if (current !== false) {
// If the current element doesn't belog to the redactor on the active tab,
// exit. A better solution would be inserting the snippet to the top of the
// text, but it looks like there's a bug in Redactor - although the redactor
// object ponts to a correct editor on the page, calling redactor.insert.node
// inserts the snippet to an editor on another tab.
var $currentParent = $(current).parent()
if ($currentParent.length && !$.contains($activeEditorTab.get(0), $currentParent.get(0)))
return
}
$richeditorNode.richEditor('insertUiBlock', $snippetNode)
}
SnippetManager.prototype.generateUniqueComponentSnippetCode = function(componentClass, originalCode, $pageForm) {
var updatedCode = originalCode,
counter = 1,
snippetFound = false
do {
snippetFound = false
$('[data-control="richeditor"] textarea', $pageForm).each(function(){
var $textarea = $(this),
$codeDom = $('<div>' + $textarea.redactor('code.get') + '</div>')
if ($codeDom.find('[data-snippet="'+updatedCode+'"][data-component]').length > 0) {
snippetFound = true
updatedCode = originalCode + counter
counter++
return false
}
})
} while (snippetFound)
return updatedCode
}
SnippetManager.prototype.syncEditorCode = function(inspectable) {
var $textarea = $(inspectable).closest('[data-control=richeditor]').find('textarea')
$textarea.redactor('code.sync')
inspectable.focus()
}
SnippetManager.prototype.initSnippets = function($editor) {
var snippetCodes = []
$('.redactor-editor [data-snippet]', $editor).each(function(){
var $snippet = $(this),
snippetCode = $snippet.attr('data-snippet'),
componentClass = $snippet.attr('data-component')
if (componentClass)
snippetCode += '|' + componentClass
snippetCodes.push(snippetCode)
$snippet.addClass('loading')
$snippet.attr({
'data-name': 'Loading...',
'tabindex': '0',
'data-inspector-css-class': 'hero',
'data-ui-block': true
})
if (componentClass)
$snippet.attr('data-inspector-class', componentClass)
this.contentEditable = false
})
if (snippetCodes.length > 0) {
var request = $editor.request('onGetSnippetNames', {
data: {
codes: snippetCodes
}
}).done(function(data) {
if (data.names !== undefined) {
$.each(data.names, function(code){
$('[data-snippet="'+code+'"]', $editor)
.attr('data-name', this)
.removeClass('loading')
})
}
})
}
}
SnippetManager.prototype.syncPageMarkup = function(ev, container) {
var $domTree = $('<div>'+container.html+'</div>')
$('[data-snippet]', $domTree).each(function(){
var $snippet = $(this)
$snippet.removeAttr('contenteditable data-name tabindex data-inspector-css-class data-inspector-class data-property-inspectorclassname data-property-inspectorproperty data-ui-block')
if (!$snippet.attr('class'))
$snippet.removeAttr('class')
})
container.html = $domTree.html()
}
SnippetManager.prototype.editorKeyDown = function(ev, originalEv, $editor, $textarea) {
if ($textarea === undefined)
return
var redactor = $textarea.redactor('core.getObject')
if (originalEv.target && $(originalEv.target).attr('data-snippet') !== undefined) {
this.snippetKeyDown(originalEv, originalEv.target)
return
}
}
SnippetManager.prototype.snippetKeyDown = function(ev, snippet) {
if (ev.which == 32) {
var $textarea = $(snippet).closest('.redactor-box').find('textarea'),
redactor = $textarea.redactor('core.getObject')
switch (ev.which) {
case 32:
// Space key
$(snippet).inspector()
break
}
}
}
$.oc.pages.snippetManager = SnippetManager
}(window.jQuery);
|
JavaScript
| 0.000013 |
@@ -1443,16 +1443,21 @@
econdary
+-tabs
.tab-pa
@@ -7672,8 +7672,9 @@
jQuery);
+%0A
|
675da6243c4b65bc40666b1f7f8861724af86a13
|
remove an unneeded conditional in generatePage()
|
generate.js
|
generate.js
|
var fs = require('fs'),
path = require('path'),
sys = require('sys'),
exec = require('child_process').exec,
hogan = require('hogan'),
models = require('./models.js'),
config = require('./config.js').config,
Page = models.Page,
Template = models.Template,
StaticFile = models.StaticFile;
/**
* Compiles a template and saves it to disk at config.webRoot + path. Expects that
* the full path to file exists and is writable and that nothing bad ever
* happens.
*
* path : The page's path relative to config.webRoot
* template : A string containing the template contents
* context : The template context
*/
var saveTemplate = function(savePath, template, context) {
var hoganTemplate = hogan.compile(template);
var finalPageContent = hoganTemplate.render(context);
fs.writeSync(fs.openSync(path.join(config.webRoot, savePath), 'w'), finalPageContent);
};
/**
* Generates the entire static site. Generates each static page and moves them
* to webroot, copies all statics to webroot, and does everything else to compile
* the entire site into webroot.
*/
exports.generateSite = function() {
// Iterate through all Pages in the site and call generatePage() oneach
Page.find({}, function(err, pages) {
pages.forEach(function(page) {
generatePage(page._id, config.webRoot);
});
});
// Iterate through all static media files in the site and call
// generateStaticMediaFile() on each
StaticFile.find({'isText': false}, function(err, mediaFiles) {
mediaFiles.forEach(function(f) {
generateStaticMediaFile(f._id, config.webRoot);
});
});
};
/**
*
*/
var generatePage = function(pageId) {
Page.findOne({'_id': pageId}).populate('template').run(function(err, page) {
var templateContext = {'page': {
'title': page.title,
'content': page.body,
'path': page.path,
}};
path.exists(path.dirname(page.path), function(exists) {
if (!exists) {
exec('mkdir -p ' + path.join(config.webRoot, path.dirname(page.path)), function(err, stdout, stderr) {
if (err) {
console.log('Could not create path to template!');
console.log(err);
} else {
saveTemplate(page.path, page.template.body, templateContext);
}
});
} else {
saveTemplate(page.path, page.template.body, templateContext);
}
});
});
};
/**
* Copies a static media file from config.mediaUploadPath to webroot
*/
var generateStaticMediaFile = function(fileId) {
StaticFile.findOne({'_id': fileId}, function(err, file) {
var finalPath = path.join(config.webRoot, file.path);
// Make sure a path up to the static file's path in webroot exists
exec('mkdir -p ' + path.dirname(finalPath), function(err, stdout, stderr) {
// Ignore errors because nothing bad ever happens
// Exec a `cp' command out of sheer laziness
exec('cp ' + file.mediaFilePath + ' ' + finalPath, function(err, stdout, stderr) {
if (err) {
console.log('Could not copy static file!');
console.log(err);
}
});
});
});
};
/**
* The inverse of generatePage. Takes the ObjectId of a Page and
* deletes the generated static file for that page from disk.
*/
exports.deletePage = function(pageId, deletedCallback) {
Page.findOne({'_id': pageId}, function(err, page) {
fs.unlink(path.join(config.webRoot, page.path), function(err) {
deletedCallback();
});
});
};
|
JavaScript
| 0 |
@@ -1967,99 +1967,139 @@
+// Make sure the page's
path
-.
+
exists
-(path.dirname(
+. i.e. if the
page
-.
+'s
path
-), function(exists) %7B%0A if (!exists) %7B%0A
+ is '/foo/bar/index.html',%0A // run a mkdir on %60webroot/foo/bar'%0A
@@ -2221,326 +2221,33 @@
- if (err) %7B%0A console.log('Could not create path to template!');%0A console.log(err);%0A %7D else %7B%0A saveTemplate(page.path, page.template.body, templateContext);%0A %7D%0A %7D);%0A %7D else %7B%0A
+// Now save the template%0A
@@ -2316,30 +2316,16 @@
ntext);%0A
- %7D%0A
|
c2fb565d6fa3c0224adc2b37f76016072fdc9c23
|
Patch officials function name.
|
src/main/webapp/scripts/toggle.js
|
src/main/webapp/scripts/toggle.js
|
const KEYWORD_TEMPLATE_PROMISE = loadTemplate('/templates/keyword.html');
const LOCATION_TEMPLATE_PROMISE = loadTemplate('/templates/location.html');
const NO_KEYWORDS_HTML = loadTemplate('/templates/noKeywords.html')
const KEYWORDS_OBJ_URL = '/keyword';
const CIVIC_OBJ_URL = '/actions/civic'
const BOOKS_OBJ_URL = '/books';
const PROJECTS_OBJ_URL = '/actions/projects';
const OBJECTS_URLS = [BOOKS_OBJ_URL, PROJECTS_OBJ_URL];
/**
* Loads the content section.
*/
async function loadContentSection() {
const keywords = await loadKeywords(KEYWORDS_OBJ_URL);
if (keywords.length === 0) {
loadNoKeywords();
} else {
keywords.forEach(loadKeywordSection);
}
loadCivicSection();
}
/**
* Loads the keywords array from a servlet or from cookies.
* Returns a promise of the keywords array.
*/
async function loadKeywords(keywordsUrl) {
const key = $("body").attr("data-key");
let keywords;
const keywordsCookie = getCookie(key);
if (keywordsCookie === "") {
keywords = await loadObject(`${keywordsUrl}?k=${key}`);
const keywordsJson = JSON.stringify(keywords);
setCookie(key, keywordsJson, 1);
} else {
keywords = JSON.parse(keywordsCookie);
}
return keywords;
}
async function loadNoKeywords() {
const noKeywordsHTML = await NO_KEYWORDS_HTML;
$('#keywords').append(noKeywordsHTML);
}
/**
* Loads a keyword section to the DOM.
*/
async function loadKeywordSection(keyword) {
const queryString = `?key=${keyword}`;
const objsUrls = OBJECTS_URLS.map(url => `${url}${queryString}`);
const objs = await loadUrls(objsUrls, loadObject);
const keywordObj = buildKeywordObj(objs[0], objs[1], keyword);
const template = await KEYWORD_TEMPLATE_PROMISE;
renderKeyword(template, keywordObj);
}
/**
* Builds a keyword object given a keyword, books, and projects.
*/
function buildKeywordObj(booksObj, projectsObj, keyword) {
let keywordObj = new Object();
keywordObj.term = keyword;
keywordObj.books = booksObj.books[keyword];
keywordObj.projects = projectsObj.results[keyword];
return keywordObj;
}
function renderKeyword(template, keywordObj) {
const keywordHTML = Mustache.render(template, keywordObj);
$('#keywords').prepend(keywordHTML);
}
/**
* Loads the civic section to the DOM, or alerts the user if there aren't any results for their location.
*/
async function loadCivicSection() {
const lat = getCookie("latitude");
const lng = getCookie("longitude");
if (lat != "" && lng != "") {
try {
const civicObj = await loadObject(`${CIVIC_OBJ_URL}?lat=${lat}&lng=${lng}`);
const locationObj = buildLocationObj(civicObj);
const locationTemplate = await LOCATION_TEMPLATE_PROMISE;
renderLocation(locationTemplate, locationObj);
} catch (err) {
alert("We couldn't find any civic information for your location.");
}
}
}
/**
* Builds a keyword object given a civic object returned by the civic API.
*/
function buildLocationObj(civicObj) {
let locationObj = new Object();
locationObj.address = civicObj.normalizedInput;
locationObj.levels = extractOfficials(civicObj);
return locationObj;
}
function renderLocation(template, locationObj) {
const locationHTML = Mustache.render(template, locationObj);
$('#keywords').append(locationHTML);
}
|
JavaScript
| 0 |
@@ -3073,24 +3073,17 @@
s =
-extractO
+o
fficials
(civ
@@ -3078,16 +3078,23 @@
fficials
+ByLevel
(civicOb
|
825252d994187e6eb0612043d32b7821781f81c4
|
Fix operation jsdocs
|
lib/operation.js
|
lib/operation.js
|
'use strict';
/**
* Module dependencies.
*/
var schema = require('./schema');
/**
* Initialize a new `Operation`.
*
* @param {Resource} resource
* @param {Object} spec
* @param {Function} fn
* @api private
*/
function Operation(spec, fn) {
if (!(this instanceof Operation)) {
return new Operation(spec, fn);
}
this.spec = spec;
this.fn = fn;
this.middleware = {};
}
/**
* Setup operation.
*
* @param {Resource} resource
* @api private
*/
Operation.prototype.setup = function(resource) {
resource.api.framework.env.validateThrow(schema.swagger.operation, this.spec);
this.resource = this.parent = resource;
};
/**
* Expose Operation.
*/
module.exports = Operation;
|
JavaScript
| 0.000009 |
@@ -120,38 +120,8 @@
%0A *%0A
- * @param %7BResource%7D resource%0A
* @
@@ -169,30 +169,29 @@
fn%0A * @api p
-rivate
+ublic
%0A */%0A%0Afuncti
|
8a125d4f918cb51a2f0dfa2ebffa05c428bc036c
|
Fix JavaScript tests (#824)
|
web/src/test/webapp/spec/routeManipulationSpec.js
|
web/src/test/webapp/spec/routeManipulationSpec.js
|
// because leaflet-src.js requires window, document etc. we need to provide these variables...
global.window = {};
global.document = {
documentElement: {
style: {}
},
getElementsByTagName: function() { return []; },
createElement: function() { return {}; }
};
global.navigator = {
userAgent: 'nodejs'
};
var L = require('leaflet');
var routeManipulation = requireFile('./routeManipulation.js');
/*some test data with url parameters:
?point=52.550,13.352&point=52.547,13.358&point=52.541,13.368&point=52.542,13.376&point=52.542,13.383
&point=52.545,13.391&point=52.542,13.408&point=52.539,13.424&point=52.533,13.441&point=52.527,13.447
&point=52.533,13.476&point=52.561,13.457&point=52.581,13.397 */
var a = L.latLng(52.5500, 13.3520);
var x1 = L.latLng(52.5470, 13.3580);
var x2 = L.latLng(52.5410, 13.3680);
var x3 = L.latLng(52.5420, 13.3760);
var b = L.latLng(52.5420, 13.3830);
var x4 = L.latLng(52.5450, 13.3910);
var x5 = L.latLng(52.5420, 13.4080);
var c = L.latLng(52.5390, 13.4240);
var x6 = L.latLng(52.5330, 13.4410);
var x7 = L.latLng(52.5270, 13.4470);
var d = L.latLng(52.5330, 13.4760);
var x8 = L.latLng(52.5610, 13.4570);
var x9 = L.latLng(52.5810, 13.3970);
var clickLocations = [
{ latlng: L.latLng(52.567,13.342), expectedIndex: 1},
{ latlng: L.latLng(52.540,13.378), expectedIndex: 1},
{ latlng: L.latLng(52.542,13.396), expectedIndex: 2},
{ latlng: L.latLng(52.526,13.463), expectedIndex: 3},
{ latlng: L.latLng(52.526,13.519), expectedIndex: 3}
];
describe('getIntermediatePointIndex', function () {
it('should work', function () {
var routeSegments = [{
coordinates: [a, x1, x2, x3, b, x4, x5, c, x6, x7, d],
wayPoints: [a, b, c, d]
}];
for(var i=0; i < clickLocations.length; ++i) {
expect(routeManipulation.getIntermediatePointIndex(routeSegments, clickLocations[i].latlng))
.toEqual(clickLocations[i].expectedIndex);
}
});
});
describe('getIntermediatePointIndex', function () {
it('should work for round trips', function () {
var routeSegments = [{
coordinates: [a, x1, x2, x3, b, x4, x5, c, x6, x7, d, x8, x9, a],
wayPoints: [a, b, c, d, a]
}];
var clickLocation = L.latLng(52.568,13.389);
expect(routeManipulation.getIntermediatePointIndex(routeSegments, clickLocation))
.toEqual(4);
});
});
describe('getIntermediaPointIndex', function() {
it('should yield a nice order if some parts of the route are crossed twice', function() {
// let 'a' be chosen as start and end point and 'b' as the first intermediate point. assume
// that the route a->b is (partly) the same as b->a. if we add a second intermediate point
// close to a road that is used on both ways we expect it to be inserted after 'b',
// and not before 'b'.
var routeSegments =[{
coordinates: [a, x1, x2, x3, b, x3, x2, x1, a],
wayPoints: [a, b, a]
}];
var clickLocation = L.latLng(52.540,13.376);
expect(routeManipulation.getIntermediatePointIndex(routeSegments, clickLocation))
.toEqual(2);
});
});
describe('getIntermediatePointIndex', function () {
it('should work when using alternative routes', function () {
var wayPoints = [a, b, c, d];
var routeSegments = [{
coordinates: [a, x1, x2, x3, b],
wayPoints: wayPoints
}, {
coordinates: [b, x4, x5, c],
wayPoints: wayPoints
}, {
coordinates: [c, x6, x7, d],
wayPoints: wayPoints
}];
for(var i=0; i < clickLocations.length; ++i) {
expect(routeManipulation.getIntermediatePointIndex(routeSegments, clickLocations[i].latlng))
.toEqual(clickLocations[i].expectedIndex);
}
});
});
|
JavaScript
| 0 |
@@ -1,12 +1,12 @@
//
-b
+B
ecause l
@@ -48,13 +48,23 @@
ment
- etc.
+, and navigator
we
@@ -70,16 +70,19 @@
need to
+%0A//
provide
@@ -98,18 +98,16 @@
riables.
-..
%0Aglobal.
@@ -116,16 +116,32 @@
ndow = %7B
+%0A screen: %7B%7D%0A
%7D;%0Agloba
@@ -321,24 +321,48 @@
vigator = %7B%0A
+ platform: 'nodejs',%0A
userAgen
@@ -1809,24 +1809,16 @@
%7D%5D;%0A
-
%0A
@@ -3753,20 +3753,16 @@
%7D%5D;%0A
-
%0A
|
cbe557a838ab90a45a833d94208f51d24d1a995a
|
Add AND operators to account for undefined objects
|
src/main/webapp/scripts/toggle.js
|
src/main/webapp/scripts/toggle.js
|
const KEYWORD_TEMPLATE_PROMISE = loadTemplate('/templates/keyword.html');
const LOCATION_TEMPLATE_PROMISE = loadTemplate('/templates/location.html');
const NO_KEYWORDS_HTML = loadTemplate('/templates/noKeywords.html')
let locationObj = null;
let language = null;
const KEYWORDS_OBJ_URL = '/keyword';
const CIVIC_OBJ_URL = '/actions/civic';
const NEWS_OBJ_URL = '/news';
const BOOKS_OBJ_URL = '/books';
const PROJECTS_OBJ_URL = '/actions/projects';
const OBJECTS_URLS = [NEWS_OBJ_URL, BOOKS_OBJ_URL, PROJECTS_OBJ_URL];
let loadingCounter;
/**
* Loads the content section.
* Returns a promise that resolves when everything loads.
*/
async function loadContentSection() {
let locationCookie = getCookie('location');
if (locationCookie != "") {
locationObj = JSON.parse(getCookie('location'))
}
const keywordsObj = await loadKeywords(KEYWORDS_OBJ_URL);
const keywords = keywordsObj["keywords"];
language = keywordsObj["language"][0];
if (keywords == null) {
$('#login-error').removeClass('hide');
hideLoading();
return;
}
const elementsToLoad = Math.max(keywords.length, 1);
counter.add(elementsToLoad);
loadingCounter = traceCounterMethods(counter, elementsToLoad);
if (keywords.length === 0) {
loadNoKeywords();
} else {
keywords.forEach(loadKeywordSection);
}
const address = encodeURI(getCookie('address'));
if (address != "") {
loadCivicSectionFromAddress(address);
} else if (locationObj) {
loadCivicSectionFromLocation(locationObj);
} else {
loadingCounter.decrement();
}
}
/**
* Loads the keywords array from a servlet or from cookies.
* Returns a promise of the keywords array.
*/
async function loadKeywords(keywordsUrl) {
const key = $("body").attr("data-key");
let keywords;
const keywordsCookie = getCookie(key);
if (keywordsCookie === "") {
keywords = await loadObject(`${keywordsUrl}?k=${key}`);
const keywordsJson = JSON.stringify(keywords);
setCookie(key, keywordsJson, 1);
} else {
keywords = JSON.parse(keywordsCookie);
}
return keywords;
}
async function loadNoKeywords() {
const noKeywordsHTML = await NO_KEYWORDS_HTML;
$('#keywords').append(noKeywordsHTML);
hideLoading();
loadingCounter.decrement();
}
function hideLoading() {
$("body").children(":not(#real-body)").addClass("hide");
$("#real-body").removeClass("hide").addClass("body");
}
function makeUrl(url, keyword) {
let queryString = `?key=${keyword}`;
let fullUrl = `${url}${queryString}`;
if (url === '/news') {
if (locationObj != null) {
fullUrl = `${fullUrl}&country=${locationObj["Short Country"]}`;
} else if (language != null) {
let country = languageToCountry(language);
fullUrl = `${fullUrl}&country=${country}`;
}
}
return fullUrl;
}
/**
* Loads a keyword section to the DOM.
*/
async function loadKeywordSection(keyword) {
const objsUrls = OBJECTS_URLS.map(url => makeUrl(url, keyword));
const objs = await loadUrls(objsUrls, loadObject);
const keywordObj = buildKeywordObj(objs[0], objs[1], objs[2], keyword);
const template = await KEYWORD_TEMPLATE_PROMISE;
renderKeyword(template, keywordObj);
loadingCounter.decrement();
}
/**
* Builds a keyword object given a keyword, news, books, and projects.
*/
function buildKeywordObj(newsObj, booksObj, projectsObj, keyword) {
let keywordObj = new Object();
keywordObj.term = keyword;
keywordObj.news = newsObj.news[keyword];
keywordObj.books = booksObj.books[keyword];
keywordObj.projects = projectsObj.results[keyword];
return keywordObj;
}
function renderKeyword(template, keywordObj) {
const keywordHTML = Mustache.render(template, keywordObj);
$('#keywords').prepend(keywordHTML);
hideLoading();
}
async function loadCivicSectionFromAddress(address) {
const civicObj = await loadObject(`${CIVIC_OBJ_URL}?address=${address}`);
if ('error' in civicObj) {
alert('Sorry, your current location is not supported');
} else {
const civicLocationObj = buildCivicLocationObj(civicObj);
const locationTemplate = await LOCATION_TEMPLATE_PROMISE;
renderLocation(locationTemplate, civicLocationObj);
}
loadingCounter.decrement();
}
/**
* Loads the civic section to the DOM, or alerts the user if there aren't any results for their location.
*/
async function loadCivicSectionFromLocation(locationObj) {
if (locationObj.Country === "United States") {
const address = locationObj2Address(locationObj);
loadCivicSectionFromAddress(address);
} else {
alert('Sorry, your current location is not supported');
loadingCounter.decrement();
}
}
/**
* Builds a civic location object given a civic object returned by the civic API.
*/
function buildCivicLocationObj(civicObj) {
let civicLocationObj = new Object();
civicLocationObj.address = civicObj.normalizedInput;
civicLocationObj.levels = officialsByLevel(civicObj);
return civicLocationObj;
}
function renderLocation(template, civicLocationObj) {
const locationHTML = Mustache.render(template, civicLocationObj);
$('#keywords').append(locationHTML);
hideLoading();
}
function languageToCountry(language) {
let country = "";
switch(language) {
case "en":
country = "us";
break;
case "zh":
country = "cn";
break;
case "ja":
country = "jp";
break;
case "ko":
country = "kp";
break;
case "pt":
country = "br";
break;
default:
country = language
}
return country;
}
|
JavaScript
| 0 |
@@ -3424,16 +3424,27 @@
j.news =
+ newsObj &&
newsObj
@@ -3479,16 +3479,28 @@
.books =
+ booksObj &&
booksOb
@@ -3540,16 +3540,31 @@
ojects =
+ projectsObj &&
project
|
e875478f2434beabc2247305a89c75bf2bf3553d
|
connect alllistings to store
|
client/src/components/Listing/AllListings/AllListings.js
|
client/src/components/Listing/AllListings/AllListings.js
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import { Container, Header, Card, Button, Divider } from 'semantic-ui-react';
export default class AllListings extends Component {
render() {
return (
<h2>AllListings</h2>
);
}
}
// const mapStateToProps = (state) => {
// }
// export default connect
|
JavaScript
| 0 |
@@ -182,31 +182,16 @@
eact';%0A%0A
-export default
class Al
@@ -226,18 +226,102 @@
%7B%0A
-render() %7B
+constructor(props) %7B%0A super(props);%0A %7D%0A%0A render() %7B%0A console.log('props', this.props);
%0A
@@ -371,19 +371,16 @@
%0A %7D%0A%7D%0A%0A
-//
const ma
@@ -412,36 +412,127 @@
%3E %7B%0A
-%0A// %7D%0A%0A// export default connect
+ const %7B allListings %7D = state.listing;%0A return %7B allListings %7D;%0A%7D%0A%0Aexport default connect(mapStateToProps)(AllListings);
|
c51dbc6ba604b31621bd4b520cf6c509330400ed
|
fix circular dependency detection
|
lib/engine.js
|
lib/engine.js
|
const minimatch = require('minimatch');
const cpp = require('child-process-promise');
const messages = require('./messages');
const Throat = require('throat');
const os = require('os');
const errors = require('./errors');
const fs = require('fs-extra');
const STARTED = Symbol('pending');
const COMPLETE = Symbol('complete');
class Recipe {
constructor(whether, howtodo, ignoreError) {
this.whether = whether;
this.howtodo = howtodo;
}
async run(ctx, item) {
try {
await this.howtodo.call(ctx, item);
} catch (e) {
if (!e.bddyIgnorable) { throw e; }
}
}
}
const fileRecipe = new Recipe(
async function (target) {
return await fs.exists('' + target)
},
async function (target) {
this.fulfill(target, await this.target.getUpdateTime());
}
)
class Definitions {
constructor() {
this.recipies = [
fileRecipe
];
}
forall(pattern, f) {
this.recipies.push(new Recipe(async target => minimatch(target + '', pattern), f))
return this;
}
async run(target, ctx) {
for (let j = this.recipies.length - 1; j >= 0; j--) {
if (await this.recipies[j].whether(target)) {
return ctx.start(target, () => this.recipies[j].run(ctx.for(target), target));
}
}
throw new errors.CannotFindRecipe(target);
}
createContext() {
return new Context(this);
}
}
class Context {
constructor(defs) {
this.definitions = defs;
this.chain = new Set();
this.tasks = new Map();
this.throat = Throat(os.cpus().length);
}
async command(cmd, ...args) {
return await this.throat(function () {
console.log(messages.DIAMOND, [cmd, ...args].join(' '));
let prom = cpp.spawn(cmd, args);
let proc = prom.childProcess;
proc.stdout.on('data', function (data) { process.stdout.write(data) });
proc.stderr.on('data', function (data) { process.stderr.write(data) });
return prom;
})
}
start(target, prom) {
const ctx = this;
const targetid = target + '';
if (this.tasks.has(targetid)) {
const status = this.tasks.get(targetid)
if (status.state === STARTED) {
return status.promise.then(function () { })
} else {
return Promise.resolve(null);
}
} else {
const prom1 = prom().then(function () { ctx.fulfill(target); })
this.tasks.set(targetid, {
state: STARTED,
time: new Date,
promise: prom1
});
return prom1;
}
}
fulfill(target, time) {
const targetid = target + '';
if (this.tasks.has(targetid)
&& this.tasks.get(targetid).state === COMPLETE) return;
this.tasks.set(targetid, { state: COMPLETE, time: time || new Date() });
}
for(target) {
let that = new TargetContext(this.definitions, target);
that.tasks = this.tasks;
that.chain = new Set(this.chain);
that.chain.add(target);
return that;
}
}
class TargetContext extends Context {
constructor(defs, target) {
super(defs);
this.target = target;
}
async check(...prerequisites) {
let tasks = [];
for (let prerequisite of prerequisites) {
if (this.chain.has(prerequisite + '')) {
throw new errors.Circular(prerequisite);
}
tasks.push(this.definitions.run(prerequisite, this));
}
return tasks;
}
async need(...prerequisites) {
let tasks = await this.check(...prerequisites);
await Promise.all(tasks);
let needUpdate = false;
for (let p of prerequisites) {
let status = this.tasks.get(p + '');
if (!status || status.state !== COMPLETE) {
throw new errors.Incomplete(p);
}
needUpdate = needUpdate || await this.target.needUpdate(status.time);
}
if (!needUpdate) {
this.fulfill(this.target, await this.target.getUpdateTime());
throw new errors.NothingToDo;
}
return prerequisites;
}
}
exports.Definitions = Definitions;
exports.Context = Context;
|
JavaScript
| 0.000005 |
@@ -1142,24 +1142,58 @@
target)) %7B%0D%0A
+%09%09%09%09const ctx1 = ctx.for(target)%0D%0A
%09%09%09%09return c
@@ -1194,16 +1194,17 @@
turn ctx
+1
.start(t
@@ -1240,28 +1240,17 @@
.run(ctx
-.for(target)
+1
, target
@@ -2820,24 +2820,29 @@
n.add(target
+ + ''
);%0D%0A%09%09return
|
1d620ff868c96cb0a31ec2cf5264daeaf37783ee
|
Add the show method.
|
cleverlay.js
|
cleverlay.js
|
/*============================================================================*\
________ __
/ ____/ /__ _ _____ _____/ /___ ___ __
/ / / / _ \ | / / _ \/ ___/ / __ `/ / / /
/ /___/ / __/ |/ / __/ / / / /_/ / /_/ /
\____/_/\___/|___/\___/_/ /_/\__,_/\__, /
/____/
JavaScript for Cleverlay
-----------------------------------------------------------------------
© 2010-2015 by Carroket, Inc.
http://www.carroket.com/
-----------------------------------------------------------------------
Made by Brian Sexton.
http://www.briansexton.com/
-----------------------------------------------------------------------
MIT License
\*============================================================================*/
(function(document, options) {
var cleverlay = new Cleverlay();
function Cleverlay() {
if (options instanceof Object && options.autoRun === true) {
this.autoRun = true;
}
}
// TO DO: Write it, cut it, paste it, save it. Load it, check it, quick—rewrite it.
Cleverlay.prototype.addImage = function(url, width, height, alt) {
var contentFrame = document.createElement('div');
var img = document.createElement('img');
// Prepare the content frame.
contentFrame.id = 'PageOverlayContentFrame';
contentFrame.className = 'CleanContentFrame';
contentFrame.style.width = width + 'px';
// Prepare the img element.
img.src = url;
img.alt = alt;
img.width = width;
img.height = height;
img.id = 'PageOverlayImage';
// Assemble the content.
contentFrame.appendChild(img);
this.overlay.appendChild(contentFrame);
};
Cleverlay.prototype.addPageOverlay = function() {
var backdrop = document.createElement('div');
var closeButton = document.createElement('div');
this.overlay = document.createElement('div');
// Prepare the overlay.
this.overlay.id = 'PageOverlay';
// Prepare the backdrop.
backdrop.id = 'PageOverlayBackdrop';
// Prepare the close button.
closeButton.id = 'PageOverlayCloseButton';
closeButton.onclick = this.removePageOverlay;
// Assemble everything.
this.overlay.appendChild(backdrop);
this.overlay.appendChild(closeButton);
document.body.appendChild(this.overlay);
};
Cleverlay.prototype.addSWF = function(url, width, height) {
var contentFrame = document.createElement('div');
var swfObject = document.createElement('object');
var swfParam = document.createElement('param');
this.overlay.style.height = document.body.offsetHeight + 'px';
// Prepare the content frame.
contentFrame.id = 'PageOverlayContentFrame';
contentFrame.className = 'CleanContentFrame';
contentFrame.style.width = width + 'px';
swfObject.data = url;
swfObject.width = width;
swfObject.height = height;
swfObject.id = 'PageOverlaySWFObject';
swfObject.title = 'SWF Content (' + url + ')';
// Prepare the SWF param element.
swfParam.name = 'movie';
swfParam.value = url;
// Assemble the content.
swfObject.appendChild(swfParam);
contentFrame.appendChild(swfObject);
this.overlay.appendChild(contentFrame);
};
Cleverlay.prototype.removePageOverlay = function() {
var backdrop = document.getElementById('PageOverlayBackdrop');
var closeButton = document.getElementById('PageOverlayCloseButton');
var contentFrame = document.getElementById('PageOverlayContentFrame');
var swfObject = document.getElementById('PageOverlaySWFObject');
this.overlay = document.getElementById('PageOverlay');
this.overlay.removeChild(closeButton);
if (swfObject) {
contentFrame.removeChild(swfObject);
}
document.body.removeChild(this.overlay);
this.overlay.removeChild(contentFrame);
this.overlay.removeChild(backdrop);
};
Cleverlay.prototype.showContent = function(url, type, width, height, token) {
if (type == 'swf')
{
this.addPageOverlay();
this.addSWF(url, width, height);
return false;
}
else if (type == 'image')
{
this.addPageOverlay();
this.addImage(url, width, height, token);
return false;
}
else
{
return true;
}
};
Cleverlay.prototype.validateContentObject = function(object) {
if (object.hasOwnProperty("url") && object.hasOwnProperty("type") && object.hasOwnProperty("width") && object.hasOwnProperty("height") && object.hasOwnProperty("token")) {
return true;
}
else {
return false;
}
};
// If a namespace was specified, attach cleverlay to it.
if (options instanceof Object && options.namespace instanceof Object) {
options.namespace.cleverlay = cleverlay;
}
})(window.document);
|
JavaScript
| 0.000001 |
@@ -3748,32 +3748,261 @@
backdrop);%0A%09%7D;%0A%0A
+%09Cleverlay.prototype.show = function(object) %7B%0A%0A%09%09if (this.validateContentObject(object)) %7B%0A%0A%09%09%09return this.showContent(object.url, object.type, object.width, object.height, object.token);%0A%09%09%7D%0A%0A%09%09else %7B%0A%0A%09%09%09return true;%0A%09%09%7D%0A%09%7D;%0A%0A
%09Cleverlay.proto
|
e7e50318b561e191560faebe62e492ca2d06dd79
|
fix cli/utils test
|
cli/utils.js
|
cli/utils.js
|
/**
* Copyright 2013-2019 the original author or authors from the JHipster project.
*
* This file is part of the JHipster project, see https://www.jhipster.tech/
* for more information.
*
* 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.
*/
/* eslint-disable no-console */
const chalk = require('chalk');
const didYouMean = require('didyoumean');
const meow = require('meow');
const yeoman = require('yeoman-environment');
const _ = require('lodash');
const SUB_GENERATORS = require('./commands');
const CLI_NAME = 'jhipster';
const GENERATOR_NAME = 'generator-jhipster';
const debug = function(msg) {
if (this.debugEnabled) {
console.log(`${chalk.blue('DEBUG!')} ${msg}`);
}
};
const info = function(msg) {
console.info(`${chalk.green.bold('INFO!')} ${msg}`);
};
const log = function(msg) {
console.log(msg);
};
const error = function(msg, trace) {
console.error(`${chalk.red(msg)}`);
if (trace) {
console.log(trace);
}
process.exit(1);
};
const init = function(program) {
program.option('-d, --debug', 'enable debugger');
const argv = program.normalize(process.argv);
this.debugEnabled = program.debug = argv.includes('-d') || argv.includes('--debug'); // Need this early
if (this.debugEnabled) {
info('Debug logging is on');
}
};
const logger = {
init,
debug,
info,
log,
error
};
const toString = item => {
if (typeof item == 'object') {
if (Array.isArray(item)) {
return item.map(it => toString(it)).join(', ');
}
return Object.keys(item)
.map(k => `${k}: ${typeof item[k] != 'function' && typeof item[k] != 'object' ? toString(item[k]) : 'Object'}`)
.join(', ');
}
return item ? item.toString() : item;
};
const initHelp = (program, cliName) => {
program.on('--help', () => {
logger.debug('Adding additional help info');
logger.info(` For more info visit ${chalk.blue('https://www.jhipster.tech')}`);
logger.info('');
});
program.on('command:*', name => {
console.error(chalk.red(`${chalk.yellow(name)} is not a known command. See '${chalk.white(`${cliName} --help`)}'.`));
const cmd = Object.values(name).join('');
const availableCommands = program.commands.map(c => c._name);
const suggestion = didYouMean(cmd, availableCommands);
if (suggestion) {
logger.info(`Did you mean ${chalk.yellow(suggestion)}?`);
}
process.exit(1);
});
};
/**
* Get arguments
*/
const getArgs = opts => {
if (opts.argument) {
return `[${opts.argument.join('|')}]`;
}
return '';
};
/**
* Get options from arguments
*/
const getOptionsFromArgs = args => {
const options = [];
args.forEach(item => {
if (typeof item == 'string') {
options.push(item);
} else if (typeof item == 'object') {
if (Array.isArray(item)) {
options.push(...item);
}
}
});
return options;
};
/* Convert option objects to command line args */
const getOptionAsArgs = (options, withEntities, force) => {
const args = Object.entries(options).map(([key, value]) => {
const prefix = key.length === 1 ? '-' : '--';
if (value === true) {
return `${prefix}${_.kebabCase(key)}`;
}
if (value === false) {
return `${prefix}no-${_.kebabCase(key)}`;
}
return value ? `${prefix}${_.kebabCase(key)} ${value}` : '';
});
if (withEntities) args.push('--with-entities');
if (force) args.push('--force');
args.push('--from-cli');
logger.debug(`converted options: ${args}`);
return _.uniq(args.join(' ').split(' ')).filter(it => it !== '');
};
/**
* Get options for the command
*/
const getCommand = (cmd, args, opts) => {
let options = [];
if (opts && opts.argument && opts.argument.length > 0) {
logger.debug('Arguments found');
options = getOptionsFromArgs(args);
}
if (args && args.length === 1) {
logger.debug('No Arguments found.');
}
const cmdArgs = options.join(' ').trim();
logger.debug(`cmdArgs: ${cmdArgs}`);
return `${CLI_NAME}:${cmd}${cmdArgs ? ` ${cmdArgs}` : ''}`;
};
const getCommandOptions = (pkg, argv) => {
const options = meow({ help: false, pkg, argv });
const flags = options ? options.flags : null;
if (flags) {
flags['from-cli'] = true;
// Add un-camelized options too, for legacy
Object.keys(flags).forEach(key => {
const legacyKey = key.replace(/[A-Z]/g, m => `-${m.toLowerCase()}`);
flags[legacyKey] = flags[key];
});
return flags;
}
return { 'from-cli': true };
};
const done = errorMsg => {
if (errorMsg) {
logger.error(`${chalk.red.bold('ERROR!')} ${errorMsg}`);
} else {
logger.info(chalk.green.bold('Congratulations, JHipster execution is complete!'));
}
};
const createYeomanEnv = () => {
const env = yeoman.createEnv();
/* Register yeoman generators */
Object.keys(SUB_GENERATORS)
.filter(command => !SUB_GENERATORS[command].cliOnly)
.forEach(generator => {
if (SUB_GENERATORS[generator].blueprint) {
/* eslint-disable prettier/prettier */
env.register(require.resolve(`${SUB_GENERATORS[generator].blueprint}/generators/${generator}`), `${CLI_NAME}:${generator}`);
} else {
env.register(require.resolve(`../generators/${generator}`), `${CLI_NAME}:${generator}`);
}
});
return env;
};
module.exports = {
CLI_NAME,
GENERATOR_NAME,
toString,
logger,
initHelp,
getArgs,
getOptionsFromArgs,
getCommand,
getCommandOptions,
done,
createYeomanEnv,
getOptionAsArgs
};
|
JavaScript
| 0.000001 |
@@ -3154,17 +3154,17 @@
t.join('
-%7C
+
')%7D%5D%60;%0A
|
4364ba171fda9aa62b3d628d4754944a7c6ef5c9
|
Add tests for toggle timer
|
edx_proctoring/static/proctoring/spec/proctored_exam_spec.js
|
edx_proctoring/static/proctoring/spec/proctored_exam_spec.js
|
describe('ProctoredExamView', function () {
beforeEach(function () {
this.server = sinon.fakeServer.create();
jasmine.clock().install();
setFixtures(
'<div class="proctored_exam_status">' +
'<script type="text/template" id="proctored-exam-status-tpl">' +
'<div class="exam-timer">' +
'You are taking "' +
'<a href="<%= exam_url_path %>"> <%= exam_display_name %> </a>' +
'" as a proctored exam. The timer on the right shows the time remaining in the exam' +
'<span id="time_remaining_id" class="pull-right"> <b> </b> </span> </div>' +
'</script>'+
'</div>'
);
this.model = new ProctoredExamModel({
in_timed_exam: true,
is_proctored: true,
exam_display_name: 'Midterm',
taking_as_proctored: true,
exam_url_path: '/test_url',
time_remaining_seconds: 45, //2 * 60 + 15,
low_threshold_sec: 30,
attempt_id: 2,
critically_low_threshold_sec: 15,
lastFetched: new Date()
});
this.proctored_exam_view = new edx.coursware.proctored_exam.ProctoredExamView(
{
model: this.model,
el: $(".proctored_exam_status"),
proctored_template: '#proctored-exam-status-tpl'
}
);
this.proctored_exam_view.render();
});
afterEach(function() {
this.server.restore();
jasmine.clock().uninstall();
});
it('renders items correctly', function () {
expect(this.proctored_exam_view.$el.find('a')).toHaveAttr('href', this.model.get("exam_url_path"));
expect(this.proctored_exam_view.$el.find('a')).toContainHtml(this.model.get('exam_display_name'));
});
it('changes behavior when clock time decreases low threshold', function () {
this.proctored_exam_view.secondsLeft = 25;
this.proctored_exam_view.render();
expect(this.proctored_exam_view.$el.find('div.exam-timer')).toHaveClass('low-time warning');
});
it('changes behavior when clock time decreases critically low threshold', function () {
this.proctored_exam_view.secondsLeft = 5;
this.proctored_exam_view.render();
expect(this.proctored_exam_view.$el.find('div.exam-timer')).toHaveClass('low-time critical');
});
it("reload the page when the exam time finishes", function(){
this.proctored_exam_view.secondsLeft = -10;
var reloadPage = spyOn(this.proctored_exam_view, 'reloadPage');
this.proctored_exam_view.updateRemainingTime(this.proctored_exam_view);
expect(reloadPage).toHaveBeenCalled();
});
it("resets the remainig exam time after the ajax response", function(){
this.server.respondWith(
"GET",
"/api/edx_proctoring/v1/proctored_exam/attempt/" +
this.proctored_exam_view.model.get('attempt_id') +
'?sourceid=in_exam&proctored=true',
[
200,
{"Content-Type": "application/json"},
JSON.stringify({
time_remaining_seconds: -10
})
]
);
this.proctored_exam_view.timerTick = this.proctored_exam_view.poll_interval-1; // to make the ajax call.
var reloadPage = spyOn(this.proctored_exam_view, 'reloadPage');
this.proctored_exam_view.updateRemainingTime(this.proctored_exam_view);
this.server.respond();
this.proctored_exam_view.updateRemainingTime(this.proctored_exam_view);
expect(reloadPage).toHaveBeenCalled();
});
});
|
JavaScript
| 0 |
@@ -574,68 +574,258 @@
pan
-id=%22time_remaining_id%22 class=%22pull-right%22%3E %3Cb%3E %3C/b%3E %3C/span%3E
+class=%22exam-timer-clock%22%3E %3Cspan id=%22time_remaining_id%22%3E' +%0A '%3Cb%3E %3C/b%3E %3Ca id=%22toggle_timer%22 href=%22#%22 title=%22Hide Timer%22%3E' +%0A '%3Ci class=%22fa fa-eye-slash%22 aria-hidden=%22true%22%3E%3C/i%3E%3C/a%3E' +%0A '%3C/span%3E %3C/span%3E' +%0A '
%3C/di
@@ -1859,24 +1859,45 @@
el.find('a')
+.not('#toggle_timer')
).toHaveAttr
@@ -1993,16 +1993,37 @@
ind('a')
+.not('#toggle_timer')
).toCont
@@ -2537,32 +2537,32 @@
_view.render();%0A
-
expect(t
@@ -2647,32 +2647,463 @@
ical');%0A %7D);%0A
+ it('toggles timer visibility correctly', function() %7B%0A var button = this.proctored_exam_view.$el.find('#toggle_timer');%0A var timer = this.proctored_exam_view.$el.find('span#time_remaining_id b');%0A expect(timer).not.toHaveClass('timer-hidden');%0A button.click();%0A expect(timer).toHaveClass('timer-hidden');%0A button.click();%0A expect(timer).not.toHaveClass('timer-hidden');%0A %7D);%0A
it(%22reload t
|
808f2a844a49fc6d7168c1c5ef8216f4821e2f56
|
Fix for de_DE locale
|
src/main/webapp/tests/testI18N.js
|
src/main/webapp/tests/testI18N.js
|
var testI18N = function()
{
var driver = new Gitana.Driver();
var setupHandler1 = function(status)
{
if (!status.isOk())
{
alert("Create failed");
}
// read the repository back
driver.repositories().read(status.getId(), setupHandler2);
};
var setupHandler2 = function(repository)
{
var _this = this;
this.repository = repository;
// read the master branch
this.repository.branches().read("master", function(branch) {
_this.branch = branch;
test1();
});
};
var test1 = function()
{
var _this = this;
var masterObject = {
"title": "english1",
"_features": {
"f:multilingual": {
"edition": "edition1"
}
}
};
_this.branch.nodes().create(masterObject, function(status) {
// read the master node back
_this.branch.nodes().read(status.getId(), function(masterNode) {
// build a translation into german "edition1"
var german = { "title": "german1" };
masterNode.translations().create("edition1", "de_ED", german, function(germanTranslation) {
// build a translation into chinese "edition1"
var chinese = { "title": "chinese1" };
masterNode.translations().create("edition1", "zh_CN", chinese, function(chineseTranslation) {
test2(masterNode);
});
});
});
});
};
var test2 = function(masterNode)
{
masterNode.translations().editions(function(editions){
if (editions.length != 1)
{
alert("There should have been 1 edition");
}
masterNode.translations().locales("edition1", function(locales) {
if (locales.length != 2)
{
alert("There should have been 2 locales");
}
test3(masterNode);
});
})
};
var test3 = function(masterNode)
{
masterNode.translations().translate("de_ED", function(germanLocalized) {
if (germanLocalized.getTitle() != "german1")
{
alert("didn't get german back");
}
test4(masterNode);
});
};
var test4 = function(masterNode)
{
masterNode.translations().translate("edition1", "zh_CN", function(chineseLocalized) {
if (chineseLocalized.getTitle() != "chinese1")
{
alert("didn't get chinese back");
}
test5(masterNode);
});
};
var test5 = function(masterNode)
{
masterNode.translations().translate("xx_YY", function(unlocalized) {
if (unlocalized.getTitle() != "english1")
{
alert("didn't get unlocalized back");
}
success();
});
};
var success = function()
{
alert("success");
};
// kick off the test after logging in
driver.security().authenticate("admin", "admin", function() {
driver.repositories().create(setupHandler1);
});
};
|
JavaScript
| 0.000006 |
@@ -1240,18 +1240,18 @@
1%22, %22de_
-E
D
+E
%22, germa
@@ -2268,10 +2268,10 @@
%22de_
-E
D
+E
%22, f
|
55228e89d3b42a5e9af041b0d3eb78b63406352c
|
Make sure service is defined when instanciating a Publisher
|
lib/publisher.js
|
lib/publisher.js
|
'use strict';
var Map = require('immutable').Map;
var Moment = require('moment');
var Promise = require('promise');
/**
* Pure function that publish a set of metadata to an external service.
*
* @class
* @param {Object} service - An object implementing a `post` function
*/
var Publisher = function (service) {
if (typeof(service.post) !== "function") {
throw new TypeError('service must implement a post function');
}
this.service = service;
}
/**
* Publish the set of metadata using a POSTable service.
*
* @param {Map.<string, *>} metadata - The metadata of the document to publish
* @returns Promise.<Array.<String>> A list of publication errors for this set of metadata
*/
Publisher.prototype.publish = function (metadata) {
if (!(metadata instanceof Map)) throw new TypeError('metadata must be a Map');
return this.service.post({
specversion: {
status: metadata.get('status'),
uri: metadata.get('thisVersion'),
latestVersionUri: metadata.get('latestVersion'),
previousVersionUri: metadata.get('previousVersion'),
date: Moment(metadata.get('docDate')).format('YYYY-MM-DD'),
title: metadata.get('title'),
deliverers: metadata.get('delivererIDs'),
editors: metadata.get('editorIds'),
informative: false, // FIXME Not always true
editorDraft: metadata.get('editorsDraft'),
processRules: metadata.get('process')
}
}).then(function (foobar) {
var response = foobar.response;
var body = foobar.body;
switch (response.statusCode) {
case 501: return Promise.reject(new Error(body.message));
case 400: return Promise.resolve(body.errors);
case 201: return Promise.resolve([]);
default:
return Promise.reject(new Error(
"There was an error when publishing: code " + response.statusCode
));
}
});
}
module.exports = Publisher;
|
JavaScript
| 0 |
@@ -323,16 +323,47 @@
(typeof
+ service !== 'object' %7C%7C typeof
(service
@@ -425,16 +425,31 @@
ce must
+be defined and
implemen
|
db9702150c52347ebbe225ad0f68eefea5e9c2b7
|
improve comments in create method file
|
src/methods/create.js
|
src/methods/create.js
|
// CREATE TASK
// this is the first task you can call from teleport to build project:
// - it decides if the name of the project is good set
// (and if not, it will give you one random)
// - it checks if there is a folder with the same project name here
// - it checks if there is no such project already refered into the .projects.json
// of your teleport app
// - it creates your folder that will contain the file system
// - it calls the sub tasks init
import childProcess from 'child_process'
import fs from 'fs'
import path from 'path'
export function create () {
// unpack
const { app, project, program } = this
// check if such a project exists already here
project.dir = path.join(this.currentDir, program.project)
this.consoleInfo(`wait a second... We create your ${program.project} project !`)
if (fs.existsSync(project.dir)) {
this.consoleWarn(`There is already a ${program.project} here...`)
process.exit()
}
const projectsByName = app.projectsByName
const previousProject = projectsByName[program.project]
if (previousProject) {
this.consoleWarn(`There is already a ${program.project} here ${previousProject.dir}...`)
process.exit()
}
projectsByName[program.project] = {
dir: project.dir
}
this.writeProjectsByName(projectsByName)
// mkdir the folder app
childProcess.execSync(`mkdir -p ${program.project}`)
// write default package
this.init()
// info
this.consoleInfo(`Your ${program.project} was successfully created, go inside with \'cd ${program.project}\' !`)
}
|
JavaScript
| 0 |
@@ -74,16 +74,17 @@
ild
+
project
-:
+.
%0A//
@@ -127,15 +127,16 @@
ect
-is good
+has been
set
@@ -173,18 +173,24 @@
you
-o
+a ge
ne
-
ra
-ndom
+ted name
)%0A//
@@ -206,130 +206,132 @@
cks
-if there is a folder with the same project name here%0A// - it checks if there is no such project already refered into
+that the project name is not already existing on the file system%0A// - it checks that the project name is not already in
the
-.
proj
@@ -339,16 +339,21 @@
cts.json
+ file
%0A// of y
@@ -364,20 +364,16 @@
teleport
- app
%0A// - it
@@ -379,17 +379,16 @@
t create
-s
your fo
@@ -458,16 +458,23 @@
sks init
+ method
%0A%0Aimport
@@ -667,22 +667,22 @@
ect
-exists
already
+ exists
her
|
ac662c0a82919e01082e1aff873971f38424c462
|
fix an error when res.count is not defined.
|
lib/queryable.js
|
lib/queryable.js
|
var _ = require("underscore")._;
var assert = require("assert");
var util = require('util');
var Entity = require('./entity');
var Where = require("./where");
var ArgTypes = require("./arg_types");
var DA = require("deasync");
/**
* Represents a queryable database entity (table or view).
* @param {[type]} args [description]
*/
var Queryable = function() {
Entity.apply(this, arguments);
// create delimited names now instead of at query time
this.delimitedName = "\"" + this.name + "\"";
this.delimitedSchema = "\"" + this.schema + "\"";
// handle naming when schema is other than public:
if(this.schema !== "public") {
this.fullname = this.schema + "." + this.name;
this.delimitedFullName = this.delimitedSchema + "." + this.delimitedName;
} else {
this.fullname = this.name;
this.delimitedFullName = this.delimitedName;
}
};
util.inherits(Queryable, Entity);
//a simple alias for returning a single record
Queryable.prototype.findOne = function() {
var args = ArgTypes.findArgs(arguments, this);
this.find(args.conditions, args.query, function(err,results) {
if (err) {
args.next(err,null);
} else {
var result;
if (_.isArray(results)) {
if (results.length > 0) { result = results[0]; }
} else {
result = results;
}
args.next(null,result);
}
});
};
Queryable.prototype.findOneSync = DA(Queryable.prototype.findOne);
/**
* Counts rows and calls back with any error and the total. There are two ways to use this method:
*
* 1. find() style: db.mytable.count({field: value}, callback);
* 2. where() style: db.mytable.count("field=$1", [value], callback);
*/
Queryable.prototype.count = function() {
var args;
var where;
if (_.isObject(arguments[0])) {
args = ArgTypes.findArgs(arguments, this);
where = _.isEmpty(args.conditions) ? {where : " "} : Where.forTable(args.conditions);
} else {
args = ArgTypes.whereArgs(arguments, this);
where = {where: " where " + args.where};
}
args.query.columns = "COUNT(1)";
args.query.order = null;
var sql = args.query.format(where.where);
this.db.query(sql, where.params || args.params, {single : true}, function(err, res) {
if (err) args.next(err, null);
else args.next(null, res.count);
});
};
Queryable.prototype.countSync = DA(Queryable.prototype.count);
//a simple way to just run something
//just pass in "id=$1" and the criteria
Queryable.prototype.where = function(){
var args = ArgTypes.whereArgs(arguments, this);
var sql = args.query.format("where " + args.where);
this.db.query(sql, args.params, args.next);
};
Queryable.prototype.whereSync = DA(Queryable.prototype.where);
Queryable.prototype.find = function() {
var args = ArgTypes.findArgs(arguments, this);
if (typeof this.primaryKeyName === 'function' && Where.isPkSearch(args.conditions)) {
var newArgs = {};
newArgs[this.primaryKeyName()] = args.conditions;
args.conditions = newArgs;
args.query.single = true;
}
var where = _.isEmpty(args.conditions) ? {where: " "} : Where.forTable(args.conditions);
var sql = args.query.format(where.where);
if (args.query.stream) {
this.db.stream(sql, where.params, args.query, args.next);
} else {
this.db.query(sql, where.params, args.query, args.next);
}
};
Queryable.prototype.findSync = DA(Queryable.prototype.find);
Queryable.prototype.search = function(args, next){
//search expects a columns array and the term
assert(args.columns && args.term, "Need columns as an array and a term string");
if(!_.isArray(args.columns)){
args.columns = [args.columns];
}
var tsv;
var vectorFormat = 'to_tsvector("%s")';
if(args.columns.length === 1){
tsv = util.format("%s", args.columns[0]);
}else{
vectorFormat = 'to_tsvector(%s)';
tsv= util.format("concat('%s')", args.columns.join(", ', '"));
}
var sql = "select * from " + this.delimitedFullName + " where " + util.format(vectorFormat, tsv);
sql+= " @@ to_tsquery($1);";
this.db.query(sql, [args.term],next);
};
Queryable.prototype.searchSync = DA(Queryable.prototype.search);
module.exports = Queryable;
|
JavaScript
| 0 |
@@ -2261,33 +2261,101 @@
lse
-args.next(null, res.count
+if (res && res.count !== undefined) args.next(null, res.count);%0A else args.next(null, null
);%0A
|
ced41eb65e11b098739ac596be056091e0bf0883
|
Fix #371 - bug with hovers
|
src/misc/sigma.misc.drawHovers.js
|
src/misc/sigma.misc.drawHovers.js
|
;(function(undefined) {
'use strict';
if (typeof sigma === 'undefined')
throw 'sigma is not declared';
// Initialize packages:
sigma.utils.pkg('sigma.misc');
/**
* This method listens to "overNodes" and "outNodes" events from a renderer
* and renders the nodes differently on the top layer. The goal is to make any
* label readable with the mouse.
*
* It has to be called in the scope of the related renderer.
*/
sigma.misc.drawHovers = function(prefix) {
var self = this,
hoveredNodes = [];
this.bind('overNode', function(event) {
hoveredNodes.push(event.data.node);
draw();
});
this.bind('outNode', function(event) {
var indexCheck = hoveredNodes.map(function(n) {
return n;
}).indexOf(event.data.node);
hoveredNodes.splice(indexCheck, 1);
draw();
});
this.bind('render', function(event) {
draw();
});
function draw() {
// Clear self.contexts.hover:
self.contexts.hover.canvas.width = self.contexts.hover.canvas.width;
var k,
renderers = sigma.canvas.hovers,
embedSettings = self.settings.embedObjects({
prefix: prefix
});
// Single hover
if (
embedSettings('enableHovering') &&
embedSettings('singleHover') &&
hoveredNodes.length
) {
if (! hoveredNodes[hoveredNodes.length - 1].hidden) {
(
renderers[hoveredNodes[hoveredNodes.length - 1].type] ||
renderers.def
)(
hoveredNodes[hoveredNodes.length - 1],
self.contexts.hover,
embedSettings
);
}
}
// Multiple hover
if (
embedSettings('enableHovering') &&
!embedSettings('singleHover') &&
hoveredNodes.length
) {
for (var i = 0; i < hoveredNodes.length; i++) {
if (! hoveredNodes[i].hidden) {
(renderers[hoveredNodes[i].type] || renderers.def)(
hoveredNodes[i],
self.contexts.hover,
embedSettings
);
}
}
}
}
};
}).call(this);
|
JavaScript
| 0 |
@@ -509,24 +509,26 @@
this,%0A
+
hoveredNodes
@@ -534,10 +534,10 @@
s =
-%5B%5D
+%7B%7D
;%0A%0A
@@ -589,44 +589,102 @@
-hoveredNodes.push(event.data.node);%0A
+var node = event.data.node;%0A if (!node.hidden) %7B%0A hoveredNodes%5Bnode.id%5D = node;%0A
@@ -685,32 +685,40 @@
draw();%0A
+ %7D%0A
%7D);%0A%0A thi
@@ -763,149 +763,47 @@
-var indexCheck = hoveredNodes.map(function(n) %7B%0A return n;%0A %7D).indexOf(event.data.node);%0A hoveredNodes.splice(indexCheck, 1)
+delete hoveredNodes%5Bevent.data.node.id%5D
;%0A
@@ -1035,16 +1035,41 @@
var k,%0A
+ hoveredNode,%0A
@@ -1101,16 +1101,18 @@
hovers,%0A
+
@@ -1166,16 +1166,18 @@
+
prefix:
@@ -1183,16 +1183,18 @@
prefix%0A
+
@@ -1314,32 +1314,44 @@
er') &&%0A
+Object.keys(
hoveredNodes.len
@@ -1338,32 +1338,33 @@
eys(hoveredNodes
+)
.length%0A )
@@ -1368,30 +1368,24 @@
) %7B%0A
- if (!
hoveredNode
@@ -1376,34 +1376,35 @@
hoveredNode
-s%5B
+ =
hoveredNodes.len
@@ -1403,123 +1403,79 @@
odes
-.length - 1%5D.hidden) %7B%0A (%0A renderers%5BhoveredNodes%5BhoveredNodes.length - 1%5D.type%5D %7C%7C%0A
+%5BObject.keys(hoveredNodes)%5B0%5D%5D;%0A (renderers%5BhoveredNode.type%5D %7C%7C
ren
@@ -1488,24 +1488,11 @@
.def
-%0A
)(%0A
-
@@ -1512,34 +1512,8 @@
Node
-s%5BhoveredNodes.length - 1%5D
,%0A
@@ -1512,34 +1512,32 @@
Node,%0A
-
self.contexts.ho
@@ -1533,34 +1533,32 @@
contexts.hover,%0A
-
embedS
@@ -1577,23 +1577,11 @@
-
);%0A
- %7D%0A
@@ -1704,121 +1704,36 @@
er')
- &&%0A hoveredNodes.length%0A ) %7B%0A for (var i = 0; i %3C hoveredNodes.length; i++) %7B%0A if (!
+%0A ) %7B%0A for (k in
hov
@@ -1745,24 +1745,12 @@
odes
-%5Bi%5D.hidden
) %7B%0A
-
@@ -1779,17 +1779,17 @@
edNodes%5B
-i
+k
%5D.type%5D
@@ -1811,34 +1811,32 @@
f)(%0A
-
hoveredNodes%5Bi%5D,
@@ -1836,14 +1836,12 @@
des%5B
-i
+k
%5D,%0A
-
@@ -1873,34 +1873,32 @@
er,%0A
-
embedSettings%0A
@@ -1909,24 +1909,10 @@
- );%0A %7D
+);
%0A
@@ -1926,18 +1926,16 @@
%7D%0A
-%0A%0A
%7D%0A
|
749cd238f0598d1ac6c9ab4f138266b051536461
|
Allow arrays in responses.
|
src/shared/state/util/npmsRequest.js
|
src/shared/state/util/npmsRequest.js
|
import Promise from 'bluebird';
import axios from 'axios';
import config from 'config';
import isPlainObject from 'lodash/isPlainObject';
function createUrl(path) {
return `${config.api.url.replace(/\/+$/, '')}/${path.replace(/^\/+/, '')}`;
}
function onFullfilled(res) {
if (!isPlainObject(res.data)) {
throw Object.assign(new Error('Unexpected response'),
{ status: res.status, statusText: res.statusText || 'Unknown' });
}
return res.data;
}
function onRejected(res) {
if (res instanceof Error) {
throw res;
}
if (!isPlainObject(res.data)) {
throw Object.assign(new Error(`${res.status} - ${res.statusText || 'Unknown'}`),
{ status: res.status, statusText: res.statusText || 'Unknown' });
}
throw Object.assign(new Error(res.data.message),
{ status: res.status, statusText: res.statusText || 'Unknown' });
}
export default function npmsRequest(path, options) {
options = { timeout: config.api.timeout, ...options };
return Promise.try(() => {
return axios(createUrl(path), options)
.then((res) => onFullfilled(res), (res) => onRejected(res));
});
}
|
JavaScript
| 0 |
@@ -295,32 +295,60 @@
Object(res.data)
+ && !Array.isArray(res.data)
) %7B%0A thro
@@ -615,32 +615,60 @@
Object(res.data)
+ && !Array.isArray(res.data)
) %7B%0A thro
|
8cc9f3b58043cf10421ea84c4fa0a8f2e9ae1245
|
Use startsWith for string match
|
src/modules/email/welcomeEmail.js
|
src/modules/email/welcomeEmail.js
|
import Logger from '../../lib/logger';
import fs from 'fs';
import jwt from 'jsonwebtoken';
import handlebars from 'handlebars';
import * as pg from '../../lib/pg';
import send from './sendEmail';
import { config } from '../../core-server';
import * as Constants from '../../lib/Constants';
const log = new Logger(__filename, 'welcome');
const WELCOME_INTERVAL = 5 * 60 * 1000, WELCOME_DELAY = 5 * 60 * 1000, connStr = config.connStr, conf = config.email,
template = handlebars.compile(fs.readFileSync(__dirname + '/../../../templates/' +
config.app_id + '.welcome.hbs', 'utf-8').toString());
let lastEmailSent, end;
function initMailSending(user) {
log.debug(user);
if (!user.identities || !Array.isArray(user.identities)) {
log.info('No identities found for user: ', user);
return;
}
const mailIds = user.identities.filter((el) => {
return /mailto:/.test(el);
});
mailIds.forEach((mailId) => {
const emailAdd = mailId.slice(7);
log.info('Sending email to:', emailAdd);
const emailHtml = template({
user: user.name || user.id,
domain: config.server.protocol + '//' + config.server.host + ':' + config.server.port,
token: jwt.sign({ email: emailAdd }, conf.secret, { expiresIn: '2 days' }),
});
send(conf.from, emailAdd, 'Welcome to ' + config.app_name, emailHtml, e => {
if (e) {
log.error('Error in sending email');
}
});
});
}
function sendWelcomeEmail () {
end = Date.now() - /* 10000 */ WELCOME_DELAY;
if (conf.debug) {
log.info('debug is enabled');
lastEmailSent = 0;
end = Date.now();
}
pg.readStream(connStr, {
$: 'SELECT id, name, identities FROM users WHERE createtime > &{start} AND createtime <= &{end}',
start: lastEmailSent,
end,
}).on('row', user => {
log.info('Got a new user: ', user.id);
initMailSending(user);
}).on('end', () => {
log.info('ended Welcome email');
pg.write(connStr, [{
$: 'UPDATE jobs SET lastrun=&{end} WHERE id=&{jid}',
end,
jid: Constants.JOB_EMAIL_WELCOME,
}], (error) => {
lastEmailSent = end;
if (!error) log.info('successfully updated jobs for welcome email');
});
});
}
export default function (row) {
lastEmailSent = row.lastrun;
log.info('starting welcome email', 'last sent: ', lastEmailSent);
sendWelcomeEmail();
setInterval(sendWelcomeEmail, /* 10000 */ WELCOME_INTERVAL);
}
|
JavaScript
| 0.000004 |
@@ -854,25 +854,31 @@
urn
-/mailto:/.test(el
+el.startsWith('mailto:'
);%0A%09
|
860c5481bcca4fd2e9749c0646ae962375f421f7
|
Add lisence file to lib/change_tracker.ts
|
firestore-document-histories/functions/lib/change_tracker.js
|
firestore-document-histories/functions/lib/change_tracker.js
|
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const diff_1 = require("./diff");
var ChangeType;
(function (ChangeType) {
ChangeType[ChangeType["CREATE"] = 0] = "CREATE";
ChangeType[ChangeType["DELETE"] = 1] = "DELETE";
ChangeType[ChangeType["UPDATE"] = 2] = "UPDATE";
})(ChangeType = exports.ChangeType || (exports.ChangeType = {}));
function getChangeType(change) {
if (!change.after.exists) {
return ChangeType.DELETE;
}
if (!change.before.exists) {
return ChangeType.CREATE;
}
return ChangeType.UPDATE;
}
exports.getChangeType = getChangeType;
function getTimestamp(context, change) {
const changeType = getChangeType((change));
switch (changeType) {
case ChangeType.CREATE:
return change.after.updateTime.toDate();
case ChangeType.DELETE:
// Due to an internal bug (129264426), before.update_time is actually the commit timestamp.
return new Date(change.before.updateTime.toDate().getTime() + 1);
case ChangeType.UPDATE:
return change.after.updateTime.toDate();
default: {
throw new Error(`Invalid change type: ${changeType}`);
}
}
}
exports.getTimestamp = getTimestamp;
function getData(change) {
const changeType = getChangeType((change));
let data = changeType == ChangeType.DELETE ? {} : change.after.data();
data.__diff = diff_1.getHistoryDiffs(changeType, changeType == ChangeType.CREATE ? null : change.before.data(), changeType == ChangeType.DELETE ? null : change.after.data());
return data;
}
exports.getData = getData;
|
JavaScript
| 0 |
@@ -7,16 +7,610 @@
trict%22;%0A
+/*%0A * Copyright 2019 Google LLC%0A *%0A * Licensed under the Apache License, Version 2.0 (the %22License%22);%0A * you may not use this file except in compliance with the License.%0A * You may obtain a copy of the License at%0A *%0A * https://www.apache.org/licenses/LICENSE-2.0%0A *%0A * Unless required by applicable law or agreed to in writing, software%0A * distributed under the License is distributed on an %22AS IS%22 BASIS,%0A * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.%0A * See the License for the specific language governing permissions and%0A * limitations under the License.%0A */%0A
Object.d
|
e7eb815940acca712c9cf3ad3c28aaef14a16de8
|
fix the test --flow options description
|
cmds/test.js
|
cmds/test.js
|
'use strict'
module.exports = {
command: 'test',
desc: 'Test your code in different environments',
builder: {
target: {
alias: 't',
describe: 'In which target environment to execute the tests',
type: 'array',
choices: ['node', 'browser', 'webworker'],
default: ['node', 'browser', 'webworker']
},
verbose: {
alias: 'v',
describe: 'Print verbose test output',
default: false
},
watch: {
alias: 'w',
describe: 'Watch files for changes and rerun tests',
default: false
},
files: {
alias: 'f',
describe: 'Custom globs for files to test',
type: 'array',
default: []
},
parallel: {
alias: 'p',
describe: 'Run tests in parallel (only available in node)',
default: true
},
timeout: {
describe: 'The default time a single test has to run',
type: 'number',
default: 5000
},
exit: {
describe: 'force shutdown of the event loop after test run: mocha will call process.exit',
default: true
},
cors: {
describe: 'Enable or disable CORS (only available in browser runs)',
default: true
},
bail: {
alias: 'b',
describe: 'Mocha should bail once a test fails',
default: false
},
flow: {
describe: 'Flow Type awesome',
default: false
},
env: {
describe: 'Sets NODE_ENV in the childprocess (NODE_ENV=dev aegir karma also works)',
default: 'development'
},
'enable-experimental-karma': {
alias: 'eek',
describe: 'Use the experimental karma config',
default: false
}
},
handler (argv) {
const test = require('../src/test')
return test.run(argv)
}
}
|
JavaScript
| 0.000033 |
@@ -1334,25 +1334,34 @@
e: '
-Flow Type awesome
+Run test with Flow support
',%0A
|
277ddc9c5e386324b98dcc25dbc7a4a8b8053af3
|
fix order
|
lib/rich-text.js
|
lib/rich-text.js
|
var Delta = require('quill-delta');
module.exports = {
name: 'rich-text',
uri: 'http://sharejs.org/types/rich-text/v0',
create: function (initial) {
var delta = new Delta(initial)
return delta.ops;
},
apply: function (snapshot, ops) {
snapshot = new Delta(snapshot);
var delta = new Delta(ops);
var applied = snapshot.compose(delta);
return applied.ops;
},
compose: function (ops1, ops2) {
var delta1 = new Delta(ops1);
var delta2 = new Delta(ops2);
var composed = delta1.compose(delta2);
return composed.ops;
},
transform: function (ops1, ops2, side) {
var delta1 = new Delta(ops1);
var delta2 = new Delta(ops2);
var transformed = delta1.transform(delta2, side === 'left');
return transformed.ops;
}
};
|
JavaScript
| 0.000046 |
@@ -706,17 +706,17 @@
= delta
-1
+2
.transfo
@@ -723,17 +723,17 @@
rm(delta
-2
+1
, side =
|
c1ffa9ed8aedb55dc343d7ae974fdb448955ace1
|
remove old code
|
js/client.js
|
js/client.js
|
var socket = io();
$('#add').click(function(e){
socket.emit('add', {
id: 'shape-' + Math.floor(Math.random() * 1000000000),
opacity: $('#opacity').val(),
backgroundColor: $('#color').val(),
width: $('#size').val() + 'px',
height: $('#size').val() + 'px',
mixBlendMode: $('#mix-blend').val(),
position: 'absolute'
});
e.preventDefault();
});
socket.on('add', function(props) {
$('#canvas').append($('<div>')
.addClass('shape')
.attr('id', props.id)
.css(props)
);
var reqAnimationFrame = (function () {
return window[Hammer.prefixed(window, 'requestAnimationFrame')] || function (callback) {
window.setTimeout(callback, 1000 / 60);
};
})();
var log = document.querySelector("#log");
var el = document.querySelector('#' + props.id);
var timer;
var ticking = false;
var transform = {
translate: { x: 0, y: 0 },
scale: 1,
angle: 0,
rx: 0,
ry: 0,
rz: 0
};
var mc = new Hammer.Manager(el);
mc.add(new Hammer.Pan({ threshold: 0, pointers: 0 }));
mc.add(new Hammer.Swipe()).recognizeWith(mc.get('pan'));
mc.add(new Hammer.Rotate({ threshold: 0 })).recognizeWith(mc.get('pan'));
mc.add(new Hammer.Pinch({ threshold: 0 })).recognizeWith([mc.get('pan'), mc.get('rotate')]);
mc.add(new Hammer.Tap({ event: 'doubletap', taps: 2 }));
mc.add(new Hammer.Tap());
mc.on("panstart panmove", onPan);
mc.on("rotatestart rotatemove", onRotate);
mc.on("pinchstart pinchmove", onPinch);
mc.on("swipe", onSwipe);
mc.on("tap", onTap);
mc.on("doubletap", onDoubleTap);
mc.on("hammer.input", function(ev) {
if(ev.isFinal) {
syncElement();
}
});
function syncElement() {
requestElementUpdate();
}
function updateElementTransform() {
var value = [
'translate3d(' + transform.translate.x + 'px, ' + transform.translate.y + 'px, 0px)',
'scale(' + transform.scale + ', ' + transform.scale + ')',
'rotate3d('+ transform.rx +','+ transform.ry +','+ transform.rz +','+ transform.angle + 'deg)'
];
value = value.join(' ');
el.style.webkitTransform = value;
el.style.mozTransform = value;
el.style.transform = value;
ticking = false;
socket.emit('move', {
me: socket.id,
id: props.id,
transform: value
});
}
function requestElementUpdate() {
if(!ticking) {
reqAnimationFrame(updateElementTransform);
ticking = true;
}
}
function logEvent(str) {
//log.insertBefore(document.createTextNode(str +"\n"), log.firstChild);
}
function onPan(ev) {
transform.translate = {
x: ev.deltaX,
y: ev.deltaY
};
requestElementUpdate();
logEvent(ev.type);
}
var initScale = 1;
function onPinch(ev) {
if(ev.type == 'pinchstart') {
initScale = transform.scale || 1;
}
el.className = '';
transform.scale = initScale * ev.scale;
requestElementUpdate();
logEvent(ev.type);
}
var initAngle = 0;
function onRotate(ev) {
if(ev.type == 'rotatestart') {
initAngle = transform.angle || 0;
}
el.className = '';
transform.rz = 1;
transform.angle = initAngle + ev.rotation;
requestElementUpdate();
logEvent(ev.type);
}
function onSwipe(ev) {
var angle = 50;
transform.ry = (ev.direction & Hammer.DIRECTION_HORIZONTAL) ? 1 : 0;
transform.rx = (ev.direction & Hammer.DIRECTION_VERTICAL) ? 1 : 0;
transform.angle = (ev.direction & (Hammer.DIRECTION_RIGHT | Hammer.DIRECTION_UP)) ? angle : -angle;
clearTimeout(timer);
timer = setTimeout(function () {
syncElement();
}, 300);
requestElementUpdate();
logEvent(ev.type);
}
function onTap(ev) {
transform.rx = 1;
transform.angle = 25;
clearTimeout(timer);
timer = setTimeout(function () {
syncElement();
}, 200);
requestElementUpdate();
logEvent(ev.type);
}
function onDoubleTap(ev) {
transform.rx = 1;
transform.angle = 80;
clearTimeout(timer);
timer = setTimeout(function () {
syncElement();
}, 500);
requestElementUpdate();
logEvent(ev.type);
}
socket.on('move', function(props) {
if (props.me !== socket.id) {
$('#' + props.id).css({
transform: props.transform
});
}
});
// .draggable()
// .on('dragstart', function( event, ui ) {
// $(this).addClass('grabbing');
// })
// .on('drag', function ( event, ui ) {
// socket.emit('move', {
// me: socket.id,
// id: $(this).attr('id'),
// left: $(this).css('left'),
// top: $(this).css('top')
// });
// })
// .on('dragstop', function( event, ui ) {
// $(this).removeClass('grabbing');
// // On dragstop we don't send the "me" ID because it should end up in the
// // same place regardless of who moved it.
// socket.emit('move', {
// id: $(this).attr('id'),
// left: $(this).css('left'),
// top: $(this).css('top')
// });
// })
});
|
JavaScript
| 0.000049 |
@@ -4232,17 +4232,16 @@
);%0A %7D%0A%0A
-%0A
socket
@@ -4395,788 +4395,8 @@
%7D);%0A
-%0A%0A // .draggable()%0A // .on('dragstart', function( event, ui ) %7B%0A // $(this).addClass('grabbing');%0A // %7D)%0A // .on('drag', function ( event, ui ) %7B%0A // socket.emit('move', %7B%0A // me: socket.id,%0A // id: $(this).attr('id'),%0A // left: $(this).css('left'),%0A // top: $(this).css('top')%0A // %7D);%0A // %7D)%0A // .on('dragstop', function( event, ui ) %7B%0A // $(this).removeClass('grabbing');%0A%0A // // On dragstop we don't send the %22me%22 ID because it should end up in the%0A // // same place regardless of who moved it.%0A // socket.emit('move', %7B%0A // id: $(this).attr('id'),%0A // left: $(this).css('left'),%0A // top: $(this).css('top')%0A // %7D);%0A // %7D)%0A
%7D);%0A
|
dbcb98136ecf6d2f6200d2e5fb29f7d1684c9edf
|
Correct color value for Black
|
js/colors.js
|
js/colors.js
|
module.exports = {
BLACK: 1,
RED: 1,
GREEN: 2,
BLUE: 3
}
|
JavaScript
| 0.000005 |
@@ -20,17 +20,17 @@
%09BLACK:
-1
+0
,%0A%09RED:
|
0c133c2c098009c1159484e0b69a87854cce07ad
|
change repo name
|
js/config.js
|
js/config.js
|
$(function() {
CMS.init({
// Name of your site or location of logo file, relative to root directory (img/logo.png)
siteName: 'John-Henry Beats The Machine',
// Tagline for your site
siteTagline: "I'm John-Henry and I Beat The Machine",
// Email address
siteEmail: '[email protected]',
// Name
siteAuthor: 'John-Henry Liberty',
// Navigation items
siteNavItems: [
{ name: 'Github', href: 'https://github.com/jhliberty', newWindow: false},
{ name: 'About'}
],
// Posts folder name
postsFolder: 'posts',
// Homepage posts snippet length
postSnippetLength: 120,
// Pages folder name
pagesFolder: 'pages',
// Order of sorting (true for newest to oldest)
sortDateOrder: true,
// Posts on Frontpage (blog style)
postsOnFrontpage: true,
// Page as Frontpage (static)
pageAsFrontpage: '',
// Posts/Blog on different URL
postsOnUrl: '',
// Site fade speed
fadeSpeed: 300,
// Site footer text
footerText: 'Helping Humans Survive The Machines Since 1987',
// Mode 'Github' for Github Pages, 'Server' for Self Hosted. Defaults
// to Github
mode: 'Github',
// If Github mode is set, your Github username and repo name.
githubUserSettings: {
username: 'jhliberty',
repo: 'jhliberty.github.io'
},
// If Github mode is set, choose which Github branch to get files from.
// Defaults to Github pages branch (gh-pages)
githubSettings: {
branch: 'gh-pages',
host: 'https://api.github.com'
}
});
// Markdown settings
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
});
|
JavaScript
| 0.000002 |
@@ -1350,25 +1350,11 @@
'jh
-liberty.github.io
+btm
'%0A
|
5ca496397a1f948ecd2e1e0cb07fc3ad3e40bc64
|
Add missing "domReady" module declaration
|
src/main/webapp/public/app-reset.js
|
src/main/webapp/public/app-reset.js
|
require.config({
paths: {
"jquery": "js/jquery-2.1.4.min",
"underscore": "js/underscore-min",
"knockout": "js/knockout-min-3.3.0"
}
});
require(['jquery', 'js/modules/dukecondb', 'js/modules/dukeconsettings', 'domReady!'], function($, db, settings) {
console.log("Clearing DB");
db.purge();
console.log("Clearing DB done; resetting localstore");
settings.purge();
console.log("Resetting localstore done; clearing the cache");
window.parent.caches.delete("call");
console.log("Clearing the cache done");
$('#loading').hide();
$('#layout').show();
});
|
JavaScript
| 0.000144 |
@@ -103,24 +103,59 @@
score-min%22,%0A
+ %22domReady%22: %22js/domReady%22,%0A
%22kno
|
24d05aba0db15d570ece81db8aad240722d321da
|
change mode
|
js/config.js
|
js/config.js
|
$(function() {
CMS.init({
// Name of your site or location of logo file ,relative to root directory (img/logo.png)
siteName: 'Médric Chouan',
// Tagline for your site
siteTagline: 'Your site tagline',
// Email address
siteEmail: '[email protected]',
// Name
siteAuthor: 'Médric Chouan',
// Navigation items
siteNavItems: [
{ name: 'Github', href: 'https://github.com/medric', newWindow: false},
{ name: 'About'}
],
// Posts folder name
postsFolder: 'posts',
// Homepage posts snippet length
postSnippetLength: 120,
// Pages folder name
pagesFolder: 'pages',
// Site fade speed
fadeSpeed: 300,
// Site footer text
footerText: '© ' + new Date().getFullYear() + ' All Rights Reserved.',
// Mode 'Github' for Github Pages, 'Apache' for Apache server. Defaults
// to Github
mode: 'Apache',
// If Github mode is set, your Github username and repo name. Defaults
// to Github pages branch (gh-pages)
githubUserSettings: {
username: 'yourusername',
repo: 'yourrepo'
}
});
// Markdown settings
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
});
});
|
JavaScript
| 0.000003 |
@@ -846,22 +846,22 @@
%09mode: '
-Apache
+Github
',%0A%0A%09%09//
|
22538093e4fe2d1c5a9548f4a10746f9183d91a3
|
Remove probably useless commented code.
|
content/addons.js
|
content/addons.js
|
/*
(function() {
// Override the existing showView() function
var _origShowView = showView;
showView = function(aView) {
dump('show view '+aView+'\n');
if ('userscripts'==aView) {
greasemonkeyAddons.selectMe();
} else {
_origShowView(aView);
}
};
})();
var greasemonkeyAddons={
oncommand: function() {
greasemonkeyAddons.selectMe();
},
select: function(event) {
//alert(event.target.id);
var selected = event.explicitOriginalTarget;
if ('viewGroup'==selected.id) {
selected = selected.getAttribute("last-selected");
} else {
selected = selected.id;
}
if ('userscripts-view'==selected) {
greasemonkeyAddons.selectMe();
} else {
$('addonsMsg').hidden = false;
$('userscripts').hidden = true;
}
},
selectMe: function() {
function $(id) { return document.getElementById(id); }
function hide(el) { if ('string'==typeof el) el=$(el); el.hidden=true; }
// Hide the native controls that don't work in the user scripts "tab".
var elementIds=[
'searchPanel', 'installFileButton', 'checkUpdatesAllButton',
'skipDialogButton', 'themePreviewArea', 'themeSplitter',
'showUpdateInfoButton', 'hideUpdateInfoButton',
'installUpdatesAllButton', 'addonsMsg'];
elementIds.forEach(hide);
$('viewGroup').setAttribute('last-selected', 'userscripts');
//$('userscripts-view').selected = true;
$('userscripts').hidden = false;
greasemonkeyAddons.fillList();
},
fillList: function() {
// I'd much prefer to use the inbuilt templates/rules mechanism that the
// native FFX bits of this dialog use, but this works as P.O.C.
var config = GM_getConfig();
var listbox = document.getElementById('userscripts');
while (listbox.firstChild) {
listbox.removeChild(listbox.firstChild);
}
for (var i = 0, script = null; script = config.scripts[i]; i++) {
var item = document.createElement('richlistitem');
var label = document.createElement('label');
label.setAttribute('value', script.name);
item.appendChild(label);
listbox.appendChild(item);
}
}
};
document.getElementById('viewGroup').addEventListener(
'select', greasemonkeyAddons.select, false);
*/
(function() {
// Override the existing showView() function, to add in capabilities for our
// custom view.
var _origShowView = showView;
showView = function(aView) {
if ('userscripts'==aView) {
greasemonkeyAddons.showView();
} else {
_origShowView(aView);
}
};
})();
var greasemonkeyAddons={
showView: function(aView) {
updateLastSelected('userscripts');
gView='userscripts';
function $(id) { return document.getElementById(id); }
function hide(el) { if ('string'==typeof el) el=$(el); el.hidden=true; }
// Hide the native controls that don't work in the user scripts view.
var elementIds=[
'searchPanel', 'installFileButton', 'checkUpdatesAllButton',
'skipDialogButton', 'themePreviewArea', 'themeSplitter',
'showUpdateInfoButton', 'hideUpdateInfoButton',
'installUpdatesAllButton'];
elementIds.forEach(hide);
//AddonsViewBuilder.updateView([]);
greasemonkeyAddons.fillList();
},
fillList: function() {
// I'd much prefer to use the inbuilt templates/rules mechanism that the
// native FFX bits of this dialog use, but this works as P.O.C.
var config = GM_getConfig();
var listbox = gExtensionsView;
while (listbox.firstChild) {
listbox.removeChild(listbox.firstChild);
}
for (var i = 0, script = null; script = config.scripts[i]; i++) {
var item = document.createElement('richlistitem');
var label = document.createElement('label');
label.setAttribute('value', script.name);
item.appendChild(label);
listbox.appendChild(item);
}
}
};
|
JavaScript
| 0 |
@@ -1,2289 +1,4 @@
-/*%0A(function() %7B%0A // Override the existing showView() function%0A var _origShowView = showView;%0A showView = function(aView) %7B%0A dump('show view '+aView+'%5Cn');%0A if ('userscripts'==aView) %7B%0A greasemonkeyAddons.selectMe();%0A %7D else %7B%0A _origShowView(aView);%0A %7D%0A %7D;%0A%7D)();%0A%0Avar greasemonkeyAddons=%7B%0A oncommand: function() %7B%0A greasemonkeyAddons.selectMe();%0A %7D,%0A%0A select: function(event) %7B%0A //alert(event.target.id);%0A var selected = event.explicitOriginalTarget;%0A if ('viewGroup'==selected.id) %7B%0A selected = selected.getAttribute(%22last-selected%22);%0A %7D else %7B%0A selected = selected.id;%0A %7D%0A%0A if ('userscripts-view'==selected) %7B%0A greasemonkeyAddons.selectMe();%0A %7D else %7B%0A $('addonsMsg').hidden = false;%0A $('userscripts').hidden = true;%0A %7D%0A %7D,%0A%0A selectMe: function() %7B%0A function $(id) %7B return document.getElementById(id); %7D%0A function hide(el) %7B if ('string'==typeof el) el=$(el); el.hidden=true; %7D%0A%0A // Hide the native controls that don't work in the user scripts %22tab%22.%0A var elementIds=%5B%0A 'searchPanel', 'installFileButton', 'checkUpdatesAllButton',%0A 'skipDialogButton', 'themePreviewArea', 'themeSplitter',%0A 'showUpdateInfoButton', 'hideUpdateInfoButton',%0A 'installUpdatesAllButton', 'addonsMsg'%5D;%0A elementIds.forEach(hide);%0A%0A $('viewGroup').setAttribute('last-selected', 'userscripts');%0A //$('userscripts-view').selected = true;%0A $('userscripts').hidden = false;%0A greasemonkeyAddons.fillList();%0A %7D,%0A%0A fillList: function() %7B%0A // I'd much prefer to use the inbuilt templates/rules mechanism that the%0A // native FFX bits of this dialog use, but this works as P.O.C.%0A var config = GM_getConfig();%0A var listbox = document.getElementById('userscripts');%0A%0A while (listbox.firstChild) %7B%0A listbox.removeChild(listbox.firstChild);%0A %7D%0A%0A for (var i = 0, script = null; script = config.scripts%5Bi%5D; i++) %7B%0A var item = document.createElement('richlistitem');%0A var label = document.createElement('label');%0A label.setAttribute('value', script.name);%0A item.appendChild(label);%0A%0A listbox.appendChild(item);%0A %7D%0A %7D%0A%7D;%0A%0Adocument.getElementById('viewGroup').addEventListener(%0A 'select', greasemonkeyAddons.select, false);%0A*/%0A%0A%0A
(fun
|
aea3fc23355b1b6bb778b474b0b213f34145e185
|
Add setter to $cell
|
src/ng/components/body/td.core.js
|
src/ng/components/body/td.core.js
|
import Directive from 'ng/directives/directive';
import cellBuilder from '../cell/cell.build';
import AppError from 'core/infrastructure/error'
import {VIEW_CORE_NAME, TD_CORE_NAME} from 'ng/definition';
import {GRID_PREFIX} from 'core/definition';
class TdCore extends Directive(TD_CORE_NAME, {view: `^^${VIEW_CORE_NAME}`}) {
constructor($scope, $element) {
super();
this.$scope = $scope;
this.$element = $element;
this.$templateScope = null;
}
onInit() {
const column = this.column;
const element = this.$element[0];
this.view.style.monitor.cell.add(this.element);
element.classList.add(`${GRID_PREFIX}-${column.key}`);
element.classList.add(`${GRID_PREFIX}-${column.type}`);
if (column.hasOwnProperty('editor')) {
element.classList.add(`${GRID_PREFIX}-${column.editor}`);
}
this.mode('init');
}
mode(value) {
const model = this.view.model;
const column = this.column;
const templateScope = this.setup();
const cache = model.body().cache;
const element = this.$element[0];
switch (value) {
case 'view':
case 'init': {
let link = cache.find(column.key);
if (!link) {
const build = cellBuilder(this.view.template);
link = build('body', model, column);
cache.set(column.key, link);
}
link(this.$element, templateScope);
if (value !== 'init') {
element.classList.remove(`${GRID_PREFIX}-edit`);
}
break;
}
case 'edit': {
let link = cache.find(`${column.key}.edit`);
if (!link) {
const build = cellBuilder(this.view.template, 'edit');
link = build('body', model, column);
cache.set(`${column.key}.edit`, link);
}
link(this.$element, templateScope);
element.classList.add(`${GRID_PREFIX}-edit`);
}
break;
default:
throw new AppError('td.core', `Invalid mode ${value}`);
}
}
setup() {
if (this.$templateScope) {
this.$templateScope.$destroy();
}
this.$templateScope = this.$scope.$new();
return this.$templateScope;
}
get value() {
const column = this.column;
const row = this.row;
return this.view.body.value(row, column);
}
get rowIndex() {
// use vscroll.row + vscroll.position in the future
return this.$scope.$parent.$index;
}
get columnIndex() {
// use vscroll.column + vscroll.position in the future
return this.$scope.$index;
}
get column() {
return this.$scope.$column.model;
}
get row() {
return this.$scope.$row;
}
onDestroy() {
if (this.$templateScope) {
this.$templateScope.$destroy();
}
this.view.style.monitor.cell.remove(this.$element[0]);
}
}
TdCore.$inject = [
'$scope',
'$element'
];
export default {
restrict: 'A',
bindToController: true,
controllerAs: '$cell',
controller: TdCore,
require: TdCore.require,
link: TdCore.link
};
|
JavaScript
| 0.000004 |
@@ -2100,24 +2100,154 @@
olumn);%0A%09%7D%0A%0A
+%09set value(value) %7B%0A%09%09const column = this.column;%0A%09%09const row = this.row;%0A%09%09this.view.edit.cell.setValue(row, column, value);%0A%09%7D%0A%0A
%09get rowInde
|
ff2a47ce977b9e086ae54550f86f279f50bb0736
|
Fix #394
|
modules/github.js
|
modules/github.js
|
const WebhooksApi = require('@octokit/webhooks')
const http = require('http') // core
const colors = require('irc').colors
let server
let webhook
let listener
const announce = (bot, msg) => {
return bot.notice(bot.config.get('github.channel'), colors.wrap('dark_green', '[github] ') + msg)
}
module.exports = {
onload: (bot) => {
webhook = new WebhooksApi({ secret: bot.config.get('github.webhook.secret') })
server = http.createServer(webhook.middleware)
listener = webhook.on('*', (webhookEvent) => {
bot.fireEvents('github', webhookEvent)
bot.fireEvents(`github:${webhookEvent.name}`, webhookEvent)
})
server.listen(bot.config.get('github.webhook.port'))
},
onunload: (bot) => {
webhook.removeListener(listener)
server.close(() => bot.log('info', 'gh server closed'))
},
events: {
github: (bot, ghEvent) => {
switch (ghEvent.name) {
case 'check_run':
case 'check_suite':
case 'create': /* create branch */
case 'issue_comment':
case 'issues':
case 'pull_request':
case 'pull_request_review':
case 'push':
case 'status':
return
}
announce(bot, colors.wrap('light_gray', `Unknown webhook event ${ghEvent.name}. keys: ${Object.keys(ghEvent.payload)}`))
},
'github:issues': (bot, ghEvent) => {
const actionColors = {
opened: 'light_green',
edited: 'orange',
deleted: 'light_red',
transferred: 'light_gray',
pinned: 'white',
unpinned: 'white',
closed: 'dark_red',
reopened: 'dark_green',
assigned: 'light_cyan',
unassigned: 'cyan',
labeled: 'light_blue',
unlabeled: 'dark_blue',
locked: 'gray',
unlocked: 'light_gray',
milestoned: 'light_magenta',
demilestoned: 'magenta'
}
let coloredAction = colors.wrap(actionColors[ghEvent.payload.action], ghEvent.payload.action)
if (ghEvent.payload.action.includes('assigned')) {
coloredAction += ' ' + ghEvent.payload.assignee.login + ' '
coloredAction += ghEvent.payload.action === 'assigned' ? 'to' : 'from'
}
return announce(bot, `${ghEvent.payload.sender.login} ${coloredAction} issue #${ghEvent.payload.issue.number} ${ghEvent.payload.issue.html_url}`)
},
'github:pull_request': (bot, ghEvent) => {
if (ghEvent.payload.action === 'synchronize') return
if (ghEvent.payload.action === 'ready_for_review') ghEvent.payload.action = 'undrafted'
return announce(bot, `${ghEvent.payload.sender.login} ${ghEvent.payload.action} pull request ${ghEvent.payload.pull_request.html_url}`)
},
'github:delete': (bot, ghEvent) => {
return announce(bot, `${ghEvent.payload.sender.login} deleted branch ${ghEvent.payload.ref}`)
},
'github:issue_comment': (bot, ghEvent) => {
let verb = ghEvent.payload.action
if (verb === 'created') verb = 'added'
verb += ' comment on '
return announce(bot, `${ghEvent.payload.sender.login} ${verb} issue comment ${ghEvent.payload.issue.html_url}`)
},
'github:push': (bot, ghEvent) => {
if (ghEvent.payload.commits.length === 0) return
return announce(bot, `${ghEvent.payload.pusher.name} pushed ${ghEvent.payload.commits.length} commits to ${ghEvent.payload.ref} ${ghEvent.payload.compare}`)
},
'github:pull_request_review': (bot, ghEvent) => {
return announce(bot, `${ghEvent.payload.sender.login} ${ghEvent.payload.action} code review: ${ghEvent.payload.review.state} ${ghEvent.payload.review.html_url}`)
}
}
}
|
JavaScript
| 0.000001 |
@@ -3001,17 +3001,16 @@
mment on
-
'%0A
|
1fd7a9a1559fb1e9dda535872bcb1c82ba814fe1
|
remove tags to parse comments correctly
|
modules/parser.js
|
modules/parser.js
|
define(function (require, exports, module) {
'use strict';
var Async = brackets.getModule('utils/Async'),
ProjectManager = brackets.getModule('project/ProjectManager'),
DocumentManager = brackets.getModule('document/DocumentManager'),
LanguageManager = brackets.getModule('language/LanguageManager'),
FileSystem = brackets.getModule('filesystem/FileSystem'),
StringUtils = brackets.getModule('utils/StringUtils'),
FileManager = require('modules/fileManager'),
ParseUtils = require('modules/parseUtils'),
Events = require('modules/events'),
newestComments = [];
/**
* setup parser on startup
* */
function setup() {
// parsing will spend a lot of time, so do it asynchronously
asynFindTrelloComments();
registerFileChangeListener();
}
/**
* Listen on all file change event to update trello comments.
* */
function registerFileChangeListener() {
var $documentManager = $(DocumentManager);
var $projectManager = $(ProjectManager);
FileSystem.on('change', function (event, file) {
// Bail if not a file or file is outside current project root.
if (file === null || file.isFile !== true || file.fullPath.indexOf(ProjectManager.getProjectRoot().fullPath) === -1) {
return false;
}
//TODO trello anzhihun update trello comments on file change.
// console.log('Brackets-Trello: change file ' + file.fullPath + ', event = ' + event);
if (ParseUtils.isSupported(LanguageManager.getLanguageForPath(file.fullPath).getId())) {
// Just find again now
asynFindTrelloComments();
}
});
FileSystem.on('rename', function (event, oldName, newName) {
//TODO trello anzhihun update trello comments on file name change.
// console.log('Brackets-Trello: rename old file ' + oldName + ' to ' + newName + ', event = ' + event);
if (ParseUtils.isSupported(LanguageManager.getLanguageForPath(oldName).getId()) ||
ParseUtils.isSupported(LanguageManager.getLanguageForPath(newName).getId())) {
// Just find again now
asynFindTrelloComments();
}
});
$projectManager.on('projectOpen', function(event, directory){
// reparse
asynFindTrelloComments();
});
}
function asynFindTrelloComments() {
window.setTimeout(function () {
findTrelloComments();
}, 1000);
}
/**
* parse all support files in current project to find trello comment.
* return all trello comments
* */
function findTrelloComments() {
//TODO Trello Find trello comment in all files now.
var filesPromise = FileManager.getFiles(),
trelloComments = [],
startTime = new Date().getTime();
filesPromise.done(function (files) {
if (files.length === 0) {
console.log('[Brackets-Trello] parse file use time ' + (new Date().getTime() - startTime) + ' ms');
updateTrelloComments(trelloComments);
return;
}
// Go through each file asynchronously.
Async.doInParallel(files, function (file) {
var result = new $.Deferred();
DocumentManager.getDocumentText(file).done(function (content) {
var oneFileComments = parseFile(file, content);
oneFileComments.forEach(function (comment) {
trelloComments.push(comment);
});
}).always(function () {
// Move on to next file.
result.resolve();
});
return result.promise();
}).always(function () {
console.log('[Brackets-Trello] parse file use time ' + (new Date().getTime() - startTime) + ' ms');
updateTrelloComments(trelloComments);
});
});
}
/**
* parse trello comments in one file.
* return trello comment array, if there is no trello comment, then return empty array.
* */
function parseFile(file, content) {
var trelloComments = [],
lines = StringUtils.getLines(content),
languageId = LanguageManager.getLanguageForPath(file.fullPath).getId();
trelloComments = ParseUtils.parseText(content, ['idea', 'todo', 'doing', 'done'], languageId);
// add path and process line num
trelloComments.forEach(function (comment) {
comment.filePath(file.fullPath);
comment.lineNumber(StringUtils.offsetToLineNum(lines, comment.lineNumber()) + 1);
comment.endLineNumber(StringUtils.offsetToLineNum(lines, comment.endLineNumber()) + 1);
});
return trelloComments;
}
function updateTrelloComments(comments) {
newestComments = comments;
Events.publish('comments:updated');
}
function onTrelloCommentsChange(callback) {
Events.subscribe('comments:updated', function () {
if ($.isFunction(callback)) {
callback(newestComments);
}
});
}
function getTrelloComments() {
return newestComments;
}
exports.setup = setup;
exports.onTrelloCommentsChange = onTrelloCommentsChange;
exports.getTrelloComments = getTrelloComments;
});
|
JavaScript
| 0 |
@@ -4577,43 +4577,8 @@
ent,
- %5B'idea', 'todo', 'doing', 'done'%5D,
lan
|
cc9389a689ee851e5b296aee5fa8ffe1990d39a1
|
change from dropdown and simplify styling plus make some minor fixes.
|
src/widget.facetviewer.js
|
src/widget.facetviewer.js
|
/*jshint multistr:true */
this.recline = this.recline || {};
this.recline.View = this.recline.View || {};
(function($, my) {
// ## FacetViewer
//
// Widget for displaying facets
//
// Usage:
//
// var viewer = new FacetViewer({
// model: dataset
// });
my.FacetViewer = Backbone.View.extend({
className: 'recline-facet-viewer',
template: ' \
<div class="facets row"> \
<div class="span1"> \
<h3>Facets</h3> \
</div> \
{{#facets}} \
<div class="facet-summary span2 dropdown" data-facet="{{id}}"> \
<a class="btn dropdown-toggle" data-toggle="dropdown" href="#"><i class="icon-chevron-down"></i> {{id}} {{label}}</a> \
<ul class="facet-items dropdown-menu"> \
{{#terms}} \
<li><a class="facet-choice js-facet-filter" data-value="{{term}}">{{term}} ({{count}})</a></li> \
{{/terms}} \
{{#entries}} \
<li><a class="facet-choice js-facet-filter" data-value="{{time}}">{{term}} ({{count}})</a></li> \
{{/entries}} \
</ul> \
</div> \
{{/facets}} \
</div> \
',
events: {
'click .js-facet-filter': 'onFacetFilter'
},
initialize: function(model) {
_.bindAll(this, 'render');
this.el = $(this.el);
this.model.facets.bind('all', this.render);
this.model.fields.bind('all', this.render);
this.render();
},
render: function() {
var tmplData = {
facets: this.model.facets.toJSON(),
fields: this.model.fields.toJSON()
};
tmplData.facets = _.map(tmplData.facets, function(facet) {
if (facet._type === 'date_histogram') {
facet.entries = _.map(facet.entries, function(entry) {
entry.term = new Date(entry.time).toDateString();
return entry;
});
}
return facet;
});
var templated = Mustache.render(this.template, tmplData);
this.el.html(templated);
// are there actually any facets to show?
if (this.model.facets.length > 0) {
this.el.show();
} else {
this.el.hide();
}
},
onHide: function(e) {
e.preventDefault();
this.el.hide();
},
onFacetFilter: function(e) {
var $target= $(e.target);
var fieldId = $target.closest('.facet-summary').attr('data-facet');
var value = $target.attr('data-value');
this.model.queryState.addTermFilter(fieldId, value);
}
});
})(jQuery, recline.View);
|
JavaScript
| 0 |
@@ -387,86 +387,13 @@
cets
- row
%22%3E %5C%0A
- %3Cdiv class=%22span1%22%3E %5C%0A %3Ch3%3EFacets%3C/h3%3E %5C%0A %3C/div%3E %5C%0A
@@ -443,23 +443,8 @@
mary
- span2 dropdown
%22 da
@@ -477,123 +477,45 @@
%3C
-a class=%22btn dropdown-toggle%22 data-toggle=%22dropdown%22 href=%22#%22%3E%3Ci class=%22icon-chevron-down%22%3E%3C/i%3E %7B%7Bid%7D%7D %7B%7Blabel%7D%7D%3C/a
+h3%3E %5C%0A %7B%7Bid%7D%7D %5C%0A %3C/h3
%3E %5C%0A
@@ -548,22 +548,8 @@
tems
- dropdown-menu
%22%3E %5C
@@ -645,16 +645,33 @@
%7Bterm%7D%7D%22
+ href=%22#%7B%7Bterm%7D%7D%22
%3E%7B%7Bterm%7D
@@ -1260,50 +1260,8 @@
= %7B%0A
- facets: this.model.facets.toJSON(),%0A
@@ -1333,30 +1333,41 @@
_.map(t
-mplData.facets
+his.model.facets.toJSON()
, functi
@@ -1964,24 +1964,48 @@
nction(e) %7B%0A
+ e.preventDefault();%0A
var $tar
@@ -2171,33 +2171,132 @@
.add
-Term
Filter(
-fieldId, value
+%7Btype: 'term', field: fieldId, term: value%7D);%0A // have to trigger explicitly for some reason%0A this.model.query(
);%0A
|
903bc664f7d704f1c9bbc507ac707ba78bc1bd2c
|
change error
|
wkD/M1_HelloFirebase/js/script.js
|
wkD/M1_HelloFirebase/js/script.js
|
$(document).ready(function(){
// REGISTER DOM ELEMENTS
const $title = $('#title');
const $id = $("#id");
// INITIALIZE FIREBASE
firebase.initializeApp({
apiKey: "AIzaSyDUH6vOCALEXSjYHgv8P9d2y3tKklE44qA",
authDomain: "f2e2020-bd468.firebaseapp.com",
databaseURL: "https://f2e2020-bd468.firebaseio.com",
projectId: "f2e2020-bd468",
storageBucket: "f2e2020-bd468.appspot.com",
messagingSenderId: "832044128799",
appId: "1:832044128799:web:5dedad46efcd2c3253932a",
measurementId: "G-QWW610MX3Z"
});
let db = firebase.firestore();
let usersRef = db.collection("users");
// usersRef.add({
// "name": "NTUE",
// "age": 13,
// "tel": {
// "tel1": "111-111",
// "tel2": "222-111"
// }
// });
let docRef = usersRef.doc("1167");
// docRef.get().then(function(doc){
// $id.html(`doc 1167' name = ${doc.data().name}`)
// });
// docRef.set({
// "name": "Alex1",
// "age": 27,
// "tel": {
// "tel1": "111-111",
// "tel2": "222-111"
// }
// });
docRef.update({
"name": "John Doe"
});
docRef.onSnapshot(
function(doc){
$title.html(`user name = ${doc.data().name}, user age = ${doc.data().age}`);
}
);
});
|
JavaScript
| 0.000003 |
@@ -93,19 +93,21 @@
st $
-i
d
+oc
= $(%22#
-i
d
+oc
%22);%0A
@@ -798,21 +798,17 @@
1167%22);%0A
-%0A //
+
docRef.
@@ -839,16 +839,19 @@
%7B%0A
-// $id
+ $(%22#doc%22)
.htm
@@ -861,17 +861,16 @@
doc 1167
-'
name =
@@ -891,19 +891,16 @@
ame%7D%60)%0A
- //
%7D);%0A%0A%0A%0A
|
f1e9d6f728e11bd1411994061441b79b036e0d16
|
fix for new_post quickfix
|
js/helper.js
|
js/helper.js
|
/*
* helper.js
*
* Helper file, you probably will not need this one.
* Must be loaded as the very last js file, be careful.
*
*/
$(document).ready(function(){
$('#navigation a, #markup a').css({
"cursor": 'pointer',
"text-decoration": 'none'
});
if (settings.showInfo) {
$('footer').append("<p id=\"showInfo\" class=\"unimportant\" style=\"text-align:center;\"></p>");
$("footer p").eq(0).append("<p id=\"githubInfo\" class=\"unimportant\" style=\"text-align:center;\"></p>");
showInfo();
setInterval("showInfo()",60000);
}
var do_replace_audio = function(element) {
var element = $(element);
element.find('audio').mediaelementplayer({
plugins:['flash','silverlight'],
pluginPath:'/js/mediaelement/'
});
$('video').mediaelementplayer();
}
var do_preview_webm = function(element) {
$(element).find('video').attr('preload', 'metadata')
}
var do_add_shorten = function(element) {
var element = $(element);
element.find("div.post.reply div.body").shorten({
moreText: 'Весь текст',
lessText: 'Скрыть',
showChars: (settings.hideLongTextNum),
});
}
do_replace_audio(document);
if (settings.previewWebm)
do_preview_webm(document);
if (settings.hideLongText)
do_add_shorten(document);
$(document).bind('new_post', function(e, post) {
//post is implied to a jquery array of elements
do_replace_audio(post);
if (settings.hideLongText)
do_add_shorten(post);
if (settings.previewWebm)
do_preview_webm(post);
});
if (device_type == "mobile") {
$("#navigation .fa").addClass("fa-2x");
$("#navigation .fa").click(function() {
$("#navigation .fa").addClass("fa-2x");
});
}
});
function showInfo() {
$.ajax({
type: 'GET',
url: "/testcount.json",
dataType: 'json',
success: function(data){
ajaxInfo = data;
$('#showInfo').text("Скорость борды: " + JSON.parse(ajaxInfo.speed) + " п/час | Онлайн: " + JSON.parse(ajaxInfo.online));
}
});
// well thank you Github
$.ajax({
type: 'GET',
url: "https://api.github.com/repos/twiforce/fukuro/contributors?anon=1",
dataType: 'json',
success: function(data){
githubContribInfo = data;
}
});
$.ajax({
type: 'GET',
url: "https://api.github.com/repos/twiforce/fukuro/commits",
dataType: 'json',
success: function(data){
githubInfo = data;
// damn son where did you find this
var ii = 0;
var totalCommits = 0;
while (ii < githubContribInfo.length) {
totalCommits = totalCommits + githubContribInfo[ii]["contributions"];
ii++;
}
$('#githubInfo').html("Последний коммит #" + totalCommits + " \"<a href=\""
+ githubInfo[0]["html_url"] + "\" target=_blank>" + githubInfo[0]["commit"]["message"]
+ "</a>\" отправил <a href=\"" + githubInfo[0]["author"]["html_url"] +"\"> " + githubInfo[0]["author"]["login"]
+ "</a> " + moment(githubInfo[0]["commit"]["author"]["date"]).fromNow() + ".")
}
});
}
|
JavaScript
| 0 |
@@ -797,17 +797,28 @@
-$
+element.find
('video'
@@ -842,24 +842,25 @@
yer();%0A %7D
+;
%0A%0A var do
@@ -957,24 +957,25 @@
data')%0A %7D
+;
%0A%0A var do
@@ -1234,16 +1234,17 @@
);%0A %7D
+;
%0A%0A do
|
5bdde209167da50affffb6aadc55678a751ec027
|
allow identifier header
|
backend/middlewares/cors.js
|
backend/middlewares/cors.js
|
module.exports = function (req, res, next) {
const method = req.raw.method && req.raw.method.toUpperCase && req.raw.method.toUpperCase()
const allowedOrigins = ['https://wago.io', 'http://io:8080']
if (!req.headers.origin) {
res.header('Access-Control-Allow-Origin', '*')
}
else if (allowedOrigins.indexOf(req.headers.origin) >= 0 || req.raw.url.match(/^\/api\//)) {
res.header('Access-Control-Allow-Origin', req.headers.origin)
}
else {
res.header('Access-Control-Allow-Origin', false)
}
res.header('Vary', 'Origin')
res.header('Access-Control-Allow-Credentials', true)
res.header('Access-Control-Expose-Headers', 'set-cookie,wotm')
// if preflight check
if (method === 'OPTIONS') {
res.header('Access-Control-Request-Headers', 'GET, OPTIONS')
res.header('Access-Control-Allow-Headers', 'set-cookie,cookie,wotm,authorization,x-auth-token,accept,accept-version,content-type,request-id,origin')
return res.code(204).send('')
}
return next()
}
|
JavaScript
| 0.000002 |
@@ -927,24 +927,35 @@
st-id,origin
+,identifier
')%0A %0A
|
ce3ae68d2bfe5a389949c544c085d06fd1996996
|
Fix favicon error
|
app/api/image-search.js
|
app/api/image-search.js
|
/*jslint node: true */
'use strict';
var Imgur = require('imgur-search');
module.exports = function (app, db) {
app.route('/api/imagesearch/:query')
.get(function(req, res){
var query = req.params.query;
var page = req.query.offset || 0;
var imgur = new Imgur(process.env.IMGUR_CLIENT_ID);
var results = imgur.search(query, 'top', page).always(function(resp){
saveQuery(query, db);
res.send(resp.map(listify));
});
});
app.route('/api/latest/imagesearch/')
.get(function(req, res){
var foo = getHistory(db, res);
});
function getHistory(db, res){
var cursor = db.collection('history').find({}, {term: 1, timestamp: 1, _id: 0}).sort({ timestamp: -1 }).limit(10).toArray(function(err, result) {
var formatted = result.map(simplify);
res.send(formatted);
});
}
function listify(image){
return {
"url": image.link,
"snippet": image.title,
"thumbnail": thumbnailify(image.link),
"context": contextify(image.id)
};
function contextify(id){
return 'http://imgur.com/gallery/' + id;
}
function thumbnailify(link){
return link.replace(/(.jpg)/, 's.jpg');
}
}
function saveQuery(term, db){
var history = db.collection('history');
history.save({ term: term, timestamp: new Date() }, function(err, result){
if(err) throw err;
});
}
function simplify(record){
return {
"term": record.term,
"timestamp": record.timestamp
};
}
};
|
JavaScript
| 0.000092 |
@@ -384,16 +384,55 @@
(resp)%7B%0A
+ if(query !== 'favicon.ico')%7B%0A
@@ -457,24 +457,26 @@
b);%0A
+
res.send(res
@@ -492,16 +492,26 @@
tify));%0A
+ %7D%0A
%7D)
|
f50db741a42903aff1e9c9054df967255c160b1a
|
change variable name
|
www/js/directives/autocomplete.js
|
www/js/directives/autocomplete.js
|
angular.module('app.directives')
.directive('iAutocomplete', function($document, $rootScope, $compile, $window, search, $timeout) {
var autocompleteScope = $rootScope.$new();
var autoCompleteEl = $compile(
'<div class="autocomplete-popup"><ul>' +
'<li ng-repeat="item in items | limitTo:6" ng-click="select(item)">' +
'<strong>{{ item.label }}</strong> {{ item.comment }}' +
'</li></ul></div>'
)(autocompleteScope);
$document.find('body').append(autoCompleteEl);
var users = [];
var usersById = {};
var maxQueryLength = 2;
autocompleteScope.items = [];
autocompleteScope.select = function(item) {
replace('@' + item.username);
};
function autocomplete() {
if (!autocompleteScope.items.length) {
return autoCompleteEl.hide();
}
var coordinates = $window.getCaretCoordinates(
autocompleteScope.element[0],
autocompleteScope.element[0].selectionEnd
);
var offset = autocompleteScope.element.offset();
autoCompleteEl.show()
.css('top', (coordinates.top + offset.top - Math.min(6, autocompleteScope.items.length) * 30))
.css('left', offset.left + coordinates.left)
;
}
function setQuery() {
autocompleteScope.query = '';
autocompleteScope.position = autocompleteScope.element[0].selectionStart;
if (autocompleteScope.position) {
var pre = autocompleteScope.element.val().substring(0, autocompleteScope.position);
var parts = pre.split(/\s/);
autocompleteScope.query = parts[parts.length - 1];
}
}
function replace(text) {
autocompleteScope.element[0].selectionStart = autocompleteScope.position - autocompleteScope.query.length;
autocompleteScope.element[0].selectionEnd = autocompleteScope.position;
autocompleteScope.element[0].setRangeText(text);
var newPosition = autocompleteScope.element.val().length;
autocompleteScope.element[0].selectionStart = newPosition;
autocompleteScope.element[0].selectionEnd = newPosition;
$timeout(function() {
autocompleteScope.element.focus();
}, 100, false);
}
function filter() {
if (autocompleteScope.query.length > maxQueryLength && autocompleteScope.query[0] === '@') {
var start = autocompleteScope.query.slice(1, autocompleteScope.query.length).toLowerCase();
autocompleteScope.items = _(users).filter(function(user) {
return 0 === user.username.toLowerCase().search(start) ||
0 === user.first_name.toLowerCase().search(start) ||
0 === user.last_name.toLowerCase().search(start)
;
});
} else {
autocompleteScope.items = [];
}
}
function fetch() {
if (autocompleteScope.query.length > maxQueryLength && autocompleteScope.query[0] === '@') {
search.searchUsers(autocompleteScope.query.slice(1, autocompleteScope.query.length))
.then(function(data) {
var dataAdded = false;
_(data).each(function(user) {
if (!usersById[user.id]) {
usersById[user.id] = user;
dataAdded = true;
users.push(user);
user.label = '@' + user.username;
user.comment = user.first_name + ' ' + user.last_name;
}
});
if(dataAdded){
filter();
autocomplete();
}
});
}
}
var textTimer = null;
return function(scope, element) {
element.on('input', function(){
$timeout.cancel(textTimer);
textTimer = $timeout(function(){
autocompleteScope.element = element;
setQuery();
filter();
fetch();
autocomplete();
}, 100);
});
element.on('blur', function() {
$timeout(function() {
autoCompleteEl.hide();
}, 500, false);
});
};
});
|
JavaScript
| 0.00008 |
@@ -569,18 +569,18 @@
var m
-ax
+in
QueryLen
@@ -2301,34 +2301,34 @@
query.length %3E m
-ax
+in
QueryLength && a
@@ -2902,10 +2902,10 @@
%3E m
-ax
+in
Quer
|
23b3ba56043fed9a53a3ec6ed6e622063d7ca5e5
|
Update CC BY 3.0 link to zh-TW localized version.
|
src/nls/zh-tw/urls.js
|
src/nls/zh-tw/urls.js
|
/*
* Copyright (c) 2012 Adobe Systems Incorporated. All rights reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a
* copy of this software and associated documentation files (the "Software"),
* to deal in the Software without restriction, including without limitation
* the rights to use, copy, modify, merge, publish, distribute, sublicense,
* and/or sell copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
* DEALINGS IN THE SOFTWARE.
*
*/
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50 */
/*global define */
define({
// Relative to the samples folder
"GETTING_STARTED" : "root/Getting Started",
"ADOBE_THIRD_PARTY" : "http://www.adobe.com/go/thirdparty/",
"WEB_PLATFORM_DOCS_LICENSE" : "http://creativecommons.org/licenses/by/3.0/"
});
|
JavaScript
| 0 |
@@ -1529,14 +1529,24 @@
/by/3.0/
+deed.zh_TW
%22%0A%7D);%0A
|
e29bb8a1c8a663bf25deeffe2a7a9a663406db4f
|
remove re-deploy service, since this may be causing a race condition in deploying the service and checking if the text is on the website, and add retries (#506)
|
background/test/app.test.js
|
background/test/app.test.js
|
const cp = require('child_process');
const path = require('path');
const projectId = process.env.GCLOUD_PROJECT;
const regionId = process.env.REGION_ID;
const app = `https://testservice-dot-${projectId}.${regionId}.r.appspot.com`;
const assert = require('assert');
const {v4: uuidv4} = require('uuid');
const {Firestore} = require('@google-cloud/firestore');
const fetch = require('node-fetch');
const {URLSearchParams} = require('url');
const waitOn = require('wait-on');
const opts = {
resources: [app],
};
const delay = async (test, addMs) => {
const retries = test.currentRetry();
await new Promise((r) => setTimeout(r, addMs));
// No retry on the first failure.
if (retries === 0) return;
// See: https://cloud.google.com/storage/docs/exponential-backoff
const ms = Math.pow(2, retries) + Math.random() * 1000;
return new Promise((done) => {
console.info(`retrying "${test.title}" in ${ms}ms`);
setTimeout(done, ms);
});
};
async function deployService() {
let uniqueID = uuidv4().split('-')[0];
cp.execSync(`npm install`, {cwd: path.join(__dirname, '../', 'function')});
try {
cp.execSync(
`gcloud functions deploy translate-${uniqueID} --runtime nodejs10 --allow-unauthenticated --set-env-vars=unique_id=${uniqueID} --trigger-topic translate`,
{cwd: path.join(__dirname, '/testApp')}
);
} catch (err) {
console.log("Wasn't able to deploy Google Cloud Function");
}
try {
cp.execSync(`gcloud app deploy app.yaml`, {
cwd: path.join(__dirname, '../', 'server'),
});
} catch (err) {
console.log("Wasn't able to deploy app to AppEngine");
}
try {
await waitOn(opts);
} catch (err) {
console.log(err);
}
return uniqueID;
}
async function deleteService(uniqueID) {
try {
cp.execSync(`gcloud app services delete testservice`, {
cwd: path.join(__dirname, '/testApp'),
});
} catch (err) {
console.log('Was not able to delete AppEngine Service');
}
try {
cp.execSync(`gcloud functions delete translate-${uniqueID}`, {
cwd: path.join(__dirname, '/testApp'),
});
} catch (err) {
console.log("Wasn't able to delete Google Cloud Functions");
}
const db = new Firestore({
project: projectId,
});
const res = await db.collection('/translations').get();
res.forEach(async (element) => {
await element.ref.delete();
});
console.log('Firebase translation collection deleted');
}
describe('behavior of cloud function', function () {
this.timeout(360000);
let uniqueID;
beforeEach(async () => {
uniqueID = await deployService();
});
afterEach(async () => {
await deleteService(uniqueID);
});
it('should get the correct website', async function () {
this.retries(4);
await deployService();
await delay(this.test, 4000);
const body = await fetch(`${app}`);
const res = await body.status;
assert.strictEqual(res, 200);
});
it('should get the correct response', async function () {
this.retries(4);
this.timeout(360000);
await deployService();
await delay(this.test, 4000);
const params = new URLSearchParams();
params.append('lang', 'en');
params.append('v', 'como estas');
let body = await fetch(`${app}/request-translation`, {
method: 'POST',
body: params,
});
console.log(await body.text());
let res = await body.status;
assert.strictEqual(res, 200);
body = await fetch(`${app}/`);
res = await body.text();
assert.ok(res.includes('how are you'));
});
});
|
JavaScript
| 0.000228 |
@@ -2998,25 +2998,25 @@
his.retries(
-4
+6
);%0A this.
@@ -3036,35 +3036,8 @@
0);%0A
- await deployService();%0A
|
a3021f922d91ae0df1bdecf3b06503d6cb5dc296
|
Fix CANCEL_EDIT_MESSAGE test to actually work.
|
src/session/__tests__/sessionReducer-test.js
|
src/session/__tests__/sessionReducer-test.js
|
import deepFreeze from 'deep-freeze';
import {
ACCOUNT_SWITCH,
CANCEL_EDIT_MESSAGE,
START_EDIT_MESSAGE,
LOGIN_SUCCESS,
} from '../../actionConstants';
import sessionReducer from '../sessionReducer';
describe('sessionReducer', () => {
describe('ACCOUNT_SWITCH', () => {
test('reissues initial fetch', () => {
const prevState = deepFreeze({});
const action = deepFreeze({
type: ACCOUNT_SWITCH,
});
const newState = sessionReducer(prevState, action);
expect(newState.needsInitialFetch).toBe(true);
});
});
describe('START_EDIT_MESSAGE', () => {
test('Test start edit message method', () => {
const prevState = deepFreeze({
twentyFourHourTime: false,
pushToken: {},
emoji: {},
editMessage: null,
});
const action = deepFreeze({
type: START_EDIT_MESSAGE,
messageId: 12,
message: 'test',
});
const expectedState = {
twentyFourHourTime: false,
pushToken: {},
emoji: {},
editMessage: {
id: 12,
content: 'test',
},
};
const newState = sessionReducer(prevState, action);
expect(newState).toEqual(expectedState);
});
});
describe('CANCEL_EDIT_MESSAGE', () => {
test('Test cancel edit message method', () => {
const prevState = deepFreeze({
twentyFourHourTime: false,
pushToken: {},
emoji: {},
editMessage: {
id: 12,
content: 'test',
},
});
const action = deepFreeze({
type: START_EDIT_MESSAGE,
});
const expectedState = {
twentyFourHourTime: false,
pushToken: {},
emoji: {},
editMessage: {
content: undefined,
id: undefined,
},
};
const newState = sessionReducer(prevState, action);
expect(newState).toEqual(expectedState);
});
});
describe('LOGIN_SUCCESS', () => {
test('reissues initial fetch', () => {
const prevState = deepFreeze({});
const action = deepFreeze({
type: LOGIN_SUCCESS,
});
const newState = sessionReducer(prevState, action);
expect(newState.needsInitialFetch).toBe(true);
});
});
});
|
JavaScript
| 0.000039 |
@@ -1586,37 +1586,38 @@
%7B%0A type:
-START
+CANCEL
_EDIT_MESSAGE,%0A
@@ -1758,74 +1758,12 @@
ge:
-%7B%0A content: undefined,%0A id: undefined,%0A %7D
+null
,%0A
|
2d59e8fbba61a2da79d32dca73197ea7f5901556
|
correct syncup
|
lib/sync/sync.js
|
lib/sync/sync.js
|
'use strict'
// need to use a function for sync -- in the funciton will recieve true if up or somethign
// addhere to play state content api -- add down / up
// this will be default behaviour for child: 'Constructor'
// if its allready the case and its own dont change it
exports.properties = {
syncUpIsFn: true,
syncDownIsFn: true,
syncUp (val) {
if (!this.hasOwnProperty('child')) {
this.set({ child: { child: 'Constructor' } }, false)
}
if (typeof val === 'function') {
this.child.prototype.syncUp = this.syncUp = true
}
this.child.prototype.syncUp = this.syncUp = resolveState(val, this)
},
syncDown (val) {
if (!this.hasOwnProperty('child')) {
this.set({ child: { child: 'Constructor' } }, false)
}
if (typeof val === 'function') {
this.child.prototype.syncDownIsFn = this.syncDownIsFn = true
}
this.child.prototype.syncDown = this.syncDown = resolveState(val, this)
},
sync (val) {
return this.set({
syncUp: val,
syncDown: val
}, false)
}
}
function resolveState (val, spawned) {
return (state) => {
if (state && state.key !== spawned.key) {
let found
while (state && !found) {
if (
state.sid() === spawned.sid() ||
(spawned._Constructor && state instanceof spawned._Constructor)
) {
found = true
} else {
state = state.parent
}
}
}
return val(state)
}
}
exports.syncUp = true
exports.syncDown = true
|
JavaScript
| 0.000114 |
@@ -517,32 +517,36 @@
prototype.syncUp
+IsFn
= this.syncUp =
@@ -543,24 +543,28 @@
s.syncUp
+IsFn
= true%0A
%7D%0A
@@ -547,32 +547,68 @@
ncUpIsFn = true%0A
+ val = resolveState(val, this)%0A
%7D%0A this.c
@@ -645,39 +645,19 @@
yncUp =
-resolveState(val, this)
+val
%0A %7D,%0A
@@ -879,24 +879,60 @@
IsFn = true%0A
+ val = resolveState(val, this)%0A
%7D%0A th
@@ -977,39 +977,19 @@
cDown =
-resolveState(val, this)
+val
%0A %7D,%0A
|
8923137c551fd8ab14798e0fe35ff2018f6b966f
|
Add file paths to icons
|
app/constants/Images.js
|
app/constants/Images.js
|
/*
* Copyright 2017-present, Hippothesis, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
'use strict';
export const Images = {
logo: null
};
export default Images;
|
JavaScript
| 0.000001 |
@@ -262,18 +262,167 @@
%7B%0A %09
-logo: null
+icons: %7B%0A home: require('../images/home-icon.png'),%0A search: require('../images/search-icon.png'),%0A profile: require('../images/profile-icon.png')%0A %7D
%0A%7D;%0A
|
372f58d452e985b09ecd32b943e19e2f7873b3ab
|
improve on hover business view
|
lib/assets/javascripts/yoolk/jquery.business-view-overlay.js
|
lib/assets/javascripts/yoolk/jquery.business-view-overlay.js
|
/*
* Plugin Name: Bussiness View Overlay
*
* Author: Instant Website Team
*
* Note: Call Business View Overlay after jQuery in Application JS loaded
*/
window.onload = function() {
(function($) {
BusinessViewOverlay = function(element, options) {
this.options = null;
this.$element = null;
this.$overlay = null
this.device = null;
this.init(element, options);
}
BusinessViewOverlay.DEFAULTS = {
label: "Click to view a 360-degree virtual tour",
channel: "instant website"
}
BusinessViewOverlay.prototype.init = function(element, options) {
this.$element = $(element);
this.options = $.extend(this.getDefaults(), options);
this.device = this.getDevice();
this.$overlay = this.getOverlay();
this.setPositionRelative();
this.onClickOverlay();
this.appendOverlay();
var self = this;
if (this.device == "desktop") {
this.$overlay.hide();
this.$element.hover(function() {
self.$overlay.toggle();
}, function() {
self.$overlay.toggle();
})
}
}
BusinessViewOverlay.prototype.getDevice = function() {
var md = new MobileDetect(window.navigator.userAgent),
device = '';
if (md.phone()) {
device = "mobile";
}
else if (md.tablet()) {
device = "tablet";
}
else {
device = "desktop";
}
return device;
}
BusinessViewOverlay.prototype.getDefaults = function () {
return BusinessViewOverlay.DEFAULTS;
}
BusinessViewOverlay.prototype.setPositionRelative = function() {
this.$element.css('position', 'relative');
}
BusinessViewOverlay.prototype.appendOverlay = function() {
this.$element.append(this.$overlay);
}
BusinessViewOverlay.prototype.getOverlay = function() {
return this.$overlay = this.$overlay || this.createOverlay();
}
BusinessViewOverlay.prototype.createOverlay = function() {
var label = this.$element.data('label') || this.options.label;
$overlay = $($.parseHTML("<div class='bizview-overlay'></div>"));
$overlay.css({
'top': 0,
'left': 0,
'right': 0,
'bottom': 0,
'cursor': 'pointer',
'position': 'absolute',
'background-color': 'rgba(225, 225, 225, 0.7)'
});
$info = $($.parseHTML("<span>" + label + "</span>"));
$info.css({
'top': '50%',
'left': '50%',
'width': '250px',
'color': '#333',
'font-size': '20px',
'position': 'absolute',
'text-align': 'center',
'margin-right': '-50%',
'transform': 'translate(-50%, -50%)',
'-webkit-transform': 'translate(-50%, -50%)',
'-ms-transform': 'translate(-50%, -50%)'
}).appendTo($overlay);
return $overlay;
}
BusinessViewOverlay.prototype.onClickOverlay = function() {
var self = this;
this.$overlay.click(function() {
self.trackBusinessView()
.success(function() {
self.$overlay.remove();
})
.fail(function(errors) {
self.$overlay.remove();
});
});
}
BusinessViewOverlay.prototype.trackBusinessView = function() {
var params = {
"data": {
"device": this.device,
"channel": this.options.channel
}
},
apiUrl = $('body').data('api-url'),
listingAliasId = $('body').data('listing-alias-id'),
url = apiUrl + "/v2/listings/" + listingAliasId + "/business_view_tracks";
return $.ajax({
type: "POST",
url: url,
data: params
});
}
// BUSINESS VIEW OVERLAY PLUGIN DEFINITION
// ========================================
function Plugin(options) {
return this.each(function () {
new BusinessViewOverlay(this, options);
})
}
var old = $.fn.businessViewOverlay;
$.fn.businessViewOverlay = Plugin;
$.fn.businessViewOverlay.Constructor = BusinessViewOverlay;
// BUSINESS VIEW OVERLAY NO CONFLICT
// =================================
$.fn.businessViewOverlay.noConflict = function () {
$.fn.businessViewOverlay = old;
return this;
}
}(jQuery));
// init business view overlay
$('.js-business-view').businessViewOverlay();
}
|
JavaScript
| 0 |
@@ -1088,38 +1088,36 @@
self.$overlay.
-toggle
+show
();%0A %7D,
@@ -1160,13 +1160,11 @@
lay.
-toggl
+hid
e();
|
f093c4a1426c376615f8fb3f9acd882ac1b31132
|
update dialog text and flow again
|
lib/drivers/onetouch/catalina-sudo/sudo-askpass.osascript.js
|
lib/drivers/onetouch/catalina-sudo/sudo-askpass.osascript.js
|
#!/usr/bin/env osascript -l JavaScript
/*
* == BSD2 LICENSE ==
* Copyright (c) 2020, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* 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 License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
/* eslint-disable */
ObjC.import('stdlib')
const app = Application.currentApplication()
app.includeStandardAdditions = true
function showDialog() {
return app.displayDialog('Please enter your computer password to allow Tidepool Uploader to access your device.', {
defaultAnswer: '',
withIcon: 'note',
buttons: ['Cancel', 'Why do I need to do this?', 'OK'],
defaultButton: 'OK',
hiddenAnswer: true,
})
}
showDialog()
if (result.buttonReturned === 'OK') {
result.textReturned
} else if (result.buttonReturned === 'Why do I need to do this?') {
app.openLocation('https://tidepool.org/') // TODO: needs link to support article
showDialog()
} else {
$.exit(255)
}
|
JavaScript
| 0 |
@@ -891,14 +891,22 @@
%7B%0A
-return
+const result =
app
@@ -1174,25 +1174,11 @@
%7D)%0A
-%7D%0A%0AshowDialog()%0A%0A
+%0A
if (
@@ -1213,16 +1213,18 @@
K') %7B%0A
+
+
result.t
@@ -1235,16 +1235,18 @@
eturned%0A
+
%7D else i
@@ -1305,16 +1305,18 @@
is?') %7B%0A
+
app.op
@@ -1335,16 +1335,24 @@
https://
+support.
tidepool
@@ -1360,50 +1360,94 @@
org/
-') // TODO: needs link to support article%0A
+hc/en-us/articles/360019872851-Uploading-your-OneTouch-Verio-and-Verio-Flex-Meter')%0A
sh
@@ -1457,16 +1457,18 @@
ialog()%0A
+
%7D else %7B
@@ -1468,16 +1468,18 @@
else %7B%0A
+
$.exit
@@ -1484,10 +1484,28 @@
it(255)%0A
-%7D
+ %7D%0A%7D%0A%0AshowDialog()
%0A
|
4da5631cfbf37e7d77f1c8bb76b571a2d77c8200
|
Update logger.js
|
js/logger.js
|
js/logger.js
|
/* global console */
/* exported Log */
/* Magic Mirror
* Logger
*
* By Michael Teeuw http://michaelteeuw.nl
* MIT Licensed.
*/
// This logger is very simple, but needs to be extended.
// This system can eventually be used to push the log messages to an external target.
var Log = (function() {
return {
info: Function.prototype.bind.call(console.info, console),
log: Function.prototype.bind.call(console.log, console),
error: Function.prototype.bind.call(console.error, console),
warn: Function.prototype.bind.call(console.warn, console),
group: Function.prototype.bind.call(console.group, console),
groupCollapsed: Function.prototype.bind.call(console.groupCollapsed, console),
groupEnd: Function.prototype.bind.call(console.groupEnd, console),
time: Function.prototype.bind.call(console.time, console),
timeEnd: Function.prototype.bind.call(console.timeEnd, console),
timeStamp: Function.prototype.bind.call(console.timeStamp, console)
};
})();
|
JavaScript
| 0.000001 |
@@ -41,13 +41,13 @@
%0A/*
-Magic
+Smart
Mir
@@ -64,71 +64,8 @@
ger%0A
- *%0A * By Michael Teeuw http://michaelteeuw.nl%0A * MIT Licensed.%0A
*/%0A
|
6da180e3b3504ee7d625e98311b8735626f53e70
|
Update melvin.js
|
js/melvin.js
|
js/melvin.js
|
/*!
* melvin.io v1.7.1
* Copyright © 2013 Melvin Chien <[email protected]> (http://melvin.io/)
* Licensed under the MIT license
*/
(function() {
$(document).ready(function() {
$(this).foundation();
$("#js-navbar .name a, #js-navbar .top-bar-section a").click(function() {
var topbar;
topbar = $(".topbar, [data-topbar]");
topbar.removeClass("fixed");
topbar.parent().addClass("fixed");
$("body").addClass("f-topbar-fixed");
topbar.css("height", "");
topbar.removeClass("expanded");
return topbar.find("li").removeClass("hover");
});
$(window).scroll(function() {
if ($(this).scrollTop() > 45) {
return $(".top-bar").removeClass("top-bar-clear");
} else {
return $(".top-bar").addClass("top-bar-clear");
}
});
$("#js-navbar, #js-container").on("click", ".deep-link", function(e) {
var href;
e.preventDefault();
href = $(this).attr("href");
href = href.replace(/^#/, "");
href = href.replace("-", "/");
return $.address.value(href);
});
return $.address.change(function(e) {
var container, content, divider, footer, href, title, url, word, _i, _len;
container = $("#js-container");
content = $("#js-content");
footer = $("#js-footer");
divider = $("#js-hexagon");
title = "melvin";
href = e.value;
href = href.replace(/^\//, "");
href = href.replace(/\/$/, "");
url = href.split("/");
for (_i = 0, _len = url.length; _i < _len; _i++) {
word = url[_i];
if (word !== "") {
switch (word) {
case "anteaternetwork":
word = "Anteater Network";
break;
case "jmmp":
word = "JMMP";
break;
case "alienescape":
word = "Alien Escape";
break;
default:
word = word.charAt(0).toUpperCase() + word.slice(1);
}
title = word + " · " + title;
}
}
$.address.title(title);
if (href === "") {
footer.fadeOut("500");
content.fadeOut("500", function() {
return container.hide();
});
return container.removeClass("active");
} else {
container.show();
href = href.replace("/", "-");
footer.fadeOut("250");
return content.fadeOut("250", function() {
return content.load("/" + href + ".html", function(response, status, xhr) {
if (status === "error") {
return window.location.replace("/" + href);
} else {
footer.fadeIn("500");
content.fadeIn("2000");
return container.addClass("active");
}
});
});
}
});
});
}).call(this);
|
JavaScript
| 0 |
@@ -39,9 +39,9 @@
201
-3
+4
Mel
|
69207913a784288cbc3ed5a1f251ca4083430c78
|
update files
|
lib/transform.js
|
lib/transform.js
|
/**
* Created by nuintun on 2015/4/27.
*/
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('./util');
var through = require('@nuintun/through');
var gutil = require('@nuintun/gulp-util');
var join = path.join;
var relative = path.relative;
/**
* include
*
* @param options
* @returns {Stream}
*/
module.exports = function(options) {
var initialized = false;
var configure = util.initOptions(options);
// stream
return through({ objectMode: true }, function(vinyl, encoding, next) {
// throw error if stream vinyl
if (vinyl.isStream()) {
return next(gutil.throwError('streaming not supported.'));
}
// hack old vinyl
vinyl._isVinyl = true;
// normalize vinyl base
vinyl.base = relative(vinyl.cwd, vinyl.base);
// return empty vinyl
if (vinyl.isNull()) {
return next(null, vinyl);
}
// when not initialized
if (!initialized) {
// debug
util.debug('cwd: %p', gutil.normalize(gutil.cwd));
var base = join(vinyl.cwd, vinyl.base);
// base out of bound of wwwroot
if (gutil.isOutBound(base, configure.wwwroot)) {
gutil.throwError(
'base: %s is out of bound of wwwroot: %s.',
gutil.normalize(base),
gutil.normalize(configure.wwwroot)
);
}
// rewrite ignore
configure.ignore = util.initIgnore(vinyl, configure);
// initialized
initialized = true;
}
// catch error
try {
// stream
var stream = this;
var path = gutil.pathFromCwd(vinyl.path);
// print process progress
util.print('process: %s', gutil.colors.reset.green(path));
// clone options
options = gutil.extend({}, configure);
// lock wwwroot
gutil.readonlyProperty(options, 'wwwroot');
// lock plugins
gutil.readonlyProperty(options, 'plugins');
// transport
util.transport(vinyl, options, function(vinyl, options) {
var pool = {};
var pkg = vinyl.package;
var start = vinyl.clone();
var end = vinyl.clone();
// set start and end file status
start.contents = gutil.BLANK_BUFFER;
start.concat = gutil.CONCAT_STATUS.START;
end.contents = gutil.BLANK_BUFFER;
end.concat = gutil.CONCAT_STATUS.END;
// clean vinyl
delete start.package;
delete end.package;
// compute include
options.include = gutil.isFunction(options.include)
? options.include(pkg.id || null, vinyl.path)
: options.include;
// debug
util.debug('concat: %p start', path);
// push start blank vinyl
stream.push(start);
// include dependencies files
includeDeps.call(stream, vinyl, pool, options, function() {
// push end blank vinyl
stream.push(end);
// free memory
pool = null;
// debug
util.debug('concat: %p ...ok', path);
next();
});
});
} catch (error) {
// show error message
util.print(gutil.colors.reset.red.bold(error.stack) + '\x07');
next();
}
});
}
/**
* create a new vinyl
*
* @param path
* @param cwd
* @param base
* @param done
* @returns {void}
*/
function vinylFile(path, cwd, base, done) {
if (!gutil.isString(path)
|| !gutil.isString(cwd)
|| !gutil.isString(base)) {
return done(null);
}
// cache path
var src = path;
// print error
function printError(error) {
util.print(
'file: %s is %s',
gutil.colors.reset.yellow(gutil.pathFromCwd(src)),
error.code
);
done(null);
}
// read file
function readFile(path, stat) {
fs.readFile(path, function(error, data) {
if (error) return printError(error);
done(new gutil.Vinyl({
path: path,
cwd: cwd,
base: base,
stat: stat,
contents: data
}));
});
}
// read file use origin path
fs.stat(path, function(error, stat) {
if (error) {
path = util.hideExt(path, true);
// read file use hide extname path
fs.stat(path, function(error, stat) {
if (error) return printError(error);
readFile(path, stat);
});
} else {
readFile(path, stat);
}
});
}
/**
* walk file
*
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function walk(vinyl, pool, options, done) {
var stream = this;
var status = pool[vinyl.path];
/**
* transport dependence file
* @param module
* @param next
*/
function transform(module, next) {
var path = module.path;
if (options.ignore[path]
|| pool[path]
|| (options.include === 'relative' && !gutil.isRelative(module.id))) {
return next();
}
// create a vinyl file
vinylFile(path, vinyl.cwd, vinyl.base, function(child) {
// read file success
if (child === null) return next();
// debug
util.debug('include: %r', child.path);
// transport file
util.transport(child, options, function(child, options) {
// cache next
status.next = next;
// add cache status
pool[child.path] = {
next: null,
parent: status,
included: false
};
// walk
walk.call(stream, child, pool, options, done);
});
});
}
/**
* include current file and flush status
*
* @returns {void}
*/
function flush() {
// push file to stream
if (!status.included) {
stream.push(vinyl);
// change cache status
status.next = null;
status.included = true;
}
var parent = status.parent;
// all file include
if (parent === null || parent.next === null) {
done();
} else {
// run parent next dependencies
parent.next();
// clean parent
delete status.parent;
}
}
var pkg = vinyl.package;
// bootstrap
if (status.included || !pkg) {
flush();
} else {
gutil.async.series(pkg.include, transform, flush);
}
}
/**
* include dependencies file
*
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function includeDeps(vinyl, pool, options, done) {
// return if include not equal 'all' and 'relative'
if (options.include !== 'all' && options.include !== 'relative') {
// push file to stream
this.push(vinyl);
// free memory
pool = null;
return done();
}
// set pool cache
pool[vinyl.path] = {
next: null,
parent: null,
included: false
};
// bootstrap
walk.call(this, vinyl, pool, options, function() {
// free memory
pool = null;
// callback
done();
});
}
|
JavaScript
| 0.000001 |
@@ -3609,16 +3609,21 @@
t.yellow
+.bold
(gutil.p
|
09ee21d74260d3419ecb63fcfb4cc3772bc36d27
|
update files
|
lib/transform.js
|
lib/transform.js
|
/*!
* transform
* Version: 0.0.1
* Date: 2017/05/19
* https://github.com/nuintun/gulp-css
*
* This is licensed under the MIT License (MIT).
* For details, see: https://github.com/nuintun/gulp-css/blob/master/LICENSE
*/
'use strict';
var fs = require('fs');
var path = require('path');
var util = require('./util');
var through = require('@nuintun/through');
var gutil = require('@nuintun/gulp-util');
var relative = path.relative;
// blank buffer
var BLANK = Buffer.from ? Buffer.from('') : new Buffer('');
/**
* transform
*
* @param options
* @returns {Stream}
*/
module.exports = function(options) {
var initialized = false;
var configure = util.initOptions(options);
// stream
return through({ objectMode: true }, function(vinyl, encoding, next) {
// throw error if stream vinyl
if (vinyl.isStream()) {
return next(gutil.throwError('streaming not supported.'));
}
// hack old vinyl
vinyl._isVinyl = true;
// normalize vinyl base
vinyl.base = relative(vinyl.cwd, vinyl.base);
// return empty vinyl
if (vinyl.isNull()) {
return next(null, vinyl);
}
if (!initialized) {
// debug
util.debug('cwd: %p', gutil.normalize(gutil.cwd));
initialized = true;
}
// stream
var stream = this;
var path = gutil.pathFromCwd(vinyl.path);
// clone options
options = gutil.extend({}, configure);
// lock wwwroot
gutil.readonlyProperty(options, 'wwwroot');
// lock plugins
gutil.readonlyProperty(options, 'plugins');
// transport
util.transport(vinyl, options, function(error, vinyl, options) {
if (error) {
stream.push(vinyl);
// show error message
util.print(gutil.colors.reset.red.bold(error.stack) + '\x07');
return next();
}
var pool = {};
var pkg = vinyl.package;
var start = vinyl.clone();
var end = vinyl.clone();
// set start and end file status
start.contents = gutil.BLANK_BUFFER;
start.concat = gutil.CONCAT_STATUS.START;
end.contents = gutil.BLANK_BUFFER;
end.concat = gutil.CONCAT_STATUS.END;
// clean vinyl
delete start.package;
delete end.package;
// compute include
options.include = gutil.isFunction(options.include)
? options.include(pkg.id || null, vinyl.path)
: options.include;
// debug
util.debug('concat: %p start', path);
// push start blank vinyl
stream.push(start);
// include dependencies files
includeDeps.call(stream, vinyl, pool, options, function() {
// push end blank vinyl
stream.push(end);
// free memory
pool = null;
// debug
util.debug('concat: %p ...ok', path);
next();
});
});
});
};
/**
* create a new vinyl
*
* @param path
* @param cwd
* @param base
* @param done
* @returns {void}
*/
function vinylFile(path, cwd, base, done) {
if (!gutil.isString(path)
|| !gutil.isString(cwd)
|| !gutil.isString(base)) {
return done(null);
}
// print error
function printError(error) {
util.print(
'file: %s is %s',
gutil.colors.reset.yellow.bold(gutil.pathFromCwd(path)),
error.code
);
done(null);
}
// read file
fs.stat(path, function(error, stat) {
if (error) return printError(error);
fs.readFile(path, function(error, data) {
if (error) return printError(error);
done(new gutil.Vinyl({
path: path,
cwd: cwd,
base: base,
stat: stat,
contents: data
}));
});
});
}
/**
* walk file
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function walk(vinyl, pool, options, done) {
var stream = this;
var status = pool[vinyl.path];
/**
* transport dependence file
*
* @param path
* @param next
* @returns {void}
*/
function transform(path, next) {
// already transport
if (pool[path]) return next();
// create a vinyl file
vinylFile(path, vinyl.cwd, vinyl.base, function(child) {
// read file success
if (child === null) return next();
// debug
util.debug('include: %r', child.path);
// transport file
util.transport(child, options, function(error, child, options) {
if (error) {
// show error message
util.print(gutil.colors.reset.red.bold(error.stack) + '\x07');
}
// cache next
status.next = next;
// add cache status
pool[child.path] = {
next: null,
parent: status,
included: false
};
// walk
walk.call(stream, child, pool, options, done);
});
});
}
/**
* include current file and flush status
*
* @returns {void}
*/
function flush() {
// push file to stream
if (!status.included) {
stream.push(vinyl);
// change cache status
status.next = null;
status.included = true;
}
var parent = status.parent;
// all file include
if (parent === null || parent.next === null) {
done();
} else {
// run parent next dependencies
parent.next();
// clean parent
delete status.parent;
}
}
var pkg = vinyl.package;
// bootstrap
if (status.included || !pkg) {
flush();
} else {
gutil.async.series(pkg.include, transform, flush);
}
}
/**
* include dependencies file
*
* @param vinyl
* @param pool
* @param options
* @param done
* @returns {void}
*/
function includeDeps(vinyl, pool, options, done) {
// return if include not equal 'all' and 'relative'
if (!options.include) {
// push file to stream
this.push(vinyl);
// free memory
pool = null;
// callback
return done();
}
// set pool cache
pool[vinyl.path] = {
next: null,
parent: null,
included: false
};
// bootstrap
walk.call(this, vinyl, pool, options, function() {
// free memory
pool = null;
// callback
done();
});
}
|
JavaScript
| 0.000001 |
@@ -3642,16 +3642,19 @@
lk file%0A
+ *%0A
* @para
@@ -4354,31 +4354,8 @@
-if (error) %7B%0A
// s
@@ -4363,32 +4363,53 @@
ow error message
+%0A if (error) %7B
%0A util.
|
e89d1eb860afdf08dc5d847d4aa1b3eb111754ea
|
make popups dissapear after 4 seconds
|
js/popUps.js
|
js/popUps.js
|
function addNotification(notificationText, typeClass) {
notification = $("#notificationsDiv .notification.prototype").clone();
notification.removeClass("prototype");
notification.find(".text").text(notificationText);
notification.addClass(typeClass);
$("#notificationsDiv").append(notification);
}
|
JavaScript
| 0.000001 |
@@ -305,11 +305,106 @@
ation);%0A
+ window.setTimeout(function() %7B%0A notification.alert().alert(%22close%22);%0A %7D, %0A 5000);%0A
%7D%0A%0A
|
c6c10c75a8b06e5387707f9d350fe50adb9ec927
|
Update minified script.
|
lib/trier.min.js
|
lib/trier.min.js
|
!function(n){"use strict";function t(n){function t(){if(i()){if(d(n))return j(n),e();j(n,function(){e()})}}function i(){return u("when")}function u(r){return g(n,r)?(v(n),x(n)?h(n):A(t,b(n)),!1):!0}function e(){u("until")&&w(n)}n=r(n),t()}function r(n){return{count:0,when:i(n.when),until:i(n.until),action:o(n.action),fail:o(n.fail),pass:o(n.pass),interval:a(n.interval,-1e3),limit:a(n.limit,-1),context:s(n.context),args:m(n.args)}}function i(n){return f(n,u,e)}function u(n){return"function"==typeof n}function e(){return!0}function o(n){return f(n,u,c)}function c(){}function f(n,t,r){return t(n)?n:r}function a(n,t){return f(n,l,t)}function l(n){return"number"==typeof n&&n===n}function s(n){return f(n,p,{})}function p(n){return"object"==typeof n&&null!==n&&y(n)===!1}function y(n){return Array.isArray?Array.isArray(n):"[object Array]"===Object.prototype.toString.call(n)}function m(n){return f(n,y,[])}function d(n){return 0===n.action.length}function g(n,t){return!n[t].apply(n.context,n.args)}function v(n){n.count+=1}function x(n){return n.limit>=0&&n.count>=n.limit}function h(n){n.fail.apply(n.context,n.args)}function b(n){var t=n.interval;return n.interval<0&&(n.interval*=2),t}function A(n,t){setTimeout(n,Math.abs(t))}function j(n,t){n.action.apply(n.context,t?n.args.concat(t):n.args)}function w(n){n.pass.apply(n.context,n.args)}function M(){"function"==typeof define&&define.amd?define(function(){return O}):"undefined"!=typeof module&&null!==module?module.exports=O:n.trier=O}var O={attempt:t};M()}(this);
|
JavaScript
| 0 |
@@ -51,60 +51,15 @@
()%7Bi
-f(i())%7Bif(d(n))return j(n),e();j(n,function()%7Be()%7D)%7D
+()&&o()
%7Dfun
@@ -83,16 +83,18 @@
u(%22when%22
+,t
)%7Dfuncti
@@ -98,16 +98,18 @@
ction u(
+t,
r)%7Bretur
@@ -114,17 +114,17 @@
urn g(n,
-r
+t
)?(v(n),
@@ -135,17 +135,17 @@
?h(n):A(
-t
+r
,b(n)),!
@@ -155,24 +155,90 @@
!0%7Dfunction
+o()%7Breturn d(n)?(j(n),e()):(j(n,function()%7Be()%7D),void 0)%7Dfunction
e()%7Bu(%22until
@@ -238,16 +238,18 @@
(%22until%22
+,o
)&&w(n)%7D
@@ -327,17 +327,17 @@
,action:
-o
+e
(n.actio
@@ -344,17 +344,17 @@
n),fail:
-o
+e
(n.fail)
@@ -359,17 +359,17 @@
l),pass:
-o
+e
(n.pass)
@@ -481,17 +481,17 @@
n f(n,u,
-e
+o
)%7Dfuncti
@@ -534,17 +534,17 @@
unction
-e
+o
()%7Bretur
@@ -556,17 +556,17 @@
unction
-o
+e
(n)%7Bretu
|
c68294b3aea028f3b4eee93f6637ae5bbf334032
|
Add focus shortcut, comments; Expose parseInput
|
js/prompt.js
|
js/prompt.js
|
const prompt = (() => {
'use strict';
const stdin = document.getElementById('stdin');
const stdout = document.getElementById('stdout');
const history = []; // history of inputs
// --- Functions ---
// Get data from the user on return
function getInput () {
let parsed = parseInput(stdin.value);
if (parsed !== null && typeof parsed !== 'undefined' && parsed !== '') { // exists and not empty
const e = event;
const code = e.keyCode || e.which;
if (code === 13) { // Enter keycode
savePrintInput(parsed);
return parsed;
}
}
}
// Parse as number if applicable
function parseInput (str) {
const trimmed = str.trim(); // remove whitespace
let parsed;
if (trimmed !== null && typeof trimmed !== 'undefined' && trimmed !== '') { // exists and not empty
if (isNaN(str) && isNaN(+str)) { // if not a number
parsed = str; // store
} else {
parsed = +str; // parse as number and store
}
} else {
parsed = trimmed; // store
}
return parsed;
}
// Display information to user, including echoing input
function prompt (msg, isInput) { // 'msg' is an array of strings
const condClass = () => {
return isInput ? ' class="msg input"' : ' class="msg output"'; // add userinput class if applicable
};
const el = document.createElement('div'); // create div
for (let i = 0; i < msg.length; i++) {
el.insertAdjacentHTML('beforeend', '<p' + condClass() + '>' + msg[i] + '</p>'); // create paragraph for each message message in array
}
stdout.insertAdjacentElement('beforeend', el); // insert div
scrollBottom();
}
// Such a clear name that it needs no explanation
function savePrintInput (input) {
history.push(input); // save to history
let arrInput = [input]; // set what we just saved as new msg for prompt
prompt(arrInput, true); // I used true; you can alternatively pass any string you want, but just don't use false
stdin.value = ''; // clear input for next response
}
// Scroll to bottom of output/page
function scrollBottom () {
window.scrollTo(0, document.body.scrollHeight);
}
// --- Event listeners ---
stdin.addEventListener('focus', () => {
if (stdin.placeholder) {
stdin.removeAttribute('placeholder');
}
});
stdin.addEventListener('blur', () => {
stdin.placeholder = '>';
});
stdin.addEventListener('keyup', getInput);
document.getElementById('stdout-clear').firstChild.addEventListener('click', scrollBottom);
// --- Expose ---
return {
history: history,
prompt: prompt,
scrollBottom: scrollBottom
};
})();
|
JavaScript
| 0 |
@@ -204,16 +204,369 @@
ns ---%0A%0A
+ // Focus the input when the slash (/) key is pressed%0A function focusInput () %7B%0A if (document.activeElement.tagName !== 'INPUT' && document.activeElement.tagName !== 'TEXTAREA') %7B%0A const e = event;%0A const code = e.keyCode %7C%7C e.which;%0A if (code === 191) %7B // slash (/) keycode%0A stdin.focus(); // focus input%0A %7D%0A %7D%0A %7D%0A%0A
// Get
@@ -2604,24 +2604,65 @@
us', () =%3E %7B
+ // remove input placeholder when focused
%0A if (std
@@ -2771,24 +2771,72 @@
ur', () =%3E %7B
+ // restore input placeholder when focus is lost
%0A stdin.p
@@ -2997,16 +2997,66 @@
Bottom);
+%0A document.addEventListener('keyup', focusInput);
%0A%0A // -
@@ -3103,16 +3103,44 @@
istory,%0A
+ parseInput: parseInput,%0A
prom
|
c7ad79e8dfafafd0adade5e9723846693fb6979d
|
Make unpublish *actually* work without args
|
lib/unpublish.js
|
lib/unpublish.js
|
module.exports = unpublish
var registry = require("./utils/registry")
, log = require("./utils/log")
, npm = require("../npm")
, readJson = require("./utils/read-json")
, path = require("path")
unpublish.usage = "npm unpublish <project>[@<version>]"
unpublish.completion = function (args, index, cb) {
var remotePkgs = require("./utils/completion/remote-packages")
remotePkgs(args, index, true, false, false, cb)
}
function unpublish (args, cb) {
var thing = args.shift().split("@")
, project = thing.shift()
, version = thing.join("@")
if (!project) {
// if there's a package.json in the current folder, then
// read the package name and version out of that.
var cwdJson = path.join(process.cwd(), "package.json")
return readJson(cwdJson, function (er, data) {
if (er) return cb("Usage:\n"+unpublish.usage)
gotProject(data.name, data.version, cb)
})
}
return gotProject(project, version, cb)
}
function gotProject (project, version, cb) {
// remove from the cache first
npm.commands.cache(["clean", project, version], function (er) {
if (er) return log.er(cb, "Failed to clean cache")(er)
registry.unpublish(project, version, cb)
})
}
|
JavaScript
| 0.000002 |
@@ -470,16 +470,30 @@
thing =
+ args.length ?
args.sh
@@ -508,16 +508,21 @@
lit(%22@%22)
+ : %5B%5D
%0A , p
|
1e9fbd18d2bc9e162e8385ddab9455fee6a4eb9f
|
consolidate export
|
lib/utils/app.js
|
lib/utils/app.js
|
'use strict';
import moduleUtils from './module';
import path from 'path';
/**
* Return JSON contents of file name from root
* @param {String} fileName - name of file to read
* @returns {Object} - file contents
*/
function getFileFromRoot(fileName) {
return require(path.join(moduleUtils.getYoPath(), fileName));
}
/**
* Return build config
* @returns {Object} - build config
*/
function getBuildConfig() {
return getFileFromRoot('build.config.js');
}
/**
* Gets the appDir from the root build.config.js
* @return {String} - app directory path
*/
exports.getAppDir = function () {
return getBuildConfig().appDir;
};
/**
* Gets the app's name from the root package.json
* @return {String} - app name
*/
exports.getAppName = function () {
return getFileFromRoot('package.json').name;
};
/**
* Gets the unitTestDir from the root build.config.js
* @return {String} - unit test directory path
*/
exports.getUnitTestDir = function () {
return getBuildConfig().unitTestDir;
};
|
JavaScript
| 0.000002 |
@@ -459,20 +459,41 @@
s');%0A%7D%0A%0A
+export default %7B%0A
/**%0A
+
* Gets
@@ -525,32 +525,34 @@
build.config.js%0A
+
* @return %7BStri
@@ -576,28 +576,24 @@
ry path%0A
+
*/%0A
-exports.
+
getAppDi
@@ -593,35 +593,25 @@
etAppDir
- = function
() %7B%0A
+
+
return g
@@ -634,24 +634,30 @@
appDir;%0A
-%7D;%0A%0A
+ %7D,%0A%0A
/**%0A
+
* Gets
@@ -698,16 +698,18 @@
ge.json%0A
+
* @retu
@@ -731,28 +731,24 @@
pp name%0A
+
*/%0A
-exports.
+
getAppNa
@@ -749,33 +749,23 @@
tAppName
- = function
() %7B%0A
+
return
@@ -807,16 +807,22 @@
me;%0A
-%7D;%0A%0A
+ %7D,%0A%0A
/**%0A
+
* G
@@ -871,16 +871,18 @@
nfig.js%0A
+
* @retu
@@ -924,20 +924,16 @@
ath%0A
+
*/%0A
-exports.
+
getU
@@ -946,25 +946,15 @@
tDir
- = function
() %7B%0A
+
re
@@ -988,11 +988,15 @@
estDir;%0A
+ %7D%0A
%7D;%0A
|
5fcd952765580e3e7f4cb206e1810028039b2f0a
|
Add `ss.api.log` unified logging API
|
lib/utils/log.js
|
lib/utils/log.js
|
'use strict';
/**
* @ngdoc service
* @name utils.log#debug
* @methodOf utils.log:log
* @function
*
* @description
* Debug level logging, silent by default. Override by assigning a
* function that takes the same parameters as console.log. Example:
* ```
* var ss = require('socketstream');
* ss.log.debug = console.log;
* ```
*/
/**
* @ngdoc service
* @name utils.log#info
* @methodOf utils.log:log
* @function
*
* @description
* Info level logging, silent by default. Override by assigning a
* function that takes the same parameters as console.log. Example:
* ```
* var ss = require('socketstream');
* ss.log.info = console.log;
* ```
*/
/**
* @ngdoc service
* @name utils.log#warn
* @methodOf utils.log:log
* @function
*
* @description
* Warn level logging, uses console.log by default. Override by assigning a
* function that takes the same parameters as console.log. Example:
* ```
* var ss = require('socketstream'),
* winston = require('winston');
* ss.log.warn = winston.warn;
* ```
*/
/**
* @ngdoc service
* @name utils.log#warn
* @methodOf utils.log:log
* @function
*
* @description
* Warn level logging, uses console.error by default. Override by assigning a
* function that takes the same parameters as console.error. Example:
* ```
* var ss = require('socketstream'),
* winston = require('winston');
* ss.log.error = winston.error;
* ```
*/
module.exports = (function() {
var l = function() {
var args = [].slice.call(arguments);
args.unshift("FIXME");
l.info.apply(this, args);
};
l.debug = function(){};
l.info = function(){};
l.warn = console.log;
l.error = console.error;
return l;
}())
|
JavaScript
| 0.000038 |
@@ -8,16 +8,213 @@
rict';%0D%0A
+/**%0D%0A * @ngdoc service%0D%0A * @name utils.log:log%0D%0A * @function%0D%0A *%0D%0A * @description%0D%0A * Contains method stubs for logging to console (by default) or%0D%0A * whatever logging provider you choose.%0D%0A */%0D%0A%0D%0A
/**%0D%0A *
@@ -439,33 +439,24 @@
console.log
-. Example
:%0D%0A * %60%60%60%0D%0A
@@ -494,24 +494,28 @@
m');%0D%0A * ss.
+api.
log.debug =
@@ -528,32 +528,124 @@
e.log;%0D%0A * %60%60%60%0D%0A
+ *%0D%0A * @example%0D%0A * %60%60%60%0D%0A * ss.api.log.debug(%22Something fairly trivial happened%22);%0D%0A * %60%60%60%0D%0A
*/%0D%0A%0D%0A/**%0D%0A * @
@@ -868,33 +868,41 @@
console.log.
- E
+%0D%0A *%0D%0A * @e
xample
-:
%0D%0A * %60%60%60%0D%0A *
@@ -906,71 +906,52 @@
%0A *
-var ss = require('socketstream');%0D%0A * ss.log.info = console.log
+ss.api.log.info(%22Just keeping you informed%22)
;%0D%0A
@@ -1210,25 +1210,16 @@
sole.log
-. Example
:%0D%0A * %60%60
@@ -1299,24 +1299,28 @@
n');%0D%0A * ss.
+api.
log.warn = w
@@ -1333,32 +1333,120 @@
.warn;%0D%0A * %60%60%60%0D%0A
+ *%0D%0A * @example%0D%0A * %60%60%60%0D%0A * ss.api.log.warn(%22Something unexpected happened!%22);%0D%0A * %60%60%60%0D%0A
*/%0D%0A%0D%0A/**%0D%0A * @
@@ -1471,36 +1471,37 @@
@name utils.log#
-warn
+error
%0D%0A * @methodOf u
@@ -1544,36 +1544,37 @@
description%0D%0A *
-Warn
+Error
level logging,
@@ -1693,17 +1693,25 @@
ror.
- E
+%0D%0A *%0D%0A * @e
xample
-:
%0D%0A *
@@ -1723,112 +1723,55 @@
%0A *
-var ss = require('socketstream'),%0D%0A * winston = require('winston');%0D%0A * ss.log.error = winston.error
+ss.api.log.error(%22Time to wakeup the sysadmin%22)
;%0D%0A
|
9687fd2c66bfeedf5b92dd7598f5e959ae82d866
|
update script
|
js/script.js
|
js/script.js
|
jQuery('#pixad1101d').css('overflow', 'hidden');jQuery('.sticky-box').remove();jQuery('#main').css('overflow', 'hidden');jQuery('.article-body iframe').remove();jQuery('.article-body .adsbygoogle').remove();
|
JavaScript
| 0.000001 |
@@ -188,20 +188,154 @@
bygoogle').remove();
+jQuery('.article-body').removeClass('show-summary');jQuery('.article-header .adsbygoogle').css(%7Bheight: '120px', overflow: 'hidden'%7D);
|
ac702c662a26b2cbbea384add761e5d435f3cae0
|
add function parallax
|
js/script.js
|
js/script.js
|
var items = document.querySelectorAll('.parallax');
for (var i = 0; i < items.length; i++ ) {
var item = items[i];
item.classList.add('out');
var parallax = new Parallax(item);
console.log(parallax, item);
}
function Parallax(elem) {
if( !(this instanceof Parallax) ) {
return new Parallax(elem);
}
this.elem = elem;
this.friction = elem.getAttribute('data-friction');
}
Parallax.prototype.run = function() {
console.log('run');
}
Parallax.prototype.clear = function() {
console.log('clear');
}
|
JavaScript
| 0.000003 |
@@ -88,17 +88,16 @@
i++ ) %7B%0A
-%0A
%09var ite
@@ -114,96 +114,19 @@
i%5D;%0A
-%09item.classList.add('out');%0A%0A%09var parallax = new Parallax(item);%0A%09console.log(parallax,
+%0A%09parallax(
item
@@ -140,25 +140,25 @@
unction
-P
+p
arallax(
elem) %7B%0A
@@ -153,196 +153,476 @@
lax(
-el
+it
em) %7B%0A
-%0A%09if( !(this instanceof Parallax) ) %7B%0A%09%09return new Parallax(elem);%09%0A%09%7D%0A%0A%09this.elem = elem;%0A%09this.friction = elem.getAttribute('data-friction');%0A%7D%0A%0AParallax.prototype.run =
+%09var current = item,%0A%09%09currentFriction = current.getAttribute('data-friction'),%0A%09%09wrap = current.getBoundingClientRect(),%0A%09%09top = wrap.top + pageYOffset,%0A%09%09bottom = top + wrap.height;%0A%0A%09document.addEventListener('scroll', function(e) %7B%0A%09%09var winH = window.innerHeight,%0A%09%09%09winBottom = pageYOffset + winH,%0A%09%09%09offset = winBottom - top,%0A%09%09%09diff = offset*currentFriction;%0A%0A%09%09window.requestAnimationFrame(
function
() %7B
@@ -621,98 +621,351 @@
tion
+
() %7B%0A%09
-console.log('run');%0A%7D%0A%0AParallax.prototype.clear = function() %7B%0A%09console.log('clear');
+%09%09%0A%09%09%09if(top %3C winBottom && bottom %3E= pageYOffset) %7B%0A%09%09%09%09parallaxRun(item, diff);%0A%09%09%09%7D%0A%0A%09%09%09if(bottom %3C pageYOffset %7C%7C top %3E winBottom) %7B%0A%09%09%09%09parallaxStop(item);%09%0A%09%09%09%7D%0A%09%09%7D);%0A%09%7D);%0A%7D%0A%0Afunction parallaxRun(item, diff) %7B%0A%09item.style.transform = %22translate3d(0, %22 + diff + %22%25, 0)%22;%0A%7D%0A%0Afunction parallaxStop(item) %7B%0A%09item.style.transform = %22%22;%09
%0A%7D%0A
|
8e0afd65465ae0154fca6655b9c8056c202ded11
|
Update social.js
|
js/social.js
|
js/social.js
|
var social = {
shareToFacebook: function(url) {
FB.ui({
method: 'share',
href: url
}, function(response){});
}
}
|
JavaScript
| 0.000001 |
@@ -12,25 +12,28 @@
= %7B%0A
- shareToFacebook
+%09facebook: %7B%0A%09%09share
: fu
@@ -50,20 +50,19 @@
) %7B%0A
-
+%09%09%09
FB.ui(%7B%0A
@@ -61,57 +61,243 @@
i(%7B%0A
- method: 'share',%0A href: url%0A
+%09%09%09%09method: 'share',%0A%09%09%09%09href: url%0A%09%09 %7D%09, function(response)%7B%7D);%0A%09%09%7D,%0A%09%09like: function(url) %7B%0A%09%09%09FB.ui(%7B%0A%09%09%09%09method: 'share_open_graph',%0A%09%09%09%09action_type: 'og.likes',%0A%09%09%09%09action_properties: JSON.stringify(%7B%0A%09%09%09%09%09object: url,%0A%09%09%09%09%7D)%0A%09%09%09
%7D, f
@@ -318,14 +318,17 @@
se)%7B%7D);%0A
-
+%09%09%7D%0A%09
%7D%0A%7D%0A
|
06aa2d41785b19844b440e0ca3572570b8b823fd
|
access token managment added
|
js/social.js
|
js/social.js
|
var access_token = "";
// This is called with the results from from FB.getLoginStatus().
function statusChangeCallback(response) {
console.log('statusChangeCallback');
console.log(response);
// The response object is returned with a status field that lets the
// app know the current login status of the person.
// Full docs on the response object can be found in the documentation
// for FB.getLoginStatus().
if (response.status === 'connected') {
// Logged into your app and Facebook.
alert(response.authResponse.accessToken);
access_token = response.authResponse.accessToken;
testAPI();
} else if (response.status === 'not_authorized') {
// The person is logged into Facebook, but not your app.
document.getElementById('status').innerHTML = 'Please log ' +
'into this app.';
} else {
// The person is not logged into Facebook, so we're not sure if
// they are logged into this app or not.
document.getElementById('status').innerHTML = 'Please log ' +
'into Facebook.';
}
}
// This function is called when someone finishes with the Login
// Button. See the onlogin handler attached to it in the sample
// code below.
function checkLoginState() {
FB.getLoginStatus(function(response) {
statusChangeCallback(response);
});
}
// Now that we've initialized the JavaScript SDK, we call
// FB.getLoginStatus(). This function gets the state of the
// person visiting this page and can return one of three states to
// the callback you provide. They can be:
//
// 1. Logged into your app ('connected')
// 2. Logged into Facebook, but not your app ('not_authorized')
// 3. Not logged into Facebook and can't tell if they are logged into
// your app or not.
//
// These three cases are handled in the callback function.
// Here we run a very simple test of the Graph API after login is
// successful. See statusChangeCallback() for when this call is made.
function testAPI() {
FB.api('/me?field=name,id', function(response) {
alert('Successful login for: ' + response.name);
});
}
function send_request() {
var myObject = new Object();
myObject.token = access_token;
alert(access_token);
$.ajax({
type: "POST",
crossDomain: true,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "succ",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
url: "http://127.0.0.1:8000/project-director/facebook",
data: JSON.stringify(myObject),
success: function(data)
{
var obj = jQuery.parseJSON(data);
alert(obj.id);
alert(obj.fist_name);
alert(obj.image_url);
// $('body').append(data);
// if(err == "Errore nell'invio dell'e-mail." || err == "E-mail non valida.") {
// $('#form-send-message').addClass('form-send-errors')
// }
// else {
// $('#form-send-message').addClass('form-send-success');
// }
}//,
// error: function(error) {
// alert(error);
// }
});
}
function succ(data) {
var obj = jQuery.parseJSON(data);
alert(obj.id);
alert(obj.fist_name);
alert(obj.image_url);
}
|
JavaScript
| 0 |
@@ -2195,26 +2195,8 @@
x(%7B%0A
- type: %22POST%22,%0A
@@ -2222,175 +2222,42 @@
-dataType: %22jsonp%22,%0A jsonp: false,%0A jsonpCallback: %22succ%22,%0A headers: %7B %0A 'Accept': 'application/json',%0A 'Content-
+type:'POST',%0A data
Type
-'
: '
-application/json' %0A %7D
+jsonp'
,%0A
|
0b59a3e95fc9cf1b85a30778ded235e9623f271e
|
Update status.js
|
js/status.js
|
js/status.js
|
sharepointProcessHelpers.status = sharepointProcessHelpers.status || {};
sharepointProcessHelpers.status.config = {
statusButtonsField: 'MoveToStatusButtons', /* field in the Statuses list that contains the status move buttons to show at each status */
};
sharepointProcessHelpers.guidance.getStatuses = function () {
/* optimize - retrieve common fields once in core then reuse */
sharepointProcessHelpers.core.getListItemById(sharepointProcessHelpers.core.config.packagesList, sharepointProcessHelpers.core.queryObj()['ID'], sharepointProcessHelpers.core.config.statusField).done(
function(ListItem) {
if (ListItem.get_item(sharepointProcessHelpers.core.config.statusField)) {
sharepointProcessHelpers.core.getListItemById(sharepointProcessHelpers.core.config.statusesList, ListItem.get_item(sharepointProcessHelpers.core.config.statusField).get_lookupId(), sharepointProcessHelpers.status.config.statusButtonsField).done(
function(ListItem) {
if (ListItem.get_item(sharepointProcessHelpers.status.config.statusButtonsField)) {
sharepointProcessHelpers.status.addStatusButtons(ListItem.get_item(sharepointProcessHelpers.status.config.statusButtonsField));
}
}
);
}
}
);
}
sharepointProcessHelpers.status.addStatusButtons = function (statuses) {
/*if (window.bounced !== true) {*/
$.each(statuses, function(index, value) {
$('#sharepoint-process-helpers_status_buttons').show();
var id = value.get_lookupId();
var title = value.get_lookupValue();
$('#sharepoint-process-helpers_status_buttons_content').append(
"<div class='sharepoint-process-helpers_button sharepoint-process-helpers_button_primary sharepoint-process-helpers_status_button' data-status-id='" +
id + "'>Move to " + title + "</div>");
});
/*}*/
}
$(document).on('click', '.sharepoint-process-helpers_status_button', function() {
var statusId = $(this).data('status-id');
/*var prerequisiteField = null;*/
/*sharepointProcessHelpers.core.getListItemById('Statuses', statusId, /*, ['PrerequisiteField',
'MoveStatusConfirmation'
]).done(function(ListItem) {*/
/*var prerequisiteField = ListItem.get_item('PrerequisiteField');
var moveStatusConfirmation = ListItem.get_item('MoveStatusConfirmation');
var cancel = false;
if (prerequisiteField) {
GetListItemById(sharepointProcessHelpers.core.config.packagesList, queryObj()['ID'], [prerequisiteField]).done(
function(ListItem) {
if (!ListItem.get_item(prerequisiteField)) {
alert(
"Please fill in the required field."
)
} else {
if (moveStatusConfirmation && !confirm(moveStatusConfirmation)) {
cancel = true;
}
if (!cancel) {
UpdateListItem(sharepointProcessHelpers.core.config.packagesList, queryObj()['ID'], sharepointProcessHelpers.core.config.statusField,
statusId).done(function() {
location.reload();
});
}
}
});
} else {
if (moveStatusConfirmation && !confirm(moveStatusConfirmation)) {
cancel = true;
}*/
/*if (!cancel) {*/
sharepointProcessHelpers.core.updateListItem(sharepointProcessHelpers.core.config.packagesList, sharepointProcessHelpers.core.queryObj()['ID'], sharepointProcessHelpers.core.config.statusField, statusId).done(
function() {
sharepointProcessHelpers.core.addMessage('statusMoved');
location.reload();
}
);
/*}*/
/*}*/
});
if (sharepointProcessHelpers.core.queryObj()['ID']) {
_spBodyOnLoadFunctionNames.push("sharepointProcessHelpers.guidance.getStatuses");
}
|
JavaScript
| 0.000002 |
@@ -3464,41 +3464,40 @@
%7B%0A
-_spBodyOnLoadFunctionNames.push(%22
+ExecuteOrDelayUntilScriptLoaded(
shar
@@ -3537,14 +3537,22 @@
Statuses
+, %22sp.js
%22);%0A%7D%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.