commit
stringlengths 40
40
| old_file
stringlengths 4
236
| new_file
stringlengths 4
236
| old_contents
stringlengths 1
3.26k
| new_contents
stringlengths 16
4.43k
| subject
stringlengths 16
624
| message
stringlengths 17
3.29k
| lang
stringclasses 5
values | license
stringclasses 13
values | repos
stringlengths 5
91.5k
|
|---|---|---|---|---|---|---|---|---|---|
7af9ca83021937683ab538c355b1e6a1a2c8cd8d
|
src/renderer/scr.state.js
|
src/renderer/scr.state.js
|
var STATE = (function(){
var FILE;
var MSGS;
var selectedChannel;
return {
uploadFile: function(file){
FILE = file;
MSGS = null;
},
getChannelList: function(){
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({ // reserve.txt
id: key,
name: channels[key].name,
server: FILE.getServer(channels[key].server),
msgcount: FILE.getMessageCount(key)
}));
},
getChannelName: function(channel){
return FILE.getChannelById(channel).name;
},
getUserName: function(user){
return FILE.getUserById(user).name;
},
selectChannel: function(channel){
selectedChannel = channel;
MSGS = Object.keys(FILE.getMessages(channel)).sort();
},
getMessageList: function(startIndex, count){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => {
var message = messages[key];
return { // reserve.txt
user: FILE.getUser(message.u),
timestamp: message.t,
contents: message.m
};
});
},
getMessageCount: function(){
return MSGS ? MSGS.length : 0;
}
};
})();
|
var STATE = (function(){
var FILE;
var MSGS;
var selectedChannel;
return {
uploadFile: function(file){
FILE = file;
MSGS = null;
},
getChannelList: function(){
var channels = FILE.getChannels();
return Object.keys(channels).map(key => ({ // reserve.txt
id: key,
name: channels[key].name,
server: FILE.getServer(channels[key].server),
msgcount: FILE.getMessageCount(key)
}));
},
getChannelName: function(channel){
return FILE.getChannelById(channel).name;
},
getUserName: function(user){
return FILE.getUserById(user).name;
},
selectChannel: function(channel){
selectedChannel = channel;
MSGS = Object.keys(FILE.getMessages(channel)).sort((key1, key2) => {
if (key1.length === key2.length){
return key1 > key2 ? 1 : key1 < key2 ? -1 : 0;
}
else{
return key1.length > key2.length ? 1 : -1;
}
});
},
getMessageList: function(startIndex, count){
if (!MSGS){
return [];
}
var messages = FILE.getMessages(selectedChannel);
return MSGS.slice(startIndex, !count ? undefined : startIndex+count).map(key => {
var message = messages[key];
return { // reserve.txt
user: FILE.getUser(message.u),
timestamp: message.t,
contents: message.m
};
});
},
getMessageCount: function(){
return MSGS ? MSGS.length : 0;
}
};
})();
|
Fix message sorting in renderer having issues with varying message key lengths
|
Fix message sorting in renderer having issues with varying message key lengths
|
JavaScript
|
mit
|
chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker,chylex/Discord-History-Tracker
|
f9de0a7b6535fe2a3129db0a886f6f9cae8d2930
|
tools/tests/dynamic-import.js
|
tools/tests/dynamic-import.js
|
var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("dynamic import(...) in development", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-devel", "dynamic-import");
s.cd("dynamic-import-test-app-devel", run.bind(s, false));
});
selftest.define("dynamic import(...) in production", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-prod", "dynamic-import");
s.cd("dynamic-import-test-app-prod", run.bind(s, true));
});
function run(prod) {
const sandbox = this;
const args = [
"test",
"--once",
"--full-app",
"--driver-package", "dispatch:mocha-phantomjs"
];
if (prod) {
args.push("--production");
}
const run = sandbox.run(...args);
run.waitSecs(60);
run.match("App running at");
run.match("SERVER FAILURES: 0");
run.match("CLIENT FAILURES: 0");
run.expectExit(0);
}
|
var selftest = require('../tool-testing/selftest.js');
var Sandbox = selftest.Sandbox;
selftest.define("dynamic import(...) in development", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-devel", "dynamic-import");
s.cd("dynamic-import-test-app-devel", run.bind(s, false));
});
selftest.define("dynamic import(...) in production", function () {
const s = new Sandbox();
s.createApp("dynamic-import-test-app-prod", "dynamic-import");
s.cd("dynamic-import-test-app-prod", run.bind(s, true));
});
function run(isProduction) {
const sandbox = this;
const args = [
"test",
"--once",
"--full-app",
"--driver-package", "dispatch:mocha-phantomjs"
];
if (isProduction) {
sandbox.set("NODE_ENV", "production");
args.push("--production");
} else {
sandbox.set("NODE_ENV", "development");
}
const run = sandbox.run(...args);
run.waitSecs(60);
run.match("App running at");
run.match("SERVER FAILURES: 0");
run.match("CLIENT FAILURES: 0");
run.expectExit(0);
}
|
Use NODE_ENV (with --production) to run production import(...) tests.
|
Use NODE_ENV (with --production) to run production import(...) tests.
|
JavaScript
|
mit
|
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
|
ceb264e849abfddfb250de15c78b78007287d83e
|
gulp/tasks/uploading.js
|
gulp/tasks/uploading.js
|
'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
progress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
|
'use strict';
const fs = require('fs');
const gulp = require('gulp');
const rsync = require('gulp-rsync');
// 'gulp deploy' -- reads rsync credentials file and incrementally uploads site to server
gulp.task('upload', () => {
var credentials = JSON.parse(fs.readFileSync('rsync-credentials.json', 'utf8'));
return gulp.src('dist')
.pipe(rsync({
// dryrun: true
root: 'dist/',
hostname: credentials.hostname,
username: credentials.username,
destination: credentials.destination,
incremental: true,
recursive: true,
compress: true,
clean: true,
chmod: "Du=rwx,Dgo=rx,Fu=rw,Fgo=r",
}));
});
|
Disable duplicate Rsync progress output
|
Disable duplicate Rsync progress output
|
JavaScript
|
mit
|
blogtips/blogtips.github.io,mmistakes/made-mistakes-jekyll,mmistakes/made-mistakes-jekyll,blogtips/blogtips.github.io,mmistakes/made-mistakes-jekyll,blogtips/blogtips.github.io
|
f157ca1c747d48ba416ec2896d2153c25ce2a8a8
|
app/components/liquid-child.js
|
app/components/liquid-child.js
|
import Ember from "ember";
export default Ember.Component.extend({
classNames: ['liquid-child'],
attributeBindings: ['style'],
style: Ember.computed('visible', function() {
return new Ember.Handlebars.SafeString(this.get('visible') ? '' : 'visibility:hidden');
}),
tellContainerWeRendered: Ember.on('didInsertElement', function(){
this.sendAction('didRender', this);
})
});
|
import Ember from "ember";
export default Ember.Component.extend({
classNames: ['liquid-child'],
updateElementVisibility: function() {
let visible = this.get('visible');
let $container = this.$();
if ($container && $container.length) {
$container.css('visibility', visible ? 'visible' : 'hidden');
}
}.on('willInsertElement').observes('visible'),
tellContainerWeRendered: Ember.on('didInsertElement', function(){
this.sendAction('didRender', this);
})
});
|
Switch inline style attribute binding to jQuery CSS DOM Manip for CSP
|
Switch inline style attribute binding to jQuery CSS DOM Manip for CSP
|
JavaScript
|
mit
|
ember-animation/liquid-fire-core,byelipk/liquid-fire,davewasmer/liquid-fire,ianstarz/liquid-fire,envoy/liquid-fire,csantero/liquid-fire,ember-animation/liquid-fire-velocity,ember-animation/ember-animated,jamesreggio/liquid-fire,ember-animation/liquid-fire-velocity,jayphelps/liquid-fire,acorncom/liquid-fire,chadhietala/liquid-fire,monegraph/liquid-fire,acorncom/liquid-fire,knownasilya/liquid-fire,jrjohnson/liquid-fire,runspired/liquid-fire,ember-animation/liquid-fire-core,dsokolowski/liquid-fire,twokul/liquid-fire,ember-animation/ember-animated,monegraph/liquid-fire,mikegrassotti/liquid-fire,gordonbisnor/liquid-fire,topaxi/liquid-fire,ianstarz/liquid-fire,davidgoli/liquid-fire,ember-animation/liquid-fire,gordonbisnor/liquid-fire,twokul/liquid-fire,chadhietala/liquid-fire,givanse/liquid-fire,dsokolowski/liquid-fire,davidgoli/liquid-fire,jamesreggio/liquid-fire,jayphelps/liquid-fire,jrjohnson/liquid-fire,knownasilya/liquid-fire,topaxi/liquid-fire,givanse/liquid-fire,mikegrassotti/liquid-fire,ember-animation/ember-animated,ef4/liquid-fire,byelipk/liquid-fire,davewasmer/liquid-fire,ember-animation/liquid-fire,runspired/liquid-fire,ef4/liquid-fire,csantero/liquid-fire
|
717722bb2a343c00fa00980fcee67717279b6264
|
bids-validator/validators/tsv/tsvParser.js
|
bids-validator/validators/tsv/tsvParser.js
|
/*
* TSV
* Module for parsing TSV (and eventually other formats)
*/
const trimSplit = separator => str => str.trim().split(separator)
const isContentfulRow = row => row && !/^\s*$/.test(row)
function parseTSV(contents) {
const content = {
headers: [],
rows: [],
}
content.rows = trimSplit('\n')(contents)
.filter(isContentfulRow)
.map(trimSplit('\t'))
content.headers = content.rows.length ? content.rows[0] : []
return content
}
export default parseTSV
|
/*
* TSV
* Module for parsing TSV (and eventually other formats)
*/
const normalizeEOL = str => str.replace('\r\n', '\n').replace('\r', '\n')
const isContentfulRow = row => row && !/^\s*$/.test(row)
function parseTSV(contents) {
const content = {
headers: [],
rows: [],
}
content.rows = normalizeEOL(contents)
.split('\n')
.filter(isContentfulRow)
.map(str => str.split('\t'))
content.headers = content.rows.length ? content.rows[0] : []
return content
}
export default parseTSV
|
Normalize TSV end-of-line without stripping all whitespace
|
FIX: Normalize TSV end-of-line without stripping all whitespace
(cherry picked from commit 786cfbb5847f5508720416cc7846fa1fcadc36bc)
|
JavaScript
|
mit
|
nellh/bids-validator,nellh/bids-validator,Squishymedia/BIDS-Validator,Squishymedia/bids-validator,nellh/bids-validator
|
7027fa2118cf7efc9dea127b68266b4aa2c6adf7
|
app/js/controllers/homepage.js
|
app/js/controllers/homepage.js
|
'use strict';
angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
[ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) {
$scope[type] = droitsDescription[type];
$scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) {
return total + Object.keys(droitsDescription[type][provider].prestations).length;
}, 0);
});
ABTestingService.setABTestingEnvironment();
var referrer = document.referrer;
if (referrer.match(/ameli\.fr/)) {
$state.go('ameli');
} else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) {
$state.go('hameconnage');
} else {
$timeout(function() {
document.querySelector('#valueProposition a').focus();
}, 1500);
}
});
|
'use strict';
angular.module('ddsApp').controller('HomepageCtrl', function($scope, $state, $sessionStorage, droitsDescription, $timeout, ABTestingService, phishingExpressions) {
[ 'prestationsNationales', 'partenairesLocaux' ].forEach(function(type) {
$scope[type] = droitsDescription[type];
$scope[type + 'Count'] = Object.keys(droitsDescription[type]).reduce(function(total, provider) {
return total + Object.keys(droitsDescription[type][provider].prestations).length;
}, 0);
});
ABTestingService.setABTestingEnvironment();
var referrer = document.referrer;
if (referrer.match(/ameli\.fr/)) {
$state.go('ameli');
} else if (_.some(phishingExpressions, function(phishingExpression) { return referrer.match(phishingExpression); })) {
if (! $sessionStorage.phishingNoticationDone) {
$sessionStorage.phishingNoticationDone = true;
$state.go('hameconnage');
}
} else {
$timeout(function() {
document.querySelector('#valueProposition a').focus();
}, 1500);
}
});
|
Allow users from phishing website to continue
|
Allow users from phishing website to continue
|
JavaScript
|
agpl-3.0
|
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
|
0b41586db6bf65a9357093c5a447ea12fab4c4ff
|
app/client/templates/modals/user_profile_edit/user_profile_edit.js
|
app/client/templates/modals/user_profile_edit/user_profile_edit.js
|
/*****************************************************************************/
/* UserProfileEdit: Event Handlers */
/*****************************************************************************/
Template.UserProfileEdit.events({
'click #confirm': function(event) {
event.preventDefault();
var newUsername = $('#new-username').val();
var newFirstName = $('#new-firstname').val();
var newLastname = $('#new-lastname').val();
var newEmail = $('#new-email').val();
var newBio = $('#new-bio').val();
var newPassword = $('#new-password').val();
// Validate username, e-mail and password
// Save new data
if (newFirstName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.firstName": newFirstName
}
});
}
}
});
/*****************************************************************************/
/* UserProfileEdit: Helpers */
/*****************************************************************************/
Template.UserProfileEdit.helpers({
data: function() {
return this;
}
});
/*****************************************************************************/
/* UserProfileEdit: Lifecycle Hooks */
/*****************************************************************************/
Template.UserProfileEdit.onCreated(function() {});
Template.UserProfileEdit.onRendered(function() {});
Template.UserProfileEdit.onDestroyed(function() {});
|
/*****************************************************************************/
/* UserProfileEdit: Event Handlers */
/*****************************************************************************/
Template.UserProfileEdit.events({
'click #confirm': function(event) {
event.preventDefault();
var newUsername = $('#new-username').val();
var newFirstName = $('#new-firstname').val();
var newLastname = $('#new-lastname').val();
var newEmail = $('#new-email').val();
var newBio = $('#new-bio').val();
var newPassword = $('#new-password').val();
// Validate username, e-mail and password
// Save new data
if (newFirstName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.firstName": newFirstName
}
});
}
if (newLastName) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.lastName": newLastName
}
});
}
if (newBio) {
Meteor.users.update({
_id: Meteor.userId()
}, {
$set: {
"profile.bio": newBio
}
});
}
}
});
/*****************************************************************************/
/* UserProfileEdit: Helpers */
/*****************************************************************************/
Template.UserProfileEdit.helpers({
data: function() {
return this;
}
});
/*****************************************************************************/
/* UserProfileEdit: Lifecycle Hooks */
/*****************************************************************************/
Template.UserProfileEdit.onCreated(function() {});
Template.UserProfileEdit.onRendered(function() {});
Template.UserProfileEdit.onDestroyed(function() {});
|
Improve user edit modal, now it saves the last name and bio
|
Improve user edit modal, now it saves the last name and bio
|
JavaScript
|
agpl-3.0
|
openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign,openp2pdesign/OpenMetaDesign
|
809b449002671226018fbd2e9d3285e6e7037ea0
|
server/index.js
|
server/index.js
|
'use strict';
var http = require('http'),
spotify = require('spotify-node-applescript');
var cb = function(request, response) {
debugger;
response.writeHead(200, {'Content-Type': 'text/html'});
response.write('Hello spotkula servereerer!');
response.end();
};
http.createServer(cb).listen(3000, 'localhost');
|
'use strict';
var http = require('http'),
spotify = require('spotify-node-applescript'),
express = require('express');
var app = express();
app.get('/', function (request, response) {
response.send('ok');
});
app.listen(3000);
console.log("Listening on port 3000");
|
Reimplement basic server as express app
|
Reimplement basic server as express app
|
JavaScript
|
mit
|
ilkka/spotkula-server
|
2a26cba118a63f53321f9285351fa8a1a9ad9484
|
lib/assets/test/spec/new-dashboard/unit/specs/core/metrics.spec.js
|
lib/assets/test/spec/new-dashboard/unit/specs/core/metrics.spec.js
|
import * as Metrics from 'new-dashboard/core/metrics';
import store from 'new-dashboard/store';
describe('Internal Metrics Tracker', () => {
describe('sendMetric', () => {
beforeEach(() => {
global.fetch = jest.fn();
});
it('should return call fetch with proper parameters', () => {
const eventName = 'fake_event';
const eventProperties = { page: 'dashboard' };
const baseURL = 'https://user.carto.com';
store.state.config.base_url = baseURL;
Metrics.sendMetric(eventName, eventProperties);
const requestURL = `${baseURL}/api/v3/metrics`;
const requestProperties = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: eventName,
properties: eventProperties
})
};
expect(global.fetch).toHaveBeenCalledWith(
requestURL,
requestProperties
);
});
});
});
|
import * as Metrics from 'new-dashboard/core/metrics';
import store from 'new-dashboard/store';
describe('Internal Metrics Tracker', () => {
describe('sendMetric', () => {
let previousState;
beforeEach(() => {
global.fetch = jest.fn();
previousState = {
...store.state,
config: { ...store.state.config },
user: { ...store.state.user }
};
});
afterEach(() => {
store.replaceState(previousState);
});
it('should return call fetch with proper parameters', () => {
const eventName = 'fake_event';
const eventProperties = { page: 'dashboard', user_id: 'fake_id' };
const baseURL = 'https://user.carto.com';
store.state.config.base_url = baseURL;
store.state.user = { id: 'fake_id' };
Metrics.sendMetric(eventName, eventProperties);
const requestURL = `${baseURL}/api/v3/metrics`;
const requestProperties = {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
name: eventName,
properties: eventProperties
})
};
expect(global.fetch).toHaveBeenCalledWith(
requestURL,
requestProperties
);
});
});
});
|
Add base url and user id to metrics test
|
Add base url and user id to metrics test
|
JavaScript
|
bsd-3-clause
|
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
|
11cec30a94f134f7442867bbbb33fc3490e6a2d2
|
src/Section/StatisticsSection/StatisticsSection.js
|
src/Section/StatisticsSection/StatisticsSection.js
|
import React from 'react'
import PieChart from '../../Charts/PieChart/PieChart'
import BarChart from '../../Charts/BarChart/BarChart'
import Percent from '../../Statistics/Percent/Percent'
const StatisticsSection = ({metrics}) => {
return (
<div className="ui equal width center aligned stackable grid">
<div className="eight wide column">
<Percent metrics={metrics} label="openness" icon="users" description="Percentage of open source data." />
</div>
<div className="eight wide column">
<Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." />
</div>
<div className="eight wide column">
<PieChart data={metrics.partitions.recordType} />
</div>
<div className="eight wide column">
<BarChart data={metrics.partitions.dataType} />
</div>
</div>
)
}
export default StatisticsSection
|
import React from 'react'
import PieChart from '../../Charts/PieChart/PieChart'
import BarChart from '../../Charts/BarChart/BarChart'
import Percent from '../../Statistics/Percent/Percent'
const StatisticsSection = ({metrics}) => {
return (
<div className="ui equal width center aligned stackable grid">
<div className="eight wide column">
<Percent metrics={metrics} label="openness" icon="unlock alternate icon" description="Percentage of open source data." />
</div>
<div className="eight wide column">
<Percent metrics={metrics} label="download" icon="download" description="Percentage of successfully downloaded data." />
</div>
<div className="eight wide column">
<PieChart data={metrics.partitions.recordType} />
</div>
<div className="eight wide column">
<BarChart data={metrics.partitions.dataType} />
</div>
</div>
)
}
export default StatisticsSection
|
Change openness users icon by unlock icon
|
Change openness users icon by unlock icon
|
JavaScript
|
mit
|
sgmap/inspire,sgmap/inspire
|
6aae6d6b876c88327ce8ef31dbf3dec8eb60d3a4
|
src/Data/Ord.js
|
src/Data/Ord.js
|
"use strict";
// module Data.Ord
exports.ordArrayImpl = function (f) {
return function (xs) {
return function (ys) {
var i = 0;
var xlen = xs.length;
var ylen = ys.length;
while (i < xlen && i < ylen) {
var x = xs[i];
var y = ys[i];
var o = f(x)(y);
if (o !== 0) {
return o;
}
i++;
}
if (xlen === ylen) {
return 0;
} else if (xlen > ylen) {
return -1;
} else {
return 1;
}
};
};
};
exports.unsafeCompareImpl = function (lt) {
return function (eq) {
return function (gt) {
return function (x) {
return function (y) {
return x < y ? lt : x > y ? gt : eq;
};
};
};
};
};
|
"use strict";
// module Data.Ord
exports.ordArrayImpl = function (f) {
return function (xs) {
return function (ys) {
var i = 0;
var xlen = xs.length;
var ylen = ys.length;
while (i < xlen && i < ylen) {
var x = xs[i];
var y = ys[i];
var o = f(x)(y);
if (o !== 0) {
return o;
}
i++;
}
if (xlen === ylen) {
return 0;
} else if (xlen > ylen) {
return -1;
} else {
return 1;
}
};
};
};
|
Remove unused (moved) FFI function
|
Remove unused (moved) FFI function
|
JavaScript
|
bsd-3-clause
|
purescript/purescript-prelude,hdgarrood/purescript-prelude
|
361524e620348e32061165c02290f04a305cfa76
|
draft-js-dnd-plugin/src/blockRendererFn.js
|
draft-js-dnd-plugin/src/blockRendererFn.js
|
import {Entity} from 'draft-js';
export default (config) => (contentBlock, getEditorState, updateEditorState) => {
const type = contentBlock.getType();
if (type === 'image') {
const entityKey = contentBlock.getEntityAt(0);
const data = entityKey ? Entity.get(entityKey).data : {};
return {
component: config.Image,
props: {
...data
}
};
}
return undefined;
};
|
import {Entity} from 'draft-js';
import removeBlock from './modifiers/removeBlock';
export default (config) => (contentBlock, getEditorState, updateEditorState) => {
const type = contentBlock.getType();
if (type === 'image') {
const entityKey = contentBlock.getEntityAt(0);
const data = entityKey ? Entity.get(entityKey).data : {};
return {
component: config.Image,
props: {
...data,
remove: ()=>updateEditorState(removeBlock(getEditorState(), contentBlock.key))
}
};
}
return undefined;
};
|
Allow Image block to access remove method
|
Allow Image block to access remove method
|
JavaScript
|
mit
|
dagopert/draft-js-plugins,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor,dagopert/draft-js-plugins,dagopert/draft-js-plugins,draft-js-plugins/draft-js-plugins-v1,nikgraf/draft-js-plugin-editor,draft-js-plugins/draft-js-plugins-v1,draft-js-plugins/draft-js-plugins,koaninc/draft-js-plugins,koaninc/draft-js-plugins,draft-js-plugins/draft-js-plugins,draft-js-plugins/draft-js-plugins,nikgraf/draft-js-plugin-editor
|
e176f4ed812d0d91646ba62838e1769548b81f39
|
example/src/redux/reducer/storage.js
|
example/src/redux/reducer/storage.js
|
import { types } from './storage.actions';
const initialState = {
file: null,
url: null,
};
export default function storageReducer(state=initialState, action={}) {
switch (action.type) {
case types.SET_FILE:
return {
...state,
file: action.file,
}
case types.SET_FILE_URL:
return {
...state,
url: action.url,
}
default:
return state;
}
}
|
import { types } from './storage.actions';
const initialState = {
file: null,
loading: false,
url: null,
};
export default function storageReducer(state=initialState, action={}) {
switch (action.type) {
case types.SET_FILE:
return {
...state,
file: action.file,
}
case types.SET_FILE_URL:
return {
...state,
loading: false,
url: action.url,
}
case types.SEND_FILE:
return {
...state,
loading: true,
};
default:
return state;
}
}
|
Store file upload loading state.
|
Store file upload loading state.
|
JavaScript
|
mit
|
n6g7/redux-saga-firebase
|
336d92edc418ef85c88390b3e33896ca73284c81
|
computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js
|
computer-science/01-introduction-to-cs-and-programming-mit/src/02-lecture.js
|
// Modules
var prompt = require( 'prompt' );
// // Create a variable x and assign value 3 to it
// var x = 3;
// // Bind x to value 9
// x *= x; // or x = x * x;
// console.log( x );
// read input data from terminal
prompt.start();
prompt.get({
name : 'number',
description : 'Enter a number'
}, function( err, results ) {
console.log( results.number );
});
// // Verify if a integer number is even or odd.
// // If odd, verify if the number is divisible by 3
// // read input data from terminal
// process.stdin.resume();
// console.log( 'Enter a integer:' );
// process.stdin.setEncoding( 'utf8' );
// process.stdin.on( 'data', function( input ) {
// var int = parseInt( input, 10 );
// if ( int % 2 === 0 ) {
// console.log( 'Even' );
// } else {
// console.log( 'Odd' );
// if ( int % 3 !== 0 ) {
// console.log( 'And not divisible by 3' );
// }
// }
// process.exit();
// });
// // Find the lowest of three numbers
|
// Modules
var prompt = require( 'prompt' );
// // Create a variable x and assign value 3 to it
// var x = 3;
// // Bind x to value 9
// x *= x; // or x = x * x;
// console.log( x );
// // read input data from terminal
// prompt.start();
// prompt.get({
// name : 'number',
// description : 'Enter a number'
// }, function( err, results ) {
// console.log( results.number );
// });
// Verify if a integer number is even or odd.
// If odd, verify if the number is divisible by 3
// read input data from terminal
prompt.start();
prompt.get([
{
name : 'number',
description : 'Enter a integer'
}
], function( err, results ) {
var int = parseInt( results.number, 10 );
if ( int % 2 === 0 ) {
console.log( int + ' is EVEN' );
} else {
var msg = int.toString() + ' is ODD';
if ( int % 3 !== 0 ) {
msg += ' and NOT divisible by 3';
}
console.log( msg );
}
});
// // Find the lowest of three numbers
|
Verify if a integer number is even or odd - refactor
|
Verify if a integer number is even or odd - refactor
|
JavaScript
|
mit
|
waterlooSunset/computer-science-and-engineering
|
7358e642ffbea4ce3d2dd54da8b26068cd3d0f4d
|
rules/es2017.js
|
rules/es2017.js
|
module.exports = {
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
rules: {
'arrow-body-style': ['error', 'as-needed', {
requireReturnForObjectLiteral: false,
}],
'arrow-spacing': ['error', { before: true, after: true }],
'no-const-assign': 'error',
'no-duplicate-imports': 'error',
'no-new-symbol': 'error',
'no-this-before-super': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {
ignoreConstructors: false,
avoidQuotes: true,
}],
'prefer-arrow-callback': ['error', {
allowNamedFunctions: false,
allowUnboundThis: true,
}],
'prefer-const': ['error', {
destructuring: 'any',
ignoreReadBeforeAssign: true,
}],
'prefer-rest-params': 'error',
// babel inserts `'use strict';` for us
'strict': ['error', 'never']
}
};
|
module.exports = {
parserOptions: {
ecmaVersion: 2017,
sourceType: 'module',
ecmaFeatures: {
experimentalObjectRestSpread: true
}
},
rules: {
'arrow-spacing': ['error', { before: true, after: true }],
'no-const-assign': 'error',
'no-duplicate-imports': 'error',
'no-new-symbol': 'error',
'no-this-before-super': 'error',
'no-var': 'error',
'object-shorthand': ['error', 'always', {
ignoreConstructors: false,
avoidQuotes: true,
}],
'prefer-arrow-callback': ['error', {
allowNamedFunctions: false,
allowUnboundThis: true,
}],
'prefer-const': ['error', {
destructuring: 'any',
ignoreReadBeforeAssign: true,
}],
'prefer-rest-params': 'error',
// babel inserts `'use strict';` for us
'strict': ['error', 'never']
}
};
|
Remove arrow-body-style. Is too confusing
|
Remove arrow-body-style. Is too confusing
|
JavaScript
|
mit
|
sevenval/eslint-config-sevenval
|
b702adaf1fae5e798db51d36b1919254f387f031
|
js/eventPage.js
|
js/eventPage.js
|
function runAlarm() {
chrome.tabs.create({
url: "http://example.com"
});
}
chrome.alarms.onAlarm.addListener(function(alarm) {
console.log(alarm);
chrome.tabs.query({}, function(tabs) {
if (tabs.length === 0) {
chrome.storage.local.set({
"missed": 1
});
} else {
runAlarm();
}
})
});
chrome.windows.onCreated.addListener(function(window) {
chrome.storage.local.get("missed", function(r) {
if (r.missed === 1) {
chrome.storage.local.set({
"missed": 0
});
runAlarm();
}
});
});
|
function runAlarm() {
chrome.tabs.create({
url: "http://example.com"
});
}
chrome.alarms.onAlarm.addListener(function(alarm) {
console.log(alarm);
chrome.tabs.query({}, function(tabs) {
if (tabs.length === 0) {
chrome.storage.local.set({
"missed": 1
});
} else {
runAlarm();
}
});
});
chrome.windows.onCreated.addListener(function(window) {
chrome.storage.local.get("missed", function(r) {
if (r.missed === 1) {
chrome.storage.local.set({
"missed": 0
});
runAlarm();
}
});
});
chrome.runtime.onInstalled.addListener(function(details) {
chrome.storage.local.get("enabled", function(r) {
if (r.enabled === undefined) {
chrome.storage.local.set({
"sites": [],
"time": "08:00",
"enabled": false,
"missed": 0
});
}
});
});
|
Create default settings upon first installation
|
Create default settings upon first installation
|
JavaScript
|
mit
|
adrianhuna/tabscheduler
|
44da4e0035a0a72346b72c696aee73c23096275f
|
tests/testWithCallBack.js
|
tests/testWithCallBack.js
|
const request = require('request')
function getLuke(cb) {
const lukeInfo = {
name: 'Luke',
}
request('https://swapi.co/api/people/1', (error, response, body) => {
if (error) return cb(error)
const data = JSON.parse(body)
const startShipURL = data.starships[0]
const vehicleURL = data.vehicles[0]
request(startShipURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, starship_class } = JSON.parse(body)
lukeInfo.startShip = { name, model, type: starship_class}
request(vehicleURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, vehicle_class } = JSON.parse(body)
lukeInfo.vehicle = { name, model, type: vehicle_class}
cb(null, lukeInfo) // <== Pass null in error and result as second arg
})
})
})
}
describe('Example with Callbacks (Callback Hell)', () => {
it('should get Luke details', (done) => {
getLuke((error, info) => {
if (error) return done(error)
console.log(info)
done()
});
})
})
|
const request = require('request')
function getLuke(cb) {
const lukeInfo = {
name: 'Luke',
}
/* Here stars the callback hell. Please notice the if (error) return cb(error) redundant code */
request('https://swapi.co/api/people/1', (error, response, body) => {
if (error) return cb(error)
const data = JSON.parse(body)
const startShipURL = data.starships[0]
const vehicleURL = data.vehicles[0]
request(startShipURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, starship_class } = JSON.parse(body)
lukeInfo.startShip = { name, model, type: starship_class}
request(vehicleURL, (error, response, body) => {
if (error) return cb(error)
const { name, model, vehicle_class } = JSON.parse(body)
lukeInfo.vehicle = { name, model, type: vehicle_class}
cb(null, lukeInfo) // <== Pass null in error and result as second arg
})
})
})
}
describe('Example with Callbacks (Callback Hell)', () => {
it('should get Luke details', (done) => {
getLuke((error, info) => {
if (error) return done(error)
console.log(info)
done()
});
})
})
|
Add notice in callback example
|
Add notice in callback example
|
JavaScript
|
mit
|
pierreroth64/js-async-tutorial
|
987d9722ecbcfa8925a48765086beceb2a913a58
|
tests/test_convert_tag.js
|
tests/test_convert_tag.js
|
var suite = require('suite.js');
var convertTag = require('../lib/convert_tag');
suite(convertTag, [
'foo', 'foo',
'self help', 'self_help',
'self-help', 'self__help',
'another self help', 'another_self_help',
'another-self-help', 'another__self__help',
'SciFi', 'sci_fi',
'sci-fi', 'sci__fi'
]);
|
var suite = require('suite.js');
var convertTag = require('../lib/convert_tag');
suite(convertTag, [
'foo', 'foo',
'self help', 'self_help',
'self-help', 'self__help',
'another self help', 'another_self_help',
'another-self-help', 'another__self__help',
'SciFi', 'sci_fi',
'SciFiToo', 'sci_fi_too',
'sci-fi', 'sci__fi'
]);
|
Add multipart case for upper case boundaries
|
Add multipart case for upper case boundaries
|
JavaScript
|
mit
|
Kikobeats/blogger2ghost,bebraw/blogger2ghost
|
c2a32db5fe2d291f4edd38b484aca17b51f5edae
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: '**/*.js',
tasks: ['jshint', 'cafemocha', 'karma:unit:run']
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
|
module.exports = function(grunt) {
grunt.initConfig({
pkg: grunt.file.readJSON('package.json'),
jshint: {
options: {
jshintrc: '.jshintrc'
},
all: [
'Gruntfile.js',
'lib/**/*.js',
'public/javascripts/lib/**/*.js',
'test/**/*.js'
]
},
cafemocha: {
options: {
ui: 'bdd',
reporter: 'dot'
},
src: 'test/unit/**/*.js'
},
// NOTE: need to start karma server first in
// separate window with `grunt karma:unit`
karma: {
unit: {
configFile: 'karma.conf.js'
}
},
watch: {
files: ['<%= jshint.all %>'],
tasks: ['jshint', 'cafemocha', 'karma:unit:run'],
options: {interrupt: true}
}
});
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-cafe-mocha');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-karma');
grunt.registerTask('default', ['jshint', 'cafemocha', 'karma:unit:run']);
};
|
Stop watchnig so many files, fixes errors
|
Stop watchnig so many files, fixes errors
|
JavaScript
|
mit
|
jamiemill/lux,jamiemill/lux,jamiemill/lux
|
439f689096d46eac35c2adfe23b901e220a0f558
|
Gruntfile.js
|
Gruntfile.js
|
module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
|
module.exports = function(grunt) {
grunt.initConfig({
bowerPkg: grunt.file.readJSON('bower.json'),
karma: {
unit: {
configFile: 'karma.conf.js',
singleRun: true,
browsers: ['PhantomJS']
}
},
cssmin: {
build: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */'
},
src: 'src/progress-button.css',
dest: 'dist/progress-button.min.css'
}
},
uglify: {
options: {
banner: '/* <%= bowerPkg.name %> v<%= bowerPkg.version %> (<%= bowerPkg.homepage %>) */\n'
},
build: {
src: 'src/progress-button.js',
dest: 'dist/progress-button.min.js'
}
}
})
grunt.loadNpmTasks('grunt-contrib-cssmin');
grunt.loadNpmTasks('grunt-contrib-uglify')
grunt.loadNpmTasks('grunt-karma')
grunt.registerTask('build', ['cssmin', 'uglify'])
grunt.registerTask('test', ['karma'])
grunt.registerTask('default', [])
}
|
Add cssmin to Grunt task ‘build’
|
Add cssmin to Grunt task ‘build’
|
JavaScript
|
bsd-2-clause
|
SonicHedgehog/angular-progress-button,SonicHedgehog/angular-progress-button
|
ae5cad1e172ecd2a12a380c9f473b8b04af0f814
|
Gruntfile.js
|
Gruntfile.js
|
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Task configuration.
csslint: {
src: ['public/**/*.css'],
},
docco: {
src: ['*.js', 'routes/**/*.js']
},
jshint: {
// See .jshintrc
src: ['*.js', 'routes/**/*.js'],
options: {
jshintrc: true
}
},
watch: {
files: '<%= jshint.src %>',
tasks: ['jshint']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-docco');
// Default task.
grunt.registerTask('default', ['jshint']);
};
|
/*global module:false*/
module.exports = function(grunt) {
// Project configuration.
grunt.initConfig({
// Task configuration.
csslint: {
src: ['public/**/*.css'],
},
docco: {
src: ['*.js', 'routes/**/*.js']
},
jshint: {
// See .jshintrc
src: ['*.js', 'routes/**/*.js'],
options: {
jshintrc: true
}
},
watch: {
files: '<%= jshint.src %>',
tasks: ['jshint']
}
});
// These plugins provide necessary tasks.
grunt.loadNpmTasks('grunt-contrib-csslint');
grunt.loadNpmTasks('grunt-contrib-jshint');
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-docco');
// Default task.
grunt.registerTask('default', ['jshint', 'csslint', 'docco']);
};
|
Add csslint and docco to the default grunt task
|
Add csslint and docco to the default grunt task
|
JavaScript
|
mit
|
nicolasmccurdy/jsbox
|
a3e29bcc9da540c6601c7ce74046c6451775809a
|
mergedSchema.js
|
mergedSchema.js
|
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
return mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
// console.warn(`[!] Type collision ${rightType}`)
return rightType
},
resolvers: mergeInfo => ({
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return mergeInfo.delegate("query", "artist", { id }, context, info)
},
},
},
}),
})
}
|
import { mergeSchemas, introspectSchema, makeRemoteExecutableSchema } from "graphql-tools"
import { createHttpLink } from "apollo-link-http"
import fetch from "node-fetch"
import localSchema from "./schema"
export default async function mergedSchema() {
const convectionLink = createHttpLink({
fetch,
uri: process.env.CONVECTION_GRAPH_URL,
headers: {
Authorization: `Bearer ${process.env.CONVECTION_TOKEN}`,
},
})
const convectionSchema = await makeRemoteExecutableSchema({
schema: await introspectSchema(convectionLink),
link: convectionLink,
})
const linkTypeDefs = `
extend type Submission {
artist: Artist
}
`
return mergeSchemas({
schemas: [localSchema, convectionSchema, linkTypeDefs],
// Prefer others over the local MP schema.
onTypeConflict: (_leftType, rightType) => {
console.warn(`[!] Type collision ${rightType}`) // eslint-disable-line no-console
return rightType
},
resolvers: mergeInfo => ({
Submission: {
artist: {
fragment: `fragment SubmissionArtist on Submission { artist_id }`,
resolve: (parent, args, context, info) => {
const id = parent.artist_id
return mergeInfo.delegate("query", "artist", { id }, context, info)
},
},
},
}),
})
}
|
Enable type name conflict logging.
|
[Stitching] Enable type name conflict logging.
|
JavaScript
|
mit
|
artsy/metaphysics,mzikherman/metaphysics-1,craigspaeth/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,mzikherman/metaphysics-1,craigspaeth/metaphysics,artsy/metaphysics,artsy/metaphysics
|
994d14b7619ff6997881cb87b0d4653b6aca645c
|
app.js
|
app.js
|
"use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
|
"use strict";
// Load the libraries and modules
var assets = require(__dirname + '/data/assets.json');
var config = {
npm: __dirname + '/node_modules/',
libraries: {
nodejs: {},
npm: {}
},
directory: __dirname + '/modules/',
modules: {
npm: {
'dragonnodejs-webserver': {
app: { port: process.env.PORT },
auth: {
realm: process.env.AUTH_REALM,
user: process.env.AUTH_USER,
password: process.env.AUTH_PASSWORD
},
bower: {
libraries: [],
path: __dirname + '/bower_components/'
},
header: {
'X-UA-Compatible': 'IE=edge,chrome=1',
'X-Frame-Options': 'DENY',
'X-XSS-Protection': '1; mode=block',
'X-Powered-By': null
},
language: {
default: 'en',
languages: ['de', 'en'],
path: __dirname + '/languages/'
},
static: { path: __dirname + '/web/' },
swig: { views: __dirname + '/views/' }
}
},
directory: {
detail: { assets: assets },
list: { assets: assets }
}
}
};
require('dragonnodejs')(config);
|
Add basic http authentication for all http requests on testserver
|
Add basic http authentication for all http requests on testserver
|
JavaScript
|
mit
|
SunnyUK/assetlist,SunnyUK/assetlist
|
df342fe730d44c0141bd169d90df7202f0d3a571
|
app.js
|
app.js
|
'use strict';
/**
* Module dependencies.
*/
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const router = require('./routes/routes');
/**
* Express configuration.
*/
const app = express();
app.use(compression());
// parse application/json
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
/**
* Catch all error requests
*/
app.use(function(err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
|
'use strict';
/**
* Module dependencies.
*/
const express = require('express');
const compression = require('compression');
const bodyParser = require('body-parser');
const router = require('./routes/routes');
/**
* Express configuration.
*/
const app = express();
app.use(compression());
// parse application/json
app.use(bodyParser.json());
// support encoded bodies
app.use(bodyParser.urlencoded({ extended: true }));
app.use(router);
/**
* Express configuration.
*/
app.set('port', process.env.PORT || 3000);
/**
* Catch all error requests
*/
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/**
* Start Express server.
*/
app.listen(app.get('port'), () => {
console.log('Express server listening on port %d in %s mode', app.get('port'), app.get('env'));
});
module.exports = app;
|
Update error function to arrow function
|
Update error function to arrow function
|
JavaScript
|
mit
|
lostatseajoshua/Challenger
|
3e67e31a319630328d2271ad323d43f7f5dd4e1c
|
app/ui/setup.js
|
app/ui/setup.js
|
const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
onStateChange();
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
};
|
const { configureStore } = require('../store');
const readline = require('readline');
const draw = require('./draw');
const { keys } = require('./input');
const actions = require('../actions');
const resize = (proc, store) => {
const action = actions.resize({
rows: proc.stdout.rows,
columns: proc.stdout.columns
});
store.dispatch(action);
};
module.exports = (initialState, proc = process) => {
const store = configureStore(proc, initialState);
const onStateChange = draw(proc, store);
store.subscribe(onStateChange);
proc.stdin.addListener('keypress', keys(store));
proc.stdout.addListener('resize', () => resize(proc, store));
resize(proc, store);
readline.emitKeypressEvents(proc.stdin);
proc.stdin.setRawMode(true);
};
|
Remove the unnecessary render on start up
|
Remove the unnecessary render on start up
|
JavaScript
|
mit
|
andybry/explorer-cli
|
510dab8128321ab8fa9f2ee4983cff3037b961a8
|
bin/sssg.js
|
bin/sssg.js
|
#!/usr/bin/env node
var argv = require("yargs").argv;
var main = require('../');
var task = argv._[0];
var options = {};
if(task === "try"){
options.env = "development";
main.do("init", options, function(){
options.src = "./src";
options.dst = "./docs";
main.do("serve", options);
});
return;
}
options.src = argv.src || argv.s;
options.dst = argv.dst || argv.d;
options.root = argv.root || argv.r;
options.env = argv.env || argv.e;
main.do(task, options);
|
#!/usr/bin/env node
var argv = require("yargs").argv;
var main = require('../');
var task = argv._[0];
var options = {};
if(task === "try"){
options.env = "development";
main.do("init", options, function(){
options.src = "./src";
options.dst = "./docs";
main.do("serve", options);
});
return;
}
options.src = argv.src || argv.s;
options.dst = argv.dst || argv.d;
options.root = argv.root || argv.r;
if(task === "serve"){
options.env = argv.env || argv.e || "development";
}
else {
options.env = argv.env || argv.e || "production";
}
main.do(task, options);
|
Set env=development when task:serve is dispatched
|
Set env=development when task:serve is dispatched
|
JavaScript
|
mit
|
Hinaser/sssg,Hinaser/sssg
|
2e926ceaa52929378444fcaa6394a90de3b8ee44
|
app/common/modules/applications.js
|
app/common/modules/applications.js
|
define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
});
|
define([
'extensions/collections/collection'
],
function (Collection) {
return {
requiresSvg: true,
collectionClass: Collection,
collectionOptions: function () {
var valueAttr = this.model.get('value-attribute') || '_count';
var options = {
valueAttr: valueAttr
};
options.format = this.model.get('format') ||
{ type: 'integer', magnitude: true, sigfigs: 3, pad: true };
options.dataSource = this.model.get('data-source');
options.dataSource['query-params'] = _.extend({flatten:true}, options.dataSource['query-params']);
options.axes = _.merge({
x: {
label: 'Dates',
key: ['_start_at', 'end_at'],
format: 'date'
},
y: [
{
label: 'Number of applications',
key: valueAttr,
format: options.format
}
]
}, this.model.get('axes'));
return options;
},
visualisationOptions: function () {
return {
valueAttr: this.model.get('value-attribute'),
maxBars: this.model.get('max-bars'),
target: this.model.get('target'),
pinTo: this.model.get('pin-to')
};
}
};
});
|
Add valueAttr to the application module
|
Add valueAttr to the application module
|
JavaScript
|
mit
|
tijmenb/spotlight,alphagov/spotlight,alphagov/spotlight,keithiopia/spotlight,tijmenb/spotlight,tijmenb/spotlight,keithiopia/spotlight,keithiopia/spotlight,alphagov/spotlight
|
3eb39cf29563deade1d8a2b6687bbb0f17101ba0
|
app/controllers/messages/create.js
|
app/controllers/messages/create.js
|
var r = require('rethinkdb');
module.exports = function messageCreator(pool) {
return function(message) {
return pool.runQuery(r.table('messages').insert({
body: message.body,
creation: r.now()
}));
};
};
|
var r = require('rethinkdb');
module.exports = function messageCreator(pool) {
return function(message) {
return pool.runQuery(r.table('messages').insert({
body: message.body,
scope: message.scope,
creation: r.now()
}));
};
};
|
Include scope in controller when adding post
|
Include scope in controller when adding post
|
JavaScript
|
mit
|
dingroll/dingroll.com,dingroll/dingroll.com
|
93204638953bebc77a46a5d8b0b3f9318046fc1a
|
src/pipeline.js
|
src/pipeline.js
|
import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
console.log(onError, result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {}
|
import { basename, extname, join, dirname, relative, resolve } from 'path'
import { default as put } from 'output-file-sync'
import { parallel } from 'async'
const keys = Object.keys
export default function createPipeline(pkg, opts, build, progress) {
const
{ onBuild = noop
, onError = noop
} = progress
return (files, callback) => {
parallel(
[].concat(files).map(file => cont => {
const name = basename(file, extname(file))
build(name, file, (error, output) => {
let result = { input: file }
if (error) {
result.error = error
onError(result)
} else {
result.messages = output.messages
result.files = keys(output.files).map(name => {
let path = join(pkg.resolve(opts.lib), dirname(relative(pkg.resolve(opts.src), resolve(file))))
let outfile = join(path, name)
put(outfile, output.files[name])
return outfile
})
onBuild(result)
}
cont(null, result)
})
})
, callback
)
}
}
function noop() {}
|
Fix error logging to actually output useful data
|
Fix error logging to actually output useful data
|
JavaScript
|
mit
|
zambezi/ez-build,zambezi/ez-build
|
e49af4ac9be10a34e24672f65bab16c6c1efa5ef
|
vue.config.js
|
vue.config.js
|
module.exports = {
assetsDir: 'styleguide/',
css: {
modules: true
}
};
|
module.exports = {
css: {
modules: true
},
publicPath: '/styleguide/'
};
|
Correct to the right property
|
Correct to the right property
|
JavaScript
|
mit
|
rodet/styleguide,rodet/styleguide
|
c3ad93cb30061349d175f48fe5df8d04f817c057
|
web/src/js/components/Settings/SettingsMenuItem.js
|
web/src/js/components/Settings/SettingsMenuItem.js
|
import React from 'react'
import PropTypes from 'prop-types'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import NavLink from 'general/NavLink'
class SettingsMenuItem extends React.Component {
render () {
const menuItemStyle = Object.assign(
{},
this.props.style)
return (
<NavLink
to={this.props.to}
style={{ textDecoration: 'none' }}
>
<ListItem style={menuItemStyle}>
<ListItemText primary={this.props.children} />
</ListItem>
</NavLink>
)
}
}
SettingsMenuItem.propTypes = {
to: PropTypes.string.isRequired,
style: PropTypes.object
}
SettingsMenuItem.defaultProps = {
style: {}
}
export default SettingsMenuItem
|
import React from 'react'
import PropTypes from 'prop-types'
import ListItem from '@material-ui/core/ListItem'
import ListItemText from '@material-ui/core/ListItemText'
import NavLink from 'general/NavLink'
class SettingsMenuItem extends React.Component {
render () {
return (
<NavLink
to={this.props.to}
style={{ textDecoration: 'none' }}
>
<ListItem button>
<ListItemText primary={this.props.children} />
</ListItem>
</NavLink>
)
}
}
SettingsMenuItem.propTypes = {
to: PropTypes.string.isRequired
}
export default SettingsMenuItem
|
Add placeholder menu item hover style
|
Add placeholder menu item hover style
|
JavaScript
|
mpl-2.0
|
gladly-team/tab,gladly-team/tab,gladly-team/tab
|
9604f1566158623e5d009df9b72e133129b7a18f
|
src/components/LawList.js
|
src/components/LawList.js
|
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const columns = [
{ name: 'groupkey', label: <span>Ab­kür­zung</span> },
{ name: 'title', label: <span>Be­zeich­nung</span> },
{ name: 'action' },
];
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
columns={columns}
rows={rows}
className='law-list'
/>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
|
import React, { PropTypes } from 'react';
import { Link } from 'react-router';
import { DataTable, TableHeader, FABButton, Icon } from 'react-mdl';
import Pagination from './Pagination';
import './lawList.scss';
const LawList = ({ laws, page, pageSize, selectPage, total }) => {
const rows = laws.map(law => ({...law,
key: law.groupkey,
action: (
<Link to={'/gesetz/' + law.groupkey}>
<FABButton mini>
<Icon name='launch' />
</FABButton>
</Link>
)
}));
return (
<div>
<DataTable
rows={rows}
className='law-list'
>
<TableHeader name='groupkey'>Ab­kür­zung</TableHeader>
<TableHeader name='title'>Be­zeich­nung</TableHeader>
<TableHeader name='action' />
</DataTable>
<Pagination
page={page}
hasNext={total > (pageSize*page)}
hasPrev={page > 1}
selectPage={selectPage}
/>
</div>
);
};
LawList.propTypes = {
laws: PropTypes.array.isRequired,
page: PropTypes.number,
pageSize: PropTypes.number,
selectPage: PropTypes.func.isRequired,
total: PropTypes.number.isRequired,
};
LawList.defaultProps = {
page: 1,
pageSize: 20,
};
export default LawList;
|
Implement new version of react-mdl's DataTable including TableHeader component.
|
Implement new version of react-mdl's DataTable including TableHeader component.
|
JavaScript
|
agpl-3.0
|
ahoereth/lawly,ahoereth/lawly,ahoereth/lawly
|
71af63a1dbbf93b49b26bed20f11e9f5abbcb591
|
app/webpack/entities/alarmClock.js
|
app/webpack/entities/alarmClock.js
|
import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
})
];
} else {
return [];
}
}
}
export default new AlarmClock();
|
import Entity from '../Entity.js';
import printMessage from '../printMessage.js';
import action from '../action.js';
import time from '../time.js';
export class AlarmClock extends Entity {
constructor() {
super();
this.ringing = true;
}
name() {
return "alarm clock";
}
actions() {
const checkTime = action("Look at the time.", () => {
printMessage(`It is now ${time()}.`);
})
if(this.ringing) {
return [
action("Snooze", () => {
printMessage(`You sleep for another 5 minutes before the alarm clock rings again. It's now ${time()}.`);
}),
action("Turn if off.", () => {
this.ringing = false;
printMessage('You turn the alarm clock off.');
}),
checkTime
];
} else {
return [checkTime];
}
}
}
export default new AlarmClock();
|
Check time after alarm disabled
|
Check time after alarm disabled
|
JavaScript
|
mit
|
TEAMBUTT/LD35
|
a7114d6f043978002f6d7c9d1974f21c72dddf77
|
lib/fs.utils.js
|
lib/fs.utils.js
|
const fs = require('fs')
function fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
function writeFile(filename, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, error => {
if (error) { reject(error); return }
resolve()
})
})
}
function readFile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (error, data) => {
if (error) { reject(error); return }
resolve(data)
})
})
}
module.exports = exports = {
fileExist,
writeFile,
readFile
}
|
const fs = require('fs')
function fileExist(filename = '') {
try {
fs.accessSync(filename)
} catch (e) {
return false
}
return true
}
function writeFile(filename, data) {
return new Promise((resolve, reject) => {
fs.writeFile(filename, data, error => {
if (error) { reject(error); return }
resolve()
})
})
}
function readFile(filename) {
return new Promise((resolve, reject) => {
fs.readFile(filename, (error, data) => {
if (error) { reject(error); return }
resolve(data)
})
})
}
function chmod(filename, rights) {
return new Promise((resolve, reject) => {
fs.chmod(filename, rights, error => {
if (error) { reject(error); return }
resolve()
})
})
}
module.exports = exports = {
fileExist,
writeFile,
readFile,
chmod
}
|
Add method to promisify chmod function
|
Add method to promisify chmod function
|
JavaScript
|
apache-2.0
|
Mindsers/configfile
|
64e91980f64ca6299b774f2d47a7c352503b6466
|
troposphere/static/js/components/modals/instance/launch/components/InstanceLaunchFooter.react.js
|
troposphere/static/js/components/modals/instance/launch/components/InstanceLaunchFooter.react.js
|
import React from 'react';
export default React.createClass({
propTypes: {
backIsDisabled: React.PropTypes.bool.isRequired,
launchIsDisabled: React.PropTypes.bool.isRequired,
advancedIsDisabled: React.PropTypes.bool.isRequired,
viewAdvanced: React.PropTypes.func,
onSubmitLaunch: React.PropTypes.func,
onCancel: React.PropTypes.func,
onBack: React.PropTypes.func,
},
renderBack: function() {
if (this.props.backIsDisabled) {
return
}
else {
return (
<a className="btn btn-default pull-left"
style={{marginRight:"10px"}}
onClick={this.props.onBack}
>
<span className="glyphicon glyphicon-arrow-left"/> Back
</a>
)
}
},
render: function() {
let launchIsDisabled = this.props.launchIsDisabled ? "disabled" : "";
let advancedIsDisabled = this.props.advancedIsDisabled ? "disabled" : "";
return (
<div className="modal-footer">
{this.renderBack()}
<a className={`pull-left btn ${advancedIsDisabled}`}
onClick={this.props.viewAdvanced}>
<i className="glyphicon glyphicon-cog"/>
Advanced Options
</a>
<button
disabled={this.props.launchIsDisabled}
type="button"
className={`btn btn-primary pull-right ${launchIsDisabled}`}
onClick={this.props.onSubmitLaunch}
>
Launch Instance
</button>
<button type="button"
className="btn btn-default pull-right"
style={{marginRight:"10px"}}
onClick={this.props.onCancel}
>
Cancel
</button>
</div>
)
}
});
|
import React from 'react';
export default React.createClass({
propTypes: {
backIsDisabled: React.PropTypes.bool.isRequired,
launchIsDisabled: React.PropTypes.bool.isRequired,
advancedIsDisabled: React.PropTypes.bool.isRequired,
viewAdvanced: React.PropTypes.func,
onSubmitLaunch: React.PropTypes.func,
onCancel: React.PropTypes.func,
onBack: React.PropTypes.func,
},
renderBack: function() {
if (this.props.backIsDisabled) {
return
}
else {
return (
<a className="btn btn-default pull-left"
style={{marginRight:"10px"}}
onClick={this.props.onBack}
>
<span className="glyphicon glyphicon-arrow-left"/> Back
</a>
)
}
},
render: function() {
return (
<div className="modal-footer">
{this.renderBack()}
<a className="pull-left btn"
disabled={this.props.advancedIsDisabled}
onClick={this.props.viewAdvanced}>
<i className="glyphicon glyphicon-cog"/>
Advanced Options
</a>
<button
disabled={this.props.launchIsDisabled}
type="button"
className="btn btn-primary pull-right"
onClick={this.props.onSubmitLaunch}
>
Launch Instance
</button>
<button type="button"
className="btn btn-default pull-right"
style={{marginRight:"10px"}}
onClick={this.props.onCancel}
>
Cancel
</button>
</div>
)
}
});
|
Make InstanceLaunchFooter functionally disabled instead of just visually
|
Make InstanceLaunchFooter functionally disabled instead of just visually
|
JavaScript
|
apache-2.0
|
CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend,CCI-MOC/GUI-Frontend
|
fe97f331b8f2e94c03630f3b6adaec711c0978bd
|
test/acceptance/features/messages/step_definitions/messages.js
|
test/acceptance/features/messages/step_definitions/messages.js
|
const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
defineSupportCode(({ Then }) => {
const Messages = client.page.Messages()
Then(/^I see the success message$/, async () => {
await Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--success')
})
Then(/^I see the error message$/, () => {
Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--error')
})
})
|
const { client } = require('nightwatch-cucumber')
const { defineSupportCode } = require('cucumber')
defineSupportCode(({ Then }) => {
const Messages = client.page.Messages()
Then(/^I see the success message$/, async () => {
await Messages
.waitForElementPresent('@flashMessage')
.assert.cssClassPresent('@flashMessage', 'c-message--success')
})
})
|
Remove redundant error message assertion
|
Remove redundant error message assertion
|
JavaScript
|
mit
|
uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2,uktrade/data-hub-frontend,uktrade/data-hub-frontend,uktrade/data-hub-fe-beta2
|
071992c3a29c44ae565bd81c18b7144f87d356ff
|
Source/Our.Umbraco.Nexu.Core/Client/controllers/base-delete-controller.js
|
Source/Our.Umbraco.Nexu.Core/Client/controllers/base-delete-controller.js
|
angular.module('umbraco').controller('Our.Umbraco.Nexu.BaseDeleteController',
['$scope', '$controller', 'Our.Umbraco.Nexu.Resource',
function ($scope, $controller, nexuResource) {
// inherit core delete controller
angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
$scope.links = {};
$scope.descendantsHaveLinks = false;
$scope.isLoading = true;
nexuResource.getIncomingLinks($scope.currentNode.id).then(function (result) {
$scope.links = result.data;
if (result.data.length == 0) {
nexuResource.checkDescendants($scope.currentNode.id, $scope.isMedia).then(function (result) {
$scope.descendantsHaveLinks = result.data;
$scope.isLoading = false;
});
} else {
$scope.isLoading = false;
}
});
}]);
|
angular.module('umbraco').controller('Our.Umbraco.Nexu.BaseDeleteController',
['$scope', '$controller', 'Our.Umbraco.Nexu.Resource',
function ($scope, $controller, nexuResource) {
// inherit core delete controller
if ($scope.isMedia) {
angular.extend(this, $controller('Umbraco.Editors.Media.DeleteController', { $scope: $scope }));
} else {
angular.extend(this, $controller('Umbraco.Editors.Content.DeleteController', { $scope: $scope }));
}
$scope.links = {};
$scope.descendantsHaveLinks = false;
$scope.isLoading = true;
nexuResource.getIncomingLinks($scope.currentNode.id).then(function (result) {
$scope.links = result.data;
if (result.data.length == 0) {
nexuResource.checkDescendants($scope.currentNode.id, $scope.isMedia).then(function (result) {
$scope.descendantsHaveLinks = result.data;
$scope.isLoading = false;
});
} else {
$scope.isLoading = false;
}
});
}]);
|
Set correct base controller for content type
|
Set correct base controller for content type
|
JavaScript
|
mit
|
dawoe/umbraco-nexu,dawoe/umbraco-nexu,dawoe/umbraco-nexu
|
463359038908a85f8624483473b29fe720050c06
|
lib/markdown.js
|
lib/markdown.js
|
/* globals atom:false */
'use strict';
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
return [ {
name: 'Markdown: view',
exec: 'mark',
args: [ '{FILE_ACTIVE}' ]
}];
}
};
};
|
/* globals atom:false */
'use strict';
exports.provideBuilder = function () {
return {
niceName: 'Markdown',
isEligable: function () {
var textEditor = atom.workspace.getActiveTextEditor();
if (!textEditor || !textEditor.getPath()) {
return false;
}
var path = textEditor.getPath();
return path.endsWith('.md') || path.endsWith('.mkd');
},
settings: function () {
return [ {
name: 'Markdown: view',
exec: 'open',
args: [ '-a', 'Marked.app', '{FILE_ACTIVE}' ]
}];
}
};
};
|
Use `open` to find Marked.app, because of path problems finding the `mark` command.
|
Use `open` to find Marked.app, because of path problems finding the `mark` command.
|
JavaScript
|
mpl-2.0
|
bwinton/atom-build-markdown
|
f659cc0dee2d9ed1df80793d87a1337a1403d7bc
|
packages/@sanity/desk-tool/src/DeskTool.js
|
packages/@sanity/desk-tool/src/DeskTool.js
|
import React, {PropTypes} from 'react'
import styles from '../styles/DeskTool.css'
import PaneResolver from 'config:desk-tool/pane-resolver'
DeskTool.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired
})
}
function DeskTool({location}) {
return (
<div className={styles.deskTool}>
<PaneResolver location={location.pathname} />
</div>
)
}
export default DeskTool
|
import React, {PropTypes} from 'react'
import styles from '../styles/DeskTool.css'
import PaneResolver from 'config:desk-tool/pane-resolver'
import ActionButton from 'component:@sanity/base/action-button?'
import schema from 'schema:@sanity/base/schema'
import config from 'config:sanity'
function DeskTool({location}) {
const actions = (schema.types || []).map(type => ({
url: `/${type.name}/${config.api.dataset}:`,
title: type.name.substr(0, 1).toUpperCase() + type.name.substr(1)
}))
return (
<div className={styles.deskTool}>
<PaneResolver location={location.pathname} />
{ActionButton && <ActionButton actions={actions} />}
</div>
)
}
DeskTool.propTypes = {
location: PropTypes.shape({
pathname: PropTypes.string.isRequired
})
}
export default DeskTool
|
Use action button if it exists
|
Use action button if it exists
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
f4f55a8ed829910cdec7d4025b4ea07ee606271b
|
rules/errors.js
|
rules/errors.js
|
'use strict';
module.exports = {
'rules': {
// Enforce trailing commas in multiline object literals
'comma-dangle': [2, 'always-multiline'],
},
};
|
'use strict';
module.exports = {
'rules': {
// Enforce trailing commas in multiline object literals
'comma-dangle' : [2, 'always-multiline'],
// Disallow template literal placeholder syntax in regular strings
'no-template-curly-in-string': [2],
// Disallow negating the left operand of relational operators
'no-unsafe-negation' : [2],
// Enforce valid JSDoc comments
'valid-jsdoc' : [2],
},
};
|
Enable more core “Errors” rules
|
Enable more core “Errors” rules
|
JavaScript
|
mit
|
nutshellcrm/eslint-config-nutshell
|
d13350e6592dce99e3d3b508b335e2b9f73000eb
|
routes/recipes/index.js
|
routes/recipes/index.js
|
var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
if (expand) {
try {
var relation = db.getData('/' + expand + 's');
_(recipes)
.forEach(function (recipe) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
});
}
catch(err) {
console.log(err);
}
}
res.json(recipes);
});
module.exports = router;
|
var express = require('express');
var router = express.Router();
var JsonDB = require('node-json-db');
var _ = require('lodash');
// Recipes listing
router.get('/', function (req, res, next) {
var db = new JsonDB('db', false, false);
var recipes = db.getData('/recipes');
// Expand requested resources if they exist
// The resource to expand is singular, e.g.
// to expand 'users' we provide _expand=user
var expand = req.query._expand;
var relation;
if (expand) {
try {
relation = db.getData('/' + expand + 's');
}
catch(err) {
console.log(err.message);
}
}
// Obtain a possible search query
var q = req.query.q;
var qReg = q && new RegExp(q, 'i');
// Filter on the search query and then optionally
// expand recipes in the response
res.json(_(recipes)
.filter(function (recipe) {
if (qReg) {
return recipe.description.trim().match(qReg);
}
return true;
})
.map(function (recipe) {
if (relation) {
recipe[expand] = _(relation).find({ id: recipe[expand + 'Id'] });
delete recipe[expand + 'Id'];
}
return recipe;
})
.value());
});
module.exports = router;
|
Add section 2.4 code to search recipe descriptions
|
Add section 2.4 code to search recipe descriptions
|
JavaScript
|
mit
|
adamsea/recipes-api
|
0a776b2259f3f3d5cda8d1103689539cfd9f862e
|
build/tasks/build-release/start.js
|
build/tasks/build-release/start.js
|
module.exports = function(grunt, config, parameters, done) {
function endForError(e) {
process.stderr.write(e.message || e);
done(false);
}
try {
var rimraf = require('rimraf'),
fs = require('fs'),
download = require('download'),
path = "./release";
rimraf.sync(path);
fs.mkdir(path);
// Download archive from git
process.stdout.write("Downloading Archive...\n");
var stream = download('https://github.com/concrete5/concrete5/archive/master.zip', path, {
extract: true
});
stream.on('close', function() {
done();
});
}
catch(e) {
endForError(e);
return;
}
};
|
module.exports = function(grunt, config, parameters, done) {
function endForError(e) {
process.stderr.write(e.message || e);
done(false);
}
try {
var shell = require('shelljs'),
fs = require('fs'),
download = require('download'),
path = "./release";
shell.rm('-rf', path);
fs.mkdir(path);
// Download archive from git
process.stdout.write("Downloading Archive...\n");
var stream = download('https://github.com/concrete5/concrete5/archive/master.zip', path, {
extract: true
});
stream.on('close', function() {
done();
});
}
catch(e) {
endForError(e);
return;
}
};
|
Use shelljs instead of rimraf
|
Use shelljs instead of rimraf
|
JavaScript
|
mit
|
matt9mg/concrete5,TimDix/concrete5,TimDix/concrete5,avdevs/concrete5,matt9mg/concrete5,avdevs/concrete5,avdevs/concrete5,MichaelMaar/concrete5,TimDix/concrete5,MichaelMaar/concrete5,matt9mg/concrete5,MichaelMaar/concrete5
|
602adb639f55da9ee6a9c16f5c0fec0e4e10821f
|
assets/debug.js
|
assets/debug.js
|
window.onerror = function(message, url, line) {
$.ajax('/api/Error', {
data: {
message: message,
url: url,
line: line
}
});
};
|
window.onerror = function(message, url, line) {
// Don't attempt to handle non-standard errors (e.g. failed
// HTTP request via jQuery).
if (typeof message !== 'string') return;
$.ajax('/api/Error', {
data: {
message: message,
url: url,
line: line
}
});
};
|
Fix for failure to serialize jQuery event object.
|
Fix for failure to serialize jQuery event object.
|
JavaScript
|
bsd-3-clause
|
developmentseed/bones,Wiredcraft/bones,developmentseed/bones,Wiredcraft/bones
|
c86593d654f2852caad6620510069c63191c3f04
|
app/index.js
|
app/index.js
|
var peer = require('./peer');
var textOT = require('ottypes').text
var gulf = require('gulf');
var bindEditor = require('gulf-textarea');
var textarea = document.querySelector('textarea#doc');
var textareaDoc = bindEditor(textarea);
var text = 'hello';
var path = 'chat.sock';
// var transport = require('./transports/socket')(path);
// var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' });
var transport = require('./transports/webrtc')();
peer(transport).then(stream => {
console.log('started');
console.log(stream.server ? 'master' : 'slave');
window.stream = stream;
var textareaMaster = textareaDoc.masterLink();
if (stream.server) {
// master
gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, doc) => {
var slave1 = doc.slaveLink();
stream.pipe(slave1).pipe(stream);
var slave2 = doc.slaveLink();
textareaMaster.pipe(slave2).pipe(textareaMaster);
});
} else {
// slave
textareaMaster.pipe(stream).pipe(textareaMaster);
}
});
|
var peer = require('./peer');
var textOT = require('ottypes').text
var gulf = require('gulf');
var text = 'hello';
var doc = require('gulf-textarea')(
document.querySelector('textarea#doc')
);
var path = 'chat.sock';
// var transport = require('./transports/socket')(path);
// var transport = require('./transports/mdns')({ port: 4321, name: 'nybblr' });
var transport = require('./transports/webrtc')();
peer(transport).then(stream => {
console.log('started');
console.log(stream.server ? 'master' : 'slave');
window.stream = stream;
var textareaMaster = doc.masterLink();
if (stream.server) {
// master
gulf.Document.create(new gulf.MemoryAdapter, textOT, text, (err, master) => {
var slave1 = master.slaveLink();
stream.pipe(slave1).pipe(stream);
var slave2 = master.slaveLink();
textareaMaster.pipe(slave2).pipe(textareaMaster);
});
} else {
// slave
textareaMaster.pipe(stream).pipe(textareaMaster);
}
});
|
Tidy doc representation into swappable one-liner.
|
Tidy doc representation into swappable one-liner.
|
JavaScript
|
cc0-1.0
|
nybblr/p2p-experiments,nybblr/p2p-experiments
|
dc79c6bdd3bae0ed3aa5a5663a55d574ab18379d
|
app/index.js
|
app/index.js
|
import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
|
import 'babel-core/polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import { ReduxRouter } from 'redux-router';
import Immutable from 'seamless-immutable';
import rootReducer from 'reducers/index';
import configureStore from 'store/configureStore';
import 'assets/styles/app.less';
const initialStoreState = createStore(rootReducer, {}).getState();
const initialState = window.__INITIAL_STATE__;
const finalState = Immutable(initialStoreState).merge(initialState, { deep: true });
const store = configureStore(finalState);
render(
<Provider store={store}>
<ReduxRouter
components={[]}
location={{}}
params={{}}
routes={[]}
/>
</Provider>,
document.getElementById('root')
);
if (__DEVTOOLS__) {
require('./createDevToolsWindow')(store);
}
// Fix for IE
if (!window.location.origin) {
window.location.origin = (
window.location.protocol + '//' + window.location.hostname + (
window.location.port ? ':' + window.location.port : ''
)
);
}
|
Fix logout link on IE
|
Fix logout link on IE
Closes #213.
|
JavaScript
|
mit
|
fastmonkeys/respa-ui
|
6dc0dabebb1ce6bf419cbb53d83c42b017c467a6
|
src/components/datepicker/utils.js
|
src/components/datepicker/utils.js
|
import { DateUtils } from 'react-day-picker/lib/src/index';
export const convertModifiersToClassnames = (modifiers, theme) => {
if (!modifiers) {
return {};
}
return Object.keys(modifiers).reduce((convertedModifiers, key) => {
return {
...convertedModifiers,
[theme[key]]: modifiers[key],
};
}, {});
};
export const isSelectingFirstDay = (from, to, day) => {
const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from);
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
|
import { DateUtils } from 'react-day-picker/lib/src/index';
import { DateTime } from 'luxon';
export const convertModifiersToClassnames = (modifiers, theme) => {
if (!modifiers) {
return {};
}
return Object.keys(modifiers).reduce((convertedModifiers, key) => {
return {
...convertedModifiers,
[theme[key]]: modifiers[key],
};
}, {});
};
export const isSelectingFirstDay = (from, to, day) => {
const isBeforeFirstDay = from && DateUtils.isDayBefore(day, from);
const isRangeSelected = from && to;
return !from || isBeforeFirstDay || isRangeSelected;
};
export function JSDateToLocaleString(date, locale, format = DateTime.DATE_SHORT) {
return DateTime.fromJSDate(date)
.setLocale(locale)
.toLocaleString(format);
}
|
Add util function to convert a JS date to locale string
|
Add util function to convert a JS date to locale string
|
JavaScript
|
mit
|
teamleadercrm/teamleader-ui
|
30c2850e9593738f2059c4c401ac75fd7b2c87fe
|
src/js/route.js
|
src/js/route.js
|
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
var route = function(name, params = {}, absolute = true) {
var domain = (namedRoutes[name].domain || baseUrl).replace(/\/+$/,'') + '/',
url = (absolute ? domain : '') + namedRoutes[name].uri,
params = typeof params !== 'object' ? [params] : params,
paramsArrayKey = 0;
return url.replace(
/\{([^}]+)\}/gi,
function (tag) {
var key = Array.isArray(params) ? paramsArrayKey : tag.replace(/\{|\}/gi, '');
paramsArrayKey++;
if (params[key] === undefined) {
throw 'Ziggy Error: "' + key + '" key is required for route "' + name + '"';
}
return params[key];
}
);
}
if (typeof exports !== 'undefined'){ exports.route = route }
|
Add support for single param instead of array/object.
|
Add support for single param instead of array/object.
|
JavaScript
|
mit
|
tightenco/ziggy,tightenco/ziggy
|
72c5934e1f5fde40ef8cdae61b205ebd91bddd3c
|
website/src/app/project/experiments/experiment/experiment.model.js
|
website/src/app/project/experiments/experiment/experiment.model.js
|
export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
|
export class ExperimentStep {
constructor(title, _type) {
this.id = '';
this.title = title;
this._type = _type;
this.steps = [];
this.description = '';
this.flags = {
important: false,
review: false,
error: false,
done: false
};
this.displayState = {
details: {
showTitle: true,
showStatus: true,
showNotes: true,
showFiles: false,
showSamples: false,
currentFilesTab: 0,
currentSamplesTab: 0
},
editTitle: true,
open: false,
maximize: false
};
this.node = null;
}
addStep(step) {
this.steps.push(step);
}
}
export class Experiment {
constructor(name) {
this.name = name;
this.goal = '';
this.description = 'Look at grain size as it relates to hardness';
this.aim = '';
this.done = false;
this.steps = [];
}
addStep(title, _type) {
let s = new ExperimentStep(title, _type);
this.steps.push(s);
}
}
|
Add done flag to experiment.
|
Add done flag to experiment.
|
JavaScript
|
mit
|
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
|
ba39cf7dbc7ec530d0e9556bd819f01ae97f73f3
|
src/helpers/collection/sort.js
|
src/helpers/collection/sort.js
|
exports.sort = function (Handlebars) {
return function (array, field, options) {
if (arguments.length === 1) {
throw new Error('Handlebars Helper "sort" needs 1 parameter');
}
options = arguments[arguments.length - 1];
if (arguments.length === 2) {
field = undefined;
}
var results;
if (field === undefined) {
results = array.sort();
} else {
results = array.sort(function (a, b) {
return a[field] > b[field];
});
}
if (!options.fn) {
return results;
} else {
if (results.length) {
var data = Handlebars.createFrame(options.data);
return results.map(function (result, i) {
data.index = i;
data.first = (i === 0);
data.last = (i === results.length - 1);
return options.fn(result, {data: data});
}).join('');
} else {
return options.inverse(this);
}
}
};
};
|
exports.sort = function (Handlebars) {
return function (input, key, options) {
if (arguments.length === 1) {
throw new Error('Handlebars Helper "sort" needs 1 parameter');
}
options = arguments[arguments.length - 1];
if (arguments.length === 2) {
key = undefined;
}
var results = input.concat();
if (key === undefined) {
results.sort();
} else {
results.sort(function (a, b) {
if (typeof a !== 'object' && typeof b !== 'object') return 0;
if (typeof a !== 'object') return -1;
if (typeof b !== 'object') return 1;
return a[key] > b[key];
});
}
if (!options.fn) {
return results;
} else {
if (results.length) {
var data = Handlebars.createFrame(options.data);
return results.map(function (result, i) {
data.index = i;
data.first = (i === 0);
data.last = (i === results.length - 1);
return options.fn(result, {data: data});
}).join('');
} else {
return options.inverse(this);
}
}
};
};
|
Sort by key now confirms both inputs are objects before comparing keys.
|
Sort by key now confirms both inputs are objects before comparing keys.
|
JavaScript
|
mit
|
ChiperSoft/HandlebarsHelperHoard,ChiperSoft/HandlebarsHelperHoard
|
90405067d41afe85eaaa7d9822f40f5ec74b7881
|
spring-boot-admin-server-ui/modules/applications/services/applicationViews.js
|
spring-boot-admin-server-ui/modules/applications/services/applicationViews.js
|
/*
* Copyright 2014 the original author or 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';
module.exports = function ($state, $q) {
'ngInject';
var views = [];
this.register = function (view) {
views.push(view);
};
this.getApplicationViews = function (application) {
var applicationViews = [];
views.forEach(function (view) {
$q.when(!view.show || view.show(application)).then(function (result) {
if (result) {
view.href = $state.href(view.state, {
id: application.id
});
applicationViews.push(view);
applicationViews.sort(function (v1, v2) {
return (v1.order || 0) - (v2.order || 0);
});
}
});
});
return applicationViews;
};
};
|
/*
* Copyright 2014 the original author or 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';
var angular = require('angular');
module.exports = function ($state, $q) {
'ngInject';
var views = [];
this.register = function (view) {
views.push(view);
};
this.getApplicationViews = function (application) {
var applicationViews = [];
views.forEach(function (view) {
$q.when(!view.show || view.show(application)).then(function (result) {
if (result) {
var appView = angular.copy(view);
appView.href = $state.href(view.state, {
id: application.id
});
applicationViews.push(appView);
applicationViews.sort(function (v1, v2) {
return (v1.order || 0) - (v2.order || 0);
});
}
});
});
return applicationViews;
};
};
|
Fix wrong links when listing multiple apps
|
Fix wrong links when listing multiple apps
|
JavaScript
|
apache-2.0
|
codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,joshiste/spring-boot-admin,codecentric/spring-boot-admin,codecentric/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin,joshiste/spring-boot-admin,librucha/spring-boot-admin
|
c3b3b55bcd208f66a2a6e85f1b97d822d815e803
|
schema/image/proxies/index.js
|
schema/image/proxies/index.js
|
module.exports = function() {
return require('./embedly').apply(null, arguments);
};
|
const { RESIZING_SERVICE } = process.env;
module.exports = function() {
if (RESIZING_SERVICE === 'gemini') {
return require('./gemini').apply(null, arguments);
} else {
return require('./embedly').apply(null, arguments);
}
};
|
Configure using an ENV variable
|
Configure using an ENV variable
|
JavaScript
|
mit
|
craigspaeth/metaphysics,mzikherman/metaphysics-1,craigspaeth/metaphysics,mzikherman/metaphysics-1,1aurabrown/metaphysics,artsy/metaphysics,broskoski/metaphysics,mzikherman/metaphysics-1,mzikherman/metaphysics-1,artsy/metaphysics,artsy/metaphysics
|
fd1b91a2cc219d27318d7b72a213a41c55fd1859
|
dataviva/static/js/modules/help.js
|
dataviva/static/js/modules/help.js
|
$('.sidebar a').on('click', function(){
$('.sidebar a').attr('class','');
$(this).toggleClass('active');
});
|
$('.sidebar a').on('click', function(){
$('.sidebar a').attr('class','');
$(this).toggleClass('active');
});
$("#home .col-md-6 > .panel-heading > h2 a").on('click', function(){
$('.sidebar a').attr('class','');
$('#sidebar_' + $(this).parent().parent()[0].id).toggleClass('active');
});
|
Add js funtion that maps tab-content to sidebar-menu.
|
Add js funtion that maps tab-content to sidebar-menu.
|
JavaScript
|
mit
|
DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site,DataViva/dataviva-site
|
6055bc4109f4ccc582095f912bf68fb796e6d63e
|
public/js/chrome/toppanel.js
|
public/js/chrome/toppanel.js
|
(function () {
/*global jsbin, $, $body*/
'use strict';
if (jsbin.settings.gui === undefined) {
jsbin.settings.gui = {};
}
if (jsbin.settings.gui.toppanel === undefined) {
jsbin.settings.gui.toppanel = true;
}
var removeToppanel = function() {
$body.addClass('toppanel-close');
$body.removeClass('toppanel');
};
var showToppanel = function() {
$body.removeClass('toppanel-close');
$body.addClass('toppanel');
};
// to remove
var goSlow = function(e) {
$body.removeClass('toppanel-slow');
if (e.shiftKey) {
$body.addClass('toppanel-slow');
}
};
$('.toppanel-hide').click(function(event) {
event.preventDefault();
goSlow(event);
jsbin.settings.gui.toppanel = false;
removeToppanel();
});
$('.toppanel-logo').click(function(event) {
event.preventDefault();
goSlow(event);
jsbin.settings.gui.toppanel = true;
showToppanel();
});
$document.keydown(function (event) {
if (event.which == 27) {
if ($body.hasClass('toppanel')) {
jsbin.settings.gui.toppanel = false;
removeToppanel();
}
}
});
}());
|
(function () {
/*global jsbin, $, $body, $document*/
'use strict';
if (jsbin.settings.gui === undefined) {
jsbin.settings.gui = {};
}
if (jsbin.settings.gui.toppanel === undefined) {
jsbin.settings.gui.toppanel = true;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
}
var removeToppanel = function() {
jsbin.settings.gui.toppanel = false;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.addClass('toppanel-close');
$body.removeClass('toppanel');
};
var showToppanel = function() {
jsbin.settings.gui.toppanel = true;
localStorage.setItem('settings', JSON.stringify(jsbin.settings));
$body.removeClass('toppanel-close');
$body.addClass('toppanel');
};
// to remove
var goSlow = function(e) {
$body.removeClass('toppanel-slow');
if (e.shiftKey) {
$body.addClass('toppanel-slow');
}
};
$('.toppanel-hide').click(function(event) {
event.preventDefault();
goSlow(event);
removeToppanel();
});
$('.toppanel-logo').click(function(event) {
event.preventDefault();
goSlow(event);
showToppanel();
});
$document.keydown(function (event) {
if (event.which == 27) {
if ($body.hasClass('toppanel')) {
removeToppanel();
}
}
});
}());
|
Save the state in localStorage
|
Save the state in localStorage
|
JavaScript
|
mit
|
IvanSanchez/jsbin,eggheadio/jsbin,yohanboniface/jsbin,jsbin/jsbin,vipulnsward/jsbin,KenPowers/jsbin,yize/jsbin,thsunmy/jsbin,jamez14/jsbin,martinvd/jsbin,ilyes14/jsbin,svacha/jsbin,remotty/jsbin,yize/jsbin,roman01la/jsbin,kirjs/jsbin,IvanSanchez/jsbin,yohanboniface/jsbin,mlucool/jsbin,kirjs/jsbin,filamentgroup/jsbin,minwe/jsbin,jamez14/jsbin,AverageMarcus/jsbin,mingzeke/jsbin,jasonsanjose/jsbin-app,francoisp/jsbin,thsunmy/jsbin,arcseldon/jsbin,fgrillo21/NPA-Exam,IveWong/jsbin,dennishu001/jsbin,dedalik/jsbin,mlucool/jsbin,pandoraui/jsbin,francoisp/jsbin,simonThiele/jsbin,ctide/jsbin,late-warrior/jsbin,saikota/jsbin,knpwrs/jsbin,blesh/jsbin,mingzeke/jsbin,HeroicEric/jsbin,saikota/jsbin,ctide/jsbin,mcanthony/jsbin,dedalik/jsbin,eggheadio/jsbin,johnmichel/jsbin,IveWong/jsbin,minwe/jsbin,fgrillo21/NPA-Exam,jwdallas/jsbin,juliankrispel/jsbin,y3sh/jsbin-fork,carolineartz/jsbin,vipulnsward/jsbin,roman01la/jsbin,ilyes14/jsbin,KenPowers/jsbin,juliankrispel/jsbin,simonThiele/jsbin,kentcdodds/jsbin,jwdallas/jsbin,knpwrs/jsbin,kentcdodds/jsbin,fend-classroom/jsbin,y3sh/jsbin-fork,johnmichel/jsbin,fend-classroom/jsbin,dhval/jsbin,KenPowers/jsbin,svacha/jsbin,mdo/jsbin,dhval/jsbin,late-warrior/jsbin,dennishu001/jsbin,jsbin/jsbin,AverageMarcus/jsbin,martinvd/jsbin,Freeformers/jsbin,peterblazejewicz/jsbin,carolineartz/jsbin,arcseldon/jsbin,HeroicEric/jsbin,filamentgroup/jsbin,Hamcha/jsbin,Hamcha/jsbin,mcanthony/jsbin,jasonsanjose/jsbin-app,digideskio/jsbin,peterblazejewicz/jsbin,knpwrs/jsbin,Freeformers/jsbin,pandoraui/jsbin,digideskio/jsbin
|
0a4fba655f4030f0b4b5d244416510086c0ae419
|
public/main/utils/updates.js
|
public/main/utils/updates.js
|
define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.location.host].join('');
logging.log("Connexion to "+this.url);
this.socket = io.connect(this.url);
// Video streaming stats
this.socket.on('stats', function(data) {
//logging.log("streaming stats ", data);
this.trigger("streaming:stats", data);
});
// Remote control connected
this.socket.on('remote', _.bind(function() {
logging.log("remote is connected");
this.trigger("remote:start");
}, this));
// Touch input from remote
this.socket.on('remote_input', _.bind(function(data) {
logging.log("remote input ", data);
this.trigger("remote:input", data);
}, this));
// Search from remote
this.socket.on('remote_search', _.bind(function(q) {
logging.log("remote search ", q);
this.trigger("remote:search", q);
yapp.History.navigate("search/:q", {
"q": q
});
}, this));
// Connexion error
this.socket.on('error', _.bind(function(data) {
logging.error("error in socket.io")
}, this));
return this;
},
}));
return Updates;
});
|
define([
"Underscore",
"yapp/yapp",
"vendors/socket.io"
], function(_, yapp, io) {
var logging = yapp.Logger.addNamespace("updates");
var Updates = new (yapp.Class.extend({
/* Constructor */
initialize: function() {
this.url = [window.location.protocol, '//', window.location.host].join('');
logging.log("Connexion to "+this.url);
this.socket = io.connect(this.url);
// Video streaming stats
this.socket.on('stats', _.bind(function(data) {
//logging.log("streaming stats ", data);
this.trigger("streaming:stats", data);
}, this));
// Remote control connected
this.socket.on('remote', _.bind(function() {
logging.log("remote is connected");
this.trigger("remote:start");
}, this));
// Touch input from remote
this.socket.on('remote_input', _.bind(function(data) {
logging.log("remote input ", data);
this.trigger("remote:input", data);
}, this));
// Search from remote
this.socket.on('remote_search', _.bind(function(q) {
logging.log("remote search ", q);
this.trigger("remote:search", q);
yapp.History.navigate("search/:q", {
"q": q
});
}, this));
// Connexion error
this.socket.on('error', _.bind(function(data) {
logging.error("error in socket.io")
}, this));
return this;
},
}));
return Updates;
});
|
Correct error in client for streaming
|
Correct error in client for streaming
|
JavaScript
|
apache-2.0
|
mafintosh/tv.js,thefkboss/tv.js,SamyPesse/tv.js,thefkboss/tv.js,mafintosh/tv.js,SamyPesse/tv.js,thefkboss/tv.js
|
15607d784bd426fa22789beaf42b6625e0c606c0
|
src/chart/candlestick/candlestickVisual.js
|
src/chart/candlestick/candlestickVisual.js
|
define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return function (ecModel, api) {
ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
var data = seriesModel.getData();
data.setVisual({
legendSymbol: 'roundRect'
});
// Only visible series has each data be visual encoded
if (!ecModel.isSeriesFiltered(seriesModel)) {
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
var sign = data.getItemLayout(idx).sign;
data.setItemVisual(
idx,
{
color: itemModel.get(
sign > 0 ? positiveColorQuery : negativeColorQuery
),
borderColor: itemModel.get(
sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
)
}
);
});
}
});
};
});
|
define(function (require) {
var positiveBorderColorQuery = ['itemStyle', 'normal', 'borderColor'];
var negativeBorderColorQuery = ['itemStyle', 'normal', 'borderColor0'];
var positiveColorQuery = ['itemStyle', 'normal', 'color'];
var negativeColorQuery = ['itemStyle', 'normal', 'color0'];
return function (ecModel, api) {
ecModel.eachRawSeriesByType('candlestick', function (seriesModel) {
var data = seriesModel.getData();
data.setVisual({
legendSymbol: 'roundRect'
});
// Only visible series has each data be visual encoded
if (!ecModel.isSeriesFiltered(seriesModel)) {
data.each(function (idx) {
var itemModel = data.getItemModel(idx);
var openVal = data.get('open', idx);
var closeVal = data.get('close', idx);
var sign = openVal > closeVal ? -1 : openVal < closeVal ? 1 : 0;
data.setItemVisual(
idx,
{
color: itemModel.get(
sign > 0 ? positiveColorQuery : negativeColorQuery
),
borderColor: itemModel.get(
sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
)
}
);
});
}
});
};
});
|
Remove layout dependency in candlestick visual
|
Remove layout dependency in candlestick visual
|
JavaScript
|
apache-2.0
|
hexj/echarts,ecomfe/echarts,ecomfe/echarts,apache/incubator-echarts,chenfwind/echarts,hexj/echarts,100star/echarts,chenfwind/echarts,hexj/echarts,starlkj/echarts,starlkj/echarts,starlkj/echarts,apache/incubator-echarts,100star/echarts
|
5a98f2a4874d47da9e05a56eae3018e911fc30f1
|
src/components/demos/DigitalLines/index.js
|
src/components/demos/DigitalLines/index.js
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
class DigitalLines {
static propTypes = {
};
canvasRender() {
};
componentDidMount() {
// Get a reference to the canvas object
var canvas = document.getElementById('digitalLinesCanvas');
// Create an empty project and a view for the canvas:
paper.setup(canvas);
// Create a Paper.js Path to draw a line into it:
var path = new paper.Path();
// Give the stroke a color
path.strokeColor = 'black';
var start = new paper.Point(100, 100);
// Move to start and draw a line from there
path.moveTo(start);
// Note that the plus operator on Point objects does not work
// in JavaScript. Instead, we need to call the add() function:
path.lineTo(start.add([ 200, -50 ]));
// Draw the view now:
paper.view.draw();
};
componentWillUpdate() {
};
render() {
return (
<div className="DigitalLines">
Hello World!
<canvas width="800" height="400" id="digitalLinesCanvas" />
</div>
);
}
}
export default {
name: 'Digital Lines',
key: 'digitalLines',
author: 'Josh',
technologies: [],
component: DigitalLines
};
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { PropTypes } from 'react';
class Line {
constructor() {
try {
this.path = new paper.Path();
this.path.fillColor = undefined;
this.path.strokeColor = 'green';
this.path.strokeWidth = 2;
// Left side
var cur = new paper.Point(0, Math.random() * 500);
this.path.moveTo(cur);
while (cur.x < 800)
{
cur = cur.add(new paper.Point(Math.random() * 50 + 25, Math.random() * 50 - 25));
this.path.lineTo(cur);
}
this.path.smooth();
}catch (e) {
console.log(e);
};
}
};
class DigitalLines {
static propTypes = {
};
canvasRender() {
};
componentDidMount() {
// Get a reference to the canvas object
var canvas = document.getElementById('digitalLinesCanvas'),
lines = [];
// Create an empty project and a view for the canvas:
paper.setup(canvas);
for (var i = 0; i < 10; i++)
lines.push(new Line());
path.view.onFrame = function (event) {
};
// Draw the view now:
paper.view.draw();
};
componentWillUpdate() {
};
render() {
return (
<div className="DigitalLines">
Hello World!
<canvas width="800" height="400" id="digitalLinesCanvas" />
</div>
);
}
}
export default {
name: 'Digital Lines',
key: 'digitalLines',
author: 'Josh',
technologies: [],
component: DigitalLines
};
|
Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves.
|
Update to DigitalLines. Taking a slight mental transition to learn about Bezier Curves.
|
JavaScript
|
mit
|
jung-digital/jd-demos,jung-digital/jd-demos
|
c951d161be8d2faf6e497d80e69998aa49a445bd
|
desktop/tests/database.spec.js
|
desktop/tests/database.spec.js
|
const assert = require('assert');
const parse = require('../app/shared/database/parse');
describe('database', () => {
describe('parse.js', () => {
const testQuery = 'Learn something! @3+2w !';
it('should return correct task text', () => {
assert(parse(testQuery).text === 'Learn something!');
});
it('should return correct starting point', () => {
assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000);
});
it('should return correct ending point', () => {
assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000);
});
it('should return correct importance', () => {
assert(parse(testQuery).importance === 2);
});
it('should return correct status', () => {
assert(parse(testQuery).status === 0);
});
});
});
|
const assert = require('assert');
const parse = require('../app/shared/database/parse');
describe('database', () => {
describe('parse.js', () => {
const testQuery = 'Learn something! @3+2w !';
it('should return task text', () => {
assert(parse(testQuery).text === 'Learn something!');
});
it('should return starting point', () => {
assert(parse(testQuery).start < Date.now() + (14 * 86400000) + 1000);
});
it('should return ending point', () => {
assert(parse(testQuery).end < Date.now() + (17 * 86400000) + 1000);
});
it('should return importance', () => {
assert(parse(testQuery).importance === 2);
});
it('should return status', () => {
assert(parse(testQuery).status === 0);
});
});
});
|
Remove "correct" word from test titles
|
Remove "correct" word from test titles
|
JavaScript
|
mit
|
mkermani144/wanna,mkermani144/wanna
|
b1f3c2110910665038b5d4738d225009b21530f1
|
plugins/knowyourmeme.js
|
plugins/knowyourmeme.js
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Know Your Meme',
version:'0.1',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'a img.small',
'/small/',
'/original/'
);
callback($(res));
}
});
|
var hoverZoomPlugins = hoverZoomPlugins || [];
hoverZoomPlugins.push({
name:'Know Your Meme',
version:'0.2',
prepareImgLinks:function (callback) {
var res = [];
hoverZoom.urlReplace(res,
'a img.small',
'/small/',
'/original/'
);
hoverZoom.urlReplace(res,
'img[src]',
['/list/', '/masonry/', '/medium/', '/newsfeed/', '/tiny/'],
['/original/', '/original/', '/original/', '/original/', '/original/']
);
callback($(res), this.name);
}
});
|
Update for plug-in : KnowYourMeme
|
Update for plug-in : KnowYourMeme
|
JavaScript
|
mit
|
extesy/hoverzoom,extesy/hoverzoom
|
4177d6050ef41c70dc25a34ee32e43984e77f461
|
visualizer/index.js
|
visualizer/index.js
|
'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
module.exports = function (trees, opts) {
opts = opts || {}
const { kernelTracing } = opts
const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init'])
const chart = graph()
const tree = trees.unmerged // default view
const categorizer = !kernelTracing && graph.v8cats
const flamegraph = fg({
categorizer,
tree,
exclude: Array.from(exclude),
element: chart
})
const { colors } = flamegraph
window.addEventListener('resize', debounce(() => {
const width = document.body.clientWidth * 0.89
flamegraph.width(width).update()
chart.querySelector('svg').setAttribute('width', width)
}, 150))
const state = createState({colors, trees, exclude, kernelTracing, title: opts.title})
const actions = createActions({flamegraph, state}, (state) => {
morphdom(iface, ui({state, actions}))
})
const iface = ui({state, actions})
document.body.appendChild(chart)
document.body.appendChild(iface)
}
|
'use strict'
const fg = require('d3-fg')
const render = require('nanohtml')
const morphdom = require('morphdom')
const debounce = require('debounce')
const createActions = require('./actions')
const createState = require('./state')
const graph = require('./cmp/graph')(render)
const ui = require('./cmp/ui')(render)
module.exports = function (trees, opts) {
opts = opts || {}
const { kernelTracing } = opts
const exclude = new Set(['cpp', 'regexp', 'v8', 'native', 'init'])
const chart = graph()
const tree = trees.unmerged // default view
const categorizer = !kernelTracing && graph.v8cats
const flamegraph = fg({
categorizer,
tree,
exclude: Array.from(exclude),
element: chart,
topOffset: 55
})
const { colors } = flamegraph
window.addEventListener('resize', debounce(() => {
const width = document.body.clientWidth * 0.89
flamegraph.width(width).update()
chart.querySelector('svg').setAttribute('width', width)
}, 150))
const state = createState({colors, trees, exclude, kernelTracing, title: opts.title})
const actions = createActions({flamegraph, state}, (state) => {
morphdom(iface, ui({state, actions}))
})
const iface = ui({state, actions})
document.body.appendChild(chart)
document.body.appendChild(iface)
}
|
Add top offset to prevent top bar from cropping the top stack
|
Add top offset to prevent top bar from cropping the top stack
|
JavaScript
|
mit
|
davidmarkclements/0x
|
e9bd0c16bda4221a420a9206c239e06b44a5911f
|
addon/index.js
|
addon/index.js
|
import Ember from 'ember';
Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, {
id: "ember-getowner-polyfill.import"
});
export default Ember.getOwner;
|
import Ember from 'ember';
Ember.deprecate("ember-getowner-polyfill is now a true polyfill. Use Ember.getOwner directly instead of importing from ember-getowner-polyfill", false, {
id: "ember-getowner-polyfill.import",
until: '3.0.0'
});
export default Ember.getOwner;
|
Add option.until to prevent extra deprecation
|
Add option.until to prevent extra deprecation
|
JavaScript
|
mit
|
rwjblue/ember-getowner-polyfill,rwjblue/ember-getowner-polyfill
|
5ddc15870172cabe4a362fa338dd804f6b1264e2
|
src/components/Media/Media.js
|
src/components/Media/Media.js
|
import React from 'react';
import classnames from 'classnames';
const Media = (props) => {
const children = props.children;
return (
<div className={classnames('ui-media')}>
{children}
</div>
);
};
Media.propTypes = {
children: React.PropTypes.node,
};
export default Media;
|
import React from 'react';
import classnames from 'classnames';
const Media = ({ compact, children }) => {
const className = classnames('ui-media', {
'ui-media-compact': compact,
});
return (
<div className={className}>
{children}
</div>
);
};
Media.propTypes = {
children: React.PropTypes.node,
compact: React.PropTypes.bool,
};
Media.defaultProps = {
compact: false,
children: null,
};
export default Media;
|
Introduce compact prop for media component
|
Introduce compact prop for media component
|
JavaScript
|
mit
|
wundery/wundery-ui-react,wundery/wundery-ui-react
|
85367a62999ef6be0e34556cd71d54871c98dc19
|
worker/index.js
|
worker/index.js
|
'use strict';
const config = require('config');
const logger = require('../modules').logger;
const rollbarHelper = require('../modules').rollbarHelper;
const invalidator = require('./invalidator');
const opendata = require('./opendata');
function shutdown() {
logger.info('[WORKER] Ending');
setTimeout(process.exit, config.worker.exit_timeout);
}
if (!module.parent) {
require('../modules').mongooseHelper.connect()
.then(() => rollbarHelper.init())
.then(() => {
invalidator.start();
opendata.start();
logger.info('[WORKER] Started');
})
.catch(err => {
logger.error(err, '[WORKER] Uncaught error');
rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception');
shutdown();
});
process.on('SIGTERM', shutdown);
}
module.exports = {
opendata
};
|
'use strict';
const config = require('config');
const logger = require('../modules').logger;
const mongooseHelper = require('../modules').mongooseHelper;
const rollbarHelper = require('../modules').rollbarHelper;
const invalidator = require('./invalidator');
const opendata = require('./opendata');
function shutdown() {
logger.info('[WORKER] Ending');
setTimeout(process.exit, config.worker.exit_timeout);
}
if (!module.parent) {
rollbarHelper.init()
.then(() => mongooseHelper.connect())
.then(() => {
invalidator.start();
opendata.start();
logger.info('[WORKER] Started');
})
.catch(err => {
logger.error(err, '[WORKER] Uncaught error');
rollbarHelper.rollbar.handleError(err, '[WORKER] Uncaught exception');
shutdown();
});
process.on('SIGTERM', shutdown);
}
module.exports = {
opendata
};
|
Initialize rollbar before mongoose in worker
|
Initialize rollbar before mongoose in worker
|
JavaScript
|
mit
|
carparker/carparker-server
|
bf79820c7a37188c9e66c912eb9a66ad45ecc7ad
|
app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js
|
app/javascript/app/pages/sectors-agriculture/sectors-agricuture-selectors.js
|
import { createSelector } from 'reselect';
// import omit from 'lodash/omit';
// import qs from 'query-string';
const getSections = routeData => routeData.route.sections || null;
// const getSearch = routeData => routeData.location.search || null;
// const getHash = routeData => routeData.hash || null;
// const getRoutes = routeData => routeData.route.routes || null;
export const getAnchorLinks = createSelector([getSections], sections =>
sections.filter(route => route.anchor).map(route => ({
label: route.label,
path: route.path,
hash: route.hash,
component: route.component
}))
);
// export const getRouteLinks = createSelector(
// [getRoutes, getHash, getSearch],
// (routes, hash, search) =>
// routes &&
// routes.filter(r => r.anchor).map(route => ({
// label: route.label,
// path: route.path,
// search: qs.stringify(omit(qs.parse(search), 'search')), // we want to reset the search on tabs change
// hash
// }))
// );
export default {
getAnchorLinks
// getRouteLinks
};
|
import { createSelector } from 'reselect';
const getSections = routeData => routeData.route.sections || null;
export const getAnchorLinks = createSelector([getSections], sections =>
sections.filter(route => route.anchor).map(route => ({
label: route.label,
path: route.path,
hash: route.hash,
component: route.component
}))
);
export default {
getAnchorLinks
};
|
Remove commented code from agriculture selectors
|
Remove commented code from agriculture selectors
|
JavaScript
|
mit
|
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
|
ed3c72146dad8baa293755c8732f3ad0ef9581f2
|
eloquent_js/chapter11/ch11_ex02.js
|
eloquent_js/chapter11/ch11_ex02.js
|
function Promise_all(promises) {
return new Promise((resolve, reject) => {
let ctr = promises.length;
let resArray = [];
if (ctr === 0) resolve(resArray);
for (let idx = 0; idx < promises.length; ++idx) {
promises[idx].then(result => {
resArray[idx] = result;
--ctr;
if (ctr === 0) resolve(resArray);
}, reject);
}
});
}
|
function Promise_all(promises) {
return new Promise((resolve, reject) => {
let result = [];
let unresolved = promises.length;
if (unresolved == 0) resolve(result);
for (let i = 0; i < promises.length; ++i) {
promises[i]
.then(value => {
result[i] = value;
--unresolved;
if (unresolved == 0) resolve(result);
})
.catch(error => reject(error));
}
});
}
|
Add chapter 11, exercise 2
|
Add chapter 11, exercise 2
|
JavaScript
|
mit
|
bewuethr/ctci
|
c4bb41471441da921da9c2dc9515e662619fef5b
|
public/javascripts/checker.js
|
public/javascripts/checker.js
|
var socket = io.connect('/');
var waitMilliSec = 1000;
var oldJavaCode = '';
var oldClassName = '';
socket.on('byte_code', function(data) {
$('#output_bc').val(data.code);
});
socket.on('wrong', function(data) {
$('#output_bc').val(data.err);
});
$(function() {
var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), {
mode: 'clike',
lineNumbers: true
});
var idleIntervalId = setInterval(function() {
newJavaCode = inputJavaCM.getValue();
newClassName = $('#class_name').val();
checkDiff(newJavaCode, newClassName);
} , waitMilliSec);
function checkDiff(newJavaCode, newClassName) {
if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) {
socket.emit('code_sent', {
code: newJavaCode,
className: newClassName
});
oldJavaCode = newJavaCode;
oldClassName = newClassName;
}
}
});
|
var socket = io.connect('/');
var waitMilliSec = 1000;
var oldJavaCode = '';
var oldClassName = '';
var outputBcCM;
socket.on('byte_code', function(data) {
outputBcCM.setValue(data.code);
});
socket.on('wrong', function(data) {
outputBcCM.setValue(data.err);
});
$(function() {
var inputJavaCM = CodeMirror.fromTextArea(document.getElementById('input_java'), {
mode: 'clike',
lineNumbers: true
});
outputBcCM = CodeMirror.fromTextArea(document.getElementById('output_bc'), {
mode: 'clike',
lineNumbers: true
});
var idleIntervalId = setInterval(function() {
newJavaCode = inputJavaCM.getValue();
newClassName = $('#class_name').val();
checkDiff(newJavaCode, newClassName);
} , waitMilliSec);
function checkDiff(newJavaCode, newClassName) {
if((newJavaCode != oldJavaCode) || (newClassName != oldClassName)) {
socket.emit('code_sent', {
code: newJavaCode,
className: newClassName
});
oldJavaCode = newJavaCode;
oldClassName = newClassName;
}
}
});
|
Apply CodeMirror to output textarea.
|
Apply CodeMirror to output textarea.
|
JavaScript
|
mit
|
Java2ByteCode/InstantBytecode,Java2ByteCode/InstantBytecode
|
d3d7932eb1c067b2a403e0260c87192940565964
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
gulp.task('mock-server', function() {
nodemon({
script: 'server.js'
, ext: 'js json'
, env: { 'NODE_ENV': 'development' }
})
});
|
var gulp = require('gulp');
var nodemon = require('gulp-nodemon');
gulp.task('default', function() {
nodemon({
script: 'server.js'
, ext: 'js json'
, env: { 'NODE_ENV': 'development' }
})
});
|
Set gulp task as default
|
Set gulp task as default
|
JavaScript
|
mit
|
isuru88/lazymine-mock-server
|
e1fb651837436053b24b9198a5d62ba869090297
|
gulpfile.js
|
gulpfile.js
|
var gulp = require('gulp');
var uglify = require('gulp-uglify');
gulp.task('default', function() {
gulp.src('lib/fs.js')
.pipe(uglify())
.pipe(gulp.dest('build'));
});
|
var gulp = require('gulp');
var uglify = require('gulp-uglify');
var babel = require('gulp-babel');
var sourcemaps = require('gulp-sourcemaps');
var rename = require('gulp-rename');
gulp.task('default', function() {
gulp.src('src/fs.js')
.pipe(sourcemaps.init())
.pipe(babel())
.pipe(uglify())
.pipe(rename('fs.min.js'))
.pipe(sourcemaps.write('.'))
.pipe(gulp.dest('dist'));
});
|
Update default task for compile prod code
|
1.2.2: Update default task for compile prod code
|
JavaScript
|
mit
|
wangpin34/fs-h5,wangpin34/fs-h5
|
83cc95b851a39cd3952fa105272a750e0a147dee
|
addons/notes/src/__tests__/index.js
|
addons/notes/src/__tests__/index.js
|
import addons from '@storybook/addons';
import { withNotes } from '..';
jest.mock('@storybook/addons');
describe('Storybook Addon Notes', () => {
it('should inject info', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = {};
const decoratedStory = withNotes('hello')(getStory);
decoratedStory(context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
});
|
import addons from '@storybook/addons';
import { withNotes } from '..';
jest.mock('@storybook/addons');
describe('Storybook Addon Notes', () => {
it('should inject text from `notes` parameter', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: { notes: 'hello' } };
withNotes(getStory, context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
it('should inject markdown from `notes.markdown` parameter', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: { notes: { markdown: '# hello' } } };
withNotes(getStory, context);
expect(channel.emit).toHaveBeenCalledWith(
'storybook/notes/add_notes',
expect.stringContaining('<h1 id="hello">hello</h1>')
);
expect(getStory).toHaveBeenCalledWith(context);
});
it('should inject info (deprecated API)', () => {
const channel = { emit: jest.fn() };
addons.getChannel.mockReturnValue(channel);
const getStory = jest.fn();
const context = { parameters: {} };
const decoratedStory = withNotes('hello')(getStory);
decoratedStory(context);
expect(channel.emit).toHaveBeenCalledWith('storybook/notes/add_notes', 'hello');
expect(getStory).toHaveBeenCalledWith(context);
});
});
|
Update tests with new API
|
Update tests with new API
|
JavaScript
|
mit
|
rhalff/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,storybooks/storybook,storybooks/storybook,rhalff/storybook,kadirahq/react-storybook,storybooks/storybook,storybooks/storybook,kadirahq/react-storybook,rhalff/storybook,storybooks/storybook,storybooks/react-storybook,storybooks/storybook,rhalff/storybook,storybooks/react-storybook,rhalff/storybook
|
721faf4dd71bef6ee170e3b029dc52ac8f9055a1
|
src/sprites/object/PineCone/place.js
|
src/sprites/object/PineCone/place.js
|
import { treeGrow as growChance } from '../../../game-data/chances';
import { tryChance } from '../../../utils';
import { fastMap } from '../../../world';
import objectPool from '../../../object-pool';
import Phaser from 'phaser';
import Tree from '../Tree';
export default function place() {
this.placed = true;
this.changeType('planted-pine-cone');
this.game.time.events.add(Phaser.Timer.SECOND * 5, function() {
if (this.destroyed) return;
const playerTile = this.game.state.states.Game.player.tile;
const thisTile = this.tile;
if (
(playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) &&
fastMap[thisTile.x + ',' + thisTile.y].length === 1 && // this pine cone should be only thing on tile
tryChance(growChance)
) {
objectPool.new('tree', Tree, {
game: this.game,
x: this.x,
y: this.y,
});
this.destroy();
} else {
place.call(this);
}
}, this);
}
|
import { treeGrow as growChance } from '../../../game-data/chances';
import { tryChance } from '../../../utils';
import { fastMap } from '../../../world';
import objectPool from '../../../object-pool';
import Phaser from 'phaser';
import Tree from '../Tree';
export default function place() {
this.placed = true;
this.changeType('planted-pine-cone');
this.game.time.events.add(Phaser.Timer.SECOND * 5, function() {
if (this.destroyed) return;
const playerTile = this.game.state.states.Game.player.tile;
const thisTile = this.tile;
if (
(playerTile.x !== thisTile.x || playerTile.y !== thisTile.y) &&
fastMap[thisTile.y][thisTile.x].length === 1 && // this pine cone should be only thing on tile
tryChance(growChance)
) {
objectPool.new('tree', Tree, {
game: this.game,
x: this.x,
y: this.y,
});
this.destroy();
} else {
place.call(this);
}
}, this);
}
|
Fix using old map format
|
Fix using old map format
|
JavaScript
|
mit
|
ThomasMays/incremental-forest,ThomasMays/incremental-forest
|
ff58f96f6579d583f8f44db8e9c91260cf2ae5a7
|
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
|
ocw-ui/frontend-new/test/spec/filters/isodatetomiddleendian.js
|
'use strict';
describe('Filter: ISODateToMiddleEndian', function () {
// load the filter's module
beforeEach(module('ocwUiApp'));
// initialize a new instance of the filter before each test
var ISODateToMiddleEndian;
beforeEach(inject(function ($filter) {
ISODateToMiddleEndian = $filter('ISODateToMiddleEndian');
}));
it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () {
var text = 'angularjs';
expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text);
});
});
|
/**
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http: *www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
'use strict';
describe('Filter: ISODateToMiddleEndian', function () {
// load the filter's module
beforeEach(module('ocwUiApp'));
// initialize a new instance of the filter before each test
var ISODateToMiddleEndian;
beforeEach(inject(function ($filter) {
ISODateToMiddleEndian = $filter('ISODateToMiddleEndian');
}));
it('should return the input prefixed with "ISODateToMiddleEndian filter:"', function () {
var text = 'angularjs';
expect(ISODateToMiddleEndian(text)).toBe('ISODateToMiddleEndian filter: ' + text);
});
});
|
Add ASF license headers to filter tests
|
Add ASF license headers to filter tests
|
JavaScript
|
apache-2.0
|
kwhitehall/climate,pwcberry/climate,MJJoyce/climate,jarifibrahim/climate,riverma/climate,lewismc/climate,apache/climate,apache/climate,huikyole/climate,MJJoyce/climate,agoodm/climate,agoodm/climate,jarifibrahim/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,MJJoyce/climate,agoodm/climate,lewismc/climate,jarifibrahim/climate,pwcberry/climate,agoodm/climate,riverma/climate,MBoustani/climate,lewismc/climate,Omkar20895/climate,lewismc/climate,pwcberry/climate,apache/climate,kwhitehall/climate,riverma/climate,Omkar20895/climate,agoodm/climate,kwhitehall/climate,MJJoyce/climate,pwcberry/climate,MBoustani/climate,huikyole/climate,Omkar20895/climate,huikyole/climate,kwhitehall/climate,riverma/climate,riverma/climate,MBoustani/climate,MBoustani/climate,pwcberry/climate,apache/climate,huikyole/climate,Omkar20895/climate,jarifibrahim/climate,MJJoyce/climate,jarifibrahim/climate,huikyole/climate,apache/climate
|
7b8c50c247a6ea4b382fb59f83c0c2a7473b9fbc
|
src/Input/TouchInput.js
|
src/Input/TouchInput.js
|
function TouchInput(inputController) {
this.inputController = inputController;
}
TouchInput.prototype.listen = function() {
document.addEventListener('touchstart', this.startTouch.bind(this));
document.addEventListener('touchmove', this.detectSwipe.bind(this));
};
TouchInput.prototype.startTouch = function(event) {
this.xStart = event.touches[0].clientX;
this.yStart = event.touches[0].clientY;
};
TouchInput.prototype.detectSwipe = function(event) {
if( this.xStart === null || this.yStart === null) {
return;
}
var xEnd = event.touches[0].clientX;
var yEnd = event.touches[0].clientY;
var deltaX = xEnd - this.xStart;
var deltaY = yEnd - this.yStart;
var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY);
if(isHorizontalSwipe) {
deltaX < 0 ? this.inputController.left(): this.inputController.right();
} else if(deltaY > 0) {
this.inputController.down();
}
this.xStart = null;
this.yStart = null;
};
|
function TouchInput(inputController, element) {
this.inputController = inputController;
this.element = typeof element !== 'undefined' ? element : document;
}
TouchInput.prototype.listen = function() {
this.element.addEventListener('touchstart', this.startTouch.bind(this));
this.element.addEventListener('touchmove', this.detectSwipe.bind(this));
};
TouchInput.prototype.startTouch = function(event) {
this.xStart = event.touches[0].clientX;
this.yStart = event.touches[0].clientY;
};
TouchInput.prototype.detectSwipe = function(event) {
if( this.xStart === null || this.yStart === null) {
return;
}
var xEnd = event.touches[0].clientX;
var yEnd = event.touches[0].clientY;
var deltaX = xEnd - this.xStart;
var deltaY = yEnd - this.yStart;
var isHorizontalSwipe = Math.abs(deltaX) > Math.abs(deltaY);
if(isHorizontalSwipe) {
deltaX < 0 ? this.inputController.left(): this.inputController.right();
} else if(deltaY > 0) {
this.inputController.down();
}
this.xStart = null;
this.yStart = null;
};
|
Add element binding to touch input
|
Add element binding to touch input
|
JavaScript
|
mit
|
mnito/factors-game,mnito/factors-game
|
e3f9fd07b08f30067d055dcbb1ce2558c776f81e
|
src/controllers/SpotifyController.js
|
src/controllers/SpotifyController.js
|
if (!!document.querySelector('#app-player')) { // Old Player
controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
frameSelector: '#app-player',
playStateSelector: '#play-pause',
playStateClass: 'playing',
playPauseSelector: '#play-pause',
nextSelector: '#next',
previousSelector: '#previous',
titleSelector: '#track-name',
artistSelector: '#track-artist'
});
controller.override('getAlbumArt', function() {
return document.querySelector(this.frameSelector).contentDocument.querySelector('#cover-art .sp-image-img').style.backgroundImage.slice(4, -1);
});
} else { // New Player
controller = new BasicController({
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
frameSelector: '#main',
playStateSelector: '#play',
playStateClass: 'playing',
playPauseSelector: '#play',
nextSelector: '#next',
previousSelector: '#previous',
titleSelector: '.caption .track',
artistSelector: '.caption .artist'
});
controller.override('getAlbumArt', function() {
return document.querySelector(this.frameSelector).contentDocument.querySelector('#large-cover-image').style.backgroundImage.slice(4, -1);
});
}
|
var config = {
supports: {
playpause: true,
next: true,
previous: true
},
useLazyObserving: true,
playStateClass: 'playing',
nextSelector: '#next',
previousSelector: '#previous'
}
if (document.querySelector('#app-player')) { // Old Player
config.artworkImageSelector = '#cover-art .sp-image-img';
config.frameSelector = '#app-player';
config.playStateSelector = '#play-pause';
config.playPauseSelector = '#play-pause';
config.titleSelector = '#track-name';
config.artistSelector = '#track-artist';
} else { // New Player
config.artworkImageSelector = '#large-cover-image';
config.frameSelector = '#main';
config.playStateSelector = '#play';
config.playPauseSelector = '#pause';
config.titleSelector = '.caption .track';
config.artistSelector = '.caption .artist';
}
controller = new BasicController(config);
controller.override('getAlbumArt', function() {
var img = this.doc().querySelector(this.artworkImageSelector);
return img && img.style.backgroundImage.slice(5, -2);
});
|
Fix album art retrieved from Spotify
|
Fix album art retrieved from Spotify
Remove double quotes around image URL retrieved from Spotify
by slicing one character more from left and one character
more from right.
Also, remove redundant code and null errors to console when
element is not found.
Signed-off-by: Tomas Slusny <71c4488fd0941e24cd13e3ad13ef1eb0a5fe5168@gmail.com>
|
JavaScript
|
agpl-3.0
|
msfeldstein/chrome-media-keys,PeterMinin/chrome-media-keys,PeterMinin/chrome-media-keys
|
9bec9dd156f97a1d00bf57a5badedebece295844
|
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
|
packages/@sanity/form-builder/src/inputs/BlockEditor-slate/toolbar/LinkButton.js
|
import React, {PropTypes} from 'react'
import ToggleButton from 'part:@sanity/components/toggles/button'
import LinkIcon from 'part:@sanity/base/sanity-logo-icon'
import styles from './styles/LinkButton.css'
export default class LinkButton extends React.Component {
static propTypes = {
onClick: PropTypes.func,
activeLink: PropTypes.bool
}
handleToggleButtonClick = () => {
this.props.onClick(this.props.activeLink)
}
render() {
return (
<div style={{position: 'relative'}}>
<ToggleButton
onClick={this.handleToggleButtonClick}
title={'Link'}
className={styles.button}
>
<div className={styles.iconContainer}>
<LinkIcon />
</div>
</ToggleButton>
</div>
)
}
}
|
import React, {PropTypes} from 'react'
import ToggleButton from 'part:@sanity/components/toggles/button'
import LinkIcon from 'part:@sanity/base/link-icon'
import styles from './styles/LinkButton.css'
export default class LinkButton extends React.Component {
static propTypes = {
onClick: PropTypes.func,
activeLink: PropTypes.bool
}
handleToggleButtonClick = () => {
this.props.onClick(this.props.activeLink)
}
render() {
const {activeLink} = this.props
return (
<div style={{position: 'relative'}}>
<ToggleButton
onClick={this.handleToggleButtonClick}
title={'Link'}
selected={activeLink}
className={styles.button}
>
<div className={styles.iconContainer}>
<LinkIcon />
</div>
</ToggleButton>
</div>
)
}
}
|
Use link icon for link button
|
[form-builder] Use link icon for link button
|
JavaScript
|
mit
|
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
|
1aa3c6485e5c6d04480332e64ee848930fcbba70
|
configurations/react.js
|
configurations/react.js
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/self-closing-comp": 2,
"react/wrap-multilines": 2
}
};
|
module.exports = {
"extends": "justinlocsei/configurations/es6",
"ecmaFeatures": {
"jsx": true
},
"env": {
"browser": true
},
"plugins": [
"react"
],
"rules": {
"jsx-quotes": [2, "prefer-double"],
"react/jsx-boolean-value": [2, "always"],
"react/jsx-curly-spacing": [2, "never"],
"react/jsx-handler-names": 2,
"react/jsx-no-bind": 2,
"react/jsx-no-duplicate-props": [2, {"ignoreCase": true}],
"react/jsx-no-undef": 2,
"react/jsx-pascal-case": 2,
"react/jsx-uses-vars": 2,
"react/jsx-wrap-multilines": 2,
"react/no-did-mount-set-state": 2,
"react/no-did-update-set-state": 2,
"react/no-direct-mutation-state": 2,
"react/no-multi-comp": 2,
"react/no-unknown-property": 2,
"react/prop-types": 2,
"react/self-closing-comp": 2
}
};
|
Update the named of a renamed React check
|
Update the named of a renamed React check
|
JavaScript
|
mit
|
justinlocsei/eslint-config-chiton
|
19b9def70f2bb1e827ba428527ebab8910ac46e2
|
app/documents/controllers/SearchController.js
|
app/documents/controllers/SearchController.js
|
module.exports = function($scope, $state, $location, $http, GlobalService,
DocumentService, DocumentApiService, MathJaxService, QueryParser) {
$scope.doSearch = function(){
var apiServer = GlobalService.apiServer()
var query = QueryParser.parse($scope.searchText)
console.log('query = ' + query)
$http.get('http://' + apiServer + '/v1/documents' + '?' + query )
.then(function(response){
console.log(response.data['status'])
console.log('Number of documents: ' + response.data['document_count'])
var jsonData = response.data
var documents = jsonData['documents']
DocumentService.setDocumentList(documents)
var id = documents[0]['id']
console.log('SearchController, id: ' + id)
DocumentApiService.getDocument(id)
.then(function(response) {
console.log('CURRENT STATE: ' + $state.current)
$state.go('documents')
$state.reload()
$scope.$watch(function(scope) {
return $scope.renderedText },
MathJaxService.reload('SearchController')
);
})
});
};
}
|
module.exports = function($scope, $state, $location, $http, GlobalService,
DocumentService, DocumentApiService, MathJaxService, QueryParser) {
$scope.doSearch = function(){
var apiServer = GlobalService.apiServer()
var query = QueryParser.parse($scope.searchText)
console.log('query = ' + query)
$http.get('http://' + apiServer + '/v1/documents' + '?' + query )
.then(function(response){
console.log(response.data['status'])
console.log('Number of documents: ' + response.data['document_count'])
var jsonData = response.data
var documents = jsonData['documents']
DocumentService.setDocumentList(documents)
var id = documents[0]['id']
console.log('SearchController, id: ' + id)
DocumentApiService.getDocument(id)
.then(function(response) {
console.log('Document " + id + ' retrieved')
console.log('CURRENT STATE: ' + $state.current)
$state.go('documents')
$state.reload()
$scope.$watch(function(scope) {
return $scope.renderedText },
MathJaxService.reload('SearchController')
);
})
});
};
}
|
Fix search problem (but how??)
|
Fix search problem (but how??)
|
JavaScript
|
mit
|
jxxcarlson/ns_angular,jxxcarlson/ns_angular
|
a3e9428d38522008b933e258588bcc91868174d3
|
src/services/content/index.js
|
src/services/content/index.js
|
'use strict';
const request = require('request-promise-native');
const querystring = require('querystring');
const hooks = require('./hooks');
class Service {
constructor(options) {
this.options = options || {};
}
find(params) {
const options = {};
if(params.query.$limit) options["page[limit]"] = params.query.$limit;
if(params.query.$skip) options["page[offset]"] = params.query.$skip;
if(params.query.query) options.query = params.query.query;
const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`;
return request(contentServerUrl).then(string => {
return JSON.parse(string);
});
}
/*get(id, params) {
return Promise.resolve({
id, text: `A new message with ID: ${id}!`
});
}*/
}
module.exports = function () {
const app = this;
// Initialize our service with any options it requires
app.use('/contents', new Service());
// Get our initialize service to that we can bind hooks
const contentService = app.service('/contents');
// Set up our before hooks
contentService.before(hooks.before);
// Set up our after hooks
contentService.after(hooks.after);
};
module.exports.Service = Service;
|
'use strict';
const request = require('request-promise-native');
const querystring = require('querystring');
const hooks = require('./hooks');
class Service {
constructor(options) {
this.options = options || {};
}
find(params) {
const options = {};
if(params.query.$limit) options["page[limit]"] = params.query.$limit;
if(params.query.$skip) options["page[offset]"] = params.query.$skip;
if(params.query.query) options.query = params.query.query;
const contentServerUrl = `https://schul-cloud.org:8090/contents?${querystring.encode(options)}`;
return request(contentServerUrl).then(string => {
let result = JSON.parse(string);
result.total = result.meta.page.total;
result.limit = result.meta.page.limit;
result.skip = result.meta.page.offset;
return result;
});
}
/*get(id, params) {
return Promise.resolve({
id, text: `A new message with ID: ${id}!`
});
}*/
}
module.exports = function () {
const app = this;
// Initialize our service with any options it requires
app.use('/contents', new Service());
// Get our initialize service to that we can bind hooks
const contentService = app.service('/contents');
// Set up our before hooks
contentService.before(hooks.before);
// Set up our after hooks
contentService.after(hooks.after);
};
module.exports.Service = Service;
|
Add result page information in feathers format
|
Add result page information in feathers format
|
JavaScript
|
agpl-3.0
|
schul-cloud/schulcloud-server,schul-cloud/schulcloud-server,schul-cloud/schulcloud-server
|
1941cfca63e0874c8bd71a24f27a80a66532a9f1
|
config.js
|
config.js
|
var config = module.exports = exports = {}
config.items =
{ tmpDir:
{ def: 'tmp' }
, outDir:
{ def: 'out' }
, originalsPath:
{ def: 'originals' }
, maxCols:
{ def: 10 }
, maxTries:
{ def: 6 }
, invalidRequestMessage:
{ def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." }
, port:
{ def: 8000 }
, maxWidth:
{ def: 10000 }
, maxHeight:
{ def: 10000 }
, minFreeSpace:
{ def: 0.01 }
}
config.files =
{ def: null
, env: "IMG_CONFIG"
}
|
var config = module.exports = exports = {}
config.items =
{ tmpDir:
{ def: 'tmp' }
, outDir:
{ def: 'out' }
, originalsPath:
{ def: 'originals' }
, maxCols:
{ def: 10 }
, maxTries:
{ def: 6 }
, invalidRequestMessage:
{ def: "Invalid request. Make sure you are respecting the sprite maker api (https://github.com/vigour-io/vigour-img/blob/master/README.md#user-content-api) and that the requested data exists." }
, port:
{ def: 8000
, cli: "-p, --port <nb>"
, desc: "Port on which the server should listen"
}
, maxWidth:
{ def: 10000 }
, maxHeight:
{ def: 10000 }
, minFreeSpace:
{ def: 0.01 }
}
config.files =
{ def: null
, env: "IMG_CONFIG"
}
|
Add command-line option to change port
|
Add command-line option to change port
|
JavaScript
|
isc
|
vigour-io/shutter,vigour-io/vigour-img
|
4211ee0bc2e124f5807fc6ad538896e60d6cef7d
|
lib/scan.js
|
lib/scan.js
|
'use strict';
var glob = require('glob'),
_ = require('lodash'),
async = require('async'),
fs = require('fs'),
lex = require('./lex');
function isFile(path) {
var stat = fs.statSync(path);
return stat.isFile();
}
function getStrings(path, done) {
glob(path, function(er, files) {
var tokens = [];
files = files.filter(isFile);
async.reduce(files, tokens, function(tokens, file, next) {
fs.readFile(file, function(err, src) {
if (err) return next();
if (src.length === 0) return next();
tokens.push(lex(src.toString()));
return next(null, tokens);
});
}, done);
});
}
function scan(path, done) {
getStrings(path, function(err, results) {
var strings = [];
if (err) return done(err, strings);
strings = results.reduce(function(strings, result) {
return strings.concat(result);
}, []);
return done(null, _.uniq(strings).sort());
});
}
module.exports = scan;
|
'use strict';
var glob = require('glob'),
_ = require('lodash'),
async = require('async'),
fs = require('fs'),
lex = require('./lex');
function isFile(path) {
var stat = fs.statSync(path);
return stat.isFile();
}
function getStrings(path, done) {
glob(path, function(er, files) {
var tokens = [];
files = files.filter(isFile);
async.reduce(files, tokens, function(tokens, file, next) {
fs.readFile(file, function(err, src) {
if (err) return next();
if (src.length === 0) return next(null, tokens);
tokens.push(lex(src.toString()));
return next(null, tokens);
});
}, done);
});
}
function scan(path, done) {
getStrings(path, function(err, results) {
var strings = [];
if (err) return done(err, strings);
strings = results.reduce(function(strings, result) {
return strings.concat(result);
}, []);
return done(null, _.uniq(strings).sort());
});
}
module.exports = scan;
|
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
|
Fix to ensure that tokens is not undefined on the next iteration when the previous file was empty
|
JavaScript
|
mit
|
onepercentclub/extract-gettext
|
26742b0534c27cb9c615c182a867afa191d06bc2
|
static/js/states/adminHome.js
|
static/js/states/adminHome.js
|
define([
'app'
], function(app) {
'use strict';
return {
parent: 'admin_layout',
url: '',
templateUrl: 'partials/admin/home.html',
controller: function($scope, $http, flash) {
$scope.loading = true;
$http.get('/api/0/systemstats/').success(function(data){
$scope.statusCounts = data.statusCounts;
$scope.resultCounts = data.resultCounts;
}).error(function(){
flash('error', 'There was an error loading system statistics.');
}).finally(function(){
$scope.loading = false;
});
}
};
});
|
define([
'app'
], function(app) {
'use strict';
return {
parent: 'admin_layout',
url: '',
templateUrl: 'partials/admin/home.html',
controller: function($scope, $http, flash) {
var timeoutId;
$scope.loading = true;
$scope.$on('$destory', function(){
if (timeoutId) {
window.cancelTimeout(timeoutId);
}
});
function tick() {
$http.get('/api/0/systemstats/').success(function(data){
$scope.statusCounts = data.statusCounts;
$scope.resultCounts = data.resultCounts;
}).error(function(){
flash('error', 'There was an error loading system statistics.');
}).finally(function(){
$scope.loading = false;
});
timeoutId = window.setTimeout(tick, 5000);
}
tick();
}
};
});
|
Add polling for system stats
|
Add polling for system stats
|
JavaScript
|
apache-2.0
|
dropbox/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,bowlofstew/changes,wfxiang08/changes,wfxiang08/changes,dropbox/changes,bowlofstew/changes,bowlofstew/changes,dropbox/changes,dropbox/changes
|
23a9512ffcad024bd7e51db5f7677b2688dcc2cd
|
server/trips/pastTripModel.js
|
server/trips/pastTripModel.js
|
// Todo Implement and export schema using mongoose
// Reference angular sprint
var mongoose = require('mongoose');
//var User = require('../users/UserModel.js');
var Schema = mongoose.Schema;
var PastTripSchema = new Schema({
creator: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
},
participants: [{
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
}],
name: {
type: String,
required: true
},
code: {
type: String,
required: true
},
expenses: [
{
name: String,
amount: Number,
date: Date,
location: Schema.Types.Mixed,
payer: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
},
stakeholders: [{
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
}],
}
],
summary: []
});
module.exports = mongoose.model('pasttrips', PastTripSchema);
|
// Todo Implement and export schema using mongoose
// Reference angular sprint
var mongoose = require('mongoose');
//var User = require('../users/UserModel.js');
var Schema = mongoose.Schema;
var PastTripSchema = new Schema({
creator: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
},
participants: [{
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
}],
name: {
type: String,
required: true
},
code: {
type: String,
required: true
},
expenses: [
{
name: String,
amount: Number,
date: Date,
locationString: String,
expenseString: String,
location: Schema.Types.Mixed,
payer: {
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
},
stakeholders: [{
id:{
type: Schema.Types.ObjectId,
ref: 'User'
},
username: {type: String}
}],
}
],
summary: []
});
module.exports = mongoose.model('pasttrips', PastTripSchema);
|
Add location and expense strings to pastTrip model
|
Add location and expense strings to pastTrip model
|
JavaScript
|
mit
|
OrgulousArtichoke/vacaypay,OrgulousArtichoke/vacaypay
|
1a09bb1a60eaace841526c22b3d08d295082227a
|
test/filters/travis_filter.js
|
test/filters/travis_filter.js
|
"use strict";
var TravisFilter = function(name) {
console.dir(process.env)
name = name || "ON_TRAVIS";
// Get environmental variables that are known
this.filter = function(test) {
if(test.metadata == null) return false;
if(test.metadata.ignore == null) return false;
if(test.metadata.ignore.travis == null) return false;
if(process.env[name] && test.metadata.ignore.travis == true) return true;
return false;
}
}
module.exports = TravisFilter;
|
"use strict";
var TravisFilter = function(name) {
// console.dir(process.env)
name = name || "TRAVIS_JOB_ID";
// Get environmental variables that are known
this.filter = function(test) {
if(test.metadata == null) return false;
if(test.metadata.ignore == null) return false;
if(test.metadata.ignore.travis == null) return false;
if(process.env[name] != null && test.metadata.ignore.travis == true) return true;
return false;
}
}
module.exports = TravisFilter;
|
Fix ignore tests for travis
|
Fix ignore tests for travis
|
JavaScript
|
apache-2.0
|
mongodb/node-mongodb-native,mongodb/node-mongodb-native,capaj/node-mongodb-native,zhangyaoxing/node-mongodb-native,tuyndv/node-mongodb-native,thenaughtychild/node-mongodb-native,jqk6/node-mongodb-native,sarathms/node-mongodb-native,agclever/node-mongodb-native,amit777/node-mongodb-native,flyingfisher/node-mongodb-native,janaipakos/node-mongodb-native,nahidcse05/node-mongodb-native,Samicelus/node-mongodb-native,mvnnn/node-mongodb-native,HBOCodeLabs/node-mongodb-native,segmentio/node-mongodb-native,elijah513/node-mongodb-native,HiLittleCat/node-mongodb-native,patriksimek/node-mongodb-native,mongodb/node-mongodb-native,beni55/node-mongodb-native,d-mon-/node-mongodb-native,Lapixx/node-mongodb-native,christophehurpeau/node-mongodb-native,mongodb/node-mongodb-native,hgGeorg/node-mongodb-native,rafkhan/node-mongodb-native,pakokrew/node-mongodb-native,PeterWangPo/node-mongodb-native
|
ddb7437159ac6f01d84f59864b6e7708f0371df5
|
scripts/build.js
|
scripts/build.js
|
#!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' +
' *\n' +
' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' +
' */\n';
exec('uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js');
exec('uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js');
console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
|
#!/usr/bin/env node
var colors = require('colors'),
exec = require('child_process').exec,
pkg = require('../package.json'),
preamble = '/*!\n' +
' * RadioRadio ' + pkg.version + '\n' +
' *\n' +
' * ' + pkg.description + '\n' +
' *\n' +
' * Source code available at: ' + pkg.homepage + '\n' +
' *\n' +
' * (c) 2015-present ' + pkg.author.name + ' (' + pkg.author.url + ')\n' +
' *\n' +
' * RadioRadio may be freely distributed under the ' + pkg.license + ' license.\n' +
' */\n';
exec('$(npm bin)/uglifyjs src/radioradio.js --beautify "indent-level=2" --preamble "' + preamble + '" --output dist/radioradio.js');
exec('$(npm bin)/uglifyjs src/radioradio.js --compress --mangle --preamble "' + preamble + '" --output dist/radioradio.min.js');
console.log(colors.green('RadioRadio %s built successfully!'), pkg.version);
|
Add 'npm bin' to uglifyjs command.
|
Add 'npm bin' to uglifyjs command.
|
JavaScript
|
mit
|
jgarber623/RadioRadio,jgarber623/RadioRadio
|
55de12e099a43807e473cb5901439796804a3186
|
material.js
|
material.js
|
const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.emissiveColor = [0, 0, 0, 1]
this.metallic = 0.01
this.roughness = 0.5
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
|
const Signal = require('signals')
let MaterialID = 0
function Material (opts) {
this.type = 'Material'
this.id = 'Material_' + MaterialID++
this.changed = new Signal()
this._uniforms = {}
const ctx = opts.ctx
this.baseColor = [0.95, 0.95, 0.95, 1]
this.emissiveColor = [0, 0, 0, 1]
this.metallic = 0.01
this.roughness = 0.5
this.displacement = 0
this.depthTest = true
this.depthWrite = true
this.depthFunc = opts.ctx.DepthFunc.LessEqual
this.blendEnabled = false
this.blendSrcRGBFactor = ctx.BlendFactor.ONE
this.blendSrcAlphaFactor = ctx.BlendFactor.ONE
this.blendDstRGBFactor = ctx.BlendFactor.ONE
this.blendDstAlphaFactor = ctx.BlendFactor.ONE
this.castShadows = false
this.receiveShadows = false
this.cullFaceEnabled = true
this.set(opts)
}
Material.prototype.init = function (entity) {
this.entity = entity
}
Material.prototype.set = function (opts) {
Object.assign(this, opts)
Object.keys(opts).forEach((prop) => this.changed.dispatch(prop))
}
module.exports = function (opts) {
return new Material(opts)
}
|
Enable face culling by default
|
Enable face culling by default
|
JavaScript
|
mit
|
pex-gl/pex-renderer,pex-gl/pex-renderer
|
6437817486b732fb9d298ce14e363db13b07f43a
|
src/providers/mailer.js
|
src/providers/mailer.js
|
var util = require('util'),
_ = require('lodash'),
vow = require('vow'),
nm = require('nodemailer'),
transport = require('nodemailer-smtp-transport'),
errors = require('../errors').Mailer,
logger = require('./../logger'),
mailer;
module.exports = {
/**
* Initialize mailer module
*/
init: function (options) {
logger.info('Initialize e-mail sending module', module);
if (!options) {
errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn');
return vow.resolve();
}
mailer = new nm.createTransport(transport({
host: options.host,
port: options.port
}));
return vow.resolve(mailer);
},
/**
* Email sending
* @param {Object} options - e-mail options object
* @returns {*}
*/
send: function (options) {
var base = { encoding: 'utf-8' };
logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module);
if (!mailer) {
errors.createError(errors.CODES.NOT_INITIALIZED).log();
return vow.resolve();
}
var def = vow.defer();
mailer.sendMail(_.extend({}, base, options), function (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
err ? def.reject(err) : def.resolve();
});
return def.promise();
}
};
|
var util = require('util'),
_ = require('lodash'),
vow = require('vow'),
nm = require('nodemailer'),
transport = require('nodemailer-smtp-transport'),
errors = require('../errors').Mailer,
logger = require('./../logger'),
mailer;
module.exports = {
/**
* Initialize mailer module
*/
init: function (options) {
logger.info('Initialize e-mail sending module', module);
if (!options) {
errors.createError(errors.CODES.MAILER_NOT_CONFIGURED).log('warn');
return vow.resolve();
}
mailer = new nm.createTransport(transport({
host: options.host,
port: options.port
}));
return vow.resolve(mailer);
},
/**
* Email sending
* @param {Object} options - e-mail options object
* @returns {*}
*/
send: function (options) {
var base = { encoding: 'utf-8' };
logger.info(util.format('send email //subject: %s //body: %s', options.subject, options.text), module);
if (!mailer) {
errors.createError(errors.CODES.NOT_INITIALIZED).log();
return vow.resolve();
}
var def = vow.defer();
mailer.sendMail(_.extend({}, base, options), function (err) {
if (err) {
errors.createError(errors.CODES.COMMON, { err: err }).log();
def.reject(err);
} else {
def.resolve();
}
});
return def.promise();
}
};
|
Fix error with invalid error message while sending e-mail
|
Fix error with invalid error message while sending e-mail
|
JavaScript
|
mpl-2.0
|
bem-site/bse-admin,bem-site/bse-admin
|
a5675bcb304623bcc28307751fd538f253c02fae
|
document/app.js
|
document/app.js
|
var express = require('express');
module.exports = function setup(options, imports, register) {
var backend = imports.backend.app,
frontend = imports.frontend.app;
var plugin = {
app: {},
documents: {}
};
backend.get('/api/Documents', function (req, res, next) {
res.json(module.documents);
});
register(null, {
document: plugin
});
};
|
var express = require('express');
module.exports = function setup(options, imports, register) {
var backend = imports.backend.app,
frontend = imports.frontend.app;
var plugin = {
app: {},
documents: {},
addType: function (name, config) {
this.documents[name] = config;
}
};
backend.get('/api/Documents', function (req, res, next) {
res.json(module.documents);
});
register(null, {
document: plugin
});
};
|
Add addType method to content
|
Add addType method to content
|
JavaScript
|
mit
|
bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs,bauhausjs/bauhausjs
|
e1e7cf8bdbaf961b665f45254a190914801d6bac
|
server/server.js
|
server/server.js
|
const express = require('express');
const app = express();
app.use(express.static('dist'));
app.listen(8080, function() {
console.log('App started on port 8080!');
});
|
const express = require('express');
const app = express();
app.use(express.static('dist'));
app.listen(3000, function() {
console.log('Listening on port 3000!');
});
|
Use port 3000 for testing
|
Use port 3000 for testing
|
JavaScript
|
mit
|
codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa,codergvbrownsville/code-rgv-pwa
|
50249d2fed6c2e8bd9f1a7abd60d53a6cbb33f59
|
backend/lib/openfisca/index.js
|
backend/lib/openfisca/index.js
|
/*
** Module dependencies
*/
var config = require('../../config/config');
var http = require('http');
var mapping = require('./mapping');
var url = require('url');
var openfiscaURL = url.parse(config.openfiscaApi);
function sendOpenfiscaRequest(simulation, callback) {
var postData = JSON.stringify(simulation);
var options = {
hostname: openfiscaURL.hostname,
port: openfiscaURL.port,
path: 'calculate',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(postData)
}
};
var request = http.request(options, function(response) {
response.setEncoding('utf8');
var rawData = '';
response.on('data', function(chunk) { rawData += chunk; });
response.on('end', function() {
try {
var content = JSON.parse(rawData);
if (response.statusCode == 200) {
callback(null, content);
} else {
callback(content.error);
}
} catch (e) {
callback({
code: 500,
errors: 'Can\'t parse: ' + rawData,
message: e.message,
stack: e.stack,
});
}
});
});
request.write(postData);
request.on('error', callback);
request.end();
}
var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest;
function calculate(situation, callback) {
var request;
try {
request = buildOpenFiscaRequest(situation);
} catch(e) {
return callback({
message: e.message,
name: e.name,
stack: e.stack
});
}
sendOpenfiscaRequest(request, callback);
}
exports.calculate = calculate;
|
var config = require('../../config/config');
var mapping = require('./mapping');
var rp = require('request-promise');
var buildOpenFiscaRequest = exports.buildOpenFiscaRequest = mapping.buildOpenFiscaRequest;
function sendToOpenfisca(endpoint) {
return function(situation, callback) {
var request;
try {
request = buildOpenFiscaRequest(situation);
} catch(e) {
return callback({
message: e.message,
name: e.name,
stack: e.stack
});
}
rp({
uri: config.openfiscaApi + '/' + endpoint,
method: 'POST',
body: request,
json: true,
})
.then(function(result) {
callback(null, result);
}).catch(callback);
};
}
exports.calculate = sendToOpenfisca('calculate');
exports.trace = sendToOpenfisca('trace');
|
Use request-promise to manage OpenFisca calls
|
Use request-promise to manage OpenFisca calls
|
JavaScript
|
agpl-3.0
|
sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui,sgmap/mes-aides-ui
|
f63b1cd62f823d89e62d559ef5e86a70f504126c
|
javascripts/pong.js
|
javascripts/pong.js
|
(function() {
'use strict';
var canvas = document.getElementById('game');
var width = window.innerWidth;
var height = window.innerHeight;
canvas.width = width;
canvas.height = height;
var ctx = canvas.getContext('2d');
var FPS = 1000 / 60;
var clear = function() {
ctx.clearRect(0, 0, width, height);
};
var update = function() {
};
var render = function () {
};
var step = function() {
update();
render();
requestAnimationFrame(FPS);
}
requestAnimationFrame(step());
})();
|
(function() {
'use strict';
var canvas = document.getElementById('game');
var WIDTH = window.innerWidth;
var HEIGHT = window.innerHeight;
canvas.width = WIDTH;
canvas.height = HEIGHT;
var ctx = canvas.getContext('2d');
var FPS = 1000 / 60;
var Paddle = function(x, y, width, height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
this.xSpeed = 0;
this.ySpeed = 0;
};
Paddle.prototype.render = function() {
ctx.fillStyle = "#FFFFFF";
ctx.fillRect(this.x, this.y, this.width, this.height);
}
var clear = function() {
ctx.clearRect(0, 0, WIDTH, HEIGHT);
};
var update = function() {
};
var render = function () {
ctx.fillStyle = '#000000';
ctx.fillRect(0, 0, WIDTH, HEIGHT);
};
var step = function() {
update();
render();
requestAnimationFrame(FPS);
}
requestAnimationFrame(step());
})();
|
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
|
Define paddle object and a basic render function. Also capitalise width and height constants to easily distinguish them from object properties or parameters
|
JavaScript
|
mit
|
msanatan/pong,msanatan/pong,msanatan/pong
|
ddfc71983fb71ccb81f5196f97f5bb040637cdf0
|
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
|
jive-sdk-service/generator/examples/todo/tiles/todo/public/javascripts/main.js
|
(function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.project = json.project || container.name;
// prepopulate the sequence input dialog
$("#project").val( json.project);
$("#btn_submit").click( function() {
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
|
(function() {
var clientid;
jive.tile.onOpen(function(config, options, other, container ) {
osapi.jive.corev3.systemExtProps.get({}).execute(function (resp) {
if( resp && resp.content ) {
clientid = resp.content.clientid;
}
});
gadgets.window.adjustHeight();
if ( typeof config === "string" ) {
config = JSON.parse(config);
}
var json = config || { };
json.project = json.project || (container && container.name) || "";
// prepopulate the sequence input dialog
$("#project").val( json.project);
$("#btn_submit").click( function() {
config.project = $("#project").val();
config.clientid = clientid;
jive.tile.close(config, {} );
gadgets.window.adjustHeight(300);
});
});
})();
|
Handle when container is undefined.
|
Handle when container is undefined.
|
JavaScript
|
apache-2.0
|
jivesoftware/jive-sdk,jivesoftware/jive-sdk,jivesoftware/jive-sdk
|
3f84b85e5524743a35237116b3e8ba9fdf3d1e2d
|
src/TopItems.js
|
src/TopItems.js
|
import React, { Component } from 'react';
import Item from './Item';
import sortByScore from './sorter';
var TopItems = React.createClass({
sortByScore: function() {
this.setState({items: sortByScore(this.props.items)});
},
render: function() {
var rank = 0;
var all_items = this.props.items.map(function(item) {
rank++;
return (
<Item key={item.id} rank={rank} item={item} />
);
});
// Retired, sort button
// <SortButton items={this.props.items} sortByScore={this.sortByScore}/>
return (
<div>
<div className="top-stories">
{all_items}
</div>
</div>
);
}
});
var SortButton = React.createClass({
render: function() {
return (
<div>
<a className='button' onClick={this.props.sortByScore}>Sort!</a>
</div>
);
}
});
export default TopItems;
|
import React, { Component } from 'react';
import Item from './Item';
var TopItems = React.createClass({
render: function() {
var rank = 0;
var all_items = this.props.items.map(function(item) {
rank++;
return (
<Item key={item.id} rank={rank} item={item} />
);
});
return (
<div>
<div className="top-stories">
{all_items}
</div>
</div>
);
}
});
export default TopItems;
|
Remove sort button, as we sort by default now
|
Remove sort button, as we sort by default now
|
JavaScript
|
mit
|
danbartlett/hn_minimal,danbartlett/hn_minimal
|
e37507356b99586b31f888ba8405b1fc320f8400
|
lib/main.js
|
lib/main.js
|
"use babel";
"use strict";
import fs from "fs";
import path from "path";
import {CompositeDisposable} from "atom";
import {name as packageName} from "../package.json";
export default {
subscriptions: null,
activate(state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => {
this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => {
this.apply(value);
}));
}));
},
deactivate() {
this.subscriptions.dispose();
},
apply(value) {
let newData = `@import "colors/${value}";\n`,
file = path.join(__dirname, "..", "styles", "syntax-variables.less"),
oldData = fs.readFileSync(file, "utf8");
if (newData !== oldData) {
fs.writeFileSync(file, newData);
this.reloadAllStylesheets();
}
},
reloadAllStylesheets() {
atom.themes.deactivateThemes();
atom.themes.refreshLessCache();
let promises = [],
ref = atom.themes.getEnabledThemeNames();
for (let i = 0, len = ref.length; i < len; i++) {
let themeName = ref[i];
promises.push(atom.packages.activatePackage(themeName));
}
Promise.all(promises).then(() => {
atom.themes.addActiveThemeClasses();
atom.themes.refreshLessCache();
atom.themes.loadUserStylesheet();
atom.themes.reloadBaseStylesheets();
});
}
};
|
"use babel";
"use strict";
import fs from "fs";
import path from "path";
import {CompositeDisposable} from "atom";
import {name as packageName} from "../package.json";
export default {
subscriptions: null,
activate(state) {
this.subscriptions = new CompositeDisposable();
this.subscriptions.add(atom.themes.onDidChangeActiveThemes(() => {
this.subscriptions.add(atom.config.observe(`${packageName}.subtheme`, value => {
this.apply(value);
}));
}));
},
deactivate() {
this.subscriptions.dispose();
},
apply(value) {
let newData = `@import "colors/${value}";\n`,
file = path.join(__dirname, "..", "styles", "syntax-variables.less"),
oldData = fs.readFileSync(file, "utf8");
if (newData !== oldData) {
fs.writeFileSync(file, newData);
this.reloadAllStylesheets();
}
},
reloadAllStylesheets() {
atom.themes.loadUserStylesheet();
atom.themes.reloadBaseStylesheets();
let ref = atom.packages.getActivePackages();
for (let i = 0, len = ref.length; i < len; i++) {
let pack = ref[i];
pack.reloadStylesheets();
}
}
};
|
Revert ":bug: Fix stylesheets issue when changing subtheme"
|
Revert ":bug: Fix stylesheets issue when changing subtheme"
This reverts commit a9b1f3c3e9932fc0d049a6be64c3c8ecc01c7f4f.
|
JavaScript
|
mit
|
gt-rios/firefox-syntax
|
5c8bfc9df05fe7d13a4435085df1ba52f27bb376
|
lib/main.js
|
lib/main.js
|
'use babel';
let lineEndingTile = null;
export function activate() {
atom.workspace.observeActivePaneItem((item) => {
let ending = getLineEnding(item);
if (lineEndingTile) lineEndingTile.firstChild.textContent = ending;
});
}
export function consumeStatusBar(statusBar) {
lineEndingTile = document.createElement('div');
lineEndingTile.style.display = "inline-block";
lineEndingTile.className = "line-ending-tile";
lineEndingTile.innerHTML = "<a></a>";
statusBar.addRightTile({item: lineEndingTile, priority: 200});
}
function getLineEnding(item) {
if (!item) return "";
let hasLF = false;
let hasCRLF = false;
if (item && item.scan) {
item.scan(/\n|\r\n/g, ({matchText}) => {
if (matchText === "\n") hasLF = true;
if (matchText === "\r\n") hasCRLF = true;
});
}
if (hasLF && hasCRLF) return "Mixed";
if (hasLF) return "LF";
if (hasCRLF) return "CRLF";
if (process.platform === 'win32') return "CRLF";
return "LF";
}
|
'use babel';
let lineEndingTile = null;
export function activate() {
atom.workspace.observeActivePaneItem((item) => {
let ending = getLineEnding(item);
if (lineEndingTile) lineEndingTile.textContent = ending;
});
}
export function consumeStatusBar(statusBar) {
lineEndingTile = document.createElement('a');
lineEndingTile.className = "line-ending-tile";
statusBar.addRightTile({item: lineEndingTile, priority: 200});
}
function getLineEnding(item) {
if (!item) return "";
let hasLF = false;
let hasCRLF = false;
if (item && item.scan) {
item.scan(/\n|\r\n/g, ({matchText}) => {
if (matchText === "\n") hasLF = true;
if (matchText === "\r\n") hasCRLF = true;
});
}
if (hasLF && hasCRLF) return "Mixed";
if (hasLF) return "LF";
if (hasCRLF) return "CRLF";
if (process.platform === 'win32') return "CRLF";
return "LF";
}
|
Remove unneeded div around tile element
|
Remove unneeded div around tile element
Signed-off-by: Max Brunsfeld <78036c9b69b887700d5846f26a788d53b201ffbb@gmail.com>
|
JavaScript
|
mit
|
clintwood/line-ending-selector,download13/line-ending-selector,atom/line-ending-selector,bolinfest/line-ending-selector
|
b6339fe3e288d639efb0236bf029b6a94602f706
|
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
|
lib/assets/test/spec/new-dashboard/unit/specs/store/user/user.spec.js
|
import UserStore from 'new-dashboard/store/user';
import { testAction } from '../helpers';
jest.mock('carto-node');
const mutations = UserStore.mutations;
const actions = UserStore.actions;
describe('UserStore', () => {
describe('mutations', () => {
it('setUserData', () => {
const state = {
email: 'example@example.org',
username: 'example',
website: 'https://carto.com'
};
const userData = {
email: 'example@carto.com',
username: 'carto'
};
mutations.setUserData(state, userData);
expect(state).toEqual({
email: 'example@carto.com',
username: 'carto',
website: 'https://carto.com'
});
});
});
describe('actions', () => {
describe('updateData', () => {
let state;
beforeEach(() => {
state = {
email: 'example@example.org',
username: 'example',
website: 'https://carto.com'
};
});
it('success', done => {
const newConfigData = {
email: 'example@carto.com',
username: 'carto'
};
testAction(actions.updateData, null, state, [
{ type: 'setUserData', payload: newConfigData }
], [], done);
});
});
});
});
|
import UserStore from 'new-dashboard/store/user';
import { testAction2 } from '../helpers';
jest.mock('carto-node');
const mutations = UserStore.mutations;
const actions = UserStore.actions;
describe('UserStore', () => {
describe('mutations', () => {
it('setUserData', () => {
const state = {
email: 'example@example.org',
username: 'example',
website: 'https://carto.com'
};
const userData = {
email: 'example@carto.com',
username: 'carto'
};
mutations.setUserData(state, userData);
expect(state).toEqual({
email: 'example@carto.com',
username: 'carto',
website: 'https://carto.com'
});
});
});
describe('actions', () => {
describe('updateData', () => {
let state;
beforeEach(() => {
state = {
email: 'example@example.org',
username: 'example',
website: 'https://carto.com'
};
});
it('success', done => {
const newConfigData = {
email: 'example@carto.com',
username: 'carto'
};
const expectedMutations = [
{ type: 'setUserData', payload: newConfigData }
];
testAction2({ action: actions.updateData, state, expectedMutations, done });
});
});
});
});
|
Use new test action function
|
test: Use new test action function
|
JavaScript
|
bsd-3-clause
|
CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb,CartoDB/cartodb
|
39ea495532f1d113a0ca6e98cd81848943e1695a
|
src/browser/home/HomePage.js
|
src/browser/home/HomePage.js
|
/* @flow */
import type { State } from '../../common/types';
import React from 'react';
import AddrListByRoom from './AddressListByRoom';
import AddrList from './AddressList';
import { connect } from 'react-redux';
import linksMessages from '../../common/app/linksMessages';
import { isEmpty, pathOr, reject } from 'ramda';
import {
Block,
Title,
View,
} from '../components';
import { Box } from 'reflexbox';
type HomePageProps = {
smartHomeState: Object,
location: Object,
};
const HomePage = ({ smartHomeState, location }: HomePageProps) => {
const { livestate, prefs } = smartHomeState;
/* Built address-list, remove some address-types which should not be displayed */
const addresses = reject(addr => addr.type === 'fb', livestate);
if (isEmpty(addresses)) {
return (
<Block>
<p>Waiting for SmartHome-State...</p>
</Block>
);
}
const viewType = pathOr('changes', ['pathname'], location);
const addrList = viewType === 'changes'
? <AddrList addresses={addresses} />
: <AddrListByRoom addresses={addresses} prefs={prefs} />;
return (
<View>
<Title message={linksMessages.home} />
<Box py={2}>
{addrList}
</Box>
</View>
);
};
export default connect(
(state: State) => ({
smartHomeState: state.smartHome,
}),
)(HomePage);
|
/* @flow */
import type { State } from '../../common/types';
import React from 'react';
import AddrListByRoom from './AddressListByRoom';
import AddrList from './AddressList';
import { connect } from 'react-redux';
import linksMessages from '../../common/app/linksMessages';
import { isEmpty, pathOr, reject, test } from 'ramda';
import { Block, Title, View } from '../components';
import { Box } from 'reflexbox';
type HomePageProps = {
smartHomeState: Object,
location: Object,
};
const HomePage = ({ smartHomeState, location }: HomePageProps) => {
const { livestate, prefs } = smartHomeState;
/* Built address-list, remove some address-types which should not be displayed */
const addresses = reject(addr => addr.type === 'fb', livestate);
if (isEmpty(addresses)) {
return (
<Block>
<p>Waiting for SmartHome-State...</p>
</Block>
);
}
const viewType = pathOr('changes', ['pathname'], location);
const addrList = test(/rooms$/, viewType)
? <AddrListByRoom addresses={addresses} prefs={prefs} />
: <AddrList addresses={addresses} />;
return (
<View>
<Title message={linksMessages.home} />
<Box py={2}>
{addrList}
</Box>
</View>
);
};
export default connect((state: State) => ({
smartHomeState: state.smartHome,
}))(HomePage);
|
Improve tolerance when matching url-paths for router-navigation.
|
Improve tolerance when matching url-paths for router-navigation.
|
JavaScript
|
mit
|
cjk/smart-home-app
|
7ced1f20afd2b52ac687bfae21ca33537b635ae6
|
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
|
src/routes/Player/components/PlayerController/PlayerControllerContainer.js
|
import PlayerController from './PlayerController'
import { connect } from 'react-redux'
import { ensureState } from 'redux-optimistic-ui'
import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue'
import {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
} from '../../modules/player'
import { playerVisualizerError } from '../../modules/playerVisualizer'
const mapActionCreators = {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
playerVisualizerError,
}
const mapStateToProps = (state) => {
const { player, playerVisualizer, prefs } = state
const queue = ensureState(state.queue)
return {
cdgAlpha: player.cdgAlpha,
cdgSize: player.cdgSize,
historyJSON: state.status.historyJSON, // @TODO use state.player instead?
isAtQueueEnd: player.isAtQueueEnd,
isErrored: player.isErrored,
isPlaying: player.isPlaying,
isPlayingNext: player.isPlayingNext,
isQueueEmpty: queue.result.length === 0,
isReplayGainEnabled: prefs.isReplayGainEnabled,
isWebGLSupported: player.isWebGLSupported,
mp4Alpha: player.mp4Alpha,
queue: getOrderedQueue(state),
queueId: player.queueId,
volume: player.volume,
visualizer: playerVisualizer,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlayerController)
|
import PlayerController from './PlayerController'
import { connect } from 'react-redux'
import { ensureState } from 'redux-optimistic-ui'
import getOrderedQueue from 'routes/Queue/selectors/getOrderedQueue'
import {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
} from '../../modules/player'
import { playerVisualizerError } from '../../modules/playerVisualizer'
const mapActionCreators = {
playerLeave,
playerError,
playerLoad,
playerPlay,
playerStatus,
playerVisualizerError,
}
const mapStateToProps = (state) => {
const { player, playerVisualizer, prefs } = state
const queue = ensureState(state.queue)
return {
cdgAlpha: player.cdgAlpha,
cdgSize: player.cdgSize,
historyJSON: player.historyJSON,
isAtQueueEnd: player.isAtQueueEnd,
isErrored: player.isErrored,
isPlaying: player.isPlaying,
isPlayingNext: player.isPlayingNext,
isQueueEmpty: queue.result.length === 0,
isReplayGainEnabled: prefs.isReplayGainEnabled,
isWebGLSupported: player.isWebGLSupported,
mp4Alpha: player.mp4Alpha,
queue: getOrderedQueue(state),
queueId: player.queueId,
volume: player.volume,
visualizer: playerVisualizer,
}
}
export default connect(mapStateToProps, mapActionCreators)(PlayerController)
|
Use internal player history instead of emitted status
|
Use internal player history instead of emitted status
|
JavaScript
|
isc
|
bhj/karaoke-forever,bhj/karaoke-forever
|
373dfb4090d23fceb878278a244b64ecde31efb0
|
lib/util.js
|
lib/util.js
|
exports = module.exports = require('util');
exports.formatDate = function(date){
if (typeof date === 'string') return date;
date = new Date(date);
var month = date.getMonth() + 1,
day = date.getDate(),
str = date.getFullYear();
str += '-';
if (month < 10) str += '0';
str += month;
str += '-';
if (day < 10) str += '0';
str += day;
return str;
};
exports.formatError = function(data){
return new Error(data.message + ' (Code: ' + data.code + ')');
};
|
exports = module.exports = require('util');
exports.formatDate = function(date){
if (typeof date === 'string') return date;
date = new Date(date);
var month = date.getMonth() + 1,
day = date.getDate(),
str = date.getFullYear();
str += '-';
if (month < 10) str += '0';
str += month;
str += '-';
if (day < 10) str += '0';
str += day;
return str;
};
exports.formatError = function(data){
var err = new Error(data.message + ' (Code: ' + data.code + ')');
err.code = data.code;
return err;
};
|
Add code to error object
|
Add code to error object
|
JavaScript
|
mit
|
tommy351/node-flurry-api
|
b3e10b4bc710a4892d430efeb2f41ef6900fb72c
|
src/components/OAuthLogin.js
|
src/components/OAuthLogin.js
|
import React from 'react';
import {FormattedMessage} from "react-intl";
import queryString from "query-string";
const OAuthLogin = ({providers, onLogin}) => {
const location = window.location;
const targetUrl = `${location.protocol}//${location.host}/login`;
const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`;
return <div className="pt-button-group pt-vertical pt-align-left pt-large">
{providers.map(provider => <p key={provider.name}>
<a href={`${provider.login}${loginUrlQueryString}`} className="pt-button pt-intent-primary pt-icon-log-in">
<FormattedMessage id="login.provider" defaultMessage="Sign in with {label}"
values={{label: provider.label}}/>
</a>
</p>)}
</div>
};
export const handleOAuthCallback = (onLoginFn) => {
const parsedHash = queryString.parse(location.hash);
if (parsedHash.token) {
onLoginFn(parsedHash.token);
location.hash = '';
}
};
export default OAuthLogin;
|
import React from 'react';
import {FormattedMessage} from "react-intl";
import {AnchorButton, Intent} from '@blueprintjs/core';
import queryString from "query-string";
const OAuthLogin = ({providers, onLogin}) => {
const location = window.location;
const targetUrl = `${location.protocol}//${location.host}/login`;
const loginUrlQueryString = `?next=${encodeURIComponent(targetUrl)}`;
return <div className="pt-button-group pt-vertical pt-align-left pt-large">
{providers.map(provider => <p key={provider.name}>
<AnchorButton href={`${provider.login}${loginUrlQueryString}`} intent={Intent.PRIMARY}>
<FormattedMessage id="login.provider" defaultMessage="Sign in with {label}"
values={{label: provider.label}}/>
</AnchorButton>
</p>)}
</div>
};
export const handleOAuthCallback = (onLoginFn) => {
const parsedHash = queryString.parse(location.hash);
if (parsedHash.token) {
onLoginFn(parsedHash.token);
location.hash = '';
}
};
export default OAuthLogin;
|
Use AnchorButton for anchor button
|
Use AnchorButton for anchor button
|
JavaScript
|
mit
|
alephdata/aleph,pudo/aleph,pudo/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,alephdata/aleph,pudo/aleph
|
84bad5d57dff7d5591d24bcc5caf6698e17e40b6
|
src/Aggregrid.js
|
src/Aggregrid.js
|
Ext.define('Jarvus.aggregrid.Aggregrid', {
extend: 'Ext.Component',
html: 'Hello World'
});
|
Ext.define('Jarvus.aggregrid.Aggregrid', {
extend: 'Ext.Component',
config: {
columnsStore: null,
rowsStore: null
},
html: 'Hello World',
// config handlers
applyColumnsStore: function(store) {
return Ext.StoreMgr.lookup(store);
},
applyRowsStore: function(store) {
return Ext.StoreMgr.lookup(store);
}
});
|
Add columnsStore and rowsStore configs
|
Add columnsStore and rowsStore configs
|
JavaScript
|
mit
|
JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid,JarvusInnovations/jarvus-aggregrid
|
b8fdcaf0033348f8ec7203bc1150f66d188c6259
|
src/Constants.js
|
src/Constants.js
|
export const BLOCK_TYPE = {
// This is used to represent a normal text block (paragraph).
UNSTYLED: 'unstyled',
HEADER_ONE: 'header-one',
HEADER_TWO: 'header-two',
HEADER_THREE: 'header-three',
HEADER_FOUR: 'header-four',
HEADER_FIVE: 'header-five',
HEADER_SIX: 'header-six',
UNORDERED_LIST_ITEM: 'unordered-list-item',
ORDERED_LIST_ITEM: 'ordered-list-item',
BLOCKQUOTE: 'blockquote',
PULLQUOTE: 'pullquote',
CODE: 'code-block',
ATOMIC: 'atomic',
};
export const ENTITY_TYPE = {
LINK: 'LINK',
};
export const INLINE_STYLE = {
BOLD: 'BOLD',
CODE: 'CODE',
ITALIC: 'ITALIC',
STRIKETHROUGH: 'STRIKETHROUGH',
UNDERLINE: 'UNDERLINE',
};
export default {
BLOCK_TYPE,
ENTITY_TYPE,
INLINE_STYLE,
};
|
export const BLOCK_TYPE = {
// This is used to represent a normal text block (paragraph).
UNSTYLED: 'unstyled',
HEADER_ONE: 'header-one',
HEADER_TWO: 'header-two',
HEADER_THREE: 'header-three',
HEADER_FOUR: 'header-four',
HEADER_FIVE: 'header-five',
HEADER_SIX: 'header-six',
UNORDERED_LIST_ITEM: 'unordered-list-item',
ORDERED_LIST_ITEM: 'ordered-list-item',
BLOCKQUOTE: 'blockquote',
PULLQUOTE: 'pullquote',
CODE: 'code-block',
ATOMIC: 'atomic',
};
export const ENTITY_TYPE = {
LINK: 'LINK',
IMAGE: 'IMAGE'
};
export const INLINE_STYLE = {
BOLD: 'BOLD',
CODE: 'CODE',
ITALIC: 'ITALIC',
STRIKETHROUGH: 'STRIKETHROUGH',
UNDERLINE: 'UNDERLINE',
};
export default {
BLOCK_TYPE,
ENTITY_TYPE,
INLINE_STYLE,
};
|
Add Image to ENTITY_TYPE Enum
|
Add Image to ENTITY_TYPE Enum
Useful for rich text editor inline image support
|
JavaScript
|
isc
|
draft-js-utils/draft-js-utils
|
969fc9567cc94d0a7a7d79528f989f8179cb3053
|
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
|
ukelonn.web.frontend/src/main/frontend/sagas/modifyPaymenttypeSaga.js
|
import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import {
MODIFY_PAYMENTTYPE_REQUEST,
MODIFY_PAYMENTTYPE_RECEIVE,
MODIFY_PAYMENTTYPE_FAILURE,
} from '../actiontypes';
function doModifyPaymenttype(paymenttype) {
return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype);
}
function* requestReceiveModifyPaymenttypeSaga(action) {
try {
const response = yield call(doModifyPaymenttype, action.payload);
const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : [];
yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes));
} catch (error) {
yield put(MODIFY_PAYMENTTYPE_FAILURE(error));
}
}
export default function* modifyPaymenttypeSaga() {
yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga);
}
|
import { takeLatest, call, put } from 'redux-saga/effects';
import axios from 'axios';
import {
MODIFY_PAYMENTTYPE_REQUEST,
MODIFY_PAYMENTTYPE_RECEIVE,
MODIFY_PAYMENTTYPE_FAILURE,
CLEAR_PAYMENT_TYPE_FORM,
} from '../actiontypes';
function doModifyPaymenttype(paymenttype) {
return axios.post('/ukelonn/api/admin/paymenttype/modify', paymenttype);
}
function* requestReceiveModifyPaymenttypeSaga(action) {
try {
const response = yield call(doModifyPaymenttype, action.payload);
const paymenttypes = (response.headers['content-type'] == 'application/json') ? response.data : [];
yield put(MODIFY_PAYMENTTYPE_RECEIVE(paymenttypes));
} catch (error) {
yield put(MODIFY_PAYMENTTYPE_FAILURE(error));
}
}
function* clearPaymenttypeForm() {
yield put(CLEAR_PAYMENT_TYPE_FORM());
}
export default function* modifyPaymenttypeSaga() {
yield takeLatest(MODIFY_PAYMENTTYPE_REQUEST, requestReceiveModifyPaymenttypeSaga);
yield takeLatest(MODIFY_PAYMENTTYPE_RECEIVE, clearPaymenttypeForm);
}
|
Clear payment type form data after succesfully saving a modified payment type
|
Clear payment type form data after succesfully saving a modified payment type
|
JavaScript
|
apache-2.0
|
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.