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
|
---|---|---|---|---|---|---|---|
976baeeb70d532a14ba1ec49c1dc849920ce1daa | function typo | src/experiment/index.js | src/experiment/index.js | import React, { PropTypes } from 'react';
import ls from 'local-storage';
export default class Experiment extends React.Component {
componentDidMount() {
console.log(this.props.name);
}
generateRandomIndex = max => Math.floor(Math.random() * max);
pickVariant = => {
const self = this;
const currentVariant = ls(`experiment_${self.props.name}`);
if (currentVariant) return currentVariant;
// no current variant for experient
// selecting new variant
const variantIndex = self.props.children ? self.generateRandomIndex(self.props.children.length) : self.generateRandomIndex(self.props.variants.length);
const variant = self.props.children ? self.props.children[variantIndex] : self.props.variants[variantIndex];
const variantName = variant.props.name;
if (!variantName) {
return {
error: 'Error: Variant component requires `name` property.'
};
}
ls.set(`experiment_${this.props.name}`, variantName);
return variant;
}
renderVariant = () => {
const self = this;
if (!self.props.children && !self.props.variants) {
console.error('Error: Experiment component requires minimum 1 child `variant`, or `variants` property passed an array of `variant` components.');
return false;
}
const variant = self.pickVariant();
if (variant.error) {
console.error(variant.error);
return false;
}
return React.cloneElement(
variant,
Object.assign(
{},
self.props.variantProps,
{
component: variant.props.component,
onVariantLoad: self.props.onVariantLoad ? self.props.onVariantLoad : false,
}
) || {}
);
}
render() {
return this.renderVariant();
}
}
| JavaScript | 0.999957 | @@ -272,16 +272,18 @@
riant =
+()
=%3E %7B%0A
|
dcf9a46cf5a4bfa130b831f65c98cfa87b02aaad | Test some more | src/extensions/guild.js | src/extensions/guild.js | const { Structures } = require('discord.js');
const Command = require('../commands/base');
const GuildSettingsHelper = require('../providers/helper');
module.exports = Structures.extend('Guild', Guild =>
/**
* A fancier Guild for fancier people.
* @class CommandoGuild
* @extends Guild
*/
class CommandoGuild extends Guild {
constructor(client, data) {
super(client, data);
/**
* Shortcut to use setting provider methods for this guild
* @type {GuildSettingsHelper}
*/
this.settings = new GuildSettingsHelper(this.client, this);
/**
* Internal command prefix for the guild, controlled by the {@link CommandoGuild#commandPrefix}
* getter/setter
* @name CommandoGuild#_commandPrefix
* @type {?string}
* @private
*/
this._commandPrefix = null;
}
/**
* Command prefix in the guild. An empty string indicates that there is no prefix, and only mentions will be used.
* Setting to `null` means that the prefix from {@link CommandoClient#commandPrefix} will be used instead.
* @type {string}
* @emits {@link CommandoClient#commandPrefixChange}
*/
get commandPrefix() {
if(this._commandPrefix === null) return this.client.commandPrefix;
return this._commandPrefix;
}
set commandPrefix(prefix) {
this._commandPrefix = prefix;
/**
* Emitted whenever a guild's command prefix is changed
* @event CommandoClient#commandPrefixChange
* @param {?Guild} guild - Guild that the prefix was changed in (null for global)
* @param {?string} prefix - New command prefix (null for default)
*/
this.client.emit('commandPrefixChange', this, this._commandPrefix);
}
/**
* Sets whether a command is enabled in the guild
* @param {CommandResolvable} command - Command to set status of
* @param {boolean} enabled - Whether the command should be enabled
*/
setCommandEnabled(command, enabled) {
command = this.client.registry.resolveCommand(command);
if(command.guarded) throw new Error('The command is guarded.');
if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
enabled = Boolean(enabled);
if(!this._commandsEnabled) {
/**
* Map object of internal command statuses, mapped by command name
* @type {Object}
* @private
*/
this._commandsEnabled = {};
}
this._commandsEnabled[command.name] = enabled;
/**
* Emitted whenever a command is enabled/disabled in a guild
* @event CommandoClient#commandStatusChange
* @param {?Guild} guild - Guild that the command was enabled/disabled in (null for global)
* @param {Command} command - Command that was enabled/disabled
* @param {boolean} enabled - Whether the command is enabled
*/
this.client.emit('commandStatusChange', this, command, enabled);
}
/**
* Checks whether a command is enabled in the guild (does not take the command's group status into account)
* @param {CommandResolvable} command - Command to check status of
* @return {boolean}
*/
isCommandEnabled(command) {
command = this.client.registry.resolveCommand(command);
if(command.guarded) return true;
if(!this._commandsEnabled || typeof this._commandsEnabled[command.name] === 'undefined') {
return command._globalEnabled;
}
return this._commandsEnabled[command.name];
}
/**
* Sets whether a command group is enabled in the guild
* @param {CommandGroupResolvable} group - Command to set status of
* @param {boolean} enabled - Whether the group should be enabled
*/
setGroupEnabled(group, enabled) {
group = this.client.registry.resolveGroup(group);
if(group.guarded) throw new Error('The group is guarded.');
if(typeof enabled === 'undefined') throw new TypeError('Enabled must not be undefined.');
enabled = Boolean(enabled);
if(!this._groupsEnabled) {
/**
* Internal map object of group statuses, mapped by group ID
* @type {Object}
* @private
*/
this._groupsEnabled = {};
}
this._groupsEnabled[group.id] = enabled;
/**
* Emitted whenever a command group is enabled/disabled in a guild
* @event CommandoClient#groupStatusChange
* @param {?Guild} guild - Guild that the group was enabled/disabled in (null for global)
* @param {CommandGroup} group - Group that was enabled/disabled
* @param {boolean} enabled - Whether the group is enabled
*/
this.client.emit('groupStatusChange', this, group, enabled);
}
/**
* Checks whether a command group is enabled in the guild
* @param {CommandGroupResolvable} group - Group to check status of
* @return {boolean}
*/
isGroupEnabled(group) {
group = this.client.registry.resolveGroup(group);
if(group.guarded) return true;
if(!this._groupsEnabled || typeof this._groupsEnabled[group.id] === 'undefined') return group._globalEnabled;
return this._groupsEnabled[group.id];
}
/**
* Creates a command usage string using the guild's prefix
* @param {string} [command] - A command + arg string
* @param {User} [user=this.client.user] - User to use for the mention command format
* @return {string}
*/
commandUsage(command, user = this.client.user) {
return Command.usage(command, this.commandPrefix, user);
}
}
);
| JavaScript | 0 | @@ -253,30 +253,16 @@
* @class
- CommandoGuild
%0A%09 * @ex
|
ba84e1ef5eed285915a65a89c861065c345c7f9e | remove content script - we should communicate with the panel directly. | src/firefox/lib/main.js | src/firefox/lib/main.js | var buttons = require('sdk/ui/button/action');
var panels = require("sdk/panel");
var self = require("sdk/self");
const {Cu} = require("chrome");
Cu.import(self.data.url('freedom-for-firefox.jsm'));
// Main uProxy button.
var button = buttons.ActionButton({
id: "uProxy-button",
label: "uProxy-button",
icon: {
"16": "./icons/uproxy-16.png",
"19": "./icons/uproxy-19.png",
"128": "./icons/uproxy-128.png"
},
onClick: start
});
var panel;
// Load freedom.
var manifest = self.data.url('core/freedom-module.json');
freedom(manifest, {}).then(function(interface) {
// Panel that gets displayed when user clicks the button.
panel = panels.Panel({
width: 371,
height: 600,
contentURL: self.data.url("polymer/popup.html"),
contentScriptFile: [
self.data.url("scripts/port.js"),
self.data.url("scripts/user.js"),
self.data.url("scripts/uproxy.js"),
self.data.url("scripts/ui.js"),
self.data.url("scripts/firefox_browser_api.js"),
self.data.url("scripts/firefox_connector.js"),
self.data.url("scripts/core_connector.js"),
self.data.url("scripts/background.js")],
contentScriptWhen: 'start'
})
// Set up connection between freedom and content script.
require('glue.js').setUpConnection(interface(), panel, button);
});
function start(state) {
panel.show({
position: button,
});
}
| JavaScript | 0 | @@ -754,430 +754,8 @@
ml%22)
-,%0A contentScriptFile: %5B%0A self.data.url(%22scripts/port.js%22),%0A self.data.url(%22scripts/user.js%22),%0A self.data.url(%22scripts/uproxy.js%22),%0A self.data.url(%22scripts/ui.js%22),%0A self.data.url(%22scripts/firefox_browser_api.js%22),%0A self.data.url(%22scripts/firefox_connector.js%22),%0A self.data.url(%22scripts/core_connector.js%22),%0A self.data.url(%22scripts/background.js%22)%5D,%0A contentScriptWhen: 'start'
%0A %7D
|
c9e73a2ceac928388b579a065ebeec83432aea07 | Revert "Fix use of no-flags/always-on-flag: 'js'" | src/foam/nanos/nanos.js | src/foam/nanos/nanos.js | /**
* @license
* Copyright 2017 The FOAM Authors. All Rights Reserved.
* http://www.apache.org/licenses/LICENSE-2.0
*/
FOAM_FILES([
{ name: "foam/nanos/auth/ChangePassword" },
{ name: "foam/nanos/auth/EnabledAware" },
{ name: "foam/nanos/auth/EnabledAwareInterface", flags: ['java'] },
{ name: "foam/nanos/auth/Group" },
{ name: "foam/nanos/auth/Language" },
{ name: "foam/nanos/auth/LastModifiedAware" },
{ name: "foam/nanos/auth/LastModifiedAwareInterface", flags:['java'] },
{ name: "foam/nanos/auth/LastModifiedByAware" },
{ name: "foam/nanos/auth/LastModifiedByAwareInterface", flags: ['java'] },
{ name: "foam/nanos/auth/Login" },
{ name: "foam/nanos/auth/Permission" },
{ name: "foam/nanos/auth/Country" },
{ name: "foam/nanos/auth/Region" },
{ name: "foam/nanos/auth/User" },
{ name: "foam/nanos/boot/NSpec" },
{ name: "foam/nanos/client/Client" },
{ name: "foam/nanos/log/LogLevel" },
{ name: "foam/nanos/log/Logger" },
{ name: "foam/nanos/log/ConsoleLogger" },
{ name: "foam/nanos/menu/Menu" },
{ name: "foam/nanos/script/Language" },
{ name: "foam/nanos/script/Script" },
{ name: "foam/nanos/test/Test" },
{ name: "foam/nanos/cron/Cron" },
{ name: "foam/nanos/export/ExportDriverRegistry"},
{ name: "foam/nanos/export/JSONDriver"},
{ name: "foam/nanos/export/XMLDriver"},
{ name: "foam/nanos/export/CSVDriver"},
{ name: "foam/nanos/auth/Relationships" },
{ name: "foam/nanos/NanoService" },
{ name: "foam/nanos/auth/AuthService" },
{ name: "foam/nanos/pm/PMInfo" }
]);
| JavaScript | 0 | @@ -208,32 +208,47 @@
th/EnabledAware%22
+, flags: %5B'js'%5D
%7D,%0A %7B name: %22f
@@ -423,24 +423,39 @@
difiedAware%22
+, flags: %5B'js'%5D
%7D,%0A %7B name
@@ -568,16 +568,31 @@
ByAware%22
+, flags: %5B'js'%5D
%7D,%0A %7B
|
dc8c982265a246a9b3c81e28f78dca4cf5418a0c | bump build number | src/front/app.config.js | src/front/app.config.js | import 'dotenv/config';
const baseBundleId = 'gov.dts.ugrc.utahwvcr';
const bundleIds = {
development: `${baseBundleId}.dev`,
staging: `${baseBundleId}.staging`,
production: baseBundleId,
};
const bundleId = bundleIds[process.env.ENVIRONMENT];
const names = {
development: 'WVC Reporter (Dev)',
staging: 'WVC Reporter (Staging)',
production: 'WVC Reporter',
};
const name = names[process.env.ENVIRONMENT];
const buildNumber = 527;
export default {
name,
slug: 'wildlife-vehicle-collision-reporter',
description: 'A mobile application for reporting and removing animal carcasses.',
scheme: bundleId,
facebookScheme: `fb${process.env.FACEBOOK_OAUTH_CLIENT_ID}`,
facebookAppId: process.env.FACEBOOK_OAUTH_CLIENT_ID,
facebookDisplayName: `Utah ${name}`,
githubUrl: 'https://github.com/agrc/roadkill-mobile',
version: '3.0.0',
orientation: 'portrait',
icon: process.env.ENVIRONMENT === 'production' ? './assets/icon.png' : `./assets/icon_${process.env.ENVIRONMENT}.png`,
splash: {
image:
process.env.ENVIRONMENT === 'production'
? './assets/splash.png'
: `./assets/splash_${process.env.ENVIRONMENT}.png`,
resizeMode: 'contain',
backgroundColor: '#ffffff',
},
updates: {
fallbackToCacheTimeout: 0,
},
assetBundlePatterns: ['**/*'],
jsEngine: 'hermes',
ios: {
bundleIdentifier: bundleId,
googleServicesFile: process.env.GOOGLE_SERVICES_IOS,
buildNumber: buildNumber.toString(),
supportsTablet: true,
config: {
usesNonExemptEncryption: false,
googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY_IOS,
},
infoPlist: {
NSLocationAlwaysUsageDescription:
'The app uses your location in the background for tracking routes. *Note* this is only applicable for agency employees or contractors. Background location is not used for public users.',
NSLocationWhenInUseUsageDescription:
'The app uses your location to help record the location of the animal that you are reporting.',
UIBackgroundModes: ['location'],
},
},
android: {
package: bundleId,
googleServicesFile: process.env.GOOGLE_SERVICES_ANDROID,
versionCode: buildNumber,
softwareKeyboardLayoutMode: 'pan',
adaptiveIcon: {
foregroundImage:
process.env.ENVIRONMENT === 'production'
? './assets/adaptive-icon.png'
: `./assets/adaptive-icon_${process.env.ENVIRONMENT}.png`,
backgroundColor: '#FFFFFF',
},
permissions: [
'ACCESS_FINE_LOCATION',
'ACCESS_COARSE_LOCATION',
'ACCESS_BACKGROUND_LOCATION',
'FOREGROUND_SERVICE',
'READ_EXTERNAL_STORAGE',
'WRITE_EXTERNAL_STORAGE',
],
config: {
googleMaps: {
apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID,
},
},
},
hooks: {
postPublish: [
{
file: 'sentry-expo/upload-sourcemaps',
config: {
organization: 'utah-ugrc',
project: 'roadkill',
authToken: process.env.SENTRY_AUTH_TOKEN,
},
},
],
},
plugins: [
'sentry-expo',
'expo-community-flipper',
[
'expo-image-picker',
{
photosPermission: 'The app accesses to your photos to allow you to submit a photo of the animal.',
cameraPermission: 'The app accesses your camera to allow you to capture and submit a photo of the animal.',
},
],
],
};
| JavaScript | 0.000001 | @@ -439,9 +439,9 @@
= 52
-7
+8
;%0A%0Ae
|
9c6b3259a95bf87140fbd352d4420157b008f3d9 | Update variable name. | apps/mp-votes/transcriptScraper/excel.js | apps/mp-votes/transcriptScraper/excel.js | var path = require('path');
var urlInfo = require('url');
var when = require('q');
var $ = require('cheerio');
var csv = require('../../../common/node/csv-util');
var Downloader = require('../../../common/node/downloader');
var Convertor = require('../../../common/node/spreadsheet2csv-node');
var Scraper = function(url, tempDir, logger) {
this.url = url;
this.baseUrl = urlInfo.parse(url);
this.baseUrl = this.baseUrl.protocol+'//'+this.baseUrl.host
this.tempDir = tempDir;
this.logger = loggerService;
this.downloader = new Downloader(logger);
this.convertor = new Convertor(logger);
}
Scraper.prototype = {
baseUrl: null,
url: null,
tempDir: null,
date: null,
logger: null,
convertor: null,
scrape: function() {
var self = this;
self.downloader.get(this.url, function(html) {
var $article = $('#leftcontent', html);
var $spreadsheets = $article.find('.frontList a[href$=".xls"]');
if ($spreadsheets.length==0) {
self.logger.info("Can't find XLS docs at: "+self.url)
return;
}
self.date = $article.find('.markframe .dateclass').text();
var topicsExtraction = when.defer();
var groupDownload = self.downloadAndConvert(
self.baseUrl+$spreadsheets.filter('[href*="gv"]').attr('href')
);
when.done(groupDownload, function(outputPath) {
topicsExtraction.resolve(self.extractTopicsFromGroupVotingCSV(outputPath))
});
var individualDownload = self.downloadAndConvert(self.baseUrl+$spreadsheets.filter('[href*="iv"]').attr('href'));
when.all([individualDownload, topicsExtraction.promise]).spread(self.extractIndividualVotesFromCSV)
})
},
downloadAndConvert: function(url) {
var self = this;
var task = when.defer();
var urlTokens = url.split('/');
var name = urlTokens[urlTokens.length-1];
var downloadPath = path.join(this.tempDir, name)
var outputPath = downloadPath.replace('.xls', '.csv');
self.downloader.save(url, downloadPath, function() {
self.convertor.convert(downloadPath, outputPath, function() {
task.resolve(outputPath);
})
})
return task.promise;
},
extractTopicsFromGroupVotingCSV: function(path) {
var task = when.defer();
var markers = {
registration: "РЕГИСТРАЦИЯ",
voteSplitter: "по тема",
vote: "ГЛАСУВАНЕ"
}
var getNum = function(title) {
var match = /Номер\s*\(?(\d+)\)?/.exec(title);
if (match!=null) return match[1];
return false;
}
var counter = 0;
var reg = false;
var topics = {
titlesByNum: {},
metadataByTitle: {},
isRegistration: function(topic) {
return topic == markers.registration
}
}
var reader = csv.readFile(path);
reader.on('record', function(row, i){
var title = row[0];
if (title.indexOf(markers.registration)==-1 && title.indexOf(markers.vote)==-1) return;
reg = title.indexOf(markers.registration)!=-1;
counter++;
var num = getNum(title) || counter;
var time = /\d+-\d+-\d+\s+\d+:\d+/.exec(title)
time = time == null ? time : time[0]
title = reg ? markers.registration : title.split(markers.voteSplitter)[1].trim();
topics.titlesByNum[num] = title;
topics.metadataByTitle[title] = {
"time": time
};
})
reader.on('end', function(){task.resolve(topics);})
return task.promise;
},
/**
* Processes CSV and forms
* @param path
* @param topics
*/
extractIndividualVotesFromCSV: function(path, topics) {
var self = this;
var headers = []
var valueMapping = {
"П": 'present',
'О': 'absent',
"Р": 'manually_registered',
'+': 'yes',
'-': 'no',
'=': 'abstain',
'0': 'absent'
}
var reader = csv.readFile(path)
reader.on('record', function(row, i) {
if (i<1) return;
if (i==1) {
headers = row;
return;
}
var record = {
date: self.date,
votes: []
}
row.forEach(function(val, i) {
if (i==0 && val!='') {
record.name = val;
}
if (val=='' || i < 4) return;
var topic = topics.titlesByNum[headers[i]]
var entry = {
time: topics.metadataByTitle[topic].time,
val: valueMapping[val]
}
if (topics.isRegistration(topic)) {
record.registration = entry
} else {
record.votes.push(entry)
}
})
console.log(JSON.stringify(record))
})
}
}
exports = module.exports = Scraper;
| JavaScript | 0 | @@ -501,15 +501,8 @@
gger
-Service
;%0A%09t
|
fdc4d2e9beb72fcdca745c23a724351ad9d48f32 | Update simple-table.js | addon/components/simple-table.js | addon/components/simple-table.js | import Ember from 'ember';
import layout from '../templates/components/simple-table';
const { A: emberA, computed, get, set, isEmpty } = Ember;
export default Ember.Component.extend({
layout,
tagName: 'table',
defaultSorting: null, // injected
sortingCriteria: computed('tColumns', {
get() {
let columns = this.get('tColumns');
return columns.reduce((reducer, item) => {
if (Ember.isArray(item)) {
item.forEach((i) => {
reducer.pushObject({ key: i.key, name: i.name, order: null });
});
} else {
reducer.pushObject({ key: item.key, name: item.name, order: null });
}
return reducer;
}, emberA([]));
}
}),
sorting: computed('sortingCriteria.[]', 'tData.[]', {
get() {
let sortingCriteria = this.get('sortingCriteria')
.filterBy('order')
.map(({ key, order }) => `${key}:${order}`);
let defaultSorting = get(this, 'defaultSorting');
if (! isEmpty(defaultSorting)) {
sortingCriteria.push(defaultSorting);
}
return sortingCriteria;
}
}),
tRows: computed.sort('tData', 'sorting'),
actions: {
sortBy(key) {
let sortAction = get(this, 'sortAction');
this._setOrderForColumn(key);
if (sortAction) {
let criteria = get(this, 'sortingCriteria');
sortAction(criteria);
}
},
removeSortOption(item) {
let sortCriteria = get(this, 'sortingCriteria');
let oldCriteria = sortCriteria.find(({ key }) => key === get(item, 'key'));
sortCriteria.removeObject(oldCriteria);
set(oldCriteria, 'order', null);
sortCriteria.pushObject(oldCriteria);
},
reorderCriteria(newOrder) {
let criteria = get(this, 'sortingCriteria');
let reordered = newOrder.map((item) => {
return criteria.find(({ key }) => key === get(item, 'key'));
});
criteria.removeObjects(reordered);
criteria.pushObjects(reordered);
}
},
_setOrderForColumn(sortingKey) {
let oldPosition = null;
let criteria = get(this, 'sortingCriteria');
let oldCriteria = criteria.find(({ key }) => key === sortingKey);
let oldOrder = get(oldCriteria, 'order');
// Save oldPosition only if we already sorted by this column previously
if (oldOrder) {
oldPosition = criteria.indexOf(oldCriteria);
}
criteria.removeObject(oldCriteria);
let newOrder = this._toggleSortingOrder(oldOrder);
set(oldCriteria, 'order', newOrder);
if (oldPosition !== null) {
criteria.insertAt(oldPosition, oldCriteria);
} else {
criteria.pushObject(oldCriteria);
}
console.log(this.get('sorting'));
},
_toggleSortingOrder(order) {
switch(order) {
case null:
return 'asc';
case 'asc':
return 'desc';
case 'desc':
return null;
default:
return 'asc';
}
}
});
| JavaScript | 0 | @@ -766,16 +766,32 @@
ata.%5B%5D',
+ defaultSorting,
%7B%0A g
|
6f16dba6316412f4b2f6c4bda200fe966b6c14b7 | Update Committee.js | src/components/Home/Committees/Committee.js | src/components/Home/Committees/Committee.js | import React from 'react';
function Committee(props){
return (
<a
className={`committee ${props.committee.class}`}
target="_blank" rel="noreferrer noopener"
href={props.committee.links.main}
>
<img src={process.env.PUBLIC_URL + props.committee.image} alt={`Logo and Wordmark for ACM ${props.committee.name}`} />
<div className="info">
{/* <h2><span>ACM</span> {props.committee.name}</h2> */}
<p>{props.committee.tagline}</p>
</div>
</a>
);
}
export default Committee; | JavaScript | 0.000001 | @@ -195,14 +195,8 @@
link
-s.main
%7D %0A%09
|
28bad0fa0110853130b9f65f0f60a71ede34c51c | Update moment-from-now.js | addon/helpers/moment-from-now.js | addon/helpers/moment-from-now.js | import Ember from 'ember';
import moment from 'moment';
const { later:runLater } = Ember.run;
export var helperFactory = function(cb) {
let ago;
if (Ember.Helper) {
ago = Ember.Helper.extend({
compute: function(params, hash) {
if (typeof cb === 'function') {
cb();
}
if (params.length === 0) {
throw new TypeError('Invalid Number of arguments, expected at least 1');
}
if (hash.interval) {
runLater(this, this.recompute, hash.interval);
}
return moment.apply(this, params).fromNow();
}
});
}
else {
ago = function(params) {
if (typeof cb === 'function') {
cb();
}
if (params.length === 0) {
throw new TypeError('Invalid Number of arguments, expected at least 1');
}
return moment.apply(this, params).fromNow();
};
}
return ago;
};
export default helperFactory();
| JavaScript | 0 | @@ -501,16 +501,25 @@
ompute,
+parseInt(
hash.int
@@ -523,16 +523,21 @@
interval
+, 10)
);%0A
|
9468a17a124b45f57b4331e2b53efa277755b9f9 | Update agent-stats-group-badges.user.js | agent-stats-group-badges.user.js | agent-stats-group-badges.user.js | // ==UserScript==
// @name Agent Stats Group Badges
// @namespace https://github.com/finntaur/monkey
// @version 0.1.201505190200
// @description Colorize group view cells in Agent Stats based on related badges.
// @include https://www.agent-stats.com/groups.php*
// @include http://www.agent-stats.com/groups.php*
// @match https://www.agent-stats.com/groups.php*
// @match http://www.agent-stats.com/groups.php*
// @grant none
// @copyright 2015+, Finntaur
// @require http://code.jquery.com/jquery-latest.js
// ==/UserScript==
var colors = new Array("#511d06", "#364142", "#744d22", "#282828", "#000000");
var requirements = [
[100, 1000, 2000, 10000, 30000], // Explorer
[10, 50, 200, 500, 5000], // Seer
[10, 100, 300, 1000, 2500], // Trekker
[2000, 10000, 30000, 100000, 200000], // Builder
[50, 1000, 5000, 25000, 100000], // Connector
[100, 500, 2000, 10000, 40000], // Mind-Controller
[5000, 50000, 250000, 1000000, 4000000], // Illuminator
[100000, 1000000, 3000000, 10000000, 25000000], // Recharger
[100, 1000, 5000, 15000, 40000], // Liberator
[20, 200, 1000, 5000, 20000], // Pioneer
[150, 1500, 5000, 20000, 50000], // Engineer
[2000, 10000, 30000, 100000, 300000], // Purifier
[3, 10, 20, 90, 150], // Guardian
[5, 25, 100, 200, 500], // SpecOps
[2000, 10000, 30000, 100000, 200000], // Hacker
[200, 2000, 6000, 20000, 50000], // Translator
[15, 30, 60, 180, 360], // Sojourner
[2, 10, 25, 50, 100] // Recruiter
];
$("#group > tbody > tr").each(function(i, tr){
$("td", tr).each(function(j, td){
if ( 4 <= j && j <= 21 ) {
var value = parseInt($(td).html().replace(/,/g, ""));
var color = "";
for ( var k = 4 ; 0 <= k ; k-- ) {
if ( requirements[j-4][k] <= value ) {
color = colors[k];
break;
}
}
if ( "" == color ) {
$(td).css("background", "repeating-linear-gradient(-45deg, #000000, #000000 5px, #002d2b 5px, #002d2b 10px)");
} else {
$(td).css("background-color", color);
}
}
});
});
| JavaScript | 0 | @@ -127,16 +127,16 @@
.201
-50519020
+60408125
0%0A//
@@ -1345,16 +1345,54 @@
SpecOps%0A
+ %5B1, 3, 6, 10, 20%5D, // Mission Day%0A
%5B200
@@ -1684,17 +1684,17 @@
& j %3C= 2
-1
+2
) %7B%0A
|
afd636d174638de7035e1da70a327ff319d330f8 | Fix bug that stopped apps from displaying | ui/src/hosts/components/HostsTable.js | ui/src/hosts/components/HostsTable.js | import React, {PropTypes} from 'react';
import {Link} from 'react-router';
import _ from 'lodash';
const HostsTable = React.createClass({
propTypes: {
hosts: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
cpu: PropTypes.number,
load: PropTypes.number,
apps: PropTypes.arrayOf(PropTypes.string.isRequired),
})),
source: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
}).isRequired,
},
getInitialState() {
return {
searchTerm: '',
sortDirection: null,
sortKey: null,
};
},
filter(allHosts, searchTerm) {
return allHosts.filter((h) => {
const apps = h.apps ? h.apps.join(', ') : '';
// search each tag for the presence of the search term
let tagResult = false;
if (h.tags) {
tagResult = Object.keys(h.tags).reduce((acc, key) => {
return acc || h.tags[key].search(searchTerm) !== -1;
}, false);
} else {
tagResult = false;
}
return (
h.name.search(searchTerm) !== -1 ||
apps.search(searchTerm) !== -1 ||
tagResult
);
});
},
sort(hosts, key, direction) {
switch (direction) {
case 'asc':
return _.sortBy(hosts, (e) => e[key]);
case 'desc':
return _.sortBy(hosts, (e) => e[key]).reverse();
default:
return hosts;
}
},
updateSearchTerm(term) {
this.setState({searchTerm: term});
},
updateSort(key) {
// if we're using the key, reverse order; otherwise, set it with ascending
if (this.state.sortKey === key) {
const reverseDirection = (this.state.sortDirection === 'asc' ? 'desc' : 'asc');
this.setState({sortDirection: reverseDirection});
} else {
this.setState({sortKey: key, sortDirection: 'asc'});
}
},
sortableClasses(key) {
if (this.state.sortKey === key) {
if (this.state.sortDirection === 'asc') {
return "sortable-header sorting-up";
}
return "sortable-header sorting-down";
}
return "sortable-header";
},
render() {
const {searchTerm, sortKey, sortDirection} = this.state;
const {hosts, source} = this.props;
const sortedHosts = this.sort(this.filter(hosts, searchTerm), sortKey, sortDirection);
const hostCount = sortedHosts.length;
let hostsTitle;
if (hostCount === 1) {
hostsTitle = `${hostCount} Host`;
} else if (hostCount > 1) {
hostsTitle = `${hostCount} Hosts`;
} else {
hostsTitle = `Loading Hosts...`;
}
return (
<div className="panel panel-minimal">
<div className="panel-heading u-flex u-ai-center u-jc-space-between">
<h2 className="panel-title">{hostsTitle}</h2>
<SearchBar onSearch={this.updateSearchTerm} />
</div>
<div className="panel-body">
<table className="table v-center">
<thead>
<tr>
<th onClick={() => this.updateSort('name')} className={this.sortableClasses('name')}>Hostname</th>
<th className="text-center">Status</th>
<th onClick={() => this.updateSort('cpu')} className={this.sortableClasses('cpu')}>CPU</th>
<th onClick={() => this.updateSort('load')} className={this.sortableClasses('load')}>Load</th>
<th>Apps</th>
</tr>
</thead>
<tbody>
{
sortedHosts.map((h) => {
return <HostRow key={h.name} host={h} source={source} />;
})
}
</tbody>
</table>
</div>
</div>
);
},
});
const HostRow = React.createClass({
propTypes: {
source: PropTypes.shape({
id: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
}).isRequired,
host: PropTypes.shape({
name: PropTypes.string,
cpu: PropTypes.number,
load: PropTypes.number,
apps: PropTypes.arrayOf(PropTypes.string.isRequired),
}),
},
shouldComponentUpdate(nextProps) {
return this.props.host !== nextProps.host;
},
render() {
const {host, source} = this.props;
const {name, cpu, load, apps = []} = host;
return (
<tr>
<td className="monotype"><Link to={`/sources/${source.id}/hosts/${name}`}>{name}</Link></td>
<td className="text-center"><div className="table-dot dot-success"></div></td>
<td className="monotype">{isNaN(cpu) ? 'N/A' : `${cpu.toFixed(2)}%`}</td>
<td className="monotype">{isNaN(load) ? 'N/A' : `${load.toFixed(2)}`}</td>
<td className="monotype">
{apps.map((app, index) => {
return (
<span key={app}>
<Link
style={{marginLeft: "2px"}}
to={{pathname: `/sources/${source.id}/hosts/${name}`, query: {app}}}>
{app}
</Link>
{index === apps.length - 1 ? null : ', '}
</span>
);
})}
</td>
</tr>
);
},
});
const SearchBar = React.createClass({
propTypes: {
onSearch: PropTypes.func.isRequired,
},
getInitialState() {
return {
searchTerm: '',
};
},
componentWillMount() {
const waitPeriod = 300;
this.handleSearch = _.debounce(this.handleSearch, waitPeriod);
},
handleSearch() {
this.props.onSearch(this.state.searchTerm);
},
handleChange() {
this.setState({searchTerm: this.refs.searchInput.value}, this.handleSearch);
},
render() {
return (
<div className="users__search-widget input-group">
<input
type="text"
className="form-control"
placeholder="Filter by Hostname..."
ref="searchInput"
onChange={this.handleChange}
/>
<div className="input-group-addon">
<span className="icon search" aria-hidden="true"></span>
</div>
</div>
);
},
});
export default HostsTable;
| JavaScript | 0.000001 | @@ -33,16 +33,75 @@
react';%0A
+import shallowCompare from 'react-addons-shallow-compare';%0A
import %7B
@@ -4173,27 +4173,28 @@
urn
-this.props.host !==
+shallowCompare(this,
nex
@@ -4203,13 +4203,9 @@
rops
-.host
+)
;%0A
@@ -4307,16 +4307,17 @@
= host;%0A
+%0A
retu
|
ce3a96189a791cfb3c4d834105bcd47790f1d443 | use path module instead of regex and string concat | es6-website/Brocfile.js | es6-website/Brocfile.js | // Babel transpiler
var babel = require('broccoli-babel-transpiler');
// filter trees (subsets of files)
var funnel = require('broccoli-funnel');
// concatenate trees
var concat = require('broccoli-concat');
// merge trees
var mergeTrees = require('broccoli-merge-trees');
// Transpile the source files
var appJs = babel('src');
// Grab the polyfill file provided by the Babel library
var babelPath = require.resolve('broccoli-babel-transpiler');
babelPath = babelPath.replace(/\/index.js$/, '');
babelPath += '/node_modules/babel-core';
var browserPolyfill = funnel(babelPath, {
files: ['browser-polyfill.js']
});
// Add the Babel polyfill to the tree of transpiled files
appJs = mergeTrees([browserPolyfill, appJs]);
// Concatenate all the JS files into a single file
appJs = concat(appJs, {
// we specify a concatenation order
inputFiles: ['browser-polyfill.js', '**/*.js'],
outputFile: '/js/my-app.js'
});
// Grab the index file
var index = funnel('src', {files: ['index.html']});
// Grab all our trees and
// export them as a single and final tree
module.exports = mergeTrees([index, appJs]);
| JavaScript | 0 | @@ -1,8 +1,59 @@
+// Node path module%0Aconst path = require('path');%0A%0A
// Babel
@@ -371,24 +371,80 @@
el('src');%0A%0A
+// Grab the polyfill file provided by the Babel library%0A
// Grab the
@@ -565,43 +565,30 @@
h =
-babelPath.replace(/%5C/index.js$/, ''
+path.dirname(babelPath
);%0Ab
@@ -600,10 +600,30 @@
ath
-+
=
+ path.join(babelPath,
'/n
@@ -645,16 +645,17 @@
el-core'
+)
;%0Avar br
@@ -690,18 +690,17 @@
Path, %7B%0A
-
+%09
files: %5B
|
6b7e95cf9e6e51622bf9473132e44a8d4d51945c | Improve messaging for first time account creation flow. | events/createAccount.js | events/createAccount.js | 'use strict';
/**
* Create an account
* Stages:
*
* done: This is always the end step, here we register them in with
* the rest of the logged in players and where they log in
*
* @param object arg This is either a Socket or a Player depending on
* the stage.
* @param string stage See above
* @param name account username
* @param account player account obj
*/
const util = require('util');
const src = '../src/';
const Account = require(src + 'accounts').Account;
const EventUtil = require('./event_util').EventUtil;
exports.event = (players, items, rooms, npcs, accounts, l10n) =>
function createAccount(socket, stage, name, account) {
const say = EventUtil.gen_say(socket);
stage = stage || 'check';
l10n.setLocale('en');
const next = EventUtil.gen_next('createAccount');
const repeat = EventUtil.gen_repeat(arguments, next);
switch (stage) {
case 'check':
let newAccount = null;
socket.write('No such account exists.\r\n');
say('<bold>Do you want your account\'s username to be ' + name + '?</bold> <cyan>[y/n]</cyan> ');
socket.once('data', data => {
if (!EventUtil.isNegot(data)) {
next(socket, 'createAccount', name, null);
return;
}
data = data.toString('').trim();
if (data[0] === 0xFA) {
return repeat();
}
const firstLetter = data[0].toLowerCase();
if (data && firstLetter === 'y') {
socket.write('Creating account...\r\n');
newAccount = new Account();
newAccount.setUsername(name);
newAccount.setSocket(socket);
return next(socket, 'password', name, newAccount);
} else if (data && data === 'n') {
socket.write('Goodbye!\r\n');
return socket.end();
} else {
return repeat();
}
});
break;
//TODO: Validate password creation.
case 'password':
socket.write('Enter your account password: ');
socket.once('data', pass => {
pass = pass.toString().trim();
if (!pass) {
socket.write('You must use a password.\r\n');
return repeat();
}
if (pass.length <= 5) {
socket.write('Your password must be 6 characters or longer.\r\n');
return repeat();
}
if (pass.length > 30) {
socket.write('Your password must be less than or equal to 30 characters.\r\n');
return repeat();
}
// setPassword handles hashing
account.setPassword(pass);
accounts.addAccount(account);
account.getSocket()
.emit('createPlayer', account.getSocket(), 'name', account, null);
});
break;
}
};
| JavaScript | 0 | @@ -2062,16 +2062,74 @@
.write('
+Your password must be between 6 and 30 characters.%5Cn%3Ccyan%3E
Enter yo
@@ -2148,16 +2148,23 @@
assword:
+%3C/cyan%3E
');%0A
|
4312d7f54d09cdc33ebd071ef2c06c62b4a191f8 | remove user report case from moderationLog event | events/moderationLog.js | events/moderationLog.js | /**
* @file moderationLog event
* @author Sankarsan Kampa (a.k.a k3rn31p4nic)
* @license GPL-3.0
*/
/**
* @param {Message} message The message that fired this moderation action
* @param {string} action The moderation action's name
* @param {User|Channel} target The target on which this action was taken
* @param {string} reason The reason for the moderation action
* @param {object} extras An object containing any extra data of the moderation action
* @returns {void}
*/
module.exports = async (message, action, target, reason, extras) => {
try {
let guild = message.guild;
let executor = message.author;
let guildModel = await message.client.database.models.guild.findOne({
attributes: [ 'moderationLog', 'moderationCaseNo' ],
where: {
guildID: guild.id
}
});
if (!guildModel || !guildModel.dataValues.moderationLog) return;
let modLogChannel = guild.channels.get(guildModel.dataValues.moderationLog);
if (!modLogChannel) return;
let modCaseNo = parseInt(guildModel.dataValues.moderationCaseNo), color,
logData = [
{
name: 'User',
value: `${target}`,
inline: true
},
{
name: 'User ID',
value: target.id,
inline: true
},
{
name: 'Reason',
value: reason || 'No reason given'
},
{
name: 'Responsible Moderator',
value: `${executor}`,
inline: true
},
{
name: 'Moderator ID',
value: executor.id,
inline: true
}
];
switch (action.toLowerCase()) {
case 'addrole':
action = message.client.i18n.event(guild.language, 'addRole');
color = message.client.colors.GREEN;
logData.unshift(
{
name: 'Role',
value: extras.role.name
}
);
break;
case 'ban':
action = message.client.i18n.event(guild.language, 'guildBanAdd');
color = message.client.colors.RED;
break;
case 'clear':
action = message.client.i18n.event(guild.language, 'messageClear');
color = message.client.colors.RED;
logData.splice(0, 3,
{
name: 'Channel',
value: `${target}`,
inline: true
},
{
name: 'Channel ID',
value: target.id,
inline: true
},
{
name: 'Cleared',
value: extras.cleared
}
);
break;
case 'deafen':
action = message.client.i18n.event(guild.language, 'deafAdd');
color = message.client.colors.ORANGE;
break;
case 'kick':
action = message.client.i18n.event(guild.language, 'kick');
color = message.client.colors.RED;
break;
case 'mute':
action = message.client.i18n.event(guild.language, 'voiceMuteAdd');
color = message.client.colors.ORANGE;
break;
/*
case 'nickname':
action = 'Updated User Nickname';
color = message.client.colors.ORANGE;
logData.push();
break;
*/
case 'removeallroles':
action = message.client.i18n.event(guild.language, 'removeAllRole');
color = message.client.colors.RED;
break;
case 'removerole':
action = message.client.i18n.event(guild.language, 'removeRole');
color = message.client.colors.RED;
logData.unshift(
{
name: 'Role',
value: extras.role.name
}
);
break;
case 'report':
action = message.client.i18n.event(guild.language, 'userReport');
color = message.client.colors.ORANGE;
logData.splice(logData.length - 2, 2,
{
name: 'Reporter',
value: `${executor}`,
inline: true
},
{
name: 'Reporter ID',
value: executor.id,
inline: true
}
);
break;
case 'softban':
action = message.client.i18n.event(guild.language, 'userSoftBan');
color = message.client.colors.RED;
break;
case 'textmute':
action = message.client.i18n.event(guild.language, 'textMuteAdd');
color = message.client.colors.ORANGE;
logData.splice(logData.length - 2, 0,
{
name: 'Channel',
value: `${extras.channel}`
}
);
break;
case 'textunmute':
action = message.client.i18n.event(guild.language, 'textMuteRemove');
color = message.client.colors.GREEN;
logData.splice(logData.length - 2, 0,
{
name: 'Channel',
value: `${extras.channel}`
}
);
break;
case 'unban':
action = message.client.i18n.event(guild.language, 'guildBanRemove');
color = message.client.colors.GREEN;
break;
case 'undeafen':
action = message.client.i18n.event(guild.language, 'deafRemove');
color = message.client.colors.GREEN;
break;
case 'unmute':
action = message.client.i18n.event(guild.language, 'voiceMuteRemove');
color = message.client.colors.GREEN;
break;
case 'warn':
action = message.client.i18n.event(guild.language, 'userWarnAdd');
color = message.client.colors.ORANGE;
break;
case 'clearwarn':
action = message.client.i18n.event(guild.language, 'userWarnRemove');
color = message.client.colors.GREEN;
break;
default:
return message.client.log.error(`Moderation logging is not present for ${action} action.`);
}
let modLogMessage = await modLogChannel.send({
embed: {
color: color,
title: action,
fields: logData,
footer: {
text: `Case Number: ${modCaseNo}`
},
timestamp: new Date()
}
});
await message.client.database.models.moderationCase.create({
guildID: guild.id,
number: modCaseNo,
messageID: modLogMessage.id
},
{
fields: [ 'guildID', 'number', 'messageID' ]
});
await message.client.database.models.guild.update({
moderationCaseNo: modCaseNo + 1
},
{
where: {
guildID: guild.id
},
fields: [ 'moderationCaseNo' ]
});
}
catch (e) {
message.client.log.error(e);
}
};
| JavaScript | 0.000002 | @@ -3658,450 +3658,8 @@
k;%0A%0A
- case 'report':%0A action = message.client.i18n.event(guild.language, 'userReport');%0A color = message.client.colors.ORANGE;%0A logData.splice(logData.length - 2, 2,%0A %7B%0A name: 'Reporter',%0A value: %60$%7Bexecutor%7D%60,%0A inline: true%0A %7D,%0A %7B%0A name: 'Reporter ID',%0A value: executor.id,%0A inline: true%0A %7D%0A );%0A break;%0A%0A
|
15b1e905e6404c6b77fd13b3b43419559fcec33d | Remove console log statements | src/helpers/reformat.js | src/helpers/reformat.js | import flatten from 'flat';
export function reformatColumns(items) {
const flatList = items.map((item) => flatten(item, { maxDepth: 2 }));
const reformattedList = rotateOnTeam(flatList);
const itemsByFeature = groupByFeature(reformattedList);
const concatObj = concatOnProperties(reformattedList);
const concatList = convertToList(concatObj);
console.log({ concatObj });
console.log('Output:', concatList);
return concatList;
}
function rotateOnTeam(list) {
// convert columns
const rotatedList = list.map((item) => ({
...item,
// Put the hours in the right column
[item['budgetHours.column']]: item['budgetHours.value'],
}));
return rotatedList;
}
function groupByFeature(reformattedList) {
const itemsByFeature = reformattedList.reduce((features, item) => {
features[item.feature] = [
...features[item.feature] || [],
item,
];
return features;
}, {});
return itemsByFeature;
}
function concatOnProperties(list) {
let concatObj = {};
// combine on feature
list.map((item) => {
// Feature isn't already in the object
if (typeof concatObj[item.feature] === 'undefined') {
concatObj[item.feature] = item;
} else {
// Add to existing feature
for (const property in item) {
if(Array.isArray(item[property])) {
concatObj[item.feature][property] = [
...concatObj[item.feature][property],
...item[property],
];
} else if(typeof item[property] === 'number') {
// Sum the numbers
concatObj[item.feature][property] = concatObj[item.feature][property] + item[property] || item[property];
}
}
}
});
return concatObj;
}
// convert concatObj from properties to array elements
function convertToList(object) {
let list = [];
for (const element in object) {
list = [...list, object[element]];
}
return list;
} | JavaScript | 0.000002 | @@ -350,76 +350,8 @@
);%0A%0A
-%09console.log(%7B concatObj %7D);%0A%0A%09console.log('Output:', concatList);%0A%0A
%09ret
|
15b403a7c05d6bb4c58b3cb173d772a4e5ee59ed | Update InMemoryDriver.js | src/deep-cache/lib/Driver/InMemoryDriver.js | src/deep-cache/lib/Driver/InMemoryDriver.js | /**
* Created by AlexanderC on 6/16/15.
*/
'use strict';
import {AbstractDriver} from './AbstractDriver';
/**
* In memory driver implementation
*/
export class InMemoryDriver extends AbstractDriver {
constructor() {
super();
this._storage = {};
}
/**
* @returns {Object}
*/
get storage() {
return this._storage;
}
/**
* @param {String} key
* @param {Function} callback
*/
_has(key, callback = () => {}) {
if (!this._storage.hasOwnProperty(key) || this._storage[key][1] === false) {
callback(null, false);
return;
}
let result = this._storage[key][1] < InMemoryDriver._now;
if (!result) {
this._invalidate(key);
callback(null, false);
return;
}
callback(null, result);
}
/**
* @param {String} key
* @param {Function} callback
*/
_get(key, callback = () => {}) {
callback(null, this._storage[key]);
}
/**
* @param {String} key
* @param {*} value
* @param {Number} ttl
* @param {Function} callback
* @returns {Boolean}
*/
_set(key, value, ttl = 0, callback = () => {}) {
this._storage[key] = [value, ttl <= 0 ? false : (InMemoryDriver._now + ttl)];
callback(null, true);
}
/**
* @param {String} key
* @param {Number} timeout
* @param {Function} callback
*/
_invalidate(key, timeout = 0, callback = () => {}) {
if (timeout <= 0) {
delete this._storage[key];
callback(null, true);
return;
}
this._storage[key][1] = InMemoryDriver._now + timeout;
callback(null, true);
}
/**
* @param {Function} callback
* @returns {AbstractDriver}
*/
_flush(callback = () => {}) {
this._storage = {};
callback(null, true);
}
/**
* @returns {Number}
* @private
*/
static get _now() {
return new Date().getTime();
}
}
| JavaScript | 0 | @@ -589,21 +589,23 @@
let
-resul
+timedOu
t = this
@@ -658,14 +658,15 @@
if (
-!resul
+timedOu
t) %7B
@@ -770,14 +770,12 @@
ll,
-result
+true
);%0A
|
d5512bcf6757954a96522a53a878640687402bce | Fix delayed re-render promise resolution | packages/second-renderer/src/index.js | packages/second-renderer/src/index.js | import Promise from 'bluebird'
import debug from 'debug'
const INITIAL_RERENDER_DELAY = 100
const log = debug('second:renderer')
export default class Renderer {
constructor ({ VDom, VDomServer, componentIsReady = () => true }) {
this.VDom = VDom
this.VDomServer = VDomServer
this.componentIsReady = componentIsReady
}
reset () {
this._reRenderDelay = INITIAL_RERENDER_DELAY
}
render (Component, params) {
this.reset()
return this.renderUntilComplete(
this.VDomServer.renderToString,
Component,
params
)
}
renderStatic (Component, params) {
this.reset()
return this.renderUntilComplete(
this.VDomServer.renderToStaticMarkup,
Component,
params
)
}
renderUntilComplete (render, Component, params) {
log(`Starting render of ${Component.displayName}`)
const delayTime = this.reRenderDelay()
return new Promise((resolve, reject) => {
const rendered = render(
this.VDom.createElement(Component, params)
)
if (!this.componentIsReady()) {
log(`Component is not ready. Trying again in ${delayTime}ms.`)
return Promise.delay(delayTime).then(() => this.renderUntilComplete(render, Component, params))
}
log(`Completed render of ${Component.displayName}`)
resolve(rendered)
}).catch(e => {
if (!this.componentIsReady()) {
log(`Error thrown by ${Component.displayName}, but component is not ready. Trying again in ${delayTime}ms.`)
return Promise.delay(delayTime).then(() => this.renderUntilComplete(render, Component, params))
}
throw e
})
}
reRenderDelay () {
const delay = this._reRenderDelay
this._reRenderDelay = Math.ceil(this._reRenderDelay * 1.1)
return delay
}
}
| JavaScript | 0.000001 | @@ -1140,37 +1140,38 @@
s.%60)%0A%0A re
-turn
+solve(
Promise.delay(de
@@ -1234,32 +1234,33 @@
ponent, params))
+)
%0A %7D%0A%0A
@@ -1311,16 +1311,17 @@
Name%7D%60)%0A
+%0A
re
|
ddd8260e4b49c178640a0e3314627c1bb5d8f70e | Update deprecation wording to be less aggressive | src/isomorphic/React.js | src/isomorphic/React.js | /**
* Copyright 2013-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule React
*/
'use strict';
var ReactChildren = require('ReactChildren');
var ReactComponent = require('ReactComponent');
var ReactPureComponent = require('ReactPureComponent');
var ReactClass = require('ReactClass');
var ReactDOMFactories = require('ReactDOMFactories');
var ReactElement = require('ReactElement');
var ReactPropTypes = require('ReactPropTypes');
var ReactVersion = require('ReactVersion');
var onlyChild = require('onlyChild');
var warning = require('warning');
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
var cloneElement = ReactElement.cloneElement;
if (__DEV__) {
var canDefineProperty = require('canDefineProperty');
var ReactElementValidator = require('ReactElementValidator');
var didWarnPropTypesDeprecated = false;
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
cloneElement = ReactElementValidator.cloneElement;
}
var __spread = Object.assign;
var createMixin = function(mixin) {
return mixin;
};
if (__DEV__) {
var warnedForSpread = false;
var warnedForCreateMixin = false;
__spread = function() {
warning(
warnedForSpread,
'React.__spread is deprecated and should not be used. Use ' +
'Object.assign directly or another helper function with similar ' +
'semantics. You may be seeing this warning due to your compiler. ' +
'See https://fb.me/react-spread-deprecation for more details.'
);
warnedForSpread = true;
return Object.assign.apply(null, arguments);
};
createMixin = function(mixin) {
warning(
warnedForCreateMixin,
'React.createMixin is deprecated and should not be used. You ' +
'can use your mixin directly instead.'
);
warnedForCreateMixin = true;
return mixin;
};
}
var React = {
// Modern
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
toArray: ReactChildren.toArray,
only: onlyChild,
},
Component: ReactComponent,
PureComponent: ReactPureComponent,
createElement: createElement,
cloneElement: cloneElement,
isValidElement: ReactElement.isValidElement,
// Classic
PropTypes: ReactPropTypes,
createClass: ReactClass.createClass,
createFactory: createFactory,
createMixin: createMixin,
// This looks DOM specific but these are actually isomorphic helpers
// since they are just generating DOM strings.
DOM: ReactDOMFactories,
version: ReactVersion,
// Deprecated hook for JSX spread, don't use this for anything.
__spread: __spread,
};
// TODO: Fix tests so that this deprecation warning doesn't cause failures.
if (__DEV__) {
if (canDefineProperty) {
Object.defineProperty(React, 'PropTypes', {
get() {
warning(
didWarnPropTypesDeprecated,
'Accessing PropTypes via the main React package is deprecated. Use ' +
'the prop-types package from npm instead.'
);
didWarnPropTypesDeprecated = true;
return ReactPropTypes;
},
});
}
}
module.exports = React;
| JavaScript | 0.000002 | @@ -2049,20 +2049,20 @@
can use
-your
+this
mixin d
|
d58d16b403c4ced538344ae1a1111da666b1514b | change scope for domImage in insertImage | src/js/addons/Images.js | src/js/addons/Images.js | import utils from '../utils';
export default class Images {
constructor(plugin, options) {
this.options = {
label: '<span class="fa fa-camera"></span>',
preview: true,
uploadUrl: 'upload.php'
};
Object.assign(this.options, options);
this._plugin = plugin;
this._editor = this._plugin.base;
this.elementClassName = 'medium-editor-insert-images';
this.label = this.options.label;
this.events();
}
events() {
this._plugin.on(document, 'click', this.unselectImage.bind(this));
this._plugin.getEditorElements().forEach((editor) => {
this._plugin.on(editor, 'click', this.selectImage.bind(this));
});
}
handleClick() {
this._input = document.createElement('input');
this._input.type = 'file';
this._input.multiple = true;
this._plugin.on(this._input, 'change', this.uploadFiles.bind(this));
this._input.click();
}
uploadFiles() {
const paragraph = this._plugin.core.selectedElement;
// Replace paragraph with div, because figure is a block element
// and can't be nested inside paragraphs
if (paragraph.nodeName.toLowerCase() === 'p') {
const div = document.createElement('div');
paragraph.parentNode.insertBefore(div, paragraph);
this._plugin.core.selectElement(div);
paragraph.remove();
}
Array.prototype.forEach.call(this._input.files, (file) => {
// Generate uid for this image, so we can identify it later
// and we can replace preview image with uploaded one
const uid = utils.generateRandomString();
if (this.options.preview) {
this.preview(file, uid);
}
this.upload(file, uid);
});
this._plugin.core.hideButtons();
}
preview(file, uid) {
const reader = new FileReader();
reader.onload = (e) => {
this.insertImage(e.target.result, uid);
};
reader.readAsDataURL(file);
}
upload(file, uid) {
const xhr = new XMLHttpRequest(),
data = new FormData();
xhr.open("POST", this.options.uploadUrl, true);
xhr.onreadystatechange = () => {
if (xhr.readyState === 4 && xhr.status === 200) {
const image = this._plugin.core.selectedElement.querySelector(`[data-uid="${uid}"]`);
if (image) {
this.replaceImage(image, xhr.responseText);
} else {
this.insertImage(xhr.responseText);
}
}
};
data.append("file", file);
xhr.send(data);
}
insertImage(url, uid) {
const el = this._plugin.core.selectedElement,
figure = document.createElement('figure'),
img = document.createElement('img'),
domImage = new Image();
img.alt = '';
if (uid) {
img.setAttribute('data-uid', uid);
}
// If we're dealing with a preview image,
// we don't have to preload it before displaying
if (url.match(/^data:/)) {
img.src = url;
figure.appendChild(img);
el.appendChild(figure);
} else {
domImage.onload = () => {
img.src = domImage.src;
figure.appendChild(img);
el.appendChild(figure);
};
domImage.src = url;
}
el.classList.add(this.elementClassName);
// Return domImage so we can test this function easily
return domImage;
}
replaceImage(image, url) {
const domImage = new Image();
domImage.onload = () => {
image.src = domImage.src;
image.removeAttribute('data-uid');
};
domImage.src = url;
// Return domImage so we can test this function easily
return domImage;
}
selectImage(e) {
const el = e.target;
if (el.nodeName.toLowerCase() === 'img' && utils.getClosestWithClassName(el, this.elementClassName)) {
el.classList.add('medium-editor-insert-image-active');
}
}
unselectImage(e) {
const el = e.target;
let clickedImage;
// Unselect all selected images. If an image is clicked, unselect all except this one.
if (el.nodeName.toLowerCase() === 'img' && el.classList.contains('medium-editor-insert-image-active')) {
clickedImage = el;
}
this._plugin.getEditorElements().forEach((editor) => {
const images = editor.getElementsByClassName('medium-editor-insert-image-active');
Array.prototype.forEach.call(images, (image) => {
if (image !== clickedImage) {
image.classList.remove('medium-editor-insert-image-active');
}
});
});
}
}
| JavaScript | 0 | @@ -2668,17 +2668,17 @@
t('img')
-,
+;
%0A
@@ -2670,35 +2670,35 @@
'img');%0A
-
+let
domImage = new
@@ -2686,38 +2686,24 @@
let domImage
- = new Image()
;%0A%0A i
@@ -3044,32 +3044,68 @@
%7D else %7B%0A
+ domImage = new Image();%0A
domI
|
7000f6bbef4cd133d10d91f10869aa29d2cf2b16 | Update jsPerf_CNNHeightWidthResize.js | CNN/jsPerf/jsPerf_CNNHeightWidthResize.js | CNN/jsPerf/jsPerf_CNNHeightWidthResize.js | //import * as ChannelShuffler from "../Layer/ChannelShuffler.js";
/**
* Test different resize implementation for CNN.
*
* @see {@link https://jsperf.com/colorfulcakechen-cnn-height-width-resize}
*/
/**
* A test set.
*/
class HeightWidthDepth {
/**
* @param {number} height image height
* @param {number} width image width
* @param {number} depth image channel count
*/
constructor( height, width, depth ) {
this.height = height;
this.width = width;
this.depth = depth;
this.valueCount = height * width * depth;
//this.concatenatedShape = [ height, width, depth ];
this.targetSize = [ ( height / 2 ), ( width / 2 ) ];
this.dataTensor3d = tf.tidy( () => {
let dataTensor1d = tf.linspace( 0, this.valueCount - 1, this.valueCount );
let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
return dataTensor3d;
});
this.depthwiseConvFilters = tf.tidy( () => {
let filterHeight = this.targetSize[ 0 ] + 1;
let filterWidth = this.targetSize[ 1 ] + 1;
let inChannels = depth;
let channelMultiplier = 1;
let filtersShape = [ filterHeight, filterWidth, inChannels, channelMultiplier ];
let filtersTensor1d = tf.range( 1, this.valueCount, 1 );
let filtersTensor4d = filtersTensor1d.reshape( filtersShape );
return filtersTensor4d;
});
}
disposeTensors() {
if ( this.dataTensor3d ) {
tf.dispose( this.dataTensor3d );
this.dataTensor3d = null;
}
if ( this.depthwiseConvFilters ) {
tf.dispose( this.depthwiseConvFilters );
this.depthwiseConvFilters = null;
}
}
// Test max-pool
test_MaxPool() {
tf.tidy( () => {
let quarter = this.dataTensor3d.maxPool( 2, 1, "valid" );
});
}
// Test avg-pool
test_AvgPool() {
tf.tidy( () => {
let quarter = this.dataTensor3d.avgPool( 2, 1, "valid" );
});
}
// Test depthwise convolution (2D)
test_DepthwiseConv2d() {
tf.tidy( () => {
let quarter = this.dataTensor3d.depthwiseConv2d( this.depthwiseConvFilters, 1, "valid" );
});
}
// Test rsize-nearest-neighbor
test_ResizeNearestNeighbor() {
tf.tidy( () => {
let quarter = this.dataTensor3d.resizeNearestNeighbor( this.targetSize, true );
});
}
// Test rsize-bilinear
test_ResizeBilinear() {
tf.tidy( () => {
let quarter = this.dataTensor3d.resizeBilinear( this.targetSize, true );
});
}
// Testing whether the results of different implementation are the same.
testResultSame() {
tf.tidy( () => {
test_MaxPool();
test_AvgPool();
test_DepthwiseConv2d();
test_ResizeNearestNeighbor();
test_ResizeBilinear();
// tf.util.assert(
// ChannelShuffler.Layer.isTensorArrayEqual( t1Array, t2Array ),
// `ConcatReshapeTransposeReshapeSplit() != ConcatGatherUnsorted()`);
});
}
}
globalThis.testSet_110x110x24 = new HeightWidthDepth( 110, 110, 24 ); // height, width, depth
| JavaScript | 0.000002 | @@ -1228,24 +1228,86 @@
tiplier %5D;%0A%0A
+ let filterSize = tf.util.sizeFromShape( filtersShape );%0A
let fi
@@ -1332,34 +1332,29 @@
.range(
-1, this.valueCount
+0, filterSize
, 1 );%0A
|
f763ffa562d5f080edbaf224819be77029322f61 | Update JS | src/js/pebble-js-app.js | src/js/pebble-js-app.js | if(Pebble.getActiveWatchInfo) {
if(Pebble.getActiveWatchInfo().platform.match("basalt")) {
// This is the Basalt platform
Pebble.addEventListener('ready', function() {
console.log('PebbleKit JS ready on Basalt!');
});
} else {
// This is the Aplite platform
Pebble.addEventListener('ready', function() {
console.log('PebbleKit JS ready on Aplite!');
});
}
} else {
// This is the Aplite platform
Pebble.addEventListener('ready', function() {
console.log('PebbleKit JS ready on Aplite!');
});
}
| JavaScript | 0 | @@ -25,18 +25,12 @@
Info
-) %7B%0A%0A if(
+ &&
Pebb
@@ -65,29 +65,25 @@
form
-.match(%22
+ === '
basalt
-%22)
+'
) %7B%0A
-%0A
@@ -228,175 +228,8 @@
);
-%0A%0A %7D else %7B%0A%0A // This is the Aplite platform%0A Pebble.addEventListener('ready', function() %7B%0A console.log('PebbleKit JS ready on Aplite!');%0A %7D);%0A %0A %7D
%0A%7D e
@@ -234,17 +234,16 @@
else %7B%0A
-%0A
// Thi
@@ -375,7 +375,5 @@
%7D);%0A
-%0A%7D%0A
+%7D
|
db39c5d574394277b1ffb73d9059283527b3aede | add appendChild override; move utility function to bottom of module | Components/ShadowDOM/polyfill/LightDOM.js | Components/ShadowDOM/polyfill/LightDOM.js | (function(scope) {
var moveChildren = function(element, upgrade) {
var n$ = element.insertions;
if (n$) {
element.insertions = null;
// clean up left-over content rendered from insertions
element.textContent = '';
} else {
n$ = [];
forEach(element.childNodes, function(n) {
n$.push(n);
});
}
forEach(n$, function(n) {
upgrade.appendChild(n);
});
};
var LightDOM = function(inNode) {
// store lightDOM as a document fragment
inNode.lightDOM = document.createDocumentFragment();
// move our children into the fragment
moveChildren(inNode, inNode.lightDOM);
// make sure there's nothing left (?)
if (inNode.textContent != '') {
console.error("LightDOM(): inNode not empty after moving children");
}
// alter inNode's API
inNode.composedNodes = inNode.childNodes;
Object.defineProperty(inNode, 'childNodes', {
get: function() {
return this.lightDOM.childNodes;
}
});
// return the fragment
return inNode.lightDOM;
};
// exports
scope.LightDOM = LightDOM;
})(window.__exported_components_polyfill_scope__);
| JavaScript | 0 | @@ -15,387 +15,8 @@
e) %7B
-%0A %0Avar moveChildren = function(element, upgrade) %7B%0A var n$ = element.insertions;%0A if (n$) %7B%0A element.insertions = null;%0A // clean up left-over content rendered from insertions%0A element.textContent = '';%0A %7D else %7B%0A n$ = %5B%5D;%0A forEach(element.childNodes, function(n) %7B%0A n$.push(n);%0A %7D);%0A %7D%0A forEach(n$, function(n) %7B%0A upgrade.appendChild(n);%0A %7D);%0A%7D;
%0A%0Ava
@@ -231,159 +231,8 @@
M);%0A
- // make sure there's nothing left (?)%0A if (inNode.textContent != '') %7B%0A console.error(%22LightDOM(): inNode not empty after moving children%22);%0A %7D%0A
//
@@ -317,17 +317,19 @@
ePropert
-y
+ies
(inNode,
@@ -329,17 +329,22 @@
inNode,
-'
+%7B%0A
childNod
@@ -349,13 +349,14 @@
odes
-',
+:
%7B%0A
+
@@ -373,16 +373,18 @@
ion() %7B%0A
+
re
@@ -414,16 +414,24 @@
dNodes;%0A
+ %7D%0A
%7D%0A
@@ -440,55 +440,544 @@
;%0A
-// return the fragment%0A return inNode.lightDOM
+inNode.appendChild = function(inNode) %7B%0A return this.lightDOM.appendChild(inNode);%0A %7D;%0A // return the fragment%0A return inNode.lightDOM;%0A%7D;%0A%0Avar moveChildren = function(inElement, inUpgrade) %7B%0A var n$ = inElement.insertions;%0A if (n$) %7B%0A // clean up insertions and content rendered from insertions%0A inElement.insertions = null;%0A inElement.textContent = '';%0A %7D else %7B%0A n$ = %5B%5D;%0A forEach(inElement.childNodes, function(n) %7B%0A n$.push(n);%0A %7D);%0A %7D%0A forEach(n$, function(n) %7B%0A inUpgrade.appendChild(n);%0A %7D)
;%0A%7D;
|
b5254a0206304077138393ea88916b1b0aa72189 | Update matlab.js | src/languages/matlab.js | src/languages/matlab.js | /*
Language: Matlab
Author: Denis Bardadym <bardadymchik@gmail.com>
Contributors: Eugene Nizhibitsky <nizhibitsky@ya.ru>
Category: scientific
*/
function(hljs) {
var COMMON_CONTAINS = [
hljs.C_NUMBER_MODE,
{
className: 'string',
begin: '\'', end: '\'',
contains: [hljs.BACKSLASH_ESCAPE, {begin: '\'\''}]
}
];
var TRANSPOSE = {
relevance: 0,
contains: [
{
begin: /'['\.]*/
}
]
};
return {
keywords: {
keyword:
'break case catch classdef continue else elseif end enumerated events for function ' +
'global if methods otherwise parfor persistent properties return spmd switch try while',
built_in:
'sin sind sinh asin asind asinh cos cosd cosh acos acosd acosh tan tand tanh atan ' +
'atand atan2 atanh sec secd sech asec asecd asech csc cscd csch acsc acscd acsch cot ' +
'cotd coth acot acotd acoth hypot exp expm1 log log1p log10 log2 pow2 realpow reallog ' +
'realsqrt sqrt nthroot nextpow2 abs angle complex conj imag real unwrap isreal ' +
'cplxpair fix floor ceil round mod rem sign airy besselj bessely besselh besseli ' +
'besselk beta betainc betaln ellipj ellipke erf erfc erfcx erfinv expint gamma ' +
'gammainc gammaln psi legendre cross dot factor isprime primes gcd lcm rat rats perms ' +
'nchoosek factorial cart2sph cart2pol pol2cart sph2cart hsv2rgb rgb2hsv zeros ones ' +
'eye repmat rand randn linspace logspace freqspace meshgrid accumarray size length ' +
'ndims numel disp isempty isequal isequalwithequalnans cat reshape diag blkdiag tril ' +
'triu fliplr flipud flipdim rot90 find sub2ind ind2sub bsxfun ndgrid permute ipermute ' +
'shiftdim circshift squeeze isscalar isvector ans eps realmax realmin pi i inf nan ' +
'isnan isinf isfinite j why compan gallery hadamard hankel hilb invhilb magic pascal ' +
'rosser toeplitz vander wilkinson'
},
illegal: '(//|"|#|/\\*|\\s+/\\w+)',
contains: [
{
className: 'function',
beginKeywords: 'function', end: '$',
contains: [
hljs.UNDERSCORE_TITLE_MODE,
{
className: 'params',
variants: [
{begin: '\\(', end: '\\)'},
{begin: '\\[', end: '\\]'}
]
}
]
},
{
begin: /[a-zA-Z_][a-zA-Z_0-9]*'['\.]*/,
returnBegin: true,
relevance: 0,
contains: [
{begin: /[a-zA-Z_][a-zA-Z_0-9]*/, relevance: 0},
TRANSPOSE.contains[0]
]
},
{
begin: '\\[', end: '\\]',
contains: COMMON_CONTAINS,
relevance: 0,
starts: TRANSPOSE
},
{
begin: '\\{', end: /}/,
contains: COMMON_CONTAINS,
relevance: 0,
starts: TRANSPOSE
},
{
// transpose operators at the end of a function call
begin: /\)/,
relevance: 0,
starts: TRANSPOSE
},
hljs.COMMENT('^\\s*\\%\\{\\s*$', '^\\s*\\%\\}\\s*$'),
hljs.COMMENT('\\%', '$')
].concat(COMMON_CONTAINS)
};
}
| JavaScript | 0.000001 | @@ -1974,16 +1974,218 @@
ilkinson
+ max min nanmax nanmin mean nanmean type table ' +%0A 'readtable writetable sortrows sort figure plot plot3 scatter scatter3 cellfun ' +%0A 'legend intersect ismember procrustes hold num2cell
'%0A %7D,
|
defd42f74e73584bf29225da6efb8338097f5e8d | fix fallback on VM. | packages/xo-acl-resolver/src/index.js | packages/xo-acl-resolver/src/index.js | // These global variables are not a problem because the algorithm is
// synchronous.
let permissionsByObject
let getObject
// -------------------------------------------------------------------
const authorized = () => true // eslint-disable-line no-unused-vars
const forbiddden = () => false // eslint-disable-line no-unused-vars
const and = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
for (const checker of checkers) {
if (!checker(object, permission)) {
return false
}
}
return true
}
const or = (...checkers) => (object, permission) => { // eslint-disable-line no-unused-vars
for (const checker of checkers) {
if (checker(object, permission)) {
return true
}
}
return false
}
// -------------------------------------------------------------------
const checkMember = memberName => (object, permission) => {
const member = object[memberName]
return checkAuthorization(member, permission)
}
const checkSelf = ({ id }, permission) => {
const permissionsForObject = permissionsByObject[id]
return (
permissionsForObject &&
permissionsForObject[permission]
)
}
// ===================================================================
const checkAuthorizationByTypes = {
host: or(checkSelf, checkMember('$pool')),
message: checkMember('$object'),
network: or(checkSelf, checkMember('$pool')),
SR: or(checkSelf, checkMember('$pool')),
task: checkMember('$host'),
VBD: checkMember('VDI'),
// Access to a VDI is granted if the user has access to the
// containing SR or to a linked VM.
VDI (vdi, permission) {
// Check authorization for the containing SR.
if (checkAuthorization(vdi.$SR, permission)) {
return true
}
// Check authorization for each of the connected VMs.
for (const { VM: vm } of vdi.$VBDs) {
if (checkAuthorization(vm, permission)) {
return true
}
}
return false
},
'VDI-snapshot': checkMember('$snapshot_of'),
VIF: or(checkMember('$network'), checkMember('$VM')),
VM: or(checkSelf, checkMember('$container')),
'VM-snapshot': checkMember('$snapshot_of'),
'VM-template': authorized
}
// Hoisting is important for this function.
function checkAuthorization (objectId, permission) {
const object = getObject(objectId)
const checker = checkAuthorizationByTypes[object.type] || checkSelf
return checker(object, permission)
}
// -------------------------------------------------------------------
export default (
permissionsByObject_,
getObject_,
permissions
) => {
// Assign global variables.
permissionsByObject = permissionsByObject_
getObject = getObject_
try {
for (const [objectId, permission] of permissions) {
if (!checkAuthorization(objectId, permission)) {
return false
}
}
return true
} finally {
// Free the global variables.
permissionsByObject = getObject = null
}
}
| JavaScript | 0 | @@ -1828,18 +1828,13 @@
nst
-%7B VM: vm %7D
+vbdId
of
@@ -1879,10 +1879,27 @@
ion(
-vm
+getObject(vbdId).VM
, pe
|
825757ca20e3bee91cc42449ef7c32b04d8145e7 | Fix Radio | src/components/Radio.js | src/components/Radio.js | var blacklist = require('blacklist');
var classNames = require('classnames');
var React = require('react/addons');
var Radio = React.createClass({
propTypes: {
inline: React.PropTypes.bool,
label: React.PropTypes.string
},
render() {
var componentClass = classNames('Radio', {
'Radio--disabled': this.props.disabled,
'Radio--inline': this.props.inline
}, this.props.className);
var props = blacklist(this.props, 'className', 'label');
return (
<label className={componentClass}>
<input type="radio" className="Radio__input" {...props} />
{this.props.label && <span className="Radio__label">{this.props.label}</span>}
</label>
);
}
});
module.exports = Radio;
| JavaScript | 0.000003 | @@ -155,16 +155,87 @@
ypes: %7B%0A
+%09%09className: React.PropTypes.string,%0A%09%09disabled: React.PropTypes.bool,%0A
%09%09inline
@@ -519,18 +519,16 @@
abel');%0A
-%09%09
%0A%09%09retur
|
34458c5654dfd25dc7fc0fcffd9eff5cda57f27f | fix build err | src/components/index.js | src/components/index.js | export {default as Carousel} from './carousel/Carousel.vue'
export {default as Slide} from './carousel/Slide.vue'
export {default as Collapse} from './collapse/Collapse.vue'
export {default as Dropdown} from './dropdown/Dropdown.vue'
export {default as Modal} from './modal/Modal.vue'
export {default as Tab} from './tabs/Tab.vue'
export {default as Tabs} from './tabs/Tabs.vue'
export {default as DatePicker} from './datepicker/DatePicker.vue'
export {default as Affix} from './affix/Affix.vue'
export {default as Alert} from './alert/Alert.vue'
export {default as Pagination} from './pagination/Pagination.vue'
export {default as Tooltip} from './tooltip/Tooltip.vue'
export {default as Popover} from './popover/Popover.vue'
export {default as TimePicker} from './timepicker/TimePicker.vue'
export {default as Typeahead} from './typeahead/Typeahead.vue'
export {default as ProgressBar} from './progressbar/ProgressBar'
export {default as ProgressBarStack} from './progressbar/ProgressBarStack'
export {default as Breadcrumbs} from './breadcrumbs/Breadcrumbs'
export {default as BreadcrumbItem} from './breadcrumbs/BreadcrumbItem'
export {default as Btn} from './button/Btn'
export {default as BtnGroup} from './button/BtnGroup'
export {default as BtnToolbar} from './button/BtnToolbar'
export {default as MultiSelect} from './select/MultiSelect'
| JavaScript | 0.000001 | @@ -1339,10 +1339,14 @@
tiSelect
+.vue
'%0A
|
f6065830f442d55f403b53968db3c1540ae0c361 | Update Header comment | src/main/webapp/components/BuildSnapshot.js | src/main/webapp/components/BuildSnapshot.js | import * as React from "react";
import {getFields} from "./utils/getFields.js";
import {Wrapper} from "./Wrapper.js";
/**
* Component used to render Build Information.
*
* @param {*} props input properties containing build information
*/
export const BuildSnapshot = (props) => {
// State variable indicating whether the BuildSnapshot is open
// isOpen === true indicates the tray should be visible
// and the indicator arrow on the Header should be facing downwards.
const [isOpen, setIsOpen] = React.useState(false);
const headerFields = ["description", "commitHash", "repository", "status"];
const trayFields = ["builders", "timestamp"];
const headerData = getFields(props.buildData, headerFields, "");
const trayData = getFields(props.buildData, trayFields, "");
return (
<Wrapper>
<Header isOpen = {isOpen} onClick = {setIsOpen} data = {headerData}/>
<Tray isOpen = {isOpen} data = {trayData}/>
</Wrapper>
);
}
/**
* Subcomponent that holds the content displayed
* when the BuildSnapshot is collapsed.
*
* @param props an object containing a "data" field.
* , which encapsulates the fields from headerFields.
*/
const Header = (props) => {
return (
<div onClick = {() => props.onClick(toggle(props.isOpen))}>
<CommitHash hash = {props.data.commitHash}/>
<Description description = {props.data.description}/>
<FailureGroup group = {"Group"}/>
<BuildStatus status = {props.data.status}/>
</div>
);
}
/**
* Subcomponent that holds the content revealed
* when the BuildSnapshot is collapsed (isOpen === true).
* @param props an object containing a "data" field
* which encapsualtes the fields from trayFields.
*/
const Tray = (props) => {
if(props.isOpen !== true) return null;
return (
<div>
<Wrapper>
<Subheading time = {props.data.timestamp}/>
<NameTagGrid data = {props.data.builders}/>
</Wrapper>
<BuilderDataTable/>
</div>
);
}
| JavaScript | 0 | @@ -1115,15 +1115,12 @@
ield
-.
%0A *
- ,
whi
|
89dea3270e28a15a55a9d88b5341725e8a75f9e8 | Add Classname to timestamp element and Add current bot element | src/main/webapp/components/BuildSnapshot.js | src/main/webapp/components/BuildSnapshot.js | import * as React from "react";
import {getFields} from "./utils/getFields.js";
/**
* Component used to render Build Information.
*
* @param {*} props input properties containing build information
*/
export const BuildSnapshot = (props) => {
// State variable indicating whether the BuildSnapshot is open or closed.
// isOpen === true indicates the tray should be visible
// and the indicator arrow on the Header should be facing downwards.
const [isOpen, setIsOpen] = React.useState(false);
const headerFields = ["description", "commitHash", "repository", "status"];
const trayFields = ["builders", "timestamp"];
const headerData = getFields(props.buildData, headerFields, "");
const trayData = getFields(props.buildData, trayFields, "");
return (
<div>
<Header isOpen = {isOpen} onClick = {setIsOpen} data = {headerData}/>
<Tray isOpen = {isOpen} data = {trayData}/>
</div>
);
}
/**
* Subcomponent that holds the content displayed
* when the BuildSnapshot is collapsed.
*
* @param props an object containing a "data" field
* which encapsulates the fields from headerFields.
*/
const Header = (props) => {
return (
<div onClick = {() => props.onClick(toggle(props.isOpen))}>
<span class="header-hash">{props.data.commitHash}</span>
<span class="header-description">{props.data.description}</span>
<FailureGroup group = {"Group"}/>
<span class="header-status">{props.data.status}</span>
</div>
);
}
/**
* Subcomponent that holds the content revealed
* when the BuildSnapshot is collapsed (isOpen === true).
*
* @param props an object containing a "data" field
* which encapsualtes the fields from trayFields.
*/
const Tray = (props) => {
if(props.isOpen !== true) return null;
return (
<div classname="tray">
<span>{props.data.timestamp}</span>
<div>bot name</div>
<BuilderGrid data = {props.data.builders}/>
<BuilderDataTable/>
</div>
);
}
| JavaScript | 0 | @@ -1808,20 +1808,16 @@
iv class
-name
=%22tray%22%3E
@@ -1828,16 +1828,38 @@
%3Cspan
+ class=%22tray-timespan%22
%3E%7Bprops.
@@ -1896,18 +1896,39 @@
div%3E
-bot n
+%3Cspan%3ECurrent Bot N
ame%3C/
+span%3E%3C/
div%3E
|
9d2c138c7dbc54519ba9574a2e8290fc10e0593a | Remove useless code | src/mist/io/static/js/app/views/key_list.js | src/mist/io/static/js/app/views/key_list.js | define('app/views/key_list', [
'app/views/mistscreen',
'text!app/templates/key_list.html',
'ember'
],
/**
* Key List View
*
* @returns Class
*/
function(MistScreen, key_list_html) {
return MistScreen.extend({
template: Ember.Handlebars.compile(key_list_html),
selectedKey: null,
inti: function() {
this._super();
$("input[type='checkbox']").checkboxradio("refresh");
},
selectedKeysObserver: function() {
var that = this;
var selectedKeysCount = 0;
Mist.keysController.keys.some(function(key) {
if (key.selected) {
if(++selectedKeysCount == 2) {
$('#keys-footer a').addClass('ui-disabled');
that.selectedKey = null;
return true;
}
that.selectedKey = key;
}
});
if (selectedKeysCount == 0) {
$('#keys-footer').fadeOut(200);
} else if (selectedKeysCount == 1) {
$('#keys-footer').fadeIn(200);
$('#keys-footer a').removeClass('ui-disabled');
}
}.observes('Mist.keysController.keys.@each.selected'),
createClicked: function() {
$("#create-key-dialog").popup("open");
},
selectClicked: function() {
$('#select-keys-dialog').popup('open');
},
selectionModeClicked: function(mode) {
Mist.keysController.keys.forEach(function(key) {
key.set('selected', mode);
});
Ember.run.next(function() {
$("input[type='checkbox']").checkboxradio("refresh");
});
$('#select-keys-dialog').popup('close');
},
deleteClicked: function() {
var keyName = this.selectedKey.name;
Mist.confirmationController.set('title', 'Delete key');
Mist.confirmationController.set('text', 'Are you sure you want to delete "' + keyName +'" ?');
Mist.confirmationController.set('callback', function() {
Mist.keysController.deleteKey(keyName);
});
Mist.confirmationController.show();
},
setDefaultClicked: function() {
Mist.keysController.setDefaultKey(this.selectedKey.name);
}
});
}
);
| JavaScript | 0.001027 | @@ -356,156 +356,8 @@
l,%0A%0A
- inti: function() %7B%0A this._super();%0A $(%22input%5Btype='checkbox'%5D%22).checkboxradio(%22refresh%22);%0A %7D,%0A%0A
|
453483f6a3cfb15e43f5f0c767f0467fc57f07be | Use isPlainObject instead of isObject | src/constructors/css.js | src/constructors/css.js | import camelize from 'fbjs/lib/camelizeStyleName'
import isObject from "lodash/isObject"
import rule from "./rule"
import MediaQuery from "../models/MediaQuery"
import RuleSet from "../models/RuleSet";
import NestedSelector from "../models/NestedSelector";
import ValidRuleSetChild from "../models/ValidRuleSetChild";
const declaration = /^\s*([\w-]+):\s*([^;]*);\s*$/
const startNesting = /^\s*([\w\.#:&>~+][^{]+?)\s*\{\s*$/
const startMedia = /^\s*@media\s+([^{]+?)\s*\{\s*$/
const stopNestingOrMedia = /^\s*}\s*$/
/* This is a bit complicated.
* Basically, you get an array of strings and an array of interpolations.
* You want to interleave them, so that they're processed together.
* That's easy enough.
* Except you also want to split the strings by line.
* Still ok I guess.
* Except that some of the interpolations are within a line i.e. background: ${ colors.white };
* So short-circuit those by converting to a string and concatenating so later
* when you split by "\n" you get valid lines of CSS.
* I know, right?
*
* Anyway, this needs to be replaced by a real CSS parser. TODO: that.
* */
const interleave = (strings, interpolations) => {
const linesAndInterpolations = strings[0].split('\n')
interpolations.forEach((interp, i) => {
/* Complex, Rule-based interpolation (could be multi-line, or nesting etc) */
if (interp instanceof ValidRuleSetChild) {
linesAndInterpolations.push(interp)
if (strings[i + 1]) linesAndInterpolations.push(...strings[i + 1].split('\n'))
/* CSS-in-JS */
} else if (isObject(interp)) {
Object.keys(interp).forEach((prop) => {
linesAndInterpolations.push(`${prop}: ${interp[prop]};`)
})
} else {
/* Simple (value) interpolation. Concatenate and move on. */
const lastStr = linesAndInterpolations.pop()
linesAndInterpolations.push(...(lastStr + interp + (strings[i + 1] || '')).split('\n'))
}
})
return linesAndInterpolations;
}
export default (strings, ...interpolations) => {
/* A data structure we can use to traverse the CSS */
let currentLevel = {
parent: null,
ruleSet: new RuleSet()
}
var linesAndInterpolations = interleave(strings, interpolations);
const processLine = line => {
const [_, subSelector] = startNesting.exec(line) || []
const [__, property, value] = declaration.exec(line) || []
const [___, mediaQuery] = startMedia.exec(line) || []
let popNestingOrMedia = stopNestingOrMedia.exec(line)
/* ARE WE STARTING A NESTING? */
if (subSelector) {
const subRules = new RuleSet()
const nesting = new NestedSelector(subSelector, subRules)
currentLevel.ruleSet.add(nesting)
currentLevel = {
parent: currentLevel,
ruleSet: subRules
}
/* ARE WE STARTING A MEDIA QUERY? */
} else if (mediaQuery) {
const subRules = new RuleSet()
const media = new MediaQuery(mediaQuery, subRules)
currentLevel.ruleSet.add(media)
currentLevel = {
parent: currentLevel,
ruleSet: subRules,
}
/* ARE WE A NORMAL RULE? */
} else if (property && value) {
const newRule = rule(camelize(property), value)
currentLevel.ruleSet.add(newRule)
} else if (popNestingOrMedia) {
if (!currentLevel.parent) {
console.error(linesAndInterpolations)
console.error(currentLevel)
throw new Error("CSS Syntax Error — Trying to un-nest one too many times")
}
currentLevel = currentLevel.parent
}
}
const processLineOrInterp = lineOrInterp => {
if (typeof lineOrInterp === 'string') {
processLine(lineOrInterp)
} else if (lineOrInterp instanceof ValidRuleSetChild) {
currentLevel.ruleSet.add(lineOrInterp)
} else {
console.warn("I don't know what to do with this:", lineOrInterp)
}
}
linesAndInterpolations.forEach(processLineOrInterp)
return currentLevel.ruleSet
}
| JavaScript | 0.000398 | @@ -52,16 +52,21 @@
mport is
+Plain
Object f
@@ -79,16 +79,21 @@
odash/is
+Plain
Object%22%0A
@@ -1538,26 +1538,24 @@
SS-in-JS */%0A
-
%7D else if
@@ -1557,16 +1557,21 @@
e if (is
+Plain
Object(i
|
ebc98f49848236a19a7054609e113710df810971 | Rename classname | src/models/Websocket.js | src/models/Websocket.js | import MessageConstants from '../constants/MessageConstants'
const STATE_CONNECTING = 0
const STATE_OPEN = 1
const STATE_CLOSING = 2
const STATE_CLOSED = 3
const socketProperty = Symbol()
const callbackProperty = Symbol()
class WebsocketWrapper {
constructor(url, callback) {
this.address = url
this.messages = []
this[callbackProperty] = callback
const self = this
try {
this[socketProperty] = new WebSocket(url)
this[socketProperty].onopen = function(e){
self.pushMessage(MessageConstants.TYPE_OPEN);
}
this[socketProperty].onclose = function(event) {
if (event.wasClean) {
self.pushMessage(MessageConstants.TYPE_CLOSE);
} else {
self.pushMessage(MessageConstants.TYPE_DISCONNECT);
}
self.pushMessage(MessageConstants.TYPE_ERROR, event.reason);
}
this[socketProperty].onmessage = function(event) {
self.pushMessage(MessageConstants.TYPE_MESSAGE, event.data);
};
this[socketProperty].onerror = function(error) {
self.pushMessage(MessageConstants.TYPE_ERROR, error.message);
};
} catch (error) {
self.pushMessage(MessageConstants.TYPE_ERROR, error.toString())
}
}
send(message){
if (this.isOpen()){
this[socketProperty].send(message)
}
}
close(){
this[socketProperty].close()
}
isOpen() {
return this[socketProperty] && this[socketProperty].readyState == STATE_OPEN
}
isClosed() {
return this[socketProperty] && this[socketProperty].readyState == STATE_CLOSED
}
pushMessage(type, content) {
this.messages.unshift({
datetime: new Date(),
type: type,
content: content,
})
this[callbackProperty]()
}
}
export default WebsocketWrapper
| JavaScript | 0.000006 | @@ -233,23 +233,16 @@
ebsocket
-Wrapper
%7B%0A con
@@ -1767,12 +1767,5 @@
cket
-Wrapper
%0A
|
bd29faee303f61e6883fd1bdf222119e64dfec80 | Remove stage prefix from auth event methodArn | src/createAuthScheme.js | src/createAuthScheme.js | 'use strict';
const Boom = require('boom');
const createLambdaContext = require('./createLambdaContext');
const functionHelper = require('./functionHelper');
const debugLog = require('./debugLog');
const _ = require('lodash');
module.exports = function createAuthScheme(authFun, authorizerOptions, funName, endpointPath, options, serverlessLog, servicePath, serverless) {
const authFunName = authorizerOptions.name;
const identitySourceMatch = /^method.request.header.((?:\w+-?)+\w+)$/.exec(authorizerOptions.identitySource);
if (!identitySourceMatch || identitySourceMatch.length !== 2) {
throw new Error(`Serverless Offline only supports retrieving tokens from the headers (λ: ${authFunName})`);
}
const identityHeader = identitySourceMatch[1].toLowerCase();
const funOptions = functionHelper.getFunctionOptions(authFun, funName, servicePath);
// Create Auth Scheme
return () => ({
authenticate(request, reply) {
process.env = _.extend({}, serverless.service.provider.environment, process.env);
console.log(''); // Just to make things a little pretty
serverlessLog(`Running Authorization function for ${request.method} ${request.path} (λ: ${authFunName})`);
// Get Authorization header
const req = request.raw.req;
const authorization = req.headers[identityHeader];
debugLog(`Retrieved ${identityHeader} header ${authorization}`);
// Create event Object for authFunction
// methodArn is the ARN of the function we are running we are authorizing access to (or not)
// Account ID and API ID are not simulated
const event = {
type: 'TOKEN',
authorizationToken: authorization,
methodArn: `arn:aws:execute-api:${options.region}:random-account-id:random-api-id/${options.stage}/${request.method.toUpperCase()}${request.path}`,
};
// Create the Authorization function handler
let handler;
try {
handler = functionHelper.createHandler(funOptions, options);
}
catch (err) {
return reply(Boom.badImplementation(null, `Error while loading ${authFunName}`));
}
// Creat the Lambda Context for the Auth function
const lambdaContext = createLambdaContext(authFun, (err, result) => {
// Return an unauthorized response
const onError = error => {
serverlessLog(`Authorization function returned an error response: (λ: ${authFunName})`, error);
return reply(Boom.unauthorized('Unauthorized'));
};
if (err) {
return onError(err);
}
const onSuccess = policy => {
// Validate that the policy document has the principalId set
if (!policy.principalId) {
serverlessLog(`Authorization response did not include a principalId: (λ: ${authFunName})`, err);
return reply(Boom.forbidden('No principalId set on the Response'));
}
serverlessLog(`Authorization function returned a successful response: (λ: ${authFunName})`, policy);
if (policy.policyDocument.Statement[0].Effect === 'Deny') {
serverlessLog(`Authorization response didn't authorize user to access resource: (λ: ${authFunName})`, err);
return reply(Boom.forbidden('User is not authorized to access this resource'));
}
// Set the credentials for the rest of the pipeline
return reply.continue({ credentials: { user: policy.principalId, context: policy.context } });
};
if (result && typeof result.then === 'function' && typeof result.catch === 'function') {
debugLog('Auth function returned a promise');
result.then(onSuccess).catch(onError);
}
else if (result instanceof Error) {
onError(result);
}
else {
onSuccess(result);
}
});
// Execute the Authorization Function
handler(event, lambdaContext, lambdaContext.done);
},
});
};
| JavaScript | 0 | @@ -1839,16 +1839,62 @@
est.path
+.replace(new RegExp(%60%5E/$%7Boptions.stage%7D%60), '')
%7D%60,%0A
|
ea9094832802996c86864bf517f5d9eb8c792f5f | Add missing negative entries. | src/data/color-fonts.js | src/data/color-fonts.js | define(function () {
return {
name: "Color fonts",
description: "Four color font formats are currently in existence: three OpenType proposals, one proprietary. Support is fragmented. When unsupported, the browser will fall back to regular glyphs in the font. Read about [the differences of the formats](http://pixelambacht.nl/2014/multicolor-fonts/).",
keywords: ["color", "multicolor"],
browsers: [
{ name: "ie", range: "11-", support: "yes", note: "Only COLR/CPAL on Windows 8.1+." },
{ name: "chrome", range: "-", support: "no" },
{ name: "firefox", range: "36-", support: "yes", note: "Only COLR/CPAL and SVG-in-OpenType." },
{ name: "opera", range: "-", support: "no" },
{ name: "safari", range: "9-", support: "yes", note: "Only Apple's proprietary SBIX." },
{ name: "ios", range: "9-", support: "yes", note: "Only Apple's proprietary SBIX." },
{ name: "android", range: "-", support: "no" }
],
features: [
{
name: "SBIX",
description: "Apple's proprietary implementation for color fonts. Uses embedded PNG images to represent the color glyphs.",
specification: "https://developer.apple.com/fonts/TrueType-Reference-Manual/RM06/Chap6sbix.html",
keywords: ['color', 'multicolor', 'sbix', 'apple'],
browsers: [
{ name: "ie", range: "-", support: "no" },
{ name: "chrome", range: "-", support: "no" },
{ name: "firefox", range: "-", support: "no" },
{ name: "safari", range: "-8", support: "no" },
{ name: "safari", range: "9", support: "yes" },
{ name: "ios", range: "-8", support: "no" },
{ name: "ios", range: "9", support: "yes" },
{ name: "opera", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
},
{
name: "COLR/CPAL",
description: "Mircosoft's proposal for the OpenType specification. Uses layered glyphs to create multicolor ones.",
specification: "https://www.microsoft.com/typography/otspec/colr.htm",
keywords: ['color', 'multicolor', 'colr', 'cpal', 'mircosoft'],
browsers: [
{ name: "ie", range: "11-", support: "yes", note: "Only on Windows 8.1+" },
{ name: "chrome", range: "-", support: "no" },
{ name: "firefox", range: "-31", support: "no" },
{ name: "firefox", range: "32-", support: "yes" },
{ name: "safari", range: "-", support: "no" },
{ name: "ios", range: "-", support: "no" },
{ name: "opera", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
},
{
name: "SVG-in-OpenType",
description: "Mozilla and Adobe's proposal for the OpenType specification. Uses embedded SVG images to represent the color glyphs.",
specification: "http://www.w3.org/2013/10/SVG_in_OpenType/",
keywords: ['color', 'multicolor', 'svg', 'adobe', 'mozilla', 'svg-in-opentype'],
browsers: [
{ name: "ie", range: "-", support: "no" },
{ name: "chrome", range: "-", support: "no" },
{ name: "firefox", range: "-25", support: "no" },
{ name: "firefox", range: "26-", support: "yes" },
{ name: "safari", range: "-", support: "no" },
{ name: "ios", range: "-", support: "no" },
{ name: "opera", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
},
{
name: "CBDT/CBLC",
description: "Google's CBDT/CBLC. Currently only supported on Android when installed as a system font; not available through @font-face. Uses embedded PNG images to represent the color glyphs.",
specification: "hhttps://www.microsoft.com/typography/otspec/cbdt.htm",
keywords: ['color', 'multicolor', 'google', 'cbdt', 'cblc'],
browsers: [
{ name: "ie", range: "-", support: "no" },
{ name: "chrome", range: "-", support: "no" },
{ name: "firefox", range: "-", support: "no" },
{ name: "safari", range: "-", support: "no" },
{ name: "ios", range: "-", support: "no" },
{ name: "opera", range: "-", support: "no" },
{ name: "android", range: "-", support: "no" }
]
}
]
};
});
| JavaScript | 0.000005 | @@ -407,24 +407,80 @@
browsers: %5B%0A
+ %7B name: %22ie%22, range: %22-10%22, support: %22no%22 %7D,%0A
%7B name
@@ -613,32 +613,88 @@
upport: %22no%22 %7D,%0A
+ %7B name: %22firefox%22, range: %22-35%22, support: %22no%22 %7D,%0A
%7B name: %22f
@@ -827,32 +827,87 @@
upport: %22no%22 %7D,%0A
+ %7B name: %22safari%22, range: %22-8%22, support: %22no%22 %7D,%0A
%7B name: %22s
@@ -1011,33 +1011,92 @@
s%22, range: %22
-9
+-8.1%22, support: %22no%22 %7D,%0A %7B name: %22ios%22, range: %229.1
-%22, support: %22ye
@@ -1821,32 +1821,33 @@
fari%22, range: %229
+-
%22, support: %22yes
@@ -1878,32 +1878,34 @@
ios%22, range: %22-8
+.1
%22, support: %22no%22
@@ -1942,16 +1942,19 @@
ange: %229
+.1-
%22, suppo
@@ -2420,32 +2420,87 @@
browsers: %5B%0A
+ %7B name: %22ie%22, range: %22-10%22, support: %22no%22 %7D,%0A
%7B name
@@ -2563,17 +2563,27 @@
dows 8.1
-+
+ and above.
%22 %7D,%0A
|
99aed9048c50c49bcd8d143d7a39505bafef68b7 | add fix rights user | GruntTasks/Options/concat.orchestracss.js | GruntTasks/Options/concat.orchestracss.js | module.exports = {
src: [
'web/built/openorchestrabackoffice/css/openorchestra.css',
'web/built/openorchestrabackoffice/css/template.css',
'web/built/openorchestrabackoffice/css/blocksPanel.css',
'web/built/openorchestrabackoffice/css/blocksIcon.css',
'web/built/openorchestrabackoffice/css/loginPage.css',
'web/built/openorchestrabackoffice/css/editTable.css',
'web/built/openorchestrabackoffice/css/node.css',
'web/built/openorchestramediaadmin/css/media.css',
'web/built/openorchestramediaadmin/css/mediaModal.css',
'web/built/openorchestraworkflowfunctionadminBundle/css/table.css'
],
dest: 'web/built/orchestra.css'
};
| JavaScript | 0.000001 | @@ -645,14 +645,8 @@
dmin
-Bundle
/css
|
1491a96e3ca589d886e7679db0f9fdb7b99874dc | Add list table columns feature for MySQL | src/db/clients/mysql.js | src/db/clients/mysql.js | import mysql from 'mysql';
const debug = require('../../debug')('db:clients:mysql');
const mysqlErrors = {
ER_EMPTY_QUERY: 'ER_EMPTY_QUERY',
};
export default function(server, database) {
return new Promise(async (resolve, reject) => {
const dbConfig = _configDatabase(server, database);
debug('creating database client %j', dbConfig);
const client = mysql.createConnection(dbConfig);
client.on('error', error => {
// it will be handled later in the next query execution
debug('Connection fatal error %j', error);
});
debug('connecting');
client.connect(err => {
if (err) {
client.end();
return reject(err);
}
debug('connected');
resolve({
disconnect: () => disconnect(client),
listTables: () => listTables(client),
listViews: () => listViews(client),
listRoutines: () => listRoutines(client),
executeQuery: (query) => executeQuery(client, query),
listDatabases: () => listDatabases(client),
getQuerySelectTop: (table, limit) => getQuerySelectTop(client, table, limit),
truncateAllTables: () => truncateAllTables(client),
});
});
});
}
export function disconnect(client) {
client.end();
}
export function listTables(client) {
return new Promise((resolve, reject) => {
const sql = `
SELECT table_name
FROM information_schema.tables
WHERE table_schema = database()
AND table_type NOT LIKE '%VIEW%'
ORDER BY table_name
`;
const params = [];
client.query(sql, params, (err, data) => {
if (err) return reject(_getRealError(client, err));
resolve(data.map(row => row.table_name));
});
});
}
export function listViews(client) {
return new Promise((resolve, reject) => {
const sql = `
SELECT table_name
FROM information_schema.views
WHERE table_schema = database()
ORDER BY table_name
`;
const params = [];
client.query(sql, params, (err, data) => {
if (err) return reject(_getRealError(client, err));
resolve(data.map(row => row.table_name));
});
});
}
export function listRoutines(client) {
return new Promise((resolve, reject) => {
const sql = `
SELECT routine_name, routine_type
FROM information_schema.routines
WHERE routine_schema = database()
ORDER BY routine_name
`;
const params = [];
client.query(sql, params, (err, data) => {
if (err) return reject(_getRealError(client, err));
resolve(data.map(row => ({
routineName: row.routine_name,
routineType: row.routine_type,
})));
});
});
}
export function executeQuery(client, query) {
return new Promise((resolve, reject) => {
client.query(query, (err, data, fields) => {
if (err && err.code === mysqlErrors.ER_EMPTY_QUERY) return resolve([]);
if (err) return reject(_getRealError(client, err));
if (!isMultipleQuery(fields)) {
return resolve([parseRowQueryResult(data, fields)]);
}
resolve(
data.map((_, idx) => parseRowQueryResult(data[idx], fields[idx]))
);
});
});
}
export function listDatabases(client) {
return new Promise((resolve, reject) => {
const sql = 'show databases';
client.query(sql, (err, data) => {
if (err) return reject(_getRealError(client, err));
resolve(data.map(row => row.Database));
});
});
}
export function getQuerySelectTop(client, table, limit) {
return `SELECT * FROM ${wrapQuery(table)} LIMIT ${limit}`;
}
export function wrapQuery(item) {
return `\`${item}\``;
}
const getSchema = async (client) => {
const [result] = await executeQuery(client, `SELECT database() AS 'schema'`);
return result.rows[0].schema;
};
export const truncateAllTables = async (client) => {
const schema = await getSchema(client);
const sql = `
SELECT table_name
FROM information_schema.tables
WHERE table_schema = '${schema}'
AND table_type NOT LIKE '%VIEW%'
`;
const [result] = await executeQuery(client, sql);
const tables = result.rows.map(row => row.table_name);
const promises = tables.map(t => executeQuery(client, `
TRUNCATE TABLE ${wrapQuery(schema)}.${wrapQuery(t)}
`));
await Promise.all(promises);
};
function _configDatabase(server, database) {
const config = {
host: server.config.host,
port: server.config.port,
user: server.config.user,
password: server.config.password,
database: database.database,
multipleStatements: true,
};
if (server.sshTunnel) {
config.host = server.config.localHost;
config.port = server.config.localPort;
}
if (server.config.ssl) {
server.config.ssl = {
// It is not the best recommend way to use SSL with node-mysql
// https://github.com/felixge/node-mysql#ssl-options
// But this way we have compatibility with all clients.
rejectUnauthorized: false,
};
}
return config;
}
function _getRealError(client, err) {
if (client && client._protocol && client._protocol._fatalError) {
return client._protocol._fatalError;
}
return err;
}
function parseRowQueryResult(data, fields) {
const isSelect = Array.isArray(data);
return {
isSelect,
rows: isSelect ? data : [],
fields: fields || [],
rowCount: isSelect ? (data : []).length : undefined,
affectedRows: !isSelect ? data.affectedRows : undefined,
};
}
function isMultipleQuery(fields) {
if (!fields) { return false; }
if (!fields.length) { return false; }
return (Array.isArray(fields[0]) || fields[0] === undefined);
}
| JavaScript | 0 | @@ -902,32 +902,102 @@
utines(client),%0A
+ listTableColumns: (table) =%3E listTableColumns(client, table),%0A
executeQ
@@ -2725,32 +2725,566 @@
%7D);%0A %7D);%0A%7D%0A%0A
+export function listTableColumns(client, table) %7B%0A return new Promise((resolve, reject) =%3E %7B%0A const sql = %60%0A SELECT column_name, data_type%0A FROM information_schema.columns%0A WHERE table_schema = database()%0A AND table_name = ?%0A %60;%0A const params = %5B%0A table,%0A %5D;%0A client.query(sql, params, (err, data) =%3E %7B%0A if (err) return reject(_getRealError(client, err));%0A resolve(data.map(row =%3E (%7B%0A columnName: row.column_name,%0A dataType: row.data_type,%0A %7D)));%0A %7D);%0A %7D);%0A%7D%0A%0A
export function
|
4875769e5f7b38642e76ef8996058b644b45aae2 | Save 'lifetime' preference for created default containers | src/defaultContainer.js | src/defaultContainer.js | import {formatString} from './utils';
import HostStorage from './Storage/HostStorage';
import ContextualIdentities from './ContextualIdentity';
import ExtendedURL from './ExtendedURL';
export async function buildDefaultContainer(preferences, url) {
url = new ExtendedURL(url);
let name = preferences['defaultContainer.containerName'];
name = formatString(name, {
ms: Date.now(),
domain: url.domain,
fqdn: url.host,
host: url.host,
tld: url.tld,
});
// Get cookieStoreId
const containers = await ContextualIdentities.get(name);
let cookieStoreId;
if (containers.length > 0) {
cookieStoreId = containers[0].cookieStoreId;
} else {
// Create a default container
const container = await ContextualIdentities.create(name);
cookieStoreId = container.cookieStoreId;
}
// Add a rule if necessary
const ruleAddition = preferences['defaultContainer.ruleAddition'];
if (ruleAddition) {
try {
const host = formatString(ruleAddition, {
domain: url.domain,
fqdn: url.host,
host: url.host,
tld: url.tld,
});
await HostStorage.set({
host: host,
cookieStoreId,
containerName: name,
enabled: true,
});
} catch (e) {
console.error('Couldn\'t add rule', ruleAddition, e);
}
}
return cookieStoreId;
}
| JavaScript | 0.000001 | @@ -177,16 +177,77 @@
dedURL';
+%0Aimport PreferenceStorage from './Storage/PreferenceStorage';
%0A%0Aexport
@@ -1384,16 +1384,228 @@
%7D%0A %7D%0A%0A
+ const lifetime = preferences%5B'defaultContainer.lifetime'%5D;%0A if(lifetime !== 'forever')%7B%0A await PreferenceStorage.set(%7B%0A key: %60containers.$%7BcookieStoreId%7D.lifetime%60,%0A value: lifetime,%0A %7D);%0A %7D%0A%0A
return
|
94585f0e845e2d0537b32caa154514bcccf81c96 | Implement SettingsSchema.sites. | src/resolvers-cassandra/Settings/queries.js | src/resolvers-cassandra/Settings/queries.js | 'use strict';
const Promise = require('promise');
const facebookAnalyticsClient = require('../../clients/facebook/FacebookAnalyticsClient');
/**
* @param {{siteId: string}} args
* @returns {Promise.<{runTime: string, sites: Array<{name: string, properties: {targetBbox: number[], defaultZoomLevel: number, logo: string, title: string, defaultLocation: number[], storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string[]}}>}>}
*/
function sites(args, res) { // eslint-disable-line no-unused-vars
}
/**
* @param {{siteId: string}} args
* @returns {Promise.<{runTime: string, accounts: Array<{accountName: string, consumerKey: string, consumerSecret: string, token: string, tokenSecret: string}>}>}
*/
function twitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}
/**
* @param {{siteId: string}} args
* @returns {Promise.<{runTime: string, accounts: Array<{RowKey: string, acctUrl: string}>}>}
*/
function trustedTwitterAccounts(args, res) { // eslint-disable-line no-unused-vars
}
/**
* @param {{siteId: string}} args
* @returns {Promise.<{runTime: string, pages: Array<{RowKey: string, pageUrl: string}>}>}
*/
function facebookPages(args, res) { // eslint-disable-line no-unused-vars
}
/**
* @param {{siteId: string, days: number}} args
* @returns {Promise.<{analytics: Array<{Name: string, Count: number, LastUpdated: string}>}>}
*/
function facebookAnalytics(args, res) { // eslint-disable-line no-unused-vars
return new Promise((resolve, reject) => {
const pageIds = ['aljazeera', 'microsoftvan']; // todo: fetch pages for args.siteId from sitesettings
Promise.all(pageIds.map(pageId => ({Name: pageId, LastUpdated: facebookAnalyticsClient.fetchPageLastUpdatedAt(pageId), Count: -1})))
.then(analytics => resolve({analytics}))
.catch(err => reject(err));
});
}
/**
* @param {{siteId: string}} args
* @returns {Promise.<{runTime: string, filters: Array<{filteredTerms: string[], lang: string, RowKey: string}>}>}
*/
function termBlacklist(args, res) { // eslint-disable-line no-unused-vars
}
module.exports = {
sites: sites,
twitterAccounts: twitterAccounts,
trustedTwitterAccounts: trustedTwitterAccounts,
facebookPages: facebookPages,
facebookAnalytics: facebookAnalytics,
termBlacklist: termBlacklist
};
| JavaScript | 0 | @@ -139,442 +139,1852 @@
');%0A
-%0A/**%0A * @param %7B%7BsiteId: string%7D%7D args%0A * @returns %7BPromise.%3C%7BrunTime: string, sites: Array%3C%7Bname: string, properties: %7BtargetBbox: number%5B%5D, defaultZoomLevel: number, logo: string, title: string, defaultLocation: number%5B%5D, storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string%5B%5D%7D%7D%3E%7D%3E%7D%0A */%0Afunction sites(args, res) %7B // eslint-disable-line no-unused-vars
+const cassandraConnector = require('../../clients/cassandra/CassandraConnector');%0A%0Afunction cassandraRowToSite(row) %7B%0A return %7B%0A name: row.sitename,%0A properties: %7B%0A targetBbox: row.geofence,%0A defaultZoomLevel: row.defaultzoom,%0A logo: row.logo,%0A title: row.title,%0A defaultLocation: row.geofence,%0A // TODO: Ask what the following commented properties map to:%0A // storageConnectionString: String,%0A // featuresConnectionString: String,%0A // mapzenApiKey: String,%0A // fbToken: String,%0A supportedLanguages: row.languages%0A %7D%0A %7D;%0A%7D%0A%0A/**%0A * @param %7B%7BsiteId: string%7D%7D args%0A * @returns %7BPromise.%3C%7BrunTime: string, sites: Array%3C%7Bname: string, properties: %7BtargetBbox: number%5B%5D, defaultZoomLevel: number, logo: string, title: string, defaultLocation: number%5B%5D, storageConnectionString: string, featuresConnectionString: string, mapzenApiKey: string, fbToken: string, supportedLanguages: string%5B%5D%7D%7D%3E%7D%3E%7D%0A */%0Afunction sites(args, res) %7B // eslint-disable-line no-unused-vars%0A const startTime = Date.now();%0A%0A return new Promise((resolve, reject) =%3E %7B%0A const siteId = args.siteId;%0A if (!siteId) %7B%0A return reject(%22No site id to fetch specified%22);%0A %7D%0A%0A const siteById = 'SELECT * FROM fortis.sitesettings WHERE id = ?';%0A cassandraConnector.executeQuery(siteById, %5BsiteId%5D)%0A // .catch(err =%3E reject(err))%0A .then(rows =%3E %7B%0A if (rows.length %3C 1) %7B%0A return reject(%60Could not find site with id $%7BsiteId%7D%60);%0A %7D%0A if (rows.length %3E 1) %7B%0A return reject(%60Got more than one ($%7Brows.length%7D) site with id $%7BsiteId%7D%60);%0A %7D%0A%0A const site = cassandraRowToSite(rows%5B0%5D);%0A const siteCollection = Object.assign(%7B%7D, %7BrunTime: %22%22 + (Date.now() - startTime), sites: %5B site %5D%7D);%0A resolve(siteCollection);%0A %7D)%0A .catch(err =%3E reject(err))%0A ;%0A %7D);
%0A%7D%0A%0A
|
1cfdf1d15d5a403c752f17cb7b0d4a30f20336ce | remove unused leftovers from when Editor had selector logic | Selector.js | Selector.js | define(["dojo/on", "dojo/aspect", "dojo/_base/sniff", "put-selector/put", "dojo/query"], function(on, aspect, has, put, query){
return function(column, type){
// accept arguments as parameters to Selector function, or from column def
column.type = type = type || column.type;
column.sortable = false;
var grid;
function onSelect(event){
if(event.type == "dgrid-cellfocusin" && (event.parentType == "mousedown" || event.keyCode != 32)){
// ignore "dgrid-cellfocusin" from "mousedown" and any keystrokes other than spacebar
return;
}
var row = grid.row(event), lastRow = grid._lastSelected && grid.row(grid._lastSelected);
if(type == "radio"){
if(!lastRow || lastRow.id != row.id){
grid.clearSelection();
grid.select(row, null, true);
grid._lastSelected = row.element;
}
}else{
if(row){
lastRow = event.shiftKey ? lastRow : null;
grid.select(row, lastRow||null, lastRow ? undefined : null);
grid._lastSelected = row.element;
}else{
put(this, (grid.allSelected ? "!" : ".") + "dgrid-select-all");
grid[grid.allSelected ? "clearSelection" : "selectAll"]();
}
}
}
function setupSelectionEvents(){
// register one listener at the top level that receives events delegated
grid._hasSelectorInputListener = true;
aspect.around(grid, "_handleSelect", function(_handleSelect){
return function(event, currentTarget){
var target = event.target;
// work around iOS potentially reporting text node as target
if(target.nodeType == 3){ target = target.parentNode; }
while(!query.matches(target, ".dgrid-selector-cell", grid.contentNode)){
if(target == grid.contentNode || !(target = target.parentNode)){
break;
}
}
if(!target || target == grid.contentNode){
_handleSelect.call(this, event, currentTarget);
}else{
onSelect.call(target, event);
}
};
});
aspect.before(grid, "_initSelectionEvents", function(){
on(this.headerNode, ".dgrid-selector-cell:mousedown,.dgrid-selector-cell:dgrid-cellfocusin", onSelect);
});
}
var renderInput = typeof type == "function" ? type : function(value, cell, object){
var input = cell.input || (cell.input = put(cell, "div.ui-icon.dgrid-selector-input.dgrid-selector-"+type, {
tabIndex: isNaN(column.tabIndex) ? -1 : column.tabIndex
}));
if(!grid._hasSelectorInputListener){
setupSelectionEvents();
}
return input;
};
column.renderCell = function(object, value, cell, options, header){
if(!grid){
grid = column.grid;
}
var row = object && grid.row(object);
value = row && grid.selection[row.id];
if(header && (type == "radio" || typeof object == "string")){
cell.appendChild(document.createTextNode(object||""));
if(!grid._hasSelectorInputListener){
setupSelectionEvents();
}
}else{
renderInput(value, cell, object);
}
};
column.renderHeaderCell = function(th){
column.renderCell(column.label || {}, null, th, null, true);
};
var cn = column.className;
column.className = "dgrid-selector-cell" + (cn ? "." + cn : "");
return column;
};
});
| JavaScript | 0.000001 | @@ -2212,36 +2212,8 @@
ut =
- cell.input %7C%7C (cell.input =
put
@@ -2343,17 +2343,16 @@
ex%0A%09%09%09%7D)
-)
;%0A%0A%09%09%09if
|
341d4be486f0712653e882318d3711c219d87f17 | missing displayName | Triangle.js | Triangle.js | 'use strict';
import React from 'react';
import {
StyleSheet,
View
} from 'react-native';
var createReactClass = require('create-react-class');
var PropTypes = require('prop-types')
var Triangle = createReactClass({
propTypes: {
direction: PropTypes.oneOf(['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']),
width: PropTypes.number,
height: PropTypes.number,
color: PropTypes.string,
},
getDefaultProps: function() {
return {
direction: 'up',
width: 0,
height: 0,
color: 'white',
};
},
_borderStyles() {
if (this.props.direction == 'up') {
return {
borderTopWidth: 0,
borderRightWidth: this.props.width/2.0,
borderBottomWidth: this.props.height,
borderLeftWidth: this.props.width/2.0,
borderTopColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: this.props.color,
borderLeftColor: 'transparent',
};
} else if (this.props.direction == 'right') {
return {
borderTopWidth: this.props.height/2.0,
borderRightWidth: 0,
borderBottomWidth: this.props.height/2.0,
borderLeftWidth: this.props.width,
borderTopColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: 'transparent',
borderLeftColor: this.props.color,
};
} else if (this.props.direction == 'down') {
return {
borderTopWidth: this.props.height,
borderRightWidth: this.props.width/2.0,
borderBottomWidth: 0,
borderLeftWidth: this.props.width/2.0,
borderTopColor: this.props.color,
borderRightColor: 'transparent',
borderBottomColor: 'transparent',
borderLeftColor: 'transparent',
};
} else if (this.props.direction == 'left') {
return {
borderTopWidth: this.props.height/2.0,
borderRightWidth: this.props.width,
borderBottomWidth: this.props.height/2.0,
borderLeftWidth: 0,
borderTopColor: 'transparent',
borderRightColor: this.props.color,
borderBottomColor: 'transparent',
borderLeftColor: 'transparent',
};
} else if (this.props.direction == 'up-left') {
return {
borderTopWidth: this.props.height,
borderRightWidth: this.props.width,
borderBottomWidth: 0,
borderLeftWidth: 0,
borderTopColor: this.props.color,
borderRightColor: 'transparent',
borderBottomColor: 'transparent',
borderLeftColor: 'transparent',
};
} else if (this.props.direction == 'up-right') {
return {
borderTopWidth: 0,
borderRightWidth: this.props.width,
borderBottomWidth: this.props.height,
borderLeftWidth: 0,
borderTopColor: 'transparent',
borderRightColor: this.props.color,
borderBottomColor: 'transparent',
borderLeftColor: 'transparent',
};
} else if (this.props.direction == 'down-left') {
return {
borderTopWidth: this.props.height,
borderRightWidth: 0,
borderBottomWidth: 0,
borderLeftWidth: this.props.width,
borderTopColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: 'transparent',
borderLeftColor: this.props.color,
};
} else if (this.props.direction == 'down-right') {
return {
borderTopWidth: 0,
borderRightWidth: 0,
borderBottomWidth: this.props.height,
borderLeftWidth: this.props.width,
borderTopColor: 'transparent',
borderRightColor: 'transparent',
borderBottomColor: this.props.color,
borderLeftColor: 'transparent',
};
} else {
console.error('Triangle.js wrong direction. ' + this.props.direction + ' is invalid. Must be one of: ' + ['up', 'right', 'down', 'left', 'up-right', 'up-left', 'down-right', 'down-left']);
return {};
}
},
render: function() {
var borderStyles = this._borderStyles();
return (
<View style={[styles.triangle, borderStyles, this.props.style]}/>
)
},
});
var styles = StyleSheet.create({
triangle: {
width: 0,
height: 0,
backgroundColor: 'transparent',
borderStyle: 'solid',
},
});
module.exports = Triangle;
| JavaScript | 0.998501 | @@ -215,16 +215,48 @@
tClass(%7B
+%0A %0A displayName: 'Triangle',
%0A%0A pro
|
72edc374c18037e5cd806dc40355a903ab9e1b02 | Unsigned +username != null | Unsigned.js | Unsigned.js | javascript:
(function(){
var myPrefix = wpTextbox1.value.substring(0, wpTextbox1.selectionStart);
var mySuffix = wpTextbox1.value.substring(wpTextbox1.selectionEnd);
var username = prompt("Username");
if (username !== "") {
wpTextbox1.value = myPrefix + "{{subst:unsigned|" + username + "}}" + mySuffix;
wpSummary.value = "掛上[[T:unsigned]] ([[User:" + username + "]])";
wpMinoredit.click();
wpSave.click();
}
})();
| JavaScript | 0.944171 | @@ -214,16 +214,37 @@
e !== %22%22
+ && username !== null
) %7B%0A%09wpT
|
8437e9e1e3776683f31c82236327f822640f69d7 | check if document is defined to support :rocket: fastboot | addon/components/file-dropzone/component.js | addon/components/file-dropzone/component.js | import Ember from 'ember';
import layout from './template';
import DataTransfer from '../../system/data-transfer';
import uuid from '../../system/uuid';
const { $, get, set, computed } = Ember;
const { bind } = Ember.run;
const { service } = Ember.inject;
const DATA_TRANSFER = 'DATA_TRANSFER' + uuid.short();
let supported = (function () {
return 'draggable' in document.createElement('span');
}());
export default Ember.Component.extend({
layout,
name: null,
supported,
ondragenter: null,
ondragleave: null,
fileQueue: service(),
queue: computed('name', {
get() {
let queueName = get(this, 'name');
let queues = get(this, 'fileQueue');
return queues.find(queueName) ||
queues.create(queueName);
}
}),
didInsertElement() {
this._super();
let id = get(this, 'elementId');
let handlers = this._dragHandlers = {
dragenter: bind(this, 'didEnterDropzone'),
dragleave: bind(this, 'didLeaveDropzone'),
dragover: bind(this, 'didDragOver'),
drop: bind(this, 'didDrop')
};
Object.keys(handlers).forEach(function (key) {
$(document).on(key, `#${id}`, handlers[key]);
});
},
willDestroyElement() {
let id = get(this, 'elementId');
let handlers = this._dragHandlers || {};
Object.keys(handlers).forEach(function (key) {
$(document).off(key, `#${id}`, handlers[key]);
});
this._dropzoneEntrance = null;
this._super();
},
didEnterDropzone({ originalEvent: evt }) {
let element = get(this, 'element');
let entrance = this._dropzoneEntrance;
if (entrance == null ||
$.contains(element, entrance) ||
element === entrance) {
this._dropzoneEntrance = evt.target;
let dataTransfer = DataTransfer.create({
queue: get(this, 'queue'),
dataTransfer: evt.dataTransfer
});
this[DATA_TRANSFER] = dataTransfer;
set(this, 'active', true);
set(this, 'valid', get(dataTransfer, 'valid'));
if (this.ondragenter) {
this.ondragenter(dataTransfer);
}
}
},
didLeaveDropzone({ originalEvent: evt }) {
let element = get(this, 'element');
// If the element paired with the dragenter
// event was removed from the DOM, clear it out
// so the process can be run again.
if (!$.contains(element, this._dropzoneEntrance) &&
element !== this._dropzoneEntrance) {
this._dropzoneEntrance = null;
}
if (evt.target === this._dropzoneEntrance) {
if (this.ondragleave) {
set(this[DATA_TRANSFER], 'dataTransfer', evt.dataTransfer);
this.ondragleave(this[DATA_TRANSFER]);
this[DATA_TRANSFER] = null;
}
set(this, 'active', false);
this._dropzoneEntrance = null;
}
},
didDragOver({ originalEvent: evt }) {
set(this[DATA_TRANSFER], 'dataTransfer', evt.dataTransfer);
evt.preventDefault();
evt.stopPropagation();
},
didDrop({ originalEvent: evt }) {
// Testing support for dragging and dropping images
// from other browser windows
let url = evt.dataTransfer.getData('text/uri-list');
let html = evt.dataTransfer.getData('text/html');
if (html) {
let img = $(html)[1];
if (img.tagName === 'IMG') {
url = img.src;
}
}
if (url) {
var image = new Image();
var [filename] = url.split('/').slice(-1);
image.crossOrigin = 'anonymous';
image.onload = () => {
var canvas = document.createElement('canvas');
canvas.width = image.width;
canvas.height = image.height;
var ctx = canvas.getContext('2d');
ctx.drawImage(image, 0, 0);
if (canvas.toBlob) {
canvas.toBlob((blob) => {
let [file] = get(this, 'queue')._addFiles([blob]);
set(file, 'name', filename);
});
} else {
let binStr = atob(canvas.toDataURL().split(',')[1]),
len = binStr.length,
arr = new Uint8Array(len);
for (var i=0; i<len; i++ ) {
arr[i] = binStr.charCodeAt(i);
}
let blob = new Blob([arr], { type: 'image/png' });
blob.name = filename;
let [file] = get(this, 'queue')._addFiles([blob]);
set(file, 'name', filename);
}
};
image.onerror = function (e) {
console.log(e);
};
image.src = url;
}
if (evt.preventDefault) { evt.preventDefault(); }
if (evt.stopPropagation) { evt.stopPropagation(); }
this._dropzoneEntrance = null;
set(this[DATA_TRANSFER], 'dataTransfer', evt.dataTransfer);
if (this.ondrop) {
this.ondrop(this[DATA_TRANSFER]);
}
set(this, 'active', false);
get(this, 'queue')._addFiles(get(this[DATA_TRANSFER], 'files'));
this[DATA_TRANSFER] = null;
evt.preventDefault();
evt.stopPropagation();
}
});
| JavaScript | 0 | @@ -346,16 +346,62 @@
return
+window.hasOwnProperty('document') &&%0A
'draggab
|
e38612fb5788a7708e6e0573b53617a3925c64e7 | integrate geo angular functionality | routes/bike-route.js | routes/bike-route.js | 'use strict';
const Router = require('express').Router;
const jsonParser = require('body-parser').json();
const createError = require('http-errors');
const debug = require('debug')('fit-O-matic:bike-route');
const fs = require('fs');
const path = require('path');
const del = require('del');
const multer = require('multer');
const s3methods = require('../lib/s3-methods.js');
const dataDir = `${__dirname}/../data`;
const upload = multer({dest: dataDir });
const bearerAuth = require('../lib/bearer-auth-middleware.js');
const Bike = require('../model/bike.js');
const Mfr = require('../model/mfr.js');
const bikeRouter = module.exports = Router();
bikeRouter.post('/api/mfr/:mfrID/bike', bearerAuth, upload.single('image'), jsonParser, function(req, res, next) {
debug('POST: /api/mfr/:mfrID/bike');
if(!req.body.bikeName) return next(createError(400, 'Need a bike name'));
if(!req.body.category) return next(createError(400, 'Need a category'));
if(!req.file) return next(createError(400, 'Need a photo'));
if(!req.file.path) return next(createError(500, 'file not saved'));
let ext = path.extname(req.file.originalname);
let params = {
ACL: 'public-read',
Bucket: process.env.AWS_BUCKET,
Key: `${req.file.filename}${ext}`,
Body: fs.createReadStream(req.file.path)
};
s3methods.uploadObjectProm(params)
.then( s3data => {
del([`${dataDir}/*`]);
req.body.photoKey = s3data.Key;
req.body.photoURI = s3data.Location;
Mfr.findById(req.params.mfrID)
.then( mfr => {
if(!mfr) return next(createError(400, 'Mfr not found'));
req.body.mfrID = mfr._id;
debug('got here', req.body);
return Bike(req.body).save()
.then( bike => {
res.json(bike);
});
});
})
.catch(next);
});
bikeRouter.get('/api/bike/:bikeID', bearerAuth, function(req, res, next) {
debug('GET /api/bike/:bikeID');
if(!req.params.bikeID) return next(createError(400, 'need a bike ID'));
Bike.findById(req.params.bikeID)
.then( bike => {
if(!bike) return next(createError(400, 'bike not found'));
res.json(bike);
})
.catch(next);
});
bikeRouter.get('/api/bikes/:mfrID', bearerAuth, function(req, res, next) {
debug('GET /api/bikes/:mfrID');
Bike.find({mfrID: req.params.mfrID})
.then( bikes => {
if(!bikes) return next(createError(400, 'no bikes'));
res.json(bikes);
})
.catch(next);
});
//TODO Write some tests
bikeRouter.get('/api/bikes', bearerAuth, function(req, res, next) {
debug('GET /api/bikes');
Bike.find()
.then( bikes => {
if(!bikes[0]) return res.sendStatus(204);
res.json(bikes);
})
.catch(next);
});
bikeRouter.put('/api/bike/:bikeID', bearerAuth, function(req, res, next) {
debug('PUT /api/bike/:bikeID');
if(Object.keys(req.body).length === 0) return next(createError(400, 'bad request'));
Bike.findByIdAndUpdate(req.params.bikeID, req.body, {new: true})
.then( bike => {
res.json(bike);
})
.catch(next);
});
bikeRouter.put('/api/photo/bike/:id', bearerAuth, upload.single('image'), jsonParser, function(req, res, next){
debug('PUT: /api/photo/bike/:id');
if(!req.file) return next(createError(400, 'photo required'));
let ext = path.extname(req.file.originalname);
let params = {
ACL: 'public-read',
Bucket: process.env.AWS_BUCKET,
Key: `${req.file.filename}${ext}`,
Body: fs.createReadStream(req.file.path)
};
s3methods.uploadObjectProm(params)
.then( s3data => {
del([`${dataDir}/*`]);
req.body.photoKey = s3data.Key;
req.body.photoURI = s3data.Location;
Bike.findByIdAndUpdate(req.params.id, req.body, {new: true})
.then( bike => {
res.json(bike);
});
})
.catch(next);
});
//TODO tests for both put routes
| JavaScript | 0.000001 | @@ -2685,32 +2685,44 @@
ID', bearerAuth,
+ jsonParser,
function(req, r
@@ -2763,24 +2763,77 @@
/:bikeID');%0A
+ debug('------------------------------', req.body);%0A
if(Object.
@@ -2903,25 +2903,24 @@
request'));%0A
-%0A
Bike.findB
|
4c6b04ecff94be5439eadadf1ecb80437d505800 | delete committee | routes/committees.js | routes/committees.js | var express = require('express');
var router = express.Router();
router
.route('/')
.get(function(req, res, next) {
req.models
.committee
.find({})
.then(function(committees){
res.send(committees);
})
.catch(function(err){
next(err)
})
})
.post(function(req, res, next) {
req.models
.committee
.create(req.body.committee)
.then(function(committee){
res.send(committee);
})
.catch(function(err){
err.status = 422;
next(err);
})
});
router
.route('/:id')
.get(function(req, res, next) {
req.models
.committee
.findOne(req.params.id)
.then(function(committee){
if(!committee) {
next({
status: 404,
message: 'Committee with id ' + req.params.id + ' not found'
});
} else {
res.send(committee);
}
});
})
.put(function(req, res, next) {
req.models
.committee
.update(req.params.id, req.body.committee)
.then(function(committee){
res.send(committee);
})
.catch(function(err){
err.status = 422;
next(err);
});
})
.delete(function(req, res, next) {
});
module.exports = router;
| JavaScript | 0.000001 | @@ -1349,16 +1349,154 @@
next) %7B%0A
+ req.models%0A .committee%0A .destroy(req.params.id)%0A .then(function()%7B%0A res.status(204).send();%0A %7D)
%0A %7D);
|
90b64339dc66063645a00a961554c7f9c6610268 | fix config editForm is not defined | routes/configEdit.js | routes/configEdit.js | 'use strict';
const linz = require('../');
/* GET /admin/config/:config/overview */
var route = function (req, res, next) {
linz.api.model.generateForm(req.linz.model, {
record: req.linz.record,
type: 'edit',
})
.then(editForm => Promise.all([
linz.api.views.getScripts(req, res, [
{
src: '//cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.10/handlebars.min.js',
integrity: 'sha256-0JaDbGZRXlzkFbV8Xi8ZhH/zZ6QQM0Y3dCkYZ7JYq34=',
crossorigin: 'anonymous',
},
{
src: `${linz.get('admin path')}/public/js/jquery.binddata.js`,
},
{
src: `${linz.get('admin path')}/public/js/documentarray.js?v1`,
},
{
src: `${linz.get('admin path')}/public/js/model/edit.js`,
},
]),
linz.api.views.getStyles(req, res),
]))
.then(([scripts, styles]) => res.render(linz.api.views.viewPath('configEdit.jade'), {
actionUrl: linz.api.url.getAdminLink(req.linz.config, 'save', req.linz.record._id),
cancelUrl: linz.api.url.getAdminLink(req.linz.config, 'list'),
form: editForm.render(),
record: req.linz.record,
scripts,
styles,
}))
.catch(next);
};
module.exports = route;
| JavaScript | 0.000001 | @@ -120,16 +120,40 @@
ext) %7B%0A%0A
+ let editForm = %7B%7D;%0A%0A
linz
@@ -274,19 +274,69 @@
hen(
-editForm =%3E
+(form) =%3E %7B%0A%0A editForm = form;%0A%0A return
Pro
@@ -346,16 +346,20 @@
e.all(%5B%0A
+
@@ -408,34 +408,42 @@
-%7B%0A
+ %7B%0A
@@ -546,16 +546,20 @@
+
+
integrit
@@ -636,16 +636,20 @@
+
crossori
@@ -662,24 +662,28 @@
anonymous',%0A
+
@@ -697,34 +697,42 @@
-%7B%0A
+ %7B%0A
@@ -806,32 +806,36 @@
+
%7D,%0A
@@ -829,34 +829,42 @@
-%7B%0A
+ %7B%0A
@@ -939,32 +939,36 @@
+
%7D,%0A
@@ -962,34 +962,42 @@
-%7B%0A
+ %7B%0A
@@ -1066,35 +1066,43 @@
-%7D,%0A
+ %7D,%0A
%5D),%0A
@@ -1105,32 +1105,36 @@
%5D),%0A
+
linz.api.views.g
@@ -1161,18 +1161,34 @@
-%5D)
+ %5D);%0A%0A %7D
)%0A
|
99a6998f0837c51a2c17555037025344200fad6c | Add test case to check if belongs to relation returns correct object | test/feature/relations/BelongsTo.spec.js | test/feature/relations/BelongsTo.spec.js | import { createStore, createState } from 'test/support/Helpers'
import Model from 'app/model/Model'
describe('Features – Relations – Belongs To', () => {
class User extends Model {
static entity = 'users'
static fields () {
return {
id: this.attr(null)
}
}
}
class Post extends Model {
static entity = 'posts'
static fields () {
return {
id: this.attr(null),
user_id: this.attr(null),
user: this.belongsTo(User, 'user_id')
}
}
}
it('can create data containing the belongs to relation', () => {
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user_id: 1,
user: { id: 1 }
}
})
const expected = createState({
users: {
'1': { $id: 1, id: 1 }
},
posts: {
'1': { $id: 1, id: 1, user_id: 1, user: 1 }
}
})
expect(store.state.entities).toEqual(expected)
})
it('can create data when the belongs to relation is `null`', () => {
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user_id: 1,
user: null
}
})
const expected = createState({
users: {},
posts: {
'1': { $id: 1, id: 1, user_id: 1, user: null }
}
})
expect(store.state.entities).toEqual(expected)
})
it('can generate relation field', () => {
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user: { id: 1 }
}
})
const expected = createState({
users: {
'1': { $id: 1, id: 1 }
},
posts: {
'1': { $id: 1, id: 1, user_id: 1, user: 1 }
}
})
expect(store.state.entities).toEqual(expected)
})
it('can resolve the belongs to relation', () => {
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user: { id: 1 }
}
})
const expected = {
$id: 1,
id: 1,
user_id: 1,
user: {
$id:1,
id: 1
}
}
const post = store.getters['entities/posts/query']().with('user').find(1)
expect(post).toEqual(expected)
})
it('can resolve belongs to relation which its id is 0', () => {
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user: { id: 0 }
}
})
const expected = {
$id: 1,
id: 1,
user_id: 0,
user: {
$id: 0,
id: 0
}
}
const post = store.getters['entities/posts/query']().with('user').first()
expect(post).toEqual(expected)
})
it('can resolve belongs to relation with custom foreign key', () => {
class User extends Model {
static entity = 'users'
static fields () {
return {
id: this.attr(null),
post_id: this.attr(null)
}
}
}
class Post extends Model {
static entity = 'posts'
static fields () {
return {
id: this.attr(null),
user_id: this.attr(null),
user: this.belongsTo(User, 'user_id', 'post_id')
}
}
}
const store = createStore([{ model: User }, { model: Post }])
store.dispatch('entities/posts/create', {
data: {
id: 1,
user_id: 2,
user: { id: 1, post_id: 2 }
}
})
const expected = {
$id: 1,
id: 1,
user_id: 2,
user: {
$id: 1,
id: 1,
post_id: 2
}
}
const post = store.getters['entities/posts/query']().with('user').find(1)
expect(post).toEqual(expected)
})
})
| JavaScript | 0.000006 | @@ -1925,32 +1925,485 @@
expected)%0A %7D)%0A%0A
+ it('returns created record from %60create%60 method', async () =%3E %7B%0A const store = createStore(%5B%7B model: User %7D, %7B model: Post %7D%5D)%0A%0A const result = await store.dispatch('entities/posts/create', %7B%0A data: %7B%0A id: 1,%0A user_id: 1,%0A user: %7B id: 1 %7D%0A %7D%0A %7D)%0A%0A const expected = %7B%0A users: %5B%7B $id: 1, id: 1 %7D%5D,%0A posts: %5B%7B $id: 1, id: 1, user_id: 1, user: null %7D%5D%0A %7D%0A%0A expect(result).toEqual(expected)%0A %7D)%0A%0A
it('can resolv
|
6b9f60ecc1eb4ea8f4c1cdb95ad41a6b3a630d6e | Add credited instrument option | mbz-setinstrument.user.js | mbz-setinstrument.user.js | // ==UserScript==
// @name MusicBrainz: Batch-set recording-artist instrument
// @author loujine
// @version 2015.6.8
// @downloadURL https://bitbucket.org/loujine/musicbrainz-scripts/src/default/mbz-setinstrument.user.js
// @description musicbrainz.org: Convert to "string" instrument AR on selected recordings
// @compatible firefox+greasemonkey quickly tested
// @licence CC BY-NC-SA 3.0 (https://creativecommons.org/licenses/by-nc-sa/3.0/)
// @include http*://*musicbrainz.org/release/*/edit-relationships
// @grant none
// @run-at document-end
// ==/UserScript==
'use strict';
// from musicbrainz-server/root/static/scripts/tests/typeInfo.js
var linkTypeInstrument = '148',
linkTypeOrchestra = '150',
linkTypePerformer = '156',
attrIdPiano = 180,
attrIdStrings = 69;
function setInstrument(attrId) {
var recordings = MB.relationshipEditor.UI.checkedRecordings(),
attr = { type: MB.attrInfoByID[attrId] };
recordings.forEach(function(recording) {
recording.relationships().forEach(function(rel) {
var linkType = rel.linkTypeID().toString();
if (linkType === linkTypeOrchestra ||
linkType === linkTypePerformer) {
rel.linkTypeID(linkTypeInstrument);
rel.setAttributes([attr]);
rel.attributes()[0].creditedAs('string quartet');
}
});
});
}
var elm = document.createElement('input');
elm.id = 'batchsetinstrument';
elm.type = 'button';
elm.value = 'Batch-set "String Quartet" instrument';
var tabdiv = document.getElementsByClassName('tabs')[0];
tabdiv.parentNode.insertBefore(elm, tabdiv.nextSibling);
document.getElementById('batchsetinstrument').addEventListener('click', function(event) {
setInstrument(attrIdStrings);
var vm = MB.releaseRelationshipEditor;
vm.editNote('Use "strings" instrument AR for a String Quartet artist');
}, false);
| JavaScript | 0.000001 | @@ -839,24 +839,32 @@
function set
+Credited
Instrument(a
@@ -868,16 +868,24 @@
t(attrId
+, credit
) %7B%0A
@@ -1351,16 +1351,71 @@
attr%5D);%0A
+ if (rel.attributes().length %3E 0) %7B%0A
@@ -1457,26 +1457,34 @@
dAs(
-'string quartet');
+credit);%0A %7D
%0A
@@ -1524,16 +1524,18 @@
%0Avar elm
+SQ
= docum
@@ -1565,16 +1565,18 @@
t');%0Aelm
+SQ
.id = 'b
@@ -1583,27 +1583,35 @@
atch
+-
set
-instrumen
+-string-quarte
t';%0Aelm
+SQ
.typ
@@ -1627,16 +1627,18 @@
on';%0Aelm
+SQ
.value =
@@ -1771,16 +1771,18 @@
fore(elm
+SQ
, tabdiv
@@ -1827,28 +1827,34 @@
d('batch
+-
set
-instrumen
+-string-quarte
t').addE
@@ -1897,42 +1897,8 @@
) %7B%0A
- setInstrument(attrIdStrings);%0A
@@ -1936,16 +1936,76 @@
Editor;%0A
+ setCreditedInstrument(attrIdStrings, 'string quartet');%0A
vm.e
|
52cba41e127d152fde474c42a49d6d2fa17cbc3b | fix queue link opening log modal on mobile rev (bug 910828) | media/js/mkt/reviewers.js | media/js/mkt/reviewers.js | require(['prefetchManifest']);
(function() {
if (z.capabilities.mobile) {
z.body.addClass('mobile');
}
if (z.capabilities.tablet) {
z.body.addClass('tablet');
}
if (z.capabilities.desktop) {
z.body.addClass('desktop');
}
// Reviewer tool search.
initAdvancedMobileSearch();
initMobileMenus();
initClearSearch();
if ($('.theme-search').length) {
initSearch(true);
} else {
initSearch();
}
})();
function initClearSearch() {
var $clear = $('.clear-queue-search'),
$appQueue = $('.search-toggle'),
$search = $('.queue-search'),
$searchIsland = $('#search-island');
$clear.click(_pd(function() {
$appQueue.show();
$('#id_q').val('');
$clear.hide();
$searchIsland.hide();
}));
}
function initSearch(isTheme) {
var search_results = getTemplate($('#queue-search-template'));
var no_results = getTemplate($('#queue-search-empty-template'));
var $clear = $('.clear-queue-search'),
$appQueue = $('.search-toggle'),
$search = $('.queue-search'),
$searchIsland = $('#search-island');
if ($search.length) {
// An underscore template for more advanced rendering.
var search_result_row = _.template($('#queue-search-row-template').html());
var apiUrl = $search.data('api-url');
var review_url = $search.data('review-url');
var statuses = $searchIsland.data('statuses');
$search.on('submit', 'form', _pd(function() {
var $form = $(this);
$.get(apiUrl, $form.serialize()).done(function(data) {
// Hide app queue.
$appQueue.hide();
$clear.show();
// Show results.
if (data.meta.total_count === 0) {
$searchIsland.html(no_results({})).show();
} else {
var results = [];
$.each(data.objects, function(i, item) {
if (isTheme) {
item = buildThemeResultRow(item, review_url,
statuses);
} else {
item = buildAppResultRow(item, review_url,
statuses);
}
results.push(search_result_row(item));
});
$searchIsland.html(
search_results({rows: results.join('')})).show();
}
});
}));
}
}
function buildAppResultRow(app, review_url, statuses) {
var flags = [];
app.review_url = review_url.replace('__slug__', app.slug);
app.status = statuses[app.status];
if (app.latest_version.status) {
app.status += format(' | {0}', statuses[app.latest_version.status]);
}
if (app.is_packaged) {
flags.push({suffix: 'packaged-app', title: gettext('Packaged App')});
}
if (app.latest_version) {
if (app.latest_version.is_privileged) {
flags.push({suffix: 'privileged-app', title: gettext('Privileged App')});
}
if (app.latest_version.has_info_request) {
flags.push({suffix: 'info', title: gettext('More Information Requested')});
}
if (app.latest_version.has_editor_comment) {
flags.push({suffix: 'editor', title: gettext('Contains Editor Comment')});
}
}
if (app.premium_type == 'premium-inapp' || app.premium_type == 'premium') {
flags.push({suffix: 'premium', title: gettext('Premium App')});
}
if (app.is_escalated) {
flags.push({suffix: 'escalated', title: gettext('Escalated')});
}
app.flags = flags;
if (app.price === null) {
app.price = gettext('Free');
}
return app;
}
function buildThemeResultRow(theme, review_url, statuses) {
// Add some extra pretty attrs for the template.
theme.name = theme.name[0];
// Rather resolve URLs in backend, infer from slug.
theme.review_url = review_url.replace(
'__slug__', theme.slug);
theme.status = statuses[theme.status];
return theme;
}
function initMobileMenus() {
// Nav action menu overlays for queues and logs.
var $logTabOverlay = $('#log-tab-overlay');
var $queueTabOverlay = $('#queue-tab-overlay');
$('.trigger-queues').click(function(e) {
if (z.capabilities.mobile || z.capabilities.tablet) {
e.preventDefault();
$logTabOverlay.show();
}
});
$('.trigger-logs').click(_pd(function() {
if (z.capabilities.mobile || z.capabilities.tablet) {
$logTabOverlay.show();
}
}));
$('.nav-action-menu button').click(_pd(function() {
// Turn buttons into links on nav tab overlays.
var $button = $(this);
if ($button.data('url') == '#cancel') {
$queueTabOverlay.hide();
$logTabOverlay.hide();
} else {
window.location.href = $button.data('url');
}
}));
}
function initAdvancedMobileSearch() {
// Value selectors for mobile advanced search.
$('.value-select-field').click(function() {
$(this).next('div[role="dialog"]').show();
});
$('div[role="dialog"] .cancel').click(_pd(function() {
$(this).closest('div[role="dialog"]').hide();
}));
var $advSearch = $('.advanced-search.desktop');
$('.advanced-search li[role="option"] input').change(
syncPrettyMobileForm).each(function(i, input) {
/* Since Gaia form doesn't use selects, browser does not populate
our Gaia form after submitting with GET params. We sync data
between the populated hidden desktop advanced search form to our
mobile Gaia form. */
var $input = $(input);
var val = $input.attr('value');
if (val) {
/* If input checked/selected in the desktop form, check/select
it in our Gaia form. */
var nameSelect = '[name="' + $input.attr('name') + '"]';
var $inputs = $(nameSelect + ' option[value="' + val + '"]:selected',
$advSearch);
$inputs = $inputs.add(
$('input[value="' + val + '"]:checked' + nameSelect,
$advSearch));
if ($inputs.length) {
$input.prop('checked', true);
}
}
});
syncPrettyMobileForm();
}
function syncPrettyMobileForm() {
/* The pretty mobile visible form does not contain actual form elements.
Value selector form elements are hidden and contained within overlays.
When we check a value our form in the overlay, we sync the pretty
representation of the form. */
// Value selector is the name of the Gaia mobile radio/checkbox form.
var $valSelectFields = $('.value-select-field');
$valSelectFields.each(function(index, valSelectField) {
var $valSelectField = $(valSelectField);
var name = $valSelectField.data('field');
var valStrs = [];
var $checkedInputs = $('li[role="option"] input[name="' + name + '"]:checked');
$checkedInputs.each(function(index, input) {
// Build pretty string.
valStrs.push($(input).next('span').text().trim());
});
// Sync new selected value to our span in the pretty form.
var firstPrettyVal = $('li[role="option"]:first-child span',
$valSelectField.next('div[role="dialog"]')).text();
$('.' + name + '.selected-val span').text(
valStrs.length ? valStrs.join() :
$('.multi-val', $valSelectField).length ? gettext('Any') :
firstPrettyVal);
});
}
| JavaScript | 0 | @@ -4596,35 +4596,37 @@
);%0A $
-log
+queue
TabOverlay.show(
|
7056c1a244a0e152600578cfd2e28210657cd951 | rename _v to _value in repeat scope | avalon/bundle/angulate-0.1.0/angulate.js | avalon/bundle/angulate-0.1.0/angulate.js | /**
* AngulateJS v0.1.0
* Copyright 2013, Hybrid Labs
* License: MIT
*/
;
(function(global) {
'use strict';
var angular = global.angular;
var angulate = global.angulate = angular.module('angulate', []);
var templates = {};
/* Helpers */
function exception(element) {
var args = Array.prototype.slice.call(arguments);
if (angular.isObject(element)) {
console.error('Element:', element);
args.shift();
}
throw args.join(' ');
}
function leave($animate, element) {
if (element.parent().length) {
$animate.leave(element);
}
}
function enter($animate, element, after) {
if (!element.parent().length) {
$animate.enter(element, null, after);
}
}
function attr(element, attrs) {
var attr;
angular.forEach(attrs.$attr, function(a) {
if (a[0] === ':') {
if (attr) {
exception(element, 'Element has multiple bindings');
}
attr = a.slice(1);
}
});
if (!attr) {
exception(element, 'Element has no binding attribute')
}
return attr;
}
function equalityScope(scope) {
// Patch $watch and $watchCollection to use object equality
var _$watch = scope.$watch;
scope.$watch = function $watch(watch, listener) {
return _$watch.apply(this, [watch, listener, true]);
};
scope.$watchCollection = function $watchCollection(watch, listener) {
return _$watch.apply(this, [watch, listener, true]);
};
return scope;
}
function registerTemplate(name, element) {
if (angular.isString(element)) {
element = angular.element(document.querySelector('#' + element));
}
templates[name] = element;
}
/* Directives */
bindDirective.$inject = ['$compile', '$animate', '$parse'];
function bindDirective($compile, $animate, $parse) {
function forkElement(element, attr, attrValue, scope) {
var clone = element.clone()
.attr(attr, attrValue)
.removeAttr('bind');
$compile(clone)(scope);
return {
element: clone,
scope: scope
};
}
function repeatScopeSearch(scope, name, level) {
if (!scope) {
return undefined;
}
return scope._v && scope._v[name] != undefined ?
(new Array(level + 1)).join('$parent.') + '_v.' + name :
repeatScopeSearch(scope.$parent, name, level + 1);
}
function link(scope, element, attrs) {
var bind = attr(element, attrs);
var repeatScopeValue = scope._v == undefined ? undefined :
repeatScopeSearch(scope, bind, 0);
if (element.attr('model')) {
// Replace this element with a clone with ng-model
var model = forkElement(element, 'ng-model', bind,
scope.$parent);
element.replaceWith(model.element);
}
else {
var display = element.css('display');
var bindName = angular.isFunction($parse(bind)(scope)) ?
bind + '(this)' : bind;
var repeat = '_v in ' + bindName + ' track by ' +
(attrs.track || '$index');
// Create repeat element after this element
repeat = forkElement(element, 'ng-repeat', repeat,
equalityScope(scope.$parent.$new()));
element.after(repeat.element);
// Watch changes and adjust view depending bind data type
scope.$watch(bindName, function bindWatch(v) {
if (element.attr('leaf')) {
element.text(v == undefined ? '' : v);
repeat.scope[bind] = null;
}
else {
if (!v) {
leave($animate, element);
return;
}
element.css('display', display);
if (angular.isArray(v)) {
// Propagate data from parent scope
delete repeat.scope[bind];
leave($animate, element);
}
else {
// Hide data from parent scope
repeat.scope[bind] = null;
enter($animate, element, repeat.element);
// Extend scope binding
if (angular.isObject(v)) {
angular.extend(scope, v);
}
}
}
}, true);
// Extend repeat scope binding
if (repeatScopeValue) {
scope.$watch(repeatScopeValue, function repeatScopeWatch(v) {
scope[bind] = v;
});
}
}
}
return {
restrict: 'EA',
scope: true,
compile: function(element, attr) {
var model = ['INPUT', 'SELECT'];
var tag = element.prop('tagName').toUpperCase();
if (model.indexOf(tag) != -1) {
attr.$set('model', true);
}
else {
attr.$set('model', undefined);
if (element.contents().length == 0) {
attr.$set('leaf', true);
}
else {
attr.$set('leaf', undefined);
}
}
return link;
}
}
}
ifDirective.$inject = ['$animate', '$parse'];
function ifDirective($animate, $parse) {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
var condition = attr(element, attrs);
var conditionName = angular.isFunction($parse(condition)(scope)) ?
condition + '(this)' : condition;
var negate = attrs.not != undefined;
var marker = negate ?
document.createComment('if: ' + conditionName) :
document.createComment('if not: ' + conditionName);
// Insert marker to track DOM location
marker = angular.element(marker);
element.after(marker);
element.remove();
marker.after(element);
scope.$watch(conditionName, function ifWatch(v) {
if (negate ? !v : v) {
enter($animate, element, marker);
}
else {
leave($animate, element);
}
}, true);
}
}
}
function templateDirective() {
return {
restrict: 'EA',
compile: function(element, attrs) {
var name = attr(element, attrs);
element.replaceWith(
angular.element('<script type="text/x-avalon-template">')
.html(element.html())
);
registerTemplate(name, element);
}
}
}
function componentDirective() {
return {
restrict: 'EA',
controller: ['$scope', '$element', '$attrs', '$injector',
function scopeController($scope, $element, $attrs, $injector) {
var controller = global[attr($element, $attrs)];
if (controller) {
$injector.invoke(controller, this, {
$scope: $scope,
$element: $element
});
}
}
],
compile: function(element, attrs) {
var name = attr(element, attrs);
if (!templates[name]) {
exception(element, 'Template not found', name);
}
element.html(templates[name].html());
}
}
}
// Register directives
angulate.directive('bind', bindDirective);
angulate.directive('if', ifDirective);
angulate.directive('template', templateDirective);
angulate.directive('component', componentDirective);
// Pre-create for Internet Explorer (IE)
document.createElement('bind');
document.createElement('if');
document.createElement('template');
document.createElement('component');
/* Public */
angulate.registerTemplate = registerTemplate;
})(this);
| JavaScript | 0.000019 | @@ -2327,16 +2327,20 @@
scope._v
+alue
&& scop
@@ -2343,16 +2343,20 @@
scope._v
+alue
%5Bname%5D !
@@ -2423,16 +2423,20 @@
') + '_v
+alue
.' + nam
@@ -2630,16 +2630,20 @@
scope._v
+alue
== unde
@@ -3136,16 +3136,20 @@
at = '_v
+alue
in ' +
|
0cacc1182e66fe3cc8ac68639309b1bc5c8714b2 | Remove leftover `console.log` in `clever env import` | src/models/variables.js | src/models/variables.js | 'use strict';
const readline = require('readline');
const _ = require('lodash');
const Bacon = require('baconjs');
function parseLine (line) {
const p = line.split('=');
const key = p[0];
p.shift();
const value = p.join('=');
if (line.trim()[0] !== '#' && p.length > 0) {
return [key.trim(), value.trim()];
}
return null;
};
function render (variables, addExport) {
return _(variables)
.map(({ name, value }) => {
if (addExport) {
const escapedValue = value.replace(/'/g, '\'\\\'\'');
return `export ${name}='${escapedValue}';`;
}
return `${name}=${value}`;
})
.join('\n');
};
function readFromStdin () {
return Bacon.fromBinder((sink) => {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
terminal: false,
});
const vars = {};
rl.on('line', (line) => {
const res = parseLine(line);
if (res) {
const [name, value] = res;
vars[name] = value;
}
});
rl.on('close', () => {
console.log(vars);
sink(new Bacon.Next(vars));
sink(new Bacon.End());
});
});
};
module.exports = {
parseLine,
render,
readFromStdin,
};
| JavaScript | 0 | @@ -1055,33 +1055,8 @@
%3E %7B%0A
- console.log(vars);%0A
|
63110f4ff16f093c5621b0ab5ae5676b005efe95 | Set up for TTC's TeamCity | Settings.js | Settings.js | var Settings = {
//The url that points to team city
teamCityUrl: 'http://tclive:8111',
//The main branch to show the master build status on the right hand panel on the screen
mainBranch: 'develop',
//Proxy to handle the cross domain ajax request.
// This will need to be hosted on the relevant server e.g. proxy-node.js on Node.js or proxy-aspnet.ashx on IIS
// You could write your own proxy just so long as it is hosted form the same domain as the rest of the app
proxy: 'proxy-aspnet.ashx?url=',
// If your TeamCity is set up for guest access, you can just use it. Otherwise, the moment that tc-radiate sends first request to TC, TC will
// ask the user for basic http credentials. Your browser may even offer you to save them.
useTeamCityGuest: true,
//How often to call the TeamCity webservices and update the screen
checkIntervalMs: 5000, //5000 ms = 5 seconds
//How often to refresh the build image;
buildImageIntervalMs: 3600000, //3600000 ms = 1 hour
//use this to stop the screen from updating automatically e.g. if you manually refresh it.
enableAutoUpdate: true,
}
//Allow the settings to be overridden by querystring parameters
//(url parameters are currently only treated as strings)
jQuery.extend(Settings, UrlParams);
var authType = Settings.useTeamCityGuest ? 'guestAuth' : 'httpAuth';
//----------------------
// TEAM CITY URLS
//----------------------
//The url for the list of all builds on the left hand side of the screen
Settings.buildsUrl = Settings.proxy + Settings.teamCityUrl + '/'+authType+'/app/rest/builds?locator=running:any,branch:branched:any,count:20';
//The url for the list of build types (used for mapping the build id (e.g. bt11) to the name (e.g. Website Tests)
Settings.buildTypesUrl = Settings.proxy + Settings.teamCityUrl + '/'+authType+'/app/rest/buildTypes';
//The url for the status of the build on the main branch
Settings.buildStatusUrl = Settings.proxy + Settings.teamCityUrl + '/'+authType+'/app/rest/builds/branch:' + Settings.mainBranch + ',running:any,canceled:any?'; | JavaScript | 0 | @@ -76,22 +76,35 @@
http
+s
://
-tclive:8111
+ci.travcorpservices.com
',%0A%0A
@@ -519,30 +519,8 @@
y: '
-proxy-aspnet.ashx?url=
',%0A%0A
@@ -781,19 +781,20 @@
yGuest:
-tru
+fals
e,%0A%0A
|
248123f9306c6805df7026153dd13e98113e9e77 | Fix suggestedMax in chart when there is no data to display | server/src/main/webapp/resources/js/dashboard.js | server/src/main/webapp/resources/js/dashboard.js |
"use strict";
$(function () {
//-----------------------
//- Dashboard > Authentication Requests Chart -
//-----------------------
try{
var authChartData = JSON.parse($("#authenticationChartJson").val());
console.log("authentication chart data");
console.log(authChartData);
var authenticationRequestsChartData = {
labels : authChartData.labels,
datasets : [
{
label : "Successful Login",
fill : false,
backgroundColor : "#00BE79",
data : authChartData.success
}, {
label : "Failed Attempts",
fill : false,
backgroundColor : "#F39C12",
data : authChartData.failure
}
]
};
var authenticationRequestsChartOptions = {
responsive: true,
scales: {
yAxes: [{
ticks: {
suggestedMin: 0,
suggestedMax: 1000
}
}]
}
};
console.log(authenticationRequestsChartData);
console.log(authenticationRequestsChartOptions);
// Get context with jQuery - using jQuery's .get() method.
var authenticationRequestsChartCanvas = $("#authenticationRequestsChart").get(0).getContext("2d");
// This will get the first returned node in the jQuery collection.
//Create the line chart
var authenticationRequestsChart = new Chart(authenticationRequestsChartCanvas, {
type: 'line',
data: authenticationRequestsChartData,
options: authenticationRequestsChartOptions
});
}catch(error){
console.log(error);
}
}); | JavaScript | 0 | @@ -828,18 +828,16 @@
dMax: 10
-00
%0A
|
926b3ff4a844a20c6f718aa1ed1974d382850145 | remove useless debug log | UIServer.js | UIServer.js | var express = require('express');
var http = require('http');
var path = require('path');
var fs = require('fs');
var favicon = require('serve-favicon');
var bodyParser = require('body-parser');
var config = require('./config.json');
var db = require('./model/db.js');
var log = require('./model/log.js');
/*
* Project Name: Kevin's Personal Website
* Author: Kevin Song
* Date : 2015/7/27
* Reference:
* 1. How to use bodyparser? https://github.com/expressjs/body-parser
* 2. ...
*/
// program mode, default set as production
var mode = "production";
if (process.argv && process.argv[2]) {
// production to be passed as param
mode = process.argv[2];
}
log.info("mode: " + mode);
// express app config here
var app = module.exports = express();
// express middle ware
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(express.static(path.join(__dirname, 'public')));
// create application/json parser, this will parse the json form data from the req
var jsonParser = bodyParser.json();
// read the mock data
if (mode === "development") {
// read the mock data
var mockArticleListData = require('./mock/article_list');
var mockArticleListData2 = require('./mock/article_list_previous');
var mockArticleData = require('./mock/article_data');
var mockArticleDataContent = fs.readFileSync('./mock/article_data_content.html', 'utf-8');
mockArticleData.data.article_content = mockArticleDataContent;
}
// http response data
var successResponse = {
"result": "success",
"data": {}
};
var failResponse = {
"result": "fail",
"error": ""
};
// get IP
app.use(function(req, res, next) {
var ip = req.headers['x-forwarded-for'] || req.connection.remoteAddress;
log.info("New request, ip: " + ip);
next();
});
// API: get_article_list
app.post('/get_article_list', jsonParser, function(req, res) {
res.writeHeader(200, {"Content-Type": "text/html"});
// get the form data
var currentPage = req.body.current_page;
var articleNumPerPage = req.body.article_num_per_page;
log.info("currentPage: " + currentPage + ", articleNumPerPage: " + articleNumPerPage);
//return the mock mock
if (mode === "development") {
// return the data according to the num
if (currentPage === 0) {
res.write(JSON.stringify(mockArticleListData));
}
else if (currentPage === 1) {
res.write(JSON.stringify(mockArticleListData2));
}
else {
failResponse.error = "we don't have these data, begin: " + begin + ", end: " + end;
res.write(JSON.stringify(failResponse));
}
}
else {
/* query data from mongodb
* here we will use mongoose to get data from mongodb.
* and sort api can let us sort the data in mongodb before search. We sort as the date.
* and skip, limit api can let us achieve the range query when user query different page's data.
*/
db.find({}, function(err, data) {
if (err) {
log.info("Database Error: get data from collection. Error: " + err);
failResponse.error = err;
res.write(JSON.stringify(failResponse));
res.end();
}
else {
log.info("Database: get data success. data.length: " + data.length);
// get the number of the all articles
db.count(function(err, count) {
if (err) {
log.info("Database Error: count articles number. Error: " + err);
failResponse.error = err;
res.write(JSON.stringify(failResponse));
}
else {
log.info("articles total number: " + count);
successResponse.data = {};
successResponse.data.total_aritcle_num = count;
successResponse.data.article_list = data;
// return response
res.write(JSON.stringify(successResponse));
}
res.end();
});
}
}).select(db.show_fields).sort({'article_time':'desc'}).skip((currentPage-1) * articleNumPerPage).limit(articleNumPerPage);
}
});
// API: get_article
app.post('/get_article', jsonParser, function(req, res) {
res.writeHeader(200, {"Content-Type": "text/html"});
// get the article id
var id = req.body._id;
//log.info("id: " + id);
//return the mock mock
if (mode === "development") {
// return the data according to the num
if (id == 1) {
res.write(JSON.stringify(mockArticleData));
}
else {
failResponse.error = "we don't have this article, id: " + id;
res.write(JSON.stringify(failResponse));
}
res.end();
}
else {
// query data from mongodb
db.findById(id, function(err, data) {
if (err) {
log.info("Database Error: get data from collection. Error: " + err);
failResponse.error = err;
res.write(JSON.stringify(failResponse));
}
else {
log.info("Database: get data success. Article title: " + data.article_title);
successResponse.data = data;
res.write(JSON.stringify(successResponse));
}
res.end();
});
}
});
// get port
var port = config.server.port;
log.info("Server listening on port: " + port);
// create server
http.createServer(app).listen(port);
| JavaScript | 0.000001 | @@ -1783,16 +1783,38 @@
request,
+ url: %22 + req.url + %22,
ip: %22 +
@@ -1819,16 +1819,16 @@
+ ip);%0A
-
next
@@ -2120,24 +2120,26 @@
e;%0A %0A
+//
log.info(%22cu
@@ -3367,32 +3367,34 @@
+//
log.info(%22Databa
@@ -3850,32 +3850,34 @@
+//
log.info(%22articl
@@ -5407,32 +5407,32 @@
else %7B%0A
+
@@ -5445,36 +5445,8 @@
fo(%22
-Database: get data success.
Arti
|
4e7aebcb2bff476703d7ca33461a887bab00af00 | Update integration/sanity/redirect tests to chai | test/integration/sanity/redirect.test.js | test/integration/sanity/redirect.test.js | describe('redirects', function() {
var testrun;
before(function(done) {
this.run({
requester: {followRedirects: false},
collection: {
item: [{
request: 'https://postman-echo.com/redirect-to?url=https://postman-echo.com/get'
}]
}
}, function(err, results) {
testrun = results;
done(err);
});
});
it('must have sent the request successfully', function() {
expect(testrun).be.ok();
expect(testrun.request.calledOnce).be.ok();
expect(testrun.request.getCall(0).args[0]).to.be(null);
});
it('must not have followed the redirect', function() {
var response = testrun.request.getCall(0).args[2];
expect(response.code).to.eql(302);
});
it('must have completed the run', function() {
expect(testrun).be.ok();
expect(testrun.done.calledOnce).be.ok();
expect(testrun.done.getCall(0).args[0]).to.be(null);
expect(testrun.start.calledOnce).be.ok();
});
});
| JavaScript | 0 | @@ -1,8 +1,46 @@
+var expect = require('chai').expect;%0A%0A
describe
@@ -480,28 +480,30 @@
);%0A%0A it('
-must
+should
have sent t
@@ -557,39 +557,40 @@
expect(testrun).
+to.
be.ok
-()
;%0A expect
@@ -589,33 +589,82 @@
expect(testrun
-.
+).to.nested.include(%7B // one request%0A '
request.calledOn
@@ -665,24 +665,33 @@
lledOnce
-).be.ok(
+': true%0A %7D
);%0A%0A
@@ -738,30 +738,29 @@
gs%5B0%5D).to.be
-(
+.
null
-)
;%0A %7D);%0A%0A
@@ -766,20 +766,22 @@
it('
-must
+should
not hav
@@ -906,22 +906,35 @@
onse
-.code).to.eql(
+).to.have.property('code',
302)
@@ -956,12 +956,14 @@
it('
-must
+should
hav
@@ -1025,64 +1025,16 @@
un).
-be.ok();%0A expect(testrun.done.calledOnce)
+to
.be.ok
-()
;%0A
@@ -1088,14 +1088,13 @@
o.be
-(
+.
null
-)
;%0A
@@ -1117,33 +1117,113 @@
trun
-.start.calledOnce).be.ok(
+).to.nested.include(%7B%0A 'done.calledOnce': true,%0A 'start.calledOnce': true%0A %7D
);%0A
|
0f9d0e5cd6ac9e0e8931cef645623710ca3833f9 | Load user script, even if RequireJS is already loaded (#1941) | web/scripts/frame.js | web/scripts/frame.js | /**
* Copyright (c) 2021, the Dart project authors. Please see the AUTHORS file
* for details. All rights reserved. Use of this source code is governed by a
* BSD-style license that can be found in the LICENSE file.
*/
replaceJavaScript = function (value) {
// Remove canvaskit from this page, This can be removed when this PR lands
// in dart-services:
// https://github.com/flutter/engine/pull/26059
removeCanvaskit();
// Remove the old node.
var oldNode = document.getElementById('compiledJsScript');
if (oldNode && oldNode.parentNode) {
oldNode.parentNode.removeChild(oldNode);
}
// Create a new node.
var scriptNode = document.createElement('script');
scriptNode.setAttribute('id', 'compiledJsScript');
scriptNode.async = false;
scriptNode.text = value;
document.head.appendChild(scriptNode);
};
addScript = function (id, url, onload) {
let existingScript = document.getElementById(id);
if (existingScript && existingScript.parentNode) {
return;
}
let scriptNode = document.createElement('script');
scriptNode.setAttribute('id', id);
scriptNode.async = false;
if (onload !== undefined) {
scriptNode.onload = onload;
}
scriptNode.setAttribute('src', url);
document.head.appendChild(scriptNode);
}
removeScript = function (id) {
let existingScript = document.getElementById(id);
if (existingScript && existingScript.parentNode) {
existingScript.parentNode.removeChild(existingScript);
}
}
addFirebase = function () {
addScript('firebase-app', 'https://www.gstatic.com/firebasejs/8.4.1/firebase-app.js');
addScript('firebase-auth', 'https://www.gstatic.com/firebasejs/8.4.1/firebase-auth.js');
addScript('firestore', 'https://www.gstatic.com/firebasejs/8.4.1/firebase-firestore.js');
}
removeFirebase = function () {
removeScript('firebase-app');
removeScript('firebase-auth');
removeScript('firestore');
}
removeCanvaskit = function () {
var scripts = document.head.querySelectorAll('script');
for (var i = 0; i < scripts.length; i++) {
var script = scripts[i];
if (script.src.includes('canvaskit.js')) {
script.parentNode.removeChild(script);
return;
}
}
}
executeWithFirebase = function (userJs) {
let existingFirebase = document.getElementById('firebase-app');
if (existingFirebase) {
// Keep existing RequireJS and Firebase.
replaceJavaScript(userJs);
} else {
// RequireJS must be added _after_ the Firebase JS. If a previous
// execution added RequireJS, then we must first remove it.
removeScript('require');
addFirebase();
// RequireJS must be added _after_ the Firebase JS.
addScript('require', 'require.js', function () {
// User script must be added after RequireJS loads.
replaceJavaScript(userJs);
});
}
}
executeWithRequireJs = function (userJs) {
addScript('require', 'require.js', function () {
// User script must be added after RequireJS loads.
replaceJavaScript(userJs);
});
}
messageHandler = function (e) {
var obj = e.data;
var command = obj.command;
var body = document.body;
if (command === 'setCss') {
document.getElementById('styleId').innerHTML = obj.css;
} else if (command === 'setHtml') {
body.innerHTML = obj.html;
} else if (command === 'execute') {
// Replace HTML, CSS, possible Firebase JS, RequireJS, and app.
body.innerHTML = obj.html;
document.getElementById('styleId').innerHTML = obj.css;
if (obj.addFirebaseJs) {
executeWithFirebase(obj.js);
} else if (obj.addRequireJs) {
executeWithRequireJs(obj.js);
} else {
replaceJavaScript(obj.js);
}
}
};
window.addEventListener('load', function () {
window.addEventListener('message', messageHandler, false);
parent.postMessage({ 'sender': 'frame', 'type': 'ready' }, '*');
});
| JavaScript | 0 | @@ -867,16 +867,266 @@
e);%0A%7D;%0A%0A
+/**%0A * Adds a script tag, with url as %22src%22 and id as %22id%22, unless a script tag with%0A * that id already exists.%0A *%0A * Executes onload after the script has loaded, if the script did not already%0A * exist, and executes onload immediately otherwise.%0A */%0A
addScrip
@@ -1259,32 +1259,50 @@
t.parentNode) %7B%0A
+ onload();%0A
return;%0A
@@ -3227,32 +3227,106 @@
%7D);%0A %7D%0A%7D%0A%0A
+/**%0A * Executes userJs, a user script, after first loading RequireJS.%0A */%0A
executeWithRequi
@@ -3511,16 +3511,159 @@
%7D);%0A%7D%0A%0A
+/**%0A * Handles any incoming messages.%0A *%0A * In particular, understands the following commands on e: 'setCss', 'setHtml',%0A * and 'execute'.%0A */%0A
messageH
|
5606bb022f8aaa70ff320ec1a6b685a5edf5ba0c | Clean the stdout pipe by catching console errors and logs (#19) | src/driver/phantomjs.js | src/driver/phantomjs.js | /* global phantom */
var page = require('webpage').create()
var args = require('system').args
var url = args[1]
var width = args[2]
var options = JSON.parse(args[3])
page.viewportSize = {
width: width,
height: width * 2
}
page.open(url, function () {
setTimeout(function () {
page.evaluate(function (options) {
options.ignoreSelectors.forEach(function (selector) {
[].slice.call(document.querySelectorAll(selector)).forEach(function (node) {
node.style.display = 'none'
})
})
}, options)
console.log(page.renderBase64('PNG'))
phantom.exit()
}, options.renderWaitTime)
})
| JavaScript | 0 | @@ -221,16 +221,127 @@
* 2%0A%7D%0A%0A
+page.onError = page.onConsoleMessage = function () %7B%0A // Prevent messages and errors from piping to stdout%0A%7D%0A%0A
page.ope
|
bdf2d8bf87e959c668ef71c8cba6d68402b908c4 | fix extra deep search message | app/assets/javascripts/form/searchForm.js | app/assets/javascripts/form/searchForm.js | module.directive('searchForm', [
'pageService',
function (page) {
var link = function ($scope) {
var form = $scope.searchForm;
form.data = {
query: page.$location.search().query
};
form.filterMode = true;
$scope.$watch('searchForm.data.query', function (val, old) {
if (page.$location.path() !== '/search' && val !== old)
page.$location.path('/search');
if (form.filterMode === true)
page.$location.search('query', form.data.query || undefined);
});
//
form.seearchFn = undefined;
form.successFn = undefined;
form.errorFn = undefined;
form.resetFn = undefined;
//
var query = function () {
page.models.Volume.query(form.data,
function (res) {
if (form.filterMode)
page.messages.add({
type: 'yellow',
countdown: 3000,
body: page.constants.message('search.deep.info')
});
if (angular.isFunction(form.successFn))
form.successFn(form, res);
form.filterMode = false;
page.$location.search('query', form.data.query);
}, function (res) {
page.messages.addError({
body: page.constants.message('search.error'),
report: res
});
if (angular.isFunction(form.errorFn))
form.errorFn(form, res);
});
};
form.search = function () {
if (angular.isFunction(form.saveFn))
form.saveFn(form);
query();
};
form.reset = function () {
if (angular.isFunction(form.resetFn))
form.resetFn(form);
form.data = {};
form.filterMode = true;
form.$setPristine();
query();
};
//
page.events.talk('searchForm-init', form, $scope);
};
//
return {
restrict: 'E',
templateUrl: 'searchForm.html',
scope: false,
replace: true,
link: link
};
}
]);
| JavaScript | 0.000431 | @@ -742,16 +742,35 @@
lterMode
+ && form.data.query
)%0A%09%09%09%09%09%09
|
f78a45d687a93b5cbd76ca6be497a160ed1e26f8 | Support serializing Service and EventNote filters in hash | app/assets/javascripts/helpers/filters.js | app/assets/javascripts/helpers/filters.js | (function() {
// Define filter operations
window.shared || (window.shared = {});
var FeedHelpers = window.shared.FeedHelpers;
window.shared.Filters = Filters = {
Range: function(key, range) {
return {
identifier: ['range', key, range[0], range[1]].join(':'),
filterFn: function(student) {
var value = student[key];
return (_.isNumber(value) && value >= range[0] && value < range[1]);
},
key: key
};
},
// Types are loose, since this is serialized from the hash
Equal: function(key, value) {
return {
identifier: ['equal', key, value].join(':'),
filterFn: function(student) {
return (student[key] == value);
},
key: key
};
},
Null: function(key) {
return {
identifier: ['none', key].join(':'),
filterFn: function(student) {
var value = student[key];
return (value === null || value === undefined) ? true : false;
},
key: key
};
},
InterventionType: function(interventionTypeId) {
return {
identifier: ['intervention_type', interventionTypeId].join(':'),
filterFn: function(student) {
if (interventionTypeId === null) return (student.interventions === undefined || student.interventions.length === 0);
return student.interventions.filter(function(intervention) {
return intervention.intervention_type_id === interventionTypeId;
}).length > 0;
},
key: 'intervention_type'
};
},
ServiceType: function(serviceTypeId) {
return {
identifier: ['service_type', serviceTypeId].join(':'),
filterFn: function(student) {
if (serviceTypeId === null) return (student.active_services === undefined || student.active_services.length === 0);
return student.active_services.filter(function(service) {
return service.service_type_id === serviceTypeId;
}).length > 0;
},
key: 'service_type'
};
},
EventNoteType: function(eventNoteTypeId) {
return {
identifier: ['event_note_type', eventNoteTypeId].join(':'),
filterFn: function(student) {
if (eventNoteTypeId === null) return (student.event_notes.length === 0);
return student.event_notes.filter(function(eventNote) {
return (eventNote.event_note_type_id === eventNoteTypeId);
}).length > 0;
},
key: 'event_note_type'
};
},
MergedNoteType: function(mergedNoteType, mergedNoteTypeId) {
return {
identifier: ['merged_note_type', mergedNoteType, mergedNoteTypeId].join(':'),
filterFn: function(student) {
var mergedNotes = FeedHelpers.mergedNotes({
event_notes: student.event_notes,
deprecated: {
interventions: student.interventions,
notes: student.notes
}
});
if (mergedNoteType === null && mergedNoteTypeId === null) return (mergedNotes.length === 0);
return mergedNotes.filter(function(mergedNote) {
return FeedHelpers.matchesMergedNoteType(mergedNote, mergedNoteType, mergedNoteTypeId);
}).length > 0;
},
key: 'merged_note_type'
};
},
YearsEnrolled: function(value) {
return {
identifier: ['years_enrolled', value].join(':'),
filterFn: function(student) {
var yearsEnrolled = Math.floor((new Date() - new Date(student.registration_date)) / (1000 * 60 * 60 * 24 * 365));
return (yearsEnrolled === value);
},
key: 'years_enrolled'
};
},
RiskLevel: function(value) {
return {
identifier: ['risk_level', value].join(':'),
filterFn: function(student) {
return (student.student_risk_level && student.student_risk_level.level === value);
}
};
},
// Has to parse from string back to numeric
createFromIdentifier: function(identifier) {
var Filters = window.shared.Filters;
var parts = identifier.split(':');
if (parts[0] === 'range') return Filters.Range(parts[1], [parseFloat(parts[2]), parseFloat(parts[3])]);
if (parts[0] === 'none') return Filters.Null(parts[1]);
if (parts[0] === 'equal') return Filters.Equal(parts[1], parts[2]);
if (parts[0] === 'intervention_type') return Filters.InterventionType(parts[1]);
if (parts[0] === 'risk_level') return Filters.InterventionType(parseFloat(parts[1]));
if (parts[0] === 'years_enrolled') return Filters.YearsEnrolled(parseFloat(parts[1]));
return null;
},
// Returns a list of Filters
parseFiltersHash: function(hash) {
var pieces = _.compact(hash.slice(1).split('&'));
return _.compact(pieces.map(function(piece) {
return Filters.createFromIdentifier(window.decodeURIComponent(piece));
}));
}
};
})();
| JavaScript | 0 | @@ -4664,24 +4664,214 @@
parts%5B1%5D));%0A
+ if (parts%5B0%5D === 'service_type') return Filters.ServiceType(parseFloat(parts%5B1%5D));%0A if (parts%5B0%5D === 'event_note_type') return Filters.EventNoteType(parseFloat(parts%5B1%5D));%0A %0A
return
|
07baf822afbec1573b7315c941fee3d0bb3ef7b2 | Move generateSlug() call up to the top, so it's more visible | app/assets/javascripts/slug-generation.js | app/assets/javascripts/slug-generation.js | $(function() {
var $form = $(".js-guide-form");
if (!$form.length) {
return;
}
var $title = $(".js-guide-title");
var $slug = $(".js-slug");
var $titleSlug = $(".js-title-slug");
var $topicSection = $(".js-topic-section");
var hasBeenPublished = $form.data("has-been-published");
var titleSlugManuallyChanged = false;
$(document).on("input", ".js-title-slug", function() {
titleSlugManuallyChanged = true;
generateSlug();
});
$(document).on("input", ".js-guide-title", generateSlug);
$(document).on("change", ".js-topic-section", generateSlug);
function generateSlug() {
// Slug can't be changed if the guide has ever been published.
if (hasBeenPublished) {
return;
}
// If a user has manually changed the slug, then we don't generate
// it from the title anymore.
if (!titleSlugManuallyChanged) {
$titleSlug.val(slugify($title.val()));
}
var slug = "";
// We get the first part of the full from the chosen topic sections' topic.
// This will be in the format /service-manual/topic-path
var topicPath = $topicSection.find(":selected").parent().data("path");
if (!topicPath) { return }
slug += topicPath + "/";
// Now add whatever title slug was generated (or manually entered by user)
// to the full slug.
if (!$titleSlug.val()) { return }
slug += slugify($titleSlug.val())
$slug.val(slug);
}
generateSlug();
function slugify(text) {
// https://gist.github.com/mathewbyrne/1280286
return text.toString().toLowerCase()
.replace(/\s+/g, '-') // Replace spaces with -
.replace(/[^\w\-]+/g, '') // Remove all non-word chars
.replace(/\-\-+/g, '-') // Replace multiple - with single -
.replace(/^[-_]+/, '') // Trim - and _ from start
.replace(/[-_]+$/, ''); // Trim - and _ from end
}
});
| JavaScript | 0 | @@ -337,16 +337,35 @@
false;%0A%0A
+ generateSlug();%0A%0A
$(docu
@@ -1443,35 +1443,16 @@
);%0A %7D%0A%0A
- generateSlug();%0A%0A
functi
|
63cd19e26f0cd5629372fb50c0244986c3ef1bbd | Stop if there's an error | app/client/templates/posts/post_submit.js | app/client/templates/posts/post_submit.js | Template.postSubmit.events({
'submit form': function(e) {
e.preventDefault();
var post = {
url: $(e.target).find('[name=url]').val(),
title: $(e.target).find('[name=title]').val()
};
post.slug = slugify(post.title);
post._id = Posts.insert(post);
Router.go('postPage', post);
}
}); | JavaScript | 0.000046 | @@ -250,39 +250,170 @@
-post._id = Posts.insert(post
+Meteor.call('postInsert', post, function(error, result) %7B%0A // display the error to the user and abort%0A if (error)%0A return alert(error.reason
);%0A
+
@@ -434,20 +434,43 @@
tPage',
-post
+%7B_id: result._id%7D); %0A %7D
);%0A %7D%0A%7D
|
f87c7591db909335105d5cffde206f35740901c8 | make sure we have actually created the map | google-maps.js | google-maps.js | var supportedTypes = ['Map', 'StreetViewPanorama'];
GoogleMaps = {
load: _.once(function(options) {
options = _.extend({ v: '3.exp' }, options);
var params = _.map(options, function(value, key) { return key + '=' + value; }).join('&');
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://maps.googleapis.com/maps/api/js?' + params +
'&callback=GoogleMaps.initialize';
document.body.appendChild(script);
}),
utilityLibraries: [],
loadUtilityLibrary: function(path) {
this.utilityLibraries.push(path);
},
_loaded: new ReactiveVar(false),
loaded: function() {
return this._loaded.get();
},
maps: {},
_callbacks: {},
initialize: function() {
this._loaded.set(true);
_.each(this.utilityLibraries, function(path) {
var script = document.createElement('script');
script.type = 'text/javascript';
script.src = path;
document.body.appendChild(script);
});
},
_ready: function(name, map) {
_.each(this._callbacks[name], function(cb) {
if (_.isFunction(cb))
cb(map);
});
},
ready: function(name, cb) {
if (! this._callbacks[name])
this._callbacks[name] = [];
// make sure we run the callback only once
// as the tilesloaded event will also run after initial load
this._callbacks[name].push(_.once(cb));
},
// options: function(options) {
// var self = this;
// return function() {
// if (self.loaded())
// return options();
// };
// },
get: function(name) {
return this.maps[name];
},
_create: function(name, options) {
var self = this;
self.maps[name] = {
instance: options.instance,
options: options.options
};
if (options.type === 'StreetViewPanorama') {
options.instance.setVisible(true);
self._ready(name, self.maps[name]);
} else {
google.maps.event.addListener(options.instance, 'tilesloaded', function() {
self._ready(name, self.maps[name]);
});
}
},
create: function(options) {
// default to Map
var type = options.type ? options.type : 'Map';
if (! _.include(supportedTypes, type))
throw new Meteor.Error("GoogleMaps - Invalid type argument: " + type);
this._create(options.name, {
type: type,
instance: new google.maps[type](options.element, options.options),
options: options.options
});
}
};
Template.googleMap.onRendered(function() {
var self = this;
self.autorun(function(c) {
// if the api has loaded
if (GoogleMaps.loaded()) {
var data = Template.currentData();
if (! data.options)
return;
if (! data.name)
throw new Meteor.Error("GoogleMaps - Missing argument: name");
self._name = data.name;
var canvas = self.$('.map-canvas').get(0);
GoogleMaps.create({
name: data.name,
type: data.type,
element: canvas,
options: data.options
});
c.stop();
}
});
});
Template.googleMap.onDestroyed(function() {
google.maps.event.clearInstanceListeners(GoogleMaps.maps[this._name].instance);
delete GoogleMaps.maps[this._name];
});
| JavaScript | 0 | @@ -3087,16 +3087,50 @@
ion() %7B%0A
+ if (GoogleMaps%5Bthis._name%5D) %7B%0A
google
@@ -3203,16 +3203,18 @@
tance);%0A
+
delete
@@ -3243,12 +3243,16 @@
_name%5D;%0A
+ %7D%0A
%7D);%0A
|
18eea1adaa1fcfd72859c0d58576aab570c34b7b | fix filter js window behavior #62 | app/assets/javascripts/arctic_admin/base.js | app/assets/javascripts/arctic_admin/base.js | //= require jquery
//= require jquery_ujs
//= require active_admin/base
$(function() {
$(document).on('click touchstart', '#sidebar', function(e) {
var position = $(this).position();
var width = $(this).width();
var target = e.target;
if ((e.pageX < position.left) && (target.tagName != 'SELECT') && (target.tagName != 'OPTION')) {
if ($(this).css('right') == '0px') {
$(this).css('position', 'fixed');
$(this).animate({
right: "-="+width
}, 600, function() {
$(this).removeAttr('style');
animationFilterDone = true;
});
} else {
$(this).animate({
right: "+="+width
}, 600, function() {
$(this).css('position', 'absolute');
animationFilterDone = true;
});
}
}
});
var animationDone = true;
$(document).on('click touchstart', '#utility_nav', function(e) {
var position = $(this).position();
var tabs = $('#tabs');
var width = Math.round(tabs[0].getBoundingClientRect().width);
if (e.pageX < (position.left + 40)) {
if(animationDone == true) {
animationDone = false;
if (tabs.css('left') == '0px') {
tabs.animate({
left: "-="+width
}, 400, function() {
animationDone = true;
});
} else {
tabs.animate({
left: "+="+width
}, 400, function() {
animationDone = true;
});
}
}
}
});
$(document).on('click touchstart', 'body', function(e) {
var tabs = $('#tabs');
var width = Math.round(tabs[0].getBoundingClientRect().width);
if (tabs.css('left') == '0px') {
if (e.pageX > width && e.pageY > 60) {
if(animationDone == true) {
animationDone = false;
tabs.animate({
left: "-="+width
}, 400, function() {
animationDone = true;
});
}
}
}
});
$(document).on('click', '#tabs .has_nested', function(e) {
e.stopPropagation();
$(this).toggleClass('open');
});
});
| JavaScript | 0 | @@ -81,16 +81,50 @@
ion() %7B%0A
+ var animationFilterDone = true;%0A
$(docu
@@ -170,32 +170,72 @@
, function(e) %7B%0A
+ if(animationFilterDone == true) %7B%0A
var position
@@ -257,24 +257,26 @@
tion();%0A
+
+
var width =
@@ -292,24 +292,26 @@
idth();%0A
+
var target =
@@ -321,16 +321,18 @@
target;%0A
+
if (
@@ -426,24 +426,26 @@
')) %7B%0A
+
if ($(this).
@@ -469,32 +469,34 @@
0px') %7B%0A
+
+
$(this).css('pos
@@ -513,32 +513,34 @@
ixed');%0A
+
$(this).animate(
@@ -543,32 +543,34 @@
ate(%7B%0A
+
+
right: %22-=%22+widt
@@ -563,32 +563,34 @@
ght: %22-=%22+width%0A
+
%7D, 600,
@@ -604,32 +604,34 @@
n() %7B%0A
+
$(this).removeAt
@@ -639,24 +639,26 @@
r('style');%0A
+
an
@@ -687,28 +687,32 @@
ue;%0A
+
%7D);%0A
+
%7D else
@@ -714,32 +714,34 @@
else %7B%0A
+
$(this).animate(
@@ -734,32 +734,34 @@
this).animate(%7B%0A
+
right:
@@ -772,32 +772,34 @@
%22+width%0A
+
%7D, 600, function
@@ -805,32 +805,34 @@
n() %7B%0A
+
+
$(this).css('pos
@@ -854,32 +854,34 @@
te');%0A
+
animationFilterD
@@ -896,28 +896,40 @@
ue;%0A
+
%7D);%0A
+ %7D%0A
%7D%0A
|
02fc43d2a0e539130e48f6ad3c821c536c6cd1b3 | Allow adding entries for dates other than today | app/components/addEntryPage/addEntryPage.js | app/components/addEntryPage/addEntryPage.js | 'use strict';
var React = require('react-native');
var Leaderboard = require('../leaderboard/leaderboard');
var {
StyleSheet,
Text,
TextInput,
DatePickerIOS,
View,
TouchableHighlight,
ActivityIndicatorIOS,
Image,
Component
} = React;
var styles = StyleSheet.create({
description: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: '#656565'
},
flowRight: {
flexDirection: 'row',
alignItems: 'center',
alignSelf: 'stretch',
marginBottom: 15
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
textInput: {
height: 36,
padding: 4,
marginRight: 5,
flex: 4,
fontSize: 18,
borderWidth: 1,
borderRadius: 8
},
button: {
height: 36,
flex: 1,
flexDirection: 'row',
backgroundColor: '43CA01',
borderColor: '#48BBEC',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
container: {
padding: 30,
marginTop: 65,
alignItems: 'center'
}
});
class AddEntryPage extends Component {
constructor(props) {
super(props);
this.state = {
duration: '0',
isLoading: false,
message: ''
};
}
render() {
console.log('AddEntryPage.render');
var spinner = this.state.isLoading ?
(<ActivityIndicatorIOS hidden="true" size="large"/>) :
(<View />);
return (
<View style={styles.container}>
<View style={styles.flowRight}>
<Text>Date: </Text>
<DatePickerIOS
date={new Date}
mode="date"
/>
</View>
<View style={styles.flowRight}>
<Text>Duration: </Text>
<TextInput
style={styles.textInput}
placeholder="Minutes"
keyboardType="numeric"
value={this.state.duration}
onChange={this.onDurationChanged.bind(this)}
clearTextOnFocus={true}
/>
</View>
<TouchableHighlight
style={styles.button}
underlayColor='#99d9f4'
onPress={this.onAddPressed.bind(this)}
>
<Text style={styles.buttonText}>Add</Text>
</TouchableHighlight>
{spinner}
<Text style={styles.description}>{this.state.message}</Text>
</View>
);
}
onDurationChanged(event) {
console.log('onDurationChanged');
this.setState({ duration: event.nativeEvent.text });
console.log(this.state.duration);
}
onAddPressed() {
var data = {
email: 'USERNAME@multunus.com',
entry: {
date: new Date(),
duration: this.state.duration
}
};
var url = 'http://staging-move1t.herokuapp.com/entries.json';
this._postToUrl(url, data);
}
_postToUrl(url, data) {
this.setState({isLoading: true});
fetch(url, {
method: 'post',
body: JSON.stringify(data),
headers: new Headers({
'Content-Type': 'application/json'
})
})
.then(function(response) {
if (response.ok) {
return response.json();
} else {
throw new Error(JSON.parse(response._bodyText).error); //FixIt - Shoudn't be using the quasi private method
}
})
.then(response => this._handleResponse(response))
.catch(error => this.setState({
isLoading: false,
message: error.message
}));
}
_handleResponse(response) {
this.setState({
isLoading: false,
message: ''
});
console.log('Response: ' + JSON.stringify(response));
this.props.navigator.push({
title: 'Leaderboard',
component: Leaderboard
});
}
}
module.exports = AddEntryPage;
| JavaScript | 0 | @@ -1163,24 +1163,48 @@
s.state = %7B%0A
+ date: new Date(),%0A
durati
@@ -1599,21 +1599,28 @@
date=%7B
-new D
+this.state.d
ate%7D%0A
@@ -1640,16 +1640,72 @@
=%22date%22%0A
+ onDateChange=%7Bthis.onDateChange.bind(this)%7D%0A
@@ -2012,17 +2012,16 @@
onChange
-d
.bind(th
@@ -2453,49 +2453,78 @@
onD
-urationChanged(event) %7B%0A console.log('
+ateChange(date) %7B%0A this.setState(%7B%0A date: date%0A %7D);%0A %7D%0A%0A
onDu
@@ -2535,20 +2535,25 @@
onChange
-d');
+(event) %7B
%0A thi
@@ -2564,16 +2564,22 @@
tState(%7B
+%0A
duratio
@@ -2607,48 +2607,14 @@
text
- %7D);
%0A
-console.log(this.state.duration
+%7D
);%0A
@@ -2716,34 +2716,39 @@
date:
-new D
+this.state.d
ate
-()
,%0A du
|
e3c9a348450c91830d5e36a792563fffcbe7d992 | Add content-encoding headers for webfetch response. Set 'chunked' | app/extensions/safe/server-routes/safe.js | app/extensions/safe/server-routes/safe.js | import logger from 'logger';
import { getAppObj } from '../network';
const safeRoute = {
method : 'GET',
path : '/safe/{link*}',
handler : async ( request, reply ) =>
{
try
{
const link = `safe://${request.params.link}`;
const app = getAppObj();
logger.verbose( `Handling SAFE req: ${link}` );
if ( !app )
{
return reply( 'SAFE not connected yet' );
}
const data = await app.webFetch( link );
return reply( data.body ).type( data.headers['Content-Type'] );
}
catch ( e )
{
logger.error( e );
return reply( e.message || e );
}
}
}
export default safeRoute;
| JavaScript | 0.000001 | @@ -565,16 +565,33 @@
a.body )
+%0A
.type( d
@@ -619,16 +619,72 @@
Type'%5D )
+%0A .header( 'Content-Encoding', 'chunked')
;%0A
|
df43256250404eb41ac7969f1435628112c3d873 | Make popover actions handleable to parents | src/edititem/PopOver.js | src/edititem/PopOver.js | import React, {PropTypes} from 'react'
import styles from 'part:@sanity/components/edititem/popover-style'
import Button from 'part:@sanity/components/buttons/default'
import {debounce} from 'lodash'
import CloseIcon from 'part:@sanity/base/close-icon'
import scroll from 'scroll'
import ease from 'ease-component'
export default class EditItemPopOver extends React.Component {
static propTypes = {
title: PropTypes.string,
children: PropTypes.node.isRequired,
className: PropTypes.string,
onClose: PropTypes.func,
isCreatingNewItem: PropTypes.bool,
actions: PropTypes.arrayOf(PropTypes.object),
fullWidth: PropTypes.bool,
onNeedScroll: PropTypes.func,
scrollContainer: PropTypes.node,
scrollContainerId: PropTypes.string
}
static defaultProps = {
onClose() {},
actions: []
}
constructor() {
super()
this.handleClose = this.handleClose.bind(this)
this.handleClick = this.handleClick.bind(this)
this.handleMouseDown = this.handleMouseDown.bind(this)
this.setRootElement = this.setRootElement.bind(this)
this.setInnerElement = this.setInnerElement.bind(this)
this.setArrowElement = this.setArrowElement.bind(this)
this.repositionElement = this.repositionElement.bind(this)
this.handleResize = debounce(this.handleResize.bind(this), 17) // 60fps
this.resetPosition = this.resetPosition.bind(this)
this.scrollOptions = {
duration: 250,
ease: ease.easeInOutQuart
}
}
handleKeyDown = event => {
if (event.key == 'Escape') {
this.handleClose()
}
}
handleClose() {
this.props.onClose()
}
handleClick(event) {
event.stopPropagation()
}
handleMouseDown(event) {
event.stopPropagation()
}
repositionElement() {
const rootElement = this._rootElement
const innerElement = this._innerElement
if (!rootElement && !innerElement) {
return
}
const rootRects = rootElement.getClientRects()
const width = rootRects[0].width
const height = rootRects[0].height
const left = rootRects[0].left
const top = rootRects[0].top
// we can use window since we don't support horizontal scrolling
// and the backdrop is fixed
const windowWidth = window.innerWidth
const containerOffsetHeight = this.scrollContainer.offsetHeight
const padding = 30
const margin = parseInt(innerElement.style.marginLeft, 10) || 0
const scrollTop = this.scrollContainer.scrollTop
// Scroll container when there is no space
// But we cant scroll more than the height of the element
if ((containerOffsetHeight + scrollTop) < (top + height)) {
let newScrollTop = (containerOffsetHeight - top - height - scrollTop) * -1
// If element is to big for screen, scroll top only top of the element
if (height > containerOffsetHeight) {
newScrollTop = top + scrollTop - (padding * 3)
}
scroll.top(this.scrollContainer, newScrollTop, this.scrollOptions)
}
// Need more bottom space
if (this.scrollContainer.scrollHeight < (scrollTop + top + height)) {
const extraPaddingBottom = Math.abs(this.scrollContainer.scrollHeight - scrollTop - height - top)
this.scrollContainer.style.marginBottom = `${extraPaddingBottom}px`
let newScrollTop = (containerOffsetHeight - top - height - scrollTop) * -1
// If element is to big for screen, scroll top only top of the element
if (height > containerOffsetHeight) {
newScrollTop = top + scrollTop - (padding * 3)
}
scroll.top(this.scrollContainer, newScrollTop, this.scrollOptions)
}
// Reposition horizon
if ((width + left - margin + padding) > windowWidth) {
const diff = windowWidth - width - padding - left + margin
innerElement.style.marginLeft = `${diff}px`
this._arrowElement.style.transform = `translateX(${diff * -1}px)`
} else {
this.resetPosition()
}
}
resetPosition() {
this._innerElement.style.marginLeft = '0'
this._arrowElement.style.transform = 'translateX(0px)'
}
handleResize() {
// Uses the css the determine if it should reposition with an Media Query
const computedStyle = window.getComputedStyle(this._rootElement, '::before')
const contentValue = computedStyle.getPropertyValue('content')
const shouldReposition = contentValue === '"shouldReposition"' || contentValue === 'shouldReposition' // Is quoted
if (shouldReposition) {
this.repositionElement()
} else {
this.resetPosition()
}
}
componentDidMount() {
// Sets a scrollContainer with ID
if (!this.props.scrollContainer && this.props.scrollContainerId) {
this.scrollContainer = document.getElementById(this.props.scrollContainerId)
} else if (this.props.scrollContainer) {
this.scrollContainer = this.props.scrollContainer
} else {
this.scrollContainer = document.getElementById('Sanity_Default_DeskTool_Editor_ScrollContainer')
}
if (this.scrollContainer) {
this.initialScrollTop = this.scrollContainer.scrollTop
this.handleResize()
window.addEventListener('resize', this.handleResize)
window.addEventListener('keydown', this.handleKeyDown, false)
}
}
componentWillUnmount() {
if (this.scrollContainer && this.initialScrollTop) {
scroll.top(this.scrollContainer, this.initialScrollTop, this.scrollOptions)
}
window.removeEventListener('keydown', this.handleKeyDown, false)
window.removeEventListener('resize', this.handleResize)
}
setRootElement(element) {
this._rootElement = element
}
setInnerElement(element) {
this._innerElement = element
}
setArrowElement(element) {
this._arrowElement = element
}
handleBackdropClick = () => {
this.handleClose()
}
handleInnerClick = event => {
event.stopPropagation()
}
render() {
const {title, children, className, isCreatingNewItem, actions, fullWidth} = this.props
return (
<div
className={`${fullWidth ? styles.fullWidth : styles.autoWidth} ${className}`}
onClick={this.handleClick}
ref={this.setRootElement}
>
<div className={styles.overlay} onClick={this.handleBackdropClick} />
<div className={styles.inner} ref={this.setInnerElement} onClick={this.handleInnerClick}>
<div className={styles.arrow} ref={this.setArrowElement} />
<button className={styles.close} type="button" onClick={this.handleClose}>
<CloseIcon />
</button>
<div className={styles.head}>
<h3 className={styles.title}>
{
isCreatingNewItem && 'New '
}
{title}
</h3>
</div>
<div className={styles.content}>
{children}
</div>
{
actions.length > 0 && <div className={styles.functions}>
{
actions.map((action, i) => {
return (
<Button
key={i}
onClick={this.handleActionClick}
data-action-index={i}
kind={action.kind}
className={styles[`button_${action.kind}`] || styles.button}
>
{action.title}
</Button>
)
})
}
</div>
}
</div>
</div>
)
}
}
| JavaScript | 0.000002 | @@ -611,14 +611,117 @@
pes.
-object
+shape(%7B%0A kind: PropTypes.string,%0A title: PropTypes.string,%0A handleClick: PropTypes.func%0A %7D)
),%0A
@@ -7204,25 +7204,21 @@
ck=%7B
-this
+action
.handle
-Action
Clic
|
4f153e87f4e95cd0b4965d594f338b1f0d28c9f1 | Remove bind to change event Instance form #14, #16 | sitemedia/js/reference-instance-canvas-toggle.js | sitemedia/js/reference-instance-canvas-toggle.js | /*
Javascript snippet to toggle the Canvas and Intervention autocompletes
sanely based on the presence of a digital edition for a selected Instance (or
the instance being edited in the case of the Reference Inline)
*/
/*
Toggle on or off based on the presence of an Instance with a digtial edition,
either in the selector on the Reference change_form or inline when editing
an Instance
*/
function toggleReferenceAutocompletes() {
var instancePksArray = []
var jsonString = $('.get_autocomplete_instances div div .grp-readonly').text();
if (jsonString) {
instancePksArray = JSON.parse(
$('.get_autocomplete_instances div div .grp-readonly').text()
);
}
/*
Check if there is an instance selected for Reference change_form or a
digital edition chosen on the Instance change_form, and if not, disable
the autcompletes.
*/
if ($('#id_instance option:selected').val() == "" ||
$('#id_digital_edition option:selected').val() == "") {
$('select[id*="canvases"]').attr('disabled', true);
$('select[id*="interventions"]').attr('disabled', true);
} else {
/*
Enable autocompletes if either #id_instance on Reference change form,
or the Instance being viewed reflect an instance with a digital edition.
For the change form, use the parsed JSON from get_autocomplete_instances
read-only field.
*/
var digitalEdFlag = $('#id_digital_edition option:selected').val();
var pkInArray = instancePksArray.indexOf($('#id_instance').val());
if (pkInArray == 0 || (digitalEdFlag != "" && digitalEdFlag != undefined)) {
$('select[id*="canvases"]').removeAttr('disabled', true);
$('select[id*="interventions"]').removeAttr('disabled', true);
}
}
}
$(document).ready(function() {
// bind function once on page load
toggleReferenceAutocompletes();
// bind to the change event on #id_instance for the Reference change_form
$("#id_instance").change(function() {
toggleReferenceAutocompletes();
})
// bind to the change event on #digital_edition for the Instance change_form
$("#id_digital_edition").change(function() {
toggleReferenceAutocompletes();
})
});
| JavaScript | 0 | @@ -1987,175 +1987,9 @@
%7D)
-%0A // bind to the change event on #digital_edition for the Instance change_form%0A $(%22#id_digital_edition%22).change(function() %7B%0A toggleReferenceAutocompletes();%0A %7D)
+;
%0A%7D);
|
9504daed314aa828cb870a17814a10aaca16ba9a | Fix for issue #162 | flowsim-ui/app/scripts/directives/fglist.js | flowsim-ui/app/scripts/directives/fglist.js | 'use strict';
/**
* @ngdoc directive
* @name flowsimUiApp.directive:fgList
* @description
* # fgList
*/
angular.module('flowsimUiApp')
.directive('fgList', function () {
return {
restrict: 'E', // HTML Element
transclude: true, // Copy element body in
templateUrl: 'views/fglist.html', // Location of template
scope: {
onInit: '&', // callback for initializing items
onAdd: '&', // callback for adding item
onDel: '&', // callback for deleting item
onSet: '&', // callback for changing item focus
category: '@'
},
controller: function($scope) {
$scope.itemName = ''; // input name to create item
$scope.focus = -1; // item with current focus
$scope.errorMsg = ''; // input name error message
$scope.items = []; // display list of items
$scope.init = false; // dislay list initialization state
$scope.clearState = function() {
$scope.itemName = '';
$scope.errorMsg = '';
};
$scope.shiftFocus = function(pos) {
if(pos >= -1 && pos < $scope.items.length) {
$scope.clearState();
$scope.focus = pos; // Update the local focus
$scope.onSet()($scope.items[pos]); // Update the parent with name
}
};
$scope.addItem = function() {
$scope.onAdd()($scope.itemName, function(err) {
if(err) {
$scope.itemName = '';
$scope.errorMsg = err;
} else {
$scope.items.push($scope.itemName);
$scope.shiftFocus($scope.items.length-1);
}
});
};
$scope.delItem = function(pos) {
var item;
if(pos >= -1 && pos < $scope.items.length) {
item = $scope.items.splice(pos, 1);
if(pos < $scope.focus) {
$scope.shiftFocus($scope.focus-1);
}
if(pos === $scope.focus && pos === $scope.items.length) {
$scope.shiftFocus($scope.focus-1);
}
$scope.onDel()(item);
$scope.clearState();
}
};
$scope.onInit()(function(err, result) {
if(err) {
console.log(err.details);
} else {
$scope.items = result;
if(result.length > 0) {
$scope.shiftFocus(0);
}
}
});
$scope.$on('$destroy', function(){
$scope.itemName = '';
$scope.focus = -1;
$scope.items = [];
$scope.init = false;
});
}
};
});
| JavaScript | 0 | @@ -2295,32 +2295,131 @@
;%0A %7D%0A
+ if(pos === $scope.focus)%7B%0A $scope.shiftFocus($scope.focus);%0A %7D%0A
$sco
|
75cf097165cd01d49cd1d68f4249a5e89a98b302 | Update Plugwoot.js | Autowoot.js/Plugwoot.js | Autowoot.js/Plugwoot.js | /*
Copyright (c) 2013-2017 by Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL
Permission to use this software for any purpose without fee is hereby granted, provided
that the above copyright notice and this permission notice appear in all copies.
Permission to copy and/or edit this software or parts of it for any purpose is permitted,
provided that the following points are followed.
- The above copyright notice and this permission notice appear in all copies
- Within two (2) days after modification is proven working, any modifications are send back
to the original authors to be inspected with the goal of inclusion in the official software
- Any edited version are only test versions and not permitted to be run as a final product
- Any edited version aren't to be distributed
- Any edited version have the prerelease version set to something that can be distinguished
from a version used in the original software
TERMS OF REPRODUCTION USE
Failure to follow these terms will result in me getting very angry at you
and having your software tweaked or removed if possible. Either way, you're
still an idiot for not following such a basic rule.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHORS DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE
INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHORS
BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER
RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
* @Author: Tawi Jordan - ๖ۣۜĐJ - ɴᴇᴏɴ - TFL (Member. on Plug.dj)
* [NOTE]: THERE IS NOTHING HERE FOR YOU! COPYING ANY PART OF THIS SCRIPT AND USING "IT" or "AS" (yours)
* WELL SERIOUSLY GET YOU TO FACE THE CONSEQUENCES!
*/
var path = 'http://pastebin.com/raw.php?i=';
function message(contents) {
var msg = '<div class="mention is-you"><i class="icon icon-chat-admin"></i><span class="from admin">Plugwoot™ </span><span class="text"> '+ contents +'</span></div>';
$('#chat-messages').append(msg);
}
var scriptFail = window.setTimeout(function() {
message("Oops! Something went wrong!")
//message('Sorry plugwoot is updating! :(');
}, 5250);
$.getScript(path+'NPqKyJwy', function() {
message("version "+ PlugStation.version +" is now available!");
console.log("Plugwoot "+ PlugStation.version +" - Created by ๖ۣۜĐل - ɴᴇᴏɴ - TFL");
window.clearTimeout(scriptFail);
});
| JavaScript | 0 | @@ -2248,16 +2248,18 @@
n() %7B%0A
+//
message(
@@ -2291,18 +2291,16 @@
ng!%22)%0A
-//
message(
@@ -2366,16 +2366,18 @@
pt(path+
+/*
'NPqKyJw
@@ -2378,16 +2378,18 @@
PqKyJwy'
+*/
, functi
@@ -2396,16 +2396,18 @@
on() %7B%0A
+//
message(
@@ -2463,16 +2463,18 @@
le!%22);%0A
+//
console.
|
1f798afd439774470684bd63a285e36e1609190d | Fix permission name so editing works again | ViewUser.js | ViewUser.js | import _ from 'lodash';
// We have to remove node_modules/react to avoid having multiple copies loaded.
// eslint-disable-next-line import/no-unresolved
import React, { Component, PropTypes } from 'react';
import Pane from '@folio/stripes-components/lib/Pane';
import PaneMenu from '@folio/stripes-components/lib/PaneMenu';
import Button from '@folio/stripes-components/lib/Button';
import KeyValue from '@folio/stripes-components/lib/KeyValue';
import { Row, Col } from 'react-bootstrap';
import TextField from '@folio/stripes-components/lib/TextField';
import MultiColumnList from '@folio/stripes-components/lib/MultiColumnList';
import Icon from '@folio/stripes-components/lib/Icon';
import Layer from '@folio/stripes-components/lib/Layer';
import IfPermission from '@folio/stripes-components/lib/IfPermission';
import UserForm from './UserForm';
import UserPermissions from './UserPermissions';
import UserLoans from './UserLoans';
import LoansHistory from './LoansHistory';
class ViewUser extends Component {
static propTypes = {
stripes: PropTypes.shape({
hasPerm: PropTypes.func.isRequired,
connect: PropTypes.func.isRequired,
}).isRequired,
paneWidth: PropTypes.string.isRequired,
data: PropTypes.shape({
user: PropTypes.arrayOf(PropTypes.object),
patronGroups: PropTypes.arrayOf(PropTypes.object),
}),
mutator: React.PropTypes.shape({
selUser: React.PropTypes.shape({
PUT: React.PropTypes.func.isRequired,
}),
}),
match: PropTypes.shape({
path: PropTypes.string.isRequired,
}).isRequired,
onClose: PropTypes.func,
};
static manifest = Object.freeze({
selUser: {
type: 'okapi',
path: 'users/:{userid}',
clear: false,
},
patronGroups: {
type: 'okapi',
path: 'groups',
records: 'usergroups',
},
});
constructor(props) {
super(props);
this.state = {
editUserMode: false,
viewLoansHistoryMode: false,
};
this.onClickEditUser = this.onClickEditUser.bind(this);
this.onClickCloseEditUser = this.onClickCloseEditUser.bind(this);
this.connectedUserLoans = props.stripes.connect(UserLoans);
this.connectedLoansHistory = props.stripes.connect(LoansHistory);
this.connectedUserPermissions = props.stripes.connect(UserPermissions);
this.onClickViewLoansHistory = this.onClickViewLoansHistory.bind(this);
this.onClickCloseLoansHistory = this.onClickCloseLoansHistory.bind(this);
}
// EditUser Handlers
onClickEditUser(e) {
if (e) e.preventDefault();
this.setState({
editUserMode: true,
});
}
onClickCloseEditUser(e) {
if (e) e.preventDefault();
this.setState({
editUserMode: false,
});
}
onClickViewLoansHistory(e) {
if (e) e.preventDefault();
this.setState({
viewLoansHistoryMode: true,
});
}
onClickCloseLoansHistory(e) {
if (e) e.preventDefault();
this.setState({
viewLoansHistoryMode: false,
});
}
update(data) {
// eslint-disable-next-line no-param-reassign
if (data.creds) delete data.creds; // not handled on edit (yet at least)
// eslint-disable-next-line no-param-reassign
if (data.available_patron_groups) delete data.available_patron_groups;
this.props.mutator.selUser.PUT(data).then(() => {
this.onClickCloseEditUser();
});
}
render() {
const fineHistory = [{ 'Due Date': '11/12/2014', Amount: '34.23', Status: 'Unpaid' }];
const { data: { selUser, patronGroups }, match: { params: { userid } } } = this.props;
const detailMenu = (<PaneMenu>
<IfPermission {...this.props} perm="selUser.item.put">
<button onClick={this.onClickEditUser} title="Edit User"><Icon icon="edit" />Edit</button>
</IfPermission>
</PaneMenu>);
if (!selUser || selUser.length === 0 || !userid) return <div />;
const user = selUser.find(u => u.id === userid);
if (!user) return <div />;
const userStatus = (_.get(user, ['active'], '') ? 'active' : 'inactive');
const patronGroupId = _.get(user, ['patronGroup'], '');
const patron_group = patronGroups.find(g => g.id === patronGroupId) || { group: '' };
return (
<Pane defaultWidth={this.props.paneWidth} paneTitle="User Details" lastMenu={detailMenu} dismissible onClose={this.props.onClose}>
<Row>
<Col xs={8} >
<Row>
<Col xs={12}>
<h2>{_.get(user, ['personal', 'lastName'], '')}, {_.get(user, ['personal', 'firstName'], '')}</h2>
</Col>
</Row>
<Row>
<Col xs={12}>
<KeyValue label="User ID" value={_.get(user, ['username'], '')} />
</Col>
</Row>
<br />
<Row>
<Col xs={12}>
<KeyValue label="Status" value={userStatus} />
</Col>
</Row>
<br />
<Row>
<Col xs={12}>
<KeyValue label="Email" value={_.get(user, ['personal', 'email'], '')} />
</Col>
</Row>
<br />
<Row>
<Col xs={12}>
<KeyValue label="Patron group" value={patron_group.group} />
</Col>
</Row>
</Col>
<Col xs={4} >
<img className="floatEnd" src="http://placehold.it/175x175" role="presentation" />
</Col>
</Row>
<br />
<hr />
<br />
<Row>
<Col xs={3}>
<h3 className="marginTopHalf">Fines</h3>
</Col>
<Col xs={4} sm={3}>
<TextField
rounded
endControl={<Button buttonStyle="fieldControl"><Icon icon="clearX" /></Button>}
startControl={<Icon icon="search" />}
placeholder="Search"
fullWidth
/>
</Col>
<Col xs={5} sm={6}>
<Button align="end" bottomMargin0 >View Full History</Button>
</Col>
</Row>
<MultiColumnList fullWidth contentData={fineHistory} />
<hr />
<IfPermission {...this.props} perm="circulation.loans.collection.get">
<this.connectedUserLoans onClickViewLoansHistory={this.onClickViewLoansHistory} {...this.props} />
</IfPermission>
<IfPermission {...this.props} perm="perms.users.get">
<this.connectedUserPermissions stripes={this.props.stripes} match={this.props.match} {...this.props} />
</IfPermission>
<Layer isOpen={this.state.editUserMode} label="Edit User Dialog">
<UserForm
initialValues={_.merge(user, { available_patron_groups: this.props.data.patronGroups })}
onSubmit={(record) => { this.update(record); }}
onCancel={this.onClickCloseEditUser}
/>
</Layer>
<Layer isOpen={this.state.viewLoansHistoryMode} label="Loans History">
<this.connectedLoansHistory userid={userid} stripes={this.props.stripes} onCancel={this.onClickCloseLoansHistory} />
</Layer>
</Pane>
);
}
}
export default ViewUser;
| JavaScript | 0 | @@ -3641,23 +3641,21 @@
%7D perm=%22
-selU
+u
ser
+s
.item.pu
|
93922e8fd2819d7cfa2c3d38d05de71c88cfc803 | Set connection url to include page fragment | static/js/chatterbox.js | static/js/chatterbox.js | // Standard django CSRF handling
function getCookie(name) {
var i, cookie, cookies, cookieValue = null;
if (document.cookie && document.cookie != '') {
cookies = document.cookie.split(';');
for (i = 0; i < cookies.length; i++) {
cookie = cookies[i].trim();
// Does this cookie string begin with the name we want?
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
var csrftoken = getCookie('csrftoken');
// Simple template renderer
function Render(tmpl, data) {
return tmpl.replace(/\{(\w+)\}/g, function (match, key) { return data[key]; });
};
// EventSource malarky
var ChatterBox = (function () {
var modemap = {}, input, messages, nicks, source, url;
var template = {
message : '<div class="message {mode}"><time>{when}</time><span>{sender}</span><p>{message}</p></div>',
action : '<div class="message action"><time>{when}</time><p><i>{sender}</i> {message}</p></div>',
join : '<div class="message join"><time>{when}</time><p><i>{message}</i></p></div>',
nick : '<div class="message nick"><time>{when}</time><p><i>{message}</i></p></div>',
msg : '<div class="message msg"><time>{when}</time><span><i>{sender}</i> ⇒ <i>{target}</i></span><p><em>{message}</em></p></div>'
};
// Encode an obj to POST format
function postEncode(obj) {
var result = [];
for(var key in obj) {
if(obj.hasOwnProperty(key)) {
result.push(encodeURIComponent(key) + '=' + encodeURIComponent(obj[key]));
}
}
return result.join('&');
};
// Send a message to server
function send(message, mode, extra) {
var xhr = new window.XMLHttpRequest();
extra = extra || {};
extra.message = message;
extra.mode = mode;
xhr.open('POST', url);
xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xhr.setRequestHeader("X-CSRFToken", csrftoken);
xhr.send(postEncode(extra));
};
// Print message to screen
function append_message(data, tmpl) {
data.mode = tmpl;
tmpl = template[tmpl] || template['message'];
data.when = data.when || moment().format('H:mm:ss');
messages.innerHTML += Render(tmpl, data);
messages.scrollTop = 9999999;
Array.prototype.slice.call(
messages.querySelectorAll('.message'), 0, -1000
).map(function (el) { messages.removeChild(el); });
};
// Parse event data and render message
function parse_message(event, tmpl) {
var data = JSON.parse(event.data);
append_message(data, tmpl || 'message');
}
function setStatus(state) {
input.classList.remove(input.classList[0]);
input.classList.add(state);
};
modemap['open'] = function (event) {
setStatus('ready');
send('', 'names');
};
modemap['error'] = function (event) {
if(event.readyState == EventSource.CLOSED) {
setStatus('disconnected');
connect();
} else {
setStatus('error');
}
};
modemap['action'] = function (event) { parse_message(event, 'action'); };
modemap['message'] = function (event) { parse_message(event, 'message'); };
modemap['note'] = function (event) { parse_message(event, 'note'); };
modemap['join'] = function (event) { send('', 'names'); parse_message(event, 'join'); };
modemap['nick'] = function (event) { send('', 'names'); parse_message(event, 'nick'); };
modemap['msg'] = function (event) { parse_message(event, 'msg'); };
modemap['names'] = function (event) {
var data = JSON.parse(event.data);
var content = [];
for(var i=0, j=data.message.length; i < j ; i++ ) {
content.push('<li>' + data.message[i] + '</li>');
}
nicks.innerHTML = content.join('\n');
};
function connect () {
setStatus('connecting');
source = new EventSource(url);
for(var key in modemap) {
if(modemap.hasOwnProperty(key)) {
source.addEventListener(key, modemap[key], false);
}
};
};
function keypress(e) {
var extra = {};
if( e.keyCode == 9 ) {
// Nick complete
// parse back for the last space to now.
var match = /(\w+)$/i.exec(input.value);
if(match) {
var pfx = match[1], pattern = RegExp('^' + match[1], 'i');
// Now find if it matches a known nick
var nl = nicks.querySelectorAll('li');
for(var i=0; i < nl.length; i++) {
if(pattern.test(nl[i].innerHTML)) {
input.value = input.value.slice(0, -pfx.length) + nl[i].innerHTML;
input.value += (input.value.length == nl[i].innerHTML.length) ? ': ' : ' ';
break;
}
}
}
e.preventDefault();
return false;
}
if( e.keyCode != 13 ) return;
var msg = input.value;
if(msg.length == 0) return;
var mode = 'message'
var match = /^\/(\w+)\s?(.+)/g.exec(msg);
if(match) {
switch(match[1]) {
case 'nick':
var match = /^(\w+)/.exec(match[2]);
mode = 'nick';
msg = match[1];
break;
case 'me':
mode = 'action';
msg = match[2];
break;
case 'names':
mode = 'names';
msg = '';
break;
case 'msg':
var match = /([-\w]+)\s+(.+)/.exec(match[2]);
mode = 'msg';
extra.target = match[1];
msg = match[2];
break;
default:
break;
}
}
send(msg, mode, extra);
clear();
};
function clear () {
input.value = '';
input.focus();
};
function init (root_url) {
url = root_url;
input = document.querySelector('#input input');
messages = document.querySelector('#messages');
nicks = document.querySelector('#nicks ul');
// Attach input handling, and connect
input.addEventListener('keydown', keypress);
clear();
connect();
window.setInterval(ChatterBox.send, 30000, '', 'names');
};
return {
init: init,
send: send,
};
})();
document.addEventListener('DOMContentLoaded', function () { ChatterBox.init('.'); }, false);
| JavaScript | 0.000001 | @@ -6890,11 +6890,47 @@
nit(
-'.'
+document.location.hash.replace('#', '')
); %7D
|
08ec3480ed96e15198f0ba2e1afd78dedea8bb27 | Add stability annotation to ol.geom.Geometry | src/ol/geom/geometry.js | src/ol/geom/geometry.js | goog.provide('ol.geom.Geometry');
goog.provide('ol.geom.GeometryType');
goog.require('goog.asserts');
goog.require('goog.functions');
goog.require('ol.Observable');
/**
* @enum {string}
*/
ol.geom.GeometryType = {
POINT: 'Point',
LINE_STRING: 'LineString',
LINEAR_RING: 'LinearRing',
POLYGON: 'Polygon',
MULTI_POINT: 'MultiPoint',
MULTI_LINE_STRING: 'MultiLineString',
MULTI_POLYGON: 'MultiPolygon',
GEOMETRY_COLLECTION: 'GeometryCollection',
CIRCLE: 'Circle'
};
/**
* @enum {string}
*/
ol.geom.GeometryLayout = {
XY: 'XY',
XYZ: 'XYZ',
XYM: 'XYM',
XYZM: 'XYZM'
};
/**
* @constructor
* @extends {ol.Observable}
*/
ol.geom.Geometry = function() {
goog.base(this);
/**
* @protected
* @type {ol.Extent|undefined}
*/
this.extent = undefined;
/**
* @protected
* @type {number}
*/
this.extentRevision = -1;
/**
* @protected
* @type {Object.<string, ol.geom.Geometry>}
*/
this.simplifiedGeometryCache = {};
/**
* @protected
* @type {number}
*/
this.simplifiedGeometryMaxMinSquaredTolerance = 0;
/**
* @protected
* @type {number}
*/
this.simplifiedGeometryRevision = 0;
};
goog.inherits(ol.geom.Geometry, ol.Observable);
/**
* @return {ol.geom.Geometry} Clone.
*/
ol.geom.Geometry.prototype.clone = goog.abstractMethod;
/**
* @param {number} x X.
* @param {number} y Y.
* @param {ol.Coordinate} closestPoint Closest point.
* @param {number} minSquaredDistance Minimum squared distance.
* @return {number} Minimum squared distance.
*/
ol.geom.Geometry.prototype.closestPointXY = goog.abstractMethod;
/**
* @param {ol.Coordinate} point Point.
* @param {ol.Coordinate=} opt_closestPoint Closest point.
* @return {ol.Coordinate} Closest point.
*/
ol.geom.Geometry.prototype.getClosestPoint = function(point, opt_closestPoint) {
var closestPoint = goog.isDef(opt_closestPoint) ?
opt_closestPoint : [NaN, NaN];
this.closestPointXY(point[0], point[1], closestPoint, Infinity);
return closestPoint;
};
/**
* @param {ol.Coordinate} coordinate Coordinate.
* @return {boolean} Contains coordinate.
*/
ol.geom.Geometry.prototype.containsCoordinate = function(coordinate) {
return this.containsXY(coordinate[0], coordinate[1]);
};
/**
* @param {number} x X.
* @param {number} y Y.
* @return {boolean} Contains (x, y).
*/
ol.geom.Geometry.prototype.containsXY = goog.functions.FALSE;
/**
* @param {ol.Extent=} opt_extent Extent.
* @return {ol.Extent} extent Extent.
*/
ol.geom.Geometry.prototype.getExtent = goog.abstractMethod;
/**
* @param {number} squaredTolerance Squared tolerance.
* @return {ol.geom.Geometry} Simplified geometry.
*/
ol.geom.Geometry.prototype.getSimplifiedGeometry = goog.abstractMethod;
/**
* @return {ol.geom.GeometryType} Geometry type.
*/
ol.geom.Geometry.prototype.getType = goog.abstractMethod;
/**
* @param {ol.TransformFunction} transformFn Transform.
*/
ol.geom.Geometry.prototype.transform = goog.abstractMethod;
/**
* @typedef {ol.Coordinate}
*/
ol.geom.RawPoint;
/**
* @typedef {Array.<ol.Coordinate>}
*/
ol.geom.RawLineString;
/**
* @typedef {Array.<ol.Coordinate>}
*
*/
ol.geom.RawLinearRing;
/**
* @typedef {Array.<ol.geom.RawLinearRing>}
*/
ol.geom.RawPolygon;
/**
* @typedef {Array.<ol.geom.RawPoint>}
*/
ol.geom.RawMultiPoint;
/**
* @typedef {Array.<ol.geom.RawLineString>}
*/
ol.geom.RawMultiLineString;
/**
* @typedef {Array.<ol.geom.RawPolygon>}
*/
ol.geom.RawMultiPolygon;
| JavaScript | 0.000607 | @@ -643,20 +643,52 @@
rvable%7D%0A
+ * @todo stability experimental%0A
*/%0A
-
ol.geom.
@@ -1295,16 +1295,48 @@
Clone.%0A
+ * @todo stability experimental%0A
*/%0Aol.g
@@ -1816,24 +1816,56 @@
sest point.%0A
+ * @todo stability experimental%0A
*/%0Aol.geom.
@@ -2216,16 +2216,48 @@
dinate.%0A
+ * @todo stability experimental%0A
*/%0Aol.g
@@ -2626,16 +2626,48 @@
Extent.%0A
+ * @todo stability experimental%0A
*/%0Aol.g
@@ -2965,16 +2965,48 @@
y type.%0A
+ * @todo stability experimental%0A
*/%0Aol.g
@@ -3057,32 +3057,32 @@
ctMethod;%0A%0A%0A/**%0A
-
* @param %7Bol.Tr
@@ -3121,16 +3121,48 @@
nsform.%0A
+ * @todo stability experimental%0A
*/%0Aol.g
|
2844d24dd8fa56c5457ca35610ea3702d16f2a91 | add tests for defaultKeyAccessor | src/withManagedData/withManagedData.spec.js | src/withManagedData/withManagedData.spec.js | // @flow weak
/* eslint-env mocha */
import { assert } from 'chai';
import {
APPEAR,
UPDATE,
REMOVE,
REVIVE,
defaultComposeNode,
} from './withManagedData';
describe('withManagedData', () => {
/**
* compose data node from provided data (data, type, udid)
*/
describe('defaultComposeNode', () => {
it('given an number, returns an object with number in data key` ', () => {
assert.deepEqual(
defaultComposeNode(5, APPEAR, 'KEY-123'),
{ data: 5, type: APPEAR, udid: 'KEY-123' },
);
});
it('given an string, returns an object with string in data key` ', () => {
assert.deepEqual(
defaultComposeNode('Wu-Tang', UPDATE, 'KEY-123'),
{ data: 'Wu-Tang', type: UPDATE, udid: 'KEY-123' },
);
});
it('given an object, returns a spread object with type and udid keys` ', () => {
assert.deepEqual(
defaultComposeNode({ x: 10, y: 12 }, REMOVE, 'KEY-123'),
{ x: 10, y: 12, type: REMOVE, udid: 'KEY-123' },
);
});
it('given an object, it will overwrite an existing type key` ', () => {
assert.deepEqual(
defaultComposeNode({ x: 10, y: 12, type: 4 }, REVIVE, 'KEY-123'),
{ x: 10, y: 12, type: REVIVE, udid: 'KEY-123' },
);
});
// it('converts a decomposed hsla color object to a string` ', () => {
// assert.strictEqual(
// convertColorToString({ type: 'hsla', values: [100, 50, 25, 0.5] }),
// 'hsla(100, 50%, 25%, 0.5)',
// );
// });
});
});
| JavaScript | 0 | @@ -133,16 +133,38 @@
seNode,%0A
+ defaultKeyAccessor,%0A
%7D from '
@@ -226,16 +226,707 @@
%7B%0A /**%0A
+ * Create a string data key from given data%0A */%0A describe('defaultKeyAccessor', () =%3E %7B%0A it('given a number, returns a string key%60 ', () =%3E %7B%0A assert.strictEqual(defaultKeyAccessor(5), 'key-5');%0A %7D);%0A%0A it('given a string, returns a string key%60 ', () =%3E %7B%0A assert.strictEqual(defaultKeyAccessor('Wu-Tang'), 'key-Wu-Tang');%0A %7D);%0A%0A it('given an object with id prop returns key-%7Bid%7D%60 ', () =%3E %7B%0A assert.strictEqual(defaultKeyAccessor(%7B id: 123, x: 10, y: 12 %7D), 'key-123');%0A %7D);%0A%0A it('given an object with udid prop returns key-%7Budid%7D%60 ', () =%3E %7B%0A assert.strictEqual(defaultKeyAccessor(%7B udid: 456, x: 10, y: 12 %7D), 'key-456');%0A %7D);%0A %7D);%0A /**%0A
* co
@@ -1168,19 +1168,19 @@
PPEAR, '
-KEY
+key
-123'),%0A
@@ -1211,35 +1211,35 @@
APPEAR, udid: '
-KEY
+key
-123' %7D,%0A )
@@ -1395,27 +1395,27 @@
', UPDATE, '
-KEY
+key
-123'),%0A
@@ -1450,35 +1450,35 @@
UPDATE, udid: '
-KEY
+key
-123' %7D,%0A )
@@ -1647,27 +1647,27 @@
%7D, REMOVE, '
-KEY
+key
-123'),%0A
@@ -1699,35 +1699,35 @@
REMOVE, udid: '
-KEY
+key
-123' %7D,%0A )
@@ -1900,19 +1900,19 @@
EVIVE, '
-KEY
+key
-123'),%0A
@@ -1960,11 +1960,11 @@
d: '
-KEY
+key
-123
@@ -1988,254 +1988,8 @@
%7D);
-%0A%0A // it('converts a decomposed hsla color object to a string%60 ', () =%3E %7B%0A // assert.strictEqual(%0A // convertColorToString(%7B type: 'hsla', values: %5B100, 50, 25, 0.5%5D %7D),%0A // 'hsla(100, 50%25, 25%25, 0.5)',%0A // );%0A // %7D);
%0A %7D
|
ed6e51def2d91aed9511c21ad7ef54f55dbfef93 | comment in index_maps.js | static/js/index_maps.js | static/js/index_maps.js | // ////////////////////////////////////////////////////////////////////////////
/*
// CUSTOM MAP FUNCTIONS
*/
/*
// Even though I like using omnivore, I am going to have to use my own omnivore
// like function for loading datasets. I cannot parse the leaflet L.geoJson
// layers in the ways that I want to, but I can parse through geojson data
// fairly easily. My own ugly little function will return geojson, and not a
// layer.
*/
// ////////////////////////////////////////////////////////////////////////////
// my own omnivore-like functions that return geojson
// unfortunately I must load the csv2geojson.js and the toGeoJson.js libararies
// to use these home made functions
// JSON
const getJSONDataset = (url) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.onload = () => {
xhr.readyState === 4 && xhr.status === 200
? resolve(JSON.parse(xhr.responseText)) : reject(Error(xhr.statusText))
}
xhr.onerror = () => reject(Error('Network Error - JSON'))
xhr.send()
})
return promise
}
// KML
const getKMLDataset = (url) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
// The next few lines are different than the getJSONDataset and getCSVDataset
// calls from here
xhr.responseType = 'document'
xhr.overrideMimeType('text/xml')
xhr.onload = () => {
xhr.readyState === 4 && xhr.status === 200
? resolve(toGeoJSON.kml(xhr.response)) : reject(Error(xhr.statusText))
}
// to here
xhr.onerror = () => reject(Error('Network Error - KML'))
xhr.send()
})
return promise
}
// CSV
const getCSVDataset = (url) => {
const promise = new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.open('GET', url)
xhr.onload = () => {
xhr.readyState === 4 && xhr.status === 200
? csv2geojson.csv2geojson(
xhr.responseText, (err, data) => {
err ? reject(Error(err)) : resolve(data)
}
)
: reject(Error(xhr.statusText))
}
xhr.onerror = () => reject(Error('Network Error - CSV'))
xhr.send()
})
return promise
}
// toggle dataset, if already dataset, add it, else, get it
const datasetToggle = (map, obj, key, ext, url, modJson) => {
obj[key]
? map.hasLayer(obj[key])
? map.removeLayer(obj[key])
: map.addLayer(obj[key]).fitBounds(obj[key].getBounds()) // little crazy with the chain
: getDataset(map, obj, key, ext, url, modJson)
}
// private function to be called when omnivore is ready
// can this be lifted from this function? Can it be public?
const layerReady = (dl, map, obj, key) => {
map.fitBounds(dl.getBounds())
map.addLayer(dl)
obj[key] = dl
}
// get and save dataset to obj[key], and add it to map
const getDataset = (map, obj, key, ext, url, modJson) => {
// check which type of dataset there is, and add it to map
// this should be a function or a loop. I really don't like this if else
// set that does almost the exact same thing
if (ext === 'kml') {
const dataLayer = omnivore.kml(url, null, modJson)
.on('ready', () => {
layerReady(dataLayer, map, obj, key)
})
} else if (ext === 'csv') {
const dataLayer = omnivore.csv(url, null, modJson)
.on('ready', () => {
layerReady(dataLayer, map, obj, key)
})
} else {
const dataLayer = omnivore.geojson(url, null, modJson)
.on('ready', () => {
layerReady(dataLayer, map, obj, key)
})
}
}
// add popups to the data points
// should this function be called every time a layer is added to a map? or will the layer
// still have the popups after it's toggled off and on?
const addPopups = (feature, layer) => {
// make array to add content to
popupContent = []
// first check if there are properties
feature.properties.length !== undefined || feature.properties.length !== 0
// push data from the dataset to the array
? Object.keys(feature.properties).forEach(key => {
popupContent.push(`<b>${key}</b>: ${feature.properties[key]}`)
})
: console.log('No feature properties')
// push feature cordinates to the popupContent array, if it's a point dataset
feature.geometry.type === 'Point'
? popupContent.push(
`<b>Latitude:</b> ${feature.geometry.coordinates[1]}`,
`<b>Longitude:</b> ${feature.geometry.coordinates[0]}`
)
: console.log(feature.geometry.type)
// bind the popupContent array to the layer's layers
layer.bindPopup(popupContent.join(`<br/>`))
}
// THESE THREE CONTROL FUNCTIONS ARE TIGHTLY COUPLED WITH DIFFERENT THINGS
// THEY WILL HAVE TO BE CHANGED EVENTUALLY
// ZMT watermark by extending Leaflet Control
L.Control.Watermark = L.Control.extend({
onAdd: (map) => {
const img = L.DomUtil.create('img')
// this will have to be changed relative to the site for production
img.src = 'http://localhost:8000/static/images/zmt_logo_blue_black_100px.png'
// img.src = imgSrc
img.style.width = '100px'
return img
},
onRemove: (map) => {
// Nothing to do here
}
})
// Home button by extending Leaflet Control
L.Control.HomeButton = L.Control.extend({
onAdd: (map) => {
const container = L.DomUtil.create('div',
'leaflet-bar leaflet-control leaflet-control-custom')
// container.innerHTML = '<i class="fa fa-home fa-2x" aria-hidden="true"></i>'
container.style.backgroundImage = 'url("http://localhost:8000/static/images/home_icon.png")'
container.style.backgroundRepeat = 'no-repeat'
container.style.backgroundColor = 'white'
container.style.width = '34px'
container.style.height = '34px'
container.addEventListener('click', () => map.setView({lat: 0, lng: 0}, 2))
return container
},
onRemove: (map) => {
// Nothing to do here
}
})
// scroll wheel toggle button
L.Control.ToggleScrollButton = L.Control.extend({
onAdd: (map) => {
const container = L.DomUtil.create('div',
'leaflet-bar leaflet-control leaflet-control-custom')
container.style.backgroundImage = 'url("http://localhost:8000/static/images/mouse.png")'
container.style.backgroundRepeat = 'no-repeat'
container.style.backgroundColor = 'white'
container.style.width = '34px'
container.style.height = '34px'
container.addEventListener('click', () => {
map.scrollWheelZoom.enabled()
? map.scrollWheelZoom.disable()
: map.scrollWheelZoom.enable()
})
return container
},
onRemove: (map) => {
// Nothing to do here
}
})
| JavaScript | 0 | @@ -3607,16 +3607,80 @@
%7D%0A%7D %0A%0A
+// I need to make a nice looking popup background that scrolls%0A%0A
// add p
@@ -4707,16 +4707,68 @@
%3Cbr/%3E%60))
+ // this is where the popup html will be implemented
%0A%0A%7D%0A%0A//
|
2ffb2e4af0045057c1c7d547495c3d6dce6232c0 | Fix typo in Overview.js (#108) | example/src/Screens/Docs/AnimatedRoute/Overview.js | example/src/Screens/Docs/AnimatedRoute/Overview.js | import React from 'react';
import { css } from 'glamor';
import Footer from 'Screens/Docs/shared/Footer';
const Element = ({ name }) => (
<code><{name} /></code>
);
const Overview = () => (
<div>
<h2>Overview</h2>
<p>A <a href="https://reacttraining.com/react-router/web/api/Route"><Element name="Route" /></a>, but with mounting & unmounting transitions.</p>
<h2>Interruptible</h2>
<p>Transitions on an <Element name="AnimateRoute" /> are <em>interruptible</em>. This means that if an animation is currently in motion and its match is toggled, it will redirect itself to its proper state mid-transition.</p>
<h2>Nestable</h2>
<p>You can put <Element name="AnimatedRoute" /> instances inside one another! You can even make them recursively nest and match–it's very likely not useful, but it sure is interesting.</p>
<Footer />
</div>
);
export default Overview;
| JavaScript | 0.000121 | @@ -452,16 +452,17 @@
%22Animate
+d
Route%22 /
|
d1c8dd1bc78d3b10244d34016240ff620ceb96ae | Fix amd-tree to output folders as well. | amd-tree.js | amd-tree.js | /* global -name*/
"use strict";
var mine = require("mine");
var pathJoin = require("pathjoin");
var binary = require('bodec');
var modes = require('js-git/lib/modes');
module.exports = amdTree;
function amdTree(servePath, req, callback) {
var path = pathJoin(req.paths.root, req.input, req.paths.local);
servePath(path, function (err, result) {
if (err) return callback(err);
return callback(null, {mode:result.mode,hash:result.hash,fetch:fetch});
function fetch(callback) {
result.fetch(function (err, value) {
if (err) return callback(err);
if (modes.isFile(result.mode)) {
return compile(path, value, callback);
}
if (result.mode === modes.tree) {
var tree = {};
Object.keys(value).forEach(function (key) {
var entry = value[key];
if (/\.js/i.test(key) && modes.isFile(entry.mode)) {
entry.hash += "-amd";
tree[key] = entry;
}
});
value = tree;
}
return callback(null, value);
});
}
});
function compile(path, blob, callback) {
var prefix = pathJoin(req.paths.root, req.input, req.base || ".");
var js = binary.toUnicode(blob);
var deps = mine(js);
var length = deps.length;
var paths = new Array(length);
var localPath = prefix ? path.substring(prefix.length + 1) : path;
var base = localPath.substring(0, localPath.lastIndexOf("/"));
for (var i = length - 1; i >= 0; i--) {
var dep = deps[i];
var depPath = dep.name[0] === "." ? pathJoin(base, dep.name) : dep.name;
if (!(/\.[^\/]+$/.test(depPath))) depPath += ".js";
paths[i] = depPath;
js = js.substr(0, dep.offset) + depPath + js.substr(dep.offset + dep.name.length);
}
js = "define(" + JSON.stringify(localPath) + ", " +
JSON.stringify(paths) + ", function (module, exports) { " +
js + "\n});\n";
callback(null, binary.fromUnicode(js));
}
} | JavaScript | 0 | @@ -872,14 +872,16 @@
if
+(
(/%5C.js
+$
/i.t
@@ -913,24 +913,71 @@
entry.mode))
+ %7C%7C%0D%0A entry.mode === modes.tree)
%7B%0D%0A
|
5de0d45080102c4c5edb79f10a5a6c49842a3140 | Disable multiselection for now | plugins/treeview/web_client/attach.js | plugins/treeview/web_client/attach.js | import _ from 'underscore';
import 'jstree';
import 'jstree/dist/themes/default/style.css';
import { root, auth, conditionalselect } from './utils';
import { model } from './utils/node';
export default function (el, settings = {}) {
const selectable = settings.selectable;
const user = auth();
$(el).each(function () {
settings = $.extend(true, {
plugins: ['types', 'conditionalselect', 'state'],
core: {
data: root(_.defaults(settings.root || {}, {user})),
force_text: true, // prevent XSS
themes: {
dots: false,
responsive: true,
stripes: true
}
},
types: {
folder: {
icon: 'icon-folder'
},
item: {
icon: 'icon-doc-text-inv'
},
user: {
icon: 'icon-user'
},
collection: {
icon: 'icon-globe'
},
users: {
icon: 'icon-users'
},
home: {
icon: 'icon-home'
},
collections: {
icon: 'icon-sitemap'
},
file: {
icon: 'icon-doc-inv'
}
},
conditionalselect: _.wrap(conditionalselect(selectable), function (func, node) {
return func.call(this, model(node), node);
}),
state: {
key: user.login
}
}, settings.jstree);
$(this).jstree(settings);
});
}
| JavaScript | 0 | @@ -703,32 +703,65 @@
%7D
+,%0A multiple: false
%0A %7D,%0A
|
d76d07db01a3df1ec3a10e16760db50672ec867a | Add version to user schema | schemas/user.js | schemas/user.js | var app = require('cantina')
, idgen = require('idgen');
require('cantina-validators');
module.exports = {
name: 'user',
indexes: {
mongo: [
[ { email_lc: 1 }, { unique: true } ],
[ { username_lc: 1 }, { unique: true } ],
{ 'name.sortable': 1 }
]
},
properties: {
id: {
type: 'string',
required: true
},
created: {
type: 'date',
required: true
},
updated: {
type: 'date',
required: true
},
username: {
type: 'string',
required: true,
validators: [app.validators.matches(/^[a-zA-Z0-9_]{3,32}$/)],
prepare: function (model) {
if (model.username) {
return model.username;
}
var username = [];
if (model.name) {
if (model.name.first) username.push(model.name.first);
if (model.name.last) username.push(model.name.last);
}
username = username.join('').replace(/[^a-zA-Z0-9_]/g, '').substring(0, 32 - 7) + '_' + idgen(6);
return username;
}
},
username_lc: {
type: 'string',
private: true,
prepare: function (model) {
if (!model.username) {
model.username = app.schemas.user.properties.username.prepare(model);
}
return model.username.toLowerCase();
}
},
email: {
type: 'string',
required: true,
validators: [app.validators.isEmail]
},
email_lc: {
type: 'string',
private: true,
prepare: function (model) {
return model.email.toLowerCase();
}
},
email_other: [{
type: 'string',
validators: [app.validators.isEmail]
}],
auth: {
type: 'string',
private: true,
validators: [app.validators.isType('string')],
default: ''
},
name: {
first: {
type: 'string',
validators: [app.validators.isType('string')],
default: ''
},
last: {
type: 'string',
validators: [app.validators.isType('string')],
default: ''
},
full: {
type: 'string',
prepare: function (model) {
var name = [];
if (model.name) {
if (model.name.first) name.push(model.name.first);
if (model.name.last) name.push(model.name.last);
}
return name.join(' ');
}
},
sortable: {
type: 'string',
prepare: function (model) {
var name = [];
if (model.name) {
if (model.name.last) name.push(model.name.last);
if (model.name.first) name.push(model.name.first);
}
if (name.length === 2) {
return name.join(', ');
}
else if (name.length === 1) {
return name[0];
}
else {
return model.username;
}
}
}
},
status: {
type: 'string',
required: true,
validators: [app.validators.matches(/^(?:active|disabled|requested|invited|unconfirmed)$/)],
default: 'active'
}
}
};
| JavaScript | 0.000001 | @@ -120,16 +120,36 @@
'user',%0A
+ version: '0.1.0',%0A
indexe
|
9fd4432e5a4ec9f810bcc44ecebef970af6bf3ed | Fix a jasmine test in CommentToggler | spec/javascripts/widgets/comment-toggler-spec.js | spec/javascripts/widgets/comment-toggler-spec.js | /* Copyright (c) 2010, Diaspora Inc. This file is
* licensed under the Affero General Public License version 3 or later. See
* the COPYRIGHT file.
*/
describe("Diaspora.Widgets.CommentToggler", function() {
var commentToggler;
beforeEach(function() {
jasmine.Clock.useMock();
spec.loadFixture("aspects_index_with_posts");
Diaspora.I18n.locale = { };
commentToggler = Diaspora.BaseWidget.instantiate("CommentToggler", $(".stream_element:first ul.comments"));
});
describe("toggleComments", function() {
it("toggles class hidden on the comments ul", function () {
expect($("ul.comments:first")).not.toHaveClass("hidden");
commentToggler.hideComments($.Event());
jasmine.Clock.tick(200);
expect($("ul.comments:first")).toHaveClass("hidden");
});
it("changes the text on the show comments link", function() {
var link = $("a.toggle_post_comments");
Diaspora.I18n.loadLocale({'comments' : {'show': 'comments.show pl'}}, 'en');
expect(link.text()).toEqual("Hide all comments");
commentToggler.hideComments($.Event());
jasmine.Clock.tick(200);
expect(link.text()).toEqual("comments.show pl");
});
});
}); | JavaScript | 0.000038 | @@ -906,32 +906,38 @@
le_post_comments
+:first
%22);%0A Diaspo
@@ -1212,8 +1212,9 @@
%7D);%0A%7D);
+%0A
|
c729d386843db74c2daf62bbd609f59c40c2d55a | Improve walker structure | walker/index.js | walker/index.js | #!/usr/bin/env node
var path = require('path');
var glob = require('glob');
var async = require('async');
var github = new (require('github'))({
version: '3.0.0',
protocol: 'https',
timeout: 5000
});
var TESTING;
main();
function main() {
var root = process.argv[2];
TESTING = process.argv[3];
if(!root) return console.error('Missing input!');
walk(root);
}
function walk(root) {
glob(path.join(root, '/**/package.json'), function(err, files) {
if(err) return console.error(err);
async.map(files, function(file, cb) {
var d = require('./' + file);
if(!d.repositories || !d.repositories[0]) {
console.warn(d.name + ' is missing a repo!');
return cb();
}
getWatchers(parseGh(d.repositories[0].url), function(err, stars) {
if(err) return cb(err);
cb(null, {
name: d.name,
version: d.version,
description: d.description,
homepage: d.homepage,
keywords: d.keywords,
stars: stars,
statistics: {}, // TODO: fetch from max
cdn: [] // TODO: this should contain links to cdn
});
});
}, function(err, d) {
if(err) return console.error(err);
console.log(d.filter(id));
});
});
}
function parseGh(url) {
if(!url) return {};
var parts = url.split('https://github.com/').join('').split('/');
return {
user: parts[0],
repo: parts[1].split('.')[0]
};
}
function getWatchers(o, cb) {
if(!o.user) {
console.warn('Missing user', o);
return cb();
}
if(!o.repo) {
console.warn('Missing repo', o);
return cb();
}
if(TESTING) return cb(null, Math.round(Math.random() * 10000));
github.repos.get(o, function(err, d) {
if(err) return cb(err);
cb(null, d.watchers_count);
});
}
function id(a) {
return a;
} | JavaScript | 0 | @@ -40,16 +40,54 @@
'path');
+%0Avar extend = require('util')._extend;
%0A%0Avar gl
@@ -828,115 +828,56 @@
-getWatchers(parseGh(d.repositories%5B0%5D.url), function(err, stars) %7B%0A if(err) return cb(err);%0A
+async.waterfall(%5B%0A function(cb) %7B
%0A
@@ -889,24 +889,29 @@
-cb(null,
+ var ret =
%7B%0A
@@ -925,16 +925,20 @@
+
+
name: d.
@@ -943,16 +943,20 @@
d.name,%0A
+
@@ -1007,16 +1007,20 @@
+
+
descript
@@ -1059,16 +1059,20 @@
+
homepage
@@ -1105,16 +1105,20 @@
+
+
keywords
@@ -1129,17 +1129,75 @@
keywords
-,
+%0A %7D;%0A%0A cb(null, ret);
%0A
@@ -1209,25 +1209,133 @@
+%7D,%0A
-stars:
+ function(ret, cb) %7B%0A getWatchers(parseGh(d.repositories%5B0%5D.url), function(err,
stars
-,
+) %7B
%0A
@@ -1355,118 +1355,205 @@
-statistics: %7B%7D, // TODO: fetch from max%0A cdn: %5B%5D // TODO: this should contain links to
+ ret.stars = stars;%0A%0A cb(null, ret);%0A %7D);%0A %7D,%0A function(ret, cb) %7B%0A // TODO: parse statistics and
cdn%0A
+%0A
@@ -1568,25 +1568,62 @@
-%7D);%0A %7D
+ cb(null, ret);%0A %7D%0A %5D, cb
);%0A
|
561d5e010f91fef43bda94e7e51af6ed5cbd9792 | Use imagepicker for all forms | app/assets/javascripts/custom.js | app/assets/javascripts/custom.js | $(document).on('turbolinks:load', function () {
$("#selectImage").imagepicker({
hide_select: true,
show_label : true
});
var $container = $('.image_picker_selector');
// initialize
$container.imagesLoaded(function () {
$container.masonry({
columnWidth: 30,
itemSelector: '.thumbnail'
});
});
});
| JavaScript | 0 | @@ -140,16 +140,216 @@
%7D);%0A%0A
+ $(%22#pendingImage%22).imagepicker(%7B%0A hide_select: true,%0A show_label : true%0A %7D);%0A%0A $(%22#moochedImage%22).imagepicker(%7B%0A hide_select: true,%0A show_label : true%0A %7D);%0A%0A
var
@@ -390,16 +390,16 @@
ctor');%0A
-
// i
@@ -508,9 +508,9 @@
th:
-3
+1
0,%0A
|
84bc2383b6c99b0e4696f758b5cb5fa9749fcb14 | Disable convertion to divs, preserve paragraphs. | app/assets/javascripts/editor.js | app/assets/javascripts/editor.js | /**
* Wysiwyg related javascript
*/
// =require ./lib/redactor.js
(function($){
$(document).ready( function() {
/**
* Minimal wysiwyg support
*/
$('.wysiwyg-minimal').redactor({
airButtons: ['bold', 'italic', 'deleted', '|', 'link'],
air: true
});
/**
* Basic wysiwyg support
*/
$('.wysiwyg').redactor();
/**
* Assets-aware wysiwyg support
*/
$('.wysiwyg-full').redactor({
fixed: true,
wym: true,
imageUpload: '/images',
imageGetJson: '/images',
imageUploadErrorCallback: function( o, json ) { alert( json.error ); },
fileUpload: '/uploads',
fileUploadErrorCallback: function( o, json ) { alert( json.error ); },
uploadFields: {
authenticity_token: $('meta[name="csrf-token"]').attr('content'),
assetable_type: $('.assetable_type').val(),
assetable_id: $('.assetable_id').val()
}
});
});
}(jQuery))
| JavaScript | 0 | @@ -476,24 +476,50 @@
wym: true,%0A
+ convertDivs: false,%0A
imageU
|
a04c900f0f6aa88872d84f92fada2f4517bba9d4 | Fix lightsoff to not use signal this.. | examples/lightsoff/arrow.js | examples/lightsoff/arrow.js | function pushed_arrow()
{
if(animating_board)
return true;
// TODO: Need to check that click count is 1
var direction = (this.flipped ? 1 : -1);
if(score.value + direction < 1)
return true;
score.set_value(score.value + direction);
swap_animation(direction);
gconf_client.set_int("/apps/lightsoff/score", score.value);
return true;
}
ArrowType = {
parent: Clutter.Group.type,
name: "Arrow",
class_init: function(klass, prototype)
{
prototype.set_arrow_flipped = function ()
{
this.flipped = 1;
this.remove_all();
var bkg = Clutter.Texture.new_from_file("./arrow-r.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.add_actor(bkg);
}
},
instance_init: function(klass)
{
this.flipped = 0;
var bkg = Clutter.Texture.new_from_file("./arrow-l.svg");
bkg.filter_quality = Clutter.TextureQuality.high;
this.reactive = true;
this.signal.button_press_event.connect(pushed_arrow, this);
this.add_actor(bkg);
}};
Arrow = new GType(ArrowType);
| JavaScript | 0.000149 | @@ -15,16 +15,28 @@
d_arrow(
+actor, event
)%0A%7B%0A%09if(
@@ -134,20 +134,21 @@
tion = (
-this
+actor
.flipped
@@ -1008,14 +1008,8 @@
rrow
-, this
);%0A%09
|
deb07c87a4b5d69eaa8ca1046592673a70af2302 | fix editor keyup event. | app/assets/javascripts/editor.js | app/assets/javascripts/editor.js | //= require_self
//= require_tree ./editor
Mousetrap.stopCallback = function(e, element, combo) {
// stop for input, select, and textarea
return element.tagName == 'INPUT' || element.tagName == 'SELECT' || element.tagName == 'TEXTAREA';
};
var Editor = function(options) {
this.editable_selector = options.editable;
this.editable = $(options.editable);
this.sanitize = new Editor.Sanitize(this.editable);
this.formator = new Editor.Formator(this);
this.formator.exec('defaultParagraphSeparator', 'p');
this.editable.focus();
this.undoManager = new Editor.UndoManager(this.editable);
if (options.toolbar) {
this.toolbar = new Editor.Toolbar(this, options.toolbar);
}
this.connectShortcuts();
this.initParagraph();
var _this = this;
this.editable.on('keyup mouseup', function() {
_this.storeRange();
});
this.editable.on({
keyup: function(event) {
_this.keyup(event);
},
keydown: function(event) {
_this.keydown(event);
},
input: function(event) {
_this.input(event);
},
paste: function(event) {
_this.paste(event);
}
});
var is_chrome = navigator.userAgent.indexOf('Chrome') > -1;
var is_safari = navigator.userAgent.indexOf("Safari") > -1;
// In mac, chrome in safari trigger input event when typing pinyin,
// so use textInput event.
if (is_chrome || is_safari) {
this.editable.on('textInput', function() {
_this.undoManagerSave();
});
} else {
this.editable.on('input', function() {
_this.undoManagerSave();
});
}
};
Editor.prototype = {
shortcuts: {
'bold' : ['ctrl+b'],
'italic' : ['ctrl+i'],
'image' : ['ctrl+g'],
'strikeThrough' : ['ctrl+d'],
'underline' : ['ctrl+shift+l'],
'link' : ['ctrl+l'],
'unorderedList' : ['ctrl+u'],
'orderedList' : ['ctrl+o'],
'p' : ['ctrl+p'],
'h1' : ['ctrl+1'],
'h2' : ['ctrl+2'],
'h3' : ['ctrl+3'],
'h4' : ['ctrl+4'],
'code' : ['ctrl+k'],
'blockquote' : ['ctrl+q'],
'undo' : ['ctrl+z'],
'redo' : ['ctrl+y', 'ctrl+shift+z']
},
connectShortcuts: function() {
var _this = this;
$.each(this.shortcuts, function(method, key) {
if (_this.formator[method]) {
Mousetrap.bind(key, function(event) {
event.preventDefault();
if (!_this.hasRange()) {
_this.restoreRange();
}
_this.formator[method]();
});
} else if (_this[method]) {
Mousetrap.bind(key, function(event) {
event.preventDefault();
_this[method]();
});
}
});
},
paste: function(event) {
this.dirty = true;
},
input: function(event) {
var _this = this;
if (_this.dirty) {
_this.sanitize.run();
_this.dirty = false;
}
},
selectContents: function(contents) {
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var start = contents.first()[0];
var end = contents.last()[0];
range.setStart(start, 0);
range.setEnd(end, end.childNodes.length || end.length); // text node don't have childNodes
selection.removeAllRanges();
selection.addRange(range);
},
keyup: function() {
this.initParagraph();
switch (event.keyCode) {
case 8: // Backspace
case 46: // Delete
this.undoManager.save();
break;
}
},
keydown: function(event) {
switch (event.keyCode) {
case 8: // Backspace
this.backspcae(event);
break;
case 13: // Enter
this.enter(event);
break;
}
},
undoManagerSave: function() {
var _this = this;
setTimeout(function() {
_this.undoManager.save();
}, 0); // webkit don't get right range offset, so setTimout to fix
},
backspcae: function(event) {
// Stop Backspace when empty, avoid cursor flash
if (this.editable.html() === '<p><br></p>') {
event.preventDefault();
}
},
enter: function(event) {
// If in pre code, insert \n
if (document.queryCommandValue('formatBlock') === 'pre') {
event.preventDefault();
var selection = window.getSelection();
var range = selection.getRangeAt(0);
var rangeAncestor = range.commonAncestorContainer;
var $pre = $(rangeAncestor).closest('pre');
range.deleteContents();
var isLastLine = ($pre.find('code').contents().last()[0] === range.endContainer);
var isEnd = (range.endContainer.length === range.endOffset);
var node = document.createTextNode("\n");
range.insertNode(node);
// keep two \n at the end, fix webkit eat \n issues.
if (isLastLine && isEnd) {
$pre.find('code').append(document.createTextNode("\n"));
}
range.setStartAfter(node);
range.setEndAfter(node);
selection.removeAllRanges();
selection.addRange(range);
}
},
undo: function() {
this.undoManager.undo();
},
redo: function() {
this.undoManager.redo();
},
initParagraph: function() {
// chrome is empty and firefox is <br>
if (this.editable.html() === '' || this.editable.html() === '<br>') {
this.formator.p();
}
},
storeRange: function() {
var selection = document.getSelection();
var range = selection.getRangeAt(0);
this.storedRange = {
startContainer: range.startContainer,
startOffset: range.startOffset,
endContainer: range.endContainer,
endOffset: range.endOffset
};
},
restoreRange: function() {
var selection = document.getSelection();
var range = document.createRange();
range.setStart(this.storedRange.startContainer, this.storedRange.startOffset);
range.setEnd(this.storedRange.endContainer, this.storedRange.endOffset);
selection.removeAllRanges();
selection.addRange(range);
},
hasRange: function() {
var selection = document.getSelection();
return selection.rangeCount && $(selection.getRangeAt(0).commonAncestorContainer).closest(this.editable_selector).length;
}
};
| JavaScript | 0 | @@ -3201,32 +3201,37 @@
keyup: function(
+event
) %7B%0A this.ini
|
288cedfce0b7fdabcdeb910ff4d4cc1ffe90b385 | Make groups non-capturing. | utils/unambiguous.js | utils/unambiguous.js | 'use strict'
exports.__esModule = true
const pattern = /(^|;)\s*(export|import)((\s+\w)|(\s*[{*=]))/m
/**
* detect possible imports/exports without a full parse.
*
* A negative test means that a file is definitely _not_ a module.
* A positive test means it _could_ be.
*
* Not perfect, just a fast way to disqualify large non-ES6 modules and
* avoid a parse.
* @type {RegExp}
*/
exports.test = function isMaybeUnambiguousModule(content) {
return pattern.test(content)
}
// future-/Babel-proof at the expense of being a little loose
const unambiguousNodeType = /^(((Exp|Imp)ort.*Declaration)|TSExportAssignment)$/
/**
* Given an AST, return true if the AST unambiguously represents a module.
* @param {Program node} ast
* @return {Boolean}
*/
exports.isModule = function isUnambiguousModule(ast) {
return ast.body.some(node => unambiguousNodeType.test(node.type))
}
| JavaScript | 0.000017 | @@ -570,18 +570,21 @@
pe = /%5E(
-((
+?:(?:
Exp%7CImp)
@@ -599,17 +599,16 @@
laration
-)
%7CTSExpor
|
e6727b3ef98c4c6fc6c560a79d9e38041397a3f2 | fix for service worker throwing error on failed requests | static/pwabuilder-sw.js | static/pwabuilder-sw.js | //This is the "Offline page" service worker
//Install stage sets up the offline page in the cache and opens a new cache
self.addEventListener('install', (event) => {
const offlinePage = new Request('offline.html', {
headers: { 'Content-Type': 'text/html' }
});
event.waitUntil(
fetch(offlinePage).then((response) => {
return caches.open('pwabuilder-offline').then((cache) => {
console.log('[PWA Builder] Cached offline page during install: '+ response.url);
return cache.put(offlinePage, response);
});
}));
});
//If any fetch fails, it will show the offline page.
//Maybe this should be limited to HTML documents?
self.addEventListener('fetch', (event) => {
event.respondWith(
fetch(event.request).catch((error) => {
console.error( '[PWA Builder] Network request Failed. Serving offline page. ' + error );
return caches.open('pwabuilder-offline').then((cache) => {
return cache.match('offline.html');
});
}));
});
//This is an event that can be fired from your page to tell the SW to update the offline page
self.addEventListener('refreshOffline', (response) => {
return caches.open('pwabuilder-offline').then((cache) => {
console.log('[PWA Builder] Offline page updated from refreshOffline event: '+ response.url);
return cache.put(offlinePage, response);
});
});
| JavaScript | 0 | @@ -1,18 +1,19 @@
//
+
This is the %22Off
@@ -41,16 +41,17 @@
rker%0A%0A//
+
Install
@@ -284,16 +284,18 @@
tUntil(%0A
+
fetch(
@@ -324,24 +324,26 @@
ponse) =%3E %7B%0A
+
return c
@@ -395,24 +395,26 @@
=%3E %7B%0A
+
+
console.log(
@@ -465,16 +465,17 @@
stall: '
+
+ respon
@@ -485,24 +485,26 @@
url);%0A
+
+
return cache
@@ -536,20 +536,24 @@
e);%0A
+
+
%7D);%0A
+
%7D));%0A%7D
@@ -558,16 +558,17 @@
%0A%7D);%0A%0A//
+
If any f
@@ -572,16 +572,33 @@
y fetch
+for an html file
fails, i
@@ -631,102 +631,104 @@
ge.%0A
-//Maybe this should be limited to HTML documents?%0Aself.addEventListener('fetch', (event) =%3E %7B%0A
+self.addEventListener('fetch', (event) =%3E %7B%0A if (event.request.destination === %22document%22) %7B%0A
ev
@@ -744,24 +744,26 @@
ndWith(%0A
+
fetch(event.
@@ -812,17 +812,16 @@
e.error(
-
'%5BPWA Bu
@@ -882,17 +882,16 @@
+ error
-
);%0A
@@ -996,36 +996,40 @@
e.html');%0A
+
%7D);%0A
+
%7D));%0A%7D);%0A%0A//
@@ -1021,23 +1021,28 @@
%7D));%0A
+ %7D%0A
%7D);%0A%0A//
+
This is
@@ -1322,16 +1322,17 @@
event: '
+
+ respon
|
92f3bcad825f9e744e1c6822852fafb36aeaa4eb | Fix broken whitespace vs. SPACE logic | components/Card/Card.js | components/Card/Card.js | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, {PropTypes} from 'react'
import config from '../../config'
import moment from 'moment'
import BlockButton from '../buttons/BlockButton'
import ProgressMeter from '../progress-meter'
import CardMetadata from '../CardMetadata'
import CardHelpDirections from '../CardHelpDirections'
import './Card.scss'
import MarkdownIt from 'markdown-it'
let md = new MarkdownIt()
let answerColor = 'gray'; // '#3E96FF' // 'rgb(0, 62, 136)' // #0678FE'
function linearTransform(domain, range, x) {
// rise / run
let slope = (range[1] - range[0]) / (domain[1] - domain[0])
// b = y - mx
var intercept = range[0] - slope * domain[0]
if (typeof x === "number") {
// If a domain value was provided, return the transformed result
return slope * x + intercept
} else {
// If no domain value was provided, return a function
return (x) => { return slope * x + intercept }
}
}
let getRotation = linearTransform([-1, 1], [-10, 10])
let getYTranslation = linearTransform([0, 1], [0, -100])
let starStyle = {
display: 'block',
position: 'absolute',
color: 'gold',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
fontSize: '128px',
opacity: 0.8
}
let star = <span style={starStyle} dangerouslySetInnerHTML={{__html: '★'}}/>
export default class Card extends React.Component {
constructor(props) {
super(props)
this.state = {
isShowingQuestion: !!props.isShowingQuestion,
skipOpacity: 0,
backOpacity: 0
}
}
showAnswer() {
this.setState({
isShowingQuestion: false
})
}
showQuestion() {
this.setState({
isShowingQuestion: true
})
}
flipCard() {
this.props.onFlip()
this.setState({
isShowingQuestion: !this.state.isShowingQuestion
})
}
onTouchStart(e) {
let {clientX:x, clientY:y} = e.targetTouches[0]
this.setState({
lastTouchStart: {x, y}
})
}
onTouchMove(e) {
let {clientX:x, clientY:y} = e.targetTouches[0]
let lastTouchStart = this.state.lastTouchStart
let deltaXRatio = (x - lastTouchStart.x) / window.document.documentElement.clientWidth
let deltaYRatio = 3 * (y - lastTouchStart.y) / window.document.documentElement.clientHeight
let rgbaValue = deltaXRatio > 0 ? `rgba(0, 128, 0, ${Math.abs(deltaXRatio)})` : `rgba(204, 0, 0, ${Math.abs(deltaXRatio)})`
this.setState({
backgroundColor: rgbaValue,
skipOpacity: deltaYRatio > 0 ? deltaYRatio : 0,
backOpacity: deltaYRatio < 0 ? Math.abs(deltaYRatio) : 0
})
}
onTouchEnd(e) {
this.setState({
backgroundColor: 'transparent'
})
}
onKeyDown(e) {
if (e.code === 'ArrowUp') this.props.onBackToAllDecks()
else if (e.code === 'ArrowLeft') this.props.onAnsweredIncorrectly()
else if (e.code === 'ArrowRight') this.props.onAnsweredCorrectly()
else if (e.code === 'ArrowDown') this.props.onSkip()
else if (e.code === 'Space') this.flipCard()
else if (e.code === 'Escape') this.props.onBackToAllDecks()
else this.flipCard()
}
componentDidMount() {
if (window.iNoBounce) window.iNoBounce.enable()
this._keyDownListener = this.onKeyDown.bind(this)
document.addEventListener('keydown', this._keyDownListener)
}
componentWillUnmount() {
document.removeEventListener('keydown', this._keyDownListener)
}
render() {
let color = this.state.isShowingQuestion ? 'black' : answerColor
let style = {
height: window.document.documentElement.clientHeight - 20 - 15, // to account for padding + navigation
color,
backgroundColor: this.state.backgroundColor || 'transparent'
}
let text = this.state.isShowingQuestion ? this.props.question : this.props.answer
let htmlText = text
.replace(/\s\s\s/g, "\n\n")
.replace(/\s\s/g, "\n")
.replace(/\\t/g, ' ')
.replace(/^(Definition):\s/, '### $1\n')
let html = md.render(htmlText)
.replace(/___/g, '<span class="blankspace"></span>')
let dangerousHtml = {__html: html}
return (
<div className="flashcard" style={style} onClick={this.flipCard.bind(this)} onTouchStart={this.onTouchStart.bind(this)} onTouchMove={this.onTouchMove.bind(this)} onTouchEnd={this.onTouchEnd.bind(this)}>
<h1 className="flashcard-header">{this.props.hasAnsweredAllCorrectly ? star : ''} {this.state.isShowingQuestion ? "Question" : "Answer"}</h1>
<div dangerouslySetInnerHTML={dangerousHtml} style={{margin: 'auto', width: '80%', left: '10%'}}/>
<span style={{fontSize: 24, position:'absolute', display: 'block', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', opacity: this.state.skipOpacity}}>Skip</span>
<span style={{fontSize: 24, position:'absolute', display: 'block', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', opacity: this.state.backOpacity}}>Back</span>
<CardMetadata {...this.props} />
</div>
)
}
}
Card.defaultProps = { lastSeen: null, isShowingQuestion: true, onFlip: function() {} }
| JavaScript | 0.999974 | @@ -3933,14 +3933,11 @@
ce(/
-%5Cs%5Cs%5Cs
+
/g,
@@ -3970,12 +3970,10 @@
ce(/
-%5Cs%5Cs
+
/g,
@@ -4011,14 +4011,51 @@
/g,
-'
+%22
-'
+%22)%0A .replace(/%5C%5Cn/g, %22%5Cn%5Cn%22
)%0A
@@ -4097,17 +4097,17 @@
s/,
-'
+%22
### $1%5Cn
')%0A%0A
@@ -4102,17 +4102,17 @@
### $1%5Cn
-'
+%22
)%0A%0A l
|
374850e2e33f0f5ffc0d71999d690c3dc8a1195c | WebSocket hard timeout | src/events/websocket/WebSocketClients.js | src/events/websocket/WebSocketClients.js | import { OPEN } from 'ws'
import {
WebSocketConnectEvent,
WebSocketDisconnectEvent,
WebSocketEvent,
} from './lambda-events/index.js'
import debugLog from '../../debugLog.js'
import serverlessLog from '../../serverlessLog.js'
import {
DEFAULT_WEBSOCKETS_API_ROUTE_SELECTION_EXPRESSION,
DEFAULT_WEBSOCKETS_ROUTE,
} from '../../config/index.js'
import { jsonPath } from '../../utils/index.js'
const { parse, stringify } = JSON
export default class WebSocketClients {
#clients = new Map()
#lambda = null
#options = null
#webSocketRoutes = new Map()
#websocketsApiRouteSelectionExpression = null
#idleTimeouts = new WeakMap()
constructor(serverless, options, lambda) {
this.#lambda = lambda
this.#options = options
this.#websocketsApiRouteSelectionExpression =
serverless.service.provider.websocketsApiRouteSelectionExpression ||
DEFAULT_WEBSOCKETS_API_ROUTE_SELECTION_EXPRESSION
}
_addWebSocketClient(client, connectionId) {
this.#clients.set(client, connectionId)
this.#clients.set(connectionId, client)
this._onWebSocketUsed(connectionId)
}
_removeWebSocketClient(client) {
const connectionId = this.#clients.get(client)
this.#clients.delete(client)
this.#clients.delete(connectionId)
return connectionId
}
_getWebSocketClient(connectionId) {
return this.#clients.get(connectionId)
}
_onWebSocketUsed(connectionId) {
const client = this._getWebSocketClient(connectionId)
this._clearIdleTimeout(client)
const timeoutId = setTimeout(() => {
debugLog(`timeout:idle:${connectionId}`)
client.close(1001, 'Going away')
}, this.#options.webSocketIdleTimeout * 1000)
this.#idleTimeouts.set(client, timeoutId)
}
_clearIdleTimeout(client) {
const timeoutId = this.#idleTimeouts.get(client)
clearTimeout(timeoutId)
}
async _processEvent(websocketClient, connectionId, route, event) {
let functionKey = this.#webSocketRoutes.get(route)
if (!functionKey && route !== '$connect' && route !== '$disconnect') {
functionKey = this.#webSocketRoutes.get('$default')
}
if (!functionKey) {
return
}
const sendError = (err) => {
if (websocketClient.readyState === OPEN) {
websocketClient.send(
stringify({
connectionId,
message: 'Internal server error',
requestId: '1234567890',
}),
)
}
// mimic AWS behaviour (close connection) when the $connect route handler throws
if (route === '$connect') {
websocketClient.close()
}
debugLog(`Error in route handler '${functionKey}'`, err)
}
const lambdaFunction = this.#lambda.get(functionKey)
lambdaFunction.setEvent(event)
// let result
try {
/* result = */ await lambdaFunction.runHandler()
// TODO what to do with "result"?
} catch (err) {
console.log(err)
sendError(err)
}
}
_getRoute(value) {
let json
try {
json = parse(value)
} catch (err) {
return DEFAULT_WEBSOCKETS_ROUTE
}
const routeSelectionExpression = this.#websocketsApiRouteSelectionExpression.replace(
'request.body',
'',
)
const route = jsonPath(json, routeSelectionExpression)
if (typeof route !== 'string') {
return DEFAULT_WEBSOCKETS_ROUTE
}
return route || DEFAULT_WEBSOCKETS_ROUTE
}
addClient(webSocketClient, request, connectionId) {
this._addWebSocketClient(webSocketClient, connectionId)
const connectEvent = new WebSocketConnectEvent(
connectionId,
request,
this.#options,
).create()
this._processEvent(webSocketClient, connectionId, '$connect', connectEvent)
const hardTimeout = setTimeout(() => {
debugLog(`timeout:hard:${connectionId}`)
webSocketClient.close()
}, this.#options.webSocketHardTimeout * 1000)
webSocketClient.on('close', () => {
debugLog(`disconnect:${connectionId}`)
this._removeWebSocketClient(webSocketClient)
const disconnectEvent = new WebSocketDisconnectEvent(
connectionId,
).create()
clearTimeout(hardTimeout)
this._clearIdleTimeout(webSocketClient)
this._processEvent(
webSocketClient,
connectionId,
'$disconnect',
disconnectEvent,
)
})
webSocketClient.on('message', (message) => {
debugLog(`message:${message}`)
const route = this._getRoute(message)
debugLog(`route:${route} on connection=${connectionId}`)
const event = new WebSocketEvent(connectionId, route, message).create()
this._onWebSocketUsed(connectionId)
this._processEvent(webSocketClient, connectionId, route, event)
})
}
addRoute(functionKey, route) {
// set the route name
this.#webSocketRoutes.set(route, functionKey)
serverlessLog(`route '${route}'`)
}
close(connectionId) {
const client = this._getWebSocketClient(connectionId)
if (client) {
client.close()
return true
}
return false
}
send(connectionId, payload) {
const client = this._getWebSocketClient(connectionId)
if (client) {
this._onWebSocketUsed(connectionId)
client.send(payload)
return true
}
return false
}
}
| JavaScript | 0.999995 | @@ -638,16 +638,48 @@
eakMap()
+%0A #hardTimeouts = new WeakMap()
%0A%0A cons
@@ -1123,32 +1123,79 @@
d(connectionId)%0A
+ this._addHardTimeout(client, connectionId)%0A
%7D%0A%0A _removeWe
@@ -1458,16 +1458,402 @@
d)%0A %7D%0A%0A
+ _addHardTimeout(client, connectionId) %7B%0A const timeoutId = setTimeout(() =%3E %7B%0A debugLog(%60timeout:hard:$%7BconnectionId%7D%60)%0A client.close(1001, 'Going away')%0A %7D, this.#options.webSocketHardTimeout * 1000)%0A this.#hardTimeouts.set(client, timeoutId)%0A %7D%0A%0A _clearHardTimeout(client) %7B%0A const timeoutId = this.#hardTimeouts.get(client)%0A clearTimeout(timeoutId)%0A %7D%0A%0A
_onWeb
@@ -1967,24 +1967,75 @@
eout(client)
+%0A debugLog(%60timeout:idle:$%7BconnectionId%7D:reset%60)
%0A%0A const
@@ -2101,32 +2101,40 @@
:$%7BconnectionId%7D
+:trigger
%60)%0A client.
@@ -4268,179 +4268,8 @@
t)%0A%0A
- const hardTimeout = setTimeout(() =%3E %7B%0A debugLog(%60timeout:hard:$%7BconnectionId%7D%60)%0A webSocketClient.close()%0A %7D, this.#options.webSocketHardTimeout * 1000)%0A%0A
@@ -4508,29 +4508,39 @@
%0A%0A
+this._
clear
+Hard
Timeout(
hardTime
@@ -4531,26 +4531,30 @@
Timeout(
-hardTimeou
+webSocketClien
t)%0A
|
d5df7d02aa2de678183b28f15004425b9ec37f74 | Add logger filename to volume action | lib/actions/volume.js | lib/actions/volume.js | var utils = require('radiodan-client').utils,
defaultLogger = utils.logger;
function boundVolume(vol) {
if(vol < 0) {
vol = 0;
} else if(vol > 100) {
vol = 100;
}
return vol;
}
module.exports = function(radio, command, logger) {
logger = logger || defaultLogger;
var commandPromise = utils.promise.reject(new Error("Volume Command not found"));
if(command.hasOwnProperty('value')) {
var absoluteVol = parseInt(command.value);
commandPromise = radio.sendCommands([
['setvol', boundVolume(absoluteVol)]
]);
} else if(command.hasOwnProperty('diff')) {
commandPromise = radio.status()
.then(function(status) {
var volume = status.volume;
var newVol = parseInt(volume)+parseInt(command.diff);
return radio.sendCommands([['setvol', boundVolume(newVol)]]);
}, utils.failedPromiseHandler());
}
return commandPromise;
};
| JavaScript | 0.000001 | @@ -71,16 +71,28 @@
s.logger
+(__filename)
;%0A%0Afunct
|
943dbc52f62234bee2b4dfa64536273ea0cff229 | Use newer buffered proxy | blueprints/ember-state-services/index.js | blueprints/ember-state-services/index.js | module.exports = {
normalizeEntityName: function() {}, // no-op since we're just adding dependencies
afterInstall: function() {
return this.addAddonToProject('ember-buffered-proxy', '^0.5.1');
}
};
| JavaScript | 0 | @@ -192,11 +192,11 @@
'%5E0.
-5.1
+6.0
');%0A
|
e1d7c0041c36e4bee2044617ba084ad4a7768484 | Ensure match 'A-B' is _in addition to_ existing 'A::B' match | assets/js/dataTables.filter.perlModule.js | assets/js/dataTables.filter.perlModule.js | /**
* This filtering plugin will allow matching of module names in either
* form of 'Foo::Bar', or 'Foo-Bar'.
*
* Based on dataTables.filter.phoneNumber.js
*
* @summary Make Perl module names searchable
* @name Perl module
* @author Zak B. Elep
*
* @example
* $(document).ready(function() {
* $('#example').dataTable({
* columDefs: [
* { type: 'perlModule', target: 1 }
* ]
* });
* });
*/
jQuery.fn.DataTable.ext.type.search.perlModule = function(data) {
return !data ?
'' :
typeof data === 'string' ?
data.replace(/::/g, '-') :
data;
};
| JavaScript | 0.999995 | @@ -569,24 +569,31 @@
g' ?%0A
+ data +
data.replac
|
8667d897ce3fa26f5ed7b9b56d0a3a465a8c6729 | add actual heavy object example to flyweight | specs/unit/patterns/structural/flyweight.spec.js | specs/unit/patterns/structural/flyweight.spec.js | /* globals expect, beforeEach, it, describe, spyOn */
import flyweightBuilder from '../../../../src/patterns/structural/flyweight.js';
import singletonBuilder from '../../../../src/patterns/creational/singleton.js';
describe('flyweight', function() {
var Flyweight;
var flyweight;
beforeEach(function() {
Flyweight = flyweightBuilder({
publics: {
heuristic(name, obj) {
return this.flyweights[name] = this.flyweights[name] || obj;
}
}
}).build();
flyweight = new Flyweight();
});
it('should allow empty options', function() {
var emptyOptions = undefined;
var Flyweight = flyweightBuilder(emptyOptions).build();
var flyweight = new Flyweight();
flyweight.create('test', {test: 'testing'});
expect(flyweight.flyweights['test'].test).toEqual('testing');
});
it('should throw an error', function() {
expect(function() {
var Flyweight = flyweightBuilder().build();
var flyweight = new Flyweight();
flyweight.create();
}).not.toThrowError('Flyweight is missing heuristic public method.');
});
it('should create a flyweight object', function() {
var test = flyweight.create('test', {
test: 'testing'
});
expect(test).toBeDefined();
expect(test.test).toEqual('testing');
});
it('should return a previously created flyweight object', function() {
flyweight.create('test', {
test: 'testing'
});
var test = flyweight.create('test', {
test: 'already created'
});
expect(test).toBeDefined();
expect(test.test).toEqual('testing');
expect(test.test).not.toEqual('already created');
});
describe('Mid Level: Memoization with Flyweight', function() {
var FactorialMemoizationFlyweight;
var factorialMemoizationFlyweight;
var factorials;
beforeEach(function() {
factorials = [2, 3, 4];
FactorialMemoizationFlyweight = singletonBuilder(flyweightBuilder({
publics: {
heuristic(val) {
return this.flyweights[val + ''] = this.flyweights[val] || this.factorial(val);
},
factorial(val) {
if(val <= 1) return 1;
return val * this.factorial(val - 1);
}
}
})).build();
factorialMemoizationFlyweight = new FactorialMemoizationFlyweight();
factorials.forEach(factorialMemoizationFlyweight.create.bind(factorialMemoizationFlyweight));
});
it('should memoize the values', function() {
expect(Object.keys(factorialMemoizationFlyweight.flyweights).length).toEqual(factorials.length);
});
it('should return memoized values', function() {
// we spy on factorial method, AFTER the initial values were declared already.
spyOn(factorialMemoizationFlyweight, 'factorial');
factorials.forEach(factorialMemoizationFlyweight.create.bind(factorialMemoizationFlyweight));
expect(factorialMemoizationFlyweight.factorial).not.toHaveBeenCalled();
});
});
describe('Advanced Level: Object Creation', function() {
var LightObjectCreation;
var lightObjectCreation;
beforeEach(function() {
LightObjectCreation = flyweightBuilder({
constructor() {
// this overrides the default object.
this.flyweights = [];
},
publics: {
heuristic(params) {
return this.find(params) || this.construct(params);
},
construct(params) {
var heavyObject = {data: params.data};
this.flyweights.push(heavyObject);
return heavyObject;
},
find(params) {
for(var i = 0, l = this.flyweights.length; i < l; i++) {
if(this.flyweights[i].data === params.data) {
return this.flyweights[i];
}
}
return null;
}
}
}).build();
lightObjectCreation = new LightObjectCreation();
spyOn(lightObjectCreation, 'construct').and.callThrough();
lightObjectCreation.create({
data: 13.01 // dummy specific data
});
lightObjectCreation.create({
data: 13.01 // dummy specific data
});
});
it('should only construct the object only once.', function() {
expect(lightObjectCreation.construct).toHaveBeenCalledTimes(1);
});
});
});
| JavaScript | 0.001353 | @@ -3121,24 +3121,217 @@
unction() %7B%0A
+ function HeavyObject(value) %7B%0A this.data = value;%0A this.store = %5B%5D;%0A for(var i = 0; i %3C value; i++)%7B%0A this.store.push(i * Math.random());%0A %7D%0A %7D%0A%0A
LightO
@@ -3357,32 +3357,32 @@
weightBuilder(%7B%0A
-
construc
@@ -3670,15 +3670,24 @@
t =
-%7Bdata:
+new HeavyObject(
para
@@ -3693,17 +3693,17 @@
ams.data
-%7D
+)
;%0A
@@ -4246,35 +4246,32 @@
data: 13
-.01
// dummy specif
@@ -4315,32 +4315,32 @@
eation.create(%7B%0A
+
data: 13
@@ -4343,11 +4343,8 @@
: 13
-.01
//
|
1bf39947827e3b5273edbc52f57a294b1449aafa | Fix whitespace | web-client/GraphQLWebClientWrapper.js | web-client/GraphQLWebClientWrapper.js | import React from 'react';
import GraphQLWebClient from './GraphQLWebClient';
var styles = {
clear: {clear: "both"}
};
export default class GraphQLWebClientWrapper extends React.Component {
constructor(props) {
super(props);
this.state = {
endpoint: this.props.endpoint,
cannedQueries: [
`{ __schema { root_fields { name, description } } }`,
`{ __types { name, description} }`,
`{ __types { name, description, fields { name, description } } }`,
`{ TodoUserClass{ objectId, name, lists:TodoItemListClass_owner { objectId, name, items:TodoItemClass_list { objectId, done, description } } } }`
]
};
this.state.defaultQuery = this.state.cannedQueries[0];
}
onChange(event) {
this.setState({endpoint: event.target.value});
}
onCannedQueryClicked(event) {
this.setState({defaultQuery: event.target.text});
}
render() {
var cannedQueries = this.state.cannedQueries.map((query) => {
return (
<li><a href="#" onClick={this.onCannedQueryClicked.bind(this)}>{query}</a></li>
);
});
return (
<div>
<h1>graphql client</h1>
<label>graphql endpoint:</label>
<input size="50" defaultValue={this.state.endpoint} onChange={this.onChange.bind(this)} />
<hr/>
<GraphQLWebClient
defaultQuery={this.state.defaultQuery}
endpoint={this.state.endpoint}
/>
<ul style={styles.clear}>
<li>Canned Queries:</li>
{cannedQueries}
</ul>
</div>
);
}
}
| JavaScript | 0.999999 | @@ -495,10 +495,16 @@
%7D%60,%0A
-%09%09
+
%60%7B T
|
8b00da31c6854d9c5d780d3c89e41fe780765835 | add task to copy assets in public folder | grunt-tasks.js | grunt-tasks.js |
module.exports = function(grunt, vendorFiles){
var environment = process.env.NODE_ENV || 'development';
environment = environment.toLowerCase();
var config = {
env : {
dev: {
NODE_ENV : 'development'
},
prod : {
NODE_ENV : 'production'
},
test: {
NODE_ENV: 'test'
}
},
preprocess : {
'default' : {
src : 'app/index.html',
dest : 'public/index.html'
},
},
clean: {
'default': [
'public'
]
},
// install bower components
"bower-install-simple": {
options: {
color: true
},
"default": {
options: {
production: environment === 'production'
}
}
},
// build the application with browserify
browserify: {
options: {
transform: ['envify']
},
'default': {
src: ['app/frontend/index.js'],
dest: 'public/app.js'
// options: {
// external: ['jquery', 'momentWrapper'],
// }
}
},
// link bower_components in public
symlink: {
options: {
overwrite: true
},
'bower_components': {
src: 'bower_components',
dest: 'public/bower_components'
},
"config": {
files: [
{src: 'config/frontend/'+environment+'.js', dest: 'config/frontend/index.js'},
{src: 'config/server/'+environment+'.js', dest: 'config/server/index.js'}
]
}
},
// // generate configuration files for a specific environement (see NODE_ENV)
// copy: {
// "config": {
// files: [
// {nonull: true, src: 'config/frontend/'+environment+'.js', dest: 'config/frontend.config.js', filter:'isFile'},
// {nonull: true, src: 'config/server/'+environment+'.js', dest: 'config/server.config.js'},
// ]
// }
// },
// build templates into public/templates
emberTemplates: {
'default': {
options: {
templateRegistration: function(name, content) {
name = name.split('/').slice(-1)[0].replace('.', '/');
return 'Ember.TEMPLATES["' + name + '"] = ' + content;
}
},
files: {
"./public/templates.js": ["app/frontend/templates/**/*.hbs", "app/frontend/templates/**/*.handlebars"]
}
}
},
// concat javascript
concat: {
'default': {
src: vendorFiles.js,
dest: 'public/vendors.js'
}
},
// minify js
uglify: {
'default': {
options: {
mangle: false
},
files: {
'public/vendors.min.js': ['public/vendors.js'],
'public/app.min.js': ['public/app.js'],
'public/templates.min.js': ['public/templates.js']
}
}
},
// minify css
cssmin: {
'default': {
options: {
target: './public'
},
files: {
'public/vendors.min.css': vendorFiles.css,
'public/app.min.css': 'app/app.css'
}
}
},
// watch assets and server
watch: {
'default': {
files: ['app/**/*', 'config/**/*'],
tasks: ['build'],
}
},
// restart server if public/app.js is changed
nodemon: {
'default': {
script: 'app/server',
options: {
watch: 'public/app.js'
}
}
},
concurrent: {
'default': {
options: {
logConcurrentOutput: true
},
tasks: ['nodemon', 'watch']
}
},
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
attention: {
'environment': {
options: {
message: 'Building for the *'+environment+'* environment\n',
border: 'comment',
borderColor: 'gray'
}
},
'build-success': {
options: {
message: 'Built with success!\n\nTo start the server, type\n *$ npm start*',
border: 'comment',
borderColor: 'gray'
}
}
}
};
require('jit-grunt')(grunt);
grunt.loadNpmTasks("grunt-extend-config");
grunt.initConfig(config);
grunt.registerTask('eureka:setenv-development', ['env:dev']);
grunt.registerTask('eureka:setenv-production', ['env:prod']);
grunt.registerTask('eureka:setenv-test', ['env:test']);
grunt.registerTask('eureka:clean', ['clean']);
grunt.registerTask('eureka:configure', ['attention:environment', 'symlink:config']);
grunt.registerTask('eureka:build-templates', ['emberTemplates']);
grunt.registerTask('eureka:_build', ['eureka:clean', 'eureka:configure' , 'preprocess', 'symlink:bower_components', 'concat', 'cssmin', 'browserify', 'eureka:build-templates']);
grunt.registerTask('eureka:build-test', ['eureka:_build']);
grunt.registerTask('eureka:build', ['eureka:_build', 'attention:build-success']);
grunt.registerTask('eureka:dist', ['eureka:_build', 'uglify', 'attention:build-success']);
grunt.registerTask('eureka:live', ['concurrent']);
grunt.registerTask('eureka:test', ['karma']);
grunt.registerTask('eureka:install', ['bower-install-simple', 'eureka:configure', 'eureka:build']);
grunt.registerTask('build', ['eureka:build']);
};
| JavaScript | 0 | @@ -1925,97 +1925,8 @@
- // // generate configuration files for a specific environement (see NODE_ENV)%0A //
cop
@@ -1942,22 +1942,19 @@
-//
- %22config
+%22assets
%22: %7B
@@ -1962,26 +1962,24 @@
-//
files:
@@ -1962,33 +1962,32 @@
-
files: %5B%0A
@@ -1978,35 +1978,32 @@
files: %5B%0A
- //
%7Bno
@@ -2018,214 +2018,68 @@
ue,
-src: 'config/frontend/'+environment+'.js', dest: 'config/frontend.config.js', filter:'isFile'%7D,%0A // %7Bnonull: true, src: 'config/server/'+environment+'.js', dest: 'config/server.config.js'
+cwd: 'app', src: 'assets/**/*', dest: 'public', expand: true
%7D,%0A
@@ -2080,27 +2080,24 @@
ue%7D,%0A
- //
%5D%0A
@@ -2102,19 +2102,16 @@
%0A
- //
%7D%0A
@@ -2116,19 +2116,16 @@
%0A
- //
%7D,%0A%0A
@@ -3761,16 +3761,63 @@
g/**/*'%5D
+.concat(vendorFiles.js).concat(vendorFiles.css)
,%0A
@@ -5495,32 +5495,32 @@
erTemplates'%5D);%0A
-
grunt.regist
@@ -5656,16 +5656,31 @@
serify',
+ 'copy:assets',
'eureka
|
122947ed42ca4a427f9d2375e91433bf33ae3d77 | Use REST API to unlink user device | web/app/view/UserDevicesController.js | web/app/view/UserDevicesController.js | /*
* Copyright 2015 Anton Tananaev (anton.tananaev@gmail.com)
*
* 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.
*/
Ext.define('Traccar.view.UserDevicesController', {
extend: 'Ext.app.ViewController',
alias: 'controller.userDevices',
init: function () {
this.userId = this.getView().user.getData().id;
this.getView().getStore().load({
scope: this,
callback: function (records, operation, success) {
var userStore = Ext.create('Traccar.store.Devices');
userStore.load({
params: {
userId: this.userId
},
scope: this,
callback: function (records, operation, success) {
var i, index;
if (success) {
for (i = 0; i < records.length; i++) {
index = this.getView().getStore().find('id', records[i].getData().id);
this.getView().getSelectionModel().select(index, true, true);
}
}
}
});
}
});
},
onBeforeSelect: function (object, record, index) {
Ext.Ajax.request({
scope: this,
url: '/api/rest/permissions',
jsonData: {
userId: this.userId,
deviceId: record.getData().id
},
callback: function (options, success, response) {
if (!success) {
Traccar.app.showError(response);
}
}
});
},
onBeforeDeselect: function (object, record, index) {
Ext.Ajax.request({
scope: this,
method: 'DELETE',
url: '/api/device/unlink',
jsonData: {
userId: this.userId,
deviceId: record.getData().id
},
callback: function (options, success, response) {
if (!success) {
Traccar.app.showError(response);
}
}
});
}
});
| JavaScript | 0 | @@ -2368,21 +2368,24 @@
api/
-device/unlink
+rest/permissions
',%0A
|
5fa217548db80492ef1e66e678f9572c9d1caa5c | fix a bug when refreshing a token on authservices | static/app/scripts/services/authservices.js | static/app/scripts/services/authservices.js | var accountservices = angular.module('crmEngine.authservices',[]);
accountservices.factory('Auth', function($http) {
var Auth = function(data) {
angular.extend(this, data);
};
Auth.checkGapiToken = function(){
var timeNow = new Date().getTime()/1000;
var gapiToken = gapi.auth.getToken();
if (gapiToken){
var expirationTime = gapiToken.expires_at;
var diff = expirationTime - timeNow;
if (diff>0){
return true;
}
}
return false;
}
Auth.initWithLocalStorage = function(){
var timeNow = new Date().getTime()/1000;
if (localStorage.getItem("access_token")){
var access_token = localStorage.getItem("access_token");
var authResultexpiration = localStorage.getItem("authResultexpiration");
var diff = authResultexpiration - timeNow;
if (diff>0 && access_token!="null"){
Auth.$scope.immediateFailed = false;
Auth.$scope.isSignedIn = true;
gapi.auth.setToken({'access_token':access_token});
Auth.$scope.runTheProcess();
}
else{
// refresh token
Auth.refreshToken();
}
// render Google+ sign-in
}else{
gapi.signin.render('myGsignin', {
'callback': Auth.signIn,
'clientid': '987765099891.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/userinfo.email',
'theme': 'dark',
'cookiepolicy': 'single_host_origin',
'accesstype': 'online',
'width':'wide'
});
}
}
Auth.goAhead = function(authResult){
if (typeof(Storage) != "undefined") {
localStorage['is_signed_in'] = true;
localStorage['access_token']=authResult.access_token;
localStorage['authResultexpiration'] = authResult.expires_at;
}
if (!window.access_token) {
window.is_signed_in = true;
window.access_token = authResult.access_token;
window.authResultexpiration = authResult.expires_at;
}
var access_token = authResult.access_token;
gapi.auth.setToken({'access_token':access_token});
Auth.$scope.runTheProcess();
}
Auth.initSimple = function(){
var timeNow = new Date().getTime()/1000;
if (window.is_signed_in){
var diff = window.authResultexpiration - timeNow;
if (diff>0){
Auth.$scope.immediateFailed = false;
Auth.$scope.isSignedIn = true;
Auth.$scope.runTheProcess();
}
else{
// refresh token
Auth.refreshToken();
}
// render Google+ sign-in
}else{
// check the gapi token
var isGapiOk = Auth.checkGapiToken();
if (isGapiOk){
var gapiToken = gapi.auth.getToken();
Auth.processAuth(gapiToken);
}else{
gapi.signin.render('myGsignin', {
'callback': Auth.signIn,
'clientid': '987765099891.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/userinfo.email',
'theme': 'dark',
'cookiepolicy': 'single_host_origin',
'accesstype': 'online',
'width':'wide'
});
}
}
}
Auth.init = function($scope){
// make sure there is only one instance of Auth.init executed
if (!window.countInitExec){
window.countInitExec = 1;
}else{
window.countInitExec = window.countInitExec+1;
var timeNow = new Date().getTime()/1000;
Auth.$scope = $scope;
if (typeof(Storage) != "undefined") {
// Using the localStorage
Auth.initWithLocalStorage();
} else {
// Using the window object
Auth.initSimple();
}
}
};
Auth.signIn = function(authResult){
Auth.processAuth(authResult);
};
Auth.processAuth = function(authResult) {
//Auth.$scope.immediateFailed = true;
if (authResult) {
if (authResult['access_token']){
Auth.$scope.immediateFailed = false;
Auth.$scope.isSignedIn = true;
Auth.goAhead(authResult);
}
else{
// Auth.renderForcedSignIn();
window.location.reload(true);
}
} else {
Auth.renderForcedSignIn();
};
};
Auth.renderForcedSignIn = function(){
window.authResult = null;
Auth.$scope.immediateFailed = true;
gapi.signin.render('myGsignin', {
'callback': Auth.signIn,
'clientid': '987765099891.apps.googleusercontent.com',
'scope': 'https://www.googleapis.com/auth/userinfo.email',
'theme': 'dark',
'cookiepolicy': 'single_host_origin',
'accesstype': 'online',
'width':'wide'
});
}
Auth.refreshToken = function(){
if (!Auth.$scope.isRefreshing){
if (typeof(Storage) != "undefined") {
localStorage['access_token']="null";
}
Auth.$scope.isRefreshing = true;
Auth.renderForcedSignIn();
}
//window.location.reload(true);
};
return Auth;
});
| JavaScript | 0.000123 | @@ -4205,24 +4205,95 @@
led = true;%0A
+ console.log(authResult);%0A Auth.$scope.isRefreshing = false;%0A
if (au
|
0c9d0f0434b58403ab5505d8988beb6c6d1a4146 | Remove event listener on unsubscribe to AttrSlot | src/foam/u2/AttrSlot.js | src/foam/u2/AttrSlot.js | /**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
foam.CLASS({
package: 'foam.u2',
name: 'AttrSlot',
extends: 'foam.core.Slot',
documentation: 'A Value bound to an Element attribute. Used to bind values to DOM.',
properties: [
{
name: 'element',
required: true
},
'value',
[ 'property', 'value' ],
[ 'event', 'change' ]
],
methods: [
function get() {
return this.element.getAttribute(this.property);
},
function set(value) {
this.element.setAttribute(this.property, value);
// The next line is necessary to fire a change event.
// This is necessary because DOM isn't proper MVC and
// doesn't fire a change event when the value is explicitly set.
this.value = value;
},
function sub(l) {
// TODO: remove listener on unsubscribe. But how?
if ( ! this.hasListeners() ) {
var self = this;
this.element.on(this.event, function() {
self.value = self.get();
});
}
return this.SUPER('propertyChange', 'value', l);
},
function toString() {
return 'AttrSlot(' + this.event + ', ' + this.property + ')';
}
]
});
| JavaScript | 0 | @@ -1383,201 +1383,444 @@
-// TODO: remove listener on unsubscribe. But how?%0A if ( ! this.hasListeners() ) %7B%0A var self = this;%0A this.element.on(this.event, function() %7B%0A self.value = self.get(
+var self = this;%0A const valueUpdateListener = function() %7B%0A self.value = self.get();%0A %7D;%0A%0A if ( ! this.hasListeners() ) %7B%0A this.element.on(this.event, valueUpdateListener);%0A %7D%0A%0A var detachable = this.SUPER('propertyChange', 'value', l);%0A%0A return %7B%0A detach: function() %7B%0A if ( self.hasListeners() ) %7B%0A self.element.removeEventListener(self.event, valueUpdateListener
);%0A
@@ -1830,73 +1830,61 @@
-%7D);
+ %7D%0A
%0A
- %7D%0A
- return this.SUPER('propertyChange', 'value', l)
+detachable.detach();%0A %7D%0A %7D
;%0A
|
be7446b7be28632cdbd211f0e3602db0eec57e8f | Fix header space problem after resizing and close #156 | app/assets/javascripts/header.js | app/assets/javascripts/header.js | function hideSmallTopNav() {
$('#small_nav').removeClass('display_block');
$('#small_nav').addClass('display_none');
$('#expand_nav').css({"opacity": 1});
}
function showSmallTopNav() {
$('#small_nav').removeClass('display_none');
$('#small_nav').addClass('display_block');
$('#expand_nav').css({"opacity": 0.8});
}
function hideExpandMe() {
$('#expand_me').removeClass('display_block');
$('#expand_me').addClass('display_none');
$('#me').css({"opacity": 1});
$('#title_expand').css({"opacity": 1});
}
function showExpandMoment() {
$('#expand_moment').removeClass('display_none');
$('#expand_moment').addClass('display_block');
}
function hideExpandMoment() {
$('#expand_moment').removeClass('display_block');
$('#expand_moment').addClass('display_none');
$('#moment').css({"opacity": 1});
$('#title_expand').css({"opacity": 1});
}
function setHeight() {
var the_height = $('#header').height();
$('#header_space').css({"height": the_height});
}
function expandButton() {
hideSmallTopNav();
$('#expand_me').toggleClass("display_none");
$('#me').toggleClass('dim');
$('#title_expand').toggleClass('dim');
setHeight();
}
function headerMouseLeave() {
if ($('#expand_moment').length && $('#expand_moment').hasClass('display_block')) {
hideExpandMoment();
setHeight();
}
}
function expandMomentMouseover() {
if ($('#expand_moment').hasClass('display_none')) {
showExpandMoment();
hideExpandMe();
setHeight();
}
}
var onReadyHeader = function() {
setHeight();
$('.expand_button').click(expandButton);
//mobile menu toggling
$('#expand_nav').click(function() {
if ($('#small_nav').hasClass('display_none')) {
showSmallTopNav();
} else {
hideSmallTopNav();
}
});
$('.expand_moment_button').mouseover(expandMomentMouseover);
$('#header').mouseleave(headerMouseLeave);
$(window).resize(function () {
setHeight();
});
};
$(document).on("page:load ready", onReadyHeader);
| JavaScript | 0 | @@ -1881,65 +1881,8 @@
ve);
-%0A%0A $(window).resize(function () %7B%0A setHeight();%0A %7D);
%0A%7D;%0A
|
5f5bb30883532920063535c12a8578070d2a97fa | simplify reseting form fields for add movie | scripts/app2.js | scripts/app2.js | /*
*
*/
"use strict";
(function($){
var app = {};
//returns null if not valid or a date object if it is valid
app.isValidDate = function(dateString) {
//mm dd yyyy format
var matches1 = dateString.match(/^(\d{2})[- \/](\d{2})[- \/](\d{4})$/);
if (!matches1) return;
var matches = dateString.match(/^(\d{1,2})[- \/](\d{1,2})[- \/](\d{4})$/);
if (!matches) return;
// parse each piece and see if it makes a valid date object
var month = parseInt(matches[1], 10);
var day = parseInt(matches[2], 10);
var year = parseInt(matches[3], 10);
var date = new Date(year, month - 1, day);
if (!date || !date.getTime()) return;
// make sure we have no funny rollovers that the date object sometimes accepts
// month > 12, day > what's allowed for the month
if (date.getMonth() + 1 != month ||
date.getFullYear() != year ||
date.getDate() != day) {
return;
}
return(date);
};
app.usDateFromDate = function(dateString){
if(!dateString){
return '';
}
var split = dateString.split('-');
return split[1] + '/' + split[2] + '/' + split[0];
};
app.formatRating = function(ratingString){
if(!ratingString){
return null;
}
return parseInt(ratingString);
};
app.movieFields = function(){
return [
{selector: '#movie_title', key: 'title'},
{selector: '#movie_pre_rating', key: 'pre_rating'},
{selector: '#movie_theater_release', key: 'theater_release'},
{selector: '#movie_dvd_release', key: 'dvd_release'},
{selector: '#movie_genre', key: 'movie_genre'}
];
};
app.resetForAdd = function(){
$('#add_edit_movie_modal').removeClass('edit').addClass('add');
var movie = {'title' : null,
'dvd_release' : null,
'theater_release' : null,
'movie_genre' : $('#movie_genre').find('option').first().val(),
'pre_rating' : null
};
$.each(this.movieFields(), function(index, el) {
$(el.selector).val(movie[el.key]);
});
this.mode = 'add';
};
app.resetForEdit = function(movie){
$('#add_edit_movie_modal').addClass('edit').removeClass('add');
this.mode = 'edit';
$.each(this.movieFields(), function(index, el) {
$(el.selector).val(movie[el.key]);
});
}
app.resetForm = function(){
//resets for both add and edit
$('#modal_errors').text('');
$('#movie_post_rating').val('');
$('.form-group').removeClass('has-error');
};
app.showModal = function(movie){
if(movie){
this.resetForEdit(movie);
}
else{
this.resetForAdd();
}
this.resetForm();
$('#add_edit_movie_modal').modal('show');
};
app.edit = function(movie_id){
var self = this;
$.post('http://localhost/movie_list_2/edit_movie.php', {'movie' : JSON.stringify({'id' : movie_id})},function(data, status){
if(data['error']){
window.alert(data['error']);
console.log(data['error']);
}
else{
self.movie = data['movie'];
self.movie = {
'title' : data['movie']['title'],
'movie_id' : movie_id,
'pre_rating' : self.formatRating(data['movie']['pre_rating']),
'post_rating' : self.formatRating(data['movie']['post_rating']),
'theater_release' : self.usDateFromDate(data['movie']['theater_release']),
'dvd_release' : self.usDateFromDate(data['movie']['dvd_release']),
'movie_genre' : parseInt(data['movie']['movie_genre'])
};
self.showModal(self.movie);
}
});
};
app.isFormValid = function(movie){
if($('#movie_form .form-group').hasClass('has-error')){
return false;
}
if(movie.title === ''){
return false;
}
return true;
};
app.serializeForm = function($form){
return $form.serializeArray().reduce(function(object, current, index){ object[current.name] = current.value; return object; }, {});
};
//turns blank values in object to null for database
app.normalizeBlankValues = function(obj){
for(var key in obj){
if(obj[key] === ''){
obj[key] = null;
}
}
return obj;
};
app.saveMovie = function(){
var movie = app.serializeForm($('#movie_form'));
movie = app.normalizeBlankValues(movie);
if(this.mode === 'edit'){
movie.movie_id = this.movie.movie_id;
}
console.log(movie);
var self = this;
if(app.isFormValid(movie)){
$.post('http://localhost/movie_list_2/add_edit_movie.php', {'movie' : JSON.stringify(movie), 'mode' : self.mode},function(data, status){
if(data['error']){
$('#modal_errors').text(data['error']);
return;
}
$('tbody').html(data['table_body']);
$('#add_edit_movie_modal').modal('hide');
});
}
else{
$('#modal_errors').text('Please fix your input values before trying to send the form.');
}
};
//add listeners
$('#movie_table').on('click', '.edit-button', function(event) {
event.preventDefault();
var movie_id = $(this).closest('tr').data('id');
app.edit(movie_id);
});
$('#add-movie-button').on('click', function(event) {
event.preventDefault();
app.showModal();
});
$('#movie_form').on('submit', function(event) {
event.preventDefault();
app.saveMovie();
});
})(jQuery);
| JavaScript | 0 | @@ -1771,92 +1771,22 @@
ovie
- = %7B'title' : null,%0A%09%09%09%09%09'dvd_release' : null,%0A%09%09%09%09%09'theater_release' : null, %0A%09%09%09%09%09
+_defaults = %7B
'mov
@@ -1847,40 +1847,9 @@
al()
-,%0A%09%09%09%09%09'pre_rating' : null%0A%09%09%09%09%09
+
%7D;%0A%09
@@ -1890,32 +1890,106 @@
on(index, el) %7B%0A
+ %09%09var value = movie_defaults%5Bel.key%5D ? movie_defaults%5Bel.key%5D : null;%0A
%09%09$(el.selec
@@ -1993,37 +1993,29 @@
lector).val(
-movie%5Bel.key%5D
+value
);%0A %09%7D);%0A
|
8b30ced2907623dbfd22e02c46d18e014abfa9e7 | test 5 | web/react/src/server/routes/routes.js | web/react/src/server/routes/routes.js | const contentRes = require('./../helpers/contentRes');
module.exports = (app) => {
app.get('*', (req, res) => {
// load content
contentRes(app, req, res);
});
};
| JavaScript | 0.000035 | @@ -48,16 +48,19 @@
tRes');%0A
+//
%0Amodule.
|
a2d8375cc27922f72a9b45040ee77b99117fb753 | remove extra line | PhilipsHue.js | PhilipsHue.js | // Philips Hue Platform Shim for HomeBridge
//
// Remember to add platform to config.json. Example:
// "platforms": [
// {
// "platform": "PhilipsHue",
// "name": "Philips Hue",
// "ip_address": "127.0.0.1",
// "username": "252deadbeef0bf3f34c7ecb810e832f"
// }
// ],
//
// When you attempt to add a device, it will ask for a "PIN code".
// The default code for all HomeBridge accessories is 031-45-154.
//
/* jslint node: true */
/* globals require: false */
/* globals config: false */
"use strict";
var hue = require("node-hue-api"),
HueApi = hue.HueApi,
lightState = hue.lightState;
var types = require("../lib/HAP-NodeJS/accessories/types.js");
function PhilipsHuePlatform(log, config) {
this.log = log;
this.ip_address = config["ip_address"];
this.username = config["username"];
}
function PhilipsHueAccessory(log, device, api) {
this.id = device.id;
this.name = device.name;
this.model = device.modelid;
this.device = device;
this.api = api;
this.log = log;
}
// Execute changes for various characteristics
// @todo Move this into accessory methods
var execute = function(api, device, characteristic, value) {
var state = lightState.create();
characteristic = characteristic.toLowerCase();
if (characteristic === "identify") {
state.alert('select');
}
else if (characteristic === "power") {
if (value) {
state.on();
}
else {
state.off();
}
}
else if (characteristic === "hue") {
state.hue(value);
}
else if (characteristic === "brightness") {
value = value/100;
value = value*255;
value = Math.round(value);
state.bri(value);
}
else if (characteristic === "saturation") {
value = value/100;
value = value*255;
value = Math.round(value);
state.sat(value);
}
api.setLightState(device.id, state, function(err, lights) {
if (!err) {
console.log("executed accessory: " + device.name + ", and characteristic: " + characteristic + ", with value: " + value + ".");
}
else {
console.log(err);
}
});
};
PhilipsHuePlatform.prototype = {
accessories: function(callback) {
this.log("Fetching Philips Hue lights...");
var that = this;
var foundAccessories = [];
var api = new HueApi(this.ip_address, this.username);
// Connect to the API and loop through lights
api.lights(function(err, response) {
if (err) throw err;
response.lights.map(function(device) {
var accessory = new PhilipsHueAccessory(that.log, device, api);
foundAccessories.push(accessory);
});
callback(foundAccessories);
});
}
};
PhilipsHueAccessory.prototype = {
// Get Services
getServices: function() {
var that = this;
return [
{
sType: types.ACCESSORY_INFORMATION_STYPE,
characteristics: [
{
cType: types.NAME_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: this.name,
supportEvents: false,
supportBonjour: false,
manfDescription: "Name of the accessory",
designedMaxLength: 255
},{
cType: types.MANUFACTURER_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: "Philips",
supportEvents: false,
supportBonjour: false,
manfDescription: "Manufacturer",
designedMaxLength: 255
},{
cType: types.MODEL_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: this.model,
supportEvents: false,
supportBonjour: false,
manfDescription: "Model",
designedMaxLength: 255
},{
cType: types.SERIAL_NUMBER_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: this.model + this.id,
supportEvents: false,
supportBonjour: false,
manfDescription: "SN",
designedMaxLength: 255
},{
cType: types.IDENTIFY_CTYPE,
onUpdate: function(value) { console.log("Change:",value); execute(that.api, that.device, "identify", value); },
perms: ["pw"],
format: "bool",
initialValue: false,
supportEvents: false,
supportBonjour: false,
manfDescription: "Identify Accessory",
designedMaxLength: 1
}
]
},{
sType: types.LIGHTBULB_STYPE,
characteristics: [
{
cType: types.NAME_CTYPE,
onUpdate: null,
perms: ["pr"],
format: "string",
initialValue: this.name,
supportEvents: false,
supportBonjour: false,
manfDescription: "Name of service",
designedMaxLength: 255
},{
cType: types.POWER_STATE_CTYPE,
onUpdate: function(value) { console.log("Change:",value); execute(that.api, that.device, "power", value); },
perms: ["pw","pr","ev"],
format: "bool",
initialValue: false,
supportEvents: false,
supportBonjour: false,
manfDescription: "Turn On the Light",
designedMaxLength: 1
},{
cType: types.HUE_CTYPE,
onUpdate: function(value) { console.log("Change:",value); execute(that.api, that.device, "hue", value); },
perms: ["pw","pr","ev"],
format: "int",
initialValue: 0,
supportEvents: false,
supportBonjour: false,
manfDescription: "Adjust Hue of Light",
designedMinValue: 0,
designedMaxValue: 65535,
designedMinStep: 1,
unit: "arcdegrees"
},{
cType: types.BRIGHTNESS_CTYPE,
onUpdate: function(value) { console.log("Change:",value); execute(that.api, that.device, "brightness", value); },
perms: ["pw","pr","ev"],
format: "int",
initialValue: 0,
supportEvents: false,
supportBonjour: false,
manfDescription: "Adjust Brightness of Light",
designedMinValue: 0,
designedMaxValue: 100,
designedMinStep: 1,
unit: "%"
},{
cType: types.SATURATION_CTYPE,
onUpdate: function(value) { console.log("Change:",value); execute(that.api, that.device, "saturation", value); },
perms: ["pw","pr","ev"],
format: "int",
initialValue: 0,
supportEvents: false,
supportBonjour: false,
manfDescription: "Adjust Saturation of Light",
designedMinValue: 0,
designedMaxValue: 100,
designedMaxValue: 255,
designedMinStep: 1,
unit: "%"
}
]
}
];
}
};
module.exports.platform = PhilipsHuePlatform;
| JavaScript | 0.018303 | @@ -6927,43 +6927,8 @@
0,%0A
- designedMaxValue: 100,%0A
|
f62b2f1954bd5fe30e615d8cf63fe010043f76a2 | Use multiple selectors for finding closest dataTable DOM element (task #7074) | webroot/js/plugin.js | webroot/js/plugin.js | $(document).ready(function () {
/** letting the cancel avoid html5 validation and redirect back */
$('.remove-client-validation').click(function () {
$(this).parent('form').attr('novalidate', 'novalidate');
});
/**
* Trigger deletion of the record from the dynamic DataTables entries.
*/
$('body').on('click','a[data-type="ajax-delete-record"]', function (e) {
e.preventDefault();
var hrefObj = this;
if (confirm($(this).data('confirm-msg'))) {
$.ajax({
url: $(this).attr('href'),
method: 'DELETE',
dataType: 'json',
contentType: 'application/json',
headers: {
'Authorization': 'Bearer ' + api_options.token
},
success: function (data) {
//traverse upwards on the tree to find table instance and reload it
var table = $(hrefObj).closest('.dataTable').DataTable();
table.ajax.reload();
}
});
}
});
});
| JavaScript | 0 | @@ -979,16 +979,34 @@
losest('
+.table-datatable,
.dataTab
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.