commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
429317e11c1c9f4394b3fc27de0b5da23bdbb0d5 | app/js/arethusa.relation/directives/nested_menu_collection.js | app/js/arethusa.relation/directives/nested_menu_collection.js | "use strict";
angular.module('arethusa.relation').directive('nestedMenuCollection', function() {
return {
restrict: 'A',
replace: 'true',
scope: {
current: '=',
all: '=',
property: '=',
ancestors: '=',
emptyVal: '@',
labelAs: "=",
change: "&"
},
link: function(scope, element, attrs) {
scope.emptyLabel = "";
scope.emptyObj = {};
scope.$watch('current[property]', function(newVal, oldVal) {
if (newVal !== oldVal) {
scope.change({ obj: scope.current });
}
});
scope.labelView = function(labelObj) {
if (scope.labelAs) {
return labelObj[scope.labelAs];
} else {
return labelObj.short;
}
};
},
template: '\
<ul>\
<li ng-if="emptyVal"\
nested-menu\
property="property"\
rel-obj="current"\
ancestors="ancestors"\
change="change"\
label="emptyLabel"\
label-obj="emptyObj">\
</li>\
<li\
ng-repeat="label in all | keys"\
nested-menu\
property="property"\
rel-obj="current"\
ancestors="ancestors"\
label="labelView(all[label])"\
label-as="labelAs"\
label-obj="all[label]">\
</li>\
</ul>\
'
};
});
| "use strict";
angular.module('arethusa.relation').directive('nestedMenuCollection', function() {
return {
restrict: 'A',
replace: 'true',
scope: {
current: '=',
all: '=',
property: '=',
ancestors: '=',
emptyVal: '@',
labelAs: "=",
},
link: function(scope, element, attrs) {
scope.emptyLabel = "";
scope.emptyObj = {};
scope.labelView = function(labelObj) {
if (scope.labelAs) {
return labelObj[scope.labelAs];
} else {
return labelObj.short;
}
};
},
template: '\
<ul>\
<li ng-if="emptyVal"\
nested-menu\
property="property"\
rel-obj="current"\
ancestors="ancestors"\
label="emptyLabel"\
label-obj="emptyObj">\
</li>\
<li\
ng-repeat="label in all | keys"\
nested-menu\
property="property"\
rel-obj="current"\
ancestors="ancestors"\
label="labelView(all[label])"\
label-as="labelAs"\
label-obj="all[label]">\
</li>\
</ul>\
'
};
});
| Remove change fn from nestedMenuCollection | Remove change fn from nestedMenuCollection
| JavaScript | mit | Masoumeh/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,PonteIneptique/arethusa | ---
+++
@@ -11,16 +11,10 @@
ancestors: '=',
emptyVal: '@',
labelAs: "=",
- change: "&"
},
link: function(scope, element, attrs) {
scope.emptyLabel = "";
scope.emptyObj = {};
- scope.$watch('current[property]', function(newVal, oldVal) {
- if (newVal !== oldVal) {
- scope.change({ obj: scope.current });
- }
- });
scope.labelView = function(labelObj) {
if (scope.labelAs) {
@@ -37,7 +31,6 @@
property="property"\
rel-obj="current"\
ancestors="ancestors"\
- change="change"\
label="emptyLabel"\
label-obj="emptyObj">\
</li>\ |
b740bdf7394e7325e174d7d4ccab1e1c185240f7 | app/scripts/components/issues/comments/issue-comments-form.js | app/scripts/components/issues/comments/issue-comments-form.js | import template from './issue-comments-form.html';
class IssueCommentsFormController {
// @ngInject
constructor($rootScope, issueCommentsService) {
this.$rootScope = $rootScope;
this.issueCommentsService = issueCommentsService;
}
submit() {
var form = this.issueCommentsService.$create(this.issue.url + 'comment/');
form.description = this.description;
this.submitting = true;
return form.$save().then(() => {
this.description = '';
this.$rootScope.$emit('refreshCommentsList');
}).finally(() => {
this.submitting = false;
});
}
}
const issueCommentsForm = {
template,
controller: IssueCommentsFormController,
bindings: {
issue: '<',
},
};
export default issueCommentsForm;
| import template from './issue-comments-form.html';
class IssueCommentsFormController {
// @ngInject
constructor($rootScope, issueCommentsService, ncUtilsFlash) {
this.$rootScope = $rootScope;
this.issueCommentsService = issueCommentsService;
this.ncUtilsFlash = ncUtilsFlash;
}
submit() {
var form = this.issueCommentsService.$create(this.issue.url + 'comment/');
form.description = this.description;
this.submitting = true;
return form.$save().then(() => {
this.description = '';
this.$rootScope.$emit('refreshCommentsList');
this.ncUtilsFlash.success(gettext('Comment has been added.'));
})
.catch(() => {
this.ncUtilsFlash.error(gettext('Unable to add comment.'));
})
.finally(() => {
this.submitting = false;
});
}
}
const issueCommentsForm = {
template,
controller: IssueCommentsFormController,
bindings: {
issue: '<',
},
};
export default issueCommentsForm;
| Add notifications for comment create processing [WAL-1036]. | Add notifications for comment create processing [WAL-1036].
| JavaScript | mit | opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport,opennode/waldur-homeport | ---
+++
@@ -2,9 +2,10 @@
class IssueCommentsFormController {
// @ngInject
- constructor($rootScope, issueCommentsService) {
+ constructor($rootScope, issueCommentsService, ncUtilsFlash) {
this.$rootScope = $rootScope;
this.issueCommentsService = issueCommentsService;
+ this.ncUtilsFlash = ncUtilsFlash;
}
submit() {
@@ -14,7 +15,12 @@
return form.$save().then(() => {
this.description = '';
this.$rootScope.$emit('refreshCommentsList');
- }).finally(() => {
+ this.ncUtilsFlash.success(gettext('Comment has been added.'));
+ })
+ .catch(() => {
+ this.ncUtilsFlash.error(gettext('Unable to add comment.'));
+ })
+ .finally(() => {
this.submitting = false;
});
} |
8b321a6c8a960f222477682e447e405971c4548e | website/addons/figshare/static/figshareFangornConfig.js | website/addons/figshare/static/figshareFangornConfig.js | var m = require('mithril');
var Fangorn = require('fangorn');
// Although this is empty it should stay here. Fangorn is going to look for figshare in it's config file.
Fangorn.config.figshare = {
};
| var m = require('mithril');
var Fangorn = require('fangorn');
// Define Fangorn Button Actions
function _fangornActionColumn (item, col) {
var self = this;
var buttons = [];
if (item.kind === 'folder') {
buttons.push(
{
'name' : '',
'tooltip' : 'Upload files',
'icon' : 'icon-upload-alt',
'css' : 'fangorn-clickable btn btn-default btn-xs',
'onclick' : Fangorn.ButtonEvents._uploadEvent
}
);
}
if (item.kind === 'file' && item.data.extra && item.data.extra.status === 'public') {
buttons.push({
'name' : '',
'tooltip' : 'Download file',
'icon' : 'icon-download-alt',
'css' : 'btn btn-info btn-xs',
'onclick' : Fangorn.ButtonEvents._downloadEvent
});
}
if (item.kind === 'file' && item.data.extra && item.data.extra.status !== 'public') {
buttons.push({
'name' : '',
'icon' : 'icon-remove',
'tooltip' : 'Delete',
'css' : 'm-l-lg text-danger fg-hover-hide',
'style' : 'display:none',
'onclick' : Fangorn.ButtonEvents._removeEvent
});
}
return buttons.map(function(btn) {
return m('span', { 'data-col' : item.id }, [ m('i',{
'class' : btn.css,
style : btn.style,
'data-toggle' : 'tooltip', title : btn.tooltip, 'data-placement': 'bottom',
'onclick' : function(event){ btn.onclick.call(self, event, item, col); }
},
[ m('span', { 'class' : btn.icon}, btn.name) ])
]);
});
}
Fangorn.config.figshare = {
// Fangorn options are called if functions, so return a thunk that returns the column builder
resolveActionColumn: function() {return _fangornActionColumn;}
}; | Repair removed figshare checks for action buttons | Repair removed figshare checks for action buttons
| JavaScript | apache-2.0 | hmoco/osf.io,cldershem/osf.io,barbour-em/osf.io,binoculars/osf.io,bdyetton/prettychart,sbt9uc/osf.io,SSJohns/osf.io,brandonPurvis/osf.io,samchrisinger/osf.io,bdyetton/prettychart,mfraezz/osf.io,baylee-d/osf.io,asanfilippo7/osf.io,felliott/osf.io,binoculars/osf.io,brandonPurvis/osf.io,wearpants/osf.io,monikagrabowska/osf.io,mluo613/osf.io,zamattiac/osf.io,RomanZWang/osf.io,Johnetordoff/osf.io,GageGaskins/osf.io,pattisdr/osf.io,ckc6cz/osf.io,zkraime/osf.io,jinluyuan/osf.io,zachjanicki/osf.io,arpitar/osf.io,billyhunt/osf.io,jmcarp/osf.io,cldershem/osf.io,petermalcolm/osf.io,chennan47/osf.io,samanehsan/osf.io,ticklemepierce/osf.io,Johnetordoff/osf.io,CenterForOpenScience/osf.io,Ghalko/osf.io,mattclark/osf.io,caneruguz/osf.io,mluo613/osf.io,saradbowman/osf.io,dplorimer/osf,Ghalko/osf.io,chennan47/osf.io,mluke93/osf.io,lyndsysimon/osf.io,kwierman/osf.io,jnayak1/osf.io,caseyrygt/osf.io,ZobairAlijan/osf.io,samchrisinger/osf.io,doublebits/osf.io,TomBaxter/osf.io,cslzchen/osf.io,ZobairAlijan/osf.io,sloria/osf.io,aaxelb/osf.io,ZobairAlijan/osf.io,KAsante95/osf.io,HalcyonChimera/osf.io,zamattiac/osf.io,alexschiller/osf.io,GageGaskins/osf.io,jinluyuan/osf.io,leb2dg/osf.io,petermalcolm/osf.io,bdyetton/prettychart,DanielSBrown/osf.io,icereval/osf.io,samanehsan/osf.io,Nesiehr/osf.io,cosenal/osf.io,kushG/osf.io,fabianvf/osf.io,cldershem/osf.io,barbour-em/osf.io,kwierman/osf.io,brianjgeiger/osf.io,zkraime/osf.io,mluo613/osf.io,GageGaskins/osf.io,cslzchen/osf.io,emetsger/osf.io,asanfilippo7/osf.io,mfraezz/osf.io,samchrisinger/osf.io,RomanZWang/osf.io,mluo613/osf.io,doublebits/osf.io,RomanZWang/osf.io,danielneis/osf.io,ckc6cz/osf.io,laurenrevere/osf.io,TomHeatwole/osf.io,samanehsan/osf.io,mattclark/osf.io,jeffreyliu3230/osf.io,DanielSBrown/osf.io,rdhyee/osf.io,erinspace/osf.io,TomHeatwole/osf.io,himanshuo/osf.io,acshi/osf.io,wearpants/osf.io,zachjanicki/osf.io,chennan47/osf.io,HalcyonChimera/osf.io,revanthkolli/osf.io,amyshi188/osf.io,amyshi188/osf.io,Johnetordoff/osf.io,lamdnhan/osf.io,KAsante95/osf.io,zachjanicki/osf.io,baylee-d/osf.io,himanshuo/osf.io,kch8qx/osf.io,arpitar/osf.io,kushG/osf.io,dplorimer/osf,arpitar/osf.io,caneruguz/osf.io,jolene-esposito/osf.io,jinluyuan/osf.io,ticklemepierce/osf.io,sbt9uc/osf.io,kch8qx/osf.io,jinluyuan/osf.io,reinaH/osf.io,TomHeatwole/osf.io,aaxelb/osf.io,cosenal/osf.io,danielneis/osf.io,lyndsysimon/osf.io,asanfilippo7/osf.io,jmcarp/osf.io,lamdnhan/osf.io,icereval/osf.io,reinaH/osf.io,asanfilippo7/osf.io,mluke93/osf.io,cwisecarver/osf.io,ZobairAlijan/osf.io,TomBaxter/osf.io,ckc6cz/osf.io,fabianvf/osf.io,leb2dg/osf.io,doublebits/osf.io,dplorimer/osf,alexschiller/osf.io,Nesiehr/osf.io,caseyrollins/osf.io,brandonPurvis/osf.io,danielneis/osf.io,samchrisinger/osf.io,sloria/osf.io,DanielSBrown/osf.io,chrisseto/osf.io,binoculars/osf.io,wearpants/osf.io,billyhunt/osf.io,arpitar/osf.io,baylee-d/osf.io,brianjgeiger/osf.io,hmoco/osf.io,bdyetton/prettychart,sbt9uc/osf.io,zachjanicki/osf.io,zamattiac/osf.io,MerlinZhang/osf.io,chrisseto/osf.io,crcresearch/osf.io,brianjgeiger/osf.io,MerlinZhang/osf.io,rdhyee/osf.io,hmoco/osf.io,danielneis/osf.io,petermalcolm/osf.io,HarryRybacki/osf.io,abought/osf.io,kushG/osf.io,monikagrabowska/osf.io,ticklemepierce/osf.io,mfraezz/osf.io,reinaH/osf.io,njantrania/osf.io,MerlinZhang/osf.io,acshi/osf.io,leb2dg/osf.io,CenterForOpenScience/osf.io,icereval/osf.io,KAsante95/osf.io,adlius/osf.io,dplorimer/osf,alexschiller/osf.io,doublebits/osf.io,cosenal/osf.io,jnayak1/osf.io,revanthkolli/osf.io,KAsante95/osf.io,aaxelb/osf.io,mfraezz/osf.io,kwierman/osf.io,amyshi188/osf.io,sloria/osf.io,billyhunt/osf.io,GageGaskins/osf.io,adlius/osf.io,haoyuchen1992/osf.io,njantrania/osf.io,emetsger/osf.io,CenterForOpenScience/osf.io,caneruguz/osf.io,kushG/osf.io,mluke93/osf.io,himanshuo/osf.io,pattisdr/osf.io,monikagrabowska/osf.io,brandonPurvis/osf.io,caseyrollins/osf.io,Ghalko/osf.io,wearpants/osf.io,jolene-esposito/osf.io,jmcarp/osf.io,mattclark/osf.io,crcresearch/osf.io,erinspace/osf.io,revanthkolli/osf.io,Johnetordoff/osf.io,crcresearch/osf.io,jeffreyliu3230/osf.io,acshi/osf.io,barbour-em/osf.io,kwierman/osf.io,HalcyonChimera/osf.io,mluo613/osf.io,SSJohns/osf.io,Nesiehr/osf.io,jolene-esposito/osf.io,chrisseto/osf.io,amyshi188/osf.io,jmcarp/osf.io,adlius/osf.io,RomanZWang/osf.io,cslzchen/osf.io,chrisseto/osf.io,HarryRybacki/osf.io,haoyuchen1992/osf.io,jnayak1/osf.io,lyndsysimon/osf.io,kch8qx/osf.io,caseyrygt/osf.io,Nesiehr/osf.io,njantrania/osf.io,adlius/osf.io,abought/osf.io,ckc6cz/osf.io,sbt9uc/osf.io,fabianvf/osf.io,jolene-esposito/osf.io,haoyuchen1992/osf.io,HalcyonChimera/osf.io,cwisecarver/osf.io,DanielSBrown/osf.io,SSJohns/osf.io,reinaH/osf.io,samanehsan/osf.io,MerlinZhang/osf.io,emetsger/osf.io,jnayak1/osf.io,zkraime/osf.io,RomanZWang/osf.io,saradbowman/osf.io,SSJohns/osf.io,GaryKriebel/osf.io,fabianvf/osf.io,GaryKriebel/osf.io,abought/osf.io,njantrania/osf.io,KAsante95/osf.io,rdhyee/osf.io,zamattiac/osf.io,felliott/osf.io,GaryKriebel/osf.io,TomHeatwole/osf.io,acshi/osf.io,cslzchen/osf.io,Ghalko/osf.io,monikagrabowska/osf.io,barbour-em/osf.io,cwisecarver/osf.io,cosenal/osf.io,billyhunt/osf.io,jeffreyliu3230/osf.io,cldershem/osf.io,laurenrevere/osf.io,lamdnhan/osf.io,GaryKriebel/osf.io,ticklemepierce/osf.io,monikagrabowska/osf.io,pattisdr/osf.io,mluke93/osf.io,cwisecarver/osf.io,acshi/osf.io,TomBaxter/osf.io,leb2dg/osf.io,lamdnhan/osf.io,abought/osf.io,felliott/osf.io,zkraime/osf.io,caseyrollins/osf.io,aaxelb/osf.io,felliott/osf.io,caseyrygt/osf.io,erinspace/osf.io,rdhyee/osf.io,HarryRybacki/osf.io,brianjgeiger/osf.io,emetsger/osf.io,hmoco/osf.io,lyndsysimon/osf.io,laurenrevere/osf.io,CenterForOpenScience/osf.io,caseyrygt/osf.io,doublebits/osf.io,GageGaskins/osf.io,caneruguz/osf.io,kch8qx/osf.io,jeffreyliu3230/osf.io,haoyuchen1992/osf.io,revanthkolli/osf.io,billyhunt/osf.io,himanshuo/osf.io,kch8qx/osf.io,HarryRybacki/osf.io,petermalcolm/osf.io,alexschiller/osf.io,alexschiller/osf.io,brandonPurvis/osf.io | ---
+++
@@ -3,8 +3,57 @@
var Fangorn = require('fangorn');
-// Although this is empty it should stay here. Fangorn is going to look for figshare in it's config file.
+// Define Fangorn Button Actions
+function _fangornActionColumn (item, col) {
+ var self = this;
+ var buttons = [];
+
+ if (item.kind === 'folder') {
+ buttons.push(
+ {
+ 'name' : '',
+ 'tooltip' : 'Upload files',
+ 'icon' : 'icon-upload-alt',
+ 'css' : 'fangorn-clickable btn btn-default btn-xs',
+ 'onclick' : Fangorn.ButtonEvents._uploadEvent
+ }
+ );
+ }
+
+ if (item.kind === 'file' && item.data.extra && item.data.extra.status === 'public') {
+ buttons.push({
+ 'name' : '',
+ 'tooltip' : 'Download file',
+ 'icon' : 'icon-download-alt',
+ 'css' : 'btn btn-info btn-xs',
+ 'onclick' : Fangorn.ButtonEvents._downloadEvent
+ });
+ }
+
+ if (item.kind === 'file' && item.data.extra && item.data.extra.status !== 'public') {
+ buttons.push({
+ 'name' : '',
+ 'icon' : 'icon-remove',
+ 'tooltip' : 'Delete',
+ 'css' : 'm-l-lg text-danger fg-hover-hide',
+ 'style' : 'display:none',
+ 'onclick' : Fangorn.ButtonEvents._removeEvent
+ });
+ }
+
+ return buttons.map(function(btn) {
+ return m('span', { 'data-col' : item.id }, [ m('i',{
+ 'class' : btn.css,
+ style : btn.style,
+ 'data-toggle' : 'tooltip', title : btn.tooltip, 'data-placement': 'bottom',
+ 'onclick' : function(event){ btn.onclick.call(self, event, item, col); }
+ },
+ [ m('span', { 'class' : btn.icon}, btn.name) ])
+ ]);
+ });
+}
+
Fangorn.config.figshare = {
-
-
+ // Fangorn options are called if functions, so return a thunk that returns the column builder
+ resolveActionColumn: function() {return _fangornActionColumn;}
}; |
05eb13e445bd7adb0a7ca0d0fbb44968093a3f9f | lib/query/query.server.js | lib/query/query.server.js | import createGraph from './lib/createGraph.js';
import prepareForProcess from './lib/prepareForProcess.js';
import hypernova from './hypernova/hypernova.js';
import Base from './query.base';
export default class Query extends Base {
/**
* Retrieves the data.
* @param context
* @returns {*}
*/
fetch(context = {}) {
const node = createGraph(
this.collection,
prepareForProcess(this.body, this.params)
);
return hypernova(node, context.userId, {params: this.params});
}
/**
* @param args
* @returns {*}
*/
fetchOne(...args) {
return _.first(this.fetch(...args));
}
/**
* Gets the count of matching elements.
* @returns {integer}
*/
getCount() {
return this.collection.find(this.body.$filters || {}, {}).count();
}
} | import createGraph from './lib/createGraph.js';
import prepareForProcess from './lib/prepareForProcess.js';
import hypernova from './hypernova/hypernova.js';
import Base from './query.base';
export default class Query extends Base {
/**
* Retrieves the data.
* @param context
* @returns {*}
*/
fetch(context = {}) {
const node = createGraph(
this.collection,
prepareForProcess(this.body, this.params)
);
return hypernova(node, context.userId, {params: this.params});
}
/**
* @param context
* @returns {*}
*/
fetchOne(context = {}) {
context.$options = context.$options || {};
context.$options.limit = 1;
return this.fetch(context);
}
/**
* Gets the count of matching elements.
* @returns {integer}
*/
getCount() {
return this.collection.find(this.body.$filters || {}, {}).count();
}
}
| Improve fetchOne to only return 1 result | Improve fetchOne to only return 1 result
Inspired by meteor's findOne | JavaScript | mit | cult-of-coders/grapher | ---
+++
@@ -19,11 +19,13 @@
}
/**
- * @param args
+ * @param context
* @returns {*}
*/
- fetchOne(...args) {
- return _.first(this.fetch(...args));
+ fetchOne(context = {}) {
+ context.$options = context.$options || {};
+ context.$options.limit = 1;
+ return this.fetch(context);
}
/** |
6215189a16e91c771ed0d4a2f1a83493625480ee | api/server/boot/install.js | api/server/boot/install.js | 'use strict';
var installed=true;
module.exports = function (app) {
if (!installed) {
var User = app.models.User;
var Role = app.models.Role;
var RoleMapping = app.models.RoleMapping;
var cb = function (m) {
console.log(m)
};
User.create([
{username: 'admin', email: 'admin@contact.com', password: 'admin'}
], function (err, users) {
if (err) return cb(err);
//create the admin role
Role.create({
name: 'administrator'
}, function (err, role) {
if (err) cb(err);
//make bob an admin
role.principals.create({
principalType: RoleMapping.USER,
principalId: users[0].id
}, function (err, principal) {
cb(err);
});
});
});
}
}; | 'use strict';
var installed=true;
module.exports = function (app) {
if (!installed) {
var Account = app.models.Account;
var Role = app.models.Role;
var RoleMapping = app.models.RoleMapping;
var cb = function (m) {
console.log(m)
};
Account.create([
{username: 'admin', email: 'admin@contact.com', password: 'admin', firstName: "Super", lastName: "Admin"}
], function (err, Accounts) {
if (err) return cb(err);
//create the admin role
Role.create({
name: 'administrator'
}, function (err, role) {
if (err) cb(err);
//make bob an admin
role.principals.create({
principalType: RoleMapping.Account,
principalId: Accounts[0].id
}, function (err, principal) {
cb(err);
});
});
});
}
}; | Use new Account model to create admin user | Use new Account model to create admin user
| JavaScript | mpl-2.0 | enimiste/ng4-loopback-blog-tutorial,enimiste/ng4-loopback-blog-tutorial,enimiste/ng4-loopback-blog-tutorial | ---
+++
@@ -2,16 +2,16 @@
var installed=true;
module.exports = function (app) {
if (!installed) {
- var User = app.models.User;
+ var Account = app.models.Account;
var Role = app.models.Role;
var RoleMapping = app.models.RoleMapping;
var cb = function (m) {
console.log(m)
};
- User.create([
- {username: 'admin', email: 'admin@contact.com', password: 'admin'}
- ], function (err, users) {
+ Account.create([
+ {username: 'admin', email: 'admin@contact.com', password: 'admin', firstName: "Super", lastName: "Admin"}
+ ], function (err, Accounts) {
if (err) return cb(err);
//create the admin role
@@ -22,8 +22,8 @@
//make bob an admin
role.principals.create({
- principalType: RoleMapping.USER,
- principalId: users[0].id
+ principalType: RoleMapping.Account,
+ principalId: Accounts[0].id
}, function (err, principal) {
cb(err);
}); |
0ab09a056a19f798fae9582f92da5087b79b67a8 | sections/advanced/refs.js | sections/advanced/refs.js | import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => this.input = x}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
\`\`\`
`
export default Refs
| import md from 'components/md'
const Refs = () => md`
## Refs
Passing a \`ref\` prop to a styled component will give you an instance of
the \`StyledComponent\` wrapper, but not to the underlying DOM node.
This is due to how refs work.
It's not possible to call DOM methods, like \`focus\`, on our wrappers directly.
To get a ref to the actual, wrapped DOM node, pass the callback to the \`innerRef\` prop instead.
> We don't support string refs (i.e. \`innerRef="node"\`), since they're already deprecated in React.
This example uses \`innerRef\` to save a ref to the styled input and focuses it once the user
hovers over it.
\`\`\`react
const Input = styled.input\`
padding: 0.5em;
margin: 0.5em;
color: palevioletred;
background: papayawhip;
border: none;
border-radius: 3px;
\`;
class Form extends React.Component {
render() {
return (
<Input
placeholder="Hover here..."
innerRef={x => { this.input = x }}
onMouseEnter={() => this.input.focus()}
/>
);
}
}
render(
<Form />
);
\`\`\`
`
export default Refs
| Add function body around ref assignment | Add function body around ref assignment
| JavaScript | mit | styled-components/styled-components-website,styled-components/styled-components-website | ---
+++
@@ -30,7 +30,7 @@
return (
<Input
placeholder="Hover here..."
- innerRef={x => this.input = x}
+ innerRef={x => { this.input = x }}
onMouseEnter={() => this.input.focus()}
/>
); |
deff306984bfb46dec7d5ac494a7f2bcb18cfc53 | app/resonant-reference-app/views/widgets/MappingView/index.js | app/resonant-reference-app/views/widgets/MappingView/index.js | import Backbone from 'backbone';
import myTemplate from './index.jade';
let MappingView = Backbone.View.extend({
initialize: function () {
},
render: function () {
this.$el.html(myTemplate());
}
});
export default MappingView;
| import Backbone from 'backbone';
import myTemplate from './index.jade';
import candela from '../../../../../src';
let MappingView = Backbone.View.extend({
initialize: function () {
},
render: function () {
const spec = candela.components.Scatter.options;
const fields = spec.filter((opt) => opt.selector && opt.selector[0] === 'field');
console.log(fields);
this.$el.html(myTemplate());
}
});
export default MappingView;
| Gather some information about field selectors | Gather some information about field selectors
| JavaScript | apache-2.0 | Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela | ---
+++
@@ -1,10 +1,16 @@
import Backbone from 'backbone';
import myTemplate from './index.jade';
+import candela from '../../../../../src';
let MappingView = Backbone.View.extend({
initialize: function () {
},
render: function () {
+ const spec = candela.components.Scatter.options;
+ const fields = spec.filter((opt) => opt.selector && opt.selector[0] === 'field');
+
+ console.log(fields);
+
this.$el.html(myTemplate());
}
}); |
bf3bdbe2b7dd247b0854f980f03c9270a6d026b7 | client/mobrender/redux/action-creators/async-update-widget.js | client/mobrender/redux/action-creators/async-update-widget.js | import { createAction } from './create-action'
import * as t from '../action-types'
import AuthSelectors from '~authenticate/redux/selectors'
import Selectors from '../selectors'
export default widget => (dispatch, getState, { api }) => {
dispatch(createAction(t.UPDATE_WIDGET_REQUEST))
const credentials = AuthSelectors(getState()).getCredentials()
const mobilization = Selectors(getState()).getMobilization()
return api
.put(`/mobilizations/${mobilization.id}/widgets/${widget.id}`, { widget }, { headers: credentials })
.then(res => {
dispatch(createAction(t.UPDATE_WIDGET_SUCCESS, res.data))
})
.catch(ex => {
dispatch(createAction(t.UPDATE_WIDGET_FAILURE, error))
return Promise.reject(ex)
})
}
| import { createAction } from './create-action'
import * as t from '../action-types'
import AuthSelectors from '~authenticate/redux/selectors'
import Selectors from '../selectors'
export default widget => (dispatch, getState, { api }) => {
dispatch(createAction(t.UPDATE_WIDGET_REQUEST))
const credentials = AuthSelectors(getState()).getCredentials()
const mobilization = Selectors(getState()).getMobilization()
return api
.put(`/mobilizations/${mobilization.id}/widgets/${widget.id}`, { widget }, { headers: credentials })
.then(res => {
dispatch(createAction(t.UPDATE_WIDGET_SUCCESS, res.data))
})
.catch(ex => {
dispatch(createAction(t.UPDATE_WIDGET_FAILURE, ex))
return Promise.reject(ex)
})
}
| Fix error update widget action | Fix error update widget action
| JavaScript | agpl-3.0 | nossas/bonde-client,nossas/bonde-client,nossas/bonde-client | ---
+++
@@ -15,7 +15,7 @@
dispatch(createAction(t.UPDATE_WIDGET_SUCCESS, res.data))
})
.catch(ex => {
- dispatch(createAction(t.UPDATE_WIDGET_FAILURE, error))
+ dispatch(createAction(t.UPDATE_WIDGET_FAILURE, ex))
return Promise.reject(ex)
})
} |
7e9b2abdd8fb3fbd799f8300a4b22269643831f0 | client/components/Location/Entriex/Creation/index.js | client/components/Location/Entriex/Creation/index.js | var ui = require('tresdb-ui');
var emitter = require('component-emitter');
var template = require('./template.ejs');
var FormView = require('../../../Entry/Form');
// Remember contents of unsubmitted forms during the session.
// Cases where necessary:
// - user fills the form but then exits to the map to search relevant info
// - user fills the form but cancels by accident or to continue later
//
var formMemory = {}; // locId -> entryData
module.exports = function (location) {
// Parameters:
// location
// location object
// NOTE only location id is needed but the view generalization in
// Location/Forms forces location argument
//
var self = this;
emitter(self);
var children = {};
var locationId = location._id;
var startFormMemory = function () {
formMemory[locationId] = {};
};
var getFormMemory = function () {
return formMemory[locationId];
};
var setFormMemory = function (entryData) {
if (entryData && locationId in formMemory) {
formMemory[locationId] = entryData;
}
};
var hasFormMemory = function () {
return (locationId in formMemory);
};
var stopFormMemory = function () {
delete formMemory[locationId];
};
self.bind = function ($mount) {
$mount.html(template({}));
if (hasFormMemory()) {
children.form = new FormView(locationId, getFormMemory());
} else {
children.form = new FormView(locationId);
startFormMemory();
}
children.form.bind($mount.find('.entry-form-container'));
children.form.once('exit', function () {
setFormMemory(children.form.getEntryData({ complete: true }));
self.emit('exit');
});
children.form.on('success', function () {
stopFormMemory();
self.emit('exit');
});
};
self.unbind = function () {
// Memorize form contents on sudden exit if memory not stopped.
if (children.form && hasFormMemory()) {
setFormMemory(children.form.getEntryData({ complete: true }));
}
// Unbind
ui.unbindAll(children);
};
};
| var ui = require('tresdb-ui');
var emitter = require('component-emitter');
var template = require('./template.ejs');
var FormView = require('../../../Entry/Form');
module.exports = function (location) {
// Parameters:
// location
// location object
// NOTE only location id is needed but the view generalization in
// Location/Forms forces the full location argument
//
var self = this;
emitter(self);
var children = {};
var locationId = location._id;
self.bind = function ($mount) {
$mount.html(template({}));
children.form = new FormView(locationId);
children.form.bind($mount.find('.entry-form-container'));
children.form.once('exit', function () {
self.emit('exit');
});
children.form.once('success', function () {
self.emit('exit');
});
};
self.unbind = function () {
ui.unbindAll(children);
children = {};
};
};
| Remove duplicate draft saving features at Location Entries Creation | Remove duplicate draft saving features at Location Entries Creation
| JavaScript | mit | axelpale/tresdb,axelpale/tresdb | ---
+++
@@ -2,20 +2,13 @@
var emitter = require('component-emitter');
var template = require('./template.ejs');
var FormView = require('../../../Entry/Form');
-
-// Remember contents of unsubmitted forms during the session.
-// Cases where necessary:
-// - user fills the form but then exits to the map to search relevant info
-// - user fills the form but cancels by accident or to continue later
-//
-var formMemory = {}; // locId -> entryData
module.exports = function (location) {
// Parameters:
// location
// location object
// NOTE only location id is needed but the view generalization in
- // Location/Forms forces location argument
+ // Location/Forms forces the full location argument
//
var self = this;
emitter(self);
@@ -23,52 +16,22 @@
var locationId = location._id;
- var startFormMemory = function () {
- formMemory[locationId] = {};
- };
- var getFormMemory = function () {
- return formMemory[locationId];
- };
- var setFormMemory = function (entryData) {
- if (entryData && locationId in formMemory) {
- formMemory[locationId] = entryData;
- }
- };
- var hasFormMemory = function () {
- return (locationId in formMemory);
- };
- var stopFormMemory = function () {
- delete formMemory[locationId];
- };
-
self.bind = function ($mount) {
$mount.html(template({}));
- if (hasFormMemory()) {
- children.form = new FormView(locationId, getFormMemory());
- } else {
- children.form = new FormView(locationId);
- startFormMemory();
- }
-
+ children.form = new FormView(locationId);
children.form.bind($mount.find('.entry-form-container'));
children.form.once('exit', function () {
- setFormMemory(children.form.getEntryData({ complete: true }));
self.emit('exit');
});
- children.form.on('success', function () {
- stopFormMemory();
+ children.form.once('success', function () {
self.emit('exit');
});
};
self.unbind = function () {
- // Memorize form contents on sudden exit if memory not stopped.
- if (children.form && hasFormMemory()) {
- setFormMemory(children.form.getEntryData({ complete: true }));
- }
- // Unbind
ui.unbindAll(children);
+ children = {};
};
}; |
358406f12becb20701ad28ec28da3fd974fd4e95 | test/reject-spec.js | test/reject-spec.js | import { expect } from 'chai';
import u from '../lib';
describe('u.reject', () => {
it('freezes the result', () => {
expect(Object.isFrozen(u.reject('a', []))).to.be.true;
});
});
| import { expect } from 'chai';
import u from '../lib';
describe('u.reject', () => {
it('can reject by index', () => {
const result = u.reject((_, index) => index === 1, [3, 4, 5]);
expect(result).to.eql([3, 5]);
});
it('freezes the result', () => {
expect(Object.isFrozen(u.reject('a', []))).to.be.true;
});
});
| Add spec for reject by index | Add spec for reject by index
| JavaScript | mit | substantial/updeep,substantial/updeep | ---
+++
@@ -2,6 +2,12 @@
import u from '../lib';
describe('u.reject', () => {
+ it('can reject by index', () => {
+ const result = u.reject((_, index) => index === 1, [3, 4, 5]);
+
+ expect(result).to.eql([3, 5]);
+ });
+
it('freezes the result', () => {
expect(Object.isFrozen(u.reject('a', []))).to.be.true;
}); |
b0966f22c8ff90a61d87215f3f1e588f4171895c | jest.config.js | jest.config.js | // For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
roots: ["<rootDir>/src/main/javascript"],
collectCoverage: false,
collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"],
coverageDirectory: "<rootDir>/target/js-coverage",
testURL: "http://localhost",
testEnvironment: "jsdom",
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/src/test/javascript/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/src/test/javascript/__mocks__/styleMock.js",
},
};
| // For a detailed explanation regarding each configuration property, visit:
// https://jestjs.io/docs/en/configuration.html
module.exports = {
roots: ["<rootDir>/src/main/javascript"],
collectCoverage: false,
collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"],
coverageDirectory: "<rootDir>/target/js-coverage",
testEnvironment: "jsdom",
testEnvironmentOptions: {
url: "http://localhost"
},
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/src/test/javascript/__mocks__/fileMock.js",
"\\.(css|less)$": "<rootDir>/src/test/javascript/__mocks__/styleMock.js",
},
};
| Migrate deprecated jest testUrl to testEnvironmentOptions.url | Migrate deprecated jest testUrl to testEnvironmentOptions.url
| JavaScript | apache-2.0 | synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung,synyx/urlaubsverwaltung | ---
+++
@@ -6,8 +6,10 @@
collectCoverage: false,
collectCoverageFrom: ["**/*.js", "!**/*.{test,spec}.js", "!**/__tests__/**", "!**/WEB-INF/**"],
coverageDirectory: "<rootDir>/target/js-coverage",
- testURL: "http://localhost",
testEnvironment: "jsdom",
+ testEnvironmentOptions: {
+ url: "http://localhost"
+ },
moduleNameMapper: {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":
"<rootDir>/src/test/javascript/__mocks__/fileMock.js", |
1c99a4bcf99b3af5563bed97beedca61727ae3b7 | js/src/util.js | js/src/util.js | const path = (props, obj) => {
let nested = obj;
const properties = typeof props === 'string' ? props.split('.') : props;
for (let i = 0; i < properties.length; i++) {
nested = nested[properties[i]];
if (nested === undefined) {
return nested;
}
}
return nested;
};
module.exports = {
path,
};
| /** Wrap DOM selector methods:
* document.querySelector,
* document.getElementById,
* document.getElementsByClassName]
*/
const dom = {
query(...args) {
return document.querySelector(args);
},
id(...args) {
return document.getElementById(args);
},
class(...args) {
return document.getElementsByClassName(args);
},
};
/**
* Returns a (nested) propery from an object, or undefined if it doesn't exist
* @param {String | Array} props - An array of properties or a single property
* @param {Object | Array} obj
*/
const path = (props, obj) => {
let nested = obj;
const properties = typeof props === 'string' ? props.split('.') : props;
for (let i = 0; i < properties.length; i++) {
nested = nested[properties[i]];
if (nested === undefined) {
return nested;
}
}
return nested;
};
module.exports = {
dom,
path,
};
| Update dom methods to avoid illegal invocation error. | Update dom methods to avoid illegal invocation error.
| JavaScript | mit | adrice727/accelerator-core-js,opentok/accelerator-core-js,opentok/accelerator-core-js,adrice727/accelerator-core-js | ---
+++
@@ -1,3 +1,25 @@
+/** Wrap DOM selector methods:
+ * document.querySelector,
+ * document.getElementById,
+ * document.getElementsByClassName]
+ */
+const dom = {
+ query(...args) {
+ return document.querySelector(args);
+ },
+ id(...args) {
+ return document.getElementById(args);
+ },
+ class(...args) {
+ return document.getElementsByClassName(args);
+ },
+};
+
+/**
+ * Returns a (nested) propery from an object, or undefined if it doesn't exist
+ * @param {String | Array} props - An array of properties or a single property
+ * @param {Object | Array} obj
+ */
const path = (props, obj) => {
let nested = obj;
const properties = typeof props === 'string' ? props.split('.') : props;
@@ -13,5 +35,6 @@
};
module.exports = {
+ dom,
path,
}; |
b26979135e1d39a8294abd664b8bb23c8b135748 | Gulpfile.js | Gulpfile.js | var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
| var gulp = require('gulp');
var concat = require('gulp-concat');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
var KarmaServer = require('karma').Server;
var bower = require('./bower.json');
var dist_dir = './'
var dist_file = 'launchpad.js';
gulp.task('version', function(){
return gulp.src('template/version.js')
.pipe(template(bower))
.pipe(gulp.dest('src/'));
});
gulp.task('concat', ['version'], function(){
return gulp.src(['src/**.js'])
.pipe(concat(dist_file, { newLine: ';' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('compress', ['concat'], function(){
return gulp.src(dist_file)
.pipe(uglify())
.pipe(rename({ extname: '.min.js' }))
.pipe(gulp.dest(dist_dir));
});
gulp.task('test', ['compress'], function(done){
new KarmaServer({
configFile: __dirname + '/karma.conf.js',
singleRun: true
}, done).start()
});
gulp.task('default', ['compress'], function(){
/* noting to do here */
});
| Create a gulp test target | Create a gulp test target
| JavaScript | mit | dvberkel/LaunchpadJS | ---
+++
@@ -3,6 +3,7 @@
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
var template = require('gulp-template');
+var KarmaServer = require('karma').Server;
var bower = require('./bower.json');
@@ -28,6 +29,13 @@
.pipe(gulp.dest(dist_dir));
});
+gulp.task('test', ['compress'], function(done){
+ new KarmaServer({
+ configFile: __dirname + '/karma.conf.js',
+ singleRun: true
+ }, done).start()
+});
+
gulp.task('default', ['compress'], function(){
/* noting to do here */
}); |
2e79e9b49dd49fb72923a45f44ced0608394c409 | qml/js/logic/channelPageLogic.js | qml/js/logic/channelPageLogic.js | .import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID,
count: 42
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken});
}
// private
function addMessagesToModel(data) {
for(var i=0; i<data.messages.length; i++) {
channelList.append(data.messages[i]);
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
| .import "../applicationShared.js" as Globals
function workerOnMessage(messageObject) {
if(messageObject.apiMethod === 'channels.history') {
addMessagesToModel(messageObject.data);
} else if(messageObject.apiMethod === 'channels.info') {
addChannelInfoToPage(messageObject.data);
} else {
console.log("Unknown api method");
}
}
function loadChannelInfo() {
var arguments = {
channel: channelPage.channelID
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
}
function loadChannelHistory() {
slackWorker.sendMessage({'apiMethod': "channels.history", 'token': Globals.slackToken});
}
// private
function addMessagesToModel(data) {
for(var i=0; i<data.messages.length; i++) {
channelList.append(data.messages[i]);
}
}
function addChannelInfoToPage(data) {
channelPage.channelPurpose = data.channel.purpose.value;
}
| Remove invalid argument of channel.info method | Remove invalid argument of channel.info method
| JavaScript | mit | neversun/Slackfish,neversun/Slackfish | ---
+++
@@ -12,8 +12,7 @@
function loadChannelInfo() {
var arguments = {
- channel: channelPage.channelID,
- count: 42
+ channel: channelPage.channelID
}
slackWorker.sendMessage({'apiMethod': "channels.info", 'token': Globals.slackToken, 'arguments': arguments });
} |
1452ae94cec46f13e888a3e80e2ce54ee552bf3f | dist/babelify-config.js | dist/babelify-config.js | const babelifyConfig = {
presets: [
['@babel/preset-env', {
'useBuiltIns': 'entry',
}],
],
extensions: '.ts',
}
module.exports = babelifyConfig;
| const babelifyConfig = {
presets: [
['@babel/preset-env', {
'useBuiltIns': 'entry',
'targets': {
'firefox': 50,
'chrome': 45,
'opera': 32,
'safari': 11,
},
}],
],
extensions: '.ts',
}
module.exports = babelifyConfig;
| Use explicit targets for babel-preset-env | Use explicit targets for babel-preset-env
This reduces bundle size by 5 KiB.
| JavaScript | agpl-3.0 | threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web,threema-ch/threema-web | ---
+++
@@ -2,6 +2,12 @@
presets: [
['@babel/preset-env', {
'useBuiltIns': 'entry',
+ 'targets': {
+ 'firefox': 50,
+ 'chrome': 45,
+ 'opera': 32,
+ 'safari': 11,
+ },
}],
],
extensions: '.ts', |
2f9a1ff18cd8a495b94dfe9104aa56a2697c3534 | chrome/test/data/extensions/samples/subscribe/feed_finder.js | chrome/test/data/extensions/samples/subscribe/feed_finder.js | find();
window.addEventListener("focus", find);
function find() {
if (window == top) {
// Find all the RSS link elements.
var result = document.evaluate(
'//link[@rel="alternate"][contains(@type, "rss") or ' +
'contains(@type, "atom") or contains(@type, "rdf")]',
document, null, 0, null);
var feeds = [];
var item;
while (item = result.iterateNext())
feeds.push(item.href);
chromium.extension.connect().postMessage(feeds);
}
}
| find();
window.addEventListener("focus", find);
function find() {
if (window == top) {
// Find all the RSS link elements.
var result = document.evaluate(
'//link[@rel="alternate"][contains(@type, "rss") or ' +
'contains(@type, "atom") or contains(@type, "rdf")]',
document, null, 0, null);
var feeds = [];
var item;
while (item = result.iterateNext())
feeds.push(item.href);
chrome.extension.connect().postMessage(feeds);
}
}
| Fix an occurence of 'chromium' that didn't get changed to 'chrome' | Fix an occurence of 'chromium' that didn't get changed to 'chrome'
Review URL: http://codereview.chromium.org/115049
git-svn-id: dd90618784b6a4b323ea0c23a071cb1c9e6f2ac7@15486 4ff67af0-8c30-449e-8e8b-ad334ec8d88c
| JavaScript | bsd-3-clause | wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser,wistoch/meego-app-browser | ---
+++
@@ -14,6 +14,6 @@
while (item = result.iterateNext())
feeds.push(item.href);
- chromium.extension.connect().postMessage(feeds);
+ chrome.extension.connect().postMessage(feeds);
}
} |
f45f0d1e7420f22d92382eb58422c990d8e913d9 | _data/split-aggregated.js | _data/split-aggregated.js | /**
* Splits the aggregated JSON file into individual JSON files per EIN
* Files are then available to Jekyll in the _data folder
*
* TODO Lots of opportunities to simplify - good first pull request 😉
*/
const {chain} = require('stream-chain');
const {parser} = require('stream-json');
const {streamArray} = require('stream-json/streamers/StreamArray');
const fs = require('fs');
try {
const pipeline = chain([
fs.createReadStream('aggregated.json'),
parser(),
streamArray(),
data => {
const doc = data.value;
return doc;
},
]);
let counter = 0;
pipeline.on('data', (data) => {
counter++;
fs.writeFileSync('ein/' + data.ein + '.json', JSON.stringify(data), 'utf-8');
});
pipeline.on('end', () => {
console.log(`Processed ${counter} documents.`);
});
} catch (error) {
console.log(error);
}
| /**
* Splits the aggregated JSON file into individual JSON files per EIN
* Files are then available to Jekyll in the _data folder
*
* TODO Lots of opportunities to simplify - good first pull request 😉
*/
const {chain} = require('stream-chain');
const {parser} = require('stream-json');
const {streamArray} = require('stream-json/streamers/StreamArray');
const fs = require('fs');
try {
const pipeline = chain([
fs.createReadStream('aggregated.json'),
parser(),
streamArray(),
data => {
const doc = data.value;
// Mutute the array and keep only the largest 50 grants
doc.grants.sort((a, b) => b.amount - a.amount);
doc.grants.splice(50);
return doc;
},
]);
let counter = 0;
pipeline.on('data', (data) => {
counter++;
fs.writeFileSync('ein/' + data.ein + '.json', JSON.stringify(data), 'utf-8');
});
pipeline.on('end', () => {
console.log(`Processed ${counter} documents.`);
});
} catch (error) {
console.log(error);
}
| Improve handling of large objects in pre-jekyll processes (cont'd) | Improve handling of large objects in pre-jekyll processes (cont'd)
Reduce grants arrays across all profiles. Goal is to reduce memory spikes when Jekyll attempts to sort the grants array during build time.
| JavaScript | mit | grantmakers/profiles,grantmakers/profiles,grantmakers/profiles | ---
+++
@@ -16,6 +16,10 @@
streamArray(),
data => {
const doc = data.value;
+ // Mutute the array and keep only the largest 50 grants
+ doc.grants.sort((a, b) => b.amount - a.amount);
+ doc.grants.splice(50);
+
return doc;
},
]); |
32697b5e5783148d518017943077814c63725257 | webpack.config.js | webpack.config.js | const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './app/src/app.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.js'
},
plugins: [
// Copy our app's index.html to the build folder.
new CopyWebpackPlugin([
{from: './app/index.html', to: "index.html"}
])
],
module: {
rules: [
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
}
}
]
},
{test: /\.json$/, use: 'json-loader'},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
options: {
limit: 25000,
}
},
{
test: /\.(ttf|svg|eot)$/,
loader: 'file-loader',
options: {
name: 'fonts/[hash].[ext]',
},
},
]
}
}
| const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
module.exports = {
entry: './app/src/app.js',
output: {
path: path.resolve(__dirname, 'build'),
filename: 'app.js'
},
plugins: [
// Copy our app's index.html to the build folder.
new CopyWebpackPlugin([
{from: './app/index.html', to: "index.html"}
])
],
module: {
rules: [
{
test: /\.css$/,
use: [
{loader: 'style-loader'},
{
loader: 'css-loader',
options: {
modules: true,
localIdentName: "[name]__[local]___[hash:base64:5]"
}
}
]
},
{test: /\.json$/, use: 'json-loader'},
{
test: /\.js$/,
exclude: /(node_modules|bower_components)/,
loader: 'babel-loader'
},
{
test: /\.(jpg|png)$/,
loader: 'url-loader',
options: {
limit: 25000,
}
},
{
test: /\.(ttf|svg|eot|otf)$/,
loader: 'file-loader',
options: {
name: 'fonts/[hash].[ext]',
},
},
]
}
}
| Add support for otf fonts | Add support for otf fonts
| JavaScript | mit | Neufund/Contracts | ---
+++
@@ -42,7 +42,7 @@
}
},
{
- test: /\.(ttf|svg|eot)$/,
+ test: /\.(ttf|svg|eot|otf)$/,
loader: 'file-loader',
options: {
name: 'fonts/[hash].[ext]', |
7da24658d59dcb5c64d0777c147ebeba80071489 | express-web-app-example.js | express-web-app-example.js | var compression = require("compression");
var express = require("express");
var handlebars = require("express-handlebars");
// Initialize Express
var app = express();
// Treat "/foo" and "/Foo" as different URLs
app.set("case sensitive routing", true);
// Treat "/foo" and "/foo/" as different URLs
app.set("strict routing", true);
// Default to port 3000
app.set("port", process.env.PORT || 3000);
// Compress all requests
app.use(compression());
// Set Handlebars as the default template language
app.engine("handlebars", handlebars({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
// Serve static contents from the public directory
app.use(express.static(__dirname + "/public"));
// Handle 404 errors
app.use(function(req, res) {
res.type("text/plain");
res.status(404);
res.send("404 - Not Found");
});
// Handle 500 errors
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type("text/plain");
res.status(500);
res.send("500 - Server Error");
});
app.listen(app.get("port"), function() {
console.log("Express started on http://localhost:" + app.get("port") + "; press Ctrl-C to terminate.");
});
| var compression = require("compression");
var express = require("express");
var handlebars = require("express-handlebars");
// Initialize Express
var app = express();
// Treat "/foo" and "/Foo" as different URLs
app.set("case sensitive routing", true);
// Treat "/foo" and "/foo/" as different URLs
app.set("strict routing", true);
// Default to port 3001
app.set("port", process.env.PORT || 3001);
// Compress all requests
app.use(compression());
// Set Handlebars as the default template language
app.engine("handlebars", handlebars({ defaultLayout: "main" }));
app.set("view engine", "handlebars");
// Serve static contents from the public directory
app.use(express.static(__dirname + "/public"));
// Handle 404 errors
app.use(function(req, res) {
res.type("text/plain");
res.status(404);
res.send("404 - Not Found");
});
// Handle 500 errors
app.use(function(err, req, res, next) {
console.error(err.stack);
res.type("text/plain");
res.status(500);
res.send("500 - Server Error");
});
app.listen(app.get("port"), function() {
console.log("Express started on http://localhost:" + app.get("port") + "; press Ctrl-C to terminate.");
});
| Set the default port to 3001 so it doesn't conflict with the default 3000 of express-rest-api-example. | Set the default port to 3001 so it doesn't conflict with the default 3000 of express-rest-api-example.
| JavaScript | mit | stevecochrane/express-web-app-example,stevecochrane/express-web-app-example | ---
+++
@@ -11,8 +11,8 @@
// Treat "/foo" and "/foo/" as different URLs
app.set("strict routing", true);
-// Default to port 3000
-app.set("port", process.env.PORT || 3000);
+// Default to port 3001
+app.set("port", process.env.PORT || 3001);
// Compress all requests
app.use(compression()); |
fa5c360cd1b642ea6ebc696052e321a7b5e62de1 | Assets/scripts/SplashClickHandler.js | Assets/scripts/SplashClickHandler.js | #pragma strict
private var _gameManager : GameManager;
private var _isTriggered = false;
function Start() {
_gameManager = GameManager.Instance();
}
function Update() {
}
function OnMouseDown() {
if (!_isTriggered) {
rollAway();
_isTriggered = true;
}
}
private function rollAway() {
iTween.RotateBy(gameObject, iTween.Hash(
'amount', Vector3(0,0,0.05)
,'easetype', 'easeInOutBack'
,'time', 1.0
));
iTween.MoveTo(gameObject, iTween.Hash(
'position', transform.position + Vector3(-Screen2D.worldWidth(),0,0)
,'easetype', 'easeInOutBack'
,'time', 1.0
));
yield WaitForSeconds(0.5);
_gameManager.SetState(GameManager.GameState.Game);
}
| #pragma strict
private var _gameManager : GameManager;
private var _isTriggered = false;
function Start() {
_gameManager = GameManager.Instance();
}
function Update() {
}
function OnMouseDown() {
if (!_isTriggered) {
rollAway();
_isTriggered = true;
}
}
private function rollAway() {
iTween.RotateBy(gameObject, iTween.Hash(
'amount', Vector3(0,0,0.05)
,'easetype', 'easeInOutBack'
,'time', 1.0
));
iTween.MoveTo(gameObject, iTween.Hash(
'position', transform.position + Vector3(-Screen2D.worldWidth() * 1.5,0,0)
,'easetype', 'easeInOutBack'
,'time', 1.0
));
yield WaitForSeconds(0.5);
_gameManager.SetState(GameManager.GameState.Game);
}
| Move splash screen farther afield on click. | Move splash screen farther afield on click.
| JavaScript | mit | mildmojo/bombay-intervention,mildmojo/bombay-intervention | ---
+++
@@ -25,7 +25,7 @@
,'time', 1.0
));
iTween.MoveTo(gameObject, iTween.Hash(
- 'position', transform.position + Vector3(-Screen2D.worldWidth(),0,0)
+ 'position', transform.position + Vector3(-Screen2D.worldWidth() * 1.5,0,0)
,'easetype', 'easeInOutBack'
,'time', 1.0
)); |
3a270f06122001df0204cce8dbd7697748659183 | app/assets/javascripts/student_profile_v2/academic_summary.js | app/assets/javascripts/student_profile_v2/academic_summary.js | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var styles = {
caption: {
marginRight: 5
},
value: {
fontWeight: 'bold'
},
sparklineContainer: {
paddingLeft: 15,
paddingRight: 15
}
};
var AcademicSummary = window.shared.AcademicSummary = React.createClass({
displayName: 'AcademicSummary',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.number.isRequired),
sparkline: React.PropTypes.element.isRequired
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({},
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
),
dom.div({ style: styles.sparklineContainer }, this.props.sparkline)
);
}
});
})(); | (function() {
window.shared || (window.shared = {});
var dom = window.shared.ReactHelpers.dom;
var createEl = window.shared.ReactHelpers.createEl;
var merge = window.shared.ReactHelpers.merge;
var PropTypes = window.shared.PropTypes;
var styles = {
caption: {
marginRight: 5
},
value: {
fontWeight: 'bold'
},
sparklineContainer: {
paddingLeft: 15,
paddingRight: 15
},
textContainer: {
paddingBottom: 5
}
};
var AcademicSummary = window.shared.AcademicSummary = React.createClass({
displayName: 'AcademicSummary',
propTypes: {
caption: React.PropTypes.string.isRequired,
value: PropTypes.nullable(React.PropTypes.number.isRequired),
sparkline: React.PropTypes.element.isRequired
},
render: function() {
return dom.div({ className: 'AcademicSummary' },
dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
),
dom.div({ style: styles.sparklineContainer }, this.props.sparkline)
);
}
});
})(); | Tweak padding on summary text | Tweak padding on summary text
| JavaScript | mit | studentinsights/studentinsights,studentinsights/studentinsights,jhilde/studentinsights,erose/studentinsights,erose/studentinsights,jhilde/studentinsights,erose/studentinsights,studentinsights/studentinsights,erose/studentinsights,jhilde/studentinsights,jhilde/studentinsights,studentinsights/studentinsights | ---
+++
@@ -15,6 +15,9 @@
sparklineContainer: {
paddingLeft: 15,
paddingRight: 15
+ },
+ textContainer: {
+ paddingBottom: 5
}
};
@@ -29,7 +32,7 @@
render: function() {
return dom.div({ className: 'AcademicSummary' },
- dom.div({},
+ dom.div({ style: styles.textContainer },
dom.span({ style: styles.caption }, this.props.caption + ':'),
dom.span({ style: styles.value }, (this.props.value === undefined) ? 'none' : this.props.value)
), |
725c60ab2f75a085cde14843ad2f6a73eab8cb76 | src/Oro/Bundle/FilterBundle/Resources/public/js/map-filter-module-name.js | src/Oro/Bundle/FilterBundle/Resources/public/js/map-filter-module-name.js | define(function() {
'use strict';
var moduleNameTemplate = 'oro/filter/{{type}}-filter';
var types = {
string: 'choice',
choice: 'select',
single_choice: 'select',
selectrow: 'select-row',
multichoice: 'multiselect',
boolean: 'select'
};
return function(type) {
return moduleNameTemplate.replace('{{type}}', types[type] || type);
};
});
| define(function() {
'use strict';
var moduleNameTemplate = 'oro/filter/{{type}}-filter';
var types = {
string: 'choice',
choice: 'select',
single_choice: 'select',
selectrow: 'select-row',
multichoice: 'multiselect',
boolean: 'select',
dictionary: 'dictionary'
};
return function(type) {
return moduleNameTemplate.replace('{{type}}', types[type] || type);
};
});
| Modify frontend component to load proper filters for both enum and dictionary types | BAP-8615: Modify frontend component to load proper filters for both enum and dictionary types
| JavaScript | mit | geoffroycochard/platform,orocrm/platform,hugeval/platform,Djamy/platform,hugeval/platform,northdakota/platform,ramunasd/platform,trustify/oroplatform,trustify/oroplatform,2ndkauboy/platform,northdakota/platform,ramunasd/platform,orocrm/platform,trustify/oroplatform,Djamy/platform,geoffroycochard/platform,2ndkauboy/platform,ramunasd/platform,2ndkauboy/platform,hugeval/platform,Djamy/platform,orocrm/platform,northdakota/platform,geoffroycochard/platform | ---
+++
@@ -8,7 +8,8 @@
single_choice: 'select',
selectrow: 'select-row',
multichoice: 'multiselect',
- boolean: 'select'
+ boolean: 'select',
+ dictionary: 'dictionary'
};
return function(type) { |
f0b4e3cc48e61b221fe2db7aa8be38d506dfd69e | lib/disproperty.js | lib/disproperty.js | /**
* Disproperty: Disposable properties.
* Copyright (c) 2015 Vladislav Zarakovsky
* MIT license https://github.com/vlazar/disproperty/blob/master/LICENSE
*/
(function(root) {
function disproperty(obj, prop, value) {
return Object.defineProperty(obj, prop, {
configurable: true,
get: function() {
delete this[prop];
return value;
},
set: function(newValue) {
value = newValue;
}
});
}
// Exports: AMD, CommonJS, <script> tag
if (typeof define === 'function' && define.amd) {
module.exports = disproperty;
} else if (typeof exports === 'object') {
define(function() { return disproperty });
} else {
root.disproperty = disproperty;
}
})(this);
| /**
* Disproperty: Disposable properties.
* Copyright (c) 2015 Vladislav Zarakovsky
* MIT license https://github.com/vlazar/disproperty/blob/master/LICENSE
*/
(function(root) {
function disproperty(obj, prop, value) {
return Object.defineProperty(obj, prop, {
configurable: true,
get: function() {
delete this[prop];
return value;
},
set: function(newValue) {
value = newValue;
}
});
}
// Exports: AMD, CommonJS, <script> tag
if (typeof define === 'function' && define.amd) {
define(function() { return disproperty });
} else if (typeof exports === 'object') {
module.exports = disproperty;
} else {
root.disproperty = disproperty;
}
})(this);
| Fix AMD and CommonJS were mixed up | Fix AMD and CommonJS were mixed up
| JavaScript | mit | vlazar/disproperty | ---
+++
@@ -22,9 +22,9 @@
// Exports: AMD, CommonJS, <script> tag
if (typeof define === 'function' && define.amd) {
+ define(function() { return disproperty });
+ } else if (typeof exports === 'object') {
module.exports = disproperty;
- } else if (typeof exports === 'object') {
- define(function() { return disproperty });
} else {
root.disproperty = disproperty;
} |
adc14a177ba3c37618b2f63f8f4ca272cdc94586 | lib/updateModel.js | lib/updateModel.js | var
_ = require('underscore'),
async = require('async'),
curry = require('curry'),
Dependency = require('../models').Dependency,
compHelper = require('./componentHelper'),
compInstall = compHelper.install,
compBuild = compHelper.build;
module.exports = function updateModel (model, data, callback) {
_.each(data, function (val, prop) {
if (prop === 'dependencies') {
model.dependencies = [];
_.each(val, function (version, name) {
model.dependencies.push(new Dependency({
name : name,
version : version
}));
})
} else if (!_.isFunction(model[prop])) {
model[prop] = val;
}
});
model.updated = new Date();
model.type = data['web-audio'].type;
async.series([
curry([data], compInstall),
curry([data], compBuild),
function () {
model.save.apply(model, arguments);
}
], callback);
};
| var
_ = require('underscore'),
async = require('async'),
curry = require('curry'),
Dependency = require('../models').Dependency,
compHelper = require('./componentHelper'),
compInstall = compHelper.install,
compBuild = compHelper.build;
module.exports = function updateModel (model, data, callback) {
_.each(data, function (val, prop) {
if (prop === 'dependencies') {
model.dependencies = [];
_.each(val, function (version, name) {
model.dependencies.push(new Dependency({
name : name,
version : version
}));
})
} else if (!_.isFunction(model[prop])) {
model[prop] = val;
}
});
model.updated = new Date();
model.type = data['web-audio'].type;
async.series([
curry([data], compInstall),
curry([data], compBuild),
function () {
model.save.apply(model, arguments);
}
], function (err) {
callback(err, model);
});
};
| Return model when finishing updating model | Return model when finishing updating model
| JavaScript | mit | web-audio-components/web-audio-components-service | ---
+++
@@ -29,5 +29,7 @@
function () {
model.save.apply(model, arguments);
}
- ], callback);
+ ], function (err) {
+ callback(err, model);
+ });
}; |
347d62cc1eac9d5b58729000df03dc43313708cd | api/script-rules-rule.vm.js | api/script-rules-rule.vm.js | (function() {
var rule = data.rules[parseInt(request.param.num, 10)] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'GET':
response.head(200);
response.end(JSON.stringify(rule, null, ' '));
return;
case 'PUT':
if (request.headers['content-type'].match(/^application\/json/)) {
var newRule = request.query;
if (newRule.isEnabled === false) {
newRule.isDisabled = true;
}
delete newRule.isEnabled;
data.rules.splice(data.rules.indexOf(rule), 1, newRule);
fs.writeFileSync(define.RULES_FILE, JSON.stringify(data.rules, null, ' '));
response.head(200);
response.end(JSON.stringify(newRule));
} else {
response.error(400);
}
return;
case 'DELETE':
child_process.exec('node app-cli.js -mode rule --remove -n ' + request.param.num, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})(); | (function() {
var num = parseInt(request.param.num, 10).toString(10);
var rule = data.rules[num] || null;
if (rule === null) return response.error(404);
switch (request.method) {
case 'GET':
response.head(200);
response.end(JSON.stringify(rule, null, ' '));
return;
case 'PUT':
if (request.headers['content-type'].match(/^application\/json/)) {
var newRule = request.query;
if (newRule.isEnabled === false) {
newRule.isDisabled = true;
}
delete newRule.isEnabled;
data.rules.splice(data.rules.indexOf(rule), 1, newRule);
fs.writeFileSync(define.RULES_FILE, JSON.stringify(data.rules, null, ' '));
response.head(200);
response.end(JSON.stringify(newRule));
} else {
response.error(400);
}
return;
case 'DELETE':
child_process.exec('node app-cli.js -mode rule --remove -n ' + num, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200);
response.end('{}');
});
return;
}
})();
| Fix rule number parameter check | Fix rule number parameter check
A parameter validation of rule number must be effective in preventing
OS command execution.
| JavaScript | mit | polamjag/Chinachu,kanreisa/Chinachu,kounoike/Chinachu,wangjun/Chinachu,tdenc/Chinachu,wangjun/Chinachu,valda/Chinachu,upsilon/Chinachu,xtne6f/Chinachu,xtne6f/Chinachu,miyukki/Chinachu,kounoike/Chinachu,upsilon/Chinachu,wangjun/Chinachu,xtne6f/Chinachu,polamjag/Chinachu,tdenc/Chinachu,miyukki/Chinachu,valda/Chinachu,upsilon/Chinachu,tdenc/Chinachu,kanreisa/Chinachu,valda/Chinachu,kounoike/Chinachu,kanreisa/Chinachu,miyukki/Chinachu,polamjag/Chinachu | ---
+++
@@ -1,6 +1,7 @@
(function() {
- var rule = data.rules[parseInt(request.param.num, 10)] || null;
+ var num = parseInt(request.param.num, 10).toString(10);
+ var rule = data.rules[num] || null;
if (rule === null) return response.error(404);
@@ -30,7 +31,7 @@
return;
case 'DELETE':
- child_process.exec('node app-cli.js -mode rule --remove -n ' + request.param.num, function(err, stdout, stderr) {
+ child_process.exec('node app-cli.js -mode rule --remove -n ' + num, function(err, stdout, stderr) {
if (err) return response.error(500);
response.head(200); |
505fd5d747f1be4c35397b2821559d21147f5fdb | gui/js/main.js | gui/js/main.js | /**
* main.js
*
* Only runs in modern browsers via feature detection
* Requires support for querySelector, classList and addEventListener
*/
if('querySelector' in document && 'classList' in document.createElement('a') && 'addEventListener' in window) {
// Add class "js" to html element
document.querySelector('html').classList.add('js');
}
| Add JS class to html element | Add JS class to html element
| JavaScript | isc | frippz/valleoptik-prototype,frippz/valleoptik-prototype | ---
+++
@@ -0,0 +1,14 @@
+/**
+ * main.js
+ *
+ * Only runs in modern browsers via feature detection
+ * Requires support for querySelector, classList and addEventListener
+ */
+
+if('querySelector' in document && 'classList' in document.createElement('a') && 'addEventListener' in window) {
+
+ // Add class "js" to html element
+ document.querySelector('html').classList.add('js');
+
+}
+ | |
4b25bf1240a13fec21cb6a2b1b4a48aa54588716 | gulp/config.js | gulp/config.js | 'use strict';
module.exports = {
'browserPort' : 3000,
'UIPort' : 3001,
'serverPort' : 3002,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css',
'prodSourcemap' : true
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'fonts': {
'src' : ['app/fonts/**/*'],
'dest': 'build/fonts'
},
'views': {
'watch': [
'app/index.html',
'app/views/**/*.html'
],
'src': 'app/views/**/*.html',
'dest': 'app/js'
},
'gzip': {
'src': 'build/**/*.{html,xml,json,css,js,js.map,css.map}',
'dest': 'build/',
'options': {}
},
'dist': {
'root' : 'build'
},
'browserify': {
'entries' : ['./app/js/main.js'],
'bundleName': 'main.js',
'prodSourcemap' : true
},
'test': {
'karma': 'test/karma.conf.js',
'protractor': 'test/protractor.conf.js'
}
};
| 'use strict';
module.exports = {
'browserPort' : 3000,
'UIPort' : 3001,
'serverPort' : 3002,
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css',
'prodSourcemap' : false
},
'scripts': {
'src' : 'app/js/**/*.js',
'dest': 'build/js'
},
'images': {
'src' : 'app/images/**/*',
'dest': 'build/images'
},
'fonts': {
'src' : ['app/fonts/**/*'],
'dest': 'build/fonts'
},
'views': {
'watch': [
'app/index.html',
'app/views/**/*.html'
],
'src': 'app/views/**/*.html',
'dest': 'app/js'
},
'gzip': {
'src': 'build/**/*.{html,xml,json,css,js,js.map,css.map}',
'dest': 'build/',
'options': {}
},
'dist': {
'root' : 'build'
},
'browserify': {
'entries' : ['./app/js/main.js'],
'bundleName': 'main.js',
'prodSourcemap' : false
},
'test': {
'karma': 'test/karma.conf.js',
'protractor': 'test/protractor.conf.js'
}
};
| Disable sourcemaps in production, by default | Disable sourcemaps in production, by default
| JavaScript | mit | jakemmarsh/angularjs-gulp-browserify-boilerplate,dandiellie/starter,Mojility/angularjs-gulp-browserify-boilerplate,hoodsy/resurgent,dkim-95112/infosys,shoaibkalsekar/angularjs-gulp-browserify-boilerplate,jakemmarsh/angularjs-gulp-browserify-boilerplate,jfarribillaga/angular16,mjpoteet/youtubeapi,Deftunk/TestCircleCi,dandiellie/starter,precisit/angularjs-bootstrap-gulp-browserify-boilerplate,dnaloco/digitala,bnmnjohnson/brandnewmedia-au,adamcolejenkins/dotcom,Cogniance/angular1-boilerplate,dkim-95112/infosys,adamcolejenkins/dotcom,henrymyers/quotes,ropollock/eve-opportunity-ui,precisit/angularjs-bootstrap-gulp-browserify-boilerplate,dnaloco/digitala,tungptvn/tungpts-ng-blog,tungptvn/tungpts-ng-blog,Mojility/angularjs-gulp-browserify-boilerplate,codeweaver-pl/angularjs-gulp-browserify-boilerplate,DrewML/angularjs-gulp-browserify-boilerplate,ray-mash/sbsa-assessment,aneeshd16/Sachin-Sachin,DrewML/angularjs-gulp-browserify-boilerplate,bnmnjohnson/brandnewmedia-au,StrikeForceZero/angularjs-ionic-gulp-browserify-boilerplate,aneeshd16/Sachin-Sachin,dnaloco/digitala,hoodsy/resurgent,jfarribillaga/angular16,tungptvn/tungpts-ng-blog,Deftunk/TestCircleCi,mjpoteet/youtubeapi,dnaloco/digitala,cshaver/angularjs-gulp-browserify-boilerplate,Cogniance/angular1-boilerplate,henrymyers/quotes,ray-mash/sbsa-assessment,ropollock/eve-opportunity-ui,shoaibkalsekar/angularjs-gulp-browserify-boilerplate,StrikeForceZero/angularjs-ionic-gulp-browserify-boilerplate,codeweaver-pl/angularjs-gulp-browserify-boilerplate,bnmnjohnson/brandnewmedia-au,cshaver/angularjs-gulp-browserify-boilerplate | ---
+++
@@ -9,7 +9,7 @@
'styles': {
'src' : 'app/styles/**/*.scss',
'dest': 'build/css',
- 'prodSourcemap' : true
+ 'prodSourcemap' : false
},
'scripts': {
@@ -49,7 +49,7 @@
'browserify': {
'entries' : ['./app/js/main.js'],
'bundleName': 'main.js',
- 'prodSourcemap' : true
+ 'prodSourcemap' : false
},
'test': { |
8ccebea0f071952a40efe56b55853df7b5e21246 | app/models/sequence-item.js | app/models/sequence-item.js | import DS from "ember-data";
export default DS.Model.extend({
page: DS.belongsTo('page'),
section: DS.belongsTo('section'),
sequence: DS.belongsTo('sequence'),
title: DS.attr('string'),
commentary: DS.hasOneFragment('markdown')
});
| import DS from "ember-data";
export default DS.Model.extend({
page: DS.belongsTo('page'),
section: DS.belongsTo('section', {async: true}),
sequence: DS.belongsTo('sequence'),
title: DS.attr('string'),
commentary: DS.hasOneFragment('markdown')
});
| Allow async loading of sections | Allow async loading of sections
| JavaScript | mit | artzte/fightbook-app | ---
+++
@@ -2,7 +2,7 @@
export default DS.Model.extend({
page: DS.belongsTo('page'),
- section: DS.belongsTo('section'),
+ section: DS.belongsTo('section', {async: true}),
sequence: DS.belongsTo('sequence'),
title: DS.attr('string'),
commentary: DS.hasOneFragment('markdown') |
0c410708be0bd112391b0f6f34d0a1cfca39ea85 | addon/engine.js | addon/engine.js | import Engine from 'ember-engines/engine';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
const { modulePrefix } = config;
const Eng = Engine.extend({
modulePrefix,
Resolver,
dependencies: {
services: [
'store',
'session'
]
}
});
loadInitializers(Eng, modulePrefix);
export default Eng;
| import Engine from 'ember-engines/engine';
import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers';
import config from './config/environment';
const { modulePrefix } = config;
const Eng = Engine.extend({
modulePrefix,
Resolver
});
loadInitializers(Eng, modulePrefix);
export default Eng;
| Revert "recieving store and sessions services" | Revert "recieving store and sessions services"
This reverts commit 185961492fca2d78bc8d8372c7d08aae08d2a166.
| JavaScript | mit | scottharris86/external-admin,scottharris86/external-admin | ---
+++
@@ -6,15 +6,7 @@
const { modulePrefix } = config;
const Eng = Engine.extend({
modulePrefix,
- Resolver,
-
- dependencies: {
- services: [
- 'store',
- 'session'
- ]
- }
-
+ Resolver
});
loadInitializers(Eng, modulePrefix); |
fe04cf7da47cb7cec0f127d54dcaa3ad17a960bb | dev/app/components/main/reports/reports.controller.js | dev/app/components/main/reports/reports.controller.js | ReportsController.$inject = [ '$rootScope', 'TbUtils', 'reports' ];
function ReportsController ($rootScope, TbUtils, reports) {
var vm = this;
vm.reports = [
{ title: 'Reporte de Costos', url: 'http://fiasps.unitec.edu:8085/api/Reports/CostsReport/2015' },
{ title: 'Reporte de Horas de Estudiantes', url: 'http://fiasps.unitec.edu:8085/api/Reports/StudentsReport/2015' }
];
vm.selectedReport = 0;
vm.generateReport = generateReport;
function generateReport () {
window.open(vm.reports[vm.selectedReport].url);
}
}
module.exports = { name: 'ReportsController', ctrl: ReportsController }; | ReportsController.$inject = [ '$rootScope', 'TbUtils', 'reports', '$state' ];
function ReportsController ($rootScope, TbUtils, reports, $state) {
if ($rootScope.Role !== 'Admin') $state.go('main.projects');
var vm = this;
vm.reports = [
{ title: 'Reporte de Costos', url: 'http://fiasps.unitec.edu:8085/api/Reports/CostsReport/2015' },
{ title: 'Reporte de Horas de Estudiantes', url: 'http://fiasps.unitec.edu:8085/api/Reports/StudentsReport/2015' }
];
vm.selectedReport = 0;
vm.generateReport = generateReport;
function generateReport () {
window.open(vm.reports[vm.selectedReport].url);
}
}
module.exports = { name: 'ReportsController', ctrl: ReportsController }; | Fix who can access reports state | Fix who can access reports state
| JavaScript | mit | Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Vinculacion-Front-End,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC,Tribu-Anal/Manejo-Horas-de-Vinculacion-UNITEC | ---
+++
@@ -1,6 +1,8 @@
-ReportsController.$inject = [ '$rootScope', 'TbUtils', 'reports' ];
+ReportsController.$inject = [ '$rootScope', 'TbUtils', 'reports', '$state' ];
-function ReportsController ($rootScope, TbUtils, reports) {
+function ReportsController ($rootScope, TbUtils, reports, $state) {
+ if ($rootScope.Role !== 'Admin') $state.go('main.projects');
+
var vm = this;
vm.reports = [ |
e78f92680c92e0dcde41875741ea707ad1031172 | addon/initializers/syncer.js | addon/initializers/syncer.js | import Syncer from '../syncer';
export function initialize(application) {
application.register('syncer:main', Syncer);
}
export default {
name: 'syncer',
before: 'store',
initialize
};
| import Syncer from '../syncer';
export function initialize(application) {
//Register factory for Syncer.
application.register('syncer:main', Syncer);
}
export default {
name: 'syncer',
before: 'ember-data',
initialize
};
| Fix using of `store` initializer | Fix using of `store` initializer
`store` initializer was added to keep backwards compatibility since
ember-data 2.5.0
| JavaScript | mit | Flexberry/ember-flexberry-offline,Flexberry/ember-flexberry-offline | ---
+++
@@ -1,11 +1,12 @@
import Syncer from '../syncer';
export function initialize(application) {
+ //Register factory for Syncer.
application.register('syncer:main', Syncer);
}
export default {
name: 'syncer',
- before: 'store',
+ before: 'ember-data',
initialize
}; |
b1c0ed1868d8d1aabeb8d76f4fe8d6db10403516 | logic/setting/campaign/writeCampaignSettingModelLogic.js | logic/setting/campaign/writeCampaignSettingModelLogic.js | var configuration = require('../../../config/configuration.json')
var utility = require('../../../public/method/utility')
module.exports = {
setCampaignSettingModel: function (redisClient, campaignHashID, payload, callback) {
}
} | var configuration = require('../../../config/configuration.json')
var utility = require('../../../public/method/utility')
module.exports = {
setCampaignSettingModel: function (redisClient, accountHashID, campaignHashID, payload, callback) {
var table
var score = utility.getUnixTimeStamp()
var multi = redisClient.multi()
var settingKeys = Object.keys(configuration.settingEnum)
var tableName = configuration.TableMACampaignModelSettingModel + campaignHashID
multi.hset(tableName, configuration.ConstantSMPriority, payload[configuration.ConstantSMPriority])
var finalCounter = 0
for (var i = 0; i < settingKeys.length; i++) {
if (settingKeys[i] === configuration.settingEnum.Priority)
continue
var key = settingKeys[i]
var scoreMemberArray = []
var keyValueArray = payload[key]
for (var j = 0; j < keyValueArray.length; j++) {
scoreMemberArray.push(score)
scoreMemberArray.push(keyValueArray[j])
}
var counter = 0
for (var j = 0; j < keyValueArray.length; j++) {
table = configuration.TableModel.general.CampaignModel + accountHashID
utility.stringReplace(table, '@', key)
redisClient.zrange(table, '0', '-1', function (err, replies) {
if (err) {
callback(err, null)
return
}
table = configuration.TableModel.general.CampaignModel + accountHashID
for (var k = 0; k < replies.length; k++) {
utility.stringReplace(table, '@', replies[k])
multi.zrem(table, campaignHashID)
}
/* Add to Model List */
table = configuration.TableModel.general.CampaignModel + accountHashID
utility.stringReplace(table, '@', keyValueArray[j])
multi.zadd(table, score, campaignHashID)
/* Add to Model Set */
table = configuration.TableModel.general.CampaignModel
utility.stringReplace(table, '@', keyValueArray[j])
multi.zadd(table, score, campaignHashID)
counter++
})
if (counter == keyValueArray.length) {
/* Model Set */
table = configuration.TableModel.general.CampaignModel + campaignHashID
utility.stringReplace(table, '@', key)
/* Remove from Model Set */
multi.zremrangebyrank(table, '0', '-1')
/* Add to Model Set */
scoreMemberArray.unshift(table)
multi.zadd(scoreMemberArray)
}
}
if (finalCounter == settingKeys.length) {
multi.exec(function (err, replies) {
if (err) {
callback(err, null)
return
}
callback(null, configuration.message.setting.campaign.set.successful)
})
}
}
}
} | Implement Create a Campaign Model Setting Dynamically | Implement Create a Campaign Model Setting Dynamically
| JavaScript | mit | Flieral/Announcer-Service,Flieral/Announcer-Service | ---
+++
@@ -2,7 +2,79 @@
var utility = require('../../../public/method/utility')
module.exports = {
- setCampaignSettingModel: function (redisClient, campaignHashID, payload, callback) {
+ setCampaignSettingModel: function (redisClient, accountHashID, campaignHashID, payload, callback) {
+ var table
+ var score = utility.getUnixTimeStamp()
+ var multi = redisClient.multi()
+ var settingKeys = Object.keys(configuration.settingEnum)
+ var tableName = configuration.TableMACampaignModelSettingModel + campaignHashID
+ multi.hset(tableName, configuration.ConstantSMPriority, payload[configuration.ConstantSMPriority])
+
+ var finalCounter = 0
+ for (var i = 0; i < settingKeys.length; i++) {
+ if (settingKeys[i] === configuration.settingEnum.Priority)
+ continue
+
+ var key = settingKeys[i]
+ var scoreMemberArray = []
+ var keyValueArray = payload[key]
+
+ for (var j = 0; j < keyValueArray.length; j++) {
+ scoreMemberArray.push(score)
+ scoreMemberArray.push(keyValueArray[j])
+ }
+
+ var counter = 0
+ for (var j = 0; j < keyValueArray.length; j++) {
+ table = configuration.TableModel.general.CampaignModel + accountHashID
+ utility.stringReplace(table, '@', key)
+
+ redisClient.zrange(table, '0', '-1', function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+
+ table = configuration.TableModel.general.CampaignModel + accountHashID
+ for (var k = 0; k < replies.length; k++) {
+ utility.stringReplace(table, '@', replies[k])
+ multi.zrem(table, campaignHashID)
+ }
+
+ /* Add to Model List */
+ table = configuration.TableModel.general.CampaignModel + accountHashID
+ utility.stringReplace(table, '@', keyValueArray[j])
+ multi.zadd(table, score, campaignHashID)
+ /* Add to Model Set */
+ table = configuration.TableModel.general.CampaignModel
+ utility.stringReplace(table, '@', keyValueArray[j])
+ multi.zadd(table, score, campaignHashID)
+
+ counter++
+ })
+
+ if (counter == keyValueArray.length) {
+ /* Model Set */
+ table = configuration.TableModel.general.CampaignModel + campaignHashID
+ utility.stringReplace(table, '@', key)
+ /* Remove from Model Set */
+ multi.zremrangebyrank(table, '0', '-1')
+ /* Add to Model Set */
+ scoreMemberArray.unshift(table)
+ multi.zadd(scoreMemberArray)
+ }
+ }
+
+ if (finalCounter == settingKeys.length) {
+ multi.exec(function (err, replies) {
+ if (err) {
+ callback(err, null)
+ return
+ }
+ callback(null, configuration.message.setting.campaign.set.successful)
+ })
+ }
+ }
}
} |
3b3d8b40a5b4dda16440a0262246aa6ff8da4332 | gulp/watch.js | gulp/watch.js | import gulp from 'gulp';
import {build} from './build';
import {test} from './test';
import {makeParser, fixParser} from './parse';
const allSrcGlob = [
'src/**/*.js',
'!src/static/antlr4/parsers/**/*.js',
'test/**/*.js',
];
const allBuildGlob = [
'build/src/*.js',
'build/test/**/*.js',
];
const grammarGlob = [
'src/static/antlr4/grammars/**/*.g4',
'build/src/static/antlr4/Translator.js',
];
const dataGlob = [
'src/static/data/**/*.*',
];
export const watch = done => {
gulp.watch(allSrcGlob, build);
gulp.watch(allBuildGlob, test);
gulp.watch(grammarGlob, gulp.series(makeParser, fixParser));
gulp.watch(dataGlob, test);
done();
};
gulp.task('watch', watch);
| import gulp from 'gulp';
import {build} from './build';
import {test} from './test';
import {makeParser, fixParser} from './parse';
const allSrcGlob = [
'src/**/*.js',
'!src/static/antlr4/parsers/**/*.js',
'test/**/*.js',
];
const allBuildGlob = [
'build/src/*.js',
'build/test/**/*.js',
];
const grammarGlob = [
'src/static/antlr4/grammars/**/*.g4',
'build/src/static/antlr4/Translator.js',
];
const dataGlob = [
'src/static/data/**/*.*',
'src/static/antlr4/parsers/TestudocParser.js',
];
export const watch = done => {
gulp.watch(allSrcGlob, build);
gulp.watch(allBuildGlob, test);
gulp.watch(grammarGlob, gulp.series(makeParser, fixParser));
gulp.watch(dataGlob, test);
done();
};
gulp.task('watch', watch);
| Test again when TestudocParser is recreated | Test again when TestudocParser is recreated
| JavaScript | mit | jlenoble/ecmascript-parser | ---
+++
@@ -18,6 +18,7 @@
];
const dataGlob = [
'src/static/data/**/*.*',
+ 'src/static/antlr4/parsers/TestudocParser.js',
];
export const watch = done => { |
dc39fb557e985ee534bc8ae2e12d0c6c83efe4fe | gulp/build.js | gulp/build.js | 'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, { read: false })
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
var bundleStream = browserify(paths.app + '/js/main.js')
.transform(istanbul)
.bundle();
bundleStream
.pipe(source(paths.app + '/js/main.js'))
.pipe($.rename('main.js'))
.pipe(gulp.dest(paths.tmp + '/js/'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
| 'use strict';
var gulp = require('gulp');
var config = require('./_config.js');
var paths = config.paths;
var $ = config.plugins;
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var istanbul = require('browserify-istanbul');
gulp.task('clean', function () {
return gulp.src(paths.tmp, { read: false })
.pipe($.rimraf());
});
gulp.task('build', ['index.html', 'js', 'css']);
gulp.task('index.html', function () {
return gulp.src(paths.app + '/index.jade')
.pipe($.jade({
pretty: true
}))
.pipe(gulp.dest(paths.tmp));
});
gulp.task('jade', function () {
return gulp.src(paths.app + '/*.html')
.pipe(gulp.dest(paths.tmp));
});
gulp.task('js', function () {
var bundleStream = browserify(paths.app + '/js/main.js')
.transform(istanbul)
.bundle();
return bundleStream
.pipe(source(paths.app + '/js/main.js'))
.pipe($.rename('main.js'))
.pipe(gulp.dest(paths.tmp + '/js/'));
});
gulp.task('css', function () {
// FIXME
return gulp.src('mama');
});
| Fix JS task to be async. Should fix travis. | Fix JS task to be async. Should fix travis.
| JavaScript | mpl-2.0 | learnfwd/learnfwd.com,learnfwd/learnfwd.com,learnfwd/learnfwd.com | ---
+++
@@ -35,7 +35,7 @@
.transform(istanbul)
.bundle();
- bundleStream
+ return bundleStream
.pipe(source(paths.app + '/js/main.js'))
.pipe($.rename('main.js'))
.pipe(gulp.dest(paths.tmp + '/js/')); |
cac5bc79f106a67c56c00448a8b4408c0f31f6f3 | lib/request.js | lib/request.js | var api = require('../config/api.json');
var appId = process.env.APPLICATION_ID;
var https = require('https');
var querystring = require('querystring');
module.exports = function requestExports(config) {
return request.bind(null, api[config]);
};
function request(config, endpoint, body, callback) {
body.application_id = appId;
body = querystring.stringify(body);
var options = {
hostname: config.hostname,
path: config[endpoint].path,
method: config[endpoint].method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': body.length
}
};
var req = https.request(options, function httpsRequestCb(response) {
var data = [];
response.setEncoding('utf8');
response.on('data', Array.prototype.push.bind(data));
response.on('end', function httpsRequestEndCb() {
var result = JSON.parse(data.join('') || '{}');
switch (result.status) {
case 'ok':
callback(null, result.data);
break;
case 'error':
callback(new Error(result.error.message));
break;
default:
callback(null, null);
break;
}
});
});
req.once('error', callback);
req.write(body);
req.end();
}
| var api = require('../config/api.json');
var appId = process.env.APPLICATION_ID;
var https = require('https');
var querystring = require('querystring');
var util = require('util');
module.exports = function requestExports(config) {
return request.bind(null, api[config]);
};
function request(config, endpoint, body, callback) {
body.application_id = appId;
body = querystring.stringify(body);
var options = {
hostname: config.hostname,
path: config[endpoint].path,
method: config[endpoint].method,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': body.length
}
};
var req = https.request(options, function httpsRequestCb(response) {
var data = [];
response.setEncoding('utf8');
response.on('data', Array.prototype.push.bind(data));
response.on('end', function httpsRequestEndCb() {
var result = JSON.parse(data.join('') || '{}');
switch (result.status) {
case 'ok':
callback(null, result.data);
break;
case 'error':
var errorFormat = util.format(
'%d %s: %s=%j',
result.error.code,
result.error.message,
result.error.field,
result.error.value
);
callback(new Error(errorFormat));
break;
default:
callback(null, null);
break;
}
});
});
req.once('error', callback);
req.write(body);
req.end();
}
| Include all the fields of a wargaming error. | Include all the fields of a wargaming error.
| JavaScript | isc | CodeMan99/wotblitz.js | ---
+++
@@ -2,6 +2,7 @@
var appId = process.env.APPLICATION_ID;
var https = require('https');
var querystring = require('querystring');
+var util = require('util');
module.exports = function requestExports(config) {
return request.bind(null, api[config]);
@@ -34,7 +35,15 @@
callback(null, result.data);
break;
case 'error':
- callback(new Error(result.error.message));
+ var errorFormat = util.format(
+ '%d %s: %s=%j',
+ result.error.code,
+ result.error.message,
+ result.error.field,
+ result.error.value
+ );
+
+ callback(new Error(errorFormat));
break;
default:
callback(null, null); |
37dc947297bb6b630e3442cd93451ab2a88a791b | app/instance-initializers/ember-href-to.js | app/instance-initializers/ember-href-to.js | import Em from 'ember';
function _getNormalisedRootUrl(router) {
let rootURL = router.rootURL;
if(rootURL.charAt(rootURL.length - 1) !== '/') {
rootURL = rootURL + '/';
}
return rootURL;
}
export default {
name: 'ember-href-to',
initialize: function(applicationInstance) {
let router = applicationInstance.container.lookup('router:main');
let rootURL = _getNormalisedRootUrl(router);
let $body = Em.$(document.body);
$body.off('click.href-to', 'a');
$body.on('click.href-to', 'a', function(e) {
let $target = Em.$(e.currentTarget);
let handleClick = (e.which === 1 && !e.ctrlKey && !e.metaKey);
if(handleClick && !$target.hasClass('ember-view') && Em.isNone($target.attr('data-ember-action'))) {
let url = $target.attr('href');
if(url && url.indexOf(rootURL) === 0) {
url = url.substr(rootURL.length - 1);
if(router.router.recognizer.recognize(url)) {
router.handleURL(url);
router.router.updateURL(url);
return false;
}
}
}
return true;
});
}
};
| import Em from 'ember';
function _getNormalisedRootUrl(router) {
let rootURL = router.rootURL;
if(rootURL.charAt(rootURL.length - 1) !== '/') {
rootURL = rootURL + '/';
}
return rootURL;
}
function _lookupRouter(applicationInstance) {
const container = 'lookup' in applicationInstance ? applicationInstance : applicationInstance.container;
return container.lookup('router:main');
}
export default {
name: 'ember-href-to',
initialize: function(applicationInstance) {
let router = _lookupRouter(applicationInstance);
let rootURL = _getNormalisedRootUrl(router);
let $body = Em.$(document.body);
$body.off('click.href-to', 'a');
$body.on('click.href-to', 'a', function(e) {
let $target = Em.$(e.currentTarget);
let handleClick = (e.which === 1 && !e.ctrlKey && !e.metaKey);
if(handleClick && !$target.hasClass('ember-view') && Em.isNone($target.attr('data-ember-action'))) {
let url = $target.attr('href');
if(url && url.indexOf(rootURL) === 0) {
url = url.substr(rootURL.length - 1);
if(router.router.recognizer.recognize(url)) {
router.handleURL(url);
router.router.updateURL(url);
return false;
}
}
}
return true;
});
}
};
| Fix router lookup to avoid deprecations in ember >= 2 | Fix router lookup to avoid deprecations in ember >= 2
| JavaScript | apache-2.0 | intercom/ember-href-to,intercom/ember-href-to | ---
+++
@@ -8,10 +8,15 @@
return rootURL;
}
+function _lookupRouter(applicationInstance) {
+ const container = 'lookup' in applicationInstance ? applicationInstance : applicationInstance.container;
+ return container.lookup('router:main');
+}
+
export default {
name: 'ember-href-to',
initialize: function(applicationInstance) {
- let router = applicationInstance.container.lookup('router:main');
+ let router = _lookupRouter(applicationInstance);
let rootURL = _getNormalisedRootUrl(router);
let $body = Em.$(document.body);
|
8a199d43edacae40ea7c1f6395dc861f196a59ba | app/GUI/Filter/activeTags.js | app/GUI/Filter/activeTags.js | import React, { Component, PropTypes } from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
export default class ActiveTags extends Component {
removeTag(tag) {
const { filterObject, position, setFilter } = this.props;
const temp = filterObject[position];
temp.delete(tag);
const newFilterObject =
Object.assign({}, filterObject, { [position]: temp });
setFilter(newFilterObject);
}
render() {
const { tags } = this.props;
const buttons = [];
Array.from(tags).sort().map((t, i) => {
buttons.push(
<Button bsSize={'xsmall'}
key={'tag' + i}
onClick={() => { this.removeTag(t); }}
>
× {t}
</Button>);
});
const content = [];
if (buttons.length) {
content.push(<ButtonGroup key={'bg'}>{buttons}</ButtonGroup>);
} else {
content.push(<p key={'p'}><small>No active tags.</small></p>);
}
return (<div>
{content}
</div>);
}
}
ActiveTags.propTypes = {
filterObject: PropTypes.object,
position: PropTypes.string,
setFilter: PropTypes.func,
tags: PropTypes.object,
};
| import React, { Component, PropTypes } from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
export default class ActiveTags extends Component {
removeTag(tag) {
const { filterObject, position, setFilter } = this.props;
const temp = filterObject[position];
temp.delete(tag);
const newFilterObject =
Object.assign({}, filterObject, { [position]: temp });
setFilter(newFilterObject);
}
render() {
const { tags } = this.props;
const buttons = [];
Array.from(tags).sort().map((t, i) => {
buttons.push(
<Button bsSize={'xsmall'}
key={'tag' + i}
style={{ marginTop: '-1px', borderRadius: '0px' }}
onClick={() => { this.removeTag(t); }}
>
× {t}
</Button>);
});
const content = [];
if (buttons.length) {
content.push(<ButtonGroup key={'bg'}>{buttons}</ButtonGroup>);
} else {
content.push(<p key={'p'}><small>No active tags.</small></p>);
}
return (<div>
{content}
</div>);
}
}
ActiveTags.propTypes = {
filterObject: PropTypes.object,
position: PropTypes.string,
setFilter: PropTypes.func,
tags: PropTypes.object,
};
| Change active tags button layout. | Change active tags button layout.
| JavaScript | mit | bgrsquared/places,bgrsquared/places,bgrsquared/places | ---
+++
@@ -19,6 +19,7 @@
buttons.push(
<Button bsSize={'xsmall'}
key={'tag' + i}
+ style={{ marginTop: '-1px', borderRadius: '0px' }}
onClick={() => { this.removeTag(t); }}
>
× {t} |
b3ee9cd866a0669bfe3776b66a2e2edc7f64931d | app/components/Views/Home.js | app/components/Views/Home.js | /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 01 June, 2016
* License: MIT
*
* React App Main Layout Component
*/
import React from "react";
import Header from "./Header/Header";
import Jumbotron from "./Section/Jumbotron";
import Footer from "./Footer/Footer";
export default
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<Header/>
<section class="container poster-section">
<Jumbotron/>
{this.props.children}
</section>
<Footer/>
</div>
);
}
}
| /**
* Poster v0.1.0
* A React webapp to list upcoming movies and maintain a watchlist, powered by TMDb
*
* Author: Kushal Pandya <kushalspandya@gmail.com> (https://doublslash.com)
* Date: 01 June, 2016
* License: MIT
*
* React App Main Layout Component
*/
import React from "react";
import Header from "./Header/Header";
import Jumbotron from "./Section/Jumbotron";
import Footer from "./Footer/Footer";
export default
class Home extends React.Component {
constructor() {
super();
}
render() {
return (
<div>
<Header/>
<section class="container poster-section">
<Jumbotron hide={this.props.params.movieId ? true : false}/>
{this.props.children}
</section>
<Footer/>
</div>
);
}
}
| Hide Jumbotron on movie details page. | Hide Jumbotron on movie details page.
| JavaScript | mit | kushalpandya/poster,kushalpandya/poster | ---
+++
@@ -26,7 +26,7 @@
<div>
<Header/>
<section class="container poster-section">
- <Jumbotron/>
+ <Jumbotron hide={this.props.params.movieId ? true : false}/>
{this.props.children}
</section>
<Footer/> |
d9504ba850c26c779bceae62ea5c903c8f505126 | library/Denkmal/library/Denkmal/Component/MessageList/All.js | library/Denkmal/library/Denkmal/Component/MessageList/All.js | /**
* @class Denkmal_Component_MessageList_All
* @extends Denkmal_Component_MessageList_Abstract
*/
var Denkmal_Component_MessageList_All = Denkmal_Component_MessageList_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageList_All',
ready: function() {
this.bindStream('global-internal', cm.model.types.CM_Model_StreamChannel_Message, 'message-create', function(message) {
this._addMessage(message);
});
},
/**
* @param {Object} message
*/
_addMessage: function(message) {
this.renderTemplate('template-message', {
id: message.id,
created: message.created,
venue: message.venue.name,
hasText: message.text !== null,
text: message.text,
hasImage: message.image !== null,
imageUrl: (message.image !== null) ? message.image['url-thumb'] : null
}).appendTo(this.$('.messageList'));
}
});
| /**
* @class Denkmal_Component_MessageList_All
* @extends Denkmal_Component_MessageList_Abstract
*/
var Denkmal_Component_MessageList_All = Denkmal_Component_MessageList_Abstract.extend({
/** @type String */
_class: 'Denkmal_Component_MessageList_All',
ready: function() {
this.bindStream('global-internal', cm.model.types.CM_Model_StreamChannel_Message, 'message-create', function(message) {
this._addMessage(message);
});
},
/**
* @param {Object} message
*/
_addMessage: function(message) {
if (this.$('.messageList > .message[data-id="' + message.id + '"]').length > 0) {
return;
}
this.renderTemplate('template-message', {
id: message.id,
created: message.created,
venue: message.venue.name,
hasText: message.text !== null,
text: message.text,
hasImage: message.image !== null,
imageUrl: (message.image !== null) ? message.image['url-thumb'] : null
}).appendTo(this.$('.messageList'));
}
});
| Add check to not add messages twice | Add check to not add messages twice
| JavaScript | mit | njam/denkmal.org,njam/denkmal.org,denkmal/denkmal.org,njam/denkmal.org,fvovan/denkmal.org,fvovan/denkmal.org,denkmal/denkmal.org,njam/denkmal.org,fvovan/denkmal.org,fvovan/denkmal.org,denkmal/denkmal.org,denkmal/denkmal.org,fvovan/denkmal.org,njam/denkmal.org,denkmal/denkmal.org | ---
+++
@@ -17,6 +17,9 @@
* @param {Object} message
*/
_addMessage: function(message) {
+ if (this.$('.messageList > .message[data-id="' + message.id + '"]').length > 0) {
+ return;
+ }
this.renderTemplate('template-message', {
id: message.id,
created: message.created, |
979fc3418b738838ee7187a11cf28ac65371cfb6 | app/components/validations-errors.js | app/components/validations-errors.js | import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['error-messages'],
didInsertElement: function () {
this._super();
Ember.run.next(function(){
var errors = this.get('validationErrors')
, errorsKeys = Ember.keys(errors);
errorsKeys.forEach(function(property){
Ember.addObserver(errors, property, this, function(){
this.validationsErrorsChanged(property);
}, this);
}.bind(this));
}.bind(this));
},
validationsErrorsChanged: function(key){
if(this.setList(key)) {
this.$().fadeIn('fast');
} else {
this.$().fadeOut('fast');
}
},
setList: function (key){
var validationErrors = this.get('validationErrors');
var errList = this.get('errList');
if (!Ember.isArray(errList)){
errList = [];
this.set('errList', errList);
}
var error = errList.findBy('key', key);
if (error){
error.set('errors', validationErrors.get(key));
}
else{
errList.addObject(Ember.Object.create({key:key, errors: validationErrors.get(key)}));
}
return errList.any(function (error){
return error.get('errors').length > 0;
});
}
});
| import Ember from 'ember';
export default Ember.Component.extend({
classNames: ['error-messages'],
didInsertElement: function () {
this._super();
Ember.run.next(function(){
var errors = this.get('validationErrors')
, errorsKeys = Ember.keys(errors);
errorsKeys.forEach(function(property){
Ember.addObserver(errors, property, this, function(){
Ember.run.debounce(this, function (){
this.validationsErrorsChanged(property);
}, 200);
}, this);
}.bind(this));
}.bind(this));
},
validationsErrorsChanged: function(key){
if(this.setList(key)) {
this.$().fadeIn('fast');
} else {
this.$().fadeOut('fast');
}
},
setList: function (key){
var validationErrors = this.get('validationErrors');
var errList = this.get('errList');
if (!Ember.isArray(errList)){
errList = [];
this.set('errList', errList);
}
var error = errList.findBy('key', key);
if (error){
error.set('errors', validationErrors.get(key));
}
else{
errList.addObject(Ember.Object.create({key:key, errors: validationErrors.get(key)}));
}
return errList.any(function (error){
return error.get('errors').length > 0;
});
}
});
| Fix problem if it takes long to valdiate | Fix problem if it takes long to valdiate
| JavaScript | mit | alexferreira/ember-cli-validations-errors | ---
+++
@@ -10,7 +10,9 @@
errorsKeys.forEach(function(property){
Ember.addObserver(errors, property, this, function(){
- this.validationsErrorsChanged(property);
+ Ember.run.debounce(this, function (){
+ this.validationsErrorsChanged(property);
+ }, 200);
}, this);
}.bind(this));
}.bind(this)); |
26cd6df2d95a4d81968d01b06144d6aeddcf5863 | index.js | index.js | module.exports = compressible
compressible.specs =
compressible.specifications = require('./specifications.json')
compressible.regex =
compressible.regexp = /json|text|javascript|dart|ecmascript|xml/
compressible.get = get
function compressible(type) {
if (!type || typeof type !== "string") return false
var i = type.indexOf(';')
, spec = compressible.specs[i < 0 ? type : type.slice(0, i)]
return spec ? spec.compressible : compressible.regex.test(type)
}
function get(type) {
if (!type || typeof type !== "string") return {
compressible: false,
sources: [],
notes: "Invalid type."
}
var spec = compressible.specs[type.split(';')[0]]
return spec ? spec : {
compressible: compressible.regex.test(type),
sources: ["compressible.regex"],
notes: "Automatically generated via regex."
}
} | module.exports = compressible
compressible.specs =
compressible.specifications = require('./specifications.json')
compressible.regex =
compressible.regexp = /json|text|javascript|dart|ecmascript|xml/
compressible.get = get
function compressible(type) {
if (!type || typeof type !== "string") return false
var i = type.indexOf(';')
, spec = compressible.specs[~i ? type.slice(0, i) : type]
return spec ? spec.compressible : compressible.regex.test(type)
}
function get(type) {
if (!type || typeof type !== "string") return {
compressible: false,
sources: [],
notes: "Invalid type."
}
var spec = compressible.specs[type.split(';')[0]]
return spec ? spec : {
compressible: compressible.regex.test(type),
sources: ["compressible.regex"],
notes: "Automatically generated via regex."
}
} | Use ~ operator to check for -1 | [minor] Use ~ operator to check for -1
This is mainly a style change as other expressjs modules use this.
Performance is mostly indifferent.
However, this tests specifically for -1.
| JavaScript | mit | jshttp/compressible | ---
+++
@@ -11,7 +11,7 @@
function compressible(type) {
if (!type || typeof type !== "string") return false
var i = type.indexOf(';')
- , spec = compressible.specs[i < 0 ? type : type.slice(0, i)]
+ , spec = compressible.specs[~i ? type.slice(0, i) : type]
return spec ? spec.compressible : compressible.regex.test(type)
}
|
683737e2e6bc4689c26afdb573d8ca0b581fa5c6 | client/config/bootstrap.js | client/config/bootstrap.js | /**
* Bootstrap
* Client entry point
* @flow
*/
// Polyfills
import 'babel/polyfill'
// Modules
import React from 'react'
import ReactDOM from 'react-dom'
import { Router } from 'react-router'
import { createHistory } from 'history'
import ReactRouterRelay from 'react-router-relay'
// Routes
import routes from './routes'
// Initialize dependencies
const history = createHistory()
// Mount the app
const instance = ReactDOM.render(
<Router
createElement={ReactRouterRelay.createElement}
history={history}
routes={routes}
/>,
document.getElementById('app')
)
// Fix hotloading for pure components
// @TODO: handle updating the routes
if (module.hot) {
module.hot.accept('./routes', () => {
instance.forceUpdate()
})
}
| /**
* Bootstrap
* Client entry point
* @flow
*/
// Polyfills
import 'babel/polyfill'
// Modules
import React from 'react'
import Relay from 'react-relay'
import ReactDOM from 'react-dom'
import { Router } from 'react-router'
import { createHistory } from 'history'
import ReactRouterRelay from 'react-router-relay'
// Routes
import routes from './routes'
// Configure Relay's network layer to include cookies
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin'
})
)
// Initialize dependencies
const history = createHistory()
// Mount the app
const instance = ReactDOM.render(
<Router
createElement={ReactRouterRelay.createElement}
history={history}
routes={routes}
/>,
document.getElementById('app')
)
// Fix hotloading for pure components
// @TODO: handle updating the routes
if (module.hot) {
module.hot.accept('./routes', () => {
instance.forceUpdate()
})
}
| Update Relay to send cookies | Update Relay to send cookies
| JavaScript | apache-2.0 | cesarandreu/bshed,cesarandreu/bshed | ---
+++
@@ -9,6 +9,7 @@
// Modules
import React from 'react'
+import Relay from 'react-relay'
import ReactDOM from 'react-dom'
import { Router } from 'react-router'
import { createHistory } from 'history'
@@ -16,6 +17,13 @@
// Routes
import routes from './routes'
+
+// Configure Relay's network layer to include cookies
+Relay.injectNetworkLayer(
+ new Relay.DefaultNetworkLayer('/graphql', {
+ credentials: 'same-origin'
+ })
+)
// Initialize dependencies
const history = createHistory() |
67aaa90ac0564920d8a65db7129a0e32804bdaea | index.js | index.js | import express from 'express';
import http from 'http';
import {renderFile} from 'ejs';
import request from 'superagent';
var app = express();
var FRIGG_API = process.env.FRIGG_API || 'https://ci.frigg.io';
app.engine('html', renderFile);
app.set('view engine', 'html');
app.set('views', '' + __dirname);
app.use('/static', express.static(__dirname + '/public'));
app.get('/api/*', (req, res, next) => {
request(FRIGG_API + req.originalUrl)
.end((err, apiRes) => {
if (err) return next(err);
res.json(apiRes.body);
});
});
app.get('*', (req, res) => {
res.render('index', {});
});
var server = http.Server(app);
var port = process.env.PORT || 3000;
server.listen(port, () => {
console.log('listening on *:' + port);
});
| import express from 'express';
import http from 'http';
import {renderFile} from 'ejs';
import request from 'superagent';
var app = express();
var FRIGG_API = process.env.FRIGG_API || 'https://ci.frigg.io';
app.engine('html', renderFile);
app.set('view engine', 'html');
app.set('views', '' + __dirname);
app.use('/static', express.static(__dirname + '/public'));
var responses = {};
app.get('/api/*', (req, res, next) => {
var url = req.originalUrl;
if (responses.hasOwnProperty(url)) {
return res.json(responses[url]);
}
request(FRIGG_API + url)
.end((err, apiRes) => {
if (err) return next(err);
responses[url] = apiRes.body;
res.json(apiRes.body);
});
});
app.get('*', (req, res) => {
res.render('index', {});
});
var server = http.Server(app);
var port = process.env.PORT || 3000;
server.listen(port, () => {
console.log('listening on *:' + port);
});
| Add caching of proxy requests in dev server | Add caching of proxy requests in dev server
| JavaScript | mit | frigg/frigg-hq-frontend,frigg/frigg-hq-frontend | ---
+++
@@ -12,10 +12,17 @@
app.set('views', '' + __dirname);
app.use('/static', express.static(__dirname + '/public'));
+var responses = {};
+
app.get('/api/*', (req, res, next) => {
- request(FRIGG_API + req.originalUrl)
+ var url = req.originalUrl;
+ if (responses.hasOwnProperty(url)) {
+ return res.json(responses[url]);
+ }
+ request(FRIGG_API + url)
.end((err, apiRes) => {
if (err) return next(err);
+ responses[url] = apiRes.body;
res.json(apiRes.body);
});
}); |
c39d828243e5e00b997c703e6ed41912ea7da6c5 | packages/@sanity/base/src/preview/PreviewMaterializer.js | packages/@sanity/base/src/preview/PreviewMaterializer.js | import React, {PropTypes} from 'react'
import observeForPreview from './observeForPreview'
import shallowEquals from 'shallow-equals'
export default class PreviewMaterializer extends React.PureComponent {
static propTypes = {
value: PropTypes.any.isRequired,
type: PropTypes.shape({
preview: PropTypes.shape({
select: PropTypes.object.isRequired,
prepare: PropTypes.func
}).isRequired
}),
children: PropTypes.func
};
state = {
loading: false,
error: null,
result: null
}
componentWillMount() {
const {type, value} = this.props
this.materialize(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
}
}
componentWillReceiveProps(nextProps) {
if (!shallowEquals(nextProps.value, this.props.value)) {
this.materialize(nextProps.value, nextProps.type)
}
}
materialize(value, type) {
this.unsubscribe()
this.subscription = observeForPreview(value, type)
.subscribe(res => {
this.setState({result: res})
})
}
render() {
const {result, loading, error} = this.state
if (loading) {
return <div>Loading…</div>
}
if (error) {
return <div>Error: {error.message}</div>
}
if (!result) {
return <div />
}
return this.props.children(result)
}
}
| import React, {PropTypes} from 'react'
import observeForPreview from './observeForPreview'
import shallowEquals from 'shallow-equals'
export default class PreviewMaterializer extends React.PureComponent {
static propTypes = {
value: PropTypes.any.isRequired,
type: PropTypes.shape({
preview: PropTypes.shape({
select: PropTypes.object.isRequired,
prepare: PropTypes.func
}).isRequired
}),
children: PropTypes.func
};
state = {
loading: false,
error: null,
result: null
}
componentWillMount() {
const {type, value} = this.props
this.materialize(value, type)
}
componentWillUnmount() {
this.unsubscribe()
}
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
this.subscription = null
}
}
componentWillReceiveProps(nextProps) {
if (!shallowEquals(nextProps.value, this.props.value)) {
this.materialize(nextProps.value, nextProps.type)
}
}
materialize(value, type) {
this.unsubscribe()
this.subscription = observeForPreview(value, type)
.subscribe(res => {
this.setState({result: res})
})
}
render() {
const {result, loading, error} = this.state
if (loading) {
return <div>Loading…</div>
}
if (error) {
return <div>Error: {error.message}</div>
}
if (!result) {
return <div />
}
return this.props.children(result)
}
}
| Set subscription to null after unsubscribe | [preview] Set subscription to null after unsubscribe
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -32,6 +32,7 @@
unsubscribe() {
if (this.subscription) {
this.subscription.unsubscribe()
+ this.subscription = null
}
}
|
8e7bfe3b0c136794de0be1802fdf9e8a90f7645d | embeds/buffer-tpc-check.js | embeds/buffer-tpc-check.js | /* globals self, bufferpm, chrome */
// buffer-tpc-check.js
// (c) 2013 Sunil Sadasivan
// Check if third party cookies are disabled
//
;(function () {
if (window !== window.top) return;
;(function check() {
if((self.port) || (xt && xt.options)) {
//if the 3rd party cookies check is disabled, store it
bufferpm.bind("buffer_3pc_disabled", function(){
if(xt && xt.options) {
xt.options['buffer.op.tpc-disabled'] = true;
}
self.port.emit('buffer_tpc_disabled');
return false;
});
var iframe = document.createElement('iframe');
iframe.id = 'buffer_tpc_check';
iframe.src = xt.data.get('data/shared/tpc-check.html');
iframe.style.display="none";
document.body.appendChild(iframe);
} else {
setTimeout(check, 50);
}
}());
}());
| /* globals self, bufferpm, chrome */
// buffer-tpc-check.js
// (c) 2013 Sunil Sadasivan
// Check if third party cookies are disabled
//
;(function () {
if (window !== window.top) return;
;(function check() {
if((self.port) || (xt && xt.options)) {
//if the 3rd party cookies check is disabled, store it
bufferpm.bind("buffer_3pc_disabled", function(){
if(xt && xt.options) {
xt.options['buffer.op.tpc-disabled'] = true;
}
self.port.emit('buffer_tpc_disabled');
return false;
});
var iframe = document.createElement('iframe');
iframe.id = 'buffer_tpc_check';
iframe.src = xt.data.get('data/shared/tpc-check.html');
iframe.style.display="none";
iframe.setAttribute('data-info', 'The Buffer extension uses this iframe to automatically ' +
'detect the browser\'s third-party cookies settings and offer the best experience based on those');
document.body.appendChild(iframe);
} else {
setTimeout(check, 50);
}
}());
}());
| Add info inside TPC check iframe attribute for curious eyes | Add info inside TPC check iframe attribute for curious eyes
| JavaScript | mit | bufferapp/buffer-extension-shared,bufferapp/buffer-extension-shared | ---
+++
@@ -23,6 +23,8 @@
iframe.id = 'buffer_tpc_check';
iframe.src = xt.data.get('data/shared/tpc-check.html');
iframe.style.display="none";
+ iframe.setAttribute('data-info', 'The Buffer extension uses this iframe to automatically ' +
+ 'detect the browser\'s third-party cookies settings and offer the best experience based on those');
document.body.appendChild(iframe);
} else {
setTimeout(check, 50); |
683ba6fcaf2072bfe7f7884b81bf04a3899c6d60 | Response.js | Response.js | 'use strict'
class Response {
constructor(messenger, msg) {
this.messenger = messenger
this.queue = msg.properties.replyTo
this.corr = msg.properties.correlationId
}
send (msg) {
if(this.queue){
this.messenger.publish(this.queue, msg)
}
}
ok (payload) {
this.send({
status: 'ok',
correlationId: this.corr,
content: payload
})
}
error (payload) {
this.send({
status: 'error',
correlationId: this.corr,
content: payload
})
}
}
module.exports = Response | 'use strict'
class Response {
constructor(messenger, msg) {
this.messenger = messenger
this.queue = msg.properties.replyTo
this.corr = msg.properties.correlationId
}
send (msg) {
if(this.queue){
this.messenger.publish(this.queue, msg)
}
}
ok (payload) {
this.send({
status: 'ok',
correlationId: this.corr,
content: payload
})
}
notify (payload) {
this.send({
status: 'notify',
correlationId: this.corr,
content: payload
})
}
error (payload) {
this.send({
status: 'error',
correlationId: this.corr,
content: payload
})
}
}
module.exports = Response | Add notify to actor service | Add notify to actor service
| JavaScript | mit | domino-logic/domino-actor-service | ---
+++
@@ -22,6 +22,14 @@
})
}
+ notify (payload) {
+ this.send({
+ status: 'notify',
+ correlationId: this.corr,
+ content: payload
+ })
+ }
+
error (payload) {
this.send({
status: 'error', |
d01d51c6e3d8d7dcc7a72384277bee95db813474 | client/app/components/dnt-hytteadmin-editor-section-kontakt.js | client/app/components/dnt-hytteadmin-editor-section-kontakt.js | import Ember from 'ember';
export default Ember.Component.extend({
});
| import Ember from 'ember';
export default Ember.Component.extend({
actions: {
setKontaktinfoGruppeById: function (id) {
var model = this.get('model');
if (typeof model.setKontaktinfoGruppeById) {
model.setKontaktinfoGruppeById(id);
}
}
}
});
| Add action for setting kontaktinfo by group id | Add action for setting kontaktinfo by group id
| JavaScript | mit | Turistforeningen/Hytteadmin,Turistforeningen/Hytteadmin | ---
+++
@@ -1,4 +1,13 @@
import Ember from 'ember';
export default Ember.Component.extend({
+ actions: {
+ setKontaktinfoGruppeById: function (id) {
+ var model = this.get('model');
+ if (typeof model.setKontaktinfoGruppeById) {
+ model.setKontaktinfoGruppeById(id);
+ }
+ }
+ }
+
}); |
9d576f6f805f5a6a72319fc1f690d9520abd215a | packages/redux-resource/src/action-types/action-types.js | packages/redux-resource/src/action-types/action-types.js | export default {
REQUEST_IDLE: 'REQUEST_IDLE',
REQUEST_PENDING: 'REQUEST_PENDING',
REQUEST_FAILED: 'REQUEST_FAILED',
REQUEST_SUCCEEDED: 'REQUEST_SUCCEEDED',
UPDATE_RESOURCES: 'UPDATE_RESOURCES',
};
| export default {
REQUEST_IDLE: 'REQUEST_IDLE',
// These will be used in Redux Resource v3.1.0. For now,
// they are reserved action types.
// REQUEST_PENDING: 'REQUEST_PENDING',
// REQUEST_FAILED: 'REQUEST_FAILED',
// REQUEST_SUCCEEDED: 'REQUEST_SUCCEEDED',
// UPDATE_RESOURCES: 'UPDATE_RESOURCES',
};
| Comment out reserved action types | Comment out reserved action types
| JavaScript | mit | jmeas/resourceful-redux,jmeas/resourceful-redux | ---
+++
@@ -1,7 +1,10 @@
export default {
REQUEST_IDLE: 'REQUEST_IDLE',
- REQUEST_PENDING: 'REQUEST_PENDING',
- REQUEST_FAILED: 'REQUEST_FAILED',
- REQUEST_SUCCEEDED: 'REQUEST_SUCCEEDED',
- UPDATE_RESOURCES: 'UPDATE_RESOURCES',
+
+ // These will be used in Redux Resource v3.1.0. For now,
+ // they are reserved action types.
+ // REQUEST_PENDING: 'REQUEST_PENDING',
+ // REQUEST_FAILED: 'REQUEST_FAILED',
+ // REQUEST_SUCCEEDED: 'REQUEST_SUCCEEDED',
+ // UPDATE_RESOURCES: 'UPDATE_RESOURCES',
}; |
223b0dd3ba63184336d615150c945bb52941c17a | packages/create-universal-package/lib/config/build-shared.js | packages/create-universal-package/lib/config/build-shared.js | const template = ({env, format, esEdition}) => `${env}.${format}.${esEdition}.js`;
const formats = ['es', 'cjs'];
module.exports = {
template,
formats,
};
| const template = ({env, format, esEdition}) => `${env}.${format}${esEdition ? `.${esEdition}` : ''}.js`;
const formats = ['es', 'cjs'];
module.exports = {
template,
formats,
};
| Fix output filepath in non-ES2015 bundles | Fix output filepath in non-ES2015 bundles
| JavaScript | mit | rtsao/create-universal-package,rtsao/create-universal-package | ---
+++
@@ -1,4 +1,4 @@
-const template = ({env, format, esEdition}) => `${env}.${format}.${esEdition}.js`;
+const template = ({env, format, esEdition}) => `${env}.${format}${esEdition ? `.${esEdition}` : ''}.js`;
const formats = ['es', 'cjs'];
module.exports = { |
c2765365104001dc4e2277c6a45c175cbb0750fe | _static/documentation_options.js | _static/documentation_options.js | var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '0.1.10',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
}; | var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
VERSION: '0.1.11',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html',
HAS_SOURCE: true,
SOURCELINK_SUFFIX: '.txt'
}; | Update docs after building Travis build 224 of regro/regolith | Update docs after building Travis build 224 of
regro/regolith
The docs were built from the branch 'master' against the commit
2cae806beee82e089f843dfbb254603d838475f7.
The Travis build that generated this commit is at
https://travis-ci.org/regro/regolith/jobs/355514019.
The doctr command that was run is
/home/travis/miniconda/envs/test/bin/doctr deploy . --deploy-repo ergs/regolith-docs --built-docs ./docs/_build/html
| JavaScript | bsd-2-clause | scopatz/regolith-docs,scopatz/regolith-docs | ---
+++
@@ -1,6 +1,6 @@
var DOCUMENTATION_OPTIONS = {
URL_ROOT: '',
- VERSION: '0.1.10',
+ VERSION: '0.1.11',
LANGUAGE: 'None',
COLLAPSE_INDEX: false,
FILE_SUFFIX: '.html', |
a392baf961f197b8268ec0666b898f82d33b35fa | app/assets/javascripts/les/profile_matrix_editor/template_updater/battery_template_updater.js | app/assets/javascripts/les/profile_matrix_editor/template_updater/battery_template_updater.js | var BatteryTemplateUpdater = (function () {
'use strict';
var defaultPercentage = 20.0,
batteryToggles = ".editable.profile",
batteries = [
"congestion_battery",
"households_flexibility_p2p_electricity"
],
sliderSettings = {
tooltip: 'hide',
formatter: function (value) {
return value + "%";
}
};
function setSlideStopValue() {
var sliderValue = $(this).val();
$(this).parents(".editable").find(".tick.value").text(sliderValue + "%");
}
BatteryTemplateUpdater.prototype = {
update: function () {
var isBattery = (batteries.indexOf(this.data.type) > -1),
isCongestionBattery = ("congestion_battery" === this.data.type),
batterySlider = this.template.find(".battery-slider"),
sliderInput = batterySlider.find("input");
this.template.find(batteryToggles).toggleClass("hidden", isBattery);
batterySlider.toggleClass("hidden", !isCongestionBattery);
if (isCongestionBattery) {
sliderInput.slider(sliderSettings)
.slider('setValue', defaultPercentage)
.on('slide', setSlideStopValue);
this.template.set(sliderInput.data('type'), defaultPercentage);
}
return this.template;
}
};
function BatteryTemplateUpdater(context) {
this.data = context.data;
this.template = context.template;
}
return BatteryTemplateUpdater;
}());
| var BatteryTemplateUpdater = (function () {
'use strict';
var defaultPercentage = 20.0,
batteryToggles = ".editable.profile",
batteries = [
"congestion_battery",
"households_flexibility_p2p_electricity"
],
sliderSettings = {
tooltip: 'hide',
formatter: function (value) {
return value + "%";
}
};
function setSlideStopValue() {
var sliderValue = $(this).val();
$(this).parents(".editable").find(".tick.value").text(sliderValue + "%");
}
BatteryTemplateUpdater.prototype = {
update: function () {
var isBattery = (batteries.indexOf(this.data.type) > -1),
isCongestionBattery = ("congestion_battery" === this.data.type),
batterySlider = this.template.find(".battery-slider"),
sliderInput = batterySlider.find("input");
this.template.find(batteryToggles).toggleClass("hidden", isBattery);
batterySlider.toggleClass("hidden", !isCongestionBattery);
if (isCongestionBattery) {
sliderInput.slider(sliderSettings)
.slider('setValue', defaultPercentage)
.on('slide', setSlideStopValue)
.trigger('slide');
this.template.set(sliderInput.data('type'), defaultPercentage);
}
return this.template;
}
};
function BatteryTemplateUpdater(context) {
this.data = context.data;
this.template = context.template;
}
return BatteryTemplateUpdater;
}());
| Set slider value when adding a new congestion battery | Set slider value when adding a new congestion battery
This would work when editing an existing battery, but without triggering
the event manually it would default to 0% when adding a new battery.
| JavaScript | mit | quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses,quintel/etmoses | ---
+++
@@ -34,7 +34,9 @@
if (isCongestionBattery) {
sliderInput.slider(sliderSettings)
.slider('setValue', defaultPercentage)
- .on('slide', setSlideStopValue);
+ .on('slide', setSlideStopValue)
+ .trigger('slide');
+
this.template.set(sliderInput.data('type'), defaultPercentage);
} |
cbb2235784307d250b6320ab8bb262da3c2fb686 | client/app/scripts/services/application.js | client/app/scripts/services/application.js | angular.module('app').factory('applicationService', ['$http', 'MARLINAPI_CONFIG',
function($http, MARLINAPI_CONFIG) {
var url = MARLINAPI_CONFIG.base_url;
// create and expose service methods
var exports = {};
// get all items
exports.getAll = function() {
return $http.get(url + 'applications').then(function(response) {
return response.data;
});
};
// get one item by id
exports.getById = function(id) {
return $http.get(url + 'applications/' + id).then(function(response) {
return response.data;
});
};
// update one item by item
// @note we figure out id from item
exports.update = function(newItem) {
var id = newItem._id;
newItem = _.omit(newItem, '_id');
return $http.put(url + 'applications/' + id, newItem).then(function(response) {
return response.data;
});
};
// add a new item
exports.add = function(item) {
return $http.post(url + 'applications', item).then(function(response) {
return response.data;
});
};
// remove item by item
exports.remove = function(id) {
return $http({
method: 'DELETE',
url: url + 'applications/' + id
}).then(function(response) {
return response.data;
});
};
// --------
return exports;
}
]);
| angular.module('app').factory('applicationService', ['$http', 'MARLINAPI_CONFIG',
function($http, MARLINAPI_CONFIG) {
var url = MARLINAPI_CONFIG.base_url;
// create and expose service methods
var exports = {};
// Generic find functionality
exports.find = function(query) {
query = JSON.stringify(query);
return $http.post(url + 'applications/find', {params: query}).then(function(response) {
return response.data;
});
};
// get all items
exports.getAll = function() {
return $http.get(url + 'applications').then(function(response) {
return response.data;
});
};
// get one item by id
exports.getById = function(id) {
return $http.get(url + 'applications/' + id).then(function(response) {
return response.data;
});
};
// update one item by item
// @note we figure out id from item
exports.update = function(newItem) {
var id = newItem._id;
newItem = _.omit(newItem, '_id');
return $http.put(url + 'applications/' + id, newItem).then(function(response) {
return response.data;
});
};
// add a new item
exports.add = function(item) {
return $http.post(url + 'applications', item).then(function(response) {
return response.data;
});
};
// remove item by item
exports.remove = function(id) {
return $http({
method: 'DELETE',
url: url + 'applications/' + id
}).then(function(response) {
return response.data;
});
};
// --------
return exports;
}
]);
| Add flexible find Application service | Add flexible find Application service | JavaScript | mit | brettshollenberger/mrl001,brettshollenberger/mrl001 | ---
+++
@@ -5,6 +5,16 @@
// create and expose service methods
var exports = {};
+
+ // Generic find functionality
+ exports.find = function(query) {
+
+ query = JSON.stringify(query);
+
+ return $http.post(url + 'applications/find', {params: query}).then(function(response) {
+ return response.data;
+ });
+ };
// get all items
exports.getAll = function() { |
4758be5962095ad86055cd0083fa9f8961f11fb7 | app/components/RecipeList.js | app/components/RecipeList.js | var React = require('react');
var Parse = require('parse');
var ParseReact = require('parse-react');
var RecipeList = new React.createClass({
mixins: [ParseReact.Mixin],
observe: function() {
return {
recipes: (new Parse.Query('Recipe')).equalTo("createdBy", Parse.User.current().id)
};
},
render: function() {
var content;
if (this.pendingQueries().length) {
content = "Loading";
} else {
debugger;
content = "Loaded";
}
return (
<div>
{content}
</div>
);
}
});
module.exports = RecipeList; | var React = require('react');
var Parse = require('parse');
var RecipeStore = require('../stores/RecipeStore');
var RecipeItem = require('./RecipeItem');
var RecipeList = new React.createClass({
getInitialState: function() {
return {
ownedRecipes: null
};
},
componentDidMount: function() {
RecipeStore.getOwned(Parse.User.current().id, this._getOwnedRecipes);
},
render: function() {
var ownedRecipes = this.state.ownedRecipes;
var recipes = [];
if (!ownedRecipes) {
recipes.push(<div>Loading</div>);
} else {
if (ownedRecipes.length == 0) {
recipes.push(<div>No recipes</div>);
}
for (var key in ownedRecipes) {
recipes.push(<RecipeItem recipe={ownedRecipes[key]} />);
}
}
return (
<div>
{recipes}
</div>
);
},
_getOwnedRecipes: function(recipes) {
this.setState({ownedRecipes:recipes});
}
});
module.exports = RecipeList; | Add recipe list to overview view | Add recipe list to overview view
| JavaScript | mit | bspride/ModernCookbook,bspride/ModernCookbook,bspride/ModernCookbook | ---
+++
@@ -1,31 +1,41 @@
var React = require('react');
var Parse = require('parse');
-var ParseReact = require('parse-react');
+var RecipeStore = require('../stores/RecipeStore');
+var RecipeItem = require('./RecipeItem');
var RecipeList = new React.createClass({
- mixins: [ParseReact.Mixin],
- observe: function() {
+ getInitialState: function() {
return {
- recipes: (new Parse.Query('Recipe')).equalTo("createdBy", Parse.User.current().id)
+ ownedRecipes: null
};
+ },
+ componentDidMount: function() {
+ RecipeStore.getOwned(Parse.User.current().id, this._getOwnedRecipes);
},
render: function() {
- var content;
- if (this.pendingQueries().length) {
- content = "Loading";
+ var ownedRecipes = this.state.ownedRecipes;
+ var recipes = [];
+ if (!ownedRecipes) {
+ recipes.push(<div>Loading</div>);
} else {
- debugger;
- content = "Loaded";
+ if (ownedRecipes.length == 0) {
+ recipes.push(<div>No recipes</div>);
+ }
+ for (var key in ownedRecipes) {
+ recipes.push(<RecipeItem recipe={ownedRecipes[key]} />);
+ }
}
return (
<div>
- {content}
+ {recipes}
</div>
);
- }
-
+ },
+ _getOwnedRecipes: function(recipes) {
+ this.setState({ownedRecipes:recipes});
+ }
});
module.exports = RecipeList; |
157db3722cc41586c41c115227be619ea62a0788 | desktop/app/main-window.js | desktop/app/main-window.js | import Window from './window'
import {ipcMain} from 'electron'
import resolveRoot from '../resolve-root'
import hotPath from '../hot-path'
import flags from '../shared/util/feature-flags'
import {globalResizing} from '../shared/styles/style-guide'
export default function () {
const mainWindow = new Window(
resolveRoot(`renderer/index.html?src=${hotPath('index.bundle.js')}`), {
width: globalResizing.login.width,
height: globalResizing.login.height,
show: flags.login
}
)
ipcMain.on('showMain', () => {
mainWindow.show(true)
})
return mainWindow
}
| import Window from './window'
import {ipcMain} from 'electron'
import resolveRoot from '../resolve-root'
import hotPath from '../hot-path'
import flags from '../shared/util/feature-flags'
import {globalResizing} from '../shared/styles/style-guide'
export default function () {
const mainWindow = new Window(
resolveRoot(`renderer/index.html?src=${hotPath('index.bundle.js')}`), {
useContentSize: true,
width: globalResizing.login.width,
height: globalResizing.login.height,
show: flags.login
}
)
ipcMain.on('showMain', () => {
mainWindow.show(true)
})
return mainWindow
}
| Use content size when creating the main window | Use content size when creating the main window
| JavaScript | bsd-3-clause | keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client,keybase/client | ---
+++
@@ -8,6 +8,7 @@
export default function () {
const mainWindow = new Window(
resolveRoot(`renderer/index.html?src=${hotPath('index.bundle.js')}`), {
+ useContentSize: true,
width: globalResizing.login.width,
height: globalResizing.login.height,
show: flags.login |
a99f9dd83e0a15dfd923ab0ae873f84755f99b0e | feedpaper-web/params.js | feedpaper-web/params.js | var fs = require('fs');
var p = require('path');
var slug = require('slug');
var url = require('url');
var util = require('util');
slug.defaults.mode ='rfc3986';
var env = process.env['FEEDPAPER_ENV'];
var feedsCategories = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feeds.json')));
var conf = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feedpaper.json')));
// in lieu of AE86 pre-hook
var apiBase = url.format({
protocol: conf.api.protocol,
hostname: conf.api.host,
pathname: util.format('v%d/%s', conf.api.version, conf.api.path)
});
var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js'));
globalJs = globalJs.replace(/var apiBase = '.*';/, util.format('var apiBase = \'%s\';', apiBase));
exports.params = {
slug: function(title, cb) {
cb(slug(title));
},
sitemap: {
'index.html': { title: 'Feedpaper' }
},
categories: feedsCategories
};
| var fs = require('fs');
var p = require('path');
var slug = require('slug');
var url = require('url');
var util = require('util');
slug.defaults.mode ='rfc3986';
var env = process.env['FEEDPAPER_ENV'];
var feedsCategories = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feeds.json')));
var conf = JSON.parse(fs.readFileSync(p.join('..', 'conf', env, 'feedpaper.json')));
// in lieu of AE86 pre-hook
var apiBase = url.format({
protocol: conf.api.protocol,
hostname: conf.api.host,
pathname: util.format('v%d/%s', conf.api.version, conf.api.path)
});
var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js'), 'utf-8');
globalJs = globalJs.replace(/var apiBase = '.*';/, util.format('var apiBase = \'%s\';', apiBase));
exports.params = {
slug: function(title, cb) {
cb(slug(title));
},
sitemap: {
'index.html': { title: 'Feedpaper' }
},
categories: feedsCategories
};
| Add encode on global.js file read. node v4.x compat. | Add encode on global.js file read. node v4.x compat.
| JavaScript | mit | cliffano/feedpaper,cliffano/feedpaper,cliffano/feedpaper | ---
+++
@@ -16,7 +16,7 @@
hostname: conf.api.host,
pathname: util.format('v%d/%s', conf.api.version, conf.api.path)
});
-var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js'));
+var globalJs = fs.readFileSync(p.join('static', 'scripts', 'global.js'), 'utf-8');
globalJs = globalJs.replace(/var apiBase = '.*';/, util.format('var apiBase = \'%s\';', apiBase));
exports.params = { |
4709f623b41dffe1ad227908e3f92782987bbfa9 | server/models/card/card.js | server/models/card/card.js | 'use strict';
var mongoose = require('mongoose');
const WAITING_FOR_PRINT = 'WAITING_FOR_PRINT';
const PRINTED_WAITING_FOR_SEND = 'PRINTED_WAITING_FOR_SEND';
const SENT = 'SENT';
var statusKeys = [
WAITING_FOR_PRINT,
PRINTED_WAITING_FOR_SEND,
SENT
];
var cardSchema = mongoose.Schema({
message: String,
senderAddress: { type:String, required: true },
receiverAddress: { type:String, required: true },
createdOn: { type: Date, default: Date.now },
statusKey: {
type: String,
enum: statusKeys,
default: WAITING_FOR_PRINT,
required: true
}
});
var Card = mongoose.model('Card', cardSchema);
module.exports = Card;
| 'use strict';
var mongoose = require('mongoose');
const WAITING_FOR_PRINT = 'WAITING_FOR_PRINT';
const PRINTED_WAITING_FOR_SEND = 'PRINTED_WAITING_FOR_SEND';
const SENT = 'SENT';
var statusKeys = [
WAITING_FOR_PRINT,
PRINTED_WAITING_FOR_SEND,
SENT
];
var cardSchema = mongoose.Schema({
message: { type: String, required: true },
senderAddress: { type: String, required: true },
receiverAddress: { type: String, required: true },
createdOn: { type: Date, default: Date.now },
statusKey: {
type: String,
enum: statusKeys,
default: WAITING_FOR_PRINT,
required: true
}
});
var Card = mongoose.model('Card', cardSchema);
module.exports = Card;
| Make message field as required | Make message field as required
| JavaScript | mit | denisnarush/postcard,denisnarush/postcard | ---
+++
@@ -13,9 +13,9 @@
];
var cardSchema = mongoose.Schema({
- message: String,
- senderAddress: { type:String, required: true },
- receiverAddress: { type:String, required: true },
+ message: { type: String, required: true },
+ senderAddress: { type: String, required: true },
+ receiverAddress: { type: String, required: true },
createdOn: { type: Date, default: Date.now },
statusKey: {
type: String, |
dfb7fd375cc6e073df2add406c9ca3e81fe211d0 | js/scripts.js | js/scripts.js | // DOM Ready
$(function() {
// SVG fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
if (!Modernizr.svg) {
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (/.*\.svg$/.test(imgs[i].src)) {
imgs[i].src = imgs[i].src.slice(0, -3) + 'png';
}
}
}
});
| // DOM Ready
jQuery(document).ready(function($) {
// SVG fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update
if (!Modernizr.svg) {
var imgs = document.getElementsByTagName('img');
for (var i = 0; i < imgs.length; i++) {
if (/.*\.svg$/.test(imgs[i].src)) {
imgs[i].src = imgs[i].src.slice(0, -3) + 'png';
}
}
}
});
| Handle jQuery in noConflict mode. | Handle jQuery in noConflict mode.
See: http://api.jquery.com/ready/
| JavaScript | mit | martinleopold/prcs-website,martinleopold/prcs-website | ---
+++
@@ -1,5 +1,5 @@
// DOM Ready
-$(function() {
+jQuery(document).ready(function($) {
// SVG fallback
// toddmotto.com/mastering-svg-use-for-a-retina-web-fallbacks-with-png-script#update |
a774ca427a200270c770dd278d55119cb31de65c | src/containers/Console.js | src/containers/Console.js | import {connect} from 'react-redux';
import Console from '../components/Console';
import {
getCurrentCompiledProjectKey,
getConsoleHistory,
getCurrentProjectKey,
getHiddenUIComponents,
getRequestedFocusedLine,
isCurrentProjectSyntacticallyValid,
isExperimental,
isTextSizeLarge,
} from '../selectors';
import {
evaluateConsoleEntry,
toggleComponent,
focusLine,
editorFocusedRequestedLine,
clearConsoleEntries,
} from '../actions';
function mapStateToProps(state) {
return {
currentCompiledProjectKey: getCurrentCompiledProjectKey(state),
currentProjectKey: getCurrentProjectKey(state),
history: getConsoleHistory(state),
isEnabled: isExperimental(state),
isOpen: !getHiddenUIComponents(state).includes('console'),
isTextSizeLarge: isTextSizeLarge(state),
requestedFocusedLine: getRequestedFocusedLine(state),
isHidden: !isCurrentProjectSyntacticallyValid(state),
};
}
function mapDispatchToProps(dispatch) {
return {
onClearConsoleEntries() {
dispatch(clearConsoleEntries());
},
onInput(input) {
dispatch(evaluateConsoleEntry(input));
},
onToggleVisible(projectKey) {
dispatch(toggleComponent(projectKey, 'console'));
},
onConsoleClicked() {
dispatch(focusLine('console', 0, 0));
},
onRequestedLineFocused() {
dispatch(editorFocusedRequestedLine());
},
};
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Console);
| import {connect} from 'react-redux';
import Console from '../components/Console';
import {
getCurrentCompiledProjectKey,
getConsoleHistory,
getCurrentProjectKey,
getHiddenUIComponents,
getRequestedFocusedLine,
isCurrentProjectSyntacticallyValid,
isExperimental,
isTextSizeLarge,
} from '../selectors';
import {
evaluateConsoleEntry,
toggleComponent,
focusLine,
editorFocusedRequestedLine,
clearConsoleEntries,
} from '../actions';
function mapStateToProps(state) {
return {
currentCompiledProjectKey: getCurrentCompiledProjectKey(state),
currentProjectKey: getCurrentProjectKey(state),
history: getConsoleHistory(state),
isEnabled: isExperimental(state),
isOpen: !getHiddenUIComponents(state).includes('console'),
isTextSizeLarge: isTextSizeLarge(state),
requestedFocusedLine: getRequestedFocusedLine(state),
isHidden: !isCurrentProjectSyntacticallyValid(state),
};
}
function mapDispatchToProps(dispatch) {
return {
onClearConsoleEntries() {
dispatch(clearConsoleEntries());
dispatch(focusLine('console', 0, 0));
},
onInput(input) {
dispatch(evaluateConsoleEntry(input));
},
onToggleVisible(projectKey) {
dispatch(toggleComponent(projectKey, 'console'));
},
onConsoleClicked() {
dispatch(focusLine('console', 0, 0));
},
onRequestedLineFocused() {
dispatch(editorFocusedRequestedLine());
},
};
}
export default connect(
mapStateToProps,
mapDispatchToProps,
)(Console);
| Fix console input focus on clearing. | Fix console input focus on clearing.
| JavaScript | mit | outoftime/learnpad,outoftime/learnpad,jwang1919/popcode,jwang1919/popcode,popcodeorg/popcode,jwang1919/popcode,popcodeorg/popcode,jwang1919/popcode,popcodeorg/popcode,popcodeorg/popcode | ---
+++
@@ -35,6 +35,7 @@
return {
onClearConsoleEntries() {
dispatch(clearConsoleEntries());
+ dispatch(focusLine('console', 0, 0));
},
onInput(input) { |
98216fdd8b2cbd8d62b2c04884939923e5719437 | examples/src/controller.js | examples/src/controller.js | import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.setAttribute('src', item.img);
img.setAttribute('style', 'vertical-align: middle; height: 50px; width: 50px; margin: 20px');
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
| import inputData from './data.js';
import infiniteDivs from '../../lib/infinitedivs.js';
let rootElement = document.body;
function divGenerator(item) {
let div = document.createElement('div'),
img = document.createElement('img'),
span = document.createElement('span');
img.setAttribute('src', item.img);
img.setAttribute('style', 'vertical-align: middle; height: 50px; width: 50px; margin: 20px');
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
div.setAttribute('style', 'border-bottom: 1px dotted');
div.appendChild(img);
div.appendChild(span);
return div;
}
let dataArray = inputData;
let config = {
bufferMultiplier: 2,
dataArray,
divGenerator,
divHeight: 90,
rootElement
};
let infinitedivs = new infiniteDivs(config);
function scrollListener() {
infinitedivs.viewDoctor();
};
document.addEventListener('scroll', scrollListener);
| Add border bottom to divs. | Add border bottom to divs.
| JavaScript | mit | supreetpal/infinite-divs,supreetpal/infinite-divs | ---
+++
@@ -13,6 +13,7 @@
img.setAttribute('alt', 'avatar');
span.textContent = item.name;
span.setAttribute('style', 'text-decoration: underline');
+ div.setAttribute('style', 'border-bottom: 1px dotted');
div.appendChild(img);
div.appendChild(span);
return div;
@@ -33,4 +34,5 @@
function scrollListener() {
infinitedivs.viewDoctor();
};
+
document.addEventListener('scroll', scrollListener); |
17beb5e36f014b3cab661981b00ad65fc2ed988d | example/index.js | example/index.js | const http = require("http")
const url = require("url")
const namor = require("namor")
const server = http.createServer((req, res) => {
const { query } = url.parse(req.url, true)
const payload = JSON.stringify(
{
generated_name: namor.generate({
words: query.words,
saltLength: query.saltLength,
saltType: query.saltType,
separator: query.separator,
subset: query.subset,
}),
},
null,
2,
)
res.setHeader("Content-Type", "application/json")
res.setHeader("Content-Length", Buffer.byteLength(payload))
res.setHeader("Access-Control-Allow-Headers", "*")
res.end(payload)
})
const port = process.env.PORT || 5000
const host = process.env.HOST || "0.0.0.0"
server.listen(port, host, () => {
console.log(`=> running at http://${host}:${port}`)
})
| const http = require("http")
const url = require("url")
const namor = require("namor")
const server = http.createServer((req, res) => {
const { query } = url.parse(req.url, true)
const payload = JSON.stringify(
{
generated_name: namor.generate({
words: query.words,
saltLength: query.saltLength,
saltType: query.saltType,
separator: query.separator,
subset: query.subset,
}),
},
null,
2,
)
res.setHeader("Content-Type", "application/json")
res.setHeader("Content-Length", Buffer.byteLength(payload))
res.setHeader("Access-Control-Allow-Origin", "*")
res.end(payload)
})
const port = process.env.PORT || 5000
const host = process.env.HOST || "0.0.0.0"
server.listen(port, host, () => {
console.log(`=> running at http://${host}:${port}`)
})
| Add cors header to example | Add cors header to example
| JavaScript | mit | jsonmaur/namor,jsonmaur/namor | ---
+++
@@ -21,7 +21,7 @@
res.setHeader("Content-Type", "application/json")
res.setHeader("Content-Length", Buffer.byteLength(payload))
- res.setHeader("Access-Control-Allow-Headers", "*")
+ res.setHeader("Access-Control-Allow-Origin", "*")
res.end(payload)
}) |
68fd319b09b021742ad309255d6a444a655a6fee | babel.config.js | babel.config.js | module.exports = {
presets: ["es2015-node4", "stage-0", "react"],
plugins: [
"add-module-exports",
["transform-async-to-module-method", {
module: "bluebird",
method: "coroutine"
}]
],
ignore: false,
only: /.es$/
}
| module.exports = {
presets: ["es2015-node4", "react"],
plugins: [
"add-module-exports",
["transform-async-to-module-method", {
module: "bluebird",
method: "coroutine"
}]
],
ignore: false,
only: /.es$/
}
| Remove babel-stage-0 preset to prevent crash in Electron 1.x | Remove babel-stage-0 preset to prevent crash in Electron 1.x
| JavaScript | mit | PHELiOX/poi,poooi/poi,syncsyncsynchalt/poi,yudachi/poi,syncsyncsynchalt/poi,KagamiChan/poi,poooi/poi,poooi/poi,poooi/poi,gnattu/poi,syncsyncsynchalt/poi,syncsyncsynchalt/poi,yudachi/poi,yudachi/poi,gnattu/poi,PHELiOX/poi,KagamiChan/poi,nagatoyk/poi,nagatoyk/poi | ---
+++
@@ -1,5 +1,5 @@
module.exports = {
- presets: ["es2015-node4", "stage-0", "react"],
+ presets: ["es2015-node4", "react"],
plugins: [
"add-module-exports",
["transform-async-to-module-method", { |
86b3ad30b978d227bd3b596d176c8d11b2a1995d | forum-web-app/src/ui.js | forum-web-app/src/ui.js | "use strict";
// src/ui.js
let ui = {
renderPosts(posts) {
console.log(posts);
}
};
export { ui };
| "use strict";
// src/ui.js
let ui = {
renderPosts(posts) {
let elements = posts.map( (post) => {
let { title, lastReply } = post;
return articleTemplate(title, lastReply);
});
let target = document.querySelector(".container");
target.innerHTML = elements.join("");
}
};
function articleTemplate(title, lastReply) {
let template = `
<article class="post">
<h2 class="post-title">
${title}
</h2>
<p class="post-meta">
${lastReply}
</p>
</article>`;
return template;
}
export { ui };
| Add articleTemplate method. Edit renderPosts | Add articleTemplate method. Edit renderPosts
| JavaScript | mit | var-bin/reactjs-training,var-bin/reactjs-training,var-bin/reactjs-training | ---
+++
@@ -4,8 +4,29 @@
let ui = {
renderPosts(posts) {
- console.log(posts);
+ let elements = posts.map( (post) => {
+ let { title, lastReply } = post;
+
+ return articleTemplate(title, lastReply);
+ });
+
+ let target = document.querySelector(".container");
+ target.innerHTML = elements.join("");
}
};
+function articleTemplate(title, lastReply) {
+ let template = `
+ <article class="post">
+ <h2 class="post-title">
+ ${title}
+ </h2>
+ <p class="post-meta">
+ ${lastReply}
+ </p>
+ </article>`;
+
+ return template;
+}
+
export { ui }; |
cf0cb38ea897541e667193ca2699ecf5e3caaacc | app/src/js/modules/events.js | app/src/js/modules/events.js | /**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (event, parameter) {
broker.triggerHandler(event, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} event - Event type
* @param {function} handler - Event handler
*/
events.on = function (event, handler) {
broker.on(event, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
| /**
* Events.
*
* @mixin
* @namespace Bolt.events
*
* @param {Object} bolt - The Bolt module.
*/
(function (bolt) {
'use strict';
/*
* Bolt.events mixin container.
*
* @private
* @type {Object}
*/
var events = {};
/*
* Event broker object.
*
* @private
* @type {Object}
*/
var broker = $({});
/**
* Fires an event.
*
* @static
* @function fire
* @memberof Bolt.events
*
* @param {string} eventType - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
events.fire = function (eventType, parameter) {
broker.triggerHandler(eventType, parameter);
};
/**
* Attach an event handler.
*
* @static
* @function on
* @memberof Bolt.events
*
* @param {string} eventType - Event type
* @param {function} handler - Event handler
*/
events.on = function (eventType, handler) {
broker.on(eventType, handler);
};
// Apply mixin container
bolt.events = events;
})(Bolt || {});
| Use jQuery nomenclature (event => eventType) | Use jQuery nomenclature (event => eventType) | JavaScript | mit | GawainLynch/bolt,nikgo/bolt,rarila/bolt,CarsonF/bolt,lenvanessen/bolt,romulo1984/bolt,electrolinux/bolt,Intendit/bolt,bolt/bolt,rarila/bolt,lenvanessen/bolt,electrolinux/bolt,Raistlfiren/bolt,GawainLynch/bolt,romulo1984/bolt,Raistlfiren/bolt,GawainLynch/bolt,lenvanessen/bolt,Raistlfiren/bolt,HonzaMikula/masivnipostele,cdowdy/bolt,lenvanessen/bolt,electrolinux/bolt,CarsonF/bolt,romulo1984/bolt,HonzaMikula/masivnipostele,romulo1984/bolt,CarsonF/bolt,HonzaMikula/masivnipostele,rarila/bolt,Intendit/bolt,nikgo/bolt,nikgo/bolt,cdowdy/bolt,cdowdy/bolt,Intendit/bolt,electrolinux/bolt,HonzaMikula/masivnipostele,cdowdy/bolt,joshuan/bolt,bolt/bolt,joshuan/bolt,joshuan/bolt,joshuan/bolt,CarsonF/bolt,nikgo/bolt,bolt/bolt,rarila/bolt,bolt/bolt,Intendit/bolt,Raistlfiren/bolt,GawainLynch/bolt | ---
+++
@@ -32,11 +32,11 @@
* @function fire
* @memberof Bolt.events
*
- * @param {string} event - Event type
+ * @param {string} eventType - Event type
* @param {object} [parameter] - Additional parameters to pass along to the event handler
*/
- events.fire = function (event, parameter) {
- broker.triggerHandler(event, parameter);
+ events.fire = function (eventType, parameter) {
+ broker.triggerHandler(eventType, parameter);
};
/**
@@ -46,11 +46,11 @@
* @function on
* @memberof Bolt.events
*
- * @param {string} event - Event type
- * @param {function} handler - Event handler
+ * @param {string} eventType - Event type
+ * @param {function} handler - Event handler
*/
- events.on = function (event, handler) {
- broker.on(event, handler);
+ events.on = function (eventType, handler) {
+ broker.on(eventType, handler);
};
// Apply mixin container |
a1b0d42fa832c518466d4a9502dd1543ac155bfd | spec/filesize-view-spec.js | spec/filesize-view-spec.js | 'use babel';
import filesizeView from '../lib/filesize-view';
describe('View', () => {
// Disable tooltip, only enable on tests when needed
atom.config.set('filesize.EnablePopupAppearance', false);
const workspaceView = atom.views.getView(atom.workspace);
const view = filesizeView(workspaceView);
describe('when refreshing the view', () => {
it('should display the human readable size', () => {
workspaceView.appendChild(view.container);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 5 });
expect(filesizeElement.innerHTML).toEqual('5 bytes');
});
it('should react to config changes', () => {
atom.config.set('filesize.UseDecimal', true);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 1024 });
expect(filesizeElement.innerHTML).toEqual('1.02 kB');
});
});
describe('when cleaning the view', () => {
it('should wipe the filesize contents', () => {
view.clean();
const filesizeElement = workspaceView.querySelector('.current-size');
expect(filesizeElement.innerHTML).toEqual('');
});
});
describe('when destroying the view', () => {
it('should remove the file-size element', () => {
view.destroy();
const filesizeElement = workspaceView.querySelector('.file-size');
expect(filesizeElement).toEqual(null);
});
});
});
| 'use babel';
import filesizeView from '../lib/filesize-view';
describe('View', () => {
// Disable tooltip, only enable on tests when needed
atom.config.set('filesize.EnablePopupAppearance', false);
const workspaceView = atom.views.getView(atom.workspace);
const view = filesizeView(workspaceView);
describe('when refreshing the view', () => {
it('should display the human readable size', () => {
workspaceView.appendChild(view.container);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 5 });
expect(filesizeElement.innerHTML).toEqual('5 bytes');
});
it('should react to config changes', () => {
atom.config.set('filesize.UseDecimal', true);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 1024 });
expect(filesizeElement.innerHTML).toEqual('1.02 kB');
});
});
describe('when cleaning the view', () => {
it('should wipe the filesize contents', () => {
view.clean();
const filesizeElement = workspaceView.querySelector('.current-size');
expect(filesizeElement.innerHTML).toEqual('');
});
});
describe('when destroying the view', () => {
it('should remove the file-size element', () => {
view.destroy();
const filesizeElement = workspaceView.querySelector('.file-size');
expect(filesizeElement).toEqual(null);
});
});
});
| Remove extra line in the end of file | Remove extra line in the end of file
| JavaScript | mit | mkautzmann/atom-filesize | ---
+++
@@ -40,4 +40,3 @@
});
});
});
- |
30a6393c9ea13501afbaae3cd349310645ce7c4a | lib/tilelive/mappool.js | lib/tilelive/mappool.js |
/**
* Small wrapper around node-pool. Establishes a pool of 5 mapnik map objects
* per mapfile.
* @TODO: Make pool size configurable.
*/
module.exports = new function() {
return {
pools: {},
acquire: function(mapfile, options, callback) {
if (!this.pools[mapfile]) {
this.pools[mapfile] = require('generic-pool').Pool({
name: mapfile,
create: function(callback) {
var width = options.width || 256,
height = options.height || 256,
Map = require('mapnik').Map,
map = new Map(width, height);
map.load(mapfile);
map.buffer_size(128);
callback(map);
},
destroy: function(map) {
map.clear();
delete map;
},
max: 5,
idleTimeoutMillis: 5000,
log: false
});
}
this.pools[mapfile].acquire(callback);
},
release: function(mapfile, map) {
this.pools[mapfile] && this.pools[mapfile].release(map);
}
};
}
|
/**
* Small wrapper around node-pool. Establishes a pool of 5 mapnik map objects
* per mapfile.
* @TODO: Make pool size configurable.
*/
module.exports = new function() {
return {
pools: {},
acquire: function(mapfile, options, callback) {
if (!this.pools[mapfile]) {
this.pools[mapfile] = require('generic-pool').Pool({
name: mapfile,
create: function(callback) {
var width = options.width || 256,
height = options.height || 256,
Map = require('mapnik').Map,
map = new Map(width, height);
try {
map.load(mapfile);
map.buffer_size(128);
callback(map);
} catch(err) {
callback(map);
}
},
destroy: function(map) {
map.clear();
delete map;
},
max: 5,
idleTimeoutMillis: 5000,
log: false
});
}
this.pools[mapfile].acquire(callback);
},
release: function(mapfile, map) {
this.pools[mapfile] && this.pools[mapfile].release(map);
}
};
}
| Use try/catch for loading mapfiles. | Use try/catch for loading mapfiles.
| JavaScript | bsd-3-clause | topwood/tilelive,mapbox/tilelive,Norkart/tilelive.js,tomhughes/tilelive.js,kyroskoh/tilelive,paulovieira/tilelive,mapbox/tilelive.js,nyurik/tilelive.js,gravitystorm/tilelive.js | ---
+++
@@ -16,9 +16,13 @@
height = options.height || 256,
Map = require('mapnik').Map,
map = new Map(width, height);
- map.load(mapfile);
- map.buffer_size(128);
- callback(map);
+ try {
+ map.load(mapfile);
+ map.buffer_size(128);
+ callback(map);
+ } catch(err) {
+ callback(map);
+ }
},
destroy: function(map) {
map.clear(); |
7d84aa5b1d0c2af75abf70e556470cb67b79b19a | spec/filesize-view-spec.js | spec/filesize-view-spec.js | 'use babel';
import filesizeView from '../lib/filesize-view';
describe('View', () => {
// Disable tooltip for these tests
atom.config.set('filesize.EnablePopupAppearance', false);
const workspaceView = atom.views.getView(atom.workspace);
const view = filesizeView(workspaceView);
describe('when refreshing the view', () => {
it('should display the human readable size', () => {
workspaceView.appendChild(view.container);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 5 });
expect(filesizeElement.innerHTML).toEqual('5 bytes');
});
});
describe('when cleaning the view', () => {
it('should wipe the filesize contents', () => {
view.clean();
const filesizeElement = workspaceView.querySelector('.current-size');
expect(filesizeElement.innerHTML).toEqual('');
});
});
describe('when destroying the view', () => {
it('should remove the file-size element', () => {
view.destroy();
const filesizeElement = workspaceView.querySelector('.file-size');
expect(filesizeElement).toEqual(null);
});
});
});
| 'use babel';
import filesizeView from '../lib/filesize-view';
describe('View', () => {
const workspaceView = atom.views.getView(atom.workspace);
const view = filesizeView(workspaceView);
describe('when refreshing the view', () => {
it('should display the human readable size', () => {
workspaceView.appendChild(view.container);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 5 });
expect(filesizeElement.innerHTML).toEqual('5 bytes');
});
it('should react to config changes', () => {
atom.config.set('filesize.KibibyteRepresentation', false);
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 1024 });
expect(filesizeElement.innerHTML).toEqual('1.02 KB');
});
});
describe('Tooltip', () => {
it('should display on click', () => {
const filesizeLink = workspaceView.querySelector('.file-size-link');
filesizeLink.click();
waitsFor(() => workspaceView.querySelector('.tooltip'));
runs(() => expect(tooltip).not.toEqual(null));
});
});
describe('when cleaning the view', () => {
it('should wipe the filesize contents', () => {
view.clean();
const filesizeElement = workspaceView.querySelector('.current-size');
expect(filesizeElement.innerHTML).toEqual('');
});
});
describe('when destroying the view', () => {
it('should remove the file-size element', () => {
view.destroy();
const filesizeElement = workspaceView.querySelector('.file-size');
expect(filesizeElement).toEqual(null);
});
});
});
| Add config change test to the View spec | Add config change test to the View spec
| JavaScript | mit | mkautzmann/atom-filesize | ---
+++
@@ -3,8 +3,6 @@
import filesizeView from '../lib/filesize-view';
describe('View', () => {
- // Disable tooltip for these tests
- atom.config.set('filesize.EnablePopupAppearance', false);
const workspaceView = atom.views.getView(atom.workspace);
const view = filesizeView(workspaceView);
@@ -14,6 +12,21 @@
const filesizeElement = workspaceView.querySelector('.current-size');
view.refresh({ size: 5 });
expect(filesizeElement.innerHTML).toEqual('5 bytes');
+ });
+ it('should react to config changes', () => {
+ atom.config.set('filesize.KibibyteRepresentation', false);
+ const filesizeElement = workspaceView.querySelector('.current-size');
+ view.refresh({ size: 1024 });
+ expect(filesizeElement.innerHTML).toEqual('1.02 KB');
+ });
+ });
+
+ describe('Tooltip', () => {
+ it('should display on click', () => {
+ const filesizeLink = workspaceView.querySelector('.file-size-link');
+ filesizeLink.click();
+ waitsFor(() => workspaceView.querySelector('.tooltip'));
+ runs(() => expect(tooltip).not.toEqual(null));
});
});
|
05b14b3f817f0cffb06ade8f1ff82bfff177c6bd | starting-angular/starting-angular/cards/cards_usesStaticJSON_cleanestVersion/js/directives.js | starting-angular/starting-angular/cards/cards_usesStaticJSON_cleanestVersion/js/directives.js | /*global cardApp*/
/*jslint unparam: true */
(function () {
'use strict';
// Implements custom validation for card number.
var INTEGER_REGEXP = /^([aAkKjJQq23456789]{1}|(10){1})$/;
cardApp.directive('integer', function () {
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
}
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
});
}
};
});
}()); | /*global cardApp*/
/*jslint unparam: true */
cardApp.directive('integer', function () {
'use strict';
// Implements custom validation for card number.
var INTEGER_REGEXP = /^([aAkKjJQq23456789]{1}|(10){1})$/;
return {
require: 'ngModel',
link: function (scope, elm, attrs, ctrl) {
ctrl.$parsers.unshift(function (viewValue) {
if (INTEGER_REGEXP.test(viewValue)) {
// it is valid
ctrl.$setValidity('integer', true);
return viewValue;
}
// it is invalid, return undefined (no model update)
ctrl.$setValidity('integer', false);
return undefined;
});
}
};
});
| Use the angular module pattern instead of using a closure. | Use the angular module pattern instead of using a closure.
| JavaScript | unlicense | bigfont/DevTeach2013,bigfont/DevTeach2013 | ---
+++
@@ -1,29 +1,29 @@
/*global cardApp*/
/*jslint unparam: true */
-(function () {
+
+cardApp.directive('integer', function () {
'use strict';
// Implements custom validation for card number.
var INTEGER_REGEXP = /^([aAkKjJQq23456789]{1}|(10){1})$/;
- cardApp.directive('integer', function () {
- return {
- require: 'ngModel',
- link: function (scope, elm, attrs, ctrl) {
- ctrl.$parsers.unshift(function (viewValue) {
- if (INTEGER_REGEXP.test(viewValue)) {
- // it is valid
- ctrl.$setValidity('integer', true);
- return viewValue;
- }
- // it is invalid, return undefined (no model update)
- ctrl.$setValidity('integer', false);
- return undefined;
+ return {
- });
- }
- };
- });
+ require: 'ngModel',
+ link: function (scope, elm, attrs, ctrl) {
+ ctrl.$parsers.unshift(function (viewValue) {
+ if (INTEGER_REGEXP.test(viewValue)) {
+ // it is valid
+ ctrl.$setValidity('integer', true);
+ return viewValue;
+ }
-}());
+ // it is invalid, return undefined (no model update)
+ ctrl.$setValidity('integer', false);
+ return undefined;
+
+ });
+ }
+ };
+}); |
749b9d4b89c9e34808b4d4e8ce5600703ce16464 | clientapp/views/pathway.js | clientapp/views/pathway.js | var HumanView = require('human-view');
var templates = require('../templates');
module.exports = HumanView.extend({
template: templates.pathway,
events: {
'dragstart .columns': 'drag',
'dragover .columns': 'over',
'dragenter .columns': 'enter',
'dragleave .columns': 'leave',
'drop .columns': 'drop'
},
render: function () {
this.renderAndBind({pathway: this.model});
this.model.once('move', this.render, this);
return this;
},
drag: function (e) {
var start = $(e.currentTarget).data('cell-coords');
e.originalEvent.dataTransfer.setData('text/plain', start);
},
over: function (e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
if (!$(e.currentTarget).find('.badge').length) {
e.preventDefault();
return false;
}
},
enter: function (e) {
if (!$(e.currentTarget).find('.badge').length) {
$(e.currentTarget).addClass('drop');
}
},
leave: function (e) {
$(e.currentTarget).removeClass('drop');
},
drop: function (e) {
var end = $(e.currentTarget).data('cell-coords');
var start = e.originalEvent.dataTransfer.getData('text/plain');
this.model.move(start, end);
e.preventDefault();
}
});
| var HumanView = require('human-view');
var templates = require('../templates');
module.exports = HumanView.extend({
template: templates.pathway,
events: {
'dragstart .columns': 'drag',
'dragover .columns': 'over',
'dragenter .columns': 'enter',
'dragleave .columns': 'leave',
'drop .columns': 'drop'
},
render: function () {
this.renderAndBind({pathway: this.model});
this.model.once('move', this.render, this);
return this;
},
drag: function (e) {
var start = $(e.currentTarget).data('cell-coords');
e.originalEvent.dataTransfer.setData('Text', start);
},
over: function (e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
if (!$(e.currentTarget).find('.badge').length) {
e.preventDefault();
e.stopPropagation();
}
},
enter: function (e) {
if (!$(e.currentTarget).find('.badge').length) {
$(e.currentTarget).addClass('drop');
}
},
leave: function (e) {
$(e.currentTarget).removeClass('drop');
},
drop: function (e) {
var end = $(e.currentTarget).data('cell-coords');
var start = e.originalEvent.dataTransfer.getData('Text');
this.model.move(start, end);
e.preventDefault();
e.stopPropagation();
}
});
| Make it work in IE10 | Make it work in IE10
| JavaScript | mpl-2.0 | mozilla/openbadges-discovery | ---
+++
@@ -17,14 +17,14 @@
},
drag: function (e) {
var start = $(e.currentTarget).data('cell-coords');
- e.originalEvent.dataTransfer.setData('text/plain', start);
+ e.originalEvent.dataTransfer.setData('Text', start);
},
over: function (e) {
e.originalEvent.dataTransfer.effectAllowed = 'move';
e.originalEvent.dataTransfer.dropEffect = 'move';
if (!$(e.currentTarget).find('.badge').length) {
e.preventDefault();
- return false;
+ e.stopPropagation();
}
},
enter: function (e) {
@@ -37,8 +37,9 @@
},
drop: function (e) {
var end = $(e.currentTarget).data('cell-coords');
- var start = e.originalEvent.dataTransfer.getData('text/plain');
+ var start = e.originalEvent.dataTransfer.getData('Text');
this.model.move(start, end);
e.preventDefault();
+ e.stopPropagation();
}
}); |
19a0c4401e5185b71d5ca715d54d13c31cab7559 | lib/sequence/binlog.js | lib/sequence/binlog.js | var Util = require('util');
var Packet = require('../packet');
var capture = require('../capture');
module.exports = function(options) {
var self = this; // ZongJi instance
var Sequence = capture(self.connection).Sequence;
var BinlogHeader = Packet.initBinlogHeader.call(self, options);
function Binlog(callback) {
Sequence.call(this, callback);
}
Util.inherits(Binlog, Sequence);
Binlog.prototype.start = function() {
this.emit('packet', new Packet.ComBinlog(options));
};
Binlog.prototype.determinePacket = function(firstByte) {
switch (firstByte) {
case 0xfe:
return Packet.Eof;
case 0xff:
return Packet.Error;
default:
return BinlogHeader;
}
};
Binlog.prototype['OkPacket'] = function(packet) {
console.log('Received one OkPacket ...');
};
Binlog.prototype['BinlogHeader'] = function(packet) {
if (this._callback) {
var event, error;
try{
event = packet.getEvent();
}catch(err){
error = err;
}
this._callback.call(this, error, event);
}
};
return Binlog;
};
| var Util = require('util');
var Packet = require('../packet');
var capture = require('../capture');
module.exports = function(options) {
var self = this; // ZongJi instance
var Sequence = capture(self.connection).Sequence;
var BinlogHeader = Packet.initBinlogHeader.call(self, options);
function Binlog(callback) {
Sequence.call(this, callback);
}
Util.inherits(Binlog, Sequence);
Binlog.prototype.start = function() {
this.emit('packet', new Packet.ComBinlog(options));
};
Binlog.prototype.determinePacket = function(firstByte) {
switch (firstByte) {
case 0xfe:
return Packet.Eof;
case 0xff:
return Packet.Error;
default:
return BinlogHeader;
}
};
Binlog.prototype['OkPacket'] = function(packet) {
// TODO: Remove console statements to make module ready for widespread use
console.log('Received one OkPacket ...');
};
Binlog.prototype['BinlogHeader'] = function(packet) {
if (this._callback) {
var event, error;
try{
event = packet.getEvent();
}catch(err){
error = err;
}
this._callback.call(this, error, event);
}
};
return Binlog;
};
| Add TODO to remove console.log from non-dump functions | Add TODO to remove console.log from non-dump functions
| JavaScript | mit | jmealo/zongji,jmealo/zongji | ---
+++
@@ -29,6 +29,7 @@
};
Binlog.prototype['OkPacket'] = function(packet) {
+ // TODO: Remove console statements to make module ready for widespread use
console.log('Received one OkPacket ...');
};
|
85168befaaab2563b91345867087d51789a88dff | client/app/common/global-events/global-events.factory.js | client/app/common/global-events/global-events.factory.js | let GlobalEvents = () => {
let events = {};
return {
off: (eventHandle) => {
let index = events[eventHandle.eventName].findIndex((singleEventHandler) => {
return singleEventHandler.id !== eventHandle.handlerId;
});
events[eventHandle.eventName].splice(index, 1);
},
on: (eventName, handlerCallback) => {
if (!events[eventName]) {
events[eventName] = [];
}
let handlers = events[eventName];
let newHandlerId = new Date().getTime();
handlers.push({
id: newHandlerId,
callback: handlerCallback
});
return {
id: newHandlerId,
eventName
};
},
trigger: (eventName, data) => {
events[eventName].forEach((singleHandler) => {
singleHandler.callback(data);
});
}
};
}
export default GlobalEvents; | let GlobalEvents = () => {
let events = {};
return {
off: (eventHandle) => {
let index = events[eventHandle.eventName].findIndex((singleEventHandler) => {
return singleEventHandler.id !== eventHandle.handlerId;
});
events[eventHandle.eventName].splice(index, 1);
},
on: (eventName, handlerCallback) => {
if (!events[eventName]) {
events[eventName] = [];
}
let handlers = events[eventName];
let newHandlerId = new Date().getTime();
handlers.push({
id: newHandlerId,
callback: handlerCallback
});
return {
id: newHandlerId,
eventName
};
},
trigger: (eventName, data) => {
if (events[eventName]) {
events[eventName].forEach((singleHandler) => {
singleHandler.callback(data);
});
}
}
};
}
export default GlobalEvents; | Fix trigger exception when no listeners specified | Fix trigger exception when no listeners specified
| JavaScript | apache-2.0 | zbicin/word-game,zbicin/word-game | ---
+++
@@ -25,9 +25,11 @@
};
},
trigger: (eventName, data) => {
- events[eventName].forEach((singleHandler) => {
- singleHandler.callback(data);
- });
+ if (events[eventName]) {
+ events[eventName].forEach((singleHandler) => {
+ singleHandler.callback(data);
+ });
+ }
}
};
} |
2eeb2979a6d7dc1ce5f5559f7437b90b2246c72f | src/DynamicCodeRegistry.js | src/DynamicCodeRegistry.js | /*
Keep track of
*/
import Backbone from "backbone"
import _ from "underscore"
export default class DynamicCodeRegistry {
constructor(){
_.extend(this, Backbone.Events)
this._content = {};
this._origins = {}
}
register(filename, content, origin){
this._content[filename] = content
if (origin) {
this._origins[filename] = origin
}
this.trigger("register", {
[filename]: content
})
}
getContent(filename){
return this._content[filename]
}
getOrigin(filename){
return this._origins[filename]
}
fileIsDynamicCode(filename){
return this._content[filename] !== undefined
}
}
| /*
Keep track of
*/
import Backbone from "backbone"
import _ from "underscore"
export default class DynamicCodeRegistry {
constructor(){
_.extend(this, Backbone.Events)
this._content = {};
this._origins = {}
}
register(filename, content, origin){
this._content[filename] = content
if (origin) {
this._origins[filename] = origin
}
this.trigger("register", {
[filename]: content
})
}
getContent(filename){
return this._content[filename]
}
getOrigin(filename){
return this._origins[filename]
}
fileIsDynamicCode(filename){
return filename.indexOf("DynamicFunction") !== -1;
}
}
| Fix detecting if it's a dynamic files... script tags from the original html were previously incorrectly identified as dynamic files. | Fix detecting if it's a dynamic files... script tags from the original html were previously incorrectly identified as dynamic files.
| JavaScript | mit | mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS,mattzeunert/FromJS | ---
+++
@@ -27,6 +27,6 @@
return this._origins[filename]
}
fileIsDynamicCode(filename){
- return this._content[filename] !== undefined
+ return filename.indexOf("DynamicFunction") !== -1;
}
} |
efd680a34c23ec2727a3033e37517e309ba29a0c | client/webcomponents/nn-annotable.js | client/webcomponents/nn-annotable.js | /* jshint camelcase:false */
Polymer('nn-annotable', {
ready: function(){
this.baseapi = this.baseapi || window.location.origin;
this.tokens = this.baseapi.split('://');
this.wsurl = this.tokens.shift() === 'https' ? 'wss' : 'ws' + '://' + this.tokens.shift();
this.domain = window.location.hostname;
this.connect = (this.connect !== undefined) ? this.connect : true;
this.comments = [];
},
attached: function(){
if(!this.nid){
throw 'Attribute missing: nid';
}
this.$.websocket.addEventListener('message', this.updateComments.bind(this));
this.$.get_comments.go();
},
populateComments: function(evt){
this.comments = evt.detail.response;
},
updateComments: function(evt){
this.comments.push(evt.detail);
},
newComment: function(evt){
this.message = '';
evt.preventDefault();
if(!this.author || !this.text){
this.message = 'completa tutti i campi';
return;
}
this.$.new_comment.go();
},
resetForm: function(){
this.author = this.text = '';
}
});
| /* jshint camelcase:false */
Polymer('nn-annotable', {
ready: function(){
this.baseapi = this.baseapi || window.location.origin;
this.tokens = this.baseapi.split('://');
this.wsurl = (this.tokens.shift() === 'https' ? 'wss' : 'ws') + '://' + this.tokens.shift();
this.domain = window.location.hostname;
this.connect = (this.connect !== undefined) ? this.connect : true;
this.comments = [];
},
attached: function(){
if(!this.nid){
throw 'Attribute missing: nid';
}
this.$.websocket.addEventListener('message', this.updateComments.bind(this));
this.$.get_comments.go();
},
populateComments: function(evt){
this.comments = evt.detail.response;
},
updateComments: function(evt){
this.comments.push(evt.detail);
},
newComment: function(evt){
this.message = '';
evt.preventDefault();
if(!this.author || !this.text){
this.message = 'completa tutti i campi';
return;
}
this.$.new_comment.go();
},
resetForm: function(){
this.author = this.text = '';
}
});
| Fix how to calculate ws URL from baseapi URL | Fix how to calculate ws URL from baseapi URL
| JavaScript | mit | sandropaganotti/annotate | ---
+++
@@ -4,7 +4,7 @@
ready: function(){
this.baseapi = this.baseapi || window.location.origin;
this.tokens = this.baseapi.split('://');
- this.wsurl = this.tokens.shift() === 'https' ? 'wss' : 'ws' + '://' + this.tokens.shift();
+ this.wsurl = (this.tokens.shift() === 'https' ? 'wss' : 'ws') + '://' + this.tokens.shift();
this.domain = window.location.hostname;
this.connect = (this.connect !== undefined) ? this.connect : true;
this.comments = []; |
447241fc88b42a03b9091da7066e7e58a414e3a2 | src/geojson.js | src/geojson.js | module.exports.point = justType('Point', 'POINT');
module.exports.line = justType('LineString', 'POLYLINE');
module.exports.polygon = justType('Polygon', 'POLYGON');
function justType(type, TYPE) {
return function(gj) {
var oftype = gj.features.filter(isType(type));
return {
geometries: oftype.map(justCoords),
properties: oftype.map(justProps),
type: TYPE
};
};
}
function justCoords(t) {
if (t.geometry.coordinates[0] !== undefined &&
t.geometry.coordinates[0][0] !== undefined &&
t.geometry.coordinates[0][0][0] !== undefined) {
return t.geometry.coordinates[0];
} else {
return t.geometry.coordinates;
}
}
function justProps(t) {
return t.properties;
}
function isType(t) {
return function(f) { return f.geometry.type === t; };
}
| module.exports.point = justType('Point', 'POINT');
module.exports.line = justType('LineString', 'POLYLINE');
module.exports.polygon = justType('Polygon', 'POLYGON');
function justType(type, TYPE) {
return function(gj) {
var oftype = gj.features.filter(isType(type));
return {
geometries: (TYPE === 'POLYGON' || TYPE === 'POLYLINE') ? [oftype.map(justCoords)] : oftype.map(justCoords),
properties: oftype.map(justProps),
type: TYPE
};
};
}
function justCoords(t) {
if (t.geometry.coordinates[0] !== undefined &&
t.geometry.coordinates[0][0] !== undefined &&
t.geometry.coordinates[0][0][0] !== undefined) {
return t.geometry.coordinates[0];
} else {
return t.geometry.coordinates;
}
}
function justProps(t) {
return t.properties;
}
function isType(t) {
return function(f) { return f.geometry.type === t; };
}
| Add type check for polygon and polyline arrays | fix(output): Add type check for polygon and polyline arrays
Added a type check to properly wrap polygon and polyline arrays | JavaScript | bsd-3-clause | mapbox/shp-write,mapbox/shp-write | ---
+++
@@ -6,7 +6,7 @@
return function(gj) {
var oftype = gj.features.filter(isType(type));
return {
- geometries: oftype.map(justCoords),
+ geometries: (TYPE === 'POLYGON' || TYPE === 'POLYLINE') ? [oftype.map(justCoords)] : oftype.map(justCoords),
properties: oftype.map(justProps),
type: TYPE
}; |
d62ccfd234f702b66124a673e54076dbdfe693be | lib/util/endpointParser.js | lib/util/endpointParser.js | var semver = require('semver');
var createError = require('./createError');
function decompose(endpoint) {
var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)\|)?([^\|#]+)(?:#(.*))?$/;
var matches = endpoint.match(regExp);
if (!matches) {
throw createError('Invalid endpoint: "' + endpoint + '"', 'EINVEND');
}
return {
name: matches[1] || '',
source: matches[2],
target: matches[3] || '*'
};
}
function compose(decEndpoint) {
var composed = '';
if (decEndpoint.name) {
composed += decEndpoint.name + '|';
}
composed += decEndpoint.source;
if (decEndpoint.target) {
composed += '#' + decEndpoint.target;
}
return composed;
}
function json2decomposed(key, value) {
var endpoint = key + '|';
if (semver.valid(value) != null || semver.validRange(value) != null) {
endpoint += key + '#' + value;
} else {
endpoint += value;
}
return decompose(endpoint);
}
module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
| var semver = require('semver');
var createError = require('./createError');
function decompose(endpoint) {
var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/;
var matches = endpoint.match(regExp);
if (!matches) {
throw createError('Invalid endpoint: "' + endpoint + '"', 'EINVEND');
}
return {
name: matches[1] || '',
source: matches[2],
target: matches[3] || '*'
};
}
function compose(decEndpoint) {
var composed = '';
if (decEndpoint.name) {
composed += decEndpoint.name + '=';
}
composed += decEndpoint.source;
if (decEndpoint.target) {
composed += '#' + decEndpoint.target;
}
return composed;
}
function json2decomposed(key, value) {
var endpoint = key + '=';
if (semver.valid(value) != null || semver.validRange(value) != null) {
endpoint += key + '#' + value;
} else {
endpoint += value;
}
return decompose(endpoint);
}
module.exports.decompose = decompose;
module.exports.compose = compose;
module.exports.json2decomposed = json2decomposed;
| Change name separator of the endpoint (can't use pipe duh). | Change name separator of the endpoint (can't use pipe duh).
| JavaScript | mit | dreamauya/bower,jisaacks/bower,Blackbaud-EricSlater/bower,DrRataplan/bower,rlugojr/bower,grigorkh/bower,omurbilgili/bower,yinhe007/bower,XCage15/bower,gronke/bower,amilaonbitlab/bower,jodytate/bower,Teino1978-Corp/bower,prometheansacrifice/bower,adriaanthomas/bower,unilynx/bower,watilde/bower,rajzshkr/bower,jvkops/bower,gorcz/bower,cgvarela/bower,magnetech/bower,Backbase/bower,supriyantomaftuh/bower,hyperweb2/upt,pjump/bower,skinzer/bower,fernandomoraes/bower,Jeremy017/bower,msbit/bower,sanyueyu/bower,akaash-nigam/bower,liorhson/bower,wenyanw/bower,mex/bower,M4gn4tor/bower,pertrai1/bower,Connectlegendary/bower,ThiagoGarciaAlves/bower,angeliaz/bower,JFrogDev/bower-art,krahman/bower,insanehong/bower,buildsample/bower,bower/bower,kodypeterson/bower,thinkxl/bower,kevinjdinicola/hg-bower,mattpugh/bower,yuhualingfeng/bower,DevVersion/bower,return02/bower,fewspider/bower,xfstudio/bower,TooHTooH/bower,kruppel/bower,pwang2/bower,Teino1978-Corp/Teino1978-Corp-bower,lukemelia/bower,haolee1990/bower,Jinkwon/naver-bower-cli,vladikoff/bower,cnbin/bower,PimsJay01/bower,twalpole/bower | ---
+++
@@ -2,7 +2,7 @@
var createError = require('./createError');
function decompose(endpoint) {
- var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)\|)?([^\|#]+)(?:#(.*))?$/;
+ var regExp = /^(?:([\w\-]|(?:[\w\.\-]+[\w\-])?)=)?([^\|#]+)(?:#(.*))?$/;
var matches = endpoint.match(regExp);
if (!matches) {
@@ -20,7 +20,7 @@
var composed = '';
if (decEndpoint.name) {
- composed += decEndpoint.name + '|';
+ composed += decEndpoint.name + '=';
}
composed += decEndpoint.source;
@@ -33,7 +33,7 @@
}
function json2decomposed(key, value) {
- var endpoint = key + '|';
+ var endpoint = key + '=';
if (semver.valid(value) != null || semver.validRange(value) != null) {
endpoint += key + '#' + value; |
0b7ec05717cf6c89e9cbe307bec611326c19ae43 | js/metronome.js | js/metronome.js | function Metronome(tempo, beatsPerMeasure){
this.tempo = Number(tempo);
this.beatsPerMeasure = Number(beatsPerMeasure);
this.interval = null;
}
Metronome.prototype.start = function(){
var millisecondsToWait = this.tempoToMilliseconds(this.tempo);
this.interval = window.setInterval(soundAndCounter, millisecondsToWait, this);
}
Metronome.prototype.tempoToMilliseconds = function(tempo){
return (1000 * 60)/tempo;
}
soundAndCounter = function(metronome){
updateCounterView(metronome);
}
updateCounterView = function(metronome){
var counter = document.getElementById("metronome-counter");
var pastBeat = Number(counter.innerHTML);
if (pastBeat < metronome.beatsPerMeasure){
counter.innerHTML = pastBeat + 1;
} else {
counter.innerHTML = 1;
}
}
Metronome.prototype.stop = function(){
window.clearInterval(this.interval);
counter.innerHTML = "";
} | function Metronome(tempo, beatsPerMeasure){
this.tempo = Number(tempo);
this.beatsPerMeasure = Number(beatsPerMeasure);
this.interval = null;
}
Metronome.prototype.start = function(){
var millisecondsToWait = this.tempoToMilliseconds(this.tempo);
this.interval = window.setInterval(soundAndCounter, millisecondsToWait, this);
}
Metronome.prototype.tempoToMilliseconds = function(tempo){
return (1000 * 60)/tempo;
}
Metronome.prototype.stop = function(){
window.clearInterval(this.interval);
var counter = document.getElementById("metronome-counter");
counter.innerHTML = "";
}
soundAndCounter = function(metronome){
updateCounterView(metronome);
}
updateCounterView = function(metronome){
var counter = document.getElementById("metronome-counter");
var pastBeat = Number(counter.innerHTML);
if (pastBeat < metronome.beatsPerMeasure){
counter.innerHTML = pastBeat + 1;
} else {
counter.innerHTML = 1;
}
}
| Add reference to counter in stop method | Add reference to counter in stop method
| JavaScript | mit | dmilburn/beatrice,dmilburn/beatrice | ---
+++
@@ -11,6 +11,12 @@
Metronome.prototype.tempoToMilliseconds = function(tempo){
return (1000 * 60)/tempo;
+}
+
+Metronome.prototype.stop = function(){
+ window.clearInterval(this.interval);
+ var counter = document.getElementById("metronome-counter");
+ counter.innerHTML = "";
}
soundAndCounter = function(metronome){
@@ -27,7 +33,3 @@
}
}
-Metronome.prototype.stop = function(){
- window.clearInterval(this.interval);
- counter.innerHTML = "";
-} |
ab53bc3e982b21a24fa7a0b36d43d98213ffbb7c | lib/winston-syslog-ain2.js | lib/winston-syslog-ain2.js | /*
* MIT LICENCE
*/
var util = require('util'),
winston = require('winston'),
SysLogger = require("ain2");
var ain;
var SyslogAin2 = exports.SyslogAin2 = function (options) {
winston.Transport.call(this, options);
options = options || {};
ain = new SysLogger(options);
};
util.inherits(SyslogAin2, winston.Transport);
SyslogAin2.prototype.name = 'SyslogAin2';
SyslogAin2.prototype.log = function (level, msg, meta, callback) {
ain[level](msg + (null!=meta ? ' '+util.inspect(meta) : ''));
callback();
};
| /*
* MIT LICENCE
*/
var util = require('util'),
winston = require('winston'),
SysLogger = require("ain2");
var SyslogAin2 = exports.SyslogAin2 = function (options) {
winston.Transport.call(this, options);
options = options || {};
this.ain = new SysLogger(options);
};
util.inherits(SyslogAin2, winston.Transport);
SyslogAin2.prototype.name = 'SyslogAin2';
SyslogAin2.prototype.log = function (level, msg, meta, callback) {
this.ain[level](msg + (null!=meta ? ' '+util.inspect(meta) : ''));
callback();
};
| Fix bug that the old settings of the ain2 is got replaced | Fix bug that the old settings of the ain2 is got replaced
| JavaScript | mit | lamtha/winston-syslog-ain2 | ---
+++
@@ -6,12 +6,10 @@
winston = require('winston'),
SysLogger = require("ain2");
-var ain;
-
var SyslogAin2 = exports.SyslogAin2 = function (options) {
winston.Transport.call(this, options);
options = options || {};
- ain = new SysLogger(options);
+ this.ain = new SysLogger(options);
};
util.inherits(SyslogAin2, winston.Transport);
@@ -19,6 +17,6 @@
SyslogAin2.prototype.name = 'SyslogAin2';
SyslogAin2.prototype.log = function (level, msg, meta, callback) {
- ain[level](msg + (null!=meta ? ' '+util.inspect(meta) : ''));
+ this.ain[level](msg + (null!=meta ? ' '+util.inspect(meta) : ''));
callback();
}; |
ec7c6848b01a3e6288b3d5326ca9df677052f7da | lib/action.js | lib/action.js | var _ = require('lodash-node');
var Action = function(name, two, three, four) {
var options, run, helpers;
// Syntax .extend('action#method', function() { ... }, {})
if ( typeof two == 'function' ) {
options = {};
run = two;
helpers = three;
}
// Syntax .extend('action#method', {}, function() { ... }, {})
if ( typeof three == 'function' ) {
options = two;
run = three;
helpers = four;
}
var presets = {
name: name,
description: name + ' description',
inputs: {
required: [],
optional: []
},
blockedConnectionTypes: [],
outputExample: {},
run: function(api, conn, next){
this.api = api;
this.next = function(success) {
next(conn, success);
};
this.json = conn.response;
this.params = conn.params;
this.req = conn.request;
run.apply(this, arguments);
}
};
return _.merge(presets, options, helpers);
};
module.exports = Action; | var _ = require('lodash-node');
var Action = function(name, two, three, four) {
var options, run, helpers;
// Syntax .extend('action#method', function() { ... }, {})
if ( typeof two == 'function' ) {
options = {};
run = two;
helpers = three;
}
// Syntax .extend('action#method', {}, function() { ... }, {})
if ( typeof three == 'function' ) {
options = two;
run = three;
helpers = four;
}
var presets = {
name: name,
description: name + ' description',
inputs: {
required: [],
optional: []
},
blockedConnectionTypes: [],
outputExample: {},
run: function(api, conn, next){
this.api = api;
this.connection = conn;
this.next = function(success) {
next(conn, success);
};
this.json = conn.response;
this.params = conn.params;
this.request = conn.request;
run.apply(this, arguments);
}
};
return _.merge(presets, options, helpers);
};
module.exports = Action; | Add connection parameter and change req to request | Add connection parameter and change req to request
| JavaScript | mit | alexparker/actionpack | ---
+++
@@ -35,12 +35,13 @@
run: function(api, conn, next){
this.api = api;
+ this.connection = conn;
this.next = function(success) {
next(conn, success);
};
this.json = conn.response;
this.params = conn.params;
- this.req = conn.request;
+ this.request = conn.request;
run.apply(this, arguments);
} |
cd0341613c11d07d2c9990adb12635f4e7809dfc | list/source/package.js | list/source/package.js | enyo.depends(
"Selection.js",
"FlyweightRepeater.js",
"List.css",
"List.js",
"PulldownList.css",
"PulldownList.js"
); | enyo.depends(
"FlyweightRepeater.js",
"List.css",
"List.js",
"PulldownList.css",
"PulldownList.js"
); | Remove enyo.Selection from layout library, moved into enyo base-UI | Remove enyo.Selection from layout library, moved into enyo base-UI
| JavaScript | apache-2.0 | enyojs/layout | ---
+++
@@ -1,5 +1,4 @@
enyo.depends(
- "Selection.js",
"FlyweightRepeater.js",
"List.css",
"List.js", |
465e33e170a10ad39c3948cb9bcb852bd5705f91 | src/ol/style/fillstyle.js | src/ol/style/fillstyle.js | goog.provide('ol.style.Fill');
goog.require('ol.color');
/**
* @constructor
* @param {olx.style.FillOptions} options Options.
*/
ol.style.Fill = function(options) {
/**
* @type {ol.Color|string}
*/
this.color = goog.isDef(options.color) ? options.color : null;
};
| goog.provide('ol.style.Fill');
goog.require('ol.color');
/**
* @constructor
* @param {olx.style.FillOptions=} opt_options Options.
*/
ol.style.Fill = function(opt_options) {
var options = goog.isDef(opt_options) ? opt_options : {};
/**
* @type {ol.Color|string}
*/
this.color = goog.isDef(options.color) ? options.color : null;
};
| Make options argument to ol.style.Fill optional | Make options argument to ol.style.Fill optional
| JavaScript | bsd-2-clause | das-peter/ol3,adube/ol3,mzur/ol3,xiaoqqchen/ol3,Distem/ol3,gingerik/ol3,antonio83moura/ol3,gingerik/ol3,itayod/ol3,bjornharrtell/ol3,tsauerwein/ol3,Antreasgr/ol3,klokantech/ol3raster,pmlrsg/ol3,das-peter/ol3,landonb/ol3,t27/ol3,kkuunnddaannkk/ol3,freylis/ol3,fredj/ol3,Andrey-Pavlov/ol3,kjelderg/ol3,geonux/ol3,elemoine/ol3,thhomas/ol3,t27/ol3,klokantech/ol3,mechdrew/ol3,bogdanvaduva/ol3,klokantech/ol3,stweil/ol3,tschaub/ol3,bill-chadwick/ol3,landonb/ol3,stweil/ol3,stweil/ol3,antonio83moura/ol3,xiaoqqchen/ol3,Distem/ol3,mzur/ol3,geekdenz/openlayers,fredj/ol3,fblackburn/ol3,llambanna/ol3,freylis/ol3,thhomas/ol3,ahocevar/openlayers,alvinlindstam/ol3,hafenr/ol3,pmlrsg/ol3,NOAA-ORR-ERD/ol3,bill-chadwick/ol3,thomasmoelhave/ol3,thhomas/ol3,CandoImage/ol3,t27/ol3,NOAA-ORR-ERD/ol3,kjelderg/ol3,fblackburn/ol3,richstoner/ol3,xiaoqqchen/ol3,geonux/ol3,NOAA-ORR-ERD/ol3,ahocevar/ol3,tschaub/ol3,llambanna/ol3,gingerik/ol3,pmlrsg/ol3,oterral/ol3,Morgul/ol3,planetlabs/ol3,tamarmot/ol3,richstoner/ol3,tsauerwein/ol3,pmlrsg/ol3,jacmendt/ol3,geonux/ol3,jacmendt/ol3,Morgul/ol3,gingerik/ol3,antonio83moura/ol3,alvinlindstam/ol3,ahocevar/ol3,openlayers/openlayers,bjornharrtell/ol3,mechdrew/ol3,Distem/ol3,CandoImage/ol3,bjornharrtell/ol3,itayod/ol3,klokantech/ol3raster,elemoine/ol3,thomasmoelhave/ol3,stweil/openlayers,kkuunnddaannkk/ol3,denilsonsa/ol3,elemoine/ol3,klokantech/ol3,stweil/openlayers,Antreasgr/ol3,llambanna/ol3,mzur/ol3,wlerner/ol3,Andrey-Pavlov/ol3,alvinlindstam/ol3,tsauerwein/ol3,Morgul/ol3,t27/ol3,denilsonsa/ol3,NOAA-ORR-ERD/ol3,klokantech/ol3,fblackburn/ol3,tsauerwein/ol3,jacmendt/ol3,bartvde/ol3,itayod/ol3,richstoner/ol3,ahocevar/ol3,adube/ol3,aisaacs/ol3,planetlabs/ol3,jmiller-boundless/ol3,Andrey-Pavlov/ol3,thomasmoelhave/ol3,geekdenz/openlayers,geekdenz/ol3,Antreasgr/ol3,geekdenz/ol3,aisaacs/ol3,tamarmot/ol3,mechdrew/ol3,denilsonsa/ol3,hafenr/ol3,bill-chadwick/ol3,llambanna/ol3,freylis/ol3,jmiller-boundless/ol3,fperucic/ol3,jmiller-boundless/ol3,tschaub/ol3,ahocevar/openlayers,bartvde/ol3,wlerner/ol3,thhomas/ol3,Andrey-Pavlov/ol3,elemoine/ol3,ahocevar/ol3,jacmendt/ol3,itayod/ol3,kkuunnddaannkk/ol3,fperucic/ol3,klokantech/ol3raster,ahocevar/openlayers,adube/ol3,bill-chadwick/ol3,aisaacs/ol3,alexbrault/ol3,bogdanvaduva/ol3,wlerner/ol3,openlayers/openlayers,fredj/ol3,jmiller-boundless/ol3,geekdenz/ol3,fredj/ol3,stweil/openlayers,jmiller-boundless/ol3,tschaub/ol3,geekdenz/openlayers,oterral/ol3,landonb/ol3,alexbrault/ol3,kjelderg/ol3,oterral/ol3,tamarmot/ol3,wlerner/ol3,freylis/ol3,richstoner/ol3,bogdanvaduva/ol3,alvinlindstam/ol3,landonb/ol3,alexbrault/ol3,CandoImage/ol3,xiaoqqchen/ol3,das-peter/ol3,Distem/ol3,thomasmoelhave/ol3,bogdanvaduva/ol3,denilsonsa/ol3,planetlabs/ol3,openlayers/openlayers,CandoImage/ol3,mzur/ol3,epointal/ol3,bartvde/ol3,epointal/ol3,fperucic/ol3,hafenr/ol3,planetlabs/ol3,stweil/ol3,das-peter/ol3,antonio83moura/ol3,mechdrew/ol3,tamarmot/ol3,geonux/ol3,epointal/ol3,aisaacs/ol3,Antreasgr/ol3,epointal/ol3,fblackburn/ol3,kkuunnddaannkk/ol3,kjelderg/ol3,alexbrault/ol3,hafenr/ol3,bartvde/ol3,klokantech/ol3raster,geekdenz/ol3,fperucic/ol3,Morgul/ol3 | ---
+++
@@ -6,9 +6,11 @@
/**
* @constructor
- * @param {olx.style.FillOptions} options Options.
+ * @param {olx.style.FillOptions=} opt_options Options.
*/
-ol.style.Fill = function(options) {
+ol.style.Fill = function(opt_options) {
+
+ var options = goog.isDef(opt_options) ? opt_options : {};
/**
* @type {ol.Color|string} |
4f2ecb38e7eed9706dd4709915a532bdb5a943f2 | rcmet/src/main/ui/test/unit/services/RegionSelectParamsTest.js | rcmet/src/main/ui/test/unit/services/RegionSelectParamsTest.js | /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http: *www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
'use strict';
describe('OCW Services', function() {
beforeEach(module('ocw.services'));
describe('RegionSelectParams', function() {
it('should initialize the regionSelectParams service', function() {
inject(function(regionSelectParams) {
expect(regionSelectParams).not.toEqual(null);
});
});
});
});
| /*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http: *www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
'use strict';
describe('OCW Services', function() {
beforeEach(module('ocw.services'));
describe('RegionSelectParams', function() {
it('should initialize the regionSelectParams service', function() {
inject(function(regionSelectParams) {
expect(regionSelectParams).not.toEqual(null);
});
});
it('should provide the getParameters function', function() {
inject(function(regionSelectParams) {
expect(regionSelectParams.getParameters()).not.toEqual(null);
});
});
});
});
| Resolve CLIMATE-147 - Add tests for regionSelectParams service | Resolve CLIMATE-147 - Add tests for regionSelectParams service
- Add getParameters test.
git-svn-id: https://svn.apache.org/repos/asf/incubator/climate/trunk@1496037 13f79535-47bb-0310-9956-ffa450edef68
Former-commit-id: 3d2be98562f344323a5532ca5757850d175ba25c | JavaScript | apache-2.0 | jarifibrahim/climate,apache/climate,Omkar20895/climate,huikyole/climate,MJJoyce/climate,lewismc/climate,MJJoyce/climate,jarifibrahim/climate,kwhitehall/climate,pwcberry/climate,riverma/climate,MJJoyce/climate,agoodm/climate,riverma/climate,agoodm/climate,MBoustani/climate,MBoustani/climate,riverma/climate,lewismc/climate,pwcberry/climate,lewismc/climate,apache/climate,MBoustani/climate,agoodm/climate,huikyole/climate,huikyole/climate,lewismc/climate,apache/climate,MJJoyce/climate,kwhitehall/climate,lewismc/climate,Omkar20895/climate,pwcberry/climate,apache/climate,agoodm/climate,jarifibrahim/climate,Omkar20895/climate,MBoustani/climate,riverma/climate,huikyole/climate,kwhitehall/climate,pwcberry/climate,apache/climate,Omkar20895/climate,kwhitehall/climate,agoodm/climate,pwcberry/climate,jarifibrahim/climate,riverma/climate,MJJoyce/climate,Omkar20895/climate,jarifibrahim/climate,MBoustani/climate,huikyole/climate | ---
+++
@@ -30,6 +30,12 @@
expect(regionSelectParams).not.toEqual(null);
});
});
+
+ it('should provide the getParameters function', function() {
+ inject(function(regionSelectParams) {
+ expect(regionSelectParams.getParameters()).not.toEqual(null);
+ });
+ });
});
});
|
9750b5683e1a545a66251e78e07ef6b362a8b6d8 | browser/main.js | browser/main.js | const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
var menu = require('./menu');
var argv = require('optimist').argv;
let mainWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
center: true,
title: 'JBrowseDesktop',
width: 1024,
height: 768
});
var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&');
mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString));
Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
mainWindow.on('closed', function () {
mainWindow = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function () {
app.quit();
});
| const electron = require('electron');
const app = electron.app;
const BrowserWindow = electron.BrowserWindow;
const Menu = electron.Menu;
var menu = require('./menu');
var argv = require('optimist').argv;
let mainWindow;
app.on('ready', function() {
mainWindow = new BrowserWindow({
center: true,
title: 'JBrowseDesktop',
width: 1024,
height: 768,
icon: require('path').resolve(__dirname, 'icons/jbrowse.png')
});
var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&');
mainWindow.loadURL('file://' + require('path').resolve(__dirname, '../index.html?'+queryString));
Menu.setApplicationMenu(Menu.buildFromTemplate(menu));
mainWindow.on('closed', function () {
mainWindow = null;
});
});
// Quit when all windows are closed.
app.on('window-all-closed', function () {
app.quit();
});
| Add icon that works for linux apps also | Add icon that works for linux apps also
| JavaScript | lgpl-2.1 | GMOD/jbrowse,GMOD/jbrowse,GMOD/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse,GMOD/jbrowse,GMOD/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse | ---
+++
@@ -13,7 +13,8 @@
center: true,
title: 'JBrowseDesktop',
width: 1024,
- height: 768
+ height: 768,
+ icon: require('path').resolve(__dirname, 'icons/jbrowse.png')
});
var queryString = Object.keys(argv).map(key => key + '=' + argv[key]).join('&');
|
f5d144abff50c9044cbfeeec16c8169a361aec1c | packages/@sanity/server/src/configs/postcssPlugins.js | packages/@sanity/server/src/configs/postcssPlugins.js | import lost from 'lost'
import postcssUrl from 'postcss-url'
import postcssImport from 'postcss-import'
import postcssCssnext from 'postcss-cssnext'
import resolveStyleImport from '../util/resolveStyleImport'
export default options => {
const styleResolver = resolveStyleImport({from: options.basePath})
const importer = postcssImport({resolve: styleResolver})
return wp => {
return [
importer,
postcssCssnext,
postcssUrl({url: 'rebase'}),
lost
]
}
}
| import path from 'path'
import lost from 'lost'
import postcssUrl from 'postcss-url'
import postcssImport from 'postcss-import'
import postcssCssnext from 'postcss-cssnext'
import resolveStyleImport from '../util/resolveStyleImport'
const absolute = /^(\/|\w+:\/\/)/
const isAbsolute = url => absolute.test(url)
export default options => {
const styleResolver = resolveStyleImport({from: options.basePath})
const importer = postcssImport({resolve: styleResolver})
const resolveUrl = (url, decl, from, dirname) => (
isAbsolute(url) ? url : path.resolve(dirname, url)
)
return wp => {
return [
importer,
postcssCssnext,
postcssUrl({url: resolveUrl}),
lost
]
}
}
| Use custom way to resolve URLs for file assets that are relative | [server] Use custom way to resolve URLs for file assets that are relative
| JavaScript | mit | sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity | ---
+++
@@ -1,18 +1,26 @@
+import path from 'path'
import lost from 'lost'
import postcssUrl from 'postcss-url'
import postcssImport from 'postcss-import'
import postcssCssnext from 'postcss-cssnext'
import resolveStyleImport from '../util/resolveStyleImport'
+const absolute = /^(\/|\w+:\/\/)/
+const isAbsolute = url => absolute.test(url)
+
export default options => {
const styleResolver = resolveStyleImport({from: options.basePath})
const importer = postcssImport({resolve: styleResolver})
+
+ const resolveUrl = (url, decl, from, dirname) => (
+ isAbsolute(url) ? url : path.resolve(dirname, url)
+ )
return wp => {
return [
importer,
postcssCssnext,
- postcssUrl({url: 'rebase'}),
+ postcssUrl({url: resolveUrl}),
lost
]
} |
f0d73e072691c7ae4ee848c7ef0868aebd6c8ce4 | components/prism-docker.js | components/prism-docker.js | Prism.languages.docker = {
'keyword': {
pattern: /(^\s*)(?:ONBUILD|FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|COPY|VOLUME|USER|WORKDIR|CMD|LABEL|ENTRYPOINT)(?=\s)/mi,
lookbehind: true
},
'string': /("|')(?:(?!\1)[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/,
'comment': /#.*/,
'punctuation': /---|\.\.\.|[:[\]{}\-,|>?]/
};
Prism.languages.dockerfile = Prism.languages.docker;
| Prism.languages.docker = {
'keyword': {
pattern: /(^\s*)(?:ADD|ARG|CMD|COPY|ENTRYPOINT|ENV|EXPOSE|FROM|HEALTHCHECK|LABEL|MAINTAINER|ONBUILD|RUN|SHELL|STOPSIGNAL|USER|VOLUME|WORKDIR)(?=\s)/mi,
lookbehind: true
},
'string': /("|')(?:(?!\1)[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/,
'comment': /#.*/,
'punctuation': /---|\.\.\.|[:[\]{}\-,|>?]/
};
Prism.languages.dockerfile = Prism.languages.docker;
| Update the list of keywords for dockerfiles | Update the list of keywords for dockerfiles
| JavaScript | mit | PrismJS/prism,mAAdhaTTah/prism,PrismJS/prism,CupOfTea696/prism,mAAdhaTTah/prism,PrismJS/prism,byverdu/prism,PrismJS/prism,byverdu/prism,CupOfTea696/prism,mAAdhaTTah/prism,mAAdhaTTah/prism,mAAdhaTTah/prism,PrismJS/prism,CupOfTea696/prism,byverdu/prism,byverdu/prism,CupOfTea696/prism,CupOfTea696/prism,byverdu/prism | ---
+++
@@ -1,6 +1,6 @@
Prism.languages.docker = {
'keyword': {
- pattern: /(^\s*)(?:ONBUILD|FROM|MAINTAINER|RUN|EXPOSE|ENV|ADD|COPY|VOLUME|USER|WORKDIR|CMD|LABEL|ENTRYPOINT)(?=\s)/mi,
+ pattern: /(^\s*)(?:ADD|ARG|CMD|COPY|ENTRYPOINT|ENV|EXPOSE|FROM|HEALTHCHECK|LABEL|MAINTAINER|ONBUILD|RUN|SHELL|STOPSIGNAL|USER|VOLUME|WORKDIR)(?=\s)/mi,
lookbehind: true
},
'string': /("|')(?:(?!\1)[^\\\r\n]|\\(?:\r\n|[\s\S]))*?\1/, |
c6db2d07bbda721d18ebce6c3526ec393b61e5b2 | src/ol/geom.js | src/ol/geom.js | /**
* @module ol/geom
*/
export {default as Circle} from './geom/Circle.js';
export {default as Geometry} from './geom/Geometry.js';
export {default as GeometryCollection} from './geom/GeometryCollection';
export {default as LineString} from './geom/LineString.js';
export {default as MultiLineString} from './geom/MultiLineString.js';
export {default as MultiPoint} from './geom/MultiPoint.js';
export {default as MultiPolygon} from './geom/MultiPolygon.js';
export {default as Point} from './geom/Point.js';
export {default as Polygon} from './geom/Polygon.js';
| /**
* @module ol/geom
*/
export {default as Circle} from './geom/Circle.js';
export {default as Geometry} from './geom/Geometry.js';
export {default as GeometryCollection} from './geom/GeometryCollection.js';
export {default as LineString} from './geom/LineString.js';
export {default as MultiLineString} from './geom/MultiLineString.js';
export {default as MultiPoint} from './geom/MultiPoint.js';
export {default as MultiPolygon} from './geom/MultiPolygon.js';
export {default as Point} from './geom/Point.js';
export {default as Polygon} from './geom/Polygon.js';
| Use .js extension for import | Use .js extension for import
Co-Authored-By: ahocevar <02d02e811da4fb4f389e866b67c0fe930c3e5051@gmail.com> | JavaScript | bsd-2-clause | adube/ol3,tschaub/ol3,stweil/openlayers,bjornharrtell/ol3,tschaub/ol3,tschaub/ol3,openlayers/openlayers,stweil/openlayers,stweil/ol3,bjornharrtell/ol3,geekdenz/openlayers,geekdenz/openlayers,geekdenz/ol3,oterral/ol3,oterral/ol3,ahocevar/ol3,geekdenz/ol3,ahocevar/openlayers,geekdenz/ol3,adube/ol3,geekdenz/ol3,bjornharrtell/ol3,stweil/ol3,openlayers/openlayers,oterral/ol3,ahocevar/ol3,ahocevar/ol3,ahocevar/ol3,stweil/ol3,ahocevar/openlayers,ahocevar/openlayers,geekdenz/openlayers,stweil/ol3,adube/ol3,tschaub/ol3,openlayers/openlayers,stweil/openlayers | ---
+++
@@ -4,7 +4,7 @@
export {default as Circle} from './geom/Circle.js';
export {default as Geometry} from './geom/Geometry.js';
-export {default as GeometryCollection} from './geom/GeometryCollection';
+export {default as GeometryCollection} from './geom/GeometryCollection.js';
export {default as LineString} from './geom/LineString.js';
export {default as MultiLineString} from './geom/MultiLineString.js';
export {default as MultiPoint} from './geom/MultiPoint.js'; |
030b97c50a57e1487b8459f91ee4a220810a8a63 | babel.config.js | babel.config.js | require("@babel/register")({
only: [
"src",
/node_modules\/alekhine/
]
})
module.exports = {
presets: [
"@babel/preset-env"
],
plugins: [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-object-rest-spread",
"add-filehash", [
"transform-imports",
{
vuetify: {
transform: "vuetify/src/components/${member}",
preventFullImport: false
}
}
]
],
env: {
development: {
"sourceMaps": "inline"
}
}
}
| module.exports = {
presets: [
"@babel/preset-env"
],
plugins: [
"@babel/plugin-transform-runtime",
"@babel/plugin-proposal-object-rest-spread",
"add-filehash", [
"transform-imports",
{
vuetify: {
transform: "vuetify/src/components/${member}",
preventFullImport: false
}
}
]
],
env: {
development: {
"sourceMaps": "inline"
}
}
}
| Revert "compile alekhine as needed in development" | Revert "compile alekhine as needed in development"
This reverts commit 917d5d50fd6ef0bbf845efa0bf13a2adba2fe58a.
| JavaScript | mit | sonnym/bughouse,sonnym/bughouse | ---
+++
@@ -1,10 +1,3 @@
-require("@babel/register")({
- only: [
- "src",
- /node_modules\/alekhine/
- ]
-})
-
module.exports = {
presets: [
"@babel/preset-env" |
27982b6392b8dcd2adc22fb0db7eb0aecab0f62a | test/algorithms/sorting/testHeapSort.js | test/algorithms/sorting/testHeapSort.js | /* eslint-env mocha */
const HeapSort = require('../../../src').algorithms.Sorting.HeapSort;
const assert = require('assert');
describe('HeapSort', () => {
it('should have no data when empty initialization', () => {
const inst = new HeapSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new HeapSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
});
| /* eslint-env mocha */
const HeapSort = require('../../../src').algorithms.Sorting.HeapSort;
const assert = require('assert');
describe('HeapSort', () => {
it('should have no data when empty initialization', () => {
const inst = new HeapSort();
assert.equal(inst.size, 0);
assert.deepEqual(inst.unsortedList, []);
assert.deepEqual(inst.sortedList, []);
});
it('should sort the array', () => {
const inst = new HeapSort([2, 1, 3, 4]);
assert.equal(inst.size, 4);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4]);
assert.deepEqual(inst.sortedList, [1, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 3, 4');
});
it('should sort the array in ascending order with few equal vals', () => {
const inst = new HeapSort([2, 1, 3, 4, 2], (a, b) => a < b);
assert.equal(inst.size, 5);
assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]);
assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]);
assert.equal(inst.toString(), '1, 2, 2, 3, 4');
});
});
| Test Heap Sort: Sort array with equal vals | Test Heap Sort: Sort array with equal vals
| JavaScript | mit | ManrajGrover/algorithms-js | ---
+++
@@ -19,4 +19,12 @@
assert.equal(inst.toString(), '1, 2, 3, 4');
});
+ it('should sort the array in ascending order with few equal vals', () => {
+ const inst = new HeapSort([2, 1, 3, 4, 2], (a, b) => a < b);
+ assert.equal(inst.size, 5);
+
+ assert.deepEqual(inst.unsortedList, [2, 1, 3, 4, 2]);
+ assert.deepEqual(inst.sortedList, [1, 2, 2, 3, 4]);
+ assert.equal(inst.toString(), '1, 2, 2, 3, 4');
+ });
}); |
6a408d16822f596bedeb524912471845ced74048 | ckanext/ckanext-apicatalog_ui/ckanext/apicatalog_ui/fanstatic/cookieconsent/ckan-cookieconsent.js | ckanext/ckanext-apicatalog_ui/ckanext/apicatalog_ui/fanstatic/cookieconsent/ckan-cookieconsent.js | window.cookieconsent.initialise({
container: document.getElementById("cookie_consent"),
position: "top",
type: "opt-in",
static: false,
theme: "suomifi",
onInitialise: function (status){
let type = this.options.type;
let didConsent = this.hasConsented();
if (type === 'opt-in' && didConsent) {
console.log("enable cookies")
}
if (type === 'opt-out' && !didConsent) {
console.log("disable cookies")
}
},
onStatusChange: function(status, chosenBefore) {
let type = this.options.type;
let didConsent = this.hasConsented();
if (type === 'opt-in' && didConsent) {
console.log("enable cookies")
window.location.reload();
}
if (type === 'opt-in' && !didConsent) {
console.log("disable cookies")
window.location.reload();
}
}
}) | ckan.module('cookie_consent', function (jQuery){
return {
initialize: function() {
window.cookieconsent.initialise({
container: document.getElementById("cookie_consent"),
position: "top",
type: "opt-in",
static: false,
theme: "suomifi",
content: {
policy: this._('Cookie Policy'),
message: this._('This website uses cookies to ensure you get the best experience on our website.'),
allow: this._('Allow cookies'),
deny: this._('Decline'),
link: this._('Learn more')
},
onStatusChange: function(status, chosenBefore) {
let type = this.options.type;
let didConsent = this.hasConsented();
if (type === 'opt-in' && didConsent) {
console.log("enable cookies")
window.location.reload();
}
if (type === 'opt-in' && !didConsent) {
console.log("disable cookies")
window.location.reload();
}
}
})
}
}
}) | Add translations to cookie popup | LIKA-244: Add translations to cookie popup
| JavaScript | mit | vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog,vrk-kpa/api-catalog | ---
+++
@@ -1,29 +1,33 @@
-window.cookieconsent.initialise({
- container: document.getElementById("cookie_consent"),
- position: "top",
- type: "opt-in",
- static: false,
- theme: "suomifi",
- onInitialise: function (status){
- let type = this.options.type;
- let didConsent = this.hasConsented();
- if (type === 'opt-in' && didConsent) {
- console.log("enable cookies")
- }
- if (type === 'opt-out' && !didConsent) {
- console.log("disable cookies")
- }
- },
- onStatusChange: function(status, chosenBefore) {
- let type = this.options.type;
- let didConsent = this.hasConsented();
- if (type === 'opt-in' && didConsent) {
- console.log("enable cookies")
- window.location.reload();
- }
- if (type === 'opt-in' && !didConsent) {
- console.log("disable cookies")
- window.location.reload();
+ckan.module('cookie_consent', function (jQuery){
+ return {
+ initialize: function() {
+ window.cookieconsent.initialise({
+ container: document.getElementById("cookie_consent"),
+ position: "top",
+ type: "opt-in",
+ static: false,
+ theme: "suomifi",
+ content: {
+ policy: this._('Cookie Policy'),
+ message: this._('This website uses cookies to ensure you get the best experience on our website.'),
+ allow: this._('Allow cookies'),
+ deny: this._('Decline'),
+ link: this._('Learn more')
+
+ },
+ onStatusChange: function(status, chosenBefore) {
+ let type = this.options.type;
+ let didConsent = this.hasConsented();
+ if (type === 'opt-in' && didConsent) {
+ console.log("enable cookies")
+ window.location.reload();
+ }
+ if (type === 'opt-in' && !didConsent) {
+ console.log("disable cookies")
+ window.location.reload();
+ }
+ }
+ })
}
}
}) |
771e7c0d485a6a0e45d550d555beb500e256ebde | react/react-practice/src/actions/lifeCycleActions.js | react/react-practice/src/actions/lifeCycleActions.js | import {firebaseApp,firebaseAuth,firebaseDb, firebaseStorage, firebaseAuthInstance } from '../components/Firebase.js'
import { browserHistory } from 'react-router';
export function goToNextState() {
return function(dispatch) {
dispatch({type: "GET_SCHEDULE"})
}
}
export function testPromise() {
let response = new Promise()
return function(dispatch) {
dispatch({type: "TEST_PROMISE"})
}
} | import {firebaseApp,firebaseAuth,firebaseDb, firebaseStorage, firebaseAuthInstance } from '../components/Firebase.js'
import { browserHistory } from 'react-router';
export function goToNextState() {
return function(dispatch) {
dispatch({type: "GET_SCHEDULE"})
}
}
export function testPromise() {
let response = new Promise((resolve, reject) => {
function(dispatch) {
dispatch({type: "TEST_PROMISE"})
}
})
return function(dispatch) {
dispatch({type: "TEST_PROMISE"})
}
}
| Test promise in the actions | Test promise in the actions | JavaScript | mit | jeremykid/FunAlgorithm,jeremykid/FunAlgorithm,jeremykid/FunAlgorithm,jeremykid/FunAlgorithm | ---
+++
@@ -8,7 +8,11 @@
}
export function testPromise() {
- let response = new Promise()
+ let response = new Promise((resolve, reject) => {
+ function(dispatch) {
+ dispatch({type: "TEST_PROMISE"})
+ }
+ })
return function(dispatch) {
dispatch({type: "TEST_PROMISE"})
} |
b9ed588780e616228d133b91117b80930d658140 | src/components/PlaybackCtrl/PlaybackCtrlContainer.js | src/components/PlaybackCtrl/PlaybackCtrlContainer.js | import { connect } from 'react-redux'
import PlaybackCtrl from './PlaybackCtrl'
import { requestPlay, requestPause, requestVolume, requestPlayNext } from 'store/modules/status'
// Object of action creators (can also be function that returns object).
const mapActionCreators = {
requestPlay,
requestPlayNext,
requestPause,
requestVolume,
}
const mapStateToProps = (state) => {
return {
isAdmin: state.user.isAdmin,
isInRoom: state.user.roomId !== null,
isPlaying: state.status.isPlaying,
isAtQueueEnd: state.status.isAtQueueEnd,
volume: state.status.volume,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlaybackCtrl)
| import { connect } from 'react-redux'
import PlaybackCtrl from './PlaybackCtrl'
import { requestPlay, requestPause, requestVolume, requestPlayNext } from 'store/modules/status'
// Object of action creators (can also be function that returns object).
const mapActionCreators = {
requestPlay,
requestPlayNext,
requestPause,
requestVolume,
}
const mapStateToProps = (state) => {
return {
isAdmin: state.user.isAdmin,
isInRoom: state.user.roomId !== null,
isPlaying: state.status.isPlaying,
isAtQueueEnd: state.status.isAtQueueEnd,
volume: state.status.volume,
isPlayerPresent: state.status.isPlayerPresent,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlaybackCtrl)
| Add missing status prop for PlaybackCtrl | Add missing status prop for PlaybackCtrl
| JavaScript | isc | bhj/karaoke-forever,bhj/karaoke-forever | ---
+++
@@ -17,6 +17,7 @@
isPlaying: state.status.isPlaying,
isAtQueueEnd: state.status.isAtQueueEnd,
volume: state.status.volume,
+ isPlayerPresent: state.status.isPlayerPresent,
}
}
|
66b91190f513893efbe7eef9beba1925e32a44d5 | lib/build-navigation/index.js | lib/build-navigation/index.js | 'use strict';
const path = require('path');
const buildNavigation = function(styleguideArray) {
let options = this;
options.navigation = {};
styleguideArray.forEach((obj) => {
let fileName = (obj.writeName || obj.title).replace(/ /g, '_').toLowerCase() + '.html';
options.navigation[obj.title] = fileName;
});
return styleguideArray;
};
module.exports = buildNavigation;
| 'use strict';
const buildNavigation = function(styleguideArray) {
let options = this,
_nav = {};
options.navigation = {};
styleguideArray.forEach((obj) => {
let fileName = (obj.writeName || obj.title).replace(/ /g, '_').toLowerCase() + '.html';
_nav[obj.title] = fileName;
});
Object.keys(_nav)
.sort()
.forEach(function(v, i) {
options.navigation[v] = _nav[v];
});
return styleguideArray;
};
module.exports = buildNavigation;
| Update navigation to be in alphabetical order | Update navigation to be in alphabetical order
| JavaScript | mit | tbremer/live-guide,tbremer/live-guide | ---
+++
@@ -1,17 +1,22 @@
'use strict';
-const path = require('path');
-
const buildNavigation = function(styleguideArray) {
- let options = this;
+ let options = this,
+ _nav = {};
options.navigation = {};
styleguideArray.forEach((obj) => {
let fileName = (obj.writeName || obj.title).replace(/ /g, '_').toLowerCase() + '.html';
- options.navigation[obj.title] = fileName;
+ _nav[obj.title] = fileName;
});
+
+ Object.keys(_nav)
+ .sort()
+ .forEach(function(v, i) {
+ options.navigation[v] = _nav[v];
+ });
return styleguideArray;
}; |
de7a0b64dcd24892e0333f9e77f56ca6117cae5a | cli/main.js | cli/main.js | #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
const UCompiler = require('..')
const knownCommands = ['go', 'watch']
const parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
| #!/usr/bin/env node
'use strict'
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
var UCompiler = require('..')
var knownCommands = ['go', 'watch']
var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]')
process.exit(0)
}
if (parameters[0] === 'go') {
UCompiler.compile(parameters[1] || null, {cwd: process.cwd()}).catch(function(e) {
console.error(e)
process.exit(1)
})
} else if (parameters[0] === 'watch') {
if (!parameters[1]) {
console.error('You must specify a path to watch')
process.exit(1)
}
UCompiler.watch(parameters[1])
}
| Use art instead of const in cli file | :art: Use art instead of const in cli file
| JavaScript | mit | steelbrain/UCompiler | ---
+++
@@ -3,9 +3,9 @@
process.title = 'ucompiler'
require('debug').enable('UCompiler:*')
-const UCompiler = require('..')
-const knownCommands = ['go', 'watch']
-const parameters = process.argv.slice(2)
+var UCompiler = require('..')
+var knownCommands = ['go', 'watch']
+var parameters = process.argv.slice(2)
if (!parameters.length || knownCommands.indexOf(parameters[0]) === -1) {
console.log('Usage: ucompiler go|watch [path]') |
ac0c31a94428c1180ef7b309c79410bfc28ccdf0 | config.js | config.js | var env = process.env.NODE_ENV || 'development';
var defaults = {
"static": {
port: 3003
},
"socket": {
options: {
origins: '*:*',
log: true,
heartbeats: false,
authorization: false,
transports: [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
],
'log level': 1,
'flash policy server': true,
'flash policy port': 3013,
'destroy upgrade': true,
'browser client': true,
'browser client minification': true,
'browser client etag': true,
'browser client gzip': false
}
},
"nohm": {
url: 'localhost',
port: 6379,
db: 2,
prefix: 'admin'
},
"redis": {
url: 'localhost',
port: 6379,
db: 2
},
"sessions": {
secret: "super secret cat",
db: 1
}
};
if (env === 'production' || env === 'staging') {
defaults["static"].port = 80;
}
if (env === 'staging') {
defaults['static'].port = 3004;
}
module.exports = defaults;
| var env = process.env.NODE_ENV || 'development';
var defaults = {
"static": {
port: 3003
},
"socket": {
options: {
origins: '*:*',
log: true,
heartbeats: false,
authorization: false,
transports: [
'websocket',
'flashsocket',
'htmlfile',
'xhr-polling',
'jsonp-polling'
],
'log level': 1,
'flash policy server': true,
'flash policy port': 3013,
'destroy upgrade': true,
'browser client': true,
'browser client minification': true,
'browser client etag': true,
'browser client gzip': false
}
},
"nohm": {
url: 'localhost',
port: 6379,
db: 2,
prefix: 'admin'
},
"redis": {
url: 'localhost',
port: 6379,
db: 2
},
"sessions": {
secret: "super secret cat",
db: 1
}
};
module.exports = defaults;
| Remove prod/staging ports so people don't get the idea to run this on these environments | Remove prod/staging ports so people don't get the idea to run this on these environments
| JavaScript | mit | maritz/nohm-admin,maritz/nohm-admin | ---
+++
@@ -44,12 +44,4 @@
}
};
-if (env === 'production' || env === 'staging') {
- defaults["static"].port = 80;
-}
-
-if (env === 'staging') {
- defaults['static'].port = 3004;
-}
-
module.exports = defaults; |
fb0993fb10b597884fb37f819743bce9d63accb0 | src/main/webapp/resources/js/apis/galaxy/galaxy.js | src/main/webapp/resources/js/apis/galaxy/galaxy.js | import axios from "axios";
export const getGalaxyClientAuthentication = clientId =>
axios
.get(
`${window.TL.BASE_URL}ajax/galaxy-export/authorized?clientId=${clientId}`
)
.then(({ data }) => data);
export const getGalaxySamples = () =>
axios
.get(`${window.TL.BASE_URL}ajax/galaxy-export/samples`)
.then(({ data }) => data);
export const exportToGalaxy = (
email,
makepairedcollection,
oauthCode,
oauthRedirect,
samples
) => {
const name = `IRIDA-${Math.random()
.toString()
.slice(2, 14)}`;
const params = {
_embedded: {
library: { name },
user: { email },
addtohistory: true, // Default according to Phil Mabon
makepairedcollection,
oauth2: {
code: oauthCode,
redirect: oauthRedirect
},
samples
}
};
const form = document.forms["js-galaxy-form"];
if (typeof form === "undefined") {
throw new Error(`Expecting the galaxy form with name "js-galaxy-form"`);
} else {
const input = form.elements["js-query"];
input.value = JSON.stringify(params);
form.submit();
}
};
| import axios from "axios";
export const getGalaxyClientAuthentication = clientId =>
axios
.get(
`${window.TL.BASE_URL}ajax/galaxy-export/authorized?clientId=${clientId}`
)
.then(({ data }) => data);
export const getGalaxySamples = () =>
axios
.get(`${window.TL.BASE_URL}ajax/galaxy-export/samples`)
.then(({ data }) => data);
export const exportToGalaxy = (
email,
makepairedcollection,
oauthCode,
oauthRedirect,
samples
) => {
const name = `IRIDA-${Date.now()}`;
/*
This structure is expected by galaxy.
*/
const params = {
_embedded: {
library: { name },
user: { email },
addtohistory: true, // Default according to Phil Mabon
makepairedcollection,
oauth2: {
code: oauthCode,
redirect: oauthRedirect
},
samples
}
};
const form = document.forms["js-galaxy-form"];
if (typeof form === "undefined") {
throw new Error(`Expecting the galaxy form with name "js-galaxy-form"`);
} else {
const input = form.elements["js-query"];
input.value = JSON.stringify(params);
form.submit();
}
};
| Update library name to be a timestamp | Update library name to be a timestamp
Signed-off-by: Josh Adam <8493dc4643ddc08e2ef6b4cf76c12d4ffb7203d1@canada.ca>
| JavaScript | apache-2.0 | phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida,phac-nml/irida | ---
+++
@@ -19,9 +19,11 @@
oauthRedirect,
samples
) => {
- const name = `IRIDA-${Math.random()
- .toString()
- .slice(2, 14)}`;
+ const name = `IRIDA-${Date.now()}`;
+
+ /*
+ This structure is expected by galaxy.
+ */
const params = {
_embedded: {
library: { name }, |
6c8ce552cf95452c35a9e5d4a322960bfdf94572 | src/helpers/replacePath.js | src/helpers/replacePath.js | import resolveNode from "../helpers/resolveNode";
import match from "../helpers/matchRedirect";
import {relative, dirname} from "path";
export default function (t, originalPath, {opts: {root, extensions}, file: {opts: {filename}}}, regexps) {
const requiredFilename = resolveNode(dirname(filename), originalPath.node.value, extensions);
console.log("requiredFilename:", requiredFilename);
// console.log("Options:", {regexps, root});
const {redirect, redirected} = match(requiredFilename, regexps, root, extensions);
console.log("CALCULATED REDIRECT:", redirected);
// args[0] = t.stringLiteral("PPAth");
// path has a corresponing redirect
if(redirected !== null) {
// console.log("from:", dirname(filename));
// console.log("rel:", relative(dirname(filename), redirected));
// args[0] = t.stringLiteral(redirected);
if(redirected.includes("/node_modules/")) {
if(resolveNode(dirname(filename), redirect, extensions)) {
console.log("FINAL -- MODULE", redirect);
originalPath.replaceWith(t.stringLiteral(redirect));
return;
}
}
let relativeRedirect = relative(dirname(filename), redirected);
if(!relativeRedirect.startsWith(".")) relativeRedirect = "./" + relativeRedirect;
originalPath.replaceWith(t.stringLiteral(relativeRedirect));
}
} | import resolveNode from "../helpers/resolveNode";
import match from "../helpers/matchRedirect";
import {relative, dirname, extname} from "path";
export default function (t, originalPath, {opts: {root, extensions}, file: {opts: {filename}}}, regexps) {
const requiredFilename = resolveNode(dirname(filename), originalPath.node.value, extensions);
console.log("requiredFilename:", requiredFilename);
// console.log("Options:", {regexps, root});
const {redirect, redirected} = match(requiredFilename, regexps, root, extensions);
console.log("CALCULATED REDIRECT:", redirected);
// args[0] = t.stringLiteral("PPAth");
// path has a corresponing redirect
if(redirected !== null) {
// console.log("from:", dirname(filename));
// console.log("rel:", relative(dirname(filename), redirected));
// args[0] = t.stringLiteral(redirected);
if(redirected.includes("/node_modules/")) {
if(resolveNode(dirname(filename), redirect, extensions)) {
console.log("FINAL -- MODULE", redirect);
originalPath.replaceWith(t.stringLiteral(redirect));
return;
}
}
let relativeRedirect = relative(dirname(filename), redirected);
if(!relativeRedirect.startsWith(".")) relativeRedirect = "./" + relativeRedirect;
if(!extname(redirect)) {
const ext = extname(relativeRedirect);
if(ext) relativeRedirect = relativeRedirect.slice(0, -ext.length);
}
originalPath.replaceWith(t.stringLiteral(relativeRedirect));
}
} | Fix file extension added when redirect didn't have one | fix(replacement): Fix file extension added when redirect didn't have one
| JavaScript | mit | Velenir/babel-plugin-import-redirect | ---
+++
@@ -1,6 +1,6 @@
import resolveNode from "../helpers/resolveNode";
import match from "../helpers/matchRedirect";
-import {relative, dirname} from "path";
+import {relative, dirname, extname} from "path";
export default function (t, originalPath, {opts: {root, extensions}, file: {opts: {filename}}}, regexps) {
const requiredFilename = resolveNode(dirname(filename), originalPath.node.value, extensions);
@@ -27,6 +27,11 @@
let relativeRedirect = relative(dirname(filename), redirected);
if(!relativeRedirect.startsWith(".")) relativeRedirect = "./" + relativeRedirect;
+ if(!extname(redirect)) {
+ const ext = extname(relativeRedirect);
+ if(ext) relativeRedirect = relativeRedirect.slice(0, -ext.length);
+ }
+
originalPath.replaceWith(t.stringLiteral(relativeRedirect));
}
} |
3ba06c96a3181c46b2c52a1849bfc284f05e9596 | experiments/GitHubGistUserCreator.js | experiments/GitHubGistUserCreator.js | const bcrypt = require('bcrypt');
const GitHub = require('github-api');
const crypto = require('crypto');
const { User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
// Authenticate using a GitHub Token
const ghClient = new GitHub({
token: GITHUB_API_TOKEN
});
const userGist = ghClient.getGist(GITHUB_GIST_ID);
userGist.read((err, gist) => {
if (err) {
console.error(err);
return;
}
JSON.parse(gist['files']['users.json']['content']).forEach((user) => { // eslint-disable-line dot-notation
const current_date = (new Date()).valueOf().toString();
const random = Math.random().toString();
const password = crypto.createHmac('sha1', current_date).update(random).digest('hex');
user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
return User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password)
.then(() => {
email.sendUserCreateEmail(user.email, user.nameNumber, password);
return;
})
.catch(console.error);
});
});
| const bcrypt = require('bcrypt');
const GitHub = require('github-api');
const crypto = require('crypto');
const { Spot, User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
const GITHUB_GIST_ID = process.env.GITHUB_GIST_ID;
// Authenticate using a GitHub Token
const ghClient = new GitHub({
token: GITHUB_API_TOKEN
});
const userGist = ghClient.getGist(GITHUB_GIST_ID);
userGist.read((err, gist) => {
if (err) {
console.error(err);
return;
}
JSON.parse(gist['files']['users.json']['content']).forEach((user) => { // eslint-disable-line dot-notation
const current_date = (new Date()).valueOf().toString();
const random = Math.random().toString();
const password = crypto.createHmac('sha1', current_date).update(random).digest('hex');
user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
return Spot.create(user.spotId)
.then(() => User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password))
.then(() => {
email.sendUserCreateEmail(user.email, user.nameNumber, password);
return;
})
.catch((err) => {
console.error(err);
console.log(user);
});
});
});
| Create spot along with user | Create spot along with user
| JavaScript | mit | osumb/challenges,osumb/challenges,osumb/challenges,osumb/challenges | ---
+++
@@ -2,7 +2,7 @@
const GitHub = require('github-api');
const crypto = require('crypto');
-const { User } = require('../models');
+const { Spot, User } = require('../models');
const { email } = require('../utils');
const GITHUB_API_TOKEN = process.env.GITHUB_TOKEN;
@@ -27,11 +27,15 @@
const password = crypto.createHmac('sha1', current_date).update(random).digest('hex');
user.password = bcrypt.hashSync(password, bcrypt.genSaltSync(1)); // eslint-disable-line no-sync
- return User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password)
+ return Spot.create(user.spotId)
+ .then(() => User.create(user.name, user.nameNumber, user.instrument, user.part, user.role, user.spotId, user.email, user.password))
.then(() => {
email.sendUserCreateEmail(user.email, user.nameNumber, password);
return;
})
- .catch(console.error);
+ .catch((err) => {
+ console.error(err);
+ console.log(user);
+ });
});
}); |
b4801f092fde031842c4858dda1794863ecaf2d9 | app/assets/javascripts/replies.js | app/assets/javascripts/replies.js | jQuery(function() {
jQuery('a[href=#preview]').click(function(e) {
var form = jQuery('#new_reply');
jQuery.ajax({
url: form.attr('action'),
type: 'post',
data: {
reply: {
content: form.find('#reply_content').val()
}
},
success: function(data) {
var html = jQuery(data).find('#preview').html();
jQuery('#preview').html(html);
}
});
});
});
| jQuery(function() {
jQuery('a[href=#preview]').click(function(e) {
var form = jQuery(this).parents('form');
jQuery.ajax({
url: '/previews/new',
type: 'get',
data: {
content: form.find('textarea').val(),
},
success: function(data) {
jQuery('#preview').html(data);
}
});
});
});
| Switch to preview rendering in seperate controller | Switch to preview rendering in seperate controller
| JavaScript | agpl-3.0 | paradime/brimir,Gitlab11/brimir,johnsmithpoten/brimir,mbchandar/brimir,himeshp/brimir,viddypiddy/brimir,git-jls/brimir,hadifarnoud/brimir,ask4prasath/brimir_clone,Gitlab11/brimir,fiedl/brimir,johnsmithpoten/brimir,viddypiddy/brimir,fiedl/brimir,Gitlab11/brimir,ask4prasath/madGeeksAimWeb,paradime/brimir,mbchandar/brimir,ask4prasath/brimirclone,paradime/brimir,mbchandar/brimir,git-jls/brimir,viddypiddy/brimir,vartana/brimir,Gitlab11/brimir,ivaldi/brimir,fiedl/brimir,johnsmithpoten/brimir,vartana/brimir,ivaldi/brimir,hadifarnoud/brimir,ask4prasath/brimirclone,git-jls/brimir,mbchandar/brimir,fiedl/brimir,hadifarnoud/brimir,vartana/brimir,ivaldi/brimir,ivaldi/brimir,git-jls/brimir,himeshp/brimir,ask4prasath/madGeeksAimWeb,himeshp/brimir,vartana/brimir,ask4prasath/brimir_clone,himeshp/brimir,hadifarnoud/brimir,ask4prasath/brimir_clone,paradime/brimir,ask4prasath/madGeeksAimWeb,ask4prasath/brimirclone,viddypiddy/brimir | ---
+++
@@ -1,19 +1,15 @@
jQuery(function() {
-
+
jQuery('a[href=#preview]').click(function(e) {
- var form = jQuery('#new_reply');
+ var form = jQuery(this).parents('form');
jQuery.ajax({
- url: form.attr('action'),
- type: 'post',
+ url: '/previews/new',
+ type: 'get',
data: {
- reply: {
- content: form.find('#reply_content').val()
- }
+ content: form.find('textarea').val(),
},
success: function(data) {
- var html = jQuery(data).find('#preview').html();
-
- jQuery('#preview').html(html);
+ jQuery('#preview').html(data);
}
});
}); |
3c84d34e41b14f43b8229fadbce86312ac19f964 | ast/call.js | ast/call.js | module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkNumberOfArguments(this.callee.referent);
this.checkArgumentNamesAndPositionalRules(this.callee.referent);
}
checkNumberOfArguments(callee) {
const numArgs = this.args.length;
const numRequiredParams = callee.requiredParameterNames.size;
const numParams = callee.allParameterNames.size;
if (numArgs < numRequiredParams) {
// We have to at least cover all the required parameters
throw new Error(`Expected at least ${numRequiredParams} arguments but called with ${numArgs}`);
}
if (numArgs > numParams) {
// We can't pass more arguments than the total number of parameters
throw new Error(`Expected at most ${numParams} arguments but called with ${numArgs}`);
}
}
checkArgumentNamesAndPositionalRules(callee) {
let keywordArgumentSeen = false;
this.args.forEach((arg) => {
if (arg.id) {
// This is a keyword argument, record that fact and check that it's okay
keywordArgumentSeen = true;
if (!callee.allParameterNames.has(arg.id)) {
throw new Error(`Function does not have a parameter called ${arg.id}`);
}
} else if (keywordArgumentSeen) {
// This is a positional argument, but a prior one was a keyword one
throw new Error('Positional argument in call after keyword argument');
}
});
}
};
| module.exports = class Call {
constructor(callee, args) {
this.callee = callee;
this.args = args;
}
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
this.checkArgumentMatching(this.callee.referent);
}
checkArgumentMatching(callee) {
let keywordArgumentSeen = false;
const matchedParameterNames = new Set([]);
this.args.forEach((arg, index) => {
if (index >= callee.params.length) {
throw new Error('Too many arguments in call');
}
if (arg.id) {
keywordArgumentSeen = true;
} else if (keywordArgumentSeen) {
throw new Error('Positional argument in call after keyword argument');
}
const parameterName = arg.id ? arg.id : callee.params[index].id;
if (!callee.allParameterNames.has(parameterName)) {
throw new Error(`Function does not have a parameter called ${parameterName}`);
}
if (matchedParameterNames.has(parameterName)) {
throw new Error(`Multiple arguments for parameter ${parameterName}`);
}
matchedParameterNames.add(parameterName);
});
// Look for and report a required parameter that is not matched
const miss = [...callee.requiredParameterNames].find(name => !matchedParameterNames.has(name));
if (miss) {
throw new Error(`Required parameter ${miss} is not matched in call`);
}
}
};
| Implement proper parameter matching rules | Implement proper parameter matching rules
| JavaScript | mit | rtoal/plainscript | ---
+++
@@ -7,37 +7,35 @@
analyze(context) {
this.callee.analyze(context);
context.assertIsFunction(this.callee.referent);
- this.checkNumberOfArguments(this.callee.referent);
- this.checkArgumentNamesAndPositionalRules(this.callee.referent);
+ this.checkArgumentMatching(this.callee.referent);
}
- checkNumberOfArguments(callee) {
- const numArgs = this.args.length;
- const numRequiredParams = callee.requiredParameterNames.size;
- const numParams = callee.allParameterNames.size;
- if (numArgs < numRequiredParams) {
- // We have to at least cover all the required parameters
- throw new Error(`Expected at least ${numRequiredParams} arguments but called with ${numArgs}`);
- }
- if (numArgs > numParams) {
- // We can't pass more arguments than the total number of parameters
- throw new Error(`Expected at most ${numParams} arguments but called with ${numArgs}`);
+ checkArgumentMatching(callee) {
+ let keywordArgumentSeen = false;
+ const matchedParameterNames = new Set([]);
+ this.args.forEach((arg, index) => {
+ if (index >= callee.params.length) {
+ throw new Error('Too many arguments in call');
+ }
+ if (arg.id) {
+ keywordArgumentSeen = true;
+ } else if (keywordArgumentSeen) {
+ throw new Error('Positional argument in call after keyword argument');
+ }
+ const parameterName = arg.id ? arg.id : callee.params[index].id;
+ if (!callee.allParameterNames.has(parameterName)) {
+ throw new Error(`Function does not have a parameter called ${parameterName}`);
+ }
+ if (matchedParameterNames.has(parameterName)) {
+ throw new Error(`Multiple arguments for parameter ${parameterName}`);
+ }
+ matchedParameterNames.add(parameterName);
+ });
+
+ // Look for and report a required parameter that is not matched
+ const miss = [...callee.requiredParameterNames].find(name => !matchedParameterNames.has(name));
+ if (miss) {
+ throw new Error(`Required parameter ${miss} is not matched in call`);
}
}
-
- checkArgumentNamesAndPositionalRules(callee) {
- let keywordArgumentSeen = false;
- this.args.forEach((arg) => {
- if (arg.id) {
- // This is a keyword argument, record that fact and check that it's okay
- keywordArgumentSeen = true;
- if (!callee.allParameterNames.has(arg.id)) {
- throw new Error(`Function does not have a parameter called ${arg.id}`);
- }
- } else if (keywordArgumentSeen) {
- // This is a positional argument, but a prior one was a keyword one
- throw new Error('Positional argument in call after keyword argument');
- }
- });
- }
}; |
1d59470c25001556346e252ca344fa7f4d26c453 | jquery.observe_field.js | jquery.observe_field.js | // jquery.observe_field.js
(function( $ ){
jQuery.fn.observe_field = function(frequency, callback) {
frequency = frequency * 1000; // translate to milliseconds
return this.each(function(){
var $this = $(this);
var prev = $this.val();
var check = function() {
var val = $this.val();
if(prev != val){
prev = val;
$this.map(callback); // invokes the callback on $this
}
};
var reset = function() {
if(ti){
clearInterval(ti);
ti = setInterval(check, frequency);
}
};
check();
var ti = setInterval(check, frequency); // invoke check periodically
// reset counter after user interaction
$this.bind('keyup click mousemove', reset); //mousemove is for selects
});
};
})( jQuery );
| // jquery.observe_field.js
(function( $ ){
jQuery.fn.observe_field = function(frequency, callback) {
frequency = frequency * 1000; // translate to milliseconds
return this.each(function(){
var $this = $(this);
var prev = $this.val();
var check = function() {
if(removed()){ // if removed clear the interval and don't fire the callback
if(ti) clearInterval(ti);
return;
}
var val = $this.val();
if(prev != val){
prev = val;
$this.map(callback); // invokes the callback on $this
}
};
var removed = function() {
return $this.closest('html').length == 0
};
var reset = function() {
if(ti){
clearInterval(ti);
ti = setInterval(check, frequency);
}
};
check();
var ti = setInterval(check, frequency); // invoke check periodically
// reset counter after user interaction
$this.bind('keyup click mousemove', reset); //mousemove is for selects
});
};
})( jQuery );
| Fix bug in IE9 when observed elements are removed from the DOM | Fix bug in IE9 when observed elements are removed from the DOM
| JavaScript | mit | splendeo/jquery.observe_field,splendeo/jquery.observe_field | ---
+++
@@ -12,11 +12,20 @@
var prev = $this.val();
var check = function() {
+ if(removed()){ // if removed clear the interval and don't fire the callback
+ if(ti) clearInterval(ti);
+ return;
+ }
+
var val = $this.val();
if(prev != val){
prev = val;
$this.map(callback); // invokes the callback on $this
}
+ };
+
+ var removed = function() {
+ return $this.closest('html').length == 0
};
var reset = function() {
@@ -36,4 +45,3 @@
};
})( jQuery );
- |
30a3ce599413db184f2ccc19ec362ea8d88f60e6 | js/component-graphic.js | js/component-graphic.js | define([], function () {
'use strict';
var ComponentGraphic = function (options) {
this.color = options.color || "#dc322f";
};
ComponentGraphic.prototype.paint = function paint(gc) {
gc.fillStyle = this.color;
gc.fillRect(0, 0, 15, 15);
};
return ComponentGraphic;
});
| define([], function () {
'use strict';
var ComponentGraphic = function (options) {
options = options || {};
this.color = options.color || "#dc322f";
};
ComponentGraphic.prototype.paint = function paint(gc) {
gc.fillStyle = this.color;
gc.fillRect(0, 0, 15, 15);
};
return ComponentGraphic;
});
| Set default options for graphic component | Set default options for graphic component
| JavaScript | mit | floriico/onyx,floriico/onyx | ---
+++
@@ -2,6 +2,7 @@
'use strict';
var ComponentGraphic = function (options) {
+ options = options || {};
this.color = options.color || "#dc322f";
};
|
69d2d2a7450b91b3533a18ad2c51e009dd3c58f7 | frontend/webpack.config.js | frontend/webpack.config.js | const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
// Extract CSS into a separate file
const extractSass = new ExtractTextPlugin({
filename: "../css/main.css",
});
// Minify JavaScript
const UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin();
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './client/js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/js'),
},
module: {
rules: [
// Process Sass files
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
minimize: true,
}
}, {
loader: "postcss-loader",
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
// Transpile JavaScript files
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
// JavaScript linter
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
// Process images
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
}
]
}
]
},
plugins: [
extractSass,
UglifyJsPlugin,
]
}
| const webpack = require('webpack');
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const path = require('path');
// Extract CSS into a separate file
const extractSass = new ExtractTextPlugin({
filename: "../css/main.css",
});
// Minify JavaScript
const UglifyJsPlugin = new webpack.optimize.UglifyJsPlugin();
module.exports = {
devtool: 'cheap-module-eval-source-map',
entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/js'),
},
module: {
rules: [
// Process Sass files
{
test: /\.scss$/,
use: extractSass.extract({
use: [{
loader: "css-loader",
options: {
minimize: true,
}
}, {
loader: "postcss-loader",
}, {
loader: "sass-loader"
}],
fallback: "style-loader"
})
},
// Transpile JavaScript files
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel-loader',
},
// JavaScript linter
{
test: /\.js$/,
exclude: /node_modules/,
loader: "eslint-loader",
},
// Process images
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'url-loader',
}
]
}
]
},
plugins: [
extractSass,
UglifyJsPlugin,
]
}
| Fix Webpack entry module path | Fix Webpack entry module path
| JavaScript | bsd-2-clause | rub/alessiorapini.me,rub/alessiorapini.me | ---
+++
@@ -14,7 +14,7 @@
module.exports = {
devtool: 'cheap-module-eval-source-map',
- entry: './client/js/index.js',
+ entry: './js/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'static/js'), |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.