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
|
---|---|---|---|---|---|---|---|
480dfa7aba5543c0ad33856423a5deb04a70ca86
|
Add JSON attribute codec support
|
app/assets/javascripts/gatemedia/data/implementation/codec.js
|
app/assets/javascripts/gatemedia/data/implementation/codec.js
|
Data.Codec = Ember.Object.extend({
decode: function (value/*, qualifier*/) {
return value;
},
encode: function (value/*, qualifier*/) {
return value;
}
});
Data.codec = {
string: Data.Codec.create({
decode: function (value) {
if (Ember.isNone(value)) {
return value;
}
switch (Ember.typeOf(value)) {
case 'string':
return value;
case 'object':
return JSON.stringify(value);
default:
Ember.Logger.warn('string codec returning raw %@ value:'.fmt(Ember.typeOf(value)), value);
return value;
}
},
encode: function (value/*, qualifier*/) {
if (!Ember.isNone(value)) {
return '%@'.fmt(value);
}
return null;
}
}),
number: Data.Codec.create({
decode: function (value/*, qualifier*/) {
if (Ember.typeOf(value) === 'number') {
return value;
}
return Number(value);
}
}),
boolean: Data.Codec.create({
encode: function (value/*, qualifier*/) {
return value ? true: false;
}
}),
array: Data.Codec.create({
decode: function (value, qualifier) {
if (value) {
return value.map(function (item) {
return Data.codec[qualifier].decode(item);
});
}
return null;
},
encode: function (value, qualifier) {
if (value) {
return value.map(function (item) {
return Data.codec[qualifier].encode(item);
});
}
}
}),
date: Data.Codec.create({
decode: function (value/*, qualifier*/) {
if (Ember.typeOf(value) === 'date') {
return moment(value);
}
return moment(value, 'YYYY-MM-DD');
},
encode: function (value/*, qualifier*/) {
if (value) {
return value.format('YYYY-MM-DD');
}
return null;
}
}),
time: Data.Codec.create({
decode: function (value/*, qualifier*/) {
return moment(value, 'HH:mm');
},
encode: function (value/*, qualifier*/) {
if (value) {
return value.format('HH:mm');
}
return null;
}
}),
datetime: Data.Codec.create({
decode: function (value/*, qualifier*/) {
return moment(value, 'YYYY-MM-DDTHH:mm:ssZ');
},
encode: function (value/*, qualifier*/) {
if (value) {
return value.format('YYYY-MM-DDTHH:mm:ssZ');
}
return null;
}
})
};
|
JavaScript
| 0 |
@@ -2392,20 +2392,296 @@
null;%0A %7D%0A
+ %7D),%0A%0A json: Data.Codec.create(%7B%0A decode: function (value/*, qualifier*/) %7B%0A return JSON.stringify(value);%0A %7D,%0A%0A encode: function (value/*, qualifier*/) %7B%0A if (value === undefined) %7B%0A return undefined;%0A %7D%0A return JSON.parse(value);%0A %7D%0A
%7D)%0A%7D;%0A
|
fb5c60c57c21b4389905b2549688e67649b7b205
|
Add check for undefined data in sql-viewer
|
app/components/visualization/page-setup/sidebar/sql-viewer.js
|
app/components/visualization/page-setup/sidebar/sql-viewer.js
|
import Component from '@ember/component';
import { inject as service } from "@ember/service";
import { computed } from '@ember/object';
export default Component.extend({
// No Ember generated container
tagName: '',
landscapeRepo: service("repos/landscape-repository"),
additionalData: service('additional-data'),
store: service(),
sortOrder: 'asc',
sortBy: 'timestamp',
filterTerm: '',
// Compute current traces when highlighting changes
databaseQueries: computed('landscapeRepo.latestApplication.databaseQueries', 'sortOrder', 'filterTerm', function () {
return this.filterAndSortQueries(this.get('landscapeRepo.latestApplication.databaseQueries'));
}),
filterAndSortQueries(queries) {
let filteredQueries = [];
let filter = this.get('filterTerm');
queries.forEach((query) => {
if (filter === ''
|| query.get('sqlStatement').toLowerCase().includes(filter)) {
filteredQueries.push(query);
}
});
if (this.get('sortOrder') === 'asc') {
filteredQueries.sort((a, b) => (a.get(this.get('sortBy')) > b.get(this.get('sortBy'))) ? 1 : ((b.get(this.get('sortBy')) > a.get(this.get('sortBy'))) ? -1 : 0));
} else {
filteredQueries.sort((a, b) => (a.get(this.get('sortBy')) < b.get(this.get('sortBy'))) ? 1 : ((b.get(this.get('sortBy')) < a.get(this.get('sortBy'))) ? -1 : 0));
}
return filteredQueries;
},
actions: {
queryClicked(query) {
// Allow deselection of query
if (query.get('isSelected')) {
query.set('isSelected', false);
return;
}
// Deselect potentially selected query
let queries = this.get('store').peekAll('databasequery');
queries.forEach((query) => {
query.set('isSelected', false);
});
// Mark new query as selected
query.set('isSelected', true);
},
filter() {
// Case insensitive string filter
this.set('filterTerm', this.get('filterInput').toLowerCase());
},
sortBy(property) {
// Determine order for sorting
if (this.get('sortBy') === property) {
// Toggle sorting order
if (this.get('sortOrder') === 'asc') {
this.set('sortOrder', 'desc');
} else {
this.set('sortOrder', 'asc');
}
} else {
// Sort in ascending order by default
this.set('sortOrder', 'asc');
}
// Set property by which shall be sorted
this.set('sortBy', property);
},
close() {
this.get('additionalData').removeComponent("visualization/page-setup/sidebar/sql-viewer");
},
},
});
|
JavaScript
| 0 |
@@ -709,24 +709,69 @@
(queries) %7B%0A
+%0A if (!queries) %7B%0A return %5B%5D;%0A %7D%0A%0A
let filt
|
91f6b6d7dfd42f5f0b97ce177d749495ca87306c
|
Add method to edit gist
|
src/github.js
|
src/github.js
|
import qs from 'querystring'
import {Base64} from 'js-base64'
import fetch from 'unfetch'
export default class GitHub extends Component {
constructor(user, pass) {
this.authorization = Base64.encode(`${user}:${pass}`)
}
makeHeaders() {
return {
'If-Modified-Since': 'Mon, 26 Jul 1997 05:00:00 GMT',
'Authorization': `Basic ${this.authorization}`
}
}
async getUser() {
let res = await fetch('https://api.github.com/user', {
headers: makeHeaders()
})
if (!res.ok) throw new Error(res.statusText)
return res.json()
}
async getGist(id) {
let res = await fetch(`https://api.github.com/gists/${id}`, {
headers: makeHeaders()
})
if (!res.ok) throw new Error(res.statusText)
return res.json()
}
async getGistContent(id) {
let gist = this.getGist(id)
let fileNames = Object.keys(gist.files)
let file = gist.files[fileNames[0]]
if (file == null) throw new Error('File not found')
if (!file.truncated) return file.content
let res = await fetch(file.raw_url)
if (!res.ok) throw new Error('Could not retrieve file')
return res.text()
}
async createGist(options) {
let res = await fetch('https://api.github.com/gists', {
method: 'POST',
headers: {
...makeHeaders(),
'Content-Type': 'application/json'
},
body: JSON.stringify(options)
})
if (!res.ok) throw new Error(res.statusText)
return res.json()
}
}
|
JavaScript
| 0 |
@@ -872,16 +872,21 @@
getGist
+First
Content(
@@ -1563,32 +1563,428 @@
ns)%0A %7D)%0A%0A
+ if (!res.ok) throw new Error(res.statusText)%0A return res.json()%0A %7D%0A%0A async editGist(id, options) %7B%0A let res = await fetch(%60https://api.github.com/gists/$%7Bid%7D%60, %7B%0A method: 'PATCH',%0A headers: %7B%0A ...makeHeaders(),%0A 'Content-Type': 'application/json'%0A %7D,%0A body: JSON.stringify(options)%0A %7D)%0A%0A
if (!res
|
12beef210a4f32cb3837ec503a46ac426899a7ca
|
Fix liniting issue with fileContent
|
extension.js
|
extension.js
|
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
var vscode = require('vscode');
var path = require('path');
YAML = require('yamljs');
var ports = {}
, servers = {}
, ios = {}
;
class Viewer {
constructor(context) {
this.context = context;
this.uri = vscode.Uri.parse('swagger://preview');
this.Emmittor = new vscode.EventEmitter();
this.onDidChange = this.Emmittor.event;
}
provideTextDocumentContent(uri, token) {
var port = this.port || 9000;
var html = `
<html>
<body style="margin:0px;padding:0px;overflow:hidden">
<div style="position:fixed;height:100%;width:100%;">
<iframe src="http://localhost:${port}" frameborder="0" style="overflow:hidden;height:100%;width:100%" height="100%" width="100%"></iframe>
</div>
</body>
</html>
`;
return html;
}
display() {
var editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
return vscode.commands.executeCommand('vscode.previewHtml', this.uri, vscode.ViewColumn.Two, 'Swagger Preview - ' + path.basename(editor.document.fileName.toLowerCase()))
.then(success => {
vscode.window.showTextDocument(editor.document);
}, reason => {
vscode.window.showErrorMessage(reason);
});
}
register() {
var ds = [];
var disposable = vscode.workspace.registerTextDocumentContentProvider('swagger', this);
ds.push(disposable);
return ds;
}
setPort(port) {
this.port = port;
}
upate() {
this.Emmittor.fire(this.uri);
}
};
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
function activate(context) {
// var viewer = new Viewer(context);
// var ds = viewer.register();
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
var lastDefaultPort
var defaultPort = lastDefaultPort = vscode.workspace.getConfiguration('swaggerViewer').defaultPort || 9000;
var disposable = vscode.commands.registerCommand('extension.previewSwagger', function () {
var openBrowser = vscode.workspace.getConfiguration('swaggerViewer').previewInBrowser || false;
if(vscode.workspace.getConfiguration('swaggerViewer').defaultPort && lastDefaultPort != vscode.workspace.getConfiguration('swaggerViewer').defaultPort){
defaultPort = lastDefaultPort = vscode.workspace.getConfiguration('swaggerViewer').defaultPort
}
let handlePreviewResponse = (option) => {
if (typeof option == 'undefined') {
return;
}
if (option.action == "open") {
let uri = vscode.Uri.parse(option.url);
vscode.commands.executeCommand('vscode.open', uri);
}
};
var editor = vscode.window.activeTextEditor;
if (!editor) {
return;
}
var doc = editor.document;
var fileName = doc.fileName.toLowerCase();
if (!servers[fileName]) {
// Display a message box to the user
//vscode.window.showInformationMessage('Hello World!');
var express = require('express');
var http = require('http');
var app = express();
app.use(express.static(path.join(__dirname, 'static')));
//app.set('port', 3002);
var server = http.createServer(app);
var io = require('socket.io')(server);
function startServer(port) {
app.set('port', port);
try {
server.listen(port, function (err) {
servers[fileName] = server;
ports[fileName] = port;
ios[fileName] = io;
if (openBrowser) {
vscode.window.showInformationMessage('Preview "' + path.basename(fileName) + '" in http://localhost:' + port + "/",
{
title: 'Open',
action: 'open',
url: 'http://localhost:' + port + '/'
}).then(handlePreviewResponse);
} else {
var viewer = new Viewer(context);
var ds = viewer.register();
context.subscriptions.push(...ds);
viewer.setPort(port);
viewer.display();
viewer.upate();
}
//console.log('Example app listening on port 3000!');
ios[fileName].on("connection", function (socket) {
socket.on("GET_INITIAL", function (data, fn) {
fn(GetParsedFile(fileName, doc));
})
})
var previewSwagger = new PreviewSwagger(fileName);
var previewSwaggerController = new PreviewSwaggerController(previewSwagger);
context.subscriptions.push(previewSwagger);
context.subscriptions.push(previewSwaggerController);
previewSwagger.update();
defaultPort++;
//viewer.upate();
});
server.on("error", function (err) {
startServer(++defaultPort);
})
}
catch (ex) {
startServer(++defaultPort);
}
}
startServer(defaultPort);
}
else{
if (openBrowser) {
vscode.window.showInformationMessage('Preview "' + path.basename(fileName) + '" in http://localhost:' + ports[fileName] + "/",
{
title: 'Open',
action: 'open',
url: 'http://localhost:' + ports[fileName] + '/'
}).then(handlePreviewResponse);
} else {
var viewer = new Viewer(context);
var ds = viewer.register();
context.subscriptions.push(...ds);
viewer.setPort(ports[fileName]);
viewer.display();
viewer.upate();
}
}
});
context.subscriptions.push(disposable);
//context.subscriptions.push(...ds);
}
function GetParsedFile(fileName, document) {
fileContent = document.getText();
if (document.languageId === "json") {
return JSON.parser(fileContent);
} else if (document.languageId === "yaml") {
return YAML.parse(fileContent);
} else if (document.languageId === "plaintext") {
if (fileContent.match(/^\s*[{[]/)) {
return JSON.parser(fileContent);
} else {
return YAML.parse(fileContent);
}
}
}
function GetFilenameExtension(fileName) {
return fileName.split('.').pop();
}
function PreviewSwagger(fileName) {
var editor = vscode.window.activeTextEditor;
var doc = editor.document;
this.update = function () {
ios[fileName].emit("TEXT_UPDATE", GetParsedFile(fileName, doc));
}
this.close = function () {
servers[fileName].close();
}
}
function PreviewSwaggerController(swag) {
var subscriptions = [];
function update() {
var editor = vscode.window.activeTextEditor;
if (!editor) { return; }
var doc = editor.document;
if (doc.languageId === "yaml" || doc.languageId === "json" || doc.languageId === "plaintext" ) {
swag.update();
} else {
swag.close();
}
}
vscode.window.onDidChangeActiveTextEditor(update, this, subscriptions);
vscode.window.onDidChangeTextEditorSelection(update, this, subscriptions);
swag.update();
}
exports.activate = activate;
// this method is called when your extension is deactivated
function deactivate() {
}
exports.deactivate = deactivate;
|
JavaScript
| 0 |
@@ -7155,16 +7155,20 @@
) %7B%0A
+var
fileCont
|
de3089cd37b3a0e9309f4665574ab6f616a34023
|
fix typo: "%{humanLevel}" -> "${humanLevel}"
|
src/index.es6
|
src/index.es6
|
'use strict'
import { debugEvents, debugMethods } from 'simple-debugger'
import { extend, trim, merge, map, mapValues,
isArray, isNumber, isString, isRegExp,
isFunction, isObject, isBoolean } from 'lodash'
import { projectVersion, projectName, projectHost } from './projectInfo'
import { inspect } from 'util'
import P from 'bluebird'
import Debug from 'debug'
import winston from 'winston'
import moment from 'moment'
import clearRequire from 'clear-require'
import validate from './validate'
let wtgDebug = new Debug('libs-winston-tcp-graylog')
class WinstonTcpGraylog extends winston.Transport {
constructor(config = {}) {
super()
debugEvents(this)
debugMethods(this, [ 'on', 'once', 'emit',
'addListener', 'removeListener' ])
this._setupConfig(config)
this._setupLevelMap()
this._setupBaseMsg()
this._setupGelf()
let baseConfig = {
name: 'tcpGraylog',
silent: false,
level: 'info',
handleExceptions: false,
humanReadableUnhandledException: false,
formatter: v => v
}
merge(this, baseConfig, this._config)
this.log = this.log.bind(this)
}
_setupConfig(config) {
let err = validate('config', config)
if (err) throw new Error(`WinstonTcpGraylog#new problem: config has wrong format!\
\n\t config: ${inspect(config)}\
\n\t err: ${inspect(err)}`)
this._config = config
wtgDebug('config: %j', config)
return this
}
_setupLevelMap() {
let myMap = {
'emergency': 0,
'emerg': 0,
'alert': 1,
'critical': 2,
'crit': 2,
'error': 3,
'err': 3,
'warning': 4,
'warn': 4,
'notice': 5,
'note': 5,
'information': 6,
'info': 6,
'log': 6,
'debug': 7
}
this._levelMap = extend(myMap, this._config.levelMap)
wtgDebug('levelMap: %j', this._levelMap)
return this
}
_setupBaseMsg() {
let appVersion = projectVersion()
let facility = projectName()
let host = projectHost()
let myBaseMsg = { appVersion, facility, host }
this._baseMsg = extend(myBaseMsg, this._config.baseMsg)
wtgDebug('baseMsg: %j', this._baseMsg)
return this
}
_setupGelf() {
clearRequire('gelf-pro')
this._gelf = require('gelf-pro')
this._gelf.setConfig(this._config.gelfPro)
wtgDebug('gelfPro: %j', this._config.gelfPro)
return this
}
_normalizeMeta(object) {
let myMap = isArray(object)
? map
: mapValues
return myMap(object, v => {
if (isObject(v) && v.message && v.stack) {
return { message: v.message, stack: v.stack }
} else if (isFunction(v) || isRegExp(v) || isBoolean(v)) {
return v.toString()
} else if (isObject(v)) {
return this._normalizeMeta(v)
} else {
return v
}
})
}
log(humanLevel, fmtMsg, rawMeta, callback) {
if (this.silent) {
let res = `WinstonTcpGraylog#handler skip: module was silent!`
wtgDebug(res)
this.emit('skip', res)
return callback(null, res)
}
// prepare resMsg
let level = this._levelMap[humanLevel]
if (!isNumber(level)) {
let err = new Error(`WinstonTcpGraylog#handler problem: level not found! \
\n\t humanLevel: %{humanLevel}`)
wtgDebug(err)
this.emit('error', err)
return callback(err)
}
let short_message = fmtMsg
.split(/[\r\t\n]/)
.filter(v => isString(v) && (trim(v).length > 0))[0]
if (short_message.length === 0) {
let res = `WinstonTcpGraylog#handler skip: catch empty message: \
\n\t fmtMsg: ${fmtMsg} \
\n\t rawMeta: ${inspect(rawMeta)}`
wtgDebug(res)
this.emit('skip', res)
return callback(null, res)
}
let full_message = fmtMsg
let humanTime = moment().format('DD/MM HH:mm:ss (Z)')
let curMsg = { level, humanLevel, short_message, full_message, humanTime }
let resMsg = this._normalizeMeta(extend({}, this._baseMsg, rawMeta, curMsg))
// prepare and send gelfMsg
let gelfMsg = this._gelf.getStringFromObject(resMsg)
return P
.fromNode(cb => this._gelf.send(gelfMsg, cb))
.then(res => {
wtgDebug('send', gelfMsg)
this.emit('send', gelfMsg, res)
callback(null, gelfMsg, res)
})
.catch((rawErr = {}) => {
let message = `WinstonTcpGraylog#handler problem: gelf-pro return error! \
\n\t err: ${rawErr.message || inspect(rawErr)}`
let err = rawErr.message
? extend(rawErr, { message })
: new Error(message)
wtgDebug(err)
this.emit('error', err)
callback(err)
})
}
}
export default WinstonTcpGraylog
winston.transports.TcpGraylog = WinstonTcpGraylog
|
JavaScript
| 0.999967 |
@@ -3267,17 +3267,17 @@
nLevel:
-%25
+$
%7BhumanLe
|
92bd004447ef5fdaad043274a9fb8b51eac8648e
|
Introduce inject HOC to inect app().xxx domains etc
|
src/inject.js
|
src/inject.js
|
import { Component } from 'react'
import setDisplayName from 'recompose/setDisplayName'
import wrapDisplayName from 'recompose/wrapDisplayName'
import createEagerFactory from 'recompose/createEagerFactory'
import fromPairs from 'lodash/fromPairs'
import { app } from '@mindhive/di'
const inspect = domains => (BaseComponent) => {
const factory = createEagerFactory(BaseComponent)
class Inject extends Component {
render() {
return factory({
...this.props,
...fromPairs((domains || []).map(d => [d, app()[d]])),
})
}
}
if (process.env.NODE_ENV !== 'production') {
return setDisplayName(wrapDisplayName(BaseComponent, 'inject'))(
Inject
)
}
return Inject
}
export default inspect
|
JavaScript
| 0 |
@@ -281,23 +281,22 @@
i'%0A%0A
-const inspect =
+export default
dom
@@ -719,27 +719,4 @@
%0A%7D%0A%0A
-export default inspect%0A
|
921d0336f905c94cd3b30796e71d63f5f1f67d9a
|
fix loosing parameters on index.html redirect
|
src/js/app.js
|
src/js/app.js
|
'use strict';
var app = angular.module('App', [
'ui.bootstrap',
'ui.toggle',
'angular-loading-bar',
'ngRoute',
'pascalprecht.translate',
'ngResource',
'angular-svg-round-progressbar',
'favicon',
'angularGrid',
'dcbImgFallback',
'angularMoment',
'LocalStorageModule',
'hc.marked',
'sticky',
])
.directive('hideUntilGood', function() {
return {
restrict: 'A',
multiElement: true,
link: function(scope, element, attrs) {
attrs.$observe('ngSrc', function(value) {
if (!value || value.length === 0) {
element.attr('src', value);
}
element.css('display', 'none');
});
element.bind('load', function() {
element.css('display', '');
});
},
};
})
.config(function($routeProvider, $translateProvider,
$locationProvider, localStorageServiceProvider) {
$translateProvider
.useStaticFilesLoader({
prefix: 'locales/locale-',
suffix: '.json',
})
.useSanitizeValueStrategy('sce')
.preferredLanguage('en');
$locationProvider.html5Mode({
enabled: true,
requireBase: false,
});
$routeProvider
.when('/', {
templateUrl: 'views/search.html',
controller: 'SearchController',
})
.when('/about', {
templateUrl: 'views/static.html',
controller: 'StaticController',
})
.when('/disclaimer', {
templateUrl: 'views/static.html',
controller: 'StaticController',
})
.when('/privacy', {
templateUrl: 'views/static.html',
controller: 'StaticController',
})
.when('/help', {
templateUrl: 'views/static.html',
controller: 'StaticController',
})
.when('/images', {
templateUrl: 'views/image.html',
controller: 'ImageController',
})
.when('/news', {
templateUrl: 'views/news.html',
controller: 'NewsController',
})
.when('/pro', {
templateUrl: 'views/search.html',
controller: 'ProController',
})
.when('/settings', {
templateUrl: 'views/settings.html',
controller: 'SettingsController',
})
.when('/language', {
templateUrl: 'views/language.html',
controller: 'LanguageController',
})
.when('/apps', {
templateUrl: 'views/apps.html',
controller: 'ApplicationsController',
})
.otherwise('/');
localStorageServiceProvider
.setPrefix('kcon')
.setDefaultToCookie(false);
});
|
JavaScript
| 0 |
@@ -2496,19 +2496,148 @@
herwise(
-'/'
+%7B%0A redirectTo: function() %7B%0A console.log(location.search);%0A return '/' + location.search;%0A %7D%0A %7D
);%0A%0A
|
c2a0443d0cd55fea1d1b82df2f66c7d4523c9bd7
|
Add static 'experiment' widget example
|
src/js/app.js
|
src/js/app.js
|
import React from 'react';
import ReactDOM from 'react-dom';
import pify from 'pify';
import 'babel-polyfill';
import * as uploader from './uploader.js';
import * as auth from './auth.js';
import ImageResponse from './image-response.js';
import TextResponse from './text-response.js';
import VideoInstruction from './video-instruction.js';
import HtmlWidget from './html-widget.js';
import Header from './header.js';
import '../scss/styles.scss';
import * as data from './data.js';
// const signInWithGoogle = () => {
// const rootRef = new Firebase("https://learning-prototype.firebaseio.com");
// rootRef.authWithOAuthPopup("google", function(error, authData) {
// if (error) {
// console.log("Login Failed!", error);
// } else {
// console.log("Authenticated successfully with payload:", authData);
// }
// });
// }
const Application = React.createClass({
componentDidMount: async function () {
data.onUpdate((data) => {
console.log('updated data');
this.setState({data});
});
await auth.whenLoggedIn();
this.setState({loggedIn: true});
},
getInitialState: function () {
return {
data: {}
};
},
render: function () {
return (
<div>
<Header lock={this.lock} authProfile={this.state.authProfile} loggedIn={this.state.loggedIn} />
<main id="main" className="content">
<div className="pure-g">
<div className="pure-u-1">
<HtmlWidget time="4">
<h3>Learn</h3>
<p>Why do plants produce flowers? Watch this video to find out.</p>
<VideoInstruction videoId="EArZXsRXsj4" />
</HtmlWidget>
</div>
<div className="pure-u-1">
<HtmlWidget time="6">
<h3>Reflect</h3>
<p>Take a picture and drop it here</p>
<ImageResponse itemId="step-1" loggedIn={this.state.loggedIn} response={this.state.data['step-1']} />
</HtmlWidget>
</div>
<div className="pure-u-1 row-gap-medium">
<HtmlWidget time="10">
<TextResponse itemId="step-2" loggedIn={this.state.loggedIn} response={this.state.data['step-2']} />
</HtmlWidget>
</div>
</div>
</main>
</div>
);
}
})
ReactDOM.render(<Application />, document.getElementById('application'));
|
JavaScript
| 0.000005 |
@@ -2277,32 +2277,528 @@
%3C/div%3E%0A
+ %3Cdiv className=%22pure-u-1 row-gap-medium%22%3E%0A %3CHtmlWidget time=%2210%22%3E%0A %3Ch3%3EConduct your own experiment%3C/h3%3E%0A %3Cp%3E%0A Follow the instructions in the link on how to conduct your own experiment on flowers. %3Ca href=%22http://goo.gl/cuf63n%22%3Ehttp://goo.gl/cuf63n%3C/a%3E%0A %3C/p%3E%0A %3Cimg src=%22http://cdn.instructables.com/FA6/OOPP/I916FK0J/FA6OOPPI916FK0J.MEDIUM.jpg%22 /%3E%0A %3C/HtmlWidget%3E%0A %3C/div%3E%0A
%3C/div%3E
|
eea9259ca0e65dc56ef0fd4b87a6140087e32610
|
modify JS file
|
src/js/app.js
|
src/js/app.js
|
angular.module('InvertedIndexApp', [])
.controller('AppController', ($scope) => {
$scope.appName = 'Inverted Index';
$scope.myInvertedIndex = new InvertedIndex();
$scope.indexTable = '';
$scope.indexTableFiles = [];
$scope.searchResults = '';
$scope.availableFiles = [];
$scope.currentFile = '';
const uploadField = document.getElementById('upload');
uploadField.addEventListener('change', (e) => {
const selectedFiles = e.target.files;
for (let file = 0; file < selectedFiles.length; file += 1) {
$scope.readAndCheckFile(selectedFiles[file]);
}
});
$scope.readAndCheckFile = (selected) => {
$scope.filename = selected.name;
const acceptedFIleType = 'application/json';
if (Object.is(selected.type, acceptedFIleType)) {
const reader = new FileReader();
reader.onload = () => {
try {
const currentContent = JSON.parse(reader.result);
if (InvertedIndexUtilities.validateData(currentContent)) {
$scope.myInvertedIndex.files[selected.name] = currentContent;
$scope.$apply(() => {
$scope.availableFiles = Object
.key($scope.myInvertedIndex.files);
$scope.currentFile = $scope.filename;
});
} else {
swal('Oops...', `Invalid JSON format!
Please select a valid JSON file`);
}
} catch (err) {
swal('Oops...', `Invalid JSON format!
Please select a valid JSON file`);
}
};
reader.readAsText(selected);
} else {
swal('Oops...', `Invalid file format!
Please select a JSON file`);
}
};
$scope.arrayFromFileLength = (fileName) => {
const selectBox = document.getElementById('file-to-index');
const fileToIndex = selectBox.options[selectBox.selectedIndex].value;
const fileLength = $scope.myInvertedIndex.files[fileToIndex].length;
const arr = [];
for (let fileIndex = 0; fileIndex < fileLength; fileIndex += 1) {
arr.push(fileIndex);
}
return arr;
};
$scope.createIndex = () => {
const selectBox = document.getElementById('file-to-index');
const fileToIndex = selectBox.options[selectBox.selectedIndex].value;
if (fileToIndex !== '') {
$scope.myInvertedIndex.createIndex(fileToIndex);
$scope.indexTable = $scope.myInvertedIndex.getIndex(fileToIndex);
$scope.currentFile = '';
} else {
swal({
title: 'Are you sure you have selected a file?',
text: `I'm just saying cos I don't think you have!
Now kindly select a file, then create index.`,
type: 'error',
confirmButtonText: 'Ok'
});
}
};
const searchField = document.getElementById('search');
searchField.addEventListener('keyup', (e) => {
const selectSearch = document.getElementById('file-to-search');
const fileToSearch = selectSearch
.options[selectSearch.selectedIndex].value;
const keyValue = e.target.value;
$scope.$apply(() => {
if (fileToSearch === '') {
$scope.searchResults = $scope.myInvertedIndex.searchIndex(keyValue);
} else {
$scope.searchResults = $scope.myInvertedIndex
.searchIndex(keyValue, fileToSearch);
}
});
});
});
$(document).ready(() => {
$('select').material_select();
$('.collapsible').collapsible();
$('select').on('DOMSubtreeModified', () => {
setTimeout(() => {
$('select').material_select();
}, 1000);
});
});
|
JavaScript
| 0.000001 |
@@ -1186,16 +1186,27 @@
= Object
+.key($scope
%0A
@@ -1214,27 +1214,16 @@
-.key($scope
.myInver
|
6b0974637862d200cd39317e0ca782498a75c4ee
|
Fix #238 - Change cache.push order
|
src/js/xhr.js
|
src/js/xhr.js
|
/*======================================================
************ XHR ************
======================================================*/
// XHR Caching
app.cache = [];
app.removeFromCache = function (url) {
var index = false;
for (var i = 0; i < app.cache.length; i++) {
if (app.cache[i].url === url) index = i;
}
if (index !== false) app.cache.splice(index, 1);
};
// XHR
app.xhr = false;
app.get = function (url, view, ignoreCache, callback) {
// should we ignore get params or not
var _url = url;
if (app.params.cacheIgnoreGetParameters && url.indexOf('?') >= 0) {
_url = url.split('?')[0];
}
if (app.params.cache && !ignoreCache && url.indexOf('nocache') < 0 && app.params.cacheIgnore.indexOf(_url) < 0) {
// Check is the url cached
for (var i = 0; i < app.cache.length; i++) {
if (app.cache[i].url === _url) {
// Check expiration
if ((new Date()).getTime() - app.cache[i].time < app.params.cacheDuration) {
// Load from cache
callback(app.cache[i].content);
return false;
}
}
}
}
app.xhr = $.ajax({
url: url,
method: 'GET',
start: app.params.onAjaxStart,
complete: function (xhr) {
if (xhr.status === 200 || xhr.status === 0) {
callback(xhr.responseText, false);
if (app.params.cache && !ignoreCache) {
app.removeFromCache(_url);
app.cache.push({
url: _url,
time: (new Date()).getTime(),
content: xhr.responseText
});
}
}
else {
callback(xhr.responseText, true);
}
if (app.params.onAjaxComplete) app.params.onAjaxComplete(xhr);
},
error: function (xhr) {
callback(xhr.responseText, true);
if (app.params.onAjaxError) app.params.onAjaxonAjaxError(xhr);
}
});
if (view) view.xhr = app.xhr;
return app.xhr;
};
|
JavaScript
| 0 |
@@ -1403,59 +1403,8 @@
) %7B%0A
- callback(xhr.responseText, false);%0A
@@ -1712,32 +1712,83 @@
%7D%0A
+ callback(xhr.responseText, false);%0A
%7D%0A
|
c98a6de202f6b8d591aea8563f5d097197a309e8
|
Change App's xhr to new DOM ajax methods
|
src/js/xhr.js
|
src/js/xhr.js
|
/*======================================================
************ XHR ************
======================================================*/
// XHR Caching
app.cache = [];
app.removeFromCache = function (url) {
var index = false;
for (var i = 0; i < app.cache.length; i++) {
if (app.cache[i].url === url) index = i;
}
if (index !== false) app.cache.splice(index, 1);
};
// XHR
app.xhr = false;
app.get = function (url, callback) {
if (app.params.cache && url.indexOf('nocache') < 0) {
// Check is the url cached
for (var i = 0; i < app.cache.length; i++) {
if (app.cache[i].url === url) {
// Check expiration
if ((new Date()).getTime() - app.cache[i].time < app.params.cacheDuration) {
// Load from cache
callback(app.cache[i].data);
return false;
}
}
}
}
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.onload = function (e) {
if (app.params.onAjaxComplete) {
app.params.onAjaxComplete(xhr);
}
$(document).trigger('ajaxComplete', {xhr: xhr});
if (callback) {
if (this.status === 200 || this.status === 0) {
callback(this.responseText, false);
if (app.params.cache) {
app.removeFromCache(url);
app.cache.push({
url: url,
time: (new Date()).getTime(),
data: this.responseText
});
}
}
else {
callback(this.responseText, true);
}
}
};
if (app.params.onAjaxStart) {
app.params.onAjaxStart(xhr);
}
$(document).trigger('ajaxStart', {xhr: xhr});
app.xhr = xhr;
xhr.send();
return xhr;
};
|
JavaScript
| 0 |
@@ -949,159 +949,81 @@
%7D%0A
+%0A
-var
+app.
xhr =
-new XMLHttpRequest();%0A xhr.open('GET', url, true);%0A xhr.onload = function (e) %7B%0A if (app.params.onAjaxComplete) %7B%0A
+$.ajax(%7B%0A url: url,%0A method: 'GET',%0A
ap
@@ -1014,25 +1014,30 @@
T',%0A
-
+start:
app.params.
@@ -1046,110 +1046,46 @@
Ajax
-Complete(xhr);%0A %7D%0A $(document).trigger('ajaxComplete', %7Bxhr: xhr%7D);%0A if (callback
+Start,%0A complete: function (xhr
) %7B%0A
@@ -1100,20 +1100,19 @@
if (
-this
+xhr
.status
@@ -1122,20 +1122,19 @@
200 %7C%7C
-this
+xhr
.status
@@ -1159,36 +1159,35 @@
callback(
-this
+xhr
.responseText, f
@@ -1434,20 +1434,19 @@
data:
-this
+xhr
.respons
@@ -1555,12 +1555,11 @@
ack(
-this
+xhr
.res
@@ -1602,17 +1602,8 @@
-%7D%0A %7D;%0A
@@ -1627,24 +1627,17 @@
Ajax
-Start) %7B%0A
+Complete)
app
@@ -1650,21 +1650,24 @@
s.onAjax
-Start
+Complete
(xhr);%0A
@@ -1673,95 +1673,187 @@
+
-%7D%0A $(document).trigger('ajaxStart', %7Bxhr: xhr%7D);%0A app.xhr =
+ %7D,%0A error: function (xhr) %7B%0A callback(xhr.responseText, true);%0A if (app.params.onAjaxError) app.params.onAjaxonAjaxError(
xhr
+)
;%0A
+
-xhr.send(
+ %7D%0A %7D
);%0A
+%0A
@@ -1859,16 +1859,20 @@
return
+app.
xhr;%0A%7D;%0A
|
f378488051456047f864b7fd5269b785c77de612
|
Add support for default key name
|
src/layout.js
|
src/layout.js
|
import XLSX from 'xlsx';
import {Table} from './table.js';
import {pad, validateRecord} from './utils.js';
function dimensions(sheet, row) {
let rows = 1, columns = 1;
for (let offset = 1; offset < sheet.rows; offset++) {
let label = sheet.get(row + offset, 0);
if (!label || label.length != 1 || label.charCodeAt(0) - 65 != offset - 1) {
break;
}
rows = offset;
}
for (let offset = 1; offset < sheet.columns; offset++) {
if (Number(sheet.get(row, offset)) != offset) {
break;
}
columns = offset;
}
return [rows, columns]
}
function validatePosition(string) {
if (!string.match(/[A-Z]\d+/)) {
throw `Invalid position: "${string}"`
}
return string;
}
function comparePositions(a, b) {
if(a.charCodeAt(0) == b.charCodeAt(0)) {
return a.substr(1) - b.substr(1);
}
return a.charCodeAt(0) - b.charCodeAt(0);
}
export class PlateLayout {
/**
*
* @param {Array|Object} contents
* @param name
* @param rows
* @param columns
*/
constructor(contents, {name = null, rows = null, columns = null} = {}) {
if(contents instanceof Array) {
this.contents = {};
for(let [position, content] of contents) {
this.contents[position] = content;
}
} else {
this.contents = contents;
}
this.name = name;
this.rows = rows;
this.columns = columns;
// TODO calculate rows and columns if not given.
}
get(row, column) {
return this.contents[encodePosition(row, column)];
}
pluck(row, column, header = 'default') {
let contents = this.contents[encodePosition(row, column)];
if(contents) {
return contents[header]
}
}
positions(zeroBased = false) {
return Object.keys(this.contents)
.sort(comparePositions);
}
entries() {
return [for (position of this.positions()) [position, this.contents[position]]];
}
get size() {
if(this.rows != null && this.columns != null) {
return this.rows * this.columns;
}
}
toSheet(headers = null) {
return PlateLayout.toSheet([this], headers)
}
/**
*
* @param layouts
* @param keys
*/
static toSheet(layouts, headers = null, format = 'list') {
}
async validate(validators, parallel = false) {
let contents = {};
let errors = {};
if(parallel) {
let ready = Promise.resolve(null);
for(let [position, content] of this.entries()) {
ready = ready.then(() =>
validateRecord(content, validators).then(
(value) => { contents[position] = value },
(error) => { errors[position] = error })
);
console.log(position, content)
}
await ready;
} else {
for(let [position, content] of this.entries()) {
try {
contents[position] = await validateRecord(content, validators);
} catch (e) {
errors[position] = e;
}
}
}
if(Object.keys(errors).length == 0) {
return new PlateLayout(contents, this);
} else {
throw errors;
}
}
/**
* Returns a list of layouts.
*
* @param sheet
* @param required
* @param converters
*/
static parse(sheet, {required = [], aliases = {}, converters = {}} = {}) {
// Determine if layout is grid or list-style:
// - list-style layout starts with a header row.
// - grid-style layout starts with an empty line or plate name, followed by A,B,C..
if (!sheet.get(0, 0) || sheet.get(1, 0) == 'A') {
let layouts = [];
for (let r = 0; r <= sheet.rows; r++) {
// TODO also check that platename is not null?
if (sheet.get(r + 1, 0) != 'A' || Number(sheet.get(r, 1)) != 1) {
continue;
}
let name = sheet.get(r, 0);
let [rows, columns] = dimensions(sheet, r);
let contents = {};
for (let row = 1; row <= rows; row++) {
for (let column = 1; column <= columns; column++) {
contents[PlateLayout.encodePosition(row, column)] = {'default': sheet.get(r + row, column)};
}
}
layouts.push(new PlateLayout(contents, {name, rows, columns}));
r += rows;
}
return layouts;
} else {
let contents = {};
let table = Table.parse(sheet, {
required: required.concat(['plate', 'position']),
converters: Object.assign(converters, {plate: 'string', position: 'string(position)'}),
aliases: Object.assign({
'plate name': 'plate',
'plate id': 'plate',
'plate barcode': 'plate',
'well': 'position'
}, aliases)
});
for (let row of table) {
if (!(row.plate in contents)) {
contents[row.plate] = {};
}
contents[row.plate][row.position] = row;
delete row.plate;
delete row.position;
}
return [for(name of Object.keys(contents)) new PlateLayout(contents[name], {name})];
}
}
static encodePosition(rowNumber, columnNumber, zeroBased = false) {
return `${String.fromCharCode(64 + rowNumber + zeroBased)}${pad(columnNumber + zeroBased)}`;
}
static decodePosition(position, zeroBased = false) {
return [position.charCodeAt(0) - 64 - zeroBased, parseInt(position.substr(1)) - zeroBased];
}
}
|
JavaScript
| 0.000001 |
@@ -3635,16 +3635,49 @@
sheet, %7B
+default: defaultKey = 'default',
required
@@ -4605,25 +4605,28 @@
mn)%5D = %7B
-'
+%5B
default
-'
+Key%5D
: sheet.
|
627b0720c0f769af3aad386f3fe6cfe86734f4be
|
Use Promise.resolve instead of removed Promise.accept
|
lib/interfaces/IDirectMessageChannelCollection.js
|
lib/interfaces/IDirectMessageChannelCollection.js
|
"use strict";
const ICollectionBase = require("./ICollectionBase");
const IDirectMessageChannel = require("./IDirectMessageChannel");
const Utils = require("../core/Utils");
const Constants = require("../Constants");
const ChannelTypes = Constants.ChannelTypes;
const rest = require("../networking/rest");
/**
* @interface
* @extends ICollectionBase
*/
class IDirectMessageChannelCollection extends ICollectionBase {
constructor(discordie, valuesGetter) {
super({
valuesGetter: valuesGetter,
itemFactory: (id) => new IDirectMessageChannel(this._discordie, id)
});
this._discordie = discordie;
Utils.privatify(this);
}
/**
* Gets a DM channel from cache or makes a request to create one.
* @param {IUser|IGuildMember|String} recipient
* @returns {Promise<IDirectMessageChannel, Error>}
*/
getOrOpen(recipient) {
const existing = this.find(c => c.recipient.equals(recipient));
if (existing)
return Promise.accept(existing);
return this.open(recipient);
}
/**
* Makes a request to create a DM channel.
* @param {IUser|IGuildMember|String} recipient
* @returns {Promise<IDirectMessageChannel, Error>}
*/
open(recipient) {
const userId = this._discordie.User.id;
recipient = recipient.valueOf();
return new Promise((rs, rj) => {
rest(this._discordie)
.users.createDirectMessageChannel(userId, recipient)
.then(channel => rs(this._discordie.DirectMessageChannels.get(channel.id)))
.catch(rj);
});
}
}
module.exports = IDirectMessageChannelCollection;
|
JavaScript
| 0.000003 |
@@ -970,14 +970,15 @@
ise.
-accept
+resolve
(exi
|
05278cac8427f3227fe3d19e7dcc3b3dfa0cafad
|
Refactor to avoid dynamic module resolution
|
lib/node_modules/@stdlib/array/int32/lib/index.js
|
lib/node_modules/@stdlib/array/int32/lib/index.js
|
'use strict';
/**
* Typed array constructor which returns a typed array representing an array of twos-complement 32-bit signed integers in the platform byte order.
*
* @module @stdlib/array/int32
*
* @example
* var ctor = require( '@stdlib/array/int32' );
*
* var arr = new ctor( 10 );
* // returns <Int32Array>
*/
// MODULES //
var hasInt32ArraySupport = require( '@stdlib/utils/detect-int32array-support' );
// MAIN //
var ctor;
if ( hasInt32ArraySupport() ) {
ctor = require( './int32array.js' );
} else {
ctor = require( './polyfill.js' );
}
// EXPORTS //
module.exports = ctor;
|
JavaScript
| 0 |
@@ -406,16 +406,103 @@
ort' );%0A
+var builtin = require( './int32array.js' );%0Avar polyfill = require( './polyfill.js' );%0A
%0A%0A// MAI
@@ -561,36 +561,15 @@
r =
-require( './int32array.js' )
+builtin
;%0A%7D
@@ -583,36 +583,24 @@
%09ctor =
-require( './
polyfill
.js' );%0A
@@ -591,22 +591,16 @@
polyfill
-.js' )
;%0A%7D%0A%0A%0A//
|
57dd9ee79e0eec7e4ab5b3cb8239bedfa2d8a2ff
|
Update namespace
|
lib/node_modules/@stdlib/string/base/lib/index.js
|
lib/node_modules/@stdlib/string/base/lib/index.js
|
/**
* @license Apache-2.0
*
* Copyright (c) 2022 The Stdlib Authors.
*
* 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.
*/
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};
/**
* @name camelcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/camelcase}
*/
setReadOnly( ns, 'camelcase', require( '@stdlib/string/base/camelcase' ) );
/**
* @name capitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/capitalize}
*/
setReadOnly( ns, 'capitalize', require( '@stdlib/string/base/capitalize' ) );
/**
* @name constantcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/constantcase}
*/
setReadOnly( ns, 'constantcase', require( '@stdlib/string/base/constantcase' ) );
/**
* @name endsWith
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/ends-with}
*/
setReadOnly( ns, 'endsWith', require( '@stdlib/string/base/ends-with' ) );
/**
* @name formatInterpolate
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-interpolate}
*/
setReadOnly( ns, 'formatInterpolate', require( '@stdlib/string/base/format-interpolate' ) );
/**
* @name formatTokenize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/format-tokenize}
*/
setReadOnly( ns, 'formatTokenize', require( '@stdlib/string/base/format-tokenize' ) );
/**
* @name kebabcase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/kebabcase}
*/
setReadOnly( ns, 'kebabcase', require( '@stdlib/string/base/kebabcase' ) );
/**
* @name ltrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/left-trim}
*/
setReadOnly( ns, 'ltrim', require( '@stdlib/string/base/left-trim' ) );
/**
* @name lowercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/lowercase}
*/
setReadOnly( ns, 'lowercase', require( '@stdlib/string/base/lowercase' ) );
/**
* @name percentEncode
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/percent-encode}
*/
setReadOnly( ns, 'percentEncode', require( '@stdlib/string/base/percent-encode' ) );
/**
* @name replace
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/replace}
*/
setReadOnly( ns, 'replace', require( '@stdlib/string/base/replace' ) );
/**
* @name rtrim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/right-trim}
*/
setReadOnly( ns, 'rtrim', require( '@stdlib/string/base/right-trim' ) );
/**
* @name trim
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/trim}
*/
setReadOnly( ns, 'trim', require( '@stdlib/string/base/trim' ) );
/**
* @name uncapitalize
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uncapitalize}
*/
setReadOnly( ns, 'uncapitalize', require( '@stdlib/string/base/uncapitalize' ) );
/**
* @name uppercase
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/string/base/uppercase}
*/
setReadOnly( ns, 'uppercase', require( '@stdlib/string/base/uppercase' ) );
// EXPORTS //
module.exports = ns;
|
JavaScript
| 0.000001 |
@@ -2765,32 +2765,236 @@
owercase' ) );%0A%0A
+/**%0A* @name pascalcase%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/string/base/pascalcase%7D%0A*/%0AsetReadOnly( ns, 'pascalcase', require( '@stdlib/string/base/pascalcase' ) );%0A%0A
/**%0A* @name perc
|
d43dc58ec7394bf94248bc26b1d9d4c81ea71756
|
Update namespace
|
lib/node_modules/@stdlib/types/array/lib/index.js
|
lib/node_modules/@stdlib/types/array/lib/index.js
|
'use strict';
/*
* When adding modules to the namespace, ensure that they are added in alphabetical order according to module name.
*/
// MODULES //
var setReadOnly = require( '@stdlib/utils/define-read-only-property' );
// MAIN //
/**
* Top-level namespace.
*
* @namespace ns
*/
var ns = {};
/**
* @name ArrayBuffer
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/buffer}
*/
setReadOnly( ns, 'ArrayBuffer', require( '@stdlib/types/array/buffer' ) );
/**
* @name Float32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/float32}
*/
setReadOnly( ns, 'Float32Array', require( '@stdlib/types/array/float32' ) );
/**
* @name Float64Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/float64}
*/
setReadOnly( ns, 'Float64Array', require( '@stdlib/types/array/float64' ) );
/**
* @name Int16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/int16}
*/
setReadOnly( ns, 'Int16Array', require( '@stdlib/types/array/int16' ) );
/**
* @name Int32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/int32}
*/
setReadOnly( ns, 'Int32Array', require( '@stdlib/types/array/int32' ) );
/**
* @name Int8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/int8}
*/
setReadOnly( ns, 'Int8Array', require( '@stdlib/types/array/int8' ) );
/**
* @name reviveTypedArray
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/array/reviver}
*/
setReadOnly( ns, 'reviveTypedArray', require( '@stdlib/types/array/reviver' ) );
/**
* @name typedarray2json
* @memberof ns
* @readonly
* @type {Function}
* @see {@link module:@stdlib/types/array/to-json}
*/
setReadOnly( ns, 'typedarray2json', require( '@stdlib/types/array/to-json' ) );
/**
* @name typedarray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/typed}
*/
setReadOnly( ns, 'typedarray', require( '@stdlib/types/array/typed' ) );
/**
* @name Uint16Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/uint16}
*/
setReadOnly( ns, 'Uint16Array', require( '@stdlib/types/array/uint16' ) );
/**
* @name Uint32Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/uint32}
*/
setReadOnly( ns, 'Uint32Array', require( '@stdlib/types/array/uint32' ) );
/**
* @name Uint8Array
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/uint8}
*/
setReadOnly( ns, 'Uint8Array', require( '@stdlib/types/array/uint8' ) );
/**
* @name Uint8ClampedArray
* @memberof ns
* @readonly
* @constructor
* @see {@link module:@stdlib/types/array/uint8c}
*/
setReadOnly( ns, 'Uint8ClampedArray', require( '@stdlib/types/array/uint8c' ) );
// EXPORTS //
module.exports = ns;
|
JavaScript
| 0.000001 |
@@ -1651,32 +1651,252 @@
/reviver' ) );%0A%0A
+/**%0A* @name SharedArrayBuffer%0A* @memberof ns%0A* @readonly%0A* @constructor%0A* @see %7B@link module:@stdlib/types/array/shared-buffer%7D%0A*/%0AsetReadOnly( ns, 'SharedArrayBuffer', require( '@stdlib/types/array/shared-buffer' ) );%0A%0A
/**%0A* @name type
|
14d002c4af33b215fe478b97c55965e3afaed05e
|
Update module.js
|
src/module.js
|
src/module.js
|
/*
MagJS v0.23
http://github.com/magnumjs/mag.js
(c) Michael Glazer
License: MIT
*/
(function(mag) {
'use strict';
var modules = [],
controllers = []
var mod = {
cache: []
}
mod.getState = function(index) {
return modules[index][1]
}
mod.setState = function(index, state) {
modules[index][1] = state
}
mod.getView = function(index) {
return modules[index][0]
}
mod.getProps = function(index) {
return modules[index][2]
}
mod.setProps = function(index, props) {
return modules[index][2] = props
}
mod.remove = function(index) {
modules.splice(index, 1)
}
mod.getId = function(index) {
return modules[index] && modules[index][3]
}
mod.exists = function(index) {
return typeof modules[index] != 'undefined' ? true : false
}
mod.setFrameId = function(index, fid) {
modules[index][4] = fid;
}
mod.getFrameId = function(index) {
return modules[index][4];
}
mod.submodule = function(id, index, module, props) {
if (modules[index]) {
// new call to existing
// update props
mod.setProps(index, props)
// reinitialize the controller ?
return modules[index]
}
modules[index] = [0, 0, 0, 0, 0]
mod.setProps(index, props)
var controller = function(context) {
return (module.controller || function() {}).call(context, mod.getProps(index)) || context
},
view = function(index, state, ele) {
module.view.call(module, state, mod.getProps(index), ele)
}.bind({}, index),
output = {
controller: controller,
view: view
}
modules[index][0] = output.view;
modules[index][3] = id;
modules[index][1] = getController(output.controller, index, id);
// register the module
return modules[index]
}
var timers = [];
var prevs = [];
function findMissing(change, element) {
var prop = change.name;
if (typeof change.object[change.name] == 'undefined') {
// prop might be hierarchical?
// getparent Object property chain?
// get value of property from DOM
var a = mag.fill.find(element, prop),
greedy = prop[0] === '$',
v, // can be an array, object or string
// for each
tmp = [];
a.reverse().forEach(function(item, index) {
if (item) {
if (item.value && item.value.length > 0) {
v = item.value
if (item.type && (item.type == 'checkbox' || item.type == 'radio')) {
v = {
_value: v
};
if (item.checked) v._checked = true
tmp.push(v)
}
} else if (item.innerText && item.innerText.length > 0) {
v = item.innerText
} else if (item.innerHTML && item.innerHTML.length > 0) {
v = item.innerHTML
} else if (!item.value && item.tagName == 'INPUT') {
v = ''
}
}
})
if (tmp.length > 0 && greedy) return tmp
return v
}
}
function getController(ctrl, index, id) {
var controller;
if (typeof Proxy !== 'undefined') {
var handler = function(type, index, change) {
var current = JSON.stringify(change.object);
var sname = String(change.name);
if (current === prevs[index + sname]) {
return;
}
prevs[index + sname] = current;
if (change.type == 'get' && type != 'props' && !~mag.fill.ignorekeys.indexOf(change.name.toString()) && typeof change.oldValue == 'undefined' && Object.keys(change.object).length === 0) {
var res = findMissing(change, mag.doc.getElementById(mod.getId(index)));
if (typeof res != 'undefined') {
cached[index] = 0;
return res;
}
} else
if (change.type == 'set' && change.oldValue && typeof change.oldValue.draw == 'function' && change.object[change.name] && !change.object[change.name].draw) {
// call unloader for module
var id = change.oldValue.getId()
mag.utils.callLCEvent('onunload', mag.mod.getState(id), mag.getNode(mag.mod.getId(id)), id);
mag.clear(id);
// remove clones
change.oldValue.clones().length = 0;
}
// call setup handler
var fun = mod.getFrameId(index);
if (typeof fun == 'function' && change.type == 'set') {
//debounce
cancelAnimationFrame(timers[index]);
timers[index] = requestAnimationFrame(fun);
}
};
var base = mod.getProps(index);
var baseP = mag.proxy(base, handler.bind({}, 'props', index));
mod.setProps(index, baseP);
var p = mag.proxy({}, handler.bind({}, 'state', index));
controller = new ctrl(p);
} else {
controller = new ctrl({})
}
return controller;
}
mod.iscached = function(key, data) {
if (mod.cache[key] && mod.cache[key] === JSON.stringify(data)) {
return true
}
mod.cache[key] = JSON.stringify(data);
}
mod.clear = function(key) {
if (key > -1 && mod.cache[key]) {
mod.cache.splice(key, 1)
}
}
var cached = []
mod.callView = function(node, index) {
var module = mod.getView(index)
if (!cached[index]) {
mag.props.attachToArgs(index, mod.getState(index), node)
cached[index] = 1
}
module(mod.getState(index), node)
}
mag.mod = mod;
}(window.mag || {}));
|
JavaScript
| 0 |
@@ -4891,17 +4891,97 @@
(key
-, data) %7B
+) %7B%0A var data = mag.utils.merge(mag.utils.copy(mod.getProps(key)), mod.getState(key));
%0A
|
4fc7ce26ef17881618420e0852a9bdfcaa53a4ce
|
Enable X-Forwarded-* headers in http-proxy
|
lib/tasks/server/middleware/proxy-server/index.js
|
lib/tasks/server/middleware/proxy-server/index.js
|
'use strict';
function ProxyServerAddon(project) {
this.project = project;
this.name = 'proxy-server-middleware';
}
ProxyServerAddon.prototype.serverMiddleware = function(options) {
var app = options.app, server = options.options.httpServer;
options = options.options;
if (options.proxy) {
var proxy = require('http-proxy').createProxyServer({
target: options.proxy,
ws: true,
secure: !options.insecureProxy,
changeOrigin: true
});
proxy.on('error', function (e) {
options.ui.writeLine('Error proxying to ' + options.proxy);
options.ui.writeError(e);
});
var morgan = require('morgan');
options.ui.writeLine('Proxying to ' + options.proxy);
server.on('upgrade', function (req, socket, head) {
options.ui.writeLine('Proxying websocket to ' + req.url);
proxy.ws(req, socket, head);
});
app.use(morgan('dev'));
app.use(function(req, res) {
return proxy.web(req, res);
});
}
};
module.exports = ProxyServerAddon;
|
JavaScript
| 0.00001 |
@@ -456,16 +456,34 @@
eOrigin:
+ true,%0A xfwd:
true%0A
|
66fa8d3fdffd2b91f92506d51d4e664daae274ff
|
fix bugs
|
lib/windows8/plugin/windows8/FileTransferProxy.js
|
lib/windows8/plugin/windows8/FileTransferProxy.js
|
var FileTransferError = require('cordova/plugin/FileTransferError'),
FileUploadResult = require('cordova/plugin/FileUploadResult'),
FileEntry = require('cordova/plugins/FireEntry');
module.exports = {
upload:function(successCallback, error, options) {
var filePath = options[0];
var server = options[1];
var win = function (fileUploadResult) {
successCallback(fileUploadResult);
};
if (filePath === null || typeof filePath === 'undefined') {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
if (String(filePath).substr(0, 8) == "file:///") {
filePath = Windows.Storage.ApplicationData.current.localFolder.path + String(filePath).substr(8).split("/").join("\\");
}
Windows.Storage.StorageFile.getFileFromPathAsync(filePath).then(function (storageFile) {
storageFile.openAsync(Windows.Storage.FileAccessMode.read).then(function (stream) {
var blob = MSApp.createBlobFromRandomAccessStream(storageFile.contentType, stream);
var formData = new FormData();
formData.append("source\";filename=\"" + storageFile.name + "\"", blob);
WinJS.xhr({ type: "POST", url: server, data: formData }).then(function (response) {
var code = response.status;
storageFile.getBasicPropertiesAsync().done(function (basicProperties) {
Windows.Storage.FileIO.readBufferAsync(storageFile).done(function (buffer) {
var dataReader = Windows.Storage.Streams.DataReader.fromBuffer(buffer);
var fileContent = dataReader.readString(buffer.length);
dataReader.close();
win(new FileUploadResult(basicProperties.size, code, fileContent));
});
});
}, function () {
error(FileTransferError.INVALID_URL_ERR);
});
});
},function(){error(FileTransferError.FILE_NOT_FOUND_ERR);});
},
download:function(win, error, options) {
var source = options[0];
var target = options[1];
if (target === null || typeof target === undefined) {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
if (String(target).substr(0, 8) == "file:///") {
target = Windows.Storage.ApplicationData.current.localFolder.path + String(target).substr(8).split("/").join("\\");
}
var path = target.substr(0, String(target).lastIndexOf("\\"));
var fileName = target.substr(String(target).lastIndexOf("\\") + 1);
if (path === null || fileName === null) {
error(FileTransferError.FILE_NOT_FOUND_ERR);
return;
}
var download = null;
Windows.Storage.StorageFolder.getFolderFromPathAsync(path).then(function (storageFolder) {
storageFolder.createFileAsync(fileName, Windows.Storage.CreationCollisionOption.generateUniqueName).then(function (storageFile) {
var uri = Windows.Foundation.Uri(source);
var downloader = new Windows.Networking.BackgroundTransfer.BackgroundDownloader();
download = downloader.createDownload(uri, storageFile);
download.startAsync().then(function () {
win(new FileEntry(storageFile.name, storageFile.path));
}, function () {
error(FileTransferError.INVALID_URL_ERR);
});
});
});
}
};
|
JavaScript
| 0.000001 |
@@ -172,13 +172,12 @@
ugin
-s
/Fi
-r
+l
eEnt
|
ee84076decfb3b787c6d08cef9fcd3db4d659076
|
update button test
|
components/button/__tests__/index.test.js
|
components/button/__tests__/index.test.js
|
import React from 'react';
import renderer from 'react-test-renderer';
import { shallow } from 'enzyme';
import Button from '../index';
describe('Button', () => {
it('renders correctly', () => {
const tree = renderer.create(<Button>foo</Button>).toJSON();
expect(tree).toMatchSnapshot();
});
describe('pressIn', () => {
let handlePressIn;
let wrapper;
beforeEach(() => {
handlePressIn = jest.fn();
wrapper = shallow(<Button onPressIn={handlePressIn}>foo</Button>);
wrapper.find('TouchableHighlight').simulate('pressIn');
});
it('fires pressIn event', () => {
expect(handlePressIn).toBeCalledWith();
});
it('change pressIn state', () => {
expect(wrapper.state('pressIn')).toBe(true);
});
});
describe('pressOut', () => {
let handlePressOut;
let wrapper;
beforeEach(() => {
handlePressOut = jest.fn();
wrapper = shallow(<Button onPressOut={handlePressOut}>foo</Button>);
wrapper.setState({ pressIn: true });
wrapper.find('TouchableHighlight').simulate('pressOut');
});
it('fires pressOut event', () => {
expect(handlePressOut).toBeCalledWith();
});
it('set pressIn state', () => {
expect(wrapper.state('pressIn')).toBe(false);
});
});
describe('showUnderlay', () => {
let handleShowUnderlay;
let wrapper;
beforeEach(() => {
handleShowUnderlay = jest.fn();
wrapper = shallow(<Button onShowUnderlay={handleShowUnderlay}>foo</Button>);
wrapper.find('TouchableHighlight').simulate('showUnderlay');
});
it('fires showUnderlay event', () => {
expect(handleShowUnderlay).toBeCalledWith();
});
it('set touchIt state', () => {
expect(wrapper.state('touchIt')).toBe(true);
});
});
describe('hideUnderlay', () => {
let handleHideUnderlay;
let wrapper;
beforeEach(() => {
handleHideUnderlay = jest.fn();
wrapper = shallow(<Button onHideUnderlay={handleHideUnderlay}>foo</Button>);
wrapper.setState({ touchIt: true });
wrapper.find('TouchableHighlight').simulate('hideUnderlay');
});
it('fires hideUnderlay event', () => {
expect(handleHideUnderlay).toBeCalledWith();
});
it('change touchIt state', () => {
expect(wrapper.state('touchIt')).toBe(false);
});
});
describe('disabled', () => {
let wrapper;
beforeEach(() => {
wrapper = shallow(<Button disabled>foo</Button>);
});
it('pressIn not change pressIn state', () => {
wrapper.find('TouchableHighlight').simulate('pressIn');
expect(wrapper.state('pressIn')).toBe(false);
});
it('pressOut not change pressIn state', () => {
wrapper.setState({ pressIn: true });
wrapper.find('TouchableHighlight').simulate('pressOut');
expect(wrapper.state('pressIn')).toBe(true);
});
it('showUnderlay not change touchIt state', () => {
wrapper.find('TouchableHighlight').simulate('showUnderlay');
expect(wrapper.state('touchIt')).toBe(false);
});
it('hideUnderlay not change touchIt state', () => {
wrapper.setState({ touchIt: true });
wrapper.find('TouchableHighlight').simulate('hideUnderlay');
expect(wrapper.state('touchIt')).toBe(true);
});
});
});
|
JavaScript
| 0.000001 |
@@ -2338,32 +2338,84 @@
%7D);%0A %7D);%0A%0A
+ // https://github.com/airbnb/enzyme/issues/386%0A //
describe('disab
@@ -2427,24 +2427,27 @@
() =%3E %7B%0A
+ //
let wrapper
@@ -2444,32 +2444,35 @@
et wrapper;%0A%0A
+ //
beforeEach(() =
@@ -2472,32 +2472,35 @@
ch(() =%3E %7B%0A
+ //
wrapper = shall
@@ -2518,16 +2518,38 @@
disabled
+ onPressIn=%7BonPressIn%7D
%3Efoo%3C/Bu
@@ -2555,24 +2555,27 @@
utton%3E);%0A
+ //
%7D);%0A%0A it
@@ -2568,26 +2568,34 @@
// %7D);%0A%0A
-it
+// it.only
('pressIn no
@@ -2624,32 +2624,35 @@
', () =%3E %7B%0A
+ //
wrapper.find('T
@@ -2689,32 +2689,35 @@
pressIn');%0A
+ //
expect(wrapper.
@@ -2742,32 +2742,35 @@
toBe(false);%0A
+ //
%7D);%0A%0A it('pr
@@ -2758,24 +2758,27 @@
// %7D);%0A%0A
+ //
it('pressOu
@@ -2809,32 +2809,35 @@
te', () =%3E %7B%0A
+ //
wrapper.setSt
@@ -2855,32 +2855,35 @@
In: true %7D);%0A
+ //
wrapper.find(
@@ -2925,24 +2925,27 @@
ssOut');%0A
+ //
expect(wr
@@ -2979,33 +2979,45 @@
e(true);%0A
+ //
%7D);%0A
+ //
%0A
+ //
it('showUnd
@@ -3052,32 +3052,35 @@
te', () =%3E %7B%0A
+ //
wrapper.find(
@@ -3122,32 +3122,35 @@
wUnderlay');%0A
+ //
expect(wrappe
@@ -3181,33 +3181,45 @@
(false);%0A
+ //
%7D);%0A
+ //
%0A
+ //
it('hideUnd
@@ -3258,24 +3258,27 @@
() =%3E %7B%0A
+ //
wrapper.s
@@ -3301,34 +3301,37 @@
t: true %7D);%0A
+//
+
wrapper.find('To
@@ -3374,24 +3374,27 @@
erlay');%0A
+ //
expect(wr
@@ -3428,27 +3428,33 @@
e(true);%0A
+ //
%7D);%0A
+ //
%7D);%0A%7D);%0A
|
63923a97cc19f5e862465f0f4ed6f7a78ecc5ca4
|
Add placeholder text for default telegraf database
|
ui/src/sources/containers/SourceForm.js
|
ui/src/sources/containers/SourceForm.js
|
import React, {PropTypes} from 'react';
import {withRouter} from 'react-router';
import {getSource, createSource, updateSource} from 'shared/apis';
import classNames from 'classnames';
export const SourceForm = React.createClass({
propTypes: {
params: PropTypes.shape({
id: PropTypes.string,
}),
router: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
location: PropTypes.shape({
query: PropTypes.shape({
redirectPath: PropTypes.string,
}).isRequired,
}).isRequired,
addFlashMessage: PropTypes.func.isRequired,
},
getInitialState() {
return {
source: {},
editMode: this.props.params.id !== undefined,
};
},
componentDidMount() {
if (!this.state.editMode) {
return;
}
getSource(this.props.params.id).then(({data: source}) => {
this.setState({source});
});
},
handleSubmit(e) {
e.preventDefault();
const {router, params, addFlashMessage} = this.props;
const newSource = Object.assign({}, this.state.source, {
url: this.sourceURL.value.trim(),
name: this.sourceName.value,
username: this.sourceUsername.value,
password: this.sourcePassword.value,
'default': this.sourceDefault.checked,
telegraf: this.sourceTelegraf.value,
});
if (this.state.editMode) {
updateSource(newSource).then(() => {
router.push(`/sources/${params.sourceID}/manage-sources`);
addFlashMessage({type: 'success', text: 'The source was successfully updated'});
}).catch(() => {
addFlashMessage({type: 'error', text: 'There was a problem updating the source. Check the settings'});
});
} else {
createSource(newSource).then(() => {
router.push(`/sources/${params.sourceID}/manage-sources`);
addFlashMessage({type: 'success', text: 'The source was successfully created'});
}).catch(() => {
addFlashMessage({type: 'error', text: 'There was a problem creating the source. Check the settings'});
});
}
},
onInputChange(e) {
const val = e.target.value;
const name = e.target.name;
this.setState((prevState) => {
const newSource = Object.assign({}, prevState.source, {
[name]: val,
});
return Object.assign({}, prevState, {source: newSource});
});
},
render() {
const {source, editMode} = this.state;
if (editMode && !source.id) {
return <div className="page-spinner"></div>;
}
return (
<div id="source-form-page">
<div className="chronograf-header">
<div className="chronograf-header__container">
<div className="chronograf-header__left">
<h1>
{editMode ? "Edit Source" : "Add a New Source"}
</h1>
</div>
</div>
</div>
<div className="container-fluid">
<div className="row">
<div className="col-md-8 col-md-offset-2">
<div className="panel panel-summer">
<div className="panel-body">
<h4 className="text-center">Connection Details</h4>
<br/>
<form onSubmit={this.handleSubmit}>
<div>
<div className="form-group col-xs-6 col-sm-4 col-sm-offset-2">
<label htmlFor="connect-string">Connection String</label>
<input type="text" name="url" ref={(r) => this.sourceURL = r} className="form-control" id="connect-string" placeholder="http://localhost:8086" onChange={this.onInputChange} value={source.url || ''}></input>
</div>
<div className="form-group col-xs-6 col-sm-4">
<label htmlFor="name">Name</label>
<input type="text" name="name" ref={(r) => this.sourceName = r} className="form-control" id="name" placeholder="Influx 1" onChange={this.onInputChange} value={source.name || ''}></input>
</div>
<div className="form-group col-xs-6 col-sm-4 col-sm-offset-2">
<label htmlFor="username">Username</label>
<input type="text" name="username" ref={(r) => this.sourceUsername = r} className="form-control" id="username" onChange={this.onInputChange} value={source.username || ''}></input>
</div>
<div className="form-group col-xs-6 col-sm-4">
<label htmlFor="password">Password</label>
<input type="password" name="password" ref={(r) => this.sourcePassword = r} className="form-control" id="password" onChange={this.onInputChange} value={source.password || ''}></input>
</div>
<div className="form-group col-xs-8 col-xs-offset-2">
<label htmlFor="telegraf">Telegraf database</label>
<input type="text" name="telegraf" ref={(r) => this.sourceTelegraf = r} className="form-control" id="telegraf" onChange={this.onInputChange} value={source.telegraf || ''}></input>
</div>
<div className="form-group col-xs-8 col-xs-offset-2">
<div className="form-control-static">
<input type="checkbox" id="defaultSourceCheckbox" defaultChecked={source.default} ref={(r) => this.sourceDefault = r} />
<label htmlFor="defaultSourceCheckbox">Make this the default source</label>
</div>
</div>
</div>
<div className="form-group col-xs-4 col-xs-offset-4">
<button className={classNames('btn btn-block', {'btn-primary': editMode, 'btn-success': !editMode})} type="submit">{editMode ? "Save Changes" : "Add Source"}</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
</div>
);
},
});
export default withRouter(SourceForm);
|
JavaScript
| 0 |
@@ -5090,16 +5090,39 @@
elegraf%22
+ placeholder=%22telegraf%22
onChang
|
7c0e4aecee44a07d3eb26c09057f854fdaf3aa9b
|
Fix for jQuery 1.6 compat.
|
var/httpd/htdocs/js/Core.Agent.Stats.js
|
var/httpd/htdocs/js/Core.Agent.Stats.js
|
// --
// Core.Agent.Stats.js - provides the special module functions for AgentStats
// Copyright (C) 2001-2011 OTRS AG, http://otrs.org/
// --
// $Id: Core.Agent.Stats.js,v 1.3 2011-10-31 10:58:10 mg Exp $
// --
// This software comes with ABSOLUTELY NO WARRANTY. For details, see
// the enclosed file COPYING for license information (AGPL). If you
// did not receive this file, see http://www.gnu.org/licenses/agpl.txt.
// --
"use strict";
var Core = Core || {};
Core.Agent = Core.Agent || {};
/**
* @namespace
* @exports TargetNS as Core.Agent.Stats
* @description
* This namespace contains the special module functions for the Dashboard.
*/
Core.Agent.Stats = (function (TargetNS) {
/**
* @function
* @return nothing
* @description
* Activates the graph size menu if a GD element is selected.
*/
TargetNS.FormatGraphSizeRelation = function () {
var $Format = $('#Format'),
Flag = false,
Reg = /^GD::/;
// find out if a GD element is used
$.each($Format.children('option'), function () {
if ($(this).attr('selected') === 'selected') {
if (Reg.test($(this).val()) === true) {
Flag = true;
}
}
});
// activate or deactivate the Graphsize menu
$('#GraphSize').attr('disabled', Flag ? false : true);
};
/**
* @function
* @return nothing
* Selects a checbox by name
* @param {Object} The name of the radio button to be selected
*/
TargetNS.SelectCheckbox = function (Name) {
$('input:checkbox[name=' + Name + ']').attr('checked', true);
};
/**
* @function
* @return nothing
* Selects a radio button by name and value
* @param {Value} The value attribute of the radio button to be selected
* @param {Object} The name of the radio button to be selected
*/
TargetNS.SelectRadiobutton = function (Value, Name) {
$('input:radio[name=' + Name + '][value=' + Value + ']').attr('checked', true);
};
return TargetNS;
}(Core.Agent.Stats || {}));
|
JavaScript
| 0 |
@@ -168,17 +168,17 @@
.js,v 1.
-3
+4
2011-10
@@ -186,15 +186,15 @@
31 1
-0:58:10
+1:02:27
mg
@@ -1665,36 +1665,41 @@
attr('checked',
-true
+'checked'
);%0A %7D;%0A%0A /
@@ -2086,20 +2086,25 @@
ecked',
-true
+'checked'
);%0A %7D
|
d5bb0f054bbfa8f27f8dbb8b3910c3cd90f3bb11
|
Add "clearOnEnter" as a code folding option
|
addon/fold/foldcode.js
|
addon/fold/foldcode.js
|
(function() {
"use strict";
function doFold(cm, pos, options, force) {
var finder = options && (options.call ? options : options.rangeFinder);
if (!finder) finder = CodeMirror.fold.auto;
if (typeof pos == "number") pos = CodeMirror.Pos(pos, 0);
var minSize = options && options.minFoldSize || 0;
function getRange(allowFolded) {
var range = finder(cm, pos);
if (!range || range.to.line - range.from.line < minSize) return null;
var marks = cm.findMarksAt(range.from);
for (var i = 0; i < marks.length; ++i) {
if (marks[i].__isFold && force !== "fold") {
if (!allowFolded) return null;
range.cleared = true;
marks[i].clear();
}
}
return range;
}
var range = getRange(true);
if (options && options.scanUp) while (!range && pos.line > cm.firstLine()) {
pos = CodeMirror.Pos(pos.line - 1, 0);
range = getRange(false);
}
if (!range || range.cleared || force === "unfold") return;
var myWidget = makeWidget(options, cm, range);
CodeMirror.on(myWidget, "mousedown", function() { myRange.clear(); });
var myRange = cm.markText(range.from, range.to, {
replacedWith: myWidget,
clearOnEnter: true,
__isFold: true
});
myRange.on("clear", function(from, to) {
CodeMirror.signal(cm, "unfold", cm, from, to);
});
CodeMirror.signal(cm, "fold", cm, range.from, range.to);
}
function makeWidget(options, cm, range) {
var widget
= (options && options.widgetFunc && options.widgetFunc(cm, range))
|| (options && options.widget)
|| "\u2194";
if (typeof widget == "string") {
var text = document.createTextNode(widget);
widget = document.createElement("span");
widget.appendChild(text);
widget.className = "CodeMirror-foldmarker";
}
return widget;
}
// Clumsy backwards-compatible interface
CodeMirror.newFoldFunction = function(rangeFinder, widget) {
return function(cm, pos) { doFold(cm, pos, {rangeFinder: rangeFinder, widget: widget}); };
};
// New-style interface
CodeMirror.defineExtension("foldCode", function(pos, options, force) {
doFold(this, pos, options, force);
});
CodeMirror.commands.fold = function(cm) {
cm.foldCode(cm.getCursor());
};
CodeMirror.registerHelper("fold", "combine", function() {
var funcs = Array.prototype.slice.call(arguments, 0);
return function(cm, start) {
for (var i = 0; i < funcs.length; ++i) {
var found = funcs[i](cm, start);
if (found) return found;
}
};
});
CodeMirror.registerHelper("fold", "auto", function(cm, start) {
var helpers = cm.getHelpers(start, "fold");
for (var i = 0; i < helpers.length; i++) {
var cur = helpers[i](cm, start);
if (cur) return cur;
}
});
})();
|
JavaScript
| 0.000001 |
@@ -1240,19 +1240,53 @@
nEnter:
-tru
+options ? options.clearOnEnter : fals
e,%0A
|
8eb60b9f35fe89350ff30dcaa7eec50a0bb1442b
|
Work around a problem in later (currently unsupported) embers where Ember.computed.bool is not a function
|
addon/helpers/-base.js
|
addon/helpers/-base.js
|
import { run } from '@ember/runloop';
import Helper from '@ember/component/helper';
import { get, observer, computed } from '@ember/object';
import { inject as service } from '@ember/service';
export default Helper.extend({
moment: service(),
disableInterval: false,
globalAllowEmpty: computed.bool('moment.__config__.allowEmpty'),
supportsGlobalAllowEmpty: true,
localeOrTimeZoneChanged: observer('moment.locale', 'moment.timeZone', function() {
this.recompute();
}),
compute(value, { interval }) {
if (get(this, 'disableInterval')) { return; }
this.clearTimer();
if (interval) {
/*
* NOTE: intentionally a setTimeout so tests do not block on it
* as the run loop queue is never clear so tests will stay locked waiting
* for queue to clear.
*/
this.intervalTimer = setTimeout(() => {
run(() => this.recompute());
}, parseInt(interval, 10));
}
},
morphMoment(time, { locale, timeZone }) {
const momentService = get(this, 'moment');
locale = locale || get(momentService, 'locale');
timeZone = timeZone || get(momentService, 'timeZone');
if (locale && time.locale) {
time = time.locale(locale);
}
if (timeZone && time.tz) {
time = time.tz(timeZone);
}
return time;
},
clearTimer() {
clearTimeout(this.intervalTimer);
},
destroy() {
this.clearTimer();
this._super(...arguments);
}
});
|
JavaScript
| 0.000004 |
@@ -297,13 +297,73 @@
uted
-.bool
+('moment.__config__.allowEmpty', function() %7B%0A return this.get
('mo
@@ -390,16 +390,22 @@
wEmpty')
+;%0A %7D)
,%0A supp
|
a77fb719e7a347fe2069b7db8a9b7e835613bb48
|
bring back the default scroll & link behaviour
|
viewer/test/test-add-heading-anchors.js
|
viewer/test/test-add-heading-anchors.js
|
/* global addHeadingAnchors:false fixture*/
var assert = chai.assert;
describe("addHeadingAnchors", function () {
before(function () {
fixture.setBase("fixtures");
});
beforeEach(function () {
fixture.load("heading-fixtures.html");
this.testcontainer = fixture.el.firstChild;
addHeadingAnchors.init("#testcontainer", "#testcontainer .popovers");
});
afterEach(function () {
fixture.cleanup();
});
describe("HTML modification", function () {
beforeEach(function () {
this.headingsWithAnId = this.testcontainer.querySelectorAll(
"h1[id], h2[id], h3[id], h4[id], h5[id], h6[id]"
);
this.headingsWithoutAnId = this.testcontainer.querySelectorAll(
"h1:not([id]), h2:not([id]), h3:not([id]), h4:not([id]), h5:not([id]), h6:not([id])"
);
});
it("added the header links beside each heading", function () {
var assertHasCopyLink = function (heading) {
var anchor = heading.lastChild;
var href;
var clipboardDataAttribute;
// is element
assert.equal(anchor.nodeType, 1, "anchor should be the last child");
// is an anchor
assert.equal(anchor.nodeName, "A");
// href is to id
href = anchor.getAttribute("href");
assert.endsWith(href, "#" + heading.getAttribute("id"));
// data-clipboard-text is the full url
clipboardDataAttribute = anchor.getAttribute("data-clipboard-text");
// this is a crappy/quick way to assert for the full url being in the data attribute.
assert.startsWith(clipboardDataAttribute, "http://");
assert.endsWith(clipboardDataAttribute, "#" + heading.getAttribute("id"));
};
Array.prototype.forEach.call(this.headingsWithAnId, assertHasCopyLink);
});
it("did not add anchors inside non-id headings", function () {
var assertNoAnchorAdded = function (heading) {
// we can just assert there is no anchor, because the starting html doesn't have it.
var anchor = heading.querySelector("a");
assert.isNull(anchor);
};
Array.prototype.forEach.call(this.headingsWithoutAnId, assertNoAnchorAdded);
});
it("does not add more anchors if init is called more than once", function () {
var count = this.testcontainer.querySelectorAll("a.headerLink").length;
var newCount;
addHeadingAnchors.init("#testcontainer", "#testcontainer .popovers");
newCount = this.testcontainer.querySelectorAll("a.headerLink").length;
assert.equal(newCount, count);
});
});
describe("click handling", function () {
beforeEach(function () {
this.clipboardAnchors = this.testcontainer.querySelectorAll("a[data-clipboard-text]");
});
it("changes the address bar when clicking on links", function () {
Array.prototype.forEach.call(this.clipboardAnchors, function assertClipboardCopy(anchor) {
var href = anchor.getAttribute("href");
anchor.click();
// assert the address bar changed
assert.equal(window.location.hash, href);
});
});
it("does not scroll when clicking on links", function () {
var clickAndAssertScrollUnchanged = function (anchor) {
var oldScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
var newScrollTop;
anchor.click();
newScrollTop = document.documentElement.scrollTop || document.body.scrollTop;
assert.equal(
newScrollTop,
oldScrollTop,
"scroll top should match the stored value from before clicking"
);
};
Array.prototype.forEach.call(this.clipboardAnchors, clickAndAssertScrollUnchanged);
});
it("fires the clipboardjs error callback when clicking on links", function (done) {
// a quick alternative to spying
var callCount = 0;
var expectedCallCount = 6;
Array.prototype.forEach.call(this.clipboardAnchors, function (anchor) {
// Register a one time event handler to check the event text
// this isn't a very good test due to the limitations.
// It basically checks that yes, clipboardjs was init and
// catches clicks on all the anchors.
// We have to use the error event,
// because it will never succeed without an actual click.
// see https://w3c.github.io/editing/execCommand.html#dfn-the-copy-command
var clipboardErrorHandler = function (e) {
var url = e.text;
assert.equal(url, anchor.getAttribute("data-clipboard-text"));
e.clearSelection();
callCount += 1;
// If we somehow don't add all 6 headings,
// this test will fail because the callback is not fired
if (callCount === expectedCallCount) {
done();
}
};
addHeadingAnchors.handler.once("error", clipboardErrorHandler);
// click on all the anchors
anchor.click();
});
});
});
});
|
JavaScript
| 0 |
@@ -2755,978 +2755,8 @@
);%0A%0A
- it(%22changes the address bar when clicking on links%22, function () %7B%0A Array.prototype.forEach.call(this.clipboardAnchors, function assertClipboardCopy(anchor) %7B%0A var href = anchor.getAttribute(%22href%22);%0A anchor.click();%0A%0A // assert the address bar changed%0A assert.equal(window.location.hash, href);%0A %7D);%0A %7D);%0A%0A it(%22does not scroll when clicking on links%22, function () %7B%0A var clickAndAssertScrollUnchanged = function (anchor) %7B%0A var oldScrollTop = document.documentElement.scrollTop %7C%7C document.body.scrollTop;%0A var newScrollTop;%0A%0A anchor.click();%0A%0A newScrollTop = document.documentElement.scrollTop %7C%7C document.body.scrollTop;%0A%0A assert.equal(%0A newScrollTop,%0A oldScrollTop,%0A %22scroll top should match the stored value from before clicking%22%0A );%0A %7D;%0A%0A Array.prototype.forEach.call(this.clipboardAnchors, clickAndAssertScrollUnchanged);%0A %7D);%0A%0A
|
bce36611af40fab5b4f4a7866ac66074868ca9d3
|
Support WIP [ci skip]
|
src/script.js
|
src/script.js
|
(function ($) {
//-----------------------+
// Better val() function |
//-----------------------+
$.fn.valInternal = jQuery.fn.val;
$.fn.val = function (val) {
if (this.length) {
var type = this.attr('type');
type = type ? type : this.get(0).tagName.toLowerCase();
switch (type) {
case 'checkbox':
if (arguments.length) {
this.prop('checked', !!val);
return $.fn.valInternal.call(this, val);
}
return this.is(':checked') ? $.fn.valInternal.call(this) : '';
case 'radio':
var parent = this.parent();
var el = parent.find(':checked');
//console.log(el);
if (arguments.length) {
console.log(val);
el.prop('checked', false);
el = parent.find('[value="' + val + '"]');
el.prop('checked', true);
return val;
}
console.log(el.get(0));
console.log(el.get(0).value);
return el.get(0).value;
}
}
if (arguments.length) {
return $.fn.valInternal.call(this, val);
} else {
return $.fn.valInternal.call(this);
}
};
//-------+
// Setup |
//-------+
$.ajaxSetup({async: false});
//-----------------+
// Selects Command |
//-----------------+
$(document).on('mouseover', '#command', function () {
// select text
this.select();
});
$(document).on('mouseout', '#command', function () {
// deselect text
this.selectionStart = this.selectionEnd;
});
//------+
// Init |
//------+
var URL = document.URL.replace(/(\/index.html.*)|(\/)$/, '');
window.form = $('#form').get(0);
form.values = {};
form.options = $('#options').get(0);
form.modules = {};
form.task.onChange = [];
form.command = '';
//-----------+
// Functions |
//-----------+
// Load form options
form.options.load = function (name) {
$.get(URL + '/' + name + '/~builder/options.html', function (response) {
form.options.innerHTML += response;
});
};
// Add command argument
form.setCommand = function (cond, name, value) {
form.command += cond ? ' -' + name + (value ? ' ' + value : '') : '';
};
// Invoke module update
form.update = function (modules) {
modules.forEach(function (module) {
if (form.modules[module] && form.modules[module].onUpdate) {
form.modules[module].onUpdate();
}
});
};
//--------------------+
// Handle form update |
//--------------------+
var update = function (event) {
if (event) {
// task select
if ($(event.target).is('[name=task]')) {
change();
return;
}
}
// command update
form.command = URL;
var task = '/' + form.task.value;
form.command += task + ' -qO- | sh -s --';
// no interaction
form.setCommand(form.no_interaction.checked, 'n');
// environment
form.setCommand(form.env.value, form.env.value);
// switch support
var support = $(form.support).val();
console.log('----------');
console.log(form.support);
console.log(form.support.value);
console.log(support);
// support WBPO
if (support === "wbpo") {
form.setCommand(true, 'with-wbpo');
}
// support Webino
if (support !== "webino") {
form.setCommand(true, 'without-webino');
}
// admin email
form.setCommand(form.admin_email.value, 'admin-email', form.admin_email.value);
// update module options
if (form.modules[form.task.value] && form.modules[form.task.value].options) {
form.update(form.modules[form.task.value].options);
}
// update command
$('#command').val('wget ' + form.command);
};
//--------------------+
// Handle task select |
//--------------------+
var change = function () {
// store form values
$(form).find('input,select').each(function (n, node) {
var el = $(node);
node.name && (form.values[node.name] = el.val());
});
// load options
form.options.innerHTML = '';
if (form.modules[form.task.value] && form.modules[form.task.value].options) {
form.modules[form.task.value].options.forEach(function (module) {
form.options.load(module);
});
}
// restore form values
for (var key in form.values) {
if (form.values.hasOwnProperty(key)) {
$(form).find('[name='+ key +']').val(form.values[key]);
}
}
// update command
update();
};
//------------------+
// Bind form update |
//------------------+
$(document).on('change', 'form', update);
$(document).on('keyup', 'form', update);
//------------+
// Init tasks |
//------------+
$(form.task).find('option:not(:disabled)').each(function () {
this.value && $.get(URL + '/' + this.value + '/~builder/script.js');
});
//------------+
// Initialize |
//------------+
change();
})(jQuery);
|
JavaScript
| 0 |
@@ -845,32 +845,64 @@
ments.length) %7B%0A
+ return;%0A
|
b8d28302572a5463cfa67390dc75f5a99dbce3f9
|
Add start function for application route
|
addon/services/poll.js
|
addon/services/poll.js
|
import Ember from 'ember';
var Poll = Ember.Service.extend({
storage: Ember.inject.service('store'),
setup: function (resource_name, path, params) {
var self = this;
self.set('polls', self.get('polls') || {});
var polls = self.get('polls');
polls[resource_name] = {path: path, params: params};
if (typeof(Ember.$.idle) !== "function") {
self.setIdleListener();
}
Ember.$(document).idle({
onIdle: function(){
self.removePoll(resource_name);
},
onActive: function(){
self.setup(resource_name, path, params);
},
idle: 30000,
});
},
run: function () {
var self = this;
var polls = this.get('polls');
var store = self.get('storage');
if (Object.keys(polls).length) {
Object.keys(polls).forEach(function (resource_name) {
var path = polls[resource_name]['path'];
var params = polls[resource_name]['params'];
Ember.$.getJSON(path + params, function( data ) {
store.pushPayload(resource_name, data);
});
});
}
},
removePoll: function (resource_name) {
var polls = this.get('polls');
delete polls[resource_name];
},
setIdleListener: function () {
Ember.$.fn.idle = function (options) {
var defaults = {
idle: 60000, //idle time in ms
events: 'mousemove keypress mousedown touchstart', //events that will trigger the idle resetter
onIdle: function () {}, //callback function to be executed after idle time
onActive: function () {}, //callback function to be executed after back from idleness
onHide: function () {}, //callback function to be executed when window is hidden
onShow: function () {}, //callback function to be executed when window is visible
keepTracking: false //if you want to keep tracking user even after the first time, set this to true
},
idle = false,
visible = true,
settings = Ember.$.extend({}, defaults, options),
resetTimeout,
timeout;
resetTimeout = function (id, settings) {
if (idle) {
settings.onActive.call();
idle = false;
}
(settings.keepTracking ? clearInterval : clearTimeout)(id);
return timeout(settings);
};
timeout = function (settings) {
var timer = (settings.keepTracking ? setInterval : setTimeout),
id;
id = timer(function () {
idle = true;
settings.onIdle.call();
}, settings.idle);
return id;
};
return this.each(function () {
var id = timeout(settings);
Ember.$(this).on(settings.events, function (e) {
id = resetTimeout(id, settings);
});
if (options.onShow || options.onHide) {
Ember.$(document).on("visibilitychange webkitvisibilitychange mozvisibilitychange msvisibilitychange", function () {
if (document.hidden || document.webkitHidden || document.mozHidden || document.msHidden) {
if (visible) {
visible = false;
settings.onHide.call();
}
} else {
if (!visible) {
visible = true;
settings.onShow.call();
}
}
});
}
});
};
},
});
export default Poll;
|
JavaScript
| 0.000001 |
@@ -308,16 +308,64 @@
arams%7D;%0A
+ %7D,%0A start: function () %7B%0A var self = this;
%0A if
@@ -486,32 +486,33 @@
Idle: function()
+
%7B%0A self.r
@@ -514,31 +514,24 @@
elf.
-removePoll(resource_nam
+set('pause', tru
e);%0A
@@ -565,16 +565,17 @@
nction()
+
%7B%0A
@@ -588,38 +588,23 @@
.set
-up(resource_name, path, params
+('pause', false
);%0A
@@ -627,9 +627,9 @@
le:
-3
+1
0000
@@ -637,16 +637,115 @@
%0A %7D);
+%0A%0A setInterval(() =%3E %7B%0A if (!self.get('pause')) %7B%0A self.run();%0A %7D%0A %7D, 2000);
%0A %7D,%0A
@@ -815,24 +815,43 @@
t('polls');%0A
+ if (polls) %7B%0A
var stor
@@ -875,24 +875,26 @@
rage');%0A
+
if (Object.k
@@ -910,24 +910,26 @@
).length) %7B%0A
+
Object
@@ -980,24 +980,26 @@
) %7B%0A
+
var path = p
@@ -1031,24 +1031,26 @@
'%5D;%0A
+
+
var params =
@@ -1083,16 +1083,18 @@
ams'%5D;%0A%0A
+
@@ -1153,16 +1153,18 @@
+
store.pu
@@ -1195,16 +1195,30 @@
data);%0A
+ %7D);%0A
@@ -1224,26 +1224,24 @@
%7D);%0A %7D
-);
%0A %7D%0A %7D,%0A
@@ -3515,25 +3515,24 @@
%7D%0A %7D);%0A
-%0A
%7D;%0A %7D,%0A
|
b1daff1108a2e65884b98bbe898eee5f85d0f0c0
|
use isPushOnly internally
|
src/script.js
|
src/script.js
|
var bip66 = require('bip66')
var bufferutils = require('./bufferutils')
var typeforce = require('typeforce')
var types = require('./types')
var scriptNumber = require('./script_number')
var OPS = require('./opcodes.json')
var REVERSE_OPS = (function () {
var result = {}
for (var op in OPS) {
var code = OPS[op]
result[code] = op
}
return result
})()
var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1
function isOPInt (value) {
return types.Number(value) &&
(value === OPS.OP_0) ||
(value >= OPS.OP_1 && value <= OPS.OP_16) ||
(value === OPS.OP_1NEGATE)
}
function pushOnlyChunk (value) {
return types.oneOf(Buffer, isOPInt)
}
function compile (chunks) {
// TODO: remove me
if (Buffer.isBuffer(chunks)) return chunks
typeforce(types.Array, chunks)
var bufferSize = chunks.reduce(function (accum, chunk) {
// data chunk
if (Buffer.isBuffer(chunk)) {
// adhere to BIP62.3, minimal push policy
if (chunk.length === 1 && chunk[0] >= 1 && chunk[0] <= 16) {
return accum + 1
}
return accum + bufferutils.pushDataSize(chunk.length) + chunk.length
}
// opcode
return accum + 1
}, 0.0)
var buffer = new Buffer(bufferSize)
var offset = 0
chunks.forEach(function (chunk) {
// data chunk
if (Buffer.isBuffer(chunk)) {
// adhere to BIP62.3, minimal push policy
if (chunk.length === 1 && chunk[0] >= 1 && chunk[0] <= 16) {
var opcode = OP_INT_BASE + chunk[0]
buffer.writeUInt8(opcode, offset)
offset += 1
return
}
offset += bufferutils.writePushDataInt(buffer, chunk.length, offset)
chunk.copy(buffer, offset)
offset += chunk.length
// opcode
} else {
buffer.writeUInt8(chunk, offset)
offset += 1
}
})
if (offset !== buffer.length) throw new Error('Could not decode chunks')
return buffer
}
function decompile (buffer) {
// TODO: remove me
if (types.Array(buffer)) return buffer
typeforce(types.Buffer, buffer)
var chunks = []
var i = 0
while (i < buffer.length) {
var opcode = buffer[i]
// data chunk
if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) {
var d = bufferutils.readPushDataInt(buffer, i)
// did reading a pushDataInt fail? empty script
if (d === null) return []
i += d.size
// attempt to read too much data? empty script
if (i + d.number > buffer.length) return []
var data = buffer.slice(i, i + d.number)
i += d.number
chunks.push(data)
// opcode
} else {
chunks.push(opcode)
i += 1
}
}
return chunks
}
function toASM (chunks) {
if (Buffer.isBuffer(chunks)) {
chunks = decompile(chunks)
}
return chunks.map(function (chunk) {
// data?
if (Buffer.isBuffer(chunk)) return chunk.toString('hex')
// opcode!
return REVERSE_OPS[chunk]
}).join(' ')
}
function fromASM (asm) {
typeforce(types.String, asm)
return compile(asm.split(' ').map(function (chunkStr) {
// opcode?
if (OPS[chunkStr] !== undefined) return OPS[chunkStr]
// data!
return new Buffer(chunkStr, 'hex')
}))
}
function decompilePushOnly (script) {
var chunks = decompile(script)
typeforce([pushOnlyChunk], chunks)
return chunks.map(function (op) {
if (Buffer.isBuffer(op)) return op
if (op === OPS.OP_0) return new Buffer(0)
return scriptNumber.encode(op - OP_INT_BASE)
})
}
function compilePushOnly (chunks) {
typeforce([pushOnlyChunk], chunks)
return compile(chunks)
}
function isCanonicalPubKey (buffer) {
if (!Buffer.isBuffer(buffer)) return false
if (buffer.length < 33) return false
switch (buffer[0]) {
case 0x02:
case 0x03:
return buffer.length === 33
case 0x04:
return buffer.length === 65
}
return false
}
function isDefinedHashType (hashType) {
var hashTypeMod = hashType & ~0x80
// return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE
return hashTypeMod > 0x00 && hashTypeMod < 0x04
}
function isCanonicalSignature (buffer) {
if (!Buffer.isBuffer(buffer)) return false
if (!isDefinedHashType(buffer[buffer.length - 1])) return false
return bip66.check(buffer.slice(0, -1))
}
module.exports = {
compile: compile,
decompile: decompile,
fromASM: fromASM,
toASM: toASM,
compilePushOnly: compilePushOnly,
decompilePushOnly: decompilePushOnly,
number: require('./script_number'),
isCanonicalPubKey: isCanonicalPubKey,
isCanonicalSignature: isCanonicalSignature,
isDefinedHashType: isDefinedHashType
}
var templates = require('./templates')
for (var key in templates) {
module.exports[key] = templates[key]
}
|
JavaScript
| 0.000013 |
@@ -586,17 +586,19 @@
unction
-p
+isP
ushOnlyC
@@ -631,29 +631,131 @@
pes.
-oneOf(Buffer, isOPInt
+Buffer(value) %7C%7C isOPInt(value)%0A%7D%0A%0Afunction isPushOnly (value) %7B%0A return types.Array(value) && value.every(isPushOnlyChunk
)%0A%7D%0A
@@ -3342,39 +3342,34 @@
typeforce(
-%5Bp
+isP
ushOnly
-Chunk%5D
, chunks)%0A%0A
@@ -3598,23 +3598,18 @@
rce(
-%5Bp
+isP
ushOnly
-Chunk%5D
, ch
|
7d23a844439ceb88dafbdfc46de903a27661473d
|
Set a high max age for static assets
|
src/server.js
|
src/server.js
|
import express from 'express';
import path from 'path';
import compression from 'compression';
import bodyParser from 'body-parser';
import favicon from 'serve-favicon';
import herokuSslRedirect from 'heroku-ssl-redirect';
import publishAllApi from '@/server/api/publish-all';
import publishApi from '@/server/api/publish';
import unpublishApi from '@/server/api/unpublish';
import unsubscribe from '@/server/api/unsubscribe';
import notifySubscribers from '@/server/api/notify-subscribers';
import tipps from '@/server/api/tipps';
import putDrawing from '@/server/api/put-drawing';
import putImage from '@/server/api/put-images';
const app = express();
app.set('views', './src/server/views');
app.set('view engine', 'pug');
// Redirect to https
app.use(herokuSslRedirect());
// Gzip all the things
app.use(compression());
// Serve the static files
app.use(favicon(path.resolve('public/favicon.ico')));
app.use(express.static('public', {
extensions: 'html',
}));
app.use(bodyParser.json());
app.use(bodyParser.raw());
app.use(bodyParser.urlencoded({ extended: false }));
// Routes
app.get('/publish', publishAllApi);
app.get('/publish/:id', publishApi);
app.get('/unpublish/:id', unpublishApi);
app.get('/unsubscribe/:id', unsubscribe);
app.get('/notifysubscribers/:id', notifySubscribers);
app.get('/tipps', tipps);
app.put('/api/drawing', putDrawing);
// catch 404 and forward to error handler
// TODO: Find a way to manage errors
/* app.use((req, res, next) => {
const err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use((err, req, res) => {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
}); */
// Initially build all the files
// publishAll().then(buildIndex).then(buildGallery);
export default app;
|
JavaScript
| 0.000002 |
@@ -988,16 +988,33 @@
html',%0D%0A
+ maxAge: '1y',%0D%0A
%7D));%0D%0Aap
|
7aad4550ba66b36a5bdca28c6d306a0a35e96e55
|
Allow access log format to be customized
|
src/server.js
|
src/server.js
|
var environment = require('./lib/environment'),
express = require('express'),
socketserver = require('./lib/socketserver'),
handlebars = require('express-hbs'),
flash = require('connect-flash'),
http = require('http'),
routes = require('./routes'),
path = require('path'),
auth = require('./lib/auth');
var app = express();
var RedisStore = require('connect-redis')(express);
// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.normalize(__dirname + '/../views'));
app.engine('handlebars', handlebars.express3({
partialsDir: path.normalize(__dirname + '/../views/partials'),
defaultLayout: path.normalize(__dirname + '/../views/layouts/main.handlebars')
}));
app.set('view engine', 'handlebars');
app.use(express.favicon());
app.use(express.logger({ format: ':remote-addr - - [:date] ":method :url HTTP/:http-version" :status :res[content-length] ":referrer" ":user-agent" (:response-time ms)', stream: environment.accesslog }));
app.use(express.bodyParser({ hash: 'sha1', keepExtensions: 'true', uploadDir: 'tmp' }));
app.use(express.methodOverride());
app.use(express.static(path.normalize(__dirname + '/../public')));
app.use('/views', express.static(path.normalize(__dirname + '/../views')));
app.use(express.cookieParser());
app.use(express.session({
store: new RedisStore({
client: environment.datastore.client()
}),
secret: 'biblionarrator'
}));
app.use(flash());
auth.initialize(app);
app.use(function(req, res, next) {
app.locals({
user: req.user,
error: req.flash('error')
});
next();
});
app.use(app.router);
//params.extend(app);
// development only
if ('development' == app.get('env')) {
app.use(express.errorHandler());
}
routes.init(app);
exports.app = app;
var httpserver;
exports.listen = function(port) {
port = port || 3000;
httpserver = http.createServer(app);
socketserver.configure(httpserver);
httpserver.listen(port);
};
exports.testhost = function() {
return 'http://127.0.0.1:' + harness().address().port;
};
var harness = function() {
httpserver = httpserver || app.listen(0);
return httpserver;
};
|
JavaScript
| 0 |
@@ -837,16 +837,49 @@
format:
+ environment.logs.accessformat %7C%7C
':remot
|
be987415b78c90f5df968fef9ece35da1c173a84
|
change message wake up
|
src/server.js
|
src/server.js
|
import winston from 'winston'
import ns from 'natural-script'
import dotenv from 'dotenv'
import fs from 'fs'
import path from 'path'
import Os from './os/os'
import { Slack } from './adapters'
import { debug, scheduler, welcome } from './middlewares'
try {
fs.accessSync(path.join(__dirname, '../.env'), fs.R_OK)
// use .env file config
dotenv.config()
} catch (e) {
console.log(e)
}
let slack = new Slack({
token: process.env.SLACK_API_TOKEN
})
slack.on('ready', () => {
winston.info('slack ready')
})
let os = new Os({
parser: ns.parse,
adapters: [ slack ],
name: process.env.NAME || 'jarvis',
icon_url: process.env.ICON_URL || 'https://avatars1.githubusercontent.com/u/24452749?v=3&s=200'
})
os.on('ready', () => {
winston.info(`assistant ${os.name} ready`)
})
os.use(welcome)
os.use(debug)
os.use(scheduler)
os.hear('wake me up {{date:date}}', (req, res) => {
// console.log(req.parsed.date)
// res.reply('ok')
scheduler.scheduleDateEvent(req.user, 'wake-up', req.parsed.date.start.date())
})
os.hear('wake me up {{occurrence:occurence}}', (req, res) => {
scheduler.scheduleOccurrenceEvent(req.user, 'wake-up', req.parsed.occurence.laterjs)
})
scheduler.on('event.scheduled', ({ diff, event }) => {
winston.info('event.scheduled')
os.speak(event.event.user, 'Roger that!')
})
scheduler.on('event.done.once', ({ event }) => {
winston.info('event.done.once')
if (event.name === 'wake-up') {
os.speak(event.event.user, 'Wake up!')
} else {
os.speak(event.event.user, 'let\'s go')
}
event.event.finish()
})
scheduler.on('event.done.several.times', ({ event }) => {
winston.info('event.done.several.times')
if (event.name === 'wake-up') {
os.speak(event.event.user, 'Wake up!')
} else {
os.speak(event.event.user, 'let\'s go')
}
})
os.hear('*', (req, res) => {
res.reply('Sorry, I didn\'t understand your request')
})
os.start()
|
JavaScript
| 0.000002 |
@@ -1445,32 +1445,38 @@
)%0A if (event.
+event.
name === 'wake-u
@@ -1737,24 +1737,30 @@
if (event.
+event.
name === 'wa
|
cd2645a940c3e1e0f7a47a50891292bb2f4091c0
|
Fix createLocation deprecated warning, server side
|
src/server.js
|
src/server.js
|
import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import createLocation from 'history/lib/createLocation';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import universalRouter from './helpers/universalRouter';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort,
ws: true
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
console.log('proxy error', error);
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = { error: 'proxy_error', reason: error.message };
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(client);
const location = createLocation(req.path, req.query);
function hydrateOnClient() {
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={<div/>} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
}
universalRouter(location, undefined, store, true)
.then(({component, redirectLocation}) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
return;
}
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
})
.catch((error) => {
if (error.redirect) {
res.redirect(error.redirect);
return;
}
console.error('ROUTER ERROR:', pretty.render(error));
hydrateOnClient(); // let client render error page or re-request data
});
});
if (config.port) {
if (config.isProduction) {
const io = new SocketIo(server);
io.path('/api/ws');
}
server.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.name, config.apiPort);
console.info('==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
JavaScript
| 0 |
@@ -105,24 +105,23 @@
t create
-Location
+History
from 'h
@@ -137,24 +137,23 @@
b/create
-Location
+History
';%0Aimpor
@@ -1742,16 +1742,32 @@
ation =
+createHistory().
createLo
|
0403998e262ea663b404cb24686f5802d1b08060
|
return item after incrementing
|
src/spelly.js
|
src/spelly.js
|
"use strict";
import fs from "fs";
import { ok as Assert } from "assert";
import Configstore from "configstore";
import exists from "exists-sync";
import pkg from "../package.json";
class Spelly {
constructor(dictionary, options = {}) {
Assert(dictionary, "Missing required dictionary");
this._defaultStore = new Configstore(pkg.name);
options.cache = options.cache || {};
options.cache.type = options.cache.type || "configstore";
this._store = this._getStore(options.cache);
}
cache(misspelled, suggestion) {
let match = this._store.get(misspelled);
if (match) {
this._addToCache(misspelled, match, suggestion);
} else {
this._createCacheItem(misspelled, suggestion);
}
}
clearCache(key, value) {
if (key && value) {
let values = this._store.get(key);
let decrementer = 1;
let newValues = values.filter(item => item.word !== value);
let oldKey = values.filter(item => item.word === value)[0].score;
newValues.forEach(item => {
if (item.score >= oldKey) {
this._decrement(decrementer, item);
++decrementer
}
});
this._store.set(key, newValues);
return this;
} else if (key) {
return this._store.del(key);
} else {
return this._store.clear();
}
}
getCache(key) {
if (key) {
return this._store.get(key);
}
return this._store.all;
}
_addToCache(cacheKey, wordCache, suggestion) {
this._reorderCache(suggestion, wordCache);
wordCache.push(suggestion);
this._store.set(cacheKey, this._sort(wordCache));
}
_createCacheItem(word, suggestion) {
this._store.set(word, [suggestion]);
}
_decrement(decrement, item) {
item.score -= decrement;
return item;
}
_getStore(cacheOptions) {
switch (cacheOptions.type) {
case "configstore":
return cacheOptions.store || this._defaultStore;
break;
default:
return cacheOptions.store || this._defaultStore;
}
}
_increment(increment, item) {
item.score += increment;
}
_reorderCache(newItem, cacheArray) {
let newItemId = newItem.score;
let incrementer = 1;
cacheArray.forEach(item => {
if (item.score >= newItemId) {
this._increment(incrementer, item);
++incrementer;
}
});
return cacheArray;
}
_sort(arr) {
return arr.sort((a, b) => {
return a.score > b.score ? 1 : -1;
});
}
}
export default Spelly;
|
JavaScript
| 0.000002 |
@@ -2091,16 +2091,33 @@
rement;%0A
+ return item;%0A
%7D%0A%0A _
|
7baf1bc3dd79b3dcb4396d0d5b7ae68cdfb95860
|
make sure to focus textarea on load
|
src/survey.js
|
src/survey.js
|
var Vue = require('vue');
var insertCss = require('insert-css');
var bind = require('component-bind');
var escape = require('escape-html');
var is = require('is');
var MESSAGES = require('nps-translations');
insertCss(require('./index.scss'));
var RATING_STATE = 'rating';
var FEEDBACK_STATE = 'feedback';
var THANKS_STATE = 'thanks';
var FILLED_STATE = 'filled';
var DIALOG_SKIN = 'dialog';
var PANEL_SKIN = 'panel';
var Survey = Vue.extend({
template: require('./survey.html'),
partials: {
rating: require('./rating.html'),
feedback: require('./feedback.html'),
scale: require('./scale.html'),
thanks: require('./thanks.html'),
filled: require('./filled.html'),
'powered-by': require('./powered-by.html')
},
components: {
dialog: require('./dialog'),
panel: require('./panel')
},
replace: true,
data: function() {
return {
// model
rating: null,
feedback: '',
reason: '',
// state
visible: false,
state: RATING_STATE,
translation: null,
// settings
language: 'en',
serviceName: null,
poweredBy: true,
skin: DIALOG_SKIN,
theme: 'pink',
preview: false, // preview mode - positioned inside a preview div
position: 'cr', // tl (top-right), tr, bl, br
reasons: []
};
},
ready: function() {
if (this.showFeedbackText) {
this.focusFeedback();
}
},
computed: {
showCloseIcon: function() {
return this.state === FEEDBACK_STATE || this.state === RATING_STATE;
},
showFeedbackText: function() {
return this.state === FEEDBACK_STATE;
},
ratings: function() {
var selectedRating = this.rating;
return [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map(function(rating) {
return {
selected: selectedRating !== null && rating <= selectedRating
};
});
},
likelyHtml: function() {
var serviceName = is.string(this.serviceName) ? this.serviceName.trim() : null;
var us = this.t('US');
var serviceHtml = serviceName ? '<b>' + escape(serviceName) + '</b>' : us;
return escape(this.t('HOW_LIKELY')).replace('%s', serviceHtml);
},
followUp: function() {
var rating = this.rating;
if (is.number(rating)) {
var key;
if (rating <= 6) {
key = 'FOLLOWUP_DETRACTOR';
}
else if (rating <= 8) {
key = 'FOLLOWUP_PASSIVE';
}
else {
key = 'FOLLOWUP_PROMOTER';
}
return this.t(key) || this.t('FOLLOWUP');
}
return this.t('FOLLOWUP');
}
},
methods: {
t: function(key, param) {
if (this.translation) {
if (this.translation[key]) {
return this.translation[key];
}
if (key === 'FOLLOWUP' && this.translation['IMPROVE']) {
return this.translation['IMPROVE'];
}
}
var messages = MESSAGES[this.language] || MESSAGES.en;
return messages[key];
},
selectRating: function (rating) {
this.rating = rating;
this.state = FEEDBACK_STATE;
this.focusFeedback();
},
focusFeedback: function() {
Vue.nextTick(bind(this, function () {
if (this._isDestroyed) {
return;
}
var $feedback = this.$el.querySelector('input') || this.$el.querySelector('textarea');
if ($feedback) {
$feedback.focus();
}
}));
},
show: function() {
this.visible = true;
},
hide: function() {
this.visible = false;
},
submit: function() {
this.$emit('submit');
this.state = THANKS_STATE;
if (this.skin === DIALOG_SKIN) {
setTimeout(bind(this, function() {
if (this._isDestroyed) {
return;
}
this.hide();
}), 800);
}
},
onClose: function() {
this.hide();
this.$emit('dismiss');
}
}
});
module.exports = Survey;
|
JavaScript
| 0 |
@@ -2622,24 +2622,390 @@
methods: %7B%0A
+ nextTick: function(fn) %7B%0A Vue.nextTick(bind(this, function() %7B%0A if (this._isDestroyed) %7B%0A return;%0A %7D%0A fn.call(this);%0A %7D));%0A %7D,%0A setTimeout: function(fn, timeout) %7B%0A setTimeout(bind(this, function() %7B%0A if (this._isDestroyed) %7B%0A return;%0A %7D%0A fn.call(this);%0A %7D), timeout);%0A %7D,%0A
t: funct
@@ -3530,35 +3530,36 @@
ction() %7B%0A
-Vue
+this
.nextTick(bind(t
@@ -3548,35 +3548,24 @@
is.nextTick(
-bind(this,
function ()
@@ -3570,69 +3570,8 @@
) %7B%0A
- if (this._isDestroyed) %7B%0A return;%0A %7D%0A
@@ -3682,24 +3682,63 @@
feedback) %7B%0A
+ this.nextTick(function() %7B%0A
$f
@@ -3750,24 +3750,26 @@
ck.focus();%0A
+
%7D%0A
@@ -3765,25 +3765,36 @@
%7D
-%0A
+);%0A
%7D
-)
+%0A %7D
);%0A %7D
@@ -4039,24 +4039,29 @@
) %7B%0A
+this.
setTimeout(b
@@ -4055,35 +4055,24 @@
.setTimeout(
-bind(this,
function() %7B
@@ -4076,75 +4076,8 @@
) %7B%0A
- if (this._isDestroyed) %7B%0A return;%0A %7D%0A
@@ -4104,17 +4104,16 @@
%7D
-)
, 800);%0A
|
3bad0660c411a8b83dcc20de45a00ba84cdf4b2b
|
load 100 images not 500
|
app/components/Main.js
|
app/components/Main.js
|
import React from "react";
import Gallery from "./Gallery";
import Home from "./Home";
import Status from "./Status";
//todo: promisify
let fetchStatuses = function() {
return { data: [
{
text: "You QCon folks are amazing. Thanks for having me. Mad hearts ❤",
date: "2016-01-31 20:22"
},
{
text: "i'll be speaking at QCon SF in a few weeks. ack",
date: "2016-01-30 15:54"
},
{
text: "our team won an Intel Internet of Things hackathon yesterday in Seattle. #wearensemble",
date: "2016-01-30 15:54"
}
]};
};
let Main = React.createClass({
getInitialState: function() {
return fetchStatuses();
},
render: function() {
return (
<div className="container-fluid">
<div className="row">
<div className="photos">
<Gallery photoCount="500" tagName="featured" />
</div>
</div>
<div className="row">
{this.props.children}
</div>
</div>
);
}
});
export default Main;
|
JavaScript
| 0.002499 |
@@ -930,17 +930,17 @@
oCount=%22
-5
+1
00%22 tagN
@@ -944,16 +944,19 @@
agName=%22
+web
featured
|
0ad67a382901684c433f586d35ea7b890cab9a9f
|
fix merge
|
region_definition/trimDigits.js
|
region_definition/trimDigits.js
|
//
// required packages
//
var fs = require('fs');
// trimDigitsInRegionsJSONFile('../public/v1/regions.json', '../public/v1/regions.json', 3);
trimDigitsInRegionsJSONFile('nwac/nwac_regions.json', 'nwac/nwac_regions.json', 3);
// trimDigitsInRegionsJSONFile('Canada_all/canada_regions_wb_fix_simplified.json', 'Canada_all/canada_regions_wb_fix_simplified.json', 3);
// trimDigitsInRegionsJSONFile('btac/btac_simplified.json', 'btac/btac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('sac/sac_simplified.json', 'sac/sac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('uac/uac_simplified.json', 'uac/uac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('caic/caic_simplified.json', 'caic/caic_simplified.json', 3);
// trimDigitsInRegionsJSONFile('esac/esac_simplified.json', 'esac/esac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('gnfac/gnfac_simplified.json', 'gnfac/gnfac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('snfac/snfac_simplified.json', 'snfac/snfac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('wcmac/wcmac_simplified_ipac_fix.json', 'wcmac/wcmac_simplified_ipac_fix.json', 3);
// trimDigitsInRegionsJSONFile('ipac/ipac_simplified.json', 'ipac/ipac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('cnfaic/cnfaic_simplified.json', 'cnfaic/cnfaic_simplified.json', 3);
// trimDigitsInRegionsJSONFile('aac/aac_simplified.json', 'aac/aac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('jac/jac_simplified.json', 'jac/jac_simplified.json', 3);
// trimDigitsInRegionsJSONFile('haic/haic_simplified.json', 'haic/haic_simplified.json', 3);
trimDigitsInRegionsJSONFile('fac/fac_simplified.json', 'fac/fac_simplified.json', 3);
function trimDigitsInRegionsJSONFile(inputFilePath, outputFilePath, digits) {
var input = fs.readFileSync(inputFilePath, 'utf8');
var output = trimDigits(input, digits);
fs.writeFileSync(outputFilePath, output, 'utf8');
}
function trimDigits(input, digits) {
var regions = JSON.parse(input);
for (var i = 0; i < regions.length; i++) {
for (var j = 0; j < regions[i].points.length; j++) {
regions[i].points[j].lat = parseFloat(regions[i].points[j].lat).toFixed(digits);
regions[i].points[j].lon = parseFloat(regions[i].points[j].lon).toFixed(digits);
}
}
return (JSON.stringify(regions, null, 4));
}
|
JavaScript
| 0.000001 |
@@ -130,32 +130,35 @@
ions.json', 3);%0A
+//
trimDigitsInRegi
|
05d362bf1ac84915f3cd1a9b63f0c84bdf016809
|
Fix the ssr build path
|
ssr/server.js
|
ssr/server.js
|
const fs = require('fs');
const path = require('path');
const bundleRunner = require('./bundle-runner');
const express = require('express');
const { renderPreloadLinks } = require('./preload-links');
const isProd = process.env.NODE_ENV === 'production';
const projectRoot = path.resolve(__dirname, '..');
const buildDir = path.join(projectRoot, 'build');
const serverBuildPath = path.join(buildDir, 'server');
const webBuildPath = path.join(buildDir, 'web');
// This is the output of build:client.
// The server will render the vue app for incoming requests and interpolate it
// into the index.html before serving out.
const indexHtmlTemplate = fs.readFileSync(path.join(webBuildPath, 'index.html'), 'utf-8');
// The SSR manifest holds mappings of vue component => assets that are in use.
// Similarly to index.html and assets, it is generated with build:client (its the --ssrManifest flag)
// As the server renders the app, it keeps track of which components it rendered.
// We use this to figure out the smallest list of assets we need to preload on the client side
// in order to hydrate it.
const ssrManifest = require(path.join(webBuildPath, 'ssr-manifest.json'));
// This is the output of build:server, and is the entry point for the ssr request.
// We read it as string instead of requiring because we only want to evaluate it within
// a new node context, and its more efficient reading it from disk once and copying it
// over to the new node context than to read it from disk for every request.
const serverBundleFile = path.join(serverBuildPath, 'server.js');
// const serverVMScript = bundleRunner.getPreparedScript(serverBundleFile);
const serverBundle = bundleRunner.compileModule(serverBundleFile);
const server = express();
// Only needed in dev builds, in prod everything would be served from cdn.
if (!isProd) {
server.use(
express.static(webBuildPath, {
index: false,
})
);
server.use('/favicon.ico', (req, res) => {
res.status(404).end();
});
}
// TODO: refactor this into somewhere else.
server.use(async (req, res) => {
try {
const context = {
url: req.url,
ua: req.headers['user-agent'],
accept: req.headers['accept'] || '',
};
console.log(context);
const s = Date.now();
// const vm = bundleRunner.getNewContext();
// const createApp = vm.run(serverVMScript).default;
// const app = await createApp(context);
// console.log('created app');
// passing SSR context object which will be available via useSSRContext()
// @vitejs/plugin-vue injects code into a component's setup() that registers
// itself on renderCtx.modules. After the render, renderCtx.modules would contain all the
// components that have been instantiated during this render call.
// vm.sandbox.app = app;
// vm.sandbox.context = context;
// vm.sandbox.serverBundleFile = serverBundleFile;
// const renderFunc = vm.run(
// `
// module.exports = async function () {
// const createApp = require(serverBundleFile).default;
// const app = await createApp(context);
// const { renderToString } = require('vue/server-renderer');
// const renderCtx = {};
// const appHtml = await renderToString(app, renderCtx);
// return [appHtml, renderCtx];
// };
// `,
// path.resolve(path.join(__dirname, 'server-sandbox.js'))
// );
// const [appHtml, renderCtx] = await renderFunc();
const createApp = serverBundle();
const [appHtml, renderCtx] = await createApp(context);
// the SSR manifest generated by Vite contains module -> chunk/asset mapping
// which we can then use to determine what files need to be preloaded for this
// request.
const preloadLinks = renderPreloadLinks(renderCtx.modules, ssrManifest);
const html = indexHtmlTemplate
.replace(`<!-- ssr-preload-links -->`, preloadLinks)
.replace(`<!-- ssr-outlet -->`, appHtml)
.replace(`<!-- gj:ssr-metatags -->`, context.meta.renderTags());
if (context.redirect) {
console.log('sending redirect', context.redirect);
res.redirect(301, context.redirect);
return;
} else if (context.errorCode) {
console.log('sending error code', context.errorCode);
res.status(context.errorCode);
} else {
res.status(200);
}
res.set({ 'Content-Type': 'text/html' }).end(html, () => {
const total = Date.now() - s;
console.log(
'response ended',
'total time:',
total + 'ms',
'render time:',
total - context.prefetchTime + 'ms',
req.url,
req.headers['host'],
req.headers['user-agent']
);
});
console.log('request ending');
} catch (e) {
console.log('got error', req.url, e);
res.status(500).end('Internal Server Error');
}
});
const port = 3501;
server.listen(port, () => {
console.log(`server started at localhost:${port}`);
});
|
JavaScript
| 0.000002 |
@@ -396,20 +396,17 @@
dDir, 's
-erve
+s
r');%0Acon
|
9ce8482a13d790aece8880a841a8ed26752e8277
|
add min sync interval time detect
|
sync/index.js
|
sync/index.js
|
/**!
* cnpmjs.org - sync/index.js
*
* Copyright(c) cnpmjs.org and other contributors.
* MIT Licensed
*
* Authors:
* dead_horse <[email protected]> (http://deadhorse.me)
*/
'use strict';
/**
* Module dependencies.
*/
var debug = require('debug')('cnpmjs.org:sync:index');
var co = require('co');
var ms = require('humanize-ms');
var util = require('util');
var config = require('../config');
var mail = require('../common/mail');
var totalService = require('../services/total');
var logger = require('../common/logger');
var syncDistWorker = require('./sync_dist');
var sync = null;
switch (config.syncModel) {
case 'all':
sync = require('./sync_all');
break;
case 'exist':
sync = require('./sync_exist');
break;
}
if (!sync && config.enableCluster) {
console.log('[%s] [sync_worker:%s] no need to sync, exit now', Date(), process.pid);
process.exit(0);
}
console.log('[%s] [sync_worker:%s] syncing with %s mode',
Date(), process.pid, config.syncModel);
//set sync_status = 0 at first
co(function* () {
yield* totalService.updateSyncStatus(0);
})();
// the same time only sync once
var syncing = false;
var handleSync = co(function* () {
debug('mode: %s, syncing: %s', config.syncModel, syncing);
if (!syncing) {
syncing = true;
debug('start syncing');
var data;
var error;
try {
data = yield *sync();
} catch (err) {
error = err;
error.message += ' (sync package error)';
logger.syncError(error);
}
data && logger.syncInfo(data);
if (!config.debug) {
sendMailToAdmin(error, data, new Date());
}
syncing = false;
}
});
if (sync) {
handleSync();
setInterval(handleSync, ms(config.syncInterval));
}
/**
* sync dist(node.js and phantomjs)
*/
var syncingDist = false;
var syncDist = co(function* syncDist() {
if (syncingDist) {
return;
}
syncingDist = true;
logger.syncInfo('Start syncing dist...');
try {
yield* syncDistWorker();
yield* syncDistWorker.syncPhantomjsDir();
} catch (err) {
err.message += ' (sync dist error)';
logger.syncError(err);
if (config.noticeSyncDistError) {
sendMailToAdmin(err, null, new Date());
}
}
syncingDist = false;
});
if (config.syncDist) {
syncDist();
setInterval(syncDist, ms(config.syncInterval));
} else {
logger.syncInfo('sync dist disable');
}
/**
* sync popular modules
*/
var syncingPopular = false;
var syncPopular = co(function* syncPopular() {
if (syncingPopular) {
return;
}
syncingPopular = true;
logger.syncInfo('Start syncing popular modules...');
var data;
var error;
try {
data = yield* require('./sync_popular');
} catch (err) {
error = err;
error.message += ' (sync package error)';
logger.syncError(error);
}
if (data) {
logger.syncInfo(data);
}
if (!config.debug) {
sendMailToAdmin(error, data, new Date());
}
syncingPopular = false;
});
if (config.syncPopular) {
syncPopular();
setInterval(syncPopular, ms(config.syncPopularInterval));
} else {
logger.syncInfo('sync popular module disable');
}
function sendMailToAdmin(err, result, syncTime) {
result = result || {};
var to = [];
for (var name in config.admins) {
to.push(config.admins[name]);
}
debug('Send email to all admins: %j, with err message: %s, result: %j, start sync time: %s.',
to, err ? err.message : '', result, syncTime);
var subject;
var type;
var html;
if (err) {
subject = 'Sync Error';
type = 'error';
html = util.format('Sync packages from official registry failed.\n' +
'Start sync time is %s.\nError message is %s: %s\n%s.', syncTime, err.name, err.message, err.stack);
} else if (result.fails && result.fails.length) {
subject = 'Sync Finished But Some Packages Failed';
type = 'warn';
html = util.format('Sync packages from official registry finished, but some packages sync failed.\n' +
'Start sync time is %s.\n %d packges sync failed: %j ...\n %d packages sync successes :%j ...',
syncTime, result.fails.length, result.fails.slice(0, 10),
result.successes.length, result.successes.slice(0, 10));
} else if (result.successes && result.successes.length) {
subject = 'Sync Finished';
type = 'log';
html = util.format('Sync packages from official registry finished.\n' +
'Start sync time is %s.\n %d packages sync successes :%j ...',
syncTime, result.successes.length, result.successes.slice(0, 10));
}
debug('send email with type: %s, subject: %s, html: %s', type, subject, html);
logger.syncInfo('send email with type: %s, subject: %s, html: %s', type, subject, html);
if (type && type !== 'log') {
mail[type](to, subject, html, function (err) {
if (err) {
logger.error(err);
}
});
}
}
|
JavaScript
| 0 |
@@ -1351,18 +1351,18 @@
= yield
-
*
+
sync();%0A
@@ -1655,24 +1655,201 @@
leSync();%0A
+var syncInterval = ms(config.syncInterval);%0A var minSyncInterval = ms('5m');%0A if (!syncInterval %7C%7C syncInterval %3C minSyncInterval) %7B%0A syncInterval = minSyncInterval;%0A %7D%0A
setInterval(
@@ -1860,26 +1860,16 @@
leSync,
-ms(config.
syncInte
@@ -1873,17 +1873,16 @@
nterval)
-)
;%0A%7D%0A%0A/**
|
40b7e0a88b982dc4d8ab4e548c32d15134ad38cd
|
fix js
|
contrib/static/mod.js
|
contrib/static/mod.js
|
/*
* mod.js, moderator page js stuff
*/
// TODO: implement mod panel all the way
document.onload = function(ev) {
// populate the mod page with stuff
}
function get_longhash(str) {
var idx = str.indexOf("#") + 1;
if ( idx > 0 ) {
str = str.substr(idx);
}
console.log(str);
return str;
}
// handle ban command
function nntpchan_ban() {
nntpchan_mod({
parser: get_longhash,
name: "ban",
handle: function(j) {
if (j.banned) {
return document.createTextNode(j.banned);
}
}
});
}
function nntpchan_unban() {
nntpchan_mod({
name: "unban",
handle: function(j) {
if (j.result) {
return document.createTextNode(j.result);
}
}
})
}
function get_board_target() {
var e = document.getElementById("nntpchan_board_target");
return e.value;
}
function nntpchan_admin_board(method) {
nntpchan_admin(method, {
newsgroup: get_board_target()
})
}
function nntpchan_admin(method, param) {
nntpchan_mod({
name:"admin",
parser: function(target) {
return method;
},
handle: function(j) {
if (j.result) {
return document.createTextNode(j.result);
} else {
return "nothing happened?";
}
}
method: ( param && "POST" ) || "GET"
})
}
// handle delete command
function nntpchan_delete() {
nntpchan_mod({
parser: get_longhash,
name: "del",
handle: function(j) {
var elem = document.createElement("div");
if (j.deleted) {
for ( var idx = 0 ; idx < j.deleted.length ; idx ++ ) {
var msg = "deleted: " + j.deleted[idx];
var e = document.createTextNode(msg);
var el = document.createElement("div");
el.appendChild(e);
elem.appendChild(el);
}
}
if (j.notdeleted) {
for ( var idx = 0 ; idx < j.notdeleted.length ; idx ++ ) {
var msg = "not deleted: " + j.notdeleted[idx];
var e = document.createTextNode(msg);
var el = document.createElement("div");
el.appendChild(e);
elem.appendChild(el);
}
}
return elem;
}
});
}
function nntpchan_mod(mod_action) {
// get the element
var input = document.getElementById("nntpchan_mod_target");
var target = input.value;
if (mod_action.parser) {
target = mod_action.parser(target);
}
var elem = document.getElementById("nntpchan_mod_result");
// clear old results
while( elem.firstChild ) {
elem.removeChild(elem.firstChild);
}
// fire off ajax
var ajax = new XMLHttpRequest();
ajax.onreadystatechange = function() {
if (ajax.readyState == XMLHttpRequest.DONE) {
var status = ajax.status;
// we gud?
if (status == 200) {
// yah
var txt = ajax.responseText;
var j = JSON.parse(txt);
if (j.error) {
var e = document.createTextNode(j.error);
elem.appendChild(e);
} else {
if (mod_action.handle) {
var result = mod_action.handle(j);
if (result) {
elem.appendChild(result);
} else {
// fail
alert("mod action failed, handler returned nothing");
}
} else {
// fail
alert("mod action has no handler");
}
}
} else if (status) {
// nah
// http error
elem.innerHTML = "error: HTTP "+status;
}
// clear input
input.value = "";
}
}
if (mod_action.name) {
var url = mod_action.name + "/" + target;
ajax.open(mod_action.method || "GET", url);
ajax.send();
} else {
alert("mod action has no name");
}
}
|
JavaScript
| 0.000002 |
@@ -1229,24 +1229,25 @@
%7D%0A %7D
+,
%0A method:
|
85b743188ae9ef495ed8c68ffed5ef9f6490340c
|
Fix wrong asset path being copied into dist folder.
|
tasks/copy.js
|
tasks/copy.js
|
module.exports = {
assets: {
files: [
{expand: true, src: ["images/**"], dest: "dist/"}
]
}
};
|
JavaScript
| 0 |
@@ -69,13 +69,13 @@
: %5B%22
-image
+asset
s/**
|
9beaadd778d1ca591d315246806217e3751edde1
|
fix typo
|
controllers/oauth2.js
|
controllers/oauth2.js
|
const express = require('express');
const router = express.Router();
const csrf = require('csurf');
const auth = require('../helpers/authentication');
const api = require('../api');
const { Configuration } = require('@schul-cloud/commons');
const csrfProtection = csrf({ cookie: true });
router.get('/login', csrfProtection, (req, res, next) => api(req)
.get(`/oauth2/loginRequest/${req.query.login_challenge}`).then((loginRequest) => {
req.session.login_challenge = req.query.login_challenge;
if (loginRequest.skip) {
res.redirect('/oauth2/login/success');
} else {
res.redirect(Configuration.get('NOT_AUTHENTICATED_REDIRECT_URL'));
}
}));
router.get('/login/success', csrfProtection, auth.authChecker, (req, res, next) => {
if (!req.session.login_challenge) res.redirect('/dashboard/');
const body = {
remember: false,
remember_for: 0,
};
api(req).patch(`/oauth2/loginRequest/${req.session.login_challenge}/?accept=1`,
{ body }).then((loginRequest) => {
delete (req.session.login_challenge);
res.redirect(loginRequest.redirect_to);
});
});
const acceptConsent = (r, w, challenge, grantScopes, remember = false) => {
const body = {
grant_scope: (Array.isArray(grantScopes) ? grantScopes : [grantScopes]),
remember,
remember_for: 60 * 60 * 24 * 30,
};
return api(r).patch(`/oauth2/consentRequest/${challenge}/?accept=1`, { body })
.then(consentRequest => w.redirect(consentRequest.redirect_to));
};
const displayScope = (scope, w) => {
switch (scope) {
case 'openid':
return w.$t('login.oauth2.label.openId');
case 'profile':
return w.$t('login.oauth2.label.yourName');
case 'email':
return w.$t('login.ouath2.label.email');
default:
return scope;
}
}
router.get('/consent', csrfProtection, auth.authChecker, (r, w) => {
// This endpoint is hit when hydra initiates the consent flow
if (r.query.error) {
// An error occurred (at hydra)
return w.send(`${r.query.error}<br />${r.query.error_description}`);
}
return api(r).get(`/oauth2/consentRequest/${r.query.consent_challenge}`).then((consentRequest) => {
return api(r).get(`/ltitools/?oAuthClientId=${consentRequest.client.client_id}&isLocal=true`).then((tool) => {
if (consentRequest.skip || tool.data[0].skipConsent) {
return acceptConsent(r, w, r.query.consent_challenge, consentRequest.requested_scope);
}
return w.render('oauth2/consent', {
inline: true,
title: w.$t('login.oauth2.headline.loginWithSchoolCloud'),
subtitle: '',
client: consentRequest.client.client_name,
action: `/oauth2/consent?challenge=${r.query.consent_challenge}`,
buttonLabel: w.$t('global.button.accept'),
scopes: consentRequest.requested_scope.map(scope => ({
display: displayScope(scope, w),
value: scope,
})),
});
});
});
});
router.post('/consent', auth.authChecker, (r, w) => acceptConsent(r, w, r.query.challenge, r.body.grantScopes, true));
router.get('/username/:pseudonym', (req, res, next) => {
api(req).get('/pseudonym', {
qs: {
pseudonym: req.params.pseudonym,
},
}).then((pseudonym) => {
let shortName;
let completeName;
const anonymousName = '???';
completeName = anonymousName;
shortName = completeName;
if (pseudonym.data.length) {
completeName = `${pseudonym.data[0].user.firstName} ${pseudonym.data[0].user.lastName}`;
shortName = `${pseudonym.data[0].user.firstName} ${pseudonym.data[0].user.lastName.charAt(0)}.`;
}
res.render('oauth2/username', {
completeName,
shortName,
infoText: res.$t('login.oauth2.text.yourNameIsProtected'),
});
});
});
module.exports = router;
|
JavaScript
| 0.999991 |
@@ -1671,10 +1671,10 @@
in.o
-u
a
+u
th2.
|
77fb23a10868c44c8fdf4e62ee6120741697f25a
|
Fix click handler test
|
__tests__/LaddaButton-test.js
|
__tests__/LaddaButton-test.js
|
jest.dontMock('..');
var React = require('react/addons');
var Ladda = require('ladda/dist/ladda.min');
var LaddaButton = React.createFactory(require('..'));
var TestUtils = React.addons.TestUtils;
Ladda.create = jest.genMockFunction();
describe('LaddaButton', function() {
function createRenderedButton(props) {
var el = LaddaButton(props, 'Click here');
return TestUtils.renderIntoDocument(el);
}
it('should default to style "expand-left"', function() {
var button = createRenderedButton({});
var node = button.getDOMNode();
expect(node.getAttribute('data-style')).toBe('expand-left');
});
it('should create a ladda button with correct attributes', function() {
var button = createRenderedButton({
active: true,
progress: 0.5,
buttonColor: '#eee',
buttonSize: 'xl',
spinnerSize: 30,
spinnerColor: '#ddd',
buttonStyle: 'slide-up'
});
var node = button.getDOMNode();
expect(node.getAttribute('data-color')).toBe('#eee');
expect(node.getAttribute('data-size')).toBe('xl');
expect(node.getAttribute('data-style')).toBe('slide-up');
expect(node.getAttribute('data-spinner-size')).toBe('30');
expect(node.getAttribute('data-spinner-color')).toBe('#ddd');
});
it('should not trigger "onClick" event', function() {
var onClick = jest.genMockFunction();
var button = createRenderedButton({onClick: onClick});
TestUtils.Simulate.click(button);
expect(onClick.mock.calls.length).toBe(0);
});
describe('child element', function() {
it('should trigger "onClick" event', function() {
var onClick = jest.genMockFunction();
var laddaButton = LaddaButton({onClick: onClick});
var button = TestUtils.renderIntoDocument(laddaButton);
var node = TestUtils.findRenderedDOMComponentWithTag(button, 'button');
TestUtils.Simulate.click(node);
expect(onClick.mock.calls.length).toBe(1);
});
});
it('should work after multiple React.render invocations', function() {
var buttonContainer = React.DOM.div(null, LaddaButton());
var div = document.createElement('div');
React.render(buttonContainer, div);
React.render(buttonContainer, div);
jest.runAllTimers();
expect(div.innerHTML).toMatch(/ladda-label/);
expect(div.innerHTML).toMatch(/ladda-spinner/);
});
});
|
JavaScript
| 0.000001 |
@@ -1279,12 +1279,8 @@
uld
-not
trig
@@ -1446,24 +1446,37 @@
click(button
+.getDOMNode()
);%0A expec
@@ -1509,17 +1509,17 @@
h).toBe(
-0
+1
);%0A %7D);
@@ -1526,86 +1526,47 @@
%0A%0A
-describe('child element', function() %7B%0A%0A it('should trigger %22onClick%22 event
+it('should inherit className from props
', f
@@ -1585,115 +1585,92 @@
-
var
-onClick = jest.genMockFunction();
+el = LaddaButton(%7B
%0A
-var laddaButton = LaddaButton(%7BonClick: onClick%7D
+className: 'buttonClass'%0A %7D, 'Click here'
);%0A
-
var
butt
@@ -1665,22 +1665,20 @@
var
-button
+node
= TestU
@@ -1705,32 +1705,21 @@
ent(
+e
l
-addaButton
);%0A
-
var
node
@@ -1718,116 +1718,61 @@
var
-node = TestUtils.findRenderedDOMComponentWithTag(button, 'button');%0A TestUtils.Simulate.click(node
+className = node.getDOMNode().getAttribute('class'
);%0A
-
@@ -1782,49 +1782,50 @@
ect(
-onClick.mock.calls.length).toBe(1);%0A %7D
+className).toBe('ladda-button buttonClass'
);%0A
|
d0371840d0e2d2f2b706cda592b1306938fa3ac5
|
Add FSO.Drive.filesystem, FSO.GetDriveName
|
_emulator/FileSystemObject.js
|
_emulator/FileSystemObject.js
|
const controller = require('../_controller');
function TextStream(filename) {
this.buffer = controller.readFile(filename) || '';
this.uuid = controller.getUUID();
this.filename = filename;
this.write = (line) => {
this.buffer = this.buffer + line;
controller.writeFile(filename, this.buffer);
controller.logResource(this.uuid, this.filename, this.buffer);
};
this.writeline = (line) => {
this.buffer = this.buffer + line + '\n';
controller.writeFile(filename, this.buffer);
controller.logResource(this.uuid, this.filename, this.buffer);
};
this.readall = () => {
return this.buffer;
};
this.close = () => {};
this.bufferarray = [];
this.readline = function() {
if (this.bufferarray.length === 0)
this.bufferarray = this.buffer.split('\n');
return this.bufferarray.shift();
};
this.shortpath = (path) => path;
}
function ProxiedTextStream(filename) {
return new Proxy(new TextStream(filename), {
get: function(target, name) {
name = name.toLowerCase();
switch (name) {
default:
if (!(name in target)) {
controller.kill(`TextStream.${name} not implemented!`);
}
return target[name];
}
},
set: function(a, b, c) {
b = b.toLowerCase();
if (c.length < 1024)
console.log(`FSObject[${b}] = ${c};`);
a[b] = c;
},
});
}
function Folder(path, autospawned) {
this.attributes = 16;
this.datelastmodified = new Date(new Date() - 15 * 60 * 1000); // Last changed: 15 minutes ago
this.files = [];
this.name = (path.replace(/\w:/i, '').match(/\\(\w*)(?:\\)?$/i) || [null, ''])[1],
this.path = path;
this.subfolders = autospawned ? [] : [new ProxiedFolder(path + '\\RandomFolder', true)];
this.type = 'folder';
}
function ProxiedFolder(path, name, autospawned = false) {
return new Proxy(new Folder(path, name, autospawned), {
get: function(target, name) {
name = name.toLowerCase();
switch (name) {
default:
if (!(name in target)) {
controller.kill(`FileSystemObject.Folder.${name} not implemented!`);
}
return target[name];
}
},
});
}
function File(contents) {
this.openastextstream = () => new ProxiedTextStream(contents);
this.shortpath = 'C:\\PROGRA~1\\example-file.exe';
this.size = Infinity;
this.attributes = 32;
}
function ProxiedFile(filename) {
return new Proxy(new File(filename), {
get: function(target, name) {
name = name.toLowerCase();
switch (name) {
default:
if (!(name in target)) {
controller.kill(`FileSystemObject.File.${name} not implemented!`);
}
return target[name];
}
},
});
}
function Drive(name) {
this.volumename = name;
this.availablespace = 80*1024*1024*1024;
this.drivetype = 2;
}
function ProxiedDrive(name) {
return new Proxy(new Drive(name), {
get: function(target, name) {
name = name.toLowerCase();
switch (name) {
default:
if (!(name in target)) {
controller.kill(`FileSystemObject.Drive.${name} not implemented!`);
}
return target[name];
}
},
});
}
function FileSystemObject() {
this.createtextfile = this.opentextfile = (filename) => new ProxiedTextStream(filename);
this.buildpath = (...args) => args.join('\\');
this.fileexists = this.deletefile = () => {
const value = process.argv.indexOf('--no-file-exists') === -1;
if (value) {
console.log('Returning `true` for FileSystemObject.FileExists; use --no-file-exists if nothing happens');
}
return value;
};
this.getfile = (filename) => new ProxiedFile(filename);
this.getspecialfolder = function(id) {
switch (id) {
case 0:
case '0':
return 'C:\\WINDOWS\\';
case 1:
case '1':
return '(System folder)';
case 2:
case '2':
return '(Temporary folder)';
default:
return '(Special folder ' + id + ')';
}
};
this.gettempname = () => '(Temporary file)';
this.createfolder = (folder) => '(Temporary new folder)';
this.folderexists = (folder) => {
const defaultValue = true;
console.log(`Checking if ${folder} exists, returning ${defaultValue}`);
return defaultValue;
};
this.getfolder = (str) => new ProxiedFolder(str);
this.getfileversion = () => '';
this.drives = [new ProxiedDrive('C:')];
this.getdrive = (drive) => new ProxiedDrive(drive);
}
module.exports = function() {
return new Proxy(new FileSystemObject(), {
get: function(target, name) {
name = name.toLowerCase();
switch (name) {
default:
if (!(name in target)) {
controller.kill(`FileSystemObject.${name} not implemented!`);
}
return target[name];
}
},
});
};
|
JavaScript
| 0.000002 |
@@ -2680,16 +2680,43 @@
pe = 2;%0A
+%09this.filesystem = %22NTFS%22;%0A
%7D%0A%0Afunct
@@ -4238,16 +4238,146 @@
drive);%0A
+%09this.getdrivename = path =%3E %7B%0A%09%09const matches = path.match(/%5E%5Cw:/);%0A%09%09if (matches == null)%0A%09%09%09return %22%22;%0A%09%09return matches%5B0%5D;%0A%09%7D%0A
%7D%0A%0Amodul
|
23ab35c33ec8c5486caa636f7fbd4cfe941b2681
|
Fix webpack-dist path
|
webpack-dist.config.js
|
webpack-dist.config.js
|
let webpack = require('webpack')
let HtmlWebpackPlugin = require('html-webpack-plugin')
let CopyWebpackPlugin = require('copy-webpack-plugin')
let vendorModules = /(node_modules|bower_components)/
let CompressionPlugin = require('compression-webpack-plugin')
let CleanPlugin = require('clean-webpack-plugin')
module.exports = {
target: "web",
entry: {
app: "./app",
},
output: {
path: './dist',
filename: "app.js",
pathinfo: true,
},
module: {
loaders: [
{
test: /\.js$/,
exclude: vendorModules,
loader: "babel",
},
{ test: /\.css$/, loader: "style-loader!css-loader" },
{ test: /\.(woff|woff2|eot|ttf|svg)$/, loader: 'url-loader?limit=100000' },
{ test: /\.(jpg|jpeg|gif|png)$/, loader:'url-loader?limit=100000' },
{ test: /\.scss$/, loaders: ["style", "css", "sass"] },
],
},
plugins: [
new webpack.optimize.CommonsChunkPlugin("init.js"),
new HtmlWebpackPlugin({
title: 'App',
minify: process.env.NODE_ENV === 'production' ? {
removeComments: true,
removeCommentsFromCDATA: true,
collapseWhitespace: true,
conservativeCollapse: false,
collapseBooleanAttributes: true,
removeAttributeQuotes: true,
removeRedundantAttributes: true,
preventAttributesEscaping: true,
useShortDoctype: true,
removeEmptyAttributes: true,
removeScriptTypeAttributes: true,
removeStyleLinkTypeAttributes: true,
} : false,
template: './index.html',
}),
new webpack.HotModuleReplacementPlugin(),
new CleanPlugin(['./dist']),
new CopyWebpackPlugin([{ from: 'assets', to: 'assets' }]),
new webpack.NoErrorsPlugin(),
new webpack.DefinePlugin({
"process.env": {
NODE_ENV: JSON.stringify(process.env.NODE_ENV),
BROWSER: JSON.stringify(true),
},
}),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.OccurenceOrderPlugin(true),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false,
},
mangle: false,
comments: /\@license|\@preserv/gi,
}),
new CompressionPlugin({
asset: "{file}.gz",
algorithm: "gzip",
regExp: new RegExp("\.(js|html|css|svg)$"),
threshold: 10240,
minRatio: 0.8,
})
],
debug: false,
watch: false,
}
|
JavaScript
| 0.000038 |
@@ -455,16 +455,36 @@
: true,%0A
+ publicPath: %22%22,%0A
%7D,%0A%0A
|
a09a8e51ccd3a48423dc19e450bb2ef6ea55abfc
|
Disable analyser
|
webpack.base.config.js
|
webpack.base.config.js
|
const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const DuplicatePackageCheckerPlugin = require('duplicate-package-checker-webpack-plugin');
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin');
const NODE_ENV = process.env.NODE_ENV || 'development';
console.log(JSON.stringify(NODE_ENV));
const isProduction = process.env.NODE_ENV === 'production';
const env = {
production: NODE_ENV === 'production',
staging: NODE_ENV === 'staging',
test: NODE_ENV === 'test',
development: NODE_ENV === 'development' || typeof NODE_ENV === 'undefined',
};
env['build'] = (env.production || env.staging);
const extractCSS = new ExtractTextPlugin({
filename: isProduction ? 'urf.[contenthash].[name].css' : 'style.[name].css',
allChunks: false,
});
module.exports = {
target: 'web',
entry: {
vendor: ['react', 'react-dom', 'unfetch'],
main: './src/entry.tsx',
},
output: {
path: path.resolve(path.join(__dirname, 'build')),
publicPath: '/assets',
filename: '[name].js',
chunkFilename: '[chunkName].chunk.js',
},
resolve: {
modules: [
'web_modules',
'node_modules',
'./src/images',
],
extensions: ['.tsx', '.ts', '.js', '.svg'],
},
plugins: [
new BundleAnalyzerPlugin({ analyzerPort: 3999 }),
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(NODE_ENV),
},
__DEV__: env.development,
__STAGING__: env.staging,
__PRODUCTION__: env.production,
}),
new LodashModuleReplacementPlugin({
collections: true,
shorthands: true,
}),
new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks: Infinity }),
// new ChunkManifestPlugin({
// filename: 'manifest.json',
// manifestVariable: 'chunkManifest',
// }),
new DuplicatePackageCheckerPlugin(),
new HtmlWebpackPlugin({
filename: 'index.html',
template: 'src/index.html',
alwaysWriteToDisk: true,
inject: true,
chunks: ['vendor', 'main'],
}),
new HtmlWebpackHarddiskPlugin(),
extractCSS,
],
module: {
rules: [
{
test: /\.js$/,
use: 'eslint-loader',
exclude: /node_modules/,
enforce: 'pre',
},
{
test: /\.css$/,
loader: extractCSS.extract({
fallback: 'style-loader',
use: 'css-loader?importLoaders=1!postcss-loader',
}),
},
{
test: /\.ts(x?)$/,
exclude: /node_modules/,
use: [
// {
// loader: 'babel-loader',
// },
{
loader: 'awesome-typescript-loader?useBabel',
},
],
},
{
test: /\.svg/,
use: ['babel-loader', {loader: 'svgr/webpack', options: {
svgo: false,
},}],
},
{
test: /\.json/,
use: 'json-loader',
}, {
test: /\.png|\.jpg|\.woff/,
use: 'url-loader?limit=10000',
},
],
},
};
|
JavaScript
| 0.000002 |
@@ -1598,24 +1598,27 @@
ugins: %5B%0A
+ //
new BundleA
|
b0064af16e70b05e66f8faf2404dc9a07605f67f
|
Enable webpack ModuleConcatenationPlugin.
|
webpack.config.prod.js
|
webpack.config.prod.js
|
var path = require('path');
var webpack = require('webpack');
var LodashModuleReplacementPlugin = require('lodash-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var ManifestPlugin = require('webpack-manifest-plugin');
var ChunkManifestPlugin = require('chunk-manifest-webpack-plugin');
var SWPrecacheWebpackPlugin = require('sw-precache-webpack-plugin');
var cssnext = require('postcss-cssnext');
var postcssFocus = require('postcss-focus');
var postcssReporter = require('postcss-reporter');
var cssnano = require('cssnano');
var WebpackBundleSizeAnalyzerPlugin = require('webpack-bundle-size-analyzer').WebpackBundleSizeAnalyzerPlugin;
var ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin');
module.exports = {
devtool: 'hidden-source-map',
entry: {
app: ['./client/index.js'],
vendor: [
'react',
'react-dom'
]
},
output: {
path: __dirname + '/dist/',
filename: '[name].[chunkhash].js',
publicPath: '/'
},
resolve: {
extensions: [
'.js', '.jsx'
],
modules: [
path.resolve('./client'),
'node_modules'
]
},
module: {
rules: [
{
test: /\.css$/,
include: [
/node_modules/, /plugin\.css/
],
use: [
{
loader: 'style-loader'
}, {
loader: 'css-loader',
options: {
localIdentName: '[local]',
modules: true,
importLoaders: 1,
sourceMap: true
}
}
]
}, {
test: /\.css$/,
exclude: [
/node_modules/, /plugin\.css$/
],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: [
{
loader: 'css-loader',
options: {
localIdentName: '[hash:base64]',
modules: true,
importLoaders: 1
}
}, {
loader: 'postcss-loader',
options: {
plugins: () => [
postcssFocus(),
cssnext({
browsers: ['last 2 versions', 'IE > 10']
}),
postcssReporter({clearMessages: true})
]
}
}
]
})
}, {
test: /\.jsx*$/,
exclude: /node_modules/,
loader: 'babel-loader'
}, {
test: /\.(jpe?g|gif|png|svg)$/i,
loader: 'url-loader',
options: {
limit: 10000
}
}, {
test: /\.json$/,
loader: 'json-loader'
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new LodashModuleReplacementPlugin({'shorthands': true, 'collections': true}),
new webpack
.optimize
.CommonsChunkPlugin({
name: 'vendor',
minChunks: function(module) {
// this assumes your vendor imports exist in the node_modules directory
return module.context && module
.context
.indexOf("node_modules") !== -1;
},
filename: 'vendor.js'
}),
new ExtractTextPlugin({filename: 'app.[chunkhash].css', allChunks: true, disable: false}),
new ManifestPlugin({basePath: '/'}),
new ChunkManifestPlugin({filename: "chunk-manifest.json", manifestVariable: "webpackManifest"}),
new webpack
.optimize
.UglifyJsPlugin({
compressor: {
unused: true,
dead_code: true, // big one--strip code that will never execute
warnings: false, // good for prod apps so users can't peek behind curtain
drop_debugger: true,
conditionals: true,
evaluate: true,
drop_console: true, // strips console statements
sequences: true,
booleans: true
},
comments: false,
sourceMap: false,
mangle: true,
minimize: true
}),
new webpack
.optimize
.AggressiveMergingPlugin(),
new WebpackBundleSizeAnalyzerPlugin('./plain-report.txt'),
new ScriptExtHtmlWebpackPlugin({
module: /\.js$/
}),
new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /(zh-tw|en)/),
new SWPrecacheWebpackPlugin({
cacheId: 'tiamat',
filename: 'precache-service-worker.js',
staticFileGlobs: ['dist/**/*.{js,css}'],
dontCacheBustUrlsMatching: /^(?!.*(vendor\.js)).*\.(js|css)$/,
stripPrefixMulti: {
'dist/': '',
'assets/': ''
},
runtimeCaching: [
{
urlPattern: /^https?:\/\/(.+)\/api/,
handler: 'networkFirst'
}, {
urlPattern: /^https?:\/\/(.+)\/(?!.*(api|\.)).*$/,
handler: 'cacheFirst'
}
],
verbose: true
})
]
};
|
JavaScript
| 0 |
@@ -855,23 +855,16 @@
r: %5B
-%0A
'react',
%0A
@@ -859,22 +859,16 @@
'react',
-%0A
'react-
@@ -871,21 +871,16 @@
act-dom'
-%0A
%5D%0A %7D,%0A%0A
@@ -4118,24 +4118,92 @@
ngPlugin(),%0A
+ new webpack%0A .optimize%0A .ModuleConcatenationPlugin(),%0A
new Webp
@@ -4289,23 +4289,16 @@
Plugin(%7B
-%0A
module:
@@ -4304,21 +4304,16 @@
/%5C.js$/
-%0A
%7D),%0A
|
1b20e6f025934332c3ac058da03d01d9097b271d
|
Use normal password inputs on OS's other than linux
|
extension/loader.js
|
extension/loader.js
|
/* globals generateElementsVariable jsSHA otplib decryptJSON loadSVG */
const DOM = generateElementsVariable([
"totpbox",
"hiddencopy",
"ticker",
"enterPassword",
"password",
"submitPassword"
]);
function hash(text) {
const extension_UUID = new URL(browser.runtime.getURL("loader.js")).hostname;
var shaObj = new jsSHA("SHA-256", "TEXT");
shaObj.update(text + extension_UUID);
var hash = shaObj.getHash("HEX");
return hash;
}
async function copyTarget(code, copy) {
// move code to textarea, copy
DOM.hiddencopy.value = code.innerText;
DOM.hiddencopy.focus();
DOM.hiddencopy.setSelectionRange(0, DOM.hiddencopy.value.length);
document.execCommand("copy");
DOM.hiddencopy.blur();
// Change icon from copy to check for 1s as visual feedback
copy.innerText = "";
copy.appendChild(await loadSVG("icons/check.svg"));
setTimeout(async () => {
copy.innerText = "";
copy.appendChild(await loadSVG("icons/content-copy.svg"));
}, 1000);
}
function timeLoop() {
// from https://github.com/yeojz/otplib/blob/gh-pages/js/app.js#L65
var epoch = Math.floor(Date.now() / 1000);
var countDown = epoch % 30;
DOM.ticker.innerText = 30 - countDown;
if (countDown === 0) {
var codes = document.getElementsByClassName("timecode");
for (var code of codes) {
if (code.dataset.key === "") {
continue;
} else {
code.innerText = otplib.authenticator.generate(code.dataset.key);
}
}
}
}
async function createRow(item) {
var row = document.createElement("div");
row.className = "row";
DOM.totpbox.appendChild(row);
var name = document.createElement("span");
name.innerText = item.name;
name.className = "name";
row.appendChild(name);
var code = document.createElement("span");
if (item.name === "") {
code.style.padding = 0;
}
if (item.key === "") {
code.innerText = "000000";
code.className = "timecode";
} else {
code.innerText = otplib.authenticator.generate(item.key);
code.className = "timecode";
}
code.dataset.key = item.key;
row.appendChild(code);
var copy = document.createElement("span");
copy.className = "copy img";
copy.appendChild(await loadSVG(browser.runtime.getURL("icons/content-copy.svg")));
row.appendChild(copy);
row.addEventListener("click", copyTarget.bind(null, code, copy));
}
async function loadTOTP() {
var res = await browser.storage.local.get();
var password = DOM.password.value;
var passwordHash = hash(password);
// Check the entered password is correct
if (passwordHash === res.hash) {
if (password !== "") {
res = decryptJSON(res, password);
}
// Hides password input popup with a transition
// and sets the popup page size to automatic
DOM.enterPassword.style.transition = "0.5s";
DOM.enterPassword.style.width = 0;
document.body.style.width = "100%";
document.body.style.height = "100%";
if (res.otp_list.length > 0) {
res.otp_list.forEach(createRow);
} else {
createRow({
name: "No sites configured.",
key: ""
});
}
timeLoop(); // loads timer before waiting 1s
setInterval(timeLoop, 1000);
} else {
document.getElementById("wrongPassword").removeAttribute("hidden");
}
}
async function main() {
var res = await browser.storage.local.get();
if (res.hash === undefined) {
browser.runtime.openOptionsPage();
window.close();
}
if (res.hash === hash("")) {
loadTOTP();
} else {
DOM.enterPassword.style.width = "100%";
document.body.style.width = "400";
document.body.style.height = "250";
}
for (let item of document.getElementsByClassName("svg-replace")) {
item.appendChild(await loadSVG(item.dataset.svg));
}
Array.from(document.getElementsByTagName("*")) // Use Array.from to permit using .forEach
.forEach(el => {
el.style.color = res.fontColor;
});
Array.from(document.getElementsByTagName("*")) // Use Array.from to permit using forEach
.forEach(el => {
el.style.backgroundColor = res.backgroundColor;
});
}
document.getElementById("settings").addEventListener("click", () => {
browser.runtime.openOptionsPage();
});
DOM.submitPassword.addEventListener("click", loadTOTP);
DOM.password.addEventListener("keyup", key => {
// submit password with enter
if (key.key === "Enter") {
loadTOTP();
}
});
document.addEventListener("DOMContentLoaded", main);
|
JavaScript
| 0.000014 |
@@ -3566,24 +3566,138 @@
on main() %7B%0A
+ if ((await browser.runtime.getPlatformInfo()).os !== %22linux%22) %7B%0A DOM.password.type = %22password%22;%0A %7D%0A
var res
|
77461501dae66242ef03dae4088b742477d574c8
|
Update app.js
|
Javascript/app.js
|
Javascript/app.js
|
//Problem: User interaction doesn't provide desired results.
//Solution: Add interactivty so the user can manage daily tasks.
var taskInput = document.getElementById("new-task"); //new-task
var addButton = document.getElementsByTagName("button")[0]; //first button
var incompleteTasksHolder = document.getElementById("incomplete-tasks"); //incomplete-tasks
var completedTasksHolder= document.getElementById("completed-tasks"); //completed-tasks
//New Task List Item
var createNewTaskElement = function(taskString) {
//Create List Item
var listItem = document.createElement("li");
//input (checkbox)
var checkBox = document.createElement("input"); // checkbox
//label
var label = document.createElement("label");
//input (text)
var editInput = document.createElement("input"); // text
//button.edit
var editButton = document.createElement("button");
//button.delete
var deleteButton = document.createElement("button");
//Each element needs modifying
checkBox.type = "checkbox";
editInput.type = "text";
editButton.innerText = "Edit";
editButton.className = "edit";
deleteButton.innerText = "Delete";
deleteButton.className = "delete";
label.innerText = taskString;
//Each element needs appending
listItem.appendChild(checkBox);
listItem.appendChild(label);
listItem.appendChild(editInput);
listItem.appendChild(editButton);
listItem.appendChild(deleteButton);
return listItem;
}
//Add a new task
var addTask = function() {
console.log("Add task...");
//Create a new list item with the text from #new-task:
var listItem = createNewTaskElement(taskInput.value);
//Append listItem to incompleteTasksHolder
incompleteTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
taskInput.value = "";
}
//Edit an existing task
var editTask = function() {
console.log("Edit task...");
var listItem = this.parentNode;
var editInput = listItem.querySelector("input[type=text");
var label = listItem.querySelector("label");
var containsClass = listItem.classList.contains("editMode");
//if the class of the parent is .editMode
if(containsClass) {
//Switch from .editMode
//label text become the input's value
label.innerText = editInput.value;
} else {
//Switch to .editMode
//input value becomes the label's text
editInput.value = label.innerText;
}
//Toggle .editMode on the list item
listItem.classList.toggle("editMode");
}
//Delete an existing task
var deleteTask = function() {
console.log("Delete task...");
var listItem = this.parentNode;
var ul = listItem.parentNode;
//Remove the parent list item from the ul
ul.removeChild(listItem);
}
//Mark a task as complete
var taskCompleted = function() {
console.log("Task complete...");
//Append the task list item to the #completed-tasks
var listItem = this.parentNode;
completedTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskIncomplete);
}
//Mark a task as incomplete
var taskIncomplete = function() {
console.log("Task incomplete...");
//Append the task list item to the #incomplete-tasks
var listItem = this.parentNode;
incompleteTasksHolder.appendChild(listItem);
bindTaskEvents(listItem, taskCompleted);
}
var bindTaskEvents = function(taskListItem, checkBoxEventHandler) {
console.log("Bind list item events");
//select taskListItem's children
var checkBox = taskListItem.querySelector("input[type=checkbox]");
var editButton = taskListItem.querySelector("button.edit");
var deleteButton = taskListItem.querySelector("button.delete");
//bind editTask to edit button
editButton.onclick = editTask;
//bind deleteTask to delete button
deleteButton.onclick = deleteTask;
//bind checkBoxEventHandler to checkbox
checkBox.onchange = checkBoxEventHandler;
}
var ajaxRequest = function() {
console.log("AJAX request");
}
//Set the click handler to the addTask function
addButton.addEventListener("click", addTask);
addButton.addEventListener("click", ajaxRequest);
//cycle over incompleteTasksHolder ul list items
for(var i = 0; i < incompleteTasksHolder.children.length; i++) {
//bind events to list item's children (taskCompleted)
bindTaskEvents(incompleteTasksHolder.children[i], taskCompleted);
}
//cycle over completedTasksHolder ul list items
for(var i = 0; i < completedTasksHolder.children.length; i++) {
//bind events to list item's children (taskIncomplete)
bindTaskEvents(completedTasksHolder.children[i], taskIncomplete);
}
|
JavaScript
| 0.000002 |
@@ -4573,28 +4573,31 @@
%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A%0A
+%0A%0A%0A
|
66108e77e9e018f830857b324827c724028cbf50
|
Remove 403 image
|
cron/wakeup.js
|
cron/wakeup.js
|
var CronJob = require("cron").CronJob;
module.exports = function(bot) {
function random(items) {
return items[Math.floor(Math.random() * items.length)];
}
new CronJob(
"0 0 10 * * 1-5",
function() {
var list = [
"http://i.imgur.com/TaD84Sw.jpg",
"http://i.imgur.com/M5tqTz0.jpg",
"https://scontent-sea1-1.cdninstagram.com/t51.2885-15/e35/19436764_645907692286091_6621865046647504896_n.jpg",
"https://i.pinimg.com/originals/53/a8/1c/53a81ce030957de6f3127c689956bc64.jpg",
"ネムイ(´・ωゞ)",
":syuzo: :syuzo: :syuzo:"
];
bot.say({
text: random(list),
channel: "C02GLQNHR"
});
},
null,
true,
"Asia/Tokyo"
);
};
|
JavaScript
| 0.000001 |
@@ -319,127 +319,8 @@
g%22,%0A
- %22https://scontent-sea1-1.cdninstagram.com/t51.2885-15/e35/19436764_645907692286091_6621865046647504896_n.jpg%22,%0A
|
6e5ab3df0c07c1d5c6e6c5612d3eda2b6731c527
|
change comment bug
|
data/comment.js
|
data/comment.js
|
"use strict";
/*
Created by Qingzheng on 2016/12/01
Name: Qingzheng Liu
*/
const mongoCollections = require("../config/mongoCollections");
const comment = mongoCollections.comment;
const uuid = require('node-uuid');
/*
The comment data structure
{
"_id": "",
"content": "",
"createTime": "",
"stars": "",
"userId": "",
"target": "",
"blogId": "",
"siteId": "",
"cityId": ""
}
*/
let exportedMethods = {
getAllComments() {
return comment().then((commentCollection) => {
return commentCollection.find({}).toArray();
});
},
getCommentById(id) {
if (!id) return Promise.reject ("You must provide a comment id.");
return comment().then((commentCollection) => {
return commentCollection.findOne({ _id: id }).then((comment) => {
if (!comment) return Promise.reject ('comment with id: ${id} is not found.');
return comment;
});
});
},
getCommentByUserId(userId) {
if (!userId) return Promise.reject ("You must provide a userId.");
return comment().then((commentCollection) => {
return commentCollection.find({ userId: userId }).toArray().then((commentList) => {
if (!commentList) return Promise.reject ('comment named ${userId} is not found.');
return commentList;
});
});
},
getCommentByCityId(cityId) {
if (!cityId) return Promise.reject ("You must provide a cityId.");
return comment().then((commentCollection) => {
return commentCollection.find({ cityId: cityId }).toArray().then((commentList) => {
if (!commentList) return Promise.reject ('comment named ${cityId} is not found.');
return commentList;
});
});
},
getCommentByBelongToId(id) {
if (!id) return Promise.reject ("You must provide a belongToId.");
return comment().then((commentCollection) => {
return commentCollection.find({ siteId: siteId }).toArray().then((commentList) => {
if (!commentList) return Promise.reject ('comment named ${siteId} is not found.');
return commentList;
});
});
},
addComment(content, createTime, stars, userId, belongToId) {
// check content and userId
if (!content) return Promise.reject ("You must provide content of the comment.");
//if (!userId) return Promise.reject ("You must provide userId of the comment.");
return comment().then((commentCollection) => {
let newComment = {
_id: uuid.v4(),
content: content,
createTime: createTime,
stars: stars,
userId: userId,
belongToId: belongToId
};
return commentCollection.insertOne(newComment).then((newInsertInformation) => {
return newInsertInformation.insertedId;
}).then((newId) => {
return this.getCommentById(newId);
});
});
},
removeComment(id) {
if (!id) return Promise.reject ("You must provide an comment id.");
return comment().then((commentCollection) => {
return commentCollection.removeOne({ _id: id }).then((deletionInfo) => {
if (deletionInfo.deletedCount === 0) {
throw ('Could not delete comment with id of ${id}.');
} else {"message","remove comment success!"}
});
});
},
removeCommentStars(id, StarsToRemove) {
if (!id) return Promise.reject("You must provide a comment id.");
if (!StarsToRemove) return Promise.reject("You must provide star to remove.");
return comment().then((commentCollection) => {
return commentCollection.update({ _id: id }, { $pullAll: { "stars": StarsToRemove } }).then((result) => {
return this.getCommentById(id);
});
});
},
updateComment(id, updatedComment) {
if (!id) return Promise.reject ("You must provide an id.");
return comment().then((commentCollection) => {
let updatedCommentData = {};
// content
if (updatedComment.content) {
updatedCommentData.content = updatedComment.content;
}
// createTime
if (updatedComment.createTime) {
updatedCommentData.createTime = updatedComment.createTime;
}
// stars
if (updatedComment.stars) {
updatedCommentData.stars = updatedComment.stars;
}
// userId
if (updatedComment.userId) {
updatedCommentData.userId = updatedComment.userId;
}
// target
if (updatedComment.target) {
updatedCommentData.target = updatedComment.target;
}
// blogId
if (updatedComment.blogId) {
updatedCommentData.blogId = updatedComment.blogId;
}
// siteId
if (updatedComment.siteId) {
updatedCommentData.siteId = updatedComment.siteId;
}
// cityId
if (updatedComment.cityId) {
updatedCommentData.cityId = updatedComment.cityId;
}
let updateCommand = {
$set: updatedCommentData
};
return commentCollection.updateOne({ _id: id }, updateCommand).then((result) => {
return this.getCommentById(id);
});
});
}
}
module.exports = exportedMethods;
|
JavaScript
| 0 |
@@ -2115,24 +2115,22 @@
nd(%7B
- siteId: siteId
+belongToId: id
%7D).t
|
c6ef260ba7283bb55c35605fbb4dcb9961b076a6
|
remove `is-generator` check on function proto
|
is-generator.js
|
is-generator.js
|
/**
* Export generator function checks.
*/
module.exports = isGenerator
module.exports.fn = isGeneratorFunction
/**
* Check whether an object is a generator.
*
* @param {Object} obj
* @return {Boolean}
*/
function isGenerator (obj) {
return obj &&
typeof obj.next === 'function' &&
typeof obj.throw === 'function'
}
/**
* Check whether a function is generator.
*
* @param {Function} fn
* @return {Boolean}
*/
function isGeneratorFunction (fn) {
return typeof fn === 'function' &&
fn.constructor &&
fn.constructor.name === 'GeneratorFunction' &&
isGenerator(fn.prototype)
}
|
JavaScript
| 0 |
@@ -575,40 +575,7 @@
ion'
- &&%0A isGenerator(fn.prototype)
%0A%7D%0A
|
1c0b569083905e2df53c8c40f5dc56a7b796f15b
|
Update bio.js
|
javascript/bio.js
|
javascript/bio.js
|
var realPhoto;
realPhoto = false;
var photoClicked = 0;
function enterPage() {
var name;
name = $("#name").val();
$("#nameText").fadeOut();
$("#name").fadeOut();
$("#enter").fadeOut();
$("#welcome").html("Welcome " + name);
$("#info").fadeIn();
$("body").css("background-color", "#EEE");
$("#welcome").css("font-size", "16pt");
$("#welcome").css("font-family", "Ubuntu Mono");
}
function collatzConjecture() {
//x = parseInt($("#collatzInital").value);
x = 23;
alert(x);
};
$("#mePhoto").click(function() {
if (!realPhoto) {
$("#mePhoto").attr("src", "image/jpg/frame.jpg");
if (photoClicked < 1) {
$("#myPhotoText").html("Another Picture of Me");
photoClicked++;
} else {
$("#myPhotoText").html("Frame");
}
realPhoto = true;
} else {
$("#mePhoto").attr("src", "image/jpg/stickFigure.jpg");
if (photoClicked < 2) {
$("#myPhotoText").html("And Another");
photoClicked++;
} else {
$("#myPhotoText").html("Stick Figure");
}
realPhoto = false;
}
});
|
JavaScript
| 0.000001 |
@@ -420,10 +420,8 @@
%7B%0A%09
-//
x =
|
571e1f1d5a08097889a6c613fa9e2a5c02c8bdcc
|
fix webpack path issue on windows
|
webpack.config.js
|
webpack.config.js
|
var rucksack = require('rucksack-css')
var webpack = require('webpack')
module.exports = {
context: __dirname + '/client',
entry: {
jsx: './index.jsx',
html: './index.html',
vendor: ['react']
},
output: {
path: __dirname + '/static',
filename: 'bundle.js',
},
module: {
loaders: [
{
test: /\.html$/,
loader: 'file?name=[name].[ext]'
},
{
test: /\.css$/,
loaders: [
'style-loader',
'css-loader?modules&sourceMap&importLoaders=1&localIdentName=[name]__[local]___[hash:base64:5]',
'postcss-loader'
]
},
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
loaders: [
'react-hot',
'babel-loader'
]
},
],
},
resolve: {
extensions: ['', '.js', '.jsx']
},
postcss: [
rucksack({
autoprefixer: true
})
],
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendor', 'vendor.bundle.js'),
new webpack.DefinePlugin({
'process.env': { NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development') }
})
]
}
|
JavaScript
| 0 |
@@ -64,16 +64,50 @@
ebpack')
+%0Avar path = path = require('path')
%0A%0Amodule
@@ -130,16 +130,29 @@
ontext:
+path.resolve(
__dirnam
@@ -156,20 +156,20 @@
name
- +
+,
'
+.
/client'
,%0A
@@ -164,16 +164,17 @@
/client'
+)
,%0A entr
@@ -277,16 +277,29 @@
path:
+path.resolve(
__dirnam
@@ -303,20 +303,20 @@
name
- +
+,
'
+.
/static'
,%0A
@@ -311,16 +311,17 @@
/static'
+)
,%0A fi
@@ -1191,11 +1191,74 @@
%7D)%0A %5D
+,%0A devServer: %7B%0A contentBase: %22./client%22,%0A hot: true%0A %7D
%0A%7D%0A
|
952e249fe429ab9c88ca39368e892129f168e3e6
|
Make HMR work when app is ran on web host
|
webpack.config.js
|
webpack.config.js
|
var path = require('path');
var webpack = require('webpack');
module.exports = {
devtool: 'eval',
entry: [
'webpack-dev-server/client?http://localhost:3000',
'webpack/hot/only-dev-server',
'./src/index'
],
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: '/static/'
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
],
module: {
loaders: [{
test: /\.js$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
}]
}
};
|
JavaScript
| 0.000001 |
@@ -144,25 +144,21 @@
http
+s
://
-localhost:3000
+notica.us
',%0A
@@ -422,16 +422,54 @@
()%0A %5D,%0A
+ watchOptions: %7B%0A poll: true%0A %7D,%0A
module
|
bb6b5008b147c8759b77da02fbd8da0458c6fa99
|
add extended option for bodyParser, see #94
|
rosetta.js
|
rosetta.js
|
// Copyright 2002-2015, University of Colorado Boulder
/**
* Main entry point for PhET translation web app. This is where ExpressJS gets configured and the routes are set up.
*
* @author John Blanco
* @author Aaron Davis
*/
/* jslint node: true */
'use strict';
// modules
var assert = require( 'assert' );
var express = require( 'express' );
var doT = require( 'express-dot' );
var parseArgs = require( 'minimist' );
var winston = require( 'winston' );
var bodyParser = require( 'body-parser' );
var query = require( 'pg-query' );
var fs = require( 'fs' );
var _ = require( 'underscore' );
// constants
var LISTEN_PORT = 16372;
var PREFERENCES_FILE;
/*
* When running on simian or figaro, rosetta is run under user "phet-admin". However, "process.env.HOME" will get
* the user who is starting the process's home directory, not phet-admin's home directory, therefore we need to use
* a different approach to get the home directory.
*/
if ( !/^win/.test( process.platform ) ) {
var passwdUser = require( 'passwd-user' );
PREFERENCES_FILE = passwdUser.sync( process.getuid() ).homedir + '/.phet/build-local.json';
}
else {
PREFERENCES_FILE = process.env.HOME + '/.phet/build-local.json';
}
// ensure that the preferences file exists and has the required fields
assert( fs.existsSync( PREFERENCES_FILE ), 'missing preferences file ' + PREFERENCES_FILE );
var preferences = require( PREFERENCES_FILE );
assert( preferences.githubUsername, 'githubUsername is missing from ' + PREFERENCES_FILE );
assert( preferences.githubPassword, 'githubPassword is missing from ' + PREFERENCES_FILE );
assert( preferences.buildServerAuthorizationCode, 'buildServerAuthorizationCode is missing from ' + PREFERENCES_FILE );
assert( preferences.rosettaSessionSecret, 'rosettaSessionSecret is missing from ' + PREFERENCES_FILE +
'. To set this up for local testing add any string as the value for "rosettaSessionSecret"' );
// initialize globals
global.preferences = preferences;
global.translatedStrings = {}; // object to hold the already translated strings
// must be required after global.preferences has been initialized
var routes = require( __dirname + '/js/routes' );
// configure postgres connection
if ( preferences.pgConnectionString ) {
query.connectionParameters = preferences.pgConnectionString;
}
else {
query.connectionParameters = 'postgresql://localhost/rosetta';
}
// Handle command line input
// First 2 args provide info about executables, ignore
var commandLineArgs = process.argv.slice( 2 );
var parsedCommandLineOptions = parseArgs( commandLineArgs, {
boolean: true
} );
var defaultOptions = {
// options for supporting help, currently no other options are supported, but this might change
help: false,
h: false
};
for ( var key in parsedCommandLineOptions ) {
if ( key !== '_' && parsedCommandLineOptions.hasOwnProperty( key ) && !defaultOptions.hasOwnProperty( key ) ) {
console.log( 'Unrecognized option: ' + key );
console.log( 'try --help for usage information.' );
return;
}
}
// If help flag, print help and usage info
if ( parsedCommandLineOptions.hasOwnProperty( 'help' ) || parsedCommandLineOptions.hasOwnProperty( 'h' ) ) {
console.log( 'Usage:' );
console.log( ' node rosetta.js [options]' );
console.log( '' );
console.log( 'Options:' );
console.log(
' --help (print usage and exit)\n' +
' type: bool default: false\n' );
return;
}
// Merge the default and supplied options.
var options = _.extend( defaultOptions, parsedCommandLineOptions );
// add timestamps
winston.remove( winston.transports.Console );
winston.add( winston.transports.Console, { 'timestamp': true } );
// Create and configure the ExpressJS app
var app = express();
app.set( 'views', __dirname + '/html/views' );
app.set( 'view engine', 'dot' );
app.engine( 'html', doT.__express );
// set static directories for css, img, and js
app.use( '/translate/css', express.static( __dirname + '/public/css' ) );
app.use( '/translate/img', express.static( __dirname + '/public/img' ) );
app.use( '/translate/js', express.static( __dirname + '/public/js' ) );
// need cookieParser middleware before we can do anything with cookies
app.use( express.cookieParser() );
app.use( express.session( { secret: preferences.rosettaSessionSecret } ) );
app.use( bodyParser.json() );
app.use( bodyParser.urlencoded() );
//----------------------------------------------------------------------------
// Set up the routes. The order matters.
//----------------------------------------------------------------------------
// route that checks whether the user is logged in
app.get( '/translate/*', routes.checkForValidSession );
// landing page for the translation utility
app.get( '/translate/', routes.chooseSimulationAndLanguage );
// route for translating a specific sim to a specific language
app.get( '/translate/sim/:simName?/:targetLocale?', routes.translateSimulation );
app.post( '/translate/sim/save/:simName?/:targetLocale?', routes.saveStrings );
app.post( '/translate/sim/:simName?/:targetLocale?', routes.submitStrings );
// route for extracting strings from a sim
app.get( '/translate/extractStrings', routes.extractStringsAPI );
// fall through route
app.get( '/*', routes.pageNotFound );
// start the server
app.listen( LISTEN_PORT, function() { winston.log( 'info', 'Listening on port ' + LISTEN_PORT ) } );
|
JavaScript
| 0 |
@@ -4401,16 +4401,37 @@
encoded(
+ %7B extended: false %7D
) );%0A%0A//
|
d44447786d864f76d71366e05655107bbba122b3
|
Update mapapp.js
|
whatsnear/js/mapapp.js
|
whatsnear/js/mapapp.js
|
$(document).ready(function () {
var map,
infowindow,
myLocation,
map,
marker,
mapBlock = $('#map')[0],
input = document.getElementById("pac-input");
var url = window.location.hash;
var hash = url.substring(url.indexOf("#")+1);
//Check for Browser support
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function (position) {
myLocation = {
lat: position.coords.latitude,
lng: position.coords.longitude
};
embedMap(myLocation);
});
} else {
mapBlock.text('Your browser is out of fashion, there\'s no geolocation!');
};
$(window).hashchange( function(){
hash = location.hash;
embedMap(latlng);
});
//Embed map
function embedMap(latlng) {
console.log(latlng);
map = new google.maps.Map(mapBlock, {
center: latlng,
zoom: 15
});
infowindow = new google.maps.InfoWindow();
var marker = new google.maps.Marker({
map: map,
anchorPoint: new google.maps.Point(0, -29)
});
var service = new google.maps.places.PlacesService(map);
service.nearbySearch({
location: latlng,
radius: 500,
types: [hash]
}, callback);
};
function callback(results, status) {
if (status === google.maps.places.PlacesServiceStatus.OK) {
for (var i = 0; i < results.length; i++) {
createMarker(results[i]);
}
}
}
function createMarker(place) {
var placeLoc = place.geometry.location;
var marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
animation: google.maps.Animation.DROP
});
google.maps.event.addListener(marker, 'click', function () {
infowindow.setContent(place.name);
infowindow.open(map, this);
});
}
});
|
JavaScript
| 0.000001 |
@@ -1710,16 +1710,45 @@
name);%0D%0A
+%09%09%09console.log(place.name);%0D%0A
%09%09%09infow
|
c458abdfd85427f7505baaae867b2be03f269fd7
|
add comments
|
test/bench.js
|
test/bench.js
|
const path = require('path');
const htmlDiffer = require('./helpers/html-differ.js');
const {loadFiles} = require('./helpers/load.js');
let marked = require('../');
function load() {
const dir = path.resolve(__dirname, './specs/commonmark');
const sections = loadFiles(dir);
let specs = [];
for (const section in sections) {
specs = specs.concat(sections[section].specs);
}
return specs;
}
function runBench(options) {
options = options || {};
const specs = load();
// Non-GFM, Non-pedantic
marked.setOptions({
gfm: false,
tables: false,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false
});
if (options.marked) {
marked.setOptions(options.marked);
}
bench('marked', specs, marked);
// GFM
marked.setOptions({
gfm: true,
tables: false,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: false
});
if (options.marked) {
marked.setOptions(options.marked);
}
bench('marked (gfm)', specs, marked);
// Pedantic
marked.setOptions({
gfm: false,
tables: false,
breaks: false,
pedantic: true,
sanitize: false,
smartLists: false
});
if (options.marked) {
marked.setOptions(options.marked);
}
bench('marked (pedantic)', specs, marked);
try {
bench('commonmark', specs, (() => {
const commonmark = require('commonmark');
const parser = new commonmark.Parser();
const writer = new commonmark.HtmlRenderer();
return function (text) {
return writer.render(parser.parse(text));
};
})());
} catch (e) {
console.error('Could not bench commonmark. (Error: %s)', e.message);
}
try {
bench('markdown-it', specs, (() => {
const MarkdownIt = require('markdown-it');
const md = new MarkdownIt();
return md.render.bind(md);
})());
} catch (e) {
console.error('Could not bench markdown-it. (Error: %s)', e.message);
}
try {
bench('markdown.js', specs, (() => {
const md = require('markdown').markdown;
return md.toHTML.bind(md);
})());
} catch (e) {
console.error('Could not bench markdown.js. (Error: %s)', e.message);
}
}
function bench(name, specs, engine) {
const before = process.hrtime();
for (let i = 0; i < 1e3; i++) {
for (const spec of specs) {
engine(spec.markdown);
}
}
const elapsed = process.hrtime(before);
const ms = prettyElapsedTime(elapsed).toFixed();
const results = [];
for (const spec of specs) {
results.push({
expected: spec.html,
actual: engine(spec.markdown)
});
}
const correct = results.reduce((num, result) => num + (htmlDiffer.isEqual(result.expected, result.actual) ? 1 : 0), 0);
const percent = (correct / results.length * 100).toFixed(2);
console.log('%s completed in %sms and passed %s%', name, ms, percent);
}
/**
* A simple one-time benchmark
*/
function time(options) {
options = options || {};
const specs = load();
if (options.marked) {
marked.setOptions(options.marked);
}
bench('marked', specs, marked);
}
/**
* Argument Parsing
*/
function parseArg(argv) {
argv = argv.slice(2);
const options = {};
const orphans = [];
function getarg() {
let arg = argv.shift();
if (arg.indexOf('--') === 0) {
// e.g. --opt
arg = arg.split('=');
if (arg.length > 1) {
// e.g. --opt=val
argv.unshift(arg.slice(1).join('='));
}
arg = arg[0];
} else if (arg[0] === '-') {
if (arg.length > 2) {
// e.g. -abc
argv = arg.substring(1).split('').map(ch => {
return `-${ch}`;
}).concat(argv);
arg = argv.shift();
} else {
// e.g. -a
}
} else {
// e.g. foo
}
return arg;
}
const defaults = marked.getDefaults();
while (argv.length) {
const arg = getarg();
switch (arg) {
case '-t':
case '--time':
options.time = true;
break;
case '-m':
case '--minified':
options.minified = true;
break;
default:
if (arg.indexOf('--') === 0) {
const opt = camelize(arg.replace(/^--(no-)?/, ''));
if (!defaults.hasOwnProperty(opt)) {
continue;
}
options.marked = options.marked || {};
if (arg.indexOf('--no-') === 0) {
options.marked[opt] = typeof defaults[opt] !== 'boolean'
? null
: false;
} else {
options.marked[opt] = typeof defaults[opt] !== 'boolean'
? argv.shift()
: true;
}
} else {
orphans.push(arg);
}
break;
}
}
if (orphans.length > 0) {
console.error();
console.error('The following arguments are not used:');
orphans.forEach(arg => console.error(` ${arg}`));
console.error();
}
return options;
}
/**
* Helpers
*/
function camelize(text) {
return text.replace(/(\w)-(\w)/g, (_, a, b) => a + b.toUpperCase());
}
/**
* Main
*/
function main(argv) {
const opt = parseArg(argv);
if (opt.minified) {
marked = require('../marked.min.js');
}
if (opt.time) {
time(opt);
} else {
runBench(opt);
}
}
/**
* returns time to millisecond granularity
*/
function prettyElapsedTime(hrtimeElapsed) {
const seconds = hrtimeElapsed[0];
const frac = Math.round(hrtimeElapsed[1] / 1e3) / 1e3;
return seconds * 1e3 + frac;
}
if (!module.parent) {
process.title = 'marked bench';
main(process.argv.slice());
} else {
exports = main;
exports.main = main;
exports.time = time;
exports.runBench = runBench;
exports.load = load;
exports.bench = bench;
module.exports = exports;
}
|
JavaScript
| 0 |
@@ -160,16 +160,38 @@
../');%0A%0A
+/**%0A * Load specs%0A */%0A
function
@@ -422,24 +422,54 @@
n specs;%0A%7D%0A%0A
+/**%0A * Run all benchmarks%0A */%0A
function run
|
9acaf319b3b5d83c9a9095faae40e5365f263e92
|
Add sixth benchmark.
|
test/bench.js
|
test/bench.js
|
"use strict";
var Benchmark = require("benchmark");
var test1 = require("./first");
var test2 = require("./second");
var test3 = require("./third");
var test4 = require("./fourth");
var test5 = require("./fifth");
var suite = new Benchmark.Suite("quadprog");
suite
.add("test1", test1)
.add("test2", test2)
.add("test3", test3)
.add("test4", test4)
.add("test5", test5)
.on("cycle", function (event) {
console.log(String(event.target));
})
.run();
|
JavaScript
| 0 |
@@ -208,16 +208,48 @@
fifth%22);
+%0Avar test6 = require(%22./sixth%22);
%0A%0Avar su
@@ -419,16 +419,41 @@
test5)%0A
+ .add(%22test6%22, test6)%0A
.on(
|
df71e638303c274fa0f87551c02231a8ac4469ff
|
Migrate core/events/events_toolbox_item_select.js to named requires
|
core/events/events_toolbox_item_select.js
|
core/events/events_toolbox_item_select.js
|
/**
* @license
* Copyright 2020 Google LLC
* SPDX-License-Identifier: Apache-2.0
*/
/**
* @fileoverview Events fired as a result of selecting an item on the toolbox.
* @author [email protected] (Monica Kozbial)
*/
'use strict';
goog.module('Blockly.Events.ToolboxItemSelect');
goog.module.declareLegacyNamespace();
goog.require('Blockly.Events');
goog.require('Blockly.Events.UiBase');
goog.require('Blockly.registry');
goog.require('Blockly.utils.object');
/**
* Class for a toolbox item select event.
* @param {?string=} opt_oldItem The previously selected toolbox item. Undefined
* for a blank event.
* @param {?string=} opt_newItem The newly selected toolbox item. Undefined for
* a blank event.
* @param {string=} opt_workspaceId The workspace identifier for this event.
* Undefined for a blank event.
* @extends {Blockly.Events.UiBase}
* @constructor
*/
const ToolboxItemSelect = function(opt_oldItem, opt_newItem,
opt_workspaceId) {
ToolboxItemSelect.superClass_.constructor.call(
this, opt_workspaceId);
/**
* The previously selected toolbox item.
* @type {?string|undefined}
*/
this.oldItem = opt_oldItem;
/**
* The newly selected toolbox item.
* @type {?string|undefined}
*/
this.newItem = opt_newItem;
};
Blockly.utils.object.inherits(ToolboxItemSelect, Blockly.Events.UiBase);
/**
* Type of this event.
* @type {string}
*/
ToolboxItemSelect.prototype.type = Blockly.Events.TOOLBOX_ITEM_SELECT;
/**
* Encode the event as JSON.
* @return {!Object} JSON representation.
*/
ToolboxItemSelect.prototype.toJson = function() {
const json = ToolboxItemSelect.superClass_.toJson.call(this);
json['oldItem'] = this.oldItem;
json['newItem'] = this.newItem;
return json;
};
/**
* Decode the JSON event.
* @param {!Object} json JSON representation.
*/
ToolboxItemSelect.prototype.fromJson = function(json) {
ToolboxItemSelect.superClass_.fromJson.call(this, json);
this.oldItem = json['oldItem'];
this.newItem = json['newItem'];
};
Blockly.registry.register(Blockly.registry.Type.EVENT,
Blockly.Events.TOOLBOX_ITEM_SELECT, ToolboxItemSelect);
exports = ToolboxItemSelect;
|
JavaScript
| 0.000001 |
@@ -319,16 +319,31 @@
ace();%0A%0A
+const Events =
goog.req
@@ -362,24 +362,39 @@
y.Events');%0A
+const UiBase =
goog.require
@@ -416,24 +416,39 @@
s.UiBase');%0A
+const object =
goog.require
@@ -457,24 +457,46 @@
Blockly.
+utils.object');%0Aconst
registry
');%0Agoog
@@ -487,20 +487,19 @@
registry
-');%0A
+ =
goog.req
@@ -508,36 +508,32 @@
re('Blockly.
-utils.object
+registry
');%0A%0A%0A/**%0A *
@@ -904,31 +904,16 @@
xtends %7B
-Blockly.Events.
UiBase%7D%0A
@@ -1328,30 +1328,16 @@
tem;%0A%7D;%0A
-Blockly.utils.
object.i
@@ -1363,31 +1363,16 @@
Select,
-Blockly.Events.
UiBase);
@@ -1457,24 +1457,16 @@
.type =
-Blockly.
Events.T
@@ -2033,24 +2033,16 @@
'%5D;%0A%7D;%0A%0A
-Blockly.
registry
@@ -2051,24 +2051,16 @@
egister(
-Blockly.
registry
@@ -2076,24 +2076,16 @@
NT,%0A
-Blockly.
Events.T
|
1550f6c847b3994dd34b3eee700b868380f97bab
|
Add files via upload
|
scriptsb.js
|
scriptsb.js
|
$(document).ready(function(){
$("#menu").bind("mousewheel", function(e){
var curScroll = $("#menu").scrollLeft();
if(e.originalEvent.wheelDelta > 0) {
$("#menu").scrollLeft(curScroll-1936);
} else {
$("#menu").scrollLeft(curScroll+1936);
}
});
$(".scroll").click(function() {
var box = $("#menu"),
x;
if ($(this).hasClass("scrollRight")) {
x = (1936) + box.scrollLeft();
box.animate({
scrollLeft: x,
})
} else {
x = (1936) - box.scrollLeft();
box.animate({
scrollLeft: -x,
})
}
});
$(".system-menu").click(function(){
$("#container").toggleClass("active");
$("#games").fadeToggle(300);
$("#games").toggleClass("active");
console.log("shift!")
});
document.onkeydown = function(e) {
console.log("keypressed!");
var box = $("#menu");
switch (e.keyCode) {
case 37:
console.log("left!");
var x = (1936) - box.scrollLeft();
box.animate({ scrollLeft: -x })
break;
case 39:
console.log("right!");
var x = (1936) + box.scrollLeft();
box.animate({ scrollLeft: x })
break;
case 38:
$("#container").toggleClass("active");
$("#games").fadeToggle(300);
$("#games").toggleClass("active");
break;
case 40:
$("#container").removeClass("active");
$("#games").fadeOut(300);
$("#games").removeClass("active");
break;
}
}
});
|
JavaScript
| 0 |
@@ -741,16 +741,789 @@
%09%7D);%0D%0A%0D%0A
+window.addEventListener(%22keydown%22, (function(canMove) %7B%0D%0A return function(event) %7B%0D%0A if (!canMove) return false;%0D%0A canMove = false;%0D%0A setTimeout(function() %7B canMove = true; %7D, 400);%0D%0A switch (event.keyCode) %7B%0D%0A%09%09case 37:%0D%0A%09%09%09var x = (1936) - $(%22#menu%22).scrollLeft();%0D%0A%09%09%09$(%22#menu%22).animate(%7B scrollLeft: -x %7D)%0D%0A%09%09%09break;%0D%0A %09case 39:%0D%0A%09%09%09var x = (1936) + $(%22#menu%22).scrollLeft();%0D%0A%09%09%09$(%22#menu%22).animate(%7B scrollLeft: +x %7D)%0D%0A%09%09%09break;%0D%0A %09case 38:%0D%0A%09%09%09$(%22#container%22).toggleClass(%22active%22);%0D%0A%09%09%09$(%22#games%22).fadeToggle(300);%0D%0A%09%09%09$(%22#games%22).toggleClass(%22active%22);%0D%0A%09%09%09break;%0D%0A%09%09case 40:%0D%0A%09%09%09$(%22#container%22).removeClass(%22active%22);%0D%0A%09%09%09$(%22#games%22).fadeOut(300);%0D%0A%09%09%09$(%22#games%22).removeClass(%22active%22);%0D%0A%09%09%09break;%09%09%0D%0A %7D %0D%0A %7D;%0D%0A%7D)(true), false);%0D%0A%0D%0A%0D%0A%0D%0A/*%0D%0A
%09documen
@@ -1607,16 +1607,92 @@
enu%22);%0D%0A
+%09%09var canMove = false;%0D%0A%09%09setTimeout(function() %7B canMove = true; %7D, 250);%0D%0A
%09%09switch
@@ -1873,24 +1873,95 @@
%22right!%22);%0D%0A
+%09%09%09%09clearTimeout(scrolling);%0D%0A%09%09%09%09scrolling = setTimeout(function()%7B%0D%0A%09
%09%09%09%09var x =
@@ -1984,32 +1984,33 @@
ollLeft();%0D%0A%09%09%09%09
+%09
box.animate(%7B sc
@@ -2021,24 +2021,36 @@
Left: x %7D)%0D%0A
+%09%09%09%09%7D, x);%0D%0A
%09%09%09%09break;%0D%0A
@@ -2337,15 +2337,17 @@
;%0D%0A%09%09%7D%0D%0A
-
%09%7D
+*/
%0D%0A%7D);
|
eafa49004e5550b45635bf4f51b07e695a9c4de0
|
Add test for circular array references
|
test/index.js
|
test/index.js
|
var test = require('tape');
var hash = require('../index');
var validSha1 = /^[0-9a-f]{40}$/i;
test('throws when nothing to hash', function (assert) {
assert.plan(2);
assert.throws(hash, 'no arguments');
assert.throws(function(){
hash(undefined, {algorithm: 'md5'});
}, 'undefined');
});
test('throws when passed an invalid options', function(assert){
assert.plan(2);
assert.throws(function(){
hash({foo: 'bar'}, {algorithm: 'shalala'});
}, 'bad algorithm');
assert.throws(function(){
hash({foo: 'bar'}, {encoding: 'base16'});
}, 'bad encoding');
});
test('hashes non-object types', function(assert){
assert.plan(4);
var func = function(a){ return a + 1; };
assert.ok(validSha1.test(hash('Shazbot!')), 'hash string');
assert.ok(validSha1.test(hash(42)), 'hash number');
assert.ok(validSha1.test(hash(true)), 'hash bool');
assert.ok(validSha1.test(hash(func)), 'hash function');
});
test('hashes special object types', function(assert){
assert.plan(8);
var dt = new Date();
dt.setDate(dt.getDate() + 1);
assert.ok(validSha1.test(hash([1,2,3,4])), 'hash array');
assert.notEqual(hash([1,2,3,4]), hash([4,3,2,1]), 'different arrays not equal');
assert.ok(validSha1.test(hash(new Date())), 'hash date');
assert.notEqual(hash(new Date()), hash(dt), 'different dates not equal');
assert.ok(validSha1.test(hash(null)), 'hash Null');
assert.ok(validSha1.test(hash(Number.NaN)), 'hash NaN');
assert.ok(validSha1.test(hash({ foo: undefined })), 'hash Undefined value');
assert.ok(validSha1.test(hash(new RegExp())), 'hash regex');
});
test('hashes a simple object', function(assert){
assert.plan(1);
assert.ok(validSha1.test(hash({foo: 'bar', bar: 'baz'})), 'hash object');
});
test('hashes identical objects with different key ordering', function(assert){
assert.plan(2);
var hash1 = hash({foo: 'bar', bar: 'baz'});
var hash2 = hash({bar: 'baz', foo: 'bar'});
var hash3 = hash({bar: 'foo', foo: 'baz'});
assert.equal(hash1, hash2, 'hashes are equal');
assert.notEqual(hash1, hash3, 'different objects not equal');
});
test('only hashes object keys when excludeValues option is set', function(assert){
assert.plan(2);
var hash1 = hash({foo: false, bar: 'OK'}, { excludeValues: true });
var hash2 = hash({foo: true, bar: 'NO'}, { excludeValues: true });
var hash3 = hash({foo: true, bar: 'OK', baz: false}, { excludeValues: true });
assert.equal(hash1, hash2, 'values not in hash digest');
assert.notEqual(hash1, hash3, 'different keys not equal');
});
test('array values are hashed', function(assert){
assert.plan(1);
var hash1 = hash({foo: ['bar', 'baz'], bax: true });
var hash2 = hash({foo: ['baz', 'bar'], bax: true });
assert.notEqual(hash1, hash2, 'different array orders are unique');
});
test('nested object values are hashed', function(assert){
assert.plan(2);
var hash1 = hash({foo: {bar: true, bax: 1}});
var hash2 = hash({foo: {bar: true, bax: 1}});
var hash3 = hash({foo: {bar: false, bax: 1}});
assert.equal(hash1, hash2, 'hashes are equal');
assert.notEqual(hash1, hash3, 'different objects not equal');
});
test('sugar methods should be equivalent', function(assert){
assert.plan(3);
var obj = {foo: 'bar', baz: true};
assert.equal(hash.keys(obj), hash(obj, {excludeValues: true}), 'keys');
assert.equal(hash.MD5(obj), hash(obj, {algorithm: 'md5'}), 'md5');
assert.equal(hash.keysMD5(obj),
hash(obj, {algorithm: 'md5', excludeValues: true}), 'keys md5');
});
test('array of nested object values are hashed', function(assert){
assert.plan(2);
var hash1 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
var hash2 = hash({foo: [ {bar: true, bax: 1}, {bar: false, bax: 2} ] });
var hash3 = hash({foo: [ {bar: false, bax: 2} ] });
assert.equal(hash1, hash2, 'hashes are equal');
assert.notEqual(hash1, hash3, 'different objects not equal');
});
test("recursive objects don't blow up stack", function(assert) {
assert.plan(1);
var hash1 = {foo: 'bar'};
hash1.recursive = hash1;
assert.doesNotThrow(function(){hash(hash1);}, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');
});
test("recursive handling tracks identity", function(assert) {
assert.plan(1);
var hash1 = {k1: {k: 'v'}, k2: {k: 'k2'}};
hash1.k1.r1 = hash1.k1;
hash1.k2.r2 = hash1.k2;
var hash2 = {k1: {k: 'v'}, k2: {k: 'k2'}};
hash2.k1.r1 = hash2.k2;
hash2.k2.r2 = hash2.k1;
assert.notEqual(hash(hash1), hash(hash2), "order of recursive objects should matter");
});
|
JavaScript
| 0 |
@@ -4178,32 +4178,308 @@
ception');%0A%7D);%0A%0A
+test(%22recursive arrays don't blow up stack%22, function(assert) %7B%0A assert.plan(1);%0A var hash1 = %5B'foo', 'bar'%5D;%0A hash1.push(hash1);%0A assert.doesNotThrow(function()%7Bhash(hash1);%7D, /Maximum call stack size exceeded/, 'Should not throw an stack size exceeded exception');%0A%7D);%0A%0A
test(%22recursive
|
da266a691091b5d7819115130c30b6162f258f59
|
Clean up
|
api/controllers/KongServicesController.js
|
api/controllers/KongServicesController.js
|
/**
* SnapshotController
*
* @description :: Server-side logic for managing snapshots
* @help :: See http://sailsjs.org/#!/documentation/concepts/Controllers
*/
var _ = require("lodash");
var KongService = require('../services/KongService');
module.exports = _.merge(_.cloneDeep(require('../base/Controller')), {
listTags: function (req, res) {
sails.models.kongservices.find({
where: {
kong_node_id: req.connection.id
},
select: ['tags']
}, function (err, extras) {
if (err) return res.negotiate(err);
var tags = [];
extras.forEach(function (extra) {
if (extra.tags instanceof Array)
tags = tags.concat(extra.tags);
});
return res.json(_.uniq(tags));
})
},
consumers: async (req,res) => {
const serviceId = req.params.id;
let serviceAclPlugin;
// let serviceJWT;
// let serviceBasicAuth;
// let serviceKeyAuth;
// let serviceOauth2;
// let serviceHMACAuth;
sails.log("KongServiceController:consumers called");
let plugins = await KongService.fetch(`/services/${serviceId}/plugins?enabled=true`, req);
if(plugins.total == 0) return res.json([]);
sails.log("Service plugins =>", plugins);
serviceAclPlugin = _.filter(plugins.data, item => item.name === 'acl')[0];
// serviceJWT = _.filter(plugins.data, item => item.name == 'jwt')[0];
// serviceBasicAuth = _.filter(plugins.data, item => item.name == 'basic-auth')[0];
// serviceKeyAuth = _.filter(plugins.data, item => item.name == 'key-auth')[0];
// serviceOauth2 = _.filter(plugins.data, item => item.name == 'oauth2')[0];
// serviceHMACAuth = _.filter(plugins.data, item => item.name == 'hmac-auth')[0];
sails.log("serviceAclPlugin",serviceAclPlugin)
let aclConsumerIds;
if(serviceAclPlugin) {
// This service is Access Controlled by ACL plugin
let whiteListedGroups = serviceAclPlugin.config.whitelist || [];
let blackListedGroups = serviceAclPlugin.config.blacklist || [];
// ACL
sails.log("whiteListedGroups",whiteListedGroups)
sails.log("blackListedGroups",blackListedGroups)
// We need to retrieve all acls and filter the accessible ones based on the whitelisted and blacklisted groups
let acls = await KongService.fetch(`/acls`, req);
let filteredAcls = _.filter(acls.data, item => {
return whiteListedGroups.indexOf(item.group) > -1 && blackListedGroups.indexOf(item.group) === -1;
});
sails.log("filteredAcls", filteredAcls);
// Gather the consume ids of the filtered groups
aclConsumerIds = _.map(filteredAcls, item => item.consumer_id);
}
let jwts = await KongService.fetch(`/jwts`, req);
let keyAuths = await KongService.fetch(`/key-auths`, req);
let hmacAuths = await KongService.fetch(`/hmac-auths`, req);
let oauth2 = await KongService.fetch(`/oauth2`, req);
let basicAuths = await KongService.fetch(`/basic-auths`, req);
let jwtConsumerIds = _.map(jwts.data, item => item.consumer_id);
let keyAuthConsumerIds = _.map(keyAuths.data, item => item.consumer_id);
let hmacAuthConsumerIds = _.map(hmacAuths.data, item => item.consumer_id);
let oauth2ConsumerIds = _.map(oauth2.data, item => item.consumer_id);
let basicAuthConsumerIds = _.map(basicAuths.data, item => item.consumer_id);
sails.log("jwtConsumerIds",jwtConsumerIds)
sails.log("keyAuthConsumerIds",keyAuthConsumerIds)
sails.log("hmacAuthConsumerIds",hmacAuthConsumerIds)
sails.log("oauth2ConsumerIds",oauth2ConsumerIds)
sails.log("basicAuthConsumerIds",basicAuthConsumerIds)
let consumerIds;
let authenticationPluginsConsumerIds = _.uniq([
...jwtConsumerIds,
...keyAuthConsumerIds,
...hmacAuthConsumerIds,
...oauth2ConsumerIds,
...basicAuthConsumerIds
]);
if(aclConsumerIds) {
sails.log("authenticationPluginsConsumerIds", authenticationPluginsConsumerIds);
sails.log("aclConsumerIds", _.uniq(aclConsumerIds));
consumerIds = _.intersection(_.uniq(aclConsumerIds), authenticationPluginsConsumerIds);
}else{
consumerIds = authenticationPluginsConsumerIds;
}
sails.log("consumerIds => ", consumerIds);
// Fetch all consumers
KongService.listAllCb(req, `/consumers`, (err, consumers) => {
if (err) return res.negotiate(err);
if(!consumers.data || !consumers.data.length) return res.json([]);
let eligibleConsumers = _.filter(consumers.data, item => {
return consumerIds.indexOf(item.id) > -1;
})
return res.json({
total: eligibleConsumers.length,
data: eligibleConsumers
})
})
}
});
|
JavaScript
| 0.000002 |
@@ -859,141 +859,8 @@
in;%0A
- // let serviceJWT;%0A // let serviceBasicAuth;%0A // let serviceKeyAuth;%0A // let serviceOauth2;%0A // let serviceHMACAuth;%0A
%0A%0A
@@ -1189,422 +1189,8 @@
%5B0%5D;
-%0A // serviceJWT = _.filter(plugins.data, item =%3E item.name == 'jwt')%5B0%5D;%0A // serviceBasicAuth = _.filter(plugins.data, item =%3E item.name == 'basic-auth')%5B0%5D;%0A // serviceKeyAuth = _.filter(plugins.data, item =%3E item.name == 'key-auth')%5B0%5D;%0A // serviceOauth2 = _.filter(plugins.data, item =%3E item.name == 'oauth2')%5B0%5D;%0A // serviceHMACAuth = _.filter(plugins.data, item =%3E item.name == 'hmac-auth')%5B0%5D;
%0A%0A
|
661d34ab3797f044eac177b3a812795066a33b14
|
fix type expression for parameter config, it is required, not optional
|
js/Enumeration.js
|
js/Enumeration.js
|
// Copyright 2018-2020, University of Colorado Boulder
/**
* Creates a simple enumeration, with most of the boilerplate.
*
* An Enumeration can be created like this:
*
* const CardinalDirection = Enumeration.byKeys( [ 'NORTH', 'SOUTH', 'EAST', 'WEST' ] );
*
* OR using rich values like so:
*
* const CardinalDirection = Enumeration.byMap( {NORTH: northObject, SOUTH: southObject, EAST: eastObject, WEST: westObject} );
*
* and values are referenced like this:
*
* CardinalDirection.NORTH;
* CardinalDirection.SOUTH;
* CardinalDirection.EAST;
* CardinalDirection.WEST;
*
* CardinalDirection.VALUES;
* // returns [ CardinalDirection.NORTH, CardinalDirection.SOUTH, CardinalDirection.EAST, CardinalDirection.WEST ]
*
* And support for checking whether any value is a value of the enumeration:
*
* CardinalDirection.includes( CardinalDirection.NORTH ); // true
* CardinalDirection.includes( CardinalDirection.SOUTHWEST ); // false
* CardinalDirection.includes( 'NORTH' ); // false, values are not strings
*
* Conventions for using Enumeration, from https://github.com/phetsims/phet-core/issues/53:
*
* (1) Enumerations are named like classes/types. Nothing in the name needs to identify that they are Enumerations.
* See the example above: CardinalDirection, not CardinalDirectionEnum or CardinalDirectionEnumeration.
*
* (2) Enumeration values are named like constants, using uppercase. See the example above.
*
* (3) If an Enumeration is closely related to some class, then make it a static field of that class. If an
* Enumeration is specific to a Property, then the Enumeration should likely be owned by the class that
* owns that Property.
*
* (4) If an Enumeration is not closely related to some class, then put the Enumeration in its own .js file.
* Do not combine multiple Enumerations into one file.
*
* (5) If a Property takes an Enumeration value, its validation typically looks like this:
*
* const cardinalDirectionProperty = new Property( CardinalDirection.NORTH, {
* validValues: CardinalDirection.VALUES
* }
*
* (6) Values of the Enumeration are considered instances of the Enumeration in documentation. For example, a method
* that that takes an Enumeration value as an argument would be documented like this:
*
* // @param {Scene} mode - value from Scene Enumeration
* setSceneMode( mode ) {
* assert && assert( Scene.includes( mode ) );
* //...
* }
*
* @author Jonathan Olson <[email protected]>
*/
define( require => {
'use strict';
// modules
const merge = require( 'PHET_CORE/merge' );
const phetCore = require( 'PHET_CORE/phetCore' );
class Enumeration {
/**
* @param {Object} [config] - must provide keys such as {keys:['RED','BLUE]}
* - or map such as {map:{RED: myRedValue, BLUE: myBlueValue}}
*
* @private - clients should use Enumeration.byKeys or Enumeration.byMap
*/
constructor( config ) {
assert && assert( config, 'config must be provided' );
const keysProvided = !!config.keys;
const mapProvided = !!config.map;
assert && assert( keysProvided !== mapProvided, 'must provide one or the other but not both of keys/map' );
const keys = config.keys || Object.keys( config.map );
const map = config.map || {};
config = merge( {
// {string|null} Will be appended to the EnumerationIO documentation, if provided
phetioDocumentation: null,
// {function(Enumeration):|null} If provided, it will be called as beforeFreeze( enumeration ) just before the
// enumeration is frozen. Since it's not possible to modify the enumeration after
// it is frozen (e.g. adding convenience functions), and there is no reference to
// the enumeration object beforehand, this allows defining custom values/methods
// on the enumeration object itself.
beforeFreeze: null
}, config );
assert && assert( Array.isArray( keys ), 'Values should be an array' );
assert && assert( _.uniq( keys ).length === keys.length, 'There should be no duplicated values provided' );
assert && keys.forEach( value => assert( typeof value === 'string', 'Each value should be a string' ) );
assert && keys.forEach( value => assert( /^[A-Z][A-Z0-9_]*$/g.test( value ),
'Enumeration values should be uppercase alphanumeric with underscores and begin with a letter' ) );
assert && assert( !_.includes( keys, 'VALUES' ),
'This is the name of a built-in provided value, so it cannot be included as an enumeration value' );
assert && assert( !_.includes( keys, 'KEYS' ),
'This is the name of a built-in provided value, so it cannot be included as an enumeration value' );
assert && assert( !_.includes( keys, 'includes' ),
'This is the name of a built-in provided value, so it cannot be included as an enumeration value' );
// @public (phet-io) - provides additional documentation for PhET-iO which can be viewed in studio
// Note this uses the same term as used by PhetioObject, but via a different channel.
this.phetioDocumentation = config.phetioDocumentation;
// @public {string[]} (read-only) - the string keys of the enumeration
this.KEYS = keys;
// @public {Object[]} (read-only) - the object values of the enumeration
this.VALUES = [];
keys.forEach( key => {
const value = map[ key ] || {};
// Set attributes of the enumeration value
assert && assert( value.name === undefined, 'rich enumeration values cannot provide their own name attribute' );
assert && assert( value.toString === Object.prototype.toString, 'rich enumeration values cannot provide their own toString' );
value.name = key; // PhET-iO public API relies on this mapping, do not change it lightly
value.toString = () => key;
// Assign to the enumeration
this[ key ] = value;
this.VALUES.push( value );
} );
config.beforeFreeze && config.beforeFreeze( this );
assert && Object.freeze( this );
assert && Object.freeze( this.VALUES );
assert && Object.freeze( this.KEYS );
assert && keys.forEach( key => assert && Object.freeze( map[ key ] ) );
}
/**
* Checks whether the given value is a value of this enumeration. Should generally be used for assertions
* @public
*
* @param {Object} value
* @returns {boolean}
*/
includes( value ) {
return _.includes( this.VALUES, value );
}
/**
* Creates an enumeration based on the provided string array
* @param {string[]} keys - such as ['RED','BLUE']
* @param {Object} [options]
* @returns {Enumeration}
* @public
*/
static byKeys( keys, options ) {
assert && assert( !options || options.keys === undefined );
return new Enumeration( merge( { keys: keys }, options ) );
}
/**
* Creates a "rich" enumeration based on the provided map
* @param {Object} map - such as {RED: myRedValue, BLUE: myBlueValue}
* @param {Object} [options]
* @returns {Enumeration}
* @public
*/
static byMap( map, options ) {
assert && assert( !options || options.map === undefined );
if ( assert ) {
const values = _.values( map );
assert && assert( values.length >= 1, 'must have at least 2 entries in an enumeration' );
assert && assert( _.every( values, value => value.constructor === values[ 0 ].constructor ), 'Values must have same constructor' );
}
return new Enumeration( merge( { map: map }, options ) );
}
}
return phetCore.register( 'Enumeration', Enumeration );
} );
|
JavaScript
| 0 |
@@ -2763,16 +2763,14 @@
ct%7D
-%5B
config
-%5D
- m
|
f8561665b45456d7e3d29447c739ae64cb9cb26b
|
add TODO item for #199
|
js/PageControl.js
|
js/PageControl.js
|
// Copyright 2002-2015, University of Colorado Boulder
/**
* An iOS-style page control. See the 'Navigation' section of the iOS Human Interface Guidelines.
* A page control indicates the number of pages and which one is currently visible.
*
* @author Chris Malley (PixelZoom, Inc.)
*/
define( function( require ) {
'use strict';
// modules
var Circle = require( 'SCENERY/nodes/Circle' );
var DownUpListener = require( 'SCENERY/input/DownUpListener' );
var inherit = require( 'PHET_CORE/inherit' );
var Node = require( 'SCENERY/nodes/Node' );
/**
* @param {number} numberOfPages - number of pages
* @param {Property<number>} pageNumberProperty - which page is currently visible
* @param {Object} [options]
* @constructor
*/
function PageControl( numberOfPages, pageNumberProperty, options ) {
options = _.extend( {
// all dots
orientation: 'horizontal',
dotRadius: 3, // {number} radius of the dots
lineWidth: 1,
dotSpacing: 10, // {number} spacing between dots
interactive: false, // {boolean} whether the control is interactive
// dots representing the current page
currentPageFill: 'black', // {Color|string} dot color for the page that is visible
currentPageStroke: null,
// dots representing all pages except the current page
pageFill: 'rgb( 200, 200, 200 )', // {Color|string} dot color for pages that are not visible
pageStroke: null
}, options );
// validate options
assert && assert( _.contains( [ 'horizontal', 'vertical' ], options.orientation ), 'invalid orientation=' + options.orientation );
// To improve readability
var isHorizontal = ( options.orientation === 'horizontal' );
// Clicking on a dot goes to that page
var dotListener = new DownUpListener( {
down: function( event ) {
assert && assert( event.currentTarget.hasOwnProperty( 'pageNumber' ) );
pageNumberProperty.set( event.currentTarget.pageNumber );
}
} );
// Create a dot for each page.
// Add them to an intermediate parent node, so that additional children can't be inadvertently added.
// For horizontal orientation, pages are ordered left-to-right.
// For vertical orientation, pages are ordered top-to-bottom.
var dotsParent = new Node();
for ( var pageNumber = 0; pageNumber < numberOfPages; pageNumber++ ) {
// dot
var dotCenter = ( pageNumber * ( 2 * options.dotRadius + options.dotSpacing ) );
var dotNode = new DotNode( pageNumber, options.dotRadius, {
fill: options.pageFill,
stroke: options.pageStroke,
lineWidth: options.lineWidth,
x: isHorizontal ? dotCenter : 0,
y: isHorizontal ? 0 : dotCenter
} );
dotsParent.addChild( dotNode );
// optional interactivity
if ( options.interactive ) {
dotNode.cursor = 'pointer';
dotNode.addInputListener( dotListener );
}
}
// Indicate which page is selected
var pageNumberObserver = function( pageNumber, oldPageNumber ) {
// previous dot
if ( oldPageNumber || oldPageNumber === 0 ) {
dotsParent.getChildAt( oldPageNumber ).fill = options.pageFill;
dotsParent.getChildAt( oldPageNumber ).stroke = options.pageStroke;
}
// current dot
dotsParent.getChildAt( pageNumber ).fill = options.currentPageFill;
dotsParent.getChildAt( pageNumber ).stroke = options.currentPageStroke;
};
pageNumberProperty.link( pageNumberObserver );
// @private
this.disposePageControl = function() {
pageNumberProperty.unlink( pageNumberObserver );
};
options.children = [ dotsParent ];
Node.call( this, options );
}
/**
* @param {number} pageNumber - page number that the dot is associated with
* @param {number} radius
* @param {Object} [options]
* @constructor
*/
function DotNode( pageNumber, radius, options ) {
this.pageNumber = pageNumber; // @public (read-only)
Circle.call( this, radius, options );
}
inherit( Circle, DotNode );
return inherit( Node, PageControl, {
// @public
dispose: function() { this.disposePageControl(); }
} );
} );
|
JavaScript
| 0 |
@@ -848,24 +848,200 @@
.extend( %7B%0A%0A
+ //TODO support multiple types of interactivity? see https://github.com/phetsims/sun/issues/199%0A interactive: false, // %7Bboolean%7D whether the control is interactive%0A%0A
// all
@@ -1208,82 +1208,8 @@
dots
-%0A interactive: false, // %7Bboolean%7D whether the control is interactive
%0A%0A
|
97a08730c18418269c4c68443bf1f6c4a55880d6
|
Update tests
|
test/index.js
|
test/index.js
|
var request = require('supertest');
describe('Routes', function () {
var server;
beforeEach(function () {
delete require.cache[require.resolve('../server')];
server = require('../server').listen(3000);
});
afterEach(function (done) {
server.close(done);
});
it('/ responds with html', function (done) {
request(server)
.get('/')
.set('Accept', 'text/html')
.expect('Content-Type', /html/)
.expect(200, done);
});
it('/* responds with json', function (done) {
request(server)
.get('/123456')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200, done);
});
});
|
JavaScript
| 0.000001 |
@@ -28,16 +28,28 @@
rtest');
+%0Avar server;
%0A%0Adescri
@@ -79,34 +79,16 @@
) %7B%0A
- var server;%0A
before
Each
@@ -83,20 +83,16 @@
before
-Each
(functio
@@ -102,68 +102,8 @@
) %7B%0A
- delete require.cache%5Brequire.resolve('../server')%5D;%0A
@@ -152,27 +152,20 @@
;%0A
-
-
%7D);%0A
-
+%0A
after
-Each
(fun
@@ -167,34 +167,28 @@
r(function (
-done
) %7B%0A
-
server.c
@@ -196,25 +196,18 @@
ose(
-done
);%0A
-
%7D);%0A
-
+%0A
it
@@ -241,34 +241,32 @@
nction (done) %7B%0A
-
request(serv
@@ -271,26 +271,24 @@
rver)%0A
-
.get('/')%0A
@@ -285,18 +285,16 @@
et('/')%0A
-
.s
@@ -317,34 +317,32 @@
xt/html')%0A
-
.expect('Content
@@ -357,18 +357,16 @@
/html/)%0A
-
.e
@@ -387,19 +387,15 @@
e);%0A
-
%7D);%0A%0A
-
it
@@ -442,18 +442,16 @@
) %7B%0A
-
request(
@@ -454,26 +454,24 @@
est(server)%0A
-
.get('
@@ -482,26 +482,24 @@
456')%0A
-
.set('Accept
@@ -521,18 +521,16 @@
/json')%0A
-
.e
@@ -561,26 +561,24 @@
son/)%0A
-
.expect(200,
@@ -585,18 +585,16 @@
done);%0A
-
%7D);%0A%7D)
|
6bbbf257c1429c5ecea21dac5611e89205471d6b
|
add tests for empty text and uppercase selectors
|
test/index.js
|
test/index.js
|
import assert from 'assert'
import { jsdom } from 'jsdom'
import d from '../domator'
const document = jsdom()
d.setDocument(document)
describe('coding style', function () {
this.timeout(5000)
it('conforms to standard', require('mocha-standard'))
})
describe('domator', function () {
it('should create a `div` element', function () {
// with domator
const element = d('div')
// with document
const expected = document.createElement('div')
assert(expected.isEqualNode(element))
})
it('should create a `div` element with class and id attrs', function () {
// with domator
const element = d('#the-id.the-class')
// with document
const expected = document.createElement('div')
expected.id = 'the-id'
expected.classList.add('the-class')
assert(expected.isEqualNode(element))
})
it('should create a `div` with custom attrs', function () {
// with domator
const element = d('div[data-custom="some-value"][data-custom2="other-value"]')
// with document
const expected = document.createElement('div')
expected.setAttribute('data-custom', 'some-value')
expected.setAttribute('data-custom2', 'other-value')
assert(expected.isEqualNode(element))
})
it('should create a `div` with the text "Hello World!".', function () {
// with domator
const element = d('div Hello World!')
// with document
const expected = document.createElement('div')
expected.textContent = 'Hello World!'
assert(expected.isEqualNode(element))
})
it('should create a `div` with attributes setted from an object.', function () {
const attrs = {
src: 'http://google.com',
title: 'Title content'
}
// with domator
const element = d('div', attrs)
// with document
const expected = document.createElement('div')
expected.setAttribute('src', attrs.src)
expected.setAttribute('title', attrs.title)
assert(expected.isEqualNode(element))
})
it('should create a `div` with two `span` siblings', function () {
// with domator
const element = d('div', ['span', 'span'])
// with document
const expected = document.createElement('div')
expected.appendChild(document.createElement('span'))
expected.appendChild(document.createElement('span'))
assert(expected.isEqualNode(element))
})
it('should create a `documentFragment` with 3 `div` siblings.', function () {
// with domator
const element = d('div', 'div', 'div')
// with document
const expected = document.createDocumentFragment()
expected.appendChild(document.createElement('div'))
expected.appendChild(document.createElement('div'))
expected.appendChild(document.createElement('div'))
assert(expected.isEqualNode(element))
})
it('should join classes from the selector and attributes.', function () {
// with domator
const element = d('div.two', {
'class': 'one',
className: 'three'
})
// with document
const expected = document.createElement('div')
expected.classList.add('one')
expected.classList.add('two')
expected.classList.add('three')
assert(expected.isEqualNode(element))
})
it('should set attributes to an existing element.', function () {
// with domator
const element = d(document.createElement('div'), {
id: 'some-id'
})
// with document
const expected = document.createElement('div')
expected.id = 'some-id'
assert(expected.isEqualNode(element))
})
})
|
JavaScript
| 0.000003 |
@@ -3467,16 +3467,932 @@
me-id'%0A%0A
+ assert(expected.isEqualNode(element))%0A %7D)%0A%0A it('should allow empty text string to be supplied', function () %7B%0A // with domator shorthand%0A const shorthandElement = d('div ')%0A // with domator text attr%0A const attrElement = d('div', %7B text: '' %7D)%0A%0A // with document%0A const expected = document.createElement('div')%0A%0A assert(expected.isEqualNode(shorthandElement))%0A assert(expected.isEqualNode(attrElement))%0A %7D)%0A%0A it('should allow uppercase characters in selector strings', function () %7B%0A // with domator%0A const id = 'someId'%0A const className = 'someClass'%0A const attr = %5B'attrName', 'attrValue'%5D%0A const template = %60div#$%7Bid%7D.$%7BclassName%7D%5B$%7Battr%5B0%5D%7D=%22$%7Battr%5B1%5D%7D%22%5D%60%0A const element = d(template)%0A%0A // with document%0A const expected = document.createElement('div')%0A expected.id = id%0A expected.classList.add(className)%0A expected.setAttribute(attr%5B0%5D, attr%5B1%5D)%0A%0A
asse
|
d840cc40d5b74e3980bbc21426ffbcc6123aa818
|
whitelist globals
|
test/index.js
|
test/index.js
|
var env = require('./support/env');
require('./engine.io-client');
require('./util');
require('./parser');
require('./socket');
require('./transport');
// browser only tests
if (env.browser) {
require('./connection');
}
|
JavaScript
| 0.000061 |
@@ -30,16 +30,266 @@
env');%0A%0A
+// whitelist some globals to avoid warnings%0Aglobal.__eio = null;%0Aglobal.WEB_SOCKET_LOGGER = null;%0Aglobal.WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = null;%0Aglobal.WEB_SOCKET_DISABLE_AUTO_INITIALIZATION = null;%0Aglobal.WEB_SOCKET_SWF_LOCATION = null;%0A%0A
require(
|
38c6cf347ca60e6051b82363ff711a18f18d2ee0
|
Add test for failing imports.
|
test/index.js
|
test/index.js
|
import path from 'path';
import test from 'ava';
import Vinyl from 'vinyl';
import Plugin from '../';
test('Accept Vinyl as parameter, resolve his id and load his contents.', t => {
var file = new Vinyl({
path: path.resolve('src/fake.js'),
contents: new Buffer('fake')
});
var unixPath = Plugin.unix(file.path);
var plugin = Plugin(file);
var id = plugin.resolveId(unixPath);
t.true(id === unixPath);
t.true(plugin.load(id) === file.contents.toString());
});
test('Accept array as parameters, resolve ids, load contents and resolve relative import', t => {
var fake1 = new Vinyl({
base: path.resolve('src'),
path: path.resolve('src/fake.js'),
contents: new Buffer('fake1')
});
var unixPath1 = Plugin.unix(fake1.path);
var fake2 = new Vinyl({
base: path.resolve('src'),
path: path.resolve('src/lib/import.js'),
contents: new Buffer('fake2')
});
var unixPath2 = Plugin.unix(fake2.path);
var plugin = Plugin([fake1, fake2]);
var id1 = plugin.resolveId(unixPath1);
var id2 = plugin.resolveId(unixPath2);
t.true(plugin.resolveId(id1) === unixPath1);
t.true(plugin.load(id1) === fake1.contents.toString());
t.true(plugin.resolveId(id2) === unixPath2);
t.true(plugin.load(id2) === fake2.contents.toString());
var relativeId = plugin.resolveId(Plugin.unix(fake2.relative), id1);
t.true(relativeId === Plugin.unix(fake2.path));
t.true(plugin.load(relativeId) === fake2.contents.toString());
});
test('Should import from non-vinyl file', t => {
var fake = new Vinyl({
base: path.resolve('src'),
path: path.resolve('src/lib/fake.js'),
contents: new Buffer('fake')
});
var plugin = Plugin(fake);
var filePath = path.resolve('src/main.js');
var id = plugin.resolveId(fake.relative, filePath);
t.true(id === Plugin.unix(fake.path));
});
|
JavaScript
| 0 |
@@ -1835,16 +1835,474 @@
ake.path));%0A%0A%7D);
+%0A%0A%0Atest('Should not resolve id and not load on wrong import', t =%3E %7B%0A%0A var fake = new Vinyl(%7B%0A base: path.resolve('src'),%0A path: path.resolve('src/lib/fake.js'),%0A contents: new Buffer('fake')%0A %7D);%0A%0A var plugin = Plugin(fake);%0A%0A var filePath = path.resolve('src/main.js');%0A var wrongId = 'src/lib/fail.js';%0A%0A var id = plugin.resolveId(wrongId, filePath);%0A%0A t.false(id === Plugin.unix(fake.path));%0A t.true(null === plugin.load(wrongId));%0A%0A%7D);
|
f5c05b847c30c7c8f4bbff58342efdcf8df28f73
|
Make assertions more verbose by avoiding the use of "every" in tests
|
test/index.js
|
test/index.js
|
var assert = require('assert');
var ghlint = require('../index');
describe('ghlint', function () {
describe('.linters', function () {
it('has multiple linters', function () {
assert(ghlint.linters.length > 1);
});
it('has linters with a String message', function () {
assert(ghlint.linters.every(function (linter) {
return linter.message && typeof linter.message === 'string';
}));
});
it('has linters with a lint function', function () {
assert(ghlint.linters.every(function (linter) {
return linter.lint && typeof linter.lint === 'function';
}));
});
});
describe('.lintRepo()', function () {
context('with a real repo', function () {
it('passes valid Results', function (done) {
ghlint.lintRepo('nicolasmccurdy', 'ghlint', function (error, results) {
assert.ifError(error);
assert(results.length > 1);
assert(results.every(function (result) {
return result.message &&
typeof result.message === 'string' &&
typeof result.result === 'boolean';
}));
done();
});
});
});
context('with a fake repo', function () {
it('passes a "Not Found" error', function (done) {
ghlint.lintRepo('nicolasmccurdy', 'qwertyuiop', function (error) {
assert(error);
assert.equal(error.message, 'Not Found');
done();
});
});
});
context('with a fake owner', function () {
it('passes a "Not Found" error', function (done) {
ghlint.lintRepo('login', 'repo', function (error) {
assert(error);
assert.equal(error.message, 'Not Found');
done();
});
});
});
});
describe('.lintReposByOwner()', function () {
context('with a real owner', function () {
it('passes valid RepoResults', function (done) {
this.timeout(10000);
ghlint.lintReposByOwner('nicolasmccurdy', function (error, repoResults) {
assert.ifError(error);
assert(repoResults.length > 1);
assert(repoResults.every(function (result) {
return typeof result.owner === 'string' &&
typeof result.name === 'string' &&
typeof result.results === 'object' &&
result.results.length;
}));
done();
});
});
});
context('with a fake user', function () {
it('passes a "Not Found" error', function (done) {
ghlint.lintReposByOwner('login', function (error) {
assert(error);
assert.equal(error.message, 'Not Found');
done();
});
});
});
});
});
|
JavaScript
| 0.998498 |
@@ -281,39 +281,32 @@
tion () %7B%0A
-assert(
ghlint.linters.e
@@ -296,37 +296,39 @@
ghlint.linters.
-every
+forEach
(function (linte
@@ -336,31 +336,31 @@
) %7B%0A
-return
+assert(
linter.messa
@@ -361,20 +361,40 @@
.message
- &&
+);%0A assert.equal(
typeof l
@@ -398,36 +398,33 @@
f linter.message
- ===
+,
'string';%0A
@@ -416,16 +416,17 @@
'string'
+)
;%0A
@@ -419,33 +419,32 @@
ring');%0A %7D)
-)
;%0A %7D);%0A%0A i
@@ -493,39 +493,32 @@
tion () %7B%0A
-assert(
ghlint.linters.e
@@ -516,21 +516,23 @@
linters.
-every
+forEach
(functio
@@ -552,23 +552,23 @@
-return
+assert(
linter.l
@@ -574,12 +574,32 @@
lint
- &&
+);%0A assert.equal(
type
@@ -612,20 +612,17 @@
ter.lint
- ===
+,
'functi
@@ -624,16 +624,17 @@
unction'
+)
;%0A
@@ -631,25 +631,24 @@
');%0A %7D)
-)
;%0A %7D);%0A
@@ -950,31 +950,24 @@
-assert(
results.
every(fu
@@ -954,29 +954,31 @@
results.
-every
+forEach
(function (r
@@ -998,23 +998,23 @@
-return
+assert(
result.m
@@ -1019,19 +1019,18 @@
.message
- &&
+);
%0A
@@ -1026,39 +1026,39 @@
e);%0A
-
+assert(
typeof result.me
@@ -1062,20 +1062,17 @@
.message
- ===
+,
'string
@@ -1064,38 +1064,35 @@
essage, 'string'
- &&%0A
+);%0A
@@ -1079,37 +1079,39 @@
');%0A
-
+assert(
typeof result.re
@@ -1114,20 +1114,17 @@
t.result
- ===
+,
'boolea
@@ -1125,16 +1125,17 @@
boolean'
+)
;%0A
@@ -1132,33 +1132,32 @@
');%0A %7D)
-)
;%0A done
@@ -2130,39 +2130,32 @@
%3E 1);%0A
-assert(
repoResults.ever
@@ -2154,13 +2154,15 @@
lts.
-every
+forEach
(fun
@@ -2194,15 +2194,15 @@
-return
+assert(
type
@@ -2216,20 +2216,17 @@
lt.owner
- ===
+,
'string
@@ -2218,35 +2218,34 @@
.owner, 'string'
- &&
+);
%0A
@@ -2233,39 +2233,39 @@
');%0A
-
+assert(
typeof result.na
@@ -2266,20 +2266,17 @@
ult.name
- ===
+,
'string
@@ -2276,19 +2276,18 @@
'string'
- &&
+);
%0A
@@ -2291,23 +2291,23 @@
-
+assert(
typeof r
@@ -2323,12 +2323,9 @@
ults
- ===
+,
'ob
@@ -2333,11 +2333,10 @@
ect'
- &&
+);
%0A
@@ -2344,23 +2344,23 @@
-
+assert(
result.r
@@ -2372,16 +2372,17 @@
s.length
+)
;%0A
@@ -2387,17 +2387,16 @@
%7D)
-)
;%0A
|
013ba5979b8f2e9496e51136ec1a6dc52b05bd72
|
fix style errors in test file
|
test/index.js
|
test/index.js
|
/*
* Test the loader
*/
var _ = require('underscore'),
expect = require('expect.js'),
oconf = require('../lib/index'),
path = require('path');
// Helper - resolve files relative to this dir, not vows's CWD.
function resolve(filename) {
return path.resolve(__dirname, filename);
}
// The tests!
describe('Basic tests', function () {
describe('base.cjson', function () {
var data;
before(function () {
data = oconf.load(resolve('./files/base.cjson'));
});
it('Has foo = "overwrite this"', function () {
expect(data).to.have.property('foo', 'overwrite this');
})
it('Has what = "this is from default.cjson."', function () {
expect(data).to.have.property('what', 'this is from default.cjson.');
});
it('Only has "foo" and "what"-keys', function () {
expect(data).to.only.have.keys(['foo', 'what']);
});
});
describe('extend-base.cjson', function () {
var data;
before(function () {
data = oconf.load(resolve('./files/extend-base.cjson'));
});
it('Has foo = "bar" (i.e. overwritten)', function () {
expect(data).to.have.property('foo', 'bar');
})
it('Has what = "this is from default.cjson."', function () {
expect(data).to.have.property('what', 'this is from default.cjson.');
});
it('Only has "foo" and "what"-keys', function () {
expect(data).to.only.have.keys(['foo', 'what']);
});
});
/*
}).addBatch({
'extend-in-subobject.cjson': {
'subobject = `contents of extend-base.cjson`': function (res) {
assert.deepEqual(
res.subobject,
{
foo: "bar",
what: "this is from default.cjson."
}
);
}
}
*/
describe('extend-in-subobject.cjson', function () {
var data;
before(function () {
data = oconf.load(resolve('./files/extend-in-subobject.cjson'));
});
it('Has subobject = contents of extend-base.cjson', function () {
expect(data)
.to.have.property('subobject')
.eql({ foo: 'bar', what: 'this is from default.cjson.' });
})
});
describe('loop1.cjson / loop2.cjson', function () {
it('Loading loop1.cjson throws error', function () {
expect(function () { loader(resolve('./files/loop1.cjson')); })
.to.throwError();
});
it('Loading loop2.cjson throws error', function () {
expect(function () { loader(resolve('./files/loop2.cjson')); })
.to.throwError();
});
});
describe('includeNonExistentFile.cjson', function () {
it('should throw an error when nonExistentFile.cjson is not ignored', function () {
expect(function () {
oconf.load(resolve('./files/includeNonExistentFile.cjson'));
}).to.throwError();
});
it('should not throw an error when nonExistentFile.cjson is ignored', function () {
expect(function () {
oconf.load(resolve('./files/includeNonExistentFile.cjson'), {ignore: resolve('./files/nonExistentFile.cjson')});
}).not.to.throwError();
});
});
});
|
JavaScript
| 0.000001 |
@@ -1,65 +1,66 @@
/*
-%0A * Test the loader%0A */%0A%0Avar _ = require('underscore'),%0A
+global describe, it, before*/%0A/*%0A * Test the loader%0A */%0A%0Avar
exp
@@ -637,32 +637,33 @@
is');%0A %7D)
+;
%0A%0A it('Ha
@@ -1262,16 +1262,17 @@
%7D)
+;
%0A%0A
@@ -2349,16 +2349,17 @@
%7D)
+;
%0A %7D);
|
e601d80819a452ba4db88c3727591fa7ce5fb63c
|
Add more test
|
test/index.js
|
test/index.js
|
var should = require('chai').should();
var util = require('util');
var bot;
before(function (done) {
var events;
var Event = require('./fixtures/models').Event;
new Event({
adapters: {
memory: require('sails-memory')
}
}, function (err, coll) {
should.not.exist(err);
events = coll;
events.createEach([
{name: 'party'},
{name: 'opening'}
]).then(function () {
bot = require('..')(events);
done();
}).fail(function (err) {
done(err);
});
});
});
describe('webot-chat-wall', function() {
it('should be a webot', function() {
bot.should.to.be.instanceof(require('webot').Webot);
});
});
describe('rules', function () {
function reply(info, callback) {
if (typeof info === 'string') {
info = {text: info};
}
if (!info.session) {
info.session = {};
}
bot.reply(info, callback);
}
it('should return help message', function (done) {
reply('help', function (err, info) {
should.not.exist(err);
should.exist(info.reply);
done();
});
});
describe('join event', function () {
var info = {};
it('should join event', function (done) {
info.text = 'join party';
reply(info, function (err, info) {
should.not.exist(err);
info.reply.should.equal('Welcome to "party"');
done();
});
});
it('should acknowledge message', function (done) {
info.text = 'hello';
reply(info, function (err, info) {
should.not.exist(err);
info.reply.should.equal('[party] copy');
done();
});
});
});
it('should prompt error', function (done) {
reply('join not existing', function (err, info) {
should.not.exist(err);
info.reply.should.equal('No such event "not existing"');
done();
});
});
});
|
JavaScript
| 0 |
@@ -1616,19 +1616,474 @@
%7D);%0A
-%7D);
+ it('should continue chat', function (done) %7B%0A info.text = 'hello again';%0A reply(info, function (err, info) %7B%0A should.not.exist(err);%0A info.reply.should.equal('%5Bparty%5D copy');%0A done();%0A %7D);%0A %7D);%0A it('should exit chat', function (done) %7B%0A info.text = 'exit';%0A reply(info, function (err, info) %7B%0A should.not.exist(err);%0A info.reply.should.equal('bye');%0A done();%0A %7D);%0A %7D);%0A %7D);%0A
%0A it('s
|
e6bd8659dceace5fa9e4b171db6116bc853af981
|
Add a selectedItem function
|
Public/Support/Components/Popup/Popup.js
|
Public/Support/Components/Popup/Popup.js
|
function ComponentPopup( id ) {
var self = _ComponentFormSelect(id);
self._requiresSelection = true;
self.setMultiple(false);
self.updateSelected();
return self;
}
|
JavaScript
| 0.000002 |
@@ -146,16 +146,127 @@
cted();%0A
+%09%0A%09self.selectedItem = function() %7B%0A%09%09var selected = self.getState('selected.list');%0A%09%09return selected%5B0%5D;%0A%09%7D;%0A
%09return
|
54dfdfa1b4f9296d90d0476dd1e1877cb6dbed7e
|
Fix loading screen on epic loading
|
app/assets/javascripts/views/epic_view.js
|
app/assets/javascripts/views/epic_view.js
|
if (typeof Fulcrum == 'undefined') {
Fulcrum = {};
}
Fulcrum.EpicView = Backbone.View.extend({
initialize: function(options) {
this.options = options;
$('td.epic_column').css('display', 'table-cell');
this.doSearch();
},
render: function() {
this.$el.html(this.options.columnView.name());
this.setClassName();
return this;
},
addStory: function(story, column) {
var view = new Fulcrum.StoryView({model: story}).render();
this.appendViewToColumn(view, column);
view.setFocus();
},
appendViewToColumn: function(view, columnName) {
$(columnName).append(view.el);
},
addAll: function() {
$(".loading_screen").show();
var that = this;
$('#epic').html("");
$('td.epic_column').show();
var search_results_ids = this.model.search.pluck("id");
var stories = this.model.stories;
_.each(search_results_ids, function(id) {
that.addStory(stories.get(id), '#epic');
});
$(".loading_screen").hide();
},
doSearch: function(e) {
var that = this;
this.model.search.fetch({
reset: true,
data: {
label: this.options.label
},
success: function() {
that.addAll();
},
error: function(e) {
window.projectView.notice({
title: 'Search Error',
text: e
});
}
});
},
});
|
JavaScript
| 0.000001 |
@@ -646,41 +646,8 @@
) %7B%0A
- $(%22.loading_screen%22).show();%0A
@@ -983,24 +983,57 @@
nction(e) %7B%0A
+ $(%22.loading_screen%22).show();%0A
var that
|
515e652a92b951fb0534eae3dc4850ed9e25f384
|
Improve tests
|
test/index.js
|
test/index.js
|
'use strict';
var deferred = require('deferred')
, resolve = require('path').resolve
, rmdir = require('fs2/rmdir')
, Database = require('dbjs')
, Event = require('dbjs/_setup/event')
, dbPath = resolve(__dirname, 'test-db')
, dbCopyPath = resolve(__dirname, 'test-db-copy');
require('leveldown');
module.exports = function (t, a, d) {
var db = new Database()
, driver = t(db, { path: dbPath })
, aaa = db.Object.newNamed('aaa')
, bar = db.Object.newNamed('bar')
, foo = db.Object.newNamed('foo')
, zzz = db.Object.newNamed('zzz');
db.Object.prototype.defineProperties({
bar: { value: 'elo' },
computed: { value: function () {
return 'foo' + this.bar;
} },
computedSet: { value: function () {
return [this.bar, this.computed];
}, multiple: true }
});
driver.trackComputed(db.Object, 'computed');
driver.trackComputed(db.Object, 'computedSet');
deferred(
driver.storeEvent(zzz._lastOwnEvent_),
driver.storeEvent(bar._lastOwnEvent_),
driver.storeEvent(foo._lastOwnEvent_),
driver.storeEvent(aaa._lastOwnEvent_),
driver.storeCustom('elo', 'marko')
)(function () {
return driver.storeEvents([
new Event(aaa.getOwnDescriptor('sdfds'), 'sdfs'),
new Event(zzz.getOwnDescriptor('sdfffds'), 'sdfs'),
new Event(foo.getOwnDescriptor('raz'), 'marko'),
new Event(bar.getOwnDescriptor('miszka'), 343),
new Event(foo.getOwnDescriptor('bal'), false),
new Event(foo.getOwnDescriptor('ole'), 767),
new Event(bar.getOwnDescriptor('ssss'), 343)
])(function () {
return driver.close();
})(function () {
var db = new Database()
, driver = t(db, { path: dbPath });
return driver.loadObject('foo')(function () {
a(db.foo.constructor, db.Object);
a(db.aaa, undefined);
a(db.bar, undefined);
a(db.zzz, undefined);
a(db.foo.raz, 'marko');
a(db.foo.bal, false);
a(db.foo.ole, 767);
return driver.loadValue('bar')(function (event) {
a(event.object, db.bar);
a(event.value, db.Object.prototype);
a(db.bar.constructor, db.Object);
a(db.bar.miszka, undefined);
});
})(function () {
return driver.loadValue('bar/miszka')(function (event) {
a(db.bar.miszka, 343);
});
})(function () {
return driver.getCustom('elo')(function (value) { a(value, 'marko'); });
})(function () {
return driver.close();
});
})(function () {
var db = new Database()
, driver = t(db, { path: dbPath });
return driver.loadAll()(function () {
a(db.foo.constructor, db.Object);
a(db.foo.raz, 'marko');
a(db.foo.bal, false);
a(db.foo.ole, 767);
a(db.aaa.constructor, db.Object);
a(db.zzz.constructor, db.Object);
a(db.bar.miszka, 343);
})(function () {
return driver.close();
});
})(function () {
var db = new Database()
, driver = t(new Database(), { path: dbPath })
, driverCopy = t(db, { path: dbCopyPath });
return driver.export(driverCopy)(function () {
return driverCopy.loadAll()(function () {
a(db.foo.constructor, db.Object);
a(db.foo.raz, 'marko');
a(db.foo.bal, false);
a(db.foo.ole, 767);
a(db.aaa.constructor, db.Object);
a(db.zzz.constructor, db.Object);
a(db.bar.miszka, 343);
});
})(function () {
return deferred(driver.close(), driverCopy.close());
});
})(function () {
return deferred(
rmdir(dbPath, { recursive: true, force: true }),
rmdir(dbCopyPath, { recursive: true, force: true })
);
});
}).done(function () { d(); }, d);
};
|
JavaScript
| 0.000009 |
@@ -803,16 +803,36 @@
%7D%0A%09%7D);%0A%0A
+%09zzz.delete('bar');%0A
%09driver.
@@ -1085,32 +1085,94 @@
lastOwnEvent_),%0A
+%09%09driver.storeEvent(zzz.getDescriptor('bar')._lastOwnEvent_),%0A
%09%09driver.storeCu
|
2f7702a69998dff0dd0587a85b24e3bdc360c3b4
|
switch from const to var for safari
|
test/index.js
|
test/index.js
|
'use strict';
const test = require('tape');
const csjs = require('../');
test('basic template string functionality', function t(assert) {
const result = csjs`#foo {color: red;}`;
assert.equal(csjs.getCss(result), '#foo {color: red;}', 'can retrieve basic css');
assert.end();
});
test('basic scoping functionality', function t(assert) {
const result = csjs`
.foo {}
.bar extends .foo {}
`;
assert.ok(result, 'result exists');
assert.ok(result.bar, 'bar has an extension');
assert.equal(result.bar.className, 'bar_1k1sUd foo_1k1sUd', 'bar extends foo');
assert.end();
});
test('multiple extensions', function t(assert) {
const one = csjs`
.foo {}
.bar extends .foo {}
`;
const two = csjs`
.baz extends ${one.bar} {}
.fob extends ${one.foo} {}
`;
const twoExpected = `
.baz_4CfzAa {}
.fob_4CfzAa {}
`;
assert.ok(two, 'result exists');
assert.equal(csjs.getCss(two), twoExpected, 'scoped css matches');
assert.ok(two.baz, 'baz has an extension');
assert.equal(two.baz.className, 'baz_4CfzAa bar_1k1sUd foo_1k1sUd',
'baz extends both bar and foo');
assert.equal(two.fob.className, 'fob_4CfzAa foo_1k1sUd',
'fob extends foo');
assert.end();
});
test('keyframes scoping', function t(assert) {
const one = csjs`
@keyframes yolo {}
.foo {
animation: yolo 5s infinite;
}
`;
const oneExpected = `
@keyframes yolo_2WD5WP {}
.foo_2WD5WP {
animation: yolo_2WD5WP 5s infinite;
}
`;
assert.ok(one.yolo, 'animation yolo is exported');
assert.equal(csjs.getCss(one), oneExpected, 'animation is scoped in css output');
const two = csjs`
.foo {
animation: ${one.yolo} 5s infinite;
}
`;
assert.ok(two, 'result exists');
assert.ok(two.foo, 'class foo is exported');
const twoExpected = `
.foo_4g9VPD {
animation: yolo_2WD5WP 5s infinite;
}
`;
assert.equal(csjs.getCss(two), twoExpected,
'class is scoped and animation imported correctly');
assert.end();
});
|
JavaScript
| 0 |
@@ -8,21 +8,19 @@
rict';%0A%0A
-const
+var
test =
@@ -36,21 +36,19 @@
tape');%0A
-const
+var
csjs =
@@ -123,37 +123,35 @@
n t(assert) %7B%0A
-const
+var
result = csjs%60#
@@ -335,21 +335,19 @@
rt) %7B%0A
-const
+var
result
@@ -632,37 +632,35 @@
n t(assert) %7B%0A
-const
+var
one = csjs%60%0A%0A
@@ -699,29 +699,27 @@
%7B%7D%0A%0A %60;%0A%0A
-const
+var
two = csjs%60
@@ -790,21 +790,19 @@
%0A %60;%0A
-const
+var
twoExpe
@@ -1266,21 +1266,19 @@
rt) %7B%0A
-const
+var
one = c
@@ -1368,21 +1368,19 @@
%60;%0A%0A
-const
+var
oneExpe
@@ -1629,29 +1629,27 @@
utput');%0A%0A
-const
+var
two = csjs%60
@@ -1805,13 +1805,11 @@
%0A%0A
-const
+var
two
|
c747f15233a6a4cab1042f904fd20e28eedd45bf
|
Fix typo
|
test/index.js
|
test/index.js
|
var assert = require('chai').assert,
hh = require('../index');
describe('#hh.route()', function () {
it('should be a function', function () {
assert.typeOf(hh.route, 'function', 'hh.route is a function');
});
it('should return an object with correct method', function () {
assert.propertyVal(hh.route('GET', '/', 'h'), 'method', 'GET');
});
it('should return an object with correct uppercased method', function () {
assert.propertyVal(hh.route('get', '/', 'h'), 'method', 'GET');
});
it('should work with array of methods', function () {
assert.deepEqual(hh.route(['get', 'post'], '/', 'h').method, ['GET', 'POST']);
});
it('should work with list of methods as one string', function () {
assert.deepEqual(hh.route('get post', '/', 'h').method, ['GET', 'POST']);
});
it('should not work with list of methods as one string with punctuation', function () {
// assert.deepNotEqual(hh.route(' get , post ', '/', 'h').method, ['GET', 'POST']);
assert.throws(function () {
hh.route('get , post', '/', 'h');
});
});
it('should work with list of methods as array with punctuation', function () {
assert.throws(function () {
hh.route([' get ,', ' post '], '/', 'h');
});
});
it('should work with array of methods with whitespace', function () {
assert.deepEqual(hh.route([' get ', ' post '], '/', 'h').method, ['GET', 'POST']);
});
it('should work with delete method in string', function () {
assert.deepEqual(hh.route(' get delete post ', '/', 'h').method, ['GET', 'DELETE', 'POST']);
});
it('should work with delete method in array', function () {
assert.deepEqual(hh.route([' get ', ' delete ', ' post '], '/', 'h').method, ['GET', 'DELETE', 'POST']);
});
it('should work with del method in string', function () {
assert.deepEqual(hh.route(' get del post ', '/', 'h').method, ['GET', 'DELETE', 'POST']);
});
it('should work with del method in array', function () {
assert.deepEqual(hh.route([' get ', ' del ', ' post '], '/', 'h').method, ['GET', 'DELETE', 'POST']);
});
it('should work with delete method in single string', function () {
assert.equal(hh.route('delete', '/', 'h').method, 'DELETE');
});
it('should work with del method in single string', function () {
assert.equal(hh.route('del', '/', 'h').method, 'DELETE');
});
it('should throw with no arguments', function () {
assert.throws(function () {
hh.route();
});
});
it('should throw with too few arguments', function () {
assert.throws(function () {
hh.route('get', '/');
});
});
it('should throw with bad arguments', function () {
assert.throws(function () {
hh.route('get', [], 'h');
});
});
});
describe('#hh.get()', function () {
it('should be a function', function () {
assert.typeOf(hh.get, 'function', 'hh.get is a function');
});
it('should return an object with GET', function () {
assert.propertyVal(hh.get('/', 'h'), 'method', 'GET');
});
it('should return object with correct values', function () {
var got = hh.get('/path', {some: 'handler'}, {some: 'config'});
var expected = {method: 'GET', path: '/path', handler: {some: 'handler'}, config: {some: 'config'}};
assert.deepEqual(got, expected);
});
});
describe('#hh.post()', function () {
it('should be a function', function () {
assert.typeOf(hh.post, 'function', 'hh.post is a function');
});
it('should return an object with POST', function () {
assert.propertyVal(hh.post('/', 'h'), 'method', 'POST');
});
});
describe('#hh.put()', function () {
it('should be a function', function () {
assert.typeOf(hh.put, 'function', 'hh.put is a function');
});
it('should return an object with PUT', function () {
assert.propertyVal(hh.put('/', 'h'), 'method', 'PUT');
});
});
describe('#hh.patch()', function () {
it('should be a function', function () {
assert.typeOf(hh.patch, 'function', 'hh.patch is a function');
});
it('should return an object with PATCH', function () {
assert.propertyVal(hh.patch('/', 'h'), 'method', 'PATCH');
});
});
describe('#hh.del()', function () {
it('should be a function', function () {
assert.typeOf(hh.del, 'function', 'hh.del is a function');
});
it('should return an object with DELETE', function () {
assert.propertyVal(hh.del('/', 'h'), 'method', 'DELETE');
});
});
describe('#hh.options()', function () {
it('should be a function', function () {
assert.typeOf(hh.options, 'function', 'hh.options is a function');
});
it('should return an object with OPTIONS', function () {
assert.propertyVal(hh.options('/', 'h'), 'method', 'OPTIONS');
});
});
describe('#hh.all()', function () {
it('should be a function', function () {
assert.typeOf(hh.all, 'function', 'hh.all is a function');
});
it('should return an object with *', function () {
assert.propertyVal(hh.all('/', 'h'), 'method', '*');
});
});
|
JavaScript
| 0.999999 |
@@ -1139,32 +1139,36 @@
%0A it('should
+not
work with list o
|
5e08b010c94df2da97ca9d3bd74aa02229bd792b
|
Add test for merge function
|
test/index.js
|
test/index.js
|
'use strict';
const Merger = require('../lib/merger')
, path = require('path');
require('./_config');
describe('Solidity Merger', () => {
it('should set default options', function () {
let merger = new Merger();
assert.equal(merger.delimeter, '\n\n', 'Delimeter must be set to 2 new lines');
assert.isArray(merger.processedFiles, 'Must be initialized as array');
});
it('should import relative files', async () => {
let merger = new Merger({ delimeter: '\n\n' });
let file = path.join(__dirname, '/contracts/LocalImports.sol');
let result = await merger.processFile(file, true);
assertWithFile(result, 'LocalImports.sol');
});
it('should not import twice same ', async () => {
let merger = new Merger({ delimeter: '\n\n' });
let file = path.join(__dirname, '/contracts/MultiImports.sol');
let result = await merger.processFile(file, true);
assertWithFile(result, 'MultiImports.sol');
});
});
|
JavaScript
| 0.000001 |
@@ -74,16 +74,52 @@
('path')
+%0A , %7B merge %7D = require('../index')
;%0Arequir
@@ -692,32 +692,248 @@
s.sol');%0A %7D);%0A%0A
+ it('should import relative files using merge', async () =%3E %7B%0A let file = path.join(__dirname, '/contracts/LocalImports.sol');%0A let result = merge(file);%0A assertWithFile(result, 'LocalImports.sol');%0A %7D);%0A%0A
it('should not
|
cb2dadacea5e5fc557ceb0a856687e5329e6b69c
|
Add commented-out test bail option to gruntfile
|
gruntfile.js
|
gruntfile.js
|
"use strict";
var config = require("./config.js");
module.exports = function (grunt) {
// load all grunt task libraries
require("load-grunt-tasks")(grunt);
// run app
grunt.registerTask("server:dev", ["express:dev", "watch:express"]);
grunt.registerTask("server:test", ["express:test"]);
grunt.registerTask("dev", ["eslint", "server:dev"]);
// clean up code and run tests
grunt.registerTask("default", ["eslint", "test"]);
grunt.registerTask("test", ["env:test", "dropDatabase", "server:test", "mochaTest:all"]);
// watch for changes and regenerate test PDF each time (for pdf development testing)
grunt.registerTask("generateTestPdf", ["express:dev", "exec:testPdf"]);
grunt.registerTask("report", ["generateTestPdf", "watch:pdf"]);
// generate code coverage using bash istanbul wrapper
grunt.registerTask("coverage", ["exec:coverage"]);
// push code coverage to coveralls.io
grunt.registerTask("coverage:push", ["exec:coverage", "coveralls"]);
// generate documentation locally
grunt.registerTask("docs", ["exec:docs"]);
// generate documentation and push it to github
grunt.registerTask("docs:push", ["docs", "gh-pages"]);
var mongoose = require("mongoose");
grunt.registerTask("dropDatabase", function () {
// force grunt into async
var done = this.async();
mongoose.connect(config.mongo, function (err) {
if (err) return done(err);
mongoose.connection.db.dropDatabase(function(err) {
if (err) return done(err);
console.log("Database dropped");
mongoose.connection.close(done);
});
});
});
grunt.initConfig({
// detect code smells and particularly bad formatting
eslint: {
target: ["Gruntfile.js", "app.js", "lib/*.js", "lib/**/*.js", "test/*.js", "test/**/*.js"]
},
// run tests: make sure to close all express/db/sinon/etc connections or this
// will hang
mochaTest: {
all: {
options: {
reporter: "spec",
timeout: "10000"
},
src: ["test/common/db_helper.js", "test/common/*.js", "test/*.js", "test/*/common.js", "test/**/*.js"]
},
unit: {
options: {
reporter: "spec",
timeout: "10000"
},
src: ["test/common/db_helper.js", "test/common/*.js", "test/*/common.js", "test/*/unit/*.js",
"test/*/unit/**/*.js"]
}
},
// set NODE_ENV so we don't send real emails or SMS' from tests
env: {
test: {
NODE_ENV: "test"
}
},
// run test server
express: {
test: {
options: {
script: "run.js"
}
},
dev: {
options: {
script: "run.js",
backround: false
}
}
},
watch: {
express: {
// reloading broken on OSX because of EMFILE hence this hack
files: [ "gruntfile.js"],
tasks: [ "express:dev" ],
options: {
spawn: false
}
},
pdf: {
// reloading broken on OSX because of EMFILE hence this hack
files: [
"lib/controllers/patients/report.js",
"test_pdf.js",
"gruntfile.js",
"lib/models/schedule/schedule.js"
],
tasks: [ "generateTestPdf" ],
options: {
spawn: false
}
}
},
exec: {
// build documentation locally: latest version of aglio doesn't play well with grunt-aglio
// so we use a shell script instead
docs: {
cwd: "docs",
cmd: "./build.sh"
},
// generate code coverage: bash wrapper around istanbul as their cli makes things a lot easier
// than playing around with js hooks
coverage: "./cover.sh",
// generate test PDF (assuming running servers)
testPdf: {
cmd: "node test_pdf.js"
}
},
// coveralls.io code coverage service
coveralls: {
options: {
force: false
},
src: ["./coverage/lcov.info"]
},
// push generated documentation straight to gh pages (with fixed commit message, but that's not
// the end of the world)
"gh-pages": {
options: {
base: "docs/output",
message: "Documentation updates (gh-pages commit message autogenerated by grunt)"
},
src: ["**"]
}
});
};
|
JavaScript
| 0 |
@@ -2124,32 +2124,67 @@
porter: %22spec%22,%0A
+ // bail: true,%0A
|
bce69be14178778aa505d8cfcf5248c13cf14a9c
|
include platform in build
|
gruntfile.js
|
gruntfile.js
|
/*
* Copyright 2013 The Toolkitchen Authors. All rights reserved.
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE file.
*/
module.exports = function(grunt) {
Toolkit = [
'src/lang.js',
'src/oop.js',
'src/register.js',
'src/bindProperties.js',
'src/bindMDV.js',
'src/attrs.js',
'src/marshal.js',
'src/events.js',
'src/observeProperties.js',
'src/styling.js',
'src/path.js',
'src/boot.js'
];
// karma setup
var browsers;
(function() {
try {
var config = grunt.file.readJSON('local.json');
if (config.browsers) {
browsers = config.browsers;
}
} catch (e) {
var os = require('os');
browsers = ['Chrome', 'Firefox'];
if (os.type() === 'Darwin') {
browsers.push('ChromeCanary');
}
if (os.type() === 'Windows_NT') {
browsers.push('IE');
}
}
})();
grunt.initConfig({
karma: {
options: {
configFile: 'conf/karma.conf.js',
browsers: browsers,
keepalive: true
},
buildbot: {
reporters: ['crbot'],
logLevel: 'OFF'
},
toolkit: {}
},
uglify: {
Toolkit: {
options: {
},
files: {
'toolkit.min.js': Toolkit
}
}
},
yuidoc: {
compile: {
name: '<%= pkg.name %>',
description: '<%= pkg.description %>',
version: '<%= pkg.version %>',
url: '<%= pkg.homepage %>',
options: {
exclude: 'third_party',
extension: '.js,.html',
paths: '.',
outdir: 'docs',
linkNatives: 'true',
tabtospace: 2,
themedir: '../docs/doc_themes/bootstrap'
}
}
},
pkg: grunt.file.readJSON('package.json')
});
// plugins
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-yuidoc');
grunt.loadNpmTasks('grunt-karma-0.9.1');
// tasks
grunt.registerTask('default', ['uglify']);
grunt.registerTask('minify', ['uglify']);
grunt.registerTask('docs', ['yuidoc']);
grunt.registerTask('test', ['karma:toolkit']);
grunt.registerTask('test-buildbot', ['karma:buildbot']);
};
|
JavaScript
| 0 |
@@ -203,16 +203,145 @@
runt) %7B%0A
+ Platform = %5B%0D%0A 'platform/platform.min.js'%0D%0A %5D;%0D%0A %0D%0A PlatformNative = %5B%0D%0A 'platform/platform.native.min.js'%0D%0A %5D;%0D%0A %0D%0A
Toolki
@@ -587,17 +587,63 @@
src/
-path.js',
+shimStyling.js',%0D%0A 'src/path.js',%0A 'src/job.js',%0D
%0A
@@ -662,18 +662,17 @@
s'%0A %5D;%0A
-
+%0D
%0A // ka
@@ -1418,29 +1418,118 @@
-options: %7B%0A %7D,
+files: %7B%0A 'toolkit.min.js': %5B%5D.concat(Platform, Toolkit)%0D%0A %7D%0A %7D,%0D%0A ToolkitNative: %7B%0D
%0A
@@ -1533,32 +1533,33 @@
files: %7B
+%0D
%0A 'tool
@@ -1562,24 +1562,31 @@
toolkit.
+native.
min.js':
Toolkit
@@ -1577,24 +1577,50 @@
min.js':
+ %5B%5D.concat(PlatformNative,
Toolkit
%0A
@@ -1611,16 +1611,18 @@
Toolkit
+)%0D
%0A
@@ -1615,32 +1615,33 @@
lkit)%0D%0A %7D
+%0D
%0A %7D%0A %7D,%0A
@@ -2544,12 +2544,14 @@
bot'%5D);%0A
+%0D%0A
%7D;%0A%0A
|
9c80ecb244921296873193f5967c3b03eae411e1
|
fix gruntfile typo
|
gruntfile.js
|
gruntfile.js
|
/*global module:false*/
var LIVERELOAD_PORT = 35729;
var lrSnippet = require('connect-livereload')({port: LIVERELOAD_PORT});
var mountFolder = function (connect, dir) {
return connect['static'](require('path').resolve(dir));
};
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
jshint: {
options: {
jshintrc: true
},
all: ['src/app/**/*.js', 'test/**/*.js']
},
connect: {
options: {
port:9000
},
// load unbuilt code w/ livereload
unbuilt: {
options: {
middleware: function (connect) {
return [
lrSnippet,
mountFolder(connect, './src/')
];
}
}
},
// load built app
build: {
options: {
base: 'dist',
// change this to '0.0.0.0' to access the server from outside
hostname: 'localhost'
}
}
},
//Open default browser at the app
open: {
unbuilt: {
path: 'http://localhost:<%= connect.options.port %>/index.html'
},
build: {
path: 'http://localhost:<%= connect.options.port %>/'
}
},
//setup watch tasks
watch: {
options: {
nospan: true,
livereload: LIVERELOAD_PORT
}
},
esri_slurp: {
options: {
version: '3.12'
},
dev: {
options: {
beautify: true
},
dest: 'src/esri'
},
prod: {
options: {
beautify: false
},
dest: 'src/esri'
}
},
// clean the output directory before each build
clean: {
build: ['dist'],
deploy: ['dist/**/*.consoleStripped.js','dist/**/*.uncompressed.js','dist/**/*.js.map'],
bower: ['src/bootstrap-map-js', 'src/dijit', 'src/dojo', 'src/dojo-bootstrap', 'src/dojox', 'src/put-selector', 'src/spinjs', 'src/util', 'src/xstyle'],
slurp: ['src/esri']
},
// dojo build configuration, mainly taken from dojo boilerplate
dojo: {
dist: {
options: {
profile: 'profiles/app.profile.js' // Profile for build
}
},
options: {
dojo: 'src/dojo/dojo.js', // Path to dojo.js file in dojo source
load: 'build', // Optional: Utility to bootstrap (Default: 'build')
// profiles: [], // Optional: Array of Profiles for build
// appConfigFile: '', // Optional: Config file for dojox/app
// package: '', // Optional: Location to search package.json (Default: nothing)
// packages: [], // Optional: Array of locations of package.json (Default: nothing)
// require: '', // Optional: Module to require for the build (Default: nothing)
// requires: [], // Optional: Array of modules to require for the build (Default: nothing)
releaseDir: '../dist', // Optional: release dir rel to basePath (Default: 'release')
cwd: './', // Directory to execute build within
// dojoConfig: '', // Optional: Location of dojoConfig (Default: null),
// Optional: Base Path to pass at the command line
// Takes precedence over other basePaths
// Default: null
basePath: './src'
}
},
processhtml: {
build: {
files: {
'dist/index.html': ['src/index.html']
}
}
},
'gh-pages': {
options: {
base: 'src'
},
src: ['app/**', 'index.html']
},
karma: {
unit: {
configFile: 'karma.conf.js'
},
firefox: {
configFile: 'karma.conf.js',
browsers: ['Firefox']
}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-connect');
grunt.loadNpmTasks('grunt-if-missing');
grunt.loadNpmTasks('grunt-open');
grunt.loadNpmTasks('grunt-gh-pages');
grunt.loadNpmTasks('grunt-esri-slurp');
grunt.loadNpmTasks('grunt-contrib-clean');
grunt.loadNpmTasks('grunt-dojo');
grunt.loadNpmTasks('grunt-processhtml');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['serve']);
grunt.registerTask('serve', function (target) {
var trgt = target || 'unbuilt';
grunt.task.run([
'jshint',
'connect:' + trgt,
'open:' + trgt,
'watch'
]);
});
grunt.registerTask('test', ['jshint', 'karma:unit']);
grunt.registerTask('slurp', ['clean:slurp', 'esri_slurp:dev']);
grunt.registerTask('build', ['jshint', 'clean:build', 'dojo', 'processhtml']);
grunt.registerTask('deploy', ['gh-pages']);
grunt.registerTask('travis', [
'if-missing:esri_slurp:prod',
'test',
'build:prod'
]);
};
|
JavaScript
| 0.00011 |
@@ -5591,21 +5591,16 @@
'build
-:prod
'%0A %5D)
|
14779ec40dc2f6063ea24f465575c1cc2677f7ba
|
Fix release options
|
gruntfile.js
|
gruntfile.js
|
module.exports = function (grunt) {
var plugins = ['karma-mocha']
var browsers = []
if (process.env.TRAVIS) {
plugins.push('karma-firefox-launcher')
browsers.push('Firefox')
} else {
plugins.push('karma-chrome-launcher')
browsers.push('Chrome')
}
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
pkgFile: 'package.json',
eslint: {
target: [
'gruntfile.js',
'lib/*.js',
'tasks/*.js',
'test/*.js'
]
},
'npm-publish': {
options: {
abortIfDirty: true
}
},
'npm-contributors': {
options: {
commitMessage: 'chore: Update contributors'
}
},
conventionalChangelog: {
release: {
options: {
changelogOpts: {
preset: 'angular'
}
},
src: 'CHANGELOG.md'
}
},
conventionalGithubReleaser: {
release: {
options: {
auth: {
type: 'oauth',
token: process.env.GH_TOKEN
},
changelogOpts: {
preset: 'angular',
releaseCount: 0
}
}
}
},
bump: {
options: {
updateConfigs: ['pkg'],
commitFiles: ['package.json', 'CHANGELOG.md'],
commitMessage: 'chore: release v%VERSION%',
pushTo: 'upstream',
push: false,
gitDescribeOptions: '| echo "beta-$(git rev-parse --short HEAD)"'
}
},
karma: {
options: {
browsers: browsers,
frameworks: ['mocha'],
plugins: plugins
},
single: {
singleRun: true,
files: [
{
src: 'node_modules/expect.js/index.js'
}, {
src: 'test/**/*.js'
}
]
},
config: {
configFile: 'karma.conf.js',
singleRun: true
},
merge: {
options: {
files: ['node_modules/expect.js/index.js']
},
singleRun: true,
files: [
{
src: 'test/**/*.js'
}
]
},
dev: {
reporters: 'dots',
background: true
},
auto: {
autoWatch: true
}
},
watch: {
tests: {
files: 'test/**/*.js',
tasks: ['karma:dev:run']
}
}
})
grunt.loadTasks('tasks')
require('load-grunt-tasks')(grunt)
grunt.registerTask('test', ['karma:single', 'karma:config', 'karma:merge'])
grunt.registerTask('default', ['eslint', 'test'])
grunt.registerTask('release', 'Bump the version and publish to npm.', function (type) {
grunt.task.run([
'npm-contributors',
'bump:' + (type || 'patch') + ':bump-only',
'conventionalChangelog',
'bump-commit',
'conventionalGithubReleaser',
'npm-publish'
])
})
}
|
JavaScript
| 0.000021 |
@@ -1107,37 +1107,8 @@
lar'
-,%0A releaseCount: 0
%0A
@@ -1342,29 +1342,8 @@
m',%0A
- push: false,%0A
|
32a0dc96941043b1d7cf556e78f2217b1530ba46
|
include Rb-ui to minify
|
gruntfile.js
|
gruntfile.js
|
/*!
* @ Package for Responsive Boilerplate Micro Lib @!!!!!
*/
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
uglify: {
options: {
banner: '/*! <%= pkg.name %> v<%= pkg.version %>, <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
files: {
src: [ 'js/*.js' ],
dest: 'js/',
expand: true,
flatten: true,
ext: '.min.js'
}
},
jshint: {
options: {
browser: true,
globals: {
jQuery: true,
console: true,
module: true,
document: true
}
},
all: {
files: {
src: ['gruntfile.js', 'js/custom.js', 'src/rb-accordion.js', 'rb-menu.js']
}
}
},
concat: {
options: {
},
dist: {
src: [
'src/rb-menu.js',
'src/rb-accordion.js'
],
dest: 'js/rb-ui.js'
}
},
less: {
development: {
options: {
paths: ['less'],
yuicompress: false
},
files: {
'css/responsiveboilerplate.css':'less/responsiveboilerplate.less',
'css/rb-ui.css':'less/rb-ui.less'
}
}
},
cssmin: {
options: {
banner: '/*! <%= pkg.name %> v<%= pkg.version %>, <%= grunt.template.today("yyyy-mm-dd") %> */\n'
},
compress: {
files: {
'css/responsiveboilerplate.min.css': ['css/responsiveboilerplate.css']
}
}
},
watch: {
scripts: {
files: ['Gruntfile.js', 'js/**/*.js', 'libs/**/*.js', 'css/**/*.css'],
tasks: ['jshint','concat','uglify'],
options: {
debounceDelay: 250
}
},
less: {
files: 'less/**/*.less',
tasks: ['less','cssmin'],
options: {
debounceDelay: 250
}
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-concat');
grunt.loadNpmTasks('grunt-contrib-uglify');
grunt.loadNpmTasks('grunt-contrib-less');
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.registerTask('default', ['jshint','concat','uglify','less','cssmin','watch']);
};
|
JavaScript
| 0.000001 |
@@ -1537,16 +1537,65 @@
te.css'%5D
+,%0A 'css/rb-ui.min.css':%5B'css/rb-ui.css'%5D
%0A
|
b17beaccf1007ddc4b17454129b6342c9d67bf22
|
Add timeout config.
|
packages/bower-config/lib/Config.js
|
packages/bower-config/lib/Config.js
|
var os = require('os');
var path = require('path');
var mout = require('mout');
var rc = require('./util/rc');
var paths = require('./util/paths');
// Guess proxy defined in the env
var proxy = process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
var httpsProxy = process.env.HTTPS_PROXY
|| process.env.https_proxy
|| process.env.HTTP_PROXY
|| process.env.http_proxy
|| null;
//-------------
function Config(cwd) {
this._cwd = cwd || process.cwd();
this._config = {};
}
Config.prototype.load = function () {
var runtimeConfig;
runtimeConfig = rc('bower', {
'cwd': this._cwd,
'directory': 'bower_components',
'registry': 'https://bower.herokuapp.com',
'shorthand-resolver': 'git://github.com/{{owner}}/{{package}}.git',
'tmp': os.tmpdir ? os.tmpdir() : os.tmpDir(),
'proxy': proxy,
'https-proxy': httpsProxy,
'ca': null,
'strict-ssl': true,
'user-agent': 'node/' + process.version + ' ' + process.platform + ' ' + process.arch,
'git': 'git',
'color': true,
'interactive': false,
'storage': {
packages: path.join(paths.cache, 'packages'),
links: path.join(paths.data, 'links'),
completion: path.join(paths.data, 'completion'),
registry: path.join(paths.cache, 'registry'),
git: path.join(paths.data, 'git')
}
}, this._cwd);
// Some backwards compatible things..
runtimeConfig['shorthand-resolver'] = runtimeConfig['shorthand-resolver']
.replace(/\{\{\{/g, '{{')
.replace(/\}\}\}/g, '}}');
// Generate config based on the rc, making every key camelCase
this._config = {};
mout.object.forOwn(runtimeConfig, function (value, key) {
key = key.replace(/_/g, '-');
this._config[mout.string.camelCase(key)] = value;
}, this);
return this;
};
Config.prototype.get = function (key) {
};
Config.prototype.set = function (key, value) {
return this;
};
Config.prototype.del = function (key, value) {
return this;
};
Config.prototype.save = function (where, callback) {
};
Config.prototype.toObject = function () {
return mout.lang.deepClone(this._config);
};
Config.create = function (cwd) {
return new Config(cwd);
};
Config.read = function (cwd) {
var config = new Config(cwd);
return config.load().toObject();
};
module.exports = Config;
|
JavaScript
| 0 |
@@ -176,16 +176,44 @@
the env%0A
+/*jshint camelcase: false*/%0A
var prox
@@ -427,16 +427,43 @@
%7C%7C null;
+%0A/*jshint camelcase: true*/
%0A%0A//----
@@ -959,24 +959,50 @@
httpsProxy,%0A
+ 'timeout': 60000,%0A
'ca'
@@ -2034,25 +2034,36 @@
ion (key) %7B%0A
+ // TODO
%0A
-
%7D;%0A%0AConfig.p
@@ -2093,33 +2093,44 @@
(key, value) %7B%0A
+ // TODO
%0A
-
return this;
@@ -2181,17 +2181,28 @@
alue) %7B%0A
+ // TODO
%0A
-
retu
@@ -2267,16 +2267,27 @@
back) %7B%0A
+ // TODO
%0A%7D;%0A%0ACon
|
1452f0328e419a7d17cd03e9f8db73f3984f4723
|
Upgrade execa
|
packages/bundler/lib/helpers/cli.js
|
packages/bundler/lib/helpers/cli.js
|
const path = require('path');
const execa = require('execa');
const bash = (cli, args = [], stdio) => execa.shell(`${cli} ${args.join(' ')}`, { shell: '/bin/bash', stdio });
const script = (cli, args = [], stdio) => {
const cmd = path.resolve(__dirname, '..', '..', 'scripts', cli);
return bash(cmd, args, stdio);
};
module.exports = { bash, script };
|
JavaScript
| 0.000001 |
@@ -59,87 +59,172 @@
');%0A
-%0Aconst bash = (cli, args = %5B%5D, stdio) =%3E execa.shell(%60$%7Bcli%7D $%7Bargs.join(' ')%7D%60
+const %7B debug %7D = require('./log')('proton-bundler');%0A%0Aconst bash = (cli, args = %5B%5D, stdio) =%3E %7B%0A debug(%7B cli, args, stdio %7D, 'bash');%0A return execa(cli, args
, %7B
@@ -253,16 +253,20 @@
dio %7D);%0A
+%7D;%0A%0A
const sc
|
4b879e108ae6af3050d406c133bb7e6f53a0f07a
|
add some logs
|
services.js
|
services.js
|
function minbet(gs) {
return gs.current_buy_in - gs.players[in_action][bet] + gs.minimum_raise;
}
function checkCard(card) {
switch (card) {
case "J" :
card = 11;
break;
case "Q" :
card = 12;
break;
case "K" :
card = 13;
break;
case "A" :
card = 14;
break;
default:
card = card;
}
return card;
}
function calculateBet(game_state) {
var ours = game_state.players[game_state.in_action].hole_cards;
var card1 = checkCard(ours[0]);
var card2 = checkCard(ours[1]);
if (card1 === card2) {
return 100000;
} else if (card1 < 6 && card2 < 6) {
return 10;
} else if (card1 < 10 && card2 < 10) {
return 200;
} else {
return 100000;
}
}
module.exports = {
checkCard: checkCard,
calBet: calculateBet,
}
|
JavaScript
| 0.000001 |
@@ -94,16 +94,38 @@
ise;%0A%7D%0A%0A
+var l = console.log;%0A%0A
function
@@ -748,24 +748,43 @@
== card2) %7B%0A
+ l(%22pair%22);%0A
retu
@@ -833,24 +833,48 @@
ard2 %3C 6) %7B%0A
+ l(%22low cards%22);%0A
retu
@@ -921,24 +921,51 @@
rd2 %3C 10) %7B%0A
+ l(%22middle cards%22);%0A
retu
@@ -987,16 +987,41 @@
else %7B%0A
+ l(%22high cards%22);%0A
|
d769f3393284abcb409e124332bb23b55292369a
|
Allow ckeditor configuration.
|
Resources/public/scripts/form.wysiwyg.js
|
Resources/public/scripts/form.wysiwyg.js
|
(function() {
'use strict';
$(function() {
var $elements = $('textarea.wysiwyg');
if (!$elements.length) {
return;
}
$.ajax({
url: "/vendor/ckeditor/ckeditor.js",
dataType: "script",
cache: true
}).done(function() {
$.ajax({
url: "/vendor/ckeditor/adapters/jquery.js",
dataType: "script",
cache: true
}).done(function() {
$elements.ckeditor();
});
});
});
}());
|
JavaScript
| 0 |
@@ -477,32 +477,127 @@
ne(function() %7B%0A
+ var config = %7B%7D;%0A $elements.trigger('ckeditor-config', config);%0A
@@ -615,16 +615,22 @@
keditor(
+config
);%0A
|
817ad388ac58dff9675d3933cb978698669cb588
|
clear display before adding content
|
plugins/jspsych-multi-stim-multi-response.js
|
plugins/jspsych-multi-stim-multi-response.js
|
/**
* jspsych-muli-stim-multi-response
* Josh de Leeuw
*
* plugin for displaying a set of stimuli and collecting a set of responses
* via the keyboard
*
* documentation: docs.jspsych.org
*
**/
jsPsych.plugins["multi-stim-multi-response"] = (function() {
var plugin = {};
jsPsych.pluginAPI.registerPreload('multi-stim-multi-response', 'stimuli', 'image',function(t){ return !t.is_html || t.is_html == 'undefined'});
plugin.info = {
name: 'multi-stim-multi-response',
description: '',
parameters: {
stimuli: {
type: [jsPsych.plugins.parameterType.STRING],
default: undefined,
array: true,
no_function: false,
description: ''
},
is_html: {
type: [jsPsych.plugins.parameterType.BOOL],
default: false,
no_function: false,
description: ''
},
choices: {
type: [jsPsych.plugins.parameterType.KEYCODE],
default: undefined,
array: true,
no_function: false,
description: ''
},
prompt: {
type: [jsPsych.plugins.parameterType.STRING],
default: '',
no_function: false,
description: ''
},
timing_stim: {
type: [jsPsych.plugins.parameterType.INT],
default: 1000,
array: true,
no_function: false,
description: ''
},
timing_response: {
type: [jsPsych.plugins.parameterType.INT],
default: -1,
no_function: false,
description: ''
},
response_ends_trial: {
type: [jsPsych.plugins.parameterType.BOOL],
default: true,
no_function: false,
description: ''
}
}
}
plugin.trial = function(display_element, trial) {
// default parameters
trial.response_ends_trial = (typeof trial.response_ends_trial === 'undefined') ? true : trial.response_ends_trial;
// timing parameters
var default_timing_array = [];
for (var j = 0; j < trial.stimuli.length; j++) {
default_timing_array.push(1000);
}
trial.timing_stim = trial.timing_stim || default_timing_array;
trial.timing_response = trial.timing_response || -1; // if -1, then wait for response forever
// optional parameters
trial.is_html = (typeof trial.is_html === 'undefined') ? false : trial.is_html;
trial.prompt = (typeof trial.prompt === 'undefined') ? "" : trial.prompt;
// if any trial variables are functions
// this evaluates the function and replaces
// it with the output of the function
trial = jsPsych.pluginAPI.evaluateFunctionParameters(trial);
// array to store if we have gotten a valid response for
// all the different response types
var validResponses = [];
for (var i = 0; i < trial.choices.length; i++) {
validResponses[i] = false;
}
// array for response times for each of the different response types
var responseTimes = [];
for (var i = 0; i < trial.choices.length; i++) {
responseTimes[i] = -1;
}
// array for response keys for each of the different response types
var responseKeys = [];
for (var i = 0; i < trial.choices.length; i++) {
responseKeys[i] = -1;
}
// function to check if all of the valid responses are received
function checkAllResponsesAreValid() {
for (var i = 0; i < validResponses.length; i++) {
if (validResponses[i] == false) {
return false;
}
}
return true;
}
// function to end trial when it is time
var end_trial = function() {
// kill any remaining setTimeout handlers
jsPsych.pluginAPI.clearAllTimeouts();
// kill keyboard listeners
jsPsych.pluginAPI.cancelKeyboardResponse(keyboardListener);
// gather the data to store for the trial
var trial_data = {
"rt": JSON.stringify(responseTimes),
"stimulus": JSON.stringify(trial.stimuli),
"key_press": JSON.stringify(responseKeys)
};
// clear the display
display_element.innerHTML = '';
// move on to the next trial
jsPsych.finishTrial(trial_data);
};
// function to handle responses by the subject
var after_response = function(info) {
var whichResponse;
for (var i = 0; i < trial.choices.length; i++) {
// allow overlap between response groups
if (validResponses[i]) {
continue;
}
for (var j = 0; j < trial.choices[i].length; j++) {
keycode = (typeof trial.choices[i][j] == 'string') ? jsPsych.pluginAPI.convertKeyCharacterToKeyCode(trial.choices[i][j]) : trial.choices[i][j];
if (info.key == keycode) {
whichResponse = i;
break;
}
}
if (typeof whichResponse !== 'undefined') {
break;
}
}
if (validResponses[whichResponse] != true) {
validResponses[whichResponse] = true;
responseTimes[whichResponse] = info.rt;
responseKeys[whichResponse] = info.key;
}
if (trial.response_ends_trial) {
if (checkAllResponsesAreValid()) {
end_trial();
}
}
};
// flattened version of the choices array
var allchoices = [];
for (var i = 0; i < trial.choices.length; i++) {
allchoices = allchoices.concat(trial.choices[i]);
}
var whichStimulus = 0;
function showNextStimulus() {
// display stimulus
if (!trial.is_html) {
display_element.innerHTML += '<img id="jspsych-multi-stim-multi-response-stimulus" src="'+trial.stimuli[whichStimulus]+'"></img>';
} else {
display_element.innerHTML += '<div id="jspsych-multi-stim-multi-response-stimulus">'+trial.stimuli[whichStimulus]+'</div>';
}
//show prompt if there is one
if (trial.prompt !== "") {
display_element.innerHTML += trial.prompt;
}
if (typeof trial.timing_stim[whichStimulus] !== 'undefined' && trial.timing_stim[whichStimulus] > 0) {
jsPsych.pluginAPI.setTimeout(function() {
// clear the display, or hide the display
if (typeof trial.stimuli[whichStimulus + 1] !== 'undefined') {
display_element.innerHTML = '';
// show the next stimulus
whichStimulus++;
showNextStimulus();
} else {
display_element.querySelector('#jspsych-multi-stim-multi-response-stimulus').style.visibility = 'hidden';
}
}, trial.timing_stim[whichStimulus]);
}
}
// show first stimulus
showNextStimulus();
// start the response listener
var keyboardListener = jsPsych.pluginAPI.getKeyboardResponse({
callback_function: after_response,
valid_responses: allchoices,
rt_method: 'date',
persist: true,
allow_held_key: false
});
// end trial if time limit is set
if (trial.timing_response > 0) {
jsPsych.pluginAPI.setTimeout(function() {
end_trial();
}, trial.timing_response);
}
};
return plugin;
})();
|
JavaScript
| 0 |
@@ -5390,16 +5390,53 @@
s = 0;%0A%0A
+ display_element.innerHTML = '';%0A%0A
func
|
a1bd30cad392b2b50af0af00c7511780706fd45d
|
Include receiver = []
|
app/scripts/controllers/admin/contexts.js
|
app/scripts/controllers/admin/contexts.js
|
GLClient.controller('AdminContextsCtrl',
['$scope', 'localization', 'AdminContexts',
function($scope, localization, AdminContexts) {
$scope.new_context = function() {
var context = new AdminContexts;
//context.name[localization.selected_language] = $scope.new_context_name;
context.name = $scope.new_context_name;
context.description = '';
context.fields = [];
context.languages = [];
context.escalation_threshold = 42;
context.file_max_download = 42;
context.tip_max_access = 42;
context.selectable_receiver = true;
context.tip_timetolive = 42;
context.$save(function(created_context){
$scope.adminContexts.push(created_context);
});
}
$scope.delete_context = function(context) {
var idx = _.indexOf($scope.adminContexts, context);
context.$delete();
$scope.adminContexts.splice(idx, 1);
}
}]);
|
JavaScript
| 0.000002 |
@@ -415,16 +415,44 @@
es = %5B%5D;
+%0A context.receivers = %5B%5D;
%0A%0A co
|
8dae9ee390a58eb6ab50d07978d18138b303625c
|
move return statement outside of loop
|
test/utils.js
|
test/utils.js
|
// test/utils.js
'use strict';
import config from '../config/config.json';
import mongoose from 'mongoose';
const ENV = 'test';
// ensure the NODE_ENV is set to 'test'
// this is helpful when you would like to change behavior when testing
process.env.NODE_ENV = ENV;
let mongoUri = config.MONGO_URI[ENV.toUpperCase()];
beforeEach((done) => {
function clearDB() {
for (var i in mongoose.connection.collections) {
mongoose.connection.collections[i].remove((error, status) => {
if(error)
console.error(error);
else {
return done();
}
});
}
}
if (mongoose.connection.readyState === 0) {
mongoose.connect(mongoUri, (err) => {
if (err) {
throw err;
}
return clearDB();
});
} else {
return clearDB();
}
});
afterEach((done) => {
mongoose.disconnect();
return done();
});
|
JavaScript
| 0.000004 |
@@ -569,34 +569,31 @@
);%0D%0A
-%0D%0A
- else %7B%0D%0A%0D
+%7D);%0D%0A %7D
%0A
-
+%0D%0A
@@ -612,37 +612,8 @@
);%0D%0A
- %7D%0D%0A %7D);%0D%0A %7D%0D%0A
%7D%0D
|
e0d96baeaa3602d03d67cd73844770e9b3b929f8
|
Fix issue where clicking on refresh button hid the custom node collection
|
app/scripts/views/WorkspaceBrowserView.js
|
app/scripts/views/WorkspaceBrowserView.js
|
define(['backbone', 'WorkspaceBrowserElementView'], function(Backbone, WorkspaceBrowserElementView) {
return Backbone.View.extend({
el: '#workspace-browser',
initialize: function(atts, arr) {
this.app = arr.app;
this.model.get('workspaces').on('reset', this.render, this );
this.model.get('workspaces').on('add', this.addWorkspaceElement, this );
this.model.get('workspaces').on('remove', this.removeWorkspaceElement, this );
this.render();
},
template: _.template( $('#workspace-browser-template').html() ),
events: {
'click .workspace-browser-refresh': "refreshClick",
'click #workspace-browser-header-custom-nodes': "customNodeHeaderClick",
'click #workspace-browser-header-projects': "projectHeaderClick"
},
render: function(arg) {
this.$el.html( this.template( this.model.toJSON() ) );
this.contents = this.$el.find('#workspace-browser-contents');
this.customNodes = this.$el.find('#workspace-browser-custom-nodes');
this.customNodes.empty();
this.projects = this.$el.find('#workspace-browser-projects');
this.projects.empty();
},
refreshClick: function(e){
this.model.refresh();
e.stopPropagation();
},
customNodeHeaderClick: function(e){
this.projects.hide();
this.customNodes.show();
$('#workspace-browser-header-custom-nodes').css('bottom','').css('top','40px');
},
projectHeaderClick: function(e){
this.customNodes.hide();
this.projects.show();
$('#workspace-browser-header-custom-nodes').css('bottom','0').css('top','');
},
addWorkspaceElement: function(x){
if (!this.contents) this.render();
var v = new WorkspaceBrowserElementView( { model: x }, { app : this.app } );
v.render();
if ( x.get('isCustomNode') ){
this.customNodes.append( v.$el );
} else {
this.projects.append( v.$el );
}
},
removeWorkspaceElement: function(ws){
if (!this.contents) return;
this.contents.find('.workspace-browser-element[data-id*=' + ws.get('_id') + ']').remove();
}
});
});
|
JavaScript
| 0 |
@@ -817,16 +817,46 @@
arg) %7B%0A%0A
+ if (!this.rendered) %7B%0A
th
@@ -904,25 +904,26 @@
JSON() ) );%0A
-%0A
+
this.c
@@ -974,25 +974,26 @@
contents');%0A
-%0A
+
this.c
@@ -1061,39 +1061,8 @@
;%0A
- this.customNodes.empty();%0A%0A
@@ -1121,24 +1121,100 @@
projects');%0A
+ %7D%0A%0A this.rendered = true;%0A %0A this.customNodes.empty();%0A
this.p
@@ -1366,32 +1366,151 @@
: function(e)%7B%0A%0A
+ // do not resize when refresh is clicked%0A if ( $(e.target).hasClass('workspace-browser-refresh') ) return;%0A%0A
this.proje
@@ -1682,24 +1682,102 @@
nction(e)%7B%0A%0A
+ if ( $(e.target).hasClass('workspace-browser-refresh') ) return;%0A %0A
this.c
|
51d0c8dfc853ac8d8a618db0484797754d316889
|
Add resize
|
RTDT/static/js/afterload.js
|
RTDT/static/js/afterload.js
|
// initialize the map
var map = L.map('map').setView([39.73, -104.99], 13);
L.tileLayer('https://{s}.tiles.mapbox.com/v4/{mapId}/{z}/{x}/{y}.png?access_token={token}', {
attribution: '<a href="https://www.mapbox.com/about/maps/" target="_blank">© Mapbox © OpenStreetMap</a>',
subdomains: ['a','b','c','d'],
mapId: 'mapbox.emerald',
token: 'pk.eyJ1Ijoia2RoZWVwYWs4OSIsImEiOiJjaWt2MXVtMHYwMGRydWFtM2JneDJ1MWMxIn0._Vr6g3q4myFgjWPB21SGiQ'
}).addTo(map);
/* Initialize the SVG layer */
map._initPathRoot()
var temp = null
function onLocationFound(e) {
var radius = e.accuracy / 2;
// L.marker(e.latlng).addTo(map);
$.ajax({
url: "/api/proximity/",
type: "get", //send it through get method
dataType: 'json',
data:{lat:e.latlng.lat, lng:e.latlng.lng},
success: function(d) {
console.log(d)
temp = d
select = document.getElementById('routename');
var opt = document.createElement('option');
opt.value = "None"
opt.innerHTML = "------ SELECT ROUTE -----";
select.appendChild(opt);
for (var i = 0, length = d.length; i < length; i++){
var opt = document.createElement('option');
opt.value = d[i];
opt.innerHTML = d[i];
select.appendChild(opt);
}
opt.value = "None"
opt.innerHTML = "------ ALL ROUTES -----";
select.appendChild(opt);
addAllBus()
},
error: function(xhr) {
select = document.getElementById('routename');
var opt = document.createElement('option');
opt.value = "None"
opt.innerHTML = "------ SELECT ROUTE -----";
select.appendChild(opt);
addAllBus()
}
});
}
function onLocationError(e) {
select = document.getElementById('routename');
var opt = document.createElement('option');
opt.value = "None"
opt.innerHTML = "------ SELECT ROUTE -----";
select.appendChild(opt);
addAllBus()
}
function addAllBus() {
$.ajax({
url: "/api/proximity/",
type: "get", //send it through get method
dataType: 'json',
success: function(d) {
console.log(d)
select = document.getElementById('routename');
for (var i = 0, length = d.length; i < length; i++){
var opt = document.createElement('option');
opt.value = d[i];
opt.innerHTML = d[i];
select.appendChild(opt);
}
document.getElementById('spinnerElement').style.display = 'none';
},
error: function(xhr) {
console.log(xhr)
}
});
}
map.on('locationfound', onLocationFound);
map.on('locationerror', onLocationError);
map.locate({setView: true, maxZoom: 14});
// when view changes
function onViewChange(e) {
$(".viewChangeClass").show();
}
map.on('move', function (e) { onViewChange(e) });
var json_data = null;
var latlngs = Array();
var routeMarkerList = Array();
var markerList = Array();
var polyline = null
function drawRoute(trip_id) {
console.log(markerList)
removeMarkers()
console.log(trip_id)
d3.json("/api/trip_id/"+trip_id,function(error,response){
json_data = response
for (var i = 0; i < json_data.stop_time_update.length; i++) {
marker = new L.marker([json_data.stop_time_update[i].location[0],
json_data.stop_time_update[i].location[1]])
.bindPopup("<b>" + json_data.stop_time_update[i].stop_name + "</b><br>Expected departure time - " +
json_data.stop_time_update[i].departure.time)
.addTo(map);
//Get latlng from first marker
latlngs.push(marker.getLatLng());
markerList.push(marker)
}
//You can just keep adding markers
//From documentation http://leafletjs.com/reference.html#polyline
// create a red polyline from an arrays of LatLng points
polyline = L.polyline(latlngs, {color: 'red'}).addTo(map);
markerList.push(polyline)
// zoom the map to the polyline
// map.fitBounds(polyline.getBounds());
});
}
function removeMarkers() {
for (var i = 0; i < markerList.length; i++) {
map.removeLayer(markerList[i])
}
markerList.splice(0)
latlngs.splice(0)
}
function removeRouteMarkers() {
for (var i = 0; i < routeMarkerList.length; i++) {
map.removeLayer(routeMarkerList[i])
}
routeMarkerList.splice(0)
}
function updateData(sel) {
removeRouteMarkers()
console.log(sel.value)
$.ajax({
url: "/api/route/",
type: "get", //send it through get method
dataType: 'json',
data:{route:sel.value},
success: function(data) {
console.log(data)
removeMarkers()
transitIcon = L.icon({
iconUrl: '/static/transit.jpg',
iconSize: [25, 25], // size of the icon
})
for (var i = 0; i < data.length; i++) {
marker = new L.marker([data[i].location[0],
data[i].location[1]], {icon: transitIcon, trip_id: data[i].trip_id})
.bindPopup("<b>" + data[i].trip_name + "</b><br>Expected to depart "+
data[i].current_location +
" at " +
data[i].expected_departure)
.addTo(map);
marker.on('click', function(e) {
drawRoute(this.options.trip_id)
})
routeMarkerList.push(marker)
}
},
error: function(xhr) {
//Do Something to handle error
}
});
}
|
JavaScript
| 0.000002 |
@@ -3936,19 +3936,16 @@
line%0A
- //
map.fit
|
7a538a0b0db43afdcf5fcd5143f98bf0a80d00fd
|
Remove unneeded undefined initialisation
|
app/src/js/modules/fields/relationship.js
|
app/src/js/modules/fields/relationship.js
|
/**
* Handling of relationship input fields.
*
* @mixin
* @namespace Bolt.fields.relationship
*
* @param {Object} bolt - The Bolt module.
* @param {Object} $ - jQuery.
*/
(function (bolt, $) {
/**
* Bolt.fields.relationship mixin container.
*
* @private
* @type {Object}
*/
var relationship = {};
/**
* Bind relationship field.
*
* @static
* @function init
* @memberof Bolt.fields.relationship
*
* @param {Object} fieldset
* @param {FieldConf} fconf
*/
relationship.init = function (fieldset, fconf) {
var select = $(fieldset).find('select'),
funcFormatSelection = undefined;
if (fconf.groupBy) {
funcFormatSelection = function (item) {
return $(item.element).parent().attr('label') + ': ' + item.text;
};
}
select.select2({
placeholder: bolt.data('field.relationship.text.placeholder'),
allowClear: true,
formatSelection: funcFormatSelection
});
};
// Apply mixin container
bolt.fields.relationship = relationship;
})(Bolt || {}, jQuery);
|
JavaScript
| 0.00128 |
@@ -642,53 +642,8 @@
ct')
-,%0A funcFormatSelection = undefined
;%0A%0A
|
a7c547cc507f8590761938291d397daef2f06afd
|
remove log
|
tests/json.js
|
tests/json.js
|
var path = require('path')
var test = require('tape')
var spawn = require('tape-spawn')
var helpers = require('./helpers')
var tmp = require('os').tmpdir()
var dat = path.resolve(__dirname + '/../cli.js')
var csvA = path.resolve(__dirname + '/fixtures/a.csv')
var dat1 = helpers.randomTmpDir()
var dat2 = helpers.randomTmpDir()
var cleanup = helpers.onedat(dat1)
// purpose of this file is to test every command with --json to ensure consistent json output
// TODO
// export
// files
// forks
// get
// import
// init
// keys
// log
// merge
// pull
// push
// read
// replicate
// root
// serve
// write
test('cli: dat checkout --json', function (t) {
helpers.exec(dat + ' log --json --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
var first = JSON.parse(out.stdout.toString().split('\n')[0]).version
var st = spawn(t, dat + ' checkout ' + first + ' --json --path=' + dat1, {cwd: tmp, end: false})
st.stdout.match(new RegExp('"version":"' + first + '"'))
st.stderr.empty()
st.end(function () {
helpers.exec(dat + ' checkout latest --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
t.end()
})
})
})
})
test('cli: dat clone --json', function (t) {
var st = spawn(t, dat + ' clone ' + dat1 + ' ' + dat2 + ' --json', {cwd: tmp})
st.stdout.match(new RegExp('"cloned":true'))
st.stderr.empty()
st.end()
})
test('cli: dat datasets --json', function (t) {
var st = spawn(t, dat + ' datasets --json --path=' + dat1, {cwd: tmp})
st.stdout.match('{"datasets":["files"]}\n')
st.stderr.empty()
st.end()
})
test('cli: dat delete --json', function (t) {
helpers.exec(dat + ' import -d foo --key=key ' + csvA + ' --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
var st = spawn(t, dat + ' delete 1 -d foo --json --path=' + dat1, {cwd: tmp})
st.stdout.match(new RegExp('"deleted":"1"'))
st.stderr.empty()
st.end()
})
})
test('cli: dat destroy --json', function (t) {
var st = spawn(t, dat + ' destroy --no-prompt --json --path=' + dat1, {cwd: tmp, end: false})
st.stdout.match(new RegExp('"destroyed":true'))
st.stderr.empty()
st.end(function () {
helpers.exec(dat + ' init --no-prompt --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
t.end()
})
})
})
test('cli: dat diff --json', function (t) {
helpers.exec(dat + ' import -d foo --key=key ' + csvA + ' --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
helpers.exec(dat + ' log --json --path=' + dat1, {cwd: tmp}, function (err, out) {
if (err) return t.ifErr(err)
var first = JSON.parse(out.stdout.toString().split('\n')[1]).version
var st = spawn(t, dat + ' diff ' + first + ' --json --path=' + dat1, {cwd: tmp})
st.stdout.match(new RegExp('"change":3,"key":"1","value":{"key":"1","name":"max"},"dataset":"foo"'))
st.stderr.empty()
st.end()
})
})
})
test('cli: dat status --json', function (t) {
var st = spawn(t, dat + ' status --json --path=' + dat1, {cwd: tmp})
st.stdout.match(new RegExp('"files"'))
st.stdout.match(new RegExp('"rows"'))
st.stderr.empty()
st.end()
})
test('cli: cleanup', function (t) {
cleanup()
t.end()
})
|
JavaScript
| 0.000001 |
@@ -1624,32 +1624,55 @@
%0A st.end()%0A%7D)%0A%0A
+// currently broken%0A//
test('cli: dat d
@@ -1693,32 +1693,35 @@
function (t) %7B%0A
+//
helpers.exec(d
@@ -1807,32 +1807,35 @@
on (err, out) %7B%0A
+//
if (err) ret
@@ -1843,32 +1843,35 @@
rn t.ifErr(err)%0A
+//
var st = spa
@@ -1932,24 +1932,27 @@
%7Bcwd: tmp%7D)%0A
+//
st.stdou
@@ -1984,24 +1984,27 @@
ted%22:%221%22'))%0A
+//
st.stder
@@ -2005,32 +2005,35 @@
.stderr.empty()%0A
+//
st.end()%0A %7D
@@ -2029,21 +2029,27 @@
t.end()%0A
+//
%7D)%0A
+//
%7D)%0A%0Atest
@@ -2811,17 +2811,17 @@
t('%5Cn')%5B
-1
+0
%5D).versi
|
821c25cb6f981caf8d4add55b36aea4562dadf61
|
comment for future guys
|
public/js/lib/cartodb/dashboard/dashboard.js
|
public/js/lib/cartodb/dashboard/dashboard.js
|
/**
* entry point for dashboard
*/
$(function() {
var Dashboard = cdb.core.View.extend({
el: document.body,
events: {
'click a[href=#create_new]': 'show_dialog',
'click': 'onClickOut'
},
initialize: function() {
this._initModels();
this._initViews();
this.tables.fetch();
},
_initModels: function() {
this.tables = new cdb.admin.Tables();
},
_initViews: function() {
this.tableList = new cdb.admin.dashboard.TableList({
el: this.$('#tablelist'),
model: this.tables
});
// this.tableStats = new cdb.admin.dashboard.TableStats({
// el: this.$('#tablelist'),
// model: this.tables
// })
// D3 API Requests
var stats = this.stats = new cdb.admin.D3Stats({
el: this.$("div.stats")
});
// User menu
var user_menu = this.user_menu = new cdb.admin.UserMenu({
target: 'a.account',
model: {username: username},
template_base: "dashboard/views/settings_item"
})
.on("optionClicked",function(ev){})
cdb.god.bind("closeDialogs", user_menu.hide, user_menu);
this.$el.append(this.user_menu.render().el);
},
show_dialog: function() {
var dialog = new cdb.admin.CreateTableDialog();
this.$el.append(dialog.render().el);
dialog.open();
dialog.bind('importStarted', this._importStarted, this);
},
_importStarted: function(imp) {
var self = this;
imp.pollCheck();
imp.bind('importComplete', function(){
cdb.log.info("updating tables");
self.tables.fetch();
imp.unbind();
});
},
onClickOut: function(ev) {
cdb.god.trigger("closeDialogs");
}
});
var DashboardRouter = Backbone.Router.extend({
routes: {
'/': 'index'
},
index: function() {
}
});
cdb.init(function() {
var dashboard = new Dashboard();
var router = new DashboardRouter();
// expose to debug
window.dashboard = dashboard;
});
});
|
JavaScript
| 0 |
@@ -1665,24 +1665,84 @@
tion(imp) %7B%0A
+ //TODO: create dialog to show the import progress%0A
va
|
636841bb66b12bf99f129e16a53d86db610ebffb
|
Update test.js
|
tests/test.js
|
tests/test.js
|
var SpotifyPlayer = require('../index');
var spotify = new SpotifyPlayer({
spotify: {
clientId: 'b6ca0e1423e74fae862f59b320e646f2',
clientSecret: 'a5b0c12d8ea34bedb63d3bde12cb51c9'
}
});
spotify.init();
// wait for setting access token
var myVar = setTimeout(() => {
//spotify.playSong("*", "Ed Sheeran");
//spotify.playPlaylistBySearch("生氣");
//spotify.playByPlaylist('playlistmesg', '5C8KgLqJyJrxQ6BrfHEDSw');
spotify.playTopTracksForArtist('16s0YTFcyjP4kgFwt7ktrY');
}, 3000);
// Add another song after 10 seconds
var myVar2 = setTimeout(() => {
//spotify.playSong("seasons in the sun", "westlife");
spotify.nextSong();
//clearInterval(myVar2);
}, 10000);
|
JavaScript
| 0.000001 |
@@ -107,98 +107,34 @@
d: '
-b6ca0e1423e74fae862f59b320e646f2',%0A clientSecret: 'a5b0c12d8ea34bedb63d3bde12cb51c9
+',%0A clientSecret: '
'%0A
@@ -643,12 +643,13 @@
%0A%0A%7D, 10000);
+%0A
|
07d8a8270bb232aa8e9b4d0a77a455d90d4f66ed
|
Fix electron-packager gulp task
|
gulp/tasks/electron.js
|
gulp/tasks/electron.js
|
import proc from 'child_process';
import gulp from 'gulp';
import runSequence from 'run-sequence';
import packager from 'electron-packager';
import electron from 'electron';
import config from '../config';
const paths = config.paths;
gulp.task('run-electron-dev', cb => {
proc.spawn(electron, [paths.base], {stdio: 'inherit'})
.on('close', cb);
});
gulp.task('run-electron-prod', cb => {
proc.spawn(electron, [paths.dist], {stdio: 'inherit'})
.on('close', cb);
});
gulp.task('electron-packager', cb => {
packager({
dir: './dist/',
asar: true,
out: 'builds',
overwrite: true
}, cb);
});
gulp.task('dev-electron', cb => {
runSequence('dev', 'set-dev-node-env', 'run-electron-dev', cb);
});
gulp.task('dist-electron', cb => {
runSequence('build', 'set-prod-node-env', 'run-electron-prod', cb);
});
gulp.task('build-electron', cb => {
runSequence('build', 'set-dev-node-env', 'electron-packager', cb);
});
|
JavaScript
| 0.99866 |
@@ -541,17 +541,18 @@
ir:
-'./
+paths.
dist
-/'
,%0A
@@ -559,19 +559,20 @@
asar:
-tru
+fals
e,%0A o
|
30cb3ff80477dd73f9728c5a71451b2390d47c7a
|
Remove prerelease flag. (#1129)
|
.github/custom-scripts/create-release.js
|
.github/custom-scripts/create-release.js
|
function getFirstLine(message) {
const index = message.indexOf('\n');
if (index === -1) {
return message;
}
return message.slice(0, index);
}
async function getBody({ github, core, context, target }) {
const res = await github.repos.getLatestRelease({
owner: context.repo.owner,
repo: context.repo.repo,
});
const latestRelease = res.data;
const diff = await github.repos.compareCommits({
owner: context.repo.owner,
repo: context.repo.repo,
base: latestRelease.tag_name,
head: target,
});
const commits = diff.data.commits;
if (!commits.length) {
return 'No changes';
}
const format = (log) => `* ${log.title} (${log.hash}) ${log.name} <${log.email}>`;
const lines = commits.map((c) => {
const payload = {
title: getFirstLine(c.commit.message),
hash: c.sha.slice(0, 7),
name: c.commit.author.name,
email: c.commit.author.email,
};
return format(payload);
});
return lines.join('\n');
}
/**
* Create Github Release given the version (provided by a tag)
*/
async function createRelease({ context, core, github, sha, version }) {
const title = `### Release Note (${version})`;
const body = await getBody({ github, core, context, target: sha });
const releaseBody = `${title}\n\n${body}`;
const release = {
owner: context.repo.owner,
repo: context.repo.repo,
tag_name: version,
target_commitish: sha,
name: version,
body: releaseBody,
draft: false,
prelease: true,
};
await github.repos.createRelease(release);
}
module.exports = createRelease;
|
JavaScript
| 0 |
@@ -1294,16 +1294,113 @@
ody%7D%60;%0A%0A
+ // TODO: Update ChangeLog.md or perhaps take release body from manual%0A // ChangeLog updates.%0A%0A
const
@@ -1599,11 +1599,12 @@
se:
-tru
+fals
e,%0A
|
448c730a6b4815c379865f2df2041467e0e052d6
|
初始化 chat
|
js/app.shell.js
|
js/app.shell.js
|
app.shell = (function () {
var
configMap = {
anchor_schema_map : {
chat : { open : true, closed : true }
},
main_html : String() +
'<div class="app-shell-head">' +
'<div class="app-shell-head-logo"></div>' +
'<div class="app-shell-head-account"></div>' +
'<div class="app-shell-head-search"></div>' +
'</div>' +
'<div class="app-shell-main">' +
'<div class="app-shell-main-nav"></div>' +
'<div class="app-shell-main-content"></div>' +
'</div>' +
'<div class="app-shell-footer"></div>' +
'<div class="app-shell-chat"></div>' +
'<div class="app-shell-modal"></div>',
chat_extend_time : 1000,
chat_retract_time : 300,
chat_extend_height : 450,
chat_retract_height : 15,
chat_extended_title : '点击关闭',
chat_retracted_title : '点击展开'
},
stateMap = {
$container : null,
anchor_map : {},
is_chat_retracted : true
},
jqueryMap = {},
setJqueryMap, initModule, toggleChat, onClickChat, copyAnchorMap, changeAnchorPart, onHasChange;
copyAnchorMap = function () {
return $.extend( true, {}, stateMap.anchor_map );
};
changeAnchorPart = function ( arg_map ) {
var
anchor_map_revise = copyAnchorMap(),
bool_return = true,
key_name, key_name_dep;
KEYVAL:
for ( key_name in arg_map ) {
if (arg_map.hasOwnProperty( key_name ) ) {
if ( key_name.indexOf( '_' ) === 0 ) {
continue KEYVAL;
}
anchor_map_revise[key_name] = arg_map[key_name];
key_name_dep = '_' + key_name;
if ( arg_map[key_name_dep] ) {
anchor_map_revise[key_name_dep] = arg_map[key_name_dep];
}
else {
delete anchor_map_revise[key_name_dep];
delete anchor_map_revise['_s' + key_name_dep];
}
}
}
try {
$.uriAnchor.setAnchor( anchor_map_revise );
}
catch ( error ) {
$.uriAnchor.setAnchor( stateMap.anchor_map, null, true );
bool_return = false;
}
return bool_return;
};
onHasChange = function ( event ) {
var
anchor_map_previous = copyAnchorMap(),
anchor_map_proposed, _s_chat_previous, _s_chat_proposed, s_chat_proposed;
try {
anchor_map_proposed = $.uriAnchor.makeAnchorMap();
}
catch ( error ) {
$.uriAnchor.setAnchor( anchor_map_proposed, null, true );
return false;
}
stateMap.anchor_map = anchor_map_proposed;
_s_chat_previous = anchor_map_previous._s_chat;
_s_chat_proposed = anchor_map_proposed._s_chat;
if ( ! anchor_map_previous || _s_chat_previous !== _s_chat_proposed ) {
s_chat_proposed = anchor_map_proposed.chat;
switch ( s_chat_proposed ) {
case 'open' :
toggleChat( true );
break;
case 'closed' :
toggleChat( false );
break;
default :
toggleChat( false );
delete anchor_map_proposed.chat;
$.uriAnchor.setAnchor( anchor_map_proposed, null, true );
}
}
return false;
};
setJqueryMap = function () {
var $container = stateMap.$container;
jqueryMap = {
$container : $container,
$chat : $container.find( '.app-shell-chat' )
};
};
toggleChat = function ( do_extrend, callback ) {
var
px_chat_ht = jqueryMap.$chat.height(),
is_open = px_chat_ht === configMap.chat_extend_height,
is_closed = px_chat_ht === configMap.chat_retract_height,
is_sliding = ! is_open && ! is_closed;
if ( is_sliding ) {
return false;
}
if ( do_extrend ) {
jqueryMap.$chat.animate(
{ height : configMap.chat_extend_height },
configMap.chat_extend_time,
function () {
jqueryMap.$chat.attr( 'title', configMap.chat_extended_title );
stateMap.is_chat_retracted = false;
if ( callback ) {
callback( jqueryMap.$chat );
}
}
);
return true;
}
jqueryMap.$chat.animate(
{ height : configMap.chat_retract_height },
configMap.chat_retract_time,
function () {
jqueryMap.$chat.attr( 'title', configMap.chat_retracted_title );
stateMap.is_chat_retracted = true;
if ( callback ) {
callback( jqueryMap.$chat );
}
}
);
return true;
};
onClickChat = function ( event ) {
changeAnchorPart({
chat : ( stateMap.is_chat_retracted ? 'open' : 'closed' )
});
return false;
};
initModule = function ( $container ) {
stateMap.$container = $container;
$container.html( configMap.main_html );
setJqueryMap();
stateMap.is_chat_retracted = true;
jqueryMap.$chat
.attr( 'title', configMap.chat_retracted_title )
.click( onClickChat );
};
$.uriAnchor.configModule({
schema_map : configMap.anchor_schema_map
});
$(window)
.bind( 'hashchange', onHasChange )
.trigger( 'hashchange' );
return { initModule : initModule };
} () );
|
JavaScript
| 0 |
@@ -6152,24 +6152,112 @@
%7D);%0A %0A
+ app.chat.configModule( %7B%7D );%0A app.chat.initModule( jqueryMap.$chat );%0A %0A
$(wind
|
120a8ce5d053f01a3247befd0bead1d4b37b51d7
|
Add options with initial callback parameter.
|
js/Interaction.js
|
js/Interaction.js
|
/**
* Interaction Class
*
* Defines an interaction between visualization children.
*
* An interaction has leaders, followers, and actions. Leaders fire events which
* are reacted to by followers as defined by actions.
*
* Options:
* leader - Child or children to lead the interaction
* event - Event to interact with
*
*/
(function () {
var E = Flotr.EventAdapter;
function Interaction(options) {
this.options = options = options || {};
this.actions = [];
this.followers = [];
this.leaders = [];
//this._initOptions();
//if (!options.leader) throw 'No leader.';
if (options.leader) {
this.lead(options.leader);
}
//this.leaders = (_.isArray(options.leader) ? options.leader : [options.leader]);
}
Interaction.prototype = {
getLeaders : function () {
return this.leaders;
},
getFollowers : function () {
return this.followers;
},
getActions : function () {
return this.actions;
},
lead : function (child) {
this.leaders.push(child);
_.each(this.actions, function (action) {
this._bindLeader(child, action);
}, this);
},
follow : function (child) {
this.followers.push(child);
},
group : function (children) {
if (!_.isArray(children)) children = [children];
_.each(children, function (child) {
this.lead(child);
this.follow(child);
}, this);
},
add : function (action) {
this.actions.push(action);
_.each(this.leaders, function (leader) {
this._bindLeader(leader, action);
}, this);
},
_bindLeader : function (leader, action) {
_.each(action.events, function (method, name) {
E.observe(leader.container, name, _.bind(action[method], this, leader));
}, this);
}
};
Humble.Vis.Interaction = Interaction;
})();
|
JavaScript
| 0 |
@@ -1389,32 +1389,41 @@
function (action
+, options
) %7B%0A this.act
@@ -1515,32 +1515,41 @@
r(leader, action
+, options
);%0A %7D, this);
@@ -1591,24 +1591,33 @@
ader, action
+, options
) %7B%0A _.ea
@@ -1711,36 +1711,273 @@
ind(
-action%5Bmethod%5D, this, leader
+function () %7B%0A var%0A args = %5Bleader%5D.concat(Array.prototype.slice.call(arguments)),%0A result = action%5Bmethod%5D.apply(this, args);%0A if (options && options.callback) %7B%0A options.callback.call(this, result);%0A %7D%0A %7D, this
));%0A
|
71e906ae9b9cd73ec97c19a5b70fc61d98b88126
|
Add ‘itemAdded’ listener on a list for dynamic reference in non-knockout data sources
|
js/layout/list.js
|
js/layout/list.js
|
(function registerListLayout(){
var dispatch = widget.layout.register( 'list', createListView, {
description: "Creates a list of widgets from a content array or from a data source"
}, {
styleClass: 'listPanel'
} );
function createItem( holder, item, listOptions, stack )
{
var options = {
listOptions: listOptions,
factory: listOptions.itemFactory
};
var itemView = widget.layout( holder, item, options, stack );
$(itemView).data( stack[0] );
return itemView;
}
function sort( def, holder )
{
if( def.options.sortBy )
{
$(holder).children().sortElements( function(a, b){
return def.options.sortBy( $(a).data(), $(b).data() );
});
}
}
/**
* Displays the footer only if there is no content in the given holder.
*/
function updateFooter( def, holder, footer )
{
if( footer.children().length )
{
if( !footer.parent().length )
holder.insertAfter( footer );
}
else
{
footer.detach();
}
var footerMode = widget.get( def, 'options.footerMode', 'emptyContent' );
if( footerMode == 'emptyContent' )
{
if( footer.children().length )
footer.toggle( (holder.children().length === 0) );
}
else
footer.toggle( true );
}
function createListView( def )
{
var parent = def.parent;
var listData = def.layout;
var listOptions = def.options;
var formKey = widget.get( def, 'options.form', false );
var panel = formKey ? $('<form/>' ) : $('<div/>' );
if( formKey )
{
if( $.type( formKey ) === 'string' )
panel.addClass( formKey );
panel.on( 'validate', function() {
var $validatables = panel.find( '.validate' );
$validatables.trigger( 'validate', def );
});
}
var holder = panel.appendTo( parent );
var footer = $('<div/>').addClass( listOptions.footerStyleClass || 'footer' ).appendTo( parent ).toggle( false );
$.each( ['max-width', 'margin-right'], function( i, key ) {
if( listOptions[ key ] )
panel.css( key, listOptions[key] );
});
var data = listData.content || [];
var dataStack = def.stack || [data];
if( def.data )
dataStack.unshift( def.data );
var layoutItem = function layoutItem( item ) {
var itemData;
if( item.data )
itemData = item.data;
else if( item.dataSource || def.layout.dataSource )
itemData = item;
if( itemData )
dataStack.unshift( itemData );
if( !(def.options) || !(def.options.filter) || (def.options.filter(item)) )
createItem( holder, item, listOptions, dataStack );
if( itemData )
dataStack.shift( itemData );
};
// if data is a knockout observable, add a listener
if( $.isFunction( data ) && $.isFunction( data.subscribe ) )
{
var resort = false;
data.subscribe( function onListChanged( changes ) {
for( var i=0; i<changes.length; i++ )
{
var change = changes[i];
if( change.status == 'added' )
{
layoutItem( change.value );
resort = true;
updateFooter( def, holder, footer );
}
else if( change.status == 'deleted' )
{
$("."+change.value._vuid).remove();
$( parent ).trigger( 'widget-update', def );
updateFooter( def, holder, footer );
}
else
console.error( "Unknown array change:", change.index, change.status, change.value );
}
if( resort )
sort( def, holder );
}, undefined, 'arrayChange' );
data = listData.content();
}
if( listOptions.holderClass )
holder = $('<div/>' ).addClass( listOptions.holderClass ).appendTo( panel );
$.each( data, function( i, item ) {
layoutItem( item );
} );
sort( def, holder );
panel.appendTo( parent );
footer.appendTo( parent );
if( listOptions.footerLayout )
widget.layout( footer, listOptions.footerLayout, {}, dataStack );
updateFooter( def, holder, footer );
panel.update = function( event, context ) {
sort( def, holder );
};
return panel;
}
})();
|
JavaScript
| 0 |
@@ -3690,24 +3690,208 @@
t();%0A %7D%0A%0A
+ panel.on( 'itemAdded', function( event, newItem ) %7B%0A layoutItem( newItem );%0A updateFooter( def, holder, footer );%0A sort( def, holder );%0A return false;%0A %7D);%0A%0A
if( list
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.