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
|
---|---|---|---|---|---|---|---|
8575fda16ee48b5363dffd55755a2625507e8ba0 | Extend test coverage. | ui/src/registrator/PrihlaskyDohlasky/StartCislo/startCisloReducer.test.js | ui/src/registrator/PrihlaskyDohlasky/StartCislo/startCisloReducer.test.js | import deepFreeze from 'deep-freeze';
import { hide as genericHide, show as genericShow } from './StartCisloActions';
import { createStartCisloReducer } from './startCisloReducer';
const hide = genericHide('PRIHLASKY');
const show = genericShow('PRIHLASKY');
const startCisloReducer = createStartCisloReducer('PRIHLASKY');
it('na začátku', () => {
const stateBefore = undefined;
const stateAfter = { showing: false };
expect(startCisloReducer(stateBefore, {})).toEqual(stateAfter);
});
it('hide', () => {
const stateBefore = { showing: true };
const stateAfter = { showing: false };
deepFreeze(stateBefore);
expect(startCisloReducer(stateBefore, hide())).toEqual(stateAfter);
});
it('show', () => {
const stateBefore = { showing: false };
const stateAfter = { showing: true };
deepFreeze(stateBefore);
expect(startCisloReducer(stateBefore, show())).toEqual(stateAfter);
});
| JavaScript | 0 | @@ -31,16 +31,79 @@
reeze';%0A
+import %7B reset %7D from '../PrihlaskyForm/PrihlaskyFormActions';%0A
import %7B
@@ -939,28 +939,234 @@
)).toEqual(stateAfter);%0A%7D);%0A
+%0Ait('reset', () =%3E %7B%0A const stateBefore = %7B showing: true %7D;%0A const stateAfter = %7B showing: false %7D;%0A deepFreeze(stateBefore);%0A%0A expect(startCisloReducer(stateBefore, reset())).toEqual(stateAfter);%0A%7D);%0A
|
b8e76d842cd05e203372799145c08b3cbe1cc989 | create snapshot with adapterOptions through _internalModel | addon/actions/action.js | addon/actions/action.js | import Ember from 'ember';
import normalizePayload from '../utils/normalize-payload';
import urlBuilder from 'ember-custom-actions/utils/url-builder';
import deepMerge from 'lodash/merge';
const {
getOwner,
computed,
Object: EmberObject,
ObjectProxy,
ArrayProxy,
PromiseProxyMixin,
typeOf: emberTypeOf,
isArray,
RSVP,
assert,
String: EmberString
} = Ember;
const promiseProxies = {
array: ArrayProxy.extend(PromiseProxyMixin),
object: ObjectProxy.extend(PromiseProxyMixin)
};
export default EmberObject.extend({
path: '',
model: null,
options: {},
payload: {},
instance: false,
init() {
this._super(...arguments);
assert('Model has to be persisted!', !(this.get('instance') && !this.get('model.id')));
let payload = this.get('payload') || {};
assert('payload should be an object', emberTypeOf(payload) === 'object');
this.set('payload', payload);
},
/**
@return {DS.Store}
*/
store: computed.readOnly('model.store'),
/**
@return {String}
*/
modelName: computed('model', function() {
let { constructor } = this.get('model');
return constructor.modelName || constructor.typeKey;
}).readOnly(),
/**
@return {DS.Adapter}
*/
adapter: computed('modelName', 'store', function() {
return this.get('store').adapterFor(this.get('modelName'));
}).readOnly(),
/**
@return {DS.Serializer}
*/
serializer: computed('modelName', 'store', function() {
return this.get('store').serializerFor(this.get('modelName'));
}).readOnly(),
/**
@return {Ember.Object}
*/
config: computed('options', function() {
let appConfig = getOwner(this.get('model')).resolveRegistration('config:environment').emberCustomActions || {};
let mergedConfig = deepMerge({}, appConfig, this.get('options'));
return EmberObject.create(mergedConfig);
}).readOnly(),
/**
@public
@method callAction
@return {Promise}
*/
callAction() {
let promise = this._promise();
let responseType = EmberString.camelize(this.get('config.responseType') || '');
let promiseProxy = promiseProxies[responseType];
return promiseProxy ? promiseProxy.create({ promise }) : promise;
},
/**
@private
@method queryParams
@return {Object}
*/
queryParams() {
let queryParams = emberTypeOf(this.get('config.queryParams')) === 'object' ? this.get('config.queryParams') : {};
return this.get('adapter').sortQueryParams(queryParams);
},
/**
@private
@method requestMethod
@return {String}
*/
requestMethod() {
return this.get('config.method').toUpperCase();
},
/**
@private
@method requestUrl
@return {String}
*/
requestUrl() {
let modelName = this.get('modelName');
let id = this.get('instance') ? this.get('model.id') : null;
let snapshot = this.get('model')._createSnapshot();
snapshot.adapterOptions = deepMerge(snapshot.adapterOptions, this.get('config.adapterOptions'));
let actionId = this.get('path');
let queryParams = this.queryParams();
if (this.get('adapter').urlForCustomAction) {
return this.get('adapter').urlForCustomAction(modelName, id, snapshot, actionId, queryParams);
} else {
let url = this.get('adapter')._buildURL(modelName, id);
return urlBuilder(url, actionId, queryParams);
}
},
/**
@private
@method requestData
@return {Object}
*/
requestData() {
let data = normalizePayload(this.get('payload'), this.get('config.normalizeOperation'));
return deepMerge({}, this.get('config.ajaxOptions'), { data });
},
// Internals
_promise() {
return this.get('adapter')
.ajax(this.requestUrl(), this.requestMethod(), this.requestData())
.then(this._onSuccess.bind(this), this._onError.bind(this));
},
_onSuccess(response) {
if (this.get('config.pushToStore') && this._validResponse(response)) {
return this.get('serializer').pushPayload(this.get('store'), response);
}
return response;
},
_onError(error) {
if (this.get('config.pushToStore') && isArray(error.errors)) {
let id = this.get('model.id');
let typeClass = this.get('model').constructor;
error.serializedErrors = this.get('serializer').extractErrors(this.get('store'), typeClass, error, id);
}
return RSVP.reject(error);
},
_validResponse(object) {
return emberTypeOf(object) === 'object' && Object.keys(object).length > 0;
}
});
| JavaScript | 0 | @@ -2860,75 +2860,39 @@
')._
-createSnapshot();%0A snapshot.adapterOptions = deepMerge(s
+internalModel.createS
napshot
-.
+(%7B
adap
@@ -2901,17 +2901,17 @@
rOptions
-,
+:
this.ge
@@ -2936,16 +2936,18 @@
ptions')
+ %7D
);%0A l
|
df7fc2f616c2f4da9dcb449db7faa16660525f56 | fix app.js | tests/dummy/app/app.js | tests/dummy/app/app.js | import Application from '@ember/application';
import Ember from 'ember';
import Resolver from './resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
let App;
Ember.MODEL_FACTORY_INJECTIONS = true;
App = Application.extend({
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
snippetPaths: ['tests/dummy/app'],
Resolver
});
loadInitializers(App, config.modulePrefix);
export default App;
| JavaScript | 0.00011 | @@ -362,45 +362,8 @@
ix,%0A
- snippetPaths: %5B'tests/dummy/app'%5D,%0A
Re
|
b52f24ccceac4275021247ac8eb1eb6c242bd373 | fix path in datepicker demo page | demo/demoPages/DatePickerPage.js | demo/demoPages/DatePickerPage.js |
import React, { Component } from 'react';
import { injectIntl } from 'react-intl';
import { messages } from '../../translations/defaultMessages';
import { DatePicker, Select } from '../../../index';
class DatePickerPage extends Component {
constructor(props){
super(props);
this.state = {
datePickerValue1 : null,
datePickerValue2 : null,
datePickerValue3 : null
};
}
render() {
const { intl } = this.props;
const { inputState, datePickerValue1, datePickerValue2, datePickerValue3 } = this.state;
// ======================Internationalization Example=========================
// intl prop is injected by the injectIntl() at the bottom of the page...
// Provider Context wraps the root element in demo.js.
// do the intl string replacement...
const text = {
textInputInfoMessage : intl.formatMessage(messages.textInputInfoMessage),
textInputErrorMessage : intl.formatMessage(messages.textInputErrorMessage)
};
return (
<div className="displaySection">
<h1><a href="http://pearson-higher-ed.github.io/design/c/date-picker/v2.0.0">DatePicker - current design (v2.0.0)</a></h1>
<div className="elementContainer">
<div className="code">
<h2>DatePicker:</h2>
<h3>Props:</h3>
<ul>
<li>time:Boolean === "render datepicker as timepicker"</li>
<li>className:String === "styles to pass to datepicker"</li>
<li>id:String === "A unique name for the datepicker"</li>
<li>dateFormat:String === "format for how the date is displayed. Defaults to mm/dd/yyyy."</li>
<li>inputState:String === "styles for input state, one of 'error','disabled','readOnly','default'"</li>
<li>labelText:String === "unique label for the input field"</li>
<li>datePickerValue:Date === "value to be displayed by the datepicker"</li>
<li>changeHandler:Function === "function to pass values on change"</li>
<li>infoMessage:String === "an optional info message displayed below the input"</li>
<li>errorMessage:String === "an optional error message displayed below the input"</li>
<li>disablePast: Boolean === "Disable all past dates"</li>
<li>minDate:Object === "Accepts a date object which disables all dates prior to that date."</li>
</ul>
<h3>Configure Props:</h3>
<Select id="select" changeHandler={e => this.setState({inputState:`${e.target.value}`}) } selectedOption={inputState} labelText="Select An inputState:" options={["default", "error", "readOnly", "disabled"]} />
</div>
<h2>DatePicker</h2>
<DatePicker
id = "someGiantId1"
dateFormat = "dd/mm/yyyy"
inputState = {inputState}
labelText = "Select date (dd/mm/yyyy)"
datepickerValue = {datePickerValue1}
changeHandler = {value => this.setState({datePickerValue1:value})}
infoMessage = {text.textInputInfoMessage}
errorMessage = {text.textInputErrorMessage}
/>
<p className="code">{`<DatePicker id="someGiantId" inputState = "default" labelText = "Select date (dd/mm/yyyy)" datepickerValue = {this.state.datepickerValue1} changeHandler = {value => this.setState({datePickerValue1:value})} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
<h2>DatePicker (range): </h2>
<DatePicker
id = "someGiantId2"
inputState = {inputState}
labelText = "Select start date (mm/dd/yyyy)"
datepickerValue = {datePickerValue2}
changeHandler = {value => this.setState({datePickerValue2:value})}
infoMessage = {text.textInputInfoMessage}
errorMessage = {text.textInputErrorMessage}
/>
<DatePicker
id = "someGiantId3"
inputState = {inputState}
labelText = "Select end date (mm/dd/yyyy)"
datepickerValue = {datePickerValue3}
changeHandler = {value => this.setState({datePickerValue3:value})}
infoMessage = {text.textInputInfoMessage}
errorMessage = {text.textInputErrorMessage}
/>
<p className="code">{`DatePicker Range is made up of two single datepickers`}</p>
<p className="code">{`<DatePicker id="someGiantId" inputState = "default" labelText = "Select start date (mm/dd/yyyy)" datepickerValue = {this.state.datepickerValue2} changeHandler = {value => this.setState({datePickerValue2:value})} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
<p className="code">{`<DatePicker id="someGiantId" inputState = "default" labelText = "Select end date (mm/dd/yyyy)" datepickerValue = {this.state.datepickerValue3} changeHandler = {value => this.setState({datePickerValue3:value})} infoMessage = "${text.textInputInfoMessage}" errorMessage = "${text.textInputErrorMessage}" />`}</p>
</div>
</div>
)
}
}
export default injectIntl(DatePickerPage);
| JavaScript | 0.000001 | @@ -120,19 +120,16 @@
rom '../
-../
translat
@@ -194,19 +194,16 @@
'../../
-../
index';%0A
|
10af4d7afada4fcdc09235ef133277fa67ab11dc | remove async, add console.log stating bot left | events/guildCreate.js | events/guildCreate.js | const MIN_MEMBERS = 3; // Minimum amount of MEMBERS that must be in a guild.
const BOT_RATIO = 70; // The percentage of Members that are Bots in a guild must be less than this.
exports.run = async (client, guild) => {
if (guild.memberCount < MIN_MEMBERS || guild.members.filter(u => u.user.bot).size * 100 / guild.memberCount >= BOT_RATIO) {
guild.owner.send(`I have left your server \`${guild.name}\` because it looks like a bot farm, or a server with only me and you.`).catch(() => null);
guild.leave();
}
};
| JavaScript | 0 | @@ -188,14 +188,8 @@
un =
- async
(cl
@@ -504,15 +504,105 @@
eave();%0A
+ console.log(%60Left server that didn't meet Anti-Botfarm requirements. ($%7Bguild.id%7D)%60);%0A
%7D%0A%7D;%0A
|
05da4890054ed7c7e95c26eb1ecb8c52f61b3df8 | Use StopFlashTabs | stopflash.js | stopflash.js | /**
* StopFlash
*
* https://github.com/JWhile/StopFlash
*
* stopflash.js
*/
// class StopFlashUI extends Builder
function StopFlashUI(elements)
{
this.super('div');
this.content = new Builder('div')
.className('content')
.append(new Builder('div')
.className('tab')
.text('Home tab'))
.append(new Builder('div')
.className('tab')
.text('Whitelist tab'))
.append(new Builder('div')
.className('tab')
.text('Options tab'));
var self = this;
this.append(new Builder('div')
.className('head')
.text('StopFlash'))
.append(new Builder('div')
.className('menu')
.append(new Builder('a')
.text('Home')
.event('click', function()
{
self.content.css('margin-left', '0px');
}))
.append(new Builder('a')
.text('Whitelist')
.event('click', function()
{
self.content.css('margin-left', '-300px');
}))
.append(new Builder('a')
.text('Options')
.event('click', function()
{
self.content.css('margin-left', '-600px');
})))
.append(this.content)
.append(new Builder('div')
.className('foot')
.html('<a href="https://github.com/JWhile/StopFlash">https://github.com/JWhile/StopFlash</a>'))
}
fus.extend(StopFlashUI, Builder);
// class StopFlashTabs extends Builder
function StopFlashTabs()
{
this.super('div');
this.tabs = []; // :Array<Builder>
}
// function addTab(Builder builder)@Chainable
StopFlashTabs.prototype.addTab = function(builder)
{
this.tabs.push(builder
.className('tab')
.insert(this));
return this;
};
// function setTab(int index):void
StopFlashTabs.prototype.setTab = function(index)
{
this.css('margin-left', '-'+ (index * 300) +'px');
this.tabs[index].css('position', '');
var self = this;
setTimeout(function()
{
for(var i = 0; i < self.tabs.length; ++i)
{
if(i !== index)
{
self.tabs[i].css('position', 'absolute');
}
}
}, 400);
};
fus.extend(StopFlashTabs, Builder);
// main
var main = function(elements)
{
new StopFlashUI(elements)
.insert(document.body);
};
chrome.tabs.query({'highlighted': true, 'currentWindow': true}, function(tabs)
{
chrome.tabs.sendMessage(tabs[0].id, {'getElements': 'stopflash'}, main);
});
| JavaScript | 0.000001 | @@ -189,37 +189,38 @@
ntent = new
-Builder('div'
+StopFlashTabs(
)%0A .c
@@ -241,37 +241,37 @@
ent')%0A .a
-ppend
+ddTab
(new Builder('di
@@ -337,37 +337,37 @@
ab'))%0A .a
-ppend
+ddTab
(new Builder('di
@@ -438,37 +438,37 @@
ab'))%0A .a
-ppend
+ddTab
(new Builder('di
@@ -888,32 +888,16 @@
ent.
-css('margin-left', '0px'
+setTab(0
);%0A
@@ -1085,35 +1085,16 @@
ent.
-css('margin-left', '-300px'
+setTab(1
);%0A
@@ -1280,35 +1280,16 @@
ent.
-css('margin-left', '-600px'
+setTab(2
);%0A
|
2bf65cc2aee431e90a47150778e1841a6ea804f4 | Update test case | tests/e2e/demo-spec.js | tests/e2e/demo-spec.js | /*global browser:false */
'use strict';
//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Report', function(){
var _ = require('lodash');
var Reports = require('./pages/reports');
var Report = require('./pages/report');
var reports = new Reports();
var report, reportName, conceptName;
it('Should create a new empty report', function(){
reports.get();
reportName = 'HelloWorld' + Math.floor((Math.random() * 10) + 1);
reports.createReport(reportName);
browser.getCurrentUrl()
.then(function(url){
var id = _.last(url.split('/'));
report = new Report(id);
report.get();
expect(report.searchBox.isPresent()).toBe(true);
expect(report.label).toBe(reportName);
});
});
it('Should create a new concept', function(){
conceptName = 'h:assets';
report.taxonomy.get();
report.taxonomy.createConcept(conceptName);
expect(report.taxonomy.conceptName).toBe(conceptName);
});
it('Creates a new element', function(){
report.taxonomy.createElement(conceptName);
expect(report.elementCount()).toBe(1);
});
it('Creates a us-gaap:Assets synonym', function(){
var synonyms = report.taxonomy.getSynonyms(conceptName);
synonyms.get();
expect(synonyms.getSynonyms().count()).toBe(0);
synonyms.addSynonym('us-gaap:Assets');
synonyms.addSynonym('us-gaap:AssetsCurrent');
expect(synonyms.getSynonyms().count()).toBe(2);
expect(synonyms.getSynonymName(synonyms.getSynonyms().first())).toBe('us-gaap:Assets');
expect(synonyms.getSynonymName(synonyms.getSynonyms().last())).toBe('us-gaap:AssetsCurrent');
});
it('Should display the fact table', function() {
report.filters.get();
browser.waitForAngular();
report.factTable.get();
expect(report.factTable.lineCount()).toBeGreaterThan(0);
});
it('Should delete report', function() {
reports.get();
reports.list.count().then(function(count){
reports.deleteReport(reportName).then(function(){
expect(reports.list.count()).toBe(count - 1);
});
});
});
});
| JavaScript | 0.000001 | @@ -1666,32 +1666,90 @@
ssetsCurrent');%0A
+ synonyms.addSynonym('us-gaap:AssetsCurrent');%0A
expe
|
9aff14f8d4b3bf08f5fdd5eb9fbeb7969c86b375 | fix syntax | cli.js | cli.js | var vorpal = require('vorpal')();
var config = require('./config.json');
var Dropbox = require('dropbox');
var recursive = require('recursive-readdir');
var upath = require('upath');
var jsonfile = require('jsonfile')
const fs = require('fs');
var log = 'mapping.json'
vorpal
.command('info', 'get defined cloud services\' informations')
.action(function(args, callback) {
});
vorpal
.command('cp <source> <destination>', 'copy file/directory to defined cloud')
.option('-d, --directory', 'Directory to move to cloud services')
.action(function(args, callback) {
/*dbx.usersGetSpaceUsage()
.then(function(r){
console.log(r);
})*/
vorpal.log('Copy files');
var entries = [];
var dbx = new Dropbox({ accessToken: config.services.dropbox[0].accessToken });
recursive(args.source, function (err, files) {
files.forEach(function(file){
fs.readFile(file, (err, data) => {
dbx.filesUpload({
autorename: false,
contents: data,
path: args.destination + upath.toUnix(file),
mode: {
'.tag': 'overwrite'
}
})
.then(function(response) {
vorpal.log(file + ' uploaded');
})
.catch(function(error) {
vorpal.log(error);
});
});
});
});
callback();
});
vorpal
.command('mv', 'move file/directory to defined cloud')
.option('-d, --directory', 'Directory to move to cloud services')
.action(function(args, callback){
callback();
});
vorpal
.delimiter('one-cloud$')
.show();
| JavaScript | 0.000023 | @@ -965,16 +965,24 @@
e(file,
+function
(err, da
@@ -988,11 +988,8 @@
ata)
- =%3E
%7B%0A
|
a75dd100ab50afefeeb9197048faecf62680194d | set correct `cwd` for the npm run path | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var childProcess = require('child_process');
var meow = require('meow');
var globby = require('globby');
var inquirer = require('inquirer');
var assign = require('lodash.assign');
var npmRunPath = require('npm-run-path');
var utils = require('./cli-utils');
var codemods = require('./codemods.json');
function runScripts(scripts, files) {
var spawnOptions = {
env: assign({}, process.env, {PATH: npmRunPath()}),
stdio: 'inherit'
};
var result;
scripts.forEach(function (script) {
result = childProcess.spawnSync('jscodeshift', ['-t', script].concat(files), spawnOptions);
if (result.error) {
throw result.error;
}
});
}
meow(`
Usage
$ ava-codemods
Available upgrades
- 0.13.x → 0.14.x
`);
codemods.sort(utils.sortByVersion);
var versions = utils.getVersions(codemods);
var questions = [{
type: 'list',
name: 'currentVersion',
message: 'What version of AVA are you currently using?',
choices: versions.slice(0, -1)
}, {
type: 'list',
name: 'nextVersion',
message: 'What version of AVA are you moving to?',
choices: versions.slice(1)
}, {
type: 'input',
name: 'files',
message: 'On which files should the codemods be applied?'
}];
console.log('Ensure you have a backup of your tests or commit the latest changes before continuing.');
inquirer.prompt(questions, function (answers) {
if (!answers.files) {
return;
}
var scripts = utils.selectScripts(codemods, answers.currentVersion, answers.nextVersion);
runScripts(scripts, globby.sync(answers.files.split(/\s+/)));
});
| JavaScript | 0.000001 | @@ -438,16 +438,32 @@
RunPath(
+%7Bcwd: __dirname%7D
)%7D),%0A%09%09s
|
bd6c9f3c141335407aedc978e5a9ea1c52b939d5 | Allow branch to be selected on the commandline | cli.js | cli.js | const path = require('path');
const fs = require('fs');
const cp = require('child_process');
// eslint-disable-next-line
const colors = require('colors');
const request = require('request-promise');
const inquirer = require('inquirer');
const minimist = require('minimist');
const ora = require('ora');
const pkg = require('./package.json');
const args = process.argv.slice(2);
const argv = minimist(args);
const task = args[0];
const options = {
baseUrl: 'https://electrode.cleverthings.io',
platforms: argv.platform || ['mac'],
arch: argv.arch || 'x64'
};
// Default ora spinner (used in build step)
const spinner = ora('Electrode CLI');
//
let userCredentials = {};
let packageJSON = {};
let apiKey = null;
// Check that the current working directory contains an Electron project
const validateWorkingDirectory = () => {
return new Promise((resolve, reject) => {
try {
// eslint-disable-next-line
const pkg = require(path.join(process.cwd(), 'package.json'));
if (!pkg.devDependencies || !pkg.devDependencies.electron) return reject('This directory contains a Node.js project, but not one that depends on Electron.');
packageJSON = pkg;
return resolve();
} catch (e) {
return reject('Could not validate current directory as Electron project. Please ensure you\'re in the right place (try issuing pwd)');
}
});
};
// Prompt the user for their credentials which we will use to register and authenticate them
const getCredentials = () => {
return new Promise((resolve, reject) => {
const credsQuestions = [
{
type: 'input',
name: 'email',
message: 'Please enter your email address'
},
{
type: 'password',
name: 'password',
message: 'Please enter a password to secure your builds, or the password you chose before.'
}
];
return inquirer.prompt(credsQuestions).then((creds) => {
return resolve(creds);
}).catch((e) => {
return reject(e);
});
});
};
// Validate the user's creds
const verifyCredentials = (creds) => {
if (!creds.email || !creds.password) {
console.error('✋ You need to enter a username and password!');
process.exit(1);
}
userCredentials = creds;
return Promise.resolve();
};
// Actually perform the registration on the remote server
const doRegister = () => {
const registerRequestOptions = {
method: 'POST',
uri: `${options.baseUrl}/register`,
body: userCredentials,
json: true,
};
return request(registerRequestOptions).catch((response) => {
if (response.error.name === 'ValidationError') {
// for now assume this is because we're already registered
return Promise.resolve();
}
return Promise.reject(response);
});
};
// Perform the authentication on the remote server
const doAuth = () => {
const registerRequestOptions = {
method: 'POST',
uri: `${options.baseUrl}/auth`,
body: userCredentials,
json: true,
};
return request(registerRequestOptions).catch((response) => {
if (response.statusCode === 404) {
console.error('User not found. Please try again.');
return Promise.reject();
}
return Promise.reject(response);
});
};
// Create a minimal archive of the project conforming to .gitignore by using the
// git archive -o method. Assumes working directory is a valid Git repo..?
const prepareProject = () => {
return new Promise((resolve, reject) => {
cp.exec('git archive -o ._electrode_project.zip master', {}, (err) => {
if (err) {
return reject(err);
}
return resolve();
});
});
};
// Pipe the new project.zip to the remote server, passing our options from the command line
// and the project.json file
const uploadProject = () => {
const registerRequestOptions = {
method: 'POST',
uri: `${options.baseUrl}/app-package`,
headers: {
Authorization: apiKey
},
formData: {
package: fs.createReadStream(path.join(process.cwd(), '._electrode_project.zip')),
options: JSON.stringify(options),
packageJSON: JSON.stringify(packageJSON)
},
json: true,
};
return request(registerRequestOptions);
};
// Perform all of the above steps in order
const buildTask = () => {
return validateWorkingDirectory()
.then(() => {
return getCredentials();
})
.then((creds) => {
spinner.start();
spinner.text = 'Registering you...';
return verifyCredentials(creds);
})
.then(() => {
return doRegister();
})
.then(() => {
spinner.text = 'Authorizing you...';
return doAuth();
})
.then((authResult) => {
spinner.text = 'Preparing your project...';
apiKey = authResult.apiKey;
return prepareProject();
})
.then(() => {
spinner.text = 'Uploading your project...';
return uploadProject();
});
};
console.log(`⚛️ Electrode CLI ${pkg.version} ~ https://electrode.cleverthings.io`.bold);
// What are we doing?
switch (task) {
case 'build':
buildTask()
.then(() => {
spinner.stop();
console.log('Success!'.bold.green, 'Your job has been queued and will be built shortly. You will recieve an email when it is finished. Remember, builds are only available for 24 hours after completion, so make sure you check your email! Have a great day!');
process.exit(0);
})
.catch((e) => {
console.error('!! Error: '.bold.red, e);
process.exit(1);
});
break;
default:
console.error('😕 Unrecognised task. Please refer to the README');
process.exit(1);
break;
}
| JavaScript | 0 | @@ -558,16 +558,51 @@
%7C%7C 'x64'
+,%0A branch: argv.branch %7C%7C 'master'
%0A%7D;%0A%0A//
@@ -3529,17 +3529,17 @@
cp.exec(
-'
+%60
git arch
@@ -3573,22 +3573,41 @@
zip
-master', %7B%7D, (
+$%7Boptions.branch%7D%60, %7B%7D, (err, std
err)
@@ -3654,16 +3654,26 @@
ject(err
+ %7C%7C stderr
);%0A
|
b81325e972f065b53ff7c676550a6fef8fb63c57 | Update Player.js | game/js/gameentities/Player.js | game/js/gameentities/Player.js | "use strict";
var Player = function(world, Bullet, audio) {
this.world = world;
this.audio = audio;
this.idleLeftAnimation = new SpriteAnimation("connor/connorL", 2, 1, 32);
this.idleRightAnimation = new SpriteAnimation("connor/connorR", 2, 1, 32);
this.walkLeftAnimation = new SpriteAnimation("connor/connorL", 2, 3, 32);
this.walkRightAnimation = new SpriteAnimation("connor/connorR", 2, 3, 32);
this.shootLeftAnimation = new SpriteAnimation("connor/connorL", 1, 5, 32);
this.shootRightAnimation = new SpriteAnimation("connor/connorR", 1, 5, 32);
this.jumpLeftAnimation = new SpriteAnimation("connor/connorL", 1, 6, 32);
this.jumpRightAnimation = new SpriteAnimation("connor/connorR", 1, 6, 32);
this.width = 20;
this.height = 38;
this.x = this.world.width / 2;
this.y = this.world.height - this.height;
this.speed = 3;
this.velX = 0;
this.velY = 0;
this.jumping = false;
this.direction = "right";
this.type = "player";
this.Bullet = Bullet;
this.shootLock = false;
this.friction = 0.8;
this.gravity = 0.3;
this.state = this.idleRightAnimation;
this.shootAudio = "pewPewBizNiss";
this.jumpAudio = "jumpFins";
this.kills = 24;
this.lives = 10;
this.myHealth = new HealthBar (world, this, {
x: 50,
lives: this.lives
});
};
var keydown = [];
Player.prototype.explode = function() {
//alert("You died");
if (this.kills > 1 && this.kills < 24) {
this.kills--;
} else {
this.lives--;
if (this.lives == 0) {
alert("You Died");
}
}
};
Player.prototype.update = function() {
// Jump
if (keydown[38]) {
if (!this.jumping) {
this.jumping = true;
this.velY = -this.speed * 2;
this.audio[this.jumpAudio].stop();
this.audio[this.jumpAudio].play();
}
}
// Right
if (keydown[39]) {
if (this.velX < this.speed) {
this.velX++;
this.direction = "right";
}
}
// Left
if (keydown[37]) {
if (this.velX > -this.speed) {
this.velX--;
this.direction = "left";
}
}
// Shoot
if (keydown[32]) {
if (!this.shootLock) {
this.shoot();
this.shootLock = true;
var that = this
setTimeout(function() {
that.shootLock = false;
}, 300);
}
}
this.velX *= this.friction;
this.velY += this.gravity;
this.x += this.velX;
this.y += this.velY;
if (this.x >= this.world.width - this.width) {
this.x = this.world.width - this.width;
} else if (this.x <= 0) {
this.x = 0;
}
if (this.y >= this.world.height - this.height) {
this.y = this.world.height - this.height;
this.jumping = false;
}
if (this.jumping) {
if (this.direction === "right") {
this.state = this.jumpRightAnimation;
} else {
this.state = this.jumpLeftAnimation;
}
} else if (this.shootLock) {
if (this.direction === "right") {
this.state = this.shootRightAnimation;
} else {
this.state = this.shootLeftAnimation;
}
} else if (keydown[37]) {
this.state = this.walkLeftAnimation;
} else if (keydown[39]) {
this.state = this.walkRightAnimation;
} else {
if (this.direction === "right") {
this.state = this.idleRightAnimation;
} else {
this.state = this.idleLeftAnimation;
}
}
if (this.kills > 24) {
this.myHealth.update(this.lives);
}
};
Player.prototype.draw = function() {
var that = this;
this.state.draw(this.x, this.y, function(spriteName, x, y) {
that.width = that.world.sprites[spriteName].width;
that.world.drawSprite(spriteName, x, y, that.width, that.height);
});
//this.world.drawSprite(this.currentImage, this.x, this.y, this.width, this.height);
//this.world.drawText("Happy Anniversary", 115, 90);
if (this.kills < 24) {
this.world.cropSprite("coverTurtleWithACrown", this.kills, this.kills, 384 - this.kills * 2, 46 - this.kills * 2, 115 + this.kills, 55 + this.kills, 384 - this.kills * 2, 46 - this.kills * 2);
}
if (this.kills > 24) {
this.myHealth.draw();
}
};
Player.prototype.midpoint = function() {
return {
x: (this.x + this.width / 2),
y: (this.y + this.height / 2)
}
};
Player.prototype.shoot = function() {
this.world.bullets.push (
new this.Bullet(this.world, {
x: this.midpoint().x,
y: this.midpoint().y - 1,
width: 9,
height: 3,
direction: this.direction,
speed: 20,
acceleration: 0.2,
owner: this.type,
kill: this
//spriteName: 'playerBullet'
}, this.audio
));
this.audio[this.shootAudio].stop();
this.audio[this.shootAudio].play();
};
Player.prototype.kill = function() {
if (this.kills < 24) {
this.kills++;
} /*
else if (this.kills == 24) {
this.myHealth = new HealthBar (world, this, {
x: 50,
lives: this.lives
});
this.kills++;
}
*/
};
document.body.addEventListener("keydown", function(e) {
keydown[e.keyCode] = true;
});
document.body.addEventListener("keyup", function(e) {
keydown[e.keyCode] = false;
});
| JavaScript | 0.000001 | @@ -3240,32 +3240,33 @@
if (this.kills %3E
+=
24) %7B%0D%0A%09%09this.m
@@ -3940,16 +3940,17 @@
.kills %3E
+=
24) %7B%0D%0A
|
d4c4de025dae0807995d38371479bc44786664eb | Add more useful error msg | tests/maxbytes.test.js | tests/maxbytes.test.js | describe('when using the "maxBytes" option', function() {
before(function () {
// Set up a route which listens to uploads
app.post('/uploadmax', function (req, res, next) {
assert(_.isFunction(req.file));
// Disable underlying socket timeout
// THIS IS IMPORTANT
// see https://github.com/joyent/node/issues/4704#issuecomment-42763313
res.setTimeout(0);
req.file('avatar').upload(adapter.receive({
maxBytes: 6000000 // 6 MB
}), function (err, files) {
if (err) {
return setTimeout(function() {
res.statusCode = 500;
return res.send(err.code);
},100);
}
res.statusCode = 200;
return res.end();
});
});
});
describe('Uploading a single file', function() {
it('should allow uploads <= the maxBytes value', function(done) {
this.slow(900000);// (15 minutes)
toUploadAFile(1)(function(err) {
return done(err);
});
});
it('should not allow uploads > the maxBytes value', function(done) {
this.slow(900000);// (15 minutes)
toUploadAFile(10)(function(err) {
if (err) {
if (err == 'E_EXCEEDS_UPLOAD_LIMIT') {return done();}
return done(err);
}
return done("Should have thrown an error!");
});
});
});
describe('Uploading multiple files in a single upstream', function() {
it('should allow uploads <= the maxBytes value', function(done) {
this.slow(900000);// (15 minutes)
var httpRequest = request.post({
url: baseurl+'/uploadmax'
}, onResponse);
var form = httpRequest.form();
form.append('foo', 'hello');
form.append('bar', 'there');
var nonsenseFileToUpload = GENERATE_NONSENSE_FILE(100000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(100000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(100000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(100000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(100000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
// Then check that it worked.
function onResponse (err, response, body) {
if (err) return done(err);
else if (response.statusCode > 300) return done(body || response.statusCode);
else done();
}
});
it('should not allow uploads > the maxBytes value', function(done) {
this.slow(900000);// (15 minutes)
var httpRequest = request.post({
url: baseurl+'/uploadmax'
}, onResponse);
var form = httpRequest.form();
form.append('foo', 'hello');
form.append('bar', 'there');
var nonsenseFileToUpload;
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
nonsenseFileToUpload = GENERATE_NONSENSE_FILE(1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
// Then check that it worked.
function onResponse (err, response, body) {
if (body == 'E_EXCEEDS_UPLOAD_LIMIT' && response.statusCode == 500) {return done();}
return done("Should have thrown an error!");
}
});
});
});
/**
* [toUploadAFile description]
* @param {Number} MB
* @return {Function}
*/
function toUploadAFile (MB) {
/**
* A function which builds an HTTP request with attached multipart
* form upload(s), checking that everything worked.
*/
return function uploadFile(cb) {
var httpRequest = request.post({
url: baseurl+'/uploadmax'
}, onResponse);
var form = httpRequest.form();
form.append('foo', 'hello');
form.append('bar', 'there');
var nonsenseFileToUpload = GENERATE_NONSENSE_FILE(MB*1000000);
form.append('avatar', fsx.createReadStream( nonsenseFileToUpload.path ));
// Then check that it worked.
function onResponse (err, response, body) {
if (err) return cb(err);
else if (response.statusCode > 300) return cb(body || response.statusCode);
else cb();
}
};
}
| JavaScript | 0.000001 | @@ -2795,32 +2795,514 @@
// (15 minutes)%0A
+%0A var httpRequest = request.post(%7B%0A url: baseurl+'/uploadmax'%0A %7D, function onResponse (err, response, body) %7B%0A // Then check that it worked:%0A if (body == 'E_EXCEEDS_UPLOAD_LIMIT' && response.statusCode == 500) %7Breturn done();%7D%0A if (err) %7B return done(err); %7D%0A return done(%22Should have responded with the expected error! Instead got status code %22+response.statusCode+%22 and body: %22+require('util').inspect(body,%7Bdepth:null%7D));%0A %7D);%0A%0A
var httpRe
@@ -4374,248 +4374,8 @@
));
-%0A // Then check that it worked.%0A function onResponse (err, response, body) %7B%0A if (body == 'E_EXCEEDS_UPLOAD_LIMIT' && response.statusCode == 500) %7Breturn done();%7D%0A return done(%22Should have thrown an error!%22);%0A %7D
%0A%0A
|
10c6129353dc2f7d5c962878413496ab7a414549 | Remove trailing line | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var fs = require('fs');
var meow = require('meow');
var imgurUploader = require('./');
var cli = meow({
help: [
'Example',
' $ imgur-uploader unicorn.png',
' $ cat unicorn.png | imgur-uploader'
].join('\n')
});
if (!cli.input.length && process.stdin.isTTY) {
console.error('Expected an image');
process.exit(1);
}
if (cli.input.length) {
fs.readFile(cli.input[0], function (err, buf) {
if (err) {
console.error(err.message);
process.exit(1);
}
imgurUploader(buf, function (err, res) {
if (err) {
console.error(err.message);
process.exit(1);
}
console.log(res.link);
});
});
} else {
var stream = imgurUploader.stream();
stream.on('upload', function (res) {
process.stdout.write(res.link);
});
process.stdin.pipe(stream);
}
| JavaScript | 0.002917 | @@ -804,13 +804,12 @@
(stream);%0A%7D%0A
-%0A
|
60b1b1eea045ff7d845882dc023374435c340bd8 | Change 'program' to 'module' | cli.js | cli.js | #!/usr/bin/env node
'use strict';
var chalk = require('chalk');
var meow = require('meow');
var process = require('process');
var allPrograms = [
'atom',
'bash',
'bin',
'fonts',
'git',
'gnome-terminal',
'vim',
'vscode'
];
var cli = meow({
help: [
'Usage: dotfiles install [<program>...]',
'',
'where <program> is one or more of of:',
' ' + allPrograms.join(', '),
'',
'Specify no <program> to install everything'
]
});
if (cli.input.length === 0) {
console.error('Error: No command specified');
cli.showHelp();
process.exit(1);
}
var commands = {
'install': install
};
if (cli.input[0] in commands) {
commands[cli.input[0]].call(undefined, cli.input.splice(1));
}
function install(programList) {
if (programList.length === 0) {
allPrograms.forEach(installProgram);
} else {
programList.forEach(installProgram);
}
}
function installProgram(program) {
if (allPrograms.indexOf(program) === -1) {
console.error('Error: tried to install non-existing program "' + program + '"');
return;
}
require('./' + program).install();
}
| JavaScript | 0.000005 | @@ -128,23 +128,22 @@
%0Avar all
-Program
+Module
s = %5B%0A
@@ -291,23 +291,22 @@
stall %5B%3C
-program
+module
%3E...%5D',%0A
@@ -325,23 +325,22 @@
'where %3C
-program
+module
%3E is one
@@ -373,23 +373,22 @@
' + all
-Program
+Module
s.join('
@@ -418,23 +418,22 @@
ify no %3C
-program
+module
%3E to ins
@@ -733,23 +733,22 @@
install(
-program
+module
List) %7B%0A
@@ -753,23 +753,22 @@
%7B%0A if (
-program
+module
List.len
@@ -787,23 +787,22 @@
%0A all
-Program
+Module
s.forEac
@@ -806,31 +806,30 @@
Each(install
-Program
+Module
);%0A %7D else
@@ -834,23 +834,22 @@
e %7B%0A
-program
+module
List.for
@@ -860,23 +860,22 @@
(install
-Program
+Module
);%0A %7D%0A%7D
@@ -896,23 +896,21 @@
tall
-Program(program
+Module(module
) %7B%0A
@@ -922,15 +922,14 @@
(all
-Program
+Module
s.in
@@ -934,23 +934,22 @@
indexOf(
-program
+module
) === -1
@@ -1012,28 +1012,26 @@
ing
-program %22' + program
+module %22' + module
+ '
@@ -1072,15 +1072,14 @@
' +
-program
+module
).in
|
c51562010a9509fb4dd22402e3d3c2b01f2053e8 | change some function names | css.js | css.js | var rework = require('rework')
, npm = require('rework-npm')
, vars = require('rework-vars')
, assets = require('rework-assets')
, path = require('path')
, fs = require('fs')
, events = require('events')
, resolve = require('resolve')
, pkg = require('package-lookup')
, read = function (f) {
return fs.readFileSync(f, 'utf8')
};
var ctor = module.exports = function (opts, cb) {
opts = opts || {};
var src
try {
src = bundle(opts)
} catch (err) {
return process.nextTick(function () { cb(err) })
}
process.nextTick(function () { cb(null, src) })
}
ctor.emitter = new events.EventEmitter()
function bundle (opts) {
var entries = [];
opts.entries.forEach(function (entry) {
var resolvedEntry = resolveFilePath(entry);
entries.push(applyRework(opts, resolvedEntry));
});
return entries.join(opts.compress ? '' : '\n');
}
function applyRework (opts, resolvedEntry) {
var css = rework(read(resolvedEntry), {source: resolvedEntry}),
dirName = path.dirname(resolvedEntry);
css.use(npm({
root: dirName,
prefilter: prefilter
}));
parseCSSVariables(css, opts);
handleAssets (css, opts, dirName);
applyReworkPlugins(css, opts, dirName);
return css.toString({
sourcemap: opts.debug || opts.sourcemap
, compress: opts.compress
});
}
function handleAssets (css, opts, dirName) {
if (opts.assets) {
css.use(assets({
src: dirName
, dest: opts.assets.dest || ''
, prefix: opts.assets.prefix || ''
, retainName: opts.assets.retainName || ''
}))
}
}
function applyReworkPlugins(css, opts, dirName) {
if (opts.plugins) {
opts.plugins.forEach(function (plugin) {
css.use(getPlugin(plugin, dirName))
})
}
}
function parseCSSVariables(css, opts) {
if (typeof opts.variables === 'string') {
var variablesFilePath = resolveFilePath(opts.variables);
opts.variables = readJSON(variablesFilePath);
}
// even if variables were not provided
// use rework-vars to process default values
css.use(vars(opts.variables));
}
function resolveFilePath(filePath) {
return path.resolve(process.cwd(), filePath);
}
function readJSON (filepath) {
var src = read(filepath);
try {
return JSON.parse(src);
} catch(e) {
throw new Error('Unable to parse "' + filepath + '" file (' + e.message + ').', e);
}
}
function getPlugin (plugin, basedir) {
var pluginName
, pluginArgs
, pluginPath
if (typeof plugin === 'string') pluginName = plugin
if (Array.isArray(plugin)) {
pluginName = plugin[0]
pluginArgs = plugin.slice(1)
}
pluginPath = resolve.sync(pluginName, {basedir: basedir})
if (pluginArgs) {
return require(pluginPath).apply(null, pluginArgs)
} else {
return require(pluginPath)
}
}
function prefilter (src, filename) {
var config = pkg.resolve(filename)
ctor.emitter.emit('file', filename)
if (config && config.atomify && config.atomify.css && config.atomify.css.plugins) {
var css = rework(src);
config.atomify.css.plugins.forEach(function (plugin) {
css.use(getPlugin(plugin, path.dirname(filename)))
})
return css.toString()
}
return src
}
| JavaScript | 0.473966 | @@ -1146,32 +1146,30 @@
);%0A%0A
-parseCSSVariable
+applyReworkVar
s(css, o
@@ -1178,22 +1178,27 @@
s);%0A
-handle
+applyRework
Assets (
@@ -1395,14 +1395,19 @@
ion
-handle
+applyRework
Asse
@@ -1875,24 +1875,22 @@
ion
-parseCSSVariable
+applyReworkVar
s(cs
|
487804493e8fcf7a2e5415f177a5acdeebdb75fe | update RNParttenLock | mockup/index.js | mockup/index.js | import React,{ Components } from 'react';
import {
Text
} from 'react-native'
import RNPatternLock from 'react-native-pattern-lock'
export default class MainScreen extends Components{
redner(){
return (
<View>
<RNPatternLock
onStart = { this.onStart }
onEnd = { this.onEnd }
status = 'setting/lock'
/>
</View>
)
}
onStart(){
}
} | JavaScript | 0 | @@ -300,73 +300,223 @@
%09%09%09%09
-status = 'setting/lock'%0A%09%09%09%09/%3E%0A%09%09%09%3C/View%3E%0A%09%09)%0A%09%7D%0A%0A%09onStart()%7B%0A%09%09%0A%09%7D%0A%7D
+type = 'lock'// oneOf%5B%22lock%22,%22set%22,%22confirm%22%5D%0A%09%09%09%09/%3E%0A%09%09%09%3C/View%3E%0A%09%09)%0A%09%7D%0A%0A%09onStart()%7B%0A%09%09%0A%09%7D%0A%0A%09onEnd(ev)%7B%0A%09%09// ev.token%0A%09%09if( ev.token == '12394' )%7B%0A%09%09%09// successHandler()%0A%09%09%7D else %7B%0A%09%09%09RNPatternLock.setError();%0A%09%09%7D%0A%09%7D%0A%7D%0A%0A
|
c6fe21e732d9b9f762a55bebc50e571a46d3819d | update models.index.js | models/index.js | models/index.js | 'use strict';
const Sql = require('sequelize');
/*const sql = new Sql(process.env.DB_LOCAL_NAME, process.env.DB_LOCAL_USER, process.env.DB_LOCAL_PASS, {
host: process.env.DB_LOCAL_HOST,
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
}
});*/
/*const sql = new Sql(process.env.DB_DEV_NAME, process.env.DB_DEV_USER, process.env.DB_DEV_PASS, {
host: process.env.DB_DEV_HOST,
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
dialectOptions: {
encrypt: true
}
});*/
const sql = new Sql(process.env.DB_NAME, process.env.DB_USER, process.env.DB_PASS, {
host: process.env.DB_HOST,
dialect: 'mssql',
pool: {
max: 5,
min: 0,
idle: 10000
},
dialectOptions: {
encrypt: true
}
});
//load models
const models = ['Contact', 'Event', 'EventTab', 'User', 'SiteStyle'];
models.forEach(function(model) {
module.exports[model] = sql.import(__dirname + '/' + model);
});
//export connection
module.exports.sql = sql;
| JavaScript | 0.000001 | @@ -253,24 +253,25 @@
: 10000%0A %7D%0A
+%0A
%7D);*/%0A/*cons
@@ -605,18 +605,16 @@
PASS, %7B%0A
-
host:
|
36474340f989013183c00787c19d162c74772d99 | remove linux line endings when adding new module dependencies | module/index.js | module/index.js | 'use strict';
var fs = require('fs')
, genBase = require('../genBase')
, path = require('path')
, utils = require('../utils');
var Generator = module.exports = genBase.extend();
Generator.prototype.initialize = function initialize() {
this.module = this.name;
};
Generator.prototype.writing = function writing() {
this.context = this.getConfig();
// if moduleName ends with a slash remove it
if (this.module.charAt(this.module.length-1) === '/' || this.module.charAt(this.module.length-1) === '\\') {
this.module = this.module.slice(0, this.module.length-1);
}
this.context.moduleName = path.basename(this.module);
this.context.hyphenModule = utils.hyphenName(this.context.moduleName);
this.context.upperModule = utils.upperCamel(this.context.moduleName);
this.context.parentModuleName = null;
this.context.templateUrl = path.join(this.module).replace(/\\/g, '/');
// create new module directory
this.mkdir(path.join('src', this.module));
var filePath, file;
// check if path and moduleName are the same
// if yes - get root app.js to prepare adding dep
// else - get parent app.js to prepare adding dep
if (this.context.moduleName === this.module) {
filePath = path.join(this.config.path, '../src/app.js');
} else {
var parentDir = path.resolve(path.join('src', this.module), '..');
// for templating to create a parent.child module name
this.context.parentModuleName = path.basename(parentDir);
filePath = path.join(parentDir, this.context.parentModuleName + '.js');
}
file = fs.readFileSync(filePath, 'utf8');
// find line to add new dependency
var lines = file.split('\n')
, angularDefinitionOpenLine = -1
, angularDefinitionCloseLine = -1;
lines.forEach(function (line, i) {
// find line with angular.module('*', [
if (angularDefinitionOpenLine < 0 && line.indexOf('angular.module') > -1) {
angularDefinitionOpenLine = i;
}
// find line with closing ]);
if (angularDefinitionOpenLine > -1 && angularDefinitionCloseLine < 0 && line.indexOf(']);') > -1) {
angularDefinitionCloseLine = i;
}
});
// create moduleName
// if parent module exists, make it part of module name
var moduleName;
if (this.context.parentModuleName) {
moduleName = ' \'' + this.context.parentModuleName + '.' + this.context.moduleName + '\'';
} else {
moduleName = ' \'' + this.context.moduleName + '\'';
}
// remove new line and add a comma to the previous depdendency
lines[angularDefinitionCloseLine-1] = lines[angularDefinitionCloseLine-1].slice(0, lines[angularDefinitionCloseLine-1].lastIndexOf('\n'));
lines[angularDefinitionCloseLine-1] = lines[angularDefinitionCloseLine-1] + ',';
// insert new line and dependency
lines.splice(angularDefinitionCloseLine, 0, moduleName);
// save modifications
fs.writeFileSync(filePath, lines.join('\n'));
// create app.js
this.template('_app.js', path.join('src', this.module, this.context.moduleName + '.js'), this.context);
};
Generator.prototype.end = function end() {
this.invoke('ng-poly:controller', {
args: [this.context.moduleName],
options: {
options: {
module: this.module
}
}
});
this.invoke('ng-poly:view', {
args: [this.context.moduleName],
options: {
options: {
module: this.module
}
}
});
}; | JavaScript | 0.000001 | @@ -2498,24 +2498,88 @@
depdendency%0A
+ // slice at the last quote to remove the varying line endings%0A
lines%5Bangu
@@ -2701,17 +2701,17 @@
dexOf('%5C
-n
+'
'));%0A l
@@ -2785,16 +2785,18 @@
ne-1%5D +
+'%5C
',';%0A%0A
|
447849cc9c34cb8a92abcfcff6603e1b339c5d09 | add return tag for http put | modules/http.js | modules/http.js | var Database = require('../persistence/mongo');
var db = new Database();
var isJson = require('../utils/common').isJson;
var model = require('../models');
var authCheck = require('../auth/basic');
var getAuthInfo = require('./utils/getAuth');
module.exports = function (app) {
app.get(/^\/topics\/(.+)$/, function (req, res) {
if (!req.headers.authorization) {
res.statusCode = 401;
res.setHeader('WWW-Authenticate', 'Basic realm="Secure Area"');
return res.end('Unauthorized');
}
var userInfo = getAuthInfo(req);
var errorCB = function () {
res.sendStatus(403);
};
var successCB = function (user) {
var options = {name: userInfo.name, token: user.uid};
db.query(options, function (dbResult) {
return res.json({'username': userInfo.name, 'topic': dbResult});
});
};
authCheck(userInfo, errorCB, successCB, errorCB);
});
function update(req, res) {
if (!req.headers.authorization) {
return res.sendStatus(403);
}
var userInfo = getAuthInfo(req);
var errorCB = function () {
res.sendStatus(403);
};
var successCB = function (user) {
var payload = {'name': user.name, 'token': user.uid, 'data': req.body};
db.insert(payload);
res.sendStatus(204);
};
authCheck(userInfo, errorCB, successCB, errorCB);
}
app.post(/^\/topics\/(.+)$/, function (req, res) {
return update(req, res);
});
return app.put(/^\/topics\/(.+)$/, function (req, res) {
update(req, res);
});
};
| JavaScript | 0 | @@ -1506,16 +1506,23 @@
) %7B%0A
+return
update(r
|
d16076de3aec7471e12b14806a9e8cfd86e59848 | Remove needless "this." | modules/main.js | modules/main.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
load('lib/WindowManager');
Cu.import('resource://gre/modules/Services.jsm');
const TYPE_BROWSER = 'navigator:browser';
var baseStyleURL = 'chrome://tabsonbottom/skin/base.css';
var platformStyleURL = 'chrome://tabsonbottom/skin/' + Services.appinfo.OS + '.css';
function addStyleSheet(aURL, aWindow) {
var d = aWindow.document;
var pi = d.createProcessingInstruction(
'xml-stylesheet',
'type="text/css" href="'+aURL+'"'
);
d.insertBefore(pi, d.documentElement);
return pi;
}
function FullscreenObserver(aWindow) {
this.window = aWindow;
this.init();
}
FullscreenObserver.prototype = {
get MutationObserver() {
var w = this.window;
return w.MutationObserver || w.MozMutationObserver;
},
init : function FullscreenObserver_onInit() {
if (!this.MutationObserver)
return;
this.observer = new this.MutationObserver((function(aMutations, aObserver) {
this.onMutation(aMutations, aObserver);
}).bind(this));
this.observer.observe(this.window.document.documentElement, { attributes : true });
this.onSizeModeChange();
},
destroy : function FullscreenObserver_destroy() {
if (this.observer) {
this.observer.disconnect();
delete this.observer;
}
delete this.window;
},
onMutation : function FullscreenObserver_onMutation(aMutations, aObserver) {
aMutations.forEach(function(aMutation) {
if (aMutation.type != 'attributes')
return;
if (aMutation.attributeName == 'sizemode')
this.window.setTimeout((function() {
this.onSizeModeChange();
}).bind(this), 10);
}, this);
},
onSizeModeChange : function FullscreenObserver_onSizeModeChange() {
var w = this.window;
var d = w.document;
if (d.documentElement.getAttribute('sizemode') != 'fullscreen')
return;
var toolbox = w.gNavToolbox;
toolbox.style.marginTop = -toolbox.getBoundingClientRect().height + 'px';
var windowControls = d.getElementById('window-controls');
var navigationToolbar = d.getElementById('nav-bar');
if (!windowControls ||
!navigationToolbar ||
windowControls.parentNode == navigationToolbar)
return;
// the location bar is flex=1, so we should not apply it.
// windowControls.setAttribute('flex', '1');
navigationToolbar.appendChild(windowControls);
}
};
function getTabStrip(aTabBrowser) {
if (!(aTabBrowser instanceof Ci.nsIDOMElement))
return null;
var strip = aTabBrowser.mStrip;
return (strip && strip instanceof Ci.nsIDOMElement) ?
strip :
this.evaluateXPath(
'ancestor::xul:toolbar[1]',
aTabBrowser.tabContainer,
Ci.nsIDOMXPathResult.FIRST_ORDERED_NODE_TYPE
).singleNodeValue || aTabBrowser.tabContainer.parentNode;
}
var NSResolver = {
lookupNamespaceURI : function(aPrefix) {
switch (aPrefix) {
case 'xul':
return 'http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul';
case 'html':
case 'xhtml':
return 'http://www.w3.org/1999/xhtml';
case 'xlink':
return 'http://www.w3.org/1999/xlink';
default:
return '';
}
}
};
function evaluateXPath(aExpression, aContext, aType) {
if (!aType)
aType = Ci.nsIDOMXPathResult.ORDERED_NODE_SNAPSHOT_TYPE;
try {
var XPathResult = (aContext.ownerDocument || aContext).evaluate(
aExpression,
(aContext || document),
NSResolver,
aType,
null
);
}
catch(e) {
return {
singleNodeValue : null,
snapshotLength : 0,
snapshotItem : function() {
return null
}
};
}
return XPathResult;
}
function onMozMouseHittest(aEvent) {
// block default behaviors of the tab bar (dragging => window move, etc.)
aEvent.stopPropagation();
}
var baseStyles = new WeakMap();
var platformStyles = new WeakMap();
var fullscreenObservers = new WeakMap();
function handleWindow(aWindow) {
var doc = aWindow.document;
if (doc.documentElement.getAttribute('windowtype') != TYPE_BROWSER)
return;
aWindow.TabsInTitlebar.allowedBy('tabsOnBottom', false);
baseStyles.set(aWindow, addStyleSheet(baseStyleURL, aWindow));
platformStyles.set(aWindow, addStyleSheet(platformStyleURL, aWindow));
fullscreenObservers.set(aWindow, new FullscreenObserver(aWindow));
var strip = getTabStrip(aWindow.gBrowser);
strip.addEventListener('MozMouseHittest', onMozMouseHittest, true); // to block default behaviors of the tab bar
aWindow.addEventListener('unload', function onUnload() {
aWindow.addEventListener('unload', onUnload, false);
strip.removeEventListener('MozMouseHittest', onMozMouseHittest, true);
baseStyles.delete(aWindow);
platformStyles.delete(aWindow);
fullscreenObservers.get(aWindow).destroy();
fullscreenObservers.delete(aWindow);
}, false);
}
WindowManager.getWindows(TYPE_BROWSER).forEach(handleWindow);
WindowManager.addHandler(handleWindow);
function shutdown() {
WindowManager.getWindows(TYPE_BROWSER).forEach(function(aWindow) {
aWindow.TabsInTitlebar.allowedBy('tabsOnBottom', true);
aWindow.document.removeChild(baseStyles.get(aWindow));
baseStyles.delete(aWindow);
aWindow.document.removeChild(platformStyles.get(aWindow));
platformStyles.delete(aWindow);
fullscreenObservers.get(aWindow).destroy();
fullscreenObservers.delete(aWindow);
});
WindowManager = undefined;
baseStyles = undefined;
platformStyles = undefined;
}
| JavaScript | 0.000712 | @@ -2738,21 +2738,16 @@
p :%0D%0A%09%09%09
-this.
evaluate
|
c366fabc81d60b9ce641ce6756f78896d45dcd3c | Add license header for MPL 2.0 | modules/main.js | modules/main.js | var BASE = '[email protected].';
var prefs = require('lib/prefs').prefs;
function log(message) {
if (prefs.getPref(BASE + 'debug')) {
console.log("auto-confirm: " + message);
}
}
load('lib/WindowManager');
var global = this;
function handleWindow(aWindow)
{
log("handleWindow");
var doc = aWindow.document;
if (doc.documentElement.localName === 'dialog' &&
doc.documentElement.id === 'commonDialog') {
handleCommonDialog(aWindow);
return;
}
}
function handleCommonDialog(aWindow)
{
log("commonDialog");
aWindow.setTimeout(function() {
log("cancelDialog");
doc.documentElement.cancelDialog();
}, 10000);
}
WindowManager.addHandler(handleWindow);
function shutdown()
{
WindowManager = undefined;
global = undefined;
}
| JavaScript | 0 | @@ -1,12 +1,218 @@
+/*%0A# This Source Code Form is subject to the terms of the Mozilla Public%0A# License, v. 2.0. If a copy of the MPL was not distributed with this%0A# file, You can obtain one at http://mozilla.org/MPL/2.0/.%0A*/%0A%0A
var BASE = '
|
4a88d4bd74051d19202c8071573d28831fcbe5a4 | Load required library correctly | modules/main.js | modules/main.js | var BASE = '[email protected].';
var prefs = require('lib/prefs').prefs;
prefs.setDefaultPref(BASE + 'anonymize', false);
prefs.setDefaultPref(BASE + 'intervalSeconds', 60);
{
let dir = Cc['@mozilla.org/file/directory_service;1']
.getService(Components.interfaces.nsIProperties)
.get('Home', Components.interfaces.nsIFile);
dir.append('firefox-memory-usage');
prefs.setDefaultPref(BASE + 'outputDirectory', dir.path);
}
var timer = Cu.import('resource://gre/modules/Timer.jsm');
var Promise = Cu.import('resource://gre/modules/Promise.jsm');
function generateDumpFilename() {
var now = new Date();
var timestamp = now.toISOString().replace(/:/g, '-');
return timestamp + '.json.gz';
}
function prepareDirectory(aDir) {
if (aDir.parent && !aDir.parent.exists())
prepareDirectory(aDir.parent);
aDir.create(Ci.nsIFile.DIRECTORY_TYPE, 0600);
}
function dumpMemoryUsage() {
console.log('dump start');
return new Promise(function(resolve, reject) {
var localName = generateDumpFilename();
var file = Cc['@mozilla.org/file/local;1']
.createInstance(Ci.nsILocalFile);
file.initWithPath(prefs.getPref(BASE + 'outputDirectory'));
file.append(localName);
prepareDirectory(file.parent);
var anonymize = prefs.getPref(BASE + 'anonymize');
var start = Date.now();
var dumper = Cc['@mozilla.org/memory-info-dumper;1']
.getService(Ci.nsIMemoryInfoDumper);
dumper.dumpMemoryReportsToNamedFile(file.path, function() {
console.log('dump finish (' + ((Date.now() - start) / 1000) + 'sec.)');
resolve();
}, null, anonymize);
});
}
var lastTimeout;
function onTimeout() {
dumpMemoryUsage()
.then(function() {
var interval = Math.max(1, prefs.getPref(BASE + 'intervalSeconds'));
lastTimeout = timer.setTimeout(onTimeout, interval * 1000);
});
}
onTimeout();
function shutdown() {
if (lastTimeout)
timer.clearTimeout(lastTimeout);
timer = Promise = prefs =
dumpMemoryUsage = lastTimeout = onTimeout =
undefined;
}
| JavaScript | 0.000001 | @@ -550,24 +550,26 @@
');%0D%0Avar
+ %7B
Promise
= Cu.im
@@ -560,16 +560,18 @@
Promise
+ %7D
= Cu.im
|
36aaecbe05096648e573f7711e7bc5b52cc286bc | send http error response code when there is an error rather than just the message | musselrunner.js | musselrunner.js | 'use strict';
var Mussel = require('./index.js');
var express = require("express");
var bunyan = require('bunyan');
var log = bunyan.createLogger({name: "musselrunner"});
var app = express();
app.get("/auths/:userid", function(req, res) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
var auths = mussel.getAuths(req.params.userid, function(err, response) {
if (err) {
log.warn(err, "Error getting authorizations");
res.send(err);
} else {
res.send(response);
}
});
});
app.get("/deauthorize/:shim", function(req, res) {
var username = req.query.username;
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
mussel.deauthorize(req.params.shim, username, function(err, response) {
if (err) {
log.warn(err, "Error deauthorizing");
res.send(err);
} else{
res.send(response);
}
});
});
var SHIMMER_HOST=process.env.SHIMMER_HOST;
var TIDEPOOL_HOST=process.env.TIDEPOOL_HOST;
var TIDEPOOL_UPLOAD_HOST=process.env.TIDEPOOL_UPLOAD_HOST;
var UPLOADER_LOGIN=process.env.UPLOADER_LOGIN;
var UPLOADER_PASSWORD=process.env.UPLOADER_PASSWORD;
var UPLOADER_USERID=process.env.UPLOADER_USERID;
var tidepoolConfig = {
host: TIDEPOOL_HOST,
uploadApi: TIDEPOOL_UPLOAD_HOST,
uploaderDetails: {uploaderLogin:UPLOADER_LOGIN, uploaderPassword:UPLOADER_PASSWORD, uploaderUserId: UPLOADER_USERID }
};
var shimmerConfig = {'host':SHIMMER_HOST};
log.info('TidePool Config:');
log.info(tidepoolConfig);
log.info('Shimmer Config:');
log.info(shimmerConfig);
function syncActivities() {
var mussel = new Mussel(shimmerConfig, tidepoolConfig);
var users = mussel.getUsers(function(err, users){
if (err) {
log.warn(err, "Error getting users");
} else {
log.info(users);
for (var i=0; i< users.length; i++) {
var omhUser = users[i].username;
var split = omhUser.split('|');
if (split < 3 || split[0] != 'tp') {
//ignore records that are not in proper format
continue;
}
var tpUserId = split[1];
log.info('\nSyncing data for Tidepool user:'+tpUserId);
for (var j=0; j< users[i].auths.length; j++) {
var shim = users[i].auths[j];
syncUser(omhUser, shim, tpUserId);
}
}
}
});
}
function syncUser(omhUser, shim, tpUserId) {
log.info('\nSyncing data for Tidepool user:'+tpUserId);
log.info('Syncing from OMH user:'+omhUser);
log.info('For Device:'+shim+'\n\n');
mussel.syncNewActivityData(omhUser, shim, tpUserId, done);
}
function done(err, response) {
if (err != null) {
console.log(err);
} else {
//console.log('handles:')
console.log(response);
//console.log(process._getActiveHandles());
//process.exit();
}
return;
}
var mussel = new Mussel(shimmerConfig, tidepoolConfig);
switch(process.argv[2]) {
case 'sync':
console.log('Syncing activities');
exitAfter(30000);
syncActivities();
break;
case 'syncuser':
syncUser(process.argv[3], process.argv[4], process.argv[5]);
exitAfter(30000);
break;
case 'delete':
console.log('Deleting activity notes');
exitAfter(30000);
mussel.deleteActivityNotes(process.argv[3], done);
break;
case 'service':
var port = process.env.PORT || 5000;
app.listen(port, function() {
console.log("Listening on " + port);
});
break;
default:
console.log('Incorrect arguments');
console.log('Usage:');
console.log('node musselrunner.js sync');
console.log('or');
console.log('node musselrunner.js syncuser omhUserid, shim, tidepoolUserId');
console.log('or');
console.log('node musselrunner.js delete userid');
console.log('or');
console.log('node musselrunner.js service');
}
function exitAfter(millis) {
setTimeout(function() {
console.log('exiting');
process.exit();
}, millis);
}
var now = new Date();
var twoMonthsAgo = new Date();
twoMonthsAgo.setMonth(twoMonthsAgo.getMonth() - 3);
//syncUser("tp|2e55bc37d7|https://devel-api.tidepool.io", "jawbone", "2e55bc37d7");
/**
mussel.getActivityData("tp|0e5fab3f1a|https://devel-api.tidepool.io", "runkeeper", twoMonthsAgo.toISOString(), now.toISOString(), function(err, response) {
mussel.transformActivitiesToTidepoolActivities(response, function(err, response) {
//console.log(response);
var objects = response;
mussel.login(function(err, response) {
if (err) {
console.log("error logging in - exiting")
process.exit();
} else {
console.log("attempting to write objects:"+objects.length)
mussel.writeTPActivities_ToObjects(objects, "2e55bc37d7", "", function(err, response) {
if (err) {
console.log("write unsuccesful")
console.log(err);
}
else {
console.log("write succesful")
console.log(response);
}
})
}
})
})
})
**/
/**
mussel.login(function(err, response) {
mussel.getLastActivity_FromObjects("2e55bc37d7","jawbone", function(err, response) {
if (err) {
console.log("error:");
console.log(err)
} else {
//console.log(response);
}
})
})
**/
| JavaScript | 0 | @@ -487,32 +487,92 @@
ns%22);%0A%09%09res.
+status(500).
send(
+%7B
err
+or: 'unable to retrieve auths', errorMsg:err %7D
);%0A%09%7D else %7B
@@ -946,16 +946,73 @@
res.
+status(500).
send(
+%7B
err
+or: 'unable to deauthorize', errorMsg:err %7D
);%0A%09
|
771e143643b1aaeeb84e917b8379d1d5f7645d7a | drop examples/ | build/examples.js | build/examples.js | var rollup = require('rollup')
var buble = require('rollup-plugin-buble')
var json = require('rollup-plugin-json')
var commonjs = require('rollup-plugin-commonjs')
var eslint = require('rollup-plugin-eslint')
var nodeResolve = require('rollup-plugin-node-resolve')
var uglify = require('rollup-plugin-uglify')
var build = function (opts) {
rollup.rollup({
entry: opts.entry,
plugins: [eslint(), json(), buble(), commonjs(), nodeResolve(), uglify()]
}).then(function (bundle) {
bundle.write({
format: 'cjs',
dest: opts.output
})
}).catch(function (err) {
console.error(err)
})
}
var examples = ['basic']
examples.forEach(example => {
build({
entry: `docs/examples/${ example }/index.js`,
output: `docs/examples/${ example }/index.min.js`
})
})
| JavaScript | 0 | @@ -633,15 +633,8 @@
= %5B
-'basic'
%5D%0Aex
|
f726173e824966e1e055bdfeb377641120aef57c | call watch native | src/Namster/gulpfile.js | src/Namster/gulpfile.js | /// <binding BeforeBuild='webpack:build, min:css' Clean='clean' />
"use strict";
var gulp = require("gulp"),
debug = require("gulp-debug"),
util = require("gulp-util"),
rimraf = require("rimraf"),
merge = require("merge-stream"),
concat = require("gulp-concat"),
rename = require("gulp-rename"),
sass = require("gulp-sass"),
cssmin = require("gulp-cssmin"),
uglify = require("gulp-uglify"),
webpack = require("webpack"),
sourcemaps = require("gulp-sourcemaps");
var webpackConfig = require("./webpack.config.js");
var paths = {
webroot: "./wwwroot/"
};
paths.js = paths.webroot + "js/**/*.js";
paths.jsx = paths.webroot + "js/**/*.jsx";
paths.minJs = paths.webroot + "js/**/*.min.js";
paths.sass = paths.webroot + "sass/**/*.scss";
paths.css = paths.webroot + "css";
paths.concatJsDest = paths.webroot + "js/site.js";
paths.concatJsMinDest = paths.webroot + "js/site.min.js";
paths.concatCssDest = paths.webroot + "css/site.min.css";
gulp.task("clean:js", function (cb) {
rimraf(paths.concatJsDest, cb);
});
gulp.task("clean:css", function (cb) {
rimraf(paths.concatCssDest, cb);
});
gulp.task("clean", ["clean:js", "clean:css"]);
gulp.task("build:js", function (callback) {
var myConfig = Object.create(webpackConfig);
webpack(myConfig, function(err, stats) {
util.log('[build:js]', stats.toString({
colors: true
}));
callback();
});
});
gulp.task("watch:js", function() {
var myConfig = Object.create(webpackConfig);
myConfig.watch = true;
webpack(myConfig, function (err, stats) {
util.log('[watch:js]', stats.toString({
colors: true
}));
});
});
gulp.task("min:css", function () {
return gulp.src([paths.sass])
.pipe(sourcemaps.init()) // start source maps
.pipe(sass()) // compile sass
.pipe(rename({ // with new directory, filename ext
dirname: paths.css,
extname: '.css'}))
.pipe(sourcemaps.write()) // create sourcemaps
.pipe(gulp.dest(".")) // write out compiled files
.pipe(concat(paths.concatCssDest)) // concat + min
.pipe(cssmin())
.pipe(gulp.dest("."));
});
gulp.task("build", ["min:css", "build:js"]);
gulp.task("watch", function() {
gulp.watch([paths.js, paths.jsx], ["watch:js"]);
gulp.watch([paths.sass], ["min:css"]);
}); | JavaScript | 0.000001 | @@ -2042,22 +2042,16 @@
.css'%7D))
-
%0A
@@ -2179,21 +2179,16 @@
ed files
-
%0A
@@ -2304,54 +2304,8 @@
);%0A%0A
-gulp.task(%22build%22, %5B%22min:css%22, %22build:js%22%5D);%0A%0A
gulp
@@ -2316,16 +2316,20 @@
k(%22watch
+:css
%22, funct
@@ -2362,39 +2362,79 @@
ths.
-js, paths.jsx%5D, %5B%22watch
+sass%5D, %5B%22min:css%22%5D);%0A%7D);%0A%0Agulp.task(%22build%22, %5B%22min:css%22, %22build
:js%22%5D);%0A
@@ -2433,50 +2433,52 @@
%5D);%0A
-
+%0A
gulp.
-watch(%5Bpaths.sass%5D, %5B%22min:cs
+task(%22watch%22, %5B%22watch:css%22, %22watch:j
s%22%5D);%0A
-%7D);
|
cd56d41c1e668a5491627f2dab9e0d349e928f1d | Remove progress print statement | src/Native/Benchmark.js | src/Native/Benchmark.js | Elm.Native.Benchmark = {};
Elm.Native.Benchmark.make = function(localRuntime) {
localRuntime.Native = localRuntime.Native || {};
localRuntime.Native.Benchmark = localRuntime.Native.Benchmark || {};
if (localRuntime.Native.Benchmark.values)
{
return localRuntime.Native.Benchmark.values;
}
//var Dict = Elm.Dict.make(localRuntime);
var List = Elm.Native.List.make(localRuntime);
//var Maybe = Elm.Maybe.make(localRuntime);
var Task = Elm.Native.Task.make(localRuntime);
var Signal = Elm.Signal.make(localRuntime);
var Utils = Elm.Native.Utils.make(localRuntime);
function makeBenchmark(name, thunk)
{
return {name : name, thunk : thunk};
}
function runWithProgress(maybeTaskFn, inSuite)
{
return Task.asyncFunction(function(callback) {
var bjsSuite = new Benchmark.Suite;
var benchArray;
var retData = [];
var finalString = "";
Task.perform(maybeTaskFn("Starting Benchmarks"));
switch (inSuite.ctor)
{
case "Suite":
benchArray = List.toArray(inSuite._1);
break;
case "SingleBenchmark":
benchArray = [inSuite._0 ];
break;
}
for (i = 0; i < benchArray.length; i++)
{
var ourThunk = function (){
//Run the thing we're timing, then mark the asynch benchmark as done
benchArray[i].thunk();
deferred.resolve();
}
bjsSuite.add(benchArray[i].name, benchArray[i].thunk );
}
bjsSuite.on('cycle', function(event) {
retData.push(
{ name : event.target.options.name
, hz : event.target.hz
, marginOfError : event.target.stats.moe
, moePercent : event.target.stats.rme
}
);
finalString += String(event.target) + "\n";
console.log("Progress ");
var intermedString = String(event.target);
Task.perform(maybeTaskFn(intermedString));
//retString += String(event.target) + "\n";
});
bjsSuite.on('complete', function(event) {
finalString = "Final results:\n\n" + finalString;
Task.perform(maybeTaskFn(finalString) );
return callback(Task.succeed(Utils.Tuple2(finalString, retData)));
});
Task.perform(
Task.asyncFunction(function(otherCallback){
bjsSuite.run({ 'async': true });
}));
});
}
return localRuntime.Native.Benchmark.values = {
makeBenchmark: F2(makeBenchmark),
runWithProgress: F2(runWithProgress)
};
};
| JavaScript | 0.000005 | @@ -2220,53 +2220,8 @@
n%22;%0A
- console.log(%22Progress %22);%0A
|
f4195e841462783670decf6658f0ded3ef3d073c | Update DNSTool.js | net2/DNSTool.js | net2/DNSTool.js | /* Copyright 2016 Firewalla LLC
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License, version 3,
* as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
'use strict';
const log = require('./logger.js')(__filename);
const rclient = require('../util/redis_manager.js').getRedisClient()
const Promise = require('bluebird');
const iptool = require('ip')
const util = require('util');
const firewalla = require('../net2/Firewalla.js');
const RED_HOLE_IP="198.51.100.101";
let instance = null;
class DNSTool {
constructor() {
if(!instance) {
instance = this;
if(firewalla.isProduction()) {
this.debugMode = false;
} else {
this.debugMode = true;
}
}
return instance;
}
getDNSKey(ip) {
return util.format("dns:ip:%s", ip);
}
getReverseDNSKey(dns) {
return `rdns:domain:${dns}`
}
async reverseDNSKeyExists(domain) {
const type = await rclient.typeAsync(this.getReverseDNSKey(domain))
return type !== 'none';
}
dnsExists(ip) {
let key = this.getDnsKey(ip);
return rclient.existsAsync(key)
.then((exists) => {
return exists == 1
})
}
getDns(ip) {
let key = this.getDnsKey(ip);
return rclient.hgetallAsync(key);
}
addDns(ip, dns, expire) {
dns = dns || {}
expire = expire || 7 * 24 * 3600; // one week by default
let key = this.getDnsKey(ip);
dns.updateTime = `${new Date() / 1000}`
return rclient.hmsetAsync(key, dns)
.then(() => {
return rclient.expireAsync(key, expire);
});
}
// doesn't have to keep it long, it's only used for instant blocking
async addReverseDns(dns, addresses, expire) {
expire = expire || 24 * 3600; // one day by default
addresses = addresses || []
addresses = addresses.filter((addr) => {
return f.isReservedBlockingIP(addr) != true
})
let key = this.getReverseDNSKey(dns)
const existing = await this.reverseDNSKeyExists(dns)
let updated = false
for (let i = 0; i < addresses.length; i++) {
const addr = addresses[i];
if(iptool.isV4Format(addr) || iptool.isV6Format(addr)) {
await rclient.zaddAsync(key, new Date() / 1000, addr)
updated = true
}
}
if(updated === false && existing === false) {
await rclient.zaddAsync(key, new Date() / 1000, RED_HOLE_IP); // red hole is a placeholder ip for non-existing domain
}
await rclient.expireAsync(key, expire)
}
async getAddressesByDNS(dns) {
let key = this.getReverseDNSKey(dns)
return rclient.zrangeAsync(key, "0", "-1")
}
async getAddressesByDNSPattern(dnsPattern) {
let pattern = `rdns:domain:*.${dnsPattern}`
let keys = await rclient.keysAsync(pattern)
let list = []
if(keys) {
for (let i = 0; i < keys.length; i++) {
const key = keys[i];
let l = await rclient.zrangeAsync(key, "0", "-1")
list.push.apply(list, l)
}
}
return list
}
removeDns(ip) {
let key = this.getDnsKey(ip);
return rclient.delAsync(key);
}
getDNS(ip) {
let key = this.getDNSKey(ip);
return rclient.hgetallAsync(key);
}
}
module.exports = DNSTool;
| JavaScript | 0 | @@ -2347,16 +2347,24 @@
return f
+irewalla
.isReser
|
244ad114563f2ad936765239cc5a7e7a46fbf629 | Use arrow functions | src/Native/websocket.js | src/Native/websocket.js | // Elm globals (some for elm-native-helpers and some for us and some for the future)
const E = {
A2: A2,
A3: A3,
A4: A4,
Scheduler: {
nativeBinding: _elm_lang$core$Native_Scheduler.nativeBinding,
succeed: _elm_lang$core$Native_Scheduler.succeed,
fail: _elm_lang$core$Native_Scheduler.fail,
rawSpawn: _elm_lang$core$Native_Scheduler.rawSpawn
},
List: {
fromArray: _elm_lang$core$Native_List.fromArray
},
Maybe: {
Nothing: _elm_lang$core$Maybe$Nothing,
Just: _elm_lang$core$Maybe$Just
},
Result: {
Err: _elm_lang$core$Result$Err,
Ok: _elm_lang$core$Result$Ok
}
};
// This module is in the same scope as Elm but all modules that are required are NOT
// So we must pass elm globals to it (see https://github.com/panosoft/elm-native-helpers for the minimum of E)
const helper = require('@panosoft/elm-native-helpers/helper')(E);
const _panosoft$elm_websocket_browser$Native_Websocket = function() {
//////////////////////////////////////////////////////////////////////////////////////////////////////////
// Cmds
const _connect = (url, openCb, messageCb, connectionClosedCb, cb) => {
try {
const ws = new WebSocket(url);
var open = false;
ws.addEventListener('open', _ => open = true, E.Scheduler.rawSpawn(A2(openCb, url, ws)));
ws.addEventListener('message', event => E.Scheduler.rawSpawn(messageCb(event.data)));
ws.addEventListener('close', _ => open ? E.Scheduler.rawSpawn(connectionClosedCb()) : null);
cb();
}
catch (err) {
cb(err.message)
}
};
const _send = (ws, message, cb) => {
try {
ws.send(message);
cb();
}
catch (err) {
cb(err.message)
}
};
const _disconnect = (ws, cb) => {
try {
ws.close();
cb()
}
catch (err) {
cb(err.message);
}
};
const connect = helper.call4_0(_connect);
const send = helper.call2_0(_send);
const disconnect = helper.call1_0(_disconnect);
return {
///////////////////////////////////////////
// Cmds
connect: F5(connect),
send: F3(send),
disconnect: F2(disconnect)
///////////////////////////////////////////
// Subs
};
}();
// for local testing
const _user$project$Native_Websocket = _panosoft$elm_websocket_browser$Native_Websocket;
| JavaScript | 0.000003 | @@ -908,18 +908,12 @@
t =
-function()
+_ =%3E
%7B%0A
|
4a66ec6b933c6971e6bd547b9a443b0006369855 | Improve persistence testing | src/Persistence.test.js | src/Persistence.test.js | import PersistenceManager from "./Persistence";
class LocalStorage {
constructor() {
this.data = {};
}
getItem(key) {
return this.data[key] || null;
}
setItem(key, value) {
this.data[key] = value;
}
}
it("can get default", () => {
const defaultValue = [];
const man = new PersistenceManager({
factory: () => new LocalStorage(),
key: "something",
default: defaultValue
});
expect(man.get()).toEqual(defaultValue);
});
it("can get what was set", () => {
const defaultValue = [];
const man = new PersistenceManager({
factory: () => new LocalStorage(),
key: "something",
default: defaultValue
});
const value = [0];
man.set(value);
expect(man.get()).toEqual(value);
});
it("works when factory raises", () => {
const defaultValue = "thing";
const man = new PersistenceManager({
factory: () => {throw new Error("just error")},
key: "somekey",
default: defaultValue
});
const value = [0];
man.set(value);
expect(man.get()).toEqual(defaultValue);
});
it("saves value into and reads value from storage", () => {
const storage = new LocalStorage();
const key = "somek";
const defaultValue = [];
const man = new PersistenceManager({
factory: () => storage,
key: key,
default: defaultValue
});
const value = [0];
expect(storage.getItem(key)).toBeNull();
expect(man.get()).toEqual(defaultValue);
expect(storage.getItem(key)).toBeNull();
man.set(value);
expect(storage.getItem(key)).toEqual(JSON.stringify(value));
expect(man.get()).toEqual(value);
});
it("gets value saved into storage", () => {
const storage = new LocalStorage();
const args = {
factory: () => storage, // same storage
key: "otherk",
default: []
};
const value = [0];
const man1 = new PersistenceManager(args);
expect(man1.get()).toEqual(args.default);
man1.set(value);
expect(man1.get()).toEqual(value);
const man2 = new PersistenceManager(args);
expect(man2.get()).toEqual(value);
});
| JavaScript | 0.000006 | @@ -93,24 +93,25 @@
this.
+_
data = %7B%7D;%0A
@@ -151,24 +151,25 @@
return this.
+_
data%5Bkey%5D %7C%7C
@@ -221,16 +221,17 @@
this.
+_
data%5Bkey
@@ -1722,18 +1722,21 @@
ue s
-aved
+et
into
+same
stor
@@ -1843,25 +1843,8 @@
age,
- // same storage
%0A
|
d5f29b64938e65561352ce8ca79edf1169cfac35 | Rename variable, to make fetching multiple URLs clearer | djofx/static/djofx/charts/monthly.js | djofx/static/djofx/charts/monthly.js | function refresh_transaction_list(data) {
$("#transaction_list").html(data);
}
function plot_bar_chart() {
var data = [
{
label: "Income",
data: flotise_years_and_months(income),
lines: {
show: true
},
points: {
show: true
}
},
{
label: "Outgoings",
data: flotise_years_and_months(outgoings),
bars: {
show: true,
barWidth: 0.5 * 1000 * 60 * 60 * 24 * 30, // milliseconds in roughly half a month
align: "center",
order: 1
}
}
];
var options = {
grid: {
hoverable: true,
clickable: true
},
xaxis: {
mode: "time",
timeformat: "%b %Y",
tickSize: [1, "month"]
},
yaxis: {
tickFormatter: format_currency_value,
}
};
$.plot("#placeholder", data, options);
$("#placeholder").bind("plotclick", function (event, pos, item) {
if (item) {
var thedate = new Date(item.datapoint[0]);
var series = item.series.label;
// January is 0, because Javascript
var themonth = thedate.getMonth() + 1;
if (themonth < 10) {
themonth = '0' + themonth;
}
var theyear = '' + thedate.getFullYear();
var theurl = Urls.djofx_transaction_list(series, theyear, themonth)
$.ajax({
type: "GET",
url: theurl,
success: refresh_transaction_list
});
}
});
}
$(document).ready(plot_bar_chart);
| JavaScript | 0.000001 | @@ -1460,18 +1460,28 @@
var t
-he
+ransactions_
url = Ur
@@ -1605,18 +1605,28 @@
url: t
-he
+ransactions_
url,%0A
|
d5a36823a5c5366199636afd8eef978870def2a8 | add demo credentials | examples/basic/app.js | examples/basic/app.js | import React, { PropTypes, Component } from 'react';
import algoliasearch from 'algoliasearch';
import AlgoliaInput from '../../lib/index';
const algoliaClient = algoliasearch('APPLICATION_ID', 'SEARCH_ONLY_API_KEY');
class App extends Component {
constructor(...args) {
super(...args);
this.state = {
hits: []
};
}
onError() {
console.log('onError', arguments);
}
onResults(content) {
this.setState({
hits: content.hits
});
}
render() {
return (
<div className="example">
<h1>algolia-react-input</h1>
<AlgoliaInput client={ algoliaClient } index='test' onResults={ ::this.onResults } onError={ ::this.onError }/>
<hr/>
{ this.state.hits.map(hit => <li ref={ hit.objectID }>{ hit.name || hit.title }</li> ) }
</div>
);
}
};
React.render(<App/>, document.getElementById('container'));
| JavaScript | 0.000001 | @@ -178,45 +178,51 @@
ch('
-APPLICATION_ID', 'SEARCH_ONLY_API_KEY
+latency', '6be0576ff61c053d5f9a3225e2a90f76
');%0A
@@ -632,12 +632,22 @@
ex='
-test
+instant_search
' on
|
50f0be6e2e5a1035de48c72ce1e63fded6617108 | add no-token scenario to admin service | imports/graphql/bll/adminService.js | imports/graphql/bll/adminService.js | export default class AdminService {
constructor(props) {
this.token = props.token;
this.user = Meteor.users.findOne({
'services.resume.loginTokens.hashedToken': Accounts._hashLoginToken(props.token),
});
this.userIsAdmin = this.user.roles.indexOf('admin') !== -1;
}
} | JavaScript | 0.000001 | @@ -1,8 +1,58 @@
+import %7B Accounts %7D from 'meteor/accounts-base';%0A%0A
export d
@@ -127,16 +127,35 @@
ps.token
+ ? props.token : ''
;%0A%09%09this
@@ -256,20 +256,19 @@
inToken(
-prop
+thi
s.token)
@@ -295,16 +295,28 @@
sAdmin =
+ this.user ?
this.us
@@ -347,14 +347,22 @@
) !== -1
+ : false
;%0A%09%7D%0A%7D
|
ceded7193726727daafef3ea0677c92fdc01f94b | fix splitting of config vars with = in them | packages/heroku-apps/commands/config/set.js | packages/heroku-apps/commands/config/set.js | 'use strict';
let cli = require('heroku-cli-util');
let co = require('co');
let extend = require('util')._extend;
let _ = require('lodash');
function* run (context, heroku) {
let vars = _.reduce(context.args, function (vars, v) {
if (v.indexOf('=') === -1) {
cli.error(`${cli.color.cyan(v)} is invalid. Must be in the format ${cli.color.cyan('FOO=bar')}.`);
process.exit(1);
}
v = v.split('=');
vars[v[0]] = v[1];
return vars;
}, {});
let p = heroku.request({
method: 'patch',
path: `/apps/${context.app}/config-vars`,
body: vars,
});
yield cli.action(`Setting config vars and restarting ${context.app}`, p);
}
let cmd = {
topic: 'config',
command: 'set',
description: 'set one or more config vars',
help: `Examples:
$ heroku config:set RAILS_ENV=staging
Setting config vars and restarting example... done
RAILS_ENV: staging
$ heroku config:set RAILS_ENV=staging RACK_ENV=staging
Setting config vars and restarting example... done
RAILS_ENV: staging
RACK_ENV: staging
`,
needsApp: true,
needsAuth: true,
variableArgs: true,
run: cli.command(co.wrap(run))
};
module.exports.set = cmd;
module.exports.add = extend({}, cmd);
module.exports.add.command = 'add';
| JavaScript | 0.000001 | @@ -148,16 +148,210 @@
ash');%0A%0A
+function split(str, delim) %7B%0A var components = str.split(delim);%0A var result = %5Bcomponents.shift()%5D;%0A if(components.length) %7B%0A result.push(components.join(delim));%0A %7D%0A return result;%0A%7D%0A%0A
function
@@ -612,16 +612,17 @@
v =
-v.
split(
+v,
'=')
|
c521d77ff730e91eae66d73ab748591ff5b535f6 | replace deprecated unescape() with decodeURIComponent() | node_example.js | node_example.js | var crypto = require('crypto');
var querystring = require('querystring')
function nonce(len) {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < len; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
function forceUnicodeEncoding(string) {
return unescape(encodeURIComponent(string));
}
function created_signed_embed_url(options) {
// looker options
var secret = options.secret;
var host = options.host;
// user options
var json_external_user_id = JSON.stringify(options.external_user_id);
var json_first_name = JSON.stringify(options.first_name);
var json_last_name = JSON.stringify(options.last_name);
var json_permissions = JSON.stringify(options.permissions);
var json_models = JSON.stringify(options.models);
var json_access_filters = JSON.stringify(options.access_filters);
// url/session specific options
var embed_path = '/login/embed/' + encodeURIComponent(options.embed_url);
var json_session_length = JSON.stringify(options.session_length);
var json_force_logout_login = JSON.stringify(options.force_logout_login);
// computed options
var json_time = JSON.stringify(Math.floor((new Date()).getTime() / 1000));
var json_nonce = JSON.stringify(nonce(16));
// compute signature
var string_to_sign = "";
string_to_sign += host + "\n";
string_to_sign += embed_path + "\n";
string_to_sign += json_nonce + "\n";
string_to_sign += json_time + "\n";
string_to_sign += json_session_length + "\n";
string_to_sign += json_external_user_id + "\n";
string_to_sign += json_permissions + "\n";
string_to_sign += json_models + "\n";
string_to_sign += json_access_filters;
var signature = crypto.createHmac('sha1', secret).update(forceUnicodeEncoding(string_to_sign)).digest('base64').trim();
// construct query string
var query_params = {
nonce: json_nonce,
time: json_time,
session_length: json_session_length,
external_user_id: json_external_user_id,
permissions: json_permissions,
models: json_models,
access_filters: json_access_filters,
first_name: json_first_name,
last_name: json_last_name,
force_logout_login: json_force_logout_login,
signature: signature
};
var query_string = querystring.stringify(query_params);
return host + embed_path + '?' + query_string;
}
function sample() {
var fifteen_minutes = 15 * 60;
var url_data = {
host: 'company.looker.com',
secret: '8ea3be011d0668741234216e06845692bab69e0101d00dcfe399dae03c52513c',
external_user_id: '57',
first_name: 'Embed Steve',
last_name: 'Krouse',
permissions: ['see_user_dashboards', 'see_lookml_dashboards', 'access_data', 'see_looks'],
models: ['thelook'],
access_filters: {
fake_model: {
id: 1
}
},
session_length: fifteen_minutes,
embed_url: "/embed/sso/dashboards/1",
force_logout_login: true
};
var url = created_signed_embed_url(url_data);
return "https://" + url;
}
var http = require('http');
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/html'});
var url = sample();
res.end("<a href='" + url + "'>" + url + "</a>");
}).listen(1337, '127.0.0.1');
console.log('Server running at http://127.0.0.1:1337/');
| JavaScript | 0.000016 | @@ -380,16 +380,26 @@
urn
-unescape
+decodeURIComponent
(enc
|
f1d89d3ff7b64c498ded8d06263db71caf3b182c | Fix error handling | src/SqsBrokerFacade.es6 | src/SqsBrokerFacade.es6 | import AWS from 'aws-sdk';
import Consumer from 'sqs-consumer';
import Producer from 'sqs-producer';
import EventeEmitter from 'events';
import ResponseStatus from './ResponseStatus';
export default class SqsBrokerFacade extends EventeEmitter {
constructor(options) {
super();
this._options = options;
this._sqs = new AWS.SQS({
region: options.region,
accessKeyId: options.accessKeyId,
secretAccessKey: options.secretAccessKey
});
this._listeners = {};
}
_ensureQueue(name) {
return new Promise((resolve, reject) => {
var params = {
QueueName: name
};
this._sqs.createQueue(params, function(err, data) {
if (err) return reject(err);
resolve(data.QueueUrl);
});
});
}
async _setupRequestProducer(domain, lane) {
let queueUrl = await this._ensureQueue(`${domain}-${lane}-req`);
let producer = Producer.create({
sqs: this._sqs,
queueUrl: queueUrl
});
return producer;
}
_processResponseMessage(message, done) {
let response = {
requestUid: message.MessageAttributes.requestUid.StringValue,
payload: JSON.parse(message.Body),
acknowledge: done
};
let status = message.MessageAttributes.status.StringValue;
this.emit('info', 'response message received');
let listener = this._listeners[response.requestUid];
delete this._listeners[response.requestUid];
if(!listener) {
done(new Error('No handler for the response'));
this.emit('info', `Response for request uid ${response.requestUid} died silently`);
return;
}
if( status == ResponseStatus.INTERNAL_ERROR ){
done();
let error = new Error(response.payload.message);
error.serviceStack = response.payload.stack;
throw error;
}
listener(response);
}
async _setupResponseConsumer(domain, lane) {
let queueUrl = await this._ensureQueue(`${domain}-${lane}-res`);
let consumer = Consumer.create({
sqs: this._sqs,
queueUrl: queueUrl,
batchSize: 10,
messageAttributeNames: ['All'],
handleMessage: (message, done) => this._processResponseMessage(message, done)
});
consumer.on('error', function (err) {
bunyanLog.info(err.message);
});
return consumer;
}
async setup() {
this._responseConsumer = await this._setupResponseConsumer(this._options.clientDomain, this._options.clientLane);
}
start() {
this._responseConsumer.start();
}
stop() {
this._responseConsumer.stop();
}
async enqueueRequest(request) {
let message = {
id: request.uid,
body: JSON.stringify(request.payload),
messageAttributes: this._buildSQSMessageAttributes(request)
};
let requestProducer = await this._setupRequestProducer(request.domain, request.lane);
return new Promise((resolve, reject) => {
requestProducer.send([message], function(err) {
if (err) reject(err);
resolve();
});
});
}
_buildSQSMessageAttributes (request) {
let messageAttributes;
switch (request.reefDialect) {
case 'reef-v1-query':
messageAttributes = {
reefDialect: { DataType: 'String', StringValue: request.reefDialect },
requestUid: { DataType: 'String', StringValue: request.uid },
queryType: { DataType: 'String', StringValue: request.queryType },
replyToDomain: { DataType: 'String', StringValue: this._options.clientDomain },
replyToLane: { DataType: 'String', StringValue: this._options.clientLane }
}
break;
case 'reef-v1-command':
messageAttributes = {
reefDialect: { DataType: 'String', StringValue: request.reefDialect },
requestUid: { DataType: 'String', StringValue: request.uid },
commandType: { DataType: 'String', StringValue: request.commandType },
replyToDomain: { DataType: 'String', StringValue: this._options.clientDomain },
replyToLane: { DataType: 'String', StringValue: this._options.clientLane }
}
break;
default:
console.error("Unrecognized reefDialect");
return;
}
return messageAttributes;
}
expectResponse(uid, timeout) {
return new Promise((resolve, reject) => {
this._listeners[String(uid)] = resolve;
setTimeout(() => {
if (this._listeners[String(uid)]) reject(new Error('Response timeout'));
}, timeout);
});
}
}
| JavaScript | 0.000007 | @@ -1631,24 +1631,81 @@
urn;%0A %7D%0A%0A
+ let promise = new Promise((resolve, reject) =%3E %7B%0A
if( stat
@@ -1747,24 +1747,28 @@
)%7B%0A
+
done();%0A
@@ -1767,24 +1767,28 @@
();%0A
+
+
let error =
@@ -1832,16 +1832,20 @@
+
error.se
@@ -1893,26 +1893,85 @@
+
-throw error
+ return reject(error);%0A %7D%0A return resolve(response)
;%0A %7D
+);
%0A%0A
@@ -1981,22 +1981,21 @@
istener(
-respon
+promi
se);%0A %7D
|
f0cda3c6d235272988f357db0ed52c20b663c8e4 | Update binary-find.js | javascript/16_binary/binary-find.js | javascript/16_binary/binary-find.js | /**
* 二分查找
*
* Author: nameczz
*/
// 查找第一个等于给定值
const biaryFindFirst = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
}
}
return -1
}
// 查找最后一个相等的数
const biaryFindLast = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target < sortedArr[mid]) {
high = mid - 1
} else if (target > sortedArr[mid]) {
low = mid + 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] > target) return mid
low = mid + 1
}
}
return -1
}
// 查找第一个大于等于给定值的元素
const biaryFindFistBig = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (target <= sortedArr[mid]) {
if (mid === 0 || sortedArr[mid - 1] < target) return mid
high = mid - 1
} else {
low = mid + 1
}
}
return -1
}
// 查找最后一个小于等于给定值的元素
const biaryFindLastSmall = (sortedArr, target) => {
if (sortedArr.length === 0) return -1
let low = 0
let high = sortedArr.length - 1
while (low <= high) {
const mid = Math.floor((low + high) / 2)
if (sortedArr[mid] > target) {
high = mid - 1
} else {
if (mid === sortedArr.length - 1 || sortedArr[mid + 1] > target) return mid
low = mid + 1
}
}
return -1
}
const arr = [1, 2, 3, 4, 4, 4, 4, 4, 6, 7, 8, 8, 9]
const first = biaryFindFirst(arr, 4)
console.log(`FindFirst: ${first}`)
const last = biaryFindLast(arr, 4)
console.log(`FindLast: ${last}`)
const FisrtBig = biaryFindFistBig(arr, 5)
console.log(`FindFisrtBig: ${FisrtBig}`)
const LastSmall = biaryFindLastSmall(arr, 4)
console.log(`FindLastSmall: ${LastSmall}`) | JavaScript | 0 | @@ -1776,32 +1776,41 @@
2)%0A if (
+target %3C
sortedArr%5Bmid%5D %3E
@@ -1807,25 +1807,16 @@
Arr%5Bmid%5D
- %3E target
) %7B%0A
@@ -1915,32 +1915,33 @@
edArr%5Bmid + 1%5D %3E
+=
target) return
@@ -2366,8 +2366,9 @@
Small%7D%60)
+%0A
|
119d4f0c60cf3d891d8d85282c0c97c838791cd6 | Add callback feature | src/abe-json-builder.js | src/abe-json-builder.js | var colors = require('colours'),
fs = require('fs'),
glob = require('glob'),
lodash = require('lodash-node'),
mkdirp = require('mkdirp'),
path = require('path'),
util = require('util'),
errors = {
'NOT_ABE': 'This file is an invalid ABE JSON format'
},
opt = {
'verbose': false,
'location': './',
'build': 'tmp/'
};
exports.jsonBuilder = function (options) {
lodash.merge(opt, options);
glob
.sync(opt.location + '.json', {
mark: true
})
.forEach(function (match) {
var json = require(process.cwd() + '/' + match);
// Check that the JSON passed to the function has examples / matches
// ABE Spec
if (!lodash.has(json, 'examples')) {
return errors.NOT_ABE;
}
var folderArr = path.dirname(match).split('/'),
filePath = process.cwd() + '/' + opt.build,
buildName = folderArr[folderArr.length - 1] + '-',
baseName = path.basename(match, '.json');
if (!fs.existsSync(filePath)) {
mkdirp(filePath, function (err) {
if (err) {
console.log(err.red);
} else if (opt.verbose) {
console.log(opt.build.yellow, ' created.');
}
});
}
// Loop through each example within the JSON to create it's own
// JSON file
lodash.forEach(json.examples, function (obj, key) {
var bodyData = json.examples[key].response.body,
fileData = JSON.stringify(bodyData, null, 4),
file = buildName + baseName + '-' + key + '.json';
fs.writeFile(filePath + file, fileData, function (err) {
if (err) {
console.log(err.red);
} else if (opt.verbose) {
console.log(file.green, ' file was saved.');
}
});
});
});
};
| JavaScript | 0 | @@ -421,20 +421,30 @@
(options
+, callback
) %7B%0A
-
loda
@@ -1212,37 +1212,58 @@
if
+(!lodash.isUndefined
(err)
+)
%7B%0A
@@ -1930,21 +1930,42 @@
if
+(!lodash.isUndefined
(err)
+)
%7B%0A
@@ -2175,24 +2175,24 @@
%7D);%0A%0A
-
%7D);%0A
@@ -2190,12 +2190,78 @@
%7D);
+%0A%0A if (lodash.isFunction(callback)) %7B%0A callback();%0A %7D
%0A%7D;%0A
|
939e5c675d039cecd7378542667d5e4942511a54 | Update some syntax and add some options to the data that is passed to the unbox function | packages/truffle-core/lib/commands/unbox.js | packages/truffle-core/lib/commands/unbox.js | /*
* returns a VCS url string given:
* - a VCS url string
* - a github `org/repo` string
* - a string containing a repo under the `truffle-box` org
*/
function normalizeURL(url) {
url = url || "https://github.com/trufflesuite/truffle-init-default";
// full URL already
if (url.indexOf("://") != -1 || url.indexOf("git@") != -1) {
return url;
}
if (url.split("/").length == 2) { // `org/repo`
return "https://github.com/" + url;
}
if (url.indexOf("/") == -1) { // repo name only
if (url.indexOf("-box") == -1) {
url = url + "-box";
}
return "https://github.com/truffle-box/" + url;
}
throw new Error("Box specified in invalid format");
}
/*
* returns a list of messages, one for each command, formatted
* so that:
*
* command key: command string
*
* are aligned
*/
function formatCommands(commands) {
var names = Object.keys(commands);
var maxLength = Math.max.apply(
null, names.map(function(name) { return name.length })
);
return names.map(function(name) {
var spacing = Array(maxLength - name.length + 1).join(" ");
return " " + name + ": " + spacing + commands[name];
});
}
var command = {
command: 'unbox',
description: 'Download a Truffle Box, a pre-built Truffle project',
builder: {},
help: {
usage: "truffle unbox <box_name>",
options: [
{
option: "<box_name>",
description: "Name of the truffle box.",
}
],
},
run: function(options, done) {
var Config = require("truffle-config");
var Box = require("truffle-box");
var OS = require("os");
var config = Config.default().with({
logger: console
});
var url = normalizeURL(options._[0]);
Box.unbox(url, config.working_directory, {logger: config.logger})
.then(function(boxConfig) {
config.logger.log("Unbox successful. Sweet!" + OS.EOL);
var commandMessages = formatCommands(boxConfig.commands);
if (commandMessages.length > 0) {
config.logger.log("Commands:" + OS.EOL);
}
commandMessages.forEach(function(message) {
config.logger.log(message);
});
if (boxConfig.epilogue) {
config.logger.log(boxConfig.epilogue.replace("\n", OS.EOL));
}
done();
})
.catch(done);
}
}
module.exports = command;
| JavaScript | 0 | @@ -1470,16 +1470,17 @@
function
+
(options
@@ -1493,19 +1493,21 @@
) %7B%0A
-var
+const
Config
@@ -1539,19 +1539,21 @@
%22);%0A
-var
+const
Box = r
@@ -1579,19 +1579,21 @@
%22);%0A
-var
+const
OS = re
@@ -1610,19 +1610,21 @@
);%0A%0A
-var
+const
config
@@ -1684,19 +1684,21 @@
);%0A%0A
-var
+const
url = n
@@ -1721,24 +1721,129 @@
ons._%5B0%5D);%0A%0A
+ const unboxOptions = Object.assign(%0A %7B%7D,%0A options,%0A %7B logger: config.logger %7D,%0A )%0A%0A
Box.unbo
@@ -1879,31 +1879,20 @@
ry,
-%7Blogger: config.logger%7D
+unboxOptions
)%0A
|
17c149e0b645068d51c51cbd3b1c2d00bb533441 | optimize ButtonRadioGroup | src/ButtonRadioGroup/ButtonRadioGroup.js | src/ButtonRadioGroup/ButtonRadioGroup.js | /**
* @file ButtonRadioGroup component
* @author liangxiaojun([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ButtonRadio from '../ButtonRadio';
import Theme from '../Theme';
import Util from '../_vendors/Util';
class ButtonRadioGroup extends Component {
static Theme = Theme;
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
value: props.value
};
}
changeHandler = item => {
this.setState({
value: item.value
}, () => {
!this.props.disabled && this.props.onChange && this.props.onChange(item.value);
});
};
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.state.value) {
this.setState({
value: !!nextProps.value
});
}
}
render() {
const {className, style, theme, activatedTheme, name, disabled, data} = this.props,
{value} = this.state,
groupClassName = classNames('button-radio-group', {
[className]: className
});
return (
<div className={groupClassName}
style={style}
disabled={disabled}>
{
name ?
<input type="hidden"
name={name}
value={value}/>
:
null
}
{
data.map((item, index) => {
const isChecked = item.value == value;
return (
<ButtonRadio key={index}
theme={isChecked ? activatedTheme : theme}
data={item}
disabled={disabled || item.disabled}
isChecked={isChecked}
onClick={this.changeHandler}/>
);
}
)
}
</div>
);
}
}
ButtonRadioGroup.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* The ButtonCheckbox theme.
*/
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The ButtonCheckbox activated theme.
*/
activatedTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The hidden input name for form submit.
*/
name: PropTypes.string,
/**
* Data for ButtonRadioGroup.
*/
data: PropTypes.arrayOf(PropTypes.shape({
/**
* The className of RaisedButton.
*/
className: PropTypes.string,
/**
* The style of RaisedButton.
*/
style: PropTypes.object,
/**
* The label of RaisedButton.
*/
label: PropTypes.any,
/**
* The value of RaisedButton.
*/
value: PropTypes.any,
/**
* If true, the RaisedButton will be disabled.
*/
disabled: PropTypes.bool
})).isRequired,
/**
* Set one of the button activation.
*/
value: PropTypes.any,
/**
* If true, the ButtonRadioGroup will be disabled.
*/
disabled: PropTypes.bool,
/**
* Callback function fired when click RaisedButton.
*/
onChange: PropTypes.func
};
ButtonRadioGroup.defaultProps = {
theme: Theme.DEFAULT,
activatedTheme: Theme.PRIMARY,
value: '',
disabled: false
};
export default ButtonRadioGroup; | JavaScript | 0.000013 | @@ -1627,24 +1627,32 @@
+ data &&
data.map((i
|
4ecac531120f1e306cc6c853cfb6acc8b7d8b44c | Fix #2027 | packages/vulcan-lib/lib/modules/settings.js | packages/vulcan-lib/lib/modules/settings.js | import Vulcan from './config.js';
import flatten from 'flat';
const getNestedProperty = function (obj, desc) {
var arr = desc.split(".");
while(arr.length && (obj = obj[arr.shift()]));
return obj;
};
export const Settings = {};
export const getAllSettings = () => {
const settingsObject = {};
let rootSettings = _.clone(Meteor.settings);
delete rootSettings.public;
delete rootSettings.private;
// root settings & private settings are both private
rootSettings = flatten(rootSettings, {safe: true});
const privateSettings = flatten(Meteor.settings.private || {}, {safe: true});
// public settings
const publicSettings = flatten(Meteor.settings.public || {}, {safe: true});
// registered default values
const registeredSettings = Settings;
const allSettingKeys = _.union(_.keys(rootSettings), _.keys(publicSettings), _.keys(privateSettings), _.keys(registeredSettings));
allSettingKeys.sort().forEach(key => {
settingsObject[key] = {};
if (typeof rootSettings[key] !== 'undefined') {
settingsObject[key].value = rootSettings[key];
} else if (typeof privateSettings[key] !== 'undefined') {
settingsObject[key].value = privateSettings[key];
} else if (typeof publicSettings[key] !== 'undefined') {
settingsObject[key].value = publicSettings[key];
}
if (typeof publicSettings[key] !== 'undefined'){
settingsObject[key].isPublic = true;
}
if (registeredSettings[key]) {
if (registeredSettings[key].defaultValue !== null || registeredSettings[key].defaultValue !== undefined) settingsObject[key].defaultValue = registeredSettings[key].defaultValue;
if (registeredSettings[key].description) settingsObject[key].description = registeredSettings[key].description;
}
});
return _.map(settingsObject, (setting, key) => ({name: key, ...setting}));
}
Vulcan.showSettings = () => {
return getAllSettings();
}
export const registerSetting = (settingName, defaultValue, description, isPublic) => {
Settings[settingName] = { defaultValue, description, isPublic };
}
export const getSetting = (settingName, settingDefault) => {
let setting;
// if a default value has been registered using registerSetting, use it
const defaultValue = settingDefault || Settings[settingName] && Settings[settingName].defaultValue;
if (Meteor.isServer) {
// look in public, private, and root
const rootSetting = getNestedProperty(Meteor.settings, settingName);
const privateSetting = Meteor.settings.private && getNestedProperty(Meteor.settings.private, settingName);
const publicSetting = Meteor.settings.public && getNestedProperty(Meteor.settings.public, settingName);
// if setting is an object, "collect" properties from all three places
if (typeof rootSetting === 'object' || typeof privateSetting === 'object' || typeof publicSetting === 'object') {
setting = {
...defaultValue,
...rootSetting,
...privateSetting,
...publicSetting,
}
} else {
if (typeof rootSetting !== 'undefined') {
setting = rootSetting;
} else if (typeof privateSetting !== 'undefined') {
setting = privateSetting;
} else if (typeof publicSetting !== 'undefined') {
setting = publicSetting;
} else {
setting = defaultValue;
}
}
} else {
// look only in public
const publicSetting = Meteor.settings.public && getNestedProperty(Meteor.settings.public, settingName);
setting = publicSetting || defaultValue;
}
// Settings[settingName] = {...Settings[settingName], settingValue: setting};
return setting;
}
registerSetting('debug', false, 'Enable debug mode (more verbose logging)');
| JavaScript | 0.000001 | @@ -3504,32 +3504,39 @@
);%0A setting =
+ typeof
publicSetting %7C
@@ -3534,18 +3534,49 @@
Setting
-%7C%7C
+!== 'undefined' ? publicSetting :
default
|
9d9aeab819f94699f0ad7ff92556f3f69f03c8e2 | Update timeline list before titles of each timeline | js/controllers/action-controller.js | js/controllers/action-controller.js | (function(app) {
'use strict';
var m = require('mithril');
var util = app.util || require('../util.js');
var TimelineController = app.TimelineController || require('./timeline-controller.js');
var ActionController = function(option) {
this.headerController = m.prop(option.headerController);
this.timeAxisController = m.prop(option.timeAxisController);
this.timelineListController = m.prop(option.timelineListController);
};
ActionController.prototype.timelineControllers = function(value) {
var headerController = this.headerController();
// headerController's timelineController is used as a cache
if (typeof value === 'undefined')
return headerController.timelineControllers();
var timelineListController = this.timelineListController();
headerController.timelineControllers(value);
timelineListController.timelineControllers(value);
};
ActionController.prototype.start = function() {
var headerController = this.headerController();
var timeAxisController = this.timeAxisController();
var timelineListController = this.timelineListController();
var daysAgo = util.loadData('days-ago', 183);
var daysAfter = util.loadData('days-after', 183);
var pixelsPerDay = util.loadData('pixels-per-day' ,8);
loadTimelineControllers(this, {
daysAgo: daysAgo,
daysAfter: daysAfter,
pixelsPerDay: pixelsPerDay
});
updateTimelineSettings(headerController, daysAgo, daysAfter, pixelsPerDay);
updateTimelineSettings(timeAxisController, daysAgo, daysAfter, pixelsPerDay);
updateTimelineSettings(timelineListController, daysAgo, daysAfter, pixelsPerDay);
headerController.onchange = onChangeHeaderController.bind(this);
headerController.ontoday = onTodayHeaderController.bind(this);
headerController.ontimelinetoggle = onTimelineToggleHeaderController.bind(this);
headerController.ontimelinereorder = onTimelineReorderHeaderController.bind(this);
timelineListController.oninit = onInitTimelineListController.bind(this);
timelineListController.onscroll = onScrollTimelineListController.bind(this);
};
var updateTimelineSettings = function(ctrl, daysAgo, daysAfter, pixelsPerDay) {
ctrl.daysAgo(daysAgo);
ctrl.daysAfter(daysAfter);
ctrl.pixelsPerDay(pixelsPerDay);
};
var loadTimelineControllers = function(ctrl, option) {
util.getJSON('settings.json').done(function(data) {
var urls = data.timelines;
if (!Array.isArray(urls))
return;
var visibleTimelineUrls = loadVisibleTimelineUrls();
var invisibleTimelineUrls = urls.filter(function(url) {
return visibleTimelineUrls.indexOf(url) === -1;
});
var visibleTimelines = visibleTimelineUrls.map(function(url) {
return new TimelineController({
url: url,
visible: true
});
});
var invisibleTimelines = invisibleTimelineUrls.map(function(url) {
return new TimelineController({
url: url,
visible: false
});
});
var timelineControllers = visibleTimelines.concat(invisibleTimelines);
m.sync(timelineControllers.map(function(timelineController) {
return timelineController.fetch();
})).then(function(timelineControllers) {
var timelineListController = ctrl.timelineListController();
var daysAgo = option.daysAgo;
var daysAfter = option.daysAfter;
var pixelsPerDay = option.pixelsPerDay;
ctrl.timelineControllers(timelineControllers);
updateTimelineSettings(timelineListController, daysAgo, daysAfter, pixelsPerDay);
m.redraw();
updateScrollLeftPosition(ctrl);
});
});
};
var updateScrollLeftPosition = function(ctrl, value) {
var timelineListController = ctrl.timelineListController();
// locate each timeline title
if (typeof value === 'undefined')
value = timelineListController.scrollLeft();
// need only adjust timeline list scroll position
// timeline list scroll event transferred to time axis
timelineListController.scrollLeft(value);
};
var toggleTimelineController = function(ctrl, index) {
var timelineControllers = ctrl.timelineControllers();
var timelineController = timelineControllers[index];
timelineController.toggle();
saveVisibleTimelineUrls(timelineControllers);
m.redraw();
updateScrollLeftPosition(ctrl);
};
var reorderTimelineController = function(ctrl, indices) {
var timelineControllers = ctrl.timelineControllers();
var clone = timelineControllers.concat();
for (var i = 0, len = timelineControllers.length; i < len; i++) {
timelineControllers[i] = clone[indices[i]];
}
saveVisibleTimelineUrls(timelineControllers);
m.redraw();
updateScrollLeftPosition(ctrl);
};
var loadVisibleTimelineUrls = function() {
return util.loadData('visible-timeline-urls', []);
};
var saveVisibleTimelineUrls = function(timelineControllers) {
util.saveData('visible-timeline-urls', timelineControllers.filter(function(timelineController) {
return timelineController.visible();
}).map(function(timelineController) {
return timelineController.url();
}));
};
var onChangeHeaderController = function(event) {
var timeAxisController = this.timeAxisController();
var timelineListController = this.timelineListController();
// get values before change
var daysAgo = timeAxisController.daysAgo();
var pixelsPerDay = timeAxisController.pixelsPerDay();
var scrollLeft = timelineListController.scrollLeft();
var name = event.name;
var value = event.value;
var methodName = util.camelCase(name);
timeAxisController[methodName](value);
timelineListController[methodName](value);
util.saveData(name, value);
m.redraw();
// adjust scroll position after redraw
if (name === 'days-ago') {
scrollLeft += (value - daysAgo) * pixelsPerDay;
} else if (name === 'pixels-per-day') {
var scrollDays = (scrollLeft + util.windowWidth() / 2) / pixelsPerDay;
scrollLeft += scrollDays * (value - pixelsPerDay);
}
updateScrollLeftPosition(this, scrollLeft);
};
var onTodayHeaderController = function() {
var headerController = this.headerController();
var daysAgo = headerController.daysAgo();
var pixelsPerDay = headerController.pixelsPerDay();
var scrollLeft = (daysAgo + 0.5) * pixelsPerDay - util.windowWidth() / 2;
updateScrollLeftPosition(this, scrollLeft);
};
var onTimelineToggleHeaderController = function(event) {
toggleTimelineController(this, event.index);
};
var onTimelineReorderHeaderController = function(event) {
reorderTimelineController(this, event.indices);
};
var onInitTimelineListController = function() {
onTodayHeaderController.call(this);
};
var onScrollTimelineListController = function(event) {
var timeAxisController = this.timeAxisController();
timeAxisController.scrollLeft(event.scrollLeft);
};
if (typeof module !== 'undefined' && module.exports)
module.exports = ActionController;
else
app.ActionController = ActionController;
})(this.app || (this.app = {})); | JavaScript | 0 | @@ -3646,32 +3646,36 @@
m.redraw(
+true
);%0A%0A upda
|
0dbe663d1182e4b271fba6917ce554d393fd2de8 | Add some docs; use thisCarousel instead of this | js/energy-systems/model/Carousel.js | js/energy-systems/model/Carousel.js | // Copyright 2016, University of Colorado Boulder
/**
* This class implements a container of sorts for positionable model elements.
* The model elements are positioned by this class, and an API is provided
* that allows clients to move elements to the "selected" position. Changes
* to the selected element are animated.
*
* @author John Blanco
* @author Andrew Adare
* @author Jesse Greenberg
*/
define( function( require ) {
'use strict';
// Modules
var inherit = require( 'PHET_CORE/inherit' );
var PropertySet = require( 'AXON/PropertySet' );
var Vector2 = require( 'DOT/Vector2' );
var Util = require( 'DOT/Util' );
// Constants
var TRANSITION_DURATION = 0.5;
/**
* Carousel class
* Container for positionable model elements
*
* @param {Vector2} selectedElementPosition Location of currently selected element
* @param {Vector2} offsetBetweenElements Offset between elements in the carousel
* @constructor
*/
function Carousel( selectedElementPosition, offsetBetweenElements ) {
PropertySet.call( this, {
// Target selected element. Will be the same as the current selection
// except when animating to a new selection. This property is the API for
// selecting elements in the carousel.
targetIndex: 0,
// Indicator for when animations are in progress, meant to be monitored by
// clients that need to be aware of this.
animationInProgress: false
} );
// The position in model space where the currently selected element should be.
this.selectedElementPosition = selectedElementPosition;
// Offset between elements in the carousel.
this.offsetBetweenElements = offsetBetweenElements;
// List of the elements whose position is managed by this carousel.
this.managedElements = new Array();
this.elapsedTransitionTime = 0;
this.currentCarouselOffset = new Vector2( 0, 0 );
this.initialCarouselOffset = new Vector2( 0, 0 );
// Monitor our own target setting and set up the variables needed for
// animation each time the target changes.
var thisCarousel = this;
this.targetIndexProperty.link( function() {
// Check bounds
var i = thisCarousel.targetIndexProperty.get();
assert && assert( i === 0 || i < thisCarousel.managedElements.size() );
thisCarousel.elapsedTransitionTime = 0;
thisCarousel.initialCarouselOffset = this.currentCarouselOffset;
this.animationInProgressProperty.set( true );
} );
}
return inherit( PropertySet, Carousel, {
/**
* Add element to list of managed elements
*
* @param {EnergySystemElement} element Element to be added to carousel
*/
add: function( element ) {
// Set the element's position to be at the end of the carousel.
if ( this.managedElements.length === 0 ) {
element.setPosition( this.selectedElementPosition );
} else {
var lastElement = this.managedElements[ this.managedElements.length - 1 ];
element.setPosition( lastElement.getPosition().plus( this.offsetBetweenElements ) );
}
// Add element to the list of managed elements.
this.managedElements.add( element );
// Update opacities.
this.updateManagedElementOpacities();
},
/**
* Get element from carousel by index.
*
* @param {Number} index Requested position in array of EnergySystemElements
*
* @return {EnergySystemElement}
*/
getElement: function( index ) {
if ( index <= this.managedElements.length ) {
return this.managedElements[ index ];
} else {
console.error( 'Requesting out of range element from carousel, index = ' + index );
return null;
}
},
getSelectedElement: function() {
var i = this.targetIndexProperty.get();
if ( i < this.managedElements.length ) {
return this.managedElements[ i ];
}
return null;
},
stepInTime: function( dt ) {
if ( !this.atTargetPosition() ) {
this.elapsedTransitionTime += dt;
var targetCarouselOffset = this.offsetBetweenElements.times( -this.targetIndexProperty.get() );
var totalTravelVector = targetCarouselOffset.minus( this.initialCarouselOffset );
var proportionOfTimeElapsed = Util.clamp( this.elapsedTransitionTime / TRANSITION_DURATION, 0, 1 );
this.currentCarouselOffset = this.initialCarouselOffset.plus( totalTravelVector.times( this.computeSlowInSlowOut( proportionOfTimeElapsed ) ) );
this.updateManagedElementPositions();
if ( proportionOfTimeElapsed === 1 ) {
this.currentCarouselOffset = targetCarouselOffset;
}
if ( this.currentCarouselOffset === targetCarouselOffset ) {
this.animationInProgressProperty.set( false );
}
this.updateManagedElementOpacities();
}
},
updateManagedElementPositions: function() {
for ( var i = 0; i < this.managedElements.length; i++ ) {
var position = this.selectedElementPosition.plus( this.offsetBetweenElements.times( i ) );
this.managedElements[ i ].setPosition( position ).plus( this.currentCarouselOffset );
}
},
updateManagedElementOpacities: function() {
var thisCarousel = this;
this.managedElements.forEach( function( managedElement ) {
var distanceFromSelectionPosition = managedElement.getPosition().distance( thisCarousel.selectedElementPosition );
var opacity = Util.clamp( 1 - ( distanceFromSelectionPosition / thisCarousel.offsetBetweenElements.magnitude() ), 0, 1 );
managedElement.opacity.set( opacity );
} );
},
atTargetPosition: function() {
var targetCarouselOffset = new Vector2( this.offsetBetweenElements.times( -this.targetIndexProperty.get() ) );
return this.currentCarouselOffset.equals( targetCarouselOffset );
},
computeSlowInSlowOut: function( zeroToOne ) {
if ( zeroToOne < 0.5 ) {
return 2.0 * zeroToOne * zeroToOne;
} else {
var complement = 1.0 - zeroToOne;
return 1.0 - 2.0 * complement * complement;
}
}
} );
} );
| JavaScript | 0 | @@ -819,46 +819,47 @@
ion
-Location of currently selected element
+Offset between elements in the carousel
%0A
@@ -905,47 +905,46 @@
s
-Offset between elements in the carousel
+Location of currently selected element
%0A
@@ -2416,24 +2416,32 @@
ffset = this
+Carousel
.currentCaro
@@ -2454,32 +2454,40 @@
fset;%0A this
+Carousel
.animationInProg
@@ -3771,24 +3771,130 @@
%7D%0A %7D,%0A%0A
+ /**%0A * Get selected element from carousel%0A *%0A * @return %7B%5Btype%5D%7D Selected element%0A */%0A
getSelec
|
2e0034329dce6bde59d73485cca29c8074a48db0 | Allow dropdown `select` events to bubble. | Dropdown.js | Dropdown.js | /* ==========================================================
* Dropdown.js v1.1.0
* ==========================================================
* Copyright 2012 xsokev
*
* 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.
* ========================================================== */
define([
'./Support',
"dojo/_base/declare",
"dojo/query",
"dojo/_base/lang",
'dojo/_base/window',
'dojo/on',
'dojo/dom-class',
"dojo/dom-attr",
"dojo/NodeList-dom",
'dojo/NodeList-traverse',
"dojo/domReady!"
], function (support, declare, query, lang, win, on, domClass, domAttr) {
"use strict";
var toggleSelector = '[data-toggle=dropdown]';
var Dropdown = declare([], {
defaultOptions:{},
constructor:function (element, options) {
this.options = lang.mixin(lang.clone(this.defaultOptions), (options || {}));
var el = query(element).closest(toggleSelector);
if (!el[0]) {
el = query(element);
}
if (el) {
this.domNode = el[0];
domAttr.set(el[0], "data-toggle", "dropdown");
}
},
select: function(e){
e.stopPropagation();
var parentNode = _getParent(this)[0];
if (parentNode) {
var target = query(toggleSelector, parentNode);
on.emit(target[0], 'select', { bubbles:false, cancelable:false, selectedItem: query(e.target).closest('li') });
}
},
toggle: function(e){
if (domClass.contains(this, "disabled") || domAttr.get(this, "disabled")) {
return false;
}
var targetNode = _getParent(this)[0];
if (targetNode) {
var isActive = domClass.contains(targetNode, 'open');
clearMenus();
if (!isActive) {
domClass.toggle(targetNode, 'open');
}
this.focus();
}
if(e){
e.preventDefault();
e.stopPropagation();
}
return false;
},
keydown: function(e) {
if (!/(38|40|27)/.test(e.keyCode)) { return; }
e.preventDefault();
e.stopPropagation();
if (domClass.contains(this, "disabled") || domAttr.get(this, "disabled")) {
return false;
}
var targetNode = _getParent(this)[0];
if (targetNode) {
var isActive = domClass.contains(targetNode, 'open');
if (!isActive || (isActive && e.keyCode === 27)) {
return on.emit(targetNode, 'click', { bubbles:true, cancelable:true });
}
var items = query('[role=menu] li:not(.divider) a', targetNode);
if (!items.length) { return; }
var index = items.indexOf(document.activeElement);
if (e.keyCode === 38 && index > 0) { index--; }
if (e.keyCode === 40 && index < items.length - 1) { index++; }
if (index < 0) { index = 0; }
if (items[index]) {
items[index].focus();
}
}
}
});
function clearMenus() {
query(toggleSelector).forEach(function(menu){
_getParent(menu).removeClass('open');
});
}
function _getParent(node){
var selector = domAttr.get(node, 'data-target');
if (!selector) {
selector = support.hrefValue(node);
}
var parentNode = query(node).parent();
if (selector && selector !== '#' && selector !== '') {
parentNode = query(selector).parent();
}
return parentNode;
}
lang.extend(query.NodeList, {
dropdown:function (option) {
var options = (lang.isObject(option)) ? option : {};
return this.forEach(function (node) {
var data = support.getData(node, 'dropdown');
if (!data) {
support.setData(node, 'dropdown', (data = new Dropdown(node, options)));
}
});
}
});
on(win.body(), 'click, touchstart', clearMenus);
on(win.body(), on.selector(toggleSelector, 'click, touchstart'), Dropdown.prototype.toggle);
on(win.body(), on.selector('.dropdown form', 'click, touchstart'), function (e) { e.stopPropagation(); });
on(win.body(), on.selector('.dropdown-menu', 'click, touchstart'), Dropdown.prototype.select);
on(win.body(), on.selector(toggleSelector+', [role=menu]', 'keydown, touchstart'), Dropdown.prototype.keydown);
return Dropdown;
}); | JavaScript | 0 | @@ -1926,20 +1926,19 @@
bubbles:
-fals
+tru
e, cance
@@ -1943,20 +1943,19 @@
celable:
-fals
+tru
e, selec
|
26d35f5c1e21cc0141f50dfbde9718e6d5b6b139 | build to include woff2 fonts from bootstrap-sass | gulp/build.js | gulp/build.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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 gulp = require('gulp'),
runSequence = require('run-sequence');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*', 'main-bower-files', 'uglify-save-license', 'del']
});
gulp.task('styles', ['wiredep', 'injector:css:preprocessor'], function () {
return gulp.src(['src/app/index.scss', 'src/app/vendor.scss'])
.pipe($.sass({style: 'expanded'}))
.on('error', function handleError(err) {
console.error(err.toString());
this.emit('end');
})
.pipe($.autoprefixer('last 1 version'))
.pipe(gulp.dest('.tmp/app/'));
});
gulp.task('injector:css:preprocessor', function () {
return gulp.src('src/app/index.scss')
.pipe($.inject(gulp.src([
'src/{app,components}/**/*.scss',
'!src/app/index.scss',
'!src/app/vendor.scss'
], {read: false}), {
transform: function(filePath) {
filePath = filePath.replace('src/app/', '');
filePath = filePath.replace('src/components/', '../components/');
return '@import \'' + filePath + '\';';
},
starttag: '// injector',
endtag: '// endinjector',
addRootSlash: false
}))
.pipe(gulp.dest('src/app/'));
});
gulp.task('injector:css', ['styles'], function () {
return gulp.src('src/index.html')
.pipe($.inject(gulp.src([
'.tmp/{app,components}/**/*.css',
'!.tmp/app/vendor.css'
], {read: false}), {
ignorePath: '.tmp',
addRootSlash: false
}))
.pipe(gulp.dest('src/'));
});
gulp.task('jshint', function () {
return gulp.src('src/{app,components}/**/*.js')
.pipe($.jshint())
.pipe($.jshint.reporter('jshint-stylish'));
});
gulp.task('injector:js', ['jshint', 'injector:css'], function () {
return gulp.src('src/index.html')
.pipe($.inject(gulp.src([
'src/{app,components,vendor}/**/*.js',
'!src/{app,components,vendor}/**/*.spec.js',
'!src/{app,components,vendor}/**/*.mock.js'
], {read: false}), {
ignorePath: 'src',
addRootSlash: false
}))
.pipe(gulp.dest('src/'));
});
gulp.task('partials', function () {
return gulp.src('src/{app,components}/**/*.html')
.pipe($.htmlmin({
empty: true,
spare: true,
quotes: true
}))
.pipe($.angularTemplatecache('templateCacheHtml.js', {
module: 'odeConsole'
}))
.pipe(gulp.dest('.tmp/inject/'));
});
gulp.task('html', ['wiredep', 'injector:css', 'injector:js', 'partials'], function () {
var htmlFilter = $.filter('*.html',{restore: true});
var jsFilter = $.filter('**/*.js',{restore: true});
var cssFilter = $.filter('**/*.css',{restore: true});
return gulp.src('src/*.html')
.pipe($.inject(gulp.src('.tmp/inject/templateCacheHtml.js', {read: false}), {
starttag: '<!-- inject:partials -->',
ignorePath: '.tmp',
addRootSlash: false
}))
.pipe($.useref())
//.pipe($.rev())
.pipe(jsFilter)
.pipe($.ngAnnotate())
.pipe($.uglify({preserveComments: $.uglifySaveLicense}))
.pipe(jsFilter.restore)
.pipe(cssFilter)
.pipe($.replace('bower_components/bootstrap-sass-official/assets/fonts/bootstrap','fonts'))
.pipe($.csso())
.pipe(cssFilter.restore)
.pipe($.useref())
.pipe($.revReplace())
.pipe(htmlFilter)
.pipe($.htmlmin({
empty: true,
spare: true,
quotes: true
}))
.pipe(htmlFilter.restore)
.pipe(gulp.dest('dist/'))
.pipe($.size({ title: 'dist/', showFiles: true }));
});
gulp.task('images', function () {
return gulp.src('src/assets/images/**/*')
.pipe($.cache($.imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/assets/images/'));
});
gulp.task('fonts', function () {
return gulp.src($.mainBowerFiles())
.pipe($.filter('**/*.{eot,svg,ttf,woff}'))
.pipe($.flatten())
.pipe(gulp.dest('dist/fonts/'));
});
gulp.task('misc', function () {
return gulp.src('src/**/*.ico')
.pipe(gulp.dest('dist/'));
});
gulp.task('clean', function () {
return $.del.sync(['dist/', '.tmp/']);
});
gulp.task('build', function(done){
runSequence('clean', 'html', 'images', 'fonts', 'misc',done);
});
| JavaScript | 0 | @@ -4638,16 +4638,22 @@
ttf,woff
+,woff2
%7D'))%0A
|
57204c6ed08fac60a547d3acec62f0866cf2869b | Fix last commit | js/src/admin/components/MailPage.js | js/src/admin/components/MailPage.js | import Page from './Page';
import FieldSet from '../../common/components/FieldSet';
import Button from '../../common/components/Button';
import Alert from '../../common/components/Alert';
import Select from '../../common/components/Select';
import saveSettings from '../utils/saveSettings';
export default class MailPage extends Page {
init() {
super.init();
this.loading = false;
this.fields = [
'mail_driver',
'mail_host',
'mail_from',
'mail_port',
'mail_username',
'mail_password',
'mail_encryption'
];
this.values = {};
const settings = app.data.settings;
this.fields.forEach(key => this.values[key] = m.prop(settings[key]));
this.localeOptions = {};
const locales = app.locales;
for (const i in locales) {
this.localeOptions[i] = `${locales[i]} (${i})`;
}
}
view() {
return (
<div className="MailPage">
<div className="container">
<form onsubmit={this.onsubmit.bind(this)}>
<h2>{app.translator.trans('core.admin.email.heading')}</h2>
<div className="helpText">
{app.translator.trans('core.admin.email.text')}
</div>
{FieldSet.component({
label: app.translator.trans('core.admin.email.addresses_heading'),
className: 'MailPage-MailSettings',
children: [
<div className="MailPage-MailSettings-input">
<label>{app.translator.trans('core.admin.email.from_label')}</label>
<input className="FormControl" value={this.values.mail_from() || ''} oninput={m.withAttr('value', this.values.mail_from)} />
</div>
]
})}
{FieldSet.component({
label: app.translator.trans('core.admin.email.driver_heading'),
className: 'MailPage-MailSettings',
children: [
<div className="MailPage-MailSettings-input">
<label>{app.translator.trans('core.admin.email.driver_label')}</label>
<Select value={this.values.mail_driver()} options={Object.keys(this.driverFields).reduce((memo, val) => ({...memo, [val]: val}), {})} onchange={this.values.mail_driver} />
</div>
]
})}
{this.values.mail_driver() == 'smtp' && FieldSet.component({
label: app.translator.trans('core.admin.email.smtp_heading'),
className: 'MailPage-MailSettings',
children: [
<div className="MailPage-MailSettings-input">
<label>{app.translator.trans('core.admin.email.host_label')}</label>
<input className = "FormControl" value={this.values.mail_host() || ''} onInput={m.withAttr('value', this.values.mail_host)} />
<label>{app.translator.trans('core.admin.email.port_label')}</label>
<input className="FormControl" value={this.values.mail_port() || ''} oninput={m.withAttr('value', this.values.mail_port)} />
<label>{app.translator.trans('core.admin.email.encryption_label')}</label>
<input className="FormControl" value={this.values.mail_encryption() || ''} oninput={m.withAttr('value', this.values.mail_encryption)} />
<label>{app.translator.trans('core.admin.email.username_label')}</label>
<input className="FormControl" value={this.values.mail_username() || ''} onInput={m.withAttr('value', this.values.mail_username)}/>
<label>{app.translator.trans('core.admin.email.password_label')}</label>
<input className="FormControl" value={this.values.mail_password() || ''} onInput={m.withAttr('value', this.values.mail_password)}/>
</div>
]
})}
{Button.component({
type: 'submit',
className: 'Button Button--primary',
children: app.translator.trans('core.admin.email.submit_button'),
loading: this.loading,
disabled: !this.changed()
})}
</form>
</div>
</div>
);
}
changed() {
return this.fields.some(key => this.values[key]() !== app.data.settings[key]);
}
onsubmit(e) {
e.preventDefault();
if (this.loading) return;
this.loading = true;
app.alerts.dismiss(this.successAlert);
const settings = {};
this.fields.forEach(key => settings[key] = this.values[key]());
saveSettings(settings)
.then(() => {
app.alerts.show(this.successAlert = new Alert({type: 'success', children: app.translator.trans('core.admin.basics.saved_message')}));
})
.catch(() => {})
.then(() => {
this.loading = false;
m.redraw();
});
}
}
| JavaScript | 0.000002 | @@ -387,16 +387,174 @@
false;%0A%0A
+ this.driverFields = %7B%0A smtp: %5B'mail_host', 'mail_port', 'mail_encryption', 'mail_username', 'mail_password'%5D,%0A mail: %5B%5D,%0A log: %5B%5D,%0A %7D;%0A%0A
this
|
cc078e4041e23409f3ae32e6f3144b4b94e49b69 | update browserify config | gulp/build.js | gulp/build.js | 'use strict';
var browserify = require('browserify');
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var $ = require('gulp-load-plugins')({
pattern: ['gulp-*']
});
/**
* scripts
**/
gulp.task('scripts', function() {
return browserify('./app/scripts/app.js')
.bundle()
//Pass desired output filename to vinyl-source-stream
.pipe(source('app.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('.tmp/scripts'));
});
gulp.task('scripts:dist', ['scripts', 'templates:dist'], function() {
return gulp.src(['.tmp/scripts/app.js', '.tmp/templates/templates.js'])
.pipe($.concat('app.js'))
.pipe($.ngAnnotate())
.pipe($.uglify())
.pipe(gulp.dest('dist/scripts'))
.pipe($.size());
});
/**
* templates
**/
gulp.task('templates', function () {
return gulp.src('app/scripts/**/*.html')
.pipe(gulp.dest('.tmp/templates'))
.pipe($.size());
});
gulp.task('templates:dist', ['templates'], function() {
return gulp.src(['.tmp/templates/**/*.html'])
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe($.ngHtml2js({
moduleName: 'myApp',
prefix: ''
}))
.pipe($.concat('templates.js'))
.pipe(gulp.dest('.tmp/templates'))
.pipe($.size());
});
/**
* styles
**/
gulp.task('styles', function () {
return gulp.src('app/styles/*.scss')
.pipe($.plumber())
.pipe($.sass({style: 'expanded'}))
.pipe($.autoprefixer('last 1 version'))
.pipe(gulp.dest('.tmp/styles'))
.pipe($.size());
});
gulp.task('styles:dist', ['styles'], function() {
return gulp.src('.tmp/styles/**/*.css')
.pipe($.cssmin())
.pipe(gulp.dest('dist/styles'))
.pipe($.size());
});
/**
* images
**/
gulp.task('images:dist', function () {
return gulp.src('app/images/**/*')
.pipe($.cache($.imagemin({
optimizationLevel: 3,
progressive: true,
interlaced: true
})))
.pipe(gulp.dest('dist/images'))
.pipe($.size());
});
/**
* html
**/
gulp.task('html:dist', function () {
return gulp.src('app/*.html')
.pipe($.minifyHtml({
empty: true,
spare: true,
quotes: true
}))
.pipe(gulp.dest('dist'))
.pipe($.size());
});
/**
* build
**/
gulp.task('build:dist', ['styles:dist', 'scripts:dist', 'images:dist', 'html:dist']);
/**
* clean
**/
gulp.task('clean', function () {
return gulp.src(['.tmp', 'dist'], { read: false }).pipe($.rimraf());
});
| JavaScript | 0.000002 | @@ -270,30 +270,118 @@
ify(
-'./app/scripts/app.js'
+%7B%0A entries: %5B'./app/scripts/app.js'%5D,%0A paths: %5B'./node_modules', './app/scripts/'%5D%0A %7D
)%0A
|
a2562acd6d221eb306f7511d6038deba488ea2fc | Remove folders from exclude | gulp/utils.js | gulp/utils.js | import fs from 'fs';
import path from 'path';
import {argv} from 'yargs';
// ENVIRONMENT SETUP
export const isProduction = argv.prod ? true : process.env.NODE_ENV === 'production';
process.env.BABEL_ENV = argv.prod ? 'production' : process.env.NODE_ENV;
const consoleColors = {
reset: '\x1b[0m',
hicolor: '\x1b[1m',
underline: '\x1b[4m',
inverse: '\x1b[7m',
// foreground colors
black: '\x1b[30m',
red: '\x1b[31m',
green: '\x1b[32m',
yellow: '\x1b[33m',
blue: '\x1b[34m',
magenta: '\x1b[35m',
cyan: '\x1b[36m',
white: '\x1b[37m'
};
export const log = (color, msg) => console.log(consoleColors[color], msg, consoleColors.reset);
export const getPaths = () => {
const categories = [];
const paths = [];
const excludeFolders = ['assets', 'less', 'css'];
const handleFolders = (folder, callback) =>
fs.readdirSync(folder).filter(file => {
if (excludeFolders.includes(file)) return false;
if (fs.statSync(path.join(folder, file)).isDirectory()) callback(file);
return true;
});
handleFolders('./examples/', category => {
categories.push(category);
handleFolders(path.join('./examples/', category), name => {
paths.push(`${category}/${name}`);
});
});
return [paths, categories];
};
// ERRORS
export const makeBuildErrorHandler = () => {
return function ({name, message, codeFrame}) {
log('magenta', `${name} ${message}${codeFrame ? `\n${codeFrame}` : ''}`);
this.emit('end');
};
};
| JavaScript | 0.000004 | @@ -768,23 +768,8 @@
ets'
-, 'less', 'css'
%5D;%0A%0A
|
765e7cb685ca340a1bb084499197340841efb923 | fix code style | gulp/watch.js | gulp/watch.js | export function run(gulp, $, config) {
gulp.task('watch', [
'build'
], () => {
gulp.watch(config.appFiles, [
'build'
]);
});
}
| JavaScript | 0.000033 | @@ -66,16 +66,17 @@
'build'
+,
%0A %5D, ()
@@ -128,16 +128,17 @@
'build'
+,
%0A %5D);
|
10a3b7d67389764ed2c1f31aad6adf9cf3779a62 | Add some more descriptive data to links | src/app/bigram/index.js | src/app/bigram/index.js | import bigram from './bigram.json';
import Set from 'es6-set';
import $ from 'jquery';
import 'bootstrap/dist/js/bootstrap.js';
import _ from 'underscore';
import { Graph } from './../../clique/model.js';
import { NodeLinkList } from './../../clique/adapter.js';
import { Cola } from './../../clique/view.js';
import { SelectionInfo } from './../../clique/view.js';
import { LinkInfo } from './../../clique/view.js';
const aCodePoint = 'a'.codePointAt(0);
function bigramGraph (data) {
// Construct the node set, one per English letter.
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let nodes = [];
for (let letter of alphabet) {
nodes.push({
name: letter
});
}
// Iterate through each possible bigram.
let done = new Set();
const threshold = 3 * (1 / 676);
let links = [];
for (let first of alphabet) {
for (let second of alphabet) {
const key = first + second;
const rev = second + first;
// Omitting double letters (not supported by Clique cola view), check to
// see whether the bigram has high enough frequency (and wasn't already
// processed as a frequent reverse of an earlier bigram).
if (first !== second && !done.has(key) && data[key] > threshold) {
let link = {
source: first.codePointAt(0) - aCodePoint,
target: second.codePointAt(0) - aCodePoint,
data: {
frequency: data[key]
}
};
// Make the link undirected if the reverse bigram is sufficiently
// frequent as well.
if (data[rev] > threshold) {
link.undirected = true;
done.add(rev);
}
links.push(link);
}
}
}
return {
nodes,
links
};
}
import './bootswatch.less';
import './index.styl';
$(function () {
const html = require('./index.jade');
$('body').html(html());
const {nodes, links} = bigramGraph(bigram);
let graph = new Graph({
adapter: new NodeLinkList(nodes, links)
});
$('#seed').on('click', function () {
const name = $('#name').val().trim();
if (name === '') {
return;
}
const spec = {
name
};
graph.adapter.findNode(spec)
.then(function (center) {
if (center) {
graph.addNode(center);
}
});
});
let view = new Cola({
model: graph,
el: '#content',
linkDistance: 200,
fill: function (d) {
var colors = [
'rgb(166,206,227)',
'rgb(31,120,180)',
'rgb(178,223,138)',
'rgb(51,160,44)',
'rgb(251,154,153)',
'rgb(227,26,28)',
'rgb(253,191,111)',
'rgb(255,127,0)',
'rgb(202,178,214)',
'rgb(106,61,154)',
'rgb(255,255,153)',
'rgb(177,89,40)'
];
return colors[(d.data.name.codePointAt(0) - aCodePoint) % colors.length];
}
});
let info = new SelectionInfo({
model: view.selection,
el: '#info',
graph: graph,
nodeButtons: [
{
label: 'Hide',
color: 'purple',
icon: 'eye-close',
callback: function (node) {
_.bind(SelectionInfo.hideNode, this)(node);
}
},
{
label: function (node) {
return node.getData('deleted') ? 'Undelete' : 'Delete';
},
color: 'red',
icon: 'remove',
callback: function (node) {
_.bind(SelectionInfo.deleteNode, this)(node);
}
},
{
label: 'Ungroup',
color: 'blue',
icon: 'scissors',
callback: function (node) {
console.log(node);
},
show: function (node) {
return node.getData('grouped');
}
},
{
label: 'Expand',
color: 'blue',
icon: 'fullscreen',
callback: function (node) {
_.bind(SelectionInfo.expandNode, this)(node);
}
},
{
label: 'Collapse',
color: 'blue',
icon: 'resize-small',
callback: function (node) {
_.bind(SelectionInfo.collapseNode, this)(node);
}
}
],
selectionButtons: [
{
label: 'Hide',
color: 'purple',
icon: 'eye-close',
repeat: true,
callback: function (node) {
_.bind(SelectionInfo.hideNode, this)(node);
}
},
{
label: 'Delete',
color: 'red',
icon: 'remove',
repeat: true,
callback: function (node) {
return _.bind(SelectionInfo.deleteNode, this)(node);
}
},
{
label: 'Expand',
color: 'blue',
icon: 'fullscreen',
repeat: true,
callback: function (node) {
_.bind(SelectionInfo.expandNode, this)(node);
}
},
{
label: 'Collapse',
color: 'blue',
icon: 'resize-small',
repeat: true,
callback: function (node) {
_.bind(SelectionInfo.collapseNode, this)(node);
}
}
]
});
info.render();
let linkInfo = new LinkInfo({
model: view.linkSelection,
el: '#link-info',
graph: graph
});
linkInfo.render();
});
| JavaScript | 0 | @@ -1391,16 +1391,67 @@
+letters: %60$%7Bfirst%7D-$%7Bsecond%7D%60,%0A forward_
frequenc
@@ -1661,16 +1661,64 @@
= true;%0A
+ link.data.back_frequency = data%5Brev%5D;%0A
|
61fe0ac833f81a5d08ba773c6e60431c79717f54 | update gulpconfig.js | gulpconfig.js | gulpconfig.js | 'use strict';
/**
* タスクの動作設定
*/
module.exports = {
/**
* 出力先ディレクトリ
*/
dest : 'dest',
/**
* 環境ごとのビルド設定
*/
build : {
default : {
css_minify : false,
js_minify : false,
bower_minify : true,
sourcemap : true
},
production : {
css_minify : false,
js_minify : false,
bower_minify : true,
sourcemap : false
}
},
/**
* サーバーの設定
*/
server : {
// Browsersync
// Options -> https://www.browsersync.io/docs/options/
browsersync : {
notify : false,
ghostMode : false,
// 動的サイトの場合は、別途XAMPP等でサーバーを用意し、以下のproxyにドメインを記述する
// 静的サイトの場合は、コメントアウトまたは削除する
// proxy : 'example.com',
},
// モックサーバー
// 特定パスへのリクエストをモックサーバに転送する
// browsersync.proxyが設定されている場合は使わない
mock : {
// モックの保存ディレクトリパス
path : 'mock',
// リバースプロキシ
proxy : {
// 転送先
pass : 'http://localhost:5000',
// 転送処理を行うパス
location : '/api'
}
}
},
/**
* Bowerの設定
*/
bower : {
output : 'libs.js'
},
/**
* Sassの設定
*/
style : {
// gulp-pleeease
// Options -> http://pleeease.io/docs/
pleeease : {
autoprefixer : {
browsers : [
'last 3 versions',
'ie >= 11',
'ios >= 9',
'android >= 4.4'
]
},
rem : false,
pseudoElements : false,
opacity : false,
minifier : false,
rebaseUrls : false
},
// gulp-sass
// Options -> https://github.com/sass/node-sass#options
sass : {
outputStyle : 'expanded',
indentType : 'tab',
indentWidth : 1
}
},
/**
* JSの設定
*/
script : {
// buble
// Options -> https://buble.surge.sh/guide/#using-the-javascript-api
buble : {
target: { ie: 9 }
}
},
/**
* 画像軽量化の設定
*/
image : {
// 画像軽量化の有無効
// true : 有効
// false : 無効
enable : true,
// imagemin-jpeg-recompress
// Options -> https://github.com/imagemin/imagemin-jpeg-recompress
jpegrecompress : {
quality : 'high',
max : 95,
min : 60
}
},
/**
* パスの設定
*/
path : {
// Bower
bower : {
dest : 'dest/assets/vendor'
},
// EJS
ejs : {
src : ['src/**/*.ejs', '!src/**/_*.ejs'],
watch : 'src/**/*.ejs',
dest : 'dest',
},
// Sass
style : {
src : 'src/assets/sass/**/*.scss',
watch : 'src/assets/sass/**/*.scss',
dest : 'dest/assets/css'
},
// CSS
css : {
src : 'src/assets/css/**/*.css',
watch : 'src/assets/css/**/*.css',
dest : 'dest/assets/css'
},
// JS
script : {
src : 'src/assets/js/*.js',
watch : 'src/assets/js/**/*.js',
dest : 'dest/assets/js'
},
// Image
image : {
src : 'src/assets/images/**/*',
watch : 'src/assets/images/**/*',
dest : 'dest/assets/images'
},
// Sprite
sprite: {
src : 'src/assets/sprites/*',
watch : 'src/assets/sprites/**/*',
dest : {
style : 'src/assets/sass/foundations/sprites',
image : 'src/assets/images'
}
},
// Copy
copy : [
{
src : ['src/**/*.{html,php}', '!src/assets/js/**/*'],
dest : 'dest'
},
{
src : 'src/assets/fonts/**/*',
dest : 'dest/assets/fonts'
},
{
src : 'src/assets/vendor/**/*',
dest : 'dest/assets/vendor'
}
]
}
}
| JavaScript | 0.000001 | @@ -2265,28 +2265,34 @@
s/sass/**/*.
+%7Bcss,
scss
+%7D
',%0A%09%09%09dest
|
41ce9c779ac2275765492e0c36bef56971b48fa0 | Clean up | tasks/jshint.js | tasks/jshint.js | var rewire = require('rewire');
var proxyquire = require('proxyquire');
try {
var react = require('react-tools');
}
catch(e) {
throw new Error('grunt-jsxhint: The module `react-tools` was not found. ' +
'To fix this error run `npm install react-tools --save-dev`.', e);
}
var jshintcli = rewire('jshint/src/cli');
var docblock = require('jstransform/src/docblock');
//Get the original lint function
var origLint = jshintcli.__get__("lint");
var jsxSuffix = ".jsx";
//override the lint function to also transform the jsx code
jshintcli.__set__("lint", function myLint(code, results, config, data, file) {
var isJsxFile = file.indexOf(jsxSuffix, file.length - jsxSuffix.length) !== -1;
//added check for having /** @jsx React.DOM */ comment
var hasDocblock = docblock.parseAsObject(docblock.extract(code)).jsx;
if (isJsxFile && !hasDocblock) {
code = '/** @jsx React.DOM */' + code;
}
if (isJsxFile || hasDocblock) {
var compiled;
try {
compiled = react.transform(code);
} catch (err) {
throw new Error('grunt-jsxhint: Error while running JSXTransformer on ' + file + '\n' + err.message);
}
origLint(compiled, results, config, data, file);
}
else {
origLint(code, results, config, data, file);
}
});
//override the jshint cli in the grunt-contrib-jshint lib folder
var libJsHint = proxyquire('grunt-contrib-jshint/tasks/lib/jshint',{
'jshint/src/cli': jshintcli
});
//insert the modified version of the jshint lib to the grunt-contrib-jshint taks
var gruntContribJshint = proxyquire('grunt-contrib-jshint/tasks/jshint',{
'./lib/jshint': libJsHint
});
//return the modified grunt-contrib-jshint version
module.exports = gruntContribJshint;
| JavaScript | 0.000002 | @@ -71,18 +71,16 @@
;%0Atry %7B%0A
-
var re
@@ -114,22 +114,21 @@
);%0A%7D
-%0A
+
catch
+
(e) %7B%0A
-
th
@@ -611,18 +611,16 @@
file) %7B%0A
-
var is
@@ -693,16 +693,18 @@
!== -1;%0A
+
//added
@@ -750,18 +750,16 @@
comment%0A
-
var ha
@@ -824,18 +824,16 @@
.jsx;%0A
-
-
if (isJs
@@ -853,28 +853,24 @@
Docblock) %7B%0A
-
code = '
@@ -902,22 +902,18 @@
code;%0A
-
-
%7D%0A
-
if (is
@@ -934,28 +934,24 @@
Docblock) %7B%0A
-
var comp
@@ -957,20 +957,16 @@
piled;%0A%0A
-
try
@@ -973,22 +973,16 @@
%7B%0A
-
-
compiled
@@ -1003,28 +1003,24 @@
form(code);%0A
-
%7D catch
@@ -1033,22 +1033,16 @@
%7B%0A
-
-
throw ne
@@ -1143,19 +1143,11 @@
- %7D%0A%0A
+%7D%0A%0A
@@ -1197,21 +1197,17 @@
ile);%0A
- %7D%0A
+%7D
else %7B%0A
@@ -1393,24 +1393,25 @@
lib/jshint',
+
%7B%0A 'jshint/
@@ -1589,16 +1589,17 @@
jshint',
+
%7B%0A './l
@@ -1713,9 +1713,8 @@
Jshint;%0A
-%0A
|
8d866b6989204e386fb31e104ad457a4ff6076e4 | Allowing question messages to be functions | tasks/prompt.js | tasks/prompt.js | /*
* grunt-prompt
* https://github.com/dylang/grunt-prompt
*
* Copyright (c) 2013 Dylan Greene
* Licensed under the MIT license.
*/
'use strict';
module.exports = function (grunt) {
grunt.registerMultiTask('prompt', 'Interactive command line user prompts.', function () {
var inquirer = require('inquirer'),
options = this.options(),
_ = require('lodash');
var questions = options.questions;
function addSeparator(choices) {
if (!choices || _.isFunction(choices)) {
return choices;
}
return choices.map(function(choice){
if (choice === '---') {
return new inquirer.Separator();
}
return choice;
});
}
if (questions) {
var done = this.async();
questions = questions.map(function(question){
// config just made more sense than name, but we accept both
question.name = question.config || question.name;
question.choices = addSeparator(question.choices);
return question;
});
inquirer.prompt( questions, function( answers ) {
_(answers).forEach(function(answer, configName){
grunt.config(configName, answer);
});
if (_.isFunction(options.then)) {
options.then(answers);
}
done();
});
}
});
};
| JavaScript | 0.999999 | @@ -1127,24 +1127,155 @@
n.choices);%0A
+ if (_.isFunction(question.message)) %7B%0A question.message = question.message();%0A %7D%0A
|
6e7b159542c6dd26d6c837ee710d375f2a37387e | Test pull 2. | helloworld.js | helloworld.js | // This function will return "Hello World"
function helloworld(){
return "Hello Wooo"
}
console.log(helloworld())
| JavaScript | 0 | @@ -66,27 +66,25 @@
%0A return %22H
-ell
+o
o Wooo%22%0A%7D%0A%0Ac
|
474c5a82fa160abd2e0201b93c40c23eda25f8a6 | Update compare.js | tests/utils/compare.js | tests/utils/compare.js | /* global XMLHttpRequest, expect */
function loadBinaryResource (url) {
const req = new XMLHttpRequest()
req.open('GET', url, false)
// XHR binary charset opt by Marcus Granado 2006 [http://mgran.blogspot.com]
req.overrideMimeType('text\/plain; charset=x-user-defined')
req.send(null)
if (req.status !== 200) {
throw new Error('Unable to load file')
}
return req.responseText
}
function sendReference (filename, data) {
const req = new XMLHttpRequest()
req.open('POST', `http://localhost:9090/${filename}`, true)
req.onload = e => {
console.log(e)
}
req.send(data)
}
const resetCreationDate = input =>
input.replace(
/\/CreationDate \(D:(.*?)\)/,
'/CreationDate (D:19871210000000+00\'00\'\)'
)
/**
* Find a better way to set this
* @type {Boolean}
*/
window.comparePdf = (actual, expectedFile, suite) => {
let pdf;
let ready = false;
let result = '';
let check = function() {
if (ready === true) {
const expected = resetCreationDate(pdf).trim()
actual = resetCreationDate(actual.trim())
expect(actual).toEqual(expected)
return;
}
setTimeout(check, 1000);
}
check();
let reader = new FileReader();
reader.onloadend = function(evt) {
// file is loaded
pdf = evt.target.result;
ready = true;
};
reader.onerror = function () {
sendReference(`/tests/${suite}/reference/${expectedFile}`, resetCreationDate(actual))
pdf = actual
}
reader.readAsDataURL(`/base/tests/${suite}/reference/${expectedFile}`);
}
| JavaScript | 0.000001 | @@ -1559,15 +1559,12 @@
adAs
-DataURL
+Text
(%60/b
|
96cac85e8153f9a34a5a5e0e0f97865210d0bbf6 | Fix a typo | src/_extras/Indigo/kekule.indigo.base.js | src/_extras/Indigo/kekule.indigo.base.js | /**
* Created by ginger on 2017/5/9.
*/
/*
* requires /utils/kekule.utils.js
* requires /core/kekule.common.js
* requires /core/kekule.structures.js
* requires /_extras/kekule.emscriptenUtils.js
* requires /localization/
*/
(function($root){
"use strict";
/** @ignore */
var EU = Kekule.EmscriptenUtils;
/**
* Initialization options of OpenBabel js module.
* @private
* @ignore
*/
var indigoInitOptions = {
usingModulaize: true, // whether using modularize option to build Indigo.js
moduleName: 'IndigoModule', // the name of OpenBabl module
moduleInitEventName: 'Indigo.Initialized',
moduleInitCallbackName: '__$indigoInitialized$__',
indigoAdaptFuncName: 'CreateIndigo'
};
/**
* Namespace of Indigo related objects.
* @namespace
*/
Kekule.Indigo = {
/**
* A flag, whether auto enable InChI function when find InChI lib is already loaded.
*/
_autoEnabled: true,
/** @private */
_module: null, // a variable to store created OpenBabel module object
/** @private */
_indigo: null,
/** @private */
SCRIPT_FILE: 'indigo.js',
/** @private */
HELPER_SCRIPT_FILE: 'indigoAdapter.js',
/** @private */
_enableFuncs: [],
isScriptLoaded: function()
{
return EU.isSupported(indigoInitOptions.moduleName)
&& (typeof($root[indigoInitOptions.indigoAdaptFuncName]) !== 'undefined');
},
getModule: function()
{
if (!KI._module)
{
KI._module = EU.getRootModule(indigoInitOptions.moduleName);
}
return KI._module;
},
setModule: function(module)
{
KI._module = module;
EU.setRootModule(indigoInitOptions.moduleName, module);
},
/**
* Returns Indigo adapter instance.
*/
getIndigo: function()
{
if (!KI._indigo)
{
var module = KI.getModule();
if (module)
KI._indigo = ($root[indigoInitOptions.indigoAdaptFuncName])(module);
}
return KI._indigo;
},
getClassCtor: function(className)
{
return EU.getClassCtor(className, KI.getModule());
},
/**
* Check if OpenBabel js file is successful loaded and available.
* @returns {Bool}
*/
isAvailable: function()
{
return KI.getModule() && KI.getIndigo();
},
/**
* Load Indigo.js lib and enable all related functions
*/
enable: function(callback)
{
if (!KI.isScriptLoaded()) // Indigo not loaded?
{
KI.loadIndigoScript(Kekule.$jsRoot.document, function(error){
//Kekule.IO.registerAllInChIFormats();
if (!error)
KI._enableAllFunctions();
if (callback)
callback(error);
});
}
else
{
KI._enableAllFunctions();
if (callback)
callback();
}
},
_enableAllFunctions: function()
{
//if (KI.isScriptLoaded())
if (EU.isModuleReady(indigoInitOptions.moduleName))
{
var funcs = KI._enableFuncs;
for (var i = 0, l = funcs.length; i < l; ++i)
{
var func = funcs[i];
if (func)
func();
}
}
}
};
/** @ignore */
Kekule.Indigo.getIndigoPath = function()
{
var path = Kekule.environment.getEnvVar('indigo.path');
if (!path)
{
var isMin = Kekule.scriptSrcInfo.useMinFile;
path = isMin ? 'extra/' : '_extras/Indigo/';
path = Kekule.scriptSrcInfo.path + path;
}
return path;
};
/** @ignore */
Kekule.Indigo.getIndigoScriptUrl = function()
{
var result = Kekule.environment.getEnvVar('indigo.path');
if (!result)
{
result = KI.getIndigoPath() + KI.SCRIPT_FILE;
var isMin = Kekule.scriptSrcInfo.useMinFile;
if (!isMin)
result += '.dev';
}
return result;
};
Kekule.Indigo.getIndigoHelperScriptUrl = function()
{
var result = KI.getIndigoPath() + KI.HELPER_SCRIPT_FILE;
return result;
};
/** @ignore */
Kekule.Indigo.loadIndigoScript = function(doc, callback)
{
if (!doc)
doc = Kekule.$jsRoot.document;
var done = function(error)
{
KI._scriptLoadedBySelf = !error;
if (!error)
Kekule.Indigo.getIndigo();
if (callback)
callback(error);
};
if (!KI._scriptLoadedBySelf && !KI.isScriptLoaded())
{
var filePath = KI.getIndigoScriptUrl();
EU.loadScript(filePath,
function(error){
if (!error)
Kekule.ScriptFileUtils.appendScriptFiles(doc, [KI.getIndigoHelperScriptUrl()], done);
else
done(error);
},
doc, indigoInitOptions);
}
else
{
done();
}
/*
if (!KI._scriptLoadedBySelf && !KI.isScriptLoaded())
{
//console.log('load');
//var urls = [KI.getIndigoScriptUrl(), KI.getIndigoHelperScriptUrl()];
//Kekule.ScriptFileUtils.appendScriptFiles(doc, urls, done);
EU.loadScript(KI.getIndigoScriptUrl(), function(){
// when finish initialize indigo.js, load the adapter
Kekule.ScriptFileUtils.appendScriptFiles(doc, [KI.getIndigoHelperScriptUrl()], done);
}, doc, indigoInitOptions);
KI._scriptLoadedBySelf = true;
}
else
{
KI._scriptLoadedBySelf = true;
if (callback)
callback();
}
*/
};
var KI = Kekule.Indigo;
/**
* Util class to convert object between Indigo and Kekule.
* Unfinished
* @class
* @ignore
*/
Kekule.Indigo.AdaptUtils = {
};
Kekule._registerAfterLoadSysProc(function() {
if (KI._autoEnabled && KI.isScriptLoaded())
{
EU.ensureModuleReady(Kekule.$jsRoot.document, indigoInitOptions, KI._enableAllFunctions);
}
});
})(this);
| JavaScript | 1 | @@ -3197,36 +3197,41 @@
tEnvVar('indigo.
-path
+scriptSrc
');%0A%09if (!result
|
3ff2fdfcee2270aafad6308b9b239564bbf176a1 | fix tests | src/components/Editor/tests/DebugLine.js | src/components/Editor/tests/DebugLine.js | import React from "react";
import { shallow } from "enzyme";
import DebugLine from "../DebugLine";
jest.mock(
"../../../utils/editor/source-documents",
jest.fn(() => ({
getDocument: jest.fn()
}))
);
import { getDocument } from "../../../utils/editor/source-documents";
getDocument.mockImplementation(() => ({
addLineClass: jest.fn(),
removeLineClass: jest.fn()
}));
const DebugLineComponent = React.createFactory(DebugLine);
function generateDefaults(overrides) {
return {
editor: {
codeMirror: {
markText: () => ({ clear: jest.fn() })
}
},
selectedFrame: {
location: {
sourceId: "x",
line: 2
}
},
...overrides
};
}
function render(overrides = {}) {
const props = generateDefaults(overrides);
const component = shallow(new DebugLineComponent(props));
return { component, props };
}
describe("DebugLine Component", () => {
describe("mount", () => {
it("should keep the debugExpression state", async () => {
const { component } = render();
expect(component.state().debugExpression).toBeDefined();
expect(component.state().debugExpression.clear).toBeDefined();
});
});
describe("unmount", () => {
it("should remove the debug line", async () => {
const { component, props: { editor } } = render();
component.unmount();
expect(editor.codeMirror.removeLineClass).toHaveBeenCalled();
});
it("should clear the debug line", async () => {
const { component, props: { editor } } = render();
component.unmount();
expect(editor.codeMirror.removeLineClass).toHaveBeenCalled();
});
});
describe("update", () => {
const selectedLocation = {
location: {
sourceId: "x",
line: 1
}
};
fit("should remove the old debug line", async () => {
const { component } = render();
component.setProps({ selectedLocation });
const getDoc = getDocument();
expect(getDoc.removeLineClass).toHaveBeenCalled();
});
it("should clear the previous debugExpression", async () => {
const { component } = render();
const previousState = component.state();
component.setProps({ selectedLocation });
expect(previousState.debugExpression.clear).toHaveBeenCalled();
});
it("should add a new line and debugExpression", async () => {
const { component } = render();
const previousState = component.state();
component.setProps({ selectedLocation });
const currentState = component.state();
expect(currentState.debugExpression).toBeDefined();
expect(currentState.debugExpression.clear).toBeDefined();
expect(previousState.debugExpression).not.toBe(
currentState.debugExpression
);
});
});
});
| JavaScript | 0.000001 | @@ -102,19 +102,16 @@
st.mock(
-%0A
%22../../.
@@ -147,19 +147,9 @@
ts%22,
-%0A jest.fn(
+
() =
@@ -153,18 +153,16 @@
) =%3E (%7B%0A
-
getDoc
@@ -182,14 +182,10 @@
n()%0A
- %7D))%0A
+%7D)
);%0Ai
@@ -257,46 +257,32 @@
s%22;%0A
-getDocument.mockImplementation(() =%3E (
+const mockGetDocument =
%7B%0A
@@ -336,17 +336,70 @@
t.fn()%0A%7D
-)
+;%0AgetDocument.mockImplementation(() =%3E mockGetDocument
);%0A%0Acons
@@ -1312,35 +1312,16 @@
omponent
-, props: %7B editor %7D
%7D = ren
@@ -1367,33 +1367,31 @@
expect(
-editor.codeMirror
+mockGetDocument
.removeL
@@ -1508,27 +1508,8 @@
nent
-, props: %7B editor %7D
%7D =
@@ -1563,25 +1563,23 @@
ect(
-editor.codeMirror
+mockGetDocument
.rem
@@ -1764,17 +1764,16 @@
%7D;%0A%0A
-f
it(%22shou
@@ -1913,57 +1913,30 @@
-const getDoc = getDocument();%0A expect(getDoc
+expect(mockGetDocument
.rem
|
365aa4d1784acc5c34591f4c540caa2d1e810cf5 | Fix bug that stopped tag name filter from working | src/components/PineTypes/KeyValuePair.js | src/components/PineTypes/KeyValuePair.js | import * as React from 'react'
import * as RegexParser from 'regex-parser'
import * as isArray from 'lodash/isArray'
import * as assign from 'lodash/assign'
import * as some from 'lodash/some'
import * as includes from 'lodash/includes'
import * as isString from 'lodash/isString'
import * as values from 'lodash/values'
import * as keys from 'lodash/keys'
import Input from '../Input'
import { Flex } from '../Grid'
const normalizeToCollection = value => (isArray(value) ? value : [value])
export const rules = {
is: (target, value) => {
return some(normalizeToCollection(target), value)
},
'is not': (target, value) => {
return !some(normalizeToCollection(target), value)
},
'key is': {
getLabel: schema => schema.keyLabel && `${schema.keyLabel} is`,
test: (target, value) => {
return some(normalizeToCollection(target), value)
}
},
'key contains': {
getLabel: schema => schema.keyLabel && `${schema.keyLabel} contains`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return some(
normalizeToCollection(target),
item => item && item[lookupKey] && item[lookupKey].includes(lookupValue)
)
}
},
'key does not contain': {
getLabel: schema =>
schema.keyLabel && `${schema.keyLabel} does not contain`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return !some(
normalizeToCollection(target),
item => item && item[lookupKey] && item[lookupKey].includes(lookupValue)
)
}
},
'key matches RegEx': {
getLabel: schema => schema.keyLabel && `${schema.keyLabel} matches RegEx`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return some(
normalizeToCollection(target),
item =>
item &&
item[lookupKey] &&
item[lookupKey].match(RegexParser(lookupValue))
)
}
},
'key does not match RegEx': {
getLabel: schema =>
schema.keyLabel && `${schema.keyLabel} does not match RegEx`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return !some(
normalizeToCollection(target),
item =>
item &&
item[lookupKey] &&
item[lookupKey].match(RegexParser(lookupValue))
)
}
},
'value is': {
getLabel: schema => schema.valueLabel && `${schema.valueLabel} is`,
test: (target, value) => {
return some(normalizeToCollection(target), value)
}
},
'value contains': {
getLabel: schema => schema.valueLabel && `${schema.valueLabel} contains`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return some(
normalizeToCollection(target),
item => item && item[lookupKey] && item[lookupKey].includes(lookupValue)
)
}
},
'value does not contain': {
getLabel: schema =>
schema.valueLabel && `${schema.valueLabel} does not contain`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return !some(
normalizeToCollection(target),
item => item && item[lookupKey] && item[lookupKey].includes(lookupValue)
)
}
},
'value matches RegEx': {
getLabel: schema =>
schema.valueLabel && `${schema.valueLabel} matches RegEx`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return some(
normalizeToCollection(target),
item =>
item &&
item[lookupKey] &&
item[lookupKey].match(RegexParser(lookupValue))
)
}
},
'value does not match RegEx': {
getLabel: schema =>
schema.valueLabel && `${schema.valueLabel} does not match RegEx`,
test: (target, value) => {
const lookupKey = keys(value).pop()
const lookupValue = values(value).pop()
return !some(normalizeToCollection(target), item => {
return (
item &&
item[lookupKey] &&
item[lookupKey].match(RegexParser(lookupValue))
)
})
}
}
}
export const validate = value => true
export const normalize = value => value
const keyOperators = [
'is',
'is not',
'key is',
'key contains',
'key does not contain',
'key matches RegEx',
'key does not match RegEx'
]
const valueOperators = [
'is',
'is not',
'value is',
'value contains',
'value does not contain',
'value matches RegEx',
'value does not match RegEx'
]
export const Edit = props => {
const { schema, onChange, operator } = props
let { value } = props
// Convert strings to objects
if (isString(value)) {
value = { [schema.value]: value }
}
return (
<Flex wrap>
{includes(keyOperators, operator) && (
<Input
type='text'
value={value ? value[schema.key] : ''}
mr={2}
mb={1}
placeholder={schema.keyLabel || 'Key'}
onChange={e =>
onChange(assign(value, { [schema.key]: e.target.value }))
}
/>
)}
{includes(valueOperators, operator) && (
<Input
type='text'
value={value ? value[schema.value] : ''}
placeholder={schema.valueLabel || 'Value'}
onChange={e =>
onChange(assign(value, { [schema.value]: e.target.value }))
}
/>
)}
</Flex>
)
}
export const Display = ({ data, ...props }) => (
<div {...props}>{JSON.stringify(data)}</div>
)
| JavaScript | 0 | @@ -4923,18 +4923,72 @@
-value = %7B
+let p = %7B%7D%0A if (includes(valueOperators, operator)) %7B%0A p
%5Bsch
@@ -5001,17 +5001,115 @@
lue%5D
-:
+ =
value
- %7D
+%0A %7D%0A if (includes(keyOperators, operator)) %7B%0A p%5Bschema.key%5D = value%0A %7D%0A%0A value = p
%0A %7D
|
4575e0002bcaa49267ff3104c5fec332602bfb88 | fix memory leak on scroll tear down, remove duplicate elm find, apply offsetX faster and only when needed | src/components/body/ScrollerDirective.js | src/components/body/ScrollerDirective.js | import { requestAnimFrame } from '../../utils/utils';
import { StyleTranslator } from './StyleTranslator';
import { TranslateXY } from '../../utils/translate';
export function ScrollerDirective($timeout){
return {
restrict: 'E',
require:'^dtBody',
transclude: true,
replace: true,
template: `<div ng-style="scrollerStyles()" ng-transclude></div>`,
link: function($scope, $elm, $attrs, ctrl){
var ticking = false,
lastScrollY = 0,
lastScrollX = 0,
parent = $elm.parent();
ctrl.options.internal.styleTranslator =
new StyleTranslator(ctrl.options.rowHeight);
ctrl.options.internal.setYOffset = function(offsetY){
parent[0].scrollTop = offsetY;
};
function update(){
$scope.$applyAsync(() => {
ctrl.options.internal.offsetY = lastScrollY;
ctrl.options.internal.offsetX = lastScrollX;
ctrl.updatePage();
if(ctrl.options.scrollbarV){
ctrl.getRows();
}
});
ticking = false;
};
function requestTick() {
if(!ticking) {
requestAnimFrame(update);
ticking = true;
}
};
$elm.parent().on('scroll', function(ev) {
lastScrollY = this.scrollTop;
lastScrollX = this.scrollLeft;
requestTick();
});
$scope.scrollerStyles = function(){
if(ctrl.options.scrollbarV){
return {
height: ctrl.count * ctrl.options.rowHeight + 'px'
}
}
};
}
};
};
| JavaScript | 0 | @@ -758,24 +758,197 @@
n update()%7B%0A
+ if(lastScrollX !== ctrl.options.internal.offsetX)%7B%0A $scope.$apply(() =%3E %7B%0A ctrl.options.internal.offsetX = lastScrollX;%0A %7D);%0A %7D%0A%0A
$sco
@@ -1029,63 +1029,8 @@
lY;%0A
- ctrl.options.internal.offsetX = lastScrollX;%0A
@@ -1324,29 +1324,22 @@
%0A%0A
-$elm.
parent
-()
.on('scr
@@ -1466,24 +1466,102 @@
%0A %7D);%0A%0A
+ $scope.$on('$destroy', () =%3E %7B%0A parent.off('scroll');%0A %7D);%0A%0A
$scope
|
9440d50a1e3fe2946700c61d9205d67bbfa7676a | Store the reference to React component in DOM | lib/assets/javascripts/react_ujs.js | lib/assets/javascripts/react_ujs.js | /*globals React, Turbolinks*/
// Unobtrusive scripting adapter for React
(function(document, window) {
// jQuery is optional. Use it to support legacy browsers.
var $ = (typeof window.jQuery !== 'undefined') && window.jQuery;
// create the namespace
window.ReactRailsUJS = {
CLASS_NAME_ATTR: 'data-react-class',
PROPS_ATTR: 'data-react-props',
// helper method for the mount and unmount methods to find the
// `data-react-class` DOM elements
findDOMNodes: function() {
// we will use fully qualified paths as we do not bind the callbacks
var selector = '[' + window.ReactRailsUJS.CLASS_NAME_ATTR + ']';
if ($) {
return $(selector);
} else {
return document.querySelectorAll(selector);
}
},
mountComponents: function() {
var nodes = window.ReactRailsUJS.findDOMNodes();
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
var className = node.getAttribute(window.ReactRailsUJS.CLASS_NAME_ATTR);
// Assume className is simple and can be found at top-level (window).
// Fallback to eval to handle cases like 'My.React.ComponentName'.
var constructor = window[className] || eval.call(window, className);
var propsJson = node.getAttribute(window.ReactRailsUJS.PROPS_ATTR);
var props = propsJson && JSON.parse(propsJson);
React.render(React.createElement(constructor, props), node);
}
},
unmountComponents: function() {
var nodes = window.ReactRailsUJS.findDOMNodes();
for (var i = 0; i < nodes.length; ++i) {
var node = nodes[i];
React.unmountComponentAtNode(node);
// now remove the `data-react-class` wrapper as well
node.parentElement && node.parentElement.removeChild(node);
}
}
};
// functions not exposed publicly
function handleTurbolinksEvents () {
var handleEvent;
if ($) {
handleEvent = function(eventName, callback) {
$(document).on(eventName, callback);
};
} else {
handleEvent = function(eventName, callback) {
document.addEventListener(eventName, callback);
};
}
handleEvent('page:change', window.ReactRailsUJS.mountComponents);
handleEvent('page:receive', window.ReactRailsUJS.unmountComponents);
}
function handleNativeEvents() {
if ($) {
$(window.ReactRailsUJS.mountComponents);
$(window).unload(window.ReactRailsUJS.unmountComponents);
} else {
document.addEventListener('DOMContentLoaded', window.ReactRailsUJS.mountComponents);
window.addEventListener('unload', window.ReactRailsUJS.unmountComponents);
}
}
if (typeof Turbolinks !== 'undefined' && Turbolinks.supported) {
handleTurbolinksEvents();
} else {
handleNativeEvents();
}
})(document, window);
| JavaScript | 0.00001 | @@ -224,19 +224,17 @@
jQuery;%0A
-
%0A
+
// cre
@@ -422,17 +422,16 @@
find the
-
%0A //
@@ -567,19 +567,16 @@
allbacks
-
%0A v
@@ -639,23 +639,17 @@
+ '%5D';%0A
-
%0A
+
if
@@ -761,29 +761,25 @@
%7D%0A %7D,%0A
-
%0A
+
mountCom
@@ -847,39 +847,33 @@
findDOMNodes();%0A
-
%0A
+
for (var i
@@ -1013,25 +1013,17 @@
_ATTR);%0A
-
%0A
+
@@ -1376,24 +1376,25 @@
sJson);%0A
+%0A
%0A
@@ -1381,32 +1381,39 @@
);%0A%0A
-%0A
+var component =
React.rende
@@ -1458,24 +1458,99 @@
ps), node);%0A
+ if ($) %7B%0A $(node).data('component', component);%0A %7D%0A
%7D%0A
@@ -1552,21 +1552,17 @@
%0A %7D,%0A
-
%0A
+
unmo
@@ -1644,23 +1644,17 @@
odes();%0A
-
%0A
+
fo
@@ -1725,17 +1725,9 @@
i%5D;%0A
-
%0A
+
@@ -2011,21 +2011,17 @@
eEvent;%0A
-
%0A
+
if (
@@ -2131,23 +2131,17 @@
%7D;%0A
-
%0A
+
%7D el
@@ -2462,19 +2462,16 @@
if ($) %7B
-
%0A $
@@ -2574,22 +2574,16 @@
nents);%0A
-
%0A %7D e
|
700017fccf75b57cc3f6a92178bf42b2d97f9809 | Add missing await (#207) | lib/basedriver/commands/settings.js | lib/basedriver/commands/settings.js | import log from '../logger';
let commands = {};
commands.updateSettings = async function (newSettings) {
if (!this.settings) {
log.errorAndThrow('Cannot update settings; settings object not found');
}
return this.settings.update(newSettings);
};
commands.getSettings = async function () {
if (!this.settings) {
log.errorAndThrow('Cannot get settings; settings object not found');
}
return this.settings.getSettings();
};
export default commands;
| JavaScript | 0.000038 | @@ -205,32 +205,38 @@
);%0A %7D%0A return
+await
this.settings.up
@@ -411,16 +411,22 @@
return
+await
this.set
|
d79a1ae985270ee04fc5d2e6344722722580be8c | Fix JSON-LD datatype handling. | lib/datasources/JsonLdDatasource.js | lib/datasources/JsonLdDatasource.js | /*! @license MIT ©2014-2016 Ruben Verborgh, Ghent University - imec */
/* An JsonLdDatasource fetches data from a JSON-LD document. */
var MemoryDatasource = require('./MemoryDatasource'),
jsonld = require('jsonld');
var ACCEPT = 'application/ld+json;q=1.0,application/json;q=0.7';
// Creates a new JsonLdDatasource
function JsonLdDatasource(options) {
if (!(this instanceof JsonLdDatasource))
return new JsonLdDatasource(options);
MemoryDatasource.call(this, options);
this._url = options && (options.url || options.file);
}
MemoryDatasource.extend(JsonLdDatasource);
// Retrieves all triples from the document
JsonLdDatasource.prototype._getAllTriples = function (addTriple, done) {
// Read the JSON-LD document
var json = '',
document = this._fetch({ url: this._url, headers: { accept: ACCEPT } });
document.on('data', function (data) { json += data; });
document.on('end', function () {
// Parse the JSON document
try { json = JSON.parse(json); }
catch (error) { return done(error); }
// Convert the JSON-LD to triples
extractTriples(json, addTriple, done);
});
};
// Extracts triples from a JSON-LD document
function extractTriples(json, addTriple, done) {
jsonld.toRDF(json, function (error, triples) {
for (var graphName in triples) {
triples[graphName].forEach(function (triple) {
addTriple(triple.subject.value,
triple.predicate.value,
convertEntity(triple.object));
});
}
done(error);
});
}
// Converts a jsonld.js entity to an N3.js IRI or literal
function convertEntity(entity) {
// Return IRIs and blank nodes as-is
if (entity.type !== 'literal')
return entity.value;
else {
// Add a language tag to the literal if present
if ('language' in entity)
return '"' + entity.value + '"@' + entity.language;
// Add a datatype to the literal if present
if (entity.datatype !== 'http://www.w3.org/2001/XMLSchema#string')
return '"' + entity.value + '"^^<' + entity.datatype + '>';
// Otherwise, return the regular literal
return '"' + entity.value + '"';
}
}
module.exports = JsonLdDatasource;
| JavaScript | 0.000006 | @@ -1560,31 +1560,42 @@
to
-an
+the
N3.js
-IRI or literal
+in-memory representation
%0Afun
@@ -2031,9 +2031,8 @@
'%22%5E%5E
-%3C
' +
@@ -2050,14 +2050,8 @@
type
- + '%3E'
;%0A
|
a0b38f4a558c1d075aa17ea686b44bfc3395549a | Clean up code | src/containers/auth/signup-form/index.js | src/containers/auth/signup-form/index.js | import React, { Component, PropTypes } from 'react';
import { reduxForm } from 'redux-form';
import { IndexLink, hashHistory } from 'react-router';
import Modal from 'react-bootstrap/lib/Modal';
import client from 'utils/api-client';
import signupValidation from 'containers/auth/signup-form/signup-validation';
import formLabelError from 'components/error-views/form-label-error';
import TermsOfService from 'components/copy/terms-of-service';
import NewReferralUserBanner from 'components/auth/new-referral-user-banner';
import NewUserBanner from 'components/auth/new-user-banner';
import { connect } from 'react-apollo';
import gql from 'graphql-tag';
import Promise from 'bluebird';
import axios from 'axios';
import config from 'config'
const BILLING_URL = process.env.APOLLO_CLIENT_URL;
@reduxForm({
form: 'Signup',
fields: ['email', 'password', 'eula'],
validate: signupValidation
})
export default class SignUpForm extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
error: PropTypes.string,
handleSubmit: PropTypes.func.isRequired,
submitFailed: PropTypes.bool.isRequired
};
constructor(props) {
super(props);
this.state = {
showEula: false,
showReferralBanner: false
};
this.submit = this.submit.bind(this);
};
componentWillMount() {
if (this.props.location.query.referralLink) {
this.setState({ showReferralBanner: true });
} else {
this.setState({ showReferralBanner: false });
}
};
openEula(event) {
event.preventDefault();
this.setState({ showEula: true });
}
closeEula() {
this.setState({ showEula: false });
}
submit() {
return new Promise((resolve, reject) => {
const credentials = {
email: this.props.fields.email.value,
password: this.props.fields.password.value,
redirect: 'https://app.storj.io/'
};
const referral = {
referralLink: this.props.location.query.referralLink,
email: this.props.fields.email.value
}
client.api.createUser(credentials).then((result) => {
if (result.error) {
return reject({ _error: result.error })
} else {
axios.post(BILLING_URL + '/credits/signups', referral)
.then((res) => {
hashHistory.push('/signup-success');
return resolve(res);
})
.catch((err) => console.error(err));
}
}, (err) => {
if (err && err.message) {
reject({_error: err.message});
}
});
});
}
renderEula() {
return (
<Modal show={this.state.showEula} onHide={this.closeEula.bind(this)} bsSize="large">
<Modal.Header closeButton><h1 className="text-center">Storj Labs</h1></Modal.Header>
<Modal.Body>
<TermsOfService/>
</Modal.Body>
<Modal.Footer>
<button className="btn btn-transparent" onClick={this.closeEula.bind(this)}>Close</button>
</Modal.Footer>
</Modal>
);
}
render() {
const {fields: {email, password, eula}, error, submitFailed, handleSubmit} = this.props;
return (
<div className="container auth">
{this.renderEula()}
<div className="row">
<div className="col-lg-6 col-lg-push-3 col-md-8 col-md-push-2 col-xs-12 text-center">
<div className="row">
<div className="col-sm-12">
<div className="content">
<h1 className="title text-center form-group">Sign Up</h1>
{
this.state.showReferralBanner
? <NewReferralUserBanner></NewReferralUserBanner>
: <NewUserBanner></NewUserBanner>
}
<form>
<div className={`
form-group
${submitFailed && email.error ? 'has-error' : ''}
`}>
{submitFailed && formLabelError(email)}
<input
type="email"
className="form-control"
name="email"
placeholder="Email Address"
{...email}
/>
</div>
<div className={`
form-group
${submitFailed && password.error ? 'has-error' : ''}
`}>
{submitFailed && formLabelError(password)}
<input
type="password"
className="form-control"
name="password"
placeholder="Password"
{...password}
/>
</div>
<div className="form-group">
<button
type="submit"
onClick={handleSubmit(this.submit)}
className="btn btn-block btn-green"
>
Sign Up
</button>
</div>
<div className="form-group checkbox">
<label>
<p>
<input
type="checkbox"
className="text-right"
name="eula"
{...eula}
/>
I agree to the
<a href="#noop" onClick={this.openEula.bind(this)}>Terms of Service </a>
</p>
</label>
</div>
{error && <div><span className="text-danger">{error}</span></div>}
{eula.error && eula.touched && <div><span className="text-danger">{eula.error}</span></div>}
</form>
</div>
<p>Already have an account?
<IndexLink to="/" className="login">Log In</IndexLink>
</p>
</div>
</div>
</div>
</div>
</div>
);
}
}
| JavaScript | 0.000004 | @@ -2180,31 +2180,25 @@
%7D)%0A %7D
- else %7B
+%0A
%0A a
@@ -2194,18 +2194,16 @@
-
axios.po
@@ -2249,18 +2249,16 @@
ferral)%0A
-
@@ -2288,18 +2288,16 @@
-
hashHist
@@ -2329,34 +2329,32 @@
');%0A
-
-
return resolve(r
@@ -2372,15 +2372,11 @@
-
%7D)%0A
-
@@ -2418,25 +2418,16 @@
(err));%0A
- %7D
%0A %7D
|
e1bfffd59b479ecd56470dff565c812a56c70577 | Add StocktakeBatch reason helpers | src/database/DataTypes/StocktakeBatch.js | src/database/DataTypes/StocktakeBatch.js | import Realm from 'realm';
import { createRecord } from '../utilities';
/**
* A stocktake batch.
*
* @property {string} id
* @property {Stocktake} stocktake
* @property {ItemBatch} itemBatch
* @property {number} snapshotNumberOfPacks
* @property {number} packSize
* @property {Date} expiryDate
* @property {string} batch
* @property {number} costPrice
* @property {number} sellPrice
* @property {number} countedNumberOfPacks
* @property {number} sortIndex
*/
export class StocktakeBatch extends Realm.Object {
/**
* Delete stocktake batch and associated item batch.
*
* @param {Realm} database
*/
destructor(database) {
if (this.snapshotNumberOfPacks === 0 && this.itemBatch.numberOfPacks === 0) {
database.delete('ItemBatch', this.itemBatch);
}
}
/**
* Get snapshot of total quantity in batch.
*
* @return {number}
*/
get snapshotTotalQuantity() {
return this.snapshotNumberOfPacks * this.packSize;
}
/**
* Get total quantity in batch.
*
* @return {number}
*/
get countedTotalQuantity() {
if (this.countedNumberOfPacks === null) return this.snapshotTotalQuantity;
return this.countedNumberOfPacks * this.packSize;
}
/**
* Get if stocktake will reduce stock on hand of item below zero.
*
* Stock on hand should never be negative. This can occur when stock has been issued
* in a customer invoice for this batch before the parent stocktake was finalised.
*
* @return {boolean}
*/
get isReducedBelowMinimum() {
const { totalQuantity: stockOnHand } = this.itemBatch;
// Return true if |stockOnHand + stocktakebatch.difference| is negative.
return stockOnHand + this.difference < 0;
}
/**
* Get if snapshot is out-of-date.
*
* Returns true if the |snapshotTotalQuantity| does not match the |totalQuantity| of the
* item batch this stocktake batch is associated with. Will occur if inventory has changed
* since this stocktake batch was created. If the net change on this batch is 0, then return
* false.
*
* @return {boolean}
*/
get isSnapshotOutdated() {
return this.snapshotTotalQuantity !== this.itemBatch.totalQuantity;
}
/**
* Get if stocktake batch has been counted.
*
* @return {boolean}
*/
get hasBeenCounted() {
return this.countedNumberOfPacks !== null;
}
/**
* Get id of item associated with this stocktake batch.
*
* @return {string}
*/
get itemId() {
if (!this.itemBatch) return '';
return this.itemBatch.item ? this.itemBatch.item.id : '';
}
/**
* Get id of item batch associated with this stocktake batch.
*
* @return {string}
*/
get itemBatchId() {
return this.itemBatch ? this.itemBatch.id : '';
}
/**
* Get difference between counted quantity and snapshop quantity.
*
* @return {number}
*/
get difference() {
return this.countedTotalQuantity - this.snapshotTotalQuantity;
}
/**
* Returns whether or not a reason should be applied to this
* stocktake batch.
* @return {bool}
*/
get shouldHaveReason() {
return this.countedTotalQuantity !== this.snapshotTotalQuantity;
}
/**
* Returns a boolean indicator whether a reason needs to be
* enforced on this stock take batch
*/
get enforceReason() {
return this.shouldHaveReason && !this.hasAnyReason;
}
/**
* Set counted total quantity.
*
* @param {number} quantity
*/
set countedTotalQuantity(quantity) {
// Handle packsize of 0.
this.countedNumberOfPacks = this.packSize ? quantity / this.packSize : 0;
}
/**
* Finalise stocktake batch.
*
* Finalising will adjust inventory appropriately and will add a new transaction
* batch in reducing or increasing transaction for this stocktake.
*
* @param {Realm} database
*/
finalise(database) {
// Update the item batch details.
this.itemBatch.batch = this.batch;
this.itemBatch.expiryDate = this.expiryDate;
// Make inventory adjustments if there is a difference to apply.
if (this.difference !== 0) {
const isAddition = this.countedTotalQuantity > this.snapshotTotalQuantity;
const inventoryAdjustment = isAddition
? this.stocktake.getAdditions(database)
: this.stocktake.getReductions(database);
// Create transaction item and transaction batch to store inventory adjustments in this
// stocktake.
const transactionItem = createRecord(
database,
'TransactionItem',
inventoryAdjustment,
this.itemBatch.item
);
const transactionBatch = createRecord(
database,
'TransactionBatch',
transactionItem,
this.itemBatch
);
// Apply difference from stocktake to actual stock on hand levels. Whether stock is increased
// or decreased is determined by the transaction, use the absolute value of difference
// (i.e. always treat as positive).
const snapshotDifference = Math.abs(this.difference);
transactionBatch.setTotalQuantity(database, snapshotDifference);
database.save('TransactionBatch', transactionBatch);
}
database.save('ItemBatch', this.itemBatch);
}
/**
* Get string representation of stocktake batch.
*
* @return {string}
*/
toString() {
return `Stocktake batch representing ${this.itemBatch}`;
}
}
StocktakeBatch.schema = {
name: 'StocktakeBatch',
primaryKey: 'id',
properties: {
id: 'string',
stocktake: 'Stocktake',
itemBatch: 'ItemBatch',
snapshotNumberOfPacks: 'double',
packSize: 'double',
expiryDate: { type: 'date', optional: true },
batch: 'string',
costPrice: 'double',
sellPrice: 'double',
countedNumberOfPacks: { type: 'double', optional: true },
sortIndex: { type: 'int', optional: true },
option: { type: 'Options', optional: true },
},
};
export default StocktakeBatch;
| JavaScript | 0 | @@ -20,16 +20,17 @@
realm';%0A
+%0A
import %7B
@@ -3428,24 +3428,185 @@
eason;%0A %7D%0A%0A
+ /**%0A * @return %7BString%7D this batches reason title, or an empty string.%0A */%0A get reasonTitle() %7B%0A return (this.option && this.option.title) %7C%7C '';%0A %7D%0A%0A
/**%0A * S
@@ -3818,32 +3818,227 @@
kSize : 0;%0A %7D%0A%0A
+ /**%0A * Applies a reason to this batch%0A */%0A applyReason(database, reason) %7B%0A database.write(() =%3E %7B%0A this.option = reason;%0A database.save('StocktakeBatch', this);%0A %7D);%0A %7D%0A%0A
/**%0A * Final
|
2044e89e2b0a5534d9f130f9427538a0bbcfc884 | update fns | fns.js | fns.js | 'use strict'
var undef = void(0)
function hasOwn(obj, prop) {
return obj && obj.hasOwnProperty && obj.hasOwnProperty(prop)
}
module.exports = {
escape: function(markup) {
if (!markup) return '';
return String(markup)
.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/'/g, ''')
.replace(/"/g, '"');
},
type: function(obj) {
if (obj === null) return 'null'
else if (obj === undef) return 'undefined';
var m = /\[object (\w+)\]/.exec(Object.prototype.toString.call(obj));
return m ? m[1].toLowerCase() : '';
},
keys: function(obj) {
var keys = []
if (!obj) return keys
if (Object.keys) return Object.keys(obj)
this.objEach(obj, function(key) {
keys.push(key)
})
return keys
},
bind: function(fn, ctx) {
if (fn.bind) return fn.bind(ctx)
return function() {
return fn.apply(ctx, arguments)
}
},
extend: function(obj) {
if (this.type(obj) != 'object' && this.type(obj) != 'function') return obj;
var source, prop;
for (var i = 1, length = arguments.length; i < length; i++) {
source = arguments[i];
for (prop in source) {
if (hasOwn(source, prop)) {
obj[prop] = source[prop];
}
}
}
return obj;
},
trim: function(str) {
if (str.trim) return str.trim()
else {
return str.replace(/^\s+|\s+$/gm, '')
}
},
indexOf: function(arr, tar) {
if (arr.indexOf) return arr.indexOf(tar)
else {
var i = -1
fns.some(arr, function(item, index) {
if (item === tar) {
i = index
return true
}
})
return i
}
},
forEach: function(arr, fn) {
if (arr.forEach) return arr.forEach(fn)
else {
var len = arr.length
for (var i = 0; i < len; i++) {
fn(arr[i], i)
}
}
return arr
},
some: function(arr, fn) {
if (arr.some) return arr.some(fn)
else {
var len = arr.length
var r = false
for (var i = 0; i < len; i++) {
if (fn(arr[i], i)) {
r = true
break
}
}
return r
}
},
map: function(arr, fn) {
if (arr.map) return arr.map(fn)
else {
var len = arr.length
var next = []
for (var i = 0; i < len; i++) {
next.push(fn(arr[i], i))
}
return next
}
},
objEach: function(obj, fn) {
if (!obj) return
for (var key in obj) {
if (hasOwn(obj, key)) {
if (fn(key, obj[key]) === false) break
}
}
},
filter: function(arr, fn, context) {
if (arr.filter) return arr.filter(fn)
else {
var len = arr.length
var res = []
for (var i = 0; i < len; i++) {
var val = arr[i]
if (fn.call(context, val, i, arr)) {
res.push(val)
}
}
return res
}
},
reduce: function(arr, fn, opt_initialValue) {
if (arr.reduce) return arr.reduce(fn, opt_initialValue)
if ('function' !== typeof fn) {
throw new TypeError(fn + ' is not a function');
}
var index, value,
length = arr.length >>> 0,
isValueSet = false;
if (2 < arguments.length) {
value = opt_initialValue;
isValueSet = true;
}
for (index = 0; length > index; ++index) {
if (arr.hasOwnProperty(index)) {
if (isValueSet) {
value = fn(value, arr[index], index, arr);
} else {
value = arr[index];
isValueSet = true;
}
}
}
if (!isValueSet) {
throw new TypeError('Reduce of empty array with no initial value');
}
return value;
},
/**
* Lock function before lock release
*/
lock: function lock(fn) {
var pending
return function() {
if (pending) return
pending = true
var args = [].slice.call(arguments, 0)
args.unshift(function() {
pending = false
})
fn.apply(this, args)
}
},
/**
* Call only once
*/
once: function(cb /*[, ctx]*/ ) {
var args = arguments.length
var called
return function() {
if (called || !cb) return
called = true
return cb.apply(args.length >= 2 ? args[1] : null, arguments)
}
}
}
| JavaScript | 0.000001 | @@ -5062,23 +5062,16 @@
rguments
-.length
%0D%0A
|
82c052ecdf1b5d1a300a670c779750096be9d42d | Update authActions' endpoints | src/auth/authActions.js | src/auth/authActions.js | import Promise from 'bluebird';
import extend from 'lodash/extend';
import steemConnect from 'steemconnect';
import broadcast from 'steem/lib/broadcast';
import * as actionTypes from './authActionTypes';
import api from '../steemAPI';
Promise.promisifyAll(steemConnect);
export const GET_FOLLOWING = 'GET_FOLLOWING';
export const GET_FOLLOWING_START = 'GET_FOLLOWING_START';
export const GET_FOLLOWING_SUCCESS = 'GET_FOLLOWING_SUCCESS';
export const GET_FOLLOWING_ERROR = 'GET_FOLLOWING_ERROR';
function getFollowing(opts) {
return (dispatch, getState) => {
const { auth } = getState();
const currentUsername = auth.user && auth.user.name;
const options = extend({
follower: currentUsername,
startFollowing: 0,
followType: 'blog',
limit: 100,
}, opts);
dispatch({
type: GET_FOLLOWING,
meta: options,
payload: {
promise: api.getFollowingWithAsync(options),
}
});
};
}
export const FOLLOW_USER = 'FOLLOW_USER';
export const FOLLOW_USER_START = 'FOLLOW_USER_START';
export const FOLLOW_USER_SUCCESS = 'FOLLOW_USER_SUCCESS';
export const FOLLOW_USER_ERROR = 'FOLLOW_USER_ERROR';
export function followUser(username) {
return (dispatch, getState) => dispatch({
type: FOLLOW_USER,
payload: {
promise: steemConnect.sendAsync('https://steemconnect.com/api/customJson', {
json: JSON.stringify([
'follow',
{
follower: getState().auth.user.name,
following: username,
},
]),
requiredAuths: [],
requiredPostingAuths: [
getState().auth.user.name,
],
}),
}
});
}
export const UNFOLLOW_USER = 'UNFOLLOW_USER';
export const UNFOLLOW_USER_START = 'UNFOLLOW_USER_START';
export const UNFOLLOW_USER_SUCCESS = 'UNFOLLOW_USER_SUCCESS';
export const UNFOLLOW_USER_ERROR = 'UNFOLLOW_USER_ERROR';
export function unfollowUser(username) {
return (dispatch, getState) => dispatch({
type: UNFOLLOW_USER,
payload: {
promise: steemConnect.sendAsync('https://steemconnect.com/api/customJson', {
json: JSON.stringify([
'unfollow',
{
unfollower: getState().auth.user.name,
unfollowing: username,
},
]),
requiredAuths: [],
requiredPostingAuths: [
getState().auth.user.name,
],
}),
}
});
}
const requestLogin = () => {
return {
type: actionTypes.LOGIN_REQUEST
};
};
const loginSuccess = (user) => {
return {
type: actionTypes.LOGIN_SUCCESS,
user
};
};
const loginFail = () => {
return {
type: actionTypes.LOGIN_FAILURE
};
};
export const login = () => {
return (dispatch) => {
dispatch(requestLogin());
steemConnect.isAuthenticated((err, result) => {
if (result.isAuthenticated) {
dispatch(getFollowing({
follower: result.username,
}));
api.getAccounts([result.username], (err, users) => {
dispatch(loginSuccess(users[0]));
});
} else {
dispatch(loginFail());
}
});
};
};
| JavaScript | 0 | @@ -109,23 +109,21 @@
%0Aimport
-broadca
+reque
st from
@@ -128,25 +128,16 @@
m 's
-teem/lib/broadcas
+uperagen
t';%0A
@@ -254,16 +254,65 @@
onnect);
+%0APromise.promisifyAll(request.Request.prototype);
%0A%0Aexport
@@ -2068,38 +2068,27 @@
romise:
-steemConnect.sendAsync
+request.get
('https:
@@ -2113,34 +2113,40 @@
/api/customJson'
-,
+).query(
%7B%0A json:
@@ -2414,32 +2414,43 @@
%5D,%0A %7D)
+.endAsync()
,%0A %7D%0A %7D);%0A%7D%0A
|
a92e7f2c20320fedfc195d50246bda89feca87ff | Add better docstrings. | src/bide/impl/router.js | src/bide/impl/router.js | /**
* router
*
* @author Andrey Antukh <[email protected]>, 2016
* @license BSD License <https://opensource.org/licenses/BSD-2-Clause>
*/
goog.provide("bide.impl.router");
goog.require("bide.impl.path");
goog.scope(function() {
var _path = bide.impl.path;
/**
* Main router class.
*
* @constructor
* @struct
*/
function Router() {
this.items = [];
this.map = {};
}
/**
* Routing Item class
*
* @constructor
* @struct
*/
function Route() {
this.re = null;
this.name = null;
this.keys = null;
this.format = null;
}
/**
* Insert a new route entry to the router.
* If router is `null` a new router is created.
*
* @param {?Router} router
* @param {string} path
* @param {!Object} name
* @param {*} options
* @return {Router}
*/
function insert(router, path, name, options) {
var route = new Route();
route.keys = [];
route.re = _path.parse(path, route.keys, options);
route.format = _path.compile(path);
route.name = name;
if (!goog.isDefAndNotNull(router)) {
router = new Router();
}
router.items.push(route);
if (router.map[name.fqn] === undefined) {
router.map[name.fqn] = [route];
} else {
router.map[name.fqn].push(route);
}
return router;
}
/**
* Match a path in the router.
*
* @param {!Router} router
* @param {!string} path
* @return {Array<*>}
*/
function match(router, path) {
var items = router.items;
var result = null;
var item = null;
for (var i=0; i<items.length; i++) {
item = items[i];
result = item.re.exec(path);
if (!goog.isNull(result)) {
break;
}
}
if (goog.isNull(result)) {
return null;
}
var params = {};
for (var i=0; i<item.keys.length; i++) {
var key = item.keys[i];
var res = result[(i + 1)];
if (goog.isDefAndNotNull(res)) {
params[key.name] = res;
}
}
if (isEmpty(params)) {
params = null;
}
return [item.name, params];
}
/**
* Perform a resolve operation on router.
*
* @param {!Router} router
* @param {*} name
* @param {Object<string,*>} params
* @return {Array<?>}
*/
function resolve(router, name, params) {
var routes = router.map[name.fqn] || null;
if (!goog.isDefAndNotNull(routes)) {
return null;
}
// If params is empty just check all possible
// options and return the first one that matches
// in case contrary check only routes with params
// because route without params does not raise
// exceptions causing that they are always elected
// independently if params are passed or not.
if (isEmpty(params)) {
for (var i=0; i<routes.length; i++) {
try {
return routes[i].format(params);
} catch (e) {}
}
} else {
for (var i=0; i<routes.length; i++) {
if (routes[i].keys.length === 0) {
continue;
}
try {
return routes[i].format(params);
} catch (e) {}
}
}
return null;
}
function isRouter(v) {
return v instanceof Router;
}
function empty() {
return new Router();
}
function isEmpty(obj) {
for (var x in obj) { return false; }
return true;
}
var module = bide.impl.router;
module.insert = insert;
module.match = match;
module.resolve = resolve;
module.isRouter = isRouter;
module.empty = empty;
});
| JavaScript | 0.000002 | @@ -2253,17 +2253,16 @@
%7D%0A */%0A
-%0A
functi
@@ -3137,118 +3137,409 @@
%0A%0A
-function isRouter(v) %7B%0A return v instanceof Router;%0A %7D%0A%0A function empty() %7B%0A return new Router();%0A %7D%0A
+/**%0A * Check if provided value is an instance of Router%0A *%0A * @param %7B*%7D v%0A * @return %7Bboolean%7D%0A */%0A function isRouter(v) %7B%0A return v instanceof Router;%0A %7D%0A%0A /**%0A * Create an empty Router instance.%0A *%0A * @return %7BRouter%7D%0A */%0A function empty() %7B%0A return new Router();%0A %7D%0A%0A /**%0A * Check if provided obj is empty.%0A *%0A * @param %7BObject%7D obj%0A * @return %7Bboolean%7D%0A */
%0A f
|
aab40cfe89defaaed156a3f543d3317ce6ef7fae | Update ip_mask.js | ip/ip_mask.js | ip/ip_mask.js | /*
mask.js
*/
IP_R = 0 // red channel
IP_G = 1 // green channel
IP_B = 2 // blue channel
IP_A = 3 // alpha channel
var ip_reset_masks = function(dst){
dst.ip_roi = null;
dst.ip_channel_mask = null;
dst.ip_luminance_mask = null;
}
/* setter */
var ip_set_roi = function(dst, x,y,w,h){
dst.ip_roi = [x,y,x+w,y+h];
}
var ip_set_channel_mask = function(dst, ch, min,max){
if( dst.ip_channel_mask == null )
dst.ip_channel_mask = [];
dst.ip_channel_mask[ch] = [min, max];
}
var ip_set_luminance_mask = function(dst, ch, min,max){
dst.ip_luminance_mask = [min, max];
}
/* getter */
var ip_get_roi = function(dst){
if( dst.ip_roi == undefined )
return [0,0, dst.width,dst.height];
else
return dst.ip_roi;
}
var ip_get_channel_mask = function(dst, ch){
if( dst.ip_channel_mask == null )
return [0,255];
else if( dst.ip_channel_mask[ch] == null )
return [0,255];
else
return dst.ip_channel_mask[ch];
}
var ip_get_luminance_mask = function(dst){
if( dst.ip_luminance_mask == null )
return [0,1];
else
return dst.ip_luminance_mask;
}
| JavaScript | 0.000003 | @@ -620,32 +620,52 @@
function(dst)%7B%0A
+ console.log(dst);%0A
if( dst.ip_roi
|
db11ac745c6b22d8634f994d3493cf791d3f26fc | tidy up rollup config, use env preset | lib/octicons_react/rollup.config.js | lib/octicons_react/rollup.config.js | import babel from 'rollup-plugin-babel'
import commonjs from 'rollup-plugin-commonjs'
import {readFileSync} from 'fs'
import {name} from './package.json'
const formats = ['esm', 'umd'] // 'cjs' ?
const presets = [
['es2015', {modules: false}],
'stage-0',
'react'
]
export default {
input: 'src/index.js',
plugins: [
babel({babelrc: false, presets}),
commonjs()
],
output: formats.map(format => ({
file: `dist/index.${format}.js`,
format,
name: 'reocticons'
}))
}
| JavaScript | 0 | @@ -82,76 +82,8 @@
njs'
-%0Aimport %7BreadFileSync%7D from 'fs'%0Aimport %7Bname%7D from './package.json'
%0A%0Aco
@@ -150,13 +150,10 @@
%5B'e
-s2015
+nv
', %7B
|
c5f22d17844666dd20ca02be96cc4943a587d5eb | make sure we visit decl inits | lib/passes/desugar-destructuring.js | lib/passes/desugar-destructuring.js | /* -*- Mode: js2; tab-width: 4; indent-tabs-mode: nil; -*-
* vim: set ts=4 sw=4 et tw=99 ft=js:
*/
import { startGenerator } from '../echo-util';
import { TransformPass } from '../node-visitor';
import * as b, { Identifier, ArrayPattern, ObjectPattern } from '../ast-builder';
import { reportError, reportWarning } from '../errors';
let gen = startGenerator();
let fresh = () => b.identifier(`%destruct_tmp${gen()}`);
// given an assignment { pattern } = id
//
function createObjectPatternBindings (id, pattern, decls) {
for (let prop of pattern.properties) {
let memberexp = b.memberExpression(id, prop.key);
decls.push(b.variableDeclarator(prop.key, memberexp));
if (prop.value.type === Identifier) {
// this happens with things like: function foo ({w:i}) { }
if (prop.value.name !== prop.key.name)
throw new Error("not sure how to handle this case..");
}
else if (prop.value.type === ObjectPattern) {
createObjectPatternBindings(memberexp, prop.value, decls);
}
else if (prop.value.type === ArrayPattern) {
createArrayPatternBindings(memberexp, prop.value, decls);
}
else {
throw new Error(`createObjectPatternBindings: prop.value.type = ${prop.value.type}`);
}
}
}
function createArrayPatternBindings (id, pattern, decls) {
let el_num = 0;
for (let el of pattern.elements) {
let memberexp = b.memberExpression(id, b.literal(el_num), true);
if (el.type === Identifier) {
decls.push(b.variableDeclarator(el, memberexp));
}
else if (el.type === ObjectPattern) {
let p_id = fresh();
decls.push(b.variableDeclarator(p_id, memberexp));
createObjectPatternBindings(p_id, el, decls);
}
else if (el.type === ArrayPattern) {
let p_id = fresh();
decls.push(b.variableDeclarator(p_id, memberexp));
createArrayPatternBindings(p_id, el, decls);
}
el_num += 1;
}
}
export class DesugarDestructuring extends TransformPass {
visitFunction (n) {
// we visit the formal parameters directly, rewriting
// them as tmp arg names and adding 'let' decls for the
// pattern identifiers at the top of the function's
// body.
let new_params = [];
let new_decls = [];
for (let p of n.params) {
if (p.type === ObjectPattern) {
let p_id = fresh();
new_params.push(p_id);
let new_decl = b.letDeclaration();
createObjectPatternBindings(p_id, p, new_decl.declarations);
new_decls.push(new_decl);
}
else if (p.type === ArrayPattern) {
let p_id = fresh();
new_params.push(p_id);
let new_decl = b.letDeclaration();
createArrayPatternBindings(p_id, p, new_decl.declarations);
new_decls.push(new_decl);
}
else if (p.type === Identifier) {
// we just pass this along
new_params.push(p);
}
else {
throw new Error(`unhandled type of formal parameter in DesugarDestructuring ${p.type}`);
}
}
n.body.body = new_decls.concat(n.body.body);
n.params = new_params;
return super(n);
}
visitVariableDeclaration (n) {
let decls = [];
for (let decl of n.declarations) {
if (decl.id.type === ObjectPattern) {
let obj_tmp_id = fresh();
decls.push(b.variableDeclarator(obj_tmp_id, decl.init));
createObjectPatternBindings(obj_tmp_id, decl.id, decls);
}
else if (decl.id.type === ArrayPattern) {
// create a fresh tmp and declare it
let array_tmp_id = fresh();
decls.push(b.variableDeclarator(array_tmp_id, decl.init));
createArrayPatternBindings(array_tmp_id, decl.id, decls);
}
else if (decl.id.type === Identifier) {
decls.push(decl);
}
else {
reportError(Error, `unhandled type of variable declaration in DesugarDestructuring ${decl.id.type}`, this.filename, n.loc);
}
}
n.declarations = decls;
return n;
}
visitAssignmentExpression (n) {
if (n.left.type === ObjectPattern || n.left.type === ArrayPattern) {
throw new Error("EJS doesn't support destructuring assignments yet (issue #16)");
if (n.operator !== "=")
reportError(Error, "cannot use destructuring with assignment operators other than '='", this.filename, n.loc);
}
else
return super(n);
}
}
| JavaScript | 0 | @@ -2468,24 +2468,56 @@
n.params) %7B%0A
+ let ptype = p.type;%0A
@@ -2517,25 +2517,24 @@
if (p
-.
type === Obj
@@ -2820,33 +2820,32 @@
else if (p
-.
type === ArrayPa
@@ -3133,17 +3133,16 @@
se if (p
-.
type ===
@@ -3363,17 +3363,16 @@
ring $%7Bp
-.
type%7D%60);
@@ -3481,16 +3481,53 @@
params;%0A
+ n.body = this.visit(n.body);%0A
@@ -3529,32 +3529,25 @@
return
-super(n)
+n
;%0A %7D%0A%0A
@@ -3790,32 +3790,43 @@
tor(obj_tmp_id,
+this.visit(
decl.init));%0A
@@ -3812,32 +3812,33 @@
isit(decl.init))
+)
;%0A
@@ -4119,24 +4119,35 @@
ray_tmp_id,
+this.visit(
decl.init));
@@ -4145,16 +4145,17 @@
l.init))
+)
;%0A
@@ -4228,32 +4228,32 @@
;%0A %7D%0A
-
else
@@ -4280,32 +4280,82 @@
= Identifier) %7B%0A
+ decl.init = this.visit(decl.init)%0A
|
1e85c22b8c4755c1a049336f59327e95a4e953c2 | Set JSON and authentication on DO API calls | lib/pkgcloud/digitalocean/client.js | lib/pkgcloud/digitalocean/client.js | /*
* client.js: Base client from which all Joyent clients inherit from
*
* (C) 2012 Nodejitsu Inc.
*
*/
var utile = require('utile'),
fs = require('fs'),
auth = require('../common/auth'),
base = require('../core/base');
//
// ### constructor (options)
// #### @opts {Object} an object literal with options
// #### @clientKey {String} Client key
// #### @apiKey {String} API key
// #### @throws {TypeError} On bad input
//
var Client = exports.Client = function (opts) {
if (!opts || !opts.clientKey || !opts.apiKey) {
throw new TypeError('clientKey and apiKey are required');
}
base.Client.call(this, opts);
this.provider = 'digitalocean';
this.protocol = opts.protocol || 'https://';
};
utile.inherits(Client, base.Client);
Client.prototype.failCodes = {
400: 'Bad Request',
401: 'Unauthorized',
403: 'Forbidden',
404: 'Not Found',
405: 'Method Not Allowed',
406: 'Not Acceptable',
409: 'Conflict',
413: 'Request Entity Too Large',
415: 'Unsupported Media Type',
420: 'Slow Down',
449: 'Retry With',
500: 'Internal Error',
503: 'Service Unavailable'
};
Client.prototype.successCodes = {
200: 'OK',
201: 'Created',
202: 'Accepted',
203: 'Non-authoritative information',
204: 'No content'
};
| JavaScript | 0 | @@ -525,19 +525,18 @@
s.client
-Key
+Id
%7C%7C !opt
@@ -681,16 +681,16 @@
ocean';%0A
-
this.p
@@ -727,16 +727,366 @@
tps://';
+%0A%0A if (!this.before) %7B%0A this.before = %5B%5D;%0A %7D%0A%0A this.before.push(function setJSON(req) %7B%0A req.json = true;%0A if (typeof req.body !== 'undefined') %7B%0A req.json = req.body;%0A delete req.body;%0A %7D%0A %7D);%0A%0A this.before.push(function setAuth(req) %7B%0A req.qs = %7B%0A client_id: opts.clientId,%0A api_key: opts.apiKey%0A %7D;%0A %7D);
%0A%7D;%0A%0Auti
|
5e666102b00520107e0daa5fedb7b6118a482b3d | fix #344 | controllers/kiln-toolbar.js | controllers/kiln-toolbar.js | var EditorToolbar,
dom = require('../services/dom'),
edit = require('../services/edit'),
events = require('../services/events'),
focus = require('../decorators/focus'),
pane = require('../services/pane'),
state = require('../services/page-state'),
progress = require('../services/progress');
/**
* Create a new page with the same layout as the current page.
* currently, this just clones the `new` page
* (cloning special "new" instances of the page-specific components)
* e.g. /components/article/instances/new
* @returns {Promise}
*/
function createPage() {
// todo: allow users to choose their layout / components
return edit.createPage().then(function (url) {
location.href = url;
});
}
/**
* @class EditorToolbar
* @param {Element} el
* @property {Element} el
*/
EditorToolbar = function (el) {
this.statusEl = dom.find(el, '.kiln-status');
this.progressEl = dom.find(el, '.kiln-progress');
this.el = el;
events.add(el, {
'.user-icon click': 'onUserClick',
'.new click': 'onNewClick',
'.history click': 'onHistoryClick',
'.publish click': 'onPublishClick'
}, this);
// stop users from leaving the page if they have an unsaved form open!
window.addEventListener('beforeunload', function (e) {
if (focus.hasCurrentFocus()) {
e.returnValue = 'Are you sure you want to leave this page? Your data may not be saved.';
}
});
return state.get().then(function (res) {
if (res.scheduled) {
state.openDynamicSchedule(res.scheduledAt, res.publishedUrl);
} else if (res.published) {
progress.open('publish', `Page is currently live: <a href="${res.publishedUrl}" target="_blank">View Page</a>`);
}
});
};
/**
* @lends EditorToolbar#
*/
EditorToolbar.prototype = {
onUserClick: function (e) {
// nothing yet
e.preventDefault();
e.stopPropagation();
},
onNewClick: function () {
if (focus.hasCurrentFocus()) {
if(window.confirm('Are you sure you want to create a new page? Your data on this page may not be saved.')) { // eslint-disable-line
return createPage();
} // else don't leave
} else {
return createPage();
}
},
onHistoryClick: function openHistoryPane() {
// open the history pane if it's not already open (close other panes first)
},
// open the publish pane if it's not already open (close other panes first)
onPublishClick: function () {
return focus.unfocus()
.then(pane.openPublish)
.catch(function () {
progress.done('error');
progress.open('error', `Data could not be saved. Please review your open form.`, true);
});
}
};
module.exports = EditorToolbar;
| JavaScript | 0 | @@ -1403,16 +1403,396 @@
%0A %7D);%0A%0A
+ // close ANY open forms if user hits ESC%0A document.addEventListener('keydown', function (e) %7B%0A if (e.keyCode === 27) %7B%0A focus.unfocus();%0A // note: this will work even if there isn't a current form open%0A // fun fact: it'll unselect components as well, in case the user has a form closed%0A // but a component selected, and they don't want that%0A %7D%0A %7D);%0A%0A
return
|
1a2e4ff52e93a163f56efccfc9e1f830b89a557e | update password error messages | src/javascript/_common/check_password.js | src/javascript/_common/check_password.js | const Mellt = require('./lib/Mellt/Mellt');
const localize = require('./localize').localize;
const checkPassword = (password_selector) => {
const el_password = document.querySelector(password_selector);
if (!el_password) {
return;
}
const div = el_password.parentNode.querySelector('.days_to_crack') || document.createElement('div');
const daysToCrack = Mellt.checkPassword(el_password.value.trim());
if (daysToCrack < 0) {
div.textContent = localize('The password you entered is one of the world\'s most commonly used passwords. You should not be using this password.');
} else {
let years;
if (daysToCrack > 365) {
years = Math.round(daysToCrack / 365 * 10) / 10;
if (years > 1000000) {
years = `${Math.round(years / 1000000 * 10) / 10} ${localize('million')}`;
} else if (years > 1000) {
years = `${Math.round(years / 1000)} ${localize('thousand')}`;
}
}
div.textContent = localize(
'Hint: it would take approximately [_1][_2] to crack this password.', [
(daysToCrack === 1000000000 ? '>' : ''),
years ? `${years} ${localize('years')}` : `${daysToCrack} ${localize('days')}`,
]);
}
div.className = `days_to_crack fill-bg-color hint ${daysToCrack < 30 ? 'red' : 'green'}`;
el_password.parentNode.appendChild(div);
};
const removeCheck = (password_selector) => {
const el_message = document.querySelector(password_selector).parentNode.querySelector('.days_to_crack');
if (el_message) {
el_message.remove();
}
};
module.exports = {
removeCheck,
checkPassword,
};
| JavaScript | 0.000001 | @@ -495,11 +495,12 @@
ze('
-The
+Your
pas
@@ -509,20 +509,8 @@
ord
-you entered
is o
@@ -523,17 +523,8 @@
the
-world%5C's
most
@@ -551,38 +551,48 @@
ords
-. You should not be using this
+ on the internet. Please choose a unique
pas
@@ -1100,12 +1100,12 @@
ack
-this
+your
pas
|
a87b117df30a3c7b11d5762cde81bb27b074f6f5 | Change left modal button class to button-link | src/js/components/modals/ActionsModal.js | src/js/components/modals/ActionsModal.js | import { Confirm, Dropdown } from "reactjs-components";
import mixin from "reactjs-mixin";
import React from "react";
import { StoreMixin } from "mesosphere-shared-reactjs";
import ModalHeading from "./ModalHeading";
import StringUtil from "../../utils/StringUtil";
import Util from "../../utils/Util";
const METHODS_TO_BIND = [
"handleButtonCancel",
"handleButtonConfirm",
"handleItemSelection",
"onActionError",
"onActionSuccess"
];
const DEFAULT_ID = "DEFAULT";
const ITEMS_DISPLAYED = 3;
class ActionsModal extends mixin(StoreMixin) {
constructor() {
super(...arguments);
this.state = {
pendingRequest: false,
requestErrors: [],
requestsRemaining: 0,
selectedItem: null,
validationError: null
};
METHODS_TO_BIND.forEach(method => {
this[method] = this[method].bind(this);
});
}
componentWillMount() {
this.setState({
requestsRemaining: this.props.selectedItems.length
});
}
componentWillUpdate(nextProps, nextState) {
const { requestsRemaining, requestErrors } = nextState;
if (requestsRemaining === 0 && !requestErrors.length) {
this.handleButtonCancel();
}
}
componentDidUpdate() {
const { requestsRemaining } = this.state;
if (requestsRemaining === 0) {
/* eslint-disable react/no-did-update-set-state */
this.setState({
pendingRequest: false,
requestsRemaining: this.props.selectedItems.length
});
/* eslint-enable react/no-did-update-set-state */
}
}
handleButtonCancel() {
this.setState({
pendingRequest: false,
requestErrors: [],
requestsRemaining: 0,
selectedItem: null,
validationError: null
});
this.props.onClose();
}
handleItemSelection(item) {
this.setState({
requestErrors: [],
selectedItem: item,
validationError: null
});
}
onActionError(error) {
this.state.requestErrors.push(error);
this.setState({
requestErrors: this.state.requestErrors,
requestsRemaining: this.state.requestsRemaining - 1
});
}
onActionSuccess() {
this.setState({
requestsRemaining: this.state.requestsRemaining - 1
});
}
getActionsModalContents() {
const { itemType } = this.props;
const { requestErrors, validationError } = this.state;
return (
<div className="text-align-center">
{this.getActionsModalContentsText()}
{this.getDropdown(itemType)}
{this.getErrorMessage(validationError)}
{this.getRequestErrorMessage(requestErrors)}
</div>
);
}
getActionsModalContentsText() {
const { actionText, itemID, selectedItems } = this.props;
let selectedItemsString = "";
if (selectedItems.length === 1) {
selectedItemsString = selectedItems[0][itemID];
} else {
// Truncate list of selected user/groups for ease of reading
const selectedItemsShown = selectedItems.slice(0, ITEMS_DISPLAYED + 1);
// Create a string concatenating n-1 items
const selectedItemsShownMinusOne = selectedItemsShown.slice(0, -1);
const itemIDs = selectedItemsShownMinusOne.map(function(item) {
return item[itemID];
});
itemIDs.forEach(function(_itemID) {
selectedItemsString += `${_itemID}, `;
});
// Handle grammar for nth element and concatenate to list
if (selectedItems.length <= ITEMS_DISPLAYED) {
// SelectedItems may be 0 length and Util.last will return null
if (selectedItems.length > 0) {
selectedItemsString += `and ${Util.last(selectedItems)[itemID]} `;
}
} else if (selectedItems.length === ITEMS_DISPLAYED + 1) {
selectedItemsString += "and 1 other ";
} else {
const overflow = selectedItems.length - ITEMS_DISPLAYED;
selectedItemsString += `and ${overflow} others `;
}
if (actionText.phraseFirst) {
selectedItemsString = selectedItemsString.slice(
0,
selectedItemsString.length - 1
);
}
}
if (actionText.phraseFirst) {
return (
<p>
{actionText.actionPhrase} <strong>{selectedItemsString}</strong>.
</p>
);
} else {
return (
<p>
<strong>{selectedItemsString}</strong> {actionText.actionPhrase}.
</p>
);
}
}
getDropdown(itemType) {
if (this.props.action === "delete") {
return null;
}
return (
<Dropdown
buttonClassName="button dropdown-toggle"
dropdownMenuClassName="dropdown-menu"
dropdownMenuListClassName="dropdown-menu-list"
dropdownMenuListItemClassName="clickable"
initialID={DEFAULT_ID}
items={this.getDropdownItems(itemType)}
onItemSelection={this.handleItemSelection}
scrollContainer=".gm-scroll-view"
scrollContainerParentSelector=".gm-prevented"
transition={true}
transitionName="dropdown-menu"
wrapperClassName="dropdown text-align-left"
/>
);
}
getErrorMessage(error) {
if (error != null) {
return <p className="text-error-state">{error}</p>;
}
}
getRequestErrorMessage(errors) {
if (errors.length > 0) {
const errorMap = errors.reduce(function(memo, error) {
if (memo[error] == null) {
memo[error] = 0;
}
memo[error]++;
return memo;
}, {});
// Compose error messages
const errorMessages = Object.keys(errorMap).map(function(error, index) {
const repeatTimes = errorMap[error];
if (repeatTimes === 1) {
return <p className="text-error-state" key={index}>{error}</p>;
} else {
return (
<p className="text-error-state" key={index}>
<span className="badge badge-danger badge-rounded">
{`${repeatTimes}x`}
</span>
{` ${error}`}
</p>
);
}
});
// Only show 5 first errors
return (
<div className="pod pod-short flush-left flush-right">
{errorMessages.slice(0, 5)}
</div>
);
}
}
render() {
const action = this.props.action;
const props = this.props;
if (action === null) {
return null;
}
const heading = (
<ModalHeading>
{this.props.actionText.title}
</ModalHeading>
);
return (
<Confirm
disabled={this.state.pendingRequest}
header={heading}
open={!!action}
onClose={this.handleButtonCancel}
leftButtonCallback={this.handleButtonCancel}
rightButtonCallback={this.handleButtonConfirm}
rightButtonText={StringUtil.capitalize(action)}
showHeader={true}
useGemini={false}
{...props}
>
{this.getActionsModalContents()}
</Confirm>
);
}
}
ActionsModal.propTypes = {
action: React.PropTypes.string.isRequired,
actionText: React.PropTypes.object.isRequired,
itemID: React.PropTypes.string.isRequired,
itemType: React.PropTypes.string.isRequired,
onClose: React.PropTypes.func.isRequired,
selectedItems: React.PropTypes.array.isRequired
};
module.exports = ActionsModal;
| JavaScript | 0.000082 | @@ -6634,32 +6634,81 @@
leButtonCancel%7D%0A
+ leftButtonClassName=%22button button-link%22%0A
rightBut
|
4a774ca29a33429c981039c17d71aac030d6046d | fix zipcode bug | src/js/facility-locator/actions/index.js | src/js/facility-locator/actions/index.js | import { api } from '../config';
import { find, compact } from 'lodash';
import { mapboxClient } from '../components/MapboxClient';
export const FETCH_VA_FACILITIES = 'FETCH_VA_FACILITIES';
export const FETCH_VA_FACILITY = 'FETCH_VA_FACILITY';
export const LOCATION_UPDATED = 'LOCATION_UPDATED';
export const SEARCH_FAILED = 'SEARCH_FAILED';
export const SEARCH_QUERY_UPDATED = 'SEARCH_QUERY_UPDATED';
export const SEARCH_STARTED = 'SEARCH_STARTED';
export const SEARCH_SUCCEEDED = 'SEARCH_SUCCEEDED';
export function updateSearchQuery(query) {
return {
type: SEARCH_QUERY_UPDATED,
payload: {
...query,
}
};
}
export function updateLocation(propertyPath, value) {
return {
type: LOCATION_UPDATED,
propertyPath,
value
};
}
export function fetchVAFacility(id, facility = null) {
if (facility) {
return {
type: FETCH_VA_FACILITY,
payload: facility,
};
}
const url = `${api.url}/${id}`;
return dispatch => {
dispatch({
type: SEARCH_STARTED,
payload: {
active: true,
},
});
return fetch(url, api.settings)
.then(res => res.json())
.then(
data => dispatch({ type: FETCH_VA_FACILITY, payload: data.data }),
err => dispatch({ type: SEARCH_FAILED, err })
);
};
}
export function searchWithBounds(bounds, facilityType, serviceType, page = 1) {
const params = compact([
...bounds.map(c => `bbox[]=${c}`),
facilityType ? `type=${facilityType}` : null,
serviceType ? `services[]=${serviceType}` : null,
`page=${page}`
]).join('&');
const url = `${api.url}?${params}`;
return dispatch => {
dispatch({
type: SEARCH_STARTED,
payload: {
page,
active: true,
},
});
return fetch(url, api.settings)
.then(res => res.json())
.then(
data => {
dispatch({ type: FETCH_VA_FACILITIES, payload: data });
},
err => dispatch({ type: SEARCH_FAILED, err })
);
};
}
export function searchWithAddress(query) {
return dispatch => {
dispatch({
type: SEARCH_STARTED,
payload: {
active: true,
},
});
mapboxClient.geocodeForward(query.searchString, {
country: 'us,vi,pr,ph,gu,as,mp',
}, (err, res) => {
const coordinates = res.features[0].center;
const zipCode = (find(res.features[0].context, (v) => {
return v.id.includes('postcode');
}) || {}).text || res.features[0].place_name;
if (!err) {
const dispatchObj = {
type: SEARCH_QUERY_UPDATED,
payload: {
...query,
context: zipCode,
position: {
latitude: coordinates[1],
longitude: coordinates[0],
},
bounds: res.features[0].bbox || [
coordinates[0] - 0.5,
coordinates[1] - 0.5,
coordinates[0] + 0.5,
coordinates[1] + 0.5,
],
zoomLevel: res.features[0].id.split('.')[0] === 'region' ? 7 : 11,
}
};
dispatch(dispatchObj);
dispatch({
type: SEARCH_SUCCEEDED,
});
} else {
dispatch({
type: SEARCH_FAILED,
err,
});
}
});
};
}
| JavaScript | 0.000001 | @@ -2521,22 +2521,16 @@
-const
dispatch
Obj
@@ -2529,14 +2529,9 @@
atch
-Obj =
+(
%7B%0A
@@ -3059,103 +3059,8 @@
%7D%0A
- %7D;%0A dispatch(dispatchObj);%0A dispatch(%7B%0A type: SEARCH_SUCCEEDED,%0A
|
1a3743dcedd838031da0ecedfdf0b67305f41d94 | update animation | js/animate.js | js/animate.js | $("#toogle-ani").css("visibility", "visible");
//start animation
var doAnimate;
$("input[value=doAnimate]").click(function( event ) {
if(doAnimate){
doAnimate = false;
}else{
doAnimate = true;
map.addLayer(Date_WMS1);
$('#image1').prop('checked', true);
}
cnt=2;
maxCnt=5;
//animation (yes a bit of a hack)
(function next() {
if (!doAnimate) return;
setTimeout(function() {
if(cnt===1){
map.removeLayer(Date_WMS2);
$('#image2').prop('checked', false);
map.removeLayer(Date_WMS3);
$('#image3').prop('checked', false);
map.removeLayer(Date_WMS4);
$('#image4').prop('checked', false);
map.removeLayer(Date_WMS5);
$('#image5').prop('checked', false);
map.addLayer(Date_WMS1);
$('#image1').prop('checked', true);
}
if(cnt===2){
map.removeLayer(Date_WMS1);
$('#image1').prop('checked', false);
map.removeLayer(Date_WMS3);
$('#image3').prop('checked', false);
map.removeLayer(Date_WMS4);
$('#image4').prop('checked', false);
map.removeLayer(Date_WMS5);
$('#image5').prop('checked', false);
map.addLayer(Date_WMS2);
$('#image2').prop('checked', true);
}
if(cnt===3){
map.removeLayer(Date_WMS1)
$('#image1').prop('checked', false);
map.removeLayer(Date_WMS2)
$('#image2').prop('checked', false);
map.removeLayer(Date_WMS4)
$('#image4').prop('checked', false);
map.removeLayer(Date_WMS5)
$('#image5').prop('checked', false);
map.addLayer(Date_WMS3)
$('#image3').prop('checked', true);
}
if(cnt===4){
map.removeLayer(Date_WMS1)
$('#image1').prop('checked', false);
map.removeLayer(Date_WMS2)
$('#image2').prop('checked', false);
map.removeLayer(Date_WMS3)
$('#image3').prop('checked', false);
map.removeLayer(Date_WMS5)
$('#image5').prop('checked', false);
map.addLayer(Date_WMS4)
$('#image4').prop('checked', true);
}
if(cnt===5){
map.removeLayer(Date_WMS1)
$('#image1').prop('checked', false);
map.removeLayer(Date_WMS2)
$('#image2').prop('checked', false);
map.removeLayer(Date_WMS3)
$('#image3').prop('checked', false);
map.removeLayer(Date_WMS4)
$('#image4').prop('checked', false);
map.addLayer(Date_WMS5)
$('#image5').prop('checked', true);
}
cnt++;
if(cnt===maxCnt){cnt=1}
next();
}, 5000);
})();
});
| JavaScript | 0.000001 | @@ -279,17 +279,17 @@
%0A%0A cnt=
-2
+1
;%0A maxC
@@ -2954,16 +2954,18 @@
==maxCnt
++1
)%7Bcnt=1%7D
@@ -2992,17 +2992,17 @@
%7D,
-5
+4
000);%0A
@@ -3010,9 +3010,8 @@
)();%0A%7D);
-%0A
|
092931766b842f4be71c27ab467f3549e1acf901 | Add UMD dist file building | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var jshint = require('gulp-jshint');
var stylish = require('jshint-stylish');
var mocha = require('gulp-mocha');
gulp.task('lint', function() {
gulp.src(['src/**/*.js', 'test/**/*.js'])
.pipe(jshint({
esnext: true
}))
.pipe(jshint.reporter(stylish))
.pipe(jshint.reporter('fail'));
});
gulp.task('test', function() {
require('6to5/register');
gulp.src(['test/**/*Test.js'])
.pipe(mocha({
reporter: 'spec'
}));
});
gulp.task('default', ['lint', 'test']); | JavaScript | 0 | @@ -133,16 +133,154 @@
mocha');
+%0Avar sixToFive = require('gulp-6to5');%0Avar uglify = require('gulp-uglify');%0Avar rename = require('gulp-rename');%0Avar del = require('del');
%0A%0Agulp.t
@@ -652,32 +652,532 @@
%7D));%0A%7D);%0A%0A
+gulp.task('clean', function() %7B%0A del('dist');%0A%7D);%0A%0Agulp.task('dist', %5B'lint', 'test', 'clean'%5D, function() %7B%0A gulp.src(%5B'src/chusha.js'%5D)%0A .pipe(sixToFive(%7B%0A // Note: I'm not sure what the difference between umd and umdStrict is.%0A // I like being stricter so I'll go with umdStrict for now.%0A modules: 'umd'%0A %7D))%0A .pipe(gulp.dest('dist'))%0A .pipe(uglify())%0A .pipe(rename('chusha.min.js'))%0A .pipe(gulp.dest('dist'));%0A%7D);%0A%0A
gulp.task('defau
@@ -1196,11 +1196,19 @@
, 'test'
+, 'dist'
%5D);
|
3f2702ed8a8114c6346b0f3af206d7f4e8fa6c25 | Add sanitize strategy for translations | js/app/app.js | js/app/app.js | /**
* Nextcloud - passman
*
* @copyright Copyright (c) 2016, Sander Brand ([email protected])
* @copyright Copyright (c) 2016, Marcos Zuriaga Miguel ([email protected])
* @license GNU AGPL version 3 or any later version
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
(function () {
'use strict';
/**
* @ngdoc overview
* @name passmanApp
* @description
* # passmanApp
*
* Main module of the application.
*/
angular
.module('passmanApp', [
'ngAnimate',
'ngCookies',
'ngResource',
'ngRoute',
'ngSanitize',
'ngTouch',
'templates-main',
'LocalStorageModule',
'offClick',
'ngPasswordMeter',
'ngclipboard',
'xeditable',
'ngTagsInput',
'angularjs-datetime-picker',
'ui.sortable',
'pascalprecht.translate'
])
.config(function ($routeProvider) {
$routeProvider
.when('/', {
templateUrl: 'views/vaults.html',
controller: 'VaultCtrl'
})
.when('/vault/:vault_id', {
templateUrl: 'views/show_vault.html',
controller: 'CredentialCtrl'
})
.when('/vault/:vault_id/new', {
templateUrl: 'views/edit_credential.html',
controller: 'CredentialEditCtrl'
})
.when('/vault/:vault_id/edit/:credential_id', {
templateUrl: 'views/edit_credential.html',
controller: 'CredentialEditCtrl'
}).when('/vault/:vault_id/:credential_id/share', {
templateUrl: 'views/share_credential.html',
controller: 'ShareCtrl'
}).when('/vault/:vault_id/:credential_id/revisions', {
templateUrl: 'views/credential_revisions.html',
controller: 'RevisionCtrl'
})
.when('/vault/:vault_id/settings', {
templateUrl: 'views/settings.html',
controller: 'SettingsCtrl'
})
.otherwise({
redirectTo: '/'
});
}).config(['$httpProvider', function ($httpProvider) {
$httpProvider.defaults.headers.common.requesttoken = oc_requesttoken;
}]).config(function (localStorageServiceProvider) {
localStorageServiceProvider
.setNotify(true, true);
}).config(function ($translateProvider) {
$translateProvider.useUrlLoader(OC.generateUrl('/apps/passman/api/v2/language'));
$translateProvider.preferredLanguage('en');
});
/**
* jQuery for notification handling D:
**/
jQuery(document).ready(function () {
var findItemByID = function (id) {
var credentials, foundItem = false;
credentials = angular.element('#app-content-wrapper').scope().credentials;
angular.forEach(credentials, function (credential) {
if (credential.credential_id === id) {
foundItem = credential;
}
});
return foundItem;
};
jQuery(document).on('click', '.undoDelete', function () {
var credential = findItemByID($(this).attr('data-item-id'));
angular.element('#app-content-wrapper').scope().recoverCredential(credential);
//Outside anglular we need $apply
angular.element('#app-content-wrapper').scope().$apply();
});
jQuery(document).on('click', '.undoRestore', function () {
var credential = findItemByID($(this).attr('data-item-id'));
angular.element('#app-content-wrapper').scope().deleteCredential(credential);
//Outside anglular we need $apply
angular.element('#app-content-wrapper').scope().$apply();
});
});
}()); | JavaScript | 0.000001 | @@ -2654,16 +2654,75 @@
ider) %7B%0A
+%09%09$translateProvider.useSanitizeValueStrategy('sanitize');%0A
%09%09$trans
|
3c115d0aec69251b1006a078c65b955f6fcc2481 | Fix old tsc* task references | Gulpfile.js | Gulpfile.js | var gulp = require("gulp");
var typescript = require("gulp-typescript");
var mocha = require("gulp-mocha");
var cover = require("gulp-coverage");
var del = require("del");
gulp.task("clean", function(cb) {
del([
"bin/**/*"
], cb);
});
gulp.task("build-copy", function() {
return gulp.src([
"./*.json", "**/*.json",
"!node_modules/*.json", "!node_modules/**/*.json",
"./*.js", "**/*.js", "!bin/*.js", "!bin/**/*.js", "!Gulpfile.js",
"!node_modules/*.js", "!node_modules/**/*.js"])
.pipe(gulp.dest("./bin"));
});
gulp.task("build-src", function() {
return gulp.src(["./src/*.ts", "./src/**/*.ts"])
.pipe(typescript())
.js
.pipe(gulp.dest("./bin/src"));
});
gulp.task("build-test", function() {
return gulp.src(["./test/*.ts", "./test/**/*.ts"])
.pipe(typescript())
.js
.pipe(gulp.dest("./bin/test"));
});
gulp.task("build", ["build-copy", "build-src", "build-test"]);
gulp.task("test", ["build"], function() {
return gulp.src("./bin/test/*.js", { read: false })
//.pipe(cover.instrument({
// pattern: ['bin/src/*.js', 'bin/src/**/*.js'],
// debugDirectory: 'debug'
//}))
.pipe(mocha({ reporter: "spec"}));
/*.pipe(cover.gather())
.pipe(cover.format())
.pipe(gulp.dest("./cover"));*/
});
gulp.task("watch-src", ["tsc-src"], function() {
return gulp.watch(["src/*", "src/**/*"], ["tsc-src"]);
});
gulp.task("watch-test", ["tsc-test"], function() {
return gulp.watch(["test/*", "test/**/*"], ["tsc-test"]);
});
gulp.task("watch", ["watch-src", "watch-test"]);
gulp.task("default", ["test"]);
| JavaScript | 0.000015 | @@ -1396,27 +1396,29 @@
tch-src%22, %5B%22
-tsc
+build
-src%22%5D, func
@@ -1473,19 +1473,21 @@
/*%22%5D, %5B%22
-tsc
+build
-src%22%5D);
@@ -1514,27 +1514,29 @@
ch-test%22, %5B%22
-tsc
+build
-test%22%5D, fun
@@ -1598,11 +1598,13 @@
, %5B%22
-tsc
+build
-tes
|
5ef845d9ebb922de01a00db062f4deac9d855b29 | store path for projects | tasks/takana.js | tasks/takana.js | /*
* grunt-takana
* https://github.com/mechio/grunt-takana
*
* Copyright (c) 2013 nc
* Licensed under the MIT license.
*/
'use strict';
var sqlite3 = require('sqlite3').verbose();
var path = require('path');
var fs = require('fs');
var underscore = require('underscore');
var DEBUG = false;
module.exports = function(grunt) {
function resolvePath (string) {
if (string.substr(0,1) === '~') {
string = process.env.HOME + string.substr(1);
return path.resolve(string);
};
};
grunt.registerTask('takana', 'register load paths', function() {
var done = this.async();
var options = this.options({
includePaths: [],
projectName: path.basename(process.cwd())
});
grunt.log.writeln(["Takana: integrating with project " + options.projectName]);
var dbFile = resolvePath("~/Library/Application Support/Edge/takana.db");
var exists = fs.existsSync(dbFile);
if (exists) {
var db = new sqlite3.Database(dbFile);
var Project = function(name) {
this.name = name;
var _this = this;
this.find = function(callback) {
var findSQL = "SELECT id, name FROM projects WHERE name IS '" + _this.name + "'";
if (DEBUG) {
console.log("running %j", findSQL)
}
db.get(findSQL, function(error, row) {
if (error || !row) {
callback(error, null);
} else {
_this.id = row.id;
callback(null, _this);
};
});
};
this.create = function(callback) {
var createSQL = "INSERT INTO projects ( name ) VALUES (?)";
if (DEBUG) {
console.log("running %j", createSQL);
}
grunt.log.write("Takana: creating project...");
db.run(createSQL, _this.name, function(error, lastId, changes) {
if (error) {
grunt.log.writeln("failed");
grunt.log.error("Please contact support <[email protected]>");
callback(error, null);
} else {
_this.find(function(error, project) {
if (error) {
grunt.log.write("failed");
grunt.log.error("Please contact support <[email protected]>");
callback(error, null);
} else {
grunt.log.writeln("created")
grunt.log.subhead("Add this script tag just before </body> on every page you want to run Takana on")
grunt.log.writeln("\t<script data-project=\"" + project.name + "\" src=\"http://localhost:48626/edge.js\"></script>");
grunt.log.subhead("\t... or get the Chrome extension")
grunt.log.writeln("\thttps://chrome.google.com/webstore/detail/takana/bldhkhmklhojenikmgdcpdbjfffoeidb?hl=en\n")
callback(null, project);
}
});
};
});
}
this.findOrCreate = function(callback) {
this.find(function(error, project) {
if (error || !project) {
grunt.log.error("could not find existing project...creating one instead");
_this.create(callback);
} else {
callback(null, project);
}
});
};
this.updateLoadPaths = function(loadPaths, callback) {
var findSQL = "SELECT id, path FROM load_paths WHERE project_id IS '" + _this.id + "'";
var updateSQL = "INSERT INTO load_paths ( project_id, path ) VALUES ";
if (DEBUG) {
console.log("running %j", findSQL);
}
db.all(findSQL, function(error, rows) {
if (error) {
callback(error, null);
} else {
var paths = underscore.pluck(rows, 'path');
var pathsToAdd = underscore.difference(loadPaths, paths);
if (DEBUG) {
console.log("paths to add are %j", pathsToAdd);
}
if (pathsToAdd.length > 0) {
var values = underscore.map(pathsToAdd, function(path) {
return "( " + _this.id + ", '" + path + "' )";
});
values = values.join(',');
var sql = updateSQL + values;
if (DEBUG) {
console.log("running %j", sql);
}
db.exec(sql, callback);
} else {
callback(null, false);
};
};
});
};
return this;
};
var project = new Project(options.projectName);
project.findOrCreate(function(error, project) {
if (error || !project) {
grunt.log.error(["Takana: could not find or create project " + options.projectName]);
db.close();
} else {
project.updateLoadPaths(options.includePaths, function(error, added) {
if (error) {
grunt.log.error(["Takana: could not add load paths", error]);
} else {
if (!added) {
grunt.log.writeln(["Takana: includePaths are up to date"]);
} else {
grunt.log.writeln(["Takana: added includePaths"]);
};
};
db.close();
});
};
});
} else {
grunt.log.writeln("Takana: could not find Takana on this machine. Be a 10x developer by using Takana today - visit http://usetakana.com for more information");
};
});
};
| JavaScript | 0 | @@ -703,16 +703,50 @@
s.cwd())
+,%0A projectPath: process.cwd()
%0A %7D);
@@ -1696,16 +1696,22 @@
s ( name
+, path
) VALUE
@@ -1713,16 +1713,19 @@
VALUES (
+?,
?)%22;%0A
@@ -1905,16 +1905,37 @@
is.name,
+ options.projectPath,
functio
|
73c4160d21e7a8463c69f980f485d790d286713d | Remove validations statement for input password | packages/strapi-plugin-content-manager/admin/src/components/Inputs/index.js | packages/strapi-plugin-content-manager/admin/src/components/Inputs/index.js | import React, { memo, useMemo } from 'react';
import PropTypes from 'prop-types';
import { get, isEmpty, omit, toLower } from 'lodash';
import { FormattedMessage } from 'react-intl';
import { Inputs as InputsIndex } from '@buffetjs/custom';
import { useStrapi } from 'strapi-helper-plugin';
import useDataManager from '../../hooks/useDataManager';
import InputJSONWithErrors from '../InputJSONWithErrors';
import SelectWrapper from '../SelectWrapper';
import WysiwygWithErrors from '../WysiwygWithErrors';
import InputUID from '../InputUID';
const getInputType = (type = '') => {
switch (toLower(type)) {
case 'boolean':
return 'bool';
case 'decimal':
case 'float':
case 'integer':
return 'number';
case 'date':
case 'datetime':
case 'time':
return type;
case 'email':
return 'email';
case 'enumeration':
return 'select';
case 'password':
return 'password';
case 'string':
return 'text';
case 'text':
return 'textarea';
case 'media':
case 'file':
case 'files':
return 'media';
case 'json':
return 'json';
case 'wysiwyg':
case 'WYSIWYG':
case 'richtext':
return 'wysiwyg';
case 'uid':
return 'uid';
default:
return 'text';
}
};
function Inputs({ autoFocus, keys, layout, name, onBlur }) {
const {
strapi: { fieldApi },
} = useStrapi();
const { didCheckErrors, formErrors, modifiedData, onChange } = useDataManager();
const attribute = useMemo(() => get(layout, ['schema', 'attributes', name], {}), [layout, name]);
const metadatas = useMemo(() => get(layout, ['metadatas', name, 'edit'], {}), [layout, name]);
const disabled = useMemo(() => !get(metadatas, 'editable', true), [metadatas]);
const type = useMemo(() => get(attribute, 'type', null), [attribute]);
const regexpString = useMemo(() => get(attribute, 'regex', null), [attribute]);
const value = get(modifiedData, keys, null);
const temporaryErrorIdUntilBuffetjsSupportsFormattedMessage = 'app.utils.defaultMessage';
const errorId = get(
formErrors,
[keys, 'id'],
temporaryErrorIdUntilBuffetjsSupportsFormattedMessage
);
let validationsToOmit = [
'type',
'model',
'via',
'collection',
'default',
'plugin',
'enum',
'regex',
];
// Remove the required validation for the password type unless the form is already submitted
// So the error is properly displayed in the password input
if (type === 'password' && errorId !== 'components.Input.error.validation.required') {
validationsToOmit = [...validationsToOmit, 'required'];
}
// Remove the minLength validation when the user clears the input so it is not displayed
if (type === 'password' && !value) {
validationsToOmit = [...validationsToOmit, 'minLength'];
}
const validations = omit(attribute, validationsToOmit);
if (regexpString) {
const regexp = new RegExp(regexpString);
if (regexp) {
validations.regex = regexp;
}
}
const { description, visible } = metadatas;
if (visible === false) {
return null;
}
const isRequired = get(validations, ['required'], false);
if (type === 'relation') {
return (
<div key={keys}>
<SelectWrapper
{...metadatas}
name={keys}
plugin={attribute.plugin}
relationType={attribute.relationType}
targetModel={attribute.targetModel}
value={get(modifiedData, keys)}
/>
</div>
);
}
let inputValue = value;
// Fix for input file multipe
if (type === 'media' && !value) {
inputValue = [];
}
let step;
if (type === 'float' || type === 'decimal') {
step = 'any';
} else if (type === 'time' || type === 'datetime') {
step = 30;
} else {
step = '1';
}
const options = get(attribute, 'enum', []).map(v => {
return (
<option key={v} value={v}>
{v}
</option>
);
});
const enumOptions = [
<FormattedMessage id="components.InputSelect.option.placeholder" key="__enum_option_null">
{msg => (
<option disabled={isRequired} hidden={isRequired} value="">
{msg}
</option>
)}
</FormattedMessage>,
...options,
];
return (
<FormattedMessage id={errorId}>
{error => {
return (
<InputsIndex
{...metadatas}
autoComplete="new-password"
autoFocus={autoFocus}
didCheckErrors={didCheckErrors}
disabled={disabled}
error={
isEmpty(error) || errorId === temporaryErrorIdUntilBuffetjsSupportsFormattedMessage
? null
: error
}
inputDescription={description}
description={description}
contentTypeUID={layout.uid}
customInputs={{
json: InputJSONWithErrors,
wysiwyg: WysiwygWithErrors,
uid: InputUID,
...fieldApi.getFields(),
}}
multiple={get(attribute, 'multiple', false)}
attribute={attribute}
name={keys}
onBlur={onBlur}
onChange={onChange}
options={enumOptions}
step={step}
type={getInputType(type)}
validations={validations}
value={inputValue}
withDefaultValue={false}
/>
);
}}
</FormattedMessage>
);
}
Inputs.defaultProps = {
autoFocus: false,
onBlur: null,
};
Inputs.propTypes = {
autoFocus: PropTypes.bool,
keys: PropTypes.string.isRequired,
layout: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
onBlur: PropTypes.func,
onChange: PropTypes.func.isRequired,
};
export default memo(Inputs);
| JavaScript | 0.000002 | @@ -2329,515 +2329,8 @@
%5D;%0A%0A
- // Remove the required validation for the password type unless the form is already submitted%0A // So the error is properly displayed in the password input%0A if (type === 'password' && errorId !== 'components.Input.error.validation.required') %7B%0A validationsToOmit = %5B...validationsToOmit, 'required'%5D;%0A %7D%0A%0A // Remove the minLength validation when the user clears the input so it is not displayed%0A if (type === 'password' && !value) %7B%0A validationsToOmit = %5B...validationsToOmit, 'minLength'%5D;%0A %7D%0A%0A
co
|
ded724afc4bcf5878ce12e733a4d95d56f4bc4d2 | remove log | Gulpfile.js | Gulpfile.js | 'use strict';
//////////////////////////////////////////////////////////////////////////////
// REQUIRED
//////////////////////////////////////////////////////////////////////////////
var gulp = require('gulp');
var cm = require('./lib/common');
var publish = require('./lib/publish');
var build = require('./lib/build');
//////////////////////////////////////////////////////////////////////////////
// TASKS
//////////////////////////////////////////////////////////////////////////////
gulp.task('clean', function(done) {
var rimraf = require('gulp-rimraf');
var DIR = cm.component_publisher_dir;
gulp.src(DIR + '/**').pipe(rimraf())
.on('end', done);
});
gulp.task('build_gh-pages', build.ghpages);
gulp.task('build_bower', build.bower);
var allowPushOnRepo = (process.env.TRAVIS == 'true') && (process.env.TRAVIS_PULL_REQUEST == 'false') && (process.env.TRAVIS_BRANCH == 'develop') && true;
gulp.task('publish_gh-pages', function(cb){
if (process.env.TRAVIS){
publish.apply(this, [{
tag: false,
push: allowPushOnRepo,
message: 'Travis commit : build ' + process.env.TRAVIS_BUILD_NUMBER
}, cb]);
}else{
publish.apply(this, [cb]);
}
});
gulp.task('publish_bower', function(cb){
console.log(process.env.TRAVIS, process.env.TRAVIS_PULL_REQUEST, process.env.TRAVIS_BRANCH);
console.log('Can push', allowPushOnRepo);
if (process.env.TRAVIS){
publish.apply(this, [
{
push: allowPushOnRepo,
message: 'Travis commit : build ' + process.env.TRAVIS_BUILD_NUMBER
}, cb]);
}else{
publish.apply(this, [cb]);
}
});
function prefixedBranchedTasks(prefix){
gulp.task(prefix, function(cb){
if (!this.env.branch )
throw new Error('\nJust say want you want to ' + prefix + ' like\n' + prefix + ' --branch=bower');
// TODO test if exist ?
gulp.run(prefix + '_' + this.env.branch, cb);
});
}
prefixedBranchedTasks('build');
prefixedBranchedTasks('publish');
| JavaScript | 0.000003 | @@ -1237,147 +1237,8 @@
b)%7B%0A
- console.log(process.env.TRAVIS, process.env.TRAVIS_PULL_REQUEST, process.env.TRAVIS_BRANCH);%0A console.log('Can push', allowPushOnRepo);%0A
if
|
906db11fd186f42cae8e718eb891f081c203f2f3 | update gulp file for handling tests | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var karma = require('gulp-karma');
var wrap = require('gulp-wrap-umd');
var testFiles = [
'src/scripts/requireJs/helloModule.js',
'tests/requireJs/helloSpec.js'
];
gulp.task('test', function() {
// Be sure to return the stream
gulp.src(testFiles)
.pipe(karma({
configFile: 'karma.conf.js',
action: 'run'
}))
});
gulp.task('umd', function(){
gulp.src(['src/scripts/requireJs/helloModule.js'])
.pipe(wrap({
namespace: 'helloUmd'
}))
.pipe(gulp.dest('src/scripts/umd/'));
});
gulp.task('default', function() {
gulp.src(testFiles)
.pipe(karma({
configFile: 'karma.conf.js',
action: 'watch'
}));
});
| JavaScript | 0 | @@ -115,84 +115,29 @@
= %5B
-%0A 'src/scripts/requireJs/helloModule.js',%0A 'tests/requireJs/helloSpec.js'%0A
+'files in karma conf'
%5D;%0A%0A
|
efcad494bd93eee9c268bce973bb4c83eefbb2ca | fix minor bug regarding internals | src/class/dependency.js | src/class/dependency.js | /* global
global, document, demand, provide, queue, processor, settings, setTimeout, clearTimeout,
DEMAND_ID, MODULE_PREFIX_HANDLER, ERROR_LOAD, DEMAND_ID, PROVIDE_ID, PATH_ID, MOCK_PREFIX, NULL, TRUE, FALSE,
object,
regexMatchInternal, regexMatchParameter,
validatorIsPositive,
functionResolvePath, functionResolveId, functionResolveUrl, functionIterate, functionToArray,
ClassRegistry, ClassPledge, ClassFailure, ClassSemver,
singletonCache
*/
//=require constants.js
//=require shortcuts.js
//=require variables.js
//=require validator/isPositive.js
//=require function/resolvePath.js
//=require function/resolveId.js
//=require function/resolveUrl.js
//=require function/iterate.js
//=require function/toArray.js
//=require class/registry.js
//=require class/pledge.js
//=require class/failure.js
//=require class/semver.js
//=require singleton/cache.js
var ClassDependency = (function() {
var PREFIX_INTERNAL = 'internal:',
registry = new ClassRegistry(),
matchInternal = /^(?:mock|internal):/i,
placeholder = [];
function setProperty(property, value) {
this[property] = value;
}
function add(id) {
if(!matchInternal.test(id)) {
this.push(id);
}
}
function addPending(id, dependency) {
if(!matchInternal.test(id) && dependency.pledge.isPending()) {
this.push(id);
}
}
function addResolved(id, dependency) {
if(!matchInternal.test(id) && dependency.pledge.isResolved()) {
this.push(id);
}
}
function addRejected(id, dependency) {
if(!matchInternal.test(id) && dependency.pledge.isRejected()) {
this.push(id);
}
}
function list() {
return functionIterate(registry.get(), add, []);
}
list.prototype = {
pending: function() {
return functionIterate(registry.get(), addPending, []);
},
resolved: function() {
return functionIterate(registry.get(), addResolved, []);
},
rejected: function() {
return functionIterate(registry.get(), addRejected, []);
}
};
function ClassDependency(uri, context, register) {
var self = this,
parameter = uri.match(regexMatchParameter) || placeholder;
self.path = functionResolvePath(uri, context);
self.mock = parameter[1] ? TRUE : FALSE;
self.cache = parameter[2] ? parameter[1] === '+' : NULL;
self.type = parameter[3] || settings.handler;
self.version = new ClassSemver(parameter[4] || settings.version);
self.lifetime = (parameter[5] && parameter[5] * 1000) || settings.lifetime;
self.id = (self.mock ? MOCK_PREFIX : '' ) + self.type + '!' + self.path;
self.uri = (self.mock ? MOCK_PREFIX : '' ) + self.type + '@' + self.version + (validatorIsPositive(self.lifetime) && self.lifetime > 0 ? '#' + self.lifetime : '' ) + '!' + self.path;
self.dfd = ClassPledge.defer();
self.pledge = self.dfd.pledge;
self.invalid = false;
self.pledge.then(function() {
self.value = functionToArray(arguments);
});
(register !== FALSE) && registry.set(self.id, self);
return self;
}
ClassDependency.prototype = {
enqueue: true // handled by handler
/* only for reference
path: NULL,
mock: NULL,
cache: NULL,
type: NULL,
version: NULL,
lifetime: NULL,
id: NULL,
uri: NULL,
dfd: NULL,
pledge: NULL,
value: NULL,
handler: NULL, // set by Dependency.resolve
source: NULL, // set by Cache or Loader
url: NULL // optional, set by Loader
*/
};
ClassDependency.get = function(uri, context) {
return registry.get(functionResolveId(uri, context));
};
ClassDependency.resolve = function(uri, context) {
var isInternal = context && regexMatchInternal.test(uri),
dependency = isInternal ? this.get(PREFIX_INTERNAL + context + '/' + uri) : this.get(uri, context),
value;
if(!dependency) {
if(isInternal) {
dependency = new ClassDependency(PREFIX_INTERNAL + context + '/' + uri);
switch(uri) {
case DEMAND_ID:
value = (function() {
return functionIterate(demand, setProperty, demand.bind(context));
}());
break;
case PROVIDE_ID:
value = provide.bind(context);
break;
case PATH_ID:
value = context;
break;
}
dependency.dfd.resolve(value);
} else {
dependency = new ClassDependency(uri, context);
demand(MODULE_PREFIX_HANDLER + dependency.type)
.then(
function(handler) {
dependency.handler = handler;
if(dependency.mock) {
dependency.dfd.resolve(handler);
} else {
singletonCache.resolve(dependency);
}
},
function() {
dependency.dfd.reject(new ClassFailure(ERROR_LOAD + ' (handler)', self.id));
}
)
}
}
return dependency;
};
ClassDependency.remove = function(uri, context, cache) {
var id = functionResolveId(uri, context),
node = document.querySelector('[' + DEMAND_ID + '-id="' + id + '"]');
registry.remove(id);
registry.remove(MOCK_PREFIX + id);
node && node.parentNode.removeChild(node);
(cache !== FALSE) && singletonCache.clear(id);
};
ClassDependency.list = list;
return ClassDependency;
}());
| JavaScript | 0 | @@ -929,17 +929,17 @@
internal
-:
+!
',%0A%09%09reg
@@ -1003,16 +1003,17 @@
%5E(?:mock
+:
%7Cinterna
@@ -1017,10 +1017,10 @@
rnal
+!
)
-:
/i,%0A
|
7cd97f44b1c735bd4d19965d701f29a5c0c9f874 | support rediect to the needed page | cypress/support/commands.js | cypress/support/commands.js | // ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
// -- This is a login command --
Cypress.Commands.add("loginAdmin", (username, password, assertLoggedIn = true) => {
cy.login("admin", "changeme");
});
Cypress.Commands.add("loginStandard", (username, password, assertLoggedIn = true) => {
cy.login("[email protected]", "abc123");
});
Cypress.Commands.add("login", (username, password, assertLoggedIn = true) => {
cy.visit("/");
cy.wait(150);
cy.get("#UserBox").type(username);
cy.get("#PasswordBox").type(password);
cy.get("form").submit();
if (assertLoggedIn) {
cy.location('pathname').should('include', "/v2/dashboard");
}
});
Cypress.Commands.add("buildRandom", (prefixString) => {
let rand = Math.random().toString(36).substring(7);
return prefixString.concat(" - ", rand);
});
| JavaScript | 0 | @@ -409,49 +409,16 @@
%22, (
-username, password, assertLoggedIn = true
+location
) =%3E
@@ -452,16 +452,26 @@
hangeme%22
+, location
);%0A%7D);%0A%0A
@@ -513,49 +513,16 @@
%22, (
-username, password, assertLoggedIn = true
+location
) =%3E
@@ -570,16 +570,26 @@
%22abc123%22
+, location
);%0A%7D);%0A%0A
@@ -643,29 +643,16 @@
rd,
-assertLoggedIn = true
+location
) =%3E
@@ -669,17 +669,39 @@
visit(%22/
-%22
+?location=/%22 + location
);%0A c
@@ -836,21 +836,15 @@
if (
-assertLoggedI
+locatio
n) %7B
@@ -898,23 +898,16 @@
e',
-%22/v2/dashboard%22
+location
);%0A
|
f869095cfffa49329d5891d717debe1b3ded64cb | fix ungreening new moves issue | js/buttons.js | js/buttons.js | var _chess;
// Creates a clone of the Lichess board and adds it to the DOM.
// @todo? Don't add clone to DOM until we have finished calling updateBoard().
// Performing manipulations while our clone isn't yet in the DOM may be cheaper.
var createBoard = function() {
// Don't create another clone if one already exists.
if ($('.le-clone').length) {
return;
}
var liBoardClone = $('.lichess_board').clone();
liBoardClone.addClass('le-clone');
// Hide the original board and add the clone where it was.
$('.lichess_board:not(.le-clone)').hide();
$('.lichess_board_wrap').prepend(liBoardClone);
// Pieces sometimes flicker while you are viewing earlier moves and a new
// move is made in the game. This is a temporary fix.
$('.lichess_board:not(.le-clone) .piece').hide();
// Prevent the user from dragging around pieces in the clone.
$('.le-clone > div').removeClass('ui-draggable ui-droppable selected');
};
var getCurrentMoveNum = function() {
var currentMove = $('.moveOn').prop('id');
if (!currentMove) {
return 0;
}
return parseInt(currentMove.split('-')[2]);
};
// Store piece and colour names in these objects so that we can convert them
// to their full names by passing the first letter as the key.
var piece = {
p: 'pawn', b: 'bishop', n: 'knight', r: 'rook', q: 'queen', k: 'king'
};
var color = {w: 'white', b: 'black'};
var goToMove = function(move, scrollTo) {
move = parseInt(move);
if (move === (FENs.length - 1)) {
moveToEnd();
return;
}
createBoard();
_chess = new Chess(FENs[move]);
// Update the clone's pieces to the new state.
$('.le-clone > div').each(function() {
$(this).find('.piece').remove();
var id = _chess.get($(this).prop('id'));
if (id === null) {
// A piece doesn't exist in this square, so return non-false value
// to skip next iteration.
return true;
}
$(this).append($('<div>', {
class: 'piece ' + piece[id.type] + ' ' + color[id.color]
}));
});
// Update the green glowing indicators that show what the last move was.
$('.le-clone .moved').removeClass('moved');
// If the current clone-state has a check, remove the indicator.
$('.le-clone .check').removeClass('check');
// If in check, update the indicator.
if ($('#le-move-' + move).text().indexOf('+') > -1) {
var col = move % 2 === 0 ? 'white' : 'black';
$('.le-clone .piece.king.' + col).parent().addClass('check');
}
$('.moveOn').removeClass('moveOn');
$('#le-move-' + move).addClass('moveOn');
var moveNew = $('#le-move-' + move + '.moveNew');
moveNew.prevAll('span:first').removeClass('moveNew');
moveNew.removeClass('moveNew');
// Doesn't seem to work... so for now, we do it the dirty way.
// $('#le-GameText').scrollTop($('#le-move-' + (_history.length + 1)).position().top);
// 17 is the height of each row
if (scrollTo !== false) {
$('#le-GameText').scrollTop(Math.floor((getCurrentMoveNum() - 1) / 2) * 17);
}
if (move < 1) {
return;
}
var moved = chess.history({verbose: true})[move - 1];
$('#' + moved.from).addClass('moved');
$('#' + moved.to).addClass('moved');
};
// Moves the clone to the start of the game.
var moveToStart = function() {
stopAutoplay();
createBoard();
goToMove(0);
};
// Moves the clone back one move.
var moveBackward = function() {
stopAutoplay();
createBoard();
goToMove(getCurrentMoveNum() - 1);
};
// Move the clone forward one move.
// We separate this from moveForward() so we can call it from doAutoplay().
var doMoveForward = function() {
goToMove(getCurrentMoveNum() + 1);
};
var moveForward = function() {
if (!$('.le-clone').length) {
return;
}
stopAutoplay();
doMoveForward();
};
// Destroys the clone, returning to the latest move.
var moveToEnd = function() {
if (!$('.le-clone').length) {
return;
}
stopAutoplay();
$('.le-clone').remove();
// Temporary fix for piece-flicker problem--see createBoard() above.
$('.lichess_board:not(.le-clone)').show();
$('.lichess_board:not(.le-clone) .piece').show();
$('.moveNew').removeClass('moveNew');
$('.moveOn').removeClass('moveOn');
$('#le-GameText #le-move-' + (FENs.length - 1)).addClass('moveOn');
$('#le-GameText').scrollTop($('#le-GameText')[0].scrollHeight);
};
var autoplay;
var stopAutoplay = function() {
clearInterval(autoplay);
$('#autoplayButton').attr('data-hint', 'toggle autoplay (start)');
};
// Autoplays through the moves.
var doAutoplay = function() {
if (!$('.le-clone').length) {
return;
}
if ($(this).attr('data-hint') === 'toggle autoplay (start)') {
$(this).attr('data-hint', 'toggle autoplay (stop)');
} else {
stopAutoplay();
return;
}
// Eliminates the initial delay.
doMoveForward();
// @todo Make delay configurable through an options page.
var delay = 1000;
autoplay = setInterval(function() {
doMoveForward();
}, delay);
};
$(document).on('click', '#startButton', moveToStart);
$(document).on('click', '#backButton', moveBackward);
$(document).on('click', '#autoplayButton', doAutoplay);
$(document).on('click', '#forwardButton', moveForward);
$(document).on('click', '#endButton', moveToEnd);
// Add keyboard support.
$(document).keydown(function(event) {
// If user is typing something, return.
if ($('.lichess_say').is(':focus')) {
return;
}
switch (event.keyCode) {
// h or up-arrow
case 72:
case 38:
event.preventDefault();
moveToStart();
break;
// j or left-arrow
case 74:
case 37:
event.preventDefault();
moveBackward();
break;
// k or right-arrow
case 75:
case 39:
event.preventDefault();
moveForward();
break;
// l or down-arrow
case 76:
case 40:
event.preventDefault();
moveToEnd();
break;
}
}); | JavaScript | 0.000001 | @@ -2539,30 +2539,8 @@
New.
-prevAll('span:first').
remo
@@ -2560,32 +2560,52 @@
New');%0A%09moveNew.
+prevAll('.le-move').
removeClass('mov
|
97d1c64b28311a27d8fa0592e62157be87d67d27 | Update cookies.js | js/cookies.js | js/cookies.js | function setCookie(cname,cvalue,exdays) {
var d = new Date();
d.setTime(d.getTime() + (exdays*24*60*60*1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cname+"="+cvalue+"; "+expires;
}
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
function checkCookie() {
var user=getCookie("username");
if (user != "") {
alert("Welcome again " + user);
} else {
user = prompt("Please enter your name:","");
if (user != "" && user != null) {
setCookie("username", user, 30);
}
}
}
| JavaScript | 0.000004 | @@ -670,13 +670,22 @@
-alert
+document.write
(%22We
|
e5d9c2f390c234419a97542d75b048692e9a5308 | Update general.js | js/general.js | js/general.js | /**
* Archivo: general.js
* Autor: Andy Sapper
* Creado: 06/30/2015
*/
var nw = require('nw.gui');
// load main window's menu
if (process.platform === 'darwin') {
var gui = require('nw.gui');
var menuBar = new gui.Menu({type:"menubar"});
menuBar.createMacBuiltin("Reportes DH", {
hideEdit: true
});
gui.Window.get().menu = menuBar;
}
else if (process.platform === 'win32') {
}
// cambiar fondo y verso del dia acorde a fecha
var dia = ( new Date().getDate() ) % 19,
versos = [
{
"body": "\"Confía en el Señor de todo corazón, y no en tu propia inteligencia.\"",
"verse": "Proverbios 3:5"
},
{
"body": "\"Todo tiene su tiempo, y todo lo que se quiere debajo del cielo tiene su hora.\"",
"verse": "Eclesiastes 3:1"
},
{
"body": "\"Y la paz de Dios, que sobrepasa todo entendimiento, guardará vuestros corazones y vuestros pensamientos en Cristo Jesús.\"",
"verse": "Filipenses 4:7"
},
{
"body": "\"Este es el día que hizo Jehová; nos gozaremos y alegraremos en él.\"",
"verse": "Salmos 118:24"
},
{
"body": "\"Un mandamiento nuevo os doy: Que os améis unos a otros; como yo os he amado, que también os améis unos a otros.\"",
"verse": "Juan 13:34"
},
{
"body": "\"Bendice, alma mía, a Jehová, y bendiga todo mi ser su santo nombre.\"",
"verse": "Salmos 103:1"
},
{
"body": "\"Ninguno tenga en poco tu juventud, sino sé ejemplo de los creyentes en palabra, conducta, amor, espíritu, fe y pureza.\"",
"verse": "1 Timoteo 4:12"
},
{
"body": "\"Todo lo puedo en Cristo que me fortalece.\"",
"verse": "Filipenses 4:13"
},
{
"body": "\"No paguéis a nadie mal por mal; procurad lo bueno delante de todos los hombres.\"",
"verse": "Romanos 12:17"
},
{
"body": "\"Mira que te mando que te esfuerces y seas valiente; no temas ni desmayes, porque Jehová tu Dios estará contigo en dondequiera que vayas.\"",
"verse": "Josué 1:9"
},
{
"body": "\"El que no ama no conoce a Dios, porque Dios es amor.\"",
"verse": "1 Juan 4:8"
},
{
"body": "\"Jehová es mi pastor; nada me faltará. En lugares de delicados pastos me hará descansar; junto a aguas de reposo me pastoreará.\"",
"verse": "Salmos 23:1-2"
},
{
"body": "\"El hombre que tiene amigos ha de mostrarse amigo; y amigo hay más unido que un hermano.\"",
"verse": "Proverbios 18:24"
},
{
"body": "\"Nadie tiene mayor amor que este, que uno ponga su vida por sus amigos.\"",
"verse": "Juan 15:13"
},
{
"body": "\"Alma mía, en Dios solamente reposa, porque de él es mi esperanza.\"",
"verse": "Salmos 62:5"
},
{
"body": "\"Porque tú, oh Jehová, bendecirás al justo; Como con un escudo lo rodearás de tu favor.\"",
"verse": "Salmos 5:12"
},
{
"body": "\"La bendición de Jehová es la que enriquece, y no añade tristeza con ella.\"",
"verse": "Proverbios 10:22"
},
{
"body": "\"Mas Dios muestra su amor para con nosotros, en que siendo aún pecadores, Cristo murió por nosotros.\"",
"verse": "Romanos 5:8"
},
{
"body": "\"Amado, yo deseo que tú seas prosperado en todas las cosas, y que tengas salud, así como prospera tu alma.\"",
"verse": "3 Juan 1:2"
}
];
// actualizar datos
$(document).ready( function () {
// cambiar imagen de strip
var element = document.getElementById('main-strip');
element.style.background = 'url(./images/backg-' + dia + '.jpg)';
// cambiar verso del dia
$('#verse-body').html(versos[dia].body);
$('#verse').html(versos[dia].verse);
});
| JavaScript | 0.000001 | @@ -76,354 +76,8 @@
*/%0A%0A
-var nw = require('nw.gui');%0A%0A// load main window's menu%0Aif (process.platform === 'darwin') %7B%0A var gui = require('nw.gui');%0A var menuBar = new gui.Menu(%7Btype:%22menubar%22%7D);%0A menuBar.createMacBuiltin(%22Reportes DH%22, %7B%0A hideEdit: true%0A %7D);%0A %0A gui.Window.get().menu = menuBar;%0A%7D%0Aelse if (process.platform === 'win32') %7B%0A %0A%7D%0A%0A
// c
|
d3835f1040bb6400d1b6322e73b44376317c4342 | update collection/pluck | src/collection/pluck.js | src/collection/pluck.js | var make = require('./make_')
var amap = require('../array/map')
var omap = require('../object/map')
var prop = require('../function/prop')
function arrPluck (arr, propName) {
return amap(arr, propName)
}
function objPluck (obj, propName) {
return omap(obj, prop(propName))
}
module.exports = make(arrPluck, objPluck)
| JavaScript | 0 | @@ -28,19 +28,23 @@
')%0Avar a
-map
+rrPluck
= requi
@@ -60,19 +60,21 @@
ray/
-map
+pluck
')%0Avar o
map
@@ -69,19 +69,23 @@
')%0Avar o
-map
+bjPluck
= requi
@@ -102,194 +102,15 @@
ect/
-map')%0Avar prop = require('../function/prop')%0A%0Afunction arrPluck (arr, propName) %7B%0A return amap(arr, propName)%0A%7D%0A%0Afunction objPluck (obj, propName) %7B%0A return omap(obj, prop(propName))%0A%7D
+pluck')
%0A%0Amo
|
e1f5282ff29a5361d8d49510cca43f751b8b79c4 | Fix linting errors in install.js command | src/commands/install.js | src/commands/install.js | var fs = require('fs');
var ff = require('ff');
var path = require('path');
var apps = require('../apps');
var install = require('../install');
var BaseCommand = require('../util/BaseCommand').BaseCommand;
var InstallCommand = Class(BaseCommand, function (supr) {
this.name = 'install';
this.description = 'installs (or updates) devkit dependencies for an app or a specific dependency if one is provided';
this.init = function () {
supr(this, 'init', arguments);
this.opts
.describe('ssh', 'switches git protocol to ssh, default: false (https)')
.describe('link', 'uses symlinks to the module cache (development only)')
.describe('skip-fetch', "if no version is specified, don't query servers for the latest version")
}
this.exec = function (args, cb) {
var argv = this.opts.argv;
var protocol = argv.ssh ? 'ssh' : 'https';
var skipFetch = argv['skip-fetch'];
var module = args.shift();
var f = ff(function () {
apps.get('.', f());
}, function (app) {
// forward along the app
f(app);
// ensure modules directory exists
if (!fs.existsSync(app.paths.modules)) {
fs.mkdirSync(app.paths.modules);
}
if (!fs.statSync(app.paths.modules).isDirectory()) {
throw new Error('"your-app/modules" must be a directory');
}
if (module) {
// single module provided, install it
install.installModule(app, module, {
protocol: protocol,
skipFetch: skipFetch
}, f());
} else {
// no module provided, install all dependencies after we ensure we
// have dependencies
var deps = app.manifest.dependencies;
if (!deps || !deps['devkit-core']) {
// ensure devkit is a dependency
logger.log('Adding default dependencies to "manifest.json"...');
app.validate({protocol: protocol}, f());
}
}
}, function (app) {
// if we installed a single module, we're done
if (!module) {
// otherwise, need to install all dependencies
install.installDependencies(app, {protocol: protocol, link: argv.link}, f());
}
}).cb(cb);
}
});
module.exports = InstallCommand;
| JavaScript | 0.000001 | @@ -351,17 +351,25 @@
ndencies
-
+' +%0A '
for an a
@@ -671,16 +671,25 @@
escribe(
+%0A
'skip-fe
@@ -697,15 +697,20 @@
ch',
- %22if no
+%0A 'if
ver
@@ -717,16 +717,20 @@
sion is
+not
specifie
@@ -736,27 +736,20 @@
ed,
-don't query servers
+server query
for
@@ -771,14 +771,23 @@
sion
-%22)
+'%0A );
%0A %7D
+;
%0A%0A
@@ -987,32 +987,47 @@
f = ff(function
+getApplication
() %7B%0A apps.
@@ -1984,32 +1984,60 @@
%7D, function
+installDependenciesIfNeeded
(app) %7B%0A //
@@ -2199,16 +2199,27 @@
s(app, %7B
+%0A
protocol
@@ -2245,16 +2245,25 @@
rgv.link
+%0A
%7D, f());
@@ -2267,24 +2267,122 @@
));%0A %7D%0A
+ %7D).onError(function installErrorHandler (err) %7B%0A console.error(err && err.stack %7C%7C err);%0A
%7D).cb(cb
@@ -2387,16 +2387,17 @@
cb);%0A %7D
+;
%0A%7D);%0A%0Amo
|
0abe01c2a5fd9f3f82d38a89a7999258e36b610a | Make events passive (#9) | lib.js | lib.js |
var rippleTypeAttr = 'data-event';
/**
* @param {!Event|!Touch} event
* @return {Node}
*/
function getHolderWithRippleJsClass(event) {
var holder = /** @type {!Node} */ (event.target);
var childNodesLength = holder.childNodes.length;
if (holder.localName !== 'button' || !childNodesLength) {
return holder.classList.contains('rippleJS') ? holder : null;
}
// fix firefox event target issue https://bugzilla.mozilla.org/show_bug.cgi?id=1089326
for (var i = 0; i < childNodesLength; ++i) {
var child = holder.childNodes[i];
var cl = child.classList;
if (cl && cl.contains('rippleJS')) {
return child; // return valid holder
}
}
return null;
}
/**
* @param {string} type
* @param {!Event|!Touch} at
*/
export function startRipple(type, at) {
var holder = getHolderWithRippleJsClass(at);
if (!holder) {
return false; // ignore
}
var cl = holder.classList;
// Store the event use to generate this ripple on the holder: don't allow
// further events of different types until we're done. Prevents double-
// ripples from mousedown/touchstart.
var prev = holder.getAttribute(rippleTypeAttr);
if (prev && prev !== type) {
return false;
}
holder.setAttribute(rippleTypeAttr, type);
// Create and position the ripple.
var rect = holder.getBoundingClientRect();
var x = at.offsetX;
var y;
if (x !== undefined) {
y = at.offsetY;
} else {
x = at.clientX - rect.left;
y = at.clientY - rect.top;
}
var ripple = document.createElement('div');
var max;
if (rect.width === rect.height) {
max = rect.width * 1.412;
} else {
max = Math.sqrt(rect.width * rect.width + rect.height * rect.height);
}
var dim = max*2 + 'px';
ripple.style.width = dim;
ripple.style.height = dim;
ripple.style.marginLeft = -max + x + 'px';
ripple.style.marginTop = -max + y + 'px';
// Activate/add the element.
ripple.className = 'ripple';
holder.appendChild(ripple);
window.setTimeout(function() {
ripple.classList.add('held');
}, 0);
var releaseEvent = (type === 'mousedown' ? 'mouseup' : 'touchend');
var release = function(ev) {
// TODO: We don't check for _our_ touch here. Releasing one finger
// releases all ripples.
document.removeEventListener(releaseEvent, release);
ripple.classList.add('done');
// larger than animation: duration in css
window.setTimeout(function() {
holder.removeChild(ripple);
if (!holder.children.length) {
cl.remove('active');
holder.removeAttribute(rippleTypeAttr);
}
}, 650);
};
document.addEventListener(releaseEvent, release);
}
/**
* Installs mousedown/touchstart handlers on the target for ripples.
*
* @param {!Node=} target to install on, default document
*/
export default function init(target) {
target = target || document;
target.addEventListener('mousedown', function(ev) {
if (ev.button === 0) {
// trigger on left click only
startRipple(ev.type, ev);
}
});
target.addEventListener('touchstart', function(ev) {
for (var i = 0; i < ev.changedTouches.length; ++i) {
startRipple(ev.type, ev.changedTouches[i]);
}
});
}
| JavaScript | 0.000113 | @@ -3008,24 +3008,41 @@
v);%0A %7D%0A
+%7D, %7Bpassive: true
%7D);%0A target
@@ -3203,14 +3203,31 @@
%7D%0A
+%7D, %7Bpassive: true
%7D);%0A%7D%0A
|
b4094ffba161713deb1dd0977a778262741ac20c | Fix log bug | log.js | log.js | /**
* log.js is a "Poor man's" logging module. It provides basic colorized logging using named
* loggers with selectable log levels.
*/
var process = require('process');
try { var colors = require('colors'); } catch(e) {var colors = false;}
var _suppress = false;
var log_buffer = [];
var LOG_BUFFER_SIZE = 500;
// String versions of the allowable log levels
LEVELS = {
'g2' : 0,
'debug' : 1,
'info' : 2,
'warn' : 3,
'error' : 4,
};
// Default log levels for loggers with specific names.
LOG_LEVELS = {
'g2' : 'debug',
'gcode' : 'debug',
'sbp' : 'debug',
'machine' : 'debug',
'manual' : 'debug',
'api' : 'debug',
'detection' :'debug',
'config_loader' : 'debug',
'settings' : 'debug',
'log':'debug'
};
function setGlobalLevel(lvl){
if (lvl)
{
if (lvl >= 0 && lvl <= 3)
{
// assign the log level to the string equivalent of the integer
Object.keys(LOG_LEVELS).forEach(function(key) {
LOG_LEVELS[key] = Object.keys(LEVELS).filter(function(key) {return (LEVELS[key] === lvl);})[0];
});
}
else if (Object.keys(LEVELS).indexOf(lvl) >= 0) // if a string
{
// assign the log level to the string that is given
Object.keys(LOG_LEVELS).forEach(function(key) {
LOG_LEVELS[key] = lvl;
});
}
else if (lvl === "none")
{
return;
}
else
{
logger('log').warn('Invalid log level: ' + lvl);
}
}
}
// The Logger object is what is created and used by modules to log to the console.
var Logger = function(name) {
this.name = name;
};
// Index of all the Logger objects that have been created.
var logs = {};
// Output the provided message with colorized output (if available) and the logger name
Logger.prototype.write = function(level, msg) {
if(_suppress) {
return;
}
my_level = LOG_LEVELS[this.name] || 'debug';
if((LEVELS[level] || 0) >= (LEVELS[my_level] || 0)) {
buffer_msg = level + ': ' + msg + ' ['+this.name+']';
if(colors) {
switch(level) {
case 'g2':
console.log((level + ': ').magenta + msg + ' ['+this.name+']');
break;
case 'debug':
console.log((level + ': ').blue + msg+' ['+this.name+']');
break;
case 'info':
console.log((level + ': ').green + msg+' ['+this.name+']');
break;
case 'warn':
console.log((level + ': ').yellow + msg+' ['+this.name+']');
break;
case 'error':
console.log((level + ': ').red + msg+' ['+this.name+']');
break;
}
} else {
console.log(level + ': ' + msg+' ['+this.name+']');
}
log_buffer.push(buffer_msg);
while(log_buffer.length > LOG_BUFFER_SIZE) {
log_buffer.shift();
}
}
};
// These functions provide a shorthand alternative to specifying the log level every time
Logger.prototype.debug = function(msg) { this.write('debug', msg);};
Logger.prototype.info = function(msg) { this.write('info', msg);};
Logger.prototype.warn = function(msg) { this.write('warn', msg);};
Logger.prototype.error = function(msg) {
this.write('error', msg);
if(msg.stack) {
this.write('error', msg.stack;
}
};
Logger.prototype.g2 = function(msg) {this.write('g2', msg);};
Logger.prototype.uncaught = function(err) {
if(colors) {
console.log("UNCAUGHT EXCEPTION".red.underline);
console.log(('' + err.stack).red)
} else {
console.log("UNCAUGHT EXCEPTION");
console.log(err.stack);
}
}
// Factory function for producing a new, named logger object
var logger = function(name) {
if(name in logs) {
return logs[name];
} else {
l = new Logger(name);
logs[name] = l;
return l;
}
};
process.on('uncaughtException', function(err) { Logger.prototype.uncaught(err); });
var suppress = function(v) {_suppress = true;};
var unsuppress = function(v) {_suppress = false;};
var getLogBuffer = function() {
return log_buffer.join('\n');
};
exports.suppress = suppress;
exports.logger = logger;
exports.setGlobalLevel = setGlobalLevel;
exports.getLogBuffer = getLogBuffer;
| JavaScript | 0.000001 | @@ -3003,16 +3003,17 @@
sg.stack
+)
;%0A%09%7D%0A%7D;%0A
|
82526025bcb7ea636feb6238ecf3a798c1c14e42 | Handle different id names. This will be unified. Right now it is a work around. | website/app/application/core/projects/project/files/file-edit-controller.js | website/app/application/core/projects/project/files/file-edit-controller.js | Application.Controllers.controller("FilesEditController",
["$scope", "$stateParams", "projectFiles", "User", "mcfile", "pubsub", "tags", "mcapi", "$modal", "toastr", "$state",
FilesEditController]);
function FilesEditController($scope, $stateParams, projectFiles, User, mcfile, pubsub, tags, mcapi, $modal, toastr, $state) {
var ctrl = this;
ctrl.editNote = false;
pubsub.waitOn($scope, 'datafile-note.change', function () {
ctrl.editNote = !ctrl.editNote;
});
pubsub.waitOn($scope, 'display-directory', function () {
ctrl.active = projectFiles.getActiveDirectory();
ctrl.type = 'dir';
});
ctrl.addTag = function (tag) {
var tag_obj = {'id': tag.tag_id, 'owner': User.u()};
tags.createTag(tag_obj, ctrl.active.df_id);
};
ctrl.removeTag = function (tag) {
tags.removeTag(tag.tag_id, ctrl.active.df_id);
};
ctrl.downloadSrc = function (file) {
return mcfile.downloadSrc(file.df_id);
};
ctrl.fileSrc = function (file) {
if (file) {
return mcfile.src(file.df_id);
}
};
ctrl.closeFile = function () {
ctrl.active = null;
};
ctrl.rename = function () {
var modalInstance = $modal.open({
size: 'sm',
templateUrl: 'application/core/projects/project/files/rename-file.html',
controller: 'RenameFileModalController',
controllerAs: 'file',
resolve: {
active: function () {
return ctrl.active;
}
}
});
modalInstance.result.then(function (name) {
mcapi("/datafile/%", $stateParams.file_id)
.success(function () {
ctrl.active.name = name;
pubsub.send('files.refresh');
})
.error(function (err) {
toastr.error("Rename failed: " + err.error, "Error");
})
.put({name: name});
});
};
function getActiveFile() {
ctrl.active = projectFiles.getActiveFile();
if (!ctrl.active) {
// A refresh on page has happened. That means we have lost
// our state in the directory tree. We have the file but
// tree isn't open on that file. In this case we show the
// top level directory.
ctrl.active = ctrl.active = projectFiles.getActiveDirectory();
//ctrl.type = 'dir';
} else {
if (_.isObject(ctrl.active.mediatype)) {
// TODO: Fix this hack
// This exists because search sends back the full mediatype, while
// the tree doesn't.
ctrl.active.mediatype = ctrl.active.mediatype.mime;
}
//ctrl.type = 'file';
if (isImage(ctrl.active.mediatype)) {
ctrl.fileType = "image";
} else if (ctrl.active.mediatype === "application/pdf") {
ctrl.fileType = "pdf";
} else if (ctrl.active.mediatype === "application/vnd.ms-excel") {
ctrl.fileType = "xls";
} else {
ctrl.fileType = ctrl.active.mediatype;
}
}
}
function init() {
ctrl.active = {};
ctrl.type = $stateParams.file_type;
if (ctrl.type == 'datafile') {
getActiveFile();
} else {
ctrl.active = projectFiles.getActiveDirectory();
}
}
init();
}
////////////////////////////////
Application.Controllers.controller("RenameFileModalController",
["$modalInstance", "active", RenameFileModalController]);
function RenameFileModalController($modalInstance, active) {
var ctrl = this;
ctrl.name = "";
ctrl.rename = rename;
ctrl.cancel = cancel;
///////////
function rename() {
if (ctrl.name != "" && ctrl.name != active.name) {
$modalInstance.close(ctrl.name);
}
}
function cancel() {
$modalInstance.dismiss('cancel');
}
} | JavaScript | 0 | @@ -1049,32 +1049,66 @@
if (file) %7B%0A
+ var id = getID(file);%0A
retu
@@ -1121,24 +1121,16 @@
ile.src(
-file.df_
id);%0A
@@ -3582,16 +3582,473 @@
init();%0A
+%0A%0A //////////////////////%0A%0A // TODO: Clean this up so we don't have to search for different id keys%0A // returns the file id depending on which key it is under.%0A function getID(file) %7B%0A if ('df_id' in file) %7B%0A return file.df_id;%0A %7D else if ('datafile_id' in file) %7B%0A return file.datafile_id;%0A %7D else if ('id' in file) %7B%0A return file.id;%0A %7D else %7B%0A return %22%22%0A %7D%0A %7D%0A
%7D%0A%0A/////
|
2b222f5e49ef5050edbb404edccc4de375b6b6f6 | Remove reduntant | jet/static/jet/js/src/features/related-popups.js | jet/static/jet/js/src/features/related-popups.js | var $ = require('jquery');
var WindowStorage = require('../utils/windowStorage');
var RelatedPopups = function() {
this.windowStorage = new WindowStorage('relatedWindows');
};
RelatedPopups.prototype = {
updateLinks: function($select) {
$select.find('~ .change-related, ~ .delete-related, ~ .add-another').each(function() {
var $link = $(this);
var hrefTemplate = $link.data('href-template');
if (hrefTemplate == undefined) {
return;
}
var value = $select.val();
if (value) {
$link.attr('href', hrefTemplate.replace('__fk__', value))
} else {
$link.removeAttr('href');
}
});
},
initLinks: function() {
var self = this;
$('.form-row select').each(function() {
var $select = $(this);
self.updateLinks($select);
$select.find('~ .add-related, ~ .change-related, ~ .delete-related, ~ .add-another').each(function() {
var $link = $(this);
$link.on('click', function(e) {
e.preventDefault();
var href = $link.attr('href');
if (href != undefined) {
if (href.indexOf('_popup') == -1) {
href += (href.indexOf('?') == -1) ? '?_popup=1' : '&_popup=1';
}
self.showPopup($select, href);
}
});
});
}).on('change', function() {
self.updateLinks($(this));
});
$('.form-row input').each(function() {
var $input = $(this);
$input.find('~ .related-lookup').each(function() {
var $link = $(this);
$link.on('click', function(e) {
e.preventDefault();
var href = $link.attr('href');
href += (href.indexOf('?') == -1) ? '?_popup=1' : '&_popup=1';
self.showPopup($input, href);
});
});
});
},
initPopupBackButton: function() {
var self = this;
$('.related-popup-back').on('click', function(e) {
e.preventDefault();
self.closePopup();
});
},
showPopup: function($input, href) {
var $document = $(window.top.document);
var $container = $document.find('.related-popup-container');
var $loading = $container.find('.loading-indicator');
var $body = $document.find('body').addClass('non-scrollable');
var $iframe = $('<iframe>')
.attr('src', href)
.on('load', function() {
$popup.add($document.find('.related-popup-back')).fadeIn(200, 'swing', function() {
$loading.hide();
});
});
var $popup = $('<div>')
.addClass('related-popup')
.data('input', $input)
.append($iframe);
$loading.show();
$container.fadeIn(200, 'swing', function() {
$container.append($popup);
});
$body.addClass('non-scrollable');
},
closePopup: function(response) {
var previousWindow = this.windowStorage.previous();
var self = this;
(function($) {
var $document = $(window.top.document);
var $popups = $document.find('.related-popup');
var $container = $document.find('.related-popup-container');
var $popup = $popups.last();
if (response != undefined) {
self.processPopupResponse($popup, response);
}
self.windowStorage.pop();
if ($popups.length == 1) {
$container.fadeOut(200, 'swing', function() {
$document.find('.related-popup-back').hide();
$document.find('body').removeClass('non-scrollable');
$popup.remove();
});
} else {
$popup.remove();
}
})(previousWindow ? previousWindow.jet.jQuery : $);
},
findPopupResponse: function() {
var self = this;
$('#django-admin-popup-response-constants').each(function() {
var $constants = $(this);
var response = $constants.data('popup-response');
self.closePopup(response);
});
},
processPopupResponse: function($popup, response) {
var $input = $popup.data('input');
switch (response.action) {
case 'change':
$input.find('option').each(function() {
var $option = $(this);
if ($option.val() == response.value) {
$option.html(response.obj).val(response.new_value);
}
});
$input.trigger('change').trigger('select:init');
break;
case 'delete':
$input.find('option').each(function() {
var $option = $(this);
if ($option.val() == response.value) {
$option.remove();
}
});
$input.trigger('change').trigger('select:init');
break;
default:
if ($input.is('select')) {
var $option = $('<option>')
.val(response.value)
.html(response.obj);
$input.append($option);
$option.attr('selected', true);
$input
.trigger('change')
.trigger('select:init');
} else if ($input.is('input.vManyToManyRawIdAdminField') && $input.val()) {
$input.val($input.val() + ',' + response.value);
} else if ($input.is('input')) {
$input.val(response.value);
}
break;
}
},
overrideRelatedGlobals: function() {
var self = this;
window.showRelatedObjectLookupPopup
= window.showAddAnotherPopup
= window.showRelatedObjectPopup
= function() { };
window.opener = this.windowStorage.previous();
window.dismissRelatedLookupPopup = function(win, chosenId) {
self.closePopup({
action: 'lookup',
value: chosenId
});
};
},
initDeleteRelatedCancellation: function() {
var self = this;
$('.popup.delete-confirmation .cancel-link').on('click', function(e) {
e.preventDefault();
self.closePopup();
}).removeAttr('onclick');
},
run: function() {
this.windowStorage.push(window);
try {
this.initLinks();
this.initPopupBackButton();
this.findPopupResponse();
this.overrideRelatedGlobals();
this.initDeleteRelatedCancellation();
this.overrideRelatedGlobals();
} catch (e) {
console.error(e, e.stack);
}
}
};
$(document).ready(function() {
new RelatedPopups().run();
});
| JavaScript | 0.000027 | @@ -2628,35 +2628,8 @@
dy')
-.addClass('non-scrollable')
;%0A
|
0a3b212eee77ab9bb906e5fbcf36fbab1dc8e568 | Disable a test that is no longer needed | plugins/candela/plugin_tests/candelaSpec.js | plugins/candela/plugin_tests/candelaSpec.js | girderTest.importPlugin('candela');
girderTest.startApp();
describe('Test the candela UI.', function () {
it('register a user', girderTest.createUser(
'johndoe', '[email protected]', 'John', 'Doe', 'password!'
));
it('uploads the data file', function () {
runs(function () {
expect($('#g-user-action-menu.open').length).toBe(0);
$('.g-user-text>a:first').click();
expect($('#g-user-action-menu.open').length).toBe(1);
$('a.g-my-folders').click();
});
waitsFor(function () {
return $('a.g-folder-list-link').length === 2;
}, 'Public and Private folders to appear');
runs(function () {
$('a.g-folder-list-link:contains("Public")').click();
});
girderTest.waitForLoad();
waitsFor(function () {
return $('ol.breadcrumb>li.active').text() === 'Public' &&
$('.g-empty-parent-message:visible').length === 1;
}, 'descending into Public folder');
girderTest.binaryUpload('clients/web/test/testFile.csv');
runs(function () {
$('.g-item-list-link:first').click();
});
});
it('sets up candela inputs and renders the visualization', function () {
waitsFor(function () {
return $('.g-item-candela-component').length === 1;
}, 'the candela component selector to appear');
runs(function () {
expect($('.g-item-candela-component option').length).toBeGreaterThan(5);
$('.g-item-candela-component').val('BarChart').change();
});
waitsFor(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
return inputs.length > 3;
}, 'the bar chart options to be available');
runs(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
expect(inputs.eq(0).find('label').text()).toBe('Width');
expect(inputs.eq(1).find('label').text()).toBe('Height');
expect(inputs.eq(2).find('label').text()).toBe('X');
var values = [];
for (var i = 0; i < 4; i += 1) {
values.push(inputs.eq(2).find('option').eq(i).text());
}
values.sort();
expect(values).toEqual(['(none)', 'a_b', 'c', 'id']);
$('.g-candela-update-vis').click();
});
waitsFor(function () {
return $('.g-candela-vis').find('canvas').length === 1;
}, 'the vis canvas to be drawn');
runs(function () {
$('.g-item-candela-component').val('TreeHeatmap').change();
});
waitsFor(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
return inputs.length === 9;
}, 'the visualization type to change to TreeHeatmap');
runs(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
expect(inputs.eq(2).find('label').text()).toBe('Identifier column');
expect(inputs.eq(3).find('label').text()).toBe('Color scale');
expect(inputs.eq(3).find('option').eq(1).text()).toBe('row');
});
runs(function () {
$('.g-item-candela-component').val('Histogram').change();
});
waitsFor(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
return inputs.length > 3;
}, 'the visualization type to change to BulletChart');
runs(function () {
var inputs = $('.g-candela-inputs-container').children().eq(1).children().children();
expect(inputs.eq(2).find('label').text()).toBe('X');
});
});
it('uploads a bad data file', function () {
runs(function () {
expect($('#g-user-action-menu.open').length).toBe(0);
$('.g-user-text>a:first').click();
});
waitsFor(function () {
return $('#g-user-action-menu.open').length === 1;
}, 'menu to open');
runs(function () {
$('a.g-my-folders').click();
});
waitsFor(function () {
return $('.g-folder-list-link').length > 0;
}, 'user folder list to load');
runs(function () {
$('a.g-folder-list-link:contains("Public")').click();
});
girderTest.waitForLoad();
waitsFor(function () {
return $('ol.breadcrumb>li.active').text() === 'Public' &&
$('.g-item-list-link').length === 1;
}, 'descending into Public folder');
girderTest.binaryUpload('clients/web/test/testFileBad.csv');
runs(function () {
$('.g-item-list-link').eq(1).click();
});
waitsFor(function () {
return $('.alert-danger').length === 1;
}, 'the error message to appear');
runs(function () {
expect($('.alert-danger').text()).toContain('An error occurred while attempting to read and parse the data file.');
});
});
});
| JavaScript | 0.000014 | @@ -3887,32 +3887,376 @@
);%0A %7D);%0A%0A
+// This test is skipped because this failure mode no longer exists with the%0A // updated Candela plugin backing technologies. Specifically, d3-dsv is used%0A // for parsing, and that module happily accepts any stream of bytes and will%0A // simply parse what it gets, even if that is a zip file or a PNG image or%0A // anything else.%0A x
it('uploads a ba
|
43ad05b19b6cb63894d647265effaed58b0ba8ec | add student (hide/show) form | js/jsrapport/coursestudentsrapportenViewModel.js | js/jsrapport/coursestudentsrapportenViewModel.js | function pageViewModel(gvm) {
gvm.projecttitle = ko.observable("");
gvm.userId = -1;
gvm.coupledCount = 0;
// Page specific i18n bindings
gvm.title = ko.computed(function (){i18n.setLocale(gvm.lang()); return gvm.app() + ' - ' + i18n.__("ProjectTitle") + ": " + gvm.projecttitle();}, gvm);
gvm.pageHeader = ko.observable("Project");
gvm.projectname = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("ProjectName");}, gvm);
gvm.addBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("AddBtn")}, gvm);
gvm.addmoduleBtn = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("Addmodule");}, gvm);
gvm.savePage = ko.computed(function(){i18n.setLocale(gvm.lang()); return i18n.__("SaveBtn");}, gvm);
gvm.getProjectInfo = function() {
$.getJSON('/api/project/' + $("#projectHeader").data('value'), function(data) {
gvm.pageHeader(data[0].code + ' - ' + data[0].name);
});
};
gvm.coupledLists = ko.observableArray([]);
gvm.availableLists = ko.observableArray([]);
gvm.addCoupledList = function(id, name) {
// Push data
var tblOject = {tid: id, tname: name};
gvm.coupledLists.push(tblOject);
$("#uncouplebtn-" + id).click(function(){
showYesNoModal("Bent u zeker dat u dit item wil ontkoppelen?", function(val){
if(val){
$.ajax({
url: '/api/project/' + $("#projectHeader").data('value') +'/studentlist/uncouple/' + id,
type: "DELETE",
success: function() {
gvm.coupledCount--;
viewModel.coupledLists.remove(tblOject);
}
});
}
});
});
}
gvm.addAvailableLists = function(id, name) {
var tblOject = {tid: id, tname: name};
gvm.availableLists.push(tblOject);
$("#couplebtn-" + id).click(function(){
if(gvm.coupledCount == 0) {
$.ajax({
url: '/api/project/' + $("#projectHeader").data('value') + '/studentlist/' + id,
type: "POST",
success: function() {
gvm.coupledCount++;
viewModel.coupledLists.push(tblOject);
}
});
} else {
alert("list already coupled");
}
});
}
gvm.getCoupledLists = function() {
$.getJSON('/api/project/' + $("#projectHeader").data('value') + '/coupledlists', function(data) {
$.each(data, function(i, item) {
gvm.coupledCount++;
gvm.addCoupledList(item.id, item.name);
});
});
}
gvm.getAvailableLists = function() {
$.getJSON('/api/studentlists/' + gvm.userId, function(data) {
$.each(data, function(i, item) {
gvm.addAvailableLists(item.id, item.name);
});
});
}
}
function getAllTeachers() {
var teachers = [];
$.getJSON('/api/getteacherrapport', function(data) {
$.each(data, function(i, item) {
teachers.push(item.firstname + " " + item.lastname);
});
});
return teachers;
}
function initPage() {
viewModel.getProjectInfo();
viewModel.getCoupledLists();
//Add Teacher
$('#addTeacherForm').hide();
$('#addTeacher').click(function(){
$("#addTeacherForm").show();
console.log(getAllTeachers());
$('#teachersComplete').autocomplete({ source: getAllTeachers() });
});
$('#addTeacherBtn').click(function() {
//add teacher
$('#addTeacherForm').hide();
});
//Add StudentList
$('#addStudentListForm').hide();
$('#addStudentListBtn').click(function(){
$("#addStudentListForm").show();
console.log(getAllTeachers());
$('#teachersComplete').autocomplete({ source: getAllTeachers() });
});
$('#addStudentListBtn').click(function() {
//add studentList
$('#addStudentListForm').hide();
});
$.getJSON('/api/currentuser', function(data) {
viewModel.userId = data.id;
viewModel.getAvailableLists(data.id);
});
} | JavaScript | 0 | @@ -3841,402 +3841,8 @@
);%0A%0A
- //Add StudentList%0A%0A $('#addStudentListForm').hide();%0A%0A $('#addStudentListBtn').click(function()%7B%0A $(%22#addStudentListForm%22).show();%0A console.log(getAllTeachers());%0A $('#teachersComplete').autocomplete(%7B source: getAllTeachers() %7D);%0A %7D);%0A%0A $('#addStudentListBtn').click(function() %7B%0A //add studentList%0A $('#addStudentListForm').hide();%0A %7D);%0A%0A
|
e7f63bb210d8c1540ff06248a687031e1a820521 | Add tsd task | Gulpfile.js | Gulpfile.js | var gulp = require('gulp')
var browserify = require('browserify')
var del = require('del')
var documentation = require('gulp-documentation')
var fs = require('fs')
var KarmaServer = require('karma').Server
var source = require('vinyl-source-stream')
var serve = require('gulp-serve')
var standard = require('gulp-standard')
var shell = require('gulp-shell')
var ts = require('gulp-typescript')
var rename = require('gulp-rename')
var tslint = require('gulp-tslint')
var argv = require('yargs').argv
var paths = {
mapillaryjs: 'mapillaryjs',
build: './build',
ts: {
src: './src/**/*.ts',
tests: './spec/**/*.ts',
dest: 'build',
testDest: 'build/spec'
},
js: {
src: './build/**/*.js',
tests: './spec/**/*.js'
}
}
var config = {
ts: JSON.parse(fs.readFileSync('./tsconfig.json', 'utf8')).compilerOptions
}
gulp.task('browserify', ['typescript'], function () {
var bundler = browserify({
entries: ['./build/Mapillary.js'],
debug: true,
fullPaths: false,
standalone: 'Mapillary'
})
bundler.transform('brfs')
bundler
.bundle()
.pipe(source('./build/Mapillary.js'))
.pipe(rename('bundle.js'))
.pipe(gulp.dest('./build/'))
})
gulp.task('clean', function () {
return del([
'html-documentation',
'build/**/*',
'debug/**/*.js'
])
})
gulp.task('documentation', ['browserify'], function () {
gulp.src(['./build/Viewer.js', './build/API.js'])
.pipe(documentation({format: 'html'}))
.pipe(gulp.dest('html-documentation'))
})
gulp.task('js-lint', function () {
return gulp.src('./Gulpfile.js')
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}))
})
gulp.task('serve', ['browserify'], serve('.'))
gulp.task('test', function (done) {
var config
if (argv.grep) {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
client: {
args: ['--grep', argv.grep]
},
singleRun: true
})
} else {
config = extendKarmaConfig(__dirname + '/karma.conf.js', {
singleRun: true
})
}
new KarmaServer(config, function (exitCode) {
if (exitCode) {
console.error(exitCode)
}
}, done).start()
})
gulp.task('test-watch', function (done) {
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: false
}, done).start()
})
gulp.task('ts-lint', function (cb) {
var stream = gulp.src(paths.ts.src)
.pipe(tslint())
.pipe(tslint.report('verbose'))
return stream
})
gulp.task('tsd', shell.task('./node_modules/tsd/build/cli.js install'))
gulp.task('typescript', ['ts-lint', 'typescript-src', 'typescript-test'], function (cb) { cb() })
gulp.task('typescript-src', function () {
var stream = gulp.src(paths.ts.src)
.pipe(ts(config.ts))
.pipe(gulp.dest(paths.ts.dest))
return stream
})
gulp.task('typescript-test', function () {
var stream = gulp.src(paths.ts.tests)
.pipe(ts(config.ts))
.pipe(gulp.dest(paths.ts.testDest))
return stream
})
gulp.task('watch', [], function () {
gulp.watch([paths.ts.src, paths.ts.tests], ['browserify'])
})
gulp.task('default', ['serve', 'watch'])
// Helpers
function extendKarmaConfig (path, conf) {
conf.configFile = path
return conf
}
| JavaScript | 0.999602 | @@ -2350,32 +2350,41 @@
.task('ts-lint',
+ %5B'tsd'%5D,
function (cb) %7B
|
da63de8ac398d10e5fc42c2fed992fb74849e350 | Remove default article url for embed title | rss/translator/embed.js | rss/translator/embed.js | const Discord = require('discord.js')
const isStr = str => str && typeof str === 'string'
// objectEmbed.message => embed.description
module.exports = (embeds, article) => {
const richEmbeds = []
for (var e = 0; e < embeds.length; ++e) {
const richEmbed = new Discord.RichEmbed()
const objectEmbed = embeds[e]
if (isStr(objectEmbed.title)) {
const t = article.convertKeywords(objectEmbed.title)
richEmbed.setTitle(t.length > 256 ? t.slice(0, 250) + '...' : t)
}
if (isStr(objectEmbed.description)) richEmbed.setDescription(article.convertKeywords(objectEmbed.description))
if (isStr(objectEmbed.url)) richEmbed.setURL(article.convertKeywords(objectEmbed.url))
else richEmbed.setURL(article.link)
if (objectEmbed.color && !isNaN(objectEmbed.color) && objectEmbed.color <= 16777215 && objectEmbed.color > 0) richEmbed.setColor(parseInt(objectEmbed.color, 10))
else if (isStr(objectEmbed.color) && objectEmbed.color.startsWith('#') && objectEmbed.color.length === 7) richEmbed.setColor(objectEmbed.color)
if (isStr(objectEmbed['footer_text'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footer_text']), isStr(objectEmbed['footer_icon_url']) ? article.convertKeywords(objectEmbed['footer_icon_url']) : undefined)
if (isStr(objectEmbed['footerText'])) richEmbed.setFooter(article.convertKeywords(objectEmbed['footerText']), isStr(objectEmbed['footerIconUrl']) ? article.convertKeywords(objectEmbed['footerIconUrl']) : undefined)
if (isStr(objectEmbed['author_name'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['author_name']), isStr(objectEmbed['author_icon_url']) ? article.convertKeywords(objectEmbed['author_icon_url']) : undefined, isStr(objectEmbed['author_url']) ? article.convertKeywords(objectEmbed['author_url']) : undefined)
if (isStr(objectEmbed['authorName'])) richEmbed.setAuthor(article.convertKeywords(objectEmbed['authorName']), isStr(objectEmbed['authorIconUrl']) ? article.convertKeywords(objectEmbed['authorIconUrl']) : undefined, isStr(objectEmbed['authorUrl']) ? article.convertKeywords(objectEmbed['authorUrl']) : undefined)
if (isStr(objectEmbed['thumbnail_url'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnail_url']))
if (isStr(objectEmbed['thumbnailUrl'])) richEmbed.setThumbnail(article.convertKeywords(objectEmbed['thumbnailUrl']))
if (isStr(objectEmbed['image_url'])) richEmbed.setImage(article.convertKeywords(objectEmbed['image_url']))
if (isStr(objectEmbed['imageUrl'])) richEmbed.setImage(article.convertKeywords(objectEmbed['imageUrl']))
if (isStr(objectEmbed.timestamp)) {
const setting = objectEmbed.timestamp
richEmbed.setTimestamp(setting === 'article' ? new Date(article.rawDate) : setting === 'now' ? new Date() : new Date(setting)) // No need to check for invalid date since discord.js does it
}
const fields = objectEmbed.fields
if (Array.isArray(fields)) {
for (var x = 0; x < fields.length; ++x) {
const field = fields[x]
const inline = field.inline === true
let title = article.convertKeywords(field.title)
title = title.length > 256 ? title.slice(0, 250) + '...' : title
let value = article.convertKeywords(field.value ? field.value : '')
value = value.length > 1024 ? value.slice(0, 1020) + '...' : value.length > 0 ? value : '\u200b'
if (typeof title === 'string' && !title) richEmbed.addBlankField(inline)
else if (richEmbed.fields.length < 10) richEmbed.addField(title, value, inline)
}
}
richEmbeds.push(richEmbed)
}
return richEmbeds
}
| JavaScript | 0 | @@ -317,16 +317,17 @@
beds%5Be%5D%0A
+%0A
if (
@@ -486,24 +486,25 @@
: t)%0A %7D%0A
+%0A
if (isSt
@@ -701,48 +701,9 @@
l))%0A
- else richEmbed.setURL(article.link)
%0A
+
@@ -864,16 +864,16 @@
r, 10))%0A
-
else
@@ -1012,16 +1012,17 @@
.color)%0A
+%0A
if (
|
fb53564b63893b6748dc480bb8089ea7d69d182e | queue number 10 to 5 | run_feedFetchTrimmer.js | run_feedFetchTrimmer.js | #! /usr/bin/env node
var fs = require('fs');
var async = require('async'); // asyncjs for async stuff
var feedFetchTrimmer = require('./feedFetchTrimmer.js');
// process.setMaxListeners(0);
fs.readFile('./feeds.json', 'utf8', function(err, data) {
'use strict';
var q = async.queue(feedFetchTrimmer, 10);
var FeedsJson = JSON.parse(data);
var urls = [];
for (var j = 0; j < FeedsJson.blogs.length; j++) {
urls.push(FeedsJson.blogs[j].url);
}
// console.log(urls);
if (err) {
throw err;
}
// Feeds = JSON.parse(data);
// var feed = Feeds.some;
// var callback = function(e) {
// if (e) {
// console.log(e);
// return;
// }
// console.log('something\'s odd, you expected an error but did not get one!');
// };
q.drain = function() {
console.log('all items have been processed');
};
q.push(urls, function(error, warning) {
if (error) {
console.log(error);
}
if (warning) {console.log(warning); }
//console.log('finished processing item');
});
// for (var i = 0; i < urls.length; i++) {
// feedFetchTrimmer(urls[i], callback);
// }
});
| JavaScript | 0.99907 | @@ -303,10 +303,9 @@
er,
-10
+5
);%0A
|
b78c1252e5edc0fc2455c2ae4f02bc3b81171fc4 | make async tests fail faster | test-main.js | test-main.js | // Use "register" extension from systemjs.
// That's what Traceur outputs: `System.register()`.
register(System);
// Cancel Karma's synchronous start,
// we will call `__karma__.start()` later, once all the specs are loaded.
__karma__.loaded = function() {};
System.baseURL = '/base/modules/';
// So that we can import packages like `core/foo`, instead of `core/src/foo`.
System.paths = {
'angular/*': './angular/src/*.js',
'angular/test/*': './angular/test/*.js',
'core/*': './core/src/*.js',
'core/test/*': './core/test/*.js',
'change_detection/*': './change_detection/src/*.js',
'change_detection/test/*': './change_detection/test/*.js',
'facade/*': './facade/src/*.js',
'facade/test/*': './facade/test/*.js',
'di/*': './di/src/*.js',
'di/test/*': './di/test/*.js',
'directives/*': './directives/src/*.js',
'directives/test/*': './directives/test/*.js',
'reflection/*': './reflection/src/*.js',
'reflection/test/*': './reflection/test/*.js',
'rtts_assert/*': './rtts_assert/src/*.js',
'rtts_assert/test/*': './rtts_assert/test/*.js',
'test_lib/*': './test_lib/src/*.js',
'test_lib/test/*': './test_lib/test/*.js',
'transpiler/*': '../tools/transpiler/*.js'
}
// Import all the specs, execute their `main()` method and kick off Karma (Jasmine).
Promise.all(
Object.keys(window.__karma__.files) // All files served by Karma.
.filter(onlySpecFiles)
.map(window.file2moduleName) // Normalize paths to module names.
.map(function(path) {
return System.import(path).then(function(module) {
if (module.hasOwnProperty('main')) {
module.main()
} else {
throw new Error('Module ' + path + ' does not implement main() method.');
}
});
})).then(function() {
__karma__.start();
}, function(error) {
console.error(error.stack || error)
__karma__.start();
});
function onlySpecFiles(path) {
return /_spec\.js$/.test(path);
}
| JavaScript | 0.000052 | @@ -108,16 +108,55 @@
stem);%0A%0A
+jasmine.DEFAULT_TIMEOUT_INTERVAL = 50;%0A
%0A// Canc
|
627f4172cc0d1b650e7bdb0ecb53dd80fad49b4c | compress protocol check | moi.js | moi.js | /**
*
* @author Daniel McDonald
* @copyright Copyright 2014, biocore
* @credits Daniel McDonald, Joshua Shorenstein, Jose Navas
* @license BSD
* @version 0.1.0-dev
* @maintainer Daniel McDonald
* @email [email protected]
* @status Development
*
*/
/**
*
* @name moi
*
* @class manages WebSocket for job and group information
*
*/
var moi = new function () {
this.VERSION = '0.1.0-dev';
var
/* the server end of the websocket */
host = null,
/* the websocket */
ws = null,
/* registered callbacks */
callbacks = {},
/* the encode and decode methods used for communication */
encode = JSON.stringify,
decode = JSON.parse;
/**
*
* Registers a callback method for a given action
*
* @param {action} The associated action verb, str.
* @param {func} The associated function, function. This function must
* accept an object. Any return is ignored.
*
*/
this.add_callback = function(action, func) { callbacks[action] = func; };
/**
*
* Packages data into an object, and passes an encoded version of the
* object to the websocket.
*
* @param {action} The associated action to send, str.
* @param {data} The data to send, str or Array of str.
*/
this.send = function(action, data) {
to_send = {};
to_send[action] = data;
ws.send(encode(to_send));
};
/**
*
* Verify the browser supports websockets, and if so, initialize the
* websocket. On construction, this method will send a message over the
* socket to get all known job information associated with this client.
*
* @param {host} The URL for the websocket, minus the ws:// header, or null
* to use the default moi-ws.
* @param {group_id} A group ID to get initial data from, or null to fetch
* all records associated with the user.
* @param {on_open} Optional function for action when websocket is opened.
* @param {on_close} Optional function for action when websocket is closed.
* @param {on_error} Optional function for action when websocket errors.
*/
this.init = function(host, group_id, on_open, on_close, on_error) {
host = host || window.location.host + '/moi-ws/';
if (!("WebSocket" in window)) {
alert("Your browser does not appear to support websockets!");
return;
}
//check if we need regular or secure websocket
socket = 'ws://';
if(window.location.protocol == "https:") { socket = 'wss://'; }
ws = new WebSocket(socket + host);
var on_open_message = null;
if (group_id === null) {
on_open_message = [];
} else {
on_open_message = [group_id];
}
on_open = on_open || function() { ws.send(encode({"get": on_open_message})); };
on_close = on_close || function(evt) { ws.send(encode({"close": null})); };
on_error = on_error || function(evt) {};
ws.onopen = on_open;
ws.onclose = on_close;
ws.onerror = on_error;
ws.onmessage = function(evt) {
message = decode(evt.data);
for(var action in message) {
if(action in callbacks) {
callbacks[action](message[action]);
}
}
};
};
};
| JavaScript | 0.000001 | @@ -2523,28 +2523,8 @@
t =
-'ws://';%0A if(
wind
@@ -2559,32 +2559,30 @@
ps:%22
-) %7B socket =
+ ? 'wss://' :
'ws
-s
://';
- %7D
%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.