commit stringlengths 40 40 | old_file stringlengths 4 150 | new_file stringlengths 4 150 | old_contents stringlengths 0 3.26k | new_contents stringlengths 1 4.43k | subject stringlengths 15 501 | message stringlengths 15 4.06k | lang stringclasses 4 values | license stringclasses 13 values | repos stringlengths 5 91.5k | diff stringlengths 0 4.35k |
|---|---|---|---|---|---|---|---|---|---|---|
400ea7145b890e6fa6c2494da7414ac336c5f721 | src/api/mailchimp/index.js | src/api/mailchimp/index.js | // @flow
import R from 'ramda';
import axios from 'axios';
import env from '../../env';
import { baseUrl, reportUrl } from './generateUrl';
const MC_KEY = env('MC_KEY');
const MC_USER = env('MC_USER');
export const coreApi = axios.create({
baseURL: baseUrl(),
auth: {
username: MC_USER,
password: MC_KEY,
},
});
export const getReport = async (campaignId: string): Promise<MCreport> => {
const result = await coreApi(reportUrl(campaignId));
const data: MCreport = result.data;
return data;
};
| ADD Initial version of mailchimp api connection | ADD Initial version of mailchimp api connection
| JavaScript | mit | adambrgmn/sst-analytics,adambrgmn/sst-analytics,adambrgmn/sst-analytics | ---
+++
@@ -0,0 +1,23 @@
+// @flow
+import R from 'ramda';
+import axios from 'axios';
+import env from '../../env';
+import { baseUrl, reportUrl } from './generateUrl';
+
+const MC_KEY = env('MC_KEY');
+const MC_USER = env('MC_USER');
+
+export const coreApi = axios.create({
+ baseURL: baseUrl(),
+ auth: {
+ username: MC_USER,
+ password: MC_KEY,
+ },
+});
+
+export const getReport = async (campaignId: string): Promise<MCreport> => {
+ const result = await coreApi(reportUrl(campaignId));
+ const data: MCreport = result.data;
+
+ return data;
+}; | |
70f9f119ddd53239d42006be8472ab979d653cab | 3/moment-add.js | 3/moment-add.js | var moment = require('moment');
console.log(moment("2014-12-11 4:30", "YYYY-MM-DD HH:mm"));
console.log(moment("2014-12-11 4:30 +0800", "YYYY-MM-DD HH:mm Z"));
console.log(moment("2014-12-11 4:30AM", "YYYY-MM-DD HH:mmA"));
| Add the example to use moment to manipulate time by add. | Add the example to use moment to manipulate time by add.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,6 @@
+var moment = require('moment');
+
+console.log(moment("2014-12-11 4:30", "YYYY-MM-DD HH:mm"));
+console.log(moment("2014-12-11 4:30 +0800", "YYYY-MM-DD HH:mm Z"));
+console.log(moment("2014-12-11 4:30AM", "YYYY-MM-DD HH:mmA"));
+ | |
20d43a411b35666db2cde5908eeb94ca6066e733 | tools/validate_components.js | tools/validate_components.js | #!/usr/bin/env node
'use strict';
/**
* Validate that a given component can actually server-side render
* with the given properties (specified via a fixture file).
*
* Not all react components can be server-side rendered: they may
* use globals, or access the DOM, or what hafve you. This script
* can be used to validate that the component *can* be server-side
* rendered.
*
* The input is a bit difficult to construct: it's a json list of
* objects like so:
* {
* jsPackages: [[pkg_name, pkg_contents], [pkg_name, pkg_contents], ...],
* pathToReactComponent: "./in/require/format.js",
* fixtureFile: "/ideally/an/absolute/path",
* }
*
* We require() the fixture file and try to server-side render the
* component using each fixture found therein. jsPackages are the
* packages needed to render the component (including the package
* that defines the component!) topologically sorted so no package
* require()s anything from a package that comes after it.
*/
/* eslint-disable no-console */
const path = require("path");
const render = require("../src/render.js");
// Returns the number of errors found trying to render the component.
const validate = function(jsPackages, pathToReactComponent, fixtureFile) {
let allProps;
try {
const relativeFixturePath = path.relative(__dirname, fixtureFile);
allProps = require(relativeFixturePath).instances;
} catch (err) {
console.log(`Error reading fixtures from ${fixtureFile}: ${err}`);
return 1;
}
let numErrors = 0;
allProps.forEach((props, i) => {
try {
render(jsPackages, pathToReactComponent, props, 'ignore');
console.log(`${pathToReactComponent} #${i}: OK`);
} catch (err) {
console.log(`${pathToReactComponent} #${i}: ERROR: ${err}`);
numErrors++;
}
});
return numErrors;
};
const main = function(inputJson) {
let numErrors = 0;
inputJson.forEach((oneInput) => {
numErrors += validate(oneInput.jsPackages,
oneInput.pathToReactComponent,
oneInput.fixtureFile);
});
return numErrors;
};
let inputText = '';
process.stdin.on('data', function(chunk) {
inputText = inputText + chunk;
});
process.stdin.on('end', function() {
const inputJson = JSON.parse(inputText);
const numErrors = main(inputJson);
console.log('DONE');
process.exit(numErrors);
});
| Add a simple script to validate that a component can be server-side rendered. | Add a simple script to validate that a component can be server-side rendered.
This is intended for use with webapp's
react_util/server_side_render_test.py.
Auditors: jlfwong
Test Plan:
In webapp, ran
tools/runtests.py --max-size=large react_util/server_side_render_test.py
It completed successfully.
I then changed the cache policy in validate_components.js from
'ignore' to 'yes', and ran the test again, and saw it fail as so:
AssertionError: ./javascript/page-package/stateful-header.jsx #0: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/content-library-package/curation-page.jsx #0: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/content-library-package/curation-page.jsx #1: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/content-library-package/curation-page.jsx #2: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/content-library-package/curation-page.jsx #3: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/style-package/style-guide.jsx #0: ERROR: TypeError: Cannot read property 'get' of undefined
./javascript/about-package/alumni.jsx #0: ERROR: TypeError: Cannot read property 'get' of undefined
This shows that it is properly iterating over all the relevant
components and all their relevant fixtures. (The 'get' error is
because I never initialize the cache, so trying to use the cache
fails.)
| JavaScript | mit | Khan/react-render-server,Khan/react-render-server,Khan/react-render-server | ---
+++
@@ -0,0 +1,81 @@
+#!/usr/bin/env node
+
+'use strict';
+
+/**
+ * Validate that a given component can actually server-side render
+ * with the given properties (specified via a fixture file).
+ *
+ * Not all react components can be server-side rendered: they may
+ * use globals, or access the DOM, or what hafve you. This script
+ * can be used to validate that the component *can* be server-side
+ * rendered.
+ *
+ * The input is a bit difficult to construct: it's a json list of
+ * objects like so:
+ * {
+ * jsPackages: [[pkg_name, pkg_contents], [pkg_name, pkg_contents], ...],
+ * pathToReactComponent: "./in/require/format.js",
+ * fixtureFile: "/ideally/an/absolute/path",
+ * }
+ *
+ * We require() the fixture file and try to server-side render the
+ * component using each fixture found therein. jsPackages are the
+ * packages needed to render the component (including the package
+ * that defines the component!) topologically sorted so no package
+ * require()s anything from a package that comes after it.
+ */
+
+/* eslint-disable no-console */
+
+const path = require("path");
+
+const render = require("../src/render.js");
+
+
+// Returns the number of errors found trying to render the component.
+const validate = function(jsPackages, pathToReactComponent, fixtureFile) {
+ let allProps;
+ try {
+ const relativeFixturePath = path.relative(__dirname, fixtureFile);
+ allProps = require(relativeFixturePath).instances;
+ } catch (err) {
+ console.log(`Error reading fixtures from ${fixtureFile}: ${err}`);
+ return 1;
+ }
+
+ let numErrors = 0;
+ allProps.forEach((props, i) => {
+ try {
+ render(jsPackages, pathToReactComponent, props, 'ignore');
+ console.log(`${pathToReactComponent} #${i}: OK`);
+ } catch (err) {
+ console.log(`${pathToReactComponent} #${i}: ERROR: ${err}`);
+ numErrors++;
+ }
+ });
+ return numErrors;
+};
+
+
+const main = function(inputJson) {
+ let numErrors = 0;
+ inputJson.forEach((oneInput) => {
+ numErrors += validate(oneInput.jsPackages,
+ oneInput.pathToReactComponent,
+ oneInput.fixtureFile);
+ });
+ return numErrors;
+};
+
+
+let inputText = '';
+process.stdin.on('data', function(chunk) {
+ inputText = inputText + chunk;
+});
+process.stdin.on('end', function() {
+ const inputJson = JSON.parse(inputText);
+ const numErrors = main(inputJson);
+ console.log('DONE');
+ process.exit(numErrors);
+}); | |
cd3451286755bc73699f5a7263c7d783b7ca2594 | assets/js/stately.js | assets/js/stately.js | function toggleNav() {
nav = document.getElementsByClassName('js-side-nav');
navItems = document.getElementsByClassName('js-side-nav-item');
activeLink = document.getElementsByClassName('js-side-nav-link-active');
activeLink[0].addEventListener('click', function(event){
event.preventDefault();
toggleClasses();
});
function toggleClasses(){
el = nav[0];
className = 'open';
if (el.classList) {
el.classList.toggle(className);
} else {
var classes = el.className.split(' ');
var existingIndex = classes.indexOf(className);
if (existingIndex >= 0)
classes.splice(existingIndex, 1);
else
classes.push(className);
el.className = classes.join(' ');
}
}
}
// Document ready
var ready = function(){
// Handler when the DOM is fully loaded
toggleNav();
};
if (
document.readyState === "complete" ||
(document.readyState !== "loading" && !document.documentElement.doScroll)
) {
ready();
} else {
document.addEventListener("DOMContentLoaded", ready);
}
| Add js for mobile nav | Add js for mobile nav
| JavaScript | mit | pmarsceill/stately,pmarsceill/stately,pmarsceill/stately,pmarsceill/stately | ---
+++
@@ -0,0 +1,43 @@
+function toggleNav() {
+ nav = document.getElementsByClassName('js-side-nav');
+ navItems = document.getElementsByClassName('js-side-nav-item');
+ activeLink = document.getElementsByClassName('js-side-nav-link-active');
+
+ activeLink[0].addEventListener('click', function(event){
+ event.preventDefault();
+ toggleClasses();
+ });
+
+ function toggleClasses(){
+ el = nav[0];
+ className = 'open';
+
+ if (el.classList) {
+ el.classList.toggle(className);
+ } else {
+ var classes = el.className.split(' ');
+ var existingIndex = classes.indexOf(className);
+
+ if (existingIndex >= 0)
+ classes.splice(existingIndex, 1);
+ else
+ classes.push(className);
+ el.className = classes.join(' ');
+ }
+ }
+}
+
+// Document ready
+var ready = function(){
+ // Handler when the DOM is fully loaded
+ toggleNav();
+};
+
+if (
+ document.readyState === "complete" ||
+ (document.readyState !== "loading" && !document.documentElement.doScroll)
+) {
+ ready();
+} else {
+ document.addEventListener("DOMContentLoaded", ready);
+} | |
a90c0660ecd7b3b09d1e49afe58b8fccba9ae417 | webpack.config.js | webpack.config.js | module.exports = {
entry: './temp/react-components/app-main.js',
output: {
path: './build/js',
filename: 'react-app.js',
},
resolve: {
extensions: ['', '.js'],
},
module: {
loaders: [
{
test: /\.js$/,
loader: 'babel-loader',
exclude: '/node_modules/'
}
]
}
} | Add a webpack settings file. | Add a webpack settings file.
| JavaScript | mit | tom-konda/OSMNearbyNotesViewer,tom-konda/OSMNearbyNotesViewer,tom-konda/OSMNearbyNotesViewer | ---
+++
@@ -0,0 +1,19 @@
+module.exports = {
+ entry: './temp/react-components/app-main.js',
+ output: {
+ path: './build/js',
+ filename: 'react-app.js',
+ },
+ resolve: {
+ extensions: ['', '.js'],
+ },
+ module: {
+ loaders: [
+ {
+ test: /\.js$/,
+ loader: 'babel-loader',
+ exclude: '/node_modules/'
+ }
+ ]
+ }
+} | |
11ba2b6845f7d09d2d4542ef59b3add196a8eeed | src/ggrc/assets/javascripts/plugins/ggrc_utils.js | src/ggrc/assets/javascripts/plugins/ggrc_utils.js | /*!
Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
Created By: ivan@reciprocitylabs.com
Maintained By: ivan@reciprocitylabs.com
*/
(function($, GGRC) {
GGRC.Utils = {
getPickerElement: function (picker) {
return _.find(_.values(picker), function (val) {
if (val instanceof Node) {
return /picker\-dialog/.test(val.className);
}
return false;
});
}
};
})(jQuery, window.GGRC = window.GGRC || {});
| /*!
Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file>
Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
Created By: ivan@reciprocitylabs.com
Maintained By: ivan@reciprocitylabs.com
*/
(function($, GGRC) {
GGRC.Utils = {
getPickerElement: function (picker) {
return _.find(_.values(picker), function (val) {
if (val instanceof Node) {
return /picker\-dialog/.test(val.className);
}
return false;
});
},
download: function(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click();
document.body.removeChild(element);
},
};
})(jQuery, window.GGRC = window.GGRC || {});
| Add helper function for downloading files | Add helper function for downloading files
| JavaScript | apache-2.0 | edofic/ggrc-core,prasannav7/ggrc-core,AleksNeStu/ggrc-core,edofic/ggrc-core,prasannav7/ggrc-core,edofic/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,j0gurt/ggrc-core,jmakov/ggrc-core,hasanalom/ggrc-core,jmakov/ggrc-core,prasannav7/ggrc-core,andrei-karalionak/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,josthkko/ggrc-core,hyperNURb/ggrc-core,plamut/ggrc-core,hasanalom/ggrc-core,NejcZupec/ggrc-core,VinnieJohns/ggrc-core,hyperNURb/ggrc-core,andrei-karalionak/ggrc-core,edofic/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,kr41/ggrc-core,AleksNeStu/ggrc-core,selahssea/ggrc-core,VinnieJohns/ggrc-core,andrei-karalionak/ggrc-core,prasannav7/ggrc-core,plamut/ggrc-core,AleksNeStu/ggrc-core,hyperNURb/ggrc-core,NejcZupec/ggrc-core,kr41/ggrc-core,jmakov/ggrc-core,josthkko/ggrc-core,plamut/ggrc-core,selahssea/ggrc-core,andrei-karalionak/ggrc-core,josthkko/ggrc-core,j0gurt/ggrc-core,hasanalom/ggrc-core,AleksNeStu/ggrc-core,jmakov/ggrc-core,NejcZupec/ggrc-core,josthkko/ggrc-core,NejcZupec/ggrc-core,hyperNURb/ggrc-core,hasanalom/ggrc-core,VinnieJohns/ggrc-core,selahssea/ggrc-core,j0gurt/ggrc-core,plamut/ggrc-core | ---
+++
@@ -13,6 +13,15 @@
}
return false;
});
- }
+ },
+ download: function(filename, text) {
+ var element = document.createElement('a');
+ element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
+ element.setAttribute('download', filename);
+ element.style.display = 'none';
+ document.body.appendChild(element);
+ element.click();
+ document.body.removeChild(element);
+ },
};
})(jQuery, window.GGRC = window.GGRC || {}); |
d97a9a136c824c810a26fe4318849c7e86adf9a2 | generators/install/index.js | generators/install/index.js | (function() {
'use strict';
var yeoman = require('yeoman-generator'),
chalk = require('chalk');
module.exports = yeoman.generators.Base.extend({
constructor: function () {
yeoman.generators.Base.apply(this, arguments);
},
initializing: function() {
this.log(chalk.cyan('\t \t ___ __ __ _ _ '));
this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
this.log(chalk.cyan('\t \t \\__ \\/ _/ _` | _| _/ _ \\ / _` |'));
this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_| \n'));
this.log(chalk.cyan('\t \t [ Install Dependencies ] \n \n'));
this.log(chalk.green('I will install all NPM and Bower dependencies. This may take a while. Go grab a coffee! \n \n'));
},
install: function() {
var _this = this;
this.on('end', function() {
this.installDependencies({
skipInstall: _this.options.skipInstall,
callback: function() {
var command = _this.spawnCommand('npm', ['install', 'glob']);
command.on('exit', function() {
_this.log(chalk.cyan(' \n \n All done and no errors! Enjoy! \n \n'));
});
}
});
});
}
});
})();
| Create a task to install all dependencies | Create a task to install all dependencies
Including NPM and Bower
| JavaScript | mit | marcosmoura/generator-scaffold,marcosmoura/generator-scaffold | ---
+++
@@ -0,0 +1,42 @@
+(function() {
+
+ 'use strict';
+
+ var yeoman = require('yeoman-generator'),
+ chalk = require('chalk');
+
+ module.exports = yeoman.generators.Base.extend({
+
+ constructor: function () {
+ yeoman.generators.Base.apply(this, arguments);
+ },
+
+ initializing: function() {
+ this.log(chalk.cyan('\t \t ___ __ __ _ _ '));
+ this.log(chalk.cyan('\t \t / __| __ __ _ / _|/ _|___| |__| |'));
+ this.log(chalk.cyan('\t \t \\__ \\/ _/ _` | _| _/ _ \\ / _` |'));
+ this.log(chalk.cyan('\t \t |___/\\__\\__,_|_| |_| \\___/_\\__,_| \n'));
+ this.log(chalk.cyan('\t \t [ Install Dependencies ] \n \n'));
+ this.log(chalk.green('I will install all NPM and Bower dependencies. This may take a while. Go grab a coffee! \n \n'));
+ },
+
+ install: function() {
+ var _this = this;
+
+ this.on('end', function() {
+ this.installDependencies({
+ skipInstall: _this.options.skipInstall,
+ callback: function() {
+ var command = _this.spawnCommand('npm', ['install', 'glob']);
+
+ command.on('exit', function() {
+ _this.log(chalk.cyan(' \n \n All done and no errors! Enjoy! \n \n'));
+ });
+ }
+ });
+ });
+ }
+
+ });
+
+})(); | |
cd022534789370d1f444ae1bac55b6298f89f72b | src/app/controllers/MemoryController.js | src/app/controllers/MemoryController.js | (function () {
angular
.module('app')
.controller('MemoryController', [
MemoryController
]);
function MemoryController() {
var vm = this;
// TODO: move data to the service
vm.memoryChartData = [ {key: 'memory', y: 42}, { key: 'free', y: 58} ];
vm.chartOptions = {
chart: {
type: 'pieChart',
height: 210,
donut: true,
pie: {
startAngle: function (d) { return d.startAngle/2 -Math.PI/2 },
endAngle: function (d) { return d.endAngle/2 -Math.PI/2 }
},
x: function (d) { return d.key; },
y: function (d) { return d.y; },
valueFormat: (d3.format(".0f")),
color: ['rgb(0, 150, 136)', 'rgb(191, 191, 191)'],
showLabels: false,
showLegend: false,
tooltips: false,
title: '42%',
titleOffset: -10,
margin: { bottom: -80, left: -20, right: -20 }
}
};
}
})();
| Add a new controller for memory management. | Add a new controller for memory management.
| JavaScript | mit | happyboy171/DailyReportDashboard-Angluar-,happyboy171/DailyReportDashboard-Angluar- | ---
+++
@@ -0,0 +1,36 @@
+(function () {
+ angular
+ .module('app')
+ .controller('MemoryController', [
+ MemoryController
+ ]);
+
+ function MemoryController() {
+ var vm = this;
+
+ // TODO: move data to the service
+ vm.memoryChartData = [ {key: 'memory', y: 42}, { key: 'free', y: 58} ];
+
+ vm.chartOptions = {
+ chart: {
+ type: 'pieChart',
+ height: 210,
+ donut: true,
+ pie: {
+ startAngle: function (d) { return d.startAngle/2 -Math.PI/2 },
+ endAngle: function (d) { return d.endAngle/2 -Math.PI/2 }
+ },
+ x: function (d) { return d.key; },
+ y: function (d) { return d.y; },
+ valueFormat: (d3.format(".0f")),
+ color: ['rgb(0, 150, 136)', 'rgb(191, 191, 191)'],
+ showLabels: false,
+ showLegend: false,
+ tooltips: false,
+ title: '42%',
+ titleOffset: -10,
+ margin: { bottom: -80, left: -20, right: -20 }
+ }
+ };
+ }
+})(); | |
db43a1e083cbf65634a592d79f631757a733dc18 | tests/js/web/PopoverTest.js | tests/js/web/PopoverTest.js | /*jshint multistr: true */
'use strict'
var $ = require('jquery');
require('../../../js/libs/popover');
$.fx.off = !$.fx.off;
describe('Test extra functionality added to Bootstrap popovers', function() {
beforeEach(function() {
this.$html = $('<div id="html"></div>').appendTo('html');
this.$body = $('<div id="body"></div>').appendTo(this.$html);
this.$code = $(`
<button class="qa-alpha" data-toggle="popover" data-autoclose="true" title="Foo" data-content="Bar">Alpha</button>
<button class="qa-bravo" rel="clickover" title="Foo" data-content="Bar">Bravo</button>
`).appendTo(this.$body);
this.$domTarget = this.$html.find('#body');
this.$autoclosingPopover = this.$html.find('.qa-alpha');
this.$legacyClickover = this.$html.find('.qa-bravo');
$.fn.popover = sinon.stub().returnsThis();
});
afterEach(function() {
this.$html.remove();
delete $.fn.popover;
});
describe('Legacy clickovers', function() {
beforeEach(function() {
this.clickEvent = $.Event('click');
this.$legacyClickover.trigger(this.clickEvent);
});
it('should trigger a popover', function() {
expect($.fn.popover).to.have.been.called;
});
it('should hide the popover when clicked anywhere in the DOM', function (done) {
this.$domTarget.trigger(this.clickEvent);
setTimeout(() => {
expect($.fn.popover).to.have.been.calledWith('hide');
done();
}, 500);
});
});
describe('Autoclosing popovers', function() {
beforeEach(function() {
this.clickEvent = $.Event('click');
this.$autoclosingPopover.trigger(this.clickEvent);
});
it('should trigger a popover', function() {
expect($.fn.popover).to.have.been.called;
});
it('should hide the popover when clicked anywhere in the DOM', function (done) {
this.$domTarget.trigger(this.clickEvent);
setTimeout(() => {
expect($.fn.popover).to.have.been.calledWith('hide');
done();
}, 500);
});
});
});
| Test cases for clickover and autoclosing popovers | Test cases for clickover and autoclosing popovers
| JavaScript | mit | jadu/pulsar,jadu/pulsar,jadu/pulsar | ---
+++
@@ -0,0 +1,76 @@
+/*jshint multistr: true */
+
+'use strict'
+
+var $ = require('jquery');
+
+require('../../../js/libs/popover');
+
+$.fx.off = !$.fx.off;
+
+describe('Test extra functionality added to Bootstrap popovers', function() {
+
+ beforeEach(function() {
+ this.$html = $('<div id="html"></div>').appendTo('html');
+ this.$body = $('<div id="body"></div>').appendTo(this.$html);
+ this.$code = $(`
+ <button class="qa-alpha" data-toggle="popover" data-autoclose="true" title="Foo" data-content="Bar">Alpha</button>
+ <button class="qa-bravo" rel="clickover" title="Foo" data-content="Bar">Bravo</button>
+ `).appendTo(this.$body);
+
+ this.$domTarget = this.$html.find('#body');
+ this.$autoclosingPopover = this.$html.find('.qa-alpha');
+ this.$legacyClickover = this.$html.find('.qa-bravo');
+
+ $.fn.popover = sinon.stub().returnsThis();
+ });
+
+ afterEach(function() {
+ this.$html.remove();
+ delete $.fn.popover;
+ });
+
+ describe('Legacy clickovers', function() {
+
+ beforeEach(function() {
+ this.clickEvent = $.Event('click');
+ this.$legacyClickover.trigger(this.clickEvent);
+ });
+
+ it('should trigger a popover', function() {
+ expect($.fn.popover).to.have.been.called;
+ });
+
+ it('should hide the popover when clicked anywhere in the DOM', function (done) {
+ this.$domTarget.trigger(this.clickEvent);
+
+ setTimeout(() => {
+ expect($.fn.popover).to.have.been.calledWith('hide');
+ done();
+ }, 500);
+ });
+ });
+
+ describe('Autoclosing popovers', function() {
+
+ beforeEach(function() {
+ this.clickEvent = $.Event('click');
+ this.$autoclosingPopover.trigger(this.clickEvent);
+ });
+
+ it('should trigger a popover', function() {
+ expect($.fn.popover).to.have.been.called;
+ });
+
+ it('should hide the popover when clicked anywhere in the DOM', function (done) {
+ this.$domTarget.trigger(this.clickEvent);
+
+ setTimeout(() => {
+ expect($.fn.popover).to.have.been.calledWith('hide');
+ done();
+ }, 500);
+ });
+ });
+
+});
+ | |
b01b6c4652c98dc1bc584b70dfabdb3eb5d7265e | src/run/update/update-gitignore.spec.js | src/run/update/update-gitignore.spec.js | // import { expect } from 'chai'
// import updateGitignore from './update-gitignore'
describe('updateGitignore', () => {
describe('given the file does not exist', () => {
it('should create the .gitignore file')
})
describe('given the file exists and it doesn’t have any of Sagui’s entries', () => {
// Make sure example was not alphabetical to start with
it('should append Sagui entries without changing the order of the existing ones')
})
describe('given exists and has some Sagui entries', () => {
it('should append the missing ones with no duplicates')
})
})
| Add test skeleton for updateGitignore | Add test skeleton for updateGitignore
| JavaScript | mit | saguijs/sagui,saguijs/sagui | ---
+++
@@ -0,0 +1,17 @@
+// import { expect } from 'chai'
+// import updateGitignore from './update-gitignore'
+
+describe('updateGitignore', () => {
+ describe('given the file does not exist', () => {
+ it('should create the .gitignore file')
+ })
+
+ describe('given the file exists and it doesn’t have any of Sagui’s entries', () => {
+ // Make sure example was not alphabetical to start with
+ it('should append Sagui entries without changing the order of the existing ones')
+ })
+
+ describe('given exists and has some Sagui entries', () => {
+ it('should append the missing ones with no duplicates')
+ })
+}) | |
672d5080adae87f5269a4fcf2407f513a43852a9 | test/i18n-test/languageHandler-test.js | test/i18n-test/languageHandler-test.js | const React = require('react');
const expect = require('expect');
import * as languageHandler from '../../src/languageHandler';
const testUtils = require('../test-utils');
describe('languageHandler', function() {
let sandbox;
beforeEach(function(done) {
testUtils.beforeEach(this);
sandbox = testUtils.stubClient();
languageHandler.setLanguage('en').done(done);
});
afterEach(function() {
sandbox.restore();
});
it('translates a string to german', function() {
languageHandler.setLanguage('de').then(function() {
const translated = languageHandler._t('Rooms');
expect(translated).toBe('Räume');
});
});
it('handles plurals', function() {
var text = 'and %(count)s others...';
expect(languageHandler._t(text, { count: 1 })).toBe('and one other...');
expect(languageHandler._t(text, { count: 2 })).toBe('and 2 others...');
});
it('handles simple variable subsitutions', function() {
var text = 'You are now ignoring %(userId)s';
expect(languageHandler._t(text, { userId: 'foo' })).toBe('You are now ignoring foo');
});
it('handles simple tag substitution', function() {
var text = 'Press <StartChatButton> to start a chat with someone';
expect(languageHandler._t(text, {}, { 'StartChatButton': () => 'foo' })).toBe('Press foo to start a chat with someone');
});
it('handles text in tags', function() {
var text = '<a>Click here</a> to join the discussion!';
expect(languageHandler._t(text, {}, { 'a': (sub) => `x${sub}x` })).toBe('xClick herex to join the discussion!');
});
it('variable substitution with React component', function() {
// Need an extra space at the end because the result of _t() has an extra empty node at the end
var text = 'You are now ignoring %(userId)s ';
expect(JSON.stringify(languageHandler._t(text, { userId: () => <i>foo</i> }))).toBe(JSON.stringify((<span>You are now ignoring <i>foo</i> </span>)));
});
it('tag substitution with React component', function() {
var text = 'Press <StartChatButton> to start a chat with someone';
expect(JSON.stringify(languageHandler._t(text, {}, { 'StartChatButton': () => <i>foo</i> }))).toBe(JSON.stringify(<span>Press <i>foo</i> to start a chat with someone</span>));
});
});
| Add unit tests for translation | Add unit tests for translation
| JavaScript | apache-2.0 | matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,matrix-org/matrix-react-sdk,aperezdc/matrix-react-sdk,aperezdc/matrix-react-sdk,matrix-org/matrix-react-sdk | ---
+++
@@ -0,0 +1,60 @@
+const React = require('react');
+const expect = require('expect');
+import * as languageHandler from '../../src/languageHandler';
+
+const testUtils = require('../test-utils');
+
+describe('languageHandler', function() {
+ let sandbox;
+
+ beforeEach(function(done) {
+ testUtils.beforeEach(this);
+ sandbox = testUtils.stubClient();
+
+ languageHandler.setLanguage('en').done(done);
+ });
+
+ afterEach(function() {
+ sandbox.restore();
+ });
+
+ it('translates a string to german', function() {
+ languageHandler.setLanguage('de').then(function() {
+ const translated = languageHandler._t('Rooms');
+ expect(translated).toBe('Räume');
+ });
+ });
+
+ it('handles plurals', function() {
+ var text = 'and %(count)s others...';
+ expect(languageHandler._t(text, { count: 1 })).toBe('and one other...');
+ expect(languageHandler._t(text, { count: 2 })).toBe('and 2 others...');
+ });
+
+ it('handles simple variable subsitutions', function() {
+ var text = 'You are now ignoring %(userId)s';
+ expect(languageHandler._t(text, { userId: 'foo' })).toBe('You are now ignoring foo');
+ });
+
+ it('handles simple tag substitution', function() {
+ var text = 'Press <StartChatButton> to start a chat with someone';
+ expect(languageHandler._t(text, {}, { 'StartChatButton': () => 'foo' })).toBe('Press foo to start a chat with someone');
+ });
+
+ it('handles text in tags', function() {
+ var text = '<a>Click here</a> to join the discussion!';
+ expect(languageHandler._t(text, {}, { 'a': (sub) => `x${sub}x` })).toBe('xClick herex to join the discussion!');
+ });
+
+ it('variable substitution with React component', function() {
+ // Need an extra space at the end because the result of _t() has an extra empty node at the end
+ var text = 'You are now ignoring %(userId)s ';
+ expect(JSON.stringify(languageHandler._t(text, { userId: () => <i>foo</i> }))).toBe(JSON.stringify((<span>You are now ignoring <i>foo</i> </span>)));
+ });
+
+ it('tag substitution with React component', function() {
+ var text = 'Press <StartChatButton> to start a chat with someone';
+ expect(JSON.stringify(languageHandler._t(text, {}, { 'StartChatButton': () => <i>foo</i> }))).toBe(JSON.stringify(<span>Press <i>foo</i> to start a chat with someone</span>));
+
+ });
+}); | |
03aa28726bb2ecb0ef429d7693a36db20ec230f1 | test/integration/test-check-is-repo.js | test/integration/test-check-is-repo.js | 'use strict';
const FS = require('fs');
const Test = require('./include/runner');
const setUp = (context) => {
context.realRoot = context.dir('real-root');
context.realSubRoot = context.dir('real-root/foo');
context.fakeRoot = context.dir('fake-root');
return context.gitP(context.realRoot).init();
};
module.exports = {
'reports true for a real root': new Test(setUp, function (context, assert) {
const expected = true;
const git = context.gitP(context.realRoot);
return git.checkIsRepo()
.then((actual) => {
assert.equals(actual, expected, 'Should be a repo');
});
}),
'reports true for a child directory of a real root': new Test(setUp, function (context, assert) {
const expected = true;
const git = context.gitP(context.realSubRoot);
return git.checkIsRepo()
.then((actual) => {
assert.equals(actual, expected, 'Should be a repo');
});
}),
'reports false for a non-root': new Test(setUp, function (context, assert) {
const expected = false;
const git = context.gitP(context.fakeRoot);
return git.checkIsRepo()
.then((actual) => {
assert.equals(actual, expected, 'Should be a repo');
});
}),
};
| Add integration test for `checkIsRepo` | Add integration test for `checkIsRepo`
| JavaScript | mit | steveukx/git-js,steveukx/git-js | ---
+++
@@ -0,0 +1,46 @@
+'use strict';
+
+const FS = require('fs');
+const Test = require('./include/runner');
+
+const setUp = (context) => {
+
+ context.realRoot = context.dir('real-root');
+ context.realSubRoot = context.dir('real-root/foo');
+ context.fakeRoot = context.dir('fake-root');
+
+ return context.gitP(context.realRoot).init();
+};
+
+module.exports = {
+ 'reports true for a real root': new Test(setUp, function (context, assert) {
+ const expected = true;
+ const git = context.gitP(context.realRoot);
+
+ return git.checkIsRepo()
+ .then((actual) => {
+ assert.equals(actual, expected, 'Should be a repo');
+ });
+
+ }),
+
+ 'reports true for a child directory of a real root': new Test(setUp, function (context, assert) {
+ const expected = true;
+ const git = context.gitP(context.realSubRoot);
+
+ return git.checkIsRepo()
+ .then((actual) => {
+ assert.equals(actual, expected, 'Should be a repo');
+ });
+ }),
+
+ 'reports false for a non-root': new Test(setUp, function (context, assert) {
+ const expected = false;
+ const git = context.gitP(context.fakeRoot);
+
+ return git.checkIsRepo()
+ .then((actual) => {
+ assert.equals(actual, expected, 'Should be a repo');
+ });
+ }),
+}; | |
39d04a8af9c5a8dbe7b53c724395f47f7f9c7a37 | scripts/authorize.js | scripts/authorize.js | // authorize.js
//
// Get OAuth token
//
// Copyright 2011-2012, StatusNet Inc.
//
// 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.
var _ = require("underscore"),
Step = require("step"),
OAuth = require("oauth").OAuth,
config = require("./config"),
argv = require("optimist")
.usage("Usage: $0 -s <nickname>")
.alias("s", "server")
.alias("P", "port")
.describe("s", "Server name (default 'localhost')")
.describe("P", "Port (default 80)")
.default("P", 80)
.default("s", "localhost")
.argv,
server = argv.s,
port = argv.P,
cl,
oa,
rt;
if (!_.has(config, "hosts") || !_.has(config.hosts, server)) {
console.error("No client key for " + server);
process.exit(1);
}
cl = config.hosts[server];
oa = new OAuth("http://"+server+":"+port+"/oauth/request_token",
"http://"+server+":"+port+"/oauth/access_token",
cl.key,
cl.secret,
"1.0",
"oob",
"HMAC-SHA1",
null, // nonce size; use default
{"User-Agent": "activitypump-scripts/0.1.0"});
Step(
function() {
oa.getOAuthRequestToken(this);
},
function(err, token, secret) {
var url;
var callback = this;
var verifier = "";
if (err) throw err;
rt = {token: token, secret: secret};
url = "http://"+server+":"+port+"/oauth/authorize?oauth_token=" + rt.token;
console.log("Log in here: " + url);
console.log("Verifier: ");
process.stdin.resume();
process.stdin.setEncoding('utf8');
process.stdin.on('data', function (chunk) {
verifier = verifier + chunk;
});
process.stdin.on('end', function () {
process.stdin.pause();
callback(null, verifier);
});
},
function(err, verifier) {
if (err) throw err;
oa.getOAuthAccessToken(rt.token, rt.secret, verifier, this);
},
function(err, token, secret, res) {
if (err) {
console.error(err);
} else {
console.dir({
token: token,
secret: secret
});
}
}
);
| Add a script to do OAuth authorization | Add a script to do OAuth authorization
Closes #124.
| JavaScript | apache-2.0 | OpenSocial/pump.io,landsurveyorsunited/pump.io,e14n/pump.io,pump-io/pump.io,stephensekula/pump.io,gabrielsr/pump.io,profOnno/pump.io,strugee/pump.io,Acidburn0zzz/pump.io,e14n/pump.io,stephensekula/pump.io,profOnno/pump.io,gabrielsr/pump.io,pump-io/pump.io,stephensekula/pump.io,landsurveyorsunited/pump.io,Acidburn0zzz/pump.io,OpenSocial/pump.io,detrout/pump.io,grdryn/pump.io,grdryn/pump.io,detrout/pump.io,pump-io/pump.io,strugee/pump.io,e14n/pump.io | ---
+++
@@ -0,0 +1,94 @@
+// authorize.js
+//
+// Get OAuth token
+//
+// Copyright 2011-2012, StatusNet Inc.
+//
+// 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.
+
+var _ = require("underscore"),
+ Step = require("step"),
+ OAuth = require("oauth").OAuth,
+ config = require("./config"),
+ argv = require("optimist")
+ .usage("Usage: $0 -s <nickname>")
+ .alias("s", "server")
+ .alias("P", "port")
+ .describe("s", "Server name (default 'localhost')")
+ .describe("P", "Port (default 80)")
+ .default("P", 80)
+ .default("s", "localhost")
+ .argv,
+ server = argv.s,
+ port = argv.P,
+ cl,
+ oa,
+ rt;
+
+if (!_.has(config, "hosts") || !_.has(config.hosts, server)) {
+ console.error("No client key for " + server);
+ process.exit(1);
+}
+
+cl = config.hosts[server];
+
+oa = new OAuth("http://"+server+":"+port+"/oauth/request_token",
+ "http://"+server+":"+port+"/oauth/access_token",
+ cl.key,
+ cl.secret,
+ "1.0",
+ "oob",
+ "HMAC-SHA1",
+ null, // nonce size; use default
+ {"User-Agent": "activitypump-scripts/0.1.0"});
+
+Step(
+ function() {
+ oa.getOAuthRequestToken(this);
+ },
+ function(err, token, secret) {
+ var url;
+ var callback = this;
+ var verifier = "";
+ if (err) throw err;
+ rt = {token: token, secret: secret};
+ url = "http://"+server+":"+port+"/oauth/authorize?oauth_token=" + rt.token;
+ console.log("Log in here: " + url);
+ console.log("Verifier: ");
+ process.stdin.resume();
+ process.stdin.setEncoding('utf8');
+
+ process.stdin.on('data', function (chunk) {
+ verifier = verifier + chunk;
+ });
+
+ process.stdin.on('end', function () {
+ process.stdin.pause();
+ callback(null, verifier);
+ });
+ },
+ function(err, verifier) {
+ if (err) throw err;
+ oa.getOAuthAccessToken(rt.token, rt.secret, verifier, this);
+ },
+ function(err, token, secret, res) {
+ if (err) {
+ console.error(err);
+ } else {
+ console.dir({
+ token: token,
+ secret: secret
+ });
+ }
+ }
+); | |
2647204d86d2760902023ae1ee85777c9414fdee | tests/acceptance/sidebar-nav-test.js | tests/acceptance/sidebar-nav-test.js | import { test } from 'qunit';
import moduleForAcceptance from 'ember-api-docs/tests/helpers/module-for-acceptance';
moduleForAcceptance('Acceptance | sidebar navigation');
test('can navigate to namespace from sidebar', function(assert) {
visit('/ember/1.0.0');
click('.toc-level-1.namespaces a:contains(Ember.String)');
andThen(() => {
assert.equal(currentURL(), '/ember/1.0.0/namespaces/Ember.String', 'navigated to namespace');
});
});
test('can navigate to module from sidebar', function(assert) {
visit('/ember/1.0.0');
click('.toc-level-1.modules a:contains(application)');
andThen(() => {
assert.equal(currentURL(), '/ember/1.0.0/modules/application', 'navigated to module');
});
});
test('can navigate to class from sidebar', function(assert) {
visit('/ember/1.0.0');
click('.toc-level-1.classes a:contains(Ember.Component)');
andThen(() => {
assert.equal(currentURL(), '/ember/1.0.0/classes/Ember.Component', 'navigated to class');
});
});
| Add sidebar navigation acceptance tests | Add sidebar navigation acceptance tests
| JavaScript | mit | ember-learn/ember-api-docs,toddjordan/ember-api-docs,toddjordan/ember-api-docs,ember-learn/ember-api-docs,MartinMalinda/ember-api-docs,MartinMalinda/ember-api-docs | ---
+++
@@ -0,0 +1,32 @@
+import { test } from 'qunit';
+
+import moduleForAcceptance from 'ember-api-docs/tests/helpers/module-for-acceptance';
+
+moduleForAcceptance('Acceptance | sidebar navigation');
+
+test('can navigate to namespace from sidebar', function(assert) {
+ visit('/ember/1.0.0');
+ click('.toc-level-1.namespaces a:contains(Ember.String)');
+
+ andThen(() => {
+ assert.equal(currentURL(), '/ember/1.0.0/namespaces/Ember.String', 'navigated to namespace');
+ });
+});
+
+test('can navigate to module from sidebar', function(assert) {
+ visit('/ember/1.0.0');
+ click('.toc-level-1.modules a:contains(application)');
+
+ andThen(() => {
+ assert.equal(currentURL(), '/ember/1.0.0/modules/application', 'navigated to module');
+ });
+});
+
+test('can navigate to class from sidebar', function(assert) {
+ visit('/ember/1.0.0');
+ click('.toc-level-1.classes a:contains(Ember.Component)');
+
+ andThen(() => {
+ assert.equal(currentURL(), '/ember/1.0.0/classes/Ember.Component', 'navigated to class');
+ });
+}); | |
60318c6b3233fd04acd4a03592227b0591e318a7 | modules/rfNotifications.js | modules/rfNotifications.js | 'use strict';
module.exports = function(config, ircbot) {
let skipMessages = [];
ircbot.on('mqttMessage', function (topic, payload) {
if (topic !== config.topic) {
return;
}
const data = JSON.parse(payload.toString());
const matchingDevices = config.devices.filter(function(device) {
return device.protocol === data.protocol &&
device.numBits === data.numBits &&
device.value === data.value
});
for (const device of matchingDevices) {
const message = device.message;
if (skipMessages.indexOf(message) > -1) {
continue;
}
if (device.timeout) {
(function(message) {
setTimeout(function() {
skipMessages = skipMessages.filter(function(skipMessage) {
return skipMessage !== message;
});
}, device.timeout);
})(message);
skipMessages.push(message);
}
ircbot.notice(config.channel, message);
}
});
ircbot.emit('mqttSubscribe', config.topic);
};
| Add module for sending RF remote notifications | Add module for sending RF remote notifications
| JavaScript | mit | initLab/irc-notifier | ---
+++
@@ -0,0 +1,42 @@
+'use strict';
+
+module.exports = function(config, ircbot) {
+ let skipMessages = [];
+
+ ircbot.on('mqttMessage', function (topic, payload) {
+ if (topic !== config.topic) {
+ return;
+ }
+
+ const data = JSON.parse(payload.toString());
+ const matchingDevices = config.devices.filter(function(device) {
+ return device.protocol === data.protocol &&
+ device.numBits === data.numBits &&
+ device.value === data.value
+ });
+
+ for (const device of matchingDevices) {
+ const message = device.message;
+
+ if (skipMessages.indexOf(message) > -1) {
+ continue;
+ }
+
+ if (device.timeout) {
+ (function(message) {
+ setTimeout(function() {
+ skipMessages = skipMessages.filter(function(skipMessage) {
+ return skipMessage !== message;
+ });
+ }, device.timeout);
+ })(message);
+
+ skipMessages.push(message);
+ }
+
+ ircbot.notice(config.channel, message);
+ }
+ });
+
+ ircbot.emit('mqttSubscribe', config.topic);
+}; | |
c8d88707abd34a09fba85212dd54f1b8728e1c14 | material-ui/modules/channel-select.js | material-ui/modules/channel-select.js | import React from 'react'
import Subheader
from 'material-ui/lib/Subheader/Subheader'
import RadioButton
from 'material-ui/lib/radio-button'
import RadioButtonGroup
from 'material-ui/lib/radio-button-group'
export default class ChannelSelect extends React.Component {
render() {
const { onChange, channels } = this.props
return (
<div>
<Subheader style={{padding: 0}}>Channel</Subheader>
<RadioButtonGroup
name = 'Channel'
defaultSelected = 'auto'
onChange = {(e, i) => onChange('auto' == i ? i : channels[i])}>
<RadioButton
key = {'auto'}
value = {'auto'}
label = {'Auto select'}
/>
{channels.map((chan, i) => (
<RadioButton
key = {i}
value = {''+i}
label = {chan.id}
/>
))}
</RadioButtonGroup>
</div>
)
}
}
| Break out channel select functionality | Break out channel select functionality
| JavaScript | agpl-3.0 | FarmRadioHangar/fessbox,FarmRadioHangar/fessbox | ---
+++
@@ -0,0 +1,36 @@
+import React from 'react'
+
+import Subheader
+ from 'material-ui/lib/Subheader/Subheader'
+import RadioButton
+ from 'material-ui/lib/radio-button'
+import RadioButtonGroup
+ from 'material-ui/lib/radio-button-group'
+
+export default class ChannelSelect extends React.Component {
+ render() {
+ const { onChange, channels } = this.props
+ return (
+ <div>
+ <Subheader style={{padding: 0}}>Channel</Subheader>
+ <RadioButtonGroup
+ name = 'Channel'
+ defaultSelected = 'auto'
+ onChange = {(e, i) => onChange('auto' == i ? i : channels[i])}>
+ <RadioButton
+ key = {'auto'}
+ value = {'auto'}
+ label = {'Auto select'}
+ />
+ {channels.map((chan, i) => (
+ <RadioButton
+ key = {i}
+ value = {''+i}
+ label = {chan.id}
+ />
+ ))}
+ </RadioButtonGroup>
+ </div>
+ )
+ }
+} | |
df3824f5362934d85ce9fc8b295758abddb4afa5 | backend/test/utils.js | backend/test/utils.js | const mongo = require('mongodb')
const http = require('http')
/** (mongo.db -> Promise) -> () */
exports.mongo = function (action) {
mongo.MongoClient
.connect("mongodb://localhost:27017/hexode")
.then(db => {
action(db).catch(e => {
db.close()
throw e
})
})
.catch(e => { throw e })
}
/** Object -> Option(Object) -> Promise({ code, result }, error) */
exports.request = function (options, data) {
options = Object.assign({
hostname: 'localhost',
port: 8080,
method: 'GET',
headers: {
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'application/json'
}
}, options)
return new Promise(resolve => {
const req = http.request(options, res => {
var buf = ""
res.setEncoding('utf8')
res.on('data', b => { buf += b })
res.on('end', () => {
const result = JSON.parse(buf)
resolve({
code: res.statusCode,
result: result
})
})
})
req.on('error', e => { throw e })
data && req.write(JSON.stringify(data))
req.end()
})
}
| Create utility methods for testing | Create utility methods for testing
| JavaScript | mit | KtorZ/Hexode,KtorZ/Hexode,14Plumes/Hexode,14Plumes/Hexode,14Plumes/Hexode,KtorZ/Hexode | ---
+++
@@ -0,0 +1,45 @@
+const mongo = require('mongodb')
+const http = require('http')
+
+/** (mongo.db -> Promise) -> () */
+exports.mongo = function (action) {
+ mongo.MongoClient
+ .connect("mongodb://localhost:27017/hexode")
+ .then(db => {
+ action(db).catch(e => {
+ db.close()
+ throw e
+ })
+ })
+ .catch(e => { throw e })
+}
+
+/** Object -> Option(Object) -> Promise({ code, result }, error) */
+exports.request = function (options, data) {
+ options = Object.assign({
+ hostname: 'localhost',
+ port: 8080,
+ method: 'GET',
+ headers: {
+ 'X-Requested-With': 'XMLHttpRequest',
+ 'Content-Type': 'application/json'
+ }
+ }, options)
+ return new Promise(resolve => {
+ const req = http.request(options, res => {
+ var buf = ""
+ res.setEncoding('utf8')
+ res.on('data', b => { buf += b })
+ res.on('end', () => {
+ const result = JSON.parse(buf)
+ resolve({
+ code: res.statusCode,
+ result: result
+ })
+ })
+ })
+ req.on('error', e => { throw e })
+ data && req.write(JSON.stringify(data))
+ req.end()
+ })
+} | |
c12d4645964ae9fda0597dc83a2d8b7a7af41eb4 | 16/ffmpeg-toFormat-audio.js | 16/ffmpeg-toFormat-audio.js | var ffmpeg = require('fluent-ffmpeg');
var dirpath = 'video/';
var tmppath = 'tmp/';
var audio = 'testaudio-one.wav';
var videoname = 'output.avi';
var Command = new ffmpeg({ source: tmppath + videoname });
Command
.fromFormat('avi')
.withVideoCodec('libx264')
.withAudioCodec('libmp3lame')
.addInput(dirpath + audio)
.toFormat('mp4')
.on('error', function(err) {
console.log('An error occurred: ' + err.message);
})
.on('end', function() {
console.log('Processing finished !');
})
.saveToFile(tmppath + 'output_audio.mp4'); | Add the example to add the audio in the video file via ffmpeg. | Add the example to add the audio in the video file via ffmpeg.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,21 @@
+var ffmpeg = require('fluent-ffmpeg');
+
+var dirpath = 'video/';
+var tmppath = 'tmp/';
+var audio = 'testaudio-one.wav';
+var videoname = 'output.avi';
+var Command = new ffmpeg({ source: tmppath + videoname });
+
+Command
+ .fromFormat('avi')
+ .withVideoCodec('libx264')
+ .withAudioCodec('libmp3lame')
+ .addInput(dirpath + audio)
+ .toFormat('mp4')
+ .on('error', function(err) {
+ console.log('An error occurred: ' + err.message);
+ })
+ .on('end', function() {
+ console.log('Processing finished !');
+ })
+ .saveToFile(tmppath + 'output_audio.mp4'); | |
4dcb2db938a9c47b0902bd9253cd6e2ff7885628 | src/utils/throttle.js | src/utils/throttle.js | /**
* Throttle a function call.
*
* @description
* Function calls are delayed by `wait` milliseconds but at least every `wait`
* milliseconds a call is triggered.
*
* @param {functiom} func - Function to be debounced
* @param {number} wait - Number of milliseconds to debounce the function call.
* @param {boolean} immediate - If `true` function is not debounced.
* @return {functiomn} Throttled function.
*/
export default function throttle (func, wait = 250, immediate = false) {
let last;
let deferTimer;
const throttled = (...args) => {
const now = Date.now();
if (last && now < last + wait) {
clearTimeout(deferTimer);
deferTimer = setTimeout(() => {
last = now;
func(...args);
}, wait);
} else {
last = now;
func(...args);
}
};
return throttled;
}
| Add a util function for throttling | Add a util function for throttling
| JavaScript | mit | flekschas/hipiler,flekschas/hipiler,flekschas/hipiler | ---
+++
@@ -0,0 +1,34 @@
+/**
+ * Throttle a function call.
+ *
+ * @description
+ * Function calls are delayed by `wait` milliseconds but at least every `wait`
+ * milliseconds a call is triggered.
+ *
+ * @param {functiom} func - Function to be debounced
+ * @param {number} wait - Number of milliseconds to debounce the function call.
+ * @param {boolean} immediate - If `true` function is not debounced.
+ * @return {functiomn} Throttled function.
+ */
+export default function throttle (func, wait = 250, immediate = false) {
+ let last;
+ let deferTimer;
+
+ const throttled = (...args) => {
+ const now = Date.now();
+
+ if (last && now < last + wait) {
+ clearTimeout(deferTimer);
+
+ deferTimer = setTimeout(() => {
+ last = now;
+ func(...args);
+ }, wait);
+ } else {
+ last = now;
+ func(...args);
+ }
+ };
+
+ return throttled;
+} | |
a8fa754a1644e9cf4203275656acc97b82d954db | src/main/resources/scripts/create-index.js | src/main/resources/scripts/create-index.js | db.apis.createIndex( { "visibility" : 1 } );
db.apis.createIndex( { "group" : 1 } );
db.applications.createIndex( { "group" : 1 } );
db.events.createIndex( { "type" : 1 } );
db.events.createIndex( { "updatedAt" : 1 } );
db.events.createIndex( { "properties.api_id" : 1 } );
db.plans.createIndex( { "apis" : 1 } );
db.subscriptions.createIndex( { "plan" : 1 } );
db.subscriptions.createIndex( { "application" : 1 } );
db.keys.createIndex( { "plan" : 1 } );
db.keys.createIndex( { "application" : 1 } );
db.pages.createIndex( { "api" : 1 } );
db.apis.reIndex();
db.applications.reIndex();
db.events.reIndex();
db.plans.reIndex();
db.subscriptions.reIndex();
db.keys.reIndex();
db.pages.reIndex(); | Add index script for better performances | chore: Add index script for better performances
| JavaScript | apache-2.0 | gravitee-io/gravitee-repository-mongodb,gravitee-io/gravitee-repository-mongodb | ---
+++
@@ -0,0 +1,20 @@
+db.apis.createIndex( { "visibility" : 1 } );
+db.apis.createIndex( { "group" : 1 } );
+db.applications.createIndex( { "group" : 1 } );
+db.events.createIndex( { "type" : 1 } );
+db.events.createIndex( { "updatedAt" : 1 } );
+db.events.createIndex( { "properties.api_id" : 1 } );
+db.plans.createIndex( { "apis" : 1 } );
+db.subscriptions.createIndex( { "plan" : 1 } );
+db.subscriptions.createIndex( { "application" : 1 } );
+db.keys.createIndex( { "plan" : 1 } );
+db.keys.createIndex( { "application" : 1 } );
+db.pages.createIndex( { "api" : 1 } );
+
+db.apis.reIndex();
+db.applications.reIndex();
+db.events.reIndex();
+db.plans.reIndex();
+db.subscriptions.reIndex();
+db.keys.reIndex();
+db.pages.reIndex(); | |
e019bcbfdd568030176442731c10fc8b970cda59 | array.ptototypes.js | array.ptototypes.js | Array.prototype.remove = function(from, to) {
var rest = this.slice((to || from) + 1 || this.length);
this.length = from < 0 ? this.length + from : from;
return this.push.apply(this, rest);
};
| Create new feature, add array prototypes | Create new feature, add array prototypes
Create new feature, add array prototypes | JavaScript | mit | christianjames/js-commons | ---
+++
@@ -0,0 +1,5 @@
+Array.prototype.remove = function(from, to) {
+ var rest = this.slice((to || from) + 1 || this.length);
+ this.length = from < 0 ? this.length + from : from;
+ return this.push.apply(this, rest);
+}; | |
0e0a526d4d7d584481fca46c551efee49aaf0c40 | js/es6-playground/08-1-golden-ratio.js | js/es6-playground/08-1-golden-ratio.js | // es6 generators example
// "The Goden Ration" (phi) approximation using fibonacci numbers
const MAX_APPROX = 100;
function* fib(x, y) {
for (let i = 0; i < MAX_APPROX; i++) {
[x, y] = [y, x + y];
yield y;
}
};
let prev = 1;
for (let n of fib(0, 1)) {
if (prev > 1) {
phi = n / parseFloat(prev);
console.log(`PHI = ${phi} [ITER ${n}]`);
}
prev = n;
}
| Add a golden ratio approximation using fibonacci numbers and es6 generators | Add a golden ratio approximation using fibonacci numbers and es6 generators
| JavaScript | mit | petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox | ---
+++
@@ -0,0 +1,20 @@
+// es6 generators example
+// "The Goden Ration" (phi) approximation using fibonacci numbers
+
+const MAX_APPROX = 100;
+
+function* fib(x, y) {
+ for (let i = 0; i < MAX_APPROX; i++) {
+ [x, y] = [y, x + y];
+ yield y;
+ }
+};
+
+let prev = 1;
+for (let n of fib(0, 1)) {
+ if (prev > 1) {
+ phi = n / parseFloat(prev);
+ console.log(`PHI = ${phi} [ITER ${n}]`);
+ }
+ prev = n;
+} | |
dc366d1418662d3ef3b473250210dc38c71098b9 | test/models/botTest.js | test/models/botTest.js | var chai = require('chai');
var expect = chai.expect; // we are using the "expect" style of Chai
var Bot = require('./../../models/bot');
describe('Bot', function() {
it('Bot() create new bot object with default value', function() {
var newBot = Bot({
name: 'Toto',
zone: {
coordinates: [[8.086, 3.455], [7.546, 5.558]]
}
});
expect(newBot.name).to.equal('Toto');
expect(newBot.zone.type).to.equal('Polygon');
// expect(newBot.zone.coordinates).to.deep.members([[8.086, 3.455], [7.546, 5.558]]);
expect(newBot.active).to.equal(true);
expect(newBot.nb_driver).to.equal(1);
expect(newBot.api_key).to.equal(undefined);
expect(newBot.json_to_send).to.equal(undefined);
expect(newBot.header_to_send).to.equal(undefined);
expect(newBot.url).to.equal(undefined);
expect(newBot.http_method).to.equal(undefined);
expect(newBot.speed).to.equal(30);
expect(newBot.precision).to.equal(20);
});
});
| Add Test for Bot model | Add Test for Bot model
| JavaScript | mit | Ecotaco/bumblebee-bot,Ecotaco/bumblebee-bot | ---
+++
@@ -0,0 +1,27 @@
+var chai = require('chai');
+var expect = chai.expect; // we are using the "expect" style of Chai
+var Bot = require('./../../models/bot');
+
+describe('Bot', function() {
+ it('Bot() create new bot object with default value', function() {
+ var newBot = Bot({
+ name: 'Toto',
+ zone: {
+ coordinates: [[8.086, 3.455], [7.546, 5.558]]
+ }
+ });
+
+ expect(newBot.name).to.equal('Toto');
+ expect(newBot.zone.type).to.equal('Polygon');
+ // expect(newBot.zone.coordinates).to.deep.members([[8.086, 3.455], [7.546, 5.558]]);
+ expect(newBot.active).to.equal(true);
+ expect(newBot.nb_driver).to.equal(1);
+ expect(newBot.api_key).to.equal(undefined);
+ expect(newBot.json_to_send).to.equal(undefined);
+ expect(newBot.header_to_send).to.equal(undefined);
+ expect(newBot.url).to.equal(undefined);
+ expect(newBot.http_method).to.equal(undefined);
+ expect(newBot.speed).to.equal(30);
+ expect(newBot.precision).to.equal(20);
+ });
+}); | |
6b36600a699a0de95573ccf062e5f9a0a9c2cc6f | test/thriftHostPool.js | test/thriftHostPool.js | /**
* Runs tests defined in thrift.js, but with ConnectionPool
* option hostPoolSize set to 5.
*/
var config = require('./helpers/thrift'),
system = require('./helpers/connection'),
thriftTest = require('./thrift'),
Helenus, conn, ks, cf_standard, row_standard, cf_composite, cf_counter;
system.hostPoolSize = 5;
module.exports = thriftTest;
| Test suite for ConnectionPools that use hostPoolSize option. | Test suite for ConnectionPools that use hostPoolSize option.
Re-runs the existing thrift.js test suite, but sets the
hostPoolSize option before starting.
| JavaScript | mit | lyveminds/scamandrios | ---
+++
@@ -0,0 +1,13 @@
+/**
+ * Runs tests defined in thrift.js, but with ConnectionPool
+ * option hostPoolSize set to 5.
+ */
+var config = require('./helpers/thrift'),
+ system = require('./helpers/connection'),
+ thriftTest = require('./thrift'),
+ Helenus, conn, ks, cf_standard, row_standard, cf_composite, cf_counter;
+
+system.hostPoolSize = 5;
+
+module.exports = thriftTest;
+ | |
48c74e8ad82fcfa58b46b384048c47265121cee4 | code/js/controllers/YandexController.js | code/js/controllers/YandexController.js | ;(function() {
"use strict";
require("BaseController").init({
siteName: "Yandex",
playPause: ".player-controls__btn_play",
playNext: ".player-controls__btn_next",
playPrev: ".player-controls__btn_prev",
mute: ".volume__icon",
like: ".player-controls .icon_like",
dislike: ".player-controls .icon_like_on",
song: ".track__title",
artist: ".track__artists"
});
})();
| ;(function() {
"use strict";
require("BaseController").init({
siteName: "Yandex",
playPause: ".player-controls__btn_play",
playNext: ".player-controls__btn_next",
playPrev: ".player-controls__btn_prev",
mute: ".volume__icon",
like: ".player-controls .icon_like",
dislike: ".player-controls .icon_like_on",
song: ".player-controls .track__title",
artist: ".player-controls .track__artists"
});
})();
| Fix current track selectors for Yandex | Fix current track selectors for Yandex | JavaScript | mit | nemchik/streamkeys,berrberr/streamkeys,berrberr/streamkeys,ovcharik/streamkeys,ovcharik/streamkeys,nemchik/streamkeys,alexesprit/streamkeys,berrberr/streamkeys,nemchik/streamkeys,alexesprit/streamkeys | ---
+++
@@ -10,7 +10,7 @@
like: ".player-controls .icon_like",
dislike: ".player-controls .icon_like_on",
- song: ".track__title",
- artist: ".track__artists"
+ song: ".player-controls .track__title",
+ artist: ".player-controls .track__artists"
});
})(); |
65792cdafa5930d653bd93ba49e08da4581b4a5b | app/assets/javascripts/application.js | app/assets/javascripts/application.js | // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require leaflet
//= require_tree .
| // This is a manifest file that'll be compiled into application.js, which will include all the files
// listed below.
//
// Any JavaScript/Coffee file within this directory, lib/assets/javascripts, vendor/assets/javascripts,
// or vendor/assets/javascripts of plugins, if any, can be referenced here using a relative path.
//
// It's not advisable to add code directly here, but if you do, it'll appear at the bottom of the
// compiled file.
//
// WARNING: THE FIRST BLANK LINE MARKS THE END OF WHAT'S TO BE PROCESSED, ANY BLANK LINE SHOULD
// GO AFTER THE REQUIRES BELOW.
//
//= require jquery
//= require jquery_ujs
//= require turbolinks
//= require leaflet
//= require_tree .
// Make a JSON representation of the Rails object available to the page
$.getJSON(document.URL, success = function(successObject) { json_representation = successObject; console.log(successObject) } );
| Make a JSON representation of the page's object available to the JS | Make a JSON representation of the page's object available to the JS
| JavaScript | mit | daguar/cityvoice,ajb/cityvoice,ajb/cityvoice,codeforamerica/cityvoice,codeforgso/cityvoice,daguar/cityvoice,daguar/cityvoice,codeforgso/cityvoice,daguar/cityvoice,ajb/cityvoice,codeforamerica/cityvoice,codeforgso/cityvoice,ajb/cityvoice,codeforgso/cityvoice,codeforamerica/cityvoice,codeforamerica/cityvoice | ---
+++
@@ -15,3 +15,7 @@
//= require turbolinks
//= require leaflet
//= require_tree .
+
+// Make a JSON representation of the Rails object available to the page
+$.getJSON(document.URL, success = function(successObject) { json_representation = successObject; console.log(successObject) } );
+ |
b9b61a56057dadd5f61015bc2e1cf880c653758b | tests.js | tests.js | const assert = require('assert')
const CNJokes = require('./index.js')
describe('get chucknorris joke', function() {
it('should return random joke', function() {
});
it('should return count jokes', function() {
});
it('should return random jokes', function() {
});
it('should return categories', function() {
});
});
| Add skeleton file for test | Add skeleton file for test
| JavaScript | mit | muhtarudinsiregar/chucknorris-quotes | ---
+++
@@ -0,0 +1,20 @@
+const assert = require('assert')
+const CNJokes = require('./index.js')
+
+describe('get chucknorris joke', function() {
+ it('should return random joke', function() {
+
+ });
+
+ it('should return count jokes', function() {
+
+ });
+
+ it('should return random jokes', function() {
+
+ });
+
+ it('should return categories', function() {
+
+ });
+}); | |
8ab948ab0133d3caba52fc770779bc2cc9c309ae | cypress/integration/home.spec.js | cypress/integration/home.spec.js | /**
* Copyright (C) 2019 The Software Heritage developers
* See the AUTHORS file at the top-level directory of this distribution
* License: GNU Affero General Public License version 3, or any later version
* See top-level LICENSE file for more information
*/
const url = '/';
const $ = Cypress.$;
describe('Home Page Tests', function() {
it('should display positive stats for each category', function() {
cy.visit(url);
cy.get('.swh-counter')
.then((counters) => {
for(let counter of counters) {
let innerText = $(counter).text();
const value = parseInt(innerText.replace(/,/g, ''));
assert.isAbove(value, 0);
}
});
})
})
| Add tests for Home Page | Add tests for Home Page
| JavaScript | agpl-3.0 | SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui,SoftwareHeritage/swh-web-ui | ---
+++
@@ -0,0 +1,24 @@
+/**
+ * Copyright (C) 2019 The Software Heritage developers
+ * See the AUTHORS file at the top-level directory of this distribution
+ * License: GNU Affero General Public License version 3, or any later version
+ * See top-level LICENSE file for more information
+ */
+
+const url = '/';
+
+const $ = Cypress.$;
+
+describe('Home Page Tests', function() {
+ it('should display positive stats for each category', function() {
+ cy.visit(url);
+ cy.get('.swh-counter')
+ .then((counters) => {
+ for(let counter of counters) {
+ let innerText = $(counter).text();
+ const value = parseInt(innerText.replace(/,/g, ''));
+ assert.isAbove(value, 0);
+ }
+ });
+ })
+}) | |
0b4aa3f1c267e2d75220334375123e47a14530c3 | examples/simple-calls.js | examples/simple-calls.js | "use strict";
var Q = require("../q");
function log() {
console.log.apply(console, arguments);
}
Q("----------- tick 1 -----------").done(log); // next tick
Q().thenResolve("----------- tick 2 -----------").done(log); // in 2 ticks
Q().thenResolve().thenResolve("----------- tick 3 -----------").done(log); // in 3 ticks
Q(1).then(log).done(); //logs "1"
Q().thenResolve(2).done(log); //logs "2"
Q(5).then(Q.fbind(log, 3, 4)).done(); //logs "3 4 5"
Q(log).fapply([6, 7, 8]).done(); //logs "6 7 8"
Q(log).fcall(9, 10, 11).done(); //logs "9 10 11"
Q.try(log, 12, 13).done(); //logs "12, 13" (same as fcall)
log("----------- tick 0 -----------"); //called this tick
| Add a simple example demonstrating ticks and calls. | Add a simple example demonstrating ticks and calls.
| JavaScript | mit | STRd6/q,kevinsawicki/q | ---
+++
@@ -0,0 +1,27 @@
+"use strict";
+
+var Q = require("../q");
+
+function log() {
+ console.log.apply(console, arguments);
+}
+
+Q("----------- tick 1 -----------").done(log); // next tick
+Q().thenResolve("----------- tick 2 -----------").done(log); // in 2 ticks
+Q().thenResolve().thenResolve("----------- tick 3 -----------").done(log); // in 3 ticks
+
+
+Q(1).then(log).done(); //logs "1"
+
+Q().thenResolve(2).done(log); //logs "2"
+
+Q(5).then(Q.fbind(log, 3, 4)).done(); //logs "3 4 5"
+
+Q(log).fapply([6, 7, 8]).done(); //logs "6 7 8"
+
+Q(log).fcall(9, 10, 11).done(); //logs "9 10 11"
+
+Q.try(log, 12, 13).done(); //logs "12, 13" (same as fcall)
+
+
+log("----------- tick 0 -----------"); //called this tick | |
311c2c5f95b68e68d03e48f84d7d3999dff9f943 | config/env/all.js | config/env/all.js | 'use strict';
module.exports = {
assets: {
lib: {
css: [
'lib/bootstrap/dist/css/bootstrap.css',
'lib/bootstrap/dist/css/bootstrap-theme.css',
'lib/font-awesome/css/font-awesome.css'
],
js: [
'lib/angular/angular.js',
'lib/angular-resource/angular-resource.js',
'lib/angular-cookies/angular-cookies.js',
'lib/angular-animate/angular-animate.js',
'lib/angular-touch/angular-touch.js',
'lib/angular-sanitize/angular-sanitize.js',
'lib/angular-ui-router/release/angular-ui-router.js',
'lib/angular-ui-utils/ui-utils.js',
'lib/angular-bootstrap/ui-bootstrap-tpls.js',
'lib/angular-breadcrumb/release/angular-breadcrumb.js'
]
},
css: [
'modules/**/css/*.css',
'dashboard.css'
],
js: [
'config.js',
'application.js',
'modules/*/*.js',
'modules/*/*[!tests]*/*.js'
],
tests: [
'lib/angular-mocks/angular-mocks.js',
'modules/*/tests/*.js'
]
}
}; | 'use strict';
module.exports = {
assets: {
lib: {
css: [
'lib/bootstrap/dist/css/bootstrap.css',
'lib/bootstrap/dist/css/bootstrap-theme.css',
'lib/font-awesome/css/font-awesome.css'
],
js: [
'lib/angular/angular.js',
'lib/angular-resource/angular-resource.js',
'lib/angular-cookies/angular-cookies.js',
'lib/angular-animate/angular-animate.js',
'lib/angular-touch/angular-touch.js',
'lib/angular-sanitize/angular-sanitize.js',
'lib/angular-ui-router/release/angular-ui-router.js',
'lib/angular-ui-utils/ui-utils.js',
'lib/angular-bootstrap/ui-bootstrap-tpls.js',
'lib/angular-breadcrumb/release/angular-breadcrumb.js',
'lib/angular-xeditable/dist/js/xeditable.js'
]
},
css: [
'modules/**/css/*.css',
'dashboard.css'
],
js: [
'config.js',
'application.js',
'modules/*/*.js',
'modules/*/*[!tests]*/*.js'
],
tests: [
'lib/angular-mocks/angular-mocks.js',
'modules/*/tests/*.js'
]
}
}; | Fix the dependencies of set os unit tests | Fix the dependencies of set os unit tests
| JavaScript | apache-2.0 | rsdevigo/jungle,michelazzo/jungle,rsdevigo/jungle,michelazzo/jungle,rsdevigo/jungle,michelazzo/jungle | ---
+++
@@ -18,7 +18,8 @@
'lib/angular-ui-router/release/angular-ui-router.js',
'lib/angular-ui-utils/ui-utils.js',
'lib/angular-bootstrap/ui-bootstrap-tpls.js',
- 'lib/angular-breadcrumb/release/angular-breadcrumb.js'
+ 'lib/angular-breadcrumb/release/angular-breadcrumb.js',
+ 'lib/angular-xeditable/dist/js/xeditable.js'
]
},
css: [ |
a1213cc2610424e7cfeb010f706fe252f3c1d889 | lib/fullscreen-class.js | lib/fullscreen-class.js | (function () {
/**
* Monkey patch to apply a 'fullscreen' class to A-Frame scenes in fullscreen
* mode. Allows overlay content to be hidden in iOS Safari, which doesn't
* have an actual fullscreen API.
*/
document.addEventListener('DOMContentLoaded', function () {
var scene = document.querySelector('a-scene');
scene.addEventListener('fullscreen-enter', function () {
scene.classList.add('fullscreen');
});
scene.addEventListener('fullscreen-enter', function () {
scene.classList.remove('fullscreen');
});
});
}());
| Add fullscreen class to scenes. | Add fullscreen class to scenes.
Affects #4 but won't work until A-Frame v0.2.0
| JavaScript | mit | polats/aframe-polats-extras,donmccurdy/sandbox-aframe,polats/aframe-polats-extras,donmccurdy/aframe-extras | ---
+++
@@ -0,0 +1,18 @@
+(function () {
+
+ /**
+ * Monkey patch to apply a 'fullscreen' class to A-Frame scenes in fullscreen
+ * mode. Allows overlay content to be hidden in iOS Safari, which doesn't
+ * have an actual fullscreen API.
+ */
+ document.addEventListener('DOMContentLoaded', function () {
+ var scene = document.querySelector('a-scene');
+ scene.addEventListener('fullscreen-enter', function () {
+ scene.classList.add('fullscreen');
+ });
+ scene.addEventListener('fullscreen-enter', function () {
+ scene.classList.remove('fullscreen');
+ });
+ });
+
+}()); | |
b349d65a9da023260414c6fcd6d6c468aabeb948 | spec/core-clone-spec.js | spec/core-clone-spec.js | 'use strict';
// const tmp = require('tmp');
// // Mine
// const core = require('../lib/core');
// const fsX = require('../lib/fsExtra');
// const util = require('../lib/util');
// //
// const cc = require('./core-common');
// function quietDoFor(internalOptions, cmd, args) {
// // Classic use of mute, suppress output from (our own) module that does not support it!
// const unmute = util.recursiveMute();
// try {
// core.doForEach(internalOptions, cmd, args);
// unmute();
// } catch (err) {
// unmute();
// throw err;
// }
// }
describe('core clone:', () => {
it('test goes here', () => {
pending('test goes here');
});
});
| Add placeholder for clone unit tests | Add placeholder for clone unit tests
| JavaScript | mit | JohnRGee/forest-arborist,JohnRGee/forest-arborist,JohnRGee/arm | ---
+++
@@ -0,0 +1,29 @@
+'use strict';
+
+// const tmp = require('tmp');
+// // Mine
+// const core = require('../lib/core');
+// const fsX = require('../lib/fsExtra');
+// const util = require('../lib/util');
+// //
+// const cc = require('./core-common');
+
+
+// function quietDoFor(internalOptions, cmd, args) {
+// // Classic use of mute, suppress output from (our own) module that does not support it!
+// const unmute = util.recursiveMute();
+// try {
+// core.doForEach(internalOptions, cmd, args);
+// unmute();
+// } catch (err) {
+// unmute();
+// throw err;
+// }
+// }
+
+
+describe('core clone:', () => {
+ it('test goes here', () => {
+ pending('test goes here');
+ });
+}); | |
fb040cb36a177198aba7cf3cdc82c5d0bbd05158 | test/testMultipleNotifications.js | test/testMultipleNotifications.js | var mercurius = require('../index.js');
var request = require('supertest');
var assert = require('assert');
var nock = require('nock');
describe('mercurius', function() {
var token;
before(function(done) {
mercurius.ready.then(function() {
request(mercurius.app)
.post('/register')
.send({
machineId: 'machineX',
endpoint: 'https://localhost:50005',
key: 'key',
})
.expect(function(res) {
token = res.text;
})
.end(done);
});
});
it('sends notifications to multiple machines of a registered user', function(done) {
nock('https://localhost:50006')
.post('/')
.reply(201);
nock('https://localhost:50005')
.post('/')
.reply(201);
request(mercurius.app)
.post('/register')
.send({
token: token,
machineId: 'machine2',
endpoint: 'https://localhost:50006',
key: 'key',
})
.expect(200, function(res) {
request(mercurius.app)
.post('/notify')
.send({
token: token,
})
.expect(200, done);
});
});
it('returns `500` if there\'s a failure in sending a notifications to one of the machines of a registered user', function(done) {
nock('https://localhost:50006')
.post('/')
.reply(201);
nock('https://localhost:50005')
.post('/')
.reply(404);
request(mercurius.app)
.post('/notify')
.send({
token: token,
})
.expect(500, done);
});
});
| Test multiple notifications failure case | Test multiple notifications failure case
| JavaScript | apache-2.0 | zalun/mercurius,marco-c/mercurius,marco-c/mercurius,marco-c/mercurius,zalun/mercurius | ---
+++
@@ -0,0 +1,68 @@
+var mercurius = require('../index.js');
+var request = require('supertest');
+var assert = require('assert');
+var nock = require('nock');
+
+describe('mercurius', function() {
+ var token;
+
+ before(function(done) {
+ mercurius.ready.then(function() {
+ request(mercurius.app)
+ .post('/register')
+ .send({
+ machineId: 'machineX',
+ endpoint: 'https://localhost:50005',
+ key: 'key',
+ })
+ .expect(function(res) {
+ token = res.text;
+ })
+ .end(done);
+ });
+ });
+
+ it('sends notifications to multiple machines of a registered user', function(done) {
+ nock('https://localhost:50006')
+ .post('/')
+ .reply(201);
+
+ nock('https://localhost:50005')
+ .post('/')
+ .reply(201);
+
+ request(mercurius.app)
+ .post('/register')
+ .send({
+ token: token,
+ machineId: 'machine2',
+ endpoint: 'https://localhost:50006',
+ key: 'key',
+ })
+ .expect(200, function(res) {
+ request(mercurius.app)
+ .post('/notify')
+ .send({
+ token: token,
+ })
+ .expect(200, done);
+ });
+ });
+
+ it('returns `500` if there\'s a failure in sending a notifications to one of the machines of a registered user', function(done) {
+ nock('https://localhost:50006')
+ .post('/')
+ .reply(201);
+
+ nock('https://localhost:50005')
+ .post('/')
+ .reply(404);
+
+ request(mercurius.app)
+ .post('/notify')
+ .send({
+ token: token,
+ })
+ .expect(500, done);
+ });
+}); | |
3b0d98edfc605f68d5cee7caba581b4a40abad66 | Toggl/WeeklyReport.user.js | Toggl/WeeklyReport.user.js | // ==UserScript==
// @name Toggl - Weekly report
// @namespace https://github.com/fabiencrassat
// @version 0.1
// @description Calculate and display the work day percentages
// @author Fabien Crassat <fabien@crassat.com>
// @include /^https:\/\/toggl\.com\/app\/reports\/weekly\/\d+\/period\/thisWeek/
// @grant none
// ==/UserScript==
/** global: $, console */
(function() {
'use strict';
const weekDaysPlusTotal = [0, 1, 2, 3, 4, 5, 6, 7];
const urlToFollow = "https://toggl.com/reports/api/v2/weekly.json";
const displayLinesSelector = "table.data-table tr:not(:first, .subgroup, :last)";
const displayColumnsSelector = "td[class^='day-'], td.col-total";
const decimalLenght = 3;
const textToJsonObject = function(text) {
if (!text) return {};
const obj = JSON.parse(text);
return obj;
};
const percentage = function(numerator, denumerator) {
if (!numerator || !denumerator || denumerator === 0) return 0;
return (numerator / denumerator);
};
const extractOneDay = function(data, dayNumber, totalDay) {
var dataDay = [];
data.forEach(function(dataLine) {
dataDay.push(percentage(dataLine.totals[dayNumber], totalDay));
});
return dataDay;
};
const main = function(weeklyData) {
// Calculate
var dataDaysPlusTotal = [];
weekDaysPlusTotal.forEach(function(dayOrTotal, index) {
dataDaysPlusTotal.push(extractOneDay(weeklyData.data, index, weeklyData.week_totals[index]));
});
// Display
const displayLines = $(displayLinesSelector);
if (!displayLines || displayLines.length !== dataDaysPlusTotal[0].length) {
console.warn("There is not the same calculated and display lines.");
return;
}
displayLines.each(function(indexLine) {
const element = $(this).find(displayColumnsSelector);
element.each(function(indexColumn) {
const dataInCeil = dataDaysPlusTotal[indexColumn][displayLines.length - indexLine - 1];
$(this).append("<p>" + dataInCeil.toFixed(decimalLenght) + "</p>");
});
});
};
const origOpen = XMLHttpRequest.prototype.open;
XMLHttpRequest.prototype.open = function() {
this.addEventListener('load', function() {
if (this.responseURL && this.responseURL.startsWith(urlToFollow)) {
const weeklyData = textToJsonObject(this.responseText);
main(weeklyData);
}
});
origOpen.apply(this, arguments);
};
})();
| Add Toggl - Weekly report: calculation and display the work day percentages | Add Toggl - Weekly report: calculation and display the work day percentages
Signed-off-by: Fabien Crassat <777bcfcf9efee56bedca63c5eb2304e67df52892@crassat.com>
| JavaScript | mit | fabiencrassat/UserScripts | ---
+++
@@ -0,0 +1,73 @@
+// ==UserScript==
+// @name Toggl - Weekly report
+// @namespace https://github.com/fabiencrassat
+// @version 0.1
+// @description Calculate and display the work day percentages
+// @author Fabien Crassat <fabien@crassat.com>
+// @include /^https:\/\/toggl\.com\/app\/reports\/weekly\/\d+\/period\/thisWeek/
+// @grant none
+// ==/UserScript==
+
+/** global: $, console */
+
+(function() {
+ 'use strict';
+
+ const weekDaysPlusTotal = [0, 1, 2, 3, 4, 5, 6, 7];
+ const urlToFollow = "https://toggl.com/reports/api/v2/weekly.json";
+ const displayLinesSelector = "table.data-table tr:not(:first, .subgroup, :last)";
+ const displayColumnsSelector = "td[class^='day-'], td.col-total";
+ const decimalLenght = 3;
+
+ const textToJsonObject = function(text) {
+ if (!text) return {};
+ const obj = JSON.parse(text);
+ return obj;
+ };
+
+ const percentage = function(numerator, denumerator) {
+ if (!numerator || !denumerator || denumerator === 0) return 0;
+ return (numerator / denumerator);
+ };
+
+ const extractOneDay = function(data, dayNumber, totalDay) {
+ var dataDay = [];
+ data.forEach(function(dataLine) {
+ dataDay.push(percentage(dataLine.totals[dayNumber], totalDay));
+ });
+ return dataDay;
+ };
+
+ const main = function(weeklyData) {
+ // Calculate
+ var dataDaysPlusTotal = [];
+ weekDaysPlusTotal.forEach(function(dayOrTotal, index) {
+ dataDaysPlusTotal.push(extractOneDay(weeklyData.data, index, weeklyData.week_totals[index]));
+ });
+
+ // Display
+ const displayLines = $(displayLinesSelector);
+ if (!displayLines || displayLines.length !== dataDaysPlusTotal[0].length) {
+ console.warn("There is not the same calculated and display lines.");
+ return;
+ }
+ displayLines.each(function(indexLine) {
+ const element = $(this).find(displayColumnsSelector);
+ element.each(function(indexColumn) {
+ const dataInCeil = dataDaysPlusTotal[indexColumn][displayLines.length - indexLine - 1];
+ $(this).append("<p>" + dataInCeil.toFixed(decimalLenght) + "</p>");
+ });
+ });
+ };
+
+ const origOpen = XMLHttpRequest.prototype.open;
+ XMLHttpRequest.prototype.open = function() {
+ this.addEventListener('load', function() {
+ if (this.responseURL && this.responseURL.startsWith(urlToFollow)) {
+ const weeklyData = textToJsonObject(this.responseText);
+ main(weeklyData);
+ }
+ });
+ origOpen.apply(this, arguments);
+ };
+})(); | |
3cc3a8913c333a18ecb5867cb70c1befc98c2374 | test/test-ime-output.js | test/test-ime-output.js | 'use strict';
var testUtil = require('./util');
var IMEOutput = require('ime-output').IMEOutput;
exports['test IMEOutput (set|finish)Composition'] = function(assert, done) {
testUtil.setupTest('', function(tab) {
var el = testUtil.getFocusedElement();
var imeOutput = new IMEOutput();
imeOutput.setFocusedElement(el);
var expectedEvents = [
{ type: 'compositionstart' },
{ type: 'compositionupdate', data: 'ㄊ' },
{ type: 'input', _value: 'ㄊ', _selectionStart: 1, _selectionEnd: 1 },
{ type: 'compositionupdate', data: 'ㄊㄞ' },
{ type: 'input', _value: 'ㄊㄞ', _selectionStart: 2, _selectionEnd: 2 },
{ type: 'compositionupdate', data: 'ㄊㄞˊ' },
{ type: 'input', _value: 'ㄊㄞˊ', _selectionStart: 3, _selectionEnd: 3 },
{ type: 'compositionupdate', data: '臺' },
{ type: 'compositionend', data: '臺' },
{ type: 'input', _value: '臺', _selectionStart: 1, _selectionEnd: 1 }
];
var check = function check(evt) {
var expectedEvent = expectedEvents.shift();
if (!expectedEvent) {
assert.fail('Unexpected event ' + evt.type);
}
for (var prop in expectedEvent) {
if (prop[0] !== '_') {
assert.strictEqual(
evt[prop], expectedEvent[prop],
'Unexpected event property ' + prop + '.');
continue;
}
assert.strictEqual(
el[prop.substr(1)], expectedEvent[prop],
'Unexpected element property ' + prop.substr(1) + '.');
}
if (expectedEvents.length === 0) {
done();
}
}
el.addEventListener('compositionstart', check, true);
el.addEventListener('compositionupdate', check, true);
el.addEventListener('compositionend', check, true);
el.addEventListener('input', check, true);
imeOutput.setComposition('ㄊ');
imeOutput.setComposition('ㄊ');
imeOutput.setComposition('ㄊㄞ');
imeOutput.setComposition('ㄊㄞˊ');
imeOutput.finishComposition('臺');
});
};
require('test').run(exports);
| Make sure IMEOutput send event and string according to spec | Make sure IMEOutput send event and string according to spec
| JavaScript | mit | timdream/jszhuyin-firefox,timdream/jszhuyin-firefox | ---
+++
@@ -0,0 +1,69 @@
+'use strict';
+
+var testUtil = require('./util');
+
+var IMEOutput = require('ime-output').IMEOutput;
+
+exports['test IMEOutput (set|finish)Composition'] = function(assert, done) {
+ testUtil.setupTest('', function(tab) {
+ var el = testUtil.getFocusedElement();
+
+ var imeOutput = new IMEOutput();
+ imeOutput.setFocusedElement(el);
+
+ var expectedEvents = [
+ { type: 'compositionstart' },
+
+ { type: 'compositionupdate', data: 'ㄊ' },
+ { type: 'input', _value: 'ㄊ', _selectionStart: 1, _selectionEnd: 1 },
+
+ { type: 'compositionupdate', data: 'ㄊㄞ' },
+ { type: 'input', _value: 'ㄊㄞ', _selectionStart: 2, _selectionEnd: 2 },
+
+ { type: 'compositionupdate', data: 'ㄊㄞˊ' },
+ { type: 'input', _value: 'ㄊㄞˊ', _selectionStart: 3, _selectionEnd: 3 },
+
+ { type: 'compositionupdate', data: '臺' },
+ { type: 'compositionend', data: '臺' },
+ { type: 'input', _value: '臺', _selectionStart: 1, _selectionEnd: 1 }
+ ];
+
+ var check = function check(evt) {
+ var expectedEvent = expectedEvents.shift();
+ if (!expectedEvent) {
+ assert.fail('Unexpected event ' + evt.type);
+ }
+
+ for (var prop in expectedEvent) {
+ if (prop[0] !== '_') {
+ assert.strictEqual(
+ evt[prop], expectedEvent[prop],
+ 'Unexpected event property ' + prop + '.');
+
+ continue;
+ }
+
+ assert.strictEqual(
+ el[prop.substr(1)], expectedEvent[prop],
+ 'Unexpected element property ' + prop.substr(1) + '.');
+ }
+
+ if (expectedEvents.length === 0) {
+ done();
+ }
+ }
+
+ el.addEventListener('compositionstart', check, true);
+ el.addEventListener('compositionupdate', check, true);
+ el.addEventListener('compositionend', check, true);
+ el.addEventListener('input', check, true);
+
+ imeOutput.setComposition('ㄊ');
+ imeOutput.setComposition('ㄊ');
+ imeOutput.setComposition('ㄊㄞ');
+ imeOutput.setComposition('ㄊㄞˊ');
+ imeOutput.finishComposition('臺');
+ });
+};
+
+require('test').run(exports); | |
90d437ce89fa442a83e5fed2f8bdc7b9006958ae | examples/invite-reply.js | examples/invite-reply.js | //
// Read an .ics file given on the command line, generate a reply, and email it
// using nodemailer.
//
var fs = require('fs');
var icalendar = require('../lib');
var invite = icalendar.parse_calendar(
fs.readFileSync(process.argv[2], {encoding: 'utf-8'}));
var vevent = invite.events()[0];
// Find the first attendee that has not responded...
var attendee = 'mailto:james@example.com';
var resp = vevent.respond(attendee, true);
console.log(resp.toString());
var reply_to = vevent.getPropertyValue('ORGANIZER').split(':')[1];
console.log('sending to', reply_to);
var nm = require('nodemailer');
var server = nm.createTransport();
server.sendMail({
from: 'james@example.com',
to: reply_to,
subject: 'Meeting accepted',
text: 'Invitation accepted!',
alternatives: [
{
content: resp.toString(),
contentType: 'text/calendar; method=REPLY; charset=utf-8',
}
]
}, function(err, msg) {
console.log(err, msg);
});
| Add an example of replying to an invitation | Add an example of replying to an invitation
| JavaScript | mit | tritech/node-icalendar,oathcomrade/node-icalendar | ---
+++
@@ -0,0 +1,45 @@
+//
+// Read an .ics file given on the command line, generate a reply, and email it
+// using nodemailer.
+//
+
+var fs = require('fs');
+
+var icalendar = require('../lib');
+
+
+var invite = icalendar.parse_calendar(
+ fs.readFileSync(process.argv[2], {encoding: 'utf-8'}));
+var vevent = invite.events()[0];
+
+
+// Find the first attendee that has not responded...
+var attendee = 'mailto:james@example.com';
+
+var resp = vevent.respond(attendee, true);
+console.log(resp.toString());
+
+
+var reply_to = vevent.getPropertyValue('ORGANIZER').split(':')[1];
+console.log('sending to', reply_to);
+
+var nm = require('nodemailer');
+
+var server = nm.createTransport();
+
+server.sendMail({
+ from: 'james@example.com',
+ to: reply_to,
+
+ subject: 'Meeting accepted',
+ text: 'Invitation accepted!',
+
+ alternatives: [
+ {
+ content: resp.toString(),
+ contentType: 'text/calendar; method=REPLY; charset=utf-8',
+ }
+ ]
+}, function(err, msg) {
+ console.log(err, msg);
+}); | |
eb0ab31f9e187973beaf94f356797e9d5ae240a9 | gulpfile.js | gulpfile.js | var gulp = require('gulp');
var uglify = require('gulp-uglify');
var rename = require('gulp-rename');
gulp.task('default', function() {
gulp.src('bootstrap-hover-dropdown.js')
// minifiy preserving preserved comments
.pipe(uglify({
preserveComments: 'some'
}))
// rename to .min.
.pipe(rename('bootstrap-hover-dropdown.min.js'))
.pipe(gulp.dest('.'));
});
var bump = require('gulp-bump');
var filter = require('gulp-filter');
var git = require('gulp-git');
var tagVersion = require('gulp-tag-version');
/**
* Bumping version number and tagging the repository with it.
* Please read http://semver.org/
*
* You can use the commands
*
* gulp patch # makes v0.1.0 → v0.1.1
* gulp feature # makes v0.1.1 → v0.2.0
* gulp release # makes v0.2.1 → v1.0.0
*
* To bump the version numbers accordingly after you did a patch,
* introduced a feature or made a backwards-incompatible release.
*/
function increment(importance) {
// get all the files to bump version in
return gulp.src(['package.json', 'bower.json', 'composer.json'])
// bump the version number in those files
.pipe(bump({ type: importance }))
// save it back to filesystem
.pipe(gulp.dest('.'))
// commit the changed version number
.pipe(git.commit('bump packages version'))
// read only one file to get the version number
.pipe(filter('package.json'))
// **tag it in the repository**
.pipe(tagVersion());
}
gulp.task('patch', function() { return increment('patch'); });
gulp.task('feature', function() { return increment('minor'); });
gulp.task('release', function() { return increment('major'); });
| Add a gulp file to perform minifications (and help manage releases) | Add a gulp file to perform minifications (and help manage releases)
| JavaScript | mit | erickacevedor/bootstrap-hover-dropdown,huangxinliu/bootstrap-hover-dropdown,surgeforward/bootstrap-hover-dropdown,Youraiseme/bootstrap-hover-dropdown,redavis/bootstrap-hover-dropdown,surgeforward/bootstrap-hover-dropdown,erickacevedor/bootstrap-hover-dropdown,huangxinliu/bootstrap-hover-dropdown,CWSpear/bootstrap-hover-dropdown,StephanieMak/bootstrap-hover-dropdown,soojee/bootstrap-hover-dropdown,StephanieMak/bootstrap-hover-dropdown,CWSpear/bootstrap-hover-dropdown,Youraiseme/bootstrap-hover-dropdown,redavis/bootstrap-hover-dropdown,soojee/bootstrap-hover-dropdown | ---
+++
@@ -0,0 +1,58 @@
+var gulp = require('gulp');
+var uglify = require('gulp-uglify');
+var rename = require('gulp-rename');
+
+gulp.task('default', function() {
+ gulp.src('bootstrap-hover-dropdown.js')
+ // minifiy preserving preserved comments
+ .pipe(uglify({
+ preserveComments: 'some'
+ }))
+
+ // rename to .min.
+ .pipe(rename('bootstrap-hover-dropdown.min.js'))
+
+ .pipe(gulp.dest('.'));
+});
+
+
+var bump = require('gulp-bump');
+var filter = require('gulp-filter');
+var git = require('gulp-git');
+var tagVersion = require('gulp-tag-version');
+
+/**
+ * Bumping version number and tagging the repository with it.
+ * Please read http://semver.org/
+ *
+ * You can use the commands
+ *
+ * gulp patch # makes v0.1.0 → v0.1.1
+ * gulp feature # makes v0.1.1 → v0.2.0
+ * gulp release # makes v0.2.1 → v1.0.0
+ *
+ * To bump the version numbers accordingly after you did a patch,
+ * introduced a feature or made a backwards-incompatible release.
+ */
+function increment(importance) {
+ // get all the files to bump version in
+ return gulp.src(['package.json', 'bower.json', 'composer.json'])
+ // bump the version number in those files
+ .pipe(bump({ type: importance }))
+
+ // save it back to filesystem
+ .pipe(gulp.dest('.'))
+
+ // commit the changed version number
+ .pipe(git.commit('bump packages version'))
+
+ // read only one file to get the version number
+ .pipe(filter('package.json'))
+
+ // **tag it in the repository**
+ .pipe(tagVersion());
+}
+
+gulp.task('patch', function() { return increment('patch'); });
+gulp.task('feature', function() { return increment('minor'); });
+gulp.task('release', function() { return increment('major'); }); | |
a80dedc42127d60ea86fd76414f495e5430a806b | updates/0.0.1-list_child-placement-considerations.js | updates/0.0.1-list_child-placement-considerations.js | exports.create = {
'Child Placement Consideration': [{
childPlacementConsideration: 'Fire Setting'
}, {
childPlacementConsideration: 'Hurts Animals'
}, {
childPlacementConsideration: 'Self Harm'
}, {
childPlacementConsideration: 'Sexual Abuse'
}]
}; | Create script to automatically create the list for Child Placement Considerations. | Create script to automatically create the list for Child Placement Considerations.
| JavaScript | mit | autoboxer/MARE,autoboxer/MARE | ---
+++
@@ -0,0 +1,11 @@
+exports.create = {
+ 'Child Placement Consideration': [{
+ childPlacementConsideration: 'Fire Setting'
+ }, {
+ childPlacementConsideration: 'Hurts Animals'
+ }, {
+ childPlacementConsideration: 'Self Harm'
+ }, {
+ childPlacementConsideration: 'Sexual Abuse'
+ }]
+}; | |
6bab509cc142542863fd86b017b85e0681f659ee | tests/helpers/custom-event-polyfill.js | tests/helpers/custom-event-polyfill.js | // Polyfill for creating CustomEvents on IE9/10/11
// code pulled from:
// https://github.com/d4tocchini/customevent-polyfill
// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
if (!window.CustomEvent || typeof window.CustomEvent !== 'function') {
var CustomEvent = function(event, params) {
var evt;
params = params || {
bubbles: false,
cancelable: false,
detail: undefined
};
evt = document.createEvent("CustomEvent");
evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
return evt;
};
CustomEvent.prototype = window.Event.prototype;
window.CustomEvent = CustomEvent; // expose definition to window
}
| Add CustomEvent polyfill for tests | Add CustomEvent polyfill for tests
| JavaScript | mit | SvitlanaShepitsena/shakou,tbossert/framework,SvitlanaShepitsena/framework,infamous/famous-framework,infamous/framework,SvitlanaShepitsena/framework-1,SvitlanaShepitsena/shakou,KraigWalker/framework,SvitlanaShepitsena/remax-banner,Famous/framework,infamous/famous-framework,woltemade/framework,Famous/framework,infamous/framework,SvitlanaShepitsena/remax-banner,woltemade/framework,colllin/famous-framework,SvitlanaShepitsena/framework,tbossert/framework,colllin/famous-framework,jeremykenedy/framework,SvitlanaShepitsena/framework-1,jeremykenedy/framework,KraigWalker/framework,ildarsamit/framework,ildarsamit/framework | ---
+++
@@ -0,0 +1,21 @@
+// Polyfill for creating CustomEvents on IE9/10/11
+// code pulled from:
+// https://github.com/d4tocchini/customevent-polyfill
+// https://developer.mozilla.org/en-US/docs/Web/API/CustomEvent#Polyfill
+if (!window.CustomEvent || typeof window.CustomEvent !== 'function') {
+ var CustomEvent = function(event, params) {
+ var evt;
+ params = params || {
+ bubbles: false,
+ cancelable: false,
+ detail: undefined
+ };
+
+ evt = document.createEvent("CustomEvent");
+ evt.initCustomEvent(event, params.bubbles, params.cancelable, params.detail);
+ return evt;
+ };
+
+ CustomEvent.prototype = window.Event.prototype;
+ window.CustomEvent = CustomEvent; // expose definition to window
+} | |
0812f6afdd572147f4203d4bbce292f20fce1b15 | src/test/ed/db/index6.js | src/test/ed/db/index6.js | // index6.js Test indexes on array subelements.
db = connect( "test" );
r = db.ed.db.index5;
r.drop();
r.save( { comments : [ { name : "eliot", foo : 1 } ] } );
r.ensureIndex( { "comments.name": 1 } );
assert( r.findOne( { "comments.name": "eliot" } ) );
| Add test for indexing simple object element within array | Add test for indexing simple object element within array
| JavaScript | apache-2.0 | babble/babble,babble/babble,babble/babble,babble/babble,babble/babble,babble/babble | ---
+++
@@ -0,0 +1,9 @@
+// index6.js Test indexes on array subelements.
+
+db = connect( "test" );
+r = db.ed.db.index5;
+r.drop();
+
+r.save( { comments : [ { name : "eliot", foo : 1 } ] } );
+r.ensureIndex( { "comments.name": 1 } );
+assert( r.findOne( { "comments.name": "eliot" } ) ); | |
f9489e43ee43ba2c3f453b14416870b2d5762dfc | test/util.js | test/util.js | /* global describe it */
'use strict'
const chai = require('chai')
const chaiAsPromised = require('chai-as-promised')
const requireInject = require('require-inject')
const sinon = require('sinon')
const sinonChai = require('sinon-chai')
require('sinon-as-promised')
chai.use(chaiAsPromised)
chai.use(sinonChai)
const expect = chai.expect
describe('exec', function () {
it('rejects if childProcess.exec fails', function () {
const exec = sinon.stub().yields(['some error'])
const stubs = {
child_process: {
exec
}
}
const util = requireInject('../lib/util', stubs)
return expect(util.exec()).to.be.eventually.rejectedWith('some error')
})
})
| Add child_process.exec failure test case | Add child_process.exec failure test case
| JavaScript | isc | jcollado/multitest | ---
+++
@@ -0,0 +1,27 @@
+/* global describe it */
+'use strict'
+
+const chai = require('chai')
+const chaiAsPromised = require('chai-as-promised')
+const requireInject = require('require-inject')
+const sinon = require('sinon')
+const sinonChai = require('sinon-chai')
+require('sinon-as-promised')
+
+chai.use(chaiAsPromised)
+chai.use(sinonChai)
+
+const expect = chai.expect
+
+describe('exec', function () {
+ it('rejects if childProcess.exec fails', function () {
+ const exec = sinon.stub().yields(['some error'])
+ const stubs = {
+ child_process: {
+ exec
+ }
+ }
+ const util = requireInject('../lib/util', stubs)
+ return expect(util.exec()).to.be.eventually.rejectedWith('some error')
+ })
+}) | |
b6e6dd452f99a3d59d05358209a341e1f2a64198 | src/lib/__tests__/date.spec.js | src/lib/__tests__/date.spec.js | /* eslint-env mocha, jest */
import {
parse,
dayStart,
dayEnd,
addDays,
} from '../date';
const sampleUnixDate = 1511100000000;
it('should parse date correctly', () => {
const expected = sampleUnixDate;
const actual = parse(new Date(sampleUnixDate));
expect(actual).toBe(expected);
});
it('should return day start correctly', () => {
const expected = 1511037000000;
const actual = dayStart(sampleUnixDate);
expect(actual).toBe(expected);
});
it('should return day end correctly', () => {
const expected = 1511123399999;
const actual = dayEnd(sampleUnixDate);
expect(actual).toBe(expected);
});
it('should add days to a date correctly', () => {
const expected = 1511359200000;
const actual = addDays(3, sampleUnixDate);
expect(actual).toBe(expected);
});
| Add date lib unit tests | Add date lib unit tests
| JavaScript | mit | mkermani144/wanna,mkermani144/wanna | ---
+++
@@ -0,0 +1,31 @@
+/* eslint-env mocha, jest */
+
+import {
+ parse,
+ dayStart,
+ dayEnd,
+ addDays,
+} from '../date';
+
+const sampleUnixDate = 1511100000000;
+
+it('should parse date correctly', () => {
+ const expected = sampleUnixDate;
+ const actual = parse(new Date(sampleUnixDate));
+ expect(actual).toBe(expected);
+});
+it('should return day start correctly', () => {
+ const expected = 1511037000000;
+ const actual = dayStart(sampleUnixDate);
+ expect(actual).toBe(expected);
+});
+it('should return day end correctly', () => {
+ const expected = 1511123399999;
+ const actual = dayEnd(sampleUnixDate);
+ expect(actual).toBe(expected);
+});
+it('should add days to a date correctly', () => {
+ const expected = 1511359200000;
+ const actual = addDays(3, sampleUnixDate);
+ expect(actual).toBe(expected);
+}); | |
e2cc892bda88a28a24855ce6bc0ca3b33902231a | test/duplicate.js | test/duplicate.js | var tessel = require('tessel');
var bleLib = require('../');
console.log('1..2');
var ble = bleLib.use(tessel.port['A']);
ble.on('ready', function(){
testOne();
});
function testOne () {
var discovered = [];
ble.startScanning();
var timeout = setTimeout(function(){
console.log('ok - did not return duplicates.');
ble.removeAllListeners('discover');
ble.stopScanning();
testTwo();
},5000);
ble.on('discover', function(device){
if (discovered.indexOf(device.address.toString()) < 0) {
discovered.push(device.address.toString());
} else {
console.log('not ok - duplicates found');
ble.removeAllListeners('discover');
clearInterval(timeout);
ble.stopScanning();
testTwo();
}
});
}
function testTwo () {
var discovered = [];
var timeout = setTimeout(function(){
console.log('not ok - did not return duplicates.');
ble.removeAllListeners('discover');
process.exit();
},20000);
setTimeout(function(){
ble.startScanning({allowDuplicates:true});
},10000);
ble.on('discover', function(device){
if (discovered.indexOf(device.address.toString()) < 0) {
discovered.push(device.address.toString());
} else {
console.log('ok - duplicates found');
ble.removeAllListeners('discover');
clearInterval(timeout);
process.exit();
}
});
}
| Add test for finding dupliates | Add test for finding dupliates
| JavaScript | apache-2.0 | tessel/ble-ble113a,tessel/ble-ble113a | ---
+++
@@ -0,0 +1,53 @@
+var tessel = require('tessel');
+var bleLib = require('../');
+console.log('1..2');
+
+var ble = bleLib.use(tessel.port['A']);
+
+ble.on('ready', function(){
+ testOne();
+});
+
+function testOne () {
+ var discovered = [];
+ ble.startScanning();
+ var timeout = setTimeout(function(){
+ console.log('ok - did not return duplicates.');
+ ble.removeAllListeners('discover');
+ ble.stopScanning();
+ testTwo();
+ },5000);
+ ble.on('discover', function(device){
+ if (discovered.indexOf(device.address.toString()) < 0) {
+ discovered.push(device.address.toString());
+ } else {
+ console.log('not ok - duplicates found');
+ ble.removeAllListeners('discover');
+ clearInterval(timeout);
+ ble.stopScanning();
+ testTwo();
+ }
+ });
+}
+
+function testTwo () {
+ var discovered = [];
+ var timeout = setTimeout(function(){
+ console.log('not ok - did not return duplicates.');
+ ble.removeAllListeners('discover');
+ process.exit();
+ },20000);
+ setTimeout(function(){
+ ble.startScanning({allowDuplicates:true});
+ },10000);
+ ble.on('discover', function(device){
+ if (discovered.indexOf(device.address.toString()) < 0) {
+ discovered.push(device.address.toString());
+ } else {
+ console.log('ok - duplicates found');
+ ble.removeAllListeners('discover');
+ clearInterval(timeout);
+ process.exit();
+ }
+ });
+} | |
d1bb96483651317cd3b079703e8d11f6e0e8d65d | test/read.spec.js | test/read.spec.js | 'use strict';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { expect } from './support/utils';
import PlainContainer from '../src/read/elements/pure/plainContainer';
import MetaError from '../src/read/elements/pure/metaError';
describe('Reads', () => {
describe('Pure Components', () => {
it('properly renders the plain container', () => {
const child = (
<div>child element</div>
);
const renderer = TestUtils.createRenderer();
renderer.render(<PlainContainer elements={child} />);
const output = renderer.getRenderOutput();
expect(output.type).to.equal('div');
expect(output).to.have.deep.property('props.children.type', 'div');
expect(output).to.have.deep.property('props.children.props.children', 'child element');
});
it('properly renders the meta error component', () => {
const renderer = TestUtils.createRenderer();
renderer.render(
<MetaError
url="https://localhost:8080/"
status={400}
message="Bad Request"
/>);
const output = renderer.getRenderOutput();
expect(output.type).to.equal('div');
expect(output).to.have.deep.property('props.children[0].type', 'p');
expect(output).to.have.deep.property('props.children[0].props.children', 'Read Error');
expect(output).to.have.deep.property('props.children[1].props.children', 'https://localhost:8080/');
expect(output).to.have.deep.property('props.children[2].props.children', 400);
expect(output).to.have.deep.property('props.children[3].props.children', 'Bad Request');
});
});
});
| Implement tests for the pure components used in reads | Implement tests for the pure components used in reads
This commit will implement tests for the PlainContainer and MetaError pure components used for the read functionality.
| JavaScript | mit | netceteragroup/girders-elements | ---
+++
@@ -0,0 +1,48 @@
+'use strict';
+
+import React from 'react';
+import TestUtils from 'react-addons-test-utils';
+import { expect } from './support/utils';
+
+import PlainContainer from '../src/read/elements/pure/plainContainer';
+import MetaError from '../src/read/elements/pure/metaError';
+
+describe('Reads', () => {
+
+ describe('Pure Components', () => {
+
+ it('properly renders the plain container', () => {
+ const child = (
+ <div>child element</div>
+ );
+
+ const renderer = TestUtils.createRenderer();
+ renderer.render(<PlainContainer elements={child} />);
+ const output = renderer.getRenderOutput();
+
+ expect(output.type).to.equal('div');
+ expect(output).to.have.deep.property('props.children.type', 'div');
+ expect(output).to.have.deep.property('props.children.props.children', 'child element');
+ });
+
+ it('properly renders the meta error component', () => {
+ const renderer = TestUtils.createRenderer();
+ renderer.render(
+ <MetaError
+ url="https://localhost:8080/"
+ status={400}
+ message="Bad Request"
+ />);
+ const output = renderer.getRenderOutput();
+
+ expect(output.type).to.equal('div');
+ expect(output).to.have.deep.property('props.children[0].type', 'p');
+ expect(output).to.have.deep.property('props.children[0].props.children', 'Read Error');
+ expect(output).to.have.deep.property('props.children[1].props.children', 'https://localhost:8080/');
+ expect(output).to.have.deep.property('props.children[2].props.children', 400);
+ expect(output).to.have.deep.property('props.children[3].props.children', 'Bad Request');
+ });
+
+ });
+
+}); | |
65fbd745b299b016cb429ad75d805518721fe31f | visualize.js | visualize.js | // Convert schema.json files to dot (graphviz' markup language)
//
// Usage:
//
// `node visualize.js schema.json | dot -Tpng -oschema.png`
var fs = require('fs')
, _ = require('underscore')
, Data = require('./data');
var schemaFile = process.ARGV[2]
, schema = JSON.parse(fs.readFileSync(schemaFile, 'utf-8'))
, graph = new Data.Graph(schema);
console.log(schemaToDot(graph));
function schemaToDot (graph) {
var result = '';
function puts (s) { result += s + '\n'; }
function quote (s) { return '"' + s + '"'; }
function getTypeName (type) {
return (type.name || type._id.replace(/^\/type\//, '')).replace(/[^a-zA-Z0-9]/g, '');
}
puts('digraph schema {');
graph.types().each(function (type) {
var typeName = getTypeName(type);
type.properties().each(function (property, propertyName) {
_.each(property.expectedTypes, function (expectedType) {
if (!/^\/type\//.test(expectedType)) return;
expectedType = getTypeName(graph.get(expectedType));
puts(quote(typeName) + ' -> ' + quote(expectedType) + ' [label=' + quote(propertyName) + '];');
});
});
});
puts('}'); // end digraph
return result;
}
| Add script that converts schema.json files to dot language for visualization with graphviz | Add script that converts schema.json files to dot language for visualization with graphviz
| JavaScript | mit | substance/data | ---
+++
@@ -0,0 +1,41 @@
+// Convert schema.json files to dot (graphviz' markup language)
+//
+// Usage:
+//
+// `node visualize.js schema.json | dot -Tpng -oschema.png`
+
+var fs = require('fs')
+, _ = require('underscore')
+, Data = require('./data');
+
+var schemaFile = process.ARGV[2]
+, schema = JSON.parse(fs.readFileSync(schemaFile, 'utf-8'))
+, graph = new Data.Graph(schema);
+
+console.log(schemaToDot(graph));
+
+function schemaToDot (graph) {
+ var result = '';
+ function puts (s) { result += s + '\n'; }
+
+ function quote (s) { return '"' + s + '"'; }
+
+ function getTypeName (type) {
+ return (type.name || type._id.replace(/^\/type\//, '')).replace(/[^a-zA-Z0-9]/g, '');
+ }
+
+ puts('digraph schema {');
+ graph.types().each(function (type) {
+ var typeName = getTypeName(type);
+ type.properties().each(function (property, propertyName) {
+ _.each(property.expectedTypes, function (expectedType) {
+ if (!/^\/type\//.test(expectedType)) return;
+ expectedType = getTypeName(graph.get(expectedType));
+ puts(quote(typeName) + ' -> ' + quote(expectedType) + ' [label=' + quote(propertyName) + '];');
+ });
+ });
+ });
+ puts('}'); // end digraph
+
+ return result;
+} | |
62151afee3bfd1e937d48f8219035041ca33ef3a | src/bom/Style.js | src/bom/Style.js | /*
==================================================================================================
Lowland - JavaScript low level functions
Copyright (C) 2012 Sebatian Fastner
==================================================================================================
*/
core.Module("lowland.bom.Style", {
addStyleText : function(css) {
var st = document.createElement("style");
var rule = document.createTextNode(css);
st.type = "text/css";
if (st.styleSheet) {
st.styleSheet.cssText = rule.nodeValue;
} else {
st.appendChild(rule);
}
document.head.appendChild(st);
}
}); | Add style text to DOM head | Add style text to DOM head
| JavaScript | mit | fastner/lowland,fastner/lowland | ---
+++
@@ -0,0 +1,20 @@
+/*
+==================================================================================================
+ Lowland - JavaScript low level functions
+ Copyright (C) 2012 Sebatian Fastner
+==================================================================================================
+*/
+
+core.Module("lowland.bom.Style", {
+ addStyleText : function(css) {
+ var st = document.createElement("style");
+ var rule = document.createTextNode(css);
+ st.type = "text/css";
+ if (st.styleSheet) {
+ st.styleSheet.cssText = rule.nodeValue;
+ } else {
+ st.appendChild(rule);
+ }
+ document.head.appendChild(st);
+ }
+}); | |
e37aa6fa46f7a84996d9796d11cb9f8eeaf81fca | lib/source-mapper.js | lib/source-mapper.js | /*
* source-mapper.js
*
* Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
*
* @license MIT
*/
'use strict';
var through = require('through');
var convert = require('convert-source-map');
var sourceMap = require('source-map');
/*jslint regexp: true*/
var stackRE = /(\sat .*)?(\[stdin\]|http\:\/\/.+)\:([0-9]+)/g;
exports.extract = function (js) {
var map = convert.fromSource(js);
var mapper;
if (map) {
map = map.toObject();
delete map.sourcesContent;
mapper = new sourceMap.SourceMapConsumer(map);
js = convert.removeComments(js);
}
return {
js : js,
map : mapper
};
};
exports.stream = function (map) {
var buf = '';
return through(function (data) {
if (data) {
buf += data.toString();
var p = buf.lastIndexOf('\n');
if (p !== -1) {
var str = buf.substring(0, p + 1).replace(stackRE,
function (m, p1, p2, nr) {
/*jslint unparam: true*/
if (nr < 1) {
return m;
}
var mapped = map.originalPositionFor({
line : Number(nr),
column : 0
});
return (p1 || '') + mapped.source + ':' + mapped.line;
});
this.queue(str);
buf = buf.substring(p + 1);
}
if (buf.length > 3 && !/^\s+at /.test(buf)) {
this.queue(buf);
buf = '';
}
}
});
};
| Move and adjust code from phantomic | Move and adjust code from phantomic
| JavaScript | mit | mantoni/source-mapper.js | ---
+++
@@ -0,0 +1,63 @@
+/*
+ * source-mapper.js
+ *
+ * Copyright (c) 2014 Maximilian Antoni <mail@maxantoni.de>
+ *
+ * @license MIT
+ */
+'use strict';
+
+var through = require('through');
+var convert = require('convert-source-map');
+var sourceMap = require('source-map');
+
+/*jslint regexp: true*/
+var stackRE = /(\sat .*)?(\[stdin\]|http\:\/\/.+)\:([0-9]+)/g;
+
+
+exports.extract = function (js) {
+ var map = convert.fromSource(js);
+ var mapper;
+ if (map) {
+ map = map.toObject();
+ delete map.sourcesContent;
+ mapper = new sourceMap.SourceMapConsumer(map);
+ js = convert.removeComments(js);
+ }
+ return {
+ js : js,
+ map : mapper
+ };
+};
+
+
+exports.stream = function (map) {
+ var buf = '';
+ return through(function (data) {
+ if (data) {
+ buf += data.toString();
+ var p = buf.lastIndexOf('\n');
+ if (p !== -1) {
+ var str = buf.substring(0, p + 1).replace(stackRE,
+ function (m, p1, p2, nr) {
+ /*jslint unparam: true*/
+ if (nr < 1) {
+ return m;
+ }
+ var mapped = map.originalPositionFor({
+ line : Number(nr),
+ column : 0
+ });
+ return (p1 || '') + mapped.source + ':' + mapped.line;
+ });
+ this.queue(str);
+ buf = buf.substring(p + 1);
+ }
+ if (buf.length > 3 && !/^\s+at /.test(buf)) {
+ this.queue(buf);
+ buf = '';
+ }
+ }
+ });
+
+}; | |
2569c7515ff4a7428ab34670782a8f93246db46f | test/algorithms/geometry/testTangentBetweenCircles.js | test/algorithms/geometry/testTangentBetweenCircles.js | /* eslint-env mocha */
const CircleTangents = require('../../../src').algorithms.geometry.CircleTangents;
const assert = require('assert');
describe('Tangent Between Circles', () => {
it('should return empty arrays if tangents do not exist (one circle is contained in the other)', () => {
const circles = new CircleTangents(0, 0, 1, 0, 0, 0.5);
assert.deepEqual(circles.tangents, [[], [], [], []]);
});
});
| Test Tangent Between Circles: no tangents | Test Tangent Between Circles: no tangents
| JavaScript | mit | ManrajGrover/algorithms-js | ---
+++
@@ -0,0 +1,11 @@
+/* eslint-env mocha */
+const CircleTangents = require('../../../src').algorithms.geometry.CircleTangents;
+
+const assert = require('assert');
+
+describe('Tangent Between Circles', () => {
+ it('should return empty arrays if tangents do not exist (one circle is contained in the other)', () => {
+ const circles = new CircleTangents(0, 0, 1, 0, 0, 0.5);
+ assert.deepEqual(circles.tangents, [[], [], [], []]);
+ });
+}); | |
9c6a2abb1e240945a435f4158a00a2deaba922db | utils/init-es.js | utils/init-es.js | var core = require("../models");
var Artwork = core.db.model("Artwork");
core.init(function() {
Artwork.createMapping(function(err, mapping) {
var stream = Artwork.synchronize();
var count = 0;
stream.on('data', function(err, doc){
count++;
//console.log('indexed ' + count);
});
stream.on('close', function(){
process.exit(0);
});
stream.on('error', function(err){
console.log(err);
});
});
}); | Add a utility for mapping and importing the artworks into Elasticsearch. | Add a utility for mapping and importing the artworks into Elasticsearch.
| JavaScript | mit | jeresig/pharos-images | ---
+++
@@ -0,0 +1,20 @@
+var core = require("../models");
+
+var Artwork = core.db.model("Artwork");
+
+core.init(function() {
+ Artwork.createMapping(function(err, mapping) {
+ var stream = Artwork.synchronize();
+ var count = 0;
+ stream.on('data', function(err, doc){
+ count++;
+ //console.log('indexed ' + count);
+ });
+ stream.on('close', function(){
+ process.exit(0);
+ });
+ stream.on('error', function(err){
+ console.log(err);
+ });
+ });
+}); | |
21989c86c39fd475a14c3dc1bfe6ffa474f229fd | Events.server.js | Events.server.js | /**
* Events:
* Manages the creation and retrieval of the events.
* Also manages sending notifications based on events.
*/
(function () {
'use strict';
var Db = require('db');
var Constants = require('Constants')();
/**
* Adds the given event for the given time slot.
*/
function add(time, event) {
// gets the events from the database
var arr = Db.shared.get('events', time.timeId);
if (arr) { // arr is defined
// add event to arr
arr.push(event);
} else { // there is no array yet
arr = [event];
}
Db.shared.set('events', time.timeId, arr);
}
/**
* Gets the events that happened on the given time.
*/
function get(time) {
var arr = Db.shared.get('events', time.timeId);
if (arr) {
return arr;
} else {
return [];
}
}
/**
* Creates a new event that states the given user died by the given reason
*/
function death(user, cause) {
return {
type: Constants.events.type.DEATH,
user: user,
cause: cause
};
}
/**
* Event denoting that a new game has started.
*/
var newGame = {type: Constants.events.type.NEW_GAME};
exports.add = add;
exports.get = get;
exports.death = death;
exports.newGame = newGame;
}());
| Add Events module for managing events | Add Events module for managing events
#3
| JavaScript | mit | StefvanSchuylenburg/darkville,StefvanSchuylenburg/darkville | ---
+++
@@ -0,0 +1,62 @@
+/**
+ * Events:
+ * Manages the creation and retrieval of the events.
+ * Also manages sending notifications based on events.
+ */
+(function () {
+ 'use strict';
+
+ var Db = require('db');
+ var Constants = require('Constants')();
+
+
+ /**
+ * Adds the given event for the given time slot.
+ */
+ function add(time, event) {
+ // gets the events from the database
+ var arr = Db.shared.get('events', time.timeId);
+ if (arr) { // arr is defined
+ // add event to arr
+ arr.push(event);
+ } else { // there is no array yet
+ arr = [event];
+ }
+
+ Db.shared.set('events', time.timeId, arr);
+ }
+
+ /**
+ * Gets the events that happened on the given time.
+ */
+ function get(time) {
+ var arr = Db.shared.get('events', time.timeId);
+ if (arr) {
+ return arr;
+ } else {
+ return [];
+ }
+ }
+
+ /**
+ * Creates a new event that states the given user died by the given reason
+ */
+ function death(user, cause) {
+ return {
+ type: Constants.events.type.DEATH,
+ user: user,
+ cause: cause
+ };
+ }
+
+ /**
+ * Event denoting that a new game has started.
+ */
+ var newGame = {type: Constants.events.type.NEW_GAME};
+
+ exports.add = add;
+ exports.get = get;
+ exports.death = death;
+ exports.newGame = newGame;
+
+}()); | |
205da483b99391f8ba934c3b30fd72792e214e08 | web/parse-log.js | web/parse-log.js | "use strict";
var sqlite3 = require('sqlite3').verbose(),
carrier = require('carrier'),
fs = require('fs');
var db;
function go() {
db.run(
'CREATE TABLE IF NOT EXISTS query_log (\n' +
' query_time TIMESTAMP, \n' +
' line VARCHAR(255), \n' +
' file VARCHAR(255), \n' +
' remote_ip VARCHAR(255), \n' +
' search_time INT \n' +
'); \n', insert_data)
}
function insert_data() {
var stream = fs.createReadStream(process.argv[2], {
encoding: 'utf8'
});
var stmt = db.prepare('INSERT INTO query_log VALUES (?, ?, ?, ?, ?)');
var re = /^\[(\d{4}-\d{2}-\d{2} \d\d:\d\d:\d\d\.\d\d\d)\] \[DEBUG\] appserver - \[([0-9.]+):\d+\] Search done: \((.*)\): (\d+)/;
var ct = 0;
function handle_one(line) {
var m = re.exec(line);
if (!m)
return;
var ts = m[1],
ip = m[2],
q = m[3],
ms = parseInt(m[4]);
try {
q = JSON.parse(q);
} catch(e) {
console.error("parse error: %s: %s", q, e);
return;
}
stmt.run(ts, q.line, q.file, ip, ms);
if (0 == (++ct % 1000))
console.log("%d...", ct);
}
carrier.carry(stream, handle_one);
stream.on('end', function() {
stmt.finalize(done);
});
}
function done() {
console.log("Done.");
db.close()
process.exit(0);
}
db = new sqlite3.Database('logs.sqlite', go);
| Add a script to parse logs into sqlite. | Add a script to parse logs into sqlite.
| JavaScript | bsd-2-clause | lekkas/livegrep,wfxiang08/livegrep,wfxiang08/livegrep,paulproteus/livegrep,lekkas/livegrep,paulproteus/livegrep,wfxiang08/livegrep,paulproteus/livegrep,lekkas/livegrep,lekkas/livegrep,paulproteus/livegrep,wfxiang08/livegrep,paulproteus/livegrep,paulproteus/livegrep,wfxiang08/livegrep,lekkas/livegrep,lekkas/livegrep,wfxiang08/livegrep | ---
+++
@@ -0,0 +1,56 @@
+"use strict";
+
+var sqlite3 = require('sqlite3').verbose(),
+ carrier = require('carrier'),
+ fs = require('fs');
+var db;
+
+function go() {
+ db.run(
+'CREATE TABLE IF NOT EXISTS query_log (\n' +
+' query_time TIMESTAMP, \n' +
+' line VARCHAR(255), \n' +
+' file VARCHAR(255), \n' +
+' remote_ip VARCHAR(255), \n' +
+' search_time INT \n' +
+'); \n', insert_data)
+}
+
+function insert_data() {
+ var stream = fs.createReadStream(process.argv[2], {
+ encoding: 'utf8'
+ });
+ var stmt = db.prepare('INSERT INTO query_log VALUES (?, ?, ?, ?, ?)');
+ var re = /^\[(\d{4}-\d{2}-\d{2} \d\d:\d\d:\d\d\.\d\d\d)\] \[DEBUG\] appserver - \[([0-9.]+):\d+\] Search done: \((.*)\): (\d+)/;
+ var ct = 0;
+ function handle_one(line) {
+ var m = re.exec(line);
+ if (!m)
+ return;
+ var ts = m[1],
+ ip = m[2],
+ q = m[3],
+ ms = parseInt(m[4]);
+ try {
+ q = JSON.parse(q);
+ } catch(e) {
+ console.error("parse error: %s: %s", q, e);
+ return;
+ }
+ stmt.run(ts, q.line, q.file, ip, ms);
+ if (0 == (++ct % 1000))
+ console.log("%d...", ct);
+ }
+ carrier.carry(stream, handle_one);
+ stream.on('end', function() {
+ stmt.finalize(done);
+ });
+}
+
+function done() {
+ console.log("Done.");
+ db.close()
+ process.exit(0);
+}
+
+db = new sqlite3.Database('logs.sqlite', go); | |
0518d8d3063103253d3eb82ce3933983dece6a45 | 10/ftp-upload.js | 10/ftp-upload.js | var FTP = require('ftp');
var client = new FTP();
client.on('ready', function() {
client.cwd('uploads', function(err) {
if (err)
throw err;
client.put('ftp-upload.js', 'ftp-upload-dest.js', function(err) {
if (err)
throw err;
client.end();
});
});
});
client.connect({
host: 'ftp.speed.hinet.net',
user: 'ftp',
password: 'ftp'
});
| Add the example to upload file to ftp server. | Add the example to upload file to ftp server.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,26 @@
+var FTP = require('ftp');
+
+var client = new FTP();
+
+client.on('ready', function() {
+
+ client.cwd('uploads', function(err) {
+
+ if (err)
+ throw err;
+
+ client.put('ftp-upload.js', 'ftp-upload-dest.js', function(err) {
+
+ if (err)
+ throw err;
+
+ client.end();
+ });
+ });
+});
+
+client.connect({
+ host: 'ftp.speed.hinet.net',
+ user: 'ftp',
+ password: 'ftp'
+}); | |
48683808d41043d9c22b0916a3f477d10d16db10 | tools/grunt-tasks/grunt-condense.js | tools/grunt-tasks/grunt-condense.js | /*
condense script and link tags to a single instance of each in the
specified HTML file; like grunt-usemin but less confusing and more dumb
example config:
condense: {
dist: {
file: 'build/app/index.html',
script: 'js/all.js',
stylesheet: 'css/all.css'
}
}
*/
module.exports = function (grunt) {
var fs = require('fs');
grunt.registerMultiTask('condense', 'Condense script and link elements', function () {
var stylesheet = this.data.stylesheet;
var script = this.data.script;
var file = this.data.file;
var content = fs.readFileSync(file, 'utf8');
// remove all link and script elements with a src
content = content.replace(/<link.+?>/g, '');
content = content.replace(/<script.*?src.*?.+?><\/script>/g, '');
// add single <script> just before the closing </body>
var html = '<script src="' + script + '"></script></body>';
content = content.replace(/<\/body>/, html);
// add a single <link> just above the closing </head>
html = '<link rel="stylesheet" href="' + stylesheet + '"></head>';
content = content.replace(/<\/head>/, html);
// overwrite the original file
fs.writeFileSync(file, content, 'utf8');
});
};
| /*
condense script and link tags to a single instance of each in the
specified HTML file; like grunt-usemin but less confusing and more dumb
example config:
condense: {
dist: {
file: 'build/app/index.html',
script: 'js/all.js',
stylesheet: 'css/all.css'
}
}
*/
module.exports = function (grunt) {
var fs = require('fs');
grunt.registerMultiTask('condense', 'Condense script and link elements', function () {
var stylesheet = this.data.stylesheet;
var script = this.data.script;
var file = this.data.file;
var content = fs.readFileSync(file, 'utf8');
// remove all link and script elements with a src
content = content.replace(/<link.+?>/g, '');
content = content.replace(/<script.*?src.*?.+?><\/script>/g, '');
// add single <script> just before the closing </body>
var html = '<script async="async" src="' + script + '"></script></body>';
content = content.replace(/<\/body>/, html);
// add a single <link> just above the closing </head>
html = '<link rel="stylesheet" href="' + stylesheet + '"></head>';
content = content.replace(/<\/head>/, html);
// overwrite the original file
fs.writeFileSync(file, content, 'utf8');
});
};
| Use async attribute on the script tag for our single script | Use async attribute on the script tag for our single script
We are loading a single script (in the minified/compiled/built
version of the app). Because the JS loads the HTML fragment
and then decorates it in the correct order, we can do
this asynchronously after the DOM has fully loaded.
| JavaScript | apache-2.0 | 01org/webapps-memory-match,01org/webapps-memory-match,dliu32x/webapps-memory-match,rattasapa/webapps-memory-match,modulexcite/webapps-memory-match,modulexcite/webapps-memory-match,rattasapa/webapps-memory-match | ---
+++
@@ -27,7 +27,7 @@
content = content.replace(/<script.*?src.*?.+?><\/script>/g, '');
// add single <script> just before the closing </body>
- var html = '<script src="' + script + '"></script></body>';
+ var html = '<script async="async" src="' + script + '"></script></body>';
content = content.replace(/<\/body>/, html);
// add a single <link> just above the closing </head> |
a49ae559bd3085f870cbc7473593de4f4d39db63 | app/shared/modals/payment-terms/PaymentTermsModal.js | app/shared/modals/payment-terms/PaymentTermsModal.js | import React from 'react';
import PropTypes from 'prop-types';
import Modal from 'react-bootstrap/lib/Modal';
import injectT from '../../../i18n/injectT';
function PaymentTermsModal({
isOpen,
onDismiss,
t,
}) {
return (
<Modal
className="app-PaymentTermsModal"
onHide={onDismiss}
show={isOpen}
>
<Modal.Header>
<Modal.Title>
TODO: Add modal title
</Modal.Title>
</Modal.Header>
<Modal.Body>
TODO: Add modal body
</Modal.Body>
</Modal>
);
}
PaymentTermsModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onDismiss: PropTypes.func.isRequired,
t: PropTypes.func.isRequired,
};
export default injectT(PaymentTermsModal);
| Add new modal for payment terms and conditions | Add new modal for payment terms and conditions
| JavaScript | mit | fastmonkeys/respa-ui | ---
+++
@@ -0,0 +1,36 @@
+import React from 'react';
+import PropTypes from 'prop-types';
+import Modal from 'react-bootstrap/lib/Modal';
+
+import injectT from '../../../i18n/injectT';
+
+function PaymentTermsModal({
+ isOpen,
+ onDismiss,
+ t,
+}) {
+ return (
+ <Modal
+ className="app-PaymentTermsModal"
+ onHide={onDismiss}
+ show={isOpen}
+ >
+ <Modal.Header>
+ <Modal.Title>
+ TODO: Add modal title
+ </Modal.Title>
+ </Modal.Header>
+ <Modal.Body>
+ TODO: Add modal body
+ </Modal.Body>
+ </Modal>
+ );
+}
+
+PaymentTermsModal.propTypes = {
+ isOpen: PropTypes.bool.isRequired,
+ onDismiss: PropTypes.func.isRequired,
+ t: PropTypes.func.isRequired,
+};
+
+export default injectT(PaymentTermsModal); | |
39b7cd5051df439e9579b23b0c2061b589982833 | camera/index.js | camera/index.js | var spawn = require('child_process').spawn;
var exports = module.exports = {};
// Trigger the start of a preview mjpeg stream from the camera
exports.startPreview = function(){
return new Promise(function(resolve, reject){
var mjpegStream = spawn('node', ['node_modules/raspberry-pi-mjpeg-server/raspberry-pi-mjpeg-server.js', '-w', '800', '-l', '480', '-q', '20', '-t', '0']);
var startTimeoutId = setTimeout(function(){
console.log('startPreview timed out');
// After 5 seconds, kill the process & reject the promise
mjpegStream.kill();
reject('startPreview timed out');
}, 5000);
// Watch the output of the child process output for the text "raspistill" and resolve if/when it occurs
mjpegStream.stdout.on('data', (data) => {
// Check if the output contains the string "raspistill" and resolve the promise if found
var output = data.toString();
console.log('Checking:', output);
if(output.indexOf('raspistill') > -1){
clearTimeout(startTimeoutId);
console.log('startPreview succeeded');
resolve(mjpegStream);
}
});
// If an error occurs, reject the promise
mjpegStream.stderr.on('data', (data) => {
clearTimeout(startTimeoutId);
console.log('error:', data.toString());
// If an error occurred, kill the child process & reject the promise
mjpegStream.kill();
reject('An error occurred: ' + data.toString());
});
});
};
// Stop the camera preview stream process
exports.stopPreview = function(mjpegStream){
mjpegStream.kill();
return true;
};
| Add camera module for starting/stopping camera functions | Add camera module for starting/stopping camera functions
| JavaScript | mit | sdunham/pi-booth,sdunham/pi-booth | ---
+++
@@ -0,0 +1,45 @@
+var spawn = require('child_process').spawn;
+
+var exports = module.exports = {};
+
+// Trigger the start of a preview mjpeg stream from the camera
+exports.startPreview = function(){
+ return new Promise(function(resolve, reject){
+
+ var mjpegStream = spawn('node', ['node_modules/raspberry-pi-mjpeg-server/raspberry-pi-mjpeg-server.js', '-w', '800', '-l', '480', '-q', '20', '-t', '0']);
+
+ var startTimeoutId = setTimeout(function(){
+ console.log('startPreview timed out');
+ // After 5 seconds, kill the process & reject the promise
+ mjpegStream.kill();
+ reject('startPreview timed out');
+ }, 5000);
+
+ // Watch the output of the child process output for the text "raspistill" and resolve if/when it occurs
+ mjpegStream.stdout.on('data', (data) => {
+ // Check if the output contains the string "raspistill" and resolve the promise if found
+ var output = data.toString();
+ console.log('Checking:', output);
+ if(output.indexOf('raspistill') > -1){
+ clearTimeout(startTimeoutId);
+ console.log('startPreview succeeded');
+ resolve(mjpegStream);
+ }
+ });
+
+ // If an error occurs, reject the promise
+ mjpegStream.stderr.on('data', (data) => {
+ clearTimeout(startTimeoutId);
+ console.log('error:', data.toString());
+ // If an error occurred, kill the child process & reject the promise
+ mjpegStream.kill();
+ reject('An error occurred: ' + data.toString());
+ });
+ });
+};
+
+// Stop the camera preview stream process
+exports.stopPreview = function(mjpegStream){
+ mjpegStream.kill();
+ return true;
+}; | |
9b0e50e747392e0e547a83790a66412fea74b7c2 | components/index.js | components/index.js | import './utils/polyfills'; // Import polyfills for IE11
export App from './app';
export AppBar from './app_bar';
export Autocomplete from './autocomplete';
export Avatar from './avatar';
export Button from './button/Button';
export IconButton from './button/IconButton';
export * from './card';
export Checkbox from './checkbox';
export DatePicker from './date_picker';
export Dialog from './dialog';
export Drawer from './drawer';
export Dropdown from './dropdown';
export FontIcon from './font_icon';
export Form from './form';
export Input from './input';
export Link from './link';
export List from './list/List';
export ListItem from './list/ListItem';
export ListDivider from './list/ListDivider';
export ListCheckbox from './list/ListCheckbox';
export ListSubHeader from './list/ListSubHeader';
export Menu from './menu/Menu';
export MenuItem from './menu/MenuItem';
export MenuDivider from './menu/MenuDivider';
export IconMenu from './menu/IconMenu';
export Navigation from './navigation';
export ProgressBar from './progress_bar';
export RadioGroup from './radio/RadioGroup';
export RadioButton from './radio/RadioButton';
export Ripple from './ripple';
export Slider from './slider';
export Snackbar from './snackbar';
export Switch from './switch';
export Table from './table';
export Tabs from './tabs/Tabs';
export Tab from './tabs/Tab';
export Tooltip from './tooltip';
export TimePicker from './time_picker';
| import './utils/polyfills'; // Import polyfills for IE11
export App from './app';
export AppBar from './app_bar';
export Autocomplete from './autocomplete';
export Avatar from './avatar';
export Button from './button/Button';
export IconButton from './button/IconButton';
export * from './card';
export Checkbox from './checkbox';
export DatePicker from './date_picker';
export Dialog from './dialog';
export Drawer from './drawer';
export Dropdown from './dropdown';
export FontIcon from './font_icon';
export Form from './form';
export Input from './input';
export Link from './link';
export List from './list/List';
export ListItem from './list/ListItem';
export ListDivider from './list/ListDivider';
export ListCheckbox from './list/ListCheckbox';
export ListSubHeader from './list/ListSubheader';
export Menu from './menu/Menu';
export MenuItem from './menu/MenuItem';
export MenuDivider from './menu/MenuDivider';
export IconMenu from './menu/IconMenu';
export Navigation from './navigation';
export ProgressBar from './progress_bar';
export RadioGroup from './radio/RadioGroup';
export RadioButton from './radio/RadioButton';
export Ripple from './ripple';
export Slider from './slider';
export Snackbar from './snackbar';
export Switch from './switch';
export Table from './table';
export Tabs from './tabs/Tabs';
export Tab from './tabs/Tab';
export Tooltip from './tooltip';
export TimePicker from './time_picker';
| Change capitalization to match the filesystem exactly. | Change capitalization to match the filesystem exactly.
| JavaScript | mit | react-toolbox/react-toolbox,rubenmoya/react-toolbox,showings/react-toolbox,rubenmoya/react-toolbox,soyjavi/react-toolbox,jasonleibowitz/react-toolbox,soyjavi/react-toolbox,rubenmoya/react-toolbox,showings/react-toolbox,KerenChandran/react-toolbox,KerenChandran/react-toolbox,react-toolbox/react-toolbox,jasonleibowitz/react-toolbox,react-toolbox/react-toolbox | ---
+++
@@ -19,7 +19,7 @@
export ListItem from './list/ListItem';
export ListDivider from './list/ListDivider';
export ListCheckbox from './list/ListCheckbox';
-export ListSubHeader from './list/ListSubHeader';
+export ListSubHeader from './list/ListSubheader';
export Menu from './menu/Menu';
export MenuItem from './menu/MenuItem';
export MenuDivider from './menu/MenuDivider'; |
49879b12aa8125ed24151feb1cbf315399b0e6eb | js/foam/lib/gmail/Sync.js | js/foam/lib/gmail/Sync.js | CLASS({
package: 'foam.lib.gmail',
name: 'Sync',
extendsModel: 'foam.core.dao.Sync',
requires: [
'FOAMGMailMessage'
],
methods: {
purge: function(ret, remoteLocal) {
// Drafts that were created and sent from the client with no sync in
// between, do not get marked as deleted. However if the client version
// is old and the draft is marked as sent, then it is no longer needed.
var self = this;
this.SUPER(function(purged) {
this.local
.where(AND(LTE(this.localVersionProp, remoteLocal),
EQ(this.FOAMGMailMessage.IS_SENT, true),
EQ(this.FOAMGMailMessage.LABEL_IDS, 'DRAFT')))
.removeAll(purged)(ret);
}.bind(this), remoteLocal);
}
}
});
| Add a GMail specific sync that has special logic for purging sent drafts created on the client. | Add a GMail specific sync that has special logic for purging sent drafts created on the client.
| JavaScript | apache-2.0 | osric-the-knight/foam,jacksonic/foam,osric-the-knight/foam,jacksonic/foam,foam-framework/foam,osric-the-knight/foam,jlhughes/foam,mdittmer/foam,mdittmer/foam,mdittmer/foam,jlhughes/foam,foam-framework/foam,jacksonic/foam,foam-framework/foam,jlhughes/foam,foam-framework/foam,osric-the-knight/foam,foam-framework/foam,jacksonic/foam,jlhughes/foam,mdittmer/foam | ---
+++
@@ -0,0 +1,23 @@
+CLASS({
+ package: 'foam.lib.gmail',
+ name: 'Sync',
+ extendsModel: 'foam.core.dao.Sync',
+ requires: [
+ 'FOAMGMailMessage'
+ ],
+ methods: {
+ purge: function(ret, remoteLocal) {
+ // Drafts that were created and sent from the client with no sync in
+ // between, do not get marked as deleted. However if the client version
+ // is old and the draft is marked as sent, then it is no longer needed.
+ var self = this;
+ this.SUPER(function(purged) {
+ this.local
+ .where(AND(LTE(this.localVersionProp, remoteLocal),
+ EQ(this.FOAMGMailMessage.IS_SENT, true),
+ EQ(this.FOAMGMailMessage.LABEL_IDS, 'DRAFT')))
+ .removeAll(purged)(ret);
+ }.bind(this), remoteLocal);
+ }
+ }
+}); | |
2598d76775b8824fcf9326a73c8c4e590cbc28eb | js/hr-challenges/algo-06-birthday-choco.js | js/hr-challenges/algo-06-birthday-choco.js | /**
* https://www.hackerrank.com/challenges/the-birthday-bar/problem
*
* Lily has a chocolate bar consisting of a row of n squares where each square
* has an integer written on it. She wants to share it with Ron for his birthday,
* which falls on month m and day d. Lily wants to give Ron a piece of chocolate
* only if it contains consecutive squares whose integers sum to d.
*
* Given m, d, and the sequence of integers written on each square of Lily's
* chocolate bar, how many different ways can Lily break off a piece of
* chocolate to give to Ron?
*
* For example, if m = 2, d = 3 and the chocolate bar contains n rows of squares
* with the integers [1, 2, 1, 3, 2] written on them from left to right, the
* following diagram shows two ways to break off a piece:
*
* Output Format
*
* Print an integer denoting the total number of ways that Lily can give a
* piece of chocolate to Ron.
*/
process.stdin.resume();
process.stdin.setEncoding('ascii');
var input_stdin = "";
var input_stdin_array = "";
var input_currentline = 0;
process.stdin.on('data', function (data) {
input_stdin += data;
});
process.stdin.on('end', function () {
input_stdin_array = input_stdin.split("\n");
main();
});
function readLine() {
return input_stdin_array[input_currentline++];
}
/////////////// ignore above this line ////////////////////
function solve(n, arr, d, m){
let result = 0;
// O(nm) or O(n^2)
for (let i = 0; i < n; i++) {
let sum = arr[i];
for (let j = i + 1; j < i + m; j++) {
sum += arr[j];
}
result += sum === d ? 1 : 0;
}
return result;
}
function main() {
var n = parseInt(readLine());
s = readLine().split(' ');
s = s.map(Number);
var d_temp = readLine().split(' ');
var d = parseInt(d_temp[0]);
var m = parseInt(d_temp[1]);
var result = solve(n, s, d, m);
process.stdout.write(""+result+"\n");
}
| Add birthday chocolate challenge solution | Add birthday chocolate challenge solution
| JavaScript | mit | petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox,petarov/sandbox | ---
+++
@@ -0,0 +1,70 @@
+/**
+ * https://www.hackerrank.com/challenges/the-birthday-bar/problem
+ *
+ * Lily has a chocolate bar consisting of a row of n squares where each square
+ * has an integer written on it. She wants to share it with Ron for his birthday,
+ * which falls on month m and day d. Lily wants to give Ron a piece of chocolate
+ * only if it contains consecutive squares whose integers sum to d.
+ *
+ * Given m, d, and the sequence of integers written on each square of Lily's
+ * chocolate bar, how many different ways can Lily break off a piece of
+ * chocolate to give to Ron?
+ *
+ * For example, if m = 2, d = 3 and the chocolate bar contains n rows of squares
+ * with the integers [1, 2, 1, 3, 2] written on them from left to right, the
+ * following diagram shows two ways to break off a piece:
+ *
+ * Output Format
+ *
+ * Print an integer denoting the total number of ways that Lily can give a
+ * piece of chocolate to Ron.
+ */
+process.stdin.resume();
+process.stdin.setEncoding('ascii');
+
+var input_stdin = "";
+var input_stdin_array = "";
+var input_currentline = 0;
+
+process.stdin.on('data', function (data) {
+ input_stdin += data;
+});
+
+process.stdin.on('end', function () {
+ input_stdin_array = input_stdin.split("\n");
+ main();
+});
+
+function readLine() {
+ return input_stdin_array[input_currentline++];
+}
+
+/////////////// ignore above this line ////////////////////
+
+function solve(n, arr, d, m){
+ let result = 0;
+
+ // O(nm) or O(n^2)
+ for (let i = 0; i < n; i++) {
+ let sum = arr[i];
+
+ for (let j = i + 1; j < i + m; j++) {
+ sum += arr[j];
+ }
+
+ result += sum === d ? 1 : 0;
+ }
+
+ return result;
+}
+
+function main() {
+ var n = parseInt(readLine());
+ s = readLine().split(' ');
+ s = s.map(Number);
+ var d_temp = readLine().split(' ');
+ var d = parseInt(d_temp[0]);
+ var m = parseInt(d_temp[1]);
+ var result = solve(n, s, d, m);
+ process.stdout.write(""+result+"\n");
+} | |
8436b9d61cbad4db54e88ce08178ceffba5ca1e4 | src/algorithms/geometry/vector_operations2d.js | src/algorithms/geometry/vector_operations2d.js | /**
* Performs the cross product between two vectors.
* @param A vector object, example: {x : 0,y : 0}
* @param A vector object, example: {x : 0,y : 0}
* @return The result of the cross product between u and v.
*/
const crossProduct = (u, v) => {
return u.x*v.y - u.y*v.x;
};
/**
* @param A point object, example: {x : 0,y : 0}
* @param A point object, example: {x : 0,y : 0}
* @param A point object, example: {x : 0,y : 0}
* @return Returns true if the point c is counter-clockwise with respect
* to the straight-line which contains the vector ab, otherwise returns false.
*/
const isClockwise = (a, b, c) => {
return crossProduct({x: b.x-a.x, y: b.y-a.y}, c) < 0;
};
module.exports = {
crossProduct: crossProduct,
isClockwise: isClockwise
};
| Add operations for 2d vectors | Add operations for 2d vectors
| JavaScript | mit | felipernb/algorithms.js | ---
+++
@@ -0,0 +1,25 @@
+/**
+ * Performs the cross product between two vectors.
+ * @param A vector object, example: {x : 0,y : 0}
+ * @param A vector object, example: {x : 0,y : 0}
+ * @return The result of the cross product between u and v.
+ */
+const crossProduct = (u, v) => {
+ return u.x*v.y - u.y*v.x;
+};
+
+/**
+ * @param A point object, example: {x : 0,y : 0}
+ * @param A point object, example: {x : 0,y : 0}
+ * @param A point object, example: {x : 0,y : 0}
+ * @return Returns true if the point c is counter-clockwise with respect
+ * to the straight-line which contains the vector ab, otherwise returns false.
+ */
+const isClockwise = (a, b, c) => {
+ return crossProduct({x: b.x-a.x, y: b.y-a.y}, c) < 0;
+};
+
+module.exports = {
+ crossProduct: crossProduct,
+ isClockwise: isClockwise
+}; | |
f8b67604f9883c6c830312b54634a942e9471e68 | 16/ninja-basic.js | 16/ninja-basic.js | var Image = require('image-ninja');
var dirpath = 'images/';
var imgname = 'download-logo.png';
var tmppath = 'tmp/'
var image = new Image(dirpath + imgname);
image
.width(1000)
.height(1000)
.save(tmppath + imgname)
.then(function (newImage) {
console.log('Done.');
}); | Add the example to adjust image's width/height via ninja. | Add the example to adjust image's width/height via ninja.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,15 @@
+var Image = require('image-ninja');
+
+var dirpath = 'images/';
+var imgname = 'download-logo.png';
+var tmppath = 'tmp/'
+
+var image = new Image(dirpath + imgname);
+
+image
+ .width(1000)
+ .height(1000)
+ .save(tmppath + imgname)
+ .then(function (newImage) {
+ console.log('Done.');
+ }); | |
f21bbb8fb2998742c62c9c30f68551729b17c844 | app/assets/javascripts/app.js | app/assets/javascripts/app.js | (function(){
'use strict';
angular
.module('shareMark', ['ui.router', 'templates', 'ngclipboard'])
.config(function($stateProvider, $urlRouterProvider){
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: "/",
template: "<home></home>"
})
.state('search', {
url: '/search',
template: '<search></search>'
})
.state('new', {
url: '/new',
template: '<new></new>'
})
.state('show', {
url: '/:id',
template: '<show></show>'
})
}]);//end config
}());
| Set up ui-router, add angular-rails-templates and ngclipboard as dependencies | Set up ui-router, add angular-rails-templates and ngclipboard as dependencies
| JavaScript | mit | Dom-Mc/shareMark,Dom-Mc/shareMark,Dom-Mc/shareMark | ---
+++
@@ -0,0 +1,33 @@
+(function(){
+ 'use strict';
+
+ angular
+ .module('shareMark', ['ui.router', 'templates', 'ngclipboard'])
+ .config(function($stateProvider, $urlRouterProvider){
+
+ $urlRouterProvider.otherwise('/');
+
+ $stateProvider
+ .state('home', {
+ url: "/",
+ template: "<home></home>"
+ })
+
+ .state('search', {
+ url: '/search',
+ template: '<search></search>'
+ })
+
+ .state('new', {
+ url: '/new',
+ template: '<new></new>'
+ })
+
+ .state('show', {
+ url: '/:id',
+ template: '<show></show>'
+ })
+
+ }]);//end config
+
+}()); | |
ff4ad58f56aebd8b6069f45c1b630f7667bfffc0 | lib/wrap/prefix.js | lib/wrap/prefix.js | /* Riot WIP, @license MIT, (c) 2015 Muut Inc. + contributors */
;(function() {
var riot = { version: 'WIP', settings: {} }
'use strict'
| /* Riot WIP, @license MIT, (c) 2015 Muut Inc. + contributors */
;(function() {
var riot = {
version: 'WIP',
// a secret backdoor to private vars
// allows to share methods with external components,
// e.g. cli.js, compiler.js from jsdelivr, tests,
// while still keeping our code minimal
_: function(k) { return eval(k) }
}
'use strict'
| Add riot.(var) backdoor to riot's private vars (for compiler, tests, etc) | Add riot.(var) backdoor to riot's private vars (for compiler, tests, etc)
| JavaScript | mit | stonexer/riot,baysao/riot,crisward/riot,marcioj/riot,thepian/riot,marciojcoelho/riotjs,dp-lewis/riot,beni55/riot,qrb/riotjs,xtity/riot,dp-lewis/riot,sylvainpolletvillard/riot,rsbondi/riotjs,tao-zeng/riot,GerHobbelt/riotjs,rasata/riot,noodle-learns-programming/riot,ListnPlay/riotjs,crisward/riot,txchen/riotjs,rthbound/riot,joshcartme/riot,antonheryanto/riot,antonheryanto/riot,seedtigo/riot,noodle-learns-programming/riot,AndrewSwerlick/riot,chetanism/riot,daemonchen/riotjs,marciojcoelho/riotjs,ListnPlay/riotjs,marcioj/riot,rthbound/riot,GerHobbelt/riotjs,scalabl3/riot,zawsx/js-lib-webcomponents-react-riot,beni55/riot,dschnare/riot,baysao/riot,sylvainpolletvillard/riot,rsbondi/riotjs,ttamminen/riotjs,txchen/riotjs,a-moses/riot,chetanism/riot,daemonchen/riotjs,qrb/riotjs,zawsx/js-lib-webcomponents-react-riot,rasata/riot,duongphuhiep/riot,a-moses/riot,mike-ward/riot,tao-zeng/riot,madlordory/riot,mike-ward/riot,laomu1988/riot,scalabl3/riot,seedtigo/riot,stonexer/riot,duongphuhiep/riot,muut/riotjs,davidmarkclements/riot,thepian/riot,joshcartme/riot,AndrewSwerlick/riot,ttamminen/riotjs,muut/riotjs,madlordory/riot,xieyu33333/riot,dschnare/riot,davidmarkclements/riot,xtity/riot,xieyu33333/riot,laomu1988/riot | ---
+++
@@ -2,6 +2,16 @@
;(function() {
- var riot = { version: 'WIP', settings: {} }
+ var riot = {
+
+ version: 'WIP',
+
+ // a secret backdoor to private vars
+ // allows to share methods with external components,
+ // e.g. cli.js, compiler.js from jsdelivr, tests,
+ // while still keeping our code minimal
+ _: function(k) { return eval(k) }
+
+ }
'use strict' |
2697c44ed205940116f9fd814a3f6175c4e75f7d | app/serializers/researcher.js | app/serializers/researcher.js | // // import { Serializer } from 'ember-graphql-adapter';
// // import { singularize } from "ember-inflector";
// // import { camelize } from "@ember/string";
// // export default Serializer.extend({
// // normalizeResponse(store, primaryModelClass, payload, id, requestType) {
// // // hack: swap `all` root queries for appropriate ember data model name
// // for (let key in payload.data) {
// // // let baseModelKey = key.replace("all", "");
// // payload.data["researcher"] =
// // payload.data[key];
// // delete payload.data[key];
// // }
// // return this._super(store, primaryModelClass, payload, id, requestType);
// // },
// // });
// import GraphqlSerializer from './graphql';
// export default GraphqlSerializer.extend({
// // normalizeResponse(store, primaryModelClass, payload, id, requestType) {
// // console.log(store)
// // console.log(payload)
// // console.log(requestType)
// // // hack: swap `all` root queries for appropriate ember data model name
// // for (let key in payload.data) {
// // // let baseModelKey = key.replace("all", "");
// // payload.data["researcher"] =
// // payload.data[key];
// // delete payload.data[key];
// // }
// // return this._super(store, primaryModelClass, payload, id, requestType);
// // },
// });
| Revert "remove un used file" | Revert "remove un used file"
This reverts commit 76a91f84cd37c936e0caa020bdfac1b15e843703.
| JavaScript | mit | datacite/bracco,datacite/bracco,datacite/bracco,datacite/bracco | ---
+++
@@ -0,0 +1,38 @@
+// // import { Serializer } from 'ember-graphql-adapter';
+// // import { singularize } from "ember-inflector";
+// // import { camelize } from "@ember/string";
+
+// // export default Serializer.extend({
+// // normalizeResponse(store, primaryModelClass, payload, id, requestType) {
+// // // hack: swap `all` root queries for appropriate ember data model name
+// // for (let key in payload.data) {
+// // // let baseModelKey = key.replace("all", "");
+// // payload.data["researcher"] =
+// // payload.data[key];
+// // delete payload.data[key];
+// // }
+
+// // return this._super(store, primaryModelClass, payload, id, requestType);
+// // },
+// // });
+
+// import GraphqlSerializer from './graphql';
+
+// export default GraphqlSerializer.extend({
+// // normalizeResponse(store, primaryModelClass, payload, id, requestType) {
+// // console.log(store)
+// // console.log(payload)
+// // console.log(requestType)
+// // // hack: swap `all` root queries for appropriate ember data model name
+// // for (let key in payload.data) {
+// // // let baseModelKey = key.replace("all", "");
+// // payload.data["researcher"] =
+// // payload.data[key];
+// // delete payload.data[key];
+// // }
+
+// // return this._super(store, primaryModelClass, payload, id, requestType);
+// // },
+// });
+
+ | |
cedfb0f0bb5b9fcea39c0c7604107038281e7ae1 | server/openstorefront/openstorefront-web/src/main/webapp/client/scripts/component/savedSearchLinkInsertWindow.js | server/openstorefront/openstorefront-web/src/main/webapp/client/scripts/component/savedSearchLinkInsertWindow.js | /*
* Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation.
*
* 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.
*/
/* global Ext, CoreService */
Ext.define('OSF.component.SavedSearchLinkInsertWindow', {
extend: 'Ext.window.Window',
alias: 'osf.widget.SavedSearchLinkInsertWindow',
layout: 'fit',
title: 'Insert Link to Saved Search',
modal: true,
width: '60%',
height: '50%',
initComponent: function () {
this.callParent();
var savedSearchLinkInsertWindow = this;
savedSearchLinkInsertWindow.getLink = function() {
return "Link text goes here.";
};
}
});
| Add saved search selection window | Add saved search selection window
We add a window which can be used to select a saved search from which
a link may be embedded.
| JavaScript | apache-2.0 | jbottel/openstorefront,jbottel/openstorefront,jbottel/openstorefront,jbottel/openstorefront | ---
+++
@@ -0,0 +1,43 @@
+/*
+ * Copyright 2016 Space Dynamics Laboratory - Utah State University Research Foundation.
+ *
+ * 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.
+ */
+/* global Ext, CoreService */
+
+Ext.define('OSF.component.SavedSearchLinkInsertWindow', {
+ extend: 'Ext.window.Window',
+ alias: 'osf.widget.SavedSearchLinkInsertWindow',
+ layout: 'fit',
+
+ title: 'Insert Link to Saved Search',
+ modal: true,
+ width: '60%',
+ height: '50%',
+
+ initComponent: function () {
+ this.callParent();
+
+ var savedSearchLinkInsertWindow = this;
+
+
+ savedSearchLinkInsertWindow.getLink = function() {
+ return "Link text goes here.";
+ };
+ }
+
+
+
+});
+
+ | |
5f4a682b991bae07e0ac25df0f2d93cbc6b78473 | benchmarks/hifiqa-master/measureTimingHifiQA-19Q4-staging2.js | benchmarks/hifiqa-master/measureTimingHifiQA-19Q4-staging2.js | Script.include("../BenchmarkLib.js");
var TRACING_RULES = "" +
"trace.*=true\n" +
"*.detail=true\n" +
"";
Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));
var testScript = new TestScript();
testScript.addTest({
name: "measureTimingHifiqa-19Q4-staging2",
loader: TestScript.locationLoader("hifi://staging2", true),
tracingRules: TRACING_RULES,
traceActions: TestScript.measureTimingSteps([
{ time: 5, step: 0.1, keepActive: true, pos: { x: 81.5, y: -97.2, z: -312.8 }, ori:{ yaw: 127.1 } }, // landing point
{ time: 5, step: 0.1, keepActive: true, pos: { x: 154.8, y: -97.7, z: -395.6 }, ori:{ yaw: 90.9 } }, // looking at quad
{ time: 5, step: 0.1, keepActive: true, pos: { x: 159.6, y: -96.8, z: -325.6 }, ori:{ yaw: -125.2 } }, // engine pod
{ time: 5, step: 0.1, keepActive: true, pos: { x: 127.3, y: -91.8, z: -336.2 }, ori:{ yaw: 173.6 } }, // near a chatterbox
{ time: 5, step: 0.1, keepActive: true, pos: { x: 119.0, y: -93.9, z: -401.8 }, ori:{ yaw: 40.7 } }, // capitol
]),
duration: 30
});
testScript.runTests();
| Create a new perf test for the new content | Create a new perf test for the new content | JavaScript | apache-2.0 | highfidelity/hifi_tests,highfidelity/hifi_tests,highfidelity/hifi_tests | ---
+++
@@ -0,0 +1,24 @@
+Script.include("../BenchmarkLib.js");
+
+var TRACING_RULES = "" +
+ "trace.*=true\n" +
+ "*.detail=true\n" +
+ "";
+
+Resources.overrideUrlPrefix(TEST_ROOT, Script.resolvePath(".."));
+var testScript = new TestScript();
+testScript.addTest({
+ name: "measureTimingHifiqa-19Q4-staging2",
+ loader: TestScript.locationLoader("hifi://staging2", true),
+ tracingRules: TRACING_RULES,
+ traceActions: TestScript.measureTimingSteps([
+ { time: 5, step: 0.1, keepActive: true, pos: { x: 81.5, y: -97.2, z: -312.8 }, ori:{ yaw: 127.1 } }, // landing point
+ { time: 5, step: 0.1, keepActive: true, pos: { x: 154.8, y: -97.7, z: -395.6 }, ori:{ yaw: 90.9 } }, // looking at quad
+ { time: 5, step: 0.1, keepActive: true, pos: { x: 159.6, y: -96.8, z: -325.6 }, ori:{ yaw: -125.2 } }, // engine pod
+ { time: 5, step: 0.1, keepActive: true, pos: { x: 127.3, y: -91.8, z: -336.2 }, ori:{ yaw: 173.6 } }, // near a chatterbox
+ { time: 5, step: 0.1, keepActive: true, pos: { x: 119.0, y: -93.9, z: -401.8 }, ori:{ yaw: 40.7 } }, // capitol
+ ]),
+ duration: 30
+});
+
+testScript.runTests(); | |
95986222a1313f9eb37651adf0ed9270c9a8961f | migrations/20170326151414_add_event_id_for_feed_items.js | migrations/20170326151414_add_event_id_for_feed_items.js |
exports.up = function(knex, Promise) {
return knex.schema.table('feed_items', function(table) {
table.integer('event_id').index();
table.foreign('event_id')
.references('id')
.inTable('events')
.onDelete('RESTRICT')
.onUpdate('CASCADE');
});
};
exports.down = function(knex, Promise) {
return knex.schema.table('feed_items', function(table) {
table.dropColumn('event_id');
});
}
| Add event_id column to feed_items table | Add event_id column to feed_items table
| JavaScript | mit | kaupunki-apina/prahapp-backend,futurice/wappuapp-backend,kaupunki-apina/prahapp-backend,futurice/wappuapp-backend | ---
+++
@@ -0,0 +1,17 @@
+
+exports.up = function(knex, Promise) {
+ return knex.schema.table('feed_items', function(table) {
+ table.integer('event_id').index();
+ table.foreign('event_id')
+ .references('id')
+ .inTable('events')
+ .onDelete('RESTRICT')
+ .onUpdate('CASCADE');
+ });
+};
+
+exports.down = function(knex, Promise) {
+ return knex.schema.table('feed_items', function(table) {
+ table.dropColumn('event_id');
+ });
+} | |
f8e10ed2f67af93d6a4c00099959af6821c9051e | frontend_tests/node_tests/common.js | frontend_tests/node_tests/common.js | var common = require("js/common.js");
set_global('$', function (f) {
if (f === '#home') {
return [{ focus: function () {} }];
}
f();
});
(function test_basics() {
common.autofocus('#home');
}());
| Add test coverage to autofocus. | node_tests: Add test coverage to autofocus.
| JavaScript | apache-2.0 | timabbott/zulip,brainwane/zulip,hackerkid/zulip,andersk/zulip,jrowan/zulip,brockwhittaker/zulip,synicalsyntax/zulip,punchagan/zulip,rishig/zulip,shubhamdhama/zulip,jrowan/zulip,j831/zulip,shubhamdhama/zulip,zulip/zulip,synicalsyntax/zulip,mahim97/zulip,vabs22/zulip,showell/zulip,jackrzhang/zulip,timabbott/zulip,tommyip/zulip,punchagan/zulip,amanharitsh123/zulip,rht/zulip,dhcrzf/zulip,verma-varsha/zulip,kou/zulip,hackerkid/zulip,rht/zulip,rishig/zulip,zulip/zulip,vabs22/zulip,jrowan/zulip,rht/zulip,shubhamdhama/zulip,vabs22/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,hackerkid/zulip,vaidap/zulip,mahim97/zulip,verma-varsha/zulip,jrowan/zulip,brainwane/zulip,Galexrt/zulip,jrowan/zulip,zulip/zulip,christi3k/zulip,Galexrt/zulip,eeshangarg/zulip,eeshangarg/zulip,jackrzhang/zulip,vabs22/zulip,andersk/zulip,brainwane/zulip,verma-varsha/zulip,verma-varsha/zulip,hackerkid/zulip,dhcrzf/zulip,showell/zulip,brockwhittaker/zulip,amanharitsh123/zulip,Galexrt/zulip,punchagan/zulip,kou/zulip,tommyip/zulip,dhcrzf/zulip,dhcrzf/zulip,andersk/zulip,Galexrt/zulip,synicalsyntax/zulip,kou/zulip,tommyip/zulip,jackrzhang/zulip,kou/zulip,rishig/zulip,tommyip/zulip,eeshangarg/zulip,andersk/zulip,rht/zulip,christi3k/zulip,punchagan/zulip,tommyip/zulip,dhcrzf/zulip,shubhamdhama/zulip,punchagan/zulip,rishig/zulip,andersk/zulip,zulip/zulip,Galexrt/zulip,eeshangarg/zulip,punchagan/zulip,rishig/zulip,shubhamdhama/zulip,timabbott/zulip,vaidap/zulip,kou/zulip,amanharitsh123/zulip,amanharitsh123/zulip,vaidap/zulip,shubhamdhama/zulip,timabbott/zulip,dhcrzf/zulip,mahim97/zulip,jackrzhang/zulip,vaidap/zulip,eeshangarg/zulip,mahim97/zulip,synicalsyntax/zulip,vabs22/zulip,vaidap/zulip,christi3k/zulip,brainwane/zulip,rht/zulip,mahim97/zulip,jackrzhang/zulip,j831/zulip,brainwane/zulip,zulip/zulip,j831/zulip,hackerkid/zulip,dhcrzf/zulip,brockwhittaker/zulip,christi3k/zulip,synicalsyntax/zulip,zulip/zulip,andersk/zulip,timabbott/zulip,jackrzhang/zulip,jackrzhang/zulip,showell/zulip,eeshangarg/zulip,synicalsyntax/zulip,brockwhittaker/zulip,verma-varsha/zulip,mahim97/zulip,hackerkid/zulip,j831/zulip,timabbott/zulip,showell/zulip,Galexrt/zulip,andersk/zulip,verma-varsha/zulip,kou/zulip,amanharitsh123/zulip,rishig/zulip,christi3k/zulip,rishig/zulip,brockwhittaker/zulip,showell/zulip,vabs22/zulip,showell/zulip,tommyip/zulip,j831/zulip,vaidap/zulip,kou/zulip,Galexrt/zulip,amanharitsh123/zulip,punchagan/zulip,tommyip/zulip,brainwane/zulip,zulip/zulip,christi3k/zulip,timabbott/zulip,rht/zulip,jrowan/zulip,j831/zulip,brainwane/zulip,shubhamdhama/zulip,brockwhittaker/zulip,rht/zulip,hackerkid/zulip | ---
+++
@@ -0,0 +1,12 @@
+var common = require("js/common.js");
+
+set_global('$', function (f) {
+ if (f === '#home') {
+ return [{ focus: function () {} }];
+ }
+ f();
+});
+
+(function test_basics() {
+ common.autofocus('#home');
+}()); | |
86d9855400fcbbd53e84e1668b92ba14abcf5d34 | scripts/babel-relay-plugin/src/__tests__/BuildChecker-test.js | scripts/babel-relay-plugin/src/__tests__/BuildChecker-test.js | /**
* Copyright 2013-2015, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @fullSyntaxTransform
*/
'use strict';
const babel = require('babel');
const fs = require('fs');
const path = require('path');
const util = require('util');
const ROOT_DIR = path.resolve(__dirname, '..', '..');
const LIB_DIR = path.join(ROOT_DIR, 'lib');
const SRC_DIR = path.join(ROOT_DIR, 'src');
/**
* Checks that `lib/` is up-to-date with `src/`.
*/
describe('babel-relay-plugin', () => {
beforeEach(() => {
jest.addMatchers({
toExist() {
const libPath = this.actual;
return fs.existsSync(libPath);
},
toTransformInto(libPath) {
const srcPath = this.actual;
const libCode = fs.readFileSync(libPath);
const srcCode = fs.readFileSync(srcPath);
this.message = () => util.format(
'Expected `%s` to transform into `%s`. Try running: npm run build',
path.relative(ROOT_DIR, libPath),
path.relative(ROOT_DIR, srcPath)
);
// Cannot use a `===` because of generated comment, newlines, etc.
return libCode.indexOf(babel.transform(srcCode).code) >= 0;
}
});
});
it('has been built properly', () => {
fs.readdirSync(SRC_DIR).forEach(filename => {
if (!filename.endsWith('.js')) {
return;
}
const libPath = path.join(LIB_DIR, filename);
const srcPath = path.join(SRC_DIR, filename);
expect(libPath).toExist();
expect(srcPath).toTransformInto(libPath);
});
});
});
| Add Build Checker for OSS Plugin | Relay: Add Build Checker for OSS Plugin
Summary: I keep forgetting to do this. Others will, too.
This adds a test that makes sure that `lib/` matches `src/`.
Reviewed By: @josephsavona
Differential Revision: D2520980
fb-gh-sync-id: ab8881ea0d22aed9b863ce52c276e263073ecce3
| JavaScript | mit | venepe/relay,yungsters/relay,voideanvalue/relay,NevilleS/relay,cesarandreu/relay,IlyasM/relayWorking,chentsulin/relay,iamchenxin/relay,cpojer/relay,facebook/relay,xuorig/relay,almasakchabayev/relay,josephsavona/relay,facebook/relay,freiksenet/relay,atxwebs/relay,wincent/relay,gabelevi/relay,facebook/relay,dbslone/relay,Aweary/relay,kassens/relay,facebook/relay,rosskevin/relay,NevilleS/relay,andimarek/generic-relay,cesarandreu/relay,apalm/relay,wincent/relay,michaelchum/relay,freiksenet/relay,iamchenxin/relay,voideanvalue/relay,chirag04/relay,wincent/relay,benjaminogles/relay,kassens/relay,gabelevi/relay,wincent/relay,IlyasM/relayWorking,cpojer/relay,kassens/relay,heracek/relay,iamchenxin/relay,forter/generic-relay,atxwebs/relay,josephsavona/relay,apalm/relay,atxwebs/relay,mroch/relay,kassens/relay,cesarandreu/relay,xuorig/relay,freiksenet/relay,michaelchum/relay,Aweary/relay,almasakchabayev/relay,facebook/relay,xuorig/relay,voideanvalue/relay,josephsavona/relay,cpojer/relay,michaelchum/relay,chirag04/relay,iamchenxin/relay,yungsters/relay,NevilleS/relay,xuorig/relay,mroch/relay,xuorig/relay,andimarek/generic-relay,Shopify/relay,venepe/relay,cpojer/relay,chentsulin/relay,gabelevi/relay,mroch/relay,atxwebs/relay,zpao/relay,rosskevin/relay,venepe/relay,IlyasM/relayWorking,heracek/relay,chentsulin/relay,zpao/relay,kassens/relay,voideanvalue/relay,yungsters/relay,Shopify/relay,facebook/relay,dbslone/relay,benjaminogles/relay,kassens/relay,benjaminogles/relay,zpao/relay,voideanvalue/relay,Aweary/relay,voideanvalue/relay,heracek/relay,Shopify/relay,apalm/relay,wincent/relay,wincent/relay,almasakchabayev/relay,xuorig/relay,chirag04/relay,andimarek/generic-relay | ---
+++
@@ -0,0 +1,60 @@
+/**
+ * Copyright 2013-2015, Facebook, Inc.
+ * All rights reserved.
+ *
+ * This source code is licensed under the BSD-style license found in the
+ * LICENSE file in the root directory of this source tree. An additional grant
+ * of patent rights can be found in the PATENTS file in the same directory.
+ *
+ * @fullSyntaxTransform
+ */
+
+'use strict';
+
+const babel = require('babel');
+const fs = require('fs');
+const path = require('path');
+const util = require('util');
+
+const ROOT_DIR = path.resolve(__dirname, '..', '..');
+
+const LIB_DIR = path.join(ROOT_DIR, 'lib');
+const SRC_DIR = path.join(ROOT_DIR, 'src');
+
+/**
+ * Checks that `lib/` is up-to-date with `src/`.
+ */
+describe('babel-relay-plugin', () => {
+ beforeEach(() => {
+ jest.addMatchers({
+ toExist() {
+ const libPath = this.actual;
+ return fs.existsSync(libPath);
+ },
+ toTransformInto(libPath) {
+ const srcPath = this.actual;
+ const libCode = fs.readFileSync(libPath);
+ const srcCode = fs.readFileSync(srcPath);
+ this.message = () => util.format(
+ 'Expected `%s` to transform into `%s`. Try running: npm run build',
+ path.relative(ROOT_DIR, libPath),
+ path.relative(ROOT_DIR, srcPath)
+ );
+ // Cannot use a `===` because of generated comment, newlines, etc.
+ return libCode.indexOf(babel.transform(srcCode).code) >= 0;
+ }
+ });
+ });
+
+ it('has been built properly', () => {
+ fs.readdirSync(SRC_DIR).forEach(filename => {
+ if (!filename.endsWith('.js')) {
+ return;
+ }
+ const libPath = path.join(LIB_DIR, filename);
+ const srcPath = path.join(SRC_DIR, filename);
+ expect(libPath).toExist();
+ expect(srcPath).toTransformInto(libPath);
+ });
+ });
+}); | |
e639dd204db6cd8dfffa0f70f711988c8048f72e | rules.js | rules.js | {
"rules": {
// All data is readable by anyone.
".read": true,
"people": {
// A list of users with their names on the site.
"$userid": {
// Only the user can write their own entry into this list.
".write": "$userid == auth.id"
}
},
"users": {
"$userid": {
// The user is allowed to write everything in their bucket.
".write": "$userid == auth.id",
"following": {
// The following list should only contain actual ids from the "people" list.
"$followingid": {
".validate": "root.child('people').hasChild($followingid)"
}
},
"followers": {
// Anyone can add themself to to this user's followers list.
"$followerid": {
".write": "$followerid == auth.id"
}
},
"feed": {
"$sparkid": {
// User A can write in user B's feed, but only if A is following B, and only for sparks for which they are the author.
".write": "root.child('users/' + $userid + '/following').hasChild(auth.id) && root.child('sparks/' + $sparkid + '/author').val() == auth.id"
}
}
}
},
"sparks": {
// A global list of sparks (the "firehose").
"$sparkid": {
// Modifying an existing spark is not allowed.
".write": "!data.exists()",
// Every spark should have an author and a body.
".validate": "newData.hasChildren(['author', 'content'])",
// A user can attribute a spark only to themselves.
"author": {
".validate": "newData.val() == auth.id"
},
"content": {
".validate": "newData.isString()"
}
}
},
"recent-users": {
// Users can add themselves to the list of users with recent activity.
"$userid": {
".write": "$userid == auth.id"
}
},
"recent-sparks": {
// Authors of sparks can add their sparks to this list.
"$sparkid": {
".write": "root.child('sparks/' + $sparkid + '/author').val() == auth.id"
}
}
}
}
| Check if syntax highlighting is better with .js | Check if syntax highlighting is better with .js
| JavaScript | mit | dieface/firefeed,googlearchive/firefeed,prisacaru/firefeed,googlearchive/firefeed,prisacaru/firefeed,prisacaru/firefeed,dieface/firefeed,googlearchive/firefeed,prisacaru/firefeed,dieface/firefeed,googlearchive/firefeed,dieface/firefeed | ---
+++
@@ -0,0 +1,65 @@
+{
+ "rules": {
+ // All data is readable by anyone.
+ ".read": true,
+ "people": {
+ // A list of users with their names on the site.
+ "$userid": {
+ // Only the user can write their own entry into this list.
+ ".write": "$userid == auth.id"
+ }
+ },
+ "users": {
+ "$userid": {
+ // The user is allowed to write everything in their bucket.
+ ".write": "$userid == auth.id",
+ "following": {
+ // The following list should only contain actual ids from the "people" list.
+ "$followingid": {
+ ".validate": "root.child('people').hasChild($followingid)"
+ }
+ },
+ "followers": {
+ // Anyone can add themself to to this user's followers list.
+ "$followerid": {
+ ".write": "$followerid == auth.id"
+ }
+ },
+ "feed": {
+ "$sparkid": {
+ // User A can write in user B's feed, but only if A is following B, and only for sparks for which they are the author.
+ ".write": "root.child('users/' + $userid + '/following').hasChild(auth.id) && root.child('sparks/' + $sparkid + '/author').val() == auth.id"
+ }
+ }
+ }
+ },
+ "sparks": {
+ // A global list of sparks (the "firehose").
+ "$sparkid": {
+ // Modifying an existing spark is not allowed.
+ ".write": "!data.exists()",
+ // Every spark should have an author and a body.
+ ".validate": "newData.hasChildren(['author', 'content'])",
+ // A user can attribute a spark only to themselves.
+ "author": {
+ ".validate": "newData.val() == auth.id"
+ },
+ "content": {
+ ".validate": "newData.isString()"
+ }
+ }
+ },
+ "recent-users": {
+ // Users can add themselves to the list of users with recent activity.
+ "$userid": {
+ ".write": "$userid == auth.id"
+ }
+ },
+ "recent-sparks": {
+ // Authors of sparks can add their sparks to this list.
+ "$sparkid": {
+ ".write": "root.child('sparks/' + $sparkid + '/author').val() == auth.id"
+ }
+ }
+ }
+} | |
8f5ac9ea7ebf07fb3debc18657f4ba43503d1240 | src/js/framework/dom.js | src/js/framework/dom.js | import {styler as Styler} from "./styler";
class DOM {
constructor() {
this.cache = {};
}
get controls() {
if (this.cache.controls) { return this.cache.controls; }
return this.cache.controls = this.reveal.querySelector(".controls");
}
get controlsLock() {
if (this.cache.controlsLock) { return this.cache.controlsLock; }
let elem = this.document.createElement("div");
Styler.addClass(elem, "controls-lock");
this.reveal.appendChild(elem);
return this.cache.controlsLock = elem;
}
get document() {
if (this.cache.document) { return this.cache.document; }
return this.cache.document = document;
}
get reveal() {
if (this.cache.reveal) { return this.cache.reveal; }
return this.cache.reveal = document.querySelector(".reveal");
}
}
let dom = new DOM();
export {DOM, dom};
| Add helper for retrieving specific DOM elements | Add helper for retrieving specific DOM elements
| JavaScript | mit | tdg5/js4pm,tdg5/js4pm,tdg5/front-end-skills-for-pms,tdg5/front-end-skills-for-pms | ---
+++
@@ -0,0 +1,34 @@
+import {styler as Styler} from "./styler";
+
+class DOM {
+ constructor() {
+ this.cache = {};
+ }
+
+ get controls() {
+ if (this.cache.controls) { return this.cache.controls; }
+ return this.cache.controls = this.reveal.querySelector(".controls");
+ }
+
+ get controlsLock() {
+ if (this.cache.controlsLock) { return this.cache.controlsLock; }
+ let elem = this.document.createElement("div");
+ Styler.addClass(elem, "controls-lock");
+ this.reveal.appendChild(elem);
+ return this.cache.controlsLock = elem;
+ }
+
+ get document() {
+ if (this.cache.document) { return this.cache.document; }
+ return this.cache.document = document;
+ }
+
+ get reveal() {
+ if (this.cache.reveal) { return this.cache.reveal; }
+ return this.cache.reveal = document.querySelector(".reveal");
+ }
+}
+
+let dom = new DOM();
+
+export {DOM, dom}; | |
80555770d64384332f2f1c18cf93232097027933 | http/examples/random-user/random-user.js | http/examples/random-user/random-user.js | import Cycle from '@cycle/core';
import {h, makeDOMDriver} from '@cycle/web';
import {makeHTTPDriver} from '@cycle/http';
function main(responses) {
const USERS_URL = 'http://jsonplaceholder.typicode.com/users/';
let getRandomUser$ = responses.DOM.get('.get-random-user', 'click')
.map(() => {
let randomNum = Math.round(Math.random()*9)+1; // from 1 to 10
return USERS_URL + String(randomNum);
});
let user$ = responses.HTTP
.filter(res$ => res$.request.indexOf(USERS_URL) === 0)
.mergeAll()
.startWith(null);
return {
DOM: user$.map(user =>
h('div.users', [
h('button.get-random-user', 'Get random user'),
user === null ? h('h1.user-name', 'Loading...') :
h('h1.user-name', user.name)
])
),
HTTP: getRandomUser$;
};
}
Cycle.run(main, {
DOM: makeDOMDriver('#app'),
HTTP: makeHTTPDriver()
});
| Add "get random user" example | Add "get random user" example
| JavaScript | mit | maskinoshita/cyclejs,cyclejs/cycle-core,cyclejs/cyclejs,ntilwalli/cyclejs,usm4n/cyclejs,usm4n/cyclejs,feliciousx-open-source/cyclejs,ntilwalli/cyclejs,staltz/cycle,cyclejs/cycle-core,maskinoshita/cyclejs,ntilwalli/cyclejs,usm4n/cyclejs,maskinoshita/cyclejs,feliciousx-open-source/cyclejs,maskinoshita/cyclejs,usm4n/cyclejs,ntilwalli/cyclejs,staltz/cycle,feliciousx-open-source/cyclejs,feliciousx-open-source/cyclejs,cyclejs/cyclejs,cyclejs/cyclejs,cyclejs/cyclejs | ---
+++
@@ -0,0 +1,32 @@
+import Cycle from '@cycle/core';
+import {h, makeDOMDriver} from '@cycle/web';
+import {makeHTTPDriver} from '@cycle/http';
+
+function main(responses) {
+ const USERS_URL = 'http://jsonplaceholder.typicode.com/users/';
+ let getRandomUser$ = responses.DOM.get('.get-random-user', 'click')
+ .map(() => {
+ let randomNum = Math.round(Math.random()*9)+1; // from 1 to 10
+ return USERS_URL + String(randomNum);
+ });
+ let user$ = responses.HTTP
+ .filter(res$ => res$.request.indexOf(USERS_URL) === 0)
+ .mergeAll()
+ .startWith(null);
+
+ return {
+ DOM: user$.map(user =>
+ h('div.users', [
+ h('button.get-random-user', 'Get random user'),
+ user === null ? h('h1.user-name', 'Loading...') :
+ h('h1.user-name', user.name)
+ ])
+ ),
+ HTTP: getRandomUser$;
+ };
+}
+
+Cycle.run(main, {
+ DOM: makeDOMDriver('#app'),
+ HTTP: makeHTTPDriver()
+}); | |
41712642e22faaeddb9d850d37b22d8e1429aa8f | ui/browser/browser-style.js | ui/browser/browser-style.js | /*
Copyright 2016 Mozilla
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.
*/
import ReactFreeStyle from 'react-free-style';
export default ReactFreeStyle.create();
| Create a single Style instance for the entire browser | Create a single Style instance for the entire browser
Signed-off-by: Victor Porof <7d8eebacd0931807085fa6b9af29638ed74e0886@mozilla.com>
| JavaScript | apache-2.0 | jsantell/tofino,mozilla/tofino,jsantell/tofino,jsantell/tofino,mozilla/tofino,bgrins/tofino,bgrins/tofino,mozilla/tofino,victorporof/tofino,jsantell/tofino,mozilla/tofino,bgrins/tofino,bgrins/tofino,victorporof/tofino | ---
+++
@@ -0,0 +1,15 @@
+/*
+Copyright 2016 Mozilla
+
+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.
+*/
+
+import ReactFreeStyle from 'react-free-style';
+
+export default ReactFreeStyle.create(); | |
a5d6e22390cf381767bdd57757211081f973711f | js/components/module-wire.js | js/components/module-wire.js | (function(app) {
'use strict';
var jCore = require('jcore');
var helper = app.helper || require('../helper.js');
var ModuleWire = helper.inherits(function() {
ModuleWire.super_.call(this);
}, jCore.Component);
if (typeof module !== 'undefined' && module.exports)
module.exports = ModuleWire;
else
app.ModuleWire = ModuleWire;
})(this.app || (this.app = {}));
| Add a constructor for a component of the module wire | Add a constructor for a component of the module wire
| JavaScript | mit | ionstage/modular,ionstage/modular | ---
+++
@@ -0,0 +1,15 @@
+(function(app) {
+ 'use strict';
+
+ var jCore = require('jcore');
+ var helper = app.helper || require('../helper.js');
+
+ var ModuleWire = helper.inherits(function() {
+ ModuleWire.super_.call(this);
+ }, jCore.Component);
+
+ if (typeof module !== 'undefined' && module.exports)
+ module.exports = ModuleWire;
+ else
+ app.ModuleWire = ModuleWire;
+})(this.app || (this.app = {})); | |
bb8dbc205387dc84799140dd53f12c9f6ee92df5 | server/migrations/20140722230151-change-recyclingAvailable-to-integer-on-reports-table.js | server/migrations/20140722230151-change-recyclingAvailable-to-integer-on-reports-table.js | module.exports = {
up: function(migration, DataTypes, done) {
migration.changeColumn(
'reports',
'recyclingAvailable',
{type: "integer USING 0"}
).complete(done);
},
down: function(migration, DataTypes, done) {
migration.changeColumn('reports', 'recyclingAvailable', {type: "boolean using false"}).complete(done);
}
}
| Change recyclingAvailable column type to integer | Change recyclingAvailable column type to integer
| JavaScript | mit | open-city/recycling,open-city/recycling,open-austin/mybuildingdoesntrecycle,open-city/recycling,open-austin/mybuildingdoesntrecycle,davidjamesknight/recycling,open-austin/mybuildingdoesntrecycle,davidjamesknight/recycling,davidjamesknight/recycling | ---
+++
@@ -0,0 +1,12 @@
+module.exports = {
+ up: function(migration, DataTypes, done) {
+ migration.changeColumn(
+ 'reports',
+ 'recyclingAvailable',
+ {type: "integer USING 0"}
+ ).complete(done);
+ },
+ down: function(migration, DataTypes, done) {
+ migration.changeColumn('reports', 'recyclingAvailable', {type: "boolean using false"}).complete(done);
+ }
+} | |
2a5bedd9051c1e77ffff22b527ac53eecbb04b9d | src/storage/sessionStorage.js | src/storage/sessionStorage.js | const DEFAULT_KEY = 'redux-simple-auth-session'
export default ({ key = DEFAULT_KEY } = {}) => ({
persist: data => {
sessionStorage.setItem(key, JSON.stringify(data || {}))
},
restore: () => JSON.parse(sessionStorage.getItem(key)) || {}
})
| Write a session storage implementation | Write a session storage implementation
| JavaScript | mit | jerelmiller/redux-simple-auth | ---
+++
@@ -0,0 +1,8 @@
+const DEFAULT_KEY = 'redux-simple-auth-session'
+
+export default ({ key = DEFAULT_KEY } = {}) => ({
+ persist: data => {
+ sessionStorage.setItem(key, JSON.stringify(data || {}))
+ },
+ restore: () => JSON.parse(sessionStorage.getItem(key)) || {}
+}) | |
52c592d303fa43837c85c01cad69e787d74c6c93 | config/dependency-lint.js | config/dependency-lint.js | /* eslint-env node */
'use strict';
module.exports = {
allowedVersions: {
'ember-getowner-polyfill': '^1.0.0 || ^2.0.0',
'ember-inflector': '^1.0.0 || ^2.0.0',
'ember-hash-helper-polyfill': '^0.1.2 || ^0.2.0' // workaround for dep. conflict ember-tooltips/liquid-fire
}
};
| /* eslint-env node */
'use strict';
module.exports = {
allowedVersions: {
'ember-get-config': '^0.2.0', // workaround for dep. conflict ember-cli-mirage/ember-light-table
'ember-getowner-polyfill': '^1.0.0 || ^2.0.0',
'ember-inflector': '^1.0.0 || ^2.0.0',
'ember-hash-helper-polyfill': '^0.1.2 || ^0.2.0' // workaround for dep. conflict ember-tooltips/liquid-fire
}
};
| Allow range of ember-get-config versions | Allow range of ember-get-config versions
| JavaScript | mit | jrjohnson/frontend,djvoa12/frontend,ilios/frontend,ilios/frontend,djvoa12/frontend,thecoolestguy/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,thecoolestguy/frontend | ---
+++
@@ -3,6 +3,7 @@
module.exports = {
allowedVersions: {
+ 'ember-get-config': '^0.2.0', // workaround for dep. conflict ember-cli-mirage/ember-light-table
'ember-getowner-polyfill': '^1.0.0 || ^2.0.0',
'ember-inflector': '^1.0.0 || ^2.0.0',
'ember-hash-helper-polyfill': '^0.1.2 || ^0.2.0' // workaround for dep. conflict ember-tooltips/liquid-fire |
72ba56e76d83c0cd0082ffcb17718c0db4fc9c15 | server/db/db.js | server/db/db.js | const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/codr');
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
// we're connected to codr!
});
| Set up database in mongoose | Set up database in mongoose
| JavaScript | mit | OrderlyPhoenix/OrderlyPhoenix,OrderlyPhoenix/OrderlyPhoenix | ---
+++
@@ -0,0 +1,10 @@
+const mongoose = require('mongoose');
+
+mongoose.connect('mongodb://localhost/codr');
+
+var db = mongoose.connection;
+
+db.on('error', console.error.bind(console, 'connection error:'));
+db.once('open', function() {
+ // we're connected to codr!
+}); | |
86f35f94e89e201263e008a171525bfe6c302b7c | test/specs/deleteFile.spec.js | test/specs/deleteFile.spec.js | var path = require("path"),
fileExists = require("exists-file").sync,
directoryExists = require("directory-exists").sync;
var localFilePath = path.resolve(__dirname, "../testContents/text document.txt"),
localDirPath = path.resolve(__dirname, "../testContents/sub1");
describe("deleteFile", function() {
beforeEach(function() {
this.client = createWebDAVClient(
"http://localhost:9988/webdav/server",
createWebDAVServer.test.username,
createWebDAVServer.test.password
);
clean();
this.server = createWebDAVServer();
return this.server.start();
});
afterEach(function() {
return this.server.stop();
});
it("deletes a remote file", function() {
expect(fileExists(localFilePath)).to.be.true;
return this.client.deleteFile("/text document.txt")
.then(() => {
expect(fileExists(localFilePath)).to.be.false;
});
});
it("deletes a remote file", function() {
expect(fileExists(localFilePath)).to.be.true;
return this.client.deleteFile("/text document.txt")
.then(() => {
expect(fileExists(localFilePath)).to.be.false;
});
});
it("deletes a remote directory", function() {
expect(directoryExists(localDirPath)).to.be.true;
return this.client.deleteFile("/sub1")
.then(() => {
expect(directoryExists(localDirPath)).to.be.false;
});
});
});
| Add tests for deleteFile (failing due to webdav-server DELETE bug) | Add tests for deleteFile (failing due to webdav-server DELETE bug)
| JavaScript | mit | perry-mitchell/webdav-client,perry-mitchell/webdav-client | ---
+++
@@ -0,0 +1,49 @@
+var path = require("path"),
+ fileExists = require("exists-file").sync,
+ directoryExists = require("directory-exists").sync;
+
+var localFilePath = path.resolve(__dirname, "../testContents/text document.txt"),
+ localDirPath = path.resolve(__dirname, "../testContents/sub1");
+
+describe("deleteFile", function() {
+
+ beforeEach(function() {
+ this.client = createWebDAVClient(
+ "http://localhost:9988/webdav/server",
+ createWebDAVServer.test.username,
+ createWebDAVServer.test.password
+ );
+ clean();
+ this.server = createWebDAVServer();
+ return this.server.start();
+ });
+
+ afterEach(function() {
+ return this.server.stop();
+ });
+
+ it("deletes a remote file", function() {
+ expect(fileExists(localFilePath)).to.be.true;
+ return this.client.deleteFile("/text document.txt")
+ .then(() => {
+ expect(fileExists(localFilePath)).to.be.false;
+ });
+ });
+
+ it("deletes a remote file", function() {
+ expect(fileExists(localFilePath)).to.be.true;
+ return this.client.deleteFile("/text document.txt")
+ .then(() => {
+ expect(fileExists(localFilePath)).to.be.false;
+ });
+ });
+
+ it("deletes a remote directory", function() {
+ expect(directoryExists(localDirPath)).to.be.true;
+ return this.client.deleteFile("/sub1")
+ .then(() => {
+ expect(directoryExists(localDirPath)).to.be.false;
+ });
+ });
+
+}); | |
2839dbc4204609571a2ccb7167970dde201be6f4 | core/client/tests/test-helper.js | core/client/tests/test-helper.js | import resolver from './helpers/resolver';
import { setResolver } from 'ember-mocha';
setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
timeout: 5000,
slow: 500
});
/* jshint ignore:end */
| import resolver from './helpers/resolver';
import { setResolver } from 'ember-mocha';
setResolver(resolver);
/* jshint ignore:start */
mocha.setup({
timeout: 15000,
slow: 500
});
/* jshint ignore:end */
| Increase timeout in ember tests | Increase timeout in ember tests
no issue
- increases individual test timeout from 5sec to 15sec
It seems Travis is occasionally _very_ slow and will timeout on heavier acceptance tests resulting in random failures. Hopefully this will reduce the number of random test failures we see.
| JavaScript | mit | RufusMbugua/TheoryOfACoder,benstoltz/Ghost,allanjsx/Ghost,acburdine/Ghost,barbastan/Ghost,daimaqiao/Ghost-Bridge,ngosinafrica/SiteForNGOs,kaychaks/kaushikc.org,kevinansfield/Ghost,hnarayanan/narayanan.co,Japh/shortcoffee,petersucks/blog,syaiful6/Ghost,chris-yoon90/Ghost,edsadr/Ghost,weareleka/blog,madole/diverse-learners,klinker-apps/ghost,handcode7/Ghost,ErisDS/Ghost,e10/Ghost,augbog/Ghost,javorszky/Ghost,Elektro1776/javaPress,MadeOnMars/Ghost,NovaDevelopGroup/Academy,rizkyario/Ghost,e10/Ghost,JohnONolan/Ghost,augbog/Ghost,sebgie/Ghost,disordinary/Ghost,leninhasda/Ghost,wemakeweb/Ghost,ignasbernotas/nullifer,klinker-apps/ghost,vainglori0us/urban-fortnight,riyadhalnur/Ghost,dggr/Ghost-sr,Kaenn/Ghost,denzelwamburu/denzel.xyz,Japh/Ghost,bosung90/Ghost,Japh/Ghost,PeterCxy/Ghost,kevinansfield/Ghost,jaswilli/Ghost,AlexKVal/Ghost,davidmenger/nodejsfan,tidyui/Ghost,dggr/Ghost-sr,jaswilli/Ghost,BlueHatbRit/Ghost,TryGhost/Ghost,sebgie/Ghost,AlexKVal/Ghost,chevex/undoctrinate,TryGhost/Ghost,Gargol/Ghost,zumobi/Ghost,lukekhamilton/Ghost,JohnONolan/Ghost,sunh3/Ghost,petersucks/blog,duyetdev/islab,wemakeweb/Ghost,leonli/ghost,TryGhost/Ghost,syaiful6/Ghost,carlyledavis/Ghost,ManRueda/manrueda-blog,janvt/Ghost,disordinary/Ghost,dbalders/Ghost,Kikobeats/Ghost,leonli/ghost,jomahoney/Ghost,Kikobeats/Ghost,panezhang/Ghost,ashishapy/ghostpy,mohanambati/Ghost,riyadhalnur/Ghost,Trendy/Ghost,ghostchina/Ghost-zh,tidyui/Ghost,barbastan/Ghost,epicmiller/pages,MadeOnMars/Ghost,dqj/Ghost,GroupxDev/javaPress,JulienBrks/Ghost,Yarov/yarov,NovaDevelopGroup/Academy,jgillich/Ghost,Kaenn/Ghost,anijap/PhotoGhost,load11/ghost,acburdine/Ghost,dbalders/Ghost,STANAPO/Ghost,GroupxDev/javaPress,mayconxhh/Ghost,ballPointPenguin/Ghost,javorszky/Ghost,daihuaye/Ghost,singular78/Ghost,novaugust/Ghost,GroupxDev/javaPress,jgillich/Ghost,letsjustfixit/Ghost,adam-paterson/blog,jamesslock/Ghost,PeterCxy/Ghost,madole/diverse-learners,load11/ghost,singular78/Ghost,dqj/Ghost,mohanambati/Ghost,karmakaze/Ghost,Elektro1776/javaPress,SachaG/bjjbot-blog,stridespace/Ghost,obsoleted/Ghost,adam-paterson/blog,Trendy/Ghost,Kaenn/Ghost,lukaszklis/Ghost,ghostchina/Ghost-zh,ckousik/Ghost,mayconxhh/Ghost,obsoleted/Ghost,SkynetInc/steam,akveo/akveo-blog,singular78/Ghost,benstoltz/Ghost,olsio/Ghost,chris-yoon90/Ghost,ngosinafrica/SiteForNGOs,telco2011/Ghost,rizkyario/Ghost,SachaG/bjjbot-blog,BlueHatbRit/Ghost,rizkyario/Ghost,daimaqiao/Ghost-Bridge,RufusMbugua/TheoryOfACoder,daimaqiao/Ghost-Bridge,Elektro1776/javaPress,ManRueda/manrueda-blog,Kikobeats/Ghost,handcode7/Ghost,JulienBrks/Ghost,pollbox/ghostblog,kevinansfield/Ghost,novaugust/Ghost,etanxing/Ghost,Xibao-Lv/Ghost,edsadr/Ghost,Smile42RU/Ghost,ManRueda/manrueda-blog,jorgegilmoreira/ghost,lukaszklis/Ghost,cicorias/Ghost,veyo-care/Ghost,karmakaze/Ghost,lukekhamilton/Ghost,denzelwamburu/denzel.xyz,pollbox/ghostblog,bitjson/Ghost,Gargol/Ghost,kaychaks/kaushikc.org,JohnONolan/Ghost,leninhasda/Ghost,letsjustfixit/Ghost,hnarayanan/narayanan.co,delgermurun/Ghost,janvt/Ghost,akveo/akveo-blog,delgermurun/Ghost,sebgie/Ghost,olsio/Ghost,novaugust/Ghost,cwonrails/Ghost,Yarov/yarov,velimir0xff/Ghost,ignasbernotas/nullifer,STANAPO/Ghost,leonli/ghost,ckousik/Ghost,sangcu/Ghost,JonSmith/Ghost,zumobi/Ghost,velimir0xff/Ghost,patterncoder/patterncoder,daihuaye/Ghost,cwonrails/Ghost,sangcu/Ghost,mohanambati/Ghost,jorgegilmoreira/ghost,NovaDevelopGroup/Academy,letsjustfixit/Ghost,cicorias/Ghost,stridespace/Ghost,sunh3/Ghost,jamesslock/Ghost,cwonrails/Ghost,etanxing/Ghost,GarrethDottin/Habits-Design,ErisDS/Ghost,dbalders/Ghost,Japh/shortcoffee,allanjsx/Ghost,lf2941270/Ghost,weareleka/blog,acburdine/Ghost,jomahoney/Ghost,veyo-care/Ghost,vainglori0us/urban-fortnight,Smile42RU/Ghost,lf2941270/Ghost,telco2011/Ghost,ballPointPenguin/Ghost,GarrethDottin/Habits-Design,allanjsx/Ghost,anijap/PhotoGhost,stridespace/Ghost,davidmenger/nodejsfan,Xibao-Lv/Ghost,epicmiller/pages,duyetdev/islab,vainglori0us/urban-fortnight,ivantedja/ghost,panezhang/Ghost,ErisDS/Ghost,ashishapy/ghostpy,bitjson/Ghost,dggr/Ghost-sr,carlyledavis/Ghost,telco2011/Ghost,JonSmith/Ghost,patterncoder/patterncoder,jorgegilmoreira/ghost,bosung90/Ghost,SkynetInc/steam | ---
+++
@@ -5,7 +5,7 @@
/* jshint ignore:start */
mocha.setup({
- timeout: 5000,
+ timeout: 15000,
slow: 500
});
/* jshint ignore:end */ |
ce7533923404c8bd74b5b767c27cde0f4765b444 | modules/openlmis-web/src/main/webapp/public/js/vaccine/inventory/module/inventory-module.js | modules/openlmis-web/src/main/webapp/public/js/vaccine/inventory/module/inventory-module.js | /*
* Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
*
* Copyright (C) 2015 Clinton Health Access Initiative (CHAI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
*
* This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
angular.module('vaccine-inventory', ['openlmis', 'ngTable','ui.bootstrap.accordion','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
.config(['$routeProvider', function ($routeProvider) {
$routeProvider.
when('/stock-on-hand', {controller:StockOnHandController, templateUrl:'partials/stock-on-hand.html',reloadOnSearch:false,resolve:StockOnHandController.resolve}).
// TODO when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
otherwise({redirectTo:'/stock-on-hand'});
}]).run(function ($rootScope, AuthorizationService) {
}).config(function(angularCombineConfigProvider) {
angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
}).filter('positive', function() {
return function(input) {
if (!input) {
return 0;
}
return Math.abs(input);
};
}); | Add Stock on Hand Module | Add Stock on Hand Module
| JavaScript | agpl-3.0 | USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,USAID-DELIVER-PROJECT/elmis,USAID-DELIVER-PROJECT/elmis,OpenLMIS/open-lmis,OpenLMIS/open-lmis | ---
+++
@@ -0,0 +1,31 @@
+/*
+ * Electronic Logistics Management Information System (eLMIS) is a supply chain management system for health commodities in a developing country setting.
+ *
+ * Copyright (C) 2015 Clinton Health Access Initiative (CHAI). This program was produced for the U.S. Agency for International Development (USAID). It was prepared under the USAID | DELIVER PROJECT, Task Order 4.
+ *
+ * This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
+ *
+ * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details.
+ *
+ * You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>.
+ */
+
+angular.module('vaccine-inventory', ['openlmis', 'ngTable','ui.bootstrap.accordion','angularCombine','ui.bootstrap.modal','ui.bootstrap.pagination'])
+ .config(['$routeProvider', function ($routeProvider) {
+ $routeProvider.
+ when('/stock-on-hand', {controller:StockOnHandController, templateUrl:'partials/stock-on-hand.html',reloadOnSearch:false,resolve:StockOnHandController.resolve}).
+// TODO when('/stock-adjustment', {controller:StockAdjustmentController, templateUrl:'partials/stock-adjustment.html',resolve:StockAdjustmentController.resolve}).
+ otherwise({redirectTo:'/stock-on-hand'});
+ }]).run(function ($rootScope, AuthorizationService) {
+
+ }).config(function(angularCombineConfigProvider) {
+ angularCombineConfigProvider.addConf(/filter-/, '/public/pages/reports/shared/filters.html');
+ }).filter('positive', function() {
+ return function(input) {
+ if (!input) {
+ return 0;
+ }
+
+ return Math.abs(input);
+ };
+ }); | |
4b1ec7b112d30e0888f8361b01561241d8c301e4 | spec/appSpec.js | spec/appSpec.js | /* eslint-env jasmine */
describe('Launching the app', () => {
it('creates a visible window', async () => {
const Application = require('spectron').Application
let app = new Application({
path: 'node_modules/.bin/electron',
args: ['built/index.js']
})
await app.start()
// expect(app.browserWindow.isVisible()).toBe(true)
// expect(false).toBe(true)
// return app.browserWindow.isVisible()
})
})
| Test if the app window is visible | Test if the app window is visible
| JavaScript | agpl-3.0 | briandk/transcriptase,briandk/transcriptase | ---
+++
@@ -0,0 +1,15 @@
+/* eslint-env jasmine */
+
+describe('Launching the app', () => {
+ it('creates a visible window', async () => {
+ const Application = require('spectron').Application
+ let app = new Application({
+ path: 'node_modules/.bin/electron',
+ args: ['built/index.js']
+ })
+ await app.start()
+ // expect(app.browserWindow.isVisible()).toBe(true)
+ // expect(false).toBe(true)
+ // return app.browserWindow.isVisible()
+ })
+}) | |
f0f71c7845c3da22db40df6013e09cfe7beecc46 | expository/towerOfHanoi.js | expository/towerOfHanoi.js | 'use strict';
/*
* Hannoi
*
* Tower solved progress look like as below:
*
* | | | | | | | | | 1 | |
* | 1 | => | | | => | | | => 2 | |
* | 2 | | | 1 3 | 1 3 | |
* 4 3 | 4 3 2 4 | 2 4 | |
*
* The less one must be set on the top of the greater one.
* Greater and less one represent the width or other attribute.
*/
const COLUMN = 3;
const COLUMNHEIGHT = 100;
function main (x, y, z) {
}
module.exports = main
| Add tower of hannoi problem. | Add tower of hannoi problem.
| JavaScript | mit | vanpipy/AlgorithmsBase | ---
+++
@@ -0,0 +1,24 @@
+'use strict';
+
+/*
+ * Hannoi
+ *
+ * Tower solved progress look like as below:
+ *
+ * | | | | | | | | | 1 | |
+ * | 1 | => | | | => | | | => 2 | |
+ * | 2 | | | 1 3 | 1 3 | |
+ * 4 3 | 4 3 2 4 | 2 4 | |
+ *
+ * The less one must be set on the top of the greater one.
+ * Greater and less one represent the width or other attribute.
+ */
+
+const COLUMN = 3;
+const COLUMNHEIGHT = 100;
+
+function main (x, y, z) {
+
+}
+
+module.exports = main | |
0483d3505810bd8aabd2aeafc26bfda816813f5a | app/projects/model.js | app/projects/model.js | var mongoose = require('mongoose');
var schema = require('validate');
var Project = mongoose.model('Project', {
name: {type: String, unique: true},
created: {type: Date, default: new Date()},
rating: {type: Number, default: 0}
});
var validate = function (project) {
var test = schema({
name: {
required: true,
type: 'string',
message: 'A project name is required'
}
}, {typecast: true});
return test.validate(project);
};
/**
* An implementation of the Elo ranking system
*/
var Elo = {
/**
* The K-factor
*/
k: 32,
/**
* Get the expected score for a given player against an opponent
* @param a The actual score of one player
* @param b The actual score of another player
* @return The expected score for the first player
*
* Example:
* playerA_expected = Elo.expected(playerA_actual, playerB_actual);
* playerB_expected = Elo.expected(playerB_actual, playerA_actual);
*/
expected: function (a, b) {
var exponent = (b - a) / 400;
var numerator = 1;
var denominator = 1 + Math.pow(10, exponent);
return numerator / denominator;
},
/**
* Update the rating for a given player
* @param expected The expected score for a player
* @param current The actual score for that player
* @param won True if the player won, false if they lost
* @return The new score for the player
*
* Example, if playerA wins:
* playerA_new = Elo.rate(playerA_expected, playerA_actual, true);
* playerB_new = Elo.rate(playerB_expected, playerB_actual, false);
*/
rate: function (expected, current, won) {
var actual = (won) ? 1 : 0;
return current + (this.k * (actual - expected));
}
};
module.exports = Project;
module.exports.validate = validate;
module.exports.Elo = Elo; | Write simple schema for projects | Write simple schema for projects
| JavaScript | mit | hacksu/kenthackenough,hacksu/kenthackenough | ---
+++
@@ -0,0 +1,68 @@
+var mongoose = require('mongoose');
+var schema = require('validate');
+
+var Project = mongoose.model('Project', {
+ name: {type: String, unique: true},
+ created: {type: Date, default: new Date()},
+ rating: {type: Number, default: 0}
+});
+
+var validate = function (project) {
+ var test = schema({
+ name: {
+ required: true,
+ type: 'string',
+ message: 'A project name is required'
+ }
+ }, {typecast: true});
+ return test.validate(project);
+};
+
+/**
+* An implementation of the Elo ranking system
+*/
+var Elo = {
+
+ /**
+ * The K-factor
+ */
+ k: 32,
+
+ /**
+ * Get the expected score for a given player against an opponent
+ * @param a The actual score of one player
+ * @param b The actual score of another player
+ * @return The expected score for the first player
+ *
+ * Example:
+ * playerA_expected = Elo.expected(playerA_actual, playerB_actual);
+ * playerB_expected = Elo.expected(playerB_actual, playerA_actual);
+ */
+ expected: function (a, b) {
+ var exponent = (b - a) / 400;
+ var numerator = 1;
+ var denominator = 1 + Math.pow(10, exponent);
+ return numerator / denominator;
+ },
+
+ /**
+ * Update the rating for a given player
+ * @param expected The expected score for a player
+ * @param current The actual score for that player
+ * @param won True if the player won, false if they lost
+ * @return The new score for the player
+ *
+ * Example, if playerA wins:
+ * playerA_new = Elo.rate(playerA_expected, playerA_actual, true);
+ * playerB_new = Elo.rate(playerB_expected, playerB_actual, false);
+ */
+ rate: function (expected, current, won) {
+ var actual = (won) ? 1 : 0;
+ return current + (this.k * (actual - expected));
+ }
+
+};
+
+module.exports = Project;
+module.exports.validate = validate;
+module.exports.Elo = Elo; | |
bf00ce887f1f0a8887a05121cc2cca8ffb00c7ea | mapreduce_jobs.js | mapreduce_jobs.js | /* Functions for extracting stats.
* To run these, start the mongo shell w/ the processed db and this file:
* mongo --shell processed mapreduce_jobs.js
* ... then call functions.
* If you need more specifics, like job completion times, it may be easier
* to just copy/paste the lines into the mongo shell.
*/
// Generic reduce function for doing counts
var reduce_count = function(k, vals) {
var sum=0;
for(var i in vals) sum += vals[i];
return sum;
};
// TODO: clean up all these functions to remove duplication, and output
// generic stats
var geo_freq = function() {
m = function() {if (this.lat && this.long) {emit(String([this.lat, this.long]), 1);}};
res = db.commits.mapReduce(m, reduce_count);
total_commits = res.counts.input;
geo_commits = res.counts.emit;
unique_geo = res.counts.output;
fraction_with_geo = geo_commits / total_commits;
geo_sorted = db[res.result].find().sort({"value": -1});
return geo_sorted;
};
var loc_by_freq = function() {
m = function() {if (this.location) {emit(this.location), 1);}};
res = db.commits.mapReduce(m, reduce_count);
total_commits = res.counts.input;
loc_commits = res.counts.emit;
unique_loc = res.counts.output;
fraction_with_loc = loc_commits / total_commits;
loc_sorted = db[res.result].find().sort({"value": -1});
return loc_sorted;
}
var proj_by_commits = function() {
m = function() {emit(this.project, 1);}
res = db.commits.mapReduce(m, reduce_count);
total_commits = res.counts.input;
unique_projects = res.counts.output;
projects_sorted = db[res.result].find().sort({"value": -1});
return projects_sorted;
}
var proj_by_users = function() {
// Phase 1: emit (project, author) keys and ignore values
m = function() {emit({project: this.project, author: this.author}, 1);}
r = function(k, vals) {
var sum=0;
for(var i in vals) sum += vals[i];
return sum;
}
res = db.commits.mapReduce(m, reduce_count);
// Phase 2: group by project, list of authors
m2 = function() {emit(this.project, 1);}
res2 = db.commits.mapReduce(m2, reduce_count);
total_commits = res.counts.input;
unique_projects = res2.counts.output;
projects_sorted = db[res2.result].find().sort({"value": -1});
return projects_sorted;
} | Add sample MapReduce stats jobs | Add sample MapReduce stats jobs
To compute the most popular locations, projects, etc.
| JavaScript | mit | emarschner/gothub,emarschner/gothub,emarschner/gothub,emarschner/gothub | ---
+++
@@ -0,0 +1,66 @@
+/* Functions for extracting stats.
+ * To run these, start the mongo shell w/ the processed db and this file:
+ * mongo --shell processed mapreduce_jobs.js
+ * ... then call functions.
+ * If you need more specifics, like job completion times, it may be easier
+ * to just copy/paste the lines into the mongo shell.
+ */
+
+// Generic reduce function for doing counts
+var reduce_count = function(k, vals) {
+ var sum=0;
+ for(var i in vals) sum += vals[i];
+ return sum;
+};
+
+// TODO: clean up all these functions to remove duplication, and output
+// generic stats
+
+var geo_freq = function() {
+ m = function() {if (this.lat && this.long) {emit(String([this.lat, this.long]), 1);}};
+ res = db.commits.mapReduce(m, reduce_count);
+ total_commits = res.counts.input;
+ geo_commits = res.counts.emit;
+ unique_geo = res.counts.output;
+ fraction_with_geo = geo_commits / total_commits;
+ geo_sorted = db[res.result].find().sort({"value": -1});
+ return geo_sorted;
+};
+
+var loc_by_freq = function() {
+ m = function() {if (this.location) {emit(this.location), 1);}};
+ res = db.commits.mapReduce(m, reduce_count);
+ total_commits = res.counts.input;
+ loc_commits = res.counts.emit;
+ unique_loc = res.counts.output;
+ fraction_with_loc = loc_commits / total_commits;
+ loc_sorted = db[res.result].find().sort({"value": -1});
+ return loc_sorted;
+}
+
+var proj_by_commits = function() {
+ m = function() {emit(this.project, 1);}
+ res = db.commits.mapReduce(m, reduce_count);
+ total_commits = res.counts.input;
+ unique_projects = res.counts.output;
+ projects_sorted = db[res.result].find().sort({"value": -1});
+ return projects_sorted;
+}
+
+var proj_by_users = function() {
+ // Phase 1: emit (project, author) keys and ignore values
+ m = function() {emit({project: this.project, author: this.author}, 1);}
+ r = function(k, vals) {
+ var sum=0;
+ for(var i in vals) sum += vals[i];
+ return sum;
+ }
+ res = db.commits.mapReduce(m, reduce_count);
+ // Phase 2: group by project, list of authors
+ m2 = function() {emit(this.project, 1);}
+ res2 = db.commits.mapReduce(m2, reduce_count);
+ total_commits = res.counts.input;
+ unique_projects = res2.counts.output;
+ projects_sorted = db[res2.result].find().sort({"value": -1});
+ return projects_sorted;
+} | |
c7932da821fb5b11ec76a9aedeafe17d9d6dfdb3 | week-7/variables-objects.js | week-7/variables-objects.js | // JavaScript Variables and Objects
// I worked on this challenge alone
// __________________________________________
// Write your code below.
var secretNumber = 7
var password = "just open the door"
var allowedIn = false
var members = []
members[0] = "John"
members[3] = "Mary"
// __________________________________________
// Test Code: Do not alter code below this line.
function assert(test, message, test_number) {
if (!test) {
console.log(test_number + "false");
throw "ERROR: " + message;
}
console.log(test_number + "true");
return true;
}
assert(
(typeof secretNumber === 'number'),
"The value of secretNumber should be a number.",
"1. "
)
assert(
secretNumber === 7,
"The value of secretNumber should be 7.",
"2. "
)
assert(
typeof password === 'string',
"The value of password should be a string.",
"3. "
)
assert(
password === "just open the door",
"The value of password should be 'just open the door'.",
"4. "
)
assert(
typeof allowedIn === 'boolean',
"The value of allowedIn should be a boolean.",
"5. "
)
assert(
allowedIn === false,
"The value of allowedIn should be false.",
"6. "
)
assert(
members instanceof Array,
"The value of members should be an array",
"7. "
)
assert(
members[0] === "John",
"The first element in the value of members should be 'John'.",
"8. "
)
assert(
members[3] === "Mary",
"The fourth element in the value of members should be 'Mary'.",
"9. "
) | Add file with all test passing | Add file with all test passing
| JavaScript | mit | Michael-Jas/phase-0,Michael-Jas/phase-0,Michael-Jas/phase-0 | ---
+++
@@ -0,0 +1,82 @@
+ // JavaScript Variables and Objects
+
+// I worked on this challenge alone
+
+// __________________________________________
+// Write your code below.
+
+var secretNumber = 7
+var password = "just open the door"
+var allowedIn = false
+var members = []
+members[0] = "John"
+members[3] = "Mary"
+
+
+
+// __________________________________________
+
+// Test Code: Do not alter code below this line.
+
+function assert(test, message, test_number) {
+ if (!test) {
+ console.log(test_number + "false");
+ throw "ERROR: " + message;
+ }
+ console.log(test_number + "true");
+ return true;
+}
+
+assert(
+ (typeof secretNumber === 'number'),
+ "The value of secretNumber should be a number.",
+ "1. "
+)
+
+assert(
+ secretNumber === 7,
+ "The value of secretNumber should be 7.",
+ "2. "
+)
+
+assert(
+ typeof password === 'string',
+ "The value of password should be a string.",
+ "3. "
+)
+
+assert(
+ password === "just open the door",
+ "The value of password should be 'just open the door'.",
+ "4. "
+)
+
+assert(
+ typeof allowedIn === 'boolean',
+ "The value of allowedIn should be a boolean.",
+ "5. "
+)
+
+assert(
+ allowedIn === false,
+ "The value of allowedIn should be false.",
+ "6. "
+)
+
+assert(
+ members instanceof Array,
+ "The value of members should be an array",
+ "7. "
+)
+
+assert(
+ members[0] === "John",
+ "The first element in the value of members should be 'John'.",
+ "8. "
+)
+
+assert(
+ members[3] === "Mary",
+ "The fourth element in the value of members should be 'Mary'.",
+ "9. "
+) | |
143d05297d369507d04044bf8161eb0c64c935b3 | src/utils/package_description.js | src/utils/package_description.js | /**
* @license Apache-2.0
*
* Copyright (c) 2021 The Stdlib Authors.
*
* 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.
*/
// MODULES //
import packageDescriptions from './package_descriptions.js';
// MAIN //
/**
* Returns a package description for a specified documentation version.
*
* @private
* @param {string} pkg - package name
* @param {string} version - documentation version
* @returns {(string|null)} package description
*/
function packageDescription( pkg, version ) {
var desc = packageDescriptions( version );
if ( desc === null ) {
return null;
}
return desc[ pkg ] || null;
}
// EXPORTS //
export default packageDescription;
| Add utility to return a package description for a specified version | Add utility to return a package description for a specified version
| JavaScript | apache-2.0 | stdlib-js/www,stdlib-js/www,stdlib-js/www | ---
+++
@@ -0,0 +1,45 @@
+/**
+* @license Apache-2.0
+*
+* Copyright (c) 2021 The Stdlib Authors.
+*
+* 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.
+*/
+
+// MODULES //
+
+import packageDescriptions from './package_descriptions.js';
+
+
+// MAIN //
+
+/**
+* Returns a package description for a specified documentation version.
+*
+* @private
+* @param {string} pkg - package name
+* @param {string} version - documentation version
+* @returns {(string|null)} package description
+*/
+function packageDescription( pkg, version ) {
+ var desc = packageDescriptions( version );
+ if ( desc === null ) {
+ return null;
+ }
+ return desc[ pkg ] || null;
+}
+
+
+// EXPORTS //
+
+export default packageDescription; | |
d377f6d6e45f3593403b27cf3e828268bb7a1fec | js/views/modals/about/BTCTicker.js | js/views/modals/about/BTCTicker.js | import loadTemplate from '../../../utils/loadTemplate';
import baseVw from '../../baseVw';
import { getExchangeRate } from '../../../utils/currency';
import app from '../../../app';
const RATE_EXPIRY_S = '300';
export default class extends baseVw {
constructor(options = {}) {
super({
className: 'aboutBTCTicker pureFlex alwaysFirst',
...options,
});
this.listenTo(app.settings, 'change:localCurrency', this.updatePrice);
}
get localCurrency() {
return app.settings.get('localCurrency');
}
getCurrentPrice() {
return getExchangeRate(this.localCurrency);
}
updatePrice() {
const latestPrice = this.getCurrentPrice();
if (latestPrice !== this.currentBTCPrice) {
this.currentBTCPrice = latestPrice;
this.render();
}
}
remove() {
clearInterval(this.refreshCode);
super.remove();
}
render() {
if (this.refreshCode == null) {
this.refreshCode = setInterval(() => this.updatePrice(), RATE_EXPIRY_S * 1000);
}
if (this.currentBTCPrice == null) {
this.currentBTCPrice = this.getCurrentPrice();
}
loadTemplate('modals/about/btcticker.html', (t) => {
this.$el.html(t({
currentBTCPrice: this.currentBTCPrice,
localCurrency: this.localCurrency,
}));
});
return this;
}
}
| import loadTemplate from '../../../utils/loadTemplate';
import baseVw from '../../baseVw';
import { getExchangeRate } from '../../../utils/currency';
import app from '../../../app';
const RATE_EXPIRY_S = '300';
export default class extends baseVw {
constructor(options = {}) {
super({
className: 'aboutBTCTicker',
...options,
});
this.listenTo(app.settings, 'change:localCurrency', this.updatePrice);
}
get localCurrency() {
return app.settings.get('localCurrency');
}
getCurrentPrice() {
return getExchangeRate(this.localCurrency);
}
updatePrice() {
const latestPrice = this.getCurrentPrice();
if (latestPrice !== this.currentBTCPrice) {
this.currentBTCPrice = latestPrice;
this.render();
}
}
remove() {
clearInterval(this.refreshCode);
super.remove();
}
render() {
if (this.refreshCode == null) {
this.refreshCode = setInterval(() => this.updatePrice(), RATE_EXPIRY_S * 1000);
}
if (this.currentBTCPrice == null) {
this.currentBTCPrice = this.getCurrentPrice();
}
loadTemplate('modals/about/btcticker.html', (t) => {
this.$el.html(t({
currentBTCPrice: this.currentBTCPrice,
localCurrency: this.localCurrency,
}));
});
return this;
}
}
| Remove unused classes in btc ticker. | Remove unused classes in btc ticker.
| JavaScript | mit | jjeffryes/openbazaar-desktop,srhoulam/openbazaar-desktop,OpenBazaar/openbazaar-desktop,jjeffryes/openbazaar-desktop,srhoulam/openbazaar-desktop,jashot7/openbazaar-desktop,OpenBazaar/openbazaar-desktop,srhoulam/openbazaar-desktop,jashot7/openbazaar-desktop,jjeffryes/openbazaar-desktop,OpenBazaar/openbazaar-desktop,jashot7/openbazaar-desktop | ---
+++
@@ -9,7 +9,7 @@
export default class extends baseVw {
constructor(options = {}) {
super({
- className: 'aboutBTCTicker pureFlex alwaysFirst',
+ className: 'aboutBTCTicker',
...options,
});
|
7bc2711c29d39466d1bfec43ac85bf936fe7a49f | test/coffee_script_redux_test.js | test/coffee_script_redux_test.js | var empower = require('../lib/empower'),
CoffeeScript = require('coffee-script-redux'),
q = require('qunitjs'),
util = require('util'),
tap = (function (qu) {
var qunitTap = require("qunit-tap").qunitTap;
var tap = qunitTap(qu, util.puts, {showSourceOnFailure: false});
qu.init();
qu.config.updateRate = 0;
return tap;
})(q);
q.test('with CoffeeScriptRedux toolchain', function (assert) {
var csCode = 'assert.ok dog.legs == three';
var parseOptions = {raw: true};
var csAST = CoffeeScript.parse(csCode, parseOptions);
var compileOptions = {bare: false};
var jsAST = CoffeeScript.compile(csAST, compileOptions);
assert.ok(jsAST);
//console.log(JSON.stringify(jsAST, null, 4));
var empoweredAst = empower.instrument(jsAST, {destructive: false, strategy: 'inline', source: csCode});
var jsGenerateOptions = {compact: true};
var jsCode = CoffeeScript.js(empoweredAst, jsGenerateOptions);
assert.equal(jsCode, "assert.ok(_pa_.expr(_pa_.binary(_pa_.ident(_pa_.ident(dog,{start:{line:1,column:11}}).legs,{start:{line:1,column:14}})===_pa_.ident(three,{start:{line:1,column:23}}),{start:{line:1,column:20}}),{start:{line:1,column:11}},'assert.ok dog.legs == three'))");
});
| Add test for CoffeeScriptRedux support. | Add test for CoffeeScriptRedux support.
| JavaScript | mit | twada/empower-core,falsandtru/power-assert,power-assert-js/power-assert,twada/power-assert,yagitoshiro/power-assert,twada/power-assert,power-assert-js/empower,power-assert-js/power-assert,twada/empower-core,falsandtru/power-assert,azu/power-assert,saneyuki/power-assert,yagitoshiro/power-assert,power-assert-js/empower,jamestalmage/empower-assert,power-assert-js/espower,azu/power-assert,twada/power-assert-runtime,jamestalmage/empower-assert,saneyuki/power-assert | ---
+++
@@ -0,0 +1,31 @@
+var empower = require('../lib/empower'),
+ CoffeeScript = require('coffee-script-redux'),
+ q = require('qunitjs'),
+ util = require('util'),
+ tap = (function (qu) {
+ var qunitTap = require("qunit-tap").qunitTap;
+ var tap = qunitTap(qu, util.puts, {showSourceOnFailure: false});
+ qu.init();
+ qu.config.updateRate = 0;
+ return tap;
+ })(q);
+
+
+q.test('with CoffeeScriptRedux toolchain', function (assert) {
+ var csCode = 'assert.ok dog.legs == three';
+
+ var parseOptions = {raw: true};
+ var csAST = CoffeeScript.parse(csCode, parseOptions);
+
+ var compileOptions = {bare: false};
+ var jsAST = CoffeeScript.compile(csAST, compileOptions);
+
+ assert.ok(jsAST);
+
+ //console.log(JSON.stringify(jsAST, null, 4));
+ var empoweredAst = empower.instrument(jsAST, {destructive: false, strategy: 'inline', source: csCode});
+
+ var jsGenerateOptions = {compact: true};
+ var jsCode = CoffeeScript.js(empoweredAst, jsGenerateOptions);
+ assert.equal(jsCode, "assert.ok(_pa_.expr(_pa_.binary(_pa_.ident(_pa_.ident(dog,{start:{line:1,column:11}}).legs,{start:{line:1,column:14}})===_pa_.ident(three,{start:{line:1,column:23}}),{start:{line:1,column:20}}),{start:{line:1,column:11}},'assert.ok dog.legs == three'))");
+}); | |
a37c35478735ffd52fb8ef0a7d409a5ab678a30d | logic/account/suspensionChecker.js | logic/account/suspensionChecker.js | var redisClient = require('../redis_client/redisClient').getClient()
var configuration = require('../config/configuration.json')
var utility = require('../utility')
module.exports = {
addToSuspensionList: function(accountHashID, suspendType, callback) {
var suspendTable = TableAccountModel.SuspendStatus[suspendType]
var modelTable = configuration.TableMAAccountModel + accountHashID
var score = utility.getUnixTimeStamp()
var multi = redisClient.multi()
multi.zadd(suspendTable, 'NX', score, accountHashID)
multi.hset(modelTable, configuration.ConstantAMSuspendStatus, suspendType)
multi.exec(function (err, replies) {
if (err)
callback(err, null)
callback(null, configuration.message.userSuspend)
})
},
removeFromSuspensionList: function(accountHashID, callback) {
var suspendTable = TableAccountModel.SuspendStatus[configuration.Enum.SuspendType.None]
var modelTable = configuration.TableMAAccountModel + accountHashID
var multi = redisClient.multi()
multi.zrem(suspendTable, accountHashID)
multi.hset(modelTable, configuration.ConstantAMSuspendStatus, configuration.Enum.SuspendType.None)
multi.exec(function (err, replies) {
if (err)
callback(err, null)
callback(null, configuration.message.userSafe)
})
},
checkAccountSuspension: function(accountHashID, callback) {
var modelTable = configuration.TableMAAccountModel + accountHashID
redisClient.hget(modelTable, configuration.ConstantAMSuspendStatus, function(err, replies) {
if (err)
callback(err, null)
if (replies === configuration.Enum.SuspendType.None)
callback(null, configuration.message.userSafe)
else
callback(null, configuration.message.userSuspend)
}
}
}
| Implement Account Suspension Checker Module for Add/Remove/Check Suspension | Implement Account Suspension Checker Module for Add/Remove/Check Suspension
| JavaScript | mit | Flieral/AAA-Service | ---
+++
@@ -0,0 +1,44 @@
+var redisClient = require('../redis_client/redisClient').getClient()
+var configuration = require('../config/configuration.json')
+var utility = require('../utility')
+
+module.exports = {
+ addToSuspensionList: function(accountHashID, suspendType, callback) {
+ var suspendTable = TableAccountModel.SuspendStatus[suspendType]
+ var modelTable = configuration.TableMAAccountModel + accountHashID
+ var score = utility.getUnixTimeStamp()
+ var multi = redisClient.multi()
+ multi.zadd(suspendTable, 'NX', score, accountHashID)
+ multi.hset(modelTable, configuration.ConstantAMSuspendStatus, suspendType)
+ multi.exec(function (err, replies) {
+ if (err)
+ callback(err, null)
+ callback(null, configuration.message.userSuspend)
+ })
+ },
+
+ removeFromSuspensionList: function(accountHashID, callback) {
+ var suspendTable = TableAccountModel.SuspendStatus[configuration.Enum.SuspendType.None]
+ var modelTable = configuration.TableMAAccountModel + accountHashID
+ var multi = redisClient.multi()
+ multi.zrem(suspendTable, accountHashID)
+ multi.hset(modelTable, configuration.ConstantAMSuspendStatus, configuration.Enum.SuspendType.None)
+ multi.exec(function (err, replies) {
+ if (err)
+ callback(err, null)
+ callback(null, configuration.message.userSafe)
+ })
+ },
+
+ checkAccountSuspension: function(accountHashID, callback) {
+ var modelTable = configuration.TableMAAccountModel + accountHashID
+ redisClient.hget(modelTable, configuration.ConstantAMSuspendStatus, function(err, replies) {
+ if (err)
+ callback(err, null)
+ if (replies === configuration.Enum.SuspendType.None)
+ callback(null, configuration.message.userSafe)
+ else
+ callback(null, configuration.message.userSuspend)
+ }
+ }
+} | |
88d4ed807e0a3ebe06d4573722dca44df9ea2d92 | node/src/main/generic-plugin.js | node/src/main/generic-plugin.js |
'use strict';
var common = require('./common');
function Parser(selector, name, fields) {
this.name = name;
this.parse = function parse(services) {
var instance = common.getInstance(services, selector);
if (!instance) {
return null;
}
var details = instance.credentials;
if (!details) {
return null;
}
var result = common.parse(instance);
fields.forEach(function (field) {
if (details[field] !== undefined || details[field] !== null) {
result[field] = details[field];
}
});
return result;
};
}
module.exports = {
Parser : Parser
};
| Add a plugin that can be configured through the constructor. | Add a plugin that can be configured through the constructor.
| JavaScript | mit | mattunderscorechampion/vcap-services-parser | ---
+++
@@ -0,0 +1,35 @@
+
+'use strict';
+
+var common = require('./common');
+
+function Parser(selector, name, fields) {
+ this.name = name;
+
+ this.parse = function parse(services) {
+ var instance = common.getInstance(services, selector);
+ if (!instance) {
+ return null;
+ }
+
+ var details = instance.credentials;
+
+ if (!details) {
+ return null;
+ }
+
+ var result = common.parse(instance);
+
+ fields.forEach(function (field) {
+ if (details[field] !== undefined || details[field] !== null) {
+ result[field] = details[field];
+ }
+ });
+
+ return result;
+ };
+}
+
+module.exports = {
+ Parser : Parser
+}; | |
fa56f9ba64a32e8e998ccc2a598227f67ddd5090 | utils/word-count.js | utils/word-count.js | export default function (s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ''); // exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, ' '); // 2 or more space to 1
s = s.replace(/\n /, '\n'); // exclude newline with a start spacing
return s.split(' ').length;
} | export default function (s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ''); // exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, ' '); // 2 or more space to 1
s = s.replace(/\n /gi, '\n'); // exclude newline with a start spacing
s = s.replace(/\n+/gi, '\n');
return s.split(/ |\n/).length;
} | Fix word count in ember. | Fix word count in ember.
| JavaScript | mit | JohnONolan/Ghost-Admin,dbalders/Ghost-Admin,airycanon/Ghost-Admin,dbalders/Ghost-Admin,acburdine/Ghost-Admin,airycanon/Ghost-Admin,acburdine/Ghost-Admin,TryGhost/Ghost-Admin,kevinansfield/Ghost-Admin,kevinansfield/Ghost-Admin,TryGhost/Ghost-Admin,JohnONolan/Ghost-Admin | ---
+++
@@ -1,6 +1,7 @@
export default function (s) {
s = s.replace(/(^\s*)|(\s*$)/gi, ''); // exclude start and end white-space
s = s.replace(/[ ]{2,}/gi, ' '); // 2 or more space to 1
- s = s.replace(/\n /, '\n'); // exclude newline with a start spacing
- return s.split(' ').length;
+ s = s.replace(/\n /gi, '\n'); // exclude newline with a start spacing
+ s = s.replace(/\n+/gi, '\n');
+ return s.split(/ |\n/).length;
} |
b833aa48e93095896448d1bf8bf998256a5567ee | test/mjsunit/test-keep-alive.js | test/mjsunit/test-keep-alive.js | // This test requires the program "ab"
process.mixin(require("./common"));
http = require("http");
sys = require("sys");
PORT = 8891;
body = "hello world\n";
server = http.createServer(function (req, res) {
res.sendHeader(200, {
"Content-Length": body.length,
"Content-Type": "text/plain",
});
res.sendBody(body);
res.finish();
});
server.listen(PORT);
var keepAliveReqSec = 0;
var normalReqSec = 0;
function error (msg) {
throw new Error("ERROR. 'ab' not installed? " + msg);
}
function runAb(opts, callback) {
sys.exec("ab " + opts + " http://localhost:" + PORT + "/")
.addErrback(error)
.addCallback(function (out) {
var matches = /Requests per second:\s*(\d+)\./mi.exec(out);
var reqSec = parseInt(matches[1]);
matches = /Keep-Alive requests:\s*(\d+)/mi.exec(out);
var keepAliveRequests;
if (matches) {
keepAliveRequests = parseInt(matches[1]);
} else {
keepAliveRequests = 0;
}
callback(reqSec, keepAliveRequests);
});
}
runAb("-k -c 100 -t 2", function (reqSec, keepAliveRequests) {
keepAliveReqSec = reqSec;
assertTrue(keepAliveRequests > 0);
puts("keep-alive: " + keepAliveReqSec + " req/sec");
runAb("-c 100 -t 2", function (reqSec, keepAliveRequests) {
normalReqSec = reqSec;
assertEquals(0, keepAliveRequests);
puts("normal: " + normalReqSec + " req/sec");
server.close();
});
});
process.addListener("exit", function () {
assertTrue(normalReqSec > 50);
assertTrue(keepAliveReqSec > 50);
assertTrue(normalReqSec < keepAliveReqSec);
});
| Add test to ensure the server can handle keep-alive | Add test to ensure the server can handle keep-alive
| JavaScript | apache-2.0 | dreamllq/node,dreamllq/node,dreamllq/node,dreamllq/node,dreamllq/node,dreamllq/node,isaacs/nshtools,dreamllq/node,dreamllq/node,dreamllq/node | ---
+++
@@ -0,0 +1,61 @@
+// This test requires the program "ab"
+process.mixin(require("./common"));
+http = require("http");
+sys = require("sys");
+PORT = 8891;
+
+body = "hello world\n";
+server = http.createServer(function (req, res) {
+ res.sendHeader(200, {
+ "Content-Length": body.length,
+ "Content-Type": "text/plain",
+ });
+ res.sendBody(body);
+ res.finish();
+});
+server.listen(PORT);
+
+var keepAliveReqSec = 0;
+var normalReqSec = 0;
+
+function error (msg) {
+ throw new Error("ERROR. 'ab' not installed? " + msg);
+}
+
+function runAb(opts, callback) {
+ sys.exec("ab " + opts + " http://localhost:" + PORT + "/")
+ .addErrback(error)
+ .addCallback(function (out) {
+ var matches = /Requests per second:\s*(\d+)\./mi.exec(out);
+ var reqSec = parseInt(matches[1]);
+
+ matches = /Keep-Alive requests:\s*(\d+)/mi.exec(out);
+ var keepAliveRequests;
+ if (matches) {
+ keepAliveRequests = parseInt(matches[1]);
+ } else {
+ keepAliveRequests = 0;
+ }
+
+ callback(reqSec, keepAliveRequests);
+ });
+}
+
+runAb("-k -c 100 -t 2", function (reqSec, keepAliveRequests) {
+ keepAliveReqSec = reqSec;
+ assertTrue(keepAliveRequests > 0);
+ puts("keep-alive: " + keepAliveReqSec + " req/sec");
+
+ runAb("-c 100 -t 2", function (reqSec, keepAliveRequests) {
+ normalReqSec = reqSec;
+ assertEquals(0, keepAliveRequests);
+ puts("normal: " + normalReqSec + " req/sec");
+ server.close();
+ });
+});
+
+process.addListener("exit", function () {
+ assertTrue(normalReqSec > 50);
+ assertTrue(keepAliveReqSec > 50);
+ assertTrue(normalReqSec < keepAliveReqSec);
+}); | |
b56581fb002c5d54fe1a83c5d2c738912ab680b5 | js/components/developer/job-preview-screen/jobTypeCardPreview.js | js/components/developer/job-preview-screen/jobTypeCardPreview.js | import React, { Component } from 'react';
import { Card } from 'native-base';
import CardImageHeader from '../common/cardImageHeader';
import SimpleCardBody from '../common/simpleCardBody';
export default class JobTypeCardPreview extends Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
cover: React.PropTypes.string.isRequired,
icon: React.PropTypes.string.isRequired,
subtitle: React.PropTypes.string.isRequired,
};
render() {
return (
<Card>
<CardImageHeader cover={this.props.cover} icon={this.props.icon} />
<SimpleCardBody title={this.props.title} subtitle={this.props.subtitle} />
</Card>
);
}
}
| Create job type card preview component | Create job type card preview component
| JavaScript | mit | justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client,justarrived/p2p-client | ---
+++
@@ -0,0 +1,23 @@
+import React, { Component } from 'react';
+import { Card } from 'native-base';
+
+import CardImageHeader from '../common/cardImageHeader';
+import SimpleCardBody from '../common/simpleCardBody';
+
+export default class JobTypeCardPreview extends Component {
+ static propTypes = {
+ title: React.PropTypes.string.isRequired,
+ cover: React.PropTypes.string.isRequired,
+ icon: React.PropTypes.string.isRequired,
+ subtitle: React.PropTypes.string.isRequired,
+ };
+
+ render() {
+ return (
+ <Card>
+ <CardImageHeader cover={this.props.cover} icon={this.props.icon} />
+ <SimpleCardBody title={this.props.title} subtitle={this.props.subtitle} />
+ </Card>
+ );
+ }
+} | |
71d4bea94ed2b822d8efae09d1f2e0a657ace1fd | js/lib/saveable.js | js/lib/saveable.js | /*global lib, JSON */
lib.saveable = function (_public, _protected, key) {
if (!JSON) {
throw new Error("JSON does not exist");
}
_public.save = function () {
return lib.storage.setItem(key, JSON.stringify(_public.attributes()));
};
_public.fetch = function () {
var data = lib.storage.getItem(key);
if (data) {
data = JSON.parse(data);
}
return data;
};
_public.loadWithDefaults = function (initialData) {
var saved = _public.fetch();
if (saved) {
_public.attributes(saved);
} else {
_public.attributes(initialData);
_public.save();
}
};
_public.clearStorage = function () {
lib.storage.setItem(key, undefined);
};
return _public;
};
| Add a way to save & fetch a model's attributes to/from local storage. | Add a way to save & fetch a model's attributes to/from local storage. | JavaScript | mit | rapportive-oss/model-r,rapportive-oss/model-r | ---
+++
@@ -0,0 +1,35 @@
+/*global lib, JSON */
+lib.saveable = function (_public, _protected, key) {
+ if (!JSON) {
+ throw new Error("JSON does not exist");
+ }
+
+ _public.save = function () {
+ return lib.storage.setItem(key, JSON.stringify(_public.attributes()));
+ };
+
+ _public.fetch = function () {
+ var data = lib.storage.getItem(key);
+ if (data) {
+ data = JSON.parse(data);
+ }
+ return data;
+ };
+
+ _public.loadWithDefaults = function (initialData) {
+ var saved = _public.fetch();
+
+ if (saved) {
+ _public.attributes(saved);
+ } else {
+ _public.attributes(initialData);
+ _public.save();
+ }
+ };
+
+ _public.clearStorage = function () {
+ lib.storage.setItem(key, undefined);
+ };
+
+ return _public;
+}; | |
0e4fe82f6f0b4ed5a9d93a626fb780023bca156b | test/unit/UserTest.js | test/unit/UserTest.js |
define(
[
'chai',
'sinon',
'fixtures',
'argumenta/widgets/User',
'argumenta/widgets/Base',
'argumenta/config'
],
function(chai, undefined, fixtures, User, Base, Config) {
var assert = chai.assert;
var baseUrl = Config.baseUrl;
// Helpers
var withUser = function() {
var user = new User();
user.element.appendTo('body');
assert.lengthOf(
$('body').find(user.element), 1,
'Widget present in DOM.'
);
return user;
};
// Tests
describe('User', function() {
it('should be a function', function() {
assert.isFunction(User);
});
it('should include a moduleID', function() {
assert.equal(User.prototype.moduleID, 'User');
});
describe('new User( options, element )', function() {
it('should return a new User widget', sinon.test(function() {
var server = sinon.fakeServer.create();
var user = new User();
assert.instanceOf(
user, Base,
'User widgets inherit from Base.'
);
assert.instanceOf(
user, User,
'User widgets are instances of User.'
);
}));
});
});
});
| Add basic tests for user widget. | Add basic tests for user widget.
| JavaScript | mit | argumenta/argumenta-widgets,argumenta/argumenta-widgets | ---
+++
@@ -0,0 +1,56 @@
+
+define(
+[
+ 'chai',
+ 'sinon',
+ 'fixtures',
+ 'argumenta/widgets/User',
+ 'argumenta/widgets/Base',
+ 'argumenta/config'
+],
+function(chai, undefined, fixtures, User, Base, Config) {
+
+ var assert = chai.assert;
+ var baseUrl = Config.baseUrl;
+
+ // Helpers
+
+ var withUser = function() {
+ var user = new User();
+ user.element.appendTo('body');
+ assert.lengthOf(
+ $('body').find(user.element), 1,
+ 'Widget present in DOM.'
+ );
+ return user;
+ };
+
+ // Tests
+
+ describe('User', function() {
+
+ it('should be a function', function() {
+ assert.isFunction(User);
+ });
+
+ it('should include a moduleID', function() {
+ assert.equal(User.prototype.moduleID, 'User');
+ });
+
+ describe('new User( options, element )', function() {
+
+ it('should return a new User widget', sinon.test(function() {
+ var server = sinon.fakeServer.create();
+ var user = new User();
+ assert.instanceOf(
+ user, Base,
+ 'User widgets inherit from Base.'
+ );
+ assert.instanceOf(
+ user, User,
+ 'User widgets are instances of User.'
+ );
+ }));
+ });
+ });
+}); | |
61a136ef8639eba98c058bb04698813552e7ade8 | src/commands/general/delet-this.js | src/commands/general/delet-this.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
const Commando = require('discord.js-commando');
const Helpers = require('../../util/helpers.js');
module.exports = class InfoCommand extends Commando.Command {
constructor(client) {
super(client, {
name: 'deletthis',
aliases: ['delet', 'dt', 'plsno', 'why'],
group: 'commands',
memberName: 'delet-this',
description: 'Delete the most recent message sent by the bot, in case it was really bad. In future, you might want to use the `filter` command to change hte server-wide filter. See `help filter`.',
examples: ['deletthis', 'delet', 'dt', 'plsno', 'why'],
});
}
async run(msg) {
const messages = msg.channel.messages.size > 20 ? msg.channel.messages : await msg.channel.fetchMessages();
const myRecentMessages = messages.filter(message => message.author.id === this.client.user.id);
const latestMessage = myRecentMessages.reduce((previous, message) => message.createdAt > previous.createdAt ? message : previous);
if (!latestMessage) return msg.reply('Couldn\'t find a recent message to delete! Call an admin instead.');
return latestMessage.delete();
}
};
| Add deletthis command, for when images are just that bad | Add deletthis command, for when images are just that bad
| JavaScript | mpl-2.0 | BytewaveMLP/Randibooru.js | ---
+++
@@ -0,0 +1,29 @@
+/* This Source Code Form is subject to the terms of the Mozilla Public
+ * License, v. 2.0. If a copy of the MPL was not distributed with this
+ * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
+
+const Commando = require('discord.js-commando');
+const Helpers = require('../../util/helpers.js');
+
+module.exports = class InfoCommand extends Commando.Command {
+ constructor(client) {
+ super(client, {
+ name: 'deletthis',
+ aliases: ['delet', 'dt', 'plsno', 'why'],
+ group: 'commands',
+ memberName: 'delet-this',
+ description: 'Delete the most recent message sent by the bot, in case it was really bad. In future, you might want to use the `filter` command to change hte server-wide filter. See `help filter`.',
+ examples: ['deletthis', 'delet', 'dt', 'plsno', 'why'],
+ });
+ }
+
+ async run(msg) {
+ const messages = msg.channel.messages.size > 20 ? msg.channel.messages : await msg.channel.fetchMessages();
+ const myRecentMessages = messages.filter(message => message.author.id === this.client.user.id);
+ const latestMessage = myRecentMessages.reduce((previous, message) => message.createdAt > previous.createdAt ? message : previous);
+
+ if (!latestMessage) return msg.reply('Couldn\'t find a recent message to delete! Call an admin instead.');
+
+ return latestMessage.delete();
+ }
+}; | |
cd54d10d9f9cd27e93b6c0119f0daa20c729ceeb | files/bootstrap.hover-dropdown/2.0.11/bootstrap-hover-dropdown.min.js | files/bootstrap.hover-dropdown/2.0.11/bootstrap-hover-dropdown.min.js | /**
* Project: Bootstrap Hover Dropdown
* Author: Cameron Spear
* Contributors: Mattia Larentis
*
* Dependencies: Bootstrap's Dropdown plugin, jQuery
*
* A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
*
* License: MIT
*
* http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
*/(function(e,t,n){var r=e();e.fn.dropdownHover=function(n){if("ontouchstart"in document)return this;r=r.add(this.parent());return this.each(function(){function h(e){r.find(":focus").blur();l.instantlyCloseOthers===!0&&r.removeClass("open");t.clearTimeout(c);s.addClass("open");i.trigger(a)}var i=e(this),s=i.parent(),o={delay:500,instantlyCloseOthers:!0},u={delay:e(this).data("delay"),instantlyCloseOthers:e(this).data("close-others")},a="show.bs.dropdown",f="hide.bs.dropdown",l=e.extend(!0,{},o,n,u),c;s.hover(function(e){if(s.hasClass("open")&&!i.is(e.target))return!0;h(e)},function(){c=t.setTimeout(function(){s.removeClass("open");i.trigger(f)},l.delay)});i.hover(function(e){if(!s.hasClass("open")&&!s.is(e.target))return!0;h(e)});s.find(".dropdown-submenu").each(function(){var n=e(this),r;n.hover(function(){t.clearTimeout(r);n.children(".dropdown-menu").show();n.siblings().children(".dropdown-menu").hide()},function(){var e=n.children(".dropdown-menu");r=t.setTimeout(function(){e.hide()},l.delay)})})})};e(document).ready(function(){e('[data-hover="dropdown"]').dropdownHover()})})(jQuery,this);
| Update project bootstrap-hover-dropdown to 2.0.11 | Update project bootstrap-hover-dropdown to 2.0.11
| JavaScript | mit | spud2451/jsdelivr,Sneezry/jsdelivr,markcarver/jsdelivr,afghanistanyn/jsdelivr,royswastik/jsdelivr,stevelacy/jsdelivr,MaxMillion/jsdelivr,evilangelmd/jsdelivr,siscia/jsdelivr,leebyron/jsdelivr,CTres/jsdelivr,leebyron/jsdelivr,MenZil/jsdelivr,cake654326/jsdelivr,MenZil/jsdelivr,dandv/jsdelivr,fchasen/jsdelivr,asimihsan/jsdelivr,algolia/jsdelivr,alexmojaki/jsdelivr,alexmojaki/jsdelivr,anilanar/jsdelivr,cedricbousmanne/jsdelivr,wallin/jsdelivr,fchasen/jsdelivr,dpellier/jsdelivr,Third9/jsdelivr,gregorypratt/jsdelivr,afghanistanyn/jsdelivr,jtblin/jsdelivr,ajkj/jsdelivr,markcarver/jsdelivr,sahat/jsdelivr,towerz/jsdelivr,siscia/jsdelivr,ramda/jsdelivr,petkaantonov/jsdelivr,gregorypratt/jsdelivr,fchasen/jsdelivr,ntd/jsdelivr,photonstorm/jsdelivr,cesarmarinhorj/jsdelivr,hubdotcom/jsdelivr,megawac/jsdelivr,ajkj/jsdelivr,markcarver/jsdelivr,Heark/jsdelivr,l3dlp/jsdelivr,cake654326/jsdelivr,ramda/jsdelivr,moay/jsdelivr,spud2451/jsdelivr,ndamofli/jsdelivr,yaplas/jsdelivr,vebin/jsdelivr,MichaelSL/jsdelivr,hubdotcom/jsdelivr,stevelacy/jsdelivr,dnbard/jsdelivr,CTres/jsdelivr,RoberMac/jsdelivr,moay/jsdelivr,vvo/jsdelivr,MenZil/jsdelivr,megawac/jsdelivr,towerz/jsdelivr,sahat/jsdelivr,siscia/jsdelivr,ntd/jsdelivr,ManrajGrover/jsdelivr,zhuwenxuan/qyerCDN,cake654326/jsdelivr,markcarver/jsdelivr,bonbon197/jsdelivr,petkaantonov/jsdelivr,photonstorm/jsdelivr,siscia/jsdelivr,ManrajGrover/jsdelivr,photonstorm/jsdelivr,oller/jsdelivr,ndamofli/jsdelivr,garrypolley/jsdelivr,tunnckoCore/jsdelivr,walkermatt/jsdelivr,zhuwenxuan/qyerCDN,evilangelmd/jsdelivr,Kingside/jsdelivr,wallin/jsdelivr,anilanar/jsdelivr,gregorypratt/jsdelivr,towerz/jsdelivr,dpellier/jsdelivr,tomByrer/jsdelivr,Metrakit/jsdelivr,leebyron/jsdelivr,RoberMac/jsdelivr,spud2451/jsdelivr,MichaelSL/jsdelivr,jtblin/jsdelivr,Metrakit/jsdelivr,royswastik/jsdelivr,EragonJ/jsdelivr,ajkj/jsdelivr,Kingside/jsdelivr,hubdotcom/jsdelivr,vebin/jsdelivr,justincy/jsdelivr,Kingside/jsdelivr,royswastik/jsdelivr,fchasen/jsdelivr,korusdipl/jsdelivr,ManrajGrover/jsdelivr,therob3000/jsdelivr,ajibolam/jsdelivr,ajibolam/jsdelivr,tunnckoCore/jsdelivr,tunnckoCore/jsdelivr,dnbard/jsdelivr,wallin/jsdelivr,oller/jsdelivr,afghanistanyn/jsdelivr,MichaelSL/jsdelivr,Swatinem/jsdelivr,alexmojaki/jsdelivr,cognitom/jsdelivr,labsvisual/jsdelivr,Sneezry/jsdelivr,AdityaManohar/jsdelivr,royswastik/jsdelivr,vousk/jsdelivr,asimihsan/jsdelivr,vousk/jsdelivr,EragonJ/jsdelivr,korusdipl/jsdelivr,ntd/jsdelivr,l3dlp/jsdelivr,asimihsan/jsdelivr,dpellier/jsdelivr,royswastik/jsdelivr,dnbard/jsdelivr,dpellier/jsdelivr,vebin/jsdelivr,bdukes/jsdelivr,vvo/jsdelivr,petkaantonov/jsdelivr,Kingside/jsdelivr,moay/jsdelivr,korusdipl/jsdelivr,stevelacy/jsdelivr,Swatinem/jsdelivr,labsvisual/jsdelivr,algolia/jsdelivr,yaplas/jsdelivr,garrypolley/jsdelivr,bonbon197/jsdelivr,rtenshi/jsdelivr,stevelacy/jsdelivr,therob3000/jsdelivr,cesarmarinhorj/jsdelivr,gregorypratt/jsdelivr,yyx990803/jsdelivr,bonbon197/jsdelivr,jtblin/jsdelivr,MichaelSL/jsdelivr,cedricbousmanne/jsdelivr,spud2451/jsdelivr,Valve/jsdelivr,ndamofli/jsdelivr,fchasen/jsdelivr,evilangelmd/jsdelivr,firulais/jsdelivr,yyx990803/jsdelivr,asimihsan/jsdelivr,walkermatt/jsdelivr,leebyron/jsdelivr,RoberMac/jsdelivr,algolia/jsdelivr,rtenshi/jsdelivr,dandv/jsdelivr,CTres/jsdelivr,Metrakit/jsdelivr,ajkj/jsdelivr,ajibolam/jsdelivr,Valve/jsdelivr,megawac/jsdelivr,tunnckoCore/jsdelivr,RoberMac/jsdelivr,siscia/jsdelivr,rtenshi/jsdelivr,firulais/jsdelivr,yaplas/jsdelivr,Heark/jsdelivr,l3dlp/jsdelivr,walkermatt/jsdelivr,ramda/jsdelivr,moay/jsdelivr,justincy/jsdelivr,ajibolam/jsdelivr,Third9/jsdelivr,korusdipl/jsdelivr,cesarmarinhorj/jsdelivr,dandv/jsdelivr,vebin/jsdelivr,AdityaManohar/jsdelivr,ntd/jsdelivr,ManrajGrover/jsdelivr,cake654326/jsdelivr,cesarmarinhorj/jsdelivr,dnbard/jsdelivr,Swatinem/jsdelivr,MaxMillion/jsdelivr,Valve/jsdelivr,megawac/jsdelivr,ndamofli/jsdelivr,MaxMillion/jsdelivr,photonstorm/jsdelivr,rtenshi/jsdelivr,Third9/jsdelivr,CTres/jsdelivr,justincy/jsdelivr,Metrakit/jsdelivr,vvo/jsdelivr,bdukes/jsdelivr,MenZil/jsdelivr,Swatinem/jsdelivr,Metrakit/jsdelivr,yyx990803/jsdelivr,l3dlp/jsdelivr,MichaelSL/jsdelivr,tomByrer/jsdelivr,cedricbousmanne/jsdelivr,cake654326/jsdelivr,stevelacy/jsdelivr,hubdotcom/jsdelivr,tomByrer/jsdelivr,afghanistanyn/jsdelivr,firulais/jsdelivr,asimihsan/jsdelivr,Third9/jsdelivr,markcarver/jsdelivr,bonbon197/jsdelivr,vebin/jsdelivr,Third9/jsdelivr,sahat/jsdelivr,dpellier/jsdelivr,walkermatt/jsdelivr,korusdipl/jsdelivr,Sneezry/jsdelivr,cedricbousmanne/jsdelivr,vousk/jsdelivr,cesarmarinhorj/jsdelivr,labsvisual/jsdelivr,moay/jsdelivr,vvo/jsdelivr,Heark/jsdelivr,bdukes/jsdelivr,anilanar/jsdelivr,wallin/jsdelivr,AdityaManohar/jsdelivr,ndamofli/jsdelivr,dandv/jsdelivr,rtenshi/jsdelivr,AdityaManohar/jsdelivr,alexmojaki/jsdelivr,firulais/jsdelivr,oller/jsdelivr,vvo/jsdelivr,algolia/jsdelivr,justincy/jsdelivr,towerz/jsdelivr,ntd/jsdelivr,wallin/jsdelivr,bdukes/jsdelivr,Swatinem/jsdelivr,ajkj/jsdelivr,MaxMillion/jsdelivr,CTres/jsdelivr,walkermatt/jsdelivr,garrypolley/jsdelivr,therob3000/jsdelivr,evilangelmd/jsdelivr,AdityaManohar/jsdelivr,Heark/jsdelivr,towerz/jsdelivr,oller/jsdelivr,alexmojaki/jsdelivr,cognitom/jsdelivr,firulais/jsdelivr,zhuwenxuan/qyerCDN,yyx990803/jsdelivr,cognitom/jsdelivr,Sneezry/jsdelivr,Valve/jsdelivr,anilanar/jsdelivr,therob3000/jsdelivr,cognitom/jsdelivr,dnbard/jsdelivr,vousk/jsdelivr,cognitom/jsdelivr,jtblin/jsdelivr,MaxMillion/jsdelivr,afghanistanyn/jsdelivr,spud2451/jsdelivr,leebyron/jsdelivr,ajibolam/jsdelivr,dandv/jsdelivr,Heark/jsdelivr,evilangelmd/jsdelivr,jtblin/jsdelivr,ManrajGrover/jsdelivr,yyx990803/jsdelivr,anilanar/jsdelivr,megawac/jsdelivr,tomByrer/jsdelivr,therob3000/jsdelivr,Valve/jsdelivr,oller/jsdelivr,cedricbousmanne/jsdelivr,MenZil/jsdelivr,justincy/jsdelivr,yaplas/jsdelivr,vousk/jsdelivr,petkaantonov/jsdelivr,Sneezry/jsdelivr,sahat/jsdelivr,zhuwenxuan/qyerCDN,labsvisual/jsdelivr,labsvisual/jsdelivr,bonbon197/jsdelivr,garrypolley/jsdelivr,Kingside/jsdelivr,l3dlp/jsdelivr,garrypolley/jsdelivr,RoberMac/jsdelivr,EragonJ/jsdelivr,tunnckoCore/jsdelivr,gregorypratt/jsdelivr,yaplas/jsdelivr,EragonJ/jsdelivr,ramda/jsdelivr,hubdotcom/jsdelivr | ---
+++
@@ -0,0 +1,13 @@
+/**
+ * Project: Bootstrap Hover Dropdown
+ * Author: Cameron Spear
+ * Contributors: Mattia Larentis
+ *
+ * Dependencies: Bootstrap's Dropdown plugin, jQuery
+ *
+ * A simple plugin to enable Bootstrap dropdowns to active on hover and provide a nice user experience.
+ *
+ * License: MIT
+ *
+ * http://cameronspear.com/blog/bootstrap-dropdown-on-hover-plugin/
+ */(function(e,t,n){var r=e();e.fn.dropdownHover=function(n){if("ontouchstart"in document)return this;r=r.add(this.parent());return this.each(function(){function h(e){r.find(":focus").blur();l.instantlyCloseOthers===!0&&r.removeClass("open");t.clearTimeout(c);s.addClass("open");i.trigger(a)}var i=e(this),s=i.parent(),o={delay:500,instantlyCloseOthers:!0},u={delay:e(this).data("delay"),instantlyCloseOthers:e(this).data("close-others")},a="show.bs.dropdown",f="hide.bs.dropdown",l=e.extend(!0,{},o,n,u),c;s.hover(function(e){if(s.hasClass("open")&&!i.is(e.target))return!0;h(e)},function(){c=t.setTimeout(function(){s.removeClass("open");i.trigger(f)},l.delay)});i.hover(function(e){if(!s.hasClass("open")&&!s.is(e.target))return!0;h(e)});s.find(".dropdown-submenu").each(function(){var n=e(this),r;n.hover(function(){t.clearTimeout(r);n.children(".dropdown-menu").show();n.siblings().children(".dropdown-menu").hide()},function(){var e=n.children(".dropdown-menu");r=t.setTimeout(function(){e.hide()},l.delay)})})})};e(document).ready(function(){e('[data-hover="dropdown"]').dropdownHover()})})(jQuery,this); | |
e7accd8135d9847c02efbc3c445eceb7b2454a09 | scripts/blueRed.js | scripts/blueRed.js | var conn = new Mongo();
var db = conn.getDB("local");
db.matches.find().forEach(function(doc){
var red = 0, games = [];
doc.games.forEach(function(game){
if (game.redScore > game.blueScore) red++;
else red--;
});
var winner = red > 0 ? "red" : "blue";
var loser = red < 0 ? "red" : "blue";
if (red === 0) db.matches.remove({_id: doc._id});
else {
doc.games.forEach(function(game){
games.push({ winnerScore: game[winner + "Score"], loserScore: game[loser + "Score"]});
});
var rename = {};
rename[winner + "Player"] = "winner";
rename[loser + "Player"] = "loser";
rename[winner + "PlayerRating"] = "winnerRating";
rename[loser + "PlayerRating"] = "loserRating";
var winnerId = doc[winner + "Player"];
var loserId = doc[loser + "Player"];
db.matches.update(
{_id: doc._id},
{
$rename: rename,
$set: { games: games },
$unset: { redPlayerDetails: '', bluePlayerDetails: '' }
}
);
db.matches.update(
{_id: doc._id},
{
$set: { winner: new ObjectId(winnerId), loser: new ObjectId(loserId) }
}
)
}
});
| Add script to convert data from blue/red to winner/loser | Add script to convert data from blue/red to winner/loser
| JavaScript | mit | jshemas/PingPong,jshemas/PingPong | ---
+++
@@ -0,0 +1,39 @@
+var conn = new Mongo();
+var db = conn.getDB("local");
+db.matches.find().forEach(function(doc){
+ var red = 0, games = [];
+ doc.games.forEach(function(game){
+ if (game.redScore > game.blueScore) red++;
+ else red--;
+ });
+ var winner = red > 0 ? "red" : "blue";
+ var loser = red < 0 ? "red" : "blue";
+ if (red === 0) db.matches.remove({_id: doc._id});
+ else {
+ doc.games.forEach(function(game){
+ games.push({ winnerScore: game[winner + "Score"], loserScore: game[loser + "Score"]});
+ });
+ var rename = {};
+ rename[winner + "Player"] = "winner";
+ rename[loser + "Player"] = "loser";
+ rename[winner + "PlayerRating"] = "winnerRating";
+ rename[loser + "PlayerRating"] = "loserRating";
+ var winnerId = doc[winner + "Player"];
+ var loserId = doc[loser + "Player"];
+ db.matches.update(
+ {_id: doc._id},
+ {
+ $rename: rename,
+ $set: { games: games },
+ $unset: { redPlayerDetails: '', bluePlayerDetails: '' }
+ }
+ );
+ db.matches.update(
+ {_id: doc._id},
+ {
+ $set: { winner: new ObjectId(winnerId), loser: new ObjectId(loserId) }
+ }
+ )
+ }
+});
+ | |
339e8e1ea11aef45a78dd8bf6a0defd6d3004efa | test/cases/resolving/commomjs-local-module/index.js | test/cases/resolving/commomjs-local-module/index.js | var should = require("should");
define("regular", function(require, exports, module) {
module.exports = "regular-module";
});
define("override-exports", function(require, exports, module) {
exports = "this one overrides exports reference";
});
define("return-module", function(require, exports, module) {
return "module is returned";
});
it("should make different modules for query", function() {
should.strictEqual(require("regular"), "regular-module");
should.strictEqual(require("return-module"), "module is returned");
const overrideExports = require("override-exports");
should(overrideExports).be.a.Object();
should(Object.keys(overrideExports).length).be.exactly(0);
});
| Fix tests — let's default to an empty object if exports keyword is overriden | Fix tests — let's default to an empty object if exports keyword is overriden
| JavaScript | mit | ts-webpack/webpack,g0ddish/webpack,NekR/webpack,g0ddish/webpack,SimenB/webpack,SimenB/webpack,ts-webpack/webpack,SimenB/webpack,NekR/webpack,SimenB/webpack,webpack/webpack,EliteScientist/webpack,EliteScientist/webpack,g0ddish/webpack,ts-webpack/webpack,ts-webpack/webpack,webpack/webpack,webpack/webpack,webpack/webpack | ---
+++
@@ -0,0 +1,23 @@
+var should = require("should");
+
+define("regular", function(require, exports, module) {
+ module.exports = "regular-module";
+});
+
+define("override-exports", function(require, exports, module) {
+ exports = "this one overrides exports reference";
+});
+
+define("return-module", function(require, exports, module) {
+ return "module is returned";
+});
+
+
+it("should make different modules for query", function() {
+ should.strictEqual(require("regular"), "regular-module");
+ should.strictEqual(require("return-module"), "module is returned");
+
+ const overrideExports = require("override-exports");
+ should(overrideExports).be.a.Object();
+ should(Object.keys(overrideExports).length).be.exactly(0);
+}); | |
fb04081962f07efa9359b0b0bc6fd526d24324d8 | src/userlist/UserStatusIndicator.js | src/userlist/UserStatusIndicator.js | import React, { Component } from 'react';
import {
StyleSheet,
View,
} from 'react-native';
import { UserStatus } from '../api';
const styles = StyleSheet.create({
common: {
width: 16,
height: 16,
borderRadius: 100,
},
active: {
borderColor: 'pink',
backgroundColor: 'green',
},
idle: {
backgroundColor: 'rgba(255, 165, 0, 0.25)',
borderColor: 'rgba(255, 165, 0, 1)',
borderWidth: 2,
},
offline: {
backgroundColor: 'transparent',
borderColor: 'lightgray',
borderWidth: 2,
},
unknown: {
},
});
export default class UserStatusIndicator extends Component {
props: {
status: UserStatus,
}
static defaultProps = {
status: 'unknown',
};
render() {
const { status } = this.props;
if (!status) return null;
return (
<View style={[styles.common, styles[status]]} />
);
}
}
| import React, { Component } from 'react';
import {
StyleSheet,
View,
} from 'react-native';
import { UserStatus } from '../api';
const styles = StyleSheet.create({
common: {
width: 12,
height: 12,
borderRadius: 100,
},
active: {
backgroundColor: '#44c21d',
},
idle: {
backgroundColor: 'rgba(255, 165, 0, 0.25)',
borderColor: 'rgba(255, 165, 0, 1)',
borderWidth: 1,
},
offline: {
backgroundColor: 'transparent',
borderColor: 'lightgray',
borderWidth: 1,
},
unknown: {
},
});
export default class UserStatusIndicator extends Component {
props: {
status: UserStatus,
}
static defaultProps = {
status: 'unknown',
};
render() {
const { status } = this.props;
if (!status) return null;
return (
<View style={[styles.common, styles[status]]} />
);
}
}
| Make status indicators more like current site | Make status indicators more like current site
| JavaScript | apache-2.0 | Sam1301/zulip-mobile,nashvail/zulip-mobile,vishwesh3/zulip-mobile,saketkumar95/zulip-mobile,nashvail/zulip-mobile,Sam1301/zulip-mobile,vishwesh3/zulip-mobile,nashvail/zulip-mobile,kunall17/zulip-mobile,Sam1301/zulip-mobile,nashvail/zulip-mobile,vishwesh3/zulip-mobile,vishwesh3/zulip-mobile,saketkumar95/zulip-mobile,Sam1301/zulip-mobile,saketkumar95/zulip-mobile,saketkumar95/zulip-mobile,kunall17/zulip-mobile,kunall17/zulip-mobile,kunall17/zulip-mobile,Sam1301/zulip-mobile,saketkumar95/zulip-mobile,Sam1301/zulip-mobile | ---
+++
@@ -8,23 +8,22 @@
const styles = StyleSheet.create({
common: {
- width: 16,
- height: 16,
+ width: 12,
+ height: 12,
borderRadius: 100,
},
active: {
- borderColor: 'pink',
- backgroundColor: 'green',
+ backgroundColor: '#44c21d',
},
idle: {
backgroundColor: 'rgba(255, 165, 0, 0.25)',
borderColor: 'rgba(255, 165, 0, 1)',
- borderWidth: 2,
+ borderWidth: 1,
},
offline: {
backgroundColor: 'transparent',
borderColor: 'lightgray',
- borderWidth: 2,
+ borderWidth: 1,
},
unknown: {
}, |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.