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 |
|---|---|---|---|---|---|---|---|
0f80b1058d233f11b95fef567d1b37dd88c94f09 | Resolve the relative path to lib files last | tools/node.js | tools/node.js | var path = require("path");
var fs = require("fs");
var vm = require("vm");
var sys = require("util");
var UglifyJS = vm.createContext({
sys : sys,
console : console,
process : process,
Buffer : Buffer,
MOZ_SourceMap : require("source-map")
});
function load_global(file) {
file = path.resolve(path.dirname(module.filename), file);
try {
var code = fs.readFileSync(file, "utf8");
return vm.runInContext(code, UglifyJS, file);
} catch(ex) {
// XXX: in case of a syntax error, the message is kinda
// useless. (no location information).
sys.debug("ERROR in file: " + file + " / " + ex);
process.exit(1);
}
};
var FILES = exports.FILES = [
"../lib/utils.js",
"../lib/ast.js",
"../lib/parse.js",
"../lib/transform.js",
"../lib/scope.js",
"../lib/output.js",
"../lib/compress.js",
"../lib/sourcemap.js",
"../lib/mozilla-ast.js"
].map(function(file){
return path.join(path.dirname(fs.realpathSync(__filename)), file);
});
FILES.forEach(load_global);
UglifyJS.AST_Node.warn_function = function(txt) {
sys.error("WARN: " + txt);
};
// XXX: perhaps we shouldn't export everything but heck, I'm lazy.
for (var i in UglifyJS) {
if (UglifyJS.hasOwnProperty(i)) {
exports[i] = UglifyJS[i];
}
}
exports.minify = function(files, options) {
options = UglifyJS.defaults(options, {
spidermonkey : false,
outSourceMap : null,
sourceRoot : null,
inSourceMap : null,
fromString : false,
warnings : false,
mangle : {},
output : null,
compress : {}
});
UglifyJS.base54.reset();
// 1. parse
var toplevel = null,
sourcesContent = {};
if (options.spidermonkey) {
toplevel = UglifyJS.AST_Node.from_mozilla_ast(files);
} else {
if (typeof files == "string")
files = [ files ];
files.forEach(function(file){
var code = options.fromString
? file
: fs.readFileSync(file, "utf8");
sourcesContent[file] = code;
toplevel = UglifyJS.parse(code, {
filename: options.fromString ? "?" : file,
toplevel: toplevel
});
});
}
// 2. compress
if (options.compress) {
var compress = { warnings: options.warnings };
UglifyJS.merge(compress, options.compress);
toplevel.figure_out_scope();
var sq = UglifyJS.Compressor(compress);
toplevel = toplevel.transform(sq);
}
// 3. mangle
if (options.mangle) {
toplevel.figure_out_scope();
toplevel.compute_char_frequency();
toplevel.mangle_names(options.mangle);
}
// 4. output
var inMap = options.inSourceMap;
var output = {};
if (typeof options.inSourceMap == "string") {
inMap = fs.readFileSync(options.inSourceMap, "utf8");
}
if (options.outSourceMap) {
output.source_map = UglifyJS.SourceMap({
file: options.outSourceMap,
orig: inMap,
root: options.sourceRoot
});
if (options.sourceMapIncludeSources) {
for (var file in sourcesContent) {
if (sourcesContent.hasOwnProperty(file)) {
output.source_map.get().setSourceContent(file, sourcesContent[file]);
}
}
}
}
if (options.output) {
UglifyJS.merge(output, options.output);
}
var stream = UglifyJS.OutputStream(output);
toplevel.print(stream);
if(options.outSourceMap){
stream += "\n//# sourceMappingURL=" + options.outSourceMap;
}
return {
code : stream + "",
map : output.source_map + ""
};
};
// exports.describe_ast = function() {
// function doitem(ctor) {
// var sub = {};
// ctor.SUBCLASSES.forEach(function(ctor){
// sub[ctor.TYPE] = doitem(ctor);
// });
// var ret = {};
// if (ctor.SELF_PROPS.length > 0) ret.props = ctor.SELF_PROPS;
// if (ctor.SUBCLASSES.length > 0) ret.sub = sub;
// return ret;
// }
// return doitem(UglifyJS.AST_Node).sub;
// }
exports.describe_ast = function() {
var out = UglifyJS.OutputStream({ beautify: true });
function doitem(ctor) {
out.print("AST_" + ctor.TYPE);
var props = ctor.SELF_PROPS.filter(function(prop){
return !/^\$/.test(prop);
});
if (props.length > 0) {
out.space();
out.with_parens(function(){
props.forEach(function(prop, i){
if (i) out.space();
out.print(prop);
});
});
}
if (ctor.documentation) {
out.space();
out.print_string(ctor.documentation);
}
if (ctor.SUBCLASSES.length > 0) {
out.space();
out.with_block(function(){
ctor.SUBCLASSES.forEach(function(ctor, i){
out.indent();
doitem(ctor);
out.newline();
});
});
}
};
doitem(UglifyJS.AST_Node);
return out + "";
};
| JavaScript | 0 | @@ -1001,16 +1001,32 @@
return
+fs.realpathSync(
path.joi
@@ -1040,32 +1040,16 @@
dirname(
-fs.realpathSync(
__filena
@@ -1051,24 +1051,24 @@
ilename)
-)
, file)
+)
;%0A%7D);%0A%0AF
|
e1ed438500b04d1ec78346e09c3d40fb95187a1d | Update for jshint fixes | website/static/js/notificationsTreebeard.js | website/static/js/notificationsTreebeard.js | 'use strict';
var $ = require('jquery');
var m = require('mithril');
var Treebeard = require('treebeard');
var $osf = require('js/osfHelpers');
var projectSettingsTreebeardBase = require('js/projectSettingsTreebeardBase');
function expandOnLoad() {
var tb = this; // jshint ignore: line
for (var i = 0; i < tb.treeData.children.length; i++) {
var parent = tb.treeData.children[i];
tb.updateFolder(null, parent);
expandChildren(tb, parent.children);
}
}
function expandChildren(tb, children) {
var openParent = false;
for (var i = 0; i < children.length; i++) {
var child = children[i];
var parent = children[i].parent();
if (child.data.kind === 'event' && child.data.event.notificationType !== 'adopt_parent') {
openParent = true;
}
if (child.children.length > 0) {
expandChildren(tb, child.children);
}
}
if (openParent) {
openAncestors(tb, children[0]);
}
}
function openAncestors (tb, item) {
var parent = item.parent();
if(parent && parent.id > 0) {
tb.updateFolder(null, parent);
openAncestors(tb, parent);
}
}
function subscribe(item, notification_type) {
var id = item.parent().data.node.id;
var event = item.data.event.title;
var payload = {
'id': id,
'event': event,
'notification_type': notification_type
};
$osf.postJSON(
'/api/v1/subscriptions/',
payload
).done(function(){
//'notfiy-success' is to override default class 'success' in treebeard
item.notify.update('Settings updated', 'notify-success', 1, 2000);
item.data.event.notificationType = notification_type;
}).fail(function() {
item.notify.update('Could not update settings', 'notify-danger', 1, 2000);
});
}
function displayParentNotificationType(item){
var notificationTypeDescriptions = {
'email_transactional': 'Instantly',
'email_digest': 'Daily',
'adopt_parent': 'Adopt setting from parent project',
'none': 'Never'
};
if (item.data.event.parent_notification_type) {
if (item.parent().parent().parent() === undefined) {
return '(' + notificationTypeDescriptions[item.data.event.parent_notification_type] + ')';
}
}
return '';
}
var popOver = function(element, isInit) {
if (!isInit) {
$(element).tooltip();
}
};
function ProjectNotifications(data) {
// Treebeard version
var tbOptions = $.extend({}, projectSettingsTreebeardBase.defaults, {
divID: 'grid',
filesData: data,
naturalScrollLimit : 0,
onload : function () {
var tb = this;
expandOnLoad.call(tb);
},
resolveRows: function notificationResolveRows(item){
var columns = [];
var iconcss = '';
// check if should not get icon
if(item.children.length < 1 ){
iconcss = 'tb-no-icon';
}
if (item.data.kind === 'heading') {
if (item.data.children.length === 0) {
columns.push({
data : 'project', // Data field name
folderIcons : false,
filter : true,
sortInclude : false,
custom : function() {
return m('div[style="padding-left:5px"]',
[m ('p', [
m('b', item.data.node.title + ': '),
m('span[class="text-warning"]', ' No configured projects.')]
)]
);
}
});
} else {
columns.push({
data : 'project', // Data field name
folderIcons : false,
filter : true,
sortInclude : false,
custom : function() {
var globalNotificationsMessage = "These are default settings for new projects you create or are added to. Modifying these settings will not modify settings on existing projects."
return m('div[style="padding-left:5px; padding-bottom:50px"]', [
m('p', [
m('b', item.data.node.title + ': '),
m('span[class="fa fa-info-circle"]', {'data-toggle': 'tooltip', 'title':globalNotificationsMessage, config: popOver, 'data-placement': 'bottom'})
])
]);
}
});
}
}
else if (item.data.kind === 'folder' || item.data.kind === 'node') {
columns.push({
data : 'project', // Data field name
folderIcons : true,
filter : true,
sortInclude : false,
custom : function() {
if (item.data.node.url !== '') {
return m('a', { href : item.data.node.url, target : '_blank' }, item.data.node.title);
} else {
return m('span', item.data.node.title);
}
}
});
}
else if (item.parent().data.kind === 'folder' || item.parent().data.kind === 'heading' && item.data.kind === 'event') {
columns.push(
{
data : 'project', // Data field name
folderIcons : true,
filter : true,
css : iconcss,
sortInclude : false,
custom : function(item, col) {
return item.data.event.description;
}
},
{
data : 'notificationType', // Data field name
folderIcons : false,
filter : false,
custom : function(item, col) {
return m('div[style="padding-right:10px"]',
[m('select.form-control', {
onchange: function(ev) {
subscribe(item, ev.target.value);
}},
[
m('option', {value: 'none', selected : item.data.event.notificationType === 'none' ? 'selected': ''}, 'Never'),
m('option', {value: 'email_transactional', selected : item.data.event.notificationType === 'email_transactional' ? 'selected': ''}, 'Instantly'),
m('option', {value: 'email_digest', selected : item.data.event.notificationType === 'email_digest' ? 'selected': ''}, 'Daily')
])
]);
}
});
}
else {
columns.push(
{
data : 'project', // Data field name
folderIcons : true,
filter : true,
css : iconcss,
sortInclude : false,
custom : function() {
return item.data.event.description;
}
},
{
data : 'notificationType', // Data field name
folderIcons : false,
filter : false,
custom : function() {
return m('div[style="padding-right:10px"]',
[m('select.form-control', {
onchange: function(ev) {
subscribe(item, ev.target.value);
}},
[
m('option', {value: 'adopt_parent',
selected: item.data.event.notificationType === 'adopt_parent' ? 'selected' : ''},
'Adopt setting from parent project ' + displayParentNotificationType(item)),
m('option', {value: 'none', selected : item.data.event.notificationType === 'none' ? 'selected': ''}, 'Never'),
m('option', {value: 'email_transactional', selected : item.data.event.notificationType === 'email_transactional' ? 'selected': ''}, 'Instantly'),
m('option', {value: 'email_digest', selected : item.data.event.notificationType === 'email_digest' ? 'selected': ''}, 'Daily')
])
]);
}
});
}
return columns;
}
});
var grid = new Treebeard(tbOptions);
}
module.exports = ProjectNotifications;
| JavaScript | 0 | @@ -4213,17 +4213,17 @@
ssage =
-%22
+'
These ar
@@ -4357,17 +4357,18 @@
rojects.
-%22
+';
%0A
|
950cdfc9483f5bc36c560bafd49061d60f1316f4 | remove former users route declaration | imports/api/routes/projectRoutes.js | imports/api/routes/projectRoutes.js | import Helpers from '/imports/api/routes/Helpers.js';
import RouteManager from '/imports/api/managers/RouteManager.js';
RouteManager.registerTranslatedPage('dashboard', {
details: 'dashboard'
});
RouteManager.registerTranslatedPage('project', {
search: 'projects'
});
RouteManager.registerTranslatedPage('user', {
search: 'users',
details: 'user/:userId'
});
RouteManager.registerEntity('project', {
details: ''
});
RouteManager.registerEntity('publisher.password', {
insert: 'publishers/:userId/password',
forwarding: {
route: 'publishers/:userId/password/forwarding',
name: 'publisher.password.details',
link: 'publisher.details'
}
});
RouteManager.registerEntity('publisher.profile.availability', {
insert: 'publishers/:userId/availability/:key/new',
details: 'publishers/:userId/availability/:key'
});
RouteManager.registerEntity('publisher.profile.vacation', {
insert: 'publishers/:userId/vacation/new',
forwarding: {
route: 'publishers/:userId/vacation/forwarding',
name: 'publisher.profile.vacation.details',
link: 'publisher.details'
}
});
RouteManager.registerEntity('publisher', {
search: 'publishers',
insert: 'publishers/new',
details: 'publishers/:userId',
update: 'publishers/:userId/:key'
});
RouteManager.registerEntity('vessel', {
search: 'vessels',
insert: 'vessels/new',
details: 'vessels/:vesselId',
update: 'vessels/:vesselId/:key'
});
RouteManager.registerEntity('vessel.visit', {
insert: 'vessels/:vesselId/visits/new',
details: 'vessels/:vesselId/visits/:visitId',
update: 'vessels/:vesselId/visits/:visitId/:key'
});
RouteManager.registerEntity('vessel.visit.language', {
insert: 'vessels/:vesselId/visits/:visitId/languages/new',
forwarding: {
route: 'vessels/:vesselId/visits/:visitId/language/forwarding',
name: 'vessel.visit.language.details',
link: 'vessel.visit.details'
}
});
RouteManager.registerEntity('note', {
search: 'notes',
insert: 'notes/new',
details: 'notes/:noteId',
update: 'notes/:noteId/:key'
});
FlowRouter.route('/:language/:projectId/calendar/:year?/:month?/:day?', {
name: 'calendar',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'home');
BlazeLayout.render('mainLayout', { content: 'calendar' });
});
}
});
FlowRouter.route('/:language/:projectId/kb', {
name: 'wiki',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'home');
BlazeLayout.render('mainLayout', { content: 'wiki' });
});
}
});
FlowRouter.route('/:language/:projectId/shifts', {
name: 'shifts',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
let parent = Session.get('parent');
if (parent != 'settings' && parent != 'home') {
Session.set('parent', 'home');
}
BlazeLayout.render('mainLayout', { content: 'shifts' });
});
}
});
FlowRouter.route('/:language/:projectId/settings', {
name: 'settings',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'project');
BlazeLayout.render('mainLayout', { content: 'settings' });
});
}
});
FlowRouter.route('/:language/:projectId/users', {
name: 'users',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'project');
BlazeLayout.render('mainLayout', { content: 'users' });
});
}
});
FlowRouter.route('/:language/:projectId/reports', {
name: 'reports',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'project');
BlazeLayout.render('mainLayout', { content: 'reports' });
});
}
});
FlowRouter.route('/:language/:projectId/store', {
name: 'store',
triggersEnter: [ Helpers.checkLanguage ],
action: () => {
Helpers.doIfLoggedIn(() => {
Session.set('parent', 'project');
BlazeLayout.render('mainLayout', { content: 'store' });
});
}
});
| JavaScript | 0 | @@ -3530,317 +3530,8 @@
);%0A%0A
-FlowRouter.route('/:language/:projectId/users', %7B%0A name: 'users',%0A triggersEnter: %5B Helpers.checkLanguage %5D,%0A action: () =%3E %7B%0A Helpers.doIfLoggedIn(() =%3E %7B%0A Session.set('parent', 'project');%0A BlazeLayout.render('mainLayout', %7B content: 'users' %7D);%0A %7D);%0A %7D%0A%7D);%0A%0A
Flow
|
38808487034aa29e039b93b77b6e14b736e57743 | Initialize graph with container to draw itself into, versus the graph element itself | src/qgr-graph-barchart.js | src/qgr-graph-barchart.js | define( [
'jquery',
'underscore',
'backbone',
'd3',
],
function ($, _, Backbone, d3) {
var BarChart = Backbone.View.extend({
initialize: function(options) {
var t = this;
t.config = t.options.graph_config;
t.raw_data = t.options.raw_data;
// Transform raw data to format needed by D3.
t.data = t.map_raw_data(t.raw_data, t.config.label)
t.init_labels = _.pluck(t.data, 'label')
var width = t.$el.width(),
height = t.$el.height();
t.x = d3.scale.linear()
.domain([0, d3.max(t.data, function(d) { return d.val; })])
.range(["0px", 0.8 * width + 'px']),
t.chart = d3.select(t.el).append("div")
.attr("class", "qgr-graph-barchart")
.style("padding-top", height/3 + 'px');
t.chart.selectAll("div")
.data(t.data)
.enter().append("div")
.style("width", function(d) { return t.x(d.val); })
.text(function(d) { return d.label + ': ' + d.val; });
},
update: function(raw_data){
var t = this;
t.raw_data = raw_data;
t.data = t.map_raw_data(t.raw_data, t.config.label)
t.data = t.order_by_init_labels(t.data, t.init_labels);
var bar = t.chart.selectAll("div")
.data(t.data)
bar
.style("visibility", function(d) {
if (d.val !== 0) {
return 'visible';
} else if (d3.select(this).style('visibility') == 'hidden') {
return 'hidden';
}
})
.text(function(d) {
if (d.val !== 0) {
return d.label + ': ' + d.val;
} else {
return '';
}
})
.transition()
.style("width", function(d) {
return t.x(d.val); })
.transition()
// Hide bars that have zero val
.style("visibility", function(d) {
if (d.val === 0) {
return 'hidden'
}
})
},
map_raw_data: function(raw_data, label_col) {
return _.map(raw_data, function(row) {
return {
val: row.val,
label: row[label_col]
};
});
},
order_by_init_labels: function(data, init_labels) {
return _.map(init_labels, function(label) {
var val;
var rows = _.where(data, {label: label});
if (_.isEmpty(rows)) {
// If there are no matching rows, then val is zero.
val = 0;
} else {
// Otherwise, there should only be one row, so we take its val.
val = rows[0].val;
}
return {
label: label,
val: val
}
});
}
});
return BarChart;
});
| JavaScript | 0 | @@ -235,16 +235,55 @@
config;%0A
+ t.container = t.options.container;%0A
t.ra
@@ -480,21 +480,30 @@
width =
-t.$el
+$(t.container)
.width()
@@ -523,13 +523,22 @@
t =
-t.$el
+$(t.container)
.hei
@@ -713,18 +713,25 @@
elect(t.
-el
+container
).append
@@ -824,24 +824,72 @@
3 + 'px');%0A%0A
+ t.setElement($('.qgr-graph-barchart')%5B0%5D);%0A%0A
t.chart.
|
1125883add6f18fb96a12c71dbc9946d63da7db2 | Remove not used prop | src/react-slidy-slider.js | src/react-slidy-slider.js | /* eslint-disable react/prop-types */
import React, {useEffect, useRef, useState} from 'react'
import slidy from './slidy'
function noop() {}
function convertToArrayFrom(children) {
return Array.isArray(children) ? children : [children]
}
function getItemsToRender({
index,
maxIndex,
items,
itemsToPreload,
numOfSlides
}) {
const preload = Math.max(itemsToPreload, numOfSlides)
if (index >= items.length - numOfSlides) {
const addNewItems =
items.length > numOfSlides ? items.slice(0, numOfSlides - 1) : []
return [...items.slice(0, maxIndex + preload), ...addNewItems]
} else {
return items.slice(0, maxIndex + preload)
}
}
function destroySlider(slidyInstance, doAfterDestroy) {
slidyInstance && slidyInstance.clean() && slidyInstance.destroy()
doAfterDestroy()
}
const renderItem = (numOfSlides, classNameToAttach) => (item, index) => {
const inlineStyle = numOfSlides !== 1 ? {width: `${100 / numOfSlides}%`} : {}
return (
<li className={classNameToAttach} key={index} style={inlineStyle}>
{item}
</li>
)
}
export default function ReactSlidySlider({
children,
classNameToAttach,
classNameBase,
doAfterDestroy,
doAfterInit,
doAfterSlide,
doBeforeSlide,
ease,
initialSlide,
itemsToPreload,
keyboardNavigation,
numOfSlides,
showArrows,
slideSpeed,
tailArrowClass
}) {
const [slidyInstance, setSlidyInstance] = useState({
next: noop,
prev: noop,
updateItems: noop
})
const [index, setIndex] = useState(initialSlide)
const [maxIndex, setMaxIndex] = useState(initialSlide)
const sliderContainerDOMEl = useRef(null)
const slidesDOMEl = useRef(null)
const items = convertToArrayFrom(children)
useEffect(
function() {
let handleKeyboard
const slidyInstance = slidy(sliderContainerDOMEl.current, {
ease,
doAfterSlide,
doBeforeSlide,
numOfSlides,
slideSpeed,
slidesDOMEl: slidesDOMEl.current,
initialSlide: index,
items: items.length,
onNext: nextIndex => {
setIndex(nextIndex)
nextIndex > maxIndex && setMaxIndex(nextIndex)
return nextIndex
},
onPrev: nextIndex => {
setIndex(nextIndex)
return nextIndex
}
})
setSlidyInstance(slidyInstance)
doAfterInit()
if (keyboardNavigation) {
handleKeyboard = e => {
if (e.keyCode === 39) slidyInstance.next(e)
else if (e.keyCode === 37) slidyInstance.prev(e)
}
document.addEventListener('keydown', handleKeyboard)
}
return () => {
destroySlider(slidyInstance, doAfterDestroy)
if (keyboardNavigation) {
document.removeEventListener('keydown', handleKeyboard)
}
}
},
[] // eslint-disable-line
)
useEffect(function() {
slidyInstance && slidyInstance.updateItems(items.length)
})
const itemsToRender = getItemsToRender({
index,
maxIndex,
items,
itemsToPreload,
numOfSlides
})
return (
<>
{showArrows && (
<>
<span
className={`${classNameBase}-prev`}
disabled={index === 0}
onClick={slidyInstance.prev}
/>
<span
className={`${classNameBase}-next`}
disabled={items.length <= numOfSlides || index === items.length - 1}
onClick={items.length > numOfSlides && slidyInstance.next}
/>
</>
)}
<div className={classNameToAttach} ref={sliderContainerDOMEl}>
<ul className={classNameToAttach} ref={slidesDOMEl}>
{itemsToRender.map(renderItem(numOfSlides, classNameToAttach))}
</ul>
</div>
</>
)
}
| JavaScript | 0.000001 | @@ -1340,26 +1340,8 @@
peed
-,%0A tailArrowClass
%0A%7D)
|
10f5e652c7c60694d0e5e472507095eec654a61b | Update admin.js | src/resources/js/admin.js | src/resources/js/admin.js | /**
* jQuery and the Bootstrap jQuery plugin
*/
try {
window.Popper = require('popper.js').default;
window.$ = window.jQuery = require('jquery');
require('bootstrap');
} catch (e) {}
/**
* Axios HTTP library
*/
window.axios = require('axios');
window.axios.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
/**
* API Token
*/
let apiToken = document.head.querySelector('meta[name="api-token"]');
if (apiToken) {
window.axios.defaults.headers.common['Authorization'] = `Bearer ${apiToken.content}`;
} else {
console.error('API token not found.');
}
/**
* Cropper.js
*/
import Cropper from 'cropperjs';
window.Cropper = Cropper;
/**
* Vue
*/
import Vue from 'vue';
window.Vue = Vue;
/**
* i18n
*/
import VueI18n from 'vue-i18n';
import fr from '../lang/fr.json';
import en from '../lang/en.json';
import es from '../lang/es.json';
const messages = { fr, en, es };
const i18n = new VueI18n({ locale: window.TypiCMS.locale, messages });
/**
* Permissions mixin
*/
import Permissions from './mixins/Permissions';
Vue.mixin(Permissions);
/**
* Date Filter
*/
import date from './filters/Date.js';
Vue.filter('date', date);
/**
* Datetime Filter
*/
import datetime from './filters/Datetime.js';
Vue.filter('datetime', datetime);
/**
* Lists
*/
import ItemListColumnHeader from './components/ItemListColumnHeader.vue';
import ItemList from './components/ItemList.vue';
import ItemListTree from './components/ItemListTree.vue';
import ItemListStatusButton from './components/ItemListStatusButton.vue';
import ItemListCheckbox from './components/ItemListCheckbox.vue';
import ItemListPositionInput from './components/ItemListPositionInput.vue';
/**
* History
*/
import History from './components/History.vue';
/**
* Files
*/
import FileManager from './components/FileManager.vue';
import FileField from './components/FileField.vue';
import FilesField from './components/FilesField.vue';
window.EventBus = new Vue({});
new Vue({
i18n,
components: {
ItemListColumnHeader,
ItemList,
ItemListTree,
ItemListStatusButton,
ItemListCheckbox,
ItemListPositionInput,
Filepicker,
FileManager,
Files,
FilesField,
FileField,
History,
},
}).$mount('#app');
/**
* Alertify
*/
window.alertify = require('alertify.js');
/**
* Selectize
*/
require('selectize');
/**
* All files in /reources/js/admin
*/
var req = require.context('./admin', true, /^(.*\.(js$))[^.]*$/im);
req.keys().forEach(function (key) {
req(key);
});
| JavaScript | 0.000001 | @@ -2185,50 +2185,15 @@
File
-picker,%0A FileManager,%0A Files
+Manager
,%0A
|
35f98ce39c2814233d0af9a61203032a0f2a5c55 | Add missing Indico header | indico/htdocs/js/custom/dropzone.js | indico/htdocs/js/custom/dropzone.js | (function(global) {
'use strict';
$(document).ready(function(){
Dropzone.autoDiscover = false;
});
global.setupDropzone = function(element) {
var $dz = $(element),
$form = $dz.closest('form'),
$flashArea = $form.find('.flashed-messages'),
options = {
clickable: element + ' .dropzone-inner',
previewsContainer: element + ' .dropzone-previews',
autoProcessQueue: false,
init: function() {
var $button = $form.find('input[type="submit"], .js-dropzone-upload'),
self = this,
file = $dz.data('value');
if (file) {
var existingFile = {
name: file.filename,
size: file.size,
accepted: true
};
self.emit('addedfile', existingFile);
$dz.find('.dz-progress').hide();
self.files[0] = existingFile;
/* Disable opening the upload dialog when clicking on the file's preview element */
$dz.find('.dz-preview').on('click', function(e) {
e.stopPropagation();
});
// Check if the existing file is an image and add the image preview.
if (file.content_type.match(/image\/.*/) && file.url) {
$dz.find('.dz-image > img').attr('src', file.url);
$dz.find('.dz-image > img').attr('width', '120px');
$dz.find('.dz-preview').removeClass('dz-file-preview').addClass('dz-image-preview');
}
}
$button.on('click', function(e) {
e.preventDefault();
e.stopPropagation();
$button.prop('disabled', true);
$.each(self.getRejectedFiles(), function(index, file) {
self.removeFile(file);
});
if (self.getQueuedFiles().length) {
$dz.find('.dz-progress').show();
self.processQueue();
} else if (options.submitIfEmpty) {
$form.submit();
}
});
self.on('addedfile', function(file) {
if (!options.uploadMultiple && self.files.length > 1) {
self.removeFile(self.files[0]);
}
// force change in form, so that we can process
// the 'change' event
$button.prop('disabled', false);
$form.find('.change-trigger').val('added-file');
$form.trigger('change');
$dz.find('.dz-message').hide();
$dz.find('.dz-progress').hide();
$(file.previewElement).on('click', function(e) {
e.stopPropagation();
});
});
self.on('removedfile', function(file) {
$button.prop('disabled', false);
if (self.files.length === 0) {
// force change in form, so that we can process the 'change' event
$form.find('.change-trigger').val('no-file');
$form.trigger('change');
$dz.find('.dz-message').show();
}
});
self.on('sendingmultiple', function() {
$form.trigger('ajaxDialog:beforeSubmit');
});
self.on('success', function(e, response) {
if (options.submitForm) {
$form.submit();
}
if (options.handleFlashes) {
handleFlashes(response, true, $flashArea);
}
$dz.data('value', response.content);
$form.find('.change-trigger').val($dz.data('value') ? 'uploaded-file' : 'no-file');
$form.trigger('indico:fieldsSaved', response);
$form.trigger('ajaxDialog:success', [response]);
});
self.on('error', function(e, msg, xhr) {
if (xhr) {
var evt = $.Event('ajaxDialog:error');
$form.trigger(evt, [xhr]);
if (!evt.isDefaultPrevented()) {
handleAjaxError(xhr);
}
}
});
}
};
_.extend(options, $dz.data('options'));
var param = options.paramName;
options.paramName = function() { return param; };
// include the csrf token in case the dropzone is submitting data to a
// seperate endpoint than the form's action
if (options.url) {
options.params = {
'csrf_token': $form.find('#csrf_token').val()
};
$dz.dropzone(options);
}
else {
$form.dropzone(options);
}
};
})(window);
| JavaScript | 0.000001 | @@ -1,16 +1,763 @@
+/* This file is part of Indico.%0A * Copyright (C) 2002 - 2016 European Organization for Nuclear Research (CERN).%0A *%0A * Indico is free software; you can redistribute it and/or%0A * modify it under the terms of the GNU General Public License as%0A * published by the Free Software Foundation; either version 3 of the%0A * License, or (at your option) any later version.%0A *%0A * Indico is distributed in the hope that it will be useful, but%0A * WITHOUT ANY WARRANTY; without even the implied warranty of%0A * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU%0A * General Public License for more details.%0A *%0A * You should have received a copy of the GNU General Public License%0A * along with Indico; if not, see %3Chttp://www.gnu.org/licenses/%3E.%0A */%0A%0A
(function(global
|
dba93ca3b6f590d4b97457cd9b9e4b18eea4c12b | Fix #254 | www/assets/js/data.js | www/assets/js/data.js | /*
The MIT License (MIT)
Copyright (c) 2013 Calvin Montgomery
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
var CL_VERSION = "2.0.0";
var CLIENT = {
rank: -1,
leader: false,
name: "",
logged_in: false,
profile: {
image: "",
text: ""
}
};
var SUPERADMIN = false;
var CHANNEL = {
opts: {},
openqueue: false,
perms: {},
css: "",
js: "",
motd: "",
motd_text: "",
name: false
};
var PLAYER = false;
var VIDEOQUALITY = false;
var FLUIDLAYOUT = false;
var VWIDTH;
var VHEIGHT;
if($("#videowidth").length > 0) {
VWIDTH = $("#videowidth").css("width").replace("px", "");
VHEIGHT = ""+parseInt(parseInt(VWIDTH) * 9 / 16);
}
var MEDIA = { hash: "" };
var PL_MOVING = false;
var PL_ADDING = false;
var PL_DELETING = false;
var REBUILDING = false;
var socket = {
emit: function() {
console.log("socket not initialized");
console.log(arguments);
}
};
var IGNORED = [];
var CHATHIST = [];
var CHATHISTIDX = 0;
var SCROLLCHAT = true;
var LASTCHATNAME = "";
var LASTCHATTIME = 0;
var FOCUSED = true;
var PAGETITLE = "CyTube";
var TITLE_BLINK;
var KICKED = false;
var NAME = readCookie("cytube_uname");
var SESSION = readCookie("cytube_session");
var LEADTMR = false;
var PL_FROM = "";
var PL_AFTER = "";
var PL_WAIT_SCROLL = false;
var FILTER_FROM = 0;
var FILTER_TO = 0;
var NO_STORAGE = typeof localStorage == "undefined" || localStorage === null;
function getOpt(k) {
return NO_STORAGE ? readCookie(k) : localStorage.getItem(k);
}
function setOpt(k, v) {
NO_STORAGE ? createCookie(k, v, 1000) : localStorage.setItem(k, v);
}
function getOrDefault(k, def) {
var v = getOpt(k);
if(v === null)
return def;
if(v === "true")
return true;
if(v === "false")
return false;
if(v.match(/^[0-9]+$/))
return parseInt(v);
if(v.match(/^[0-9\.]+$/))
return parseFloat(v);
return v;
}
var USEROPTS = {
theme : getOrDefault("theme", "default"),
css : getOrDefault("css", ""),
layout : getOrDefault("layout", "default"),
synch : getOrDefault("synch", true),
hidevid : getOrDefault("hidevid", false),
show_timestamps : getOrDefault("show_timestamps", true),
modhat : getOrDefault("modhat", false),
blink_title : getOrDefault("blink_title", false),
sync_accuracy : getOrDefault("sync_accuracy", 2),
wmode_transparent : getOrDefault("wmode_transparent", true),
chatbtn : getOrDefault("chatbtn", false),
altsocket : getOrDefault("altsocket", false),
joinmessage : getOrDefault("joinmessage", true),
qbtn_hide : getOrDefault("qbtn_hide", false),
qbtn_idontlikechange : getOrDefault("qbtn_idontlikechange", false),
first_visit : getOrDefault("first_visit", true),
ignore_channelcss : getOrDefault("ignore_channelcss", false),
ignore_channeljs : getOrDefault("ignore_channeljs", false)
};
var NO_WEBSOCKETS = USEROPTS.altsocket;
var Rank = {
Guest: 0,
Member: 1,
Leader: 1.5,
Moderator: 2,
Admin: 3,
Owner: 10,
Siteadmin: 255
};
function createCookie(name,value,days) {
if (days) {
var date = new Date();
date.setTime(date.getTime()+(days*24*60*60*1000));
var expires = "; expires="+date.toGMTString();
}
else var expires = "";
document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(";");
for(var i=0;i < ca.length;i++) {
var c = ca[i];
while (c.charAt(0)==" ") c = c.substring(1,c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
}
return null;
}
function eraseCookie(name) {
createCookie(name,"",-1);
}
/* to be implemented in callbacks.js */
function setupCallbacks() { }
| JavaScript | 0.000001 | @@ -4048,16 +4048,137 @@
nneljs%22,
+ false),%0A sort_rank : getOrDefault(%22sort_rank%22, false),%0A sort_afk : getOrDefault(%22sort_afk%22,
false)%0A
|
4a4e34a7e2ef1841e18baa2ead5572343e1edeaa | fix logger error | packages/cloud-core/pubsub-connector.js | packages/cloud-core/pubsub-connector.js | const Rx = require('rx-lite')
const redis = require("redis");
const {PromiseUtils} = require('isomorphic-core');
PromiseUtils.promisifyAll(redis.RedisClient.prototype);
PromiseUtils.promisifyAll(redis.Multi.prototype);
class PubsubConnector {
constructor() {
this._broadcastClient = null;
this._listenClient = null;
this._listenClientSubs = {};
}
buildClient(accountId) {
const client = redis.createClient(process.env.REDIS_URL || null);
global.Logger.log.info({account_id: accountId}, "Connecting to Redis")
client.on("error", global.Logger.log.error);
client.on("end", () => {
global.Logger.log.info({account_id: accountId}, "Redis disconnected")
this._broadcastClient = null;
})
return client;
}
broadcastClient() {
if (!this._broadcastClient) {
this._broadcastClient = this.buildClient("broadcast");
}
return this._broadcastClient;
}
queueProcessMessage({messageId, accountId}) {
if (!messageId) {
throw new Error("queueProcessMessage: The message body processor expects a messageId")
}
if (!accountId) {
throw new Error("queueProcessMessage: The message body processor expects a accountId")
}
this.broadcastClient().lpush(`message-processor-queue`, JSON.stringify({messageId, accountId}));
}
// Shared channel
_observableForChannelOnSharedListener(channel) {
if (!this._listenClient) {
this._listenClient = this.buildClient();
this._listenClientSubs = {};
}
return Rx.Observable.create((observer) => {
this._listenClient.on("message", (msgChannel, message) => {
if (msgChannel !== channel) { return }
observer.onNext(message)
});
if (!this._listenClientSubs[channel]) {
this._listenClientSubs[channel] = 1;
this._listenClient.subscribe(channel);
} else {
this._listenClientSubs[channel] += 1;
}
return () => {
this._listenClientSubs[channel] -= 1;
if (this._listenClientSubs[channel] === 0) {
this._listenClient.unsubscribe(channel);
}
}
});
}
notifyAccount(accountId, {type, data}) {
this.broadcastClient().publish(`account-${accountId}`, JSON.stringify({type, data}));
}
observeAccount(accountId) {
return this._observableForChannelOnSharedListener(`account-${accountId}`);
}
notifyDelta(accountId, transactionJSON) {
this.broadcastClient().publish(`deltas-${accountId}`, JSON.stringify(transactionJSON))
}
observeAllAccounts() {
return Rx.Observable.create((observer) => {
const sub = this.buildClient();
sub.on("pmessage", (pattern, channel, message) =>
observer.onNext(channel.replace('account-', ''), message));
sub.psubscribe(`account-*`);
return () => {
sub.unsubscribe();
sub.quit();
}
})
}
observeDeltas(accountId) {
return Rx.Observable.create((observer) => {
const sub = this.buildClient(accountId);
sub.on("message", (channel, transactionJSONString) => {
observer.onNext(JSON.parse(transactionJSONString))
})
sub.subscribe(`deltas-${accountId}`);
return () => {
global.Logger.log.info({account_id: accountId}, "Closing Redis")
sub.unsubscribe();
sub.quit();
}
})
}
}
module.exports = new PubsubConnector()
| JavaScript | 0 | @@ -467,36 +467,32 @@
global.Logger.
-log.
info(%7Baccount_id
@@ -565,20 +565,16 @@
.Logger.
-log.
error);%0A
@@ -614,36 +614,32 @@
global.Logger.
-log.
info(%7Baccount_id
@@ -3199,12 +3199,8 @@
ger.
-log.
info
|
385e8b4f7786772d7420cf7ab2ae0ec432bacf28 | Add slight animation for modal open/close to make it less jarring | www/docs/js/quant2.js | www/docs/js/quant2.js | var researchUser;
var startTime = new Date();
var recordEndpoint = 'http://logbook.mysociety.org/quant2';
var siteTag = 'openaustralia';
$(document).ready(function() {
// Retrieve the bucket from storage, or allocate the user if not.
if ($.localStorage.isEmpty('research.qual2')) {
researchUser = {
'bucket': Math.floor(Math.random() * 3) + 1,
};
$.localStorage.set('research.qual2', researchUser);
} else {
researchUser = $.localStorage.get('research.qual2');
}
// Record this page view and bucket
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'view',
'page': document.URL,
'bucket': researchUser.bucket
},
dataType: 'jsonp'
});
// Choose which action to take
if (researchUser.bucket == 1) {
// Bind modal behaviours
$('#whereNextModal').popup({
scrolllock: true
});
// Bind the "where next" click event
$('#research-quant2-bucket1-wherenext').click(function(e) {
e.preventDefault();
var link = $(this);
var endTime = new Date();
var timer = endTime - startTime;
timer /= 1000;
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'click_popup_link',
'page': document.URL,
'bucket': researchUser.bucket,
'data': 'where-next',
'timer': timer
},
dataType: 'jsonp',
timeout: 300
}).always(function() {
window.location.assign(link.attr('href'));
});
});
// Bind the "where next" click event
$('[data-research-quant2-bucket1-linkname]').click(function(e) {
e.preventDefault();
var link = $(this);
var endTime = new Date();
var timer = endTime - startTime;
timer /= 1000;
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'click_popup_link',
'page': document.URL,
'bucket': researchUser.bucket,
'data': link.data('research-quant2-bucket1-linkname'),
'timer': timer
},
dataType: 'jsonp'
});
$('#whereNextModal').popup('toggle');
$('#whereNextModal').attr('hidden', '');
});
// On the page for 10 seconds, do the popup
setTimeout(function() {
// Are popups suppressed (ie have we already shown one?)
if ($.localStorage.isEmpty('research.qual2.suppress_popup')) {
// Set the suppress popup flag.
$.localStorage.set('research.qual2.suppress_popup', true);
$('#whereNextModal').popup('toggle');
$('#whereNextModal').removeAttr('hidden');
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'show_popup',
'page': document.URL,
'bucket': researchUser.bucket,
'data': 'timed'
},
dataType: 'jsonp'
});
} else {
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'suppressed_popup',
'page': document.URL,
'bucket': researchUser.bucket,
'data': 'timed'
},
dataType: 'jsonp'
});
}
}, 10000);
} else if (researchUser.bucket == 2) {
$('#research-quant2-bucket2').show();
// Bind the click event
$('#research-quant2-bucket2 a').click(function(e) {
e.preventDefault();
var link = $(this);
var endTime = new Date();
var timer = endTime - startTime;
timer /= 1000;
$.ajax({
url: recordEndpoint,
data: {
'site': siteTag,
'method': 'click_nav_link',
'page': document.URL,
'bucket': researchUser.bucket,
'timer': timer
},
dataType: 'jsonp',
timeout: 300
}).always(function() {
window.location.assign(link.attr('href'));
});
});
}
// Bucket 3 doesn't do anything except record a view, which we've already done.
});
| JavaScript | 0 | @@ -939,16 +939,50 @@
popup(%7B%0A
+ transition: 'all 0.3s',%0A
|
adaead228929fe6d00b2a83533a2a85b5a13a6d1 | fix post to back end | www/js/controllers.js | www/js/controllers.js | angular.module('starter.controllers', [])
.controller('DashCtrl', function($scope, $state, WarningService) {
$scope.warning = {
message: '1',
id_contact_type: 3
};
var listContactType = WarningService.getContactTypes();
listContactType.then(function(result) {
if (result) {
$scope.contact_types = result;
//$scope.warning.id_message = $routeParams.id_message*1;
}
});
var listMessage = WarningService.getMessages('pt-br');
listMessage.then(function(result) {
if (result) {
$scope.messages = result;
//$scope.warning.id_message = $routeParams.id_message*1;
}
});
$scope.send = function(){
$scope.warning.created_date = new Date();
$scope.warning.timezone = (new Date()).getTimezoneOffset()+"";
var warnService = WarningService.send($scope.warning);
warnService.then(function(data) {
$scope.handleServerResponse(data);
}, function(error) {
$scope.error = error;
});
$scope.error = null;
};
$scope.handleServerResponse = function (data){
$scope.error = null;
$scope.invalid_facebook = null;
$scope.email_error = null;
$scope.invalid_phone_number = null;
$scope.invalid_ddd = null;
$scope.server_msg_danger = null;
$scope.server_msg_sucess = null;
switch(data.id){
case 200:
$scope.server_msg_danger = null;
$scope.server_msg_sucess = data.name;
$scope.warning.id_message = null;
$scope.warning.contact = null;
$scope.sms = null;
$scope.email = null;
$scope.facebook = null;
break;
default:
$scope.server_msg_danger = data.name;
$scope.server_msg_sucess = null;
break;
}
}
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
}
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
lang_key: 'pt-br'
};
});
| JavaScript | 0 | @@ -133,26 +133,8 @@
-message: '1',%0A
id_c
@@ -147,16 +147,203 @@
_type: 3
+,%0A browser: %22android%22,%0A operating_system: %22android%22,%0A device: %22android%22,%0A raw: %22android%22,%0A warning_resp: %7B%7D,%0A enableName: false,%0A ip: %22android%22,%0A lang_key: %22pt-br%22
%0A %7D;%0A%0A
@@ -619,23 +619,39 @@
essages(
-'pt-br'
+$scope.warning.lang_key
);%0A lis
@@ -1929,16 +1929,361 @@
%09%09%09%7D%0A%09%09%7D
+;%0A%0A $scope.$watch('sms', function(value, oldValue) %7B%0A%0A%0A $scope.warning.contact = String(value);%0A%0A %7D);%0A%0A $scope.$watch('whatsapp', function(value, oldValue) %7B%0A%0A $scope.warning.contact = String(value);%0A%0A %7D);%0A%0A $scope.$watch('email', function(value, oldValue) %7B%0A%0A $scope.warning.contact = String(value);%0A%0A %7D);
%0A%0A%7D)%0A%0A.c
|
3b24dcd1e05aa164d6ebdb52781165e9bd0e4f8c | Remove inadvertently introduced alert | www/js/controllers.js | www/js/controllers.js | 'use strict';
angular.module('emission.controllers', ['emission.splash.updatecheck',
'emission.splash.startprefs'])
.controller('RootCtrl', function($scope) {})
.controller('DashCtrl', function($scope) {})
.controller('SplashCtrl', function($scope, $state, $interval, $rootScope,
UpdateCheck, StartPrefs) {
console.log('SplashCtrl invoked');
alert("attach debugger!");
UpdateCheck.checkForUpdates();
StartPrefs.startWithPrefs();
$rootScope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){
console.log("Finished changing state from "+JSON.stringify(fromState)
+ " to "+JSON.stringify(toState));
/*
if ($rootScope.checkedForUpdates) {
window.Logger.log(window.Logger.log("Already checked for update, skipping"));
} else {
UpdateCheck.checkForUpdates();
$rootScope.checkedForUpdates = true;
} */
});
console.log('SplashCtrl invoke finished');
})
.controller('ChatsCtrl', function($scope, Chats) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//
//$scope.$on('$ionicView.enter', function(e) {
//});
$scope.chats = Chats.all();
$scope.remove = function(chat) {
Chats.remove(chat);
};
})
.controller('ChatDetailCtrl', function($scope, $stateParams, Chats) {
$scope.chat = Chats.get($stateParams.chatId);
})
.controller('AccountCtrl', function($scope) {
$scope.settings = {
enableFriends: true
};
});
| JavaScript | 0 | @@ -386,16 +386,19 @@
ked');%0A
+ //
alert(%22
|
a72a4ce783aa7a430676408c4c5bf84d299728d7 | Revert "centering colin" | www/js/states/init.js | www/js/states/init.js | var gameState = {};
var state_init = function(game) {
return {
preload: function() {
game.load.image('colin1', 'assets/colin1.jpg');
game.load.image('judgeResponse', 'assets/judgeResponse.jpg');
},
create: function() {
var colin = game.add.sprite(game.world.centerX, game.world.centerY, 'colin1');
gameState.dancer = colin;
game.time.events.add(Phaser.Timer.SECOND * 4, endGame, this);
},
update: function() {
}
};
};
function endGame() {
game.add.sprite(game.world.centerX, game.world.centerY,'judgeResponse');
gameState.dancer.kill();
}
game.state.add('init', state_init);
| JavaScript | 0 | @@ -312,46 +312,12 @@
ite(
-game.world.centerX, game.world.centerY
+0, 0
, 'c
@@ -539,46 +539,11 @@
ite(
-game.world.centerX, game.world.centerY
+0,0
,'ju
|
f8062f118b29316a4053fdbe0262f8d4faf289b4 | Allow requestors to manually specify response ID | packages/net/protocols/Cuppa.js | packages/net/protocols/Cuppa.js | "use import";
import lib.Callback;
import lib.PubSub;
from net.protocols.rtjp import RTJPProtocol;
var Error = Class(function() {
this.init = function(protocol, id, msg, details, requestId) {
this.id = id;
this.msg = msg;
this.details = details;
this.requestId = requestId;
}
});
var RPCRequest = Class(function() {
this.init = function(protocol, id) {
this.protocol = protocol;
this.id = id;
this._onError = new lib.Callback();
this._onSuccess = new lib.Callback();
}
this.onError = function() { this._onError.forward(arguments); }
this.onSuccess = function() { this._onSuccess.forward(arguments); }
this.bindLater = function(l) {
var args = [].slice(arguments, 1);
this._onError.forward([l, l.fail].concat(args));
this._onSuccess.forward([l, l.succed].concat(args));
return l;
}
});
var ReceivedRequest = Class(function() {
this.type = "request"
this.init = function(protocol, id, name, args, target) {
this.protocol = protocol
this.id = id;
this.name = name
this.responded = false;
this.args = args;
this.target = target;
}
this.error = function(msg, details) {
if (this.responded) { throw new Error("already responded"); }
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
args = {
id: this.id,
msg: msg + ""
}
if (details !== undefined) { args.details = details }
this.responded = true;
this.protocol.sendFrame('ERROR', args);
}
this.respond = function(args) {
if (this.responded) { throw new Error("already responded"); }
if (this._timer) {
clearTimeout(this._timer);
this._timer = null;
}
this.responded = true;
this.protocol.sendFrame('RESPONSE', {
id: this.id,
args: args == undefined ? {} : args // python cuppa ignores responses with undefined args
});
}
this.timeoutAfter = function(duration, msg) {
if (this.responded) { return; }
if (this._timer) { clearTimeout(this._timer); }
this._timer = setTimeout(bind(this, '_timeout', msg), duration);
}
this._timeout = function(msg) {
if (!this.responded) {
this.error(msg);
}
}
});
var ReceivedEvent = Class(function() {
this.init = function(protocol, id, name, args, target) {
this.id = id;
this.name = name;
this.args = args;
this.target = target;
}
});
exports = Class(RTJPProtocol, function(supr) {
this.init = function() {
supr(this, 'init', arguments);
this._onConnect = new lib.Callback();
this._onDisconnect = new lib.Callback();
this._requests = {};
this.onEvent = new lib.PubSub();
this.onRequest = new lib.PubSub();
}
this.disconnect = function() { this.transport.loseConnection(); }
// pass something to call (ctx, method, args...) when connected
this.onConnect = function() { this._onConnect.forward(arguments); }
this.onDisconnect = function() { this._onDisconnect.forward(arguments); }
// called when we're connected
this.connectionMade = function() {
this._isConnected = true;
this._onConnect.fire();
}
this.connectionLost = function(err) {
this._isConnected = false;
this._onDisconnect.fire(err);
}
this.sendRequest = function(name, args, target, cb) {
if (arguments.length > 4) { // allow bound functions (e.g. [this, 'onResponse', 123])
cb = bind.apply(GLOBAL, Array.prototype.slice.call(arguments, 3));
}
var frameArgs = {
name: name,
args: args
};
if (target) { frameArgs.target = target; }
var id = this.sendFrame('RPC', frameArgs),
req = this._requests[id] = new RPCRequest(this, id);
if (cb) {
req.onSuccess(GLOBAL, cb, false); // will call cb(false, args...)
req.onError(GLOBAL, cb); // will call cb(err)
}
return req;
}
this.sendEvent = function(name, args, target) {
this.sendFrame('EVENT', {name: name, args: args, target: target || null});
}
this.frameReceived = function(id, name, args) {
logger.debug('RECEIVED', id, name, args);
switch(name.toUpperCase()) {
case 'RESPONSE':
var req = this._requests[args.id];
if (!req) { return; }
delete this._requests[requestId];
req._onSuccess.fire(args.args);
break;
case 'ERROR':
var msg = args.msg || 'unknown',
requestId = args.id,
req = this._requests[requestId],
err = new Error(this, id, msg, args.details, requestId);
if (!req) {
return this.errorReceived(err);
} else {
delete this._requests[requestId];
req._onError.fire(err);
}
break;
case 'RPC':
case 'EVENT':
if (!args.name) {
return self.sendFrame('ERROR', { 'id': id, 'msg': 'missing "name"' });
}
var frameArgs = args.args || {},
target = args.target || null,
isRPC = name.toUpperCase() == 'RPC',
reqCtor = isRPC ? ReceivedRequest : ReceivedEvent,
pubTarget = isRPC ? this.onRequest : this.onEvent,
req = new reqCtor(this, id, args.name, frameArgs, target);
pubTarget.publish(req.name, req);
break;
default:
break;
}
}
});
| JavaScript | 0 | @@ -4547,16 +4547,27 @@
%7B 'id':
+ args.id %7C%7C
id, 'ms
@@ -4597,21 +4597,16 @@
;%0A%09%09%09%09%7D%0A
-%09%09%09%09%0A
%09%09%09%09var
@@ -4847,24 +4847,35 @@
eqCtor(this,
+ args.id %7C%7C
id, args.na
|
52aaa6133d2ce1f3f2f99193ee2c44984564c890 | Make revision suggesiton button's label less forceful | app/js/app/services/QuestionActions.js | app/js/app/services/QuestionActions.js | /**
* Copyright 2017 Meurig Thomas
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
define([], function() {
return ["$state", "$location", function($state, $location) {
var MAX_LABEL_LENGTH = 17;
var defaultAction = {
disabled: false
}
this.checkMyAnswer = function(scope, api) { // TODO refactor so that less is passed to this function
var checkAnswer = function() {
if (scope.question.selectedChoice != null && scope.canSubmit) {
scope.canSubmit = false;
if (scope.doc.type == "isaacSymbolicQuestion" || scope.doc.type == "isaacSymbolicChemistryQuestion") {
var symbols = JSON.parse(scope.question.selectedChoice.value).symbols;
if (Object.keys(symbols).length == 0) {
return;
}
}
var s = api.questionValidator.validate({id: scope.doc.id}, scope.question.selectedChoice);
s.$promise.then(function foo(validationResponse) {
scope.question.validationResponse = validationResponse;
}, function bar(e) {
console.error("Error validating answer:", e);
var eMessage = e.data.errorMessage;
var eTitle = "Can't Submit Answer";
if (eMessage != null && eMessage.indexOf("ValidatorUnavailableException:") == 0) {
eTitle = "Error Checking Answer"
eMessage = eMessage.replace("ValidatorUnavailableException:", "");
}
scope.showToast(scope.toastTypes.Failure, eTitle, eMessage != undefined ? eMessage : "");
// If an error, after a little while allow them to submit the same answer again.
setTimeout(function() { scope.canSubmit = true; }, 5000);
});
}
};
return {
prototype: defaultAction,
label: "Check my answer",
disabled: !scope.canSubmit,
onClick: checkAnswer,
title: "Submit answer for marking",
};
};
this.tryEasierQuestion = function(easierQuestion, currentQuestionId, pageCompleted, questionHistory, gameboardId) {
var fullLabel = easierQuestion.level == '2' ? 'Revise' : 'Practice';
fullLabel += " " + easierQuestion.title.toLowerCase();
var abbreviatedLabel = easierQuestion.level == '2' ? 'Revise' : 'Practice';
abbreviatedLabel += " this concept";
if (fullLabel.length <= MAX_LABEL_LENGTH) {
abbreviatedLabel = fullLabel;
}
if (!pageCompleted) {
questionHistory.push(currentQuestionId);
}
commaSeparatedQuestionHistory = questionHistory.join(',');
return {
prototype: defaultAction,
title: fullLabel,
label: abbreviatedLabel,
onClick: function() {
$state.go('question', {id:easierQuestion.id, questionHistory:commaSeparatedQuestionHistory, board:gameboardId});
}
};
};
this.trySupportingQuestion = function(supportingQuestion, currentQuestionId, pageCompleted, questionHistory, gameboardId) {
var fullLabel = "Try more " + supportingQuestion.title.toLowerCase() + " ";
fullLabel += supportingQuestion.level == '2' ? 'revision' : 'practice';
var abbreviatedLabel = "Try more concept ";
abbreviatedLabel += supportingQuestion.level == '2' ? 'revision' : 'practice';
if (fullLabel.length <= MAX_LABEL_LENGTH) {
abbreviatedLabel = fullLabel;
}
if (!pageCompleted) {
questionHistory.push(currentQuestionId);
}
var commaSeparatedQuestionHistory = questionHistory.join(',');
return {
prototype: defaultAction,
title: fullLabel,
label: abbreviatedLabel,
onClick: function() {
$state.go('question', {id:supportingQuestion.id, questionHistory:commaSeparatedQuestionHistory, board:gameboardId});
},
};
};
this.showRelatedConceptPage = function(conceptPage) {
return {
prototype: defaultAction,
title: "Read suggested related concept page",
label: "Read related concept page",
onClick: function() {
$state.go('concept', {id:conceptPage.id});
},
};
};
this.retryPreviousQuestion = function(questionHistory, gameboardId) {
var previousQuestionId = questionHistory.pop();
var commaSeparatedQuestionHistory = questionHistory.join(',')
return {
prototype: defaultAction,
title: "Retry previous question page",
label: "Return to previous question",
onClick: function() {
$state.go('question', {id:previousQuestionId, questionHistory:commaSeparatedQuestionHistory, board:gameboardId})
}
};
};
this.backToBoard = function(gameboardId) {
return {
prototype: defaultAction,
title: "This question is completed, return to gameboard",
label: "Return to Top 10 Board",
onClick: function() {
$location.url("/gameboards#" + gameboardId);
},
};
};
// TODO for each method in factory wrap result with prototype default action
return this;
}];
}); | JavaScript | 0.000106 | @@ -3394,32 +3394,33 @@
'2' ? 'revision
+?
' : 'practice';%0A
@@ -3412,24 +3412,25 @@
: 'practice
+?
';%0A%09%09%09var ab
@@ -3533,16 +3533,17 @@
revision
+?
' : 'pra
@@ -3543,24 +3543,25 @@
: 'practice
+?
';%0A%09%09%09if (fu
|
4898d0618e9c467d18fff2cc0d4d808b4a63dee9 | Fix django undefined error | query/utils/i18n.js | query/utils/i18n.js | let momentLocale = null;
if(window.languageCode) {
momentLocale = `moment-locale/${window.languageCode}`;
}
define(["moment", momentLocale], function(moment){
const i18n = {};
if(!django.jsi18n_initialized){
function noop(x) {
return x;
}
const i18n = {};
i18n.gettext = noop;
i18n.ngettext = noop;
i18n.gettext_noop = noop;
i18n.pgettext = noop;
i18n.npgettext = noop;
i18n.languageCode = "en";
i18n.highchartsLang = {};
return i18n;
}
const _ = window.gettext;
i18n.gettext = window.gettext;
i18n.ngettext = window.ngettext;
i18n.gettext_noop = window.gettext_noop;
i18n.pgettext = window.pgettext;
i18n.npgettext = window.npgettext;
i18n.languageCode = window.languageCode;
const localeData = moment.localeData(i18n.languageCode);
i18n.highchartsLang = { // excludes dates, these are taken from moment.js
"loading": _("Loading..."),
"resetZoom": _("Reset zoom"),
"resetZoomTitle": _("Reset zoom level 1:1"),
"printChart": _("Print chart"),
"downloadPNG": _("Download PNG image"),
"downloadJPEG": _("Download JPEG image"),
"downloadPDF": _("Download PDF document"),
"downloadSVG": _("Download SVG vector image"),
"contextButtonTitle": _("Chart context menu")
};
return i18n ;
});
| JavaScript | 0.000121 | @@ -188,16 +188,49 @@
%0A if(
+typeof django === %22undefined%22 %7C%7C
!django.
|
6e77f1e10189ed8d3bf2068316dcf13f8d5b890a | Make sure to redefine clickAction only when needed | app/js/arethusa.core/globalSettings.js | app/js/arethusa.core/globalSettings.js | "use strict";
angular.module('arethusa.core').service('globalSettings', [
'configurator',
'plugins',
'$injector',
'$rootScope',
'notifier',
'$timeout',
'$injector',
function(configurator, plugins, $injector, $rootScope, notifier, $timeout) {
var self = this;
self.settings = {};
self.colorizers = { disabled: true };
var confKeys = [
"alwaysDeselect",
"colorizer"
];
self.defaultConf = {
alwaysDeselect: false,
colorizer: 'morph'
};
function configure() {
self.conf = configurator.configurationFor('main').globalSettings || {};
configurator.delegateConf(self, confKeys, true); // true makes them sticky
defineSettings();
}
function Conf(property, type, directive, label) {
this.property = property;
this.label = label || "globalSettings." + property;
this.type = type || 'checkbox';
this.directive = directive;
}
function defineSettings() {
self.defineSetting('clickAction', 'custom', 'global-click-action');
self.defineSetting('alwaysDeselect');
self.defineSetting('keyboardMappings');
self.defineSetting('colorizer', 'custom', 'colorizer-setting');
self.defineSetting('layout', 'custom', 'layout-setting');
}
this.defineSetting = function(property, type, directive, label) {
self.settings[property] = new Conf(property, type, directive, label);
};
this.removeSetting = function(setting) {
delete self.settings[setting];
};
this.toggle = function() {
self.active = !self.active;
};
this.defaultClickAction = function(id) {
state().toggleSelection(id, 'click');
};
this.clickActions = {};
this.addClickAction = function(name, fn, preFn) {
self.clickActions[name] = [fn, preFn];
};
this.removeClickAction = function(name) {
delete self.clickActions[name];
if (self.clickAction === name) self.setClickAction('disabled');
};
this.setClickAction = function(name, silent) {
self.clickAction = name;
var actions = self.clickActions[self.clickAction];
self.clickFn = actions[0];
self.preClickFn = actions[1];
if (!silent) {
$rootScope.$broadcast('clickActionChange');
}
};
this.addColorizer = function(pluginName) {
self.colorizers[pluginName] = true;
};
this.isColorizer = function(pluginName) {
return self.colorizer === pluginName;
};
var lazyState;
function state() {
if (!lazyState) lazyState = $injector.get('state');
return lazyState;
}
this.applyColorizer = function() {
if (self.colorizer === 'disabled') {
state().unapplyStylings();
} else {
// Check if the colorizer is really present
if (self.colorizers[self.colorizer]) {
plugins.get(self.colorizer).applyStyling();
}
}
};
this.colorMaps = function() {
return arethusaUtil.inject({}, self.colorizers, function(memo, name, _) {
if (name !== 'disabled') {
memo[name] = plugins.get(name).colorMap();
}
});
};
function setLayout() {
self.layout = configurator.configurationFor('main').template;
}
// When Arethusa is used as widget, it's imperative to wait
// for this event.
$rootScope.$on('confLoaded', setLayout);
this.broadcastLayoutChange = function() {
var layoutName = self.layouts[self.layout];
if (layoutName === 'Grid') {
$timeout(function() {
notifier.warning('The grid layout is an experimental feature and WILL contain bugs!', 'WARNING');
}, 1200);
}
$rootScope.$broadcast('layoutChange', layoutName);
};
this.layouts = {
'templates/main_with_sidepanel.html': 'Sidepanel',
'templates/main_grid.html': 'Grid'
};
this.addLayout = function(name, url) {
self.layout[name] = url;
};
this.init = function() {
configure();
self.addClickAction('disabled', self.defaultClickAction);
self.setClickAction('disabled', true);
};
}
]);
| JavaScript | 0 | @@ -2039,24 +2039,125 @@
, silent) %7B%0A
+ // When nothing changed, we don't need to do anything%0A if (self.clickAction !== name) %7B%0A
self.c
@@ -2171,24 +2171,26 @@
ion = name;%0A
+
var ac
@@ -2236,24 +2236,26 @@
ion%5D;%0A
+
self.clickFn
@@ -2271,24 +2271,26 @@
s%5B0%5D;%0A
+
+
self.preClic
@@ -2309,24 +2309,26 @@
s%5B1%5D;%0A
+
if (!silent)
@@ -2334,24 +2334,26 @@
) %7B%0A
+
+
$rootScope.$
@@ -2380,24 +2380,34 @@
onChange');%0A
+ %7D%0A
%7D%0A
|
919436e47e0e78f10d5528e5b28dca492c3a14f2 | move proto select after ip version selection | applications/luci-app-mwan3/htdocs/luci-static/resources/view/mwan3/network/rule.js | applications/luci-app-mwan3/htdocs/luci-static/resources/view/mwan3/network/rule.js | 'use strict';
'require form';
'require fs';
'require view';
'require uci';
return view.extend({
load: function() {
return Promise.all([
fs.exec_direct('/usr/libexec/luci-mwan3', ['ipset', 'dump']),
uci.load('mwan3')
]);
},
render: function (data) {
var m, s, o;
m = new form.Map('mwan3', _('MultiWAN Manager - Rules'),
_('Rules specify which traffic will use a particular MWAN policy.') + '<br />' +
_('Rules are based on IP address, port or protocol.') + '<br />' +
_('Rules are matched from top to bottom.') + '<br />' +
_('Rules below a matching rule are ignored.') + '<br />' +
_('Traffic not matching any rule is routed using the main routing table.') + '<br />' +
_('Traffic destined for known (other than default) networks is handled by the main routing table.') + '<br />' +
_('Traffic matching a rule, but all WAN interfaces for that policy are down will be blackholed.') + '<br />' +
_('Names may contain characters A-Z, a-z, 0-9, _ and no spaces.') + '<br />' +
_('Rules may not share the same name as configured interfaces, members or policies.'));
s = m.section(form.GridSection, 'rule');
s.addremove = true;
s.anonymous = false;
s.nodescriptions = true;
s.sortable = true;
o = s.option(form.ListValue, 'family', _('Internet Protocol'));
o.default = '';
o.value('', _('IPv4 and IPv6'));
o.value('ipv4', _('IPv4 only'));
o.value('ipv6', _('IPv6 only'));
o.modalonly = true;
o = s.option(form.Value, 'src_ip', _('Source address'),
_('Supports CIDR notation (eg \"192.168.100.0/24\") without quotes'));
o.datatype = 'ipaddr';
o = s.option(form.Value, 'src_port', _('Source port'),
_('May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes'));
o.depends('proto', 'tcp');
o.depends('proto', 'udp');
o = s.option(form.Value, 'dest_ip', _('Destination address'),
_('Supports CIDR notation (eg \"192.168.100.0/24\") without quotes'));
o.datatype = 'ipaddr';
o = s.option(form.Value, 'dest_port', _('Destination port'),
_('May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes'));
o.depends('proto', 'tcp');
o.depends('proto', 'udp');
o = s.option(form.Value, 'proto', _('Protocol'),
_('View the content of /etc/protocols for protocol description'));
o.default = 'all';
o.rmempty = false;
o.value('all');
o.value('tcp');
o.value('udp');
o.value('icmp');
o.value('esp');
o = s.option(form.ListValue, 'sticky', _('Sticky'),
_('Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface'));
o.default = '0';
o.value('1', _('Yes'));
o.value('0', _('No'));
o.modalonly = true;
o = s.option(form.Value, 'timeout', _('Sticky timeout'),
_('Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set'));
o.datatype = 'range(1, 1000000)';
o.modalonly = true;
o = s.option(form.Value, 'ipset', _('IPset'),
_('Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")'));
o.value('', _('-- Please choose --'));
var ipsets = data[0].split(/\n/);
for (var i = 0; i < ipsets.length; i++) {
if (ipsets[i].length > 0)
o.value(ipsets[i]);
}
o.modalonly = true;
o = s.option(form.Flag, 'logging', _('Logging'),
_('Enables firewall rule logging (global mwan3 logging must also be enabled)'));
o.modalonly = true;
o = s.option(form.ListValue, 'use_policy', _('Policy assigned'));
var options = uci.sections('mwan3', 'policy')
for (var i = 0; i < options.length; i++) {
var value = options[i]['.name'];
o.value(value);
}
o.value('unreachable', _('unreachable (reject)'));
o.value('blackhole', _('blackhole (drop)'));
o.value('default', _('default (use main routing table)'));
return m.render();
}
})
| JavaScript | 0 | @@ -1444,32 +1444,287 @@
alonly = true;%0A%0A
+%09%09o = s.option(form.Value, 'proto', _('Protocol'),%0A%09%09%09_('View the content of /etc/protocols for protocol description'));%0A%09%09o.default = 'all';%0A%09%09o.rmempty = false;%0A%09%09o.value('all');%0A%09%09o.value('tcp');%0A%09%09o.value('udp');%0A%09%09o.value('icmp');%0A%09%09o.value('esp');%0A%0A
%09%09o = s.option(f
@@ -2541,263 +2541,8 @@
);%0A%0A
-%09%09o = s.option(form.Value, 'proto', _('Protocol'),%0A%09%09%09_('View the content of /etc/protocols for protocol description'));%0A%09%09o.default = 'all';%0A%09%09o.rmempty = false;%0A%09%09o.value('all');%0A%09%09o.value('tcp');%0A%09%09o.value('udp');%0A%09%09o.value('icmp');%0A%09%09o.value('esp');%0A%0A
%09%09o
|
280feef3512739b0484db751e7c2969c954a933b | Fix globalSettings labels for angular-translate | app/js/arethusa.core/globalSettings.js | app/js/arethusa.core/globalSettings.js | "use strict";
angular.module('arethusa.core').service('globalSettings', [
'configurator',
function(configurator) {
var self = this;
var confKeys = [
"alwaysDeselect"
];
function configure() {
self.conf = configurator.configurationFor('main').globalSettings || {};
configurator.delegateConf(self, confKeys, true); // true makes them sticky
self.settings = {};
defineSettings();
}
function Conf(property, type) {
this.property = property;
this.type = type || 'checkbox';
}
function defineSettings(args) {
defineSetting('alwaysDeselect');
}
function defineSetting(property, type) {
self.settings[property] = new Conf(property, type);
}
this.toggle = function() {
self.active = !self.active;
};
configure();
}
]);
| JavaScript | 0.000003 | @@ -499,16 +499,65 @@
operty;%0A
+ this.label = %22globalSettings.%22 + property;%0A
th
|
af85bcd585f529ff0553a6b4bdb595466c0b026b | change development config | config/env/development.js | config/env/development.js | 'use strict';
module.exports = {
db: 'mongodb://' + (process.env.DB_PORT_27017_TCP_ADDR || 'localhost') + '/mean-dev',
debug: true,
logging: {
format: 'tiny'
},
// aggregate: 'whatever that is not false, because boolean false value turns aggregation off', //false
aggregate: false,
mongoose: {
debug: false
},
hostname: 'http://localhost:3000',
app: {
name: 'MEAN - A Modern Stack - Development'
},
strategies: {
local: {
enabled: true
},
landingPage: '/',
facebook: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/facebook/callback',
enabled: false
},
twitter: {
clientID: 'DEFAULT_CONSUMER_KEY',
clientSecret: 'CONSUMER_SECRET',
callbackURL: 'http://localhost:3000/api/auth/twitter/callback',
enabled: false
},
github: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/github/callback',
enabled: false
},
google: {
clientID: 'DEFAULT_APP_ID',
clientSecret: 'APP_SECRET',
callbackURL: 'http://localhost:3000/api/auth/google/callback',
enabled: false
},
linkedin: {
clientID: 'DEFAULT_API_KEY',
clientSecret: 'SECRET_KEY',
callbackURL: 'http://localhost:3000/api/auth/linkedin/callback',
enabled: false
}
},
emailFrom: 'SENDER EMAIL ADDRESS', // sender address like ABC <abc@example.com>
mailer: {
service: 'SERVICE_PROVIDER', // Gmail, SMTP
auth: {
user: 'EMAIL_ID',
pass: 'PASSWORD'
}
},
secret: 'SOME_TOKEN_SECRET'
};
| JavaScript | 0.000001 | @@ -349,30 +349,45 @@
'http://
-localhost:3000
+pictionary.dev6.linnovate.net
',%0A app
|
575c9ce4426126c026bddfd86873bbeca4642f1b | update TODO header | config/gulp/tasks/docs.js | config/gulp/tasks/docs.js | 'use strict';
/**
* Module dependencies
*/
var gulp = require('gulp'),
gutil = require('gulp-util'),
fs = require('fs'),
runSequence = require('run-sequence'),
plato = require('plato'),
Dgeni = require('dgeni'),
todo = require('gulp-todo'),
changelog = require('conventional-changelog'),
marked = require('gulp-marked'),
config = require('../config'),
_ = require('../util');
gulp.task('docs', function (done) {
runSequence(
'docs:plato',
'docs:dgeni',
'docs:todo',
'docs:changelog',
'docs:marked',
_.runCallback(done)
);
});
gulp.task('docs:plato', function (done) {
var files = config.plato.files,
outputDir = config.plato.outputDir,
opts = {
title : _.getPackage().name,
jshint : _.getJsHintOptions(true)
};
plato.inspect(files, outputDir, opts, function (report) {
done();
});
});
gulp.task('docs:dgeni', function () {
// TODO this needs configuration
var dgeni = new Dgeni([
require('../../dgeni/docs.config')
]);
return dgeni.generate();
});
gulp.task('docs:todo', function () {
return gulp.src(config.sources.js)
.pipe(todo({
fileName : 'TODO.md',
verbose : config.watch,
transformComment: function (file, line, text) {
return [
'| [' + file + '](' + file + '#L' + line + ') ' +
'| ' + line + ' | ' + text
];
},
transformHeader: function (kind) {
return [
'### ' + kind + 's',
'| Filename | line # | todo',
'|:---------|:------:|:-------'
];
}
}))
.pipe(gulp.dest('./'));
});
gulp.task('docs:changelog', function (done) {
var pkg = _.getPackage();
if (!(pkg.repository && pkg.repository.url)) {
throw new gutil.PluginError(
'docs:changelog', 'repository url not configured in package.json');
}
changelog({
repository : pkg.repository.url,
version : pkg.version,
}, function (err, log) {
if (err) {
throw new gutil.PluginError('docs:changelog', err);
}
fs.writeFileSync('CHANGELOG.md', log);
done();
});
});
gulp.task('docs:marked', function (done) {
return gulp.src([
'TODO.md',
'CHANGELOG.md',
])
.pipe(marked({
gfm: true
}))
.pipe(gulp.dest('./release/'));
});
| JavaScript | 0.000001 | @@ -1562,17 +1562,17 @@
e %7C
-l
+L
ine # %7C
todo
@@ -1567,20 +1567,23 @@
ine # %7C
-todo
+Comment
',%0A
|
37a7b254bd696725a6a5969fb34502433043cdcd | Add method to generate random game of life board | game-of-life/src/BoardContainer.js | game-of-life/src/BoardContainer.js | import React, { Component } from 'react';
class BoardContainer extends Component {
constructor() {
}
}
export default BoardContainer;
| JavaScript | 0.000007 | @@ -99,12 +99,231 @@
) %7B%0A
-
+%0A %7D%0A randomArray = () =%3E %7B%0A array = %5B%5D;%0A for (let i = 0; i %3C 10; i++) %7B%0A array%5Bi%5D = %5B%5D;%0A for (let j = 0; j %3C 10; j++) %7B%0A array%5Bi%5D%5Bj%5D = Math.floor(Math.random() + .5);%0A %7D%0A %7D%0A return array;
%0A %7D
|
f9547a5b0025d39276b3059f5115078d91258783 | Update jsPerf_CNNChannelShuffle.js | CNN/jsPerf/jsPerf_CNNChannelShuffle.js | CNN/jsPerf/jsPerf_CNNChannelShuffle.js |
/**
* Test different channel shuffle implementation for CNN ShuffleNet.
*
* @see {@link https://jsperf.com/colorfulcakechen-cnn-channel-shuffle}
*/
// concat-reshape-transpose-reshape-split
function ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
return tf.tidy( () => {
let groupCount = dataTensor3dArray.length;
let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;
let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );
let [ h, w, c ] = dataTensor3d.shape;
let intermediateChannelCount = c / groupCount;
let x = dataTensor3d.reshape( [ h, w, groupCount, intermediateChannelCount ] );
x = x.transpose( [ 0, 1, 3, 2 ] );
x = x.reshape( [ h, w, c] );
return x = x.split( groupCount, lastAxisId );
});
}
// concat-gather
function ConcatGather( dataTensor3dArray ) {
return tf.tidy( () => {
let groupCount = dataTensor3dArray.length;
let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;
let dataTensor3d = tf.concat( dataTensor3dArray, lastAxisId );
// shuffle and split by gather (one operation achieves two operations).
let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesTensor1dArray.map(
( shuffledChannelIndicesTensor1d, i ) => {
return dataTensor3d.gather( shuffledChannelIndicesTensor1d, lastAxisId );
});
return shuffledSplitedTensor3dArray;
});
}
// split-concat
function SplitConcat( dataTensor3dArray ) {
return tf.tidy( () => {
let groupCount = dataTensor3dArray.length;
let lastAxisId = dataTensor3dArray[ 0 ].rank - 1;
let totalChannelCount = groupCount * dataTensor3dArray[ 0 ].shape[ lastAxisId ];
let intermediateChannelCount = totalChannelCount / groupCount;
// Split every group (a multiple channel tensor3d) into more (intermediate) channels.
let tensor3dArrayArray = dataTensor3dArray.map( ( dataTensor3d, i ) => {
return dataTensor3d.split( intermediateChannelCount, lastAxisId );
});
let oneChannelTensor3dArray = tensor3dArrayArray.flat(); // Every element will be a single channel tensor3d.
// shuffle and split by concat (one operation achieves two operations).
let shuffledSplitedTensor3dArray = globalThis.shuffledChannelIndicesArray.map( ( shuffledChannelIndices, i ) => {
let multipleChannelTensor3dArray = shuffledChannelIndices.map( ( channelIndex ) => {
return oneChannelTensor3dArray[ channelIndex ];
});
return tf.concat( multipleChannelTensor3dArray, lastAxisId );
});
return shuffledSplitedTensor3dArray;
// !!!
// let resultTensor3dArray = new Array( groupCount );
// let shuffledTensor3dArray = new Array( intermediateChannelCount );
// for ( let x = 0; x < groupCount; ++x ) {
//
// // Collect x-th intermediate channels of every group as new (x-th) group (i.e. shuffle them).
// for ( let y = 0; y < intermediateChannelCount; ++y ) {
// shuffledTensor3dArray[ y ] = tensor3dArrayArray[ x ][ y ];
// }
//
// // Concatenate x-th intermediate channels into one group (i.e. the x-th group).
// resultTensor3dArray[ x ] = tf.concat( shuffledTensor3dArray, lastAxisId );
// }
//
// return resultTensor3dArray;
});
}
// Test concat-reshape-transpose-reshape-split
function by_ConcatReshapeTransposeReshapeSplit( dataTensor3dArray ) {
tf.tidy( () => {
ConcatReshapeTransposeReshapeSplit( dataTensor3dArray );
});
}
// Test concat-gather
function by_ConcatGather( dataTensor3dArray ) {
tf.tidy( () => {
ConcatGather( dataTensor3dArray );
});
}
// Test split-concat
function by_SplitConcat( dataTensor3dArray ) {
tf.tidy( () => {
SplitConcat( dataTensor3dArray );
});
}
let height = 10; // image height
let width = 15; // image width
let depth = 12; // image channel count
let valueCount = height * width * depth;
let groupCount = 2; // Split the data into how many groups.
let dataTensor3dArray = tf.tidy( () => {
let dataTensor1d = tf.linspace(0, valueCount - 1, valueCount );
let dataTensor3d = dataTensor1d.reshape( [ height, width, depth ] );
return dataTensor3d.split( groupCount, dataTensor3d.rank - 1 ); // Along the last axis.
});
// Shuffled channel indices tensor1d (One dimension) for ConcatGather()
globalThis.shuffledChannelIndicesTensor1dArray = tf.tidy( () => {
let channelIndices = tf.linspace( 0, depth - 1, depth ).toInt(); // should be integer so that can be used as gather's index.
let lastAxisId = channelIndices.rank - 1;
let intermediateChannelCount = depth / groupCount;
let x = channelIndices.reshape( [ groupCount, intermediateChannelCount ] );
x = x.transpose( [ 1, 0 ] );
x = x.reshape( [ depth ] );
return x.split( groupCount, lastAxisId );
});
// Shuffled channel indices (One dimension) for SplitConcat()
globalThis.shuffledChannelIndicesArray = new Array( globalThis.shuffledChannelIndicesTensor1dArray.length );
globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndicesTensor1d.dataSync();
});
//!!!
// Promise.all(
// globalThis.shuffledChannelIndicesTensor1dArray.map( ( shuffledChannelIndicesTensor1d, i ) => {
// let p = shuffledChannelIndicesTensor1d.data().then( ( shuffledChannelIndices ) => {
// globalThis.shuffledChannelIndicesArray[ i ] = shuffledChannelIndices;
// });
// return p;
// })
// ).then( ( values ) => {
// //globalThis.shuffledChannelIndicesArray = values;
// });
globalThis.dataTensor3dArray = dataTensor3dArray;
globalThis.cnnShuffle_by_ConcatReshapeTransposeReshapeSplit = by_ConcatReshapeTransposeReshapeSplit();
globalThis.cnnShuffle_by_ConcatGather = by_ConcatGather();
globalThis.cnnShuffle_by_SplitSplitConcatConcat = by_SplitSplitConcatConcat();
| JavaScript | 0.000001 | @@ -2080,16 +2080,94 @@
ensor3d.
+%0A let multipleChannelTensor3dArray = new Array( intermediateChannelCount );
%0A%0A //
@@ -2350,24 +2350,33 @@
s, i ) =%3E %7B%0A
+//!!!%0A//
let mu
@@ -2446,32 +2446,35 @@
nelIndex ) =%3E %7B%0A
+//
return o
@@ -2509,24 +2509,27 @@
nelIndex %5D;%0A
+//
%7D);%0A
@@ -2526,16 +2526,176 @@
%7D);%0A
+%0A shuffledChannelIndices.forEach( ( channelIndex, i ) =%3E %7B%0A multipleChannelTensor3dArray%5B i %5D = oneChannelTensor3dArray%5B channelIndex %5D;%0A %7D);%0A%0A
re
|
f902c135ab5338e9bf23a2029d344936e94d5171 | Fix in update view redirect. | bridje-web/src/main/resources/BRIDJE-INF/web/themes/bridje/resources/bridje-ajax.js | bridje-web/src/main/resources/BRIDJE-INF/web/themes/bridje/resources/bridje-ajax.js | /*
* Copyright 2016 Bridje Framework.
*
* 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.
*/
/**
* Executes a bridje action to the server, and updates the HTML of the current view.
*
* @param string event The event to invoke on the server.
*/
function bridjeExecuteAction(event)
{
var form = document.getElementById("bridje-view-container");
var data = new FormData(form);
var enctype = form.getAttribute("enctype");
var view = form.getAttribute("data-bridje-view");
var url = window.location;
window.console && console.log('executing bridje action: ');
window.console && console.log(' view: ' + view);
window.console && console.log(' enctype: ' + enctype);
window.console && console.log(' event: ' + event);
window.console && console.log(' data: ' + data);
try
{
xhr = new XMLHttpRequest();
xhr.open(form.getAttribute("method"), url, 1);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.setRequestHeader('Bridje-View', encodeURI(view));
xhr.setRequestHeader('Bridje-Event', encodeURI(event));
xhr.onload = function()
{
if (xhr.status === 200)
{
var location = xhr.getResponseHeader("Bridje-Location");
console.log(location);
form.innerHTML = xhr.responseText;
window.bridjeActionExecutionComplete && window.bridjeActionExecutionComplete();
}
else if (xhr.status !== 200)
{
window.console && console.log('Request failed. Returned status of ' + xhr.status);
}
};
xhr.send(data);
}
catch (e)
{
window.console && console.log(e);
}
}
| JavaScript | 0 | @@ -1812,28 +1812,105 @@
-console.log(
+if(typeof location === %22string%22)%0A %7B%0A window.location =
location
);%0A
@@ -1905,19 +1905,79 @@
location
-)
;%0A
+ %7D%0A else%0A %7B%0A
@@ -2019,16 +2019,20 @@
seText;%0A
+
@@ -2115,24 +2115,42 @@
Complete();%0A
+ %7D%0A
|
fab82c96110ac5470055adaad43cef3cb1c20779 | correct slider hover/focus colors | packages/theme-data/src/colorSchemes/darkGray/components/slider.js | packages/theme-data/src/colorSchemes/darkGray/components/slider.js | export default {
"slider.thumb.backgroundColor": {
value: { ref: "basics.colors.charcoal100" }
},
// These color overrides specifying colorScheme.baseColor would not be necessary if darkBlue's baseColor were
// basics.colors.darkBlue200. The darkGray theme inherits from darkBlue, so we must override darkBlue's override of
// the baseTheme slider values in order to set the colors back to reference the theme baseColor.
"slider.track.color": {
value: { ref: "colorScheme.baseColor" }
},
"slider.value.color": {
value: { ref: "basics.colors.charcoal100" }
},
// Focused
"slider.focused.thumb.color": {
value: { ref: "basics.colors.charcoal100" }
},
// Hover
"slider.hover.halo.color": {
value: { ref: "colorScheme.baseColor" }
},
"slider.hover.thumb.color": {
value: { ref: "basics.colors.charcoal100" }
},
// Pressed
"slider.pressed.halo.color": {
transform: { alpha: 0.125 }
},
"slider.pressed.thumb.color": {
value: { ref: "basics.colors.charcoal100" }
}
};
| JavaScript | 0.000002 | @@ -878,78 +878,8 @@
sed%0A
- %22slider.pressed.halo.color%22: %7B%0A transform: %7B alpha: 0.125 %7D%0A %7D,%0A
%22s
|
d46c6495610a6a02b15d7e51566bf80c755dce17 | clean up changes | app/instagram.js | app/instagram.js | var request = require('request');
var Q = require('q');
var ig = require('../config/instagram');
// Kind of sly, but makes interacting with the Instagram API
// a little more effecient. In Node, variables can be shared
// across requests. We only need 1 API access token from
// Instagram, so we can use the same one since the user is
// to specify their user ID.
var _accessToken = '297048867.0a344b6.e7c0bb354e5b4699a43f11f854832985';
// ----------------------------------------------------------
// Public Methods
// ----------------------------------------------------------
var instagram = {
getAccessToken: function() {
return _getAccessToken();
},
getRecentByUserId: function(userId) {
var deferred = Q.defer();
_getAccessToken().then(function(accessToken) {
request('https://api.instagram.com/v1/users/' + userId + '/media/recent?access_token=' + accessToken,
function(err, httpResponse, body) {
if (err) return deferred.reject(err);
console.log(JSON.stringify(httpResponse).headers);
try {
var response = JSON.parse(body);
console.log(response);
deferred.resolve(response);
} catch (e) {
console.error('JSON parse error');
deferred.reject(e);
}
});
}, function(err) { return deferred.reject(err) });
return deferred.promise;
}
}
// ----------------------------------------------------------
// Private Methods
// ----------------------------------------------------------
var _getAccessToken = function() {
var deferred = Q.defer();
if (_accessToken) {
deferred.resolve(_accessToken);
return deferred.promise;
}
request.post({
url: ig.site_url,
form: {
client_id: ig.client_id,
client_secret: ig.client_secret,
username: ig.username,
password: ig.password,
grant_type: 'password'
},
}, function(err, httpResponse, body) {
if (err) return deferred.reject(err);
var response = JSON.parse(body);
console.log(response);
if (response.code) {
return deferred.reject(response);
}
_accessToken = response.access_token;
deferred.resolve(response.access_token);
});
return deferred.promise;
};
// ----------------------------------------------------------
module.exports = instagram; | JavaScript | 0.000001 | @@ -392,60 +392,12 @@
n =
-'297048867.0a344b6.e7c0bb354e5b4699a43f11f854832985'
+null
;%0A%0A/
@@ -948,68 +948,8 @@
);%0A%0A
- console.log(JSON.stringify(httpResponse).headers);%0A%0A
@@ -1004,41 +1004,8 @@
dy);
-%0A console.log(response);
%0A%0A
|
d43a8652caee922b10bd0a8b6d02694928df9da9 | fix iframe | app/scripts/components/IFrame/index.js | app/scripts/components/IFrame/index.js | import React from 'react';
import LoadingSpinner from '../Loading/LoadingSpinner';
class IFrame extends React.Component {
constructor() {
super();
this.allowGoInside = true;
this.state = {
loaded: false,
height: 400
};
}
componentDidMount() {
this.allowGoInside = this.props.src.indexOf('/proxy?url=') > -1;
this.refs.iframe.addEventListener('load', () => this.onLoad());
}
componentWillUnmount() {
this.refs.iframe.removeEventListener('load', () => this.onLoad());
}
onLoad() {
let height = this.props.src.indexOf('maps.arcgis.com') ? 650 : 400;
if (this.allowGoInside) {
height = this.refs.iframe.contentDocument.body.scrollHeight;
}
this.setState({ loaded: true, height });
}
render() {
let loading;
if (!this.state.loaded) loading = <LoadingSpinner inner />;
return (
<div className="c-iframe" style={{ height: this.state.height }}>
{loading}
<iframe ref="iframe" src={this.props.src}></iframe>
</div>
);
}
}
IFrame.propTypes = {
/**
* The source url to load iframe
*/
src: React.PropTypes.string.isRequired
};
export default IFrame;
| JavaScript | 0.000028 | @@ -1001,16 +1001,31 @@
ops.src%7D
+ sandbox=%7Btrue%7D
%3E%3C/ifram
|
b469be3bac24c97e2d7002065dc71e7f800fc38b | Fix labelling of point charts | app/scripts/controllers/pointcharts.js | app/scripts/controllers/pointcharts.js | 'use strict';
/**
* @ngdoc function
* @name ausEnvApp.controller:PointchartsCtrl
* @description
* # PointchartsCtrl
* Controller of the ausEnvApp
*/
angular.module('ausEnvApp')
.controller('PointchartsCtrl', function ($scope,$interpolate,$q,selection,details,timeseries,spatialFoci) {
$scope.selection = selection;
$scope.watchList = ['selectionMode','selectedLayer','selectedPoint'];
$scope.origViewOptions = [
{
style:'bar',
icon:'fa-bar-chart',
tooltip:'Annual time series',
visible:true
},
{
style:'timeseries',
icon:'fa-line-chart',
tooltip:'Detailed time series',
visible:true
}
];
$scope.viewOptions = $scope.origViewOptions.slice();
$scope.chartView = function(chart,visible){
for(var i in $scope.viewOptions){
var c = $scope.viewOptions[i];
if(c.style===chart){
c.visible=visible;
return;
}
}
};
$scope.locationLabel = function(){
return $interpolate('{{selectedPoint.lat() | number:4}}°,{{selectedPoint.lng()|number:4}}°')(selection);
};
$scope.canShowChart = function(style,layer,regionType){
layer = layer || $scope.selection.selectedLayer;
regionType = regionType || $scope.selection.regionType;
return layer&®ionType&&!(layer['disable-'+style]||regionType['disable-'+style]);
};
$scope.buildEvents = function(dapData,variable){
return dapData[variable].map(function(v,i){
return {
value: v,
label: dapData.time[i].getFullYear()
};
});
};
$scope.getBarData = function(){
var result = $q.defer();
var layer = $scope.selection.selectedLayer;
layer = layer.normal || layer;
var pt = $scope.selection.selectedPoint;
if(!pt){
result.reject();
$scope.chartView('bar',false);
return result.promise;
}
$scope.chartView('bar',true);
spatialFoci.regionTypes().then(function(rt){
$q.all([timeseries.retrieveAnnualForPoint(pt,layer),details.getPolygonAnnualTimeSeries(rt[0])]).then(function(resp){
var dapData = resp[0];
var metadata = resp[1];
var data = $scope.buildEvents(dapData,layer.variable);
result.resolve([data,metadata]);
},function(){
result.reject();
});
});
return result.promise;
};
$scope.getLineChartData = function(){
var result = $q.defer();
var layer = $scope.selection.selectedLayer;
layer = layer.timeseries;
if(!layer){
$scope.chartView('timeseries',false);
result.reject();return result.promise;
}
var pt = $scope.selection.selectedPoint;
if(!pt){
$scope.chartView('timeseries',false);
result.reject();return result.promise;
}
$scope.chartView('timeseries',true);
spatialFoci.regionTypes().then(function(rt){
$q.all([timeseries.retrieveTimeSeriesForPoint(pt,layer,selection.year),details.getPolygonAnnualTimeSeries(rt[0])]).then(function(resp){
var data = resp[0];
var metadata = resp[1];
result.resolve([data[layer.variable],data.time,metadata,layer.units]);
},function(){
result.reject();
});
});
return result.promise;
};
});
| JavaScript | 0.001638 | @@ -1632,32 +1632,227 @@
%7D);%0A %7D;%0A%0A
+ $scope.buildMetadata = function(layer)%7B%0A return %7B%0A label:layer.title,%0A Title:layer.title,%0A Description:layer.description,%0A Units:layer.units%0A %7D;%0A %7D;%0A%0A
$scope.getBa
@@ -1863,32 +1863,32 @@
a = function()%7B%0A
-
var result
@@ -2149,32 +2149,82 @@
omise;%0A %7D%0A%0A
+ var metadata = $scope.buildMetadata(layer);%0A
$scope.cha
@@ -2457,43 +2457,8 @@
0%5D;%0A
- var metadata = resp%5B1%5D;%0A%0A
@@ -2785,32 +2785,83 @@
n.selectedLayer;
+%0A%0A var metadata = $scope.buildMetadata(layer);
%0A layer = l
@@ -3421,32 +3421,34 @@
data = resp%5B0%5D;%0A
+//
var me
|
f93d77f86adca9310c24cd97dded0a4c16a57185 | Fix jshint errors | app/scripts/directives/formElements.js | app/scripts/directives/formElements.js | 'use strict';
angular.module('confRegistrationWebApp')
.directive('formElements', function () {
return {
restrict: 'A',
link: function questionsToolbarInterface(scope) {
//Debouncing plugin for jQuery from http://www.paulirish.com/2009/throttled-smartresize-jquery-event-handler/
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 500);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
function setQuestionToolbarSize(){
$(".questions-toolbar-container").css("min-height", function(){
return $(".questions-toolbar").height();
});
}
window.setTimeout(function () {
$(".questions-toolbar").affix({
offset: {
top: 240
}
});
setQuestionToolbarSize();
$(window).smartresize(function(){
setQuestionToolbarSize();
});
}, 500);
}
};
});
| JavaScript | 0.000318 | @@ -177,13 +177,8 @@
ace(
-scope
) %7B%0A
@@ -696,32 +696,34 @@
if (!execAsap)
+ %7B
%0A
@@ -748,16 +748,34 @@
args);%0A
+ %7D%0A
@@ -813,17 +813,16 @@
%7D
-;
%0A%0A
@@ -841,16 +841,18 @@
timeout)
+ %7B
%0A
@@ -897,16 +897,17 @@
+%7D
else if
@@ -916,16 +916,18 @@
xecAsap)
+ %7B
%0A
@@ -958,16 +958,31 @@
args);%0A
+ %7D
%0A
@@ -1055,32 +1055,33 @@
%7D;%0A %7D
+;
%0A // sm
@@ -1283,33 +1283,33 @@
()%7B%0A $(
-%22
+'
.questions-toolb
@@ -1324,16 +1324,16 @@
iner
-%22
+'
).css(
-%22
+'
min-
@@ -1338,17 +1338,17 @@
n-height
-%22
+'
, functi
@@ -1374,17 +1374,17 @@
eturn $(
-%22
+'
.questio
@@ -1393,17 +1393,17 @@
-toolbar
-%22
+'
).height
@@ -1482,17 +1482,17 @@
$(
-%22
+'
.questio
@@ -1505,9 +1505,9 @@
lbar
-%22
+'
).af
|
023a1d5efa6619301f6e5750acf94aeeb04fd47c | Add a function to delete compare info by user ID | app/services/compare.server.service.js | app/services/compare.server.service.js | 'use strict';
var mongoose = require('mongoose'),
Compare = mongoose.model('Compare'),
_ = require('lodash'),
Q = require('q'),
config = require('../../config/config');
exports.deleteCompareById = function (compareId) {
var deferred = Q.defer();
compareId.findByIdAndRemove(compareId, function (err, compare) {
if (err) {
return deferred.reject(err);
}
return deferred.resolve(compare);
});
return deferred.promise;
};
var isExistCompare = function (userId, callback) {
Compare.findOne({user: userId}, function (error, compare) {
if (error || !compare) {
return callback(false);
}
return callback(compare);
});
};
var createCompare = function (userId, items, callback) {
var newCompare = new Compare({user: userId, items: items});
newCompare.save(function (error) {
if (error) {
return callback(false);
}
return callback(true);
});
};
var isExistItem = function (userId, productId, callback) {
Compare.findOne({user: userId, 'items.product': productId}, function (error, compare) {
if (error || !compare) {
return callback(false);
}
return callback(true);
});
};
var addItem = function (userId, item, callback) {
Compare.findOneAndUpdate({user: userId}, {$push: {items: item}}, function (error) {
if (error) {
return callback(false);
}
return callback(true);
});
};
exports.addToCompare = function (userId, item) {
var deferred = Q.defer();
isExistCompare(userId, function (existCompare) {
if (existCompare) {
isExistItem(userId, item.product, function (exitItem) {
if (exitItem) {
return deferred.resolve({msg: 'success'});
} else {
addItem(userId, item, function (added) {
if (added) {
return deferred.resolve({msg: 'success'});
}
return deferred.reject({msg: 'failed'});
});
}
});
} else {
createCompare(userId, [item], function (created) {
if (created) {
return deferred.resolve({msg: 'success'});
}
return deferred.reject({msg: 'failed'});
});
}
});
return deferred.promise;
};
exports.getCompare = function (userId) {
var deferred = Q.defer();
Compare.findOne({user: userId})
.populate('items.product', 'info photos')
.exec(function (error, compare) {
if (error) {
return deferred.reject({msg: 'empty'});
}
if (!compare) {
return deferred.resolve({});
}
return deferred.resolve(compare);
});
return deferred.promise;
};
exports.getCompareById = function (compareId) {
var deferred = Q.defer();
Compare.findOne({_id: compareId})
.populate('items.product', 'info photos')
.exec(function (error, compare) {
if (error) {
return deferred.reject({msg: 'empty'});
}
if (!compare) {
return deferred.resolve({});
}
return deferred.resolve(compare);
});
return deferred.promise;
};
exports.deleteCompareItem = function (userId, item) {
var deferred = Q.defer();
Compare.findOneAndUpdate({user: userId}, {$pull: {items: {product: item.product}}}, {new: true})
.populate('items.product', 'info photos')
.exec(function (error, compare) {
if (error) {
return deferred.reject({msg: 'failed'});
}
return deferred.resolve(compare);
});
return deferred.promise;
};
exports.deleteAllCompareItems = function (userId) {
var deferred = Q.defer();
Compare.findOneAndUpdate({user: userId}, {$set: {items: []}}, {new: true})
.exec(function (error, compare) {
if (error) {
return deferred.reject({msg: 'failed'});
}
return deferred.resolve(compare);
});
return deferred.promise;
};
| JavaScript | 0 | @@ -265,25 +265,23 @@
();%0A
-c
+C
ompare
-Id
.findByI
@@ -477,24 +477,339 @@
romise;%0A%7D;%0A%0A
+exports.deleteCompareByUserId = function (userId) %7B%0A var deferred = Q.defer();%0A Compare.findOneAndRemove(%7Buser: userId%7D, function (err, compare) %7B%0A if (err) %7B%0A return deferred.reject(err);%0A %7D%0A return deferred.resolve(%7Bmsg: 'success'%7D);%0A %7D);%0A return deferred.promise;%0A%7D;%0A%0A
var isExistC
|
c370ced80fed16a993fe2223709763843d1e099b | Use upload file chunked | scripts/sources/BlobFileSource.js | scripts/sources/BlobFileSource.js |
var BlobFileSource = Source.createComponent("BlobFileSource");
BlobFileSource.defineMethod("construct", function construct() {
if (!this.fileHandler) this.fileHandler = new BlobFileHandler();
});
BlobFileSource.defineMethod("init", function init(content, jointSource, sourceId) {
if (content) {
this.fileHandler.blob = content["0"];
this.fileHandler.didUpdate();
}
});
BlobFileSource.defineMethod("didUpdate", function didUpdate() {
this.fileHandler.blob = this.content["0"];
this.fileHandler.didUpdate();
});
BlobFileSource.defineMethod("destruct", function destruct() {
this.fileHandler.destroy();
});
BlobFileSource.prototype.prePublish = function () {
return Promise.resolve()
.then(function () {
if (this.content["0"] && this.content["0"] instanceof Blob) {
return ICA.uploadFile(this.content["0"])
.then(function (fileId) {
this.content["0"] = fileId;
}.bind(this));
}
}.bind(this));
};
BlobFileSource.prototype.getFileStats = function () {
if (this.content["0"]) {
if (this.content["0"] instanceof Blob) {
return Promise.resolve({
size: this.content["0"].size,
type: this.content["0"].type
});
}
return ICA.getFileStats(this.content["0"]);
}
return Promise.reject(new Error("File not exist"));
};
| JavaScript | 0 | @@ -831,16 +831,23 @@
loadFile
+Chunked
(this.co
|
d434e4f7b68a45c7118c021c446ed22dfe3f0939 | add global 'saveState()' function for saving after console changes | scripts/ui/requiremodsshortcut.js | scripts/ui/requiremodsshortcut.js | /**
* RequireModsShortcut
*
* @return RequireModsShortcut
* @author Erik E. Lorenz <erik@tuvero.de>
* @license MIT License
* @see LICENSE
*/
define(['lib/extend', 'core/model'], function (extend, Model) {
function RequireModsShortcut () {
RequireModsShortcut.superconstructor.call(this)
window.setTimeout(this.createModsObject.bind(this), 1)
}
extend(RequireModsShortcut, Model)
RequireModsShortcut.prototype.createModsObject = function () {
var rjsdef, mods
if (window.mods !== undefined) {
return
}
rjsdef = require.s.contexts._.defined
if (!rjsdef) {
console.error('require.s.contexts._.defined is undefined')
return
}
mods = window.mods = {}
// add every key to mods, which is similar to the directory tree
Object.keys(rjsdef).forEach(function (key) {
var keyparts, subobject
keyparts = key.split('/')
subobject = mods
// search the position of the key, add new objects as necessary
keyparts.forEach(function (part, partid) {
if (partid >= keyparts.length - 1) {
subobject[part] = rjsdef[key]
} else {
if (subobject[part] === undefined) {
subobject[part] = {}
}
subobject = subobject[part]
}
})
})
window.tuvero = mods.tuvero
window.state = mods.ui && mods.ui.state
window.teams = mods.ui && mods.ui.state.teams
window.tournaments = mods.ui && mods.ui.state.tournaments
}
return RequireModsShortcut
})
| JavaScript | 0.000001 | @@ -1485,16 +1485,108 @@
rnaments
+%0A%0A window.saveState = mods.ui && function () %7B%0A mods.ui.statesaver.saveState()%0A %7D
%0A %7D%0A%0A
|
593e175e44d8bf2c184a56fe6cdd0f2d662f87d8 | Fix API vor GoCD v20.2.0 | server/services/GoBuildService.js | server/services/GoBuildService.js | import rp from 'request-promise';
import Logger from '../utils/Logger';
import GoPipelineParser from '../utils/GoPipelineParser';
import Util from '../utils/Util';
export default class GoBuildService {
constructor(goConfig) {
this.conf = goConfig;
}
/**
* @returns {Promise<Array<string>>} All available pipelines from the go.cd server
*/
getAllPipelines() {
const options = Util.createRequestOptions(`${this.conf.serverUrl}/go/api/pipelines.xml`, this.conf);
return rp(options)
.then((res) => {
// Parse response xml
return GoPipelineParser.parsePipelineNames(res).then((pipelineNames) => {
return pipelineNames;
}, (error) => {
Logger.error('Failed to parse pipelines.xml');
throw error;
});
}).catch((err) => {
Logger.error('Failed to retrieve pipeline names');
throw err
});
}
/**
* @returns {Promise<Array<Object>>} All available pipeline groups from the go.cd server
*/
getPipelineGroups() {
const options = Util.createRequestOptions(`${this.conf.serverUrl}/go/api/config/pipeline_groups`, this.conf);
return rp(options)
.then((res) => {
return JSON.parse(res);
}).catch((err) => {
Logger.error('Failed to retrieve pipeline groups');
throw err
});
}
/**
* Retrive all pipelines paused info.
*
* @return {Promise<Object}
* Example
* {
* 'pipeline1' : {
* paused : false,
* paused_by: null,
* pause_reason: null},
* 'pipeline2' : {
* paused : true,
* paused_by : 'me',
* pause_reason : 'Under construction'
* }
* }
*/
getPipelinesPauseInfo() {
const options = Util.createRequestOptions(`${this.conf.serverUrl}/go/api/dashboard`, this.conf, true, {'Accept' : 'application/vnd.go.cd.v1+json'});
return rp(options)
.then((res) => {
// Return map with pipeline name as key.
return res._embedded.pipeline_groups.reduce((acc, curr) => {
curr._embedded.pipelines.forEach((cp) => {
acc[cp.name] = cp.pause_info;
});
return acc;
}, {});
})
.catch((err) => {
Logger.error('Failed to retrieve pipeline pause information');
return {};
})
}
/**
* @param {string} name Name of the pipeline
* @returns {Promise<Object>} Pipeline instance.
* Example
* {
* name : 'id,
* buildtime : 1457085089646,
* author: 'Bobby Malone',
* counter: 255,
* paused: false,
* health: 2,
* stageresults: [
* {
* name: 'Build',
* status: 'passed',
* jobresults: [{
* name: 'build-job',
* result: 'passed',
* schedueld: 1457085089646
* }]
* },
* {
* name: 'Test',
* status: 'building'
* jobresults: []
* }]
* }
*/
getPipelineHistory(name) {
const options = Util.createRequestOptions(`${this.conf.serverUrl}/go/api/pipelines/${name}/history/0`, this.conf, true);
return rp(options)
.then(res => GoPipelineParser.parsePipelineResult(res.pipelines.slice(0, 5)))
.catch((err) => {
Logger.error(`Failed to get pipeline history for pipeline "${name}" returning last result, ${err.statusCode}: ${err.message}`);
return this.pipelines ? this.pipelines.filter((p) => p && p.name === name)[0] : null;
});
}
}
| JavaScript | 0.000002 | @@ -1865,17 +1865,17 @@
.go.cd.v
-1
+3
+json'%7D)
@@ -3130,10 +3130,8 @@
tory
-/0
%60, t
@@ -3144,20 +3144,65 @@
nf, true
+, %7B'Accept' : 'application/vnd.go.cd.v1+json'%7D
);%0A
-%0A
retu
|
046e8b537bd192273951c4a296932f805c922fc0 | Handle correct spelling of card code input | app/assets/javascripts/store/spree_reuse_credit_card.js | app/assets/javascripts/store/spree_reuse_credit_card.js | //= require jquery.alerts/jquery.alerts
//= require_self
var creditCardDeleteCallback=$.noop();
function displayCreditCardDeleteStatus(notice) {
notice_div = $('.flash.notice');
if (notice) {
if (notice_div.length > 0) {
notice_div.html(notice);
notice_div.show();
} else {
$("#card_notice").html('<div class="flash notice">' + notice + '</div>');
}
}
creditCardDeleteCallback();
}
function paymentPageResetCreditCardOptions() {
// if we don't do this, we'll accidentally submit our 'use existing'
// id and we won't use a new card
$("#existing_cards input[type=radio]:checked:hidden").removeAttr('checked');
// if we select a card, we enable the continue button, but if we then
// delete it, we need to restore the button back to it's disabled state
// did we just delete the last card?
if ($('.existing-credit-card-list tbody tr:visible').length == 0) {
$('#card_options').hide();
$('#existing_cards').hide();
// 'new card'is our only option now
$('#use_existing_card_no').click();
// restoreContinueButton();
} else {
useExistingCardsInit();
}
}
$(document).on('click', '#use_existing_card_no', function () {
// why am i having to hide the contents of the div as well???
$("#existing_cards").hide();
$("#existing_cards h4").hide();
$("#existing_cards table").hide();
$("[data-hook=card_number]").show();
$("[data-hook=card_expiration]").show();
$("[data-hook=cart_code]").show(); // unfortunately this is a typo in spree (cart v card)
restoreContinueButton();
// if we don't do this, we'll accidentally submit our 'use existing'
// id and we won't use a new card
$("#existing_cards input[type=radio]:checked").removeAttr('checked');
});
$(document).on('click', '#use_existing_card_yes', function () {
useExistingCardsInit();
});
$(document).on('change', 'input[type=radio][name=existing_card]',function () {
if ($(this).is(':checked')) {
restoreContinueButton();
}
}
);
// when we select a different payment method, make sure we re-enable the continue button
// so find every payment method radio that's not a credit card method
$(document).on('click','input[type="radio"][name="order[payments_attributes][][payment_method_id]"]', function() {
($('#payment-methods li')).hide();
if (this.checked) {
if ($('#payment_method_' + this.value).find('#existing_cards').length > 0) {
disableContinueButton();
} else {
restoreContinueButton();
}
return ($('#payment_method_' + this.value)).show();
}
});
function restoreContinueButton() {
$(".form-buttons input[type=submit]").attr('disabled',false);
$(".form-buttons input[type=submit]").val(original_button_text);
}
function useExistingCardsInit() {
$("#existing_cards").show();
$("#existing_cards h4").show();
$("#existing_cards table").show();
$("[data-hook=card_number]").hide();
$("[data-hook=card_expiration]").hide();
$("[data-hook=cart_code]").hide(); // unfortunately this is a typo in spree (cart v card)
disableContinueButton();
}
function disableContinueButton() {
if ($("#existing_cards input[type=radio]:checked").length == 0) {
// temporarily rename & disable the save button if no cards are selected
$(".form-buttons input[type=submit]").attr('disabled',true);
$(".form-buttons input[type=submit]").val('Please Select a Card to Use');
}
}
| JavaScript | 0.999911 | @@ -1728,16 +1728,38 @@
rt_code%5D
+,%5Bdata-hook=card_code%5D
%22).show(
@@ -1772,36 +1772,38 @@
unfortunately th
-is i
+ere wa
s a typo in spre
@@ -1796,32 +1796,41 @@
a typo in spree
+pre-v1.1
(cart v card)%0A%0A
@@ -3539,16 +3539,38 @@
rt_code%5D
+,%5Bdata-hook=card_code%5D
%22).hide(
@@ -3595,12 +3595,14 @@
y th
-is i
+ere wa
s a
@@ -3615,16 +3615,25 @@
n spree
+pre-v1.1
(cart v
|
a5591c90559007af79766c2fd280f9cfe9a7d730 | remove duplicated code (#805) | packages/gluestick/src/renderer/main.js | packages/gluestick/src/renderer/main.js | /* @flow */
/**
* To import/require file from project use aliases:
* root, src, actions, assets, components, containers, reducers, config
* To import/require renderer server file use relative paths.
*/
import type {
Context,
Request,
Response,
ServerPlugin,
} from '../types';
const path = require('path');
const express = require('express');
const compression = require('compression');
const middleware = require('./middleware');
const entries = require('project-entries').default;
// $FlowIgnore
const entriesConfig = require('project-entries-config');
// $FlowIgnore
const EntryWrapper = require('entry-wrapper').default;
// $FlowIgnore
const assets = require('webpack-chunks');
// $FlowIgnore
const projectHooks = require('gluestick-hooks').default;
const BodyWrapper = require('./components/Body').default;
// $FlowIgnore
const reduxMiddlewares = require('redux-middlewares').default;
// $FlowIgnore
const entriesPlugins = require('project-entries').plugins;
const hooksHelper = require('./helpers/hooks');
const prepareServerPlugins = require('../plugins/prepareServerPlugins');
// $FlowIgnore Assets should be bundled into render to serve them in production.
require.context('build-assets');
module.exports = ({ config, logger }: Context) => {
const serverPlugins: ServerPlugin[] = prepareServerPlugins(logger, entriesPlugins);
// Merge hooks from project and plugins' hooks.
const hooks = hooksHelper.merge(projectHooks, serverPlugins);
// Developers can add an optional hook that
// includes script with initialization stuff.
if (hooks.preInitServer && typeof hooks.preInitServer === 'function') {
hooks.preInitServer();
}
// Developers can add an optional hook that
// includes script with initialization stuff.
if (hooks.preInitServer && typeof hooks.preInitServer === 'function') {
hooks.preInitServer();
}
// Get runtime plugins that will be passed to EntryWrapper.
const runtimePlugins: Function[] = entriesPlugins
.filter((plugin: Object) => plugin.type === 'runtime')
.map((plugin: Object) => plugin.ref);
const app: Object = express();
app.use(compression());
app.use('/assets', express.static(
path.join(process.cwd(), config.GSConfig.buildAssetsPath),
));
if (process.env.NODE_ENV !== 'production') {
app.get('/gluestick-proxy-poll', (req: Request, res: Response) => {
// allow requests from our client side loading page
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept');
res.status(200).json({ up: true });
});
}
app.use((req: Request, res: Response) => {
middleware(
{ config, logger },
req, res,
{ entries, entriesConfig, entriesPlugins: runtimePlugins },
{ EntryWrapper, BodyWrapper },
assets,
{
reduxMiddlewares,
envVariables: [],
httpClient: {},
entryWrapperConfig: {},
},
{ hooks, hooksHelper: hooksHelper.call },
serverPlugins,
);
});
const server: Object = app.listen(config.GSConfig.ports.server);
// Call express App Hook which accept app as param.
hooksHelper.call(hooks.postServerRun, app);
logger.success(`Renderer listening on port ${config.GSConfig.ports.server}.`);
process.on('exit', () => {
server.close();
});
process.on('SIGINT', () => {
server.close();
});
};
| JavaScript | 0 | @@ -1345,24 +1345,25 @@
esPlugins);%0A
+%0A
// Merge h
@@ -1400,16 +1400,16 @@
hooks.%0A
+
const
@@ -1467,207 +1467,8 @@
ns);
-%0A // Developers can add an optional hook that%0A // includes script with initialization stuff.%0A if (hooks.preInitServer && typeof hooks.preInitServer === 'function') %7B%0A hooks.preInitServer();%0A %7D
%0A%0A
|
1eceff92a52f91bcabb791d76000d90670c90781 | Fix contexts not being displayed in the same order as the resource tree. | assets/components/clientconfig/js/mgr/widgets/combos.js | assets/components/clientconfig/js/mgr/widgets/combos.js | ClientConfig.combo.Groups = function(config) {
config = config || {};
Ext.applyIf(config,{
url: ClientConfig.config.connectorUrl,
baseParams: {
action: 'mgr/groups/getlist',
combo: true
},
fields: ['id','label'],
hiddenName: config.name || 'group',
pageSize: 15,
valueField: 'id',
displayField: 'label'
});
ClientConfig.combo.Groups.superclass.constructor.call(this,config);
if (config.storeLoadListener) {
this.store.on('load', config.storeLoadListener, this);
this.on('render', function() {
if (!this.getValue()) {
this.store.load();
}
});
}
};
Ext.extend(ClientConfig.combo.Groups,MODx.combo.ComboBox);
Ext.reg('clientconfig-combo-groups',ClientConfig.combo.Groups);
ClientConfig.combo.FieldTypes = function(config) {
config = config || {};
Ext.applyIf(config,{
store: new Ext.data.ArrayStore({
mode: 'local',
fields: ['xtype','label'],
data: [
['textfield', _('clientconfig.xtype.textfield')],
['textarea', _('clientconfig.xtype.textarea')],
['richtext', _('clientconfig.xtype.richtext')],
['code', _('clientconfig.xtype.code')],
['modx-panel-tv-image', _('clientconfig.xtype.image')],
['modx-panel-tv-file', _('clientconfig.xtype.file')],
['numberfield', _('clientconfig.xtype.numberfield')],
['colorpickerfield', _('clientconfig.xtype.colorpalette')],
['email', _('clientconfig.xtype.email')],
['xcheckbox', _('clientconfig.xtype.xcheckbox')],
['datefield', _('clientconfig.xtype.datefield')],
['timefield', _('clientconfig.xtype.timefield')],
['password', _('clientconfig.xtype.password')],
['modx-combo', _('clientconfig.xtype.combobox')],
['googlefontlist', _('clientconfig.xtype.googlefonts')],
['clientconfig-line', _('clientconfig.xtype.line')]
]
}),
hiddenName: config.name || 'xtype',
valueField: 'xtype',
displayField: 'label',
mode: 'local',
value: 'textfield'
});
if (MODx.config['clientconfig.google_fonts_api_key'] == '') config.store.removeAt(config.store.find('xtype','googlefontlist'));
ClientConfig.combo.FieldTypes.superclass.constructor.call(this,config);
};
Ext.extend(ClientConfig.combo.FieldTypes,MODx.combo.ComboBox);
Ext.reg('clientconfig-combo-fieldtypes',ClientConfig.combo.FieldTypes);
ClientConfig.combo.GoogleFontList = function(config) {
config = config || {};
Ext.applyIf(config,{
url: ClientConfig.config.connectorUrl,
baseParams: {
action: 'mgr/fonts/google/getList',
combo: true
},
fields: ['family','name'],
hiddenName: config.name || 'font',
valueField: 'family',
displayField: 'name'
});
ClientConfig.combo.GoogleFontList.superclass.constructor.call(this,config);
};
Ext.extend(ClientConfig.combo.GoogleFontList, MODx.combo.ComboBox);
Ext.reg('googlefontlist',ClientConfig.combo.GoogleFontList);
ClientConfig.combo.ContextList = function(config) {
config = config || {};
Ext.applyIf(config,{
url: ClientConfig.config.connectorUrl,
baseParams: {
action: 'mgr/contexts/getlist',
exclude: 'mgr',
combo: true
},
fields: ['key','name'],
hiddenName: config.name || 'context',
valueField: 'key',
displayField: 'name',
pageSize: 20
// Typeahead prevents the dropdown from opening on click, needs a solution first
// editable: true,
// typeahead: true,
// forceSelection: true,
// queryParam: 'search',
});
ClientConfig.combo.ContextList.superclass.constructor.call(this,config);
};
Ext.extend(ClientConfig.combo.ContextList, MODx.combo.ComboBox);
Ext.reg('clientconfig-combo-contexts',ClientConfig.combo.ContextList);
ClientConfig.ux.Line = Ext.extend(Ext.Component, {
autoEl: 'hr'
});
Ext.reg('clientconfig-line', ClientConfig.ux.Line); | JavaScript | 0 | @@ -3551,32 +3551,61 @@
combo: true
+,%0A sort: '%60rank%60',
%0A %7D,%0A
|
e8e910b7c58ec522df8d32daa6c383aaeb65179f | Address Code Climate issues | assets/js/app/admin/products/product_form_controller.js | assets/js/app/admin/products/product_form_controller.js | 'use strict';
/**
* @todo This mirrors the admin_user_form_controller.js file in a lot of regards, could be abstracted.
*/
/**@ngInject*/
function ProductFormController($state, FlashesService) {
var self = this;
this.product = null;
this.formSubmitted = false;
this.priceRegex = "\\d{1,6}(\\.\\d{1,4})?";
this.initForm = function(parent) {
this.product = parent.product;
};
this.create = function() {
self.formSubmitted = true;
if (self.form.$invalid) {
return false;
}
self.product.$save(function() {
$state.go('base.authed.admin.products.list');
}, function() {
FlashesService.add({
timeout: true,
type: 'error',
message: 'There was a problem saving the product. You may want to try again later.'
});
});
};
this.update = function() {
self.formSubmitted = true;
if (self.form.$invalid) {
return false;
}
// Make sure description is a string, textarea empty is null which is not valid;
self.product.description = String(self.product.description);
self.product.$update(function() {
$state.go('base.authed.admin.products.list');
}, function() {
FlashesService.add({
timeout: true,
type: 'error',
message: 'There was a problem updating the product. You may want to try again later.'
});
});
};
this.destroy = function() {
self.formSubmitted = true;
self.product.$delete(function() {
$state.go('base.authed.admin.products.list');
}, function() {
FlashesService.add({
timeout: true,
type: 'error',
message: 'There was a problem removing the product. You may want to try again later.'
});
});
};
this.canSubmit = function() {
return !self.formSubmitted || (self.form.$dirty && self.form.$valid);
};
this.hasError = function(field, validation) {
// Only show validation errors on submit; Avoids angulars hasty error messaging
if (validation) {
return self.formSubmitted && self.form[field].$error[validation];
}
return self.formSubmitted && self.form[field].$invalid;
};
}
module.exports = ProductFormController;
| JavaScript | 0 | @@ -397,160 +397,31 @@
%0A%0A
-this.create = function() %7B%0A self.formSubmitted = true;%0A if (self.form.$invalid) %7B%0A return false;%0A %7D%0A self.product.$save(function
+function onSuccess
() %7B%0A
-
@@ -460,36 +460,36 @@
ducts.list');%0A
- %7D,
+%7D%0A%0A
function() %7B%0A
@@ -473,39 +473,47 @@
%0A %7D%0A%0A function
+ onFailure
() %7B%0A
-
FlashesServi
@@ -513,34 +513,32 @@
esService.add(%7B%0A
-
timeout: t
@@ -540,34 +540,32 @@
ut: true,%0A
-
type: 'error',%0A
@@ -555,34 +555,32 @@
type: 'error',%0A
-
message: '
@@ -653,35 +653,192 @@
later.'%0A
- %7D);%0A %7D
+%7D);%0A %7D%0A%0A this.create = function() %7B%0A self.formSubmitted = true;%0A if (self.form.$invalid) %7B%0A return false;%0A %7D%0A self.product.$save(onSuccess, onFailure
);%0A %7D;%0A%0A t
@@ -1131,637 +1131,143 @@
ate(
-function() %7B%0A $state.go('base.authed.admin.products.list');%0A %7D, function() %7B%0A FlashesService.add(%7B%0A timeout: true,%0A type: 'error',%0A message: 'There was a problem updating the product. You may want to try again later.'%0A %7D);%0A %7D);%0A %7D;%0A%0A this.destroy = function() %7B%0A self.formSubmitted = true;%0A self.product.$delete(function() %7B%0A $state.go('base.authed.admin.products.list');%0A %7D, function() %7B%0A FlashesService.add(%7B%0A timeout: true,%0A type: 'error',%0A message: 'There was a problem removing the product. You may want to try again later.'%0A %7D);%0A %7D
+onSuccess, onFailure);%0A %7D;%0A%0A this.destroy = function() %7B%0A self.formSubmitted = true;%0A self.product.$delete(onSuccess, onFailure
);%0A
|
489658129dcfe43d27c97410efb3e5c06ba57faf | fix inserted marks (#1338) | packages/slate/src/changes/at-current-range.js | packages/slate/src/changes/at-current-range.js |
import Block from '../models/block'
import Inline from '../models/inline'
import Mark from '../models/mark'
/**
* Changes.
*
* @type {Object}
*/
const Changes = {}
/**
* Mix in the changes that pass through to their at-range equivalents because
* they don't have any effect on the selection.
*/
const PROXY_TRANSFORMS = [
'deleteBackward',
'deleteCharBackward',
'deleteLineBackward',
'deleteWordBackward',
'deleteForward',
'deleteCharForward',
'deleteWordForward',
'deleteLineForward',
'setBlock',
'setInline',
'splitInline',
'unwrapBlock',
'unwrapInline',
'wrapBlock',
'wrapInline',
]
PROXY_TRANSFORMS.forEach((method) => {
Changes[method] = (change, ...args) => {
const { value } = change
const { selection } = value
const methodAtRange = `${method}AtRange`
change[methodAtRange](selection, ...args)
}
})
/**
* Add a `mark` to the characters in the current selection.
*
* @param {Change} change
* @param {Mark} mark
*/
Changes.addMark = (change, mark) => {
mark = Mark.create(mark)
const { value } = change
const { document, selection } = value
if (selection.isExpanded) {
change.addMarkAtRange(selection, mark)
}
else if (selection.marks) {
const marks = selection.marks.add(mark)
const sel = selection.set('marks', marks)
change.select(sel)
}
else {
const marks = document.getActiveMarksAtRange(selection).add(mark)
const sel = selection.set('marks', marks)
change.select(sel)
}
}
/**
* Delete at the current selection.
*
* @param {Change} change
*/
Changes.delete = (change) => {
const { value } = change
const { selection } = value
change.deleteAtRange(selection)
// Ensure that the selection is collapsed to the start, because in certain
// cases when deleting across inline nodes, when splitting the inline node the
// end point of the selection will end up after the split point.
change.collapseToStart()
}
/**
* Insert a `block` at the current selection.
*
* @param {Change} change
* @param {String|Object|Block} block
*/
Changes.insertBlock = (change, block) => {
block = Block.create(block)
const { value } = change
const { selection } = value
change.insertBlockAtRange(selection, block)
// If the node was successfully inserted, update the selection.
const node = change.value.document.getNode(block.key)
if (node) change.collapseToEndOf(node)
}
/**
* Insert a `fragment` at the current selection.
*
* @param {Change} change
* @param {Document} fragment
*/
Changes.insertFragment = (change, fragment) => {
if (!fragment.nodes.size) return
let { value } = change
let { document, selection } = value
const { startText, endText, startInline } = value
const lastText = fragment.getLastText()
const lastInline = fragment.getClosestInline(lastText.key)
const keys = document.getTexts().map(text => text.key)
const isAppending = (
!startInline ||
selection.hasEdgeAtStartOf(startText) ||
selection.hasEdgeAtEndOf(endText)
)
change.insertFragmentAtRange(selection, fragment)
value = change.value
document = value.document
const newTexts = document.getTexts().filter(n => !keys.includes(n.key))
const newText = isAppending ? newTexts.last() : newTexts.takeLast(2).first()
if (newText && lastInline) {
change.select(selection.collapseToEndOf(newText))
}
else if (newText) {
change.select(selection.collapseToStartOf(newText).move(lastText.text.length))
}
else {
change.select(selection.collapseToStart().move(lastText.text.length))
}
}
/**
* Insert an `inline` at the current selection.
*
* @param {Change} change
* @param {String|Object|Inline} inline
*/
Changes.insertInline = (change, inline) => {
inline = Inline.create(inline)
const { value } = change
const { selection } = value
change.insertInlineAtRange(selection, inline)
// If the node was successfully inserted, update the selection.
const node = change.value.document.getNode(inline.key)
if (node) change.collapseToEndOf(node)
}
/**
* Insert a string of `text` with optional `marks` at the current selection.
*
* @param {Change} change
* @param {String} text
* @param {Set<Mark>} marks (optional)
*/
Changes.insertText = (change, text, marks) => {
const { value } = change
const { document, selection } = value
marks = marks || selection.marks
change.insertTextAtRange(selection, text, marks)
// If the text was successfully inserted, and the selection had marks on it,
// unset the selection's marks.
if (selection.marks && document != change.value.document) {
change.select({ marks: null })
}
}
/**
* Split the block node at the current selection, to optional `depth`.
*
* @param {Change} change
* @param {Number} depth (optional)
*/
Changes.splitBlock = (change, depth = 1) => {
const { value } = change
const { selection } = value
change
.splitBlockAtRange(selection, depth)
.collapseToEnd()
}
/**
* Remove a `mark` from the characters in the current selection.
*
* @param {Change} change
* @param {Mark} mark
*/
Changes.removeMark = (change, mark) => {
mark = Mark.create(mark)
const { value } = change
const { document, selection } = value
if (selection.isExpanded) {
change.removeMarkAtRange(selection, mark)
}
else if (selection.marks) {
const marks = selection.marks.remove(mark)
const sel = selection.set('marks', marks)
change.select(sel)
}
else {
const marks = document.getActiveMarksAtRange(selection).remove(mark)
const sel = selection.set('marks', marks)
change.select(sel)
}
}
/**
* Add or remove a `mark` from the characters in the current selection,
* depending on whether it's already there.
*
* @param {Change} change
* @param {Mark} mark
*/
Changes.toggleMark = (change, mark) => {
mark = Mark.create(mark)
const { value } = change
const exists = value.activeMarks.has(mark)
if (exists) {
change.removeMark(mark)
} else {
change.addMark(mark)
}
}
/**
* Wrap the current selection with prefix/suffix.
*
* @param {Change} change
* @param {String} prefix
* @param {String} suffix
*/
Changes.wrapText = (change, prefix, suffix = prefix) => {
const { value } = change
const { selection } = value
change.wrapTextAtRange(selection, prefix, suffix)
// If the selection was collapsed, it will have moved the start offset too.
if (selection.isCollapsed) {
change.moveStart(0 - prefix.length)
}
// Adding the suffix will have pushed the end of the selection further on, so
// we need to move it back to account for this.
change.moveEnd(0 - suffix.length)
// There's a chance that the selection points moved "through" each other,
// resulting in a now-incorrect selection direction.
if (selection.isForward != change.value.selection.isForward) {
change.flip()
}
}
/**
* Export.
*
* @type {Object}
*/
export default Changes
| JavaScript | 0 | @@ -4361,25 +4361,21 @@
arks %7C%7C
-selection
+value
.marks%0A
|
ba5f12778a5b7392ecb8c0857bc9c869d532af6c | fix clean permission | packages/strapi-admin/services/content-type.js | packages/strapi-admin/services/content-type.js | 'use strict';
const _ = require('lodash');
const fp = require('lodash/fp');
const EXCLUDE_FIELDS = ['created_by', 'updated_by'];
/**
* Creates an array of paths to the fields and nested fields, without path nodes
* @param {string} model model used to get the nested fields
* @param {Object} options
* @param {string} options.prefix prefix to add to the path
* @param {number} options.nestingLevel level of nesting to achieve
* @param {object} options.components components where components attributes can be found
* @param {object} options.requiredOnly only returns required nestedFields
* @param {object} options.existingFields fields that are already selected, meaning that some sub-fields may be required
* @returns {array<string>}
* @param model
*/
const getNestedFields = (
model,
{ prefix = '', nestingLevel = 15, components = {}, requiredOnly = false, existingFields = [] }
) => {
if (nestingLevel === 0) {
return prefix ? [prefix] : [];
}
return _.reduce(
model.attributes,
(fields, attr, key) => {
if (EXCLUDE_FIELDS.includes(key)) return fields;
const fieldPath = prefix ? `${prefix}.${key}` : key;
const requiredOrNotNeeded = !requiredOnly || attr.required === true;
const insideExistingFields = existingFields && existingFields.some(fp.startsWith(fieldPath));
if (attr.type === 'component') {
if (requiredOrNotNeeded || insideExistingFields) {
const compoFields = getNestedFields(components[attr.component], {
nestingLevel: nestingLevel - 1,
prefix: fieldPath,
components,
requiredOnly,
existingFields,
});
if (requiredOnly && compoFields.length === 0 && attr.required) {
return fields.concat(fieldPath);
}
return fields.concat(compoFields);
}
return fields;
}
if (requiredOrNotNeeded) {
return fields.concat(fieldPath);
}
return fields;
},
[]
);
};
/**
* Creates an array of paths to the fields and nested fields, with path nodes
* @param {string} model model used to get the nested fields
* @param {Object} options
* @param {string} options.prefix prefix to add to the path
* @param {number} options.nestingLevel level of nesting to achieve
* @param {object} options.components components where components attributes can be found
* @returns {array<string>}
*/
const getNestedFieldsWithIntermediate = (
model,
{ prefix = '', nestingLevel = 15, components = {} }
) => {
if (nestingLevel === 0) {
return [];
}
return _.reduce(
model.attributes,
(fields, attr, key) => {
if (EXCLUDE_FIELDS.includes(key)) return fields;
const fieldPath = prefix ? `${prefix}.${key}` : key;
fields.push(fieldPath);
if (attr.type === 'component') {
const compoFields = getNestedFieldsWithIntermediate(components[attr.component], {
nestingLevel: nestingLevel - 1,
prefix: fieldPath,
components,
});
fields.push(...compoFields);
}
return fields;
},
[]
);
};
/**
* Creates an array of permissions with the "fields" attribute filled
* @param {array} actions array of actions
* @param {object} options
* @param {number} options.nestingLevel level of nesting
* @param {array} options.fieldsNullFor actionIds where the fields should be null
* @param {array} options.restrictedSubjects subjectsId to ignore
* @returns {array<permissions>}
*/
const getPermissionsWithNestedFields = (
actions,
{ nestingLevel, fieldsNullFor = [], restrictedSubjects = [] } = {}
) =>
actions.reduce((perms, action) => {
action.subjects
.filter(subject => !restrictedSubjects.includes(subject))
.forEach(contentTypeUid => {
const fields = fieldsNullFor.includes(action.actionId)
? null
: getNestedFields(strapi.contentTypes[contentTypeUid], {
components: strapi.components,
nestingLevel,
});
perms.push({
action: action.actionId,
subject: contentTypeUid,
fields,
conditions: [],
});
});
return perms;
}, []);
/**
* Cleans fields of permissions (add required ones, remove the non-existing anymore ones)
* @param {object} permissions array of existing permissions in db
* @param {object} options
* @param {number} options.nestingLevel level of nesting
* @param {array} options.fieldsNullFor actionIds where the fields should be null
* @returns {array<permissions>}
*/
const cleanPermissionFields = (permissions, { nestingLevel, fieldsNullFor = [] }) =>
permissions.map(perm => {
let newFields = perm.fields;
if (fieldsNullFor.includes(perm.actionId)) {
newFields = null;
} else if (perm.subject && strapi.contentTypes[perm.subject]) {
const possiblefields = getNestedFieldsWithIntermediate(strapi.contentTypes[perm.subject], {
components: strapi.components,
nestingLevel,
});
const requiredFields = getNestedFields(strapi.contentTypes[perm.subject], {
components: strapi.components,
requiredOnly: true,
nestingLevel,
existingFields: perm.fields,
});
const badNestedFields = _.uniq([
..._.intersection(perm.fields, possiblefields),
...requiredFields,
]);
newFields = badNestedFields.filter(
field => !badNestedFields.some(fp.startsWith(`${field}.`))
);
}
return { ...perm, fields: newFields };
}, []);
module.exports = {
getNestedFields,
getPermissionsWithNestedFields,
cleanPermissionFields,
getNestedFieldsWithIntermediate,
};
| JavaScript | 0 | @@ -4782,18 +4782,16 @@
m.action
-Id
)) %7B%0A
|
926eb91d597af11883b16f6b6035f0290da6bd24 | add native events in TextField | packages/web/src/components/basic/TextField.js | packages/web/src/components/basic/TextField.js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import {
addComponent,
removeComponent,
watchComponent,
updateQuery,
} from '@appbaseio/reactivecore/lib/actions';
import {
debounce,
checkValueChange,
checkPropChange,
getClassName,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';
import Input from '../../styles/Input';
import Title from '../../styles/Title';
class TextField extends Component {
constructor(props) {
super(props);
this.type = 'match';
this.state = {
currentValue: '',
};
this.locked = false;
}
componentWillMount() {
this.props.addComponent(this.props.componentId);
this.setReact(this.props);
if (this.props.selectedValue) {
this.setValue(this.props.selectedValue, true);
} else if (this.props.defaultSelected) {
this.setValue(this.props.defaultSelected, true);
}
}
componentWillReceiveProps(nextProps) {
checkPropChange(this.props.react, nextProps.react, () => {
this.setReact(nextProps);
});
checkPropChange(this.props.dataField, nextProps.dataField, () => {
this.updateQuery(this.state.currentValue, nextProps);
});
if (this.props.defaultSelected !== nextProps.defaultSelected) {
this.setValue(nextProps.defaultSelected, true, nextProps);
} else if (
// since, selectedValue will be updated when currentValue changes,
// we must only check for the changes introduced by
// clear action from SelectedFilters component in which case,
// the currentValue will never match the updated selectedValue
this.props.selectedValue !== nextProps.selectedValue
&& this.state.currentValue !== nextProps.selectedValue
) {
this.setValue(nextProps.selectedValue || '', true, nextProps);
}
}
componentWillUnmount() {
this.props.removeComponent(this.props.componentId);
}
setReact(props) {
if (props.react) {
props.watchComponent(props.componentId, props.react);
}
}
defaultQuery = (value, props) => {
if (value && value.trim() !== '') {
return {
[this.type]: {
[props.dataField]: value,
},
};
}
return null;
}
handleTextChange = debounce((value) => {
this.updateQuery(value, this.props);
}, this.props.debounce);
setValue = (value, isDefaultValue = false, props = this.props) => {
// ignore state updates when component is locked
if (props.beforeValueChange && this.locked) {
return;
}
this.locked = true;
const performUpdate = () => {
this.setState({
currentValue: value,
}, () => {
if (isDefaultValue) {
this.updateQuery(value, props);
} else {
// debounce for handling text while typing
this.handleTextChange(value);
}
this.locked = false;
});
};
checkValueChange(
props.componentId,
value,
props.beforeValueChange,
props.onValueChange,
performUpdate,
);
};
updateQuery = (value, props) => {
const query = props.customQuery || this.defaultQuery;
const { onQueryChange = null } = props;
props.updateQuery({
componentId: props.componentId,
query: query(value, props),
value,
label: props.filterLabel,
showFilter: props.showFilter,
onQueryChange,
URLParams: props.URLParams,
});
};
handleChange = (e) => {
this.setValue(e.target.value);
};
render() {
return (
<div style={this.props.style} className={this.props.className}>
{this.props.title && <Title className={getClassName(this.props.innerClass, 'title') || null}>{this.props.title}</Title>}
<Input
type="text"
className={getClassName(this.props.innerClass, 'input') || null}
placeholder={this.props.placeholder}
onChange={this.handleChange}
value={this.state.currentValue}
/>
</div>
);
}
}
TextField.propTypes = {
addComponent: types.funcRequired,
componentId: types.stringRequired,
defaultSelected: types.string,
react: types.react,
removeComponent: types.funcRequired,
dataField: types.stringRequired,
title: types.title,
beforeValueChange: types.func,
onValueChange: types.func,
customQuery: types.func,
onQueryChange: types.func,
updateQuery: types.funcRequired,
placeholder: types.string,
selectedValue: types.selectedValue,
filterLabel: types.string,
URLParams: types.boolRequired,
showFilter: types.bool,
style: types.style,
className: types.string,
innerClass: types.style,
debounce: types.number,
};
TextField.defaultProps = {
placeholder: 'Search',
URLParams: false,
showFilter: true,
style: {},
className: null,
debounce: 0,
};
const mapStateToProps = (state, props) => ({
selectedValue: (state.selectedValues[props.componentId]
&& state.selectedValues[props.componentId].value) || null,
});
const mapDispatchtoProps = dispatch => ({
addComponent: component => dispatch(addComponent(component)),
removeComponent: component => dispatch(removeComponent(component)),
watchComponent: (component, react) => dispatch(watchComponent(component, react)),
updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
});
export default connect(mapStateToProps, mapDispatchtoProps)(TextField);
| JavaScript | 0.000002 | @@ -3725,16 +3725,232 @@
tValue%7D%0A
+%09%09%09%09%09onBlur=%7Bthis.props.onBlur%7D%0A%09%09%09%09%09onFocus=%7Bthis.props.onFocus%7D%0A%09%09%09%09%09onKeyPress=%7Bthis.props.onKeyPress%7D%0A%09%09%09%09%09onKeyDown=%7Bthis.props.onKeyDown%7D%0A%09%09%09%09%09onKeyUp=%7Bthis.props.onKeyUp%7D%0A%09%09%09%09%09autoFocus=%7Bthis.props.autoFocus%7D%0A
%09%09%09%09/%3E%0A%09
@@ -4606,16 +4606,154 @@
number,%0A
+%09onBlur: types.func,%0A%09onFocus: types.func,%0A%09onKeyPress: types.func,%0A%09onKeyDown: types.func,%0A%09onKeyUp: types.func,%0A%09autoFocus: types.bool,%0A
%7D;%0A%0AText
|
086828956101fb7489b5f9b93dcd9a84c5e1d4bf | Use fixed size arrays | packages/most-buffer/src/buffer-sink.js | packages/most-buffer/src/buffer-sink.js | class BufferSink {
constructor(count, sink) {
this.active = true;
this.sink = sink;
this.count = count;
this.buffer = [];
}
event(time, value) {
if (!this.active) {
return;
}
// Buffering the new value
this.buffer.push(value);
// If the buffer has a limit and is full, let's emit it
if (this.count && this.buffer.length === this.count) {
this.sink.event(time, this.buffer);
this.buffer = [];
}
}
error(time, error) {
// Forward errors
this.sink.error(time, error);
}
end(time, value) {
if (!this.active) {
return;
}
// Sending what's left in the buffer
this.sink.event(time, this.buffer);
this.buffer = [];
// And ending everything
this.active = false;
this.sink.end(time, value);
}
}
module.exports = BufferSink;
| JavaScript | 0.000001 | @@ -125,26 +125,88 @@
is.buffer =
-%5B%5D
+count === undefined ? %5B%5D : new Array(count);%0A this.length = 0
;%0A %7D%0A%0A eve
@@ -318,20 +318,31 @@
ffer
-.push(
+%5Bthis.length++%5D =
value
-)
;%0A%0A
@@ -417,29 +417,8 @@
his.
-count && this.buffer.
leng
@@ -444,37 +444,29 @@
%7B%0A
-this.sink.event(time,
+const value =
this.bu
@@ -465,26 +465,26 @@
this.buffer
-)
;
+%0A
%0A this.
@@ -492,18 +492,96 @@
uffer =
-%5B%5D
+new Array(this.count);%0A this.length = 0;%0A this.sink.event(time, value)
;%0A %7D%0A
@@ -811,20 +811,65 @@
his.
-buffer);%0A
+length %3C this.count ? this.buffer.slice(0, this.length) :
thi
@@ -880,13 +880,9 @@
ffer
- = %5B%5D
+)
;%0A%0A
|
6edc10a91fe9256172685be7eb9b5b41322fb6ca | Add reflow option and encode predicate support to ChangeSet. | packages/vega-dataflow/src/ChangeSet.js | packages/vega-dataflow/src/ChangeSet.js | import {ingest} from './Tuple';
import {array, constant, isFunction} from 'vega-util';
export function isChangeSet(v) {
return v && v.constructor === changeset;
}
export default function changeset() {
var add = [], // insert tuples
rem = [], // remove tuples
mod = [], // modify tuples
remp = [], // remove by predicate
modp = []; // modify by predicate
return {
constructor: changeset,
insert: function(t) {
var d = array(t), i = 0, n = d.length;
for (; i<n; ++i) add.push(d[i]);
return this;
},
remove: function(t) {
var a = isFunction(t) ? remp : rem,
d = array(t), i = 0, n = d.length;
for (; i<n; ++i) a.push(d[i]);
return this;
},
modify: function(t, field, value) {
var m = {field: field, value: constant(value)};
if (isFunction(t)) m.filter = t, modp.push(m);
else m.tuple = t, mod.push(m);
return this;
},
encode: function(t, set) {
mod.push({tuple: t, field: set});
return this;
},
pulse: function(pulse, tuples) {
var out, i, n, m, f, t, id;
// add
for (i=0, n=add.length; i<n; ++i) {
pulse.add.push(ingest(add[i]));
}
// remove
for (out={}, i=0, n=rem.length; i<n; ++i) {
t = rem[i];
out[t._id] = t;
}
for (i=0, n=remp.length; i<n; ++i) {
f = remp[i];
tuples.forEach(function(t) {
if (f(t)) out[t._id] = t;
});
}
for (id in out) pulse.rem.push(out[id]);
// modify
function modify(t, f, v) {
if (v) t[f] = v(t); else pulse.encode = f;
out[t._id] = t;
}
for (out={}, i=0, n=mod.length; i<n; ++i) {
m = mod[i];
modify(m.tuple, m.field, m.value);
pulse.modifies(m.field);
}
for (i=0, n=modp.length; i<n; ++i) {
m = modp[i];
f = m.filter;
tuples.forEach(function(t) {
if (f(t)) modify(t, m.field, m.value);
});
pulse.modifies(m.field);
}
for (id in out) pulse.mod.push(out[id]);
return pulse;
}
};
}
| JavaScript | 0 | @@ -355,17 +355,17 @@
odp = %5B%5D
-;
+,
// modi
@@ -379,16 +379,38 @@
redicate
+%0A reflow = false;
%0A%0A retu
@@ -1005,40 +1005,178 @@
-mod.push(%7Btuple: t, field: set%7D)
+if (isFunction(t)) modp.push(%7Bfilter: t, field: set%7D);%0A else mod.push(%7Btuple: t, field: set%7D);%0A return this;%0A %7D,%0A reflow: function() %7B%0A reflow = true
;%0A
@@ -1797,32 +1797,45 @@
ode = f;%0A
+ if (!reflow)
out%5Bt._id%5D = t;
@@ -2214,32 +2214,238 @@
field);%0A %7D%0A
+%0A // reflow?%0A if (reflow) %7B%0A pulse.mod = rem.length %7C%7C remp.length%0A ? tuples.filter(function(t) %7B return out.hasOwnProperty(t._id); %7D)%0A : tuples.slice();%0A %7D else %7B%0A
for (id in
@@ -2466,32 +2466,40 @@
d.push(out%5Bid%5D);
+%0A %7D
%0A%0A return p
|
f72e3bb75441c045d106a31eb4a64e101acc912b | Remove angularjs CDN | pipeline/app/assets/javascripts/application.js | pipeline/app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require angular-rails-templates
//= require_tree ../templates
//= require_tree .
| JavaScript | 0.000007 | @@ -612,16 +612,36 @@
ery_ujs%0A
+//= require angular%0A
//= requ
|
188693f80cff1782b74325683d2a12502f8cc32e | Add angular and angular-route requires | pipeline/app/assets/javascripts/application.js | pipeline/app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or any plugin's vendor/assets/javascripts directory can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// Read Sprockets README (https://github.com/rails/sprockets#sprockets-directives) for details
// about supported directives.
//
//= require jquery
//= require jquery_ujs
//= require_tree .
| JavaScript | 0.000003 | @@ -612,16 +612,62 @@
ery_ujs%0A
+//= require angular%0A//= require angular-route%0A
//= requ
|
3b7f030ca5cd743b74a5cfbd3bf4a161f82a4892 | Remove unused block from search reducer | app/state/reducers/ui/searchReducer.js | app/state/reducers/ui/searchReducer.js | import types from 'constants/ActionTypes';
import Immutable from 'seamless-immutable';
import { pickSupportedFilters } from 'utils/searchUtils';
import { getDuration, getEndTimeString, getStartTimeString } from 'utils/timeUtils';
const initialState = Immutable({
filters: {
date: '',
people: '',
purpose: '',
municipality: '',
search: '',
distance: '',
duration: 0,
start: '',
end: '',
useTimeRange: false,
},
page: 1,
position: null,
resultCount: 0,
results: [],
searchDone: false,
showMap: false,
unitId: null,
});
function searchReducer(state = initialState, action) {
switch (action.type) {
case types.API.SEARCH_RESULTS_GET_SUCCESS: {
const results = Object.keys(action.payload.entities.resources || {});
const paginatedResources = Object.values(action.payload.entities.paginatedResources || {});
const resultCount = paginatedResources.length ? paginatedResources[0].count : 0;
return state.merge({
resultCount,
results,
searchDone: true,
unitId: null,
});
}
case types.API.SORT_RESULTS_GET_SUCCESS: {
const results = Object.keys(action.payload.entities.resources || {});
const paginatedResources = Object.values(action.payload.entities.paginatedResources || {});
const resultCount = paginatedResources.length ? paginatedResources[0].count : 0;
return state.merge({
resultCount,
results,
searchDone: true,
unitId: null,
});
}
case types.UI.CHANGE_SEARCH_FILTERS: {
const filters = pickSupportedFilters(action.payload);
return state.merge({ filters }, { deep: true });
}
case types.UI.CLEAR_SEARCH_FILTERS: {
const { results, searchDone } = state;
return initialState.merge({ results, searchDone });
}
case types.UI.ENABLE_GEOPOSITION_SUCCESS: {
const position = {
lat: action.payload.coords.latitude,
lon: action.payload.coords.longitude,
};
return state.merge({ position });
}
case types.UI.ENABLE_GEOPOSITION_ERROR:
case types.UI.DISABLE_GEOPOSITION: {
const position = null;
return state.merge({ position });
}
case types.UI.DISABLE_TIME_RANGE: {
const filters = pickSupportedFilters({ useTimeRange: false });
return state.merge({ filters }, { deep: true });
}
case types.UI.ENABLE_TIME_RANGE: {
const duration = getDuration(Number(state.filters.duration));
const end = getEndTimeString(state.filters.end);
const start = getStartTimeString(state.filters.start);
const useTimeRange = true;
const filters = pickSupportedFilters({
duration, end, start, useTimeRange
});
return state.merge({ filters }, { deep: true });
}
case types.UI.TOGGLE_SEARCH_SHOW_MAP: {
return state.merge({ showMap: !state.showMap });
}
case types.UI.SELECT_SEARCH_RESULTS_UNIT: {
return state.merge({ unitId: action.payload });
}
case types.UI.SEARCH_MAP_CLICK: {
return state.merge({ unitId: null });
}
default: {
return state;
}
}
}
export default searchReducer;
| JavaScript | 0.000001 | @@ -1096,446 +1096,8 @@
%7D%0A%0A
- case types.API.SORT_RESULTS_GET_SUCCESS: %7B%0A const results = Object.keys(action.payload.entities.resources %7C%7C %7B%7D);%0A const paginatedResources = Object.values(action.payload.entities.paginatedResources %7C%7C %7B%7D);%0A const resultCount = paginatedResources.length ? paginatedResources%5B0%5D.count : 0;%0A return state.merge(%7B%0A resultCount,%0A results,%0A searchDone: true,%0A unitId: null,%0A %7D);%0A %7D%0A%0A
|
9c96464ebda4719ff1cf31146cf1fdd795643c60 | Fix first favorite fail bug | app/views/_detail/detail.controller.js | app/views/_detail/detail.controller.js | /**
* Detail controller
*/
(function () {
'use strict';
angular
.module( 'com.missofis.ontheair' )
.controller( 'DetailCtrl', DetailCtrl );
DetailCtrl.$inject = [ '$log', 'TMDbTV', '$routeParams', 'OnTheAirFirebaseDatabase', 'OnTheAirUtils', '$scope', '$mdDialog', '$mdToast', '$location', '$rootScope', '_show', '$filter' ];
/**
* Detail controller
*/
function DetailCtrl( $log, TMDbTV, $routeParams, OnTheAirFirebaseDatabase, OnTheAirUtils, $scope, $mdDialog, $mdToast, $location, $rootScope, _show, $filter ) {
var vm = this;
/*
----------------------------------------------------------------
Initiate public scope variables
----------------------------------------------------------------
*/
// controller bindables
vm.show = null;
vm.appState = null;
vm.favorited = false;
vm.videoVisible = false;
vm.video = null;
vm.youtubePlayer = null;
vm.pageLoading = true;
// controller api
vm.getShow = _getShow;
vm.getVideos = _getVideos;
vm.toggleFavorite = _toggleFavorite;
vm.toggleVideo = _toggleVideo;
// initialize controller
_init();
/*
----------------------------------------------------------------
Private API
----------------------------------------------------------------
*/
// get show
function _getShow() {
vm.show = _show; // resolved as _show at routing state, TMDbTV.get( { id: $routeParams.showId } );
}
// get show videos
function _getVideos() {
TMDbTV.get( { id: $routeParams.showId, endpoint: 'videos' } )
.$promise
.then( function( response ) {
vm.video = $filter( 'filter' )( response.results, 'Youtube' )[0];
vm.pageLoading = false;
} );
}
// toggle favorite
function _toggleFavorite() {
if( !vm.appState.user ) {
$mdDialog
.show( $mdDialog.confirm( {
title: 'Uppsiee!',
textContent: 'You should "login" to favorite content.',
ok: 'Login',
cancel: 'no thanks'
} ) )
.then( function() {
$location.path( '/welcome' );
}, function() {
$mdToast.showSimple( 'Maybe later?' );
} );
return;
}
if( vm.favorited ) {
OnTheAirFirebaseDatabase
.unfavorite( vm.appState.user.uid, $routeParams.showId )
.then( function() {
delete vm.appState.user_favorites[ $routeParams.showId ];
$scope.$apply( function() {
vm.favorited = false;
} );
$rootScope.$apply();
} );
}
else {
OnTheAirFirebaseDatabase
.favorite( vm.appState.user.uid, $routeParams.showId, vm.show.name )
.then( function() {
vm.appState.user_favorites[ $routeParams.showId ] = vm.show.name;
$scope.$apply( function() {
vm.favorited = true;
} );
$rootScope.$apply();
} );
}
}
// toggle video
function _toggleVideo() {
if( vm.videoVisible ) {
vm.youtubePlayer.stopVideo();
vm.videoVisible = false;
}
else {
// vm.youtubePlayer.playVideo();
vm.videoVisible = true;
}
}
// controller initialize
function _init() {
$log.info( '$$____ :: CONTROLLER INITIALIZE', 'DetailCtrl' );
vm.appState = OnTheAirUtils.getAppState();
$scope.$watchCollection( 'vm.appState.user_favorites', function( newVal, oldVal ) {
if( false === newVal && false === oldVal ) {
// skip initial $watch visit
return;
}
else if( newVal ) {
vm.favorited = vm.appState.user_favorites[ $routeParams.showId ];
}
else {
vm.favorited = false;
}
} );
vm.getShow();
vm.getVideos();
}
}
})(); | JavaScript | 0.000001 | @@ -2566,24 +2566,264 @@
unction() %7B%0A
+%09%09%09%09%09%09// todo :: check for another solution (initial app set is false, but service returns null. false set needed for $watchCollection below)%0A%09%09%09%09%09%09if( null === vm.appState.user_favorites ) %7B%0A%09%09%09%09%09%09%09vm.appState.user_favorites = %7B%7D;%0A%09%09%09%09%09%09%7D%0A
%09%09%09%09%09%09vm.app
|
85c9fa28b12aa5674455d695195514739e03b898 | save flickity-object for further use | Flickity/Kwc/Slider/Component.defer.js | Flickity/Kwc/Slider/Component.defer.js | "use strict";
var $ = require('jQuery');
var onReady = require('kwf/on-ready');
var flickity = require('flickity');
onReady.onRender('.kwcClass', function(el) {
var config = el.data('config');
var elements = el.find('.kwcClass__listItem');
elements.first().css('visibility', 'visible');
if (config['lazyImages']) {
for(var i=0; i <= parseInt(config['lazyImages']); i++) {
if (i > parseInt(elements.length/2)) break;
elements.eq(i).css('visibility', 'visible');
elements.eq(elements.length - i).css('visibility', 'visible');
}
}
var flkty = new flickity(el[0], config);
flkty.on( 'cellSelect', function() {
if ((flkty.selectedIndex + config['lazyImages']) <= (flkty.cells.length - 1) &&
elements.eq(flkty.selectedIndex + config['lazyImages']).css('visibility') != 'visible') {
elements.eq(flkty.selectedIndex + config['lazyImages']).css('visibility', 'visible');
} else if ((flkty.selectedIndex - config['lazyImages']) >= 0 &&
elements.eq(flkty.selectedIndex - config['lazyImages']).css('visibility') != 'visible') {
elements.eq(flkty.selectedIndex - config['lazyImages']).css('visibility', 'visible');
}
onReady.callOnContentReady(el, { action: 'show' });
});
});
| JavaScript | 0 | @@ -639,16 +639,45 @@
config);
+%0A el.data('flkty', flkty);
%0A%0A fl
|
4d8eeba08b566946f4d1e253041013e03340829e | test viewport | application/static/js/image_capture.js | application/static/js/image_capture.js | var page = require('webpage').create(),
system = require('system');
if (system.args.length === 1) {
console.log('Pass arg when invoking script');
phantom.exit();
}
else{
title = system.args[1];
console.log(title);
page.open('http://192.241.148.248/imggen/index.php/imggen/'+title, function ( status ) {
if (status !== 'success') {
console.log('Unable to load the address!');
phantom.exit();
} else {
window.setTimeout(function () {
//page.clipRect = { top: 0, left: 10, width: 450, height: 250 };
page.viewportSize = { top: 0, left: 10, width: 450, height:250 };
page.render("../../image_captures/"+title+".png");
phantom.exit();
}, 200);
}
});
} | JavaScript | 0.000001 | @@ -476,18 +476,16 @@
%09
-//
page.cli
@@ -545,24 +545,26 @@
;%0A%09%09
+//
page.viewpor
|
1a72d2de01d288c8341f436a9d7da245379846dd | Fix lint | packages/m-types/src/__tests__/Pointer.test.js | packages/m-types/src/__tests__/Pointer.test.js | // @flow
import Composite from '../Composite';
import Primitive from '../Primitive';
import Pointer from '../Pointer';
const string = new Primitive('string', {
isValid: value => typeof value === 'string',
coerce: String,
});
const CRDT = { import: data => data };
const Product = new Composite('Product', { CRDT });
const Player = new Composite('Player', { CRDT });
describe('Pointer', () => {
it('works', () => {
const pointer = new Pointer(string, Product);
expect(pointer.name).toBe('pointer');
expect(pointer.subtype).toBe(string);
expect(pointer.to).toBe(Product);
});
it('dehydrates using string coercion', () => {
const object = { toString: () => 'string-coerced' };
const pointer = new Pointer(string, Product);
expect(pointer.dehydrate(object)).toBe(object.toString());
});
it('validates using the subtype', () => {
const pointer = new Pointer(string, Product);
expect(pointer.isValid('abc123')).toBe(true);
expect(pointer.isValid(5)).toBe(false);
expect(pointer.isValid(null)).toBe(false);
expect(pointer.isValid([])).toBe(false);
});
it('dehydrates to the same value', () => {
const pointer = new Pointer(string, Product);
expect(pointer.dehydrate('value')).toBe('value');
expect(pointer.dehydrate('1234')).toBe('1234');
});
it('hydrates using the derivation subtype', () => {
const pointer = new Pointer(string, Product);
const wat = '%^&*(){GuINcN}';
expect(pointer.hydrate('string')).toBe('string');
expect(pointer.hydrate('12345')).toBe('12345');
expect(pointer.hydrate(wat)).toBe(wat);
});
});
| JavaScript | 0.000002 | @@ -318,58 +318,8 @@
%7D);
-%0Aconst Player = new Composite('Player', %7B CRDT %7D);
%0A%0Ade
|
2b059f6b30d8222c447ef038a27786c93935e75b | clean queries for rison in prod, warn in dev | packages/mwp-store/src/browser/fetchQueries.js | packages/mwp-store/src/browser/fetchQueries.js | import JSCookie from 'js-cookie';
import rison from 'rison';
import { setClickCookie } from 'mwp-tracking-plugin/lib/util/clickState';
import { parseQueryResponse, getAuthedQueryFilter } from '../util/fetchUtils';
export const CSRF_HEADER = 'x-csrf-jwt';
export const CSRF_HEADER_COOKIE = 'x-csrf-jwt-header';
/**
* that the request will have the required OAuth and CSRF credentials and constructs
* the `fetch` call arguments based on the request method. It also records the
* CSRF header value in a cookie for use as a CSRF header in future fetches.
*
* @param {String} apiUrl the general-purpose endpoint for API calls to the
* application server
* @param {Array} queries the queries to send - must all use the same `method`
* @param {Object} meta additional characteristics of the request, e.g.
* click tracking data
* @return {Object} { url, config } arguments for a fetch call
*/
export const getFetchArgs = (apiUrl, queries, meta) => {
if (process.env.NODE_ENV !== 'production') {
// basic query validation for dev. This block will be stripped out by
// minification in prod bundle.
try {
rison.encode_array(queries);
} catch (err) {
console.error(err);
console.error(
'Problem encoding queries',
'- please ensure that there are no undefined params',
JSON.stringify(queries, null, 2)
);
}
}
const headers = {};
const method = ((queries[0].meta || {}).method || 'GET') // fallback to 'get'
.toUpperCase(); // must be upper case - requests can fail silently otherwise
const hasBody = method === 'POST' || method === 'PATCH';
const isFormData = queries[0].params instanceof FormData;
const isDelete = method === 'DELETE';
const searchParams = new URLSearchParams();
searchParams.append('queries', rison.encode_array(queries));
if (meta) {
const {
clickTracking,
onSuccess, // eslint-disable-line no-unused-vars
onError, // eslint-disable-line no-unused-vars
promise, // eslint-disable-line no-unused-vars
request, // eslint-disable-line no-unused-vars
...metadata
} = meta;
if (clickTracking) {
setClickCookie(clickTracking);
}
// send other metadata in searchParams
const encodedMetadata = metadata && rison.encode_object(metadata);
if (encodedMetadata) {
// send other metadata in searchParams
searchParams.append('metadata', encodedMetadata);
}
}
if (!isFormData) {
// need to manually specify content-type for any non-multipart request
headers['content-type'] = hasBody
? 'application/x-www-form-urlencoded'
: 'application/json';
}
if (hasBody || isDelete) {
headers[CSRF_HEADER] = JSCookie.get(CSRF_HEADER_COOKIE);
}
const config = {
method,
headers,
credentials: 'same-origin', // allow response to set-cookies
};
if (hasBody) {
config.body = isFormData ? queries[0].params : searchParams.toString();
}
const useQueryString = isFormData || !hasBody;
const url = useQueryString ? `${apiUrl}?${searchParams}` : apiUrl;
return {
url,
config,
};
};
const _fetchQueryResponse = (apiUrl, queries, meta) => {
if (queries.length === 0) {
// no queries => no responses (no need to fetch)
return Promise.resolve({ responses: [] });
}
const { url, config } = getFetchArgs(apiUrl, queries, meta);
return fetch(url, config)
.then(queryResponse => queryResponse.json())
.catch(err => {
console.error(
JSON.stringify({
err: err.stack,
message: 'App server API fetch error',
context: config,
})
);
throw err; // handle the error upstream
});
};
/**
* Wrapper around `fetch` to send an array of queries to the server and organize
* the responses.
*
* **IMPORTANT**: This function should _only_ be called from the browser. The
* server should never need to call itself over HTTP
*
* @param {String} apiUrl the general-purpose endpoint for API calls to the
* application server
* @param {Array} queries the queries to send - must all use the same `method`
* @param {Object} meta additional characteristics of the request, e.g.
* click tracking data
* @return {Promise} resolves with a `{queries, responses}` object
*/
const fetchQueries = (apiUrl, member) => (queries, meta) => {
if (
typeof window === 'undefined' &&
typeof test === 'undefined' // not in browser // not in testing env (global set by Jest)
) {
throw new Error('fetchQueries was called on server - cannot continue');
}
const authedQueries = getAuthedQueryFilter(member);
const validQueries = queries.filter(authedQueries);
return _fetchQueryResponse(
apiUrl,
validQueries,
meta
).then(queryResponse => ({
...parseQueryResponse(validQueries)(queryResponse),
}));
};
export default fetchQueries;
| JavaScript | 0 | @@ -357,18 +357,8 @@
red
-OAuth and
CSRF
@@ -385,16 +385,16 @@
structs%0A
+
* the %60
@@ -949,158 +949,727 @@
%7B%0A%09
-if (process.env.NODE_ENV !== 'production') %7B%0A%09%09// basic query validation for dev. This block will be stripped out by%0A%09%09// minification in prod bundle.
+// rison serialization fails for unserializable data, including params with%0A%09// %60undefined%60 values. This if/else will log an error in the browser in dev%0A%09// in order to catch mistakes, and force-clean the data in prod to avoid%0A%09// client app crashes. In many cases, %60undefined%60 params will not result in%0A%09// invalid return values, but they should be cleaned up to avoid uncertainty%0A%09//%0A%09// This if/else will be simplified to only contain the correct block in the%0A%09// production bundle%0A%09if (process.env.NODE_ENV === 'production') %7B%0A%09%09// quick-and-cheap object cleanup for serialization. This will remove%0A%09%09// undefined and unserializable values (e.g. functions)%0A%09%09queries = JSON.parse(JSON.stringify(queries));%0A%09%7D else %7B
%0A%09%09t
|
c31ff0eae7027df578625a6d2be6f4fb7bf2ab2a | fix auth | modules/users/client/controllers/authentication.client.controller.js | modules/users/client/controllers/authentication.client.controller.js | (function () {
'use strict';
angular
.module('users')
.controller('AuthenticationController', AuthenticationController);
AuthenticationController.$inject = ['$scope', '$state', '$http', '$location', '$window', 'Authentication', 'PasswordValidator', '$mdToast'];
function AuthenticationController($scope, $state, $http, $location, $window, Authentication, PasswordValidator, $mdToast) {
var vm = this;
vm.authentication = Authentication;
vm.getPopoverMsg = PasswordValidator.getPopoverMsg;
vm.signup = signup;
vm.signin = signin;
vm.callOauthProvider = callOauthProvider;
// Get an eventual error defined in the URL query string:
vm.error = $location.search().err;
// If user is signed in then redirect back home
if (vm.authentication.user) {
$location.path('/');
}
function signup(isValid) {
vm.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.userForm');
return false;
}
$http.post('/api/auth/signup', vm.credentials).success(function (response) {
// If successful we assign the response to the global user model
vm.authentication.user = response;
$mdToast.show(
$mdToast.simple()
.textContent("Welcome " + vm.authentication.user.displayName)
.hideDelay(3000)
);
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
vm.error = response.message;
$mdToast.show(
$mdToast.simple()
.textContent(vm.error)
.hideDelay(3000)
);
});
}
function signin(isValid) {
vm.error = null;
if (!isValid) {
$scope.$broadcast('show-errors-check-validity', 'vm.userForm');
return false;
}
$http.post('/api/auth/signin', vm.credentials).success(function (response) {
// If successful we assign the response to the global user model
vm.authentication.user = response;
$mdToast.show(
$mdToast.simple()
.textContent("Welcome " + vm.authentication.user.displayName)
.hideDelay(3000)
);
// And redirect to the previous or home page
$state.go($state.previous.state.name || 'home', $state.previous.params);
}).error(function (response) {
vm.error = response.message;
$mdToast.show(
$mdToast.simple()
.textContent(vm.error)
.hideDelay(3000)
);
});
}
// OAuth provider request
function callOauthProvider(url) {
if ($state.previous && $state.previous.href) {
url += '?redirect_to=' + encodeURIComponent($state.previous.href);
}
// Effectively call OAuth authentication route:
$window.location.href = url;
}
}
}());
| JavaScript | 0.002303 | @@ -1185,37 +1185,32 @@
m.authentication
-.user
= response;%0A
@@ -2084,21 +2084,16 @@
tication
-.user
= respo
|
a33ca11ff237781fe6d64ac2ed93825e001411ac | fix fix | redef/patron-client/src/frontend/components/work/fields/WorkSerie.js | redef/patron-client/src/frontend/components/work/fields/WorkSerie.js | import React, { PropTypes } from 'react'
import { injectIntl, intlShape, defineMessages } from 'react-intl'
import { Link } from 'react-router'
import MetaItem from '../../MetaItem'
import isEmpty from '../../../utils/emptyObject'
const WorkSerie = ({ workserie }) => {
if (!isEmpty(workserie)) {
return (
<MetaItem label={messages.labelWorkSerie} data-automation-id="work_work_serie">
<Link
data-automation-id="work_series_link"
to={`/search?query=series:%3A"${workserie.mainTitle}"`}>
{workserie.mainTitle}
</Link>
</MetaItem>
)
}
return null
}
WorkSerie.defaultProps = {
workserie: {}
}
WorkSerie.propTypes = {
workserie: PropTypes.object.isRequired,
intl: intlShape.isRequired
}
export const messages = defineMessages({
labelWorkSerie: {
id: 'WorkSerie.labelWorkSerie',
description: 'Label for work serie',
defaultMessage: 'A part of serie'
}
})
export default injectIntl(WorkSerie)
| JavaScript | 0.001033 | @@ -489,17 +489,16 @@
y=series
-:
%253A%22$%7Bwo
|
569f9e5cf0eb72762cf4cfa8d41e0053798b7cba | combine handlewrite functions | regulations/static/regulations/js/source/views/main/preamble-view.js | regulations/static/regulations/js/source/views/main/preamble-view.js | 'use strict';
var $ = require('jquery');
var _ = require('underscore');
var Backbone = require('backbone');
Backbone.$ = $;
var ChildView = require('./child-view');
var MainEvents = require('../../events/main-events');
var PreambleHeadView = require('../header/preamble-head-view');
var CommentView = require('../comment/comment-view');
var CommentIndexView = require('../comment/comment-index-view');
var CommentEvents = require('../../events/comment-events');
var PreambleView = ChildView.extend({
el: '#content-wrapper',
events: {
'click .activate-write': 'handleWriteLink'
},
initialize: function(options) {
this.options = options;
this.id = options.id;
this.url = 'preamble/' + this.id.split('-').join('/');
if (!options.render) {
this.render();
}
ChildView.prototype.initialize.apply(this, arguments);
this.listenTo(CommentEvents, 'read:proposal', this.handleRead);
this.listenTo(CommentEvents, 'comment:write', this.handleWriteEvent);
this.listenTo(MainEvents, 'paragraph:active', this.handleParagraphActive);
CommentEvents.trigger('comment:readTabOpen');
},
handleRead: function() {
this.$write.hide();
this.$read.show();
},
handleParagraphActive: function(id) {
// update current Section ID as active paragraph changes
this.currentSectionId = id;
},
handleWriteEvent: function() {
var $section = $('#' + this.currentSectionId);
this.write(
this.currentSectionId,
$section.find('.activate-write').data('label'),
$section
);
},
handleWriteLink: function(e) {
var $target = $(e.target);
this.write(
$target.data('section'),
$target.data('label'),
$target.closest('[data-permalink-section]')
);
CommentEvents.trigger('comment:writeTabOpen');
},
write: function(section, label, $parent) {
$parent = $parent.clone();
$parent.find('.activate-write').remove();
CommentEvents.trigger('comment:target', {
section: section,
label: label,
$parent: $parent
});
this.$read.hide();
this.$write.show();
},
render: function() {
ChildView.prototype.render.apply(this, arguments);
this.$read = this.$el.find('#preamble-read');
this.$write = this.$el.find('#preamble-write');
this.currentSectionId = this.$read.closest('section').attr('id');
this.docId = this.currentSectionId.split('-')[0];
this.preambleHeadView = new PreambleHeadView();
this.commentView = new CommentView({
el: this.$write.find('.comment-wrapper'),
section: this.section
});
this.commentIndex = new CommentIndexView({
el: this.$write.find('.comment-index'),
docId: this.docId
});
if (this.options.mode === 'write') {
var $parent = $('#' + this.options.section).find('[data-permalink-section]');
this.write(this.options.section, this.options.label, $parent);
} else {
this.handleRead();
}
},
remove: function() {
this.commentView.remove();
this.commentIndex.remove();
Backbone.View.prototype.remove.call(this);
}
});
module.exports = PreambleView;
| JavaScript | 0.000003 | @@ -576,20 +576,16 @@
dleWrite
-Link
'%0A %7D,%0A%0A
@@ -981,21 +981,16 @@
dleWrite
-Event
);%0A t
@@ -1352,21 +1352,16 @@
dleWrite
-Event
: functi
@@ -1363,24 +1363,25 @@
unction(
+e
) %7B%0A
var $sec
@@ -1376,216 +1376,65 @@
-var $section = $('#' + this.currentSectionId);%0A%0A this.write(%0A this.currentSectionId,%0A $section.find('.activate-write').data('label'),%0A $section%0A );%0A %7D,%0A%0A handleWriteLink: function
+// + Write a comment about section (link)%0A if
(e) %7B%0A
+
@@ -1460,24 +1460,26 @@
arget);%0A
+
+
this.write(%0A
@@ -1478,16 +1478,18 @@
.write(%0A
+
$t
@@ -1509,32 +1509,34 @@
ection'),%0A
+
+
$target.data('la
@@ -1538,24 +1538,26 @@
a('label'),%0A
+
$targe
@@ -1598,20 +1598,24 @@
%5D')%0A
+
);%0A%0A
+
Comm
@@ -1649,32 +1649,267 @@
writeTabOpen');%0A
+ %7D%0A // Write a comment tab%0A else %7B%0A var $section = $('#' + this.currentSectionId);%0A%0A this.write(%0A this.currentSectionId,%0A $section.find('.activate-write').data('label'),%0A $section%0A );%0A %7D%0A
%7D,%0A%0A write: f
@@ -2272,16 +2272,17 @@
ments);%0A
+%0A
this
@@ -2549,24 +2549,25 @@
HeadView();%0A
+%0A
this.com
@@ -2671,32 +2671,33 @@
section%0A %7D);%0A
+%0A
this.comment
|
b2bc8e4b64abbb700d4ac8cc740c9819d7583232 | add in missing border line on card filters accordion. | resources/frontend_client/app/home/components/AccordianItem.react.js | resources/frontend_client/app/home/components/AccordianItem.react.js | "use strict";
import React, { Component, PropTypes } from "react";
import Icon from "metabase/components/Icon.react";
export default class AccordianItem extends Component {
render() {
let { children, onClickFn, isOpen, itemId, title } = this.props;
return (
<div key={itemId}>
<div className="p2 text-grey-4 text-brand-hover" onClick={() => (onClickFn(itemId))}>
<span className="float-left">{title}</span>
<div className="text-right text-grey-2 text-brand-hover">
{ isOpen ?
<Icon name="chevronup" width={12} height={12}></Icon>
:
<Icon name="chevrondown" width={12} height={12}></Icon>
}
</div>
</div>
{ isOpen ?
<div className="articlewrap">
<div className="article">
{children}
</div>
</div>
:
null
}
</div>
);
}
}
| JavaScript | 0 | @@ -371,16 +371,30 @@
nd-hover
+ border-bottom
%22 onClic
@@ -936,19 +936,11 @@
me=%22
-articlewrap
+pt1
%22%3E%0A
|
bd6ce854419f250a8fae3cb8c413b1f93356bbc6 | Fix a typo which was causing requests with DateTime2 parameters to fail. | src/rpcrequest-payload.js | src/rpcrequest-payload.js | import { WritableTrackingBuffer } from './tracking-buffer/tracking-buffer';
import { writeToTrackingBuffer as writeAllHeaders } from './all-headers';
// const OPTION = {
// WITH_RECOMPILE: 0x01,
// NO_METADATA: 0x02,
// REUSE_METADATA: 0x04
// };
const STATUS = {
BY_REF_VALUE: 0x01,
DEFAULT_VALUE: 0x02
};
/*
s2.2.6.5
*/
export default class RpcRequestPayload {
constructor(request, txnDescriptor, options) {
this.request = request;
this.procedure = this.request.sqlTextOrProcedure;
const buffer = new WritableTrackingBuffer(500);
if (options.tdsVersion >= '7_2') {
const outstandingRequestCount = 1;
writeAllHeaders(buffer, txnDescriptor, outstandingRequestCount);
}
if (typeof this.procedure === 'string') {
buffer.writeUsVarchar(this.procedure);
} else {
buffer.writeUShort(0xFFFF);
buffer.writeUShort(this.procedure);
}
const optionFlags = 0;
buffer.writeUInt16LE(optionFlags);
const parameters = this.request.parameters;
for (let i = 0, len = parameters.length; i < len; i++) {
const parameter = parameters[i];
buffer.writeBVarchar('@' + parameter.name);
let statusFlags = 0;
if (parameter.output) {
statusFlags |= STATUS.BY_REF_VALUE;
}
buffer.writeUInt8(statusFlags);
const param = {
value: parameter.value
};
const type = parameter.type;
if ((type.id & 0x30) === 0x20) {
if (parameter.length) {
param.length = parameter.length;
} else if (type.resolveLength) {
param.length = type.resolveLength(parameter);
}
}
if (type.hasPrecision) {
if (parameter.precision) {
param.precision = parameter.precision;
} else if (type.resolvePrecision) {
param.precision = type.resolvePrecision(parameter);
}
}
if (type.hasScale) {
if (parameter.scale) {
param.scale = parameter.scale;
} else if (type.resolvePrecision) {
param.scale = type.resolveScale(parameter);
}
}
type.writeTypeInfo(buffer, param, options);
type.writeParameterData(buffer, param, options);
}
this.data = buffer.data;
}
toString(indent) {
indent || (indent = '');
return indent + ("RPC Request - " + this.procedure);
}
}
| JavaScript | 0 | @@ -2010,33 +2010,29 @@
type.resolve
-Precision
+Scale
) %7B%0A
|
948e099daf09a4ff812b4548cd941b94fcafefb8 | Fix slider glitch | dist/js/d3.slider.js | dist/js/d3.slider.js | /*
D3.js Slider
Inspired by jQuery UI Slider
Copyright (c) 2013, Bjorn Sandvik - http://blog.thematicmapping.org
BSD license: http://opensource.org/licenses/BSD-3-Clause
*/
d3.slider = function module() {
"use strict";
// Public variables width default settings
var min = 0,
max = 100,
step = 0.01,
axis = false,
margin = 50,
value,
scale;
// Private variables
var axisScale,
dispatch = d3.dispatch("slide", "slideend"),
formatPercent = d3.format(".2%"),
tickFormat = d3.format(".0"),
sliderLength;
var redraws = [];
function slider(selection) {
selection.each(function() {
// Create scale if not defined by user
if (!scale) {
scale = d3.scale.linear().domain([min, max]);
}
// Start value
value = value || scale.domain()[0];
var drag = d3.behavior.drag();
drag.on('dragend', function () {
dispatch.slideend(d3.event, value);
})
var div = d3.select(this)
.classed("d3-slider", true)
.call(drag);
var handle = div.append("a")
.classed("d3-slider-handle", true)
.attr("xlink:href", "#")
.attr('id', "handle-one")
.on("click", stopPropagation)
.call(drag);
redraws.push(function() {
var newPos = formatPercent(scale(stepValue(value)));
handle.style('left', newPos);
});
div.on("mousedown", onClickHorizontal);
handle.style("left", formatPercent(scale(value)));
drag.on("drag", onDragHorizontal);
sliderLength = parseInt(div.style("width"), 10);
if (axis) {
createAxis(div);
}
function createAxis(dom) {
// Create axis if not defined by user
if (typeof axis === "boolean") {
axis = d3.svg.axis()
.ticks(Math.round(sliderLength / 100))
.tickFormat(tickFormat)
.orient('bottom');
}
// Copy slider scale to move from percentages to pixels
axisScale = scale.copy().range([0, sliderLength]);
axis.scale(axisScale);
// Create SVG axis container
var svg = dom.append("svg")
.classed("d3-slider-axis d3-slider-axis-" + axis.orient(), true)
.on("click", stopPropagation);
var g = svg.append("g");
svg.style("margin-left", -margin + "px");
svg.attr({
width: sliderLength + margin * 2,
height: margin
});
if (axis.orient() === "top") {
svg.style("top", -margin + "px");
g.attr("transform", "translate(" + margin + "," + margin + ")");
} else { // bottom
g.attr("transform", "translate(" + margin + ",0)");
}
g.call(axis);
}
// Move slider handle on click/drag
function moveHandle(pos) {
var newValue = stepValue(scale.invert(pos / sliderLength)),
currentValue = value.length ? value[0]: value;
if (currentValue !== newValue) {
var oldPos = formatPercent(scale(stepValue(currentValue))),
newPos = formatPercent(scale(stepValue(newValue)));
dispatch.slide(d3.event.sourceEvent || d3.event, value = newValue);
handle.style("left", newPos);
}
}
// Calculate nearest step value
function stepValue(val) {
if (val === scale.domain()[0] || val === scale.domain()[1]) {
return val;
}
var valModStep = (val - scale.domain()[0]) % step,
alignValue = val - valModStep;
if (Math.abs(valModStep) * 2 >= step) {
alignValue += (valModStep > 0) ? step : -step;
}
return alignValue;
}
function onClickHorizontal() {
if (!value.length) {
moveHandle(d3.event.offsetX || d3.event.layerX);
}
}
function onDragHorizontal() {
moveHandle(Math.max(0, Math.min(sliderLength, d3.event.x)));
}
function stopPropagation() {
d3.event.stopPropagation();
}
});
}
// Getter/setter functions
slider.min = function(_) {
if (!arguments.length) return min;
min = _;
return slider;
};
slider.max = function(_) {
if (!arguments.length) return max;
max = _;
return slider;
};
slider.step = function(_) {
if (!arguments.length) return step;
step = _;
return slider;
};
slider.axis = function(_) {
if (!arguments.length) return axis;
axis = _;
return slider;
};
slider.margin = function(_) {
if (!arguments.length) return margin;
margin = _;
return slider;
};
slider.value = function(_) {
if (!arguments.length) return value;
value = _;
return slider;
};
slider.redraw = function() {
for (var i=0; i<redraws.length; i++) {
var redraw = redraws[i];
redraw();
}
}
slider.scale = function(_) {
if (!arguments.length) return scale;
scale = _;
return slider;
};
d3.rebind(slider, dispatch, "on");
return slider;
};
| JavaScript | 0.000001 | @@ -1504,17 +1504,13 @@
on(%22
-mousedown
+click
%22, o
|
23b4c4da8d12d6cf99f9603b0d3d317f9e0bc91d | Make getStringFromTypedArray more testable | Source/Core/getStringFromTypedArray.js | Source/Core/getStringFromTypedArray.js | /*global define*/
define([
'./defined',
'./DeveloperError'
], function(
defined,
DeveloperError) {
"use strict";
/*global TextDecoder*/
/**
* @private
*/
var getStringFromTypedArray = function(buffer, byteOffset, length) {
//>>includeStart('debug', pragmas.debug);
if (!defined(buffer)) {
throw new DeveloperError('buffer is required.');
}
if (!defined(byteOffset)) {
throw new DeveloperError('byteOffset is required.');
}
if (!defined(length)) {
throw new DeveloperError('length is required.');
}
//>>includeEnd('debug');
var view = new Uint8Array(buffer, byteOffset, length);
if (typeof TextDecoder !== 'undefined') {
var decoder = new TextDecoder('utf-8');
return decoder.decode(view);
}
return String.fromCharCode.apply(String, view);
};
return getStringFromTypedArray;
});
| JavaScript | 0.000059 | @@ -694,19 +694,46 @@
-var view =
+return getStringFromTypedArray.decode(
new
@@ -774,30 +774,94 @@
gth)
-;%0A%0A if (typeof
+);%0A %7D;%0A%0A // Exposed functions for testing%0A getStringFromTypedArray.decodeWith
Text
@@ -872,31 +872,27 @@
der
-!=
=
-'undefined') %7B%0A
+function(view) %7B%0A
@@ -939,28 +939,24 @@
');%0A
-
return decod
@@ -980,77 +980,387 @@
- %7D%0A%0A return String.fromCharCode.apply(String, view);%0A %7D;
+%7D;%0A%0A getStringFromTypedArray.decodeWithFromCharCode = function(view) %7B%0A return String.fromCharCode.apply(String, view);%0A %7D;%0A%0A if (typeof TextDecoder !== 'undefined') %7B%0A getStringFromTypedArray.decode = getStringFromTypedArray.decodeWithTextDecoder;%0A %7D else %7B%0A getStringFromTypedArray.decode = getStringFromTypedArray.decodeWithFromCharCode;%0A %7D
%0A%0A
|
19df4f7b1265405e4f2c6ae8705af5ceae7796d4 | enable title by default (#8750) | packages/react/src/components/Switch/Switch.js | packages/react/src/components/Switch/Switch.js | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
const { prefix } = settings;
const Switch = React.forwardRef(function Switch(props, tabRef) {
const {
className,
disabled,
index,
name,
onClick,
onKeyDown,
selected,
text,
...other
} = props;
const handleClick = (e) => {
e.preventDefault();
onClick({ index, name, text });
};
const handleKeyDown = (event) => {
const key = event.key || event.which;
onKeyDown({ index, name, text, key });
};
const classes = classNames(className, `${prefix}--content-switcher-btn`, {
[`${prefix}--content-switcher--selected`]: selected,
});
const commonProps = {
onClick: handleClick,
onKeyDown: handleKeyDown,
className: classes,
disabled,
};
return (
<button
type="button"
ref={tabRef}
role="tab"
tabIndex={selected ? '0' : '-1'}
aria-selected={selected}
{...other}
{...commonProps}>
<span className={`${prefix}--content-switcher__label`}>{text}</span>
</button>
);
});
Switch.displayName = 'Switch';
Switch.propTypes = {
/**
* Specify an optional className to be added to your Switch
*/
className: PropTypes.string,
/**
* Specify whether or not the Switch should be disabled
*/
disabled: PropTypes.bool,
/**
* The index of your Switch in your ContentSwitcher that is used for event handlers.
* Reserved for usage in ContentSwitcher
*/
index: PropTypes.number,
/**
* Provide the name of your Switch that is used for event handlers
*/
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* A handler that is invoked when a user clicks on the control.
* Reserved for usage in ContentSwitcher
*/
onClick: PropTypes.func,
/**
* A handler that is invoked on the key down event for the control.
* Reserved for usage in ContentSwitcher
*/
onKeyDown: PropTypes.func,
/**
* Whether your Switch is selected. Reserved for usage in ContentSwitcher
*/
selected: PropTypes.bool,
/**
* Provide the contents of your Switch
*/
text: PropTypes.string.isRequired,
};
Switch.defaultProps = {
selected: false,
text: 'Provide text',
onClick: () => {},
onKeyDown: () => {},
};
export default Switch;
| JavaScript | 0 | @@ -1298,15 +1298,44 @@
el%60%7D
-%3E%7Btext%7D
+ title=%7Btext%7D%3E%0A %7Btext%7D%0A
%3C/sp
|
0f3c89943d47691f70f2c62033b2d966b07cc1b1 | Add support for secondary colour overrides for `magazine-comment` and `magazinestandard` (#1526) | packages/styleguide/src/theme/theme-factory.js | packages/styleguide/src/theme/theme-factory.js | import sectionColours, { secondarySectionColours } from "../colours/section";
const sectionColourPicker = (
section = "default",
template = "mainstandard"
) => {
const config = {
indepth: {
...sectionColours,
...secondarySectionColours
},
magazinecomment: {
...sectionColours
},
magazinestandard: {
...sectionColours
},
maincomment: {
...sectionColours
},
mainstandard: {
...sectionColours
}
};
return config[template][section];
};
export default (section, template) => ({
sectionColour: sectionColourPicker(section, template)
});
| JavaScript | 0 | @@ -297,32 +297,66 @@
..sectionColours
+,%0A ...secondarySectionColours
%0A %7D,%0A maga
@@ -386,32 +386,66 @@
..sectionColours
+,%0A ...secondarySectionColours
%0A %7D,%0A main
|
f321f71408554e9443722b23c60e84b65092908f | disable dragging on maps | modules/mod_ginger_base/lib/js/map.js | modules/mod_ginger_base/lib/js/map.js |
$.widget( "ui.googlemap", {
_create: function() {
var me = this,
widgetElement = $(me.element),
id = widgetElement.attr('id'),
container = widgetElement,
locations = jQuery.parseJSON(widgetElement.data('locations')),
options,
map,
bounds = new google.maps.LatLngBounds(),
info = new google.maps.InfoWindow({maxWidth: 250}),
icon,
i,
mc,
mcOptions = {
styles: [
{
height: 28,
width: 28,
url: "/lib/images/cluster-default-small.svg"
},
{
height: 45,
width: 45,
url: "/lib/images/cluster-default.svg"
},
{
height: 54,
width: 54,
url: "/lib/images/cluster-default-large.svg"
}
],
zoomOnClick: false
},
markers = [];
me.id = id;
options = jQuery.parseJSON(widgetElement.data('mapoptions'));
if (!id) return false;
if (options.blackwhite == true) {
options.styles = [{
"stylers": [
{ "saturation": -100 },
{ "lightness": -8 },
{ "gamma": 1.18 }
]
}
];
delete options.blackwhite;
}
map = new google.maps.Map(document.getElementById(id), options);
me.map = map;
me.infowindow = null;
me.markers = markers;
// Show multiple markers with info windows
for (i = 0; i < locations.length; i++) {
icon = '/lib/images/marker-default.svg';
// Add marker
var marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i].lat, locations[i].lng),
icon: icon,
zotonic_id: parseInt(locations[i].id)
});
marker.addListener('click', function() {
var markerList = [];
markerList.push(this);
me.startShowInfoWindow(markerList);
});
bounds.extend(marker.position);
markers.push(marker);
}
mc = new MarkerClusterer(map, markers, mcOptions);
me.mc = mc;
google.maps.event.addListener(mc, "clusterclick", function(cluster) {
$.proxy(me.clusterClicked(cluster), me);
return false;
});
if (locations.length == 1) {
var zoomLevel = (!locations[0].zoom ? 15 : parseInt(locations[0].zoom));
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(zoomLevel);
});
}
map.fitBounds(bounds);
},
clusterClicked: function(cluster) {
var me = this,
markers = cluster.getMarkers(),
posCoordList = [],
markerList = [],
zoom = me.map.getZoom(),
clusterBounds = new google.maps.LatLngBounds();
$.each(markers, function(index, marker) {
clusterBounds.extend(marker.position);
posCoordList.push(marker.position.G + ', ' + marker.position.K);
markerList.push(marker);
});
posCoordList = me.unique(posCoordList);
if (posCoordList.length == 1 || zoom >= 21) {
me.startShowInfoWindow(markerList);
return false;
} else {
me.map.fitBounds(clusterBounds);
}
},
unique: function(list) {
var result = [];
$.each(list, function(i, e) {
if ($.inArray(e, result) == -1) result.push(e);
});
return result;
},
startShowInfoWindow: function(markerList) {
var me = this,
html = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse elementum elit felis, sit amet finibus risus scelerisque et. Pellentesque dignissim urna vel est lacinia, vel pulvinar ex laoreet. Vestibulum in mauris a nisl sodales placerat. Cras lobortis volutpat nisi vitae bibendum. Phasellus ac velit sit amet ligula sagittis aliquam. Sed id erat non nulla egestas porttitor. Mauris nulla sem, eleifend vel risus sed, sollicitudin imperdiet neque. Nunc aliquet, nulla nec porttitor sagittis, ante nunc dapibus sem, semper lobortis nulla nisi eu nisi. Curabitur egestas est pretium sodales convallis. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Sed non nisi sit amet massa pretium fringilla.Phasellus sed porttitor arcu. Suspendisse potenti. Aenean pharetra aliquet faucibus. Morbi placerat, ante maximus elementum pulvinar, enim turpis luctus massa, sed pellentesque ipsum nibh nec tellus. Aenean efficitur dui a magna posuere elementum. Vestibulum suscipit nisl mi, eget sagittis elit tempus ut. Vestibulum vel fermentum libero, a';
marker = markerList[0];
var ids = $.map(markerList, function(val, i) {
return val.zotonic_id;
});
z_event('map_infobox', {ids: ids, element: me.id});
},
showInfoWindow: function(zotonic_id, contentHTML) {
var me = this,
marker = me.getMarker(zotonic_id),
ibOptions = {
content: decodeURIComponent(contentHTML),
disableAutoPan: false,
maxWidth: 0,
pixelOffset: new google.maps.Size(-140, 0),
zIndex: null,
boxStyle: {
background: "red",
opacity: 0.75,
width: "280px",
height: "300px"
},
closeBoxMargin: "10px 2px 2px 2px",
closeBoxURL: "http://www.google.com/intl/en_us/mapfiles/close.gif",
infoBoxClearance: new google.maps.Size(1, 1),
isHidden: false,
pane: "floatPane",
enableEventPropagation: false
};
if (me.infowindow) me.infowindow.close();
me.infowindow = new InfoBox(ibOptions);
me.infowindow.open(me.map, marker);
},
getMarker: function(zotonic_id) {
var me = this,
marker;
$.each(me.markers, function(i, val) {
if (val.zotonic_id == zotonic_id) marker = val;
});
return marker;
}
});
| JavaScript | 0 | @@ -816,16 +816,45 @@
ions'));
+%0A%09%09options.draggable = false;
%0A%0A%09%09if (
|
741401f327e824adb501d48a4836a99ad9a71262 | Check whether a property in a form exists | content-scripts/helper.js | content-scripts/helper.js | function getFormElements(form) {
return Object.keys(form)
.filter(key => form[key] instanceof HTMLElement)
.map(key => form[key]);
}
function elementScore(element, regexMap) {
let score = 0;
for(let prop in regexMap) {
regexMap[prop].forEach(pair => {
let regex = pair[0],
reward = pair[1];
if(regex.test(element[prop]))
score += reward;
});
}
return score;
}
function getAllForms() {
return Array.from(document.forms).map(element => {
let inputs = formInputsObj(element, rules.inputs);
return Object.assign({ element }, inputs);
});
}
function getFormsByRegex(regexMap) {
return getAllForms()
.map(form => ({ form, 'score': elementScore(form.element, regexMap) }))
.filter(form => form.score >= 0)
.sort((a, b) => b.score - a.score)
.map(form => form.form)
}
function getDomain() {
return location.hostname;
}
function getCredentials(domain) {
return new Promise((resolve, reject) => {
chrome.runtime.sendMessage({ 'action': 'get', domain }, data => {
if(data && data.props && data.props.credentials)
resolve(data.props.credentials);
else
reject('No matching entry found');
});
});
}
function setFormData(form, data) {
if(!form || !data)
return;
for(let credential in data)
form[credential].val(data[credential]);
}
function autofill(form) {
let domain = getDomain();
return getCredentials(domain)
.then(setFormData.bind(null, form))
.catch(console.warn);
}
function formInputsObj(form, map) {
let inputs = $(form).find('input'),
obj = { };
for(let name in map) {
let typeFilter = map[name].type.map(type => `[type=${type}]`).join(','),
regexMap = map[name].regexMap,
nominated = inputs.filter(typeFilter), // .filter(':visible') needs some revision
scores;
let matches = nominated
.get() // Convert to JavaScript Array
.map(input => ({ 'element': input, 'score': elementScore(input, regexMap) }))
.filter(input => input.score > 0)
.sort((a, b) => b.score - a.score)
.map(input => input.element)
.slice(0, map[name].maxAmount || 1);
obj[name] = $(matches);
}
return obj;
} | JavaScript | 0.000006 | @@ -1226,26 +1226,20 @@
for(let
-credential
+prop
in data
@@ -1243,50 +1243,61 @@
ata)
+ %7B
%0A%09%09
+if(
form%5B
-credential%5D.val(data%5Bcredential%5D);
+prop%5D)%0A%09%09%09form%5Bprop%5D.val(data%5Bprop%5D);%0A%09%7D
%0A%7D%0A%0A
|
8beed1f2ae76535b5be194274ae0bc306b7b3bd3 | Undo last commit | js/numberlookup/NumberLookupService.js | js/numberlookup/NumberLookupService.js | 'use strict';
function NumberLookupService(options) {
this.sources = options.sources.map(function (Constructor) {
return new Constructor();
});
}
NumberLookupService.prototype.lookup = function (number) {
var self = this;
return new Promise(function (resolve) {
var promises = self.sources.map(function (source) {
return source.lookup(number);
});
Promise.all(promises).then(function (results) {
results = results.filter(function (result) {
return !!result || (Array.isArray(result) && result.length === 0);
});
resolve(results);
});
});
};
| JavaScript | 0 | @@ -501,58 +501,8 @@
sult
- %7C%7C (Array.isArray(result) && result.length === 0)
;%0A
|
beb87f306996500c578352920362d6af83ad4de8 | Add 'ui-accordion:visibility' event to handle visibility of header and content of each accordion group | src/main/resources/de/csgis/geobricks/webapp/modules/ui-accordion.js | src/main/resources/de/csgis/geobricks/webapp/modules/ui-accordion.js | define([ "jquery", "message-bus", "ui-commons" ], function($, bus, commons) {
var baseEventName = "ui-accordion";
bus.listen(baseEventName + ":create", function(e, msg) {
var accordion = commons.getOrCreateDiv(msg.div, msg.parentDiv);
accordion.addClass(msg.css);
});
bus.listen(baseEventName + ":add-group", function(e, msg) {
var accordionId = msg.accordion;
var groupId = msg.id;
var title = msg.title;
var visible = msg.visible;
var accordion = $("#" + accordionId);
var header = $("<div/>");
var content = $("<div/>").attr("id", groupId);
var headerText = $("<p/>").text(title);
header.addClass("accordion-header");
headerText.addClass("accordion-header-text");
header.click(function() {
content.slideToggle({
duration : 300
});
});
if (visible) {
content.show();
} else {
content.hide();
}
header.append(headerText);
accordion.append(header);
accordion.append(content);
});
}); | JavaScript | 0 | @@ -511,16 +511,48 @@
%3Cdiv/%3E%22)
+.attr(%22id%22, groupId + %22-header%22)
;%0A%09%09var
@@ -972,12 +972,334 @@
t);%0A%09%7D);
+%0A%0A%09function visibility(id, visibility) %7B%0A%09%09if (visibility !== undefined) %7B%0A%09%09%09var div = $(%22#%22 + id);%0A%09%09%09if (visibility) %7B%0A%09%09%09%09div.show();%0A%09%09%09%7D else %7B%0A%09%09%09%09div.hide();%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D%0A%0A%09bus.listen(%22ui-accordion:visibility%22, function(e, msg) %7B%0A%09%09visibility(msg.id + %22-header%22, msg.header);%0A%09%09visibility(msg.id, msg.content);%0A%09%7D);
%0A%7D);
|
f987245dfafd1689ffe7a30a0dc205a1b7a22d0c | remove extra space.. | js/solGS/listTypeTrainingPopulation.js | js/solGS/listTypeTrainingPopulation.js |
/**
reference population upload from lists.
Isaak Y Tecle
iyt2@cornell.edu
*/
JSAN.use("CXGN.List");
JSAN.use("jquery.blockUI");
jQuery(document).ready( function() {
var list = new CXGN.List();
var listMenu = list.listSelect("reference_genotypes", ['plots', 'trials']);
if(listMenu.match(/option/) != null) {
jQuery("#reference_genotypes_list").append(listMenu);
} else {
jQuery("#reference_genotypes_list").append("<select><option>no lists found</option></select>");
}
});
jQuery(document).ready( function() {
var listId;
jQuery("<option>", {value: '', selected: true}).prependTo("#reference_genotypes_list_select");
jQuery("#reference_genotypes_list_select").change(function() {
listId = jQuery(this).find("option:selected").val();
if(listId) {
jQuery("#reference_genotypes_list_upload").click(function() {
//alert('get list: ' + listId);
loadReferenceGenotypesList(listId);
});
}
});
});
function getReferenceGenotypesList(listId) {
var list = new CXGN.List();
var genotypesList;
if (! listId == "") {
genotypesList = list.getListData(listId);
}
var listName = list.listNameById(listId);
return {'name' : listName,
'list' : genotypesList.elements,
};
}
function loadReferenceGenotypesList(listId) {
var genoList = getReferenceGenotypesList(listId);
var listName = genoList.name;
var list = genoList.list;
var modelId = getModelId(listId);
var populationType = 'uploaded_reference';
if ( list.length === 0) {
alert('The list is empty. Please select a list with content.' );
}
else {
jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
jQuery.blockUI({message: 'Please wait..'});
list = JSON.stringify(list);
jQuery.ajax({
type: 'POST',
dataType: 'json',
data: {'model_id': modelId, 'list_name': listName, 'list': list, 'population_type': populationType},
url: '/solgs/upload/reference/genotypes/list',
success: function(response) {
if (response.status == 'success') {
var uploadedRefPops = jQuery("#uploaded_reference_pops_table").doesExist();
if (uploadedRefPops == false) {
uploadedRefPops = getUserUploadedRefPop(listId);
jQuery("#uploaded_reference_populations").append(uploadedRefPops).show();
}
else {
var url = '\'/solgs/population/'+ modelId + '\'';
var listIdArg = '\'' + listId +'\'';
var listSource = '\'from_db\'';
var popIdName = {model_id : modelId, name: listName,};
popIdName = JSON.stringify(popIdName);
var hiddenInput = '<input type="hidden" value=\'' + popIdName + '\'/>';
var addRow = '<tr><td>'
+ '<a href="/solgs/population/' + modelId + '\" onclick="javascript:loadPopulationPage(' + url + ','
+ listIdArg + ',' + listSource + ')">' + '<data>'+ hiddenInput + '</data>'
+ listName + '</a>'
+ '</td>'
+ '<td id="list_reference_page_' + modelId + '">'
+ '<a href="/solgs/population/' + modelId + '\" onclick="javascript:loadPopulationPage(' + url + ','
+ listIdArg + ',' + listSource + ')">'
+ '[ Build Model ]'+ '</a>'
+ '</td><tr>';
// alert(addRow);
var tdId = '#list_reference_page_' + modelId;
var addedRow = jQuery(tdId).doesExist();
// alert(addedRow);
if (addedRow == false) {
jQuery("#uploaded_reference_pops_table tr:last").after(addRow);
}
}
jQuery.unblockUI();
} else {
alert("fail: Error occured while uploading the list of reference genotypes.");
jQuery.unblockUI();
}
},
error: function(res) {
alert("Error occured while uploading the list of reference genotypes.");
jQuery.unblockUI();
}
});
}
}
jQuery.fn.doesExist = function(){
return jQuery(this).length > 0;
};
function getUserUploadedRefPop (listId) {
var genoList = getReferenceGenotypesList(listId);
var listName = genoList.name;
var list = genoList.list;
var modelId = getModelId(listId);
var url = '\'/solgs/population/'+ modelId + '\'';
var listIdArg = '\'' + listId +'\'';
var listSource = '\'from_db\'';
var popIdName = {id : modelId, name: listName,};
popIdName = JSON.stringify(popIdName);
var hiddenInput = '<input type="hidden" value=\'' + popIdName + '\'/>';
var uploadedSelPop ='<table id="uploaded_reference_pops_table" style="width:100%; text-align:left"><tr>'
+ '<th>List-based training population</th>'
+ '<th>Build model</th>'
+'</tr>'
+ '<tr>'
+ '<td>'
+ '<a href="/solgs/population/' + modelId + '\" onclick="javascript:loadPopulationPage(' + url + ','
+ listIdArg + ',' + listSource + ')">' + '<data>'+ hiddenInput + '</data>'
+ listName + '</a>'
+ '</td>'
+ '<td id="list_reference_page_' + modelId + '">'
+ '<a href="/solgs/population/' + modelId + '\" onclick="javascript:loadPopulationPage(' + url + ','
+ listIdArg + ',' + listSource + ')">'
+ '[ Build model ]'+ '</a>'
+ '</td></tr></table>';
return uploadedSelPop;
}
function loadPopulationPage (url, listId, listSource) {
// var traitId = getTraitId();
var genoList = getReferenceGenotypesList(listId);
var listName = genoList.name;
var modelId = getModelId(listId);
//alert('loadPopulationPage: url ' + url);
jQuery.blockUI.defaults.applyPlatformOpacityRules = false;
jQuery.blockUI({message: 'Please wait..'});
jQuery.ajax({
type: 'POST',
url: url,
dataType: 'json',
data: {
'uploaded_reference': 1,
'model_id': modelId,
'list_source': listSource,
'list_name' : listName,
},
success: function (response) {
if (response.status == 'success') {
jQuery.unblockUI();
}
else {
alert('Fail: Error occured calculating GEBVs for the list of selection genotypes.');
jQuery.unblockUI();
}
},
error: function(response) {
alert('error: ' + res.responseText);
}
});
}
function getModelId (listId) {
var modelId = 'uploaded_' + listId;
return modelId;
}
| JavaScript | 0.000003 | @@ -2081,17 +2081,16 @@
lse %7B %0A
-%0A
@@ -6674,33 +6674,32 @@
+ modelId + '%5C%22
-
onclick=%22javasc
|
96a4f42072bf498ef75a0286f84beb68a85e86cc | add iOS6 to iOS workarounds Fixes #5332 - Fixed header jumps around when iOS keyboard disappears | js/widgets/fixedToolbar.workarounds.js | js/widgets/fixedToolbar.workarounds.js | //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Browser specific workarounds for "fixed" headers and footers
//>>label: Toolbars: Fixed: Workarounds
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.fixedToolbar.css
define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.core", "../jquery.mobile.navigation", "./page", "./page.sections", "../jquery.mobile.zoom", "./fixedToolbar" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, undefined ) {
$.widget( "mobile.fixedtoolbar", $.mobile.fixedtoolbar, {
_create: function() {
this._super();
this._workarounds();
},
//check the browser and version and run needed workarounds
_workarounds: function() {
var ua = navigator.userAgent,
platform = navigator.platform,
// Rendering engine is Webkit, and capture major version
wkmatch = ua.match( /AppleWebKit\/([0-9]+)/ ),
wkversion = !!wkmatch && wkmatch[ 1 ],
os = null,
self = this;
//set the os we are working in if it dosent match one with workarounds return
if( platform.indexOf( "iPhone" ) > -1 || platform.indexOf( "iPad" ) > -1 || platform.indexOf( "iPod" ) > -1 ){
os = "ios";
} else if( ua.indexOf( "Android" ) > -1 ){
os = "android";
} else {
return;
}
//check os version if it dosent match one with workarounds return
if( os === "ios" && wkversion && wkversion > 533 && wkversion < 536 ) {
//iOS 5 run all workarounds for iOS 5
self._bindScrollWorkaround();
} else if( os === "android" && wkversion && wkversion < 534 ) {
//Android 2.3 run all Android 2.3 workaround
self._bindScrollWorkaround();
self._bindListThumbWorkaround();
} else {
return;
}
},
//Utility class for checking header and footer positions relative to viewport
_viewportOffset: function() {
var $el = this.element,
header = $el.is( ".ui-header" ),
offset = Math.abs($el.offset().top - $.mobile.window.scrollTop());
if( !header ) {
offset = Math.round(offset - $.mobile.window.height() + $el.outerHeight())-60;
}
return offset;
},
//bind events for _triggerRedraw() function
_bindScrollWorkaround: function() {
var self = this;
//bind to scrollstop and check if the toolbars are correctly positioned
this._on( $.mobile.window, { scrollstop: function() {
var viewportOffset = self._viewportOffset();
//check if the header is visible and if its in the right place
if( viewportOffset > 2 && self._visible) {
self._triggerRedraw();
}
}});
},
//this addresses issue #4250 Persistent footer instability in v1.1 with long select lists in Android 2.3.3
//and issue #3748 Android 2.x: Page transitions broken when fixed toolbars used
//the absolutely positioned thumbnail in a list view causes problems with fixed position buttons above in a nav bar
//setting the li's to -webkit-transform:translate3d(0,0,0); solves this problem to avoide potential issues in other
//platforms we scope this with the class ui-android-2x-fix
_bindListThumbWorkaround: function() {
this.element.closest(".ui-page").addClass( "ui-android-2x-fixed" );
},
//this addresses issues #4337 Fixed header problem after scrolling content on iOS and Android
//and device bugs project issue #1 Form elements can lose click hit area in position: fixed containers.
//this also addresses not on fixed toolbars page in docs
//adding 1px of padding to the bottom then removing it causes a "redraw"
//which positions the toolbars correctly (they will always be visually correct)
_triggerRedraw: function() {
var paddingBottom = parseFloat( $( ".ui-page-active" ).css( "padding-bottom" ) );
//trigger page redraw to fix incorrectly positioned fixed elements
$( ".ui-page-active" ).css( "padding-bottom", ( paddingBottom + 1 ) +"px" );
//if the padding is reset with out a timeout the reposition will not occure.
//this is independant of JQM the browser seems to need the time to react.
setTimeout( function() {
$( ".ui-page-active" ).css( "padding-bottom", paddingBottom + "px" );
}, 0 );
},
destroy: function() {
this._super();
//Remove the class we added to the page previously in android 2.x
this.element.closest(".ui-page-active").removeClass( "ui-android-2x-fix" );
}
});
})( jQuery );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
| JavaScript | 0 | @@ -1408,59 +1408,8 @@
ios%22
- && wkversion && wkversion %3E 533 && wkversion %3C 536
) %7B
@@ -1424,17 +1424,8 @@
iOS
-5 run all
wor
@@ -1436,18 +1436,8 @@
unds
- for iOS 5
%0A%09%09%09
|
f50f5b36c2cc5f5c0b8134965f9b3b89a292fa63 | Rewrite Decals API for Koa | api/controllers/decal.js | api/controllers/decal.js | 'use strict'
const Errors = require('../errors')
const Decal = require('../classes/Decal')
const User = require('../db').User
const Permission = require('../permission')
class HTTP {
static check (request, response, next) {
if (Object.keys(request.query).length > 0) {
Permission.require('user.read', request.user).then(function () {
User.findOne({
where: request.query
}).then(function (user) {
if (!user) {
let error = Error.template('not_found', 'user')
response.model.errors.push(error)
response.status(error.code)
next()
}
Decal.checkEligble(user).then(function () {
response.model.data = {
eligble: true
}
response.status = 200
next()
}).catch(function (error) {
response.model.errors.push(error)
response.status(error.code)
next()
})
})
}).catch(function (error) {
response.model.errors.push(error)
response.status(error.error.code)
next()
})
} else {
Decal.checkEligble(request.user).then(function () {
response.model.data = {
eligble: true
}
response.status = 200
next()
}).catch(function (error) {
response.model.errors.push(error)
response.status(error.code)
next()
})
}
}
static redeem (request, response, next) {
Decal.getDecalForUser(request.user).then(function (decal) {
response.model.data = decal
response.status = 200
next()
}).catch(function (errorData) {
let error = Errors.throw('server_error', errorData)
response.model.errors.push(error.error)
response.status(error.error.code)
next()
})
}
}
module.exports = {
HTTP
} | JavaScript | 0 | @@ -18,17 +18,16 @@
st Error
-s
= requi
@@ -166,16 +166,89 @@
on')
+%0Aconst DecalsPresenter = require('../classes/Presenters').DecalsPresenter
%0A%0Aclass
HTTP
@@ -243,20 +243,22 @@
%0A%0Aclass
-HTTP
+Decals
%7B%0A sta
@@ -265,38 +265,24 @@
tic
+async
check (
-request, response, next
+ctx
) %7B%0A
@@ -301,23 +301,19 @@
ct.keys(
-request
+ctx
.query).
@@ -332,16 +332,20 @@
%7B%0A
+if (
Permissi
@@ -355,16 +355,17 @@
require(
+%5B
'user.re
@@ -371,50 +371,71 @@
ead'
+%5D
,
-request.user).then(function () %7B%0A
+ctx.state.user, ctx.state.scope)) %7B%0A let user = await
Use
@@ -463,23 +463,19 @@
where:
-request
+ctx
.query%0A
@@ -487,34 +487,10 @@
%7D)
-.then(function (user) %7B%0A
+%0A%0A
@@ -512,37 +512,29 @@
%7B%0A
- let error =
+throw
Error.templ
@@ -562,115 +562,8 @@
r')%0A
- response.model.errors.push(error)%0A response.status(error.code)%0A next()%0A
@@ -573,25 +573,29 @@
%7D%0A%0A
-
+await
Decal.check
@@ -611,61 +611,23 @@
ser)
-.then(function () %7B%0A response.model.data =
+%0A return
%7B%0A
@@ -631,32 +631,29 @@
%7B%0A
-
-
elig
+i
ble: true%0A
@@ -662,476 +662,84 @@
- %7D%0A response.status = 200%0A next()%0A %7D).catch(function (error) %7B%0A response.model.errors.push(error)%0A response.status(error.code)%0A next()%0A %7D)%0A %7D)%0A %7D).catch(function (error) %7B%0A response.model.errors.push(error)%0A response.status(error.error.code)%0A next()%0A %7D)%0A %7D else %7B%0A Decal.checkEligble(request.user).then(function () %7B%0A response.model.data =
+%7D%0A %7D%0A %7D else %7B%0A await Decal.checkEligble(ctx.user)%0A return
%7B%0A
@@ -745,22 +745,21 @@
-
-
elig
+i
ble: tru
@@ -770,585 +770,144 @@
-
%7D%0A
- response.status = 200%0A next()%0A %7D).catch(function (error) %7B%0A response.model.errors.push(error)%0A response.status(error.code)%0A next()%0A %7D)%0A %7D%0A %7D%0A%0A static redeem (request, response, next) %7B%0A Decal.getDecalForUser(request.user).then(function (decal) %7B%0A
+%7D%0A %7D%0A%0A static async redeem (ctx) %7B%0A let decal = await Decal.getDecalForUser(ctx.user)%0A
-
re
-sponse.model.data = decal%0A response.status = 200%0A next()%0A %7D).catch(function (errorData) %7B%0A let error = Errors.throw('server_error', errorData)%0A response.model.errors.push(error.error)%0A response.status(error.error.code)%0A next()%0A %7D
+turn DecalsPresenter.render(decal
)%0A
@@ -934,14 +934,10 @@
s =
-%7B%0A HTTP%0A%7D
+Decals
|
6e92984133b033b68ea2395e4d7fda732435fc49 | Remove JQ set of placholder attribute as this is now done inPython | discussion/static/discussion/scripts/discussion.js | discussion/static/discussion/scripts/discussion.js | $(function() {
// Forum enhancements
// Requires jquery.form.js, jquery.autogrow.js and jquery.placeholder.js
//
function init(context) {
var allPostTextarea = $('.post-form textarea,', context);
var allCommentTextarea = $('.comment-form textarea,', context);
// Initialise post fields
if ($.fn.autogrow) {
// The class sets the height differently if we are using autogrow, otherwise uses a larger height
allPostTextarea.addClass('autogrow').autogrow()
allCommentTextarea.addClass('autogrow').autogrow()
}
if ($.fn.placeholder) {
var defaultPost = 'Start a conversation';
var defaultComment = 'Reply to this conversation';
defaultPost.attr('placeholder', defaultPost).placeholder();
allCommentTextarea.attr('placeholder', defaultComment).placeholder();
}
if ($.fn.ajaxSubmit) {
// initialise the comment forms
// Post comments via ajax
$('.comment-form', context).bind('submit', function(){
var form = $(this);
form.find('textarea').focus();
form.find(':submit').addClass('disabled').attr('disabled', true);
form.ajaxSubmit({
success: function(data, status_string, jqXHR) {
form.closest('.comment').before(data);
form.find(':input:not(:hidden,:submit)').val('').blur();
form.find('.errorlist').remove();
form.find(':submit').removeClass('disabled').attr('disabled', false);
},
error: function(jqXHR, textStatus, errorThrown) {
if (jqXHR.status == 400) {
var newForm = $(jqXHR.responseText);
form.replaceWith(newForm);
init(newForm.parent());
newForm.find('textarea').focus();
}
}
});
return false;
})
}
// Scroll to the top of the textarea with a little bit of padding
// (that is a quarter of the viewport)
$('.post-reply', context).click(function() {
var reply = $($(this).attr('href'));
$('body').animate({scrollTop: reply.offset().top - $(window).height()/4 });
reply.find('textarea').focus()
return false;
});
// Load the hidden comments with ajax
$('.comment.show-hidden a', context).click(function() {
$(this).closest('.post-comments').load($(this).attr('href')+' .post-comments', '', function(responseText, textStatus, XMLHttpRequest) {
init($(this));
})
return false;
});
}
init();
});
| JavaScript | 0 | @@ -607,28 +607,24 @@
) %7B%0A
-var
defaultPost
@@ -626,146 +626,8 @@
Post
- = 'Start a conversation';%0A var defaultComment = 'Reply to this conversation';%0A defaultPost.attr('placeholder', defaultPost)
.pla
@@ -669,44 +669,8 @@
rea.
-attr('placeholder', defaultComment).
plac
|
966c453b6e072f6eecb95a5350412f438f333241 | Update Recyclable_OwnerArray.js | CNN/util/Recyclable/Recyclable_OwnerArray.js | CNN/util/Recyclable/Recyclable_OwnerArray.js | export { OwnerArray };
import * as Pool from "../Pool.js";
import { Base } from "./Recyclable_Base.js";
/**
* Similar to Recyclable_Array but it owns its contents (which are instances of Recyclable.Base). It will release its contents
* (by calling their .disposeResources_and_recycleToPool()) in .disposeResources().
*
*
* Note: The behavior of this class's constructor (and .setAsConstructor()) is different from original Array (and Recyclable.Array).
*
* - Original Array (and Recyclable.Array):
*
* - If there is only one argument, it is viewed as the length of the newly created array.
*
* - This Recyclable.OwnerArray:
*
* - Even if there is only one argument, all arguments always are viewed as the contents the newly created array.
* The reason is for convenient and for avoiding un-initialized element object.
*
*
*/
class OwnerArray extends Array {
/**
* Used as default Recyclable.OwnerArray provider for conforming to Recyclable interface.
*/
static Pool = new Pool.Root( "Recyclable.OwnerArray.Pool", OwnerArray, OwnerArray.setAsConstructor );
/**
* Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
*
* Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
* is given.
*/
constructor( ...restArgs ) {
super( restArgs.length );
OwnerArray.setAsConstructor_self.call( this, restArgs );
}
/**
* Every element of restArgs should be instance of ChannelPartInfo (even if restArgs has only one element).
*
* Note: This behavior is different from original Array which will views the argement is length (not element) if only one argument
* is given.
*
* @override
*/
static setAsConstructor( ...restArgs ) {
super.setAsConstructor( restArgs.length );
OwnerArray.setAsConstructor_self.call( this, restArgs );
return this;
}
/** @override */
static setAsConstructor_self( objectArray ) {
for ( let i = 0; i < objectArray.length; ++i ) {
this[ i ] = objectArray[ i ];
}
}
/** @override */
disposeResources() {
// Release all contents since they are owned by this OwnerArray.
for ( let i = 0; i < this.length; ++i ) {
let object = this[ i ];
if ( object instanceof Recyclable.Base ) {
object.disposeResources_and_recycleToPool();
this[ i ] = null; // So that it will not become dangling object (since it has already been recycled).
}
}
super.disposeResources();
}
}
| JavaScript | 0.000001 | @@ -62,20 +62,41 @@
mport %7B
-Base
+Array as Recyclable_Array
%7D from
@@ -109,20 +109,21 @@
yclable_
-Base
+Array
.js%22;%0A%0A/
@@ -904,16 +904,27 @@
extends
+Recyclable_
Array %7B%0A
|
2680b26fb89c3dcdb5b1003ddcb61988a3785876 | add en field | lib/app/model/drama.js | lib/app/model/drama.js | "use strict";
import mongoose from 'mongoose';
let Schema = mongoose.Schema;
let dramaSchema = new Schema({
// 드라마 제목
title: { type: String, required: true },
// 드라마 시간
airTime: { type: [Date], required: true },
channel: { type: String },
chatrooms: { type: [Schema.Types.ObjectId], ref: 'chatrooms' },
category: { type: String }
});
dramaSchema.index({ title: 1 });
mongoose.model('dramas', dramaSchema);
let dramaModel = mongoose.model('dramas');
export default dramaModel; | JavaScript | 0.000001 | @@ -323,32 +323,56 @@
ategory: %7B type:
+ String %7D,%0A en: %7B type:
String %7D%0A%7D);%0A%0Ad
|
85d522c73b118384b32da6c3125f26b8c530b19c | add electron-prebuilt to search paths | lib/browser_process.js | lib/browser_process.js | 'use strict';
const child = require('child_process');
const fs = require('fs');
const path = require('path');
const util = require('util');
const which = require('which');
const debug = util.debuglog('browser_process');
const browsers = {
chrome: {
type: 'chrome',
paths: {
darwin: [
'/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome',
path.join(process.env['HOME'], '/Applications/Google\ Chrome.app/Contents/MacOS/Google\ Chrome'),
],
linux: [
'google-chrome'
],
win32: [
process.env['LOCALAPPDATA'] + '\\Google\\Chrome\\Application\\chrome.exe',
process.env['PROGRAMFILES'] + '\\Google\\Chrome\\Application\\chrome.exe',
process.env['PROGRAMFILES(X86)'] + '\\Google\\Chrome\\Application\\chrome.exe',
],
}[process.platform],
},
chromium: {
type: 'chrome',
paths: {
darwin: [
'/Applications/Chromium.app/Contents/MacOS/Chromium',
path.join(process.env['HOME'], '/Applications/Chromium.app/Contents/MacOS/Chromium'),
],
linux: [
'chromium-browser',
],
win32: [
process.env['LOCALAPPDATA'] + '\\Chromium\\Application\\chrome.exe',
process.env['PROGRAMFILES'] + '\\Chromium\\Application\\chrome.exe',
process.env['PROGRAMFILES(X86)'] + '\\Chromium\\Application\\chrome.exe',
]
}[process.platform],
},
electron: {
type: 'electron',
paths: {
darwin: [
'/Applications/Electron.app/Contents/MacOS/Electron',
path.join(process.env['HOME'], '/Applications/Electron.app/Contents/MacOS/Electron'),
'electron',
],
linux: [
'electron',
],
win32: [
'electron',
'electron.cmd',
]
}[process.platform],
},
firefox: {
type: 'firefox',
paths: {
darwin: [
'/Applications/Firefox.app/Contents/MacOS/Firefox',
path.join(process.env['HOME'], '/Applications/Firefox.app/Contents/MacOS/Firefox'),
],
linux: [
'firefox',
],
win32: [
process.env['LOCALAPPDATA'] + '\\Mozilla\ Firefox\\firefox.exe',
process.env['PROGRAMFILES'] + '\\Mozilla\ Firefox\\firefox.exe',
process.env['PROGRAMFILES(X86)'] + '\\Mozilla\ Firefox\\firefox.exe',
],
}[process.platform],
},
};
function type(command) {
if (browsers[command]) {
return browsers[command].type;
}
let basename = path.basename(command);
let key = Object.keys(browsers).find(key => {
return browsers[key].paths.some(exename => {
return basename === path.basename(exename);
});
});
if (key) {
return browsers[key].type;
}
throw Error('Bad browser command ' + command);
}
module.exports.type = type;
function find(identifier, callback) {
if (path.isAbsolute(identifier)) {
return callback(null, identifier);
}
let browser = browsers[identifier];
if (browser === undefined) {
let error = new Error('Invalid browser command');
return callback(error);
}
let done = false;
browser.paths.forEach(filename => {
which(filename, (error, command) => {
if (error || done) {
return;
}
done = true;
callback(null, command);
});
});
}
module.exports.find = find;
function detect(callback) {
let commands = [];
let pending = 0;
Object.keys(browsers).forEach(name => {
let browser = browsers[name];
pending += browser.paths.length;
browser.paths.forEach(filename => {
which(filename, (error, command) => {
if (command) {
commands.push(command);
}
if (--pending == 0) {
callback(commands.filter((value, index, array) => {
return array.indexOf(value) == index;
}));
}
});
});
});
}
module.exports.detect = detect;
function options(identifier, values) {
let kind = type(identifier);
let args = [];
if (kind.match(/chrome/)) {
if (values.debug) {
args.push(`--remote-debugging-port=${values.debug}`);
}
if (values.private) {
args.push(`--incognito`);
}
if (values.profile) {
args.push(`--user-data-dir=${values.profile}`);
}
if (values.url) {
args.push(values.url);
}
if (values.window) {
args.push('--new-window');
}
args.push('--no-default-browser-check');
args.push('--no-first-run');
}
if (kind.match(/electron/)) {
if (values.debug) {
args.push(`--remote-debugging-port=${values.debug}`);
}
if (values.url) {
if (values.url.match(/^(file|http|about)/) || values.url.match(/\.html$/)) {
args.push(require.resolve('./electron-browser'));
}
args.push(values.url);
}
}
if (kind.match(/firefox/)) {
if (values.debug) {
args.push(`--start-debugging-server`, values.debug);
}
if (values.private) {
args.push(`--private`);
}
if (values.profile) {
args.push(`--profile`, values.profile);
}
if (values.url) {
args.push(values.url);
}
if (values.window) {
args.push('--new-window');
}
}
return args;
}
module.exports.options = options;
function spawn(name, args, options, callback) {
if (typeof args === 'function') {
callback = args;
args = undefined;
} else if (typeof options === 'function') {
callback = options;
options = undefined;
}
find(name, (error, command) => {
if (error) {
return callback(error);
}
fs.realpath(command, (error, command) => {
if (error) {
return callback(error);
}
debug('spawn %s %s', command, util.inspect(args));
let ps = child.spawn(command, args, options);
ps.once('error', callback);
process.nextTick(function () {
ps.removeListener('error', callback);
callback(null, ps);
});
});
});
}
module.exports.spawn = spawn;
| JavaScript | 0.000001 | @@ -1469,32 +1469,98 @@
darwin: %5B%0A
+ 'node_modules/dist/Electron.app/Contents/MacOS/Electron',%0A
'/Applic
@@ -1700,33 +1700,33 @@
ron'),%0A '
-e
+E
lectron',%0A
@@ -1744,32 +1744,68 @@
nux: %5B%0A '
+node_modules/electron-prebuilt/dist/
electron',%0A
@@ -1835,29 +1835,61 @@
-'electron',%0A '
+path.resolve('node_modules%5C%5Celectron-prebuilt%5C%5Cdist%5C%5C
elec
@@ -1897,12 +1897,13 @@
ron.
-cmd'
+exe')
,%0A
|
9fda450e860d10896ba0dba9b14be71c1b46b237 | revert removing a space between parameters by mistake | test/sample_project/back/resources/products/variations/variations.js | test/sample_project/back/resources/products/variations/variations.js | var variations = [];
exports.post = function (req,res) {
variations.push({
name: req.body.name,
productsId: req.params.productsId
});
res.end();
};
exports.getIndex = function (res) {
res.json(variations);
};
| JavaScript | 0.000014 | @@ -44,16 +44,17 @@
on (req,
+
res) %7B%0A
|
f01cce9c0305404a2a044bbfbfd8961d40beb3da | add http status code to the response object | lib/casperjs-server.js | lib/casperjs-server.js | var system = require("system");
var Logger = require('./utils/casperLogger');
var logger = new Logger(system.env.CASPER_LOG_FILE || './casper.log');
var casper = require('casper').create({
viewportSize: {width: 1920, height: 1080},
pageSettings: {
"userAgent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.149 Safari/537.36",
"loadImages": false,
"loadPlugins": false
},
verbose: true,
logLevel: system.env.CASPER_LOG_LEVEL ? system.env.CASPER_LOG_LEVEL.toLowerCase() : 'debug'
});
var config = JSON.parse(system.args[system.args.length - 1]);
var server = require('webserver').create();
casper.start();
var timeout = 5000;
var service = server.listen(config.port, function(request, response) {
casper.on('remote.message', function(msg) {
logger.info('<REMOTE MESSAGE> ' + msg);
});
casper.then(function() {
//var method = request.method;
if (request.url === '/scrape') {
var postData = request.post;
postData = this.evaluate(function(s) {
return JSON.parse(s);
}, postData);
if (postData) {
_process(postData, response);
} else {
_output(JSON.stringify({
"status": false,
"message": "There is no urls to be updated."
}), response);
}
} else {//used for ping server , check it's health
_output("server is running.", response);
}
});
casper.on("exit", function(msg) {
logger.error("Casper server exit:" + msg);
casper.log("Casper server exit:" + msg, "error");
});
casper.on("error", function(msg) {
logger.error("Casper server occour error:" + msg);
casper.log("Casper server occour error:" + msg, "error");
});
casper.on("log", function(msg) {
if (msg) {
logger.info(msg.message);
}
});
casper.on("resource.error", function(resourceError) {
//only write log into casper log file , for the log that need to send back to node process. see below
logger.error("Resource error:" + JSON.stringify(resourceError));
// here change the log lever of resource.error from error to debug
// due many these log are occoure like 'Operation canceled' , etc, normally these kind of error won't cause two terrible issue
// so in the production we don't want them to be inserted into log file .
// in dev eviroment we will use level debug ,there information will come out.
casper.log("Resource error:" + JSON.stringify(resourceError), "debug");
});
casper.run(function() {
logger.info("Casper listening on port " + config.port);
casper.log("Casper listening on port " + config.port, "info");
});
});
function _process(params, res) {
var products = [];
var outputJson = {
"status": false,
"message": ""
};
casper.eachThen(params, function(job) {
var url = job.data.url;
var method = job.data.method;
var retailerFile = job.data.script;
var json = {
status: false,
url: url,
updateTime: new Date().toUTCString(),
script: retailerFile.split("/").slice(-1).join("/")
};
var script = require(retailerFile);
if (script) {
// allow script to make changes to the url prior to opening
if (script.redirect) {
url = script.redirect(url);
json.actualURL = url;
}
this.thenOpen(url, function onResponse(response) {
json.code = response.status;
switch (response.status) {
case 200 :
try {
if (script[method]) {
script[method](casper, timeout, function(productDetails) {
if (productDetails) {
productDetails.url = json.url;
productDetails.updateTime = json.updateTime;
productDetails.script = json.script;
productDetails.timestamp = (new Date()).getTime();
if (json.actualURL)
productDetails.actualURL = json.actualURL;
logger.info("SCRAPED with method '"+ method +"' :" + JSON.stringify(productDetails));
casper.log(JSON.stringify(productDetails),"info");
products.push(productDetails);
} else {
json.message = "Selector not found, maybe invalid page or need new selector.";
products.push(json);
}
});
} else {
json.message = "unknown method " + method;
products.push(json);
}
} catch (e) {
json.message = e.message;
products.push(json);
}
break;
case 404:
json.status = true;
json.stock = "notfound";
products.push(json);
break;
case 410:
json.status = true;
json.stock = "notfound";
products.push(json);
break;
default:
json.status = false;
json.message = "Failed to access site " + url + " - "
+ (response ? JSON.stringify(response) : "");
products.push(json);
}
}, function onTimeout() {
json.message = "Timeout opening " + url;
products.push(json);
}, timeout);
} else {
json.message = retailerFile + " not found";
products.push(json);
}
});
casper.then(function() {
if (products.length === params.length) {
outputJson.status = true;
outputJson.results = products;
} else {
outputJson.status = false;
outputJson.message = "responses received:" + products.length + " - responses expected:" + params.length;
outputJson.params = params;
outputJson.results = products;
}
_output(JSON.stringify(outputJson), res);
});
casper.on("error", function(msg, backtrace) {
outputJson.message = msg;
outputJson.status = false;
_output(JSON.stringify(outputJson), res);
});
}
function _output(data, response) {
response.writeHead(200, {'Content-Type': 'application/json'});
response.write(data);
response.close();
} | JavaScript | 0.000001 | @@ -3710,16 +3710,59 @@
ualURL;%0A
+%09%09%09%09%09%09%09%09%09%09productDetails.code = json.code;%0A
%09%09%09%09%09%09%09%09
|
df2c1ca6fa837ea7a78300eab366cbb514921c2e | read package version from package.json | lib/cli/version.cli.js | lib/cli/version.cli.js | 'use strict';
var Bluebird = require('bluebird');
/**
*
* @returns {*} promise
* @param parsedArgs - minimist-style parsed args
*/
module.exports = function (parsedArgs) {
//TODO: read from package.json file
var version = '0.0.1';
console.log(version);
return Bluebird.resolve(version);
};
| JavaScript | 0.000001 | @@ -48,196 +48,178 @@
');%0A
-%0A/**%0A *%0A * @returns %7B*%7D promise%0A * @param parsedArgs - minimist-style parsed args%0A */%0Amodule.exports = function (parsedArgs) %7B%0A //TODO: read from package.json file%0A var version = '0.0.1'
+var pkg = require('./../../package.json');%0A%0A/**%0A * Prints OraDBPM version to stdout%0A * @returns %7B*%7D promise%0A */%0Amodule.exports = function () %7B%0A var version = pkg.version
;%0A
|
66eac872b8cbc2f6fcdf5ea67a51a3b4041fd3b7 | Revert to a method where we internally track location state. | lib/client/location.js | lib/client/location.js | var dep = new Deps.Dependency;
var popped = false;
function onclick (e) {
var el = e.currentTarget;
var which = _.isUndefined(e.which) ? e.button : e.which;
var href = el.href;
var path = el.pathname + el.search + el.hash;
// we only want to handle clicks on links which:
// - are with the left mouse button with no meta key pressed
if (which !== 1)
return;
if (e.metaKey || e.ctrlKey || e.shiftKey)
return;
// - haven't been cancelled already
if (e.isDefaultPrevented())
return;
// - aren't in a new window
if (el.target)
return;
// - aren't external to the app
if (!IronLocation.isSameOrigin(href))
return;
// note that we _do_ handle links which point to the current URL
// and links which only change the hash.
e.preventDefault();
IronLocation.set(path);
}
function onpopstate (e) {
if (popped)
dep.changed();
}
IronLocation = {};
IronLocation.options = {
"linkSelector": 'a[href]'
};
IronLocation.configure = function(options){
if (this.isStarted){
IronLocation.unbindEvents();
}
_.extend(this.options, options);
if(this.isStarted){
IronLocation.bindEvents();
}
};
IronLocation.origin = function () {
return location.protocol + '//' + location.host;
};
IronLocation.isSameOrigin = function (href) {
var origin = IronLocation.origin();
return href.indexOf(origin) === 0;
};
IronLocation.get = function () {
dep.depend();
return location;
};
IronLocation.path = function () {
dep.depend();
return location.pathname + location.search + location.hash;
};
IronLocation.set = function (url, options) {
options = options || {};
var state = options.state || {};
if (/^http/.test(url))
href = url;
else {
if (url.charAt(0) !== '/')
url = '/' + url;
href = IronLocation.origin() + url;
}
if (!IronLocation.isSameOrigin(href))
window.location = href;
else if (options.where === 'server')
window.location = href;
else if (options.replaceState)
IronLocation.replaceState(state, options.title, url);
else
IronLocation.pushState(state, options.title, url);
if (options.skipReactive !== true)
dep.changed();
};
IronLocation.pushState = function (state, title, url) {
popped = true;
if (history.pushState)
history.pushState(state, title, url);
else
window.location = url;
};
IronLocation.replaceState = function (state, title, url) {
popped = true;
if (history.replaceState)
history.replaceState(state, title, url);
else
window.location = url;
};
IronLocation.bindEvents = function(){
$(window).on('popstate', onpopstate);
$(document).on('click', this.options.linkSelector, onclick);
};
IronLocation.unbindEvents = function(){
$(window).off('popstate', onpopstate);
$(window).off('click', this.options.linkSelector, onclick);
};
IronLocation.start = function () {
if (this.isStarted)
return;
IronLocation.bindEvents();
this.isStarted = true;
// store the fact that this is the first route we hit.
// this serves two purposes
// 1. We can tell when we've reached an unhandled route and need to show a
// 404 (rather than bailing out to let the server handle it)
// 2. Users can look at the state to tell if the history.back() will stay
// inside the app (this is important for mobile apps).
if (history.replaceState)
history.replaceState({initial: true}, null, location.pathname + location.search + location.hash);
};
IronLocation.stop = function () {
IronLocation.unbindEvents();
this.isStarted = false;
};
IronLocation.start();
| JavaScript | 0 | @@ -43,16 +43,290 @@
= false;
+%0A// XXX: we have to store the state internally (rather than just calling out%0A// to window.location) due to an android 2.3 bug. See:%0A// https://github.com/EventedMind/iron-router/issues/350%0Avar currentState = %7B%0A path: location.pathname + location.search + location.hash%0A%7D;
%0A%0Afuncti
@@ -1125,24 +1125,107 @@
state (e) %7B%0A
+ setState(e.state, null, location.pathname + location.search + location.hash);%0A %0A
if (popped
@@ -1802,24 +1802,28 @@
return
-location
+currentState
;%0A%7D;%0A%0AIr
@@ -1883,58 +1883,24 @@
urn
-location.pathname + location.search + location.has
+currentState.pat
h;%0A%7D
@@ -2505,24 +2505,197 @@
nged();%0A%7D;%0A%0A
+// store the state for later access%0AsetState = function(newState, title, url) %7B%0A currentState = newState %7C%7C %7B%7D;%0A currentState.path = url;%0A currentState.title = title;%0A%7D%0A%0A
IronLocation
@@ -2747,32 +2747,66 @@
popped = true;%0A
+ setState(state, title, url);%0A %0A
if (history.pu
@@ -2945,32 +2945,32 @@
, title, url) %7B%0A
-
popped = true;
@@ -2970,16 +2970,50 @@
= true;%0A
+ setState(state, title, url);%0A %0A
if (hi
|
820b462709f2a76881d289a18dad9345effd0215 | Split git commands to multiple calls to `runCommand` (#67) | lib/commands/commit.js | lib/commands/commit.js | 'use strict';
var exec = require('child_process').exec;
var RSVP = require('rsvp');
module.exports = {
name: 'github-pages:commit',
aliases: ['gh-pages:commit'],
description: 'Build the test app for production and commit it into a git branch',
works: 'insideProject',
availableOptions: [{
name: 'message',
type: String,
default: 'new gh-pages version',
description: 'The commit message to include with the build, must be wrapped in quotes.'
}, {
name: 'environment',
type: String,
default: 'production',
description: 'The ember environment to create a build for'
}, {
name: 'branch',
type: String,
default: 'gh-pages',
description: 'The git branch to push your pages to'
}, {
name: 'destination',
type: String,
default: '.',
description: 'The directory into which the built application should be copied'
}],
run: function(options, rawArgs) {
var ui = this.ui;
var root = this.project.root;
var execOptions = { cwd: root, shell: process.env.SHELL };
function buildApp() {
var env = options.environment;
return runCommand('ember build --environment=' + env, execOptions);
}
function checkoutGhPages() {
return runCommand('git checkout ' + options.branch, execOptions);
}
function copy() {
if (options.destination === '.') {
return runCommand('cp -R dist/* .', execOptions);
} else {
return runCommand('rm -r ' + options.destination +
' && mkdir ' + options.destination +
' && cp -R dist/* ' + options.destination + '/',
execOptions);
}
}
function addAndCommit() {
return runCommand('git -c core.safecrlf=false add "' + options.destination + '"' +
' && git commit -m "' + options.message + '"',
execOptions);
}
function returnToPreviousCheckout() {
return runCommand('git checkout -', execOptions);
}
return buildApp()
.then(checkoutGhPages)
.then(copy)
.then(addAndCommit)
.then(returnToPreviousCheckout)
.then(function() {
var branch = options.branch;
ui.write('Done. All that\'s left is to git push the ' + branch +
' branch.\nEx: git push origin ' + branch + ':' + branch +'\n');
});
}
};
function runCommand(/* child_process.exec args */) {
var args = Array.prototype.slice.call(arguments);
var lastIndex = args.length - 1;
var lastArg = args[lastIndex];
var logOutput = false;
if (typeof lastArg === 'boolean') {
logOutput = lastArg;
args.splice(lastIndex);
}
return new RSVP.Promise(function(resolve, reject) {
var cb = function(err, stdout, stderr) {
if (logOutput) {
if (stderr) {
console.log(stderr);
}
if (stdout) {
console.log(stdout);
}
}
if (err) {
return reject(err);
}
return resolve();
};
args.push(cb);
exec.apply(exec, args);
}.bind(this));
}
| JavaScript | 0.000001 | @@ -1587,34 +1587,46 @@
ions.destination
- +
+, execOptions)
%0A
@@ -1626,31 +1626,72 @@
- ' &&
+.then(function() %7B%0A return runCommand('
mkdir '
@@ -1711,18 +1711,31 @@
tination
- +
+, execOptions);
%0A
@@ -1730,32 +1730,40 @@
ns);%0A
+ %7D)%0A
'
@@ -1761,21 +1761,73 @@
-' &&
+ .then(function() %7B%0A return runCommand('
cp -R di
@@ -1861,27 +1861,31 @@
n + '/',
-%0A
+ execOptions);%0A
@@ -1888,35 +1888,25 @@
-execOptions
+%7D
);%0A %7D%0A
@@ -2027,18 +2027,30 @@
on + '%22'
- +
+, execOptions)
%0A
@@ -2060,23 +2060,62 @@
- ' &&
+.then(function() %7B%0A return runCommand('
git
@@ -2151,27 +2151,31 @@
e + '%22',
-%0A
+ execOptions);%0A
@@ -2180,29 +2180,18 @@
-execOptions);
+%7D)
%0A %7D%0A%0A
|
94974e7e185511361f17eb35c28de4564cbfc25d | Use switch statement instead of if/else in server | lib/commands/server.js | lib/commands/server.js | var http = require('http')
, events = require('../services/event_manager')
, notify = require('../services/notifier')
, growl_enabled = false;
exports.requestHandler = function(req, res) {
var body = '';
req.on('data', function(chunk) {
body += chunk.toString();
});
req.on('end', function() {
var event;
body = body ? JSON.parse(body) : {};
if (req.method === 'GET') {
// Block on event
event = events.find(body.event);
} else if (req.method === 'POST') {
// Announce status of event
event = events.add(body);
notify.event(body);
} else if (req.method === 'DELETE') {
// Flush events
events.clear();
notify.flush();
res.writeHead(204);
return res.end();
}
res.writeHead(200, {'Content-Type': 'text/json'});
res.end(JSON.stringify(event));
});
};
exports.start = function(opts) {
notify.set_growl_support(opts && opts.growl);
var server = http.createServer(exports.requestHandler);
server.listen(this.port);
console.log("Listening on port " + this.port);
return server;
};
| JavaScript | 0.000002 | @@ -368,19 +368,22 @@
%7B%7D;%0A
-if
+switch
(req.met
@@ -389,46 +389,45 @@
thod
- === 'GET') %7B%0A // Block on event%0A
+) %7B%0A case 'GET': // Flinch on%0A
@@ -469,84 +469,72 @@
-%7D else if (req.method === 'POST') %7B%0A // Announce status of event%0A
+ break;%0A case 'POST': // Flinch at OR Flinch gg%0A
+
even
@@ -557,24 +557,26 @@
ody);%0A
+
notify.event
@@ -591,68 +591,58 @@
-%7D else if (req.method === 'DELETE') %7B%0A // Flush events%0A
+ break;%0A case 'DELETE': // Flinch flush%0A
@@ -661,24 +661,26 @@
ar();%0A
+
+
notify.flush
@@ -679,24 +679,26 @@
fy.flush();%0A
+
res.wr
@@ -711,16 +711,102 @@
d(204);%0A
+ return res.end();%0A default: // Bad request%0A res.writeHead(400);%0A
re
|
18a130af77b7517ece8c3fe89d49bcf66b3659c2 | Stop Klarna from flashing on billing address change - Fix for ECPINT-394. | view/frontend/web/js/view/payment/method-renderer/checkoutcom_apm.js | view/frontend/web/js/view/payment/method-renderer/checkoutcom_apm.js | /**
* Checkout.com
* Authorized and regulated as an electronic money institution
* by the UK Financial Conduct Authority (FCA) under number 900816.
*
* PHP version 7
*
* @category Magento2
* @package Checkout.com
* @author Platforms Development Team <platforms@checkout.com>
* @copyright 2010-2019 Checkout.com
* @license https://opensource.org/licenses/mit-license.html MIT License
* @link https://docs.checkout.com/
*/
define(
[
'jquery',
'Magento_Checkout/js/view/payment/default',
'CheckoutCom_Magento2/js/view/payment/utilities',
'Magento_Checkout/js/model/full-screen-loader',
'Magento_Checkout/js/model/payment/additional-validators',
'Magento_Checkout/js/model/quote',
'mage/translate',
'jquery/ui'
],
function ($, Component, Utilities, FullScreenLoader, AdditionalValidators, Quote, __) {
'use strict';
window.checkoutConfig.reloadOnBillingAddress = true;
const METHOD_ID = 'checkoutcom_apm';
let loadEvents = true;
return Component.extend(
{
defaults: {
template: 'CheckoutCom_Magento2/payment/' + METHOD_ID + '.html',
redirectAfterPlaceOrder: false
},
/**
* @return {exports}
*/
initialize: function () {
this._super();
Utilities.loadCss('apm', 'apm');
},
/**
* @return {string}
*/
getCode: function () {
return METHOD_ID;
},
/**
* @return {string}
*/
getValue: function (field) {
return Utilities.getValue(METHOD_ID, field);
},
/**
* @return {void}
*/
checkDefaultEnabled: function () {
return Utilities.checkDefaultEnabled(METHOD_ID);
},
/**
* @return {void}
*/
initWidget: function () {
// Start the loader
FullScreenLoader.startLoader();
let self = this;
// Send the AJAX request
$.ajax(
{
type: "POST",
url: Utilities.getUrl('apm/display'),
success: function (data) {
self.animateRender(data);
},
error: function (request, status, error) {
Utilities.log(error);
// Stop the loader
FullScreenLoader.stopLoader();
}
}
);
},
/**
* @return {void}
*/
initEvents: function () {
if (loadEvents) {
let self = this;
let prevAddress;
Quote.billingAddress.subscribe(
function(newAddress) {
if (!newAddress || !prevAddress || newAddress.getKey() !== prevAddress.getKey()) {
prevAddress = newAddress;
if (newAddress) {
self.reloadApms(Quote.billingAddress().countryId);
}
}
}
);
loadEvents = false
}
},
reloadApms: function (countryId) {
let self = this;
// Start the loader
FullScreenLoader.startLoader();
// Send the AJAX request
$.ajax(
{
type: "POST",
url: Utilities.getUrl('apm/display'),
data: {
country_id: countryId
},
success: function (data) {
self.animateRender(data);
$( "#apm-container" ).accordion( "refresh" );
// Stop the loader
FullScreenLoader.stopLoader();
},
error: function (request, status, error) {
Utilities.log(error);
// Stop the loader
FullScreenLoader.stopLoader();
}
}
);
},
/**
* Animate opening of APM accordion
*/
animateRender: function (data) {
$('#apm-container').empty();
$('#apm-container').append(data.html)
.accordion(
{
heightStyle: 'content',
animate: {
duration: 200
}
}
);
if (data.klarna != true) {
// Stop the loader
$('#apm-container').show();
FullScreenLoader.stopLoader();
}
},
/**
* @return {void}
*/
placeOrder: function () {
let id = $("#apm-container div[aria-selected=true]").attr('id')
if (Utilities.methodIsSelected(METHOD_ID) && id) {
let form = $("#cko-apm-form-" + id),
data = {methodId: METHOD_ID};
// Start the loader
FullScreenLoader.startLoader();
// Serialize data
form.serializeArray().forEach(
function (e) {
data[e.name] = e.value;
}
);
// Place the order
if (AdditionalValidators.validate() && form.valid() && this.custom(data)) {
Utilities.placeOrder(
data,
METHOD_ID,
function () {
Utilities.log(__('Success'));
},
function () {
Utilities.log(__('Fail'));
}
);
}
FullScreenLoader.stopLoader();
}
},
/**
* Custom "before place order" flows.
*/
/**
* Dynamic function handler.
*
* @param {String} id The identifier
* @return {boolean}
*/
custom: function (data) {
var result = true;
if (typeof this[data.source] == 'function') {
result = this[data.source](data);
}
return result;
},
/**
* @return {boolean}
*/
klarna: function (data) {
try {
Klarna.Payments.authorize(
{
instance_id: "klarna-payments-instance",
auto_finalize: true
},
{},
function (response) {
data.authorization_token = response.authorization_token;
Utilities.placeOrder(
data,
METHOD_ID,
function () {
Utilities.log(__('Success'));
},
function () {
Utilities.showMessage('error', 'Could not finalize the payment.', METHOD_ID);
}
);
}
);
} catch (e) {
Utilities.showMessage('error', 'Could not finalize the payment.', METHOD_ID);
Utilities.log(e);
}
return false;
},
/**
* @return {boolean}
*/
sepa: function (data) {
return data.hasOwnProperty('accepted');
}
}
);
}
);
| JavaScript | 0 | @@ -5318,16 +5318,23 @@
.empty()
+.hide()
;%0A
|
6cfbae403abc3cf690565b09569f71cdd41a8372 | document run alias for run-script | lib/config/cmd-list.js | lib/config/cmd-list.js | var extend = Object.assign || require('util')._extend
// short names for common things
var shorthands = {
'un': 'uninstall',
'rb': 'rebuild',
'list': 'ls',
'ln': 'link',
'i': 'install',
'it': 'install-test',
'up': 'update',
'c': 'config',
's': 'search',
'se': 'search',
'unstar': 'star', // same function
'tst': 'test',
't': 'test',
'ddp': 'dedupe',
'v': 'view'
}
var affordances = {
'la': 'ls',
'll': 'ls',
'verison': 'version',
'isntall': 'install',
'dist-tags': 'dist-tag',
'apihelp': 'help',
'find-dupes': 'dedupe',
'upgrade': 'update',
'login': 'adduser',
'add-user': 'adduser',
'author': 'owner',
'home': 'docs',
'issues': 'bugs',
'info': 'view',
'show': 'view',
'find': 'search',
'unlink': 'uninstall',
'remove': 'uninstall',
'rm': 'uninstall',
'r': 'uninstall'
}
// these are filenames in .
var cmdList = [
'install',
'install-test',
'uninstall',
'cache',
'config',
'set',
'get',
'update',
'outdated',
'prune',
'pack',
'dedupe',
'rebuild',
'link',
'publish',
'star',
'stars',
'tag',
'adduser',
'logout',
'unpublish',
'owner',
'access',
'team',
'deprecate',
'shrinkwrap',
'help',
'help-search',
'ls',
'search',
'view',
'init',
'version',
'edit',
'explore',
'docs',
'repo',
'bugs',
'root',
'prefix',
'bin',
'whoami',
'dist-tag',
'ping',
'test',
'stop',
'start',
'restart',
'run-script',
'completion'
]
var plumbing = [
'build',
'unbuild',
'xmas',
'substack',
'visnup'
]
module.exports.aliases = extend(extend({}, shorthands), affordances)
module.exports.shorthands = shorthands
module.exports.affordances = affordances
module.exports.cmdList = cmdList
module.exports.plumbing = plumbing
| JavaScript | 0.000001 | @@ -385,16 +385,39 @@
: 'view'
+,%0A 'run': 'run-script'
%0A%7D%0A%0Avar
|
704e57c81520fc7678a312ce7b4e3001fff0ed7a | fix error handling of forum-api create response #915 | lib/forum-api/index.js | lib/forum-api/index.js | var mongoose = require('mongoose');
var express = require('express');
var api = require('lib/db-api');
var utils = require('lib/utils');
var restrict = utils.restrict;
var maintenance = utils.maintenance;
var Log = require('debug');
var log = new Log('democracyos:forum-api');
var app = module.exports = express();
app.get('/forum/mine', restrict, function(req, res) {
if (!req.isAuthenticated()) return res.status(404).send();
api.forum.findOneByOwner(req.user.id, function(err, forum) {
if (err) return _handleError(err, req, res);
if (forum) {
return res.status(200).json(forum);
} else {
return res.status(404).send();
}
});
});
app.get('/forum/:id', function(req, res, next) {
if (!mongoose.Types.ObjectId.isValid(req.params.id)) return next();
api.forum.findById(req.params.id, function(err, forum) {
if (err) return _handleError(err, req, res);
if (forum) {
return res.status(200).json(forum);
} else {
return res.status(404).send();
}
});
});
app.get('/forum/:name', function(req, res) {
api.forum.findOneByName(req.params.name, function(err, forum) {
if (err) return _handleError(err, req, res);
if (forum) {
return res.status(200).json(forum);
} else {
return res.status(404).send();
}
});
});
app.post('/forum', restrict, maintenance, function(req, res) {
var data = {
name: req.body.name,
title: req.body.title,
owner: req.user._id.toString(),
body: req.body.body,
};
log('Trying to create forum: %o', data);
api.forum.create(data, function (err, forum) {
if (err) {
log(err);
return res.status(500).json({ error: 'Sorry, there was an unexpected error. Try again later please'});
} else {
log('Forum document created successfully');
return res.status(200).json(forum);
}
});
});
app.del('/forum/:name', restrict, maintenance, function(req, res) {
api.forum.findOneByName(req.params.name, function(err, forum) {
if (err) return _handleError(err, req, res);
if (!forum) return _handleError('Forum not found.', req, res);
if (forum.owner.toString() !== req.user._id.toString()) {
return res.status(401).send();
}
log('Trying to delete forum: %s', forum.id);
api.forum.del(forum, function(_err) {
if (_err) return res.status(500).json(_err);
res.status(200).send();
});
});
});
app.get('/forum/exists', function(req, res, next) {
api.forum.exists(req.query.name, function(err, exists) {
if (err) return next(err);
return res.status(200).json({ exists: exists });
});
});
/**
* Helper functions
*/
function _handleError (err, req, res) {
log('Error found: %s', err);
var error = err;
if (err.errors && err.errors.text) error = err.errors.text;
if (error.type) error = error.type;
res.status(400).json({ error: error });
}
| JavaScript | 0 | @@ -1615,150 +1615,44 @@
rr)
-%7B%0A log(err);%0A return res.status(500).json(%7B error: 'So
+return _handleError(e
rr
-y
,
-there was an unexpected error. Try again later please'%7D);%0A %7D else %7B%0A
+req, res);%0A
@@ -1695,26 +1695,24 @@
ully');%0A
-
return res.s
@@ -1735,22 +1735,16 @@
forum);%0A
- %7D%0A
%7D);%0A%7D)
|
9cc074ff2a5480128394d24929fccac80d7e958a | fix file replacement viewing in MultiFileClient | exampleCourse/clientFilesCourse/MultiFileClient.js | exampleCourse/clientFilesCourse/MultiFileClient.js | var httpDownloadPrefix = 'data:text/plain;base64,';
define(["SimpleClient", "underscore", "clientCode/dropzone"], function(SimpleClient, _, Dropzone) {
return function(questionTemplate, submissionTemplate) {
var simpleClient = new SimpleClient.SimpleClient({questionTemplate: questionTemplate, submissionTemplate: submissionTemplate, skipRivets: true});
// Returns the raw (base-64 encoded) file contents
function getSubmittedFileContents(name) {
var files = simpleClient.submittedAnswer.get('files') || [];
console.log(files)
var contents = null;
_.each(files, function(file) {
if (file.name === name) {
contents = file.contents;
}
});
return contents;
}
// contents should be base-64 encoded
function saveSubmittedFile(name, contents) {
var files = simpleClient.submittedAnswer.get('files') || [];
var idx = _.findIndex(files, function(file) {
if (file.name === name) {
return true;
}
});
if (idx === -1) {
files.push({
name: name,
contents: contents
});
} else {
files[idx].contents = contents;
}
simpleClient.submittedAnswer.set('files', files);
}
// Uses the same method as Git to check if a file is binary or text:
// If the first 8000 bytes contain a NUL character ('\0'), we consider
// the file to be binary.
// http://stackoverflow.com/questions/6119956/how-to-determine-if-git-handles-a-file-as-binary-or-as-text
function isBinary(decodedFileContents) {
var nulIdx = decodedFileContents.indexOf('\0');
var fileLength = decodedFileContents.length;
return nulIdx != -1 && nulIdx <= (fileLength <= 8000 ? fileLength : 8000);
}
function uploadStatus() {
var $uploadStatusPanel = $('<div class="panel panel-default"></div>');
var $uploadStatusPanelHeading = $('<div class="panel-heading">Files</div>');
$uploadStatusPanel.append($uploadStatusPanelHeading);
var $uploadStatus = $('<ul class="list-group"></ul>');
var requiredFiles = simpleClient.params.get('requiredFiles');
_.each(requiredFiles, function(file) {
console.log(file)
var $item = $('<li class="list-group-item"></li>');
$uploadStatus.append($item);
$item.append('<code>' + encodeURIComponent(file) + '</code> - ');
var fileData = getSubmittedFileContents(file);
if (!fileData) {
$item.append('not uploaded');
} else {
var $preview = $('<pre><code></code></pre>');
try {
var fileContents = atob(fileData);
if (!isBinary(fileContents)) {
$preview.find('code').text(fileContents);
} else {
$preview.find('code').text('Binary file not previewed.');
}
} catch (e) {
console.log(e);
$preview.find('code').text('Unable to decode file.');
}
$preview.hide();
var $toggler = $('<a href="#">view</a>');
$toggler.on('click', function(e) {
$preview.toggle();
e.preventDefault();
return false;
});
$item.append($toggler);
$item.append($preview);
}
});
$uploadStatusPanel.append($uploadStatus);
return $uploadStatusPanel;
}
function initializeTemplate() {
var $fileUpload = $('#fileUpload');
$fileUpload.html('');
var $dropTarget = $('<div class="dropzone"><div class="dz-message">Drop files here or click to upload.<br/><small>Only the files listed below will be accepted—others will be silently ignored.</small></div></div>');
var $style = $('<style scoped>' +
'.dropzone { position: relative; min-height: 15ex; border-radius: 4px; background-color: #FAFDFF; border: 1px solid #D9EDF7; }' +
'.dropzone.dz-clickable { cursor: pointer; }' +
'.dropzone.dz-drag-hover { background-color: #D9EDF7; border-color: #AED3E5; }' +
'.dz-message { position: absolute; top: 50%; transform: translateY(-50%); text-align: center; width: 100%; }' +
'</style>'
);
var requiredFiles = simpleClient.params.get('requiredFiles');
var dropzone = $dropTarget.dropzone({
url: '/none',
autoProcessQueue: false,
accept: function(file, done) {
if (_.contains(requiredFiles, file.name)) {
done();
return;
}
done('invalid file');
},
addedfile: function(file) {
console.log("adding file...")
if (!_.contains(requiredFiles, file.name)) {
return;
}
console.log("reading!")
var reader = new FileReader();
reader.onload = function(e) {
var dataUrl = e.target.result;
var commaSplitIdx = dataUrl.indexOf(',');
// Store the file as base-64 encoded data
var base64FileData = dataUrl.substring(commaSplitIdx + 1);
saveSubmittedFile(file.name, base64FileData);
};
reader.readAsDataURL(file);
},
});
$fileUpload.append($style);
$fileUpload.append($dropTarget);
$fileUpload.append('<div class="fileUploadStatus" style="margin-top: 1ex;"></div>');
updateTemplate();
}
function updateTemplate() {
$('#fileUpload .fileUploadStatus').html('');
$('#fileUpload .fileUploadStatus').append(uploadStatus());
}
simpleClient.on('renderQuestionFinished', function() {
simpleClient.submittedAnswer.bind('change', function() {
updateTemplate();
});
simpleClient.addOptionalAnswer('files');
initializeTemplate();
});
return simpleClient;
};
});
if (!window.File || !window.FileReader || !window.FileList || !window.Blob) {
alert('Warning: Your browser does not fully support HTML5 file upload operations.' +
'Please use a more current browser or you may not be able to complete this question.')
}
| JavaScript | 0 | @@ -976,32 +976,142 @@
'files') %7C%7C %5B%5D;%0A
+ files = JSON.parse(JSON.stringify(files)); // deep clone needed to avoid changing backbone object%0A
var
|
1879f243dd94a430ee638927dcf5d26c7858ffd0 | generate shorter code | lib/runtime/TrustedTypesRuntimeModule.js | lib/runtime/TrustedTypesRuntimeModule.js | /*
MIT License http://www.opensource.org/licenses/mit-license.php
*/
"use strict";
const RuntimeGlobals = require("../RuntimeGlobals");
const Template = require("../Template");
const HelperRuntimeModule = require("./HelperRuntimeModule");
class TrustedTypesRuntimeModule extends HelperRuntimeModule {
constructor() {
super("trusted types");
}
/**
* @returns {string} runtime code
*/
generate() {
const { compilation } = this;
const { runtimeTemplate, outputOptions } = compilation;
const { trustedTypesPolicy } = outputOptions;
const fn = RuntimeGlobals.createScriptUrl;
if (!trustedTypesPolicy) {
// Skip Trusted Types logic.
return Template.asString([
`${fn} = ${runtimeTemplate.basicFunction("url", ["return url;"])};`
]);
}
return Template.asString([
"var policy;",
`${fn} = ${runtimeTemplate.basicFunction("url", [
"// Create Trusted Type policy if Trusted Types are available and the policy doesn't exist yet.",
"if (typeof policy === 'undefined') {",
Template.indent([
"policy = {",
Template.indent([
"createScriptURL: function(url) {",
Template.indent("return url;"),
"}"
]),
"};",
"if (typeof trustedTypes !== 'undefined' && trustedTypes.createPolicy) {",
Template.indent([
`policy = trustedTypes.createPolicy(${JSON.stringify(
trustedTypesPolicy
)}, policy);`
]),
"}"
]),
"}",
"return policy.createScriptURL(url);"
])};`
]);
}
}
module.exports = TrustedTypesRuntimeModule;
| JavaScript | 1 | @@ -702,37 +702,41 @@
runtimeTemplate.
-basic
+returning
Function(%22url%22,
@@ -739,23 +739,13 @@
l%22,
-%5B%22return url;%22%5D
+%22url%22
)%7D;%60
@@ -968,23 +968,16 @@
%09%09%09%22if (
-typeof
policy =
@@ -979,17 +979,16 @@
icy ===
-'
undefine
@@ -988,17 +988,16 @@
ndefined
-'
) %7B%22,%0A%09%09
@@ -1064,17 +1064,17 @@
%5B%0A%09%09%09%09%09%09
-%22
+%60
createSc
@@ -1086,70 +1086,65 @@
RL:
-f
+$%7Br
un
-c
ti
-on(url) %7B%22,%0A%09%09%09%09%09%09Template.indent(%22return url;%22)
+meTemplate.returningFunction(%0A%09%09%09%09%09%09%09%22url%22
,%0A%09%09%09%09%09%09
%22%7D%22%0A
@@ -1135,28 +1135,41 @@
url%22,%0A%09%09%09%09%09%09
-%22%7D
+%09%22url
%22%0A
+%09%09%09%09%09%09)%7D%60%0A
%09%09%09%09%09%5D),%0A%09%09%09
@@ -1177,25 +1177,25 @@
%09%22%7D;%22,%0A%09%09%09%09%09
-%22
+'
if (typeof t
@@ -1210,17 +1210,17 @@
pes !==
-'
+%22
undefine
@@ -1220,17 +1220,17 @@
ndefined
-'
+%22
&& trus
@@ -1253,17 +1253,17 @@
olicy) %7B
-%22
+'
,%0A%09%09%09%09%09T
|
154ff9e80031b69a3a4295757c61a27c1e007770 | move autoclose log | lib/workers/repository/finalise/prune.js | lib/workers/repository/finalise/prune.js | module.exports = {
pruneStaleBranches,
};
async function pruneStaleBranches(config, branchList) {
// TODO: try/catch
logger.debug('Removing any stale branches');
logger.trace({ config }, `pruneStaleBranches`);
logger.debug(`config.repoIsOnboarded=${config.repoIsOnboarded}`);
if (!branchList) {
logger.debug('No branchList');
return;
}
logger.debug({ branchList }, 'branchList');
let renovateBranches = await platform.getAllRenovateBranches(
config.branchPrefix
);
if (!(renovateBranches && renovateBranches.length)) {
logger.debug('No renovate branches found');
return;
}
logger.debug({ branchList, renovateBranches });
const lockFileBranch = `${config.branchPrefix}lock-file-maintenance`;
if (renovateBranches.includes(lockFileBranch)) {
logger.debug('Checking lock file branch');
const pr = await platform.getBranchPr(lockFileBranch);
if (pr && pr.isUnmergeable) {
logger.info('Deleting lock file maintenance branch as it is unmergeable');
await platform.deleteBranch(lockFileBranch);
}
renovateBranches = renovateBranches.filter(
branch => branch !== lockFileBranch
);
}
const remainingBranches = renovateBranches.filter(
branch => !branchList.includes(branch)
);
logger.debug(`remainingBranches=${remainingBranches}`);
if (remainingBranches.length === 0) {
logger.debug('No branches to clean up');
return;
}
for (const branchName of remainingBranches) {
logger.info({ branch: branchName }, `Deleting orphan branch`);
const pr = await platform.findPr(branchName, null, 'open');
if (pr) {
await platform.updatePr(pr.number, `${pr.title} - autoclosed`);
}
const closePr = true;
await platform.deleteBranch(branchName, closePr);
logger.info({ prNo: pr.number, prTitle: pr.title }, 'PR autoclosed');
}
}
| JavaScript | 0.000008 | @@ -1682,24 +1682,100 @@
toclosed%60);%0A
+ logger.info(%7B prNo: pr.number, prTitle: pr.title %7D, 'PR autoclosed');%0A
%7D%0A co
@@ -1852,82 +1852,8 @@
r);%0A
- logger.info(%7B prNo: pr.number, prTitle: pr.title %7D, 'PR autoclosed');%0A
%7D%0A
|
bdf3c423bf715620cf3cc74f428ba1a2c2957c72 | fix callback url error | app/util/Util.js | app/util/Util.js | Ext.define('Wodu.util.Util', {
singleton: true,
myApikey: '0d8bbcbe916a9aec28a3363bb43fd0c4',
mySecret: '7d5e2e16976b6d4a',
showNavBarTitle: function(theNavView, title) {
var navBar = theNavView.getNavigationBar();
if (theNavView.getInnerItems().length === navBar.backButtonStack.length) {
var stack = navBar.backButtonStack;
stack[stack.length - 1] = title;
navBar.setTitle(title);
}
},
checkLogin: function(success, failure) {
if (localStorage.myToken === undefined) {
failure();
} else {
success();
}
},
// oauth2 with douban
authentication: function(success, failure) {
if (localStorage.myToken === undefined) {
$.oauth2(
{
auth_url: 'https://www.douban.com/service/auth2/auth',
response_type: 'code', // required - "code"/"token"
token_url: 'https://www.douban.com/service/auth2/token', // required if response_type = 'code'
logout_url: '', // recommended if available
client_id: this.myApikey,
client_secret: this.mySecret, // required if response_type = 'code'
redirect_uri: 'http://aikanshu.sinaapp.com/', // required - some dummy url
other_params: {scope: 'book_basic_r,book_basic_w,douban_basic_common'} // optional params object for scope, state, display...
},
function(token, response) { // success
localStorage.myToken = token;
localStorage.myId = response.douban_user_id;
localStorage.myRefreshToken = response.refresh_token;
localStorage.myName = response.douban_user_name;
success();
},
function(error, response){ // failure
localStorage.removeItem('myToken');
failure();
});
} else {
success();
}
},
// 搜索图书
// GET https://api.douban.com/v2/book/search?q=searchText
searchForBooks: function(searchText, store) {
if (localStorage.myId) {
var proxy = store.getProxy();
proxy.setExtraParams({
fields: 'title,image,author,summary,publisher,pubdate,isbn13,pages,price,id,rating,images',
q: searchText,
apikey: this.myApikey
});
proxy.setUrl('https://api.douban.com/v2/book/search');
proxy.setHeaders({Authorization: 'Bearer ' + localStorage.myToken});
store.load();
};
},
// 获取某个用户的所有图书收藏信息
// GET https://api.douban.com/v2/book/user/:name/collections?status=xx
getBookCollections: function(status, store, done, fail) {
store.on('load', done);
var proxy = store.getProxy();
proxy.setExtraParams({
fields: 'updated,id,book_id,book',
status: status,
apikey: this.myApikey
});
proxy.setUrl('https://api.douban.com/v2/book/user/' + localStorage.myId + '/collections');
store.load();
},
// 用户删除对某本图书的收藏
// DELETE https://api.douban.com/v2/book/:id/collection
deleteBookFromCollection: function(bookId, done, fail) {
if (localStorage.myToken === undefined) {
fail('');
}
$.ajax({
url: 'https://api.douban.com/v2/book/' + bookId + '/collection',
method: 'DELETE',
headers: {Authorization: 'Bearer ' + localStorage.myToken}
}).done(done)
.fail(fail);
},
// 用户收藏某本图书
// POST https://api.douban.com/v2/book/:id/collection&status=wish
addBookToCollection: function(bookId, done, fail) {
if (localStorage.myToken === undefined) {
fail('');
}
$.ajax({
url: 'https://api.douban.com/v2/book/' + bookId + '/collection',
method: 'POST',
data: 'status=wish',
headers: {Authorization: 'Bearer ' + localStorage.myToken}
})
.done(done)
.fail(fail);
},
// 用户修改对某本图书的收藏
// PUT https://api.douban.com/v2/book/:id/collection?status=xxx
changeBookCollectionStatus: function(bookId, status, done, fail) {
if (localStorage.myToken === undefined) {
fail('');
}
$.ajax({
url: 'https://api.douban.com/v2/book/' + bookId + '/collection',
method: 'PUT',
data: 'status=' + status,
headers: {Authorization: 'Bearer ' + localStorage.myToken}
}).done(done)
.fail(fail);
}
}); | JavaScript | 0.000001 | @@ -1248,17 +1248,16 @@
aapp.com
-/
', // re
|
b9eac67f12b83c7e7e369757ca1bb8069c1a1ef9 | remove console.log() | assets/github.js | assets/github.js | (function ($, undefined) {
// Put custom repo URL's in this object, keyed by repo name.
var repoUrls = {};
function repoUrl(repo) {
return repoUrls[repo.name] || repo.html_url;
}
// Put custom repo descriptions in this object, keyed by repo name.
var repoDescriptions = {
"bootstrap": "An HTML, CSS, and JS toolkit designed to kickstart development of webapps and sites",
"naggati2": "A protocol builder for Netty using Scala 2.8"
};
function repoDescription(repo) {
return repoDescriptions[repo.name] || repo.description;
}
function addRecentlyUpdatedRepo(repo) {
var $item = $("<li>");
var $name = $("<a>").attr("href", repo.html_url).text(repo.name);
$item.append($("<span>").addClass("name").append($name));
var $time = $("<a>").attr("href", repo.html_url + "/commits").text(strftime("%h %e, %Y", repo.pushed_at));
$item.append($("<span>").addClass("time").append($time));
$item.append('<span class="bullet">⋅</span>');
var $watchers = $("<a>").attr("href", repo.html_url + "/watchers").text(repo.watchers + " stargazers");
$item.append($("<span>").addClass("watchers").append($watchers));
$item.append('<span class="bullet">⋅</span>');
var $forks = $("<a>").attr("href", repo.html_url + "/network").text(repo.forks + " forks");
$item.append($("<span>").addClass("forks").append($forks));
$item.appendTo("#recently-updated-repos");
}
function addRepo(repo) {
if (repo.fork === false) {
var $item = $("<li>").addClass("repo grid-1 " + (repo.language || '').toLowerCase());
var $link = $("<a>").attr("href", repoUrl(repo)).appendTo($item);
$link.append($("<h2>").text(repo.name));
$link.append($("<h3>").text(repo.language));
$link.append($("<p>").text(repoDescription(repo)));
console.log(repo);
console.log(repo.fork);
$item.appendTo("#repos");
}
}
function addRepos(repos, page) {
repos = repos || [];
page = page || 1;
var uri = "https://api.github.com/users/buren/repos?callback=?"
+ "&per_page=100"
+ "&page="+page;
$.getJSON(uri, function (result) {
if (result.data && result.data.length > 0) {
repos = repos.concat(result.data);
addRepos(repos, page + 1);
}
else {
$(function () {
$("#num-repos").text(repos.length);
// Convert pushed_at to Date.
$.each(repos, function (i, repo) {
repo.pushed_at = new Date(repo.pushed_at);
var weekHalfLife = 1.146 * Math.pow(10, -9);
var pushDelta = (new Date) - Date.parse(repo.pushed_at);
var createdDelta = (new Date) - Date.parse(repo.created_at);
var weightForPush = 1;
var weightForWatchers = 1.314 * Math.pow(10, 7);
repo.hotness = weightForPush * Math.pow(Math.E, -1 * weekHalfLife * pushDelta);
repo.hotness += weightForWatchers * repo.watchers / createdDelta;
});
// Sort by highest # of watchers.
repos.sort(function (a, b) {
if (a.hotness < b.hotness) return 1;
if (b.hotness < a.hotness) return -1;
return 0;
});
$.each(repos, function (i, repo) {
addRepo(repo);
});
// Sort by most-recently pushed to.
repos.sort(function (a, b) {
if (a.pushed_at < b.pushed_at) return 1;
if (b.pushed_at < a.pushed_at) return -1;
return 0;
});
$.each(repos.slice(0, 3), function (i, repo) {
addRecentlyUpdatedRepo(repo);
});
});
}
});
}
addRepos();
})(jQuery);
| JavaScript | 0.000002 | @@ -1822,63 +1822,8 @@
));%0A
- console.log(repo);%0A console.log(repo.fork);%0A
|
2a096d956428458497610291a49c5f83f67a0a7c | Remove jquery cookie from shim config. | assets/js/app.js | assets/js/app.js | requirejs.config({
baseUrl: 'assets/js',
paths: {
'jquery': '//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min',
'bootstrap': '//maxcdn.bootstrapcdn.com/bootstrap/3.3.1/js/bootstrap.min',
'underscore': '//cdnjs.cloudflare.com/ajax/libs/underscore.js/1.7.0/underscore-min',
'backbone': '//cdnjs.cloudflare.com/ajax/libs/backbone.js/1.1.2/backbone-min',
'jquery-cookie': '//cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min'
},
shim: {
'jquery-cookie': {
deps: ['jquery'],
exports: 'jQuery.fn.cookie'
}
}
});
requirejs(['main']); | JavaScript | 0 | @@ -493,134 +493,8 @@
in'%0A
- %7D,%0A shim: %7B%0A 'jquery-cookie': %7B%0A deps: %5B'jquery'%5D,%0A exports: 'jQuery.fn.cookie'%0A %7D%0A
|
d4b0545a943615d38487419c1e90666220be1eb5 | fix main | lib/assets/javascripts/esphinx/main.js | lib/assets/javascripts/esphinx/main.js | //= require ./extensor
"use strict";
var
esPhinx,
Extensor,
Iterator;
// IIFE
esPhinx = (function () {
return function esPhinx (selector, context) {
var
$ = esPhinx,
mainReference = this,
collection = [],
selectorsPattern = /(^[*.#])|(\[.+\])|(:.+)|(.+[+,~>].+)/g,
removeBreakLine = function (text) {
return text.replace(/(?!>)\n+/g, "");
};
if (!(mainReference instanceof $)) {
return new $(selector, context);
}
if (!context || context.constructor === Text) {
context = document;
} else {
if (typeof context === "string") {
context = esPhinx(context);
} else if (!context instanceof $) {
if (!context instanceof Node) {
throw new Error("An invalid or illegal context was specified.");
}
}
}
if (selector) {
// recognize tagName
// ([^<][^ >]+)
// attributes = selector.match(/[^< ]+[\=]+[^ >]+)|([^< ]+[^ >]/g)
// get children "".match(/(?:>)(<.+(?=(<\/)))/)[0]
if (selector instanceof $) {
return selector;
} else if (typeof selector === "function") {
return document
.addEventListener("DOMContentLoaded", function (e) {
selector.call($, e);
});
} else if (typeof selector === "string") {
if (/^(?:<)(.+)/.test(selector)) {
collection = Array.from((new DOMParser())
.parseFromString(removeBreakLine(selector), "text/html")
.body.childNodes);
} else {
if (Iterator.isIterable(context)) {
Array.from(context).forEach(function (node) {
collection = collection.concat(Array
.from(node.querySelectorAll(selector)))
.flatten();
});
} else {
if (!/^ +$/.test(selector)) {
collection = Array
.from(context.querySelectorAll(selector));
}
}
}
} else if (selector instanceof Node) {
collection = [selector];
} else if (selector instanceof Object) {
collection = Array.from(selector);
mainReference[0] = selector;
}
if (collection.length) {
Object.assign(mainReference, collection);
}
}
Object.defineProperties(mainReference, {
splice: {
value: Array.prototype.splice
}
});
Object.toIterable(mainReference);
return mainReference;
};
}());
(function ($module) {
Extensor.new($module, {
extend: function () {
Extensor.new(this, arguments[0]);
}
});
})(esPhinx);
(function ($) {
$.extend({
merge: function () {
var
self = arguments[0],
args = Array.from(arguments),
merged = {},
i;
Iterator.each(self, function (v, i) {
merged[i] = v;
});
for(i = 1; i < args.length; i++) {
if (args[i] instanceof Object) {
Iterator.each(args[i], function (v, i) {
merged[i] = v;
});
}
}
return merged;
},
type: function (object) {
// /[^ ]+(?=\])/g
return /[A-Z_]+[^\]]+/g.exec(Object.prototype.toString
.call(object))[0].replace(/ /g, "");
},
// each: function (enumerable, callback, recursive = false) {
each: function (enumerable, callback, recursive) {
if (typeof recursive !== "boolean") { recursive = false; }
Iterator.each(enumerable, recursive, function (v, i) {
callback.call(enumerable, v, parseInt(i));
});
return this;
},
prototype: {
each: function (callback) {
$.each(this, callback);
return this;
},
recursiveEach: function (callback) {
$.each(this, callback, true);
return this;
}
}
});
}(esPhinx));
| JavaScript | 0.000088 | @@ -2618,16 +2618,84 @@
ector);%0A
+%0A if (selector.constructor !== HTMLCollection) %7B%0A
@@ -2723,32 +2723,50 @@
%5B0%5D = selector;%0A
+ %7D%0A
%7D%0A%0A
|
ef75e2efae3c5a7d87cbba9dc11075fc55a65aa6 | Change button to Next in add profile test | funnel/assets/cypress/integration/00_addProfile.js | funnel/assets/cypress/integration/00_addProfile.js | describe('Profile', function() {
const owner = require('../fixtures/user.json').owner;
const profile = require('../fixtures/profile.json');
it('Create a new profile', function() {
cy.login('/organizations', owner.username, owner.password);
cy.get('a')
.contains('new organization')
.click();
cy.location('pathname').should('contain', '/new');
cy.get('#title').type(profile.title);
cy.get('#name').type(profile.title);
cy.get('#is_public_profile').click();
cy.get('button')
.contains('Create')
.click();
});
});
| JavaScript | 0 | @@ -532,22 +532,20 @@
ntains('
-Create
+Next
')%0A
|
7f4fe73d5a5c61295da2c77708e984c46d6f881f | Use "themes" service in catalog directive | geoportailv3/static/js/catalog/catalogdirective.js | geoportailv3/static/js/catalog/catalogdirective.js | /**
* @fileoverview This file provides the "catalog" directive. That directive is
* used to create the catalog tree in the page. It is based on the
* "ngeo-layertree" directive. And it relies on c2cgeoportal's "themes" web
* service.
*
* Example:
*
* <app-catalog app-catalog-map="::mainCtrl.map"></app-catalog>
*
* Note the use of the one-time binding operator (::) in the map expression.
* One-time binding is used because we know the map is not going to change
* during the lifetime of the application.
*/
goog.provide('app.catalogDirective');
goog.require('app');
goog.require('app.GetLayerForCatalogNode');
goog.require('ngeo.layertreeDirective');
/**
* @return {angular.Directive} The Directive Definition Object.
*/
app.catalogDirective = function() {
return {
restrict: 'E',
scope: {
'map': '=appCatalogMap'
},
controller: 'AppCatalogController',
controllerAs: 'catalogCtrl',
bindToController: true,
template: '<div ngeo-layertree="catalogCtrl.tree" ' +
'ngeo-layertree-map="catalogCtrl.map" ' +
'ngeo-layertree-nodelayer="catalogCtrl.getLayer(node)"></div>'
};
};
app.module.directive('appCatalog', app.catalogDirective);
/**
* @constructor
* @param {angular.$http} $http Angular http service.
* @param {string} treeUrl Catalog tree URL.
* @param {app.GetLayerForCatalogNode} appGetLayerForCatalogNode Function to
* create layers from catalog nodes.
* @export
* @ngInject
*/
app.CatalogController = function($http, treeUrl, appGetLayerForCatalogNode) {
$http.get(treeUrl).then(goog.bind(
/**
* @param {angular.$http.Response} resp Ajax response.
*/
function(resp) {
this['tree'] = resp.data['items'][2];
}, this));
/**
* @type {app.GetLayerForCatalogNode}
* @private
*/
this.getLayerFunc_ = appGetLayerForCatalogNode;
};
/**
* @param {Object} node Tree node.
* @param {ol.layer.Layer} layer OpenLayers layer.
* @export
*/
app.CatalogController.prototype.getInfo = function(node, layer) {
window.alert(node['name']);
};
/**
* Return the OpenLayers layer for this node. `null` is returned if the node
* is not a leaf.
* @param {Object} node Tree node.
* @return {ol.layer.Layer} The OpenLayers layer.
* @export
*/
app.CatalogController.prototype.getLayer = function(node) {
var layer = this.getLayerFunc_(node);
if (!goog.isNull(layer)) {
layer.set('metadata', node['metadata']);
}
return layer;
};
app.module.controller('AppCatalogController', app.CatalogController);
| JavaScript | 0.000001 | @@ -615,24 +615,52 @@
alogNode');%0A
+goog.require('app.Themes');%0A
goog.require
@@ -1265,93 +1265,43 @@
m %7Ba
-ngular.$http%7D $http Angular http service.%0A * @param %7Bstring%7D treeUrl Catalog tree URL
+pp.Themes%7D appThemes Themes service
.%0A *
@@ -1481,22 +1481,17 @@
ion(
-$http, treeUrl
+appThemes
, ap
@@ -1521,27 +1521,42 @@
) %7B%0A
+%0A
-$http.get(treeUrl
+appThemes.getThemeObject('main'
).th
@@ -1600,49 +1600,45 @@
am %7B
-angular.$http.Response%7D resp Ajax respons
+Object%7D tree Tree object for the them
e.%0A
@@ -1661,20 +1661,20 @@
unction(
+t
re
-sp
+e
) %7B%0A
@@ -1696,29 +1696,12 @@
%5D =
+t
re
-sp.data%5B'items'%5D%5B2%5D
+e
;%0A
|
bd753807333ddba357eac26d754a1df92e8573fd | Fix travis error 2 | blueprints/flexberry-list-form/files/__root__/controllers/__name__.js | blueprints/flexberry-list-form/files/__root__/controllers/__name__.js | import ListFormController from 'ember-flexberry/controllers/list-form';
export default ListFormController.extend({
/**
Name of related edit form route.
@property editFormRoute
@type String
@default '<%= editForm %>'
*/
editFormRoute: '<%= editForm %>'
});
| JavaScript | 0.00001 | @@ -109,16 +109,18 @@
xtend(%7B%0A
+
/**%0A
|
b2635680944c9f330971f3f5321639db3e0b12f5 | increase transition speed | client-vendor/after-body/jquery.clickFeedback/jquery.clickFeedback.js | client-vendor/after-body/jquery.clickFeedback/jquery.clickFeedback.js | /*
* Author: CM
* Dependencies: jquery.transit.js
*/
(function($) {
$(document).on('mousedown', '.clickFeedback', function(event) {
var $this = $(this);
var buttonOffset = $this.offset();
var feedbackSize = 2 * Math.sqrt(Math.pow($this.outerWidth(), 2) + Math.pow($this.outerHeight(), 2));
var posX = event.pageX;
var posY = event.pageY;
var $feedback = $('<div class="clickFeedback-ripple" />');
$feedback.css({
width: feedbackSize,
height: feedbackSize,
left: posX - buttonOffset.left - (feedbackSize / 2),
top: posY - buttonOffset.top - (feedbackSize / 2)
});
$this.append($feedback);
$feedback.transition({
scale: 1
}, '300ms', 'in').transition({
opacity: 0
}, '200ms', 'out', function() {
$feedback.remove();
});
});
})(jQuery);
| JavaScript | 0.000001 | @@ -704,9 +704,9 @@
%7D, '
-3
+2
00ms
|
9e2fdc6e27322a436c5cf1c0b9c7646509861a90 | Update send_message_to_console_MOD.js (#405) | actions/send_message_to_console_MOD.js | actions/send_message_to_console_MOD.js | module.exports = {
name: "Send Message to Console",
section: "Other Stuff",
subtitle: function(data) {
if (data.tosend.length > 0) {
return `<font color="${data.color}">${data.tosend}</font>`;
} else {
return "Please enter a message!";
}
},
fields: ["tosend", "color"],
html: function(isEvent, data) {
return `
<div style="padding-top: 8px;">
Message to send:<br>
<textarea id="tosend" rows="4" style="width: 99%; font-family: monospace; white-space: nowrap; resize: none;"></textarea>
</div>`;
},
init: function() {},
action: function(cache) {
const Mods = this.getMods();
Mods.CheckAndInstallNodeModule("chalk");
const chalk = Mods.require("chalk");
const data = cache.actions[cache.index];
const send = this.evalMessage(data.tosend, cache);
if (send.length > 0) {
const color = this.evalMessage(data.color, cache); // Default to #f2f2f2
console.log(chalk.hex(color)(send));
this.callNextAction(cache);
} else {
console.log(chalk.gray(`Please provide something to log: Action #${cache.index + 1}`));
this.callNextAction(cache);
}
},
mod: function(DBM) {
DBM.Actions["Send Message to Console (Logs)"] = DBM.Actions["Send Message to Console"];
}
};
| JavaScript | 0 | @@ -603,51 +603,8 @@
();%0A
-%09%09Mods.CheckAndInstallNodeModule(%22chalk%22);%0A
%09%09co
|
a4ec5e5f87296b31e47f9d1e8bae57003c682226 | Fix registrations form fields visibility (#562) | decidim-core/app/assets/javascripts/decidim/user_registrations.js.es6 | decidim-core/app/assets/javascripts/decidim/user_registrations.js.es6 | $(document).on('turbolinks:load', () => {
const $userRegistrationForm = $('.register-form');
const $userGroupFields = $userRegistrationForm.find('.user-group-fields');
const inputSelector = 'input[name="user[sign_up_as]"]';
const setGroupFieldsVisibility = (value) => {
if (value === 'user') {
$userGroupFields.hide();
} else {
$userGroupFields.show();
}
}
setGroupFieldsVisibility($userRegistrationForm.find(inputSelector).val());
$userRegistrationForm.on('change', inputSelector, (event) => {
const value = event.target.value;
setGroupFieldsVisibility(value);
});
});
| JavaScript | 0 | @@ -453,16 +453,19 @@
rm.find(
+%60$%7B
inputSel
@@ -469,16 +469,26 @@
Selector
+%7D:checked%60
).val())
|
3e991189d86da2aa3620701e0f04015955877c0c | Add methods to clear cache | addon/mixins/ember-data-store-cache.js | addon/mixins/ember-data-store-cache.js | /**
* Provides findWithCache method that forces a minimum cache time on the find
* requests.
*
* @class Ember Data Store Cache Mixin
*/
import Ember from "ember";
export default Ember.Mixin.create({
/**
* Number of seconds to require caching when using findWithCache method.
*
* @param cacheSeconds
* @type {Integer}
* @default 600
*/
cacheSeconds: 600,
/**
* Customized find method that checks for cache within a certain timeframe.
*
* @method findWithCache
* @param {String} typeKey
* @param {Mixed|Integer|Object} id
* @param {Object} payload
* @param {Integer} cacheTime Amount of time in seconds to cache for
* (overrides cacheSeconds param per instance)
*/
findWithCache: function(typeKey, id, payload, cacheTime) {
if (arguments.length === 1) {
// Find all.
// Get last queried time.
var type = this.modelFor(typeKey);
var requestedAt = this.typeMapFor(type).metadata.find_all_requested;
var now = this._getTimeNow();
cacheTime = cacheTime || this.get('cacheSeconds');
if (requestedAt && now - requestedAt < cacheTime) {
// If time is within cacheSeconds, get from store.
return this.all(typeKey);
} else {
// Else, make request.
return this.findAll(typeKey, id);
}
}
if (Ember.typeOf(id) === 'object') {
// Find query.
Ember.assert('findWithCache does not support queries yet. To use cache, request with find and use store.filter instead.');
}
// Find record by ID. Already loads from store if present.
Ember.assert('findWithCache does not support finding by id. Use find since it returns the record from the store if it is present.');
},
/**
* Override findAll method of store to set the find_all_requested metadata
* for use in determining the last request time in findWithCache
*
* @method findAll
* @param {String} typeKey
*/
findAll: function(typeKey) {
var type = this.modelFor(typeKey);
this.typeMapFor(type).metadata.find_all_requested = this._getTimeNow();
return this._super.apply(this, arguments);
},
/**
* Return the current timestamp in seconds.
*
* @method _getTimeNow
* @private
* @return {Integer} Timestamp in seconds.
*/
_getTimeNow: function() {
return Math.ceil(new Date() / 1000);
}
});
| JavaScript | 0.000001 | @@ -90,18 +90,17 @@
ests.%0A *
-
%0A
+
* @clas
@@ -282,33 +282,32 @@
e method.%0A *
-
%0A * @param c
@@ -392,25 +392,17 @@
s: 600,%0A
-
%0A
+
/**%0A
@@ -479,33 +479,32 @@
imeframe.%0A *
-
%0A * @method
@@ -691,17 +691,16 @@
ache for
-
%0A *
@@ -877,29 +877,17 @@
nd all.%0A
-
%0A
+
@@ -1090,21 +1090,9 @@
();%0A
-
%0A
+
@@ -1453,33 +1453,25 @@
%7D%0A %7D%0A
-
%0A
+
if (
@@ -1675,25 +1675,17 @@
%7D%0A
-
%0A
+
@@ -1883,36 +1883,788 @@
sent.');%0A %7D,%0A
+%0A
+/**%0A * Remove all entries of typeKey from the store and reset the metadata%0A * cache time so the next request via findWithCache will make the request%0A * to the server.%0A *%0A * @method clearCache%0A * @param %7BString%7D typeKey Type to clear%0A */%0A clearCache: function(typeKey) %7B%0A this.unloadAll(typeKey);%0A this.clearCacheTime(typeKey);%0A %7D,%0A%0A /**%0A * Reset the cache time for time to null so the next request via%0A * findWithCache will make the request to the server.%0A *%0A * @method clearCacheTime%0A * @param %7BString%7D typeKey Type of clear%0A */%0A clearCacheTime(typeKey) %7B%0A var type = this.modelFor(typeKey);%0A this.typeMapFor(type).metadata.find_all_requested = null;%0A %7D,%0A
%0A /**%0A *
@@ -2806,25 +2806,24 @@
Cache%0A *
-
%0A * @met
@@ -3033,17 +3033,9 @@
();%0A
-
%0A
+
@@ -3092,13 +3092,9 @@
%7D,%0A
-
%0A
+
@@ -3145,23 +3145,22 @@
econds.%0A
+
*
-
%0A *
|
8cfd21f6334c3198123b6981a677b95f892805ea | fix after cash-dom migration | addon/mixins/mobile-input-component.js | addon/mixins/mobile-input-component.js | import {
isTouchDevice
} from '../utils/mobile-utils';
import {
get
} from '@ember/object';
import Mixin from '@ember/object/mixin';
import {
scheduleOnce
} from '@ember/runloop';
import $ from 'cash-dom';
import {
inject
} from '@ember/service';
import {
alias
} from '@ember/object/computed';
import $ from 'cash-dom';
export default Mixin.create({
tagName: 'span',
disabled: false,
mobileInputEventBus: inject('mobile-input-event-bus'),
mobileInputService: inject('mobile-input'),
mobileInputVisible: alias('mobileInputService.mobileInputVisible'),
init() {
this._super(...arguments);
this.get('mobileInputEventBus').subscribe('mobileInputVisibleChanged', this, this.mobileInputVisibleChangedFn);
},
mobileInputVisibleChangedFn(value) {
if (this.get('isDestroyed') || this.get('isDestroying')) {
return;
}
this.set('mobileInputVisible', value);
},
actions: {
inputClicked() {
if (get(this, 'disabled') === true) {
return;
}
if (isTouchDevice()) {
this.get('mobileInputService').toggleProperty('mobileInputVisible');
//simulate click "propagation" on the input, because we just stole the click on the input
scheduleOnce('afterRender', () => {
let $element = $(this.element).find('.native-input');
$element.trigger('focus');
$element.trigger('click');
});
}
}
}
});
| JavaScript | 0.000002 | @@ -301,34 +301,8 @@
ed';
-%0Aimport $ from 'cash-dom';
%0A%0Aex
|
42ec4db561623c9be33b3cd8969171f8a18a5c27 | Fix Apollo Client instance caching on client-side | lib/graphql/client/initializeApollo.js | lib/graphql/client/initializeApollo.js | import {ApolloClient, HttpLink, InMemoryCache} from "@apollo/client"
import fetch from "isomorphic-fetch"
/**
* @typedef {import("@apollo/client").NormalizedCacheObject} NormalizedCacheObject
*/
/**
* @type {ApolloClient<NormalizedCacheObject>}
*/
let cachedClient = null
const createApollo = () => new ApolloClient({
ssrMode: process.browser === false || typeof window === "undefined",
link: new HttpLink({
uri: process.env.NEXT_PUBLIC_GRAPHQL,
credentials: "same-origin",
fetch
}),
cache: new InMemoryCache()
})
/**
* @param {Object.<string, any>} initialState
*/
function initializeApollo(initialState = null) {
/**
* @type {ApolloClient<NormalizedCacheObject>}
*/
const client = cachedClient ?? createApollo()
if (initialState) {
const oldCache = client.extract()
client.cache.restore({...oldCache, ...initialState})
}
// Always return a new client for SSR
if (process.browser === false) {
return client
}
if (cachedClient) {
cachedClient = client
}
return client
}
export default initializeApollo
| JavaScript | 0.000001 | @@ -970,22 +970,68 @@
nt%0A %7D%0A%0A
+ // Cache client if it wasn't cached before%0A
if (
+!
cachedCl
|
94ce50e0599246be6eafe2c5f1f457995d5e18dc | correct instructions | lib/modules/apostrophe-groups/index.js | lib/modules/apostrophe-groups/index.js | // Provide a way to group [apostrophe-users](../apostrophe-users/index.html) together
// and assign permissions to them. This module is always active "under the hood," even if
// you take advantage of the `groups` option of `apostrophe-users` to skip a separate
// admin bar button for managing groups. **To have an admin bar button for groups
// `apostrophe-users` should not be configured at project level.**
//
// By default the `published` schema field is removed. As a general rule we believe
// that conflating users and groups, who can log into the website, with public directories
// of people most often leads to confusion. Use a separate subclass of pieces to
// represent departments, etc.
//
// If you do add the `published` field back you will need to extend the cursor to make
// `published(true)` the default again.
//
// This module is **not** intended to be extended with new subclass modules, although
// you may implicitly subclass it at project level to change its behavior.
var _ = require('lodash');
module.exports = {
alias: 'groups',
extend: 'apostrophe-pieces',
name: 'apostrophe-group',
label: 'Group',
pluralLabel: 'Groups',
// Means not included in public sitewide search. -Tom
searchable: false,
// You can't give someone permission to edit groups because that
// allows them to make themselves an admin. -Tom
adminOnly: true,
addFields: [
{
type: 'joinByArrayReverse',
name: '_users',
label: 'Users',
idsField: 'groupIds',
withType: 'apostrophe-user',
ifOnlyOne: true
},
{
type: 'checkboxes',
name: 'permissions',
label: 'Permissions',
// This gets patched at modulesReady time
choices: []
}
],
beforeConstruct: function(self, options) {
options.removeFields = (options.minimumRemoved || [ 'published' ])
.concat(options.removeFields || []);
options.removeFilters = [ 'published' ]
.concat(options.removeFilters || []);
},
construct: function(self, options) {
self.modulesReady = function() {
self.setPermissionsChoices();
self.addToAdminBarIfSuitable();
};
self.setPermissionsChoices = function() {
var permissions = _.find(self.schema, { name: 'permissions' });
if (!permissions) {
return;
}
permissions.choices = self.apos.permissions.getChoices();
};
self.addToAdminBar = function() {};
// Adds an admin bar button if and only if the `apostrophe-users` module
// is not using its `groups` option for simplified group administration.
self.addToAdminBarIfSuitable = function() {
if (self.apos.users.options.groups) {
// Using the simplified group choice menu, so
// there is no managing of groups by the end user
} else {
self.apos.adminBar.add(self.__meta.name, self.pluralLabel, self.isAdminOnly() ? 'admin' : ('edit-' + self.name), { after: 'apostrophe-users' });
}
};
}
}
| JavaScript | 0.999999 | @@ -301,19 +301,19 @@
s. **To
-hav
+mak
e an adm
@@ -330,18 +330,93 @@
ton
-for groups
+available%0A// for managing groups, do NOT set the %60groups%60 option when configuring the
%0A//
@@ -438,21 +438,27 @@
rs%60
-should not be
+module. That option
con
@@ -467,26 +467,67 @@
gure
-d at project le
+s a hardcoded list of groups%0A// as a simplified alternati
ve
-l
.**%0A
|
ffd66c2e4a5c939ceb691e4f3927906f0c82dcfe | Update textediter.js | pages/textediter/textediter.js | pages/textediter/textediter.js | const mongo = require('mongodb');
var MongoClient = mongo.MongoClient;
function startdb(){
//code from 'ENOW code editor'
var code = document.getElementById("iframecode").contentWindow['code'];
//name of sourcecode saved in mongodb
var name = document.getElementById('nameofcode');
//connect to mongodb. insert data in 'source' db
MongoClient.connect('mongodb://localhost/source',function(err,db) {
var src = document.getElementById('source');
var name = document.getElementById('nameofcode');
console.log("start db");
//insert in mongodb.
var insertDocument = function(db, callback){
//insert in 'codes' collection
db.collection('codes').insertOne({
"name" : name.value,
"source" : code
},function(err, result){
console.log("Inserted a document into logs collection.");
callback();
});
};
insertDocument(db, function(){
db.close();
});
});
};
| JavaScript | 0.000001 | @@ -3,343 +3,732 @@
nst
-mongo = require('mongodb');%0Avar MongoClient = mongo.MongoClient;%0A%0A%0A%0Afunction startdb()%7B%0A%09//code from 'ENOW code editor'%0A%09var code = document.getElementById(%22iframecode%22).contentWindow%5B'code'%5D;%0A%09//name of sourcecode saved in mongodb%0A var name = document.getElementById('nameofcode');%0A%09//connect to mongodb. insert data in 'source' db
+http = require('http');%0Aconst express = require('express');%0Aconst mongo = require('mongodb');%0Aconst bodyparser = require('body-parser');%0A%0Avar path = require('path');%0Avar MongoClient = mongo.MongoClient;%0Avar expressapp = express();%0Aexpressapp.use(bodyparser.urlencoded(%7Bextended:true%7D));%0Aexpressapp.use(express.static(path.join(__dirname, 'public')));%0Avar router = express.Router();%0Aconst hostname = '127.0.0.1';%0Aconst port = 3000;%0A%0Arouter.use(function(req, res, next) %7B%0A%09console.log(req.method, req.url);%0A%09next();%0A%7D);%0A%0Ahttp.createServer(expressapp).listen(3000);%0A%0Aexpressapp.get('/', function(req, res)%7B%0A%09console.log(%22aa%22);%0A%7D);%0A%0Afunction startdb()%7B%0A var name = document.getElementById('src');%0A console.log(name.value);
%0A
@@ -765,16 +765,17 @@
//localh
+%09
ost/sour
@@ -809,19 +809,17 @@
var
-src
+i
= docum
@@ -843,71 +843,10 @@
d('s
-ource');%0A var name = document.getElementById('nameofcode
+rc
');%0A
@@ -882,31 +882,8 @@
%22);%0A
-%09%09//insert in mongodb.%0A
@@ -935,42 +935,8 @@
k)%7B%0A
-%09%09%09//insert in 'codes' collection%0A
@@ -1003,26 +1003,23 @@
name%22 :
-name.value
+%22hello%22
,%0A
@@ -1039,19 +1039,22 @@
urce%22 :
-cod
+i.valu
e%0A
|
c836187925f14d38700d173704df16784f3b834a | Order applied to measurements query. | lib/assets/core/javascripts/cartodb3/data/data-observatory/measurements-collection.js | lib/assets/core/javascripts/cartodb3/data/data-observatory/measurements-collection.js | var _ = require('underscore');
var BaseCollection = require('./data-observatory-base-collection');
var BaseModel = require('../../components/custom-list/custom-list-item-model');
var MEASUREMENTS_QUERY_WITH_REGION = 'SELECT * FROM OBS_GetAvailableNumerators((SELECT ST_SetSRID(ST_Extent(the_geom), 4326) FROM (<%- query %>) q), {{{ region }}}) numers';
var MEASUREMENTS_QUERY_WITHOUT_REGION = 'SELECT * FROM OBS_GetAvailableNumerators((SELECT ST_SetSRID(ST_Extent(the_geom), 4326) FROM (<%- query %>) q)) numers';
module.exports = BaseCollection.extend({
model: function (attrs, opts) {
return new BaseModel(attrs, opts);
},
_onFetchSuccess: function (data) {
var models = data.rows;
models = _.map(models, function (model) {
var o = {};
// label and val to custom list compatibility
o.val = model.numer_id;
o.label = model.numer_name;
o.description = model.numer_description;
o.type = model.numer_type;
o.aggregate = model.numer_aggregate;
// a measurement can belong to more than one category (filter)
o.filter = [];
var tags = model.numer_tags;
if (!_.isObject(tags)) {
tags = JSON.parse(tags);
}
for (var key in tags) {
if (/^subsection/.test(key)) {
o.filter.push({
id: key,
name: tags[key]
});
}
if (/^license/.test(key)) {
o.license = tags[key];
}
}
return o;
}).filter(function (model) {
return model.filter.length > 0;
});
this.reset(models);
},
buildQuery: function (options) {
return options && options.region && options.region != null
? _.template(MEASUREMENTS_QUERY_WITH_REGION)
: _.template(MEASUREMENTS_QUERY_WITHOUT_REGION);
}
});
| JavaScript | 0 | @@ -344,16 +344,40 @@
) numers
+ ORDER BY numer_name ASC
';%0Avar M
@@ -529,16 +529,40 @@
) numers
+ ORDER BY numer_name ASC
';%0A%0Amodu
|
de0d7e5ebd4f4b8364a7a60723597e4a392dc04b | Fix workaround for avoiding rich formatting in article title | peel/frontend/scripts/react.js | peel/frontend/scripts/react.js | /** @jsx React.DOM */
var EventHandlerMixin = {
onBlur: function(event) {
var html = this.getDOMNode().innerHTML,
fn = this.props.fieldName,
data = {};
$(this.getDOMNode()).hallo({editable: false});
data[fn] = html;
this.props.updateArticle(data, true);
},
onMouseDown: function(event) {
if (event.ctrlKey) {
var node = $(this.getDOMNode()),
innerNode = node.children(':first');
if (innerNode.hasClass('placeholder')) {
innerNode.html('');
}
node.hallo({editable: true});
}
},
};
var ArticleTitle = React.createClass({
mixins: [EventHandlerMixin],
componentDidMount: function() {
$(this.getDOMNode()).on('hallomodified', this.onHalloModified);
},
onHalloModified: function(event) {
var node = this.getDOMNode();
// TODO: Figure out a better workaround to avoid rich formatting.
node.innerHTML = node.innerText;
},
render: function() {
var title = this.props.title || '<i class="placeholder">Add title</i>';
return (
<span onBlur={this.onBlur} onMouseDown={this.onMouseDown}
dangerouslySetInnerHTML={{__html: title}} />
);
}
})
var ArticleBody = React.createClass({
mixins: [EventHandlerMixin],
render: function() {
var body = this.props.content || '<i class="placeholder">Add body</i>';
return (
<div className="article-body" onBlur={this.onBlur} onMouseDown={this.onMouseDown}
dangerouslySetInnerHTML={{__html: body}} />
);
}
});
var Article = React.createClass({
getDefaultProps: function() {
return {id: '', title: '', content: '', tags: [], created_at: '', updated_at: ''};
},
updateArticle: function(data, partial) {
var url = '/api/v1/article/',
reqOpts = {
type: 'POST',
contentType: 'application/json',
data: JSON.stringify(data),
dataType: 'json'
};
var id = this.props.id;
if (id) {
// The article already exists, so just update it.
url = url + id + '/';
// PATCH is forbidden on GAE, so use POST and a special header so
// Tastypie will interpret it as a partial update.
reqOpts.headers = partial ? {'X-HTTP-Method-Override': 'PATCH'} : {};
}
reqOpts.url = url;
$.ajax(reqOpts)
.done(function(response) {
response.key = id;
this.props.updateArticleState(response);
}.bind(this));
},
render: function() {
var tags = [];
this.props.tags.forEach(function(tag) {
tags.push(<li><a href="#">{tag}</a></li>);
});
return (
<div className="article">
<div className="date pull-right" title={this.props.updated_at}>{this.props.created_at}</div>
<h3 className="title">
<ArticleTitle updateArticle={this.updateArticle} fieldName="title" title={this.props.title} />
<ul className="tags">{tags}</ul>
</h3>
<ArticleBody updateArticle={this.updateArticle} fieldName="content" content={this.props.content} />
</div>
);
}
});
var ArticleList = React.createClass({
render: function() {
var articles = this.props.articles.map(function(article, i) {
return <Article key={article.id} id={article.id} title={article.title}
content={article.content} tags={article.tags}
created_at={article.created_at}
updated_at={article.updated_at}
updateArticleState={this.props.updateArticleState}
/>;
}.bind(this));
return <div id="articles">{articles}</div>;
}
});
var AddArticleButton = React.createClass({
componentDidMount: function() {
$(this.getDOMNode()).tooltip();
},
onClick: function() {
this.props.updateArticleState({});
},
render: function() {
return (
<button type="button" className="btn btn-primary" onClick={this.onClick}
data-toggle="tooltip" data-placement="top" title="Add a new article">
<span className="glyphicon glyphicon-plus"></span>
</button>
);
}
});
var Content = React.createClass({
getInitialState: function() {
return {articles: []};
},
componentDidMount: function() {
$.get(this.props.articleSource, function(result) {
this.setState({articles: result.objects});
}.bind(this));
},
/**
* Update an article that already exists in the backend.
*/
updateExistingArticle: function(articles, articleData) {
for (var i=0; i < articles.length; i++) {
if (articleData.key == articles[i].id) {
articles[i] = articleData;
break;
}
}
},
/**
* Update or create a placeholder article.
*/
updatePlaceholderArticle: function(articles, articleData) {
if ($.isEmptyObject(articleData)) {
if (articles[0] !== undefined && $.isEmptyObject(articles[0])) {
return;
}
// Add a new placeholder article
articles.splice(0, 0, articleData);
} else {
if ($.isEmptyObject(articles[0])) {
// Update an existing placeholder article
articles[0] = articleData;
}
}
},
updateArticleState: function(data) {
if (this.isMounted()) {
var articles = this.state.articles;
if (data.key) {
this.updateExistingArticle(articles, data);
} else {
this.updatePlaceholderArticle(articles, data);
}
this.setState({articles: articles})
}
},
render: function() {
return (
<div>
<div className="row" data-js="header">
<div className="col-lg-12 text-center">
<AddArticleButton updateArticleState={this.updateArticleState} />
</div>
</div>
<ArticleList articles={this.state.articles} updateArticleState={this.updateArticleState} />
</div>
);
}
});
React.renderComponent(<Content articleSource="/api/v1/article" />, document.getElementById('content'));
| JavaScript | 0.000001 | @@ -639,33 +639,25 @@
in%5D,%0A%0A
-componentDidMount
+onKeyDown
: functi
@@ -651,36 +651,100 @@
yDown: function(
+e
) %7B%0A
+ // Persist the data on Enter%0A if (e.keyCode === 13) %7B%0A
$(this.getDO
@@ -756,234 +756,202 @@
()).
-on('
hallo
-modified', this.onHalloModified);%0A %7D,%0A%0A onHalloModified: function(event) %7B%0A var node = this.getDOMNode();%0A // TODO: Figure out a better workaround to avoid rich formatting.%0A node.innerHTML = node.innerText;
+(%7Beditable: false%7D);%0A %7D else if (e.ctrlKey && $.inArray(e.keyCode, %5B66, 73, 85%5D) %3E -1) %7B%0A // Ignore Hallo shortcuts (%5EB, %5EI, %5EU)%0A e.stopPropagation();%0A return false;%0A %7D
%0A %7D
@@ -1128,32 +1128,59 @@
useDown%7D%0A
+ onKeyDown=%7Bthis.onKeyDown%7D
dangerouslySetI
@@ -1220,18 +1220,19 @@
);%0A %7D%0A
-
%7D)
+;
%0A%0Avar Ar
|
b2ae81f26b03f509f823a197b2ff734f8bbdcd71 | fix on js | _Build/vue/components/VExercise/VExercise.js | _Build/vue/components/VExercise/VExercise.js | "use strict";
import moment from "moment";
export default {
data(){
return {
result: {
reps: '',
weight: ''
}
};
},
props: [
'exercise',
'area',
'stopwatch'
],
computed: {
time(){
return this.stopwatch.time;
},
stats(){
var max = 0;
var last = 0;
var target = 0;
var next = 0;
var gD = this.exercise.defaults;
var currentSet = 0;
var maxLast = 0;
var weightSplit = 0;
var weightIncrement = 2.5;
var readyForIncrease = false;
var maxSession = 0;
var volume = 0;
var today = moment().format('DD/MM/YYYY');
if(!gD.max){
gD.max = 'auto';
}
if(this.exercise.sessions){
var workout = window.Workout(this.exercise.sessions);
var recentWorkout = workout.last();
var recentSets = recentWorkout.sets();
var todayBegan = 0;
if(recentSets.data.length && recentWorkout.date() === today){
todayBegan = 1;
}
max = workout.max();
if(todayBegan){
currentSet = recentSets.length();
volume = recentWorkout.volume();
last = recentSets.last().weight();
maxLast = workout.fromLast(1).max();
} else {
maxLast = recentWorkout.max();
}
if(gD.max !== 'auto'){
maxLast = gD.max;
}
// Intervals set and theres enough sessions to calculate
if(recentWorkout.sets().length() && gD.incInterval > 0 && workout.length() > (gD.incInterval + todayBegan)){
readyForIncrease = true;
var holdLastMax = 0;
var holdVolumeLast = 0;
for(var i = 0; i < gD.incInterval; i++){
var index = i + todayBegan;
var lastWorkout = workout.fromLast(index);
var tempLastMax = lastWorkout.max();
var tempVolumeLast = lastWorkout.volume();
if(tempVolumeLast > holdVolumeLast){
holdVolumeLast = tempVolumeLast;
}
if(tempLastMax > holdLastMax){
holdLastMax = tempLastMax;
}
}
for(i = 0; i < gD.incInterval; i++){
index = i + todayBegan;
lastWorkout = workout.fromLast(index);
tempLastMax = lastWorkout.max();
tempVolumeLast = lastWorkout.volume();
if(tempLastMax < holdLastMax || tempVolumeLast < holdVolumeLast || !lastWorkout.target()){
readyForIncrease = false;
break;
}
}
}
for (i = 0; i < gD.sets; ++i) {
var base = 0;
var incrememnt = 0;
var currentWeight = 0;
if(i < gD.peak){
if(gD.peak <= 1){
currentWeight = maxLast;
} else {
base = gD.startPercent * maxLast;
incrememnt = maxLast - base;
incrememnt /= (gD.peak - 1);
currentWeight = base + (incrememnt * i);
}
} else {
base = gD.endPercent * maxLast;
incrememnt = maxLast - base;
incrememnt /= (gD.sets - gD.peak);
currentWeight = maxLast - (incrememnt * (i - (gD.peak - 1)));
}
if(readyForIncrease){
currentWeight += gD.increase;
}
if(currentWeight > maxSession){
maxSession = currentWeight;
}
if(i === currentSet){
target = weightIncrement * Math.round(currentWeight / weightIncrement);
} else if(i === currentSet + 1){
next = weightIncrement * Math.round(currentWeight / weightIncrement);
}
}
weightSplit = ((target - gD.equipmentWeight) * 0.5);
if(weightSplit <= 0){
weightSplit = 0;
}
}
this.result.reps = gD.reps;
this.result.weight = target;
return {
lastMax: `${maxLast}kg`,
volume: `${volume}kg`,
increaseSession: readyForIncrease,
maxSession: maxSession,
setsDone: currentSet,
setsLeft: gD.sets - currentSet,
last: `${last}kg`,
target: target,
weightSplit: `${weightSplit}kg`,
next: `${next}kg`
};
}
},
methods: {
defaults(){
if(window.socket){
window.socket.emit('changeConfig', {
"title": this.exercise.title,
"group": this.area.toLowerCase(),
"gymDefaults": this.exercise.defaults
});
}
},
onSubmit(){
if(!this.exercise.sessions || this.exercise.sessions[this.exercise.sessions.length - 1].date !== moment().format('DD/MM/YYYY')){
if(!this.exercise.sessions){
this.exercise.sessions = [];
}
this.exercise.sessions.push({
date: moment().format('DD/MM/YYYY'),
sets: []
});
}
this.exercise.sessions[this.exercise.sessions.length - 1].sets.push({
"weight": this.result.weight,
"reps": this.result.reps,
"split": this.stopwatch.time,
"target": (
+this.result.weight > this.stats.target ||
(
+this.result.weight >= this.stats.target &&
+this.result.reps >= this.exercise.defaults.reps
)
)
});
if(window.socket){
window.socket.emit('saveLift', {
"title": this.exercise.title,
"group": this.area.toLowerCase(),
"weight": this.result.weight,
"reps": this.result.reps,
"split": this.stopwatch.time,
"target": (
+this.result.weight > this.stats.target ||
(
+this.result.weight >= this.stats.target &&
+this.result.reps >= this.exercise.defaults.reps
)
)
});
}
this.stopwatch.reset();
}
}
}; | JavaScript | 0.000001 | @@ -38,16 +38,71 @@
ment%22;%0A%0A
+var Workout = require('../../../js/libs/workout.js');%0A%0A
export d
@@ -726,23 +726,16 @@
rkout =
-window.
Workout(
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.