commit
stringlengths
40
40
old_file
stringlengths
4
264
new_file
stringlengths
4
264
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
624
message
stringlengths
15
4.7k
lang
stringclasses
3 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
ddb79a63bd6bfd489758db9cb940b4cb9656a754
routes/useCases.js
routes/useCases.js
var app = require('../load'), useCases = app.useCases, h = require('../configHelpers'); exports.index = function(req, res){ res.json(app.useCases); }; exports.create = function(req, res){ h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); app.useCases.push(req.body); res.json(app.useCases); };
var app = require('../load'), useCases = app.useCases, h = require('../configHelpers'); exports.index = function(req, res){ res.json(app.useCases); }; exports.create = function(req, res){ // TODO: do this check in ember, before hitting the route if (h.loadConfigWithPathConverted(app.config().configPath, req.body.name + '.json')) { res.send(409, 'Conflict: Use Case Already Exists'); } else { h.overwriteConfigWithPath(req.body, app.config().configPath, req.body.name + '.json'); app.useCases.push(req.body); res.json(app.useCases); } };
Return 409 if creating a use case that already exists
Return 409 if creating a use case that already exists
JavaScript
mit
Webkite-Themes/iago
ea0293471dcee31b21b9b3ae5b91276ba95e6aed
src/js/chat.js
src/js/chat.js
/** * Chat Component * $("#chat").chat({ * ruleGroupName: "", * style: ["block"], * template: [1], * environment: "1"|"2"|"3" * }); */ ui.chat = function(conf) { var that = ui.object(); // Inheritance var getDomain = function(n) { switch (n) { case "1": return "mercadolidesa.com.ar"; break; case "2": return "mercadolistage.com.ar"; break; case "3": return "mercadolibre.com.ar"; break; } } if (conf.msg) { conf.ruleGroupName = conf.msg; } that.load = function() { loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3"); } ui.get({ method: "component", name: "chat", script: "http://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", callback: function() { that.load(); } }); that.publish = { uid: conf.uid, element: conf.element, type: conf.type } return that.publish; }
/** * Chat Component * $("#chat").chat({ * ruleGroupName: "", * style: ["block"], * template: [1], * environment: "1"|"2"|"3" * }); */ ui.chat = function(conf) { var that = ui.object(); // Inheritance var getDomain = function(n) { switch (n) { case "1": return "mercadolidesa.com.ar"; break; case "2": return "mercadolistage.com.ar"; break; case "3": return "mercadolibre.com.ar"; break; } } if (conf.msg) { conf.ruleGroupName = conf.msg; } that.load = function() { loadChatGZ(conf.ruleGroupName, conf.element.id, conf.style||"block", conf.template||"1",conf.environment||"3"); } ui.get({ method: "component", name: "chat", script: "https://www."+getDomain(conf.environment)+"/org-img/jsapi/chat/chatRBIScript.js", callback: function() { that.load(); } }); that.publish = { uid: conf.uid, element: conf.element, type: conf.type } return that.publish; }
Change https protocol for Chat component
Change https protocol for Chat component
JavaScript
mit
mercadolibre/chico,atma/chico,vrleonel/chico,atma/chico,vrleonel/ml-test,amireynoso/uxtest,amireynoso/uxtest,vrleonel/chico,vrleonel/ml-test,mercadolibre/chico
6aa9a30b0238a58980897ee83972514400ea2a5c
lib/handlebars.js
lib/handlebars.js
var Handlebars = require("handlebars/base"); module.exports = Handlebars; require("handlebars/utils"); require("handlebars/ast"); require("handlebars/printer"); require("handlebars/visitor"); require("handlebars/compiler"); // BEGIN(BROWSER) // END(BROWSER)
var Handlebars = require("handlebars/base"); module.exports = Handlebars; require("handlebars/utils"); require("handlebars/ast"); require("handlebars/printer"); require("handlebars/visitor"); require("handlebars/compiler/compiler"); require("handlebars/vm"); // BEGIN(BROWSER) // END(BROWSER)
Update node loader for compiler/vm split
Update node loader for compiler/vm split
JavaScript
mit
xiaobai93yue/handlebars.js,shakyShane/hb-fork,xiaobai93yue/handlebars.js,gautamkrishnar/handlebars.js,shakyShane/hb-fork,denniskuczynski/handlebars.js,cgvarela/handlebars.js,code0100fun/handlebars.js,mosoft521/handlebars.js,samokspv/handlebars.js,liudianpeng/handlebars.js,mubassirhayat/handlebars.js,halhenke/handlebars.js,mosoft521/handlebars.js,ThiagoGarciaAlves/handlebars.js,nikolas/handlebars.js,0xack13/handlebars.js,hafeez-syed/handlebars.js,hafeez-syed/handlebars.js,ThiagoGarciaAlves/handlebars.js,palindr0me/handlebars.js,palindr0me/handlebars.js,thechampanurag/handlebars.js,kamalbhatia/handlebars.js,eGood/handlebars,airportyh/ember-handlebars,kingsj/handlebars.js,ThiagoGarciaAlves/handlebars.js,wjb12/handlebars.js,vantage777/handlebars.js,airportyh/ember-handlebars,denniskuczynski/handlebars.js,280455936/handlebars.js,thechampanurag/handlebars.js,chiefninew/handlebars.js,jacqt/handlebars.js,code0100fun/handlebars.js,cgvarela/handlebars.js,ftdebugger/handlebars.js,wycats/handlebars.js,mosoft521/handlebars.js,wycats/handlebars.js,nazhenhuiyi/handlebars.js,machty/handlebars.js,jbboehr/handlebars.js,ianmstew/handlebars.js,handlebars-lang/handlebars.js,xiaobai93yue/handlebars.js,MaxIndu/handlebars.js,mosoft521/handlebars.js,jacqt/handlebars.js,chiefninew/handlebars.js,kuailingmin/handlebars.js,eGood/handlebars,michaellopez/handlebars.js,wycats/handlebars.js,vantage777/handlebars.js,chiefninew/handlebars.js,mubassirhayat/handlebars.js,hafeez-syed/handlebars.js,fpauser/handlebars.js,cgvarela/handlebars.js,ianmstew/handlebars.js,MaxIndu/handlebars.js,nazhenhuiyi/handlebars.js,haveal/handlebars.js,vantage777/handlebars.js,kamalbhatia/handlebars.js,nikolas/handlebars.js,wycats/handlebars.js,kingsj/handlebars.js,ftdebugger/handlebars.js,margaritis/handlebars.js,wjb12/handlebars.js,haveal/handlebars.js,leandono/handlebars.js,kingsj/handlebars.js,leandono/handlebars.js,mosoft521/handlebars.js,code0100fun/handlebars.js,michaellopez/handlebars.js,0xack13/handlebars.js,thechampanurag/handlebars.js,fpauser/handlebars.js,machty/handlebars.js,haveal/handlebars.js,MaxIndu/handlebars.js,ianmstew/handlebars.js,kuailingmin/handlebars.js,flenter/handlebars.js,margaritis/handlebars.js,jacqt/handlebars.js,280455936/handlebars.js,wycats/handlebars.js,handlebars-lang/handlebars.js,handlebars-lang/handlebars.js,0xack13/handlebars.js,liudianpeng/handlebars.js,halhenke/handlebars.js,samokspv/handlebars.js,wjb12/handlebars.js,michaellopez/handlebars.js,ftdebugger/handlebars.js,airportyh/ember-handlebars,gautamkrishnar/handlebars.js,mubassirhayat/handlebars.js,meteor/handlebars.js,kamalbhatia/handlebars.js,handlebars-lang/handlebars.js,nazhenhuiyi/handlebars.js,jbboehr/handlebars.js,gautamkrishnar/handlebars.js,meteor/handlebars.js,jbboehr/handlebars.js,nikolas/handlebars.js,flenter/handlebars.js,handlebars-lang/handlebars.js,flenter/handlebars.js,halhenke/handlebars.js,liudianpeng/handlebars.js,palindr0me/handlebars.js,samokspv/handlebars.js,280455936/handlebars.js
1ef81c6657121d4aeabfbf6b27b9df63b739e6db
src/App.js
src/App.js
import React, { Component } from 'react'; import "./css/App.css"; import logo from "../public/logo.svg"; import Markdown from "./Markdown"; import TocHeader from "./TocHeader"; class App extends Component { render() { return ( <div> <div className="header"> <img className="logo" src={logo} alt="Logo"/> <div className="logo-text">FredBoat</div> </div> <div className="page-body"> <div className="table-of-contents"> <div className="toc-title"> Contents </div> <TocHeader activePage={this.props.page} page="index" name="Quickstart"/> <TocHeader activePage={this.props.page} page="faq" name="FAQ"/> <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> <TocHeader activePage={this.props.page} page="selfhosting" name="Selfhosting"/> <TocHeader activePage={this.props.page} page="systemdservice" name="Selfhosting (systemd)"/> </div> <Markdown name={this.props.page}/> </div> </div> ) } } export default App;
import React, { Component } from 'react'; import "./css/App.css"; import logo from "../public/logo.svg"; import Markdown from "./Markdown"; import TocHeader from "./TocHeader"; class App extends Component { render() { return ( <div> <div className="header"> <img className="logo" src={logo} alt="Logo"/> <div className="logo-text">FredBoat</div> </div> <div className="page-body"> <div className="table-of-contents"> <div className="toc-title"> Contents </div> <TocHeader activePage={this.props.page} page="index" name="Quickstart"/> <TocHeader activePage={this.props.page} page="faq" name="FAQ"/> <TocHeader activePage={this.props.page} page="selfhosting" name="Selfhosting"/> <TocHeader activePage={this.props.page} page="systemdservice" name="Selfhosting (systemd)"/> <TocHeader activePage={this.props.page} page="terms" name="Terms of Service"/> </div> <Markdown name={this.props.page}/> </div> </div> ) } } export default App;
Move ToS to the bottom
Move ToS to the bottom
JavaScript
mit
FredBoat/docs.fredboat.com,FredBoat/fredboat.com,FredBoat/docs.fredboat.com,FredBoat/fredboat.com
e1d9d0e9f784df298df41967cfba947fa65c2698
commands/access/remove.js
commands/access/remove.js
'use strict'; var Heroku = require('heroku-client'); var co = require('co'); var heroku; module.exports = { topic: 'access', needsAuth: true, needsApp: true, command: 'remove', description: 'Remove users from your app', help: 'heroku access:remove [email protected] --app APP', args: [{name: 'user', optional: false}], run: function (context) { let appName; appName = context.app; co(function* () { heroku = new Heroku({token: context.auth.password}); yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) { if (err) { throw err; } console.log(`Removing ${context.args.user} from application ${cli.color.cyan(appName)}...done`); }); }).catch(function (err) { console.error(err); }); } };
'use strict'; var Heroku = require('heroku-client'); var co = require('co'); var heroku; module.exports = { topic: 'access', needsAuth: true, needsApp: true, command: 'remove', description: 'Remove users from your app', help: 'heroku access:remove [email protected] --app APP', args: [{name: 'user', optional: false}], run: function (context) { let appName; appName = context.app; co(function* () { heroku = new Heroku({token: context.auth.password}); yield heroku.apps(appName).collaborators(context.args.user).delete(function (err) { if (err) { throw err; } console.log(`Removing ${context.args.user} from application appName...done`); }); }).catch(function (err) { console.error(err); }); } };
Remove is not ready yet
Remove is not ready yet
JavaScript
isc
heroku/heroku-access,heroku/heroku-orgs
8ca011e17298196dba123b83b02a72e010020291
app/documents/services/SearchService.js
app/documents/services/SearchService.js
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if (documents.length == 0) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
module.exports = function($http, $state, $location, $q, DocumentApiService, DocumentRouteService, DocumentService, GlobalService, UserService, MathJaxService) { console.log('SEARCH SERVICE') var deferred = $q.defer(); var apiServer = GlobalService.apiServer() this.query = function(searchText, scope, destination='documents') { if (UserService.accessTokenValid() == false) { searchText += '&public' } return $http.get('http://' + apiServer + '/v1/documents' + '?' + searchText ) .then(function(response){ var jsonData = response.data var documents = jsonData['documents'] if ((documents == undefined) || (documents.length == 0)) { documents = [GlobalService.defaultDocumentID()] } DocumentService.setDocumentList(documents) var id = documents[0]['id'] DocumentApiService.getDocument(id) DocumentApiService.getDocument(id).then(function(response) { $state.go('documents', {}, {reload: true}) }) }) } }
Handle case of undefined document list as result of search
Handle case of undefined document list as result of search
JavaScript
mit
jxxcarlson/ns_angular,jxxcarlson/ns_angular
8ffc8c6ca7b831278db6e0891409c58ea1fd3daa
app/instance-initializers/ember-a11y.js
app/instance-initializers/ember-a11y.js
// This initializer exists only to make sure that the following // imports happen before the app boots. import { registerKeywords } from 'ember-a11y/ember-internals'; registerKeywords(); import Ember from 'ember'; export function initialize(application) { let startRouting = application.startRouting; application.startRouting = function() { console.log('here'); startRouting.call(application); } } export default { name: 'ember-a11y', initialize };
// This initializer exists only to make sure that the following // imports happen before the app boots. import Ember from 'ember'; import { registerKeywords } from 'ember-a11y/ember-internals'; registerKeywords(); let handlerInfos; Ember.Router.reopen({ didTransition(handlerInfos) { this._super(...arguments); } }); export function initialize(application) {} export default { name: 'ember-a11y', initialize };
Stop monkeypatching all the things. Monkeypatch the right things.
Stop monkeypatching all the things. Monkeypatch the right things.
JavaScript
mit
ember-a11y/ember-a11y,nathanhammond/ember-a11y,ember-a11y/ember-a11y,nathanhammond/ember-a11y
3158eb1bbd06d8a7fb8bc9c60e9fed423f3971a4
src/DrawingManager.js
src/DrawingManager.js
var p; var drawings = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { console.log('Added ' + drawing); drawings.unshift(drawing); } DrawingManager.prototype.drawAll = function () { for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
var p; var drawings = []; var lowerLayer = []; var DrawingManager = function (p5Sketch) { p = p5Sketch; }; DrawingManager.prototype.add = function (drawing) { if (drawing.pulse.layer) { lowerLayer.unshift(drawing); } else { console.log('Added ' + drawing); drawings.unshift(drawing); } } DrawingManager.prototype.drawAll = function () { for (var i = lowerLayer.length - 1; i >= 0; i--) { lowerLayer[i].draw(p); if (lowerLayer[i].done()) { lowerLayer.splice(i, 1); } }; for (var i = drawings.length - 1; i >= 0; i--) { drawings[i].draw(p); if (drawings[i].done()) { drawings.splice(i, 1); } }; } DrawingManager.prototype.update = function (pulse, config) { for (var i = drawings.length - 1; i >= 0; i--) { if (drawings[i].pulse.name === pulse.name) { drawings[i].update(p, pulse, config); console.log("UPDATED pulse", drawings[i].pulse.name); } } } DrawingManager.prototype.clear = function () { drawings = []; } module.exports = DrawingManager;
Add a lower layer to the drawing manager
Add a lower layer to the drawing manager
JavaScript
mit
Dermah/pulsar,Dermah/pulsar
ba54cae1371b15fda7037d930c9353ace6e3c342
lib/plugin/pluginRegistry.js
lib/plugin/pluginRegistry.js
"use strict"; const Registry = require('../util/registry'); /** * TODO: Could this be replaced with an InitRegistry? * @class * @memberOf Defiant.Plugin * @extends Defiant.util.Registry */ class PluginRegistry extends Registry { /** * @function * @param {Defiant.Plugin} obj The plugin to add to the registry. * @param {Defiant.Engine} engine The app engine. * @returns {Defiant.Plugin.PluginRegistry} The plugin registry. */ set(obj, engine) { // Initialize the plugin. return super.set(new obj(engine)); } } module.exports = PluginRegistry;
"use strict"; const Registry = require('../util/registry'); /** * TODO: Could this be replaced with an InitRegistry? * @class * @memberOf Defiant.Plugin * @extends Defiant.util.Registry */ class PluginRegistry extends Registry { /** * @function * @param {Defiant.Plugin} obj * The plugin to add to the registry. * @param {Defiant.Engine} engine * The app engine. * @returns {Defiant.Plugin.PluginRegistry} * The plugin registry. */ set(obj, engine) { // Initialize the plugin. return super.set(new obj(engine)); } } module.exports = PluginRegistry;
Standardize Jsdoc style for Defiant.Plugin.PluginRegistry
Doc: Standardize Jsdoc style for Defiant.Plugin.PluginRegistry
JavaScript
mit
coreyp1/defiant,coreyp1/defiant
099f3ab0f5271e6369eb1b45deade038427922dc
service/metrics.js
service/metrics.js
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearTimeout(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
var Graphite = require('graphite'); var Measured = require('measured'); var reportInterval = 5000; var graphiteHost = process.env.GRAPHITE_HOST || null; var graphitePort = process.env.GRAPHITE_PORT || 2003; var envName = process.env.NODE_ENV || "unknown"; var processIdentifier = 'pid-' + process.pid; var timer = null; var graphite = null; var data = Measured.createCollection('origami.polyfill.' + envName + '.' + processIdentifier); if (graphiteHost) { graphite = Graphite.createClient('plaintext://'+graphiteHost+':'+graphitePort); timer = setInterval(function() { graphite.write(data.toJSON(), function(err) { if (err) { // Ignore timeouts if (err.code === 'ETIMEDOUT') return; console.error(err, err.stack); console.warn('Disabling graphite reporting due to error'); clearInterval(timer); } }); }, reportInterval); timer.unref(); } module.exports = data;
Fix segfault caused by using incorrect clear method
Fix segfault caused by using incorrect clear method
JavaScript
mit
jonathan-fielding/polyfill-service,mcshaz/polyfill-service,jonathan-fielding/polyfill-service,kdzwinel/polyfill-service,mcshaz/polyfill-service,kdzwinel/polyfill-service,JakeChampion/polyfill-service,JakeChampion/polyfill-service,jonathan-fielding/polyfill-service,mcshaz/polyfill-service,kdzwinel/polyfill-service
6a0aaf2fa2bd52aa77b01a463edf7c8347ae61a9
msisdn-gateway/utils.js
msisdn-gateway/utils.js
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; /** * Returns a random integer between min and max */ function getRandomInt(min, max) { return Math.floor(Math.random() * (max - min + 1)) + min; } /** * Build a digits code */ function digitsCode(size) { var s = size; var code = ""; while (s > 0) { s--; code += getRandomInt(0, 9); } return code; } module.exports = { digitsCode: digitsCode };
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ "use strict"; var crypto = require("crypto"); /** * Build a digits code */ function digitsCode(size) { var nbBytes = Math.ceil(size/2); return parseInt(crypto.randomBytes(nbBytes).toString("hex"), 16) .toString().substr(0, size); } module.exports = { digitsCode: digitsCode };
Refactor digitCode to use /dev/urandom instead of Math.random. r=Tarek
Refactor digitCode to use /dev/urandom instead of Math.random. r=Tarek
JavaScript
mpl-2.0
mozilla-services/msisdn-gateway,mozilla-services/msisdn-gateway,mozilla-services/msisdn-gateway
1ab4424effd5f5ca1362e042d26d06911993511f
packages/landing-scripts/scripts/init.js
packages/landing-scripts/scripts/init.js
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
const fs = require('fs-extra'); const path = require('path'); const chalk = require('chalk'); function copyTemplate(appDir, templatePath) { fs.copySync(templatePath, appDir); fs.removeSync('.gitignore'); fs.moveSync( path.join(appDir, 'gitignore'), path.join(appDir, '.gitignore'), ); } function addPackageScripts(appDir) { const scripts = { start: 'landing-scripts start', build: 'landing-scripts build', }; const packageJson = require(`${appDir}/package.json`); packageJson.scripts = scripts; fs.writeFileSync( path.join(appDir, 'package.json'), JSON.stringify(packageJson, null, 2), ); } function init(appDir, appName, templatePath) { const isUsingYarn = fs.existsSync(path.join(appDir, 'yarn.lock')); const command = isUsingYarn ? 'yarn' : 'npm'; copyTemplate(appDir, templatePath); addPackageScripts(appDir); console.log(chalk.green('Project ready!')); console.log(); console.log('To start the project typing:'); console.log(); console.log(chalk.cyan('cd'), appName); console.log(chalk.cyan(command), 'start'); } module.exports = init;
Remove .gitignore on bootstrap the project
Remove .gitignore on bootstrap the project
JavaScript
mit
kevindantas/create-landing-page,kevindantas/create-landing-page,kevindantas/create-landing-page
d4c964e13fa20ff609d3b9c0b7d16d5d884cd8cc
database/recall.js
database/recall.js
'use strict'; module.exports = function (mongoose) { var recallSchema = mongoose.Schema({ Year: Number, Make: String, Model: String, Manufacturer: String, Component: String, Summary: String, Consequence: String, Remedy: String, Notes: String, NHTSACampaignNumber: String, ReportReceivedDate: String }); mongoose.model('Recall', recallSchema); };
'use strict'; module.exports = function (mongoose) { var recallSchema = mongoose.Schema({ Year: { type: Number, index: true }, Make: { type: String, index: true }, Model: { type: String, index: true }, Manufacturer: String, Component: String, Summary: String, Consequence: String, Remedy: String, Notes: String, NHTSACampaignNumber: String, ReportReceivedDate: String }); recallSchema.set('autoIndex', false); recallSchema.index({ Year: 1, Make: 1, Model: 1 }); mongoose.model('Recall', recallSchema); };
Add indexes to Recall schema
Add indexes to Recall schema * Sorting the data and attempting to access tail results would result in a buffer overrun error. Indexes were missing from the schema and have now been added.
JavaScript
mit
justinsa/maine-coone,justinsa/maine-coone
8ab0eab5c760dc26536e561e7f589709ef2160d1
library/CM/FormField/Text.js
library/CM/FormField/Text.js
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, enableTriggerChange: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; if (!self._skipTriggerChange) { self.trigger('change'); } } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
/** * @class CM_FormField_Text * @extends CM_FormField_Abstract */ var CM_FormField_Text = CM_FormField_Abstract.extend({ _class: 'CM_FormField_Text', /** @type Boolean */ _skipTriggerChange: false, events: { 'blur input, textarea': function() { this.trigger('blur'); }, 'focus input, textarea': function() { this.trigger('focus'); }, 'change input, textarea': function() { this.triggerChange(); } }, /** * @param {String} value */ setValue: function(value) { this._skipTriggerChange = true; this.$('input, textarea').val(value); this._skipTriggerChange = false; }, /** * @return {Boolean} */ hasFocus: function() { return this.getInput().is(':focus'); }, triggerChange: function() { if (this._skipTriggerChange) { return; } this.trigger('change'); }, enableTriggerChangeOnInput: function() { var self = this; var $input = this.getInput(); var valueLast = $input.val(); var callback = function() { var value = this.value; if (value != valueLast) { valueLast = value; this.triggerChange(); } }; // `propertychange` and `keyup` needed for IE9 $input.on('input propertychange keyup', callback); } });
Introduce triggerChange, use it on input/textarea change
Introduce triggerChange, use it on input/textarea change
JavaScript
mit
njam/CM,fauvel/CM,zazabe/cm,fvovan/CM,tomaszdurka/CM,fauvel/CM,cargomedia/CM,vogdb/cm,tomaszdurka/CM,tomaszdurka/CM,vogdb/cm,mariansollmann/CM,cargomedia/CM,alexispeter/CM,alexispeter/CM,tomaszdurka/CM,mariansollmann/CM,vogdb/cm,cargomedia/CM,vogdb/cm,fauvel/CM,njam/CM,cargomedia/CM,alexispeter/CM,mariansollmann/CM,tomaszdurka/CM,alexispeter/CM,njam/CM,vogdb/cm,fvovan/CM,zazabe/cm,zazabe/cm,njam/CM,fvovan/CM,mariansollmann/CM,njam/CM,fauvel/CM,fauvel/CM,fvovan/CM,zazabe/cm
7fb65123e15dbbcfd236d6a5bc4a5b51da19bb29
functions/chatwork/src/index.js
functions/chatwork/src/index.js
import template from './builder.js'; import kms from './kms.js'; import cw from './post.js'; import auth from './auth.js'; exports.handler = (event, context, callback) => { console.log('Received event:', JSON.stringify(event, null, 2)); // Encrypted Chatwork token const encCwtoken = process.env.CHATWORK_API_TOKEN || ''; // Chatwork Room ID from queryString const roomId = event.pathParameters.room_id || ''; // Payload from GitHub const payload = event.requestParameters; // GitHub Event Name const eventName = event.headers['X-GitHub-Event'] || event.headers['x-github-event'] || ''; // Original API token const token = event.queryParameters.token || ''; // API token key const tokenKey = process.env.API_TOKEN || ''; auth.verify(token, tokenKey).then(() => Promise.all([ kms.decrypt(encCwtoken), new Promise((resolve, reject) => { if (roomId != '') { resolve(roomId); } else { reject('roomId is blank.'); } }), template.build(eventName, payload), ])) .then(payload => cw.message( payload[0], // Raw Chatwork token payload[1], // Chatwork Room ID payload[2], // Chatwork message body )) .then((res) => { context.succeed(res); }) .catch((reason) => { console.log(reason); console.log('Not post to chatwork.'); context.fail(reason); }); };
import template from './builder'; import kms from './kms'; import cw from './post'; import auth from './auth'; exports.handler = (event, context, callback) => { console.log('Received event:', JSON.stringify(event, null, 2)); // Encrypted Chatwork token const encCwtoken = process.env.CHATWORK_API_TOKEN || ''; // Chatwork Room ID from queryString const roomId = event.pathParameters.room_id || ''; // Payload from GitHub const payload = event.requestParameters; // GitHub Event Name const eventName = event.headers['X-GitHub-Event'] || event.headers['x-github-event'] || ''; // Original API token const token = event.queryParameters.token || ''; // API token key const tokenKey = process.env.API_TOKEN || ''; auth.verify(token, tokenKey).then(() => Promise.all([ kms.decrypt(encCwtoken), new Promise((resolve, reject) => { if (roomId != '') { resolve(roomId); } else { reject('roomId is blank.'); } }), template.build(eventName, payload), ])) .then(payload => cw.message( payload[0], // Raw Chatwork token payload[1], // Chatwork Room ID payload[2], // Chatwork message body )) .then((res) => { context.succeed(res); }) .catch((reason) => { console.log(reason); console.log('Not post to chatwork.'); context.fail(reason); }); };
Remove file extension js from import
Remove file extension js from import
JavaScript
mit
Nate-River56/hub2chat,Nate-River56/hub2chat,Nate-River56/hub2chat
adc05976c2c7f97d46c214518d448b0b13e377d6
ui/app/utils/classes/rolling-array.js
ui/app/utils/classes/rolling-array.js
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Capture the originals of each array method, but // associate them with the array to prevent closures. array._push = array.push; array._splice = array.splice; array._unshift = array.unshift; // All mutable array methods build on top of insertAt array._insertAt = array.insertAt; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { this._push(...items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = this._splice(...args); this._limit(); return returnValue; }; array.insertAt = function(...args) { const returnValue = this._insertAt(...args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
// An array with a max length. // // When max length is surpassed, items are removed from // the front of the array. // Native array methods let { push, splice } = Array.prototype; // Ember array prototype extension let { insertAt } = Array.prototype; // Using Classes to extend Array is unsupported in Babel so this less // ideal approach is taken: https://babeljs.io/docs/en/caveats#classes export default function RollingArray(maxLength, ...items) { const array = new Array(...items); array.maxLength = maxLength; // Bring the length back down to maxLength by removing from the front array._limit = function() { const surplus = this.length - this.maxLength; if (surplus > 0) { this.splice(0, surplus); } }; array.push = function(...items) { push.apply(this, items); this._limit(); return this.length; }; array.splice = function(...args) { const returnValue = splice.apply(this, args); this._limit(); return returnValue; }; // All mutable array methods build on top of insertAt array.insertAt = function(...args) { const returnValue = insertAt.apply(this, args); this._limit(); this.arrayContentDidChange(); return returnValue; }; array.unshift = function() { throw new Error('Cannot unshift onto a RollingArray'); }; return array; }
Use the prototype instead of "private" property backups
Use the prototype instead of "private" property backups
JavaScript
mpl-2.0
dvusboy/nomad,dvusboy/nomad,hashicorp/nomad,hashicorp/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,nak3/nomad,burdandrei/nomad,burdandrei/nomad,nak3/nomad,dvusboy/nomad,dvusboy/nomad,nak3/nomad,hashicorp/nomad,dvusboy/nomad,burdandrei/nomad,nak3/nomad,nak3/nomad,burdandrei/nomad,hashicorp/nomad,nak3/nomad,burdandrei/nomad,hashicorp/nomad,nak3/nomad,dvusboy/nomad,burdandrei/nomad
ea95e486f37ad049ca2431ca10b3550c19ca222c
ui/src/admin/components/UsersTable.js
ui/src/admin/components/UsersTable.js
import React, {PropTypes} from 'react' const UsersTable = ({users}) => ( <div className="panel panel-minimal"> <div className="panel-body"> <table className="table v-center"> <thead> <tr> <th>User</th> <th>Roles</th> <th>Permissions</th> </tr> </thead> <tbody> { users.length ? users.map((user) => ( <tr key={user.name}> <td>{user.name}</td> <td>{user.roles.map((r) => r.name).join(', ')}</td> <td>{user.permissions.map((p) => p.scope).join(', ')}</td> </tr> )) : (() => ( <tr className="table-empty-state"> <th colSpan="5"> <p>You don&#39;t have any Users,<br/>why not create one?</p> </th> </tr> ))() } </tbody> </table> </div> </div> ) const { arrayOf, shape, string, } = PropTypes UsersTable.propTypes = { users: arrayOf(shape({ name: string.isRequired, roles: arrayOf(shape({ name: string, })), permissions: arrayOf(shape({ name: string, scope: string.isRequired, })), })), } export default UsersTable
import React, {PropTypes} from 'react' const UsersTable = ({users}) => ( <div className="panel panel-minimal"> <div className="panel-body"> <table className="table v-center"> <thead> <tr> <th>User</th> <th>Roles</th> <th>Permissions</th> </tr> </thead> <tbody> { users.length ? users.map((user) => ( <tr key={user.name}> <td>{user.name}</td> <td>{users.roles && user.roles.map((r) => r.name).join(', ')}</td> <td>{user.permissions.map((p) => p.scope).join(', ')}</td> </tr> )) : (() => ( <tr className="table-empty-state"> <th colSpan="5"> <p>You don&#39;t have any Users,<br/>why not create one?</p> </th> </tr> ))() } </tbody> </table> </div> </div> ) const { arrayOf, shape, string, } = PropTypes UsersTable.propTypes = { users: arrayOf(shape({ name: string.isRequired, roles: arrayOf(shape({ name: string, })), permissions: arrayOf(shape({ name: string, scope: string.isRequired, })), })), } export default UsersTable
Handle no roles on users table
Handle no roles on users table
JavaScript
mit
nooproblem/influxdb,nooproblem/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdata/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,mark-rushakoff/influxdb,influxdb/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,li-ang/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb
1ddb89ef8b4d2304a991e3a09e08693b8b84c5e8
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/number-cell.js
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/number-cell.js
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/formatter/number-formatter' ], function(_, Backgrid, NumberFormatter) { 'use strict'; var NumberCell; /** * Number column cell. * * @export oro/datagrid/cell/number-cell * @class oro.datagrid.cell.NumberCell * @extends Backgrid.NumberCell */ NumberCell = Backgrid.NumberCell.extend({ /** @property {orodatagrid.datagrid.formatter.NumberFormatter} */ formatterPrototype: NumberFormatter, /** @property {String} */ style: 'decimal', /** * @inheritDoc */ initialize: function(options) { _.extend(this, options); NumberCell.__super__.initialize.apply(this, arguments); this.formatter = this.createFormatter(); }, /** * Creates number cell formatter * * @return {orodatagrid.datagrid.formatter.NumberFormatter} */ createFormatter: function() { return new this.formatterPrototype({style: this.style}); } }); return NumberCell; });
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/formatter/number-formatter' ], function(_, Backgrid, NumberFormatter) { 'use strict'; var NumberCell; /** * Number column cell. * * @export oro/datagrid/cell/number-cell * @class oro.datagrid.cell.NumberCell * @extends Backgrid.NumberCell */ NumberCell = Backgrid.NumberCell.extend({ /** @property {orodatagrid.datagrid.formatter.NumberFormatter} */ formatterPrototype: NumberFormatter, /** @property {String} */ style: 'decimal', /** * @inheritDoc */ initialize: function(options) { _.extend(this, options); NumberCell.__super__.initialize.apply(this, arguments); this.formatter = this.createFormatter(); }, /** * Creates number cell formatter * * @return {orodatagrid.datagrid.formatter.NumberFormatter} */ createFormatter: function() { return new this.formatterPrototype({style: this.style}); }, /** * @inheritDoc */ render: function() { var render = NumberCell.__super__.render.apply(this, arguments); this.enterEditMode(); return render; }, /** * @inheritDoc */ enterEditMode: function() { if (this.column.get('editable')) { NumberCell.__super__.enterEditMode.apply(this, arguments); } }, /** * @inheritDoc */ exitEditMode: function() { if (!this.column.get('editable')) { NumberCell.__super__.exitEditMode.apply(this, arguments); } } }); return NumberCell; });
Add a grid to popup - added possibility to render number cell as an editable field
COM-212: Add a grid to popup - added possibility to render number cell as an editable field
JavaScript
mit
orocrm/platform,ramunasd/platform,ramunasd/platform,trustify/oroplatform,orocrm/platform,ramunasd/platform,Djamy/platform,trustify/oroplatform,geoffroycochard/platform,orocrm/platform,Djamy/platform,geoffroycochard/platform,geoffroycochard/platform,trustify/oroplatform,Djamy/platform
0dadb60ecd51ab01d4c804d5c741c795a6ca7b47
app/js/app.js
app/js/app.js
define(function (require) { 'use strict'; var store = require('store'); var items = new Vue({ el: 'body', data: { items: [], domains: store.fetch(), domain: '' }, ready: function () { var timer, that = this; this.$watch('domains', function (domains) { store.save(domains); }); this.$watch('domain', function (value) { that.items = []; for (var i = 0; i < that.domains.length && value; i++) { if (that.domains[i].name.indexOf(value) === 0) { that.items.push(that.domains[i]); } } }); }, methods: { onRemove: function (item) { this.domains.$remove(item.$data); this.domain = ''; }, onHandle: function (e) { var data, value = this.domain.trim(); if (e.keyCode === 13) { this.domains.push({ name: value, active: true }); this.domain = ''; } if (e.keyCode === 27) { this.domain = value = ''; } }, domainFilter: function (self) { return self.name.indexOf(this.domain) === 0; } } }); });
define(function (require) { 'use strict'; var store = require('store'); var items = new Vue({ el: 'body', data: { items: [], domains: store.fetch(), domain: '' }, ready: function () { var timer, that = this; this.$watch('domains', function (domains) { store.save(domains); }); this.$watch('domain', function (value) { that.items = []; for (var i = 0; i < that.domains.length && value; i++) { if (that.domains[i].name.indexOf(value) === 0) { that.items.push(that.domains[i]); } } }); }, methods: { onRemove: function (item) { this.domains.$remove(item.$data); this.domain = ''; }, onHandle: function (e) { var data, value = this.domain.trim(); function parse(input) { var regex = /((?:https?:\/\/)?(?:[^\.]*\.)*?)([^\.]*\.\w+)(\/.*)?$/; return input.replace(regex, function (match, p1, p2, p3) { p1 = p1 || ''; p2 = p2 || ''; p3 = p3 || ''; return p1 + p2.bold() + p3; }); } if (e.keyCode === 13) { this.domains.push({ name: value, active: true }); this.domain = ''; } else if (e.keyCode === 27) { this.domain = value = ''; } else { //this.domain = parse(value); } }, domainFilter: function (self) { return self.name.indexOf(this.domain) === 0; } } }); });
Add domain detect and show bold font of domain
Add domain detect and show bold font of domain
JavaScript
mit
Witcher42/PacManagerVue
1154dffa3aa8a714d183d9048fe9381dfdb0a28d
app/server.js
app/server.js
var jadeStream = require('jade-stream') var http = require('http') var st = require('st') var mount = st({ path: 'app/assets', index: 'index.jade' }) var app = http.createServer(function server(req, res) { if (req.url === '/') res.filter = jadeStream() mount(req, res) }) app.listen(process.env.port, function listening() { var info = app.address() console.log('App running on http://%s:%s', info.address, info.port) })
var jadeStream = require('jade-stream') var config = require('rc')('bc-webplayer'); var http = require('http') var st = require('st') var mount = st({ path: 'app/assets', index: 'index.jade', cache: config.cache }) var app = http.createServer(function server(req, res) { if (req.url === '/') res.filter = jadeStream() mount(req, res) }) app.listen(process.env.port, function listening() { var info = app.address() console.log('App running on http://%s:%s', info.address, info.port) })
Add project settings via rc
Add project settings via rc
JavaScript
mit
joshgillies/bc-webplayer
a33395797ecfc8dfbdad9cc6de5a41c2fd2783fc
webpack.config.js
webpack.config.js
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
const webpack = require("webpack"); const CopyWebpackPlugin = require("copy-webpack-plugin"); const { CleanWebpackPlugin } = require("clean-webpack-plugin"); const ZipPlugin = require("zip-webpack-plugin"); const path = require("path"); const package = require("./package"); const widgetName = package.name; const widgetNameContext = widgetName + "Context"; const widgetVersion = package.version; module.exports = { entry: { [widgetName]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetName}.js` ], [widgetNameContext]: [ "core-js/es/promise", `./src/${widgetName}/widget/${widgetNameContext}.js` ], }, output: { path: path.resolve(__dirname, "dist/tmp/src"), filename: `${widgetName}/widget/[name].js`, chunkFilename: `${widgetName}/widget/${widgetName}[id].js`, libraryTarget: "amd", publicPath: "/widgets/" }, devtool: false, mode: "production", externals: [ /^mxui\/|^mendix\/|^dojo\/|^dijit\// ], plugins: [ new webpack.LoaderOptionsPlugin({ debug: true }), new CleanWebpackPlugin({ cleanOnceBeforeBuildPatterns: "dist/tmp" }), new CopyWebpackPlugin([ {context: "src", from: "**/*.xml", debug: true} ], { copyUnmodified: true }), new ZipPlugin({ path: `../../${widgetVersion}`, filename: widgetName, extension: "mpk" }) ] };
Fix widgets path when using pages that have an ID (e.g. //host/p/Page)
Fix widgets path when using pages that have an ID (e.g. //host/p/Page)
JavaScript
apache-2.0
mendix/HTMLSnippet,mendix/HTMLSnippet,mendix/HTMLSnippet
4f48bc9b0c2f475639be917d08cd2583e670ed25
webpack.config.js
webpack.config.js
const webpack = require('webpack'); module.exports = { entry: './src/index.js', output: { filename: './dist/html2canvas.js', library: 'html2canvas' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }] }, plugins: [ new webpack.DefinePlugin({ '__DEV__': true }) ] };
const webpack = require('webpack'); module.exports = { entry: './src/index.js', output: { filename: './dist/html2canvas.js', library: 'html2canvas', libraryTarget: 'umd' }, module: { loaders: [{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader' }] }, plugins: [ new webpack.DefinePlugin({ '__DEV__': true }) ] };
Define browser build target as umd
Define browser build target as umd
JavaScript
mit
niklasvh/html2canvas,niklasvh/html2canvas,niklasvh/html2canvas
2a58db089a6cf0edc394fe8a036bb51f1a246f94
webpack.config.js
webpack.config.js
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./webapp/assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel', query: { presets:['react', 'es2015', 'stage-2'] } }, // to transform JSX into JS ], }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] }, watchOptions: { poll: 1000, aggregateTimeout: 1000 }, }
var path = require("path") var webpack = require('webpack') var BundleTracker = require('webpack-bundle-tracker') module.exports = { context: __dirname, entry: './webapp/assets/js/index', // entry point of our app. assets/js/index.js should require other js modules and dependencies it needs output: { path: path.resolve('./webapp/assets/bundles/'), filename: "[name]-[hash].js", }, plugins: [ new BundleTracker({filename: './webpack-stats.json'}), ], module: { loaders: [ { test: /\.jsx?$/, exclude: /node_modules/, loader: 'babel-loader', query: { presets:['react', 'es2015', 'stage-2'] } }, // to transform JSX into JS ], }, resolve: { modulesDirectories: ['node_modules', 'bower_components'], extensions: ['', '.js', '.jsx'] }, watchOptions: { poll: 1000, aggregateTimeout: 1000 }, }
Use babel loader instead of babel to production
Use babel loader instead of babel to production
JavaScript
mit
Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_platform,Semillas/semillas_backend,Semillas/semillas_backend,Semillas/semillas_platform
f73e07d291144ccc167491c8fbebb466f172e71c
webpack.config.js
webpack.config.js
const config = { entry: './src/index.js' }; module.exports = config;
const path = require('path'); // We can use whatever nodejs package const config = { entry: './src/index.js', output: { path: path.resolve(__dirname, 'build'), //./build filename: 'bundle.js' } }; module.exports = config;
Set name and path of the output file
Set name and path of the output file
JavaScript
mit
debiasej/webpack2-learning,debiasej/webpack2-learning
dcd07488f11a0ce089b396b95d880d704f43a985
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); var GameModel = require('../models/game'); var model = require('../models'); const _ = require('underscore'); /* GET home page. */ router.get('/', function(req, res, next) { let gameParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Guide, attributes: [ [model.sequelize.fn('COUNT', 'Guide.id'), 'Count'] ] } ], limit: 5 }; let guideParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Game, attributes: ['name', 'url'] }, { model: model.User, attributes: ['name'] } ], limit: 5 }; Promise .all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)]) .then(values => { let [games, guides] = values; console.info(guides[0]); games = games.map(g => { return _.extend({ guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 }, g.dataValues); }); res.render('home', { games: games, guides: guides }); }).catch(err => next(err)); }); router.get('/tag/:tag', function(req, res, next) { res.render('index', { title: 'tag' }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var GameModel = require('../models/game'); var model = require('../models'); const _ = require('underscore'); /* GET home page. */ router.get('/', function(req, res, next) { let gameParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Guide, attributes: [ [model.sequelize.fn('COUNT', 'Guide.id'), 'Count'] ] } ], limit: 5 }; let guideParam = { order: [ ['id', 'desc'] ], include: [ { model: model.Game, attributes: ['name', 'url'] }, { model: model.User, attributes: ['name'] } ], limit: 5 }; Promise .all([model.Game.findAll(gameParam), model.Guide.findAll(guideParam)]) .then(values => { let [games, guides] = values; games = games .filter(game => game.id) .map(g => { return _.extend({ guideCount: g.Guides.length > 0 ? g.Guides[0].dataValues.Count : 0 }, g.dataValues); }); res.render('home', { games: games, guides: guides }); }).catch(err => next(err)); }); router.get('/tag/:tag', function(req, res, next) { res.render('index', { title: 'tag' }); }); module.exports = router;
Fix home page. When there are no game, it still show a random entry.
Fix home page. When there are no game, it still show a random entry.
JavaScript
mit
JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node,JixunMoe/GameGuide.Node
8a370e11dc746ee9d354c21c80ab5fb70722326f
client/components/App.js
client/components/App.js
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import actions from '../actions/index.js'; import '../scss/app.scss'; import Nav from './Nav.js'; import Profile from './Profile.js'; import RecipeContainer from './RecipeContainer.js'; class App extends Component { render() { const { profile, recipesOwned, recipesFollowed } = this.props; return ( <div> <Nav /> <Profile profile={profile} /> <h1>Dashboard</h1> <RecipeContainer className="recipes-owned" type="My Owned Recipes" recipes={recipesOwned} /> <RecipeContainer className="recipes-followed" type="My Followed Recipes" recipes={recipesFollowed} /> </div> ); } } const mapStateToProps = function (state) { return { profile: state.profile, recipesOwned: state.recipesOwned, recipesFollowed: state.recipesFollowed, }; }; // const mapDispatchToProps = function (dispatch) { // return { // // fill in any actions here // }; // }; App.propTypes = { recipesOwned: PropTypes.array.isRequired, recipesFollowed: PropTypes.array.isRequired, profile: PropTypes.shape({ avatar: PropTypes.string, username: PropTypes.string, }).isRequired, }; export default connect( mapStateToProps // mapDispatchToProps, )(App);
import React, { PropTypes, Component } from 'react'; import { connect } from 'react-redux'; import actions from '../actions/index.js'; // import '../scss/app.scss'; import Nav from './Nav.js'; import Profile from './Profile.js'; import RecipeContainer from './RecipeContainer.js'; class App extends Component { render() { const { profile, recipesOwned, recipesFollowed } = this.props; return ( <div> <Nav /> <Profile profile={profile} /> <h1>Dashboard</h1> <RecipeContainer className="recipes-owned" type="My Owned Recipes" recipes={recipesOwned} /> <RecipeContainer className="recipes-followed" type="My Followed Recipes" recipes={recipesFollowed} /> </div> ); } } const mapStateToProps = function (state) { return { profile: state.profile, recipesOwned: state.recipesOwned, recipesFollowed: state.recipesFollowed, }; }; // const mapDispatchToProps = function (dispatch) { // return { // // fill in any actions here // }; // }; App.propTypes = { recipesOwned: PropTypes.array.isRequired, recipesFollowed: PropTypes.array.isRequired, profile: PropTypes.shape({ avatar: PropTypes.string, username: PropTypes.string, }).isRequired, }; export default connect( mapStateToProps // mapDispatchToProps, )(App);
Comment out reference to app.scss file
Comment out reference to app.scss file
JavaScript
mit
forkful/forkful,rompingstalactite/rompingstalactite,rompingstalactite/rompingstalactite,forkful/forkful,rompingstalactite/rompingstalactite,forkful/forkful
e95c90357117c63142d591190b1a74f323e5f108
routes/index.js
routes/index.js
var express = require('express'); var router = express.Router(); var moment = require('moment'); var languageColors = require('../language_colors'); // GET home page languageColors.get(function (languages, updated) { // HTML router.get('/', function(req, res) { res.render('index', { languages: languages, updated: moment(updated).fromNow() }); }); // JSON router.get('/index.json', function(req, res) { res.json(languages); }); }); module.exports = router;
var express = require('express'); var router = express.Router(); var moment = require('moment'); var languageColors = require('../language_colors'); // GET home page languageColors.get(function (languages, updated) { // HTML router.get('/', function(req, res) { res.render('index', { languages: languages, updated: moment(updated).fromNow() }); }); // JSON router.get('/index.json', function(req, res) { res.json({ languages: languages, updated: updated }); }); }); module.exports = router;
Update the API and add the updated time
Update the API and add the updated time
JavaScript
mit
nicolasmccurdy/language-colors,nicolasmccurdy/language-colors
29195eaefde2949134c608771ddfed3fa22677a5
routes/users.js
routes/users.js
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { // db.User.find({username: req.params.username}).then(function(user) { // res.render('users/show', {user}); // }); var user = req.params.username; res.render('users/show', {user}); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
const express = require('express'), router = express.Router(), db = require('../models'); router.get('/', function(req, res, next) { res.render('index'); }); router.get('/new', function(req, res, next) { res.render('users/new'); }); router.get('/:username', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/show', {user}); }); }); router.get('/:username/edit', function(req, res, next) { db.User.find({username: req.params.username}).then(function(user) { res.render('users/edit', {user}); }); }); router.post('/', function(req, res, next) { db.User.create(req.body).then(function() { res.redirect('/'); }); }); // find not by ID and update router.patch('/:username', function(req, res, next) { db.User.findByIdAndUpdate(req.params.username, req.body.newUsername).then(function() { res.redirect('/:username'); }); }); // find and then remove router.delete('/:username', function(req, res, next) { db.User.findByIdAndRemove(req.params.username).then(function() { res.redirect('/'); }); }); module.exports = router;
Use Mongoose to find user and pass to show page
Use Mongoose to find user and pass to show page
JavaScript
mit
tymeart/mojibox,tymeart/mojibox
77452232e9080665355f86082b28fae1a31ee8e4
src/directives/ng-viewport.js
src/directives/ng-viewport.js
ngGridDirectives.directive('ngViewport', [function() { return function($scope, elm) { var isMouseWheelActive; var prevScollLeft; var prevScollTop = 0; elm.bind('scroll', function(evt) { var scrollLeft = evt.target.scrollLeft, scrollTop = evt.target.scrollTop; if ($scope.$headerContainer) { $scope.$headerContainer.scrollLeft(scrollLeft); } $scope.adjustScrollLeft(scrollLeft); $scope.adjustScrollTop(scrollTop); if (!$scope.$root.$$phase) { $scope.$digest(); } prevScollLeft = scrollLeft; prevScollTop = scrollTop; isMouseWheelActive = false; return true; }); elm.bind("mousewheel DOMMouseScroll", function() { isMouseWheelActive = true; if (elm.focus) { elm.focus(); } return true; }); if (!$scope.enableCellSelection) { $scope.domAccessProvider.selectionHandlers($scope, elm); } }; }]);
ngGridDirectives.directive('ngViewport', [function() { return function($scope, elm) { var isMouseWheelActive; var prevScollLeft; var prevScollTop = 0; var ensureDigest = function() { if (!$scope.$root.$$phase) { $scope.$digest(); } }; elm.bind('scroll', function(evt) { var scrollLeft = evt.target.scrollLeft, scrollTop = evt.target.scrollTop; if ($scope.$headerContainer) { $scope.$headerContainer.scrollLeft(scrollLeft); } $scope.adjustScrollLeft(scrollLeft); $scope.adjustScrollTop(scrollTop); ensureDigest(); prevScollLeft = scrollLeft; prevScollTop = scrollTop; isMouseWheelActive = false; return true; }); elm.bind("mousewheel DOMMouseScroll", function() { isMouseWheelActive = true; if (elm.focus) { elm.focus(); } return true; }); if (!$scope.enableCellSelection) { $scope.domAccessProvider.selectionHandlers($scope, elm); } }; }]);
Refactor out function to call digest only when safe
Refactor out function to call digest only when safe
JavaScript
mit
FernCreek/ng-grid,ppossanzini/ui-grid,PeopleNet/ng-grid-fork,FugleMonkey/ng-grid,rightscale/ng-grid,rightscale/ng-grid,FernCreek/ng-grid,angular-ui/ng-grid-legacy,FernCreek/ng-grid,FugleMonkey/ng-grid,PeopleNet/ng-grid-fork,ppossanzini/ui-grid,FugleMonkey/ng-grid,angular-ui/ng-grid-legacy,angular-ui/ng-grid-legacy,ppossanzini/ui-grid
f2539fed876794f065fe096c3816f49103cb1766
src/MenuOptions.js
src/MenuOptions.js
import React from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: React.PropTypes.func, customStyles: React.PropTypes.object, renderOptionsContainer: React.PropTypes.func, optionsContainerStyle: React.PropTypes.oneOfType([ React.PropTypes.object, React.PropTypes.number, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
import React, { PropTypes } from 'react'; import { View } from 'react-native'; const MenuOptions = ({ style, children, onSelect, customStyles }) => ( <View style={[customStyles.optionsWrapper, style]}> { React.Children.map(children, c => React.isValidElement(c) ? React.cloneElement(c, { onSelect: c.props.onSelect || onSelect, customStyles: Object.keys(c.props.customStyles || {}).length ? c.props.customStyles : customStyles }) : c ) } </View> ); MenuOptions.propTypes = { onSelect: PropTypes.func, customStyles: PropTypes.object, renderOptionsContainer: PropTypes.func, optionsContainerStyle: PropTypes.oneOfType([ PropTypes.object, PropTypes.number, PropTypes.array, ]), }; MenuOptions.defaultProps = { customStyles: {}, }; export default MenuOptions;
Allow also array as style prop type
Allow also array as style prop type
JavaScript
isc
instea/react-native-popup-menu
46d8ccf455fa6455520d87b4ac397c9b976b8c78
edwin/client/static/js/components/TeamList.js
edwin/client/static/js/components/TeamList.js
import React from 'react'; import Router from 'react-router'; import ControllerComponent from '../utils/ControllerComponent'; import * as edwinAPI from '../utils/edwinAPI'; import TeamStore from '../stores/TeamStore'; const {Link} = Router; /** * Shows a list of teams. * @class */ export default class TeamList extends ControllerComponent { get stores() { return [TeamStore]; } getNewState() { return { teams: TeamStore.getAll(), }; } /** * On mounting, fetch data from APIs. */ componentDidMount() { super.componentDidMount(); edwinAPI.getTeams(); } render() { return ( <div className="Welcome"> <h1>Teams</h1> <ul> {this.state.teams.map((team) => ( <li key={`team-${team.slug}`}> <Link to="timeline" params={{team: team.get('slug')}}> {team.get('name')} </Link> </li> ))} </ul> </div> ); } }
import React from 'react'; import Router from 'react-router'; import ControllerComponent from '../utils/ControllerComponent'; import * as edwinAPI from '../utils/edwinAPI'; import TeamStore from '../stores/TeamStore'; const {Link} = Router; /** * Shows a list of teams. * @class */ export default class TeamList extends ControllerComponent { get stores() { return [TeamStore]; } getNewState() { return { teams: TeamStore.getAll(), }; } /** * On mounting, fetch data from APIs. */ componentDidMount() { super.componentDidMount(); edwinAPI.getTeams(); } render() { return ( <div className="Welcome"> <h1>Teams</h1> <ul> {this.state.teams.map((team) => ( <li key={`team-${team.get('slug')}`}> <Link to="timeline" params={{team: team.get('slug')}}> {team.get('name')} </Link> </li> ))} </ul> </div> ); } }
Use Immutable-style .get instead of JS style property access on Team list page.
Use Immutable-style .get instead of JS style property access on Team list page. Fixes #35.
JavaScript
mpl-2.0
mythmon/edwin,mythmon/edwin,mythmon/edwin,mythmon/edwin
fece5a97acbf07c6d405c5a8bd9f40de60fa5c29
src/kit/ui/StringComponent.js
src/kit/ui/StringComponent.js
import { Component } from 'substance' import TextInput from './TextInput' export default class StringComponent extends Component { render ($$) { let placeholder = this.props.placeholder let model = this.props.model let path = model.getPath() let name = path.join('.') let el = $$('div').addClass(this.getClassNames()) el.append( $$(TextInput, { name, path, placeholder }).ref('input') ) return el } getClassNames () { return 'sc-string' } }
import { Component } from 'substance' import TextInput from './TextInput' export default class StringComponent extends Component { render ($$) { let placeholder = this.props.placeholder let model = this.props.model let path = model.getPath() let name = path.join('.') let el = $$('div').addClass(this.getClassNames()) if (this.props.readOnly) { let doc = this.context.api.getDocument() let TextPropertyComponent = this.getComponent('text-property') el.append( $$(TextPropertyComponent, { doc, tagName: 'div', placeholder, path }).ref('display') ) } else { el.append( $$(TextInput, { name, path, placeholder }).ref('input') ) } return el } getClassNames () { return 'sc-string' } }
Allow to render text or string read-only.
Allow to render text or string read-only.
JavaScript
mit
substance/texture,substance/texture
1c19dbe6c8b8b462f86f3d901203e77ef5486cbd
lib/createHeader.js
lib/createHeader.js
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
var Immutable = require('immutable'); var Draft = require('draft-js'); var TYPES = require('./TYPES'); var createRow = require('./createRow'); /** * Create a new table header * * @param {String} tableKey * @param {Number} countColumns * @return {OrderedMap<String:Draft.ContentBlock>} */ function createHeader(tableKey, countColumns) { var tableHeaderKey = Draft.genNestedKey(tableKey); var tableHeaderBlock = new Draft.ContentBlock({ key: tableHeaderKey, type: TYPES.HEADER, data: Immutable.Map({ align: Array .apply(null, Array(10)) .map(function(){ return TYPES.LEFT; }) }) }); return Immutable.OrderedMap([ [tableHeaderKey, tableHeaderBlock] ]) .merge( createRow(tableHeaderKey, countColumns) ); } module.exports = createHeader;
Create align data when creating table
Create align data when creating table
JavaScript
apache-2.0
SamyPesse/draft-js-table,SamyPesse/draft-js-table
a58013389178b6254eed66983b3d6bac5a2c4ae0
lib/diff-pane-item-component.js
lib/diff-pane-item-component.js
/* @flow */ /** @jsx etch.dom */ import etch from 'etch' // $FlowBug: Yes, we know this isn't a React component :\ import DiffComponent from './diff-component' import type DiffViewModel from './diff-view-model' type DiffPaneItemComponentProps = {diffViewModel: DiffViewModel} export default class DiffPaneItemComponent { diffViewModel: DiffViewModel; element: HTMLElement; refs: {diffComponent: HTMLElement}; constructor (props: DiffPaneItemComponentProps) { this.acceptProps(props) } acceptProps ({diffViewModel}: DiffPaneItemComponentProps): Promise<void> { this.diffViewModel = diffViewModel let updatePromise = Promise.resolve() if (this.element) { updatePromise = etch.update(this) } else { etch.initialize(this) } this.element.addEventListener('focus', () => this.refs.diffComponent.focus()) return updatePromise } update (props: DiffPaneItemComponentProps, children: Array<any>): Promise<void> { return this.acceptProps(props) } render () { return ( <div className='pane-item' tabIndex='-1'>{ <DiffComponent ref='diffComponent' diffViewModel={this.diffViewModel}/> }</div> ) } }
/* @flow */ /** @jsx etch.dom */ import etch from 'etch' import {Disposable, CompositeDisposable} from 'atom' // $FlowBug: Yes, we know this isn't a React component :\ import DiffComponent from './diff-component' import type DiffViewModel from './diff-view-model' type DiffPaneItemComponentProps = {diffViewModel: DiffViewModel} export default class DiffPaneItemComponent { diffViewModel: DiffViewModel; element: HTMLElement; refs: {diffComponent: HTMLElement}; subscriptions: CompositeDisposable; constructor (props: DiffPaneItemComponentProps) { this.subscriptions = new CompositeDisposable() this.acceptProps(props) const onFocus = () => this.refs.diffComponent.focus() this.element.addEventListener('focus', onFocus) this.subscriptions.add(new Disposable(() => this.element.removeEventListener('focus', onFocus))) } acceptProps ({diffViewModel}: DiffPaneItemComponentProps): Promise<void> { this.diffViewModel = diffViewModel let updatePromise = Promise.resolve() if (this.element) { updatePromise = etch.update(this) } else { etch.initialize(this) } return updatePromise } update (props: DiffPaneItemComponentProps, children: Array<any>): Promise<void> { return this.acceptProps(props) } render () { return ( <div className='pane-item' tabIndex='-1'>{ <DiffComponent ref='diffComponent' diffViewModel={this.diffViewModel}/> }</div> ) } destroy (): Promise<void> { this.subscriptions.dispose() return etch.destroy(this) } }
Clean up the focus handler.
Clean up the focus handler.
JavaScript
mit
atom/github,atom/github,atom/github
4340850c7b2803002c747f425ef7c3da8bca8fdd
.template-lintrc.js
.template-lintrc.js
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': true, 'self-closing-void-elements': true, 'img-alt-attributes': false, 'link-rel-noopener': true, 'invalid-interactive': false, 'inline-link-to': true, 'style-concatenation': true, 'triple-curlies': false, 'deprecated-each-syntax': true, 'deprecated-inline-view-helper': false, } };
/* eslint-env node */ 'use strict'; var defaultAllowedBaseStrings = ['(', ')', ',', '.', '&', '+', '-', '=', '*', '/', '#', '%', '!', '?', ':', '[', ']', '{', '}', '<', '>', '•', '—', ' ', '|']; module.exports = { extends: 'recommended', rules: { 'bare-strings': ['?', '»', '&mdash;'].concat(defaultAllowedBaseStrings), 'block-indentation': true, 'html-comments': true, 'nested-interactive': true, 'self-closing-void-elements': true, 'img-alt-attributes': false, 'invalid-interactive': false, 'inline-link-to': true, 'triple-curlies': false, 'deprecated-each-syntax': true, 'deprecated-inline-view-helper': false, } };
Remove rules which are now enabled by default
Remove rules which are now enabled by default These template lint rules are now enabled in the 'recommended' configuration so we don't need to override them in our config.
JavaScript
mit
jrjohnson/frontend,ilios/frontend,thecoolestguy/frontend,dartajax/frontend,djvoa12/frontend,dartajax/frontend,djvoa12/frontend,gabycampagna/frontend,jrjohnson/frontend,ilios/frontend,gabycampagna/frontend,thecoolestguy/frontend,gboushey/frontend,gboushey/frontend
4bd2a3ccb73d9a2b8579a2fed42943548be51199
sw-precache-config.js
sw-precache-config.js
/** * https://github.com/GoogleChrome/sw-precache#command-line-interface */ module.exports = { root: 'build', staticFileGlobs: [ 'build/javascripts/main.js', 'build/stylesheets/**.css', 'build/images/**/*.*', ], stripPrefix: 'build/' }
/** * https://github.com/GoogleChrome/sw-precache#command-line-interface */ module.exports = { root: 'build', swFile: 'sw-precache.js', staticFileGlobs: [ 'build/javascripts/main.js', 'build/stylesheets/**.css', 'build/images/**/*.*', ], stripPrefix: 'build/' }
Rename service-worker.js -> sw-precache.js for other worker names
feat: Rename service-worker.js -> sw-precache.js for other worker names
JavaScript
mit
Leko/WEB-EGG,Leko/WEB-EGG,Leko/WEB-EGG
f74253045897f209768c7490d3b68c8b4488a623
client/app/pages/admin/outdated-queries/index.js
client/app/pages/admin/outdated-queries/index.js
import moment from 'moment'; import { Paginator } from '../../../utils'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, Events, $http, $timeout) { Events.record('view', 'page', 'admin/outdated_queries'); $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function (ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
import moment from 'moment'; import { Paginator } from '../../../utils'; import template from './outdated-queries.html'; function OutdatedQueriesCtrl($scope, Events, $http, $timeout) { Events.record('view', 'page', 'admin/outdated_queries'); $scope.autoUpdate = true; this.queries = new Paginator([], { itemsPerPage: 50 }); const refresh = () => { if ($scope.autoUpdate) { $scope.refresh_time = moment().add(1, 'minutes'); $http.get('/api/admin/queries/outdated').success((data) => { this.queries.updateRows(data.queries); $scope.updatedAt = data.updated_at * 1000.0; }); } const timer = $timeout(refresh, 59 * 1000); $scope.$on('$destroy', () => { if (timer) { $timeout.cancel(timer); } }); }; refresh(); } export default function (ngModule) { ngModule.component('outdatedQueriesPage', { template, controller: OutdatedQueriesCtrl, }); return { '/admin/queries/outdated': { template: '<outdated-queries-page></outdated-queries-page>', title: 'Outdated Queries', }, }; }
Test line end carriages redo.
Test line end carriages redo.
JavaScript
bsd-2-clause
moritz9/redash,moritz9/redash,moritz9/redash,moritz9/redash
d6dac26b729b9a2f0adade9d870dfd7edbd2c3b9
.stylelintrc.js
.stylelintrc.js
const declarationBlockPropertiesOrder = require('./.csscomb.json')['sort-order'][0]; module.exports = { extends: `stylelint-config-modularis`, rules: { 'declaration-block-properties-order': declarationBlockPropertiesOrder, 'no-indistinguishable-colors': [true, { threshold: 1 }] } };
const declarationBlockPropertiesOrder = require(`./.csscomb.json`)[`sort-order`][0]; module.exports = { extends: `stylelint-config-modularis`, rules: { 'declaration-block-properties-order': declarationBlockPropertiesOrder, 'no-indistinguishable-colors': [true, { threshold: 1 }], }, };
Fix code style errors in the stylelint config file
Fix code style errors in the stylelint config file
JavaScript
mit
avalanchesass/avalanche-website,avalanchesass/avalanche-website
dd538b5472f01f45822f026624d98da78408e492
lib/Procure.js
lib/Procure.js
var fs = require('fs'); var url = require('url'); var request = require('request'); /** * @class */ var Procure = function() {}; /** * "Procure" a resource, whether local or remote. * @function procure * @param {string} uri Some path to a file. * @param {Procure~ProcuringComplete} callback Function called on sucess or failure. */ Procure.prototype.procure = function( uri , procured ) { var info = url.parse( uri ); if (~['http:', 'https:'].indexOf( info.protocol )) { request({ uri: uri, headers: { 'Accept': 'application/json;q=0.9,*/*;q=0.8' } }, function(err, res, body) { if (res.statusCode != 200 ) return procured('non-200 response'); return procured( err , body ); }); } else { fs.readFile( uri , procured ); } }; /** * The callback function when the file is retrieved (or not). * @callback Procure~ProcuringComplete * @param {mixed} err Error message, if any. Null / undefined if none. * @param {string} body Body of the requested content. */ module.exports = Procure;
var fs = require('fs'); var url = require('url'); var request = require('request'); var package = require('../package.json'); /** * @class */ var Procure = function() {}; /** * "Procure" a resource, whether local or remote. * @function procure * @param {string} uri Some path to a file. * @param {Procure~ProcuringComplete} callback Function called on sucess or failure. */ Procure.prototype.procure = function( uri , procured ) { var info = url.parse( uri ); if (~['http:', 'https:'].indexOf( info.protocol )) { request({ uri: uri, headers: { 'Accept': 'application/json;q=0.9,*/*;q=0.8', 'User-Agent': 'procure/' + package.version } }, function(err, res, body) { var statusCode = res.statusCode; if (statusCode != 200 ) return procured('non-200 response ' + statusCode); return procured( err , body ); }); } else { fs.readFile( uri , procured ); } }; /** * The callback function when the file is retrieved (or not). * @callback Procure~ProcuringComplete * @param {mixed} err Error message, if any. Null / undefined if none. * @param {string} body Body of the requested content. */ module.exports = Procure;
Add User-Agent for GitHub calls.
Add User-Agent for GitHub calls.
JavaScript
mit
martindale/procure
2538a506cc1dec5557a22ef51b11ce068a350440
lib/actions.js
lib/actions.js
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta); if (! request) { throw new Error('fluxapp:router:init unable to locate route specified', route); } if (isEnabled()) { window.history.replaceState( request, request.title || '', request.url ); } return request; }, go: function go(id, meta) { var request = router.build(id, meta); if (! request) { throw new Error('fluxapp:router:Go unable to locate route specified', route); } if (isEnabled()) { window.history.pushState( request, request.title, request.url ); } return request; }, back: function back() { if (isEnabled) { window.history.back(); } }, forward: function forward() { if (isEnabled) { window.history.forward(); } } } }
'use strict'; var fluxApp = require('fluxapp'); var router = fluxApp.getRouter(); function isEnabled() { return !! (typeof window !== 'undefined' && window.history); } module.exports = { router: { init: function init(url, meta) { var request = router.build(url, meta, false); if (! request) { throw new Error('fluxapp:router:init unable to locate route specified', route); } if (isEnabled()) { window.history.replaceState( request, request.title || '', request.url ); } return request; }, go: function go(id, meta) { var request = router.build(id, meta); if (! request) { throw new Error('fluxapp:router:Go unable to locate route specified', route); } if (isEnabled()) { window.history.pushState( request, request.title, request.url ); } return request; }, back: function back() { if (isEnabled) { window.history.back(); } }, forward: function forward() { if (isEnabled) { window.history.forward(); } } } }
Allow for 404 not found
Allow for 404 not found
JavaScript
mit
colonyamerican/fluxapp-router
5b7b02e254769ec79a9525c23b9eb85353e9b38e
src/components/body/ScrollerDirective.js
src/components/body/ScrollerDirective.js
import { requestAnimFrame } from '../../utils/utils'; import { scrollHelper } from './scrollHelper'; export function ScrollerDirective($timeout){ return { restrict: 'E', require:'^dtBody', transclude: true, template: `<div ng-style="scrollerStyles()" ng-transclude></div>`, link: function($scope, $elm, $attrs, ctrl){ var ticking = false, lastScrollY = 0, lastScrollX = 0, helper = scrollHelper.create($elm); function update(){ $timeout(() => { ctrl.options.internal.offsetY = lastScrollY; ctrl.options.internal.offsetX = lastScrollX; ctrl.updatePage(); }); ticking = false; }; function requestTick() { if(!ticking) { requestAnimFrame(update); ticking = true; } }; $elm.parent().on('scroll', function(ev) { lastScrollY = this.scrollTop; lastScrollX = this.scrollLeft; requestTick(); }); $scope.scrollerStyles = function(scope){ return { height: ctrl.count * ctrl.options.rowHeight + 'px' } }; } }; };
import { requestAnimFrame } from '../../utils/utils'; import { scrollHelper } from './scrollHelper'; export function ScrollerDirective($timeout){ return { restrict: 'E', require:'^dtBody', transclude: true, replace: true, template: `<div ng-style="scrollerStyles()" ng-transclude></div>`, link: function($scope, $elm, $attrs, ctrl){ var ticking = false, lastScrollY = 0, lastScrollX = 0, helper = scrollHelper.create($elm.parent()); function update(){ $timeout(() => { ctrl.options.internal.offsetY = lastScrollY; ctrl.options.internal.offsetX = lastScrollX; ctrl.updatePage(); }); ticking = false; }; function requestTick() { if(!ticking) { requestAnimFrame(update); ticking = true; } }; $elm.parent().on('scroll', function(ev) { lastScrollY = this.scrollTop; lastScrollX = this.scrollLeft; requestTick(); }); $scope.scrollerStyles = function(scope){ return { height: ctrl.count * ctrl.options.rowHeight + 'px' } }; } }; };
Fix footer paging not working
Fix footer paging not working
JavaScript
mit
kuzman/angular-data-table,gabigeo/angular-data-table,kuzman/angular-data-table
c43bd67537d933ed345e79997ed315263f48c27c
examples/simple.js
examples/simple.js
"use strict"; const FigText = require('../lib/FigText'); const cursor = require('kittik-cursor').create().resetTTY(); FigText.create({ text: 'KittikJS\n Rules\n !!!', x: 'center', y: 'middle', font: 'Star Wars', foreground: 'yellow_1', horizontalLayout: 'full' }).render(cursor); cursor.flush();
"use strict"; const FigText = require('../lib/FigText'); const cursor = require('kittik-cursor').create().resetTTY(); FigText.create({ text: 'KittikJS', x: 'center', y: 'middle', font: 'Star Wars', foreground: 'yellow_1', horizontalLayout: 'full' }).render(cursor); cursor.moveTo(1, process.stdout.rows).flush();
Update shape-basic to the latest version
fix(shape): Update shape-basic to the latest version
JavaScript
mit
kittikjs/shape-fig-text
523263d6b469f6b65a119b42c5c889f1b445d08e
src/fast_validation/helpers/types.js
src/fast_validation/helpers/types.js
'use strict'; const { mapValues } = require('../../utilities'); const isObject = function (value) { return value.constructor === Object; }; const isObjectArray = function (value) { return Array.isArray(value) && value.every(isObject); }; const typeTest = ({ test: testFunc, message }) => name => ({ test ({ [name]: value }) { if (value == null) { return true; } return testFunc(value); }, message: `'${name}' must be ${message}`, }); const typeCheckers = { stringTest: { test: value => typeof value === 'string', message: 'a string', }, booleanTest: { test: value => typeof value === 'boolean', message: 'true or false', }, numberTest: { test: value => Number.isFinite(value), message: 'a number', }, integerTest: { test: value => Number.isInteger(value), message: 'an integer', }, objectTest: { test: isObject, message: 'an object', }, objectArrayTest: { test: isObjectArray, message: 'an array of objects', }, objectOrArrayTest: { test: value => isObject(value) || isObjectArray(value), message: 'an array of objects', }, }; const typeTests = mapValues(typeCheckers, typeTest); module.exports = { ...typeTests, };
'use strict'; const { mapValues, get } = require('../../utilities'); const isObject = function (value) { return value.constructor === Object; }; const isObjectArray = function (value) { return Array.isArray(value) && value.every(isObject); }; const typeTest = ({ test: testFunc, message }) => name => ({ test (value) { const val = get(value, name.split('.')); if (val == null) { return true; } return testFunc(val); }, message: `'${name}' must be ${message}`, }); const typeCheckers = { stringTest: { test: value => typeof value === 'string', message: 'a string', }, booleanTest: { test: value => typeof value === 'boolean', message: 'true or false', }, numberTest: { test: value => Number.isFinite(value), message: 'a number', }, integerTest: { test: value => Number.isInteger(value), message: 'an integer', }, objectTest: { test: isObject, message: 'an object', }, objectArrayTest: { test: isObjectArray, message: 'an array of objects', }, objectOrArrayTest: { test: value => isObject(value) || isObjectArray(value), message: 'an array of objects', }, }; const typeTests = mapValues(typeCheckers, typeTest); module.exports = { ...typeTests, };
Fix typeTest for deep attrs
Fix typeTest for deep attrs
JavaScript
apache-2.0
autoserver-org/autoserver,autoserver-org/autoserver
762ea681fb722e0c08761e5daec6ea4979de6d11
lib/get_all.js
lib/get_all.js
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b); }).filter(fp.id).length > 0; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
var minimatch = require('minimatch'); var is = require('annois'); var fp = require('annofp'); var zip = require('annozip'); module.exports = function(model, query, cb) { if(!is.object(query) || fp.count(query) === 0) { return is.fn(cb)? cb(null, model._data): query(null, model._data); } var fields = query.fields; var limit = query.limit; var offset = query.offset || 0; delete query.fields; delete query.limit; delete query.offset; var zq = zip(query); var ret = model._data; if(fp.count(query)) { ret = ret.filter(function(o) { return zq.map(function(p) { var a = o[p[0]]? o[p[0]].toLowerCase(): ''; var b = p[1]? p[1].toLowerCase(): ''; return minimatch(a, b); }).filter(fp.id).length === zq.length; }); } if(fields) { fields = is.array(fields)? fields: [fields]; ret = ret.map(function(o) { var r = {}; fields.forEach(function(k) { r[k] = o[k]; }); return r; }); } if(limit) { ret = ret.slice(offset, offset + limit); } cb(null, ret); };
Allow fuzzy searches to be combined
Allow fuzzy searches to be combined Ie. v1/jsdelivr/libraries?name=jq*&lastversion=*.0.1 .
JavaScript
mit
jsdelivr/api,MartinKolarik/api-sync,jsdelivr/api-sync,MartinKolarik/api,jsdelivr/api-sync,2947721120/jsdelivr-api,MartinKolarik/api-sync
821c22c7318e4405058f56d5c2aacfd7cd23bf52
packages/coinstac-server-core/src/services/logger.js
packages/coinstac-server-core/src/services/logger.js
'use strict'; const mkdirp = require('mkdirp'); const path = require('path'); const pify = require('pify'); const touch = require('touch'); const winston = require('winston'); /** * @module service/logger * * {@link https://www.npmjs.com/package/winston} */ /** * Log file directory. * * @const {string} */ const LOG_DIR = '/var/log/coinstac'; /** * Log file name. * * @const {string} */ const LOG_BASE = 'application.log'; /** * Logger instance. * * @type {winston.Logger} */ const logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true, level: 'info', }), ], }); /** * Set up file transport async. If an error occurs the executable will catch the * unhandled rejection and shut the server down. */ pify(mkdirp)(LOG_DIR) .then(() => { return new Promise((resolve, reject) => { touch(path.join(LOG_DIR, LOG_BASE), error => { if (error) { reject(error); } else { resolve(); } }); }); }) .then(() => { logger.add(winston.transports.File, { filename: path.join(LOG_DIR, LOG_BASE), level: 'silly', silent: false, }); }); module.exports = logger;
'use strict'; const mkdirp = require('mkdirp'); const path = require('path'); const pify = require('pify'); const touch = require('touch'); const winston = require('winston'); /** * @module service/logger * * {@link https://www.npmjs.com/package/winston} */ /** * Log file directory. * * @const {string} */ const LOG_DIR = '/var/log/coinstac'; /** * Log file name. * * @const {string} */ const LOG_BASE = 'application.log'; /** * Logger instance. * * @type {winston.Logger} */ const logger = new (winston.Logger)({ transports: [ new (winston.transports.Console)({ colorize: true, level: 'info', }), ], }); /** * Set up file transport async. If an error occurs the executable will catch the * unhandled rejection and shut the server down. */ pify(mkdirp)(LOG_DIR) .then(() => pify(touch)(path.join(LOG_DIR, LOG_BASE))) .catch(() => { throw new Error( `Couldn't create log file: ${path.join(LOG_DIR, LOG_BASE)}` ); }) .then(() => { logger.add(winston.transports.File, { filename: path.join(LOG_DIR, LOG_BASE), level: 'silly', silent: false, }); }); module.exports = logger;
Make log `touch` error more human-readable.
Make log `touch` error more human-readable.
JavaScript
mit
MRN-Code/coinstac,MRN-Code/coinstac,MRN-Code/coinstac
18e5fe55934899ba1e4454e1383ef49c5068dafb
ember-cli-build.js
ember-cli-build.js
/* eslint-env node */ /* global require, module */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, 'ember-cli-babel': { includePolyfill: true }, 'ember-cli-mocha': { useLintTree: false }, sassOptions: { includePaths: [ 'addon/styles' ] }, snippetPaths: [ 'code-snippets' ], snippetSearchPaths: [ 'tests/dummy' ] }) app.import('bower_components/highlightjs/styles/github.css') app.import(app.project.addonPackages['ember-source'] ? 'vendor/ember/ember-template-compiler.js' : 'bower_components/ember/ember-template-compiler.js') return app.toTree() }
/* eslint-env node */ /* global require, module */ const EmberAddon = require('ember-cli/lib/broccoli/ember-addon') module.exports = function (defaults) { var app = new EmberAddon(defaults, { babel: { optional: ['es7.decorators'] }, 'ember-cli-babel': { includePolyfill: true }, sassOptions: { includePaths: [ 'addon/styles' ] }, snippetPaths: [ 'code-snippets' ], snippetSearchPaths: [ 'tests/dummy' ] }) app.import('bower_components/highlightjs/styles/github.css') app.import(app.project.addonPackages['ember-source'] ? 'vendor/ember/ember-template-compiler.js' : 'bower_components/ember/ember-template-compiler.js') return app.toTree() }
Remove useLintTree ember-cli-mocha build configuration
Remove useLintTree ember-cli-mocha build configuration
JavaScript
mit
EWhite613/ember-frost-core,dafortin/ember-frost-core,ciena-frost/ember-frost-core,dafortin/ember-frost-core,ciena-frost/ember-frost-core,dafortin/ember-frost-core,ciena-frost/ember-frost-core,EWhite613/ember-frost-core,EWhite613/ember-frost-core
d15cb49d88672b866158c5ef267d1f4c0bd7509b
lib/publish.js
lib/publish.js
// get a url to a tarball, fetch it, read the package.json, and // publish to the registry. module.exports = publish var fs = require("fs") , path = require("path") , chain = require("./utils/chain") , rm = require("./utils/rm-rf") , readJson = require("./utils/read-json") , exec = require("./utils/exec") , mkdir = require("./utils/mkdir-p") , log = require("./utils/log") , semver = require("./utils/semver") , fetch = require("./utils/fetch") , registry = require("./utils/registry") , npm = require("../npm") , url = require("url") function publish (args, cb) { log(args, "publish") npm.commands.cache.add(args[0], args[1], function (er, data) { if (er) return cb(er) log(data, "publish") if (!data) return cb(new Error("no data!?")) registry.publish(data, cb) }) }
module.exports = publish var npm = require("../npm") , registry = require("./utils/registry") , log = require("./utils/log") function publish (args, cb) { log(args, "publish") npm.commands.cache.add(args[0], args[1], function (er, data) { if (er) return cb(er) log(data, "publish") if (!data) return cb(new Error("no data!?")) registry.publish(data, cb) }) }
Remove a bunch of unnecessary require() statements
Remove a bunch of unnecessary require() statements
JavaScript
artistic-2.0
ekmartin/npm,kriskowal/npm,segmentio/npm,yibn2008/npm,kemitchell/npm,chadnickbok/npm,cchamberlain/npm,segmentio/npm,xalopp/npm,thomblake/npm,cchamberlain/npm,evocateur/npm,xalopp/npm,Volune/npm,segrey/npm,lxe/npm,xalopp/npm,princeofdarkness76/npm,segment-boneyard/npm,evocateur/npm,kemitchell/npm,cchamberlain/npm-msys2,segment-boneyard/npm,princeofdarkness76/npm,midniteio/npm,DIREKTSPEED-LTD/npm,yyx990803/npm,rsp/npm,cchamberlain/npm-msys2,thomblake/npm,yyx990803/npm,cchamberlain/npm,DIREKTSPEED-LTD/npm,segrey/npm,TimeToogo/npm,Volune/npm,kimshinelove/naver-npm,rsp/npm,ekmartin/npm,yibn2008/npm,misterbyrne/npm,segrey/npm,TimeToogo/npm,kimshinelove/naver-npm,evanlucas/npm,TimeToogo/npm,haggholm/npm,segment-boneyard/npm,Volune/npm,kemitchell/npm,haggholm/npm,misterbyrne/npm,lxe/npm,misterbyrne/npm,DIREKTSPEED-LTD/npm,yodeyer/npm,chadnickbok/npm,evanlucas/npm,evanlucas/npm,yodeyer/npm,princeofdarkness76/npm,kriskowal/npm,cchamberlain/npm-msys2,DaveEmmerson/npm,midniteio/npm,DaveEmmerson/npm,chadnickbok/npm,DaveEmmerson/npm,yyx990803/npm,ekmartin/npm,yibn2008/npm,rsp/npm,segmentio/npm,kimshinelove/naver-npm,thomblake/npm,kriskowal/npm,evocateur/npm,lxe/npm,haggholm/npm,yodeyer/npm,midniteio/npm
15cf2fd1ca05cf8be0491f10672a36f4352a9d8e
packages/ember-model/tests/model_sideloading_test.js
packages/ember-model/tests/model_sideloading_test.js
var attr = Ember.attr; module("Ember.Model sideloading"); test("data can be sideloaded without materializing records", function() { expect(1); var Model = Ember.Model.extend({ id: attr(), name: attr() }); Model.adapter = { find: function(record, id) { ok(false, "Adapter#find shouldn't be called for records with sideloaded data"); } }; Model.load([{id: 1, name: "Erik"}]); var record = Model.find(1); ok(record.get('isLoaded'), "Record should be loaded immediately"); // ok(record.get('isLoaded'), "Record should be loaded immediately"); });
var attr = Ember.attr; module("Ember.Model sideloading"); test("data can be sideloaded without materializing records", function() { expect(1); var Model = Ember.Model.extend({ id: attr(), name: attr(), camelCase: attr() }); Model.adapter = { find: function(record, id) { ok(false, "Adapter#find shouldn't be called for records with sideloaded data"); } }; Model.load([{id: 1, name: "Erik", camel_case: "Dromedary"}]); var record = Model.find(1); ok(record.get('isLoaded'), "Record should be loaded immediately"); strictEqual(record.get('id'), 1, "Record ID retained successfully"); strictEqual(record.get('name'), "Erik", "Record name retained successfully"); strictEqual(record.get('camelCase'), "Dromedary", "camel cased attributes retained correctly"); // ok(record.get('isLoaded'), "Record should be loaded immediately"); });
Add breaking test for sideloading data with camel cased attributes
Add breaking test for sideloading data with camel cased attributes
JavaScript
mit
zenefits/ember-model,greyhwndz/ember-model,sohara/ember-model,asquet/ember-model,juggy/ember-model,GavinJoyce/ember-model,igorgoroshit/ember-model,ipavelpetrov/ember-model,CondeNast/ember-model,ebryn/ember-model,asquet/ember-model,ckung/ember-model,Swrve/ember-model,julkiewicz/ember-model,c0achmcguirk/ember-model,intercom/ember-model,gmedina/ember-model,ipavelpetrov/ember-model
9079ca9a5a9565b02a0bfae9b073f8a8edc789dc
app/scripts/museum/address-filter.js
app/scripts/museum/address-filter.js
(function() { 'use strict'; /** * Generate a human-readable address string from a single museum object * * Can get fancy here and prioritize one of the three address types provided: * source address, geocoded address, physical address * * For now, default to geocoded address since that's what seems to always be populated */ /* ngInject */ function AddressFilter() { return function (input) { var address = input.gaddress; var city = input.gcity; var state = input.gstate; var zip = input.gzip; return address + ', ' + city + ', ' + state + ' ' + zip; }; } angular.module('imls.museum') .filter('imlsAddress', AddressFilter); })();
(function() { 'use strict'; /** * Generate a human-readable address string from a single museum object * * Can get fancy here and prioritize one of the three address types provided: * source address, geocoded address, physical address * * For now, default to geocoded address since that's what seems to always be populated */ /* ngInject */ function AddressFilter() { return function (input) { var address = input.adstreet; var city = input.adcity; var state = input.adstate; var zip = input.adzip; return address + ', ' + city + ', ' + state + ' ' + zip; }; } angular.module('imls.museum') .filter('imlsAddress', AddressFilter); })();
Use valid columns in address filter
Bugfix: Use valid columns in address filter
JavaScript
apache-2.0
MuseumStat/imls-museum-data,azavea/imls-museum-data,azavea/imls-museum-data,azavea/imls-museum-data,MuseumStat/imls-museum-data,MuseumStat/imls-museum-data
d17596670403e4f20efa4d1957aad1d1f52b4038
lib/runtime.js
lib/runtime.js
var adt; try { adt = require("adt"); } catch (e) { adt = null; } // Given an object and a class name, tries to determin if the object is an // instance of said class. function matchesTypeName (obj, name) { if (adt && isADT(obj)) { var types = adt.lookup(name); if (types) { for (var i = 0, len = types.length; i < len; i++) { if (obj instanceof types[i]) return true; } } return false; } if (obj.constructor && obj.constructor.name && obj.constructor.name === name) { return true; } return false; } // Checks whether an object is an adt.js type. function isADT (obj) { return obj instanceof adt.__Base__; } // Export module.exports = { matchesTypeName: matchesTypeName, isADT: isADT };
var adt; try { adt = require("adt"); } catch (e) { adt = null; } // Given an object and a class name, tries to determin if the object is an // instance of said class. function matchesTypeName (obj, name) { if (name === "Number") { return typeof obj === "number"; } else if (name === "String") { return typeof obj === "string"; } else if (name === "Function") { return obj instanceof Function; } else if (name === "Object") { return obj instanceof Object; } else if (adt && isADT(obj)) { var types = adt.lookup(name); if (types) { for (var i = 0, len = types.length; i < len; i++) { if (obj instanceof types[i]) return true; } } return false; } return false; } // Checks whether an object is an adt.js type. function isADT (obj) { return obj instanceof adt.__Base__; } // Export module.exports = { matchesTypeName: matchesTypeName, isADT: isADT };
Remove checking of constructor.name, instead just check primitive types and adt.js types
Remove checking of constructor.name, instead just check primitive types and adt.js types
JavaScript
mit
ermouth/matches.js,natefaubion/matches.js
759e7a66ca850755d7dad05974bf4a559d51f984
source/javascripts/pricing.js
source/javascripts/pricing.js
$(function () { $.fn.equalHeights = function() { var maxHeight = 0, $this = $(this); $this.each( function() { var height = $(this).innerHeight(); if (height > maxHeight) { maxHeight = height; } }); return $this.css('height', maxHeight); }; function equilize() { $('[data-equal]').each(function(){ var $this = $(this), target = $this.data('equal'); if ($(window).width() >= 992) { $this.find(target).css('height', '').equalHeights(); } else { $this.find(target).css('height', ''); } }); } setTimeout(equilize, 500); $(window).on('resize', equilize); $('.js-faq-question').on('click', function (e) { e.preventDefault(); isOpen = $(this).closest('.faq-item').is('.is-open'); $('.faq-item.is-open').removeClass('is-open'); if (!isOpen) { $(this).closest('.faq-item').toggleClass('is-open'); } }); });
$(function () { $.fn.equalHeights = function() { var maxHeight = 0, $this = $(this); $this.each( function() { var height = $(this).innerHeight(); if (height > maxHeight) { maxHeight = height; } }); return $this.css('height', maxHeight); }; function equilize() { $('[data-equal]').each(function(){ var $this = $(this), target = $this.data('equal'); if ($(window).width() >= 992) { $this.find(target).css('height', '').equalHeights(); } else { $this.find(target).css('height', ''); } }); } setTimeout(equilize, 500); $(window).on('resize', equilize); $('.featured-item-expand').on('click', function(e) { var listExpander = $(this); targetFeatureList = $($(this).attr('href')); if (!targetFeatureList.is(':visible')) { targetFeatureList.addClass('list-expanded'); listExpander.addClass('chevron-up'); } else { targetFeatureList.removeClass('list-expanded'); listExpander.removeClass('chevron-up'); } e.preventDefault(); }); $('.js-faq-question').on('click', function (e) { e.preventDefault(); isOpen = $(this).closest('.faq-item').is('.is-open'); $('.faq-item.is-open').removeClass('is-open'); if (!isOpen) { $(this).closest('.faq-item').toggleClass('is-open'); } }); });
Add event listener to expand/collapse edition card info
Add event listener to expand/collapse edition card info
JavaScript
mit
damianhakert/damianhakert.github.io
493a5038a3afe675213e2f8e1802a088b2cfc38c
src/javascript/app_2/Stores/Modules/Trading/Helpers/end-time.js
src/javascript/app_2/Stores/Modules/Trading/Helpers/end-time.js
export const getSelectedTime = ( server_time, selected_time, market_open_time, ) => { const boundaries = selected_time.isBefore(market_open_time) ? market_open_time.isBefore(server_time) ? server_time.add(5, 'minute') : market_open_time.add(5, 'minute') : selected_time; return boundaries.format('HH:mm'); }; export const getBoundaries = ( server_time, market_open_time, market_close_time, ) => { const boundaries = { start: server_time.isBefore(market_open_time) ? market_open_time.add(5, 'minute') : server_time.add(5, 'minute'), end: market_close_time, }; return boundaries; };
export const getSelectedTime = ( server_time, selected_time, market_open_time, ) => { const value = selected_time.isBefore(market_open_time) ? market_open_time.isBefore(server_time) ? server_time.add(5, 'minute') : market_open_time.add(5, 'minute') : selected_time; return value.format('HH:mm'); }; export const getBoundaries = ( server_time, market_open_time, market_close_time, ) => { const boundaries = { start: server_time.isBefore(market_open_time) ? market_open_time.add(5, 'minute') : server_time.add(5, 'minute'), end: market_close_time, }; return boundaries; };
Rename boundaries -> value, on getSelectedTime
Rename boundaries -> value, on getSelectedTime
JavaScript
apache-2.0
ashkanx/binary-static,binary-com/binary-static,binary-static-deployed/binary-static,binary-com/binary-static,binary-com/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,ashkanx/binary-static,binary-static-deployed/binary-static,4p00rv/binary-static,kellybinary/binary-static,4p00rv/binary-static,4p00rv/binary-static,kellybinary/binary-static,kellybinary/binary-static
4f503b03227cf7eebc552672ae469443016c0d6d
src/index.js
src/index.js
require("./stylesheets/main.less"); var marked = require("marked"); var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "markdown.preview", title: "Markdown: Preview", context: ["editor"], run: function(args, context) { return codebox.tabs.add(codebox.tabs.HtmlPanel, { className: "component-markdown-preview", content: marked(context.getContent()) }, { type: "markdown", title: "Markdown: " + context.model.get("name"), section: "markdown" }); } });
require("./stylesheets/main.less"); var marked = require("marked"); var commands = codebox.require("core/commands"); var dialogs = codebox.require("utils/dialogs"); commands.register({ id: "markdown.preview", title: "Markdown: Preview", context: ["editor"], run: function(args, ctx) { return codebox.tabs.add(codebox.tabs.HtmlPanel, { className: "component-markdown-preview", content: marked(ctx.editor.getContent()) }, { type: "markdown", title: "Markdown: " + ctx.editor.model.get("name"), section: "markdown" }); } });
Use new multiple cmd contexts
Use new multiple cmd contexts
JavaScript
apache-2.0
CodeboxIDE/package-markdown
30fb1dd1918d561c8ac2a99708af962224824c9e
src/index.js
src/index.js
import {EntityManager} from './entity-manager'; export {DefaultRepository} from './default-repository'; export {Repository} from './repository'; export {Entity} from './entity'; export {EntityManager} from './entity-manager'; export {association} from './decorator/association'; export {resource} from './decorator/resource'; export {repository} from './decorator/repository'; export {validation} from './decorator/validation'; export {validatedResource} from './decorator/validated-resource'; export function configure(aurelia, configCallback) { let entityManagerInstance = aurelia.container.get(EntityManager); configCallback(entityManagerInstance); }
import {EntityManager} from './entity-manager'; import {ValidationGroup} from 'aurelia-validation'; import {HasAssociationValidationRule} from './validator/has-association'; export {DefaultRepository} from './default-repository'; export {Repository} from './repository'; export {Entity} from './entity'; export {OrmMetadata} from './orm-metadata'; export {EntityManager} from './entity-manager'; export {association} from './decorator/association'; export {resource} from './decorator/resource'; export {repository} from './decorator/repository'; export {validation} from './decorator/validation'; export {validatedResource} from './decorator/validated-resource'; export function configure(aurelia, configCallback) { let entityManagerInstance = aurelia.container.get(EntityManager); configCallback(entityManagerInstance); ValidationGroup.prototype.hasAssociation = function() { return this.isNotEmpty().passesRule(new HasAssociationValidationRule()); }; }
Add validation rule for associations to validator
feat(validator): Add validation rule for associations to validator
JavaScript
mit
SpoonX/aurelia-orm,kellyethridge/aurelia-orm,freska-fi/aurelia-orm,freska-fi/aurelia-orm,doktordirk/aurelia-orm,kellyethridge/aurelia-orm,SpoonX/aurelia-orm,bas080/aurelia-orm,doktordirk/aurelia-orm,bas080/aurelia-orm
f71e561347293bdf7adb688739cc0b9e45e08a48
test/test-creation.js
test/test-creation.js
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('bespoke generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('bespoke:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. 'package.json', 'bower.json', 'Gruntfile.js', '.gitignore', '.jshintrc', '.bowerrc', 'src/index.jade', 'src/js/js.js', 'src/css/css.styl' ]; helpers.mockPrompt(this.app, { 'name': 'Foo Bar', 'bullets': 'Y', 'hash': 'Y' }); this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
/*global describe, beforeEach, it*/ 'use strict'; var path = require('path'); var helpers = require('yeoman-generator').test; describe('bespoke generator', function () { beforeEach(function (done) { helpers.testDirectory(path.join(__dirname, 'temp'), function (err) { if (err) { return done(err); } this.app = helpers.createGenerator('bespoke:app', [ '../../app' ]); done(); }.bind(this)); }); it('creates expected files', function (done) { var expected = [ // add files you expect to exist here. 'package.json', 'bower.json', 'Gruntfile.js', '.gitignore', '.jshintrc', '.bowerrc', 'src/index.jade', 'src/js/js.js', 'src/css/css.styl' ]; helpers.mockPrompt(this.app, { 'title': 'Foo Bar', 'bullets': 'Y', 'hash': 'Y' }); this.app.run({}, function () { helpers.assertFiles(expected); done(); }); }); });
Rename 'name' to 'title' in test
Rename 'name' to 'title' in test
JavaScript
mit
pimterry/generator-bespoke,mikemaccana/generator-bespoke,bguiz/generator-bespoke,markdalgleish/generator-bespoke,bespokejs/generator-bespoke,markdalgleish/generator-bespoke,markdalgleish/generator-bespoke,bespokejs/generator-bespoke,bespokejs/generator-bespoke
a24c7ca0ddbef44abeda4e12cd5382b7748a1204
src/store.js
src/store.js
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers from './reducers' import rootSaga from './sagas' const logger = createLogger() const saga = createSagaMiddleware() export const store = createStore( reducers, applyMiddleware(logger, saga) ) saga.run(rootSaga)
/** @babel */ import { applyMiddleware, createStore } from 'redux' import createLogger from 'redux-logger' import createSagaMiddleware from 'redux-saga' import reducers from './reducers' import rootSaga from './sagas' const logger = createLogger({ collapsed: true, diff: true }) const saga = createSagaMiddleware() export const store = createStore( reducers, applyMiddleware(logger, saga) ) saga.run(rootSaga)
Add collapsing to the logger
Add collapsing to the logger
JavaScript
mit
sanack/atom-jq
c12f5f84fd3201298b84362cc0f5c0c6de4bc86c
lib/assets/javascripts/cartodb3/editor/layers/analysis-views/default-layer-analysis-view.js
lib/assets/javascripts/cartodb3/editor/layers/analysis-views/default-layer-analysis-view.js
var template = require('./default-layer-analysis-view.tpl'); /** * View for an analysis node with a single input * * this.model is expected to be a analysis-definition-node-nodel */ module.exports = cdb.core.View.extend({ initialize: function (opts) { if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required'); if (!opts.layerAnalysisViewFactory) throw new Error('layerAnalysisViewFactory is required'); this._layerDefinitionModel = opts.layerDefinitionModel; this._layerAnalysisViewFactory = opts.layerAnalysisViewFactory; this.model.on('change', this.render, this); }, render: function () { this.clearSubViews(); this.$el.html(template({ id: this.model.id, title: this.model.get('type') })); var view = this._layerAnalysisViewFactory.createView(this.model.get('source_id'), this._layerDefinitionModel); this.addView(view); this.$el.append(view.render().el); return this; } });
var template = require('./default-layer-analysis-view.tpl'); /** * View for an analysis node with a single input * * this.model is expected to be a analysis-definition-node-nodel */ module.exports = cdb.core.View.extend({ initialize: function (opts) { if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required'); if (!opts.layerAnalysisViewFactory) throw new Error('layerAnalysisViewFactory is required'); this._layerDefinitionModel = opts.layerDefinitionModel; this._layerAnalysisViewFactory = opts.layerAnalysisViewFactory; this.model.on('change', this.render, this); }, render: function () { this.clearSubViews(); this.$el.html(template({ id: this.model.id, title: this.model.get('type') })); var view = this._layerAnalysisViewFactory.createView(this.model.sourceIds()[0], this._layerDefinitionModel); this.addView(view); this.$el.append(view.render().el); return this; } });
Use sourceIds instead of hardcoded attribute name
Use sourceIds instead of hardcoded attribute name The source_id attr just happened to work, use the sourceIds method instead
JavaScript
bsd-3-clause
bloomberg/cartodb,codeandtheory/cartodb,CartoDB/cartodb,splashblot/dronedb,bloomberg/cartodb,codeandtheory/cartodb,bloomberg/cartodb,CartoDB/cartodb,CartoDB/cartodb,splashblot/dronedb,bloomberg/cartodb,codeandtheory/cartodb,CartoDB/cartodb,codeandtheory/cartodb,codeandtheory/cartodb,splashblot/dronedb,CartoDB/cartodb,bloomberg/cartodb,splashblot/dronedb,splashblot/dronedb
57a4b691eb7dcc09c6f4f970b6880b6e5c1c2538
src/process/normalizeToPercentage.js
src/process/normalizeToPercentage.js
// @flow import type Series from '../series/Series'; type Config = { key: string }; export default function normalizeToPercentage(config: Config) { const {key} = config; return (series: Series) => { series.preprocess.normalizeToPercentage = true; series.preprocess.stacked = true; series.preprocess.stackType = 'points'; const next = series.mapPoints((point) => { const total = point.reduce((rr, point) => rr + (point[key] || 0), 0); let sum = 0; const nextPoints = point.map(point => { let next = Object.assign({}, point); next.originalValue = next[key]; sum += (next[key] || 0); next[key] = sum / total; return next; }); return nextPoints; }); return next; }; }
// @flow import type Series from '../series/Series'; type Config = { key: string }; export default function normalizeToPercentage(config: Config) { const {key} = config; return (series: Series) => { series.preprocess.normalizeToPercentage = true; series.preprocess.stacked = true; series.preprocess.stackType = 'points'; const next = series.mapPoints((point) => { const total = point.reduce((rr, point) => rr + (point[key] || 0), 0); let sum = 0; const nextPoints = point.map(point => { let next = Object.assign({}, point); next.originalValue = next[key]; next.percentValue = ((next[key] || 0) / total); sum += (next[key] || 0); next[key] = sum / total; return next; }); return nextPoints; }); return next; }; }
Add percentage value to points
Add percentage value to points points contained their ending % position and original decimal value however did not contain a percentage value from the total of the series, this has been added.
JavaScript
mit
bigdatr/pnut,bigdatr/pnut
0dd95707d02673649f113b3553c68b466f3dfdc4
packages/@sanity/core/src/actions/dataset/chooseDatasetPrompt.js
packages/@sanity/core/src/actions/dataset/chooseDatasetPrompt.js
import debug from '../../debug' import promptForDatasetName from './datasetNamePrompt' module.exports = async (context, options = {}) => { const {apiClient, prompt} = context const {message, allowCreation} = options const client = apiClient() const datasets = await client.datasets.list() const hasProduction = datasets.find(dataset => dataset.name === 'production') const datasetChoices = datasets.map(dataset => ({value: dataset.name})) const selected = await prompt.single({ message: message || 'Select dataset to use', type: 'list', choices: allowCreation ? [{value: 'new', name: 'Create new dataset'}, new prompt.Separator(), ...datasetChoices] : datasetChoices }) if (selected === 'new') { debug('User wants to create a new dataset, prompting for name') const newDatasetName = await promptForDatasetName(prompt, { message: 'Name your dataset:', default: hasProduction ? undefined : 'production' }) await client.datasets.create(newDatasetName) return newDatasetName } return selected }
import debug from '../../debug' import promptForDatasetName from './datasetNamePrompt' export default async (context, options = {}) => { const {apiClient, prompt} = context const {message, allowCreation} = options const client = apiClient() const datasets = await client.datasets.list() const hasProduction = datasets.find(dataset => dataset.name === 'production') const datasetChoices = datasets.map(dataset => ({value: dataset.name})) const selected = await prompt.single({ message: message || 'Select dataset to use', type: 'list', choices: allowCreation ? [{value: 'new', name: 'Create new dataset'}, new prompt.Separator(), ...datasetChoices] : datasetChoices }) if (selected === 'new') { debug('User wants to create a new dataset, prompting for name') const newDatasetName = await promptForDatasetName(prompt, { message: 'Name your dataset:', default: hasProduction ? undefined : 'production' }) await client.datasets.create(newDatasetName) return newDatasetName } return selected }
Use ESM default export for dataset prompt
[core] Use ESM default export for dataset prompt
JavaScript
mit
sanity-io/sanity,sanity-io/sanity,sanity-io/sanity,sanity-io/sanity
3aee21ae0a0b376e101861e97431f09cc431a11a
packages/plugins/users-permissions/admin/src/pages/AdvancedSettings/utils/schema.js
packages/plugins/users-permissions/admin/src/pages/AdvancedSettings/utils/schema.js
import * as yup from 'yup'; import { translatedErrors } from '@strapi/helper-plugin'; const URL_REGEX = new RegExp('(^$)|((https?://.*)(d*)/?(.*))'); const schema = yup.object().shape({ email_confirmation_redirection: yup.mixed().when('email_confirmation', { is: true, then: yup .string() .matches(URL_REGEX) .required(), otherwise: yup.string().nullable(), }), email_reset_password: yup .string(translatedErrors.string) .matches(URL_REGEX, translatedErrors.regex) .nullable(), }); export default schema;
import * as yup from 'yup'; import { translatedErrors } from '@strapi/helper-plugin'; const URL_REGEX = new RegExp('(^$)|((.+:\\/\\/.*)(d*)\\/?(.*))'); const schema = yup.object().shape({ email_confirmation_redirection: yup.mixed().when('email_confirmation', { is: true, then: yup .string() .matches(URL_REGEX) .required(), otherwise: yup.string().nullable(), }), email_reset_password: yup .string(translatedErrors.string) .matches(URL_REGEX, translatedErrors.regex) .nullable(), }); export default schema;
Allow all URI schemes for setting reset password page
Allow all URI schemes for setting reset password page
JavaScript
mit
wistityhq/strapi,wistityhq/strapi
77aa85536f93aea8caeb48b7008665ab1477d1c3
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/select-cell.js
src/Oro/Bundle/DataGridBundle/Resources/public/js/datagrid/cell/select-cell.js
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/editor/select-cell-radio-editor' ], function(_, Backgrid, SelectCellRadioEditor) { 'use strict'; var SelectCell; /** * Select column cell. Added missing behaviour. * * @export oro/datagrid/cell/select-cell * @class oro.datagrid.cell.SelectCell * @extends Backgrid.SelectCell */ SelectCell = Backgrid.SelectCell.extend({ /** * @inheritDoc */ initialize: function(options) { if (this.expanded && !this.multiple) { this.editor = SelectCellRadioEditor; } if (options.column.get('metadata').choices) { this.optionValues = []; _.each(options.column.get('metadata').choices, function(value, key) { this.optionValues.push([value, key]); }, this); } else { throw new Error('Column metadata must have choices specified'); } SelectCell.__super__.initialize.apply(this, arguments); } }); return SelectCell; });
define([ 'underscore', 'backgrid', 'orodatagrid/js/datagrid/editor/select-cell-radio-editor' ], function(_, Backgrid, SelectCellRadioEditor) { 'use strict'; var SelectCell; /** * Select column cell. Added missing behaviour. * * @export oro/datagrid/cell/select-cell * @class oro.datagrid.cell.SelectCell * @extends Backgrid.SelectCell */ SelectCell = Backgrid.SelectCell.extend({ /** * @inheritDoc */ initialize: function(options) { if (this.expanded && !this.multiple) { this.editor = SelectCellRadioEditor; } if (options.column.get('metadata').choices) { this.optionValues = []; _.each(options.column.get('metadata').choices, function(value, key) { this.optionValues.push([value, key]); }, this); } else { throw new Error('Column metadata must have choices specified'); } SelectCell.__super__.initialize.apply(this, arguments); this.listenTo(this.model, 'change:' + this.column.get('name'), function() { this.enterEditMode(); this.$el.find('select').uniform(); }); }, /** * @inheritDoc */ render: function() { var render = SelectCell.__super__.render.apply(this, arguments); this.enterEditMode(); return render; }, /** * @inheritDoc */ enterEditMode: function() { if (this.column.get('editable')) { SelectCell.__super__.enterEditMode.apply(this, arguments); } }, /** * @inheritDoc */ exitEditMode: function() { this.$el.removeClass('error'); this.stopListening(this.currentEditor); delete this.currentEditor; } }); return SelectCell; });
Test and merge to master - revert select cell functionality
BB-1315: Test and merge to master - revert select cell functionality
JavaScript
mit
ramunasd/platform,geoffroycochard/platform,trustify/oroplatform,Djamy/platform,trustify/oroplatform,orocrm/platform,orocrm/platform,trustify/oroplatform,ramunasd/platform,orocrm/platform,Djamy/platform,geoffroycochard/platform,Djamy/platform,geoffroycochard/platform,ramunasd/platform
5298747365e5ecc6c15a2e5582da48e76ed34a4c
src/TypeaheadContext.js
src/TypeaheadContext.js
import {noop, pick} from 'lodash'; import createReactContext from 'create-react-context'; import React from 'react'; const TypeaheadContext = createReactContext({ activeIndex: -1, hintText: '', initialItem: null, isOnlyResult: false, onActiveItemChange: noop, onAdd: noop, onInitialItemChange: noop, onMenuItemClick: noop, selectHintOnEnter: false, }); export const withContext = (Component, values) => (props) => ( <TypeaheadContext.Consumer> {(context) => <Component {...props} {...pick(context, values)} />} </TypeaheadContext.Consumer> ); export default TypeaheadContext;
import {noop, pick} from 'lodash'; import createReactContext from 'create-react-context'; import React from 'react'; const TypeaheadContext = createReactContext({ activeIndex: -1, hintText: '', initialItem: null, isOnlyResult: false, onActiveItemChange: noop, onAdd: noop, onInitialItemChange: noop, onMenuItemClick: noop, selectHintOnEnter: false, }); export const withContext = (Component, values) => { // Note: Use a class instead of function component to support refs. /* eslint-disable-next-line react/prefer-stateless-function */ return class extends React.Component { render() { return ( <TypeaheadContext.Consumer> {(context) => ( <Component {...this.props} {...pick(context, values)} /> )} </TypeaheadContext.Consumer> ); } }; }; export default TypeaheadContext;
Use class instead of stateless component in `withContext`
Use class instead of stateless component in `withContext`
JavaScript
mit
ericgio/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead,ericgio/react-bootstrap-typeahead
5f9a7836146062c94ce08b98db2705c2bab10e34
Kwf_js/Viewport.js
Kwf_js/Viewport.js
Kwf.ViewportWithoutMenu = Ext2.extend(Ext2.Viewport, { layout: 'fit', mabySubmit: function(cb, options) { var ret = true; this.items.each(function(i) { if (i.mabySubmit && !i.mabySubmit(cb, options)) { ret = false; return false; //break each } }, this); return ret; } }); Kwf.Viewport = Ext2.extend(Kwf.ViewportWithoutMenu, { initComponent: function() { Kwf.menu = Ext2.ComponentMgr.create({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.items.push({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.layout = 'border'; Kwf.Viewport.superclass.initComponent.call(this); } });
Kwf.ViewportWithoutMenu = Ext2.extend(Ext2.Viewport, { layout: 'fit', mabySubmit: function(cb, options) { var ret = true; this.items.each(function(i) { if (i.mabySubmit && !i.mabySubmit(cb, options)) { ret = false; return false; //break each } }, this); return ret; } }); Kwf.Viewport = Ext2.extend(Kwf.ViewportWithoutMenu, { initComponent: function() { Kwf.menu = Ext2.ComponentMgr.create({ xtype: 'kwf.menu', region: 'north', height: 30 }); this.items.push(Kwf.menu); this.layout = 'border'; Kwf.Viewport.superclass.initComponent.call(this); } });
Fix Menu reload after re-login
Fix Menu reload after re-login This bug existed for ages. After re-login there always was this 'this.tr is undefined' error. Problem was that two menu objects where created and the one actually rendered was not set to Kwf.menu. That caused the reload for the wrong object.
JavaScript
bsd-2-clause
nsams/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework,kaufmo/koala-framework,koala-framework/koala-framework,kaufmo/koala-framework,nsams/koala-framework,nsams/koala-framework
3ce6ed46cb1da34e631abc6bda5fd9f15ae4f53a
html/main.js
html/main.js
var ProtoBuf = dcodeIO.ProtoBuf; var Builder = ProtoBuf.loadProtoFile("proto/ClientMessage.proto"); ProtoBuf.loadProtoFile("proto/Login.proto", Builder); var Message = Builder.build("msg"); var ClientMessage = Message.ClientMessage; var LoginMessage = Message.Login; var loginMsg = new LoginMessage("[email protected]","secret"); var clientMsg = new ClientMessage({ "msgType" : "LoginType", "login":{ "email":"[email protected]", "password":"secret"}}); var ws; window.onload=function(){ ws=new WebSocket("ws://localhost:8080/index"); ws.onmessage = function(evt) { console.log(evt.data); var loginFormSection = document.getElementById("loginFormSection"); if(evt.data == "AUTHPLS") { loginFormSection.style.display = "block"; } if(evt.data == "AUTHOKTHX") { loginFormSection.style.display = "none"; document.getElementById("portal").style.display = "block"; } }; ws.onopen=function(evt){ // ws.send("Hello"); ws.send(clientMsg.toArrayBuffer()); }; }; window.onclose=function(){ ws.close(); }; function loginSubmitEvent () { var email = document.getElementById("loginEmail").value; var password = document.getElementById("loginPassword").value; ws.send(email + ":" + password); }
var ProtoBuf = dcodeIO.ProtoBuf; var Builder = ProtoBuf.loadProtoFile("proto/ClientMessage.proto"); ProtoBuf.loadProtoFile("proto/Login.proto", Builder); var Message = Builder.build("msg"); var ClientMessage = Message.ClientMessage; var LoginMessage = Message.Login; var loginMsg = new LoginMessage("[email protected]","secret"); var clientMsg = new ClientMessage({ "msgType" : "LoginType", "login":{ "email":"[email protected]", "password":"secret"}}); var ws; window.onload=function(){ ws=new WebSocket("ws://localhost:8080/index"); ws.onmessage = function(evt) { console.log(evt.data); var loginFormSection = document.getElementById("loginFormSection"); if(evt.data == "AUTHPLS") { loginFormSection.style.display = "block"; } if(evt.data == "AUTHOKTHX") { loginFormSection.style.display = "none"; document.getElementById("portal").style.display = "block"; } }; ws.onopen=function(evt){ // ws.send("Hello"); for(i = 0; i < 1000; i++) { ws.send(clientMsg.toArrayBuffer()); } }; }; window.onclose=function(){ ws.close(); }; function loginSubmitEvent () { var email = document.getElementById("loginEmail").value; var password = document.getElementById("loginPassword").value; ws.send(email + ":" + password); }
Send 1k messages on startup for testing.
Send 1k messages on startup for testing.
JavaScript
mit
mjgerdes/cg,mjgerdes/cg,mjgerdes/cg,mjgerdes/cg
d7505d1c5497192c8768bf5da3a0f8d585717241
src/server/db/mongoHelper.js
src/server/db/mongoHelper.js
const mongoose = require('mongoose'); const Grid = require('gridfs-stream'); const mongoURI = process.env.MONGODB_URI || process.env.MONGOHQ_URL; mongoose.Promise = Promise; mongoose.connect(mongoURI, { useMongoClient: true }); const mongoHelper = { init() { const connection = mongoose.createConnection(mongoURI, { useMongoClient: true }); connection.once('open', () => { mongoHelper.gridfs = Grid(connection.db, mongoose.mongo); }); }, gridfs: undefined, }; module.exports = mongoHelper;
const mongoose = require('mongoose'); const Grid = require('gridfs-stream'); const mongoURI = process.env.MONGODB_URI || process.env.MONGOHQ_URL; mongoose.Promise = Promise; mongoose.connect(mongoURI); const mongoHelper = { init() { const connection = mongoose.createConnection(mongoURI); connection.once('open', () => { mongoHelper.gridfs = Grid(connection.db, mongoose.mongo); }); }, gridfs: undefined, }; module.exports = mongoHelper;
Revert "fix deprecated mongoose methods"
Revert "fix deprecated mongoose methods" This reverts commit 4dce797
JavaScript
mit
r3dDoX/geekplanet,r3dDoX/geekplanet,r3dDoX/geekplanet
f69040c9d2b21491e33a9676a68ce20d97787ab4
test/load.js
test/load.js
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"); require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = null; files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
process.env.TZ = "America/Los_Angeles"; var smash = require("smash"), jsdom = require("jsdom"); require("./XMLHttpRequest"); module.exports = function() { var files = [].slice.call(arguments).map(function(d) { return "src/" + d; }), expression = "d3", sandbox = {Date: Date}; // so we can use deepEqual in tests files.unshift("src/start"); files.push("src/end"); function topic() { smash.load(files, expression, sandbox, this.callback); } topic.expression = function(_) { expression = _; return topic; }; topic.document = function(_) { var document = jsdom.jsdom("<html><head></head><body></body></html>"); // Monkey-patch createRange support to JSDOM. document.createRange = function() { return { selectNode: function() {}, createContextualFragment: jsdom.jsdom }; }; sandbox = { console: console, XMLHttpRequest: XMLHttpRequest, document: document, window: document.createWindow(), setTimeout: setTimeout, clearTimeout: clearTimeout, Date: Date // so we can override Date.now in tests, and use deepEqual }; return topic; }; return topic; }; process.on("uncaughtException", function(e) { console.trace(e.stack); });
Fix time tests by adding Date to sandbox.
Fix time tests by adding Date to sandbox. Since tests are now run in their own sandbox, assert.deepEqual was not properly testing the returned Date objects for equality, as they weren't instances of the same Date class used by the test itself, causing type inference to fail. It was always returning true, even for different dates.
JavaScript
bsd-3-clause
josealbertohm/d3,nishant8BITS/d3,Limky/d3,Jonathan-S-Phillips/d3,welloncn/d3,azilnoor/d3,mujiatong/d3,lijanele/d3,xiaojie123/d3,Sigfried/d3,madlen99/d3,jordancheah/d3,pradeeptas/d3,ornelaxh/d3,zhoux10/d3,Vardhan17/d3,zzzzw/d3,makenti/d3,Ali925/d3,aihua/d3,ishang27/d3,li0t/d3,nicgallardo/d3,mountwe/d34kpor,w124384389/d3,clarinete/d3,supriyantomaftuh/d3,ABaldwinHunter/d3,liang42hao/d3,kewal07/d3,whoinlee/d3,CallAnotherBarry/d3,burakkp/d3,kpcorda/d3,fsaglam2002/d3,ThinkedCoder/d3,abhuzz/d3,mainelander/d3,lunyang/d3,ssrx17/d3,Eric-Zhong/d3,atsolakid/d3,nonconforme/d3,lauraweaver/d3,idkwim/d3,angeliaz/d3,s-a-r-id/d3,JunichiWatanuki/d3,bestwpw/d3,christianevans214/d3,tempbottle/d3,standino/go-easy-portal,larskris/d3,kjeldandersen/d3,codingang/d3-1,charlesDADI/d3,danforthdesign/d3,geoff111/d3,s-a-r-id/d3,ZhuLiangwh/d3,roma07/d3,n1n9-jp/d3,aljachimiak/d3,nitishmadhukar/d3,aluck19/d3,house-fiction/d3,sk187/d3,yuanzhiqian/d3,jessiejea/d3,fredlang/d3,hqren/d3,smartinsantos/d3,MeganBeneteau/d3,RacingTadpole/d3,HardlyHaki/d3,lihanhui/d3,Petah/d3,dbirchak/d3,agarbuno/d3,okierie/d3,kaijie/d3,keyanzhang/d3,halcyonstar/d3,marianbida/d3,evdevgit/d3,vp2177/d3,buzybee83/d3,fatmazaman/d3,Petermuturi/d3,ABaldwinHunter/d3-classic,humanrelationships/d3,AromaR/d3,lukeskip/d3,cbtpro/d3,house-fiction/d3,supriyantomaftuh/d3,wangjun/d3,reynoldqi/TestFirst,ammula88/d3,sajeetharan/d3,Hbl15/d3,Ahmad-Hilali/d3,shaximinion/d3,DagoCIMA/Prueba1,kyroskoh/d3,berlynhubler/d3,keyanzhang/d3,Hbl15/d3,johnnyg3p/d3,ammula88/d3,ishang27/d3,leeleo26/d3,yuhualingfeng/d3,emirhartato/d3,kidaa/d3,wallmarkets/d3,jakimhartford/d3,stity/d3,radovanx/d3,nicksrandall/d3,kyoungchinseo/d3,GibbleBots/d3,xujie-nm/d3,npmcomponent/mbostock-d3,makenti/d3,hillaryskye/d3,behzad88/d3,AromaR/d3,AndBicScadMedia/d3,xiaochen0620/d3,hgarnelo/d3,anusornc/d3,markpj1/d3,Limky/d3,dongnhut/d3,ilovezy/d3,jessiejea/d3,trinath3/d3,ayshaabbas/d3,mountwe/d34kpor,johnochs/d3,radovanx/d3,JungMinu/d3,Acker2015/d3,allenjin/d3,8DTechnologies/d3,nbende/d3,burakkp/d3,ilo10/d3,Jonham/d3,onlyyouandty/d3,lypzln/d3,triggerThis/d3,ralic/d3,leohmoraes/d3,studiowangfei/d3,AlpinHologramm/d3,mendax-grip/d3,Teino1978-Corp/Teino1978-Corp-d3,woshiniuren/d3,smartpcr/d3,joehannes-libs/d3,liang42hao/d3,evdevgit/d3,chaoallsome/d3,salambolog/d3,tempbottle/d3,Sachin-Ganesh/d3,onlyyouandty/d3,okierie/d3,Henrilin28/d3,fatmazaman/d3,HomeMango/d3,Ali925/d3,XueQian/d3,nitishmadhukar/d3,UpstatePedro/d3,m-br/d3,iamcap/d3,Shuffguy/d3,VirosaLi/d3,guangyue/d3,mlawry/d3,nheinzer1210/d3,reiaaoyama/d3,batnasan06/d3,UmarMughal/d3,gyenumula/d3,Ahmad-Hilali/d3,nishant8BITS/d3,moodboom/d3,youprofit/d3,aihua/d3,edktsnr/d3,supzann3/d3,KevinMarkVI/d3,Petermuturi/d3,nirajvora/d3,JeebsM/d3,nbende/d3,1174751315/d3,ananya77041/d3,mssjtxwd/d3,guangyue/d3,Shuffguy/d3,2947721120/redolent-hockeypuck,mingyaaaa/d3,emmanuelq2/d3,MilkXin/dingTalk,monoc44/d3,UpstatePedro/d3,latur19318/d3,2947721120/redolent-hockeypuck,chenflat/d3,boshika/d3,peterwu8/d3,allenjin/d3,gorcz/d3,UmarMughal/d3,itxd/d3,xuzhaokui/d3,monoc44/d3,larskris/d3,taylorhxu/d3,salamer/d3,aigouzz/d3,qodbtn41/d3,JungMinu/d3,VirosaLi/d3,Simon-Lau/d3,juliaty/d3,moodboom/d3,nilqed/d3,eaglesjava/d3,leitzler/d3,smartpcr/d3,jordancheah/d3,ABaldwinHunter/d3,Eric-Zhong/d3,FangMath/d3,fredlang/d3,ilovezy/d3,patrickkillalea/d3,macressler/d3,kiwizhang/d3,chenflat/d3,maureenwaitherero/d3,MartinDavila/d3,macressler/d3,lukeskip/d3,hqren/d3,kx1911/d3,gorcz/d3,jakimhartford/d3,lovewitty/d3,sigma-random/d3,3mao/d3,RCGTDev/d3,shashi-dokania/d3,polzak/d3,folpindo/d3,LikeGit-2013/d3,JoaquinSiabra/d3,marianbida/d3,kaijie/d3,emmanuelq2/d3,trankmichael/d3,Wombatpm/d3,sunios/d3,awdesch/d3,imshibaji/d3,chiu/d3,LikeGit-2013/d3,emirhartato/d3,rlugojr/d3,supzann3/d3,Lchchen/d3,wallmarkets/d3,amccartney/d3,Sachin-Ganesh/d3,ansjcy/d3,chewett/d3,kitlomerc/d3,FredrikAhlberg/IconLiveD3.js,DataVizApril/d3,stefwalter/d3,darshanhs90/d3,erhanBLC/d3,zicouser/d3,fsaglam2002/d3,mattcale7/d3,studiowangfei/d3,lauraweaver/d3,markengelstad/d3,madlen99/d3,teefresh/d3,ansjcy/d3,vp2177/d3,cool-Blue/d3,amccartney/d3,suezse/d3,aaron-goshine/d3,anant10/dinto,sysexits/d3,aleksa000777/d3,mhsmith/d3,nicksrandall/d3,li0t/d3,smartinsantos/d3,MartinDavila/d3,alex-zhang/d3,Jonekee/d3,christianevans214/d3,JoaquinSiabra/d3,rubenv/d3,Simon-Lau/d3,oanaradulescu/d3,boshika/d3,XiqianZ/d3,joycedelatorre/d3,excelwang/d3,chaoallsome/d3,clayzermk1/d3,MeganBeneteau/d3,trinath3/d3,jeanpan/d3,ZhuLiangwh/d3,datawrapper/d3-light,imshibaji/d3,3mao/d3,chen-ben/d3,johnochs/d3,2947721120/squealing-octo-capsicum,alexgarciac/d3,forkmsrini/d3,quevedin/d3,n1n9-jp/d3,xc145214/d3,tessafallon/nypl-pg,jsan4christ/d3,yuanzhiqian/d3,bestwpw/d3,10000TB/d3,welloncn/d3,Tinysymphony/d3,CrandellWS/d3,uetsujitomoya/d3,dongnhut/d3,dogobox/d3,ayadoguchi/d3_practice,kevinresol/d3,CallAnotherBarry/d3,kx1911/d3,nheinzer1210/d3,dushmis/d3,caseytrombley/d3,10000TB/d3,kingland/d3,Acker2015/d3,hyrole/d3,xuzhaokui/d3,oanaradulescu/d3,kpcorda/d3,joycedelatorre/d3,iyogeshjoshi/d3,sysexits/d3,danforthdesign/d3,abhuzz/d3,suezse/d3,hillaryskye/d3,Petah/d3,mssjtxwd/d3,kitlomerc/d3,matheosu/d3,FangMath/d3,salamer/d3,ClaireRutkoske/d3,GibbleBots/d3,lrinili/d3,abgaryanharutyun/d3,darshanhs90/d3,iorikiir/d3,datawrapper/d3-light,angeliaz/d3,ChaofengZhou/d3,alex-zhang/d3,DagoCIMA/Prueba1,ykominami/d3,littlstar/d3,awdesch/d3,2947721120/squealing-octo-capsicum,xujie-nm/d3,nirajvora/d3,kyoungchinseo/d3,caseytrombley/d3,lunyang/d3,batnasan06/d3,dieface/d3,jsan4christ/d3,elpoisterio/d3,ssrx17/d3,krystism/d3,Ossehoht/d3,hkjels/d3,elpoisterio/d3,roma07/d3,kjeldandersen/d3,larskotthoff/d3,iyogeshjoshi/d3,mssyogi/d3,aleksa000777/d3,kennethd/d3,littlstar/d3,ABaldwinHunter/d3-classic,manashmndl/d3,amorwilliams/d3,idkwim/d3,leeleo26/d3,bqevin/d3,kbarnhart/d3,jeanpan/d3,mlawry/d3,1174751315/d3,navjotahuja92/d3,okcd00/d3,aigouzz/d3,datawrapper/d3-light,davidvmckay/d3,buzybee83/d3,KevinMarkVI/d3,woshiniuren/d3,fsanchezro/d3,rohittiwarirvt/d3,wangjun/d3,zicouser/d3,leohmoraes/d3,elkingtonmcb/d3,elancom/d3,uetsujitomoya/d3,julialintern/d3,latur19318/d3,danbwhiting/d3,Jonham/d3,Jonathan-S-Phillips/d3,chen-ben/d3,Naomifh/moboshock,nilqed/d3,kyroskoh/d3,nirmalks/d3,josealbertohm/d3,hyrole/d3,itxd/d3,ee08b397/d3,diazmartin/d3,mssyogi/d3,18Shubhamgupta/d3,codingang/d3-1,amorwilliams/d3,xc145214/d3,overmind1980/d3,bsipocz/d3,folpindo/d3,danbwhiting/d3,Lyoneidas/d3,jamesgarfield/d3,teefresh/d3,salambolog/d3,Jonekee/d3,witcxc/d3,Jai-Chaudhary/d3,alexgarciac/d3,okcd00/d3,aljachimiak/d3,whoinlee/d3,18Shubhamgupta/d3,standino/go-easy-portal,standino/go-easy-portal,d3/d3,halcyonstar/d3,lovewitty/d3,AndBicScadMedia/d3,Lyoneidas/d3,leitzler/d3,AlpinHologramm/d3,cool-Blue/d3,mattcale7/d3,jamesblunt/d3,aluck19/d3,DataVizApril/d3,ornelaxh/d3,mayblue9/d3,alex179ohm/d3,joehannes-libs/d3,sigma-random/d3,SystemicEmotions/d3,elkingtonmcb/d3,kevinresol/d3,larskotthoff/d3,kewal07/d3,sk187/d3,XueQian/d3,clarinete/d3,yuhualingfeng/d3,Sigfried/d3,qqqlllyyyy/d3,alex179ohm/d3,ThinkedCoder/d3,qodbtn41/d3,ee08b397/d3,diazmartin/d3,atsolakid/d3,stefanom/d3,patrickkillalea/d3,esparza83/d3,kaktus40/d3,julialintern/d3,standino/go-easy-portal,stefwalter/d3,youprofit/d3,hubandbob/d3,zhoux10/d3,kennethd/d3,edktsnr/d3,JunichiWatanuki/d3,jamesgarfield/d3,shaximinion/d3,ferrero-zhang/d3,omarbenites/d3,mainelander/d3,zzzzw/d3,nicgallardo/d3,Teino1978-Corp/Teino1978-Corp-d3,JeebsM/d3,SystemicEmotions/d3,RCGTDev/d3,ClaireRutkoske/d3,quevedin/d3,rubenv/d3,m4s0/d3,sunios/d3,dogobox/d3,v11yu/d3,ptkeller/d3,omarbenites/d3,kidaa/d3,HardlyHaki/d3,dbirchak/d3,manashmndl/d3,polzak/d3,markpj1/d3,ayshaabbas/d3,azilnoor/d3,KehindeAyanleye/d3,kbarnhart/d3,nirmalks/d3,jling90/d3,berlynhubler/d3,reynoldqi/TestFirst,mingyaaaa/d3,krystism/d3,nonconforme/d3,overmind1980/d3,geoff111/d3,mhsmith/d3,juliaty/d3,abgaryanharutyun/d3,Tinysymphony/d3,pradeeptas/d3,clayzermk1/d3,m4s0/d3,mayblue9/d3,xiaojie123/d3,anant10/dinto,bqevin/d3,hgarnelo/d3,esparza83/d3,lypzln/d3,vinicius5581/d3,sajeetharan/d3,stefanom/d3,dieface/d3,maureenwaitherero/d3,trankmichael/d3,lijanele/d3,ralic/d3,hkjels/d3,shashi-dokania/d3,v11yu/d3,Lchchen/d3,aaronhoffman/d3,hubandbob/d3,qqqlllyyyy/d3,vinicius5581/d3,Yelp/d3,lihanhui/d3,matheosu/d3,ferrero-zhang/d3,bsipocz/d3,rohittiwarirvt/d3,fsanchezro/d3,reiaaoyama/d3,staceb/d3,jamesblunt/d3,402332509/d3,Vardhan17/d3,jling90/d3,Genie77998/d3,taylorhxu/d3,ChaofengZhou/d3,triggerThis/d3,ptkeller/d3,peterwu8/d3,elancom/d3,anusornc/d3,markengelstad/d3,futuraprime/d3,XiqianZ/d3,Ossehoht/d3,xudongcamsys/d3,Genie77998/d3,ykominami/d3,mujiatong/d3,402332509/d3,iorikiir/d3,CrandellWS/d3,KehindeAyanleye/d3,futuraprime/d3,stity/d3,w124384389/d3,forkmsrini/d3,behzad88/d3,kiwizhang/d3,DaEunPark/d3,excelwang/d3,lrinili/d3,ananya77041/d3,cbtpro/d3,gyenumula/d3,tessafallon/nypl-pg,8DTechnologies/d3,HomeMango/d3,tessafallon/nypl-pg,xiaochen0620/d3,charlesDADI/d3,m-br/d3,chiu/d3,ilo10/d3,mendax-grip/d3,johnnyg3p/d3,suryasingh/d3
3425cb4aedf0a0c2160ea63f550bfd0f0de6d19d
ghost/admin/routes/editor.js
ghost/admin/routes/editor.js
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var EditorRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['editor'], controllerName: 'posts.post', model: function (params) { return this.store.find('post', params.post_id); } }); export default EditorRoute;
import styleBody from 'ghost/mixins/style-body'; import AuthenticatedRoute from 'ghost/routes/authenticated'; var EditorRoute = AuthenticatedRoute.extend(styleBody, { classNames: ['editor'], controllerName: 'posts.post', model: function (params) { var post = this.store.getById('post', params.post_id); if (post) { return post; } return this.store.filter('post', { status: 'all' }, function (post) { return post.get('id') === params.post_id; }).then(function (records) { return records.get('firstObject'); }); } }); export default EditorRoute;
Fix Editor/:postId 404 on draft
Fix Editor/:postId 404 on draft closes #2857 - in EditorRoute, get model from the datastore if it's there - if page is refreshed, get model from `/posts` API with `{status: 'all'}`
JavaScript
mit
TryGhost/Ghost,TryGhost/Ghost,TryGhost/Ghost
116808327ac226934af7cd48ac8336d16e602af7
addon/mixins/component-lookup-mixin.js
addon/mixins/component-lookup-mixin.js
import Ember from 'ember'; export default Ember.Mixin.create({ componentFor(name, owner) { let component = this._super(name, owner); // Ensure components are always managed my the container and thus have a connection to their styles if (!component) { owner.register(`component:${name}`, Ember.Component); component = this._super(name, owner); } return component; } });
import Ember from 'ember'; export default Ember.Mixin.create({ componentFor(name, owner) { let component = this._super(name, owner); // Ensure components are always managed my the container and thus have a connection to their styles if (!component) { if (owner.register) { owner.register(`component:${name}`, Ember.Component); } else { owner._registry.register(`component:${name}`, Ember.Component); // Support for Ember 2.0.X } component = this._super(name, owner); } return component; } });
Fix error in Ember 2.0
Fix error in Ember 2.0
JavaScript
mit
salsify/ember-css-modules,salsify/ember-css-modules
49d0f365e0a2da4ab9ba2c571806229052a8cc83
app/webpack/entities/circleBurger/Door.js
app/webpack/entities/circleBurger/Door.js
import NormalDoor from 'entities/Door'; import state from 'state'; import finish from 'finish'; import action from 'action'; import { changeScene } from 'currentScene'; import entrance from 'scenes/circleBurger/entrance'; export default class Door extends NormalDoor { actions() { return [ action(this.actionName, () => { changeScene(this.destination); state.currentTime.add(Math.floor((Math.random() * 5) + 1), 'minutes'); }), action("Lock the door. (This ends the game. You can't go back.)", () => { state.doorLocked = true; if (this.destination === entrance) { state.lockedIn = true; } if (state.currentTime.isBefore(state.closingTime.clone().subtract(5, 'minutes'))) { state.closedEarly = true; } if (state.currentTime.isAfter( state.closingTime.clone().add(1, 'hour') )) { state.closedLate = true; } finish(); }) ]; } };
import NormalDoor from 'entities/Door'; import state from 'state'; import finish from 'finish'; import action from 'action'; import { changeScene } from 'currentScene'; import entrance from 'scenes/circleBurger/entrance'; export default class Door extends NormalDoor { actions() { return [ action(this.actionName, () => { changeScene(this.destination); state.currentTime.add(Math.floor((Math.random() * 5) + 1), 'minutes'); }), action("Lock the door. (This ends the game. You can't go back.)", () => { if(confirm("Closing the Circle Burger ends the day.\n\nAre you sure you've done enough to keep your job?")) { state.doorLocked = true; if (this.destination === entrance) { state.lockedIn = true; } if (state.currentTime.isBefore(state.closingTime.clone().subtract(5, 'minutes'))) { state.closedEarly = true; } if (state.currentTime.isAfter( state.closingTime.clone().add(1, 'hour') )) { state.closedLate = true; } finish(); } }) ]; } };
Add confirm on end game door
Add confirm on end game door
JavaScript
mit
TEAMBUTT/LD35
a5d2080045c34b23e53b3da5798b806293cd4d9b
core/app/assets/javascripts/backbone/views/fact_relation_view.js
core/app/assets/javascripts/backbone/views/fact_relation_view.js
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { this.$el.fadeOut('fast', function() { this.$el.remove(); }); }, render: function() { this.$el.html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); $('a.supporting',this.$el).tooltip({'title':"This is relevant"}); $('a.weakening',this.$el).tooltip({'title':"This is not relevant", 'placement':'bottom'}); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { var self = this; self.$el.animate({"background-color": "#ffffe1"}, {duration: 2000, complete: function() { $(this).animate({"background-color": "#ffffff"}, 2000); }}); } });
window.FactRelationView = Backbone.View.extend({ tagName: "li", className: "fact-relation", events: { "click .relation-actions>.weakening": "disbelieveFactRelation", "click .relation-actions>.supporting": "believeFactRelation" }, initialize: function() { this.useTemplate('fact_relations','fact_relation'); this.model.bind('destroy', this.remove, this); this.model.bind('change', this.render, this); }, remove: function() { this.$el.fadeOut('fast', function() { this.$el.remove(); }); }, render: function() { $('a.weakening',this.$el).tooltip('hide'); $('a.supporting',this.$el).tooltip('hide'); this.$el.html(Mustache.to_html(this.tmpl, this.model.toJSON(), this.partials)).factlink(); $('a.supporting',this.$el).tooltip({'title':"This is relevant"}); $('a.weakening',this.$el).tooltip({'title':"This is not relevant", 'placement':'bottom'}); return this; }, disbelieveFactRelation: function() { this.model.disbelieve(); }, believeFactRelation: function() { this.model.believe(); }, highlight: function() { var self = this; self.$el.animate({"background-color": "#ffffe1"}, {duration: 2000, complete: function() { $(this).animate({"background-color": "#ffffff"}, 2000); }}); } });
Make the tooltips hide when they are clicked.
Make the tooltips hide when they are clicked.
JavaScript
mit
daukantas/factlink-core,Factlink/factlink-core,daukantas/factlink-core,Factlink/factlink-core,Factlink/factlink-core,Factlink/factlink-core,daukantas/factlink-core,daukantas/factlink-core
c1c138acb4026af9173008dbf037f97fe4f19b9e
src/AppBundle/Resources/assets/javascripts/sticky.js
src/AppBundle/Resources/assets/javascripts/sticky.js
/*jshint browser: true */ (function () { "use strict"; var root = this, $ = root.jQuery, body = $('body'); if (typeof GOVUK === 'undefined') { root.GOVUK = {}; } var StickyHeader = function(element) { this.top = $(element).offset().top - 30; this.addEventHandlers(); }; StickyHeader.prototype.addEventHandlers = function () { this.windowScrollHandler = this.getWindowScrollEventHandler(); window.onscroll = this.windowScrollHandler; }; StickyHeader.prototype.getWindowScrollEventHandler = function () { return function (e) { this.handleWindowScroll($(e.target)); }.bind(this); }; StickyHeader.prototype.handleWindowScroll = function () { if (window.pageYOffset >= this.top) { body.addClass('fixed'); } else { body.removeClass('fixed'); } }; root.GOVUK.StickyHeader = StickyHeader; }).call(this);
/*jshint browser: true */ (function () { "use strict"; var root = this, $ = root.jQuery, body = $('body'), mobileSafari = navigator.userAgent.match(/(iPod|iPhone|iPad)/) && navigator.userAgent.match(/AppleWebKit/); if (typeof GOVUK === 'undefined') { root.GOVUK = {}; } var StickyHeader = function(element) { this.wrapper = $(element); this.top = $(element).offset().top - 30; this.addEventHandlers(); }; StickyHeader.prototype.addEventHandlers = function () { this.windowScrollHandler = this.getWindowScrollEventHandler(); document.addEventListener("scroll", this.windowScrollHandler, false); }; StickyHeader.prototype.getWindowScrollEventHandler = function () { return function (e) { this.handleWindowScroll($(e.target)); }.bind(this); }; StickyHeader.prototype.handleWindowScroll = function () { if (window.pageYOffset >= this.top) { body.addClass('fixed'); // Mobile safari hides fixed elements when the keyboard is shown so use // absolute instead. if (mobileSafari) { this.wrapper.css({ position: 'absolute', top: window.pageYOffset + 'px', left: 0 }); } } else { body.removeClass('fixed'); if (mobileSafari) { this.wrapper.css({ position: 'static' }); } } }; root.GOVUK.StickyHeader = StickyHeader; }).call(this);
Fix issue with Safari on IOS which caused the title to be hidden when entering data.
Fix issue with Safari on IOS which caused the title to be hidden when entering data.
JavaScript
mit
ministryofjustice/opg-digi-deps-client,ministryofjustice/opg-digi-deps-client,ministryofjustice/opg-digi-deps-client,ministryofjustice/opg-digi-deps-client
222bf732b58e1f12b78c0c3aa2671d8993be8908
http/assets/js/aside-menu.js
http/assets/js/aside-menu.js
'use strict'; /** * Open and close button for aside-menu */ $('show-aside-button').addEvent('click', function (event) { // Get the aside current margin-left as integer var asideMargin = parseInt($('aside-menu').getStyle('margin-left')); /** * Change aside margin to show or hide it */ $('aside-menu').setStyle( 'margin-left', asideMargin === 0 ? '-18rem' : '0rem' ); /** * Change content width do adjust to fit on the side of aside */ $('content').setStyle( 'width', asideMargin === 0 ? '100%' : 'calc(100% - 17rem)' ); });
'use strict'; /** * Change aside margin to show it * Change content width do adjust to fit on the side of aside */ var showAside = (function() { $('aside-menu').setStyle('margin-left', '0rem'); $('content').setStyle('width', 'calc(100% - 17rem)'); }); /** * Change aside margin to hide it * Change content width do adjust to fit on the side of aside */ var hideAside = (function() { $('aside-menu').setStyle('margin-left', '-18rem'); $('content').setStyle('width', '100%'); }); /** * Open and close button for aside-menu */ $('show-aside-button').addEvent('click', function (event) { // Get the aside current margin-left as integer var asideMargin = parseInt($('aside-menu').getStyle('margin-left')); if (0 === asideMargin) { hideAside(); return true; } showAside(); }); /** * Catch all clicks on the content element, then check if we should close the * aside or not. */ $('content').addEvent('click', function (event) { var asideButtonVisible = $('show-aside-button').getStyle('display') === 'inline-block'; var asideVisible = parseInt($('aside-menu').getStyle('margin-left')) === 0; if (false === asideButtonVisible && false === asideVisible) { showAside(); } if (true === asideButtonVisible && true === asideVisible) { hideAside(); } });
Refactor and other ways to close the aside
Refactor and other ways to close the aside
JavaScript
isc
etu/0bRSS,etu/0bRSS,etu/0bRSS
2c5953f6f7cb1c20ccada40ad3f41915b0e29c98
npm-depends.js
npm-depends.js
#!/bin/env node 'use strict'; var agent = require('superagent'); var program = require('commander'); var semver = require('semver'); var name, version; program .version(require('./package.json').version) .arguments('<name> <version>') .action(function (name_, version_) { name = name_; version = version_; }) .parse(process.argv); // TODO shouldn't be needed, probably a bug in commander if (!name) program.missingArgument('name'); if (!semver.valid(version)) { console.error('invalid version number: ' + version); process.exit(1); } var encodedName = encodeURIComponent(name); var npmURL = 'https://skimdb.npmjs.com/registry/_design/app/_view/dependentVersions?startkey=%5B%22' + encodedName + '%22%5D&endkey=%5B%22' + encodedName + '%22%2C%7B%7D%5D&reduce=false'; agent.get(npmURL) .set('Accept', 'application/json') .end(function (error, response) { if (error) { throw error; } var packages = response.body.rows.filter(function (pack) { return semver.satisfies(version, pack.key[1]); }).map(function (pack) { return pack.id; }); if (packages.length) { console.log(packages.join('\n')); } });
#!/usr/bin/env node 'use strict'; var agent = require('superagent'); var program = require('commander'); var semver = require('semver'); var name, version; program .version(require('./package.json').version) .arguments('<name> <version>') .action(function (name_, version_) { name = name_; version = version_; }) .parse(process.argv); // TODO shouldn't be needed, probably a bug in commander if (!name) program.missingArgument('name'); if (!semver.valid(version)) { console.error('invalid version number: ' + version); process.exit(1); } var encodedName = encodeURIComponent(name); var npmURL = 'https://skimdb.npmjs.com/registry/_design/app/_view/dependentVersions?startkey=%5B%22' + encodedName + '%22%5D&endkey=%5B%22' + encodedName + '%22%2C%7B%7D%5D&reduce=false'; agent.get(npmURL) .set('Accept', 'application/json') .end(function (error, response) { if (error) { throw error; } var packages = response.body.rows.filter(function (pack) { return semver.satisfies(version, pack.key[1]); }).map(function (pack) { return pack.id; }); if (packages.length) { console.log(packages.join('\n')); } });
Correct shebang to use /usr/bin/env node.
Correct shebang to use /usr/bin/env node. /bin/env is not the usual location for the shebang line. Instead use /usr/bin/env.
JavaScript
mit
targos/npm-depends
fa59afebde57aff27c919e65222815b6497db8da
hyp-content-for.js
hyp-content-for.js
angular.module("hypContentFor", []) .constant("HYP_CONTENT_FOR_IDS", [ ]) .directive("content", function (HYP_CONTENT_FOR_IDS) { return { scope: { "for": "@" }, transclude: true, controller: function ($scope, $transclude) { HYP_CONTENT_FOR_IDS[$scope["for"]] = $transclude(); } }; }) .directive("yield", function ($interval, HYP_CONTENT_FOR_IDS) { return { scope: { to: "@" }, link: function (scope, elem) { interval = null; repeatFn = function () { content = HYP_CONTENT_FOR_IDS[scope.to]; if (content) { $interval.cancel(interval); } else { return; } elem.replaceWith(content); } repeatFn(); interval = $interval(repeatFn, 100, 9); } }; });
angular.module("hypContentFor", []) .value("HYP_CONTENT_FOR_IDS", { }) .directive("content", function () { return { scope: { "for": "@" }, transclude: true, controller: function ($scope, $transclude, HYP_CONTENT_FOR_IDS) { HYP_CONTENT_FOR_IDS[$scope["for"]] = $transclude(); } }; }) .directive("yield", function ($interval, HYP_CONTENT_FOR_IDS) { return { scope: { to: "@" }, link: function (scope, elem) { interval = null; watchFn = function () { return HYP_CONTENT_FOR_IDS[scope.to]; }; scope.$watch(watchFn, function (newValue) { elem.empty(); elem.append(newValue); }); } }; });
Watch for changes on HYP_CONTENT_FOR_IDS
Watch for changes on HYP_CONTENT_FOR_IDS
JavaScript
mit
hyperoslo/hyper-content-for-angular,hyperoslo/hyper-content-for-angular
0e6ba9a3d53ec694c565273c9560ecf77485c010
src/js/libs/load-new-data.js
src/js/libs/load-new-data.js
import getWeatherInfo from './get-weather-info'; import fetchRandomPhoto from './fetch-random-photo'; import { lessThanOneHourAgo, lessThan24HoursAgo } from './helpers'; /* * Load the next image and update the weather */ const loadNewData = () => { chrome.storage.sync.get('photoFrequency', result => { const { photoFrequency } = result; if (photoFrequency === 'newtab') { fetchRandomPhoto(); return; } const nextImage = JSON.parse(localStorage.getItem('nextImage')); if ( photoFrequency === 'everyhour' && !lessThanOneHourAgo(nextImage.timestamp) ) { fetchRandomPhoto(); return; } if ( photoFrequency === 'everyday' && !lessThan24HoursAgo(nextImage.timestamp) ) { fetchRandomPhoto(); } }); chrome.storage.local.get('forecast', result => { const { forecast } = result; chrome.storage.sync.get('coords', d => { const { coords } = d; if (!forecast && coords) { getWeatherInfo(); return; } if (forecast) { const { timestamp } = forecast; if (timestamp) { if (!lessThanOneHourAgo(timestamp)) { getWeatherInfo(); } } } }); }); }; export default loadNewData;
import getWeatherInfo from './get-weather-info'; import fetchRandomPhoto from './fetch-random-photo'; import { lessThanOneHourAgo, lessThan24HoursAgo } from './helpers'; /* * Load the next image and update the weather */ const loadNewData = () => { chrome.storage.sync.get('photoFrequency', result => { const { photoFrequency } = result; if (photoFrequency === 'newtab') { fetchRandomPhoto(); return; } chrome.storage.local.get('nextImage', r => { const { nextImage } = r; if ( photoFrequency === 'everyhour' && !lessThanOneHourAgo(nextImage.timestamp) ) { fetchRandomPhoto(); return; } if ( photoFrequency === 'everyday' && !lessThan24HoursAgo(nextImage.timestamp) ) { fetchRandomPhoto(); } }); }); chrome.storage.local.get('forecast', result => { const { forecast } = result; chrome.storage.sync.get('coords', d => { const { coords } = d; if (!forecast && coords) { getWeatherInfo(); return; } if (forecast) { const { timestamp } = forecast; if (timestamp) { if (!lessThanOneHourAgo(timestamp)) { getWeatherInfo(); } } } }); }); }; export default loadNewData;
Change from local storage to chrome storage
Change from local storage to chrome storage
JavaScript
mit
ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos,ayoisaiah/stellar-photos
f2875d45257f892607df8a460b253cd35fb0900a
config/http-get-param-interceptor.js
config/http-get-param-interceptor.js
'use strict'; angular.module('gc.ngHttpGetParamInterceptor', [ 'gc.utils' ]).factory('httpGetParamInterceptor', [ 'utils', function httpGetParamInterceptor(utils) { function deleteUndefinedValues(obj) { _.keys(obj).forEach(function(key) { if (_.isUndefined(obj[key])) { delete obj[key]; } else if (_.isObject(obj[key])) { deleteUndefinedValues(obj[key]); } }); } return { request: function(config) { // Manually build query params using custom logic because Angular and // Rails do not handle nested query parameters in the same way if (config.params) { deleteUndefinedValues(config.params); config.url = config.url + '?' + utils.param(config.params); delete config.params; } return config; } }; } ]);
'use strict'; angular.module('gc.ngHttpGetParamInterceptor', [ 'gc.utils' ]).factory('httpGetParamInterceptor', [ 'utils', function httpGetParamInterceptor(utils) { return { request: function(config) { // Manually build query params using custom logic because Angular and // Rails do not handle nested query parameters in the same way if (config.params) { config.url = config.url + '?' + utils.param(config.params); delete config.params; } return config; } }; } ]);
Revert "delete undefined properties from http config params"
Revert "delete undefined properties from http config params" This reverts commit f52b94743e6539bf8088e773310359762b3d9cb5.
JavaScript
mit
gocardless-ng/ng-gc-base-app-service
0b3b4a73a06288627d6bb9e2c3f9d06bfad4fa18
src/components/Brand/Brand.js
src/components/Brand/Brand.js
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Link from '../Link'; import s from './Brand.css'; function Brand(){ return ( <Link className={s.brand} to="//skoli.fr" rel="nofollow" target="_blank">Skoli</Link> ) } export default withStyles(s)(Brand);
import React from 'react'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import Link from '../Link'; import s from './Brand.css'; function Brand(){ return ( <Link className={s.brand} to="http://skoli.fr" rel="nofollow" target="_blank">Skoli</Link> ) } export default withStyles(s)(Brand);
Add http to skoli.fr link
Add http to skoli.fr link
JavaScript
mit
Skoli-Code/DerangeonsLaChambre
6cbcdd143c822b6edefc28d8d70f123b0c53ea6d
tasks/remark.js
tasks/remark.js
'use strict'; var remark = require('remark'); var engine = require('unified-engine'); module.exports = function(grunt) { grunt.registerMultiTask('remark', 'Process markdown with remark', function() { var done = this.async(); var globs = this.filesSrc; var options = this.options({ processor: remark, globs: globs, extensions: ['md', 'markdown', 'mkd', 'mkdn', 'mkdown'], pluginPrefix: 'remark', presetPrefix: 'remark-preset', rcName: '.remarkrc', packageField: 'remarkConfig', ignoreName: '.remarkignore', color: true }); engine(options, function(err) { if (err) grunt.fail.warn(err); done(); }); }); };
'use strict'; var remark = require('remark'); var engine = require('unified-engine'); module.exports = function(grunt) { grunt.registerMultiTask('remark', 'Process markdown with remark', function() { var done = this.async(); var globs = this.filesSrc; var options = this.options({ processor: remark, globs: globs, extensions: ['md', 'markdown', 'mkd', 'mkdn', 'mkdown'], pluginPrefix: 'remark', presetPrefix: 'remark-preset', rcName: '.remarkrc', packageField: 'remarkConfig', ignoreName: '.remarkignore', color: true }); engine(options, function(err, status) { if (err || status) grunt.fail.warn(err || 'Unsuccessful running'); done(); }); }); };
Allow failure based off run status
Allow failure based off run status Add a default message when an error message is not passed
JavaScript
mit
ChristianMurphy/grunt-remark
7dbf771b1ce636ab3991458c955f7e34e6e2207f
app.js
app.js
/*! * AllOrigins * written by Gabriel Nunes <[email protected]> * http://github.com/gnuns */ const express = require('express') const {version} = require('./package.json') const processRequest = require('./app/process-request') // yep, global. it's ok // https://softwareengineering.stackexchange.com/a/47926/289420 global.AO_VERSION = version const app = express() app.set('case sensitive routing', false) app.disable('x-powered-by') app.use(enableCORS) app.all('/:format', processRequest) function enableCORS (req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin || '*') res.header('Access-Control-Allow-Credentials', true) res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE') res.header('Via', `allOrigins v${version}`) next() } module.exports = app
/*! * AllOrigins * written by Gabriel Nunes <[email protected]> * http://github.com/gnuns */ const express = require('express') const {version} = require('./package.json') // yep, global. it's ok // https://softwareengineering.stackexchange.com/a/47926/289420 global.AO_VERSION = version const processRequest = require('./app/process-request') const app = express() app.set('case sensitive routing', false) app.disable('x-powered-by') app.use(enableCORS) app.all('/:format', processRequest) function enableCORS (req, res, next) { res.header('Access-Control-Allow-Origin', req.headers.origin || '*') res.header('Access-Control-Allow-Credentials', true) res.header('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept') res.header('Access-Control-Allow-Methods', 'OPTIONS, GET, POST, PATCH, PUT, DELETE') res.header('Via', `allOrigins v${version}`) next() } module.exports = app
Define AO_VERSION before require process-request
Define AO_VERSION before require process-request
JavaScript
mit
gnuns/AllOrigins
48c8c0d3ef20cfef5aeb946f89c09155804be4ed
app.js
app.js
RTC({ // use the public google stun servers :) ice: [ { url: 'stun1.l.google.com:19302' }, { url: 'stun2.l.google.com:19302' }, { url: 'stun3.l.google.com:19302' }, { url: 'stun4.l.google.com:19302' } ], // we want this to work on iOS as well so we will use // the rtc-plugin-nicta-ios plugin so we can use the // build.rtc.io to create a native iOS app plugins: [ RTC.IOS ] });
var conference = RTC({ // use the public google stun servers :) ice: [ { url: 'stun1.l.google.com:19302' }, { url: 'stun2.l.google.com:19302' }, { url: 'stun3.l.google.com:19302' }, { url: 'stun4.l.google.com:19302' } ], // we want this to work on iOS as well so we will use // the rtc-plugin-nicta-ios plugin so we can use the // build.rtc.io to create a native iOS app plugins: [ RTC.IOS ] });
Create a conference variable that can be played with by forkers
Create a conference variable that can be played with by forkers
JavaScript
mit
rtc-io/demo-helloworld,rtc-io/demo-helloworld,rtc-io/demo-helloworld
db0bcc505eaf95cae39d4dd0b2f7b39fc4e404c1
test/unit/GameOfLife.spec.js
test/unit/GameOfLife.spec.js
var ALIVE = "alive", DEAD = "dead"; function Cell(initialState) { var state = initialState || DEAD; return { setNeighbours: function (neighbours) { var nbAliveCells = 0; neighbours.forEach(function(neighbor) { if(neighbor.state === ALIVE) { nbAliveCells += 1; } }); if(nbAliveCells < 2) { state = DEAD; } }, get state() { return state; } }; } describe('Live cell', function () { it('should die when it has fewer than two live neighbours', function () { var cell = new Cell(ALIVE); cell.setNeighbours([new Cell(ALIVE)]); expect(cell.state).toBe(DEAD); }); });
var GameOfLife = (function() { var ALIVE = "alive", DEAD = "dead"; function Cell(initialState) { var state = initialState || DEAD; function getNumberOfAlive(neighbours) { var nbAliveCells = 0; neighbours.forEach(function (neighbor) { if (neighbor.isAlive()) { nbAliveCells += 1; } }); return nbAliveCells; } return { setNeighbours: function (neighbours) { if(getNumberOfAlive(neighbours) < 2) { state = DEAD; } }, isAlive: function() { return state === ALIVE; } }; } function AliveCell() { return new Cell(ALIVE); } function DeadCell() { return new Cell(DEAD); } return { AliveCell: AliveCell, DeadCell: DeadCell }; })(); describe('Live cell', function () { it('should die when it has fewer than two live neighbours', function () { var cell = new GameOfLife.AliveCell(); cell.setNeighbours([new GameOfLife.AliveCell()]); expect(cell.isAlive()).toBe(false); }); });
Refactor less than two neighbours then cell dies
Refactor less than two neighbours then cell dies
JavaScript
mit
velcrin/GameOfLife
76c051f0874c76671a33e8974a8e0e2c0cba3ec8
test/unit/controllersSpec.js
test/unit/controllersSpec.js
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ beforeEach(module('swiftBrowser.controllers')); it('should list containers', inject(function($controller, $httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; var scope = {}; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); $controller('RootCtrl', {$scope: scope}); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', inject(function($controller) { var scope = {}; $controller('RootCtrl', {$scope: scope}); expect(scope.orderProp).toEqual('name'); })); });
'use strict'; /* jasmine specs for controllers go here */ describe('RootCtrl', function(){ var scope; beforeEach(module('swiftBrowser.controllers')); beforeEach(inject(function($controller) { scope = {}; $controller('RootCtrl', {$scope: scope}); })); it('should list containers', inject(function($httpBackend) { var containers = [ {"count": 10, "bytes": 1234, "name": "foo"}, {"count": 20, "bytes": 2345, "name": "bar"}, ]; $httpBackend.whenGET('/v1/AUTH_abc?format=json') .respond(200, containers); expect(scope.containers).toEqual([]); $httpBackend.flush(); expect(scope.containers).toEqual(containers); })); it('should set sort order', function() { expect(scope.orderProp).toEqual('name'); }); });
Refactor common logic for setting up RootCtrl and scope
Refactor common logic for setting up RootCtrl and scope
JavaScript
apache-2.0
mgeisler/swift-browser,mindware/swift-browser,mgeisler/swift-browser,zerovm/swift-browser,mindware/swift-browser,zerovm/swift-browser
897f72d6c7d52abcdc8274756644fb7c217c3572
app/assets/javascripts/new_timeslot.js
app/assets/javascripts/new_timeslot.js
$(document).ready(function(){ $("#new-timeslot-form").submit(function(event){ event.preventDefault(); var data = createDate(); $("#modal_new_timeslot").modal('toggle'); $.ajax({ type: "POST", url: "/api/timeslots", data: { start: data } }).done(function(response) { swal({ title: "Great!", text: "You have set up a tutoring availability!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar( 'refetchEvents' ); }).fail(function(response) { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }) }) var createDate = function() { var date = $('.timepicker').val(); var time = $('.datepicker').val(); var dateTime = date + " " + time; return (new Date(dateTime)); }
$(document).ready(function(){ $("#new-timeslot-form").submit(function(event){ event.preventDefault(); var data = createDate(); $("#modal_new_timeslot").modal('toggle'); $.ajax({ type: "POST", url: "/api/timeslots", data: { start: data }, beforeSend: customBlockUi(this) }).done(function(response) { swal({ title: "Great!", text: "You have set up a tutoring availability!", confirmButtonColor: "#66BB6A", type: "success" }); $('#tutor-cal').fullCalendar( 'refetchEvents' ); }).fail(function(response) { swal({ title: "Oops...", text: "Something went wrong!", confirmButtonColor: "#EF5350", type: "error" }); }); }) }) var createDate = function() { var date = $('.timepicker').val(); var time = $('.datepicker').val(); var dateTime = date + " " + time; return (new Date(dateTime)); }
Add block ui to ajax call for creating new timeslot
Add block ui to ajax call for creating new timeslot
JavaScript
mit
theresaboard/theres-a-board,theresaboard/theres-a-board,theresaboard/theres-a-board
85bee713801bb259fdcbf6c06358372c692b508b
src/ZSchema.js
src/ZSchema.js
"use strict"; /* default options */ var defaultOptions = { // force additionalProperties and additionalItems to be defined on "object" and "array" types forceAdditional: false, // force items to be defined on "array" types forceItems: false, // force maxLength to be defined on "string" types forceMaxLength: false, // force properties or patternProperties to be defined on "object" types forceProperties: false, // disallow usage of keywords that this validator can't handle noExtraKeywords: false, // disallow usage of schema's without "type" defined noTypeless: false, // disallow zero length strings in validated objects noZeroLengthStrings: false, // forces "uri" format to be in fully rfc3986 compliant strictUris: false, // forces "email" format to be validated more strictly strictEmails: false, // turn on all of the above strict: false }; /* constructor */ function ZSchema(options) { this.options = options; } /* instance methods */ ZSchema.prototype.compileSchema = function (schema, callback) { }; ZSchema.prototype.validateSchema = function (schema, callback) { }; ZSchema.prototype.validate = function (json, schema, callback) { }; /* static methods */ ZSchema.registerFormat = function (formatName, validatorFunction) { }; module.exports = ZSchema;
"use strict"; /* default options */ var defaultOptions = { // force additionalProperties and additionalItems to be defined on "object" and "array" types forceAdditional: false, // force items to be defined on "array" types forceItems: false, // force maxLength to be defined on "string" types forceMaxLength: false, // force properties or patternProperties to be defined on "object" types forceProperties: false, // disallow usage of keywords that this validator can't handle noExtraKeywords: false, // disallow usage of schema's without "type" defined noTypeless: false, // disallow zero length strings in validated objects noZeroLengthStrings: false, // forces "uri" format to be in fully rfc3986 compliant strictUris: false, // forces "email" format to be validated more strictly strictEmails: false, // turn on all of the above strict: false }; /* constructor */ function ZSchema(options) { this.options = options; } /* instance methods */ ZSchema.prototype.compileSchema = function (schema, callback) { }; ZSchema.prototype.validateSchema = function (schema, callback) { }; ZSchema.prototype.validate = function (json, schema, callback) { }; /* static methods */ ZSchema.registerFormat = function (formatName, validatorFunction) { }; ZSchema.registerFormatter = function (formatterName, formatterFunction) { }; module.exports = ZSchema;
Add an API for formatter functionality.
Add an API for formatter functionality.
JavaScript
mit
whitlockjc/z-schema,crypti/z-schema,whitlockjc/z-schema,crypti/z-schema
081312e0ab495e4e8d2e93ce8ff3a8d7305644ea
src/interface/button.js
src/interface/button.js
/* @flow */ import { isPayPalDomain } from '@paypal/sdk-client/src'; import { PopupOpenError as _PopupOpenError, destroy as zoidDestroy, destroyComponents } from 'zoid/src'; import { setupLogger, allowIframe as _allowIframe } from '../lib'; import { getCheckoutComponent } from '../checkout'; import { getButtonsComponent } from '../buttons'; import { Buttons as _ButtonsTemplate } from '../buttons/template'; export const request = { addHeaderBuilder: () => { // pass } }; export const Buttons = { __get__: () => getButtonsComponent() }; export const Checkout = { __get__: () => { const component = getCheckoutComponent(); if (isPayPalDomain()) { return component; } } }; export const ButtonsTemplate = { __get__: () => { if (isPayPalDomain()) { return _ButtonsTemplate; } } }; export const PopupOpenError = { __get__: () => { if (isPayPalDomain()) { return _PopupOpenError; } } }; export const allowIframe = { __get__: () => { if (isPayPalDomain()) { return _allowIframe; } } }; export const destroyAll = { __get__: () => { if (isPayPalDomain() || __TEST__) { return destroyComponents; } } }; export function setup() { setupLogger(); getButtonsComponent(); getCheckoutComponent(); } export function destroy() { zoidDestroy(); }
/* @flow */ import { isPayPalDomain } from '@paypal/sdk-client/src'; import { PopupOpenError as _PopupOpenError, destroy as zoidDestroy, destroyComponents } from 'zoid/src'; import { setupLogger, allowIframe as _allowIframe } from '../lib'; import { getCheckoutComponent } from '../checkout'; import { getButtonsComponent } from '../buttons'; import { Buttons as _ButtonsTemplate } from '../buttons/template'; function protectedExport<T>(xport : T) : ?T { if (isPayPalDomain()) { return xport; } } export const request = { addHeaderBuilder: () => { // pass } }; export const Buttons = { __get__: () => getButtonsComponent() }; export const Checkout = { __get__: () => protectedExport(getCheckoutComponent()) }; export const ButtonsTemplate = { __get__: () => protectedExport(_ButtonsTemplate) }; export const PopupOpenError = { __get__: () => protectedExport(_PopupOpenError) }; export const allowIframe = { __get__: () => protectedExport(_allowIframe) }; export const forceIframe = { __get__: () => protectedExport(_allowIframe) }; export const destroyAll = { __get__: () => protectedExport(destroyComponents) }; export function setup() { setupLogger(); getButtonsComponent(); getCheckoutComponent(); } export function destroy() { zoidDestroy(); }
Add forceIframe as a protected export
Add forceIframe as a protected export
JavaScript
apache-2.0
paypal/paypal-checkout,paypal/paypal-checkout,paypal/paypal-checkout
15659df3b6b540995f09892ba88fd29986e024e8
src/models/UserAdmin.js
src/models/UserAdmin.js
import User from 'src/models/User'; import { auth } from 'src/config/firebase-admin'; User.prototype.login = function login(email, password) { return auth .signInWithEmailAndPassword(email, password) .then((firebaseUser) => { this.uid = firebaseUser.uid; this.displayName = firebaseUser.displayName; this.email = firebaseUser.email; this.isAnonymous = firebaseUser.isAnonymous; this.emailVerified = firebaseUser.emailVerified; this.photoURL = firebaseUser.photoURL; this.refreshToken = firebaseUser.refreshToken; return this; }); } User.prototype.logout = () => auth.signOut(); export default User;
import User from 'src/models/User'; import { auth } from 'src/config/firebase'; User.prototype.login = function login(email, password) { return auth .signInWithEmailAndPassword(email, password) .then((firebaseUser) => { this.uid = firebaseUser.uid; this.displayName = firebaseUser.displayName; this.email = firebaseUser.email; this.isAnonymous = firebaseUser.isAnonymous; this.emailVerified = firebaseUser.emailVerified; this.photoURL = firebaseUser.photoURL; this.refreshToken = firebaseUser.refreshToken; return this; }); } User.prototype.logout = () => auth.signOut(); export default User;
Use firebase here, server never imports this
Use firebase here, server never imports this
JavaScript
mit
tuelsch/bolg,tuelsch/bolg
95a72a64eb23dfd693e2df8be14e07ede94a9d5b
lib/util/sendJSON.js
lib/util/sendJSON.js
module.exports = function sendJSON(res, next) { return _sendJSON(error, data) { if (error) { return next(error); } return res.json(data); } };
module.exports = function sendJSON(res, next) { return function _sendJSON(error, data) { if (error) { return next(error); } return res.json(data); } };
Fix syntax error - missing function declaration
Fix syntax error - missing function declaration
JavaScript
mit
ganemone/bookshelf-restful
def0b69334011054fabaa1dc83b9ea4fb1a1b0cd
client/components/banettes/banettes.constant.js
client/components/banettes/banettes.constant.js
'use strict'; angular.module('impactApp').constant('banettes', [ { id: 'toutes', label: 'Toutes' }, { id: 'emise', label: 'Émise' }, { id: 'complet', label: 'Complète' }, { id: 'incomplet', label: 'Incomplète' }, { id: 'archive', label: 'Archivée' } ]);
'use strict'; angular.module('impactApp').constant('banettes', [ { id: 'toutes', label: 'Toutes' }, { id: 'emise', label: 'Émise' }, { id: 'complet', label: 'Complète' }, { id: 'incomplet', label: 'Incomplète' }, { id: 'en_cours', label: 'En cours de saisie' }, { id: 'archive', label: 'Archivée' } ]);
Add display of new status
Add display of new status
JavaScript
agpl-3.0
sgmap/impact,sgmap/impact
21eeb265e755b09ebd06249c5e0c7e6beadeb7d7
client/src/components/pages/Login/index.js
client/src/components/pages/Login/index.js
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import Paper from 'material-ui/Paper'; import styles from './styles.css'; import LoginForm from './LoginForm'; const LoginPage = ({ isAuthenticated, location }) => { const { from } = location.state || { from: { pathname: '/' } }; return isAuthenticated ? <Redirect t={ from } /> : <div className="login"> <div className="login__modal"> <Paper className="modal"> <Toolbar> <ToolbarTitle text="Welcome back." style={{ color: 'white '}} /> </Toolbar> <LoginForm /> </Paper> </div> </div> }; export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }) )(LoginPage);
import React from 'react'; import { connect } from 'react-redux'; import { Redirect } from 'react-router-dom'; import { Toolbar, ToolbarTitle } from 'material-ui/Toolbar'; import Paper from 'material-ui/Paper'; import styles from './styles.css'; import LoginForm from './LoginForm'; const LoginPage = ({ isAuthenticated, location }) => { const { from } = location.state || { from: { pathname: '/' } }; return isAuthenticated ? <Redirect to={ from } /> : <div className="login"> <div className="login__modal"> <Paper className="modal"> <Toolbar> <ToolbarTitle text="Welcome back." style={{ color: 'white '}} /> </Toolbar> <LoginForm /> </Paper> </div> </div> }; export default connect( ({ root }) => ({ isAuthenticated: root.isAuthenticated }) )(LoginPage);
Fix broken redirect after login
Fix broken redirect after login
JavaScript
mit
mbchoa/presence,mbchoa/presence
e6b0b562e53afde0dfc32abb90d367456ba9d1d8
client/templates/courses/tagged-courses.js
client/templates/courses/tagged-courses.js
Template.taggedCourses.helpers({ 'courses': function () { return Courses.find().fetch(); }, 'tag': function () { // Get reference to template instance var instance = this; // Get tag from instance var tag = instance.tag; return tag; } }); Template.taggedCourses.onCreated(function(){ // Get reference to template instance var instance = this; // Accessing the Iron.controller to invoke getParams method of Iron Router. var router = Router.current(); // Getting Params of the URL instance.tag = router.params.tag; // Subscribe to courses tagged with the current tag instance.subscribe('taggedCourses', instance.tag); // Subscribe to course images instance.subscribe('images'); });
Template.taggedCourses.helpers({ 'courses': function () { return Courses.find().fetch(); }, 'tag': function () { // Get reference to template instance var instance = this; // Get tag from instance var tag = instance.tag; return tag; } }); Template.taggedCourses.onCreated(function(){ // Get reference to template instance var instance = this; // Accessing the Iron.controller to invoke getParams method of Iron Router. var router = Router.current(); // Getting Params of the URL instance.tag = router.params.tag; // Subscribe to courses tagged with the current tag instance.subscribe('taggedCourses', instance.tag); // Subscribe to course images instance.subscribe('images'); }); Template.taggedCourses.rendered = function () { // Get reference to template instance var instance = this; // Set the page site title for SEO Meta.setTitle('Courses tagged "' + instance.tag + '"'); };
Set page title on render
Set page title on render
JavaScript
agpl-3.0
Crowducate/crowducate-platform,Crowducate/crowducate-platform
ff1dd026c76dcf7592ddf3072a33a0a87d220ccc
lib/clients/carbon_client.js
lib/clients/carbon_client.js
var util = require('util'), OxideClient = require('./oxide_client.js'), Metric = require('../metrics/metric.js'); function CarbonClient (opts) { OxideClient.call(this); } util.inherits(CarbonClient, OxideClient); CarbonClient.prototype.record = function (path, value, timestamp) { var opts = { path: this._pathify(path), value: value } if (typeof timestamp !== 'undefined') { opts.timestamp = timestamp } return this.enqueue(new Metric(opts)); } module.exports = CarbonClient;
var util = require('util'), OxideClient = require('./oxide_client.js'), Metric = require('../metrics/metric.js'); function CarbonClient (opts) { OxideClient.call(this, opts); } util.inherits(CarbonClient, OxideClient); CarbonClient.prototype.record = function (path, value, timestamp) { var opts = { path: this._pathify(path), value: value } if (typeof timestamp !== 'undefined') { opts.timestamp = timestamp } return this.enqueue(new Metric(opts)); } module.exports = CarbonClient;
Fix passing opts through carbon client to oxide client
Fix passing opts through carbon client to oxide client
JavaScript
mit
MCProHosting/oxide
02cc9cfbd1e23bfedff71a256ed60c32936afb1e
cmd/tchaik/ui/static/js/__tests__/components/ArtworkImage-test.js
cmd/tchaik/ui/static/js/__tests__/components/ArtworkImage-test.js
var __path__ = '../../src/components/ArtworkImage.js'; jest.dontMock(__path__); describe('ArtworkImage', function() { var React, TestUtils, ArtworkImage; var artworkImage; beforeEach(function() { React = require('react/addons'); TestUtils = React.addons.TestUtils; ArtworkImage = require(__path__); artworkImage = TestUtils.renderIntoDocument( <ArtworkImage path='/artwork/19199193' /> ) }); it('works', function() { expect(true).toBeTruthy(); }); });
var __path__ = '../../src/components/ArtworkImage.js'; jest.dontMock(__path__); describe('ArtworkImage', function() { var React, TestUtils, ArtworkImage; var domNode, artworkImage; beforeEach(function() { React = require('react/addons'); TestUtils = React.addons.TestUtils; ArtworkImage = require(__path__); artworkImage = TestUtils.renderIntoDocument( <ArtworkImage path='/artwork/19199193' /> ); domNode = React.findDOMNode(artworkImage); }); describe('in the initial state', function() { it('should not be visible', function() { var classes = domNode.getAttribute('class').split(' '); expect(classes).not.toContain('visible'); }); }); describe('after the image has loaded', function() { beforeEach(function() { TestUtils.Simulate.load(domNode); }); it('should be visible', function() { var classes = domNode.getAttribute('class').split(' '); expect(classes).toContain('visible'); }); }); describe('after the image has errored', function() { beforeEach(function() { TestUtils.Simulate.error(domNode); }); it('should be visible', function() { var classes = domNode.getAttribute('class').split(' '); expect(classes).not.toContain('visible'); }); }); });
Add *useful* tests for the ArtworkImage component
Add *useful* tests for the ArtworkImage component
JavaScript
bsd-2-clause
solarnz/tchaik,solarnz/tchaik,GrahamGoudeau21/tchaik,solarnz/tchaik,GrahamGoudeau21/tchaik,tchaik/tchaik,tchaik/tchaik,GrahamGoudeau21/tchaik,solarnz/tchaik,tchaik/tchaik,GrahamGoudeau21/tchaik,tchaik/tchaik
d5baa6a9f98ddf3c6c46bb8eb8f6a98f62e4d8b7
src/TodoApp/TodoList/Todo.js
src/TodoApp/TodoList/Todo.js
import React from 'react'; export default class Todo extends React.Component { static propTypes = { text: React.PropTypes.string.isRequired } render() { return ( <li>{this.props.text}</li> ); } }
import React from 'react'; export default class Todo extends React.Component { static propTypes = { text: React.PropTypes.string.isRequired } state = { completed: false } render() { const style = { textDecoration: this.state.completed ? 'line-through' : undefined, cursor: 'default' }; return ( <li style={style} onClick={this.toggleCompleted} > {this.props.text} </li> ); } toggleCompleted = (event) => { this.setState({ completed: !this.state.completed }); } }
Add the ability to cross off items on the list
Add the ability to cross off items on the list
JavaScript
cc0-1.0
ksmithbaylor/react-todo-list,ksmithbaylor/react-todo-list
18e9cf3851ddaae9f865b326f4152d53ce5eb882
types/number.js
types/number.js
"use strict"; let errors = require('../errors.js'); let Type = require('./type.js'); let Value = require('./value.js'); class NumberValue extends Value { constructor(type) { super(type); this.value = 0; } assign(newValue) { if (typeof newValue == 'number') { this.value = newValue; } else if (newValue.value !== undefined && typeof newValue.value == 'number') { this.value = newValue.value; } else { throw new errors.Internal(`Trying to assign ${newValue.type} to Number;`); } } equals(other) { return this.type == other.type && this.value == other.value; } innerToString() { return `${this.value}`; } toString() { return `${this.value}`; } } class NumberType extends Type { constructor() { super(null, null, 'Number'); } equals(other) { return other === NumberType.singleton; } makeDefaultValue() { return new NumberValue(this); } toString() { return 'Number'; } } NumberType.singleton = new NumberType(); module.exports = { Type: NumberType, Value: NumberValue, };
"use strict"; let errors = require('../errors.js'); let Type = require('./type.js'); let Value = require('./value.js'); class NumberValue extends Value { constructor(type) { super(type); this.value = 0; } assign(newValue) { if (typeof newValue == 'number') { this.value = newValue; } else if (newValue.value !== undefined && typeof newValue.value == 'number') { this.value = newValue.value; } else { throw new errors.Internal(`Trying to assign ${newValue.type} to Number;`); } } equals(other) { return this.type == other.type && this.value == other.value; } innerToString() { return `${this.value}`; } assignJSON(spec) { this.value = spec; } toJSON() { return this.value; } toString() { return `${this.value}`; } } class NumberType extends Type { constructor() { super(null, null, 'Number'); } equals(other) { return other === NumberType.singleton; } makeDefaultValue() { return new NumberValue(this); } toString() { return 'Number'; } } NumberType.singleton = new NumberType(); module.exports = { Type: NumberType, Value: NumberValue, };
Add assignJSON/toJSON to Number types
Add assignJSON/toJSON to Number types
JavaScript
mit
salesforce/runway-browser,SalesforceEng/runway-browser,SalesforceEng/runway-browser
e9fa8ee78fc8630d67fcd9384e8731c2a13d4ff9
languages/es-ES.js
languages/es-ES.js
/*! * numbro.js language configuration * language : spanish Spain * author : Hernan Garcia : https://github.com/hgarcia */ (function () { var language = { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'k', million: 'mm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (b === 1 || b === 3) ? 'er' : (b === 2) ? 'do' : (b === 7 || b === 0) ? 'mo' : (b === 8) ? 'vo' : (b === 9) ? 'no' : 'to'; }, currency: { symbol: '€', position: 'postfix' }, defaults: { currencyFormat: ',0000 a' }, formats: { fourDigits: '0000 a', fullWithTwoDecimals: ',0.00 $', fullWithTwoDecimalsNoCurrency: ',0.00', fullWithNoDecimals: ',0 $' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && this.numbro && this.numbro.language) { this.numbro.language('es', language); } }());
/*! * numbro.js language configuration * language : spanish Spain * author : Hernan Garcia : https://github.com/hgarcia */ (function () { var language = { delimiters: { thousands: '.', decimal: ',' }, abbreviations: { thousand: 'k', million: 'mm', billion: 'b', trillion: 't' }, ordinal: function (number) { var b = number % 10; return (b === 1 || b === 3) ? 'er' : (b === 2) ? 'do' : (b === 7 || b === 0) ? 'mo' : (b === 8) ? 'vo' : (b === 9) ? 'no' : 'to'; }, currency: { symbol: '€', position: 'postfix' }, defaults: { currencyFormat: ',0000 a' }, formats: { fourDigits: '0000 a', fullWithTwoDecimals: ',0.00 $', fullWithTwoDecimalsNoCurrency: ',0.00', fullWithNoDecimals: ',0 $' } }; // Node if (typeof module !== 'undefined' && module.exports) { module.exports = language; } // Browser if (typeof window !== 'undefined' && this.numbro && this.numbro.language) { this.numbro.language('es-ES', language); } }());
Correct culture code for Español
Correct culture code for Español
JavaScript
mit
Stillat/numeral.php,foretagsplatsen/numbro,stewart42/numbro,rafde/numbro,clayzermk1/numbro,prantlf/numbro,atuttle/numbro,Kistler-Group/numbro,danghongthanh/numbro,BenjaminVanRyseghem/numbro,matthieuprat/numbro
81c22ea31edcadd73f459470923cf8ee62b09a8a
website/js/dashboard-ajax.js
website/js/dashboard-ajax.js
// Common ajax-handling functions for dashboard-like pages. Looks for <reload/> // elements to reload the page, and reports errors or failures via alerts. g_action_url = "action.php"; // Note that this doesn't run if the $.ajax call has a 'success:' callback that // generates an error. $(document).ajaxSuccess(function(event, xhr, options, xmldoc) { var fail = xmldoc.documentElement.getElementsByTagName("failure"); if (fail && fail.length > 0) { console.log(xmldoc); alert("Action failed: " + fail[0].textContent); } }); // <reload/> element $(document).ajaxSuccess(function(event, xhr, options, xmldoc) { var reload = xmldoc.documentElement.getElementsByTagName("reload"); if (reload && reload.length > 0) { console.log('ajaxSuccess event: reloading page'); location.reload(true); } }); $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { console.log("ajaxError: " + thrownError); console.log(thrownError); console.log(jqXHR); console.log(jqXHR.responseText); console.log(event); alert("Ajax error: " + thrownError); });
// Common ajax-handling functions for dashboard-like pages. Looks for <reload/> // elements to reload the page, and reports errors or failures via alerts. g_action_url = "action.php"; // Note that this doesn't run if the $.ajax call has a 'success:' callback that // generates an error. $(document).ajaxSuccess(function(event, xhr, options, xmldoc) { var fail = xmldoc.documentElement.getElementsByTagName("failure"); if (fail && fail.length > 0) { console.log(xmldoc); alert("Action failed: " + fail[0].textContent); } }); // <reload/> element $(document).ajaxSuccess(function(event, xhr, options, xmldoc) { var reload = xmldoc.documentElement.getElementsByTagName("reload"); if (reload && reload.length > 0) { console.log('ajaxSuccess event: reloading page'); location.reload(true); } }); $(document).ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { console.log("ajaxError: " + thrownError); console.log(thrownError); console.log(jqXHR); console.log("Response text: " + jqXHR.responseText); console.log("ReadyState: " + jqXHR.readyState); console.log("status: " + jqXHR.status); console.log(event); alert("Ajax error: " + thrownError); });
Add some additional logging for ajax failures.
Add some additional logging for ajax failures.
JavaScript
mit
jeffpiazza/derbynet,jeffpiazza/derbynet,jeffpiazza/derbynet,jeffpiazza/derbynet,jeffpiazza/derbynet,jeffpiazza/derbynet,jeffpiazza/derbynet
cc56d5cce91d4031b4a12d71739bdabd86b8481d
lib/collections.js
lib/collections.js
CommitMessages = new Mongo.Collection("CommitMessages"); RepositoryList = new Mongo.Collection("RepositoryList"); Announcements = new Mongo.Collection("Announcements"); MentorQueue = new Mongo.Collection("MentorQueue"); AnonReports = new Mongo.Collection('AnonReports');
CommitMessages = new Mongo.Collection("CommitMessages"); RepositoryList = new Mongo.Collection("RepositoryList"); Announcements = new Mongo.Collection("Announcements"); MentorQueue = new Mongo.Collection("MentorQueue"); AnonReports = new Mongo.Collection('AnonReports'); AnonUserData = new Mongo.Collection('AnonUserData');
Initialize collection for anonymous data
Initialize collection for anonymous data
JavaScript
mit
mpoegel/HackRPI-Status-Board,hack-rpi/Status-Board,hack-rpi/Status-Board,mpoegel/HackRPI-Status-Board,hack-rpi/Status-Board,mpoegel/HackRPI-Status-Board,mpoegel/HackRPI-Status-Board
10c71a738177fc02053601dff5594ba17cb2ab61
src/Umbraco.Web.UI.Client/src/views/propertyeditors/boolean/boolean.controller.js
src/Umbraco.Web.UI.Client/src/views/propertyeditors/boolean/boolean.controller.js
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
function booleanEditorController($scope, $rootScope, assetsService) { function setupViewModel() { $scope.renderModel = { value: false }; if ($scope.model.config && $scope.model.config.default && $scope.model.config.default.toString() === "1" && $scope.model && !$scope.model.value) { $scope.renderModel.value = true; } if ($scope.model && $scope.model.value && ($scope.model.value.toString() === "1" || angular.lowercase($scope.model.value) === "true")) { $scope.renderModel.value = true; } } setupViewModel(); if( $scope.model && !$scope.model.value ) { $scope.model.value = ($scope.renderModel.value === true) ? '1' : '0'; } //here we declare a special method which will be called whenever the value has changed from the server //this is instead of doing a watch on the model.value = faster $scope.model.onValueChanged = function (newVal, oldVal) { //update the display val again if it has changed from the server setupViewModel(); }; // Update the value when the toggle is clicked $scope.toggle = function(){ if($scope.renderModel.value){ $scope.model.value = "0"; setupViewModel(); return; } $scope.model.value = "1"; setupViewModel(); }; } angular.module("umbraco").controller("Umbraco.PropertyEditors.BooleanController", booleanEditorController);
Set a initial $scope.model.value for true/false
Set a initial $scope.model.value for true/false
JavaScript
mit
marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,dawoe/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,NikRimington/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,abryukhov/Umbraco-CMS,mattbrailsford/Umbraco-CMS,abryukhov/Umbraco-CMS,hfloyd/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,hfloyd/Umbraco-CMS,lars-erik/Umbraco-CMS,madsoulswe/Umbraco-CMS,bjarnef/Umbraco-CMS,dawoe/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,hfloyd/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,tcmorris/Umbraco-CMS,robertjf/Umbraco-CMS,lars-erik/Umbraco-CMS,dawoe/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,tcmorris/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,arknu/Umbraco-CMS,tcmorris/Umbraco-CMS,hfloyd/Umbraco-CMS,WebCentrum/Umbraco-CMS,aaronpowell/Umbraco-CMS,madsoulswe/Umbraco-CMS,dawoe/Umbraco-CMS,arknu/Umbraco-CMS,arknu/Umbraco-CMS,marcemarc/Umbraco-CMS,umbraco/Umbraco-CMS,WebCentrum/Umbraco-CMS,mattbrailsford/Umbraco-CMS,dawoe/Umbraco-CMS,abjerner/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,umbraco/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,aaronpowell/Umbraco-CMS,madsoulswe/Umbraco-CMS,abryukhov/Umbraco-CMS,leekelleher/Umbraco-CMS,rasmuseeg/Umbraco-CMS,leekelleher/Umbraco-CMS,tompipe/Umbraco-CMS,abryukhov/Umbraco-CMS,robertjf/Umbraco-CMS,KevinJump/Umbraco-CMS,mattbrailsford/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,marcemarc/Umbraco-CMS,hfloyd/Umbraco-CMS,bjarnef/Umbraco-CMS,robertjf/Umbraco-CMS,abjerner/Umbraco-CMS,tcmorris/Umbraco-CMS,marcemarc/Umbraco-CMS,leekelleher/Umbraco-CMS,lars-erik/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,robertjf/Umbraco-CMS,NikRimington/Umbraco-CMS,bjarnef/Umbraco-CMS,tcmorris/Umbraco-CMS,aaronpowell/Umbraco-CMS,umbraco/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,tompipe/Umbraco-CMS,umbraco/Umbraco-CMS,KevinJump/Umbraco-CMS,abjerner/Umbraco-CMS,marcemarc/Umbraco-CMS,JimBobSquarePants/Umbraco-CMS,KevinJump/Umbraco-CMS,rasmuseeg/Umbraco-CMS,PeteDuncanson/Umbraco-CMS,JeffreyPerplex/Umbraco-CMS,lars-erik/Umbraco-CMS,leekelleher/Umbraco-CMS,nul800sebastiaan/Umbraco-CMS,arknu/Umbraco-CMS
9bddc584038883014c928fd46120090b37827b4c
js/view.js
js/view.js
( function( global, chrome, d ) { // I know, UGLY, but it's just a prototype. function View( $element, manager ) { this.manager = manager; this.$left = $element.find( '.left' ); this.$right = $element.find( '.right' ); } View.prototype.display = function() { var self = this; self.manager.getSections( function( sections ) { sections.forEach( function( section ) { var $column = ( section.title.substring( 0, 1 ) === '+' ) ? self.$left : self.$right; $s = $( '<section></section>' ); $s.append( '<h1>' + section.title.substring( 1 ) + '</h1>' ); $column.append( $s ); ( function( $section ) { self.manager.getBookmarks( section, function( bookmarks ) { bookmarks.forEach( function( bookmark ) { var $link = $( '<a href="' + bookmark.url + '">' + bookmark.title + '</a>' ); $section.append( $link ); } ); } ); } )( $s ); } ); } ); } d.View = View; } )( this, chrome, this.Dashboard = this.Dashboard || {} ); var $c = $( '#container' ), $s;
( function( global, chrome, d ) { // I know, UGLY, but it's just a prototype. // FIXME: Refactor, improve, rewrite from scrath, whatever but make it pretty and efficient ! function View( $element, manager ) { this.manager = manager; this.$left = $element.find( '.left' ); this.$right = $element.find( '.right' ); } View.prototype.display = function() { var self = this; self.manager.getSections( function( sections ) { sections.forEach( function( section ) { var $column = ( section.title.substring( 0, 1 ) === '+' ) ? self.$left : self.$right, $s = $( '<section></section>' ); $s[ 0 ].id = section.id; $s.append( '<h1>' + section.title.substring( 1 ) + '</h1>' ); $column.append( $s ); ( function( $section ) { self.manager.getBookmarks( section, function( bookmarks ) { bookmarks.forEach( function( bookmark ) { var $link = $( '<a>' + bookmark.title + '</a>' ); $link[ 0 ].id = bookmark.id; $link[ 0 ].href = bookmark.url; $section.append( $link ); } ); } ); } )( $s ); } ); } ); } d.View = View; } )( this, chrome, this.Dashboard = this.Dashboard || {} ); var $c = $( '#container' ), $s;
Set each bookmark's identifier on its DOM element 'id' attribute.
Set each bookmark's identifier on its DOM element 'id' attribute.
JavaScript
mit
romac/mdash,romac/mdash,romac/mdash
d85c88ca5e9e069d889fc6a54e26bfe90cefcf3b
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var browserSync = require('browser-sync'); gulp.task('default', ['serve']); gulp.task('serve', function() { browserSync.init(null, { server: { baseDir: './' }, notify: false }); gulp.watch([ './*.html', './css/**/*.css', './js/**/*.js' ], browserSync.reload); });
var gulp = require('gulp'); var browserSync = require('browser-sync'); gulp.task('default', ['serve']); gulp.task('serve', function() { browserSync.init(null, { server: { baseDir: './' }, notify: false }); gulp.watch([ './*.html', './css/**/*.css', './js/**/*.js' ], function() { browserSync.reload({ once: true }); }); });
Make sure that the reload only triggers once for multiple file updates.
Make sure that the reload only triggers once for multiple file updates.
JavaScript
mit
tvararu/tvararu.github.io,tvararu/tvararu.github.io