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
|
---|---|---|---|---|---|---|---|
c64ed24082c0543f70d7a20920638e30ad80e5bc
|
remove unused function
|
src/plug.js
|
src/plug.js
|
'use strict';
const Device = require('./device');
class Plug extends Device {
constructor (options) {
super(options);
if (typeof options === 'undefined') options = {};
this.log.debug('plug.constructor()');
this.apiModuleNamespace = {
'system': 'system',
'cloud': 'cnCloud',
'schedule': 'schedule',
'timesetting': 'time',
'emeter': 'emeter',
'netif': 'netif'
};
this.inUseThreshold = options.inUseThreshold || 0;
this.lastState = Object.assign(this.lastState, { powerOn: null, inUse: null });
this.emitEventsEnabled = true;
}
get sysInfo () {
return super.sysInfo;
}
set sysInfo (sysInfo) {
super.sysInfo = sysInfo;
this.log.debug('[%s] plug sysInfo set', this.name);
this.emitEvents();
}
get consumption () { return this._consumption; }
set consumption (consumption) {
this.log.debug('[%s] plug consumption set', this.name);
this._consumption = consumption;
if (this.supportsConsumption) {
this.emitEvents();
}
}
get inUse () {
if (this.supportsConsumption) {
return (this.consumption.power > this.inUseThreshold);
} else {
return (this.sysInfo.relay_state === 1);
}
}
async getInUse () {
if (this.supportsConsumption) {
let consumption = await this.getConsumption();
return (consumption.power > this.inUseThreshold);
}
let si = await this.getSysInfo();
return (si.relay_state === 1);
}
emitEvents () {
if (!this.emitEventsEnabled) { return; }
const inUse = this.inUse;
const powerOn = (this.sysInfo.relay_state === 1);
this.log.debug('[%s] plug.emitEvents() inUse: %s powerOn: %s lastState: %j', this.name, inUse, powerOn, this.lastState);
if (this.lastState.inUse !== inUse) {
this.lastState.inUse = inUse;
if (inUse) {
this.emit('in-use', this, inUse);
} else {
this.emit('not-in-use', this, inUse);
}
} else {
this.emit('in-use-update', this, inUse);
}
if (this.lastState.powerOn !== powerOn) {
this.lastState.powerOn = powerOn;
if (powerOn) {
this.emit('power-on', this, powerOn);
} else {
this.emit('power-off', this, powerOn);
}
} else {
this.emit('power-update', this, powerOn);
}
if (this.supportsConsumption) {
this.emit('consumption-update', this, this.consumption);
}
}
async getInfo () {
let data = await this.send('{"emeter":{"get_realtime":{}},"schedule":{"get_next_action":{}},"system":{"get_sysinfo":{}},"cnCloud":{"get_info":{}}}');
this.sysInfo = data.system.get_sysinfo;
this.cloudInfo = data.cnCloud.get_info;
this.consumption = data.emeter.get_realtime;
this.scheduleNextAction = data.schedule.get_next_action;
return {sysInfo: this.sysInfo, cloudInfo: this.cloudInfo, consumption: this.consumption, scheduleNextAction: this.scheduleNextAction};
}
async getSysInfoAndConsumption () {
let data = await this.sendCommand('{"emeter":{"get_realtime":{}},"system":{"get_sysinfo":{}}}');
this.sysInfo = data.system.get_sysinfo;
this.consumption = data.emeter.get_realtime;
return {sysInfo: this.sysInfo, consumption: this.consumption};
}
async getPowerState () {
let sysInfo = await this.getSysInfo();
return (sysInfo.relay_state === 1);
}
async setPowerState (value) {
this.log.debug('[%s] plug.setPowerState(%s)', this.name, value);
await this.sendCommand(`{"system":{"set_relay_state":{"state":${(value ? 1 : 0)}}}}`);
this.sysInfo.relay_state = (value ? 1 : 0);
this.emitEvents();
return true;
}
async getAwayRules () {
return this.sendCommand(`{"anti_theft":{"get_rules":{}}}`);
}
async getTimerRules () {
return this.sendCommand(`{"count_down":{"get_rules":{}}}`);
}
async getLedState () {
let sysInfo = await this.getSysInfo();
return (sysInfo.led_off === 0);
}
async setLedState (value) {
await this.sendCommand(`{"system":{"set_led_off":{"off":${(value ? 0 : 1)}}}}`);
this.sysInfo.set_led_off = (value ? 0 : 1);
return true;
}
async blink (times = 5, rate = 1000) {
let delay = (t) => { return new Promise((resolve) => { setTimeout(resolve, t); }); };
let origLedState = await this.getLedState();
let lastBlink = Date.now();
let currLedState = false;
for (var i = 0; i < times * 2; i++) {
currLedState = !currLedState;
lastBlink = Date.now();
await this.setLedState(currLedState);
let timeToWait = (rate / 2) - (Date.now() - lastBlink);
if (timeToWait > 0) {
await delay(timeToWait);
}
}
if (currLedState !== origLedState) {
await this.setLedState(origLedState);
}
return true;
}
}
module.exports = Plug;
|
JavaScript
| 0.000016 |
@@ -2949,312 +2949,8 @@
%7D%0A%0A
- async getSysInfoAndConsumption () %7B%0A let data = await this.sendCommand('%7B%22emeter%22:%7B%22get_realtime%22:%7B%7D%7D,%22system%22:%7B%22get_sysinfo%22:%7B%7D%7D%7D');%0A this.sysInfo = data.system.get_sysinfo;%0A this.consumption = data.emeter.get_realtime;%0A return %7BsysInfo: this.sysInfo, consumption: this.consumption%7D;%0A %7D%0A%0A
as
|
94f85ab2ed3aff89aa5f167ab6c17c58978e5659
|
Fix Display.js so it doesn't double add elements.
|
src/scripts/classes/Display.class.js
|
src/scripts/classes/Display.class.js
|
/**
* Displays class
* Takes an applicant display json and adds convienece methods for getting
* info
*
* @param {} obj
* @param {Application} application
*/
function Display(obj, application){
var self = this;
this.display = obj;
this.application = application;
};
/**
* Get the display objext
*/
Display.prototype.getObj = function(){
return this.display;
};
/**
* Get the display objext
*/
Display.prototype.getApplication = function(){
return this.application;
};
/**
* List the elements
*/
Display.prototype.listElements = function(){
return this.display.elements;
};
/**
* Get the display name
*/
Display.prototype.getName = function(){
return this.display.name;
};
/**
* Set the display name
* @param String name
*/
Display.prototype.setName = function(name){
this.display.name = name;
};
/**
* Get the display type
*/
Display.prototype.getType = function(){
return this.display.type;
};
/**
* Get the display name
*/
Display.prototype.getId = function(){
return this.display.id;
};
/**
* Check if a page should be displayed
*/
Display.prototype.displayPage = function(pageId){
return ($.inArray(pageId, this.display.pages) > -1);
};
/**
* Check if an element should be displayed
* @param type
* @param name
*/
Display.prototype.displayElement = function(obj){
var matches = $.grep(this.display.elements, function(element) {
switch(obj.type){
case 'applicant':
case 'element':
return element.type == obj.type && element.name == obj.name;
break;
case 'page':
return element.type == obj.type && element.name == obj.name && element.pageId == obj.pageId;
break;
}
});
return (matches.length > 0);
};
/**
* Check if an element should be displayed
*/
Display.prototype.addElement = function(obj){
if(this.displayElement(obj.type, obj.name)){
this.removeElement(obj);
}
this.display.elements.push(obj);
};
/**
* Remove an element from the display
*/
Display.prototype.removeElement = function(obj){
if(this.displayElement(obj)){
this.display.elements = $.grep(this.display.elements, function(element) {
switch(obj.type){
case 'applicant':
case 'element':
return element.type != obj.type || element.name != obj.name;
break;
case 'page':
return element.type != obj.type || element.name != obj.name || element.pageId != obj.pageId;
break;
}
});
}
};
|
JavaScript
| 0 |
@@ -1865,23 +1865,8 @@
(obj
-.type, obj.name
))%7B%0A
|
5994d7c05c854dd2211bf8b50fb8e57d2694ffb0
|
Fix fallback if secret is missing
|
src/services/authentication/index.js
|
src/services/authentication/index.js
|
'use strict';
const auth = require('feathers-authentication');
const jwt = require('feathers-authentication-jwt');
const local = require('feathers-authentication-local');
const logger = require('winston');
const system = require('./strategies/system');
const hooks = require('./hooks');
let authenticationSecret = null;
try {
authenticationSecret = require("../../../config/secrets.json").authentication;
} catch (e) {
logger.log('warn', 'Could not read authentication secret, using insecure default value.');
}
module.exports = function() {
const app = this;
const authConfig = Object.assign({}, app.get('auth'), {
header: 'Authorization',
entity: 'account',
service: 'accounts',
jwt: {
header: { typ: 'access' },
audience: 'https://schul-cloud.org',
subject: 'anonymous',
issuer: 'feathers',
algorithm: 'HS256',
expiresIn: '30d'
},
secret: authenticationSecret
});
const localConfig = {
name: 'local',
entity: 'account',
service: 'accounts',
// TODO: change username to unique identifier as multiple
// users can have same username in different services
usernameField: 'username',
passwordField: 'password'
};
const jwtConfig = {
name: 'jwt',
entity: 'account',
service: 'accounts',
header: 'Authorization'
};
if(authenticationSecret) {
Object.assign(jwtConfig, {secretOrKey: authenticationSecret});
}
// Configure feathers-authentication
app.configure(auth(authConfig));
app.configure(jwt(jwtConfig));
app.configure(local(localConfig));
app.configure(system({
name: 'moodle',
loginStrategy: require('../account/strategies/moodle')
}));
app.configure(system({
name: 'lernsax',
loginStrategy: require('../account/strategies/lernsax')
}));
app.configure(system({
name: 'itslearning',
loginStrategy: require('../account/strategies/itslearning')
}));
const authenticationService = app.service('authentication');
// TODO: feathers-swagger
/*
authenticationService.docs = {
description: 'A service to send and receive messages',
create: {
//type: 'Example',
parameters: [{
description: 'username or email',
//in: 'path',
required: true,
name: 'username',
type: 'string'
},
{
description: 'password',
//in: 'path',
required: false,
name: 'password',
type: 'string'
},
{
description: 'ID of the system that acts as a login provider. Required for new accounts or accounts with non-unique usernames.',
//in: 'path',
required: false,
name: 'systemId',
type: 'string'
}],
summary: 'Log in with or create a new account',
notes: 'Returns a JSON Web Token for the associated user in case of success.'
//errorResponses: []
}
};*/
// Set up our hooks
authenticationService.hooks({
before: hooks.before,
after: hooks.after
});
};
|
JavaScript
| 0.000005 |
@@ -314,12 +314,16 @@
t =
-null
+%22secret%22
;%0Atr
@@ -1281,69 +1281,12 @@
ion'
-%0A%09%7D;%0A%09if(authenticationSecret) %7B%0A%09%09Object.assign(jwtConfig, %7B
+,%0A%09%09
secr
@@ -1318,14 +1318,13 @@
cret
-%7D);
%0A%09%7D
+;%0A
%0A%0A%09/
|
15e679b9bf2c1f60fc397ce5bc8df4239d2f8f0f
|
remove display inline-block… again
|
src/slate/block-decorators/resize.js
|
src/slate/block-decorators/resize.js
|
import React, { Component, PropTypes } from 'react';
import { throttleInput } from 'olymp';
import { findDOMNode } from 'react-dom';
import { DraggableCore } from 'react-draggable';
import cn from 'classnames';
const Cover = ({ children, style }) => (
<div style={{ backgroundColor: 'black', position: 'absolute', top: 0, left: 0, width: '100%', height: '100%', zIndex: 3 }}>{children}</div>
);
export default (options = {}) => Block => {
const { coverOnResize, enable, resizeX, resizeY, width: initialWidth, height: initialHeight } = options;
return class ResizeableDecorator extends Component {
throttle = throttleInput();
static slate = Block.slate;
static propTypes = {
getData: PropTypes.func,
setData: PropTypes.func,
editor: PropTypes.object,
style: PropTypes.object,
}
static defaultProps = {
style: {},
}
constructor(props) {
super(props);
const { getData } = props;
this.state = {
resize: false,
width: getData('width', initialWidth),
height: getData('height', initialHeight),
};
}
componentDidMount() {
this.element = findDOMNode(this.block);
}
onResizeStart = () => {
this.setState({ resize: true });
}
onResizeStop = (event, { deltaX, deltaY }) => {
const { setData } = this.props;
const newState = {};
if (this.state.width) newState.width = this.state.width;
if (this.state.height) newState.height = this.state.height;
setData(newState);
this.setState({ resize: false });
}
onResize = (event, { deltaX, deltaY, x, y }) => {
const { getData, alignment } = this.props;
const elementDimensions = this.element.getBoundingClientRect();
const newState = {};
if (resizeX !== false) {
const width = x ? (alignment === 'right' ? (elementDimensions.width - x) : x) : getData('width', initialWidth);
const relWidth = Math.round(12 / elementDimensions.width * width);
if (relWidth >= 0) newState.width = relWidth;
}
if (resizeY !== false) {
const height = y || getData('width', initialWidth);
if (height >= 0) newState.height = height;
}
if (newState.height !== this.state.height || newState.width !== this.state.width) {
this.setState(newState);
}
}
render() {
if (enable === false) return <Block {...this.props} />;
const { editor, alignment, style, className } = this.props;
const { resize, height, width } = this.state;
const children = editor.props.readOnly ? this.props.children : [
...this.props.children,
resize && coverOnResize ? <Cover key="resizableCover" /> : null,
<DraggableCore key="resizableHandle" onStop={this.onResizeStop} onStart={this.onResizeStart} onDrag={this.onResize}>
<span className={cn('react-resizable-handle', alignment === 'right' ? 'handle-left' : 'handle-right')} />
</DraggableCore>,
];
const blockStyle = {
...style,
display: 'inline-block'
};
if (height) blockStyle.height = `${height}px`;
return (
<Block {...this.props} style={blockStyle} className={cn(width && `p-0 col-xs-${width}`, className)} ref={e => this.block = e}>
{children}
</Block>
);
}
};
};
|
JavaScript
| 0 |
@@ -3057,16 +3057,19 @@
%0A
+ //
display
|
a66c1c9239cdebd7855daa399c1b1db65800337f
|
Set default user name to 'You'.
|
src/roll.js
|
src/roll.js
|
const qs = require('qs');
module.exports.handler = (event, context, callback) => {
/** Immediate response for WarmUP plugin */
if (event.source === 'serverless-plugin-warmup') {
console.log('WarmUP - Lambda is warm!');
return callback(null, 'Lambda is warm!');
}
const body = qs.parse(event.body);
const result = body.text === 'coin'
? `:coin_${Math.floor((Math.random() * 2) + 1)}:`
: `:dice_${Math.floor((Math.random() * 6) + 1)}:`;
const response = {
statusCode: 200,
headers: {
// Required for CORS support to work
'Access-Control-Allow-Origin': '*',
// Required for cookies, authorization headers with HTTPS
'Access-Control-Allow-Credentials': true,
'Content-type': 'application/json',
},
body: JSON.stringify({
response_type: 'in_channel',
text: `@${body.user_name} just rolled: ${result}`,
}),
};
callback(null, response);
};
|
JavaScript
| 0.000011 |
@@ -852,16 +852,25 @@
ser_name
+ %7C%7C 'You'
%7D just r
|
3c91d244ea5fa6c467405c36edba0e8d07461f7a
|
Fix JSCS
|
addon/routes/fd-visual-edit-form.js
|
addon/routes/fd-visual-edit-form.js
|
import Ember from 'ember';
import { Query } from 'ember-flexberry-data';
const { Builder } = Query;
export default Ember.Route.extend({
currentProjectContext: Ember.inject.service('fd-current-project-context'),
formId: null,
classId: null,
beforeModel: function(params) {
this.formId = params.queryParams.formId;
this.classId = params.queryParams.classId;
},
model() {
let store = this.get('store');
let stagePk = this.get('currentProjectContext').getCurrentStage();
let promise = new Ember.RSVP.Promise((resolve, reject) => {
let fdControlModel = store.createRecord('fd-visual-edit-control',
{
isSelected: true,
name: 'Some control',
notNullable: true,
});
let editFormModel = store.createRecord('fd-visual-edit-form', {});
editFormModel.get('controls').pushObject(fdControlModel);
let modelBuilder = new Builder(this.store, 'fd-dev-class').
selectByProjection('EditFormView').
byId(this.formId);
this.store.query('fd-dev-class', modelBuilder.build()).then((data)=> {
editFormModel.set('id', this.formId);
editFormModel.set('name', data.objectAt(0).get('name'));
editFormModel.set('description', data.objectAt(0).get('description'));
resolve(editFormModel);
}).catch(reject);
});
return promise;
},
setupController: function(controller, model) {
this._super(controller, model);
},
});
|
JavaScript
| 0.000223 |
@@ -135,86 +135,8 @@
(%7B%0A%0A
- currentProjectContext: Ember.inject.service('fd-current-project-context'),%0A%0A
fo
@@ -348,79 +348,8 @@
e');
-%0A let stagePk = this.get('currentProjectContext').getCurrentStage();
%0A%0A
@@ -1207,16 +1207,18 @@
romise;%0A
+
%7D,%0A%0A se
|
2d5402869babdc2420b63d40b99587dbb1746df1
|
Fix task directory
|
src/task.js
|
src/task.js
|
'use strict';
var _ = require('lodash');
var gulp = require('gulp');
exports.register = function (name, src, dest, options) {
var task = _.defaults(require('./tasks/' + name), {
src: true,
dest: true
});
gulp.task(name, function () {
var input;
if (task.src) input = task.options.rawSrc ? src : gulp.src(src, task.srcOptions);
var result = task(input, options);
if (task.dest) return result.pipe(gulp.dest(dest));
return result;
});
};
|
JavaScript
| 0.000017 |
@@ -158,16 +158,17 @@
quire('.
+.
/tasks/'
|
89bc3762eaa37cd1376329682dd68118e3ff07c6
|
check for invalid rule configs
|
src/test.js
|
src/test.js
|
import defRules from './rules'
import util from './util'
const allDevices = Object.keys(util.devices).map(key => util.devices[key])
const severity = function (val) {
switch (val) {
case 0:
case 'off':
return 'off'
case 1:
case 'warn':
return 'warn'
case 2:
case 'error':
return 'error'
default:
throw new Error(`react-a11y: invalid severity ${val}`)
}
}
const normalize = function (opts = 'off') {
if ( Array.isArray(opts) ) {
opts[0] = severity(opts[0])
return opts
} else {
return [ severity(opts) ]
}
}
export default class Suite {
constructor (React, options) {
this.options = options
this.React = React
this.ReactDOM = this.options.ReactDOM
if (!this.React && !this.React.createElement) {
throw new Error('Missing parameter: React')
}
const {
plugins = []
} = this.options
// prepare all rules by including every plugin and saving their rules
// namespaced like plugin/rule
this.rules = plugins
.map(function (name) {
try {
const mod = require(`react-a11y-plugin-${name}`)
const rules = 'default' in mod ? mod.default : mod
return Object.keys(rules).reduce((acc, key) => ({
...acc
, [`${name}/${key}`]: rules[key]
}), {})
} catch (err) {
throw new Error(`Could not find react-a11y-plugin-${name}`)
}
})
.reduce((acc, next) => ({ ...acc, ...next }), defRules)
}
test (tagName, props, children, done) {
Object.keys(this.rules)
.forEach(function (key) {
// find ruleopts
const opts = normalize(this.options.rules[key])
const [
sev
, ...options
] = opts
if ( sev !== 'off' ) {
const ctx = {
report (info) {
const {
devices = allDevices
} = info
// TODO: fix this and failureHandler to accept all info
// TODO: add ability to ignore by device class
done({
...info
, tagName
, props
, severity: sev
})
}
, options
, React: this.React
, ReactDOM: this.ReactDOM
}
const tests = this.rules[key](ctx)
if ( tagName in tests ) {
tests[tagName](props, children)
} else if ( '_any_' in tests ) {
tests._any_(tagName, props, children)
}
}
}.bind(this))
}
}
|
JavaScript
| 0 |
@@ -1590,24 +1590,32 @@
t.keys(this.
+options.
rules)%0A
@@ -2388,24 +2388,212 @@
%7D%0A%0A
+ if ( !(key in this.rules) ) %7B%0A throw new Error(%60react-a11y: rule $%7Bkey%7D not found,%60%0A + %60maybe you're missing a plugin?%60)%0A %7D%0A%0A
|
9867ebafe0c56f27a6ed3964118c086aae3d5ab4
|
Fix #376 - Delay component had memory leak Now removes triggered events from _delays array
|
src/time.js
|
src/time.js
|
/**@
* #Crafty Time
* @category Utilities
*/
Crafty.c("Delay", {
init : function() {
this._delays = [];
this.bind("EnterFrame", function() {
var now = new Date().getTime();
for(var index in this._delays) {
var item = this._delays[index];
if(!item.triggered && item.start + item.delay + item.pause < now) {
item.triggered=true;
item.func.call(this);
}
}
});
this.bind("Pause", function() {
var now = new Date().getTime();
for(var index in this._delays) {
this._delays[index].pauseBuffer = now;
}
});
this.bind("Unpause", function() {
var now = new Date().getTime();
for(var index in this._delays) {
var item = this._delays[index];
item.pause += now-item.pauseBuffer;
}
});
},
/**@
* #.delay
* @comp Crafty Time
* @sign public this.delay(Function callback, Number delay)
* @param callback - Method to execute after given amount of milliseconds
* @param delay - Amount of milliseconds to execute the method
*
* The delay method will execute a function after a given amount of time in milliseconds.
*
* It is not a wrapper for `setTimeout`.
*
* If Crafty is paused, the delay is interrupted with the pause and then resume when unpaused
*
* If the entity is destroyed, the delay is also destroyed and will not have effect.
*
* @example
* ~~~
* console.log("start");
* this.delay(function() {
console.log("100ms later");
* }, 100);
* ~~~
*/
delay : function(func, delay) {
return this._delays.push({
start : new Date().getTime(),
func : func,
delay : delay,
triggered : false,
pauseBuffer: 0,
pause: 0
});
}
});
|
JavaScript
| 0 |
@@ -172,32 +172,33 @@
etTime();%0A%09%09%09for
+
(var index in th
@@ -184,34 +184,44 @@
%09for (var index
-in
+= 0; index %3C
this._delays) %7B
@@ -209,32 +209,48 @@
x %3C this._delays
+.length; index++
) %7B%0A%09%09%09%09var item
@@ -284,27 +284,8 @@
%09if(
-!item.triggered &&
item
@@ -340,49 +340,103 @@
tem.
-triggered=true;%0A%09%09%09%09%09item.func.call(this)
+func.call(this);%0A%09%09%09%09%09// remove item from array%0A%09%09%09%09%09this._delays.splice(index,1);%0A%09%09%09%09%09index--
;%0A%09%09
@@ -807,20 +807,17 @@
%7D);%0A%09%7D,%0A
-
+%09
/**@%0A%09*
@@ -1443,20 +1443,17 @@
on() %7B%0A%09
-
+%09
console
@@ -1629,30 +1629,8 @@
ay,%0A
-%09%09%09triggered : false,%0A
%09%09%09p
|
90c74cb7b8060833b127ea68ef7f09a71b2a1daa
|
Fix surrogate range calculation
|
src/util.js
|
src/util.js
|
// -*- Mode: js; indent-tabs-mode: nil; c-basic-offset: 4; tab-width: 4 -*-
//
// Copyright (c) 2013 Giovanni Campagna <[email protected]>
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
// * Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
// * Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in the
// documentation and/or other materials provided with the distribution.
// * Neither the name of the GNOME Foundation nor the
// names of its contributors may be used to endorse or promote products
// derived from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
// DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
const Gdk = imports.gi.Gdk;
const Gio = imports.gi.Gio;
const GObject = imports.gi.GObject;
const Gtk = imports.gi.Gtk;
const Lang = imports.lang;
const Params = imports.params;
const System = imports.system;
function loadUI(resourcePath, objects) {
let ui = new Gtk.Builder();
if (objects) {
for (let o in objects)
ui.expose_object(o, objects[o]);
}
ui.add_from_resource(resourcePath);
return ui;
}
function loadStyleSheet(resource) {
let provider = new Gtk.CssProvider();
provider.load_from_file(Gio.File.new_for_uri('resource://' + resource));
Gtk.StyleContext.add_provider_for_screen(Gdk.Screen.get_default(),
provider,
Gtk.STYLE_PROVIDER_PRIORITY_APPLICATION);
}
function initActions(actionMap, simpleActionEntries, context) {
simpleActionEntries.forEach(function(entry) {
let filtered = Params.filter(entry, { activate: null,
state_changed: null,
context: null });
let action = new Gio.SimpleAction(entry);
let context = filtered.context || actionMap;
if (filtered.activate)
action.connect('activate', filtered.activate.bind(context));
if (filtered.state_changed)
action.connect('state-changed', filtered.state_changed.bind(context));
actionMap.add_action(action);
});
}
function arrayEqual(one, two) {
if (one.length != two.length)
return false;
for (let i = 0; i < one.length; i++)
if (one[i] != two[i])
return false;
return true;
}
function getSettings(schemaId, path) {
const GioSSS = Gio.SettingsSchemaSource;
let schemaSource;
if (!pkg.moduledir.startsWith('resource://')) {
// Running from the source tree
schemaSource = GioSSS.new_from_directory(pkg.pkgdatadir,
GioSSS.get_default(),
false);
} else {
schemaSource = GioSSS.get_default();
}
let schemaObj = schemaSource.lookup(schemaId, true);
if (!schemaObj) {
log('Missing GSettings schema ' + schemaId);
System.exit(1);
}
if (path === undefined)
return new Gio.Settings({ settings_schema: schemaObj });
else
return new Gio.Settings({ settings_schema: schemaObj,
path: path });
}
function loadIcon(iconName, size) {
let theme = Gtk.IconTheme.get_default();
return theme.load_icon(iconName,
size,
Gtk.IconLookupFlags.GENERIC_FALLBACK);
}
function assertEqual(one, two) {
if (one != two)
throw Error('Assertion failed: ' + one + ' != ' + two);
}
function assertNotEqual(one, two) {
if (one == two)
throw Error('Assertion failed: ' + one + ' == ' + two);
}
function capitalize(s) {
return s.split(/\s+/).map(function(w) {
if (w.length > 0)
return w[0].toUpperCase() + w.slice(1).toLowerCase();
return w;
}).join(' ');
}
function toCodePoint(s) {
let codePoint = s.charCodeAt(0);
if (codePoint > 0xD800) {
let high = codePoint;
let low = s.charCodeAt(1);
codePoint = 0x10000 + (high - 0xD800) * 0x400 + (low - 0xDC00);
}
return codePoint;
}
|
JavaScript
| 0.000012 |
@@ -4927,23 +4927,47 @@
ePoint %3E
+=
0xD800
+ && codePoint %3C= 0xDBFF
) %7B%0A
|
cdeb9febbf246dfd49fa9bc4b310b9c85dc346c3
|
check for 200
|
src/util.js
|
src/util.js
|
var request = require("request");
var _globals = {
apikey: null,
realm: null,
region: null
};
var gen_url = function (options, type, cb) {
var region_p = options.region || _globals.region || "EU";
var realm_p = options.realm || _globals.realm || false;
var apikey_p = options.apikey || _globals.apikey || false;
var name = options.name || false;
if (!realm_p){
cb("ERROR: No realm given");
return false;
}
if (!apikey_p){
cb("ERROR: No apikey given");
return false;
}
if (!name){
cb("ERROR: No name given");
return false;
}
var baseUrl = "https://:region:.api.battle.net/wow/:type:/:realm:/:name:?locale=en_GB&apikey=:apikey:&fields=:fields:";
return baseUrl
.replace(":type:", type)
.replace(":region:", encodeURIComponent(region_p))
.replace(":realm:", encodeURIComponent(realm_p))
.replace(":name:", encodeURIComponent(name))
.replace(":apikey:", apikey_p);
};
var do_request = function (url, cb) {
request(url, function (error, response, body) {
var data = JSON.parse(body);
var errorMsg = null;
if (!error && data.status === "nok")
errorMsg = "ERROR: " + data.reason;
if (error) errorMsg = error;
return cb(errorMsg, data);
});
};
module.exports = {
"_globals": _globals,
"gen_url": gen_url,
"do_request": do_request
};
|
JavaScript
| 0 |
@@ -1097,24 +1097,134 @@
se, body) %7B%0A
+ if(response !== 200)%7B%0A cb(%22ERROR: HTTP RESPONSE %22+response);%0A return;%0A %7D%0A
var
|
9b53660a69cf4f0c180f54bbc9228e17c0cd0617
|
add command for znc command execution
|
plugins/znc.js
|
plugins/znc.js
|
function ZNCPlugin(bot) {
var self = this;
self.name = "znc";
self.help = "ZNC plugin";
self.depend = [];
self.zncRe = /^([^!\s]+)!([^@\s]+)@znc\.in$/;
self.events = {
"message": function(nick, to, text, message) {
var match = message.prefix.match(self.zncRe);
if (match) {
bot.out.log("znc", match[1] + ": " + text);
}
}
};
}
module.exports = ZNCPlugin;
|
JavaScript
| 0.000065 |
@@ -100,16 +100,29 @@
pend = %5B
+%22cmd%22, %22auth%22
%5D;%0A%0A%09sel
@@ -352,16 +352,127 @@
%09%09%09%7D%0A%09%09%7D
+,%0A%0A%09%09%22cmd#znc%22: bot.plugins.auth.proxyEvent(10, function(nick, to, args) %7B%0A%09%09%09bot.say(%22*status%22, args%5B0%5D);%0A%09%09%7D)
%0A%09%7D;%0A%7D%0A%0A
|
d6f47d36d28b7de83a1e976f0c6b2ee38b0a4362
|
Update Tocca.js
|
Tocca.js
|
Tocca.js
|
/**
*
* Version: 0.1.3
* Author: Gianluca Guarini
* Contact: [email protected]
* Website: http://www.gianlucaguarini.com/
* Twitter: @gianlucaguarini
*
* Copyright (c) Gianluca Guarini
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
**/
(function(doc, win) {
'use strict';
if (typeof doc.createEvent !== 'function') return false; // no tap events here
// helpers
var useJquery = typeof jQuery !== 'undefined',
// some helpers borrowed from https://github.com/WebReflection/ie-touch
msPointerEnabled = !!navigator.pointerEnabled || navigator.msPointerEnabled,
isTouch = (!!('ontouchstart' in win) && navigator.userAgent.indexOf('PhantomJS') < 0) || msPointerEnabled,
msEventType = function(type) {
var lo = type.toLowerCase(),
ms = 'MS' + type;
return navigator.msPointerEnabled ? ms : lo;
},
touchevents = {
touchstart: msEventType('PointerDown') + ' touchstart',
touchend: msEventType('PointerUp') + ' touchend',
touchmove: msEventType('PointerMove') + ' touchmove'
},
setListener = function(elm, events, callback) {
var eventsArray = events.split(' '),
i = eventsArray.length;
while (i--) {
elm.addEventListener(eventsArray[i], callback, false);
}
},
getPointerEvent = function(event) {
return event.targetTouches ? event.targetTouches[0] : event;
},
getTimestamp = function () {
return new Date().getTime();
},
sendEvent = function(elm, eventName, originalEvent, data) {
var customEvent = doc.createEvent('Event');
data = data || {};
data.x = currX;
data.y = currY;
data.distance = data.distance;
if (useJquery)
jQuery(elm).trigger(eventName, data);
else {
customEvent.originalEvent = originalEvent;
for (var key in data) {
customEvent[key] = data[key];
}
customEvent.initEvent(eventName, true, true);
elm.dispatchEvent(customEvent);
}
},
onTouchStart = function(e) {
var pointer = getPointerEvent(e);
// caching the current x
cachedX = currX = pointer.pageX;
// caching the current y
cachedY = currY = pointer.pageY;
timestamp = getTimestamp();
tapNum++;
// we will use these variables on the touchend events
},
onTouchEnd = function(e) {
var eventsArr = [],
deltaY = cachedY - currY,
deltaX = cachedX - currX;
// clear the previous timer in case it was set
clearTimeout(tapTimer);
if (deltaX <= -swipeThreshold)
eventsArr.push('swiperight');
if (deltaX >= swipeThreshold)
eventsArr.push('swipeleft');
if (deltaY <= -swipeThreshold)
eventsArr.push('swipedown');
if (deltaY >= swipeThreshold)
eventsArr.push('swipeup');
if (eventsArr.length) {
for (var i = 0; i < eventsArr.length; i++) {
var eventName = eventsArr[i];
sendEvent(e.target, eventName, e, {
distance: {
x: Math.abs(deltaX),
y: Math.abs(deltaY)
}
});
}
} else {
if (
(timestamp + tapThreshold) - getTimestamp() >= 0 &&
cachedX >= currX - tapPrecision &&
cachedX <= currX + tapPrecision &&
cachedY >= currY - tapPrecision &&
cachedY <= currY + tapPrecision
) {
// Here you get the Tap event
sendEvent(e.target, (tapNum === 2) ? 'dbltap' : 'tap', e);
}
// reset the tap counter
tapTimer = setTimeout(function() {
tapNum = 0;
}, dbltapThreshold);
}
},
onTouchMove = function(e) {
var pointer = getPointerEvent(e);
currX = pointer.pageX;
currY = pointer.pageY;
},
swipeThreshold = win.SWIPE_THRESHOLD || 100,
tapThreshold = win.TAP_THRESHOLD || 150, // range of time where a tap event could be detected
dbltapThreshold = win.DBL_TAP_THRESHOLD || 200, // delay needed to detect a double tap
tapPrecision = win.TAP_PRECISION / 2 || 60 / 2, // touch events boundaries ( 60px by default )
justTouchEvents = win.JUST_ON_TOUCH_DEVICES || isTouch,
tapNum = 0,
currX, currY, cachedX, cachedY, tapTimer, timestamp;
//setting the events listeners
setListener(doc, touchevents.touchstart + (justTouchEvents ? '' : ' mousedown'), onTouchStart);
setListener(doc, touchevents.touchend + (justTouchEvents ? '' : ' mouseup'), onTouchEnd);
setListener(doc, touchevents.touchmove + (justTouchEvents ? '' : ' mousemove'), onTouchMove);
}(document, window));
|
JavaScript
| 0 |
@@ -5335,16 +5335,24 @@
imestamp
+, target
;%0A%0A //s
@@ -5686,8 +5686,9 @@
indow));
+%0A
|
287795cf6ebc8918958231548aea7e5031c1c6de
|
Remove addressTypes from "resources" propTypes
|
Users.js
|
Users.js
|
import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import queryString from 'query-string';
import makeQueryFunction from '@folio/stripes-components/util/makeQueryFunction';
import { stripesShape } from '@folio/stripes-core/src/Stripes';
import SearchAndSort from'./lib/SearchAndSort';
import packageInfo from './package';
const INITIAL_RESULT_COUNT = 30;
const RESULT_COUNT_INCREMENT = 30;
const filterConfig = [
{
label: 'Status',
name: 'active',
cql: 'active',
values: [
{ name: 'Active', cql: 'true' },
{ name: 'Inactive', cql: 'false' },
],
},
{
label: 'Patron group',
name: 'pg',
cql: 'patronGroup',
values: [], // will be filled in by componentWillUpdate
},
];
class Users extends React.Component {
static propTypes = {
stripes: stripesShape.isRequired,
resources: PropTypes.shape({
patronGroups: PropTypes.shape({
records: PropTypes.arrayOf(PropTypes.object),
}),
addressTypes: PropTypes.shape({
records: PropTypes.arrayOf(PropTypes.object),
}),
users: PropTypes.shape({
hasLoaded: PropTypes.bool.isRequired,
other: PropTypes.shape({
totalRecords: PropTypes.number.isRequired,
}),
isPending: PropTypes.bool.isPending,
successfulMutations: PropTypes.arrayOf(
PropTypes.shape({
record: PropTypes.shape({
id: PropTypes.string.isRequired,
username: PropTypes.string.isRequired,
}).isRequired,
}),
),
}),
userCount: PropTypes.number,
notes: PropTypes.shape({
records: PropTypes.arrayOf(PropTypes.object),
}),
}).isRequired,
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
search: PropTypes.string,
}).isRequired,
match: PropTypes.shape({
path: PropTypes.string.isRequired,
}).isRequired,
mutator: PropTypes.shape({
userCount: PropTypes.shape({
replace: PropTypes.func,
}),
users: PropTypes.shape({
POST: PropTypes.func,
}),
}).isRequired,
okapi: PropTypes.shape({
url: PropTypes.string.isRequired,
tenant: PropTypes.string.isRequired,
token: PropTypes.string.isRequired,
}).isRequired,
onSelectRow: PropTypes.func,
disableUserCreation: PropTypes.bool,
};
static manifest = Object.freeze({
userCount: { initialValue: INITIAL_RESULT_COUNT },
users: {
type: 'okapi',
records: 'users',
recordsRequired: '%{userCount}',
perRequest: 30,
path: 'users',
GET: {
params: {
query: makeQueryFunction(
'username=*',
'username="$QUERY*" or personal.firstName="$QUERY*" or personal.lastName="$QUERY*" or personal.email="$QUERY*" or barcode="$QUERY*" or id="$QUERY*" or externalSystemId="$QUERY*"',
{
Status: 'active',
Name: 'personal.lastName personal.firstName',
'Patron Group': 'patronGroup.group',
Username: 'username',
Barcode: 'barcode',
Email: 'personal.email',
},
filterConfig,
),
},
staticFallback: { params: {} },
},
},
patronGroups: {
type: 'okapi',
path: 'groups',
records: 'usergroups',
},
addressTypes: {
type: 'okapi',
path: 'addresstypes',
records: 'addressTypes',
},
});
constructor(props) {
super(props);
this.state = {};
this.okapi = props.okapi;
this.connectedSearchAndSort = props.stripes.connect(SearchAndSort);
const logger = props.stripes.logger;
this.log = logger.log.bind(logger);
this.anchoredRowFormatter = this.anchoredRowFormatter.bind(this);
this.resultsList = null;
}
componentWillUpdate() {
const pg = (this.props.resources.patronGroups || {}).records || [];
if (pg && pg.length) {
filterConfig[1].values = pg.map(rec => ({ name: rec.group, cql: rec.id }));
}
}
getRowURL(rowData) {
return `/users/view/${rowData.id}${this.props.location.search}`;
}
// custom row formatter to wrap rows in anchor tags.
anchoredRowFormatter(
{ rowIndex,
rowClass,
rowData,
cells,
rowProps,
labelStrings,
},
) {
return (
<a
href={this.getRowURL(rowData)} key={`row-${rowIndex}`}
aria-label={labelStrings && labelStrings.join('...')}
role="listitem"
className={rowClass}
{...rowProps}
>
{cells}
</a>
);
}
render() {
const props = this.props;
const urlQuery = queryString.parse(props.location.search || '');
const initialPath = (_.get(packageInfo, ['stripes', 'home']) ||
_.get(packageInfo, ['stripes', 'route']));
return (<this.connectedSearchAndSort
stripes={props.stripes}
okapi={props.okapi}
initialPath={initialPath}
filterConfig={filterConfig}
initialResultCount={INITIAL_RESULT_COUNT}
resultCountIncrement={RESULT_COUNT_INCREMENT}
parentResources={props.resources}
parentMutator={props.mutator}
onSelectRow={props.onSelectRow}
path={props.location.pathname}
urlQuery={urlQuery}
/>);
}
}
export default Users;
|
JavaScript
| 0.000001 |
@@ -993,110 +993,8 @@
%7D),%0A
- addressTypes: PropTypes.shape(%7B%0A records: PropTypes.arrayOf(PropTypes.object),%0A %7D),%0A
|
f8167fc0430c54df55b50c06f539eb095311a678
|
add show/hide DOM elements
|
d.js
|
d.js
|
import toArray from './util/toArray'
import objectAssign from './util/objectAssign'
class DOM {
constructor (selector) {
let elements = document.querySelectorAll(selector)
this.length = elements.length
objectAssign(this, elements)
}
map (fn) {
toArray(this).map(el => fn.call(el, el))
return this
}
each (fn) {
toArray(this).forEach(el => fn.call(el, el))
return this
}
reduce (fn) {
toArray(this).forEach(el => fn.call(el, el))
return this
}
addClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.add(...classes))
}
removeClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.add(...classes))
}
toggleClass (classNames) {
let classes = classNames.split(' ')
return this.map(el => el.classList.toggle(...classes))
}
hasClass (className) {
for (let el of toArray(this)) {
if (el.classList.contains(className)) {
return true
}
}
return false
}
on (eventNames, callback) {
let events = eventNames.split(' ')
events.forEach(event =>
this.map(el => el.addEventListener(event, callback, false))
)
return this
}
attr (attributeName, value=null) {
if (value == null) {
return this[0][attributeName]
} else {
return this.each(el => el[attributeName] = value)
}
}
val (value=null) {
if (value == null) {
return this.attr('value')
} else {
this.attr('value', value)
}
}
text (value=null) {
if (value == null) {
return this.attr('textContent')
} else {
this.attr('textContent', value)
}
}
}
window.$ = window.d = selector => new DOM(selector)
|
JavaScript
| 0 |
@@ -1693,16 +1693,154 @@
%7D%0A %7D
+%0A%0A show () %7B%0A return this.each(el =%3E el.style.display = '')%0A %7D%0A%0A hide () %7B%0A return this.each(el =%3E el.style.display = 'none')%0A %7D
%0A%7D%0A%0Awind
|
af0638a0a804e56bd324e6446564eb5fd9fe6c6f
|
fix bugs w SRSWOR
|
2ch.js
|
2ch.js
|
var FILE_PATH = "/Users/pete/iMacros/Macros/jcrawler/{0}";
var URL_BBS_LIST = "http://menu.2ch.net/bbstable.html";
var THREAD = "http://{0}.2ch.net/test/read.cgi/{1}/{2}/";
var REGEX_HREF = new RegExp("href=\"[^\"]+\"", "gi");
var REGEX_2CH_HREF = new RegExp("http://[^\.]+\.2ch\.net/");
var REGEX_BOARD_HREF = new RegExp("http://([^\.]+)\.2ch\.net/([^/]+)");
var IGNORE_BBS_SUBDOMAIN = ["headline", "www", "info", "watch", "shop", "epg", "find", "be", "newsnavi", "irc"];
// Source: http://forum.iopus.com/viewtopic.php?f=11&t=5267
// Note: this may not work depending on Java version(?)
write_file = function(path, data) {
iimDisplay("Writing file:"+path);
try {
var out = new java.io.BufferedWriter(new java.io.OutputStreamWriter(new java.io.FileOutputStream(new java.io.File(path)), "Shift_JIS"));
out.write(data);
out.close();
out=null;
}
catch(e) { //catch and report any errors
alert(""+e);
}
};
// Source: http://stackoverflow.com/questions/610406/javascript-equivalent-to-printf-string-format/4256130#4256130
String.prototype.format = function() {
var formatted = this;
for (var i = 0; i < arguments.length; i++) {
var regexp = new RegExp('\\{'+i+'\\}', 'gi');
formatted = formatted.replace(regexp, arguments[i]);
}
return formatted;
};
// Source: http://stackoverflow.com/questions/646628/javascript-startswith
if (typeof String.prototype.startsWith != 'function') {
String.prototype.startsWith = function (str){
return this.slice(0, str.length) == str;
};
}
// inclusive random range
// Source: http://www.admixweb.com/2010/08/24/javascript-tip-get-a-random-number-between-two-integers/
random_range = function(from, to){
var val = Math.floor(Math.random() * (to - from + 1) + from);
if(val > to) { // in case Math.random() can produce 1.0 (does it?)
val = to;
}
return val;
};
// Source: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
function date_string(d){
function pad(n){return n<10 ? '0'+n : n}
return d.getUTCFullYear()+''
+ pad(d.getUTCMonth()+1)+''
+ pad(d.getUTCDate())+''
+ pad(d.getUTCHours())+''
+ pad(d.getUTCMinutes())+''
+ pad(d.getUTCSeconds())}
srswor = function(list, n) {
var new_list = [];
while(new_list.length < n) {
var rand_idx = random_range(0, new_list.length - 1);
new_list.push(list.splice(rand_idx, 1));
}
return new_list;
};
run = function(code, n) {
var retcode = iimPlay("CODE: "+code);
if(retcode != 1) {
alert("BAD CODE:\n"+code+"\n\nretcode:"+retcode);
return;
}
if(n) {
var extract = iimGetLastExtract(n);
if(extract == "#EANF#") return false; // "Extraction Anchor Not Found"
return extract;
}
};
sleep = function(seconds) { run("WAIT SECONDS="+seconds); };
visit_url = function(url) { run("URL GOTO="+url); };
random_boards_list = function(n) {
visit_url(URL_BBS_LIST);
var raw = run("TAG POS=1 TYPE=FONT ATTR=* EXTRACT=HTM", 1);
var raw_list = raw.match(REGEX_HREF);
var mod_list = [];
for(var i=0; i<raw_list.length; i++) {
var link = raw_list[i].substring(6, raw_list[i].length - 2);
if(!link.match(REGEX_2CH_HREF)) {
continue;
}
var ignore_subdomain = false;
for(var j=0; j<IGNORE_BBS_SUBDOMAIN.length; j++) {
if(link.startsWith("http://"+IGNORE_BBS_SUBDOMAIN[j]+".")) {
ignore_subdomain = true; break;
}
}
if(ignore_subdomain) {
continue;
}
mod_list.push(link);
}
return srswor(mod_list, n);
};
random_threads_list = function(n) {
var raw = run("TAG POS=1 TYPE=SMALL ATTR=* EXTRACT=HTM", 1);
var list = raw.match(REGEX_HREF);
var mod_list = [];
for(var i=0; i<list.length; i++) {
mod_list.push(list[i].substring(6, list[i].length - 5));
}
return srswor(mod_list, n);
};
board_url_info = function(url_string) {
var match = url_string.match(REGEX_BOARD_HREF);
// [subdomain, board_name]
return [match[1], match[2]];
};
thread_link = function(subdomain, board, thread) {
return THREAD.format(subdomain, board, thread);
};
save_thread = function(link, thread) {
visit_url(link);
var raw_messages = run("TAG POS=1 TYPE=DL ATTR=CLASS:thread EXTRACT=HTM", 1);
var filename = date_string(new Date())+"_"+thread;
var path = FILE_PATH.format("data/2ch/"+filename+".data");
write_file(path, raw_messages);
};
main = function() {
//alert(random_boards_list(10));
//http://yuzuru.2ch.net/billiards/subback.html
//alert(board_url_info("http://yuzuru.2ch.net/billiards/"));
//alert(random_threads_list(10));
var thread = "1287916288";
save_thread(thread_link("yuzuru", "billiards", thread),thread)
};
main();
|
JavaScript
| 0 |
@@ -2290,16 +2290,35 @@
ngth %3C n
+ && list.length %3E 0
) %7B%0A
@@ -2348,20 +2348,16 @@
ange(0,
-new_
list.len
|
19162d65af97084735129fde1dc71384f0b773e6
|
fix tests
|
acl.js
|
acl.js
|
var _ = require('lodash');
var assert = require('assert');
var Promise = require('bluebird');
module.exports = function (db) {
var q = require('./queries')(db);
return function (queries, acl, entity, key) {
assert.ok(entity, 'entity required');
key = key || 'id';
var _acl = _.extend({}, acl, {
locks: function(ent, done) {
var entityId = ent.id;
acl.locks(ent, function(locks) {
done(null, _processLocks(locks));
});
function _setDefaults(lock) {
return _.defaults(lock, {
entityId: entityId,
entity: entity,
read: false,
write: false,
remove: false
});
}
function _filterAllowed(lock) {
return (lock.key && lock.lock && (lock.read || lock.write || lock.remove));
}
function _processLocks(locks) {
return _(locks)
.map(_setDefaults)
.filter(_filterAllowed)
.value();
}
}
});
// convert async functions to promises
var promised = {
locks: Promise.promisify(_acl.locks),
keychain: Promise.promisify(_acl.keychain),
query: Promise.promisify(_acl.query)
};
function setPermissionWhere(knex, access, opts) {
// checking context here to determine if we need to add ACLs
if (!opts || !opts.user$) { return knex; }
opts.q = opts.q || {};
// query functions are node-style callbacks, but this
// needs to return a promise.
return promised.keychain(opts.user$)
.then(function (keychain) {
return _.extend({}, opts, {
keychain: keychain,
access: access,
entity: entity,
key: key
});
})
.then(promised.query)
.then(function (subselect) {
return knex.whereIn(key, subselect);
});
}
function regenerateLocks(opts) {
var entityId = _.get(opts, 'ent.id');
// remove all current ace entries
return function (rows) {
if (key !== 'id') { return rows; }
return promised.locks(opts.ent)
.then(_removeLocks)
.each(q.insert)
.thenReturn(rows);
};
function _removeLocks(locks) {
var args = { entityId: entityId, entity: entity };
return q.remove(args).thenReturn(locks);
}
}
return _.extend({}, queries, {
list: function (opts) {
var knex = queries.list(opts);
return setPermissionWhere(knex, 'read', opts);
},
load: function (opts) {
var knex = queries.load(opts);
return setPermissionWhere(knex, 'read', opts);
},
insert: function (opts) {
return queries.insert(opts).then(regenerateLocks(opts));
},
update: function (opts) {
return queries.update(opts).then(regenerateLocks(opts));
},
acl: _acl
});
};
};
|
JavaScript
| 0.000001 |
@@ -406,16 +406,21 @@
unction(
+err,
locks) %7B
|
2a815adb88b7970c9ac48ac509f67e3c223fa654
|
Edit port to listen
|
api.js
|
api.js
|
var User = require('./models/user');
var express = require('express');
var session = require('express-session');
var app = express();
var port = process.env.PORT || 8080;
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/labeli-api');
var bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
currentUser = null;
app.use(session({
secret: 'labeliSessionPwordAss',
resave: true,
saveUninitialized: true
}));
app.use(function(req, res, next)
{
res.header("Cache-Control", "no-cache");
res.header("Access-Control-Allow-Origin", "http://localhost");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", "true");
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
app.use(function(req, res, next)
{
console.log("request by "+req.session.userId);
if(req.session.userId == null)
{
currentUser = null;
next();
}
else
{
User.findById(req.session.userId, function(err, user)
{
currentUser = user;
next();
});
}
});
app.use(require('./routes/users'));
app.use(require('./routes/projects'));
app.use(require('./routes/auth'));
app.use(router);
app.listen(port);
console.log('API listening on port ' + port);
module.exports = app;
|
JavaScript
| 0 |
@@ -166,32 +166,12 @@
=
-process.env.PORT %7C%7C 8080
+9005
;%0Ava
|
74986c0abbb236382c5b9576bb963735721748f7
|
test the functionalities
|
app.js
|
app.js
|
function NotesApplication(author) {
this.author = author;
this.notesList = [];
}
NotesApplication.create = function(note_content){
this.notesList.push(note_content);
};
NotesApplication.prototype.listNotes = function(){
if(this.notesList.length>0){
for(i = 0; i<this.notesList.length; i++){
console.log("Note ID: " +i);
console.log(this.notesList[i]);
console.log("By Author " + this.author );
}
}
};
NotesApplication.prototype.get = function(note_id){
console.log(this.notesList[note_id]);
};
NotesApplication.prototype.search = function(search_text){
var result = "Showing results for search";
for(i=0; i<this.notesList.length; i++){
if(this.notesList.indexOf(search_text) !== -1){
note = "Notes ID: " +i+ "\n" + this.notesList[i] + "\n" +"By Author "+ author;
} result += note;
}
console.log(result);
};
NotesApplication.prototype.delete = function(note_id){
if(this.notesList.length> note_id)
this.notesList.splice(note_id, 1);
};
NotesApplication.prototype.edit = function(note_id, new_content){
if(this.notesList.length > note_id){
this.notesList[note_id] = new_content;
}
};
|
JavaScript
| 0.002149 |
@@ -94,16 +94,26 @@
ication.
+prototype.
create =
@@ -620,17 +620,31 @@
r search
-%22
+ %22+ search_text
;%0A%09for(i
@@ -697,16 +697,19 @@
otesList
+%5Bi%5D
.indexOf
@@ -738,20 +738,25 @@
%0A%09%09%09
+var
note
+s
= %22Note
s ID
@@ -755,27 +755,21 @@
Note
-s
ID: %22
-
+i+
- %22%5Cn%22 +
+%22 %22+
this
@@ -785,14 +785,12 @@
t%5Bi%5D
-
+ %22
-%5Cn
+
%22 +%22
@@ -801,17 +801,21 @@
uthor %22+
-
+this.
author;%0A
@@ -816,17 +816,16 @@
thor;%0A%09%09
-%7D
%09result
@@ -831,21 +831,21 @@
+= note
+s
;%0A%09
-%7D%0A
+%09
%09console
@@ -854,24 +854,34 @@
og(result);%0A
+%09%09%7D%09%0A%09%7D%0A%09%0A
%7D;%0A%0ANotesApp
@@ -1149,12 +1149,294 @@
ntent;%0A%09%7D%0A%7D;
+%0A%0Avar peete = new NotesApplication(%22peete%22);%0Apeete.create(%22hi, this is andela bootcamp%22);%0Apeete.create(%22hi, i love andela bootcamp3%22);%0Apeete.create(%22hi, this is andela bootcamp1%22);%0Apeete.get(1);%0Apeete.search(%22love%22);%0Apeete.delete(2);%0Apeete.edit(1, %22no love lost, no love found%22);%0A%0A
|
5f33efddc7ccc00b1d402a59e37e5ce46e043f6e
|
Fix some sentences in email
|
app.js
|
app.js
|
var email = require('./email.js');
var fs = require('fs');
var http = require('http');
var nodemailer = require('nodemailer');
var db = require('monk')('localhost/diagnostico');
var questions = db.get('questions');
var server = http.createServer(function(req, res) {
if (req.method == "POST") {
var jsonString = '';
var jsonData;
req.on('data', function(data) {
jsonString += data;
});
req.on('end', function() {
var jsonData = JSON.parse(jsonString);
if (req.url === '/results') {
questions.insert(jsonData, function(err, doc) {
if (err) throw err;
res.writeHead(200, { 'Content-Type': 'application/json' });
console.log(doc);
res.write(JSON.stringify(doc));
res.end();
});
} else {
composeAndSendEmail(jsonData);
res.end();
}
});
} else {
res.end();
}
});
server.listen(3000);
// create reusable transporter object using SMTP transport
//
// NB! No need to recreate the transporter object. You can use
// the same transporter object for all e-mails
var transporter = nodemailer.createTransport({
service: 'Gmail',
auth: email.credentials
});
var composeAndSendEmail = function(json) {
var text = "";
var notKnownCategories = [];
var jsonQuestions = {};
fs.readFile(__dirname + '/client/app/questions/questions.json', function(err, data) {
if (err) {
console.log(err);
} else {
text += "Enhorabuena, ¡Los bienes comunes producidos colaborativamente ya forman parte de tu vida!\n\n";
text += "Las comunidades del procomún ya forman parte de tu vida, al menos en los siguientes aspectos:\n";
jsonQuestions = JSON.parse(data.toString());
var categories = {};
for (var i = 0, len = jsonQuestions.length; i<len; i++){
var key = jsonQuestions[i].id;
categories[key] = jsonQuestions[i];
var categoryName = categories[key].text;
if (json.hasOwnProperty(key)){
text += categoryName;
if (i === len-1){
text+= ".";
}
else{
text+=", ";
}
} else {
notKnownCategories.push(categories[key]);
}
}
text += "\n";
text += "- Descubre nuevas comunidades:\n";
for (var i = 0, lengthI = notKnownCategories.length; i<lengthI; i++){
var category = notKnownCategories[i];
text += category.text + ": ";
for (var j = 0, lengthJ = category.questions.length; j<lengthJ; j++){
for (var k = 0, lengthK = category.questions[j].examples.length;
k < lengthK; k ++){
text += category.questions[j].examples[k].link + ", ";
}
}
text +="\n";
}
text += "\n- Atrévete a participar en las comunidades que ya conoces. ¡Seguro que puedes aprender cosas nuevas!\n";
for (var key in json){
if (categories.hasOwnProperty(key)){
console.log("\nkey " + key);
for (var i = 0, len = categories[key].questions.length; i< len; i++){
console.log("\ni " + i);
var que = categories[key].questions[i].id;
console.log("\nque: "+ que);
if (json[key].hasOwnProperty(que)){
for (var j = 0, lenJ = categories[key].questions[i].examples.length; j< lenJ; j++){
console.log("\nj " + j);
var ex = categories[key].questions[i].examples[j].id;
if (json[key][que].hasOwnProperty(ex)){
text += categories[key].questions[i].examples[j].link + ", ";
}
}
}
}
}
}
console.log(text);
sendEmail(json.email,text);
}
});
};
var sendEmail = function(address, body) {
// setup e-mail data with unicode symbols
var mailOptions = {
from: 'UCM P2Pvalue <[email protected]>', // sender address
to: address, // list of receivers
subject: 'Cuestionario Noche de los Investigadores', // Subject line
text: body
};
// send mail with defined transport object
transporter.sendMail(mailOptions, function(error, info){
if(error){
console.log(error);
}else{
console.log('Message sent: ' + info.response);
}
});
};
|
JavaScript
| 1 |
@@ -1484,17 +1484,17 @@
buena, %C2%A1
-L
+l
os biene
@@ -1673,24 +1673,26 @@
aspectos:%5Cn
+%5Cn
%22;%0A jso
@@ -2248,19 +2248,57 @@
t += %22%5Cn
+%5Cn
%22;%0A
+ text += %22Ahora puedes...%5Cn%5Cn%22%0A
te
@@ -2313,17 +2313,18 @@
Descubr
-e
+ir
nuevas
|
d39d8b4d83869fc163de11ca8740b2ee35388f69
|
add a method to locate a machine
|
app.js
|
app.js
|
var express = require('express');
var app = express();
var models = require('./models');
var crypto = require('crypto');
var bodyParser = require('body-parser');
//
// register
// --------
//
// This method registers a machine
// for the service.
//
var register = function (req, res) {
var key = crypto.randomBytes(16).toString('hex');
var secret = crypto.randomBytes(16).toString('hex');
models.Machine.create({ key: key, secret: secret })
.then(function (machine) {
res.status(201).json(machine).end();
})
.catch(function (err) {
res.status(500).end();
});
};
//
// identify
// --------
//
// This method allows a machine to
// identify its location.
//
var identify = function (req, res) {
var key = req.param('key');
var secret = req.body.secret;
var ip = req.body.ip;
models.Machine.findOne({ where: { key: key, secret: secret }})
.then(function (machine) {
if (!machine)
throw { status: 404, message: 'Machine not found!' };
return machine.update({ ip: ip });
})
.then(function (machine) {
res.status(200).json(machine).end();
})
.catch(function (err) {
if (res.status) return res.status(err.status).json(err).end();
res.status(500).end();
});
};
//
// locate
// ------
//
// This method returns the location
// of a machine.
//
var locate = function (req, res) {
};
//
// runApp
// ------
//
// This method starts the express server
//
var runApp = function () {
app.listen(3000);
console.log('server running');
};
//
// dbFailed
// --------
//
// This method runs if the application
// fails to connect to the database.
//
var dbFailed = function (err) {
console.log('failed to connect to db');
console.log(err);
};
app.use(bodyParser.json());
app.post('/machines', register);
app.put('/machines/:key', identify);
app.get('/machines/:key', locate);
models.sequelize.sync().then(runApp).catch(dbFailed);
|
JavaScript
| 0.000053 |
@@ -1373,16 +1373,426 @@
res) %7B%0A
+ var key = req.param('key');%0A models.Machine.findOne(%7B where: %7B key: key %7D%7D)%0A .then(function (machine) %7B%0A if (!machine)%0A throw %7B status: 404, message: 'Machine not found!' %7D;%0A%0A machine.secret = undefined;%0A res.status(200).json(machine).end();%0A %7D)%0A .catch(function (err) %7B%0A if (res.status) return res.status(err.status).json(err).end();%0A res.status(500).end();%0A %7D);
%0A%7D;%0A%0A//%0A
|
e2d2fdd02fc65b04b26807342b32eace79f6f7cc
|
adding express
|
app.js
|
app.js
|
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost', function (err) { // note using default port, so no need to specify
if (err) throw err;
console.log('connected!');
mongoose.disconnect();
});
|
JavaScript
| 0.998604 |
@@ -28,16 +28,50 @@
goose');
+%0Avar express = require('express');
%0A%0Amongoo
@@ -194,17 +194,16 @@
ow err;%0A
-%0A
consol
@@ -227,30 +227,255 @@
');%0A
+%0A
-mongoose.disconnect(
+var app = express();%0A%0A // set routes%0A app.get('/', function (req, res) %7B%0A res.status(200).send('hello mongoose blog!');%0A %7D);%0A%0A // start listening%0A app.listen(3000, function () %7B%0A console.log('listening at http://localhost:3000');%0A %7D
);%0A%7D
|
c7a4c691847ea6beeb2a282f2cf4034690ced86e
|
limit tweet results to 5
|
app.js
|
app.js
|
var express = require('express'),
app = express(),
server = require('http').createServer(app),
ejs = require('ejs'),
bodyParser = require('body-parser'),
passport = require('passport'),
passportLocal = require('passport-local'),
flash = require('connect-flash'),
cookieParser = require('cookie-parser'),
cookieSession = require('cookie-session'),
OAuth = require('oauth'),
io = require('socket.io').listen(server),
db = require('./models/index');
app.set('view engine', 'ejs');
app.use(express.static(__dirname + '/public'));
app.use(bodyParser.urlencoded({extended: true}));
app.use(cookieSession({
secret: 'thisismysecretkey', // generate a random hash
name: 'cookie created by cameron',
// keep user logged in for one week
maxage: 604800000
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// prepare serialize (grab user id)
passport.serializeUser(function(user, done) {
console.log('serialize just ran');
done(null, user.id);
});
// deserialize (check if user id is in the db)
passport.deserializeUser(function(id, done) {
console.log('deserialize just ran');
db.user.find({
where: {
id: id
}
}).done(function(error, user) {
done(error, user);
});
});
// set up oauth
var oauth = new OAuth.OAuth(
'https://api.twitter.com/oauth/request_token',
'https://api.twitter.com/oauth/access_token',
process.env.TWITTER_KEY,
process.env.TWITTER_SECRET,
'1.0A',
null,
'HMAC-SHA1'
);
// set variables for searched keyword and URL
var searchKey;
var searchURL;
// connect to socket
io.on('connection', function(socket) {
console.log('user connected');
socket.on('disconnect', function() {
console.log('user disconnected');
});
});
// root route automatically tracks tweets from searchKey
// initial searchKey is user's defaultSearch if logged in
app.get('/', function(req, res) {
if (!req.user) {
searchKey = 'San Francisco';
}
else {
searchKey = req.user.defaultSearch;
}
console.log(searchKey);
searchURL = 'https://api.twitter.com/1.1/search/tweets.json?q=' + searchKey + '&result_type=recent&count=100';
console.log(searchURL);
oauth.get(searchURL, null, null, function(e, data, res) {
var tweets = JSON.parse(data).statuses;
io.sockets.emit('receive_tweets', tweets);
// console.log(tweets);
});
res.render('site/index', {searchKey: searchKey,
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
// when user searches new keyword
// set searchKey to new keyword
app.post('/search', function(req, res) {
var keyword = req.body.keyword;
searchKey = keyword;
console.log(searchKey);
searchURL = 'https://api.twitter.com/1.1/search/tweets.json?q=' + searchKey + '&result_type=recent&count=100';
console.log(searchURL);
oauth.get(searchURL, null, null, function(e, data, res) {
var tweets = JSON.parse(data).statuses;
io.sockets.emit('receive_tweets', tweets);
// console.log(tweets);
});
res.render('site/index', {searchKey: searchKey,
isAuthenticated: req.isAuthenticated(),
user: req.user
});
});
app.get('/signup', function(req, res) {
if (!req.user) {
res.render('site/signup', {username: '', defaultSearch: ''});
}
else {
res.redirect('/');
}
});
app.get('/login', function(req, res) {
if (!req.user) {
res.render('site/login', {username: '', message: req.flash('loginMessage')});
}
else {
res.redirect('/');
}
});
app.post('/signup', function(req, res) {
newUsername = req.body.username;
newPassword = req.body.password;
defaultSearch = req.body.defaultSearch;
db.user.createNewUser(newUsername, newPassword, defaultSearch,
function(err) {
res.render('site/signup', {message: err.message, username: newUsername, defaultSearch: defaultSearch});
},
function(success) {
res.render('site/login', {message: success.message, username: newUsername});
}
);
});
app.post('/login', passport.authenticate('local', {
successRedirect: '/',
failureRedirect: '/login',
failureFlash: true
}));
app.get('/logout', function(req, res) {
req.logout();
res.redirect('/');
});
// render 404 page when any other URL attempted
app.get('/*', function(req, res) {
res.status(404);
res.render('site/404', {isAuthenticated: req.isAuthenticated(),
user: req.user});
});
server.listen(process.env.PORT || 3000, function(){
console.log('server started on localhost:3000');
});
|
JavaScript
| 0.999161 |
@@ -2141,35 +2141,33 @@
pe=recent&count=
-100
+5
';%0A console.log
@@ -2795,11 +2795,9 @@
unt=
-100
+5
';%0A
|
dcbf3a889b6c78defe44d47ea2e3135b97dfdc74
|
add listening confirmation
|
app.js
|
app.js
|
require('dotenv').config();
var express = require('express');
var app = express();
var http = require('http');
var port = process.env.PORT || 3000;
var botPort = process.env.BOT_PORT || 3001;
var mongoose = require('mongoose');
var passport = require('passport');
var path = require('path');
var bodyParser = require('body-parser');
var session = require('express-session');
var sassMiddleware = require('node-sass-middleware');
var MongoStore = require('connect-mongo')(session);
var autoIncrement = require('mongoose-auto-increment');
var banMiddleware = require('./lib/ban-middleware');
var priceUpdater = require('./manager/prices');
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);
var botIo = io.of('/csgo-bot');
require('./lib/passport')(passport);
require('./lib/db')(mongoose);
require('./lib/cache');
autoIncrement.initialize(mongoose.connection);
var sessionStore = new MongoStore({ mongooseConnection: mongoose.connection });
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
var sessionMiddleware = session({
key: 'connect.sid',
name: 'connect.sid',
secret: process.env.SESSION_SECRET,
store: sessionStore,
resave: true,
saveUninitialized: true
});
var sassMiddleware = sassMiddleware({
src: path.join(__dirname, 'public/sass'),
dest: path.join(__dirname, 'public/stylesheets'),
debug: false,
outputStyle: 'compressed',
prefix: '/stylesheets'
});
app.use(sessionMiddleware);
app.use(passport.initialize());
app.use(passport.session());
app.use(banMiddleware);
app.use(sassMiddleware);
app.use(express.static(path.join(__dirname, 'public')));
require('./router')(app);
server.listen(port || 3000);
io.use(function(socket, next) {
sessionMiddleware(socket.request, {}, next);
});
require('./lib/socket')(io);
priceUpdater(20 * 60 * 1000); //update prices every 20 minutes
require('./lib/socket/bot')(botIo, io);
|
JavaScript
| 0 |
@@ -146,52 +146,8 @@
00;%0A
-var botPort = process.env.BOT_PORT %7C%7C 3001;%0A
var
@@ -1741,24 +1741,81 @@
ten(port
- %7C%7C 3000
+, () =%3E %7B%0A console.log('Server listening on port =%3E ' + port);%0A%7D
);%0A%0Aio.u
|
8485ccc7c1e57163ae59b5c9fc7b7a21ac1ce6ba
|
Clean up console.logs
|
app.js
|
app.js
|
// See (Electron): https://github.com/electron/electron-quick-start
// See (Door sensor application): https://github.com/brentertz/ocupado-app
const path = require('path');
const url = require('url');
const fs = require('fs');
const _ = require('lodash');
const defaultConfig = require('./config/defaults');
const localConfigPath = path.join(__dirname, '/config', 'local.js');
const localConfig = fs.existsSync(localConfigPath) ? require(localConfigPath) : {};
const {PHOTON_1, PHOTON_2, PARTICLE_ACCESS_TOKEN} = _.merge({}, defaultConfig, localConfig);
const { app, BrowserWindow, ipcMain, Menu, Tray } = require('electron');
console.log('photon_1', PHOTON_1);
console.log('photon_2', PHOTON_2);
console.log('particle_access_token', PARTICLE_ACCESS_TOKEN);
let appWindow, tray;
let browserState = 'Checking connection to Internet...';
let devices = {
[PHOTON_1]: {name: 'Toilet 1', online: false, open: false, eventSource: null},
[PHOTON_2]: {name: 'Toilet 2', online: false, open: false, eventSource: null}
};
function createWindow() {
appWindow = new BrowserWindow({ width: 0, height: 0, show: false });
appWindow.loadURL(url.format({
pathname: path.join(__dirname, 'index.html'),
protocol: 'file:',
slashes: true
}));
appWindow.on('closed', function () {
appWindow = null;
});
console.log('devices keys', Object.keys(devices));
let openToilets = Object.values(devices).filter((device) => (device.online && device.open));
console.log('openToilets', openToilets);
tray = new Tray(path.join(__dirname, '/images', '/poo-' + openToilets.length + '-icon.png')); // **
createMenu();
}
function createMenu() {
const template = [
{ label: browserState, enabled: false },
{ type: 'separator' },
{ label: 'Quit', click: app.quit }
];
const contextMenu = Menu.buildFromTemplate(template);
tray.setToolTip('Toilet Princess');
tray.setHighlightMode('never');
tray.setContextMenu(contextMenu);
}
app.on('ready', createWindow);
app.on('window-all-closed', function() {
// On OS X it is common for applications and their menu bar
// to stay active until the user quits explicitly with Cmd + Q
if (process.platform !== 'darwin') {
app.quit();
}
});
app.on('activate', function () {
// On OS X it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (appWindow === null) {
createWindow()
}
});
ipcMain.on('browser-status-changed', (event, status) => {
if (status === 'online') {
browserState = 'Online';
} else {
browserState = 'Offline';
}
});
|
JavaScript
| 0.000002 |
@@ -628,140 +628,8 @@
);%0A%0A
-console.log('photon_1', PHOTON_1);%0Aconsole.log('photon_2', PHOTON_2);%0Aconsole.log('particle_access_token', PARTICLE_ACCESS_TOKEN);%0A%0A
let
@@ -1184,62 +1184,8 @@
);%0A%0A
- console.log('devices keys', Object.keys(devices));%0A%0A
le
@@ -1280,52 +1280,8 @@
);%0A%0A
- console.log('openToilets', openToilets);%0A%0A
tr
|
daed32dc9f743758f35b938f2dfe4649f3ceb13d
|
remove commented out code
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express');
var compress = require('compression');
var session = require('express-session');
var bodyParser = require('body-parser');
var logger = require('morgan');
var errorHandler = require('errorhandler');
var lusca = require('lusca');
var dotenv = require('dotenv');
try {
dotenv.load()
} catch (e) {
console.log("no .env file found. Moving on.");
}
// var fs = require('fs')
//
// fs.stat('.env', function(err, stat) {
// if(err == null) {
// console.log("loading .env");
// dotenv.load()
// } else {
// console.log("not loading .env");
// }
// });
var MongoStore = require('connect-mongo/es5')(session);
var flash = require('express-flash');
var path = require('path');
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
var passport = require('passport');
var expressValidator = require('express-validator');
var sass = require('node-sass-middleware');
var multer = require('multer');
var upload = multer({ dest: path.join(__dirname, 'uploads') });
var httpProxy = require('http-proxy');
var proxy = httpProxy.createProxyServer();
var config = require('./config/config')
var httpProxy = require('http-proxy');
/**
* Load environment variables from .env file, where API keys and passwords are configured.
*
* Default path: .env (You can remove the path argument entirely, after renaming `.env.example` to `.env`)
*/
/**
* API keys and Passport configuration.
*/
var passportConfig = require('./config/passport');
/**
* Create Express server.
*/
var app = express();
// end
/**
* Connect to MongoDB.
*/
console.log("trying to connect to "+config.db.URL)
mongoose.connect(config.db.URL);
mongoose.connection.on('connected', function () {
console.log("connected to " + config.db.URL)
});
mongoose.connection.on('error', function() {
console.log('MongoDB Connection Error. Please make sure that MongoDB is running.');
process.exit(1);
});
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(compress());
app.use(sass({
src: path.join(__dirname, 'public'),
dest: path.join(__dirname, 'public'),
sourceMap: true
}));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(expressValidator());
app.use(session({
resave: true,
saveUninitialized: true,
secret: process.env.SESSION_SECRET,
store: new MongoStore({
url: process.env.MONGODB || process.env.MONGOLAB_URI,
autoReconnect: true
})
}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
// app.use(function(req, res, next) {
// if (req.path === '/api/upload') {
// next();
// } else {
// lusca.csrf()(req, res, next);
// }
// });
app.use(lusca.xframe('SAMEORIGIN'));
app.use(lusca.xssProtection(true));
app.use(function(req, res, next) {
res.locals.user = req.user;
next();
});
app.use(function(req, res, next) {
// After successful login, redirect back to /api, /contact or /
if (/(api)|(contact)|(^\/$)/i.test(req.path)) {
req.session.returnTo = req.path;
}
next();
});
app.use(express.static(path.join(__dirname, 'public'), { maxAge: 31557600000 }));
app.use(express.static(path.join(__dirname, 'dist'), { maxAge: 31557600000 }));
app.use('/', require('./config/routes'))
/**
* Error Handler.
*/
app.use(errorHandler());
// // We only want to run the workflow when not in production
// var isProduction = config.currentEnv=== 'production';
// var proxy = httpProxy.createProxyServer();
// if (!isProduction) {
//
// // We require the bundler inside the if block because
// // it is only needed in a development environment. Later
// // you will see why this is a good idea
// var bundle = require('./bundle.js');
// bundle();
//
// // Any requests to localhost:3000/build is proxied
// // to webpack-dev-server
// app.all('/build/*', function (req, res) {
// proxy.web(req, res, {
// target: 'http://localhost:8080'
// });
// });
//
// }
// It is important to catch any errors from the proxy or the
// server will crash. An example of this is connecting to the
// server when webpack is bundling
proxy.on('error', function(e) {
console.log('Could not connect to proxy, please try again...');
});
/**
* Start Express server.
*/
const port = process.env.PORT || 3000
app.listen(port, function() {
console.log('Express server listening on port %d in %s mode', port, config.currentEnv);
});
module.exports = app;
|
JavaScript
| 0 |
@@ -412,239 +412,8 @@
%0A%7D%0A%0A
-// var fs = require('fs')%0A//%0A// fs.stat('.env', function(err, stat) %7B%0A// if(err == null) %7B%0A// console.log(%22loading .env%22);%0A// dotenv.load()%0A// %7D else %7B%0A// console.log(%22not loading .env%22);%0A// %7D%0A// %7D);%0A%0A
var
|
9a49144d5be10a1389658fc2f35fffcb7b1bbcff
|
Add middleware function to derive contentfulLocale
|
app.js
|
app.js
|
/*
* The application entry point
* Here all express middleware, routers, config, logging,
* globals and socket.io will be loaded / initialized.
*/
'use strict';
global.IS_TEST = process.env.FRONTEND_RUN_TESTS === 'true';
global.ROOT = require('path').resolve(__dirname);
const co = require('co');
const config = require('./config/config');
const sticky = require('sticky-cluster');
const path = require('path');
const fs = require('fs');
const morgan = require('morgan');
const express = require('express');
const exphbs = require('express-handlebars');
const bodyparser = require('body-parser');
const _ = require('lodash');
const socketio = require('socket.io');
const session = require('express-session');
const MongoStore = require('connect-mongo')(session);
const cookieParser = require('cookie-parser')();
const connectFlash = require('connect-flash')();
const http = require('http');
const logger = require('./services/logger');
require('newrelic');
const mongoose = require('./controller/mongo.js');
const passport = require('./services/auth.js');
const API = require('./services/api-proxy');
const websocket = require('./services/websocket');
function setupLogger(app) {
if (IS_TEST) return;
app.use(morgan('combined', {stream: fs.createWriteStream(ROOT + '/logs/access.log', {flags: 'a'})}));
}
// TODO: eslint ignore unused
// next may be unused but must be here in order to be work properly!
function genericErrorHandler(err, req, res, next) {
logger.error(err);
res.status(err.status || 500);
if (process.env.NODE_ENVIRONMENT === 'dev' || process.env.SHOW_ERROR === 'true') {
res.render('error', {
code: err.status,
message: err.message,
error: err
});
} else {
res.render('error', {
code: err.status,
message: 'Internal Server error'
});
}
}
function notFoundHandler(req, res) {
res.status(404);
res.render('error', {
code: 404,
message: req.url + ' could not be found on this server'
});
}
function sessionHandler(req, res, next) {
co(function*() {
if (req.isAuthenticated()
&& req.user.expires_at
&& new Date() > new Date(req.user.expires_at)
) {
const refr = yield API.refresh(req.user);
req.login(yield passport.createSession(req.user.email, refr), (error) => {
if (error) throw error;
next();
});
} else {
next();
}
}).catch(ex => {
logger.error(ex.stack);
req.logout();
req.flash('error', 'Something went wrong while refreshing your token. You were logged out.');
res.redirect('/');
});
}
function maintenanceView(req, res, next) {
if(req.app.get('maintenance')) {
res.render('dynamic/register/maintenance', {
layout: 'funnel',
language: req.language
});
} else {
next();
}
}
function checkForDuplicates(partialsDirs) {
// Read all files from the template directories and flatten them into one array
const readDirs = partialsDirs
.map(dir => fs.readdirSync(dir))
.reduce((first, second) => first.concat(second));
// If there are any duplicates in the list, they are different in length
const uniqueFiles = _.uniq(_.filter(readDirs, v => _.filter(readDirs, v1 => v1 === v).length > 1));
if (uniqueFiles.length) {
throw new Error('There are duplicate templates: ' + _.join(uniqueFiles));
}
}
function server(callback) {
const app = express();
// Register the static path here, to avoid getting them logged
app.use(express.static(path.join(__dirname, 'public')));
setupLogger(app);
// All dirs containing templates
const partialsDirs = [
'views/partials',
'views/templates'
];
checkForDuplicates(partialsDirs); // TODO: Why do we need this??
// Handlebars setup
const hbs = exphbs.create({
helpers: require('./services/helpers'),
partialsDir: partialsDirs
});
global.HBS = hbs;
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
if (process.env.NODE_ENVIRONMENT === 'prod' && !config.jwt_secret) {
throw new Error('No secret specified, please set one via jwt_secret');
}
if (process.env.NODE_ENVIRONMENT === 'prod' && process.env.SHOW_ERROR !== 'true') {
app.enable('view cache');
}
app.use(session({
secret: config.jwt_secret,
resave: false,
saveUninitialized: false,
store: new MongoStore({mongooseConnection: mongoose.connection})
}));
app.use(passport.initialize()); // Initialize password
app.use(passport.session()); // Restore authentication state, if any
app.use(bodyparser.urlencoded({extended: true}));
app.use(bodyparser.json());
app.use(cookieParser);
app.use(connectFlash);
app.use(require('./services/i18n').init); //Set language header correctly including fallback option.
app.use(sessionHandler);
app.use(maintenanceView);
// Routers
app.use('/', require('./routes/main'));
app.use('/', require('./routes/dynamic'));
app.use('/', require('./routes/static'));
app.use('/team', require('./routes/team'));
app.use('/post', require('./routes/posting'));
app.use('/messages', require('./routes/messages'));
app.use('/settings', require('./routes/settings'));
app.use('/admin', require('./routes/admin'));
// ENV specific setup
if(process.env.FRONTEND_MAINTENANCE) app.enable('maintenance');
else app.disable('maintenance');
var server = http.createServer(app);
const io = socketio(server);
websocket.init(io);
// The order is important here
// First try to handle errors
app.use(genericErrorHandler);
app.use(notFoundHandler);
if (callback) {
callback(server);
} else {
app.listen(3000);
}
}
if (!IS_TEST) {
sticky(server, {
port: 3000
});
}
module.exports = server;
|
JavaScript
| 0.000006 |
@@ -2801,16 +2801,416 @@
%0A %7D%0A%7D%0A%0A
+function contentfulLocale(req, res, next) %7B%0A var preferredLanguage = req.acceptsLanguages()%5B0%5D;%0A%0A%0A if (preferredLanguage.substring(0, 2) === 'de') %7B%0A preferredLanguage = 'de';%0A %7D else %7B%0A preferredLanguage = 'en-US';%0A %7D%0A%0A req.contentfulLocale = preferredLanguage;%0A logger.debug(%60Using contentfulLocale $%7BpreferredLanguage%7D from acceptsLanguage $%7Breq.acceptsLanguage()%5B0%5D%7D%60);%0A%0A next();%0A%7D%0A%0A
%0Afunctio
@@ -5217,24 +5217,54 @@
anceView);%0A%0A
+ app.use(contentfulLocale);%0A%0A
// Routers
|
de9432defb98f2736e7f54c0b179b1122823d2f7
|
Fix error handling
|
app.js
|
app.js
|
var leveldb = require('level'),
http = require('http'),
conf = require('./config'),
qs = require('querystring'),
fs = require('fs'),
express = require('express');
var db = leveldb('./urldb');
var app = express();
app.use(express.bodyParser());
app.use(express.static(__dirname + "/public"));
app.listen(3000)
function generateShortUrl(len) {
//http://tools.ietf.org/html/rfc3986 all valid characters
var allowedCharacters = 'abcdefghijklmnopqrstuvwxyABCDEFGHIJKLMNOPQRSTUVWXY-._~';
var out = "";
for(var i=0;i<len;i++) {
out += allowedCharacters[Math.floor(Math.random()*allowedCharacters.length)];
}
return out;
}
function limitedRunGetUnused(limit, len, cb) {
if(limit == 0) return cb("Error, could not generate short url");
var s = generateShortUrl(len);
db.get(s, function(err, value) {
if(err && err.notFound) return cb(false,s);
else limitedRunGetUnused(limit - 1, len, cb);
});
}
function getUnusedShortUrl(len, cb) {
limitedRunGetUnused(10, len, cb);
}
app.post('/api/shorten', function(req, res) {
var url = req.body.url.trim();
if(conf.disallowedUrlRegex.test(url) || url.length == 0) {
return res.json({error: "Invalid url to shorten"});
}
var short = generateShortUrl(4);
getUnusedShortUrl(4, function(err1, short) {
if(err1) return res.json({error: err1});
db.put(short, url, function(err) {
if(err) res.json({error: err});
else res.json({success: 1, shortUrl: conf.baseUrl + short});
});
});
});
app.post('/api/shorten2', function(req, res) {
var url = req.body.url.trim();
var short = req.body.short.trim();
var auth = req.body.auth.trim();
if(auth !== conf.adminkey) return res.json({error: "Invalid auth"});
db.get(short, function(err1, val) {
if(err1 && err1.notFound) {
db.put(short, url, function(err) {
if(err) res.json({error: err});
else res.json({success: 1, shortUrl: conf.baseUrl + short});
});
} else if(err1) {
res.json({error: err1});
} else {
res.json({error: "Short url already points to " + val});
}
});
});
app.get('/:id', function(req, res) {
var id = req.params.id;
db.get(id, function(err, value) {
if(err) console.log(err);
if(err && err.notFound) return res.write("No such short url. <a href='/'>Go home</a>");
res.redirect(302, value);
});
});
app.get('/api/info/:id', function(req, res) {
var id = req.params.id;
db.get(id, function(err, value) {
if(err) console.log(err);
if(err && err.notFound) return res.json({error: "No such short url"});
res.json({success: 1, longUrl: value});
});
});
|
JavaScript
| 0.000007 |
@@ -2216,34 +2216,20 @@
if(err)
-console.log(err);%0A
+%7B%0A
if(e
@@ -2222,39 +2222,32 @@
) %7B%0A if(err
- && err
.notFound) retur
@@ -2245,24 +2245,38 @@
nd)
-return res.write
+%7B%0A res.status(404).send
(%22No
@@ -2319,16 +2319,135 @@
%3C/a%3E%22);%0A
+ %7D else %7B%0A console.log(err);%0A res.status(404).send(%22Unknown error occured%22);%0A %7D%0A %7D else %7B%0A
res.
@@ -2469,16 +2469,22 @@
value);%0A
+ %7D%0A
%7D);%0A%7D)
@@ -2609,38 +2609,8 @@
(err
-) console.log(err);%0A if(err
&&
@@ -2669,16 +2669,120 @@
url%22%7D);
+%0A if(err) %7B%0A console.log(err);%0A return res.json(%7Berror: %22An unknown error occured%22%7D);%0A %7D
%0A res
|
50c882625cfe7be3f8eb4c169faa9f5eda03d2ab
|
Fix getting real IP address of requester.
|
app.js
|
app.js
|
var express = require('express'),
path = require('path'),
favicon = require('serve-favicon'),
logger = require('morgan'),
cookieParser = require('cookie-parser'),
bodyParser = require('body-parser'),
_ = require('lodash'),
db = require('./db'),
App = require('./models/App'),
UserController = require('./controllers/UserController'),
PushController = require('./controllers/PushController'),
app = express();
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
var authenticationMiddleware = function(req, res, next) {
var app = res.locals.app = req.get('X-App-Name'),
ip = req.ip || req.connection.remoteAddress;
// Check the app name
if (!app)
return res.status(417).end();
// Get the app
App.findOne({name: app}, function(err, aApp) {
if (err)
return res.status(500).end();
// Is request ip allowed?
if ((aApp.ips || []).indexOf(ip) > -1)
next();
else
res.status(401).end();
});
};
// Routes
app.get('/', function(req, res) { res.json({}); });
app.put('/user/:userId', authenticationMiddleware, UserController.upsert);
app.delete('/user/:userId/device', authenticationMiddleware, UserController.deleteDevice);
app.delete('/user/:userId', authenticationMiddleware, UserController.delete);
app.post('/message', authenticationMiddleware, PushController.send);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
|
JavaScript
| 0 |
@@ -865,16 +865,70 @@
ip =
+ req.get('X-Real-IP') %7C%7C req.get('X-Forwarded-For') %7C%7C
req.ip
@@ -953,17 +953,16 @@
remoteAd
-d
ress;%0A%0A
|
c49d40275a823b1d59a5648ccf90327458685fbe
|
Change HTTP call to HTTPS in response to error in API call after deploying to Heroku
|
app.js
|
app.js
|
/**
* Created by jadk157 on 2/6/16.
*/
(function(){
var app = angular.module('timeline', ['inputyear', 'ngAnimate']);
app.controller('TimelineController', ['$http', function($http){
var timeline = this;
timeline.year;
timeline.world = {
Europe: ["Germany", 'France', 'Britain', 'Italy', 'Spain', 'Russia', 'Turkey', 'Austria', 'Hungary', 'Norway', 'Sweden', 'Finland', 'Denmark', 'Estonia', 'Latvia', 'Lithuania', 'Serbia', 'Greece'],
"East Asia": ['China', 'Japan', 'Korea', 'North Korea', 'South Korea', 'Taiwan', 'Mongolia'],
"Southeast Asia": ['Thailand', 'Indonesia', 'Singapore', 'Vietnam', 'Laos', 'Cambodia', 'Malaysia', 'Burma', 'Brunei', 'East Timor'],
"Indian Subcontinent": ['India', 'Nepal', 'Bhutan', 'Maldives', 'Sri Lanka', 'Bangladesh', 'Pakistan'],
Americas: ['Brazil', 'Argentina', 'Mexico', 'Venezuela', 'Peru', 'Colombia', 'Bolivia', 'El Salvador', 'Guatemala', 'Costa Rica', 'Ecuador', 'Chile'],
Carribean: ['Cuba', 'Haiti', 'Dominican Republic', 'Jamaica', 'Bahamas', 'Curacao', 'Kitts', 'Barbados', 'Antigua', 'Bermuda'],
"North Africa": ['Egypt', 'Morocco', 'Tunisia', 'Libya', 'Western Sahara', 'Sudan'],
"Sub Saharan Africa": ['Liberia', 'Ethiopia', 'Egypt', 'Ghana', 'Somalia', 'Burundi', 'Botswana', 'Rwanda', 'Zimbabwe', 'South Africa', 'Chad', 'Nigeria', 'Benin', 'Togo', 'Equatorial Guinea', 'Senegal', 'Gambia', 'Zambia', 'Mozambique', 'Kenya', 'Tanzania'],
"Middle East": ['Israel', 'Palestine', 'Jordan', 'Lebanon', 'Syria', 'Iran', 'Iraq', 'Kuwait', 'Saudia Arabia', 'Yemen', 'Oman', 'United Arab Emirates', 'Qatar', 'Bahrain'],
Oceania: ['Australia', 'New Zealand', 'Papua New Guinea', 'Fiji', 'New Caledonia', 'Vanuatu', 'Tuvalu']
};
timeline.region = "";
timeline.articleList = [];
timeline.showFind = true;
timeline.showSearch = function() {
timeline.showFind = true;
return true;
};
timeline.hideSearch = function() {
timeline.showFind = false;
return true;
};
// Shows the list of articles to be pushed onto the screen
timeline.showArticles = function(){
console.log(timeline.articleList);
};
// Randomly selects countries from a region
timeline.randomizeCountries = function(region){
var countryList = region;
for(i = 0; i < countryList.length; i++){
var random = Math.floor((Math.random() * 10) + 1);
if(random > 7){
countryList.splice(i, 1);
}
}
return countryList;
};
// Adds to articleList the first article given back by the API query result that has
// the country's name either in its snippet or its headline
timeline.selectArticle = function(query, country){
var quota_fulfill = false;
for(j = 0; j < query.length; j++){
var snippet = query[j].snippet;
var main = query[j].headline.main;
if(snippet != null && main != null){
if((snippet.toUpperCase().includes(country) || main.toUpperCase().includes(country)) //making sure that the country is in the snippet or headline
&& quota_fulfill === false){
var newArticle = {
headline: "",
snippet: "",
country: country
};
newArticle.headline = query[j].headline.main;
newArticle.snippet = query[j].snippet;
if(!timeline.isDuplicate(newArticle)){
timeline.articleList.push(newArticle);
quota_fulfill = true;
}
}
}
}
console.log(timeline.articleList);
};
timeline.isDuplicate = function(newArticle){
var isDuplicate = false;
for(i = 0; i < timeline.articleList.length; i++){
if(newArticle.headline != "" && newArticle.headline === timeline.articleList[i].headline){
isDuplicate = true;
}
}
return isDuplicate;
};
timeline.submit = function(){
timeline.articleList = [];
timeline.hideSearch();
var countryList = timeline.randomizeCountries(timeline.world[timeline.region]);
for(i = 0; i < countryList.length; i++){
$http.get('http://api.nytimes.com/svc/search/v2/articlesearch.json?q='
+ countryList[i]
+ '&begin_date='
+ timeline.year
+ '0101&end_date='
+ (timeline.year + 1)
+ '0101&sort=oldest&fl=snippet%2Cheadline&api-key=db6c22023a90449345e4d9e999dabb02:2:74312658')
.success((function(i, countryList){ //solution 2 from http://stackoverflow.com/questions/19116815/how-to-pass-a-value-to-an-angularjs-http-success-callback accepted answer
return function(data){
var query = data.response.docs;
timeline.selectArticle(query, countryList[i].toUpperCase());
}
})(i, countryList));
};
};
}]);
})();
//ng-model='timeline.headline' ng-click='update(timeline.headline, timeline.startYear, timeline.endYear)'
|
JavaScript
| 0 |
@@ -4772,16 +4772,17 @@
et('http
+s
://api.n
|
a963656ac52fd70ac35c1819eca00b4c02416c58
|
test commit.
|
app.js
|
app.js
|
/*
* Melodycoder
* http://botobe.net/
*
* Copyright (c) 2013 Kai.XU
* Licensed under the MIT license.
*/
var express = require('express'), route = require('./RouterMap'), http = require('http'), path = require('path'), db = require('./model/db'), config = require('./config').config;
var app = express();
app.configure(function() {
app.use(express.cookieParser());
app.use(express.session({
secret : config.SESSION_SECRET
}));
app.use(db.initialize());
app.set('port', process.env.PORT || 3000);
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(require('stylus').middleware(__dirname + '/public'));
app.use(express.static(path.join(__dirname, 'public')));
});
// 开发环境
app.configure('development', function() {
app.use(express.logger('dev'));
app.use(express.errorHandler());
});
// 生产环境
app.configure('production', function() {
app.use(express.compress());
});
route(app);
http.createServer(app).listen(app.get('port'));
|
JavaScript
| 0 |
@@ -146,17 +146,19 @@
press'),
-
+%0D%0A%09
route =
@@ -180,17 +180,19 @@
erMap'),
-
+%0D%0A%09
http = r
@@ -206,17 +206,19 @@
'http'),
-
+%0D%0A%09
path = r
@@ -232,17 +232,19 @@
'path'),
-
+%0D%0A%09
db = req
@@ -262,17 +262,19 @@
el/db'),
-
+%0D%0A%09
config =
@@ -428,17 +428,16 @@
%09%09secret
-
: config
@@ -1104,14 +1104,12 @@
et('port'));
-%0D%0A
|
22d038cd8cfc5ba4b5cda91768d56135a7208c80
|
Debug logs and fixes
|
app.js
|
app.js
|
'use strict';
const DEVICE_ID = process.env.DEVICE_ID;
const PORT = 8080;
let fs = require('fs');
let url = require('url');
let http = require('http');
let async = require('async');
let sqlite3 = require('sqlite3').verbose();
let express = require('express');
let readline = require('readline');
let WebSocket = require('ws');
let db;
async.series([
function (done) {
db = new sqlite3.Database('./db/rb.db', done);
},
function (done) {
db.serialize(function () {
db.run('CREATE TABLE IF NOT EXISTS attendance(id INTEGER PRIMARY KEY, write_date DATETIME, create_date DATETIME, full_name TEXT, country_represented INT, rfid_tag TEXT, attendance_id INT, id_photo BLOB, country_image BLOB)');
db.run('CREATE TABLE IF NOT EXISTS country(id INTEGER PRIMARY KEY,name TEXT, image BLOB)');
db.run('CREATE TABLE IF NOT EXISTS meeting_log(id INTEGER PRIMARY KEY AUTOINCREMENT, write_date DATETIME, rfid_tag TEXT, machine_code TEXT, sync INT)');
done();
});
},
/*function (done) {
let ws = new WebSocket('ws://54.87.230.167:8052');
ws.on('open', function open() {
console.log('Websocket Connection to Reekoh initialized.');
done();
});
ws.on('message', function (data) {
console.log(data);
});
},*/
function (done) {
let app = express();
let server = http.createServer(app);
let wss = new WebSocket.Server({server: server});
app.use(express.static('./public'));
app.get('/', function (req, res) {
fs.readFile('./public/index.html', 'utf8', function (err, text) {
res.send(text);
});
});
wss.broadcast = function broadcast(data) {
async.each(wss.clients, function (client, cb) {
if (client.readyState === WebSocket.OPEN) client.send(data);
cb();
});
};
wss.on('error', function (err) {
console.error('Error on Websocket Server.');
console.error(err);
setTimeout(function () {
process.exit(1);
}, 3000);
});
wss.on('connection', function connection(ws) {
ws.on('message', function (message) {
console.log('received: %s', message);
});
});
SerialPort.list(function (err, ports) {
async.each(ports, function (port, done) {
console.log(port);
let rfIdPort = new SerialPort(port.comName, {
baudRate: 115200,
autoOpen: false
});
rfIdPort.on('error', function (err) {
console.error('Error on Serial Port.');
console.error(err);
setTimeout(function () {
process.exit(1);
}, 3000);
});
let reader = readline.createInterface({
input: rfIdPort,
output: process.stdout,
terminal: false
});
reader.on('line', function (line) {
db.get('SELECT a.id, a.full_name, a.id_photo, c.image FROM attendance a left join country c on c.name = a.country_represented where a.rfid_tag = $tag', {
$tag: line
}, function (err, row) {
let msg = '';
if (err || !row) {
msg = `<div class="content-bg">
<img src="/assets/asean_logos.png" class="wide-img main-img img-responsive center-block"/>
<br/>
<img src="/assets/avatar.png" class="wide-img main-img img-responsive center-block" />
<br/><br/>
<h1 class="participant">${row.full_name || ''}</h1>
</div>`;
}
else {
msg = `<div class="content-bg">
<img src="/assets/asean_logos.png" class="wide-img main-img img-responsive center-block"/>
<br/>
<img src="data:;base64,${row.id_photo}" class="wide-img main-img img-responsive center-block" />
<br/><br/>
<h1 class="participant">${row.full_name}</h1>
<br/>
<img src="data:;base64,${row.image}" class="img-flag main-img img-responsive center-block" />
</div>`;
}
wss.broadcast(msg);
});
});
rfIdPort.open(function (err) {
if (err) {
console.error(`Error opening port ${port.comName}`);
console.error(err);
return setTimeout(function () {
process.exit(1);
}, 3000);
}
console.log(`Port ${port.comName} has been opened.`);
});
done();
});
});
server.listen(PORT, done);
}
], function (err) {
if (err) {
console.error(err);
return process.exit(1);
}
console.log('Web server now listening on %s', PORT);
});
|
JavaScript
| 0 |
@@ -321,16 +321,56 @@
e('ws');
+%0Alet SerialPort = require('serialport');
%0A%0Alet db
@@ -2653,24 +2653,49 @@
on (line) %7B%0A
+%09%09%09%09%09console.log(line);%0A%0A
%09%09%09%09%09db.get(
|
630d0683e59e2e645a3e95a3d03823b1d25ba987
|
Disable dev tools
|
app.js
|
app.js
|
/* Tèsèvè
* A simple static webserver, in an app.
*
* ~/app.js - Application entry point
* started at 25/08/2015, by leny@flatLand!
*/
"use strict";
var electron = require( "app" ),
BrowserWindow = require( "browser-window" ),
path = require( "path" ),
lodash = require( "lodash" ),
os = require( "os" ),
Menu = require( "menu" );
global.app = {
"windows": {}
};
var oMenu = [
{
"label": "Tèsèvè",
"submenu": [
{
"label": "About Tèsèvè",
"selector": "orderFrontStandardAboutPanel:"
},
{
"type": "separator"
},
{
"label": "Services",
"submenu": []
},
{
"type": "separator"
},
{
"label": "Hide Electron",
"accelerator": "CmdOrCtrl+H",
"selector": "hide:"
},
{
"label": "Hide Others",
"accelerator": "CmdOrCtrl+Shift+H",
"selector": "hideOtherApplications:"
},
{
"label": "Show All",
"selector": "unhideAllApplications:"
},
{
"type": "separator"
},
{
"label": "Quit",
"accelerator": "CmdOrCtrl+Q",
"selector": "terminate:"
}
]
},
{
"label": "Server",
"submenu": [
{
"label": "New Server",
"accelerator": "CmdOrCtrl+N",
"click": function() {
console.log( "Create new window!" );
}
},
{
"type": "separator"
},
{
"label": "Close Server",
"accelerator": "CmdOrCtrl+W",
"click": function() {
console.log( "Close current window!" );
}
},
{
"label": "Close All Servers",
"accelerator": "CmdOrCtrl+Shift+W",
"click": function() {
console.log( "Close current window!" );
}
},
]
}
];
electron.on( "window-all-closed", function() {
return electron.quit(); // TODO: TMP
if( process.platform !== "darwin" ) {
electron.quit();
}
} );
electron.on( "ready", function() {
// Menu.setApplicationMenu( Menu.buildFromTemplate( oMenu ) );
var oWindow = new BrowserWindow( {
"id": lodash.uniqueId(),
"title": "Tèsèvè",
"icon": path.resolve( __dirname, "assets/icon.png" ),
"width": 640,
"height": 480,
"min-width": 640,
"min-height": 480,
"center": true,
"standard-window": false,
"resizable": true,
"frame": false,
"show": false
} );
oWindow.openDevTools();
global.app.windows[ oWindow.id ] = oWindow;
oWindow.on( "closed", function( a, b, c, d ) {
delete global.app.windows[ this.id ];
oWindow = null;
} );
oWindow.loadUrl( "file://" + __dirname + "/app.html" );
} );
|
JavaScript
| 0.000001 |
@@ -2996,32 +2996,35 @@
se%0A %7D );%0A%0A
+ //
oWindow.openDev
|
b44016df5b8c92256fd4dcfe37087e840ef98574
|
make some changes into the express app
|
app.js
|
app.js
|
// Dependencies
var express = require('express')
var bodyParser = require('body-parser')
var DoorRemoteControl = require('./lib/doorRemoteControl')
var auth = require('./lib/auth')
var config = require('../config')
var app = express()
var door = new DoorRemoteControl()
app.use(express.static('public'))
app.set('views', __dirname + '/views')
app.set('view engine', 'jsx')
app.engine('jsx', require('express-react-views').createEngine())
// parse application/json
app.use(bodyParser.json())
app.get('/keymaster-status', function (req, res) {
door.status(function (err) {
if (err) {
return res.status(503).send('KEYMASTER DOWN')
}
return res.sendStatus(200)
})
})
app.post('/', function (req, res) {
if (!req.body || !auth(req.body.passphrase)) {
return res.status(401).send('YOU SHALL NOT PASS!!1')
}
door.open(function (err) {
if (err) {
return res.status(503).send('KEYMASTER DOWN')
}
return res.sendStatus(200)
})
})
app.listen(config.http.port)
|
JavaScript
| 0.000043 |
@@ -145,41 +145,8 @@
l')%0A
-var auth = require('./lib/auth')%0A
var
@@ -164,17 +164,16 @@
quire('.
-.
/config'
@@ -270,143 +270,8 @@
))%0A%0A
-app.set('views', __dirname + '/views')%0Aapp.set('view engine', 'jsx')%0Aapp.engine('jsx', require('express-react-views').createEngine())%0A%0A
// p
@@ -328,30 +328,15 @@
app.
-ge
+pos
t('/
-keymaster-status
', f
@@ -363,22 +363,20 @@
%0A door.
-status
+open
(functio
@@ -499,34 +499,28 @@
%7D)%0A%7D)%0A%0Aapp.
-post('/',
+use(
function (re
@@ -535,254 +535,24 @@
%7B%0A
-if (!req.body %7C%7C !auth(req.body.passphrase)) %7B%0A return res.status(401).send('YOU SHALL NOT PASS!!1')%0A %7D%0A%0A door.open(function (err) %7B%0A if (err) %7B%0A return res.status(503).send('KEYMASTER DOWN')%0A %7D%0A%0A return res.sendStatus(200)%0A %7D
+res.redirect('/'
)%0A%7D)
|
8bcc935474059b2d12bc2126a3a5201ad2449292
|
fix details
|
app.js
|
app.js
|
const express = require('express');
const path = require('path');
const favicon = require('serve-favicon');
const logger = require('morgan');
const bodyParser = require('body-parser');
const http = require('http');
const ejs = require('ejs');
const index = require('./routes/index');
const tongqu = require('./routes/tongqu');
const contact = require('./routes/contact');
const app = express();
app.set('views', path.join(__dirname, 'views'));
app.engine('.html', ejs.__express);
app.set('view engine', 'html');
app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/tongqu', express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/tongqu', tongqu);
app.use('/contact', contact);
app.set('port', process.env.PORT || 3000);
app.set('host', '127.0.0.1');
const server = http.createServer(app).listen(app.get('port'), app.get('host'), function() {
console.log(`Qingniao website server listening on port ${app.get('port')} at host ${app.get('host')}`);
});
app.use((req, res, next) => {
let err = new Error('Not Found');
err.status = 404;
next(err);
});
app.use((err, req, res, next) => {
res.status(err.status || 500);
res.render('consolerror', {
active: {
index: '',
tongqu: '',
contact: 'active'
},
consolerror: {
title: "404",
content: err.message
}
});
});
module.exports = app;
|
JavaScript
| 0.000162 |
@@ -25,24 +25,54 @@
'express');%0A
+const http = require('http');%0A
const path =
@@ -212,38 +212,8 @@
');%0A
-const http = require('http');%0A
cons
@@ -907,28 +907,8 @@
rt',
- process.env.PORT %7C%7C
300
|
df655f4dfa65e4bb86199eaa219a702805daa216
|
Remove code to handle the nonexistant reset button
|
app.js
|
app.js
|
global.$ = $;
var fs = require('fs');
var process = require('process');
var app = require('electron').remote.app;
var dialog = require('electron').remote.dialog;
var execFile = require('child_process').execFile;
var bootloader_ready = false;
var flash_in_progress = false;
var dfu_location = 'dfu/dfu-programmer';
if (process.platform == "win32") {
dfu_location = dfu_location + '.exe'
}
fs.access(dfu_location, fs.F_OK, function(err) {
if (err) {
// Running in deployed mode, use the app copy
var dfu_location = app.getAppPath() + '/' + dfu_location;
}
});
$(document).ready(function() {
// Handle drag-n-drop events
$(document).on('dragenter dragover', function(event) {
event.preventDefault();
event.stopPropagation();
});
$(document).on('drop', function(event) {
event.preventDefault();
event.stopPropagation();
var file = event.originalEvent.dataTransfer.files[0];
loadHex(file.path);
});
$(document).on('open-file', function(event, path) {
event.preventDefault();
event.stopPropagation();
loadHex(path);
});
// Bind actions to our buttons
$('#flash-hex').attr('disabled','disabled');
$('#close-window-button').bind('click', function (event) {
window.close();
});
$('#load-file').bind('click', function (event) {
loadHex(loadFile()[0]);
});
$('#flash-hex').bind('click', function (event) {
disableButtons();
sendHex($("#file-path").val(), function(success) {
if (success) {
sendStatus("Flashing complete!");
} else {
sendStatus("An error occured - please try again.");
}
});
});
$('#reset').bind('click', function (event) {
disableButtons();
resetChip(function(success) {
enableButtons();
if (success) {
sendStatus("Reset complete!");
} else {
sendStatus("An error occured - please try again.");
}
});
});
// Ready to go
execFile(dfu_location, ['--version'], function(error, stdout, stderr) {
if (stderr.indexOf('dfu-programmer') > -1) {
window.setTimeout(checkForBoard, 10);
sendStatus("Select a firmware file by clicking 'Choose .hex' or drag and drop a file onto this window.");
} else {
sendStatus("Could not run dfu-programmer! Please report this as a bug!");
sendStatus("<br>Debugging information:<br>");
sendStatus(error);
sendStatus("stdout:");
writeStatus(stdout);
sendStatus("stderr:");
writeStatus(stderr);
}
});
});
function loadHex(filename) {
// Load a file and prepare to flash it.
if (filename.slice(-4) != '.hex') {
sendStatus("Invalid firmware file: " + filename);
return;
}
$("#file-path").val(filename);
enableButtons();
clearStatus();
if (!bootloader_ready) sendStatus("Press RESET on your keyboard's PCB.");
}
function disableButtons() {
$('#flash-hex').attr('disabled','disabled');
$('#flash-hex').css('background-color', 'red');
$('#flash-hex').css('color', 'black');
}
function enableButtons() {
if (bootloader_ready && $('#file-path').val() != "") {
$('#flash-hex').removeAttr('disabled');
$('#flash-hex').css('background-color', 'green');
$('#flash-hex').css('color', 'white');
}
}
function clearStatus() {
$('#status').text('');
}
function writeStatus(text) {
$('#status').append(text);
$('#status').scrollTop($('#status')[0].scrollHeight);
}
function sendStatus(text) {
writeStatus('<b>' + text + "</b>\n");
}
function loadFile() {
return dialog.showOpenDialog({
properties: [ 'openFile' ],
filters: [
{ name: 'Custom File Type', extensions: ['hex'] }
]
});
}
function sendHex(file, callback) {
flash_in_progress = true;
eraseChip(function(success) {
if (success) {
// continue
flashChip(file, function(success) {
if (success) {
// continue
resetChip(function(success) {
if (success) {
// completed successfully
callback(true);
} else {
callback(false)
}
});
} else {
// memory error / other
callback(false);
}
});
} else {
// no device / other error
callback(false);
}
});
flash_in_progress = false;
};
/*
var escapeShell = function(cmd) {
return ''+cmd.replace(/(["\s'$`\\\(\)])/g,'\\$1')+'';
};
*/
function eraseChip(callback) {
sendStatus('dfu-programmer atmega32u4 erase --force');
execFile(dfu_location, ['atmega32u4', 'erase', '--force'], function(error, stdout, stderr) {
sendStatus(error);
writeStatus(stdout);
writeStatus(stderr);
var regex = /.*Success.*\r?\n|\rChecking memory from .* Empty.*/;
if (regex.test(stderr)) {
callback(true);
} else {
callback(false);
}
});
}
function flashChip(file, callback) {
sendStatus('dfu-programmer atmega32u4 flash ' + file);
execFile(dfu_location, ['atmega32u4', 'flash', file], function(error, stdout, stderr) {
writeStatus(stdout);
writeStatus(stderr);
if (stderr.indexOf("Validating... Success") > -1) {
callback(true);
} else {
callback(false);
}
});
}
function resetChip(callback) {
sendStatus('dfu-programmer atmega32u4 reset');
execFile(dfu_location, ['atmega32u4', 'reset'], function(error, stdout, stderr) {
writeStatus(stdout);
writeStatus(stderr);
if (stderr == "") {
callback(true);
} else {
callback(false);
}
});
}
function checkForBoard() {
if (!flash_in_progress) {
execFile(dfu_location, ['atmega32u4', 'get', 'bootloader-version'], function(error, stdout, stderr) {
if (stdout.indexOf("Bootloader Version:") > -1) {
if (!bootloader_ready && $('#file-path').val() != "") clearStatus();
bootloader_ready = true;
if ($('#file-path').val() != "") enableButtons();
} else {
bootloader_ready = false;
disableButtons();
}
});
}
window.setTimeout(checkForBoard, 10000);
}
|
JavaScript
| 0.000002 |
@@ -1624,291 +1624,8 @@
%7D);
-%0A $('#reset').bind('click', function (event) %7B%0A disableButtons();%0A resetChip(function(success) %7B%0A enableButtons();%0A if (success) %7B%0A sendStatus(%22Reset complete!%22);%0A %7D else %7B%0A sendStatus(%22An error occured - please try again.%22);%0A %7D%0A %7D);%0A %7D);
%0A%0A
|
ffc22f9a2578d3e139c969724bab39b0c2f20af6
|
test mokies4
|
app.js
|
app.js
|
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Found kies mohamed');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// 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');
});
module.exports = app;
|
JavaScript
| 0 |
@@ -890,16 +890,27 @@
mohamed
+ abdelkader
');%0A er
|
b0811a0b004659a5f4a4bbf4006c9c4949ca2977
|
change port to 4000
|
app.js
|
app.js
|
const serve = require('koa-static');
const Koa = require('koa');
const app = new Koa();
const logger = require('koa-logger');
const buildPage = require('./util/build-page.js');
// styles.build();
app.proxy = true;
app.use(logger());
app.use(serve('public/autograph', {
index: false
}));
app.use(async (ctx) => {
console.log('Home page');
ctx.body = await buildPage();
});
const server = app.listen(process.env.PORT || 3000)
server.on('listening', () => {
console.log(`Client listening on port ${process.env.PORT || 3000}`);
});
|
JavaScript
| 0.000238 |
@@ -417,17 +417,17 @@
PORT %7C%7C
-3
+4
000)%0Aser
@@ -519,9 +519,9 @@
%7C%7C
-3
+4
000%7D
|
ccd95230842507aba76a36baccbfbbaa69ba9b1c
|
version 9
|
app.js
|
app.js
|
/**
* Copyright 2015 IBM Corp. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
var express = require('express'); // app server
var bodyParser = require('body-parser'); // parser for post requests
var Conversation = require('watson-developer-cloud/conversation/v1'); // watson sdk
var request = require('request'); // http requests
var app = express();
// Bootstrap application settings
app.use(express.static('./public')); // load UI from public folder
app.use(bodyParser.json());
// Create the service wrapper
var conversation = new Conversation({
// If unspecified here, the CONVERSATION_USERNAME and CONVERSATION_PASSWORD env properties will be checked
// After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
// username: '<username>',
// password: '<password>',
url: 'https://gateway.watsonplatform.net/conversation/api',
version_date: '2016-10-21',
version: 'v1'
});
function callback(error, response, body) {
if (!error) {
var info = JSON.parse(JSON.stringify(body));
console.log(info);
}
else {
console.log('Error happened: '+ error);
}
}
// Endpoint to be call from the client side
app.post('/api/message', function(req, res) {
var workspace = process.env.WORKSPACE_ID || '<workspace-id>';
if (!workspace || workspace === '<workspace-id>') {
return res.json({
'output': {
'text': 'The app has not been configured with a <b>WORKSPACE_ID</b> environment variable. Please refer to the ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple">README</a> documentation on how to set this variable. <br>' + 'Once a workspace has been defined the intents may be imported from ' + '<a href="https://github.com/watson-developer-cloud/conversation-simple/blob/master/training/car_workspace.json">here</a> in order to get a working application.'
}
});
}
var payload = {
workspace_id: workspace,
context: req.body.context || {},
input: req.body.input || {}
};
// Send the input to the conversation service
conversation.message(payload, function(err, data) {
if (err) {
return res.status(err.code || 500).json(err);
}else
{
/*
console.log("Temp:", data.context.temperature);
if(data.context && data.context.temperature_set==='true')
{
console.log("Test temp");
}
*/
//onsole.log("Test: ",data);
if(data.context && data.context.finished==='true')
{
var path = "book";
if(data.context.atcar == 'true') {
path = "car"
console.log("test_path", path);
}
if(data.context.targetadress != 'null')
{
path = "sms_giveback";
}
var request = require('request');
var conversation_answer = data;
var options = {
method: 'POST',
url: 'https://CognitiveCarBookingApp.mybluemix.net/' + path,
headers: {
'Content-Type': 'application/json'
},
json: conversation_answer
};
//send request with conversation data result to next service
request(options, function(err, result, body) {
//console.log("CAROLINE", err);
//console.log("Result:", body);
data.extra = body;
return res.json(updateMessage(payload, data));
});
} else {
return res.json(updateMessage(payload, data));
}
}
}
);
});
/**
* Updates the response text using the intent confidence
* @param {Object} input The request to the Conversation service
* @param {Object} response The response from the Conversation service
* @return {Object} The response with the updated message
*/
function updateMessage(input, response) {
var responseText = null;
if (!response.output) {
response.output = {};
} else {
return response;
}
if (response.intents && response.intents[0]) {
var intent = response.intents[0];
// Depending on the confidence of the response the app can return different messages.
// The confidence will vary depending on how well the system is trained. The service will always try to assign
// a class/intent to the input. If the confidence is low, then it suggests the service is unsure of the
// user's intent . In these cases it is usually best to return a disambiguation message
// ('I did not understand your intent, please rephrase your question', etc..)
if (intent.confidence >= 0.75) {
responseText = 'I understood your intent was ' + intent.intent;
} else if (intent.confidence >= 0.5) {
responseText = 'I think your intent was ' + intent.intent;
} else {
responseText = 'I did not understand your intent';
}
}
response.output.text = responseText;
return response;
}
module.exports = app;
|
JavaScript
| 0 |
@@ -3266,16 +3266,20 @@
%09%09%7D%0A%09%09%09%0A
+%09%09%09%0A
%09%09%09var r
|
17e1c4d65ca2e537bbedafd113f1205d8d3bb29a
|
Update app.js
|
app.js
|
app.js
|
var myApp = angular.module('myApp',[]);
myApp.controller('MyController', function($scope) {
$scope.spices = [{"name":"pasilla", "spiciness":"mild"},
{"name":"jalapeno", "spiciness":"hot hot hot!"},
{"name":"habanero", "spiciness":"LAVA HOT!!"}];
$scope.spice = "habanero";
});
|
JavaScript
| 0.000001 |
@@ -313,8 +313,565 @@
o%22;%0A%7D);%0A
+%0A//Controller test:%0Adescribe('myController function', function() %7B%0A%0A describe('myController', function() %7B%0A var $scope;%0A%0A beforeEach(module('myApp'));%0A%0A beforeEach(inject(function($rootScope, $controller) %7B%0A $scope = $rootScope.$new();%0A $controller('MyController', %7B$scope: $scope%7D);%0A %7D));%0A%0A it('should create %22spices%22 model with 3 spices', function() %7B%0A expect($scope.spices.length).toBe(3);%0A %7D);%0A%0A it('should set the default value of spice', function() %7B%0A expect($scope.spice).toBe('habanero');%0A %7D);%0A %7D);%0A%7D);%0A
|
7510002343b54d1393fae9dcdae1dacaf1c8bfb1
|
Revert "bad commit"
|
app.js
|
app.js
|
/**
* app.js - Entry point for Express NodeJS server.
* Modified from default template generated by Express.
* Authors: Ian McGaunn; Dave Zimmelman
* Modified: 09 Mar 15
*/
var express = require('express');
var session = require('express-session');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var browse = require('./routes/browse');
var search = require('./routes/search');
var users = require('./routes/users');
var test = require('./routes/test');
var api = require('./routes/api');
var podcast = require('./routes/podcast');
var badcache = require('./lib/badcache');
var users = require('./lib/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(session({secret: 'hotsaucerman'})); // Secret session key: can be any string
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', index);
app.use('/browse', browse);
app.use('/search', search);
app.use('/users', users);
app.use('/test', test);
app.use('/api', api);
app.use('/podcast', podcast);
// Makes generated HTML not look like garbage
app.locals.pretty = true;
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
users.registerUser('podplay', '[email protected]', 'pcast123', function (err, o) {
console.log(err);
console.log(o);
}, function (data) {
console.log(data);
console.log("success");
});
// Update top 100 cache every 2 hours
badcache.update_top100();
var top100timer = setInterval(badcache.update_top100, 1000 * 60 * 60 * 2)
module.exports = app;
|
JavaScript
| 0 |
@@ -755,44 +755,8 @@
e');
-%0Avar users = require('./lib/users');
%0A%0Ava
@@ -2200,206 +2200,8 @@
);%0A%0A
-users.registerUser('podplay', '[email protected]', 'pcast123', function (err, o) %7B%0A console.log(err);%0A console.log(o);%0A%7D, function (data) %7B%0A console.log(data);%0A console.log(%22success%22);%0A%7D);%0A%0A
// U
|
8b7513f837e357c6d33e17b6da18d2be1ac2bc99
|
Change tab font-family
|
app.js
|
app.js
|
(function($) {
"use strict";
if (Echo.App.isDefined("Echo.Apps.TopicRadar")) return;
var radar = Echo.App.manifest("Echo.Apps.TopicRadar");
radar.config = {
"tabs": []
};
radar.templates.main =
'<div class="{class:container}">' +
'<div class="{class:tabs}"></div>' +
'<div class="{class:panels}"></div>' +
'</div>';
radar.templates.panel =
'<div class="{class:panel} {class:panel}-{data:index}"></div>';
radar.templates.column =
'<div class="{class:column} {class:column}-{data:index}"></div>';
radar.templates.instance =
'<div class="{class:instance} {class:instance}-{data:index}"></div>';
radar.init = function() {
this.render();
this.ready();
};
radar.renderers.tabs = function(element) {
var self = this;
element.empty();
var tabs = this.config.get("tabs");
if (tabs.length <= 1) {
element.hide();
}
new Echo.GUI.Tabs({
"target": element,
"panels": this.view.get("panels"),
"entries": $.map(tabs, function(tab, tabIndex) {
return {
"id": "tab-" + tabIndex,
"label": tab.title,
"extraClass": self.cssPrefix + "tab-" + tabIndex,
"panel": (function(columns) {
var panel = $(self.substitute({
"template": self.templates.panel,
"data": {
"index": tabIndex
}
}));
$.each(columns || [], function(columnIndex, column) {
var columnContainer = $(self.substitute({
"template": self.templates.column,
"data": {
"index": columnIndex
}
}));
self.view.render({
"name": "_column",
"target": columnContainer,
"extra": {"column": column}
});
panel.append(columnContainer);
});
return panel;
})(tab.columns)
};
})
});
return element;
};
radar.renderers._column = function(element, extra) {
var self = this;
var column = extra && extra.column;
if (column.width) {
element.css("width", column.width);
}
$.each(column.instances || [], function(instanceIndex, instance) {
var container = $(self.substitute({
"template": self.templates.instance,
"data": {
"index": instanceIndex
}
}));
element.append(container);
Echo.Loader.initApplication($.extend(true, {
"config": {
"target": container,
"context": self.config.get("context")
}
}, instance));
});
return element.addClass(this.cssPrefix + "column");
};
radar.dependencies = [{
"loaded": function() { return !!Echo.GUI; },
"url": "{config:cdnBaseURL.sdk}/gui.pack.js"
}, {
"url": "{config:cdnBaseURL.sdk}/gui.pack.css"
}];
radar.css =
'.{class:panel} { table-layout: fixed; }' +
'.echo-sdk-ui .{class:panels}.tab-content > .active { display: table; table-layout: fixed; width: 100%; }' +
'.{class:column} { display: table-cell; vertical-align: top; }' +
'.{class:column} { padding-right: 10px; }' +
'.{class:column}:last-child { padding-right: 0px; }' +
'.{class:instance} { padding-bottom: 10px; }' +
'.{class:instance}:last-child { padding-bottom: 0px; }' +
// TODO remove this code when F:2086 will be fixed.
'.echo-appserver-controls-preview-content .{class:container} .echo-canvas-appContainer { margin: 0px; border: 0px; padding: 0px; background: transperent; }';
Echo.App.create(radar);
})(Echo.jQuery);
|
JavaScript
| 0.000001 |
@@ -1048,28 +1048,106 @@
elf.
-cssPrefix + %22tab-%22 +
+substitute(%7B%0A%09%09%09%09%09%22template%22: %22%7Bclass:tab%7D %7Bclass:tab%7D-%7Bdata:tabIndex%7D%22,%0A%09%09%09%09%09%22data%22: %7B%22tabIndex%22:
tab
@@ -1147,24 +1147,32 @@
x%22: tabIndex
+%7D%0A%09%09%09%09%7D)
,%0A%09%09%09%09%22panel
@@ -2744,24 +2744,100 @@
100%25; %7D' +%0A
+%09'.%7Bclass:tab%7D %3E a %7B font-family: %22Helvetica Neue%22, arial, sans-serif; %7D' +%0A
%09'.%7Bclass:co
|
a8fbed4327f9464423224a01a240e3b3931ccc89
|
Add res.send(...) to close client response
|
app.js
|
app.js
|
//Set up Reqs
var express = require('express');
var bodyParser = require('body-parser');
var request = require('request');
var qs = require('querystring');
//set up heroku environment variables
var env_var = {
ga_key: process.env.GOOGLE_ANALYTICS_UAID
};
//Server Details
var app = express();
var port = process.env.PORT || 3000;
//Set Body Parser
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());
app.use(bodyParser.json({ type: 'application/vnd.api+json' }));
//Routes
app.get('/', function(req, res){
res.send('here');
});
app.post('/collect', function(req, res){
var channel = {
id: req.body.channel_id,
name: req.body.channel_name
};
var user = {
id: req.body.user_id
};
var msgText = req.body.text;
var teamDomain = req.body.team_domain;
function searchM(regex){
var searchStr = msgText.match(regex);
if(searchStr != null){
return searchStr.length;
}
return 0;
};
function searchS(regex){
var searchStr = msgText.split(regex);
if(searchStr != undefined){
return searchStr.length;
}
return 0;
};
var wordCount = searchS(/\s+\b/);
var emojiCount = searchM(/:[a-z_0-9]*:/g);
var exclaCount = searchM(/!/g);
var questionMark = searchM(/\?/g);
var elipseCount = searchM(/\.\.\./g);
//Structure Data
var data = {
v: 1,
tid: env_var.ga_key,
cid: user.id,
ds: "slack", //data source
cs: "slack", // campaign source
cd1: user.id,
cd2: channel.name,
cd3: msgText,
cm1: wordCount,
cm2: emojiCount,
cm3: exclaCount,
// cm4: letterCount,
cm5: elipseCount,
cm6: questionMark, //need to set up in GA
dh: teamDomain+".slack.com",
dp: "/"+channel.name,
dt: "Slack Channel: "+channel.name,
t: "event",
ec: "slack: "+ channel.name + "|" + channel.id,
ea: "post by " + user.id,
el: msgText,
ev: 1
};
console.log(JSON.stringify(data));
console.log(req.body);
//Make Post Request
request.post("https://www.google-analytics.com/collect?" + qs.stringify(data),
function(error, resp, body){
console.log(error);
})
});
//Start Server
app.listen(port, function () {
console.log('Listening on port ' + port);
});
|
JavaScript
| 0 |
@@ -2157,16 +2157,33 @@
;%0D%0A%09%7D)%0D%0A
+%09res.send(%22OK%22)%0D%0A
%7D);%0D%0A%0D%0A/
|
231a4db3c461a0523ed7f24212bfdd67756031e0
|
Fix missing ;
|
app.js
|
app.js
|
var http = require('http');
var hellobot = require('./hellobot');
var express = require('express');
var bodyParser = require('body-parser');
//var $ = require('jQuery');
var ig = require('instagram-node').instagram({});
var Slack = require('node-slack');
var slack = new Slack("https://hooks.slack.com/services/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");
var app = express();
var port = process.env.PORT || 3000;
// body parser middleware
app.use(bodyParser.urlencoded({ extended: true}));
app.use(bodyParser.json());
// --------------------------------
// Instagram Authentification
// Overide instagram authentification
ig.use({
client_id: "bd09eab6bd9b4c9daf691a550faf04a9",
client_secret: "e37f5afad6e74ac5906380de076da0d4"
});
// Slash command login
app.post('/slash', function (req, res) {
if (req.query.text == "login") {
slack.send({
text: "<https://lit-journey-12058.herokuapp.com/authorize_user|Sign in from here!>"
});
res.send("Login slash tag detected")
} else {
slack.send({
text: "Can't recognize the tag. Try something else plz."
});
res.send("Slash tag can't be recognized");
}
});
// Below links kept here for testing purposes
//https://lit-journey-12058.herokuapp.com/handleauth
//http://localhost:3000/handleauth
var redirect_uri = "https://lit-journey-12058.herokuapp.com/handleauth";
// Authorize the user by redirecting user to sign in page
exports.authorize_user = function(req, res) {
res.redirect(ig.get_authorization_url(redirect_uri,
{ scope: ['likes'],
state: 'a state' }));
};
// Send message on #general that the user is signed in
exports.handleauth = function(req, res) {
ig.authorize_user(req.query.code, redirect_uri, function(err, result) {
if (err) {
console.log(err.body);
res.send("Didn't work");
slack.send({
text: "Login Unseccessful :("
});
} else {
console.log('Yay! Access token is ' + result.access_token);
var verityToken = result.access_token;
slack.send({
text: "Log in Successful!\n Welcome to Go Outside Challenge!"
});
// Instagram subscription
ig.subscriptions(function(err, result, remaining, limit){});
ig.add_user_subscription('https://lit-journey-12058.herokuapp.com/user',
{verify_token: verifyToken},
function(err, result, remaining, limit){});
}
});
};
// This is where pi initially send users to authorize
app.get('/authorize_user', exports.authorize_user);
// This is redirect URI
app.get('/handleauth', exports.handleauth);
// ---------------------------------
// Instagram subscrription API endpoints
app.get('/user', function(req, res) {
slack.send({
text: "I subscribed to the feed!"
});
res.send(req.query.hub.challenge)
ig.subscriptions(function(err, subscriptions, remaining, limit){
console.log(subscriptions);
res.send("Subscription Added");
});
});
app.post('/user', function(req, res) {
slack.send({
text: "There's a new picture!"
});
res.send("New activity from the subcription detected");
} );
// ----------------------------------
// test route
app.get('/', function (req, res) { res.status(200).send('Hello World!') });
// error handler
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(400).send(err.message);
});
app.listen(port, function () {
console.log('Slack bot listening on port ' + port);
})
// handle the "hello" api call (test case)
app.post('/hello', hellobot);
|
JavaScript
| 0.000022 |
@@ -2959,16 +2959,17 @@
allenge)
+;
%0A ig.
|
38d8f1498d06909915d34389549d6422dc19dadf
|
Add open link to snackbar when scanned content is an HTTP(S) URL.
|
app.js
|
app.js
|
function escapeHtml(text) {
var map = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
return text.replace(/[&<>"']/g, function (m) { return map[m]; });
}
var app = new Vue({
el: '#app',
data: {
scans: [],
links: 'ignore',
cameras: [],
activeCamera: null
},
methods: {
start: function () {
var self = this;
var scanner = new CameraQrScanner(document.querySelector('#camera'));
scanner.onResult = this.onScanResult;
scanner.getCameras(function (cameras) {
self.cameras = cameras;
self.activeCamera = cameras[0].id;
});
this.$watch('activeCamera', function (camera) {
scanner.start(camera);
});
new Clipboard('.clipboard-copy', {
text: function (trigger) {
return trigger.dataset.clipboard;
}
});
},
deleteScan: function(scan) {
this.scans = this.scans.filter(s => s.date !== scan.date);
},
addScan: function (content) {
this.scans.push({
content: content,
date: +(new Date())
});
},
onScanResult: function (content) {
$('body').snackbar({
alive: 5 * 1000,
content: 'Scanned: '
+ content
+ '<a href="#" class="clipboard-copy" data-dismiss="snackbar" data-clipboard="'
+ escapeHtml(content)
+ '"><span class="icon icon-md">content_copy</span> Copy</a>'
});
this.addScan(content);
if (this.links !== 'ignore' && content.match(/^https?:\/\//i)) {
if (this.links === 'new-tab') {
var win = window.open(content, '_blank');
win.focus();
} else if (this.links === 'current-tab') {
window.location = content;
}
}
}
}
});
app.start();
|
JavaScript
| 0 |
@@ -1170,70 +1170,84 @@
-$('body').snackbar(%7B%0A alive: 5 * 1000,%0A c
+var isHttpUrl = content.match(/%5Ehttps?:%5C/%5C//i);%0A%0A var snackbarC
ontent
-:
+ =
'Sc
@@ -1263,23 +1263,16 @@
-
-
+ conten
@@ -1273,23 +1273,16 @@
content%0A
-
@@ -1369,23 +1369,16 @@
-
+ escape
@@ -1392,24 +1392,242 @@
ntent)%0A
+ + '%22%3E%3Cspan class=%22icon icon-md%22%3Econtent_copy%3C/span%3E Copy%3C/a%3E';%0A%0A if (isHttpUrl) %7B%0A snackbarContent += '%3Ca href=%22'%0A + escapeHtml(content)%0A + '%22 target=%22_blank%22 data-dismiss=%22snackbar%22%3E'%0A
+
@@ -1619,34 +1619,32 @@
%3E'%0A + '
-%22%3E
%3Cspan class=%22ico
@@ -1654,36 +1654,35 @@
con-md%22%3E
-content_copy
+open_in_new
%3C/span%3E
Copy%3C/a%3E
@@ -1673,25 +1673,120 @@
%3C/span%3E
-Copy
+Open
%3C/a%3E'
+;%0A %7D%0A%0A $('body').snackbar(%7B%0A alive: 5 * 1000,%0A content: snackbarContent
%0A %7D
@@ -1860,38 +1860,17 @@
&&
-content.match(/%5Ehttps?:%5C/%5C//i)
+isHttpUrl
) %7B%0A
|
f4fa5e092425e6005170145afea85f512a68b0e0
|
Add debug logs for bill payment
|
app.js
|
app.js
|
'use strict';
process.env.DEBUG = 'actions-on-google:*';
let Assistant = require('actions-on-google').ApiAiAssistant;
let express = require('express');
let fuse = require('fuse.js');
let bodyParser = require('body-parser');
let app = express();
app.use(bodyParser.json({type: 'application/json'}));
const INTENT_WELCOME = "input.welcome";
const INTENT_CHECK_BALANCE = "check_balance";
const INTENT_CHECK_BILLS = "check_bills";
const INTENT_PAY_BILL = "pay_bill";
const ARG_BILL_NAME = "billName";
app.post('/', function (req, res) {
const assistant = new Assistant({request: req, response: res});
console.log('Request headers: ' + JSON.stringify(req.headers));
console.log('Request body: ' + JSON.stringify(req.body));
function init (assistant) {
assistant.data.cashMoney = 2000;
assistant.data.bills = [
{ recepient: "Anime Mystery Box", cost: 50.00 },
{ recepient: "University of Waterloo Tuition Bill", cost: 8000.00 },
{ recepient: "Waterloo North Hydro", cost: 120.00 }
];
assistant.ask('Sup fam, Budgetbot at your service.');
}
function checkBalance (assistant) {
assistant.ask("Your account balance is " + assistant.data.cashMoney + " dollars.");
}
function checkBills (assistant) {
let billsArray = assistant.data.bills;
var statement = "Good job, no bills are due for this month!";
if (billsArray.length > 0) {
statement = "The following bills are due by the end of the month: ";
for (var i=0; i < billsArray.length; i++) {
let bill = billsArray[i];
statement = statement + bill["recepient"] + " at " + bill["cost"] + " dollars";
if (i == billsArray.length - 1) {
statement = statement + ".";
} else if (i == billsArray.length - 2) {
statement = statement + ", and ";
} else {
statement = statement + ", ";
}
}
}
assistant.ask(statement);
}
function payBill (assistant) {
let fuzzyBillsArray = new Fuse(assistant.data.bills, { keys: ["recepient"] });
let currentCashMoney = assistant.data.cashMoney;
let targetBillName = assistant.getArgument(ARG_BILL_NAME);
let fuzzyResults = fuzzyBillsArray.search(targetBillName);
if (fuzzyResults.length > 0) {
let billRecepient = fuzzyResults[0]["recepient"];
let billCost = fuzzyResults[0]["cost"];
if (foundBill["cost"] <= currentCashMoney) {
deleteBill(foundBill);
assistant.data.cashMoney = assistant.data.cashMoney - billCost;
assistant.ask("Okay, paying " + billCost + " dollars to " + billRecepient + ". You have " + assistant.data.cashMoney + " dollars remaining.");
} else {
assistant.ask("Whoops, you don't have enough money to pay that bill. The bill is " + billCost + " dollars, and you have " + currentCashMoney + " on hand.");
}
} else {
assistant.ask("Sorry, I can't seem to find that bill.");
}
}
function deleteBill(targetBill) {
for (var i=0; i < assistant.data.bills.length; i++) {
if (assistant.data.bills[i]["recepient"] === targetBill["recepient"] && assistant.data.bills[i]["cost"] === targetBill["cost"]) {
assistant.data.bills.splice(i, 1);
return;
}
}
}
let actionMap = new Map();
actionMap.set(INTENT_WELCOME, init);
actionMap.set(INTENT_CHECK_BALANCE, checkBalance);
actionMap.set(INTENT_CHECK_BILLS, checkBills);
actionMap.set(INTENT_PAY_BILL, payBill);
assistant.handleRequest(actionMap);
});
if (module === require.main) {
let server = app.listen(process.env.PORT || 8080, function () {
let port = server.address().port;
console.log('App listening on port %s', port);
});
}
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -1949,32 +1949,89 @@
l (assistant) %7B%0A
+ console.log(%22INFO: payBill - this is being called%22);%0A
let fuzzyBil
@@ -2281,43 +2281,159 @@
e);%0A
-%0A if (fuzzyResults.length %3E 0) %7B
+ console.log(%22INFO: payBill - fuzzySearch successful%22);%0A%0A if (fuzzyResults.length %3E 0) %7B%0A console.log(%22INFO: payBill - We found something%22);
%0A
@@ -2578,24 +2578,85 @@
ashMoney) %7B%0A
+ console.log(%22INFO: payBill - about to delete bill%22);%0A
dele
@@ -2899,32 +2899,143 @@
g.%22);%0A
-%7D else %7B
+ console.log(%22INFO: payBill - done%22);%0A %7D else %7B%0A console.log(%22INFO: payBill - costs too much damn money%22);
%0A ass
@@ -3205,24 +3205,85 @@
%7D else %7B%0A
+ console.log(%22INFO: payBill - couldn't find anything%22);%0A
assist
@@ -3376,24 +3376,74 @@
rgetBill) %7B%0A
+ console.log(%22INFO: payBill - deleting bill%22);%0A
for (var
|
04a8ef9f649e215eb01446ae7d448d87c1efa8d2
|
remove debug statements, parse json response
|
app.js
|
app.js
|
var express = require('express'),
app = express.createServer(),
io = require('socket.io').listen(app),
port = process.env.PORT || 5000;
io.configure(function () {
io.set("transports", ["xhr-polling"]);
io.set("polling duration", 10);
});
app.configure(function(){
app.use(express.bodyParser());
});
app.listen(port);
app.get('/', function (req, res) {
res.sendfile(__dirname + '/index.html');
});
app.post('/commit', function (req, res) {
console.log('---commit---');
console.log(req.body);
io.sockets.emit('commit', req.body.payload);
res.send('thanks github!');
});
|
JavaScript
| 0.000006 |
@@ -460,64 +460,8 @@
) %7B%0A
- console.log('---commit---');%0A console.log(req.body);%0A
io
@@ -484,16 +484,27 @@
ommit',
+JSON.parse(
req.body
@@ -512,16 +512,17 @@
payload)
+)
;%0A res.
|
4f98c93557ebeb27858988ec103a2a2f30dc5f2b
|
add aws stuff
|
app.js
|
app.js
|
var express = require('express')
var app = express()
app.configure(function() {
app.use(app.router)
app.use('/', express.static(__dirname + '/public'))
})
app.listen(8025)
|
JavaScript
| 0 |
@@ -26,16 +26,1246 @@
press')%0A
+var AWS = require('aws-sdk')%0A%0AAWS.config.loadFromPath('./aws-config.json')%0A%0Avar s3 = new AWS.S3();%0A%0Aparams = %7B%0A Bucket:'becsws'%0A%7D%0A%0Avar s3_dir_value = false%0A%0A// album - (Object)%0A// genre - (String)%0A// artist - (String)%0A// album - (String)%0A// files - (Array%3CString%3E) S3 key%0A%0A// albums - (Object%3CString:album%3E) key is genre/artist/album, album is album object%0Avar albums = %7B%7D%0A%0A// artist_index - (Object%3CString:Array%3CString%3E%3E) key is artist, value is array of genre/artist/album%0Avar artist_index = %7B%7D%0A%0Afunction process_s3_data(data) %7B%0A if (data.IsTruncated === true) %7B%0A console.log(%22WARNING: S3 data is tructated%22);%0A %7D%0A%0A data.Contents.forEach(function(item) %7B%0A if (r = /(.*)%5C/(.*)%5C/(.*)%5C/(.*%5C.mp3$)/.exec(item.Key)) %7B%0A var file = r%5B4%5D;%0A var s = %7B%0A genre:r%5B1%5D,%0A artist:r%5B2%5D,%0A album:r%5B3%5D,%0A files:%5B%5D%0A %7D%0A var key = s.genre + '/' + s.artist + '/' + s.album;%0A if (albums.hasOwnProperty(key)) %7B%0A albums%5Bkey%5D.files.push(file);%0A %7D else %7B%0A albums%5Bkey%5D = s;%0A %7D%0A %7D%0A %7D)%0A%7D%0A%0As3.listObjects(params, function(err, data) %7B%0A if (err) %7B%0A console.log(err);%0A %7D else %7B%0A //console.log(data);%0A process_s3_data(data);%0A console.log(albums);%0A %7D%0A%7D);
%0A%0Avar ap
@@ -1394,18 +1394,133 @@
app.
-listen(8025
+get('/albums', function(req, res) %7B%0A res.send(albums);%0A%7D)%0A%0Aport = 8025%0Aapp.listen(port)%0Aconsole.log(%22started on port %22 + port
)%0A%0A
|
91c82f112fec476176d6cdf08456320657174de5
|
check for tilda at end of filename
|
app.js
|
app.js
|
var RaspiCam = require("raspicam"),
colors = require("colors"),
Spacebrew = require('./sb-1.3.0').Spacebrew,
sb,
camera,
config = require("./machine"),
fs = require("fs");
var image_path = __dirname + "/files/";
// setup spacebrew
sb = new Spacebrew.Client( config.server, config.name, config.description ); // create spacebrew client object
// create the spacebrew subscription channels
//sb.addPublish("config", "string", ""); // publish config for handshake
//sb.addSubscribe("config", "boolean"); // subscription for config handshake
sb.addSubscribe("start", "boolean"); // subscription for starting timelapse
sb.addSubscribe("stop", "boolean"); // subscription for starting timelapse
sb.addSubscribe("test", "boolean"); // subscription for starting timelapse
//sb.addPublish("src", "string", ""); // publish image url for handshake
sb.addPublish("image", "binary.png"); // publish the serialized binary image data
sb.onBooleanMessage = onBooleanMessage;
sb.onOpen = onOpen;
// connect to spacbrew
sb.connect();
/**
* Function that is called when Spacebrew connection is established
*/
function onOpen() {
console.log( "Connected through Spacebrew as: " + sb.name() + "." );
// initialize RaspiCam timelapse
camera = new RaspiCam({
mode: "timelapse",
output: image_path + "image_%06d.png", // image_000001.jpg, image_000002.jpg,...
encoding: "png",
width: 640,
height: 480,
timelapse: 5000, // take a picture every x seconds
timeout: 86400000 // stop after 24 hours
});
camera.on("start", function( err, timestamp ){
console.log("timelapse started at " + timestamp);
});
camera.on("read", function( err, timestamp, filename ){
console.log("timelapse image captured with filename: " + filename);
setTimeout(function(){
fs.readFile(image_path + filename, function(err, data) {
var base64data = data.toString('base64');
console.log('sending base 64 with length' + base64data.length);
sb.send("image", "binary.png", base64data);
});
}, 2000);
});
camera.on("exit", function( timestamp ){
console.log("timelapse child process has exited");
});
camera.on("stop", function( err, timestamp ){
console.log("timelapse child process has been stopped at " + timestamp);
});
}
/**
* onStringMessage Function that is called whenever new spacebrew string messages are received.
* It accepts two parameters:
* @param {String} name Holds name of the subscription feed channel
* @param {String} value Holds value received from the subscription feed
*/
function onBooleanMessage( name, value ){
console.log("[onBooleanMessage] value: " + value + " name: " + name);
switch(name){
case "config":
console.log([
// Timestamp
String(+new Date()).grey,
// Message
String("sending config").cyan
].join(" "));
sb.send("config", "string", JSON.stringify( config ) );
break;
case "start":
if(value == true){
console.log([
// Timestamp
String(+new Date()).grey,
// Message
String("starting camera").magenta
].join(" "));
// start timelapse
camera.start();
}
break;
case "stop":
if(value == true){
console.log([
// Timestamp
String(+new Date()).grey,
// Message
String("stopping camera").magenta
].join(" "));
// stop timelapse
camera.stop();
}
break;
case "test":
if(value == true){
console.log("calling test");
fs.readFile(image_path + "image_000007.png", function(err, data) {
var base64data = data.toString('base64');
console.log('sending base 64 with length' + base64data.length);
sb.send("image", "binary.png", base64data);
});
}
}
}
|
JavaScript
| 0 |
@@ -1751,20 +1751,70 @@
lename);
+%0A%09%09if(filename.charAt(filename.length-1) != %22~%22)%7B
%0A%0A%09%09
+%09
setTimeo
@@ -1828,16 +1828,17 @@
tion()%7B%0A
+%09
%09%09%09fs.re
@@ -1889,24 +1889,25 @@
data) %7B%0A%09%09%09%09
+%09
var base64da
@@ -1932,24 +1932,25 @@
('base64');%0A
+%09
%09%09%09%09console.
@@ -2006,24 +2006,25 @@
ngth);%0A%0A%09%09%09%09
+%09
sb.send(%22ima
@@ -2058,20 +2058,22 @@
ta);%0A%09%09%09
+%09
%7D);%0A
+%09
%09%09%7D, 200
@@ -2076,16 +2076,20 @@
2000);%0A
+%09%09%7D%0A
%09%09%09%0A%09%7D);
|
85e1e8f77bc51c63efdaf8b833cec4279ada039a
|
fix ip thingy
|
app.js
|
app.js
|
// Require the http module and the proxy module
var http = require('http'),
httpProxy = require('http-proxy'),
routes = require('./config/routes');
console.log(routes);
// Create the proxy
var proxy = httpProxy.createProxyServer({});
// Set the ip header
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('X-Proxy-Header', req.ip);
});
// Setup the proxy server and determine routing
var server = http.createServer(function(req, res) {
var rqstUrl = req.headers.host;
// console.log(rqstUrl);
if(routes[rqstUrl]) {
target_address = routes.ipaddress + routes[rqstUrl].target;
proxy.web(req, res, { target: target_address });
}
else {
res.writeHead(404, {"Content-Type": "text/plain"});
res.write("404: Not Found\n");
res.end();
}
});
// Check to see if an error has occurred
proxy.on('error', function(err, req, res) {
res.writeHead(500, { 'Content-Type': 'text/plain' });
res.write('A server error occurred! Nothing is running at this address and port!');
res.end();
});
// Determine the port number
var port = 3000;
// Start the Server
server.listen(process.env.PORT || port, process.env.IP || '0.0.0.0', function() {
var address = server.address();
console.log('Proxy server is running on ', address.address + ':' + address.port);
});
|
JavaScript
| 0 |
@@ -370,18 +370,40 @@
r', req.
-ip
+connection.remoteAddress
);%0A%7D);%0A%0A
@@ -1121,11 +1121,9 @@
t =
-300
+8
0;%0A%0A
|
a39b097a8f8be83366ed607120eeac75a8fee373
|
test issue with redis connection
|
app.js
|
app.js
|
/**
* Module dependencies.
*/
var express = require('express')
//, mongoose = require('mongoose')
, routes = require('./routes')
//, middleware = require('./middleware')
//, request = require('request')
//, timemap = require('./timemap')
;
var redis;
var init = exports.init = function (config) {
//var db_uri = process.env.MONGOLAB_URI || process.env.MONGODB_URI || config.default_db_uri;
//mongoose.connect(db_uri);
redis = require("redis").createClient();
if (process.env.REDISTOGO_URL) {
var rtg = require("url").parse(process.env.REDISTOGO_URL);
redis = require("redis").createClient(rtg.port, rtg.hostname);
redis.auth(rtg.auth.split(":")[1]);
}
var app = express.createServer();
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', { pretty: true });
app.use(express.bodyParser());
app.use(express.cookieParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: false}));
});
// Routes
app.get('/', function(req, res){
res.render('homepage', { json: "" });
});
app.post('/map', function(req, res){
//var tm = new timemap.TimeMap({
// json: req.body.json
//});
//tm.save(function(err){
// res.send({ outcome: ( err || tm._id ) });
//});
var specialkey = Math.round( Math.random() * 1000000000 ) + "";
redis.set(specialkey, req.body.json);
res.send({ outcome: specialkey });
});
app.get('/map/:byid', function(req, res){
//timemap.TimeMap.findById(req.params.byid, function(err, map){
// res.render('homepage', { json: map.json });
//});
redis.get(req.params.byid, function(err, reply){
if(err){
return res.send(err);
}
res.render('homepage', { json: reply });
});
});
var replaceAll = function(src, oldr, newr){
while(src.indexOf(oldr) > -1){
src = src.replace(oldr, newr);
}
return src;
};
//app.get('/auth', middleware.require_auth_browser, routes.index);
//app.post('/auth/add_comment',middleware.require_auth_browser, routes.add_comment);
// redirect all non-existent URLs to doesnotexist
app.get('*', function onNonexistentURL(req,res) {
res.render('doesnotexist',404);
});
return app;
};
// Don't run if require()'d
if (!module.parent) {
var config = require('./config');
var app = init(config);
app.listen(process.env.PORT || 3000);
console.info("Express server listening on port %d in %s mode", app.address().port, app.settings.env);
}
|
JavaScript
| 0 |
@@ -453,51 +453,8 @@
%0A %0A
- redis = require(%22redis%22).createClient();%0A
if
@@ -480,24 +480,47 @@
TOGO_URL) %7B%0A
+ console.log(%22p1%22);%0A
var rtg
@@ -570,16 +570,39 @@
O_URL);%0A
+ console.log(%22p2%22);%0A
redi
@@ -660,16 +660,39 @@
tname);%0A
+ console.log(%22p3%22);%0A
redi
|
4bfe65df6a721dfb34d9107f525f692fa01bdf00
|
Use querySelector instead of getElementById.
|
app.js
|
app.js
|
window.AudioContext = window.AudioContext || window.webkitAudioContext;
navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
navigator.cancelAnimationFrame = navigator.cancelAnimationFrame || navigator.webkitCancelAnimationFrame || navigator.mozCancelAnimationFrame;
navigator.requestAnimationFrame = navigator.requestAnimationFrame || navigator.webkitRequestAnimationFrame || navigator.mozRequestAnimationFrame;
var audioCtx = new AudioContext();
var analyser = audioCtx.createAnalyser();
var distortion = audioCtx.createWaveShaper();
var gainNode = audioCtx.createGain();
var biquadFiler = audioCtx.createBiquadFilter();
var convolver = audioCtx.createConvolver();
if (!navigator.getUserMedia) {
throw new Error("getUserMedia not supported");
}
navigator.getUserMedia(
{
audio: true,
video: true
},
function (stream) {
document.getElementById('camFeed').src = window.URL.createObjectURL(stream);
},
function (err) {
console.log("The following error occured: " + err.name);
}
);
|
JavaScript
| 0 |
@@ -928,24 +928,24 @@
ent.
-getElementById
+querySelector
('
+#
camF
|
08ab0c2af1d2d3e7b6563f46f256ee35c747cf76
|
Use temporary reporting site for bad headers
|
app.js
|
app.js
|
/**
* @file The application.
*/
var express = require('express');
var path = require('path');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
let helmet = require('helmet');
let v1 = require('./lib/v1');
v1.use_datastore(path.join(__dirname, 'data', 'datastore.json'));
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hjs');
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use('/public', express.static(path.join(__dirname, 'public')));
app.use(helmet());
app.use(helmet.contentSecurityPolicy({ directives: { defaultSrc: ["'self'"] } }));
app.use(helmet.noCache());
app.use(helmet.referrerPolicy());
app.enable('trust proxy');
app.use((req, res, next) => {
/** Azure removes the X-Forwarded-Proto header. */
if (!req.headers['x-forwarded-proto'] && req.headers['x-arr-ssl']) req.headers['x-forwarded-proto'] = req.headers['x-arr-ssl'];
return next();
});
app.use('/v1', v1);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handler
app.use(function(err, req, res, next) {
// 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');
});
module.exports = app;
|
JavaScript
| 0 |
@@ -716,16 +716,18 @@
Policy(%7B
+%0A
directi
@@ -732,16 +732,20 @@
tives: %7B
+%0A
default
@@ -756,80 +756,751 @@
%5B%22'
-self'%22%5D %7D %7D));%0Aapp.use(helmet.noCache());%0Aapp.use(helmet.referrerPolicy(
+none'%22%5D,%0A styleSrc: %5B%22'self'%22%5D,%0A imgSrc: %5B%22'self'%22%5D,%0A scriptSrc: %5B%22'unsafe-inline'%22, 'www.google-analytics.com'%5D,%0A reportUri: 'https://be37585b9eac08181012c0a06e6f132a.report-uri.io/r/default/csp/enforce'%0A %7D%0A%7D));%0Aapp.use(helmet.noCache());%0Aapp.use(helmet.referrerPolicy());%0Aapp.use(helmet.hpkp(%7B%0A maxAge: 2,%0A sha256s: %5B%0A 'CzdPous1hY3sIkO55pUH7vklXyIHVZAl/UnprSQvpEI=',%0A 'xjXxgkOYlag7jCtR5DreZm9b61iaIhd+J3+b2LiybIw=',%0A 'wBdPad95AU7OgLRs0FU/E6ILO1MSCM84kJ9y0H+TT7s=',%0A 'wUY9EOTJmS7Aj4fDVCu/KeE++mV7FgIcbn4WhMz1I2k=',%0A 'RCbqB+W8nwjznTeP4O6VjqcwdxIgI79eBpnBKRr32gc='%0A %5D,%0A includeSubdomains: true,%0A reportUri: 'https://be37585b9eac08181012c0a06e6f132a.report-uri.io/r/default/hpkp/reportOnly',%0A reportOnly: true%0A%7D
));%0A
|
8592723de4d981df04c198b6f748e73f16a7c00f
|
Fix port.
|
app.js
|
app.js
|
// Copyright 2015 Gautam Mittal under the MIT License
var dotenv = require('dotenv');
dotenv.load();
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
var cheerio = require('cheerio');
var fs = require('fs');
var greetings = require('greetings');
var request = require('request');
var sendgrid = require('sendgrid')(process.env.SENDGRID_API_KEY);
var writeGood = require('write-good');
var port = 3000;
app.use(bodyParser());
app.use(express.static(__dirname + '/email_templates'));
app.post('/check', function (req, res) {
var googleDoc = req.body.url;
var email = req.body.email;
if (googleDoc) {
if (email) {
// res.setHeader('Content-Type', 'application/json');
console.log(googleDoc);
console.log(email);
// console.log(googleDoc);
// take in a google doc, spit out the contents
request(googleDoc, function (error, response, body) {
if (!error && response.statusCode == 200) {
var lines = body.split("\n");
var c = cheerio.load(body);
if (c("meta:nth-child(3)")["0"]["attribs"]["content"] == "Google Docs") {
var docTitle = c("meta:nth-child(1)")["0"]["attribs"]["content"];
var largeData = "";
var parsedItems = [];
for (var i = 0; i < lines.length; i++) {
if (lines[i].indexOf("DOCS_modelChunk = [{") > -1) {
// console.log(i);
$ = cheerio.load(lines[i]);
var scripts = $("script").text().split("</script>");
for (var j = 0; j < scripts.length; j++) {
if (scripts[j].indexOf('[{"ty"') > -1) {
// console.log(j);
// console.log(scripts[j]);
var objs = scripts[j].split("DOCS_modelChunkParseStart = new Date().getTime();");
for (var k = 0; k < objs.length; k++) {
if (objs[k].indexOf("DOCS_modelChunk = [{") > -1) {
// console.log(objs[k]);
var stringsss = objs[k].split("},");
largeData = ""; // the file contents of the Google Doc
// var c = 0;
for (var o = 0; o < stringsss.length; o++) {
// console.log(o);
if (stringsss[o].indexOf("DOCS_modelChunk = [{") > -1) {
// c++;
// console.log(o);
// console.log(stringsss[o]);
var jsobj = stringsss[o].replace("DOCS_modelChunk = ", "");
jsobj += "}]";
var parsed = JSON.parse(jsobj)[0].s;
// console.log(parsed);
parsedItems.push(parsed);
// largeData += parsed;
// console.log(o);
// console.log(largeData);
}
}
// console.log(parsedItems.length);
}
}
}
}
// console.log(largeData);
console.log(parsedItems.length);
largeData = parsedItems.join("");
console.log(parsedItems);
var suggestions = writeGood(largeData); // lint the writing piece
console.log(suggestions);
var htmlString = largeData;
var excess = 0;
var suggestionsListString = "";
for (var l = 0; l < suggestions.length; l++) {
htmlString = htmlString.insert(suggestions[l].index + excess, '<b>');
excess += '<b>'.length;
htmlString = htmlString.insert(suggestions[l].index + suggestions[l].offset + excess, "</b>");
excess += "</b>".length;
suggestionsListString += "<li>" + suggestions[l].reason + "</li>";
}
htmlString = htmlString.replace(/\n/g, "<br />");
// htmlString = urlify(htmlString); // to turn all of the hyperlinks into urls, except it doesn't have perfect regex matching
// console.log(htmlString);
fs.readFile("email_templates/template4.html", 'utf-8', function (err, fileData) {
if (err) {
res.send("An error occurred.");
} else {
var finalData = fileData;
finalData = fileData.replace("{USER-WORK-s6ZG5rnRHt4Ydg9O2fv7}", htmlString);
finalData = finalData.replace("{SUGGESTION-LIST-CWwbXpU8BUyEdAYULIrC}", suggestionsListString);
finalData = finalData.replace("{HEADER-MESSAGE-L4VTRRHMppErK8V07Bkq}", greetings.random);
sendgrid.send({
to: email,
from: '[email protected]',
subject: 'Report for ' + docTitle,
html: finalData
}, function(err, json) {
if (err) { return console.error(err); }
console.log(json);
res.send("Your results should be sent to your email now.");
});
}
});
}
} // end for loop
} else {
res.send("An error occurred. The document you sent was not a valid Google Doc.");
} // end if Google Doc
} else {
// console.log(response.statusCode);
res.send("An error occurred.");
}
});
} else {
res.send("Invalid parameters");
}
} else {
res.send("Invalid parameters");
}
});
String.prototype.splice = function( idx, rem, s ) {
return (this.slice(0,idx) + s + this.slice(idx + Math.abs(rem)));
};
String.prototype.insert = function (index, string) {
if (index > 0)
return this.substring(0, index) + string + this.substring(index, this.length);
else
return string + this;
};
function urlify(text) {
var urlRegex = /(https?:\/\/[^\s]+)/g;
return text.replace(urlRegex, function(url) {
return '<a href="' + url + '">' + url + '</a>';
})
// or alternatively
// return text.replace(urlRegex, '<a href="$1">$1</a>')
}
var server = app.listen(port, function () {
var host = server.address().address;
var port = server.address().port;
console.log('Example app listening at http://%s:%s', host, port);
});
|
JavaScript
| 0 |
@@ -439,16 +439,36 @@
r port =
+ process.env.PORT %7C%7C
3000;%0A%0A
@@ -6305,12 +6305,13 @@
, port);%0A%7D);
+%0A
|
51cba35e9651b5db25ea88b64cf1ebee3c82472e
|
make clusters grouped by area category
|
app.js
|
app.js
|
var mapConf = {
boundary: [[21.5, 119], [25.5, 123]],
clusterConf: {
disableClusteringAtZoom: 14
}
};
(function(rexQuoteStrip) {
csv2json = function(csv, headers) {
var rtn = [];
var rows = csv.split('\n');
var row;
var obj;
var matched;
for (var i = 0, c = rows.length; i < c; i++) {
row = rows[i].split(',');
obj = {};
for (var j = 0, d = headers.length; j < d; j++) {
if (row[j] == null)
continue;
if (matched = row[j].match(rexQuoteStrip)) {
row[j] = matched[1];
} else if (!isNaN(matched = parseFloat(row[j]))) {
// convert to number if possible
row[j] = matched;
}
obj[headers[j]] = row[j];
}
rtn.push(obj);
}
return rtn;
}
})(/^\s*"(.*)"\s*$/);
// test case:
// csv2json('111,222,333,"444"\n555,666,777,"888"\n,1,2,3', ['A','B','C','D'])
var hotspotColl = null;
var hotspotList = [];
var hotspotMarkers = new L.MarkerClusterGroup(mapConf.clusterConf);
$.ajax({
url: 'hotspotlist.csv',
success: function(resp) {
//console.log(resp);
hotspotColl = csv2json(resp, ["owner","area","name","addr","lng","lat"]);
var hs, mkr;
// add the icon
for (var i = 0, c = hotspotColl.length; i < c; i++) {
hs = hotspotColl[i];
mkr = new L.marker([hs.lng, hs.lat], { title: hs.name });
mkr.bindPopup('<h4 class="title">' + hs.name + '</h4><p class="address">' + hs.addr + '</p>');
hotspotList.push(mkr);
// L.marker([hs.lng, hs.lat]).addTo(map);
}
hotspotMarkers.addLayers(hotspotList);
map.addLayer(hotspotMarkers);
}
});
// load OSM
var map = L.map('mapContainer', {
minZoom: 9,
maxBounds: mapConf.boundary
}).setView([25.059, 121.557], 11);
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
// buffer: 4,
bounds: mapConf.boundary,
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
|
JavaScript
| 0.000051 |
@@ -69,17 +69,18 @@
nf: %7B%0A
-%09
+
disableC
@@ -98,16 +98,51 @@
Zoom: 14
+,%0A spiderfyDistanceMultiplier: 3
%0A %7D%0A%7D;%0A
@@ -843,102 +843,8 @@
);%0A%0A
-// test case:%0A// csv2json('111,222,333,%22444%22%5Cn555,666,777,%22888%22%5Cn,1,2,3', %5B'A','B','C','D'%5D)%0A%0A
var
@@ -867,30 +867,8 @@
ll;%0A
-var hotspotList = %5B%5D;%0A
var
@@ -999,9 +999,10 @@
) %7B%0A
-%09
+
//co
@@ -1113,16 +1113,41 @@
s, mkr;%0A
+ var hotspotCat = %7B%7D;%0A
// a
@@ -1243,16 +1243,290 @@
oll%5Bi%5D;%0A
+ if (!hotspotCat%5Bhs.area%5D) %7B%0A hotspotCat%5Bhs.area%5D = %5B%5D;%0A %7D%0A hotspotCat%5Bhs.area%5D.push(hs);%0A %7D%0A%0A for (var x in hotspotCat) %7B%0A var hotspotList = %5B%5D;%0A for (var i = 0, c = hotspotCat%5Bx%5D.length; i %3C c; i++) %7B%0A hs = hotspotCat%5Bx%5D%5Bi%5D;%0A
mk
@@ -1581,16 +1581,18 @@
ame %7D);%0A
+
mk
@@ -1686,24 +1686,26 @@
p%3E');%0A
+
hotspotList.
@@ -1725,56 +1725,12 @@
-// L.marker(%5Bhs.lng, hs.lat%5D).addTo(map);%0A
%7D%0A
+
@@ -1768,16 +1768,22 @@
tList);%0A
+ %7D%0A
map.
|
6d3d366395891fcb32c35324a44e27b8caaab037
|
Add knobCtrl
|
demo/demo.js
|
demo/demo.js
|
JavaScript
| 0.000001 |
@@ -0,0 +1,155 @@
+'use strict';%0A%0Aangular.module('KnobDemoApp')%0A .controller('knobCtrl', function ($scope) %7B%0A $scope.value = 65;%0A $scope.options = %7B%0A %0A %7D;%0A %7D);%0A
|
|
394e6122abb9414d5149819224fddc55364416a1
|
Update intro comment.
|
bot.js
|
bot.js
|
/**
* nodeEbot v.2.0.0!
* A twitter_ebooks style bot for Node.js
* by Dave Schumaker (@davely)
*
* Heavily inspired by the twitter_ebooks project for Ruby by Mispy
* https://github.com/mispy/twitter_ebooks
*/
// Import required modules to make our robot work!
var fs = require('fs');
var util = require('util');
var Twitter = require('twitter');
var Promise = require('bluebird');
// Import configuration settings and API keys
var config = require('./config/config.js');
// Import generator for creating new sentences!
var generator = require('./generator');
// Create promises
//fs = Promise.promisifyAll(fs);
//generator = Promise.promisifyAll(generator);
/////////////////////
// Filename to source or tweets and other content from?
tweetFile = 'tweets.txt';
// RAW CONTENT!
// Load files that contain all relevant tweets, stopwords, etc
var content = fs.readFileSync(tweetFile).toString().split("\n");
var processed = generator.buildCorpus(content);
// fs.writeFile('processed_data.txt', util.inspect(processed, false, null), function (err,data) {
// if (err) {
// return console.log(err);
// }
// console.log(data);
// });
setInterval(function() {
console.log(generator.makeTweet(140) + '');
}, 750);
// var content;
// fs.readFileAsync(tweetFile)
// .then(function(fileContents) {
// //console.log("Get file contents");
// content = fileContents.toString().split("\n");
// //console.log(content);
// return content;
// })
// .then(function(content){
// //console.log("Build Corpus");
// return generator.buildCorpus(content);
// })
// .then (function(data){
// //console.log("Make Tweet!!");
// // setInterval(function() {
// // console.log(generator.makeTweet(140) + '\n');
// // }, 2500);
// return generator.makeTweet(140);
// })
// .then(function(tweet){
// console.log('NEW TWEET:', tweet);
// });
// Generate corpus
/*
generator.buildCorpusAsync(content)
.then(function(data) {
console.log('hey');
});
*/
//console.log(generator.makeTweet(140));
//console.log(corpus);
|
JavaScript
| 0 |
@@ -89,16 +89,60 @@
davely)%0A
+* https://github.com/daveschumaker/nodeEbot%0A
*%0A* Heav
@@ -161,16 +161,26 @@
by the
+following
twitter_
@@ -211,16 +211,17 @@
by Mispy
+:
%0A* https
|
c63bb668bcdf89528dfb93ea73b9d991a72a2379
|
Teste com openshift
|
bot.js
|
bot.js
|
var token = process.env.TOKEN;
var Bot = require('node-telegram-bot-api');
var bot;
if(process.env.NODE_ENV === 'production') {
bot = new Bot(token);
bot.setWebHook(process.env.HEROKU_URL + bot.token);
}
else {
bot = new Bot(token, { polling: true });
}
console.log('Bot server started in the ' + process.env.NODE_ENV + ' mode');
// // Matches "/echo [whatever]"
// bot.onText(/\/echo (.+)/, (msg, match) => {
// // 'msg' is the received Message from Telegram
// // 'match' is the result of executing the regexp above on the text content
// // of the message
//
// const chatId = msg.chat.id;
// const resp = match[1];
//
// bot.sendMessage(chatId, resp);
// });
bot.onText(/\/errocritico (.+)/, function onD20Text(msg, match) {
const chatId = msg.chat.id;
const damage = [
"acabou de torce o joelho!",
"quebrou o braço! Hahaha",
"caiu no chão, e quebrou o nariz!",
"torceu o pulso!",
"foi atingido em um órgão vital! Chama logo um curandeiro porra!"
];
let chosen = damage[Math.floor((Math.random() * damage.length) + 1)-1];
let resp = match[1]+" "+chosen
bot.sendMessage(chatId, resp);
});
bot.onText(/\/d20/, function onD20Text(msg) {
const chatId = msg.chat.id;
const resp = Math.floor((Math.random() * 20) + 1);
bot.sendMessage(chatId, resp);
});
bot.onText(/\/d10/, function onD20Text(msg) {
const chatId = msg.chat.id;
const resp = Math.floor((Math.random() * 10) + 1);
bot.sendMessage(chatId, resp);
});
bot.onText(/\/d8/, function onD20Text(msg) {
const chatId = msg.chat.id;
const resp = Math.floor((Math.random() * 8) + 1);
bot.sendMessage(chatId, resp);
});
bot.onText(/\/d6/, function onD20Text(msg) {
const chatId = msg.chat.id;
const resp = Math.floor((Math.random() * 6) + 1);
bot.sendMessage(chatId, resp);
});
bot.onText(/\/d4/, function onD20Text(msg) {
const chatId = msg.chat.id;
const resp = Math.floor((Math.random() * 4) + 1);
bot.sendMessage(chatId, resp);
});
bot.onText(/\/odanilo/, function onDaniloText(msg) {
const chatId = msg.chat.id;
const resp = "é a mulher da minha vida";
bot.sendMessage(chatId, resp);
});
// bot.onText(/^/, function (msg) {
// var name = msg.from.first_name;
// bot.sendMessage(msg.chat.id, 'Bem vindo ao Bot do grupo RPGzão, ' + name + '!').then(function () {
// });
// });
module.exports = bot;
|
JavaScript
| 0 |
@@ -180,18 +180,25 @@
env.
-HEROKU_URL
+OPENSHIFT_APP_DNS
+ b
|
93c482cc26ed2288257baed9ad72c5b4404b7bdb
|
Refactor single hear statement with config object
|
bot.js
|
bot.js
|
var http = require('http');
var Botkit = require('botkit');
var _ = require('underscore');
var controller = Botkit.slackbot();
var answers = require('./lib/answers');
var janitor = controller.spawn({
token: process.env.token
});
janitor.startRTM(function(err,bot,payload) {
if (err) {
throw new Error('Could not connect to Slack');
}
});
function matcher(text) {
var text = text;
return function(pattern) {
var re = new RegExp(pattern);
return re.test(text);
};
}
controller.hears(['.*'], ['direct_message,direct_mention'], function(bot, message) {
var shutdown = _.any(
['shutdown', 'get lost', 'self.*destruct', 'destroy', 'shut.*up', 'go away'],
matcher(message.text)
);
if (shutdown) {
answers.shutdown(bot, message);
return;
}
var nextColl = _.any(
['next.*coll'],
matcher(message.text)
);
if (nextColl) {
answers.nextCollection(bot, message);
return;
}
var todayColl = _.any(
['today'],
matcher(message.text)
);
if (todayColl) {
answers.todayCollection(bot, message);
return;
}
var board = _.any(
['board'],
matcher(message.text)
);
if (board) {
answers.stationBoard(bot, message);
return;
}
var nextConn = _.any(
['next.*conn'],
matcher(message.text)
);
if (nextConn) {
answers.nextConnection(bot, message);
return;
}
var calendar = _.any(
['calendar'],
matcher(message.text)
);
if (calendar) {
answers.nextCalendarEntries(bot, message);
return;
}
var hello = _.any(
['hi', 'hello', 'hey'],
matcher(message.text)
);
if (hello) {
answers.hello(bot, message);
return;
}
var uptime = _.any(
['uptime', 'identify yourself', 'who are you', 'what is your name', 'what do you do', 'can you help me'],
matcher(message.text)
);
if (uptime) {
answers.uptime(bot, message);
return;
}
answers.didNotUnderstand(bot, message);
});
// To keep Heroku's free dyno awake
http.createServer(function(request, response) {
response.writeHead(200, {'Content-Type': 'text/plain'});
response.end('Ok, dyno is awake.');
}).listen(process.env.PORT || 5000);
|
JavaScript
| 0 |
@@ -502,127 +502,54 @@
%0A%7D%0A%0A
-%0Acontroller.hears(%5B'.*'%5D, %5B'direct_message,direct_mention'%5D, function(bot, message) %7B%0A var shutdown = _.any(%0A
+var requestConfig = %5B%0A %7B%0A 'pattern':
%5B's
@@ -635,64 +635,19 @@
-matcher(message.text)%0A );%0A if (shutdown) %7B%0A
+'answerFn':
ans
@@ -663,161 +663,76 @@
down
-(bot, message);
%0A
+%7D,%0A
-return;
+%7B
%0A
-%7D%0A%0A
-var nextColl = _.any(%0A %5B'next.*coll'%5D,%0A matcher(message.text)%0A );%0A if (nextColl) %7B%0A
+'pattern': %5B'next.*coll'%5D,%0A 'answerFn':
ans
@@ -754,158 +754,71 @@
tion
-(bot, message);
%0A
+%7D,%0A
-return;
+%7B
%0A
-%7D%0A%0A
-var todayColl = _.any(%0A %5B'today'%5D,%0A matcher(message.text)%0A );%0A if (todayColl) %7B%0A
+'pattern': %5B'today'%5D,%0A 'answerFn':
ans
@@ -841,150 +841,71 @@
tion
-(bot, message);
%0A
+%7D,%0A
-return;
+%7B
%0A
-%7D%0A%0A
-var board = _.any(%0A %5B'board'%5D,%0A matcher(message.text)%0A );%0A if (board) %7B%0A
+'pattern': %5B'board'%5D,%0A 'answerFn':
ans
@@ -925,440 +925,225 @@
oard
-(bot, message);
%0A
+%7D,%0A
-return;
+%7B
%0A
-%7D%0A%0A
-var nextConn = _.any(%0A %5B'next.*conn'%5D,%0A matcher(message.text)%0A );%0A if (nextConn) %7B%0A answers.nextConnection(bot, message);%0A return;
+'pattern': %5B'next.*conn'%5D,%0A 'answerFn': answers.nextConnection%0A %7D,
%0A
-%7D
+%7B
%0A
-%0A
-var calendar = _.any(%0A %5B'calendar'%5D,%0A matcher(message.text)%0A );%0A if (calendar) %7B%0A answers.nextCalendarEntries(bot, message);%0A return;
+'pattern': %5B'calendar'%5D,%0A 'answerFn': answers.nextCalendarEntries%0A %7D,
%0A
-%7D
+%7B
%0A
-%0A
-var hello = _.any(%0A
+'pattern':
%5B'h
@@ -1175,145 +1175,65 @@
-matcher(message.text)%0A );%0A if (hello) %7B%0A answers.hello(bot, message);
+'answerFn': answers.hello
%0A
+%7D,%0A
-return;
+%7B
%0A
-%7D%0A%0A
-var uptime = _.any(%0A
+'pattern':
%5B'u
@@ -1347,77 +1347,314 @@
-matcher(message.text)%0A );%0A if (uptime) %7B%0A answers.uptime
+'answerFn': answers.uptime%0A %7D,%0A%5D;%0A%0A%0Acontroller.hears(%5B'.*'%5D, %5B'direct_message,direct_mention'%5D, function(bot, message) %7B%0A var noAnswer = _.every(requestConfig, function(request) %7B%0A var matched = _.any(request.pattern, matcher(message.text));%0A if (matched) %7B%0A request.answerFn
(bot
@@ -1677,23 +1677,148 @@
+
return
-;%0A %7D%0A%0A
+ false; //break out of every()%0A %7D%0A return true; // continue with next requestConfig%0A %7D);%0A if (noAnswer) %7B%0A
@@ -1857,16 +1857,22 @@
ssage);%0A
+ %7D%0A
%7D);%0A%0A%0A//
|
a6846b5b2a8408ae59dd309ba044c2eb7a6ebc70
|
allow ciphers to be configurable
|
bws.js
|
bws.js
|
#!/usr/bin/env node
var async = require('async');
var fs = require('fs');
var ExpressApp = require('./lib/expressapp');
var WsApp = require('./lib/wsapp');
var config = require('./config');
var sticky = require('sticky-session');
var log = require('npmlog');
log.debug = log.verbose;
log.disableColor();
var port = process.env.BWS_PORT || config.port || 3232;
var cluster = require('cluster');
var http = require('http');
var numCPUs = require('os').cpus().length;
var clusterInstances = config.clusterInstances || numCPUs;
var serverModule = config.https ? require('https') : require('http');
var serverOpts = {};
if (config.https) {
serverOpts.key = fs.readFileSync(config.privateKeyFile || './ssl/privatekey.pem');
serverOpts.cert = fs.readFileSync(config.certificateFile || './ssl/certificate.pem');
// This sets the intermediate CA certs only if they have all been designated in the config.js
if (config.CAinter1 && config.CAinter2 && config.CAroot) {
serverOpts.ca = [fs.readFileSync(config.CAinter1),
fs.readFileSync(config.CAinter2),
fs.readFileSync(config.CAroot)
];
};
}
var start = function(cb) {
var expressApp = new ExpressApp();
var wsApp = new WsApp();
function doStart(cb) {
var server = config.https ? serverModule.createServer(serverOpts, expressApp.app) : serverModule.Server(expressApp.app);
server.on('connection', function(socket) {
socket.setTimeout(30 * 1000);
})
async.parallel([
function(done) {
expressApp.start(config, done);
},
function(done) {
wsApp.start(server, config, done);
},
], function(err) {
if (err) {
log.error('Could not start BWS instance', err);
}
if (cb) return cb(err);
});
return server;
};
if (config.cluster) {
var server = sticky(clusterInstances, function() {
return doStart();
});
return cb(null, server);
} else {
var server = doStart(function(err) {
return cb(err, server);
});
}
};
if (config.cluster && !config.lockOpts.lockerServer)
throw 'When running in cluster mode, locker server need to be configured';
if (config.cluster && !config.messageBrokerOpts.messageBrokerServer)
throw 'When running in cluster mode, message broker server need to be configured';
start(function(err, server) {
if (err) {
console.log('Could not start BWS:', err);
process.exit(0);
}
server.listen(port, function(err) {
if (err) console.log('ERROR: ', err);
log.info('Bitcore Wallet Service running on port ' + port);
});
});
|
JavaScript
| 0.000001 |
@@ -809,16 +809,126 @@
e.pem');
+%0A if (config.ciphers) %7B%0A serverOpts.ciphers = config.ciphers;%0A serverOpts.honorCipherOrder = true;%0A %7D;
%0A%0A // T
|
9ae8d849c3d27c9cee8faa2a4e5b9ee2a8505cea
|
Update Pool_Array.js
|
CNN/util/Pool/Pool_Array.js
|
CNN/util/Pool/Pool_Array.js
|
export { ArrayPool as Array };
import { Root } from "./Pool_Base.js";
/**
* Providing Array by specifying length.
*
*/
class ArrayPool extends Root {
constructor() {
super( Array, ArrayPool.setAsConstructor_by_length );
}
/**
* @param {Array} this
* The array object to be set length.
*
* @param {number} newLength
* The this.length to be set to newLength.
*
* @return {Array}
* Return the this object.
*/
static setAsConstructor_by_length( newLength ) {
this.length = newLength;
return this;
}
}
|
JavaScript
| 0.000001 |
@@ -555,8 +555,96 @@
%0A %7D%0A%0A%7D%0A
+%0A/**%0A * Used as default Pool.Array provider.%0A */%0AArrayPool.Singleton = new ArrayPool();%0A
|
3aeab72f1cfb62fe96916bde221597cd8f68c904
|
regression. failed to sniff command properly
|
cli.js
|
cli.js
|
#!/usr/bin/env node
;(function () { // wrapper in case we're in module_context mode
var log = require("./lib/utils/log")
log.waitForConfig()
log.info("ok", "it worked if it ends with")
var fs = require("./lib/utils/graceful-fs")
, path = require("path")
, sys = require("./lib/utils/sys")
, npm = require("./npm")
, ini = require("./lib/utils/ini")
, rm = require("./lib/utils/rm-rf")
, errorHandler = require("./lib/utils/error-handler")
, argv = process.argv.slice(2)
, parseArgs = require("./lib/utils/parse-args")
log.verbose(argv, "cli")
var conf = parseArgs(argv)
npm.argv = conf.argv.remain
if (-1 !== npm.fullList.indexOf(npm.argv[0])) {
npm.command = npm.argv.shift()
}
if (conf.version) {
console.log(npm.version)
return
} else log("npm@"+npm.version, "using")
log("node@"+process.version, "using")
// make sure that this version of node works with this version of npm.
var semver = require("./lib/utils/semver")
, nodeVer = process.version
, reqVer = npm.nodeVersionRequired
if (reqVer && !semver.satisfies(nodeVer, reqVer)) {
return errorHandler(new Error(
"npm doesn't work with node " + nodeVer
+ "\nRequired: node@" + reqVer), true)
}
process.on("uncaughtException", errorHandler)
if (conf.usage && npm.command && npm.command !== "help") {
npm.argv.unshift(npm.command)
npm.command = "help"
}
// now actually fire up npm and run the command.
// this is how to use npm programmatically:
conf._exit = true
npm.load(conf, function (er) {
if (er) return errorHandler(er)
npm.commands[npm.command](npm.argv, errorHandler)
})
})()
|
JavaScript
| 0.998585 |
@@ -619,34 +619,16 @@
if (
--1 !== npm.fullList.indexO
+npm.dere
f(np
@@ -1237,23 +1237,8 @@
e &&
- npm.command &&
npm
|
3b9536002c26a37b03184cc24c961a4110d1d27a
|
correct arg parsing
|
cli.js
|
cli.js
|
#!/usr/bin/env node
'use strict';
var path = require('path');
var mail = require('./server');
var fs = require('fs');
var configPath = path.resolve(process.argv[2]);
var len = process.argv.length;
fs.readFile(configPath, function (err, resp) {
if (err) {
throw err;
}
var config = JSON.parse(resp.toString());
switch (len) {
case 4: return mail(config.key, config.api);
case 5: return mail(config.key, config.api, process.argv[3]);
default: throw new TypeError('wrong number of arguments');
}
});
|
JavaScript
| 0.000189 |
@@ -343,9 +343,9 @@
ase
-4
+3
: re
@@ -392,9 +392,9 @@
ase
-5
+4
: re
|
2a045f549d39fc846526f876359ccb50ef2ba7be
|
edit comment
|
cli.js
|
cli.js
|
/*
* Copyright (c) 2011-2013, Yahoo! Inc. All rights reserved.
* Copyrights licensed under the New BSD License.
* See the accompanying LICENSE file for terms.
*/
'use strict';
var resolve = require('path').resolve,
log = require('./lib/log'),
getopts = require('./lib/getopts'),
getenv = require('./lib/getenv');
function tryRequire(str) {
var mod = false;
try {
mod = require(str);
log.debug('required %s', str);
} catch(err) {
log.debug('unable to require %s', str);
}
return mod;
}
/**
* load a module for use as a subcommand
* @param {string} sub-command, like 'help', 'create', etc.
* @param {object} cli, app, and mojito, metadata
* @return {object|function} module loaded via `require`
*/
function load(cmd, env) {
var mod = false,
mo_cmd_list = env.mojito && env.mojito.commands,
mo_cmd_path = mo_cmd_list && env.mojito.commandsPath;
// command path is registered in ./config.js:commands hash
if (env.cli.commands.hasOwnProperty(cmd)) {
mod = tryRequire(env.cli.commands[cmd]);
} else {
// command is in one of node's module.paths
mod = tryRequire('mojito-' + cmd);
// command is in local mojito commands path (BC)
if (!mod && mo_cmd_list && (mo_cmd_list.indexOf(cmd) > -1)) {
mod = tryRequire(resolve(mo_cmd_path, cmd));
}
}
return mod;
}
/**
* invoke subcommand with env metadata and callback
* @param {object} env
* @param {array} args command line arguments (see getopts.js)
* @param {object} opts command line options (see getopts.js)
* @param {string} cwd absolute path to current working directory
* @param {object} cli metadata (see getenv.js:cli())
* @param {object|false} app metadata (see getenv.js:read())
* @param {object|false} mojito metadata (see getenv.js:mojito())
* @param {function(err, msg)} callback
*/
function exec(env, cb) {
var mod = load(env.command, env);
// re-parse command line arguments; may modify env.args & env.opts
getopts.redux(env, mod.options);
if (mod && mod.hasOwnProperty('run')) {
log.debug('runnning legacy mojito command %s', env.command);
mod.run(env.args, env.opts, cb);
} else if ('function' === typeof mod) {
log.debug('getting bundled command %s', env.command);
mod(env, cb);
} else {
cb('Unable to invoke command ' + env.command);
}
}
/**
* gather configs and metadata in env object, and call exec
* @param {array} argv command line arguments process.argv.slice(2)
* @param {string} cwd current working directory process.cwd()
* @param {function(err, msg)} callback
* @return {string} subcommand name
*/
function main(argv, cwd, cb) {
var cli = getenv.cli(__dirname),
env = getopts(argv, cli.options);
if (env.opts.loglevel) {
log.level = env.opts.loglevel;
log.silly('logging level set to', env.opts.loglevel);
}
if (!env.command) {
log.error('No command.');
env.command = 'help';
}
// collect parsed args and env metadata
env.cwd = cwd;
env.cli = cli;
env.app = (cwd !== __dirname) && getenv(cwd);
env.mojito = env.app && getenv.mojito(cwd, env.opts.lib);
log.silly('env:', env);
exec(env, cb);
return env.command;
}
module.exports = main;
module.exports.load = load; // help.js
|
JavaScript
| 0 |
@@ -1126,37 +1126,126 @@
is
-in one of node's module.paths
+requireable, presumably in $NODE_PATH %60npm root -g%60%0A // http://nodejs.org/api/modules.html#modules_all_together
%0A
|
93b45bc111fb99f4adb717e42712f9fb636076d1
|
Refactor cli.js.
|
cli.js
|
cli.js
|
// Modules
import meow from 'meow';
import stdin from 'get-stdin';
import textr from 'textr';
// Native
import path from 'path';
import fs from 'fs';
// package.json
import pkg from './package';
const cli = meow(`
Usage
$ textr
Options
-t, --transforms Array of transformers
-w, --watch Watch sources
-d, --diff Output diff instead of result
`,
{
default: {
transforms: [],
watch: false,
diff: false
},
alias: {
t: 'transforms',
w: 'watch',
d: 'diff'
}
}
);
// Text that's gonna be transformed
let text = '';
// Resolve dir depend on cwd()
const resolveDir = file =>
path.resolve(process.cwd(), file);
// Write output
const write = (text) => {
process.stdout.write((textr().use.apply(null, tfs))(text));
process.exit(0);
};
// Get transformers from -t or --transforms
let tfs = cli.flags.transforms;
if (tfs) {
// if only one -t was used, then it's string, so split it
// After that, require everything
tfs = (typeof tfs === 'string' ? tfs.split(',') : tfs).map(tf => require(tf));
}
// Get input
if (cli.input[0]) {
// for files
const str = fs.readFileSync(resolveDir(cli.input[0])).toString();
write(str);
} else {
// For stdin
stdin().then(str => write(str));
}
|
JavaScript
| 0 |
@@ -1,10 +1,14 @@
//
+ NPM
Modules
@@ -111,16 +111,24 @@
/ Native
+ Modules
%0Aimport
@@ -181,58 +181,8 @@
';%0A%0A
-// package.json%0Aimport pkg from './package';%0A
%0Acon
@@ -283,18 +283,17 @@
-
-w
+h
, --
-watch
+help
@@ -301,75 +301,232 @@
-Watch sources%0A -d, --diff Output diff instead of result
+ Show this message%0A%0A Examples%0A $ textr foo.md -t typographic-quotes -t typographic-quotes%0A $ textr foo.md -t typographic-single-spaces,typographic-quotes%0A $ cat foo.md %7C textr --transforms=typographic-single-spaces
%0A%60,%0A
@@ -699,107 +699,17 @@
);%0A%0A
-// Text that's gonna be transformed%0Alet text = '';%0A%0A// Resolve dir depend on cwd()%0Aconst resolveDir
+const cwd
= f
@@ -757,43 +757,38 @@
);%0A%0A
-// Write output%0Aconst write = (text
+const render = (text, tfs = %5B%5D
) =%3E
@@ -879,198 +879,51 @@
%7D;%0A%0A
-// Get transformers from -t or --transforms%0Alet tfs = cli.flags.transforms;%0Aif (tfs) %7B%0A // if only one -t was used, then it's string, so split it%0A // After that, require everything%0A tfs =
+const tfs = (t = cli.flags.transforms) =%3E%0A
(ty
@@ -928,18 +928,16 @@
typeof t
-fs
=== 'st
@@ -945,18 +945,16 @@
ing' ? t
-fs
.split('
@@ -960,18 +960,16 @@
',') : t
-fs
).map(tf
@@ -985,18 +985,16 @@
re(tf));
-%0A%7D
%0A%0A// Get
@@ -1029,31 +1029,69 @@
//
-for files%0A const str =
+If there is first argument, then read this file%0A render(%0A
fs.
@@ -1107,18 +1107,11 @@
ync(
-resolveDir
+cwd
(cli
@@ -1136,21 +1136,22 @@
ng()
-;%0A write(str
+,%0A tfs()%0A
);%0A%7D
@@ -1167,11 +1167,54 @@
//
-For
+If there's no first argument, then try to read
std
@@ -1225,16 +1225,21 @@
stdin()
+%0A
.then(st
@@ -1247,18 +1247,49 @@
=%3E
-write(str)
+render(str, tfs()))%0A .catch(err =%3E err
);%0A%7D
|
ee84aa3d06110f56645ed4705e50ccae7a1d6bbd
|
Fix mismatched argument in debugger attach event handler
|
cmd.js
|
cmd.js
|
#!/usr/bin/env node
var amok = require('./');
var async = require('async');
var fs = require('fs');
var path = require('path');
var repl = require('repl');
var util = require('util');
var bole = require('bole');
var bistre = require('bistre');
function program(callback, data) {
var cmd = require('commander');
var pkg = require('./package.json');
cmd.usage('[options] <script>');
cmd.version(pkg.version);
cmd.option('--host <HOST>', 'specify http host', 'localhost');
cmd.option('--port <PORT>', 'specify http port', 9966);
cmd.option('--debugger-host <HOST>', 'specify debugger host', 'localhost');
cmd.option('--debugger-port <PORT>', 'specify debugger port', 9222);
cmd.option('-i, --interactive', 'enable interactive mode');
cmd.option('--client <CMD>', 'specify the client to spawn');
cmd.option('--compiler <CMD>', 'specify the compiler to spawn');
cmd.option('-v, --verbose', 'enable verbose logging mode');
cmd.parse(process.argv);
cmd.cwd = process.cwd();
if (cmd.args.length < 1) {
cmd.help();
}
var scripts = cmd.args.filter(function(arg) {
return path.extname(arg);
});
cmd.scripts = scripts.reduce(function(object, value, key) {
object[value] = path.resolve(value);
return object;
}, {});
var transform = bistre.createStream();
transform.pipe(process.stdout);
bole.output({
level: cmd.verbose ? 'info' : 'error',
stream: transform
});
callback(null, cmd);
}
function compiler(callback, data) {
var log = bole('compile');
if (data.program.compiler === undefined) {
log.info('skip');
return callback(null, null);
}
log.info('spawn');
var compiler = amok.compile(data.program, function(error, stdout, stderr) {
if (error) {
return callback(error);
}
log.info('ok', { pid: compiler.pid });
data.program.scripts = {
'bundle.js': compiler.output,
};
callback(null, compiler);
});
compiler.stdout.on('data', function(data) {
log.info(data.toString());
});
compiler.stderr.on('data', function(data) {
log.error(data.toString());
});
}
function watcher(callback, data) {
var log = bole('watch');
log.info('start');
var watcher = amok.watch(data.program, function() {
log.info('ok');
callback(null, watcher);
});
watcher.on('change', function(filename) {
log.info('change', { filename: filename });
var script = Object.keys(data.program.scripts).filter(function(key) {
return data.program.scripts[key] === filename;
}).pop();
if (script) {
log.info('re-compile', { filename: filename });
fs.readFile(filename, 'utf-8', function(error, contents) {
if (error) {
log.error(error);
}
data.bugger.source(script, contents, function(error) {
if (error) {
return log.error(error);
}
log.info('ok');
});
});
}
});
watcher.on('error', function(error) {
log.error(error);
process.exit(error.errno);
});
}
function server(callback, data) {
var log = bole('http');
log.info('starting');
var server = amok.serve(data.program, function() {
var address = server.address();
log.info('listening', { host: address.address, port: address.port });
callback(null, server);
});
server.on('request', function(request, response) {
log.info(request);
});
server.on('error', function(error) {
log.error(error);
process.exit(error.errno);
});
}
function client(callback, data) {
var log = bole('client');
if (data.program.client === undefined) {
log('skip');
return callback(null, null);
}
log.info('spawn');
var client = amok.open(data.program, function(error, stdout, stderr) {
if (error) {
return callback(error);
}
log.info('ok', { pid: client.pid });
callback(null, client);
});
client.on('error', function(error) {
log.error(error);
process.exit(error.errno);
});
client.stdout.on('data', function(data) {
log.info(data.toString());
});
client.stderr.on('data', function(data) {
log.warn(data.toString());
});
}
function bugger(callback, data) {
var log = bole('debugger');
log.info('connect');
var bugger = amok.debug(data.program, function(error, target) {
if (error) {
return callback(error);
}
callback(null, bugger);
});
bugger.on('attach', function(error) {
log.info('attach', { url: target.url, title: target.title });
});
bugger.on('detatch', function() {
log.warn('detatch');
});
bugger.on('error', function(error) {
log.error(error);
process.exit(error.errno);
});
bugger.console.on('data', function(message) {
if (message.parameters) {
var parameters = message.parameters.map(function(parameter) {
return parameter.value;
});
if (console[message.level]) {
console[message.level].apply(console, parameters);
}
}
});
}
function prompt(callback, data) {
if (data.program.interactive === undefined) {
return callback(null, null);
}
var options = {
prompt: '> ',
input: process.stdin,
output: process.stdout,
writer: function(result) {
if (result.value) {
return util.inspect(result.value, {
colors: true,
});
} else if (result.objectId) {
return util.format('[class %s]\n%s', result.className, result.description);
}
},
eval: function(cmd, context, filename, write) {
data.bugger.evaluate(data.program, function(error, result) {
write(error, result);
});
},
};
var prompt = repl.start(options);
callback(null, prompt);
}
async.auto({
'program': [program],
'compiler': ['program', compiler],
'server': ['program', 'compiler', server],
'client': ['program', 'server', client],
'bugger': ['program', 'client', bugger],
'watcher': ['program', 'bugger', watcher],
'prompt': ['program', 'bugger', prompt],
}, function(error, data) {
if (error) {
console.error(error);
process.exit(1);
}
});
|
JavaScript
| 0.000009 |
@@ -4420,37 +4420,38 @@
tach', function(
-error
+target
) %7B%0A log.info
|
78e329eaa3f8f7d434da79acfe9db35f5600124e
|
Update Sounds.js
|
ColorsAndGraphics/Sounds.js
|
ColorsAndGraphics/Sounds.js
|
function Sounds(callback) {
Sounds.names = [];
Sounds.durations = [];
Sounds.loadNames(callback);
}
Sounds.loadNames=function(parentCallback){
var request = "sound/names";
var callback = function(response) {
Sounds.names = response.split("\n")
Sounds.names = Sounds.names.filter(function(n){ return n != "" });
HtmlServer.sendRequest("server/log/LOG:Got_Names"+Sounds.names.length);
for (var i = 0; i < Sounds.names.length; i++) {
var request = "sound/duration/" + Sounds.getSoundName(i);
var callback = function(duration) {
HtmlServer.sendRequest("server/log/LOG:Got_duration"+ Sounds.getSoundName(i));
Sounds.durations[i] = duration;
if(i == Sounds.names.length - 1) {
parentCallback();
}
}
HtmlServer.sendRequestWithCallback(request,callback);
}
};
HtmlServer.sendRequestWithCallback(request, callback);
};
Sounds.getSoundDuration=function(index){
return Sounds.durations[index];
};
Sounds.getSoundName=function(index){
return Sounds.names[index];
};
Sounds.getSoundCount=function(){
return Sounds.names.length;
};
Sounds.indexFromName=function(soundName){
return Sounds.names.indexOf(soundName);
};
Sounds.checkNameIsValid=function(soundName){
return Sounds.indexFromName(soundName)>=0;
};
|
JavaScript
| 0.000001 |
@@ -503,32 +503,69 @@
(i);%0A%09%09%09var
-c
+durationCallback = %5B%5D;%0A%09%09%09durationC
allback
+%5Bi%5D
= function(
@@ -631,16 +631,27 @@
duration
+:%22 + i + %22:
%22+ Sound
@@ -825,24 +825,35 @@
request,
-c
+durationC
allback
+%5Bi%5D
);%0A%09%09%7D%09%0A
|
cda7f4ea95ac3262de2df11aa156deab86431a13
|
correct path
|
lib.js
|
lib.js
|
module.exports = require('./lib');
|
JavaScript
| 0.000354 |
@@ -24,11 +24,18 @@
e('./lib
+/lib.js
');
|
e92cb3e821e3972d3f80d8e25f177ae48c5d6d71
|
Exclude plumbing commands from completion
|
npm.js
|
npm.js
|
process.title = "npm"
if (require.main === module) {
console.error(["It looks like you're doing 'node npm.js'."
,"Don't do that. Instead, run 'make install'"
,"and then use the 'npm' command line utility."
].join("\n"))
process.exit(1)
}
var EventEmitter = require("events").EventEmitter
, npm = module.exports = new EventEmitter
, config = require("./lib/config")
, set = require("./lib/utils/set")
, get = require("./lib/utils/get")
, ini = require("./lib/utils/ini")
, log = require("./lib/utils/log")
, fs = require("./lib/utils/graceful-fs")
, path = require("path")
, mkdir = require("./lib/utils/mkdir-p")
, abbrev = require("./lib/utils/abbrev")
npm.commands = {}
npm.ELIFECYCLE = {}
npm.E404 = {}
try {
// startup, ok to do this synchronously
var j = JSON.parse(fs.readFileSync(path.join(__dirname, "package.json"))+"")
npm.version = j.version
npm.nodeVersionRequired = j.engines.node
} catch (ex) {
try {
log(ex, "error reading version")
} catch (er) {}
npm.version = ex
}
var commandCache = {}
// short names for common things
, aliases = { "rm" : "uninstall"
, "r" : "uninstall"
, "un" : "uninstall"
, "rb" : "rebuild"
, "bn" : "bundle"
, "list" : "ls"
, "ln" : "link"
, "i" : "install"
, "up" : "update"
, "c" : "config"
}
, aliasNames = Object.keys(aliases)
// these are filenames in ./lib
, cmdList = [ "install"
, "activate"
, "deactivate"
, "uninstall"
, "build"
, "link"
, "publish"
, "tag"
, "adduser"
, "config"
, "help"
, "cache"
, "test"
, "stop"
, "start"
, "restart"
, "unpublish"
, "ls"
, "owner"
, "update"
, "update-dependents"
, "view"
, "repl"
, "rebuild"
, "bundle"
, "outdated"
, "init"
, "completion"
, "deprecate"
, "version"
, "edit"
, "explore"
, "docs"
]
, fullList = npm.fullList = cmdList.concat(aliasNames)
, abbrevs = abbrev(fullList)
Object.keys(abbrevs).forEach(function (c) {
Object.defineProperty(npm.commands, c, { get : function () {
if (!loaded) throw new Error(
"Call npm.load(conf, cb) before using this command.\n"+
"See the README.md or cli.js for example usage.")
var a = npm.deref(c)
if (commandCache[a]) return commandCache[a]
return commandCache[a] = require(__dirname+"/lib/"+a)
}, enumerable: fullList.indexOf(c) !== -1 })
})
npm.deref = function (c) {
var a = abbrevs[c]
if (aliases[a]) a = aliases[a]
return a
}
var loaded = false
npm.load = function (conf, cb_) {
if (!cb_ && typeof conf === "function") cb_ = conf , conf = {}
function cb (er) { return cb_(er, npm) }
if (loaded) return cb()
loaded = true
log.waitForConfig()
ini.resolveConfigs(conf, function (er) {
if (er) return cb(er)
mkdir(npm.tmp, cb)
})
}
// Local store for package data, so it won't have to be fetched/read more than
// once in a single pass.
var registry = {}
npm.set = function (key, val) {
if (typeof key === "object" && !val && key._id) {
val = key
key = key._id
}
return set(registry, key, val)
}
npm.get = function (key) { return get(registry, key) }
var path = require("path")
npm.config =
{ get : function (key) { return ini.get(key) }
, set : function (key, val) { return ini.set(key, val, "cli") }
, del : function (key, val) { return ini.del(key, val, "cli") }
}
Object.defineProperty(npm, "root",
{ get : function () { return npm.config.get("root") }
, set : function (r) {
r = r.charAt(0) === "/" ? r
: path.join(process.execPath, "..", "..", r)
return npm.config.set("root", r)
}
, enumerable : true
})
Object.defineProperty(npm, "dir",
{ get : function () { return path.join(npm.root, ".npm") }
, enumerable : true
})
Object.defineProperty(npm, "cache",
{ get : function () { return path.join(npm.root, ".npm", ".cache") }
, enumerable : true
})
var tmpFolder
Object.defineProperty(npm, "tmp",
{ get : function () {
if (!tmpFolder) tmpFolder = "npm-"+Date.now()
return path.join(npm.config.get("tmproot"), tmpFolder)
}
, enumerable : true
})
if (process.getuid() === 0) process.nextTick(function () {
log( "\nRunning npm as root is not recommended!\n"
+ "Seriously, don't do this!\n", "sudon't!", "error")
})
|
JavaScript
| 0.000024 |
@@ -2401,59 +2401,207 @@
,
-fullList = npm.fullList = cmdList.concat(aliasNames
+plumbing = %5B %22build%22%0A , %22update-dependents%22%0A %5D%0A , fullList = npm.fullList = cmdList.concat(aliasNames).filter(function (c) %7B%0A return plumbing.indexOf(c) === -1%0A %7D
)%0A
@@ -2651,16 +2651,33 @@
bbrevs).
+concat(plumbing).
forEach(
@@ -3114,16 +3114,59 @@
n (c) %7B%0A
+ if (plumbing.indexOf(c) !== -1) return c%0A
var a
|
64914fae33c4fd9891a1ecb7d2b76269c67fa15f
|
work in node, and have more helpful error message
|
rng.js
|
rng.js
|
(function() {
module.exports = function(size) {
var bytes = new Buffer(size); //in browserify, this is an extended Uint8Array
/* This will not work in older browsers.
* See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
*/
crypto.getRandomValues(bytes);
return bytes;
}
}())
|
JavaScript
| 0 |
@@ -13,42 +13,271 @@
%7B%0A
-module.exports = function(size) %7B%0A
+var g = ('undefined' === typeof window ? global : window) %7C%7C %7B%7D%0A var foolBrowserify = require%0A _crypto = (%0A g.crypto %7C%7C g.msCrypto %7C%7C foolBrowserify('crypto')%0A )%0A module.exports = function(size) %7B%0A // Modern Browsers%0A if(_crypto.getRandomValues) %7B%0A
@@ -354,16 +354,18 @@
t8Array%0A
+
/* T
@@ -406,16 +406,18 @@
s.%0A
+
* See ht
@@ -493,16 +493,18 @@
mValues%0A
+
*/%0A
@@ -507,16 +507,24 @@
*/%0A
+%0A _
crypto.g
@@ -541,34 +541,284 @@
lues
-(bytes);%0A return bytes;
+%0A return bytes;%0A %7D%0A else if (_crypto.randomBytes) %7B%0A return _crypto.randomBytes(size)%0A %7D%0A else%0A throw new Error(%0A 'secure random number generation not supported by this browser%5Cn'+%0A 'use chrome, FireFox or Internet Explorer 11'%0A )
%0A %7D
|
3c6aba6ed4037bf1828ac8f038bc323002f99b66
|
remove unneeded background attr
|
packages/mjml-column/src/index.js
|
packages/mjml-column/src/index.js
|
import { BodyComponent } from 'mjml-core'
import widthParser from 'mjml-core/lib/helpers/widthParser'
export default class MjColumn extends BodyComponent {
static allowedAttributes = {
'background-color': 'color',
border: 'string',
'border-bottom': 'string',
'border-left': 'string',
'border-radius': 'unit(px,%)',
'border-right': 'string',
'border-top': 'string',
direction: 'enum(ltr,rtl)',
'padding-bottom': 'unit(px,%)',
'padding-left': 'unit(px,%)',
'padding-right': 'unit(px,%)',
'padding-top': 'unit(px,%)',
padding: 'unit(px,%){1,4}',
'vertical-align': 'string',
width: 'unit(px,%)',
}
static defaultAttributes = {
direction: 'ltr',
'vertical-align': 'top',
}
getChildContext() {
const { containerWidth: parentWidth } = this.context
const { nonRawSiblings } = this.props
const paddingSize =
this.getShorthandAttrValue('padding', 'left') +
this.getShorthandAttrValue('padding', 'right')
let containerWidth =
this.getAttribute('width') ||
`${parseFloat(parentWidth) / nonRawSiblings}px`
const { unit, parsedWidth } = widthParser(containerWidth, {
parseFloatToInt: false,
})
if (unit === '%') {
containerWidth = `${parseFloat(parentWidth) * parsedWidth / 100 -
paddingSize}px`
} else {
containerWidth = `${parsedWidth - paddingSize}px`
}
return {
...this.context,
containerWidth,
}
}
getStyles() {
const tableStyle = {
'background-color': this.getAttribute('background-color'),
border: this.getAttribute('border'),
'border-bottom': this.getAttribute('border-bottom'),
'border-left': this.getAttribute('border-left'),
'border-radius': this.getAttribute('border-radius'),
'border-right': this.getAttribute('border-right'),
'border-top': this.getAttribute('border-top'),
'vertical-align': this.getAttribute('vertical-align'),
}
return {
div: {
'font-size': '13px',
'text-align': 'left',
direction: this.getAttribute('direction'),
display: 'inline-block',
'vertical-align': this.getAttribute('vertical-align'),
width: this.getMobileWidth(),
},
table: {
...(this.hasGutter() ? {} : tableStyle),
},
tdOutlook: {
'vertical-align': this.getAttribute('vertical-align'),
width: this.getWidthAsPixel(),
},
gutter: {
...tableStyle,
padding: this.getAttribute('padding'),
'padding-top': this.getAttribute('padding-top'),
'padding-right': this.getAttribute('padding-right'),
'padding-bottom': this.getAttribute('padding-bottom'),
'padding-left': this.getAttribute('padding-left'),
},
}
}
getMobileWidth() {
const { nonRawSiblings, containerWidth } = this.context
const width = this.getAttribute('width')
const mobileWidth = this.getAttribute('mobileWidth')
if (mobileWidth !== 'mobileWidth') {
return '100%'
} else if (width === undefined) {
return `${parseInt(100 / nonRawSiblings, 10)}%`
}
const { unit, parsedWidth } = widthParser(width, {
parseFloatToInt: false,
})
switch (unit) {
case '%':
return width
case 'px':
default:
return `${parsedWidth / parseInt(containerWidth, 10)}%`
}
}
getWidthAsPixel() {
const { containerWidth } = this.context
const { unit, parsedWidth } = widthParser(this.getParsedWidth(true), {
parseFloatToInt: false,
})
if (unit === '%') {
return `${parseFloat(containerWidth) * parsedWidth / 100}px`
}
return `${parsedWidth}px`
}
getParsedWidth(toString) {
const { nonRawSiblings } = this.props
const width = this.getAttribute('width') || `${100 / nonRawSiblings}%`
const { unit, parsedWidth } = widthParser(width, {
parseFloatToInt: false,
})
if (toString) {
return `${parsedWidth}${unit}`
}
return {
unit,
parsedWidth,
}
}
getColumnClass() {
const { addMediaQuery } = this.context
let className = ''
const { parsedWidth, unit } = this.getParsedWidth()
switch (unit) {
case '%':
className = `mj-column-per-${parseInt(parsedWidth, 10)}`
break
case 'px':
default:
className = `mj-column-px-${parseInt(parsedWidth, 10)}`
break
}
// Add className to media queries
addMediaQuery(className, {
parsedWidth,
unit,
})
return className
}
hasGutter() {
return [
'padding',
'padding-bottom',
'padding-left',
'padding-right',
'padding-top',
].some(attr => this.getAttribute(attr) != null)
}
renderGutter() {
return `
<table
${this.htmlAttributes({
background: this.getAttribute('background-color'),
border: '0',
cellpadding: '0',
cellspacing: '0',
role: 'presentation',
width: '100%',
})}
>
<tbody>
<tr>
<td ${this.htmlAttributes({ style: 'gutter' })}>
${this.renderColumn()}
</td>
</tr>
</tbody>
</table>
`
}
renderColumn() {
const { children } = this.props
return `
<table
${this.htmlAttributes({
border: '0',
cellpadding: '0',
cellspacing: '0',
role: 'presentation',
style: 'table',
width: '100%',
})}
>
${this.renderChildren(children, {
renderer: (
component, // eslint-disable-line no-confusing-arrow
) =>
component.constructor.isRawElement()
? component.render()
: `
<tr>
<td
${component.htmlAttributes({
align: component.getAttribute('align'),
'vertical-align': component.getAttribute('vertical-align'),
class: component.getAttribute('css-class'),
style: {
background: component.getAttribute(
'container-background-color',
),
'font-size': '0px',
padding: component.getAttribute('padding'),
'padding-top': component.getAttribute('padding-top'),
'padding-right': component.getAttribute('padding-right'),
'padding-bottom': component.getAttribute('padding-bottom'),
'padding-left': component.getAttribute('padding-left'),
'word-break': 'break-word',
},
})}
>
${component.render()}
</td>
</tr>
`,
})}
</table>
`
}
render() {
let classesName = `${this.getColumnClass()} outlook-group-fix`
if (this.getAttribute('css-class')) {
classesName += ` ${this.getAttribute('css-class')}`
}
return `
<div
${this.htmlAttributes({
class: classesName,
style: 'div',
})}
>
${this.hasGutter() ? this.renderGutter() : this.renderColumn()}
</div>
`
}
}
|
JavaScript
| 0.000001 |
@@ -4867,69 +4867,8 @@
s(%7B%0A
- background: this.getAttribute('background-color'),%0A
|
d42f5c24fc2fa0b63aba54c1ab6257319d29b6d1
|
set dropbox api key for staging
|
lib/assets/javascripts/cartodb/common/import_dropbox_pane.js
|
lib/assets/javascripts/cartodb/common/import_dropbox_pane.js
|
/**
* Dropbox pane for import a file
*/
cdb.admin.ImportDropboxPane = cdb.admin.ImportPane.extend({
className: "import-pane import-pane-dropbox",
events: {
'click .dropbox-chooser' : '_onClickDBButton'
},
_APPI_KEY: 'gy3nqo2op179l74',
initialize: function() {
this.template = this.options.template || cdb.templates.getTemplate('common/views/import_dropbox');
this.render();
},
_onClickDBButton: function(e) {
var self = this;
this.killEvent(e);
Dropbox.choose({
linkType: "direct",
multiselect: false,
success: function(files) {
var link = files[0].link;
self.trigger('fileChosen', 'url', link);
}
});
},
render: function() {
this.$el.html(this.template({ app_api_key: this._APPI_KEY }));
return this;
}
});
|
JavaScript
| 0 |
@@ -257,23 +257,23 @@
Y: '
-gy3nqo2op179l74
+8q16cyuf54akjf3
',%0A%0A
|
8f40ad51df609a9c0a30545ea578730f2ccbaf7a
|
Fix undefined error variable.
|
lib/shikimori.js
|
lib/shikimori.js
|
var request = require('request'),
querystring = require('querystring');
var baseUrl = 'https://shikimori.org/api/';
var Shikimori = function(options, callback) {
if (!(this instanceof Shikimori)) {
return new Shikimori(options, callback);
}
if (typeof options === 'function') {
callback = options;
}
if (options.nickname === undefined) {
callback(null, this);
} else {
this.nickname = options.nickname;
if (options.password !== undefined) {
var self = this;
this.requestToken(this.nickname, options.password, function(err, token) {
if (typeof callback === 'function') {
callback(err, self);
}
});
} else if (options.token !== undefined) {
this.setToken(options.token);
if (typeof callback === 'function') {
callback(null, this);
}
} else {
callback('Password/Token is required');
}
}
return this;
}
Shikimori.prototype.request = function(method, path, params, callback) {
callback = callback || function() {}
var url = baseUrl + path;
if (typeof params === 'function') {
callback = params;
} else if (method === 'get') {
url += '?' + querystring.stringify(params);
}
var options = {
url: url,
method: method.toUpperCase(),
headers: {
'X-User-Nickname': this.nickname,
'X-User-Api-Access-Token': this.token,
'User-Agent': 'node-shikimori',
}
};
if (method !== 'get' && params !== undefined) {
options.body = JSON.stringify(params);
options.headers['Content-Type'] = 'application/json';
}
request(options, function(err, response, data) {
if (err) {
callback(error);
} else {
try {
var parsedData = JSON.parse(data);
} catch (e) {
callback(e, data, response);
}
callback(null, parsedData, response);
}
});
}
Shikimori.prototype.get = function(path, params, callback) {
return this.request('get', path, params, callback);
}
Shikimori.prototype.post = function(path, params, callback) {
return this.request('post', path, params, callback);
}
Shikimori.prototype.patch = function(path, params, callback) {
return this.request('post', path, params, callback);
}
Shikimori.prototype.put = function(path, params, callback) {
return this.request('post', path, params, callback);
}
Shikimori.prototype.delete = function(path, callback) {
return this.request('delete', path, undefined, callback);
}
Shikimori.prototype.setToken = function(token) {
this.token = token;
}
Shikimori.prototype.requestToken = function(nickname, password, callback) {
var self = this;
this.get('access_token', {nickname: nickname, password: password}, function(err, data, response) {
var token = data.api_access_token;
if (err) {
callback(err);
} else if (token === null || token === undefined) {
callback('Invalid login or password');
} else {
var token = data.api_access_token;
self.setToken(token);
callback(null, token);
}
});
}
exports.Shikimori = Shikimori;
|
JavaScript
| 0.000002 |
@@ -1662,18 +1662,16 @@
back(err
-or
);%0A %7D
@@ -3056,8 +3056,9 @@
ikimori;
+%0A
|
8473d6b6029a9a6aee3ce2fed76787345337fc25
|
Fix Linux Bug
|
lib/spellbook.js
|
lib/spellbook.js
|
//
// SpellBook Manager
//
var Handlebars = require("Handlebars");
var git = require("simple-git");
var path = require("path");
var fs = require("fs");
function objMerge (obj1, obj2) {
for (var item in obj2) {
if (!this.hasOwnProperty(item))
obj1[item] = obj2[item];
}
return obj1;
}
var walk = function(dir) {
var results = [];
var list = fs.readdirSync(dir);
list.forEach(function(file) {
var f = file;
file = path.join(dir, file);
var stat = fs.statSync(file);
if (f.startsWith(".") || stat.isSymbolicLink())
return;
if (stat && stat.isDirectory() )
results = results.concat(walk(file));
else
results.push(file);
});
return results;
};
function render(str, data, gVars) {
var template = Handlebars.compile(str);
var templateData = objMerge(data, gVars);
return template(templateData);
}
module.exports = function(stupefy) {
var SB = {
fetch: function(repo) {
console.log("Fetching " + repo);
git(stupefy.conf["spells"]).clone(repo, function(err, rsp) {
console.log(rsp);
if (!err) {
console.log("Finished");
console.log("Added spellbook " + repo);
// Update metadata
} else {
stupefy.error(err);
}
});
},
update: function(dirName, done) {
var rp = git(path.join(stupefy.conf["spells"], dirName));
rp.getRemotes(true, function(e, remotes) {
if (e || remotes.length == 0) {
stupefy.error("No remote found for " + dirName);
return;
}
var url = remotes[0].refs.fetch;
rp.fetch(url, function (err, fetchSummary) {
if (!err) {
// check if update available
if (fetchSummary.raw != "") {
rp.pull(function(error, update) {
if (!error && update) {
console.log("Updated Spellbook - " + dirName);
console.log(update.summary);
done();
}
});
} else {
console.log(dirName + " is up to date");
}
}
});
});
},
// remove spellbook
remove: function(name) {
var dir = path.join(stupefy.conf["spells"], name);
if (fs.existsSync(dir)) {
fs.rmdirSync(dir);
}
},
list: function(name) {
if (!stupefy.spells) {
var spellsDir = stupefy.conf["spells"];
var results = [];
var files = fs.readdirSync(spellsDir).filter(function(fname) {
if(fs.statSync(path.join(spellsDir, fname)).isDirectory())
return true;
else if (!fname.startsWith("."))
results.push(path.join(spellsDir, fname));
});
for (var i = 0;i < files.length;i++) {
results = results.concat(walk(path.join(spellsDir, files[i]), name));
}
stupefy.spells = results;
}
if(typeof name == "undefined")
return stupefy.spells;
// filter
return stupefy.spells.filter(function(relpath) {
return path.basename(relpath) == name;
});
},
enchant: function(name, data) {
var results = SB.list(name);
if (results.length > 0) {
return render(fs.readFileSync(results[0], "utf8"), data, stupefy.variables);
} else {
// Search Remote Repositories
stupefy.error("No such spell named " + name);
}
}
};
return SB;
};
|
JavaScript
| 0.000001 |
@@ -47,17 +47,17 @@
equire(%22
-H
+h
andlebar
|
a0ec026eff24c456405f2fcd3ac748e04c34e06f
|
remove secrets.js
|
dale/main.js
|
dale/main.js
|
// Generated by CoffeeScript 1.9.3
(function() {
var Slack, autoMark, autoReconnect, slack, token;
var scoreKeeper = require('./scoreKeeper.js');
var yolo = require('./yolo.js');
var secrets = require('../secrets.js');
Slack = require('..');
token = process.env.SLACKBOT_TOKEN;
autoReconnect = true;
autoMark = true;
slack = new Slack(token, autoReconnect, autoMark);
scoreKeeper(slack);
yolo(slack);
slack.on('open', function() {
var channel, channels, group, groups, id, messages, unreads;
channels = [];
groups = [];
unreads = slack.getUnreadCount();
channels = (function() {
var ref, results;
ref = slack.channels;
results = [];
for (id in ref) {
channel = ref[id];
if (channel.is_member) {
results.push("#" + channel.name);
}
}
return results;
})();
groups = (function() {
var ref, results;
ref = slack.groups;
results = [];
for (id in ref) {
group = ref[id];
if (group.is_open && !group.is_archived) {
results.push(group.name);
}
}
return results;
})();
console.log("Welcome to Slack. You are @" + slack.self.name + " of " + slack.team.name);
console.log('You are in: ' + channels.join(', '));
console.log('As well as: ' + groups.join(', '));
messages = unreads === 1 ? 'message' : 'messages';
return console.log("You have " + unreads + " unread " + messages);
});
slack.on('error', function(error) {
return console.error("Error: " + error);
});
slack.login();
}).call(this);
|
JavaScript
| 0.000002 |
@@ -184,50 +184,8 @@
);%0A%0A
- var secrets = require('../secrets.js');%0A
Sl
|
3760477abbf5162cf8a2a2fbb0d3ddfdd8291848
|
fix confirmUser method
|
src/main/webapp/javascript/user-auth.js
|
src/main/webapp/javascript/user-auth.js
|
var auth2;
function getId() {
return auth2.currentUser.get().getId();
}
function onStart() {
console.log("onstart");
gapi.load('auth2', initSigninV2);
}
/**
* initializes google authentication API and sets event listeners.
*/
function initSigninV2() {
auth2 = gapi.auth2.init({
client_id : '1034390229233-u07o0iaas2oql8l4jhe7fevpfsbrtv7n.apps.googleusercontent.com'
});
gapi.signin2.render('g-signin-container');
auth2.currentUser.listen(function(newGoogleUser) {
insertUserInfo(newGoogleUser);
});
auth2.isSignedIn.listen(function(signedIn) {
if (signedIn) {
console.log('enable dropdown');
enableUserDropdown();
} else {
console.log('disable dropdown');
disableUserDropdown();
}
});
}
/**
* returns a promise that resolves when user signs in,
* or rejects if user does not sign in.
* currently doesn't work because auth2.signin resolves before signin is complete
* for some reason.
*/
function confirmUser() {
return new Promise((resolve, reject) => {
if (!auth2.isSignedIn.get()) {
auth2.signIn().then(resolve()).catch(reject());
} else {
console.log("already done");
resolve();
}
})
}
/**
* signs our current user from g-signin API.
*/
function signOut() {
auth2.signOut().then(function () {
console.log('User signed out.');
});
}
/**
* To be run in currentUser listener, activates whenever current user changes.
*
* @param {GoogleUser} current user to provide profile info.
*/
function insertUserInfo(googleUser) {
// insert user name into user-page anchor
let text = googleUser.getBasicProfile().getGivenName() + '\'s Page';
const userPageAnchor = document.getElementById('user-page-anchor');
userPageAnchor.innerText = text;
}
function enableUserDropdown() {
const dropdown = document.querySelector('.dropdown');
dropdown.addEventListener('mouseover', showDropdown = function() {
dropdown.querySelector('.dropdown-content').style.display = 'block';
});
dropdown.addEventListener('mouseleave', hideDropdown = function() {
dropdown.querySelector('.dropdown-content').style.display = 'none';
});
}
function disableUserDropdown() {
const dropdown = document.querySelector('.dropdown');
dropdown.removeEventListener('mouseover', showDropdown);
dropdown.removeEventListener('mouseleave', hideDropdown);
dropdown.querySelector('.dropdown-content').style.display = 'none';
}
function userSpecificService() {
confirmUser.then(console.log('test ' + auth2.currentUser.get().getBasicProfile().getName()));
}
|
JavaScript
| 0.000001 |
@@ -759,466 +759,8 @@
%0A%7D%0A%0A
-/**%0A * returns a promise that resolves when user signs in,%0A * or rejects if user does not sign in.%0A * currently doesn't work because auth2.signin resolves before signin is complete%0A * for some reason.%0A */%0Afunction confirmUser() %7B%0A return new Promise((resolve, reject) =%3E %7B%0A if (!auth2.isSignedIn.get()) %7B%0A auth2.signIn().then(resolve()).catch(reject());%0A %7D else %7B%0A console.log(%22already done%22);%0A resolve();%0A %7D%0A %7D)%0A%7D
%0A%0A/*
@@ -1992,24 +1992,330 @@
'none';%0A%7D%0A%0A
+/**%0A * Provides a sign-in popup if user is signed out,%0A * returns a promise when user is signed in.%0A * %0A */%0Afunction confirmUser() %7B%0A return new Promise((resolve, reject) =%3E %7B%0A if (!auth2.isSignedIn.get()) %7B%0A auth2.signIn().then(resolve).catch(reject);%0A %7D else %7B%0A resolve();%0A %7D%0A %7D)%0A%7D%0A%0A
function use
@@ -2354,31 +2354,142 @@
User
+()
.then(
-console.log('test
+(googleUser) =%3E %7B%0A outputPlace = document.getElementById('test-output');%0A outputPlace.innerText = 'current user:
' +
@@ -2540,13 +2540,19 @@
etName()
-)
+;%0A %7D
);%0A%7D
|
cfd4ae8c4cb66b66070f05880e5fafbdcf521f60
|
Make it a kata, all tests fail.
|
katas/es6/language/symbol/keyFor.js
|
katas/es6/language/symbol/keyFor.js
|
// 36: Symbol.keyFor - retrieves a shared symbol key from the global symbol registry
// To do: make all tests pass, leave the assert lines unchanged!
describe('`Symbol.keyFor` gets the symbol key for a given symbol', function() {
it('pass the symbol to `keyFor()` and you get it`s key', function() {
const sym = Symbol.for('foo');
const key = Symbol.keyFor(sym);
assert.equal(key, 'foo');
});
it('local symbols are not in the runtime-wide registry', function() {
const localSymbol = Symbol('foo');
const key = Symbol.keyFor(localSymbol);
assert.equal(key, void 0);
});
it('well-known symbols are not in the runtime-wide registry either', function() {
const key = Symbol.keyFor(Symbol.iterator);
assert.equal(key, void 0);
});
it('for non-Symbols throws an error', function() {
function fn() {
Symbol.keyFor(null);
}
assert.throws(fn);
});
});
|
JavaScript
| 0.000003 |
@@ -223,24 +223,60 @@
tion() %7B%0A %0A
+ const sym = Symbol.for('foo');%0A %0A
it('pass t
@@ -339,43 +339,8 @@
) %7B%0A
- const sym = Symbol.for('foo');%0A
@@ -358,22 +358,20 @@
Symbol.
-keyFor
+____
(sym);%0A
@@ -477,32 +477,80 @@
', function() %7B%0A
+ // hint: %60Symbol()%60 creates a local symbol!%0A
const localS
@@ -563,16 +563,20 @@
= Symbol
+.for
('foo');
@@ -791,17 +791,17 @@
ol.itera
-t
+T
or);%0A
@@ -939,12 +939,11 @@
For(
-null
+sym
);%0A
|
fdedf5349ba7fec5a205b7ac854e1ded49b8b3b3
|
Add Organizations Reducer tests.
|
app/scripts/reducers/organizations.js
|
app/scripts/reducers/organizations.js
|
import superagent from 'superagent'
const REQUEST_FETCH_ORGANIZATIONS = 'REQUEST_FETCH_ORGANIZATIONS'
const SUCCESS_FETCH_ORGANIZATIONS = 'SUCCESS_FETCH_ORGANIZATIONS'
const FAILURE_FETCH_ORGANIZATIONS = 'FAILURE_FETCH_ORGANIZATIONS'
const initialState = {
loaded: false,
editing: false,
data: []
}
export default function organizations(state = initialState, action) {
switch (action.type) {
case REQUEST_FETCH_ORGANIZATIONS:
return {...state, loaded: false}
case SUCCESS_FETCH_ORGANIZATIONS:
return {...state, data: action.result, loaded: true}
case FAILURE_FETCH_ORGANIZATIONS:
return {...state, loaded: true}
default:
return state
}
}
export function isOrganizationsLoaded(globalState) {
return globalState.organizations.loaded
}
export function fetchOrganizations() {
return {
types: [REQUEST_FETCH_ORGANIZATIONS, SUCCESS_FETCH_ORGANIZATIONS, FAILURE_FETCH_ORGANIZATIONS],
promise: function() {
return new Promise(function(resolve, reject) {
superagent.get(`${process.env.API_URL}/organizations`)
.end((err, res) => {
if (err) {
reject(res.body || err)
} else {
resolve(res.body)
}
})
})
}
}
}
|
JavaScript
| 0 |
@@ -33,112 +33,50 @@
nt'%0A
-%0Aconst REQUEST_FETCH_ORGANIZATIONS = 'REQUEST_FETCH_ORGANIZATIONS'%0Aconst SUCCESS_FETCH_ORGANIZATIONS = '
+import %7B%0A REQUEST_FETCH_ORGANIZATIONS,%0A
SUCC
@@ -102,15 +102,11 @@
IONS
-'%0Aconst
+,%0A
FAI
@@ -133,42 +133,54 @@
IONS
- = 'FAILURE_FETCH_ORGANIZATIONS'%0A%0A
+%0A%7D from './../constants/ActionTypes'%0A%0A%0Aexport
cons
@@ -313,16 +313,21 @@
, action
+ = %7B%7D
) %7B%0A sw
@@ -391,32 +391,33 @@
:%0A return %7B
+
...state, loaded
@@ -401,32 +401,40 @@
turn %7B ...state,
+%0A
loaded: false%7D%0A
@@ -431,16 +431,23 @@
d: false
+%0A
%7D%0A ca
@@ -484,32 +484,33 @@
:%0A return %7B
+
...state, data:
@@ -502,16 +502,24 @@
..state,
+%0A
data: a
@@ -531,16 +531,24 @@
.result,
+%0A
loaded:
@@ -548,24 +548,31 @@
loaded: true
+%0A
%7D%0A case F
@@ -613,16 +613,17 @@
return %7B
+
...state
@@ -623,16 +623,24 @@
..state,
+%0A
loaded:
@@ -644,16 +644,23 @@
ed: true
+%0A
%7D%0A de
@@ -741,16 +741,21 @@
balState
+ = %7B%7D
) %7B%0A re
@@ -758,16 +758,48 @@
return
+ !!(globalState.organizations &&
globalS
@@ -823,16 +823,17 @@
s.loaded
+)
%0A%7D%0A%0Aexpo
@@ -890,16 +890,23 @@
types: %5B
+%0A
REQUEST_
@@ -925,16 +925,22 @@
ZATIONS,
+%0A
SUCCESS
@@ -960,16 +960,22 @@
ZATIONS,
+%0A
FAILURE
@@ -994,16 +994,21 @@
IZATIONS
+%0A
%5D,%0A p
|
006b56aa6897b075aeafc004e2883812ee5e7006
|
Clean up
|
src/KeyboardPrefixSelectionMixin.js
|
src/KeyboardPrefixSelectionMixin.js
|
import * as symbols from './symbols.js';
import { TYPING_TIMEOUT_DURATION } from './constants.js';
// Symbols for private data members on an element.
const typedPrefixKey = Symbol('typedPrefix');
const prefixTimeoutKey = Symbol('prefixTimeout');
/**
* Mixin that handles list box-style prefix typing, in which the user can type
* a string to select the first item that begins with that string.
*
* Example: suppose a component using this mixin has the following items:
*
* <sample-list-component>
* <div>Apple</div>
* <div>Apricot</div>
* <div>Banana</div>
* <div>Blackberry</div>
* <div>Blueberry</div>
* <div>Cantaloupe</div>
* <div>Cherry</div>
* <div>Lemon</div>
* <div>Lime</div>
* </sample-list-component>
*
* If this component receives the focus, and the user presses the "b" or "B"
* key, the "Banana" item will be selected, because it's the first item that
* matches the prefix "b". (Matching is case-insensitive.) If the user now
* presses the "l" or "L" key quickly, the prefix to match becomes "bl", so
* "Blackberry" will be selected.
*
* The prefix typing feature has a one second timeout — the prefix to match
* will be reset after a second has passed since the user last typed a key.
* If, in the above example, the user waits a second between typing "b" and
* "l", the prefix will become "l", so "Lemon" would be selected.
*
* This mixin expects the component to invoke a `keydown` method when a key is
* pressed. You can use [KeyboardMixin](KeyboardMixin) for that
* purpose, or wire up your own keyboard handling and call `keydown` yourself.
*
* This mixin also expects the component to provide an `items` property. The
* `textContent` of those items will be used for purposes of prefix matching.
*
* @module KeyboardPrefixSelectionMixin
*/
export default function KeyboardPrefixSelectionMixin(Base) {
// The class prototype added by the mixin.
class KeyboardPrefixSelection extends Base {
constructor() {
// @ts-ignore
super();
resetTypedPrefix(this);
}
get defaultState() {
return Object.assign({}, super.defaultState, {
itemsForTexts: null,
texts: null
});
}
// Default implementation returns an item's `alt` attribute or its
// `textContent`, in that order.
[symbols.getItemText](item) {
return item.getAttribute('alt') || item.textContent;
}
[symbols.keydown](event) {
let handled;
let resetPrefix;
switch (event.key) {
case 'Backspace':
handleBackspace(this);
handled = true;
resetPrefix = false;
break;
case 'Escape':
// Pressing Escape lets user quickly start typing a new prefix.
resetPrefix = true;
break;
default:
if (!event.ctrlKey && !event.metaKey && !event.altKey &&
event.key !== ' ') {
handlePlainCharacter(this, String.fromCharCode(event.keyCode));
}
resetPrefix = false;
}
if (resetPrefix) {
resetTypedPrefix(this);
}
// Prefer mixin result if it's defined, otherwise use base result.
return handled || (super[symbols.keydown] && super[symbols.keydown](event));
}
refineState(state) {
let result = super.refineState ? super.refineState(state) : true;
const items = state.items || null;
const itemsChanged = items !== state.itemsForTexts;
if (itemsChanged) {
const texts = getTextsForItems(this, items);
Object.freeze(texts);
Object.assign(state, {
texts,
itemsForTexts: items
});
result = false;
}
return result;
}
/**
* Select the first item whose text content begins with the given prefix.
*
* @param {string} prefix - The prefix string to search for
* @returns {boolean}
*/
selectItemWithTextPrefix(prefix) {
if (super.selectItemWithTextPrefix) { super.selectItemWithTextPrefix(prefix); }
if (prefix == null || prefix.length === 0) {
return false;
}
const selectedIndex = getIndexOfTextWithPrefix(this.state.texts, prefix);
if (selectedIndex >= 0) {
const previousIndex = this.selectedIndex;
this.setState({ selectedIndex });
return this.selectedIndex !== previousIndex;
} else {
return false;
}
}
}
return KeyboardPrefixSelection;
}
// Return the index of the first item with the given prefix, else -1.
function getIndexOfTextWithPrefix(texts, prefix) {
const prefixLength = prefix.length;
for (let i = 0; i < texts.length; i++) {
const itemTextContent = texts[i];
if (itemTextContent.substr(0, prefixLength) === prefix) {
return i;
}
}
return -1;
}
// Return an array of the text content (in lowercase) of all items.
function getTextsForItems(component, items) {
const texts = Array.prototype.map.call(items, item => {
const text = component[symbols.getItemText](item);
return text.toLowerCase();
});
return texts;
}
// Handle the Backspace key: remove the last character from the prefix.
function handleBackspace(element) {
const length = element[typedPrefixKey] ? element[typedPrefixKey].length : 0;
if (length > 0) {
element[typedPrefixKey] = element[typedPrefixKey].substr(0, length - 1);
}
element.selectItemWithTextPrefix(element[typedPrefixKey]);
setPrefixTimeout(element);
}
// Add a plain character to the prefix.
function handlePlainCharacter(element, char) {
const prefix = element[typedPrefixKey] || '';
element[typedPrefixKey] = prefix + char.toLowerCase();
element.selectItemWithTextPrefix(element[typedPrefixKey]);
setPrefixTimeout(element);
}
// Stop listening for typing.
function resetPrefixTimeout(element) {
if (element[prefixTimeoutKey]) {
clearTimeout(element[prefixTimeoutKey]);
element[prefixTimeoutKey] = false;
}
}
// Clear the prefix under construction.
function resetTypedPrefix(element) {
element[typedPrefixKey] = '';
resetPrefixTimeout(element);
}
// Wait for the user to stop typing.
function setPrefixTimeout(element) {
resetPrefixTimeout(element);
element[prefixTimeoutKey] = setTimeout(() => {
resetTypedPrefix(element);
}, TYPING_TIMEOUT_DURATION);
}
|
JavaScript
| 0.000002 |
@@ -2508,31 +2508,8 @@
led;
-%0A let resetPrefix;
%0A%0A
@@ -2622,39 +2622,8 @@
ue;%0A
- resetPrefix = false;%0A
@@ -2752,21 +2752,25 @@
eset
+Typed
Prefix
- = true
+(this)
;%0A
@@ -2976,24 +2976,24 @@
.keyCode));%0A
+
%7D%0A
@@ -2996,105 +2996,8 @@
%7D%0A
- resetPrefix = false;%0A %7D%0A%0A if (resetPrefix) %7B%0A resetTypedPrefix(this);%0A
|
aa81c0aa3fb9760a0ef1445f760a62466b78b9d3
|
Build failes when git is not initialized (e.g. zip download)
|
gulpfile.babel.js
|
gulpfile.babel.js
|
import autoprefixer from 'gulp-autoprefixer'
import babel from 'rollup-plugin-babel'
import buffer from 'vinyl-buffer'
import cleanCSS from 'gulp-clean-css'
import clone from 'gulp-clone'
import commonJs from 'rollup-plugin-commonjs'
import concat from 'gulp-concat'
import del from 'del'
import esdoc from 'gulp-esdoc-stream'
import gulp from 'gulp'
import header from 'gulp-header'
import mergeStream from 'merge-stream'
import mocha from 'gulp-mocha'
import nodeResolve from 'rollup-plugin-node-resolve'
import rename from 'gulp-rename'
import revision from 'git-rev-sync'
import rollup from 'rollup-stream'
import sass from 'gulp-sass'
import sassSVGInliner from 'sass-inline-svg'
import source from 'vinyl-source-stream'
import sourcemaps from 'gulp-sourcemaps'
import standard from 'gulp-standard'
import uglify from 'gulp-uglify'
let meta = require('./package.json')
let distHeader =
`/*! ${meta.name} v${meta.version} (commit ${revision.long()})` +
` - (c) ${meta.author} */\n`
let paths = {
assets: './assets',
script: './src',
scriptDist: './public/dist/script',
style: './style',
styleDist: './public/dist/style',
test: './test',
doc: './public/docs',
}
gulp.task('lint-test', () => {
return gulp.src(paths.test + '/**/*.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true,
quiet: true
}))
})
gulp.task('lint-script', () => {
return gulp.src(paths.script + '/**/*.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true,
quiet: true
}))
})
gulp.task('test', ['lint-test', 'lint-script'], () => {
return gulp.src(paths.test + '/**/*.js', { read: false })
.pipe(mocha({
reporter: 'spec',
compilers: [
'js:babel-core/register'
]
}))
})
gulp.task('doc', ['clean-doc'], () => {
return gulp.src(paths.script + '/**/*.js')
.pipe(esdoc({
destination: paths.doc,
title: 'Cryptii',
test: {
type: 'mocha',
source: paths.test,
includes: ['.js$'],
}
}))
})
let rollupCache
gulp.task('script', ['lint-script', 'clean-script'], () => {
let appStream = rollup({
input: paths.script + '/index.js',
external: [
],
plugins: [
babel({
babelrc: false,
presets: [
['env', {
loose: true,
modules: false
}]
],
plugins: [
'external-helpers',
['babel-plugin-transform-builtin-extend', {
globals: ['Error']
}]
],
exclude: ['node_modules/**']
}),
nodeResolve({
jsnext: true,
main: true
}),
commonJs({
include: ['node_modules/**']
})
],
format: 'umd',
sourcemap: true,
cache: rollupCache,
amd: { id: meta.name }
})
appStream = appStream
// enable rollup cache
.on('bundle', (bundle) => {
rollupCache = bundle
})
// handle errors gracefully
.on('error', err => {
console.error(err.message)
if (err.codeFrame !== undefined) {
console.error(err.codeFrame)
}
stream.emit('end')
})
// set output filename
.pipe(source(`${meta.name}.js`, paths.src))
// buffer the output
.pipe(buffer())
// init sourcemaps with inline sourcemap produced by rollup-stream
.pipe(sourcemaps.init({
loadMaps: true
}))
// minify code
.pipe(uglify())
// append header
.pipe(header(distHeader))
// create polyfill stream from existing files
let polyfillStream = gulp.src([
'./node_modules/dom4/build/dom4.js',
'./node_modules/babel-polyfill/dist/polyfill.min.js'
], { base: '.' })
.pipe(sourcemaps.init())
// compose library bundle
let libraryBundleStream = appStream.pipe(clone())
// render sourcemaps
.pipe(sourcemaps.write('.'))
// compose browser bundle
let browserBundleStream = mergeStream(polyfillStream, appStream)
// concat polyfill and library
.pipe(concat(`${meta.name}-browser.js`))
// render sourcemaps
.pipe(sourcemaps.write('.'))
// save bundles and sourcemaps
return mergeStream(libraryBundleStream, browserBundleStream)
.pipe(gulp.dest(paths.scriptDist))
})
gulp.task('style', ['clean-style'], () => {
return gulp.src(paths.style + '/main.scss')
// init sourcemaps
.pipe(sourcemaps.init())
// compile sass to css
.pipe(
sass({
includePaths: ['node_modules'],
outputStyle: 'expanded',
functions: {
'inline-svg': sassSVGInliner(paths.assets)
}
})
.on('error', sass.logError)
)
// autoprefix css
.pipe(autoprefixer('last 2 version', 'ie 11', '> 1%'))
// minify
.pipe(cleanCSS({ processImport: false }))
// append header
.pipe(header(distHeader))
// save result
.pipe(rename(meta.name + '.css'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest(paths.styleDist))
})
gulp.task('clean-style', () => {
return del([paths.styleDist])
})
gulp.task('clean-script', () => {
return del([paths.scriptDist])
})
gulp.task('clean-doc', () => {
return del([paths.doc])
})
gulp.task('watch', () => {
// watch scripts and tests
gulp.watch(
[paths.script + '/**/*.js', paths.test + '/**/*.js'],
['test', 'script'])
// watch styles
gulp.watch(
paths.style + '/**/*.scss',
['style'])
})
gulp.task('build', ['script', 'style', 'doc'])
gulp.task('default', ['test', 'script', 'style', 'watch'])
|
JavaScript
| 0 |
@@ -873,125 +873,8 @@
n')%0A
-let distHeader =%0A %60/*! $%7Bmeta.name%7D v$%7Bmeta.version%7D (commit $%7Brevision.long()%7D)%60 +%0A %60 - (c) $%7Bmeta.author%7D */%5Cn%60%0A%0A
let
@@ -883,16 +883,16 @@
ths = %7B%0A
+
assets
@@ -1064,11 +1064,289 @@
s',%0A
-
%7D%0A%0A
+// try to retrieve current commit hash%0Alet distRevision%0Atry %7B%0A distRevision = revision.long()%0A%7D catch (evt) %7B%0A distRevision = 'unknown'%0A%7D%0A%0A// compose dist header%0Alet distHeader =%0A %60/*! $%7Bmeta.name%7D v$%7Bmeta.version%7D (commit $%7BdistRevision%7D)%60 +%0A %60 - (c) $%7Bmeta.author%7D */%5Cn%60%0A%0A
gulp
|
174577ac1c33d039e2f6e0de5d36973dbaa69357
|
remove logging
|
storymap.js
|
storymap.js
|
(function ($) {
'use strict';
$.fn.storymap = function(options) {
var defaults = {
selector: '[data-place]',
breakpointPos: '33.333%',
createMap: function () {
// create a map in the "map" div, set the view to a given place and zoom
var map = L.map('map').setView([65, 18], 5);
// add an OpenStreetMap tile layer
L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
attribution: '© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
}).addTo(map);
return map;
},
markerOptions: {
radius: 5,
color: '#de2d26'
},
clustering: true
};
var settings = $.extend(defaults, options);
if (typeof(L) === 'undefined') {
throw new Error('Storymap requires Laeaflet');
}
if (typeof(_) === 'undefined') {
throw new Error('Storymap requires underscore.js');
}
function getDistanceToTop(elem, top) {
var docViewTop = $(window).scrollTop();
var elemTop = $(elem).offset().top;
var dist = elemTop - docViewTop;
var d1 = top - dist;
if (d1 < 0) {
return $(document).height();
}
return d1;
}
function highlightTopPara(paragraphs, top) {
var distances = _.map(paragraphs, function (element) {
var dist = getDistanceToTop(element, top);
return {el: $(element), distance: dist};
});
var closest = _.min(distances, function (dist) {
return dist.distance;
});
_.each(paragraphs, function (element) {
var paragraph = $(element);
if (paragraph[0] !== closest.el[0]) {
paragraph.trigger('notviewing');
}
});
if (!closest.el.hasClass('viewing')) {
closest.el.trigger('viewing');
}
}
function watchHighlight(element, searchfor, top) {
var paragraphs = element.find(searchfor);
highlightTopPara(paragraphs, top);
$(window).scroll(function () {
highlightTopPara(paragraphs, top);
});
}
var makeStoryMap = function (element, markers, markerOptions) {
var topElem = $('<div class="breakpoint-current"></div>')
.css('top', settings.breakpointPos);
$('body').append(topElem);
var top = topElem.offset().top - $(window).scrollTop();
var searchfor = settings.selector;
var paragraphs = element.find(searchfor);
paragraphs.on('viewing', function () {
$(this).addClass('viewing');
});
paragraphs.on('notviewing', function () {
$(this).removeClass('viewing');
});
watchHighlight(element, searchfor, top);
var map = settings.createMap();
var initPoint = map.getCenter();
var initZoom = map.getZoom();
var fg = L.featureGroup().addTo(map);
var clusteredMarkers = L.markerClusterGroup({
showCoverageOnHover: false,
maxClusterRadius: 50
});
function showMapView(key) {
fg.clearLayers();
clusteredMarkers.clearLayers();
if (key === 'overview') {
map.setView(initPoint, initZoom, true);
} else if (markers[key]) {
var marker = markers[key];
var center = marker.center;
var photos = marker.photos;
var layer = marker.layer;
if(typeof layer !== 'undefined'){
fg.addLayer(layer);
};
// change to circleMarker so marker is more easily customized
//fg.addLayer(L.circleMarker([center.lat, center.lon], markerOptions));
// add photos
for (var i = 0; i < photos.length; i++) {
console.log(settings.clustering);
if (settings.clustering == true) {
clusteredMarkers.addLayer(L.circleMarker([photos[i].lat, photos[i].lon], markerOptions)
.bindTooltip("<img class='tooltip-image' src='"+photos[i].url+"'>"));
fg.addLayer(clusteredMarkers);
} else {
fg.addLayer(L.circleMarker([photos[i].lat, photos[i].lon], markerOptions)
.bindTooltip("<img class='tooltip-image' src='"+photos[i].url+"'>"));
}
}
map.setView([center.lat, center.lon], center.zoom, 1);
}
}
paragraphs.on('viewing', function () {
showMapView($(this).data('place'));
});
};
makeStoryMap(this, settings.markers, settings.markerOptions);
return this;
}
}(jQuery));
|
JavaScript
| 0.000001 |
@@ -4357,41 +4357,8 @@
-console.log(settings.clustering);
%0A
|
f020d2975cd310e14e68a0a2689245aee82630de
|
copy json files to build
|
gulpfile.babel.js
|
gulpfile.babel.js
|
// Import the neccesary modules.
import del from 'del';
import gulp from 'gulp';
import babel from 'gulp-babel';
/**
* The default build function.
* @returns {void}
*/
function build() {
gulp.src('src/**/*.js').pipe(babel()).pipe(gulp.dest('build'));
}
// Delete the `build` directory.
gulp.task('clean', () => del(['build']));
// Transpile the `src` directory with Babel.
gulp.task('build', ['clean'], build);
// Watch the `src` directory and build when a file changes.
gulp.task('watch', ['build'], () => gulp.watch('src/**/*.js', ['build']));
// Set the default task as `build`.
gulp.task('default', ['clean'], build);
|
JavaScript
| 0 |
@@ -250,16 +250,70 @@
ild'));%0A
+ gulp.src('src/**/*.json').pipe(gulp.dest('build'));%0A
%7D%0A%0A// De
|
bf8143a8480c4ef1bf96686a13fed5744a364e6e
|
Use IE11 on Windows 7 people using Windows 10 will use Edge, as it's advertised everwhere inside IE anyhow. And on Windows 8.1 and above, IE11 has a bit more abilities regarding MSE, so we want to test the vanilla one.
|
karma.conf.js
|
karma.conf.js
|
// Karma configuration
// Generated on Sun Jun 18 2017 16:28:13 GMT+0300 (Jerusalem Daylight Time)
const webpack = require('./webpack.config');
const { testGlob } = require('./package.json');
const sauceLabsLaunchers = { // Check out https://saucelabs.com/platforms for all browser/platform combos
slChrome: {
base: 'SauceLabs',
browserName: 'chrome'
},
slFirefox: {
base: 'SauceLabs',
browserName: 'firefox'
},
slEdge15: {
base: 'SauceLabs',
platform: 'Windows 10',
browserName: 'MicrosoftEdge',
version: '15.15063'
},
slIE11: {
base: 'SauceLabs',
platform: 'Windows 10',
browserName: 'internet explorer',
version: '11.103'
},
slIE10: {
base: 'SauceLabs',
platform: 'Windows 7',
browserName: 'internet explorer',
version: '10.0'
},
slSafari10: {
base: 'SauceLabs',
platform: 'macOS 10.12',
browserName: 'safari',
version: '10.0'
},
slSafari9: {
base: 'SauceLabs',
platform: 'OS X 10.11',
browserName: 'safari',
version: '9.0'
},
slAndroid5: {
base: 'SauceLabs',
browserName: 'Android',
version: '5.1'
},
slAndroid4: {
base: 'SauceLabs',
browserName: 'Android',
version: '4.4'
}
};
module.exports = function (config) {
config.set({
// this key is used by karma-webpack, see preprocessors below
webpack,
// the default mime type for ts files is video/mp2t, which Chrome won't execute, so force correct mime type
mime: {
"text/x-typescript": ["ts", "tsx"],
},
customLaunchers: sauceLabsLaunchers,
sauceLabs: {
startConnect: false,
build: 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')',
tunnelIdentifier: process.env.TRAVIS_JOB_NUMBER,
},
captureTimeout: 120000,
browserNoActivityTimeout: 25000,
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['mocha'],
// list of files / patterns to load in the browser
files: [
'./node_modules/core-js/client/shim.min.js',
testGlob
],
// list of files to exclude
exclude: [
],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
[testGlob]: ['webpack']
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: process.env.TRAVIS ? ['dots', 'saucelabs'] : ['dots'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: process.env.TRAVIS_BRANCH === 'master' && !process.env.TRAVIS_PULL_REQUEST ?
Object.keys(sauceLabsLaunchers) :
['Chrome'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity
})
}
|
JavaScript
| 0 |
@@ -663,34 +663,33 @@
tform: 'Windows
-10
+7
',%0A brows
@@ -742,11 +742,9 @@
'11.
-103
+0
'%0A
|
9644de9aa3e707f002d36268602887ea77952f46
|
Use etag
|
lib/web/middleware/static.js
|
lib/web/middleware/static.js
|
// Copyright, 2013-2014, by Tomas Korcak. <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
(function () {
'use strict';
var define = require('amdefine')(module);
/**
* Array of modules this one depends on.
* @type {Array}
*/
var deps = [
'../../../config',
'express'
];
define(deps, function (config, express) {
function MiddlewareStatic(web) {
this.web = web;
this.app = web.app;
// Set static assets dir
this.app.use(express.static(this.web.publicDir));
}
module.exports = MiddlewareStatic;
});
}());
|
JavaScript
| 0 |
@@ -1610,16 +1610,57 @@
icDir));
+%0A%0A this.app.set('etag', true);
%0A
|
9eef346a68a08b4e3d1bd50670a262c45fc8d479
|
Switch back to headless Chrome in tests
|
karma.conf.js
|
karma.conf.js
|
module.exports = config => {
config.set({
// define browsers
customLaunchers: {
ChromeHeadlessNoSandbox: {
base: "ChromeHeadless",
flags: ["--no-sandbox"]
}
},
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ["Chrome"],
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: "./",
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ["mocha"],
// list of files / patterns to load in the browser
files: [
"node_modules/@babel/polyfill/dist/polyfill.min.js",
"node_modules/console-polyfill/index.js",
"tests/input/*.js"
],
// list of files to exclude
exclude: ["karma.conf.js"],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
"tests/input/*.js": ["webpack"]
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ["progress"],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: false,
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
webpack: {
devtool: false,
performance: {
hints: false
},
mode: "development",
output: {
filename: "[name].js"
},
resolve: {
modules: ["node_modules", "."]
},
module: require("./webpack.config").module
}
});
};
|
JavaScript
| 0.000001 |
@@ -330,16 +330,33 @@
%5B%22Chrome
+HeadlessNoSandbox
%22%5D,%0A%0A
@@ -1784,20 +1784,19 @@
gleRun:
-fals
+tru
e,%0A%0A
|
9abe48d9f5e1338b1d6ef880a33e6ee6258dac57
|
change CRLF to LF
|
gulpfile.babel.js
|
gulpfile.babel.js
|
import gulp from 'gulp'
import babel from 'gulp-babel'
import eslint from 'gulp-eslint'
import path from 'path'
import chmod from 'gulp-chmod'
import watch from 'gulp-watch'
import del from 'del'
const src = path.join(__dirname, 'src/**/*.js')
const dist = path.join(__dirname, 'dist')
const binSrc = path.join(__dirname, 'bin/*')
gulp.task('trans', () => {
gulp.src(src)
.pipe(babel())
.pipe(gulp.dest(dist))
})
gulp.task('lint', () => {
gulp.src(src)
.pipe(eslint())
.pipe(eslint.format())
// .pipe(eslint.failAfterError())
})
gulp.task('bin', () => {
gulp.src(binSrc)
.pipe(babel())
.pipe(chmod(0o755))
.pipe(gulp.dest(path.join(dist, 'bin')))
})
gulp.task('clean', (cb) => del([dist], cb))
gulp.task('watch', () => {
watch(src, () => gulp.start(['lint', 'trans']))
watch(binSrc, () => gulp.start('bin'))
})
gulp.task('build', ['clean'], () => {
gulp.start(['lint', 'trans', 'bin'])
})
gulp.task('default', ['build'])
|
JavaScript
| 0.003203 |
@@ -16,17 +16,16 @@
m 'gulp'
-%0D
%0Aimport
@@ -47,17 +47,16 @@
p-babel'
-%0D
%0Aimport
@@ -80,17 +80,16 @@
-eslint'
-%0D
%0Aimport
@@ -104,17 +104,16 @@
m 'path'
-%0D
%0Aimport
@@ -135,17 +135,16 @@
p-chmod'
-%0D
%0Aimport
@@ -166,17 +166,16 @@
p-watch'
-%0D
%0Aimport
@@ -188,19 +188,17 @@
om 'del'
-%0D%0A%0D
+%0A
%0Aconst s
@@ -237,17 +237,16 @@
*/*.js')
-%0D
%0Aconst d
@@ -279,17 +279,16 @@
'dist')
-%0D
%0Aconst b
@@ -324,19 +324,17 @@
'bin/*')
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -344,33 +344,32 @@
'trans', () =%3E %7B
-%0D
%0A gulp.src(src)
@@ -360,33 +360,32 @@
%0A gulp.src(src)
-%0D
%0A .pipe(babel
@@ -379,33 +379,32 @@
.pipe(babel())
-%0D
%0A .pipe(gulp.
@@ -414,23 +414,20 @@
t(dist))
-%0D
%0A%7D)
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -436,33 +436,32 @@
('lint', () =%3E %7B
-%0D
%0A gulp.src(src)
@@ -460,17 +460,16 @@
src(src)
-%0D
%0A .pi
@@ -476,25 +476,24 @@
pe(eslint())
-%0D
%0A .pipe(e
@@ -507,17 +507,16 @@
ormat())
-%0D
%0A //
@@ -545,23 +545,20 @@
Error())
-%0D
%0A%7D)
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -566,33 +566,32 @@
k('bin', () =%3E %7B
-%0D
%0A gulp.src(binS
@@ -593,17 +593,16 @@
(binSrc)
-%0D
%0A .pi
@@ -612,17 +612,16 @@
babel())
-%0D
%0A .pi
@@ -636,17 +636,16 @@
(0o755))
-%0D
%0A .pi
@@ -681,23 +681,20 @@
'bin')))
-%0D
%0A%7D)
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -729,19 +729,17 @@
t%5D, cb))
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -757,17 +757,16 @@
() =%3E %7B
-%0D
%0A watch
@@ -807,17 +807,16 @@
rans'%5D))
-%0D
%0A watch
@@ -848,23 +848,20 @@
('bin'))
-%0D
%0A%7D)
-%0D%0A%0D
+%0A
%0Agulp.ta
@@ -890,17 +890,16 @@
() =%3E %7B
-%0D
%0A gulp.
@@ -933,15 +933,12 @@
n'%5D)
-%0D
%0A%7D)
-%0D%0A%0D
+%0A
%0Agul
@@ -969,6 +969,5 @@
d'%5D)
-%0D
%0A
|
5492026544b8a483dc91fb4327f3aa3727942026
|
Update karma.conf.js to load outline.js
|
karma.conf.js
|
karma.conf.js
|
// Karma configuration
'use strict'
module.exports = (config) => {
config.set({
// base path that will be used to resolve all patterns (eg. files, exclude)
basePath: '',
// frameworks to use
// available frameworks: https://npmjs.org/browse/keyword/karma-adapter
frameworks: ['jasmine'],
// list of files / patterns to load in the browser
files: [
'node_modules/adler32cs/adler32cs.js',
'libs/deflate.js',
'libs/html2canvas/dist/html2canvas.js',
'jspdf.js',
'plugins/acroform.js',
'plugins/annotations.js',
'plugins/split_text_to_size.js',
'plugins/standard_fonts_metrics.js',
'plugins/autoprint.js',
'plugins/addhtml.js',
'plugins/addimage.js',
'plugins/viewerpreferences.js',
'tests/utils/compare.js',
{
pattern: 'tests/**/*.spec.js',
included: true
}, {
pattern: 'tests/**/reference/*.pdf',
included: false,
served: true
}
],
// list of files to exclude
exclude: [],
// preprocess matching files before serving them to the browser
// available preprocessors: https://npmjs.org/browse/keyword/karma-preprocessor
preprocessors: {
'jspdf.js': 'coverage',
'plugins/*.js': 'coverage',
'tests/!(acroform)*/*.js': 'babel'
},
// test results reporter to use
// possible values: 'dots', 'progress'
// available reporters: https://npmjs.org/browse/keyword/karma-reporter
reporters: ['mocha', 'coverage'],
// web server port
port: 9876,
// enable / disable colors in the output (reporters and logs)
colors: true,
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_INFO,
// enable / disable watching file and executing tests whenever any file changes
autoWatch: true,
// start these browsers
// available browser launchers: https://npmjs.org/browse/keyword/karma-launcher
browsers: ['Chrome', 'Firefox'],
// Continuous Integration mode
// if true, Karma captures browsers, runs the tests and exits
singleRun: false,
// Concurrency level
// how many browser should be started simultaneous
concurrency: Infinity,
coverageReporter: {
reporters: [
{
type: 'lcov',
dir: 'coverage/'
},
{
type: 'text'
}
]
},
babelPreprocessor: {
options: {
presets: ['es2015'],
sourceMap: 'inline'
}
}
})
}
|
JavaScript
| 0.000001 |
@@ -775,16 +775,44 @@
ces.js',
+%0A 'plugins/outline.js',
%0A%0A
|
5a4b99f631b658c32596b5c768929bb833493abf
|
Set proxy when downloading node
|
script/download-node.js
|
script/download-node.js
|
#!/usr/bin/env node
var fs = require('fs');
var mv = require('mv');
var zlib = require('zlib');
var path = require('path');
var request = require('request');
var tar = require('tar');
var temp = require('temp');
temp.track();
var downloadFileToLocation = function(url, filename, callback) {
var stream = fs.createWriteStream(filename);
stream.on('end', callback);
stream.on('error', callback);
return request(url).pipe(stream);
};
var downloadTarballAndExtract = function(url, location, callback) {
var tempPath = temp.mkdirSync('apm-node-');
var stream = tar.Extract({
path: tempPath
});
stream.on('end', callback.bind(this, tempPath));
stream.on('error', callback);
return request(url).pipe(zlib.createGunzip()).pipe(stream);
};
var copyNodeBinToLocation = function(callback, version, targetFilename, fromDirectory) {
var arch = process.arch === 'ia32' ? 'x86' : process.arch;
var subDir = "node-" + version + "-" + process.platform + "-" + arch;
var fromPath = path.join(fromDirectory, subDir, 'bin', 'node');
return mv(fromPath, targetFilename, function(err) {
if (err) {
callback(err);
return;
}
fs.chmod(targetFilename, "755", callback);
});
};
var downloadNode = function(version, done) {
var arch, downloadURL, filename;
if (process.platform === 'win32') {
arch = process.arch === 'x64' ? 'x64/' : '';
downloadURL = "http://nodejs.org/dist/" + version + "/" + arch + "node.exe";
filename = path.join('bin', "node.exe");
} else {
arch = process.arch === 'ia32' ? 'x86' : process.arch;
downloadURL = "http://nodejs.org/dist/" + version + "/node-" + version + "-" + process.platform + "-" + arch + ".tar.gz";
filename = path.join('bin', "node");
}
if (fs.existsSync(filename)) {
done();
return;
}
if (process.platform === 'win32') {
return downloadFileToLocation(downloadURL, filename, done);
} else {
var next = copyNodeBinToLocation.bind(this, done, version, filename);
return downloadTarballAndExtract(downloadURL, filename, next);
}
};
downloadNode('v0.10.26', function(error) {
if (error != null) {
console.error('Failed to download node', error);
return process.exit(1);
} else {
return process.exit(0);
}
});
|
JavaScript
| 0 |
@@ -678,32 +678,137 @@
or', callback);%0A
+ var requestOptions = %7B%0A url: url,%0A proxy: process.env.http_proxy %7C%7C process.env.https_proxy%0A %7D;%0A
return request
@@ -804,27 +804,38 @@
urn request(
-url
+requestOptions
).pipe(zlib.
|
705aaa70c674b2676331db978edb3a30514cabea
|
Add xors to desolve
|
libglitch/modules/desolve.js
|
libglitch/modules/desolve.js
|
const defaults = require('../lib/defaults');
const randint = require('../lib/rand').randint;
const p = require('../param');
function desolve(glitchContext, options) {
options = defaults(options, desolve.paramDefaults);
const imageData = glitchContext.getImageData();
const {data, height, width} = imageData;
const xRes = randint(options.xMin % width, options.xMax % width);
const yRes = randint(options.yMin % height, options.yMax % height);
for (let y = 0; y < height; y += yRes) {
for (let x = 0; x < width; x += xRes) {
const srcOffset = y * 4 * width + x * 4;
for (let yo = 0; yo < yRes; yo++) {
for (let xo = 0; xo < xRes; xo++) {
const dx = x + xo;
const dy = y + yo;
if (dx >= 0 && dy >= 0 && dx < width && dy < height) {
const dstOffset = dy * 4 * width + dx * 4;
data[dstOffset] = data[srcOffset];
data[dstOffset + 1] = data[srcOffset + 1];
data[dstOffset + 2] = data[srcOffset + 2];
}
}
}
}
}
glitchContext.setImageData(imageData);
}
desolve.paramDefaults = {
xMin: 1,
xMax: 4,
yMin: 1,
yMax: 4,
};
desolve.params = [
p.int('xMax', {min: 1, max: 800}),
p.int('xMin', {min: 1, max: 800}),
p.int('yMax', {min: 1, max: 800}),
p.int('yMin', {min: 1, max: 800}),
];
module.exports = desolve;
|
JavaScript
| 0.000005 |
@@ -43,24 +43,31 @@
);%0Aconst
+ %7Brand,
randint
= requi
@@ -58,16 +58,17 @@
randint
+%7D
= requi
@@ -88,16 +88,8 @@
nd')
-.randint
;%0Aco
@@ -446,16 +446,63 @@
eight);%0A
+ const op = (a, b, xor) =%3E (xor ? a %5E b : b);%0A
for (l
@@ -623,24 +623,174 @@
th + x * 4;%0A
+ const rXor = (rand() %3C options.rXorChance);%0A const gXor = (rand() %3C options.gXorChance);%0A const bXor = (rand() %3C options.bXorChance);%0A
for (l
@@ -1070,16 +1070,36 @@
ffset%5D =
+ op(data%5BdstOffset%5D,
data%5Bsr
@@ -1106,16 +1106,23 @@
cOffset%5D
+, rXor)
;%0A
@@ -1148,16 +1148,40 @@
t + 1%5D =
+ op(data%5BdstOffset + 1%5D,
data%5Bsr
@@ -1192,16 +1192,23 @@
set + 1%5D
+, gXor)
;%0A
@@ -1234,16 +1234,40 @@
t + 2%5D =
+ op(data%5BdstOffset + 2%5D,
data%5Bsr
@@ -1278,16 +1278,23 @@
set + 2%5D
+, bXor)
;%0A
@@ -1441,16 +1441,67 @@
Max: 4,%0A
+ rXorChance: 0,%0A gXorChance: 0,%0A bXorChance: 0,%0A
%7D;%0A%0Adeso
@@ -1618,32 +1618,32 @@
1, max: 800%7D),%0A
-
p.int('yMin',
@@ -1663,16 +1663,85 @@
800%7D),%0A
+ p.num('rXorChance'),%0A p.num('gXorChance'),%0A p.num('bXorChance'),%0A
%5D;%0A%0Amodu
|
47842b6383cff213a046db7ed510a325e5c86298
|
Add site id to file upload
|
library/CM/FormField/File.js
|
library/CM/FormField/File.js
|
fileUploader: null,
ready: function() {
var field = this;
this.fileUploader = new qq.FileUploader({
element: field.$(".file-uploader").get(0),
action: "/upload/?field=" + field._class,
multiple: !field.getOption("cardinality") || field.getOption("cardinality") > 1,
allowedExtensions: field.getOption("allowedExtensions"),
template: field.$(".file-uploader").html(),
fileTemplate: $.trim(field.$(".previewsTemplate").html()),
listElement: field.$(".previews").get(0),
onComplete: function(id, fileName, response) {
var $item = field.$(".previews").children().filter(function(i) {
return this.qqFileId == id;
});
if (response.success) {
this.showMessage(null);
while (field.getOption("cardinality") && field.getOption("cardinality") < field.getCountUploaded()) {
$item.siblings().first().remove();
}
$item.html(response.success.preview + "<input type=\"hidden\" name=\"" +field.getName()+ "[]\" value=\"" +response.success.id+ "\"/>");
} else {
$item.remove();
}
if (field.fileUploader.getInProgress() == 0 && field.getCountUploaded() > 0) {
field.trigger("uploadComplete");
}
},
showMessage: function(message) {
if (message && message.msg) {
message = message.msg;
}
field.error(message);
}
});
this.$(".previews").on("click", ".delete", function() {
$(this).parent("li").remove();
});
},
getCountUploaded: function() {
return this.$(".previews .qq-upload-success").length;
}
|
JavaScript
| 0 |
@@ -162,16 +162,42 @@
/upload/
+%22 + cm.options.siteId + %22/
?field=%22
|
3e52dc0a678b910444058c5e9f0b81fa1df3c37b
|
Fix bad typo
|
src/organisms/cards/SelectCard/index.js
|
src/organisms/cards/SelectCard/index.js
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import SelectField from 'molecules/formfields/SelectField';
function SelectCard( props ) {
const {
className,
label,
placeholder,
selectOptions,
onClick,
input,
defaultValue,
} = props;
return (
<div className={className}
<SelectField
label={label}
placeholder={placeholder}
selectOptions={selectOptions}
input={input}
defaultValue={defaultValue}
onAdditionalInfoClick={onClick}
/>
</div>
);
}
SelectCard.propTypes = {
/**
* optional additional class name for card
*/
className: PropTypes.string,
/**
* text for footer link// Deprecated. No more footer link.
*/
footerText: PropTypes.string.isRequired,
/**
* label for select field
*/
label: PropTypes.oneOfType([
PropTypes.string,
PropTypes.object
]),
/**
* url for footer link // Deprecated. No more footer link.
*/
linkUrl: PropTypes.string,
/**
* onClick callback for footer link
*/
onClick: PropTypes.func,
/**
* placeholder for select field
*/
placeholder: PropTypes.string,
/**
* array of select options for select field
*/
selectOptions: PropTypes.array,
/**
* Redux Form input object; pass any variables necessary for input change here
*/
input: PropTypes.object,
/**
* Default / non-changeable value for the select field
*/
defaultValue: PropTypes.string
};
export default SelectCard;
|
JavaScript
| 0.999999 |
@@ -355,16 +355,17 @@
assName%7D
+%3E
%0A %3C
|
49486f59f6c43cc60ac27804e43822bc44b077a8
|
Revert spec test back to true/false
|
spec/specs.js
|
spec/specs.js
|
describe('pingPong', function() {
it("returns ping for a number that is divisible by 3", function() {
expect(pingPong(6)).to.equal("ping");
});
it("returns pong for a number that is divisible by 5", function() {
expect(pingPong(10)).to.equal("pong");
});
it("returns ping pong for a number that is divisible by 3 and 5", function() {
expect(pingPong(30)).to.equal("ping pong")
});
it("is false for a number that is not divisible by 3 or 5", function() {
expect(pingPong(8)).to.equal(false);
});
});
|
JavaScript
| 0.001596 |
@@ -41,20 +41,20 @@
returns
-ping
+true
for a n
@@ -134,14 +134,12 @@
ual(
-%22ping%22
+true
);%0A
@@ -157,20 +157,20 @@
returns
-pong
+true
for a n
@@ -251,14 +251,12 @@
ual(
-%22pong%22
+true
);%0A
@@ -274,25 +274,20 @@
returns
-ping pong
+true
for a n
@@ -374,19 +374,12 @@
ual(
-%22ping pong%22
+true
)%0A
|
66634942de79bb189590a3a98cdb5631f67b0194
|
Fix tabbing / control flow
|
discovery.js
|
discovery.js
|
var request = require("request");
/*
* DiscoveryClient constructor.
* Creates a new uninitialized DiscoveryClient.
*/
function DiscoveryClient(host, options) {
this.host = host;
this.state = {announcements: {}};
this.errorHandlers = [this._backoff.bind(this)];
this.watchers = [this._update.bind(this), this._unbackoff.bind(this)];
this.announcements = [];
this.backoff = 1;
this.logger = (options && options.logger) || require("ot-logger");
}
/* Increase the watch backoff interval */
DiscoveryClient.prototype._backoff = function () {
this.backoff = Math.min(this.backoff * 2, 10240);
}
/* Reset the watch backoff interval */
DiscoveryClient.prototype._unbackoff = function() {
this.backoff = 1;
}
DiscoveryClient.prototype._randomServer = function() {
return this.servers[Math.floor(Math.random()*this.servers.length)];
}
/* Consume a WatchResult from the discovery server and update internal state */
DiscoveryClient.prototype._update = function (update) {
var disco = this;
if (update.fullUpdate) {
Object.keys(disco.state.announcements).forEach(function (id) { delete disco.state.announcements[id]; });
}
disco.state.index = update.index;
update.deletes.forEach(function (id) { delete disco.state.announcements[id]; });
update.updates.forEach(function (announcement) { disco.state.announcements[announcement.announcementId] = announcement; });
}
/* Connect to the Discovery servers given the endpoint of any one of them */
DiscoveryClient.prototype.connect = function (onComplete) {
var disco = this;
request({
url: "http://" + this.host + "/watch",
json: true
}, function (error, response, update) {
if (error) {
onComplete(error);
}
if (response.statusCode != 200) {
onComplete(new Error("Unable to initiate discovery: " + update), undefined, undefined);
}
if (!update.fullUpdate) {
onComplete(new Error("Expecting a full update: " + update), undefined, undefined);
}
disco._update(update);
disco.servers = [];
Object.keys(disco.state.announcements).forEach(function (id) {
var announcement = disco.state.announcements[id];
if (announcement.serviceType == "discovery") {
disco.servers.push(announcement.serviceUri);
}
});
disco._schedule();
setInterval(disco._announce.bind(disco), 10000);
onComplete(undefined, disco.host, disco.servers);
});
};
/* Register a callback on every discovery update */
DiscoveryClient.prototype.onUpdate = function (watcher) {
this.watchers.push(watcher);
}
/* Register a callback on every error */
DiscoveryClient.prototype.onError = function (handler) {
this.errorHandlers.push(handler);
}
/* Internal scheduling method. Schedule the next poll in the event loop */
DiscoveryClient.prototype._schedule = function() {
var c = this.poll.bind(this);
if (this.backoff <= 1) {
setImmediate(c);
} else {
setTimeout(c, this.backoff).unref();
}
}
/* Long-poll the discovery server for changes */
DiscoveryClient.prototype.poll = function () {
var disco = this;
var server = this._randomServer();
var url = server + "/watch?since=" + (this.state.index + 1);
request({
url: url,
json: true
}, function (error, response, body) {
if (error) {
disco.errorHandlers.forEach(function (h) { h(error); });
disco._schedule();
return;
}
if (response.statusCode == 204) {
disco._schedule();
return;
}
if (response.statusCode != 200) {
var error = new Error("Bad status code " + response.statusCode + " from watch: " + response);
disco.errorHandlers.forEach(function (h) { h(error); });
disco._schedule();
return;
}
disco.watchers.forEach(function (w) { w(body); });
disco._schedule();
});
};
/* Lookup a service by service type! */
DiscoveryClient.prototype.find = function (serviceType) {
var disco = this;
var candidates = [];
Object.keys(disco.state.announcements).forEach(function (id) {
var a = disco.state.announcements[id];
if (a.serviceType == serviceType) {
candidates.push(a.serviceUri);
}
});
if (candidates.length == 0) {
return undefined;
}
return candidates[Math.floor(Math.random()*candidates.length)];
}
DiscoveryClient.prototype._announce = function() {
var disco = this;
function cb(error, announcement) {
if (error) {
disco.errorHandlers.forEach(function (h) { h(error); });
}
}
this.announcements.forEach(function (a) {
disco._singleAnnounce(a, cb);
});
}
DiscoveryClient.prototype._singleAnnounce = function (announcement, cb) {
var server = this._randomServer();
request({
url: server + "/announcement",
method: "POST",
json: true,
body: announcement
}, function (error, response, body) {
if (error) {
cb(error);
return;
}
if (response.statusCode != 201) {
cb(new Error("During announce, bad status code " + response.statusCode + ": " + body));
return;
}
cb(undefined, body);
});
}
/* Announce ourselves to the registry */
DiscoveryClient.prototype.announce = function (announcement, cb) {
var disco = this;
this._singleAnnounce(announcement, function(error, a) {
if (error) {
cb(error);
return;
}
disco.logger.log("Announced as " + a);
disco.announcements.push(a);
cb(undefined, a);
});
}
/* Remove a previous announcement. The passed object *must* be the
* lease as returned by the 'announce' callback. */
DiscoveryClient.prototype.unannounce = function (announcement, callback) {
var disco = this;
var server = disco._randomServer();
var url = server + "/announcement/" + announcement.announcementId;
disco.announcements.splice(disco.announcements.indexOf(announcement), 1);
request({
url: url,
method: "DELETE"
}, function (error, response, body) {
if (error) {
disco.logger.error(error);
if (callback) {
callback();
}
return;
}
disco.logger.log("Unannounce DELETE '" + url + "' returned " + response.statusCode + ": " + body);
if (callback) {
callback();
}
});
}
module.exports = DiscoveryClient;
|
JavaScript
| 0 |
@@ -5928,65 +5928,23 @@
r);%0A
-%09
-if (callback) %7B%0A%09%09 callback();%0A%09 %7D%0A%09 return;%0A %7D%0A
+ %7D else %7B%0A
@@ -6042,16 +6042,22 @@
body);%0A
+ %7D%0A
if (
@@ -6072,9 +6072,12 @@
) %7B%0A
-%09
+
ca
|
8ba2f8f5f03198c0e4a7702087cfcfb70408e06a
|
Rebuild for new version of Task
|
dist/Task.js
|
dist/Task.js
|
"use strict";function Task(r,t,e,a){r=r.replace(" ","");var i,l=[],o=r.indexOf("{");if(-1!==o){var u=r.match(/{(.*?)}/).slice(1)[0].split(","),n=!0,s=!1,c=void 0;try{for(var f,p=u[Symbol.iterator]();!(n=(f=p.next()).done);n=!0){var v=f.value;v&&l.push(v)}}catch(h){s=!0,c=h}finally{try{!n&&p["return"]&&p["return"]()}finally{if(s)throw c}}i=r.slice(0,o)}else i=r;var y;y="function"==typeof t?t:function(){Short(t,e,a)},gulp.task(i,l,y)}var gulp=require("gulp"),Short=require("./Short");module.exports=Task;
|
JavaScript
| 0 |
@@ -22,21 +22,21 @@
Task(r,
-t,e,a
+e,t,i
)%7Br=r.re
@@ -57,16 +57,16 @@
var
-i,l
+n,o
=%5B%5D,
-o
+a
=r.i
@@ -85,17 +85,17 @@
if(-1!==
-o
+a
)%7Bvar u=
@@ -140,14 +140,14 @@
,%22),
-n
+l
=!0,
-s
+f
=!1,
@@ -167,17 +167,17 @@
for(var
-f
+s
,p=u%5BSym
@@ -198,12 +198,12 @@
);!(
-n=(f
+l=(s
=p.n
@@ -215,17 +215,17 @@
).done);
-n
+l
=!0)%7Bvar
@@ -227,17 +227,17 @@
)%7Bvar v=
-f
+s
.value;v
@@ -238,17 +238,17 @@
alue;v&&
-l
+o
.push(v)
@@ -258,17 +258,17 @@
atch(h)%7B
-s
+f
=!0,c=h%7D
@@ -280,17 +280,17 @@
ly%7Btry%7B!
-n
+l
&&p%5B%22ret
@@ -321,17 +321,17 @@
ally%7Bif(
-s
+f
)throw c
@@ -332,17 +332,17 @@
hrow c%7D%7D
-i
+n
=r.slice
@@ -348,17 +348,17 @@
e(0,
-o
+a
)%7Delse
-i
+n
=r;v
@@ -387,11 +387,46 @@
eof
-t?t
+e?e:%22undefined%22==typeof e?function()%7B%7D
:fun
@@ -443,13 +443,13 @@
ort(
-t,e,a
+e,t,i
)%7D,g
@@ -461,11 +461,11 @@
ask(
-i,l
+n,o
,y)%7D
|
1bf391a6a52bec26a2d0bf3ec2d1cd0eed6fecf3
|
Update stray babel-core import to @babel/core.
|
register.js
|
register.js
|
var assert = require("assert");
var path = require("path");
var fs = require("fs");
var hasOwn = Object.hasOwnProperty;
var convertSourceMap = require("convert-source-map");
var meteorBabel = require("./index.js");
var util = require("./util.js");
var Module = module.constructor;
require("reify/lib/runtime").enable(Module.prototype);
var config = {
sourceMapRootPath: null,
allowedDirectories: Object.create(null),
babelOptions: null
};
function setBabelOptions(options) {
config.babelOptions = Object.assign({}, options, {
// Overrides for default options:
sourceMap: "inline"
});
return exports;
}
// Set default config.babelOptions.
setBabelOptions(require("./options.js").getDefaults({
nodeMajorVersion: parseInt(process.versions.node)
}));
exports.setBabelOptions = setBabelOptions;
exports.setSourceMapRootPath = function (smrp) {
config.sourceMapRootPath = smrp;
return exports;
};
exports.allowDirectory = function (dir) {
config.allowedDirectories[dir] = true;
// Sometimes the filename passed to the require.extensions handler is a
// real path, and thus may not appear to be contained by an allowed
// directory, even though it should be.
config.allowedDirectories[fs.realpathSync(dir)] = true;
return exports;
};
var defaultHandler = require.extensions[".js"];
require.extensions[".js"] = function(module, filename) {
if (shouldNotTransform(filename)) {
defaultHandler(module, filename);
} else {
module._compile(
getBabelResult(filename).code,
filename
);
// As of version 0.10.0, the Reify require.extensions[".js"] handler
// is responsible for running parent setters after the module has
// finished loading for the first time, so we need to call that method
// here because we are not calling the defaultHandler.
module.runSetters();
}
};
exports.retrieveSourceMap = function(filename) {
if (shouldNotTransform(filename)) {
return null;
}
const babelCore = require("babel-core");
if (typeof babelCore.transformFromAst !== "function") {
// The retrieveSourceMap function can be called as a result of
// importing babel-core for the first time, at a point in time before
// babelCore.transformFromAst has been defined. The absence of that
// function will cause meteorBabel.compile to fail if we try to call
// getBabelResult here. Fortunately, we can just return null instead,
// which means we couldn't retrieve a source map, which is fine.
return null;
}
var result = getBabelResult(filename);
var converted = result && convertSourceMap.fromSource(result.code);
var map = converted && converted.toJSON();
return map && {
url: map.file,
map: map
} || null;
};
function shouldNotTransform(filename) {
if (path.resolve(filename) !==
path.normalize(filename)) {
// If the filename is not absolute, then it's a file in a core Node
// module, and should not be transformed.
return true;
}
var dirs = Object.keys(config.allowedDirectories);
var allowed = dirs.some(function (dir) {
var relPath = path.relative(dir, filename);
if (relPath.slice(0, 2) === "..") {
// Ignore files that are not contained by an allowed directory.
return false;
}
if (relPath.split(path.sep).indexOf("node_modules") >= 0) {
// Ignore files that are contained by a node_modules directory that
// is itself contained by the allowed dir.
return false;
}
return true;
});
return ! allowed;
}
function getBabelResult(filename) {
var source = fs.readFileSync(filename, "utf8");
var babelOptions = {};
for (var key in config.babelOptions) {
if (hasOwn.call(config.babelOptions, key)) {
babelOptions[key] = config.babelOptions[key];
}
}
if (babelOptions.sourceMap) {
if (config.sourceMapRootPath) {
var relativePath = path.relative(
config.sourceMapRootPath,
filename
);
if (relativePath.slice(0, 2) !== "..") {
// If the given filename is a path contained within
// config.sourceMapRootPath, use the relative path but prepend
// path.sep so that source maps work more reliably.
filename = path.sep + relativePath;
}
}
babelOptions.sourceFileName = filename;
babelOptions.sourceMapTarget = filename + ".map";
}
babelOptions.filename = filename;
return meteorBabel.compile(source, babelOptions);
}
|
JavaScript
| 0 |
@@ -1987,22 +1987,23 @@
equire(%22
+@
babel
--
+/
core%22);%0A
@@ -2148,14 +2148,15 @@
ing
+@
babel
--
+/
core
|
4382103d069b723263fca89e5a94edb65eb6093e
|
Fix lint
|
test/SvgFilter.js
|
test/SvgFilter.js
|
/*global describe, it, __dirname, setTimeout*/
const expect = require('unexpected').clone().installPlugin(require('unexpected-stream'));
const SvgFilter = require('../lib/SvgFilter');
const Path = require('path');
const fs = require('fs');
describe('SvgFilter', function () {
it('should produce a smaller file when exporting only a specific ID', async function () {
await expect(
fs.createReadStream(Path.resolve(__dirname, 'data', 'dialog-information.svg')),
'when piped through',
new SvgFilter({keepId: ['linearGradient3175']}),
'to yield output satisfying',
'when decoded as', 'utf-8',
expect.it('to contain', 'id="linearGradient3175"')
.and('not to contain', 'id="linearGradient2399"')
);
});
it('should produce a smaller file when exporting only a specific ID, command-line argument style', async function () {
await expect(
fs.createReadStream(Path.resolve(__dirname, 'data', 'dialog-information.svg')),
'when piped through',
new SvgFilter(['--keepId=linearGradient3175']),
'to yield output satisfying',
'when decoded as', 'utf-8',
expect.it('to contain', 'id="linearGradient3175"')
.and('not to contain', 'id="linearGradient2399"')
);
});
it('should execute inline JavaScript with the specified id', async function () {
await expect(
fs.createReadStream(Path.resolve(__dirname, 'data', 'svg-with-script.svg')),
'when piped through',
new SvgFilter({runScript: 'run', injectId: 'theId'}),
'to yield output satisfying',
'when decoded as', 'utf-8',
'to contain', 'id="theId"'
);
});
it('should execute external JavaScript with the specified file name', async function () {
await expect(
fs.createReadStream(Path.resolve(__dirname, 'data', 'dialog-information.svg')),
'when piped through',
new SvgFilter({
runScript: 'addBogusElement.js',
url: 'file://' + __dirname + '/data/',
bogusElementId: 'theBogusElementId'
}),
'to yield output satisfying',
'when decoded as', 'utf-8',
'to contain', 'id="theBogusElementId"'
);
});
it('should not emit data events while paused', function (done) {
const svgFilter = new SvgFilter();
function fail() {
done(new Error('SvgFilter emitted data while it was paused!'));
}
svgFilter.pause();
svgFilter.on('data', fail).on('error', done);
fs.createReadStream(Path.resolve(__dirname, 'data', 'dialog-information.svg')).pipe(svgFilter);
setTimeout(function () {
svgFilter.removeListener('data', fail);
const chunks = [];
svgFilter
.on('data', chunk => chunks.push(chunk))
.on('end', () => {
const resultSvgBuffer = Buffer.concat(chunks);
expect(resultSvgBuffer.length, 'to equal', 38291);
done();
});
svgFilter.resume();
}, 1000);
});
it('should emit an error if an invalid image is processed', function (done) {
const svgFilter = new SvgFilter();
svgFilter.on('error', err => {
expect(err, 'to have message', /Parse error/);
done();
})
.on('data', chunk => done(new Error('SvgFilter emitted data when an error was expected')))
.on('end', () => done(new Error('SvgFilter emitted end when an error was expected')));
svgFilter.end(new Buffer('<?img attr="<>&"/>', 'utf-8'));
});
});
|
JavaScript
| 0.000032 |
@@ -3542,32 +3542,36 @@
%7D)%0A
+
.on('data', chun
@@ -3645,16 +3645,20 @@
ted')))%0A
+
|
6cd7bb2e9271f0211a807b26cb677accf87bee32
|
Remove cache from crazy benchmark
|
benchmark/deps-chain.js
|
benchmark/deps-chain.js
|
#!/usr/bin/env node
/*eslint no-console: 0, no-nested-ternary: 0*/
'use strict';
var SIZE = 40;
var Benchmark = require('benchmark');
var Core = require('../core/core');
var Suite = Benchmark.Suite;
var Track = require('../core/track');
var app = new Core();
var f = require('util').format;
function noop() {
return this.name;
}
Benchmark.options.minSamples = 100;
console.log('Crazy deps chain, just for speed up debugging');
app.logger.conf({
logLevel: 'NOTSET'
});
app.unit({
base: 0,
name: f('unit_%s', SIZE),
deps: [f('unit_%s', SIZE - 1), f('unit_%s', SIZE - 2)],
main: noop
});
SIZE -= 1;
while (SIZE) {
app.unit({
base: 0,
name: f('unit_%s', SIZE),
deps: SIZE < 2 ?
[] :
SIZE < 3 ?
[f('unit_%s', SIZE - 1)] :
[
f('unit_%s', SIZE - 1),
f('unit_%s', SIZE - 2)
],
main: noop,
maxAge: 100,
identify: noop
});
SIZE -= 1;
}
var suite = new Suite().
on('cycle', function (e) {
console.log(String(e.target));
}).
add('test', function (defer) {
app.callUnit(new Track(app, app.logger.bind('foo')), 'unit_40', null, function () {
defer.resolve();
});
}, {
defer: true
});
app.ready().done(function () {
suite.run({
async: true,
queued: true
});
});
|
JavaScript
| 0 |
@@ -953,53 +953,8 @@
ain:
- noop,%0A maxAge: 100,%0A identify:
noo
|
a16e538e2f6f7187866ecf365fae30bec1cfd820
|
Add 100x file
|
test/benchmark.js
|
test/benchmark.js
|
const Benchmark = require('benchmark')
const BrickFace = require('../brickface')
let suite = new Benchmark.Suite()
const python = require('./python')
let pythonFile = python.pythonFile
let tokenizePython = python.tokenize
suite.add('python', function() {
tokenizePython(pythonFile, () => {})
})
let pythonFile10 = ''
for (var i = 10; i--; ) { pythonFile10 += pythonFile }
suite.add('python x10', function() {
tokenizePython(pythonFile10, () => {})
})
suite.on('cycle', function(event) {
var bench = event.target;
if (bench.error) {
console.log(' ✘ ', bench.name)
console.log(bench.error.stack)
console.log('')
} else {
console.log(' ✔ ' + bench)
}
})
.on('complete', function() {
// TODO: report geometric mean.
})
.run()
|
JavaScript
| 0.000002 |
@@ -456,16 +456,180 @@
%7B%7D)%0A%7D)%0A%0A
+let pythonFile100 = ''%0Afor (var i = 100; i--; ) %7B pythonFile100 += pythonFile %7D%0Asuite.add('python x100', function() %7B%0A tokenizePython(pythonFile100, () =%3E %7B%7D)%0A%7D)%0A%0A
%0Asuite.o
|
a3f3ce0d09cd722dc6435110b61920059af78d64
|
Fix failing test
|
test/cases/loaders/issue-2299/loader/index.js
|
test/cases/loaders/issue-2299/loader/index.js
|
var path = require('path');
var async = require('async');
var assign = require('object-assign');
module.exports = function(content) {
var cb = this.async();
var json = JSON.parse(content);
async.mapSeries(
json.imports,
function(url, callback) {
this.loadModule(url, function(err, source, map, module) {
if (err) {
return callback(err);
}
callback(null, this.exec(source, url));
}.bind(this))
}.bind(this),
function(err, results) {
if (err) {
return cb(err);
}
// Combine all the results into one object and return it
cb(null, 'module.exports = ' + JSON.stringify(results.reduce(function(prev, result) {
return assign({}, prev, result);
}, json)));
}
);
}
|
JavaScript
| 0.000002 |
@@ -55,47 +55,8 @@
');%0A
-var assign = require('object-assign');%0A
modu
@@ -616,39 +616,132 @@
%09%09%09%09
-return assign(%7B%7D, prev, result)
+for (var key in result) %7B%0A%09%09%09%09%09if (result.hasOwnProperty(key)) %7B%0A%09%09%09%09%09%09prev%5Bkey%5D = result%5Bkey%5D;%0A%09%09%09%09%09%7D%0A%09%09%09%09%7D%0A%09%09%09%09return prev
;%0A%09%09
|
5c5bcfbe676784b724b741da034f1cc480dcd01d
|
Rename UT Suite
|
test/cli/commands/generate-psm1-utils-test.js
|
test/cli/commands/generate-psm1-utils-test.js
|
/**
* Copyright (c) Microsoft. All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
var assert = require('assert');
var generatePsm1 = require('../../../lib/cli/generate-psm1-utils');
suite('sharedkey-tests', function () {
test('getNormalizedParameterName', function (done) {
assert.equal(generatePsm1.getNormalizedParameterName('p#p#p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p,p,p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p(p(p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p)p)p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p{{p{{p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p}}p}}p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p[p[p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p]p]p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p&p&p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p-p-p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p\\p\\p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p/p/p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p$p$p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p^p^p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p;p;p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p:p:p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p"p"p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p\'p\p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p<p<p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p>p>p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p|p|p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p?p?p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p@p@p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p`p`p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p*p*p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p%p%p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p+p+p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p=p=p'), 'ppp');
assert.equal(generatePsm1.getNormalizedParameterName('p~p~p'), 'ppp');
done();
});
});
|
JavaScript
| 0.000006 |
@@ -706,23 +706,21 @@
te('
-sharedkey-tests
+generate-psm1
', f
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.