commit
stringlengths
40
40
old_file
stringlengths
4
150
new_file
stringlengths
4
150
old_contents
stringlengths
0
3.26k
new_contents
stringlengths
1
4.43k
subject
stringlengths
15
501
message
stringlengths
15
4.06k
lang
stringclasses
4 values
license
stringclasses
13 values
repos
stringlengths
5
91.5k
diff
stringlengths
0
4.35k
91faa0f9e1e9d211b7be72b254b18578d2bdb3b3
www/timelines.js
www/timelines.js
function load_timelines() { $.getJSON('/time_series.json',function(data) { var options = { xaxis: { mode: "time" }, series: { points: { show: "true" }, lines: { show: "true" } }, grid: { }, yaxis: { min: 29.5, max: 40 } }; $.plot('#psnr_graph',[data[0].sort()],options); options.yaxis.min = 29; options.yaxis.max = 40; $.plot('#psnrhvs_graph',[data[1].sort()],options); options.yaxis.min = 9; options.yaxis.max = 20; $.plot('#ssim_graph',[data[2].sort()],options); options.yaxis.min = 11; options.yaxis.max = 30; $.plot('#fastssim_graph',[data[3].sort()],options); }); }
var wd; function load_timelines() { load_timelines_watermark(); } function load_timelines_watermark() { $.getJSON('/watermark.json', function(data) { wd = data; load_time_series(); } } function load_time_series() { $.getJSON('/time_series.json',function(data) { var options = { xaxis: { mode: "time" }, series: { points: { show: "true" }, lines: { show: "true" } }, grid: { markings: [ { yaxis: { from: wd.x265.psnr, to: wd.x265.psnr}, color: "#ff0000"}, { yaxis: { from: wd.x264.psnr, to: wd.x264.psnr}, color: "#00ff00"} ] }, yaxis: { min: 29.5, max: 40 } }; $.plot('#psnr_graph',[data[0].sort()],options); options.yaxis.min = 29; options.yaxis.max = 40; $.plot('#psnrhvs_graph',[data[1].sort()],options); options.yaxis.min = 9; options.yaxis.max = 20; $.plot('#ssim_graph',[data[2].sort()],options); options.yaxis.min = 11; options.yaxis.max = 30; $.plot('#fastssim_graph',[data[3].sort()],options); }); }
Refactor timeline support to load watermarks from json file
Refactor timeline support to load watermarks from json file
JavaScript
mit
tdaede/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,mdinger/awcy,tdaede/awcy,tdaede/awcy,mdinger/awcy,mdinger/awcy
--- +++ @@ -1,4 +1,17 @@ +var wd; + function load_timelines() { + load_timelines_watermark(); +} + +function load_timelines_watermark() { + $.getJSON('/watermark.json', function(data) { + wd = data; + load_time_series(); + } +} + +function load_time_series() { $.getJSON('/time_series.json',function(data) { var options = { xaxis: { @@ -13,6 +26,8 @@ } }, grid: { + markings: [ { yaxis: { from: wd.x265.psnr, to: wd.x265.psnr}, color: "#ff0000"}, + { yaxis: { from: wd.x264.psnr, to: wd.x264.psnr}, color: "#00ff00"} ] }, yaxis: { min: 29.5,
fe5bd0dedb1d5dba919bfe9f7b9aaa721e1598f9
instance_introspection/static/src/js/tests.js
instance_introspection/static/src/js/tests.js
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths")', element: '.btn-reload', wait: 200, }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
(function() { 'use strict'; openerp.Tour.register({ id: 'test_instance_introspection', name: 'Complete a basic order trough the Front-End', path: '/instance_introspection', mode: 'test', steps: [ { title: 'Wait for the main screen', waitFor: 'h3:contains("Addons Paths"),#accordion.results', element: '.btn-reload', wait: 200, }, { title: 'Load Repositories', waitFor: '#accordion.results', }, ], }); })();
Test expecting results also since the begining
[IMP] Test expecting results also since the begining
JavaScript
agpl-3.0
vauxoo-dev/server-tools,vauxoo-dev/server-tools,vauxoo-dev/server-tools
--- +++ @@ -9,7 +9,7 @@ steps: [ { title: 'Wait for the main screen', - waitFor: 'h3:contains("Addons Paths")', + waitFor: 'h3:contains("Addons Paths"),#accordion.results', element: '.btn-reload', wait: 200, },
535e980c271e6e39514857c54189339a2cb7f70d
weckan/static/js/dataset.js
weckan/static/js/dataset.js
/** * Dataset page specific features */ (function($, swig){ "use strict"; var COW_URL = $('link[rel="cow"]').attr('href'), COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking'; $(function() { var name = $('meta[name="dataset-name"]').attr('content'), url = COW_API_URL.replace('{name}', name); // Fetch ranking $.get(url, function(data) { var weight = data.value.weight.toFixed(3), tpl = swig.compile($('#quality-template').text()); $('#infos-list').append(tpl({ weight: weight})); }); }); }(window.jQuery, window.swig));
/** * Dataset page specific features */ (function($, swig){ "use strict"; var QUALITY_PRECISION = 2, COW_URL = $('link[rel="cow"]').attr('href'), COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking'; $(function() { var name = $('meta[name="dataset-name"]').attr('content'), url = COW_API_URL.replace('{name}', name); // Fetch ranking $.get(url, function(data) { var weight = data.value.weight, tpl = swig.compile($('#quality-template').text()); if (weight) { $('#infos-list').append(tpl({ weight: weight.toFixed(QUALITY_PRECISION) })); } }); }); }(window.jQuery, window.swig));
Set quality precision at 2 digits and handle no weight case
Set quality precision at 2 digits and handle no weight case
JavaScript
agpl-3.0
etalab/weckan,etalab/weckan
--- +++ @@ -5,7 +5,8 @@ "use strict"; - var COW_URL = $('link[rel="cow"]').attr('href'), + var QUALITY_PRECISION = 2, + COW_URL = $('link[rel="cow"]').attr('href'), COW_API_URL = COW_URL + '/api/1/datasets/{name}/ranking'; $(function() { @@ -14,10 +15,14 @@ // Fetch ranking $.get(url, function(data) { - var weight = data.value.weight.toFixed(3), + var weight = data.value.weight, tpl = swig.compile($('#quality-template').text()); - $('#infos-list').append(tpl({ weight: weight})); + if (weight) { + $('#infos-list').append(tpl({ + weight: weight.toFixed(QUALITY_PRECISION) + })); + } }); });
4b5444a909d064ec2b8fb1e237001152816b3403
imports/api/collections/posts/publications.js
imports/api/collections/posts/publications.js
import { Meteor } from 'meteor/meteor'; import { Posts } from '../'; Meteor.publish('posts', () => Posts.find({}, { limit: 10 }));
import { Meteor } from 'meteor/meteor'; import { Posts, Comments } from '../'; Meteor.publishComposite('posts', (limit = 10) => { return { find() { return Posts.find({}, { limit, sort: { createdAt: -1, }, }); }, children: [ { find(post) { return Comments.find({ postId: post._id, }, { sort: { createdAt: -1, }, limit: 3, }); }, }, ], }; });
Join comments on posts publication
Join comments on posts publication
JavaScript
apache-2.0
evancorl/portfolio,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/skate-scenes,evancorl/portfolio,evancorl/portfolio
--- +++ @@ -1,5 +1,30 @@ import { Meteor } from 'meteor/meteor'; -import { Posts } from '../'; +import { Posts, Comments } from '../'; -Meteor.publish('posts', () => Posts.find({}, { limit: 10 })); +Meteor.publishComposite('posts', (limit = 10) => { + return { + find() { + return Posts.find({}, { + limit, + sort: { + createdAt: -1, + }, + }); + }, + children: [ + { + find(post) { + return Comments.find({ + postId: post._id, + }, { + sort: { + createdAt: -1, + }, + limit: 3, + }); + }, + }, + ], + }; +});
ae1cbbc68890a64279ba3a17ba61d8b24cdb0d2d
src/components/HomePage.js
src/components/HomePage.js
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Category from "./Category"; import {getCategories} from "../actions/Category"; import {connect} from "react-redux"; export class HomePage extends Component { componentDidMount() { this.props.getCategories(); } render() { let categories = this.props.categories; return ( <div className="container"> {categories && categories.map((category) => { return ( <div> <Category name={category.name}/> <br/> </div> ) }) } </div> ) } } const mapStateToProps = (state, props) => ({ categories: state.category.categories }); const mapDispatchToProps = dispatch => ({ getCategories: () => dispatch(getCategories()) }); HomePage.propTypes = {}; export default connect( mapStateToProps, mapDispatchToProps )(HomePage)
/** * Created by farid on 8/16/2017. */ import React, {Component} from "react"; import Category from "./Category"; import {getCategories} from "../actions/Category"; import {connect} from "react-redux"; export class HomePage extends Component { componentDidMount() { this.props.getCategories(); } render() { let categories = this.props.categories; return ( <div className="container"> {categories && categories.map((category, index) => { return ( <div key={index}> <Category name={category.name}/> <br/> </div> ) }) } </div> ) } } const mapStateToProps = (state, props) => ({ categories: state.category.categories }); const mapDispatchToProps = dispatch => ({ getCategories: () => dispatch(getCategories()) }); HomePage.propTypes = {}; export default connect( mapStateToProps, mapDispatchToProps )(HomePage)
Add key iterator for categories map
fix: Add key iterator for categories map
JavaScript
mit
faridsaud/udacity-readable-project,faridsaud/udacity-readable-project
--- +++ @@ -17,9 +17,9 @@ let categories = this.props.categories; return ( <div className="container"> - {categories && categories.map((category) => { + {categories && categories.map((category, index) => { return ( - <div> + <div key={index}> <Category name={category.name}/> <br/> </div>
0a6a8623a2ba76e88718fb733b6f87fffca58dda
src/components/HomeView.js
src/components/HomeView.js
import React, { Component } from 'react'; import { Link } from 'react-router'; class HomeView extends Component { render() { return ( <div> <Link to={"v/1"}>Video Link</Link> </div> ); } } export default HomeView;
import React, { Component } from 'react'; import { Link } from 'react-router'; class HomeView extends Component { constructor() { super(); this.state = { videos: ["hello", "world"] }; } render() { return ( <div> {this.state.videos.map((video, index) => ( <Link to={"v/1"} key={index}>Video Link</Link> ))} </div> ); } } export default HomeView;
Work on Home view links
Work on Home view links
JavaScript
mit
mg4tv/mg4tv-web,mg4tv/mg4tv-web
--- +++ @@ -2,10 +2,19 @@ import { Link } from 'react-router'; class HomeView extends Component { + constructor() { + super(); + this.state = { + videos: ["hello", "world"] + }; + } + render() { return ( <div> - <Link to={"v/1"}>Video Link</Link> + {this.state.videos.map((video, index) => ( + <Link to={"v/1"} key={index}>Video Link</Link> + ))} </div> ); }
fba75bcb6bd371d42a22bbe09a34c11631233b21
modules/roles.js
modules/roles.js
"use strict"; /*Their structure is different because of how the commands to use them are invoked.*/ module.exports = { "elevated": { "80773161284538368": "Admins", "80773196516700160": "Mods" }, "user_assignable": { "Coders" : "229748381159915520", "Techies": "229748333114163200", "Players": "222989842739363840", "Destiny": "368565663343706123" } };
"use strict"; /*Their structure is different because of how the commands to use them are invoked.*/ module.exports = { "elevated": { "80773161284538368": "Admins", "80773196516700160": "Mods" }, "user_assignable": { "Coders" : "229748381159915520", "Techies": "229748333114163200", "Players": "222989842739363840", "Destiny": "368565663343706123", "WoW": "371081851240185857" } };
Add support for WoW assigning guild
Add support for WoW assigning guild
JavaScript
mit
izy521/Sera-PCMR
--- +++ @@ -10,6 +10,7 @@ "Coders" : "229748381159915520", "Techies": "229748333114163200", "Players": "222989842739363840", - "Destiny": "368565663343706123" + "Destiny": "368565663343706123", + "WoW": "371081851240185857" } };
47034634668b0baea5cb0b13a88d2172e7e5a8ac
public/main.js
public/main.js
define(['jquery', 'underscore', 'pullManager', 'appearanceManager', 'module', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager'], function($, _, pullManager, appearanceManager, module, PullFilter, ElementFilter, Column, ConnectionManager) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); //$(appearanceManager.addCollapseSwaps); globalPullFilter.update(pullManager.getPulls()); });
define(['jquery', 'underscore', 'pullManager', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager', 'bootstrap'], // Note that not all of the required items above are represented in the function argument list. Some just need to be loaded, but that's all. function($, _, pullManager, PullFilter, ElementFilter, Column) { var spec = View; var globalPullFilter = new PullFilter(spec); var globalElementFilter = new ElementFilter(spec); _.each(spec.columns, function(columnSpec) { var pullFilter = new PullFilter(columnSpec); var elementFilter = new ElementFilter(columnSpec, globalElementFilter); var col = new Column(elementFilter, columnSpec); globalPullFilter.onUpdate(pullFilter.update); pullFilter.onUpdate(col.update); }); pullManager.onUpdate(globalPullFilter.update); globalPullFilter.update(pullManager.getPulls()); });
Change requirements to reflect reality
Change requirements to reflect reality * Add `bootstrap` so the scripts get loaded * Remove `module` and `appearanceManager` because they aren't used any more * Stop providing variables in function with modules that are only loaded for side effects
JavaScript
mit
iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher,iFixit/pulldasher
--- +++ @@ -1,5 +1,6 @@ -define(['jquery', 'underscore', 'pullManager', 'appearanceManager', 'module', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager'], - function($, _, pullManager, appearanceManager, module, PullFilter, ElementFilter, Column, ConnectionManager) { +define(['jquery', 'underscore', 'pullManager', 'PullFilter', 'ElementFilter', 'Column', 'ConnectionManager', 'bootstrap'], +// Note that not all of the required items above are represented in the function argument list. Some just need to be loaded, but that's all. + function($, _, pullManager, PullFilter, ElementFilter, Column) { var spec = View; @@ -17,7 +18,5 @@ pullManager.onUpdate(globalPullFilter.update); - //$(appearanceManager.addCollapseSwaps); - globalPullFilter.update(pullManager.getPulls()); });
0fdd418274a18fa954510053fd34c4730d2c7267
lib/preload/redir-stdout.js
lib/preload/redir-stdout.js
'use strict' const fs = require('fs') process.stdout.write = ((write) => (chunk, encoding, cb) => { if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { throw new TypeError( 'Invalid data, chunk must be a string or buffer, not ' + typeof chunk); } if (typeof encoding === 'function') { cb = encoding } fs.writeSync(3, chunk) if (typeof cb === 'function') cb() return true })(process.stdout.write.bind(process.stdout))
'use strict' const net = require('net') const socket = new net.Socket({ fd: 3, readable: false, writable: true }) Object.defineProperty(process, 'stdout', { configurable: true, enumerable: true, get: () => socket })
Change process.stdout switcharoo to a full net.Socket instance
Change process.stdout switcharoo to a full net.Socket instance No matter how you write to stdout, this should catch it! The `defineProperty` call uses the same options as the default `process.stdout`.
JavaScript
mit
davidmarkclements/0x
--- +++ @@ -1,14 +1,13 @@ 'use strict' -const fs = require('fs') -process.stdout.write = ((write) => (chunk, encoding, cb) => { - if (typeof chunk !== 'string' && !(chunk instanceof Buffer)) { - throw new TypeError( - 'Invalid data, chunk must be a string or buffer, not ' + typeof chunk); - } - if (typeof encoding === 'function') { - cb = encoding - } - fs.writeSync(3, chunk) - if (typeof cb === 'function') cb() - return true -})(process.stdout.write.bind(process.stdout)) +const net = require('net') + +const socket = new net.Socket({ + fd: 3, + readable: false, + writable: true +}) +Object.defineProperty(process, 'stdout', { + configurable: true, + enumerable: true, + get: () => socket +})
a4f4dd98a2b78ed66af02761d33ebbc8dd5e516d
src/shared/components/libs/ExperimentImages.js
src/shared/components/libs/ExperimentImages.js
import React from "react"; class ExperimentImages extends React.Component { constructor() { super(); } render() { let imageDiv = this.props.images.map(url => { return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) }); return ( <div className="images"> {imageDiv} </div> ); } } module.exports = ExperimentImages;
import React from "react"; class ExperimentImages extends React.Component { constructor() { super(); } render() { let imageDiv = null; if(this.props.images) { imageDiv = this.props.images.map(url => { return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) }); } return ( <div className="images"> {imageDiv} </div> ); } } module.exports = ExperimentImages;
Fix undefined this.props.images. Change between experiments will be smoother
Fix undefined this.props.images. Change between experiments will be smoother
JavaScript
mit
olavvatne/ml-monitor
--- +++ @@ -8,9 +8,12 @@ render() { - let imageDiv = this.props.images.map(url => { - return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) - }); + let imageDiv = null; + if(this.props.images) { + imageDiv = this.props.images.map(url => { + return (<a href={url} target="_blank"><img src={url} alt="experiment image"/></a>) + }); + } return ( <div className="images"> {imageDiv}
763e473a5fc126fdbb5d0cf666683c8d9d869e7c
lib/model/classes/StyleSheetExtension.js
lib/model/classes/StyleSheetExtension.js
var props = require("../properties/all.js"); var BaseObj = require("../BaseObj"); var obj = BaseObj.create("XWiki.StyleSheetExtension"); obj.addProp("name", props.XString.create({ "prettyName": "Name", "size": "30" })); obj.addProp("code", props.TextArea.create({ "prettyName": "Code" })); obj.addProp("use", props.StaticList.create({ "prettyName": "Use this extension", "values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki" })); obj.addProp("parse", props.XBoolean.create({ "prettyName": "Parse content" })); obj.addProp("cache", props.StaticList.create({ "prettyName": "Caching policy", "values": "long|short|default|forbid" })); module.exports.create = function () { return obj.instance(); };
var props = require("../properties/all.js"); var BaseObj = require("../BaseObj"); var obj = BaseObj.create("XWiki.StyleSheetExtension"); obj.addProp("cache", props.StaticList.create({ "prettyName": "Caching policy", "values": "long|short|default|forbid" })); obj.addProp("code", props.TextArea.create({ "prettyName": "Code" })); obj.addProp("name", props.XString.create({ "prettyName": "Name", "size": "30" })); obj.addProp("parse", props.XBoolean.create({ "prettyName": "Parse content" })); obj.addProp("use", props.StaticList.create({ "prettyName": "Use this extension", "values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki" })); module.exports.create = function () { return obj.instance(); };
Reorder property to keep XWiki order
Reorder property to keep XWiki order
JavaScript
agpl-3.0
xwiki-contrib/node-xwikimodel
--- +++ @@ -2,24 +2,24 @@ var BaseObj = require("../BaseObj"); var obj = BaseObj.create("XWiki.StyleSheetExtension"); +obj.addProp("cache", props.StaticList.create({ + "prettyName": "Caching policy", + "values": "long|short|default|forbid" +})); +obj.addProp("code", props.TextArea.create({ + "prettyName": "Code" +})); obj.addProp("name", props.XString.create({ "prettyName": "Name", "size": "30" })); -obj.addProp("code", props.TextArea.create({ - "prettyName": "Code" +obj.addProp("parse", props.XBoolean.create({ + "prettyName": "Parse content" })); obj.addProp("use", props.StaticList.create({ "prettyName": "Use this extension", "values": "currentPage=Always on this page|onDemand=On demand|always=Always on this wiki" })); -obj.addProp("parse", props.XBoolean.create({ - "prettyName": "Parse content" -})); -obj.addProp("cache", props.StaticList.create({ - "prettyName": "Caching policy", - "values": "long|short|default|forbid" -})); module.exports.create = function () { return obj.instance();
32a7a99b61968f88f1d62c98275b755f3990d1a9
src/styles/Images/assets/index.js
src/styles/Images/assets/index.js
export default { BackgroundsPlus: require("./backgrounds-plus.jpg") };
import React from "react"; import Image from "../../../components/Image" export const BackgroundsPlus = p => <Image {...p} src={require("./backgrounds-plus.jpg")} />
Deploy to GitHub pages
Deploy to GitHub pages [ci skip]
JavaScript
mit
tutti-ch/react-styleguide,tutti-ch/react-styleguide
--- +++ @@ -1,3 +1,3 @@ -export default { - BackgroundsPlus: require("./backgrounds-plus.jpg") -}; +import React from "react"; +import Image from "../../../components/Image" +export const BackgroundsPlus = p => <Image {...p} src={require("./backgrounds-plus.jpg")} />
23d59b4908f2b48934207b711221026859797820
src/components/RespondToPetitionForm/fields.js
src/components/RespondToPetitionForm/fields.js
import settings from 'settings'; export default [ { element: 'input', name: 'petitionId', hidden: true, html: { type: 'hidden' } }, { element: 'input', name: 'token', hidden: true, html: { type: 'hidden' } }, { element: 'textarea', name: 'answer.text', label: settings.respondToPetitionFields.response.label, hint: settings.respondToPetitionFields.response.hint, html: { placeholder: settings.respondToPetitionFields.response.placeholder, required: true, minLength: 50, maxLength: 500 } }, { element: 'input', name: 'answer.name', label: settings.respondToPetitionFields.name.label, hint: settings.respondToPetitionFields.name.hint, html: { type: 'text', placeholder: settings.respondToPetitionFields.name.placeholder, required: true, minLength: 15, maxLength: 80 } } ];
import settings from 'settings'; export default [ { element: 'input', name: 'petitionId', hidden: true, html: { type: 'hidden' } }, { element: 'input', name: 'token', hidden: true, html: { type: 'hidden' } }, { element: 'textarea', name: 'answer.text', label: settings.respondToPetitionFields.response.label, hint: settings.respondToPetitionFields.response.hint, html: { placeholder: settings.respondToPetitionFields.response.placeholder, required: true, minLength: 50, maxLength: 10000 } }, { element: 'input', name: 'answer.name', label: settings.respondToPetitionFields.name.label, hint: settings.respondToPetitionFields.name.hint, html: { type: 'text', placeholder: settings.respondToPetitionFields.name.placeholder, required: true, minLength: 15, maxLength: 80 } } ];
Increase max length of petition answer text
Increase max length of petition answer text
JavaScript
apache-2.0
iris-dni/iris-frontend,iris-dni/iris-frontend,iris-dni/iris-frontend
--- +++ @@ -26,7 +26,7 @@ placeholder: settings.respondToPetitionFields.response.placeholder, required: true, minLength: 50, - maxLength: 500 + maxLength: 10000 } }, {
5590ae2a489a339abf3e3694d3ba31ea0d31fa36
src/ol/source/topojsonsource.js
src/ol/source/topojsonsource.js
goog.provide('ol.source.TopoJSON'); goog.require('ol.format.TopoJSON'); goog.require('ol.source.VectorFile'); /** * @constructor * @extends {ol.source.VectorFile} * @param {olx.source.TopoJSONOptions=} opt_options Options. */ ol.source.TopoJSON = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; goog.base(this, { attributions: options.attributions, extent: options.extent, format: new ol.format.TopoJSON({ defaultProjection: options.defaultProjection }), logo: options.logo, object: options.object, projection: options.projection, reprojectTo: options.reprojectTo, text: options.text, url: options.url }); }; goog.inherits(ol.source.TopoJSON, ol.source.VectorFile);
goog.provide('ol.source.TopoJSON'); goog.require('ol.format.TopoJSON'); goog.require('ol.source.VectorFile'); /** * @constructor * @extends {ol.source.VectorFile} * @param {olx.source.TopoJSONOptions=} opt_options Options. * @todo stability experimental */ ol.source.TopoJSON = function(opt_options) { var options = goog.isDef(opt_options) ? opt_options : {}; goog.base(this, { attributions: options.attributions, extent: options.extent, format: new ol.format.TopoJSON({ defaultProjection: options.defaultProjection }), logo: options.logo, object: options.object, projection: options.projection, reprojectTo: options.reprojectTo, text: options.text, url: options.url }); }; goog.inherits(ol.source.TopoJSON, ol.source.VectorFile);
Add stability annotation to ol.source.TopoJSON
Add stability annotation to ol.source.TopoJSON
JavaScript
bsd-2-clause
oterral/ol3,tschaub/ol3,denilsonsa/ol3,openlayers/openlayers,bogdanvaduva/ol3,ahocevar/ol3,geekdenz/ol3,gingerik/ol3,alexbrault/ol3,alvinlindstam/ol3,thhomas/ol3,jmiller-boundless/ol3,CandoImage/ol3,fblackburn/ol3,jacmendt/ol3,bartvde/ol3,mechdrew/ol3,geekdenz/ol3,bill-chadwick/ol3,pmlrsg/ol3,antonio83moura/ol3,kkuunnddaannkk/ol3,Andrey-Pavlov/ol3,kjelderg/ol3,bill-chadwick/ol3,NOAA-ORR-ERD/ol3,bartvde/ol3,alvinlindstam/ol3,klokantech/ol3,denilsonsa/ol3,geekdenz/openlayers,Antreasgr/ol3,planetlabs/ol3,CandoImage/ol3,wlerner/ol3,NOAA-ORR-ERD/ol3,landonb/ol3,openlayers/openlayers,bartvde/ol3,antonio83moura/ol3,wlerner/ol3,stweil/openlayers,gingerik/ol3,denilsonsa/ol3,fredj/ol3,fperucic/ol3,tamarmot/ol3,geonux/ol3,tamarmot/ol3,alexbrault/ol3,xiaoqqchen/ol3,klokantech/ol3raster,planetlabs/ol3,Antreasgr/ol3,antonio83moura/ol3,geonux/ol3,adube/ol3,tsauerwein/ol3,richstoner/ol3,landonb/ol3,fperucic/ol3,kjelderg/ol3,epointal/ol3,richstoner/ol3,planetlabs/ol3,klokantech/ol3,bogdanvaduva/ol3,tamarmot/ol3,stweil/ol3,fblackburn/ol3,fperucic/ol3,kkuunnddaannkk/ol3,Distem/ol3,kkuunnddaannkk/ol3,epointal/ol3,geonux/ol3,mechdrew/ol3,bjornharrtell/ol3,ahocevar/ol3,jmiller-boundless/ol3,jacmendt/ol3,freylis/ol3,thomasmoelhave/ol3,geekdenz/ol3,Andrey-Pavlov/ol3,fperucic/ol3,tschaub/ol3,wlerner/ol3,tamarmot/ol3,mechdrew/ol3,stweil/ol3,NOAA-ORR-ERD/ol3,aisaacs/ol3,denilsonsa/ol3,bill-chadwick/ol3,Distem/ol3,aisaacs/ol3,richstoner/ol3,itayod/ol3,aisaacs/ol3,t27/ol3,openlayers/openlayers,gingerik/ol3,ahocevar/openlayers,hafenr/ol3,bartvde/ol3,geonux/ol3,fredj/ol3,adube/ol3,t27/ol3,mzur/ol3,klokantech/ol3,fredj/ol3,jacmendt/ol3,ahocevar/openlayers,Andrey-Pavlov/ol3,das-peter/ol3,bogdanvaduva/ol3,stweil/ol3,llambanna/ol3,pmlrsg/ol3,elemoine/ol3,gingerik/ol3,epointal/ol3,fblackburn/ol3,richstoner/ol3,alexbrault/ol3,das-peter/ol3,ahocevar/ol3,aisaacs/ol3,fblackburn/ol3,llambanna/ol3,alvinlindstam/ol3,mzur/ol3,fredj/ol3,jmiller-boundless/ol3,oterral/ol3,Morgul/ol3,CandoImage/ol3,hafenr/ol3,Distem/ol3,thhomas/ol3,ahocevar/openlayers,elemoine/ol3,klokantech/ol3,Distem/ol3,stweil/ol3,klokantech/ol3raster,Morgul/ol3,elemoine/ol3,geekdenz/openlayers,alvinlindstam/ol3,Morgul/ol3,das-peter/ol3,tsauerwein/ol3,epointal/ol3,Morgul/ol3,adube/ol3,Antreasgr/ol3,itayod/ol3,NOAA-ORR-ERD/ol3,kkuunnddaannkk/ol3,t27/ol3,klokantech/ol3raster,ahocevar/ol3,thhomas/ol3,stweil/openlayers,bill-chadwick/ol3,bjornharrtell/ol3,landonb/ol3,klokantech/ol3raster,bogdanvaduva/ol3,llambanna/ol3,xiaoqqchen/ol3,t27/ol3,alexbrault/ol3,planetlabs/ol3,freylis/ol3,thomasmoelhave/ol3,mzur/ol3,pmlrsg/ol3,itayod/ol3,das-peter/ol3,CandoImage/ol3,thomasmoelhave/ol3,antonio83moura/ol3,kjelderg/ol3,tschaub/ol3,hafenr/ol3,freylis/ol3,thhomas/ol3,jmiller-boundless/ol3,hafenr/ol3,kjelderg/ol3,mechdrew/ol3,freylis/ol3,Andrey-Pavlov/ol3,Antreasgr/ol3,xiaoqqchen/ol3,tsauerwein/ol3,geekdenz/openlayers,bjornharrtell/ol3,itayod/ol3,oterral/ol3,stweil/openlayers,geekdenz/ol3,jacmendt/ol3,mzur/ol3,xiaoqqchen/ol3,wlerner/ol3,tschaub/ol3,thomasmoelhave/ol3,tsauerwein/ol3,elemoine/ol3,jmiller-boundless/ol3,llambanna/ol3,landonb/ol3,pmlrsg/ol3
--- +++ @@ -9,6 +9,7 @@ * @constructor * @extends {ol.source.VectorFile} * @param {olx.source.TopoJSONOptions=} opt_options Options. + * @todo stability experimental */ ol.source.TopoJSON = function(opt_options) {
b8b145fee10b51f99deefc86001fa745cc2e96da
test/resourceful-webhooks-test.js
test/resourceful-webhooks-test.js
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
var http = require('http'), assert = require('assert'), cb = require('assert-called'), resourceful = require('resourceful'); require('../'); var PORT = 8123, gotCallbacks = 0; function maybeEnd() { if (++gotCallbacks === 2) { server.close(); } } var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); assert.equal(req.headers['content-type'], 'application/json'); var data = ''; req.on('data', function (chunk) { data += chunk; }); req.on('end', function () { data = JSON.parse(data); if (data.hello === 'world') { res.writeHead(200); res.end(); } else if (data.hello === 'universe') { res.writeHead(400); res.end(); } else { assert(false); } maybeEnd(); }); }).listen(PORT); var Resource = resourceful.define('Resource', function () { this.webhooks({ url: 'http://127.0.0.1:' + PORT.toString(), events: ['create'] }); }); Resource.create({ id: 'resource/good', hello: 'world' }, cb(function goodCb(err) { assert(!err); })); Resource.create({ id: 'resource/bad', hello: 'universe' }, cb(function badCb(err) { assert(err); }));
Add a failing test for `content-type` header
[test] Add a failing test for `content-type` header
JavaScript
mit
mmalecki/resourceful-webhooks,mmalecki/resourceful-webhooks
--- +++ @@ -16,6 +16,7 @@ var server = http.createServer(function (req, res) { assert.equal(req.url, '/?event=create'); + assert.equal(req.headers['content-type'], 'application/json'); var data = '';
3a1f44610586e3a984b2a5a468132be81038fca1
packages/server-render/package.js
packages/server-render/package.js
Package.describe({ name: "server-render", version: "0.1.0", summary: "Generic support for server-side rendering in Meteor apps", documentation: "README.md" }); Npm.depends({ "magic-string": "0.21.3", "parse5": "3.0.2" }); Package.onUse(function(api) { api.use("ecmascript"); api.use("webapp@1.3.17"); api.mainModule("server-render.js", "server"); }); Package.onTest(function(api) { api.use("ecmascript"); api.use("tinytest"); api.use("server-render"); api.mainModule("server-render-tests.js", "server"); });
Package.describe({ name: "server-render", version: "0.1.0", summary: "Generic support for server-side rendering in Meteor apps", documentation: "README.md" }); Npm.depends({ "magic-string": "0.21.3", "parse5": "3.0.2" }); Package.onUse(function(api) { api.use("ecmascript"); api.use("webapp"); api.mainModule("server-render.js", "server"); }); Package.onTest(function(api) { api.use("ecmascript"); api.use("tinytest"); api.use("server-render"); api.mainModule("server-render-tests.js", "server"); });
Remove webapp version constraint for now.
Remove webapp version constraint for now. The server-render package requires webapp@1.3.17 or later, but using a non-prerelease version contraint for a package involved in the release (i.e., webapp) is tricky during the prerelease phase, since the -beta.n version is strictly enforced.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -12,7 +12,7 @@ Package.onUse(function(api) { api.use("ecmascript"); - api.use("webapp@1.3.17"); + api.use("webapp"); api.mainModule("server-render.js", "server"); });
b8424424ae7e46f2b0fbc36d16a8a1d41f6e66c5
src/scripts/scanRepliesAndNotify.js
src/scripts/scanRepliesAndNotify.js
import lib from './lib'; import redis from 'src/lib/redisClient'; import addTime from 'date-fns/add'; import Client from 'src/database/mongoClient'; export default async function scanRepliesAndNotify() { const timeOffset = JSON.parse(process.env.REVIEW_REPLY_BUFFER) || {}; const lastScannedAt = (await redis.get('lastScannedAt')) || addTime(new Date(), { days: -90 }).toISOString(); console.log('[notify] lastScannedAt:' + lastScannedAt); const nowWithOffset = addTime(new Date(), timeOffset).toISOString(); const notificationList = await lib.getNotificationList( lastScannedAt, nowWithOffset ); await lib.sendNotification(notificationList); await redis.set('lastScannedAt', nowWithOffset); // disconnect redis and mongodb await redis.quit(); await (await Client.getInstance()).close(); } if (require.main === module) { scanRepliesAndNotify(); }
import lib from './lib'; import redis from 'src/lib/redisClient'; import rollbar from 'src/lib/rollbar'; import addTime from 'date-fns/add'; import Client from 'src/database/mongoClient'; export default async function scanRepliesAndNotify() { const timeOffset = JSON.parse(process.env.REVIEW_REPLY_BUFFER) || {}; const lastScannedAt = (await redis.get('lastScannedAt')) || addTime(new Date(), { days: -90 }).toISOString(); console.log('[notify] lastScannedAt:' + lastScannedAt); const nowWithOffset = addTime(new Date(), timeOffset).toISOString(); const notificationList = await lib.getNotificationList( lastScannedAt, nowWithOffset ); await lib.sendNotification(notificationList); await redis.set('lastScannedAt', nowWithOffset); // disconnect redis and mongodb await redis.quit(); await (await Client.getInstance()).close(); } if (require.main === module) { scanRepliesAndNotify().catch(e => { console.error(e); rollbar.error(e); process.exit(1); }); }
Add error handler and send error to rollbar
Add error handler and send error to rollbar
JavaScript
mit
cofacts/rumors-line-bot,cofacts/rumors-line-bot,cofacts/rumors-line-bot
--- +++ @@ -1,5 +1,6 @@ import lib from './lib'; import redis from 'src/lib/redisClient'; +import rollbar from 'src/lib/rollbar'; import addTime from 'date-fns/add'; import Client from 'src/database/mongoClient'; @@ -24,5 +25,9 @@ } if (require.main === module) { - scanRepliesAndNotify(); + scanRepliesAndNotify().catch(e => { + console.error(e); + rollbar.error(e); + process.exit(1); + }); }
660dc74cef1a6a3f7da701b57e9f3f71ccd6bb57
app/js/arethusa.core/directives/sentence_list.js
app/js/arethusa.core/directives/sentence_list.js
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
"use strict"; angular.module('arethusa.core').directive('sentenceList', [ '$compile', 'navigator', function($compile, navigator) { return { restrict: 'A', scope: true, link: function(scope, element, attrs) { scope.n = navigator; function createList() { // We want this to load only once, and only if // a user requests it! if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ <div id="canvas" class="row panel full-height scrollable" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\ sentence="s"\ ng-repeat="s in n.sentences">\ </li>\ </ul>\ </div>\ '; navigator.list().append($compile(template)(scope)); navigator.hasList = true; } } scope.$on('viewModeSwitched', createList); element.bind('click', function() { createList(); scope.$apply(function() { navigator.switchView(); }); }); } }; } ]);
Make sentenceList scrollable at all times
Make sentenceList scrollable at all times
JavaScript
mit
alpheios-project/arethusa,fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,alpheios-project/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,latin-language-toolkit/arethusa,fbaumgardt/arethusa
--- +++ @@ -16,7 +16,7 @@ if (! navigator.hasList) { var template = '\ <div class="canvas-border"/>\ - <div id="canvas" class="row panel full-height" full-height>\ + <div id="canvas" class="row panel full-height scrollable" full-height>\ <ul class="sentence-list">\ <li \ class="sentence-list"\
dddad05c90b4772a3f4b8c73b5223e044aa65872
app/views/emailConfirmation/emailConfirmation.js
app/views/emailConfirmation/emailConfirmation.js
angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"]) .config(function($routeProvider) { "use strict"; $routeProvider.when("/confirmpreregistration", { templateUrl: "views/emailConfirmation/emailConfirmation.html", controller: "EmailConfirmationCtrl", }); }) .controller("EmailConfirmationCtrl", function($scope, $location, $mdDialog, $routeParams, Registration) { "use strict"; $scope.verifying = true; $scope.error = false; $scope.email = $routeParams.email; var token = $routeParams.token; if (!angular.isDefined($scope.email) || !angular.isDefined(token)) { $location.path("/register") } else { Registration.confirmEmail($scope.email, token).then(function() { $scope.verifying = false; }, function(resp) { $scope.verifying = false; $scope.error = resp.data.trim(); }); } });
angular.module("ccj16reg.view.emailConfirmation", ["ngRoute", "ngMaterial", "ccj16reg.registration"]) .config(function($routeProvider) { "use strict"; $routeProvider.when("/confirmpreregistration", { templateUrl: "views/emailConfirmation/emailConfirmation.html", controller: "EmailConfirmationCtrl", }); }) .controller("EmailConfirmationCtrl", function($scope, $location, $routeParams, Registration) { "use strict"; $scope.verifying = true; $scope.error = false; $scope.email = $routeParams.email; var token = $routeParams.token; if (!angular.isDefined($scope.email) || !angular.isDefined(token)) { $location.path("/register") } else { Registration.confirmEmail($scope.email, token).then(function() { $scope.verifying = false; }, function(resp) { $scope.verifying = false; $scope.error = resp.data.trim(); }); } });
Remove unnecessary $mdDialog from the EmailConfirmationCtrl.
Remove unnecessary $mdDialog from the EmailConfirmationCtrl.
JavaScript
agpl-3.0
CCJ16/registration,CCJ16/registration,CCJ16/registration
--- +++ @@ -8,7 +8,7 @@ }); }) -.controller("EmailConfirmationCtrl", function($scope, $location, $mdDialog, $routeParams, Registration) { +.controller("EmailConfirmationCtrl", function($scope, $location, $routeParams, Registration) { "use strict"; $scope.verifying = true; $scope.error = false;
a0ec4aae2d9b4e07f281d49235d11543ffb9066f
cli.js
cli.js
#! /usr/bin/env node const args = process.argv const command = args[2] const config = { app_dir: process.env.HOME + '/.stay' } if (!command) { require('./cli/help')(args, config) process.exit(1) } try { require('./cli/' + command)(args, config) } catch (err) { console.log(err) if (err.code === 'MODULE_NOT_FOUND') { console.log('Command "' + command + '" not found') } else { throw new Error(err) } } const mkdirp = require('mkdirp') mkdirp.sync(config.app_dir)
#! /usr/bin/env node const fs = require('fs') const args = process.argv const command = args[2] const config = { app_dir: process.env.HOME + '/.stay' } try { fs.accessSync(config.app_dir, fs.F_OK) } catch (e) { const mkdirp = require('mkdirp') mkdirp.sync(config.app_dir) } if (!command) { require('./cli/help')(args, config) process.exit(1) } try { require('./cli/' + command)(args, config) } catch (Err) { if (Err.code === 'MODULE_NOT_FOUND') { console.log('Command "' + command + '" not found') } else { throw Err } }
Initialize config only if not exists
Initialize config only if not exists
JavaScript
mit
EverythingStays/stay-cli,EverythingStays/stay-cli
--- +++ @@ -1,10 +1,18 @@ #! /usr/bin/env node +const fs = require('fs') const args = process.argv const command = args[2] const config = { app_dir: process.env.HOME + '/.stay' +} + +try { + fs.accessSync(config.app_dir, fs.F_OK) +} catch (e) { + const mkdirp = require('mkdirp') + mkdirp.sync(config.app_dir) } if (!command) { @@ -14,14 +22,10 @@ try { require('./cli/' + command)(args, config) -} catch (err) { - console.log(err) - if (err.code === 'MODULE_NOT_FOUND') { +} catch (Err) { + if (Err.code === 'MODULE_NOT_FOUND') { console.log('Command "' + command + '" not found') } else { - throw new Error(err) + throw Err } } - -const mkdirp = require('mkdirp') -mkdirp.sync(config.app_dir)
ae645ad9f0173639dfaf642928684849e4a16ec1
src/logger.js
src/logger.js
/* Copyright 2018 André Jaenisch Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @module logger */ const log = require("loglevel"); // This is to demonstrate, that you can use any namespace you want. // Namespaces allow you to turn on/off the logging for specific parts of the // application. // An idea would be to control this via an environment variable (on Node.js). // See https://www.npmjs.com/package/debug to see how this could be implemented // Part of #332 is introducing a logging library in the first place. const DEFAULT_NAME_SPACE = "matrix"; const logger = log.getLogger(DEFAULT_NAME_SPACE); logger.setLevel(log.levels.DEBUG); /** * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}. * Can be tailored down to specific use cases if needed. */ export default logger;
/* Copyright 2018 André Jaenisch Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ /** * @module logger */ const log = require("loglevel"); // This is to demonstrate, that you can use any namespace you want. // Namespaces allow you to turn on/off the logging for specific parts of the // application. // An idea would be to control this via an environment variable (on Node.js). // See https://www.npmjs.com/package/debug to see how this could be implemented // Part of #332 is introducing a logging library in the first place. const DEFAULT_NAME_SPACE = "matrix"; const logger = log.getLogger(DEFAULT_NAME_SPACE); logger.setLevel(log.levels.DEBUG); /** * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}. * Can be tailored down to specific use cases if needed. */ module.exports = logger;
Use Node.js module export, since ES6 export breaks build.
Use Node.js module export, since ES6 export breaks build. Signed-off-by: André Jaenisch <2c685275bd32aff3e28a84de6a3e3ac9f1b2b901@posteo.de>
JavaScript
apache-2.0
krombel/matrix-js-sdk,krombel/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk,krombel/matrix-js-sdk,matrix-org/matrix-js-sdk,matrix-org/matrix-js-sdk
--- +++ @@ -33,4 +33,4 @@ * Drop-in replacement for <code>console</code> using {@link https://www.npmjs.com/package/loglevel|loglevel}. * Can be tailored down to specific use cases if needed. */ -export default logger; +module.exports = logger;
b9835c9a26829fd36917d16a1a6813f9d54e9d3f
client/app/scripts/services/googleMapsService.js
client/app/scripts/services/googleMapsService.js
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { /* // Load the Google Maps scripts Asynchronously (function(d){ var js, id = 'google-maps', ref = d.getElementsByTagName('script')[0]; if (d.getElementById(id)) {return;} js = d.createElement('script'); js.id = id; js.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"; ref.parentNode.insertBefore(js, ref); }(document)); */ var methods = {}; methods.geo = function(address, type) { //var deferred = $q.defer(); var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { console.log(results[0]); geoData.lat = results[0].geometry.location.mb; // mb geoData.lng = results[0].geometry.location.nb; // nb // @todo why is this the new format? // did things change on the Google API side? if (!geoData.lat || !geoData.lng) { geoData.lat = results[0].geometry.location.ob; // mb geoData.lng = results[0].geometry.location.pb; // nb } if (!geoData.lat || !geoData.lng) { $rootScope.$broadcast('event:geo-location-failure'); } else { $rootScope.$broadcast('event:geo-location-success', geoData, type); } } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); //return deferred.promise; }; return methods; } ]);
angular .module('app') .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { var methods = {}; methods.geo = function(address, type) { var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { if (status == google.maps.GeocoderStatus.OK) { var location = results[0].geometry.location; geoData.lng = location.lng(); geoData.lat = location.lat(); $rootScope.$broadcast('event:geo-location-success', geoData, type); } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); //alert('Geocode was not successful for the following reason: ' + status); } }; geocoder.geocode({ 'address': address }, handleResult); }; return methods; } ]);
Make the digestion of the google geo result standardized
Make the digestion of the google geo result standardized
JavaScript
mit
brettshollenberger/mrl001,brettshollenberger/mrl001
--- +++ @@ -3,45 +3,23 @@ .factory('googleMapsService', ['$rootScope', '$q', function($rootScope, $q) { - /* -// Load the Google Maps scripts Asynchronously - (function(d){ - var js, id = 'google-maps', ref = d.getElementsByTagName('script')[0]; - if (d.getElementById(id)) {return;} - js = d.createElement('script'); js.id = id; - js.src = "https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"; - ref.parentNode.insertBefore(js, ref); - }(document)); -*/ - var methods = {}; methods.geo = function(address, type) { - //var deferred = $q.defer(); var geocoder = new google.maps.Geocoder(); var geoData = {}; var handleResult = function(results, status) { + if (status == google.maps.GeocoderStatus.OK) { - console.log(results[0]); - geoData.lat = results[0].geometry.location.mb; // mb - geoData.lng = results[0].geometry.location.nb; // nb + var location = results[0].geometry.location; + geoData.lng = location.lng(); + geoData.lat = location.lat(); - // @todo why is this the new format? - // did things change on the Google API side? - if (!geoData.lat || !geoData.lng) { - geoData.lat = results[0].geometry.location.ob; // mb - geoData.lng = results[0].geometry.location.pb; // nb - } - - if (!geoData.lat || !geoData.lng) { - $rootScope.$broadcast('event:geo-location-failure'); - } else { - $rootScope.$broadcast('event:geo-location-success', geoData, type); - } + $rootScope.$broadcast('event:geo-location-success', geoData, type); } else { $rootScope.$broadcast('event:geo-location-failure', geoData, type); @@ -52,8 +30,6 @@ geocoder.geocode({ 'address': address }, handleResult); - - //return deferred.promise; }; return methods;
2d3954d279f686187369dfeb673f49f6dd050988
lib/server/server_router.js
lib/server/server_router.js
var connect = Npm.require('connect'); var Fiber = Npm.require('fibers'); var root = global; var connectHandlers , connect; if (typeof __meteor_bootstrap__.app !== 'undefined') { connectHandlers = __meteor_bootstrap__.app; } else { connectHandlers = WebApp.connectHandlers; } ServerRouter = RouterUtils.extend(IronRouter, { constructor: function () { var self = this; ServerRouter.__super__.constructor.apply(this, arguments); this.start(); }, onRun: function (controller, context, options) { var response = context.options.response; try { this.runController(controller, context); } finally { response.end(); } }, start: function () { connectHandlers .use(connect.query()) .use(connect.bodyParser()) .use(_.bind(this.onRequest, this)); }, onRequest: function (req, res, next) { var self = this; Fiber(function () { self.dispatch(req.url, { request: req, response: res, next: next }); }).run(); }, stop: function () { }, onUnhandled: function (path, options) { options.next(); }, onRouteNotFound: function (path, options) { options.next(); } }); Router = new ServerRouter;
var connect = Npm.require('connect'); var Fiber = Npm.require('fibers'); var root = global; var connectHandlers , connect; if (typeof __meteor_bootstrap__.app !== 'undefined') { connectHandlers = __meteor_bootstrap__.app; } else { connectHandlers = WebApp.connectHandlers; } ServerRouter = RouterUtils.extend(IronRouter, { constructor: function () { var self = this; ServerRouter.__super__.constructor.apply(this, arguments); Meteor.startup(function () { setTimeout(function () { if (self.options.autoStart !== false) self.start(); }); }); }, onRun: function (controller, context, options) { var response = context.options.response; try { this.runController(controller, context); } finally { response.end(); } }, start: function () { connectHandlers .use(connect.query()) .use(connect.bodyParser()) .use(_.bind(this.onRequest, this)); }, onRequest: function (req, res, next) { var self = this; Fiber(function () { self.dispatch(req.url, { request: req, response: res, next: next }); }).run(); }, stop: function () { }, onUnhandled: function (path, options) { options.next(); }, onRouteNotFound: function (path, options) { options.next(); } }); Router = new ServerRouter;
Allow apps to kill the server router.
Allow apps to kill the server router.
JavaScript
mit
Aaron1992/iron-router,Sombressoul/iron-router,leoetlino/iron-router,abhiaiyer91/iron-router,Aaron1992/iron-router,assets1975/iron-router,TechplexEngineer/iron-router,Hyparman/iron-router,jg3526/iron-router,tianzhihen/iron-router,jg3526/iron-router,firdausramlan/iron-router,iron-meteor/iron-router,DanielDornhardt/iron-router-2,snamoah/iron-router,ecuanaso/iron-router,DanielDornhardt/iron-router-2,snamoah/iron-router,iron-meteor/iron-router,firdausramlan/iron-router,sean-stanley/iron-router,ecuanaso/iron-router,TechplexEngineer/iron-router,sean-stanley/iron-router,Hyparman/iron-router,tianzhihen/iron-router,abhiaiyer91/iron-router,appoets/iron-router,assets1975/iron-router,appoets/iron-router,Sombressoul/iron-router
--- +++ @@ -16,7 +16,12 @@ constructor: function () { var self = this; ServerRouter.__super__.constructor.apply(this, arguments); - this.start(); + Meteor.startup(function () { + setTimeout(function () { + if (self.options.autoStart !== false) + self.start(); + }); + }); }, onRun: function (controller, context, options) {
d58e398584d35be2ff852d241dbdd0af439f5716
packages/truffle-core/index.js
packages/truffle-core/index.js
var pkg = require("./package.json"); module.exports = { build: require("./lib/build"), create: require("./lib/create"), compiler: require("truffle-compile"), config: require("./lib/config"), console: require("./lib/repl"), contracts: require("./lib/contracts"), require: require("truffle-require"), init: require("./lib/init"), migrate: require("truffle-migrate"), package: require("./lib/package"), serve: require("./lib/serve"), sources: require("truffle-contract-sources"), test: require("./lib/test"), version: pkg.version };
var pkg = require("./package.json"); module.exports = { build: require("./lib/build"), create: require("./lib/create"), config: require("./lib/config"), console: require("./lib/repl"), contracts: require("./lib/contracts"), init: require("./lib/init"), package: require("./lib/package"), serve: require("./lib/serve"), test: require("./lib/test"), version: pkg.version };
Remove references to items that have been pulled out into their own modules.
Remove references to items that have been pulled out into their own modules.
JavaScript
mit
ConsenSys/truffle
--- +++ @@ -3,16 +3,12 @@ module.exports = { build: require("./lib/build"), create: require("./lib/create"), - compiler: require("truffle-compile"), config: require("./lib/config"), console: require("./lib/repl"), contracts: require("./lib/contracts"), - require: require("truffle-require"), init: require("./lib/init"), - migrate: require("truffle-migrate"), package: require("./lib/package"), serve: require("./lib/serve"), - sources: require("truffle-contract-sources"), test: require("./lib/test"), version: pkg.version };
326466c2a866cd27749d6d5561f23b674840fd67
packages/jest-environment-enzyme/src/setup.js
packages/jest-environment-enzyme/src/setup.js
/* eslint-disable global-require */ export const exposeGlobals = () => { let dep; switch (global.enzymedepDescriptor) { case 'react13': dep = 'enzyme-adapter-react-13'; break; case 'react14': dep = 'enzyme-adapter-react-14'; break; case 'react15': dep = 'enzyme-adapter-react-15'; break; case 'react15.4': dep = 'enzyme-adapter-react-15.4'; break; case 'react16': default: dep = 'enzyme-adapter-react-16'; } let Adapter; try { Adapter = require(dep); } catch (e) { console.error( ` Requiring the proper enzyme-adapter during jest-enzyme setup failed. This most likely happens when your application does not properly list the adapter in your devDependencies. Run this line to add the correct adapter: > yarn add --dev ${dep} or with npm > npm i --save-dev ${dep} ` ); return; } const { configure, mount, render, shallow } = require('enzyme'); // Setup Enzyme Adapter configure({ adapter: new Adapter() }); global.shallow = shallow; global.mount = mount; global.render = render; global.React = require('react'); };
/* eslint-disable global-require */ // eslint-disable-next-line import/prefer-default-export export const exposeGlobals = () => { let dep; switch (global.enzymeAdapterDescriptor) { case 'react13': dep = 'enzyme-adapter-react-13'; break; case 'react14': dep = 'enzyme-adapter-react-14'; break; case 'react15': dep = 'enzyme-adapter-react-15'; break; case 'react15.4': dep = 'enzyme-adapter-react-15.4'; break; case 'react16': default: dep = 'enzyme-adapter-react-16'; } let Adapter; try { // eslint-disable-next-line import/no-dynamic-require Adapter = require(dep); } catch (e) { // eslint-disable-next-line no-console console.error( ` Requiring the proper enzyme-adapter during jest-enzyme setup failed. This most likely happens when your application does not properly list the adapter in your devDependencies. Run this line to add the correct adapter: > yarn add --dev ${dep} or with npm > npm i --save-dev ${dep} ` ); return; } const { configure, mount, render, shallow } = require('enzyme'); // Setup Enzyme Adapter configure({ adapter: new Adapter() }); global.shallow = shallow; global.mount = mount; global.render = render; global.React = require('react'); };
Use correct global when resolving enzymeAdapter
fix: Use correct global when resolving enzymeAdapter
JavaScript
mit
blainekasten/enzyme-matchers
--- +++ @@ -1,8 +1,9 @@ /* eslint-disable global-require */ +// eslint-disable-next-line import/prefer-default-export export const exposeGlobals = () => { let dep; - switch (global.enzymedepDescriptor) { + switch (global.enzymeAdapterDescriptor) { case 'react13': dep = 'enzyme-adapter-react-13'; break; @@ -22,8 +23,10 @@ let Adapter; try { + // eslint-disable-next-line import/no-dynamic-require Adapter = require(dep); } catch (e) { + // eslint-disable-next-line no-console console.error( ` Requiring the proper enzyme-adapter during jest-enzyme setup failed.
7d8efe71af7abf4bc21f400fd06bc3f2247be4c1
centreon-frontend/centreon-ui/src/Title/index.js
centreon-frontend/centreon-ui/src/Title/index.js
import React from "react"; import classnames from 'classnames'; import styles from './custom-title.scss'; const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => ( <div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')} onClick={onClick} style={style} > {icon ? ( <span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/> ) : null} <div className={styles["custom-title-label-container"]}> <span className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])} style={labelStyle} > {label} </span> {children} </div> </div> ); export default Title;
import React from "react"; import classnames from 'classnames'; import styles from './custom-title.scss'; const Title = ({ icon, label, titleColor, customTitleStyles, onClick, style, labelStyle, children }) => ( <div className={classnames(styles["custom-title"], customTitleStyles ? styles["custom-title-styles"] : '')} onClick={onClick} style={style} > {icon ? ( <span className={classnames(styles["custom-title-icon"], {[styles[`custom-title-icon-${icon}`]]: true})}/> ) : null} <div className={styles["custom-title-label-container"]}> <span className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])} style={labelStyle} title={label} > {label} </span> {children} </div> </div> ); export default Title;
Add label to the title component.
fix(extensions): Add label to the title component.
JavaScript
apache-2.0
centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon,centreon/centreon
--- +++ @@ -14,6 +14,7 @@ <span className={classnames(styles["custom-title-label"], styles[titleColor ? titleColor : ''])} style={labelStyle} + title={label} > {label} </span>
776ee9c3d3dd199f5c3ef746cf948bd7c06e162b
test-projects/multi-page-test-project/gulpfile.js
test-projects/multi-page-test-project/gulpfile.js
var gulp = require('gulp'); var defs = [ { title: 'Test Index Title', path: '', description: 'Test index description', twitterImage: '20euro.png', openGraphImage: '50euro.png', schemaImage: '100euro.png' }, { path: '/subpage', title: 'Test Subpage Title', description: 'Test subpage description', twitterImage: '100euro.png', openGraphImage: '50euro.png', schemaImage: '20euro.png' } ]; var opts = { publishFromFolder: 'dist', assetContext: 'test-path/', pageDefs: defs, embedCodes: false, iframeResize: false, entryPoint: path.resolve('src/js/entry-point.jsx'), } var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
var gulp = require('gulp'); var path = require('path'); var defs = [ { title: 'Test Index Title', path: '', description: 'Test index description', twitterImage: '20euro.png', openGraphImage: '50euro.png', schemaImage: '100euro.png' }, { path: '/subpage', title: 'Test Subpage Title', description: 'Test subpage description', twitterImage: '100euro.png', openGraphImage: '50euro.png', schemaImage: '20euro.png' } ]; var opts = { publishFromFolder: 'dist', assetContext: 'test-path/', pageDefs: defs, embedCodes: false, iframeResize: false, entryPoint: path.resolve('src/js/entry-point.jsx'), } var builder = require('../../index.js'); // lucify-component-builder builder(gulp, opts);
Add missing require to test project
Add missing require to test project
JavaScript
mit
lucified/lucify-component-builder,lucified/lucify-component-builder,lucified/lucify-component-builder
--- +++ @@ -1,5 +1,6 @@ var gulp = require('gulp'); +var path = require('path'); var defs = [ {
d9e92fb56f73f8415f4ca9ed791a27e511faee36
root/include/news_look_up.js
root/include/news_look_up.js
function yql_lookup(query, cb_function) { var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true'; //alert(url); $.getJSON(url, cb_function); } function look_up_news() { var feed_url = 'http://mediacloud.org/blog/feed/'; //alert(google_url); yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { var results = response.query.results; var news_items = $('#news_items'); //console.log(results); news_items.children().remove(); news_items.html(''); $.each(results.item, function (index, element) { var title = element.title; var link = element.link; news_items.append($('<a/>', { 'href': link }).text(title)).append('<br/>'); }); }); }
function yql_lookup(query, cb_function) { var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&diagnostics=true'; //alert(url); $.getJSON(url, cb_function); } function look_up_news() { // TEMPORARY HACK //mediacloud.org is password protected so we can't pull from it directly // instead we pull from 'https://blogs.law.harvard.edu/mediacloud2/feed/' and dynamically rewrite the URLs to point to mediacloud.org/blog; var feed_url = 'https://blogs.law.harvard.edu/mediacloud2/feed/'; //alert(google_url); yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { var results = response.query.results; var news_items = $('#news_items'); //console.log(results); news_items.children().remove(); news_items.html(''); $.each(results.item, function (index, element) { var title = element.title; var link = element.link; link = link.replace('https://blogs.law.harvard.edu/mediacloud2/', 'http://www.mediacloud.org/blog/'); news_items.append($('<a/>', { 'href': link }).text(title)).append('<br/>'); }); }); }
Add work around for the mediacloud.org/blog page being password protected so we can still display the news dynamically on the front page.
Add work around for the mediacloud.org/blog page being password protected so we can still display the news dynamically on the front page.
JavaScript
agpl-3.0
berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,AchyuthIIIT/mediacloud,berkmancenter/mediacloud
--- +++ @@ -9,7 +9,10 @@ function look_up_news() { - var feed_url = 'http://mediacloud.org/blog/feed/'; + // TEMPORARY HACK + //mediacloud.org is password protected so we can't pull from it directly + // instead we pull from 'https://blogs.law.harvard.edu/mediacloud2/feed/' and dynamically rewrite the URLs to point to mediacloud.org/blog; + var feed_url = 'https://blogs.law.harvard.edu/mediacloud2/feed/'; //alert(google_url); yql_lookup("select * from rss where url = '" + feed_url + "'", function (response) { @@ -26,6 +29,7 @@ var title = element.title; var link = element.link; + link = link.replace('https://blogs.law.harvard.edu/mediacloud2/', 'http://www.mediacloud.org/blog/'); news_items.append($('<a/>', { 'href': link }).text(title)).append('<br/>');
f6259eb662610e8d140028661d41e223d619293d
frontend/src/SubmitButton.js
frontend/src/SubmitButton.js
import React, { Component } from "react"; import styled from "styled-components"; class SubmitButton extends Component { render() { const { isShowingPositive, onNegativeClick, onPositiveClick, disabled, positiveText, negativeText } = this.props; return ( <StyledSubmitButton disabled={disabled} type="button" value={isShowingPositive ? positiveText : negativeText} onClick={isShowingPositive ? onPositiveClick : onNegativeClick} /> ); } } export const StyledSubmitButton = styled.input` background-color: #00a8e2; transition: background-color 0.25s ease-out, color 0.25s ease-out; color: #fff; border: none; outline: none; padding: 15px 45px; font-size: 1.1em; :hover { cursor: pointer; background-color: #0090c2; } :active { background-color: #006b8f; } :disabled { background-color: #c4c4c4; } `; export default SubmitButton;
import React, { Component } from "react"; import styled from "styled-components"; class SubmitButton extends Component { render() { const { isShowingPositive, onNegativeClick, onPositiveClick, disabled, positiveText, negativeText } = this.props; return ( <StyledSubmitButton disabled={disabled} type="button" value={isShowingPositive ? positiveText : negativeText} onClick={isShowingPositive ? onPositiveClick : onNegativeClick} /> ); } } export const StyledSubmitButton = styled.input` -webkit-appearance: none; background-color: #00a8e2; transition: background-color 0.25s ease-out, color 0.25s ease-out; color: #fff; border: none; outline: none; padding: 15px 45px; font-size: 1.1em; :hover { cursor: pointer; background-color: #0090c2; } :active { background-color: #006b8f; } :disabled { background-color: #c4c4c4; } `; export default SubmitButton;
Set webkit-appearance to none on submit button.
Set webkit-appearance to none on submit button.
JavaScript
mit
Tejpbit/talarlista,Tejpbit/talarlista,Tejpbit/talarlista
--- +++ @@ -24,6 +24,7 @@ } export const StyledSubmitButton = styled.input` + -webkit-appearance: none; background-color: #00a8e2; transition: background-color 0.25s ease-out, color 0.25s ease-out; color: #fff;
6fec68f130beffcc842ad79efa94f85eba1009fc
schema/groupofuniquenames.js
schema/groupofuniquenames.js
// Copyright 2012 Joyent, Inc. All rights reserved. var util = require('util'); var ldap = require('ldapjs'); var Validator = require('../lib/schema/validator'); ///--- Globals var ConstraintViolationError = ldap.ConstraintViolationError; ///--- API function GroupOfUniqueNames() { Validator.call(this, { name: 'groupofuniquenames', required: { uniquemember: 1000000 }, optional: { description: 1 }, strict: true }); } util.inherits(GroupOfUniqueNames, Validator); GroupOfUniqueNames.prototype.validate = function validate(entry, callback) { var members = entry.attributes.uniquemember; members.sort(); for (var i = 0; i < members.length; i++) { if (members.indexOf(members[i], i + 1) !== -1) { return callback(new ConstraintViolationError(members[i] + ' is not unique')); } } return callback(); }; ///--- Exports module.exports = { createInstance: function createInstance() { return new GroupOfUniqueNames(); } };
// Copyright 2013 Joyent, Inc. All rights reserved. var util = require('util'); var ldap = require('ldapjs'); var Validator = require('../lib/schema/validator'); ///--- Globals var ConstraintViolationError = ldap.ConstraintViolationError; ///--- API function GroupOfUniqueNames() { Validator.call(this, { name: 'groupofuniquenames', optional: { uniquemember: 1000000, description: 1 }, strict: true }); } util.inherits(GroupOfUniqueNames, Validator); GroupOfUniqueNames.prototype.validate = function validate(entry, callback) { var members = entry.attributes.uniquemember || []; members.sort(); for (var i = 0; i < members.length; i++) { if (members.indexOf(members[i], i + 1) !== -1) { return callback(new ConstraintViolationError(members[i] + ' is not unique')); } } return callback(); }; ///--- Exports module.exports = { createInstance: function createInstance() { return new GroupOfUniqueNames(); } };
Allow creation of empty user groups
CAPI-219: Allow creation of empty user groups
JavaScript
mpl-2.0
joyent/sdc-ufds,arekinath/sdc-ufds,arekinath/sdc-ufds,joyent/sdc-ufds
--- +++ @@ -1,4 +1,4 @@ -// Copyright 2012 Joyent, Inc. All rights reserved. +// Copyright 2013 Joyent, Inc. All rights reserved. var util = require('util'); @@ -19,10 +19,8 @@ function GroupOfUniqueNames() { Validator.call(this, { name: 'groupofuniquenames', - required: { - uniquemember: 1000000 - }, optional: { + uniquemember: 1000000, description: 1 }, strict: true @@ -32,7 +30,7 @@ GroupOfUniqueNames.prototype.validate = function validate(entry, callback) { - var members = entry.attributes.uniquemember; + var members = entry.attributes.uniquemember || []; members.sort(); for (var i = 0; i < members.length; i++) {
df2cf92d8667a3a598aecb37c86c45c82804d089
app/assets/javascripts/active_admin_pro/components/link.js
app/assets/javascripts/active_admin_pro/components/link.js
App.ready(function() { "use strict"; var body = $('body'); var links = $('a:not([data-method="delete"]):not(.has_many_add):not(.dropdown_menu_button):not([target="_blank"])'); // Add active class on click to style while loading via turbolinks // and add loading class to the body element. links.click(function() { body.addClass('loading'); $(this).addClass('active'); }); // Remove loading and active classes on page load body.removeClass('loading'); links.removeClass('active'); });
App.ready(function() { "use strict"; var body = $('body'); var links = $('a:not([data-method="delete"]):not(.has_many_add):not(.dropdown_menu_button):not([target="_blank"])'); // Add active class on click to style while loading via turbolinks // and add loading class to the body element. links.click(function() { body.addClass('loading'); $(this).addClass('active'); }); // Remove loading and active classes on page load body.removeClass('loading'); links.removeClass('active'); // We also need to make sure to remove the loading classes when the // page is restored by Turbolinks when using the back button document.addEventListener('page:restore', function() { body.removeClass('loading'); links.removeClass('active'); }); });
Fix issue with back button and loading indicators
Fix issue with back button and loading indicators
JavaScript
mit
codelation/active_admin_pro,codelation/active_admin_pro,codelation/activeadmin_pro,codelation/activeadmin_pro
--- +++ @@ -13,4 +13,11 @@ // Remove loading and active classes on page load body.removeClass('loading'); links.removeClass('active'); + + // We also need to make sure to remove the loading classes when the + // page is restored by Turbolinks when using the back button + document.addEventListener('page:restore', function() { + body.removeClass('loading'); + links.removeClass('active'); + }); });
39da1bcb08c1ea479ae980513bc23e92be2fd52f
handlers/regex/runCustomCmd.js
handlers/regex/runCustomCmd.js
'use strict'; const { hears } = require('telegraf'); const R = require('ramda'); // DB const { getCommand } = require('../../stores/command'); const capitalize = R.replace(/^./, R.toUpper); const getRepliedToId = R.path([ 'reply_to_message', 'message_id' ]); const typeToMethod = type => type === 'text' ? 'replyWithHTML' : `replyWith${capitalize(type)}`; const runCustomCmdHandler = async (ctx, next) => { const { message, state } = ctx; const { isAdmin, isMaster } = state; const commandName = ctx.match[1].toLowerCase(); const command = await getCommand({ isActive: true, name: commandName }); if (!command) { return next(); } const { caption, content, type } = command; const role = command.role.toLowerCase(); if ( role === 'master' && !isMaster || role === 'admins' && !isAdmin ) { return next(); } const reply_to_message_id = getRepliedToId(message); const options = { caption, disable_web_page_preview: true, reply_to_message_id, }; return ctx[typeToMethod(type)](content, options); }; module.exports = hears(/^!(\w+)/, runCustomCmdHandler);
'use strict'; const { hears } = require('telegraf'); const R = require('ramda'); // DB const { getCommand } = require('../../stores/command'); const capitalize = R.replace(/^./, R.toUpper); const getRepliedToId = R.path([ 'reply_to_message', 'message_id' ]); const typeToMethod = type => type === 'text' ? 'replyWithHTML' : `replyWith${capitalize(type)}`; const runCustomCmdHandler = async (ctx, next) => { const { message, state } = ctx; const { isAdmin, isMaster } = state; const commandName = ctx.match[1].toLowerCase(); const command = await getCommand({ isActive: true, name: commandName }); if (!command) { return next(); } const { caption, content, type } = command; const role = command.role.toLowerCase(); if ( role === 'master' && !isMaster || role === 'admins' && !isAdmin ) { return next(); } const reply_to_message_id = getRepliedToId(message); const options = { caption, disable_web_page_preview: true, reply_to_message_id, }; return ctx[typeToMethod(type)](content, options); }; module.exports = hears(/^! ?(\w+)/, runCustomCmdHandler);
Allow space before custom command name
Allow space before custom command name
JavaScript
agpl-3.0
TheDevs-Network/the-guard-bot
--- +++ @@ -47,4 +47,4 @@ return ctx[typeToMethod(type)](content, options); }; -module.exports = hears(/^!(\w+)/, runCustomCmdHandler); +module.exports = hears(/^! ?(\w+)/, runCustomCmdHandler);
8d8ba7bf3358f5a42f4c2fe377ec20a78d05478a
public/js/app.js
public/js/app.js
var timeDisplay = document.querySelector('#timeDisplay'); var startButton = document.querySelector('#startButton'); var abandonButton = document.querySelector('#abandonButton'); var completeButton = document.querySelector('#completeButton'); var restartButton = document.querySelector('#restartButton'); var buttons = document.querySelectorAll('button'); for (var i = 0; i < buttons.length; i++) { var button = buttons[i]; button.onclick = function () { handleInput(this.id); }; } var sessionLength = 25 * 60 * 1000; var currentTime; var timeRemaining; var timer; function handleInput (id) { var buttons = { startButton: start, completeButton: complete, abandonButton: abandon, restartButton: restart }; buttons[id](); } function countdown () { var oldTime = currentTime; currentTime = Date.now(); timeRemaining -= currentTime - oldTime; if (timeRemaining <= 0) { timeRemaining = 0; end(); } else { updateDOM(); } } function end () { stopTimer(); showElement(restartButton); } function stopTimer () { window.clearInterval(timer); } function start () { hideElement(startButton); showElement(abandonButton); showElement(completeButton); startTimer(); } function startTimer () { currentTime = Date.now(); timeRemaining = sessionLength + 900; updateDOM(); timer = window.setInterval(countdown, 10); } function complete () { stopTimer(); // sendCompleteRequest(); } function abandon () { stopTimer(); // sendAbandonRequest(); } function restart () { hideElement(restartButton); startTimer(); } function updateDOM () { timeDisplay.innerText = formatTime(timeRemaining); } function formatTime (time) { var seconds = Math.floor((time / 1000) % 60).toString(); var minutes = Math.floor((time / (60 * 1000)) % 60).toString(); if (seconds.length < 2) seconds = '0' + seconds; if (minutes.length < 2) minutes = '0' + minutes; return '' + minutes + ':' + seconds; } function hideElement (elem) { elem.style.display = 'none'; } function showElement (elem) { elem.style.display = 'block'; }
Add basic code for timer with commented lines where requests will go
Add basic code for timer with commented lines where requests will go
JavaScript
mit
The-Authenticators/gitpom,The-Authenticators/gitpom
--- +++ @@ -0,0 +1,99 @@ +var timeDisplay = document.querySelector('#timeDisplay'); +var startButton = document.querySelector('#startButton'); +var abandonButton = document.querySelector('#abandonButton'); +var completeButton = document.querySelector('#completeButton'); +var restartButton = document.querySelector('#restartButton'); + +var buttons = document.querySelectorAll('button'); +for (var i = 0; i < buttons.length; i++) { + var button = buttons[i]; + button.onclick = function () { + handleInput(this.id); + }; +} + +var sessionLength = 25 * 60 * 1000; +var currentTime; +var timeRemaining; +var timer; + +function handleInput (id) { + var buttons = { + startButton: start, + completeButton: complete, + abandonButton: abandon, + restartButton: restart + }; + + buttons[id](); +} + +function countdown () { + var oldTime = currentTime; + currentTime = Date.now(); + timeRemaining -= currentTime - oldTime; + if (timeRemaining <= 0) { + timeRemaining = 0; + end(); + } else { + updateDOM(); + } +} + +function end () { + stopTimer(); + showElement(restartButton); +} + +function stopTimer () { + window.clearInterval(timer); +} + +function start () { + hideElement(startButton); + showElement(abandonButton); + showElement(completeButton); + startTimer(); +} + +function startTimer () { + currentTime = Date.now(); + timeRemaining = sessionLength + 900; + updateDOM(); + timer = window.setInterval(countdown, 10); +} + +function complete () { + stopTimer(); + // sendCompleteRequest(); +} + +function abandon () { + stopTimer(); + // sendAbandonRequest(); +} + +function restart () { + hideElement(restartButton); + startTimer(); +} + +function updateDOM () { + timeDisplay.innerText = formatTime(timeRemaining); +} + +function formatTime (time) { + var seconds = Math.floor((time / 1000) % 60).toString(); + var minutes = Math.floor((time / (60 * 1000)) % 60).toString(); + if (seconds.length < 2) seconds = '0' + seconds; + if (minutes.length < 2) minutes = '0' + minutes; + return '' + minutes + ':' + seconds; +} + +function hideElement (elem) { + elem.style.display = 'none'; +} + +function showElement (elem) { + elem.style.display = 'block'; +}
012a8df1ee01e08b0da47d75b13e32ff4f98f6d4
js/forum/src/components/NewPostNotification.js
js/forum/src/components/NewPostNotification.js
import Notification from 'flarum/components/Notification'; import username from 'flarum/helpers/username'; export default class NewPostNotification extends Notification { icon() { return 'star'; } href() { const notification = this.props.notification; const discussion = notification.subject(); const content = notification.content() || {}; return app.route.discussion(discussion, content.postNumber); } content() { return app.translator.trans('flarum-subscriptions.forum.notifications:new_post_text', {user: this.props.notification.sender()}); } }
import Notification from 'flarum/components/Notification'; import username from 'flarum/helpers/username'; export default class NewPostNotification extends Notification { icon() { return 'star'; } href() { const notification = this.props.notification; const discussion = notification.subject(); const content = notification.content() || {}; return app.route.discussion(discussion, content.postNumber); } content() { return app.translator.trans('flarum-subscriptions.forum.notifications.new_post_text', {user: this.props.notification.sender()}); } }
Fix typo in new post notification translation key
Fix typo in new post notification translation key
JavaScript
mit
flarum/flarum-ext-subscriptions,flarum/flarum-ext-subscriptions,flarum/flarum-ext-subscriptions
--- +++ @@ -15,6 +15,6 @@ } content() { - return app.translator.trans('flarum-subscriptions.forum.notifications:new_post_text', {user: this.props.notification.sender()}); + return app.translator.trans('flarum-subscriptions.forum.notifications.new_post_text', {user: this.props.notification.sender()}); } }
07688d877058ed228ffb776b927138fc2ad1ed8d
addon/index.js
addon/index.js
import Ember from 'ember'; const { RSVP } = Ember; function preloadRecord(record, toPreload) { return preloadAll([record], toPreload).then(() => { return record; }); } function preloadAll(records, toPreload) { switch(Ember.typeOf(toPreload)) { case 'object': const properties = Object.keys(toPreload); return RSVP.all(properties.map((p) => { return RSVP.all(records.map((record) => { return record.get(p); })).then((data) => { const subRecords = data.reduce((prev, cur) => prev.concat(cur.toArray()), []); return preloadAll(subRecords, toPreload[p]); }); })).then(() => records); case 'string': return RSVP.all(records.map((record) => record.get(toPreload))) .then(() => records); default: throw 'Illegal Argument'; } } function preload(thing, toPreload) { if (thing.then) { return thing.then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } else { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); } } export default preload;
import Ember from 'ember'; const { RSVP } = Ember; function getPromise(object, property) { return RSVP.resolve(Ember.get(object, property)); } function preloadRecord(record, toPreload) { if (!record) { return RSVP.resolve(record); } switch(Ember.typeOf(toPreload)) { case 'string': return getPromise(record, toPreload).then(() => record); case 'array': return RSVP.all(toPreload.map((p) => preloadRecord(record, p))).then(() => record); case 'object': return RSVP.all(Object.keys(toPreload).map((p) => getPromise(record, p).then((data) => preload(data, toPreload[p])))).then(() => record); default: throw 'Illegal Argument'; } } function preloadAll(records, toPreload) { return RSVP.all(records.map((record) => preload(record, toPreload))); } function preload(thing, toPreload) { return RSVP.resolve(thing).then(() => { return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } export default preload;
Refactor preload to handle more cases
Refactor preload to handle more cases
JavaScript
mit
levanto-financial/ember-data-preload,levanto-financial/ember-data-preload
--- +++ @@ -2,41 +2,35 @@ const { RSVP } = Ember; +function getPromise(object, property) { + return RSVP.resolve(Ember.get(object, property)); +} + function preloadRecord(record, toPreload) { - return preloadAll([record], toPreload).then(() => { - return record; + if (!record) { + return RSVP.resolve(record); + } + + switch(Ember.typeOf(toPreload)) { + case 'string': + return getPromise(record, toPreload).then(() => record); + case 'array': + return RSVP.all(toPreload.map((p) => preloadRecord(record, p))).then(() => record); + case 'object': + return RSVP.all(Object.keys(toPreload).map((p) => + getPromise(record, p).then((data) => preload(data, toPreload[p])))).then(() => record); + default: throw 'Illegal Argument'; + } +} + +function preloadAll(records, toPreload) { + return RSVP.all(records.map((record) => preload(record, toPreload))); +} + +function preload(thing, toPreload) { + return RSVP.resolve(thing).then(() => { + return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); }); } -function preloadAll(records, toPreload) { - switch(Ember.typeOf(toPreload)) { - case 'object': - const properties = Object.keys(toPreload); - return RSVP.all(properties.map((p) => { - return RSVP.all(records.map((record) => { - return record.get(p); - })).then((data) => { - const subRecords = data.reduce((prev, cur) => prev.concat(cur.toArray()), []); - return preloadAll(subRecords, toPreload[p]); - }); - })).then(() => records); - case 'string': - return RSVP.all(records.map((record) => record.get(toPreload))) - .then(() => records); - default: throw 'Illegal Argument'; - } -} - -function preload(thing, toPreload) { - if (thing.then) { - return thing.then(() => { - return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); - }); - } - else { - return Ember.isArray(thing) ? preloadAll(thing, toPreload) : preloadRecord(thing, toPreload); - } - -} - export default preload;
30c117968a90baa7ffe14927147498e0c10bb418
web/src/js/lib/models/LayerModel.js
web/src/js/lib/models/LayerModel.js
cinema.models.LayerModel = Backbone.Model.extend({ constructor: function (defaults, options) { Backbone.Model.call(this, {}, options); if (typeof defaults === 'string') { this.setFromString(defaults); } else if (defaults) { this.set('state', defaults); } }, /** * Convert an object that maps layer identifiers to color-by values into * a single string that is consumable by other parts of the application. */ serialize: function () { var query = ''; _.each(this.attributes, function (v, k) { query += k + v; }); return query; }, /** * Convert a query string to an object that maps layer identifiers to * their color-by value. The query string is a sequence of two-character * pairs, where the first character identifies the layer ID and the second * character identifies which field it should be colored by. * * The query string is then saved to the model. */ unserialize: function (query) { var obj = {}; if (query.length % 2) { return console.error('Query string "' + query + '" has odd length.'); } for (var i = 0; i < query.length; i += 2) { obj[query[i]] = query[i + 1]; } return obj; }, /** * Set the layers by a "query string". */ setFromString: function (query) { var obj = this.unserialize(query); this.set('state', obj); } });
cinema.models.LayerModel = Backbone.Model.extend({ constructor: function (defaults, options) { Backbone.Model.call(this, {}, options); if (typeof defaults === 'string') { this.setFromString(defaults); } else if (defaults) { this.set('state', defaults); } }, /** * Convert an object that maps layer identifiers to color-by values into * a single string that is consumable by other parts of the application. */ serialize: function () { var query = ''; _.each(this.get('state'), function (v, k) { query += k + v; }); return query; }, /** * Convert a query string to an object that maps layer identifiers to * their color-by value. The query string is a sequence of two-character * pairs, where the first character identifies the layer ID and the second * character identifies which field it should be colored by. * * The query string is then saved to the model. */ unserialize: function (query) { var obj = {}; if (query.length % 2) { return console.error('Query string "' + query + '" has odd length.'); } for (var i = 0; i < query.length; i += 2) { obj[query[i]] = query[i + 1]; } return obj; }, /** * Set the layers by a "query string". */ setFromString: function (query) { var obj = this.unserialize(query); this.set('state', obj); } });
Fix layer model serialize method to use new organization
Fix layer model serialize method to use new organization
JavaScript
bsd-3-clause
Kitware/cinema,Kitware/cinema,Kitware/cinema,Kitware/cinema
--- +++ @@ -16,7 +16,7 @@ serialize: function () { var query = ''; - _.each(this.attributes, function (v, k) { + _.each(this.get('state'), function (v, k) { query += k + v; });
7d81ece0291bb469f1bea3bcf2c9225f74eab7d6
server/game/cards/events/01/puttothetorch.js
server/game/cards/events/01/puttothetorch.js
const DrawCard = require('../../../drawcard.js'); class PutToTheTorch extends DrawCard { canPlay(player, card) { if(player !== this.controller || this !== card) { return false; } var currentChallenge = this.game.currentChallenge; if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attacker !== this.controller || currentChallenge.strengthDifference < 5 || currentChallenge.challengeType !== 'military') { return false; } return true; } play(player) { if(this.controller !== player) { return; } this.game.promptForSelect(player, { activePromptTitle: 'Select a location to discard', waitingPromptTitle: 'Waiting for opponent to use ' + this.name, cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location', onSelect: (p, card) => this.onCardSelected(p, card) }); } onCardSelected(player, card) { card.controller.moveCard(card, 'discard pile'); this.game.addMessage('{0} uses {1} to discard {2}', player, this, card); return true; } } PutToTheTorch.code = '01042'; module.exports = PutToTheTorch;
const DrawCard = require('../../../drawcard.js'); class PutToTheTorch extends DrawCard { canPlay(player, card) { if(player !== this.controller || this !== card) { return false; } var currentChallenge = this.game.currentChallenge; if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attackingPlayer !== this.controller || currentChallenge.strengthDifference < 5 || currentChallenge.challengeType !== 'military') { return false; } return true; } play(player) { if(this.controller !== player) { return; } this.game.promptForSelect(player, { activePromptTitle: 'Select a location to discard', waitingPromptTitle: 'Waiting for opponent to use ' + this.name, cardCondition: card => card.inPlay && card.controller !== player && card.getType() === 'location', onSelect: (p, card) => this.onCardSelected(p, card) }); } onCardSelected(player, card) { card.controller.discardCard(card); this.game.addMessage('{0} uses {1} to discard {2}', player, this, card); return true; } } PutToTheTorch.code = '01042'; module.exports = PutToTheTorch;
Fix put to the torch and allow it to use saves
Fix put to the torch and allow it to use saves
JavaScript
mit
Antaiseito/throneteki_for_doomtown,jeremylarner/ringteki,jeremylarner/ringteki,samuellinde/throneteki,cavnak/throneteki,cryogen/gameteki,jbrz/throneteki,cryogen/throneteki,gryffon/ringteki,cryogen/throneteki,Antaiseito/throneteki_for_doomtown,cryogen/gameteki,jeremylarner/ringteki,ystros/throneteki,gryffon/ringteki,DukeTax/throneteki,DukeTax/throneteki,jbrz/throneteki,cavnak/throneteki,samuellinde/throneteki,gryffon/ringteki
--- +++ @@ -8,7 +8,7 @@ var currentChallenge = this.game.currentChallenge; - if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attacker !== this.controller || currentChallenge.strengthDifference < 5 || + if(!currentChallenge || currentChallenge.winner !== this.controller || currentChallenge.attackingPlayer !== this.controller || currentChallenge.strengthDifference < 5 || currentChallenge.challengeType !== 'military') { return false; } @@ -30,7 +30,7 @@ } onCardSelected(player, card) { - card.controller.moveCard(card, 'discard pile'); + card.controller.discardCard(card); this.game.addMessage('{0} uses {1} to discard {2}', player, this, card);
9cb2f8d9efef1d47ddaec2266bcc203baa1990bc
test/index.js
test/index.js
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = exp.split('\r\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
var readFile = require('fs').readFile; var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; var platform = require('os').platform; // Test the expected output. exec('node .', function(err, stdout, stderr) { if (err) { throw err; } readFile(join(__dirname, 'expected.txt'), 'UTF-8', function(err, exp) { if (err) { throw err; } var expected = platform() == 'win32' ? exp.split('\r\n') : exp.split('\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) { assert.equal(actual[i], expected[i], "Expected '" + actual[i] + "' to be '" + expected[i] + "' on line " + (i + 1) + "."); } console.log('All tests pass!'); }); });
Add test support for Windows
Add test support for Windows
JavaScript
isc
unioncollege-webtech/fizzbuzz
--- +++ @@ -2,6 +2,7 @@ var assert = require('assert'); var exec = require('child_process').exec; var join = require('path').join; +var platform = require('os').platform; // Test the expected output. exec('node .', function(err, stdout, stderr) { @@ -14,7 +15,7 @@ throw err; } - var expected = exp.split('\r\n'); + var expected = platform() == 'win32' ? exp.split('\r\n') : exp.split('\n'); var actual = stdout.split('\n'); for (var i = 0, mx = expected.length; i < mx; i++) {
427c79e42267e4f326e8ed0048914a9e2feb3a4a
test/index.js
test/index.js
// Native import path from 'path' // Packages import test from 'ava' import {transformFile} from 'babel-core' // Ours import plugin from '../babel' import read from './_read' const transform = file => ( new Promise((resolve, reject) => { transformFile(path.resolve(__dirname, file), { plugins: [ plugin ] }, (err, data) => { if (err) { return reject(err) } resolve(data) }) }) ) test('works with stateless', async t => { const {code} = await transform('./fixtures/stateless.js') const out = await read('./fixtures/stateless.out.js') t.is(code, out.trim()) }) test('works with class', async t => { const {code} = await transform('./fixtures/class.js') const out = await read('./fixtures/class.out.js') t.is(code, out.trim()) }) test('ignores when attribute is absent', async t => { const {code} = await transform('./fixtures/absent.js') const out = await read('./fixtures/absent.out.js') t.is(code, out.trim()) })
// Native import path from 'path' // Packages import test from 'ava' import {transformFile} from 'babel-core' // Ours import plugin from '../dist/babel' import read from './_read' const transform = file => ( new Promise((resolve, reject) => { transformFile(path.resolve(__dirname, file), { plugins: [ plugin ] }, (err, data) => { if (err) { return reject(err) } resolve(data) }) }) ) test('works with stateless', async t => { const {code} = await transform('./fixtures/stateless.js') const out = await read('./fixtures/stateless.out.js') t.is(code, out.trim()) }) test('works with class', async t => { const {code} = await transform('./fixtures/class.js') const out = await read('./fixtures/class.out.js') t.is(code, out.trim()) }) test('ignores when attribute is absent', async t => { const {code} = await transform('./fixtures/absent.js') const out = await read('./fixtures/absent.out.js') t.is(code, out.trim()) })
Make tests read from the right dir
Make tests read from the right dir
JavaScript
mit
zeit/styled-jsx
--- +++ @@ -6,7 +6,7 @@ import {transformFile} from 'babel-core' // Ours -import plugin from '../babel' +import plugin from '../dist/babel' import read from './_read' const transform = file => (
7e355008d3bc810b84ca4818e4aeecf494a89d20
assets/components/checkblock/js/inputs/checkblock.js
assets/components/checkblock/js/inputs/checkblock.js
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(document.getElementById('checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
// Wrap your stuff in this module pattern for dependency injection (function ($, ContentBlocks) { // Add your custom input to the fieldTypes object as a function // The dom variable contains the injected field (from the template) // and the data variable contains field information, properties etc. ContentBlocks.fieldTypes.checkblock = function(dom, data) { var input = { // Some optional variables can be defined here }; // Do something when the input is being loaded input.init = function() { $(dom.find('#checkblock_' + data.generated_id)).prop('checked', data.value); } // Get the data from this input, it has to be a simple object. input.getData = function() { return { value:$(dom.find('#checkblock_' + data.generated_id)).is(':checked') } } // Always return the input variable. return input; } })(vcJquery, ContentBlocks);
Fix checkboxes not ticking themselves
Fix checkboxes not ticking themselves Closes #1
JavaScript
mit
jpdevries/checkblock,jpdevries/checkblock
--- +++ @@ -10,12 +10,13 @@ // Do something when the input is being loaded input.init = function() { + $(dom.find('#checkblock_' + data.generated_id)).prop('checked', data.value); } // Get the data from this input, it has to be a simple object. input.getData = function() { return { - value:$(document.getElementById('checkblock_' + data.generated_id)).is(':checked') + value:$(dom.find('#checkblock_' + data.generated_id)).is(':checked') } }
53db7bd5313293b436d9664d90080eee18315165
sample/core.js
sample/core.js
enchant(); window.onload = function () { var core = new Core(320, 320); core.onload = function () { core.rootScene.backgroundColor = '#eee'; var field = new TextField(160, 24); field.x = (core.width - field.width) / 2; field.y = 64; field.placeholder = 'what is your name ?'; field.style.border = '2px solid #f6c'; field.style.borderRadius = '4px'; field.onfocus = function () { label.text = 'onfocus called!!'; }; field.onblur = function () { label.text = 'onblur called!!'; }; field.onreturn = function () { label.text = 'onreturn called!!<br>' + this.value + '!!'; }; core.rootScene.addChild(field); var label = new Label(); label.font = '32px Arial'; label.width = 320; label.height = 32; label.x = 0; label.y = core.height - label.height * 2; label.textAlign = 'center'; core.rootScene.addChild(label); }; core.start(); };
enchant(); window.onload = function () { var core = new Core(320, 320); core.onload = function () { core.rootScene.backgroundColor = '#eee'; // Create an instance of enchant.TextField var textField = new TextField(160, 24); // Set position textField.x = (core.width - textField.width) / 2; textField.y = 64; // Set placeholder textField.placeholder = 'what is your name ?'; // Set styles textField.style.border = '2px solid #f6c'; textField.style.borderRadius = '4px'; // Define events textField.onfocus = function () { label.text = 'onfocus called!!'; }; textField.onblur = function () { label.text = 'onblur called!!'; }; textField.onreturn = function () { label.text = 'onreturn called!!<br>' + this.value + '!!'; }; // Add to the scene core.rootScene.addChild(textField); var label = new Label(); label.font = '32px Arial'; label.width = 320; label.height = 32; label.x = 0; label.y = core.height - label.height * 2; label.textAlign = 'center'; core.rootScene.addChild(label); }; core.start(); };
Add some comments and rename TextField instance
Add some comments and rename TextField instance
JavaScript
mit
131e55/textField.enchant.js
--- +++ @@ -6,25 +6,33 @@ core.onload = function () { core.rootScene.backgroundColor = '#eee'; - var field = new TextField(160, 24); - field.x = (core.width - field.width) / 2; - field.y = 64; - field.placeholder = 'what is your name ?'; + // Create an instance of enchant.TextField + var textField = new TextField(160, 24); - field.style.border = '2px solid #f6c'; - field.style.borderRadius = '4px'; + // Set position + textField.x = (core.width - textField.width) / 2; + textField.y = 64; - field.onfocus = function () { + // Set placeholder + textField.placeholder = 'what is your name ?'; + + // Set styles + textField.style.border = '2px solid #f6c'; + textField.style.borderRadius = '4px'; + + // Define events + textField.onfocus = function () { label.text = 'onfocus called!!'; }; - field.onblur = function () { + textField.onblur = function () { label.text = 'onblur called!!'; }; - field.onreturn = function () { + textField.onreturn = function () { label.text = 'onreturn called!!<br>' + this.value + '!!'; }; - core.rootScene.addChild(field); + // Add to the scene + core.rootScene.addChild(textField); var label = new Label(); label.font = '32px Arial';
3b9af3bf12b4ec3790caf898900b94d3d49aee00
elemental-ca.js
elemental-ca.js
var w = 300, gens = 10; var c = document.getElementById('cs'); var ctx = c.getContext('2d'); var ruleset = [0,1,0,1,1,0,1,0].reverse(); var cells = []; for (var i=0; i<w; i++) { cells[i] = 0; } cells[Math.ceil(w/2)] = 1; function rules(l,c,r) { var rule = '' + l + c + r; return ruleset[parseInt(rule, 2)]; } function draw(h) { var size=2; for (var i =0; i < cells.length; i++) { if (cells[i] === 0) { ctx.fillStyle = 'rgb(200,200,100)'; } else { ctx.fillStyle = 'rgb(0,155,100)'; console.log(i); } ctx.fillRect(i*size,h*size,size,size); } } function generate() { var newgen = []; for(var i=0; i < cells.length; i++) { l = cells[i-1]; c = cells[i]; r = cells[i+1]; newgen[i] = rules(l, c, r); } cells = newgen; } for (var i=0; i < gens; i++) { draw(i); generate(); }
var w = 600, gens = 800; var c = document.getElementById('cs'); var ctx = c.getContext('2d'); var ruleset = [0,1,0,1,1,0,1,0].reverse(); var cells = []; for (var i=0; i<w; i++) { cells[i] = 0; } cells[Math.ceil(w/2)] = 1; function rules(l,c,r) { var rule = '' + l + c + r; return ruleset[parseInt(rule, 2)]; } function draw(h) { var size=1; for (var i =0; i < cells.length; i++) { if (cells[i] === 0) { ctx.fillStyle = 'rgb(100,200,200)'; } else { ctx.fillStyle = 'rgb(100,55,100)'; } ctx.fillRect(i*size,h*size,size,size); } } function generate() { var newgen = []; for(var i=0; i < cells.length; i++) { l = cells[i-1]; c = cells[i]; r = cells[i+1]; newgen[i] = rules(l, c, r); } cells = newgen; } for (var i=0; i < gens; i++) { draw(i); generate(); }
Tweak the color and size a bit
Tweak the color and size a bit
JavaScript
mit
mmcfarland/canvas-renderings
--- +++ @@ -1,5 +1,5 @@ -var w = 300, - gens = 10; +var w = 600, + gens = 800; var c = document.getElementById('cs'); var ctx = c.getContext('2d'); @@ -18,15 +18,14 @@ } function draw(h) { - var size=2; + var size=1; for (var i =0; i < cells.length; i++) { if (cells[i] === 0) { - ctx.fillStyle = 'rgb(200,200,100)'; + ctx.fillStyle = 'rgb(100,200,200)'; } else { - ctx.fillStyle = 'rgb(0,155,100)'; - console.log(i); + ctx.fillStyle = 'rgb(100,55,100)'; } - + ctx.fillRect(i*size,h*size,size,size); } }
4c1987b918d353f849ad1aaad174db797525ee10
scripts/app.js
scripts/app.js
var ko = require('knockout-client'), vm = require('./viewModel'); vm.wtf(); ko.applyBindings(vm);
var ko = require('knockout-client'), vm = require('./viewModel'); ko.applyBindings(vm);
Remove increment on refresh / initial visit
Remove increment on refresh / initial visit
JavaScript
mit
joshka/countw.tf,joshka/countw.tf,joshka/countw.tf,joshka/countw.tf
--- +++ @@ -1,5 +1,4 @@ var ko = require('knockout-client'), vm = require('./viewModel'); -vm.wtf(); ko.applyBindings(vm);
c70bb59f3a7357f7d2711f0de20c1cd1717fec70
react/gameday2/components/EmbedTwitch.js
react/gameday2/components/EmbedTwitch.js
import React from 'react' import { webcastPropType } from '../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
import React from 'react' import { webcastPropType } from '../utils/webcastUtils' const EmbedTwitch = (props) => { const channel = props.webcast.channel const iframeSrc = `https://player.twitch.tv/?channel=${channel}` return ( <iframe src={iframeSrc} frameBorder="0" scrolling="no" height="100%" width="100%" allowFullScreen /> ) } EmbedTwitch.propTypes = { webcast: webcastPropType.isRequired, } export default EmbedTwitch
Fix gameday2 not allowing fullscreen Twitch
Fix gameday2 not allowing fullscreen Twitch
JavaScript
mit
nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,nwalters512/the-blue-alliance,fangeugene/the-blue-alliance,fangeugene/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,nwalters512/the-blue-alliance,bdaroz/the-blue-alliance,bdaroz/the-blue-alliance,the-blue-alliance/the-blue-alliance,phil-lopreiato/the-blue-alliance,phil-lopreiato/the-blue-alliance,tsteward/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,tsteward/the-blue-alliance,the-blue-alliance/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,jaredhasenklein/the-blue-alliance,verycumbersome/the-blue-alliance,fangeugene/the-blue-alliance,phil-lopreiato/the-blue-alliance,verycumbersome/the-blue-alliance,bdaroz/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,verycumbersome/the-blue-alliance,verycumbersome/the-blue-alliance,phil-lopreiato/the-blue-alliance,nwalters512/the-blue-alliance,tsteward/the-blue-alliance,fangeugene/the-blue-alliance,bdaroz/the-blue-alliance,phil-lopreiato/the-blue-alliance,the-blue-alliance/the-blue-alliance,tsteward/the-blue-alliance,nwalters512/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,the-blue-alliance/the-blue-alliance,jaredhasenklein/the-blue-alliance,jaredhasenklein/the-blue-alliance
--- +++ @@ -11,6 +11,7 @@ scrolling="no" height="100%" width="100%" + allowFullScreen /> ) }
66e5f23ae0283fd89d313b802c3ed20ea52137ed
app/public/app.js
app/public/app.js
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); $('.results_container').slideDown( "slow"); }); }); });
$(function () { $(document).on({ ajaxStart: function() { $('body').addClass("loading"); }, ajaxStop: function() { $('body').removeClass("loading"); } }) $( "#request_form" ).submit(function( event ) { event.preventDefault(); $('.results_container').slideUp( "slow"); $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); if (data) { $.each(data, function(key, value) { $('.results_container .results').append("<div class='result'>"+value+"</div>"); }); } else { $('.results_container .results').append("<div class='result'>None</div>"); } $('.results_container').slideDown( "slow"); }); }); });
Fix view for empty response
Fix view for empty response
JavaScript
mit
nezhar/PictureChallenge,nezhar/PictureChallenge
--- +++ @@ -12,9 +12,13 @@ $.post( "/call", { challenge_number: $("#challenge_number").val(), weeks: $("#weeks").val() }).done(function( data ) { $('.results_container .result').html(''); - $.each(data, function(key, value) { - $('.results_container .results').append("<div class='result'>"+value+"</div>"); - }); + if (data) { + $.each(data, function(key, value) { + $('.results_container .results').append("<div class='result'>"+value+"</div>"); + }); + } else { + $('.results_container .results').append("<div class='result'>None</div>"); + } $('.results_container').slideDown( "slow"); });
4be53761875922cc8d27e54363624cd1ae34bc16
app/containers/Main/index.js
app/containers/Main/index.js
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import types from '../../utils/types'; import SocketEvents from '../../utils/socketEvents'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { ...types.entries, ...types.sections, site: PropTypes.object.isRequired, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: PropTypes.object.isRequired, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { user, entries, sections, fields, assets, ui, dispatch, site } = this.props; if (user.isFetching || entries.isFetching || sections.isFetching || assets.isFetching || fields.isFetching) return null; return ( <main className="main"> <MainNav siteName={site.siteName} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
import React, { Component, PropTypes } from 'react'; import fetchData from '../../actions/fetchData'; import Toast from '../../components/Toast'; import Modals from '../Modals'; import types from '../../utils/types'; import SocketEvents from '../../utils/socketEvents'; import './Main.scss'; import MainNav from '../MainNav'; export default class Main extends Component { static propTypes = { ...types.entries, ...types.sections, site: PropTypes.object.isRequired, socket: PropTypes.object.isRequired, ui: PropTypes.object.isRequired, user: PropTypes.object.isRequired, location: PropTypes.object.isRequired, children: PropTypes.object.isRequired, dispatch: PropTypes.func.isRequired, }; componentDidMount() { const { dispatch, socket } = this.props; fetchData(); const events = new SocketEvents(socket, dispatch); events.listen(); } render() { const { ui, dispatch, site } = this.props; if (Object.keys(this.props).some(key => this.props[key].isFetching)) return null; return ( <main className="main"> <MainNav siteName={site.siteName} /> {React.cloneElement(this.props.children, { ...this.props, key: this.props.location.pathname, })} <div className="toasts"> {ui.toasts.map(t => <Toast dispatch={dispatch} key={t.dateCreated} {...t} />)} </div> <Modals {...this.props} /> </main> ); } }
Check for isFetching with .some
:wrench: Check for isFetching with .some
JavaScript
mit
JasonEtco/flintcms,JasonEtco/flintcms
--- +++ @@ -31,12 +31,8 @@ } render() { - const { user, entries, sections, fields, assets, ui, dispatch, site } = this.props; - if (user.isFetching - || entries.isFetching - || sections.isFetching - || assets.isFetching - || fields.isFetching) return null; + const { ui, dispatch, site } = this.props; + if (Object.keys(this.props).some(key => this.props[key].isFetching)) return null; return ( <main className="main">
0c91dac30e3bf9a0fb06e315c3ab52489d703a5e
lib/getReactNativeExternals.js
lib/getReactNativeExternals.js
'use strict'; var fs = require('fs'); var path = require('path'); /** * Extract the React Native module paths for a given directory * * @param {String} rootDir * @return {Object} */ function getReactNativeExternals(rootDir) { var externals = {}; var file; var walk = function(dir) { fs.readdirSync(dir).forEach(function(mod) { file = path.resolve(dir, mod); if (fs.lstatSync(file).isDirectory()) { walk(file); } else if (path.extname(mod) === '.js') { mod = mod.replace(/\.js$/, ''); // Only externalize RN's "React" dependency (uppercase). if (mod !== 'react') { externals[mod] = 'commonjs ' + mod; } } }); } walk(rootDir); // 'react-native' is aliased as `React` in the global object externals['react-native'] = 'React'; return externals; } module.exports = getReactNativeExternals;
'use strict'; var fs = require('fs'); var path = require('path'); /** * Extract the React Native module paths for a given directory * * @param {String} rootDir * @return {Object} */ function getReactNativeExternals(rootDir) { var externals = {}; var file; var walk = function(dir) { fs.readdirSync(dir).forEach(function(mod) { file = path.resolve(dir, mod); if (fs.lstatSync(file).isDirectory()) { walk(file); } else if (path.extname(mod) === '.js') { mod = mod.replace(/(\.android|\.ios)?\.js$/, ''); // FIXME(mj): // This is a temporary hack until we move to getting the dependencies // from the RN packager. // See: https://github.com/mjohnston/react-native-webpack-server/issues/23 if (mod === 'StaticContainer') { mod = 'StaticContainer.react'; } // Only externalize RN's "React" dependency (uppercase). if (mod !== 'react') { externals[mod] = 'commonjs ' + mod; } } }); } walk(rootDir); // 'react-native' is aliased as `React` in the global object externals['react-native'] = 'React'; return externals; } module.exports = getReactNativeExternals;
Fix for requiring `*.ios.js` modules
Fix for requiring `*.ios.js` modules Also temporary workaround for `require('StaticContainer.react')`. Fixes #22
JavaScript
mit
hammerandchisel/react-native-webpack-server,Owenzh/react-native-webpack-server,pascience/react-native-webpack-server,patrickomeara/react-native-webpack-server,jeffreywescott/react-native-webpack-server,refinery29/react-native-webpack-server,nevir/react-native-webpack-server,carcer/react-native-webpack-server,prathamesh-sonpatki/react-native-webpack-server,elliottsj/react-native-webpack-server,tgriesser/react-native-webpack-server,davecoates/react-native-webpack-server,lanceharper/react-native-webpack-server,gaearon/react-native-webpack-server,joshuabates/react-native-webpack-server,ppiekarczyk/react-native-webpack-server,paolorovella/react-native-webpack-server,lightsofapollo/react-native-webpack-server,mjohnston/react-native-webpack-server,scottishredpill/react-native-webpack-server,ptmt/react-native-webpack-server,ali/react-native-webpack-server,krambertech/react-native-webpack-server,skevy/react-native-webpack-server
--- +++ @@ -19,7 +19,14 @@ if (fs.lstatSync(file).isDirectory()) { walk(file); } else if (path.extname(mod) === '.js') { - mod = mod.replace(/\.js$/, ''); + mod = mod.replace(/(\.android|\.ios)?\.js$/, ''); + // FIXME(mj): + // This is a temporary hack until we move to getting the dependencies + // from the RN packager. + // See: https://github.com/mjohnston/react-native-webpack-server/issues/23 + if (mod === 'StaticContainer') { + mod = 'StaticContainer.react'; + } // Only externalize RN's "React" dependency (uppercase). if (mod !== 'react') { externals[mod] = 'commonjs ' + mod;
779157a8fb6076e35fce4edcb2eb7a7a55ccdade
js/characters-list.js
js/characters-list.js
var Character = require('./character'); var React = require('react'); var _ = require('underscore') var CharactersList = React.createClass({ render: function () { return ( <div> { this.props.items.map(function(item, index) { var name = item.name; var image = item.image; var description = item.description; return <Character key={index} name={name} image={image} description={description}/>; }) } </div> ); } }); module.exports = CharactersList;
var Character = require('./character'); var React = require('react'); var _ = require('underscore') var CharactersList = React.createClass({ render: function () { return ( <div> { this.props.items.map(function(item, index) { var name = item.name; var image = item.thumbnail.path+'.'+item.thumbnail.extension; var description = item.description; return <Character key={index} name={name} image={image} description={description}/>; }) } </div> ); } }); module.exports = CharactersList;
Fix for the image prop of the character
Fix for the image prop of the character
JavaScript
mit
adrrian17/excelsior
--- +++ @@ -9,7 +9,7 @@ { this.props.items.map(function(item, index) { var name = item.name; - var image = item.image; + var image = item.thumbnail.path+'.'+item.thumbnail.extension; var description = item.description; return <Character key={index} name={name} image={image} description={description}/>;
a942d28c315f59428a80d2fd0b268cd99bbe3b66
common/src/configureStore.js
common/src/configureStore.js
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; if (process.env.NODE_ENV !== 'production') { // eslint-disable-line no-undef const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
import appReducer from './app/reducer'; import createLogger from 'redux-logger'; import fetch from 'isomorphic-fetch'; import injectDependencies from './lib/injectDependencies'; import promiseMiddleware from 'redux-promise-middleware'; import stateToJS from './lib/stateToJS'; import validate from './validate'; import {applyMiddleware, createStore} from 'redux'; export default function configureStore(initialState) { const dependenciesMiddleware = injectDependencies( {fetch}, {validate} ); const middlewares = [ dependenciesMiddleware, promiseMiddleware ]; const loggerEnabled = process.env.IS_BROWSER && // eslint-disable-line no-undef process.env.NODE_ENV !== 'production'; // eslint-disable-line no-undef if (loggerEnabled) { const logger = createLogger({ collapsed: () => true, transformer: stateToJS }); middlewares.push(logger); } const store = applyMiddleware(...middlewares)(createStore)( appReducer, initialState); if (module.hot) { // eslint-disable-line no-undef // Enable Webpack hot module replacement for reducers. module.hot.accept('./app/reducer', () => { // eslint-disable-line no-undef const nextAppReducer = require('./app/reducer'); // eslint-disable-line no-undef store.replaceReducer(nextAppReducer); }); } return store; }
Enable Flux logger only for dev
Enable Flux logger only for dev
JavaScript
mit
puzzfuzz/othello-redux,christophediprima/este,XeeD/este,abelaska/este,skyuplam/debt_mgmt,AugustinLF/este,TheoMer/Gyms-Of-The-World,skyuplam/debt_mgmt,langpavel/este,XeeD/test,robinpokorny/este,aindre/este-example,christophediprima/este,SidhNor/este-cordova-starter-kit,robinpokorny/este,glaserp/Maturita-Project,christophediprima/este,AlesJiranek/este,sikhote/davidsinclair,blueberryapps/este,TheoMer/Gyms-Of-The-World,XeeD/test,TheoMer/Gyms-Of-The-World,syroegkin/mikora.eu,zanj2006/este,este/este,TheoMer/este,puzzfuzz/othello-redux,vacuumlabs/este,estaub/my-este,cjk/smart-home-app,AlesJiranek/este,skallet/este,neozhangthe1/framedrop-web,GarrettSmith/schizophrenia,este/este,aindre/este-example,neozhangthe1/framedrop-web,nezaidu/este,GarrettSmith/schizophrenia,amrsekilly/updatedEste,skallet/este,neozhangthe1/framedrop-web,amrsekilly/updatedEste,amrsekilly/updatedEste,este/este,zanj2006/este,este/este,neozhangthe1/framedrop-web,nason/este,glaserp/Maturita-Project,XeeD/este,abelaska/este,TheoMer/este,syroegkin/mikora.eu,steida/este,ViliamKopecky/este,estaub/my-este,syroegkin/mikora.eu,neozhangthe1/framedrop-web,steida/este,robinpokorny/este,vacuumlabs/este,blueberryapps/este,estaub/my-este,Brainfock/este,abelaska/este,sikhote/davidsinclair,TheoMer/este,langpavel/este,sikhote/davidsinclair,GarrettSmith/schizophrenia,christophediprima/este,shawn-dsz/este,AugustinLF/este,skallet/este
--- +++ @@ -16,8 +16,11 @@ dependenciesMiddleware, promiseMiddleware ]; + const loggerEnabled = + process.env.IS_BROWSER && // eslint-disable-line no-undef + process.env.NODE_ENV !== 'production'; // eslint-disable-line no-undef - if (process.env.NODE_ENV !== 'production') { // eslint-disable-line no-undef + if (loggerEnabled) { const logger = createLogger({ collapsed: () => true, transformer: stateToJS
43f0a5cefb43be20ae8f48deb2fa886540528b2d
lib/indie-registry.js
lib/indie-registry.js
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
'use babel' import {Emitter, CompositeDisposable} from 'atom' import Validate from './validate' import Indie from './indie' export default class IndieRegistry { constructor() { this.subscriptions = new CompositeDisposable() this.emitter = new Emitter() this.indieLinters = new Set() this.subscriptions.add(this.emitter) } register(linter) { Validate.linter(linter, true) const indieLinter = new Indie(linter) this.subscriptions.add(indieLinter) this.indieLinters.add(indieLinter) indieLinter.onDidDestroy(() => { this.indieLinters.delete(indieLinter) }) indieLinter.onDidUpdateMessages(messages => { this.emitter.emit('did-update-messages', {linter: indieLinter, messages}) }) this.emit('observe', indieLinter) return indieLinter } has(indieLinter) { return this.indieLinters.has(indieLinter) } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose() } } // Private method observe(callback) { this.indieLinters.forEach(callback) return this.emitter.on('observe', callback) } // Private method onDidUpdateMessages(callback) { return this.emitter.on('did-update-messages', callback) } dispose() { this.subscriptions.dispose() } }
Add a new has method
:new: Add a new has method
JavaScript
mit
Arcanemagus/linter,e-jigsaw/Linter,atom-community/linter,AtomLinter/Linter,steelbrain/linter
--- +++ @@ -30,6 +30,9 @@ return indieLinter } + has(indieLinter) { + return this.indieLinters.has(indieLinter) + } unregister(indieLinter) { if (this.indieLinters.has(indieLinter)) { indieLinter.dispose()
dcf5dde3cb5833fde7430a0238e3c9436e796dc0
lib/score-combiner.js
lib/score-combiner.js
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) var largest = 0.0 Object.keys(scores).map((key, index, arr) => { if (scores[key] >= largest) { largest = scores[key] } }) return largest } } module.exports = { Mean: MeanQ, Largest: LargestQ }
/** * checks if there are scores which can be combined */ function checkValidity (scores) { if (scores == null) { throw new Error('There must be a scores object parameter') } if (Object.keys(scores).length <= 0) { throw new Error('At least one score must be passed') } } /** * Score canidate based on the mean value of two or more parent Qs. */ class MeanQ { /** * Returns the mean value of the given scores. * @param scores - obect that contains the keys and scores * for each used scoring method * @return mean value of given scores */ combine (scores) { checkValidity(scores) var sum = 0 Object.keys(scores).map((key, index, arr) => { sum += scores[key] }) return sum / Object.keys(scores).length } } /** * Chooses the biggest score out of all possible scores */ class LargestQ { /** * combines all scores by choosing the largest score */ combine (scores) { checkValidity(scores) return Math.max.apply(null, Object.values(scores)) } } module.exports = { Mean: MeanQ, Largest: LargestQ }
Refactor LargestQ.combine() to use built-ins.
Refactor LargestQ.combine() to use built-ins.
JavaScript
agpl-3.0
amos-ws16/amos-ws16-arrowjs-server,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs,amos-ws16/amos-ws16-arrowjs-server
--- +++ @@ -42,14 +42,7 @@ */ combine (scores) { checkValidity(scores) - - var largest = 0.0 - Object.keys(scores).map((key, index, arr) => { - if (scores[key] >= largest) { - largest = scores[key] - } - }) - return largest + return Math.max.apply(null, Object.values(scores)) } }
73b274515279466e125e658e539b1863301c5759
lib/windshaft/models/dummy_mapconfig_provider.js
lib/windshaft/models/dummy_mapconfig_provider.js
var util = require('util'); var MapStoreMapConfigProvider = require('./mapstore_mapconfig_provider'); function DummyMapConfigProvider(mapConfig, params) { if (!(this instanceof DummyMapConfigProvider)) { return new DummyMapConfigProvider(mapConfig, params); } MapStoreMapConfigProvider.call(this, undefined, params); this.mapConfig = mapConfig; } util.inherits(DummyMapConfigProvider, MapStoreMapConfigProvider); module.exports = DummyMapConfigProvider; DummyMapConfigProvider.prototype.getMapConfig = function(callback) { return callback(null, this.mapConfig, this.params, {}); };
var util = require('util'); var MapStoreMapConfigProvider = require('./mapstore_mapconfig_provider'); function DummyMapConfigProvider(mapConfig, params) { MapStoreMapConfigProvider.call(this, undefined, params); this.mapConfig = mapConfig; } util.inherits(DummyMapConfigProvider, MapStoreMapConfigProvider); module.exports = DummyMapConfigProvider; DummyMapConfigProvider.prototype.getMapConfig = function(callback) { return callback(null, this.mapConfig, this.params, {}); };
Remove instance check as it's an internal class and have full control
Remove instance check as it's an internal class and have full control
JavaScript
bsd-3-clause
CartoDB/Windshaft,wsw0108/Windshaft,CartoDB/Windshaft,CartoDB/Windshaft,wsw0108/Windshaft,wsw0108/Windshaft
--- +++ @@ -2,10 +2,6 @@ var MapStoreMapConfigProvider = require('./mapstore_mapconfig_provider'); function DummyMapConfigProvider(mapConfig, params) { - if (!(this instanceof DummyMapConfigProvider)) { - return new DummyMapConfigProvider(mapConfig, params); - } - MapStoreMapConfigProvider.call(this, undefined, params); this.mapConfig = mapConfig;
969cc51155d7be88f97e27f305bf678836fa9220
packages/server/src/__tests__/jestSetup.js
packages/server/src/__tests__/jestSetup.js
const root = __dirname + '/../../../..'; require('@babel/register')({ root, cwd: root, configFile: root + '/packages/server/babel.config.js', extensions: ['.js', '.jsx', '.ts', '.tsx'] }); require.extensions['.scss'] = () => {}; require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; Object.assign(global, require('../../jest.config').globals); const { setup } = require('@gqlapp/testing-server-ts'); require('..'); module.exports = setup;
const root = __dirname + '/../../../..'; require('@babel/register')({ root, cwd: root, configFile: root + '/packages/server/babel.config.js', extensions: ['.js', '.jsx', '.ts', '.tsx'], cache: false }); require.extensions['.scss'] = () => {}; require.extensions['.css'] = () => {}; require.extensions['.less'] = () => {}; Object.assign(global, require('../../jest.config').globals); const { setup } = require('@gqlapp/testing-server-ts'); require('..'); module.exports = setup;
Work around babel-plugin-import-graphql caching intolerance
Work around babel-plugin-import-graphql caching intolerance
JavaScript
mit
sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-universal-starter-kit,sysgears/apollo-fullstack-starter-kit
--- +++ @@ -4,7 +4,8 @@ root, cwd: root, configFile: root + '/packages/server/babel.config.js', - extensions: ['.js', '.jsx', '.ts', '.tsx'] + extensions: ['.js', '.jsx', '.ts', '.tsx'], + cache: false }); require.extensions['.scss'] = () => {};
36ae9ccc7f43445485a6baacc4dc18834d61cda2
pretty-seconds.js
pretty-seconds.js
function quantify(data, unit, value) { if (value) { if (value > 1 || value < -1) unit += 's'; data.push(value + ' ' + unit); } return data; } module.exports = function prettySeconds(seconds) { var prettyString = '', data = []; if (typeof seconds === 'number') { data = quantify(data, 'day', parseInt(seconds / 86400)); data = quantify(data, 'hour', parseInt((seconds % 86400) / 3600)); data = quantify(data, 'minute', parseInt((seconds % 3600) / 60)); data = quantify(data, 'second', seconds % 60); var length = data.length, i; for (i = 0; i < length; i++) { if (prettyString.length > 0) if (i == length - 1) prettyString += ' and '; else prettyString += ', '; prettyString += data[i]; } } return prettyString; };
function quantify(data, unit, value) { if (value) { if (value > 1 || value < -1) unit += 's'; data.push(value + ' ' + unit); } return data; } module.exports = function prettySeconds(seconds) { var prettyString = '', data = []; if (typeof seconds === 'number') { data = quantify(data, 'day', parseInt(seconds / 86400)); data = quantify(data, 'hour', parseInt((seconds % 86400) / 3600)); data = quantify(data, 'minute', parseInt((seconds % 3600) / 60)); data = quantify(data, 'second', Math.floor(seconds % 60)); var length = data.length, i; for (i = 0; i < length; i++) { if (prettyString.length > 0) if (i == length - 1) prettyString += ' and '; else prettyString += ', '; prettyString += data[i]; } } return prettyString; };
Trim decimal places off seconds
Trim decimal places off seconds
JavaScript
mit
binarykitchen/pretty-seconds
--- +++ @@ -19,7 +19,7 @@ data = quantify(data, 'day', parseInt(seconds / 86400)); data = quantify(data, 'hour', parseInt((seconds % 86400) / 3600)); data = quantify(data, 'minute', parseInt((seconds % 3600) / 60)); - data = quantify(data, 'second', seconds % 60); + data = quantify(data, 'second', Math.floor(seconds % 60)); var length = data.length, i;
438e6b49e171e8db87e1982677861b6c61dfcdad
scripts/nummer.js
scripts/nummer.js
// Description: // Pick and tag a random user that has to do shitty work, replies when the bot // hears @noen. This script also supports mentions of @aktive and @nye. const _ = require('lodash'); const members = require('../lib/members'); const prefixes = [ 'Time to shine', "The work doesn't do itself", 'Get going', 'lol rekt', 'About time you got picked', 'RIP', 'Move it' ]; const createMention = username => `@${username}`; module.exports = robot => { robot.hear(/@noen-nye/i, msg => { members('?new=true') .then(members => { if (!members.length) { return; } const luckyMember = _.sample(members); const mention = createMention(luckyMember.slack); const cheesyPrefix = _.sample(prefixes); msg.send(`${cheesyPrefix} ${mention}`); }) .catch(error => msg.send(error.message)); }); robot.hear(/@noen/i, msg => { // Reply with a cheesy message and a random picked mention. members('?active=true') .then(members => { if (!members.length) { return; } const luckyMember = _.sample(members); const mention = createMention(luckyMember.slack); const cheesyPrefix = _.sample(prefixes); msg.send(`${cheesyPrefix} ${mention}`); }) .catch(error => msg.send(error.message)); }); robot.hear(/@aktive|@active/i, msg => { // Reply with a message containing mentions of all active users. members('?active=true') .then(members => { if (members.length === 0) { return; } msg.send(members.map(member => createMention(member.slack)).join(', ')); }) .catch(error => msg.send(error.message)); }); robot.hear(/@nye/i, msg => { members('?new=true') .then(members => { if (members.length === 0) { return; } msg.send(members.map(member => createMention(member.slack)).join(', ')); }) .catch(error => msg.send(error.message)); }); };
// Description: // Get all phone numbers for active members const _ = require('lodash'); const members = require('../lib/members'); module.exports = robot => { robot.respond(/nummer/i, msg => { members('?active=true') .then(members => { if (members.length === 0) { return; } msg.send( members .map( m => `*${m.name}*:${'\t'} ${m.phone_number.substr( 0, 3 )} ${m.phone_number .substr(3) .match(/.{1,2}/g) .join(' ')}` ) .sort() .join('\n') ); }) .catch(error => msg.send(error.message)); }); };
Remove duplicate posts by ababot
Remove duplicate posts by ababot
JavaScript
mit
webkom/ababot,webkom/ababot
--- +++ @@ -1,75 +1,31 @@ // Description: -// Pick and tag a random user that has to do shitty work, replies when the bot -// hears @noen. This script also supports mentions of @aktive and @nye. +// Get all phone numbers for active members const _ = require('lodash'); const members = require('../lib/members'); -const prefixes = [ - 'Time to shine', - "The work doesn't do itself", - 'Get going', - 'lol rekt', - 'About time you got picked', - 'RIP', - 'Move it' -]; - -const createMention = username => `@${username}`; - module.exports = robot => { - robot.hear(/@noen-nye/i, msg => { - members('?new=true') - .then(members => { - if (!members.length) { - return; - } - - const luckyMember = _.sample(members); - const mention = createMention(luckyMember.slack); - const cheesyPrefix = _.sample(prefixes); - msg.send(`${cheesyPrefix} ${mention}`); - }) - .catch(error => msg.send(error.message)); - }); - - robot.hear(/@noen/i, msg => { - // Reply with a cheesy message and a random picked mention. - members('?active=true') - .then(members => { - if (!members.length) { - return; - } - - const luckyMember = _.sample(members); - const mention = createMention(luckyMember.slack); - const cheesyPrefix = _.sample(prefixes); - msg.send(`${cheesyPrefix} ${mention}`); - }) - .catch(error => msg.send(error.message)); - }); - - robot.hear(/@aktive|@active/i, msg => { - // Reply with a message containing mentions of all active users. + robot.respond(/nummer/i, msg => { members('?active=true') .then(members => { if (members.length === 0) { return; } - - msg.send(members.map(member => createMention(member.slack)).join(', ')); - }) - .catch(error => msg.send(error.message)); - }); - - robot.hear(/@nye/i, msg => { - members('?new=true') - .then(members => { - if (members.length === 0) { - return; - } - - msg.send(members.map(member => createMention(member.slack)).join(', ')); + msg.send( + members + .map( + m => + `*${m.name}*:${'\t'} ${m.phone_number.substr( + 0, + 3 + )} ${m.phone_number + .substr(3) + .match(/.{1,2}/g) + .join(' ')}` + ) + .sort() + .join('\n') + ); }) .catch(error => msg.send(error.message)); });
1aef53ef94e4031cb23e9c79c1b677299307284b
app/renderer/js/utils/domain-util.js
app/renderer/js/utils/domain-util.js
'use strict'; const {app} = require('electron').remote; const JsonDB = require('node-json-db'); class DomainUtil { constructor() { this.db = new JsonDB(app.getPath('userData') + '/domain.json', true, true); } getDomains() { return this.db.getData('/domains'); } addDomain() { const servers = { url: 'https://chat.zulip.org', alias: 'Zulip 2', avatar: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' } db.push("/domains[]", servers, true); } } module.exports = DomainUtil;
'use strict'; const {app} = require('electron').remote; const JsonDB = require('node-json-db'); class DomainUtil { constructor() { this.db = new JsonDB(app.getPath('userData') + '/domain.json', true, true); } getDomains() { return this.db.getData('/domains'); } addDomain() { const servers = { url: 'https://chat.zulip.org', alias: 'Zulip 2333', icon: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' } this.db.push("/domains[]", servers, true); } removeDomains() { this.db.delete("/domains"); } } module.exports = DomainUtil;
Change domain config schema and update DomainUtil.
Change domain config schema and update DomainUtil.
JavaScript
apache-2.0
zulip/zulip-desktop,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-desktop,zulip/zulip-electron,zulip/zulip-electron,zulip/zulip-desktop
--- +++ @@ -15,10 +15,14 @@ addDomain() { const servers = { url: 'https://chat.zulip.org', - alias: 'Zulip 2', - avatar: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' + alias: 'Zulip 2333', + icon: 'https://chat.zulip.org/static/images/logo/zulip-icon-128x128.271d0f6a0ca2.png' } - db.push("/domains[]", servers, true); + this.db.push("/domains[]", servers, true); + } + + removeDomains() { + this.db.delete("/domains"); } }
e91e43feeddafb7d674f67f18cb2c0748a395006
packages/fela-bindings/src/extractUsedProps.js
packages/fela-bindings/src/extractUsedProps.js
/* @flow */ export default function extractUsedProps( rule: Function, theme: Object = {} ): Array<string> { const usedProps = [] // if the browser doesn't support proxies // we simply return an empty props object // see https://github.com/rofrischmann/fela/issues/468 if (typeof Proxy === 'undefined') { return usedProps } const handler = props => ({ get(target, key) { if (typeof target[key] === 'object' && target[key] !== null) { props.push(key) return target[key] } props.push(key) return target[key] }, }) const proxy = new Proxy({ theme }, handler(usedProps)) rule(proxy) return usedProps }
/* @flow */ export default function extractUsedProps( rule: Function, theme: Object = {} ): Array<string> { const usedProps = [] // if the browser doesn't support proxies // we simply return an empty props object // see https://github.com/rofrischmann/fela/issues/468 if (typeof Proxy === 'undefined') { return usedProps } const handler = props => ({ get(target, key) { if (typeof target[key] === 'object' && target[key] !== null) { props.push(key) return target[key] } props.push(key) return target[key] }, }) const proxy = new Proxy({ theme }, handler(usedProps)) try { rule(proxy) return usedProps } catch (err) { return [] } }
Handle exception extracting used props
Handle exception extracting used props Fix #595
JavaScript
mit
risetechnologies/fela,rofrischmann/fela,risetechnologies/fela,rofrischmann/fela,risetechnologies/fela,rofrischmann/fela
--- +++ @@ -24,6 +24,10 @@ }) const proxy = new Proxy({ theme }, handler(usedProps)) - rule(proxy) - return usedProps + try { + rule(proxy) + return usedProps + } catch (err) { + return [] + } }
8bc778f740fa3fa77a49328739265e5d4edd9e54
modules/slider/Gruntfile.js
modules/slider/Gruntfile.js
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
module.exports = function(grunt) { grunt.config.merge({ imagemin: { slider: { files: [{ expand: true, cwd: 'bower_components/cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }] } } }); grunt.registerTask('build-slider', ['imagemin:slider']); };
Update path of slider images.
Update path of slider images.
JavaScript
mit
aptuitiv/cacao
--- +++ @@ -5,7 +5,7 @@ slider: { files: [{ expand: true, - cwd: 'cacao/modules/slider/images', + cwd: 'bower_components/cacao/modules/slider/images', src: ['**/*.{png,jpg,gif}'], dest: '<%= global.dest %>/layout/images' }]
ad80b2068cdb6804ffe22f9d98b19ee1a19ea6c3
packages/non-core/bundle-visualizer/package.js
packages/non-core/bundle-visualizer/package.js
Package.describe({ version: '1.1.1', summary: 'Meteor bundle analysis and visualization.', documentation: 'README.md', }); Npm.depends({ "d3-selection": "1.0.5", "d3-shape": "1.0.6", "d3-hierarchy": "1.1.4", "d3-transition": "1.0.4", "d3-collection": "1.0.4", "pretty-bytes": "4.0.2", }); Package.onUse(function(api) { api.use('isobuild:dynamic-import@1.5.0'); api.use([ 'ecmascript', 'dynamic-import', 'http', ]); api.mainModule('server.js', 'server'); api.mainModule('client.js', 'client'); });
Package.describe({ version: '1.1.2', summary: 'Meteor bundle analysis and visualization.', documentation: 'README.md', }); Npm.depends({ "d3-selection": "1.0.5", "d3-shape": "1.0.6", "d3-hierarchy": "1.1.4", "d3-transition": "1.0.4", "d3-collection": "1.0.4", "pretty-bytes": "4.0.2", }); Package.onUse(function(api) { api.use('isobuild:dynamic-import@1.5.0'); api.use([ 'ecmascript', 'dynamic-import', 'http', ]); api.mainModule('server.js', 'server'); api.mainModule('client.js', 'client'); });
Bump bundle-visualizer patch version to 1.1.2.
Bump bundle-visualizer patch version to 1.1.2.
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -1,5 +1,5 @@ Package.describe({ - version: '1.1.1', + version: '1.1.2', summary: 'Meteor bundle analysis and visualization.', documentation: 'README.md', });
49965cc87d2f9ebf8ce7b0601845533b4721ecff
test/spec/sanity-checks.js
test/spec/sanity-checks.js
/* global describe, it, before */ var request = require('supertest') var assert = require('assert') var path = require('path') var fs = require('fs') /** * Basic sanity checks on the dev server */ describe('The prototype kit', function () { var app before(function (done) { app = require('../../server') done() }) it('should generate assets into the /public folder', function () { assert.doesNotThrow(function () { fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js')) fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico')) fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css')) }) }) it('should send with a well formed response for the index page', function (done) { request(app) .get('/') .expect('Content-Type', /text\/html/) .expect(200, done) }) })
/* eslint-env mocha */ var request = require('supertest') var app = require('../../server.js') var path = require('path') var fs = require('fs') var assert = require('assert') /** * Basic sanity checks on the dev server */ describe('The prototype kit', function () { it('should generate assets into the /public folder', function () { assert.doesNotThrow(function () { fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js')) fs.accessSync(path.resolve(__dirname, '../../public/images/favicon.ico')) fs.accessSync(path.resolve(__dirname, '../../public/stylesheets/application.css')) }) }) it('should send with a well formed response for the index page', function (done) { request(app) .get('/') .expect('Content-Type', /text\/html/) .expect(200) .end(function (err, res) { if (err) { done(err) } else { done() } }) }) })
Simplify the sanity test check
Simplify the sanity test check App doesn't need to listen in the test script as supertest accepts the app variable and handles the listening and un-listening itself. This also removes the needs for the after block to stop the server.
JavaScript
mit
hannalaakso/accessible-timeout-warning,alphagov/govuk_prototype_kit,nhsbsa/ppc-prototype,joelanman/govuk_prototype_kit,davedark/proto-timeline,companieshouse/ch-accounts-prototype,Demwunz/esif-prototype,danblundell/verify-local-patterns,Demwunz/esif-prototype,abbott567/govuk_prototype_kit,dwpdigitaltech/ejs-prototype,chrishanes/pvb_prisoner_proto,abbott567/govuk_prototype_kit,nhsbsa/ppc-prototype,arminio/govuk_prototype_kit,dwpdigitaltech/hrt-prototype,samwake/hoddat-cofc-caseworking,danblundell/verify-local-patterns,tsmorgan/marx,hannalaakso/accessible-timeout-warning,arminio/govuk_prototype_kit,gavinwye/govuk_prototype_kit,DilwoarH/GDS-Prototype-DM-SavedSearch,kenmaddison-scc/verify-local-patterns,benjeffreys/hmcts-idam-proto,hannalaakso/accessible-timeout-warning,dwpdigitaltech/ejs-prototype,davedark/proto-timeline,dwpdigitaltech/hrt-prototype,BucksCountyCouncil/verify-local-patterns,davedark/proto-timeline,tsmorgan/marx,benjeffreys/hmcts-idam-proto,paulpod/invgov,alphagov/govuk_prototype_kit,joelanman/govuk_prototype_kit,danblundell/verify-local-patterns,DilwoarH/GDS-Prototype-DM-SavedSearch,kenmaddison-scc/verify-local-patterns,chrishanes/pvb_prisoner_proto,dwpdigitaltech/hrt-prototype,arminio/govuk_prototype_kit,samwake/hoddat-cofc-caseworking,BucksCountyCouncil/verify-local-patterns,samwake/hoddat-cofc-caseworking,tsmorgan/marx,joelanman/govuk_prototype_kit,alphagov/govuk_prototype_kit,abbott567/govuk_prototype_kit,DilwoarH/GDS-Prototype-DM-SavedSearch,chrishanes/pvb_prisoner_proto,benjeffreys/hmcts-idam-proto,gavinwye/govuk_prototype_kit,nhsbsa/ppc-prototype,BucksCountyCouncil/verify-local-patterns,kenmaddison-scc/verify-local-patterns,Demwunz/esif-prototype,dwpdigitaltech/ejs-prototype,paulpod/invgov,paulpod/invgov,companieshouse/ch-accounts-prototype
--- +++ @@ -1,20 +1,14 @@ -/* global describe, it, before */ +/* eslint-env mocha */ var request = require('supertest') -var assert = require('assert') +var app = require('../../server.js') var path = require('path') var fs = require('fs') +var assert = require('assert') /** * Basic sanity checks on the dev server */ describe('The prototype kit', function () { - var app - - before(function (done) { - app = require('../../server') - done() - }) - it('should generate assets into the /public folder', function () { assert.doesNotThrow(function () { fs.accessSync(path.resolve(__dirname, '../../public/javascripts/application.js')) @@ -27,6 +21,13 @@ request(app) .get('/') .expect('Content-Type', /text\/html/) - .expect(200, done) + .expect(200) + .end(function (err, res) { + if (err) { + done(err) + } else { + done() + } + }) }) })
f4ef68a267821b41409b60d1f3efe51e7a8cd588
tests/dujs/modelfactory.js
tests/dujs/modelfactory.js
/** * Created by ChengFuLin on 2015/6/10. */ var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, should = require('should'); describe('ModelFactory', function () { "use strict"; describe('Factory Method', function () { it('should support to create empty Model', function () { var analyzedCFG = factoryAnalyzedCFG.create(); should.not.exist(analyzedCFG._testonly_._graph); should.exist(analyzedCFG._testonly_._relatedScopes); analyzedCFG._testonly_._relatedScopes.length.should.eql(0); should.exist(analyzedCFG._testonly_._dupairs); analyzedCFG._testonly_._dupairs.size.should.eql(0); }); }); });
/* * Test cases for ModelFactory * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) * @lastmodifiedDate 2015-08-14 */ var factoryModel = require('../../lib/dujs/modelfactory'); var should = require('should'); describe('ModelFactory', function () { "use strict"; describe('public methods', function () { describe('create', function () { it('should support to create empty Model', function () { var model = factoryModel.create(); should.not.exist(model._testonly_._graph); should.exist(model._testonly_._relatedScopes); model._testonly_._relatedScopes.length.should.eql(0); should.exist(model._testonly_._dupairs); model._testonly_._dupairs.size.should.eql(0); }); }); }); });
Refactor test cases for ModelFactory
Refactor test cases for ModelFactory
JavaScript
mit
chengfulin/dujs,chengfulin/dujs
--- +++ @@ -1,19 +1,23 @@ -/** - * Created by ChengFuLin on 2015/6/10. +/* + * Test cases for ModelFactory + * @lastmodifiedBy ChengFuLin(chengfulin0806@gmail.com) + * @lastmodifiedDate 2015-08-14 */ -var factoryAnalyzedCFG = require('../../lib/dujs').factoryAnalyzedCFG, - should = require('should'); +var factoryModel = require('../../lib/dujs/modelfactory'); +var should = require('should'); describe('ModelFactory', function () { "use strict"; - describe('Factory Method', function () { - it('should support to create empty Model', function () { - var analyzedCFG = factoryAnalyzedCFG.create(); - should.not.exist(analyzedCFG._testonly_._graph); - should.exist(analyzedCFG._testonly_._relatedScopes); - analyzedCFG._testonly_._relatedScopes.length.should.eql(0); - should.exist(analyzedCFG._testonly_._dupairs); - analyzedCFG._testonly_._dupairs.size.should.eql(0); - }); + describe('public methods', function () { + describe('create', function () { + it('should support to create empty Model', function () { + var model = factoryModel.create(); + should.not.exist(model._testonly_._graph); + should.exist(model._testonly_._relatedScopes); + model._testonly_._relatedScopes.length.should.eql(0); + should.exist(model._testonly_._dupairs); + model._testonly_._dupairs.size.should.eql(0); + }); + }); }); });
1a71a91e9b143625d5863c21dc9de039e38541a2
src/user/components/online_payments.js
src/user/components/online_payments.js
import React from 'react' import CreaditCardPayment from './credit_card_payment.js' import Paypal from './paypal.js' export default (props) => { return props.user_payments.payment_sent ? SuccessfulPayment(props) : (props.user_payments.braintree_error ? Error() : PaymentOptions(props)) } const Error = () => <div>There has been a network error. Please refresh the browser.</div> const PaymentOptions = (props) => <div className='make-payment'> <h1 className='title'>Online Payment</h1> <h3 className='subtitle'>If you would prefer to pay by PayPal</h3> <h3 className='subtitle'>Alternatively pay by card</h3> <CreaditCardPayment {...props} /> </div> // <Paypal {...props} /> const SuccessfulPayment = ({ user_payments }) => <div className='make-payment'> <h1 className='title'>Successful Payment</h1> <h3 className='subtitle'> Thank you for your payment of £{user_payments.amount_entered}. Your reference for that payment is {user_payments.payment_sent.reference}. </h3> </div>
import React from 'react' import CreaditCardPayment from './credit_card_payment.js' import Paypal from './paypal.js' export default (props) => { return props.user_payments.payment_sent ? SuccessfulPayment(props) : (props.user_payments.braintree_error ? Error() : PaymentOptions(props)) } const Error = () => <div>There has been a network error. Please refresh the browser.</div> const PaymentOptions = (props) => <div className='make-payment'> <h1 className='title'>Online Payment</h1> <h3 className='subtitle'>Pay using PayPal</h3> <Paypal {...props} /> <h3 className='subtitle'>Alternatively pay by card</h3> <CreaditCardPayment {...props} /> </div> const SuccessfulPayment = ({ user_payments }) => <div className='make-payment'> <h1 className='title'>Successful Payment</h1> <h3 className='subtitle'> Thank you for your payment of £{user_payments.amount_entered}. Your reference for that payment is {user_payments.payment_sent.reference}. </h3> </div>
Add paypal component to online payments.
Add paypal component to online payments.
JavaScript
mit
foundersandcoders/sail-back,foundersandcoders/sail-back
--- +++ @@ -15,12 +15,12 @@ const PaymentOptions = (props) => <div className='make-payment'> <h1 className='title'>Online Payment</h1> - <h3 className='subtitle'>If you would prefer to pay by PayPal</h3> + <h3 className='subtitle'>Pay using PayPal</h3> + <Paypal {...props} /> <h3 className='subtitle'>Alternatively pay by card</h3> <CreaditCardPayment {...props} /> </div> - // <Paypal {...props} /> const SuccessfulPayment = ({ user_payments }) => <div className='make-payment'>
d23aed5fd0e19b5a6612211810ebce796af3db58
sieve-of-eratosthenes.js
sieve-of-eratosthenes.js
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(num){ var squareRoot = Math.sqrt(num); }
// Sieve of Eratosthenes /*RULES: Function takes one parameter Return an array of all prime numbers from 0-parameter */ /*PSEUDOCODE: 1) Find square root of parameter 2) Create an array of numbers from 0-parameter 3) Loop through numbers, but stop until square root (if a float, stop after number rounded up?) 4) Return array */ function sieveOfEratosthenes(num){ var squareRoot = Math.sqrt(num); var arr = [...Array(num + 1)].map((x, i) => i) }
Create var arr that creates the needed array depending on the given param
Create var arr that creates the needed array depending on the given param
JavaScript
mit
benjaminhyw/javascript_algorithms
--- +++ @@ -14,4 +14,7 @@ function sieveOfEratosthenes(num){ var squareRoot = Math.sqrt(num); + var arr = [...Array(num + 1)].map((x, i) => i) + + }
2b5f19052395fd6364bd488b85e37f15b9a9bda9
cmds/create.js
cmds/create.js
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { console.log("Got command, sending"); this.bot.sendMessage({ to: cid, message: 'Hello ' + username + ' [' + message + ']', }, (err, res) => { console.log('CB', err, res); }); var split = message.split(' '); var givenName = 'Temporary Channel'; if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
'use strict'; /* * /create [name] - Creates a voice-chat channel. Optionally names it, otherwise names it Username-[current game] * */ class Create{ constructor (bot, config) { this.bot = bot; this.config = config; } get command () { return 'create' } // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { var split = message.split(' '); var givenName = 'Temporary Channel'; // Check if user is in game, then name it that var user = this.bot.users[uid]; if (user.game !== null) { givenName = user.game.name; } // Check if name is defined, use that if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName; console.log('Creating channel', channelName); this.bot.createTemporaryChannel(channelName, gid); } checkUserPermissions(uid, server) { return true; } } module.exports = Create;
Add temp channel init with game name
Add temp channel init with game name
JavaScript
mit
Just-Fans-Of/Impromp2
--- +++ @@ -15,16 +15,17 @@ // Message input, user id <snowflake>, guild id <snowflake>, channel id <snowflake> onCommandEntered(message, username, uid, gid, cid) { - console.log("Got command, sending"); - this.bot.sendMessage({ - to: cid, - message: 'Hello ' + username + ' [' + message + ']', - }, (err, res) => { - console.log('CB', err, res); - }); var split = message.split(' '); var givenName = 'Temporary Channel'; + + // Check if user is in game, then name it that + var user = this.bot.users[uid]; + if (user.game !== null) { + givenName = user.game.name; + } + + // Check if name is defined, use that if (split.length > 1) split.slice(0, split.length).join(' '); var channelName = this.config.tempChannelNamePrefix + username + ': ' + givenName;
9d7c0cf74c1f7c1791cfe9ec8a36edca7a2b646d
sms-notifier/LambdaFunction.js
sms-notifier/LambdaFunction.js
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); // define configuration const phoneNumber =''; // Insert phone number here. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100 //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
// Sample Lambda Function to send notifications via text when an AWS Health event happens var AWS = require('aws-sdk'); var sns = new AWS.SNS(); //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { //get phone number from Env Variable var phoneNumber = process.env.PHONE_NUMBER; //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { if (err) { const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); callback(null, snsPublishSuccessMessage); //return success } }); };
Switch phone number to Environment Variable (instead of const)
Switch phone number to Environment Variable (instead of const)
JavaScript
apache-2.0
chetankrishna08/aws-health-tools,robperc/aws-health-tools,robperc/aws-health-tools,chetankrishna08/aws-health-tools
--- +++ @@ -2,17 +2,16 @@ var AWS = require('aws-sdk'); var sns = new AWS.SNS(); -// define configuration -const phoneNumber =''; // Insert phone number here. For example, a U.S. phone number in E.164 format would appear as +1XXX5550100 - //main function which gets AWS Health data from Cloudwatch event exports.handler = (event, context, callback) => { + //get phone number from Env Variable + var phoneNumber = process.env.PHONE_NUMBER; //extract details from Cloudwatch event eventName = event.detail.eventTypeCode healthMessage = 'The following AWS Health event type has occured: ' + eventName + ' For more details, please see https://phd.aws.amazon.com/phd/home?region=us-east-1#/dashboard/open-issues'; //prepare message for SNS to publish var snsPublishParams = { - Message: healthMessage, + Message: healthMessage, PhoneNumber: phoneNumber, }; sns.publish(snsPublishParams, function(err, data) { @@ -20,7 +19,7 @@ const snsPublishErrorMessage = `Error publishing AWS Health event to SNS`; console.log(snsPublishErrorMessage, err); callback(snsPublishErrorMessage); - } + } else { const snsPublishSuccessMessage = `Successfully got details from AWS Health event, ${eventName} and sent SMS via SNS.`; console.log(snsPublishSuccessMessage, data); @@ -28,4 +27,3 @@ } }); }; -
6387ed56e8b5e41aa51a7994ca9f1db5b68a5644
app/assets/javascripts/multi-part.js
app/assets/javascripts/multi-part.js
// Javascript specific to guide admin $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); });
// Javascript specific to guide admin // When we add a new part, ensure we add the auto slug generator handler $(document).on('nested:fieldAdded:parts', function(event){ addAutoSlugGeneration(); }); function addAutoSlugGeneration() { $('input.title'). on('change', function () { var elem = $(this); var value = elem.val(); // Set slug on change. var slug_field = elem.closest('.part').find('.slug'); if (slug_field.text() === '') { slug_field.val(GovUKGuideUtils.convertToSlug(value)); } // Set header on change. var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); } $(function() { var sortable_opts = { axis: "y", handle: "a.accordion-toggle", stop: function(event, ui) { $('.part').each(function (i, elem) { $(elem).find('input.order').val(i + 1); ui.item.find("a.accordion-toggle").addClass("highlight"); setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) }); } } $('#parts').sortable(sortable_opts) .find("a.accordion-toggle").css({cursor: 'move'}); addAutoSlugGeneration(); });
Fix auto slug generation for newly added parts
Fix auto slug generation for newly added parts Since moving to use nested forms, we now need to listen for a nested field added event and attach the auto slug generator handler accordingly.
JavaScript
mit
theodi/publisher,telekomatrix/publisher,alphagov/publisher,theodi/publisher,theodi/publisher,telekomatrix/publisher,alphagov/publisher,leftees/publisher,telekomatrix/publisher,leftees/publisher,leftees/publisher,theodi/publisher,alphagov/publisher,leftees/publisher,telekomatrix/publisher
--- +++ @@ -1,19 +1,10 @@ // Javascript specific to guide admin -$(function() { - var sortable_opts = { - axis: "y", - handle: "a.accordion-toggle", - stop: function(event, ui) { - $('.part').each(function (i, elem) { - $(elem).find('input.order').val(i + 1); - ui.item.find("a.accordion-toggle").addClass("highlight"); - setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) - }); - } - } - $('#parts').sortable(sortable_opts) - .find("a.accordion-toggle").css({cursor: 'move'}); +// When we add a new part, ensure we add the auto slug generator handler +$(document).on('nested:fieldAdded:parts', function(event){ + addAutoSlugGeneration(); +}); +function addAutoSlugGeneration() { $('input.title'). on('change', function () { var elem = $(this); @@ -29,4 +20,21 @@ var header = elem.closest('fieldset').prev('h3').find('a'); header.text(value); }); +} + +$(function() { + var sortable_opts = { + axis: "y", + handle: "a.accordion-toggle", + stop: function(event, ui) { + $('.part').each(function (i, elem) { + $(elem).find('input.order').val(i + 1); + ui.item.find("a.accordion-toggle").addClass("highlight"); + setTimeout(function() { $("a.accordion-toggle.highlight").removeClass("highlight") }, 20 ) + }); + } + } + $('#parts').sortable(sortable_opts) + .find("a.accordion-toggle").css({cursor: 'move'}); + addAutoSlugGeneration(); });
940624b8bbd2d18fa4072808cb3037078d5820d3
public/javascripts/App/Search/SearchPanel.ui.js
public/javascripts/App/Search/SearchPanel.ui.js
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' }, '-', { text: 'Save search', icon: urlRoot + 'images/disk.png' }, { text: 'Saved searches', icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
App.Search.SearchPanelUi = Ext.extend(Ext.form.FormPanel, { title: 'Search criteria', labelWidth: 100, labelAlign: 'left', layout: 'form', tbar: { xtype: 'toolbar', items: [{ text: 'Add language', icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' //}, '-', { //text: 'Save search', //icon: urlRoot + 'images/disk.png' //}, { //text: 'Saved searches', //icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png' }, '-', { text: '<b>Search</b>', icon: urlRoot + 'images/zoom.png' }] }, initComponent: function() { App.Search.SearchPanelUi.superclass.initComponent.call(this); this.setupSubcomponents(); }, /* Setup */ setupSubcomponents: function() { this.addLanguageButton.on('click', this.onAddLanguageClicked, this); }, /* Event handlers */ onAddLanguageClicked: function() { alert('hei'); } });
Hide search saving buttons for now
Hide search saving buttons for now
JavaScript
mit
textlab/glossa,textlab/rglossa,textlab/rglossa,textlab/rglossa,textlab/glossa,textlab/rglossa,textlab/glossa,textlab/glossa,textlab/glossa,textlab/rglossa
--- +++ @@ -10,12 +10,12 @@ icon: urlRoot + 'images/add.png', cls: 'x-btn-text-icon', ref: '../addLanguageButton' - }, '-', { - text: 'Save search', - icon: urlRoot + 'images/disk.png' - }, { - text: 'Saved searches', - icon: urlRoot + 'images/folder_explore.png' + //}, '-', { + //text: 'Save search', + //icon: urlRoot + 'images/disk.png' + //}, { + //text: 'Saved searches', + //icon: urlRoot + 'images/folder_explore.png' }, '-', { text: 'Reset form', icon: urlRoot + 'images/cancel.png'
6fe782fcd362e3cd330d22dbd17e270f26ebcf1b
app/js/arethusa/.version_template.js
app/js/arethusa/.version_template.js
'use strict'; angular.module('arethusa').constant('VERSION', { revision: '<%= sha %>', date: '<%= new Date().toJSON() %>' });
'use strict'; angular.module('arethusa').constant('VERSION', { revision: '<%= sha %>', date: '<%= new Date().toJSON() %>', repository: 'http://github.com/latin-language-toolkit/arethusa' });
Add the repo to the version CONSTANT
Add the repo to the version CONSTANT
JavaScript
mit
fbaumgardt/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,Masoumeh/arethusa,PonteIneptique/arethusa,fbaumgardt/arethusa,fbaumgardt/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa,latin-language-toolkit/arethusa,alpheios-project/arethusa
--- +++ @@ -2,5 +2,6 @@ angular.module('arethusa').constant('VERSION', { revision: '<%= sha %>', - date: '<%= new Date().toJSON() %>' + date: '<%= new Date().toJSON() %>', + repository: 'http://github.com/latin-language-toolkit/arethusa' });
7d0effb1e72b0957b20676a1717e07780100dae6
app/scripts/services/auth.factory.js
app/scripts/services/auth.factory.js
angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUIUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'signup', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; });
angular.module('MovnThereUI').factory('AuthFactory', function($http, $window, ServerUrl) { 'use strict'; var login = function(credentials) { return $http .post(ServerUrl + 'login', credentials) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var signup = function(credentials) { var params = { user: credentials }; return $http .post(ServerUrl + 'signup', params) .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); }; var logout = function(credentials) { return $http .post(ServerUrl + '/logout') .success(function(response) { $window.sessionStorage.removeItem('movnThereUI.user'); }); }; var isAuthenticated = function() { return !!$window.sessionStorage.getItem('movnThereUI.user'); }; return { login: login, signup: signup, logout: logout, isAuthenticated: isAuthenticated }; });
Fix sessionStorage name to retrieve token.
Fix sessionStorage name to retrieve token.
JavaScript
mit
HollyM021980/movin-there
--- +++ @@ -8,7 +8,7 @@ .success(function(response) { $window.sessionStorage.setItem('movnThereUI.user', response.token); - $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUIUI.user'); + $http.defaults.headers.common['Authorization'] = 'Token token=' + $window.sessionStorage.getItem('movnThereUI.user'); }); };
16e2183f60a66f41a78fef3f12b6321000be6357
packages/webmiddle-service-http-request/src/HttpRequest.js
packages/webmiddle-service-http-request/src/HttpRequest.js
import WebMiddle, { PropTypes } from 'webmiddle'; import request from 'request'; const HttpRequest = ({ name, contentType, url, method = 'GET', body = {}, httpHeaders = {}, cookies = {} }) => { // TODO: cookies return new Promise((resolve, reject) => { request({ uri: url, method, form: body, headers: httpHeaders, jar: true, // remember cookies for future use }, (error, response, content) => { if (!error && response.statusCode === 200) { resolve({ name, contentType, content }); } else { reject(error || response.statusCode); } }); }); }; HttpRequest.propTypes = { name: PropTypes.string.isRequired, contentType: PropTypes.string.isRequired, url: PropTypes.string.isRequired, method: PropTypes.string, body: PropTypes.oneOfType([ PropTypes.object, PropTypes.string, ]), httpHeaders: PropTypes.object, cookies: PropTypes.object, }; export default HttpRequest;
import WebMiddle, { PropTypes } from 'webmiddle'; import request from 'request'; const HttpRequest = ({ name, contentType, url, method = 'GET', body = {}, httpHeaders = {}, cookies = {} }) => { // TODO: cookies return new Promise((resolve, reject) => { const isJsonBody = httpHeaders && httpHeaders['Content-Type'] === 'application/json'; if (typeof body === 'object' && body !== null) { // body as string if (isJsonBody) { body = JSON.stringify(body); } else { // default: convert to form data body = Object.keys(body).reduce((list, prop) => { const value = body[prop]; list.push(`${encodeURIComponent(prop)}=${encodeURIComponent(value)}`); return list; }, []).join('&'); } } request({ uri: url, method, body, headers: { // default form content type needs to be explicitly set // (request doesn't do it automatically when using the body property) 'Content-Type': !isJsonBody ? 'application/x-www-form-urlencoded' : undefined, ...httpHeaders, }, jar: true, // remember cookies for future use }, (error, response, content) => { if (!error && response.statusCode === 200) { resolve({ name, contentType, content }); } else { reject(error || response.statusCode); } }); }); }; HttpRequest.propTypes = { name: PropTypes.string.isRequired, contentType: PropTypes.string.isRequired, url: PropTypes.string.isRequired, method: PropTypes.string, body: PropTypes.oneOfType([ PropTypes.object, PropTypes.string, ]), httpHeaders: PropTypes.object, cookies: PropTypes.object, }; export default HttpRequest;
Fix request body conversion and passing
Fix request body conversion and passing
JavaScript
mit
webmiddle/webmiddle
--- +++ @@ -5,11 +5,32 @@ ({ name, contentType, url, method = 'GET', body = {}, httpHeaders = {}, cookies = {} }) => { // TODO: cookies return new Promise((resolve, reject) => { + const isJsonBody = httpHeaders && httpHeaders['Content-Type'] === 'application/json'; + + if (typeof body === 'object' && body !== null) { + // body as string + if (isJsonBody) { + body = JSON.stringify(body); + } else { + // default: convert to form data + body = Object.keys(body).reduce((list, prop) => { + const value = body[prop]; + list.push(`${encodeURIComponent(prop)}=${encodeURIComponent(value)}`); + return list; + }, []).join('&'); + } + } + request({ uri: url, method, - form: body, - headers: httpHeaders, + body, + headers: { + // default form content type needs to be explicitly set + // (request doesn't do it automatically when using the body property) + 'Content-Type': !isJsonBody ? 'application/x-www-form-urlencoded' : undefined, + ...httpHeaders, + }, jar: true, // remember cookies for future use }, (error, response, content) => { if (!error && response.statusCode === 200) {
6421950d93e8e34e55971e6a0a84817075ed18fc
packages/meteor-components-ioc-plugin/package.js
packages/meteor-components-ioc-plugin/package.js
/*global Package*/ Package.describe({ name: 'dschnare:meteor-components-ioc-plugin', version: '0.2.0', // Brief, one-line summary of the package. summary: 'A plugin for Meteor Components that integrates IOC Containers.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/dschnare/meteor-components-ioc-plugin', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript', 'client'); api.use('xamfoo:reactive-obj', 'client'); api.use('ejson', 'client'); api.use([ 'dschnare:meteor-components@0.5.0', 'dschnare:ioc-container@0.2.0' ], 'client', { weak: true }); api.addFiles('meteor-components-ioc-plugin.js', 'client'); api.export('ComponentRootIoc', 'client'); }); Package.onTest(function(api) { api.use('ecmascript', 'client'); api.use('tinytest', 'client'); api.use('dschnare:meteor-components-ioc-plugin', 'client'); api.addFiles('meteor-components-ioc-plugin-tests.js', 'client'); });
/*global Package*/ Package.describe({ name: 'dschnare:meteor-components-ioc-plugin', version: '0.2.0', // Brief, one-line summary of the package. summary: 'A plugin for Meteor Components that integrates IOC Containers.', // URL to the Git repository containing the source code for this package. git: 'https://github.com/dschnare/meteor-components-ioc-plugin', // By default, Meteor will default to using README.md for documentation. // To avoid submitting documentation, set this field to null. documentation: 'README.md' }); Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript', 'client'); api.use('xamfoo:reactive-obj@0.5.0', 'client'); api.use('ejson', 'client'); api.use([ 'dschnare:meteor-components@0.5.0', 'dschnare:ioc-container@0.2.0' ], 'client', { weak: true }); api.addFiles('meteor-components-ioc-plugin.js', 'client'); api.export('ComponentRootIoc', 'client'); }); Package.onTest(function(api) { api.use('ecmascript', 'client'); api.use('tinytest', 'client'); api.use('dschnare:meteor-components-ioc-plugin', 'client'); api.addFiles('meteor-components-ioc-plugin-tests.js', 'client'); });
Add version constraint for reactive-obj
Add version constraint for reactive-obj
JavaScript
mit
dschnare/meteor-components-ioc-plugin,dschnare/meteor-components-ioc-plugin
--- +++ @@ -14,7 +14,7 @@ Package.onUse(function(api) { api.versionsFrom('1.2.1'); api.use('ecmascript', 'client'); - api.use('xamfoo:reactive-obj', 'client'); + api.use('xamfoo:reactive-obj@0.5.0', 'client'); api.use('ejson', 'client'); api.use([ 'dschnare:meteor-components@0.5.0',
f972dfc1091d58884b0a5b656f0e2cf02d94ba1d
tests/integration/components/loading-bar-test.js
tests/integration/components/loading-bar-test.js
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await later(() => { assert.equal(find(bar).getAttribute('value').trim(), 0); }, 2000); }, 1000); }); });
import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; import { render, find, waitFor } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; module('Integration | Component | loading bar', function(hooks) { setupRenderingTest(hooks); test('it renders', async function (assert) { const bar = '.bar'; const emptyBar = '.bar[value="0"]'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); await waitFor(bar); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); await waitFor(emptyBar); assert.equal(find(bar).getAttribute('value').trim(), 0); }, 500); }); });
Improve async loading bar test
Improve async loading bar test The waitFor helper is allows us to wait for what we are actually testing instead of a time which sometimes blocks the rendering and causes the test to be flaky.
JavaScript
mit
dartajax/frontend,thecoolestguy/frontend,djvoa12/frontend,dartajax/frontend,thecoolestguy/frontend,djvoa12/frontend,jrjohnson/frontend,ilios/frontend,ilios/frontend,jrjohnson/frontend
--- +++ @@ -1,6 +1,6 @@ import { module, test } from 'qunit'; import { setupRenderingTest } from 'ember-qunit'; -import { render, find } from '@ember/test-helpers'; +import { render, find, waitFor } from '@ember/test-helpers'; import hbs from 'htmlbars-inline-precompile'; import { later } from '@ember/runloop'; @@ -9,19 +9,20 @@ test('it renders', async function (assert) { const bar = '.bar'; + const emptyBar = '.bar[value="0"]'; this.set('isLoading', true); // don't `await` this render as the internal task that never stops will keep this test running forever render(hbs`{{loading-bar isLoading=isLoading}}`); + await waitFor(bar); // we need to give the bar a moment to actually change state and we // cannot use wait here because the task actually keeps running forever preventing // any kind of settled state await later(async () => { assert.ok(find(bar).getAttribute('value').trim() > 0); this.set('isLoading', false); - await later(() => { - assert.equal(find(bar).getAttribute('value').trim(), 0); - }, 2000); - }, 1000); + await waitFor(emptyBar); + assert.equal(find(bar).getAttribute('value').trim(), 0); + }, 500); }); });
1bbb5f18d567cc45f10b4d1a3b943ccdf93fb7d2
test/unit/analysis/camshaft-reference.spec.js
test/unit/analysis/camshaft-reference.spec.js
var camshaftReference = require('../../../src/analysis/camshaft-reference'); describe('src/analysis/camshaft-reference', function () { describe('.getSourceNamesForAnalysisType', function () { it('should return the source names for a given analyses type', function () { expect(camshaftReference.getSourceNamesForAnalysisType('source')).toEqual([]); expect(camshaftReference.getSourceNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getSourceNamesForAnalysisType('trade-area')).toEqual(['source']); }); }); describe('.getParamNamesForAnalysisType', function () { it('should return the params names for a given analyses type', function () { expect(camshaftReference.getParamNamesForAnalysisType('source')).toEqual(['query']); expect(camshaftReference.getParamNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved', 'provider' ]); }); }); });
var camshaftReference = require('../../../src/analysis/camshaft-reference'); describe('src/analysis/camshaft-reference', function () { describe('.getSourceNamesForAnalysisType', function () { it('should return the source names for a given analyses type', function () { expect(camshaftReference.getSourceNamesForAnalysisType('source')).toEqual([]); expect(camshaftReference.getSourceNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getSourceNamesForAnalysisType('trade-area')).toEqual(['source']); }); }); describe('.getParamNamesForAnalysisType', function () { it('should return the params names for a given analyses type', function () { expect(camshaftReference.getParamNamesForAnalysisType('source')).toEqual(['query']); expect(camshaftReference.getParamNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved' ]); }); }); });
Remove expected/optional param as it was removed from reference
Remove expected/optional param as it was removed from reference
JavaScript
bsd-3-clause
splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js,splashblot/cartodb.js
--- +++ @@ -13,7 +13,7 @@ it('should return the params names for a given analyses type', function () { expect(camshaftReference.getParamNamesForAnalysisType('source')).toEqual(['query']); expect(camshaftReference.getParamNamesForAnalysisType('point-in-polygon')).toEqual(['points_source', 'polygons_source']); - expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved', 'provider' ]); + expect(camshaftReference.getParamNamesForAnalysisType('trade-area')).toEqual([ 'source', 'kind', 'time', 'isolines', 'dissolved' ]); }); }); });
f224d222e7ee47c272b168004aad4f1a344733cb
client/main.js
client/main.js
/** * @module client/main */ 'use strict'; var app = require('./app'); require('angular'); /** * Each 'index' generated via grunt process dynamically includes all browserify common-js modules * in js bundle */ require('./controllers/index'); require('./services/index'); require('./router'); var io = require('./lib/socket.io'); var socket = io.connect('http://localhost:3000'); socket.on('postSequence', function (data) { console.log('postSequence: ', data); }); /** * Bundle of all templates to be attached to $templateCache generated by grunt process */ var views = require('./build/views/viewBundle'); /** * Pre-load template cache with compiled jade templates included in JS bundle */ app.run(['$rootScope', '$templateCache', function ( $rootScope, $templateCache) { Object.keys(views.Templates).forEach(function (viewName) { $templateCache.put(viewName, views.Templates[viewName]()); }); } ]); /** * DOM-ready event, start app */ angular.element(document).ready(function () { angular.bootstrap(document, ['app']); });
/** * @module client/main */ 'use strict'; var app = require('app'); require('angular'); /** * Each 'index' generated via grunt process dynamically includes all browserify common-js modules * in js bundle */ require('./controllers/index'); require('./services/index'); require('./router'); var io = require('./lib/socket.io'); var socket = io.connect('http://localhost:3000'); socket.on('postSequence', function (data) { console.log('postSequence: ', data); }); /** * Bundle of all templates to be attached to $templateCache generated by grunt process */ var views = require('./build/views/viewBundle'); /** * Pre-load template cache with compiled jade templates included in JS bundle */ app.run(['$rootScope', '$templateCache', function ( $rootScope, $templateCache) { Object.keys(views.Templates).forEach(function (viewName) { $templateCache.put(viewName, views.Templates[viewName]()); }); } ]); /** * DOM-ready event, start app */ angular.element(document).ready(function () { angular.bootstrap(document, ['app']); });
Change argument to require from relative to global path
Change argument to require from relative to global path
JavaScript
mit
Runnable/hyperion,Runnable/hyperion
--- +++ @@ -3,7 +3,7 @@ */ 'use strict'; -var app = require('./app'); +var app = require('app'); require('angular'); /**
9c11b6de5181e4825a345c103add725a2f487926
lib/curry-provider.js
lib/curry-provider.js
'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (prefix) { const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { const createSugg = this.createSuggestion.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } return null; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider();
'use babel'; import completions from '../data/completions'; class CurryProvider { constructor() { this.scopeSelector = '.source.curry'; this.disableForScopeSelector = '.source.curry .comment'; this.suggestionPriority = 2; this.filterSuggestions = true; this.acpTypes = new Map([['types', 'type'], ['constructors', 'tag'], ['functions', 'function']]); } getSuggestions({prefix}) { if (!prefix) { return null; } const suggestions = []; for (const module of completions) { for (const [key, type] of this.acpTypes) { const createSugg = this.createSuggestion.bind(null, module.name, type); const matches = module[key].map(createSugg); suggestions.push(...matches); } } return suggestions; } createSuggestion(module, type, suggestion) { return { text: suggestion.name, description: suggestion.description, type: type, leftLabel: module, rightLabel: suggestion.typeSig }; } } export default new CurryProvider();
Return null as early as possible if the prefix is invalid
Return null as early as possible if the prefix is invalid
JavaScript
mit
matthesjh/autocomplete-curry
--- +++ @@ -14,23 +14,23 @@ } getSuggestions({prefix}) { - if (prefix) { - const suggestions = []; - - for (const module of completions) { - for (const [key, type] of this.acpTypes) { - const createSugg = this.createSuggestion.bind(null, module.name, type); - - const matches = module[key].map(createSugg); - - suggestions.push(...matches); - } - } - - return suggestions; + if (!prefix) { + return null; } - return null; + const suggestions = []; + + for (const module of completions) { + for (const [key, type] of this.acpTypes) { + const createSugg = this.createSuggestion.bind(null, module.name, type); + + const matches = module[key].map(createSugg); + + suggestions.push(...matches); + } + } + + return suggestions; } createSuggestion(module, type, suggestion) {
c3d64c3a782d546284955d653a88dcd41237f6f4
www/plugin.js
www/plugin.js
var exec = require('cordova/exec'); var PLUGIN_NAME = 'SystemSound'; var SystemSound = { playSound: function(cb) { exec(cb, null, PLUGIN_NAME, 'playSound', []); } }; module.exports = SystemSound;
var exec = require('cordova/exec'); var PLUGIN_NAME = 'SystemSound'; var SystemSound = { playSound: function(cb) { exec(cb, null, PLUGIN_NAME, 'playSound', [phrase]); } }; module.exports = SystemSound;
Fix exec function with no argument
Fix exec function with no argument
JavaScript
mit
Switch168/cordova-plugin-system-sound-services
--- +++ @@ -5,7 +5,7 @@ var SystemSound = { playSound: function(cb) { - exec(cb, null, PLUGIN_NAME, 'playSound', []); + exec(cb, null, PLUGIN_NAME, 'playSound', [phrase]); } };
0da59ee8c95f2d065b6f0b600f4d6cffd654437e
packages/ddp-client/common/getClientStreamClass.js
packages/ddp-client/common/getClientStreamClass.js
import { Meteor } from 'meteor/meteor'; // In the client and server entry points, we make sure the // bundler loads the correct thing. Here, we just need to // make sure that we require the right one. export default function getClientStreamClass() { // The static analyzer of the bundler specifically looks // for direct calls to 'require', so it won't treat the // below calls as a request to include that module. const notRequire = require; if (Meteor.isClient) { return notRequire('../client/stream_client_sockjs').default; } else { /* Meteor.isServer */ return notRequire('../server/stream_client_nodejs').default; } }
import { Meteor } from 'meteor/meteor'; // In the client and server entry points, we make sure the // bundler loads the correct thing. Here, we just need to // make sure that we require the right one. export default function getClientStreamClass() { // The static analyzer of the bundler specifically looks // for static calls to 'require', so it won't treat the // below calls as a request to include that module. // // That means stream_client_nodejs won't be included on // the client, as desired. const modulePath = Meteor.isClient ? '../client/stream_client_sockjs' : '../server/stream_client_nodejs'; return require(modulePath).default; }
Switch to more concise require as suggested by Ben
Switch to more concise require as suggested by Ben
JavaScript
mit
Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor,Hansoft/meteor
--- +++ @@ -5,14 +5,14 @@ // make sure that we require the right one. export default function getClientStreamClass() { // The static analyzer of the bundler specifically looks - // for direct calls to 'require', so it won't treat the + // for static calls to 'require', so it won't treat the // below calls as a request to include that module. - const notRequire = require; + // + // That means stream_client_nodejs won't be included on + // the client, as desired. + const modulePath = Meteor.isClient + ? '../client/stream_client_sockjs' + : '../server/stream_client_nodejs'; - if (Meteor.isClient) { - return notRequire('../client/stream_client_sockjs').default; - } else { - /* Meteor.isServer */ - return notRequire('../server/stream_client_nodejs').default; - } + return require(modulePath).default; }
db1c42b80ee59bc6ab4b9757c37172a0dab55d0e
examples/index.js
examples/index.js
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request', 'math.add'); client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); });
'use strict'; var Harmonia = require('harmonia'); // Create a new server that listens to a given queue var harmonia = new Harmonia.Server('rpc'); harmonia.route({ method : 'math.add', module : './math/add.js' }); harmonia.route({ method : 'math.subtract', module : './math/subtract.js', }); harmonia.route({ method : 'math.divide', module : './math/divide.js', }); // Start the server harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client var client = Harmonia.Client.createClient('amqp://localhost', 'request'); client.then(function(client) { client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); }); });
Update Harmonia client example to reflect changes in 0.4
Update Harmonia client example to reflect changes in 0.4
JavaScript
mit
linearregression/harmonia,colonyamerican/harmonia
--- +++ @@ -24,19 +24,21 @@ harmonia.listen('amqp://localhost'); // Make some requests using the Harmonia client -var client = Harmonia.Client.createClient('amqp://localhost', 'request', 'math.add'); +var client = Harmonia.Client.createClient('amqp://localhost', 'request'); -client.call('math.add', { x : 15, y : 5 }) +client.then(function(client) { + client.call('math.add', { x : 15, y : 5 }) .then(function(result) { console.log('add', result.content); }); -client.call('math.subtract', { x : 15, y : 5 }) + client.call('math.subtract', { x : 15, y : 5 }) .then(function(result) { console.log('subtract', result.content); }); -client.call('math.divide', { x : 15, y : 5 }) + client.call('math.divide', { x : 15, y : 5 }) .then(function(result) { console.log('divide', result.content); }); +});
4af7e62397088ab5e49f022f1f60f2347249920a
gulpfile.js
gulpfile.js
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
var gulp = require('gulp'), csslint = require('gulp-csslint'), jshint = require('gulp-jshint'), rename = require('gulp-rename'), uglify = require('gulp-uglify'), autoprefixer = require('gulp-autoprefixer'), minifyCSS = require('gulp-minify-css'), stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') .pipe(csslint('.csslintrc')) .pipe(csslint.reporter()) }); gulp.task('minify:css', function () { return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], cascade: false, })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css')) .pipe(gulp.dest('dist/')); }); gulp.task('jshint', function () { return gulp.src('src/imagelightbox.js') .pipe(jshint()) .pipe(jshint.reporter(stylish)); }); gulp.task('minify:js', function () { return gulp.src('src/imagelightbox.js') .pipe(uglify()) .pipe(rename('imagelightbox.min.js')) .pipe(gulp.dest('dist/')); }); gulp.task('default', ['csslint', 'minify:css', 'jshint', 'minify:js']);
Remove code alignment, add trailing comma, add EOF newline
Remove code alignment, add trailing comma, add EOF newline
JavaScript
mit
Lochlan/imagelightbox,Lochlan/imagelightbox
--- +++ @@ -1,11 +1,11 @@ -var gulp = require('gulp'), - csslint = require('gulp-csslint'), - jshint = require('gulp-jshint'), - rename = require('gulp-rename'), - uglify = require('gulp-uglify'), - autoprefixer = require('gulp-autoprefixer'), - minifyCSS = require('gulp-minify-css'), - stylish = require('jshint-stylish'); +var gulp = require('gulp'), + csslint = require('gulp-csslint'), + jshint = require('gulp-jshint'), + rename = require('gulp-rename'), + uglify = require('gulp-uglify'), + autoprefixer = require('gulp-autoprefixer'), + minifyCSS = require('gulp-minify-css'), + stylish = require('jshint-stylish'); gulp.task('csslint', function () { return gulp.src('src/imagelightbox.css') @@ -17,7 +17,7 @@ return gulp.src('src/imagelightbox.css') .pipe(autoprefixer({ browsers: ['last 2 versions', 'ie >= 7', 'Firefox ESR', 'Android >= 2.3'], - cascade: false + cascade: false, })) .pipe(minifyCSS()) .pipe(rename('imagelightbox.min.css'))
61ab0adcfc8750dda6f5aae5552cb5c282fc5282
gulpfile.js
gulpfile.js
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
var gulp = require('gulp'); var react = require('gulp-react'); var git = require('gulp-git'); var fs = require('fs'); var shell = require('gulp-shell') gulp.task('brew', function () { if (fs.existsSync('homebrew')) { git.pull('origin', 'master', { cwd: 'homebrew' }, function (err) { if (err) throw err; }); } else { git.clone('https://github.com/Homebrew/homebrew', function (err) { if (err) throw err; }); } }); gulp.task('collect', shell.task([ './bin/collect homebrew' ])); gulp.task('info', shell.task([ './bin/info homebrew' ])); gulp.task('rank', shell.task([ './bin/rank' ])); gulp.task('dump', shell.task([ './bin/dump > dist/formulae.json' ])); gulp.task('copy', function () { return gulp.src('src/index.html') .pipe(gulp.dest('dist')) }) gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist')); });
Add automatic running of info script
Add automatic running of info script
JavaScript
mit
zharley/ferment,zharley/ferment,zharley/ferment,zharley/ferment
--- +++ @@ -20,6 +20,10 @@ './bin/collect homebrew' ])); +gulp.task('info', shell.task([ + './bin/info homebrew' +])); + gulp.task('rank', shell.task([ './bin/rank' ])); @@ -33,7 +37,7 @@ .pipe(gulp.dest('dist')) }) -gulp.task('default', [ 'brew', 'collect', 'rank', 'dump', 'copy' ], function () { +gulp.task('default', [ 'brew', 'collect', 'info', 'rank', 'dump', 'copy' ], function () { return gulp.src('src/index.js') .pipe(react()) .pipe(gulp.dest('dist'));
670474a38b8114afd4e990ad3689f50e868ea356
resources/public/crel.min.js
resources/public/crel.min.js
(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],o(l=a.attrMap[l]||l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(()=>e):this.crel=e});
(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],l=a.attrMap[l]||l,o(l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(e):this.crel=e});
Update crel to latest version from github.com/KoryNunn/crel
Update crel to latest version from github.com/KoryNunn/crel
JavaScript
mit
xSke/Pxls,xSke/Pxls,xSke/Pxls,xSke/Pxls
--- +++ @@ -1 +1 @@ -(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],o(l=a.attrMap[l]||l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(()=>e):this.crel=e}); +(e=>{const t="function",n="isNode",r=document,o=(e,t)=>typeof e===t,i=(e,t)=>{null!==t&&(Array.isArray(t)?t.map(t=>i(e,t)):(a[n](t)||(t=r.createTextNode(t)),e.appendChild(t)))};function a(e,f){let l,d,s=arguments,c=1;if(e=a.isElement(e)?e:r.createElement(e),o(f,"object")&&!a[n](f)&&!Array.isArray(f))for(l in c++,f)d=f[l],l=a.attrMap[l]||l,o(l,t)?l(e,d):o(d,t)?e[l]=d:e.setAttribute(l,d);for(;c<s.length;c++)i(e,s[c]);return e}a.attrMap={},a.isElement=(e=>e instanceof Element),a[n]=(e=>e instanceof Node),a.proxy=new Proxy(a,{get:(e,t)=>(!(t in a)&&(a[t]=a.bind(null,t)),a[t])}),e(a,t)})((e,t)=>{"object"==typeof exports?module.exports=e:typeof define===t&&define.amd?define(e):this.crel=e});
5ab7f8deedf44a29dffa468ffdbed7a406b46458
app/assets/javascripts/analytics/_init.js
app/assets/javascripts/analytics/_init.js
(function() { "use strict"; var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; GOVUK.Analytics.load(); GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain, receiveCrossDomainTracking: true }); GOVUK.analytics.trackPageview(); GOVUK.analytics.addLinkedTrackerDomain('digitalservicesstore.service.gov.uk'); })();
(function() { "use strict"; var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; var property = 'UA-49258698-1'; GOVUK.Analytics.load(); GOVUK.analytics = new GOVUK.Analytics({ universalId: property, cookieDomain: cookieDomain, receiveCrossDomainTracking: true }); GOVUK.analytics.trackPageview(); GOVUK.analytics.addLinkedTrackerDomain('digitalservicesstore.service.gov.uk'); })();
Use a single UA code for Buyer App analytics
Use a single UA code for Buyer App analytics Missed out of this story (which only changed the Supplier App): https://www.pivotaltracker.com/story/show/106115458
JavaScript
mit
AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,AusDTO/dto-digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend,alphagov/digitalmarketplace-buyer-frontend
--- +++ @@ -1,7 +1,7 @@ (function() { "use strict"; var cookieDomain = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? '.digitalmarketplace.service.gov.uk' : document.domain; - var property = (document.domain === 'www.digitalmarketplace.service.gov.uk') ? 'UA-49258698-1' : 'UA-49258698-3'; + var property = 'UA-49258698-1'; GOVUK.Analytics.load(); GOVUK.analytics = new GOVUK.Analytics({
3bbb177681f8c05443f001721ebd50dfd205c4f5
ui/src/pages/blog/index.js
ui/src/pages/blog/index.js
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
import React from 'react' import Link from 'gatsby-link' import './index.scss' export default ({ data }) => { return ( <section> <div className="container"> <header className="major"> <h2>Blog</h2> </header> {data.allMarkdownRemark.edges.map(({ node }) => ( <section key={node.id} className="blog-preview"> <article > <Link to={node.frontmatter.path}><h3>{node.frontmatter.title}</h3></Link> <h4>{node.frontmatter.date}</h4> <p>{node.excerpt}</p> </article> </section> ))} </div> </section> ) } export const query = graphql` query BlogListQuery { allMarkdownRemark( filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}, sort: {fields: [frontmatter___date], order: DESC} ) { edges { node { id frontmatter { date title path } excerpt(pruneLength: 300) } } } } `
Sort blog entries by date.
Sort blog entries by date.
JavaScript
mit
danielbh/danielhollcraft.com,danielbh/danielhollcraft.com,danielbh/danielhollcraft.com-gatsbyjs,danielbh/danielhollcraft.com
--- +++ @@ -25,7 +25,10 @@ export const query = graphql` query BlogListQuery { - allMarkdownRemark(filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}) { + allMarkdownRemark( + filter: {fileAbsolutePath: {regex: "/blog/.*\\.md$/"}}, + sort: {fields: [frontmatter___date], order: DESC} + ) { edges { node { id
c22367e21f4f5282a8079731fd1f30cf49432ae9
ui/src/utils/formatting.js
ui/src/utils/formatting.js
export const formatBytes = (bytes) => { if (bytes === 0) { return '0 Bytes'; } if (!bytes) { return null; } const k = 1000; const dm = 2; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; } export const formatRPDuration = (duration) => { if (duration === '0' || duration === '0s') { return 'infinite'; } let adjustedTime = duration; const [_, hours, minutes, seconds] = duration.match(/(\d*)h(\d*)m(\d*)s/); // eslint-disable-line no-unused-vars const hoursInDay = 24; if (hours > hoursInDay) { const remainder = hours % hoursInDay; const days = (hours - remainder) / hoursInDay; adjustedTime = `${days}d`; adjustedTime += +remainder === 0 ? '' : `${remainder}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } else { adjustedTime = `${hours}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } return adjustedTime; }
export const formatBytes = (bytes) => { if (bytes === 0) { return '0 Bytes'; } if (!bytes) { return null; } const k = 1000; const dm = 2; const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']; const i = Math.floor(Math.log(bytes) / Math.log(k)); return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`; } export const formatRPDuration = (duration) => { if (duration === '0' || duration === '0s') { return '∞'; } let adjustedTime = duration; const [_, hours, minutes, seconds] = duration.match(/(\d*)h(\d*)m(\d*)s/); // eslint-disable-line no-unused-vars const hoursInDay = 24; if (hours > hoursInDay) { const remainder = hours % hoursInDay; const days = (hours - remainder) / hoursInDay; adjustedTime = `${days}d`; adjustedTime += +remainder === 0 ? '' : `${remainder}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } else { adjustedTime = `${hours}h`; adjustedTime += +minutes === 0 ? '' : `${minutes}m`; adjustedTime += +seconds === 0 ? '' : `${seconds}s`; } return adjustedTime; }
Add ∞ for infinite duration
Add ∞ for infinite duration
JavaScript
mit
nooproblem/influxdb,nooproblem/influxdb,influxdata/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,mark-rushakoff/influxdb,mark-rushakoff/influxdb,nooproblem/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdb/influxdb,influxdata/influxdb,influxdb/influxdb,nooproblem/influxdb,li-ang/influxdb,mark-rushakoff/influxdb,li-ang/influxdb
--- +++ @@ -17,7 +17,7 @@ export const formatRPDuration = (duration) => { if (duration === '0' || duration === '0s') { - return 'infinite'; + return '∞'; } let adjustedTime = duration;
c13d87bfb90bd3a7a1951305795c586be6afde98
lib/pick-chain-url.js
lib/pick-chain-url.js
const MAIN_API_URL = 'https://api.etherscan.io'; const OTHER_API_URL_MAP = { ropsten: 'https://api-ropsten.etherscan.io', kovan: 'https://api-kovan.etherscan.io', rinkeby: 'https://api-rinkeby.etherscan.io', homestead: 'https://api.etherscan.io', arbitrum: 'https://api.arbiscan.io', arbitrum_rinkeby: 'https://api-testnet.arbiscan.io' }; /** * gets the correct urls of the backend * @param {string} chain * @returns Url of backend */ function pickChainUrl(chain) { if (!chain || !OTHER_API_URL_MAP[chain]) { return MAIN_API_URL; } return OTHER_API_URL_MAP[chain]; } module.exports = pickChainUrl;
const MAIN_API_URL = 'https://api.etherscan.io'; const OTHER_API_URL_MAP = { ropsten: 'https://api-ropsten.etherscan.io', kovan: 'https://api-kovan.etherscan.io', rinkeby: 'https://api-rinkeby.etherscan.io', goerli: 'https://api-goerli.etherscan.io', sepolia: 'https://api-sepolia.etherscan.io', homestead: 'https://api.etherscan.io', arbitrum: 'https://api.arbiscan.io', arbitrum_rinkeby: 'https://api-testnet.arbiscan.io' }; /** * gets the correct urls of the backend * @param {string} chain * @returns Url of backend */ function pickChainUrl(chain) { if (!chain || !OTHER_API_URL_MAP[chain]) { return MAIN_API_URL; } return OTHER_API_URL_MAP[chain]; } module.exports = pickChainUrl;
Add Goerli and Sepolia to the API list
Add Goerli and Sepolia to the API list Hey @sebs Thanks a lot for this amazing library. I created this PR to include the Sepolia and Goerli API endpoints. Currently I'm creating the client (with `axios.create`) to support those two, but I'd be cool if I have directly included on the library. Thanks!
JavaScript
mit
sebs/etherscan-api
--- +++ @@ -3,6 +3,8 @@ ropsten: 'https://api-ropsten.etherscan.io', kovan: 'https://api-kovan.etherscan.io', rinkeby: 'https://api-rinkeby.etherscan.io', + goerli: 'https://api-goerli.etherscan.io', + sepolia: 'https://api-sepolia.etherscan.io', homestead: 'https://api.etherscan.io', arbitrum: 'https://api.arbiscan.io', arbitrum_rinkeby: 'https://api-testnet.arbiscan.io'
69d52f1cbac1c63a3a6f05aa32f8b8274cf4854f
src/open.js
src/open.js
function readSingleFile(e) { var file = e.target.files[0]; if (!file) { return; } var reader = new FileReader(); reader.onload = function(e) { var contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var lines = contents.split("\n"), output = [], i; output.push("<thead><tr><th scope=\"col\"><button>" + lines[0].slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + "</button></th></tr></thead>"); for (i = 1; i < lines.length; i++) output.push("<tr><td>" + lines[i].slice(0, -1).split(",").join("</td><td>") + "</td></tr>"); output = "<table>" + output.join("") + "</table>"; var div = document.getElementById('file-content'); div.innerHTML = output; var ths = document.getElementsByTagName("th"); console.log("ths " + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }
let csv = (function () { let buildHeader = function (line) { return "<thead><tr><th scope=\"col\"><button>" + line.slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + "</button></th></tr></thead>" }; let buildAsHtml = function (lines) { let output = [buildHeader(lines[0])]; for (let i = 1; i < lines.length; i++) output.push("<tr><td>" + lines[i].slice(0, -1).split(",").join("</td><td>") + "</td></tr>"); return "<table>" + output.join("") + "</table>"; }; return { buildAsHtml: buildAsHtml }; })(); function readSingleFile(e) { let file = e.target.files[0]; if (!file) { return; } let reader = new FileReader(); reader.onload = function(e) { let contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; reader.readAsText(file); } function TestCall(event, other) { console.log(event); console.log(other); } function displayContents(contents) { var div = document.getElementById('file-content'); div.innerHTML = csv.buildAsHtml(contents.split("\n")); var ths = document.getElementsByTagName("th"); console.log("ths " + ths); for (var i = 0; i < ths.length; i++) { ths[i].onclick = TestCall } // var element = $('#content'); // element.innerHTML = contents; }
Move csv in a module
Move csv in a module
JavaScript
mpl-2.0
aloisdg/kanti,aloisdg/kanti
--- +++ @@ -1,11 +1,31 @@ +let csv = (function () { + let buildHeader = function (line) { + return "<thead><tr><th scope=\"col\"><button>" + + line.slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + + "</button></th></tr></thead>" + }; + let buildAsHtml = function (lines) { + let output = [buildHeader(lines[0])]; + for (let i = 1; i < lines.length; i++) + output.push("<tr><td>" + + lines[i].slice(0, -1).split(",").join("</td><td>") + + "</td></tr>"); + return "<table>" + output.join("") + "</table>"; + }; + + return { + buildAsHtml: buildAsHtml + }; +})(); + function readSingleFile(e) { - var file = e.target.files[0]; + let file = e.target.files[0]; if (!file) { return; } - var reader = new FileReader(); + let reader = new FileReader(); reader.onload = function(e) { - var contents = e.target.result; + let contents = e.target.result; displayContents(contents); $('#play-input').disabled = false; }; @@ -18,19 +38,8 @@ } function displayContents(contents) { - var lines = contents.split("\n"), - output = [], - i; - output.push("<thead><tr><th scope=\"col\"><button>" + - lines[0].slice(0, -1).split(",").join("</button></th><th scope=\"col\"><button>") + - "</button></th></tr></thead>"); - for (i = 1; i < lines.length; i++) - output.push("<tr><td>" + - lines[i].slice(0, -1).split(",").join("</td><td>") + - "</td></tr>"); - output = "<table>" + output.join("") + "</table>"; var div = document.getElementById('file-content'); - div.innerHTML = output; + div.innerHTML = csv.buildAsHtml(contents.split("\n")); var ths = document.getElementsByTagName("th"); console.log("ths " + ths); for (var i = 0; i < ths.length; i++) {
0d5e7868c1cc1354748af529aca5727ffa9472c4
lib/state-snapshot.js
lib/state-snapshot.js
class StateSnapshot { constructor({ store, initialState, meta, currentState = initialState }) { this.store = store; this.initialState = { ...initialState }; this.items = { ...currentState }; this.meta = meta; this.closed = false; } async dispatchToStateSnapshot(action) { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; const newItems = await this.store.reducer({ ...this.items }, action); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, currentState: newItems, meta: this.meta, }); } async commitStateSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; await this.store.commit({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.items }, meta: this.meta, }); } async discardStateSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; await this.store.discard({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, meta: this.meta, }); } } exports.StateSnapshot = StateSnapshot;
class StateSnapshot { constructor({ store, initialState, meta, currentState = initialState }) { this.store = store; this.initialState = { ...initialState }; this.items = { ...currentState }; this.meta = meta; this.closed = false; } _closeSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; } async dispatchToStateSnapshot(action) { this._closeSnapshot(); const newItems = await this.store.reducer({ ...this.items }, action); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, currentState: newItems, meta: this.meta, }); } async commitStateSnapshot() { this._closeSnapshot(); await this.store.commit({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.items }, meta: this.meta, }); } async discardStateSnapshot() { this._closeSnapshot(); await this.store.discard({ meta: this.meta, items: this.items, }); return new StateSnapshot({ store: this.store, initialState: { ...this.initialState }, meta: this.meta, }); } } exports.StateSnapshot = StateSnapshot;
Remove code duplication from snapshot closed check
Remove code duplication from snapshot closed check
JavaScript
mit
jay-depot/cloverleaf
--- +++ @@ -7,12 +7,16 @@ this.closed = false; } - async dispatchToStateSnapshot(action) { + _closeSnapshot() { if (this.closed) { throw new Error('Attempted to dispatch action to closed StateSnapshot'); } this.closed = true; + } + + async dispatchToStateSnapshot(action) { + this._closeSnapshot(); const newItems = await this.store.reducer({ ...this.items }, action); return new StateSnapshot({ @@ -24,11 +28,7 @@ } async commitStateSnapshot() { - if (this.closed) { - throw new Error('Attempted to dispatch action to closed StateSnapshot'); - } - - this.closed = true; + this._closeSnapshot(); await this.store.commit({ meta: this.meta, items: this.items, @@ -42,11 +42,7 @@ } async discardStateSnapshot() { - if (this.closed) { - throw new Error('Attempted to dispatch action to closed StateSnapshot'); - } - - this.closed = true; + this._closeSnapshot(); await this.store.discard({ meta: this.meta, items: this.items,
8513c39e48ed6bd6ff28b21c898f39d96a9a8259
src/actions/user-actions.js
src/actions/user-actions.js
import db from '../db'; import { createAction } from 'redux-actions'; export const USER_LOGIN = 'USER_LOGIN'; export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'; export const USER_SIGNUP = 'USER_SIGNUP'; export const USER_SIGNUP_SUCCESS = 'USER_SIGNUP_SUCCESS'; export const USER_SIGNUP_FAIL = 'USER_SIGNUP_FAIL'; export const USER_LOGOUT = 'USER_LOGOUT'; export const login = createAction(USER_LOGIN, (username, password) => db.login(username, password));
import db from '../db'; import { createAction } from 'redux-actions'; export const USER_LOGIN = 'USER_LOGIN'; export const USER_SIGNUP = 'USER_SIGNUP'; export const USER_LOGOUT = 'USER_LOGOUT'; export const login = createAction(USER_LOGIN, (username, password) => db.login(username, password)); export const signup = createAction(USER_SIGNUP, (username, password) => db.signup(username, password)); export const logout = createAction(USER_LOGOUT, () => db.logout());
Add actions for user management
Add actions for user management
JavaScript
mit
andrew-filonenko/habit-tracker,andrew-filonenko/habit-tracker
--- +++ @@ -2,11 +2,10 @@ import { createAction } from 'redux-actions'; export const USER_LOGIN = 'USER_LOGIN'; -export const USER_LOGIN_SUCCESS = 'USER_LOGIN_SUCCESS'; export const USER_SIGNUP = 'USER_SIGNUP'; -export const USER_SIGNUP_SUCCESS = 'USER_SIGNUP_SUCCESS'; -export const USER_SIGNUP_FAIL = 'USER_SIGNUP_FAIL'; export const USER_LOGOUT = 'USER_LOGOUT'; export const login = createAction(USER_LOGIN, (username, password) => db.login(username, password)); +export const signup = createAction(USER_SIGNUP, (username, password) => db.signup(username, password)); +export const logout = createAction(USER_LOGOUT, () => db.logout());
c042d3fcdf6f38fc2a6562d4d4c1b17bcc2da269
client/js/directives/file-uploader-directive.js
client/js/directives/file-uploader-directive.js
"use strict"; angular.module("hikeio"). directive("fileUploader", ["$window", function($window) { return { compile: function(tplElm, tplAttr) { var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : ""; tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>"); return function(scope, elm, attr) { if (scope.$eval(attr.enabled)) { var input = angular.element(elm[0].nextSibling); input.bind("change", function() { if (input[0].files.length > 0) { scope.$eval(attr.fileUploader, {files: input[0].files}); input[0].value = ""; // Allow the user to select the same file again } }); elm.bind("click", function() { if (input[0].disabled) { $window.alert("Sorry this browser doesn't support file upload."); } input[0].click(); }); elm.css("cursor", "pointer"); } }; }, replace: true, template: "<div data-ng-transclude></div>", transclude: true }; }]);
"use strict"; angular.module("hikeio"). directive("fileUploader", ["$window", function($window) { return { compile: function(tplElm, tplAttr) { var mulitpleStr = tplAttr.multiple === "true" ? "multiple" : ""; tplElm.after("<input type='file' " + mulitpleStr + " accept='image/png, image/jpeg' style='display: none;'>"); return function(scope, elm, attr) { if (scope.$eval(attr.enabled)) { var input = angular.element(elm[0].nextSibling); input.bind("change", function() { if (input[0].files.length > 0) { scope.$eval(attr.fileUploader, {files: input[0].files}); input[0].value = ""; // Allow the user to select the same file again } }); elm.bind("click", function() { if (input[0].disabled || !$window.FileReader || !window.FormData) { $window.alert("Sorry, you cannot upload photos from this browser."); return; } input[0].click(); }); elm.css("cursor", "pointer"); } }; }, replace: true, template: "<div data-ng-transclude></div>", transclude: true }; }]);
Disable file inputs on browsers that don't support FileReader / FormData.
Disable file inputs on browsers that don't support FileReader / FormData.
JavaScript
mit
zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io,zaknelson/hike.io
--- +++ @@ -19,8 +19,9 @@ }); elm.bind("click", function() { - if (input[0].disabled) { - $window.alert("Sorry this browser doesn't support file upload."); + if (input[0].disabled || !$window.FileReader || !window.FormData) { + $window.alert("Sorry, you cannot upload photos from this browser."); + return; } input[0].click(); });
0a0e0ce83fba432df1a108925933a2a1e9a8c2f7
src/js/rishson/widget/example/nls/es/Wishlist.js
src/js/rishson/widget/example/nls/es/Wishlist.js
define({ root: { SortBy: "Ordenar por:", Descending: "Descendente", Name: "Nombre", DateAdded: "Fecha de entrada", Price: "Precio", Actions: "Acciones", Add: "Añadir", Remove: "Eliminar", Save: "Guardar" } });
define({ SortBy: "Ordenar por:", Descending: "Descendente", Name: "Nombre", DateAdded: "Fecha de entrada", Price: "Precio", Actions: "Acciones", Add: "Añadir", Remove: "Eliminar", Save: "Guardar" });
Fix mistake in Spanish i18n resource for example widget
Fix mistake in Spanish i18n resource for example widget
JavaScript
isc
rishson/dojoEnterpriseApp,rishson/dojoEnterpriseApp
--- +++ @@ -1,13 +1,11 @@ define({ - root: { - SortBy: "Ordenar por:", - Descending: "Descendente", - Name: "Nombre", - DateAdded: "Fecha de entrada", - Price: "Precio", - Actions: "Acciones", - Add: "Añadir", - Remove: "Eliminar", - Save: "Guardar" - } + SortBy: "Ordenar por:", + Descending: "Descendente", + Name: "Nombre", + DateAdded: "Fecha de entrada", + Price: "Precio", + Actions: "Acciones", + Add: "Añadir", + Remove: "Eliminar", + Save: "Guardar" });
55effc39da807b77262aca98a8587db369ca19e5
src/js/main.js
src/js/main.js
(function() { "use strict"; // animate moving between anchor links smoothScroll.init({ selector: "a", speed: 500, easing: "easeInOutCubic" }); // better external SVG spiresheet support svg4everybody(); // random placeholders for the contact form fields var form = document.querySelector(".contact"), names = [ "Paul Bunyan", "Luke Skywalker", "Jason Bourne", "James Bond" ], messages = [ "Like what you see? Let me know!", "Want to know more? Get in touch!", "Hey! Did I tickle your fancy?" ]; form.querySelector("[id='name']").placeholder = randomFromArray(names); form.querySelector("[id='message']").placeholder = randomFromArray(messages); function randomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; } })();
(function() { "use strict"; // animate moving between anchor hash links smoothScroll.init({ selector: "a", speed: 500, easing: "easeInOutCubic" }); // better external SVG spritesheet support svg4everybody(); // random placeholders for the contact form fields var names = [ "Paul Bunyan", "Luke Skywalker", "Jason Bourne", "James Bond" ], messages = [ "Like what you see? Let me know!", "Want to know more? Get in touch!", "Hey! Did I tickle your fancy?" ]; document.getElementById("name").placeholder = randomFromArray(names); document.getElementById("message").placeholder = randomFromArray(messages); function randomFromArray(array) { return array[Math.floor(Math.random() * array.length)]; } })();
Fix typo and optimize DOM querying
[js] Fix typo and optimize DOM querying
JavaScript
mit
Pinjasaur/portfolio,Pinjasaur/portfolio
--- +++ @@ -1,19 +1,19 @@ (function() { + "use strict"; - // animate moving between anchor links + // animate moving between anchor hash links smoothScroll.init({ selector: "a", speed: 500, easing: "easeInOutCubic" }); - // better external SVG spiresheet support + // better external SVG spritesheet support svg4everybody(); // random placeholders for the contact form fields - var form = document.querySelector(".contact"), - names = [ + var names = [ "Paul Bunyan", "Luke Skywalker", "Jason Bourne", @@ -25,8 +25,8 @@ "Hey! Did I tickle your fancy?" ]; - form.querySelector("[id='name']").placeholder = randomFromArray(names); - form.querySelector("[id='message']").placeholder = randomFromArray(messages); + document.getElementById("name").placeholder = randomFromArray(names); + document.getElementById("message").placeholder = randomFromArray(messages); function randomFromArray(array) { return array[Math.floor(Math.random() * array.length)];
ab3f0d14c998384b161c966b114c4793e1cb2795
src/history/startListener.js
src/history/startListener.js
import { manualChange } from '../redux/actions'; /** * Dispatches a manualChange action once on app start, * and whenever a popstate navigation event occurs. */ function startListener(history, store) { store.dispatch(manualChange(history.location.path)); history.listen((location, action) => { if (action === 'POP') { store.dispatch(manualChange(location.path)); } }); } export { startListener };
import { manualChange } from '../redux/actions'; /** * Dispatches a manualChange action once on app start, * and whenever a popstate navigation event occurs. */ function startListener(history, store) { store.dispatch(manualChange(`${history.location.pathname}${history.location.search}${history.location.hash}`)); history.listen((location, action) => { if (action === 'POP') { store.dispatch(manualChange(`${location.pathname}${location.search}${location.hash}`)); } }); } export { startListener };
Fix location dispatched in history listener
Fix location dispatched in history listener
JavaScript
mit
mksarge/redux-json-router
--- +++ @@ -5,11 +5,11 @@ * and whenever a popstate navigation event occurs. */ function startListener(history, store) { - store.dispatch(manualChange(history.location.path)); + store.dispatch(manualChange(`${history.location.pathname}${history.location.search}${history.location.hash}`)); history.listen((location, action) => { if (action === 'POP') { - store.dispatch(manualChange(location.path)); + store.dispatch(manualChange(`${location.pathname}${location.search}${location.hash}`)); } }); }
2f5135c85d627805e587efbcfdc91aa0fab9afca
examples/todo/client/src/components/TaskList.js
examples/todo/client/src/components/TaskList.js
import React from 'react'; import { Redirect } from 'react-router-dom'; import TodoItem from './TodoItem'; import TodoTextInput from './TodoTextInput'; import './TaskList.css'; export default function (props) { if (!props.doesExist) { return <Redirect to="/" />; } return ( <div className="todobody"> <div className="todoapp"> <h1 className="page-header">{props.title}</h1> <TodoTextInput newTodo onSave={name => props.onTodoItemCreate(name, props.cardId)} placeholder="What needs to be done?" /> <ul className="todo-list"> {Object.keys(props.tasks).map(key => ( <TodoItem key={key} todo={props.tasks[key]} onCheck={() => props.onTodoItemToggleCheck(key)} onRemove={() => props.onTodoItemRemove(key)} /> ))} </ul> </div> </div> ); }
import React from 'react'; import { Redirect } from 'react-router-dom'; import TodoItem from './TodoItem'; import TodoTextInput from './TodoTextInput'; import './TaskList.css'; export default function (props) { if (!props.doesExist) { return <Redirect to="/" />; } return ( <div className="todobody"> <div className="todoapp"> <h1 className="page-header">{props.title}</h1> {props.cardId && <TodoTextInput newTodo onSave={name => props.onTodoItemCreate(name, props.cardId)} placeholder="What needs to be done?" />} <ul className="todo-list"> {Object.keys(props.tasks).map(key => ( <TodoItem key={key} todo={props.tasks[key]} onCheck={() => props.onTodoItemToggleCheck(key)} onRemove={() => props.onTodoItemRemove(key)} /> ))} </ul> </div> </div> ); }
Fix input appearance in the 'All' view
Fix input appearance in the 'All' view
JavaScript
mit
reimagined/resolve,reimagined/resolve
--- +++ @@ -14,11 +14,12 @@ <div className="todobody"> <div className="todoapp"> <h1 className="page-header">{props.title}</h1> - <TodoTextInput - newTodo - onSave={name => props.onTodoItemCreate(name, props.cardId)} - placeholder="What needs to be done?" - /> + {props.cardId && + <TodoTextInput + newTodo + onSave={name => props.onTodoItemCreate(name, props.cardId)} + placeholder="What needs to be done?" + />} <ul className="todo-list"> {Object.keys(props.tasks).map(key => ( <TodoItem
03ea14a48ad3d8f6a1d1081295113e2ba8289727
resources/assets/js/components/BaseBlock.js
resources/assets/js/components/BaseBlock.js
import inlineFieldMixin from 'mixins/inlineFieldMixin'; import imagesLoaded from 'imagesloaded'; import { eventBus } from 'plugins/eventbus'; export default { props: [ 'type', 'index', 'fields', 'other' ], mixins: [inlineFieldMixin], data() { return { ...this.fields }; }, created() { this.fieldElements = {}; this.watching = {}; this.watchFields(this.fields); // should only be triggered when all fields are overwitten this.$watch('fields', () => { this.watchFields(this.fields); }); }, methods: { watchFields(fields) { Object.keys(fields).map((name) => { if(!this.watching[name]) { this.watching[name] = true; this.$watch(`fields.${name}`, (newVal) => { if(this.internalChange) { this.internalChange = false; return; } this[name] = newVal; // TODO: use state for this? imagesLoaded(this.$el, () => { eventBus.$emit('block:updateBlockOverlays'); }); }, { deep: true }); } }); } } };
import inlineFieldMixin from 'mixins/inlineFieldMixin'; import imagesLoaded from 'imagesloaded'; import { eventBus } from 'plugins/eventbus'; export default { props: [ 'type', 'index', 'fields', 'other' ], mixins: [inlineFieldMixin], data() { return { ...this.fields }; }, created() { this.fieldElements = {}; this.watching = {}; this.watchFields(this.fields); // should only be triggered when all fields are overwitten this.$watch('fields', () => { this.watchFields(this.fields); }); }, methods: { watchFields(fields) { Object.keys(fields).map((name) => { if(!this.watching[name]) { this.watching[name] = true; this.$watch(`fields.${name}`, (newVal) => { if(this.internalChange) { this.internalChange = false; return; } this[name] = newVal; eventBus.$emit('block:hideHoverOverlay'); // TODO: use state for this? imagesLoaded(this.$el, () => { eventBus.$emit('block:updateBlockOverlays'); }); }, { deep: true }); } }); } } };
Hide block hover overlay if it's still there when editing a field.
Hide block hover overlay if it's still there when editing a field.
JavaScript
mit
unikent/astro,unikent/astro,unikent/astro,unikent/astro,unikent/astro
--- +++ @@ -42,6 +42,8 @@ this[name] = newVal; + eventBus.$emit('block:hideHoverOverlay'); + // TODO: use state for this? imagesLoaded(this.$el, () => { eventBus.$emit('block:updateBlockOverlays');
a6bc03b09d04df24b049fa9f3e5c257b82040078
src/Model/Game/Levels.js
src/Model/Game/Levels.js
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if( typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
function Levels(prng, paletteRange, paletteBuilder) { this.prng = prng; this.paletteRange = paletteRange; this.paletteBuilder = paletteBuilder; } Levels.prototype.get = function(level) { if(typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); var puzzle = new Puzzle(level, board); return new Level(puzzle, levelPalette); };
Remove extra space from if statement
Remove extra space from if statement
JavaScript
mit
mnito/factors-game,mnito/factors-game
--- +++ @@ -5,24 +5,24 @@ } Levels.prototype.get = function(level) { - if( typeof this.prng.seed === 'function') { + if(typeof this.prng.seed === 'function') { this.prng.seed(level); } var hue = Math.floor(this.prng.random() * 360); var saturation = Math.floor(this.prng.random() * 20) + 80; - + this.paletteBuilder.hue = hue; this.paletteBuilder.saturation = saturation; var boardColors = this.paletteBuilder.build(16, this.paletteRange); var numberColor = HSL.complement(boardColors[Math.floor(this.prng.random() * 16)]); - + var levelPalette = new LevelPalette(numberColor, boardColors); var board = Board.create(4, 4, this.prng); board.shuffle(); - + var puzzle = new Puzzle(level, board); - + return new Level(puzzle, levelPalette); };
fb44adf35090e3e03fa80cdc0cf585b611d458e5
src/chrome/lib/help-page.js
src/chrome/lib/help-page.js
(function (h) { 'use strict'; function HelpPage(chromeTabs, extensionURL) { this.showHelpForError = function (tab, error) { if (error instanceof h.LocalFileError) { return this.showLocalFileHelpPage(tab); } else if (error instanceof h.NoFileAccessError) { return this.showNoFileAccessHelpPage(tab); } throw new Error('showHelpForError does not support the error: ' + e.message); }; this.showLocalFileHelpPage = showHelpPage.bind(null, 'local-file'); this.showNoFileAccessHelpPage = showHelpPage.bind(null, 'no-file-access'); // Render the help page. The helpSection should correspond to the id of a // section within the help page. function showHelpPage(helpSection, tab) { chromeTabs.update(tab.id, { url: extensionURL('/help/permissions.html#' + helpSection) }); } } h.HelpPage = HelpPage; })(window.h || (window.h = {}));
(function (h) { 'use strict'; function HelpPage(chromeTabs, extensionURL) { this.showHelpForError = function (tab, error) { if (error instanceof h.LocalFileError) { return this.showLocalFileHelpPage(tab); } else if (error instanceof h.NoFileAccessError) { return this.showNoFileAccessHelpPage(tab); } throw new Error('showHelpForError does not support the error: ' + error.message); }; this.showLocalFileHelpPage = showHelpPage.bind(null, 'local-file'); this.showNoFileAccessHelpPage = showHelpPage.bind(null, 'no-file-access'); // Render the help page. The helpSection should correspond to the id of a // section within the help page. function showHelpPage(helpSection, tab) { chromeTabs.update(tab.id, { url: extensionURL('/help/permissions.html#' + helpSection) }); } } h.HelpPage = HelpPage; })(window.h || (window.h = {}));
Fix typo in the HelpPage module
Fix typo in the HelpPage module
JavaScript
bsd-2-clause
hypothesis/browser-extension,hypothesis/browser-extension,project-star/browser-extension,project-star/browser-extension,hypothesis/browser-extension,project-star/browser-extension,hypothesis/browser-extension
--- +++ @@ -10,7 +10,7 @@ return this.showNoFileAccessHelpPage(tab); } - throw new Error('showHelpForError does not support the error: ' + e.message); + throw new Error('showHelpForError does not support the error: ' + error.message); }; this.showLocalFileHelpPage = showHelpPage.bind(null, 'local-file'); this.showNoFileAccessHelpPage = showHelpPage.bind(null, 'no-file-access');
ee2c4f35fdcf4784b08cc341a0aff77d2f33883e
app/assets/javascripts/toggle_display_with_checked_input.js
app/assets/javascripts/toggle_display_with_checked_input.js
(function(window, $){ window.toggleDisplayWithCheckedInput = function(args){ var $input = args.$input, $element = args.$element, showElement = args.mode === 'show'; var toggleOnChange = function(){ console.log($input); console.log("args.$mode =" + args.$mode); if($input.prop("checked")) { console.log("checked - toggle: " + showElement); $element.toggle(showElement); } else { console.log("unchecked - toggle: " + !showElement); $element.toggle(!showElement); } } $input.change(toggleOnChange); }; })(window, $);
(function(window, $){ window.toggleDisplayWithCheckedInput = function(args){ var $input = args.$input, $element = args.$element, showElement = args.mode === 'show'; var toggleOnChange = function(){ if($input.prop("checked")) { $element.toggle(showElement); } else { $element.toggle(!showElement); } } $input.change(toggleOnChange); }; })(window, $);
Remove console.log debug from toggleDisplayWithCheckedInput JS
Remove console.log debug from toggleDisplayWithCheckedInput JS
JavaScript
mit
alphagov/manuals-publisher,alphagov/manuals-publisher,alphagov/manuals-publisher
--- +++ @@ -5,14 +5,9 @@ showElement = args.mode === 'show'; var toggleOnChange = function(){ - console.log($input); - console.log("args.$mode =" + args.$mode); if($input.prop("checked")) { - console.log("checked - toggle: " + showElement); $element.toggle(showElement); - } - else { - console.log("unchecked - toggle: " + !showElement); + } else { $element.toggle(!showElement); } }
f0ccc846a8e1849e3fb37fbdded2de74ce76e1ae
app/components/add-expense.js
app/components/add-expense.js
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Component.extend({ attributeBindings: ['dialog-open'], didInsertElement () { var dialog = document.getElementById(this.$().attr('id')); var showDialogButton = $('[dialog-open]'); console.log(dialog, showDialogButton); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showDialogButton.click(function () { dialog.showModal(); }); // dialog.querySelector('.close').addEventListener('click', function () { // dialog.close(); // }); $(dialog).on('click', function () { dialog.close(); }); componentHandler.upgradeAllRegistered() } });
import Ember from 'ember'; import $ from 'jquery'; export default Ember.Component.extend({ attributeBindings: ['dialog-open'], expenseCategories: [ 'Charity', 'Clothing', 'Education', 'Events', 'Food', 'Gifts', 'Healthcare', 'Household', 'Leisure', 'Hobbies', 'Trasportation', 'Utilities', 'Vacation' ], didInsertElement () { var dialog = document.getElementById(this.$().attr('id')); var showDialogButton = $('[dialog-open]'); console.log(dialog, showDialogButton); if (!dialog.showModal) { dialogPolyfill.registerDialog(dialog); } showDialogButton.click(function () { dialog.showModal(); }); // dialog.querySelector('.close').addEventListener('click', function () { // dialog.close(); // }); $(dialog).on('click', function () { dialog.close(); }); componentHandler.upgradeAllRegistered() } });
Set expense categories in component
feat: Set expense categories in component
JavaScript
mit
pe1te3son/spendings-tracker,pe1te3son/spendings-tracker
--- +++ @@ -3,6 +3,21 @@ export default Ember.Component.extend({ attributeBindings: ['dialog-open'], + expenseCategories: [ + 'Charity', + 'Clothing', + 'Education', + 'Events', + 'Food', + 'Gifts', + 'Healthcare', + 'Household', + 'Leisure', + 'Hobbies', + 'Trasportation', + 'Utilities', + 'Vacation' + ], didInsertElement () { var dialog = document.getElementById(this.$().attr('id')); var showDialogButton = $('[dialog-open]');
7b6debe0ab1c1b4beb349ec963cb7ff026a8e48a
server/model/Post/schema.js
server/model/Post/schema.js
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${createSlug(value)}-${format(Date.now(), "YYYY-MM-dd")}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
import {DataTypes as t} from "sequelize" import format from "date-fns/format" import createSlug from "lib/helper/util/createSlug" /** * @const schema * * @type {import("sequelize").ModelAttributes} */ const schema = { id: { type: t.INTEGER.UNSIGNED, primaryKey: true, autoIncrement: true }, userId: { type: t.INTEGER.UNSIGNED, allowNull: false }, title: { type: t.STRING, allowNull: false, /** * @param {string} value */ set(value) { this.setDataValue("title", value) this.setDataValue( "slug", `${format(Date.now(), "YYYY-MM-dd")}/${createSlug(value)}}` ) } }, slug: { type: t.STRING, allowNull: false, unique: true }, text: { type: t.TEXT({length: "medium"}), allowNull: false }, isDraft: { type: t.BOOLEAN, allowNull: false, defaultValue: true } } export default schema
Change slug format in Post model
Change slug format in Post model
JavaScript
mit
octet-stream/eri,octet-stream/eri
--- +++ @@ -31,7 +31,7 @@ this.setDataValue( "slug", - `${createSlug(value)}-${format(Date.now(), "YYYY-MM-dd")}` + `${format(Date.now(), "YYYY-MM-dd")}/${createSlug(value)}}` ) } },
cd8a3d11287f247fe3898593f80bf1bdf3840d4f
app/js/services/apihandler.js
app/js/services/apihandler.js
'use strict'; /* * Abstration layer for various RESTful api calls */ var apihandler = angular.module('apihandler', []); apihandler.factory('apiFactory', function ($http, configFactory) { // Private API var url = configFactory.getValue('apiUrl') // Public API return {}; });
'use strict'; /* * Abstration layer for various RESTful API calls */ var apihandler = angular.module('apihandler', []); apihandler.factory('apiFactory', function ($http, configFactory) { // Private API var url = configFactory.getValue('apiUrl'); // Various different kinds of errors that can be returned from the REST API var errorTypes = { VERIFICATION : { USER_EXISTS : 'user_exists', NUMBER_MISSING : 'number_missing' }, REGISTER : { NO_VERIFICATION : 'no_verification', VERIFICATION_EXPIRED : 'verification_expired', VERIFICATION_USED : 'verification_used', REGISTER_FAILED : 'register_failed', }, LOGIN : { USER_NOT_FOUND : 'user_not_found', BCRYPT_ERROR : 'bcrypt_error', WRONG_PASSWORD : 'wrong_password' } }; // Public API return {}; });
Add error types from REST Api
Add error types from REST Api
JavaScript
mit
learning-layers/sardroid,learning-layers/sardroid,learning-layers/sardroid
--- +++ @@ -1,14 +1,33 @@ 'use strict'; /* - * Abstration layer for various RESTful api calls + * Abstration layer for various RESTful API calls */ var apihandler = angular.module('apihandler', []); apihandler.factory('apiFactory', function ($http, configFactory) { // Private API - var url = configFactory.getValue('apiUrl') + var url = configFactory.getValue('apiUrl'); + + // Various different kinds of errors that can be returned from the REST API + var errorTypes = { + VERIFICATION : { + USER_EXISTS : 'user_exists', + NUMBER_MISSING : 'number_missing' + }, + REGISTER : { + NO_VERIFICATION : 'no_verification', + VERIFICATION_EXPIRED : 'verification_expired', + VERIFICATION_USED : 'verification_used', + REGISTER_FAILED : 'register_failed', + }, + LOGIN : { + USER_NOT_FOUND : 'user_not_found', + BCRYPT_ERROR : 'bcrypt_error', + WRONG_PASSWORD : 'wrong_password' + } + }; // Public API return {};