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
9ba3095bdc0a81a1546634160f2a20c3a0196d51
src/time_slot.js
src/time_slot.js
Occasion.Modules.push(function(library) { library.TimeSlot = class TimeSlot extends library.Base {}; library.TimeSlot.className = 'TimeSlot'; library.TimeSlot.queryName = 'time_slots'; library.TimeSlot.belongsTo('product'); library.TimeSlot.belongsTo('venue'); library.TimeSlot.afterRequest(function() { if(this.product().merchant()) { this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone); } else { throw 'Must use includes({ product: \'merchant\' }) in timeSlot request'; } this.duration = moment.duration(this.duration, 'minutes'); }); });
Occasion.Modules.push(function(library) { library.TimeSlot = class TimeSlot extends library.Base {}; library.TimeSlot.className = 'TimeSlot'; library.TimeSlot.queryName = 'time_slots'; library.TimeSlot.belongsTo('order'); library.TimeSlot.belongsTo('product'); library.TimeSlot.belongsTo('venue'); library.TimeSlot.afterRequest(function() { if(this.product().merchant()) { this.startsAt = moment.tz(this.startsAt, this.product().merchant().timeZone); } else { throw 'Must use includes({ product: \'merchant\' }) in timeSlot request'; } this.duration = moment.duration(this.duration, 'minutes'); }); });
Add TimeSlot belongsTo order relationship
Add TimeSlot belongsTo order relationship
JavaScript
mit
nicklandgrebe/occasion-sdk-js
b447e585b0c77739315677deb367140184d24a17
src/models/reminder.js
src/models/reminder.js
const mongoose = require('mongoose'); const reminderSchema = new mongoose.Schema({ user_address: { type: Object, required: true, index: true }, value: { type: String, required: true }, expiration: { type: Date, required: true } }); module.exports = mongoose.model('Reminder', reminderSchema);
const mongoose = require('mongoose'); const reminderSchema = new mongoose.Schema({ user_address: { useAuth: Boolean, serviceUrl: String, bot: { name: String, id: String }, conversation: { id: String, isGroup: Boolean }, user: { name: { type: String, index: true }, id: String }, channelId: String, id: String }, value: { type: String, required: true }, expiration: { type: Date, required: true } }); module.exports = mongoose.model('Reminder', reminderSchema);
Improve mongoose schema, index user.name
Improve mongoose schema, index user.name
JavaScript
mit
sebsylvester/reminder-bot
26fa40b50deee67a1ce8711ef5f35a7cd977c18d
src/openpoliticians.js
src/openpoliticians.js
"use strict"; var cors = require('cors'); var originWhitelist = [ 'http://openpoliticians.org', 'http://localhost:4000', ]; var openPoliticiansCors = cors({ origin: function(origin, callback) { var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); }, credentials: true, }); module.exports = openPoliticiansCors;
"use strict"; var cors = require('cors'); var originWhitelist = [ 'http://openpoliticians.org', 'http://everypolitician.org', 'http://localhost:4000', ]; var openPoliticiansCors = cors({ origin: function(origin, callback) { var originIsWhitelisted = originWhitelist.indexOf(origin) !== -1; callback(null, originIsWhitelisted); }, credentials: true, }); module.exports = openPoliticiansCors;
Add everypolitician.org to allowed CORS addresses
Add everypolitician.org to allowed CORS addresses
JavaScript
agpl-3.0
Sinar/popit-api,mysociety/popit-api,mysociety/popit-api,Sinar/popit-api
0edf973af2efff8614ddae037eb28d5f2b178599
ext/codecast/7.1/codecast-loader.js
ext/codecast/7.1/codecast-loader.js
$(document).ready(function() { if (window.taskData) { var taskInstructionsHtml = $('#taskIntro').html(); var hints = $('#taskHints > div').toArray().map(elm => { return { content: elm.innerHTML.trim() }; }); var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {}; if (window.codecastPreload) { additionalOptions.preload = true; } var codecastParameters = $.extend(true, { start: 'task', showStepper: true, showStack: true, showViews: true, showIO: true, showDocumentation: true, showFullScreen: true, showMenu: true, canRecord: false, platform: 'python', canChangePlatform: true, canChangeLanguage: true, controls: {}, // audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js", baseUrl: "https://codecast.france-ioi.org/v7", authProviders: ["algorea", "guest"], task: window.taskData, taskInstructions: taskInstructionsHtml, taskHints: hints, }, additionalOptions, window.codecastPreload ? window.codecastPreload : {}); Codecast.start(codecastParameters); } });
$(document).ready(function() { if (window.taskData) { var taskInstructionsHtml = $('#taskIntro').html(); var hints = $('#taskHints > div').toArray().map(elm => { return { content: elm.innerHTML.trim() }; }); var additionalOptions = window.taskData.codecastParameters ? window.taskData.codecastParameters : {}; if (window.codecastPreload) { additionalOptions.preload = true; } if (!additionalOptions.language && window.stringsLanguage) { additionalOptions.language = window.stringsLanguage; } var codecastParameters = $.extend(true, { start: 'task', showStepper: true, showStack: true, showViews: true, showIO: true, showDocumentation: true, showFullScreen: true, showMenu: true, canRecord: false, platform: 'python', canChangePlatform: true, canChangeLanguage: true, controls: {}, // audioWorkerUrl: modulesPath + "ext/codecast/7.0/index.worker.worker.js", baseUrl: "https://codecast.france-ioi.org/v7", authProviders: ["algorea", "guest"], task: window.taskData, taskInstructions: taskInstructionsHtml, taskHints: hints, }, additionalOptions, window.codecastPreload ? window.codecastPreload : {}); Codecast.start(codecastParameters); } });
Revert "Revert "Use window.stringsLanguage by default if fulfilled""
Revert "Revert "Use window.stringsLanguage by default if fulfilled"" This reverts commit 6c738f09b3c930a90847440c564d65179417c469.
JavaScript
mit
France-ioi/bebras-modules,France-ioi/bebras-modules
f3f2ed4622828fdce9ca809e32939548267cf406
lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js
lib/node_modules/@stdlib/types/ndarray/ctor/lib/get2d.js
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; // FUNCTIONS // /** * Returns an array element. * * @private * @param {integer} i - index for first dimension * @param {integer} j - index for second dimension * @throws {TypeError} index for first dimension must be an integer value * @throws {TypeError} index for second dimension must be an integer value * @returns {*} array element */ function get( i, j ) { /* eslint-disable no-invalid-this */ var idx; if ( !isInteger( i ) ) { throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' ); } if ( !isInteger( j ) ) { throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' ); } // TODO: support index modes idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j ); return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
'use strict'; // MODULES // var isInteger = require( '@stdlib/assert/is-integer' ).isPrimitive; var getIndex = require( './get_index.js' ); // FUNCTIONS // /** * Returns an array element. * * @private * @param {integer} i - index for first dimension * @param {integer} j - index for second dimension * @throws {TypeError} index for first dimension must be an integer value * @throws {TypeError} index for second dimension must be an integer value * @returns {*} array element */ function get( i, j ) { /* eslint-disable no-invalid-this */ var idx; if ( !isInteger( i ) ) { throw new TypeError( 'invalid input argument. Index for first dimension must be an integer value. Value: `'+i+'`.' ); } if ( !isInteger( j ) ) { throw new TypeError( 'invalid input argument. Index for second dimension must be an integer value. Value: `'+j+'`.' ); } i = getIndex( i, this._shape[ 0 ], this._mode ); j = getIndex( j, this._shape[ 1 ], this._mode ); idx = this._offset + ( this._strides[0]*i ) + ( this._strides[1]*j ); return this._buffer[ idx ]; } // end FUNCTION get() // EXPORTS // module.exports = get;
Add support for an index mode
Add support for an index mode
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
5620dd2921b534e1328c9305c66c254d04131797
app/index.js
app/index.js
'use strict'; var util = require('util'); var yeoman = require('yeoman-generator'); var Generator = module.exports = function () { var cb = this.async(); var ignores = [ '.git', 'CHANGELOG.md', 'CONTRIBUTING.md', 'LICENSE.md', 'README.md' ]; this.prompt([{ type: 'confirm', name: 'docs', message: 'Would you like docs included?', default: false }], function (props) { if (props.docs) { this.directory('doc'); } this.directory('css'); this.directory('img'); this.directory('js'); this.expandFiles('*', { cwd: this.sourceRoot(), dot: true }).forEach(function (el) { if (ignores.indexOf(el) === -1) { this.copy(el, el); } }, this); cb(); }.bind(this)); }; util.inherits(Generator, yeoman.generators.Base); Generator.name = 'HTML5 Boilerplate';
'use strict'; var util = require('util'); var yeoman = require('yeoman-generator'); var Generator = module.exports = function Generator () { yeoman.generators.Base.apply(this, arguments); }; util.inherits(Generator, yeoman.generators.NamedBase); Generator.prototype.copyFiles = function () { var cb = this.async(); var ignores = [ '.git', 'CHANGELOG.md', 'CONTRIBUTING.md', 'LICENSE.md', 'README.md' ]; this.prompt([{ type: 'confirm', name: 'docs', message: 'Would you like docs included?', default: false }], function (props) { if (props.docs) { this.directory('doc'); } this.directory('css'); this.directory('img'); this.directory('js'); this.expandFiles('*', { cwd: this.sourceRoot(), dot: true }).forEach(function (el) { if (ignores.indexOf(el) === -1) { this.copy(el, el); } }, this); cb(); }.bind(this)); }; Generator.name = 'HTML5 Boilerplate';
Make generator work with `yo` v1.0.5
Make generator work with `yo` v1.0.5 Ref #12. Fix #11.
JavaScript
mit
h5bp/generator-h5bp
7aee442d3b12698bb027c747a11719a075d9c586
lib/autoprefix-processor.js
lib/autoprefix-processor.js
var autoprefixer = require('autoprefixer-core'); module.exports = function(less) { function AutoprefixProcessor(options) { this.options = options || {}; }; AutoprefixProcessor.prototype = { process: function (css, extra) { var options = this.options; var sourceMap = extra.sourceMap; var sourceMapInline, processOptions = {}; if (sourceMap) { processOptions.map = {}; processOptions.to = sourceMap.getOutputFilename(); processOptions.from = sourceMap.getInputFilename(); sourceMapInline = sourceMap.isInline(); if (sourceMapInline) { processOptions.map.inline = true; } else { processOptions.map.prev = sourceMap.getExternalSourceMap(); processOptions.map.annotation = sourceMap.getSourceMapURL(); } } var processed = autoprefixer(options).process(css, processOptions); if (sourceMap && !sourceMapInline) { sourceMap.setExternalSourceMap(processed.map); } return processed.css; } }; return AutoprefixProcessor; };
var autoprefixer = require('autoprefixer-core'); module.exports = function(less) { function AutoprefixProcessor(options) { this.options = options || {}; }; AutoprefixProcessor.prototype = { process: function (css, extra) { var options = this.options; var sourceMap = extra.sourceMap; var sourceMapInline, processOptions = {}; if (sourceMap) { processOptions.map = {}; processOptions.to = sourceMap.getOutputFilename(); // setting from = input filename works unless there is a directory, // then autoprefixer adds the directory onto the source filename twice. // setting to to anything else causes an un-necessary extra file to be // added to the map, but its better than it failing processOptions.from = sourceMap.getOutputFilename(); sourceMapInline = sourceMap.isInline(); if (sourceMapInline) { processOptions.map.inline = true; } else { processOptions.map.prev = sourceMap.getExternalSourceMap(); processOptions.map.annotation = sourceMap.getSourceMapURL(); } } var processed = autoprefixer(options).process(css, processOptions); if (sourceMap && !sourceMapInline) { sourceMap.setExternalSourceMap(processed.map); } return processed.css; } }; return AutoprefixProcessor; };
Fix sourcemaps when in a directory
Fix sourcemaps when in a directory
JavaScript
apache-2.0
less/less-plugin-autoprefix,PixnBits/less-plugin-autoprefix
7df02298180fcd94019506f363392c48e0fe21cf
app.js
app.js
function Person(name) { this.name = name; this.parent = null; this.children = []; this.siblings = []; this.getChildren = function () { return this.children; } }; var Nancy = new Person("Nancy") var Adam = new Person("Adam") var Jill = new Person("Jill") var Carl = new Person("Carl") Nancy.children.push(Adam, Jill, Carl) console.log(Nancy.getChildren());
var familyTree = []; function Person(name) { this.name = name; this.parent = null; this.children = []; this.siblings = []; this.addChild = function(name) { var child = new Person(name) child.parent = this this.children.push(child); }; this.init(); }; Person.prototype.init = function(){ familyTree.push(this) }; //Driver test console.log(familyTree); var nancy = new Person("Nancy"); nancy.addChild("Adam") console.log(familyTree);
Restructure Person prototype and add family array
Restructure Person prototype and add family array
JavaScript
mit
Nilaco/Family-Tree,Nilaco/Family-Tree
cf73385957d54ef0c808aa69e261fe57b87cb7f9
ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js
ukelonn.web.frontend/src/main/frontend/reducers/passwordReducer.js
import { createReducer } from 'redux-starter-kit'; import { UPDATE, } from '../actiontypes'; const passwordReducer = createReducer(null, { [UPDATE]: (state, action) => { if (!(action.payload && action.payload.password)) { return state; } return action.payload.password; }, }); export default passwordReducer;
import { createReducer } from 'redux-starter-kit'; import { UPDATE, LOGIN_RECEIVE, INITIAL_LOGIN_STATE_RECEIVE, } from '../actiontypes'; const passwordReducer = createReducer(null, { [UPDATE]: (state, action) => { if (!(action.payload && action.payload.password)) { return state; } return action.payload.password; }, [LOGIN_RECEIVE]: (state, action) => '', [INITIAL_LOGIN_STATE_RECEIVE]: (state, action) => '', }); export default passwordReducer;
Set password in redux to empty string on successful login
Set password in redux to empty string on successful login
JavaScript
apache-2.0
steinarb/ukelonn,steinarb/ukelonn,steinarb/ukelonn
ea015fcb266ab4287e583bed76bf5fbbb62205e5
database/index.js
database/index.js
let pgp = require('pg-promise')({ssl: true}); // let databaseUrl = process.env.DATABASE_URL || require('./config'); // module.exports = pgp(databaseUrl);
let pgp = require('pg-promise')(); // initialization option was {ssl: true}, sorry for deleting, but wasn't working for me with it let connection = process.env.DATABASE_URL || require('./config'); module.exports = pgp(connection);
Delete initialization options and change variable name
Delete initialization options and change variable name
JavaScript
mit
SentinelsOfMagic/SentinelsOfMagic
62188e803684cb8b7cf965a895da23bc583b83a5
postcss.config.js
postcss.config.js
"use strict"; const {media_breakpoints} = require("./static/js/css_variables"); module.exports = { plugins: { // Warning: despite appearances, order is significant "postcss-nested": {}, "postcss-extend-rule": {}, "postcss-simple-vars": { variables: media_breakpoints, }, "postcss-calc": {}, "postcss-media-minmax": {}, autoprefixer: {}, }, };
"use strict"; const {media_breakpoints} = require("./static/js/css_variables"); module.exports = { plugins: [ require("postcss-nested"), require("postcss-extend-rule"), require("postcss-simple-vars")({variables: media_breakpoints}), require("postcss-calc"), require("postcss-media-minmax"), require("autoprefixer"), ], };
Convert plugins object to an array.
postcss: Convert plugins object to an array. Since order matters for plugins, its better to use the Array syntax to pass plugins to the PostCSS instead of Object. This also allows us to reliably add more plugins programatically if we so choose. [dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com: Adjust to work with postcss-cli.] Co-authored-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com> Signed-off-by: Anders Kaseorg <dfdb7392591db597bc41cf266a9c3bc12a2706e5@zulip.com>
JavaScript
apache-2.0
eeshangarg/zulip,kou/zulip,kou/zulip,kou/zulip,andersk/zulip,zulip/zulip,rht/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,rht/zulip,rht/zulip,rht/zulip,zulip/zulip,zulip/zulip,eeshangarg/zulip,eeshangarg/zulip,rht/zulip,zulip/zulip,andersk/zulip,rht/zulip,andersk/zulip,zulip/zulip,rht/zulip,zulip/zulip,zulip/zulip,kou/zulip,eeshangarg/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,eeshangarg/zulip,kou/zulip,andersk/zulip,andersk/zulip
55a531708dfcf895433ce9abaf2c11fe9635df14
public/js/read.js
public/js/read.js
var imgWidth = new Array(); function imageWidth() { var width = $(window).width() - fixedPadding; $(".img_flex").each(function(index) { if (width != $(this).width()) { if (width < imgWidth[index]) { $(this).width(width); } else { $(this).width(imgWidth[index]); } } }); } $(document).ready(function() { $(document).keyup(function(e) { if (e.keyCode === 37) window.location.href = prevPage; if (e.keyCode === 39) window.location.href = nextPage; }); $(".jump").on('change', function() { window.location.href = baseUrl + this.value; }); $(".img_flex").each(function(index) { imgWidth.push($(this).width()); }); imageWidth(); $(window).resize(function(){ imageWidth(); }); });
var imgWidth = new Array(); var imagePadding = 100; function imageWidth() { var width = $(window).width() - imagePadding; $(".img_flex").each(function(index) { if (width != $(this).width()) { if (width < imgWidth[index]) { $(this).width(width); } else { $(this).width(imgWidth[index]); } } }); } $(document).ready(function() { $(document).keyup(function(e) { if (e.keyCode === 37) window.location.href = prevPage; if (e.keyCode === 39) window.location.href = nextPage; }); $(".jump").on('change', function() { window.location.href = baseUrl + this.value; }); $(".img_flex").each(function(index) { imgWidth.push($(this).width()); }); imageWidth(); $(window).resize(function(){ imageWidth(); }); });
Change padding depend on window width (the bigger the more big the width is)
Change padding depend on window width (the bigger the more big the width is)
JavaScript
mit
hernantas/MangaReader,hernantas/MangaReader,hernantas/MangaReader
8be4bc9543ba1f23019d619c822bc7e4769e22da
stories/Autocomplete.stories.js
stories/Autocomplete.stories.js
import React from 'react'; import { storiesOf } from '@storybook/react'; import Autocomplete from '../src/Autocomplete'; const stories = storiesOf('javascript/Autocomplete', module); stories.addParameters({ info: { text: `Add an autocomplete dropdown below your input to suggest possible values in your form. You can populate the list of autocomplete options dynamically as well.` } }); stories.add('Default', () => ( <Autocomplete options={{ data: { ['Gus Fring']: null, ['Saul Goodman']: null, ['Tuco Salamanca']: 'https://placehold.it/250x250' } }} placeholder="Insert here" /> ));
import React from 'react'; import { storiesOf } from '@storybook/react'; import Autocomplete from '../src/Autocomplete'; const stories = storiesOf('javascript/Autocomplete', module); stories.addParameters({ info: { text: `Add an autocomplete dropdown below your input to suggest possible values in your form. You can populate the list of autocomplete options dynamically as well.` } }); stories.add('Default', () => ( <Autocomplete options={{ data: { ['Gus Fring']: null, ['Saul Goodman']: null, ['Tuco Salamanca']: 'https://placehold.it/250x250' } }} placeholder="Insert here" /> )); stories.add('With icon', () => ( <Autocomplete options={{ data: { ['Gus Fring']: null, ['Saul Goodman']: null, ['Tuco Salamanca']: 'https://placehold.it/250x250' } }} placeholder="Insert here" icon="textsms" /> ));
Add autocomplete with icon story
Add autocomplete with icon story
JavaScript
mit
react-materialize/react-materialize,react-materialize/react-materialize,react-materialize/react-materialize
ef090c4c1b819b2df89ec50a855260decdf5ace0
app/tradeapi/tradeapi.js
app/tradeapi/tradeapi.js
/** This Angular module provide interface to VNDIRECT API, include: - Auth API - Trade API */ angular.module('myApp.tradeapi', []) .factory('tradeapi', ['$http', function($http) { var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth'; var token = null; return { login: function(username, password) { $http({ method: 'POST', url: AUTH_URL, data: { username: username, password: password } }) .then(function(response) { console.log('Login success', response); }) }, }; });
/** This Angular module provide interface to VNDIRECT API, include: - Auth API - Trade API */ angular.module('myApp.tradeapi', []) .factory('tradeapi', ['$http', '$q', function($http, $q) { var AUTH_URL = 'https://auth-api.vndirect.com.vn/auth'; var CUSOMTER_URL = 'https://trade-api.vndirect.com.vn/customer'; var token = null; return { login: function(username, password) { var deferred = $q.defer(); $http({ method: 'POST', url: AUTH_URL, data: { username: username, password: password } }) .then(function(response) { deferred.resolve(response.data); token = response.data.token; }, function(response) { deferred.reject(response.data.message); }); return deferred.promise; }, /** Retrieve customer information such as cusid, name, accou */ retrieve_customer: function() { var deferred = $q.defer(); if(token) { $http({ method: 'GET', url: CUSOMTER_URL, headers: { 'X-AUTH-TOKEN': token } }) .then(function(response) { deferred.resolve(response.data); }, function(response) { deferred.reject(response.data.message); }); return deferred.promise; } else{ throw 'You are not logged in'; } } }; }]);
Integrate login & retrieve customer with Trade API
Integrate login & retrieve customer with Trade API
JavaScript
mit
VNDIRECT/SmartP,VNDIRECT/SmartP
d299ceac7d3d115266a8f45a14f1fd9f42cea883
tests/test-simple.js
tests/test-simple.js
/* * Copyright 2011 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var et = require('elementtree'); exports['test_error_type'] = function(test, assert) { /* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */ var Element = et.Element var root = Element('root'); root.append(Element('one')); root.append(Element('two')); root.append(Element('three')); assert.equal(3, root.len()) assert.equal('one', root.getItem(0).tag) assert.equal('two', root.getItem(1).tag) assert.equal('three', root.getItem(2).tag) test.finish(); };
/* * Copyright 2011 Rackspace * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ var et = require('elementtree'); exports['test_simplest'] = function(test, assert) { /* Ported from <https://github.com/lxml/lxml/blob/master/src/lxml/tests/test_elementtree.py> */ var Element = et.Element var root = Element('root'); root.append(Element('one')); root.append(Element('two')); root.append(Element('three')); assert.equal(3, root.len()) assert.equal('one', root.getItem(0).tag) assert.equal('two', root.getItem(1).tag) assert.equal('three', root.getItem(2).tag) test.finish(); }; exports['test_attribute_values'] = function(test, assert) { var XML = et.XML; var root = XML('<doc alpha="Alpha" beta="Beta" gamma="Gamma"/>'); assert.equal('Alpha', root.attrib['alpha']); assert.equal('Beta', root.attrib['beta']); assert.equal('Gamma', root.attrib['gamma']); test.finish(); };
Add simple attributes test case
Add simple attributes test case
JavaScript
apache-2.0
racker/node-elementtree
f8c3893888e1cd5d8b31e4621fe6c04b3343bfce
src/app/UI/lib/managers/statistics/client/components/routes.js
src/app/UI/lib/managers/statistics/client/components/routes.js
import React from "react"; import { Route } from "react-router"; import { View as TAView } from "ui-components/type_admin"; import Item from "./Item"; import List from "./List"; const routes = [ <Route key="charts" path="charts" component={TAView} List={List} type="stat.chart" label="Statistics" > <Route key="stat" path=":_id" component={TAView} Item={Item} type="stat.chart" /> </Route> ]; export default routes;
import React from "react"; import { Route } from "react-router"; import { View as TAView, EditTags as TAEditTags } from "ui-components/type_admin"; import Item from "./Item"; import List from "./List"; const routes = [ <Route key="charts" path="charts" component={TAView} List={List} type="stat.chart" label="Statistics" > <Route path=":_id" component={TAView} Item={Item} type="stat.chart" > <Route path="tags" component={TAView} Action={TAEditTags} type="stat.chart" /> </Route> </Route> ]; export default routes;
Add edit tags to statistics chart
UI: Add edit tags to statistics chart
JavaScript
mit
Combitech/codefarm,Combitech/codefarm,Combitech/codefarm
d6ab81e3e201e08004aee6ec30d4cf0d85678886
src/D3TopoJson.js
src/D3TopoJson.js
po.d3TopoJson = function(fetch) { if (!arguments.length) fetch = po.queue.json; var topoToGeo = function(url, callback) { function convert(topology, object, layer, features) { if (object.type == "GeometryCollection" && !object.properties) { object.geometries.forEach(function(g) { convert(topology, g, layer, features); }); } else { var feature = topojson.feature(topology, object); feature.properties = { layer: layer }; if (object.properties) { Object.keys(object.properties).forEach(function(property) { feature.properties[property] = object.properties[property]; }); } features.push(feature); } } return fetch(url, function(topology) { var features = []; for (var o in topology.objects) { convert(topology, topology.objects[o], o, features); } callback({ type: "FeatureCollection", features: features }); }); }; var d3TopoJson = po.d3GeoJson(topoToGeo); return d3TopoJson; };
po.d3TopoJson = function(fetch) { if (!arguments.length) fetch = po.queue.json; var topologyFeatures = function(topology) { function convert(topology, object, layer, features) { if (object.type == "GeometryCollection" && !object.properties) { object.geometries.forEach(function(g) { convert(topology, g, layer, features); }); } else { var feature = topojson.feature(topology, object); feature.properties = { layer: layer }; if (object.properties) { Object.keys(object.properties).forEach(function(property) { feature.properties[property] = object.properties[property]; }); } features.push(feature); } } var features = []; for (var o in topology.objects) { convert(topology, topology.objects[o], o, features); } return features; }; var topoToGeo = function(url, callback) { return fetch(url, function(topology) { callback({ type: "FeatureCollection", features: topologyFeatures(topology) }); }); }; var d3TopoJson = po.d3GeoJson(topoToGeo); d3TopoJson.topologyFeatures = function(x) { if (!arguments.length) return topologyFeatures; topologyFeatures = x; return d3TopoJson; }; return d3TopoJson; };
Allow changing the function used to extract GeoJSON features from TopoJSON.
Allow changing the function used to extract GeoJSON features from TopoJSON.
JavaScript
bsd-3-clause
dillan/mapsense.js,RavishankarDuMCA10/mapsense.js,sfchronicle/mapsense.js,manueltimita/mapsense.js,cksachdev/mapsense.js,mapsense/mapsense.js,shkfnly/mapsense.js,Laurian/mapsense.js,gimlids/mapsense.js
97e1d783d9a09dca204dff19bf046fc0af198643
test/js/thumbs_test.js
test/js/thumbs_test.js
window.addEventListener('load', function(){ // touchstart module('touchstart', environment); test('should respond to touchstart', 1, function() { listen('touchstart').trigger('mousedown'); }); // touchend module('touchend', environment); test('should respond to touchend', 1, function() { listen('touchend').trigger('mouseup'); }); // touchmove module('touchmove', environment); test('should respond to touchmove', 1, function() { listen('touchmove').trigger('mousemove'); }); });
window.addEventListener('load', function(){ // mousedown module('mousedown', environment); test('should respond to mousedown', 1, function() { listen('mousedown').trigger('mousedown'); }); // mouseup module('mouseup', environment); test('should respond to mouseup', 1, function() { listen('mouseup').trigger('mouseup'); }); // mousemove module('mousemove', environment); test('should respond to mousemove', 1, function() { listen('mousemove').trigger('mousemove'); }); // touchstart module('touchstart', environment); test('should respond to touchstart', 1, function() { listen('touchstart').trigger('mousedown'); }); // touchend module('touchend', environment); test('should respond to touchend', 1, function() { listen('touchend').trigger('mouseup'); }); // touchmove module('touchmove', environment); test('should respond to touchmove', 1, function() { listen('touchmove').trigger('mousemove'); }); });
Add mousedown/mouseup/mousemove to test suite.
Add mousedown/mouseup/mousemove to test suite. To make sure that we do not clobber those events.
JavaScript
mit
mwbrooks/thumbs.js,pyrinelaw/thumbs.js,pyrinelaw/thumbs.js
11ec2067d683564efe69793ee2345e05d8264e94
lib/flux_mixin.js
lib/flux_mixin.js
var React = require("react"); module.exports = { propTypes: { flux: React.PropTypes.object }, childContextTypes: { flux: React.PropTypes.object }, contextTypes: { flux: React.PropTypes.object }, getChildContext: function() { return { flux: this.context.flux || this.props.flux }; } };
var React = require("react"); module.exports = { propTypes: { flux: React.PropTypes.object.isRequired }, childContextTypes: { flux: React.PropTypes.object }, getChildContext: function() { return { flux: this.props.flux }; } };
Make Fluxbox.Mixin only for the top-level components
Make Fluxbox.Mixin only for the top-level components
JavaScript
mit
alcedo/fluxxor,dantman/fluxxor,chimpinano/fluxxor,nagyistoce/fluxxor,VincentHoang/fluxxor,vsakaria/fluxxor,dantman/fluxxor,nagyistoce/fluxxor,davesag/fluxxor,hoanglamhuynh/fluxxor,demiazz/fluxxor,davesag/fluxxor,BinaryMuse/fluxxor,dantman/fluxxor,davesag/fluxxor,VincentHoang/fluxxor,hoanglamhuynh/fluxxor,STRML/fluxxor,chimpinano/fluxxor,webcoding/fluxxor,chimpinano/fluxxor,SqREL/fluxxor,hoanglamhuynh/fluxxor,nagyistoce/fluxxor,STRML/fluxxor,andrewslater/fluxxor,thomasboyt/fluxxor
7d566b878a58ec91c2f88e3bd58ff5d7ec9b41df
lib/orbit/main.js
lib/orbit/main.js
/** Contains core methods and classes for Orbit.js @module orbit @main orbit */ // Prototype extensions if (!Array.prototype.forEach) { Array.prototype.forEach = function (fn, scope) { var i, len; for (i = 0, len = this.length; i < len; ++i) { if (i in this) { fn.call(scope, this[i], i, this); } } }; } /** Namespace for core Orbit methods and classes. @class Orbit @static */ var Orbit = {}; export default Orbit;
/** Contains core methods and classes for Orbit.js @module orbit @main orbit */ /** Namespace for core Orbit methods and classes. @class Orbit @static */ var Orbit = {}; export default Orbit;
Remove prototype extensions. ES5.1 now required.
Remove prototype extensions. ES5.1 now required.
JavaScript
mit
greyhwndz/orbit.js,orbitjs/orbit.js,orbitjs/orbit-core,lytbulb/orbit.js,opsb/orbit.js,opsb/orbit.js,rollokb/orbit.js,lytbulb/orbit.js,ProlificLab/orbit.js,SmuliS/orbit.js,orbitjs/orbit.js,rollokb/orbit.js,jpvanhal/orbit.js,greyhwndz/orbit.js,beni55/orbit.js,jpvanhal/orbit.js,ProlificLab/orbit.js,SmuliS/orbit.js,beni55/orbit.js,jpvanhal/orbit-core,jpvanhal/orbit-core
49adc111cd02ea1d1d22281f172fda0819876970
main.js
main.js
var game = new Phaser.Game(600, 800, Phaser.AUTO, '', {preload: preload, create: create, update: update}); function preload() { game.load.image('player', 'assets/player.png'); } var player; function create() { player = game.add.sprite(game.world.width / 2 - 50, game.world.height - 76, 'player'); } function update() { }
var game = new Phaser.Game(600, 800, Phaser.AUTO, '', {preload: preload, create: create, update: update}); function preload() { game.load.image('player', 'assets/player.png'); } var player; var cursors; function create() { game.physics.startSystem(Phaser.Physics.ARCADE); player = game.add.sprite(game.world.width / 2 - 50, game.world.height - 76, 'player'); game.physics.arcade.enable(player); player.body.collideWorldBounds = true; cursors = game.input.keyboard.createCursorKeys(); } function update() { player.body.velocity.x = 0; player.body.velocity.y = 0; if (cursors.left.isDown) { player.body.velocity.x = -200; } else if (cursors.right.isDown) { player.body.velocity.x = 200; } if (cursors.up.isDown) { player.body.velocity.y = -200; } else if (cursors.down.isDown) { player.body.velocity.y = 200; } }
Allow player to move up/down/right/left
Allow player to move up/down/right/left
JavaScript
mit
Acaki/WWW_project,Acaki/WWW_project,Acaki/WWW_project
3f32dd2bede0cb23f5453891d7b92a83e90c2d71
routes/apiRoot.js
routes/apiRoot.js
var contentType = require('../middleware/contentType'), config = require('../config'); function apiRoot(req, res) { var root = config.get('apiEndpoint'); var answer = { motd: 'Welcome to the NGP VAN OSDI Service!', max_pagesize: 200, vendor_name: 'NGP VAN, Inc.', product_name: 'VAN', osdi_version: '1.0', _links: { self: { href: root, title: 'NGP VAN OSDI Service Entry Point' }, 'osdi:tags': { 'href': root + 'tags', 'title': 'The collection of tags in the system' }, 'osdi:questions': { 'href': root + 'questions', 'title': 'The collection of questions in the system' }, 'osdi:people': { 'href': root + 'people', 'title': 'The collection of people in the system' } } }; return res.status(200).send(answer); } module.exports = function (app) { app.get('/api/v1/', contentType, apiRoot); };
var contentType = require('../middleware/contentType'), config = require('../config'); function apiRoot(req, res) { var root = config.get('apiEndpoint'); var answer = { motd: 'Welcome to the NGP VAN OSDI Service!', max_pagesize: 200, vendor_name: 'NGP VAN, Inc.', product_name: 'VAN', osdi_version: '1.0', _links: { self: { href: root, title: 'NGP VAN OSDI Service Entry Point' }, 'osdi:tags': { 'href': root + 'tags', 'title': 'The collection of tags in the system' }, 'osdi:questions': { 'href': root + 'questions', 'title': 'The collection of questions in the system' }, "osdi:person_signup_helper": { "href": root + 'people/person_signup', "title": "The person signup helper for the system" } } }; return res.status(200).send(answer); } module.exports = function (app) { app.get('/api/v1/', contentType, apiRoot); };
Correct AEP resource for person signup helper
Correct AEP resource for person signup helper Signed-off-by: shaisachs <47bd79f9420edf5d0991d1e2710179d4e040d480@ngpvan.com>
JavaScript
apache-2.0
NGPVAN/osdi-service,joshco/osdi-service
929e85200848bb9974eb480efa9945c6af3250f4
resource-router-middleware.js
resource-router-middleware.js
var Router = require('express').Router; var keyed = ['get', 'read', 'put', 'patch', 'update', 'del', 'delete'], map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' }; module.exports = function ResourceRouter(route) { route.mergeParams = route.mergeParams ? true : false; var router = Router({mergeParams: route.mergeParams}), key, fn, url; if (route.middleware) router.use(route.middleware); if (route.load) { router.param(route.id, function(req, res, next, id) { route.load(req, id, function(err, data) { if (err) return res.status(404).send(err); req[route.id] = data; next(); }); }); } for (key in route) { fn = map[key] || key; if (typeof router[fn]==='function') { url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/'; router[fn](url, route[key]); } } return router; }; module.exports.keyed = keyed;
var Router = require('express').Router; var keyed = ['get', 'read', 'put', 'update', 'patch', 'modify', 'del', 'delete'], map = { index:'get', list:'get', read:'get', create:'post', update:'put', modify:'patch' }; module.exports = function ResourceRouter(route) { route.mergeParams = route.mergeParams ? true : false; var router = Router({mergeParams: route.mergeParams}), key, fn, url; if (route.middleware) router.use(route.middleware); if (route.load) { router.param(route.id, function(req, res, next, id) { route.load(req, id, function(err, data) { if (err) return res.status(404).send(err); req[route.id] = data; next(); }); }); } for (key in route) { fn = map[key] || key; if (typeof router[fn]==='function') { url = ~keyed.indexOf(key) ? ('/:'+route.id) : '/'; router[fn](url, route[key]); } } return router; }; module.exports.keyed = keyed;
Add modify to keyed methods to enable patch with id
Add modify to keyed methods to enable patch with id
JavaScript
bsd-3-clause
developit/resource-router-middleware
4383d7d3f566e33e5d4dc86e64fb1539ddad1642
src/compressor.js
src/compressor.js
'use strict'; var es = require('event-stream'), path = require('path'), zlib = require('zlib'); var compressibles = [ '.js', '.json', '.css', '.html' ]; function isCompressibleFile( file ) { var ext = path.extname( file.path ).toLowerCase(); return ( compressibles.indexOf( ext ) > -1 ); } module.exports = function() { return es.map( function( file, cb ) { if( !isCompressibleFile( file ) ) { cb( null, file ); return; } zlib.gzip( file.contents, function( err, result ) { if( err ) { cb( err, null ); return; } file.path += '.gz'; file.contents = result; cb( null, file ); } ); } ); }; module.exports._isCompressibleFile = isCompressibleFile;
'use strict'; var es = require('event-stream'), path = require('path'), zlib = require('zlib'); var compressibles = [ '.js', '.css', '.html' ]; function isCompressibleFile( file ) { var ext = path.extname( file.path ).toLowerCase(); return ( compressibles.indexOf( ext ) > -1 ); } module.exports = function() { return es.map( function( file, cb ) { if( !isCompressibleFile( file ) ) { cb( null, file ); return; } zlib.gzip( file.contents, function( err, result ) { if( err ) { cb( err, null ); return; } file.path += '.gz'; file.contents = result; cb( null, file ); } ); } ); }; module.exports._isCompressibleFile = isCompressibleFile;
Revert "adding JSON to the list of extensions that should be compressed"
Revert "adding JSON to the list of extensions that should be compressed" This reverts commit c90513519febf8feeea78b06da6a467bb1085948.
JavaScript
apache-2.0
Brightspace/gulp-frau-publisher,Brightspace/gulp-frau-publisher,Brightspace/frau-publisher,Brightspace/frau-publisher
fbf98e6125a702a63857688cfa07fefa6791a909
src/stages/main/patchers/SoakedMemberAccessOpPatcher.js
src/stages/main/patchers/SoakedMemberAccessOpPatcher.js
import NodePatcher from './../../../patchers/NodePatcher.js'; export default class SoakedMemberAccessOpPatcher extends NodePatcher { patchAsExpression() { } patchAsStatement() { this.patchAsExpression(); } }
import NodePatcher from './../../../patchers/NodePatcher.js'; export default class SoakedMemberAccessOpPatcher extends NodePatcher { patchAsExpression() { throw this.error('cannot patch soaked member access (e.g. `a?.b`) yet'); } }
Throw when encountering a SoakedMemberAccessOp.
Throw when encountering a SoakedMemberAccessOp.
JavaScript
mit
decaffeinate/decaffeinate,alangpierce/decaffeinate,decaffeinate/decaffeinate,eventualbuddha/decaffeinate,alangpierce/decaffeinate,eventualbuddha/decaffeinate,alangpierce/decaffeinate
666e5e1efa16941ac7ded51444b566a0d5faedd1
move-plugins/moveplugins.js
move-plugins/moveplugins.js
module.exports.movePlugins = function (src, dest) { var exec = require('child_process').exec console.log(`Copying ${src} to ${dest}`) exec(`rm -rf ${dest}${src}`, function (error) { if (error) { console.error(`exec error: ${error}`) } else { exec(`cp -r ${src} ${dest}`, function (error, stdout, stderr) { if (error) { console.error(`exec error: ${error}`) } }) } }) }
module.exports.movePlugins = function (src, dest) { var exec = require('child_process').exec exec(`rm ${dest}${src} -rf`, function (error) { if (error) console.error(`exec error: ${error}`) exec(`cp -r ${src} ${dest}`, function (error, stdout, stderr) { if (error) console.error(`exec error: ${error}`) }) }) }
Revert "fixed possible bug & Mac OSX compatibility issue with rm"
Revert "fixed possible bug & Mac OSX compatibility issue with rm" This reverts commit b4ed13e1cd70025d4b8bb4b29e98334b00bfdbed.
JavaScript
mit
Lamassau/PiTrol,Lamassau/PiTrol,AlhasanIQ/PiTrol,fadeenk/PiTrol,fadeenk/PiTrol,AlhasanIQ/PiTrol
eaf69c1a63c41db025a65d87e104390deb6db591
components/CopyButton.js
components/CopyButton.js
import React from 'react'; import ClipboardJS from 'clipboard'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.btnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.btnRef.current, { text: () => this.props.content, }); } render() { return ( <button ref={this.btnRef} key="copy" onClick={() => {}} className="btn-copy" data-clipboard-target="#testCopyTarget" > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
import React from 'react'; import ClipboardJS from 'clipboard'; export default class CopyButton extends React.PureComponent { constructor(props) { super(props); this.btnRef = React.createRef(); this.clipboardRef = React.createRef(); } static defaultProps = { content: '', }; componentDidMount() { this.clipboardRef.current = new ClipboardJS(this.btnRef.current, { text: () => this.props.content, }); } render() { return ( <button ref={this.btnRef} key="copy" onClick={() => {}} className="btn-copy" > 複製到剪貼簿 <style jsx>{` .btn-copy { margin-left: 10px; } `}</style> </button> ); } }
Solve 'invalid target element' error
Solve 'invalid target element' error
JavaScript
mit
cofacts/rumors-site,cofacts/rumors-site
f0d2f99dbdd764915efd138361f815e86a3d2210
app/assets/javascripts/angular/services/annotation_refresher.js
app/assets/javascripts/angular/services/annotation_refresher.js
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { return e.name.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { tags: t.join(","), until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { return e.name.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { 'tags[]': t, until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
Send annotation tags as array.
Send annotation tags as array.
JavaScript
apache-2.0
alonpeer/promdash,lborguetti/promdash,jonnenauha/promdash,lborguetti/promdash,lborguetti/promdash,jonnenauha/promdash,jmptrader/promdash,alonpeer/promdash,thooams/promdash,jonnenauha/promdash,prometheus/promdash,prometheus/promdash,juliusv/promdash,juliusv/promdash,jmptrader/promdash,juliusv/promdash,jmptrader/promdash,jonnenauha/promdash,thooams/promdash,alonpeer/promdash,lborguetti/promdash,thooams/promdash,thooams/promdash,prometheus/promdash,juliusv/promdash,alonpeer/promdash,jmptrader/promdash,prometheus/promdash
1896a56db306f7cadfc004373839887ce6b3c5cd
app/assets/javascripts/angular/services/annotation_refresher.js
app/assets/javascripts/angular/services/annotation_refresher.js
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", function($http) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { return e.name.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { 'tags[]': t, until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
angular.module("Prometheus.services").factory('AnnotationRefresher', ["$http", "VariableInterpolator", function($http, VariableInterpolator) { return function(graph, scope) { var tags = graph.tags.map(function(e) { if (e.name) { var n = VariableInterpolator(e.name, scope.vars); return n.split(",").map(function(s) { return s.trim(); }); } else { return ""; } }) if (tags.length) { var range = Prometheus.Graph.parseDuration(graph.range); var until = Math.floor(graph.endTime || Date.now()) / 1000; tags.forEach(function(t) { $http.get('/annotations', { params: { 'tags[]': t, until: until, range: range } }) .then(function(payload) { scope.$broadcast('annotateGraph', payload.data.posts); }, function(response) { scope.errorMessages.push("Error " + response.status + ": Error occurred fetching annotations."); }); }); } }; }]);
Allow for tags to be interpolated variables.
Allow for tags to be interpolated variables.
JavaScript
apache-2.0
prometheus/promdash,prometheus/promdash,thooams/promdash,lborguetti/promdash,jmptrader/promdash,juliusv/promdash,jonnenauha/promdash,lborguetti/promdash,lborguetti/promdash,jmptrader/promdash,prometheus/promdash,jmptrader/promdash,juliusv/promdash,juliusv/promdash,thooams/promdash,jonnenauha/promdash,lborguetti/promdash,jmptrader/promdash,alonpeer/promdash,juliusv/promdash,alonpeer/promdash,alonpeer/promdash,thooams/promdash,jonnenauha/promdash,thooams/promdash,jonnenauha/promdash,prometheus/promdash,alonpeer/promdash
ce79d7a652564fed3b86000e9c295f00f28e5223
examples/myShellExtension.js
examples/myShellExtension.js
'use strict'; exports.register = function (callback) { var commands = [{ name : 'hello', desc : 'print Hello, John', options : { wizard : false, params : { required: 'name', optional: 'etc...' } }, handler : function (callback, args) { console.log ('Hello, ' + args.join (' ')); callback (); } }, { name : 'wizard', desc : 'begins a wizard', options : { wizard : true }, handler : function (callback, args) { var wizard = [{ /* Inquirer definition... */ type: 'input', name: 'zog', message: 'tell zog' }]; callback (wizard, function (answers) { /* stuff on answers */ if (answers.zog === 'zog') { console.log ('zog zog'); } else { console.log ('lokthar?'); } /* * You can return false if you must provide several wizard with only * one call to this command handler. * You can call callback () without argument in order to return to the * prompt instead of returning true. */ return true; }); } }]; callback (null, commands); }; exports.unregister = function (callback) { /* internal stuff */ callback (); };
'use strict'; var cmd = {}; cmd.hello = function (callback, args) { console.log ('Hello, ' + args.join (' ')); callback (); }; cmd.wizard = function (callback) { var wizard = [{ /* Inquirer definition... */ type: 'input', name: 'zog', message: 'tell zog' }]; callback (wizard, function (answers) { /* stuff on answers */ if (answers.zog === 'zog') { console.log ('zog zog'); } else { console.log ('lokthar?'); } /* * You can return false if you must provide several wizard with only * one call to this command handler. * You can call callback () without argument in order to return to the * prompt instead of returning true. */ return true; }); }; exports.register = function (callback) { var commands = [{ name : 'hello', desc : 'print Hello, John', options : { wizard : false, params : { required: 'name', optional: 'etc...' } }, handler : cmd.hello }, { name : 'wizard', desc : 'begins a wizard', options : { wizard : true }, handler : cmd.wizard }]; callback (null, commands); }; exports.unregister = function (callback) { /* internal stuff */ callback (); };
Split the register function for the readability.
Split the register function for the readability.
JavaScript
mit
Xcraft-Inc/shellcraft.js
efda627489ccfa3bc6e3f64a40623da2d62ee316
gatsby-browser.js
gatsby-browser.js
exports.onClientEntry = () => { (() => { function OptanonWrapper() { } // eslint-disable-line no-unused-vars })(); };
exports.onClientEntry = () => { (() => { function OptanonWrapper() {} // eslint-disable-line no-unused-vars })(); }; // Always start at the top of the page on a route change. exports.onInitialClientRender = () => { if (!window.location.hash) { window.scrollTo(0, 0); } else { window.location = window.location.hash; } };
Add function to start at top of new page unless window.location has a hash
[MARKENG-156] Add function to start at top of new page unless window.location has a hash
JavaScript
apache-2.0
postmanlabs/postman-docs,postmanlabs/postman-docs
65a50b9a92299366e37a412d99b1b31a4f15b3d9
lib/cape/mixins/propagator_methods.js
lib/cape/mixins/propagator_methods.js
'use strict'; var PropagatorMethods = { attach: function(component) { var target = component; for (var i = 0, len = this._.components.length; i < len; i++) { if (this._.components[i] === component) return; } this._.components.push(component); }, detach: function(component) { for (var i = 0, len = this._.components.length; i < len; i++) { if (this._.components[i] === component) { this._.components.splice(i, 1); break; } } }, propagate: function() { for (var i = this._.components.length; i--;) this._.components[i].refresh(); } } module.exports = PropagatorMethods;
'use strict' let PropagatorMethods = { attach: function(component) { let target = component for (let i = 0, len = this._.components.length; i < len; i++) { if (this._.components[i] === component) return } this._.components.push(component) }, detach: function(component) { for (let i = 0, len = this._.components.length; i < len; i++) { if (this._.components[i] === component) { this._.components.splice(i, 1) break } } }, propagate: function() { for (let i = this._.components.length; i--;) this._.components[i].refresh() } } module.exports = PropagatorMethods
Rewrite PropagatorMethods module with ES6 syntax
Rewrite PropagatorMethods module with ES6 syntax
JavaScript
mit
capejs/capejs,capejs/capejs
ced84f283761f38156960f2d8e001ba6f3cd2b08
src/hook/index.js
src/hook/index.js
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class HookGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
import { Base } from 'yeoman-generator'; import generatorArguments from './arguments'; import generatorOptions from './options'; import generatorSteps from './steps'; export default class HookGenerator extends Base { constructor(...args) { super(...args); Object.keys(generatorArguments).forEach(key => this.argument(key, generatorArguments[key])); Object.keys(generatorOptions).forEach(key => this.option(key, generatorOptions[key])); this.description = 'Scaffold a custom hook in api/hooks'; } get configuring() { return generatorSteps.configuring; } get conflicts() { return generatorSteps.conflicts; } get default() { return generatorSteps.default; } get end() { return generatorSteps.end; } get initializing() { return generatorSteps.initializing } get install() { return generatorSteps.install; } get prompting() { return generatorSteps.prompting } get writing() { return generatorSteps.writing; } }
Add description to hook generator
Add description to hook generator
JavaScript
mit
tnunes/generator-trails,IncoCode/generator-sails-rest-api,ghaiklor/generator-sails-rest-api,jaumard/generator-trails,konstantinzolotarev/generator-trails,italoag/generator-sails-rest-api,italoag/generator-sails-rest-api,ghaiklor/generator-sails-rest-api
88135630eeee214e6a6777b325970084305a3028
src/i18n/index.js
src/i18n/index.js
/** * You can customize the initial state of the module from the editor initialization * ```js * const editor = grapesjs.init({ * i18n: { * locale: 'en', * messages: { * en: { * hello: 'Hello', * }, * ... * } * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const i18n = editor.I18n; * ``` * * @module I18n */ import messages from './messages'; export default () => { let em; let config; const { language } = window.navigator || {}; const localeDef = language ? language.split('-')[0] : 'en'; const configDef = { locale: localeDef, localeFallback: 'en', counter: 'n', messages }; return { name: 'I18n', /** * Get module configurations * @returns {Object} Configuration object */ getConfig() { return config; }, /** * Initialize module * @param {Object} config Configurations * @private */ init(opts = {}) { config = { ...configDef, ...opts }; em = opts.em; this.em = em; return this; } }; };
/** * You can customize the initial state of the module from the editor initialization * ```js * const editor = grapesjs.init({ * i18n: { * locale: 'en', * messages: { * en: { * hello: 'Hello', * }, * ... * } * } * }) * ``` * * Once the editor is instantiated you can use its API. Before using these methods you should get the module from the instance * * ```js * const i18n = editor.I18n; * ``` * * @module I18n */ import messages from './messages'; export default () => { const { language } = window.navigator || {}; const localeDef = language ? language.split('-')[0] : 'en'; const config = { locale: localeDef, localeFallback: 'en', counter: 'n', messages }; return { name: 'I18n', config, /** * Get module configurations * @returns {Object} Configuration object */ getConfig() { return this.config; }, /** * Update current locale * @param {String} locale Locale value * @returns {this} * @example * i18n.setLocale('it'); */ setLocale(locale) { this.config.locale = locale; return this; }, /** * Get current locale * @returns {String} Current locale value */ getLocale() { return this.config.locale; }, /** * Initialize module * @param {Object} config Configurations * @private */ init(opts = {}) { this.em = opts.em; return this; } }; };
Add locales methods to i18n
Add locales methods to i18n
JavaScript
bsd-3-clause
artf/grapesjs,QuorumDMS/grapesjs,artf/grapesjs,artf/grapesjs,QuorumDMS/grapesjs
9963a7f7e6f161fa6b9b0085ae3f48df33c2fb20
package.js
package.js
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.3+0.0.42" }); Package._transitional_registerBuildPlugin({ name: "compileHarmony", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: { "traceur": "0.0.42" } }); Package.on_use(function (api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); // Export `module.exports` and `exports` down the package pipeline api.use('exports'); api.export(['module', 'exports']); }); Package.on_test(function (api) { api.use(['harmony', 'tinytest']); api.add_files([ 'harmony_test_setup.js', 'harmony_tests.js', 'tests/harmony_test_setup.next.js', 'tests/harmony_tests.next.js' ], ["client", "server"]); });
var path = Npm.require("path"); Package.describe({ summary: "JavaScript.next-to-JavaScript-of-today compiler", version: "1.0.3+0.0.42" }); Package._transitional_registerBuildPlugin({ name: "compileHarmony", use: [], sources: [ "plugin/compile-harmony.js" ], npmDependencies: { "traceur": "0.0.42" } }); Package.on_use(function (api) { // The location of this runtime file is not supposed to change: // http://git.io/B2s0Tg var dir = ".npm/plugin/compileHarmony/node_modules/traceur/bin/"; api.add_files(path.join(dir, "traceur-runtime.js")); // Export `module.exports` and `exports` down the package pipeline api.imply('exports'); }); Package.on_test(function (api) { api.use(['harmony', 'tinytest']); api.add_files([ 'harmony_test_setup.js', 'harmony_tests.js', 'tests/harmony_test_setup.next.js', 'tests/harmony_tests.next.js' ], ["client", "server"]); });
Use `imply` instead of `use` and `export` together
Use `imply` instead of `use` and `export` together This commit uses the `api.imply` shorthand to use a package and export its exports.
JavaScript
mit
mquandalle/meteor-harmony
92e4e867c02ab0d55ad54539568ac29692f01733
src/index.node.js
src/index.node.js
/* eslint-env node */ const Canvas = require('canvas'); const fs = require('fs'); const { Image } = Canvas; /** * Create a new canvas object with height and width * set to the given values. * * @param width {number} The width of the canvas. * @param height {number} The height of the canvas. * * @return {Canvas} A canvas object with * height and width set to the given values. */ function createCanvas(width, height) { return new Canvas(width, height); } /** * Load the image given by the file path, returning * a promise to the image represented by the given path. * * @parm path {string} The path to the image. * * @return {Image} An image element referring to * the given path. */ function loadImage(path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { return reject(err); } const image = new Image(); image.src = data; return resolve(image); }); }); } module.exports = { createCanvas, loadImage, };
/* eslint-env node */ const Canvas = require('canvas'); const fs = require('fs'); const { Image } = Canvas; /** * Create a new canvas object with height and width * set to the given values. * * @param width {number} The width of the canvas. * @param height {number} The height of the canvas. * * @return {Canvas} A canvas object with * height and width set to the given values. */ function createCanvas(width, height) { return new Canvas(width, height); } /** * Load the image given by the file path, returning * a promise to the image represented by the given path. * * @parm path {string} The path to the image. * * @return {Image} An image element referring to * the given path. */ function loadImage(path) { return new Promise((resolve, reject) => { fs.readFile(path, (err, data) => { if (err) { reject(err); return; } const image = new Image(); image.onload = () => resolve(image); image.onerror = err => reject(err); image.src = data; return resolve(image); }); }); } module.exports = { createCanvas, loadImage, };
Use image onload and onerror
Use image onload and onerror
JavaScript
mit
bschlenk/canvas-everywhere
053ce99dec181fa886818c69fe80507257dffd56
src/Views/PickList.js
src/Views/PickList.js
/* * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved. */ /** * @class Mobile.SalesLogix.Views.PickList * * * @extends Sage.Platform.Mobile.List * */ define('Mobile/SalesLogix/Views/PickList', [ 'dojo/_base/declare', 'dojo/string', 'Sage/Platform/Mobile/List' ], function( declare, string, List ) { return declare('Mobile.SalesLogix.Views.PickList', [List], { //Templates itemTemplate: new Simplate([ '<h3>{%: $.text %}</h3>' ]), //View Properties id: 'pick_list', expose: false, resourceKind: 'picklists', resourceProperty: 'items', contractName: 'system', activateEntry: function(params) { if (this.options.keyProperty === 'text' && !this.options.singleSelect) { params.key = params.descriptor; } this.inherited(arguments); }, show: function(options) { this.set('title', options && options.title || this.title); this.inherited(arguments); }, formatSearchQuery: function(searchQuery) { return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]); } }); });
/* * Copyright (c) 1997-2013, SalesLogix, NA., LLC. All rights reserved. */ /** * @class Mobile.SalesLogix.Views.PickList * * * @extends Sage.Platform.Mobile.List * */ define('Mobile/SalesLogix/Views/PickList', [ 'dojo/_base/declare', 'dojo/string', 'Sage/Platform/Mobile/List' ], function( declare, string, List ) { return declare('Mobile.SalesLogix.Views.PickList', [List], { //Templates itemTemplate: new Simplate([ '<h3>{%: $.text %}</h3>' ]), //View Properties id: 'pick_list', expose: false, resourceKind: 'picklists', resourceProperty: 'items', contractName: 'system', activateEntry: function(params) { if (this.options.keyProperty === 'text' && !this.options.singleSelect) { params.key = params.descriptor; } this.inherited(arguments); }, show: function(options) { this.set('title', options && options.title || this.title); if (options.keyProperty) { this.idProperty = options.keyProperty; } if (options.textProperty) { this.labelProperty = options.textProperty; } this.inherited(arguments); }, formatSearchQuery: function(searchQuery) { return string.substitute('upper(text) like "${0}%"', [this.escapeSearchQuery(searchQuery.toUpperCase())]); } }); });
Update the idProperty and labelProperty of the store properly based on what the picklist is using.
Update the idProperty and labelProperty of the store properly based on what the picklist is using.
JavaScript
apache-2.0
Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix,Saleslogix/argos-saleslogix
433541eee8c71f67265240dcd35323cfb0790e2b
src/about.js
src/about.js
import h from 'hyperscript'; import fetch from 'unfetch'; import audio from './audio'; import aboutSrc from './content/about.md'; let visible = false; let fetched = false; const toggle = () => { visible = !visible; document.body.classList[visible ? 'remove' : 'add']('mod-overflow-hidden'); about.classList[visible ? 'remove' : 'add']('mod-hidden'); audio[visible ? 'pause' : 'play'](); if (!fetched) { fetched = true; fetch(aboutSrc) .then(response => response.text()) .then(data => { about.innerHTML = data; about.appendChild(closeButton); }); } }; const about = h('div.about.mod-hidden') const closeButton = h('div.about-close-button', { onclick: toggle }, '×'); document.body.appendChild(about); export default { toggle };
import h from 'hyperscript'; import fetch from 'unfetch'; import audio from './audio'; import aboutSrc from './content/about.md'; let visible = false; let fetched = false; const toggle = async () => { visible = !visible; document.body.classList[visible ? 'remove' : 'add']('mod-overflow-hidden'); about.classList[visible ? 'remove' : 'add']('mod-hidden'); audio[visible ? 'pause' : 'play'](); if (!fetched) { fetched = true; const response = await fetch(aboutSrc); const data = await response.text(); about.innerHTML = data; about.appendChild(closeButton); } }; const about = h('div.about.mod-hidden'); const closeButton = h('div.about-close-button', { onclick: toggle }, '×'); document.body.appendChild(about); export default { toggle };
Switch markdown loading to fetch/async/await
Switch markdown loading to fetch/async/await
JavaScript
apache-2.0
puckey/dance-tonite,puckey/dance-tonite
6dbe686652f6e642000b183a4063d68f27c8b6e0
karma.conf.js
karma.conf.js
module.exports = (config) => { config.set({ frameworks: ['mocha', 'karma-typescript'], browsers: ['ChromeHeadless'], singleRun: true, concurrency: Infinity, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_WARN, files: [ 'src/*.ts', 'test/*.ts', ], preprocessors: { '**/*.ts': ['karma-typescript'], }, karmaTypescriptConfig: { compilerOptions: { target: 'es6', baseUrl: __dirname, }, }, }) };
module.exports = (config) => { config.set({ frameworks: ['mocha', 'karma-typescript'], browsers: ['ChromeHeadless'], singleRun: true, concurrency: Infinity, reporters: ['mocha'], port: 9876, colors: true, logLevel: config.LOG_WARN, files: [ 'src/*.ts', 'test/*.ts', { pattern: 'test/*.html', watched: false, included: false, served: true, }, ], preprocessors: { '**/*.ts': ['karma-typescript'], }, karmaTypescriptConfig: { compilerOptions: { target: 'es6', baseUrl: __dirname, }, }, }); };
Add file rule for test template file
Add file rule for test template file
JavaScript
mit
marcoms/make-element,marcoms/make-element,marcoms/make-element
a7eef3262e571e51f2f8a0403dbfbd7b51b1946a
src/tools/courseraSampleToArray.js
src/tools/courseraSampleToArray.js
var http = require('http'); /* * Convert from coursera sample format to javascript array. * e.g : * * a.txt : * * 111 * 222 * 333 * 444 * * converts to * * [111,222,333,444] * */ var strToArray = function(str) { return str.trim().split('\r\n').map(function (elStr) { return parseInt(elStr); }) } function simpleHttpHandler(url, callback) { http.get(url, function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { callback( str ) }); }); } exports.getNumberArray = function (url, callback) { simpleHttpHandler(url, function (str) { var numberArry = str.trim().split('\r\n').map(function (elStr) { return parseInt(elStr); }) callback(numberArry); }); };
var http = require('http'); var courseraHttpHandler = function(url, processor, callback) { http.get(url, function(response) { var str = ''; response.on('data', function (chunk) { str += chunk; }); response.on('end', function () { var processedStr = str.trim().split('\r\n').map( processor ); callback( processedStr ); }); }); } var strToInt = function (str) { return parseInt(str); } /* * Convert from coursera sample format to javascript array. * e.g : * * a.txt : * * 111 * 222 * 333 * 444 * * converts to * * [111,222,333,444] * */ exports.getNumberArray = function (url, callback) { courseraHttpHandler(url, strToInt, callback); }; exports.getAdjacencylist = function (url, callback) { courseraHttpHandler(url, function (str) { return str.trim().split('\t').map( strToInt ); }, callback); }
Refactor coursera tool. Add getAdjacencylist function.
Refactor coursera tool. Add getAdjacencylist function. lzhoucs|G580|Win8|WebStorm9
JavaScript
apache-2.0
lzhoucs/cs-algorithms
b43e6f2a5fdbb355369d82a2c5ff65f5b0e42a23
webroot/rsrc/js/application/repository/repository-crossreference.js
webroot/rsrc/js/application/repository/repository-crossreference.js
/** * @provides javelin-behavior-repository-crossreference * @requires javelin-behavior * javelin-dom * javelin-uri */ JX.behavior('repository-crossreference', function(config) { // NOTE: Pretty much everything in this file is a worst practice. We're // constrained by the markup generated by the syntax highlighters. var container = JX.$(config.container); JX.DOM.alterClass(container, 'repository-crossreference', true); JX.DOM.listen( container, 'click', 'tag:span', function(e) { var target = e.getTarget(); var map = {nc : 'class', nf : 'function'}; if (JX.DOM.isNode(target, 'span') && (target.className in map)) { var symbol = target.textContent || target.innerText; var uri = JX.$U('/diffusion/symbol/' + symbol + '/'); uri.addQueryParams({ type : map[target.className], lang : config.lang, projects : config.projects.join(','), jump : true }); window.open(uri); e.kill(); } }); });
/** * @provides javelin-behavior-repository-crossreference * @requires javelin-behavior * javelin-dom * javelin-uri */ JX.behavior('repository-crossreference', function(config) { // NOTE: Pretty much everything in this file is a worst practice. We're // constrained by the markup generated by the syntax highlighters. var container = JX.$(config.container); JX.DOM.alterClass(container, 'repository-crossreference', true); JX.DOM.listen( container, 'click', 'tag:span', function(e) { var target = e.getTarget(); var map = {nc : 'class', nf : 'function'}; while (target !== document.body) { if (JX.DOM.isNode(target, 'span') && (target.className in map)) { var symbol = target.textContent || target.innerText; var uri = JX.$U('/diffusion/symbol/' + symbol + '/'); uri.addQueryParams({ type : map[target.className], lang : config.lang, projects : config.projects.join(','), jump : true }); window.open(uri); e.kill(); break; } target = target.parentNode; } }); });
Make symbol linking more lenient.
Make symbol linking more lenient. Summary: Sometimes a symbol has a nested <span> in it. Clicks on that should count as clicks on the symbol. So keep looking for symbols among the ancestors of the click target. This is a silly method because I don't know if there's a more idiomatic way to do it in Javelin. Test Plan: Open a Differential revision where part of a symbol is highlighted. Click on the highlighted part. Symbol search opens. Reviewers: epriestley Reviewed By: epriestley CC: aran, epriestley Maniphest Tasks: T1577 Differential Revision: https://secure.phabricator.com/D3113
JavaScript
apache-2.0
parksangkil/phabricator,hach-que/unearth-phabricator,freebsd/phabricator,phacility/phabricator,dannysu/phabricator,wxstars/phabricator,schlaile/phabricator,apexstudios/phabricator,optimizely/phabricator,Soluis/phabricator,MicroWorldwide/phabricator,Drooids/phabricator,devurandom/phabricator,wikimedia/phabricator-phabricator,kanarip/phabricator,coursera/phabricator,kwoun1982/phabricator,freebsd/phabricator,wangjun/phabricator,eSpark/phabricator,huangjimmy/phabricator-1,eSpark/phabricator,benchling/phabricator,optimizely/phabricator,UNCC-OpenProjects/Phabricator,UNCC-OpenProjects/Phabricator,huaban/phabricator,devurandom/phabricator,ide/phabricator,shrimpma/phabricator,cjxgm/p.cjprods.org,vuamitom/phabricator,devurandom/phabricator,vuamitom/phabricator,Automatic/phabricator,zhihu/phabricator,gsinkovskiy/phabricator,devurandom/phabricator,hshackathons/phabricator-deprecated,Automatic/phabricator,kalbasit/phabricator,optimizely/phabricator,r4nt/phabricator,matthewrez/phabricator,benchling/phabricator,vinzent/phabricator,matthewrez/phabricator,hshackathons/phabricator-deprecated,wikimedia/phabricator-phabricator,ide/phabricator,huangjimmy/phabricator-1,christopher-johnson/phabricator,hach-que/phabricator,tanglu-org/tracker-phabricator,aik099/phabricator,wusuoyongxin/phabricator,librewiki/phabricator,parksangkil/phabricator,gsinkovskiy/phabricator,WuJiahu/phabricator,uhd-urz/phabricator,librewiki/phabricator,NigelGreenway/phabricator,Automatic/phabricator,folsom-labs/phabricator,Khan/phabricator,shl3807/phabricator,leolujuyi/phabricator,akkakks/phabricator,tanglu-org/tracker-phabricator,uhd-urz/phabricator,memsql/phabricator,huaban/phabricator,aswanderley/phabricator,Automattic/phabricator,jwdeitch/phabricator,a20012251/phabricator,wxstars/phabricator,optimizely/phabricator,kwoun1982/phabricator,wangjun/phabricator,hach-que/unearth-phabricator,coursera/phabricator,tanglu-org/tracker-phabricator,Drooids/phabricator,kanarip/phabricator,sharpwhisper/phabricator,ryancford/phabricator,Khan/phabricator,UNCC-OpenProjects/Phabricator,memsql/phabricator,shrimpma/phabricator,wusuoyongxin/phabricator,memsql/phabricator,leolujuyi/phabricator,shrimpma/phabricator,hshackathons/phabricator-deprecated,cjxgm/p.cjprods.org,gsinkovskiy/phabricator,wikimedia/phabricator-phabricator,huaban/phabricator,Soluis/phabricator,phacility/phabricator,wangjun/phabricator,hach-que/phabricator,parksangkil/phabricator,zhihu/phabricator,benchling/phabricator,WuJiahu/phabricator,coursera/phabricator,Soluis/phabricator,huaban/phabricator,folsom-labs/phabricator,Automattic/phabricator,aik099/phabricator,a20012251/phabricator,NigelGreenway/phabricator,schlaile/phabricator,akkakks/phabricator,codevlabs/phabricator,wxstars/phabricator,huangjimmy/phabricator-1,Khan/phabricator,folsom-labs/phabricator,matthewrez/phabricator,denisdeejay/phabricator,a20012251/phabricator,Drooids/phabricator,Soluis/phabricator,phacility/phabricator,WuJiahu/phabricator,r4nt/phabricator,shl3807/phabricator,r4nt/phabricator,NigelGreenway/phabricator,kalbasit/phabricator,vinzent/phabricator,sharpwhisper/phabricator,devurandom/phabricator,kwoun1982/phabricator,NigelGreenway/phabricator,Symplicity/phabricator,denisdeejay/phabricator,apexstudios/phabricator,schlaile/phabricator,shrimpma/phabricator,Symplicity/phabricator,wangjun/phabricator,christopher-johnson/phabricator,codevlabs/phabricator,cjxgm/p.cjprods.org,MicroWorldwide/phabricator,eSpark/phabricator,librewiki/phabricator,apexstudios/phabricator,wikimedia/phabricator,UNCC-OpenProjects/Phabricator,kanarip/phabricator,denisdeejay/phabricator,kanarip/phabricator,jwdeitch/phabricator,zhihu/phabricator,codevlabs/phabricator,huangjimmy/phabricator-1,tanglu-org/tracker-phabricator,telerik/phabricator,benchling/phabricator,gsinkovskiy/phabricator,matthewrez/phabricator,optimizely/phabricator,kanarip/phabricator,ryancford/phabricator,ryancford/phabricator,dannysu/phabricator,hach-que/phabricator,jwdeitch/phabricator,WuJiahu/phabricator,kwoun1982/phabricator,kalbasit/phabricator,uhd-urz/phabricator,akkakks/phabricator,uhd-urz/phabricator,vinzent/phabricator,kalbasit/phabricator,vinzent/phabricator,NigelGreenway/phabricator,wusuoyongxin/phabricator,codevlabs/phabricator,Symplicity/phabricator,Automattic/phabricator,sharpwhisper/phabricator,Drooids/phabricator,jwdeitch/phabricator,aswanderley/phabricator,dannysu/phabricator,akkakks/phabricator,hshackathons/phabricator-deprecated,memsql/phabricator,denisdeejay/phabricator,leolujuyi/phabricator,gsinkovskiy/phabricator,devurandom/phabricator,kwoun1982/phabricator,wikimedia/phabricator,eSpark/phabricator,christopher-johnson/phabricator,freebsd/phabricator,MicroWorldwide/phabricator,leolujuyi/phabricator,r4nt/phabricator,shl3807/phabricator,wikimedia/phabricator,hach-que/unearth-phabricator,huangjimmy/phabricator-1,parksangkil/phabricator,ide/phabricator,wikimedia/phabricator-phabricator,aswanderley/phabricator,aik099/phabricator,wxstars/phabricator,zhihu/phabricator,vuamitom/phabricator,Symplicity/phabricator,hach-que/phabricator,vinzent/phabricator,folsom-labs/phabricator,hach-que/unearth-phabricator,zhihu/phabricator,wusuoyongxin/phabricator,wikimedia/phabricator,christopher-johnson/phabricator,a20012251/phabricator,ide/phabricator,memsql/phabricator,MicroWorldwide/phabricator,vuamitom/phabricator,telerik/phabricator,shl3807/phabricator,hach-que/unearth-phabricator,hach-que/phabricator,aswanderley/phabricator,uhd-urz/phabricator,phacility/phabricator,a20012251/phabricator,dannysu/phabricator,telerik/phabricator,christopher-johnson/phabricator,freebsd/phabricator,Soluis/phabricator,ryancford/phabricator,sharpwhisper/phabricator,eSpark/phabricator,librewiki/phabricator,cjxgm/p.cjprods.org,akkakks/phabricator,vuamitom/phabricator,r4nt/phabricator,schlaile/phabricator,tanglu-org/tracker-phabricator,aswanderley/phabricator,dannysu/phabricator,librewiki/phabricator,Khan/phabricator,zhihu/phabricator,Automatic/phabricator,hshackathons/phabricator-deprecated,folsom-labs/phabricator,coursera/phabricator,codevlabs/phabricator,cjxgm/p.cjprods.org,sharpwhisper/phabricator,wikimedia/phabricator-phabricator,aik099/phabricator
48c94504fce5b6ccbdd84dec3e676a6867c0125f
lib/convoy.js
lib/convoy.js
var Queue = require('./queue'); var Job = require('./job'); var Worker = require('./worker'); var redis = require('./redis'); exports.redis = redis; exports.createQueue = function(name){ var q = new Queue(name); q.client = exports.redis.createClient(); q.workerClient = exports.redis.createClient(); return q; }; exports.Job = Job; exports.Worker = Worker;
var Queue = require('./queue'); var Job = require('./job'); var Worker = require('./worker'); var redis = require('./redis'); exports.redis = redis; exports.createQueue = function(name, opts){ if(!opts) opts = {}; if(typeof opts.redis == 'undefined'){ opts.redis = redis; } var q = new Queue(name, opts); return q; }; exports.Job = Job; exports.Worker = Worker;
Send redis library to queue via opts
Send redis library to queue via opts
JavaScript
mit
gosquared/convoy,intertwine/convoy
67ffd189c4717ff78dc04fdc7268d60e4840eebf
lib/linter.js
lib/linter.js
var JSLINT = require("../lib/nodelint"); function addDefaults(options) { 'use strict'; ['node', 'es5'].forEach(function (opt) { if (!options.hasOwnProperty(opt)) { options[opt] = true; } }); return options; } exports.lint = function (script, options) { 'use strict'; // remove shebang /*jslint regexp: true*/ script = script.replace(/^\#\!.*/, ""); options = options || {}; delete options.argv; options = addDefaults(options); var ok = JSLINT(script, options), result = { ok: true, errors: [] }; if (!ok) { result = JSLINT.data(); result.errors = (result.errors || []).filter(function (error) { return !(/\/\/.*bypass/).test(error.evidence); }); result.ok = !result.errors.length; } result.options = options; return result; };
var JSLINT = require("../lib/nodelint"); function addDefaults(options) { 'use strict'; ['node', 'es5'].forEach(function (opt) { if (!options.hasOwnProperty(opt)) { options[opt] = true; } }); return options; } exports.lint = function (script, options) { 'use strict'; // remove shebang /*jslint regexp: true*/ script = script.replace(/^\#\!.*/, ""); options = options || {}; delete options.argv; options = addDefaults(options); var ok = JSLINT(script, options), result = { ok: true, errors: [] }; if (!ok) { result = JSLINT.data(); result.errors = (result.errors || []).filter(function (error) { return !error.evidence || !(/\/\/.*bypass/).test(error.evidence); }); result.ok = !result.errors.length; } result.options = options; return result; };
Fix unexpected error when there is no context in an error
Fix unexpected error when there is no context in an error
JavaScript
bsd-3-clause
BenoitZugmeyer/node-jslint-extractor,BenoitZugmeyer/node-jslint-extractor
3650f297790e9c53fe609e72c65771b70e1af6ab
app/scripts/directives/radioQuestion.js
app/scripts/directives/radioQuestion.js
'use strict'; angular.module('confRegistrationWebApp') .directive('radioQuestion', function () { return { templateUrl: 'views/radioQuestion.html', restrict: 'E', controller: function ($scope) { $scope.answer = {}; } }; });
'use strict'; angular.module('confRegistrationWebApp') .directive('radioQuestion', function () { return { templateUrl: 'views/radioQuestion.html', restrict: 'E', controller: function ($scope) { $scope.updateAnswer = function (answer) { console.log('block ' + $scope.block.id + ' answer changed to ' + answer); }; $scope.answer = {}; } }; });
Add the previously removed updateAnswer function
Add the previously removed updateAnswer function
JavaScript
mit
CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web,CruGlobal/conf-registration-web
a1e8fb35145d772c9766b0e279b75969a2192491
src/index.js
src/index.js
export function search(select, queryString, callback) { select.find('input').simulate('change', { target: { value: queryString } }); setTimeout(() => { callback(); }, 0); } export function chooseOption(select, optionText) { const options = select.find('.Select-option span'); const matchingOptions = options.findWhere((option) => { return option.text() === optionText; }); matchingOptions.simulate('mouseDown'); } export function chooseOptionBySearching(select, queryString, optionText, callback) { search(select, queryString, () => { chooseOption(select, optionText); callback(); }); } export default { search, chooseOption, chooseOptionBySearching };
import Select from 'react-select'; function findSelect(wrapper) { const plainSelect = wrapper.find(Select); if (plainSelect.length > 0) { return plainSelect; } const asyncSelect = wrapper.find(Select.Async); if (asyncSelect.length > 0) { return asyncSelect; } throw "Couldn't find Select or Select.Async in wrapper"; } export function search(wrapper, queryString, callback) { findSelect(wrapper).find('.Select-input input').simulate('change', { target: { value: queryString } }); setTimeout(callback, 0); } export function chooseOption(wrapper, optionText) { const options = findSelect(wrapper).find('.Select-option'); const matchingOptions = options.findWhere((option) => { return option.text() === optionText; }); matchingOptions.simulate('mouseDown'); } export function chooseOptionBySearching(wrapper, queryString, optionText, callback) { search(wrapper, queryString, () => { chooseOption(wrapper, optionText); callback(); }); } export default { search, chooseOption, chooseOptionBySearching };
Make helpers a little more robust by searching specifically for Select or Select.Async components
Make helpers a little more robust by searching specifically for Select or Select.Async components
JavaScript
mit
patientslikeme/react-select-test-utils
903a944fd035f558f862dc7e8fa86d45625a6a9d
src/index.js
src/index.js
import {StreamTransformer} from './stream.transformer'; import {TracebackTransformer} from './traceback.transformer'; import {LaTeXTransformer} from './latex.transformer'; import {MarkdownTransformer} from 'transformime-commonmark'; import {PDFTransformer} from './pdf.transformer'; export default {StreamTransformer, TracebackTransformer, MarkdownTransformer};
import {StreamTransformer} from './stream.transformer'; import {TracebackTransformer} from './traceback.transformer'; import {LaTeXTransformer} from './latex.transformer'; import {MarkdownTransformer} from 'transformime-commonmark'; import {PDFTransformer} from './pdf.transformer'; export default { StreamTransformer, TracebackTransformer, MarkdownTransformer, LaTeXTransformer, PDFTransformer };
Include the PDF and LaTeX Transformers
Include the PDF and LaTeX Transformers
JavaScript
bsd-3-clause
rgbkrk/transformime-jupyter-transformers,jdfreder/transformime-jupyter-transformers,nteract/transformime-jupyter-transformers,nteract/transformime-jupyter-renderers
ec8a6e644a68f05da723bf5f463bda662ad0dde1
lib/router.js
lib/router.js
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return [Meteor.subscribe('posts'), Meteor.subscribe('notifications')]; } }); Router.route('/', { name: 'postsList'}); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Router.configure({ layoutTemplate: 'layout', loadingTemplate: 'loading', notFoundTemplate: 'notFound', waitOn: function() { return Meteor.subscribe('notifications'); } }); Router.route('/', { name: 'postsList'}); Router.route('/posts/:_id', { name: 'postPage', waitOn: function() { return Meteor.subscribe('comments', this.params._id); }, data: function() { return Posts.findOne(this.params._id); } }); Router.route('posts/:_id/edit', { name: 'postEdit', data: function() { return Posts.findOne(this.params._id); } }); Router.route('/submit', { name: 'postSubmit' }); Router.route('/:postsLimit?', { name: 'postsList', waitOn: function() { var limit = parseInt(this.params.postsLimit) || 5; return Meteor.subscribe('posts', { sort: { submitted: -1 }, limit: limit }); } }); var requireLogin = function() { if (!Meteor.user()) { if (Meteor.loggingIn()) { this.render(this.loadingTemplate); } else { this.render('accessDenied'); } } else { this.next(); } } Router.onBeforeAction('dataNotFound', { only: 'postPage' }); Router.onBeforeAction(requireLogin, { only: 'postSubmit' });
Add route to limit posts
Add route to limit posts
JavaScript
mit
Bennyz/microscope,Bennyz/microscope
c11be7a5d0e635699f079e4d4151a0ffaeec4603
src/candela/components/index.js
src/candela/components/index.js
import BarChart from './BarChart'; import BoxPlot from './BoxPlot'; import BulletChart from './BulletChart'; import GanttChart from './GanttChart'; import Geo from './Geo'; import Heatmap from './Heatmap'; import Histogram from './Histogram'; import LineChart from './LineChart'; import LineUp from './LineUp'; import ParallelCoordinates from './ParallelCoordinates'; import ScatterPlot from './ScatterPlot'; import ScatterPlotMatrix from './ScatterPlotMatrix'; import UpSet from './UpSet'; export default { BarChart, BoxPlot, BulletChart, GanttChart, Geo, Heatmap, Histogram, LineChart, LineUp, ParallelCoordinates, UpSet };
import BarChart from './BarChart'; import BoxPlot from './BoxPlot'; import BulletChart from './BulletChart'; import GanttChart from './GanttChart'; import Geo from './Geo'; import Heatmap from './Heatmap'; import Histogram from './Histogram'; import LineChart from './LineChart'; import LineUp from './LineUp'; import ParallelCoordinates from './ParallelCoordinates'; import ScatterPlot from './ScatterPlot'; import ScatterPlotMatrix from './ScatterPlotMatrix'; import UpSet from './UpSet'; export default { BarChart, BoxPlot, BulletChart, GanttChart, Geo, Heatmap, Histogram, LineChart, LineUp, ParallelCoordinates, ScatterPlot, ScatterPlotMatrix, UpSet };
Replace lost classes in components list
Replace lost classes in components list
JavaScript
apache-2.0
Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela,Kitware/candela
f9ea9934ee9cfc21d9b1642452977c4f30474491
src/client/app/trades/trades.js
src/client/app/trades/trades.js
"use strict"; (function () { angular .module("argo") .controller("Trades", Trades); Trades.$inject = ["toastService", "tradesService"]; function Trades(toastService, tradesService) { var vm = this; vm.getTrades = getTrades; vm.closeTrade = closeTrade; tradesService.getTrades().then(getTrades); function getTrades(trades) { vm.trades = trades; } function closeTrade(id) { tradesService.closeTrade(id).then(function (trade) { var message = "Closed " + trade.side + " " + trade.instrument + " #" + trade.id + " @" + trade.price + " P&L " + trade.profit; toastService.show(message); tradesService.getTrades().then(getTrades); }); } } }());
"use strict"; (function () { angular .module("argo") .controller("Trades", Trades); Trades.$inject = ["$mdDialog", "toastService", "tradesService"]; function Trades($mdDialog, toastService, tradesService) { var vm = this; vm.getTrades = getTrades; vm.closeTrade = closeTrade; tradesService.getTrades().then(getTrades); function getTrades(trades) { vm.trades = trades; } function closeTrade(event, id) { var confirm = $mdDialog.confirm() .content("Are you sure to close the trade?") .ariaLabel("Trade closing confirmation") .ok("Ok") .cancel("Cancel") .targetEvent(event); $mdDialog.show(confirm).then(function () { tradesService.closeTrade(id).then(function (trade) { var message = "Closed " + trade.side + " " + trade.instrument + " #" + trade.id + " @" + trade.price + " P&L " + trade.profit; toastService.show(message); tradesService.getTrades().then(getTrades); }); }); } } }());
Add confirmation dialog to close trade.
Add confirmation dialog to close trade.
JavaScript
mit
albertosantini/argo,albertosantini/argo
637339c263e278e99b4bec3eb1b48d3c721ab57b
src/index.js
src/index.js
var Transmitter = function (config) { var router = require('./router.js'); router(config); var io = require('socket.io')(router.server); // Socket.io connection handling io.on('connection', function(socket){ console.log('PULSAR: client connected'); socket.on('disconnect', function() { console.log('PULSAR: client disconnected'); }); }); var Processor = require('@dermah/pulsar-input-keyboard'); var processor = new Processor(io, config); } module.exports = Transmitter;
var Transmitter = function (config) { var router = require('./router.js'); router(config); var io = require('socket.io')(router.server); // Socket.io connection handling io.on('connection', function(socket){ console.log('PULSAR: client connected'); socket.on('disconnect', function() { console.log('PULSAR: client disconnected'); }); }); var Processor = require('@dermah/pulsar-input-keyboard'); var processor = new Processor(config); processor.on('pulse', pulse => { io.emit('pulse', pulse) }); processor.on('pulsar control', pulse => { io.emit('pulsar control', pulse) }); processor.on('pulse update', pulse => { io.emit('pulse update', pulse); }); } module.exports = Transmitter;
Use the new EventEmitter input by passing its events to socket.io
Use the new EventEmitter input by passing its events to socket.io
JavaScript
mit
Dermah/pulsar-transmitter
0ee8baa8d70d20502f8c3134f6feea475646fbca
src/index.js
src/index.js
"use strict"; const http = require('http'); const mongoose = require('mongoose'); const requireAll = require('require-all'); const TelegramBot = require('node-telegram-bot-api'); const GitHubNotifications = require('./common/GitHubNotifications'); const User = require('./models/User'); const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`}); const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN']; if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token'); const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, {polling: true}); Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot)); mongoose.connect(process.env['MONGODB_URI']); User.find({}, (error, users) => { if (error) throw new Error(error); users.forEach(user => { new GitHubNotifications(user.username, user.token).on('notification', data => { bot.sendMessage(user.telegramId, `You have unread notification - ${data}`); }); }); }); http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Bot is working\n'); }).listen(process.env['PORT']);
"use strict"; const http = require('http'); const mongoose = require('mongoose'); const requireAll = require('require-all'); const TelegramBot = require('node-telegram-bot-api'); const GitHubNotifications = require('./services/GitHubNotifications'); const User = require('./models/User'); const BOT_COMMANDS = requireAll({dirname: `${__dirname}/commands`}); const TELEGRAM_BOT_TOKEN = process.env['TELEGRAM_BOT_TOKEN']; if (!TELEGRAM_BOT_TOKEN) throw new Error('You must provide telegram bot token'); const telegramBotConfig = process.env.NODE_ENV === 'production' ? {webHook: true} : {polling: true}; const bot = new TelegramBot(TELEGRAM_BOT_TOKEN, telegramBotConfig); Object.keys(BOT_COMMANDS).forEach(command => BOT_COMMANDS[command](bot)); mongoose.connect(process.env['MONGODB_URI']); User.find({}, (error, users) => { if (error) throw new Error(error); users.forEach(user => { new GitHubNotifications(user.username, user.token).on('notification', data => { bot.sendMessage(user.telegramId, `You have unread notification - ${data}`); }); }); }); http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Bot is working\n'); }).listen(process.env['PORT']);
Implement switching to webhooks in production
feat(bot): Implement switching to webhooks in production
JavaScript
mit
ghaiklor/telegram-bot-github
d8e2ceeb05de3c2fda22ef00486d50ef7fe9379c
src/index.js
src/index.js
'use strict'; require('foundation-sites/scss/foundation.scss') require('./styles.scss'); require('font-awesome/css/font-awesome.css'); // Require index.html so it gets copied to dist require('./index.html'); var Elm = require('./Main.elm'); var mountNode = document.getElementById('main'); // The third value on embed are the initial values for incomming ports into Elm var app = Elm.Main.embed(mountNode);
'use strict'; require('./styles.scss'); require('font-awesome/css/font-awesome.css'); // Require index.html so it gets copied to dist require('./index.html'); var Elm = require('./Main.elm'); var mountNode = document.getElementById('main'); // The third value on embed are the initial values for incomming ports into Elm var app = Elm.Main.embed(mountNode);
Remove foundation-sites require as foundation is not used anymore.
Remove foundation-sites require as foundation is not used anymore. Signed-off-by: Snorre Magnus Davøen <b6ec5a60a98746258b9d59fdb44419d796d6053e@gmail.com>
JavaScript
mit
Snorremd/builds-dashboard-gitlab,Snorremd/builds-dashboard-gitlab
bb40f82aaa28cfef7b362f97bbc0ef332b925fe0
sandbox-react-redux/src/enhancer.js
sandbox-react-redux/src/enhancer.js
export default function enhancer() { return (next) => (reducer, preloadedState) => { const initialState = Object.assign({}, preloadedState, loadState(restoreState)); const store = next(reducer, initialState); store.subscribe(() => saveState(store.getState())); return store; } } const restoreState = (state) => { return { misc: state }; } const loadState = (transform) => { const state = { locked: true }; return transform(state); } const saveState = (state) => { if (state.misc) { console.log(state.misc); } }
export default function enhancer() { return (next) => (reducer, preloadedState) => { const initialState = Object.assign({}, preloadedState, loadState(restoreState)); const store = next(reducer, initialState); store.subscribe(() => saveState(store.getState(), filterState)); return store; } } const restoreState = (state) => { return { misc: state }; } const filterState = (state) => { return state.misc; } const storageKey = 'sample'; const loadState = (transform) => { const saved = window.localStorage.getItem(storageKey); if (saved) { return transform(JSON.parse(saved)); } } const saveState = (state, transform) => { const saving = transform(state); if (saving) { window.localStorage.setItem(storageKey, JSON.stringify(saving)); } }
Tweak sample for react-redux in order to use local storage
Tweak sample for react-redux in order to use local storage
JavaScript
mit
ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox,ohtomi/sandbox
8b9af7220cc36962794a953525505bb57d8f426e
public/assets/wee/build/tasks/legacy-convert.js
public/assets/wee/build/tasks/legacy-convert.js
/* global legacyConvert, module, project */ module.exports = function(grunt) { grunt.registerTask('convertLegacy', function(task) { var dest = legacyConvert[task], content = grunt.file.read(dest), rootSize = project.style.legacy.rootSize, rootValue = 10; // Determine root value for unit conversion if (rootSize.indexOf('%') !== -1) { rootValue = (rootSize.replace('%', '') / 100) * 16; } else if (rootSize.indexOf('px') !== -1) { rootValue = rootSize.replace('px', ''); } else if (rootSize.indexOf('em') !== -1) { rootValue = rootSize.replace('em', ''); } else if (rootSize.indexOf('pt') !== -1) { rootValue = rootSize.replace('pt', ''); } content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) { return (match * rootValue) + 'px'; }).replace(/opacity:([.\d]+)/gi, function(str, match) { return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');'; }); grunt.file.write(dest, content); }); };
/* global legacyConvert, module, project */ module.exports = function(grunt) { grunt.registerTask('convertLegacy', function(task) { var dest = legacyConvert[task], content = grunt.file.read(dest), rootSize = project.style.legacy.rootSize, rootValue = 10; // Determine root value for unit conversion if (rootSize.indexOf('%') !== -1) { rootValue = (rootSize.replace('%', '') / 100) * 16; } else if (rootSize.indexOf('px') !== -1) { rootValue = rootSize.replace('px', ''); } else if (rootSize.indexOf('em') !== -1) { rootValue = rootSize.replace('em', ''); } else if (rootSize.indexOf('pt') !== -1) { rootValue = rootSize.replace('pt', ''); } content = content.replace(/(-?[.\d]+)rem/gi, function(str, match) { return (match * rootValue) + 'px'; }).replace(/opacity:([.\d]+)/gi, function(str, match) { return 'filter:alpha(opacity=' + Math.round((match * 100) * 100 / 100) + ');'; }).replace(/::/g, ':'); grunt.file.write(dest, content); }); };
Replace :: with : in IE8 for backward compatibility with element pseudo selectors
Replace :: with : in IE8 for backward compatibility with element pseudo selectors
JavaScript
apache-2.0
weepower/wee,janusnic/wee,weepower/wee,janusnic/wee
729fb1c904ca57b39110894b85e8439a11cab554
src/widgets/Wizard.js
src/widgets/Wizard.js
/* eslint-disable import/no-named-as-default */ /* eslint-disable react/forbid-prop-types */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Stepper } from './Stepper'; import { TabNavigator } from './TabNavigator'; import DataTablePageView from './DataTablePageView'; import { WizardActions } from '../actions/WizardActions'; import { selectCurrentTab } from '../selectors/wizard'; /** * Layout component for a Tracker and TabNavigator, displaying steps * to completion for completion. See TabNavigator and StepsTracker * for individual component implementation. */ const WizardComponent = ({ tabs, titles, currentTab, nextTab }) => ( <DataTablePageView> <Stepper numberOfSteps={tabs.length} currentStep={currentTab} onPress={nextTab} titles={titles} /> <TabNavigator tabs={tabs} currentTabIndex={currentTab} /> </DataTablePageView> ); WizardComponent.propTypes = { tabs: PropTypes.array.isRequired, titles: PropTypes.array.isRequired, nextTab: PropTypes.func.isRequired, currentTab: PropTypes.number.isRequired, }; const mapStateToProps = state => { const currentTab = selectCurrentTab(state); return { currentTab }; }; const mapDispatchToProps = dispatch => ({ nextTab: tab => dispatch(WizardActions.switchTab(tab)), }); export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
/* eslint-disable import/no-named-as-default */ /* eslint-disable react/forbid-prop-types */ import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Stepper } from './Stepper'; import { TabNavigator } from './TabNavigator'; import DataTablePageView from './DataTablePageView'; import { WizardActions } from '../actions/WizardActions'; import { selectCurrentTab } from '../selectors/wizard'; /** * Layout component for a Tracker and TabNavigator, displaying steps * to completion for completion. See TabNavigator and StepsTracker * for individual component implementation. */ const WizardComponent = ({ tabs, titles, currentTab, switchTab }) => ( <DataTablePageView> <Stepper numberOfSteps={tabs.length} currentStep={currentTab} onPress={switchTab} titles={titles} /> <TabNavigator tabs={tabs} currentTabIndex={currentTab} /> </DataTablePageView> ); WizardComponent.propTypes = { tabs: PropTypes.array.isRequired, titles: PropTypes.array.isRequired, switchTab: PropTypes.func.isRequired, currentTab: PropTypes.number.isRequired, }; const mapStateToProps = state => { const currentTab = selectCurrentTab(state); return { currentTab }; }; const mapDispatchToProps = dispatch => ({ switchTab: tab => dispatch(WizardActions.switchTab(tab)), }); export const Wizard = connect(mapStateToProps, mapDispatchToProps)(WizardComponent);
Add renaming of nextTab -> switchTab
Add renaming of nextTab -> switchTab
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
04b32b2c6f6bc92f9fbe6cc994c137968f4b522c
lib/i18n/dicts.js
lib/i18n/dicts.js
module.exports = { 'ar': require('../../i18n/ar.json'), 'da': require('../../i18n/da.json'), 'de': require('../../i18n/de.json'), 'en': require('../../i18n/en.json'), 'es': require('../../i18n/es.json'), 'fr': require('../../i18n/fr-FR.json'), 'fr-FR': require('../../i18n/fr-FR.json'), 'he': require('../../i18n/he.json'), 'it': require('../../i18n/it.json'), 'ja': require('../../i18n/ja.json'), 'ko': require('../../i18n/ko.json'), 'nb-NO': require('../../i18n/nb-NO.json'), 'nl': require('../../i18n/nl-NL.json'), 'nl-NL': require('../../i18n/nl-NL.json'), 'pt': require('../../i18n/pt.json'), 'pt-BR': require('../../i18n/pt-BR.json'), 'ru': require('../../i18n/ru.json'), 'sv': require('../../i18n/sv.json'), 'tlh': require('../../i18n/tlh.json'), 'tr': require('../../i18n/tr.json'), 'zh': require('../../i18n/zh.json'), 'zh-TW': require('../../i18n/zh-TW.json') }
module.exports = { 'ar': require('../../i18n/ar.json'), 'da': require('../../i18n/da.json'), 'de': require('../../i18n/de.json'), 'en': require('../../i18n/en.json'), 'es': require('../../i18n/es.json'), 'fr': require('../../i18n/fr-FR.json'), 'fr-FR': require('../../i18n/fr-FR.json'), 'he': require('../../i18n/he.json'), 'it': require('../../i18n/it.json'), 'ja': require('../../i18n/ja.json'), 'ko': require('../../i18n/ko.json'), 'nb-NO': require('../../i18n/nb-NO.json'), 'nl': require('../../i18n/nl-NL.json'), 'nl-NL': require('../../i18n/nl-NL.json'), 'pl': require('../../i18n/pl.json'), 'pt': require('../../i18n/pt.json'), 'pt-BR': require('../../i18n/pt-BR.json'), 'ru': require('../../i18n/ru.json'), 'sv': require('../../i18n/sv.json'), 'tlh': require('../../i18n/tlh.json'), 'tr': require('../../i18n/tr.json'), 'zh': require('../../i18n/zh.json'), 'zh-TW': require('../../i18n/zh-TW.json') }
Add polish dict to base code
Add polish dict to base code
JavaScript
mit
cwilgenhoff/lock,cwilgenhoff/lock,adam2314/lock,cwilgenhoff/lock,adam2314/lock,adam2314/lock
28b05e832339fafe433e5970b00466f5a915b895
website/app/application/core/projects/project/processes/process-list-controller.js
website/app/application/core/projects/project/processes/process-list-controller.js
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { console.log('projectListProcess'); var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { console.log(' ctrl.processes.length !== 0'); ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; //$state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
(function (module) { module.controller('projectListProcess', projectListProcess); projectListProcess.$inject = ["processes", "project", "$state", "mcmodal", "$filter"]; function projectListProcess(processes, project, $state, mcmodal, $filter) { var ctrl = this; ctrl.viewProcess = viewProcess; ctrl.chooseTemplate = chooseTemplate; ctrl.processes = processes; ctrl.project = project; if (ctrl.processes.length !== 0) { ctrl.processes = $filter('orderBy')(ctrl.processes, 'name'); ctrl.current = ctrl.processes[0]; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } /////////////////////////////////// function viewProcess(process) { ctrl.current = process; $state.go('projects.project.processes.list.view', {process_id: ctrl.current.id}); } function chooseTemplate() { mcmodal.chooseTemplate(ctrl.project); } } }(angular.module('materialscommons')));
Remove debug of ui router state changes.
Remove debug of ui router state changes.
JavaScript
mit
materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org,materials-commons/materialscommons.org
e022dd7bd62f4f088a9d943adfc5258fbfc91006
app/components/Pit/index.js
app/components/Pit/index.js
import React, { PropTypes } from 'react'; import './index.css'; const Pit = React.createClass({ propTypes: { pit: PropTypes.object.isRequired, }, render() { const { pit } = this.props; return ( <div className="Pit"> <div className="Pit-name">{pit.name}</div> <div className="Pit-type">{pit.type}</div> <div className="Pit-dataset">{pit.dataset}</div> <div className="Pit-id">{pit.id}</div> <table> {Object.keys(pit.data).map((key) => <tr> <td>{key}</td> <td>{pit.data[key]}</td> </tr> )} </table> </div> ); }, }); export default Pit;
import React, { PropTypes } from 'react'; import './index.css'; const Pit = React.createClass({ propTypes: { pit: PropTypes.object.isRequired, }, render() { const { pit } = this.props; return ( <div className="Pit"> <div className="Pit-name">{pit.name}</div> <div className="Pit-type">{pit.type}</div> <div className="Pit-dataset">{pit.dataset}</div> <div className="Pit-id">{pit.id}</div> <table> <tbody> {Object.keys(pit.data).map((key) => <tr key={key}> <td>{key}</td> <td>{pit.data[key]}</td> </tr> )} </tbody> </table> </div> ); }, }); export default Pit;
Add keys to table loop
Add keys to table loop
JavaScript
mit
transparantnederland/browser,waagsociety/tnl-relationizer,transparantnederland/browser,transparantnederland/relationizer,waagsociety/tnl-relationizer,transparantnederland/relationizer
885f50a52c41cbc50f8de0d46ef57fc62fce1c17
src/actions/socketActionsFactory.js
src/actions/socketActionsFactory.js
import { SOCKET_SET_OPENING, SOCKET_SET_CLOSING, SOCKET_SEND_MESSAGE } from "../constants/ActionTypes"; export default (socketClient) => ({ open: url => { const action = { type: SOCKET_SET_OPENING }; try { socketClient.open(url); action.payload = url; } catch (err) { action.error = true; action.payload = err; } return action; }, close: () => { const action = { type: SOCKET_SET_CLOSING }; try { socketClient.close(); } catch (err) { action.error = true; action.payload = err; } return action; }, send: message => { const action = { type: SOCKET_SEND_MESSAGE }; try { socketClient.send(JSON.stringify(message)); } catch (err) { action.error = true; action.payload = err; } return action; } });
import { SOCKET_SET_OPENING, SOCKET_SET_CLOSING, SOCKET_SEND_MESSAGE } from "../constants/ActionTypes"; export default (socketClient) => ({ open: url => { const action = { type: SOCKET_SET_OPENING }; try { socketClient.open(url); action.payload = url; } catch (err) { action.error = true; action.payload = err; } return action; }, close: () => { const action = { type: SOCKET_SET_CLOSING }; try { socketClient.close(); } catch (err) { action.error = true; action.payload = err; } return action; }, send: message => { const action = { type: SOCKET_SEND_MESSAGE }; try { socketClient.send(JSON.stringify(message)); action.payload = message; } catch (err) { action.error = true; action.payload = err; } return action; } });
Add message to SEND_MESSAGE action for debugging.
Add message to SEND_MESSAGE action for debugging.
JavaScript
mit
letitz/solstice-web,letitz/solstice-web
f9efd3ba4b435a46a47aec284a30abe83efb9e6a
src/reducers/FridgeReducer.js
src/reducers/FridgeReducer.js
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import moment from 'moment'; import { UIDatabase } from '../database'; import { FRIDGE_ACTIONS } from '../actions/FridgeActions'; const initialState = () => { const fridges = UIDatabase.objects('Location'); return { fridges, selectedFridge: fridges[0], fromDate: moment(new Date()) .subtract(30, 'd') .toDate(), toDate: new Date(), }; }; export const FridgeReducer = (state = initialState(), action) => { const { type } = action; switch (type) { case FRIDGE_ACTIONS.SELECT: { const { payload } = action; const { fridge } = payload; return { ...state, selectedFridge: fridge }; } case FRIDGE_ACTIONS.CHANGE_FROM_DATE: { const { payload } = action; const { date } = payload; return { ...state, fromDate: date }; } case FRIDGE_ACTIONS.CHANGE_TO_DATE: { const { payload } = action; const { date } = payload; return { ...state, toDate: date }; } default: return state; } };
/** * mSupply Mobile * Sustainable Solutions (NZ) Ltd. 2020 */ import moment from 'moment'; import { UIDatabase } from '../database'; import { FRIDGE_ACTIONS } from '../actions/FridgeActions'; const initialState = () => { const fridges = UIDatabase.objects('Location'); return { fridges, selectedFridge: fridges[0], fromDate: moment(new Date()) .subtract(30, 'd') .toDate(), toDate: new Date(), }; }; export const FridgeReducer = (state = initialState(), action) => { const { type } = action; switch (type) { case FRIDGE_ACTIONS.SELECT: { const { payload } = action; const { fridge } = payload; return { ...state, selectedFridge: fridge }; } case FRIDGE_ACTIONS.CHANGE_FROM_DATE: { const { payload } = action; const { date } = payload; const fromDate = new Date(date); fromDate.setUTCHours(0, 0, 0, 0); return { ...state, fromDate }; } case FRIDGE_ACTIONS.CHANGE_TO_DATE: { const { payload } = action; const { date } = payload; const toDate = new Date(date); toDate.setUTCHours(23, 59, 59, 999); return { ...state, toDate }; } default: return state; } };
Add UTC manipulation of dates for to and froms
Add UTC manipulation of dates for to and froms
JavaScript
mit
sussol/mobile,sussol/mobile,sussol/mobile,sussol/mobile
d3c58065a12e493e0a30bcdb9d19dcfebebff83e
src/misterT/skills/warnAboutMissingTimesheet.js
src/misterT/skills/warnAboutMissingTimesheet.js
'use strict'; const moment = require('moment') const _ = require('lodash') const lastBusinessDay = require('../../businessDays').last module.exports = ({ getChatUsers, getWorkEntries }) => { return async function warnAboutMissingTimesheet () { const day = lastBusinessDay(moment()).format('YYYY-MM-DD'); const users = await getChatUsers() const workEntries = users.map(slackId => { return (async function () { const workEntries = await getWorkEntries(slackId, day, day) const hours = _.reduce(workEntries, function (sum, entry) { return sum + entry[ 'hours' ] }, 0); if (hours < 8) { return { text: `Ieri ha segnato solo ${hours} ore\n, non è che ti sei dimenticato di qualcosa?`, channel: slackId } } }()) }) return _.filter(await Promise.all(workEntries)) } }
'use strict'; const moment = require('moment') const _ = require('lodash') const lastBusinessDay = require('../../businessDays').last module.exports = ({ getChatUsers, getWorkEntries }) => { return async function warnAboutMissingTimesheet () { const day = lastBusinessDay(moment()).format('YYYY-MM-DD'); const users = await getChatUsers() const workEntries = users.map(slackId => { return (async function () { const workEntries = await getWorkEntries(slackId, day, day) const hours = _.reduce(workEntries, function (sum, entry) { return sum + entry[ 'hours' ] }, 0); if (hours < 8) { return { text: `Ieri ha segnato solo ${hours} ore, non è che ti sei dimenticato di qualcosa?\n Puoi <https://report.ideato.it/|aggiornare il timesheet>`, channel: slackId } } }()) }) return _.filter(await Promise.all(workEntries)) } }
Add link to report from hell
Add link to report from hell
JavaScript
mit
ideatosrl/mister-t
fe0a75812fd1e26ad45cf2457230641ed12af605
static/js/base.js
static/js/base.js
'use strict'; if (!waitlist) { var waitlist = {}; } waitlist.base = (function(){ function getMetaData (name) { return $('meta[name="'+name+'"]').attr('content'); } function displayMessage(message, type, html=false) { var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="text-xs-center"></p> </div>`)); var textContainer = $('.text-xs-center', alertHTML); if (html === true) { textContainer.html(message); } else { textContainer.text(message); } var alertArea = $('#alert-area-base'); alertArea.append(alertHTML); } return { getMetaData: getMetaData, displayMessage: displayMessage }; })();
'use strict'; if (!waitlist) { var waitlist = {}; } waitlist.base = (function(){ function getMetaData (name) { return $('meta[name="'+name+'"]').attr('content'); } function displayMessage(message, type, html=false, id=false) { var alertHTML = $($.parseHTML(`<div class="alert alert-dismissible alert-${type}" role="alert"> <button type="button" class="close" data-dismiss="alert" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> <p class="text-xs-center"></p> </div>`)); var textContainer = $('.text-xs-center', alertHTML); if (id !== false) { alertHTML.attr("id", id); } if (html === true) { textContainer.html(message); } else { textContainer.text(message); } var alertArea = $('#alert-area-base'); alertArea.append(alertHTML); } return { getMetaData: getMetaData, displayMessage: displayMessage }; })();
Update alert to allow for setting an id.
Update alert to allow for setting an id.
JavaScript
mit
SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist,SpeedProg/eve-inc-waitlist
d34f4ef6b96090913839b158423d912bd18a585f
release.js
release.js
var shell = require('shelljs'); if (exec('git status --porcelain').output != '') { console.error('Git working directory not clean.'); process.exit(2); } var versionIncrement = process.argv[process.argv.length -1]; if (versionIncrement != 'major' && versionIncrement != 'minor' && versionIncrement != 'patch') { console.error('Usage: node release.js major|minor|patch'); process.exit(1); } exec('npm version ' + versionIncrement); exec('npm test'); exec('git push'); exec('git push --tags'); exec('npm publish'); function exec(cmd) { var ret = shell.exec(cmd, { silent : true }); if (ret.code != 0) { console.error(ret.output); process.exit(1); } return ret; }
var shell = require('shelljs'); if (exec('git status --porcelain').stdout != '') { console.error('Git working directory not clean.'); process.exit(2); } var versionIncrement = process.argv[process.argv.length -1]; if (versionIncrement != 'major' && versionIncrement != 'minor' && versionIncrement != 'patch') { console.error('Usage: node release.js major|minor|patch'); process.exit(1); } exec('npm version ' + versionIncrement); exec('npm test'); exec('git push'); exec('git push --tags'); exec('npm publish'); function exec(cmd) { var ret = shell.exec(cmd, { silent : true }); if (ret.code != 0) { console.error(ret.output); process.exit(1); } return ret; }
Fix checking of exec output
Fix checking of exec output
JavaScript
isc
saintedlama/git-visit
d4673dcb8a1b07edec917c390311b20b22fd91c7
app/javascript/app/components/scroll-to-highlight-index/scroll-to-highlight-index.js
app/javascript/app/components/scroll-to-highlight-index/scroll-to-highlight-index.js
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { scrollIt } from 'utils/scroll'; class ScrollToHighlightIndex extends PureComponent { // eslint-disable-line react/prefer-stateless-function componentDidMount() { setTimeout(this.handleScroll, 150); } componentWillReceiveProps(nextProps) { if (nextProps.content.html !== this.props.content.html) { setTimeout(this.handleScroll, 150); } } handleScroll = () => { const { idx, targetElementsSelector } = this.props; const e = idx ? document.querySelectorAll(targetElementsSelector)[idx] : document.querySelectorAll(targetElementsSelector)[0]; if (e) { scrollIt(document.querySelector(targetElementsSelector), 300, 'smooth'); } }; render() { return null; } } ScrollToHighlightIndex.propTypes = { idx: PropTypes.string, targetElementsSelector: PropTypes.string, content: PropTypes.object }; export default ScrollToHighlightIndex;
import { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { scrollIt } from 'utils/scroll'; class ScrollToHighlightIndex extends PureComponent { // eslint-disable-line react/prefer-stateless-function componentDidMount() { setTimeout(this.handleScroll, 150); } componentWillReceiveProps(nextProps) { if (nextProps.content.html !== this.props.content.html) { setTimeout(this.handleScroll, 150); } } handleScroll = () => { const { idx, targetElementsSelector } = this.props; const target = idx ? document.querySelectorAll(targetElementsSelector)[idx] : document.querySelectorAll(targetElementsSelector)[0]; if (target) { scrollIt(target, 300, 'smooth'); } }; render() { return null; } } ScrollToHighlightIndex.propTypes = { idx: PropTypes.string, targetElementsSelector: PropTypes.string, content: PropTypes.object }; export default ScrollToHighlightIndex;
Use index to scroll to desired target
Use index to scroll to desired target
JavaScript
mit
Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch,Vizzuality/climate-watch
98cb394af2d4244c85ddaf2e5ef02fa4e1c9c2c1
templates/localise.js
templates/localise.js
function localizeHtmlPage() { //Localize by replacing __MSG_***__ meta tags var objects = document.querySelectorAll('.message'); for (var j = 0; j < objects.length; j++) { var obj = objects[j]; var valStrH = obj.innerHTML.toString(); var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function (match, v1) { return v1 ? browser.i18n.getMessage(v1) : ""; }); if (valNewH != valStrH) { obj.innerHTML = valNewH; } } } localizeHtmlPage();
function localizeHtmlPage() { //Localize by replacing __MSG_***__ meta tags var objects = document.querySelectorAll('.message'); for (var j = 0; j < objects.length; j++) { var obj = objects[j]; var valStrH = obj.innerHTML.toString(); var valNewH = valStrH.replace(/__MSG_(\w+)__/g, function (match, v1) { return v1 ? browser.i18n.getMessage(v1) : ""; }); if (valNewH != valStrH) { obj.textContent = valNewH; } } } localizeHtmlPage();
Change to using textContent instead of innerHTML
Change to using textContent instead of innerHTML
JavaScript
mit
codefisher/mozbutton_sdk,codefisher/mozbutton_sdk
1a43f902beb82336e9f66dc75b1768721dc419c0
frontend/app/components/modal-dialog.js
frontend/app/components/modal-dialog.js
import Ember from "ember"; export default Ember.Component.extend({ didInsertElement: function() { // show the dialog this.$('.modal').modal('show'); // send the according action after it has been hidden again var _this = this; this.$('.modal').one('hidden.bs.modal', function() { Ember.run(function() { // send the according action after it has been hidden _this.sendAction("dismiss"); }); }); }, showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'), actions: { accept: function() { this.sendAction("accept"); }, doNotAccept: function() { this.sendAction("doNotAccept"); }, cancel: function() { this.sendAction("cancel"); } } });
import Ember from "ember"; export default Ember.Component.extend({ didInsertElement: function() { // show the dialog this.$('.modal').modal('show'); // send the according action after it has been hidden again var _this = this; this.$('.modal').one('hidden.bs.modal', function() { Ember.run(function() { // send the according action after it has been hidden _this.sendAction("dismiss"); }); }); }, willDestroyElement: function() { this.$('.modal').modal('hide'); }, showDoNotAccept: Ember.computed.notEmpty('doNotAcceptText'), actions: { accept: function() { this.sendAction("accept"); }, doNotAccept: function() { this.sendAction("doNotAccept"); }, cancel: function() { this.sendAction("cancel"); } } });
Hide dialog when leaving route
Hide dialog when leaving route
JavaScript
apache-2.0
uboot/stromx-web,uboot/stromx-web,uboot/stromx-web
e3389659239731bb5bb367061cc0dd113998097f
src/containers/NewsFeedContainer.js
src/containers/NewsFeedContainer.js
/* NewsFeedContainer.js * Container for our NewsFeed as a view * Dependencies: ActionTypes * Modules: NewsActions, and NewsFeed * Author: Tiffany Tse * Created: July 29, 2017 */ //import dependencie import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; //import modules import { loadNews } from '../actions/NewsActions.js'; import NewsFeed from '../component/NewsFeed.js'; import { reshapeNewsData } from '../util/DataTransformations.js'; import { allNewsSelector } from '../selectors/NewsSelectors.js'; //create state for mapStateToProps which exposes state tree's news property as a prop //to NewsFeed called news const mapStateToProps = state ({ news: reshapeNewsData(state.news); }); //create the dispatcher for actions as a prop const mapDispatchToProps = dispatch => ( bindActionCreators({ loadNews}, dispatch) ); //export mapStateToProps and mapDispatchToProps as props to to newsFeed export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
/* NewsFeedContainer.js * Container for our NewsFeed as a view * Dependencies: ActionTypes * Modules: NewsActions, and NewsFeed * Author: Tiffany Tse * Created: July 29, 2017 */ //import dependencie import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; //import modules import { loadNews } from '../actions/NewsActions.js'; import NewsFeed from '../component/NewsFeed.js'; import { reshapeNewsData } from '../util/DataTransformations.js'; import { allNewsSelector } from '../selectors/NewsSelectors.js'; //create state for mapStateToProps which exposes state tree's news property as a prop //to NewsFeed called news const mapStateToProps = state ({ news: allNewsSelector(state); }); //create the dispatcher for actions as a prop const mapDispatchToProps = dispatch => ( bindActionCreators({ loadNews}, dispatch) ); //export mapStateToProps and mapDispatchToProps as props to to newsFeed export default connect(mapStateToProps, mapDispatchToProps)(NewsFeed);
Update reshapeNewsData to use allNewsSelector and pass state to it
Update reshapeNewsData to use allNewsSelector and pass state to it
JavaScript
mit
titse/NYTimes-Clone,titse/NYTimes-Clone,titse/NYTimes-Clone
68f46c73a0de920803aebb9db5b78a28e458ea9e
lib/api/reddit.js
lib/api/reddit.js
/*jshint node:true */ "use strict"; var request = require('request'); var reddit = { top: function (subreddit, callback) { var url = "http://www.reddit.com/r/" + subreddit + "/top.json"; var currentTime = (new Date()).getTime(); request .get({url: url + "?bust=" + currentTime, json: true}, function (error, response, body) { if (!error && response.statusCode == 200) { body.url = url; body.timestamp = currentTime; if (callback) { callback(body); } } }); } }; module.exports = reddit;
/*jshint node:true */ "use strict"; var request = require('request'); var reddit = { top: function (subreddit, callback) { var url = "http://www.reddit.com/r/" + subreddit + "/top.json"; var currentTime = new Date(); request .get({url: url + "?bust=" + currentTime, json: true}, function (error, response, body) { if (!error && response.statusCode == 200) { body.url = url; body.date = { "timestamp": currentTime.getTime(), "year": currentTime.getUTCFullYear(), "month": currentTime.getUTCMonth() + 1, // Date.getUTCMonth is 0 indexed... wtf? "day": currentTime.getUTCDate(), "hour": currentTime.getUTCHours(), "minute": currentTime.getUTCMinutes() }; if (callback) { callback(body); } } }); } }; module.exports = reddit;
Expand timestamp json for db indicies
Expand timestamp json for db indicies
JavaScript
mit
netherwarhead/netherwarhead,netherwarhead/baconytics2,netherwarhead/netherwarhead,netherwarhead/baconytics2,netherwarhead/baconytics2,netherwarhead/netherwarhead
701feebf107a55a5720aca2ee52d40d421647cbc
js/app/app.js
js/app/app.js
App = Ember.Application.create(); // Add routes here App.Router.map(function() { // Atoms (Components) this.resource('atoms', function() { // Sub-routes here this.route('hs-button'); }); // Molecules (Modules) this.resource('molecules', function() { // Sub-routes here }); // Organisms (Layouts) this.resource('organisms', function() { // Sub-routes here }); // Templates this.resource('templates', function() { // Sub-routes here }); }); // Use this mixin for high-level atomic routes App.AtomicRouteMixin = Ember.Mixin.create({ renderTemplate: function() { this.render('atomic'); } }); // Modify high-level routes to use the same template App.AtomsRoute = Ember.Route.extend(App.AtomicRouteMixin); App.MoleculesRoute = Ember.Route.extend(App.AtomicRouteMixin); App.OrganismsRoute = Ember.Route.extend(App.AtomicRouteMixin); App.TemplatesRoute = Ember.Route.extend(App.AtomicRouteMixin);
Ember.Route.reopen({ beforeModel: function(transition) { if (transition) { transition.then(function() { Ember.run.scheduleOnce('afterRender', this, function() { $(document).foundation(); }); }); } } }); App = Ember.Application.create(); // Add routes here App.Router.map(function() { // Atoms (Components) this.resource('atoms', function() { // Sub-routes here this.route('hs-button'); }); // Molecules (Modules) this.resource('molecules', function() { // Sub-routes here }); // Organisms (Layouts) this.resource('organisms', function() { // Sub-routes here }); // Templates this.resource('templates', function() { // Sub-routes here }); }); // Use this mixin for high-level atomic routes App.AtomicRouteMixin = Ember.Mixin.create({ renderTemplate: function() { this.render('atomic'); } }); // Modify high-level routes to use the same template App.AtomsRoute = Ember.Route.extend(App.AtomicRouteMixin); App.MoleculesRoute = Ember.Route.extend(App.AtomicRouteMixin); App.OrganismsRoute = Ember.Route.extend(App.AtomicRouteMixin); App.TemplatesRoute = Ember.Route.extend(App.AtomicRouteMixin);
Initialize Foundation after every route transition
Initialize Foundation after every route transition
JavaScript
mit
jneurock/pattern-lib
f7108b212c596ba5c3f2bbf0184d186714130e93
app/assets/javascripts/ng-app/services/control-panel-service.js
app/assets/javascripts/ng-app/services/control-panel-service.js
angular.module('myApp') .factory('ctrlPanelService', ['$rootScope', 'userService', 'locationService','transactionService', function($rootScope, $userService, locationService, transactionService) { var settings = { users: null, userId: null }; settings.updateUsers = function(users) { settings.users = users; $rootScope.$broadcast('updateUsers'); } settings.setUserId = function(userId) { settings.userId = userId; $rootScope.$broadcast('updateUserId'); } // define generic submit event for other controllers to use settings.submit = function() { $rootScope.$broadcast('submit') }; return settings; }]);
angular.module('myApp') .factory('ctrlPanelService', ['$rootScope', 'userService', 'locationService','transactionService', function($rootScope, $userService, locationService, transactionService) { // this service is responsible for storing and broadcasting changes // to any of the control panel's settings. These settings are intended // to be available to the entire app to be synced with whatever portion // uses them. For example, transactions tab in charts will react to a // selected userId via 'updateUserId' event on the $rootScope. var settings = { users: null, userId: null }; settings.updateUsers = function(users) { settings.users = users; $rootScope.$broadcast('updateUsers'); } settings.setUserId = function(userId) { settings.userId = userId; $rootScope.$broadcast('updateUserId'); } // define generic submit event for other controllers to use settings.submit = function() { $rootScope.$broadcast('submit') }; return settings; }]);
Add comments for ctrlPanelService and its role
Add comments for ctrlPanelService and its role
JavaScript
mit
godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper,godspeedyoo/Breeze-Mapper
8a60c3bd25bd166d3e4c8a1bf6beb825bd84df81
gulp/psk-config.js
gulp/psk-config.js
module.exports = { // Autoprefixer autoprefixer: { // https://github.com/postcss/autoprefixer#browsers browsers: [ 'Explorer >= 10', 'ExplorerMobile >= 10', 'Firefox >= 30', 'Chrome >= 34', 'Safari >= 7', 'Opera >= 23', 'iOS >= 7', 'Android >= 4.4', 'BlackBerry >= 10' ] }, // BrowserSync browserSync: { browser: 'default', // or ["google chrome", "firefox"] https: false, // Enable https for localhost development. notify: false, // The small pop-over notifications in the browser. port: 9000 }, // GitHub Pages ghPages: { branch: 'gh-pages', domain: 'polymer-starter-kit.startpolymer.org', // change it! origin: 'origin' }, // PageSpeed Insights // Please feel free to use the `nokey` option to try out PageSpeed // Insights as part of your build process. For more frequent use, // we recommend registering for your own API key. For more info: // https://developers.google.com/speed/docs/insights/v1/getting_started pageSpeed: { key: '', // need uncomment in task nokey: true, site: 'http://polymer-starter-kit.startpolymer.org', // change it! strategy: 'mobile' // or desktop } };
module.exports = { // Autoprefixer autoprefixer: { // https://github.com/postcss/autoprefixer#browsers browsers: [ 'Explorer >= 10', 'ExplorerMobile >= 10', 'Firefox >= 30', 'Chrome >= 34', 'Safari >= 7', 'Opera >= 23', 'iOS >= 7', 'Android >= 4.4', 'BlackBerry >= 10' ] }, // BrowserSync browserSync: { browser: 'default', // or ["google chrome", "firefox"] https: false, // Enable https for localhost development. notify: false, // The small pop-over notifications in the browser. port: 9000 }, // GitHub Pages ghPages: { branch: 'gh-pages', domain: 'polymer-starter-kit.startpolymer.org', // change it! origin: 'origin' }, // Metalsmith metalsmith: { configFile: './psa-config.yaml' }, // PageSpeed Insights // Please feel free to use the `nokey` option to try out PageSpeed // Insights as part of your build process. For more frequent use, // we recommend registering for your own API key. For more info: // https://developers.google.com/speed/docs/insights/v1/getting_started pageSpeed: { key: '', // need uncomment in task nokey: true, site: 'http://polymer-starter-kit.startpolymer.org', // change it! strategy: 'mobile' // or desktop } };
Add metalsmith config to gulp config
Add metalsmith config to gulp config
JavaScript
mit
StartPolymer/polymer-static-app,StartPolymer/polymer-static-app
2c1b060470eb3cb5b9c876a3fe64ccebc1bdbcab
app/assets/javascripts/respondent/question_answered.js
app/assets/javascripts/respondent/question_answered.js
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') matrix_answer_field = $(this).closest('.answer_fields_wrapper').find('.submission-matrix') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) $("select#answers_"+the_id).attr("disabled", true) $(matrix_answer_field).find('select').attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $("select#answers_"+the_id).attr("disabled", false) $(matrix_answer_field).find('select').attr("disabled", false) $('.sticky_save_all').click(); } }); });
$(document).ready(function() { $(document).on('change', '.question-answered-box', function(){ the_id = $(this).data('the-id') text_answer_field = $(this).closest('.text-answer').find('.text-answer-field') matrix_answer_field = $(this).closest('.answer_fields_wrapper').find('.submission-matrix') if($(this).prop('checked')) { $(text_answer_field).attr("readonly", true) $(text_answer_field).addClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", true) $("li.answer-option-"+the_id+" textarea").attr("disabled", true) $("select#answers_"+the_id).attr("disabled", true) $(matrix_answer_field).find('select').attr("disabled", true) $(matrix_answer_field).find('input').attr("disabled", true) } else { $(text_answer_field).attr("disabled", false) $(text_answer_field).attr("readonly", false) $(text_answer_field).removeClass("disabled") $("input[name='answers["+the_id+"]']:radio").attr("disabled", false) $("li.answer-option-"+the_id+" textarea").attr("disabled", false) $("select#answers_"+the_id).attr("disabled", false) $(matrix_answer_field).find('select').attr("disabled", false) $(matrix_answer_field).find('input').attr("disabled", false) $('.sticky_save_all').click(); } }); });
Mark as answered to disable all matrix input types
Mark as answered to disable all matrix input types
JavaScript
bsd-3-clause
unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS,unepwcmc/ORS
d76319bf9ba2d629fd21c1cd5ac90f0f5b8a9981
history-handler.js
history-handler.js
/* * Copyright (c) 2010 Kevin Decker (http://www.incaseofstairs.com/) * See LICENSE for license information */ var HistoryHandler = (function() { var currentHash, callbackFn; function loadHash() { return decodeURIComponent(/#(.*)$/.exec(location.href)[1]); } function checkHistory(){ var hashValue = loadHash(); if(hashValue !== currentHash) { currentHash = hashValue; callbackFn(currentHash); } } return { init: function(callback) { callbackFn = callback; currentHash = loadHash(); callbackFn(currentHash); setInterval(checkHistory, 500); }, store: function(state) { currentHash = state; location = "#" + encodeURIComponent(state); } } })();
/* * Copyright (c) 2010 Kevin Decker (http://www.incaseofstairs.com/) * See LICENSE for license information */ var HistoryHandler = (function() { var currentHash, callbackFn; function loadHash() { return decodeURIComponent(/#(.*)$/.exec((location.href || []))[1] || ""); } function checkHistory(){ var hashValue = loadHash(); if(hashValue !== currentHash) { currentHash = hashValue; callbackFn(currentHash); } } return { init: function(callback) { callbackFn = callback; currentHash = loadHash(); callbackFn(currentHash); setInterval(checkHistory, 500); }, store: function(state) { currentHash = state; location = "#" + encodeURIComponent(state); } } })();
Fix no hash case in history handler
Fix no hash case in history handler
JavaScript
bsd-3-clause
leonardohipolito/border-image-generator,kpdecker/border-image-generator,kpdecker/border-image-generator,leonardohipolito/border-image-generator
f6596240ba68ce13c08254cb864f0f353320e313
application/widgets/source/class/widgets/view/Start.js
application/widgets/source/class/widgets/view/Start.js
/* ************************************************************************ widgets Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /** * Start View */ qx.Class.define("widgets.view.Start", { extend : unify.view.StaticView, type : "singleton", members : { // overridden getTitle : function(type, param) { return "Start"; }, // overridden _createView : function() { var layer = new unify.ui.Layer(this); //var titlebar = new unify.ui.ToolBar(this); //layer.add(titlebar); /*var content = new unify.ui.Content; content.add("Hello World"); layer.add(content);*/ var layerWidget = new unify.ui.widget.core.Layer(layer); var cont = new unify.ui.widget.basic.Label("Das ist ein Test"); layerWidget.add(cont, { left: 50, top: 10 }); cont.set({ width: 100, height: 50 }); return layer; } } });
/* ************************************************************************ widgets Copyright: 2009 Deutsche Telekom AG, Germany, http://telekom.com ************************************************************************ */ /** * Start View */ qx.Class.define("widgets.view.Start", { extend : unify.view.StaticView, type : "singleton", members : { // overridden getTitle : function(type, param) { return "Start"; }, // overridden _createView : function() { var layer = new unify.ui.Layer(this); //var titlebar = new unify.ui.ToolBar(this); //layer.add(titlebar); /*var content = new unify.ui.Content; content.add("Hello World"); layer.add(content);*/ var layerWidget = new unify.ui.widget.core.Layer(layer); /*var cont = new unify.ui.widget.basic.Label("Das ist ein Test"); layerWidget.add(cont, { left: 50, top: 10 }); cont.set({ width: 100, height: 50 });*/ var scroller = new unify.ui.widget.container.Scroll(); layerWidget.add(scroller, { left: 50, top: 50 }); scroller.set({ width: 300, height: 300 }); var label = new unify.ui.widget.basic.Label("Das ist ein Test"); scroller.add(label, { left: 50, top: 10 }); label.set({ width: 100, height: 50 }); return layer; } } });
Add scroll area to test application
Add scroll area to test application
JavaScript
mit
unify/unify,unify/unify,unify/unify,unify/unify,unify/unify,unify/unify
72e9f05a844f38eb03611625f5bc639c3c2a5f20
app/javascript/packs/application.js
app/javascript/packs/application.js
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb console.log('Hello World from Webpacker')
/* eslint no-console:0 */ // This file is automatically compiled by Webpack, along with any other files // present in this directory. You're encouraged to place your actual application logic in // a relevant structure within app/javascript and only use these pack files to reference // that code so it'll be compiled. // // To reference this file, add <%= javascript_pack_tag 'application' %> to the appropriate // layout file, like app/views/layouts/application.html.erb
Remove default message from webpack
Remove default message from webpack
JavaScript
mit
apvale/apvale.github.io,apvale/apvale.github.io,apvale/apvale.github.io
80d3bccc16c15681292e67edd69ec1631a4c63d1
chrome/browser/resources/net_internals/http_cache_view.js
chrome/browser/resources/net_internals/http_cache_view.js
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. * @constructor */ function HttpCacheView() { const mainBoxId = 'http-cache-view-tab-content'; const statsDivId = 'http-cache-view-cache-stats'; DivView.call(this, mainBoxId); this.statsDiv_ = $(statsDivId); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } inherits(HttpCacheView, DivView); HttpCacheView.prototype.onLoadLogFinish = function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }; HttpCacheView.prototype.onHttpCacheInfoChanged = function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; };
// Copyright (c) 2011 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. /** * This view displays information on the HTTP cache. */ var HttpCacheView = (function() { // IDs for special HTML elements in http_cache_view.html const MAIN_BOX_ID = 'http-cache-view-tab-content'; const STATS_DIV_ID = 'http-cache-view-cache-stats'; // We inherit from DivView. var superClass = DivView; /** * @constructor */ function HttpCacheView() { // Call superclass's constructor. superClass.call(this, MAIN_BOX_ID); this.statsDiv_ = $(STATS_DIV_ID); // Register to receive http cache info. g_browser.addHttpCacheInfoObserver(this); } cr.addSingletonGetter(HttpCacheView); HttpCacheView.prototype = { // Inherit the superclass's methods. __proto__: superClass.prototype, onLoadLogFinish: function(data) { return this.onHttpCacheInfoChanged(data.httpCacheInfo); }, onHttpCacheInfoChanged: function(info) { this.statsDiv_.innerHTML = ''; if (!info) return false; // Print the statistics. var statsUl = addNode(this.statsDiv_, 'ul'); for (var statName in info.stats) { var li = addNode(statsUl, 'li'); addTextNode(li, statName + ': ' + info.stats[statName]); } return true; } }; return HttpCacheView; })();
Refactor HttpCacheView to be defined inside an anonymous namespace.
Refactor HttpCacheView to be defined inside an anonymous namespace. BUG=90857 Review URL: http://codereview.chromium.org/7544008 git-svn-id: de016e52bd170d2d4f2344f9bf92d50478b649e0@94868 0039d316-1c4b-4281-b951-d872f2087c98
JavaScript
bsd-3-clause
PeterWangIntel/chromium-crosswalk,hujiajie/pa-chromium,bright-sparks/chromium-spacewalk,rogerwang/chromium,zcbenz/cefode-chromium,mohamed--abdel-maksoud/chromium.src,ondra-novak/chromium.src,M4sse/chromium.src,ondra-novak/chromium.src,Jonekee/chromium.src,jaruba/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,zcbenz/cefode-chromium,dednal/chromium.src,fujunwei/chromium-crosswalk,hgl888/chromium-crosswalk-efl,ltilve/chromium,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,anirudhSK/chromium,patrickm/chromium.src,dednal/chromium.src,hgl888/chromium-crosswalk-efl,fujunwei/chromium-crosswalk,nacl-webkit/chrome_deps,markYoungH/chromium.src,mogoweb/chromium-crosswalk,crosswalk-project/chromium-crosswalk-efl,Fireblend/chromium-crosswalk,anirudhSK/chromium,timopulkkinen/BubbleFish,krieger-od/nwjs_chromium.src,ltilve/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,axinging/chromium-crosswalk,nacl-webkit/chrome_deps,junmin-zhu/chromium-rivertrail,hgl888/chromium-crosswalk-efl,Jonekee/chromium.src,robclark/chromium,ondra-novak/chromium.src,dednal/chromium.src,TheTypoMaster/chromium-crosswalk,littlstar/chromium.src,Just-D/chromium-1,ltilve/chromium,Fireblend/chromium-crosswalk,ltilve/chromium,zcbenz/cefode-chromium,fujunwei/chromium-crosswalk,robclark/chromium,patrickm/chromium.src,robclark/chromium,chuan9/chromium-crosswalk,dushu1203/chromium.src,markYoungH/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,patrickm/chromium.src,fujunwei/chromium-crosswalk,krieger-od/nwjs_chromium.src,ChromiumWebApps/chromium,ChromiumWebApps/chromium,keishi/chromium,fujunwei/chromium-crosswalk,dushu1203/chromium.src,dushu1203/chromium.src,Just-D/chromium-1,crosswalk-project/chromium-crosswalk-efl,dednal/chromium.src,dednal/chromium.src,krieger-od/nwjs_chromium.src,rogerwang/chromium,hgl888/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,mohamed--abdel-maksoud/chromium.src,junmin-zhu/chromium-rivertrail,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,Jonekee/chromium.src,M4sse/chromium.src,Fireblend/chromium-crosswalk,keishi/chromium,chuan9/chromium-crosswalk,hujiajie/pa-chromium,jaruba/chromium.src,ChromiumWebApps/chromium,nacl-webkit/chrome_deps,keishi/chromium,Jonekee/chromium.src,patrickm/chromium.src,hgl888/chromium-crosswalk-efl,Chilledheart/chromium,nacl-webkit/chrome_deps,rogerwang/chromium,Just-D/chromium-1,keishi/chromium,M4sse/chromium.src,bright-sparks/chromium-spacewalk,Just-D/chromium-1,timopulkkinen/BubbleFish,keishi/chromium,jaruba/chromium.src,rogerwang/chromium,bright-sparks/chromium-spacewalk,chuan9/chromium-crosswalk,TheTypoMaster/chromium-crosswalk,nacl-webkit/chrome_deps,crosswalk-project/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,patrickm/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,rogerwang/chromium,crosswalk-project/chromium-crosswalk-efl,crosswalk-project/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,pozdnyakov/chromium-crosswalk,axinging/chromium-crosswalk,Jonekee/chromium.src,nacl-webkit/chrome_deps,jaruba/chromium.src,jaruba/chromium.src,ondra-novak/chromium.src,ChromiumWebApps/chromium,axinging/chromium-crosswalk,dushu1203/chromium.src,Jonekee/chromium.src,chuan9/chromium-crosswalk,krieger-od/nwjs_chromium.src,Just-D/chromium-1,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,jaruba/chromium.src,Pluto-tv/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,patrickm/chromium.src,anirudhSK/chromium,axinging/chromium-crosswalk,krieger-od/nwjs_chromium.src,dednal/chromium.src,Pluto-tv/chromium-crosswalk,Jonekee/chromium.src,ltilve/chromium,ChromiumWebApps/chromium,axinging/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,ChromiumWebApps/chromium,M4sse/chromium.src,anirudhSK/chromium,Jonekee/chromium.src,hgl888/chromium-crosswalk,jaruba/chromium.src,hujiajie/pa-chromium,jaruba/chromium.src,markYoungH/chromium.src,mogoweb/chromium-crosswalk,mogoweb/chromium-crosswalk,littlstar/chromium.src,zcbenz/cefode-chromium,Chilledheart/chromium,bright-sparks/chromium-spacewalk,robclark/chromium,M4sse/chromium.src,ondra-novak/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,mohamed--abdel-maksoud/chromium.src,axinging/chromium-crosswalk,rogerwang/chromium,anirudhSK/chromium,anirudhSK/chromium,Pluto-tv/chromium-crosswalk,bright-sparks/chromium-spacewalk,dushu1203/chromium.src,junmin-zhu/chromium-rivertrail,mogoweb/chromium-crosswalk,hgl888/chromium-crosswalk,pozdnyakov/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,hgl888/chromium-crosswalk,Just-D/chromium-1,krieger-od/nwjs_chromium.src,Fireblend/chromium-crosswalk,zcbenz/cefode-chromium,littlstar/chromium.src,pozdnyakov/chromium-crosswalk,M4sse/chromium.src,dednal/chromium.src,Chilledheart/chromium,dushu1203/chromium.src,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,PeterWangIntel/chromium-crosswalk,timopulkkinen/BubbleFish,hgl888/chromium-crosswalk-efl,junmin-zhu/chromium-rivertrail,nacl-webkit/chrome_deps,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,Jonekee/chromium.src,crosswalk-project/chromium-crosswalk-efl,anirudhSK/chromium,markYoungH/chromium.src,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,PeterWangIntel/chromium-crosswalk,littlstar/chromium.src,bright-sparks/chromium-spacewalk,Chilledheart/chromium,dushu1203/chromium.src,robclark/chromium,timopulkkinen/BubbleFish,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,M4sse/chromium.src,anirudhSK/chromium,ltilve/chromium,pozdnyakov/chromium-crosswalk,Chilledheart/chromium,zcbenz/cefode-chromium,Fireblend/chromium-crosswalk,rogerwang/chromium,ondra-novak/chromium.src,hgl888/chromium-crosswalk,dednal/chromium.src,Fireblend/chromium-crosswalk,ChromiumWebApps/chromium,hgl888/chromium-crosswalk,dednal/chromium.src,ondra-novak/chromium.src,littlstar/chromium.src,Fireblend/chromium-crosswalk,timopulkkinen/BubbleFish,hujiajie/pa-chromium,M4sse/chromium.src,hgl888/chromium-crosswalk-efl,markYoungH/chromium.src,chuan9/chromium-crosswalk,bright-sparks/chromium-spacewalk,dednal/chromium.src,dednal/chromium.src,crosswalk-project/chromium-crosswalk-efl,nacl-webkit/chrome_deps,mogoweb/chromium-crosswalk,keishi/chromium,timopulkkinen/BubbleFish,TheTypoMaster/chromium-crosswalk,hgl888/chromium-crosswalk,markYoungH/chromium.src,krieger-od/nwjs_chromium.src,keishi/chromium,pozdnyakov/chromium-crosswalk,junmin-zhu/chromium-rivertrail,littlstar/chromium.src,ondra-novak/chromium.src,dushu1203/chromium.src,axinging/chromium-crosswalk,chuan9/chromium-crosswalk,rogerwang/chromium,junmin-zhu/chromium-rivertrail,keishi/chromium,rogerwang/chromium,hujiajie/pa-chromium,dushu1203/chromium.src,Pluto-tv/chromium-crosswalk,ChromiumWebApps/chromium,hujiajie/pa-chromium,mogoweb/chromium-crosswalk,keishi/chromium,littlstar/chromium.src,dushu1203/chromium.src,robclark/chromium,PeterWangIntel/chromium-crosswalk,zcbenz/cefode-chromium,Chilledheart/chromium,crosswalk-project/chromium-crosswalk-efl,zcbenz/cefode-chromium,junmin-zhu/chromium-rivertrail,chuan9/chromium-crosswalk,Fireblend/chromium-crosswalk,Pluto-tv/chromium-crosswalk,ltilve/chromium,Pluto-tv/chromium-crosswalk,patrickm/chromium.src,krieger-od/nwjs_chromium.src,pozdnyakov/chromium-crosswalk,Just-D/chromium-1,ChromiumWebApps/chromium,Just-D/chromium-1,Chilledheart/chromium,hgl888/chromium-crosswalk-efl,TheTypoMaster/chromium-crosswalk,markYoungH/chromium.src,Jonekee/chromium.src,mohamed--abdel-maksoud/chromium.src,nacl-webkit/chrome_deps,hujiajie/pa-chromium,anirudhSK/chromium,jaruba/chromium.src,markYoungH/chromium.src,hgl888/chromium-crosswalk-efl,hujiajie/pa-chromium,ltilve/chromium,axinging/chromium-crosswalk,mogoweb/chromium-crosswalk,anirudhSK/chromium,ltilve/chromium,rogerwang/chromium,junmin-zhu/chromium-rivertrail,hujiajie/pa-chromium,Jonekee/chromium.src,zcbenz/cefode-chromium,Pluto-tv/chromium-crosswalk,fujunwei/chromium-crosswalk,pozdnyakov/chromium-crosswalk,nacl-webkit/chrome_deps,ChromiumWebApps/chromium,fujunwei/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,nacl-webkit/chrome_deps,pozdnyakov/chromium-crosswalk,ondra-novak/chromium.src,zcbenz/cefode-chromium,crosswalk-project/chromium-crosswalk-efl,robclark/chromium,robclark/chromium,mohamed--abdel-maksoud/chromium.src,pozdnyakov/chromium-crosswalk,patrickm/chromium.src,mogoweb/chromium-crosswalk,chuan9/chromium-crosswalk,chuan9/chromium-crosswalk,ChromiumWebApps/chromium,ChromiumWebApps/chromium,hgl888/chromium-crosswalk-efl,mohamed--abdel-maksoud/chromium.src,hujiajie/pa-chromium,TheTypoMaster/chromium-crosswalk,Chilledheart/chromium,anirudhSK/chromium,Fireblend/chromium-crosswalk,hgl888/chromium-crosswalk,timopulkkinen/BubbleFish,markYoungH/chromium.src,jaruba/chromium.src,junmin-zhu/chromium-rivertrail,fujunwei/chromium-crosswalk,junmin-zhu/chromium-rivertrail,PeterWangIntel/chromium-crosswalk,krieger-od/nwjs_chromium.src,mohamed--abdel-maksoud/chromium.src,timopulkkinen/BubbleFish,M4sse/chromium.src,bright-sparks/chromium-spacewalk,anirudhSK/chromium,robclark/chromium,hujiajie/pa-chromium,robclark/chromium,mogoweb/chromium-crosswalk,jaruba/chromium.src
679962935ae5303bde46ca18a216b14504e2327c
worldGenerator/DungeonBluePrints.js
worldGenerator/DungeonBluePrints.js
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { for (let i = 0; i < this.worldSize; i++) { let dungeonId = `dungeon_${i}`; let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
'use strict'; const common = require('./../server/common'); export class DungeonBluePrints { constructor (number, worldSize, locationSize) { this.number = number; this.worldSize = worldSize; this.locationSize = locationSize; this.blueprints = {}; } generate () { const idList = []; while (this.number) { let lx = common.getRandomInt(0, this.worldSize - 1); let ly = common.getRandomInt(0, this.worldSize - 1); let locationId = `location_${ly}_${lx}`; if (locationId in idList) continue; idList.push(locationId); this.number--; let dungeonId = `dungeon_${this.number}`; let levels = common.getRandomInt(1, this.worldSize); let entrances = []; for (let l = 0; l < levels; l++) { let x = common.getRandomInt(0, this.locationSize - 1); let y = common.getRandomInt(0, this.locationSize - 1); entrances.push([x, y]); } this.blueprints[dungeonId] = { 'locationId': locationId, 'levels': levels, 'entrances': entrances }; } } }
Improve generate method for uniq locations
Improve generate method for uniq locations
JavaScript
mit
nobus/Labyrinth,nobus/Labyrinth
bd7bd1f25231434489d425613f41e1bda888a291
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js", path: path.resolve(__dirname, "public/") }, resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, use: "awesome-typescript-loader" }, { test: /\.js$/, use: "source-map-loader", enforce: "pre" }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/, use: 'url-loader' } ] } };
const path = require('path'); module.exports = { entry: "./src/index.tsx", output: { filename: "bundle.js", path: path.resolve(__dirname, "public/") }, resolve: { // Add '.ts' and '.tsx' as resolvable extensions. extensions: [".ts", ".tsx", ".js", ".json"] }, module: { rules: [ { test: /\.tsx?$/, use: "awesome-typescript-loader" }, { test: /\.js$/, use: "source-map-loader", exclude: /node_modules/, enforce: "pre" }, { test: /\.css$/, use: ['style-loader', 'css-loader'] }, { test: /\.(otf|eot|svg|ttf|woff|woff2|jpg|png)(\?.+)?$/, use: 'url-loader' } ] } };
Fix for a source-map warning
:hammer: Fix for a source-map warning
JavaScript
mit
tadashi-aikawa/owlora,tadashi-aikawa/owlora,tadashi-aikawa/owlora
6d40c5a2511368407c86e4f9fc39850d3f2a74c2
js/musichipster.js
js/musichipster.js
window.onload = function() { var tabs = function() { var args = models.application.arguments; var current = $("#"+args[0]); var sections = $(".section"); sections.hide(); current.show(); } sp = getSpotifyApi(1); var models = sp.require("sp://import/scripts/api/models"); models.application.observe(models.EVENT.ARGUMENTSCHANGED, tabs); }
window.onload = function() { var tabs = function() { var args = models.application.arguments; var current = $("#"+args[0]); var sections = $(".section"); sections.hide(); current.show(); } sp = getSpotifyApi(1); var models = sp.require("sp://import/scripts/api/models"); models.application.observe(models.EVENT.ARGUMENTSCHANGED, tabs); $("#judgeMeButton").click(function() { console.info("judging..."); }); }
Add handler for Judging button
Add handler for Judging button
JavaScript
mit
hassy/music_hipster
22e747a989a343402fe54193b2780ef3d91c5d4a
node-tests/unit/utils/make-dir-test.js
node-tests/unit/utils/make-dir-test.js
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { afterEach(() => { td.reset(); }); it('makes the directory', () => { var mkdirSync = td.replace(fs, 'mkdirSync'); let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
'use strict'; const td = require('testdouble'); const MakeDir = require('../../../src/utils/make-dir'); const fs = require('fs'); const path = require('path'); describe('MakeDir', () => { context('when base and destPath', () => { let mkdirSync; beforeEach(() => { mkdirSync = td.replace(fs, 'mkdirSync'); }); afterEach(() => { td.reset(); }); it('makes the directory', () => { let base = './'; const destPath = 'foo/bar'; MakeDir(base, destPath); // Verify replaced property was invoked. destPath.split('/').forEach((segment) => { base = path.join(base, segment); td.verify(mkdirSync(base)); }); }); }); });
Update test to move test double replacement to before block
refactor(make-dir): Update test to move test double replacement to before block
JavaScript
mit
isleofcode/splicon
85ff298cf9f22036f83388a72cc99a868a2fabe5
examples/Node.js/exportTadpoles.js
examples/Node.js/exportTadpoles.js
require('../../index.js'); var scope = require('./Tadpoles'); scope.view.exportFrames({ amount: 200, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
require('../../node.js/'); var paper = require('./Tadpoles'); paper.view.exportFrames({ amount: 400, directory: __dirname, onComplete: function() { console.log('Done exporting.'); }, onProgress: function(event) { console.log(event.percentage + '% complete, frame took: ' + event.delta); } });
Clean up Node.js tadpoles example.
Clean up Node.js tadpoles example.
JavaScript
mit
NHQ/paper,NHQ/paper
c5a54ec1b1de01baf05788b0602e20d41ebfc767
packages/babel-plugin-inline-view-configs/__tests__/index-test.js
packages/babel-plugin-inline-view-configs/__tests__/index-test.js
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+react_native * @format */ 'use strict'; const {transform: babelTransform} = require('@babel/core'); const fixtures = require('../__test_fixtures__/fixtures.js'); const failures = require('../__test_fixtures__/failures.js'); function transform(fixture, filename) { return babelTransform(fixture, { babelrc: false, cwd: '/', filename: filename, highlightCode: false, plugins: [require('@babel/plugin-syntax-flow'), require('../index')], }).code; } describe('Babel plugin inline view configs', () => { Object.keys(fixtures) .sort() .forEach(fixtureName => { it(`can inline config for ${fixtureName}`, () => { expect(transform(fixtures[fixtureName], fixtureName)).toMatchSnapshot(); }); }); Object.keys(failures) .sort() .forEach(fixtureName => { it(`fails on inline config for ${fixtureName}`, () => { expect(() => { transform(failures[fixtureName], fixtureName); }).toThrowErrorMatchingSnapshot(); }); }); });
/** * Copyright (c) Facebook, Inc. and its affiliates. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. * * @emails oncall+react_native * @format */ 'use strict'; const {transform: babelTransform} = require('@babel/core'); const fixtures = require('../__test_fixtures__/fixtures.js'); const failures = require('../__test_fixtures__/failures.js'); const transform = (fixture, filename) => babelTransform(fixture, { babelrc: false, cwd: '/', filename: filename, highlightCode: false, plugins: [require('@babel/plugin-syntax-flow'), require('../index')], }).code.replace(/^[A-Z]:\\/g, '/'); // Ensure platform consistent snapshots. describe('Babel plugin inline view configs', () => { Object.keys(fixtures) .sort() .forEach(fixtureName => { it(`can inline config for ${fixtureName}`, () => { expect(transform(fixtures[fixtureName], fixtureName)).toMatchSnapshot(); }); }); Object.keys(failures) .sort() .forEach(fixtureName => { it(`fails on inline config for ${fixtureName}`, () => { expect(() => { transform(failures[fixtureName], fixtureName); }).toThrowErrorMatchingSnapshot(); }); }); });
Fix inline-view-configs test on Windows.
Fix inline-view-configs test on Windows. Summary: *facepalm* The file path is platform specific. Changelog: [Internal] Reviewed By: GijsWeterings Differential Revision: D20793023 fbshipit-source-id: 4fbcbf982911ee449a4fa5067cc0c5d81088ce04
JavaScript
bsd-3-clause
hammerandchisel/react-native,hoangpham95/react-native,janicduplessis/react-native,exponent/react-native,hammerandchisel/react-native,hoangpham95/react-native,exponentjs/react-native,facebook/react-native,hammerandchisel/react-native,myntra/react-native,javache/react-native,pandiaraj44/react-native,hammerandchisel/react-native,facebook/react-native,pandiaraj44/react-native,janicduplessis/react-native,myntra/react-native,exponent/react-native,pandiaraj44/react-native,arthuralee/react-native,pandiaraj44/react-native,myntra/react-native,exponentjs/react-native,facebook/react-native,javache/react-native,facebook/react-native,myntra/react-native,arthuralee/react-native,hoangpham95/react-native,hammerandchisel/react-native,hammerandchisel/react-native,javache/react-native,hammerandchisel/react-native,pandiaraj44/react-native,exponent/react-native,exponentjs/react-native,javache/react-native,janicduplessis/react-native,hoangpham95/react-native,myntra/react-native,arthuralee/react-native,janicduplessis/react-native,facebook/react-native,pandiaraj44/react-native,exponent/react-native,exponent/react-native,exponentjs/react-native,exponentjs/react-native,exponentjs/react-native,javache/react-native,facebook/react-native,javache/react-native,arthuralee/react-native,hoangpham95/react-native,exponent/react-native,myntra/react-native,janicduplessis/react-native,facebook/react-native,hoangpham95/react-native,exponentjs/react-native,pandiaraj44/react-native,janicduplessis/react-native,javache/react-native,arthuralee/react-native,pandiaraj44/react-native,hoangpham95/react-native,myntra/react-native,myntra/react-native,exponentjs/react-native,javache/react-native,hammerandchisel/react-native,exponent/react-native,exponent/react-native,javache/react-native,facebook/react-native,myntra/react-native,janicduplessis/react-native,janicduplessis/react-native,facebook/react-native,hoangpham95/react-native
0cae8b6bebd3f28a92084289951b944bed35c937
webpack.config.js
webpack.config.js
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
var webpack = require('webpack'); var path = require('path'); module.exports = { context: __dirname + '/app', entry: './index.js', output: { path: __dirname + '/bin', publicPath: '/', filename: 'bundle.js', }, stats: { colors: true, progress: true, }, resolve: { extensions: ['', '.webpack.js', '.js'], modulesDirectories: [ 'app', 'node_modules', ], }, module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, query: { presets: ['es2015'], }, loader: 'babel', }, ], }, };
Resolve directories in the app folder
Resolve directories in the app folder
JavaScript
mit
oliverbenns/pong,oliverbenns/pong
219c639530f7e72ac12980291d03b2e9a2808d3e
webpack.config.js
webpack.config.js
const path = require('path'); module.exports = { devtool: 'inline-source-map', entry: './src/index.js', module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', exclude: /node_modules/, options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, output: { library: 'Muxy', libraryTarget: 'umd', umdNamedDefine: true, path: path.resolve(__dirname, 'dist'), filename: 'muxy-extensions-sdk.js' } };
const path = require('path'); const port = process.env.PORT || 9000; module.exports = { devtool: 'inline-source-map', entry: './src/index.js', module: { rules: [ { test: /\.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', exclude: /node_modules/, options: { formatter: require('eslint-friendly-formatter') } }, { test: /\.js$/, exclude: /node_modules/, use: { loader: 'babel-loader' } } ] }, output: { library: 'Muxy', libraryTarget: 'umd', umdNamedDefine: true, path: path.resolve(__dirname, 'dist'), filename: 'muxy-extensions-sdk.js' }, devServer: { port } };
Use PORT env for dev server
Use PORT env for dev server
JavaScript
isc
muxy/extensions-js,muxy/extensions-js,muxy/extensions-js
cdce8405c85996b5362ef05fc4c715725e640394
webpack.config.prod.js
webpack.config.prod.js
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
const path = require('path'); const webpack = require('webpack'); const CleanWebpackPlugin = require('clean-webpack-plugin'); const HtmlWebpackPlugin = require('html-webpack-plugin'); const project = require('./project.config.json'); const plugins = [ new CleanWebpackPlugin(['public']), new webpack.optimize.CommonsChunkPlugin({ name: 'commons', filename: 'js/common.js' }), new HtmlWebpackPlugin({ title: project.title, filename: '../index.html', template: 'index_template.ejs', inject: true, hash: true }) ]; module.exports = { entry: { 'app': './src' }, output: { path: path.join(__dirname, './public/assets'), publicPath: project.repoName + '/assets/', filename: 'js/[name].js' }, module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', include: path.join(__dirname, 'src') }, { test: /\.css$/, loader: 'style!css' } ] }, resolve: { root: [ path.resolve(__dirname, 'src') ], extensions: ['', '.js', '.jsx'], }, plugins: plugins };
Add hashing in build HMTL
Add hashing in build HMTL
JavaScript
mit
ibleedfilm/fcc-react-project,ibleedfilm/recipe-box,ibleedfilm/fcc-react-project,ibleedfilm/recipe-box
26e3988ea21f5dea1e47cefe51eb546ea6a06f64
blueocean-web/src/main/js/try.js
blueocean-web/src/main/js/try.js
var $ = require('jquery-detached').getJQuery(); var jsModules = require('@jenkins-cd/js-modules'); $(document).ready(function () { var tryBlueOcean = $('<div class="try-blueocean header-callout">Try Blue Ocean UI ...</div>'); tryBlueOcean.click(function () { // We could enhance this further by looking at the current // URL and going to different places in the BO UI depending // on where the user is in classic jenkins UI e.g. if they // are currently in a job on classic UI, bring them to the // same job in BO UI Vs just brining them to the root of // BO UI i.e. make the button context sensitive. window.location.replace(jsModules.getRootURL() + '/blue'); }); $('#page-head #header').append(tryBlueOcean); });
var $ = require('jquery-detached').getJQuery(); var jsModules = require('@jenkins-cd/js-modules'); $(document).ready(() => { var tryBlueOcean = $('<div class="try-blueocean header-callout">Try Blue Ocean UI ...</div>'); tryBlueOcean.click(() => { // We could enhance this further by looking at the current // URL and going to different places in the BO UI depending // on where the user is in classic jenkins UI e.g. if they // are currently in a job on classic UI, bring them to the // same job in BO UI Vs just brining them to the root of // BO UI i.e. make the button context sensitive. window.location.replace(`${jsModules.getRootURL()}/blue`); }); $('#page-head #header').append(tryBlueOcean); });
Add a "Try Blue Ocean UI" button in classic Jenkins - fix lint errors
Add a "Try Blue Ocean UI" button in classic Jenkins - fix lint errors
JavaScript
mit
kzantow/blueocean-plugin,kzantow/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,jenkinsci/blueocean-plugin,ModuloM/blueocean-plugin,tfennelly/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,kzantow/blueocean-plugin,kzantow/blueocean-plugin,ModuloM/blueocean-plugin,alvarolobato/blueocean-plugin,ModuloM/blueocean-plugin,alvarolobato/blueocean-plugin,jenkinsci/blueocean-plugin,tfennelly/blueocean-plugin
bc864168d477192120b67ff32f71d07ea1674d76
client/src/js/dispatcher/user.js
client/src/js/dispatcher/user.js
/** * Copyright 2015, Government of Canada. * All rights reserved. * * This source code is licensed under the MIT license. * * @providesModule User */ var Cookie = require('react-cookie'); var Events = require('./Events'); /** * An object that manages all user authentication and the user profile. * * @constructor */ var User = function () { this.name = null; this.events = new Events(['change', 'logout'], this); this.load = function (data) { // Update the username, token, and reset properties with the authorized values. _.assign(this, _.omit(data, '_id')); this.name = data._id; Cookie.save('token', data.token); this.emit('change'); }; this.authorize = function (data) { this.load(data); dispatcher.sync(); }; this.deauthorize = function (data) { dispatcher.storage.deleteDatabase(function () { location.hash = 'home/welcome'; this.name = null; _.forIn(dispatcher.db, function (collection) { collection.documents = []; collection.synced = false; }); this.emit('logout', data); }.bind(this)); }.bind(this); this.logout = function () { dispatcher.send({ collectionName: 'users', methodName: 'logout', data: { token: this.token } }, this.deauthorize); }; }; module.exports = User;
/** * Copyright 2015, Government of Canada. * All rights reserved. * * This source code is licensed under the MIT license. * * @providesModule User */ var Cookie = require('react-cookie'); var Events = require('./Events'); /** * An object that manages all user authentication and the user profile. * * @constructor */ var User = function () { this.name = null; this.events = new Events(['change', 'logout'], this); this.load = function (data) { // Update the username, token, and reset properties with the authorized values. _.assign(this, _.omit(data, '_id')); this.name = data._id; Cookie.save('token', data.token); this.emit('change'); }; this.authorize = function (data) { this.load(data); dispatcher.sync(); }; this.deauthorize = function (data) { dispatcher.db.loki.deleteDatabase({}, function () { location.hash = 'home/welcome'; this.name = null; _.forIn(dispatcher.db, function (collection) { collection.documents = []; collection.synced = false; }); this.emit('logout', data); }.bind(this)); }.bind(this); this.logout = function () { dispatcher.send({ collectionName: 'users', methodName: 'logout', data: { token: this.token } }, this.deauthorize); }; }; module.exports = User;
Delete Loki database and persistent storage on logout.
Delete Loki database and persistent storage on logout.
JavaScript
mit
igboyes/virtool,igboyes/virtool,virtool/virtool,virtool/virtool
64019f0ffd4582e8bb047e261152c9a034bfe378
index.js
index.js
window.onload = function() { sectionShow(); blogController(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
window.onload = function() { sectionShow(); }; function sectionShow() { var sectionControls = {'home_btn': 'home', 'about_btn': 'about', 'projects_btn': 'projects', 'blog_btn': 'blog'} document.getElementById('menu').addEventListener('click', function(event) { event.preventDefault(); hideSections(sectionControls); document.getElementById(sectionControls[event.target.id]).style.display = 'inline'; if (event.target.id == 'blog_btn') { blogController() }; }); }; function hideSections(sections) { for (i in sections) { document.getElementById(sections[i]).style.display = 'none'; }; }; function blogController() { document.getElementById('blog_control').addEventListener('click', function(event) { event.preventDefault(); ajaxWrapper(blogList[i]); }; }); }; function ajaxWrapper(blog_page) { var xml = new XMLHttpRequest(); xml.onreadystatechange = function() { if (xml.readyState == 4 && xml.status == 200) { blog_div = document.getElementById('blog_show'); blog_div.style.display = 'inline'; blog_div.innerHTML = xml.responseText; }; }; xml.open('GET', blog_page, true); xml.send(); };
Move blogController to run only if blog section is loaded
Index.js: Move blogController to run only if blog section is loaded
JavaScript
mit
jorgerc85/jorgerc85.github.io,jorgerc85/jorgerc85.github.io
c1928257ac5233ad15866c5d4675ebdf7f552203
index.js
index.js
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-docker-config', contentFor: function(type, config) { if (type === 'head') { return '<script type="text/javascript">window.DynamicENV = ' + this.dynamicConfig(config.DynamicConfig) + ';</script>'; } }, dynamicConfig: function(config) { var param; if (!config) { return ''; } var configParams = []; for (param in config) { if (typeof config[param] === 'object') { configParams.push('"' + param + '": ' + this.dynamicConfig(config[param])); } else { if (process.env[config[param]]) { configParams.push('"' + param + '": "' + process.env[config[param]] + '"'); } } } return '{' + configParams.join(',') + '}'; } };
/* jshint node: true */ 'use strict'; module.exports = { name: 'ember-cli-docker-config', contentFor: function(type, config) { if (type === 'head') { return '<script type="text/javascript">window.DynamicENV = ' + this.dynamicConfig(config.DynamicConfig) + ';</script>'; } }, dynamicConfig: function(config) { var param; if (!config) { return ''; } var configParams = []; for (param in config) { switch (typeof config[param]) { case 'object': configParams.push('"' + param + '": ' + this.dynamicConfig(config[param])); break; case 'string': if (process.env[config[param]]) { configParams.push('"' + param + '": "' + process.env[config[param]] + '"'); } break; case 'function': configParams.push('"' + param + '": "' + config[param](process.env) + '"'); break; } } return '{' + configParams.join(',') + '}'; } };
Add ability to specify a function instead of a string for dynamic configs
Add ability to specify a function instead of a string for dynamic configs
JavaScript
mit
pk4media/ember-cli-docker-config,pk4media/ember-cli-docker-config
d09cd9ef89e9860c7b972cba9fcb1736f4de17c7
lib/node_modules/@stdlib/repl/lib/context/regexp/index.js
lib/node_modules/@stdlib/repl/lib/context/regexp/index.js
'use strict'; var NS = {}; // MODULES // var getKeys = require( 'object-keys' ).shim(); NS.RE_EOL = require( '@stdlib/regexp/eol' ); NS.RE_EXTNAME = require( '@stdlib/regexp/extname' ); NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' ); NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' ); NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' ); // VARIABLES // var KEYS = getKeys( NS ); // BIND // /** * Binds functions to a REPL namespace. * * @private * @param {Object} ns - namespace * @returns {Object} input namespace * * @example * var ns = {}; * bind( ns ); * // returns <input_namespace> */ function bind( ns ) { var key; var i; for ( i = 0; i < KEYS.length; i++ ) { key = KEYS[ i ]; ns[ key ] = NS[ key ]; } return ns; } // end FUNCTION bind() // EXPORTS // module.exports = bind;
'use strict'; var NS = {}; // MODULES // var getKeys = require( 'object-keys' ).shim(); NS.RE_EOL = require( '@stdlib/regexp/eol' ); NS.RE_DIRNAME = require( '@stdlib/regexp/dirname' ); NS.RE_DIRNAME_POSIX = require( '@stdlib/regexp/dirname-posix' ); NS.RE_DIRNAME_WINDOWS = require( '@stdlib/regexp/dirname-windows' ); NS.RE_EXTNAME = require( '@stdlib/regexp/extname' ); NS.RE_EXTNAME_POSIX = require( '@stdlib/regexp/extname-posix' ); NS.RE_EXTNAME_WINDOWS = require( '@stdlib/regexp/extname-windows' ); NS.RE_FUNCTION_NAME = require( '@stdlib/regexp/function-name' ); // VARIABLES // var KEYS = getKeys( NS ); // BIND // /** * Binds functions to a REPL namespace. * * @private * @param {Object} ns - namespace * @returns {Object} input namespace * * @example * var ns = {}; * bind( ns ); * // returns <input_namespace> */ function bind( ns ) { var key; var i; for ( i = 0; i < KEYS.length; i++ ) { key = KEYS[ i ]; ns[ key ] = NS[ key ]; } return ns; } // end FUNCTION bind() // EXPORTS // module.exports = bind;
Add dirname RegExps to REPL context
Add dirname RegExps to REPL context
JavaScript
apache-2.0
stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib,stdlib-js/stdlib
2beadbe92492133a4b643ec257ab40910e520031
src/bot.js
src/bot.js
const Eris = require("eris"); const config = require("./cfg"); const bot = new Eris.Client(config.token, { getAllUsers: true, restMode: true, }); module.exports = bot;
const Eris = require("eris"); const config = require("./cfg"); const bot = new Eris.Client(config.token, { restMode: true, }); module.exports = bot;
Disable getAllUsers from the client
Disable getAllUsers from the client We can lazy-load members instead.
JavaScript
mit
Dragory/modmailbot
2efd96c382e193197acbbc30c0e0d6be135cd09c
lib/js/tabulate.js
lib/js/tabulate.js
(function($) { $(document).ready(function() { $('#template-entry-hidden').load("entry.template.html"); $('#btn-load-project').click(function(){ var project = $('#project-name').val(); $.getJSON(project, renderData); }); }); function renderData(data) { $.each(data, function(index, entry) { var entryDiv = $('#template-entry-hidden').clone().children(); entryDiv.find(".tabula-command").html(entry.entry.command); entryDiv.appendTo('div#project-data'); }); } })(jQuery);
(function($) { $(document).ready(function() { $('#template-entry-hidden').load("entry.template.html"); $('#btn-load-project').click(function(){ var project = $('#project-name').val(); $.getJSON(project, renderData); }); }); function renderData(data) { // For each entry $.each(data, function(index, entry) { // Clone the template var entryDiv = $('#template-entry-hidden').clone().children(); // Set background colour based on exit status entryDiv.css("background-color", pickExitColour(entry.entry.exitStatus)) entryDiv.find(".tabula-command").html(entry.entry.command); // Append to the main div entryDiv.appendTo('div#project-data'); }); } function pickExitColour(exitStatus) { if (exitStatus === 0) { // Successful return "#00FF00"; } else if (exitStatus > 127) { // Killed by user return "#FFFF00"; } else { // Failed for some reason. return "#FF0000"; } } })(jQuery);
Set the background colour based on exit status.
Set the background colour based on exit status.
JavaScript
bsd-3-clause
nc6/tabula-viewer
feab634e3d57c84f1e76ee6d00f13b2e99050b94
src/view/table/cell/AmountEntryCell.js
src/view/table/cell/AmountEntryCell.js
/** * Cell used for showing an AmountEntry * * Copyright 2015 Ethan Smith */ var Marionette = require('backbone.marionette'); var AmountEntryCell = Marionette.ItemView.extend({ tagName: 'td', render: function() { this.$el.html(this.model.entry.readable()); } }); module.exports = AmountEntryCell;
/** * Cell used for showing an AmountEntry * * Copyright 2015 Ethan Smith */ var Marionette = require('backbone.marionette'); var AmountEntryCell = Marionette.ItemView.extend({ tagName: 'td', className: function() { return this.model.entry.get() === 0 ? 'zero' : ''; }, render: function() { this.$el.html(this.model.entry.readable()); } }); module.exports = AmountEntryCell;
Add zero class to new AmountEntry cell
Add zero class to new AmountEntry cell
JavaScript
mit
onebytegone/banknote-client,onebytegone/banknote-client
f937a7643eb831c8ab4d5f4b2356a1ec2335acfa
db/migrations/20131219233339-ripple-addresses.js
db/migrations/20131219233339-ripple-addresses.js
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('ripple_addresses', { id: { type: 'int', primaryKey: true, autoIncrement: true }, user_id: { type: 'int', notNull: true }, managed: { type: 'boolean', default: false, notNull: true}, address: { type: 'string', notNull: true, unique: true }, type: { type: 'string', notNull: true }, tag: { type: 'string' }, secret: { type: 'string' }, previous_transaction_hash: { type: 'string' } }, callback); }; exports.down = function(db, callback) { db.dropTable('ripple_addresses', callback); };
var dbm = require('db-migrate'); var type = dbm.dataType; exports.up = function(db, callback) { db.createTable('ripple_addresses', { id: { type: 'int', primaryKey: true, autoIncrement: true }, user_id: { type: 'int', notNull: true }, managed: { type: 'boolean', default: false, notNull: true}, address: { type: 'string', notNull: true }, type: { type: 'string', notNull: true }, tag: { type: 'string' }, secret: { type: 'string' }, previous_transaction_hash: { type: 'string' }, createdAt: { type: 'datetime' }, updatedAt: { type: 'datetime' } }, callback); }; exports.down = function(db, callback) { db.dropTable('ripple_addresses', callback); };
Make ripple_address address column not required. Add timestamps.
[FEATURE] Make ripple_address address column not required. Add timestamps.
JavaScript
isc
xdv/gatewayd,zealord/gatewayd,Parkjeahwan/awegeeks,whotooktwarden/gatewayd,xdv/gatewayd,crazyquark/gatewayd,whotooktwarden/gatewayd,crazyquark/gatewayd,Parkjeahwan/awegeeks,zealord/gatewayd
ee71493015ea0a949d6f9dcc77e641ffc77659f0
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
misc/chrome_plugins/clean_concourse_pipeline/src/inject.user.js
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementsByTagName("nav")[0]; element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
// ==UserScript== // @name Remove concourse elements // @namespace cloudpipeline.digital // @description Strips away some of the cruft from the concourse pipeline view when showing it on monitoring screens. // @include https://deployer.*.cloudpipeline.digital/* // @include https://deployer.cloud.service.gov.uk/* // @version 1 // @grant none // ==/UserScript== var readyStateCheckInterval = setInterval(function() { if (document.readyState === "complete") { clearInterval(readyStateCheckInterval); console.log("Monitor mode is go"); var element = document.getElementsByClassName("legend")[0]; element.parentNode.removeChild(element); var element = document.getElementsByClassName("lower-right-info")[0]; element.parentNode.removeChild(element); var hostname = location.hostname.replace("deployer.", "").replace(".cloudpipeline.digital","") var element = document.getElementById("top-bar-app"); element.innerHTML = "&nbsp;<font size=5>" + hostname + "</font>"; } }, 10);
Update chrome plugin for concourse 2.1.0
Update chrome plugin for concourse 2.1.0 It was mostly working, but just left a dark bar across the top with the env name in it. This updates it to remove that bar as well to maintain consistency with the existing appearence.
JavaScript
mit
alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,jimconner/paas-cf,alphagov/paas-cf,jimconner/paas-cf,jimconner/paas-cf,jimconner/paas-cf,alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,alphagov/paas-cf,alphagov/paas-cf,jimconner/paas-cf,alphagov/paas-cf
e7004fd93bd36390c4d644f1ec0cd66e267ff61a
app/shared/current_user/currentUser.spec.js
app/shared/current_user/currentUser.spec.js
describe('current-user module', function() { var currentUser; beforeEach(module('current-user')); beforeEach(inject(function(_currentUser_) { currentUser = _currentUser_; })); describe('currentUser', function() { it("should be a resource", function() { expect(currentUser).toBeDefined(); }); it('should default as empty', function() { expect(currentUser.getCurrentUser()).toEqual({}); }); it('should update user with setter', function() { expect(currentUser.getCurrentUser()).toEqual({}); currentUser.setCurrentUser({ 'name': 'tester', }); expect(currentUser.getCurrentUser()).toEqual({ 'name': 'tester', }); }); }); });
describe('current-user module', function() { var currentUser; beforeEach(module('current-user')); beforeEach(inject(function(_currentUser_) { currentUser = _currentUser_; })); describe('currentUser', function() { it("should be a resource", function() { expect(currentUser).toBeDefined(); }); it('should default as empty', function() { expect(currentUser.getCurrentUser()).toEqual({}); }); it('should update user with setter', function() { expect(currentUser.getCurrentUser()).toEqual({}); currentUser.setCurrentUser({ 'name': 'tester', }); expect(currentUser.getCurrentUser()).toEqual({ 'name': 'tester', }); }); it('should delete user cache', function() { currentUser.setCurrentUser({ $id: 123, name: '123', }); expect(currentUser.getCurrentUser()).toEqual({ $id: 123, name: '123', }); currentUser.deleteCurrentUser(); expect(currentUser.getCurrentUser()).toEqual({}); }); it('should check if user logged in correctly', function() { currentUser.setCurrentUser({ $id: 123, name: '123', }); expect(currentUser.isLoggedIn()).toEqual(true); currentUser.deleteCurrentUser(); expect(currentUser.isLoggedIn()).toEqual(false); }); }); });
Update currentUser module test cases
Update currentUser module test cases
JavaScript
mit
christse02/project,christse02/project
2013acb3bdc6905b26a52c060309ba2605ad50f4
jujugui/static/gui/src/app/components/spinner/spinner.js
jujugui/static/gui/src/app/components/spinner/spinner.js
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; const Spinner = React.createClass({ displayName: 'Spinner', render: function() { return ( <div className="spinner-container"> <div className="spinner-loading">Loading...</div> </div> ); } }); YUI.add('loading-spinner', function() { juju.components.Spinner = Spinner; }, '0.1.0', { requires: [] });
/* This file is part of the Juju GUI, which lets users view and manage Juju environments within a graphical interface (https://launchpad.net/juju-gui). Copyright (C) 2015 Canonical Ltd. This program is free software: you can redistribute it and/or modify it under the terms of the GNU Affero General Public License version 3, as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranties of MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more details. You should have received a copy of the GNU Affero General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. */ 'use strict'; class Spinner extends React.Component { render() { return ( <div className="spinner-container"> <div className="spinner-loading">Loading...</div> </div> ); } }; YUI.add('loading-spinner', function() { juju.components.Spinner = Spinner; }, '0.1.0', { requires: [] });
Update Spinner to use es6 class.
Update Spinner to use es6 class.
JavaScript
agpl-3.0
mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui,mitechie/juju-gui
62f3a153dd791bcd8ff30b54aaa2b7c0d8254156
src/utils/math.js
src/utils/math.js
/** * Creates a new 2 dimensional Vector. * * @constructor * @this {Circle} * @param {number} x The x value of the new vector. * @param {number} y The y value of the new vector. */ function Vector2(x, y) { if (typeof x === 'undefined') { x = 0; } if (typeof y === 'undefined') { y = 0; } this.x = x; this.y = y; } Vector2.prototype.add = function(v) { if ( !(v instanceof Vector2) ) { throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v); } this.x += v.x; this.y += v.y; } Vector2.prototype.toString = function() { return "[" + this.x + ", " + this.y + "]"; }
/** * Creates a new 2 dimensional Vector. * * @constructor * @this {Circle} * @param {number} x The x value of the new vector. * @param {number} y The y value of the new vector. */ function Vector2(x, y) { if (typeof x === 'undefined') { x = 0; } if (typeof y === 'undefined') { y = 0; } this.x = x; this.y = y; } Vector2.prototype.add = function(v) { if ( !(v instanceof Vector2) ) { throw new InvalidArgumentError("v", "You can only add a vector to another vector! The object passed was: " + v); } this.x += v.x; this.y += v.y; return this; } Vector2.prototype.toString = function() { return "[" + this.x + ", " + this.y + "]"; }
Change add to return the vector itself, for method chaining
Change add to return the vector itself, for method chaining
JavaScript
mit
zedutchgandalf/OpenJGL,zedutchgandalf/OpenJGL
e067299612793593a85694901339bcbd78e4d417
themes/hive-learning-networks/js/ui.js
themes/hive-learning-networks/js/ui.js
$("#hive-intro-menu .hive-list li").click(function(event) { var placeName = $(this).find(".the-place").text(); var twitterHandle = $(this).find(".the-details .twitter-handle").text(); var websiteURL = $(this).find(".the-details .website-url").text(); // show content $("#hive-intro-box h2").html(placeName); if ( twitterHandle ) { $("#hive-intro-box .twitter") .attr("href", "http://twitter.com/" + twitterHandle) .text(twitterHandle) .removeClass("hide"); } $("#hive-intro-box .hive-btn") .attr("href", websiteURL) .text("Visit Website"); // hide the general info $("#hive-intro-box .general-cta").hide(); }); /* **************************************** * "Locations" Page */ $("#locations-menu div:not(#hive-coming-menu) a").click(function(){ var locationSelected = $(this).data("profile"); console.log( locationSelected ); // highlight selected item $("#locations-menu li.active").removeClass("active"); $(this).parent("li").addClass("active"); // show corresponding sections, hide the rest $(".hive-profile").parent(".container").addClass("hide"); // profile section of the selected item var profile = $(".hive-profile[data-profile="+ locationSelected +"]").parent(".container"); profile.removeClass("hide"); $("html, body").animate({ scrollTop: profile.offset().top }, "slow"); });
$("#hive-intro-menu .hive-list li").click(function(event) { var placeName = $(this).find(".the-place").text(); var twitterHandle = $(this).find(".the-details .twitter-handle").text(); var websiteURL = $(this).find(".the-details .website-url").text(); // show content $("#hive-intro-box h2").html(placeName); if ( twitterHandle ) { $("#hive-intro-box .twitter") .attr("href", "http://twitter.com/" + twitterHandle) .text(twitterHandle) .removeClass("hide"); } else { $("#hive-intro-box .twitter").addClass("hide"); } $("#hive-intro-box .hive-btn") .attr("href", websiteURL) .text("Visit Website"); // hide the general info $("#hive-intro-box .general-cta").hide(); }); /* **************************************** * "Locations" Page */ $("#locations-menu div:not(#hive-coming-menu) a").click(function(){ var locationSelected = $(this).data("profile"); console.log( locationSelected ); // highlight selected item $("#locations-menu li.active").removeClass("active"); $(this).parent("li").addClass("active"); // show corresponding sections, hide the rest $(".hive-profile").parent(".container").addClass("hide"); // profile section of the selected item var profile = $(".hive-profile[data-profile="+ locationSelected +"]").parent(".container"); profile.removeClass("hide"); $("html, body").animate({ scrollTop: profile.offset().top }, "slow"); });
Hide twitter field if value is empty
Hide twitter field if value is empty
JavaScript
mpl-2.0
mmmavis/hivelearningnetworks.org,mmmavis/hivelearningnetworks.org,mozilla/hivelearningnetworks.org,mmmavis/hivelearningnetworks.org,mozilla/hivelearningnetworks.org
8c6d9d92092b13a86b6cec85be8141757e2da8a4
site/src/electron/ElectronInterface.js
site/src/electron/ElectronInterface.js
class ElectronInterface extends SiteInterface { constructor() { super(); } }
class ElectronInterface extends SiteInterface { constructor() { super(); this.style = new Style(ElectronInterface.STYLE_PATH); } } ElectronInterface.STYLE_PATH = "../interface/SiteInterface/siteInterface.css";
Add style to Electron Interface
Add style to Electron Interface
JavaScript
mit
ukahoot/ukahoot,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot.github.io,ukahoot/ukahoot,ukahoot/ukahoot,ukahoot/ukahoot