commit
stringlengths 40
40
| old_file
stringlengths 4
264
| new_file
stringlengths 4
264
| old_contents
stringlengths 0
3.26k
| new_contents
stringlengths 1
4.43k
| subject
stringlengths 15
624
| message
stringlengths 15
4.7k
| lang
stringclasses 3
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
---|---|---|---|---|---|---|---|---|---|
3cd107a985bcfd81b79633f06d3c21fe641f68c5
|
app/js/services.js
|
app/js/services.js
|
'use strict';
/* Services */
var splitcoinServices = angular.module('splitcoin.services', ['ngResource']);
// Demonstrate how to register services
// In this case it is a simple value service.
splitcoinServices.factory('Ticker', ['$resource',
function($resource){
return $resource('/sampledata/ticker.json', {}, {
query: {method:'GET'}
});
}
]);
|
'use strict';
/* Services */
var splitcoinServices = angular.module('splitcoin.services', ['ngResource']);
// Demonstrate how to register services
// In this case it is a simple value service.
splitcoinServices.factory('Ticker', ['$resource',
function($resource){
// For real data use: http://blockchain.info/ticker
return $resource('/sampledata/ticker.json', {}, {
query: {method:'GET'}
});
}
]);
|
Add comment about real data
|
Add comment about real data
|
JavaScript
|
mit
|
kpeatt/splitcoin,kpeatt/splitcoin,kpeatt/splitcoin
|
e324b674c13a39b54141acaa0ab31ebc66177eb2
|
app/assets/javascripts/umlaut/expand_contract_toggle.js
|
app/assets/javascripts/umlaut/expand_contract_toggle.js
|
/* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content.
The JS needs to swap out the image for expand/contract toggle. AND we need
the URL it swaps in to be an ABSOLUTE url when we're using partial html
widget.
So we swap in a non-fingerprinted URL, even if the original was asset
pipline fingerprinted. sorry, best way to make it work!
*/
jQuery(document).ready(function($) {
$(".collapse-toggle").live("click", function(event) {
$(this).collapse('toggle');
event.preventDefault();
return false;
});
$(".collapse").live("shown", function(event) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Hide ");
});
$(".collapse").live("hidden", function(event) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Show ");
});
});
|
/* expand_contract_toggle.js: Support for show more/hide more in lists of umlaut content.
The JS needs to swap out the image for expand/contract toggle. AND we need
the URL it swaps in to be an ABSOLUTE url when we're using partial html
widget.
So we swap in a non-fingerprinted URL, even if the original was asset
pipline fingerprinted. sorry, best way to make it work!
*/
jQuery(document).ready(function($) {
$(".collapse-toggle").live("click", function(event) {
event.preventDefault();
$(this).collapse('toggle');
return false;
});
$(".collapse").live("shown", function(event) {
// Hack cuz collapse don't work right
if($(this).hasClass('in')) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-closed").addClass("umlaut_icons-list-open");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Hide ");
}
});
$(".collapse").live("hidden", function(event) {
// Hack cuz collapse don't work right
if(!$(this).hasClass('in')) {
// Update the icon
$(this).parent().find('.collapse-toggle i').removeClass("umlaut_icons-list-open").addClass("umlaut_icons-list-closed");
// Update the action label
$(this).parent().find(".expand_contract_action_label").text("Show ");
}
});
});
|
Add JS hack cuz Bootstrap don't work right with collapsible.
|
Add JS hack cuz Bootstrap don't work right with collapsible.
|
JavaScript
|
mit
|
team-umlaut/umlaut,team-umlaut/umlaut,team-umlaut/umlaut
|
e23a40064468c27be76dbb27efd4e4f2ac91ece5
|
app/js/arethusa.core/directives/arethusa_grid_handle.js
|
app/js/arethusa.core/directives/arethusa_grid_handle.js
|
"use strict";
angular.module('arethusa.core').directive('arethusaGridHandle', [
function() {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs, ctrl, transclude) {
},
templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html'
};
}
]);
|
"use strict";
angular.module('arethusa.core').directive('arethusaGridHandle', [
function() {
return {
restrict: 'E',
scope: true,
link: function(scope, element, attrs, ctrl, transclude) {
function mouseEnter() {
scope.$apply(function() { scope.visible = true; });
}
function mouseLeave(event) {
scope.$apply(function() { scope.visible = false; });
}
var trigger = element.find('.drag-handle-trigger');
var handle = element.find('.drag-handle');
trigger.bind('mouseenter', mouseEnter);
handle.bind('mouseleave', mouseLeave);
},
templateUrl: 'templates/arethusa.core/arethusa_grid_handle.html'
};
}
]);
|
Fix mouse events in arethusaGridHandle
|
Fix mouse events in arethusaGridHandle
|
JavaScript
|
mit
|
PonteIneptique/arethusa,Masoumeh/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,alpheios-project/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,latin-language-toolkit/arethusa
|
21b22e766902e94c60f6a257bde1dae9b7a16975
|
index.js
|
index.js
|
const yaml = require('js-yaml');
const ignore = require('ignore');
module.exports = robot => {
robot.on('pull_request.opened', autolabel);
robot.on('pull_request.synchronize', autolabel);
async function autolabel(context) {
const content = await context.github.repos.getContent(context.repo({
path: '.github/autolabeler.yml'
}));
const config = yaml.load(Buffer.from(content.data.content, 'base64').toString());
const files = await context.github.pullRequests.getFiles(context.issue());
const changedFiles = files.data.map(file => file.filename);
const labels = new Set();
// eslint-disable-next-line guard-for-in
for (const label in config) {
robot.log('looking for changes', label, config[label]);
const matcher = ignore().add(config[label]);
if (changedFiles.find(file => matcher.ignores(file))) {
labels.add(label);
}
}
const labelsToAdd = Array.from(labels);
robot.log('Adding labels', labelsToAdd);
if (labelsToAdd.length > 0) {
return context.github.issues.addLabels(context.issue({
labels: labelsToAdd
}));
}
}
};
|
const yaml = require('js-yaml');
const ignore = require('ignore');
module.exports = robot => {
robot.on('pull_request.opened', autolabel);
robot.on('pull_request.synchronize', autolabel);
async function autolabel(context) {
const content = await context.github.repos.getContent(context.repo({
path: '.github/autolabeler.yml'
}));
const config = yaml.safeLoad(Buffer.from(content.data.content, 'base64').toString());
const files = await context.github.pullRequests.getFiles(context.issue());
const changedFiles = files.data.map(file => file.filename);
const labels = new Set();
// eslint-disable-next-line guard-for-in
for (const label in config) {
robot.log('looking for changes', label, config[label]);
const matcher = ignore().add(config[label]);
if (changedFiles.find(file => matcher.ignores(file))) {
labels.add(label);
}
}
const labelsToAdd = Array.from(labels);
robot.log('Adding labels', labelsToAdd);
if (labelsToAdd.length > 0) {
return context.github.issues.addLabels(context.issue({
labels: labelsToAdd
}));
}
}
};
|
Use yaml safeLoad instead of load
|
Use yaml safeLoad instead of load
|
JavaScript
|
isc
|
SymbiFlow/autolabeler
|
5e579bd846f2fd223688dbfeca19b8a9a9f98295
|
src/config.js
|
src/config.js
|
import dotenv from "dotenv";
import moment from "moment";
dotenv.load();
export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test";
export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test";
export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates";
export const LOG_LEVEL = process.env.LOG_LEVEL || "info";
export const ALLOWED_SOURCES = ["reading", "forecast"];
export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds();
export const FORMULAS_COLLECTION = "virtual-sensors-formulas";
export const PRODUCER = "iwwa-lambda-virtual-aggregator";
export const EVENT_READING_INSERTED = "element inserted in collection readings";
|
import dotenv from "dotenv";
import moment from "moment";
dotenv.load();
export const MONGODB_URL = process.env.MONGODB_URL || "mongodb://localhost:27017/test";
export const KINESIS_STREAM_NAME = process.env.KINESIS_STREAM_NAME || "test";
export const AGGREGATES_COLLECTION_NAME = process.env.AGGREGATES_COLLECTION_NAME || "readings-daily-aggregates";
export const LOG_LEVEL = process.env.LOG_LEVEL || "info";
export const ALLOWED_SOURCES = ["reading", "forecast", "reference"];
export const DEFAULT_SAMPLE_DELTA_IN_MS = moment.duration(5, "minutes").asMilliseconds();
export const FORMULAS_COLLECTION = "virtual-sensors-formulas";
export const PRODUCER = "iwwa-lambda-virtual-aggregator";
export const EVENT_READING_INSERTED = "element inserted in collection readings";
|
Add reference to allowed sources
|
Add reference to allowed sources
|
JavaScript
|
apache-2.0
|
innowatio/iwwa-lambda-virtual-aggregator,innowatio/iwwa-lambda-virtual-aggregator
|
eaf923a11d75bbdb5373cd4629d31e4a38c5a659
|
js/rapido.utilities.js
|
js/rapido.utilities.js
|
(function($, window, document, undefined) {
$.rapido_Utilities = {
// Get class of element object
getClass: function(el) {
el = $(el).attr('class').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
return '.' + el.split(' ').join('.');
},
// Remove dot from class
dotlessClass: function(string) {
return string.slice(1);
},
// Check if an element exist
elemExist: function(string) {
return $(string).length !== 0;
}
};
})(jQuery, window, document);
|
(function($, window, document, undefined) {
$.rapido_Utilities = {
// Get class of element object
getClass: function(el) {
var attr = $(el).attr('class');
if (typeof attr !== 'undefined' && attr !== false) {
el = $(el).attr('class').replace(/^\s\s*/, '').replace(/\s\s*$/, '');
return '.' + el.split(' ').join('.');
}
},
// Remove dot from class
dotlessClass: function(string) {
return string.slice(1);
},
// Check if an element exist
elemExist: function(string) {
return $(string).length !== 0;
}
};
})(jQuery, window, document);
|
Fix error in IE8 "attr(...)' is null or not an object"
|
Fix error in IE8 "attr(...)' is null or not an object"
|
JavaScript
|
mit
|
raffone/rapido,raffone/rapido,raffone/rapido
|
018018062b1a4f127d4861707ec9c438248a8dab
|
index.js
|
index.js
|
"use strict";
var glob = require("glob");
var path = require("path");
module.exports = function (content, sourceMap) {
this.cacheable && this.cacheable();
var resourceDir = path.dirname(this.resourcePath);
var pattern = content.trim();
var files = glob.sync(pattern, {
cwd: resourceDir,
realpath: true
});
if (!files.length) {
this.emitWarning('Did not find anything for glob "' + pattern + '" in directory "' + resourceDir + '"');
}
return "module.exports = [\n" + files.map(function (file) {
this.addDependency(file);
return " require(" + JSON.stringify(file) + ")"
}.bind(this)).join(",\n") + "\n];"
};
|
"use strict";
var glob = require("glob");
var path = require("path");
module.exports = function (content, sourceMap) {
var resourceDir = path.dirname(this.resourcePath);
var pattern = content.trim();
var files = glob.sync(pattern, {
cwd: resourceDir,
realpath: true
});
if (!files.length) {
this.emitWarning('Did not find anything for glob "' + pattern + '" in directory "' + resourceDir + '"');
}
return "module.exports = [\n" + files.map(function (file) {
this.addDependency(file);
return " require(" + JSON.stringify(file) + ")"
}.bind(this)).join(",\n") + "\n];"
};
|
Revert "feat: make results cacheable"
|
Revert "feat: make results cacheable"
This reverts commit 43ac8eee4f33ac43c97ed6831a3660b1387148cb.
|
JavaScript
|
mit
|
seanchas116/glob-loader
|
f2ac02fcd69265f4e045883f5b033a91dd4e406d
|
index.js
|
index.js
|
var fs = require('fs'),
path = require('path')
module.exports = function (target) {
var directory = path.dirname(module.parent.filename),
rootDirectory = locatePackageJson(directory)
return requireFromRoot(target, rootDirectory)
}
function locatePackageJson(directory) {
try {
fs.readFileSync(path.join(directory, 'package.json'))
return directory
} catch (e) {}
if (directory === path.resolve('/')) {
return
} else {
directory = path.join(directory, '..')
return locatePackageJson(directory)
}
}
function requireFromRoot(target, directory) {
return require(path.join(directory, target))
}
|
"use strict";
// Node
var lstatSync = require("fs").lstatSync;
var path = require("path");
/**
* Attempts to find the project root by finding the nearest package.json file.
* @private
* @param {String} currentPath - Path of the file doing the including.
* @return {String?}
*/
function findProjectRoot(currentPath) {
var result = undefined;
try {
var packageStats = lstatSync(path.join(currentPath, "package.json"));
if (packageStats.isFile()) {
result = currentPath;
}
} catch (error) {
if (currentPath !== path.resolve("/")) {
result = findProjectRoot(path.join(currentPath, ".."));
}
}
return result;
}
/**
* Creates the include function wrapper around <code>require</code> based on the path of the calling file and not the
* install location of the module.
* @param {String} callerPath - Path of the calling file.
* @return {Function}
* @example
*
* var include = require("include")(__dirname);
*
* var projectFn = include("src/method");
*/
function createInclude(callerPath) {
return function (target) {
var projectRoot = findProjectRoot(callerPath);
return projectRoot ?
require(path.join(projectRoot, target)) :
require(target);
};
}
module.exports = createInclude;
|
Fix relative path being relative to install location and not requesting file
|
Fix relative path being relative to install location and not requesting file
Fixes #2.
|
JavaScript
|
mit
|
anthonynichols/node-include
|
78da26a359947988dbcacd635600909764b410a3
|
src/UCP/AbsenceBundle/Resources/public/js/app/views/planningview.js
|
src/UCP/AbsenceBundle/Resources/public/js/app/views/planningview.js
|
App.Views.PlanningView = Backbone.View.extend({
className: 'planning',
initialize: function() {
this.lessons = this.collection;
this.lessons.on('add change remove reset', this.render, this);
},
render: function() {
var lessons = this.lessons.toArray();
// Build day views and keep DOM elements for insertion
var elements = [];
this.groupByDay(lessons, function(date, lessons) {
var view = new App.Views.PlanningDayView({
date: date,
lessons: lessons
});
view.render();
elements.push(view.el);
});
this.$el.append(elements);
return this;
},
groupByDay: function(lessons, iterator) {
// Lessons are expected in date sorted order
var lastDate, // The day we are working on
lessonDate, // The date of of currently evaluated lesson
lessonBag = []; // Temporary array holding holding lessons between each iterator call
_.each(lessons, function(lesson) {
lessonDate = new Date(lesson.get('start'));
lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely
if (lessonDate > lastDate) {
// We changed of day: call iterator and reset lesson bag
iterator(lastDate, lessonBag);
lessonBag = [];
}
lessonBag.push(lesson);
lastDate = lessonDate;
});
}
});
|
App.Views.PlanningView = Backbone.View.extend({
className: 'planning',
initialize: function() {
this.lessons = this.collection;
this.lessons.on('add change remove reset', this.render, this);
},
render: function() {
var lessons = this.lessons.toArray();
// Build day views and keep DOM elements for insertion
var elements = [];
this.groupByDay(lessons, function(date, lessons) {
var view = new App.Views.PlanningDayView({
date: date,
lessons: lessons
});
view.render();
elements.push(view.el);
});
this.$el.append(elements);
return this;
},
groupByDay: function(lessons, iterator) {
// Lessons are expected in date sorted order
var lastDate, // The day we are working on
lessonDate, // The date of of currently evaluated lesson
lessonBag = []; // Temporary array holding holding lessons between each iterator call
_.each(lessons, function(lesson) {
lessonDate = moment(lesson.get('start')).toDate();
lessonDate.setHours(0,0,0,0); // We strip time components to compare date reliablely
if (lessonDate > lastDate) {
// We changed of day: call iterator and reset lesson bag
iterator(lastDate, lessonBag);
lessonBag = [];
}
lessonBag.push(lesson);
lastDate = lessonDate;
});
}
});
|
Fix planning page on Safari
|
Fix planning page on Safari
new Date("…") cannot parse ISO8601 with a timezone on certain non-fully
ES5 compliant browsers
|
JavaScript
|
mit
|
mdarse/take-the-register,mdarse/take-the-register
|
e32792f7b23aa899a083f0618d1b093f93101e9f
|
src/errors.js
|
src/errors.js
|
export function ValidationError(message, details = {}) {
const {
columns = {},
value = null
} = details;
this.message = message;
this.columns = columns;
this.value = value;
if (message instanceof Error) {
this.message = message.message;
this.stack = message.stack;
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
ValidationError.prototype = Object.create(Error);
ValidationError.prototype.constructor = ValidationError;
ValidationError.prototype.toString = Error.prototype.toString;
Object.defineProperty(ValidationError, 'name', {
value: 'ValidationError'
});
|
export function ValidationError(message, details = {}) {
const {
columns = {},
value = null
} = details;
this.message = message;
this.columns = columns;
this.value = value;
if (message instanceof Error) {
this.message = message.message;
this.stack = message.stack;
} else if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
ValidationError.prototype = Object.create(Error);
ValidationError.prototype.constructor = ValidationError;
ValidationError.prototype.toString = Error.prototype.toString;
Object.defineProperty(ValidationError.prototype, 'name', {
value: 'ValidationError'
});
|
Define 'name' on the prototype instead of constructor
|
Define 'name' on the prototype instead of constructor
|
JavaScript
|
mit
|
goodybag/nagoya
|
a4b63fa20875feef9f7e5e940b5873dd8fb2c082
|
index.js
|
index.js
|
'use strict';
const choo = require('choo');
const html = require('choo/html');
const app = choo();
app.model({
state: {
todos: [],
},
reducers: {
addTodo: (state, data) => {
const newTodos = state.todos.slice();
newTodos.push(data);
return {
todos: newTodos,
};
},
},
});
const hTodoLi = (todo) => html`<li>${todo.title}</li>`;
const view = (state, prevState, send) => {
const onTaskSubmition = (e) => {
const userInput = e.target.children[0];
send('addTodo', { title: userInput.value });
userInput.value = '';
e.preventDefault();
};
return html`
<div>
<h1>ChooDo</h1>
<form onsubmit=${onTaskSubmition}>
<input type="text" placeholder="Write your next task here..." id="title" autofocus>
</form>
<ul>
${state.todos.map(hTodoLi)}
</ul>
</div>
`;
}
app.router([
['/', view],
]);
const tree = app.start();
document.body.appendChild(tree);
|
'use strict';
const extend = require('xtend');
const choo = require('choo');
const html = require('choo/html');
const app = choo();
app.model({
state: {
todos: [],
},
reducers: {
addTodo: (state, data) => {
const todo = extend(data, {
completed: false,
});
const newTodos = state.todos.slice();
newTodos.push(data);
return {
todos: newTodos,
};
},
},
});
const hTodoLi = (todo) => html`
<li>
<input type="checkbox" ${todo.completed ? 'checked' : ''} />
${todo.title}
</li>`;
const view = (state, prevState, send) => {
const onTaskSubmition = (e) => {
const userInput = e.target.children[0];
send('addTodo', { title: userInput.value });
userInput.value = '';
e.preventDefault();
};
return html`
<div>
<h1>ChooDo</h1>
<form onsubmit=${onTaskSubmition}>
<input type="text" placeholder="Write your next task here..." id="title" autofocus>
</form>
<ul>
${state.todos.map(hTodoLi)}
</ul>
</div>
`;
}
app.router([
['/', view],
]);
const tree = app.start();
document.body.appendChild(tree);
|
Use `xtend` to add a property to tasks, add view to show state
|
Use `xtend` to add a property to tasks, add view to show state
State is not being saved anywhere.
|
JavaScript
|
mit
|
fernandocanizo/choodo
|
e16f18fadb94f7eee4b71db653e65f4bbe4ab396
|
index.js
|
index.js
|
'use strict';
var eco = require('eco');
exports.name = 'eco';
exports.outputFormat = 'xml';
exports.compile = eco;
|
'use strict';
var eco = require('eco');
exports.name = 'eco';
exports.outputFormat = 'html';
exports.compile = eco;
|
Fix to use `html` outputFormat
|
Fix to use `html` outputFormat
|
JavaScript
|
mit
|
jstransformers/jstransformer-eco,jstransformers/jstransformer-eco
|
3908e9c9fea87ec27ab8ce3434f14f0d50618e11
|
src/js/app.js
|
src/js/app.js
|
'use strict';
/**
* @ngdoc Main App module
* @name app
* @description Main entry point of the application
*
*/
angular.module('app', [
'ui.router', 'ui.bootstrap',
'app.environment',
'module.core'
]).config(function($urlRouterProvider, ENV) {
$urlRouterProvider.otherwise('/app');
}).run(function() {});
|
'use strict';
/**
* @ngdoc Main App module
* @name app
* @description Main entry point of the application
*
*/
angular.module('app', [
'ui.router', 'ui.bootstrap',
'app.environment',
'module.core'
]).config(function($urlRouterProvider, ENV) {
$urlRouterProvider.otherwise('/page/home');
}).run(function() {});
|
Change default route to pages/home
|
Change default route to pages/home
|
JavaScript
|
mit
|
genu/simple-frontend-boilerplate,genu/simple-angular-boilerplate,genu/simple-frontend-boilerplate,genu/simple-angular-boilerplate
|
951adf61d874553956ac63d2268629d7b2a603ec
|
core/imagefile.js
|
core/imagefile.js
|
function ImageFile(_game) {
this.game = _game;
this.name = new Array();
this.data = new Array();
this.counter = 0;
return this;
};
ImageFile.prototype.load = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
var s = new Sprite(_imageSrc, _width, _height);
s.image = this.getImageDataByName(_imageSrc);
this.game.current.scene.sprite.push(s);
return s;
};
ImageFile.prototype.isLoaded = function() {
if(this.counter === this.data.length) {
return true;
}
return false;
};
ImageFile.prototype.getImageDataByName = function(_imageName) {
return this.data[this.name.indexOf(_imageName)];
};
|
function ImageFile(_game) {
this.game = _game;
this.name = new Array();
this.data = new Array();
this.counter = 0;
return this;
};
ImageFile.prototype.load = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
var s = new Sprite(_imageSrc, _width, _height);
s.image = this.getImageDataByName(_imageSrc);
this.game.current.scene.sprite.push(s);
return s;
};
ImageFile.prototype.loadMap = function(_imageSrc, _width, _height) {
if(!this.getImageDataByName(_imageSrc)) {
var self = this;
var _image = new Image();
_image.src = _imageSrc;
_image.addEventListener('load', function(){self.counter++});
this.name.push(_imageSrc);
this.data.push(_image);
}
return this.getImageDataByName(_imageSrc);
}
ImageFile.prototype.isLoaded = function() {
if(this.counter === this.data.length) {
return true;
}
return false;
};
ImageFile.prototype.getImageDataByName = function(_imageName) {
return this.data[this.name.indexOf(_imageName)];
};
|
Create loadMap function to load map images
|
Create loadMap function to load map images
|
JavaScript
|
mit
|
fjsantosb/Molecule
|
9f71330ad43cb188feef6a6c6053ae9f6dd731f5
|
index.js
|
index.js
|
var babelPresetEs2015,
commonJsPlugin,
es2015PluginList,
es2015WebpackPluginList;
babelPresetEs2015 = require('babel-preset-es2015');
try {
// npm ^2
commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
if (!commonJsPlugin) {
try {
// npm ^3
commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
}
if (!commonJsPlugin) {
throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".');
}
es2015PluginList = babelPresetEs2015.plugins;
es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) {
return es2015Plugin !== commonJsPlugin;
});
if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) {
throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.');
}
module.exports = {
plugins: es2015WebpackPluginList
};
|
var babelPresetEs2015,
commonJsPlugin,
es2015PluginList,
es2015WebpackPluginList;
babelPresetEs2015 = require('babel-preset-es2015');
try {
// npm ^3
commonJsPlugin = require('babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
if (!commonJsPlugin) {
try {
// npm ^2
commonJsPlugin = require('babel-preset-es2015/node_modules/babel-plugin-transform-es2015-modules-commonjs');
} catch (error) {
}
}
if (!commonJsPlugin) {
throw new Error('Cannot resolve "babel-plugin-transform-es2015-modules-commonjs".');
}
es2015PluginList = babelPresetEs2015.plugins;
es2015WebpackPluginList = es2015PluginList.filter(function (es2015Plugin) {
return es2015Plugin !== commonJsPlugin;
});
if (es2015PluginList.length !== es2015WebpackPluginList.length + 1) {
throw new Error('Cannot remove "babel-plugin-transform-es2015-modules-commonjs" from the plugin list.');
}
module.exports = {
plugins: es2015WebpackPluginList
};
|
Fix module resolution for npm 3+
|
Fix module resolution for npm 3+
|
JavaScript
|
bsd-3-clause
|
gajus/babel-preset-es2015-webpack
|
8929cc57fe95f1802a7676250ed489562f76c8db
|
index.js
|
index.js
|
/* jshint node: true */
'use strict';
var request = require('request');
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-cdnify-purge-cache',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'],
didDeploy: function(context) {
let config = context.config['cdnify-purge-cache']
let apiKey = config['cdnifyApiKey'];
let resourceId = config['cdnifyResourceId'];
let endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`;
let credentials = `${apiKey}:x`;
var self = this;
return new Promise(function(resolve, reject) {
request({
url: `https://${credentials}@${endpoint}`,
method: "DELETE"
}, function(error, response, body) {
if(error) {
self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true });
reject(error);
} else {
self.log("CDNIFY CACHE PURGED!", { verbose: true });
resolve(body);
}
})
});
}
});
return new DeployPlugin();
}
};
|
/* jshint node: true */
'use strict';
var request = require('request');
var BasePlugin = require('ember-cli-deploy-plugin');
module.exports = {
name: 'ember-cli-deploy-cdnify-purge-cache',
createDeployPlugin: function(options) {
var DeployPlugin = BasePlugin.extend({
name: options.name,
requiredConfig: ['cdnifyResourceId', 'cdnifyApiKey'],
didDeploy: function(context) {
var config = context.config['cdnify-purge-cache']
var apiKey = config['cdnifyApiKey'];
var resourceId = config['cdnifyResourceId'];
var endpoint = `cdnify.com/api/v1/resources/${resourceId}/cache`;
var credentials = `${apiKey}:x`;
var self = this;
return new Promise(function(resolve, reject) {
request({
url: `https://${credentials}@${endpoint}`,
method: "DELETE"
}, function(error, response, body) {
if(error) {
self.log("CDNIFY CACHE *NOT* PURGED!", { verbose: true });
reject(error);
} else {
self.log("CDNIFY CACHE PURGED!", { verbose: true });
resolve(body);
}
})
});
}
});
return new DeployPlugin();
}
};
|
Remove let until upstream Ember-CLI issue is fixed
|
Remove let until upstream Ember-CLI issue is fixed
|
JavaScript
|
mit
|
fauxton/ember-cli-deploy-cdnify-purge-cache,fauxton/ember-cli-deploy-cdnify-purge-cache
|
fbed9d4aac28c0ef9d5070b31aeec9de09009e26
|
index.js
|
index.js
|
var url = require('url')
module.exports = function(uri, cb) {
var parsed
try {
parsed = url.parse(uri)
}
catch (err) {
return cb(err)
}
if (!parsed.host) {
return cb(new Error('Invalid url: ' + uri))
}
var opts = {
host: parsed.host
, port: parsed.port
, path: parsed.path
, method: 'HEAD'
, agent: false
}
var http = parsed.protocol === 'https:'
? require('https')
: require('http')
var req = http.request(opts)
req.end()
req.on('response', function(res) {
var code = res.statusCode
if (code >= 400) {
return cb(new Error('Received invalid status code: ' + code))
}
cb(null, +res.headers['content-length'])
})
}
|
var request = require('request')
module.exports = function(options, cb) {
if ('string' === typeof options) {
options = {
uri: options
}
}
options = options || {}
options.method = 'HEAD'
options.followAllRedirects = true
request(options, function(err, res, body) {
if (err) return cb(err)
var code = res.statusCode
if (code >= 400) {
return cb(new Error('Received invalid status code: ' + code))
}
var len = res.headers['content-length']
if (!len) {
return cb(new Error('Unable to determine file size'))
}
if (isNaN(+len)) {
return cb(new Error('Invalid Content-Length received'))
}
cb(null, +res.headers['content-length'])
})
}
|
Use request and allow passing object
|
Use request and allow passing object
|
JavaScript
|
mit
|
evanlucas/remote-file-size
|
05e85127b8a0180651c0d5eba9116106fbc40ce9
|
index.js
|
index.js
|
/* eslint-env node */
'use strict';
module.exports = {
name: 'ember-cli-flagpole',
flagpoleConfigPath: 'config/flagpole',
init() {
this._super.init && this._super.init.apply(this, arguments);
const Registry = require('./lib/-registry');
this._flagRegistry = new Registry();
this.flag = require('./lib/flag')(this._flagRegistry);
},
config: function(env/* , baseConfig */) {
// TODO: check options/overrides in this.app.options
const resolve = require('path').resolve;
const existsSync = require('fs').existsSync;
// TODO: support use as a nested addon?
const projectRoot = this.project.root;
// TODO: check for custom path to flagpole.js
const resolved = resolve(projectRoot, this.flagpoleConfigPath);
if (existsSync(resolved + '.js')) {
require(resolved)(this.flag);
return {
featureFlags: this._flagRegistry.collectFor(env)
};
}
return { featureFlags: 'DEBUG_NONE' };
},
includedCommands() {
return {
'audit-flags': require('./lib/commands/audit-flags'),
};
},
};
|
/* eslint-env node */
'use strict';
const DEFAULT_CFG_PATH = 'config/flagpole';
const DEFAULT_CFG_PROPERTY = 'featureFlags';
module.exports = {
name: 'ember-cli-flagpole',
isDevelopingAddon() { return true; },
flagpoleConfigPath: DEFAULT_CFG_PATH,
flagpolePropertyName: DEFAULT_CFG_PROPERTY,
init() {
this._super.init && this._super.init.apply(this, arguments);
const Registry = require('./lib/-registry');
this._flagRegistry = new Registry();
this.flag = require('./lib/flag')(this._flagRegistry);
},
included(app) {
const options = app.options['ember-cli-flagpole'] || {};
this.flagpoleConfigPath = options.configPath || DEFAULT_CFG_PATH;
this.flagpolePropertyName = options.propertyName || DEFAULT_CFG_PROPERTY;
},
config: function(env/* , baseConfig */) {
const resolve = require('path').resolve;
const existsSync = require('fs').existsSync;
// TODO: support use as a nested addon?
const projectRoot = this.project.root;
// TODO: check for custom path to flagpole.js
const resolved = resolve(projectRoot, this.flagpoleConfigPath);
if (existsSync(resolved + '.js')) {
require(resolved)(this.flag);
return {
[this.flagpolePropertyName]: this._flagRegistry.collectFor(env)
};
}
return { [this.flagpolePropertyName]: 'DEBUG_NONE' };
},
includedCommands() {
return {
'audit-flags': require('./lib/commands/audit-flags'),
};
},
};
|
Allow configuration of property name and config path in app *build options* (ember-cli-build.js)
|
Allow configuration of property name and config path in app *build options* (ember-cli-build.js)
|
JavaScript
|
mit
|
camhux/ember-cli-flagpole,camhux/ember-cli-flagpole,camhux/ember-cli-flagpole
|
7920bd541507d35990f146aa45168a4b2f4331be
|
index.js
|
index.js
|
"use strict"
const examine = require("./lib/examine")
const inspect = require("./lib/inspect")
const isPlainObject = require("./lib/is-plain-object")
const whereAll = require("./lib/where-all")
module.exports = { examine, inspect, isPlainObject, whereAll }
|
"use strict"
const { examine, see } = require("./lib/examine")
const inspect = require("./lib/inspect")
const isPlainObject = require("./lib/is-plain-object")
const whereAll = require("./lib/where-all")
module.exports = { examine, inspect, isPlainObject, see, whereAll }
|
Include the missing `see` function
|
Include the missing `see` function
|
JavaScript
|
mit
|
icylace/icylace-object-utils
|
0ed42a900e206c2cd78fdf6b5f6578254394f3e2
|
src/sprites/Common/index.js
|
src/sprites/Common/index.js
|
import Phaser from 'phaser';
export default class extends Phaser.Sprite {
constructor(game, x, y, sprite, frame) {
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
}
}
|
import Phaser from 'phaser';
import { alignToGrid } from '../../tiles';
export default class extends Phaser.Sprite {
constructor(game, x, y, sprite, frame) {
const alignedCoords = alignToGrid({ x, y });
x = alignedCoords.x;
y = alignedCoords.y;
super(game, x, y, sprite, frame);
this.anchor.setTo(0.5, 0.5);
}
}
|
Align to grid before placing object
|
Align to grid before placing object
|
JavaScript
|
mit
|
ThomasMays/incremental-forest,ThomasMays/incremental-forest
|
ae1ac92b8884f41656eda30a0949fec0eceb2428
|
server/services/passport.js
|
server/services/passport.js
|
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');
const mongoose = require('mongoose');
const User = mongoose.model('users'); // retrieve this collection
// Tell passport to use google oauth for authentication
passport.use(
new GoogleStrategy(
{
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback'
},
// Get executed when a user is actually executed. we can store this on the database
// to link this token to a user for later use.
(accessToken, refreshToken, profile, done) => {
User.findOne({googleId: profile.id})
.then( existingUser => {
if ( existingUser ) {
// first arg: no error, second arg: tell passport that this is the user that we just created
done(null, existingUser);
} else {
new User({ googleId: profile.id }) // create a user model instance
.save() //save it to db
.then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process
}
});
} )
);
|
const passport = require('passport');
const GoogleStrategy = require('passport-google-oauth20').Strategy;
const keys = require('../config/keys');
const mongoose = require('mongoose');
const User = mongoose.model('users'); // retrieve this collection
// Tell passport to use google oauth for authentication
passport.use(
new GoogleStrategy(
{
clientID: keys.googleClientID,
clientSecret: keys.googleClientSecret,
callbackURL: '/auth/google/callback'
},
// Get executed when a user is actually executed. we can store this on the database
// to link this token to a user for later use.
(accessToken, refreshToken, profile, done) => {
User.findOne({googleId: profile.id})
.then( existingUser => {
if ( existingUser ) {
// first arg: no error, second arg: tell passport that this is the user that we just created
done(null, existingUser);
} else {
new User({ googleId: profile.id }) // create a user model instance
.save() //save it to db
.then(user => done(null, user)); // finish saving, so we need to call done to finish the OAuth process
}
});
} )
);
// Once we get the user instance from the db ( this happens after the authentication process above finishes )
// We ask passport to use user.id ( not googleId ), created by MongoDb, to send this info to the client
// by setting it in the cookie, so that future requests from the client will have this information in the cookie
// set automatically by the browser
passport.serializeUser( (user, done) => {
done(null, user.id);
});
// Client sends more requests to the server after all the auth process. Passport will use the cookie info
// in the request to create or query for the User instance associated with that info
passport.deserializeUser( (id, done) => {
User.findById(id)
.then(user => done( null, user));
});
// Tell passport that it needs to use cookie to keep track of the currently signed in user
|
Add serialization and deserlization for User
|
Add serialization and deserlization for User
Serialization step: get the user.id as a cookie value and send it back to the client for later user.
Deserialization: client sends make a request with cookie value that can be turned into an actual user instance.
|
JavaScript
|
mit
|
chhaymenghong/FullStackReact
|
4bfa64cf19896baf36af8a21f022771252700c27
|
ui/app/common/components/pnc-temporary-build-record-label/pncTemporaryBuildRecordLabel.js
|
ui/app/common/components/pnc-temporary-build-record-label/pncTemporaryBuildRecordLabel.js
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
'use strict';
angular.module('pnc.common.components').component('pncTemporaryBuildRecordLabel', {
bindings: {
/**
* Object: a Record object representing Build Record
*/
buildRecord: '<?',
/**
* Object: a Record object representing Build Group Record
*/
buildGroupRecord: '<?',
},
templateUrl: 'common/components/pnc-temporary-build-record-label/pnc-temporary-build-record-label.html',
controller: [Controller]
});
function Controller() {
var $ctrl = this;
var buildRecord = $ctrl.buildRecord ? $ctrl.buildRecord : $ctrl.buildGroupRecord;
// -- Controller API --
$ctrl.isTemporary = isTemporary;
// --------------------
function isTemporary() {
return buildRecord.temporaryBuild;
}
}
})();
|
/*
* JBoss, Home of Professional Open Source.
* Copyright 2014-2018 Red Hat, Inc., and individual contributors
* as indicated by the @author tags.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
(function () {
'use strict';
angular.module('pnc.common.components').component('pncTemporaryBuildRecordLabel', {
bindings: {
/**
* Object: a Record object representing Build Record
*/
buildRecord: '<?',
/**
* Object: a Record object representing Build Group Record
*/
buildGroupRecord: '<?',
},
templateUrl: 'common/components/pnc-temporary-build-record-label/pnc-temporary-build-record-label.html',
controller: [Controller]
});
function Controller() {
var $ctrl = this;
var buildRecord;
$ctrl.$onInit = function() {
buildRecord = $ctrl.buildRecord ? $ctrl.buildRecord : $ctrl.buildGroupRecord;
$ctrl.isTemporary = isTemporary;
};
function isTemporary() {
return buildRecord.temporaryBuild;
}
}
})();
|
Fix temporary build label init process
|
Fix temporary build label init process
|
JavaScript
|
apache-2.0
|
thescouser89/pnc,jdcasey/pnc,matedo1/pnc,matedo1/pnc,alexcreasy/pnc,alexcreasy/pnc,jdcasey/pnc,rnc/pnc,matejonnet/pnc,alexcreasy/pnc,matedo1/pnc,pkocandr/pnc,jdcasey/pnc,project-ncl/pnc
|
e39eb6b1f2c4841ddc293428ab0c358214e897ad
|
src/colors.js
|
src/colors.js
|
const colors = {
red: '#e42d40',
white: '#ffffff',
veryLightGray: '#ededed',
lightGray: '#cccccc',
gray: '#888888',
darkGray: '#575757'
}
const brandPreferences = {
primary: colors.red,
bg: colors.white,
outline: colors.lightGray,
placeholder: colors.veryLightGray,
userInput: colors.darkGray
}
export default Object.assign({}, colors, brandPreferences)
|
const colors = {
red: '#e42d40',
white: '#ffffff',
veryLightGray: '#ededed',
lightGray: '#cccccc',
gray: '#888888',
darkGray: '#575757'
}
const brandPreferences = {
primary: colors.red,
bg: colors.white,
outline: colors.lightGray,
placeholder: colors.veryLightGray,
userInput: colors.darkGray
}
export default {
...colors,
...brandPreferences
}
|
Use spread syntax instead of Object.assign
|
Use spread syntax instead of Object.assign
|
JavaScript
|
mit
|
hackclub/api,hackclub/api,hackclub/api
|
edd75a3c15c81feb05d51736af6dd605bb10a72f
|
src/routes.js
|
src/routes.js
|
import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Widgets,
About,
Login,
LoginSuccess,
Survey,
NotFound,
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replaceState, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replaceState(null, '/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
return (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="widgets" component={Widgets}/>
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route onEnter={requireLogin}>
<Route path="chat" component={Chat}/>
<Route path="loginSuccess" component={LoginSuccess}/>
</Route>
<Route path="survey" component={Survey}/>
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Widgets,
About,
Login,
LoginSuccess,
Survey,
NotFound,
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replaceState, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replaceState(null, '/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="chat" component={Chat}/>
<Route path="loginSuccess" component={LoginSuccess}/>
</Route>
{ /* Routes */ }
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
Use alphabetical route order for easier merging
|
Use alphabetical route order for easier merging
|
JavaScript
|
mit
|
ames89/keystone-react-redux,sunh11373/t648,ptim/react-redux-universal-hot-example,andyshora/memory-tools,huangc28/palestine-2,quicksnap/react-redux-universal-hot-example,melodylu/react-redux-universal-hot-example,moje-skoly/web-app,AndriyShepitsen/svredux,dieface/react-redux-universal-hot-example,ThatCheck/AutoLib,dumbNickname/oasp4js-goes-react,lordakshaya/pages,gihrig/react-redux-universal-hot-example,Kronenberg/WebLabsTutorials,PhilNorfleet/pBot,thomastanhb/ericras,delwiv/saphir,TribeMedia/react-redux-universal-hot-example,micooz/react-redux-universal-hot-example,TonyJen/react-redux-universal-hot-example,ames89/keystone-react-redux,tanvip/hackPrinceton,bdefore/universal-redux,MarkPhillips7/happy-holidays,nathanielks/universal-redux,AnthonyWhitaker/react-redux-universal-hot-example,codejunkienick/katakana,sars/appetini-front,CalebEverett/soulpurpose,bdefore/react-redux-universal-hot-example,Widcket/sia,trueter/react-redux-universal-hot-example,hank7444/react-redux-universal-hot-example,PhilNorfleet/pBot,erikras/react-redux-universal-hot-example,tonykung06/realtime-exchange-rates,kiyonish/kiyonishimura,mull/require_hacker_error_reproduction,sfarthin/youtube-search,frankleng/react-redux-universal-hot-example,danieloliveira079/healthy-life-app,guymorita/creditTiger,andbet39/reactPress,eastonqiu/frontend,jeremiahrhall/react-redux-universal-hot-example,sanyamagrawal/royalgeni,reggi/react-shopify-app,avantcontra/react-redux-custom-starter,mscienski/stpauls,bdefore/universal-redux,nase-skoly/web-app,delwiv/tactill-techtest,Dengo/bacon-bacon,elbstack/elbstack-hackreact-web-3,prgits/react-product,vidaaudrey/avanta,hldzlk/wuhao,tpphu/react-pwa,codejunkienick/katakana,Widcket/sia,sseppola/react-redux-universal-hot-example,Smotko/react-redux-universal-hot-example,nathanielks/universal-redux,fforres/coworks,hokustalkshow/friend-landing-page,Trippstan/elephonky,DelvarWorld/some-game,Shabananana/hot-nav,jairoandre/lance-web-hot,RomanovRoman/react-redux-universal-hot-example,hitripod/react-redux-universal-hot-example,user512/teacher_dashboard,Druddigon/react-redux-learn,bertho-zero/react-redux-universal-hot-example,svsool/react-redux-universal-hot-example,TracklistMe/client-web,hldzlk/wuhao,ThatCheck/AutoLib,thingswesaid/seed,fiTTrail/fiTTrail,runnables/react-redux-universal-hot-example,mscienski/stpauls,chrisslater/snapperfish,twomoonsfactory/custom-poll,ipbrennan90/movesort-app,TracklistMe/client-react,thekevinscott/react-redux-universal-starter-kit,ercangursoy/react-dev,EnrikoLabriko/react-redux-universal-hot-example,robertSahm/port,Xvakin/quiz,Widcket/sia,Widcket/react-boilerplate,bazanowsky/react-ssr-exercise,tpphu/react-pwa,delwiv/saphir,yomolify/cc_material
|
3dfaa509dcae64b13f8b68c74fb6085e18c1ccc2
|
src/app/auth/auth.service.js
|
src/app/auth/auth.service.js
|
(function() {
'use strict';
var app = angular.module('radar.auth');
app.factory('authService', function(session, $q, store, adapter) {
return {
login: login
};
function login(username, password) {
var deferred = $q.defer();
adapter.post('/login', {}, {username: username, password: password}).then(function(response) {
var userId = response.data.userId;
var token = response.data.token;
return store.findOne('users', userId)
.then(function(user) {
deferred.resolve({
user: user,
token: token
});
})
.catch(function(response) {
if (response.status === 422) {
deferred.reject(response.data.errors);
} else {
deferred.reject('Error logging in, please try again.');
}
});
});
return deferred.promise;
}
});
})();
|
(function() {
'use strict';
var app = angular.module('radar.auth');
app.factory('authService', function(session, $q, store, adapter) {
return {
login: login
};
function login(username, password) {
var deferred = $q.defer();
adapter.post('/login', {}, {username: username, password: password})
.then(function(response) {
var userId = response.data.userId;
var token = response.data.token;
return store.findOne('users', userId)
.then(function(user) {
deferred.resolve({
user: user,
token: token
});
})
.catch(function() {
deferred.reject('Error logging in, please try again.');
});
})
.catch(function(response) {
if (response.status === 422) {
deferred.reject(response.data.errors);
} else {
deferred.reject('Error logging in, please try again.');
}
});
return deferred.promise;
}
});
})();
|
Add pagination support to API
|
Add pagination support to API
|
JavaScript
|
agpl-3.0
|
renalreg/radar-client,renalreg/radar-client,renalreg/radar-client
|
ad4f2512ab1e42bf19b877c04eddd831cf747fb0
|
models/collections.js
|
models/collections.js
|
var TreeModel = require('tree-model');
module.exports = function(DataTypes) {
return [{
name: {
type: DataTypes.STRING,
allowNull: false
}
}, {
instanceMethods: {
insertIntoDirs: function(UUID, parentUUID) {
var tree = new TreeModel();
var dirs = tree.parse(JSON.parse(this.dirs));
var parent;
if (parentUUID) {
parent = dirs.first(function(node) {
return node.model.UUID === parent;
});
}
if (!parent) {
parent = dirs;
}
parent.addChild(tree.parse({ UUID: UUID }));
this.dirs = JSON.stringify(dirs.model);
return this.save(['dirs']);
}
}
}];
};
|
var TreeModel = require('tree-model');
module.exports = function(DataTypes) {
return [{
name: {
type: DataTypes.STRING,
allowNull: false
}
}];
};
|
Remove unnecessary instance methods of collection
|
Remove unnecessary instance methods of collection
|
JavaScript
|
mit
|
wikilab/wikilab-api
|
f0dc23100b7563c60f62dad82a4aaf364a69c2cb
|
test/index.js
|
test/index.js
|
// require Johnny's static
var JohhnysStatic = require("../index")
// require http
, http = require('http');
// set static server: public folder
JohhnysStatic.setStaticServer({root: "./public"});
// set routes
JohhnysStatic.setRoutes({
"/": { "url": __dirname + "/html/index.html" }
, "/test1/": { "url": __dirname + "/html/test1.html" }
, "/test2/": { "url": __dirname + "/html/test2.html" }
});
// create http server
http.createServer(function(req, res) {
// safe serve
if (JohhnysStatic.exists(req, res)) {
// serve file
JohhnysStatic.serve(req, res, function (err) {
// not found error
if (err.code === "ENOENT") {
// write head
res.writeHead(404, {"Content-Type": "text/html"});
// send response
res.end("404 - Not found.");
// return
return;
}
// other error
res.end(JSON.stringify(err));
});
// return
return;
}
// if the route doesn't exist, it's a 404!
res.end("404 - Not found");
}).listen(8000);
// output
console.log("Listening on 8000.");
|
// require Johnny's static
var JohhnysStatic = require("../index")
// require http
, http = require('http');
// set static server: public folder
JohhnysStatic.setStaticServer({root: __dirname + "/public"});
// set routes
JohhnysStatic.setRoutes({
"/": { "url": "/html/index.html" }
, "/test1/": { "url": "/html/test1.html" }
, "/test2/": { "url": "/html/test2.html" }
});
// create http server
http.createServer(function(req, res) {
// safe serve
if (JohhnysStatic.exists(req, res)) {
// serve file
JohhnysStatic.serve(req, res, function (err) {
// not found error
if (err.code === "ENOENT") {
// write head
res.writeHead(404, {"Content-Type": "text/html"});
// send response
res.end("404 - Not found.");
// return
return;
}
// other error
res.end(JSON.stringify(err));
});
// return
return;
}
// if the route doesn't exist, it's a 404!
res.end("404 - Not found");
}).listen(8000);
// output
console.log("Listening on 8000.");
|
Use __dirname when setting the root
|
Use __dirname when setting the root
|
JavaScript
|
mit
|
IonicaBizauTrash/johnnys-node-static,IonicaBizau/statique,IonicaBizauTrash/johnnys-node-static,IonicaBizau/node-statique,IonicaBizau/johnnys-node-static,IonicaBizau/johnnys-node-static
|
d01325010342043712e1680d4fb577eaa4df3634
|
test/index.js
|
test/index.js
|
'use strict';
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const sass = require('../');
const root = path.resolve(__dirname, './test-cases');
const cases = fs.readdirSync(root);
cases.forEach((test) => {
let hasPackageJson;
try {
hasPackageJson = require(path.resolve(root, test, './package.json'));
} catch (e) {}
describe(test, () => {
before((done) => {
if (hasPackageJson) {
cp.exec('npm install', { cwd: path.resolve(root, test) }, (err) => {
done(err);
});
} else {
done();
}
});
it('can compile from code without error', (done) => {
sass(path.resolve(root, test, './index.scss'), (err, output) => {
done(err);
});
});
it('can compile from cli without error', (done) => {
cp.exec(path.resolve(__dirname, '../bin/npm-sass') + ' index.scss', {
cwd: path.resolve(root, test)
}, (err, stdout) => {
done(err);
});
});
try {// to load test cases from within test case
assertions = require(path.resolve(root, test, './test'));
} catch (e) {}
});
});
|
'use strict';
const fs = require('fs');
const path = require('path');
const cp = require('child_process');
const sass = require('../');
const css = require('css');
const root = path.resolve(__dirname, './test-cases');
const cases = fs.readdirSync(root);
cases.forEach((test) => {
let hasPackageJson;
try {
hasPackageJson = require(path.resolve(root, test, './package.json'));
} catch (e) {}
describe(test, () => {
before((done) => {
if (hasPackageJson) {
cp.exec('npm install', { cwd: path.resolve(root, test) }, (err) => {
done(err);
});
} else {
done();
}
});
it('can compile from code without error', (done) => {
sass(path.resolve(root, test, './index.scss'), (err, output) => {
css.parse(output.css.toString());
done(err);
});
});
it('can compile from cli without error', (done) => {
cp.exec(path.resolve(__dirname, '../bin/npm-sass') + ' index.scss', {
cwd: path.resolve(root, test)
}, (err, stdout) => {
css.parse(stdout);
done(err);
});
});
try {// to load test cases from within test case
assertions = require(path.resolve(root, test, './test'));
} catch (e) {}
});
});
|
Check output is valid css in test cases
|
Check output is valid css in test cases
|
JavaScript
|
mit
|
GeorgeTaveras1231/npm-sass,lennym/npm-sass
|
98943dcae31dbee0ad3e7a4b2b568128a3d20524
|
app/controllers/DefaultController.js
|
app/controllers/DefaultController.js
|
import AppController from './AppController'
export default class DefaultController extends AppController {
async indexAction(context) {
return context.redirectToRoute('hello', {name: 'Christoph', foo: 'bar'})
}
}
|
import AppController from './AppController'
export default class DefaultController extends AppController {
async indexAction(context) {
return context.redirectToRoute('hello', {name: 'Christoph', foo: 'bar'})
}
async missingRouteAction(context) {
return context.redirectToRoute('foobarbazboo')
}
}
|
Add an action that redirects to a missing route
|
Add an action that redirects to a missing route
|
JavaScript
|
mit
|
CHH/learning-node,CHH/learning-node
|
f76d185650f187a509b59e86a09df063a177af78
|
test/utils.js
|
test/utils.js
|
import assert from 'power-assert';
import { camelToKebab } from '../src/utils';
describe('utils', () => {
it('translates camelCase to kebab-case', () => {
assert(camelToKebab('camelCaseToKebabCase') === 'camel-case-to-kebab-case');
});
it('does not add hyphen to the first position', () => {
assert(camelToKebab('FirstPosition') === 'first-position');
});
it('does nothing if there is no camel case string', () => {
assert(camelToKebab('no_camel-string0123') === 'no_camel-string0123');
});
it('adds hyphen between a number and a upper case character', () => {
assert(camelToKebab('camel012Camel') === 'camel012-camel');
});
});
|
import assert from 'power-assert';
import { camelToKebab, assign, pick, mapValues } from '../src/utils';
describe('utils', () => {
describe('camelToKebab', () => {
it('translates camelCase to kebab-case', () => {
assert(camelToKebab('camelCaseToKebabCase') === 'camel-case-to-kebab-case');
});
it('does not add hyphen to the first position', () => {
assert(camelToKebab('FirstPosition') === 'first-position');
});
it('does nothing if there is no camel case string', () => {
assert(camelToKebab('no_camel-string0123') === 'no_camel-string0123');
});
it('adds hyphen between a number and a upper case character', () => {
assert(camelToKebab('camel012Camel') === 'camel012-camel');
});
});
describe('assign', () => {
it('extends the first argument by latter arguments', () => {
const a = { a: 1, b: 1 };
const actual = assign(a, { a: 2, c: 1 }, { d: 1 }, { c: 2 });
assert.deepEqual(a, {
a: 2,
b: 1,
c: 2,
d: 1
});
assert(a === actual);
});
});
describe('pick', () => {
it('picks specified properties', () => {
const a = { a: 1, b: 1, c: 1, d: 1 };
const actual = pick(a, ['a', 'c', 'e']);
assert.deepEqual(actual, { a: 1, c: 1 });
});
});
describe('mapValues', () => {
it('maps the values of an object', () => {
const f = n => n + 1;
const a = { a: 1, b: 2, c: 3 };
const actual = mapValues(a, f);
assert.deepEqual(actual, { a: 2, b: 3, c: 4 });
});
});
});
|
Add test cases for utility functions
|
Add test cases for utility functions
|
JavaScript
|
mit
|
ktsn/vuex-connect,ktsn/vuex-connect
|
069de55f17261315570eff2183b1c042abbec45a
|
services/resource-updater.js
|
services/resource-updater.js
|
'use strict';
var P = require('bluebird');
var _ = require('lodash');
var Schemas = require('../generators/schemas');
function ResourceUpdater(model, params) {
var schema = Schemas.schemas[model.collection.name];
this.perform = function () {
return new P(function (resolve, reject) {
var query = model
.findByIdAndUpdate(params.id, {
$set: params
}, {
new: true
});
_.each(schema.fields, function (field) {
if (field.reference) { query.populate(field); }
});
query
.lean()
.exec(function (err, record) {
if (err) { return reject(err); }
resolve(record);
});
});
};
}
module.exports = ResourceUpdater;
|
'use strict';
var P = require('bluebird');
var _ = require('lodash');
var Schemas = require('../generators/schemas');
function ResourceUpdater(model, params) {
var schema = Schemas.schemas[model.collection.name];
this.perform = function () {
return new P(function (resolve, reject) {
var query = model
.findByIdAndUpdate(params.id, {
$set: params
}, {
new: true
});
_.each(schema.fields, function (field) {
if (field.reference) { query.populate(field.field); }
});
query
.lean()
.exec(function (err, record) {
if (err) { return reject(err); }
resolve(record);
});
});
};
}
module.exports = ResourceUpdater;
|
Fix the populate query on update
|
Fix the populate query on update
|
JavaScript
|
mit
|
SeyZ/forest-express-mongoose
|
073c72bb5caef958a820cdeadc440a042dd4f111
|
test/_page.js
|
test/_page.js
|
import puppeteer from 'puppeteer';
export async function evaluatePage (url, matches, timeout = 4000) {
const args = await puppeteer.defaultArgs();
const browser = await puppeteer.launch({
args: [...args, '--enable-experimental-web-platform-features']
});
const page = await browser.newPage();
await page.goto(url);
try {
return await new Promise((resolve, reject) => {
page.on('console', msg => {
const text = msg.text();
if (text.match(matches)) {
clearTimeout(timer);
resolve(text);
}
});
const timer = setTimeout(() => reject(Error('Timed Out')), timeout);
});
} finally {
await browser.close();
}
}
|
import puppeteer from 'puppeteer';
export async function evaluatePage (url, matches, timeout = 4000) {
const args = await puppeteer.defaultArgs();
const browser = await puppeteer.launch({
args: [
...args,
'--no-sandbox',
'--disable-setuid-sandbox',
'--enable-experimental-web-platform-features'
]
});
const page = await browser.newPage();
await page.goto(url);
try {
return await new Promise((resolve, reject) => {
page.on('console', msg => {
const text = msg.text();
if (text.match(matches)) {
clearTimeout(timer);
resolve(text);
}
});
const timer = setTimeout(() => reject(Error('Timed Out')), timeout);
});
} finally {
await browser.close();
}
}
|
Disable chrome sandbox in tests
|
Disable chrome sandbox in tests
|
JavaScript
|
apache-2.0
|
GoogleChromeLabs/worker-plugin
|
7317ad7bfd9b9d55ab1cf54c09c537a64ea0e798
|
routes/year.js
|
routes/year.js
|
'use strict';
const debug = require('debug')('calendar:routes:year');
const express = require('express');
const common = require('./common');
const monthRouter = require('./month');
const validators = require('../lib/validators');
const kollavarsham = require('./../lib/kollavarsham');
const yearRouter = express.Router();
yearRouter.route('/years/:year').get(validators.validateYear, function (req, res) {
debug('Within the month route');
const year = parseInt(req.params.year, 10);
const output = kollavarsham.getYear(year, req.query.lang);
common.sendAppropriateResponse(req, res, output);
});
yearRouter.use('/years/:year/months', monthRouter);
module.exports = yearRouter;
|
'use strict';
const debug = require('debug')('calendar:routes:year');
const express = require('express');
const common = require('./common');
const monthRouter = require('./month');
const validators = require('../lib/validators');
const kollavarsham = require('./../lib/kollavarsham');
const yearRouter = express.Router();
yearRouter.route('/years/:year').get(validators.validateYear, (req, res) => {
debug('Within the month route');
const year = parseInt(req.params.year, 10);
const output = kollavarsham.getYear(year, req.query.lang);
common.sendAppropriateResponse(req, res, output);
});
yearRouter.use('/years/:year/months', monthRouter);
module.exports = yearRouter;
|
Use arrow functions instead of `function` keyword
|
Use arrow functions instead of `function` keyword
|
JavaScript
|
mit
|
kollavarsham/calendar-api
|
e5954cf78a8daf138ca1a81ead64f1d38719a970
|
public/ssr.js
|
public/ssr.js
|
var ssr = require('done-ssr-middleware');
module.exports = ssr({
config: __dirname + "/package.json!npm",
main: "bitcentive/index.stache!done-autorender",
liveReload: true
});
|
var ssr = require('done-ssr-middleware');
module.exports = ssr({
config: __dirname + "/package.json!npm",
main: "bitcentive/index.stache!done-autorender",
liveReload: true,
auth: {
cookie: "feathers-jwt",
domains: [
"localhost"
]
}
});
|
Add auth-cookie options to SSR.
|
Add auth-cookie options to SSR.
|
JavaScript
|
mit
|
donejs/bitcentive,donejs/bitcentive
|
b404a2f25f0259fd49dbc3f851765e5be2bc7050
|
packages/vega-util/src/logger.js
|
packages/vega-util/src/logger.js
|
function log(level, msg) {
var args = [level].concat([].slice.call(msg));
console.log.apply(console, args); // eslint-disable-line no-console
}
export var None = 0;
export var Warn = 1;
export var Info = 2;
export var Debug = 3;
export default function(_) {
var level = _ || None;
return {
level: function(_) { if (arguments.length) level = +_; return level; },
warn: function() { if (level >= Warn) log('WARN', arguments); },
info: function() { if (level >= Info) log('INFO', arguments); },
debug: function() { if (level >= Debug) log('DEBUG', arguments); }
}
}
|
function log(level, msg) {
var args = [level].concat([].slice.call(msg));
console.log.apply(console, args); // eslint-disable-line no-console
}
export var None = 0;
export var Warn = 1;
export var Info = 2;
export var Debug = 3;
export default function(_) {
var level = _ || None;
return {
level: function(_) { return arguments.length ? (level = +_, this) : level; },
warn: function() { if (level >= Warn) log('WARN', arguments); return this; },
info: function() { if (level >= Info) log('INFO', arguments); return this; },
debug: function() { if (level >= Debug) log('DEBUG', arguments); return this; }
}
}
|
Update logging to return this.
|
Update logging to return this.
|
JavaScript
|
bsd-3-clause
|
vega/vega,vega/vega,vega/vega,lgrammel/vega,vega/vega
|
04fb2218cd6a5d32a0b4c1d8de9b9ad43994888d
|
src/api/routes/verifyGET.js
|
src/api/routes/verifyGET.js
|
const Route = require('../structures/Route');
class verifyGET extends Route {
constructor() {
super('/verify', 'get');
}
run(req, res, user) {
return res.json({
message: 'Successfully verified token',
user
});
}
}
module.exports = verifyGET;
|
const Route = require('../structures/Route');
class verifyGET extends Route {
constructor() {
super('/verify', 'get');
}
run(req, res, user) {
const returnUser = {
id: user.id,
username: user.username,
apiKey: user.apiKey,
isAdmin: user.isAdmin
};
return res.json({
message: 'Successfully verified token',
user: returnUser
});
}
}
module.exports = verifyGET;
|
Return less info to the user when verifying
|
Return less info to the user when verifying
|
JavaScript
|
mit
|
WeebDev/lolisafe,WeebDev/lolisafe,WeebDev/loli-safe,WeebDev/loli-safe
|
de11f73477e3c6881f09b613d87063489756686d
|
packages/modules-runtime/package.js
|
packages/modules-runtime/package.js
|
Package.describe({
name: "modules-runtime",
version: "0.7.10",
summary: "CommonJS module system",
git: "https://github.com/benjamn/install",
documentation: "README.md"
});
Npm.depends({
install: "0.8.8"
});
Package.onUse(function(api) {
api.addFiles(".npm/package/node_modules/install/install.js", [
"client",
"server"
], {
bare: true
});
api.addFiles("modules-runtime.js");
api.export("meteorInstall");
});
Package.onTest(function(api) {
api.use("tinytest");
api.use("modules"); // Test modules-runtime via modules.
api.addFiles("modules-runtime-tests.js");
});
|
Package.describe({
name: "modules-runtime",
version: "0.7.10-rc.4",
summary: "CommonJS module system",
git: "https://github.com/benjamn/install",
documentation: "README.md"
});
Npm.depends({
install: "0.8.8"
});
Package.onUse(function(api) {
api.addFiles(".npm/package/node_modules/install/install.js", [
"client",
"server"
], {
bare: true
});
api.addFiles("modules-runtime.js");
api.export("meteorInstall");
});
Package.onTest(function(api) {
api.use("tinytest");
api.use("modules"); // Test modules-runtime via modules.
api.addFiles("modules-runtime-tests.js");
});
|
Add `-rc.n` suffix to `modules-runtime`.
|
Add `-rc.n` suffix to `modules-runtime`.
|
JavaScript
|
mit
|
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
|
79078552e7df6cb28ef277a2ecf46b9cacd1c7ee
|
lib/config/mongostore.js
|
lib/config/mongostore.js
|
'use strict';
/*
** Module dependencies
*/
var mongoose = require('mongoose');
var util = require('util');
var TTL = 24*3600;
var Schema = new mongoose.Schema({
sid: { type: String, required: true, unique: true },
data: { type: mongoose.Schema.Types.Mixed, required: true },
usedAt: { type: Date, expires: TTL }
});
var Session = mongoose.model('Session', Schema);
module.exports = function(session) {
var Store = session.Store;
function Store(options) {
Store.call(this, options);
}
util.inherits(Store, Store);
Store.prototype.get = function(sid, done) {
Session.findOne({ sid: sid }, function(err, session) {
if (err) return done(err);
if (!session) return done(null, false);
done(null, session.data);
});
};
Store.prototype.set = function(sid, data, done) {
Session.update({ sid: sid }, {
sid: sid,
data: data,
usedAt: new Date()
}, { upsert: true }, done);
};
Store.prototype.destroy = function(sid, done) {
Session.remove({ sid: sid }, done);
};
Store.prototype.clear = function(done) {
Session.collection.drop(done);
};
return Store;
};
|
'use strict';
/*
** Module dependencies
*/
var mongoose = require('mongoose');
var util = require('util');
var TTL = 24*3600;
var Schema = new mongoose.Schema({
sid: { type: String, required: true, unique: true },
data: { type: mongoose.Schema.Types.Mixed, required: true },
usedAt: { type: Date, expires: TTL }
});
var Session = mongoose.model('Session', Schema);
module.exports = function(session) {
var Store = session.Store;
function MongoStore(options) {
Store.call(this, options);
}
util.inherits(Store, Store);
MongoStore.prototype.get = function(sid, done) {
Session.findOne({ sid: sid }, function(err, session) {
if (err) return done(err);
if (!session) return done(null, false);
done(null, session.data);
});
};
MongoStore.prototype.set = function(sid, data, done) {
Session.update({ sid: sid }, {
sid: sid,
data: data,
usedAt: new Date()
}, { upsert: true }, done);
};
MongoStore.prototype.destroy = function(sid, done) {
Session.remove({ sid: sid }, done);
};
MongoStore.prototype.clear = function(done) {
Session.collection.drop(done);
};
return Store;
};
|
Rename Store into MongoStore to pass JSLint
|
Rename Store into MongoStore to pass JSLint
|
JavaScript
|
agpl-3.0
|
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
|
b6e483d624a1a8be8559277d5c430bd470abf68e
|
src/commonmark.transform.js
|
src/commonmark.transform.js
|
"use strict";
var commonmark = require("commonmark");
var markdownTransform = function(){
let reader = new commonmark.Parser();
let writer = new commonmark.HtmlRenderer({
safe: true
});
return function(mimetype, data, document) {
var div = document.createElement("div");
var parsed = reader.parse(data);
// TODO: Any other transformations on the parsed object
// See https://github.com/jgm/commonmark.js#usage
div.innerHTML = writer.render(parsed);
return div;
};
}();
markdownTransform.mimetype = 'text/markdown';
export default markdownTransform;
|
"use strict";
var commonmark = require("commonmark");
var markdownTransform = function(){
// Stick reader and writer in a closure so they only get created once.
let reader = new commonmark.Parser();
let writer = new commonmark.HtmlRenderer({
safe: true
});
return function(mimetype, data, document) {
var div = document.createElement("div");
var parsed = reader.parse(data);
// TODO: Any other transformations on the parsed object
// See https://github.com/jgm/commonmark.js#usage
div.innerHTML = writer.render(parsed);
return div;
};
}();
markdownTransform.mimetype = 'text/markdown';
export default markdownTransform;
|
Comment on why the closure was used.
|
Comment on why the closure was used.
|
JavaScript
|
bsd-3-clause
|
nteract/transformime-commonmark
|
407a8292712cfa3cc6ae9957e6ba22ed1795ad28
|
addon/mixins/version-header-handler.js
|
addon/mixins/version-header-handler.js
|
import Ember from 'ember';
import config from 'ember-get-config';
const {
'ember-new-version-detection': {
appName,
},
} = config;
const {
computed,
inject: {
service,
},
run: {
next: runNext,
},
Mixin,
} = Ember;
export default Mixin.create({
newVersionDetector: service(),
headers: computed('newVersionDetector.reportedVersion', function() {
let reportedVersion = this.get('newVersionDetector.reportedVersion');
return {
'X-App-Version': reportedVersion,
'X-App-Name': appName,
};
}),
handleResponse(_, headers) {
runNext(this, function() {
this.set('newVersionDetector.activeVersion', headers['X-Current-Version']);
});
return this._super(...arguments);
},
});
|
import Ember from 'ember';
import config from 'ember-get-config';
const {
'ember-new-version-detection': {
appName,
},
} = config;
const {
computed,
inject: {
service,
},
run: {
next: runNext,
},
Mixin,
} = Ember;
export default Mixin.create({
newVersionDetector: service(),
headers: computed('newVersionDetector.reportedVersion', function() {
let headers = this._super(...arguments) || {};
headers['X-App-Version'] = this.get('newVersionDetector.reportedVersion');
headers['X-App-Name'] = appName;
return headers;
}),
handleResponse(_, headers) {
runNext(this, function() {
this.set('newVersionDetector.activeVersion', headers['X-Current-Version']);
});
return this._super(...arguments);
},
});
|
Call _super so that we don't stomp on headers returned by other mixins
|
Call _super so that we don't stomp on headers returned by other mixins
|
JavaScript
|
mit
|
PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection,PrecisionNutrition/ember-new-version-detection
|
7168416a52b9b85f1bdee68614a6324f957b219d
|
app/assets/javascripts/main-buttons.js
|
app/assets/javascripts/main-buttons.js
|
/**
* Created by mcgourtyalex on 4/14/15.
*/
var MainButtons = {
// setup sets a callback for #breeder_find keyup
setup: function() {
$('.button-a').hover( function() {
$('#tagline-text').html("Keep breeders <strong>honest</strong> by rating your pup");
});
$('.button-b').click( function() {
$('.box-b').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find the <strong>right</strong> breed for you");
});
$('#cancel-b').click( function() {
$('.box-b').toggleClass("hidden");
});
$('.button-c').click( function() {
$('.box-c').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews");
});
$('#cancel-c').click( function() {
$('.box-c').toggleClass("hidden");
});
}
};
$(document).ready(function () {
$(MainButtons.setup);
});
|
/**
* Created by mcgourtyalex on 4/14/15.
*/
var MainButtons = {
// setup sets a callback for #breeder_find keyup
setup: function() {
$('.button-a').hover( function() {
$('#tagline-text').html("Contribute information about <strong>your<strong> dog to our database");
});
$('.button-b').click( function() {
$('.box-b').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find the <strong>right</strong> breed for you");
});
$('#cancel-b').click( function() {
$('.box-b').toggleClass("hidden");
});
$('.button-c').click( function() {
$('.box-c').toggleClass("hidden");
}).hover( function() {
$('#tagline-text').html("Find a dog breeder with <strong>great</strong> reviews");
});
$('#cancel-c').click( function() {
$('.box-c').toggleClass("hidden");
});
}
};
$(document).ready(function () {
$(MainButtons.setup);
});
|
Change text for hover over rate your pup
|
Change text for hover over rate your pup
|
JavaScript
|
mit
|
hyu596/Simpatico-Pup,hyu596/Simpatico-Pup,eabartlett/ratemypup,cjzcpsyx/rate-my-pup,cjzcpsyx/rate-my-pup,eabartlett/ratemypup,eabartlett/ratemypup,cjzcpsyx/rate-my-pup,cjzcpsyx/rate-my-pup,hyu596/Simpatico-Pup,eabartlett/ratemypup
|
fbd633276f7c5e126777838ec442c72aed5cfb88
|
django_fixmystreet/fixmystreet/static/js/leaflet/example/leaflet-dev.js
|
django_fixmystreet/fixmystreet/static/js/leaflet/example/leaflet-dev.js
|
function getRandomLatLng(map) {
var bounds = map.getBounds(),
southWest = bounds.getSouthWest(),
northEast = bounds.getNorthEast(),
lngSpan = northEast.lng - southWest.lng,
latSpan = northEast.lat - southWest.lat;
return new L.LatLng(southWest.lat + latSpan * Math.random(), southWest.lng + lngSpan * Math.random());
}
|
var STATIC_URL = 'http://127.0.0.1:8000/static/';
function getRandomLatLng(map) {
var bounds = map.getBounds(),
southWest = bounds.getSouthWest(),
northEast = bounds.getNorthEast(),
lngSpan = northEast.lng - southWest.lng,
latSpan = northEast.lat - southWest.lat;
return new L.LatLng(southWest.lat + latSpan * Math.random(), southWest.lng + lngSpan * Math.random());
}
function gettext(s) {
return s;
}
|
Add constant & function for dev.
|
Add constant & function for dev.
|
JavaScript
|
agpl-3.0
|
IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet,IMIO/django-fixmystreet
|
e05370ea9c0a001cee9d9a20ec44e7ea212a3822
|
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
|
DynamixelServo.Quadruped.WebInterface/wwwroot/js/VideoStreaming.js
|
let videoImage = document.getElementById('video_image');
videoImage.src = `http://${document.domain}:8080/?action=stream`;
let cameraJoystick = {
zone: videoImage,
color: 'red'
};
let cameraJoystickManager = nipplejs.create(cameraJoystick);
const clickTimeout = 500;
var lastStartClick = Date.now();
cameraJoystickManager.on('added',
function (evt, nipple) {
nipple.on('move',
function (evt, arg) {
var json = JSON.stringify({
joystickType: 'camera',
angle: arg.angle.radian,
MessageType: 'movement',
distance: arg.distance
});
serverSocket.send(json);
});
nipple.on('start',
function () {
if (lastStartClick - Date.now() < clickTimeout) {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'reset' });
serverSocket.send(json);
} else {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'start' });
serverSocket.send(json);
}
lastStartClick = Date.now();
});
nipple.on('end',
function () {
var json = JSON.stringify({
joystickType: 'camera',
MessageType: 'stop'
});
serverSocket.send(json);
});
});
|
let videoImage = document.getElementById('video_image');
videoImage.src = `http://${document.domain}:8080/?action=stream`;
let cameraJoystick = {
zone: videoImage,
color: 'red'
};
let cameraJoystickManager = nipplejs.create(cameraJoystick);
const clickTimeout = 500;
var lastStartClick = Date.now();
cameraJoystickManager.on('added',
function (evt, nipple) {
nipple.on('move',
function (evt, arg) {
var json = JSON.stringify({
joystickType: 'camera',
angle: arg.angle.radian,
MessageType: 'movement',
distance: arg.distance
});
serverSocket.send(json);
});
nipple.on('start',
function () {
if (Date.now() - lastStartClick < clickTimeout) {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'reset' });
serverSocket.send(json);
} else {
const json = JSON.stringify(
{ joystickType: 'camera', MessageType: 'start' });
serverSocket.send(json);
}
lastStartClick = Date.now();
});
nipple.on('end',
function () {
var json = JSON.stringify({
joystickType: 'camera',
MessageType: 'stop'
});
serverSocket.send(json);
});
});
|
Fix but with reset always triggering
|
Fix but with reset always triggering
|
JavaScript
|
apache-2.0
|
dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo,dmweis/DynamixelServo
|
ee692dc4d7321e7440b681c13ae82fdb8ed97516
|
app/assets/javascripts/angular/dramas/dramas-controller.js
|
app/assets/javascripts/angular/dramas/dramas-controller.js
|
App.controller('DramasCtrl', [ '$http', function($http, $q) {
var dramas = this;
dramas.list1 = 'Drag and Drop with default confirmation';
dramas.items = [];
$http.get('/dramas').then(function(response) {
dramas.items = response.data;
console.log(response.data);
}, function(errResponse) {
console.error('Error while fetching dramas')
});
dramas.beforeDrop = function() {
var deferred = $q.defer();
if (confirm('Are you sure???')) {
deferred.resolve();
} else {
deferred.reject();
}
return deferred.promise;
};
}]);
|
(function(){
'use strict';
angular
.module('secondLead')
.controller('DramasCtrl', [
'DramaModel',
'Restangular',
function(DramaModel, Restangular, $q) {
var dramas = this;
dramas.items = DramaModel.getAll;
dramas.setCurrentDrama = function(item){
dramas.currentDrama = item;
};
}])
})();
|
Update dramactrl to fetch dramas from api using restangular
|
Update dramactrl to fetch dramas from api using restangular
|
JavaScript
|
mit
|
ac-adekunle/secondlead,ac-adekunle/secondlead,ac-adekunle/secondlead
|
a8dde15447d79b73ca12a0a7acf2ff0390f24b49
|
web-client/app/scripts/controllers/profileController.js
|
web-client/app/scripts/controllers/profileController.js
|
'use strict';
angular.module('webClientApp')
.controller('ProfileCtrl', ['$scope', '$rootScope', '$location', '$routeParams', 'UserArticle', 'UserDraft', 'User',
function ($scope, $rootScope, $location, $routeParams, UserArticle, UserDraft, User) {
$scope.user = User.get({'userId': $routeParams.userId});
// Only get drafts if the current profile being viewed and the logged in user
// are the same person.
if ($rootScope.currentUser.id === parseInt($routeParams.userId)) {
$scope.drafts = UserDraft.query({});
}
$scope.articles = UserArticle.query({'userId': $routeParams.userId});
}]);
|
'use strict';
angular.module('webClientApp')
.controller('ProfileCtrl', ['$scope', '$rootScope', '$location', '$routeParams', 'UserArticle', 'UserDraft', 'User',
function ($scope, $rootScope, $location, $routeParams, UserArticle, UserDraft, User) {
$scope.user = User.get({'userId': $routeParams.userId});
// Only get drafts if the current profile being viewed and the logged in user
// are the same person.
if (($rootScope.currentUser &&
$rootScope.currentUser.id === parseInt($routeParams.userId))) {
$scope.drafts = UserDraft.query({});
}
$scope.articles = UserArticle.query({'userId': $routeParams.userId});
}]);
|
Fix non-logged in error when visiting a profile.
|
Fix non-logged in error when visiting a profile.
|
JavaScript
|
bsd-2-clause
|
ahmgeek/manshar,RashaHussein/manshar,mjalajel/manshar,manshar/manshar,ahmgeek/manshar,RashaHussein/manshar,manshar/manshar,ahmgeek/manshar,manshar/manshar,ahmgeek/manshar,mjalajel/manshar,RashaHussein/manshar,mjalajel/manshar,mjalajel/manshar,RashaHussein/manshar,manshar/manshar
|
fdaf5bc5b02619d65ee4a2ef2cf6dbef91e0d480
|
common/predictive-text/unit_tests/headless/worker-intialization.js
|
common/predictive-text/unit_tests/headless/worker-intialization.js
|
var assert = require('chai').assert;
var worker = require('../../worker');
describe('Dummy worker', function() {
describe('#hello()', function() {
it('should return "hello"', function() {
assert.equal(worker.hello(), 'hello');
});
});
});
|
var assert = require('chai').assert;
var worker = require('../../worker');
describe('LMLayerWorker', function() {
describe('#constructor()', function() {
it('should construct with zero arguments', function() {
assert.isOk(new worker.LMLayerWorker);
});
});
});
|
Test whether the LMLayerWorker can be instantiated.
|
Test whether the LMLayerWorker can be instantiated.
|
JavaScript
|
apache-2.0
|
tavultesoft/keymanweb,tavultesoft/keymanweb
|
0241f074b65dbf70f10b5da6ddf0d3bfa161964f
|
api/src/pages/Html.js
|
api/src/pages/Html.js
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render ({ children, assets, title } = this.props) {
return (
<html>
<head>
<title>{title}</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
<meta name='description' content='Analyze your site’s speed according to HTTP best practices.' />
<meta name='author' content='Jan Svager <https://www.svager.cz>' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: children }} />
<script defer src={`/${assets.init.js}`} />
<script defer src={`/${assets.react.js}`} />
<script defer src={`/${assets.app.js}`} />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
import React, { PropTypes } from 'react'
export default class Html extends React.Component {
render ({ children, assets, title } = this.props) {
return (
<html lang='en'>
<head>
<title>{title}</title>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<link type='text/css' rel='stylesheet' href={`/${assets.app.css}`} />
<link rel='dns-prefetch' href='https://github.com/' />
<link rel='dns-prefetch' href='https://www.svager.cz/' />
<meta name='description' content='Analyze your site’s speed according to HTTP best practices.' />
<meta name='author' content='Jan Svager <https://www.svager.cz>' />
</head>
<body>
<div id='app' dangerouslySetInnerHTML={{ __html: children }} />
<script defer src={`/${assets.init.js}`} />
<script defer src={`/${assets.react.js}`} />
<script defer src={`/${assets.app.js}`} />
</body>
</html>
)
}
}
Html.propTypes = {
children: PropTypes.node.isRequired,
title: PropTypes.string.isRequired
}
|
Add lang property to the html tag
|
Add lang property to the html tag
|
JavaScript
|
mit
|
svagi/httptest
|
3c396dff053dceb6472d3283e7b6eeb7f6c6e976
|
app/components/device-mock/component.js
|
app/components/device-mock/component.js
|
import Ember from 'ember';
const { Component } = Ember;
export default Component.extend({
tagName: 'box'
});
|
import Ember from 'ember';
const { Component } = Ember;
export default Component.extend({
tagName: 'div'
});
|
Use div to fix centering
|
Use div to fix centering
|
JavaScript
|
mit
|
shipshapecode/website,shipshapecode/shipshape.io,shipshapecode/shipshape.io,shipshapecode/website
|
9acffe52b1c8dcd806459968c03c96afaad9fb06
|
client/app/scripts/components/node-details/node-details-health-overflow-item.js
|
client/app/scripts/components/node-details/node-details-health-overflow-item.js
|
import React from 'react';
import metricFeeder from '../../hoc/metric-feeder';
import { formatMetric } from '../../utils/string-utils';
function NodeDetailsHealthOverflowItem(props) {
return (
<div className="node-details-health-overflow-item">
<div className="node-details-health-overflow-item-value">
{formatMetric(props.value, props)}
</div>
<div className="node-details-health-overflow-item-label truncate">{props.label}</div>
</div>
);
}
export default metricFeeder(NodeDetailsHealthOverflowItem);
|
import React from 'react';
import { formatMetric } from '../../utils/string-utils';
function NodeDetailsHealthOverflowItem(props) {
return (
<div className="node-details-health-overflow-item">
<div className="node-details-health-overflow-item-value">
{formatMetric(props.value, props)}
</div>
<div className="node-details-health-overflow-item-label truncate">{props.label}</div>
</div>
);
}
export default NodeDetailsHealthOverflowItem;
|
Remove the metricFeeder for the overflow items too for now.
|
Remove the metricFeeder for the overflow items too for now.
|
JavaScript
|
apache-2.0
|
dilgerma/scope,paulbellamy/scope,dilgerma/scope,kinvolk/scope,weaveworks/scope,weaveworks/scope,alban/scope,weaveworks/scope,weaveworks/scope,paulbellamy/scope,kinvolk/scope,kinvolk/scope,alban/scope,paulbellamy/scope,alban/scope,kinvolk/scope,dilgerma/scope,alban/scope,kinvolk/scope,paulbellamy/scope,alban/scope,weaveworks/scope,dilgerma/scope,weaveworks/scope,dilgerma/scope,dilgerma/scope,alban/scope,paulbellamy/scope,kinvolk/scope,paulbellamy/scope
|
3df2bbf433f53347458d6defef06a88937b89d0b
|
rollup.config.js
|
rollup.config.js
|
import nodeResolve from 'rollup-plugin-node-resolve';
import { globalsRegex, GLOBAL } from 'rollup-globals-regex';
export default {
input: 'dist/src/ng-dynamic-component.js',
output: {
file: 'dist/bundles/ng-dynamic-component.es2015.js',
format: 'es',
},
name: 'dynamicComponent',
plugins: [
nodeResolve({ jsnext: true, browser: true })
],
globals: globalsRegex({
'tslib': 'tslib',
[GLOBAL.NG2]: GLOBAL.NG2.TPL,
[GLOBAL.RX]: GLOBAL.RX.TPL,
[GLOBAL.RX_OPERATOR]: GLOBAL.RX_OPERATOR.TPL,
}),
external: (moduleId) => {
if (/^(\@angular|rxjs|tslib)\/?/.test(moduleId)) {
return true;
}
return false;
}
};
|
import nodeResolve from 'rollup-plugin-node-resolve';
import { globalsRegex, GLOBAL } from 'rollup-globals-regex';
export default {
input: 'dist/ng-dynamic-component.js',
output: {
file: 'dist/bundles/ng-dynamic-component.es2015.js',
format: 'es',
},
name: 'dynamicComponent',
plugins: [
nodeResolve({ jsnext: true, browser: true })
],
globals: globalsRegex({
'tslib': 'tslib',
[GLOBAL.NG2]: GLOBAL.NG2.TPL,
[GLOBAL.RX]: GLOBAL.RX.TPL,
[GLOBAL.RX_OPERATOR]: GLOBAL.RX_OPERATOR.TPL,
}),
external: (moduleId) => {
if (/^(\@angular|rxjs|tslib)\/?/.test(moduleId)) {
return true;
}
return false;
}
};
|
Fix path to compiled file
|
build(rollup): Fix path to compiled file
|
JavaScript
|
mit
|
gund/ng-dynamic-component,gund/ng-dynamic-component,gund/ng-dynamic-component
|
3f0ede6159e8f6286112fafe1fbea1ac3b0822c0
|
src/infrastructure/logger.js
|
src/infrastructure/logger.js
|
const bunyan = require('bunyan');
const path = require('path');
const PrettyStream = require('bunyan-prettystream');
const streams = [{
level: (process.env.NODE_ENV === 'development') ? 'debug' : 'info',
path: path.join(__dirname, '/../../log/octopush')
}];
if (process.env.NODE_ENV === 'development') {
const prettyStdOut = new PrettyStream();
prettyStdOut.pipe(process.stdout);
streams.push({level: 'debug', type: 'raw', stream: prettyStdOut});
}
module.exports = bunyan.createLogger({name: 'octopush', streams});
|
const bunyan = require('bunyan');
const path = require('path');
const streams = [
{
level: process.env.NODE_ENV === 'development' ? 'debug' : 'info',
path: path.join(__dirname, '/../../log/octopush')
}
];
if (process.env.NODE_ENV === 'development') {
const PrettyStream = require('bunyan-prettystream');
const prettyStdOut = new PrettyStream();
prettyStdOut.pipe(process.stdout);
streams.push({level: 'debug', type: 'raw', stream: prettyStdOut});
}
module.exports = bunyan.createLogger({name: 'octopush', streams});
|
Move logging dev dependency to dev only code path
|
Move logging dev dependency to dev only code path
|
JavaScript
|
mit
|
octahedron/octopush
|
364c445bab29675b8f0992efec57ca70ed6dd989
|
client/packages/settings-dashboard-extension-worona/src/dashboard/selectorCreators/index.js
|
client/packages/settings-dashboard-extension-worona/src/dashboard/selectorCreators/index.js
|
import { createSelector } from 'reselect';
import * as deps from '../deps';
import * as selectors from '../selectors';
export const getSettingsCreator = (packageName) => createSelector(
selectors.getSettingsLiveCollection,
deps.selectors.getSelectedSiteId,
(settings, siteId) => (
settings.find(
item =>
(item.woronaInfo.name === packageName
&& item.woronaInfo.siteId === siteId)
) || { woronaInfo: {} } // default to empty object til settings collections is loaded
)
);
export const getSettingCreator = packageName => (settingName, settingDefault = undefined) =>
createSelector(
getSettingsCreator(packageName),
settings => (settings && settings[settingName]) || settingDefault
);
|
import { createSelector } from 'reselect';
import * as deps from '../deps';
import * as selectors from '../selectors';
export const getSettings = packageNamespace =>
createSelector(
selectors.getSettingsLiveCollection,
deps.selectors.getSelectedSiteId,
(settings, siteId) =>
settings.find(
item => item.woronaInfo.namespace === packageNamespace && item.woronaInfo.siteId === siteId,
) || { woronaInfo: {} }, // default to empty object til settings collections is loaded
);
export const getSetting = (packageNamespace, settingName, settingDefault = undefined) =>
createSelector(
getSettings(packageNamespace),
settings => settings && settings[settingName] || settingDefault,
);
|
Change getSettings format to match app.
|
Change getSettings format to match app.
|
JavaScript
|
mit
|
worona/worona,worona/worona-dashboard,worona/worona-core,worona/worona,worona/worona-core,worona/worona,worona/worona-dashboard
|
3f6c7ef639ea0a475cdff67b4e85fe58e6a1de07
|
src/encoded/static/libs/react-middleware.js
|
src/encoded/static/libs/react-middleware.js
|
'use strict';
var React = require('react');
var doctype = '<!DOCTYPE html>\n';
var transformResponse = require('subprocess-middleware').transformResponse;
var render = function (Component, body, res) {
//var start = process.hrtime();
var context = JSON.parse(body);
var props = {
context: context,
href: res.getHeader('X-href') || context['@id']
};
var component, markup;
try {
component = Component(props);
markup = React.renderComponentToString(component);
} catch (err) {
props.context = {
'@type': ['RenderingError', 'error'],
status: 'error',
code: 500,
title: 'Server Rendering Error',
description: 'The server erred while rendering the page.',
detail: err.stack,
log: console._stdout.toString(),
warn: console._stderr.toString(),
context: context
};
// To debug in browser, pause on caught exceptions:
// app.setProps({context: app.props.context.context})
component = Component(props);
markup = React.renderComponentToString(component);
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
//var duration = process.hrtime(start);
//res.setHeader('X-React-duration', duration[0] * 1e6 + (duration[1] / 1000 | 0));
return new Buffer(doctype + markup);
};
module.exports.build = function (Component) {
return transformResponse(render.bind(null, Component));
};
|
'use strict';
var React = require('react');
var doctype = '<!DOCTYPE html>\n';
var transformResponse = require('subprocess-middleware').transformResponse;
var render = function (Component, body, res) {
//var start = process.hrtime();
var context = JSON.parse(body);
var props = {
context: context,
href: res.getHeader('X-href') || context['@id']
};
var component, markup;
try {
component = Component(props);
markup = React.renderComponentToString(component);
} catch (err) {
props.context = {
'@type': ['RenderingError', 'error'],
status: 'error',
code: 500,
title: 'Server Rendering Error',
description: 'The server erred while rendering the page.',
detail: err.stack,
log: console._stdout.toString(),
warn: console._stderr.toString(),
context: context
};
// To debug in browser, pause on caught exceptions:
// app.setProps({context: app.props.context.context})
res.statusCode = 500;
component = Component(props);
markup = React.renderComponentToString(component);
}
res.setHeader('Content-Type', 'text/html; charset=utf-8');
//var duration = process.hrtime(start);
//res.setHeader('X-React-duration', duration[0] * 1e6 + (duration[1] / 1000 | 0));
return new Buffer(doctype + markup);
};
module.exports.build = function (Component) {
return transformResponse(render.bind(null, Component));
};
|
Set status 500 on React rendered errors.
|
Set status 500 on React rendered errors.
|
JavaScript
|
mit
|
kidaa/encoded,4dn-dcic/fourfront,hms-dbmi/fourfront,philiptzou/clincoded,ENCODE-DCC/snovault,hms-dbmi/fourfront,ENCODE-DCC/encoded,ENCODE-DCC/encoded,hms-dbmi/fourfront,kidaa/encoded,T2DREAM/t2dream-portal,ClinGen/clincoded,ENCODE-DCC/snovault,philiptzou/clincoded,ClinGen/clincoded,ENCODE-DCC/snovault,ENCODE-DCC/encoded,kidaa/encoded,T2DREAM/t2dream-portal,philiptzou/clincoded,T2DREAM/t2dream-portal,philiptzou/clincoded,kidaa/encoded,kidaa/encoded,ClinGen/clincoded,hms-dbmi/fourfront,T2DREAM/t2dream-portal,4dn-dcic/fourfront,ClinGen/clincoded,ClinGen/clincoded,ENCODE-DCC/snovault,philiptzou/clincoded,4dn-dcic/fourfront,hms-dbmi/fourfront,ENCODE-DCC/snovault,4dn-dcic/fourfront,ENCODE-DCC/encoded
|
e9a8702b3995781cb5ed6b8c2e746c360e36b812
|
src/js/directive/contacts.js
|
src/js/directive/contacts.js
|
'use strict';
var ngModule = angular.module('woDirectives');
ngModule.directive('keyfileInput', function() {
return function(scope, elm) {
elm.on('change', function(e) {
for (var i = 0; i < e.target.files.length; i++) {
importKey(e.target.files.item(i));
}
});
function importKey(file) {
var reader = new FileReader();
reader.onload = function(e) {
scope.importKey(e.target.result);
};
reader.readAsText(file);
}
};
});
|
'use strict';
var ngModule = angular.module('woDirectives');
ngModule.directive('keyfileInput', function() {
return function(scope, elm) {
elm.on('change', function(e) {
for (var i = 0; i < e.target.files.length; i++) {
importKey(e.target.files.item(i));
}
elm.val(null); // clear input
});
function importKey(file) {
var reader = new FileReader();
reader.onload = function(e) {
scope.importKey(e.target.result);
};
reader.readAsText(file);
}
};
});
|
Clear file input after key import
|
[WO-927] Clear file input after key import
|
JavaScript
|
mit
|
whiteout-io/mail,dopry/mail-html5,sheafferusa/mail-html5,dopry/mail-html5,tanx/hoodiecrow,clochix/mail-html5,b-deng/mail-html5,dopry/mail-html5,tanx/hoodiecrow,dopry/mail-html5,whiteout-io/mail-html5,whiteout-io/mail-html5,clochix/mail-html5,whiteout-io/mail,whiteout-io/mail,sheafferusa/mail-html5,kalatestimine/mail-html5,b-deng/mail-html5,whiteout-io/mail-html5,clochix/mail-html5,kalatestimine/mail-html5,tanx/hoodiecrow,b-deng/mail-html5,whiteout-io/mail,b-deng/mail-html5,kalatestimine/mail-html5,sheafferusa/mail-html5,whiteout-io/mail-html5,sheafferusa/mail-html5,clochix/mail-html5,kalatestimine/mail-html5
|
cbccd67c481080e5e4d65d75dc03c57ea26de763
|
public/personality.controller.js
|
public/personality.controller.js
|
'use strict';
angular.module('personality.controller', [])
.controller('PersonalityController', [
'$scope', '$http', 'personalityService',
($scope, $http, personalityService) => {
$scope.roastOptions = [
'light',
'medium',
'dark'
];
$scope.getData = () => {
$http.put('/api/watson/' + $scope.twitter)
.success(data => {
$scope.array = data;
$scope.preference = personalityService.determinePreference(data);
$scope.curiosity = personalityService.getCuriosityPercentage(data);
$scope.liberty = personalityService.getLibertyPercentage(data);
})
.error(err => {
console.log(err);
});
};
$scope.submitFeedback = actualPreference => {
$http
.post('/api/feedback', {
twitter_handle: $scope.twitter,
expected_preference: $scope.preference,
actual_preference: actualPreference
})
.then(() => $scope.feedbackSubmitted = true);
};
}]);
|
'use strict';
angular.module('personality.controller', [])
.controller('PersonalityController', [
'$scope', '$http', 'personalityService',
($scope, $http, personalityService) => {
$scope.roastOptions = [
'light',
'medium',
'dark'
];
$scope.getData = () => {
resetFeedback();
$http.put('/api/watson/' + $scope.twitter)
.success(data => {
$scope.array = data;
$scope.preference = personalityService.determinePreference(data);
$scope.curiosity = personalityService.getCuriosityPercentage(data);
$scope.liberty = personalityService.getLibertyPercentage(data);
})
.error(err => {
console.log(err);
});
};
$scope.submitFeedback = actualPreference => {
$http
.post('/api/feedback', {
twitter_handle: $scope.twitter,
expected_preference: $scope.preference,
actual_preference: actualPreference
})
.then(() => $scope.feedbackSubmitted = true);
};
function resetFeedback() {
$scope.feedbackSubmitted = false;
$scope.showRoastFeedbackOptions = false;
}
}]);
|
Reset feedback on new submissions
|
Reset feedback on new submissions
|
JavaScript
|
mit
|
o3world/o3-barista,o3world/o3-barista
|
000f6aa302cda2e54d2e26ca85e28452dc50c382
|
src/js/modules/polyfills.js
|
src/js/modules/polyfills.js
|
require('svg4everybody')();
|
require('svg4everybody')();
if (!window.Element.prototype.matches) {
window.Element.prototype.matches = window.Element.prototype.msMatchesSelector;
}
|
Add Element.matches fix for IE
|
Add Element.matches fix for IE
|
JavaScript
|
mit
|
engageinteractive/front-end-baseplate,engageinteractive/core,engageinteractive/core,engageinteractive/front-end-baseplate,engageinteractive/front-end-baseplate
|
a093a6e38762c35091f46136942a3f469483de6b
|
app/models/session.js
|
app/models/session.js
|
import DS from 'ember-data';
import Session from 'exp-models/models/session';
export default Session.extend({
frameIndex: DS.attr(),
surveyPage: DS.attr()
});
|
import DS from 'ember-data';
import Session from 'exp-models/models/session';
export default Session.extend({
frameIndex: DS.attr({defaultValue: 0}),
surveyPage: DS.attr({defaultValue: 0})
});
|
Set default frameIndex & surveyPage to 0
|
Set default frameIndex & surveyPage to 0
|
JavaScript
|
apache-2.0
|
CenterForOpenScience/isp,CenterForOpenScience/isp,CenterForOpenScience/isp
|
f9d943aa29eef1367e24e7815d0bc8970e98bd27
|
app/scripts/routes/application_route.js
|
app/scripts/routes/application_route.js
|
App.ApplicationRoute = Ember.Route.extend({
// admittedly, this should be in IndexRoute and not in the
// top level ApplicationRoute; we're in transition... :-)
model: function () {
return ['red', 'yellow', 'blue'];
}
});
|
App.ApplicationRoute = Ember.Route.extend({
});
|
Remove old application route example
|
Remove old application route example
|
JavaScript
|
mit
|
rjsamson/ember-hapi-base
|
76161510b3ad61a0f667958bc4b2eb97c4f36469
|
src/server/utils/promises.js
|
src/server/utils/promises.js
|
import Promise from 'bluebird';
import { logger } from './logging';
/**
* Do a promise returning function with retries.
*/
export function withRetries(promiseFn, maxRetries, delaySeconds, errMsg, expBackoff) {
let retryCount = 0;
function doIt() {
return promiseFn().catch(err => {
// If we've hit the max, just propagate the error
if (retryCount >= maxRetries) {
throw err;
}
// Calculate delay time in MS
let delayMs = expBackoff === true
? Math.pow(delaySeconds, retryCount) * 1000
: delaySeconds * 1000;
// Log, delay, and try again
retryCount++;
logger.log('debug', '', err);
if (err instanceof AggregateError) {
logger.log('debug', 'Inner errors:');
err.innerErrors.forEach(innerError => {
logger.log('debug', '', innerError);
});
}
logger.log('verbose', `${errMsg}. Retry ${retryCount} in ${delayMs}ms.`);
return Promise.delay(delayMs).then(doIt);
});
}
return doIt();
};
|
import Promise from 'bluebird';
import { logger } from './logging';
/**
* Do a promise returning function with retries.
*/
export function withRetries(promiseFn, maxRetries, delaySeconds, errMsg, expBackoff) {
let retryCount = 0;
function doIt() {
return promiseFn().catch(err => {
// If we've hit the max, just propagate the error
if (retryCount >= maxRetries) {
throw err;
}
// Calculate delay time in MS
let delayMs = expBackoff === true
? Math.pow(delaySeconds, retryCount) * 1000
: delaySeconds * 1000;
// Log, delay, and try again
retryCount++;
logger.log('debug', '', err);
logger.log('verbose', `${errMsg}. Retry ${retryCount} in ${delayMs}ms.`);
return Promise.delay(delayMs).then(doIt);
});
}
return doIt();
};
|
Remove old ref to AggregateError
|
Remove old ref to AggregateError
- Leftover from converting the nodejs-common package to local functions
|
JavaScript
|
apache-2.0
|
KillrVideo/killrvideo-web,KillrVideo/killrvideo-web,KillrVideo/killrvideo-web
|
6334dd1cbe27a8b84df69cc8e450a92c637df3b7
|
setup.js
|
setup.js
|
'use strict';
var serialNumber = require('./index');
var fail = function (err) {
console.error('Could not read serial number:', err);
};
serialNumber(function (err) {
if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) {
[
'\x1B[7m' + // inverse style
'Your system requires root/administrative priviledge to access the serial number.' +
'\x1B[27m',
'\x1B[31m' + // red
'Attempting to run command with `sudo` and cache your serial for future use.' +
'\x1B[39m',
'\x1B[31m' + // red
'You will be prompted for password.' +
'\x1B[39m'
].forEach(function (msg) {console.info(msg);});
serialNumber.useSudo(function (err, val) {
if (err) {return fail(err);}
require('fs').writeFile('cached', val, function (err) {
if (err) {
console.error('Could not write serial number cache file:', err);
} else {
// green
console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m');
}
});
});
} else if (err) {
fail(err);
}
});
|
'use strict';
var serialNumber = require('./index');
var fail = function (err) {
console.error('Could not read serial number:', err);
};
serialNumber(function (err) {
if (process.platform !== 'win32' && err.toString().match(/Permission denied/i)) {
[
'\x1B[7m' + // inverse style
'Your system requires root/administrative priviledge to access the serial number.' +
'\x1B[27m',
'\x1B[31m' + // red
'Attempting to run command with `sudo` and cache your serial for future use.' +
'\x1B[39m'
].forEach(function (msg) {console.info(msg);});
serialNumber.useSudo(function (err, val) {
if (err) {return fail(err);}
require('fs').writeFile('cached', val, function (err) {
if (err) {
console.error('Could not write serial number cache file:', err);
} else {
// green
console.info('\x1B[32m' + 'Successfully cached serial number' + '\x1B[39m');
}
});
});
} else if (err) {
fail(err);
}
});
|
Remove redundant console message about password prompt
|
Remove redundant console message about password prompt
|
JavaScript
|
isc
|
dcrystalj/serial-number,es128/serial-number
|
3d2e011bc3efd28f6ddaa2dde04a76abeabf3574
|
website/src/app/models/api/public-comments-api.service.js
|
website/src/app/models/api/public-comments-api.service.js
|
class PublicCommentsAPIService {
constructor(publicAPIRoute) {
this.publicAPIRoute = publicAPIRoute;
}
getCommentsListFor(targetId) {
return this.publicAPIRoute('comments').get({target: targetId}).then(
(rv) => {
rv = rv.plain();
return rv.val;
}
);
}
}
angular.module('materialscommons').service('publicCommentsAPI', PublicCommentsAPIService);
|
class PublicCommentsAPIService {
constructor(Restangular) {
this.Restangular = Restangular;
}
getCommentsListFor(datasetId) {
return this.Restangular.one('v3').one('getCommentsForPublishedDataset').customPOST({dataset_id: datasetId}).then(
(ds) => ds.plain().data
);
}
}
angular.module('materialscommons').service('publicCommentsAPI', PublicCommentsAPIService);
|
Switch to actionhero based API
|
Switch to actionhero based API
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
1274571cbf950f85158974cd575b717753a1db3e
|
index.js
|
index.js
|
var yarn = require('yarn/lib/lockfile/wrapper.js')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 5000;
app.use(bodyParser.text());
app.disable('x-powered-by');
app.use(function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
next();
});
app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){
var dependencies = yarn.parse(req.body)
var deps = []
Object.keys(dependencies).forEach((dep) => {
deps.push({
name: dep.split('@')[0],
version: dependencies[dep].version,
type: 'runtime'
})
})
res.json(deps)
});
app.use(function(err, req, res, next) {
console.error('ERR:', err);
console.error('STACK:', err.stack);
res.status(500).send({error: 'Something went wrong.'});
});
app.listen(port, function() {
console.log('Listening on', port);
});
|
var yarn = require('yarn/lib/lockfile/wrapper.js')
var express = require('express')
var bodyParser = require('body-parser')
var app = express()
var port = process.env.PORT || 5000;
app.use(bodyParser.text());
app.disable('x-powered-by');
app.use(function(req, res, next) {
res.set('Access-Control-Allow-Origin', '*');
next();
});
app.use(express.bodyParser({limit: '5mb'}));
app.post("/parse/", bodyParser.text({type: '*/*'}), function(req,res){
var dependencies = yarn.parse(req.body)
var deps = []
Object.keys(dependencies).forEach((dep) => {
deps.push({
name: dep.split('@')[0],
version: dependencies[dep].version,
type: 'runtime'
})
})
res.json(deps)
});
app.use(function(err, req, res, next) {
console.error('ERR:', err);
console.error('STACK:', err.stack);
res.status(500).send({error: 'Something went wrong.'});
});
app.listen(port, function() {
console.log('Listening on', port);
});
|
Allow up to 5mb uploads
|
Allow up to 5mb uploads
|
JavaScript
|
agpl-3.0
|
librariesio/yarn-parser
|
ffa9d2d83ac39ffbff46036c1c53045f6de488a0
|
services/api/src/routes/index.js
|
services/api/src/routes/index.js
|
// @flow
const express = require('express');
const statusRoute = require('./status');
const keysRoute = require('./keys');
const graphqlRoute = require('./graphql');
/* ::
import type { $Request, $Response } from 'express';
*/
function createRouter() {
const router = new express.Router();
// Redirect GET requests on "/" to the status route.
router.get('/', (req /* : $Request */, res /* : $Response */) =>
res.redirect('/status'),
);
// Fetch the current api status.
router.get('/status', ...statusRoute);
// Return keys of all clients from clients.yaml.
router.post('/keys', ...keysRoute);
// Enable graphql requests.
router.all('/graphql', ...graphqlRoute);
return router;
}
module.exports = createRouter;
|
// @flow
const express = require('express');
const statusRoute = require('./status');
const keysRoute = require('./keys');
const graphqlRoute = require('./graphql');
/* ::
import type { $Request, $Response } from 'express';
*/
function createRouter() {
const router = new express.Router();
// Redirect GET requests on "/" to the status route.
router.get('/', (req /* : $Request */, res /* : $Response */) =>
res.redirect('/status'),
);
// Fetch the current api status.
router.get('/status', ...statusRoute);
// Return keys of all customers
router.post('/keys', ...keysRoute);
// Enable graphql requests.
router.all('/graphql', ...graphqlRoute);
return router;
}
module.exports = createRouter;
|
Update `clients` to `customer` in API routes
|
Update `clients` to `customer` in API routes
|
JavaScript
|
apache-2.0
|
amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon,amazeeio/lagoon
|
115438d4ea6dde1eeaf68054b8f7606a28e13009
|
challenges-completed.js
|
challenges-completed.js
|
var ipc = require('ipc')
var userData = require('./user-data.js')
document.addEventListener('DOMContentLoaded', function (event) {
var data = userData.getData()
updateIndex(data.contents)
ipc.on('confirm-clear-response', function (response) {
if (response === 1) return
else clearAllChallenges()
})
var clearAllButton = document.getElementById('clear-all-challenges')
clearAllButton.addEventListener('click', function () {
for (var chal in data) {
if (data[chal].completed) {
data[chal].completed = false
var completedElement = '#' + chal + ' .completed-challenge-list'
document.querySelector(completedElement).remove()
}
}
userData.updateData(data, function (err) {
// this takes in a challenge, which you're not doing
if (err) return console.log(err)
})
})
function updateIndex (data) {
for (var chal in data) {
if (data[chal].completed) {
var currentText = document.getElementById(chal).innerHTML
var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>"
document.getElementById(chal).innerHTML = completedText + ' ' + currentText
}
}
}
})
|
var ipc = require('ipc')
var fs = require('fs')
var userData = require('./user-data.js')
document.addEventListener('DOMContentLoaded', function (event) {
var data = userData.getData()
var clearAllButton = document.getElementById('clear-all-challenges')
updateIndex(data.contents)
ipc.on('confirm-clear-response', function (response) {
if (response === 1) return
else clearAllChallenges(data)
})
clearAllButton.addEventListener('click', function () {
ipc.send('confirm-clear')
})
function updateIndex (data) {
for (var chal in data) {
if (data[chal].completed) {
var currentText = document.getElementById(chal).innerHTML
var completedText = "<span class='completed-challenge-list'>[ Completed ]</span>"
document.getElementById(chal).innerHTML = completedText + ' ' + currentText
}
}
}
})
function clearAllChallenges (data) {
for (var chal in data.contents) {
if (data.contents[chal].completed) {
data.contents[chal].completed = false
var completedElement = '#' + chal + ' .completed-challenge-list'
document.querySelector(completedElement).remove()
}
}
fs.writeFileSync(data.path, JSON.stringify(data.contents, null, 2))
}
|
Fix all the bugs in writing data and confirming clear
|
Fix all the bugs in writing data and confirming clear
|
JavaScript
|
bsd-2-clause
|
dice/git-it-electron,countryoven/git-it-electron,countryoven/git-it-electron,dice/git-it-electron,rets5s/git-it-electron,IonicaBizauKitchen/git-it-electron,jlord/git-it-electron,IonicaBizauKitchen/git-it-electron,countryoven/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,countryoven/git-it-electron,countryoven/git-it-electron,dice/git-it-electron,dice/git-it-electron,dice/git-it-electron,IonicaBizauKitchen/git-it-electron,dice/git-it-electron,countryoven/git-it-electron,IonicaBizauKitchen/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,dice/git-it-electron,rets5s/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,countryoven/git-it-electron,IonicaBizauKitchen/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,IonicaBizauKitchen/git-it-electron,rets5s/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,shiftkey/git-it-electron,vongola12324/git-it-electron,shiftkey/git-it-electron,rets5s/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron,IonicaBizauKitchen/git-it-electron,rets5s/git-it-electron,vongola12324/git-it-electron,jlord/git-it-electron,vongola12324/git-it-electron
|
1009736eb9141fec58a34584b6b8764e92a3967e
|
config/app.json.js
|
config/app.json.js
|
module.exports = {
"allow_create_new_accounts" : true,
"send_emails" : false,
"application_sender_email" : process.env.SENDER_EMAIL || "[email protected]",
// transports email via SMTP
"email_smtp_transporter" : {
"host" : process.env.MAILGUN_SMTP_SERVER || "localhost",
"port" : process.env.MAILGUN_SMTP_PORT || 25,
"auth" : {
"user" : process.env.MAILGUN_SMTP_LOGIN || "user",
"pass" : process.env.MAILGUN_SMTP_PASSWORD || "pass"
}
},
// transports emails via Mailgun REST API (which is 3x faster than SMTP)
// precedes email_smtp_transporter if api_key and domain are set
"email_mailgun_transporter" : {
auth: {
api_key: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN
}
},
"crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_",
"application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management",
"promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management"
}
|
module.exports = {
"allow_create_new_accounts" : true,
"send_emails" : false,
"application_sender_email" : process.env.SENDER_EMAIL || "[email protected]",
// transports email via SMTP
"email_smtp_transporter" : {
"host" : process.env.SMTP_SERVER || "localhost",
"port" : process.env.SMTP_PORT || 25,
"auth" : {
"user" : process.env.SMTP_LOGIN || "user",
"pass" : process.env.SMTP_PASSWORD || "pass"
}
},
// transports emails via Mailgun REST API (which is 3x faster than SMTP)
// precedes email_smtp_transporter if api_key and domain are set
"email_mailgun_transporter" : {
auth: {
api_key: process.env.MAILGUN_API_KEY,
domain: process.env.MAILGUN_DOMAIN
}
},
"crypto_secret" : process.env.CRYPTO_SECRET || "!2~`HswpPPLa22+=±§sdq qwe,appp qwwokDF_",
"application_domain" : process.env.APPLICATION_DOMAIN || "http://app.timeoff.management",
"promotion_website_domain" : process.env.PROMOTION_WEBSITE_DOMAIN || "http://timeoff.management"
}
|
Use generic names for SMTP env variables
|
Use generic names for SMTP env variables
|
JavaScript
|
mit
|
YulioTech/timeoff,YulioTech/timeoff
|
513507afcb36ad4d56bcc89596bd9252774fca2b
|
src/replace_country_code.js
|
src/replace_country_code.js
|
export default function replaceCountryCode(
currentSelectedCountry,
nextSelectedCountry,
number,
) {
const dialCodeRegex = RegExp(`^(${currentSelectedCountry.dialCode})`)
const newNumber = number.replace(dialCodeRegex, nextSelectedCountry.dialCode)
// if we couldn't find any replacement, just attach the new country's dial code at the front
if (newNumber === number) {
return nextSelectedCountry.dialCode + number
}
return newNumber
}
|
export default function replaceCountryCode(
currentSelectedCountry,
nextSelectedCountry,
number,
) {
const dialCodeRegex = RegExp(`^(${currentSelectedCountry.dialCode})`)
const newNumber = number.replace(dialCodeRegex, nextSelectedCountry.dialCode)
return newNumber
}
|
Remove automatic country code appending
|
Remove automatic country code appending
|
JavaScript
|
mit
|
mukeshsoni/react-telephone-input,mukeshsoni/react-telephone-input
|
900ef0236d288e29ff715030f53db78c13afa6c1
|
src/cli/cli.js
|
src/cli/cli.js
|
#! /usr/bin/env node
import yargs from 'yargs'
import { init, change, add, deploy } from './cmds'
const argv = yargs.usage("$0 command")
.command("init", "create a new generic website")
.command("change <field>", "update any field with a new value")
.command("add <field>", "add a new key and value")
.command("deploy", "deploy your website")
.demand(1, "must provide a valid command")
.help("h")
.alias("h", "help")
.argv
switch (argv._[0]) {
case 'init': init(); break
case 'change': change(argv.field); break
case 'add': add(argv.field); break
case 'deploy': deploy(); break
}
|
#! /usr/bin/env node
import yargs from 'yargs'
import { init, change, add, deploy } from './cmds'
const argv = yargs.usage("$0 command")
.command("init", "create a new generic website")
.command("change <field>", "update any field with a new value")
.command("add", "add a new key and value", (yargs) => (
yargs
.option("s", {alias: "section", describe: "add a section"})
.option("f", {alias: "field", describe: "provide a field name"})
.demandOption(['f'], "Please provide a field name, it is required.")
.help("h").alias("h", "help")
))
.command("deploy <location>", "deploy your website")
.demand(1, "must provide a valid command")
.help("h")
.alias("h", "help")
.argv
switch (argv._[0]) {
case 'init': init(); break
case 'change': change(argv.field); break
case 'add': console.log(argv); add(argv.field); break
case 'deploy': deploy(); break
}
|
Add section options for add cmd
|
Add section options for add cmd
|
JavaScript
|
mpl-2.0
|
Quite-nice/generic-website
|
1a8b13fd53e23cd069e792476854e5b9af20f19a
|
site/gulpfile.js
|
site/gulpfile.js
|
var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var print = require('gulp-print');
var tsc = require('gulp-typescript-compiler');
gulp.task('typescript', function() {
return gulp.src( [ '*.ts', '**/*.ts' ] )
.pipe( print() )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) )
.pipe( print() )
.pipe(uglify());
});
// Default Task
gulp.task('default', ['typescript']);
|
var gulp = require('gulp');
var watch = require('gulp-watch');
var uglify = require('gulp-uglify');
var print = require('gulp-print');
var tsc = require('gulp-typescript-compiler');
gulp.task('ts_server', function() {
return gulp.src( [ '*.ts', '**/*.ts', '!./public/**/*.ts', '!./node_modules/**/*.ts' ] )
.pipe( print() )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) )
.pipe(uglify());
});
gulp.task('ts_client', function() {
return gulp.src( [ './public/**/*.ts' ] )
.pipe( print() )
.pipe( tsc( { module: 'amd', target: 'ES5', sourcemap: false, logErrors: true } ) )
.pipe(uglify());
});
// Default Task
gulp.task( 'default', ['ts_server','ts_client'] );
|
Split tasks for client-side and server-side typescript files.
|
Split tasks for client-side and server-side typescript files.
Signed-off-by: Michele Ursino <[email protected]>
|
JavaScript
|
mit
|
micurs/relax.js,micurs/relax.js,micurs/relax.js
|
7f148da89b0048bf05acbfa8c64a39d0927a4e79
|
scripts/plugins/markdown-markup.js
|
scripts/plugins/markdown-markup.js
|
var minimatch = require('minimatch');
var cheerio = require('cheerio');
var extend = require('extend');
var marked = require('marked');
var config = require('../config/marked');
marked.setOptions(config);
function plugin(opts) {
return function(files, metalsmith, done) {
// Get global metadata.
var metadata = metalsmith.metadata();
// Get all file names.
Object.keys(files)
// Get stylesheets file names.
.filter(minimatch.filter('*.html', { matchBase: true }))
// Curate content.
.forEach(function(file) {
// Get file data.
var data = files[file];
// Get file HTML.
var html = data.contents.toString();
// Prepare HTML for analysis.
var $ = cheerio.load(html, {
decodeEntities: false
});
// Find all <jade> nodes.
$('md').each(function(i, el) {
// Get the content.
var source = $(this).html();
// Merge global metadata with local file data.
var options = extend({}, opts, metadata, data);
// Render the content as Jade.
var html = marked(source);
// Replace the <jade> node with the new rendered content.
$(this).replaceWith(html);
});
// Save updated HTML.
data.contents = new Buffer($.html(), 'utf8');
});
done();
}
}
module.exports = plugin;
|
var minimatch = require('minimatch');
var cheerio = require('cheerio');
var marked = require('marked');
var config = require('../config/marked');
marked.setOptions(config);
function plugin(opts) {
return function(files, metalsmith, done) {
// Get global metadata.
var metadata = metalsmith.metadata();
// Get all file names.
Object.keys(files)
// Get stylesheets file names.
.filter(minimatch.filter('*.html', { matchBase: true }))
// Curate content.
.forEach(function(file) {
// Get file data.
var data = files[file];
// Get file HTML.
var html = data.contents.toString();
// Prepare HTML for analysis.
var $ = cheerio.load(html, {
decodeEntities: false
});
// Find all <jade> nodes.
$('md').each(function(i, el) {
// Get the content.
var source = $(this).html();
// Render the content as Jade.
var html = marked(source);
// Replace the <jade> node with the new rendered content.
$(this).replaceWith(html);
});
// Save updated HTML.
data.contents = new Buffer($.html(), 'utf8');
});
done();
}
}
module.exports = plugin;
|
Remove unused variable and import
|
Update: Remove unused variable and import
|
JavaScript
|
mit
|
basham/v4.bash.am,basham/v4.bash.am
|
35748918436e557248c659c837635daf0af2e7bd
|
src/store/index.js
|
src/store/index.js
|
// Main vuex store
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import intro from './modules/intro'
import weeks from './modules/weeks'
import switches from './modules/switches'
import models from './modules/models'
import * as types from './mutation-types'
import branding from 'json!yaml!../../config.yaml'
Vue.use(Vuex)
const state = {
// D3 plot objects
timeChart: null,
choropleth: null,
distributionChart: null,
// All the data!
data: null,
updateTime: null,
branding: branding.branding
}
// mutations
const mutations = {
[types.SET_DATA] (state, val) {
state.data = val.data
state.updateTime = val.updateTime
},
[types.SET_TIMECHART] (state, val) {
state.timeChart = val
},
[types.SET_CHOROPLETH] (state, val) {
state.choropleth = val
},
[types.SET_DISTRIBUTIONCHART] (state, val) {
state.distributionChart = val
},
[types.SET_BRAND_LOGO] (state, val) {
state.branding.logo = val
}
}
export default new Vuex.Store({
state,
actions,
getters,
mutations,
modules: {
intro,
weeks,
switches,
models
}
})
|
// Main vuex store
import Vue from 'vue'
import Vuex from 'vuex'
import * as actions from './actions'
import * as getters from './getters'
import intro from './modules/intro'
import weeks from './modules/weeks'
import switches from './modules/switches'
import models from './modules/models'
import * as types from './mutation-types'
import branding from 'json!yaml!../../config.yaml'
Vue.use(Vuex)
const state = {
// D3 plot objects
timeChart: null,
choropleth: null,
distributionChart: null,
// All the data!
data: null,
updateTime: null,
branding: Object.assign({logo: ''}, branding.branding)
}
// mutations
const mutations = {
[types.SET_DATA] (state, val) {
state.data = val.data
state.updateTime = val.updateTime
},
[types.SET_TIMECHART] (state, val) {
state.timeChart = val
},
[types.SET_CHOROPLETH] (state, val) {
state.choropleth = val
},
[types.SET_DISTRIBUTIONCHART] (state, val) {
state.distributionChart = val
},
[types.SET_BRAND_LOGO] (state, val) {
state.branding.logo = val
}
}
export default new Vuex.Store({
state,
actions,
getters,
mutations,
modules: {
intro,
weeks,
switches,
models
}
})
|
Fix issue with branding icon by pre allocating logo slot
|
Fix issue with branding icon by pre allocating logo slot
|
JavaScript
|
mit
|
reichlab/flusight,reichlab/flusight,reichlab/flusight
|
71130ab567994962d9083c9dbd8bd69ea4a35d52
|
src/time-travel.js
|
src/time-travel.js
|
require('es6-shim');
const intent = require('./intent');
const makeTime$ = require('./time');
const record = require('./record-streams');
const timeTravelStreams = require('./time-travel-streams');
const timeTravelBarView = require('./view');
const scopedDOM = require('./scoped-dom');
function logStreams (DOM, streams, name = '.time-travel') {
const {timeTravelPosition$, playing$} = intent(scopedDOM(DOM, name));
const time$ = makeTime$(playing$, timeTravelPosition$);
const recordedStreams = record(streams, time$);
const timeTravel = timeTravelStreams(recordedStreams, time$);
return {
DOM: timeTravelBarView(time$, playing$, recordedStreams),
timeTravel
};
}
module.exports = logStreams;
|
require('es6-shim');
const intent = require('./intent');
const makeTime$ = require('./time');
const record = require('./record-streams');
const timeTravelStreams = require('./time-travel-streams');
const timeTravelBarView = require('./view');
const scopedDOM = require('./scoped-dom');
function TimeTravel (DOM, streams, name = '.time-travel') {
const {timeTravelPosition$, playing$} = intent(scopedDOM(DOM, name));
const time$ = makeTime$(playing$, timeTravelPosition$);
const recordedStreams = record(streams, time$);
const timeTravel = timeTravelStreams(recordedStreams, time$);
return {
DOM: timeTravelBarView(time$, playing$, recordedStreams),
timeTravel
};
}
module.exports = TimeTravel;
|
Rename main function form logStreams to TimeTravel
|
Rename main function form logStreams to TimeTravel
|
JavaScript
|
mit
|
cyclejs/cycle-time-travel
|
1fc05c7aeba8dc6fa7217ad438980bd99e5a325b
|
src/subgenerators/errors.js
|
src/subgenerators/errors.js
|
// try block handler
exports.TryStatement = (node, anscestors, generator) => {
generator.advance("try");
// node.block will always be a BlockStatement
generator.generate(node.block, anscestors);
node.handler && generator.generate(node.handler, anscestors);
node.finalizer && generator.generate(node.finalizer, anscestors);
};
// catch (param) body
exports.CatchClause = (node, anscestors, generator) => {
generator.advance("catch(");
generator.generate(node.param, anscestors);
generator.advance(")");
// node.body will always be a BlockStatement
generator.generate(node.body, anscestors);
};
// throw expression
exports.ThrowStatement = (node, anscestors, generator) => {
generator.advance("throw ");
generator.generate(node.argument, anscestors);
};
|
// try block handler
exports.TryStatement = (node, anscestors, generator) => {
generator.advance("try");
// node.block will always be a BlockStatement
generator.generate(node.block, anscestors);
node.handler && generator.generate(node.handler, anscestors);
node.finalizer && generator.generate(node.finalizer, anscestors);
};
// catch (param) body
exports.CatchClause = (node, anscestors, generator) => {
generator.advance("catch(");
generator.generate(node.param, anscestors);
generator.advance(")");
// node.body will always be a BlockStatement
generator.generate(node.body, anscestors);
};
// throw expression
exports.ThrowStatement = (node, anscestors, generator) => {
generator.advance("throw ");
generator.generate(node.argument, anscestors);
generator.advance(";");
};
|
Throw statement should end in a `;`.
|
Throw statement should end in a `;`.
|
JavaScript
|
mit
|
interlockjs/intergenerator
|
09a491cff5573526768c1161eaf393cf1e29f74a
|
src/message.js
|
src/message.js
|
// @flow
import debug from 'debug'
import get from 'lodash/get'
const dbg = debug('woonerf:message')
/**
* Expose a Set of all the keys used
*/
export const KeysUsed = new Set()
/**
* Set the messages object
*/
export function setMessages (newMessages) {
messages = newMessages
}
let messages = {}
if (process.env.MESSAGES) {
setMessages(JSON.parse(process.env.MESSAGES))
}
/**
* Requires a key, defaultMessage and parameters are optional
*/
export default function getMessage (key: string, defaultMessage?: string | Object, parameters?: Object): string {
if (defaultMessage == null) {
defaultMessage = ''
parameters = {}
} else if (typeof defaultMessage === 'object') {
parameters = defaultMessage
defaultMessage = ''
}
// Store the used key
KeysUsed.add(key)
// Get the message with "lodash/get" to allow nested keys ('noun.action' => {noun: {action: 'value'}})
const msg = get(messages, key, defaultMessage)
const result = parameters ? replaceMessage(msg, parameters) : msg
dbg(key, result)
return result
}
function replaceMessage (msg, data) {
return msg.replace(new RegExp('%\\((' + Object.keys(data).join('|') + ')\\)', 'g'), (m, key) => data[key] || m)
}
|
// @flow
import debug from 'debug'
import get from 'lodash/get'
const dbg = debug('woonerf:message')
/**
* Expose a Set of all the keys used
*/
export const KeysUsed = new Set()
/**
* Set the messages object
*/
export function setMessages (newMessages) {
messages = newMessages
}
let messages = {}
if (process.env.MESSAGES) {
setMessages(JSON.parse(process.env.MESSAGES))
}
/**
* Requires a key, defaultMessage and parameters are optional
*/
export default function getMessage (key: string, defaultMessage?: string | Object, parameters?: Object): string {
if (defaultMessage == null) {
defaultMessage = ''
parameters = {}
} else if (typeof defaultMessage === 'object') {
parameters = defaultMessage
defaultMessage = ''
}
// Store the used key
KeysUsed.add(key)
// Get the message with "lodash/get" to allow nested keys ('noun.action' => {noun: {action: 'value'}})
const msg = get(messages, key, defaultMessage)
const result = parameters ? replaceMessage(msg, parameters) : msg
dbg(key, result)
return result
}
function replaceMessage (msg, data) {
return msg.replace(
new RegExp('%\\((' + Object.keys(data).join('|') + ')\\)', 'g'),
(m, key) => data.hasOwnProperty(key) ? data[key] : m
)
}
|
Check property existence to allow 0s
|
Check property existence to allow 0s
|
JavaScript
|
mit
|
conveyal/woonerf
|
479f229198bdfcfd3a63d02babdddaa8b2209ccb
|
server/helpers/customValidators.js
|
server/helpers/customValidators.js
|
'use strict'
const validator = require('validator')
const constants = require('../initializers/constants')
const customValidators = {
eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid,
eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid,
isArray: isArray
}
function eachIsRemoteVideosAddValid (values) {
return values.every(function (val) {
return validator.isLength(val.name, 1, 50) &&
validator.isLength(val.description, 1, 50) &&
validator.isLength(val.magnetUri, 10) &&
validator.isURL(val.podUrl) &&
!isNaN(val.duration) &&
val.duration >= 0 &&
val.duration < constants.MAXIMUM_VIDEO_DURATION &&
validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) &&
validator.isDate(val.createdDate)
})
}
function eachIsRemoteVideosRemoveValid (values) {
return values.every(function (val) {
return validator.isLength(val.magnetUri, 10)
})
}
function isArray (value) {
return Array.isArray(value)
}
// ---------------------------------------------------------------------------
module.exports = customValidators
|
'use strict'
const validator = require('validator')
const constants = require('../initializers/constants')
const customValidators = {
eachIsRemoteVideosAddValid: eachIsRemoteVideosAddValid,
eachIsRemoteVideosRemoveValid: eachIsRemoteVideosRemoveValid,
isArray: isArray
}
function eachIsRemoteVideosAddValid (values) {
return values.every(function (val) {
return validator.isLength(val.name, 1, 50) &&
validator.isLength(val.description, 1, 50) &&
validator.isLength(val.magnetUri, 10) &&
validator.isURL(val.podUrl) &&
!isNaN(val.duration) &&
val.duration >= 0 &&
val.duration < constants.MAXIMUM_VIDEO_DURATION &&
validator.isLength(val.author, 1, constants.MAXIMUM_AUTHOR_LENGTH) &&
validator.isBase64(val.thumbnailBase64) &&
validator.isByteLength(val.thumbnailBase64, { min: 0, max: 20000 }) &&
validator.isDate(val.createdDate)
})
}
function eachIsRemoteVideosRemoveValid (values) {
return values.every(function (val) {
return validator.isLength(val.magnetUri, 10)
})
}
function isArray (value) {
return Array.isArray(value)
}
// ---------------------------------------------------------------------------
module.exports = customValidators
|
Add check for the thumbnail in base64 (requests inter pods)
|
Add check for the thumbnail in base64 (requests inter pods)
|
JavaScript
|
agpl-3.0
|
Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Chocobozzz/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube,Green-Star/PeerTube
|
fbda3077971863a82f07c1131fe8f91f92e438eb
|
src/Main/Mana.js
|
src/Main/Mana.js
|
import React from 'react';
import PropTypes from 'prop-types';
import ManaLevelGraph from 'Main/ManaLevelGraph';
import ManaUsageGraph from 'Main/ManaUsageGraph';
const Mana = ({ parser }) => (
<div>
<h1>Mana level</h1>
<ManaLevelGraph
reportCode={parser.report.code}
actorId={parser.playerId}
start={parser.fight.start_time}
end={parser.fight.end_time}
manaUpdates={parser.modules.manaValues.manaUpdates}
currentTimestamp={parser.currentTimestamp}
/> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/}
<h1>Mana usage</h1>
<ManaUsageGraph
start={parser.fight.start_time}
end={parser.fight.end_time}
healingBySecond={parser.modules.healingDone.bySecond}
manaUpdates={parser.modules.manaValues.manaUpdates}
timestamp={parser.currentTimestamp}
/> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/}
</div>
);
Mana.propTypes = {
parser: PropTypes.object.isRequired,
};
export default Mana;
|
import React from 'react';
import PropTypes from 'prop-types';
import ManaLevelGraph from 'Main/ManaLevelGraph';
import ManaUsageGraph from 'Main/ManaUsageGraph';
const Mana = ({ parser }) => (
<div>
<h1>Mana pool</h1>
<ManaLevelGraph
reportCode={parser.report.code}
actorId={parser.playerId}
start={parser.fight.start_time}
end={parser.fight.end_time}
manaUpdates={parser.modules.manaValues.manaUpdates}
currentTimestamp={parser.currentTimestamp}
/> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/}
<h1>Mana usage</h1>
<ManaUsageGraph
start={parser.fight.start_time}
end={parser.fight.end_time}
healingBySecond={parser.modules.healingDone.bySecond}
manaUpdates={parser.modules.manaValues.manaUpdates}
timestamp={parser.currentTimestamp}
/> {/* the currentTimestamp makes sure the Mana tab re-renders after parsing events*/}
</div>
);
Mana.propTypes = {
parser: PropTypes.object.isRequired,
};
export default Mana;
|
Rename mana level to mana pool
|
Rename mana level to mana pool
|
JavaScript
|
agpl-3.0
|
FaideWW/WoWAnalyzer,hasseboulen/WoWAnalyzer,mwwscott0/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,Juko8/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,enragednuke/WoWAnalyzer,WoWAnalyzer/WoWAnalyzer,sMteX/WoWAnalyzer,fyruna/WoWAnalyzer,enragednuke/WoWAnalyzer,fyruna/WoWAnalyzer,yajinni/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer,yajinni/WoWAnalyzer,enragednuke/WoWAnalyzer,yajinni/WoWAnalyzer,yajinni/WoWAnalyzer,mwwscott0/WoWAnalyzer,anom0ly/WoWAnalyzer,anom0ly/WoWAnalyzer,ronaldpereira/WoWAnalyzer,ronaldpereira/WoWAnalyzer,anom0ly/WoWAnalyzer,FaideWW/WoWAnalyzer,hasseboulen/WoWAnalyzer,FaideWW/WoWAnalyzer,hasseboulen/WoWAnalyzer,fyruna/WoWAnalyzer,sMteX/WoWAnalyzer,Juko8/WoWAnalyzer
|
7eae22dc3a4a35bdd568a559b569964378196ba9
|
app/core/forms.js
|
app/core/forms.js
|
import includes from 'lodash/includes';
import map from 'lodash/map';
import reduce from 'lodash/reduce';
import keys from 'lodash/keys';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
export const getFieldsMeta = (schema, getFieldMeta) => {
const fieldKeys = keys(schema.fields);
const reduceFields = (_fieldKeys, prefix = '') => reduce(_fieldKeys, (result, field) => {
const nestedFields = get(schema.fields, `${field}.fields`);
if (nestedFields) {
// Recurse for nested field keys
result[field] = reduceFields(keys(nestedFields), `${field}.`);
} else {
const fieldKey = `${prefix}${field}`;
const fieldMeta = getFieldMeta(fieldKey);
result[field] = {
...fieldMeta,
valid: (!isEmpty(fieldMeta.value) || fieldMeta.touched) && !fieldMeta.error,
};
}
return result;
}, {});
return reduceFields(fieldKeys);
};
export const fieldsAreValid = (fieldNames, fieldsMeta) => !includes(map(fieldNames, fieldName => get(fieldsMeta, `${fieldName}.valid`)), false);
|
import includes from 'lodash/includes';
import map from 'lodash/map';
import reduce from 'lodash/reduce';
import keys from 'lodash/keys';
import get from 'lodash/get';
import isEmpty from 'lodash/isEmpty';
export const getFieldsMeta = (schema, getFieldMeta) => {
const fieldKeys = keys(schema.fields);
const reduceFields = (_fieldKeys, prefix = '') => reduce(_fieldKeys, (result, field) => {
const nestedFields = get(schema.fields, `${field}.fields`);
if (nestedFields) {
// Recurse for nested field keys
result[field] = reduceFields(keys(nestedFields), `${field}.`);
} else {
const fieldKey = `${prefix}${field}`;
const fieldMeta = getFieldMeta(fieldKey);
result[field] = {
...fieldMeta,
valid: (!isEmpty(fieldMeta.value) || fieldMeta.touched) && !fieldMeta.error,
};
}
return result;
}, {});
return reduceFields(fieldKeys);
};
export const fieldsAreValid = (fieldNames, fieldsMeta) => !includes(map(fieldNames, fieldName => get(fieldsMeta, `${fieldName}.valid`)), false);
export const getFieldError = fieldMeta => fieldMeta.touched && fieldMeta.error ? fieldMeta.error : null;
|
Add getFieldError convenience form util
|
[WEB-819] Add getFieldError convenience form util
|
JavaScript
|
bsd-2-clause
|
tidepool-org/blip,tidepool-org/blip,tidepool-org/blip
|
af0106c1e90dba0a66c7f162a23f1060b28beaa1
|
main.js
|
main.js
|
const menubar = require('menubar')
const { ipcMain } = require('electron')
const configure = require('./src/helpers/configure')
const mb = menubar({
alwaysOnTop: true,
resizable: false,
width: 292,
height: 344,
icon: `${__dirname}/img/iconTemplate.png`
})
mb.on('ready', () => {
console.log('App started in menu bar.')
configure(mb)
})
ipcMain.on('APP_PATH_REQUEST', (event) => {
event.sender.send('APP_PATH_REPLY', mb.app.getAppPath())
})
|
const menubar = require('menubar')
const { ipcMain } = require('electron')
const configure = require('./src/helpers/configure')
const mb = menubar({
alwaysOnTop: true,
resizable: false,
width: 292,
height: 344,
icon: `${__dirname}/img/iconTemplate.png`
})
mb.on('ready', () => {
console.log('App started in menu bar.')
configure(mb)
mb.tray.on('drag-enter', () => mb.showWindow())
})
mb.on('focus-lost', () => mb.hideWindow());
ipcMain.on('APP_PATH_REQUEST', (event) => {
event.sender.send('APP_PATH_REPLY', mb.app.getAppPath())
})
|
Add ability to drag files into Tray to open Alchemy
|
Add ability to drag files into Tray to open Alchemy
* On window blur Alchemy is minimized
|
JavaScript
|
mit
|
dawnlabs/alchemy,dawnlabs/alchemy,dawnlabs/alchemy
|
945a41728236981a1d5f5884763cbd9793ba42f8
|
generatorTests/test/fileStructureSpec.js
|
generatorTests/test/fileStructureSpec.js
|
var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('when testing cartridge file structure', function() {
it('then _config files should exist', function() {
var pathToTest = path.join(ROOT_DIR, '_config/');
var filePathToTest;
var files = [
'project.json',
'paths.js'
];
files.forEach(function(fileName) {
filePathToTest = path.join(pathToTest, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
it('then required base files should exist', function() {
var filePathToTest;
var files = [
'gulpfile.js',
'package.json',
'readme.md',
];
files.forEach(function(fileName) {
filePathToTest = path.join(ROOT_DIR, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
it('then required handlebars view files should exist', function() {
var pathToTest = path.join(ROOT_DIR, 'views/');
var files = [
'index.hbs',
'styleguide.hbs',
]
files.forEach(function(fileName) {
filePathToTest = path.join(pathToTest, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
});
});
|
var path = require('path');
var chai = require('chai');
chai.use(require('chai-fs'));
chai.should();
const ROOT_DIR = path.join(process.cwd(), '..');
describe('As a dev', function() {
describe('when testing cartridge file structure', function() {
it('then _config files should exist', function() {
var pathToTest = path.join(ROOT_DIR, '_config/');
var filePathToTest;
var files = [
'project.json'
];
files.forEach(function(fileName) {
filePathToTest = path.join(pathToTest, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
it('then required base files should exist', function() {
var filePathToTest;
var files = [
'gulpfile.js',
'package.json',
'readme.md',
];
files.forEach(function(fileName) {
filePathToTest = path.join(ROOT_DIR, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
it('then required handlebars view files should exist', function() {
var pathToTest = path.join(ROOT_DIR, 'views/');
var files = [
'index.hbs',
'styleguide.hbs',
]
files.forEach(function(fileName) {
filePathToTest = path.join(pathToTest, fileName);
filePathToTest.should.be.a.file().and.not.empty;
});
})
});
});
|
Remove reference to deleted file
|
tests: Remove reference to deleted file
|
JavaScript
|
mit
|
cartridge/cartridge,code-computerlove/slate,code-computerlove/slate
|
fb1497b7195af0ed76e00d670d07f7472c1a3fb0
|
static/main.js
|
static/main.js
|
function setCurrentMonthInInput() {
console.log("Tried to set month in input. Disabled right now");
}
$('#form-submit-button').click(function (a, c) {
console.log("Form being submitted", a, c);
return false;
});
|
function setCurrentMonthInInput() {
console.log("Tried to set month in input. Disabled right now");
}
function failureAlert() {
return `<div class="alert alert-danger" role="alert" id="failure-alert">
<!-- <button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button> -->
<strong>Error!</strong> Please choose a month before submitting.
</div>`;
}
var table_index = 1;
function tableHead(value) {
var h = document.createElement('th')
h.appendChild(document.createTextNode(value));
return h;
}
function createAndAppendRow(data) {
var row = document.createElement('tr');
row.appendChild(tableHead(table_index));
table_index++;
row.appendChild(tableHead(data.messageUids[0]));
row.appendChild(tableHead(data.userName));
row.appendChild(tableHead(data.userId));
row.appendChild(tableHead(data.chatName));
row.appendChild(tableHead(data.chat));
var tableBody = $('#table-body');
tableBody.append(row);
}
$('#form-submit-button').click(function (event, c) {
var month = $('#form-month-input').val();
console.log("Form being submitted", event, c, month);
if (month === undefined) {
// $('.container')[0].innerHTML = failureAlert() + $('.container')[0].innerHTML;
// setTimeout(function(){
// if ($('#failure-alert').length > 0) {
// $('#failure-alert').remove();
// }
// }, 2000)
console.log("No month on page.");
return false;
}
console.log("Got Month", month);
var data = {'month': month};
$.ajax({
url: '/history',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(UIDs) {
UIDs.forEach(function(UID, index, array) {
var data = {'UID': UID};
$.ajax({
url: '/UID',
type: 'POST',
data: JSON.stringify(data),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(data) {
console.log(data);
createAndAppendRow(data);
}
});
});
}
});
return false;
});
|
Add JS to handle submission of dates
|
Add JS to handle submission of dates
|
JavaScript
|
mit
|
ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter,ayushgoel/flock-message-reporter
|
f246bb8163d663ca173ae3be386a9f7bb82fd66c
|
src/mapHelper.js
|
src/mapHelper.js
|
/**
* We need to map identifiers between TestSwarm and BrowserStack.
*
* Sources:
* - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php
* - ua-parser: https://github.com/ua-parser/uap-core
* - BrowserStack:
* https://github.com/browserstack/api
* http://api.browserstack.com/3/browsers (requires authentication)
*/
// These are in the direction testswarm (ua-parser) -> browserstack.
module.exports = {
browserFamily: {
'Yandex Browser': 'yandex',
'Android': 'Android Browser'
},
osFamily: {
'Windows': 'Windows',
'Mac OS X': 'OS X',
'Android': 'android',
'iOS': 'ios'
},
// BrowserStack puts device version inside device family.
// Normalise them here, we use OS version instead.
deviceFamily: {
// Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc.
'iPad': /^iPad\b/,
// Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc.
'iPhone': /^iPhone\b/
}
};
|
/**
* We need to map identifiers between TestSwarm and BrowserStack.
*
* Sources:
* - TestSwarm: https://github.com/jquery/testswarm/blob/master/inc/BrowserInfo.php
* - ua-parser: https://github.com/ua-parser/uap-core
* - BrowserStack:
* https://github.com/browserstack/api
* http://api.browserstack.com/3/browsers (requires authentication)
*/
// These are in the direction testswarm (ua-parser) -> browserstack.
module.exports = {
browserFamily: {
'Yandex Browser': 'yandex',
'Android': 'Android Browser',
// Android 4.4 and higher use Chrome Mobile instead of Android Browser.
// BrowserStack supports both Chrome and Firefox on Android through
// the UI. However, the v4 API only exposes one of them (Chrome)
// but labels it "Android Browser" for back-compat.
'Chrome Mobile': 'Android Browser'
},
osFamily: {
'Windows': 'Windows',
'Mac OS X': 'OS X',
'Android': 'android',
'iOS': 'ios'
},
// BrowserStack puts device version inside device family.
// Normalise them here, we use OS version instead.
deviceFamily: {
// Match "iPad 2", "iPad 3rd (6.0)", "iPad Air 2", etc.
'iPad': /^iPad\b/,
// Match "iPhone 4", "iPhone 4S (6.0)", "iPhone 6S Plus", etc.
'iPhone': /^iPhone\b/
}
};
|
Add mapping for 'Chrome Mobile' -> 'Android Browser'
|
map: Add mapping for 'Chrome Mobile' -> 'Android Browser'
BrowserStack v4 has back-compat mapping that is actually working
against us in this case..
|
JavaScript
|
mit
|
clarkbox/testswarm-browserstack,clarkbox/testswarm-browserstack,mzgol/testswarm-browserstack,mzgol/testswarm-browserstack
|
4d3a9dd9764f0cd934342d63036b6b5b76e6e0be
|
public/models/os-project.js
|
public/models/os-project.js
|
import DefineMap from 'can-define/map/';
import DefineList from 'can-define/list/';
import superMap from 'can-connect/can/super-map/';
import tag from 'can-connect/can/tag/';
export const OsProject = DefineMap.extend({
seal: false
}, {
'_id': '*',
'name': 'string'
});
OsProject.List = DefineList.extend({
'*': OsProject
});
export const os-projectConnection = superMap({
url: '/api/os_projects',
idProp: '_id',
Map: OsProject,
List: OsProject.List,
name: 'os-project'
});
tag('os-project-model', os-projectConnection);
export default OsProject;
|
import DefineMap from 'can-define/map/';
import DefineList from 'can-define/list/';
import superMap from 'can-connect/can/super-map/';
import tag from 'can-connect/can/tag/';
export const OsProject = DefineMap.extend({
seal: false
}, {
'_id': '*',
'name': 'string'
});
OsProject.List = DefineList.extend({
'*': OsProject
});
export const osProjectConnection = superMap({
url: '/api/os_projects',
idProp: '_id',
Map: OsProject,
List: OsProject.List,
name: 'os-project'
});
tag('os-project-model', osProjectConnection);
export default OsProject;
|
Fix os project model connection name
|
Fix os project model connection name
|
JavaScript
|
mit
|
donejs/bitcentive,donejs/bitcentive
|
78c5eab8d563b44269a591b9249439b55d31d72b
|
test/pages-test.js
|
test/pages-test.js
|
const { expect } = require('chai');
const request = require('supertest');
const app = require('../app');
describe('Pages', function() {
describe('/', function() {
let req;
beforeEach(function() {
req = request(app).get('/');
});
it('returns 200 OK', function(done) {
req.expect(200, done);
});
it('renders a template', function (done) {
req.expect('Content-Type', /text\/html/, done);
});
});
});
|
const { expect } = require('chai');
const request = require('supertest');
const app = require('../app');
describe('Pages', function() {
let req;
describe('/', function() {
beforeEach(function() {
req = request(app).get('/')
});
it('returns 200 OK', function(done) {
req.expect(200, done);
});
it('renders template', function (done) {
req.expect('Content-Type', /text\/html/, done);
});
});
describe('/contact', function() {
beforeEach(function() {
req = request(app).get('/contact');
});
it('returns 200 OK', function (done) {
req.expect(200, done);
});
it('renders template', function (done) {
req.expect('Content-Type', /text\/html/, done);
});
});
});
|
Add tests for /contact page
|
Add tests for /contact page
|
JavaScript
|
mit
|
slavapavlutin/pavlutin-node,slavapavlutin/pavlutin-node
|
7361aa3e36272dfe8a138df011894d79e79b4448
|
tasks/docco.js
|
tasks/docco.js
|
// grunt-docco
// https://github.com/DavidSouther/grunt-docco
//
// Copyright (c) 2012 David Souther
// Licensed under the MIT license.
"use strict"
var docco = require('docco');
module.exports = function(grunt) {
grunt.registerMultiTask('docco', 'Docco processor.', function() {
var options = this.options({ output: this.file.dest }),
_this = this,
files = this.file.src,
fdone = 0;
var done = _this.async();
files.forEach(function(file) {
var files = grunt.file.expandFiles(file);
docco.document(files, options, function(err, result, code){
if(fdone++ == files.length) done();
});
});
});
};
|
// grunt-docco
// https://github.com/DavidSouther/grunt-docco
//
// Copyright (c) 2012 David Souther
// Licensed under the MIT license.
"use strict"
var docco = require('docco');
module.exports = function(grunt) {
grunt.registerMultiTask('docco', 'Docco processor.', function() {
var fdone = 0;
var flength = this.files.length;
var done = this.async();
this.files.forEach(function(file) {
var files = grunt.file.expand(file.src);
docco.document(files, { output: file.dest }, function(err, result, code){
if(++fdone === flength) done();
});
});
});
};
|
Update to be compatible with grunt 0.4rc6
|
Update to be compatible with grunt 0.4rc6
|
JavaScript
|
mit
|
joseph-jja/grunt-docco-dir,DavidSouther/grunt-docco,joseph-jja/grunt-docco-dir,neocotic/grunt-docco
|
b42ca23427c9a6e630b77b58b94f4de9c56b372b
|
test/unit/constants_spec.js
|
test/unit/constants_spec.js
|
/*global angular */
'use strict';
describe('Unit: Constants', function () {
var constants;
beforeEach(function () {
// instantiate the app module
angular.mock.module('app');
// mock the directive
angular.mock.inject(function (AppSettings) {
constants = AppSettings;
});
});
it('should exist', function () {
expect(constants).toBeDefined();
});
it('should have an application name', function () {
expect(constants.appTitle).toEqual('IRC Bed Management Dashboard');
});
});
|
/*global angular */
'use strict';
describe('Unit: Constants', function () {
var constants;
beforeEach(function () {
// instantiate the app module
angular.mock.module('app');
// mock the directive
angular.mock.inject(function (AppSettings) {
constants = AppSettings;
});
});
it('should exist', function () {
expect(constants).toBeDefined();
});
it('should have an application name', function () {
expect(constants.appTitle).toEqual('IRC Capacity Management Dashboard');
});
});
|
Fix test to match new name
|
Fix test to match new name
|
JavaScript
|
mit
|
UKHomeOffice/removals_wallboard,UKHomeOffice/removals_wallboard,UKHomeOffice/removals_wallboard
|
25cdc352467d9302aa6c09cd0124295f4e3b8814
|
src/swap-case.js
|
src/swap-case.js
|
import R from 'ramda';
import compose from './util/compose.js';
import join from './util/join.js';
import not from './util/not.js';
import upperCase from './util/upper-case.js';
import lowerCase from './util/lower-case.js';
import isUpperCase from '../src/is-upper-case.js';
// a -> a
const swapCase = compose(
join(''),
R.map(
R.either(
R.both(isUpperCase, lowerCase),
R.both(compose(not, isUpperCase), upperCase)
)
)
);
export default swapCase;
|
import R from 'ramda';
import compose from './util/compose.js';
import either from './util/either.js';
import join from './util/join.js';
import not from './util/not.js';
import upperCase from './util/upper-case.js';
import lowerCase from './util/lower-case.js';
import isUpperCase from '../src/is-upper-case.js';
// a -> a
const swapCase = compose(
join(''),
R.map(
either(
R.both(isUpperCase, lowerCase),
R.both(compose(not, isUpperCase), upperCase)
)
)
);
export default swapCase;
|
Refactor swapCase function to use custom either function
|
Refactor swapCase function to use custom either function
|
JavaScript
|
mit
|
restrung/restrung-js
|
e950c031b3b80ada5110a286e8966d8dce7f2241
|
src/JBrowse/main.js
|
src/JBrowse/main.js
|
// saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'JBrowse/Store/Sequence/StaticChunked',
'JBrowse/Store/SeqFeature/NCList',
'JBrowse/Store/TiledImage/Fixed',
'JBrowse/Store/Names/Hash',
'JBrowse/Store/Names/REST',
// common track views
'JBrowse/View/Track/Sequence',
'JBrowse/View/Track/HTMLFeatures',
'JBrowse/View/Track/FixedImage/Wiggle',
'JBrowse/View/Track/Wiggle',
'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/View/Track/Wiggle/Density',
'JBrowse/View/Track/Alignments',
'JBrowse/View/Track/Alignments2',
'JBrowse/View/Track/FeatureCoverage',
'JBrowse/View/Track/SNPCoverage',
// track lists
'JBrowse/Store/TrackMetaData'
]);
|
// saves some loading time by loading most of the commonly-used
// JBrowse modules at the outset
require([
'JBrowse/Browser',
'JBrowse/ConfigAdaptor/JB_json_v1',
// default tracklist view
'JBrowse/View/TrackList/Hierarchical',
// common stores
'JBrowse/Store/Sequence/StaticChunked',
'JBrowse/Store/SeqFeature/NCList',
'JBrowse/Store/TiledImage/Fixed',
'JBrowse/Store/Names/Hash',
'JBrowse/Store/Names/REST',
// common track views
'JBrowse/View/Track/Sequence',
'JBrowse/View/Track/HTMLFeatures',
'JBrowse/View/Track/FixedImage/Wiggle',
'JBrowse/View/Track/Wiggle',
'JBrowse/View/Track/Wiggle/XYPlot',
'JBrowse/View/Track/Wiggle/Density',
'JBrowse/View/Track/Alignments',
'JBrowse/View/Track/Alignments2',
'JBrowse/View/Track/FeatureCoverage',
'JBrowse/View/Track/SNPCoverage',
// track lists
'JBrowse/Store/TrackMetaData',
'xstyle/core/load-css',
'dojox/gfx/svg'
]);
|
Add back the xstyle and dojox svg modules correctly
|
Add back the xstyle and dojox svg modules correctly
|
JavaScript
|
lgpl-2.1
|
GMOD/jbrowse,erasche/jbrowse,GMOD/jbrowse,Arabidopsis-Information-Portal/jbrowse,Arabidopsis-Information-Portal/jbrowse,nathandunn/jbrowse,erasche/jbrowse,erasche/jbrowse,nathandunn/jbrowse,nathandunn/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,GMOD/jbrowse,GMOD/jbrowse,nathandunn/jbrowse,Arabidopsis-Information-Portal/jbrowse,GMOD/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,nathandunn/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse,erasche/jbrowse,Arabidopsis-Information-Portal/jbrowse
|
7edcb97899f0812c280bb73326b6041d734656d1
|
src/core/GraoModel.js
|
src/core/GraoModel.js
|
var GraoModel = function(di) {
di.event.newSuccess('Database Connection....');
di.mongoose.connect(di.config.db);
di.event.newSuccess('Instance created');
di.models = this;
di.models = di.loader.tryLoad(di.loader.loading('model'), di, 'models');
};
module.exports = exports = GraoModel;
|
var GraoModel = function(di) {
di.event.newSuccess('Database Connection....');
//di.mongoose.connect(di.config.db);
di.mongoose.connect(di.config.db, {useMongoClient: true});
di.event.newSuccess('Instance created');
di.models = this;
di.models = di.loader.tryLoad(di.loader.loading('model'), di, 'models');
};
module.exports = exports = GraoModel;
|
Add new param to mongoose connection
|
Add new param to mongoose connection
|
JavaScript
|
mit
|
marcelomf/graojs,marcelomf/graojs,marcelomf/graojs,synackbr/graojs,synackbr/graojs,synackbr/graojs
|
c1dca6018d44c0090e1b5bbf16eb4df12882ece5
|
src/player.js
|
src/player.js
|
function Player() {
this.strength = statRoll();
this.dexterity = statRoll();
this.mind = statRoll();
this.init(arguments);
}
Mextend(Player, {
player: true,
name: '<sV|Bvs>(.exe)',
experience: 0
});
Player.prototype.act = function(callback) {
controls.act();
};
Player.prototype.addExperience = function(exp) {
this.experience += exp;
unimportant('You gain %d experience.', exp);
while (this.experience > this.nextLevel()) {
this.levelUp();
}
};
/**
* Level up the player.
*/
Player.prototype.levelUp = function() {
this.experience -= this.nextLevel();
this.level += 1;
var hproll = d6();
this.maxhp += hproll;
this.hp = this.maxhp;
var mproll = d6();
this.maxmp += mproll;
this.mp += mproll;
if ((this.level % 3) === 0) this.strength++; // XXX
important("You are now at version %d.0!", this.level);
};
Player.prototype.nextLevel = function() {
return Math.ceil(Math.pow(this.level + 8, 2.1));
};
|
function Player() {
this.strength = statRoll();
this.dexterity = statRoll();
this.mind = statRoll();
this.init(arguments);
}
Mextend(Player, {
player: true,
name: '<sV|Bvs>(.exe)',
experience: 0
});
Player.prototype.act = function(callback) {
controls.act();
};
Player.prototype.addExperience = function(exp) {
this.experience += exp;
unimportant('You gain %d experience.', exp);
while (this.experience > this.nextLevel()) {
this.levelUp();
}
};
/**
* Level up the player.
*/
Player.prototype.levelUp = function() {
this.experience -= this.nextLevel();
this.level += 1;
var hproll = d6();
for (var i = 1; i < bonus(this.strength); i++) hproll += d6();
this.maxhp += hproll;
this.hp = this.maxhp;
var mproll = d6();
this.maxmp += mproll;
this.mp += mproll;
switch (this.level % 3) {
case 0:
this.strength++;
break;
case 1:
this.dexterity++;
break;
case 2:
this.mind++;
break;
}
important("You are now at version %d.0!", this.level);
};
Player.prototype.nextLevel = function() {
return Math.ceil(Math.pow(this.level + 8, 2.1));
};
|
Make leveling a bit stronger.
|
Make leveling a bit stronger.
|
JavaScript
|
unlicense
|
skeeto/disc-rl
|
7f7eae887362b117cca1f567fbd2ea8677082e0c
|
examples/index.js
|
examples/index.js
|
var Gravatar = require('../dist/index.js');
var React = require('react');
React.renderComponent(
React.DOM.div(null,
[
React.DOM.h2(null, "<Gravatar email='[email protected]' />"),
Gravatar({email: '[email protected]'}),
React.DOM.h2(null, "<Gravatar email='[email protected]' size=100 />"),
Gravatar({email: '[email protected]', size: 100}),
React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."),
Gravatar({email: '[email protected]'}),
]), document.body);
|
var React = require('react');
var Gravatar = React.createFactory(require('../dist/index.js'));
React.render(
React.DOM.div(null,
[
React.DOM.h2(null, "<Gravatar email='[email protected]' />"),
Gravatar({email: '[email protected]'}),
React.DOM.h2(null, "<Gravatar email='[email protected]' size=100 />"),
Gravatar({email: '[email protected]', size: 100}),
React.DOM.h2(null, "For emails without a gravatar, use the retro default. You can override this by passing in a different 'default' prop. See https://en.gravatar.com/site/implement/images/ for options."),
Gravatar({email: '[email protected]'}),
]), document.body);
|
Fix example for React 0.13
|
Fix example for React 0.13
|
JavaScript
|
mit
|
KyleAMathews/react-gravatar
|
e3c41cb206d1c36622c41cf0ec45e61501bababa
|
config/config-sample.js
|
config/config-sample.js
|
module.exports =
{
home: '/home', // the path to users home directory (absolute!)
tmp: process.env.HOME + '/.ezseed/tmp', //the tmp folder path - default to HOME/.ezseed/tmp (absolute!)
watcher: 'unix:///usr/local/opt/ezseed/watcher.sock',
watcher_rpc: 'unix:///usr/local/opt/ezseed/watcher_rpc.sock',
transmission: false, //is transmission installed?
rtorrent: false, //is rtorrent installed?
client_link: 'embed', //embed|link do we embed the p2p web interface or should it be openin a new window?
theme: 'ezseed-web',
scrapper: 'tmdb',
lang: 'en',
secret: 'really-secret-key'
}
|
module.exports =
{
home: '/home', // the path to users home directory (absolute!)
tmp: process.env.HOME + '/.ezseed/tmp', //the tmp folder path - default to HOME/.ezseed/tmp (absolute!)
watcher: 'unix:///usr/local/opt/ezseed/watcher.sock',
watcher_rpc: 'unix:///usr/local/opt/ezseed/watcher_rpc.sock',
transmission: false, //is transmission installed?
rtorrent: false, //is rtorrent installed?
client_link: 'embed', //embed|link do we embed the p2p web interface or should it be openin a new window?
theme: 'ezseed-web',
scrapper: 'tmdb',
lang: 'en',
secret: 'really-secret-key',
base: '/' //ezseed base path
}
|
Add base path to config
|
feat(config): Add base path to config
|
JavaScript
|
bsd-3-clause
|
ezseed/ezseed,ezseed/ezseed
|
3b346545f373a2d52db9dc4d8774b75c4cf46246
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var rename = require('gulp-rename');
gulp.task('scripts', function() {
browserify('./static/js/app.js')
.bundle()
.pipe(source('js.min.js'))
//.pipe(streamify(uglify()))
.pipe(gulp.dest('./static/build'));
});
gulp.task('css', function() {
gulp.src('./static/sass/style.scss')
.pipe(sass({
outputStyle: 'compressed',
errLogToConsole: true,
error: function(err) {
console.log(err);
}
}))
.pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7"))
.pipe(rename('css.min.css'))
.pipe(gulp.dest('./static/build'));
});
// Watch
gulp.task('watch', function() {
// Watch .scss files
gulp.watch(['static/js/**/*', 'static/sass/**/*'], ['css', 'scripts']);
});
gulp.task('default', ['scripts', 'css']);
|
var gulp = require('gulp');
var source = require('vinyl-source-stream');
var browserify = require('browserify');
var streamify = require('gulp-streamify');
var uglify = require('gulp-uglify');
var sass = require('gulp-sass');
var prefix = require('gulp-autoprefixer');
var rename = require('gulp-rename');
var gutil = require('gulp-util');
var webpack = require('gulp-webpack');
gulp.task('scripts', function() {
browserify('./static/js/app.js')
.bundle()
.pipe(source('js.min.js'))
//.pipe(streamify(uglify()))
.pipe(gulp.dest('./static/build'));
});
gulp.task('css', function() {
gulp.src('./static/sass/style.scss')
.pipe(sass({
outputStyle: 'compressed',
errLogToConsole: true,
error: function(err) {
console.log(err);
}
}))
.pipe(prefix("last 1 version", "> 1%", "ie 8", "ie 7"))
.pipe(rename('css.min.css'))
.pipe(gulp.dest('./static/build'));
});
gulp.task('webpack', function(callback) {
return gulp.src('./static/js/app.js')
.pipe(webpack({ /* webpack configuration */ }))
.pipe(uglify())
.pipe(rename('js.min.js'))
.pipe(gulp.dest('./static/build'));
});
// Watch
gulp.task('watch', function() {
// Watch .scss files
gulp.watch(['static/js/**/*', 'static/sass/**/*'], ['css', 'scripts']);
});
gulp.task('default', ['scripts', 'css']);
|
Add in webpack in there.
|
Add in webpack in there.
|
JavaScript
|
mit
|
eiriksm/sqr,eiriksm/sqr
|
b894d45eda87023ebcb4775c2720b0ceb58a4c9a
|
gulpfile.js
|
gulpfile.js
|
var eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip'),
rename = require('gulp-rename');
gulp.task('prepare-release', function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('button-refresh-plugin-' + version + '.zip')),
getSources()
.pipe(tar('button-refresh-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(0644))
.pipe(gulp.dest('release'));
});
// Builds and packs plugins sources
gulp.task('default', ['prepare-release'], function() {
// The "default" task is just an alias for "prepare-release" task.
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Plugin.php',
'README.md',
'LICENSE'
],
{base: './'}
)
.pipe(rename(function(path) {
path.dirname = 'Mibew/Mibew/Plugin/ButtonRefresh/' + path.dirname;
}));
}
|
var eventStream = require('event-stream'),
gulp = require('gulp'),
chmod = require('gulp-chmod'),
zip = require('gulp-zip'),
tar = require('gulp-tar'),
gzip = require('gulp-gzip'),
rename = require('gulp-rename');
gulp.task('prepare-release', function() {
var version = require('./package.json').version;
return eventStream.merge(
getSources()
.pipe(zip('button-refresh-plugin-' + version + '.zip')),
getSources()
.pipe(tar('button-refresh-plugin-' + version + '.tar'))
.pipe(gzip())
)
.pipe(chmod(644))
.pipe(gulp.dest('release'));
});
// Builds and packs plugins sources
gulp.task('default', ['prepare-release'], function() {
// The "default" task is just an alias for "prepare-release" task.
});
/**
* Returns files stream with the plugin sources.
*
* @returns {Object} Stream with VinylFS files.
*/
var getSources = function() {
return gulp.src([
'Plugin.php',
'README.md',
'LICENSE'
],
{base: './'}
)
.pipe(rename(function(path) {
path.dirname = 'Mibew/Mibew/Plugin/ButtonRefresh/' + path.dirname;
}));
}
|
Fix invalid bitmask for release archives
|
Fix invalid bitmask for release archives
|
JavaScript
|
apache-2.0
|
Mibew/button-refresh-plugin,Mibew/button-refresh-plugin
|
1726c021482bff178832cb4e3c0816cf560416f0
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var jasmine = require('gulp-jasmine');
gulp.task('jasmine', function () {
return gulp.src('spec/**/*.js')
.pipe(jasmine({
verbose: true
}));
});
gulp.task('babel', function () {
return gulp.src('src/**/*.js')
//.pipe(sourcemaps.init())
.pipe(babel({
stage: 0 // http://babeljs.io/docs/usage/experimental/
}))
//.pipe(concat('all.js'))
//.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
gulp.task('watch', function(){
gulp.watch(['src/**/*.js', 'spec/**/*.js'], ['babel', 'jasmine']);
});
gulp.task('default', ['watch']);
|
var gulp = require('gulp');
var sourcemaps = require('gulp-sourcemaps');
var babel = require('gulp-babel');
var concat = require('gulp-concat');
var jasmine = require('gulp-jasmine');
gulp.task('jasmine', function () {
return gulp.src('spec/**/*.js')
.pipe(jasmine({
verbose: true
}));
});
gulp.task('babel', function () {
return gulp.src('src/**/*.js')
//.pipe(sourcemaps.init())
.pipe(babel({
stage: 0 // http://babeljs.io/docs/usage/experimental/
}))
.on('error', console.error.bind(console))
//.pipe(concat('all.js'))
//.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
gulp.task('watch', function(){
gulp.watch(['src/**/*.js', 'spec/**/*.js'], ['babel', 'jasmine']);
});
gulp.task('default', ['watch']);
|
Add error handling to make babel not exit on error
|
Add error handling to make babel not exit on error
|
JavaScript
|
mit
|
trapridge/es67-fun
|
b10940e31c2a218574f9a5babbf2b782bc7baecd
|
lib/buster-util/jstestdriver-shim.js
|
lib/buster-util/jstestdriver-shim.js
|
function testCase(name, tests) {
var testCase = TestCase(name);
for (var test in tests) {
if (test != "setUp" && test != "tearDown") {
testCase.prototype["test " + test] = tests[test];
} else {
testCase.prototype[test] = tests[test];
}
}
return testCase;
}
var assert = this;
(function () {
var mappedAssertions = {
ok: "True",
doesNotThrow: "NoException",
throws: "Exception",
equal: "Equals"
};
for (var assertion in mappedAssertions) {
assert[assertion] = assert["assert" + mappedAssertions[assertion]];
}
}());
|
function testCase(name, tests) {
var testCase = TestCase(name);
for (var test in tests) {
if (test != "setUp" && test != "tearDown") {
testCase.prototype["test " + test] = tests[test];
} else {
testCase.prototype[test] = tests[test];
}
}
return testCase;
}
var assert = this;
(function () {
var mappedAssertions = {
ok: "True",
doesNotThrow: "NoException",
throws: "Exception",
equal: "Equals"
};
for (var assertion in mappedAssertions) {
assert[assertion] = assert["assert" + mappedAssertions[assertion]];
}
}());
if (buster.assert && buster.format) {
buster.assert.format = buster.format.ascii;
buster.assert.fail = fail;
}
|
Add buster.assert hook when it's available
|
Add buster.assert hook when it's available
|
JavaScript
|
bsd-3-clause
|
busterjs/buster-core,geddski/buster-core,busterjs/buster-core
|
602fe72de7d59a80ff3a50c011bce5c4f820a905
|
config/environment.js
|
config/environment.js
|
/* eslint-env node */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'noise',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.noiseUrl = '//localhost:3000/query'
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.noiseUrl = '//try.noisesearch.org:3000/query'
}
return ENV;
};
|
/* eslint-env node */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'noise',
environment: environment,
rootURL: '/',
locationType: 'auto',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
},
EXTEND_PROTOTYPES: {
// Prevent Ember Data from overriding Date.parse.
Date: false
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
ENV.noiseUrl = '//localhost:3000/query'
}
if (environment === 'test') {
// Testem prefers this...
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
ENV.noiseUrl = '/query'
}
return ENV;
};
|
Use the proxied endpoint for production
|
Use the proxied endpoint for production
|
JavaScript
|
apache-2.0
|
pipedown/try_out_noise,pipedown/try_out_noise,pipedown/try_out_noise
|
ce8ce0520c7cf64fe954b55fb8e90e6e21b0909d
|
src/methodCreators.js
|
src/methodCreators.js
|
const takeNoArgs = (method) => function() {
return method(this.props);
};
const takeFirstArg = (method) => function(nextProps) {
return method(this.props, nextProps);
};
const methodCreators = {
componentWillMount: takeNoArgs,
componentDidMount: takeNoArgs,
componentWillReceiveProps: takeFirstArg,
shouldComponentUpdate: takeFirstArg,
componentWillUpdate: takeFirstArg,
componentDidUpdate: takeFirstArg,
componentWillUnmount: takeNoArgs
};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(methodCreators);
}
export default methodCreators;
|
const takeNoArgs = (method) => function() {
return method(this.props);
};
const takeFirstArg = (method) => function(arg1) {
return method(this.props, arg1);
};
const methodCreators = {
componentWillMount: takeNoArgs,
componentDidMount: takeNoArgs,
componentWillReceiveProps: takeFirstArg,
shouldComponentUpdate: takeFirstArg,
componentWillUpdate: takeFirstArg,
componentDidUpdate: takeFirstArg,
componentWillUnmount: takeNoArgs
};
if (process.env.NODE_ENV !== 'production') {
Object.freeze(methodCreators);
}
export default methodCreators;
|
Use more generic param name
|
Use more generic param name
|
JavaScript
|
mit
|
jfairbank/react-classify,jfairbank/react-classify
|
3cc85e098b44c54683820526998e341dd0a184e1
|
test/bindings.js
|
test/bindings.js
|
/*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.should.equal(1);
done();
});
});
it('should support bindings with client.stream()', function(done) {
var client = gremlin.createClient();
var stream = client.stream('g.v(x)', { x: 1 });
stream.on('data', function(result) {
result.id.should.equal(1);
});
stream.on('end', function() {
done();
});
});
it('should give an error with erroneous binding name in .exec', function(done) {
var client = gremlin.createClient();
client.execute('g.v(id)', { id: 1 }, function(err, result) {
(err !== null).should.be.true;
(result === undefined).should.be.true;
done();
});
});
});
|
/*jshint -W030 */
var gremlin = require('../');
describe('Bindings', function() {
it('should support bindings with client.execute()', function(done) {
var client = gremlin.createClient();
client.execute('g.v(x)', { x: 1 }, function(err, result) {
(err === null).should.be.true;
result.length.should.equal(1);
done();
});
});
it('should support bindings with client.stream()', function(done) {
var client = gremlin.createClient();
var stream = client.stream('g.v(x)', { x: 1 });
stream.on('data', function(result) {
result.id.should.equal(1);
});
stream.on('end', function() {
done();
});
});
it('should give an error with erroneous binding name in .exec', function(done) {
var client = gremlin.createClient();
// This is supposed to throw a NoSuchElementException in Gremlin Server:
// --> "The vertex with id id of type does not exist in the graph"
// id is a reserved (imported) variable and can't be used in a script
client.execute('g.v(id)', { id: 1 }, function(err, result) {
(err !== null).should.be.true;
(result === undefined).should.be.true;
done();
});
});
});
|
Add explicit comments in test using reserved binding name
|
Add explicit comments in test using reserved binding name
|
JavaScript
|
mit
|
jbmusso/gremlin-client,hiddenmoo/gremlin-client,CosmosDB/gremlin-javascript,CosmosDB/gremlin-javascript,hiddenmoo/gremlin-client,jbmusso/gremlin-javascript,jbmusso/gremlin-javascript
|
d0c2c5dd1d067c832c7fcd1883f737132956adc3
|
src/document/Doc.js
|
src/document/Doc.js
|
Doc = Base.extend({
beans: true,
initialize: function(canvas) {
if (canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.size = new Size(canvas.offsetWidth, canvas.offsetHeight);
}
Paper.documents.push(this);
this.activate();
this.layers = [];
this.activeLayer = new Layer();
this.currentStyle = null;
this.symbols = [];
},
getCurrentStyle: function() {
return this._currentStyle;
},
setCurrentStyle: function(style) {
this._currentStyle = new PathStyle(this, style);
},
activate: function() {
Paper.activateDocument(this);
},
redraw: function() {
if (this.canvas) {
this.ctx.clearRect(0, 0, this.size.width + 1, this.size.height);
for (var i = 0, l = this.layers.length; i < l; i++) {
this.layers[i].draw(this.ctx);
}
}
}
});
|
Doc = Base.extend({
beans: true,
initialize: function(canvas) {
if (canvas) {
this.canvas = canvas;
this.ctx = this.canvas.getContext('2d');
this.size = new Size(canvas.offsetWidth, canvas.offsetHeight);
}
Paper.documents.push(this);
this.activate();
this.layers = [];
this.activeLayer = new Layer();
this.currentStyle = null;
this.symbols = [];
},
getCurrentStyle: function() {
return this._currentStyle;
},
setCurrentStyle: function(style) {
this._currentStyle = new PathStyle(this, style);
},
activate: function() {
Paper.activateDocument(this);
},
redraw: function() {
if (this.canvas) {
// TODO: clearing the canvas by setting
// this.canvas.width = this.canvas.width might be faster..
this.ctx.clearRect(0, 0, this.size.width + 1, this.size.height);
for (var i = 0, l = this.layers.length; i < l; i++) {
this.layers[i].draw(this.ctx);
}
}
}
});
|
Add todo about speeding up canvas clearing.
|
Add todo about speeding up canvas clearing.
|
JavaScript
|
mit
|
proofme/paper.js,iconexperience/paper.js,Olegas/paper.js,superjudge/paper.js,0/paper.js,li0t/paper.js,li0t/paper.js,byte-foundry/paper.js,luisbrito/paper.js,fredoche/paper.js,nancymark/paper.js,Olegas/paper.js,nancymark/paper.js,rgordeev/paper.js,ClaireRutkoske/paper.js,ClaireRutkoske/paper.js,byte-foundry/paper.js,JunaidPaul/paper.js,ClaireRutkoske/paper.js,0/paper.js,JunaidPaul/paper.js,fredoche/paper.js,baiyanghese/paper.js,mcanthony/paper.js,luisbrito/paper.js,li0t/paper.js,superjudge/paper.js,iconexperience/paper.js,JunaidPaul/paper.js,baiyanghese/paper.js,proofme/paper.js,NHQ/paper,legendvijay/paper.js,EskenderDev/paper.js,mcanthony/paper.js,lehni/paper.js,proofme/paper.js,superjudge/paper.js,rgordeev/paper.js,lehni/paper.js,legendvijay/paper.js,iconexperience/paper.js,mcanthony/paper.js,lehni/paper.js,rgordeev/paper.js,baiyanghese/paper.js,nancymark/paper.js,EskenderDev/paper.js,legendvijay/paper.js,luisbrito/paper.js,EskenderDev/paper.js,fredoche/paper.js,chad-autry/paper.js,NHQ/paper,byte-foundry/paper.js,Olegas/paper.js
|
2bbab9759bce51c6f9641e4237c8010445d848d8
|
packages/@sanity/core/src/actions/dataset/streamDataset.js
|
packages/@sanity/core/src/actions/dataset/streamDataset.js
|
import got from 'got'
export default (client, dataset) => {
// Sanity client doesn't handle streams natively since we want to support node/browser
// with same API. We're just using it here to get hold of URLs and tokens.
const url = client.getUrl(`/data/export/${dataset}`)
return got.stream(url, {
headers: {Authorization: `Bearer: ${client.config().token}`}
})
}
|
import got from 'got'
export default (client, dataset) => {
// Sanity client doesn't handle streams natively since we want to support node/browser
// with same API. We're just using it here to get hold of URLs and tokens.
const url = client.getUrl(`/data/export/${dataset}`)
return got.stream(url, {
headers: {Authorization: `Bearer ${client.config().token}`}
})
}
|
Fix incorrect authorization header on dataset export
|
[core] Fix incorrect authorization header on dataset export
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
c8fc979080729361180ab6a04df63c0140a1ffd2
|
packages/@sanity/server/src/configs/webpack.config.prod.js
|
packages/@sanity/server/src/configs/webpack.config.prod.js
|
import webpack from 'webpack'
import getBaseConfig from './webpack.config'
export default config => {
const baseConfig = getBaseConfig(Object.assign({}, config, {env: 'production'}))
const skipMinify = config.skipMinify
return Object.assign({}, baseConfig, {
devtool: config.sourceMaps ? 'source-map' : undefined,
plugins: (baseConfig.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
}),
!skipMinify && new webpack.optimize.UglifyJsPlugin({
compressor: {
warnings: false
}
})
].filter(Boolean))
})
}
|
import webpack from 'webpack'
import getBaseConfig from './webpack.config'
export default config => {
const baseConfig = getBaseConfig(Object.assign({}, config, {env: 'production'}))
return Object.assign({}, baseConfig, {
devtool: config.sourceMaps ? 'source-map' : undefined,
plugins: (baseConfig.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify('production')
}
})
].filter(Boolean))
})
}
|
Move minification out of webpack
|
Move minification out of webpack
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.