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 |
|---|---|---|---|---|---|---|---|---|---|---|
0d4919d22140a13374e57db8d83dd218b4db8958 | src/main/webapp/scripts/results.js | src/main/webapp/scripts/results.js | $().ready(() => {
loadContentSection().then(() =>{
$('body').removeClass('loading');
});
});
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(".extended").removeClass("extended");
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$("body").on('click', '.level-name', function() {
const isThisExtended = $(this).parent().hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).parent().addClass("extended");
}
});
| $().ready(loadContentSection);
$("body").on('click', '.keyword', function() {
$(this).addClass("active");
$(".base").hide(200);
$("#real-body").addClass("focus");
});
$("body").on('click', ".close", function(event) {
event.stopPropagation();
$(".extended").removeClass("extended");
$(this).parent().removeClass("active");
$(".base").show(200);
$("#real-body").removeClass("focus");
});
$("body").on('click', ".active .item", function() {
$(".item").off("click");
const url = $(this).attr("data-url");
window.location.href = url;
});
$("body").on('click', '.level-name', function() {
const isThisExtended = $(this).parent().hasClass("extended");
$(".extended").removeClass("extended");
if (!isThisExtended) {
$(this).parent().addClass("extended");
}
});
| Change await promises to counter | Change await promises to counter
| JavaScript | apache-2.0 | googleinterns/step36-2020,googleinterns/step36-2020,googleinterns/step36-2020 | ---
+++
@@ -1,8 +1,4 @@
-$().ready(() => {
- loadContentSection().then(() =>{
- $('body').removeClass('loading');
- });
-});
+$().ready(loadContentSection);
$("body").on('click', '.keyword', function() {
$(this).addClass("active"); |
6a6494f7fe7fbfd64cc6493f464603c51b6d2b93 | src/test/javascript/specRunner.js | src/test/javascript/specRunner.js | // We need to prime vertx since jasmine tests don't run in the vert.x container.
if ((typeof nodyn) !== 'object') {
load('./node.js');
}
// jasmine's fake clock thinks it's using milliseconds,
// but in fact it's using seconds. Set the timeout increment
// to one second.
jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 1;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1;
var fs = require('vertx/file_system');
var jasmineEnv = jasmine.getEnv();
var origCallback = jasmineEnv.currentRunner_.finishCallback;
jasmineEnv.currentRunner_.finishCallback = function() {
origCallback.call(this);
process.emit('exit', '__jvertx.stop()');
__jvertx.stop();
};
describe('Nodyn', function() {
it('should execute integration specs', function() {
var complete = false;
waitsFor(function() { return complete; }, 300); // bail after 5 minutes?
fs.readDir('src/test/javascript', '.+Spec.js', function(err, arr) {
for(var i in arr) {
System.err.println( "::: " + arr[i] );
require(arr[i]);
}
complete = true;
});
});
});
| // We need to prime vertx since jasmine tests don't run in the vert.x container.
if ((typeof nodyn) !== 'object') {
load('./node.js');
}
// jasmine's fake clock thinks it's using milliseconds,
// but in fact it's using seconds. Set the timeout increment
// to one second.
jasmine.WaitsForBlock.TIMEOUT_INCREMENT = 1;
jasmine.DEFAULT_TIMEOUT_INTERVAL = 1;
var fs = require('vertx/file_system');
var jasmineEnv = jasmine.getEnv();
var origCallback = jasmineEnv.currentRunner_.finishCallback;
jasmineEnv.currentRunner_.finishCallback = function() {
origCallback.call(this);
process.exit();
};
describe('Nodyn', function() {
it('should execute integration specs', function() {
var complete = false;
waitsFor(function() { return complete; }, 300); // bail after 5 minutes?
fs.readDir('src/test/javascript', '.+Spec.js', function(err, arr) {
for(var i in arr) {
System.err.println( "::: " + arr[i] );
require(arr[i]);
}
complete = true;
});
});
});
| Use process.exit() to clean up after tests | Use process.exit() to clean up after tests
| JavaScript | apache-2.0 | nodyn/nodyn,dherges/nodyn,tony--/nodyn,nodyn/nodyn,tony--/nodyn,dherges/nodyn,nodyn/nodyn,dherges/nodyn,tony--/nodyn | ---
+++
@@ -15,8 +15,7 @@
jasmineEnv.currentRunner_.finishCallback = function() {
origCallback.call(this);
- process.emit('exit', '__jvertx.stop()');
- __jvertx.stop();
+ process.exit();
};
describe('Nodyn', function() { |
3a82f7aca54c37a28158a5bb7f78459bc69e7f0e | public/script/init.js | public/script/init.js | /* global hljs */
(function() {
'use strict';
var cells = document.querySelectorAll('.diff tbody td');
for (var i = 0, len = cells.length; i < len; i++) {
hljs.highlightBlock(cells[i]);
}
})();
| /* global hljs */
(function() {
'use strict';
document.addEventListener('DOMContentLoaded', function() {
var cells = document.querySelectorAll('.diff tbody td');
for (var i = 0, len = cells.length; i < len; i++) {
hljs.highlightBlock(cells[i]);
}
});
})();
| Tweak execution timing of highlighting | Tweak execution timing of highlighting
| JavaScript | mit | takenspc/diffofhtmls,takenspc/diffofhtmls,takenspc/diffofhtmls | ---
+++
@@ -1,8 +1,10 @@
/* global hljs */
(function() {
'use strict';
- var cells = document.querySelectorAll('.diff tbody td');
- for (var i = 0, len = cells.length; i < len; i++) {
- hljs.highlightBlock(cells[i]);
- }
+ document.addEventListener('DOMContentLoaded', function() {
+ var cells = document.querySelectorAll('.diff tbody td');
+ for (var i = 0, len = cells.length; i < len; i++) {
+ hljs.highlightBlock(cells[i]);
+ }
+ });
})(); |
21043bdce769c06b08b9e9b1054eafebcb842351 | test/wordpress/wordpress/index.js | test/wordpress/wordpress/index.js | import sinon from 'sinon';
import chai from 'chai';
const expect = chai.expect;
import * as fetch from '../../../src/functions/fetch.js';
import checkWordpress from '../../../src/wordpress/wordpress';
describe('wordpress', function() {
describe('test wordpress promise', function() {
let sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should return original URL even if not a WordPress site', () => {
const html = {
body: '<html><head><title>No index</title></head><body><h1>No index</h1></body></html>',
};
sandbox.stub(fetch, 'fetch').returns(html);
return new Promise((resolve, reject) => {
resolve('https://www.juffalow.com');
})
.then(checkWordpress)
.then(() => {
expect.fail(null, null, 'This promise in this test should end with error, therefore jump to catch');
}).catch((error) => {
expect(error).to.equal('Not a WordPress site!');
});
});
});
});
| import sinon from 'sinon';
import chai from 'chai';
const expect = chai.expect;
import * as fetch from '../../../src/functions/fetch.js';
import checkWordpress from '../../../src/wordpress/wordpress';
describe('wordpress', function() {
describe('test wordpress promise', function() {
let sandbox;
beforeEach(function() {
sandbox = sinon.sandbox.create();
});
afterEach(function() {
sandbox.restore();
});
it('should return original URL even if not a WordPress site', () => {
const html = {
body: '<html><head><title>No index</title></head><body><h1>No index</h1></body></html>',
};
sandbox.stub(fetch, 'fetch').returns(html);
return new Promise((resolve, reject) => {
resolve('https://www.juffalow.com');
})
.then(checkWordpress)
.then(() => {
expect.fail(null, null, 'This promise in this test should end with error, therefore jump to catch');
}).catch((error) => {
expect(error).to.equal('Not a WordPress site!');
});
});
it('should return original URL', () => {
const html = {
body: '<html><head><title>Index of folder</title><link href="https://example.com/wp-content/themes/example/css/example.css" rel="stylesheet"></head><body><h1>Index of folder</h1></body></html>',
};
sandbox.stub(fetch, 'fetch').returns(html);
return new Promise((resolve, reject) => {
resolve('https://www.juffalow.com');
})
.then(checkWordpress)
.then((url) => {
expect(url).to.equal('https://www.juffalow.com');
});
});
});
});
| Add new test case in wordpress | Add new test case in wordpress
| JavaScript | mit | juffalow/pentest-tool-lite,juffalow/pentest-tool-lite | ---
+++
@@ -33,5 +33,21 @@
expect(error).to.equal('Not a WordPress site!');
});
});
+
+ it('should return original URL', () => {
+ const html = {
+ body: '<html><head><title>Index of folder</title><link href="https://example.com/wp-content/themes/example/css/example.css" rel="stylesheet"></head><body><h1>Index of folder</h1></body></html>',
+ };
+
+ sandbox.stub(fetch, 'fetch').returns(html);
+
+ return new Promise((resolve, reject) => {
+ resolve('https://www.juffalow.com');
+ })
+ .then(checkWordpress)
+ .then((url) => {
+ expect(url).to.equal('https://www.juffalow.com');
+ });
+ });
});
}); |
8c6348d276301e549e40025210b35d3daff49ab3 | src/components/molecules/user_info/UserInfo.js | src/components/molecules/user_info/UserInfo.js | 'use strict';
import React from 'react';
import ProfileImage from 'components/atoms/profile_image/ProfileImage';
import Username from 'components/atoms/username/Username';
import Badges from 'components/molecules/badges/Badges';
require('./stylesheets/user_info.scss');
class UserInfo extends React.Component {
getUserProfile() {
return JSON.parse(localStorage.getItem('userProfile'));
}
render() {
let userProfile = this.getUserProfile();
return (
<div className='user-info-component'>
<ProfileImage email={userProfile.email} />
<div className='column'>
<Username username={userProfile.nickname} />
<Badges points='500' />
</div>
</div>
);
}
}
UserInfo.displayName = 'MoleculeUserInfo';
// Uncomment properties you need
// UserInfo.propTypes = {};
// UserInfo.defaultProps = {};
export default UserInfo;
| 'use strict';
import React from 'react';
import ProfileImage from 'components/atoms/profile_image/ProfileImage';
import Username from 'components/atoms/username/Username';
import Badges from 'components/molecules/badges/Badges';
require('./stylesheets/user_info.scss');
class UserInfo extends React.Component {
getUserProfile() {
return JSON.parse(localStorage.getItem('userProfile')) || {email:"",nickname:""};
}
render() {
let userProfile = this.getUserProfile();
return (
<div className='user-info-component'>
<ProfileImage email={userProfile.email} />
<div className='column'>
<Username username={userProfile.nickname} />
<Badges points='500' />
</div>
</div>
);
}
}
UserInfo.displayName = 'MoleculeUserInfo';
// Uncomment properties you need
// UserInfo.propTypes = {};
// UserInfo.defaultProps = {};
export default UserInfo;
| Fix not chached user bug | Fix not chached user bug
| JavaScript | mit | cassioscabral/rateissuesfront,DominikePessoa/rateissuesfront,DominikePessoa/rateissuesfront,cassioscabral/rateissuesfront | ---
+++
@@ -9,7 +9,7 @@
class UserInfo extends React.Component {
getUserProfile() {
- return JSON.parse(localStorage.getItem('userProfile'));
+ return JSON.parse(localStorage.getItem('userProfile')) || {email:"",nickname:""};
}
render() {
|
20cfac0e9414eee5ac907c16d63241b7297b21a7 | tests/dummy/config/environment.js | tests/dummy/config/environment.js | /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
// Personally, hash is nicer for test work. The browser knows not
// to do a full page refresh when you manually edit the url.
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'none';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| /* jshint node: true */
module.exports = function(environment) {
var ENV = {
modulePrefix: 'dummy',
environment: environment,
baseURL: '/',
// Personally, hash is nicer for test work. The browser knows not
// to do a full page refresh when you manually edit the url.
locationType: 'hash',
EmberENV: {
FEATURES: {
// Here you can enable experimental features on an ember canary build
// e.g. 'with-controller': true
}
},
APP: {
// Here you can pass flags/options to your application instance
// when it is created
}
};
if (environment === 'development') {
// ENV.APP.LOG_RESOLVER = true;
// ENV.APP.LOG_ACTIVE_GENERATION = true;
// ENV.APP.LOG_TRANSITIONS = true;
// ENV.APP.LOG_TRANSITIONS_INTERNAL = true;
// ENV.APP.LOG_VIEW_LOOKUPS = true;
}
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false;
ENV.APP.LOG_VIEW_LOOKUPS = false;
ENV.APP.rootElement = '#ember-testing';
}
if (environment === 'production') {
}
return ENV;
};
| Revert "fix links from test page" | Revert "fix links from test page"
This reverts commit 27dd0e3170bb185e385deed11b153d86983ae0c6.
| JavaScript | mit | ember-animation/liquid-fire-velocity,byelipk/liquid-fire,jrjohnson/liquid-fire,ember-animation/liquid-fire,topaxi/liquid-fire,monegraph/liquid-fire,givanse/liquid-fire,totallymike/liquid-fire,chadhietala/liquid-fire,chadhietala/liquid-fire,givanse/liquid-fire,totallymike/liquid-fire,jrjohnson/liquid-fire,knownasilya/liquid-fire,dsokolowski/liquid-fire,acorncom/liquid-fire,gordonbisnor/liquid-fire,jamesreggio/liquid-fire,ember-animation/liquid-fire,ef4/liquid-fire,csantero/liquid-fire,runspired/liquid-fire,monegraph/liquid-fire,ember-animation/ember-animated,davidgoli/liquid-fire,twokul/liquid-fire,csantero/liquid-fire,ember-animation/ember-animated,knownasilya/liquid-fire,kategengler/liquid-fire,ember-animation/ember-animated,ramybenaroya/liquid-fire,dsokolowski/liquid-fire,davewasmer/liquid-fire,jayphelps/liquid-fire,envoy/liquid-fire,davidgoli/liquid-fire,jayphelps/liquid-fire,topaxi/liquid-fire,ef4/liquid-fire,kategengler/liquid-fire,byelipk/liquid-fire,ember-animation/liquid-fire-velocity,mikegrassotti/liquid-fire,gordonbisnor/liquid-fire,ianstarz/liquid-fire,davewasmer/liquid-fire,jamesreggio/liquid-fire,ember-animation/liquid-fire-core,ianstarz/liquid-fire,ember-animation/liquid-fire-core,twokul/liquid-fire,mikegrassotti/liquid-fire,acorncom/liquid-fire,runspired/liquid-fire | ---
+++
@@ -34,7 +34,7 @@
if (environment === 'test') {
// Testem prefers this...
ENV.baseURL = '/';
- ENV.locationType = 'none';
+ ENV.locationType = 'auto';
// keep test console output quieter
ENV.APP.LOG_ACTIVE_GENERATION = false; |
234a9ac5c3e2e76a38991523eeac2a6eb425df76 | tests/unit/controllers/crate/version-test.js | tests/unit/controllers/crate/version-test.js | import { module, test } from 'qunit';
import { setupTest } from 'ember-qunit';
import { A } from '@ember/array';
import Service from '@ember/service';
module('Unit | Controller | crate/version', function(hooks) {
setupTest(hooks);
const userId = 1;
// stub the session service
// https://guides.emberjs.com/release/testing/testing-components/#toc_stubbing-services
const sessionStub = Service.extend();
hooks.beforeEach(function() {
sessionStub.currentUser = { id: userId };
this.owner.register('service:session', sessionStub);
});
test('notYankedOrIsOwner is true when conditions fulfilled', function(assert) {
assert.expect(2);
let controller = this.owner.lookup('controller:crate/version');
controller.model = { yanked: false };
controller.crate = { owner_user: A([{ id: userId }]) };
assert.ok(controller);
assert.ok(controller.notYankedOrIsOwner);
});
test('notYankedOrIsOwner is false when conditions fulfilled', function(assert) {
assert.expect(2);
let controller = this.owner.lookup('controller:crate/version');
controller.model = { yanked: true };
controller.crate = { owner_user: A([{ id: userId }]) };
assert.ok(controller);
assert.notOk(controller.notYankedOrIsOwner);
});
});
| Add a unit test for notYankedOrIsOwner (authored by @efx). | Add a unit test for notYankedOrIsOwner (authored by @efx).
| JavaScript | apache-2.0 | rust-lang/crates.io,rust-lang/crates.io,rust-lang/crates.io,rust-lang/crates.io | ---
+++
@@ -0,0 +1,35 @@
+import { module, test } from 'qunit';
+import { setupTest } from 'ember-qunit';
+import { A } from '@ember/array';
+import Service from '@ember/service';
+
+module('Unit | Controller | crate/version', function(hooks) {
+ setupTest(hooks);
+ const userId = 1;
+ // stub the session service
+ // https://guides.emberjs.com/release/testing/testing-components/#toc_stubbing-services
+ const sessionStub = Service.extend();
+
+ hooks.beforeEach(function() {
+ sessionStub.currentUser = { id: userId };
+ this.owner.register('service:session', sessionStub);
+ });
+
+ test('notYankedOrIsOwner is true when conditions fulfilled', function(assert) {
+ assert.expect(2);
+ let controller = this.owner.lookup('controller:crate/version');
+ controller.model = { yanked: false };
+ controller.crate = { owner_user: A([{ id: userId }]) };
+ assert.ok(controller);
+ assert.ok(controller.notYankedOrIsOwner);
+ });
+
+ test('notYankedOrIsOwner is false when conditions fulfilled', function(assert) {
+ assert.expect(2);
+ let controller = this.owner.lookup('controller:crate/version');
+ controller.model = { yanked: true };
+ controller.crate = { owner_user: A([{ id: userId }]) };
+ assert.ok(controller);
+ assert.notOk(controller.notYankedOrIsOwner);
+ });
+}); | |
917becac84b4fc486d05efe5e0845210fb36a139 | models/List_Gender.js | models/List_Gender.js | var keystone = require('keystone'),
Types = keystone.Field.Types;
// Create model. Additional options allow menu name to be used what auto-generating URLs
var Gender = new keystone.List('Gender', {
autokey: { path: 'key', from: 'gender', unique: true },
map: { name: 'gender' }
});
// Create fields
Gender.add({
gender: { type: String, label: 'Gender', required: true, index: true, initial: true }
});
// Define default columns in the admin interface and register the model
Gender.defaultColumns = 'gender';
Gender.register(); | Add Reference list model for Genders. | Add Reference list model for Genders.
| JavaScript | mit | autoboxer/MARE,autoboxer/MARE | ---
+++
@@ -0,0 +1,17 @@
+var keystone = require('keystone'),
+ Types = keystone.Field.Types;
+
+// Create model. Additional options allow menu name to be used what auto-generating URLs
+var Gender = new keystone.List('Gender', {
+ autokey: { path: 'key', from: 'gender', unique: true },
+ map: { name: 'gender' }
+});
+
+// Create fields
+Gender.add({
+ gender: { type: String, label: 'Gender', required: true, index: true, initial: true }
+});
+
+// Define default columns in the admin interface and register the model
+Gender.defaultColumns = 'gender';
+Gender.register(); | |
8a3599bf87bcb5dbf621f669f27d7c498cb37f2e | files/jquery.leanmodal2/2.3/jQuery.leanModal2.min.js | files/jquery.leanmodal2/2.3/jQuery.leanModal2.min.js | // jQuery.leanModal2.min.js v2.3 - MIT Licensed by eustasy http://eustasy.org
(function($){function leanModal_Close(modal_id){$('.js-target-jquery-leanmodal-overlay').fadeOut(300);$(modal_id).fadeOut(200);}$.fn.extend({leanModal:function(options){var defaults={top:100,overlayOpacity:0.5,closeButton:false,disableCloseOnOverlayClick:false,disableCloseOnEscape:false,};options=$.extend(defaults,options);if($('.js-target-jquery-leanmodal-overlay').length==0){var style='background:#000;display:none;height:100%;left:0px;position:fixed;top:0px;width:100%;z-index:100;';var overlay=$('<div class="js-target-jquery-leanmodal-overlay" style="'+style+'"></div>');$('body').append(overlay);}return this.each(function(){$(this).css({'cursor':'pointer'});$(this).unbind('click').click(function(e){if($(this).attr('href')){var modal_id=$(this).attr('href');}else if($(this).attr('data-modal-id')){var modal_id=$(this).attr('data-modal-id');}else{return false;}$('.js-target-jquery-leanmodal-overlay').click(function(){if(!options.disableCloseOnOverlayClick){leanModal_Close(modal_id);}});if(options.closeButton){$(options.closeButton).click(function(){leanModal_Close(modal_id);});}$(document).on('keyup',function(evt){if(!options.disableCloseOnEscape&&evt.keyCode==27){leanModal_Close(modal_id);}});var modal_height=$(modal_id).innerHeight();var modal_width=$(modal_id).innerWidth();$(modal_id).css({'display':'block','position':'fixed','opacity':0,'z-index':11000,'left':50+'%','margin-left':-(modal_width/2)+'px','top':options.top+'px'});$('.js-target-jquery-leanmodal-overlay').css({'display':'block',opacity:0});$('.js-target-jquery-leanmodal-overlay').fadeTo(300,options.overlayOpacity);$(modal_id).fadeTo(200,1);e.preventDefault();});});}});})(jQuery);
| Update project jQuery.leanModal2 to 2.3 | Update project jQuery.leanModal2 to 2.3
| JavaScript | mit | vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr,vvo/jsdelivr | ---
+++
@@ -0,0 +1,2 @@
+// jQuery.leanModal2.min.js v2.3 - MIT Licensed by eustasy http://eustasy.org
+(function($){function leanModal_Close(modal_id){$('.js-target-jquery-leanmodal-overlay').fadeOut(300);$(modal_id).fadeOut(200);}$.fn.extend({leanModal:function(options){var defaults={top:100,overlayOpacity:0.5,closeButton:false,disableCloseOnOverlayClick:false,disableCloseOnEscape:false,};options=$.extend(defaults,options);if($('.js-target-jquery-leanmodal-overlay').length==0){var style='background:#000;display:none;height:100%;left:0px;position:fixed;top:0px;width:100%;z-index:100;';var overlay=$('<div class="js-target-jquery-leanmodal-overlay" style="'+style+'"></div>');$('body').append(overlay);}return this.each(function(){$(this).css({'cursor':'pointer'});$(this).unbind('click').click(function(e){if($(this).attr('href')){var modal_id=$(this).attr('href');}else if($(this).attr('data-modal-id')){var modal_id=$(this).attr('data-modal-id');}else{return false;}$('.js-target-jquery-leanmodal-overlay').click(function(){if(!options.disableCloseOnOverlayClick){leanModal_Close(modal_id);}});if(options.closeButton){$(options.closeButton).click(function(){leanModal_Close(modal_id);});}$(document).on('keyup',function(evt){if(!options.disableCloseOnEscape&&evt.keyCode==27){leanModal_Close(modal_id);}});var modal_height=$(modal_id).innerHeight();var modal_width=$(modal_id).innerWidth();$(modal_id).css({'display':'block','position':'fixed','opacity':0,'z-index':11000,'left':50+'%','margin-left':-(modal_width/2)+'px','top':options.top+'px'});$('.js-target-jquery-leanmodal-overlay').css({'display':'block',opacity:0});$('.js-target-jquery-leanmodal-overlay').fadeTo(300,options.overlayOpacity);$(modal_id).fadeTo(200,1);e.preventDefault();});});}});})(jQuery); | |
0dd064b77199e2c8125d50017450b30acc888084 | lib/helpers/helpers.js | lib/helpers/helpers.js | /**
* Created by JiaHao on 5/10/15.
*/
var os = require('os');
function platformIsWindows() {
var platform = os.platform();
return platform.indexOf('win') > -1;
}
module.exports = {
platformIsWindows: platformIsWindows
}; | Add helper to check if platform is windows | Add helper to check if platform is windows
| JavaScript | mit | jiahaog/Revenant | ---
+++
@@ -0,0 +1,14 @@
+/**
+ * Created by JiaHao on 5/10/15.
+ */
+
+var os = require('os');
+
+function platformIsWindows() {
+ var platform = os.platform();
+ return platform.indexOf('win') > -1;
+}
+
+module.exports = {
+ platformIsWindows: platformIsWindows
+}; | |
ee9bafc127c84dad9b11f3f97d5c6f13a7f76732 | app/components/file-upload.js | app/components/file-upload.js | import Ember from 'ember';
import EmberUploader from 'ember-uploader';
const { FileField, Uploader } = EmberUploader;
export default FileField.extend({
url: '',
filesDidChange(files) {
const uploadUrl = this.get('url');
const uploader = Uploader.create({ url: uploadUrl });
this.sendAction('startUploading');
uploader.on('didUpload', (e) => {
this.sendAction('finishedUploading', e);
});
uploader.on('progress', (e) => {
this.sendAction('setUploadPercentage', e.percent);
});
if (!Ember.isEmpty(files)) {
uploader.upload(files[0]);
}
}
});
| import Ember from 'ember';
import EmberUploader from 'ember-uploader';
const { FileField, Uploader } = EmberUploader;
const { inject, computed } = Ember;
const { service } = inject;
let IliosUploader = Uploader.extend({
iliosHeaders: [],
ajaxSettings: function() {
let settings = this._super(...arguments);
settings.headers = this.get('iliosHeaders');
return settings;
}
});
export default FileField.extend({
session: service(),
url: '',
headers: computed('session.isAuthenticated', function(){
let headers = {};
this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
headers[headerName] = headerValue;
});
return headers;
}),
filesDidChange(files) {
const uploadUrl = this.get('url');
const uploader = IliosUploader.create({
url: uploadUrl,
iliosHeaders: this.get('headers')
});
this.sendAction('startUploading');
uploader.on('didUpload', (e) => {
this.sendAction('finishedUploading', e);
});
uploader.on('progress', (e) => {
this.sendAction('setUploadPercentage', e.percent);
});
if (!Ember.isEmpty(files)) {
uploader.upload(files[0]);
}
}
});
| Send authorization headers with upload requests | Send authorization headers with upload requests
Our new simple auth library doesn’t do this automatically so we have to
hand it on our own.
| JavaScript | mit | jrjohnson/frontend,stopfstedt/frontend,stopfstedt/frontend,gboushey/frontend,thecoolestguy/frontend,djvoa12/frontend,gabycampagna/frontend,gabycampagna/frontend,thecoolestguy/frontend,dartajax/frontend,jrjohnson/frontend,dartajax/frontend,ilios/frontend,gboushey/frontend,ilios/frontend,djvoa12/frontend | ---
+++
@@ -2,13 +2,38 @@
import EmberUploader from 'ember-uploader';
const { FileField, Uploader } = EmberUploader;
+const { inject, computed } = Ember;
+const { service } = inject;
+
+let IliosUploader = Uploader.extend({
+ iliosHeaders: [],
+ ajaxSettings: function() {
+ let settings = this._super(...arguments);
+ settings.headers = this.get('iliosHeaders');
+
+ return settings;
+ }
+
+});
export default FileField.extend({
+ session: service(),
url: '',
+ headers: computed('session.isAuthenticated', function(){
+ let headers = {};
+ this.get('session').authorize('authorizer:token', (headerName, headerValue) => {
+ headers[headerName] = headerValue;
+ });
+
+ return headers;
+ }),
filesDidChange(files) {
const uploadUrl = this.get('url');
- const uploader = Uploader.create({ url: uploadUrl });
+ const uploader = IliosUploader.create({
+ url: uploadUrl,
+ iliosHeaders: this.get('headers')
+ });
this.sendAction('startUploading');
|
1ec6d8f49940e603778e006617dd5823fee8b23c | backend/scripts/conversion/fixproperties.js | backend/scripts/conversion/fixproperties.js | #!/usr/bin/env node
"use strict";
var ropts = {
db: process.env.MCDB || 'materialscommons',
port: process.env.MCDB_PORT || 30815
};
console.log(ropts);
var r = require('rethinkdbdash')(ropts);
var bluebird = require('bluebird');
function SetupProperty(setupID, name, description, attribute, _type, value, unit) {
this.setup_id = setupID;
this.name = name;
this.description = description;
this.attribute = attribute;
this._type = _type;
this.value = value;
this.unit = unit;
}
function* fixSetup(setupId, settings) {
for (let i = 0; i < settings.length; i++) {
let current = settings[i];
// Create each property for the setting. Add these to the
// setting variable so we can return a setting object with
// all of its properties.
for (let j = 0; j < current.properties.length; j++) {
let p = current.properties[j].property;
let val = p.value;
let prop = new SetupProperty(setupId, p.name, p.description, p.attribute,
p._type, val, p.unit);
yield r.table('setupproperties').insert(prop);
}
}
}
bluebird.coroutine(function*() {
try {
var processes = yield r.db("materialscommons").table('processes')
.eqJoin('id', r.db('materialscommons').table('process2setup'), {index: 'process_id'}).zip()
.merge(function(p) {
return {
properties: r.db('materialscommons').table('setupproperties')
.getAll(p('setup_id'), {index: 'setup_id'}).count()
}
}).filter(r.row('properties').eq(0));
for (let i = 0; i < processes.length; i++) {
let p = processes[i];
console.log("Adding setup for " + p.name + "/" + p.process_id);
let template = yield r.table('templates').get(p.template_id);
yield * fixSetup(p.setup_id, template.setup);
console.log("Done.")
}
console.log("Finished with updates, exiting...");
process.exit(0);
} catch (err) {
console.log(err);
}
})();
| Add script to add properties to processes that don't have any template properties. | Add script to add properties to processes that don't have any template properties.
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -0,0 +1,64 @@
+#!/usr/bin/env node
+
+"use strict";
+
+var ropts = {
+ db: process.env.MCDB || 'materialscommons',
+ port: process.env.MCDB_PORT || 30815
+};
+
+console.log(ropts);
+var r = require('rethinkdbdash')(ropts);
+var bluebird = require('bluebird');
+
+function SetupProperty(setupID, name, description, attribute, _type, value, unit) {
+ this.setup_id = setupID;
+ this.name = name;
+ this.description = description;
+ this.attribute = attribute;
+ this._type = _type;
+ this.value = value;
+ this.unit = unit;
+}
+
+function* fixSetup(setupId, settings) {
+ for (let i = 0; i < settings.length; i++) {
+ let current = settings[i];
+ // Create each property for the setting. Add these to the
+ // setting variable so we can return a setting object with
+ // all of its properties.
+ for (let j = 0; j < current.properties.length; j++) {
+ let p = current.properties[j].property;
+ let val = p.value;
+ let prop = new SetupProperty(setupId, p.name, p.description, p.attribute,
+ p._type, val, p.unit);
+ yield r.table('setupproperties').insert(prop);
+ }
+ }
+}
+
+bluebird.coroutine(function*() {
+ try {
+ var processes = yield r.db("materialscommons").table('processes')
+ .eqJoin('id', r.db('materialscommons').table('process2setup'), {index: 'process_id'}).zip()
+ .merge(function(p) {
+ return {
+ properties: r.db('materialscommons').table('setupproperties')
+ .getAll(p('setup_id'), {index: 'setup_id'}).count()
+ }
+ }).filter(r.row('properties').eq(0));
+ for (let i = 0; i < processes.length; i++) {
+ let p = processes[i];
+ console.log("Adding setup for " + p.name + "/" + p.process_id);
+ let template = yield r.table('templates').get(p.template_id);
+ yield * fixSetup(p.setup_id, template.setup);
+ console.log("Done.")
+ }
+ console.log("Finished with updates, exiting...");
+ process.exit(0);
+ } catch (err) {
+ console.log(err);
+ }
+})();
+
+ | |
706e7e4c22a6a1c94170588ec4370dfc9fe91ed3 | app/scripts/app/utils/parse-fields-metadata.js | app/scripts/app/utils/parse-fields-metadata.js | function parseFields (payload) {
if (Array.isArray(payload)) {
payload.forEach(parseFields);
return;
}
if (typeof payload === 'object' && payload.hasOwnProperty('fields')) {
payload.fields = JSON.parse(payload.fields);
}
}
export default parseFields;
| Move parseFields function to its own module | Move parseFields function to its own module
| JavaScript | mit | darvelo/wishlist,darvelo/wishlist | ---
+++
@@ -0,0 +1,12 @@
+function parseFields (payload) {
+ if (Array.isArray(payload)) {
+ payload.forEach(parseFields);
+ return;
+ }
+
+ if (typeof payload === 'object' && payload.hasOwnProperty('fields')) {
+ payload.fields = JSON.parse(payload.fields);
+ }
+}
+
+export default parseFields; | |
c5b009d7122e448fd9e726ea5c1fe1bb1617920a | test/consistency.js | test/consistency.js | var tap = require("tap")
var normalize = require("../lib/normalize")
var path = require("path")
var fs = require("fs")
var _ = require("underscore")
var async = require("async")
var data, clonedData
tap.test("consistent normalization", function(t) {
path.resolve(__dirname, "./fixtures/read-package-json.json")
fs.readdir (__dirname + "/fixtures", function (err, entries) {
verifyConsistency = function(entryName, next) {
filename = __dirname + "/fixtures/" + entryName
fs.readFile(filename, function(err, contents) {
if (err) return next(err)
data = JSON.parse(contents.toString())
normalize(data)
clonedData = _.clone(data)
normalize(data)
t.deepEqual(data, clonedData,
"Normalization of " + entryName + "is consistent.")
next(null)
}) // fs.readFile
} // verifyConsistency
async.forEach(entries, verifyConsistency, function(err) {
if (err) throw err
t.end()
})
}) // fs.readdir
}) // tap.test | var tap = require("tap")
var normalize = require("../lib/normalize")
var path = require("path")
var fs = require("fs")
var _ = require("underscore")
var async = require("async")
var data, clonedData
var warn
tap.test("consistent normalization", function(t) {
path.resolve(__dirname, "./fixtures/read-package-json.json")
fs.readdir (__dirname + "/fixtures", function (err, entries) {
// entries = ['coffee-script.json'] // uncomment to limit to a specific file
verifyConsistency = function(entryName, next) {
warn = function(msg) {
// t.equal("",msg) // uncomment to have some kind of logging of warnings
}
filename = __dirname + "/fixtures/" + entryName
fs.readFile(filename, function(err, contents) {
if (err) return next(err)
data = JSON.parse(contents.toString())
normalize(data, warn)
clonedData = _.clone(data)
normalize(data, warn)
t.deepEqual(clonedData, data,
"Normalization of " + entryName + "is consistent.")
next(null)
}) // fs.readFile
} // verifyConsistency
async.forEach(entries, verifyConsistency, function(err) {
if (err) throw err
t.end()
})
}) // fs.readdir
}) // tap.test | Add some ways to get warnings. | Add some ways to get warnings.
| JavaScript | bsd-2-clause | kemitchell/normalize-package-data,sindresorhus/normalize-package-data | ---
+++
@@ -6,19 +6,24 @@
var async = require("async")
var data, clonedData
+var warn
tap.test("consistent normalization", function(t) {
path.resolve(__dirname, "./fixtures/read-package-json.json")
fs.readdir (__dirname + "/fixtures", function (err, entries) {
+ // entries = ['coffee-script.json'] // uncomment to limit to a specific file
verifyConsistency = function(entryName, next) {
+ warn = function(msg) {
+ // t.equal("",msg) // uncomment to have some kind of logging of warnings
+ }
filename = __dirname + "/fixtures/" + entryName
fs.readFile(filename, function(err, contents) {
if (err) return next(err)
data = JSON.parse(contents.toString())
- normalize(data)
+ normalize(data, warn)
clonedData = _.clone(data)
- normalize(data)
- t.deepEqual(data, clonedData,
+ normalize(data, warn)
+ t.deepEqual(clonedData, data,
"Normalization of " + entryName + "is consistent.")
next(null)
}) // fs.readFile |
062ab472fd083b2ecbb2c022aa4dc4d7a24b4a9e | tests/benchmark/compare-trianglepath-construction-with-rounded-corners.js | tests/benchmark/compare-trianglepath-construction-with-rounded-corners.js | var suite = new PerfSuite({
name: 'RedRaphael Compare Trianglepath Construction With and Without Rounded Corners',
jquery: true,
assets: [
'../../package/raphael-min.js',
'../../source/components/raphael.trianglepath.js'
],
global: {
setup: function() {
if (typeof Raphael === 'undefined') {
$.ajaxSetup({
async: false
});
$.getScript('assets/raphael-min.js');
$.getScript('assets/raphael.trianglepath.js');
}
}
}
});
suite.add({
name: 'create trianglepath without rounded corners',
setup: function() {
var paper;
if (typeof Raphael === 'undefined') {
$.ajaxSetup({
async: false
});
$.getScript('assets/raphael-min.js');
$.getScript('assets/raphael.trianglepath.js');
}
paper = new Raphael(0, 0, 600, 350);
},
fn: function() {
paper.trianglepath(20,30,20,60,40,45);
},
teardown: function() {
paper.remove();
}
});
suite.add({
name: 'create trianglepath with rounded corners',
setup: function() {
var paper;
if (typeof Raphael === 'undefined') {
$.ajaxSetup({
async: false
});
$.getScript('assets/raphael-min.js');
$.getScript('assets/raphael.trianglepath.js');
}
paper = new Raphael(0, 0, 600, 350);
},
fn: function() {
paper.trianglepath(20,30,20,60,40,45,5);
},
teardown: function() {
paper.remove();
}
}); | Add benchmark comparison for trianglepath construction with rounded corners. | Add benchmark comparison for trianglepath construction with rounded corners.
| JavaScript | mit | fusioncharts/redraphael,AyanGhatak/redraphael,AyanGhatak/redraphael,fusioncharts/redraphael,AyanGhatak/redraphael,fusioncharts/redraphael | ---
+++
@@ -0,0 +1,71 @@
+var suite = new PerfSuite({
+ name: 'RedRaphael Compare Trianglepath Construction With and Without Rounded Corners',
+ jquery: true,
+
+ assets: [
+ '../../package/raphael-min.js',
+ '../../source/components/raphael.trianglepath.js'
+ ],
+
+ global: {
+ setup: function() {
+ if (typeof Raphael === 'undefined') {
+ $.ajaxSetup({
+ async: false
+ });
+ $.getScript('assets/raphael-min.js');
+ $.getScript('assets/raphael.trianglepath.js');
+ }
+ }
+ }
+});
+
+suite.add({
+ name: 'create trianglepath without rounded corners',
+ setup: function() {
+ var paper;
+
+ if (typeof Raphael === 'undefined') {
+ $.ajaxSetup({
+ async: false
+ });
+ $.getScript('assets/raphael-min.js');
+ $.getScript('assets/raphael.trianglepath.js');
+ }
+
+ paper = new Raphael(0, 0, 600, 350);
+ },
+
+ fn: function() {
+ paper.trianglepath(20,30,20,60,40,45);
+ },
+
+ teardown: function() {
+ paper.remove();
+ }
+});
+
+suite.add({
+ name: 'create trianglepath with rounded corners',
+ setup: function() {
+ var paper;
+
+ if (typeof Raphael === 'undefined') {
+ $.ajaxSetup({
+ async: false
+ });
+ $.getScript('assets/raphael-min.js');
+ $.getScript('assets/raphael.trianglepath.js');
+ }
+
+ paper = new Raphael(0, 0, 600, 350);
+ },
+
+ fn: function() {
+ paper.trianglepath(20,30,20,60,40,45,5);
+ },
+
+ teardown: function() {
+ paper.remove();
+ }
+}); | |
7757d2986ae9890091dcb8b5f984ac30f12f9e3a | lib/ctrls/trivagoCall.js | lib/ctrls/trivagoCall.js | 'use strict'
const crypto = require('crypto')
const config = require('../config')
const rp = require('request-promise')
const Q = require('q')
const _ = require('lodash')
var fixDate = function (date) {
return (date).toISOString().split('.')[0] + 'Z'
}
const protocol = 'https://'
const endpoint = 'api.trivago.com'
function doReq (query, path) {
const hmac = crypto.createHmac('sha256', config.SECRET_KEY)
_.extend(query, {
access_id: config.ACCESS_ID,
timestamp: fixDate(new Date())
})
query = Object.keys(query).sort().map((key) => key + '=' + encodeURIComponent(query[key])).join('&')
const unhashedSignature = ['GET', endpoint, path, query].join('\n')
query += '&signature=' + hmac.update(unhashedSignature).digest('base64')
const url = protocol + endpoint + path + '?' + query
Q.spawn(function *() {
try {
const res = yield rp({
uri: url,
headers: {
'Accept': 'application/vnd.trivago.affiliate.hal+json;version=1',
'Accept-Language': 'en-GB'
},
resolveWithFullResponse: true
})
if (res.statusCode === 200) {
return res.body
} else { // res.statusCode === 202
doReq()
}
} catch (err) {
yield wait(100)
doReq()
}
})
}
function wait (times) {
return Q.promise((resolve, reject) => {
console.log('waiting for ', times)
setInterval(_ => resolve(), times)
})
}
module.exports = doReq
| Make a generic trivago api call function | Make a generic trivago api call function
| JavaScript | mit | TrvgoHack/Propsl | ---
+++
@@ -0,0 +1,59 @@
+'use strict'
+
+const crypto = require('crypto')
+const config = require('../config')
+const rp = require('request-promise')
+const Q = require('q')
+const _ = require('lodash')
+
+var fixDate = function (date) {
+ return (date).toISOString().split('.')[0] + 'Z'
+}
+
+const protocol = 'https://'
+const endpoint = 'api.trivago.com'
+
+function doReq (query, path) {
+ const hmac = crypto.createHmac('sha256', config.SECRET_KEY)
+
+ _.extend(query, {
+ access_id: config.ACCESS_ID,
+ timestamp: fixDate(new Date())
+ })
+
+ query = Object.keys(query).sort().map((key) => key + '=' + encodeURIComponent(query[key])).join('&')
+ const unhashedSignature = ['GET', endpoint, path, query].join('\n')
+ query += '&signature=' + hmac.update(unhashedSignature).digest('base64')
+ const url = protocol + endpoint + path + '?' + query
+
+ Q.spawn(function *() {
+ try {
+ const res = yield rp({
+ uri: url,
+ headers: {
+ 'Accept': 'application/vnd.trivago.affiliate.hal+json;version=1',
+ 'Accept-Language': 'en-GB'
+ },
+ resolveWithFullResponse: true
+ })
+
+ if (res.statusCode === 200) {
+ return res.body
+ } else { // res.statusCode === 202
+ doReq()
+ }
+ } catch (err) {
+ yield wait(100)
+ doReq()
+ }
+ })
+}
+
+function wait (times) {
+ return Q.promise((resolve, reject) => {
+ console.log('waiting for ', times)
+ setInterval(_ => resolve(), times)
+ })
+}
+
+module.exports = doReq | |
0f32d2e5fbf71d859dc2dcafe3d94955ca455a19 | 6/postgressql-insert.js | 6/postgressql-insert.js | var pg = require('pg');
var uri = 'postgres://fred:12345678@localhost/mydb';
pg.connect(uri, function(err, client, done) {
if (err) {
return console.error('error fetching client from pool', err);
}
var sqlStr = 'INSERT INTO myTable (name, date) VALUES ($1, $2)';
client.query(sqlStr, [ 'Fred', new Date() ], function(err, result) {
done();
});
});
| Add the example to use postgres to insert data into db. | Add the example to use postgres to insert data into db.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,13 @@
+var pg = require('pg');
+var uri = 'postgres://fred:12345678@localhost/mydb';
+
+pg.connect(uri, function(err, client, done) {
+ if (err) {
+ return console.error('error fetching client from pool', err);
+ }
+
+ var sqlStr = 'INSERT INTO myTable (name, date) VALUES ($1, $2)';
+ client.query(sqlStr, [ 'Fred', new Date() ], function(err, result) {
+ done();
+ });
+}); | |
cd2ea8efaaf7805df173c625d3938744273d5d9c | tests/unit/utilities/open-editor-test.js | tests/unit/utilities/open-editor-test.js | 'use strict';
var openEditor = require('../../../lib/utilities/open-editor');
var expect = require('chai').expect;
var td = require('testdouble');
describe('open-editor', function() {
beforeEach(function() {
td.replace(openEditor, '_env');
td.replace(openEditor, '_spawn');
});
afterEach(function() {
td.reset();
});
it('throws if EDITOR is not set', function() {
td.when(openEditor._env()).thenReturn({});
expect(function() { openEditor('test') }).to.throw('EDITOR environment variable is not set');
});
it('spawns EDITOR with passed file', function() {
td.when(openEditor._env()).thenReturn({ EDITOR: 'vi' });
openEditor('test');
td.verify(openEditor._spawn('vi', ['test'], { stdio: 'inherit' }));
});
describe('.canEdit()', function() {
it('returns false if EDITOR is not set', function() {
td.when(openEditor._env()).thenReturn({});
expect(openEditor.canEdit()).to.be.false;
});
it('returns true if EDITOR is set', function() {
td.when(openEditor._env()).thenReturn({ EDITOR: 'vi' });
expect(openEditor.canEdit()).to.be.true;
});
});
});
| Add tests for "open-editor" utility | tests: Add tests for "open-editor" utility
| JavaScript | mit | pzuraq/ember-cli,ef4/ember-cli,seawatts/ember-cli,patocallaghan/ember-cli,sivakumar-kailasam/ember-cli,jasonmit/ember-cli,fpauser/ember-cli,fpauser/ember-cli,Turbo87/ember-cli,mike-north/ember-cli,williamsbdev/ember-cli,rtablada/ember-cli,xtian/ember-cli,johanneswuerbach/ember-cli,lazybensch/ember-cli,givanse/ember-cli,yaymukund/ember-cli,ef4/ember-cli,gfvcastro/ember-cli,HeroicEric/ember-cli,gfvcastro/ember-cli,seawatts/ember-cli,akatov/ember-cli,trentmwillis/ember-cli,scalus/ember-cli,asakusuma/ember-cli,trabus/ember-cli,runspired/ember-cli,cibernox/ember-cli,calderas/ember-cli,trabus/ember-cli,johanneswuerbach/ember-cli,pixelhandler/ember-cli,trabus/ember-cli,mohlek/ember-cli,runspired/ember-cli,HeroicEric/ember-cli,trentmwillis/ember-cli,givanse/ember-cli,trentmwillis/ember-cli,kriswill/ember-cli,balinterdi/ember-cli,eccegordo/ember-cli,kriswill/ember-cli,buschtoens/ember-cli,thoov/ember-cli,ember-cli/ember-cli,patocallaghan/ember-cli,josemarluedke/ember-cli,Turbo87/ember-cli,mohlek/ember-cli,yaymukund/ember-cli,Turbo87/ember-cli,nathanhammond/ember-cli,pzuraq/ember-cli,cibernox/ember-cli,acorncom/ember-cli,jasonmit/ember-cli,pixelhandler/ember-cli,jasonmit/ember-cli,twokul/ember-cli,acorncom/ember-cli,kellyselden/ember-cli,kriswill/ember-cli,rtablada/ember-cli,romulomachado/ember-cli,kellyselden/ember-cli,lazybensch/ember-cli,kanongil/ember-cli,eccegordo/ember-cli,acorncom/ember-cli,jrjohnson/ember-cli,jgwhite/ember-cli,johanneswuerbach/ember-cli,givanse/ember-cli,mohlek/ember-cli,akatov/ember-cli,balinterdi/ember-cli,patocallaghan/ember-cli,sivakumar-kailasam/ember-cli,xtian/ember-cli,williamsbdev/ember-cli,BrianSipple/ember-cli,cibernox/ember-cli,givanse/ember-cli,gfvcastro/ember-cli,kanongil/ember-cli,akatov/ember-cli,ef4/ember-cli,kellyselden/ember-cli,nathanhammond/ember-cli,asakusuma/ember-cli,pzuraq/ember-cli,kategengler/ember-cli,scalus/ember-cli,gfvcastro/ember-cli,josemarluedke/ember-cli,romulomachado/ember-cli,HeroicEric/ember-cli,runspired/ember-cli,pixelhandler/ember-cli,jgwhite/ember-cli,raycohen/ember-cli,thoov/ember-cli,johanneswuerbach/ember-cli,eccegordo/ember-cli,lazybensch/ember-cli,pixelhandler/ember-cli,ember-cli/ember-cli,rtablada/ember-cli,calderas/ember-cli,seawatts/ember-cli,nathanhammond/ember-cli,johnotander/ember-cli,BrianSipple/ember-cli,twokul/ember-cli,fpauser/ember-cli,elwayman02/ember-cli,BrianSipple/ember-cli,johnotander/ember-cli,josemarluedke/ember-cli,elwayman02/ember-cli,nathanhammond/ember-cli,acorncom/ember-cli,scalus/ember-cli,mike-north/ember-cli,twokul/ember-cli,Turbo87/ember-cli,jrjohnson/ember-cli,mohlek/ember-cli,mike-north/ember-cli,romulomachado/ember-cli,ef4/ember-cli,josemarluedke/ember-cli,fpauser/ember-cli,ember-cli/ember-cli,thoov/ember-cli,thoov/ember-cli,kriswill/ember-cli,yaymukund/ember-cli,patocallaghan/ember-cli,eccegordo/ember-cli,yaymukund/ember-cli,lazybensch/ember-cli,BrianSipple/ember-cli,seawatts/ember-cli,trentmwillis/ember-cli,sivakumar-kailasam/ember-cli,trabus/ember-cli,kellyselden/ember-cli,calderas/ember-cli,raycohen/ember-cli,johnotander/ember-cli,mike-north/ember-cli,xtian/ember-cli,rtablada/ember-cli,williamsbdev/ember-cli,runspired/ember-cli,romulomachado/ember-cli,xtian/ember-cli,sivakumar-kailasam/ember-cli,kanongil/ember-cli,jgwhite/ember-cli,kanongil/ember-cli,buschtoens/ember-cli,cibernox/ember-cli,akatov/ember-cli,calderas/ember-cli,kategengler/ember-cli,jasonmit/ember-cli,pzuraq/ember-cli,johnotander/ember-cli,HeroicEric/ember-cli,williamsbdev/ember-cli,scalus/ember-cli,jgwhite/ember-cli,twokul/ember-cli | ---
+++
@@ -0,0 +1,42 @@
+'use strict';
+
+var openEditor = require('../../../lib/utilities/open-editor');
+
+var expect = require('chai').expect;
+var td = require('testdouble');
+
+describe('open-editor', function() {
+ beforeEach(function() {
+ td.replace(openEditor, '_env');
+ td.replace(openEditor, '_spawn');
+ });
+
+ afterEach(function() {
+ td.reset();
+ });
+
+ it('throws if EDITOR is not set', function() {
+ td.when(openEditor._env()).thenReturn({});
+ expect(function() { openEditor('test') }).to.throw('EDITOR environment variable is not set');
+ });
+
+ it('spawns EDITOR with passed file', function() {
+ td.when(openEditor._env()).thenReturn({ EDITOR: 'vi' });
+ openEditor('test');
+ td.verify(openEditor._spawn('vi', ['test'], { stdio: 'inherit' }));
+ });
+
+ describe('.canEdit()', function() {
+ it('returns false if EDITOR is not set', function() {
+ td.when(openEditor._env()).thenReturn({});
+ expect(openEditor.canEdit()).to.be.false;
+ });
+
+ it('returns true if EDITOR is set', function() {
+ td.when(openEditor._env()).thenReturn({ EDITOR: 'vi' });
+ expect(openEditor.canEdit()).to.be.true;
+ });
+ });
+});
+
+ | |
99172fb251dd0dc052f7056e44751fe0851ecd15 | test/resources/untyped-acl-ttl.js | test/resources/untyped-acl-ttl.js | module.exports = `@prefix acl: <http://www.w3.org/ns/auth/acl#>.
@prefix foaf: <http://xmlns.com/foaf/0.1/> .
<#authorization>
# Not present: a acl:Authorization;
acl:agent
<https://alice.example.com/#me>;
acl:accessTo <https://alice.example.com/docs/file1>;
acl:mode
acl:Read, acl:Write, acl:Control.`
| Add untyped acl test resource | Add untyped acl test resource
| JavaScript | mit | solid/solid-permissions | ---
+++
@@ -0,0 +1,11 @@
+module.exports = `@prefix acl: <http://www.w3.org/ns/auth/acl#>.
+@prefix foaf: <http://xmlns.com/foaf/0.1/> .
+
+<#authorization>
+ # Not present: a acl:Authorization;
+
+ acl:agent
+ <https://alice.example.com/#me>;
+ acl:accessTo <https://alice.example.com/docs/file1>;
+ acl:mode
+ acl:Read, acl:Write, acl:Control.` | |
7b8f2bebfaef9da1d59fd9cf25e93cebce4e9f19 | backfeed.js | backfeed.js | /* backfeed.js */
var Backfeed = (function() {
"use strict";
//define classes to add/remove
const errorStatusClass = 'glyphicon-remove';
const errorGroupClass = 'has-error';
const successStatusClass = 'glyphicon-ok';
const successGroupClass = 'has-success';
//attach change listeners to each input
var watchInputs = function(inputList) {
for (let formInput in inputList) {
console.log(inputList[formInput]);
var currInput = inputList[formInput];
var inputStatus = currInput['status'];
var inputGroup = currInput['group'];
_registerListener('keyup', currInput['input'], currInput['status'], currInput['group']);
}
};
//Add an event listener to a single form input
var _registerListener = function(eventName, element, status, group) {
element.addEventListener(eventName, function invoke(event) {
_updateStatus(event, status, group);
}, false);
};
//update the classes of the usernameInput field
var _updateStatus = function(event, statusTag, groupTag) {
var statusClasses = statusTag.classList;
var groupClasses = groupTag.classList;
if (event.target.checkValidity()) {
//contents are valid
if (!statusClasses.contains(successStatusClass)) {
statusClasses.add(successStatusClass);
}
if (!groupClasses.contains(successGroupClass)) {
groupClasses.add(successGroupClass);
}
if (statusClasses.contains(errorStatusClass)) {
statusClasses.remove(errorStatusClass);
}
if (groupClasses.contains(errorGroupClass)) {
groupClasses.remove(errorGroupClass);
}
} else {
//contents are invalid
if (statusClasses.contains(successStatusClass)) {
statusClasses.remove(successStatusClass);
}
if (groupClasses.contains(successGroupClass)) {
groupClasses.remove(successGroupClass);
}
if (!statusClasses.contains(errorStatusClass)) {
statusClasses.add(errorStatusClass);
}
if (!groupClasses.contains(errorGroupClass)) {
groupClasses.add(errorGroupClass);
}
}
};
return {
watch: watchInputs,
}
})();
| Add first version of code. | Add first version of code.
Until this point, development of this javascript was handled through codepen. However, this side project has reached a level of ambition that requires the power of real version control. | JavaScript | mit | whereswaldon/backfeed,whereswaldon/bill | ---
+++
@@ -0,0 +1,66 @@
+/* backfeed.js */
+var Backfeed = (function() {
+ "use strict";
+ //define classes to add/remove
+ const errorStatusClass = 'glyphicon-remove';
+ const errorGroupClass = 'has-error';
+ const successStatusClass = 'glyphicon-ok';
+ const successGroupClass = 'has-success';
+
+ //attach change listeners to each input
+ var watchInputs = function(inputList) {
+ for (let formInput in inputList) {
+ console.log(inputList[formInput]);
+ var currInput = inputList[formInput];
+ var inputStatus = currInput['status'];
+ var inputGroup = currInput['group'];
+ _registerListener('keyup', currInput['input'], currInput['status'], currInput['group']);
+ }
+ };
+
+ //Add an event listener to a single form input
+ var _registerListener = function(eventName, element, status, group) {
+ element.addEventListener(eventName, function invoke(event) {
+ _updateStatus(event, status, group);
+ }, false);
+ };
+
+ //update the classes of the usernameInput field
+ var _updateStatus = function(event, statusTag, groupTag) {
+ var statusClasses = statusTag.classList;
+ var groupClasses = groupTag.classList;
+ if (event.target.checkValidity()) {
+ //contents are valid
+ if (!statusClasses.contains(successStatusClass)) {
+ statusClasses.add(successStatusClass);
+ }
+ if (!groupClasses.contains(successGroupClass)) {
+ groupClasses.add(successGroupClass);
+ }
+ if (statusClasses.contains(errorStatusClass)) {
+ statusClasses.remove(errorStatusClass);
+ }
+ if (groupClasses.contains(errorGroupClass)) {
+ groupClasses.remove(errorGroupClass);
+ }
+ } else {
+ //contents are invalid
+ if (statusClasses.contains(successStatusClass)) {
+ statusClasses.remove(successStatusClass);
+ }
+ if (groupClasses.contains(successGroupClass)) {
+ groupClasses.remove(successGroupClass);
+ }
+ if (!statusClasses.contains(errorStatusClass)) {
+ statusClasses.add(errorStatusClass);
+ }
+ if (!groupClasses.contains(errorGroupClass)) {
+ groupClasses.add(errorGroupClass);
+ }
+ }
+ };
+
+ return {
+ watch: watchInputs,
+ }
+})(); | |
66864cbe083386e1f8b748f59938f8fd6b055199 | src/answer_generators/zillow/zillow_link.js | src/answer_generators/zillow/zillow_link.js | /*jslint continue: true, devel: true, evil: true, indent: 2, plusplus: true, rhino: true, unparam: true, vars: true, white: true */
function isNonBlankString(s) {
'use strict';
return s && (s.trim().length > 0);
}
function generateResults(recognitionResults, q, context) {
'use strict';
var list = recognitionResults['com.solveforall.recognition.location.UsAddress'];
if (!list || (list.length === 0)) {
return null;
}
var recognitionResult = list[0];
var shouldOutput = false;
var address = recognitionResult.streetAddress || '';
if (address.length > 0) {
var secondaryUnit = recognitionResult.secondaryUnit;
if (isNonBlankString(secondaryUnit)) {
address += ' ' + secondaryUnit;
}
address += ',';
}
var city = recognitionResult.city;
var hasCity = isNonBlankString(city);
var state = recognitionResult.stateAbbreviation;
var hasState = isNonBlankString(state);
if (hasCity) {
address += city;
}
if (hasState) {
if (hasCity) {
address += ',';
}
address += state;
shouldOutput = true;
}
var zip = recognitionResult.zipCode;
if (isNonBlankString(zip)) {
if (hasCity || hasState) {
address += ',';
}
address += zip;
shouldOutput = true;
}
if (!shouldOutput) {
return null;
}
var url = 'http://www.zillow.com/homes/';
url += address.replace(/\s+/, '-');
url += '_rb';
return [{
label: 'Zillow',
iconUrl: 'http://www.zillow.com/favicon.ico',
uri: url,
summaryHtml: 'View ' + _(address).escapeHTML() + ' on Zillow',
relevance: recognitionResult.recognitionLevel
}];
}
| Add Zillow link Answer Generator | Add Zillow link Answer Generator
| JavaScript | apache-2.0 | jtsay362/solveforall-example-plugins,jtsay362/solveforall-example-plugins | ---
+++
@@ -0,0 +1,74 @@
+/*jslint continue: true, devel: true, evil: true, indent: 2, plusplus: true, rhino: true, unparam: true, vars: true, white: true */
+function isNonBlankString(s) {
+ 'use strict';
+ return s && (s.trim().length > 0);
+}
+
+
+function generateResults(recognitionResults, q, context) {
+ 'use strict';
+
+ var list = recognitionResults['com.solveforall.recognition.location.UsAddress'];
+
+ if (!list || (list.length === 0)) {
+ return null;
+ }
+
+ var recognitionResult = list[0];
+
+ var shouldOutput = false;
+
+ var address = recognitionResult.streetAddress || '';
+
+ if (address.length > 0) {
+ var secondaryUnit = recognitionResult.secondaryUnit;
+ if (isNonBlankString(secondaryUnit)) {
+ address += ' ' + secondaryUnit;
+ }
+
+ address += ',';
+ }
+
+ var city = recognitionResult.city;
+ var hasCity = isNonBlankString(city);
+ var state = recognitionResult.stateAbbreviation;
+ var hasState = isNonBlankString(state);
+
+ if (hasCity) {
+ address += city;
+ }
+
+ if (hasState) {
+ if (hasCity) {
+ address += ',';
+ }
+ address += state;
+ shouldOutput = true;
+ }
+
+ var zip = recognitionResult.zipCode;
+
+ if (isNonBlankString(zip)) {
+ if (hasCity || hasState) {
+ address += ',';
+ }
+ address += zip;
+ shouldOutput = true;
+ }
+
+ if (!shouldOutput) {
+ return null;
+ }
+
+ var url = 'http://www.zillow.com/homes/';
+ url += address.replace(/\s+/, '-');
+ url += '_rb';
+
+ return [{
+ label: 'Zillow',
+ iconUrl: 'http://www.zillow.com/favicon.ico',
+ uri: url,
+ summaryHtml: 'View ' + _(address).escapeHTML() + ' on Zillow',
+ relevance: recognitionResult.recognitionLevel
+ }];
+} | |
fe94556ea4dd84965662dabbba7e4c32f2402968 | ui/src/shared/components/SourceIndicator.js | ui/src/shared/components/SourceIndicator.js | import React, {PropTypes} from 'react';
const SourceIndicator = React.createClass({
propTypes: {
source: PropTypes.shape({}).isRequired,
},
render() {
const {source} = this.props;
return (
<div className="source-indicator">
<span className="icon server"></span>
{source && source.name}
</div>
);
},
});
export default SourceIndicator;
| import React, {PropTypes} from 'react';
const SourceIndicator = React.createClass({
propTypes: {
sourceName: PropTypes.string,
},
render() {
const {sourceName} = this.props;
if (!sourceName) {
return null;
}
return (
<div className="source-indicator">
<span className="icon server"></span>
{sourceName}
</div>
);
},
});
export default SourceIndicator;
| Change sourceIndicator to receive a string instead of an object | Change sourceIndicator to receive a string instead of an object
| JavaScript | mit | influxdata/influxdb,influxdata/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb | ---
+++
@@ -2,15 +2,18 @@
const SourceIndicator = React.createClass({
propTypes: {
- source: PropTypes.shape({}).isRequired,
+ sourceName: PropTypes.string,
},
render() {
- const {source} = this.props;
+ const {sourceName} = this.props;
+ if (!sourceName) {
+ return null;
+ }
return (
<div className="source-indicator">
<span className="icon server"></span>
- {source && source.name}
+ {sourceName}
</div>
);
}, |
893eb08b44602119f0839f04a74703de033ae2d7 | src/languages/ceylon.js | src/languages/ceylon.js | /*
Language: Ceylon
Author: Lucas Werkmeister <mail@lucaswerkmeister.de>
*/
function(hljs) {
// 2.3. Identifiers and keywords
var KEYWORDS =
'assembly module package import alias class interface object given value ' +
'assign void function new of extends satisfies abstracts in out return ' +
'break continue throw assert dynamic if else switch case for while try ' +
'catch finally then let this outer super is exists nonempty';
// 7.4.1 Declaration Modifiers
var DECLARATION_MODIFIERS =
'shared abstract formal default actual variable late native deprecated' +
'final sealed annotation suppressWarnings small';
// 7.4.2 Documentation
var DOCUMENTATION =
'doc by license see throws tagged';
var LANGUAGE_ANNOTATIONS = DECLARATION_MODIFIERS + ' ' + DOCUMENTATION;
return {
keywords: KEYWORDS + ' ' + LANGUAGE_ANNOTATIONS,
contains: [
hljs.C_LINE_COMMENT_MODE,
hljs.C_BLOCK_COMMENT_MODE,
hljs.APOS_STRING_MODE, // TODO proper string literals with interpolation and unicode escapes
hljs.QUOTE_STRING_MODE
]
};
}
| Add first version of Ceylon language file | Add first version of Ceylon language file
| JavaScript | bsd-3-clause | liang42hao/highlight.js,highlightjs/highlight.js,adjohnson916/highlight.js,daimor/highlight.js,highlightjs/highlight.js,robconery/highlight.js,abhishekgahlot/highlight.js,weiyibin/highlight.js,delebash/highlight.js,sourrust/highlight.js,STRML/highlight.js,0x7fffffff/highlight.js,brennced/highlight.js,daimor/highlight.js,MakeNowJust/highlight.js,carlokok/highlight.js,highlightjs/highlight.js,SibuStephen/highlight.js,christoffer/highlight.js,martijnrusschen/highlight.js,dx285/highlight.js,ysbaddaden/highlight.js,martijnrusschen/highlight.js,tenbits/highlight.js,kayyyy/highlight.js,axter/highlight.js,Ankirama/highlight.js,jean/highlight.js,teambition/highlight.js,cicorias/highlight.js,ponylang/highlight.js,dx285/highlight.js,kevinrodbe/highlight.js,carlokok/highlight.js,ehornbostel/highlight.js,zachaysan/highlight.js,1st1/highlight.js,dYale/highlight.js,dublebuble/highlight.js,jean/highlight.js,aurusov/highlight.js,adam-lynch/highlight.js,dbkaplun/highlight.js,1st1/highlight.js,1st1/highlight.js,palmin/highlight.js,VoldemarLeGrand/highlight.js,J2TeaM/highlight.js,lizhil/highlight.js,carlokok/highlight.js,ilovezy/highlight.js,STRML/highlight.js,yxxme/highlight.js,VoldemarLeGrand/highlight.js,Ajunboys/highlight.js,krig/highlight.js,bluepichu/highlight.js,ysbaddaden/highlight.js,xing-zhi/highlight.js,xing-zhi/highlight.js,christoffer/highlight.js,Delermando/highlight.js,sourrust/highlight.js,lizhil/highlight.js,kba/highlight.js,jean/highlight.js,sourrust/highlight.js,axter/highlight.js,ysbaddaden/highlight.js,adam-lynch/highlight.js,Ankirama/highlight.js,StanislawSwierc/highlight.js,ponylang/highlight.js,palmin/highlight.js,aristidesstaffieri/highlight.js,devmario/highlight.js,kba/highlight.js,delebash/highlight.js,lead-auth/highlight.js,delebash/highlight.js,ehornbostel/highlight.js,J2TeaM/highlight.js,bogachev-pa/highlight.js,SibuStephen/highlight.js,taoger/highlight.js,cicorias/highlight.js,adam-lynch/highlight.js,MakeNowJust/highlight.js,taoger/highlight.js,brennced/highlight.js,Delermando/highlight.js,cicorias/highlight.js,Amrit01/highlight.js,alex-zhang/highlight.js,devmario/highlight.js,VoldemarLeGrand/highlight.js,Delermando/highlight.js,zachaysan/highlight.js,daimor/highlight.js,isagalaev/highlight.js,Ajunboys/highlight.js,robconery/highlight.js,liang42hao/highlight.js,isagalaev/highlight.js,bogachev-pa/highlight.js,Ankirama/highlight.js,brennced/highlight.js,STRML/highlight.js,krig/highlight.js,bogachev-pa/highlight.js,Amrit01/highlight.js,highlightjs/highlight.js,ehornbostel/highlight.js,Sannis/highlight.js,Amrit01/highlight.js,krig/highlight.js,zachaysan/highlight.js,devmario/highlight.js,dYale/highlight.js,weiyibin/highlight.js,axter/highlight.js,CausalityLtd/highlight.js,kba/highlight.js,0x7fffffff/highlight.js,dbkaplun/highlight.js,bluepichu/highlight.js,kayyyy/highlight.js,MakeNowJust/highlight.js,palmin/highlight.js,adjohnson916/highlight.js,dublebuble/highlight.js,dublebuble/highlight.js,Ajunboys/highlight.js,lizhil/highlight.js,abhishekgahlot/highlight.js,xing-zhi/highlight.js,adjohnson916/highlight.js,teambition/highlight.js,dx285/highlight.js,J2TeaM/highlight.js,StanislawSwierc/highlight.js,aurusov/highlight.js,taoger/highlight.js,yxxme/highlight.js,kevinrodbe/highlight.js,aristidesstaffieri/highlight.js,martijnrusschen/highlight.js,snegovick/highlight.js,0x7fffffff/highlight.js,CausalityLtd/highlight.js,ilovezy/highlight.js,Sannis/highlight.js,tenbits/highlight.js,yxxme/highlight.js,liang42hao/highlight.js,tenbits/highlight.js,alex-zhang/highlight.js,snegovick/highlight.js,weiyibin/highlight.js,aurusov/highlight.js,aristidesstaffieri/highlight.js,teambition/highlight.js,dbkaplun/highlight.js,snegovick/highlight.js,kevinrodbe/highlight.js,SibuStephen/highlight.js,abhishekgahlot/highlight.js,dYale/highlight.js,robconery/highlight.js,carlokok/highlight.js,Sannis/highlight.js,CausalityLtd/highlight.js,ilovezy/highlight.js,ponylang/highlight.js,kayyyy/highlight.js,christoffer/highlight.js,bluepichu/highlight.js,alex-zhang/highlight.js | ---
+++
@@ -0,0 +1,29 @@
+/*
+Language: Ceylon
+Author: Lucas Werkmeister <mail@lucaswerkmeister.de>
+*/
+function(hljs) {
+ // 2.3. Identifiers and keywords
+ var KEYWORDS =
+ 'assembly module package import alias class interface object given value ' +
+ 'assign void function new of extends satisfies abstracts in out return ' +
+ 'break continue throw assert dynamic if else switch case for while try ' +
+ 'catch finally then let this outer super is exists nonempty';
+ // 7.4.1 Declaration Modifiers
+ var DECLARATION_MODIFIERS =
+ 'shared abstract formal default actual variable late native deprecated' +
+ 'final sealed annotation suppressWarnings small';
+ // 7.4.2 Documentation
+ var DOCUMENTATION =
+ 'doc by license see throws tagged';
+ var LANGUAGE_ANNOTATIONS = DECLARATION_MODIFIERS + ' ' + DOCUMENTATION;
+ return {
+ keywords: KEYWORDS + ' ' + LANGUAGE_ANNOTATIONS,
+ contains: [
+ hljs.C_LINE_COMMENT_MODE,
+ hljs.C_BLOCK_COMMENT_MODE,
+ hljs.APOS_STRING_MODE, // TODO proper string literals with interpolation and unicode escapes
+ hljs.QUOTE_STRING_MODE
+ ]
+ };
+} | |
88fe9e90862113d5207ab339a1e9a47c9bb8ef5d | chat-plugins/music-box.js | chat-plugins/music-box.js | /* Music Box chat-plugin
* parses links into the HTML for music boxes
* by panpawn
*/
var https = require("https");
exports.commands = {
musicbox: function (target, room, user) {
if (!target) return this.sendReply("/musicbox link, link, link - parses it to be in a music box")
this.sendReply(parse(target));
}
};
function parse (link) {
try {
var id = link.substring(link.indexOf("=") + 1).replace(".","");
var options = {
host: 'www.googleapis.com',
path: '/youtube/v3/videos?id=' + id + '&key=AIzaSyBHyOyjHSrOW5wiS5A55Ekx4df_qBp6hkQ&fields=items(snippet(channelId,title,categoryId))&part=snippet'
};
var callback = function(response) {
var str = '';
response.on('data', function(chunk) {
str += chunk;
});
response.on('end', function() {
title = str.substring(str.indexOf("title") + 9, str.indexOf("categoryId") - 8);
});
};
https.request(options,callback).end();
} catch (e) {}
return '<a href="' + link + '"><button title="' + title + '">' + title + '</a></button><br />'; //parse it now
title = ""; //buggy will work this out later
} | Implement music box parsing command | Implement music box parsing command
| JavaScript | mit | BuzzyOG/Pokemon-Showdown,panpawn/Pokemon-Showdown,BuzzyOG/Pokemon-Showdown,panpawn/Gold-Server,Git-Worm/City-PS,panpawn/Gold-Server,BuzzyOG/Pokemon-Showdown,Git-Worm/City-PS,panpawn/Gold-Server,panpawn/Pokemon-Showdown | ---
+++
@@ -0,0 +1,36 @@
+/* Music Box chat-plugin
+ * parses links into the HTML for music boxes
+ * by panpawn
+ */
+
+var https = require("https");
+
+exports.commands = {
+ musicbox: function (target, room, user) {
+ if (!target) return this.sendReply("/musicbox link, link, link - parses it to be in a music box")
+ this.sendReply(parse(target));
+ }
+};
+
+function parse (link) {
+ try {
+ var id = link.substring(link.indexOf("=") + 1).replace(".","");
+ var options = {
+ host: 'www.googleapis.com',
+ path: '/youtube/v3/videos?id=' + id + '&key=AIzaSyBHyOyjHSrOW5wiS5A55Ekx4df_qBp6hkQ&fields=items(snippet(channelId,title,categoryId))&part=snippet'
+ };
+ var callback = function(response) {
+ var str = '';
+ response.on('data', function(chunk) {
+ str += chunk;
+ });
+ response.on('end', function() {
+ title = str.substring(str.indexOf("title") + 9, str.indexOf("categoryId") - 8);
+
+ });
+ };
+ https.request(options,callback).end();
+ } catch (e) {}
+ return '<a href="' + link + '"><button title="' + title + '">' + title + '</a></button><br />'; //parse it now
+ title = ""; //buggy will work this out later
+} | |
d894cec86eee44dfd07d3e906e80d4de145fafc8 | static/service-worker.js | static/service-worker.js | var CACHE_NAME = 'v1'
var CAHCED_DEFAULTS = [
'/',
'/styles/main.css',
'/styles/normalize.css',
'/scripts/main.js',
'/slides.json',
'https://fonts.googleapis.com/css?family=Material+Icons|Roboto:400,700'
]
this.addEventListener('install', onInstall)
this.addEventListener('fetch', onFetch)
function onInstall(event) {
event.waitUntil(
caches.open(CACHE_NAME).then(function (cache) {
return cache.addAll(CAHCED_DEFAULTS)
})
)
}
// Cache first strategy
function onFetch(event) {
event.respondWith(
// Try to grab from cache
caches.match(event.request)
.then(function (response) {
// If caches has response use that
if (response) {
return response
}
var request = event.request.clone();
// Else fetch it from network
return fetch(request)
.then(function (response) {
// If got a fancy response do not cache
if (!response || response.status !== 200 || response.type !== 'basic') {
return response
}
//Else cache it for the next time
var cacheableResponse = response.clone()
caches.open(CACHE_NAME)
.then(function (cache) {
cache.put(event.request, cacheableResponse)
})
return response
})
})
)
} | Fix service worker (sw path and scope were messed up) | Fix service worker (sw path and scope were messed up)
| JavaScript | unlicense | ghzmdr/showtell,ghzmdr/showtell | ---
+++
@@ -0,0 +1,65 @@
+var CACHE_NAME = 'v1'
+
+var CAHCED_DEFAULTS = [
+ '/',
+
+ '/styles/main.css',
+ '/styles/normalize.css',
+
+ '/scripts/main.js',
+
+ '/slides.json',
+
+ 'https://fonts.googleapis.com/css?family=Material+Icons|Roboto:400,700'
+]
+
+this.addEventListener('install', onInstall)
+this.addEventListener('fetch', onFetch)
+
+
+
+function onInstall(event) {
+ event.waitUntil(
+ caches.open(CACHE_NAME).then(function (cache) {
+ return cache.addAll(CAHCED_DEFAULTS)
+ })
+ )
+}
+
+// Cache first strategy
+function onFetch(event) {
+
+ event.respondWith(
+ // Try to grab from cache
+ caches.match(event.request)
+ .then(function (response) {
+
+ // If caches has response use that
+ if (response) {
+ return response
+ }
+
+ var request = event.request.clone();
+
+ // Else fetch it from network
+ return fetch(request)
+ .then(function (response) {
+
+ // If got a fancy response do not cache
+ if (!response || response.status !== 200 || response.type !== 'basic') {
+ return response
+ }
+
+ //Else cache it for the next time
+ var cacheableResponse = response.clone()
+
+ caches.open(CACHE_NAME)
+ .then(function (cache) {
+ cache.put(event.request, cacheableResponse)
+ })
+
+ return response
+ })
+ })
+ )
+} | |
f4c84d9c9b2cf7a15b947a6a1cb8d86e485431df | blueprints/ember-purify/index.js | blueprints/ember-purify/index.js | /*jshint node:true*/
module.exports = {
name: 'ember-purify',
afterinstall: function(options) {
this.addBowerPackageToProject('DOMPurify', '^0.8.3');
}
};
| Install bower deps on addon install | Install bower deps on addon install
| JavaScript | mit | sivakumar-kailasam/ember-purify,sivakumar-kailasam/ember-purify | ---
+++
@@ -0,0 +1,8 @@
+/*jshint node:true*/
+module.exports = {
+ name: 'ember-purify',
+
+ afterinstall: function(options) {
+ this.addBowerPackageToProject('DOMPurify', '^0.8.3');
+ }
+}; | |
184cd407f85f39d310516672fa04a18dff7c4b0c | src/colors.js | src/colors.js | define([], function() {
return {
getColor: function(colorSeries, boundsArray, val) {
for (var i in boundsArray) {
if ((val-boundsArray[i]>=0) && (val-boundsArray[parseInt(i)+1]<0)) {
return colorSeries[boundsArray.length][i];
}
}
return "#7F7F7F";
}
};
});
| Make color information available to iwindow | Make color information available to iwindow
No user-visible changes. If you don't plan to use the tract colors in
the info window, disregard.
| JavaScript | mit | codeforboston/ungentry,codeforboston/ungentry,codeforboston/ungentry,codeforboston/ungentry,codeforboston/ungentry | ---
+++
@@ -0,0 +1,12 @@
+define([], function() {
+ return {
+ getColor: function(colorSeries, boundsArray, val) {
+ for (var i in boundsArray) {
+ if ((val-boundsArray[i]>=0) && (val-boundsArray[parseInt(i)+1]<0)) {
+ return colorSeries[boundsArray.length][i];
+ }
+ }
+ return "#7F7F7F";
+ }
+ };
+}); | |
4be233251a810e6a74c3ffa271378e91e0148dca | backend/servers/mcapid/lib/dal/__tests__/files-tests.js | backend/servers/mcapid/lib/dal/__tests__/files-tests.js | const r = require('@lib/r');
const files = require('@dal/files')(r);
const tutil = require('@lib/test-utils')(r);
const dirUtils = require('@dal/dir-utils')(r);
describe('Test moveFileToDirectory', () => {
let project, dir1, fileInDir1;
beforeAll(async() => {
project = await tutil.createTestProject();
[dir1, dir11] = await dirUtils.createDirsFromParent('dir1/dir11', project.root_dir.id, project.id);
fileInDir1 = await tutil.createFile('file1.txt', dir1.id, project.id);
});
afterAll(async() => {
tutil.deleteProject(project.id);
});
test('it should throw an error if file directory does not exist', async() => {
await expect(files.moveFileToDirectory(fileInDir1.id, 'does-not-exist', dir11.id)).rejects.toThrow();
});
test('it should throw an error if file does not exist', async() => {
await expect(files.moveFileToDirectory('does-not-exist', dir1.id, dir11.id)).rejects.toThrow();
});
test('it should move the file', async() => {
let file = await files.moveFileToDirectory(fileInDir1.id, dir1.id, dir11.id);
expect(file.directory.id).toBe(dir11.id);
});
}); | Add tests for moving a file | Add tests for moving a file
| JavaScript | mit | materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org | ---
+++
@@ -0,0 +1,31 @@
+const r = require('@lib/r');
+const files = require('@dal/files')(r);
+const tutil = require('@lib/test-utils')(r);
+const dirUtils = require('@dal/dir-utils')(r);
+
+describe('Test moveFileToDirectory', () => {
+ let project, dir1, fileInDir1;
+
+ beforeAll(async() => {
+ project = await tutil.createTestProject();
+ [dir1, dir11] = await dirUtils.createDirsFromParent('dir1/dir11', project.root_dir.id, project.id);
+ fileInDir1 = await tutil.createFile('file1.txt', dir1.id, project.id);
+ });
+
+ afterAll(async() => {
+ tutil.deleteProject(project.id);
+ });
+
+ test('it should throw an error if file directory does not exist', async() => {
+ await expect(files.moveFileToDirectory(fileInDir1.id, 'does-not-exist', dir11.id)).rejects.toThrow();
+ });
+
+ test('it should throw an error if file does not exist', async() => {
+ await expect(files.moveFileToDirectory('does-not-exist', dir1.id, dir11.id)).rejects.toThrow();
+ });
+
+ test('it should move the file', async() => {
+ let file = await files.moveFileToDirectory(fileInDir1.id, dir1.id, dir11.id);
+ expect(file.directory.id).toBe(dir11.id);
+ });
+}); | |
ce177a9a20ddbe09072d0780069c8a49bc836cb0 | lib/node_modules/@stdlib/repl/ctor/lib/workspace_aliases.js | lib/node_modules/@stdlib/repl/ctor/lib/workspace_aliases.js | /**
* @license Apache-2.0
*
* Copyright (c) 2019 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.
*/
'use strict';
// MAIN //
/*
* List of workspace API aliases and corresponding argument completion compatibility.
*
* ## Notes
*
* - Each entry in the list has the following format:
*
* ```
* [ <alias>, <completion_flag>, ... ]
* ```
*
* where `<alias>` is a workspace API alias and `<completion_flag>` is an `integer` indicating whether an argument is compatible with workspace name or variable completion.
*
* - Completion flags:
*
* - `0`: non-completable
* - `1`: workspace name
* - `2`: workspace variable
*
* - For the purposes of TAB completion, only those positional arguments which expect workspace names or variables need to be included. For example, if an API has three parameters and only the first argument expects either a workspace name or variable, only that first argument needs to be included below; the remaining two arguments can be omitted, as those arguments are assumed to be incompatible with workspace name or variable completion. If an API has three parameters and only the second argument expects a workspace name or variable, only the first two arguments need to be included below, with the first argument documented as `null`; the remaining argument can be omitted.
*/
var aliases = [
// Note: keep in alphabetical order...
[ 'assignfrom', 1, 2 ],
[ 'assignin', 1, 2 ],
[ 'clearWorkspace', 1 ],
[ 'deleteWorkspace', 1 ],
[ 'evalin', 1 ],
[ 'loadWorkspace', 1 ],
[ 'renameWorkspace', 1 ],
[ 'varsWorkspace', 1 ],
[ 'workspace', 1 ]
];
// EXPORTS //
module.exports = aliases;
| Document workspace API completable arguments | Document workspace API completable arguments
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -0,0 +1,60 @@
+/**
+* @license Apache-2.0
+*
+* Copyright (c) 2019 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.
+*/
+
+'use strict';
+
+// MAIN //
+
+/*
+* List of workspace API aliases and corresponding argument completion compatibility.
+*
+* ## Notes
+*
+* - Each entry in the list has the following format:
+*
+* ```
+* [ <alias>, <completion_flag>, ... ]
+* ```
+*
+* where `<alias>` is a workspace API alias and `<completion_flag>` is an `integer` indicating whether an argument is compatible with workspace name or variable completion.
+*
+* - Completion flags:
+*
+* - `0`: non-completable
+* - `1`: workspace name
+* - `2`: workspace variable
+*
+* - For the purposes of TAB completion, only those positional arguments which expect workspace names or variables need to be included. For example, if an API has three parameters and only the first argument expects either a workspace name or variable, only that first argument needs to be included below; the remaining two arguments can be omitted, as those arguments are assumed to be incompatible with workspace name or variable completion. If an API has three parameters and only the second argument expects a workspace name or variable, only the first two arguments need to be included below, with the first argument documented as `null`; the remaining argument can be omitted.
+*/
+var aliases = [
+ // Note: keep in alphabetical order...
+ [ 'assignfrom', 1, 2 ],
+ [ 'assignin', 1, 2 ],
+ [ 'clearWorkspace', 1 ],
+ [ 'deleteWorkspace', 1 ],
+ [ 'evalin', 1 ],
+ [ 'loadWorkspace', 1 ],
+ [ 'renameWorkspace', 1 ],
+ [ 'varsWorkspace', 1 ],
+ [ 'workspace', 1 ]
+];
+
+
+// EXPORTS //
+
+module.exports = aliases; | |
76a2946b6dbb184bf252dd1c8b4d25e554e85499 | lib/node_modules/@stdlib/process/umask/scripts/binary_to_symbolic.js | lib/node_modules/@stdlib/process/umask/scripts/binary_to_symbolic.js | 'use strict';
var toBinaryString = require( '@stdlib/number/uint16/base/to-binary-string' );
var lpad = require( '@stdlib/string/left-pad' );
// Set this to "pretty" print results:
var PRETTY_PRINT = false;
var TOTAL;
var masks;
var bstr;
var perm;
var who;
var tmp;
var i;
var j;
// Total number of combinations (octal numbers):
TOTAL = 8 * 8 * 8 * 8;
// For each integer value (octal number), determine the symbolic notation equivalent to the value's binary representation...
masks = new Array( TOTAL );
for ( i = 0; i < TOTAL; i++ ) {
tmp = '';
// Convert the octal value to its binary representation:
bstr = toBinaryString( i );
// Discard the first four bits (a four digit octal number only uses 12 bits):
bstr = bstr.substring( 4 );
// Iterate over each bit starting from the fourth bit (left-to-right; the leftmost three bits are special mode bits, which are ignored when the mask is applied) and determine whether a bit is clear. If the bit is clear, the mask allows a permission to be enabled.
for ( j = 3; j < bstr.length; j++ ) {
who = (j-3) / 3;
if ( who === (who|0) ) { // is integer check
// Determine the user class:
who |= 0;
if ( who === 0 ) {
who = 'u';
} else if ( who === 1 ) {
who = 'g';
} else {
who = 'o';
}
if ( j >= 6 ) { // who|0 > 0
tmp += ',';
}
tmp += who + '=';
}
if ( bstr[ j ] === '0' ) {
// Determine the permission:
perm = j % 3;
if ( perm === 0 ) {
perm = 'r';
} else if ( perm === 1 ) {
perm = 'w';
} else {
perm = 'x';
}
tmp += perm;
}
}
// [ integer, octal, binary_string, symbolic_notation ]
masks[ i ] = [ i, lpad( i.toString( 8 ), 4, '0' ), bstr, tmp ];
}
if ( PRETTY_PRINT ) {
// Print the list of masks in symbolic notation:
for ( i = 0; i < TOTAL; i++ ) {
console.log( '%d = %s = %s = %s', masks[i][0], masks[i][1], masks[i][2], masks[i][3] );
}
} else {
console.log( JSON.stringify( masks ) );
}
| Add script to convert from binary representation to symbolic notation | Add script to convert from binary representation to symbolic notation
| JavaScript | apache-2.0 | stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib | ---
+++
@@ -0,0 +1,74 @@
+'use strict';
+
+var toBinaryString = require( '@stdlib/number/uint16/base/to-binary-string' );
+var lpad = require( '@stdlib/string/left-pad' );
+
+// Set this to "pretty" print results:
+var PRETTY_PRINT = false;
+
+var TOTAL;
+var masks;
+var bstr;
+var perm;
+var who;
+var tmp;
+var i;
+var j;
+
+// Total number of combinations (octal numbers):
+TOTAL = 8 * 8 * 8 * 8;
+
+// For each integer value (octal number), determine the symbolic notation equivalent to the value's binary representation...
+masks = new Array( TOTAL );
+for ( i = 0; i < TOTAL; i++ ) {
+ tmp = '';
+
+ // Convert the octal value to its binary representation:
+ bstr = toBinaryString( i );
+
+ // Discard the first four bits (a four digit octal number only uses 12 bits):
+ bstr = bstr.substring( 4 );
+
+ // Iterate over each bit starting from the fourth bit (left-to-right; the leftmost three bits are special mode bits, which are ignored when the mask is applied) and determine whether a bit is clear. If the bit is clear, the mask allows a permission to be enabled.
+ for ( j = 3; j < bstr.length; j++ ) {
+ who = (j-3) / 3;
+ if ( who === (who|0) ) { // is integer check
+ // Determine the user class:
+ who |= 0;
+ if ( who === 0 ) {
+ who = 'u';
+ } else if ( who === 1 ) {
+ who = 'g';
+ } else {
+ who = 'o';
+ }
+ if ( j >= 6 ) { // who|0 > 0
+ tmp += ',';
+ }
+ tmp += who + '=';
+ }
+ if ( bstr[ j ] === '0' ) {
+ // Determine the permission:
+ perm = j % 3;
+ if ( perm === 0 ) {
+ perm = 'r';
+ } else if ( perm === 1 ) {
+ perm = 'w';
+ } else {
+ perm = 'x';
+ }
+ tmp += perm;
+ }
+ }
+ // [ integer, octal, binary_string, symbolic_notation ]
+ masks[ i ] = [ i, lpad( i.toString( 8 ), 4, '0' ), bstr, tmp ];
+}
+
+if ( PRETTY_PRINT ) {
+ // Print the list of masks in symbolic notation:
+ for ( i = 0; i < TOTAL; i++ ) {
+ console.log( '%d = %s = %s = %s', masks[i][0], masks[i][1], masks[i][2], masks[i][3] );
+ }
+} else {
+ console.log( JSON.stringify( masks ) );
+} | |
810af368e821a4ae67972ce3d03ccbfb7d155983 | lib/service.js | lib/service.js | module.exports = function(options, callback) {
var fs = require('fs'),
restify = require('restify'),
util = require('util');
var serverOptions = {
name: 'queixinhas-API',
version: '0.0.1'
};
var server = restify.createServer(serverOptions);
server.use(restify.acceptParser(server.acceptable));
server.use(restify.queryParser());
server.use(restify.bodyParser());
/**
* HACK to accept some custom headers
*
* This should be removed when restify supports
* another way of doing this.
* This is expected in version 2.0
*/
var monkey_response = require("http").ServerResponse;
var original_writeHead = monkey_response.prototype.writeHead;
monkey_response.prototype.writeHead = function () {
var default_headers = this.getHeader("Access-Control-Allow-Headers");
if (default_headers) {
this.setHeader("Access-Control-Allow-Headers", default_headers + ", X-Mime-Type, X-Requested-With, X-File-Name, Cache-Control");
}
original_writeHead.apply(this, arguments);
}
// Get the models
var model = require('./models');
var Report = model.Report;
var Image = model.Image;
/**
* GET /reports/:reportID
*
* Returns the report with the given ID
*/
server.get('/reports/:reportID', function(req, res, next) {
var report = new Report({id: req.params.reportID});
report.on('load', function(){
res.send(report.toJSON());
});
report.load();
});
/**
* POST /reports
*
* Creates a new report
*/
server.post('/reports', function(req, res, next) {
var report = new Report(req.params);
report.on('save', function() {
res.send(report.toJSON());
});
report.save();
});
/**
* POST /images
*
* Creates a new image
*/
server.post('/images', function(req, res, next) {
if(req.files) {
for(var f in req.files) {
fs.readFile(req.files[f].path, function(err, data) {
if(err) {
// throw error
}
if(data) {
var image = new Image(data, req.files[f].type);
image.on('save', function() {
res.send({
'success': true,
'url': image.getURL()
});
});
image.save();
}
});
}
}
});
// Put the service listening
server.listen(options.port, function() {
if (callback) {
callback(server);
}
});
}; | Add the POST method for /images and /reports | Add the POST method for /images and /reports
| JavaScript | mit | queixinhas/queixinhas-api | ---
+++
@@ -0,0 +1,104 @@
+module.exports = function(options, callback) {
+
+ var fs = require('fs'),
+ restify = require('restify'),
+ util = require('util');
+
+ var serverOptions = {
+ name: 'queixinhas-API',
+ version: '0.0.1'
+ };
+
+ var server = restify.createServer(serverOptions);
+
+ server.use(restify.acceptParser(server.acceptable));
+ server.use(restify.queryParser());
+ server.use(restify.bodyParser());
+
+ /**
+ * HACK to accept some custom headers
+ *
+ * This should be removed when restify supports
+ * another way of doing this.
+ * This is expected in version 2.0
+ */
+ var monkey_response = require("http").ServerResponse;
+ var original_writeHead = monkey_response.prototype.writeHead;
+ monkey_response.prototype.writeHead = function () {
+ var default_headers = this.getHeader("Access-Control-Allow-Headers");
+ if (default_headers) {
+ this.setHeader("Access-Control-Allow-Headers", default_headers + ", X-Mime-Type, X-Requested-With, X-File-Name, Cache-Control");
+ }
+ original_writeHead.apply(this, arguments);
+ }
+
+ // Get the models
+ var model = require('./models');
+ var Report = model.Report;
+ var Image = model.Image;
+
+ /**
+ * GET /reports/:reportID
+ *
+ * Returns the report with the given ID
+ */
+ server.get('/reports/:reportID', function(req, res, next) {
+ var report = new Report({id: req.params.reportID});
+
+ report.on('load', function(){
+ res.send(report.toJSON());
+ });
+
+ report.load();
+ });
+
+ /**
+ * POST /reports
+ *
+ * Creates a new report
+ */
+ server.post('/reports', function(req, res, next) {
+ var report = new Report(req.params);
+ report.on('save', function() {
+ res.send(report.toJSON());
+ });
+ report.save();
+ });
+
+ /**
+ * POST /images
+ *
+ * Creates a new image
+ */
+ server.post('/images', function(req, res, next) {
+ if(req.files) {
+ for(var f in req.files) {
+ fs.readFile(req.files[f].path, function(err, data) {
+ if(err) {
+ // throw error
+ }
+
+ if(data) {
+ var image = new Image(data, req.files[f].type);
+
+ image.on('save', function() {
+ res.send({
+ 'success': true,
+ 'url': image.getURL()
+ });
+ });
+
+ image.save();
+ }
+ });
+ }
+ }
+ });
+
+ // Put the service listening
+ server.listen(options.port, function() {
+ if (callback) {
+ callback(server);
+ }
+ });
+}; | |
361b0aad5ce1fb53ebc1558540f5076f5ec8dbb0 | spec/confirm-challenge-list-spec.js | spec/confirm-challenge-list-spec.js | /* eslint-disable no-undef */
const controllers = require('../controllers');
// const db = require('../utils').db;
const fixtures = require('../spec/fixtures');
const Challenges = new controllers.Challenges();
// const Performances = new controllers.Performances();
// const Results = new controllers.Results();
// const Sessions = new controllers.Sessions();
// const StaticPages = new controllers.StaticPages();
// const Users = new controllers.Users();
const { testData } = fixtures;
const { testChallenges, testPerformance } = testData;
/* MAKE CHALLENGES */
describe('Make Challenges', () => {
const res = {
json: () => {
return;
},
send: () => {
return;
}
};
beforeEach(() => {
spyOn(res, 'json');
});
testChallenges.forEach(({ ErrorCode, UserNameNumber, SpotId }) => {
const req = {
body: {
spotId: SpotId
},
session: {
currentPerformance: testPerformance
},
user: {
nameNumber: UserNameNumber
}
};
// 0 = Successful challenge
// 1 = Spot Already Fully Challenged
// 2 = User Has Already Made A Challenge
if (ErrorCode === 0) {
it('Should Make The Challenge', (done) => {
Challenges.create(req, res)
.then(() => {
expect(res.json).toHaveBeenCalledWith({ code: 0 });
done();
});
});
} else if (ErrorCode === 1) {
it('Should reject the challenge with error code 1', (done) => {
Challenges.create(req, res)
.then(() => {
expect(res.json).toHaveBeenCalledWith({ code: 1 });
done();
});
});
} else {
it('Should reject the challenge with error code 2', (done) => {
Challenges.create(req, res)
.then(() => {
expect(res.json).toHaveBeenCalledWith({ code: 2 });
done();
});
});
}
});
});
| Add test challenge list test | Add test challenge list test
| JavaScript | mit | osumb/challenges,osumb/challenges,osumb/challenges,osumb/challenges | ---
+++
@@ -0,0 +1,74 @@
+/* eslint-disable no-undef */
+const controllers = require('../controllers');
+// const db = require('../utils').db;
+const fixtures = require('../spec/fixtures');
+
+const Challenges = new controllers.Challenges();
+// const Performances = new controllers.Performances();
+// const Results = new controllers.Results();
+// const Sessions = new controllers.Sessions();
+// const StaticPages = new controllers.StaticPages();
+// const Users = new controllers.Users();
+
+const { testData } = fixtures;
+
+const { testChallenges, testPerformance } = testData;
+
+/* MAKE CHALLENGES */
+describe('Make Challenges', () => {
+ const res = {
+ json: () => {
+ return;
+ },
+ send: () => {
+ return;
+ }
+ };
+
+ beforeEach(() => {
+ spyOn(res, 'json');
+ });
+
+ testChallenges.forEach(({ ErrorCode, UserNameNumber, SpotId }) => {
+ const req = {
+ body: {
+ spotId: SpotId
+ },
+ session: {
+ currentPerformance: testPerformance
+ },
+ user: {
+ nameNumber: UserNameNumber
+ }
+ };
+
+ // 0 = Successful challenge
+ // 1 = Spot Already Fully Challenged
+ // 2 = User Has Already Made A Challenge
+ if (ErrorCode === 0) {
+ it('Should Make The Challenge', (done) => {
+ Challenges.create(req, res)
+ .then(() => {
+ expect(res.json).toHaveBeenCalledWith({ code: 0 });
+ done();
+ });
+ });
+ } else if (ErrorCode === 1) {
+ it('Should reject the challenge with error code 1', (done) => {
+ Challenges.create(req, res)
+ .then(() => {
+ expect(res.json).toHaveBeenCalledWith({ code: 1 });
+ done();
+ });
+ });
+ } else {
+ it('Should reject the challenge with error code 2', (done) => {
+ Challenges.create(req, res)
+ .then(() => {
+ expect(res.json).toHaveBeenCalledWith({ code: 2 });
+ done();
+ });
+ });
+ }
+ });
+}); | |
eb24559fd611dbfa6b125938809a7c016a37f46a | ut/tabPanes_TimePaneSpec.js | ut/tabPanes_TimePaneSpec.js | describe('tab-panes TimePaneCtrler', function() {
var $rootScope;
var $controller;
beforeEach(module('popupApp'));
beforeEach(inject(function(_$rootScope_, _$controller_) {
$rootScope = _$rootScope_;
$controller = _$controller_;
}));
function StoreItemFactoryMock() {
return {
loadItem: function(keys, stores, default_value, scope, that, callback) {
// Use "$apply" because angular doesn't know this turn.
scope.$apply(function() {
var items = {
key_diffTime: {"hours":2,"minutes":0},
key_startTime: {"hours":18,"minutes":00},
key_stopTime: {"hours":20,"minutes":00}
};
angular.forEach(items, function(item, key) {
var store = stores[keys.indexOf(key)];
that[store] = (item != null) ? angular.fromJson(item) : default_value;
});
if (callback)
callback();
});
},
/*
* saveItem
*/
saveItem: function(keys, stringValues) {
}
};
};
it('should get current time object.', function() {
var timePaneCtrler = $controller('TimePaneCtrler', { $scope: $rootScope, StoreItemFactory: StoreItemFactoryMock() });
var currentTime = timePaneCtrler.getTime();
expect( currentTime.hours ).not.toBe(null);
expect( currentTime.minutes ).not.toBe(null);
});
});
| Create a spec for TimePaneCtrler | Create a spec for TimePaneCtrler
| JavaScript | apache-2.0 | shioyang/IDontDisturbMe,shioyang/IDontDisturbMe | ---
+++
@@ -0,0 +1,45 @@
+describe('tab-panes TimePaneCtrler', function() {
+ var $rootScope;
+ var $controller;
+ beforeEach(module('popupApp'));
+ beforeEach(inject(function(_$rootScope_, _$controller_) {
+ $rootScope = _$rootScope_;
+ $controller = _$controller_;
+ }));
+
+ function StoreItemFactoryMock() {
+ return {
+ loadItem: function(keys, stores, default_value, scope, that, callback) {
+ // Use "$apply" because angular doesn't know this turn.
+ scope.$apply(function() {
+ var items = {
+ key_diffTime: {"hours":2,"minutes":0},
+ key_startTime: {"hours":18,"minutes":00},
+ key_stopTime: {"hours":20,"minutes":00}
+ };
+ angular.forEach(items, function(item, key) {
+ var store = stores[keys.indexOf(key)];
+ that[store] = (item != null) ? angular.fromJson(item) : default_value;
+ });
+ if (callback)
+ callback();
+ });
+ },
+
+ /*
+ * saveItem
+ */
+ saveItem: function(keys, stringValues) {
+ }
+ };
+ };
+
+ it('should get current time object.', function() {
+ var timePaneCtrler = $controller('TimePaneCtrler', { $scope: $rootScope, StoreItemFactory: StoreItemFactoryMock() });
+ var currentTime = timePaneCtrler.getTime();
+ expect( currentTime.hours ).not.toBe(null);
+ expect( currentTime.minutes ).not.toBe(null);
+ });
+
+});
+ | |
1b2a2de06e98c609ed6832b9e85b1961c913c0d6 | morse-codec.js | morse-codec.js | var morseCodec = function(options) {
if (typeof options === 'undefined') {
options = {};
}
this.versions = {
'ITC': 'itc'
};
var ditDuration = options.ditDuration || 100;
var dahDuration = ditDuration * 3;
var characterSeparationDuration = ditDuration * 3;
var wordSeparationDuration = ditDuration * 7;
var version = options.version || this.versions.ITC;
var dictionary = {};
var encodingOptions = options.encoding || {
'characterSeparator': ' ',
'inputWordSeparator': ' ',
'wordSeparator': '/'
};
var dictionaries = {
'itc': {
'A': '.-',
'B': '-...',
'C': '-.-.',
'D': '-..',
'E': '.',
'F': '..-.',
'G': '--.',
'H': '....',
'I': '..',
'J': '.---',
'K': '-.-',
'L': '.-..',
'M': '--',
'N': '-.',
'O': '---',
'P': '.--.',
'Q': '--.-',
'R': '.-.',
'S': '...',
'T': '-',
'U': '..-',
'V': '...-',
'W': '.--',
'X': '-..-',
'Y': '-.--',
'Z': '--..',
'1': '.----',
'2': '..---',
'3': '...--',
'4': '....-',
'5': '.....',
'6': '-....',
'7': '--...',
'8': '---..',
'9': '----.',
'0': '-----'
}
};
this.encode = function(input) {
var length = input.length;
var output = '';
for (var i = 0; i < length; i++) {
var character = input.charAt(i).toUpperCase();
var parsedCharacter = dictionary[character];
if (typeof parsedCharacter !== 'undefined') {
output += parsedCharacter + encodingOptions.characterSeparator;
}
else {
if (character === encodingOptions.inputWordSeparator) {
var lastCharacterPosition = output.length - 1;
if (output.charAt(lastCharacterPosition) === encodingOptions.inputWordSeparator) {
output = output.substr(0, lastCharacterPosition);
}
output += encodingOptions.wordSeparator;
}
}
}
return output;
};
function getDictionary(version) {
var dictionary = {};
var versionDictionary = dictionaries[version];
for (var key in versionDictionary) {
dictionary[key] = versionDictionary[key];
}
return dictionary;
}
function init() {
dictionary = getDictionary(version);
}
init();
};
module.exports = morseCodec;
| Add library for handling morse code. This will be tapped when we want to send a pattern from the "not-yet-created" lights module. | Add library for handling morse code.
This will be tapped when we want to send a pattern from the "not-yet-created" lights module.
The current example is taking the number of active-builds and using that value as a pattern.
Ex.) three active builds => ...-- where each dit/dah corresponds to lights being on (difference is in duration).
| JavaScript | mit | ritterim/sparkles | ---
+++
@@ -0,0 +1,108 @@
+var morseCodec = function(options) {
+ if (typeof options === 'undefined') {
+ options = {};
+ }
+
+ this.versions = {
+ 'ITC': 'itc'
+ };
+
+ var ditDuration = options.ditDuration || 100;
+ var dahDuration = ditDuration * 3;
+ var characterSeparationDuration = ditDuration * 3;
+ var wordSeparationDuration = ditDuration * 7;
+ var version = options.version || this.versions.ITC;
+ var dictionary = {};
+ var encodingOptions = options.encoding || {
+ 'characterSeparator': ' ',
+ 'inputWordSeparator': ' ',
+ 'wordSeparator': '/'
+ };
+
+ var dictionaries = {
+ 'itc': {
+ 'A': '.-',
+ 'B': '-...',
+ 'C': '-.-.',
+ 'D': '-..',
+ 'E': '.',
+ 'F': '..-.',
+ 'G': '--.',
+ 'H': '....',
+ 'I': '..',
+ 'J': '.---',
+ 'K': '-.-',
+ 'L': '.-..',
+ 'M': '--',
+ 'N': '-.',
+ 'O': '---',
+ 'P': '.--.',
+ 'Q': '--.-',
+ 'R': '.-.',
+ 'S': '...',
+ 'T': '-',
+ 'U': '..-',
+ 'V': '...-',
+ 'W': '.--',
+ 'X': '-..-',
+ 'Y': '-.--',
+ 'Z': '--..',
+ '1': '.----',
+ '2': '..---',
+ '3': '...--',
+ '4': '....-',
+ '5': '.....',
+ '6': '-....',
+ '7': '--...',
+ '8': '---..',
+ '9': '----.',
+ '0': '-----'
+ }
+ };
+
+ this.encode = function(input) {
+ var length = input.length;
+ var output = '';
+
+ for (var i = 0; i < length; i++) {
+ var character = input.charAt(i).toUpperCase();
+ var parsedCharacter = dictionary[character];
+
+ if (typeof parsedCharacter !== 'undefined') {
+ output += parsedCharacter + encodingOptions.characterSeparator;
+ }
+ else {
+ if (character === encodingOptions.inputWordSeparator) {
+ var lastCharacterPosition = output.length - 1;
+
+ if (output.charAt(lastCharacterPosition) === encodingOptions.inputWordSeparator) {
+ output = output.substr(0, lastCharacterPosition);
+ }
+
+ output += encodingOptions.wordSeparator;
+ }
+ }
+ }
+
+ return output;
+ };
+
+ function getDictionary(version) {
+ var dictionary = {};
+ var versionDictionary = dictionaries[version];
+
+ for (var key in versionDictionary) {
+ dictionary[key] = versionDictionary[key];
+ }
+
+ return dictionary;
+ }
+
+ function init() {
+ dictionary = getDictionary(version);
+ }
+
+ init();
+};
+
+module.exports = morseCodec; | |
ad40a8a6eb20d07b6701680847d5d895415ea38f | bin/npm-yarn-compare.js | bin/npm-yarn-compare.js | #!/usr/bin/env node
process.title = 'npm-yarn-compare';
let child_process = require('child_process'),
prettyMs = require('pretty-ms'),
clc = require('cli-color');
let packageName = process.argv[2];
console.log('🛀 Checking if yarn is installed...');
let cmdExist = child_process.execSync('hash yarn').toString().trim();
if (cmdExist !== '') {
console.log('🤕 yarn command not found in a global scope.');
console.log('😴 Installing yarn...');
child_process.execSync('npm install -g yarn');
} else {
console.log('👯 yarn exists in a global scope');
}
console.log('🛀 Adding ' + clc.green(packageName) + ' with ' + clc.blue('yarn'));
let timeStamp = Date.now();
child_process.execSync('yarn add ' + packageName + ' > /dev/null 2>&1');
let timeTaken = Date.now() - timeStamp;
console.log('🚀 Time taken by yarn to add ' + clc.red(prettyMs(timeTaken)) + '');
console.log('🛀 Removing ' + clc.green(packageName) + ' with ' + clc.blue('yarn'));
timeStamp = Date.now();
child_process.execSync('yarn remove ' + packageName + ' > /dev/null 2>&1');
timeTaken = Date.now() - timeStamp;
console.log('🚀 Time taken by yarn to remove ' + clc.red(prettyMs(timeTaken)) + '');
timeStamp = Date.now();
console.log('🛀 Installing ' + clc.green(packageName) + ' with ' + clc.blue('npm'));
child_process.execSync('npm install ' + packageName + ' > /dev/null 2>&1');
timeTaken = Date.now() - timeStamp;
console.log('🚀 Time taken by npm to install ' + clc.red(prettyMs(timeTaken)) + '');
console.log('🛀 Removing ' + clc.green(packageName) + ' with ' + clc.blue('npm'));
timeStamp = Date.now();
child_process.execSync('npm uninstall ' + packageName + ' > /dev/null 2>&1');
timeTaken = Date.now() - timeStamp;
console.log('🚀 Time taken by npm to uninstall ' + clc.red(prettyMs(timeTaken)) + '');
| Add binary with v1 code. | Add binary with v1 code.
| JavaScript | mit | supreetpal/npmvsyarn | ---
+++
@@ -0,0 +1,44 @@
+#!/usr/bin/env node
+
+process.title = 'npm-yarn-compare';
+
+let child_process = require('child_process'),
+ prettyMs = require('pretty-ms'),
+ clc = require('cli-color');
+
+let packageName = process.argv[2];
+
+console.log('🛀 Checking if yarn is installed...');
+let cmdExist = child_process.execSync('hash yarn').toString().trim();
+
+if (cmdExist !== '') {
+ console.log('🤕 yarn command not found in a global scope.');
+ console.log('😴 Installing yarn...');
+ child_process.execSync('npm install -g yarn');
+} else {
+ console.log('👯 yarn exists in a global scope');
+}
+
+console.log('🛀 Adding ' + clc.green(packageName) + ' with ' + clc.blue('yarn'));
+let timeStamp = Date.now();
+child_process.execSync('yarn add ' + packageName + ' > /dev/null 2>&1');
+let timeTaken = Date.now() - timeStamp;
+console.log('🚀 Time taken by yarn to add ' + clc.red(prettyMs(timeTaken)) + '');
+
+console.log('🛀 Removing ' + clc.green(packageName) + ' with ' + clc.blue('yarn'));
+timeStamp = Date.now();
+child_process.execSync('yarn remove ' + packageName + ' > /dev/null 2>&1');
+timeTaken = Date.now() - timeStamp;
+console.log('🚀 Time taken by yarn to remove ' + clc.red(prettyMs(timeTaken)) + '');
+
+timeStamp = Date.now();
+console.log('🛀 Installing ' + clc.green(packageName) + ' with ' + clc.blue('npm'));
+child_process.execSync('npm install ' + packageName + ' > /dev/null 2>&1');
+timeTaken = Date.now() - timeStamp;
+console.log('🚀 Time taken by npm to install ' + clc.red(prettyMs(timeTaken)) + '');
+
+console.log('🛀 Removing ' + clc.green(packageName) + ' with ' + clc.blue('npm'));
+timeStamp = Date.now();
+child_process.execSync('npm uninstall ' + packageName + ' > /dev/null 2>&1');
+timeTaken = Date.now() - timeStamp;
+console.log('🚀 Time taken by npm to uninstall ' + clc.red(prettyMs(timeTaken)) + ''); | |
4891d09f6754607b7b41551ea2a421588552db69 | javascript/control_structure/control.js | javascript/control_structure/control.js | // operator if..elseif..else
/*
JavaScript has a similar set of control structures to other languages in the C family.
Conditional statements are supported by if and else; you can chain them together if you like:
*/
var name = "Nick";
if ( name == "Mark"){
name+= "!";
}else if( name == "Nick"){
name +="!!";
}else{
name = "!" + name;
}
console.log(name);
/*
JavaScript has while loops and do-while loops.
The first is good for basic looping; the second for loops where you wish to ensure that
the body of the loop is executed at least once:
*/ | Structure of the operators if else | Structure of the operators if else
| JavaScript | mit | niksolaz/Learning-Javacript,niksolaz/Learning-Javacript,niksolaz/Learning-Javacript,niksolaz/Learning-Javacript,niksolaz/Learning-Javacript,niksolaz/Learning-Javacript | ---
+++
@@ -0,0 +1,22 @@
+// operator if..elseif..else
+/*
+JavaScript has a similar set of control structures to other languages in the C family.
+Conditional statements are supported by if and else; you can chain them together if you like:
+*/
+
+var name = "Nick";
+if ( name == "Mark"){
+ name+= "!";
+}else if( name == "Nick"){
+ name +="!!";
+}else{
+ name = "!" + name;
+}
+
+console.log(name);
+
+/*
+JavaScript has while loops and do-while loops.
+The first is good for basic looping; the second for loops where you wish to ensure that
+the body of the loop is executed at least once:
+*/ | |
34280c7360244fea4918c829cf4045919bfc9498 | www/js/init.js | www/js/init.js | // Insert script into the DOM
function insertScript(src) {
var a=document.createElement("script");
a.src=src;
document.head.appendChild(a);
}
insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/jquery.min.js");
insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/main.js");
insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/jquery.mobile.min.js");
insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/libs.js");
// We now have jQuery since the above are synchronous. Let’s grab the body of the Sprinklers app and inject them into the pages body
$.get("index.html",function(data){
var pages = $(data).find("body"),
getPassword = function(){
var popup = $("<div data-role='popup'>" +
// This needs to be made still......
"</div>");
// Set result as password
curr_pw = "";
};
$.mobile.loading("show");
$("body").html(pages);
// Set current IP to the device IP
curr_ip = document.URL.match(/https?:\/\/(.*)\/.*?/)[1];
// Disables site selection menu
curr_local = true;
// Update controller and load home page
update_controller().done(function(){
changePage("#sprinklers");
});
});
| Add loader for Arduino firmware | Base: Add loader for Arduino firmware
Point the Javascript URL to this URL:
http://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/
This will automatically intercept the UI and load the mobile app instead
| JavaScript | agpl-3.0 | OpenSprinkler/OpenSprinkler-App,OpenSprinkler/OpenSprinkler-App,OpenSprinkler/OpenSprinkler-App,PeteBa/OpenSprinkler-App,PeteBa/OpenSprinkler-App,PeteBa/OpenSprinkler-App | ---
+++
@@ -0,0 +1,38 @@
+// Insert script into the DOM
+function insertScript(src) {
+ var a=document.createElement("script");
+ a.src=src;
+ document.head.appendChild(a);
+}
+
+insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/jquery.min.js");
+insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/main.js");
+insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/jquery.mobile.min.js");
+insertScript("https://raw.githubusercontent.com/salbahra/Sprinklers/master/www/js/libs.js");
+
+// We now have jQuery since the above are synchronous. Let’s grab the body of the Sprinklers app and inject them into the pages body
+$.get("index.html",function(data){
+ var pages = $(data).find("body"),
+ getPassword = function(){
+ var popup = $("<div data-role='popup'>" +
+ // This needs to be made still......
+ "</div>");
+
+ // Set result as password
+ curr_pw = "";
+ };
+
+ $.mobile.loading("show");
+ $("body").html(pages);
+
+ // Set current IP to the device IP
+ curr_ip = document.URL.match(/https?:\/\/(.*)\/.*?/)[1];
+
+ // Disables site selection menu
+ curr_local = true;
+
+ // Update controller and load home page
+ update_controller().done(function(){
+ changePage("#sprinklers");
+ });
+}); | |
699a80458b1d7d3617b9d505ccd73fce99bca01f | src/trade-type-picker/helpText.js | src/trade-type-picker/helpText.js | export default ({
CALL: 'You win the payout if the exit spot is strictly higher than the entry spot.',
PUT: 'You win the payout if the exit spot is strictly lower than the entry spot.',
CALL2: 'You win the payout if the exit spot is strictly higher than the barrier.',
PUT2: 'You win the payout if the exit spot is strictly lower than the barrier.',
ONETOUCH: 'You win the payout if the market touches the barrier at any time during the contract period.',
NOTOUCH: 'You win the payout if the market never touches the barrier at any time during the contract period.',
EXPIRYRANGE: 'You win the payout if the exit spot is strictly higher than the Low barrier AND strictly lower than the High barrier.',
EXPIRYMISS: 'You win the payout if the exit spot is EITHER strictly higher than the High barrier, OR strictly lower than the Low barrier.',
RANGE: 'You win the payout if the market stays between (does not touch) either the High barrier or the Low barrier at any time during the contract period.',
UPORDOWN: 'You win the payout if the market touches either the High barrier or the Low barrier at any time during the contract period.',
ASIANU: 'You will win the payout if the last tick is higher than the average of the ticks.',
ASIAND: 'You will win the payout if the last tick is lower than the average of the ticks.',
DIGITMATCH: 'You will win the payout if the last digit of the last tick is the same as your prediction.',
DIGITDIFF: 'You will win the payout if the last digit of the last tick is not the same as your prediction.',
DIGITEVEN: 'You will win the payout if the last digit of the last tick is an even number (i.e., 2, 4, 6, 8, or 0).',
DIGITODD: 'You will win the payout if the last digit of the last tick is an odd number (i.e., 1, 3, 5, 7, or 9).',
DIGITOVER: 'You will win the payout if the last digit of the last tick is greater than your prediction.',
DIGITUNDER: 'You will win the payout if the last digit of the last tick is less than your prediction.',
SPREADU: 'Spread contracts payout based on the movement of the index relative to the entry level of the contract.',
SPREADD: 'Spread contracts payout based on the movement of the index relative to the entry level of the contract.',
});
| Add help text for trading types | Add help text for trading types
| JavaScript | mit | nuruddeensalihu/binary-next-gen,nuruddeensalihu/binary-next-gen,nazaninreihani/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen,nuruddeensalihu/binary-next-gen,binary-com/binary-next-gen,binary-com/binary-next-gen,nazaninreihani/binary-next-gen | ---
+++
@@ -0,0 +1,22 @@
+export default ({
+ CALL: 'You win the payout if the exit spot is strictly higher than the entry spot.',
+ PUT: 'You win the payout if the exit spot is strictly lower than the entry spot.',
+ CALL2: 'You win the payout if the exit spot is strictly higher than the barrier.',
+ PUT2: 'You win the payout if the exit spot is strictly lower than the barrier.',
+ ONETOUCH: 'You win the payout if the market touches the barrier at any time during the contract period.',
+ NOTOUCH: 'You win the payout if the market never touches the barrier at any time during the contract period.',
+ EXPIRYRANGE: 'You win the payout if the exit spot is strictly higher than the Low barrier AND strictly lower than the High barrier.',
+ EXPIRYMISS: 'You win the payout if the exit spot is EITHER strictly higher than the High barrier, OR strictly lower than the Low barrier.',
+ RANGE: 'You win the payout if the market stays between (does not touch) either the High barrier or the Low barrier at any time during the contract period.',
+ UPORDOWN: 'You win the payout if the market touches either the High barrier or the Low barrier at any time during the contract period.',
+ ASIANU: 'You will win the payout if the last tick is higher than the average of the ticks.',
+ ASIAND: 'You will win the payout if the last tick is lower than the average of the ticks.',
+ DIGITMATCH: 'You will win the payout if the last digit of the last tick is the same as your prediction.',
+ DIGITDIFF: 'You will win the payout if the last digit of the last tick is not the same as your prediction.',
+ DIGITEVEN: 'You will win the payout if the last digit of the last tick is an even number (i.e., 2, 4, 6, 8, or 0).',
+ DIGITODD: 'You will win the payout if the last digit of the last tick is an odd number (i.e., 1, 3, 5, 7, or 9).',
+ DIGITOVER: 'You will win the payout if the last digit of the last tick is greater than your prediction.',
+ DIGITUNDER: 'You will win the payout if the last digit of the last tick is less than your prediction.',
+ SPREADU: 'Spread contracts payout based on the movement of the index relative to the entry level of the contract.',
+ SPREADD: 'Spread contracts payout based on the movement of the index relative to the entry level of the contract.',
+}); | |
009e91723f6161dbe7bb08a2e607b2c4271bde74 | test/test431.js | test/test431.js | if(typeof exports === 'object') {
var assert = require("assert");
var alasql = require('..');
}
describe('Test 431 error in 8 and 108 convert formats', function() {
it('1. Should format time correctly', function(done) {
var date = new Date(2016, 0, 1, 0, 0, 0);
var correctTime = '00:00:00';
var res = alasql('SELECT VALUE CONVERT(STRING, ?, 108)', [date]);
assert.equal(res, correctTime);
res = alasql('SELECT VALUE CONVERT(STRING, ?, 8)', [date]);
assert.equal(res, correctTime);
done();
});
});
| Test for time conversion fix | Test for time conversion fix | JavaScript | mit | agershun/alasql,kanghj/alasql,kanghj/alasql,agershun/alasql,kanghj/alasql,agershun/alasql,agershun/alasql | ---
+++
@@ -0,0 +1,17 @@
+if(typeof exports === 'object') {
+ var assert = require("assert");
+ var alasql = require('..');
+}
+describe('Test 431 error in 8 and 108 convert formats', function() {
+
+ it('1. Should format time correctly', function(done) {
+ var date = new Date(2016, 0, 1, 0, 0, 0);
+ var correctTime = '00:00:00';
+ var res = alasql('SELECT VALUE CONVERT(STRING, ?, 108)', [date]);
+ assert.equal(res, correctTime);
+ res = alasql('SELECT VALUE CONVERT(STRING, ?, 8)', [date]);
+ assert.equal(res, correctTime);
+
+ done();
+ });
+}); | |
f8d34c9c3b5e3f322ead929b4032d0e5c533e2cd | test/test10.js | test/test10.js | // Test suite for woad.
// Run from 'test' subfolder
'use strict';
const lg = require('../woad.js');
const test = require('unit.js');
const fs = require('fs');
function testFunc() {
console.log('test10 started - testing duplicate name.');
const fname1 = './test10f1.txt';
const fname2 = './test10f2.txt';
const tname = 'test10';
const message = 'A logging message.';
var f1 = lg.create({'name': tname, 'file': fname1 });
var f2 = lg.create({'name': tname, 'file': fname2 });
// test we have the the first log file name from 'create'
test
.string(f1).is(tname);
// test the 2nd name is null
test
.value(f2).isNull();
lg.setlevel(f1, lg.TRACE);
lg.error(message);
lg.warn(message);
lg.info(message);
lg.verbose(message);
lg.debug(message);
lg.trace(message);
// test log file does not exists
fs.access(fname2, function(err) {
if (!err) {
test.fail('log file [' + fname2 + '] does exist.');
}
});
// test log file exists
fs.access(fname1, function(err) {
if (err) {
test.fail('log file [' + fname1 + '] does not exist.');
}
// test contents of log file
fs.readFile(fname1, (err, data) => {
if (err) {
test.fail('log file [' + fname1 + '] reading contents.')
}
var m1 = data.toString();
console.log(m1);
test
.string(m1).contains('ERROR')
.string(m1).contains('WARN')
.string(m1).contains('INFO')
.string(m1).contains('VERBOSE')
.string(m1).contains('DEBUG')
.string(m1).contains('TRACE')
.string(m1).contains('-')
.string(m1).contains(':')
.string(m1).contains(message);
});
});
}
testFunc();
| Test for duplicate name added. | Test for duplicate name added.
| JavaScript | mit | kelvin-martin/woad | ---
+++
@@ -0,0 +1,69 @@
+// Test suite for woad.
+// Run from 'test' subfolder
+'use strict';
+const lg = require('../woad.js');
+const test = require('unit.js');
+const fs = require('fs');
+
+function testFunc() {
+ console.log('test10 started - testing duplicate name.');
+ const fname1 = './test10f1.txt';
+ const fname2 = './test10f2.txt';
+ const tname = 'test10';
+ const message = 'A logging message.';
+
+ var f1 = lg.create({'name': tname, 'file': fname1 });
+ var f2 = lg.create({'name': tname, 'file': fname2 });
+
+ // test we have the the first log file name from 'create'
+ test
+ .string(f1).is(tname);
+
+ // test the 2nd name is null
+ test
+ .value(f2).isNull();
+
+ lg.setlevel(f1, lg.TRACE);
+
+ lg.error(message);
+ lg.warn(message);
+ lg.info(message);
+ lg.verbose(message);
+ lg.debug(message);
+ lg.trace(message);
+
+ // test log file does not exists
+ fs.access(fname2, function(err) {
+ if (!err) {
+ test.fail('log file [' + fname2 + '] does exist.');
+ }
+ });
+
+ // test log file exists
+ fs.access(fname1, function(err) {
+ if (err) {
+ test.fail('log file [' + fname1 + '] does not exist.');
+ }
+
+ // test contents of log file
+ fs.readFile(fname1, (err, data) => {
+ if (err) {
+ test.fail('log file [' + fname1 + '] reading contents.')
+ }
+ var m1 = data.toString();
+ console.log(m1);
+ test
+ .string(m1).contains('ERROR')
+ .string(m1).contains('WARN')
+ .string(m1).contains('INFO')
+ .string(m1).contains('VERBOSE')
+ .string(m1).contains('DEBUG')
+ .string(m1).contains('TRACE')
+ .string(m1).contains('-')
+ .string(m1).contains(':')
+ .string(m1).contains(message);
+ });
+ });
+}
+
+testFunc(); | |
8e1afd54645731ae67d115506e2a9cff418e2980 | website/core/AltGridBlock.js | website/core/AltGridBlock.js | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
'use strict';
const React = require('react');
const classNames = require('classnames');
class GridBlock extends React.Component {
renderBlock = origBlock => {
const blockDefaults = {
imageAlign: 'left',
};
const block = {
...blockDefaults,
...origBlock,
};
const blockClasses = classNames('blockElement', this.props.className, {
alignCenter: this.props.align === 'center',
alignRight: this.props.align === 'right',
fourByGridBlock: this.props.layout === 'fourColumn',
imageAlignSide:
block.image &&
(block.imageAlign === 'left' || block.imageAlign === 'right'),
imageAlignTop: block.image && block.imageAlign === 'top',
imageAlignRight: block.image && block.imageAlign === 'right',
imageAlignBottom: block.image && block.imageAlign === 'bottom',
imageAlignLeft: block.image && block.imageAlign === 'left',
threeByGridBlock: this.props.layout === 'threeColumn',
twoByGridBlock: this.props.layout === 'twoColumn',
});
const topLeftImage =
(block.imageAlign === 'top' || block.imageAlign === 'left') &&
this.renderBlockImage(block.image, block.imageLink, block.imageAlt);
const bottomRightImage =
(block.imageAlign === 'bottom' || block.imageAlign === 'right') &&
this.renderBlockImage(block.image, block.imageLink, block.imageAlt);
return (
<div className={blockClasses} key={block.title}>
{topLeftImage}
<div className="blockContent">
{this.renderBlockTitle(block.title)}
{block.content}
</div>
{bottomRightImage}
</div>
);
};
renderBlockImage(image, imageLink, imageAlt) {
if (!image) {
return null;
}
return (
<div className="blockImage">
{imageLink ? (
<a href={imageLink}>
<img src={image} alt={imageAlt} />
</a>
) : (
<img src={image} alt={imageAlt} />
)}
</div>
);
}
renderBlockTitle(title) {
if (!title) {
return null;
}
return <h2>{title}</h2>;
}
render() {
return (
<div className="gridBlock">
{this.props.contents.map(this.renderBlock, this)}
</div>
);
}
}
GridBlock.defaultProps = {
align: 'left',
contents: [],
layout: 'twoColumn',
};
module.exports = GridBlock;
| Introduce GridBlock component that doesn't parse markdown | Introduce GridBlock component that doesn't parse markdown
Reviewed By: jstejada
Differential Revision: D26202230
fbshipit-source-id: fa3fc259e1fc34ef5ce383c142ee45963e3354d6
| JavaScript | mit | yungsters/relay,voideanvalue/relay,atxwebs/relay,kassens/relay,wincent/relay,facebook/relay,kassens/relay,wincent/relay,atxwebs/relay,wincent/relay,wincent/relay,voideanvalue/relay,josephsavona/relay,xuorig/relay,atxwebs/relay,josephsavona/relay,wincent/relay,facebook/relay,xuorig/relay,facebook/relay,kassens/relay,yungsters/relay,voideanvalue/relay,josephsavona/relay,voideanvalue/relay,kassens/relay,voideanvalue/relay,xuorig/relay,voideanvalue/relay,kassens/relay,xuorig/relay,wincent/relay,atxwebs/relay,facebook/relay,xuorig/relay,facebook/relay,xuorig/relay,facebook/relay,yungsters/relay,kassens/relay | ---
+++
@@ -0,0 +1,103 @@
+/**
+ * Copyright (c) Facebook, Inc. and its affiliates.
+ *
+ * This source code is licensed under the MIT license found in the
+ * LICENSE file in the root directory of this source tree.
+ *
+ * @format
+ */
+
+'use strict';
+
+const React = require('react');
+
+const classNames = require('classnames');
+
+class GridBlock extends React.Component {
+ renderBlock = origBlock => {
+ const blockDefaults = {
+ imageAlign: 'left',
+ };
+
+ const block = {
+ ...blockDefaults,
+ ...origBlock,
+ };
+
+ const blockClasses = classNames('blockElement', this.props.className, {
+ alignCenter: this.props.align === 'center',
+ alignRight: this.props.align === 'right',
+ fourByGridBlock: this.props.layout === 'fourColumn',
+ imageAlignSide:
+ block.image &&
+ (block.imageAlign === 'left' || block.imageAlign === 'right'),
+ imageAlignTop: block.image && block.imageAlign === 'top',
+ imageAlignRight: block.image && block.imageAlign === 'right',
+ imageAlignBottom: block.image && block.imageAlign === 'bottom',
+ imageAlignLeft: block.image && block.imageAlign === 'left',
+ threeByGridBlock: this.props.layout === 'threeColumn',
+ twoByGridBlock: this.props.layout === 'twoColumn',
+ });
+
+ const topLeftImage =
+ (block.imageAlign === 'top' || block.imageAlign === 'left') &&
+ this.renderBlockImage(block.image, block.imageLink, block.imageAlt);
+
+ const bottomRightImage =
+ (block.imageAlign === 'bottom' || block.imageAlign === 'right') &&
+ this.renderBlockImage(block.image, block.imageLink, block.imageAlt);
+
+ return (
+ <div className={blockClasses} key={block.title}>
+ {topLeftImage}
+ <div className="blockContent">
+ {this.renderBlockTitle(block.title)}
+ {block.content}
+ </div>
+ {bottomRightImage}
+ </div>
+ );
+ };
+
+ renderBlockImage(image, imageLink, imageAlt) {
+ if (!image) {
+ return null;
+ }
+
+ return (
+ <div className="blockImage">
+ {imageLink ? (
+ <a href={imageLink}>
+ <img src={image} alt={imageAlt} />
+ </a>
+ ) : (
+ <img src={image} alt={imageAlt} />
+ )}
+ </div>
+ );
+ }
+
+ renderBlockTitle(title) {
+ if (!title) {
+ return null;
+ }
+
+ return <h2>{title}</h2>;
+ }
+
+ render() {
+ return (
+ <div className="gridBlock">
+ {this.props.contents.map(this.renderBlock, this)}
+ </div>
+ );
+ }
+}
+
+GridBlock.defaultProps = {
+ align: 'left',
+ contents: [],
+ layout: 'twoColumn',
+};
+
+module.exports = GridBlock; | |
3637584f3c858a5025494d508193302e8a1cd8f8 | test/hamjestSpec.js | test/hamjestSpec.js | 'use strict';
var _ = require('lodash-node')
, hamjest = require('../lib/hamjest')
, assertFalse = require('./asserts').assertFalse
;
describe('hamjest', function () {
it('should not export undefined matchers', function () {
_.forEach(hamjest, function (value, key) {
assertFalse(_.isUndefined(value), 'Undefined entry for key: ' + key);
});
});
});
| Add minimal sanity test for hamjest exports | Add minimal sanity test for hamjest exports
| JavaScript | mit | rluba/hamjest,rluba/hamjest | ---
+++
@@ -0,0 +1,14 @@
+'use strict';
+
+var _ = require('lodash-node')
+ , hamjest = require('../lib/hamjest')
+ , assertFalse = require('./asserts').assertFalse
+ ;
+
+describe('hamjest', function () {
+ it('should not export undefined matchers', function () {
+ _.forEach(hamjest, function (value, key) {
+ assertFalse(_.isUndefined(value), 'Undefined entry for key: ' + key);
+ });
+ });
+}); | |
a38d85b0914b7fbcd3e30d7776390605d6c08d4e | examples/fisherman.js | examples/fisherman.js | const mineflayer = require('mineflayer')
if (process.argv.length < 4 || process.argv.length > 6) {
console.log('Usage : node scoreboard.js <host> <port> [<name>] [<password>]')
process.exit(1)
}
const bot = mineflayer.createBot({
host: process.argv[2],
port: parseInt(process.argv[3]),
username: process.argv[4] ? process.argv[4] : 'fisherman',
password: process.argv[5],
verbose: true
})
// To fish we have to give bot the fishing rod and teleport bot to the water
// /give fisherman fishing_rod 1
// /teleport fisherman ~ ~ ~
// To eat we have to apply hunger first
// /effect fisherman minecraft:hunger 1 255
bot.on('message', (cm) => {
if (cm.toString().includes('start')) {
startFishing()
}
if (cm.toString().includes('stop')) {
stopFishing()
}
if (cm.toString().includes('eat')) {
eat()
}
})
let nowFishing = false
function onCollect (player, entity) {
if (entity.kind === 'Drops' && player === bot.entity) {
bot.removeListener('playerCollect', onCollect)
startFishing()
}
}
function startFishing () {
bot.chat('Fishing')
bot.equip(346, 'hand', (err) => {
if (err) {
return bot.chat(err.message)
}
nowFishing = true
bot.on('playerCollect', onCollect)
bot.fish((err) => {
nowFishing = false
if (err) {
bot.chat(err.message)
}
})
})
}
function stopFishing () {
bot.removeListener('playerCollect', onCollect)
if (nowFishing) {
bot.activateItem()
}
}
function eat () {
stopFishing()
bot.equip(349, 'hand', (err) => {
if (err) {
return bot.chat(err.message)
}
bot.consume((err) => {
if (err) {
return bot.chat(err.message)
}
})
})
}
| Add fishing and consume example | Add fishing and consume example
| JavaScript | mit | PrismarineJS/mineflayer,andrewrk/mineflayer | ---
+++
@@ -0,0 +1,89 @@
+const mineflayer = require('mineflayer')
+
+if (process.argv.length < 4 || process.argv.length > 6) {
+ console.log('Usage : node scoreboard.js <host> <port> [<name>] [<password>]')
+ process.exit(1)
+}
+
+const bot = mineflayer.createBot({
+ host: process.argv[2],
+ port: parseInt(process.argv[3]),
+ username: process.argv[4] ? process.argv[4] : 'fisherman',
+ password: process.argv[5],
+ verbose: true
+})
+
+// To fish we have to give bot the fishing rod and teleport bot to the water
+// /give fisherman fishing_rod 1
+// /teleport fisherman ~ ~ ~
+
+// To eat we have to apply hunger first
+// /effect fisherman minecraft:hunger 1 255
+
+bot.on('message', (cm) => {
+ if (cm.toString().includes('start')) {
+ startFishing()
+ }
+
+ if (cm.toString().includes('stop')) {
+ stopFishing()
+ }
+
+ if (cm.toString().includes('eat')) {
+ eat()
+ }
+})
+
+let nowFishing = false
+
+function onCollect (player, entity) {
+ if (entity.kind === 'Drops' && player === bot.entity) {
+ bot.removeListener('playerCollect', onCollect)
+ startFishing()
+ }
+}
+
+function startFishing () {
+ bot.chat('Fishing')
+ bot.equip(346, 'hand', (err) => {
+ if (err) {
+ return bot.chat(err.message)
+ }
+
+ nowFishing = true
+ bot.on('playerCollect', onCollect)
+
+ bot.fish((err) => {
+ nowFishing = false
+
+ if (err) {
+ bot.chat(err.message)
+ }
+ })
+ })
+
+}
+
+function stopFishing () {
+ bot.removeListener('playerCollect', onCollect)
+
+ if (nowFishing) {
+ bot.activateItem()
+ }
+}
+
+function eat () {
+ stopFishing()
+
+ bot.equip(349, 'hand', (err) => {
+ if (err) {
+ return bot.chat(err.message)
+ }
+
+ bot.consume((err) => {
+ if (err) {
+ return bot.chat(err.message)
+ }
+ })
+ })
+} | |
4a1389a2844388d11b595a7fc7cf85213ce2e221 | public/javascript/accountKitLogin.js | public/javascript/accountKitLogin.js | // initialize Account Kit with CSRF protection
AccountKit_OnInteractive = function () {
AccountKit.init(
{
appId: '169812573551460',
state: 'csrf',
version: 'v1.1',
fbAppEventsEnabled: true,
debug: true
}
)
}
// login callback
function loginCallback (response) {
console.log('<accountKitLogin.js , loginCallback > response ----> ', response)
if (response.status === 'PARTIALLY_AUTHENTICATED') {
console.log('<accountKitLogin.js , loginCallback > response.code = ', response.code, ' response.state = ', response.state)
document.getElementById('code').value = response.code
document.getElementById('csrf').value = response.state
document.getElementById('login_success').submit()
// Send code to server to exchange for access token
} else if (response.status === 'NOT_AUTHENTICATED') {
// handle authentication failure
} else if (response.status === 'BAD_PARAMS') {
// handle bad parameters
}
}
// phone form submission handler
function smsLogin () {
//let countryCodeSelect = document.getElementById('country_code')
//let countryCode = countryCodeSelect.options[countryCodeSelect.selectedIndex].value
//let phoneNumber = document.getElementById('phone_number').value
AccountKit.login(
'PHONE',
{countryCode: '+91', phoneNumber: ''}, // will use default values if not specified
loginCallback
)
}
| Create handling of accountKit in client side | Create handling of accountKit in client side
| JavaScript | mit | chandrajob365/ChatApp,chandrajob365/ChatApp | ---
+++
@@ -0,0 +1,40 @@
+// initialize Account Kit with CSRF protection
+ AccountKit_OnInteractive = function () {
+ AccountKit.init(
+ {
+ appId: '169812573551460',
+ state: 'csrf',
+ version: 'v1.1',
+ fbAppEventsEnabled: true,
+ debug: true
+ }
+ )
+ }
+
+ // login callback
+ function loginCallback (response) {
+ console.log('<accountKitLogin.js , loginCallback > response ----> ', response)
+ if (response.status === 'PARTIALLY_AUTHENTICATED') {
+ console.log('<accountKitLogin.js , loginCallback > response.code = ', response.code, ' response.state = ', response.state)
+ document.getElementById('code').value = response.code
+ document.getElementById('csrf').value = response.state
+ document.getElementById('login_success').submit()
+ // Send code to server to exchange for access token
+ } else if (response.status === 'NOT_AUTHENTICATED') {
+ // handle authentication failure
+ } else if (response.status === 'BAD_PARAMS') {
+ // handle bad parameters
+ }
+ }
+
+ // phone form submission handler
+ function smsLogin () {
+ //let countryCodeSelect = document.getElementById('country_code')
+ //let countryCode = countryCodeSelect.options[countryCodeSelect.selectedIndex].value
+ //let phoneNumber = document.getElementById('phone_number').value
+ AccountKit.login(
+ 'PHONE',
+ {countryCode: '+91', phoneNumber: ''}, // will use default values if not specified
+ loginCallback
+ )
+ } | |
49f2e660460a8fe3efb64e8037dd5a943f3a9999 | public_html/type-racer-controller.js | public_html/type-racer-controller.js | function TypeRacerCtrl($scope) {
this.selectedLevelName;
this.selectedLevelSpeed;
this.playerName;
this.$onInit = function() {
this.levels = [
{
levelName: 'Beginner',
charsPerSecond: 3
},
{
levelName: 'Intermediate',
charsPerSecond: 7
},
{
levelName: 'Expert',
charsPerSecond: 9
}
];
this.shouldShowRacingPage = false;
};
$scope.$watch(
(function() {return this.selectedLevelName;}).bind(this),
(function(newVal, oldVal) {
if (newVal !== oldVal) {
for (var index=0; index<this.levels.length; index++) {
for (var key in this.levels[index]) {
if (this.levels[index].hasOwnProperty(key)
&& key==='levelName'
&& this.levels[index][key]
=== this.selectedLevelName) {
this.selectedLevelSpeed =
this.levels[index]['charsPerSecond'];
}
}
}
}
}).bind(this));
}
/*
* Whether to show the racing page.
*
* @param {boolean} isSubmitted
*/
TypeRacerCtrl.prototype.showRacingPage = function(isSubmitted) {
this.shouldShowRacingPage = isSubmitted;
};
angular
.module('typeRacer')
.controller('TypeRacerCtrl', ['$scope', TypeRacerCtrl]); | Add the controller for the type racer game. | Add the controller for the type racer game. | JavaScript | mit | gbelwariar/TypeRacer,gbelwariar/TypeRacer | ---
+++
@@ -0,0 +1,55 @@
+function TypeRacerCtrl($scope) {
+ this.selectedLevelName;
+ this.selectedLevelSpeed;
+ this.playerName;
+
+ this.$onInit = function() {
+ this.levels = [
+ {
+ levelName: 'Beginner',
+ charsPerSecond: 3
+ },
+ {
+ levelName: 'Intermediate',
+ charsPerSecond: 7
+ },
+ {
+ levelName: 'Expert',
+ charsPerSecond: 9
+ }
+ ];
+ this.shouldShowRacingPage = false;
+ };
+
+ $scope.$watch(
+ (function() {return this.selectedLevelName;}).bind(this),
+ (function(newVal, oldVal) {
+ if (newVal !== oldVal) {
+ for (var index=0; index<this.levels.length; index++) {
+ for (var key in this.levels[index]) {
+ if (this.levels[index].hasOwnProperty(key)
+ && key==='levelName'
+ && this.levels[index][key]
+ === this.selectedLevelName) {
+ this.selectedLevelSpeed =
+ this.levels[index]['charsPerSecond'];
+ }
+ }
+ }
+ }
+ }).bind(this));
+}
+
+
+/*
+ * Whether to show the racing page.
+ *
+ * @param {boolean} isSubmitted
+ */
+TypeRacerCtrl.prototype.showRacingPage = function(isSubmitted) {
+ this.shouldShowRacingPage = isSubmitted;
+};
+
+angular
+ .module('typeRacer')
+ .controller('TypeRacerCtrl', ['$scope', TypeRacerCtrl]); | |
bb471dc55d06a5851acd35bb4ca79ee3811c6f0a | packages/es-components/src/components/base/spinner/Spinner.specs.js | packages/es-components/src/components/base/spinner/Spinner.specs.js | /* eslint-env jest */
import React from 'react';
import { render, cleanup } from 'react-testing-library';
import Spinner from './Spinner';
beforeEach(cleanup);
it('does not include title when not provided', () => {
const { queryByText } = render(
<Spinner description="test spinner description" />
);
expect(queryByText('Title')).toBeNull();
});
it('includes title when provided', () => {
const { getByText } = render(<Spinner title="Test spinner" />);
const title = getByText('Test spinner');
expect(title).not.toBeNull();
});
it('does not include desc when not provided', () => {
const { queryByText } = render(<Spinner title="Test spinner" />);
expect(queryByText('test spinner description')).toBeNull();
});
it('includes desc when not provided', () => {
const { getByText } = render(
<Spinner description="test spinner description" />
);
const desc = getByText('test spinner description');
expect(desc).not.toBeNull();
});
| Add tests to Spinner component | Update: Add tests to Spinner component
| JavaScript | mit | TWExchangeSolutions/es-components,jrios/es-components,TWExchangeSolutions/es-components,jrios/es-components,jrios/es-components | ---
+++
@@ -0,0 +1,33 @@
+/* eslint-env jest */
+
+import React from 'react';
+import { render, cleanup } from 'react-testing-library';
+import Spinner from './Spinner';
+
+beforeEach(cleanup);
+
+it('does not include title when not provided', () => {
+ const { queryByText } = render(
+ <Spinner description="test spinner description" />
+ );
+ expect(queryByText('Title')).toBeNull();
+});
+
+it('includes title when provided', () => {
+ const { getByText } = render(<Spinner title="Test spinner" />);
+ const title = getByText('Test spinner');
+ expect(title).not.toBeNull();
+});
+
+it('does not include desc when not provided', () => {
+ const { queryByText } = render(<Spinner title="Test spinner" />);
+ expect(queryByText('test spinner description')).toBeNull();
+});
+
+it('includes desc when not provided', () => {
+ const { getByText } = render(
+ <Spinner description="test spinner description" />
+ );
+ const desc = getByText('test spinner description');
+ expect(desc).not.toBeNull();
+}); | |
eb6590a9b0685b1f36905bacfec1f1a9027f00d4 | tools/nipponPrinterTests.js | tools/nipponPrinterTests.js | const minimist = require('minimist')
const SerialPort = require('serialport')
const portOptions = {
autoOpen: false,
baudRate: 115200,
parity: 'odd',
dataBits: 8,
stopBits: 1,
rtscts: false,
xon: true,
xoff: true
}
const args = minimist(process.argv.slice(2))
const device = args.dev || '/dev/ttyJ5'
const qrcodeStr = args.str || 'https://lamassu.is'
const port = new SerialPort(device, portOptions)
port.on('error', (err) => {
console.log(`[ERROR]: An error occurred for ${device}: ${err.message}`)
})
port.on('close', (err) => {
console.log(`[INFO]: Closed connection to ${device}`)
})
port.open((err) => {
if (err) {
console.log(`[ERROR]: Could not open ${device}. ` +
`Additional information: "${err.message}"`)
return
}
else console.log(`[INFO]: Successfully opened a connection to ${device}.`)
port.write('Thank you for using Lamassu\'s', 'utf-8')
port.write(Buffer.from([0x0a])) /* Line Feed */
port.write('Cryptomats! <3', 'utf-8')
port.write(Buffer.from([0x0a]))
port.write(`Visit us at ${qrcodeStr} or`, 'utf-8')
port.write(Buffer.from([0x0a]))
port.write('use the QR code.', 'utf-8')
const qrcodeLen = Math.floor(qrcodeStr.length / 256)
const qrcodeLenRemainder = qrcodeStr.length % 256
port.write(Buffer.from([0x1b, 0x71, 0x06, 0x03, 0x04, 0x05, qrcodeLenRemainder, qrcodeLen]))
port.write(qrcodeStr, 'utf-8')
port.write(Buffer.from([0x0a])) /* Line Feed */
port.write(Buffer.from([0x1b, 0x69])) /* Full Cut */
})
| Add test script for the Nippon kiosk printer | Add test script for the Nippon kiosk printer | JavaScript | unlicense | lamassu/lamassu-machine,lamassu/lamassu-machine,lamassu/lamassu-machine,lamassu/lamassu-machine | ---
+++
@@ -0,0 +1,52 @@
+const minimist = require('minimist')
+const SerialPort = require('serialport')
+
+const portOptions = {
+ autoOpen: false,
+ baudRate: 115200,
+ parity: 'odd',
+ dataBits: 8,
+ stopBits: 1,
+ rtscts: false,
+ xon: true,
+ xoff: true
+}
+
+const args = minimist(process.argv.slice(2))
+const device = args.dev || '/dev/ttyJ5'
+const qrcodeStr = args.str || 'https://lamassu.is'
+const port = new SerialPort(device, portOptions)
+
+
+port.on('error', (err) => {
+ console.log(`[ERROR]: An error occurred for ${device}: ${err.message}`)
+})
+
+port.on('close', (err) => {
+ console.log(`[INFO]: Closed connection to ${device}`)
+})
+
+port.open((err) => {
+ if (err) {
+ console.log(`[ERROR]: Could not open ${device}. ` +
+ `Additional information: "${err.message}"`)
+ return
+ }
+ else console.log(`[INFO]: Successfully opened a connection to ${device}.`)
+
+ port.write('Thank you for using Lamassu\'s', 'utf-8')
+ port.write(Buffer.from([0x0a])) /* Line Feed */
+ port.write('Cryptomats! <3', 'utf-8')
+ port.write(Buffer.from([0x0a]))
+ port.write(`Visit us at ${qrcodeStr} or`, 'utf-8')
+ port.write(Buffer.from([0x0a]))
+ port.write('use the QR code.', 'utf-8')
+
+ const qrcodeLen = Math.floor(qrcodeStr.length / 256)
+ const qrcodeLenRemainder = qrcodeStr.length % 256
+ port.write(Buffer.from([0x1b, 0x71, 0x06, 0x03, 0x04, 0x05, qrcodeLenRemainder, qrcodeLen]))
+ port.write(qrcodeStr, 'utf-8')
+
+ port.write(Buffer.from([0x0a])) /* Line Feed */
+ port.write(Buffer.from([0x1b, 0x69])) /* Full Cut */
+}) | |
e606304f9d074c8541aa45e376bb6cf3cc14137a | test/reducers/shogi/enhanceCanDropPosition_test.js | test/reducers/shogi/enhanceCanDropPosition_test.js | import shogi from '../../../frontend/reducers/shogi';
import * as Action from '../../../frontend/actions';
import Piece from '../../../frontend/src/shogi/piece';
import Board from '../../../frontend/src/shogi/board';
import memo from 'memo-is';
describe('shogi', () => {
describe('ENHANCE_CAN_DROP_PIECE', () => {
const board = memo().is(() => {
const board = new Board;
board.board = [
[
Piece.create({ type: '*', x: 9, y: 1 }),
Piece.create({ type: '*', x: 8, y: 1 }),
Piece.create({ type: '*', x: 7, y: 1 }),
],
[
Piece.create({ type: '*', x: 9, y: 2 }),
Piece.create({ type: 'P', x: 8, y: 2 }),
Piece.create({ type: '*', x: 7, y: 2 }),
],
[
Piece.create({ type: '*', x: 9, y: 3 }),
Piece.create({ type: '*', x: 8, y: 3 }),
Piece.create({ type: '*', x: 7, y: 3 }),
],
];
return board;
});
const expectedBoard = memo().is(() => {
const expectedBoard = new Board;
expectedBoard.board = [
[
Piece.create({ type: '*', x: 9, y: 1 }),
Piece.create({ type: '*', x: 8, y: 1 }),
Piece.create({ type: '*', x: 7, y: 1 }),
],
[
Piece.create({ type: '*', x: 9, y: 2, isDrop: true }),
Piece.create({ type: 'P', x: 8, y: 2 }),
Piece.create({ type: '*', x: 7, y: 2, isDrop: true }),
],
[
Piece.create({ type: '*', x: 9, y: 3, isDrop: true }),
Piece.create({ type: '*', x: 8, y: 3 }),
Piece.create({ type: '*', x: 7, y: 3, isDrop: true }),
],
];
return expectedBoard;
});
it('have property of `isDrop` if piece can be dropped', () => {
const piece = Piece.create({ type: 'P' });
const action = Action.enhanceCanDropPosition(piece);
const state = { board: board() };
shogi(state, action).should.eql({
...state,
board: expectedBoard(),
});
});
});
});
| Add reducer test for ENHANCE_CAN_DROP_PIECE. | Add reducer test for ENHANCE_CAN_DROP_PIECE.
| JavaScript | mit | mgi166/usi-front,mgi166/usi-front | ---
+++
@@ -0,0 +1,64 @@
+import shogi from '../../../frontend/reducers/shogi';
+import * as Action from '../../../frontend/actions';
+import Piece from '../../../frontend/src/shogi/piece';
+import Board from '../../../frontend/src/shogi/board';
+import memo from 'memo-is';
+
+describe('shogi', () => {
+ describe('ENHANCE_CAN_DROP_PIECE', () => {
+ const board = memo().is(() => {
+ const board = new Board;
+ board.board = [
+ [
+ Piece.create({ type: '*', x: 9, y: 1 }),
+ Piece.create({ type: '*', x: 8, y: 1 }),
+ Piece.create({ type: '*', x: 7, y: 1 }),
+ ],
+ [
+ Piece.create({ type: '*', x: 9, y: 2 }),
+ Piece.create({ type: 'P', x: 8, y: 2 }),
+ Piece.create({ type: '*', x: 7, y: 2 }),
+ ],
+ [
+ Piece.create({ type: '*', x: 9, y: 3 }),
+ Piece.create({ type: '*', x: 8, y: 3 }),
+ Piece.create({ type: '*', x: 7, y: 3 }),
+ ],
+ ];
+ return board;
+ });
+
+ const expectedBoard = memo().is(() => {
+ const expectedBoard = new Board;
+ expectedBoard.board = [
+ [
+ Piece.create({ type: '*', x: 9, y: 1 }),
+ Piece.create({ type: '*', x: 8, y: 1 }),
+ Piece.create({ type: '*', x: 7, y: 1 }),
+ ],
+ [
+ Piece.create({ type: '*', x: 9, y: 2, isDrop: true }),
+ Piece.create({ type: 'P', x: 8, y: 2 }),
+ Piece.create({ type: '*', x: 7, y: 2, isDrop: true }),
+ ],
+ [
+ Piece.create({ type: '*', x: 9, y: 3, isDrop: true }),
+ Piece.create({ type: '*', x: 8, y: 3 }),
+ Piece.create({ type: '*', x: 7, y: 3, isDrop: true }),
+ ],
+ ];
+ return expectedBoard;
+ });
+
+ it('have property of `isDrop` if piece can be dropped', () => {
+ const piece = Piece.create({ type: 'P' });
+ const action = Action.enhanceCanDropPosition(piece);
+ const state = { board: board() };
+
+ shogi(state, action).should.eql({
+ ...state,
+ board: expectedBoard(),
+ });
+ });
+ });
+}); | |
f99b4a72a5871b49dd95fa41bdf66ada81912e7e | test/plugin/in/client_test.js | test/plugin/in/client_test.js | var client = require('../../../lib/plugin/in/client.js'),
nock = require('nock'),
here = require('here').here;
describe('input plugin: client', function(){
var mockApiUrl = "http://test.com/json";
beforeEach(function(done) {
var testJsonApiResponse = here(/*
{
"data": {
"bio": "Sample",
"counts": {
"followed_by": 777,
"follows": 222,
"media": 500
},
"full_name": "evac",
"id": "1",
"profile_picture": "http://hideack.github.io/evac",
"username": "evac",
"website": "http://hideack.github.io/evac"
},
"meta": {
"code": 200
}
}
*/
).unindent();
nock("http://test.com").get('/json').reply(200, testJsonApiResponse, {"Content-Type": "application/json; charset=utf-8"});
done();
});
it('should be parse JSON API', function(done){
client.load({url: mockApiUrl, targetProperty:"data.counts.followed_by", json: true}, function(err, responses) {
err.should.be.false;
responses[0].should.be.equal(777);
done();
});
});
});
| Add input plugin test. - client plugin added. | Add input plugin test.
- client plugin added.
| JavaScript | mit | hideack/evac | ---
+++
@@ -0,0 +1,42 @@
+var client = require('../../../lib/plugin/in/client.js'),
+ nock = require('nock'),
+ here = require('here').here;
+
+describe('input plugin: client', function(){
+ var mockApiUrl = "http://test.com/json";
+
+ beforeEach(function(done) {
+ var testJsonApiResponse = here(/*
+ {
+ "data": {
+ "bio": "Sample",
+ "counts": {
+ "followed_by": 777,
+ "follows": 222,
+ "media": 500
+ },
+ "full_name": "evac",
+ "id": "1",
+ "profile_picture": "http://hideack.github.io/evac",
+ "username": "evac",
+ "website": "http://hideack.github.io/evac"
+ },
+ "meta": {
+ "code": 200
+ }
+ }
+ */
+ ).unindent();
+
+ nock("http://test.com").get('/json').reply(200, testJsonApiResponse, {"Content-Type": "application/json; charset=utf-8"});
+ done();
+ });
+
+ it('should be parse JSON API', function(done){
+ client.load({url: mockApiUrl, targetProperty:"data.counts.followed_by", json: true}, function(err, responses) {
+ err.should.be.false;
+ responses[0].should.be.equal(777);
+ done();
+ });
+ });
+}); | |
74fcbee17bd99b0586a155b0794f561428181660 | test/config/templates-schema.js | test/config/templates-schema.js | const fs = require('fs');
const path = require('path');
const jsYaml = require('js-yaml');
const should = require('should');
// eslint-disable-next-line no-unused-vars
const Config = require('../../lib/config');
const schema = require('../../lib/schemas');
describe('EG templates schema validation', () => {
['basic', 'getting-started'].forEach((template) => {
const basePath = path.join(__dirname, '../../bin/generators/gateway/templates', template, 'config');
['gateway.config', 'system.config'].forEach((config) => {
it(`${template} should pass the JSON schema validation for ${config}`, () => {
should(schema.validate(`http://express-gateway.io/models/${config}.json`,
jsYaml.load(fs.readFileSync(path.join(basePath, `${config}.yml`)))).isValid).be.true();
});
});
});
});
| Add template json schema test | Add template json schema test
| JavaScript | apache-2.0 | ExpressGateway/express-gateway | ---
+++
@@ -0,0 +1,19 @@
+const fs = require('fs');
+const path = require('path');
+const jsYaml = require('js-yaml');
+const should = require('should');
+// eslint-disable-next-line no-unused-vars
+const Config = require('../../lib/config');
+const schema = require('../../lib/schemas');
+
+describe('EG templates schema validation', () => {
+ ['basic', 'getting-started'].forEach((template) => {
+ const basePath = path.join(__dirname, '../../bin/generators/gateway/templates', template, 'config');
+ ['gateway.config', 'system.config'].forEach((config) => {
+ it(`${template} should pass the JSON schema validation for ${config}`, () => {
+ should(schema.validate(`http://express-gateway.io/models/${config}.json`,
+ jsYaml.load(fs.readFileSync(path.join(basePath, `${config}.yml`)))).isValid).be.true();
+ });
+ });
+ });
+}); | |
8cef34add0bbe730f4046faa9616aa99533bbe23 | test/BitwiseHash.js | test/BitwiseHash.js | var assert = require('assert'),
BitwiseHash = require('./../lib/BitwiseHash');
describe('BitwiseHash', function () {
it('Should create instance', function () {
var hash = new BitwiseHash('some data');
assert(hash instanceof BitwiseHash, 'Should be instance of BitwiseHash');
});
it('Should properly hash data', function () {
var hash;
hash = new BitwiseHash('some data');
assert.equal(hash.hash(), '-642587818', 'Should properly hash string data');
hash.setData(['another', 'data']);
assert.equal(hash.hash(), '-689840973', 'Should properly hash array data');
hash.setData({
foo: 'bar',
bar: 'foo'
});
assert.equal(hash.hash(), '-1074417128', 'Should properly hash object data');
});
});
| Add test for bitwise hash | Add test for bitwise hash
| JavaScript | mit | ghaiklor/data-2-hash | ---
+++
@@ -0,0 +1,25 @@
+var assert = require('assert'),
+ BitwiseHash = require('./../lib/BitwiseHash');
+
+describe('BitwiseHash', function () {
+ it('Should create instance', function () {
+ var hash = new BitwiseHash('some data');
+ assert(hash instanceof BitwiseHash, 'Should be instance of BitwiseHash');
+ });
+
+ it('Should properly hash data', function () {
+ var hash;
+
+ hash = new BitwiseHash('some data');
+ assert.equal(hash.hash(), '-642587818', 'Should properly hash string data');
+
+ hash.setData(['another', 'data']);
+ assert.equal(hash.hash(), '-689840973', 'Should properly hash array data');
+
+ hash.setData({
+ foo: 'bar',
+ bar: 'foo'
+ });
+ assert.equal(hash.hash(), '-1074417128', 'Should properly hash object data');
+ });
+}); | |
246fdaece68ae60c6f25fa59f27d9c4183371b9b | lib/logger.js | lib/logger.js | var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG: ';
}
this.util.log(type + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
| var Logger = function (config) {
this.config = config;
this.backend = this.config.backend || 'stdout'
this.level = this.config.level || "LOG_INFO"
if (this.backend == 'stdout') {
this.util = require('util');
} else {
if (this.backend == 'syslog') {
this.util = require('node-syslog');
this.util.init(config.application || 'statsd', this.util.LOG_PID | this.util.LOG_ODELAY, this.util.LOG_LOCAL0);
} else {
throw "Logger: Should be 'stdout' or 'syslog'."
}
}
}
Logger.prototype = {
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
type = 'DEBUG';
}
this.util.log(type + ": " + msg);
} else {
if (!type) {
type = this.level
if (!this.util[type]) {
throw "Undefined log level: " + type;
}
} else if (type == 'debug') {
type = "LOG_DEBUG";
}
this.util.log(this.util[type], msg);
}
}
}
exports.Logger = Logger
| Tweak log formating to append colon and space to stdout type. | Tweak log formating to append colon and space to stdout type.
| JavaScript | mit | VivienBarousse/statsd,blurredbits/statsd,tuxinaut/statsd,bmhatfield/statsd,DataDog/statsd,pagerinc/statsd,atsid/statsd,jmptrader/statsd,zzzbit/statsd,jxqlovejava/statsd,jxqlovejava/statsd,ngpestelos/statsd,jmptrader/statsd,tuxinaut/statsd,omniti-labs/statsd,ShalomCohen/statsd,Charlesdong/statsd,wyzssw/statsd,zzzbit/statsd,ScottKaiGu/statsd,VivienBarousse/statsd,AdamMagaluk/statsd-cloudwatch,rex/statsd,AdamMagaluk/statsd-cloudwatch,kickstarter/statsd,roflmao/statsd,bartoszcisek/statsd,jxqlovejava/statsd,jxqlovejava/statsd,cit-lab/statsd,Mindera/statsd,sdgdsffdsfff/statsd,kickstarter/statsd,ShalomCohen/statsd,tuxinaut/statsd,Charlesdong/statsd,zzzbit/statsd,abhi1021/statsd,DataDog/statsd,cit-lab/statsd,ShalomCohen/statsd,hjhart/statsd,Yelp/statsd,DataDog/statsd,bartoszcisek/statsd,crashlytics/statsd,jmptrader/statsd,kickstarter/statsd,Yelp/statsd,aronatkins/statsd,rex/statsd,joshughes/statsd,tuxinaut/statsd,aronatkins/statsd,Mindera/statsd,aronatkins/statsd,AdamMagaluk/statsd-cloudwatch,tuxinaut/statsd,roflmao/statsd,omniti-labs/statsd,abhi1021/statsd,zzzbit/statsd,ShalomCohen/statsd,abhi1021/statsd,MichaelLiZhou/statsd,jxqlovejava/statsd,tsheasha/statsd,easybiblabs/statsd,joshughes/statsd,tuxinaut/statsd,DataDog/statsd,abhi1021/statsd,jxqlovejava/statsd,blurredbits/statsd,cit-lab/statsd,Yelp/statsd,roflmao/statsd,omniti-labs/statsd,abhi1021/statsd,aronatkins/statsd,jxqlovejava/statsd,jxqlovejava/statsd,tsheasha/statsd,omniti-labs/statsd,blurredbits/statsd,sax/statsd,mdobson/link-statsd-elasticsearch,DataDog/statsd,VivienBarousse/statsd,cit-lab/statsd,jasonchaffee/statsd,omniti-labs/statsd,joshughes/statsd,aronatkins/statsd,blurredbits/statsd,VivienBarousse/statsd,joshughes/statsd,cit-lab/statsd,Yelp/statsd,blurredbits/statsd,zzzbit/statsd,sax/statsd,bartoszcisek/statsd,roflmao/statsd,ShalomCohen/statsd,etsy/statsd,Yelp/statsd,Charlesdong/statsd,sax/statsd,blurredbits/statsd,sax/statsd,kickstarter/statsd,sax/statsd,wyzssw/statsd,easybiblabs/statsd,Mindera/statsd,VivienBarousse/statsd,pagerinc/statsd,sdgdsffdsfff/statsd,bmhatfield/statsd,mdobson/link-statsd-elasticsearch,kickstarter/statsd,aronatkins/statsd,Yelp/statsd,sax/statsd,jmptrader/statsd,ShalomCohen/statsd,blurredbits/statsd,roflmao/statsd,tsheasha/statsd,DataDog/statsd,zzzbit/statsd,Mindera/statsd,roflmao/statsd,Yelp/statsd,aronatkins/statsd,jmptrader/statsd,joshughes/statsd,pagerinc/statsd,cit-lab/statsd,rex/statsd,atsid/statsd,sax/statsd,aronatkins/statsd,Yelp/statsd,tuxinaut/statsd,cit-lab/statsd,abhi1021/statsd,ShalomCohen/statsd,abhi1021/statsd,atsid/statsd,VivienBarousse/statsd,crashlytics/statsd,Mindera/statsd,jmptrader/statsd,Mindera/statsd,kickstarter/statsd,sdgdsffdsfff/statsd,kickstarter/statsd,MichaelLiZhou/statsd,tuxinaut/statsd,VivienBarousse/statsd,ShalomCohen/statsd,omniti-labs/statsd,zzzbit/statsd,roflmao/statsd,Mindera/statsd,bmhatfield/statsd,mdobson/link-statsd-elasticsearch,DataDog/statsd,tuxinaut/statsd,joshughes/statsd,zzzbit/statsd,crashlytics/statsd,DataDog/statsd,sax/statsd,DataDog/statsd,ScottKaiGu/statsd,wyzssw/statsd,jxqlovejava/statsd,etsy/statsd,VivienBarousse/statsd,sax/statsd,jmptrader/statsd,omniti-labs/statsd,abhi1021/statsd,jmptrader/statsd,ngpestelos/statsd,joshughes/statsd,jmptrader/statsd,zzzbit/statsd,hjhart/statsd,Mindera/statsd,aronatkins/statsd,ngpestelos/statsd,jasonchaffee/statsd,joshughes/statsd,roflmao/statsd,omniti-labs/statsd,omniti-labs/statsd,blurredbits/statsd,ScottKaiGu/statsd,abhi1021/statsd,kickstarter/statsd,etsy/statsd,VivienBarousse/statsd,blurredbits/statsd,roflmao/statsd,cit-lab/statsd,ShalomCohen/statsd,kickstarter/statsd,MichaelLiZhou/statsd,Yelp/statsd,Mindera/statsd,easybiblabs/statsd,joshughes/statsd,cit-lab/statsd,jasonchaffee/statsd | ---
+++
@@ -18,9 +18,9 @@
log: function (msg, type) {
if (this.backend == 'stdout') {
if (!type) {
- type = 'DEBUG: ';
+ type = 'DEBUG';
}
- this.util.log(type + msg);
+ this.util.log(type + ": " + msg);
} else {
if (!type) {
type = this.level |
5baba1ee915859c95d0c3d1a5d56861f8a66df36 | 16/graphicsmagick-resize.js | 16/graphicsmagick-resize.js | var gm = require('gm');
var dirpath = 'images/';
var imgname = 'download-logo.png';
var tmppath = 'tmp/';
gm(dirpath + imgname)
.resize(300, 200)
.write(tmppath + 'New_' + imgname, function (err) {
if (err)
throw err;
console.log('done');
});
| Add the example to resize the image file via garphicsmagick. | Add the example to resize the image file via garphicsmagick.
| JavaScript | mit | nicebook/Node.js-Reference,nicebook/Node.js-Reference,nicebook/Node.js-Reference | ---
+++
@@ -0,0 +1,13 @@
+var gm = require('gm');
+var dirpath = 'images/';
+var imgname = 'download-logo.png';
+var tmppath = 'tmp/';
+
+gm(dirpath + imgname)
+
+ .resize(300, 200)
+ .write(tmppath + 'New_' + imgname, function (err) {
+ if (err)
+ throw err;
+ console.log('done');
+}); | |
bde9bf0bd609a89609088e4903fd921f0acdbe78 | lib/compiler/ChildCompiler.js | lib/compiler/ChildCompiler.js | var extend = require('extend');
var Promise = require('bluebird');
var PluginError = require('../utils/PluginError');
/**
* @param {Compilation} compilation
* @param {Object} options
* @param {string} options.name Name required, because it used as cache kay in parent compilation.
* @param {string} [options.context] By default taken from parent compilation.
* @param {Object} [options.output] Output options. By default taken from parent compilation.
* @see http://webpack.github.io/docs/configuration.html#output
* @constructor
*/
function ChildCompiler(compilation, options) {
options = options || {};
var context = options.context || compilation.compiler.context;
var outputOptions = extend(true, {}, compilation.outputOptions, options.output || {});
var name = options.name;
var compiler = compilation.createChildCompiler(name, outputOptions);
compiler.context = context;
// Cache
compiler.plugin('compilation', function (compilation) {
if (compilation.cache) {
if (!compilation.cache[name]) {
compilation.cache[name] = {};
}
compilation.cache = compilation.cache[name];
}
});
this.compiler = compiler;
}
/**
* TODO: Restore the parent compilation to the state like it was before the child compilation (html-webpack-plugin)
* Taken from html-webpack-plugin
* @see https://github.com/ampedandwired/html-webpack-plugin
* @returns {Promise}
*/
ChildCompiler.prototype.run = function () {
var compiler = this.compiler;
return new Promise(function (resolve, reject) {
compiler.runAsChild(function (err, entries, compilation) {
var hasErrors = compilation.errors && compilation.errors.length;
if (hasErrors) {
var errorDetails = compilation.errors.map(function (error) {
return error.message + (error.error ? ':\n' + error.error : '');
}).join('\n');
reject(new PluginError('Child compilation %s failed: %s', compiler.name, errorDetails));
} else if (err) {
reject(err);
} else {
resolve(compilation);
}
});
});
}; | Add promise wrapper over the child compiler | Add promise wrapper over the child compiler
| JavaScript | mit | kisenka/docpack,kisenka/webpack-docs-plugin | ---
+++
@@ -0,0 +1,64 @@
+var extend = require('extend');
+var Promise = require('bluebird');
+var PluginError = require('../utils/PluginError');
+
+/**
+ * @param {Compilation} compilation
+ * @param {Object} options
+ * @param {string} options.name Name required, because it used as cache kay in parent compilation.
+ * @param {string} [options.context] By default taken from parent compilation.
+ * @param {Object} [options.output] Output options. By default taken from parent compilation.
+ * @see http://webpack.github.io/docs/configuration.html#output
+ * @constructor
+ */
+function ChildCompiler(compilation, options) {
+ options = options || {};
+ var context = options.context || compilation.compiler.context;
+ var outputOptions = extend(true, {}, compilation.outputOptions, options.output || {});
+ var name = options.name;
+
+ var compiler = compilation.createChildCompiler(name, outputOptions);
+ compiler.context = context;
+
+ // Cache
+ compiler.plugin('compilation', function (compilation) {
+ if (compilation.cache) {
+ if (!compilation.cache[name]) {
+ compilation.cache[name] = {};
+ }
+ compilation.cache = compilation.cache[name];
+ }
+ });
+
+ this.compiler = compiler;
+}
+
+/**
+ * TODO: Restore the parent compilation to the state like it was before the child compilation (html-webpack-plugin)
+ * Taken from html-webpack-plugin
+ * @see https://github.com/ampedandwired/html-webpack-plugin
+ * @returns {Promise}
+ */
+ChildCompiler.prototype.run = function () {
+ var compiler = this.compiler;
+
+ return new Promise(function (resolve, reject) {
+ compiler.runAsChild(function (err, entries, compilation) {
+ var hasErrors = compilation.errors && compilation.errors.length;
+
+ if (hasErrors) {
+ var errorDetails = compilation.errors.map(function (error) {
+ return error.message + (error.error ? ':\n' + error.error : '');
+ }).join('\n');
+
+ reject(new PluginError('Child compilation %s failed: %s', compiler.name, errorDetails));
+
+ } else if (err) {
+ reject(err);
+
+ } else {
+ resolve(compilation);
+ }
+ });
+ });
+}; | |
1f02ea68b643c87e2031f0a4d1ca870849708d65 | test/kanban-board.spec.js | test/kanban-board.spec.js | import Board from '../src/components/kanban-board.vue'
describe("KanbanBoard", () => {
it("should have child components", () => {
expect(Board.components.KanbanList).to.be.an('object')
})
it("should have computed properties", () => {
expect(Board.computed).to.be.an('object')
expect(Board.computed.todo).to.be.a('function')
expect(Board.computed.doing).to.be.a('function')
expect(Board.computed.done).to.be.a('function')
})
}) | Add tests for board vue component | Add tests for board vue component
| JavaScript | mit | drayah/xerpa-kanban,drayah/xerpa-kanban | ---
+++
@@ -0,0 +1,14 @@
+import Board from '../src/components/kanban-board.vue'
+
+describe("KanbanBoard", () => {
+ it("should have child components", () => {
+ expect(Board.components.KanbanList).to.be.an('object')
+ })
+
+ it("should have computed properties", () => {
+ expect(Board.computed).to.be.an('object')
+ expect(Board.computed.todo).to.be.a('function')
+ expect(Board.computed.doing).to.be.a('function')
+ expect(Board.computed.done).to.be.a('function')
+ })
+}) | |
2887771f4aa39e4065c43f485f308e23e5a4aec7 | packages/backbone/package.js | packages/backbone/package.js | Package.describe({
summary: "A minimalist client-side MVC framework"
});
Package.on_use(function (api) {
// XXX Backbone requires either jquery or zepto
api.use("jquery");
api.add_files("backbone.js", "client");
});
| Package.describe({
summary: "A minimalist client-side MVC framework"
});
Package.on_use(function (api, where) {
// XXX Backbone requires either jquery or zepto
api.use(["jquery", "json"]);
where = where || ['client', 'server'];
api.add_files("backbone.js", where);
});
| Allow backbone on the server also. | Allow backbone on the server also.
Also, add json dependency.
| JavaScript | mit | hristaki/meteor,TribeMedia/meteor,SeanOceanHu/meteor,akintoey/meteor,fashionsun/meteor,deanius/meteor,eluck/meteor,karlito40/meteor,meonkeys/meteor,pjump/meteor,AnjirHossain/meteor,sdeveloper/meteor,IveWong/meteor,jdivy/meteor,HugoRLopes/meteor,jenalgit/meteor,joannekoong/meteor,pjump/meteor,chasertech/meteor,D1no/meteor,DAB0mB/meteor,cbonami/meteor,shrop/meteor,williambr/meteor,msavin/meteor,yonglehou/meteor,imanmafi/meteor,shmiko/meteor,eluck/meteor,wmkcc/meteor,baysao/meteor,joannekoong/meteor,Ken-Liu/meteor,namho102/meteor,yonas/meteor-freebsd,esteedqueen/meteor,daltonrenaldo/meteor,elkingtonmcb/meteor,yonas/meteor-freebsd,chiefninew/meteor,JesseQin/meteor,devgrok/meteor,h200863057/meteor,Profab/meteor,elkingtonmcb/meteor,PatrickMcGuinness/meteor,juansgaitan/meteor,IveWong/meteor,EduShareOntario/meteor,meteor-velocity/meteor,wmkcc/meteor,meteor-velocity/meteor,eluck/meteor,henrypan/meteor,shmiko/meteor,meteor-velocity/meteor,yonglehou/meteor,yyx990803/meteor,Jeremy017/meteor,rabbyalone/meteor,rabbyalone/meteor,ashwathgovind/meteor,chiefninew/meteor,sclausen/meteor,daslicht/meteor,JesseQin/meteor,mauricionr/meteor,yinhe007/meteor,shadedprofit/meteor,mjmasn/meteor,benjamn/meteor,mirstan/meteor,justintung/meteor,vjau/meteor,Urigo/meteor,h200863057/meteor,cherbst/meteor,yonas/meteor-freebsd,JesseQin/meteor,paul-barry-kenzan/meteor,saisai/meteor,yinhe007/meteor,lorensr/meteor,allanalexandre/meteor,yanisIk/meteor,mauricionr/meteor,ericterpstra/meteor,Paulyoufu/meteor-1,devgrok/meteor,vacjaliu/meteor,zdd910/meteor,ndarilek/meteor,sitexa/meteor,D1no/meteor,ericterpstra/meteor,modulexcite/meteor,tdamsma/meteor,l0rd0fwar/meteor,cog-64/meteor,rozzzly/meteor,dboyliao/meteor,elkingtonmcb/meteor,evilemon/meteor,emmerge/meteor,johnthepink/meteor,eluck/meteor,somallg/meteor,kengchau/meteor,mubassirhayat/meteor,tdamsma/meteor,yalexx/meteor,GrimDerp/meteor,stevenliuit/meteor,lpinto93/meteor,kencheung/meteor,AlexR1712/meteor,sitexa/meteor,mauricionr/meteor,williambr/meteor,michielvanoeffelen/meteor,yanisIk/meteor,allanalexandre/meteor,servel333/meteor,karlito40/meteor,servel333/meteor,fashionsun/meteor,baysao/meteor,aldeed/meteor,pandeysoni/meteor,chinasb/meteor,Profab/meteor,qscripter/meteor,judsonbsilva/meteor,Paulyoufu/meteor-1,planet-training/meteor,youprofit/meteor,lieuwex/meteor,Eynaliyev/meteor,johnthepink/meteor,cherbst/meteor,baiyunping333/meteor,kencheung/meteor,chmac/meteor,4commerce-technologies-AG/meteor,pjump/meteor,jg3526/meteor,DAB0mB/meteor,aramk/meteor,yonas/meteor-freebsd,l0rd0fwar/meteor,chengxiaole/meteor,ashwathgovind/meteor,jeblister/meteor,ndarilek/meteor,alexbeletsky/meteor,johnthepink/meteor,ericterpstra/meteor,yonglehou/meteor,jeblister/meteor,daslicht/meteor,codedogfish/meteor,HugoRLopes/meteor,papimomi/meteor,shadedprofit/meteor,meonkeys/meteor,saisai/meteor,guazipi/meteor,sunny-g/meteor,lpinto93/meteor,youprofit/meteor,Eynaliyev/meteor,yalexx/meteor,chiefninew/meteor,karlito40/meteor,namho102/meteor,devgrok/meteor,planet-training/meteor,Puena/meteor,zdd910/meteor,akintoey/meteor,daltonrenaldo/meteor,bhargav175/meteor,mjmasn/meteor,codingang/meteor,calvintychan/meteor,shrop/meteor,dfischer/meteor,katopz/meteor,brdtrpp/meteor,justintung/meteor,aramk/meteor,elkingtonmcb/meteor,chasertech/meteor,justintung/meteor,kidaa/meteor,jirengu/meteor,HugoRLopes/meteor,LWHTarena/meteor,allanalexandre/meteor,GrimDerp/meteor,daslicht/meteor,msavin/meteor,sdeveloper/meteor,cbonami/meteor,ashwathgovind/meteor,zdd910/meteor,yinhe007/meteor,cog-64/meteor,nuvipannu/meteor,neotim/meteor,rabbyalone/meteor,jrudio/meteor,arunoda/meteor,whip112/meteor,justintung/meteor,TribeMedia/meteor,youprofit/meteor,cherbst/meteor,namho102/meteor,framewr/meteor,deanius/meteor,saisai/meteor,evilemon/meteor,juansgaitan/meteor,mubassirhayat/meteor,JesseQin/meteor,wmkcc/meteor,brettle/meteor,rozzzly/meteor,katopz/meteor,yanisIk/meteor,IveWong/meteor,shrop/meteor,SeanOceanHu/meteor,h200863057/meteor,yyx990803/meteor,4commerce-technologies-AG/meteor,stevenliuit/meteor,joannekoong/meteor,evilemon/meteor,bhargav175/meteor,DCKT/meteor,neotim/meteor,Prithvi-A/meteor,jdivy/meteor,ljack/meteor,mjmasn/meteor,namho102/meteor,h200863057/meteor,wmkcc/meteor,chengxiaole/meteor,AnthonyAstige/meteor,planet-training/meteor,iman-mafi/meteor,ericterpstra/meteor,steedos/meteor,akintoey/meteor,AlexR1712/meteor,benjamn/meteor,eluck/meteor,Puena/meteor,msavin/meteor,queso/meteor,JesseQin/meteor,whip112/meteor,mauricionr/meteor,sclausen/meteor,stevenliuit/meteor,AlexR1712/meteor,daltonrenaldo/meteor,jagi/meteor,karlito40/meteor,justintung/meteor,deanius/meteor,iman-mafi/meteor,LWHTarena/meteor,williambr/meteor,pandeysoni/meteor,codingang/meteor,Paulyoufu/meteor-1,whip112/meteor,sitexa/meteor,Puena/meteor,steedos/meteor,yiliaofan/meteor,dfischer/meteor,sunny-g/meteor,alphanso/meteor,namho102/meteor,LWHTarena/meteor,johnthepink/meteor,cbonami/meteor,oceanzou123/meteor,cbonami/meteor,meteor-velocity/meteor,dev-bobsong/meteor,yyx990803/meteor,steedos/meteor,shrop/meteor,kengchau/meteor,newswim/meteor,Hansoft/meteor,kencheung/meteor,Ken-Liu/meteor,aldeed/meteor,emmerge/meteor,henrypan/meteor,dboyliao/meteor,paul-barry-kenzan/meteor,imanmafi/meteor,whip112/meteor,dboyliao/meteor,chasertech/meteor,vjau/meteor,DAB0mB/meteor,imanmafi/meteor,modulexcite/meteor,qscripter/meteor,luohuazju/meteor,Prithvi-A/meteor,HugoRLopes/meteor,rabbyalone/meteor,oceanzou123/meteor,Jonekee/meteor,chasertech/meteor,modulexcite/meteor,Puena/meteor,mjmasn/meteor,skarekrow/meteor,jg3526/meteor,namho102/meteor,neotim/meteor,yonglehou/meteor,chinasb/meteor,HugoRLopes/meteor,PatrickMcGuinness/meteor,chengxiaole/meteor,lassombra/meteor,youprofit/meteor,jeblister/meteor,nuvipannu/meteor,alphanso/meteor,sclausen/meteor,pjump/meteor,rabbyalone/meteor,kengchau/meteor,chmac/meteor,yyx990803/meteor,rozzzly/meteor,Hansoft/meteor,DCKT/meteor,allanalexandre/meteor,PatrickMcGuinness/meteor,mjmasn/meteor,qscripter/meteor,tdamsma/meteor,jagi/meteor,mauricionr/meteor,AnjirHossain/meteor,ljack/meteor,ndarilek/meteor,benstoltz/meteor,ljack/meteor,kengchau/meteor,Prithvi-A/meteor,pandeysoni/meteor,Quicksteve/meteor,oceanzou123/meteor,TechplexEngineer/meteor,ljack/meteor,l0rd0fwar/meteor,alexbeletsky/meteor,Prithvi-A/meteor,wmkcc/meteor,Theviajerock/meteor,sunny-g/meteor,lassombra/meteor,jg3526/meteor,benjamn/meteor,alexbeletsky/meteor,esteedqueen/meteor,esteedqueen/meteor,eluck/meteor,williambr/meteor,chmac/meteor,judsonbsilva/meteor,yanisIk/meteor,Jonekee/meteor,jagi/meteor,whip112/meteor,lpinto93/meteor,luohuazju/meteor,Jeremy017/meteor,benstoltz/meteor,tdamsma/meteor,AnthonyAstige/meteor,iman-mafi/meteor,deanius/meteor,iman-mafi/meteor,IveWong/meteor,DAB0mB/meteor,elkingtonmcb/meteor,LWHTarena/meteor,Profab/meteor,HugoRLopes/meteor,lassombra/meteor,skarekrow/meteor,Jonekee/meteor,jrudio/meteor,katopz/meteor,karlito40/meteor,EduShareOntario/meteor,dev-bobsong/meteor,queso/meteor,lassombra/meteor,aldeed/meteor,brdtrpp/meteor,guazipi/meteor,vacjaliu/meteor,tdamsma/meteor,paul-barry-kenzan/meteor,sdeveloper/meteor,jirengu/meteor,framewr/meteor,Jeremy017/meteor,mauricionr/meteor,chinasb/meteor,calvintychan/meteor,paul-barry-kenzan/meteor,jeblister/meteor,PatrickMcGuinness/meteor,vacjaliu/meteor,msavin/meteor,baiyunping333/meteor,sclausen/meteor,yinhe007/meteor,lpinto93/meteor,sitexa/meteor,Ken-Liu/meteor,pandeysoni/meteor,codedogfish/meteor,rozzzly/meteor,dfischer/meteor,kencheung/meteor,chmac/meteor,pjump/meteor,sunny-g/meteor,l0rd0fwar/meteor,Theviajerock/meteor,esteedqueen/meteor,bhargav175/meteor,Theviajerock/meteor,Eynaliyev/meteor,ashwathgovind/meteor,colinligertwood/meteor,vacjaliu/meteor,ndarilek/meteor,fashionsun/meteor,alphanso/meteor,mubassirhayat/meteor,chengxiaole/meteor,ashwathgovind/meteor,aleclarson/meteor,aramk/meteor,somallg/meteor,yalexx/meteor,pandeysoni/meteor,planet-training/meteor,shrop/meteor,luohuazju/meteor,codedogfish/meteor,cog-64/meteor,AlexR1712/meteor,yanisIk/meteor,eluck/meteor,vacjaliu/meteor,codingang/meteor,jagi/meteor,yanisIk/meteor,kidaa/meteor,alexbeletsky/meteor,allanalexandre/meteor,lorensr/meteor,rozzzly/meteor,yiliaofan/meteor,benstoltz/meteor,yonas/meteor-freebsd,Paulyoufu/meteor-1,Theviajerock/meteor,dboyliao/meteor,whip112/meteor,alphanso/meteor,AnjirHossain/meteor,joannekoong/meteor,brdtrpp/meteor,lassombra/meteor,framewr/meteor,lorensr/meteor,bhargav175/meteor,jeblister/meteor,calvintychan/meteor,SeanOceanHu/meteor,jeblister/meteor,paul-barry-kenzan/meteor,TechplexEngineer/meteor,lorensr/meteor,Jonekee/meteor,framewr/meteor,allanalexandre/meteor,servel333/meteor,saisai/meteor,mjmasn/meteor,sitexa/meteor,qscripter/meteor,daltonrenaldo/meteor,udhayam/meteor,daslicht/meteor,Ken-Liu/meteor,guazipi/meteor,michielvanoeffelen/meteor,zdd910/meteor,brettle/meteor,Urigo/meteor,TribeMedia/meteor,AnjirHossain/meteor,brettle/meteor,cherbst/meteor,judsonbsilva/meteor,joannekoong/meteor,TribeMedia/meteor,lorensr/meteor,devgrok/meteor,esteedqueen/meteor,IveWong/meteor,mirstan/meteor,dfischer/meteor,shmiko/meteor,imanmafi/meteor,dboyliao/meteor,mirstan/meteor,akintoey/meteor,judsonbsilva/meteor,aldeed/meteor,sdeveloper/meteor,codingang/meteor,baiyunping333/meteor,justintung/meteor,DCKT/meteor,papimomi/meteor,allanalexandre/meteor,h200863057/meteor,baysao/meteor,HugoRLopes/meteor,l0rd0fwar/meteor,Hansoft/meteor,framewr/meteor,AnthonyAstige/meteor,DAB0mB/meteor,jg3526/meteor,sunny-g/meteor,yanisIk/meteor,jenalgit/meteor,somallg/meteor,chinasb/meteor,arunoda/meteor,mubassirhayat/meteor,deanius/meteor,GrimDerp/meteor,calvintychan/meteor,dev-bobsong/meteor,HugoRLopes/meteor,dboyliao/meteor,newswim/meteor,udhayam/meteor,devgrok/meteor,kengchau/meteor,arunoda/meteor,elkingtonmcb/meteor,4commerce-technologies-AG/meteor,imanmafi/meteor,Urigo/meteor,aramk/meteor,aleclarson/meteor,mirstan/meteor,deanius/meteor,juansgaitan/meteor,yinhe007/meteor,Jeremy017/meteor,Hansoft/meteor,yonglehou/meteor,meonkeys/meteor,joannekoong/meteor,luohuazju/meteor,chmac/meteor,Urigo/meteor,TribeMedia/meteor,Paulyoufu/meteor-1,katopz/meteor,chiefninew/meteor,lawrenceAIO/meteor,GrimDerp/meteor,aramk/meteor,karlito40/meteor,meonkeys/meteor,Quicksteve/meteor,vjau/meteor,jg3526/meteor,lawrenceAIO/meteor,Hansoft/meteor,mubassirhayat/meteor,johnthepink/meteor,elkingtonmcb/meteor,chiefninew/meteor,jenalgit/meteor,dandv/meteor,brettle/meteor,deanius/meteor,emmerge/meteor,msavin/meteor,GrimDerp/meteor,alexbeletsky/meteor,bhargav175/meteor,chinasb/meteor,chasertech/meteor,benstoltz/meteor,stevenliuit/meteor,yinhe007/meteor,ljack/meteor,lpinto93/meteor,emmerge/meteor,ndarilek/meteor,Profab/meteor,alexbeletsky/meteor,Ken-Liu/meteor,codingang/meteor,henrypan/meteor,brdtrpp/meteor,yonglehou/meteor,codingang/meteor,mauricionr/meteor,papimomi/meteor,sdeveloper/meteor,AnthonyAstige/meteor,akintoey/meteor,ljack/meteor,tdamsma/meteor,evilemon/meteor,ericterpstra/meteor,williambr/meteor,Prithvi-A/meteor,sunny-g/meteor,somallg/meteor,jirengu/meteor,brettle/meteor,neotim/meteor,saisai/meteor,yonas/meteor-freebsd,Profab/meteor,hristaki/meteor,williambr/meteor,ashwathgovind/meteor,akintoey/meteor,pjump/meteor,sitexa/meteor,chiefninew/meteor,Quicksteve/meteor,cog-64/meteor,vacjaliu/meteor,brdtrpp/meteor,joannekoong/meteor,chmac/meteor,mirstan/meteor,D1no/meteor,youprofit/meteor,Eynaliyev/meteor,codedogfish/meteor,servel333/meteor,cherbst/meteor,D1no/meteor,lorensr/meteor,kengchau/meteor,DCKT/meteor,calvintychan/meteor,hristaki/meteor,shmiko/meteor,shadedprofit/meteor,Jeremy017/meteor,l0rd0fwar/meteor,vacjaliu/meteor,judsonbsilva/meteor,whip112/meteor,TribeMedia/meteor,hristaki/meteor,PatrickMcGuinness/meteor,jirengu/meteor,Jonekee/meteor,chasertech/meteor,benstoltz/meteor,Eynaliyev/meteor,yiliaofan/meteor,skarekrow/meteor,meteor-velocity/meteor,codingang/meteor,katopz/meteor,nuvipannu/meteor,neotim/meteor,alphanso/meteor,saisai/meteor,baysao/meteor,sclausen/meteor,dboyliao/meteor,akintoey/meteor,somallg/meteor,TechplexEngineer/meteor,chasertech/meteor,aleclarson/meteor,bhargav175/meteor,Ken-Liu/meteor,lieuwex/meteor,zdd910/meteor,lawrenceAIO/meteor,alphanso/meteor,udhayam/meteor,Theviajerock/meteor,sdeveloper/meteor,newswim/meteor,Eynaliyev/meteor,ljack/meteor,iman-mafi/meteor,baysao/meteor,jrudio/meteor,GrimDerp/meteor,dfischer/meteor,framewr/meteor,queso/meteor,jenalgit/meteor,stevenliuit/meteor,jirengu/meteor,shadedprofit/meteor,modulexcite/meteor,modulexcite/meteor,katopz/meteor,mubassirhayat/meteor,AnjirHossain/meteor,cbonami/meteor,benjamn/meteor,guazipi/meteor,JesseQin/meteor,AnthonyAstige/meteor,neotim/meteor,juansgaitan/meteor,brettle/meteor,msavin/meteor,sunny-g/meteor,codedogfish/meteor,papimomi/meteor,chiefninew/meteor,Quicksteve/meteor,steedos/meteor,brdtrpp/meteor,msavin/meteor,papimomi/meteor,Hansoft/meteor,namho102/meteor,planet-training/meteor,colinligertwood/meteor,youprofit/meteor,lawrenceAIO/meteor,vjau/meteor,jdivy/meteor,D1no/meteor,sdeveloper/meteor,lawrenceAIO/meteor,SeanOceanHu/meteor,evilemon/meteor,lieuwex/meteor,youprofit/meteor,meteor-velocity/meteor,meonkeys/meteor,somallg/meteor,esteedqueen/meteor,Puena/meteor,alexbeletsky/meteor,newswim/meteor,mubassirhayat/meteor,rabbyalone/meteor,yyx990803/meteor,chinasb/meteor,baiyunping333/meteor,meonkeys/meteor,hristaki/meteor,planet-training/meteor,shrop/meteor,framewr/meteor,jagi/meteor,somallg/meteor,EduShareOntario/meteor,baiyunping333/meteor,henrypan/meteor,lawrenceAIO/meteor,kidaa/meteor,SeanOceanHu/meteor,AlexR1712/meteor,meteor-velocity/meteor,hristaki/meteor,iman-mafi/meteor,lieuwex/meteor,alexbeletsky/meteor,queso/meteor,EduShareOntario/meteor,cbonami/meteor,jagi/meteor,PatrickMcGuinness/meteor,arunoda/meteor,michielvanoeffelen/meteor,newswim/meteor,lassombra/meteor,qscripter/meteor,steedos/meteor,AnthonyAstige/meteor,dev-bobsong/meteor,Puena/meteor,arunoda/meteor,benjamn/meteor,ndarilek/meteor,fashionsun/meteor,aramk/meteor,dev-bobsong/meteor,Theviajerock/meteor,jeblister/meteor,tdamsma/meteor,4commerce-technologies-AG/meteor,kidaa/meteor,cherbst/meteor,ericterpstra/meteor,jagi/meteor,Theviajerock/meteor,EduShareOntario/meteor,skarekrow/meteor,michielvanoeffelen/meteor,shadedprofit/meteor,chengxiaole/meteor,stevenliuit/meteor,michielvanoeffelen/meteor,shrop/meteor,juansgaitan/meteor,johnthepink/meteor,sclausen/meteor,colinligertwood/meteor,jenalgit/meteor,fashionsun/meteor,skarekrow/meteor,emmerge/meteor,AnthonyAstige/meteor,chmac/meteor,jenalgit/meteor,udhayam/meteor,jg3526/meteor,yalexx/meteor,baiyunping333/meteor,queso/meteor,nuvipannu/meteor,steedos/meteor,Profab/meteor,katopz/meteor,jirengu/meteor,Jonekee/meteor,AnthonyAstige/meteor,benstoltz/meteor,stevenliuit/meteor,emmerge/meteor,lpinto93/meteor,williambr/meteor,judsonbsilva/meteor,johnthepink/meteor,dandv/meteor,rabbyalone/meteor,ndarilek/meteor,SeanOceanHu/meteor,bhargav175/meteor,steedos/meteor,lassombra/meteor,Prithvi-A/meteor,h200863057/meteor,Prithvi-A/meteor,benstoltz/meteor,calvintychan/meteor,servel333/meteor,sitexa/meteor,vjau/meteor,shmiko/meteor,pjump/meteor,l0rd0fwar/meteor,luohuazju/meteor,hristaki/meteor,codedogfish/meteor,skarekrow/meteor,cherbst/meteor,cog-64/meteor,Ken-Liu/meteor,daltonrenaldo/meteor,TechplexEngineer/meteor,yonglehou/meteor,pandeysoni/meteor,aldeed/meteor,cbonami/meteor,yalexx/meteor,emmerge/meteor,jrudio/meteor,brdtrpp/meteor,michielvanoeffelen/meteor,kencheung/meteor,cog-64/meteor,LWHTarena/meteor,chiefninew/meteor,mirstan/meteor,sunny-g/meteor,evilemon/meteor,yanisIk/meteor,zdd910/meteor,shmiko/meteor,zdd910/meteor,iman-mafi/meteor,karlito40/meteor,jrudio/meteor,yalexx/meteor,kidaa/meteor,dandv/meteor,lieuwex/meteor,pandeysoni/meteor,henrypan/meteor,guazipi/meteor,LWHTarena/meteor,eluck/meteor,planet-training/meteor,jdivy/meteor,EduShareOntario/meteor,mirstan/meteor,luohuazju/meteor,devgrok/meteor,dandv/meteor,Paulyoufu/meteor-1,colinligertwood/meteor,dandv/meteor,colinligertwood/meteor,justintung/meteor,dandv/meteor,judsonbsilva/meteor,servel333/meteor,saisai/meteor,Urigo/meteor,yonas/meteor-freebsd,neotim/meteor,qscripter/meteor,lieuwex/meteor,Jeremy017/meteor,juansgaitan/meteor,GrimDerp/meteor,Quicksteve/meteor,aldeed/meteor,queso/meteor,sclausen/meteor,udhayam/meteor,kencheung/meteor,imanmafi/meteor,yiliaofan/meteor,Jeremy017/meteor,nuvipannu/meteor,mubassirhayat/meteor,nuvipannu/meteor,daltonrenaldo/meteor,lawrenceAIO/meteor,codedogfish/meteor,AnjirHossain/meteor,Jonekee/meteor,vjau/meteor,jg3526/meteor,baiyunping333/meteor,daltonrenaldo/meteor,jdivy/meteor,skarekrow/meteor,oceanzou123/meteor,qscripter/meteor,udhayam/meteor,arunoda/meteor,guazipi/meteor,juansgaitan/meteor,ashwathgovind/meteor,ndarilek/meteor,jrudio/meteor,Eynaliyev/meteor,DAB0mB/meteor,oceanzou123/meteor,JesseQin/meteor,daslicht/meteor,kencheung/meteor,lpinto93/meteor,oceanzou123/meteor,4commerce-technologies-AG/meteor,cog-64/meteor,allanalexandre/meteor,meonkeys/meteor,IveWong/meteor,yiliaofan/meteor,devgrok/meteor,kidaa/meteor,AlexR1712/meteor,TechplexEngineer/meteor,dfischer/meteor,IveWong/meteor,Quicksteve/meteor,baysao/meteor,servel333/meteor,yinhe007/meteor,AlexR1712/meteor,ericterpstra/meteor,modulexcite/meteor,yyx990803/meteor,baysao/meteor,jdivy/meteor,henrypan/meteor,fashionsun/meteor,D1no/meteor,TechplexEngineer/meteor,AnjirHossain/meteor,LWHTarena/meteor,daslicht/meteor,michielvanoeffelen/meteor,henrypan/meteor,fashionsun/meteor,imanmafi/meteor,wmkcc/meteor,shadedprofit/meteor,4commerce-technologies-AG/meteor,yalexx/meteor,yiliaofan/meteor,alphanso/meteor,papimomi/meteor,Puena/meteor,papimomi/meteor,D1no/meteor,TechplexEngineer/meteor,DCKT/meteor,queso/meteor,DAB0mB/meteor,somallg/meteor,esteedqueen/meteor,nuvipannu/meteor,dev-bobsong/meteor,dev-bobsong/meteor,jenalgit/meteor,benjamn/meteor,Hansoft/meteor,vjau/meteor,TribeMedia/meteor,DCKT/meteor,rozzzly/meteor,Eynaliyev/meteor,PatrickMcGuinness/meteor,aramk/meteor,aldeed/meteor,lieuwex/meteor,paul-barry-kenzan/meteor,dfischer/meteor,Profab/meteor,daltonrenaldo/meteor,SeanOceanHu/meteor,newswim/meteor,daslicht/meteor,chengxiaole/meteor,colinligertwood/meteor,Urigo/meteor,jirengu/meteor,modulexcite/meteor,karlito40/meteor,shadedprofit/meteor,Paulyoufu/meteor-1,rozzzly/meteor,tdamsma/meteor,paul-barry-kenzan/meteor,jdivy/meteor,evilemon/meteor,Quicksteve/meteor,SeanOceanHu/meteor,D1no/meteor,shmiko/meteor,h200863057/meteor,calvintychan/meteor,guazipi/meteor,planet-training/meteor,ljack/meteor,chinasb/meteor,4commerce-technologies-AG/meteor,lorensr/meteor,Urigo/meteor,brettle/meteor,EduShareOntario/meteor,newswim/meteor,oceanzou123/meteor,kidaa/meteor,arunoda/meteor,yiliaofan/meteor,colinligertwood/meteor,luohuazju/meteor,chengxiaole/meteor,wmkcc/meteor,benjamn/meteor,servel333/meteor,dandv/meteor,kengchau/meteor,yyx990803/meteor,brdtrpp/meteor,DCKT/meteor,udhayam/meteor,mjmasn/meteor,dboyliao/meteor | ---
+++
@@ -2,9 +2,10 @@
summary: "A minimalist client-side MVC framework"
});
-Package.on_use(function (api) {
+Package.on_use(function (api, where) {
// XXX Backbone requires either jquery or zepto
- api.use("jquery");
+ api.use(["jquery", "json"]);
- api.add_files("backbone.js", "client");
+ where = where || ['client', 'server'];
+ api.add_files("backbone.js", where);
}); |
bc79b09f2081e7af016580f6a383aee322617655 | 2013/js-inheritance-es6.js | 2013/js-inheritance-es6.js | // ES6 variation with classes for "Classical inheritance in JS ES5".
//
// Eli Bendersky [http://eli.thegreenplace.net]
// This code is in the public domain.
class Shape {
constructor(x, y) {
this.x = x;
this.y = y;
}
move(x, y) {
this.x += x;
this.y += y;
}
}
class Circle extends Shape {
constructor(x, y, r) {
super(x, y);
this.r = r;
}
circumference() {
return this.r * 2 * Math.PI;
}
}
var shp = new Shape(1, 2);
console.log([shp.x, shp.y]);
shp.move(1, 1);
console.log([shp.x, shp.y]);
var cir = new Circle(5, 6, 2);
console.log([cir.x, cir.y, cir.r]);
cir.move(1, 1);
console.log([cir.x, cir.y, cir.r]);
console.log(cir.circumference());
console.log("instanceof tests:");
console.log(cir instanceof Shape);
console.log(cir instanceof Circle);
console.log(shp instanceof Shape);
console.log(shp instanceof Circle);
| Add ES6 variant using classes | Add ES6 variant using classes
| JavaScript | unlicense | eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog,eliben/code-for-blog | ---
+++
@@ -0,0 +1,44 @@
+// ES6 variation with classes for "Classical inheritance in JS ES5".
+//
+// Eli Bendersky [http://eli.thegreenplace.net]
+// This code is in the public domain.
+
+class Shape {
+ constructor(x, y) {
+ this.x = x;
+ this.y = y;
+ }
+
+ move(x, y) {
+ this.x += x;
+ this.y += y;
+ }
+}
+
+class Circle extends Shape {
+ constructor(x, y, r) {
+ super(x, y);
+ this.r = r;
+ }
+
+ circumference() {
+ return this.r * 2 * Math.PI;
+ }
+}
+
+var shp = new Shape(1, 2);
+console.log([shp.x, shp.y]);
+shp.move(1, 1);
+console.log([shp.x, shp.y]);
+
+var cir = new Circle(5, 6, 2);
+console.log([cir.x, cir.y, cir.r]);
+cir.move(1, 1);
+console.log([cir.x, cir.y, cir.r]);
+console.log(cir.circumference());
+
+console.log("instanceof tests:");
+console.log(cir instanceof Shape);
+console.log(cir instanceof Circle);
+console.log(shp instanceof Shape);
+console.log(shp instanceof Circle); | |
7ff5b1ccb90e096f5dbcbaa431bbcde5f208aca6 | Akai/LPD8.Virek.control.js | Akai/LPD8.Virek.control.js | // Bitwig controller script for AKAI LPD
// by Nick Donaldson, 2016
//
// Global constants
var SCRIPT_API_VERSION = 1;
var SCRIPT_VERSION = "0.1";
var SCRIPT_UUID = "b5a7af1c-23b0-4d4c-b8b6-1ef889bbbee2";
var DEVICE_NAME = "LPD8";
var NUM_PORTS_IN = 1;
var NUM_PORTS_OUT = 0;
// Initialization and Controller Definition
loadAPI(SCRIPT_API_VERSION);
host.defineController("Akai", "LPD8 (Generic)", SCRIPT_VERSION, SCRIPT_UUID, "Nick Donaldson");
host.defineMidiPorts(NUM_PORTS_IN, NUM_PORTS_OUT);
host.addDeviceNameBasedDiscoveryPair([DEVICE_NAME], [DEVICE_NAME]);
| Add LPD8 script for cross-device identification | Add LPD8 script for cross-device identification
| JavaScript | cc0-1.0 | ndonald2/bitwig-controller-scripts,ndonald2/bitwig-controller-scripts | ---
+++
@@ -0,0 +1,20 @@
+// Bitwig controller script for AKAI LPD
+// by Nick Donaldson, 2016
+//
+// Global constants
+
+var SCRIPT_API_VERSION = 1;
+var SCRIPT_VERSION = "0.1";
+var SCRIPT_UUID = "b5a7af1c-23b0-4d4c-b8b6-1ef889bbbee2";
+
+var DEVICE_NAME = "LPD8";
+var NUM_PORTS_IN = 1;
+var NUM_PORTS_OUT = 0;
+
+// Initialization and Controller Definition
+
+loadAPI(SCRIPT_API_VERSION);
+host.defineController("Akai", "LPD8 (Generic)", SCRIPT_VERSION, SCRIPT_UUID, "Nick Donaldson");
+host.defineMidiPorts(NUM_PORTS_IN, NUM_PORTS_OUT);
+host.addDeviceNameBasedDiscoveryPair([DEVICE_NAME], [DEVICE_NAME]);
+ | |
e5f244dd6892a07efb64763c8dda241de16d677f | notes/add_chart.js | notes/add_chart.js | // const User = require('./user')
// const Key = require('./note-key').Key
// const Note = require('./note-key').Note
// const ScaleNote = require('./note-key').ScaleNote
// const Chord = require('./chord-lyric').Chord
// const Lyric = require('./chord-lyric').Lyric
// const Measure = require('./measure')
// const Section = require('./section')
// const Chart = require('./chart')
// const ChartUser = require('./chartuser')
// require('./associations')
Chart.create({
createdAt: '2017-07-29T06:57:54.103Z',
title: 'Blackbird',
composer: 'Paul McCartney',
lyricistSame: true,
author: 'bds',
originalKey: 'G',
// users: [{id: 1}],
sections: [{
beatsPerMeasure: 4,
index: 1,
verseCount: 1,
measuresPerRow: 1,
measures: [{
index: 1,
chords: [{
beatIndex: 1,
note: {noteCode: 'G'},
}],
lyrics: [{
verseIndex: 1,
lyricText: 'Blackbird'
}]
}]
}]
},
{
include: [
// User,
{
model: Section,
include: [{
model: Measure,
include: [
Lyric,
{ model: Chord,
include: [ Note ]
}
]
}]
},
]
}).then(thisChart => {
console.log('thisChart', thisChart)
})
| Create sketch for adding chart.\n\nStill need to investigate adding when associations (user, note, etc.) already exist. | Create sketch for adding chart.\n\nStill need to investigate adding when associations (user, note, etc.) already exist.
| JavaScript | agpl-3.0 | flyrightsister/boxcharter,flyrightsister/boxcharter | ---
+++
@@ -0,0 +1,57 @@
+// const User = require('./user')
+// const Key = require('./note-key').Key
+// const Note = require('./note-key').Note
+// const ScaleNote = require('./note-key').ScaleNote
+// const Chord = require('./chord-lyric').Chord
+// const Lyric = require('./chord-lyric').Lyric
+// const Measure = require('./measure')
+// const Section = require('./section')
+// const Chart = require('./chart')
+// const ChartUser = require('./chartuser')
+// require('./associations')
+
+Chart.create({
+ createdAt: '2017-07-29T06:57:54.103Z',
+ title: 'Blackbird',
+ composer: 'Paul McCartney',
+ lyricistSame: true,
+ author: 'bds',
+ originalKey: 'G',
+ // users: [{id: 1}],
+ sections: [{
+ beatsPerMeasure: 4,
+ index: 1,
+ verseCount: 1,
+ measuresPerRow: 1,
+ measures: [{
+ index: 1,
+ chords: [{
+ beatIndex: 1,
+ note: {noteCode: 'G'},
+ }],
+ lyrics: [{
+ verseIndex: 1,
+ lyricText: 'Blackbird'
+ }]
+ }]
+ }]
+},
+{
+ include: [
+ // User,
+ {
+ model: Section,
+ include: [{
+ model: Measure,
+ include: [
+ Lyric,
+ { model: Chord,
+ include: [ Note ]
+ }
+ ]
+ }]
+ },
+ ]
+}).then(thisChart => {
+ console.log('thisChart', thisChart)
+}) | |
aaaa73ca984792217bc4e1c1c9185be47250a8a8 | hue.js | hue.js | HueBridge = function(server, username) {
this.server = server;
this.username = username;
}
HueBridge.prototype = {
_apiCall: function(method, path, data, callback) {
HTTP.call(method, "http://" + this.server + "/api/" + this.username + path, {}, function(error, result) {
if (error) {
console.log(error);
} else if (result.data && result.data[0] && result.data[0].error) {
let error = result.data[0].error;
// throw new Meteor.Error(error, );
console.log(error);
} else {
callback(result.data);
}
});
},
getLights: function(callback) {
var bridge = this;
this._apiCall("GET", "/lights/", {}, function(results) {
let lights = [];
for (id in results) {
lights.push(new HueLight(bridge, id, results[id]))
}
callback(lights);
});
},
getLight: function(id, callback) {
var bridge = this;
this._apiCall("GET", `/lights/${id}`, {}, function(result) {
let light = new HueLight(bridge, id, result);
callback(light);
});
}
}
HueLight = function(bridge, id, params) {
this.bridge = bridge;
this.id = id;
this.params = params;
}
| Implement basic Hue API control | Implement basic Hue API control
| JavaScript | mit | iwazaru/notrebeausapin.fr,iwazaru/notrebeausapin.fr | ---
+++
@@ -0,0 +1,46 @@
+HueBridge = function(server, username) {
+ this.server = server;
+ this.username = username;
+}
+
+HueBridge.prototype = {
+
+ _apiCall: function(method, path, data, callback) {
+ HTTP.call(method, "http://" + this.server + "/api/" + this.username + path, {}, function(error, result) {
+ if (error) {
+ console.log(error);
+ } else if (result.data && result.data[0] && result.data[0].error) {
+ let error = result.data[0].error;
+ // throw new Meteor.Error(error, );
+ console.log(error);
+ } else {
+ callback(result.data);
+ }
+ });
+ },
+
+ getLights: function(callback) {
+ var bridge = this;
+ this._apiCall("GET", "/lights/", {}, function(results) {
+ let lights = [];
+ for (id in results) {
+ lights.push(new HueLight(bridge, id, results[id]))
+ }
+ callback(lights);
+ });
+ },
+
+ getLight: function(id, callback) {
+ var bridge = this;
+ this._apiCall("GET", `/lights/${id}`, {}, function(result) {
+ let light = new HueLight(bridge, id, result);
+ callback(light);
+ });
+ }
+}
+
+HueLight = function(bridge, id, params) {
+ this.bridge = bridge;
+ this.id = id;
+ this.params = params;
+} | |
ad030be7e8cbdbc6817d2b9436317a255687e7c3 | spec/javascripts/mixerSpec.js | spec/javascripts/mixerSpec.js | describe("Mixer", function(){
var mixer;
var song;
beforeEach(function(){
mixer = [];
song = new Howl({
urls: "https://s3.amazonaws.com/the-golden-record/Music/Soul+Jazz-Mike+Frederick.mp3"
});
it("should be play a particular song", function() {
// play song
// expect player at song to be playing ((pause: false)?)
});
describe("when song has been paused", function() {
beforeEach(function() {
// pause song
// pause on this song should be true
});
});
});
});
| Add skeleton of mixer tests for play and pause | Add skeleton of mixer tests for play and pause
| JavaScript | mit | chi-bobolinks-2015/TheGoldenRecord,chi-bobolinks-2015/TheGoldenRecord,chi-bobolinks-2015/TheGoldenRecord | ---
+++
@@ -0,0 +1,27 @@
+describe("Mixer", function(){
+ var mixer;
+ var song;
+
+ beforeEach(function(){
+ mixer = [];
+ song = new Howl({
+ urls: "https://s3.amazonaws.com/the-golden-record/Music/Soul+Jazz-Mike+Frederick.mp3"
+
+ });
+
+ it("should be play a particular song", function() {
+ // play song
+ // expect player at song to be playing ((pause: false)?)
+ });
+
+ describe("when song has been paused", function() {
+ beforeEach(function() {
+ // pause song
+ // pause on this song should be true
+ });
+ });
+ });
+});
+
+
+ | |
754b5d1d5c6695cc944448bcb3336f8042b7e442 | newswriter.js | newswriter.js | (function () {
function run () {
// (reads from quizServer.cfg and mypwd.txt)
var config = require('./lib/config').config;
var optsModule = require('./lib/opts.js');
var optsClass = new optsModule.optsClass(config);
var opts = optsClass.getOpts();
if (!opts) {
return;
} else if (opts.save_parameters) {
console.log("Save parameters!");
}
// (creates subdirs and sqlite3 database if necessary,
// migrates to sqlite3 db from old CSV files, and removes
// CSV and their subdirs after validation)
var initModule = require('./lib/init.js');
var initClass = new initModule.initClass(opts);
var init = initClass.getInit();
var sysModule = require('./lib/sys.js');
var sysClass = new sysModule.sysClass(opts);
var sys = sysClass.getSys();
var pagesModule = require('./lib/pages.js');
var pagesClass = new pagesModule.pagesClass(sys);
var sys = pagesClass.getPages();
var cogsModule = require('./lib/cogs.js');
var cogsClass = new cogsModule.cogsClass(sys);
var cogs = cogsClass.getCogs();
var apiModule = require('./lib/api.js');
var apiClass = new apiModule.apiClass(sys,cogs);
var api = apiClass.getApi();
var serverModule = require('./lib/server.js');
var serverClass = new serverModule.serverClass(sys,api);
serverClass.runServer();
}
exports.run = run;
})();
| Add master run file to repo. Oops. | Add master run file to repo. Oops.
| JavaScript | unlicense | fbennett/newswriter | ---
+++
@@ -0,0 +1,45 @@
+(function () {
+ function run () {
+
+ // (reads from quizServer.cfg and mypwd.txt)
+ var config = require('./lib/config').config;
+
+ var optsModule = require('./lib/opts.js');
+ var optsClass = new optsModule.optsClass(config);
+ var opts = optsClass.getOpts();
+ if (!opts) {
+ return;
+ } else if (opts.save_parameters) {
+ console.log("Save parameters!");
+ }
+
+ // (creates subdirs and sqlite3 database if necessary,
+ // migrates to sqlite3 db from old CSV files, and removes
+ // CSV and their subdirs after validation)
+ var initModule = require('./lib/init.js');
+ var initClass = new initModule.initClass(opts);
+ var init = initClass.getInit();
+
+ var sysModule = require('./lib/sys.js');
+ var sysClass = new sysModule.sysClass(opts);
+ var sys = sysClass.getSys();
+
+ var pagesModule = require('./lib/pages.js');
+ var pagesClass = new pagesModule.pagesClass(sys);
+ var sys = pagesClass.getPages();
+
+ var cogsModule = require('./lib/cogs.js');
+ var cogsClass = new cogsModule.cogsClass(sys);
+ var cogs = cogsClass.getCogs();
+
+ var apiModule = require('./lib/api.js');
+ var apiClass = new apiModule.apiClass(sys,cogs);
+ var api = apiClass.getApi();
+
+ var serverModule = require('./lib/server.js');
+ var serverClass = new serverModule.serverClass(sys,api);
+ serverClass.runServer();
+ }
+ exports.run = run;
+})();
+ | |
2c091531f153b8d6b4a0d6d91fd351483030a1f8 | test/cli/promptOptionsSpec.js | test/cli/promptOptionsSpec.js | var chai = require('chai');
var expect = chai.expect;
var promptOptionsModule = require('../../bin/promptOptions')();
chai.should();
describe('As a user of the promptOptions module', function() {
it('should return an object', function() {
var test = promptOptionsModule;
expect(test).to.be.a('object');
})
describe('When using getNewCommandPromptOptions()', function() {
it('should be a function', function() {
var test = promptOptionsModule.getNewCommandPromptOptions;
expect(test).to.be.a('function');
})
it('should return an array', function() {
var test = promptOptionsModule.getNewCommandPromptOptions();
expect(test instanceof Array).to.be.true;
})
it('should return an array that is not empty', function() {
var actual = promptOptionsModule.getNewCommandPromptOptions();
expect(actual.length).to.be.above(1);
})
})
}) | Add tests for prompt options module | tests: Add tests for prompt options module
| JavaScript | mit | code-computerlove/quarry,cartridge/cartridge-cli,code-computerlove/slate-cli | ---
+++
@@ -0,0 +1,38 @@
+var chai = require('chai');
+var expect = chai.expect;
+
+var promptOptionsModule = require('../../bin/promptOptions')();
+
+chai.should();
+
+describe('As a user of the promptOptions module', function() {
+
+ it('should return an object', function() {
+ var test = promptOptionsModule;
+
+ expect(test).to.be.a('object');
+ })
+
+ describe('When using getNewCommandPromptOptions()', function() {
+
+ it('should be a function', function() {
+ var test = promptOptionsModule.getNewCommandPromptOptions;
+
+ expect(test).to.be.a('function');
+ })
+
+ it('should return an array', function() {
+ var test = promptOptionsModule.getNewCommandPromptOptions();
+
+ expect(test instanceof Array).to.be.true;
+ })
+
+ it('should return an array that is not empty', function() {
+ var actual = promptOptionsModule.getNewCommandPromptOptions();
+
+ expect(actual.length).to.be.above(1);
+ })
+
+ })
+
+}) | |
ee3e4a943a7077547af7dffcb12c4c42b613efcb | tests/e2e/saving-scenario_.js | tests/e2e/saving-scenario_.js | 'use strict';
//https://github.com/angular/protractor/blob/master/docs/api.md
//GetAttribute() returns "boolean" values and will return either "true" or null
describe('Reports', function(){
var id = '1fueA5hrxIHxvRf7Btr_J6efDJ3qp-s9KV731wDc4OOaw';
var Report = require('../../app/report/report-page');
var FiltersPage = require('../../app/report/filters/filters-page');
it('Should throw an exception if we reloading while saving the report', function(){
var report = new Report(id);
var filters = report.filters;
filters.visitPage();
//Let's do an illegal update where we don't wait for angularjs to finish
//See https://github.com/angular/protractor/issues/308
filters.resetSelectedFilters();
filters.visitPage().then(function(){
expect(true).toBe(false);
}, function(){
expect(true).toBe(true);
});
//browser.switchTo().alert().then(function(alert) {
// alert.accept();
//});
});
});
| Add working draft of a saving scenario | Add working draft of a saving scenario
| JavaScript | apache-2.0 | 28msec/nolap-report-editor | ---
+++
@@ -0,0 +1,27 @@
+'use strict';
+
+//https://github.com/angular/protractor/blob/master/docs/api.md
+//GetAttribute() returns "boolean" values and will return either "true" or null
+describe('Reports', function(){
+
+ var id = '1fueA5hrxIHxvRf7Btr_J6efDJ3qp-s9KV731wDc4OOaw';
+ var Report = require('../../app/report/report-page');
+ var FiltersPage = require('../../app/report/filters/filters-page');
+
+ it('Should throw an exception if we reloading while saving the report', function(){
+ var report = new Report(id);
+ var filters = report.filters;
+ filters.visitPage();
+ //Let's do an illegal update where we don't wait for angularjs to finish
+ //See https://github.com/angular/protractor/issues/308
+ filters.resetSelectedFilters();
+ filters.visitPage().then(function(){
+ expect(true).toBe(false);
+ }, function(){
+ expect(true).toBe(true);
+ });
+ //browser.switchTo().alert().then(function(alert) {
+ // alert.accept();
+ //});
+ });
+}); | |
332f393ac7527800036ca24bf5b76d84af531a41 | src/deck.js | src/deck.js | const Card = require('./card.js');
class Deck {
constructor() {
this.cards = [];
for (let suit of Card.Suits()) {
for (let rank of Card.Ranks()) {
let card = new Card(rank, suit);
this.cards.push(card);
}
}
}
shuffle() {
let numberOfCards = this.cards.length;
for (let index = 0; index < numberOfCards; index++) {
let newIndex = Deck.getRandomInt(0, numberOfCards);
let cardToSwap = this.cards[newIndex];
this.cards[newIndex] = this.cards[index];
this.cards[index] = cardToSwap;
}
}
drawCard() {
return this.cards.shift();
}
toString() {
return this.cards.join();
}
static getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
}
module.exports = Deck; | const Card = require('./card.js');
class Deck {
constructor() {
this.cards = [];
for (let suit of Card.Suits()) {
for (let rank of Card.Ranks()) {
let card = new Card(rank, suit);
this.cards.push(card);
}
}
}
// Public: Performs a proper Fisher-Yates shuffle.
//
// Returns nothing; the shuffle is in-place.
shuffle() {
let temp, idx;
let cardsRemaining = this.cards.length;
// While there remain elements to shuffle…
while (cardsRemaining) {
// Pick a remaining element…
idx = Math.floor(Math.random() * cardsRemaining--);
// And swap it with the current element.
temp = this.cards[cardsRemaining];
this.cards[cardsRemaining] = this.cards[idx];
this.cards[idx] = temp;
}
}
drawCard() {
return this.cards.shift();
}
toString() {
return this.cards.join();
}
}
module.exports = Deck;
| Implement a proper Fisher-Yates shuffle. | Implement a proper Fisher-Yates shuffle.
| JavaScript | mit | stvvan/slack-poker-bot,bdthinh/slack-poker-bot,CharlieHess/slack-poker-bot,rodrigomonteiro/slack-poker-bot,codevlabs/slack-poker-bot,sqlbyme/slack-poker-bot,jbomotti/slack-poker-bot,Andrey-Pavlov/slack-poker-bot,tim-mc/slack-poker-bot,bitzesty/slack-poker-bot,ysterp/poker,A-w-K/slack-poker-bot,Th3Mouk/slack-poker-bot,sametheridge/slack-poker-bot,jingpei/slack-poker-bot,kvartz/slack-poker-bot,abmohan/slack-poker-bot,shaunstanislaus/slack-poker-bot,coreyaus/slack-poker-bot,calsaviour/slack-poker-bot,hubdotcom/slack-poker-bot,andrewho83/slack-poker-bot,pas256/slack-poker-bot,mitchbank/slack-poker-bot,kitwalker12/slack-poker-bot,minalecs/slack-poker-bot,wcjohnson11/slack-poker-bot,thepoho/slack-poker-bot,jabbink/slack-poker-bot | ---
+++
@@ -10,29 +10,33 @@
}
}
}
-
+
+ // Public: Performs a proper Fisher-Yates shuffle.
+ //
+ // Returns nothing; the shuffle is in-place.
shuffle() {
- let numberOfCards = this.cards.length;
-
- for (let index = 0; index < numberOfCards; index++) {
- let newIndex = Deck.getRandomInt(0, numberOfCards);
- let cardToSwap = this.cards[newIndex];
-
- this.cards[newIndex] = this.cards[index];
- this.cards[index] = cardToSwap;
+ let temp, idx;
+ let cardsRemaining = this.cards.length;
+
+ // While there remain elements to shuffle…
+ while (cardsRemaining) {
+
+ // Pick a remaining element…
+ idx = Math.floor(Math.random() * cardsRemaining--);
+
+ // And swap it with the current element.
+ temp = this.cards[cardsRemaining];
+ this.cards[cardsRemaining] = this.cards[idx];
+ this.cards[idx] = temp;
}
}
-
+
drawCard() {
return this.cards.shift();
}
-
+
toString() {
return this.cards.join();
- }
-
- static getRandomInt(min, max) {
- return Math.floor(Math.random() * (max - min)) + min;
}
}
|
de4a7ee9cb31e257a3fe5ceb494586b19a412ba2 | src/v2/stories/Bookmarklet.stories.js | src/v2/stories/Bookmarklet.stories.js | import React from 'react'
import { storiesOf } from '@storybook/react'
import Specimen from 'v2/stories/__components__/Specimen'
import Bookmarklet from 'v2/components/Bookmarklet/components/Blocks'
storiesOf('Bookmarklet', module).add('Bookmarklet', () => (
<Specimen>
<Bookmarklet />
</Specimen>
))
| Add story for bookmarklet component | Add story for bookmarklet component
| JavaScript | mit | aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell,aredotna/ervell | ---
+++
@@ -0,0 +1,12 @@
+import React from 'react'
+import { storiesOf } from '@storybook/react'
+
+import Specimen from 'v2/stories/__components__/Specimen'
+
+import Bookmarklet from 'v2/components/Bookmarklet/components/Blocks'
+
+storiesOf('Bookmarklet', module).add('Bookmarklet', () => (
+ <Specimen>
+ <Bookmarklet />
+ </Specimen>
+)) | |
d8b89e1d4bd4b6c0b58b3804f9b3502f9f80a5eb | ch02/fizz_buzz_2.js | ch02/fizz_buzz_2.js | /**
* Created by larry on 8/28/16.
*/
for(var i = 1; i <= 100; i++) {
if (i % 3 == 0 && i % 5 == 0) {
console.log("FizzBuzz");
}
else if (i % 3 == 0) {
console.log("Fizz");
}
else if (i % 5 == 0) {
console.log("Buzz");
}
else {
console.log(i);
}
}
| Write the second version of "Fizz Buzz." | Write the second version of "Fizz Buzz."
This version handles all the cases in the actual game:
* Print "FizzBuzz" if the value is evenly divisible by both 3 and 5
* Print "Fizz" if the value is evenly divisible by 3
* Print "Buzz" if the value is evenly divisble by 5
* Otherwise, print the value
| JavaScript | apache-2.0 | mrwizard82d1/eloquent-js | ---
+++
@@ -0,0 +1,18 @@
+/**
+ * Created by larry on 8/28/16.
+ */
+
+for(var i = 1; i <= 100; i++) {
+ if (i % 3 == 0 && i % 5 == 0) {
+ console.log("FizzBuzz");
+ }
+ else if (i % 3 == 0) {
+ console.log("Fizz");
+ }
+ else if (i % 5 == 0) {
+ console.log("Buzz");
+ }
+ else {
+ console.log(i);
+ }
+} | |
cb260529a8585a8a5e34ff7962602e560be08e39 | app/actions/__tests__/tasks.js | app/actions/__tests__/tasks.js | import * as actions from '../tasks';
describe('Task Actions', () => {
let defaultId,
defaultTask;
beforeEach(() => {
defaultId = 'someUniqueId';
defaultTask = {
id: 'someIdString',
name: 'Some task name'
};
});
it('ADD_TASK should return the object with the passed in task', () => {
const result = actions.ADD_TASK(defaultTask);
expect(result).toEqual({
type: 'ADD_TASK',
task: defaultTask
});
});
it('EDIT_TASK should return the object with the passed in ID and task', () => {
const result = actions.EDIT_TASK(defaultId, defaultTask);
expect(result).toEqual({
type: 'EDIT_TASK',
id: defaultId,
task: defaultTask
});
});
it('DELETE_TASK should return the object with the passed in ID', () => {
const result = actions.DELETE_TASK(defaultId);
expect(result).toEqual({
type: 'DELETE_TASK',
id: defaultId
});
});
it('TOGGLE_TASK should return the object with the passed in ID', () => {
const result = actions.TOGGLE_TASK(defaultId);
expect(result).toEqual({
type: 'TOGGLE_TASK',
id: defaultId
});
});
it('SWIPEOUT_TASK should return the object with the passed in ID', () => {
const result = actions.SWIPEOUT_TASK(defaultId);
expect(result).toEqual({
type: 'SWIPEOUT_TASK',
id: defaultId
});
});
});
| Add test coverage for actions | Add test coverage for actions
| JavaScript | mit | CarlaCrandall/DoItNow,CarlaCrandall/DoItNow,CarlaCrandall/DoItNow | ---
+++
@@ -0,0 +1,56 @@
+import * as actions from '../tasks';
+
+describe('Task Actions', () => {
+ let defaultId,
+ defaultTask;
+
+ beforeEach(() => {
+ defaultId = 'someUniqueId';
+ defaultTask = {
+ id: 'someIdString',
+ name: 'Some task name'
+ };
+ });
+
+ it('ADD_TASK should return the object with the passed in task', () => {
+ const result = actions.ADD_TASK(defaultTask);
+ expect(result).toEqual({
+ type: 'ADD_TASK',
+ task: defaultTask
+ });
+ });
+
+ it('EDIT_TASK should return the object with the passed in ID and task', () => {
+ const result = actions.EDIT_TASK(defaultId, defaultTask);
+ expect(result).toEqual({
+ type: 'EDIT_TASK',
+ id: defaultId,
+ task: defaultTask
+ });
+ });
+
+ it('DELETE_TASK should return the object with the passed in ID', () => {
+ const result = actions.DELETE_TASK(defaultId);
+ expect(result).toEqual({
+ type: 'DELETE_TASK',
+ id: defaultId
+ });
+ });
+
+ it('TOGGLE_TASK should return the object with the passed in ID', () => {
+ const result = actions.TOGGLE_TASK(defaultId);
+ expect(result).toEqual({
+ type: 'TOGGLE_TASK',
+ id: defaultId
+ });
+ });
+
+ it('SWIPEOUT_TASK should return the object with the passed in ID', () => {
+ const result = actions.SWIPEOUT_TASK(defaultId);
+ expect(result).toEqual({
+ type: 'SWIPEOUT_TASK',
+ id: defaultId
+ });
+ });
+
+}); | |
ad3b613fc3eeb800a4c2a9d5f51d35debb9871c9 | learning/javascript/TeamStats.js | learning/javascript/TeamStats.js | const team = {
_players:[
{
firstName: 'Cristiano',
lastName: 'Ronaldo',
age: 36
},
{
firstName: 'Lionel',
lastName: 'Messi',
age:32
},
{
firstName: 'Ice',
lastName: 'Shi',
ange:37
}
],
_games:[
{
opponent: 'Manchester United',
teamPoint: 1,
opponentPoints: 3
},
{
opponent: 'Real Marid',
teamPoint: 3,
opponentPoints: 0
},
{
opponent: 'AC Milan',
teamPoint: 3,
opponentPoints: 3
}
],
get players(){
return this._players;
},
get games(){
return this._games;
},
addPlayer(firstName, lastName, age){
const player = {
firstName:firstName,
lastName: lastName,
age: age
};
this._players.push(player);
},
addGame(opponent, teamPoint, opponentPoint){
const game = {
opponent:opponent,
teamPoint: teamPoint,
opponentPoint: opponentPoint
};
this._games.push(game);
}
};
team.addPlayer('Steph', 'Curry', 28);
team.addPlayer('Lisa', 'Leslie', 44);
team.addPlayer('Bugs', 'Bunny', 76);
console.log(team.players);
team.addGame('Team We', 4, 1);
console.log(team.games); | Add project team stats on learning Object section | Add project team stats on learning Object section
| JavaScript | apache-2.0 | SpAiNiOr/mystudy,SpAiNiOr/mystudy,SpAiNiOr/mystudy | ---
+++
@@ -0,0 +1,67 @@
+const team = {
+ _players:[
+ {
+ firstName: 'Cristiano',
+ lastName: 'Ronaldo',
+ age: 36
+ },
+ {
+ firstName: 'Lionel',
+ lastName: 'Messi',
+ age:32
+ },
+ {
+ firstName: 'Ice',
+ lastName: 'Shi',
+ ange:37
+ }
+ ],
+ _games:[
+ {
+ opponent: 'Manchester United',
+ teamPoint: 1,
+ opponentPoints: 3
+ },
+ {
+ opponent: 'Real Marid',
+ teamPoint: 3,
+ opponentPoints: 0
+ },
+ {
+ opponent: 'AC Milan',
+ teamPoint: 3,
+ opponentPoints: 3
+ }
+ ],
+ get players(){
+ return this._players;
+ },
+ get games(){
+ return this._games;
+ },
+ addPlayer(firstName, lastName, age){
+ const player = {
+ firstName:firstName,
+ lastName: lastName,
+ age: age
+ };
+ this._players.push(player);
+ },
+ addGame(opponent, teamPoint, opponentPoint){
+ const game = {
+ opponent:opponent,
+ teamPoint: teamPoint,
+ opponentPoint: opponentPoint
+ };
+ this._games.push(game);
+ }
+ };
+
+ team.addPlayer('Steph', 'Curry', 28);
+ team.addPlayer('Lisa', 'Leslie', 44);
+ team.addPlayer('Bugs', 'Bunny', 76);
+
+ console.log(team.players);
+
+ team.addGame('Team We', 4, 1);
+ console.log(team.games); | |
ad1dde3af5b710077ce07d450d92f86762b70da0 | week-7/javascript_olympics.js | week-7/javascript_olympics.js | /*
PEER PARING CHALLENGE 7.6: JAVASCRIPT OLYMPICS
WE PAIRED ON THIS CHALLENGE: Becca Nelson & Lars Johnson
THIS CHALLENGE TOOK US: ___ Hours
*/
// ###########################################################
// WARM UP
// ###########################################################
// BULK UP
// ###########################################################
// JUMBLE YOUR WORDS
// ###########################################################
// 2, 4, 6, 8! WHO DO YOU APPRECIATE?
// ###########################################################
// WE BUILT THIS CITY
/* ________________________________________________________________________________________
// DRIVER TEST CODE
var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
console.log(michaelPhelps.constructor === Athlete)
console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)
/*
/* ###########################################################
// REFLECTION
1. What JavaScript knowledge did you solidify in this challenge?
2. What are constructor functions?
3. How are constructors different from Ruby classes (in your research)?
*/
| Create JS Olympics file for 7.6 | Create JS Olympics file for 7.6
| JavaScript | mit | larsjx/phase-0,larsjx/phase-0,larsjx/phase-0 | ---
+++
@@ -0,0 +1,57 @@
+/*
+
+ PEER PARING CHALLENGE 7.6: JAVASCRIPT OLYMPICS
+
+ WE PAIRED ON THIS CHALLENGE: Becca Nelson & Lars Johnson
+ THIS CHALLENGE TOOK US: ___ Hours
+
+*/
+// ###########################################################
+// WARM UP
+
+
+
+
+// ###########################################################
+// BULK UP
+
+
+
+
+// ###########################################################
+// JUMBLE YOUR WORDS
+
+
+
+
+// ###########################################################
+// 2, 4, 6, 8! WHO DO YOU APPRECIATE?
+
+
+
+
+// ###########################################################
+// WE BUILT THIS CITY
+
+
+/* ________________________________________________________________________________________
+// DRIVER TEST CODE
+
+var michaelPhelps = new Athlete("Michael Phelps", 29, "swimming", "It's medicinal I swear!")
+console.log(michaelPhelps.constructor === Athlete)
+console.log(michaelPhelps.name + " " + michaelPhelps.sport + " " + michaelPhelps.quote)
+
+/*
+/* ###########################################################
+// REFLECTION
+
+ 1. What JavaScript knowledge did you solidify in this challenge?
+
+
+ 2. What are constructor functions?
+
+
+ 3. How are constructors different from Ruby classes (in your research)?
+
+
+*/ | |
41aa5f27916122de2f7f12f9a5916c08b1800649 | flow-typed/npm/@storybook/addon-actions_v4.x.x.js | flow-typed/npm/@storybook/addon-actions_v4.x.x.js | // flow-typed signature: 824de8c4d861db90a6471d410d3df917
// flow-typed version: <<STUB>>/@storybook/addon-actions_v4.0.0/flow_v0.90.0
/**
* This is an autogenerated libdef stub for:
*
* '@storybook/addon-actions'
*
* Fill this stub out by replacing all the `any` types.
*
* Once filled out, we encourage you to share your work with the
* community by sending a pull request to:
* https://github.com/flowtype/flow-typed
*/
declare module '@storybook/addon-actions' {
declare type Action = (name: string) => (...args: Array<any>) => void;
declare type DecorateFn = (args: Array<any>) => Array<any>;
declare module.exports: {
action: Action,
decorateAction(args: Array<DecorateFn>): Action;
};
}
| Add types for @storybook/addon-actions package | Add types for @storybook/addon-actions package
| JavaScript | mit | moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0,moira-alert/web2.0 | ---
+++
@@ -0,0 +1,24 @@
+// flow-typed signature: 824de8c4d861db90a6471d410d3df917
+// flow-typed version: <<STUB>>/@storybook/addon-actions_v4.0.0/flow_v0.90.0
+
+/**
+ * This is an autogenerated libdef stub for:
+ *
+ * '@storybook/addon-actions'
+ *
+ * Fill this stub out by replacing all the `any` types.
+ *
+ * Once filled out, we encourage you to share your work with the
+ * community by sending a pull request to:
+ * https://github.com/flowtype/flow-typed
+ */
+
+declare module '@storybook/addon-actions' {
+ declare type Action = (name: string) => (...args: Array<any>) => void;
+ declare type DecorateFn = (args: Array<any>) => Array<any>;
+
+ declare module.exports: {
+ action: Action,
+ decorateAction(args: Array<DecorateFn>): Action;
+ };
+} | |
5bffa73605614b0250d047033621e9591ddc578c | webextensions/common/common.js | webextensions/common/common.js | 'use strict';
var configs;
function log(aMessage, ...aArgs) {
if (!configs || !configs.debug)
return;
console.log('reload-on-idle: ' + aMessage, ...aArgs);
};
function createFilter() {
try {
return new RegExp(configs.filter, 'i');
} catch (e) {
log(`"${configs.filter}" is not a valid expression.`);
return /./;
}
};
configs = new Configs({
idleSeconds: 600,
filter: '.',
reloadBusyTabs: false,
debug: false,
});
| Define the data structure for addon settings. | WE: Define the data structure for addon settings.
This is a straight-forward translation of the XPCOM-based configuration.
(Few options are missing for compatibility reasons, though)
See 'reload-on-idle/content/config.xul' for details.
| JavaScript | mpl-2.0 | clear-code/reload-on-idle,clear-code/reload-on-idle,clear-code/reload-on-idle | ---
+++
@@ -0,0 +1,25 @@
+'use strict';
+
+var configs;
+
+function log(aMessage, ...aArgs) {
+ if (!configs || !configs.debug)
+ return;
+ console.log('reload-on-idle: ' + aMessage, ...aArgs);
+};
+
+function createFilter() {
+ try {
+ return new RegExp(configs.filter, 'i');
+ } catch (e) {
+ log(`"${configs.filter}" is not a valid expression.`);
+ return /./;
+ }
+};
+
+configs = new Configs({
+ idleSeconds: 600,
+ filter: '.',
+ reloadBusyTabs: false,
+ debug: false,
+}); | |
c126dd52a5993b29eed8c87b32a6699c648d0570 | js/components/immutableComponent.js | js/components/immutableComponent.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 React = require('react')
class ImmutableComponent extends React.Component {
shouldComponentUpdate (nextProps, nextState) {
return Object.keys(nextProps).some(prop => nextState !== this.props[prop])
}
}
module.exports = ImmutableComponent
| /* 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 React = require('react')
class ImmutableComponent extends React.Component {
shouldComponentUpdate (nextProps) {
return Object.keys(nextProps).some(prop => nextProps[prop] !== this.props[prop])
}
}
module.exports = ImmutableComponent
| Use nextProps for comparison not nextState | Use nextProps for comparison not nextState
Auditors: da39a3ee5e6b4b0d3255bfef95601890afd80709@bridiver
| JavaScript | mpl-2.0 | MKuenzi/browser-laptop,timborden/browser-laptop,willy-b/browser-laptop,willy-b/browser-laptop,manninglucas/browser-laptop,timborden/browser-laptop,MKuenzi/browser-laptop,darkdh/browser-laptop,diasdavid/browser-laptop,diasdavid/browser-laptop,timborden/browser-laptop,darkdh/browser-laptop,Sh1d0w/browser-laptop,pmkary/braver,manninglucas/browser-laptop,timborden/browser-laptop,dcposch/browser-laptop,manninglucas/browser-laptop,darkdh/browser-laptop,diasdavid/browser-laptop,jonathansampson/browser-laptop,luixxiul/browser-laptop,darkdh/browser-laptop,willy-b/browser-laptop,pmkary/braver,jonathansampson/browser-laptop,luixxiul/browser-laptop,dcposch/browser-laptop,jonathansampson/browser-laptop,diasdavid/browser-laptop,MKuenzi/browser-laptop,Sh1d0w/browser-laptop,Sh1d0w/browser-laptop,Sh1d0w/browser-laptop,jonathansampson/browser-laptop,MKuenzi/browser-laptop,pmkary/braver,luixxiul/browser-laptop,luixxiul/browser-laptop,willy-b/browser-laptop,manninglucas/browser-laptop,pmkary/braver,dcposch/browser-laptop,dcposch/browser-laptop | ---
+++
@@ -5,8 +5,8 @@
const React = require('react')
class ImmutableComponent extends React.Component {
- shouldComponentUpdate (nextProps, nextState) {
- return Object.keys(nextProps).some(prop => nextState !== this.props[prop])
+ shouldComponentUpdate (nextProps) {
+ return Object.keys(nextProps).some(prop => nextProps[prop] !== this.props[prop])
}
}
|
8bab3396c6e13326d8aba4e31adac88d4f310399 | src/common/bootstrap/bootstrap.js | src/common/bootstrap/bootstrap.js | /**
* Enhances the angular bootstrap directive to allow it to stay open when the
* user clicks inside the menu.
*/
angular.module('ui.bootstrap.dropdownToggle', []).directive('dropdownToggleNoClose',
['$document', '$location', '$window', function ($document, $location, $window) {
var openElement = null,
closeMenu = angular.noop;
return {
restrict: 'CA',
link: function(scope, element, attrs) {
// close the menu if the route changes
scope.$watch('$location.path', function() { closeMenu(); });
element.parent().bind('click', function() { closeMenu(); });
element.bind('click', function(event) {
// Do not cascade up to the parent since that would close the menu
event.preventDefault();
event.stopPropagation();
var elementWasOpen = (element === openElement);
if (!!openElement) {
closeMenu();
}
if (!elementWasOpen){
element.parent().addClass('open');
openElement = element;
closeMenu = function (event) {
if (event) {
event.preventDefault();
event.stopPropagation();
}
element.parent().removeClass('open');
closeMenu = angular.noop;
openElement = null;
};
}
// When the document is clicked close the menu
$document.bind('click', closeMenu);
});
// But allow clicking in the menu itself
angular.forEach(element.parent().children(), function(node) {
var elm = angular.element(node);
if (elm.hasClass('dropdown-menu')) {
elm.bind('click', function(event){
// Stop the event so that the close menu above is not triggered
event.preventDefault();
event.stopPropagation();
return false;
});
}
});
}
};
}]);
| Add a variation on the Angular UI Bootstrap code which keeps the dropdown open as long as the clicks are inside the menu | Add a variation on the Angular UI Bootstrap code which keeps the dropdown open as long as the clicks are inside the menu
| JavaScript | bsd-3-clause | trestle-pm/trestle | ---
+++
@@ -0,0 +1,60 @@
+/**
+ * Enhances the angular bootstrap directive to allow it to stay open when the
+ * user clicks inside the menu.
+ */
+angular.module('ui.bootstrap.dropdownToggle', []).directive('dropdownToggleNoClose',
+ ['$document', '$location', '$window', function ($document, $location, $window) {
+ var openElement = null,
+ closeMenu = angular.noop;
+
+ return {
+ restrict: 'CA',
+
+ link: function(scope, element, attrs) {
+ // close the menu if the route changes
+ scope.$watch('$location.path', function() { closeMenu(); });
+ element.parent().bind('click', function() { closeMenu(); });
+
+ element.bind('click', function(event) {
+ // Do not cascade up to the parent since that would close the menu
+ event.preventDefault();
+ event.stopPropagation();
+
+ var elementWasOpen = (element === openElement);
+ if (!!openElement) {
+ closeMenu();
+ }
+
+ if (!elementWasOpen){
+ element.parent().addClass('open');
+ openElement = element;
+ closeMenu = function (event) {
+ if (event) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ element.parent().removeClass('open');
+ closeMenu = angular.noop;
+ openElement = null;
+ };
+ }
+
+ // When the document is clicked close the menu
+ $document.bind('click', closeMenu);
+ });
+
+ // But allow clicking in the menu itself
+ angular.forEach(element.parent().children(), function(node) {
+ var elm = angular.element(node);
+ if (elm.hasClass('dropdown-menu')) {
+ elm.bind('click', function(event){
+ // Stop the event so that the close menu above is not triggered
+ event.preventDefault();
+ event.stopPropagation();
+ return false;
+ });
+ }
+ });
+ }
+ };
+}]); | |
8ee1550f8931410495e329d04a3b6bd71a462e1f | app/models/customer.server.model.js | app/models/customer.server.model.js | 'use strict';
/**
* Module dependencies.
*/
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
/**
* Customer Schema
*/
var CustomerSchema = new Schema({
firstName: {
type: String,
default: '',
trim: true
},
surName: {
type: String,
default: '',
trim: true
},
suburb: {
type: String,
default: '',
trim: true
},
country: {
type: String,
default: '',
trim: true
},
industry: {
type: String,
default: '',
trim: true
},
email: {
type: String,
default: '',
trim: true
},
phone: {
type: String,
default: '',
trim: true
},
referred: {
type: Boolean
},
channel: {
type: String,
default: '',
trim: true
},
created: {
type: Date,
default: Date.now
},
user: {
type: Schema.ObjectId,
ref: 'User'
}
});
mongoose.model('Customer', CustomerSchema);
| Update as Day 10 Customer Model | Update as Day 10 Customer Model
| JavaScript | mit | cheshiret/myMeanProject,cheshiret/myMeanProject,cheshiret/myMeanProject | ---
+++
@@ -0,0 +1,66 @@
+'use strict';
+
+/**
+ * Module dependencies.
+ */
+var mongoose = require('mongoose'),
+ Schema = mongoose.Schema;
+
+/**
+ * Customer Schema
+ */
+var CustomerSchema = new Schema({
+ firstName: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ surName: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ suburb: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ country: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ industry: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ email: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ phone: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ referred: {
+ type: Boolean
+ },
+ channel: {
+ type: String,
+ default: '',
+ trim: true
+ },
+ created: {
+ type: Date,
+ default: Date.now
+ },
+ user: {
+ type: Schema.ObjectId,
+ ref: 'User'
+ }
+});
+
+mongoose.model('Customer', CustomerSchema); | |
c0304dcb326316638c41c209b76409e1853a8230 | test/browser/refs.js | test/browser/refs.js | import { h, render, Component } from '../../src/preact';
/** @jsx h */
describe('refs', () => {
let scratch;
before( () => {
scratch = document.createElement('div');
(document.body || document.documentElement).appendChild(scratch);
});
beforeEach( () => {
scratch.innerHTML = '';
});
after( () => {
scratch.parentNode.removeChild(scratch);
scratch = null;
});
it('should invoke refs in render()', () => {
let spy = sinon.spy();
render(<div ref={spy} />, scratch);
expect(spy).to.have.been.calledOnce.and.calledWith(scratch.firstChild);
});
it('should invoke refs in Component.render()', () => {
let outer = sinon.spy(),
inner = sinon.spy();
class Foo extends Component {
render() {
return (
<div ref={outer}>
<span ref={inner} />
</div>
);
}
}
render(<Foo />, scratch);
expect(outer).to.have.been.calledWith(scratch.firstChild);
expect(inner).to.have.been.calledWith(scratch.firstChild.firstChild);
});
it('should pass components to ref functions', () => {
let spy = sinon.spy(),
instance;
class Foo extends Component {
constructor() {
super();
instance = this;
}
render() {
return <div />;
}
}
render(<Foo ref={spy} />, scratch);
expect(spy).to.have.been.calledOnce.and.calledWith(instance);
});
it('should pass high-order children to ref functions', () => {
let outer = sinon.spy(),
inner = sinon.spy(),
outerInst,
innerInst;
class Outer extends Component {
constructor() {
super();
outerInst = this;
}
render() {
return <Inner ref={inner} />;
}
}
class Inner extends Component {
constructor() {
super();
innerInst = this;
}
render() {
return <span />;
}
}
render(<Outer ref={outer} />, scratch);
expect(outer).to.have.been.calledOnce.and.calledWith(outerInst);
expect(inner).to.have.been.calledOnce.and.calledWith(innerInst);
});
});
| Add tests for `ref` :) | Add tests for `ref` :)
| JavaScript | mit | neeharv/preact,developit/preact,gogoyqj/preact,neeharv/preact,developit/preact | ---
+++
@@ -0,0 +1,90 @@
+import { h, render, Component } from '../../src/preact';
+/** @jsx h */
+
+describe('refs', () => {
+ let scratch;
+
+ before( () => {
+ scratch = document.createElement('div');
+ (document.body || document.documentElement).appendChild(scratch);
+ });
+
+ beforeEach( () => {
+ scratch.innerHTML = '';
+ });
+
+ after( () => {
+ scratch.parentNode.removeChild(scratch);
+ scratch = null;
+ });
+
+ it('should invoke refs in render()', () => {
+ let spy = sinon.spy();
+ render(<div ref={spy} />, scratch);
+ expect(spy).to.have.been.calledOnce.and.calledWith(scratch.firstChild);
+ });
+
+ it('should invoke refs in Component.render()', () => {
+ let outer = sinon.spy(),
+ inner = sinon.spy();
+ class Foo extends Component {
+ render() {
+ return (
+ <div ref={outer}>
+ <span ref={inner} />
+ </div>
+ );
+ }
+ }
+ render(<Foo />, scratch);
+
+ expect(outer).to.have.been.calledWith(scratch.firstChild);
+ expect(inner).to.have.been.calledWith(scratch.firstChild.firstChild);
+ });
+
+ it('should pass components to ref functions', () => {
+ let spy = sinon.spy(),
+ instance;
+ class Foo extends Component {
+ constructor() {
+ super();
+ instance = this;
+ }
+ render() {
+ return <div />;
+ }
+ }
+ render(<Foo ref={spy} />, scratch);
+
+ expect(spy).to.have.been.calledOnce.and.calledWith(instance);
+ });
+
+ it('should pass high-order children to ref functions', () => {
+ let outer = sinon.spy(),
+ inner = sinon.spy(),
+ outerInst,
+ innerInst;
+ class Outer extends Component {
+ constructor() {
+ super();
+ outerInst = this;
+ }
+ render() {
+ return <Inner ref={inner} />;
+ }
+ }
+ class Inner extends Component {
+ constructor() {
+ super();
+ innerInst = this;
+ }
+ render() {
+ return <span />;
+ }
+ }
+ render(<Outer ref={outer} />, scratch);
+
+ expect(outer).to.have.been.calledOnce.and.calledWith(outerInst);
+ expect(inner).to.have.been.calledOnce.and.calledWith(innerInst);
+ });
+}); | |
988174a6294ab863be2961267174901440100944 | test/mjsunit/test-path.js | test/mjsunit/test-path.js | var path = require("path");
process.mixin(require("./common"));
var f = __filename;
assert.equal(path.basename(f), "test-path.js");
assert.equal(path.basename(f, ".js"), "test-path");
assert.equal(path.extname(f), ".js");
assert.equal(path.dirname(f).substr(-13), "/test/mjsunit");
path.exists(f, function (y) { assert.equal(y, true) });
assert.equal(path.join(".", "fixtures/b", "..", "/b/c.js"), "fixtures/b/c.js");
assert.equal(path.normalize("./fixtures///b/../b/c.js"), "fixtures/b/c.js");
assert.equal(path.normalize("./fixtures///b/../b/c.js",true), "fixtures///b/c.js");
assert.deepEqual(path.normalizeArray(["fixtures","b","","..","b","c.js"]), ["fixtures","b","c.js"]);
assert.deepEqual(path.normalizeArray(["fixtures","","b","..","b","c.js"], true), ["fixtures","","b","c.js"]);
assert.equal(path.normalize("a//b//../b", true), "a//b/b");
assert.equal(path.normalize("a//b//../b"), "a/b");
assert.equal(path.normalize("a//b//./c", true), "a//b//c");
assert.equal(path.normalize("a//b//./c"), "a/b/c");
assert.equal(path.normalize("a//b//.", true), "a//b/");
assert.equal(path.normalize("a//b//."), "a/b");
| Add tests for path module. | Add tests for path module.
| 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,27 @@
+var path = require("path");
+process.mixin(require("./common"));
+
+var f = __filename;
+
+assert.equal(path.basename(f), "test-path.js");
+assert.equal(path.basename(f, ".js"), "test-path");
+assert.equal(path.extname(f), ".js");
+assert.equal(path.dirname(f).substr(-13), "/test/mjsunit");
+path.exists(f, function (y) { assert.equal(y, true) });
+
+assert.equal(path.join(".", "fixtures/b", "..", "/b/c.js"), "fixtures/b/c.js");
+
+assert.equal(path.normalize("./fixtures///b/../b/c.js"), "fixtures/b/c.js");
+assert.equal(path.normalize("./fixtures///b/../b/c.js",true), "fixtures///b/c.js");
+
+assert.deepEqual(path.normalizeArray(["fixtures","b","","..","b","c.js"]), ["fixtures","b","c.js"]);
+assert.deepEqual(path.normalizeArray(["fixtures","","b","..","b","c.js"], true), ["fixtures","","b","c.js"]);
+
+assert.equal(path.normalize("a//b//../b", true), "a//b/b");
+assert.equal(path.normalize("a//b//../b"), "a/b");
+
+assert.equal(path.normalize("a//b//./c", true), "a//b//c");
+assert.equal(path.normalize("a//b//./c"), "a/b/c");
+assert.equal(path.normalize("a//b//.", true), "a//b/");
+assert.equal(path.normalize("a//b//."), "a/b");
+ | |
5470155907b3c85417b63e92e7b2d9c7c04690fc | test/test-api-util-cache.js | test/test-api-util-cache.js | module.exports = {
setUp: function (callback) {
var path = require('path');
this.cache = require('../lib/utils/cache');
this.cache.init({
"path" : path.resolve(__dirname, "../") + "/cache"
});
this.cacheKey = "test";
this.cacheValue = "{test:tefdsafsafdsast}";
callback();
},
tearDown: function (callback) {
// clean up
callback();
},
testAddCachedValue: function (test) {
this.cache.add(this.cacheKey, this.cacheValue, function(val){
console.log(val);
test.done();
});
},
testGetCachedValue: function (test) {
this.cache.get(this.cacheKey, function(val){
console.log(val);
test.done();
});
}
}; | Create test file for cache. | Create test file for cache.
| JavaScript | mit | Solid-Interactive/grasshopper-api-js,Solid-Interactive/grasshopper-api-js | ---
+++
@@ -0,0 +1,32 @@
+module.exports = {
+ setUp: function (callback) {
+ var path = require('path');
+
+ this.cache = require('../lib/utils/cache');
+ this.cache.init({
+ "path" : path.resolve(__dirname, "../") + "/cache"
+ });
+ this.cacheKey = "test";
+ this.cacheValue = "{test:tefdsafsafdsast}";
+
+ callback();
+ },
+ tearDown: function (callback) {
+ // clean up
+ callback();
+ },
+ testAddCachedValue: function (test) {
+
+ this.cache.add(this.cacheKey, this.cacheValue, function(val){
+ console.log(val);
+ test.done();
+ });
+ },
+ testGetCachedValue: function (test) {
+
+ this.cache.get(this.cacheKey, function(val){
+ console.log(val);
+ test.done();
+ });
+ }
+}; | |
1017054e95ecb84155c54102705f8570e0199a49 | polygerrit-ui/app/types/polymer-behaviors.js | polygerrit-ui/app/types/polymer-behaviors.js | /**
* @license
* Copyright (C) 2019 The Android Open Source Project
*
* 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.
*/
/**
* For the purposes of template type checking, externs should be added for
* anything set on the window object. Note that sub-properties of these
* declared properties are considered something separate.
*
* This file is only for template type checking, not used in Gerrit code.
*/
/* eslint-disable no-var */
/* eslint-disable no-unused-vars */
function PolymerMixins() {
// This function must not be called.
// Due to an issue in polymer linter the linter can't
// process correctly some behaviors from Polymer library.
// To workaround this issue, here we define a minimal mixin to allow
// linter process our code correctly. You can add more properties to mixins
// if needed.
// Important! Use mixins from these file only inside JSDoc comments.
// Do not use it in the real code
/**
* @polymer
* @mixinFunction
* */
Polymer.IronFitMixin = base =>
class extends base {
static get properties() {
return {
positionTarget: Object,
};
}
};
}
| Add mock mixin for Polymer.IronFitBehavior | Add mock mixin for Polymer.IronFitBehavior
Polymer.IronFitBehavior doesn't have a mixin and should be added to
component using Polymer.mixinBehavior([Polymer.IronFitBehavior]).
Polymer linter doesn't process this correctly. To workaround it the mock
mixin was added. It will be used in JSDoc comments after conversion to
class-based elements.
Change-Id: I61be019129879efe50c11c0f7dd56d6cef679136
| JavaScript | apache-2.0 | GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit,GerritCodeReview/gerrit | ---
+++
@@ -0,0 +1,52 @@
+/**
+ * @license
+ * Copyright (C) 2019 The Android Open Source Project
+ *
+ * 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.
+ */
+
+/**
+ * For the purposes of template type checking, externs should be added for
+ * anything set on the window object. Note that sub-properties of these
+ * declared properties are considered something separate.
+ *
+ * This file is only for template type checking, not used in Gerrit code.
+ */
+
+/* eslint-disable no-var */
+/* eslint-disable no-unused-vars */
+
+function PolymerMixins() {
+ // This function must not be called.
+ // Due to an issue in polymer linter the linter can't
+ // process correctly some behaviors from Polymer library.
+ // To workaround this issue, here we define a minimal mixin to allow
+ // linter process our code correctly. You can add more properties to mixins
+ // if needed.
+
+ // Important! Use mixins from these file only inside JSDoc comments.
+ // Do not use it in the real code
+
+ /**
+ * @polymer
+ * @mixinFunction
+ * */
+ Polymer.IronFitMixin = base =>
+ class extends base {
+ static get properties() {
+ return {
+ positionTarget: Object,
+ };
+ }
+ };
+} | |
2060d39c9d2690095ce5520ea0cf25bad1015c70 | lib/core/behaviour/physics.js | lib/core/behaviour/physics.js | /**
* @module Joy.Behaviour
*/
(function(J) {
/**
* TODO: Wouldn't it be nice?
*/
var Physics = J.Behaviour.extend({
INIT: function (options) {},
UPDATE: function () {}
});
J.Behaviour.Physics = Physics;
})(Joy);
| Add Physics placeholder. Planned to be implemented soon. | Add Physics placeholder. Planned to be implemented soon.
| JavaScript | mit | royquintanar/joy.js,endel/joy.js,royquintanar/joy.js | ---
+++
@@ -0,0 +1,14 @@
+/**
+ * @module Joy.Behaviour
+ */
+(function(J) {
+ /**
+ * TODO: Wouldn't it be nice?
+ */
+ var Physics = J.Behaviour.extend({
+ INIT: function (options) {},
+ UPDATE: function () {}
+ });
+
+ J.Behaviour.Physics = Physics;
+})(Joy); | |
6088dceecde8bd76c02bc3860b17e3d4ba932289 | lib/linters/trailing_semicolon.js | lib/linters/trailing_semicolon.js | 'use strict';
module.exports = {
name: 'trailingSemicolon',
nodeTypes: ['rule', 'atrule'],
message: 'All property declarations should end with a semicolon.',
lint: function trailingSemicolonLinter (config, node) {
var others = 0;
if (node.ruleWithoutBody || !node.nodes.length) {
return;
}
if (!node.raws.semicolon) {
node.walk(function (n) {
if (n.type !== 'decl') {
others++;
}
});
/**
* If the node contains child nodes that aren't Declarations,
* then PostCSS will report raws.semicolon: false. in that case
* we should wait until lesshint walks to that Rule/AtRule, and
* let the linter handle that one.
*/
if (others === 0) {
return [{
column: node.source.start.column,
line: node.source.start.line,
message: this.message
}];
}
}
}
};
| 'use strict';
module.exports = {
name: 'trailingSemicolon',
nodeTypes: ['rule', 'atrule'],
message: 'All property declarations should end with a semicolon.',
lint: function trailingSemicolonLinter (config, node) {
var others = 0;
if (node.ruleWithoutBody || (node.nodes && !node.nodes.length)) {
return;
}
if (!node.raws.semicolon) {
node.walk(function (n) {
if (n.type !== 'decl') {
others++;
}
});
/**
* If the node contains child nodes that aren't Declarations,
* then PostCSS will report raws.semicolon: false. in that case
* we should wait until lesshint walks to that Rule/AtRule, and
* let the linter handle that one.
*/
if (others === 0) {
return [{
column: node.source.start.column,
line: node.source.start.line,
message: this.message
}];
}
}
}
};
| Add an extra safety check to trailingSemicolon | Add an extra safety check to trailingSemicolon
| JavaScript | mit | JoshuaKGoldberg/lesshint,runarberg/lesshint,lesshint/lesshint | ---
+++
@@ -8,7 +8,7 @@
lint: function trailingSemicolonLinter (config, node) {
var others = 0;
- if (node.ruleWithoutBody || !node.nodes.length) {
+ if (node.ruleWithoutBody || (node.nodes && !node.nodes.length)) {
return;
}
|
a45f169d1917b5e5275818142a9033cdcdd25766 | rules/application_access_override.js | rules/application_access_override.js | function (user, context, callback) {
// Applications that are restricted
var MOCO_MOFO_APPS = ['phonebook.mozilla.com', 'phonebook-dev.mozilla.com', 'login.mozilla.com', 'passwordreset.mozilla.com'];
// LDAP groups allowed to access these applications
var ALLOWED_GROUPS = ['team_moco', 'team_mofo'];
if (MOCO_MOFO_APPS.indexOf(context.clientName) !== -1) {
var groupHasAccess = ALLOWED_GROUPS.some(
function (group) {
if (!user.groups)
return false;
return user.groups.indexOf(group) >= 0;
});
if (groupHasAccess) {
return callback(null, user, context);
} else {
context.redirect = {
url: "https://sso.mozilla.com"
};
return callback(null, null, context);
}
}
callback(null, user, context);
}
| Add support for auth0-side application access restriction override This fails authentication for specific applications directly from auth0, instead of letting the application decide. Mainly used for applications that do not have proper OIDC or SAML support with authorization management capabilities. | Add support for auth0-side application access restriction override
This fails authentication for specific applications directly from auth0,
instead of letting the application decide. Mainly used for applications
that do not have proper OIDC or SAML support with authorization
management capabilities.
| JavaScript | mpl-2.0 | mozilla-iam/auth0-deploy,mozilla-iam/auth0-deploy,jdow/auth0-deploy,jdow/auth0-deploy,tristanweir/auth0-deploy,tristanweir/auth0-deploy | ---
+++
@@ -0,0 +1,24 @@
+function (user, context, callback) {
+ // Applications that are restricted
+ var MOCO_MOFO_APPS = ['phonebook.mozilla.com', 'phonebook-dev.mozilla.com', 'login.mozilla.com', 'passwordreset.mozilla.com'];
+ // LDAP groups allowed to access these applications
+ var ALLOWED_GROUPS = ['team_moco', 'team_mofo'];
+
+ if (MOCO_MOFO_APPS.indexOf(context.clientName) !== -1) {
+ var groupHasAccess = ALLOWED_GROUPS.some(
+ function (group) {
+ if (!user.groups)
+ return false;
+ return user.groups.indexOf(group) >= 0;
+ });
+ if (groupHasAccess) {
+ return callback(null, user, context);
+ } else {
+ context.redirect = {
+ url: "https://sso.mozilla.com"
+ };
+ return callback(null, null, context);
+ }
+ }
+ callback(null, user, context);
+} | |
efdf64567548a52776c29f432911fce1a78a9bf5 | test/in-view.offset.spec.js | test/in-view.offset.spec.js | import test from 'ava';
import inView from '../src/in-view';
test('inView.offset returns the offset', t => {
t.true(inView.offset(50) === 50);
});
test('inView.offset returns current offset if it doesn\'t receive a number', t => {
t.true(inView.offset(10) === 10);
t.true(inView.offset('foo') === 10);
});
| Add initial tests for inView.offset | Add initial tests for inView.offset
| JavaScript | mit | kudago/in-view,camwiegert/in-view | ---
+++
@@ -0,0 +1,11 @@
+import test from 'ava';
+import inView from '../src/in-view';
+
+test('inView.offset returns the offset', t => {
+ t.true(inView.offset(50) === 50);
+});
+
+test('inView.offset returns current offset if it doesn\'t receive a number', t => {
+ t.true(inView.offset(10) === 10);
+ t.true(inView.offset('foo') === 10);
+}); | |
6d435c7da8a100b1520d0aedbb1974f0f41ee84f | test/test-multiple-batch.js | test/test-multiple-batch.js | // test-multiple-batch.js -- Multiple calls to addBatch()
//
// Copyright 2016 fuzzy.ai <evan@fuzzy.ai>
//
// 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.
/* jshint esversion: 6 */
"use strict";
const fs = require('fs');
const _ = require('lodash');
const debug = require('debug')('perjury:test-multiple-batch');
const vows = require('../lib/index');
const assert = vows.assert;
// benedict
let numberBatch = (num) => {
let batch = {};
batch[`When we return ${num}`] = {
topic() {
return num;
},
'it works': (err, value) => {
assert.ifError(err);
assert.isNumber(value);
assert.equal(value, num);
}
};
return batch;
};
vows
.describe('Multiple addBatch() calls')
.addBatch(numberBatch(4))
.addBatch(numberBatch(8))
.addBatch(numberBatch(15))
.addBatch(numberBatch(16))
.addBatch(numberBatch(23))
.addBatch(numberBatch(42))
.export(module);
| Test for multiple addBatch() calls | Test for multiple addBatch() calls
| JavaScript | apache-2.0 | vowsjs/vows,fuzzy-ai/perjury | ---
+++
@@ -0,0 +1,53 @@
+// test-multiple-batch.js -- Multiple calls to addBatch()
+//
+// Copyright 2016 fuzzy.ai <evan@fuzzy.ai>
+//
+// 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.
+
+/* jshint esversion: 6 */
+
+"use strict";
+
+const fs = require('fs');
+
+const _ = require('lodash');
+const debug = require('debug')('perjury:test-multiple-batch');
+
+const vows = require('../lib/index');
+const assert = vows.assert;
+
+// benedict
+let numberBatch = (num) => {
+ let batch = {};
+ batch[`When we return ${num}`] = {
+ topic() {
+ return num;
+ },
+ 'it works': (err, value) => {
+ assert.ifError(err);
+ assert.isNumber(value);
+ assert.equal(value, num);
+ }
+ };
+ return batch;
+};
+
+vows
+ .describe('Multiple addBatch() calls')
+ .addBatch(numberBatch(4))
+ .addBatch(numberBatch(8))
+ .addBatch(numberBatch(15))
+ .addBatch(numberBatch(16))
+ .addBatch(numberBatch(23))
+ .addBatch(numberBatch(42))
+ .export(module); | |
de3d1a3c4cfbabc50e24c4acad51822daa7476e8 | fakehue/simplebutton.js | fakehue/simplebutton.js | var MeshbluSocketIO = require('meshblu');
var SerialPort = require('serialport');
var tinycolor = require('tinycolor2');
var cfg = require('./meshblu.json');
var serport = null;
var meshblu = null;
SerialPort.list(function (err, ports) {
ports.forEach(function(port) {
if (port.vendorId == '1B4F') {
console.log("Found device on port " + port.comName);
serport = new SerialPort(port.comName, {
baudrate: 9600,
parser: SerialPort.parsers.readline('\n')
});
serport.on('data', function(data) {
handleSerial(data);
});
}
});
});
function handleSerial(data) {
//console.log(data.toString().trim());
if (data.toString().trim() == "BUTTON") {
console.log("Button!");
if (meshblu) {
var state = {"buttonevent": 34, "lastupdated": (new Date()).toISOString()};
var data = {action:"click", button:"1", state:state};
var msg = {devices:['*'], data:data};
meshblu.message(msg);
}
}
}
meshblu = new MeshbluSocketIO(cfg);
meshblu.on('ready', function(){
console.log('Meshblu is ready to rock');
});
meshblu.connect();
meshblu.on('message', function(msg){
console.log('Message in');
console.log(JSON.stringify(msg, null, 2));
if (("data" in msg) && (msg.data) && ("color" in msg.data) && msg.data.color) {
console.log(":" + msg.data.color);
var color;
if (msg.data.color === "OCTOBLU") {
color = msg.data.color;
}
else {
color = tinycolor(msg.data.color).toHexString();
}
if (serport && serport.isOpen()) {
serport.write("COLOR " + color + "\n");
}
}
});
| Add temporary simple LED button | Add temporary simple LED button
| JavaScript | mit | jamesbulpin/meshblu-connector-ledbutton | ---
+++
@@ -0,0 +1,66 @@
+var MeshbluSocketIO = require('meshblu');
+var SerialPort = require('serialport');
+var tinycolor = require('tinycolor2');
+
+var cfg = require('./meshblu.json');
+
+var serport = null;
+var meshblu = null;
+
+SerialPort.list(function (err, ports) {
+ ports.forEach(function(port) {
+ if (port.vendorId == '1B4F') {
+ console.log("Found device on port " + port.comName);
+
+ serport = new SerialPort(port.comName, {
+ baudrate: 9600,
+ parser: SerialPort.parsers.readline('\n')
+ });
+
+ serport.on('data', function(data) {
+ handleSerial(data);
+ });
+ }
+ });
+});
+
+function handleSerial(data) {
+ //console.log(data.toString().trim());
+ if (data.toString().trim() == "BUTTON") {
+ console.log("Button!");
+ if (meshblu) {
+ var state = {"buttonevent": 34, "lastupdated": (new Date()).toISOString()};
+ var data = {action:"click", button:"1", state:state};
+ var msg = {devices:['*'], data:data};
+
+ meshblu.message(msg);
+ }
+ }
+}
+
+meshblu = new MeshbluSocketIO(cfg);
+meshblu.on('ready', function(){
+ console.log('Meshblu is ready to rock');
+});
+meshblu.connect();
+
+
+meshblu.on('message', function(msg){
+ console.log('Message in');
+ console.log(JSON.stringify(msg, null, 2));
+
+ if (("data" in msg) && (msg.data) && ("color" in msg.data) && msg.data.color) {
+ console.log(":" + msg.data.color);
+ var color;
+ if (msg.data.color === "OCTOBLU") {
+ color = msg.data.color;
+ }
+ else {
+ color = tinycolor(msg.data.color).toHexString();
+ }
+ if (serport && serport.isOpen()) {
+ serport.write("COLOR " + color + "\n");
+ }
+ }
+});
+ | |
ba5cb655163ee7e2f646f0716ba3e9125567156b | files/require-css/0.1.8/css.min.js | files/require-css/0.1.8/css.min.js | define(function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/)||0,n=!1,r=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]||t[8]?r=!1:t[4]&&(n=parseInt(t[4])<18);var o={};o.pluginBuilder="./css-builder";var a,i,s,l=function(){a=document.createElement("style"),e.appendChild(a),i=a.styleSheet||a.sheet},u=0,d=[],c=function(e){u++,32==u&&(l(),u=0),i.addImport(e),a.onload=function(){f()}},f=function(){s();var e=d.shift();return e?(s=e[1],void c(e[0])):void(s=null)},h=function(e,t){if(i&&i.addImport||l(),i&&i.addImport)s?d.push([e,t]):(c(e),s=t);else{a.textContent='@import "'+e+'";';var n=setInterval(function(){try{a.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},p=function(t,n){var o=document.createElement("link");if(o.type="text/css",o.rel="stylesheet",r)o.onload=function(){o.onload=function(){},setTimeout(n,7)};else var a=setInterval(function(){for(var e=0;e<document.styleSheets.length;e++){var t=document.styleSheets[e];if(t.href==o.href)return clearInterval(a),n()}},10);o.href=t,e.appendChild(o)};return o.normalize=function(e,t){return".css"==e.substr(e.length-4,4)&&(e=e.substr(0,e.length-4)),t(e)},o.load=function(e,t,r){(n?h:p)(t.toUrl(e+".css"),r)},o}); | Update project require-css to 0.1.8 | Update project require-css to 0.1.8
| JavaScript | mit | fchasen/jsdelivr,RoberMac/jsdelivr,jtblin/jsdelivr,firulais/jsdelivr,labsvisual/jsdelivr,bdukes/jsdelivr,stevelacy/jsdelivr,vousk/jsdelivr,dpellier/jsdelivr,RoberMac/jsdelivr,ajibolam/jsdelivr,anilanar/jsdelivr,cake654326/jsdelivr,yaplas/jsdelivr,dnbard/jsdelivr,wallin/jsdelivr,CTres/jsdelivr,ndamofli/jsdelivr,ajkj/jsdelivr,Heark/jsdelivr,royswastik/jsdelivr,bdukes/jsdelivr,ntd/jsdelivr,ajkj/jsdelivr,AdityaManohar/jsdelivr,l3dlp/jsdelivr,rtenshi/jsdelivr,labsvisual/jsdelivr,therob3000/jsdelivr,Heark/jsdelivr,vebin/jsdelivr,vebin/jsdelivr,vvo/jsdelivr,afghanistanyn/jsdelivr,MichaelSL/jsdelivr,garrypolley/jsdelivr,evilangelmd/jsdelivr,stevelacy/jsdelivr,ManrajGrover/jsdelivr,Swatinem/jsdelivr,bonbon197/jsdelivr,towerz/jsdelivr,Third9/jsdelivr,bonbon197/jsdelivr,rtenshi/jsdelivr,cognitom/jsdelivr,moay/jsdelivr,yaplas/jsdelivr,hubdotcom/jsdelivr,Third9/jsdelivr,MenZil/jsdelivr,oller/jsdelivr,tunnckoCore/jsdelivr,vvo/jsdelivr,cedricbousmanne/jsdelivr,Valve/jsdelivr,therob3000/jsdelivr,cake654326/jsdelivr,leebyron/jsdelivr,garrypolley/jsdelivr,justincy/jsdelivr,Metrakit/jsdelivr,photonstorm/jsdelivr,MenZil/jsdelivr,justincy/jsdelivr,tomByrer/jsdelivr,ajkj/jsdelivr,ajibolam/jsdelivr,justincy/jsdelivr,Swatinem/jsdelivr,vousk/jsdelivr,asimihsan/jsdelivr,dnbard/jsdelivr,fchasen/jsdelivr,moay/jsdelivr,stevelacy/jsdelivr,bonbon197/jsdelivr,spud2451/jsdelivr,ajkj/jsdelivr,AdityaManohar/jsdelivr,Kingside/jsdelivr,yyx990803/jsdelivr,Sneezry/jsdelivr,ajibolam/jsdelivr,walkermatt/jsdelivr,dpellier/jsdelivr,vvo/jsdelivr,cesarmarinhorj/jsdelivr,alexmojaki/jsdelivr,ntd/jsdelivr,photonstorm/jsdelivr,garrypolley/jsdelivr,tunnckoCore/jsdelivr,MenZil/jsdelivr,vebin/jsdelivr,Valve/jsdelivr,yyx990803/jsdelivr,afghanistanyn/jsdelivr,asimihsan/jsdelivr,rtenshi/jsdelivr,Metrakit/jsdelivr,leebyron/jsdelivr,walkermatt/jsdelivr,ManrajGrover/jsdelivr,ajibolam/jsdelivr,wallin/jsdelivr,wallin/jsdelivr,anilanar/jsdelivr,therob3000/jsdelivr,dnbard/jsdelivr,ajkj/jsdelivr,spud2451/jsdelivr,AdityaManohar/jsdelivr,l3dlp/jsdelivr,tomByrer/jsdelivr,Sneezry/jsdelivr,ndamofli/jsdelivr,markcarver/jsdelivr,garrypolley/jsdelivr,jtblin/jsdelivr,siscia/jsdelivr,CTres/jsdelivr,markcarver/jsdelivr,yyx990803/jsdelivr,algolia/jsdelivr,dpellier/jsdelivr,korusdipl/jsdelivr,wallin/jsdelivr,CTres/jsdelivr,siscia/jsdelivr,justincy/jsdelivr,dnbard/jsdelivr,markcarver/jsdelivr,ntd/jsdelivr,megawac/jsdelivr,afghanistanyn/jsdelivr,oller/jsdelivr,justincy/jsdelivr,algolia/jsdelivr,dandv/jsdelivr,stevelacy/jsdelivr,garrypolley/jsdelivr,megawac/jsdelivr,anilanar/jsdelivr,walkermatt/jsdelivr,photonstorm/jsdelivr,siscia/jsdelivr,Sneezry/jsdelivr,gregorypratt/jsdelivr,cesarmarinhorj/jsdelivr,tomByrer/jsdelivr,therob3000/jsdelivr,evilangelmd/jsdelivr,vousk/jsdelivr,dandv/jsdelivr,stevelacy/jsdelivr,cake654326/jsdelivr,l3dlp/jsdelivr,korusdipl/jsdelivr,Sneezry/jsdelivr,petkaantonov/jsdelivr,firulais/jsdelivr,towerz/jsdelivr,fchasen/jsdelivr,dnbard/jsdelivr,labsvisual/jsdelivr,Kingside/jsdelivr,royswastik/jsdelivr,ajibolam/jsdelivr,markcarver/jsdelivr,towerz/jsdelivr,rtenshi/jsdelivr,RoberMac/jsdelivr,vousk/jsdelivr,algolia/jsdelivr,yyx990803/jsdelivr,photonstorm/jsdelivr,ramda/jsdelivr,gregorypratt/jsdelivr,asimihsan/jsdelivr,cesarmarinhorj/jsdelivr,moay/jsdelivr,MenZil/jsdelivr,Heark/jsdelivr,cesarmarinhorj/jsdelivr,cedricbousmanne/jsdelivr,anilanar/jsdelivr,AdityaManohar/jsdelivr,wallin/jsdelivr,Swatinem/jsdelivr,ramda/jsdelivr,algolia/jsdelivr,walkermatt/jsdelivr,Third9/jsdelivr,petkaantonov/jsdelivr,MichaelSL/jsdelivr,hubdotcom/jsdelivr,royswastik/jsdelivr,hubdotcom/jsdelivr,Swatinem/jsdelivr,spud2451/jsdelivr,fchasen/jsdelivr,dandv/jsdelivr,Kingside/jsdelivr,cesarmarinhorj/jsdelivr,walkermatt/jsdelivr,alexmojaki/jsdelivr,tunnckoCore/jsdelivr,alexmojaki/jsdelivr,rtenshi/jsdelivr,megawac/jsdelivr,gregorypratt/jsdelivr,royswastik/jsdelivr,MichaelSL/jsdelivr,dandv/jsdelivr,cedricbousmanne/jsdelivr,yaplas/jsdelivr,MenZil/jsdelivr,spud2451/jsdelivr,cake654326/jsdelivr,oller/jsdelivr,moay/jsdelivr,petkaantonov/jsdelivr,alexmojaki/jsdelivr,vvo/jsdelivr,cognitom/jsdelivr,megawac/jsdelivr,yaplas/jsdelivr,cognitom/jsdelivr,leebyron/jsdelivr,petkaantonov/jsdelivr,anilanar/jsdelivr,RoberMac/jsdelivr,towerz/jsdelivr,bdukes/jsdelivr,leebyron/jsdelivr,cognitom/jsdelivr,ndamofli/jsdelivr,l3dlp/jsdelivr,dandv/jsdelivr,ntd/jsdelivr,leebyron/jsdelivr,ManrajGrover/jsdelivr,CTres/jsdelivr,yaplas/jsdelivr,Third9/jsdelivr,Metrakit/jsdelivr,cognitom/jsdelivr,labsvisual/jsdelivr,royswastik/jsdelivr,firulais/jsdelivr,cake654326/jsdelivr,afghanistanyn/jsdelivr,Kingside/jsdelivr,ManrajGrover/jsdelivr,gregorypratt/jsdelivr,dpellier/jsdelivr,cedricbousmanne/jsdelivr,korusdipl/jsdelivr,ntd/jsdelivr,moay/jsdelivr,Metrakit/jsdelivr,MichaelSL/jsdelivr,siscia/jsdelivr,hubdotcom/jsdelivr,Metrakit/jsdelivr,bonbon197/jsdelivr,Heark/jsdelivr,ManrajGrover/jsdelivr,evilangelmd/jsdelivr,afghanistanyn/jsdelivr,Swatinem/jsdelivr,RoberMac/jsdelivr,hubdotcom/jsdelivr,jtblin/jsdelivr,towerz/jsdelivr,Sneezry/jsdelivr,therob3000/jsdelivr,oller/jsdelivr,bonbon197/jsdelivr,Heark/jsdelivr,l3dlp/jsdelivr,ramda/jsdelivr,evilangelmd/jsdelivr,dpellier/jsdelivr,MichaelSL/jsdelivr,Valve/jsdelivr,tunnckoCore/jsdelivr,tomByrer/jsdelivr,Kingside/jsdelivr,asimihsan/jsdelivr,ndamofli/jsdelivr,firulais/jsdelivr,AdityaManohar/jsdelivr,yyx990803/jsdelivr,korusdipl/jsdelivr,vebin/jsdelivr,korusdipl/jsdelivr,alexmojaki/jsdelivr,oller/jsdelivr,cedricbousmanne/jsdelivr,Third9/jsdelivr,Valve/jsdelivr,ndamofli/jsdelivr,gregorypratt/jsdelivr,ramda/jsdelivr,evilangelmd/jsdelivr,bdukes/jsdelivr,jtblin/jsdelivr,vebin/jsdelivr,firulais/jsdelivr,Valve/jsdelivr,labsvisual/jsdelivr,vvo/jsdelivr,siscia/jsdelivr,vousk/jsdelivr,jtblin/jsdelivr,CTres/jsdelivr,markcarver/jsdelivr,spud2451/jsdelivr,asimihsan/jsdelivr,megawac/jsdelivr,tunnckoCore/jsdelivr,fchasen/jsdelivr | ---
+++
@@ -0,0 +1 @@
+define(function(){if("undefined"==typeof window)return{load:function(e,t,n){n()}};var e=document.getElementsByTagName("head")[0],t=window.navigator.userAgent.match(/Trident\/([^ ;]*)|AppleWebKit\/([^ ;]*)|Opera\/([^ ;]*)|rv\:([^ ;]*)(.*?)Gecko\/([^ ;]*)|MSIE\s([^ ;]*)|AndroidWebKit\/([^ ;]*)/)||0,n=!1,r=!0;t[1]||t[7]?n=parseInt(t[1])<6||parseInt(t[7])<=9:t[2]||t[8]?r=!1:t[4]&&(n=parseInt(t[4])<18);var o={};o.pluginBuilder="./css-builder";var a,i,s,l=function(){a=document.createElement("style"),e.appendChild(a),i=a.styleSheet||a.sheet},u=0,d=[],c=function(e){u++,32==u&&(l(),u=0),i.addImport(e),a.onload=function(){f()}},f=function(){s();var e=d.shift();return e?(s=e[1],void c(e[0])):void(s=null)},h=function(e,t){if(i&&i.addImport||l(),i&&i.addImport)s?d.push([e,t]):(c(e),s=t);else{a.textContent='@import "'+e+'";';var n=setInterval(function(){try{a.sheet.cssRules,clearInterval(n),t()}catch(e){}},10)}},p=function(t,n){var o=document.createElement("link");if(o.type="text/css",o.rel="stylesheet",r)o.onload=function(){o.onload=function(){},setTimeout(n,7)};else var a=setInterval(function(){for(var e=0;e<document.styleSheets.length;e++){var t=document.styleSheets[e];if(t.href==o.href)return clearInterval(a),n()}},10);o.href=t,e.appendChild(o)};return o.normalize=function(e,t){return".css"==e.substr(e.length-4,4)&&(e=e.substr(0,e.length-4)),t(e)},o.load=function(e,t,r){(n?h:p)(t.toUrl(e+".css"),r)},o}); | |
e3f3e344eef2dadf3781a54d0fad7231d7e20ec0 | array/array_merge2.js | array/array_merge2.js | //function to combine two one dimensional arrays to one
function array_merge2(arr1, arr2) {
return arr1.concat(arr2);
}
console.log(array_merge2([1, 2, 3], [4, 5]));
| Create function that merge 2 arrays | chore: Create function that merge 2 arrays
| JavaScript | mit | divyanshu-rawat/Basic-JS-Algorithms | ---
+++
@@ -0,0 +1,8 @@
+//function to combine two one dimensional arrays to one
+
+function array_merge2(arr1, arr2) {
+ return arr1.concat(arr2);
+}
+
+console.log(array_merge2([1, 2, 3], [4, 5]));
+ | |
14f9ee8730d2acfdc74a4963b1e1a8ea3f5ef47e | bin/upload-release.js | bin/upload-release.js | "use strict"
let version = process.argv[2]
let auth = process.argv[3]
if (!auth) {
console.log("Usage: upload-release.js [TAG] [github-user:password]")
process.exit(1)
}
require('child_process').exec("git --no-pager show -s --format='%s' " + version, (error, stdout) => {
if (error) throw error
let message = stdout.split("\n").slice(2)
message = message.slice(0, message.indexOf("-----BEGIN PGP SIGNATURE-----")).join("\n")
let req = require("https").request({
host: "api.github.com",
auth: auth,
headers: {"user-agent": "Release uploader"},
path: "/repos/codemirror/codemirror/releases",
method: "POST"
}, res => {
if (res.statusCode >= 300) {
console.error(res.statusMessage)
res.on("data", d => console.log(d.toString()))
res.on("end", process.exit(1))
}
})
req.write(JSON.stringify({
tag_name: version,
name: version,
body: message
}))
req.end()
})
| Add a github release upload script | Add a github release upload script
| JavaScript | mit | dperetti/CodeMirror,bfrohs/CodeMirror,xeronith/CodeMirror,codio/CodeMirror,hackmdio/CodeMirror,alur/CodeMirror,Jisuanke/CodeMirror,SidPresse/CodeMirror,vincentwoo/CodeMirror,wingify/CodeMirror,pabloferz/CodeMirror,MarcelGerber/CodeMirror,INTELOGIE/CodeMirror,alur/CodeMirror,dperetti/CodeMirror,jayaprabhakar/CodeMirror,hackmdio/CodeMirror,alur/CodeMirror,INTELOGIE/CodeMirror,Dominator008/CodeMirror,nightwing/CodeMirror,schanzer/CodeMirror,jayaprabhakar/CodeMirror,codio/CodeMirror,grzegorzmazur/CodeMirror,namin/CodeMirror,MarcelGerber/CodeMirror,crazy4chrissi/CodeMirror,INTELOGIE/CodeMirror,wingify/CodeMirror,notepadqq/CodeMirror,codio/CodeMirror,Jisuanke/CodeMirror,jkaplon/CodeMirror,notepadqq/CodeMirror,crazy4chrissi/CodeMirror,mizchi/CodeMirror,schanzer/CodeMirror,jkaplon/CodeMirror,kerabromsmu/CodeMirror,SidPresse/CodeMirror,pabloferz/CodeMirror,adobe/CodeMirror2,bfrohs/CodeMirror,crazy4chrissi/CodeMirror,mtaran-google/CodeMirror,sourcelair/CodeMirror,dperetti/CodeMirror,TDaglis/CodeMirror,grzegorzmazur/CodeMirror,vincentwoo/CodeMirror,thomasjm/CodeMirror,kerabromsmu/CodeMirror,namin/CodeMirror,thomasjm/CodeMirror,jayaprabhakar/CodeMirror,ficristo/CodeMirror,mtaran-google/CodeMirror,notepadqq/CodeMirror,mizchi/CodeMirror,hackmdio/CodeMirror,nightwing/CodeMirror,Dominator008/CodeMirror,thomasjm/CodeMirror,namin/CodeMirror,ficristo/CodeMirror,rrandom/CodeMirror,TDaglis/CodeMirror,adobe/CodeMirror2,Jisuanke/CodeMirror,ejgallego/CodeMirror,sourcelair/CodeMirror,MarcelGerber/CodeMirror,Dominator008/CodeMirror,SidPresse/CodeMirror,TDaglis/CodeMirror,nightwing/CodeMirror,xeronith/CodeMirror,sourcelair/CodeMirror,vincentwoo/CodeMirror,schanzer/CodeMirror,adobe/CodeMirror2,bfrohs/CodeMirror,grzegorzmazur/CodeMirror,kerabromsmu/CodeMirror,jkaplon/CodeMirror,ejgallego/CodeMirror,wingify/CodeMirror,mizchi/CodeMirror,rrandom/CodeMirror,ficristo/CodeMirror,mtaran-google/CodeMirror,rrandom/CodeMirror,ejgallego/CodeMirror,pabloferz/CodeMirror,xeronith/CodeMirror | ---
+++
@@ -0,0 +1,35 @@
+"use strict"
+
+let version = process.argv[2]
+let auth = process.argv[3]
+
+if (!auth) {
+ console.log("Usage: upload-release.js [TAG] [github-user:password]")
+ process.exit(1)
+}
+
+require('child_process').exec("git --no-pager show -s --format='%s' " + version, (error, stdout) => {
+ if (error) throw error
+ let message = stdout.split("\n").slice(2)
+ message = message.slice(0, message.indexOf("-----BEGIN PGP SIGNATURE-----")).join("\n")
+
+ let req = require("https").request({
+ host: "api.github.com",
+ auth: auth,
+ headers: {"user-agent": "Release uploader"},
+ path: "/repos/codemirror/codemirror/releases",
+ method: "POST"
+ }, res => {
+ if (res.statusCode >= 300) {
+ console.error(res.statusMessage)
+ res.on("data", d => console.log(d.toString()))
+ res.on("end", process.exit(1))
+ }
+ })
+ req.write(JSON.stringify({
+ tag_name: version,
+ name: version,
+ body: message
+ }))
+ req.end()
+}) | |
4bbc2eefe6a89f38a5cf2b21a757acc86047b010 | lib/youtube-track.js | lib/youtube-track.js | var ytdl = require('ytdl-core');
module.exports = YoutubeTrack = function(vid, cb) {
var _this = this;
var requestUrl = 'http://www.youtube.com/watch?v=' + vid;
ytdl.getInfo(requestUrl, (err, info) => {
if (err) cb(err, undefined);
else {
_this.vid = info.vid;
_this.title = info.title;
_this.author = info.author;
_this.viewCount = info.viewCount;
_this.lengthSeconds = info.lengthSeconds;
_this.containedVideo = info;
cb(_this);
}
});
};
| Add YoutubeTrack class to represent a youtube track For future soundcloud support. | Add YoutubeTrack class to represent a youtube track
For future soundcloud support.
| JavaScript | mit | meew0/Lethe | ---
+++
@@ -0,0 +1,18 @@
+var ytdl = require('ytdl-core');
+
+module.exports = YoutubeTrack = function(vid, cb) {
+ var _this = this;
+ var requestUrl = 'http://www.youtube.com/watch?v=' + vid;
+ ytdl.getInfo(requestUrl, (err, info) => {
+ if (err) cb(err, undefined);
+ else {
+ _this.vid = info.vid;
+ _this.title = info.title;
+ _this.author = info.author;
+ _this.viewCount = info.viewCount;
+ _this.lengthSeconds = info.lengthSeconds;
+ _this.containedVideo = info;
+ cb(_this);
+ }
+ });
+}; | |
d9350a3749a7d33a425c3f5f499984ff52c8690b | src/exports/assets.js | src/exports/assets.js | import {
Asset,
BondBase,
BondCorporate,
BondGovernment,
BondMortgage,
Currency,
CustomAsset,
Derivative,
BondOption,
CFD,
Equity,
ForeignExchangeOption,
Fund,
ExchangeTradedFund,
ForeignExchange,
NonDeliverableForward,
Index,
BondFuture,
BondFutureOption,
EnergyFuture,
EquityFuture,
Future,
FutureOption,
IndexFuture,
InterestRateFuture,
ListedContractForDifference,
ListedDerivative,
RealAsset,
RealEstate,
Wine,
Sukuk,
Synthetic,
SyntheticFromBook,
SyntheticMultiLeg
} from '../assets'
import {
retrieve,
insert,
amend,
partialAmend,
deactivate
} from '../utils/assets'
export {
Asset,
BondBase,
BondCorporate,
BondGovernment,
BondMortgage,
Currency,
CustomAsset,
Derivative,
BondOption,
CFD,
Equity,
ForeignExchangeOption,
Fund,
ExchangeTradedFund,
ForeignExchange,
NonDeliverableForward,
Index,
BondFuture,
BondFutureOption,
EnergyFuture,
EquityFuture,
Future,
FutureOption,
IndexFuture,
InterestRateFuture,
ListedContractForDifference,
ListedDerivative,
RealAsset,
RealEstate,
Wine,
Sukuk,
Synthetic,
SyntheticFromBook,
SyntheticMultiLeg,
retrieve,
insert,
amend,
partialAmend,
deactivate
}
| Create exports folder for namespacing imports/exports. | Create exports folder for namespacing imports/exports.
| JavaScript | apache-2.0 | amaas-fintech/amaas-core-sdk-js | ---
+++
@@ -0,0 +1,86 @@
+import {
+ Asset,
+ BondBase,
+ BondCorporate,
+ BondGovernment,
+ BondMortgage,
+ Currency,
+ CustomAsset,
+ Derivative,
+ BondOption,
+ CFD,
+ Equity,
+ ForeignExchangeOption,
+ Fund,
+ ExchangeTradedFund,
+ ForeignExchange,
+ NonDeliverableForward,
+ Index,
+ BondFuture,
+ BondFutureOption,
+ EnergyFuture,
+ EquityFuture,
+ Future,
+ FutureOption,
+ IndexFuture,
+ InterestRateFuture,
+ ListedContractForDifference,
+ ListedDerivative,
+ RealAsset,
+ RealEstate,
+ Wine,
+ Sukuk,
+ Synthetic,
+ SyntheticFromBook,
+ SyntheticMultiLeg
+} from '../assets'
+
+import {
+ retrieve,
+ insert,
+ amend,
+ partialAmend,
+ deactivate
+} from '../utils/assets'
+
+export {
+ Asset,
+ BondBase,
+ BondCorporate,
+ BondGovernment,
+ BondMortgage,
+ Currency,
+ CustomAsset,
+ Derivative,
+ BondOption,
+ CFD,
+ Equity,
+ ForeignExchangeOption,
+ Fund,
+ ExchangeTradedFund,
+ ForeignExchange,
+ NonDeliverableForward,
+ Index,
+ BondFuture,
+ BondFutureOption,
+ EnergyFuture,
+ EquityFuture,
+ Future,
+ FutureOption,
+ IndexFuture,
+ InterestRateFuture,
+ ListedContractForDifference,
+ ListedDerivative,
+ RealAsset,
+ RealEstate,
+ Wine,
+ Sukuk,
+ Synthetic,
+ SyntheticFromBook,
+ SyntheticMultiLeg,
+ retrieve,
+ insert,
+ amend,
+ partialAmend,
+ deactivate
+} | |
dce6f6ba0af831253b4351dd99735b3a28692335 | test/components/Scrollbar/Scrollbar.spec.js | test/components/Scrollbar/Scrollbar.spec.js | import React from 'react';
import { mount } from 'enzyme';
import Scrollbar from '../../../src/components/Scrollbar/Scrollbar';
describe('<Scrollbar />', function () {
beforeEach(function () {
this.update = sinon.spy();
});
describe('when mounted', function () {
it('add scrollbar using the Highcharts update method', function () {
mount(<Scrollbar update={this.update} />);
expect(this.update).to.have.been.calledWith({
scrollbar: {
enabled: true,
update: this.update
}
});
});
it('updates the scrollbar with the passed props', function () {
mount(
<Scrollbar barBackgroundColor="red" height={20} update={this.update} />
);
expect(this.update).to.have.been.calledWith({
scrollbar: {
enabled: true,
barBackgroundColor: 'red',
height: 20,
update: this.update
}
});
});
});
describe('update', function () {
it('should use the update method when props change', function () {
const wrapper = mount(
<Scrollbar update={this.update} />
);
wrapper.setProps({ height: 12345 });
expect(this.update).to.have.been.calledWith({
scrollbar: {
height: 12345
}
});
});
});
describe('when unmounted', function () {
it('should disable the Scrollbar', function () {
const wrapper = mount(<Scrollbar update={this.update} />);
wrapper.unmount();
expect(this.update).to.have.been.calledWith({
scrollbar: {
enabled: false
}
})
});
});
});
| Add tests for the Scrollbar component | Add tests for the Scrollbar component
| JavaScript | mit | whawker/react-jsx-highcharts,AlexMayants/react-jsx-highcharts,whawker/react-jsx-highcharts,AlexMayants/react-jsx-highcharts | ---
+++
@@ -0,0 +1,61 @@
+import React from 'react';
+import { mount } from 'enzyme';
+import Scrollbar from '../../../src/components/Scrollbar/Scrollbar';
+
+describe('<Scrollbar />', function () {
+ beforeEach(function () {
+ this.update = sinon.spy();
+ });
+
+ describe('when mounted', function () {
+ it('add scrollbar using the Highcharts update method', function () {
+ mount(<Scrollbar update={this.update} />);
+ expect(this.update).to.have.been.calledWith({
+ scrollbar: {
+ enabled: true,
+ update: this.update
+ }
+ });
+ });
+
+ it('updates the scrollbar with the passed props', function () {
+ mount(
+ <Scrollbar barBackgroundColor="red" height={20} update={this.update} />
+ );
+ expect(this.update).to.have.been.calledWith({
+ scrollbar: {
+ enabled: true,
+ barBackgroundColor: 'red',
+ height: 20,
+ update: this.update
+ }
+ });
+ });
+ });
+
+ describe('update', function () {
+ it('should use the update method when props change', function () {
+ const wrapper = mount(
+ <Scrollbar update={this.update} />
+ );
+ wrapper.setProps({ height: 12345 });
+ expect(this.update).to.have.been.calledWith({
+ scrollbar: {
+ height: 12345
+ }
+ });
+ });
+ });
+
+ describe('when unmounted', function () {
+ it('should disable the Scrollbar', function () {
+ const wrapper = mount(<Scrollbar update={this.update} />);
+ wrapper.unmount();
+ expect(this.update).to.have.been.calledWith({
+ scrollbar: {
+ enabled: false
+ }
+ })
+ });
+ });
+}); | |
b26d9ab3b9a031f52e8a1f40a20f3da625e561ba | js/i18n/zh-cn.js | js/i18n/zh-cn.js | plupload.addI18n({"Stop Upload":"停止上传","Upload URL might be wrong or doesn't exist.":"上传的URL可能是错误的或不存在。","tb":"tb","Size":"大小","Close":"关闭","Init error.":"初始化错误。","Add files to the upload queue and click the start button.":"将文件添加到上传队列,然后点击”开始上传“按钮。","Filename":"文件名","Image format either wrong or not supported.":"图片格式错误或者不支持。","Status":"状态","HTTP Error.":"HTTP 错误。","Start Upload":"开始上传","mb":"mb","kb":"kb","Duplicate file error.":"重复文件错误。","File size error.":"文件大小错误。","N/A":"N/A","gb":"gb","Error: Invalid file extension:":"错误:无效的文件扩展名:","Select files":"选择文件","%s already present in the queue.":"%s 已经在当前队列里。","File: %s":"文件: %s","b":"b","Uploaded %d/%d files":"已上传 %d/%d 个文件","Upload element accepts only %d file(s) at a time. Extra files were stripped.":"只允许同时上传 %d 个文件,多余的文件已被取消。","%d files queued":"%d 个文件加入到队列","File: %s, size: %d, max file size: %d":"文件: %s, 大小: %d, 最大文件大小: %d","Drag files here.":"把文件拖到这里。","Runtime ran out of available memory.":"运行时已消耗所有可用内存。","File count error.":"文件数量错误。","File extension error.":"文件扩展名错误。","Error: File too large:":"错误: 文件太大:","Add Files":"增加文件"});
| Add language pack for Simplified Chinese. | Add language pack for Simplified Chinese.
| JavaScript | agpl-3.0 | envato/plupload,vitr/fend005-plupload,moxiecode/plupload,envato/plupload,vitr/fend005-plupload,moxiecode/plupload | ---
+++
@@ -0,0 +1 @@
+plupload.addI18n({"Stop Upload":"停止上传","Upload URL might be wrong or doesn't exist.":"上传的URL可能是错误的或不存在。","tb":"tb","Size":"大小","Close":"关闭","Init error.":"初始化错误。","Add files to the upload queue and click the start button.":"将文件添加到上传队列,然后点击”开始上传“按钮。","Filename":"文件名","Image format either wrong or not supported.":"图片格式错误或者不支持。","Status":"状态","HTTP Error.":"HTTP 错误。","Start Upload":"开始上传","mb":"mb","kb":"kb","Duplicate file error.":"重复文件错误。","File size error.":"文件大小错误。","N/A":"N/A","gb":"gb","Error: Invalid file extension:":"错误:无效的文件扩展名:","Select files":"选择文件","%s already present in the queue.":"%s 已经在当前队列里。","File: %s":"文件: %s","b":"b","Uploaded %d/%d files":"已上传 %d/%d 个文件","Upload element accepts only %d file(s) at a time. Extra files were stripped.":"只允许同时上传 %d 个文件,多余的文件已被取消。","%d files queued":"%d 个文件加入到队列","File: %s, size: %d, max file size: %d":"文件: %s, 大小: %d, 最大文件大小: %d","Drag files here.":"把文件拖到这里。","Runtime ran out of available memory.":"运行时已消耗所有可用内存。","File count error.":"文件数量错误。","File extension error.":"文件扩展名错误。","Error: File too large:":"错误: 文件太大:","Add Files":"增加文件"}); | |
f6b2e366048308c44de85eb573417d9d12472974 | src/Problems/PairsWithDifferenceK.js | src/Problems/PairsWithDifferenceK.js | const test = require('tape')
/**
* Given an array arr of distinct integers and a nonnegative integer k,
* write a function that returns an array of all pairs [x,y],
* such that x - y = k. If no such pairs exist, return an empty array.
*
* Examples:
*
* input = [0, -1, -2, 2, 1], k = 1
* output: [[0, -1], [-1, -2], [2, 1], [1, 0]]
*
* input = [1, 7, 5, 3, 32, 17, 12], k = 17
* output: []
*
* @param {Array} input
* @param {Number} k
* @returns {Array}
*/
function findPairsWithDistance(input, k) {
input.sort((a, b) => a - b)
const result = []
let first = 0
let last = 1
while (first < input.length && last < input.length) {
if (input[last] === input[first] + k) {
result.push([input[last], input[first]])
first++
last++
} else if (input[last] < input[first] + k) {
last++
} else {
first++
}
}
return result
}
test('Test Case #1', assert => {
assert.deepEqual(findPairsWithDistance([4, 1], 3), [[4, 1]])
assert.end()
})
test('Test Case #2', assert => {
assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 4), [[5, 1], [11, 7]])
assert.end()
})
test('Test Case #3', assert => {
assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 6), [[7, 1], [11, 5]])
assert.end()
})
test('Test Case #4', assert => {
assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 10), [[11, 1]])
assert.end()
})
test('Test Case #5', assert => {
assert.deepEqual(findPairsWithDistance([0, -1, -2, 2, 1], 1), [
[-1, -2],
[0, -1],
[1, 0],
[2, 1]
])
assert.end()
})
test('Test Case #6', assert => {
assert.deepEqual(findPairsWithDistance([1, 7, 5, 3, 32, 17, 12], 17), [])
assert.end()
})
| Add pairs with given difference | Add pairs with given difference
| JavaScript | mit | ayastreb/cs101 | ---
+++
@@ -0,0 +1,74 @@
+const test = require('tape')
+
+/**
+ * Given an array arr of distinct integers and a nonnegative integer k,
+ * write a function that returns an array of all pairs [x,y],
+ * such that x - y = k. If no such pairs exist, return an empty array.
+ *
+ * Examples:
+ *
+ * input = [0, -1, -2, 2, 1], k = 1
+ * output: [[0, -1], [-1, -2], [2, 1], [1, 0]]
+ *
+ * input = [1, 7, 5, 3, 32, 17, 12], k = 17
+ * output: []
+ *
+ * @param {Array} input
+ * @param {Number} k
+ * @returns {Array}
+ */
+function findPairsWithDistance(input, k) {
+ input.sort((a, b) => a - b)
+
+ const result = []
+ let first = 0
+ let last = 1
+ while (first < input.length && last < input.length) {
+ if (input[last] === input[first] + k) {
+ result.push([input[last], input[first]])
+ first++
+ last++
+ } else if (input[last] < input[first] + k) {
+ last++
+ } else {
+ first++
+ }
+ }
+
+ return result
+}
+
+test('Test Case #1', assert => {
+ assert.deepEqual(findPairsWithDistance([4, 1], 3), [[4, 1]])
+ assert.end()
+})
+
+test('Test Case #2', assert => {
+ assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 4), [[5, 1], [11, 7]])
+ assert.end()
+})
+
+test('Test Case #3', assert => {
+ assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 6), [[7, 1], [11, 5]])
+ assert.end()
+})
+
+test('Test Case #4', assert => {
+ assert.deepEqual(findPairsWithDistance([1, 5, 11, 7], 10), [[11, 1]])
+ assert.end()
+})
+
+test('Test Case #5', assert => {
+ assert.deepEqual(findPairsWithDistance([0, -1, -2, 2, 1], 1), [
+ [-1, -2],
+ [0, -1],
+ [1, 0],
+ [2, 1]
+ ])
+ assert.end()
+})
+
+test('Test Case #6', assert => {
+ assert.deepEqual(findPairsWithDistance([1, 7, 5, 3, 32, 17, 12], 17), [])
+ assert.end()
+}) | |
f5b2b81e1b87583f54ecc6b3578e072205566875 | popular_posts.js | popular_posts.js | var superagent = require('superagent');
var _ = require('lodash');
var fs = require('fs');
var path = require('path');
var frontMatter = require('front-matter');
var postsPath = path.join(__dirname, 'pages/posts');
var postFiles = fs.readdirSync(postsPath);
var posts = _.map(postFiles, function(file) {
var filePath = path.join(postsPath, file);
var contents = fs.readFileSync(filePath).toString();
var metadata = frontMatter(contents);
return {
path: filePath,
contents: contents,
body: metadata.body,
data: metadata.attributes
};
});
var lookup = Object.create(null);
_.forEach(posts, function(post) {
lookup[post.data.path] = post;
});
superagent
.get('https://piwik.sinap.ps/index.php')
.query({
module: 'API',
method: 'Actions.getPageUrls',
format: 'JSON',
idSite: 3,
period: 'range',
date: '2013-1-1,2016-01-21',
expanded: 1,
token_auth: '8c3e249277ac43852917552b63335dba',
filter_limit: 100
})
.end(function(err, res) {
if (err) {
throw err;
}
if (res.status !== 200) {
throw new Error('non-200 response! ' + res.text);
}
_.forEach(res.body, function(entry) {
var url = '/' + entry.label + '/';
var hits = entry.nb_hits;
if (url === '/how-not-to-do-customer-service-credit-card-edition/') {
return;
}
var target = lookup[url];
if (!target) {
return;
}
console.log('updating', target.path, ' with ' + hits);
var contents = target.contents;
var existingHits = /^hits: [0-9]+$/m;
var newHits = /^[^-]*---/;
if (existingHits.test(contents)) {
contents = contents.replace(existingHits, 'hits: ' + hits);
}
else {
contents = contents.replace(newHits, '---\nhits: ' + hits);
}
fs.writeFileSync(target.path, contents);
});
});
| Add script to pull piwik data, inject into posts | Add script to pull piwik data, inject into posts | JavaScript | mit | scottnonnenberg/blog,scottnonnenberg/blog,scottnonnenberg/blog | ---
+++
@@ -0,0 +1,77 @@
+var superagent = require('superagent');
+var _ = require('lodash');
+var fs = require('fs');
+var path = require('path');
+var frontMatter = require('front-matter');
+
+var postsPath = path.join(__dirname, 'pages/posts');
+
+var postFiles = fs.readdirSync(postsPath);
+var posts = _.map(postFiles, function(file) {
+ var filePath = path.join(postsPath, file);
+ var contents = fs.readFileSync(filePath).toString();
+ var metadata = frontMatter(contents);
+ return {
+ path: filePath,
+ contents: contents,
+ body: metadata.body,
+ data: metadata.attributes
+ };
+});
+
+var lookup = Object.create(null);
+_.forEach(posts, function(post) {
+ lookup[post.data.path] = post;
+});
+
+superagent
+ .get('https://piwik.sinap.ps/index.php')
+ .query({
+ module: 'API',
+ method: 'Actions.getPageUrls',
+ format: 'JSON',
+ idSite: 3,
+ period: 'range',
+ date: '2013-1-1,2016-01-21',
+ expanded: 1,
+ token_auth: '8c3e249277ac43852917552b63335dba',
+ filter_limit: 100
+ })
+ .end(function(err, res) {
+ if (err) {
+ throw err;
+ }
+ if (res.status !== 200) {
+ throw new Error('non-200 response! ' + res.text);
+ }
+
+ _.forEach(res.body, function(entry) {
+ var url = '/' + entry.label + '/';
+ var hits = entry.nb_hits;
+
+ if (url === '/how-not-to-do-customer-service-credit-card-edition/') {
+ return;
+ }
+
+ var target = lookup[url];
+ if (!target) {
+ return;
+ }
+
+ console.log('updating', target.path, ' with ' + hits);
+
+ var contents = target.contents;
+ var existingHits = /^hits: [0-9]+$/m;
+ var newHits = /^[^-]*---/;
+
+ if (existingHits.test(contents)) {
+ contents = contents.replace(existingHits, 'hits: ' + hits);
+ }
+ else {
+ contents = contents.replace(newHits, '---\nhits: ' + hits);
+ }
+
+ fs.writeFileSync(target.path, contents);
+ });
+ });
+ | |
001cacd3ddc41e01f230da17562d1c51835f7cb8 | app/assets/javascripts/new_timeslot.js | app/assets/javascripts/new_timeslot.js | $(document).ready(function(){
$("#new-timeslot-form").submit(function(event){
event.preventDefault();
var data = createDate();
$("#modal_new_timeslot").modal('toggle');
$.ajax({
type: "POST",
url: "/api/timeslots",
data: { start: data }
}).done(function(response) {
swal({
title: "Great!",
text: "You have set up a tutoring availability!",
confirmButtonColor: "#66BB6A",
type: "success"
});
$('#tutor-cal').fullCalendar( 'refetchEvents' );
}).fail(function(response) {
swal({
title: "Oops...",
text: "Something went wrong!",
confirmButtonColor: "#EF5350",
type: "error"
});
});
})
})
var createDate = function() {
var date = $('.timepicker').val();
var time = $('.datepicker').val();
var dateTime = date + " " + time;
return (new Date(dateTime));
} | Create new timeslot with ajax call | Create new timeslot with ajax call
| JavaScript | mit | theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board | ---
+++
@@ -0,0 +1,36 @@
+$(document).ready(function(){
+
+ $("#new-timeslot-form").submit(function(event){
+ event.preventDefault();
+ var data = createDate();
+ $("#modal_new_timeslot").modal('toggle');
+ $.ajax({
+ type: "POST",
+ url: "/api/timeslots",
+ data: { start: data }
+ }).done(function(response) {
+ swal({
+ title: "Great!",
+ text: "You have set up a tutoring availability!",
+ confirmButtonColor: "#66BB6A",
+ type: "success"
+ });
+ $('#tutor-cal').fullCalendar( 'refetchEvents' );
+ }).fail(function(response) {
+ swal({
+ title: "Oops...",
+ text: "Something went wrong!",
+ confirmButtonColor: "#EF5350",
+ type: "error"
+ });
+ });
+ })
+
+})
+
+var createDate = function() {
+ var date = $('.timepicker').val();
+ var time = $('.datepicker').val();
+ var dateTime = date + " " + time;
+ return (new Date(dateTime));
+} | |
1d0b3c7cb45be76fe7002a6f428373606e24e192 | Resources/public/js/tests/fieldTest.js | Resources/public/js/tests/fieldTest.js | describe('Test the field component', function() {
/**
* Get the textarea component
*/
function getFieldComponent(field) {
var editorAdvancedFieldComponent = Vue.extend(editorAdvancedField);
var store = new Vuex.Store({
state: {
configuration: {
configured_types_tags: [
'defaultTag1',
'-defaultTag2',
'+defaultTag3'
]
},
formProperties: {
value: ''
},
configuredTypes: [
{
name: 'my_email',
tags: 'my_email_tag',
icon: 'envelope',
description: 'Email input field',
form_type: 'email',
form_type_name: 'email',
extra_form_options: {
label: {
extra_form_type: 'text',
options: {
required: false,
data: 'ouais le mien'
}
},
extra_form_constraints: {}
}
}
]
},
getters: extraFormEditorGetters
});
return new editorAdvancedFieldComponent({
store: store,
propsData: {
index: 1,
field: field
}
}).$mount();
}
it('Should initialize tags correctly', function() {
var vm = getFieldComponent({
tags: 'francois,nicolas,macron'
});
expect(vm.tags).toEqual('francois,nicolas,macron');
var vm = getFieldComponent({
name: 'my_email',
tags: 'the_good_tag'
});
expect(vm.tags).toEqual('the_good_tag');
var vm = getFieldComponent({
name: 'my_email',
});
expect(vm.tags).toEqual('my_email_tag');
var vm = getFieldComponent({
name: 'un_unknow_field'
});
expect(vm.tags).toEqual('defaultTag1,+defaultTag3');
});
});
| Add field component tests on tags. | Add field component tests on tags.
| JavaScript | mit | IDCI-Consulting/ExtraFormBundle,IDCI-Consulting/ExtraFormBundle | ---
+++
@@ -0,0 +1,82 @@
+describe('Test the field component', function() {
+
+ /**
+ * Get the textarea component
+ */
+ function getFieldComponent(field) {
+ var editorAdvancedFieldComponent = Vue.extend(editorAdvancedField);
+
+ var store = new Vuex.Store({
+ state: {
+ configuration: {
+ configured_types_tags: [
+ 'defaultTag1',
+ '-defaultTag2',
+ '+defaultTag3'
+ ]
+ },
+ formProperties: {
+ value: ''
+ },
+ configuredTypes: [
+ {
+ name: 'my_email',
+ tags: 'my_email_tag',
+ icon: 'envelope',
+ description: 'Email input field',
+ form_type: 'email',
+ form_type_name: 'email',
+ extra_form_options: {
+ label: {
+ extra_form_type: 'text',
+ options: {
+ required: false,
+ data: 'ouais le mien'
+ }
+ },
+ extra_form_constraints: {}
+ }
+ }
+ ]
+ },
+ getters: extraFormEditorGetters
+ });
+
+ return new editorAdvancedFieldComponent({
+ store: store,
+ propsData: {
+ index: 1,
+ field: field
+ }
+
+ }).$mount();
+ }
+
+ it('Should initialize tags correctly', function() {
+ var vm = getFieldComponent({
+ tags: 'francois,nicolas,macron'
+ });
+
+ expect(vm.tags).toEqual('francois,nicolas,macron');
+
+ var vm = getFieldComponent({
+ name: 'my_email',
+ tags: 'the_good_tag'
+ });
+
+ expect(vm.tags).toEqual('the_good_tag');
+
+ var vm = getFieldComponent({
+ name: 'my_email',
+ });
+
+ expect(vm.tags).toEqual('my_email_tag');
+
+ var vm = getFieldComponent({
+ name: 'un_unknow_field'
+ });
+
+ expect(vm.tags).toEqual('defaultTag1,+defaultTag3');
+ });
+
+}); | |
821ff82302228712ce5eea057b5437074cd722c1 | test/client/modules/videos/mark_as_favourite_spec.js | test/client/modules/videos/mark_as_favourite_spec.js | var expect = chai.expect;
describe('markAsFavouriteService', function () {
// console.log(angular.module('APP'))
var $httpBackend;
// var APP;
var video = {
_id: '123'
}
var apiUrl = '/api/v1/videos/' + video._id + '/mark_favourite';
beforeEach(module('APP'));
beforeEach(inject(function ($injector) {
$httpBackend = $injector.get("$httpBackend");
$httpBackend.when("POST", apiUrl)
.respond(200, {value:"goodValue"});
}));
afterEach(function () {
$httpBackend.verifyNoOutstandingExpectation();
$httpBackend.verifyNoOutstandingRequest();
});
// beforeEach(angular.mock.module('APP'));
// beforeEach(function () {APP = angular.module('APP')});
// beforeEach(inject(function (service, _$httpBackend_) {
// service = MyService;
// $httpBackend = _$httpBackend_;
// }));
it('should have a markAsFavouriteService', function() {
//expect(APP.markAsFavouriteService).not.to.equal(null);
});
it('calls http', inject(['markAsFavouriteService', function (serv) {
$httpBackend.expectPOST(apiUrl);
serv(video, true);
$httpBackend.flush();
}]));
it('marks the video as favourite on success', inject(['markAsFavouriteService', function (serv) {
// console.log(serv);
// console.log('running');
// var pro = serv(video, true);
// console.log('promise', pro);
// console.log(pro.success);
// pro.success(function (response) {
// console.log('response back')
// expect(video.favourite).to.equal(true);
// $httpBackend.flush();
// });
}]));
it('doesnt mark the video as favourite on success', inject(['markAsFavouriteService', function (serv) {
}]));
it('notifies the user on error', inject(['markAsFavouriteService', function (serv) {
}]));
}); | Test for mark as fav | Test for mark as fav
| JavaScript | mit | sporto/devtalks.net | ---
+++
@@ -0,0 +1,66 @@
+var expect = chai.expect;
+
+describe('markAsFavouriteService', function () {
+
+ // console.log(angular.module('APP'))
+ var $httpBackend;
+
+ // var APP;
+ var video = {
+ _id: '123'
+ }
+
+ var apiUrl = '/api/v1/videos/' + video._id + '/mark_favourite';
+
+ beforeEach(module('APP'));
+
+ beforeEach(inject(function ($injector) {
+ $httpBackend = $injector.get("$httpBackend");
+ $httpBackend.when("POST", apiUrl)
+ .respond(200, {value:"goodValue"});
+ }));
+
+ afterEach(function () {
+ $httpBackend.verifyNoOutstandingExpectation();
+ $httpBackend.verifyNoOutstandingRequest();
+ });
+
+ // beforeEach(angular.mock.module('APP'));
+ // beforeEach(function () {APP = angular.module('APP')});
+ // beforeEach(inject(function (service, _$httpBackend_) {
+ // service = MyService;
+ // $httpBackend = _$httpBackend_;
+ // }));
+
+ it('should have a markAsFavouriteService', function() {
+ //expect(APP.markAsFavouriteService).not.to.equal(null);
+ });
+
+ it('calls http', inject(['markAsFavouriteService', function (serv) {
+ $httpBackend.expectPOST(apiUrl);
+ serv(video, true);
+ $httpBackend.flush();
+ }]));
+
+ it('marks the video as favourite on success', inject(['markAsFavouriteService', function (serv) {
+ // console.log(serv);
+ // console.log('running');
+ // var pro = serv(video, true);
+ // console.log('promise', pro);
+ // console.log(pro.success);
+
+ // pro.success(function (response) {
+ // console.log('response back')
+ // expect(video.favourite).to.equal(true);
+ // $httpBackend.flush();
+ // });
+ }]));
+
+ it('doesnt mark the video as favourite on success', inject(['markAsFavouriteService', function (serv) {
+
+ }]));
+
+ it('notifies the user on error', inject(['markAsFavouriteService', function (serv) {
+
+ }]));
+}); | |
f4a490fcbe4d751a6ef64c4e5a0ffe4c4919bea4 | assets/js/pages/lessees/reservations.js | assets/js/pages/lessees/reservations.js | $(document).ready(function() {
$('#reservation-table').DataTable({});
});
$('.btn-cancel').on('click', function() {
if (confirm('Are you sure to cancel this reservation?')) {
console.log('cancelled');
}
});
$('.btn-view').on('click', function() {
$('reservation-modal').modal('show');
}); | Add script for lessee reservation list | Add script for lessee reservation list
| JavaScript | mit | gctomakin/renTRMNL,gctomakin/renTRMNL,gctomakin/renTRMNL | ---
+++
@@ -0,0 +1,13 @@
+$(document).ready(function() {
+ $('#reservation-table').DataTable({});
+});
+
+$('.btn-cancel').on('click', function() {
+ if (confirm('Are you sure to cancel this reservation?')) {
+ console.log('cancelled');
+ }
+});
+
+$('.btn-view').on('click', function() {
+ $('reservation-modal').modal('show');
+}); | |
33b7b330687c4daa4e04ffe1e4d0e23b942673c6 | client/components/SignUp/SignUpPage.js | client/components/SignUp/SignUpPage.js | import React, { Component } from 'react';
import logo from '../../public/images/logo.png';
import PageFooter from '../PageFooter';
import SignUpForm from './SignUpForm';
import { connect } from 'react-redux';
class SignUpPage extends Component {
constructor(props) {
super(props);
this.renderSignUpMessage = this.renderSignUpMessage.bind(this);
}
renderSignUpMessage(){
let signUpMessage = '';
if (this.props.isSigningUp){
signUpMessage = 'Signing you up...';
}
if (this.props.hasErrored) {
signUpMessage = `Sign up failed. ${ this.props.error }`;
}
if (this.props.user) {
signUpMessage = 'Sign up successful';
}
return signUpMessage;
}
render() {
return (
<div className="grey lighten-4">
<div className="row">
<div className="col s3 "></div>
<div className="col s6">
<div className="row card-panel">
<div className="row">
<div className="center-align">
<img src={logo} alt="logo" className="form-logo" />
</div>
</div>
<div className="row">
<div className = "row center-align">
<span className = {this.props.hasErrored ? "signUpError" : "signUpSuccess" } >
{ this.renderSignUpMessage() }
</span>
</div>
<SignUpForm />
</div>
</div>
</div>
<div className="col s3"></div>
</div>
<PageFooter />
</div>
)
}
}
const mapStateToProps = (state) => {
return {
error: state.auth.error,
isSigningUp: state.auth.isSigningUp,
hasErrored: state.auth.hasErrored,
user: state.auth.user,
}
}
export default connect(mapStateToProps)(SignUpPage);
| Create container for SignUpForm component | Create container for SignUpForm component
| JavaScript | mit | amarachukwu-agbo/hello-books,amarachukwu-agbo/hello-books | ---
+++
@@ -0,0 +1,69 @@
+import React, { Component } from 'react';
+import logo from '../../public/images/logo.png';
+import PageFooter from '../PageFooter';
+import SignUpForm from './SignUpForm';
+import { connect } from 'react-redux';
+
+
+
+class SignUpPage extends Component {
+ constructor(props) {
+ super(props);
+ this.renderSignUpMessage = this.renderSignUpMessage.bind(this);
+ }
+ renderSignUpMessage(){
+ let signUpMessage = '';
+ if (this.props.isSigningUp){
+ signUpMessage = 'Signing you up...';
+ }
+ if (this.props.hasErrored) {
+ signUpMessage = `Sign up failed. ${ this.props.error }`;
+ }
+ if (this.props.user) {
+ signUpMessage = 'Sign up successful';
+ }
+ return signUpMessage;
+ }
+
+ render() {
+ return (
+ <div className="grey lighten-4">
+ <div className="row">
+ <div className="col s3 "></div>
+ <div className="col s6">
+ <div className="row card-panel">
+ <div className="row">
+ <div className="center-align">
+ <img src={logo} alt="logo" className="form-logo" />
+ </div>
+ </div>
+ <div className="row">
+ <div className = "row center-align">
+ <span className = {this.props.hasErrored ? "signUpError" : "signUpSuccess" } >
+ { this.renderSignUpMessage() }
+ </span>
+ </div>
+ <SignUpForm />
+ </div>
+ </div>
+ </div>
+ <div className="col s3"></div>
+ </div>
+ <PageFooter />
+ </div>
+ )
+ }
+
+}
+
+const mapStateToProps = (state) => {
+ return {
+ error: state.auth.error,
+ isSigningUp: state.auth.isSigningUp,
+ hasErrored: state.auth.hasErrored,
+ user: state.auth.user,
+ }
+}
+
+export default connect(mapStateToProps)(SignUpPage);
+ | |
1e7390448d7cd39522d122205e917f61438e7ba4 | promise-it-wont-hurt/reject-a-promise.js | promise-it-wont-hurt/reject-a-promise.js | var q = require('q');
var deferred = q.defer();
deferred.promise.then(null, function(err) {
console.log(err.message);
});
setTimeout(deferred.reject, 300, new Error("REJECTED!"));
| Complete 'Reject a promise' challenge in 'Promise it won't hurt' tutorial | Complete 'Reject a promise' challenge in 'Promise it won't hurt' tutorial
| JavaScript | mit | PaoloLaurenti/nodeschool | ---
+++
@@ -0,0 +1,7 @@
+var q = require('q');
+var deferred = q.defer();
+deferred.promise.then(null, function(err) {
+ console.log(err.message);
+});
+
+setTimeout(deferred.reject, 300, new Error("REJECTED!")); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.