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
|
---|---|---|---|---|---|---|---|
06627cfa6ac8f1f1cb1769c2158c31916b736345
|
use index.js for integration testing, not app.js
|
test/server/integration/test.api.example.js
|
test/server/integration/test.api.example.js
|
var should = require('should'),
request = require('supertest'),
app = require('../../../app');
describe('/api/example', function () {
describe('POST /api/example', function () {
it('should return valid status', function (done) {
request(app)
.post('/api/example')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.eql({
status: 'Created record!'
});
done();
});
});
});
describe('GET /api/example', function () {
it('should return valid status', function (done) {
request(app)
.get('/api/example')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.eql({
status: 'Sending you the list of examples.'
});
done();
});
});
});
describe('GET /api/example/:id', function () {
it('should return valid status', function (done) {
request(app)
.get('/api/example/123')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.eql({
status: 'sending you record with id of 123'
});
done();
});
});
});
describe('PUT /api/example/:id', function () {
it('should return valid status', function (done) {
request(app)
.put('/api/example/123')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.eql({
status: 'updated record with id 123'
});
done();
});
});
});
describe('DELETE /api/example/:id', function () {
it('should return valid status', function (done) {
request(app)
.del('/api/example/123')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.body.should.eql({
status: 'deleted record with id 123'
});
done();
});
});
});
describe('GET /api/example/custom', function () {
it('should return valid status', function (done) {
request(app)
.get('/api/example/custom')
.expect('Content-Type', /html/)
.expect(200)
.end(function (err, res) {
if (err) return done(err);
res.text.should.equal('<p>Hello from custom action controller</p>');
done();
});
});
});
});
|
JavaScript
| 0.000002 |
@@ -89,19 +89,21 @@
./../../
-app
+index
');%0A%0Ades
|
ea6ce326b47ff7de1b0066b653dff3ea1f666719
|
add filter for file extension, works on win!
|
app/atom.js
|
app/atom.js
|
// Stopgap atom.js file for handling normal browser things that atom
// does not yet have stable from the browser-side API.
// - Opening external links in default web browser
// - Saving files/downloads to disk
$(document).ready(function() {
if (typeof process === 'undefined') return;
if (typeof process.versions['atom-shell'] === undefined) return;
var remote = require('remote');
var shell = require('shell');
var http = require('http');
var url = require('url');
var fs = require('fs');
$('body').on('click', 'a', function(ev) {
var uri = url.parse(ev.currentTarget.href);
// Opening external URLs.
if (uri.hostname && uri.hostname !== 'localhost') {
shell.openExternal(ev.currentTarget.href);
return false;
}
// File saving.
var fileTypes = {
tm2z: 'Package',
mbtiles: 'Tiles',
png: 'Image',
jpg: 'Image',
jpeg: 'Image'
}
var typeExtension = uri.pathname.split('.').pop().toLowerCase();
var typeLabel = fileTypes[typeExtension];
if (typeLabel) {
var filePath = remote.require('dialog').showSaveDialog({
title: 'Save ' + typeLabel,
defaultPath: '~/Untitled ' + typeLabel + '.' + typeExtension
});
if (filePath) {
uri.method = 'GET';
var writeStream = fs.createWriteStream(filePath);
var req = http.request(uri, function(res) {
if (res.statusCode !== 200) return;
res.pipe(writeStream);
});
req.end();
}
return false;
}
// Passthrough everything else.
});
});
|
JavaScript
| 0 |
@@ -1333,16 +1333,110 @@
xtension
+,%0A filters: %5B%7B name: typeExtension.toUpperCase(), extensions: %5BtypeExtension%5D%7D%5D
%0A
|
db014c16bf9ebf9021578d4137f328b670c787eb
|
Backup restore() when 'close' fails to fire
|
core/door.js
|
core/door.js
|
/* jslint node: true */
'use strict';
var spawn = require('child_process').spawn;
var events = require('events');
var _ = require('lodash');
var pty = require('ptyw.js');
var decode = require('iconv-lite').decode;
var net = require('net');
var async = require('async');
exports.Door = Door;
function Door(client, exeInfo) {
events.EventEmitter.call(this);
this.client = client;
this.exeInfo = exeInfo;
this.exeInfo.encoding = this.exeInfo.encoding || 'cp437';
//
// Members of exeInfo:
// cmd
// args[]
// env{}
// cwd
// io
// encoding
// dropFile
// node
// inhSocket
//
}
require('util').inherits(Door, events.EventEmitter);
Door.prototype.run = function() {
var self = this;
var doorData = function(data) {
// :TODO: skip decoding if we have a match, e.g. cp437 === cp437
self.client.term.write(decode(data, self.exeInfo.encoding));
};
var restore = function(piped) {
if(self.client.term.output) {
self.client.term.output.unpipe(piped);
self.client.term.output.resume();
}
};
var sockServer;
async.series(
[
function prepareServer(callback) {
if('socket' === self.exeInfo.io) {
sockServer = net.createServer(function connected(conn) {
sockServer.getConnections(function connCount(err, count) {
// We expect only one connection from our DOOR/emulator/etc.
if(!err && count <= 1) {
self.client.term.output.pipe(conn);
conn.on('data', doorData);
conn.on('end', function ended() {
restore(conn);
});
conn.on('error', function error(err) {
self.client.log.info('Door socket server connection error: ' + err.message);
restore(conn);
});
}
});
});
sockServer.listen(0, function listening() {
callback(null);
});
} else {
callback(null);
}
},
function launch(callback) {
// Expand arg strings, e.g. {dropFile} -> DOOR32.SYS
var args = _.clone(self.exeInfo.args); // we need a copy so the original is not modified
for(var i = 0; i < args.length; ++i) {
args[i] = self.exeInfo.args[i].format({
dropFile : self.exeInfo.dropFile,
node : self.exeInfo.node.toString(),
//inhSocket : self.exeInfo.inhSocket.toString(),
srvPort : sockServer ? sockServer.address().port.toString() : '-1',
userId : self.client.user.userId.toString(),
});
}
var door = pty.spawn(self.exeInfo.cmd, args, {
cols : self.client.term.termWidth,
rows : self.client.term.termHeight,
// :TODO: cwd
env : self.exeInfo.env,
});
if('stdio' === self.exeInfo.io) {
self.client.log.debug('Using stdio for door I/O');
self.client.term.output.pipe(door);
door.on('data', doorData);
door.on('close', function closed() {
restore(door);
});
} else if('socket' === self.exeInfo.io) {
self.client.log.debug(
{ port : sockServer.address().port },
'Using temporary socket server for door I/O');
}
door.on('exit', function exited(code) {
self.client.log.info( { code : code }, 'Door exited');
if(sockServer) {
sockServer.close();
}
door.removeAllListeners();
self.emit('finished');
});
}
],
function complete(err) {
if(err) {
self.client.log.warn( { error : err.toString() }, 'Failed executing door');
}
}
);
};
|
JavaScript
| 0.000002 |
@@ -889,24 +889,48 @@
ing));%0A%09%7D;%0A%0A
+%09var restored = false;%0A%0A
%09var restore
@@ -955,16 +955,29 @@
%7B%0A%09%09if(
+!restored &&
self.cli
@@ -1074,16 +1074,36 @@
sume();%0A
+%09%09%09restored = true;%0A
%09%09%7D%0A%09%7D;%0A
@@ -3276,24 +3276,123 @@
();%0A%09%09%09%09%09%7D%0A%0A
+%09%09%09%09%09//%09we may not get a close%0A%09%09%09%09%09if('stdio' === self.exeInfo.io) %7B%0A%09%09%09%09%09%09restore(door);%0A%09%09%09%09%09%7D%0A%0A
%09%09%09%09%09door.re
|
f5f9be47c450f8d10d519007d3dbcdcd9d4f61bc
|
remove unused file reference
|
app/boot.js
|
app/boot.js
|
window.name = 'NG_DEFER_BOOTSTRAP!';
require.config({
waitSeconds: 120,
baseUrl : '/app',
paths: {
'authentication' : 'services/authentication',
'angular' : 'libs/angular-flex/angular-flex',
'ngRoute' : 'libs/angular-route/angular-route.min',
'ngSanitize' : 'libs/angular-sanitize/angular-sanitize.min',
'domReady' : 'libs/requirejs-domready/domReady',
'text' : 'libs/requirejs-text/text',
'bootstrap' : 'libs/bootstrap/dist/js/bootstrap.min',
'lodash' : 'libs/lodash/lodash.min',
'URIjs' : 'libs/uri.js/src',
'linqjs' : 'libs/linqjs/linq.min',
'leaflet' : 'libs/leaflet/dist/leaflet',
'jquery' : 'libs/jquery/dist/jquery.min',
'moment' : 'libs/moment/moment',
'leaflet-directive' : 'js/libs/leaflet/angular-leaflet-directive',
'ng-breadcrumbs' : 'js/libs/ng-breadcrumbs/dist/ng-breadcrumbs.min',
'bootstrap-datepicker': 'libs/bootstrap-datepicker/js/bootstrap-datepicker',
'ionsound' : 'libs/ionsound/js/ion.sound.min',
'jqvmap' : 'js/libs/jqvmap/jqvmap/jquery.vmap',
'jqvmapworld' : 'js/libs/jqvmap/jqvmap/maps/jquery.vmap.world',
'ngAnimate' : 'libs/angular-animate/angular-animate.min',
'ngAria' : 'libs/angular-aria/angular-aria.min',
'ngMaterial' : 'libs/angular-material/angular-material.min',
'ngSmoothScroll' : 'libs/ngSmoothScroll/angular-smooth-scroll.min',
'ammap3WorldHigh' : 'directives/reporting-display/worldEUHigh',
'ammap3' : 'libs/ammap3/ammap/ammap',
'ammap-theme' : 'libs/ammap3/ammap/themes/light',
'ammap-resp' : 'libs/ammap3/ammap/plugins/responsive/responsive',
'ammap-export' : 'libs/ammap3/ammap/plugins/export/export.min',
'ammap-ex-fabric' : 'libs/ammap3/ammap/plugins/export/libs/fabric.js/fabric.min',
'ammap-ex-filesaver' : 'libs/ammap3/ammap/plugins/export/libs/FileSaver.js/FileSaver.min',
'ammap-ex-pdfmake' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/pdfmake.min',
'ammap-ex-vfs-fonts' : 'libs/ammap3/ammap/plugins/export/libs/pdfmake/vfs_fonts',
'ammap-ex-jszip' : 'libs/ammap3/ammap/plugins/export/libs/jszip/jszip.min',
'ammap-ex-xlsx' : 'libs/ammap3/ammap/plugins/export/libs/xlsx/xlsx.min',
},
shim: {
'libs/angular/angular' : { deps: ['jquery'] },
'angular' : { deps: ['libs/angular/angular'] },
'ngRoute' : { deps: ['angular'] },
'ngSanitize' : { deps: ['angular'] },
'leaflet-directive' : { deps: ['angular', 'leaflet'], exports : 'L' },
'ng-breadcrumbs' : { deps: ['angular'] },
'bootstrap' : { deps: ['jquery'] },
'linqjs' : { deps: [], exports : 'Enumerable' },
'leaflet' : { deps: [], exports : 'L' },
'bootstrap-datepicker' : { deps: ['bootstrap'] },
'jqvmap' : { deps: ['jquery'] },
'jqvmapworld' : { deps: ['jqvmap'] },
'ionsound' : { deps: ['jquery'] },
'ngAnimate' : { deps: ['angular'] },
'ngAria' : { deps: ['angular'] },
'ngMaterial' : { deps: ['angular', 'ngAnimate', 'ngAria'] },
'ngSmoothScroll' : { deps: ['angular'] },
'ammapEU' : { deps: ['ammap3'] },
'ammap3WorldHigh' : { deps: ['ammap3'] },
'ammap-theme' : { deps: ['ammap3']},
'ammap-resp' : { deps: ['ammap3']},
'ammap-export' : { deps: ['ammap3']}
},
});
// BOOT
require(['angular', 'domReady!', 'bootstrap', 'app', 'routes', 'index'], function(ng, doc){
ng.bootstrap(doc, ['kmApp']);
ng.resumeBootstrap();
});
|
JavaScript
| 0.000001 |
@@ -3625,65 +3625,8 @@
%7D,%0A
- 'ammapEU' : %7B deps: %5B'ammap3'%5D %7D,%0A
|
88aebd69c12ba6d9b2c9300f643bc560eb71b0c5
|
Update fichaReme.js
|
app/pdf/fichaReme.js
|
app/pdf/fichaReme.js
|
var PdfPrinter = require('pdfmake/src/printer');
var path = require('path');
module.exports = {
pdf: function(Ficha) {
// Validar Ficha para reemplazar nulos por strings vacios, para que no aparezca "null" en el pdf
var fichaTemp = JSON.stringify(Ficha, function(key, value){
if(value === null){
return "";
}
// Primera letra mayuscula en la seccion
if(key == "seccion"){
return value.charAt(0).toUpperCase() + value.slice(1)
}
return value;
});
Ficha = JSON.parse(fichaTemp);
// Parsear area de desarrollo
var areadedesarrollo = "";
var area = "";
switch (Ficha.seccion) {
case 'manada':
area = "Presa";
switch(Ficha.areadedesarrollo){
case "corporalidad":
areadedesarrollo = "Bagheera (Corporalidad)";
break;
case "creatividad":
areadedesarrollo = "Kaa (Creatividad)";
break;
case "caracter":
areadedesarrollo = "Baloo (Carácter)";
break;
case "afectividad":
areadedesarrollo = "Rikki-Tikki-Tavi (Afectividad)";
break;
case "sociabilidad":
areadedesarrollo = "Kotick (Sociabilidad)";
break;
case "espiritualidad":
areadedesarrollo = "Francisco de Asís (Espiritualidad)";
break;
};
break;
case 'tropa':
= "Territorio";
switch(Ficha.areadedesarrollo){
case "corporalidad":
areadedesarrollo = "Pez (Corporalidad)";
break;
case "creatividad":
areadedesarrollo = "Ave (Creatividad)";
break;
case "caracter":
areadedesarrollo = "Tortuga (Carácter)";
break;
case "afectividad":
areadedesarrollo = "Flor (Afectividad)";
break;
case "sociabilidad":
areadedesarrollo = "Abeja (Sociabilidad)";
break;
case "espiritualidad":
areadedesarrollo = "Árbol (Espiritualidad)";
break;
};
break;
case 'comunidad':
area = "Desafío";
switch(Ficha.areadedesarrollo){
case "corporalidad":
areadedesarrollo = "Delfín (Corporalidad)";
break;
case "creatividad":
areadedesarrollo = "Ave (Creatividad)";
break;
case "caracter":
areadedesarrollo = "Caballo (Carácter)";
break;
case "afectividad":
areadedesarrollo = "Flor (Afectividad)";
break;
case "sociabilidad":
areadedesarrollo = "Abeja (Sociabilidad)";
break;
case "espiritualidad":
areadedesarrollo = "Árbol (Espiritualidad)";
break;
};
break;
case 'clan':
area = "Área de Desarrollo";
switch(Ficha.areadedesarrollo){
case "corporalidad":
areadedesarrollo = "Corporalidad";
break;
case "creatividad":
areadedesarrollo = "Creatividad";
break;
case "caracter":
areadedesarrollo = "Carácter";
break;
case "afectividad":
areadedesarrollo = "Afectividad";
break;
case "sociabilidad":
areadedesarrollo = "Sociabilidad";
break;
case "espiritualidad":
areadedesarrollo = "Espiritualidad";
break;
};
break;
}
// Parsear materiales string a array
var materiales =[];
Ficha.materiales.split("<br>").slice(0,Ficha.materiales.split('<br>').length - 1).forEach(function(material){
materiales.push(material);
});
// PDF Content
var dd= {
info: {
title: ''+Ficha.nombreactividad+'',
author: ''+Ficha.User.facebookname+'',
subject: ''+Ficha.nombreactividad+'',
keywords: 'scouts',
creator: 'http://uhluscout.com'
},
content: [
{ text: ''+Ficha.nombreactividad+'', style: 'header'},
{
layout: 'headerLineOnly',
table: {
headerRows: 1,
widths: [ 'auto', 'auto', 'auto', '*' ],
body: [
[ 'NOMBRE DE LA ACTIVIDAD', 'SECCIÓN', ''+area.toUpperCase()+'', 'PARTICIPANTES' ],
[ ''+Ficha.nombreactividad+'', ''+Ficha.seccion+'', ''+areadedesarrollo+'', ''+Ficha.participantes+'' ]
]
},
style: 'marginBot'
},
{
layout: 'headerLineOnly',
table: {
headerRows: 1,
widths: [ '*'],
body: [
[ 'DESCRIPCIÓN DE LA ACTIVIDAD'],
[ ''+Ficha.descripcion+'']
]
},
style: 'marginBot'
},
{
layout: 'headerLineOnly',
table: {
headerRows: 1,
widths: [ '*'],
body: [
[ 'RECOMENDACIONES'],
[ ''+Ficha.recomendaciones+'']
]
},
style: 'marginBot'
},
{
layout: 'headerLineOnly',
table: {
headerRows: 1,
widths: [ '*'],
body: [
[ 'MATERIALES'],
[
{
// to treat a paragraph as a bulleted list, set an array of items under the ul key
ul: materiales
},
]
]
},
style: 'marginBot'
},
{
layout: 'headerLineOnly',
table: {
headerRows: 1,
widths: [ '*', '*', '*'],
body: [
[ 'TIEMPOS', 'AUTOR', 'FECHA'],
[ ''+Ficha.tiempos+'', ''+Ficha.User.facebookname+'', ''+Ficha.created_at+'']
]
},
style: 'marginBot'
},
{ text: 'Ficha Elaborada y descargada desde http://uhluscout.com', link: 'http://uhluscout.com', style: 'footer'}
],
styles: {
header: {
fontSize: 22,
bold: true,
alignment: 'right',
margin: [ 0, 0, 0, 25 ]
},
marginBot:{
margin: [ 0, 0, 0, 25 ]
},
footer: {
bold: true,
alignment: 'right'
},
}
}//end dd
var fontDescriptors = {
Roboto: {
normal: path.join(__dirname, '/fonts/Roboto-Regular.ttf'),
bold: path.join(__dirname, '/fonts/Roboto-Medium.ttf'),
italics: path.join(__dirname, '/fonts/Roboto-Italic.ttf'),
bolditalics: path.join(__dirname, '/fonts/Roboto-MediumItalic.ttf')
}
};
var printer = new PdfPrinter(fontDescriptors);
return printer.createPdfKitDocument(dd);
}
};
|
JavaScript
| 0 |
@@ -1826,16 +1826,20 @@
+area
= %22Terr
|
2158a055d10893c0e30d4d376c2e51eed4ba5291
|
Use lazyFunctionRequire for improved import performance.
|
extensions/roc-plugin-typescript/src/roc/index.js
|
extensions/roc-plugin-typescript/src/roc/index.js
|
import webpack from '../webpack';
export default {
description: `
# roc-plugin-typescript
A roc plugin for compiling typescript (*.ts and *.tsx) files. It uses
[ts-loader](https://github.com/TypeStrong/ts-loader) for to let webpack compile
typescript files and adds source maps via
[source-map-loader](https://github.com/webpack/source-map-loader).
## How to use?
Add the plugin as a dev dependency of your [roc](http://www.getroc.org) application:
\`\`\`
npm install --save-dev roc-plugin-typescript
\`\`\`
The plugin will automatically hook into webpacks build process and add a loader
for *.ts and *.tsx files. The compiler will look for a \`tsconfig.json\` file in
the root of you roc project, which you can use for configuration.
`,
actions: [{
hook: 'build-webpack',
description: 'Adds typescript support to Webpack.',
action: webpack,
}],
required: {
'roc-package-webpack': '^1.0.0-beta.1',
},
};
|
JavaScript
| 0 |
@@ -4,33 +4,93 @@
ort
-webpack from '../webpack'
+%7B lazyFunctionRequire %7D from 'roc';%0A%0Aconst lazyRequire = lazyFunctionRequire(require)
;%0A%0Ae
@@ -977,23 +977,41 @@
action:
+lazyRequire('../
webpack
+')
,%0A %7D%5D
|
7ffb29aa6ce5a95fd78d725379eb3d8a45adf185
|
Fix #path() (#1519)
|
test/support/builders/atom_watcher_event.js
|
test/support/builders/atom_watcher_event.js
|
/* @flow */
const _ = require('lodash')
const path = require('path')
const metadata = require('../../../core/metadata')
const events = require('../../../core/local/steps/event')
const statsBuilder = require('./stats')
/*::
import type { Stats } from 'fs'
import type { Metadata } from '../../../core/metadata'
import type { AtomWatcherEvent, EventAction, EventKind, Batch } from '../../../core/local/steps/event'
import type { StatsBuilder } from './stats'
*/
function randomPick /*:: <T> */ (elements /*: Array<T> */) /*: T */{
const l = elements.length
const i = Math.floor(Math.random() * l)
return elements[i]
}
function kind (doc /*: Metadata */) /*: EventKind */ {
return doc.docType === 'folder' ? 'directory' : doc.docType
}
module.exports = class AtomWatcherEventBuilder {
/*::
_event: AtomWatcherEvent
_statsBuilder: ?StatsBuilder
*/
constructor (old /*: ?AtomWatcherEvent */) {
if (old) {
this._event = _.cloneDeep(old)
} else {
const kind = randomPick(events.KINDS)
this._event = {
action: randomPick(events.ACTIONS),
kind,
path: '/',
_id: '/'
}
}
this._ensureStatsBuilder()
}
_ensureStatsBuilder () /*: StatsBuilder */ {
this._statsBuilder = this._statsBuilder ||
statsBuilder
.fromStats(this._event.stats)
.kind(this._event.kind)
return this._statsBuilder
}
fromDoc (doc /*: Metadata */) /*: this */ {
const updatedAt = new Date(doc.updated_at)
let builder =
this
.kind(kind(doc))
.path(doc.path)
.ctime(updatedAt)
.mtime(updatedAt)
if (doc.ino) builder = builder.ino(doc.ino)
return builder
}
build () /*: AtomWatcherEvent */ {
if (this._statsBuilder) {
this._event.stats = this._statsBuilder.build()
}
return this._event
}
action (newAction /*: EventAction */) /*: this */ {
this._event.action = newAction
if (newAction === 'deleted') this.noStats()
return this
}
kind (newKind /*: EventKind */) /*: this */ {
this._event.kind = newKind
if (this._statsBuilder) this._statsBuilder.kind(newKind)
return this
}
path (newPath /*: string */) /*: this */ {
this._event.path = path.normalize(newPath)
this._event._id = metadata.id(newPath)
return this
}
oldPath (newPath /*: string */) /*: this */{
this._event.oldPath = path.normalize(newPath)
return this
}
id (newId /*: string */) /*: this */ {
this._event._id = newId
return this
}
ino (newIno /*: number */) /*: this */ {
this._ensureStatsBuilder().ino(newIno)
return this
}
mtime (newMtime /*: Date */) /*: this */ {
this._ensureStatsBuilder().mtime(newMtime)
return this
}
ctime (newCtime /*: Date */) /*: this */ {
this._ensureStatsBuilder().ctime(newCtime)
return this
}
noStats () /*: this */ {
delete this._event.stats
delete this._statsBuilder
return this
}
md5sum (newMd5sum /*: string */) /*: this */ {
this._event.md5sum = newMd5sum
return this
}
noIgnore () /*: this */ {
this._event.noIgnore = true
return this
}
incomplete () /*: this */ {
this._event.incomplete = true
delete this._event.md5sum
return this.noStats()
}
}
|
JavaScript
| 0.000001 |
@@ -2298,20 +2298,29 @@
data.id(
-newP
+this._event.p
ath)%0A
|
6eb7430ed13290d36b34d61454d2d0e083e6e92a
|
fix missing http method
|
app/js/plex/PlexServer.js
|
app/js/plex/PlexServer.js
|
var request = require('request');
var safeParse = require("safe-json-parse/callback")
var parseXMLString = require('xml2js').parseString;
var PlexTv = require('./PlexTv.js')
var PlexClient = require('./PlexClient.js')
var PlexConnection = require('./PlexConnection.js')
var PlexAuth = require('./PlexAuth.js')
module.exports = function PlexServer(){
this.name;
this.product;
this.productVersion;
this.platform;
this.platformVersion;
this.device;
this.clientIdentifier;
this.createdAt;
this.lastSeenAt;
this.provides;
this.owned;
this.httpsRequired;
this.ownerId;
this.home;
this.accessToken
this.sourceTitle;
this.synced;
this.relay;
this.publicAddressMatches;
this.presence;
this.plexConnections;
this.chosenConnection = null;
//Functions
this.hitApi = function(command,params,callback){
var that = this
var query = "";
for (key in params) {
query += encodeURIComponent(key)+'='+encodeURIComponent(params[key])+'&';
}
global.log.info('Hitting server ' + this.name + ' via ' + this.chosenConnection.uri)
var _url = this.chosenConnection.uri + command + '?' + query
var options = PlexAuth.getApiOptions(_url, this.accessToken, 15000);
//global.log.info('Hitting server ' + this.name + ' with command ' + command)
//global.log.info(options)
request(options, function (error, response, body) {
if (!error) {
safeParse(body, function (err, json){
if (err){
return callback(null,that,connection)
}
return callback(json,that,connection)
})
} else {
return callback(null,that,connection)
}
})
}
this.hitApiTestConnections = function(command,connection,callback){
//For use with #findConnection
if (connection == null){
if (this.chosenConnection == null){
global.log.info('You need to specify a connection!')
return(callback(false,connection))
}
}
var _url = connection.uri + command
var options = PlexAuth.getApiOptions(_url, this.accessToken, 7500);
request(options, function (error, response, body) {
if (!error) {
safeParse(body, function (err, json){
if (err){
return callback(null,connection)
}
return callback(json,connection)
})
} else {
return callback(null,connection)
}
})
}
this.setChosenConnection = function(con) {
console.log('Setting the used connection for ' + this.name + ' to ' + con.uri)
this.chosenConnection = con
return
}
this.findConnection = function(){
//This function iterates through all available connections and
// if any of them return a valid response we'll set that connection
// as the chosen connection for future use.
var that = this;
for (var i in this.plexConnections){
var connection = this.plexConnections[i]
this.hitApiTestConnections('',connection,function(result,connectionUsed){
//global.log.info('Connection attempt result below for ' + that.name)
//global.log.info(connectionUsed)
if (result == null || result == undefined) {
global.log.info('Connection failed: ' + connectionUsed.uri)
//global.log.info(result)
return
}
if (that.chosenConnection != null){
//Looks like we've already found a good connection
// lets disregard this connection
global.log.info('Already have a working connection for ' + that.name + ' which is ' + that.chosenConnection.uri)
return
}
if (result.MediaContainer != undefined || result._elementType != undefined){
global.log.info('Found the first working connection for ' + that.name + ' which is ' + connectionUsed.uri)
that.setChosenConnection(connectionUsed)
return
}
//global.log.info('Unsure of what this result is for connection to PMS. Probably failed. Server: ' + that.name)
//global.log.info(result)
return
})
}
}
//Functions for dealing with media
this.search = function(searchTerm,callback){
//This function hits the PMS using the /search endpoint and returns what the server returns if valid
var that = this
this.hitApi('/search',{'query':searchTerm},function(result){
validResults = []
if (result){
for (var i in result._children){
var res = result._children[i]
if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
validResults.push(res)
}
}
return callback(validResults,that)
}
return callback(null,that)
})
}
this.getMediaByRatingKey = function(ratingKey,callback){
//This function hits the PMS and returns the item at the ratingKey
this.hitApi('/library/metadata/'+ratingKey,{},function(result,that){
validResults = []
global.log.info('Response back from metadata request')
//global.log.info(result)
if (result != null){
if (result._children) {
// Old Server version compatibility
for (var i in result._children){
var res = result._children[i]
if (res._elementType == 'Directory' || res._elementType == 'Media' || res._elementType == 'Video'){
return callback(res,that)
}
}
} else {
// New Server compatibility
return callback(result.MediaContainer.Metadata[0],that)
}
global.log.info('Didnt find a compatible PMS Metadata object. Result from the server is below')
global.log.info(result)
return callback(null,that)
}
global.log.info('Didnt find a compatible PMS Metadata object because result == null. Result from the server is below')
global.log.info(result)
return callback(null,that)
})
}
};
|
JavaScript
| 0.006941 |
@@ -1289,16 +1289,23 @@
n, 15000
+, 'GET'
);%0A
@@ -2335,16 +2335,23 @@
en, 7500
+, 'GET'
);%0A
|
2ec265aa4f81f672a14a2705c2c3b00785f89650
|
Create logic to insert sibling status span if it doesn't exist.
|
backfeed.js
|
backfeed.js
|
/* backfeed.js */
var Backfeed = (function() {
"use strict";
//define classes to add/remove
const errorStatusClass = 'glyphicon-remove';
const errorGroupClass = 'has-error';
const successStatusClass = 'glyphicon-ok';
const successGroupClass = 'has-success';
const formGroupClass = 'form-group';
const formControlFeedbackClass = 'form-control-feedback';
//attach change listeners to each input
var watchInputs = function(inputList) {
for (let formInput in inputList) {
var currInput = inputList[formInput];
_registerListener('keyup', currInput['input']);
}
};
//Traverse upward through the DOM to the nearest form group
var _getParentFormGroup = function(element) {
while (! element.parentNode.classList.contains(formGroupClass)) {
element = element.parentNode;
}
return element.parentNode;
};
//Traverse input siblings to find sibling form-control-feedback
var _getSiblingFormControlFeedback = function(element) {
var siblingsInclusive = element.parentNode.children;
var sibling;
for (var i = 0; i < siblingsInclusive.length; i ++) {
sibling = siblingsInclusive[i];
if (sibling !== element) {
if (sibling.classList.contains(formControlFeedbackClass)) {
return sibling;
}
}
}
return null;
};
//Add an event listener to a single form input
var _registerListener = function(eventName, element) {
element = document.getElementById(element);
var status = _getSiblingFormControlFeedback(element);
var group = _getParentFormGroup(element);
element.addEventListener(eventName, function invoke(event) {
_updateStatus(event, status, group);
}, false);
};
//update the classes of the usernameInput field
var _updateStatus = function(event, statusTag, groupTag) {
var statusClasses = statusTag.classList;
var groupClasses = groupTag.classList;
if (event.target.checkValidity()) {
//contents are valid
if (!statusClasses.contains(successStatusClass)) {
statusClasses.add(successStatusClass);
}
if (!groupClasses.contains(successGroupClass)) {
groupClasses.add(successGroupClass);
}
if (statusClasses.contains(errorStatusClass)) {
statusClasses.remove(errorStatusClass);
}
if (groupClasses.contains(errorGroupClass)) {
groupClasses.remove(errorGroupClass);
}
} else {
//contents are invalid
if (statusClasses.contains(successStatusClass)) {
statusClasses.remove(successStatusClass);
}
if (groupClasses.contains(successGroupClass)) {
groupClasses.remove(successGroupClass);
}
if (!statusClasses.contains(errorStatusClass)) {
statusClasses.add(errorStatusClass);
}
if (!groupClasses.contains(errorGroupClass)) {
groupClasses.add(errorGroupClass);
}
}
};
return {
watch: watchInputs
}
})();
|
JavaScript
| 0 |
@@ -361,16 +361,55 @@
edback';
+%0A const baseStatusClass = 'glyphicon';
%0A%0A //at
@@ -1218,24 +1218,74 @@
element) %7B%0A
+ //if there is a proper sibling, return it%0A
if (
@@ -1398,19 +1398,265 @@
-return null
+//if no sibling was found, create one and return it.%0A var status = document.createElement('span');%0A status.classList.add(baseStatusClass);%0A status.classList.add(formControlFeedbackClass)%0A element.parentNode.appendChild(status);%0A return status
;%0A
|
c7eb40a612d198e26a8bc4276684a2281651401c
|
Convert modal actions to action creators
|
app/redux/modules/modal.js
|
app/redux/modules/modal.js
|
{
type: OPEN_MODAL,
}
{
type: CLOSE_MODAL,
}
{
type: UPDATE_DUCK_TEXT,
newDuckText
}
const initialState = {
duckText: '',
isOpen: false,
}
export default function modal (state = initialState, action) {
switch (action.type) {
case OPEN_MODAL :
return {
...state,
isOpen: true,
}
case CLOSE_MODAL :
return {
duckText: '',
isOpen: false,
}
case UPDATE_DUCK_TEXT :
return {
...state,
duckText: action.newDuckText,
}
default :
return state
}
}
|
JavaScript
| 0.999999 |
@@ -1,57 +1,176 @@
-%7B%0A type: OPEN_MODAL,%0A%7D%0A%0A%7B%0A type: CLOSE_MODAL,%0A%7D%0A%0A%7B%0A
+function openModal () %7B%0A return %7B%0A type: OPEN_MODAL,%0A %7D%0A%7D%0A%0Afunction closeModal () %7B%0A return %7B%0A type: CLOSE_MODAL,%0A %7D%0A%7D%0A%0Afunction updateDuckText () %7B%0A return %7B%0A
ty
@@ -191,16 +191,18 @@
K_TEXT,%0A
+
newDuc
@@ -207,16 +207,20 @@
uckText%0A
+ %7D%0A
%7D%0A%0Aconst
|
981eb204ad7b5be8f07cb4a6f721a3a8fe9b3c54
|
Remove dead code.
|
app/main.js
|
app/main.js
|
exports = module.exports = function(IoC, interpreter, translator, unsealer, sealer, logger) {
var Tokens = require('tokens').Tokens;
var tokens = new Tokens();
return Promise.resolve(tokens)
.then(function(tokens) {
var components = IoC.components('http://i.bixbyjs.org/tokens/Token');
return Promise.all(components.map(function(comp) { return comp.create(); } ))
.then(function(formats) {
formats.forEach(function(format, i) {
var type = components[i].a['@type'];
logger.info('Loaded token type: ' + type);
tokens.format(type, format)
});
})
.then(function() {
return tokens;
});
})
.then(function(tokens) {
// Register token dialects.
return new Promise(function(resolve, reject) {
var components = IoC.components('http://i.bixbyjs.org/tokens/Dialect');
(function iter(i) {
var component = components[i];
if (!component) {
return resolve(tokens);
}
component.create()
.then(function(dialect) {
logger.info('Loaded token dialect: ' + component.a['@type']);
tokens.dialect(component.a['@type'], dialect);
iter(i + 1);
}, function(err) {
// TODO: Print the package name in the error, so it can be found
// TODO: Make the error have the stack of dependencies.
if (err.code == 'IMPLEMENTATION_NOT_FOUND') {
logger.notice(err.message + ' while loading component ' + component.id);
return iter(i + 1);
}
reject(err);
})
})(0);
});
})
.then(function(tokens) {
var api = {};
// TODO: Return tokens directly;
api.createSerializer = tokens.createSerializer.bind(tokens);
api.createDeserializer = tokens.createDeserializer.bind(tokens);
api.createSealer = tokens.createSealer.bind(tokens);
api.createUnsealer = tokens.createUnsealer.bind(tokens);
api.seal = function(claims, recipients, options, cb) {
console.log('SEAL THIS MESSAGE!');
console.log(claims)
var type = options.type || 'application/jwt';
var sealer;
try {
sealer = tokens.createSealer(type);
} catch (ex) {
return cb(ex);
}
sealer.seal(claims, recipients, options, function(err, token) {
console.log('SEALED IT!');
console.log(err)
console.log(token)
if (err) { return cb(err); }
return cb(null, token);
});
};
api.unseal = function(token, options, cb) {
if (typeof options == 'function') {
cb = options;
options = undefined;
}
options = options || {};
var unsealer;
try {
unsealer = tokens.createUnsealer();
} catch (ex) {
return cb(ex);
}
unsealer.unseal(token, options, function(err, claims, conditions, issuer) {
if (err) { return cb(err); }
return cb(null, claims, conditions, issuer);
});
};
/*
api.negotiate = function(formats) {
return negotiator.negotiate(formats);
}
*/
api.cipher = function(ctx, options, cb) {
if (typeof options == 'function') {
cb = options;
options = undefined;
}
options = options || {};
translator.translate(ctx, options, function(err, claims) {
if (err) { return cb(err); }
// Marshal context necessary for sealing the token. This includes this
// that are conceptually "header" information, such as the audience, time
// of issuance, expiration, etc.
options.audience = ctx.audience;
sealer.seal(claims, options, function(err, token) {
if (err) { return cb(err); }
return cb(null, token);
});
});
}
api.decipher = function(token, options, cb) {
if (typeof options == 'function') {
cb = options;
options = undefined;
}
options = options || {};
unsealer.unseal(token, options, function(err, tok) {
if (err) { return cb(err); }
interpreter.interpret(tok, options, function(err, sctx) {
if (err) { return cb(err); }
return cb(null, sctx, tok);
});
});
}
return api;
});
};
exports['@implements'] = 'http://i.bixbyjs.org/tokens';
exports['@singleton'] = true;
exports['@require'] = [
'!container',
'./interpreter',
'./translator',
'./unsealer',
'./sealer',
'http://i.bixbyjs.org/Logger'
];
|
JavaScript
| 0.00001 |
@@ -2155,2534 +2155,546 @@
api.
-seal = function(claims, recipients, options, cb) %7B%0A console.log('SEAL THIS MESSAGE!');%0A console.log(claims)%0A %0A var type = options.type %7C%7C 'application/jwt';%0A %0A %0A var sealer;%0A try %7B%0A sealer = tokens.createSealer(type);%0A %7D catch (ex) %7B%0A return cb(ex);%0A %7D%0A %0A sealer.seal(claims, recipients, options, function(err, token) %7B%0A console.log('SEALED IT!');%0A console.log(err)%0A console.log(token)%0A %0A if (err) %7B return cb(err); %7D%0A return cb(null, token);%0A %7D);%0A %7D;%0A %0A api.unseal = function(token, options, cb) %7B%0A if (typeof options == 'function') %7B%0A cb = options;%0A options = undefined;%0A %7D%0A options = options %7C%7C %7B%7D;%0A %0A var unsealer;%0A try %7B%0A unsealer = tokens.createUnsealer();%0A %7D catch (ex) %7B%0A return cb(ex);%0A %7D%0A %0A unsealer.unseal(token, options, function(err, claims, conditions, issuer) %7B%0A if (err) %7B return cb(err); %7D%0A return cb(null, claims, conditions, issuer);%0A %7D);%0A %7D;%0A %0A %0A /*%0A api.negotiate = function(formats) %7B%0A return negotiator.negotiate(formats);%0A %7D%0A */%0A %0A api.cipher = function(ctx, options, cb) %7B%0A if (typeof options == 'function') %7B%0A cb = options;%0A options = undefined;%0A %7D%0A options = options %7C%7C %7B%7D;%0A %0A translator.translate(ctx, options, function(err, claims) %7B%0A if (err) %7B return cb(err); %7D%0A %0A // Marshal context necessary for sealing the token. This includes this%0A // that are conceptually %22header%22 information, such as the audience, time%0A // of issuance, expiration, etc.%0A options.audience = ctx.audience;%0A %0A sealer.seal(claims, options, function(err, token) %7B%0A if (err) %7B return cb(err); %7D%0A return cb(null, token);%0A %7D);%0A %7D);%0A %7D%0A %0A api.decipher = function(token, options, cb) %7B%0A if (typeof options == 'function') %7B%0A cb = options;%0A options = undefined;%0A %7D%0A options = options %7C%7C %7B%7D;%0A %0A unsealer.unseal(token, options, function(err, tok) %7B%0A if (err) %7B return cb(err); %7D%0A %0A interpreter.interpret(tok, options, function(err, sctx) %7B%0A if (err) %7B return cb(err); %7D%0A return cb(null, sctx, tok);%0A %7D);%0A %7D);%0A %7D
+unseal = function(token, options, cb) %7B%0A if (typeof options == 'function') %7B%0A cb = options;%0A options = undefined;%0A %7D%0A options = options %7C%7C %7B%7D;%0A %0A var unsealer;%0A try %7B%0A unsealer = tokens.createUnsealer();%0A %7D catch (ex) %7B%0A return cb(ex);%0A %7D%0A %0A unsealer.unseal(token, options, function(err, claims, conditions, issuer) %7B%0A if (err) %7B return cb(err); %7D%0A return cb(null, claims, conditions, issuer);%0A %7D);%0A %7D;
%0A %0A
|
e3fb57663ba676e374997e419a29cdcdc301b3d3
|
Update logger.js
|
ideas/logger/logger.js
|
ideas/logger/logger.js
|
var Logger = function($) {
function Logger() {
if (this instanceof Logger) {
var that = this;
var id = 'web-commons-logger';
var $box = $('<div style="display: none; position: absolute; top: 10px; right: 10px; width: 600px; height: 300px; z-index: 9999; border: 1px solid #ddd; font: normal 12px \'Courier New\', Courier, monospace; border: 1px solid #DDD; background: #FFF;"></div>');
$box.css('opacity', 0.93);
var $title = $('<div style="position: relative; text-indent: 5px; line-height: 18px; background: #DDD;"><b>'+id+':</b></div>');
var $close = $('<div style="position: absolute; top: 0; right: 5px;"><b>x</b></div>');
$close.on('click', function() {
that.hide();
that.clear();
});
$title.append($close);
$box.append($title);
var $content = $('<div class="log" style="word-wrap: break-word; word-break: break-all; height: 282px; padding: 0 5px;"></div>');
$content.css('overflow-y', 'scroll');
$box.append($content);
$('body', document).append($box);
this.$box = $box;
}
}
var colors = {
'number': '#099',
'string': '#D14',
'function': '#009926',
'array': '#51A841',
'object': '#444',
'boolean': '#00F',
'undefined': '#444',
'null': '#777',
'property': '#333',
'regexp': '#009926'
};
function stylize(str, useHtml, type) {
return useHtml ? '<b style="color: ' +colors[type] +'">' +str +'</b>' : str;
}
function serialize(any, useHtml) {
var type = $.type(any);
var builder = [];
var res;
switch(type) {
case 'function':
res = ('' + any).replace(/\s+/gim, ' ').replace(/\r?\n/gim, '').match(/.+?\{/gim)+'}';
break;
case 'array':
for (var i = 0, l = any.length; i < l; ++i) {
builder.push(serialize(any[i], useHtml));
}
res = '['+ builder.join(', ') +']';
break;
case 'object':
for (var k in any) {
if (any.hasOwnProperty(k)) {
builder.push(
stylize(k, useHtml, 'property')+': ' +serialize(any[k], useHtml)
);
}
}
res = '{'+ builder.join(', ') +'}';
break;
case 'null':
case 'undefined':
res = type;
break;
case 'string':
res = '"' +any.replace(/(["'\\])/gim, '\\$1') +'"';
break;
case 'number':
case 'boolean':
res = any;
break;
}
return stylize(res, useHtml, type);
}
Logger.prototype = {
log: function(/*args*/) {
this.$box.show();
var args = Array.prototype.slice.call(arguments);
var res = [];
for (var i = 0, l = args.length; i < l; ++i) {
res.push(serialize(args[i], true));
}
var $log = this.$box.children('.log');
$log.append('<p style="margin: 0.5em 0;">' +res.join(', ') +'</p>');
$log.clearQueue();
$log.animate({scrollTop: $log[0].scrollHeight});
},
show: function() {
this.$box.show();
},
hide: function() {
this.$box.hide('fast');
},
clear: function() {
this.$box.children('.log').empty();
}
};
return Logger;
}(jQuery);
|
JavaScript
| 0.000001 |
@@ -194,32 +194,50 @@
none; position:
+ fixed; *position:
absolute; top:
@@ -1973,17 +1973,25 @@
stylize(
-k
+%22'%22+k+%22'%22
, useHtm
@@ -2187,25 +2187,192 @@
%09%09case '
-string':
+regexp':%0A%09%09%09%09any = ('' + any);%0A%09%09%09case 'string': %0A%09%09%09%09any = useHtml ? %0A%09%09%09%09%09any.replace(/%5B%3C%3E%5D/gim, function(k) %7B%0A%09%09%09%09%09%09return '&#' + k.charCodeAt(0) + ';';%0A%09%09%09%09%09%7D) %0A%09%09%09%09%09: any;
%0A%09%09%09%09res
|
1b672091c1bf4ea3713319afefa4b154781c9096
|
Update bookmarklet.js
|
ModOp/bookmarklet.js
|
ModOp/bookmarklet.js
|
(function () { var jsCode=document.createElement('script');jsCode.setAttribute('src', 'https://dl.dropboxusercontent.com/u/13815598/ModOp.js');document.body.appendChild(jsCode);}());
|
JavaScript
| 0.000001 |
@@ -93,18 +93,18 @@
s://
-dl.dropbox
+raw.github
user
@@ -119,18 +119,37 @@
com/
-u/13815598
+AlessandroChecco/ModOp/master
/Mod
@@ -195,8 +195,9 @@
e);%7D());
+%0A
|
f7ff86c9838692affecb2b90aa74a78bf5dcb549
|
Remove a debug line
|
app/main.js
|
app/main.js
|
'use strict';
var app = require('app');
var BrowserWindow = require('browser-window');
var Menu = require("menu");
var env = require('./vendor/electron_boilerplate/env_config');
var menuTemplate = require('./menu_template')(app);
var windowStateKeeper = require('./vendor/electron_boilerplate/window_state');
var shell = require('shell');
var path = require('path');
var electron = require('electron');
var ipc = electron.ipcMain;
var autoUpdater = electron.autoUpdater;
var mainWindow;
// Preserver of the window size and position between app launches.
var mainWindowState = windowStateKeeper('main', {
width: 1000,
height: 600
});
app.on('ready', function () {
mainWindow = new BrowserWindow({
x: mainWindowState.x,
y: mainWindowState.y,
width: mainWindowState.width,
height: mainWindowState.height,
"node-integration": false,
"web-preferences": {
"web-security": false, // remove this line to enable CSP
"preload": path.join(__dirname, 'expose-window-apis.js')
}
});
if (mainWindowState.isMaximized) {
mainWindow.maximize();
}
mainWindow.log = function(text) {
mainWindow.webContents.executeJavaScript('console.log("' + text + '");');
}
mainWindow.log("version: " + app.getVersion());
mainWindow.webContents.on('did-finish-load', function(event) {
this.executeJavaScript("s = document.createElement('script');s.setAttribute('src','localhax://slack-hacks-loader.js'); document.head.appendChild(s);");
});
mainWindow.webContents.on('new-window', function(e, url) {
e.preventDefault();
shell.openExternal(url);
});
mainWindow.loadURL('https://my.slack.com/ssb');
var menu = Menu.buildFromTemplate(menuTemplate);
Menu.setApplicationMenu(menu);
var versionMenuItem = menu.items[0].submenu.items[1];
mainWindow.log("hello from the master process");
var auresponse = function(which, message) {
return function(arg1) {
mainWindow.log("au event: " + which);
mainWindow.log(message);
}
}
if (env.name != "development") {
autoUpdater.setFeedURL("https://obscure-fjord-9578.herokuapp.com/updates?version=" + app.getVersion());
autoUpdater.checkForUpdates();
autoUpdater.on('error', auresponse("error", "update failed"));
autoUpdater.on('checking-for-update', auresponse("checking-for-update", "looking for update"));
autoUpdater.on('update-available', auresponse("update-available", "downloading update"));
autoUpdater.on('update-not-available', auresponse("update-not-available", "latest"));
autoUpdater.on('update-downloaded', auresponse("update-downloaded", "restart to update"));
}
if (env.name === 'development') {
mainWindow.openDevTools();
}
mainWindow.on('close', function () {
mainWindowState.saveState(mainWindow);
});
ipc.on('bounce', function(event, arg) {
app.dock.bounce(arg.type);
});
ipc.on('badge', function(event, arg) {
app.dock.setBadge(arg.badge_text);
});
app.on('zoom-in', function(event, arg) {
mainWindow.webContents.executeJavaScript("host.zoom.increase();")
});
app.on('zoom-out', function(event, arg) {
mainWindow.webContents.executeJavaScript("host.zoom.decrease();")
});
app.on('reset-zoom', function(event, arg) {
mainWindow.webContents.executeJavaScript("host.zoom.reset();")
});
var httpHandler = function(protocol) {
return function(request, callback) {
var url = request.url.split("://", 2)[1]
url = protocol + "://" + url
console.log("got " + url);
return callback( {url: url} );
}
}
electron.protocol.registerHttpProtocol('haxs', httpHandler("https"))
electron.protocol.registerHttpProtocol('hax', httpHandler("http"))
electron.protocol.registerFileProtocol('localhax', function(request, callback) {
var url = request.url.split("://", 2)[1]
callback({path: path.normalize(__dirname + '/localhax/' + url)});
});
});
app.on('window-all-closed', function () {
app.quit();
});
|
JavaScript
| 0.000587 |
@@ -3523,41 +3523,8 @@
url%0A
- console.log(%22got %22 + url);%0A
|
dd39a8d1369994fc2f10a334d2e30e232def67ee
|
Remove radar tooltips for everything but the actual value ring
|
src/interface/report/Results/statistics/Radar.js
|
src/interface/report/Results/statistics/Radar.js
|
import React from 'react';
import PropTypes from 'prop-types';
import { formatNumber } from 'common/format';
const Ring = ({ size, color, style, ...others }) => (
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
width: size,
height: size,
border: `2px solid ${color}`,
borderRadius: '50%',
...style,
}}
{...others}
/>
);
Ring.propTypes = {
size: PropTypes.number.isRequired,
color: PropTypes.string,
style: PropTypes.object,
};
Ring.defaultProps = {
color: '#9c9c9c',
};
const Radar = ({ distance, size, style, playerColor }) => {
const pixelsPerYard = size / 40;
return (
<div
style={{
position: 'relative',
width: size,
height: size,
...style,
}}
>
<Ring size={40 * pixelsPerYard} style={{ opacity: 0.25, background: 'rgba(255, 255, 255, 0.05)' }} data-tip="30-40 yards" />
<Ring size={30 * pixelsPerYard} style={{ opacity: 0.5 }} data-tip="20-30 yards" />
<Ring size={20 * pixelsPerYard} style={{ opacity: 0.75 }} data-tip="10-20 yards" />
<Ring size={10 * pixelsPerYard} style={{ opacity: 1 }} data-tip="0-10 yards" />
<Ring
size={distance * pixelsPerYard}
data-tip={`${formatNumber(distance)} yards`}
color="#f8b700"
style={{
background: 'rgba(248, 183, 0, 0.3)',
boxShadow: '0 0 4px #f8b700',
}}
/>
<div
style={{
position: 'absolute',
top: '50%',
left: '50%',
width: 5,
height: 5,
borderRadius: '50%',
transform: 'translate(-50%, -50%)',
background: playerColor,
pointerEvents: 'none',
}}
/>
</div>
);
};
Radar.propTypes = {
distance: PropTypes.number.isRequired,
size: PropTypes.number,
style: PropTypes.object,
playerColor: PropTypes.string,
};
Radar.defaultProps = {
size: 100,
playerColor: '#f8b700',
};
export default Radar;
|
JavaScript
| 0 |
@@ -937,31 +937,8 @@
' %7D%7D
- data-tip=%2230-40 yards%22
/%3E%0A
@@ -1003,31 +1003,8 @@
5 %7D%7D
- data-tip=%2220-30 yards%22
/%3E%0A
@@ -1070,31 +1070,8 @@
5 %7D%7D
- data-tip=%2210-20 yards%22
/%3E%0A
@@ -1134,30 +1134,8 @@
1 %7D%7D
- data-tip=%220-10 yards%22
/%3E%0A
|
22f9901f4f3479bbe7883b9fc13ec040ae03aa75
|
Disable debug informations
|
app/main.js
|
app/main.js
|
import angular from 'angular'
import register from './utils/register'
import hrRes from 'angular-hy-res'
import formly from 'angular-formly'
import formlyBootstrap from 'angular-formly-templates-bootstrap'
import angularAnimate from 'angular-animate'
import 'ng-promise-status'
import './directives/progressBar/progressBar'
import applicationDirective from './directives/application/application'
import applicationHeaderDirective from './directives/applicationHeader/applicationHeader'
import pollsList from './directives/pollsList/pollsList'
import pollsService from './services/pollsService'
import pollDirective from './directives/poll/poll'
import sirenActionDirective from './directives/sirenAction/sirenAction'
angular.module('pollsClient', [
'hrSiren',
'hrLinkHeader',
hrRes,
formly,
formlyBootstrap,
angularAnimate,
'ngPromiseStatus',
'isteven-omni-bar'
])
.constant('apiLocation', 'https://polls.apiblueprint.org/')
//.constant('apiLocation', 'http://private-851d-pollshypermedia.apiary-mock.com/')
register('pollsClient')
.directive('application', applicationDirective)
.directive('pollsList', pollsList)
.directive('applicationHeader', applicationHeaderDirective)
.directive('poll', pollDirective)
.directive('sirenAction', sirenActionDirective)
.service('pollsService', pollsService)
|
JavaScript
| 0.000002 |
@@ -1038,16 +1038,150 @@
k.com/')
+%0A .config(%5B'$compileProvider', function ($compileProvider) %7B%0A // disable debug info%0A $compileProvider.debugInfoEnabled(false);%0A%7D%5D);
%0A%0Aregist
|
8c2fa813ade4fe09fa58c40307964030f51ab637
|
Customize for handling years
|
simpleshelf/_attachments/code/models/byyearspinelist.js
|
simpleshelf/_attachments/code/models/byyearspinelist.js
|
/**
* ByYearSpineList: SpineList extended for holding Spines by year
*/
window.ByYearSpineList = window.SpineList.extend({
model: Spine, // same
initialize: function(models, options) {
// Backbone.Model.prototype.set.call(this, attributes, options);
window.SpineList.prototype.initialize.call(this, models, options);
// additional bindings
_.bindAll(this, 'getAvailableYears');
},
url: function(){
return '/simpleshelf/_design/simpleshelf/_view/by_year'
},
parse: function(response){
var results = [], row, values;
if (response.rows){
for (var x = 0; x < response.rows.length; x++){
row = response.rows[x];
values = {
'_rev': row.value._rev,
'id': row.id,
'latestDateFinished': row.value.latestDateFinished,
'title': row.value.title,
'year': row.key
};
results.push(values);
}
}
return results;
},
/**
* Return sorted list of years with data
*/
getAvailableYears: function(){
var allYears = this.map(function(model){
return model.get('year');
});
// sort, make uniq
allYears.sort();
return _.uniq(allYears, true);
}
});
|
JavaScript
| 0 |
@@ -572,18 +572,24 @@
, values
+, year
;%0A
-
@@ -708,16 +708,145 @@
ows%5Bx%5D;%0A
+ year = parseInt(row.key);%0A if (_.isNaN(year))%7B%0A year = null;%0A %7D%0A
@@ -1068,17 +1068,20 @@
-%09
+
'year':
row.
@@ -1076,23 +1076,20 @@
'year':
-row.key
+year
%0A
@@ -1439,16 +1439,16 @@
sort();%0A
-
@@ -1478,16 +1478,268 @@
true);%0A
+ %7D,%0A%0A /**%0A * Return list of spines within given year%0A */%0A getSpinesByYear: function(year)%7B%0A return this.filter(function(model)%7B%0A if (model.get('year') == year) %7B%0A return true;%0A %7D%0A %7D);%0A
%7D%0A%0A%7D
|
41a3376fdb9dd9a4b6cf7c003e60eb13270387ab
|
Move IsAndroid and IsIOS to storage
|
src/js/containers/ImportAccount/ImportAccount.js
|
src/js/containers/ImportAccount/ImportAccount.js
|
import React from "react"
import { connect } from "react-redux"
import { ImportAccountView, LandingPage } from '../../components/ImportAccount'
import {
ImportKeystore, ImportByDevice, ImportByPrivateKey,
ErrorModal, ImportByMetamask,
ImportByDeviceWithLedger, ImportByDeviceWithTrezor
} from "../ImportAccount"
import { setIsAndroid, setIsIos } from "../../actions/globalActions"
import { getTranslate } from 'react-localize-redux'
import { importAccountMetamask } from "../../actions/accountActions"
import BLOCKCHAIN_INFO from "../../../../env"
import Web3Service from "../../services/web3"
@connect((store, props) => {
var tokens = store.tokens.tokens
var supportTokens = []
Object.keys(tokens).forEach((key) => {
supportTokens.push(tokens[key])
})
return {
...store.account,
translate: getTranslate(store.locale),
isVisitFirstTime: store.global.isVisitFirstTime,
translate: getTranslate(store.locale),
termOfServiceAccepted: store.global.termOfServiceAccepted,
ethereum: store.connection.ethereum,
tokens: supportTokens,
screen: props.screen,
tradeType: props.tradeType,
global: store.global
}
})
export default class ImportAccount extends React.Component {
constructor() {
super()
this.state = {
isOpen: false
}
}
componentDidMount = () => {
var swapPage = document.getElementById("swap-app");
swapPage.className = swapPage.className === "" ? "no-min-height" : swapPage.className + " no-min-height";
var web3Service = new Web3Service();
if (true) {
if (true) {
this.props.dispatch(setIsIos(true));
} else if (isMobile.Android()) {
this.props.dispatch(setIsAndroid(true));
}
}
if (this.props.termOfServiceAccepted){
if (web3Service.isHaveWeb3()) {
var walletType = web3Service.getWalletType()
if (walletType !== "metamask") {
this.props.dispatch(importAccountMetamask(web3Service, BLOCKCHAIN_INFO.networkId,
this.props.ethereum, this.props.tokens, this.props.screen, this.props.translate, walletType))
}
}
}
}
getAppDownloadHtml(downloadLink) {
return (<div className="download-mobile">
<div className="mobile-left">
<div className="mobile-icon"></div>
<div className="mobile-content">
<div className="mobile-title">Coinbase Wallet</div>
<div className="mobile-desc">Ethereum Wallet & DApp Browser</div>
</div>
</div>
<a href={downloadLink} className="mobile-btn" target="_blank">
{this.props.translate("download") || "Download"}
</a>
</div>)
}
render() {
var content;
if (!this.props.termOfServiceAccepted) {
content = <LandingPage translate={this.props.translate} tradeType={this.props.tradeType}/>
} else {
if (this.props.global.isIos){
content = this.getAppDownloadHtml("https://itunes.apple.com/us/app/coinbase-wallet/id1278383455?mt=8");
} else if (this.props.global.isAndroid) {
content = this.getAppDownloadHtml("https://play.google.com/store/apps/details?id=org.toshi&hl=en");
} else {
content = (
<ImportAccountView
firstKey={<ImportByMetamask />}
secondKey={<ImportKeystore />}
thirdKey={<ImportByDeviceWithTrezor />}
fourthKey={<ImportByDeviceWithLedger />}
fifthKey={<ImportByPrivateKey />}
errorModal={<ErrorModal />}
translate={this.props.translate}
/>
)
}
}
return (
<div id="landing_page">{content}</div>
)
}
}
|
JavaScript
| 0.000004 |
@@ -1556,30 +1556,61 @@
if (
-true) %7B%0A if (true
+!web3Service.isHaveWeb3()) %7B%0A if (isMobile.iOS()
) %7B%0A
|
5fe7e4d51eebb52f13f56f39b0248737906b862d
|
Fix blundered callback ordering
|
app/models/calibration.js
|
app/models/calibration.js
|
var mysql = require('mysql');
var connectionParams = require('../../config/connectionParams');
var pool = mysql.createPool(connectionParams);
/*
Creates a Fossil object from a database row
*/
function Fossil(databaseRow) {
// From Link_CalibrationFossil and View_Fossils
this.id = databaseRow['FossilID'];
this.collection = databaseRow['CollectionAcro'];
this.collectionNumber = databaseRow['CollectionNumber'];
this.shortReference = databaseRow['ShortName'];
this.fullReference = databaseRow['FullReference'];
this.stratUnit = databaseRow['Stratum'];
this.maxAge = databaseRow['MaxAge'];
this.maxAgeType = databaseRow['MaxAgeType'];
this.maxAgeTypeDetails = databaseRow['MaxAgeTypeOtherDetails'];
this.minAge = databaseRow['MinAge'];
this.minAgeType = databaseRow['MinAgeType'];
this.minAgeTypeDetails = databaseRow['MinAgeTypeOtherDetails'];
this.locationRelativeToNode= databaseRow['FossilLocationRelativeToNode'];
}
/*
Creates a TipPair object from a database row
*/
function TipPair(databaseRow) {
}
/*
Creates a calibration object from a database row
*/
function Calibration(databaseRow) {
// Properties to fill
this.nodeName = databaseRow['NodeName'];
this.nodeMinAge = databaseRow['MinAge'];
this.nodeMaxAge = databaseRow['MaxAge'];
this.calibrationReference = databaseRow['FullReference'];
this.fossils = [];
// fossils
this.tipPairs = [];
// tip_pairs
// Tip 1 Name
// Tip 2 Name
// “Distance” of root from tip(s)?
}
function Calibrations() {
var TABLE_NAME = 'View_Calibrations';
function query(queryString, queryParams, callback) {
return pool.query(queryString, queryParams, callback);
}
// Fetches a calibration and populates its fossils
function getCalibration(calibrationId, callback) {
fetchCalibration(calibrationId, function(calibration, err) {
if(err) {
callback(null, err);
} else {
// attach fossils
fetchFossils(calibrationId, function (fossils, err) {
if (err) {
callback(null, err);
} else {
calibration.fossils = fossils;
callback(calibration);
}
});
// tips
}
});
}
// Fetch a single calibration from the database by ID and produce a single object
function fetchCalibration(calibrationId, callback) {
var queryString = 'SELECT * FROM ' + TABLE_NAME + ' WHERE CalibrationID = ?';
query(queryString, [calibrationId], function(err, results) {
if(err) {
callback(null,err);
} else {
var calibrationResult = new Calibration(results[0]);
callback(calibrationResult);
}
});
}
// Fetch Fossils for a calibration from the database and produce a list of fossils
function fetchFossils(calibrationId, callback) {
var queryString = 'SELECT F.*, L.* from Link_CalibrationFossil L, View_Fossils F WHERE L.CalibrationId = ? AND L.FossilID = F.FossilID';
query(queryString, [calibrationId], function(err, results) {
if(err) {
callback(null,err);
} else {
var fossilResults = results.map(function(result) { return new Fossil(result); });
callback(fossilResults);
}
});
}
this.findById = function(calibrationId, callback) {
getCalibration(calibrationId, callback);
};
this.findByFilter = function(params, callback) {
var queryString = 'SELECT CalibrationID FROM ' + TABLE_NAME + ' WHERE minAge > ? AND maxAge < ?';
var calibrationResults = [];
var success = function(result) {
callback(result);
};
var failed = function(err) {
callback(null, err);
};
query(queryString, [params.min, params.max], function(err, results) {
if(err) {
failed(err);
return;
}
results.forEach(function(result, index, array) {
var calibrationId = result['CalibrationID'];
getCalibration(calibrationId, function(calibration, err) {
if(err) {
failed(err);
return;
}
calibrationResults.push(calibration);
// If this is the last one, finish everything up
// This is done because mysql results are async
// Could use the async node module to help a little bit, but this works for now
if(index == array.length - 1) {
success(calibrationResults);
return;
}
});
});
});
};
}
module.exports = new Calibrations();
|
JavaScript
| 0.00003 |
@@ -1562,16 +1562,56 @@
tions';%0A
+ // this callback is err, rows, fields%0A
functi
@@ -1864,32 +1864,37 @@
ionId, function(
+err,
calibration, err
@@ -1880,37 +1880,32 @@
err, calibration
-, err
) %7B%0A if(err
@@ -1917,38 +1917,32 @@
callback(
-null,
err);%0A %7D el
@@ -2022,20 +2022,20 @@
on (
+err,
fossils
-, err
) %7B%0A
@@ -2068,38 +2068,32 @@
callback(
-null,
err);%0A
@@ -2157,32 +2157,38 @@
callback(
+null,
calibration);%0A
@@ -3737,36 +3737,36 @@
%5D, function(
-err,
results
+, err
) %7B%0A if
@@ -3963,32 +3963,37 @@
ionId, function(
+err,
calibration, err
@@ -3987,21 +3987,16 @@
ibration
-, err
) %7B%0A
|
a663d8c5d68fd12eff3583e5c768838d96dc2dae
|
switch confirm text around
|
src/js/controllers/tournaments/inProgressCtrl.js
|
src/js/controllers/tournaments/inProgressCtrl.js
|
import site from '../../app';
site.filter('inRound', () => (items, round) => _.filter(items, (i) => i.id.r === round));
site.filter('inSection', () => (items, section) => _.filter(items, (i) => i.id.s === section));
site.controller('inProgressController', ($scope, SidebarManagement, CurrentPlayerBucket, UserStatus, TournamentStatus, FirebaseURL, $firebaseObject, $state, $stateParams, $mdDialog) => {
SidebarManagement.hasSidebar = false;
$scope.url = window.location.href;
$scope.toCharacter = (round) => {
let str = '';
while(round > 0) {
const modulo = (round-1)%26;
str = String.fromCharCode(65+modulo) + str;
round = Math.round((round - modulo) / 26);
}
return str;
};
$scope.loadTournament = (ref, makeNew = false) => {
$scope.bucket = ref.players;
const oldScores = _.cloneDeep(ref.trn);
$scope.trn = ref.trn && !makeNew ? Duel.restore($scope.bucket.length, ref.options, ref.trn) : new Duel($scope.bucket.length, ref.options);
if(ref.trn && !makeNew) {
_.each(oldScores, match => {
const existingMatch = _.findWhere($scope.trn.matches, { id: match.id });
if(!existingMatch) return;
existingMatch.score = _.clone(match.score);
});
}
};
$scope.ref = $firebaseObject(new Firebase(`${FirebaseURL}/users/${atob($stateParams.userId)}/players/${$stateParams.setId}/tournaments/${$stateParams.tournamentId}`));
$scope.reset = (ev) => {
const confirm = $mdDialog.confirm()
.title('Would you like to reset this bracket?')
.content('This is a permanent, irreversible action.')
.targetEvent(ev)
.ok('Yes')
.cancel('No');
$mdDialog.show(confirm).then(() => {
$scope.loadTournament($scope.ref, true);
$scope.ref.$save();
});
};
$scope.toPDF = () => {
const pdf = new jsPDF();
pdf.fromHTML($('.duel-area').get(0), 15, 15);
};
$scope.savePublicity = () => {
$scope.ref.$save();
};
$scope.ref.$watch(() => $scope.loadTournament($scope.ref));
$scope.ref.$loaded().then(() => {
$scope.tournamentName = $scope.ref.name;
$scope.loadTournament($scope.ref);
const horizMatches = _.max($scope.trn.matches, 'id.r').id.r; // these start at 1 I guess.
const totalSections = _.max($scope.trn.matches, 'id.s').id.s; // get the highest section
$scope.maxMatches = new Array(horizMatches);
$scope.numMatchesPerSection = _.map(new Array(totalSections), () => 0);
$scope.nextMatch = $scope.trn.right;
$scope.matchesLeft = () => _.reduce($scope.trn.matches, ((prev, m) => prev + ($scope.noRender(m) ? 0 : ~~!m.m)), 0);
const idMap = {};
$scope.getIdForMatch = (id) => {
const strId = JSON.stringify(id);
if(idMap[strId]) return idMap[strId];
return idMap[strId] = ++$scope.numMatchesPerSection[id.s-1];
};
$scope.getName = (idx) => {
const user = $scope.bucket[idx];
if(!user) return '-';
if(user.alias) return user.alias;
return user.name;
};
$scope.invalidMatch = (match) => !$scope.trn.isPlayable(match);
$scope.noRender = (match) => _.any(match.p, p => p === -1);
$scope.scoresEqual = (match) => match.score && match.score.length > 1 ? match.score.length !== _.compact(_.uniq(match.score)).length : true;
$scope.confirmScore = (match) => {
$scope.trn.score(match.id, _.map(match.score, i => +i));
$scope.save();
};
$scope.save = () => {
$scope.ref.trn = $scope.trn.state;
if($scope.trn.isDone()) $scope.ref.status = TournamentStatus.COMPLETED;
$scope.ref.$save();
};
});
});
|
JavaScript
| 0 |
@@ -1501,16 +1501,48 @@
.title('
+Reset Bracket')%0A .content('
Would yo
@@ -1570,35 +1570,17 @@
bracket?
-')%0A .content('
+
This is
|
89717854256d1d173dfc5ec8017b1676308ff0e1
|
Fix jshint errors.
|
app/scripts/modal.js
|
app/scripts/modal.js
|
/* foundation modal tweaks
*/
// add a class on the body, when the modal is opened
// so we can set position: fixed on the background.
$(document).on('opened', '[data-reveal]', function () {
$(document.body).addClass('modal-opened');
});
$(document).on('closed', '[data-reveal]', function () {
$(document.body).removeClass('modal-opened');
});
|
JavaScript
| 0.000003 |
@@ -25,16 +25,49 @@
ks%0A */%0A%0A
+(function() %7B%0A 'use strict';%0A%0A
// add a
@@ -111,16 +111,18 @@
opened%0A
+
// so we
@@ -165,16 +165,18 @@
ground.%0A
+
$(docume
@@ -215,32 +215,34 @@
, function () %7B%0A
+
$(document.bod
@@ -274,13 +274,17 @@
');%0A
+
%7D);%0A%0A
+
$(do
@@ -335,16 +335,18 @@
on () %7B%0A
+
$(docu
@@ -385,12 +385,20 @@
ened');%0A
+
%7D);%0A
+%7D)();%0A
|
41cf3e9c561167b6ed677f305542d54b2811dbce
|
Remove unused vars
|
app/views/explore.js
|
app/views/explore.js
|
'use strict'
let component = require('omniscient')
let immutable = require('immutable')
let S = require('underscore.string.fp')
let logger = require('js-logger-aknudsen').get('explore')
let R = require('ramda')
let h = require('react-hyperscript')
let React = require('react')
let ReactDOM = require('react-dom')
let Packery = React.createFactory(require('react-packery-component')(React))
let FocusingInput = require('./focusingInput')
let ajax = require('../ajax')
let router = require('../router')
if (__IS_BROWSER__) {
require('./explore.styl')
}
let getQualifiedId = (project) => {
return `${project.owner}/${project.projectId}`
}
let setSearch = (cursor, text) => {
logger.debug(`Setting search to '${text}'`)
cursor.cursor('explore').set('search', text)
}
let createProjectElement = (cursor, i) => {
let project = cursor.toJS()
let thumbnail = !R.isEmpty(project.pictures || []) ? project.pictures[0].exploreUrl :
'/images/revox-reel-to-reel-resized.jpg'
return h('.project-item', {
key: i,
'data-id': getQualifiedId(project),
}, [
h('a', {href: `/u/${project.owner}/${project.projectId}`,}, [
h('.project-item-header', [
h('.project-item-title', project.title),
h('.project-item-author', project.owner),
]),
h('img.project-item-image', {src: thumbnail,}),
]),
])
}
let Results = component('Results', (cursor) => {
let exploreCursor = cursor.cursor('explore')
if (exploreCursor.get('isSearching')) {
return h('p', 'Searching...')
} else {
let projectsCursor = exploreCursor.cursor('projects')
logger.debug(`Got ${projectsCursor.toJS().length} search results`)
let projectElems = projectsCursor.map(createProjectElement).toJS()
return projectsCursor.isEmpty() ? h('p', 'No projects were found, please try again.') :
Packery({
className: 'projects-container',
options: {
itemSelector: '.project-item',
},
}, projectElems)
}
})
let searchAsync = (cursor, query) => {
return ajax.getJson('/api/search', {query: query || '',})
.then((projects) => {
logger.debug(`Searching succeeded`)
return projects
}, (reason) => {
logger.warn('Searching failed:', reason)
return []
})
}
let performSearch = (cursor) => {
let exploreCursor = cursor.cursor('explore')
let query = cursor.getIn([`explore`, `search`,])
let searchString = encodeURIComponent(query.replace(' ', '+'))
if (S.isBlank(searchString)) {
router.goTo(`/`)
} else {
router.goTo(`/?q=${searchString}`)
}
}
let SearchBox = component('SearchBox', function (cursor) {
let searchQuery = cursor.cursor('explore').get('search')
logger.debug(`SearchBox rendering, query: '${searchQuery}'`)
let hasSearchQuery = !S.isBlank(searchQuery)
return h('.search-box', [
h('span#explore-do-search.search-icon.icon-search.muted', {
onClick: R.partial(performSearch, [cursor,]),
}),
FocusingInput({
id: 'explore-search-input',
value: searchQuery,
placeholder: 'Search MuzHack',
ref: 'search',
refName: 'search',
onChange: (event) => {
let text = event.currentTarget.value
logger.debug(`Search input detected`)
setSearch(cursor, text)
},
onEnter: R.partial(performSearch, [cursor,]),
}),
hasSearchQuery ? h('span#explore-clear-search.clear-icon.icon-cross.muted', {
onClick: () => {
logger.debug('Clear search clicked')
setSearch(cursor, '')
let node = ReactDOM.findDOMNode(this.refs.search)
logger.debug('Giving focus to search input:', node)
node.select()
},
}) : null,
])
})
module.exports = {
createState: () => {
return immutable.fromJS({
search: '',
projects: [
],
})
},
loadData: (cursor, params, queryParams) => {
logger.debug(`Loading projects`)
let searchString = queryParams.q || ''
return searchAsync(cursor, searchString)
.then((projects) => {
return {
explore: {
isSearching: false,
search: searchString,
projects,
},
}
})
},
render: (cursor) => {
let exploreCursor = cursor.cursor('explore')
// logger.debug(`Explore state:`, exploreCursor.toJS())
return h('.pure-g', [
h('.pure-u-1', [
h('#explore-pad', [
SearchBox(cursor),
Results(cursor),
]),
]),
])
},
}
|
JavaScript
| 0.000001 |
@@ -2299,55 +2299,8 @@
%3E %7B%0A
- let exploreCursor = cursor.cursor('explore')%0A
le
@@ -4159,57 +4159,8 @@
%3E %7B%0A
- let exploreCursor = cursor.cursor('explore')%0A
|
96bcfc188f26b26a9133695520a1b5251786fe9c
|
Add not started boolean to approvalStates array
|
src/main/web/florence/js/functions/_viewCollections.js
|
src/main/web/florence/js/functions/_viewCollections.js
|
function viewCollections(collectionId) {
var result = {};
var pageDataRequests = []; // list of promises - one for each ajax request.
pageDataRequests.push(
$.ajax({
url: "/zebedee/collections",
type: "get",
success: function (data) {
result.data = data;
},
error: function (jqxhr) {
handleApiError(jqxhr);
}
})
);
pageDataRequests.push(
getTeams(
success = function (team) {
result.team = team;
},
error = function (response) {
handleApiError(response);
}
)
);
$.when.apply($, pageDataRequests).then(function () {
var response = [], teams = [], date = "";
$.each(result.data, function (i, collection) {
var approvalStates = {inProgress: false, thrownError: false, completed: false};
if (collection.approvalStatus != "COMPLETE") {
// Set publish date
if (!collection.publishDate) {
date = '[manual collection]';
} else if (collection.publishDate && collection.type === 'manual') {
date = StringUtils.formatIsoDateString(collection.publishDate) + ' [rolled back]';
} else {
date = StringUtils.formatIsoDateString(collection.publishDate);
}
// Set approval state
switch (collection.approvalStatus) {
case (undefined): {
break;
}
case ('IN_PROGRESS'): {
approvalStates.inProgress = true;
break;
}
case ('COMPLETE'): {
approvalStates.completed = true;
break;
}
case ('ERROR'): {
approvalStates.thrownError = true;
break;
}
}
response.push({id: collection.id, name: collection.name, date: date, approvalState: approvalStates});
}
});
var isDataVis = false;
if (Florence.Authentication.userType() === "DATA_VISUALISATION") {
isDataVis = true;
}
var collectionsHtml = templates.collectionList({response: response, teams: result.team.teams, isDataVis: isDataVis});
$('.section').html(collectionsHtml);
if (collectionId) {
viewCollectionDetails(collectionId, $('.js-selectable-table tr[data-id="' + collectionId + '"]'));
}
$('.js-selectable-table tbody tr').click(function () {
var collectionId = $(this).attr('data-id');
viewCollectionDetails(collectionId, $(this));
});
$("#team-tag").tagit({
singleField: true,
singleFieldNode: $('#team-input')
});
$('.ui-autocomplete-input').hide();
$('select#team').change(function () {
$('#team-tag').tagit('createTag', $("#team option:selected").text());
});
$('#team-input').change(function () {
teams = $('#team-input').val().split(',');
//After creating the array tagit leaves an empty string if all elements are removed
if (teams.length === 1 && teams[0] === "") {
teams = [];
}
});
$('form input[type=radio]').click(function () {
if ($(this).val() === 'manual') {
$('#scheduledPublishOptions').hide();
} else if ($(this).val() === 'scheduled') {
$('#scheduledPublishOptions').show();
} else if ($(this).val() === 'custom') {
$('#customScheduleOptions').show();
$('#releaseScheduleOptions').hide();
} else if ($(this).val() === 'release') {
$('#customScheduleOptions').hide();
$('#releaseScheduleOptions').show();
}
});
$(function () {
var today = new Date();
$('#date').datepicker({
minDate: today,
dateFormat: 'dd/mm/yy',
constrainInput: true
});
});
$('.btn-select-release').on("click", function (e) {
e.preventDefault();
viewReleaseSelector();
});
$('.form-create-collection').submit(function (e) {
e.preventDefault();
createCollection(teams);
});
});
}
|
JavaScript
| 0.000003 |
@@ -944,16 +944,35 @@
mpleted:
+ false, notStarted:
false%7D;
@@ -1658,32 +1658,187 @@
%7D%0A
+ case ('NOT_STARTED'): %7B%0A approvalStates.notStarted = true;%0A break;%0A %7D%0A
|
19251287b3eb05f6dc1fa3f57b4f60f912428083
|
Switch to notmyidea
|
scripts/reducers/homepage.js
|
scripts/reducers/homepage.js
|
const INITIAL_STATE = {
title: "",
server: "https://leplatrem-happiness.herokuapp.com/v1",
bucket: "happiness"
};
export default function homepage(state=INITIAL_STATE, action) {
return state;
}
|
JavaScript
| 0.000006 |
@@ -53,41 +53,27 @@
s://
-leplatrem-happiness.herokuapp.com
+kinto.notmyidea.org
/v1%22
|
f7052544340875279dc3ec8e4fa6e95ca3a97c1d
|
Change function name.
|
app/sync.js
|
app/sync.js
|
/**
* Copyright 2016 Google Inc. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
function prefetchArticles() {
clients.matchAll({includeUncontrolled: true, type: 'window'}).then(function(clients){
for (var i = 0; i < clients.length; i++) {
var anchorLocation = clients[i].url.indexOf('#');
var anchorName = clients[i].url.slice(anchorLocation + 1);
if (anchorLocation != -1) {
fetch('https://www.reddit.com/r/' + anchorName + '.json')
.then(function(response) {
return response.json();
}).then(function(json) {
json.data.children.forEach(function(child) {
if (child.data.domain == ('self.' + anchorName)) {
var jsonUrl = child.data.url.slice(0, -1) + '.json';
var req = new Request(jsonUrl, {mode: 'cors'});
caches.open('articles').then(function(aCache) {
aCache.add(req);
})
}
})
})
}
}
}).catch(function(err){
console.log("Didn't work. Here's what happened: " + err);
})
}
self.addEventListener('sync', function(event) {
//console.log("event: " + event);
if (event.tag == 'articles') {
//console.log("Inside wait.");
prefetchArticles();
}
});
|
JavaScript
| 0.000002 |
@@ -621,19 +621,16 @@
unction
-pre
fetchArt
@@ -1448,16 +1448,17 @@
ion(err)
+
%7B%0A%09%09cons
@@ -1519,16 +1519,17 @@
%09%7D)%0A %7D%0A%0A
+%0A
self.ad
@@ -1575,113 +1575,41 @@
%7B%0A %09
-//console.log(%22event: %22 + event);%0A %09if (event.tag == 'articles') %7B%0A%09%09//console.log(%22Inside wait.%22);%0A%09%09pre
+if (event.tag == 'articles') %7B%0A%09%09
fetc
@@ -1624,15 +1624,16 @@
s();%0A %09%7D
+
%0A %7D);%0A%0A
|
ec4f4caf2753d7a4061f111ef1506087799e6b4a
|
Update costing formula
|
app/util.js
|
app/util.js
|
export function getProjectCost (project) {
return project.cost.capital + project.cost.operating * ATF_CONFIG.budget.years
}
export function formatCost (cost) {
if(cost < 1000000000) {
return '$' + Math.round(cost/1000000) + 'M'
}
return '$' + Math.round(cost/100000000)/10 + 'B'
}
|
JavaScript
| 0.000001 |
@@ -1,24 +1,59 @@
+import haversine from 'haversine'%0A%0A
export function getProje
@@ -71,16 +71,91 @@
ject) %7B%0A
+ if(project.cost && (project.cost.capital %7C%7C project.cost.operating)) %7B%0A
return
@@ -231,175 +231,986 @@
ars%0A
-%7D%0A%0Aexport function formatCost (cost) %7B%0A if(cost %3C 1000000000) %7B%0A return '$' + Math.round(cost/1000000) + 'M'%0A %7D%0A return '$' + Math.round(cost/100000000)/10 + 'B'%0A
+ %7D%0A switch(project.category) %7B%0A case 'lrt':%0A case 'rail':%0A case 'rapid_bus':%0A const dist = getProjectLength(project.geojson.geometry.coordinates)%0A const modeCosts = ATF_CONFIG.budget%5Bproject.category%5D%0A const cap = dist * modeCosts.capital_cost_per_mile * modeCosts.local_capital_share%0A const ops = dist * modeCosts.operating_cost_per_mile * ATF_CONFIG.budget.years * modeCosts.local_operating_share%0A return cap + ops%0A %7D%0A%0A return 0%0A%7D%0A%0Aexport function formatCost (cost) %7B%0A if(cost %3C 1000000000) %7B%0A return '$' + Math.round(cost/1000000) + 'M'%0A %7D%0A return '$' + Math.round(cost/100000000)/10 + 'B'%0A%0A%7D%0A%0Afunction getProjectLength (coords) %7B%0A let dist = 0%0A for(let i = 0; i %3C coords.length - 1; i++) %7B%0A const start = %7B%0A longitude: coords%5Bi%5D%5B0%5D,%0A latitude: coords%5Bi%5D%5B1%5D%0A %7D%0A const end = %7B%0A longitude: coords%5Bi+1%5D%5B0%5D,%0A latitude: coords%5Bi+1%5D%5B1%5D%0A %7D%0A dist += haversine(start, end, %7Bunit: 'mi'%7D)%0A %7D%0A return dist
%0A%7D%0A
|
f5ac5105e38ce7a3721d852342ea6c265630f057
|
Revert "Add multiple domains separated by whitespace"
|
scripts/pi-hole/js/list.js
|
scripts/pi-hole/js/list.js
|
// IE likes to cache too much :P
$.ajaxSetup({cache: false});
// Get PHP info
var token = $("#token").html();
var listType = $("#list-type").html();
var fullName = listType === "white" ? "Whitelist" : "Blacklist";
function sub(index, entry) {
var domain = $("#"+index);
domain.hide("highlight");
$.ajax({
url: "scripts/pi-hole/php/sub.php",
method: "post",
data: {"domain":entry, "list":listType, "token":token},
success: function(response) {
if(response.length !== 0){
return;
}
domain.remove();
},
error: function(jqXHR, exception) {
alert("Failed to remove the domain!");
}
});
}
function refresh(fade) {
var list = $("#list");
if(fade) {
list.fadeOut(100);
}
$.ajax({
url: "scripts/pi-hole/php/get.php",
method: "get",
data: {"list":listType},
success: function(response) {
list.html("");
var data = JSON.parse(response);
if(data.length === 0) {
list.html("<div class=\"alert alert-info\" role=\"alert\">Your " + fullName + " is empty!</div>");
}
else {
data.forEach(function (entry, index) {
list.append(
"<li id=\"" + index + "\" class=\"list-group-item clearfix\">" + entry +
"<button class=\"btn btn-danger btn-xs pull-right\" type=\"button\">" +
"<span class=\"glyphicon glyphicon-trash\"></span></button></li>"
);
// Handle button
$("#list #"+index+"").on("click", "button", function() {
sub(index, entry);
});
});
}
list.fadeIn("fast");
},
error: function(jqXHR, exception) {
$("#alFailure").show();
}
});
}
window.onload = refresh(false);
function add(domain) {
if(domain.length === 0){
return;
}
var alInfo = $("#alInfo");
var alSuccess = $("#alSuccess");
var alFailure = $("#alFailure");
alInfo.show();
alSuccess.hide();
alFailure.hide();
$.ajax({
url: "scripts/pi-hole/php/add.php",
method: "post",
data: {"domain":domain, "list":listType, "token":token},
success: function(response) {
if (response.indexOf("not a valid argument") >= 0 ||
response.indexOf("is not a valid domain") >= 0) {
alFailure.show();
alFailure.delay(1000).fadeOut(2000, function() {
alFailure.hide();
});
alInfo.delay(1000).fadeOut(2000, function() {
alInfo.hide();
});
} else {
alSuccess.show();
alSuccess.delay(1000).fadeOut(2000, function() {
alSuccess.hide();
});
alInfo.delay(1000).fadeOut(2000, function() {
alInfo.hide();
});
refresh(true);
}
},
error: function(jqXHR, exception) {
alFailure.show();
alFailure.delay(1000).fadeOut(2000, function() {
alFailure.hide();
});
alInfo.delay(1000).fadeOut(2000, function() {
alInfo.hide();
});
}
});
$("#domain").val("");
}
function handleAdd() {
$("#domain").val().split(/\s+/).forEach(function (domain) {
add(domain);
});
}
// Handle enter button for adding domains
$(document).keypress(function(e) {
if(e.which === 13 && $("#domain").is(":focus")) {
// Enter was pressed, and the input has focus
handleAdd();
}
});
// Handle buttons
$("#btnAdd").on("click", function() {
handleAdd();
});
$("#btnRefresh").on("click", function() {
refresh(true);
});
// Handle hiding of alerts
$(function(){
$("[data-hide]").on("click", function(){
$(this).closest("." + $(this).attr("data-hide")).hide();
});
});
|
JavaScript
| 0 |
@@ -2024,25 +2024,50 @@
ion add(
-domain) %7B
+) %7B%0A var domain = $(%22#domain%22);
%0A if(
@@ -2073,16 +2073,22 @@
(domain.
+val().
length =
@@ -2396,16 +2396,22 @@
%22:domain
+.val()
, %22list%22
@@ -3105,32 +3105,60 @@
%7D);%0A
+ domain.val(%22%22);%0A
refr
@@ -3503,154 +3503,11 @@
%7D);%0A
- $(%22#domain%22).val(%22%22);%0A%7D%0A%0Afunction handleAdd() %7B%0A $(%22#domain%22).val().split(/%5Cs+/).forEach(function (domain) %7B%0A add(domain);%0A %7D);%0A%7D
+%7D%0A%0A
%0A%0A//
@@ -3693,31 +3693,25 @@
cus%0A
-handleA
+a
dd();%0A %7D%0A
@@ -3779,15 +3779,9 @@
-handleA
+a
dd()
|
2a80df3379d528b8c13e5609671ca571c75245db
|
Fix bug in new attribute setter
|
khufu-runtime/src/index.js
|
khufu-runtime/src/index.js
|
import {store_handler, cleanup_stores} from './stores'
import {patch, attributes, notifications, symbols} from 'incremental-dom'
import {elementOpen, elementClose, elementVoid, text} from 'incremental-dom'
import {CANCEL} from './stores'
import {add_style} from './style'
import {item} from './dom'
export {CANCEL, add_style, item,
elementOpen, elementClose, elementVoid, text}
// This is different from incrementa-dom default, because it sets boolean
// attributes as property instead of attribute. This works better for
// properties like `checked`. May need better heuristics though.
function applyAttribute(el, name, value) {
var type = typeof value;
if (type === 'object' || type === 'function' || type == 'boolean') {
applyProp(el, name, value);
} else {
applyAttr(el, name, value);
}
}
function set_global_state(fun) {
var old = {
stores: attributes.__stores,
applyAttr: attributes[symbols.default],
deleted: notifications.nodesDeleted,
}
attributes.__stores = store_handler(fun)
attributes[symbols.default] = applyAttribute
notifications.nodesDeleted = cleanup_stores
return old
}
function clean_global_state(old) {
notifications.nodesDeleted = old.deleted
attributes[symbols.default] = old.applyAttr
attributes.__stores = old.stores
}
export default function init(element, template) {
let queued = false;
function queue_render() {
if(!queued) {
queued = true;
window.requestAnimationFrame(render)
}
}
function render() {
queued = false;
let obj = set_global_state(queue_render)
try {
patch(element, template)
} catch(e) {
console.error("Render error", e)
}
clean_global_state(obj)
}
render() // Immediate render works better with hot reload
return {
queue_render
}
}
|
JavaScript
| 0 |
@@ -191,32 +191,85 @@
ncremental-dom'%0A
+import %7BapplyAttr, applyProp%7D from 'incremental-dom'%0A
import %7BCANCEL%7D
@@ -471,16 +471,17 @@
crementa
+l
-dom def
|
5c8e787803af7337f8b7665bceb8b90be78dff5a
|
Clarify test types during scaffolding (#34638)
|
plopfile.js
|
plopfile.js
|
module.exports = function (plop) {
function getFileName(str) {
return str.toLowerCase().replace(/ /g, '-')
}
plop.setGenerator('test', {
description: 'Create a new test',
prompts: [
{
type: 'input',
name: 'name',
message: 'Test name',
},
{
type: 'list',
name: 'type',
message: 'Test type',
choices: ['e2e', 'unit', 'production', 'development'],
},
],
actions: function (data) {
const fileName = getFileName(data.name)
return [
{
type: 'add',
templateFile: `test/${
data.type === 'unit' ? 'unit' : 'e2e'
}/example.txt`,
path: `test/{{type}}/${
data.type === 'unit'
? `${fileName}.test.ts`
: `${fileName}/index.test.ts`
}`,
},
]
},
})
plop.setGenerator('error', {
description: 'Create a new error document',
prompts: [
{
name: 'title',
type: 'input',
message: 'Title for the error',
},
],
actions: function (data) {
const fileName = getFileName(data.title)
return [
{
type: 'add',
path: `errors/${fileName}.md`,
templateFile: `errors/template.txt`,
},
{
type: 'modify',
path: 'errors/manifest.json',
transform(fileContents, data) {
const manifestData = JSON.parse(fileContents)
manifestData.routes[0].routes.push({
title: fileName,
path: `/errors/${fileName}.md`,
})
return JSON.stringify(manifestData, null, 2)
},
},
]
},
})
}
|
JavaScript
| 0 |
@@ -390,50 +390,408 @@
s: %5B
-'e2e', 'unit', 'production', 'development'
+%0A %7B%0A name: 'e2e - Test %22next dev%22 and %22next build && next start%22',%0A value: 'e2e',%0A %7D,%0A %7B%0A name: 'production - Test %22next build && next start%22',%0A value: 'production',%0A %7D,%0A %7B name: 'development - Test %22next dev%22', value: 'development' %7D,%0A %7B name: 'unit - Test individual files', value: 'unit' %7D,%0A
%5D,%0A
|
384c9bd339b7c0e2b20959dfe848d08d906763ee
|
Remove Debugger Statement From Route
|
app/routes/application.js
|
app/routes/application.js
|
import config from '../config/environment';
import {
inject as service
} from '@ember/service';
import AuthenticateRoute from 'wholetale/routes/authenticate';
export default AuthenticateRoute.extend({
internalState: service(),
model: function (params) {
// console.log("Called Authenticate, proceeding in Application");
let router = this;
return router._super(...arguments)
.then(_ => {
let user = router.get('userAuth').getCurrentUser();
return user;
});
},
setupController: function (controller, model) {
this._super(controller, model);
if (model) {
controller.set('loggedIn', true);
controller.set('user', model);
controller.set('gravatarUrl', config.apiUrl + "/user/" + model.get('_id') + "/gravatar?size=64");
this.store.findAll('job', {
reload: true,
adapterOptions: {
queryParams: {
limit: "0"
}
}
}).then(jobs => {
controller.set('jobs', jobs);
controller.set('isLoadingJobs', false);
});
}
},
actions: {
toRoute() {
this.transitionTo.call(this, ...arguments);
return true;
},
showModal(modalDialogName, modalContext) {
const applicationController = this.controller;
Ember.setProperties(applicationController, {
modalDialogName,
modalContext,
isModalVisible: true
});
},
closeModal() {
debugger;
const applicationController = this.controller;
Ember.set(applicationController, 'isModalVisible', false);
}
}
});
|
JavaScript
| 0 |
@@ -1466,26 +1466,8 @@
) %7B%0A
- debugger;%0A
|
35156c460f2cedae679a98c4d09d9c4b7c967a44
|
Disable KPI ID button
|
src/components/Login.js
|
src/components/Login.js
|
import React from 'react'
import {Link} from 'react-router-dom';
import SupportInformationDialog from './SupportInformationDialog';
import * as campus from "../CampusClient";
import TelegramLoginWidget from "./TelegramLoginWidget";
class Login extends React.Component {
state = {
login: '',
password: '',
authFail: false
};
componentDidMount = async () => {
if (!!await campus.getCurrentUser()) {
this.props.history.push('/home');
}
};
setLogin = (event) => {
this.setState({login: event.target.value});
};
setPassword = (event) => {
this.setState({password: event.target.value});
};
authorize = async (e) => {
e.preventDefault();
const user = await campus.auth(this.state.login, this.state.password);
await this.setState({authFail: !user});
if (!!user) {
this.props.history.push(`/home`);
window.location.reload();
}
};
handleTelegramResponse = async (telegramResponse) => {
const user = await campus.authViaTelegram(telegramResponse);
await this.setState({authFail: !user});
if (!!user) {
this.props.history.push(`/home`);
window.location.reload();
}
};
render = () =>
<div className="row">
<div className="col-md-4"/>
<div className="col-md-4">
<br/>
<div className="card">
<div className="card-body">
<div className="text-center">
<a href="/"> <img src="/images/logo-big-green.png" alt="Електроний кампус"
className="img-responsive logo-green"/> </a>
<h2 className="text-center">Авторизацiя у системi</h2>
<div className="panel-body">
<form>
<fieldset>
<div className="form-group">
<input type="text" value={this.state.login} onChange={this.setLogin} className="form-control"
placeholder="Логін"/>
</div>
<div className="form-group">
<input type="password" value={this.state.password} onChange={this.setPassword}
className="form-control" placeholder="Пароль"/>
</div>
{this.state.authFail && <div className="form-group">
<div className="alert alert-danger">
<button type="button" className="close" onClick={() => this.setState({authFail: false})}
data-dismiss="alert" aria-hidden="true">×</button>
Перевірте корректність логіну та паролю.
</div>
</div>}
<div className="form-group">
<input type="submit" onClick={this.authorize} className="btn btn-success btn-block" value="Вхід"/>
</div>
<div className="form-group">
<a className="btn btn-block btn-social btn-facebook"
href={campus.generateFacebookAuthorizationLink()}>
<div className="icon">
<span className="fa fa-facebook"/>
</div>
Увiйти через Facebook
</a>
</div>
{/*<div className="form-group">*/}
{/* <a className="btn btn-block btn-social btn-kpi-id" href="/kpiid">*/}
{/* <div className="icon">*/}
{/* <span className="fa fa-key"/>*/}
{/* </div>*/}
{/* Увiйти через KPI ID*/}
{/* </a>*/}
{/*</div>*/}
<div className="form-group">
<TelegramLoginWidget
callbackOnAuth={this.handleTelegramResponse}
botName={campus.config.telegram.botName}/>
</div>
</fieldset>
</form>
<br/>
<SupportInformationDialog/>
<Link to={`/restore-password`}>Вiдновити втрачений пароль</Link>
</div>
</div>
</div>
</div>
</div>
<div className="col-md-4"/>
</div>;
}
export default Login
|
JavaScript
| 0.000001 |
@@ -3359,19 +3359,16 @@
-%7B/*
%3Cdiv cla
@@ -3387,19 +3387,16 @@
-group%22%3E
-*/%7D
%0A
@@ -3408,19 +3408,16 @@
-%7B/*
%3Ca cla
@@ -3475,19 +3475,16 @@
/kpiid%22%3E
-*/%7D
%0A
@@ -3492,27 +3492,24 @@
-%7B/*
%3Cdiv cla
@@ -3522,19 +3522,16 @@
=%22icon%22%3E
-*/%7D
%0A
@@ -3539,27 +3539,24 @@
-%7B/*
%3Cspan
@@ -3578,19 +3578,16 @@
a-key%22/%3E
-*/%7D
%0A
@@ -3595,27 +3595,24 @@
-%7B/*
%3C/div%3E*/
@@ -3609,19 +3609,16 @@
%3C/div%3E
-*/%7D
%0A
@@ -3630,19 +3630,16 @@
-%7B/*
%D0%A3%D0%B2i%D0%B9
@@ -3653,19 +3653,16 @@
%D0%B7 KPI ID
-*/%7D
%0A
@@ -3678,20 +3678,14 @@
-%7B/*
%3C/a%3E
-*/%7D
%0A
@@ -3705,20 +3705,14 @@
-%7B/*
%3C/div%3E
-*/%7D
%0A%0A
|
474546c114e04bc610443e47ec241ca48d00b5d0
|
Update meta
|
hawk/routes/yard/index.js
|
hawk/routes/yard/index.js
|
'use strict';
var express = require('express');
var router = express.Router();
/**
* Home page
*/
router.get('/', function (req, res, next) {
res.render('yard/index');
});
/**
* Docs page
*/
router.get('/docs', function (req, res, next) {
res.render('yard/docs/index', {
main: {
title : 'Hawk.so Docs',
description : 'Hawk.so is a clever and easy-to-use error tracker. It helps improve your applications. To learn how to start using Hawk..'
}
});
});
module.exports = router;
|
JavaScript
| 0.000001 |
@@ -289,11 +289,12 @@
m
-ain
+eta
: %7B%0A
@@ -313,20 +313,30 @@
: '
-Hawk.so Docs
+Platform documentation
',%0A
@@ -441,17 +441,18 @@
cations.
-
+%5Cn
To learn
|
f8c51a084064ae01dafcc5bbe8e26c6623b61b9c
|
remove unused flow suppression
|
packages/relay-runtime/mutations/commitRelayModernMutation.js
|
packages/relay-runtime/mutations/commitRelayModernMutation.js
|
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @providesModule commitRelayModernMutation
* @flow
* @format
*/
'use strict';
const RelayDeclarativeMutationConfig = require('RelayDeclarativeMutationConfig');
const invariant = require('invariant');
const isRelayModernEnvironment = require('isRelayModernEnvironment');
const warning = require('warning');
import type {Disposable, Variables} from '../util/RelayRuntimeTypes';
import type {DeclarativeMutationConfig} from 'RelayDeclarativeMutationConfig';
import type {GraphQLTaggedNode} from 'RelayModernGraphQLTag';
import type {PayloadError, UploadableMap} from 'RelayNetworkTypes';
import type {Environment, SelectorStoreUpdater} from 'RelayStoreTypes';
export type MutationConfig<T> = {|
configs?: Array<DeclarativeMutationConfig>,
mutation: GraphQLTaggedNode,
variables: Variables,
uploadables?: UploadableMap,
onCompleted?: ?(response: T, errors: ?Array<PayloadError>) => void,
onError?: ?(error: Error) => void,
optimisticUpdater?: ?SelectorStoreUpdater,
optimisticResponse?: Object,
updater?: ?SelectorStoreUpdater,
|};
/**
* Higher-level helper function to execute a mutation against a specific
* environment.
*/
function commitRelayModernMutation<T>(
/* $FlowFixMe(>=0.55.0 site=www) This comment suppresses an error found when
* Flow v0.55 was deployed. To see the error delete this comment and run
* Flow. */
environment: Environment,
config: MutationConfig<T>,
): Disposable {
invariant(
isRelayModernEnvironment(environment),
'commitRelayModernMutation: expect `environment` to be an instance of ' +
'`RelayModernEnvironment`.',
);
const {createOperationSelector, getRequest} = environment.unstable_internal;
const mutation = getRequest(config.mutation);
if (mutation.operationKind !== 'mutation') {
throw new Error('commitRelayModernMutation: Expected mutation operation');
}
let {optimisticResponse, optimisticUpdater, updater} = config;
const {configs, onError, variables, uploadables} = config;
const operation = createOperationSelector(mutation, variables);
// TODO: remove this check after we fix flow.
if (typeof optimisticResponse === 'function') {
optimisticResponse = optimisticResponse();
warning(
false,
'commitRelayModernMutation: Expected `optimisticResponse` to be an object, ' +
'received a function.',
);
}
if (
optimisticResponse &&
mutation.fragment.selections &&
mutation.fragment.selections.length === 1 &&
mutation.fragment.selections[0].kind === 'LinkedField'
) {
const mutationRoot = mutation.fragment.selections[0].name;
warning(
optimisticResponse[mutationRoot],
'commitRelayModernMutation: Expected `optimisticResponse` to be wrapped ' +
'in mutation name `%s`',
mutationRoot,
);
}
if (configs) {
({optimisticUpdater, updater} = RelayDeclarativeMutationConfig.convert(
configs,
mutation,
optimisticUpdater,
updater,
));
}
return environment
.executeMutation({
operation,
optimisticResponse,
optimisticUpdater,
updater,
uploadables,
})
.subscribeLegacy({
onNext: payload => {
// NOTE: commitRelayModernMutation has a non-standard use of
// onCompleted() by calling it on every next value. It may be called
// multiple times if a network request produces multiple responses.
const {onCompleted} = config;
if (onCompleted) {
const snapshot = environment.lookup(operation.fragment);
onCompleted((snapshot.data: $FlowFixMe), payload.response.errors);
}
},
onError,
});
}
module.exports = commitRelayModernMutation;
|
JavaScript
| 0 |
@@ -1372,176 +1372,8 @@
T%3E(%0A
- /* $FlowFixMe(%3E=0.55.0 site=www) This comment suppresses an error found when%0A * Flow v0.55 was deployed. To see the error delete this comment and run%0A * Flow. */%0A
en
|
6423bad50226de2e1a972a083df44517bbaa0d36
|
Fix `form-input-list `directive reference
|
app/views/profile.js
|
app/views/profile.js
|
define(['app', 'angular', 'jquery', '/app/views/forms-input-list.partial.html.js'], function(app, angular, $){
return ['$scope', '$http', '$location', '$filter', '$timeout', 'user', function ($scope, authHttp, $location, $filter, $timeout, user) {
$scope.returnUrl = $location.search().returnurl || $location.search().returnUrl || '/';
//============================================================
//
//
//============================================================
function initialize() {
authHttp.get('/api/v2013/users/' + $scope.user.userID).then(function onsuccess (response) {
$scope.document = response.data;
$scope.phones = ($scope.document.Phone||'').split(';');
$scope.faxes = ($scope.document.Fax ||'').split(';');
$scope.emailsCc = ($scope.document.EmailsCc ||'').split(';');
}).catch(function onerror (response) {
$scope.error = response.data;
});
authHttp.get('/api/v2013/thesaurus/domains/countries/terms', { cache: true }).then(function onerror (response) {
$scope.countries = $filter('orderBy')(response.data, 'name');
}).catch(function onerror (response) {
$scope.error = response.data;
});
}
//============================================================
//
//
//============================================================
$scope.actionSave = function() {
$scope.waiting = true;
authHttp.put('/api/v2013/users/' + $scope.user.userID, angular.toJson($scope.document)).success(function () {
$location.path('/profile/done');
}).error(function (data) {
$scope.waiting = false;
$scope.error = data;
});
};
$scope.$watch('phones+faxes+emailsCc', function () {
if($scope.document) {
$scope.document.Phone = ($scope.phones||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
$scope.document.Fax = ($scope.faxes ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
$scope.document.EmailsCc = ($scope.emailsCc ||[]).join(';').replace(/^\s+|;$|\s+$/gm,'');
}
});
$timeout(initialize, 350);
}];
});
|
JavaScript
| 0.000067 |
@@ -24,27 +24,17 @@
', '
-jquery', '/app/view
+directive
s/fo
@@ -51,24 +51,8 @@
list
-.partial.html.js
'%5D,
@@ -72,19 +72,16 @@
angular
-, $
)%7B%0A%0Aretu
|
9e228967b5ced34f22a9c8492cd28b1875f6bfa9
|
Fix Vehicles fields in bills component
|
src/components/bills.js
|
src/components/bills.js
|
import React, {Component} from 'react'
import Table from 'grommet/components/Table'
import TableRow from 'grommet/components/TableRow'
import Heading from 'grommet/components/Heading'
import Box from 'grommet/components/Box'
import Select from 'grommet/components/Select'
import Columns from 'grommet/components/Columns'
import FormField from 'grommet/components/FormField'
import DateTime from 'grommet/components/DateTime'
import {Link} from 'react-router-dom'
import axios from 'axios'
import numeral from 'numeral'
import moment from 'moment'
moment.locale('es')
class Bills extends Component {
getDate = () => {
const now = new Date()
return `${now.getMonth()+1}/${now.getFullYear()}`
}
state = {
bills: [],
error: false,
providerOptions: [],
vehicleOptions: [],
selectedVehicle: 'Todos',
selectedProvider: 'Todos',
date: this.getDate()
}
componentDidMount() {
this.fetchProviders()
this.fetchVehicles()
axios.get('/api/bill')
.then(({data}) => {
this.setState(() => ({bills: data}))
})
.catch(err => {
this.setState({
error: true
})
})
}
fetchProviders = () => {
axios.get('/api/provider')
.then(({data}) => {
this.setState({
providerOptions: data
})
})
}
fetchVehicles = () => {
axios.get('/api/vehicles')
.then(({data}) => {
this.setState({
vehicleOptions: data
})
})
}
handleProviderSelect = ({option}) => {
this.setState({
selectedProvider: option
})
}
handleVehicleSelect = ({option}) => {
this.setState({
selectedVehicle: option
})
}
filteredData = () => {
const bills = this.state.bills.filter(bill => {
const date = new Date(bill.date)
return `${date.getMonth()+1}/${date.getFullYear()}` === this.state.date
})
if(this.state.selectedProvider === 'Todos' && this.state.selectedVehicle==='Todos'){
return bills
} else {
return bills.filter(bill => {
let ok = true
if(this.state.selectedProvider !== 'Todos'){
ok = bill.provider.nombre === this.state.selectedProvider
}
if(this.state.selectedVehicle !=='Todos'){
if(ok){
if(bill.vehicle){
const vehicle = bill.vehicle
ok = `${vehicle.modelo} ${vehicle.color} ${vehicle.placas}` === this.state.selectedVehicle
} else {
ok = false
}
}
}
return ok
})
}
}
filteredProviderOptions = () => {
const options = this.state.providerOptions.map(opt => opt.nombre)
options.unshift('Todos')
return options
}
filteredVehicleOptions = () => {
const options = this.state.vehicleOptions.map(opt => `${opt.modelo} ${opt.color} ${opt.placas}`)
options.unshift('Todos')
return options
}
handleDate = (date) => {
this.setState(() => ({date}))
}
render(){
return(
<Box align='center'>
<Heading>Facturas</Heading>
<Columns justify='center' size='small'>
<FormField label='Proveedor'>
<Select options={this.filteredProviderOptions()} onChange={this.handleProviderSelect} value={this.state.selectedProvider} />
</FormField>
<FormField label='Vehículo'>
<Select options={this.filteredVehicleOptions()} onChange={this.handleVehicleSelect} value={this.state.selectedVehicle}/>
</FormField>
<FormField label='Mes/Año'>
<DateTime format='M/YYYY' value={this.state.date} onChange={this.handleDate}/>
</FormField>
</Columns>
<Table>
<thead>
<tr>
<th>
Proveedor
</th>
<th>
Total
</th>
<th>
Fecha
</th>
<th>
Vehículo
</th>
<th>
Detalles
</th>
</tr>
</thead>
<tbody>
{this.filteredData().map((bill) => {
return(
<TableRow key={bill._id}>
{bill.provider ? <td>{bill.provider.nombre}</td>: <td>Ninguno</td>}
<td>${numeral(bill.total).format('0,0')}</td>
<td>{moment(bill.date).format('LL')}</td>
<td>{bill.vehicle ? `${bill.vehicle.modelo} ${bill.vehicle.color} ${bill.vehicle.placas}` : 'No aplica'}</td>
<td><Link to={'/factura/' + bill._id} style={{textDecoration: 'none', color: 'white'}}><Box colorIndex='brand' align='center' style={{borderRadius: '10px'}}>Ver Detalles</Box></Link></td>
</TableRow>
)
})}
</tbody>
</Table>
</Box>
)
}
}
export default Bills
|
JavaScript
| 0 |
@@ -1353,17 +1353,16 @@
/vehicle
-s
')%0A .
@@ -2796,17 +2796,17 @@
%60$%7Bopt.
-m
+M
odelo%7D $
@@ -2810,17 +2810,17 @@
%7D $%7Bopt.
-c
+C
olor%7D $%7B
@@ -2823,17 +2823,17 @@
%7D $%7Bopt.
-p
+P
lacas%7D%60)
|
9aa40fd4881538878fa68b035f79a72cfaf13b29
|
add note about 200 Hz text analysis being perhaps overzealous
|
scripts/textanalysis-ui.js
|
scripts/textanalysis-ui.js
|
var text = ""; // Last text of sentence
var sugg = []; // suggestions for autocompletion of node names
$('#textanalyser').autocompleteTrigger({
triggerStart: '#',
triggerEnd: '',
source: sugg
});
// TODO - hide this in a scope
function analyzeSentence(sentence, finalize)
{
var ret = TextAnalyser2(sentence, finalize);
for (var k in ret.sugg) {
sugg.push(ret.sugg[k]);
}
switch (ret.state) {
case ANALYSIS_NODE_START:
$('.typeselection').css({top:window.innerHeight/2-115,left:window.innerWidth/2-325});
$('.typeselection').html('<table><tr><td style="height:28px"></td></tr><tr><td>Use [TAB] key to pick a type</td></tr></table>');
break;
case ANALYSIS_LINK:
$('.typeselection').css('top', -300);
$('.typeselection').css('left', 0);
break;
}
//REINITIALISE GRAPH (DUMB BUT IT WORKS)
graph.removeNodes("temp");
graph.removeLinks("temp");
for (var k in ret.nodes) {
var n = ret.nodes[k];
graph.addNode(n.id, n.type, n.state);
}
for (var k in ret.links) {
var l = ret.links[k];
graph.addLink(l.sourceId, l.targetId, l.name, l.state);
}
//UPDATE GRAPH ONCE
graph.update();
if (finalize) {
$('.typeselection').css('top', -300);
$('.typeselection').css('left', 0);
}
}
$("#textanalyser").keypress(function(e) {
if (graph.history !== undefined) {
graph.history.record_keystrokes(KEYSTROKE_WHERE_TEXTANALYSIS, [e.which]);
}
if (e.which == 13) {
if(!suggestionChange) {
text = $('#textanalyser').val();
$('#textanalyser').val("");
analyzeSentence(text, true);
typeStack = [];
} else {
suggestionChange = false;
}
return false;
}
if (e.which == 37) {//RIGHT
$('body').scrollLeft(0);
e.stopPropagation();
return false;
}
if (e.which == 39) { //LEFT
$('body').scrollLeft(0);
e.stopPropagation();
return false;
}
});
$(document).keydown(function(e) {
if (graph.history !== undefined) {
graph.history.record_keystrokes(KEYSTROKE_WHERE_DOCUMENT, [e.KeyCode]);
}
if (e.keyCode == 9) {//TAB
e.preventDefault();
changeType("down", lastnode);
return false;
}
if (e.keyCode == 37) {//UP
$('html, body').scrollLeft(0);
}
if (e.keyCode == 39) {//DOWN
$('html, body').scrollLeft(0);
}
if (e.keyCode == 38) {//UP
suggestionChange = true;
}
if (e.keyCode == 40) {//DOWN
suggestionChange = true;
}
if (e.keyCode == 9) {//TAB
return false;
}
});
function textSelect(inp, s, e) {
e = e || s;
if (inp.createTextRange) {
var r = inp.createTextRange();
r.collapse(true);
r.moveEnd('character', e);
r.moveStart('character', s);
r.select();
}else if(inp.setSelectionRange) {
inp.focus();
inp.setSelectionRange(s, e);
}
}
function changeType(arg, id) {
if(!id)id="new node";
if (arg === 'up') {
if (typeindex < 4) typeindex++;
else typeindex = 0;
graph.editType(id, null, nodetypes[typeindex]);
$('.typeselection').html('<table><tr><td style="height:28px"></td></tr><tr><td>' + "Chosen Type: " + nodetypes[typeindex] + '</td></tr></table>');
graph.findCoordinates(lastnode,null);
} else {
if (typeindex > 0) typeindex--;
else typeindex = 4;
graph.editType(id, null, nodetypes[typeindex]);
$('.typeselection').html('<table><tr><td style="height:28px"></td></tr><tr><td>' + "Chosen Type: " + nodetypes[typeindex] + '</td></tr></table>');
graph.findCoordinates(lastnode,null);
}
graph.updateGraph();
}
window.setInterval(function() {
if ($('#textanalyser').val() != text) {
if(text.length*8>500)$('#textanalyser').css('width',text.length*8+20);
// text changed
text = $('#textanalyser').val();
analyzeSentence(text, false);
suggestionChange=false;
}
}, 5);
|
JavaScript
| 0 |
@@ -3856,16 +3856,116 @@
h();%0A%7D%0A%0A
+/* TODO: don't use interval by default but only if keys are comming to fast (but still - 5 ms??) */%0A
window.s
@@ -4057,17 +4057,19 @@
length*8
-%3E
+ %3E
500)$('#
@@ -4241,17 +4241,19 @@
onChange
-=
+ =
false;%0A
|
4731bbe2f4154fd7f9c5ef7e64f3c47b6d461d32
|
Fix clean race condition, add more clean tasks
|
app/templates/gulpfile.js
|
app/templates/gulpfile.js
|
var gulp = require('gulp'),
gutil = require('gulp-util'),
clean = require('gulp-clean'),
header = require('gulp-header'),
rename = require('gulp-rename'),
uglify = require('gulp-uglify'),
stylus = require('gulp-stylus'),
autoprefixer = require('gulp-autoprefixer'),
csso = require('gulp-csso'),
jade = require('gulp-jade'),
connect = require('gulp-connect'),
plumber = require('gulp-plumber'),
opn = require('opn'),
pkg = require('./package.json'),
browserify = require('gulp-browserify'),
through = require('through'),
path = require('path'),
ghpages = require('gh-pages'),
template = require('lodash').template,
isDemo = process.argv.indexOf('demo') > 0;
gulp.task('default', ['clean', 'compile']);
gulp.task('demo', ['compile', 'watch', 'connect']);
gulp.task('compile', ['compile:lib', 'compile:demo']);
gulp.task('compile:lib', ['stylus', 'browserify:lib']);
gulp.task('compile:demo', ['jade', 'browserify:demo']);
gulp.task('watch', function() {
gulp.watch('lib/*', ['compile:lib', 'browserify:demo']);
gulp.watch('demo/src/*.jade', ['jade']);
gulp.watch('demo/src/**/*.js', ['browserify:demo']);
});
gulp.task('clean', function() {
return gulp.src(['dist', 'lib/tmp'], { read: false })
.pipe(clean());
});
gulp.task('stylus', function() {
return gulp.src('lib/theme.styl')
.pipe(isDemo ? plumber() : through())
.pipe(stylus({
'include css': true,
'paths': ['./node_modules']
}))
.pipe(autoprefixer('last 2 versions'))
.pipe(csso())
.pipe(gulp.dest('lib/tmp'));
});
gulp.task('browserify', ['browserify:lib', 'browserify:demo']);
gulp.task('browserify:lib', ['stylus'], function() {
return gulp.src('lib/<%= themeFullName %>.js')
.pipe(isDemo ? plumber() : through())
.pipe(browserify({ transform: ['brfs'], standalone: 'bespoke.themes.<%= themeNameCamelized %>' }))
.pipe(header(template([
'/*!',
' * <%%= name %> v<%%= version %>',
' *',
' * Copyright <%%= new Date().getFullYear() %>, <%%= author.name %>',
' * This content is released under the <%%= licenses[0].type %> license',
' * <%%= licenses[0].url %>',
' */\n\n'
].join('\n'), pkg)))
.pipe(gulp.dest('dist'))
.pipe(rename('<%= themeFullName %>.min.js'))
.pipe(uglify())
.pipe(header(template([
'/*! <%%= name %> v<%%= version %> ',
'© <%%= new Date().getFullYear() %> <%%= author.name %>, ',
'<%%= licenses[0].type %> License */\n'
].join(''), pkg)))
.pipe(gulp.dest('dist'));
});
gulp.task('browserify:demo', function() {
return gulp.src('demo/src/scripts/main.js')
.pipe(isDemo ? plumber() : through())
.pipe(browserify({ transform: ['brfs'] }))
.pipe(rename('build.js'))
.pipe(gulp.dest('demo/dist/build'))
.pipe(connect.reload());
});
gulp.task('jade', function() {
return gulp.src('demo/src/index.jade')
.pipe(isDemo ? plumber() : through())
.pipe(jade({ pretty: true }))
.pipe(gulp.dest('demo/dist'))
.pipe(connect.reload());
});
gulp.task('connect', ['compile'], function(done) {
connect.server({
root: 'demo/dist',
livereload: true
});
opn('http://localhost:8080', done);
});
gulp.task('deploy', ['compile:demo'], function(done) {
ghpages.publish(path.join(__dirname, 'demo/dist'), { logger: gutil.log }, done);
});
|
JavaScript
| 0 |
@@ -1165,16 +1165,186 @@
'clean',
+ %5B'clean:browserify', 'clean:stylus', 'clean:jade'%5D);%0Agulp.task('clean:browserify', %5B'clean:browserify:lib', 'clean:browserify:demo'%5D);%0A%0Agulp.task('clean:browserify:lib',
functio
@@ -1378,82 +1378,453 @@
ist'
+%5D
,
-'lib/tmp'%5D, %7B read: false %7D)%0A .pipe(clean());%0A%7D);%0A%0Agulp.task('stylus'
+%7B read: false %7D)%0A .pipe(clean());%0A%7D);%0A%0Agulp.task('clean:browserify:demo', function() %7B%0A return gulp.src(%5B'demo/dist/build'%5D, %7B read: false %7D)%0A .pipe(clean());%0A%7D);%0A%0Agulp.task('clean:stylus', function() %7B%0A return gulp.src(%5B'lib/tmp'%5D, %7B read: false %7D)%0A .pipe(clean());%0A%7D);%0A%0Agulp.task('clean:jade', function() %7B%0A return gulp.src(%5B'demo/dist/index.html'%5D, %7B read: false %7D)%0A .pipe(clean());%0A%7D);%0A%0Agulp.task('stylus', %5B'clean:stylus'%5D
, fu
@@ -2185,32 +2185,56 @@
owserify:lib', %5B
+'clean:browserify:lib',
'stylus'%5D, funct
@@ -3123,32 +3123,59 @@
rowserify:demo',
+ %5B'clean:browserify:demo'%5D,
function() %7B%0A
@@ -3424,24 +3424,40 @@
task('jade',
+ %5B'clean:jade'%5D,
function()
|
1ffd003c0534924ab9d3fa054d2b318d35fceced
|
disable dom merging; our target event handling doesn't work with it atm
|
logology-v05/src/www/js/app/index.js
|
logology-v05/src/www/js/app/index.js
|
/*****************************************************************************
*
* Logology V{{{VERSION}}}
* Author: {{{AUTHOR.NAME}}} <{{{AUTHOR.EMAIL}}}> <{{{AUTHOR.SITE}}}>
*
* This is a very simple demonstration of using gulp + ES6; it obviously
* doesn't do anything resembling the goal of the app yet.
*
*****************************************************************************/
/*globals MobileAccessibility, setImmediate*/
import "babel/polyfill";
import h from "yasmf-h";
import Emitter from "yasmf-emitter";
import GCS from "../lib/grandCentralStation";
import SoftKeyboard from "../lib/SoftKeyboard";
import L from "./localization/localization";
import Theme from "../lib/Theme";
import ThemeManager from "../lib/ThemeManager";
import NavigationViewController from "../lib/NavigationViewController.js";
import Settings from "./models/Settings";
import Dictionaries from "./models/Dictionaries";
import StarterDictionary from "./models/StarterDictionary";
/*
function simpleAlert() {
let outerDiv = document.createElement("div"),
innerDiv = document.createElement("div"),
titleEl = document.createElement("h1"),
messageEl = document.createElement("p"),
buttonEl = document.createElement("button"),
mainWindow = document.getElementById("mainWindow");
outerDiv.setAttribute("is", "y-alert-container");
innerDiv.setAttribute("is", "y-alert-dialog");
titleEl.textContent = "Important!";
messageEl.textContent = "This is an important message. Close this by tapping OK.";
buttonEl.textContent = "OK";
// accessibility
innerDiv.setAttribute("role", "alertdialog");
messageEl.setAttribute("role", "alert");
// create the dom structure
outerDiv.appendChild(innerDiv);
innerDiv.appendChild(titleEl);
innerDiv.appendChild(messageEl);
innerDiv.appendChild(buttonEl);
document.body.appendChild(outerDiv);
setTimeout(function () {
outerDiv.classList.add("visible");
mainWindow.setAttribute("aria-hidden", true);
buttonEl.focus();
}, 0);
buttonEl.addEventListener("click", function() {
outerDiv.classList.remove("visible");
setTimeout(function() {
mainWindow.removeAttribute("aria-hidden");
document.body.removeChild(outerDiv);
}, 400);
}, false);
}
*/
import SearchViewController from "./controllers/SearchViewController";
class App extends Emitter {
constructor() {
super();
//document.addEventListener("deviceready", this.start.bind(this), false);
document.addEventListener("DOMContentLoaded", this.start.bind(this), false);
this.GCS = GCS;
GCS.on("APP:startupFailure", this.onStartupFailure, this);
}
onStartupFailure(sender, notice, err) {
console.log(`Startup failure ${err}`);
}
async start() {
// try {
// zoom our text for accessibility
if (typeof MobileAccessibility !== "undefined") {
MobileAccessibility.usePreferredTextZoom(true);
}
// load localization information
let locale = await L.loadLocale();
this.locale = locale;
this.L = L;
L.loadTranslations(require("./localization/root/messages"));
// load theme
this.theme = new Theme();
this.themeManager = new ThemeManager();
this.themeManager.currentTheme = this.theme;
// load settings
this.settings = new Settings();
// create dictionaries list
this.dictionaries = new Dictionaries();
this.dictionaries.addDictionary(StarterDictionary);
this.searchViewController = new SearchViewController({model: new StarterDictionary()});
this.searchViewController2 = new SearchViewController({model: new StarterDictionary()});
//this.searchViewController.renderElement = document.getElementById("mainWindow");
this.navigationViewController = new NavigationViewController({subviews: [this.searchViewController],
themeManager: this.themeManager,
renderElement: document.getElementById("mainWindow")});
// tell everyone that the app has started
GCS.emit("APP:started");
this.emit("started");
/* } catch (err) {
GCS.emit("APP:startupFailure", err);
this.emit("startupFailure", err);
}*/
//document.querySelector("[is='y-menu-glyph']").addEventListener("click", simpleAlert, false);
this.softKeyboard = new SoftKeyboard({selectors: [".ui-scroll-container", "[is='y-scroll-container']", "y-scroll-container"]});
}
}
let app = new App();
export default app;
|
JavaScript
| 0 |
@@ -488,16 +488,44 @@
smf-h%22;%0A
+%0A//h.useDomMerging = true;%0A%0A
import E
|
fbddfae8ec7756e36d027f0813814528bbc0e40d
|
mark for translation
|
plugins/services/src/js/constants/ServiceTableHeaderLabels.js
|
plugins/services/src/js/constants/ServiceTableHeaderLabels.js
|
var ServiceTableHeaderLabels = {
cpus: "CPU",
disk: "Disk",
gpus: "GPU",
mem: "Mem",
name: "Name",
status: "Status",
version: "Version",
instances: "Instances",
regions: "Region"
};
module.exports = ServiceTableHeaderLabels;
|
JavaScript
| 0 |
@@ -1,7 +1,52 @@
-var
+import %7B i18nMark %7D from %22@lingui/react%22;%0A%0Aconst
Ser
@@ -83,13 +83,23 @@
us:
+i18nMark(
%22CPU%22
+)
,%0A
@@ -108,14 +108,24 @@
sk:
+i18nMark(
%22Disk%22
+)
,%0A
@@ -134,13 +134,23 @@
us:
+i18nMark(
%22GPU%22
+)
,%0A
@@ -158,13 +158,23 @@
em:
+i18nMark(
%22Mem%22
+)
,%0A
@@ -183,14 +183,24 @@
me:
+i18nMark(
%22Name%22
+)
,%0A
@@ -211,16 +211,25 @@
us:
+i18nMark(
%22Status%22
,%0A
@@ -224,16 +224,17 @@
%22Status%22
+)
,%0A vers
@@ -238,16 +238,25 @@
ersion:
+i18nMark(
%22Version
@@ -256,16 +256,17 @@
Version%22
+)
,%0A inst
@@ -272,16 +272,25 @@
tances:
+i18nMark(
%22Instanc
@@ -292,16 +292,17 @@
stances%22
+)
,%0A regi
@@ -310,16 +310,25 @@
ns:
+i18nMark(
%22Region%22
%0A%7D;%0A
@@ -323,16 +323,17 @@
%22Region%22
+)
%0A%7D;%0A%0Amod
|
5f70d258dfe4f173b9380cd986e04411f1b9dd6e
|
Add getElasticsearchHealth
|
main/server/methods/elasticsearch.js
|
main/server/methods/elasticsearch.js
|
// Npm packages imports
import ElasticSearch from 'elasticsearch';
Meteor.methods({
async getElasticsearchData (host) {
// Placeholder for Elasticsearch data
let elasticsearchData;
// default query parameters
const queryParams = {
size: 0,
body: {
query: {
filtered: {
query: {
bool: {
should: [
{
wildcard: {
request_path: {
// Add '*' to partially match the url
value: '/*',
},
},
},
],
},
},
filter: {
range: {
request_at: {
},
},
},
},
},
aggs: {
data_time: {
date_histogram: {
field: 'request_at',
interval: 'month',
format: 'dd-MM-yyyy'
},
},
},
},
};
// Initialize Elasticsearch client, using provided host value
const esClient = new ElasticSearch.Client({ host });
// Check if we can connect to Elasticsearch
const elasticsearchAccessible = await esClient.ping({
// ping usually has a 3000ms timeout
requestTimeout: 1000
})
.then(
(response) => {
// Elasticsearch is accessible
return true;
},
(error) => {
// Throw an error
throw new Meteor.Error(error.message);
return false;
}
)
// Make sure Elasticsearch is available
if (elasticsearchAccessible) {
// Get Elasticsearch data
// return data or throw error
elasticsearchData = await esClient.search(queryParams)
.then(
(response) => {
return response;
},
(error) => {
// Throw an error
throw new Meteor.Error(error.message);
});
return elasticsearchData;
}
}
});
|
JavaScript
| 0 |
@@ -2050,16 +2050,567 @@
;%0A %7D%0A
+ %7D,%0A async getElasticsearchHealth (host) %7B%0A // Initialize Elasticsearch client, using provided host value%0A const esClient = new ElasticSearch.Client(%7B host %7D);%0A%0A // Check if we can connect to Elasticsearch%0A const elasticsearchHealth = await esClient.cat.health(%7B%0A format: 'json',%0A %7D)%0A .then(%0A (response) =%3E %7B%0A // Return Elasticsearch health%0A return response;%0A %7D,%0A (error) =%3E %7B%0A // Throw an error%0A throw new Meteor.Error(error.message);%0A %7D%0A )%0A%0A return elasticsearchHealth;%0A
%7D%0A%7D);%0A
|
3793c4a5819848557c982d96d73b8f13a0c68847
|
Fix style for image
|
scripts/amazon-bookmarklet.js
|
scripts/amazon-bookmarklet.js
|
javascript: (() => {
const productUrl = document
.querySelector('link[rel="canonical"]')
.href.replace(/amazon.co.jp\/.*\/dp/, 'amazon.co.jp/dp');
const imageUrl = document.querySelector('#main-image-container img')
.attributes['src'].textContent;
const title = document.querySelector('#productTitle').innerText;
const detailElement = document.querySelector('#bylineInfo');
const detail = detailElement == undefined ? '' : detailElement.innerText;
const elements =
'<div class="flex items-center m-4"><div class="amazon-image"><a href="' +
productUrl +
'" target="_blank"> <img src="' +
imageUrl +
'" class="h-40"> </a> </div> <div class="m-8"> <p>' +
title +
'<br/>' +
detail +
'</p> <p class="underline font-medium"> <a href="' +
productUrl +
'" target="_blank">Amazon の商品ページへ</a> </p> </div> </div>';
alert(elements);
})();
|
JavaScript
| 0.000001 |
@@ -649,11 +649,15 @@
ss=%22
+max-
h-
-4
+6
0%22%3E
|
67027607b3d4114f607b10cff2244c46c0a203b4
|
Add pixelToGenomeLoci export
|
app/scripts/utils/index.js
|
app/scripts/utils/index.js
|
export { default as absToChr } from './abs-to-chr';
export { default as chromInfoBisector } from './chrom-info-bisector';
export { default as scalesToGenomeLoci } from './scales-to-genome-loci';
|
JavaScript
| 0 |
@@ -111,24 +111,95 @@
-bisector';%0A
+export %7B default as pixelToGenomeLoci %7D from './pixel-to-genome-loci';%0A
export %7B def
|
b466d006b1c6e7e70c494ade2754c6b691949cbc
|
use env be url
|
app/services/sketch-svc.js
|
app/services/sketch-svc.js
|
'use strict';
angular.module('myApp.sketchSvc', []).service("sketchSvc", ['$q', '$http', function($q, $http) {
return {
all: function(options) {
let { user } = options;
let deferred = $q.defer();
$http({
method: 'GET',
url: "http://localhost:3000/sketches"
}).then(({ sketches }) => {
deferred.resolve(sketches);
}, (e) => {
deferred.reject(e);
});
return deferred.promise;
}
};
}]);
|
JavaScript
| 0.999692 |
@@ -264,30 +264,17 @@
rl:
-%22http://localhost:3000
+%60$%7BbeURL%7D
/ske
@@ -278,17 +278,17 @@
sketches
-%22
+%60
%0A %7D
|
638ba6a2c5796e239e75714b67912e190c6592c2
|
fix travis e2e build
|
scripts/update-examples.js
|
scripts/update-examples.js
|
// call it as `$ node scripts/update-examples.js` from root
const join = require('path').join;
const existsSync = require('fs').existsSync;
const spawn = require('child_process').spawn;
const execSync = require('child_process').execSync;
const rimrafSync = require('rimraf').sync;
const examples = [
'browser-less',
'browser-ts',
'browser-ts-react',
'browser-ts-react-i18n',
'spa-ts',
'spa-ts-i18n',
'node-ts'
];
const stdio = 'inherit';
examples.forEach(example => {
console.log(`Update "${example}":`);
try {
// fresh start
const cwd = join(process.cwd(), 'examples', example);
rimrafSync(join(cwd, 'node_modules'));
rimrafSync(join(cwd, 'dist'));
rimrafSync(join(cwd, 'dist-tests'));
rimrafSync(join(cwd, 'dist-release'));
execSync('npm install', { cwd, stdio });
// test commands
execSync('npm run -s ws -- build', { cwd, stdio });
if (example.includes('spa')) {
execSync('npm run -s ws -- build --production', { cwd, stdio });
}
execSync('npm run -s ws -- lint', { cwd, stdio });
if (
existsSync(join(cwd, 'tests', 'unit.ts')) ||
existsSync(join(cwd, 'tests', 'unit.js')) ||
existsSync(join(cwd, 'tests', 'unit.tsx'))
) {
execSync('npm run -s ws -- unit', { cwd, stdio });
}
// test grid
if (example === 'spa-ts') {
const server = spawn('npm', [ 'run', '-s', 'ws', '--', 'serve'], { cwd, detached: true });
execSync('npm run -s ws -- e2e --browsers ff', { cwd, stdio });
// execSync('npm run -s ws -- e2e -g', { cwd, stdio });
// execSync('npm run -s ws -- unit -g', { cwd, stdio });
server.kill();
}
} catch (err) {
throw `[ERROR] Couldn't update "${example}"!`;
}
console.log(`Finished updating "${example}".`);
});
console.log('Updated all examples ♥');
|
JavaScript
| 0 |
@@ -1416,22 +1416,13 @@
wd,
-detached: true
+stdio
%7D);
|
0765d8b0b57981dbaaec46d90c87a71b7f79bb39
|
Remove log
|
addon/components/list-card/header-dropdown-item.js
|
addon/components/list-card/header-dropdown-item.js
|
import Ember from 'ember';
import layout from '../../templates/components/list-card/header-dropdown-item';
export default Ember.Component.extend({
tagName: 'li',
classNames: ['list-card-header-dropdown-item'],
layout: layout,
/**
* Passed in to component
*/
dropdownItem: null,
/**
* Actions
*/
onSelect: Ember.K,
onDeselect: Ember.K,
/**
* Active query tokens
*/
queryTokens: null,
isSelected: Ember.computed('queryTokens.@each.{key,value}', 'queryTokens', 'dropdownItem', function() {
let activeQueryTokens = this.get('queryTokens');
let queryToken = this.get('dropdownItem.queryToken');
console.log("Recomput isSelected");
if (Ember.isBlank(queryToken)) {
return false;
}
let matchedTokens = activeQueryTokens.filter(function(activeQueryToken) {
return activeQueryToken.equals(queryToken);
// return activeQueryToken.key === queryToken.key && activeQueryToken.value === queryToken.value;
});
return !Ember.isEmpty(matchedTokens);
}),
actions: {
click() {
if (this.get('isSelected')) {
this.get('onDeselect')(this.get('dropdownItem'));
} else {
this.get('onSelect')(this.get('dropdownItem'));
}
}
}
});
|
JavaScript
| 0.000001 |
@@ -643,49 +643,8 @@
);%0A%0A
- console.log(%22Recomput isSelected%22);%0A%0A
|
565f3364a31eab82a609f38bda6f0dda78b095f0
|
Update menu
|
core/menu.js
|
core/menu.js
|
var display = require('display');
var options = {};
options.coffee = function () {
return 'Coffee';
};
options.coffeeWithSugar = function () {
return 'Coffee with sugar';
};
options.coffeeWithCream = function () {
return 'Coffee with cream';
};
options.coffeeWithCreamAndSugar = function () {
return 'Coffee with cream and sugar';
};
options.soup = function () {
return 'Soup';
};
|
JavaScript
| 0.000001 |
@@ -385,12 +385,36 @@
n 'Soup';%0A%7D;
+%0A%0Amodule.exports = menu;
|
f15d367300d862ba6e26e731da80296849c1a601
|
add log for 404
|
agir/front/components/notFoundPage/NotFoundPage.js
|
agir/front/components/notFoundPage/NotFoundPage.js
|
import PropTypes from "prop-types";
import React, { useEffect } from "react";
import { usePrevious } from "react-use";
import styled from "styled-components";
import style from "@agir/front/genericComponents/_variables.scss";
import background from "@agir/front/genericComponents/images/illustration-404.svg";
import { useIsOffline } from "@agir/front/offline/hooks";
import TopBar from "@agir/front/allPages/TopBar";
import Button from "@agir/front/genericComponents/Button";
import Spacer from "@agir/front/genericComponents/Spacer";
import illustration from "./illustration.svg";
const Container = styled.div`
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
width: 100%;
min-height: calc(100vh - 74px);
position: relative;
overflow: auto;
background-image: url("${background}");
background-position: center;
background-size: cover;
background-repeat: no-repeat;
padding: 28px 14px;
`;
const InterrogationMark = styled.div`
width: 56px;
height: 56px;
border-radius: 56px;
font-size: 30px;
background-color: ${style.secondary500};
display: inline-flex;
justify-content: center;
align-items: center;
font-weight: 500;
`;
const StyledButton = styled(Button)`
max-width: 450px;
width: 100%;
margin-top: 2rem;
justify-content: center;
`;
const PageStyle = styled.div`
display: flex;
flex-direction: column;
justify-content: center;
`;
const OfflineBlock = styled.div`
& > * {
margin: 0 auto;
padding: 0 16px;
}
& > h1 {
font-size: 20px;
}
`;
export const NotFoundPage = ({
isTopBar = true,
title = "Page",
subtitle = "Cette page",
reloadOnReconnection = true,
}) => {
const isOffline = useIsOffline();
const wasOffline = usePrevious(isOffline);
useEffect(() => {
reloadOnReconnection &&
wasOffline &&
!isOffline &&
window.location.reload();
}, [reloadOnReconnection, isOffline, wasOffline]);
if (isOffline === null) return null;
return (
<PageStyle>
{isTopBar && (
<>
<TopBar />
<Spacer size="74px" />
</>
)}
<Container>
{isOffline ? (
<OfflineBlock>
<img
src={illustration}
width="163"
height="175"
style={{ marginBottom: "32px" }}
/>
<h1 style={{ marginBottom: "8px" }}>Pas de connexion</h1>
<p>
Connectez-vous à un
<br />
réseau Wi-Fi ou mobile
</p>
</OfflineBlock>
) : (
<>
<InterrogationMark>?</InterrogationMark>
<h1 style={{ textAlign: "center", fontSize: "26px" }}>
{title + " "}introuvable
</h1>
<span>{subtitle + " "}n’existe pas ou plus</span>
<StyledButton color="primary" block as="Link" route="events">
Retourner à l'accueil
</StyledButton>
<span style={{ marginTop: "2rem", backgroundColor: "#fff" }}>
ou consulter le{" "}
<a href="https://infos.actionpopulaire.fr/">centre d'aide</a>
</span>
</>
)}
</Container>
</PageStyle>
);
};
NotFoundPage.propTypes = {
isTopBar: PropTypes.bool,
title: PropTypes.string,
subtitle: PropTypes.string,
reloadOnReconnection: PropTypes.bool,
};
export default NotFoundPage;
|
JavaScript
| 0.000001 |
@@ -581,16 +581,114 @@
.svg%22;%0A%0A
+import generateLogger from %22@agir/lib/utils/logger%22;%0A%0Aconst logger = generateLogger(__filename);%0A%0A
const Co
@@ -2086,16 +2086,108 @@
null;%0A%0A
+ if (!isOffline) %7B%0A logger.error(%60React 404 on page $%7Bwindow.location.pathname%7D%60);%0A %7D%0A%0A
return
|
be79394bc851b6a5ba4a3c4d5d37d331600138f1
|
Remove blank line
|
src/reducers/workspace/updateElementReducer.js
|
src/reducers/workspace/updateElementReducer.js
|
const updateElement = (workspace, elementId, newProps) => {
const element = workspace.entities[elementId]
return Object.assign({}, workspace, {
...workspace,
entities: {
...workspace.entities,
[elementId]: {
...element,
...newProps
}
}
})
}
export const changePrimitiveType = (workspace, payload) => {
const { elementId, newType } = payload
return updateElement(workspace, elementId, { type: newType })
}
export const changePrimitiveValue = (workspace, payload) => {
const { elementId, newValue } = payload
return updateElement(workspace, elementId, { value: newValue })
}
|
JavaScript
| 0.999999 |
@@ -285,17 +285,16 @@
%7D%0A %7D)%0A
-%0A
%7D%0A%0Aexpor
|
b8bcec94c1187486048abfc11f5df43800418025
|
fix resize handler
|
scripts/core/config/widget.js
|
scripts/core/config/widget.js
|
/**
* Created with JetBrains RubyMine.
* User: teamco
* Date: 11/24/12
* Time: 1:49 PM
* To change this template use File | Settings | File Templates.
*/
/**
* Created with JetBrains RubyMine.
* User: teamco
* Date: 11/17/12
* Time: 4:10 PM
* To change this template use File | Settings | File Templates.
*/
define([
'modules/base',
'modules/mvc',
'controller/widget.controller',
'model/widget.model',
'view/widget.view',
'event/widget.event.manager',
'permission/widget.permission',
'controller/widget/widget.map',
'controller/widget/widget.wireframe'
], function defineWidget(Base, MVC, Controller, Model, View, EventManager, Permission, Map, Wireframe) {
/**
* Define Widget
* @param opts {object}
* @constructor
*/
var Widget = function Widget(opts) {
this.dom = {};
var DEFAULTS = {
order: 1,
html: {
header: false,
footer: false,
frameLess: false,
opacity: 0.6
},
maximize: false,
events: {
draggable: {
snap: false,
iframeFix: true,
axis: false,
scroll: true,
connectToSortable: false,
cursor: 'move',
appendTo: 'parent'
// handle: '.header',
// cancel: '.header .icons li, .header input, .icons li, .menu'
},
resizable: {
iframeFix: true,
handles: 'n, e, s, w'
},
droppable: {
activeClass: 'widget-ui-hover',
hoverClass: 'widget-ui-active',
greedy: true,
tolerance: 'pointer'
}
}
};
// Init MVC
new MVC({
scope: this,
config: [opts, DEFAULTS],
components: [
Controller,
Model,
View,
EventManager,
Permission
],
render: true
});
/**
* Define map
* @type {widget.map}
*/
this.map = new Map(this);
/**
* Define wireframe
* @type {widget.wireframe}
*/
this.wireframe = new Wireframe(this);
/**
* Define interactions: Drag/Resize
* @type {{}}
*/
this.interactions = {};
this.observer.publish(this.eventmanager.eventList.successCreated);
};
return Widget.extend(Base);
});
|
JavaScript
| 0.000001 |
@@ -1640,18 +1640,11 @@
s: '
-n, e, s, w
+all
'%0A
|
221d6d0180608b6bb2b87ac47fb0410ee97ae15d
|
add expiration time on token
|
api/application-services/authentication-service.js
|
api/application-services/authentication-service.js
|
'use strict';
var UserService = require('../domain/services/users/user-service');
var jwt = require('jsonwebtoken');
var config = require('../config/config');
var appConstants = require('../config/app-constants');
var EntityWithFilterMustExistSpec = require('./specifications/entity-with-filter-must-exist-spec');
var q = require('q');
var moment = require('moment');
var messages = require('../errors-messages/messages-application').authentication;
class AuthenticationService {
constructor(userService) {
this._userService = userService || new UserService();
this._userMustExistWithNameAndPasswordSpec = new EntityWithFilterMustExistSpec(this._userService,
messages.invalidUsernameOrPassword.message,
messages.invalidUsernameOrPassword.code);
}
_createToken(username, id) {
return jwt.sign({ username: username, _id: id, permissions: [appConstants.mustBeAuthenticatedPermission] }, config.secret, {
expiresIn: '1h' // expires in 1 hour
});
}
_createAuthenticationResponse(username, userId) {
// create a token
let token = this._createToken(username, userId);
return { token: token, id: userId, expiresAt: moment().add(1, 'hour').format() };
}
registerAndAuthenticate(userViewModel) {
return this._userService.save(userViewModel)
.then((newEntity) => {
return q(this._createAuthenticationResponse(newEntity.username, newEntity._id));
})
.catch((err) => {
return q.reject(err);
});
}
/**
*
*/
authenticate(authenticateViewModel) {
return this._userMustExistWithNameAndPasswordSpec.isSatisfiedBy(authenticateViewModel)
.then((user) => {
return q(this._createAuthenticationResponse(user.username, user._id));
})
.catch((err) => {
return q.reject(err);
});
}
}
module.exports = AuthenticationService;
|
JavaScript
| 0.000006 |
@@ -945,17 +945,18 @@
resIn: '
-1
+72
h' // ex
|
193542d83dd17027b4ed23f0afa53ae0e44ec973
|
add type annotation for win and ga/gtag
|
src/runtime/google-analytics-event-listener.js
|
src/runtime/google-analytics-event-listener.js
|
/**
* Copyright 2021 The Subscribe with Google Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {analyticsEventToGoogleAnalyticsEvent} from './event-type-mapping';
import {isFunction} from '../utils/types';
export class GoogleAnalyticsEventListener {
/**
* @param {!./deps.DepsDef} deps
*/
constructor(deps) {
/** @private @const {!./deps.DepsDef} deps */
this.deps_ = deps;
/** @private @const {!./client-event-manager.ClientEventManager} */
this.eventManager_ = deps.eventManager();
}
/**
* Start listening to client events
*/
start() {
this.eventManager_.registerEventListener(
this.handleClientEvent_.bind(this)
);
}
/**
* Listens for new events from the events manager and logs appropriate events to Google Analytics.
* @param {!../api/client-event-manager-api.ClientEvent} event
* @param {(!../api/client-event-manager-api.ClientEventParams|undefined)=} eventParams
*/
handleClientEvent_(event, eventParams = undefined) {
// Bail immediately if neither ga function (analytics.js) nor gtag function (gtag.js) exists in Window.
if (
!this.constructor.isGaEligible(this.deps_) &&
!this.constructor.isGtagEligible(this.deps_)
) {
return;
}
let subscriptionFlow = '';
if (event.additionalParameters) {
// additionalParameters isn't strongly typed so checking for both object and class notation.
subscriptionFlow =
event.additionalParameters.subscriptionFlow ||
event.additionalParameters.getSubscriptionFlow();
}
let gaEvent = analyticsEventToGoogleAnalyticsEvent(
event.eventType,
subscriptionFlow
);
if (!gaEvent) {
return;
}
const analyticsParams = eventParams?.googleAnalyticsParameters || {};
gaEvent = {
...gaEvent,
eventCategory: analyticsParams.event_category || gaEvent.eventCategory,
eventLabel: analyticsParams.event_label || gaEvent.eventLabel,
};
// TODO(b/234825847): Remove it once universal analytics is deprecated in 2023.
if (this.constructor.isGaEligible(this.deps_)) {
const ga = this.deps_.win().ga || null;
ga('send', 'event', gaEvent);
}
if (this.constructor.isGtagEligible(this.deps_)) {
const gtag = this.deps_.win().gtag || null;
const gtagEvent = {
'event_category': gaEvent.eventCategory,
'event_label': gaEvent.eventLabel,
'non_interaction': gaEvent.nonInteraction,
...analyticsParams,
};
gtag('event', gaEvent.eventAction, gtagEvent);
}
}
/**
* Function to determine whether event is eligible for GA logging.
* @param {!./deps.DepsDef} deps
* @returns {boolean}
*/
static isGaEligible(deps) {
return isFunction(deps.win().ga || null);
}
/**
* Function to determine whether event is eligible for gTag logging.
* @param {!./deps.DepsDef} deps
* @returns {boolean}
*/
static isGtagEligible(deps) {
return isFunction(deps.win().gtag || null);
}
}
|
JavaScript
| 0 |
@@ -2516,24 +2516,167 @@
abel,%0A %7D;
+%0A%0A /** @type %7BWindow %7C%7Bga?: function(string, string, Object), gtag?: function(string, string, Object)%7D%7D */%0A const win = this.deps_.win();
%0A // TODO
@@ -2822,35 +2822,14 @@
a =
-this.deps_.
win
-()
.ga
- %7C%7C null
;%0A
@@ -2947,37 +2947,16 @@
g =
-this.deps_.
win
-()
.gtag
- %7C%7C null
;%0A
|
ea98bf19a34bc81665ff03a0fb7c5eb243d40a05
|
Load custom preprocessor from ".thought/hb-preprocessor.js" change name of custom helper file to ".thought/hb-helpers.js"
|
customize.js
|
customize.js
|
/*!
* thought <https://github.com/nknapp/thought>
*
* Copyright (c) 2015 Nils Knappmeier.
* Released under the MIT license.
*/
'use strict'
var path = require('path')
/**
*
* Create a spec that can be loaded with `customize` using the `load()` function.
*
* @param {String} workingDir the working directory of thought
* @returns {Function} the Customize-Spec
*/
module.exports = function createSpec (workingDir) {
return function thoughtSpec (customize) {
return customize
.registerEngine('handlebars', require('customize-engine-handlebars'))
.merge({
handlebars: {
partials: path.join(__dirname, 'handlebars', 'partials'),
templates: path.join(__dirname, 'handlebars', 'templates'),
helpers: require.resolve('./handlebars/helpers.js'),
data: {
'package': require(path.resolve('package.json')),
'workingDir': workingDir
},
preprocessor: require('./handlebars/preprocessor.js')
}
})
.merge({
handlebars: {
partials: path.join(workingDir, '.thought', 'partials'),
templates: path.join(workingDir, '.thought', 'templates'),
helpers: path.join(workingDir, '.thought', 'handlebars-helpers,js')
}
})
// .tap(console.log)
}
}
|
JavaScript
| 0 |
@@ -1202,36 +1202,39 @@
helpers: path.
-join
+resolve
(workingDir, '.t
@@ -1248,26 +1248,101 @@
, 'h
-andlebars-helpers,
+b-helpers,js'),%0A preprocessor: path.resolve(workingDir, '.thought','hb-preprocessor.
js')
|
ceadec6369646233fa43672ee5023dfdd057307c
|
check key length in #byteLength as well
|
v2/header.js
|
v2/header.js
|
// Copyright (c) 2015 Uber Technologies, Inc.
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
'use strict';
var bufrw = require('bufrw');
var inherits = require('util').inherits;
var errors = require('../errors');
// TODO: different struct pattern that doesn't realize a temporary list of
// [key, val] tuples may be better. At the very least, such structure would
// allow for more precise error reporting.
function HeaderRW(countrw, keyrw, valrw, options) {
if (!(this instanceof HeaderRW)) {
return new HeaderRW(countrw, keyrw, valrw, options);
}
var self = this;
self.countrw = countrw;
self.keyrw = keyrw;
self.valrw = valrw;
self.maxHeaderCount = options.maxHeaderCount;
self.maxKeyLength = options.maxKeyLength;
bufrw.Base.call(self);
}
inherits(HeaderRW, bufrw.Base);
HeaderRW.prototype.byteLength = function byteLength(headers) {
var self = this;
var length = 0;
var keys = Object.keys(headers);
var res;
length += self.countrw.width;
for (var i = 0; i < keys.length; i++) {
var key = keys[i];
res = self.keyrw.byteLength(key);
if (res.err) return res;
length += res.length;
res = self.valrw.byteLength(headers[key]);
if (res.err) return res;
length += res.length;
}
return bufrw.LengthResult.just(length);
};
HeaderRW.prototype.writeInto = function writeInto(headers, buffer, offset) {
var self = this;
var keys = Object.keys(headers);
var res;
res = self.countrw.writeInto(keys.length, buffer, offset);
if (keys.length > self.maxHeaderCount) {
return bufrw.WriteResult.error(errors.TooManyHeaders({
offset: offset,
endOffset: res.offset,
count: keys.length
}), offset);
}
for (var i = 0; i < keys.length; i++) {
if (res.err) return res;
offset = res.offset;
var key = keys[i];
res = self.keyrw.writeInto(key, buffer, offset);
if (res.err) return res;
var keyByteLength = res.offset - offset;
if (keyByteLength > self.maxKeyLength) {
return bufrw.WriteResult.error(errors.TransportHeaderTooLong({
maxLength: self.maxKeyLength,
headerName: key,
offset: offset,
endOffset: res.offset
}), offset);
}
offset = res.offset;
res = self.valrw.writeInto(headers[key], buffer, offset);
}
return res;
};
HeaderRW.prototype.readFrom = function readFrom(buffer, offset) {
var self = this;
var headers = {};
var start = 0;
var n = 0;
var key = '';
var val = '';
var res;
res = self.countrw.readFrom(buffer, offset);
if (res.err) return res;
offset = res.offset;
n = res.value;
if (n > self.maxHeaderCount) {
return bufrw.ReadResult.error(errors.TooManyHeaders({
offset: offset,
endOffset: res.offset,
count: n
}), offset, headers);
}
for (var i = 0; i < n; i++) {
start = offset;
res = self.keyrw.readFrom(buffer, offset);
if (res.err) return res;
key = res.value;
if (!key.length) {
return bufrw.ReadResult.error(errors.NullKeyError({
offset: offset,
endOffset: res.offset
}), offset, headers);
} else if (res.offset - offset > self.maxKeyLength) {
return bufrw.ReadResult.error(errors.TransportHeaderTooLong({
maxLength: self.maxKeyLength,
headerName: key,
offset: offset,
endOffset: res.offset
}), offset, headers);
}
offset = res.offset;
res = self.valrw.readFrom(buffer, offset);
if (res.err) return res;
val = res.value;
if (headers[key] !== undefined) {
return bufrw.ReadResult.error(errors.DuplicateHeaderKeyError({
offset: start,
endOffset: res.offset,
key: key,
value: val,
priorValue: headers[key]
}), offset, headers);
}
offset = res.offset;
headers[key] = val;
}
return bufrw.ReadResult.just(offset, headers);
};
module.exports = HeaderRW;
// nh:1 (hk~1 hv~1){nh}
module.exports.header1 = HeaderRW(bufrw.UInt8, bufrw.str1, bufrw.str1, {
maxHeaderCount: 128,
maxKeyLength: 16
});
// nh:2 (hk~2 hv~2){nh}
module.exports.header2 = HeaderRW(bufrw.UInt16BE, bufrw.str2, bufrw.str2, {
maxHeaderCount: Infinity,
maxKeyLength: Infinity
});
|
JavaScript
| 0 |
@@ -2286,32 +2286,259 @@
rr) return res;%0A
+ if (res.length %3E self.maxKeyLength) %7B%0A return bufrw.LengthResult.error(errors.TransportHeaderTooLong(%7B%0A maxLength: self.maxKeyLength,%0A headerName: key%0A %7D));%0A %7D%0A
length +
|
ddd6d66bc621c272abf424c096f048760af6b94f
|
Remove old comments.
|
experimental/babel-preset-env/test/debug-fixtures.js
|
experimental/babel-preset-env/test/debug-fixtures.js
|
const chai = require("chai");
const child = require("child_process");
const fs = require("fs-extra");
const helper = require("babel-helper-fixtures");
const path = require("path");
const fixtureLoc = path.join(__dirname, "debug-fixtures");
const tmpLoc = path.join(__dirname, "tmp");
const clear = () => {
process.chdir(__dirname);
if (fs.existsSync(tmpLoc)) fs.removeSync(tmpLoc);
fs.mkdirSync(tmpLoc);
process.chdir(tmpLoc);
};
const saveInFiles = files => {
Object.keys(files).forEach(filename => {
const content = files[filename];
fs.outputFileSync(filename, content);
});
};
const testOutputType = (type, stdTarg, opts) => {
stdTarg = stdTarg.trim();
stdTarg = stdTarg.replace(/\\/g, "/");
const optsTarg = opts[type];
if (optsTarg) {
const expectStdout = optsTarg.trim();
chai.expect(stdTarg).to.equal(expectStdout, `${type} didn't match`);
} else {
const file = path.join(opts.testLoc, `${type}.txt`);
console.log(`New test file created: ${file}`);
fs.outputFileSync(file, stdTarg);
}
};
const assertTest = (stdout, stderr, opts) => {
// stderr = stderr.trim();
// if (stderr) {
// throw new Error("stderr:\n" + stderr);
// }
testOutputType("stdout", stdout, opts);
if (stderr) {
testOutputType("stderr", stderr, opts);
}
};
const buildTest = opts => {
const binLoc = path.join(process.cwd(), "node_modules/.bin/babel");
return callback => {
clear();
saveInFiles(opts.inFiles);
let args = [binLoc];
args = args.concat(opts.args);
const spawn = child.spawn(process.execPath, args);
let stdout = "";
let stderr = "";
spawn.stdout.on("data", chunk => stdout += chunk);
spawn.stderr.on("data", chunk => stderr += chunk);
spawn.on("close", () => {
let err;
try {
assertTest(stdout, stderr, opts);
} catch (e) {
err = e;
}
callback(err);
});
};
};
describe("debug output", () => {
fs.readdirSync(fixtureLoc).forEach(testName => {
if (testName.slice(0, 1) === ".") return;
const testLoc = path.join(fixtureLoc, testName);
if (testName.slice(0, 1) === ".") return;
const opts = {
args: ["src", "--out-dir", "lib"],
testLoc: testLoc,
};
const stdoutLoc = path.join(testLoc, "stdout.txt");
const stderrLoc = path.join(testLoc, "stderr.txt");
if (fs.existsSync(stdoutLoc)) {
opts.stdout = helper.readFile(stdoutLoc);
}
if (fs.existsSync(stderrLoc)) {
opts.stderr = helper.readFile(stderrLoc);
}
const optionsLoc = path.join(testLoc, "options.json");
if (!fs.existsSync(optionsLoc)) {
throw new Error(
`Debug test '${testName}' is missing an options.json file`,
);
}
const inFilesFolderLoc = path.join(testLoc, "in");
opts.inFiles = {
".babelrc": helper.readFile(optionsLoc),
};
if (!fs.existsSync(inFilesFolderLoc)) {
opts.inFiles["src/in.js"] = "";
} else {
fs.readdirSync(inFilesFolderLoc).forEach(filename => {
opts.inFiles[`src/${filename}`] = helper.readFile(
path.join(inFilesFolderLoc, filename),
);
});
}
it(testName, buildTest(opts));
});
});
|
JavaScript
| 0 |
@@ -1097,111 +1097,8 @@
%3E %7B%0A
- // stderr = stderr.trim();%0A%0A // if (stderr) %7B%0A // throw new Error(%22stderr:%5Cn%22 + stderr);%0A // %7D%0A%0A
te
|
8844ef82ef57d32c7cb4fd2cd0c2134b95d4a85a
|
fix getting server port
|
backhome.js
|
backhome.js
|
'use strict';
let config = require('config'),
path = require('path'),
fs = require('fs'),
// Http server
express = require('express'),
bodyParser = require('body-parser'),
app = express(),
port = config.get('http.port'),
// Security
https = require('https'),
httpsOptions = {
// key: fs.readFileSync('./config/ssl/backhome_privkey.pem'),
// cert: fs.readFileSync('./config/ssl/backhome_certificate.pem')
},
helmet = require('helmet'),
// Authentification Require
crypto = require('crypto'),
passport = require('passport'),
LocalStrategy = require('passport-local').Strategy,
cookieSession = require('cookie-session'),
// Dash button Setup
// dash_button = require('node-dash-button'),
// dash = dash_button(config.get('dash.mac'), null, null, 'all'),
// Plug Setup
plugApi = require('hs100-api'),
plugClient = new plugApi.Client(),
plug = plugClient.getPlug(config.get('switch.host')),
// Kodi Setup
kodi = require('kodi-ws'),
kodiConf = config.get('kodi'),
// App Setup
appConf = config.get('app'),
musicMorning = appConf.music.morning,
musicEvening = appConf.music.evening,
canPlayMusic = appConf.enable,
playMusic = function(musicId)
{
let youtubeRegex = /^https:\/\/www.youtube.com\/watch\?v=(.+)&?.+$/;
if(youtubeRegex.test(musicId))
{
musicId = musicId.match(youtubeRegex)[1];
}
return kodi(kodiConf.host, kodiConf.port)
.then(function(connection)
{
/* Start the video */
return connection.Player.Open(
{
item :
{
file : 'plugin:\/\/plugin.video.youtube\/?path=\/root\/search&action=play_video&videoid=' + musicId
}
});
});
},
stopMusic = function()
{
return kodi(kodiConf.host, kodiConf.port)
.then(function(connection)
{
return connection.Player.GetActivePlayers()
.then(function(players)
{
/* Stop everything thats playing */
return Promise.all(players.map(function(player)
{
return connection.Player.Stop(player.playerid);
}));
});
});
}
;
// Main application
// Dash Button
// dash.on("detected", () =>
// {
// console.log('Dash Button : pressed');
// plug.getPowerState()
// .then((state) =>
// {
// plug.setPowerState(!state);
// if(state)
// {
// console.log('Smart Plug : switch off');
// stopMusic()
// .then(function()
// {
// console.log('Kodi : Stop all players');
// })
// .catch(function(error)
// {
// console.error('Kodi : ' + error);
// });
// }
// else
// {
// console.log('Smart Plug : switch on');
// if (canPlayMusic)
// {
// let d = new Date(),
// n = new Date(),
// musics = musicMorning
// ;
// d.setHours(12, 0, 0, 0);
// (n>d) && (musics = musicEvening);
// playMusic(musics[Math.floor(Math.random() * (musics.length))])
// .then(function()
// {
// console.log('Kodi : Playing Music ' + (n>d ? 'Evening' : 'Morning'));
// })
// .catch(function(error)
// {
// console.error('Kodi : ' + error);
// });
// }
// else
// {
// console.log('Kodi : Not Playing Music');
// }
// }
// })
// .catch(function(error)
// {
// console.error('Smart Plug : ' + error);
// })
// ;
// });
console.log('Back Home Ready');
passport.use(new LocalStrategy(
function(username, password, done)
{
var userApp = config.get('server.user.username'),
passApp = config.get('server.user.password'),
userId
;
if (userApp !== username ||
passApp !== password
)
{
return done(null, false, { message: 'Incorrect username or password' });
}
return done(null, { id : config.get('server.user.id') });
}
));
passport.serializeUser(function(user, done)
{
done(null, user);
});
passport.deserializeUser(function(user, done)
{
done(null, user);
});
app
.use(helmet())
.use('/static', express.static(path.join(__dirname, 'public')))
.use(bodyParser.json())
.use(bodyParser.urlencoded({ extended: true}))
.use(cookieSession(
{
name: 'session',
keys: config.get('server.auth.cookieKeys')
}))
.use(passport.initialize())
.use(passport.session())
.set('view engine', 'pug')
.get('/login', function(req, res)
{
res.render('login', { active : 'Login' });
})
.post('/login', passport.authenticate('local',
{
successRedirect: '/',
failureRedirect: '/login'
}))
.get('/', function(req, res)
{
if(!req.isAuthenticated())
{
res.redirect('/login');
}
res.render('index',
{
active : 'Configuration',
enable : canPlayMusic,
musicMorning : musicMorning,
musicEvening : musicEvening
});
})
.post('/saveMusic', function(req, res)
{
if(!req.isAuthenticated())
{
res.redirect('/login');
}
musicMorning = req.body.musicMorning.filter(Boolean);
musicEvening = req.body.musicEvening.filter(Boolean);
if(req.body.enable !== 'undefined')
{
canPlayMusic = req.body.enable;
}
res.end();
})
.get('/play', function(req, res)
{
if(!req.isAuthenticated())
{
res.redirect('/login');
}
playMusic(req.query.music)
.then(function()
{
console.log('Kodi : Playing Music UI');
});
})
.get('/sw', function(req, res)
{
res.sendFile(path.join(__dirname, 'sw.js'));
})
;
//var httpsServer = https.createServer(httpsOptions, app);
app.listen(port, function()
{
console.log(`Server listening ${port}`);
});
|
JavaScript
| 0.000001 |
@@ -209,20 +209,22 @@
ig.get('
-http
+server
.port'),
|
55c8af91633746abad48602c2c070b8e95c6bd75
|
Make radar icons change size based on distance. Law of inverse variation
|
src/systems/renderer/sample-renderer-system.js
|
src/systems/renderer/sample-renderer-system.js
|
"use strict";
var point, angle, opposite, adjacent, distance;
var collidables, vp, vs, vc, op, os, oc, i, image, size = { "width": 20, "height": 45 };
var radius, type;
var viewPort = 5;
module.exports = function(ecs, game) { // eslint-disable-line no-unused-vars
game.entities.registerSearch("linesToCollidablesSearch", ["collisions", "position", "size"]);
ecs.add(function linesToCollidables(entities, context) {
collidables = game.entities.find("collisions");
vp = game.entities.get(viewPort, "position");
vs = game.entities.get(viewPort, "size");
vc = {
"x": vp.x + (vs.width * 0.5),
"y": vp.y + (vs.height * 0.5)
};
for (i = 0; i < collidables.length; i++) {
if (game.entities.get(collidables[i], "food")) {
op = game.entities.get(collidables[i], "position");
os = game.entities.get(collidables[i], "size");
oc = {
"x": op.x + (os.width * 0.5),
"y": op.y + (os.height * 0.5)
};
//boxSize = 20;
radius = 470;
type = game.entities.get(collidables[i], "type");
image = new Image();
switch (type) {
case 1:
image.src = "./images/yellow_arrow.png";
break;
case 2:
image.src = "./images/green_arrow.png";
break;
case 3:
image.src = "./images/blue_arrow.png";
break;
case 4:
image.src = "./images/red_arrow.png";
break;
default:
image.src = "./images/white_arrow.png";
break;
}
opposite = oc.y - vc.y;
adjacent = oc.x - vc.x;
angle = Math.atan2(opposite, adjacent);
point = getPointOnCircle(vc, angle, radius);
distance = Math.sqrt((vc.x - oc.x) * (vc.x - oc.x) + (vc.y - oc.y) * (vc.y - oc.y));
if (distance > radius) {
angle += Math.PI;
context.translate(point.x, point.y);
context.rotate(angle);
context.drawImage(image, -size.width * 0.5, -size.height * 0.5, size.width, size.height);
context.rotate(-angle);
context.translate(-point.x, -point.y);
}
}
}
}, "linesToCollidablesSearch");
};
function getPointOnCircle(point, angle, radius) {
return {
"x": point.x + (radius * Math.cos(angle)),
"y": point.y + (radius * Math.sin(angle))
};
}
|
JavaScript
| 0.000001 |
@@ -129,26 +129,30 @@
h%22:
-20, %22height%22: 45 %7D
+45 %7D, constant = 21150
;%0Ava
@@ -2377,32 +2377,366 @@
.rotate(angle);%0A
+ // Law of inverse variation:%0A // Constant = 21150 so width = 45 at the radar radius%0A // @see http://www.regentsprep.org/regents/math/algtrig/ate7/inverse%2520variation.htm%0A size.width = constant / distance;%0A size.height = size.width * 2.5;%0A
|
e1b17c8ca8872b11f90d7df7a9ef838a8f131969
|
use minimal output
|
scripts/karma.config.sauce.js
|
scripts/karma.config.sauce.js
|
const baseConfig = require('./karma.config.base');
const {
CIRCLE_BRANCH,
CIRCLE_BUILD_NUM,
FORCE_MOBILE_TEST,
} = process.env;
const customLaunchers = {
sl_chrome: {
base: 'SauceLabs',
browserName: 'chrome',
platform: 'Windows 7',
version: 'latest',
},
sl_firefox: {
base: 'SauceLabs',
browserName: 'firefox',
version: 'latest',
},
// yet another IE family
sl_mac_safari_8: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.10',
version: '8',
},
sl_mac_safari_9: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'OS X 10.11',
version: '9',
},
sl_mac_safari_10: {
base: 'SauceLabs',
browserName: 'safari',
platform: 'macOS 10.12',
},
// IE family
sl_ie_10: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 7',
version: '10',
},
sl_ie_11: {
base: 'SauceLabs',
browserName: 'internet explorer',
platform: 'Windows 8.1',
version: '11',
},
sl_edge: {
base: 'SauceLabs',
browserName: 'MicrosoftEdge',
platform: 'Windows 10',
},
};
// mobile emulators are really really slow
// only run them on develop/master branch
if (CIRCLE_BRANCH === 'develop' || CIRCLE_BRANCH === 'master' || FORCE_MOBILE_TEST) {
Object.assign(customLaunchers, {
sl_ios_9: {
base: 'SauceLabs',
browserName: 'iphone',
version: '9.3',
},
sl_ios_10: {
base: 'SauceLabs',
browserName: 'iphone',
version: '10.0',
},
sl_android_5: {
base: 'SauceLabs',
browserName: 'android',
version: '5.1',
},
});
}
const buildNum = CIRCLE_BUILD_NUM ? `#${CIRCLE_BUILD_NUM}` : `@${Date.now()}`;
module.exports = function (config) {
config.set(Object.assign(baseConfig, {
reporters: ['mocha', 'saucelabs'],
browsers: Object.keys(customLaunchers),
customLaunchers: customLaunchers,
// wait for mobile emulators
captureTimeout: 300000,
browserNoActivityTimeout: 300000,
sauceLabs: {
testName: 'Service Mocker tests',
recordScreenshots: false,
build: `service-mocker ${buildNum}`,
},
}));
};
|
JavaScript
| 0.999337 |
@@ -2157,22 +2157,75 @@
m%7D%60,%0A %7D,%0A
+ mochaReporter: %7B%0A output: 'minimal',%0A %7D,%0A
%7D));%0A%7D;%0A
|
dc89576790420ed1024c2b7f289a0864dbd214ce
|
remove debug messages
|
commands.js
|
commands.js
|
exports.handle = handle;
exports.replyMention = replyMention;
exports.greet = greet;
function handle(data)
{
for (var i=0;i<commands.length;i++)
{
if (data.message.slice(0,commands[i].name.length) === commands[i].name) {
//missing permission level check
console.log("x");
commands[i].handler(data);
break;
}
}
}
function replyMention(data)
{
//basic test, want to add some conversation module
var msg=data.message;
if (msg.search("fish")!=-1)
bot.sendChat("fish go m00");
else if (msg.search("cows")!=-1)
bot.sendChat("cows go blub");
else bot.sendChat("Sup @"+data.raw.un);
}
function greet(data)
{
bot.sendChat("Ol @"+data.username+"!");
}
// command levels: 1-user,2-dj,3-bouncer,4-manager,5-host
//add user to queue
var _add={
"name":".add",
"level":3,
"handler":function(data){
console.log("test add");
}
};
var _help={
"name":".help",
"level":1,
"handler":function(data){
console.log("test help");
var str="";
for (var i=0;i<commands.length;i++)
{
if (commands[i].level==1) //only show user commands, mods have to know their shit
str+=commands[i].name+" ";
}
bot.sendChat("Available commands: "+str);
}
};
var commands=[_add,_help];
|
JavaScript
| 0.000001 |
@@ -280,38 +280,8 @@
eck%0A
- console.log(%22x%22);%0A
@@ -1006,42 +1006,8 @@
a)%7B%0A
- console.log(%22test help%22);%0A
|
5bdcba9fdda4028a32c07fd383f09707e5c85f53
|
Fix chart js copy/paste error
|
app/assets/javascripts/charts/mcas_scaled_chart.js
|
app/assets/javascripts/charts/mcas_scaled_chart.js
|
(function(root) {
var McasScaledChart = function initializeMcasScaledChart (series) {
this.title = 'MCAS score';
this.series = series;
};
McasScaledChart.fromChartData = function mcasScaledChartFromChartData(chartData) {
var datums = [];
var math_scaled_data = chartData.data('mcas-series-math-scaled');
var ela_scaled_data = chartData.data('mcas-series-ela-scaled')
if (math_scaled_data !== null) {
var math_scaled = new ProfileChartData("Math scale score", math_scaled_data).toDateChart();
datums.push(math_scaled);
}
if (ela_scaled_data !== null) {
var ela_scaled = new ProfileChartData("English scale score", ela_scaled_data).toDateChart();
datums.push(math_scaled);
}
return new McasScaledChart(datums);
};
McasScaledChart.prototype.toHighChart = function mcasChartToHighChart () {
return $.extend({}, ChartSettings.base_options, {
xAxis: ChartSettings.x_axis_datetime,
yAxis: ChartSettings.default_yaxis,
series: this.series
});
};
McasScaledChart.prototype.render = function renderMcasScaledChart (controller) {
controller.renderChartOrEmptyView(this);
};
root.McasScaledChart = McasScaledChart;
})(window)
|
JavaScript
| 0.000001 |
@@ -708,36 +708,35 @@
datums.push(
-math
+ela
_scaled);%0A %7D%0A
|
3475b4d518addfc4820683a11a8791fbe14a6ae4
|
Tweak asset picker so it doesn't include black entries from a select.
|
app/assets/javascripts/islay/admin/asset_picker.js
|
app/assets/javascripts/islay/admin/asset_picker.js
|
/* -------------------------------------------------------------------------- */
/* ASSET PICKER
/* This mostly leans on the asset dialog and acts as a convenience for
/* initalizing it.
/* -------------------------------------------------------------------------- */
(function($){
var Picker = function(input, type) {
this.$input = input;
// Stub out the UI
this.$list = $('<ul class="islay-form-asset-picker"></ul>');
this.$add = $('<li class="add"><i class="icon-plus-sign"></i></li>');
this.$add.click($.proxy(this, 'clickAdd'));
this.$list.append(this.$add);
this.clickRemove = $.proxy(this, 'clickRemove');
this.selectionEnumerator = $.proxy(this, 'selectionEnumerator');
// Generate entries for existing selections
this.selected = {};
var opts = this.$input.find(':selected');
for (var i = 0; i < opts.length; i++) {
var $opt = $(opts[i]);
this.addEntry($opt.attr('value'), $opt.attr('data-preview'), $opt);
};
// Hide the existing select
this.$input.after(this.$list).hide();
};
Picker.prototype = {
clickAdd: function() {
if (this.dialog) {
this.dialog.show();
}
else {
this.dialog = new Islay.Dialogs.AssetBrowser({
add: $.proxy(this, 'updateSelection')
});
}
},
clickRemove: function(e) {
var $li = $(e.target).parent('li'),
id = $li.attr('data-value');
$li.remove();
this.selected[id].prop('selected', false);
this.selected[id] = undefined;
},
updateSelection: function(selections) {
$.each(selections, this.selectionEnumerator);
},
selectionEnumerator: function(i, selection) {
if (!this.selected[selection.id]) {
this.addEntry(selection.id, selection.get('url'));
}
},
addEntry: function(id, url, el) {
this.selected[id] = el || this.$input.find('option[value="' + id + '"]');
this.selected[id].prop('selected', true);
var $li = $('<li class="choice"></li>').attr('data-value', id),
$img = $('<img>').attr('src', url),
$remove = $('<i class="icon-remove-sign remove"><i/>');
$remove.click(this.clickRemove);
$li.append($img, $remove);
this.$add.before($li);
}
};
$.fn.islayAssetPicker = function(type) {
this.each(function() {
var $this = $(this);
if (!$this.data('islayAssetPicker')) {
$this.data('islayAssetPicker', new Picker($this, type));
}
});
return this;
}
})(jQuery);
|
JavaScript
| 0 |
@@ -900,16 +900,55 @@
ts%5Bi%5D);%0A
+ if (!_.isEmpty($opt.text())) %7B%0A
th
@@ -1013,16 +1013,24 @@
$opt);%0A
+ %7D%0A
%7D;%0A%0A
|
a684418a1fa4c4df893dbebb2b2e7c0d4510532a
|
return artwork
|
app/assets/javascripts/services/ArtworkServices.js
|
app/assets/javascripts/services/ArtworkServices.js
|
JavaScript
| 0 |
@@ -0,0 +1,162 @@
+function Artwork($resource) %7B%0A return $resource('http://localhost:8080/artworks/:id', %7Bid: '@_id'%7D)%0A%7D)%0A%0Aangular%0A .module('app')%0A .services('Artwork', Artwork)%0A
|
|
82d3674ef2cc295a224a854c93ba0cab67fbbabc
|
remove c3 mock from snapshot tests (#2205)
|
app/assets/javascripts/test/enzyme/snapshot.e2e.js
|
app/assets/javascripts/test/enzyme/snapshot.e2e.js
|
// @flow
/* eslint import/no-extraneous-dependencies: ["error", {"peerDependencies": true}] */
/* eslint-disable import/first */
// This needs to be the very first import
import { createSnapshotable, debugWrapper, waitForAllRequests } from "./e2e-setup";
import { mount } from "enzyme";
import test from "ava";
import mockRequire from "mock-require";
import React from "react";
import { Provider } from "react-redux";
import { Router } from "react-router-dom";
import createBrowserHistory from "history/createBrowserHistory";
mockRequire("app", {
currentUser: {
email: "[email protected]",
teams: [{ role: { name: "admin" } }],
},
});
// Those wrappers interfere with global.window and global.document otherwise
mockRequire("libs/hammerjs_wrapper", {});
mockRequire("libs/keyboardjs_wrapper", {});
mockRequire("libs/window", global.window);
// The following components cannot be rendered by enzyme. Let's mock them
mockRequire("antd/lib/upload", () => <div />);
mockRequire("c3", () => {});
mockRequire("react-c3js", () => <div />);
// Antd makes use of fancy effects, which is why the rendering output is not reliable.
// Mock these components to avoid this issue.
mockRequire("antd/lib/spin", props => <div className="mock-spinner">{props.children}</div>);
mockRequire("antd/lib/button", props => (
<div className="mock-button" {...props}>
{props.children}
</div>
));
const ProjectListView = mockRequire.reRequire("../../admin/views/project/project_list_view")
.default;
const Dashboard = mockRequire.reRequire("../../dashboard/views/dashboard_view").default;
const UserListView = mockRequire.reRequire("../../admin/views/user/user_list_view").default;
const Store = mockRequire.reRequire("../../oxalis/throttled_store").default;
const { setActiveUserAction } = mockRequire.reRequire("../../oxalis/model/actions/user_actions");
const { getActiveUser } = mockRequire.reRequire("../../admin/admin_rest_api");
// Cannot be rendered for some reason
// const TracingLayoutView = mockRequire.reRequire("../../oxalis/view/tracing_layout_view").default;
const browserHistory = createBrowserHistory();
test.beforeEach(async _ => {
// There needs to be an active user in the store for the pages to render correctly
const user = await getActiveUser();
Store.dispatch(setActiveUserAction(user));
});
test("Dashboard", async t => {
const dashboard = mount(
<Provider store={Store}>
<Router history={browserHistory}>
<Dashboard userId={null} isAdminView={false} />
</Router>
</Provider>,
);
await waitForAllRequests(dashboard);
t.is(dashboard.find(".TestDatasetHeadline").length, 1);
debugWrapper(dashboard, "Dashboard-1");
t.snapshot(createSnapshotable(dashboard), { id: "Dashboard-Datasets" });
dashboard
.find(".ant-tabs-tab")
.at(1)
.simulate("click");
await waitForAllRequests(dashboard);
t.is(dashboard.find(".TestAdvancedDatasetView").length, 1);
debugWrapper(dashboard, "Dashboard-2");
t.snapshot(createSnapshotable(dashboard), { id: "Dashboard-Datasets-Advanced" });
// Active tasks tab
dashboard
.find(".ant-tabs-tab")
.at(2)
.simulate("click");
await waitForAllRequests(dashboard);
t.is(dashboard.find(".TestTasksHeadline").length, 1);
debugWrapper(dashboard, "Dashboard-3");
t.snapshot(createSnapshotable(dashboard), { id: "Dashboard-Tasks" });
// Active explorative annotations tab
dashboard
.find(".ant-tabs-tab")
.at(3)
.simulate("click");
await waitForAllRequests(dashboard);
t.is(dashboard.find(".TestExplorativeAnnotationsView").length, 1);
debugWrapper(dashboard, "Dashboard-4");
t.snapshot(createSnapshotable(dashboard), { id: "Dashboard-Explorative-Annotations" });
});
test("Users", async t => {
const userListView = mount(
<Router history={browserHistory}>
<UserListView />
</Router>,
);
await waitForAllRequests(userListView);
debugWrapper(userListView, "UserListView");
t.snapshot(createSnapshotable(userListView), { id: "UserListView" });
});
test("Projects", async t => {
const projectListView = mount(
<Provider store={Store}>
<Router history={browserHistory}>
<ProjectListView />
</Router>
</Provider>,
);
await waitForAllRequests(projectListView);
t.is(projectListView.find(".TestProjectListView").length, 1);
debugWrapper(projectListView, "ProjectListView");
t.snapshot(createSnapshotable(projectListView), { id: "ProjectListView" });
});
|
JavaScript
| 0 |
@@ -981,79 +981,8 @@
/%3E);
-%0AmockRequire(%22c3%22, () =%3E %7B%7D);%0AmockRequire(%22react-c3js%22, () =%3E %3Cdiv /%3E);
%0A%0A//
|
5c441d54cc6f1d6f66cc84cf78e6b26b8cd00005
|
Add a reference to `window` on our fake-browser emulator
|
app/assets/javascripts/tests/helpers/global-dom.js
|
app/assets/javascripts/tests/helpers/global-dom.js
|
/**
* This module is a helper in order to test modules that requires DOM access
* such as globally available `window` or `document`.
*
* You should use it wrapping it around your `DOM`-dependent module. Example:
*
* ```js
* it('test feature', function() {
* const cleanup = require('../helpers/global-dom')('<html></html>', { url: '/sign_in' });
* const myModule = require('my-module');
*
* // Test myModule
*
* cleanup();
* })
* ```
*
* It **WILL NOT** work with `import` statement. If you want to use `import`,
* please, use as the following:
*
* ```js
* import cleanup from '../helpers/register-global-dom'
* import 'my-module'
*
* // ...
* ```
*
* The only drawback of using it like that is that you can't customize the HTML
* nor the URI that you want to stub. Also, the global variables will remain
* through all the script and you will have little control of them.
*/
module.exports = function globalJsDOM(html, options) {
const defaultHtml = `<!doctype html><html>
<head><meta charset="utf-8"></head>
<body></body></html>`;
const jsDomOptions = Object.assign({
url: `${process.env.BASE_URL}/index?query=1#hashstr`,
referrer: process.env.BASE_URL,
contentType: 'text/html',
userAgent: 'JSDOM',
includeNodeLocations: false,
}, options);
// Loads JSDOM and injects it globally
// eslint-disable-next-line global-require
const cleanup = require('jsdom-global')(html || defaultHtml, jsDomOptions);
// Set the document.domain, since JSDOM.url doesn't
document.domain = `${window.location.protocol}://${window.location.host}`;
return cleanup;
};
|
JavaScript
| 0 |
@@ -1616,16 +1616,116 @@
ost%7D%60;%0A%0A
+ // Add circular reference to have %60window%60 as an alias to the %60global%60 object%0A window = global;%0A%0A
return
|
31f4d23389abfd8070965ab7bd1912bbf6a30fb4
|
update link
|
test/client/scripts/public/titleCanvas.spec.js
|
test/client/scripts/public/titleCanvas.spec.js
|
'use strict';
import { expect } from 'chai';
import titleCanvas from '../../../../client/scripts/public/modules/titleCanvas';
describe('ARCADE MODE Canvas animation', () => {
const canvasObject = titleCanvas();
before(() => {
document.body.innerHTML =
'<a href="//arcademode.herokuapp.com" class="am__am__link"><div class="am__am__logo"><canvas class="am__am__canvas" height="50" width="220">ARCADE MODE</canvas><svg class="am__am__svg"><clipPath id="arcadePath"><text class="am__am__canvas__text" x="0" y="35">ARCADE MODE</text></clipPath></svg></div></a>';
canvasObject.init();
});
after(() => {
document.body.removeChild(document.querySelector('.am__am__link'));
});
it('should render', () => {
const canvasEl = document.querySelector('.am__am__canvas');
expect(canvasEl.height).to.equal(50);
expect(canvasEl.width).to.equal(220);
expect(canvasObject.hue).to.be.within(0, 360);
});
});
|
JavaScript
| 0 |
@@ -274,32 +274,42 @@
=%22//
-arcademode.herokuapp.com
+freecodecamp.github.io/arcade-mode
%22 cl
|
ce3c039d21e6e656eb14382be8724c4cb74b16db
|
Load config from ENV
|
app/instance-initializers/ember-ambitious-forms.js
|
app/instance-initializers/ember-ambitious-forms.js
|
export function initialize (appInstance) {
let emberAmbitiousForms = appInstance.lookup('service:ember-ambitious-forms')
emberAmbitiousForms.configure((config) => {
if (appInstance.hasRegistration('service:i18n')) {
config.fieldPlugins.push('i18n')
}
if (appInstance.hasRegistration('service:validations')) {
config.fieldPlugins.push('validations')
}
if ((typeof RESTless != 'undefined') && (RESTless instanceof Ember.Namespace)) {
config.fieldPlugins.push('restless')
}
})
}
export default {
name: 'ember-ambitious-forms',
initialize: initialize
}
|
JavaScript
| 0.000001 |
@@ -1,12 +1,82 @@
+import Ember from 'ember'%0Aimport config from '../config/environment'%0A%0A
export funct
@@ -192,52 +192,278 @@
)%0A
-emberAmbitiousForms.configure((config
+if (config%5B'ember-ambitious-forms'%5D) %7B%0A emberAmbitiousForms.configure(config%5B'ember-ambitious-forms'%5D)%0A %7D%0A%0A if (!Ember.get(config, 'ember-ambitious-forms.fieldPlugins')) %7B%0A // Detect plugins if they are not defined%0A emberAmbitiousForms.configure((eaf
) =%3E %7B%0A
+
@@ -511,38 +511,37 @@
i18n')) %7B%0A
-config
+ eaf
.fieldPlugins.pu
@@ -551,26 +551,30 @@
'i18n')%0A
+
+
%7D%0A
+
if (appI
@@ -621,38 +621,37 @@
ions')) %7B%0A
-config
+ eaf
.fieldPlugins.pu
@@ -668,26 +668,30 @@
tions')%0A
-%7D%0A
+ %7D%0A
if ((typ
@@ -769,22 +769,21 @@
%7B%0A
+
-config
+ eaf
.fieldPl
@@ -813,14 +813,22 @@
-%7D%0A %7D)
+ %7D%0A %7D)%0A %7D
%0A%7D%0A%0A
|
6da32069dc7de124ba05c266fdadab428c6e65c0
|
fix bug initialisation situation.hasImmoblier
|
app/js/controllers/foyer/captureImmobilierModal.js
|
app/js/controllers/foyer/captureImmobilierModal.js
|
'use strict';
angular.module('ddsApp').controller('FoyerCaptureImmobilierModalCtrl', function($scope, $modalInstance, situation, SituationService) {
$scope.situation = situation;
var conjointLabels = {
'mariage': 'conjoint',
'pacs': 'partenaire PACS',
'relation_libre': 'concubin',
};
$scope.debutPeriode = moment().startOf('month').subtract('years', 1).format('MMMM YYYY');
$scope.finPeriode = moment().startOf('month').subtract('months', 1).format('MMMM YYYY');
$scope.months = SituationService.getMonths();
$scope.revenusLocatifs = {
months: [
{montant: 0},
{montant: 0},
{montant: 0}
],
year: 0
};
$scope.revenusDuCapital = {
months: [
{montant: 0},
{montant: 0},
{montant: 0}
],
year: 0
};
$scope.situation.hasImmobilier = false;
$scope.situation.valeurLocativeImmoNonLoue = 0;
$scope.situation.valeurLocativeTerrainNonLoue = 0;
$scope.hasMobilier = false;
$scope.situation.mobilierValueLivret = 0;
$scope.situation.epargneSansRevenus = 0;
$scope.conjointLabel = function() {
return conjointLabels[$scope.situation.conjoint.relationType];
};
$scope.updateRevenusLocatifsYearAmount = function() {
var montants = _.map($scope.revenusLocatifs.months, function(month) {
return month.montant;
});
$scope.revenusLocatifs.year = Math.round(4 * _.reduce(montants, function(sum, num) {
return sum + num;
}));
};
$scope.submit = function(form) {
$scope.situation.immobilierCaptured = true;
$modalInstance.close();
};
});
|
JavaScript
| 0.000003 |
@@ -1040,16 +1040,26 @@
$scope.
+situation.
hasMobil
|
535ee9b4575d491f9f8727c6c7040b41b32b61e0
|
use new course field for context cards
|
app/jsx/context_cards/GraphQLStudentContextTray.js
|
app/jsx/context_cards/GraphQLStudentContextTray.js
|
/*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import $ from 'jquery'
import _ from 'underscore'
import React from 'react'
import StudentContextTray from './StudentContextTray'
import {client, ApolloProvider, Query, gql} from '../canvas-apollo'
const SCC_QUERY = gql`
query StudentContextCard($courseId: ID!, $studentId: ID!) {
course: legacyNode(type: Course, _id: $courseId) {
... on Course {
_id
name
permissions {
become_user: becomeUser
manage_grades: manageGrades
send_messages: sendMessages
view_all_grades: viewAllGrades
view_analytics: viewAnalytics
}
submissionsConnection(
first: 10
orderBy: [{field: gradedAt, direction: descending}]
studentIds: [$studentId]
) {
edges {
submission: node {
id
score
grade
excused
user {
_id
}
assignment {
name
html_url: htmlUrl
points_possible: pointsPossible
}
}
}
}
}
}
user: legacyNode(type: User, _id: $studentId) {
... on User {
_id
short_name: shortName
avatar_url: avatarUrl
enrollments(courseId: $courseId) {
last_activity_at: lastActivityAt
section {
name
}
grades {
current_grade: currentGrade
current_score: currentScore
}
}
analytics: summaryAnalytics(courseId: $courseId) {
page_views: pageViews {
total
max
level
}
participations {
total
max
level
}
tardiness_breakdown: tardinessBreakdown {
late
missing
on_time: onTime
}
}
}
}
}
`
export default props => {
return (
<ApolloProvider client={client}>
<Query query={SCC_QUERY} variables={{courseId: props.courseId, studentId: props.studentId}}>
{({data, loading}) => {
const {course, user} = data
return <StudentContextTray data={{loading, course, user}} {...props} />
}}
</Query>
</ApolloProvider>
)
}
|
JavaScript
| 0.000001 |
@@ -992,77 +992,26 @@
urse
-: legacyNode(type: Course, _id: $courseId) %7B%0A ... on Course %7B%0A
+(id: $courseId) %7B%0A
@@ -1012,26 +1012,24 @@
%7B%0A _id%0A
-
name%0A
@@ -1033,18 +1033,16 @@
e%0A
-
permissi
@@ -1043,26 +1043,24 @@
rmissions %7B%0A
-
beco
@@ -1087,18 +1087,16 @@
-
manage_g
@@ -1123,18 +1123,16 @@
-
-
send_mes
@@ -1151,18 +1151,16 @@
essages%0A
-
@@ -1194,26 +1194,24 @@
des%0A
-
-
view_analyti
@@ -1234,26 +1234,24 @@
s%0A
-
%7D%0A
submis
@@ -1238,26 +1238,24 @@
%7D%0A
-
-
submissionsC
@@ -1273,18 +1273,16 @@
-
first: 1
@@ -1283,18 +1283,16 @@
rst: 10%0A
-
@@ -1343,18 +1343,16 @@
nding%7D%5D%0A
-
@@ -1386,16 +1386,12 @@
-
) %7B%0A
-
@@ -1398,26 +1398,24 @@
edges %7B%0A
-
su
@@ -1431,18 +1431,16 @@
node %7B%0A
-
@@ -1462,18 +1462,14 @@
-
score%0A
-
@@ -1494,18 +1494,16 @@
-
excused%0A
@@ -1514,18 +1514,16 @@
-
-
user %7B%0A
@@ -1531,26 +1531,24 @@
-
_id%0A
@@ -1543,38 +1543,34 @@
_id%0A
-
-
%7D%0A
-
assi
@@ -1588,33 +1588,29 @@
-
-
name%0A
-
@@ -1643,18 +1643,16 @@
-
points_p
@@ -1679,24 +1679,8 @@
ble%0A
- %7D%0A
|
7ea0f43fdfcac38c7dc8fa3ba826c2ebf98d80e6
|
fix catch error in unit test
|
test/unit/specs/services/kuzzleWrapper.spec.js
|
test/unit/specs/services/kuzzleWrapper.spec.js
|
const kuzzleWrapperInjector = require('inject!../../../../src/services/kuzzleWrapper')
let sandbox = sinon.sandbox.create()
describe('Kuzzle wrapper service', () => {
describe('performSearch tests', () => {
let triggerError = true
let fakeResponse = {
total: 42,
documents: [{
content: {
name: {
first: 'toto'
}
},
id: 'id'
}]
}
let responseWithAdditionalAttr = {
documents: [{
content: {name: {first: 'toto'}},
id: 'id',
additionalAttribute: {name: 'name.first', value: 'toto'}
}],
total: 42
}
let kuzzleWrapper
beforeEach(() => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
dataCollectionFactory () {
return {
advancedSearch (filters, cb) {
if (triggerError) {
cb(new Error('error'))
} else {
cb(null, fakeResponse)
}
}
}
}
}
})
})
it('should reject a promise as there is no collection nor index', (done) => {
kuzzleWrapper.performSearch()
.then(() => {})
.catch(err => {
expect(err.message).to.equals('Missing collection or index')
done()
})
})
it('should reject a promise', (done) => {
kuzzleWrapper.performSearch('collection', 'index')
.then(() => {})
.catch(e => {
expect(e.message).to.equals('error')
done()
})
})
it('should receive documents', (done) => {
triggerError = false
kuzzleWrapper.performSearch('collection', 'index')
.then(res => {
expect(res).to.deep.equals(fakeResponse)
done()
}).catch(() => {})
})
it('should receive sorted documents with additional attributes for the sort array', (done) => {
triggerError = false
kuzzleWrapper.performSearch('collection', 'index', {}, {}, [{'name.first': 'asc'}])
.then(res => {
expect(res).to.deep.equals(responseWithAdditionalAttr)
done()
}).catch(() => {})
})
})
describe('deleteDocuments tests', () => {
let triggerError = true
let kuzzleWrapper
beforeEach(() => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
dataCollectionFactory () {
return {
deleteDocument (filters, cb) {
if (triggerError) {
cb(new Error('error'))
} else {
cb(null)
}
}
}
},
refreshIndex (index, cb) {
cb()
}
}
})
})
it('should do nothing if there is no ids nor index and collection', () => {
kuzzleWrapper.deleteDocuments()
})
it('should reject a promise', (done) => {
kuzzleWrapper.deleteDocuments('index', 'collection', [42])
.then(() => {})
.catch(e => {
expect(e.message).to.equals('error')
done()
})
})
it('should delete a document and refresh the index, then resolve a promise', (done) => {
triggerError = false
kuzzleWrapper.deleteDocuments('index', 'collection', [42])
.then(() => {
done()
})
})
})
describe('isConnected', () => {
let kuzzleWrapper
let removeListener = sandbox.stub()
it('should resolve if kuzzle is connected', (done) => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
state: 'connected'
}
})
kuzzleWrapper.isConnected()
.then(() => done())
.catch(e => done(e))
})
it('should resolve if kuzzle trigger event connected', (done) => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
state: 'connecting',
addListener (event, cb) {
cb()
},
removeListener
}
})
kuzzleWrapper.isConnected()
.then(() => {
expect(removeListener.called).to.be.equal(true)
done()
})
.catch(e => done(e))
})
it('should reject if kuzzle never trigger event connected', (done) => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
state: 'connecting',
addListener: sandbox.stub(),
removeListener
}
})
kuzzleWrapper.isConnected(10)
.then(() => {
done(new Error('Promise was resolved'))
})
.catch(() => done())
})
})
describe('initStoreWithKuzzle', () => {
let kuzzleWrapper
let removeAllListeners = sandbox.stub()
let setConnection = sandbox.stub()
let setTokenValid = sandbox.stub()
let setKuzzleHostPort = sandbox.stub()
it('should call removeListeners and addListeners with right params', () => {
kuzzleWrapper = kuzzleWrapperInjector({
'./kuzzle': {
host: 'toto',
wsPort: 8888,
state: 'connecting',
addListener (event, cb) {
cb()
},
removeAllListeners
},
'../vuex/modules/common/kuzzle/actions': {
setConnection,
setKuzzleHostPort
},
'../vuex/modules/auth/actions': {
setTokenValid
}
})
let store = {store: 'mystore'}
kuzzleWrapper.initStoreWithKuzzle(store)
expect(setKuzzleHostPort.calledWith(store, 'toto', 8888)).to.be.equal(true)
expect(removeAllListeners.calledWith('jwtTokenExpired'))
expect(removeAllListeners.calledWith('disconnected'))
expect(removeAllListeners.calledWith('reconnected'))
expect(setTokenValid.calledWithMatch(store, false))
expect(setConnection.calledWithMatch(store, true))
expect(setConnection.calledWithMatch(store, false))
})
})
})
|
JavaScript
| 0.000001 |
@@ -1808,32 +1808,41 @@
)%0A %7D)
+%0A
.catch((
) =%3E %7B%7D)%0A
@@ -1821,39 +1821,45 @@
.catch((
+e
) =%3E
-%7B%7D
+done(e)
)%0A %7D)%0A%0A it
|
519ecf682fcd5a3b862a6fa680492f93b79fe762
|
Update main.js
|
data/main.js
|
data/main.js
|
/*@pjs preload="data/images/logo1.png";*/
var sketchProc=function(processingInstance){ with (processingInstance){
//Setup
var wi = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth;
var he = window.innerHeight ||
document.documentElement.clientHeight ||
document.body.clientHeight;
size(wi*0.9,he*0.9);
frameRate(60);
setup = function() {
mainfont = createFont("Times New Roman");
logo = loadImage("data/images/logo1.png");
ismobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
keys = [];
pages = [];
page = 0;
chapter1 = [];
chapter1pages = [];
chapter1length = 6;
chapter2 = [];
chapter2pages = [];
m = false;
md = false;
flevel = 255;
bw = width/6;
bh = width/12;
prim = color(15,15,15);
sec = color(100,30,30);
tert = color(150,150,150);
backg = color(55,55,55);
// Standard fade in.
fade = function() {
flevel -= 10;
fill(55,55,55,flevel);
noStroke();
rectMode(CORNER);
rect(-1,-1,width+1,height+1);
};
// Loads all panels in the named folder into the target array.
loadpanels = function(name,number,target) {
for (i = 0; i < number;) {
target[i] = loadImage("data/images/panels/"+name+i+".png");
i ++;
}
};
// The array of data for buttons used.
buttons = {
start:{x:width*(3/4),y:height/2,w:bw,h:bh,text:"Enter"},
next:{x:width*(8/9),y:height*(1/2),w:bw,h:bh,text:"Next"},
prev:{x:width*(1/9),y:height*(1/2),w:bw,h:bh,text:"Previous"},
};
// The hefty button function. Works on all platforms tested. Needs an exterior click call.
button = function(con) {
bux = con.x
buy = con.y
buw = con.w
buh = con.h
butext = con.text
con.pressed = false;
mouseover = false;
rectMode(CENTER);
if (mouseX>bux-buw/2&&mouseX<bux+buw/2 && mouseY>buy-buh/2&&mouseY<buy+buh/2) {
mouseover = true;
}
if (mouseover) {
fill(prim);
} else {
fill(sec);
}
stroke(prim);
strokeWeight(buh/10);
rect(bux,buy,buw,buh,buh/2.5);
if (mouseover) {
fill(sec);
} else {
fill(prim);
}
textFont(mainfont,buh/2);
if (ismobile) {
textSize(buh/3);
}
textAlign(CENTER,CENTER);
text(butext,bux,buy);
if (ismobile && mouseover) {
con.pressed = true;
return con.pressed;
}
if (mouseover && m) {
con.pressed = true;
return con.pressed;
}
return con.pressed;
};
// Standard button layout
standardbuttons = function() {
button(buttons.next);
if (buttons.next.pressed) {
if (ismobile) {
if (flevel < 0) {
page += 1;
flevel = 255;
}
} else if (flevel < 80) {
page += 1;
flevel = 255;
}
};
button(buttons.prev);
if (buttons.prev.pressed) {
if (ismobile) {
if (flevel < 0) {
page -= 1;
flevel = 255;
}
} else if (flevel < 80) {
page -= 1;
flevel = 255;
}
};
};
// Displays an image properly.
displaypanel = function(img,x,y) {
imageMode(CENTER);
pushMatrix();
translate(x,y);
scale(0.001*height,0.001*height);
image(img,0,0);
popMatrix();
};
// Creates a full page
displaypage = function(chap,number) {
background(backg);
displaypanel(chap[number],width/2,height/2);
standardbuttons();
fade();
};
// Loads an array with full pages
loadpages = function(cha,targ) {
for (i = 0; i < cha.length; i ++) {
targ.push(function() {fcha= cha; fi= i; displaypage(fcha,fi)});
};
targ[cha.length] = function() {
background(backg);
textSize(height/5);
fill(sec);
text("Under Construction",width/2,height/2);
};
};
loadpanels("chap1/",chapter1length,chapter1);
pages = [
function() {
background(backg)
displaypanel(logo,width/4,height/2)
button(buttons.start)
if (buttons.start.pressed==true) {
page += 1
}
},
];
loadpages(chapter1,pages);
};
draw = function() {
pages[page]();
textSize(17);
text(pages[2],width/2,height/2);
};
keyPressed = function() {
keys[keyCode] = true;
};
keyReleased = function() {
keys[keyCode] = false;
};
mousePressed = function() {
m = true;
};
mouseReleased = function() {
m = false;
};
}};
|
JavaScript
| 0.000001 |
@@ -3398,26 +3398,8 @@
() %7B
-fcha= cha; fi= i;
disp
@@ -3410,15 +3410,20 @@
age(
-f
cha
-,fi
+p1,page-1
)%7D);
|
8d8ee0151e43096d7cce5ffb52d3cb4882d10d27
|
Improve centering of map on Seattle.
|
seattle_example/center.js
|
seattle_example/center.js
|
var center = [47.610913, -122.330413];
|
JavaScript
| 0 |
@@ -15,25 +15,24 @@
47.6
-10913,
+07181,
-122.33
-0413
+7226
%5D;%0A
|
891c6bfbea73d84d232254b06f63abe23abb0a05
|
removed unneccesary semicolon
|
functions/attachBoundWindowListener/rendition1.js
|
functions/attachBoundWindowListener/rendition1.js
|
/*global attachBoundWindowListener:true,bind,attachWindowListener */
if(attachWindowListener && bind) {
attachBoundWindowListener = function(eventType, fn, thisObject) {
var listener = bind(fn, thisObject);
return attachWindowListener(eventType, listener);
};
};
|
JavaScript
| 0.998061 |
@@ -260,9 +260,8 @@
);%0A%09%7D;%0A%7D
-;
|
4aee5e505cf421b751fb401c97b99b2fe9c78209
|
allow updates
|
server/collectionRules.js
|
server/collectionRules.js
|
define('collectionRules', ['collections'], function(collections) {
'use strict';
var anyInsert = {
insert: function(userId, doc) {
return true;
}
}
// currently no restrictions on creating sessions or workItems
collections.sessions.allow(anyInsert);
collections.workItems.allow(anyInsert);
function isValidEstimate(value) {
return _.isFinite(value) && value >= 0;
};
collections.estimates.allow({
insert: function(userId, doc) {
return isValidEstimate(doc.value);
},
update: function(userId, doc, fields, modifer) {
// TODO
return true;
}
});
function isNonBlankString(value) {
return _.isString(value) && value.replace(/ /g, '').length > 0;
}
collections.users.allow({
insert: function(userId, doc) {
return isNonBlankString(doc.name);
},
update: function(userId, doc, fields, modifer) {
// TODO
return true;
}
});
return null;
});
|
JavaScript
| 0 |
@@ -92,16 +92,24 @@
nyInsert
+OrUpdate
= %7B%0A
@@ -132,38 +132,84 @@
n(userId, doc) %7B
-%0A
+ return true; %7D,%0A update: function(userId, doc) %7B
return true;%0A
@@ -205,20 +205,16 @@
rn true;
-%0A
%7D%0A %7D%0A%0A
@@ -316,16 +316,24 @@
nyInsert
+OrUpdate
);%0A col
@@ -366,16 +366,24 @@
nyInsert
+OrUpdate
);%0A%0A fu
|
69c5a6867154a9c4e334a306460a718e7f2ca714
|
fix pretty printing
|
bin/gest.js
|
bin/gest.js
|
#! /usr/bin/env node
// Native
const path = require('path')
// Packages
const args = require('args')
const chalk = require('chalk')
const ora = require('ora')
// Ours
const gest = require('../src/index')
const REPL = require('../src/REPL')
const {
readFile,
checkPath,
flagsToOptions,
colorResponse,
colorizeGraphQL,
readDir,
errorMessage
} = require('../src/util')
const { getGraphQL, getPackageInfo } = require('../src/import')
const GraphQL = getGraphQL()
args
.option(['S', 'schema'], 'Path to your GraphQL schema')
.option(['H', 'header'], 'Set HTTP request header')
.option(['I', 'inspect'], 'Print your GraphQL schema types')
.option(['B', 'baseUrl'], 'Base URL for sending HTTP requests')
.option(['A', 'all'], 'Run `gest` for all *.(gql|graphql|query) files')
.option(['P', 'print'], 'Pretty print the GraphQL query')
const flags = args.parse(process.argv, {
value: '[query | queryPath]',
mainColor: ['magenta', 'bold'], // following the GraphQL brand
usageFilter: info => info.replace('[command] ', '')
})
const getQueryString = q =>
checkPath(path.join(process.cwd(), q))
.then(readFile)
.catch(() => q)
const wrapLogging = p => p.then(message => console.log(`\n${message}`)).catch(console.log)
try {
let schema
const options = Object.assign({ schema: 'schema.js' }, getPackageInfo(), flagsToOptions(flags))
try {
schema = require(path.join(process.cwd(), options.schema))
} catch (e) {
// schema is required unless sending over HTTP
if (!options.baseURL) throw e
}
if (flags.inspect) {
console.log('\n' + colorizeGraphQL(GraphQL.printSchema(schema)))
process.exit()
}
if (flags.all) {
readDir(process.cwd(), /.*\.(query|graphql|gql)$/i)
.then(values => {
if (!values.length) {
console.log(
`\n${chalk.yellow('Warning')}: no files matching *.(graphql|gql|query) were found`
)
} else {
console.log()
}
return values
})
.then(values =>
Promise.all(
values.map(v => {
const paths = v.replace(process.cwd(), '.').split('/')
// separate file from rest of path
const fileName = paths.pop()
const rep = chalk.dim(paths.concat('').join('/')).concat(fileName)
const spinner = ora({ text: rep, color: 'magenta' }).start()
return readFile(v)
.then(gest(schema, Object.assign(options, { verbose: false })))
.then(value => {
if (value.errors && value.data) spinner.warn()
else if (value.errors) spinner.fail(`${rep}\n - ${value.errors}`)
else spinner.succeed()
return value
})
.catch(console.log)
})
)
)
.then(() => console.log())
.catch(console.log)
} else {
if (args.sub && args.sub.length) {
if (flags.print) {
const q = args.sub[0] // only print first value
wrapLogging(
getQueryString(q)
.then(GraphQL.parse)
.then(GraphQL.print)
)
} else {
args.sub.map(q =>
wrapLogging(
getQueryString(q)
.then(gest(schema, options))
.then(colorResponse)
.then(message => `${message}\n`)
)
)
}
} else {
// Open REPL
REPL(schema, options)
}
}
} catch (e) {
console.log(errorMessage(e))
}
|
JavaScript
| 0.000003 |
@@ -2892,49 +2892,8 @@
e %7B%0A
- if (args.sub && args.sub.length) %7B%0A
@@ -2907,26 +2907,24 @@
gs.print) %7B%0A
-
const
@@ -2943,41 +2943,35 @@
%5B0%5D
-// only print first value
+%7C%7C flags.print
%0A
-
+return
wra
@@ -2980,34 +2980,32 @@
ogging(%0A
-
-
getQueryString(q
@@ -2998,34 +2998,32 @@
tQueryString(q)%0A
-
.then(
@@ -3039,34 +3039,32 @@
arse)%0A
-
-
.then(GraphQL.pr
@@ -3078,29 +3078,55 @@
- )%0A %7D else
+)%0A %7D%0A if (args.sub && args.sub.length)
%7B%0A
-
@@ -3153,18 +3153,16 @@
-
-
wrapLogg
@@ -3162,26 +3162,24 @@
rapLogging(%0A
-
ge
@@ -3198,34 +3198,32 @@
(q)%0A
-
-
.then(gest(schem
@@ -3243,26 +3243,24 @@
-
.then(colorR
@@ -3264,26 +3264,24 @@
orResponse)%0A
-
@@ -3313,28 +3313,16 @@
ge%7D%5Cn%60)%0A
- )%0A
@@ -3325,25 +3325,25 @@
)%0A
-%7D
+)
%0A %7D else
|
4d5d94f69a66faad61cb4c0e743204897bd5de59
|
Update Plugwoot.js
|
Autowoot.js/Plugwoot.js
|
Autowoot.js/Plugwoot.js
|
/*
Copyright (c) 2012-2013 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL
Permission to use this software for any purpose without fee is hereby granted, provided
that the above copyright notice and this permission notice appear in all copies.
Permission to copy and/or edit this software or parts of it for any purpose is permitted,
provided that the following points are followed.
- The above copyright notice and this permission notice appear in all copies
- Within two (2) days after modification is proven working, any modifications are send back
to the original authors to be inspected with the goal of inclusion in the official software
- Any edited version are only test versions and not permitted to be run as a final product
- Any edited version aren't to be distributed
- Any edited version have the prerelease version set to something that can be distinguished
from a version used in the original software
TERMS OF REPRODUCTION USE
Failure to follow these terms will result in me getting very angry at you
and having your software tweaked or removed if possible. Either way, you're
still an idiot for not following such a basic rule.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
* NOTE: PLEASE CONTACT DJ-NEON FOR THIS SCRIPT (DO NOT CHANGE ANYTHING ON THIS SCRIPT OR USE AND EDIT THIS SCRIPT WHICH
* WAS WRITTEN BY IT'S RIGHTFUL OWNER: DJ NOEN)
*
* @Author: Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)
*
*/
var path = 'http://pastebin.com/raw.php?i=';
function message(contents) {
var msg = '<div class="message"><i class="icon icon-chat-admin"></i><span class="from admin ">PlugWoot </span><span class="text"> ' + contents + '</span></div>';
$('#chat-messages').append(msg);
}
var scriptFail = window.setTimeout(function() {
message('Oops! An Error Occurred');
}, 2000);
$.getScript(path + 'rM15aY1b' , function() {message("PlugWoot V."+ pw.version+" is now available!");
window.clearTimeout(scriptFail);
});
|
JavaScript
| 0 |
@@ -2356,19 +2356,9 @@
ge(%22
-PlugWoot V.
+v
%22+ p
|
ad6d1bd2c81640088e7f9cc3c627ae20e8e39073
|
add MSMoment to flow globals
|
flow-typed/sketch.js
|
flow-typed/sketch.js
|
/* @flow */
declare var CGAffineTransformConcat: any;
declare var CGAffineTransformMakeRotation: any;
declare var CGAffineTransformMakeScale: any;
declare var CGAffineTransformMakeTranslation: any;
declare var CGSizeMake: any;
declare var COSAlertWindow: any;
declare var MSArtboardGroup: any
declare var MSAttributedString: any;;
declare var MSColor: any;
declare var MSImageData: any;
declare var MSJSONDataArchiver;
declare var MSLayerGroup: any;
declare var MSOvalShape: any;
declare var MSRect: any;
declare var MSRectangleShape: any;
declare var MSShapeGroup: any;
declare var MSTextLayer: any;
declare var NSAttributedString: any;
declare var NSArray: any;
declare var NSColor: any;
declare var NSDataBase64EncodingEndLineWithCarriageReturn: any;
declare var NSDate: any;
declare var NSFontCondensedTrait: any;
declare var NSFontItalicTrait: any;
declare var NSFontManager: any;
declare var NSFontSymbolicTrait: any;
declare var NSFontTraitsAttribute: any;
declare var NSFontWeightBlack: any;
declare var NSFontWeightBold: any;
declare var NSFontWeightHeavy: any;
declare var NSFontWeightLight: any;
declare var NSFontWeightMedium: any;
declare var NSFontWeightRegular: any;
declare var NSFontWeightSemibold: any;
declare var NSFontWeightThin: any;
declare var NSFontWeightTrait: any;
declare var NSFontWeightUltraLight: any;
declare var NSFont: any;
declare var NSFontAttributeName: any;
declare var NSImage: any;
declare var NSKernAttributeName: any;
declare var NSMakeRect: any;
declare var NSMutableParagraphStyle: any;
declare var NSParagraphStyleAttributeName: any;
declare var NSString: any;
declare var NSStringDrawingUsesLineFragmentOrigin: any;
declare var NSTextField: any;
declare var NSTextView: any;
declare var NSURL: any;
declare var NSView: any;
declare var log: any;
|
JavaScript
| 0 |
@@ -436,32 +436,59 @@
ayerGroup: any;%0A
+declare var MSMoment: any;%0A
declare var MSOv
|
3b867589649972d9720a376e26c1a10bfea534ac
|
Fix load method response for csv time in columns reader
|
src/readers/csv-time_in_columns/csv-time_in_columns.js
|
src/readers/csv-time_in_columns/csv-time_in_columns.js
|
import CSVReader from 'readers/csv/csv';
import { isNumber } from 'base/utils';
const CSVTimeInColumnsReader = CSVReader.extend({
_name: 'csv-time_in_columns',
init(readerInfo) {
this._super(readerInfo);
},
load() {
return this._super()
.then(({ data, columns }) => {
const indicatorKey = columns[this.keySize];
const concepts = data.reduce((result, row) => {
Object.keys(row).forEach((concept) => {
concept = concept === indicatorKey ? row[indicatorKey] : concept;
if (Number(concept) != concept && !result.includes(concept)) {
result.push(concept);
}
});
return result;
}, []).concat('time');
const indicators = concepts.slice(1, -1);
const [entityDomain] = concepts;
return data.reduce((result, row) => {
Object.keys(row).forEach((key) => {
if (![entityDomain, indicatorKey].includes(key)) {
result.push(
Object.assign({
[entityDomain]: row[entityDomain],
time: key,
}, indicators.reduce((result, indicator) => {
result[indicator] = row[indicatorKey] === indicator ? row[key] : null;
return result;
}, {})
)
);
}
});
return result;
}, []);
});
}
});
export default CSVTimeInColumnsReader;
|
JavaScript
| 0.000001 |
@@ -348,20 +348,18 @@
-cons
+le
t concep
@@ -706,16 +706,40 @@
%5B%5D)
-.concat(
+;%0A concepts.splice(1, 0,
'tim
@@ -790,13 +790,9 @@
ice(
-1, -1
+2
);%0A
@@ -845,16 +845,63 @@
return
+ %7B%0A columns: concepts,%0A data:
data.re
@@ -926,32 +926,34 @@
=%3E %7B%0A
+
+
Object.keys(row)
@@ -968,24 +968,26 @@
((key) =%3E %7B%0A
+
@@ -1043,32 +1043,34 @@
%7B%0A
+
+
result.push(%0A
@@ -1066,16 +1066,18 @@
t.push(%0A
+
@@ -1100,16 +1100,18 @@
ssign(%7B%0A
+
@@ -1157,16 +1157,18 @@
omain%5D,%0A
+
@@ -1208,16 +1208,18 @@
+
%7D, indic
@@ -1252,24 +1252,26 @@
cator) =%3E %7B%0A
+
@@ -1361,32 +1361,34 @@
+
return result;%0A
@@ -1378,32 +1378,34 @@
return result;%0A
+
@@ -1429,18 +1429,22 @@
-)%0A
+ )%0A
@@ -1456,32 +1456,34 @@
);%0A
+
%7D%0A %7D);%0A
@@ -1470,37 +1470,41 @@
%7D%0A
+
+
%7D);%0A%0A
+
return
@@ -1512,38 +1512,50 @@
result;%0A
+
%7D, %5B%5D)
+%0A %7D
;%0A %7D);%0A %7D%0A
|
310aa7a65e43345d7e27038314a2e21f6499dd0c
|
add typescript support
|
bin/lint.js
|
bin/lint.js
|
#!/usr/bin/env node
const yargs = require('yargs')
const execSync = require('child_process').execSync
const argv = yargs.usage('Usage: $0 [options]').option('fix', {
describe: 'auto-fix problems',
type: 'boolean',
}).argv
function exec(command) {
try {
execSync(command, {stdio: 'inherit'})
return true
} catch (err) {
process.stderr.write(err.message + '\n')
return false
}
}
const lintFixArg = argv.fix ? '--fix' : ''
const lintPassed = exec(`eslint ${lintFixArg} .`)
const prettierFixArg = argv.fix ? '--write' : '--list-different'
const prettierPassed = exec(`prettier ${prettierFixArg} '**/*.{ts,css,scss,md}'`)
process.exit(lintPassed && prettierPassed ? 0 : 1)
|
JavaScript
| 0 |
@@ -14,16 +14,41 @@
v node%0A%0A
+const fs = require('fs')%0A
const ya
@@ -247,16 +247,153 @@
).argv%0A%0A
+const IS_TYPESCRIPT =%0A fs.existsSync('tsconfig.json') %7C%7C%0A fs.existsSync('../tsconfig.json') %7C%7C%0A fs.existsSync('../../tsconfig.json')%0A%0A
function
@@ -572,44 +572,206 @@
nst
-lintFixArg = argv.fix ? '--fix' : ''
+directories = %60?(packages/*/)%7Bsrc/**/,lib/**/,bin/**/,test/**/,./%7D%60%0A%0Aconst lintFixArg = argv.fix ? '--fix' : ''%0Aconst lintCommand = IS_TYPESCRIPT ? %60tslint --project .%60 : %60eslint $%7Bdirectories%7D*.js%60
%0Acon
@@ -792,22 +792,30 @@
= exec(%60
-es
+$%7B
lint
+Command%7D
$%7BlintF
@@ -820,18 +820,16 @@
tFixArg%7D
- .
%60)%0Aconst
@@ -945,19 +945,30 @@
ixArg%7D '
-**/
+$%7Bdirectories%7D
*.%7Bts,cs
|
2130c968aa223305ed3f95891c85fd71f6119eba
|
Update mailer.js
|
server/services/mailer.js
|
server/services/mailer.js
|
/*
Framework for building object relational database apps
Copyright (C) 2021 John Rogelstad
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/*jslint node devel*/
/**
@module Email
*/
(function (exports) {
"use strict";
const fs = require("fs");
const {PDF} = require("./pdf");
const {Config} = require("../config");
const config = new Config();
const pdf = new PDF();
const nodemailer = require("nodemailer");
let smtp;
config.read().then(function (resp) {
smtp = {
auth: {
password: resp.smtpAuthPassword,
user: resp.smtpAuthUser
},
host: resp.smtpHost,
port: resp.smtpPort,
secure: resp.smtpSecure
};
});
/**
@class Email
@constructor
@namespace Services
*/
exports.Mail = function () {
// ..........................................................
// PRIVATE
//
let that = {};
// ..........................................................
// PUBLIC
//
/**
Send an email message with an optional Pdf attached.
@method send
@param {Object} Request payload
@param {Object} payload.data Payload data
@param {Object} payload.data.message Message data
@param {String} payload.data.message.from From address
@param {String} payload.data.message.to To address
@param {String} [payload.data.message.cc] Cc address
@param {String} [payload.data.message.bcc] Bcc address
@param {String} payload.data.message.subject Subject
@param {String} [payload.data.message.text] Message text
@param {String} [payload.data.message.html] Message html
@param {Object} [payload.data.pdf] PDF Generation data (optional)
@param {String} [payload.data.pdf.form] Form name
@param {String|Array} [payload.data.pdf.ids] Record id or ids
@param {filename} [payload.data.pdf.filename] Name of attachement
@param {Object} payload.client Database client
@return {Object} Promise
*/
that.sendMail = function (obj) {
return new Promise(function (resolve, reject) {
let message = obj.data.message;
let opts = obj.data.pdf;
function cleanup() {
fs.unlink(message.attachments.path, function (err) {
if (err) {
reject(err);
return;
}
resolve();
});
}
function attachPdf(resp) {
return new Promise(function (resolve) {
message.attachments = {
path: "./files/downloads/" + resp
};
resolve();
});
}
function sendMail() {
return new Promise(function (resolve, reject) {
let transporter = nodemailer.createTransport(smtp);
transporter.sendMail(
message
).then(
resolve
).catch(
reject
);
});
}
if (opts) {
pdf.printForm(
obj.client,
opts.form,
opts.ids,
opts.filename
).then(
attachPdf
).then(
sendMail
).then(
cleanup
).catch(
reject
);
} else {
sendMail().then(resolve).catch(reject);
}
});
};
return that;
};
}(exports));
|
JavaScript
| 0.000001 |
@@ -1188,20 +1188,16 @@
pass
-word
: resp.s
@@ -1211,12 +1211,8 @@
Pass
-word
,%0A
|
43a5a71abe563b80e4f3750d2f61dbc1ec145ed4
|
Update consentVersionService.js
|
src/services/consent/services/consentVersionService.js
|
src/services/consent/services/consentVersionService.js
|
const { authenticate } = require('@feathersjs/authentication');
const { BadRequest } = require('@feathersjs/errors');
const {
iff,
isProvider,
disallow,
} = require('feathers-hooks-common');
const {
populateCurrentSchool,
restrictToCurrentSchool,
hasPermission,
} = require('../../../hooks');
const { modelServices: { prepareInternalParams } } = require('../../../utils');
const ConsentVersionServiceHooks = {
before: {
all: [iff(isProvider('external'), [
authenticate('jwt'),
populateCurrentSchool, // TODO: test if it is needed
restrictToCurrentSchool, // TODO restricted erscheint mir hier nicht hilfreich
])],
find: [],
get: [],
create: [iff(isProvider('external'), hasPermission('SCHOOL_EDIT'))],
update: [disallow()],
patch: [disallow()],
remove: [disallow()],
},
after: {
all: [],
find: [],
get: [],
create: [],
update: [],
patch: [],
remove: [],
},
};
class ConsentVersionService {
constructor(options) {
this.options = options || {};
this.docs = {};
}
createBase64File(data = {}) {
const { schoolId, consentData } = data;
if (consentData) {
if (!schoolId) {
return Promise.reject(new BadRequest('SchoolId is required for school consents.'));
}
return this.app.service('base64Files').create({
schoolId,
data: consentData,
fileType: 'pdf',
filename: 'Datenschutzerklärung',
});
}
return Promise.resolve({});
}
get(id, params) {
return this.app.service('consentVersionsModel').get(id, prepareInternalParams(params));
}
find(params) {
const { query } = params;
if (query && query.schoolId) {
if (!query.$or) {
query.$or = [];
}
query.$or.push({ schoolId: query.schoolId });
delete query.schoolId;
}
return this.app.service('consentVersionsModel').find(prepareInternalParams(params));
}
async create(data, params) {
const base64 = await this.createBase64File(data);
if (base64._id) {
data.consentDataId = base64._id;
delete data.consentData;
}
return this.app.service('consentVersionsModel').create(data, prepareInternalParams(params));
}
setup(app) {
this.app = app;
}
}
module.exports = {
ConsentVersionService,
ConsentVersionServiceHooks,
};
|
JavaScript
| 0 |
@@ -1318,17 +1318,17 @@
%09%09%09%09file
-T
+t
ype: 'pd
|
a372a6631af06e415b907ba924555e2237daf21c
|
fix number of blocks
|
algorea_training/training-repeat-if-paint/task.js
|
algorea_training/training-repeat-if-paint/task.js
|
function initTask(subTask) {
var cellSide = 60;
subTask.gridInfos = {
hideSaveOrLoad: true,
cellSide: cellSide,
actionDelay: 200,
itemTypes: {
green_robot: { img: "green_robot.png", side: 80, nbStates: 9, isObstacle: true, offsetX: -14, category: "robot", team: 0, zOrder: 2 },
paint: { img: "paint.png", side: cellSide, category: "paint", isPaint: true, isObstacle: false, hasColor: true, color: "gris", zOrder: 1 },
marker: { num: 2, img: "marker.png", side: cellSide, category: "marker", isObstacle: false, isMarker: true, zOrder: 0 }
},
maxInstructions: 10,
includeBlocks: {
groupByCategory: false,
generatedBlocks: {
robot: ["east", "north", "south", "paint", "markedCell"]
},
standardBlocks: {
includeAll: false,
wholeCategories: [],
singleBlocks: {
shared: ["controls_repeat", "controls_if"],
easy: [],
medium: [],
hard: ["controls_if_else"]
}
}
},
ignoreInvalidMoves: false,
checkEndEveryTurn: false,
checkEndCondition: robotEndConditions.checkMarkersPainted
};
subTask.data = {
easy: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 2, 2, 1, 1, 2, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 1, col: 0, dir: 0, type: "green_robot" }
]
}
],
medium: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 2, col: 0, dir: 0, type: "green_robot" }
]
}
],
hard: [
{
tiles: [
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1],
[1, 1, 1, 2, 1, 1, 2, 1, 2, 1, 1, 1, 2, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 2, 1],
[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
],
initItems: [
{ row: 2, col: 0, dir: 0, type: "green_robot" }
]
}
]
};
initBlocklySubTask(subTask);
displayHelper.thresholdEasy = 5000;
displayHelper.thresholdMedium = 10000;
}
initWrapper(initTask, ["easy", "medium", "hard"], null, true);
|
JavaScript
| 0.000023 |
@@ -621,18 +621,48 @@
ctions:
-10
+%7Beasy: 10, medium: 10, hard: 18%7D
,%0A
|
aac63669930a2f54b77321bad88a54bf3538660d
|
Improve file handling
|
src/ActionService.js
|
src/ActionService.js
|
const actions = {};
const MODULE_NAME_REGEXP = /^.\/(.*)\.js/;
const ActionService = {
registerFromRequireContext: function (ctx)
{
const modules = ctx.keys();
for (let i = 0; i < modules.length; i++)
{
const moduleName = modules[i];
let handler = ctx(moduleName);
if (typeof handler !== "function")
{
throw new Error("Action module '" + moduleName + "' does not export a function");
}
const actionName = moduleName.replace(MODULE_NAME_REGEXP, "$1");
ActionService.register(actionName, handler);
}
},
register: function (actionName, handler)
{
//console.log("Register" , actionName , "to", handler);
actions[actionName] = handler;
},
lookup: function(actionName)
{
let handler = actions[actionName];
//console.log("Lookup", actionName , "=>", handler);
return handler;
}
};
module.exports = ActionService;
|
JavaScript
| 0 |
@@ -55,16 +55,17 @@
(.*)%5C.js
+$
/;%0A%0Acons
@@ -516,67 +516,86 @@
nst
-actionName = moduleName.replace(MODULE_NAME_REGEXP, %22$1%22);%0A
+m = MODULE_NAME_REGEXP.exec(moduleName);%0A if (m)%0A %7B%0A
@@ -625,26 +625,20 @@
egister(
-actionName
+m%5B1%5D
, handle
@@ -633,32 +633,46 @@
m%5B1%5D, handler);%0A
+ %7D%0A
%7D%0A %7D,
|
2b07a395f51ca88f68002380bd87c228d86c2f2e
|
fix date picker: remove console log
|
modules/date-picker/js/date-picker_directive.js
|
modules/date-picker/js/date-picker_directive.js
|
/* global angular */
/* global moment */
/* global navigator */
'use strict'; // jshint ignore:line
angular.module('lumx.date-picker', [])
.controller('lxDatePickerController', ['$scope', '$timeout', '$window', function($scope, $timeout, $window)
{
var self = this,
activeLocale,
$datePicker,
$datePickerFilter,
$datePickerContainer,
$computedWindow;
$scope.ctrlData = {
isOpen: false
};
this.init = function(element, locale)
{
$datePicker = element.find('.lx-date-picker');
$datePickerContainer = element;
$computedWindow = angular.element($window);
self.build(locale, false);
};
this.build = function(locale, isNewModel)
{
if (locale === activeLocale && !isNewModel)
{
return;
}
activeLocale = locale;
moment.locale(activeLocale);
if (angular.isDefined($scope.model))
{
$scope.selected = {
model: moment($scope.model).format('LL'),
date: $scope.model
};
$scope.activeDate = moment($scope.model);
}
else
{
$scope.selected = {
model: undefined,
date: new Date()
};
$scope.activeDate = moment();
}
$scope.moment = moment;
$scope.days = [];
$scope.daysOfWeek = [moment.weekdaysMin(1), moment.weekdaysMin(2), moment.weekdaysMin(3), moment.weekdaysMin(4), moment.weekdaysMin(5), moment.weekdaysMin(6), moment.weekdaysMin(0)];
$scope.years = [];
for (var y = moment().year() - 100; y <= moment().year() + 100; y++)
{
$scope.years.push(y);
}
generateCalendar();
};
$scope.previousMonth = function()
{
$scope.activeDate = $scope.activeDate.subtract(1, 'month');
generateCalendar();
};
$scope.nextMonth = function()
{
$scope.activeDate = $scope.activeDate.add(1, 'month');
generateCalendar();
};
$scope.select = function(day)
{
$scope.selected = {
model: day.format('LL'),
date: day.toDate()
};
$scope.model = day.toDate();
generateCalendar();
};
$scope.selectYear = function(year)
{
$scope.yearSelection = false;
$scope.selected.model = moment($scope.selected.date).year(year).format('LL');
$scope.selected.date = moment($scope.selected.date).year(year).toDate();
$scope.model = moment($scope.selected.date).toDate();
$scope.activeDate = $scope.activeDate.add(year - $scope.activeDate.year(), 'year');
generateCalendar();
};
$scope.openPicker = function()
{
if ($scope.ctrlData.isOpen)
{
return;
}
$scope.ctrlData.isOpen = true;
$timeout(function()
{
$scope.yearSelection = false;
$datePickerFilter = angular.element('<div/>', {
class: 'lx-date-filter'
});
$datePickerFilter
.appendTo('body')
.on('click', function()
{
$scope.closePicker();
});
$datePicker
.appendTo('body')
.show();
$timeout(function()
{
$datePickerFilter.addClass('lx-date-filter--is-shown');
$datePicker.addClass('lx-date-picker--is-shown');
}, 100);
});
};
$scope.closePicker = function()
{
if (!$scope.ctrlData.isOpen)
{
return;
}
$datePickerFilter.removeClass('lx-date-filter--is-shown');
$datePicker.removeClass('lx-date-picker--is-shown');
$computedWindow.off('resize');
$timeout(function()
{
$datePickerFilter.remove();
$datePicker
.hide()
.appendTo($datePickerContainer);
$scope.ctrlData.isOpen = false;
}, 600);
};
$scope.displayYearSelection = function()
{
$scope.yearSelection = true;
$timeout(function()
{
var $yearSelector = $datePicker.find('.lx-date-picker__year-selector');
var $activeYear = $yearSelector.find('.lx-date-picker__year--is-active');
console.log($activeYear, $yearSelector.scrollTop(), $activeYear.position().top, $yearSelector.height(), $activeYear.height());
$yearSelector.scrollTop($yearSelector.scrollTop() + $activeYear.position().top - $yearSelector.height()/2 + $activeYear.height()/2);
});
};
$scope.clearDate = function()
{
$scope.model = undefined;
};
function generateCalendar()
{
var days = [],
previousDay = angular.copy($scope.activeDate).date(0),
firstDayOfMonth = angular.copy($scope.activeDate).date(1),
lastDayOfMonth = angular.copy(firstDayOfMonth).endOf('month'),
maxDays = angular.copy(lastDayOfMonth).date();
$scope.emptyFirstDays = [];
for (var i = firstDayOfMonth.day() === 0 ? 6 : firstDayOfMonth.day() - 1; i > 0; i--)
{
$scope.emptyFirstDays.push({});
}
for (var j = 0; j < maxDays; j++)
{
var date = angular.copy(previousDay.add(1, 'days'));
date.selected = angular.isDefined($scope.selected.model) && date.isSame($scope.selected.date, 'day');
date.today = date.isSame(moment(), 'day');
days.push(date);
}
$scope.emptyLastDays = [];
for (var k = 7 - (lastDayOfMonth.day() === 0 ? 7 : lastDayOfMonth.day()); k > 0; k--)
{
$scope.emptyLastDays.push({});
}
$scope.days = days;
}
}])
.directive('lxDatePicker', function()
{
return {
restrict: 'AE',
controller: 'lxDatePickerController',
scope: {
model: '=',
label: '@',
fixedLabel: '&',
allowClear: '@',
icon: '@'
},
templateUrl: 'date-picker.html',
link: function(scope, element, attrs, ctrl)
{
ctrl.init(element, checkLocale(attrs.locale));
attrs.$observe('locale', function()
{
ctrl.build(checkLocale(attrs.locale), false);
});
scope.$watch('model', function()
{
ctrl.build(checkLocale(attrs.locale), true);
});
attrs.$observe('allowClear', function(newValue)
{
scope.allowClear = !!(angular.isDefined(newValue) && newValue === 'true');
});
function checkLocale(locale)
{
if (!locale)
{
return (navigator.language !== null ? navigator.language : navigator.browserLanguage).split("_")[0].split("-")[0] || 'en';
}
return locale;
}
}
};
});
|
JavaScript
| 0.000002 |
@@ -4970,151 +4970,8 @@
');%0A
- console.log($activeYear, $yearSelector.scrollTop(), $activeYear.position().top, $yearSelector.height(), $activeYear.height());%0A
|
e8d4806b4581380178517f2920d9af77df79ca10
|
combine export declaration assignments into variable declarations
|
lib/6to5/modules/common.js
|
lib/6to5/modules/common.js
|
module.exports = CommonJSFormatter;
var util = require("../util");
var t = require("../types");
function CommonJSFormatter(file) {
this.file = file;
}
CommonJSFormatter.prototype.import = function (node, nodes) {
// import "foo";
nodes.push(util.template("require", {
MODULE_NAME: node.source.raw
}, true));
};
CommonJSFormatter.prototype.importSpecifier = function (specifier, node, nodes) {
var variableName = t.getSpecifierName(specifier);
// import foo from "foo";
if (specifier.default) {
specifier.id = t.identifier("default");
}
var templateName = "require-assign";
// import * as bar from "foo";
if (specifier.type !== "ImportBatchSpecifier") templateName += "-key";
nodes.push(util.template(templateName, {
VARIABLE_NAME: variableName,
MODULE_NAME: node.source.raw,
KEY: specifier.id
}));
};
CommonJSFormatter.prototype.export = function (node, nodes) {
var declar = node.declaration;
if (node.default) {
var ref = declar;
if (t.isClass(ref) || t.isFunction(ref)) {
if (ref.id) {
nodes.push(ref);
ref = ref.id;
}
}
nodes.push(util.template("exports-default", {
VALUE: ref
}, true));
} else {
var id = declar.id;
if (t.isVariableDeclaration(declar)) {
id = declar.declarations[0].id;
}
var assign = util.template("exports-assign", {
VALUE: id,
KEY: id
}, true);
nodes.push(declar);
if (t.isFunctionDeclaration(declar)) {
assign._blockHoist = true;
}
nodes.push(assign);
}
};
CommonJSFormatter.prototype._exportSpecifier = function (getRef, specifier, node, nodes) {
var variableName = t.getSpecifierName(specifier);
if (node.source) {
if (t.isExportBatchSpecifier(specifier)) {
// export * from "foo";
nodes.push(util.template("exports-wildcard", {
OBJECT: getRef()
}, true));
} else {
// export { foo } from "test";
nodes.push(util.template("exports-assign-key", {
VARIABLE_NAME: variableName.name,
OBJECT: getRef(),
KEY: specifier.id
}, true));
}
} else {
// export { foo };
nodes.push(util.template("exports-assign", {
VALUE: specifier.id,
KEY: variableName
}, true));
}
};
CommonJSFormatter.prototype.exportSpecifier = function (specifier, node, nodes) {
return this._exportSpecifier(function () {
return t.callExpression(t.identifier("require"), [node.source]);
}, specifier, node, nodes);
};
|
JavaScript
| 0.000016 |
@@ -1239,23 +1239,16 @@
var
-id = declar.id;
+assign;%0A
%0A
@@ -1293,18 +1293,24 @@
%7B%0A
-id
+var decl
= decla
@@ -1330,27 +1330,205 @@
s%5B0%5D
-.id;%0A %7D%0A%0A var
+%0A%0A if (decl.init) %7B%0A decl.init = util.template(%22exports-assign%22, %7B%0A VALUE: decl.init,%0A KEY: decl.id%0A %7D);%0A %7D%0A%0A nodes.push(declar);%0A %7D else %7B%0A
ass
@@ -1573,23 +1573,32 @@
%7B%0A
+
VALUE:
+declar.
id,%0A
@@ -1603,22 +1603,33 @@
+
+
KEY:
+declar.
id%0A
+
+
%7D, t
@@ -1631,24 +1631,26 @@
%7D, true);%0A%0A
+
nodes.pu
@@ -1661,17 +1661,45 @@
eclar);%0A
-%0A
+ nodes.push(assign);%0A%0A
if (
@@ -1735,24 +1735,26 @@
r)) %7B%0A
+
assign._bloc
@@ -1776,34 +1776,17 @@
+
%7D
-%0A
%0A
-nodes.push(assign);
+%7D
%0A %7D
|
3b3c5a5ca1c3e117b13782cf3d08948c3821a960
|
Change the flag name for the host option in the REPL
|
bin/repl.js
|
bin/repl.js
|
#!/usr/bin/env node
var repl = require('repl');
var util = require('util');
var program = require('commander');
var protocol = require('../lib/protocol.json');
var Chrome = require('../');
program
.option('-h, --host <host>', 'Remote Debugging Protocol host')
.option('-p, --port <port>', 'Remote Debugging Protocol port')
.parse(process.argv);
var options = {
'host': program.host,
'port': program.port
};
Chrome(options, function (chrome) {
var chromeRepl = repl.start({
'prompt': 'chrome> ',
'ignoreUndefined': true,
'writer': function (object) {
return util.inspect(object, {
'colors': true,
'depth': null
});
}
});
// disconnect on exit
chromeRepl.on('exit', function () {
chrome.close();
});
// add protocol API
for (var domainIdx in protocol.domains) {
var domainName = protocol.domains[domainIdx].domain;
chromeRepl.context[domainName] = chrome[domainName];
}
}).on('error', function () {
console.error('Cannot connect to Chrome');
});
|
JavaScript
| 0.000002 |
@@ -206,17 +206,17 @@
ption('-
-h
+t
, --host
|
965fe9a74fb1d8849100262d6d506e9ad9c1e427
|
Format dat diff properly, to include checkout
|
bin/diff.js
|
bin/diff.js
|
var pump = require('pump')
var ndjson = require('ndjson')
var openDat = require('../lib/open-dat.js')
var abort = require('../lib/abort.js')
var usage = require('../lib/usage.js')('diff.txt')
module.exports = {
name: 'diff',
command: handleDiff
}
function handleDiff (args) {
if (args.help) return usage()
if (args._.length < 2) return usage()
openDat(args, function ready (err, db) {
if (err) abort(err)
var diffs = db.createDiffStream(args._[0], args._[1])
pump(diffs, ndjson.serialize(), process.stdout, function done (err) {
if (err) throw err
})
})
}
|
JavaScript
| 0 |
@@ -20,16 +20,50 @@
'pump')%0A
+var through = require('through2')%0A
var ndjs
@@ -462,163 +462,802 @@
var
-diffs = db.createDiffStream(args._%5B0%5D, args._%5B1%5D)%0A pump(diffs, ndjson.serialize(), process.stdout, function done (err) %7B%0A if (err) throw err%0A %7D)
+headA = args._%5B0%5D%0A var headB = args._%5B1%5D%0A%0A var diffs = db.createDiffStream(headA, headB)%0A pump(diffs, datDiffFormatter(), ndjson.serialize(), process.stdout, function done (err) %7B%0A if (err) throw err%0A %7D)%0A%0A function datDiffFormatter () %7B%0A return through.obj(function write (obj, enc, next) %7B%0A var a = obj%5B0%5D%0A var b = obj%5B1%5D%0A var diff = %7B%7D%0A if (a) diff.key = a.key%0A if (b) diff.key = b.key%0A diff.versions = %5B%5D%0A if (a) %7B%0A a.checkout = headA%0A diff.versions.push(a)%0A %7D else %7B%0A diff.versions.push(null)%0A %7D%0A if (b) %7B%0A b.checkout = headB%0A diff.versions.push(b)%0A %7D else %7B%0A diff.versions.push(null)%0A %7D%0A next(null, diff)%0A %7D)%0A %7D
%0A %7D
|
8a4bb41c97170b1911c7016d2f67eeede57acb78
|
revert #804, AM bug issue
|
server/static/js/staff.js
|
server/static/js/staff.js
|
// initialize datepicker
jQuery(document).ready(function($){
$('.datepicker').datetimepicker({format:'YYYY-MM-DD hh:mm:ss'});
});
|
JavaScript
| 0 |
@@ -55,16 +55,19 @@
on($)%7B%0A
+ //
$('.dat
@@ -92,16 +92,23 @@
picker(%7B
+%0A // %09
format:'
@@ -127,16 +127,23 @@
h:mm:ss'
+,%0A //
%7D);%0A%7D);%0A
|
b148901db4b68926089593b1b7f0078121899ccd
|
use correct option name
|
bin/ytdl.js
|
bin/ytdl.js
|
#!/usr/bin/env node
var path = require('path');
var fs = require('fs');
var ytdl = require('..');
var cliff = require('cliff');
require('colors');
var info = JSON.parse(
fs.readFileSync(path.resolve(__dirname, '..', 'package.json')));
var opts = require('nomnom')
.option('version', {
abbr: 'v'
, flag: true
, callback: function() {
console.log('v' + info.version);
process.exit();
}
, help: 'Print program version.'
})
.option('url', {
position: 0
, required: true
, help: 'URL to the video.'
})
.option('quality', {
abbr: 'q'
, metavar: 'ITAG'
, help: 'Video quality to download. Default: `highest`'
})
.option('start', {
abbr: 's'
, metavar: 'TIME'
, help: 'Where to begin the video. ie 1m3s, 45s, 2300.'
})
.option('output', {
abbr: 'o'
, metavar: 'FILE'
, help: 'Where to save the file. Default: stdout'
})
.option('filterContainer', {
full: 'filter-container'
, metavar: 'REGEXP'
, help: 'Filter in format container.'
})
.option('unfilterContainer', {
full: 'unfilter-container'
, metavar: 'REGEXP'
, help: 'Filter out format container.'
})
.option('filterResolution', {
full: 'filter-resolution'
, metavar: 'REGEXP'
, help: 'Filter in format resolution.'
})
.option('unfilterResolution', {
full: 'unfilter-resolution'
, metavar: 'REGEXP'
, help: 'Filter out format resolution.'
})
.option('filterEncoding', {
full: 'filter-encoding'
, metavar: 'REGEXP'
, help: 'Filter in format encoding.'
})
.option('unfilterEncoding', {
full: 'unfilter-encoding'
, metavar: 'REGEXP'
, help: 'Filter out format encoding.'
})
.option('info', {
abbr: 'i'
, flag: true
, help: 'Print only video information without downloading'
})
.script('ytdl')
.colors()
.parse()
;
/**
* Converts seconds into human readable time hh:mm:ss
*
* @param {Number} seconds
* @return {String}
*/
function toHumanTime(seconds) {
var h = Math.floor(seconds / 3600);
if (h < 10) { h = '0' + h; }
var m = Math.floor(seconds / 60) % 60;
if (m < 10) { m = '0' + m; }
var s = seconds % 60;
if (s < 10) { s = '0' + s; }
return h + ':' + m + ':' + s;
}
/**
* Prints basic video information.
*
* @param {Object} info
*/
function printVideoInfo(info) {
console.log();
console.log('title: '.grey.bold + info.title);
console.log('author: '.grey.bold + info.author);
var rating = typeof info.avg_rating === 'number' ?
info.avg_rating.toFixed(1) : info.avg_rating;
console.log('average rating: '.grey.bold + rating);
console.log('view count: '.grey.bold + info.view_count);
console.log('length: '.grey.bold + toHumanTime(info.length_seconds));
}
if (opts.info) {
ytdl.getInfo(opts.url, function(err, info) {
if (err) {
console.error(err.message);
process.exit(1);
return;
}
printVideoInfo(info);
console.log('formats:'.grey.bold);
var cols = ['itag', 'container', 'resolution', 'encoding'];
var colors = ['green', 'blue', 'green', 'blue'];
console.log(cliff.stringifyObjectRows(info.formats, cols, colors));
ytdl.cache.die();
});
return;
}
var output = opts.output;
var writeStream = output ? fs.createWriteStream(output) : process.stdout;
var ytdlOptions = {};
ytdlOptions.quality = opts.quality;
ytdlOptions.begin = opts.begin;
// Create filters.
var filters = [];
/**
* @param {String} field
* @param {String} regexpStr
* @param {Boolean|null} negated
*/
function createFilter(field, regexpStr, negated) {
try {
var regexp = new RegExp(regexpStr, 'i');
} catch (err) {
console.error(err.message);
process.exit(1);
}
filters.push(function(format) {
return negated !== regexp.test(format[field]);
});
}
['container', 'resolution', 'encoding'].forEach(function(field) {
var key = 'filter' + field[0].toUpperCase() + field.slice(1);
if (opts[key]) {
createFilter(field, opts[key], false);
}
key = 'un' + key;
if (opts[key]) {
createFilter(field, opts[key], true);
}
});
ytdlOptions.filter = function(format) {
return filters.every(function(filter) {
return filter(format);
});
};
var readStream = ytdl(opts.url, ytdlOptions);
readStream.pipe(writeStream);
readStream.on('error', function(err) {
console.error(err.stack);
process.exit(1);
});
// Converst bytes to human readable unit.
// Thank you Amir from StackOverflow.
var units = ' KMGTPEZYXWVU';
function toHumanSize(bytes) {
if (bytes <= 0) { return 0; }
var t2 = Math.min(Math.floor(Math.log(bytes) / Math.log(1024)), 12);
return (Math.round(bytes * 100 / Math.pow(1024, t2)) / 100) +
units.charAt(t2).replace(' ', '') + 'B';
}
// Print progress bar and some video info if not streaming to stdout.
if (output) {
readStream.on('info', function(info, format) {
printVideoInfo(info);
console.log('container: '.grey.bold + format.container);
console.log('resolution: '.grey.bold + format.resolution);
console.log('encoding: '.grey.bold + format.encoding);
console.log('size: '.grey.bold + toHumanSize(format.size));
console.log('output: '.grey.bold + output);
console.log();
// Create progress bar.
var bar = require('progress-bar').create(process.stdout, 50);
bar.format = '$bar; $percentage;%';
// Keep track of progress.
var dataRead = 0;
readStream.on('data', function(data) {
dataRead += data.length;
var percent = dataRead / format.size;
bar.update(percent);
});
ytdl.cache.die();
});
}
readStream.on('end', function onend() {
console.log();
});
process.on('SIGINT', function onsigint() {
console.log();
process.exit();
});
|
JavaScript
| 0.000051 |
@@ -3350,21 +3350,21 @@
ons.
-begin
+start
= opts.
begi
@@ -3359,21 +3359,21 @@
= opts.
-begin
+start
;%0A%0A// Cr
|
5d0a12653c54846ed5380d5b9bd85d47cc8f9f0b
|
Add test cases for missing parameters
|
server/test/app.delete.js
|
server/test/app.delete.js
|
var assert = require('assert'),
mongoose = require('mongoose');
var config = require('./../config');
var appSv = require('./../service/app');
describe('app.update', function(){
var appObj = {};
var appInstance;
// Connect to Mongo DB
// Clean app database
// Create a test app
before(function(){
console.log("START TEST APP.DELETE");
mongoose.connect(config.mongodb.test);
});
// Disconnect
after(function(){
console.log("END TEST APP.DELETE");
mongoose.disconnect();
});
beforeEach(function(done){
appObj =
{
identifier: "de.unittest"
, licenses: [{
trialtype: "time"
, value: 30
}]
};
appSv.clean(function(err){
if(err) throw err;
appSv.create(appObj, function(err, app){
if(err) throw err;
appInstance = app;
done();
});
});
});
it('should delete app and return deleted app', function(done){
appSv.delete(appInstance, function(err, app){
assert.ifError(err);
assert.equal(app.identifier, appObj.identifier);
done();
});
});
});
|
JavaScript
| 0.000003 |
@@ -821,16 +821,389 @@
;%0A%09%7D);%0A%0A
+%09it('should return an error for undefined app parameter', function(done)%7B%0A%09%09var undefinedParameter;%0A%09%09appSv.delete(undefinedParameter, function(err, app)%7B%0A%09%09%09assert.notEqual(err, null);%0A%09%09%09done();%0A%09%09%7D);%0A%09%7D);%0A%0A%09it('should return an error for null app parameter', function(done)%7B%0A%09%09appSv.delete(null, function(err, app)%7B%0A%09%09%09assert.notEqual(err, null);%0A%09%09%09done();%0A%09%09%7D);%0A%09%7D);%0A%0A
%09it('sho
|
4acf88a0354a8a04364826ca76a0777bb6b58a32
|
Fix stale getState on hot reloading (#90)
|
src/createDispatcher.js
|
src/createDispatcher.js
|
import composeMiddleware from './utils/composeMiddleware';
export default function createDispatcher(store, middlewares = []) {
return function dispatcher(initialState, setState) {
let state = setState(store(initialState, {}));
function dispatch(action) {
state = setState(store(state, action));
return action;
}
function getState() {
return state;
}
if (typeof middlewares === 'function') {
middlewares = middlewares(getState);
}
return composeMiddleware(...middlewares, dispatch);
};
}
|
JavaScript
| 0 |
@@ -395,12 +395,33 @@
-if (
+const finalMiddlewares =
type
@@ -449,19 +449,18 @@
unction'
-) %7B
+ ?
%0A m
@@ -473,39 +473,39 @@
ares
- = middlewares(getState);%0A %7D
+(getState) :%0A middlewares;
%0A%0A
@@ -534,17 +534,22 @@
ware(...
-m
+finalM
iddlewar
|
60b82eb955dd400adc22084b1d41e27d1a6a475a
|
Update sns_publishtotopic.js
|
javascript/example_code/sns/sns_publishtotopic.js
|
javascript/example_code/sns/sns_publishtotopic.js
|
// Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
// Licensed under the Apache-2.0 License on an "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND.
// ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
// https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/sns-examples-publishing-messages.html
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set region
AWS.config.update({region: 'us-west-2'});
// Create publish parameters
var params = {
Message: 'This is David sending another text message from programming code.', /* required */
TopicArn: 'arn:aws:sns:us-west-2:617985816162:FirstTopic',
};
// Create promise and SNS service object
var publishTextPromise = new AWS.SNS({apiVersion: '2010-03-31'}).publish(params).promise();
// handle promise's fulfilled/rejected states
publishTextPromise.then(
function(data) {
console.log("Message ${params.message} send sent to the topic ${params.topicArn}");
console.log("MessageID is " + data.MessageId);
}).catch(
function(err) {
console.error(err, err.stack);
});
|
JavaScript
| 0.000002 |
@@ -655,53 +655,17 @@
n: '
-arn:aws:sns:us-west-2:617985816162:FirstTopic
+TOPIC_ARN
',%0A%7D
|
cef6852f9c6ebe34847de990ce4ec53eefb558f4
|
add example logging
|
services/default/index.js
|
services/default/index.js
|
/**
* default service pack
*/
'use strict';
const marked = require('marked');
const fs = require('fs');
require(_PATH_LIB + 'example');
APP.get('/', function (req, res) {
let file = _PATH_ROOT + 'README.md';
let opts = {
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: true,
smartLists: true,
smartypants: false
};
marked.setOptions(opts);
let src = marked(fs.readFileSync(file).toString()).replace(/<table>/g, '<table class="table">');
res.send(`
<html>
<head>
<title>Node Micro Service Bootstrap</title>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
rel="stylesheet"
crossorigin="anonymous">
<style>
h1, h2, h3, h4, h5{
margin-top: 20px;
}
</style>
</head>
<body>
<div class="container" style="margin-bottom: 60px;line-height: 1.8;">
<div class="row">
<div class="alert alert-info" role="alert"><strong>You are seeing this page because the default service is loaded,
run the app with custom services and the default service will be replaced.</strong></div>
${src}
</div>
</div>
</body>
</html>
`);
});
/**
* example apis
*/
APP.get('/example/:action', function (req, res) {
const example = _LIB.example;
const action = req.params.action;
let response = {};
// callback and use response maker
try {
const callback = _LIB.example[action];
_log('EXAMPLE', {
action: action,
callback: callback,
params: req.params
});
response = _LIB.util.response.success(callback('hello world'), `action ${action} success`);
} catch (e) {
_log('EXAMPLE', {
action: action,
error: e.toString()
}, 'ERROR');
response = _LIB.util.response.error(e);
}
// return response
res.send(response);
});
|
JavaScript
| 0 |
@@ -1460,16 +1460,40 @@
ction%5D;%0A
+ // log info example%0A
_log
@@ -1587,16 +1587,17 @@
%7D);%0A
+%0A
resp
@@ -1688,23 +1688,108 @@
%60);%0A
- %7D catch (e) %7B
+%0A // log success example%0A _log('EXAMPLE', 'success');%0A %7D catch (e) %7B%0A // log error example
%0A
@@ -1872,16 +1872,17 @@
RROR');%0A
+%0A
resp
|
e051446e5b349e87ae6cca9efc92ced80e96776a
|
Increase zoom out when viewing individual poi
|
apps/poi/js/PoiMapView.js
|
apps/poi/js/PoiMapView.js
|
define(['jquery', 'backbone', 'chrome', 'apps/poi/js/PoiCollection', 'text!apps/poi/templates/poi-tpl.html', 'apps/poi/js/PoiTypeCollection', 'gmaps', 'locator'], function ($, Backbone, Chrome, PoiCollection, Templates, PoiTypeCollection, GMaps, Locator) {
'use strict';
Templates = $('<div>').html(Templates);
var View = Backbone.View.extend({
collection: PoiCollection,
typeid: null,
poiid: null,
directions: null,
directionsType: null,
all: false,
el: "body",
initialize: function(info) {
this.typeid = info.typeid || null;
this.poiid = info.poiid || null;
this.directions = info.directions || false;
this.directionsType = info.directionsType || null;
this.all = !this.typeid && !this.poiid && !this.directions;
var that = this;
$(this.el).undelegate('#findMe', 'click');
// Remove all previous bound events to avoid repeated bindings
$(document).off('pageshow.poiMap');
$(document).on('pageshow.poiMap', '#poiMap', function (event) {
$("#mapCanvas").css({
width: $("#poiMap").width(),
height: $("#poiMap").height() - $("#mapHeader").height()
} );
that.mapRender(that.typeid, that.poiid, that.directions, that.directionsType, that.all);
});
if(!this.collection.loaded) {
var that = this;
this.collection.fetch().success(function(){
that.render();
});
} else {
this.render();
}
},
template: _.template(Templates.find('#poiMapTemplate').html()),
events: {
"click #findMe": "findMeCenter"
},
mapRender: function(typeid, poiid, directions, directionsType, all) {
typeid = typeid || null;
poiid = poiid || null;
directions = directions || false;
directionsType = directionsType || null;
var poiCollection = !typeid || all ?
this.collection :
this.collection.filterByType( typeid )
;
var mainpoi = poiid ? poiCollection.get(poiid) : null;
var useBounds = mainpoi ? false : true;
this.mapLoad()
.mapDrawPoints(poiCollection, mainpoi, typeid, all, useBounds)
.mapCenterPoint(mainpoi)
.mapDrawDirections(directions, directionsType, mainpoi);
if( !useBounds) {
this.mapSetZoom(19);
}
},
mapLoad: function() {
GMaps.loadInto( $('#mapCanvas').get(0) );
return this;
},
mapDrawPoints: function(poiCollection, mainpoi, typeid, all, useBounds) {
if( typeid === null && !all) {
return this;
}
var pois = [], image;
if( !mainpoi ) {
poiCollection.each(function(poi){
image = poi.get("active") ?
PoiTypeCollection.get(poi.get('type')).get( 'mapImage' ) :
PoiTypeCollection.get(poi.get('type')).get( 'closedMapImage' );
pois.push( {
name: poi.get("name"),
link: '<a href="#poi/info/'+poi.id+'">'+poi.get('name')+'</a>',
lat: poi.get("latitude"),
lng: poi.get("longitude"),
image: image
});
});
} else {
image = mainpoi.get("active") ?
PoiTypeCollection.get(mainpoi.get('type')).get( 'mapImage' ) :
PoiTypeCollection.get(mainpoi.get('type')).get( 'closedMapImage' );
pois.push( {
name: mainpoi.get("name"),
link: '<a href="#poi/info/'+mainpoi.id+'">'+mainpoi.get('name')+'</a>',
lat: mainpoi.get("latitude"),
lng: mainpoi.get("longitude"),
image: image
});
}
GMaps.drawPoints( pois, useBounds );
return this;
},
mapSetZoom: function(level) {
GMaps.setZoom(level);
return this;
},
mapCenterPoint: function(mainpoi) {
if( !mainpoi ) {
return this;
}
GMaps.setCenter({
lat: mainpoi.get("latitude"),
lng: mainpoi.get("longitude"),
});
return this;
},
mapDrawDirections: function(directions, directionsType, mainpoi) {
if( !directions || !mainpoi) {
return this;
}
Locator.location(function(from, success){
if(success) {
var to = {
lat: mainpoi.get("latitude"),
lng: mainpoi.get("longitude"),
};
GMaps.drawDirections(from, to, directionsType);
}
});
return this;
},
render: function() {
var filteredPois = this.typeid === null ?
this.collection :
this.collection.filterByType( this.typeid );
var html = this.template({pois: filteredPois.toJSON()});
var parsehtml = Chrome.parseHTML(html);
this.urlAlterHtml( parsehtml, filteredPois );
Chrome.showPage( parsehtml );
},
/**
* Function that makes addtional html alterations based on current url
*/
urlAlterHtml: function( parsehtml, pois ) {
// Url directions
if( window.location.hash.substring(0, 20) == '#poi/info/directions' ) {
// Add footer with various direction options
var $footer = parsehtml.find( 'div[data-role="footer"]' );
var directions_path = '#poi/info/directions' + '/' + this.poiid + '/';
var driving_active = "";
var transit_active = "";
var bicycling_active = "";
var walking_active = "";
switch( this.directionsType ) {
case "driving":
driving_active = "ui-btn-active ui-state-persist";
break;
case "transit":
transit_active = "ui-btn-active ui-state-persist";
break;
case "bicycling":
bicycling_active = "ui-btn-active ui-state-persist";
break;
case "walking":
walking_active = "ui-btn-active ui-state-persist";
break;
}
$footer.append( $('<div data-role="controlgroup" data-type="horizontal">' +
'<a href="' + directions_path + 'driving' + '" data-role="button" data-icon="plus" class="' + driving_active + '">Bil</a>' +
'<a href="' + directions_path + 'transit' + '" data-role="button" data-icon="plus" class="' + transit_active + '">Transit</a>' +
'<a href="' + directions_path + 'bicycling' + '" data-role="button" data-icon="plus" class="' + bicycling_active + '">Cykel</a>' +
'<a href="' + directions_path + 'walking' + '" data-role="button" data-icon="plus" class="' + walking_active + '">Gång</a>' +
'</div>') );
// Link close button back to poi info page, instead of simple 'back'
var $closeButton = parsehtml.find( '#closeButton' );
$closeButton.removeAttr('data-direction');
$closeButton.removeAttr('data-rel');
$closeButton.prop('href', "#poi/info/" + this.poiid );
}
},
findMeCenter: function() {
Locator.location(function(myPos, success){
if(success) {
GMaps.setCenter(myPos, true);
}
});
return false;
}
});
return View;
});
//
|
JavaScript
| 0 |
@@ -2349,9 +2349,9 @@
om(1
-9
+5
);%0A
|
06cb6b3344b7e95f22fd0bc5f5e3a9a6e9c1982c
|
Convert `Bindable` to ES6.
|
bindable.js
|
bindable.js
|
function Path (path) {
this.family = 'unix'
this.path = path
}
Path.prototype.toString = function () {
return this.path
}
Path.prototype.options = function (connect) {
return { path: this.path, ...connect }
}
function Bindable (host, port) {
this.family = 'IPv4'
this.host = host
this.port = port
}
Bindable.prototype.toString = function () {
return this.host + ':' + this.port
}
Bindable.prototype.options = function (connect) {
return { host: this.host, port: this.port, ...connect }
}
function isNumeric (value) {
return !isNaN(parseFloat(value)) && isFinite(value)
}
// TODO IPv6.
function parse (value) {
if (/^[.\/]/.test(value)) {
return new Path(value)
}
var bind = value.split(':')
if (bind.length == 1) {
bind.unshift('0.0.0.0')
}
// TODO You'll want string aliases so that `"foo is required" -> "generic required"
if (!isNumeric(bind[1])) {
return null
}
var parts = bind[0].split('.')
if (parts.length != 4) {
return null
}
if (parts.filter(function (part) {
return isNumeric(part) && 0 <= +part && +part <= 255
}).length != 4) {
return null
}
var bind = value.split(':')
if (bind.length == 1) {
bind.unshift('0.0.0.0')
}
return new Bindable(bind[0], +bind[1])
}
module.exports = function (value, name) {
value = String(value)
value = parse(value)
if (value == null) {
throw '%s is not bindable'
}
return value
}
|
JavaScript
| 0.999999 |
@@ -1,17 +1,32 @@
-function Path
+class Path %7B%0A constructor
(pa
@@ -27,32 +27,36 @@
or (path) %7B%0A
+
+
this.family = 'u
@@ -60,16 +60,20 @@
'unix'%0A
+
this
@@ -89,51 +89,37 @@
ath%0A
-%7D%0A%0APath.prototype.toString = function
+ %7D%0A%0A toString
() %7B%0A
+
@@ -139,44 +139,26 @@
ath%0A
-%7D%0A%0APath.prototype.options = function
+ %7D%0A%0A options
(co
@@ -158,32 +158,36 @@
ons (connect) %7B%0A
+
return %7B pat
@@ -217,28 +217,49 @@
t %7D%0A
-%7D%0A%0Afunction Bindable
+ %7D%0A%7D%0A%0Aclass Bindable %7B%0A constructor
(ho
@@ -270,24 +270,28 @@
port) %7B%0A
+
+
this.family
@@ -299,16 +299,20 @@
'IPv4'%0A
+
this
@@ -324,24 +324,28 @@
= host%0A
+
+
this.port =
@@ -353,55 +353,37 @@
ort%0A
-%7D%0A%0ABindable.prototype.toString = function
+ %7D%0A%0A toString
() %7B%0A
+
@@ -421,48 +421,26 @@
ort%0A
-%7D%0A%0ABindable.prototype.options = function
+ %7D%0A%0A options
(co
@@ -444,24 +444,28 @@
(connect) %7B%0A
+
return %7B
@@ -512,16 +512,22 @@
nnect %7D%0A
+ %7D%0A
%7D%0A%0Afunct
@@ -713,35 +713,37 @@
alue)%0A %7D%0A
-var
+const
bind = value.sp
@@ -962,19 +962,21 @@
%7D%0A
-var
+const
parts =
@@ -1202,40 +1202,8 @@
%7D%0A
- var bind = value.split(':')%0A
|
26500cdfde46689ea17bece0f2b1fc22aa217c03
|
添加参数,使session的会话信息更完善
|
blog/app.js
|
blog/app.js
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
//导入配置文件
var settings = require('./settings');
//支持会话信息
var session = require('express-session');
var MongoStore = require('connect-mongo')(session);
//生成一个express实例app
var app = express();
//设置views文件夹为存放视图文件的目录,即存放模版文件的地方
//__dirname为全局变量,存储当前正在执行的脚本所在的目录。
// view engine setup
app.set('views', path.join(__dirname, 'views'));
//设置视图模版引擎为jade
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
// 设置/public/favicon.ico为favicon图标
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
//加载日志中间件
app.use(logger('dev'));
//加载解析json的中间件
app.use(bodyParser.json());
//加载解析urlencoded请求体中的中间件
app.use(bodyParser.urlencoded({ extended: false }));
//加载解析cookie的中间件
app.use(cookieParser());
// 设置public文件夹为存放静态文件的目录.
app.use(express.static(path.join(__dirname, 'public')));
//路由控制器
app.use('/', routes);
app.use('/users', users);
//捕获404错误,并转发到错误处理器.
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
//错误处理器
// error handlers
//开发环境下的错误处理器,
// 将错误信息渲染到error模版并显示到浏览器中(打印堆栈信息).
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
//生产环境下的错误处理器
//将错误信息渲染到error模版并显示到浏览器中(不打印堆栈信息)
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
app.use(session({
secret: setting.cookieSecret,
key: setting.db,//cookie name
cookie: {maxAge: 1000 * 60 * 60 * 24 * 30}, //30 days
store: new MongoStore({
db: settings.db,
host: settings.host,
port: settings.prot
})
}));
//导出app实例供其他模块调用。
module.exports = app;
|
JavaScript
| 0 |
@@ -1947,16 +1947,115 @@
ssion(%7B%0A
+ resave:false,//resave %E2%80%94%E2%80%94%E9%87%8D%E6%96%B0%E4%BF%9D%E5%AD%98%EF%BC%9A%E5%BC%BA%E5%88%B6%E4%BC%9A%E8%AF%9D%E4%BF%9D%E5%AD%98%E5%8D%B3%E4%BD%BF%E6%98%AF%E6%9C%AA%E4%BF%AE%E6%94%B9%E7%9A%84%EF%BC%8C%E9%BB%98%E8%AE%A4%E4%B8%BAtrue%0A saveUninitialized: true,//%E5%BC%BA%E5%88%B6%E4%BF%9D%E5%AD%98%E6%9C%AA%E5%88%9D%E5%A7%8B%E5%8C%96%E7%9A%84%E4%BC%9A%E8%AF%9D%E5%88%B0%E5%AD%98%E5%82%A8%E5%99%A8 %0A
secret
@@ -2063,16 +2063,17 @@
setting
+s
.cookieS
@@ -2093,16 +2093,17 @@
setting
+s
.db,//co
|
3927440c33d84ecb8d2d8834d912d64c080db8da
|
Add removeById function to remove an item from an array that matches a particular id. Assumes the object passed in and the array of objects all have id fields.
|
website/app/index/util.js
|
website/app/index/util.js
|
function isImage(mime) {
switch (mime) {
case "image/gif":
case "image/jpeg":
case "image/png":
case "image/tiff":
case "image/x-ms-bmp":
case "image/bmp":
return true;
default:
return false;
}
}
function numberWithCommas(n) {
n = n.toString();
var pattern = /(-?\d+)(\d{3})/;
while (pattern.test(n)) {
n = n.replace(pattern, "$1,$2");
}
return n;
}
function bytesToSizeStr(bytes) {
if(bytes === 0) return '0 Byte';
var k = 1000;
var sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
var i = Math.floor(Math.log(bytes) / Math.log(k));
return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
}
function endsWith(str, suffix) {
return str.indexOf(suffix, str.length - suffix.length) !== -1;
}
function _add_json_callback(url) {
return url + "&callback=JSON_CALLBACK";
}
function _add_json_callback2(url) {
var qIndex = url.indexOf("?");
var argSeparator = "&";
if (qIndex == -1) {
argSeparator = "?";
}
return url + argSeparator + "callback=JSON_CALLBACK";
}
function differenceById(from, others) {
var idsFrom = from.map(function(entry) {
return entry.id;
});
var idsOthers = others.map(function(entry) {
return entry.id;
});
var diff = _.difference(idsFrom, idsOthers);
return from.filter(function(entry) {
return _.indexOf(diff, function(e) {
return e == entry.id;
}) !== -1;
})
}
String.prototype.capitalize = function () {
return this.replace(/(?:^|\s)\S/g, function (a) {
return a.toUpperCase();
});
};
// save a reference to the core implementation
var indexOfValue = _.indexOf;
// using .mixin allows both wrapped and unwrapped calls:
// _(array).indexOf(...) and _.indexOf(array, ...)
_.mixin({
// return the index of the first array element passing a test
indexOf: function (array, test) {
// delegate to standard indexOf if the test isn't a function
if (!_.isFunction(test)) return indexOfValue(array, test);
// otherwise, look for the index
for (var x = 0; x < array.length; x++) {
if (test(array[x])) return x;
}
// not found, return fail value
return -1;
}
});
|
JavaScript
| 0 |
@@ -1519,16 +1519,196 @@
%7D)%0A%7D%0A%0A
+function removeById(from, what) %7B%0A var i = _.indexOf(from, function(item) %7B%0A return item.id === what.id;%0A %7D);%0A%0A if (i !== -1) %7B%0A from.splice(i, 1);%0A %7D%0A%7D%0A%0A
String.p
|
61497313fb11666191f1b38232d527336855e624
|
fix reward example
|
Example/index.js
|
Example/index.js
|
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Platform,
TouchableHighlight,
Button,
ScrollView,
} from 'react-native';
import {
AdMobBanner,
AdMobRewarded,
AdMobInterstitial,
PublisherBanner,
} from 'react-native-admob';
const BannerExample = ({ style, title, children, ...props }) => (
<View {...props} style={[styles.example, style]}>
<Text style={styles.title}>{title}</Text>
<View>
{children}
</View>
</View>
);
const bannerWidths = [200, 250, 320];
export default class Example extends Component {
constructor() {
super();
this.state = {
fluidSizeIndex: 0,
};
}
componentDidMount() {
AdMobRewarded.setTestDevices([AdMobRewarded.simulatorId]);
AdMobRewarded.setAdUnitID('ca-app-pub-3940256099942544/1033173712');
AdMobRewarded.addEventListener('rewardedVideoDidRewardUser',
(type, amount) => console.log('rewardedVideoDidRewardUser', type, amount)
);
AdMobRewarded.addEventListener('rewardedVideoDidLoad',
() => console.log('rewardedVideoDidLoad')
);
AdMobRewarded.addEventListener('rewardedVideoDidFailToLoad',
(error) => console.log('rewardedVideoDidFailToLoad', error)
);
AdMobRewarded.addEventListener('rewardedVideoDidOpen',
() => console.log('rewardedVideoDidOpen')
);
AdMobRewarded.addEventListener('rewardedVideoDidStartPlaying',
() => console.log('rewardedVideoDidStartPlaying')
);
AdMobRewarded.addEventListener('rewardedVideoDidClose',
() => {
console.log('rewardedVideoDidClose');
AdMobRewarded.requestAd().catch(error => console.log(error));
}
);
AdMobRewarded.addEventListener('rewardedVideoWillLeaveApplication',
() => console.log('rewardedVideoWillLeaveApplication')
);
AdMobRewarded.requestAd().catch(error => console.log(error));
AdMobInterstitial.setTestDevices([AdMobInterstitial.simulatorId]);
AdMobInterstitial.setAdUnitID('ca-app-pub-3940256099942544/4411468910');
AdMobInterstitial.addEventListener('interstitialDidLoad',
() => console.log('interstitialDidLoad')
);
AdMobInterstitial.addEventListener('interstitialDidFailToLoad',
(error) => console.log('interstitialDidFailToLoad', error)
);
AdMobInterstitial.addEventListener('interstitialDidOpen',
() => console.log('interstitialDidOpen')
);
AdMobInterstitial.addEventListener('interstitialDidClose',
() => {
console.log('interstitialDidClose');
AdMobInterstitial.requestAd().catch(error => console.log(error));
}
);
AdMobInterstitial.addEventListener('interstitialWillLeaveApplication',
() => console.log('interstitialWillLeaveApplication')
);
AdMobInterstitial.requestAd().catch(error => console.log(error));
}
componentWillUnmount() {
AdMobRewarded.removeAllListeners();
AdMobInterstitial.removeAllListeners();
}
showRewarded() {
AdMobRewarded.showAd().catch(error => console.log(error));
}
showInterstitial() {
AdMobInterstitial.showAd().catch(error => console.log(error));
}
render() {
return (
<View style={styles.container}>
<ScrollView>
<BannerExample title="AdMob - Basic">
<AdMobBanner
adSize="banner"
adUnitID="ca-app-pub-3940256099942544/2934735716"
ref={el => (this._basicExample = el)}
/>
<Button
title="Reload"
onPress={() => this._basicExample.loadBanner()}
/>
</BannerExample>
<BannerExample title="Rewarded">
<Button
title="Show Rewarded Video and preload next"
onPress={this.showRewarded}
/>
</BannerExample>
<BannerExample title="Interstitial">
<Button
title="Show Interstitial and preload next"
onPress={this.showInterstitial}
/>
</BannerExample>
<BannerExample title="DFP - Multiple Ad Sizes">
<PublisherBanner
adSize="banner"
validAdSizes={['banner', 'largeBanner', 'mediumRectangle']}
adUnitID="/6499/example/APIDemo/AdSizes"
ref={el => (this._adSizesExample = el)}
/>
<Button
title="Reload"
onPress={() => this._adSizesExample.loadBanner()}
/>
</BannerExample>
<BannerExample title="DFP - App Events" style={this.state.appEventsExampleStyle}>
<PublisherBanner
style={{ height: 50 }}
adUnitID="/6499/example/APIDemo/AppEvents"
onAdmobDispatchAppEvent={(event) => {
if (event.name === 'color') {
this.setState({
appEventsExampleStyle: { backgroundColor: event.info },
});
}
}}
ref={el => (this._appEventsExample = el)}
/>
<Button
title="Reload"
onPress={() => this._appEventsExample.loadBanner()}
style={styles.button}
/>
</BannerExample>
<BannerExample title="DFP - Fluid Ad Size">
<View
style={[
{ backgroundColor: '#f3f', paddingVertical: 10 },
this.state.fluidAdSizeExampleStyle,
]}
>
<PublisherBanner
adSize="fluid"
adUnitID="/6499/example/APIDemo/Fluid"
ref={el => (this._appFluidAdSizeExample = el)}
style={{ flex: 1 }}
/>
</View>
<Button
title="Change Banner Width"
onPress={() => this.setState(prevState => ({
fluidSizeIndex: prevState.fluidSizeIndex + 1,
fluidAdSizeExampleStyle: { width: bannerWidths[prevState.fluidSizeIndex % bannerWidths.length] },
}))}
style={styles.button}
/>
<Button
title="Reload"
onPress={() => this._appFluidAdSizeExample.loadBanner()}
style={styles.button}
/>
</BannerExample>
</ScrollView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
marginTop: (Platform.OS === 'ios') ? 30 : 10,
},
example: {
paddingVertical: 10,
},
title: {
margin: 10,
fontSize: 20,
},
});
AppRegistry.registerComponent('Example', () => Example);
|
JavaScript
| 0.000003 |
@@ -909,28 +909,22 @@
%0A (
-type, amount
+reward
) =%3E con
@@ -966,20 +966,14 @@
r',
-type, amount
+reward
)%0A
|
a21089b71893b3ee00c547f35bab0fac794db35a
|
include clinician
|
myuw/static/js/card/accounts/hr_payroll_card.js
|
myuw/static/js/card/accounts/hr_payroll_card.js
|
var HRPayrollCard = {
name: 'HRPayrollCard',
dom_target: undefined,
render_init: function() {
var source = $("#hr_payroll_card").html();
var template = Handlebars.compile(source);
var compiled = template({
card_name: HRPayrollCard.name,
is_faculty: window.user.faculty,
is_employee: window.user.employee,
is_stud_employee: window.user.stud_employee
});
HRPayrollCard.dom_target.html(compiled);
LogUtils.cardLoaded(HRPayrollCard.name, HRPayrollCard.dom_target);
}
};
/* node.js exports */
if (typeof exports == "undefined") {
var exports = {};
}
exports.HRPayrollCard = HRPayrollCard;
|
JavaScript
| 0.000433 |
@@ -343,32 +343,33 @@
is_employee:
+(
window.user.empl
@@ -372,16 +372,42 @@
employee
+ %7C%7C window.user.clinician)
,%0A
|
0c8725c8a5c363b8465d5ef4e34dc4b1691df773
|
fix modal
|
client/app/activity_detail/ad_participates_item.js
|
client/app/activity_detail/ad_participates_item.js
|
import React from 'React';
import {hashHistory} from 'react-router';
import {addFriend} from '../server';
import {hideElement} from '../util';
import {socket,getToken} from '../credentials';
var debug = require('react-debug');
export default class Ad_participates_item extends React.Component{
constructor(props){
super(props);
this.state = {
data: props.data,
success:false
}
}
handleRedirect(e){
e.preventDefault();
hashHistory.push("profile/"+this.props.data._id);
}
checkFriendsOfUser(){
if(this.props.friends===undefined){
return false;
}
return this.props.friends.filter((friend)=>{
if(friend._id===this.props.data._id)
return true;
else return false;
}).length>0;
}
handleAddFriend(e){
e.preventDefault();
debug("----gg---------------------------------------this.props.currUser")
addFriend(this.props.currUser,this.props.data._id,(success)=>{
if(success){
debug("-------------------------------------------this.props.currUser")
debug(this.props.currUser)
socket.emit('notification',{
authorization:getToken(),
sender: this.props.currUser,
target: this.props.data._id
});
this.setState({
success:true
});
}
});
}
render(){
return(
<li className="media">
<div className={"alert alert-success "+hideElement(!this.state.success)} role="alert">Request sent!</div>
<div className="media-left">
<a onClick={(e)=>this.handleRedirect(e)} data-dismiss="modal" aria-label="Close">
<img className="media-object" src={this.props.data.avatar} height="55px" alt="..."/>
</a>
</div>
<div className="media-body media-top">
{this.props.data.fullname}<br/>
{this.props.data.description}
</div>
<div className="media-body media-right" style={{textAlign:"right"}} >
<a href="#" onClick={(e)=>this.handleAddFriend(e)}><i className={"fa fa-user-plus pull-right "+hideElement(this.checkFriendsOfUser()||this.props.data._id===this.props.currUser)} style={{'paddingRight':'20px'}} aria-hidden="true"></i></a>
<i className={"fa fa-check pull-right "+hideElement(!this.checkFriendsOfUser())} style={{color:'green','paddingRight':'20px',textAlign:"right"}} aria-hidden="true"></i>
</div>
</li>
)
}
}
|
JavaScript
| 0.000001 |
@@ -1818,32 +1818,36 @@
top%22%3E%0A
+%3Ch5%3E
%7Bthis.props.da
@@ -1863,11 +1863,11 @@
me%7D%3C
-br/
+/h5
%3E%0A
@@ -1868,24 +1868,30 @@
h5%3E%0A
+ %3Ch5%3E
%7Bthis.pr
@@ -1911,16 +1911,21 @@
ription%7D
+%3C/h5%3E
%0A
@@ -2005,16 +2005,28 @@
:%22right%22
+,width:'0px'
%7D%7D %3E%0A
@@ -2408,26 +2408,8 @@
0px'
-,textAlign:%22right%22
%7D%7D a
|
d41435b7e64c7800b8e3a9b6ed317af5a666dc0b
|
fix redundancy
|
server/config/db.config.js
|
server/config/db.config.js
|
const Sequelize = require('sequelize')
const creds = require('./credentials') // grabbing the data from credentials.json
/* NOTE: that file is gitignored, add instructions on how to get
username and password!
*/
// creates database connection credentials needed to connect to DB via Sequelize
const dburl = `postgres://${creds.username}:${creds.password}@tantor.db.elephantsql.com:5432/sritpzob`
// MARK, connect our db here!;
const dbConnection = new Sequelize('postgres://sritpzob:[email protected]:5432/sritpzob')
// Don't delete. May be useful later.
// db.on('connected', function () {
// console.log('Connected to database successfully.');
// });
// db.on('disconnected', function () {
// console.log('Disconnected from database!');
// });
// db.on('error', function (err) {
// console.log('Connectioned failed with error:', err);
// });
// process.on('SIGINT', function () {
// db.close(function () {
// console.log('Process terminated. SOME DUDE PRESSED CONTROL+C!?');
// process.exit(0);
// });
// });
// process.once('SIGUSR2', function () {
// db.close(function () {
// console.log('Process terminated by nodemon.');
// process.kill(process.pid, 'SIGUSR2');
// });
// });
module.exports = dbConnection
require('../api/poi/poi.model.js')
require('../api/users/users.model.js')
require('../api/reviews/reviews.model.js')
|
JavaScript
| 0.000148 |
@@ -472,100 +472,13 @@
ze('
-postgres://sritpzob:[email protected]:5432/sritpzob
+dburl
')%0A%0A
|
266ddafe744728ecd08dd8e20edb0d04fd0e3548
|
fix lint
|
client/app/components/_topbar/topbar.controller.js
|
client/app/components/_topbar/topbar.controller.js
|
class TopbarController {
constructor(Authentication, SessionUser, $window, ScreenSize, $scope, $rootScope, $mdSidenav, $timeout) {
"ngInject";
Object.assign(this, {
Authentication,
SessionUser,
ScreenSize,
$mdSidenav,
$scope,
$rootScope,
$timeout,
reloadPage: () => $window.location.reload() // makes it easier to stub
});
}
$onInit() {
this.Authentication.update();
}
openSidenav() {
this.listeners = [];
this.$mdSidenav("left").onClose(() => this.listeners.map((deregister) => deregister()));
return this.$mdSidenav("left")
.open()
.then(() => {
let close = () => this.$mdSidenav("left").close();
this.listeners = [
this.$scope.$on("$locationChangeStart", close),
this.$rootScope.$on("$translateChangeSuccess", close)
];
});
}
logOut(){
this.Authentication.logout()
.then(() => {
this.reloadPage();
}, () => {
//Logout failed!
});
}
showPreviewHint() {
return this.SessionUser.isLoggedIn() && !window.localStorage.getItem("hidePreviewHint");
}
hidePreviewHint() {
console.log(window.localStorage.getItem("hidePreviewHint"));
this.$timeout(() => {
window.localStorage.setItem("hidePreviewHint", true);
console.log(window.localStorage.getItem("hidePreviewHint"));
})
}
}
export default TopbarController;
|
JavaScript
| 0.000013 |
@@ -1170,74 +1170,8 @@
() %7B
-%0A%0A console.log(window.localStorage.getItem(%22hidePreviewHint%22));
%0A
@@ -1261,77 +1261,11 @@
-
- console.log(window.localStorage.getItem(%22hidePreviewHint%22));%0A
%7D)
+;
%0A %7D
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.