commit
stringlengths
40
40
subject
stringlengths
1
3.25k
old_file
stringlengths
4
311
new_file
stringlengths
4
311
old_contents
stringlengths
0
26.3k
lang
stringclasses
3 values
proba
float64
0
1
diff
stringlengths
0
7.82k
9f1eb689fbdc4b90895d479b10fc8cfd4a2f4665
replace true false values with icons in README (#15)
generate-json.js
generate-json.js
const fs = require('fs'); const awsRegionTableParser = require('./index.js'); const chartGenerator = require('./chart-generator.js'); const sortArrayByProp = (array, prop, asc = true) => { return array.sort((a, b) => { return asc ? a[prop] - b[prop] : b[prop] - a[prop]; }); }; async function generateRegionSummary(parseddata) { const regionSummary = sortArrayByProp(Object.values(parseddata.regionSummary), 'value', false); const chartConfig = { "type": "bar", "data": { "labels": [], "datasets": [ { "label": "Regions", "backgroundColor": ["#7f0000", "#330000", "#ff2200", "#d97b6c", "#d9b1a3", "#a64200", "#331400", "#66381a", "#99754d", "#cc8800", "#33260d", "#ffeabf", "#5f6600", "#a3bf30", "#20331a", "#c8ffbf", "#40ff59", "#1d733f", "#66ccb8", "#39736f", "#80e6ff", "#002233", "#267399", "#80b3ff", "#0044ff", "#405180", "#241966", "#8273e6", "#ad00d9", "#daace6", "#ff80f6", "#661a4d", "#ff80b3", "#ff0044", "#a6294b", "#73565e"], "data": [] } ] }, "options": { "legend": { "display": false }, "title": { "display": true, "text": "No. of supported services per region." } } }; let markdownTable = `### Region Summary # \n`; markdownTable += `| Region Code | Region Name | no. of Supported Services | \n`; markdownTable += `| ------ | -------- | -------- | \n`; regionSummary.forEach(region => { markdownTable += `${region.regionCode} | ${region.regionName} | ${region.value}\n`; chartConfig.data.labels.push(`${region.regionCode}`); chartConfig.data.datasets[0].data.push(region.value); }); markdownTable += `\n\n`; return await chartGenerator.getChartUrl(chartConfig).then((chartUrl) => { markdownTable += `<img src='${chartUrl}'>\n\n`; return markdownTable; }); } awsRegionTableParser.get().then(async function (servicesAndRegions) { fs.writeFileSync('./data/parseddata.json', JSON.stringify(servicesAndRegions, null, 2), 'utf8'); // TODO: clean this up const services = Object.values(servicesAndRegions.services); const edgeLocations = servicesAndRegions.edgeLocations; const regionalEdgeCaches = servicesAndRegions.regionalEdgeCaches; const regions = services[0]; let READMEheader = `### ${edgeLocations.length} Edge Locations\n`; READMEheader += `### ${regionalEdgeCaches.length} Regional Edge Caches\n`; READMEheader += `### ${services.length} Services\n\n`; READMEheader += await generateRegionSummary(servicesAndRegions); READMEheader += `# Region and Service Table # \n` READMEheader += `| | ${Object.keys(regions).join(' | ')} |\n`; READMEheader += `| ------------- | ${Object.keys(regions).fill('-------------').join(' | ')}|`; const READMErows = []; for (var value in servicesAndRegions.services) { const longServiceName = servicesAndRegions.serviceNames[value]; const row = `${longServiceName}|${Object.values(servicesAndRegions.services[value]).join(' | ')}`; READMErows.push(row); } const READMEtext = `${READMEheader}\n${READMErows.join('\n')}`; fs.writeFileSync('./data/README.md', READMEtext, 'utf8'); });
JavaScript
0
@@ -317,16 +317,24 @@ nSummary +Markdown (parsedd @@ -2516,16 +2516,24 @@ nSummary +Markdown (service @@ -2994,16 +2994,67 @@ value%5D). +map(value =%3E value ? ':white_check_mark:' : ':x:'). join(' %7C
3b3bfe35367cd6a48aa30a99aedb1fa7cded186c
add route for signupChild function
modules/users/server/routes/auth.server.routes.js
modules/users/server/routes/auth.server.routes.js
'use strict'; /** * Module dependencies. */ var passport = require('passport'); module.exports = function(app) { // User Routes var users = require('../controllers/users.server.controller'); // Setting up the users password api app.route('/api/auth/forgot').post(users.forgot); app.route('/api/auth/reset/:token').get(users.validateResetToken); app.route('/api/auth/reset/:token').post(users.reset); // Setting up the users authentication api app.route('/api/auth/signup').post(users.signup); app.route('/api/auth/signin').post(users.signin); app.route('/api/auth/signout').get(users.signout); // Setting the facebook oauth routes app.route('/api/auth/facebook').get(passport.authenticate('facebook', { scope: ['email'] })); app.route('/api/auth/facebook/callback').get(users.oauthCallback('facebook')); // Setting the twitter oauth routes app.route('/api/auth/twitter').get(passport.authenticate('twitter')); app.route('/api/auth/twitter/callback').get(users.oauthCallback('twitter')); // Setting the google oauth routes app.route('/api/auth/google').get(passport.authenticate('google', { scope: [ 'https://www.googleapis.com/auth/userinfo.profile', 'https://www.googleapis.com/auth/userinfo.email' ] })); app.route('/api/auth/google/callback').get(users.oauthCallback('google')); // Setting the linkedin oauth routes app.route('/api/auth/linkedin').get(passport.authenticate('linkedin', { scope: [ 'r_basicprofile', 'r_emailaddress' ] })); app.route('/api/auth/linkedin/callback').get(users.oauthCallback('linkedin')); // Setting the github oauth routes app.route('/api/auth/github').get(passport.authenticate('github')); app.route('/api/auth/github/callback').get(users.oauthCallback('github')); };
JavaScript
0.000001
@@ -500,16 +500,77 @@ ignup);%0A +%09app.route('/api/auth/signupchild').post(users.signupChild);%0A %09app.rou
aa1a32685ce67dd4b935c3cf878e22e5f273c83d
support for current latency
requests-sorted-by-latency-saved.js
requests-sorted-by-latency-saved.js
const assert = require('assert') const debug = require('debug')('requestsSortedByLatencySaved') const _ = require('lodash') module.exports = function requestsSortedByLatencySaved (problem) { return _.orderBy(_.reduce(problem.requests, (links, request) => { const endpoint = problem.endpoints[request.endpoint] return links.concat(_(endpoint.cacheServers.map(cache => ({ video: request.video, endpoint: endpoint.index, cache: cache.id, latency: request.popularity * cache.latency, savedLatency: request.popularity * endpoint.datacenterLatency - request.popularity * cache.latency })).filter(link => link.savedLatency > 0)).value()) }, []), ['savedLatency'], ['desc']) }
JavaScript
0
@@ -185,12 +185,23 @@ blem +, latencies ) %7B%0A - re @@ -321,16 +321,114 @@ dpoint%5D%0A + const latency = _.get(latencies, %5Bendpoint.index, request.video%5D, endpoint.datacenterLatency)%0A retu @@ -662,57 +662,18 @@ y * -endpoint.datacenterLatency - request.popularity * +(latency - cac @@ -682,16 +682,17 @@ .latency +) %0A %7D))
719966026fd573c364740a7c030917758ffa765b
Fix double scroll issue (#16108)
packages/material-ui/src/DialogActions/DialogActions.js
packages/material-ui/src/DialogActions/DialogActions.js
import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; import '../Button'; // So we don't have any override priority issue. export const styles = { /* Styles applied to the root element. */ root: { display: 'flex', alignItems: 'center', padding: 8, justifyContent: 'flex-end', }, /* Styles applied to the root element if `disableSpacing={false}`. */ spacing: { '& > * + *': { marginLeft: 8, }, }, }; const DialogActions = React.forwardRef(function DialogActions(props, ref) { const { disableSpacing = false, classes, className, ...other } = props; return ( <div className={clsx(classes.root, { [classes.spacing]: !disableSpacing }, className)} ref={ref} {...other} /> ); }); DialogActions.propTypes = { /** * The content of the component. */ children: PropTypes.node, /** * Override or extend the styles applied to the component. * See [CSS API](#css) below for more details. */ classes: PropTypes.object.isRequired, /** * @ignore */ className: PropTypes.string, /** * If `true`, the actions do not have additional margin. */ disableSpacing: PropTypes.bool, }; export default withStyles(styles, { name: 'MuiDialogActions' })(DialogActions);
JavaScript
0
@@ -371,16 +371,38 @@ x-end',%0A + flex: '0 0 auto',%0A %7D,%0A /
f191cf104387dc8e5060af24a5e7a7b05b88fa8d
Update studio-edit.js
main/local_modules/frontend_studio/static/js/studio-edit.js
main/local_modules/frontend_studio/static/js/studio-edit.js
// ref : https://output.jsbin.com/quvelo/2/#tab3 $(window).load(function () { // cache the id var navbox = $('.nav-tabs'); // activate tab on click navbox.on('click', 'a', function (e) { var $this = $(this); // prevent the Default behavior e.preventDefault(); // send the hash to the address bar window.location.hash = $this.attr('href'); // activate the clicked tab $this.tab('show'); }); // will show tab based on hash function refreshHash() { navbox.find('a[href="' + window.location.hash + '"]').tab('show'); } // show tab if hash changes in address bar $(window).bind('hashchange', refreshHash); // read has from address bar and show it if (window.location.hash) { // show tab on load refreshHash(); } });
JavaScript
0.000001
@@ -44,16 +44,132 @@ #tab3 %0D%0A +// fonction de re-formatage de l'adresse URL pour pouvoir acc%C3%A9der aux tabs depuis un lien et une page externe.%0D%0A%0D%0A%0D%0A %0D%0A$(wind @@ -916,8 +916,10 @@ %0D%0A%0D%0A %7D); +%0D%0A
795afba02dcec11c92cbc646c770cf86f9bc504b
fix merge
lib/components/WeatherCards.js
lib/components/WeatherCards.js
import React from 'react'; const WeatherCards = ({ weatherText, weatherSimple, city }) => { if(!weatherText.forecastday) { return ( <div> please whatevers </div> ) } return ( <<<<<<< HEAD ======= >>>>>>> b90c5e7665a56cf78ccfdaa9ad76d936aad13326 <div> <p>Conditions Today in {city}: { weatherSimple.forecastday[0].conditions }</p> <p>Day Today: { weatherSimple.forecastday[0].date.weekday_short }</p> <p>Month: { weatherSimple.forecastday[0].date.monthname_short }</p> <p>The: { weatherSimple.forecastday[0].date.day }</p> <p>Year: { weatherSimple.forecastday[0].date.year }</p> <p>Today's High: { weatherSimple.forecastday[0].high.fahrenheit + '°' }</p> <p>Today's Low: { weatherSimple.forecastday[0].low.fahrenheit + '°' }</p> <p> { weatherText.forecastday[0].title } Summary: { weatherText.forecastday[0].fcttext }</p> </div> ) } export default WeatherCards;
JavaScript
0.000001
@@ -208,83 +208,8 @@ n (%0A -%3C%3C%3C%3C%3C%3C%3C HEAD%0A%0A %0A=======%0A%3E%3E%3E%3E%3E%3E%3E b90c5e7665a56cf78ccfdaa9ad76d936aad13326 %0A
b26718580fdb4d6daddf5252965bd41b136697c7
Fix text wrap test
expanding.js
expanding.js
// Expanding Textareas v0.1.0 // MIT License // https://github.com/bgrins/ExpandingTextareas (function(factory) { // Add jQuery via AMD registration or browser globals if (typeof define === 'function' && define.amd) { define([ 'jquery' ], factory); } else { factory(jQuery); } }(function ($) { var Expanding = function($textarea, opts) { Expanding._registry.push(this); this.$textarea = $textarea; this.$textCopy = $("<span />"); this.$clone = $("<pre class='expanding-clone'><br /></pre>").prepend(this.$textCopy); this._resetStyles(); this._setCloneStyles(); this._setTextareaStyles(); $textarea .wrap($("<div class='expanding-wrapper' style='position:relative' />")) .after(this.$clone); this.attach(); this.update(); if (opts.update) $textarea.bind("update.expanding", opts.update); }; // Stores (active) `Expanding` instances // Destroyed instances are removed Expanding._registry = []; // Returns the `Expanding` instance given a DOM node Expanding.getExpandingInstance = function(textarea) { var $textareas = $.map(Expanding._registry, function(instance) { return instance.$textarea[0]; }), index = $.inArray(textarea, $textareas); return index > -1 ? Expanding._registry[index] : null; }; // Returns the version of Internet Explorer or -1 // (indicating the use of another browser). // From: http://msdn.microsoft.com/en-us/library/ms537509(v=vs.85).aspx#ParsingUA var ieVersion = (function() { var v = -1; if (navigator.appName === "Microsoft Internet Explorer") { var ua = navigator.userAgent; var re = new RegExp("MSIE ([0-9]{1,}[\\.0-9]{0,})"); if (re.exec(ua) !== null) v = parseFloat(RegExp.$1); } return v; })(); // Check for oninput support // IE9 supports oninput, but not when deleting text, so keyup is used. // onpropertychange _is_ supported by IE8/9, but may not be fired unless // attached with `attachEvent` // (see: http://stackoverflow.com/questions/18436424/ie-onpropertychange-event-doesnt-fire), // and so is avoided altogether. var inputSupported = "oninput" in document.createElement("input") && ieVersion !== 9; Expanding.prototype = { // Attaches input events // Only attaches `keyup` events if `input` is not fully suported attach: function() { var events = 'input.expanding change.expanding', _this = this; if(!inputSupported) events += ' keyup.expanding'; this.$textarea.bind(events, function() { _this.update(); }); }, // Updates the clone with the textarea value update: function() { this.$textCopy.text(this.$textarea.val().replace(/\r\n/g, "\n")); // Use `triggerHandler` to prevent conflicts with `update` in Prototype.js this.$textarea.triggerHandler("update.expanding"); }, // Tears down the plugin: removes generated elements, applies styles // that were prevously present, removes instance from registry, // unbinds events destroy: function() { this.$clone.remove(); this.$textarea .unwrap() .attr('style', this._oldTextareaStyles || ''); delete this._oldTextareaStyles; var index = $.inArray(this, Expanding._registry); if (index > -1) Expanding._registry.splice(index, 1); this.$textarea.unbind( 'input.expanding change.expanding keyup.expanding update.expanding'); }, // Applies reset styles to the textarea and clone // Stores the original textarea styles in case of destroying _resetStyles: function() { this._oldTextareaStyles = this.$textarea.attr('style'); this.$textarea.add(this.$clone).css({ margin: 0, webkitBoxSizing: "border-box", mozBoxSizing: "border-box", boxSizing: "border-box", width: "100%" }); }, // Sets the basic clone styles and copies styles over from the textarea _setCloneStyles: function() { var css = { display: 'block', border: '0 solid', visibility: 'hidden', minHeight: this.$textarea.outerHeight() }; if(this.$textarea.attr("wrap") === "off") css.overflowX = "scroll"; else css.whiteSpace = "pre-wrap"; this.$clone.css(css); this._copyTextareaStylesToClone(); }, _copyTextareaStylesToClone: function() { var _this = this, properties = [ 'lineHeight', 'textDecoration', 'letterSpacing', 'fontSize', 'fontFamily', 'fontStyle', 'fontWeight', 'textTransform', 'textAlign', 'direction', 'wordSpacing', 'fontSizeAdjust', 'wordWrap', 'word-break', 'borderLeftWidth', 'borderRightWidth', 'borderTopWidth','borderBottomWidth', 'paddingLeft', 'paddingRight', 'paddingTop','paddingBottom', 'maxHeight']; $.each(properties, function(i, property) { var val = _this.$textarea.css(property); // Prevent overriding percentage css values. if(_this.$clone.css(property) !== val) { _this.$clone.css(property, val); if(property == 'maxHeight' && val) { _this.$clone.css('overflow', 'hidden'); } } }); }, _setTextareaStyles: function() { this.$textarea.css({ position: "absolute", top: 0, left: 0, height: "100%", resize: "none", overflow: "auto" }); } }; $.expanding = $.extend({ autoInitialize: true, initialSelector: "textarea.expanding", opts: { update: function() { } } }, $.expanding || {}); $.fn.expanding = function(o) { if (o === "destroy") { this.each(function() { var instance = Expanding.getExpandingInstance(this); if (instance) instance.destroy(); }); return this; } // Checks to see if any of the given DOM nodes have the // expanding behaviour. if (o === "active") { return !!this.filter(function() { return !!Expanding.getExpandingInstance(this); }).length; } var opts = $.extend({ }, $.expanding.opts, o); this.filter("textarea").each(function() { var visible = this.offsetWidth > 0 || this.offsetHeight > 0, initialized = Expanding.getExpandingInstance(this); if(visible && !initialized) new Expanding($(this), opts); else { if(!visible) _warn("ExpandingTextareas: attempt to initialize an invisible textarea. Call expanding() again once it has been inserted into the page and/or is visible."); if(initialized) _warn("ExpandingTextareas: attempt to initialize a textarea that has already been initialized. Subsequent calls are ignored."); } }); return this; }; function _warn(text) { if(window.console && console.warn) console.warn(text); } $(function () { if ($.expanding.autoInitialize) { $($.expanding.initialSelector).expanding(); } }); }));
JavaScript
0.013758
@@ -5147,16 +5147,17 @@ perty == += 'maxHei @@ -5163,24 +5163,35 @@ ight' && val + !== 'none' ) %7B%0A
fd12786736618e7b9e83ef1adbf8865b11b42813
Add fusionMerge() utility
src/utilities/functional/merge.js
src/utilities/functional/merge.js
'use strict'; const { throwError } = require('../error'); // Deep merge objects and arrays (concatenates for arrays) const deepMerge = function (objA, ...objects) { if (objects.length === 0) { return objA; } if (objects.length === 1) { return simpleMerge({ objA, objects }); } return recursiveMerge({ objA, objects }); }; const simpleMerge = function ({ objA, objects }) { const [objB] = objects; validateInputType({ objA, objB }); validateInputSameTypes({ objA, objB }); if (Array.isArray(objA)) { return [...objA, ...objB]; } if (objA.constructor === Object) { return mergeObjects({ objA, objB }); } }; const validateInputType = function ({ objA, objB }) { const isInvalidType = (objA.constructor !== Object && !Array.isArray(objA)) || (objB.constructor !== Object && !Array.isArray(objB)); if (!isInvalidType) { return; } const message = `'deepMerge' utility cannot merge together objects with arrays: ${objA} and ${objB}`; throwError(message); }; const validateInputSameTypes = function ({ objA, objB }) { const isDifferentTypes = (objA.constructor === Object && objB.constructor !== Object) || (objA.constructor !== Object && objB.constructor === Object); if (!isDifferentTypes) { return; } const message = `'deepMerge' utility can only merge together objects or arrays: ${objA} and ${objB}`; throwError(message); }; const mergeObjects = function ({ objA, objB }) { return Object.entries(objB).reduce( (newObjA, [objBKey, objBVal]) => mergeObjectProp({ objA: newObjA, objBKey, objBVal }), objA, ); }; const mergeObjectProp = function ({ objA, objBKey, objBVal }) { const objAVal = objA[objBKey]; const shouldDeepMerge = objAVal && objBVal && ((Array.isArray(objAVal) && Array.isArray(objBVal)) || (objAVal.constructor === Object && objBVal.constructor === Object)); const newVal = shouldDeepMerge ? deepMerge(objAVal, objBVal) : objBVal; return { ...objA, [objBKey]: newVal }; }; const recursiveMerge = function ({ objA, objects }) { const newObjA = deepMerge(objA, objects[0]); const newObjects = objects.slice(1); return deepMerge(newObjA, ...newObjects); }; module.exports = { deepMerge, };
JavaScript
0.000001
@@ -57,78 +57,15 @@ );%0A%0A -// Deep merge objects and arrays (concatenates for arrays)%0A const -deepM +m erge @@ -77,16 +77,22 @@ nction ( +type, objA, .. @@ -213,24 +213,30 @@ bjA, objects +, type %7D);%0A %7D%0A%0A @@ -272,16 +272,22 @@ objects +, type %7D);%0A%7D;%0A @@ -324,32 +324,38 @@ (%7B objA, objects +, type %7D) %7B%0A const %5Bo @@ -480,41 +480,98 @@ bjA) -) %7B%0A return %5B...objA, ... + && Array.isArray(objB)) %7B%0A return mergeMap%5Btype%5D.array(%7B arrayA: objA, arrayB: objB -%5D + %7D) ;%0A @@ -642,24 +642,30 @@ %7B objA, objB +, type %7D);%0A %7D%0A%7D;%0A @@ -1453,32 +1453,38 @@ on (%7B objA, objB +, type %7D) %7B%0A return O @@ -1603,16 +1603,22 @@ objBVal +, type %7D),%0A @@ -1691,16 +1691,22 @@ objBVal +, type %7D) %7B%0A @@ -1956,20 +1956,33 @@ erge - ? deepMerge +%0A ? mergeMap%5Btype%5D.top (obj @@ -1995,16 +1995,20 @@ objBVal) +%0A : objBV @@ -2052,24 +2052,351 @@ wVal %7D;%0A%7D;%0A%0A +const concatArrays = function (%7B arrayA, arrayB %7D) %7B%0A return %5B...arrayA, ...arrayB%5D;%0A%7D;%0A%0Aconst mergeArrays = function (%7B arrayA, arrayB %7D) %7B%0A const bigArray = arrayA.length %3E= arrayB.length ? arrayA : arrayB;%0A return bigArray.map((value, index) =%3E%0A (arrayA%5Bindex%5D === undefined ? arrayB%5Bindex%5D : arrayA%5Bindex%5D),%0A );%0A%7D;%0A%0A const recurs @@ -2431,16 +2431,22 @@ objects +, type %7D) %7B%0A @@ -2461,25 +2461,34 @@ wObjA = -deepMerge +mergeMap%5Btype%5D.top (objA, o @@ -2547,25 +2547,34 @@ return -deepMerge +mergeMap%5Btype%5D.top (newObjA @@ -2595,16 +2595,367 @@ s);%0A%7D;%0A%0A +// Deep merge objects and arrays (concatenates for arrays)%0Aconst deepMerge = merge.bind(null, 'deep');%0A%0A// Deep merge objects and arrays (merge for arrays)%0Aconst fusionMerge = merge.bind(null, 'fusion');%0A%0Aconst mergeMap = %7B%0A deep: %7B%0A top: deepMerge,%0A array: concatArrays,%0A %7D,%0A fusion: %7B%0A top: fusionMerge,%0A array: mergeArrays,%0A %7D,%0A%7D;%0A%0A module.e @@ -2978,11 +2978,26 @@ pMerge,%0A + fusionMerge,%0A %7D;%0A
de797c406d3b5dc1f51000296e973c9ee11f10ee
Rename mantissa to fractionalPart in the LOD vertice shader
experiments/projected_grid_vs_lod/js/shaders/LODShader.js
experiments/projected_grid_vs_lod/js/shaders/LODShader.js
/** * @author jbouny / https://github.com/fft-ocean */ THREE.ShaderChunk["lod_pars_vertex"] = [ 'uniform float u_scale;', 'uniform int u_resolution;', 'uniform int u_level;', 'uniform vec3 u_planeUp;', 'uniform vec3 u_planeAt;', 'uniform vec3 u_planePoint;', 'uniform bool u_usePlaneParameters;', 'vec2 computeAncestorMorphing(int level, vec2 gridPosition, float heightMorphFactor, vec3 cameraScaledPosition, float resolution, vec2 previousMorphing )', '{', // Check if it is needed to apply the morphing (on 1 square on 2) ' vec2 mantissa = gridPosition * resolution * 0.5;', ' if( level > 1 ) {', ' mantissa = ( mantissa + 0.5 ) / pow( 2.0, float( level - 1 ) );', ' }', ' mantissa -= floor( mantissa );', // Compute morphing factors (based on the height and the parent LOD ' vec2 squareOffset = abs( cameraScaledPosition.xz - ( gridPosition + previousMorphing ) ) / float( level );', ' vec2 comparePos = max( vec2( 0.0 ), squareOffset * 4.0 - 1.0 );', ' float parentMorphFactor = min( 1.0, max( comparePos.x, comparePos.y ) );', // Compute the composition of morphing factors ' vec2 morphFactor = vec2( 0.0 );', ' if( mantissa.x + mantissa.y > 0.49 ) {', ' float morphing = parentMorphFactor;', // If first LOD, apply the height morphing factor everywhere ' if( u_level + level == 1 ) {', ' morphing = max( heightMorphFactor, morphing );', ' }', ' morphFactor += morphing * floor( mantissa * 2.0 );', ' }', ' return float( level ) * morphFactor / resolution;', '}', 'vec4 computePosition( vec4 position )', '{', // Extract the 3x3 rotation matrix and the translation vector from the 4x4 view matrix, then compute the camera position // Xc = R * Xw + t // c = - R.t() * t <=> c = - t.t() * R ' vec3 cameraPosition = - viewMatrix[3].xyz * mat3( viewMatrix );', ' float resolution = float( u_resolution );', ' vec3 planeY = normalize( u_planeUp );', // Compute the plane rotation (if needed) ' mat3 planeRotation;', ' if( u_usePlaneParameters ) {', ' vec3 planeZ = normalize( u_planeAt );', ' vec3 planeX = normalize( cross( planeY, planeZ ) );', ' planeZ = normalize( cross( planeY, planeX ) );', ' planeRotation = mat3( planeX, planeY, planeZ );', ' }', // Project the camera position and the scene origin on the grid using plane parameters ' vec3 projectedCamera = vec3( cameraPosition.x, 0.0, cameraPosition.z );', ' vec3 projectedOrigin = vec3( 0 );', ' if( u_usePlaneParameters ) {', ' projectedCamera = cameraPosition - dot( cameraPosition - u_planePoint, planeY ) * planeY;', ' projectedOrigin = - dot( - u_planePoint, planeY ) * planeY;', ' }', // Discretise the space and made the grid following the camera ' float cameraHeightLog = log2( length( cameraPosition - projectedCamera ) );', ' float scale = u_scale * pow( 2.0, floor( cameraHeightLog ) ) * 0.005;', ' vec3 cameraScaledPosition = projectedCamera / scale;', ' if( u_usePlaneParameters ) {', ' cameraScaledPosition = cameraScaledPosition * planeRotation;', ' }', ' vec2 gridPosition = position.xz + floor( cameraScaledPosition.xz * resolution + 0.5 ) / resolution;', // Compute the height morphing factor ' float heightMorphFactor = cameraHeightLog - floor( cameraHeightLog );', // Compute morphing factors from LOD ancestors ' vec2 morphing = vec2( 0 );', ' for( int i = 1; i <= 2; ++i ) {', ' morphing += computeAncestorMorphing( i, gridPosition, heightMorphFactor, cameraScaledPosition, resolution, morphing );', ' }', // Apply final morphing ' gridPosition = gridPosition + morphing;', // Compute world coordinates (if needed) ' vec3 worldPosition = vec3( gridPosition.x * scale, 0, gridPosition.y * scale );', ' if( u_usePlaneParameters ) {', ' worldPosition = planeRotation * worldPosition + projectedOrigin;', ' }', // Return the final position ' return vec4( worldPosition, 1.0 );', '}' ].join('\n'); THREE.ShaderChunk["lod_vertex"] = [ 'worldPosition = computePosition( worldPosition );', ].join('\n');
JavaScript
0.000011
@@ -570,24 +570,31 @@ ' vec2 -mantissa +fractionnalPart = gridP @@ -661,29 +661,43 @@ ' -mantissa = ( mantissa +fractionnalPart = ( fractionnalPart + 0 @@ -757,35 +757,49 @@ ' -mantissa -= floor( mantissa +fractionnalPart -= floor( fractionnalPart );' @@ -1259,29 +1259,43 @@ if( -mantissa.x + mantissa +fractionnalPart.x + fractionnalPart .y %3E @@ -1576,16 +1576,23 @@ or( -mantissa +fractionnalPart * 2
77f0d7b40427654157e3748dfa8c2bd247344e3c
implement fire() in timerAid
resource/modules/utils/timerAid.jsm
resource/modules/utils/timerAid.jsm
moduleAid.VERSION = '2.0.0'; moduleAid.LAZY = true; // timerAid - Object to aid in setting, initializing and cancelling timers // init(aName, aFunc, aDelay, aType) - initializes a named timer to be kept in the timers object // aName - (string) to name the timer // aFunc - (function) to be fired by the timer, it will be bound to self // aDelay - (int) msec to set the timer // (optional) aType - // (string) 'slack' fires every aDelay msec and waits for the last aFunc call to finish before restarting the timer, // (string) 'precise' fires every aDelay msec, // (string) 'precise_skip' not really sure what this one does, // (string) 'once' fires only once, // defaults to once this.timerAid = { timers: {}, init: function(aName, aFunc, aDelay, aType) { this.cancel(aName); var type = this._switchType(aType); this.timers[aName] = { timer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer), handler: aFunc }; this.timers[aName].timer.init(function(aSubject, aTopic, aData) { timerAid.timers[aName].handler.call(self, aSubject, aTopic, aData); if(typeof(timerAid) != 'undefined' && aSubject.type == Ci.nsITimer.TYPE_ONE_SHOT) { timerAid.cancel(aName); } }, aDelay, type); this.__defineGetter__(aName, function() { return this.timers[aName]; }); return this.timers[aName]; }, cancel: function(name) { if(this.timers[name]) { this.timers[name].timer.cancel(); delete this.timers[name]; delete this[name]; return true; } return false; }, clean: function() { for(var timerObj in this.timers) { this.cancel(timerObj); } }, create: function(aFunc, aDelay, aType) { var type = this._switchType(aType); var newTimer = { timer: Cc["@mozilla.org/timer;1"].createInstance(Ci.nsITimer), handler: aFunc.bind(self), cancel: function() { this.timer.cancel(); } }; newTimer.timer.init(newTimer.handler, aDelay, type); return newTimer; }, _switchType: function(type) { switch(type) { case 'slack': return Ci.nsITimer.TYPE_REPEATING_SLACK; break; case 'precise': return Ci.nsITimer.TYPE_REPEATING_PRECISE; break; case 'precise_skip': return Ci.nsITimer.TYPE_REPEATING_PRECISE_CAN_SKIP; break; case 'once': default: return Ci.nsITimer.TYPE_ONE_SHOT; break; } return false; } }; moduleAid.UNLOADMODULE = function() { timerAid.clean(); };
JavaScript
0.000032
@@ -18,17 +18,17 @@ = '2.0. -0 +1 ';%0Amodul @@ -1510,16 +1510,208 @@ ;%0A%09%7D,%0A%09%0A +%09fire: function(name) %7B%0A%09%09if(this.timers%5Bname%5D) %7B%0A%09%09%09aSync(this.timers%5Bname%5D.handler);%0A%09%09%09if(this.timers%5Bname%5D.timer.type == Ci.nsITimer.TYPE_ONE_SHOT) %7B%0A%09%09%09%09this.cancel(name);%0A%09%09%09%7D%0A%09%09%7D%0A%09%7D,%0A%09%0A %09clean: @@ -1723,16 +1723,16 @@ ion() %7B%0A - %09%09for(va @@ -2197,16 +2197,58 @@ slack':%0A +%09%09%09case Ci.nsITimer.TYPE_REPEATING_SLACK:%0A %09%09%09%09retu @@ -2314,16 +2314,60 @@ ecise':%0A +%09%09%09case Ci.nsITimer.TYPE_REPEATING_PRECISE:%0A %09%09%09%09retu @@ -2440,16 +2440,69 @@ _skip':%0A +%09%09%09case Ci.nsITimer.TYPE_REPEATING_PRECISE_CAN_SKIP:%0A %09%09%09%09retu @@ -2552,32 +2552,32 @@ KIP;%0A%09%09%09%09break;%0A - %09%09%09case 'once':%0A @@ -2576,16 +2576,51 @@ 'once':%0A +%09%09%09case Ci.nsITimer.TYPE_ONE_SHOT:%0A %09%09%09defau
3d5ab47426953ab54f8242d382dc2b2848bb0d6d
fix (pinning): do not pass empty slots to getCachedMetadata
addon/Feeds/TopSitesFeed.js
addon/Feeds/TopSitesFeed.js
/* globals Task, NewTabUtils */ const {Cu} = require("chrome"); const {PlacesProvider} = require("addon/PlacesProvider"); const Feed = require("addon/lib/Feed"); const {TOP_SITES_SHOWMORE_LENGTH} = require("common/constants"); const am = require("common/action-manager"); const UPDATE_TIME = 15 * 60 * 1000; // 15 minutes const getScreenshot = require("addon/lib/getScreenshot"); const {isRootDomain} = require("addon/lib/utils"); Cu.import("resource://gre/modules/Task.jsm"); Cu.import("resource://gre/modules/NewTabUtils.jsm"); module.exports = class TopSitesFeed extends Feed { constructor(options) { super(options); this.getScreenshot = getScreenshot; this.missingData = false; this.pinnedLinks = options.pinnedLinks || NewTabUtils.pinnedLinks; } shouldGetScreenshot(link) { return !isRootDomain(link.url) || (link.hasMetadata && !link.hasHighResIcon); } pinLink(action) { this.pinnedLinks.pin(action.data.site, action.data.index); } unpinLink(action) { this.pinnedLinks.unpin(action.data.site); } sortLinks(links, pinned) { // Separate out the pinned from the rest let pinnedLinks = []; let sortedLinks = []; links.forEach(link => { if (this.pinnedLinks.isPinned(link)) { pinnedLinks.push(link); } else { sortedLinks.push(link); } }); // Insert the pinned links in their location pinned.forEach((val, index) => { if (!val) { return; } let site = Object.assign({}, pinnedLinks.find(link => link.url === val.url), {isPinned: true, pinIndex: index}); if (index > sortedLinks.length) { sortedLinks[index] = site; } else { sortedLinks.splice(index, 0, site); } }); return sortedLinks; } getData() { return Task.spawn(function*() { const experiments = this.store.getState().Experiments.values; // Get pinned links let pinned = this.pinnedLinks.links; // Get links from places and cache them let frecent = yield PlacesProvider.links.getTopFrecentSites(); // Filter out pinned links from frecent frecent = frecent.filter(link => !this.pinnedLinks.isPinned(link)); // Concat the pinned with the frecent let links = pinned.concat(frecent); // Get metadata from PreviewProvider links = yield this.options.getCachedMetadata(links, "TOP_FRECENT_SITES_RESPONSE"); this.missingData = false; // Get screenshots if the favicons are too small if (experiments.screenshotsLongCache) { for (let link of links) { if (this.shouldGetScreenshot(link)) { const screenshot = this.getScreenshot(link.url, this.store); if (screenshot) { link.screenshot = screenshot; link.metadata_source = `${link.metadata_source}+Screenshot`; } else { this.missingData = true; } } else if (!link.hasMetadata) { this.missingData = true; } } } // Place the pinned links where they go links = this.sortLinks(links, pinned); return am.actions.Response("TOP_FRECENT_SITES_RESPONSE", links); }.bind(this)); } onAction(state, action) { switch (action.type) { case am.type("APP_INIT"): // When the app first starts up, refresh the data. this.refresh("app was initializing"); break; case am.type("SCREENSHOT_UPDATED"): if (this.missingData) { this.refresh("new screenshot is available and we're missing data"); } break; case am.type("METADATA_UPDATED"): if (this.missingData) { this.refresh("new metadata is available and we're missing data"); } break; case am.type("RECEIVE_PLACES_CHANGES"): // When a user visits a site, if we don't have enough top sites yet, refresh the data. if (state.TopSites.rows.length < TOP_SITES_SHOWMORE_LENGTH) { this.refresh("there were not enough sites"); } else if (Date.now() - this.state.lastUpdated >= UPDATE_TIME) { // When a user visits a site, if the last time we refreshed the data // is greater than 15 minutes, refresh the data. this.refresh("the sites were too old"); } break; case am.type("MANY_LINKS_CHANGED"): // manyLinksChanged is an event fired by Places when all history is cleared, // or when frecency of links change due to something like a sync this.refresh("frecency of many links changed"); break; case am.type("NOTIFY_PIN_TOPSITE"): this.pinLink(action); this.refresh("a site was pinned"); break; case am.type("NOTIFY_UNPIN_TOPSITE"): this.unpinLink(action); this.refresh("a site was unpinned"); break; } } }; module.exports.UPDATE_TIME = UPDATE_TIME;
JavaScript
0
@@ -2243,16 +2243,39 @@ pinned. +filter(link =%3E !!link). concat(f
ff685f2c587eeaa7f26ea96e0c511b1d1fac74b5
Add api-ui in proxy
server/proxies/api.js
server/proxies/api.js
module.exports = function(app, options) { var path = require('path'); var ForeverAgent = require('forever-agent'); var HttpProxy = require('http-proxy'); var httpServer = options.httpServer; var config = require('../../config/environment')().APP; var target = config.apiServer; var proxy = HttpProxy.createProxyServer({ ws: true, xfwd: true, target: config.apiServer, secure: false, }); proxy.on('error', onProxyError); // WebSocket for Rancher httpServer.on('upgrade', function proxyWsRequest(req, socket, head) { if ( req.url.startsWith('/_lr/') ) { return; } if ( socket.ssl ) { req.headers['x-forwarded-proto'] = 'https'; } let targetHost = config.apiServer.replace(/^https?:\/\//, ''); let host = req.headers['host']; let port; if ( socket.ssl ) { req.headers['x-forwarded-proto'] = 'https'; port = 443; } else { req.headers['x-forwarded-proto'] = 'http'; port = 80; } if ( host ) { idx = host.lastIndexOf(':'); if ( ( host.startsWith('[') && host.includes(']:') || !host.startsWith('[') ) && idx > 0 ){ port = host.substr(idx+1); host = host.substr(0, host.lastIndexOf(':')); } } req.headers['x-forwarded-host'] = host; req.headers['x-forwarded-port'] = port; req.headers['host'] = targetHost; req.headers['origin'] = config.apiServer; req.socket.servername = targetHost; proxyLog('WS', req); try { proxy.ws(req, socket, head); } catch (err) { proxyLog(err); } }); let map = { 'Project': config.projectEndpoint.replace(config.projectToken, ''), 'Cluster': config.clusterEndpoint.replace(config.clusterToken, ''), 'Global': config.apiEndpoint, 'Public': config.publicApiEndpoint, 'Magic': config.magicEndpoint, 'Telemetry': config.telemetryEndpoint, 'K8s': '/k8s', 'Meta': '/meta', 'Swagger': '/swaggerapi', 'Version': '/version', } app.use('/', function(req, res, next) { if ( (req.headers['user-agent']||'').toLowerCase().includes('mozilla') ) { next(); } else { proxyLog('Root', req); req.headers['X-Forwarded-Proto'] = req.protocol; proxy.web(req, res); } }), console.log('Proxying APIs to', target); Object.keys(map).forEach(function(label) { let base = map[label]; app.use(base, function(req, res, next) { if ( req.url === '/' ) { req.url = ''; } // include root path in proxied request req.url = path.join(base, req.url); req.headers['X-Forwarded-Proto'] = req.protocol; // don't include the original host header req.headers['X-Forwarded-Host'] = req.headers['host']; delete req.headers['host']; proxyLog(label, req); proxy.web(req, res); }); }); } function onProxyError(err, req, res) { console.log('Proxy Error on '+ req.method + ' to', req.url, err); var error = { type: 'error', status: 500, code: 'ProxyError', message: 'Error connecting to proxy', detail: err.toString() } if ( req.upgrade ) { res.end(); } else { res.writeHead(500, {'Content-Type': 'application/json'}); res.end(JSON.stringify(error)); } } function proxyLog(label, req) { console.log(`[${ label }]`, req.method, req.url); }
JavaScript
0.000001
@@ -1994,16 +1994,40 @@ rsion',%0A + 'Apiui': '/api-ui',%0A %7D%0A%0A a
30307231e63a57d8bedac103be0ad88d4e33e95f
Fix linting issues
src/main-process/file-recovery-service.js
src/main-process/file-recovery-service.js
'use babel' import {BrowserWindow, ipcMain} from 'electron' import crypto from 'crypto' import Path from 'path' import fs from 'fs-plus' class RecoveryFile { constructor (originalPath, recoveryPath) { this.originalPath = originalPath this.recoveryPath = recoveryPath this.refCount = 0 } storeSync () { fs.writeFileSync(this.recoveryPath, fs.readFileSync(this.originalPath)) } recoverSync () { fs.writeFileSync(this.originalPath, fs.readFileSync(this.recoveryPath)) this.removeSync() this.refCount = 0 } removeSync () { fs.unlinkSync(this.recoveryPath) } retain () { if (this.refCount === 0) this.storeSync() this.refCount++ } release () { this.refCount-- if (this.refCount === 0) this.removeSync() } isReleased () { return this.refCount === 0 } } export default class FileRecoveryService { constructor (recoveryDirectory) { this.recoveryDirectory = recoveryDirectory this.recoveryFilesByFilePath = new Map() this.recoveryFilesByWindow = new WeakMap() this.observedWindows = new WeakSet() } start () { ipcMain.on('will-save-path', this.willSavePath.bind(this)) ipcMain.on('did-save-path', this.didSavePath.bind(this)) } willSavePath (event, path) { if (!fs.existsSync(path)) { // Unexisting files won't be truncated/overwritten, and so there's no data to be lost. event.returnValue = false return } const window = BrowserWindow.fromWebContents(event.sender) let recoveryFile = this.recoveryFilesByFilePath.get(path) if (recoveryFile == null) { const recoveryPath = Path.join(this.recoveryDirectory, crypto.randomBytes(5).toString('hex')) recoveryFile = new RecoveryFile(path, recoveryPath) this.recoveryFilesByFilePath.set(path, recoveryFile) } recoveryFile.retain() if (!this.recoveryFilesByWindow.has(window)) this.recoveryFilesByWindow.set(window, new Set()) this.recoveryFilesByWindow.get(window).add(recoveryFile) if (!this.observedWindows.has(window)) { this.observedWindows.add(window) window.webContents.on("crashed", () => this.recoverFilesForWindow(window)) window.on("closed", () => { this.observedWindows.delete(window) this.recoveryFilesByWindow.delete(window) }) } event.returnValue = true } didSavePath (event, path) { const window = BrowserWindow.fromWebContents(event.sender) const recoveryFile = this.recoveryFilesByFilePath.get(path) if (recoveryFile != null) { recoveryFile.release() if (recoveryFile.isReleased()) this.recoveryFilesByFilePath.delete(path) this.recoveryFilesByWindow.get(window).delete(recoveryFile) } event.returnValue = true } recoverFilesForWindow (window) { if (!this.recoveryFilesByWindow.has(window)) return for (const recoveryFile of this.recoveryFilesByWindow.get(window)) { try { recoveryFile.recoverSync() } catch (error) { console.log(`Cannot recover ${recoveryFile.originalPath}. A recovery file has been saved here: ${recoveryFile.recoveryPath}.`) } finally { this.recoveryFilesByFilePath.delete(recoveryFile.originalPath) } } this.recoveryFilesByWindow.delete(window) } }
JavaScript
0.000001
@@ -2127,17 +2127,17 @@ .on( -%22 +' crashed -%22 +' , () @@ -2196,16 +2196,16 @@ .on( -%22 +' closed -%22 +' , ()
8d105803ef89efd3c59ca63c1a846cef633997f1
Create stripGenericPattern
extension.js
extension.js
const path = require('path'); const vscode = require('vscode'); function stripWorkspaceFolder(currentFilename, workspaceFolder) { if (workspaceFolder && currentFilename.indexOf(workspaceFolder) === 0) { return currentFilename.slice(workspaceFolder.length); } else { return currentFilename; } } function stripExcessDirectoryLevels(currentFilename, separator, directoryLevelsToPreserve) { const filenameParts = currentFilename.split(separator); const startingIndex = filenameParts.length - 1 - directoryLevelsToPreserve; const boundedStartingIndex = Math.min(Math.max(startingIndex, 1), filenameParts.length - 1); return filenameParts.slice(boundedStartingIndex).join(separator); } function stripExtension(currentFilename, separator) { const filenameParts = currentFilename.split(separator); let basename = filenameParts[filenameParts.length - 1]; let extension; while (extension = path.extname(basename)) { basename = path.basename(basename, extension); } filenameParts[filenameParts.length - 1] = basename; return filenameParts.join(separator); } function stripPatterns(currentFilename, separator, patterns) { if (patterns) { patterns.forEach(function(pattern) { if (pattern === '{EXTENSION}') { currentFilename = stripExtension(currentFilename, separator); } else { currentFilename = currentFilename.replace(pattern, ''); } }); } return currentFilename; } function buildPrefix(currentFilename, workspaceFolder, separator, config) { currentFilename = stripWorkspaceFolder(currentFilename, workspaceFolder); currentFilename = stripExcessDirectoryLevels(currentFilename, separator, config.directoryLevelsToPreserve); currentFilename = stripPatterns(currentFilename, separator, config.patternsToStrip); return currentFilename; } function showRelatedFiles() { const { document } = vscode.window.activeTextEditor; const currentFilename = document.fileName; const workspaceFolder = vscode.workspace.getWorkspaceFolder(document.uri).uri.path; const separator = path.sep; const config = vscode.workspace.getConfiguration('quickPickRelatedFiles'); const prefix = buildPrefix(currentFilename, workspaceFolder, separator, config); vscode.commands.executeCommand('workbench.action.quickOpen', prefix); } function activate(context) { context.subscriptions.push(vscode.commands.registerCommand('quickPickRelatedFiles.show', showRelatedFiles)); } module.exports.buildPrefix = buildPrefix; module.exports.activate = activate;
JavaScript
0.000001
@@ -1118,32 +1118,141 @@ (separator);%0A%7D%0A%0A +function stripGenericPattern(currentFilename, pattern) %7B%0A return currentFilename.replace(pattern, '');%0A%7D%0A%0A function stripPa @@ -1541,16 +1541,36 @@ ename = +stripGenericPattern( currentF @@ -1576,36 +1576,25 @@ Filename -.replace( +, pattern -, '' );%0A
3ee7ed2698db579ec2d8b4cb6c6c4afc509993c2
Add an emitter to AbstractComponent
lib/core/abstract-component.js
lib/core/abstract-component.js
/** @babel */ import etch from 'etch' import {CompositeDisposable} from 'atom' export default class AbstractComponent { constructor(properties, children, callback) { if (properties) this.properties = properties else this.properties = {} if (children) this.children = children else this.children = [] this.disposables = new CompositeDisposable() if (callback) callback(this.properties, this.children) etch.initialize(this) } update(properties, children, callback) { if (properties && this.properties !== properties) this.properties = properties if (children && this.children !== children) this.children = children if (callback) callback(this.properties, this.children) return etch.update(this) } destroy(callback) { this.disposables.dispose() if (callback) callback() return etch.destroy(this) } }
JavaScript
0.000001
@@ -41,16 +41,25 @@ import %7B +Emitter, Composit @@ -369,24 +369,57 @@ isposable()%0A + this.emitter = new Emitter()%0A if (call @@ -837,24 +837,51 @@ s.dispose()%0A + this.emitter.dispose()%0A if (call
028e0ea9371b890fe6accac6b04ff8430abebd34
Fix lint error in DOM fixtures (#10369)
fixtures/dom/src/components/fixtures/date-inputs/index.js
fixtures/dom/src/components/fixtures/date-inputs/index.js
const React = window.React; import Fixture from '../../Fixture'; import FixtureSet from '../../FixtureSet'; import TestCase from '../../TestCase'; import SwitchDateTestCase from './switch-date-test-case'; class DateInputFixtures extends React.Component { render() { return ( <FixtureSet title="Dates" description=""> <TestCase title="Switching between date and datetime-local"> <TestCase.Steps> <li>Type a date into the date picker</li> <li>Toggle "Switch type"</li> </TestCase.Steps> <TestCase.ExpectedResult> The month, day, and year values should correctly transfer. The hours/minutes/seconds should not be discarded. </TestCase.ExpectedResult> <Fixture> <SwitchDateTestCase /> </Fixture> </TestCase> </FixtureSet> ); } } export default DateInputFixtures;
JavaScript
0
@@ -1,33 +1,4 @@ -const React = window.React;%0A%0A impo @@ -171,16 +171,45 @@ case';%0A%0A +const React = window.React;%0A%0A class Da
3c32a0eec0697be3a61508a99a75e28157f4cde4
add residence as props to p2p
src/javascript/app/pages/cashier/dp2p.js
src/javascript/app/pages/cashier/dp2p.js
const React = require('react'); const ReactDOM = require('react-dom'); const Client = require('../../base/client'); const BinarySocket = require('../../base/socket'); const getLanguage = require('../../../_common/language').get; const urlForStatic = require('../../../_common/url').urlForStatic; const DP2P = (() => { const onLoad = () => { const is_svg = Client.get('landing_company_shortcode') === 'svg'; if (is_svg) { import('@deriv/p2p').then((module) => { const el_dp2p_container = document.getElementById('binary-dp2p'); const shadowed_el_dp2p = el_dp2p_container.attachShadow({ mode: 'closed' }); const el_main_css = document.createElement('style'); // These are styles that are to be injected into the Shadow DOM, so they are in JS and not stylesheets // They are to be applied to the `:host` selector el_main_css.innerHTML = ` @import url(${urlForStatic('css/p2p.min.css')}); :host { --hem:10px; } :host .theme--light { --button-primary-default: #2e8836; --button-primary-hover: #14602b; --brand-red-coral: #2a3052; --state-active: #2a3052; --general-section-1: #ffffff; --text-profit-success: #2e8836; } .dc-button-menu__wrapper .dc-button-menu__button:not(.dc-button-menu__button--active) { background-color: #f2f2f2 !important; } .link { color: #E88024 !important; } .dc-button-menu__wrapper .dc-button-menu__button--active .btn__text { color: #ffffff; } .dc-input__field { box-sizing:border-box; } .link { color: var(--brand-red-coral); font-weight: bold; text-decoration: none; } .link:hover { text-decoration: underline; cursor: pointer; } `; el_main_css.rel = 'stylesheet'; const dp2p_props = { className : 'theme--light', websocket_api: BinarySocket, lang : getLanguage(), client : { currency : Client.get('currency'), is_virtual: Client.get('is_virtual'), }, }; ReactDOM.render( // eslint-disable-next-line no-console React.createElement(module.default, dp2p_props), shadowed_el_dp2p ); shadowed_el_dp2p.prepend(el_main_css); }); } else { document.getElementById('message_cashier_unavailable').setVisibility(1); } }; const onUnload = () => { // TODO: Look into clearance }; return { onLoad, onUnload, }; })(); module.exports = DP2P;
JavaScript
0
@@ -2751,24 +2751,85 @@ _virtual'),%0A + residence : Client.get('residence'),%0A
7d35415d2962f2cd9af78e515db5663c7b90ddf4
make path logic more robust
bin/polymerize.js
bin/polymerize.js
#!/usr/bin/env node /** * @license * Copyright (c) 2015 The Polymer Project Authors. All rights reserved. * This code may only be used under the BSD style license found at http://polymer.github.io/LICENSE.txt * The complete set of authors may be found at http://polymer.github.io/AUTHORS.txt * The complete set of contributors may be found at http://polymer.github.io/CONTRIBUTORS.txt * Code distributed by Google as part of the polymer project is also * subject to an additional IP rights grant found at http://polymer.github.io/PATENTS.txt */ 'use strict'; var commander = require('commander'); var concat = require('gulp-concat'); var del = require('del'); var fs = require('fs'); var gulp = require('gulp'); var filter = require('gulp-filter'); var mainBowerFiles = require('main-bower-files'); var path = require('path'); var polyclean = require('polyclean'); var replace = require('gulp-replace'); var shell = require('gulp-shell'); var mainImport = require('../lib/main-import'); var gulpsettings = require('../lib/gulpsettings'); commander .usage('[options] <components...>') .option('-d, --workdir [dir]', 'sets directory used for polymerization. Defaults to polymers/') .option('-m, --mainfile [file]', 'Sets debug main file. Defaults to main.html') .option('-p, --outfile [file]', 'Sets the output file. Defaults to polymers.html') .parse(process.argv) var workdir = commander.workdir; if (!workdir) { workdir = "polymers"; } var outfile = commander.outfile; if (!outfile) { outfile = "polymers.html"; } console.log(workdir); console.log(outfile); console.log(commander.args); function vulcanize(filename, outfile, root) { var cmd = path.join(__dirname + '../node_modules/vulcanize/bin/vulcanize'); cmd = cmd + ' ' + filename + ' > ' + outfile; console.log(cmd); return cmd } function bower(args) { var cmd = path.join(__dirname + '../node_modules/bower/bin/bower '); return cmd + args } function bower_install(components) { return bower(' --save install ' + components.join(' ')) } function bower_init() { return bower(' init') } gulp.task('clean', function(cb) { del([workdir], cb); }); gulp.task('mkdir', ['clean'], function(cb) { fs.mkdir(workdir, null, cb); }); gulp.task('bower-init', ['mkdir'], function(cb) { fs.writeFile(path.join(workdir, 'bower.json'), JSON.stringify(gulpsettings()), cb) }) gulp.task('bower', ['bower-init'], shell.task(bower_install(commander.args), {cwd: workdir})); var bowerDir = path.join(workdir, 'bower_components'); gulp.task('component-main', ['bower'], function() { return gulp.src(mainBowerFiles({ paths: { bowerJson: path.join(workdir, 'bower.json'), bowerDirectory: bowerDir } })) .pipe(filter('**/*.html')) .pipe(mainImport()) .pipe(concat("main.html")) .pipe(gulp.dest(process.cwd())); }); gulp.task('vulcanize', ['component-main'], shell.task(vulcanize("main.html", outfile))); gulp.task('polish', ['vulcanize'], function() { return gulp.src(outfile) .pipe(polyclean.cleanJsComments()) // Get rid of erroneous html comments .pipe(replace(/<!--((?!@license)[^])*?-->/g, '')) // Reduce script tags .pipe(replace(/<\/script>\s*<script>/g, '\n')) // Collapse newlines .pipe(replace(/\n\s*\n/g, '\n')) // Collapse leading spaces+tabs. .pipe(replace(/^[ \t]+/gm, '')) .pipe(gulp.dest(process.cwd())); }); gulp.start('polish');
JavaScript
0.000067
@@ -1677,34 +1677,34 @@ h.join(__dirname +, -+ '../node_module @@ -1870,18 +1870,17 @@ _dirname - + +, '../nod
bcd1908dac5524ce05fa242b62f8e6aa5bb58d28
fix referrer
app/assets/javascripts/scripts/core/lib/modules/renderer/combo.box.js
app/assets/javascripts/scripts/core/lib/modules/renderer/combo.box.js
/** * Created by i061485 on 7/10/14. */ define([], function defineComboBoxRenderer() { /** * Define ComboBoxRenderer * @class ComboBoxRenderer * @extends LabelRenderer * @constructor */ var ComboBoxRenderer = function ComboBoxRenderer() { }; return ComboBoxRenderer.extend('ComboBoxRenderer', { /** * Render combo box * @member ComboBoxRenderer * @param {Array} data * @param selected * @param {string} name * @param {string} index * @param {{type: string, callback: function}} [event] * @param {boolean} [visible] * @param {boolean} [placeholder] */ renderCombobox: function renderCombobox(data, selected, name, index, event, visible, placeholder) { // Init placeholder placeholder = typeof (placeholder) === 'undefined' ? false : !!placeholder; /** * Get wrapper * @returns {BaseElement.$} * @private */ function _getWrapper() { /** * Get referrer * @type {*} */ var referrer = this.view.scope.referrer, $modal, $wrapper = this.$; if (referrer) { /** * Get $modal dialog * @type {ModalElement} */ $modal = referrer.view.elements.$modal; if ($modal) { $wrapper = $modal.$; } } return $wrapper; } /** * Define active content * @type {*|Page|WidgetContent} */ var activeContent = this.view.scope.activeContent; /** * Define container * @type {*|jQuery} */ var $div = $('<div class="combo-box" />'). addClass((activeContent ? [index, activeContent.constructor.prototype.name].join('') : index).toDash()). attr({ id: this.base.lib.generator.UUID() + '-combobox' }).append( $('<input class="hidden" />').attr({ name: index, disabled: true, type: 'text', value: selected }) ); /** * Open combo box * @private */ function _open() { if (this.isDisabledComboBox($div.parent())) { return false; } // Get wrapper var $wrapper = _getWrapper.bind(this)(); // close all como-boxes $('.combo-box', $wrapper).removeClass('open'); $div.addClass('open'); $('div.html', $wrapper).addClass('visible'); } /** * Hide combo box * @private */ function _hide() { // Get wrapper var $wrapper = _getWrapper.bind(this)(); $div.removeClass('open'); $('div.html', $wrapper).removeClass('visible'); } /** * Store prefs * @param $selected * @param selected * @returns {boolean} * @private */ function _store($selected, selected) { // Remove tooltip text before store selected value $('.tooltip', $selected).remove(); /** * Define value * @type {String} */ var value = $selected.text(); if (value === selected) { return false; } $('input[name="' + index + '"]', $div).val(value); } /** * Define $ul * @type {*|jQuery} */ var $ul = $('<ul />'), i = 0, l = data.length; for (; i < l; i++) { var field = data[i], $li = $('<li />'); if (field.type === 'text') { $li.text(field.value); } if (field.type === 'html') { $li.html(field.value); } if (field.type === 'field') { $li.append( this.renderTextField({ name: field.name, placeholder: field.placeholder, value: field.value, disabled: field.disabled }) ); } if (selected === field.value) { $li.addClass('selected'); } $li.on( 'click.comboBoxInternal', /** * Select combo box item * @param e * @returns {boolean} */ function comboBoxInternalEvent(e) { ($div.hasClass('open') ? _hide : _open).bind(this)(); /** * Define selected $li * @type {*|jQuery|HTMLElement} */ var $selected = $(e.target); if ($selected.hasClass('selected')) { _store($selected, selected); return false; } $('li', $selected.parent()).removeClass('selected'); $selected.addClass('selected'); _store($selected, selected); }.bind(this) ); // hide on mouse leave $ul.on('mouseleave.comboBoxInternal', _hide.bind(this)); if (this.base.isDefined(event)) { if (this.base.isFunction(event.callback)) { $li.on(event.type, function comboBoxEvent(e) { event.callback($(e.target).attr('rel')); }); } } $li.attr({ rel: field.key || field.value, title: data[i].title || field.value }).appendTo($ul); /** * Get tooltip * @type {string|*} */ var tooltip = data[i].tooltip; if (tooltip) { // Set reference $li.$ = $li; this.renderTooltip({ title: field.value, description: tooltip, $container: $li }); } } if (typeof(selected) === 'undefined') { if (placeholder) { $ul.prepend( $('<li class="placeholder" />').text( 'Select ' + name ).on( 'click.placeholder', function clickOn(e) { if (this.isDisabledComboBox($div.parent())) { return false; } $(e.target).remove(); $('li:first', $ul).trigger('click.comboBoxInternal'); }.bind(this) ) ); } $('li:first', $ul).show(); } // fix to define modal dialog height setTimeout(function () { visible ? $div.show() : $div.hide(); }, 500); return [ this.renderLabel(undefined, name, undefined, visible), $div.append([ $ul, $('<div />').addClass('combo-box-arrow') ]) ]; }, /** * Check if combo box disabled * @member ComboBoxRenderer * @param $combo * @returns {boolean} */ isDisabledComboBox: function isDisabledComboBox($combo) { return $combo.find('div.combo-box.disabled').length === 1; }, /** * Define enable combo box * @member ComboBoxRenderer * @param $combo */ enableComboBox: function enableComboBox($combo) { $combo.find('div.combo-box').removeClass('disabled'); }, /** * Define disable combo box * @member ComboBoxRenderer * @param $combo */ disableComboBox: function disableComboBox($combo) { $combo.find('div.combo-box').addClass('disabled'); }, /** * Clear placeholder * @member ComboBoxRenderer * @param $combo */ clearPlaceholder: function clearPlaceholder($combo) { $combo.find('div.combo-box > ul li.placeholder'). trigger('click.placeholder'). remove(); } }); });
JavaScript
0.000002
@@ -955,32 +955,77 @@ * Get wrapper%0A + * @param %7BBaseElement%7D $element%0A * @ @@ -1121,16 +1121,24 @@ Wrapper( +$element ) %7B%0A%0A @@ -1266,20 +1266,24 @@ errer = -this +$element .view.sc @@ -1339,14 +1339,78 @@ r = -this.$ +$element.$;%0A%0A referrer = referrer ? referrer : $element ;%0A%0A @@ -2199,30 +2199,8 @@ ent. -constructor.prototype. name @@ -2878,37 +2878,30 @@ _getWrapper -.bind (this) -() ;%0A%0A @@ -3300,29 +3300,22 @@ tWrapper -.bind (this) -() ;%0A%0A
440a6415c55ddd8481fc1827460dbdf4ab99fbbb
Remove unused dep
packages/rest-bearer-token-parser/package.js
packages/rest-bearer-token-parser/package.js
Package.describe({ name: 'simple:rest-bearer-token-parser', version: '1.0.0', // Brief, one-line summary of the package. summary: 'Parse standard bearer token via request headers, query params ' + 'or body (REST middleware)', // URL to the Git repository containing the source code for this package. git: 'https://github.com/stubailo/meteor-rest', // 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.0'); api.use('simple:[email protected]'); api.addFiles('bearer_token_parser.js', 'server'); }); Package.onTest(function (api) { api.use('simple:rest-bearer-token-parser'); api.use('tinytest'); api.use('test-helpers'); api.use('http'); api.use('simple:[email protected]'); api.use('simple:[email protected]'); api.addFiles('bearer_token_parser_tests.js'); });
JavaScript
0.000001
@@ -885,58 +885,8 @@ ');%0A - api.use('simple:[email protected]');%0A ap
8e37d74ce6024af6f519871acfef4884577e5352
fix typos
app-start.js
app-start.js
/** * This PM2 file starts a Kuzzle instance. Without any argument, a Kuzzle instance is launched, complete * with a server and a single set of workers. * * This default configuration isn't optimal performance-wise. Instead, it's prefered to start a Kuzzle server, and * then spawns a couple of workers. * * To start a Kuzzle server: * pm2 start -n 'server' app-start.js -- --server * * To start 3 sets of workers: * pm2 start -n 'worker' -f -i 3 app-start.js -- --worker * * You can then scale up/down the number of workers: * pm2 scale worker <new number of workers> * * Please check the default PM2 JSON configuration file provided in Kuzzle installation directories. * * To get a complete list of available options, launch 'bin/kuzzle.js start -h' */ if (process.env.NEW_RELIC_APP_NAME) { require('newrelic'); } (function () { var kuzzle = require('./lib'), rc = require('rc'), fs = require('fs'), RequestObject = require('./lib/api/core/models/requestObject'), result, fixtures = {}, fixture, collection; kuzzle.start(rc('kuzzle')); var reset = function(callback) { result = kuzzle.services.list.readEngine.reset(); if (result) { kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); kuzzle.log.info('Reset done: Kuzzle is now like a virgin, touched for the very first time !'); kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); } else { kuzzle.log.error('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); kuzzle.log.error('Oops... something really bad happened during reset...'); kuzzle.log.error('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); } if (callback) { callback(); } } // is a reset has been asked and we are launching a server ? if (process.env.LIKE_A_VIRGIN == 1 && process.argv.indexOf('--server') > -1) { reset(); } // is a fixture file has been specified to be inserted into database at Kuzzle start and we are launching a server ? if (process.env.FIXTURES != '' && process.argv.indexOf('--server') > -1) { // implies reset reset(function(){ kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); kuzzle.log.info('Reading fixtures file',process.env.FIXTURES); try { fixtures = JSON.parse(fs.readFileSync(process.env.FIXTURES, 'utf8')); } catch(e) { kuzzle.log.error('An error occured when reading the', process.env.FIXTURES,'file!'); kuzzle.log.error('Remember to put the file into the docker scope...'); kuzzle.log.error('Here is the original error:', e); return; } for (collection in fixtures) { kuzzle.log.info('== Importing fixtures for collection', collection, '...'); fixture = { action: 'import', persist: true, collection: collection, body: fixtures[collection] }; kuzzle.services.list.readEngine.import(new RequestObject(fixture), function(error, response) { console.log('RESPONSE',error, response); if (error) { kuzzle.log.error('Fixture import error for', error); } else { kuzzle.log.log('Fixture import OK for', response); } }); } kuzzle.log.info('All fixtures imports launched.'); kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-'); }); } })();
JavaScript
0.999974
@@ -1142,17 +1142,8 @@ %0A - result = kuz @@ -1156,28 +1156,29 @@ rvices.list. -read +write Engine.reset @@ -1183,426 +1183,228 @@ et() -; %0A -if (result) %7B%0A kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A kuzzle.log.info('Reset done: Kuzzle is now like a virgin, touched for the very first time !');%0A kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A %7D else %7B%0A kuzzle.log.error('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A + .then(function()%7B%0A kuzzle.log.info('Reset done: Kuzzle is now like a virgin, touched for the very first time !');%0A if (callback) %7B%0A callback();%0A %7D%0A %7D)%0A .catch(function()%7B%0A @@ -1488,92 +1488,8 @@ - kuzzle.log.error('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A %7D%0A @@ -1506,24 +1506,28 @@ ck) %7B%0A + + callback();%0A @@ -1530,17 +1530,36 @@ ();%0A -%7D + %7D%0A %7D)%0A ; %0A %7D%0A%0A @@ -1962,109 +1962,8 @@ ()%7B%0A - kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A @@ -2703,20 +2703,21 @@ es.list. -read +write Engine.i @@ -2782,59 +2782,8 @@ ) %7B%0A - console.log('RESPONSE',error, response);%0A @@ -2977,24 +2977,24 @@ );%0A%0A %7D%0A + kuzzle @@ -3042,109 +3042,8 @@ ');%0A - kuzzle.log.info('=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-');%0A
576976d42ce045176db932449fd163c83335fd84
Change default width of desktop settings
src/main/features/core/desktopSettings.js
src/main/features/core/desktopSettings.js
import { BrowserWindow } from 'electron'; import path from 'path'; import AutoLaunch from 'auto-launch'; const appLauncher = new AutoLaunch({ name: 'Google Play Music Desktop Player', }); export const showDesktopSettings = () => { if (WindowManager.getAll('settings').length > 0) { WindowManager.getAll('settings')[0].show(); return; } const desktopSettings = new BrowserWindow({ width: 800, height: 540, autoHideMenuBar: true, frame: Settings.get('nativeFrame'), titleBarStyle: Settings.get('nativeFrame') && process.platform === 'darwin' ? 'hidden' : 'default', show: false, webPreferences: { nodeIntegration: true, }, icon: path.resolve(`${__dirname}/../../../assets/img/main.${(process.platform === 'win32' ? 'ico' : 'png')}`), // eslint-disable-line title: 'Settings', }); desktopSettings.loadURL(`file://${__dirname}/../../../public_html/desktop_settings.html`); WindowManager.add(desktopSettings, 'settings'); WindowManager.forceFocus(desktopSettings); }; export const showColorWheel = () => { if (WindowManager.getAll('color_wheel').length > 0) { WindowManager.getAll('color_wheel')[0].show(); return; } const colorWheel = new BrowserWindow({ width: 400, height: 400, autoHideMenuBar: true, frame: Settings.get('nativeFrame'), titleBarStyle: Settings.get('nativeFrame') && process.platform === 'darwin' ? 'hidden' : 'default', show: false, webPreferences: { nodeIntegration: true, }, icon: path.resolve(`${__dirname}/../../../assets/img/main.${(process.platform === 'win32' ? 'ico' : 'png')}`), // eslint-disable-line title: 'Color Wheel', }); colorWheel.loadURL(`file://${__dirname}/../../../public_html/color_wheel.html`); WindowManager.add(colorWheel, 'color_wheel'); WindowManager.forceFocus(colorWheel); }; Emitter.on('window:settings', () => { // const mainWindow = WindowManager.getAll('main')[0]; showDesktopSettings(); }); Emitter.on('window:color_wheel', () => { showColorWheel(); }); Emitter.on('settings:set', (event, details) => { Settings.set(details.key, details.value); // DEV: React to settings change switch (details.key) { case 'miniAlwaysShowSongInfo': Emitter.sendToGooglePlayMusic('miniAlwaysShowSongInfo', { state: details.value }); break; case 'miniAlwaysOnTop': Emitter.sendToGooglePlayMusic('miniAlwaysOnTop', { state: details.value }); break; case 'miniUseScrollVolume': Emitter.sendToGooglePlayMusic('miniUseScrollVolume', { state: details.value }); break; case 'speechRecognition': Emitter.sendToGooglePlayMusic('speech:toggle', { state: details.value }); break; case 'scrollLyrics': Emitter.sendToAll('settings:set:scrollLyrics', details.value); break; case 'auto-launch': if (details.value === true) { appLauncher.enable(); } else { appLauncher.disable(); } break; default: break; } });
JavaScript
0
@@ -403,17 +403,17 @@ width: 8 -0 +4 0,%0A h
c0422c9957d4f0317406c3aaf6b5b9df8ae0151f
fix promise regression
core/env.js
core/env.js
/** Copyright 2014 Gordon Williams ([email protected]) This Source Code is subject to the terms of the Mozilla Public License, v2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ------------------------------------------------------------------ Board Environment variables (process.env) - queried when board connects ------------------------------------------------------------------ **/ "use strict"; (function(){ var JSON_DIR = "http://www.espruino.com/json/"; var environmentData = {}; var boardData = {}; function init() { Espruino.Core.Config.add("ENV_ON_CONNECT", { section : "Communications", name : "Request board details on connect", description : 'Just after the board is connected, should we query `process.env` to find out which board we\'re connected to? '+ 'This enables the Web IDE\'s code completion, compiler features, and firmware update notice.', type : "boolean", defaultValue : true, }); Espruino.addProcessor("connected", function(data, callback) { // Give us some time for any stored data to come in setTimeout(queryBoardProcess, 200, data, callback); }); } function queryBoardProcess(data, callback) { if (!Espruino.Config.ENV_ON_CONNECT) { return callback(data); } Espruino.Core.Utils.executeExpression("process.env", function(result) { var json = {}; if (result!==undefined) { try { json = JSON.parse(result); } catch (e) { console.log("JSON parse failed - " + e + " in " + JSON.stringify(result)); } } // now process the enviroment variables for (var k in json) { boardData[k] = json[k]; environmentData[k] = json[k]; } if (environmentData.VERSION) { var v = environmentData.VERSION; var vIdx = v.indexOf("v"); if (vIdx>=0) { environmentData.VERSION_MAJOR = parseInt(v.substr(0,vIdx)); var minor = v.substr(vIdx+1); var dot = minor.indexOf("."); if (dot>=0) environmentData.VERSION_MINOR = parseInt(minor.substr(0,dot)) + parseInt(minor.substr(dot+1))*0.001; else environmentData.VERSION_MINOR = parseFloat(minor); } } Espruino.callProcessor("environmentVar", environmentData, function(data) { environmentData = data; }); callback(data); }); } /** Get all data merged in from the board */ function getData() { return environmentData; } /** Get just the board's environment data */ function getBoardData() { return boardData; } /** Get a list of boards that we know about */ function getBoardList(callback) { Espruino.Core.Utils.getJSONURL(JSON_DIR + "boards.json", function(boards){ // now load all the individual JSON files var promises = []; for (var boardId in boards) { promises.push((function() { var id = boardId; return new Promise(function(resolve, reject) { Espruino.Core.Utils.getJSONURL(JSON_DIR + boards[boardId].json, function (data) { boards[id]["json"] = data; dfd.resolve(); }); }); })()); } // When all are loaded, load the callback Promise.all(promises).then(function(){ callback(boards); }); }); } Espruino.Core.Env = { init : init, getData : getData, getBoardData : getBoardData, getBoardList : getBoardList, }; }());
JavaScript
0.000001
@@ -3302,12 +3302,8 @@ -dfd. reso
9db222b4b4e87e78ede7186c045991eca415138c
Remove unused JSHint directive
packages/@glimmer/blueprint/files/config/environment.js
packages/@glimmer/blueprint/files/config/environment.js
'use strict'; /* jshint node: true */ module.exports = function(environment) { let ENV = { modulePrefix: '<%= component %>', environment: environment }; return ENV; };
JavaScript
0
@@ -12,33 +12,8 @@ ';%0A%0A -/* jshint node: true */%0A%0A modu
2d74c10d8fa70ab805682bf96eee2cd79366f5bb
Add EngineJS_ prefix
resources/sendFormRequestManager.js
resources/sendFormRequestManager.js
var EngineJS_sendFormRequestManage = { formInstance: null, treatAllErrorAsGeneral: true, apiClient: null, requestInProgress: false, submitUrl: null, onErrorCallback: function() {}, onGeneralErrorCallback: function() {}, onSuccessCallback: function() {}, beforeSubmitCallback: function() {}, init: function(newFormInstance, config) { this.formInstance = $(newFormInstance); if (typeof config == "undefined") { config = {}; } if (typeof config.treatAllErrorAsGeneral != "undefined") { this.treatAllErrorAsGeneral = config.treatAllErrorAsGeneral; } if (typeof config.apiClient != "undefined") { this.apiClient = config.apiClient; } if (typeof config.submitUrl != "undefined") { this.submitUrl = config.submitUrl; } var that = this; this.formInstance.on('submit', function(event) { event.preventDefault(); if (that.requestInProgress == true) { return ; } that.requestInProgress = true; var sendData = {}; that.formInstance.serializeArray().map(function(item){ sendData[item.name] = item.value; }); var executeBefore = that.beforeSubmitCallback(sendData); if (typeof executeBefore != "undefined") { if (executeBefore['status'] == 'generalError') { that.onGeneralErrorCallback({'error': executeBefore['message']}, that.formInstance); that.requestInProgress = false; return; // if there is an error we don't want to continue. } } if (typeof that.submitUrl == 'function') { submitUrl = that.submitUrl(); } else { submitUrl = that.submitUrl; } that.apiClient.post(submitUrl, sendData, { success: function(response) { that.requestInProgress = false; // call propar erro based on status code that.onSuccessCallback(response); }, error: function(status, response) { that.requestInProgress = false; if (status == 422) { if (that.treatAllErrorAsGeneral) { that.onGeneralErrorCallback(response, that.formInstance); } else { that.onErrorCallback(response); } } else if (status == 400) { that.onGeneralErrorCallback(response, that.formInstance); } else { console.log("Something went wrong"); } }, }); }); }, getFirstErrorField: function(errors) { for (var index in errors) { var firstErorrField = errors[index]; for (var index2 in firstErorrField) { return firstErorrField[index2]; } } }, onError: function(newOnError) { this.onErrorCallback = newOnError; }, onGeneralError: function(newOnGeneralError) { this.onGeneralErrorCallback = newOnGeneralError; }, onSuccess: function(newOnSuccess) { this.onSuccessCallback = newOnSuccess; }, beforeSubmit: function(newBeforeSummit) { this.beforeSubmitCallback = newBeforeSummit; } };
JavaScript
0.00003
@@ -27,16 +27,17 @@ stManage +r = %0A%7B%0A
e321a78226b3d03e4f35dba3793346ef62cff372
add JsHint
tests/src/encoder-mattermost-test.js
tests/src/encoder-mattermost-test.js
var sonarExemple = require("./../resources/sonar.exemple.json"); var EncoderMattermost = require('./../../src/encoder-mattermost'); var chai = require('chai'); var expect = chai.expect; describe('EncoderMattermost', function() { it('encodeSonarMessage() should return null if there\'s no message',function() { var encoderMattermost = new EncoderMattermost(); expect(encoderMattermost.encodeSonarMessage("")).to.be.null; }); it('encodeSonarMessage() should return an object with sonar.exemple.json',function() { var encoderMattermost = new EncoderMattermost(); var contenu = encoderMattermost.encodeSonarMessage(sonarExemple); expect(contenu).not.be.null; }); });
JavaScript
0.000004
@@ -63,16 +63,20 @@ );%0D%0Avar +Test EncoderM @@ -127,24 +127,24 @@ termost');%0D%0A - var chai = r @@ -186,16 +186,32 @@ expect;%0D +%0Achai.should();%0D %0A%0D%0Adescr @@ -363,32 +363,36 @@ attermost = new +Test EncoderMattermos @@ -604,16 +604,20 @@ t = new +Test EncoderM @@ -733,14 +733,21 @@ nu). +should.be. not -.be .nul
3ae891b42f738b906d13a6a8fb71dfd331736f5f
Make the rounding actually work
js/ScatterChartController.js
js/ScatterChartController.js
function ScatterChartController(data) { this.chart = null; this.context = null; this.topicID = data.topicID; this.latestPointTime = 0; } ScatterChartController.prototype = { draw: function() { var topic = topics[this.topicID]; var $canvas = $('<canvas>').addClass('').attr('id', 'canvas_' + topic.id); $('#placeForCharts').append( $('<li>').append( $('<fieldset>').addClass('chartContainer').append( $('<legend>').css('text-align', 'center').text(topic.description), $('<table>').addClass('summary').append( $('<tr>').append( $('<td>').addClass('firstColumn'), $('<td>').addClass('secondColumn').attr('colspan', '2'), //.addClass('valueCell valueTitle').attr('id', 'minmax_'+t).text('Past '+topics[t].periodName()), $('<td>') ), $('<tr>').append( $('<td>').addClass('valueCell').append( $('<div>').addClass('valueTitle').text('Current'), $('<div>').css('font-size', '150%').attr('id', 'current_' + topic.id) ), $('<td>').addClass('valueCell').append( $('<div>').addClass('valueTitle').text('Min'), $('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'min24_' + topic.id) ), $('<td>').addClass('valueCell').append( $('<div>').addClass('valueTitle').text('Max'), $('<div>').css('font-size', '100%').css('padding-top', '5px').attr('id', 'max24_' + topic.id) ), $('<td>') ) ), $('<div>').addClass('chart').append($canvas), $('<div>').addClass('lastUpdated').attr('id', 'lastUpdated_' + topic.id) ) ) ); this.context = document.getElementById("canvas_" + topic.id).getContext("2d"); this.chart = new Chart(this.context).Scatter([ { label: topic.description, strokeColor: topic.colour, pointColor: topic.colour, pointStrokeColor: '#fff', data: [{x: 0, y: 0}] } ], { bezierCurve: false, datasetStroke: true, pointDot: false, showTooltips: true, scaleShowHorizontalLines: true, scaleShowLabels: true, scaleType: "date", scaleLabel: "<%=Math.round(value, " + topic.decimalPoints + ")%>" + topic.units, //scaleLabel: "<%=value%>" + topic.units, useUtc: false, scaleDateFormat: "mmm d", scaleTimeFormat: "HH:MM", scaleDateTimeFormat: "mmm d, yyyy, HH:MM", animation: false, responsive: true, maintainAspectRatio: false, pointHitDetectionRadius: 1 }); }, update: function() { //add more data from the topic var newTemps = topics[this.topicID].dataForScatterChart(this.latestPointTime); for (var n in newTemps) { this.chart.datasets[0].addPoint(newTemps[n].x, newTemps[n].y); this.latestPointTime = Math.max(this.latestPointTime, moment(newTemps[n][0]).unix()) } if (this.chart.datasets[0].points.length > 1 && this.chart.datasets[0].points[0].arg == 0) { this.chart.datasets[0].removePoint(0); } this.chart.update(); $('#current_' + this.topicID).empty().text(topics[this.topicID].latestPoint.value + topics[this.topicID].units); $('#lastUpdated_' + this.topicID).empty().text('Updated ' + topics[this.topicID].latestPoint.time.fromNow()); var minMax = topics[this.topicID].minMax(); $('#min24_' + this.topicID).empty().append( minMax.minValue + topics[this.topicID].units ); $('#max24_' + this.topicID).empty().append( minMax.maxValue + topics[this.topicID].units ); }, redrawChart: function() { this.chart.datasets[0].points = []; var u = moment().unix() - period; for (var p in topics[this.topicID].points) { if (p < u) { continue; } this.chart.datasets[0].addPoint(topics[this.topicID].points[p].time.toDate(), topics[this.topicID].points[p].value) } this.chart.update(); } };
JavaScript
0.000012
@@ -2112,21 +2112,16 @@ el: %22%3C%25= -Math. round(va
a08eba428d77f8d2e07b175bc4a40e27da1843c6
remove code from configure time.
app/clock.js
app/clock.js
var Clock = function(minutes) { this.minutes = minutes; this.seconds = 60; this.paused = true; this.power = false; this.init = function() { var currentTime = document.getElementById("currentTime"); var configureTime = document.getElementById("configureTime"); currentTime.innerHTML = this.minutes; configureTime.innerHTML = this.minutes; }; this.togglePaused = function() { this.paused = !this.paused; }; this.displayTime = function(minutes, seconds, element) { var element = document.getElementById(element); element.innerHTML = minutes + ":" + seconds; return this.minutes + ":" + this.seconds; }; this.addAMinute = function() { console.log(this.power); this.minutes++; this.seconds = 60; if(this.power && this.paused) { var currentTime = document.getElementById("currentTime"); currentTime.innerHTML = this.minutes; } var configureTime = document.getElementById("configureTime"); configureTime.innerHTML = this.minutes; }; this.minusAMinute = function() { console.log(this.power); if(this.minutes === 1) { return this.minutes; } this.minutes--; this.seconds = 60; if(this.power && this.paused) { var currentTime = document.getElementById("currentTime"); currentTime.innerHTML = this.minutes; } var configureTime = document.getElementById("configureTime"); configureTime.innerHTML = this.minutes; }; this.switchConfigure = function(clock) { var minus = document.getElementById("minus"); var plus = document.getElementById("plus"); var session = document.getElementById("session"); var breaks = document.getElementById("break"); var configureTime = document.getElementById("configureTime"); console.log(this); if(clock == "session") { minus.setAttribute("onclick", "session.minusAMinute()"); plus.setAttribute("onclick", "session.addAMinute()"); session.setAttribute("style", "background-color: #00cf9e; color: #f9f9f9;"); breaks.setAttribute("style", "background-color: #f9f9f9; color: #00cf9e; border: 5px solid #00cf9e;"); configureTime.innerHTML = this.minutes; } else if(clock == "breaks"){ minus.setAttribute("onclick", "breaks.minusAMinute()"); plus.setAttribute("onclick", "breaks.addAMinute()"); session.setAttribute("style", "background-color: #f9f9f9; color: #00cf9e; border: 5px solid #00cf9e;"); breaks.setAttribute("style", "background-color: #00cf9e; color: #f9f9f9;"); configureTime.innerHTML = this.minutes; } } this.countdown = function() { var clock = this; var minutes = clock.minutes - 1; if(!clock.paused) { var countDown = setInterval(function() { if(clock.paused) { clearInterval(countDown); } if(minutes === 0 && clock.seconds <= 1) { clock.togglePaused(); clock.power = false; clearInterval(countDown); } if(minutes <= 1) { minutes = 0; } if(clock.seconds < 1) { minutes--; clock.seconds = 60; } clock.seconds--; clock.displayTime(minutes, clock.seconds, "currentTime"); }, 1000); } }; }; var session = new Clock(25); var breaks = new Clock(5); session.power = true; session.init(); module.exports = Clock;
JavaScript
0
@@ -470,24 +470,12 @@ ion( -minutes, seconds +time , el @@ -535,16 +535,17 @@ ement);%0A +%0A elem @@ -564,84 +564,17 @@ L = -minutes + %22:%22 + seconds;%0A%0A return this.minutes + %22:%22 + this.seconds +time ;%0A %7D -; %0A t @@ -611,335 +611,127 @@ -console.log(this.power);%0A this.minutes++;%0A this.seconds = 60; +this.minutes++;%0A %0A -if( this. -power && this.paused) %7B%0A var currentTime = document.getElementById(%22currentTime%22);%0A currentTime.innerHTML = this.minutes;%0A %7D%0A%0A var configureTime = document.getElementById(%22configureTime%22);%0A configureTime.innerHTML = this.minutes +displayTime(this.minutes, %22currentTime%22);%0A this.displayTime(this.minutes, %22configureTime%22) ;%0A @@ -772,37 +772,8 @@ ) %7B%0A - console.log(this.power);%0A @@ -858,289 +858,112 @@ -this.seconds = 60;%0A %0A -if( this. -power && this.paused) %7B%0A var currentTime = document.getElementById(%22currentTime%22);%0A currentTime.innerHTML = this.minutes;%0A %7D%0A%0A var configureTime = document.getElementById(%22configureTime%22);%0A configureTime.innerHTML = this.minutes;%0A +displayTime(this.minutes, %22currentTime%22);%0A this.displayTime(this.minutes, %22configureTime%22); %0A %7D @@ -1281,32 +1281,8 @@ );%0A%0A -%0A console.log(this);%0A
eabc0671d86b7e3012e4dacc1eceaf96d7a9ed1b
add optional path to save preferences
packages/app-extensions/src/rest/helpers/preferences.js
packages/app-extensions/src/rest/helpers/preferences.js
import {call} from 'redux-saga/effects' import {requestSaga} from '../rest' /** * To fetch user preferences. * * @param path {string} To load specific preferences matching the path. Wildcards (e.g. *) may be used. */ export function* fetchUserPreferences(path) { const response = yield call(requestSaga, `client/preferences${path ? '/' + path : ''}`) return response.body.preferences } /** * Deletes all preferences matching the path. * * @param path {string} All preferences matching the path will be deleted. Wildcards (e.g. *) may be used. */ export function* deleteUserPreferences(path) { yield call(requestSaga, `client/preferences/${path}`, {method: 'DELETE'}) } /** * To add or overwrite preferences. * * @param preferences {object} Key/Value pairs. */ export function* savePreferences(preferences) { yield call(requestSaga, 'client/preferences', {method: 'PATCH', body: {values: preferences}}) }
JavaScript
0
@@ -771,16 +771,56 @@ pairs.%0A + * @param path %7Bstring%7D preference path%0A */%0Aexpo @@ -859,16 +859,45 @@ ferences +, path = '/nice2/ui/settings' ) %7B%0A yi @@ -965,16 +965,22 @@ body: %7B +path, values:
a524cdd835e2b52b2395e492ba4b582e8122dfe8
Make the marker visible again when the visitor dismisses the startup modal
script.js
script.js
;(function () { 'use strict' Ink.loadScript = function () { } // no dynamic loading today! var streetViewSvc = { endPoint: 'http://maps.googleapis.com/maps/api/streetview?size=300x300&sensor=false', apiKey: 'notsureifshouldshow' } var googleMapsDirectionsLink = 'https://maps.google.com/maps?daddr=' var mapCanvas = Ink.i('mapCanvas'); var modalText = Ink.i('modalText'); var streetView = Ink.i('streetView'); var modalLink = document.getElementById('modalLink'); var gmaps = google.maps; var hadHash // sets whether the user is visiting a spot or trying to show someone a spot function setHadHash(hash) { hash = ('' + hash).replace(/#/, '') document.documentElement.className = document.documentElement.className .replace(/(^| )(had-hash|no-had-hash)( |$)/, ' ') // now I have 2 problems document.documentElement.className += hash ? ' had-hash' : ' no-had-hash'; hadHash = hash } setHadHash('' + location.hash) if (hadHash) { initVisitMode(); } else { initShareMode(); } // creating the map Ink.createModule('aa.map', 1, ['Ink.Dom.Event_1', 'Ink.Dom.Element_1'], function (InkEvent, InkElement) { var center = (hadHash ? hadHash : '39.436193,-8.22876'); var map = window.map = new gmaps.Map(mapCanvas, { zoom: 6, center: stringToLatLng(center) }) return map; }); function initShareMode() { // creating the marker Ink.createModule('aa.marker', 1, ['aa.map_1'], function (map) { var marker = window.marker = new google.maps.Marker({ position: map.getCenter(), map: map, draggable: !hadHash, visible: !!hadHash, title: hadHash ? '' : 'clica aqui' }); return marker; }); // listening to events, firing the modal Ink.requireModules(['aa.marker_1', 'aa.map_1', 'Ink.Dom.Event_1', 'Ink.Dom.Element_1', 'Ink.UI.Modal_1'], function (marker, map, InkEvent, InkElement, Modal) { gmaps.event.addListener(map, 'rightclick', onNewMarkerPosition); gmaps.event.addListener(marker, 'dragend', onNewMarkerPosition); gmaps.event.addListener(marker, 'click', function () { var href = latLngToString(marker.getPosition()) window.location.hash = href InkElement.setTextContent(modalLink, window.location + '') modalLink.setAttribute('href', window.location + '') new Modal(modalText, { height: '350px', width: '800px' }) }) function onNewMarkerPosition (ev) { if (hadHash) return; marker.setPosition(new gmaps.LatLng(ev.latLng.lat(), ev.latLng.lng())) marker.setVisible(true) } }); } function initVisitMode() { var geocoder = new google.maps.Geocoder(); geocoder.geocode({'latLng': stringToLatLng(hadHash)}, function(results, status) { var theResult; if (status == google.maps.GeocoderStatus.OK) { theResult = results[1].formatted_address } else { theResult = 'Morada desconhecida' } Ink.createModule('address', 1, [], function () { return theResult; }); }); setTimeout(function () { Ink.createModule('address', 1, [], function () { return 'Morada Desconhecida' }) }, 2000) Ink.requireModules(['Ink.UI.Modal_1', 'Ink.Dom.Element_1', 'address_1'], function (Modal, InkElement, address) { streetView.src = streetViewSvc.endPoint + '&location=' + hadHash + '&key=' + streetViewSvc.apiKey InkElement.setTextContent(Ink.i('address'), address) InkElement.setTextContent(Ink.i('coords'), hadHash.toString().replace(',', ', ')) Ink.i('directions').href = googleMapsDirectionsLink + hadHash new Modal(modalText, { onDismiss: function () { setHadHash(''); initShareMode(); }, width: '800px' }) }) } function round6 (n) { return Math.round(n * 100000) / 100000 } function latLngToString(pos) { return '' + round6(pos.lat()) + ',' + round6(pos.lng()) } function stringToLatLng(s) { var splt = s.split(',') return new gmaps.LatLng(+splt[0], +splt[1]) } }());
JavaScript
0.000001
@@ -3912,24 +3912,160 @@ hareMode();%0A + Ink.requireModules(%5B'aa.marker_1'%5D, function (marker) %7B%0A marker.setVisible(true);%0A %7D)%0A
69efd16a6db1794ae3a719740d296a035e79c7f0
Add missing calls to `util.callbackify`
bin/rebuildPad.js
bin/rebuildPad.js
'use strict'; /* This is a repair tool. It rebuilds an old pad at a new pad location up to a known "good" revision. */ // As of v14, Node.js does not exit when there is an unhandled Promise rejection. Convert an // unhandled rejection into an uncaught exception, which does cause Node.js to exit. process.on('unhandledRejection', (err) => { throw err; }); if (process.argv.length !== 4 && process.argv.length !== 5) { throw new Error('Use: node bin/repairPad.js $PADID $REV [$NEWPADID]'); } const async = require('ep_etherpad-lite/node_modules/async'); const npm = require('ep_etherpad-lite/node_modules/npm'); const util = require('util'); const padId = process.argv[2]; const newRevHead = process.argv[3]; const newPadId = process.argv[4] || `${padId}-rebuilt`; let db, oldPad, newPad; let Pad, PadManager; async.series([ (callback) => npm.load({}, callback), (callback) => { // Get a handle into the database db = require('ep_etherpad-lite/node/db/DB'); db.init(callback); }, (callback) => { Pad = require('ep_etherpad-lite/node/db/Pad').Pad; PadManager = require('ep_etherpad-lite/node/db/PadManager'); // Get references to the original pad and to a newly created pad // HACK: This is a standalone script, so we want to write everything // out to the database immediately. The only problem with this is // that a driver (like the mysql driver) can hardcode these values. db.db.db.settings = {cache: 0, writeInterval: 0, json: true}; // Validate the newPadId if specified and that a pad with that ID does // not already exist to avoid overwriting it. if (!PadManager.isValidPadId(newPadId)) { throw new Error('Cannot create a pad with that id as it is invalid'); } PadManager.doesPadExists(newPadId, (err, exists) => { if (exists) throw new Error('Cannot create a pad with that id as it already exists'); }); PadManager.getPad(padId, (err, pad) => { oldPad = pad; newPad = new Pad(newPadId); callback(); }); }, (callback) => { // Clone all Chat revisions const chatHead = oldPad.chatHead; for (let i = 0, curHeadNum = 0; i <= chatHead; i++) { db.db.get(`pad:${padId}:chat:${i}`, (err, chat) => { db.db.set(`pad:${newPadId}:chat:${curHeadNum++}`, chat); console.log(`Created: Chat Revision: pad:${newPadId}:chat:${curHeadNum}`); }); } callback(); }, (callback) => { // Rebuild Pad from revisions up to and including the new revision head const AuthorManager = require('ep_etherpad-lite/node/db/AuthorManager'); const Changeset = require('ep_etherpad-lite/static/js/Changeset'); // Author attributes are derived from changesets, but there can also be // non-author attributes with specific mappings that changesets depend on // and, AFAICT, cannot be recreated any other way newPad.pool.numToAttrib = oldPad.pool.numToAttrib; for (let curRevNum = 0; curRevNum <= newRevHead; curRevNum++) { db.db.get(`pad:${padId}:revs:${curRevNum}`, (err, rev) => { if (rev.meta) { throw new Error('The specified revision number could not be found.'); } const newRevNum = ++newPad.head; const newRevId = `pad:${newPad.id}:revs:${newRevNum}`; db.db.set(newRevId, rev); AuthorManager.addPad(rev.meta.author, newPad.id); newPad.atext = Changeset.applyToAText(rev.changeset, newPad.atext, newPad.pool); console.log(`Created: Revision: pad:${newPad.id}:revs:${newRevNum}`); if (newRevNum === newRevHead) { callback(); } }); } }, (callback) => { // Add saved revisions up to the new revision head console.log(newPad.head); const newSavedRevisions = []; for (const savedRev of oldPad.savedRevisions) { if (savedRev.revNum <= newRevHead) { newSavedRevisions.push(savedRev); console.log(`Added: Saved Revision: ${savedRev.revNum}`); } } newPad.savedRevisions = newSavedRevisions; callback(); }, (callback) => { // Save the source pad db.db.set(`pad:${newPadId}`, newPad, (err) => { console.log(`Created: Source Pad: pad:${newPadId}`); util.callbackify(newPad.saveToDatabase.bind(newPad))(callback); }); }, ], (err) => { if (err) throw err; console.info('finished'); });
JavaScript
0
@@ -983,15 +983,33 @@ +util.callbackify( db.init +) (cal @@ -1763,24 +1763,41 @@ ;%0A %7D%0A +util.callbackify( PadManager.d @@ -1807,17 +1807,17 @@ PadExist -s +) (newPadI @@ -1938,24 +1938,41 @@ %7D);%0A +util.callbackify( PadManager.g @@ -1976,16 +1976,17 @@ r.getPad +) (padId,
7c74bce8a10ca8896815d6715d9b084ac7bf9977
Add retry logic to downloadFile (#59)
src/downloadFile.js
src/downloadFile.js
import fs from 'fs'; import https from 'https'; export default async function downloadFile(url, dest) { let file = fs.createWriteStream(dest); let response = await new Promise((resolve, reject) => { https.get(url, (response) => { resolve(response); }).on('error', (err) => { reject(err); }); }); response.pipe(file); await new Promise((resolve, reject) => { file.on('finish', () => { file.close(); resolve(); }); file.on('error', (err) => { reject(err); }); }); }
JavaScript
0
@@ -46,23 +46,8 @@ ';%0A%0A -export default asyn @@ -57,17 +57,20 @@ unction -d +tryD ownloadF @@ -230,26 +230,144 @@ -resolve(response); +if (response.statusCode %3C 400) %7B%0A resolve(response);%0A %7D else %7B%0A reject(new Error('Error downloading file.'));%0A %7D %0A @@ -630,12 +630,12 @@ %7D);%0A - %7D);%0A%7D%0A @@ -634,8 +634,370 @@ %7D);%0A%7D%0A +%0Aexport default async function downloadFile(url, dest) %7B%0A for (let i = 0; i %3C 5; i++) %7B%0A console.log(%60Dowloading $%7Burl%7D...%60);%0A try %7B%0A await tryDownloadFile(url, dest);%0A console.log('Success.');%0A return;%0A %7D catch (e) %7B%0A console.log('Error. Retrying...');%0A %7D%0A %7D%0A throw new Error(%60Download of $%7Burl%7D failed after 5 attempts.%60);%0A%7D%0A
02af129651f3032e592b75dd1c5385ebc4deb6e0
Fix update on date.
lib/assets/javascripts/cartodb3/components/modals/publish/publish-view.js
lib/assets/javascripts/cartodb3/components/modals/publish/publish-view.js
var _ = require('underscore'); var moment = require('moment'); var CoreView = require('backbone/core-view'); var template = require('./publish.tpl'); var TabPaneTemplate = require('./tab-pane-submenu.tpl'); var createTextLabelsTabPane = require('../../tab-pane/create-text-labels-tab-pane'); var PublishView = require('./publish/publish-view'); var ShareView = require('./share/share-view'); var PrivacyDropdown = require('../../privacy-dropdown/privacy-dropdown-view'); var PublishButton = require('./publish-button-view'); var ShareWith = require('./share-with-view'); var UpgradeView = require('./upgrade-view'); var REQUIRED_OPTS = [ 'modalModel', 'visDefinitionModel', 'privacyCollection', 'userModel', 'configModel' ]; var MODE_FULL = 'full'; var MODE_SHARE = 'share'; var MODE_PUBLISH = 'publish'; module.exports = CoreView.extend({ className: 'Publish-modal', events: { 'click .js-done': '_onDone' }, initialize: function (opts) { _.each(REQUIRED_OPTS, function (item) { if (opts[item] === undefined) throw new Error(item + ' is required'); this['_' + item] = opts[item]; }, this); // Optional options this._mapcapsCollection = opts.mapcapsCollection; this.mode = opts.mode || MODE_FULL; }, render: function () { this.clearSubViews(); this.$el.html(template({ name: this._visDefinitionModel.get('name'), isSimple: !this._hasTabs(), hasShareStats: this._hasShareStats() })); this._initViews(); if (this.mode === MODE_FULL) { if (!this._hasOrganization()) { this._makePublishView(); } else { this._initTabsViews(); } } else if (this.mode === MODE_SHARE) { this._makeShareView(); } else if (this.mode === MODE_PUBLISH) { this._makePublishView(); } return this; }, _hasShareStats: function () { return this.mode !== MODE_PUBLISH && this._hasOrganization(); }, _hasOrganization: function () { return this._userModel.isInsideOrg(); }, _hasTabs: function () { var hasOrganization = this._hasOrganization(); return hasOrganization && this.mode === MODE_FULL; }, _makePublishView: function () { var view = this._createPublishView(); this.$('.js-panes').append(view.render().el); this.addView(view); }, _makeShareView: function () { var view = this._createShareView(); this.$('.js-panes').append(view.render().el); this.addView(view); }, _initViews: function () { var dropdown; var publishButton; var shareWith; var upgradeView; dropdown = new PrivacyDropdown({ privacyCollection: this._privacyCollection, visDefinitionModel: this._visDefinitionModel, userModel: this._userModel, configModel: this._configModel }); this.$('.js-dropdown').append(dropdown.render().el); this.addView(dropdown); if (this._mapcapsCollection !== undefined) { publishButton = new PublishButton({ visDefinitionModel: this._visDefinitionModel, mapcapsCollection: this._mapcapsCollection, configModel: this._configModel }); this.$('.js-update').append(publishButton.render().el); this.addView(publishButton); } else { this.$('.js-update').html(_t('editor.published', { when: moment(this._visDefinitionModel.get('updated_at')).fromNow() })); } if (this._hasShareStats()) { shareWith = new ShareWith({ visDefinitionModel: this._visDefinitionModel, userModel: this._userModel, avatarClass: 'Share-user--big', separationClass: 'u-rSpace--xl' }); this.$('.js-share-users').append(shareWith.render().el); this.addView(shareWith); } if (!this._hasOrganization()) { upgradeView = new UpgradeView(); this.$('.js-upgrade').append(upgradeView.render().el); this.addView(upgradeView); } }, _initTabsViews: function () { var self = this; var tabPaneTabs = [{ name: 'share', label: _t('components.modals.publish.menu.share'), createContentView: self._createShareView.bind(self) }, { name: 'publish', label: _t('components.modals.publish.menu.publish'), createContentView: self._createPublishView.bind(self) }]; var tabPaneOptions = { tabPaneOptions: { template: TabPaneTemplate, tabPaneItemOptions: { tagName: 'li', className: 'CDB-NavSubmenu-item' } }, tabPaneItemLabelOptions: { tagName: 'button', className: 'CDB-NavSubmenu-link u-upperCase Publish-modalLink' } }; this._layerTabPaneView = createTextLabelsTabPane(tabPaneTabs, tabPaneOptions); this.$('.js-panes').append(this._layerTabPaneView.render().$el); this.addView(this._layerTabPaneView); }, _createShareView: function () { return new ShareView({ className: 'Share-wrapper', currentUserId: this._userModel.id, visDefinitionModel: this._visDefinitionModel, organization: this._userModel._organizationModel, configModel: this._configModel }); }, _createPublishView: function () { return new PublishView({ visDefinitionModel: this._visDefinitionModel, mapcapsCollection: this._mapcapsCollection, userModel: this._userModel }); }, _onDone: function () { this._modalModel.destroy(); } });
JavaScript
0
@@ -2573,16 +2573,37 @@ adeView; +%0A var publishedOn; %0A%0A dr @@ -3268,128 +3268,254 @@ -this.$('.js-update').html(_t('editor.published', %7B when: moment(this._visDefinitionModel.get('updated_at')).fromNow() %7D) +publishedOn = _t('components.modals.publish.share.last-published', %7B date:%0A moment(this._visDefinitionModel.get('updated_at')).format('Do MMMM YYYY, HH:mm')%0A %7D);%0A%0A this.$('.js-update').html(publishedOn );%0A
831e1f7dc92411abe5c40cbaea4748e6d4adce55
Switch to using d3 drag events
packages/system/public/controllers/battle.js
packages/system/public/controllers/battle.js
/*global angular, d3*/ 'use strict'; angular.module('mean.system') .controller('BattleController', ['$scope', 'Global', function ($scope, Global) { $scope.global = Global; console.log( 'Battle started' ); // Game state is contiained in this structure, which is synchronized between devices var gameState, me, opponent, fire, updateArena; // Create SVG to hold game arena var width = 800; var height = 600; var creatureSize = 50; // How big creatures should be var shotSize = 10; // How big shots should be var arena = d3.select('body').append('svg') .attr('width', width) .attr('height', height) .style('fill', '#000000') .append('g'); // Helper functions and behaviours for creatures var positionCreature = function( creature ) { creature .attr('cx', function(d) { return d.position.x; }) .attr('cy', function(d) { return d.position.y; }) .attr('r', creatureSize); }; // Add behaviour for dragging, to shoot var drag = d3.behavior.drag() .origin(function(d) { return d.position; }) .on('dragstart', function( d ) { // Stash away drag start location d._dragStart = { x: d3.event.sourceEvent.x, y: d3.event.sourceEvent.y }; }) .on('dragend', function( d ) { var dragDirection = { x: d3.event.sourceEvent.x - d._dragStart.x, y: d3.event.sourceEvent.y - d._dragStart.y }; //console.log( 'Dragged in direction:' ); //console.log( dragDirection ); var shot = { position: d._dragStart, direction: dragDirection, player: me }; fire( shot ); }); fire = function( shot ) { // Normalize direction var factor = shot.direction.y > 0 ? ( height - shot.position.y - 50 ) / shot.direction.y : ( shot.position.y -50 ) / shot.direction.y; shot.direction.x *= factor; shot.direction.y *= factor; gameState.shots.push( shot ); updateArena(); }; // Rendering, binds actions to SVG elements using d3 updateArena = function() { // Add creatures for player one (assuming it's `me`) var creatures = arena.selectAll( 'circle.me' ) .data( me.creatures ) // Bind creatures data set to selection .enter().append( 'circle' ) .classed('me', true) .call( positionCreature ); // Add creatures for player two (assuming it's the opponent) arena.selectAll( 'circle.opponent' ) .data( opponent.creatures ) // Bind creatures data set to selection .enter().append( 'circle' ) .classed('opponent', true) .call( positionCreature ); // Add health labels var health = arena.selectAll( 'text.health' ) .data( me.creatures.concat( opponent.creatures ) ); health .enter().append( 'text' ) .classed('health', true) .style('fill', '#ff7700') .attr('x', function(d) { return d.position.x; }) .attr('y', function(d) { return d.position.y; }); health .text( function( d ) { return d.health; } ); // Bind drag behaviour to creatures creatures.call( drag ); // Add shots arena.selectAll( 'circle.shot' ) .data( gameState.shots ) .enter().append( 'circle' ) .classed('shot', true) .attr('r', shotSize) .attr('cx', function(d) { return d.position.x; }) .attr('cy', function(d) { return d.position.y; }) .transition() .ease( 'linear' ) .attr('cx', function(d) { return d.position.x + d.direction.x; }) .attr('cy', function(d) { return d.position.y + d.direction.y; }) .each( 'end', function( d, i ) { // Remove shot at end of animation gameState.shots.splice( i, 1 ); // Check if we hit something (pretty terrible hit-testing, should use line/circle intersection) for ( var c in opponent.creatures ) { var creature = opponent.creatures[c]; if ( Math.abs( d.position.x + d.direction.x - creature.position.x ) < 1.1 * creatureSize ) { creature.health -= 10; updateArena(); } } }) .remove(); }; d3.json('system/data.json', function(error, json) { if (error) { return console.warn(error); } gameState = json; // TODO do not hardcode me = gameState.players[0]; opponent = gameState.players[1]; updateArena(); }); }]);
JavaScript
0
@@ -1203,42 +1203,119 @@ rag -start location%0A d._dragStar +points%0A d._dragPoints = %5B%5D;%0A %7D)%0A .on('drag', function( d ) %7B%0A // Stash%0A var poin t = @@ -1338,28 +1338,16 @@ 3.event. -sourceEvent. x,%0A @@ -1367,31 +1367,57 @@ ent. -sourceEvent.y%0A %7D +y%0A %7D; %0A d._dragPoints.push( point ) ;%0A @@ -1476,79 +1476,160 @@ var -dragDirection = %7B%0A x: d3.event.sourceEvent.x - d._dragS +start = d._dragPoints%5B0%5D;%0A var end = d._dragPoints%5Bd._dragPoints.length - 1%5D;%0A console.log( d._dragPoints );%0A console.log( s tart -.x, + ); %0A @@ -1637,46 +1637,110 @@ - y: d3.event.sourceEvent +console.log( end );%0A var dragDirection = %7B%0A x: end.x - start.x,%0A y: end .y - -d._dragS +s tart @@ -1888,16 +1888,9 @@ on: -d._dragS +s tart
12ed1dbfd2cfa2d9c5ef9dd93b1ede0e28c32fdf
Add colored output to repl
bin/ballz-repl.js
bin/ballz-repl.js
#!/usr/bin/env node /*! * BALLZ repl module * * @author pfleidi */ var Readline = require('readline'); var Util = require('util'); var Parser = require('../lib/parser'); var Environment = require('../lib/environment'); var interpreter = require('../lib/interpreter').createInterpreter( Environment.createEnvironment() ); var repl = Readline.createInterface(process.stdin, process.stdout); function exec(cmd) { var ast = Parser.parse(cmd); return Util.inspect(interpreter.eval(ast)); } repl.setPrompt('ballz >'); repl.on('line', function (cmd) { try { console.log('==> ' + exec(cmd)); } catch (e) { console.log(e.message); console.log(e.stack); } repl.prompt(); }); repl.on('SIGINT', function () { repl.close(); }); repl.on('close', function () { console.log('goodbye!'); process.exit(0); }); repl.prompt();
JavaScript
0.000003
@@ -106,20 +106,20 @@ ');%0Avar -Util +Eyes = requi @@ -126,12 +126,12 @@ re(' -util +eyes ');%0A @@ -458,12 +458,12 @@ urn -Util +Eyes .ins
901a3acf21ff024205095fef356a656056c23c91
Add author and gihub
camut_slider.js
camut_slider.js
(function($) { $.fn.camutSlider = function() { $(".slider").each(function (i, el) { // Variables var slider = $(el), // this is the element numSlides = slider.find("li").length, // number of slides width = slider.outerWidth(), height = slider.find("li:eq(0)").outerHeight(), // Not needed, but here for future use count = 0; // Generic counter so we can keep track of slides // Setup: var settings = { arrows: true, dots: true, auto: true, // Make the slides cycle on their own interval: 6000, // the time between slides speed: 1 // number of seconds that the slider transitions should be }; // Override the default settings if the data attributes are set for (var key in settings) { if (slider.data(key) !== undefined) { settings[key] = slider.data(key); } } function placeSlider(width, speed) { if (speed === undefined) {speed = settings.speed;} slider.find(".slides").css({ "-webkit-transform": "translate3d(" + (-count * width) + "px, 0px, 0px)", "-webkit-transition": speed + "s ease", "-moz-transform": "translate3d(" + (-count * width) + "px, 0px, 0px)", "-moz-transition": speed + "s ease", "-ms-transform": "translate3d(" + (-count * width) + "px, 0px, 0px)", "-ms-transition": speed + "s ease", "-o-transform": "translate3d(" + (-count * width) + "px, 0px, 0px)", "-o-transition": speed + "s ease", "transform": "translate3d(" + (-count * width) + "px, 0px, 0px)", "transition": speed + "s ease" }); } function placeSlides(width, speed) { if (speed === undefined) {speed = settings.speed;} slider.find("li").each(function (j, elj) { $(this).css({ "left": j * width, "-webkit-transition": speed + "s ease", "-moz-transition": speed + "s ease", "-ms-transition": speed + "s ease", "-o-transition": speed + "s ease", "transition": speed + "s ease" }); }); } placeSlides(width); $(window).bind("resize load", function() { width = slider.outerWidth(); placeSlides(width, 0); placeSlider(width, 0); }); // Make the first slider have an active class slider.find("li:eq(0)").addClass("active"); // Add the dot selectors if (settings.dots && numSlides > 1) { var counter = $("<ol class='dots'></ol>"), dot = $("<li></li>"); slider.append(counter); for (var k = 0; k < numSlides; k++) { counter.append(dot.clone()); } var cWidth = counter.outerWidth(); counter.css("margin-left", (-cWidth / 2) + "px"); counter.find("li:eq(0)").addClass("active"); } // Add the arrows if (settings.arrows && numSlides > 1) { var arrows = $("<a href='#' class='arrow prev'></a><a href='#' class='arrow next'></a>"); slider.append(arrows); } // Auto slide settingsuration var slideAuto = { totalSeconds: 0, start: function () { var self = this; this.interval = setInterval(function () { count++; if (count === numSlides) { count = 0; } slideEm(count, width); }, settings.interval); }, pause: function () { clearInterval(this.interval); delete this.interval; }, resume: function () { if (!this.interval) this.start(); } }; slideAuto.start(); // Click function for the arrows slider.find(".arrow").click(function (e) { e.preventDefault(); slideAuto.pause(); var arrow = $(this), prev = arrow.hasClass("prev"), next = arrow.hasClass("next"); if (prev) { count--; } else { count++; } if (count === numSlides) { count = 0; } else if (count < 0) { count = numSlides - 1; } slideEm(count, width); setTimeout(function () { slideAuto.resume(); }, 1000); }); // Click function for the dots slider.find(".dots li").click(function () { slideAuto.pause(); var index = $(this).index(); count = index; if (count === numSlides) { count = 0; } else if (count < 0) { count = numSlides - 1; } slideEm(count, width); setTimeout(function () { slideAuto.resume(); }, 1000); }); // Bind mouse hover to pause and resume slider slider.bind("mouseover", function(){ slideAuto.pause(); }); slider.bind("mouseleave", function(){ slideAuto.resume(); }); // This is the function that makes the sliders slide function slideEm(count, width) { placeSlider(width); // Handling active classes of dots and slides slider.find(".slides li").removeClass("active"); setTimeout(function () { slider.find(".slides li:eq(" + count + ")").addClass("active"); }, settings.speed * 1000); // Waits until the animation occurs to add the active class slider.find("ol.dots li").removeClass("active"); slider.find("ol.dots li:eq(" + count + ")").addClass("active"); } }); } // The End! }(jQuery));
JavaScript
0
@@ -1,16 +1,102 @@ +/*%0A%09@author: Jim Camut%0A%09Github: https://github.com/jimcamut/Simple-jQuery-Slider%0A*/%0A%0A%0A (function($) %7B%0A%0A @@ -6934,8 +6934,9 @@ Query)); +%0A
595a6b264bc8865f11b54988d93238e16573d0f8
format nested
ckstyle/entity/nestedstatement.js
ckstyle/entity/nestedstatement.js
var helper = require('./entityutil'); Cleaner = helper.Cleaner; var doExtraDetect = require('../browsers/Hacks').doExtraDetect var ALL = require('../browsers/BinaryRule').ALL function NestedStatement(selector, statement, comments, styleSheet) { var self = this; self.extra = true self.nested = true self.selector = Cleaner.clearSelector(selector) self.statement = statement.trim() self.roughStatement = statement self.roughSelector = selector self.comments = comments.trim() self.styleSheet = styleSheet self.fixedSelector = '' self.fixedStatement = '' self.compressedStatement = '' self.browser = doExtraDetect(self.selector) self.toBeUsed = {} self.innerStyleSheet = null } NestedStatement.prototype.rebase = function() { var self = this; self.fixedSelector = '' self.fixedStatement = '' } NestedStatement.prototype.compress = function(browser) { browser = browser || ALL; var self = this; if (!(self.browser & browser)) return '' var value = self._compressedStatement(browser); if (value == '{}') { return '' } return self.fixedSelector + value } NestedStatement.prototype.fixed = function(config) { var self = this; self.fixedSelector = self.fixedSelector || self.selector self.fixedStatement = self.fixedStatement || self.statement // if (self.innerStyleSheet) { // self.fixedStatement = self.innerStyleSheet.fixed(config) // } return self.fixedSelector + ' {\n ' + self.fixedStatement.split('\n').join('\n ') + '\n}' } NestedStatement.prototype._compressedStatement = function(browser) { var self = this; var stmt = self.compressedStatement if (!stmt) { stmt = Cleaner.clean(self.fixedStatement); if (self.innerStyleSheet) { stmt = self.innerStyleSheet.compress(browser) } } return '{' + stmt + '}' } NestedStatement.prototype.toString = function () { var self = this; return self.statement } module.exports = NestedStatement;
JavaScript
0.000004
@@ -1302,24 +1302,29 @@ elector%0A +if (! self.fixedSt @@ -1335,59 +1335,65 @@ ent -= +&& self. -fixedStatement %7C%7C self.statement%0A // if ( +innerStyleSheet) %7B%0A self.fixedStatement = self @@ -1412,19 +1412,29 @@ heet -) %7B +.fixed(config) %0A -// +%7D%0A @@ -1464,46 +1464,40 @@ elf. -innerStyleSheet.fixed(config)%0A // %7D +fixedStatement %7C%7C self.statement %0A
7464ca5a5d6d69b706d6a74a7d270ec7be18f670
Order config options
extension.js
extension.js
var vscode = require('vscode'); var renderTableInOutputChannel = require('./view'); var fzCalculator = require('filesize-calculator'); var window = vscode.window; var workspace = vscode.workspace; var cachedLocation = 'left'; var statusBarItem, oc, info, config, isShowingDetailedInfo; function updateConfig() { var configuration = workspace.getConfiguration('filesize'); config = { useDecimal: configuration.get('useDecimal'), use24HourFormat: configuration.get('use24HourFormat'), showGzip: configuration.get('showGzip'), showGzipInStatusBar: configuration.get('showGzipInStatusBar'), displayInfoOnTheRightSideOfStatusBar: configuration.get('displayInfoOnTheRightSideOfStatusBar') }; updateStatusBarItem(); return config; } function showStatusBarItem(newInfo) { info = fzCalculator.addPrettySize(newInfo, config); if (info && info.prettySize) { statusBarItem.text = info.prettySize; if (config.showGzipInStatusBar) { statusBarItem.text = `Min: ${info.prettySize}`; info = fzCalculator.addGzipSize(info, config); statusBarItem.text += ` | Gzip: ${info.gzipSize}` } statusBarItem.show(); } } function hideStatusBarItem() { hideDetailedInfo(); statusBarItem.text = ''; statusBarItem.hide(); } // Update simple info in the status bar function updateStatusBarItem() { // Check where to display the status bar var location = config.displayInfoOnTheRightSideOfStatusBar ? 'right' : 'left'; // Set up statusBarItem if (cachedLocation !== location) { cachedLocation = location; if (location === 'right') { statusBarItem = window.createStatusBarItem(vscode.StatusBarAlignment.Right, 1); } else { statusBarItem = window.createStatusBarItem(vscode.StatusBarAlignment.Left, 1); } statusBarItem.command = 'extension.toggleFilesizeInfo'; statusBarItem.tooltip = 'Current file size - Click to toggle more info'; } try { var currentEditor = window.activeTextEditor.document; if (currentEditor && currentEditor.uri.scheme === 'file') { hideDetailedInfo(); showStatusBarItem(fzCalculator.loadFileInfoSync(currentEditor.fileName)); } else { if (currentEditor.uri.scheme !== 'output') hideStatusBarItem(); } } catch (e) { hideStatusBarItem(); } } // Show detailed filesize info in the OC function showDetailedInfo() { if (info && info.prettySize) { info = config.showGzip ? fzCalculator.addGzipSize(info, config) : info; info = fzCalculator.addMimeTypeInfo(info); info = fzCalculator.addPrettyDateInfo(info, config); const table = []; if (info.prettySize) table.push({ header: 'Size', content: info.prettySize }); if (info.gzipSize) table.push({ header: 'Gzipped', content: info.gzipSize }); if (info.mimeType) table.push({ header: 'Mime type', content: info.mimeType }); if (info.prettyDateCreated) table.push({ header: 'Created', content: info.prettyDateCreated }); if (info.prettyDateChanged) table.push({ header: 'Changed', content: info.prettyDateChanged }); renderTableInOutputChannel(oc, info.absolutePath, table); } else { oc.clear(); oc.appendLine('No file information available for this context!'); } oc.show(true); isShowingDetailedInfo = true; } function hideDetailedInfo() { oc.hide(); isShowingDetailedInfo = false; } function toggleDetailedInfo() { if (isShowingDetailedInfo) { hideDetailedInfo(); } else { showDetailedInfo(); } } // Called when VS Code activates the extension function activate(context) { console.log('filesize is active'); // Set up statusBarItem statusBarItem = window.createStatusBarItem(vscode.StatusBarAlignment.Left, 1); statusBarItem.command = 'extension.toggleFilesizeInfo'; statusBarItem.tooltip = 'Current file size - Click to toggle more info'; // Global OutputChannel to be used for the extension detailed info oc = window.createOutputChannel('filesize'); // Update handlers var onSave = workspace.onDidSaveTextDocument(updateStatusBarItem); var onActiveEditorChanged = window.onDidChangeActiveTextEditor(updateStatusBarItem); var onChangeConfig = workspace.onDidChangeConfiguration(updateConfig); // Show detailed info through custom command var command = vscode.commands.registerCommand('extension.toggleFilesizeInfo', toggleDetailedInfo); // Register disposables that get disposed when deactivating context.subscriptions.push(onSave); context.subscriptions.push(onChangeConfig); context.subscriptions.push(onActiveEditorChanged); context.subscriptions.push(command); // Set default config updateConfig(); } // Called when VS Code deactivates the extension function deactivate() { if (oc) { oc.clear(); oc.dispose(); } if (statusBarItem) { statusBarItem.hide(); statusBarItem.dispose(); } oc = null; statusBarItem = null; config = null; info = null; } module.exports = { activate: activate, deactivate: deactivate };
JavaScript
0.000001
@@ -703,16 +703,132 @@ tusBar') +,%0A showBrotli: configuration.get('showBrotli'),%0A showGzipInStatusBar: configuration.get('showGzipInStatusBar') %0A %7D;%0A @@ -2591,16 +2591,96 @@ : info;%0A + info = config.showBrotli ? fzCalculator.addBrotliSize(info, config) : info;%0A info @@ -2954,32 +2954,117 @@ fo.gzipSize %7D);%0A + if (info.brotliSize) table.push(%7B header: 'Brotli', content: info.brotliSize %7D);%0A if (info.mim
23720759e3a31557468ee6a7041a3d6e48d4f5d3
remove jquery
addon/mixins/active-link.js
addon/mixins/active-link.js
import Ember from 'ember'; // these are not currently editable in Ember const transitioningInClass = 'ember-transitioning-in'; const transitioningOutClass = 'ember-transitioning-out'; export default Ember.Mixin.create({ classNameBindings: ['_active','_disabled','_transitioningIn','_transitioningOut'], linkSelector: 'a.ember-view', init() { this._super(...arguments); this.set('childLinkViews', Ember.A([])); }, buildChildLinkViews: Ember.on('didInsertElement', function(){ Ember.run.scheduleOnce('afterRender', this, function(){ let childLinkSelector = this.get('linkSelector'); let childLinkElements = this.$(childLinkSelector); let viewRegistry = Ember.getOwner(this).lookup('-view-registry:main'); let childLinkViews = childLinkElements.toArray().map( view => viewRegistry[view.id] ); this.set('childLinkViews', Ember.A(childLinkViews)); }); }), _transitioningIn: Ember.computed('[email protected]', function(){ if (this.get('childLinkViews').isAny('transitioningIn')) { return transitioningInClass; } }), _transitioningOut: Ember.computed('[email protected]', function(){ if (this.get('childLinkViews').isAny('transitioningOut')) { return transitioningOutClass; } }), hasActiveLinks: Ember.computed('[email protected]', function(){ return this.get('childLinkViews').isAny('active'); }), activeClass: Ember.computed('[email protected]', function(){ let activeLink = this.get('childLinkViews').findBy('active'); return (activeLink ? activeLink.get('active') : 'active'); }), _active: Ember.computed('hasActiveLinks', 'activeClass', function(){ return (this.get('hasActiveLinks') ? this.get('activeClass') : false); }), allLinksDisabled: Ember.computed('[email protected]', function(){ return !Ember.isEmpty(this.get('childLinkViews')) && this.get('childLinkViews').isEvery('disabled'); }), disabledClass: Ember.computed('[email protected]', function(){ let disabledLink = this.get('childLinkViews').findBy('disabled'); return (disabledLink ? disabledLink.get('disabled') : 'disabled'); }), _disabled: Ember.computed('allLinksDisabled', 'disabledClass', function(){ return (this.get('allLinksDisabled') ? this.get('disabledClass') : false); }) });
JavaScript
0.000001
@@ -649,9 +649,32 @@ his. -$ +element.querySelectorAll (chi @@ -795,16 +795,41 @@ Views = +Array.prototype.map.call( childLin @@ -841,23 +841,9 @@ ents -.toArray().map( +, %0A
42674d6ba86948b868d7e5458990f89ea9bfefd9
Clean up login page
src/js/components/handlers/login-page.js
src/js/components/handlers/login-page.js
'use strict'; var h = require('react-hyperscript'); var React = require('react'); var Router = require('react-router'); var SessionActions = require('../../actions/session.actions'); var SessionStore = require('../../stores/session.store'); var LoginPage = React.createClass({ displayName: 'LoginPage', mixins: [Router.State, Router.Navigation], getInitialState: function getInitialState() { return { applicationStats: {} }; }, componentDidMount: function componentDidMount() { SessionStore.addChangeListener(this._onChange); React.findDOMNode(this.refs.email).focus(); }, componentWillUnmount: function componentWillUnmount() { SessionStore.removeChangeListener(this._onChange); }, _onChange: function _onChange() { this.setState({ currentUser: SessionStore.getCurrentUser() }); if (this.state.currentUser) { this.transitionTo('dashboard'); } }, _onFormChange: function _onFormChange(event) { var target = event.target; var state = {}; state[target.id] = target.value; this.setState(state); }, _onSubmit: function _onSubmit(event) { event.preventDefault(); var request = { email: this.state.email, password: this.state.password }; SessionActions.login(request); }, render: function render() { return ( h('div', {className: 'row'}, [ h('section', {className: 'col-md-12'}, [ h('div', {className: 'page__header'}, [ h('h1', {className: 'page__title'}, 'Tools Login') ]) ]), h('section', {className: 'col-md-12'}, [ h('div', {className: 'page__body'}, [ h('div', {className: 'row'}, [ h('div', {className: 'col-md-4'}, [ h('form', [ h('div', {className: 'form-group'}, [ h('label', {htmlFor: 'email'}, 'Email address'), h('input', { type: 'text', id: 'email', ref: 'email', onChange: this._onFormChange }) ]), h('div', {className: 'form-group'}, [ h('label', {htmlFor: 'password'}, 'Password'), h('input', { type: 'password', id: 'password', onChange: this._onFormChange }) ]), h('div', {className: 'form-group'}, [ h('button', { className: 'btn btn-default', // type: 'submit', onClick: this._onSubmit }, 'Login') ]) ]) ]) ]) ]) ]) ]) ); } }); module.exports = LoginPage;
JavaScript
0
@@ -1364,35 +1364,41 @@ ', %7BclassName: ' -row +container '%7D, %5B%0A h( @@ -1390,39 +1390,35 @@ %7D, %5B%0A h(' -section +div ', %7BclassName: ' @@ -1413,33 +1413,27 @@ className: ' -col-md-12 +row '%7D, %5B%0A @@ -1462,20 +1462,32 @@ e: ' -page__header +col-md-4 col-md-offset-4 '%7D, @@ -1507,10 +1507,11 @@ h(' -h1 +div ', %7B @@ -1528,61 +1528,37 @@ 'pa -ge__title'%7D, 'Tools Login')%0A %5D)%0A %5D),%0A +nel panel-default'%7D, %5B%0A @@ -1568,15 +1568,11 @@ h(' -section +div ', %7B @@ -1587,17 +1587,21 @@ e: ' -col-md-12 +panel-heading '%7D, @@ -1604,38 +1604,43 @@ '%7D, %5B%0A + + h(' -div +h3 ', %7BclassName: ' @@ -1645,64 +1645,53 @@ 'pa -ge__body'%7D, %5B%0A h('div', %7BclassName: 'row'%7D, %5B +nel-title'%7D, 'Tools Login')%0A %5D), %0A @@ -1723,24 +1723,26 @@ sName: ' -col-md-4 +panel-body '%7D, %5B%0A @@ -1957,24 +1957,73 @@ pe: 'text',%0A + className: 'form-control',%0A @@ -2365,32 +2365,81 @@ pe: 'password',%0A + className: 'form-control',%0A @@ -2642,24 +2642,24 @@ 'button', %7B%0A + @@ -2702,49 +2702,8 @@ t',%0A - // type: 'submit',%0A
720c6ef160c7511b83e2cf6548a5b2abeeaac221
update key shortcut docs
js/plugins/keyShortcuts.js
js/plugins/keyShortcuts.js
/** Copyright 2014 Gordon Williams ([email protected]) This Source Code is subject to the terms of the Mozilla Public License, v2.0. If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. ------------------------------------------------------------------ Key shortcuts for IDE (the editor/etc often add their own) ------------------------------------------------------------------ **/ "use strict"; (function(){ var SHORTCUTS = { // Map key combination to an ACTION (below) "Ctrl + `" : "TOGGLE_TERMINAL_EDITOR", "Ctrl + O" : "icon-openFile", "Ctrl + S" : "icon-saveFile", "Ctrl + U" : "icon-deploy", "Shift + ENTER" : "UPLOAD_SELECTED" }; /* ACTIONS: Are either implemented in `action` function. or `icon-` prefixed actions, eg `icon-deploy` will 'click' the relevant icon */ var BUILTIN_SHORTCUTS = { "Ctrl + C / Cmd + C" : "Copy (simple drag and release copies from the Terminal Window)", "Ctrl + V / Cmd + V" : "Paste", "Alt + ENTER" : "(In REPL) Create new line without executing", "Ctrl + F / Cmd-F" : "Start searching (in editor), Fullscreen (in terminal)", "Ctrl + G / Cmd-G" : "Find next", "Shift + Ctrl + G / Shift + Cmd-G" : "Find previous", "Shift + Ctrl + F / Cmd + Option +F" : "Replace", "Shift + Ctrl + R / Shift + Cmd + Option + F" : "Replace all", "Ctrl + Space" : "Autocomplete", "Ctrl + I" : "Find type at cursor", "Alt + ." : "Jump to definition (Alt-, to jump back)", "Ctrl + Q" : "Rename variable", "Ctrl + ." : "Select all occurrences of a variable", } function init() { window.addEventListener("keydown",function(e) { var key = (""+e.key).toUpperCase(); if (e.shiftKey) key = "Shift + "+key; if (e.altKey) key = "Alt + "+key; if (e.ctrlKey) key = "Ctrl + "+key; if (e.metaKey) key = "Cmd + "+key; //console.log(key); var actionName = SHORTCUTS[key]; if (actionName!==undefined) { e.preventDefault(); console.log("Key Shortcut "+key+" => "+actionName); action(actionName); } }); } function action(name, getDescription) { if (name.startsWith("icon-")) { var icon = document.getElementById(name); if (icon!==null) { if (getDescription) return icon.getAttribute("title"); else icon.click(); return; } } switch (name) { case "TOGGLE_TERMINAL_EDITOR": if(getDescription) return "Toggle between typing in the Terminal or Code Editor"; if (Espruino.Core.Terminal.hasFocus()) Espruino.Core.Code.focus(); else Espruino.Core.Terminal.focus(); break; case "UPLOAD_SELECTED": if(getDescription) return "Upload just the text that is selected in the editor pane"; if (Espruino.Core.Code.isInBlockly()) return; var selectedCode = Espruino.Core.EditorJavaScript.getSelectedCode().trim(); if (selectedCode) { Espruino.Core.MenuPortSelector.ensureConnected(function() { var old_RESET_BEFORE_SEND = Espruino.Config.RESET_BEFORE_SEND; /* No need to tweak SAVE_ON_SEND/etc because by calling writeToEspruino we skip the usual pipeline of code modifications. But maybe we shouldn't? Could then do compiled code/etc on demand too. */ Espruino.Config.RESET_BEFORE_SEND = false; Espruino.Core.CodeWriter.writeToEspruino(selectedCode,function(){ Espruino.Config.RESET_BEFORE_SEND = old_RESET_BEFORE_SEND; }); }); } break; default: console.log("keyShortcuts.js: Unknown Action "+JSON.stringify(name)); } } function getShortcutDescriptions() { var desc = {}; Object.keys(BUILTIN_SHORTCUTS).forEach(function(key) { desc[key] = BUILTIN_SHORTCUTS[key]; }); Object.keys(SHORTCUTS).forEach(function(key) { desc[key] = action(SHORTCUTS[key], true); }); return desc; } Espruino.Plugins.KeyShortcuts = { init : init, action : action, // perform action, or using action("...",true) get the description getShortcutDescriptions : getShortcutDescriptions, // get a map of shortcut key -> description SHORTCUTS : SHORTCUTS, // public to allow shortcuts to be added easily }; }());
JavaScript
0
@@ -1447,41 +1447,46 @@ l + -I +B %22 : %22 -Find type +Beautify (reform at +) c -ursor +ode %22,%0A %22 Alt @@ -1485,59 +1485,40 @@ %22 -Alt + . +Ctrl + I %22 : %22 -Jump to definition (Alt-, to jump back) +Find type at cursor %22,%0A @@ -1609,16 +1609,75 @@ iable%22,%0A + %22Alt + .%22 : %22Jump to definition (Alt-, to jump back)%22,%0A %7D%0A%0A f
6f079e8165464ad92bc0ab77e7dca532a9f02ca2
revert weird table export
packages/veritone-widgets/src/build-entry.js
packages/veritone-widgets/src/build-entry.js
import r from 'regenerator-runtime/runtime'; window.regeneratorRuntime = r; export VeritoneApp from './shared/VeritoneApp'; export AppBar, { AppBarWidget } from './widgets/AppBar'; export OAuthLoginButton, { OAuthLoginButtonWidget } from './widgets/OAuthLoginButton'; export FilePicker, { FilePickerWidget } from './widgets/FilePicker'; export filePickerReducer, * as filePickerModule from './redux/modules/filePicker'; export filePickerSaga from './redux/modules/filePicker/filePickerSaga'; export { EngineSelectionWidget } from './widgets/EngineSelection'; export { TableWidget as Table, TableWidget } from './widgets/Table'; export { GlobalNotificationDialog, GlobalSnackBar } from './widgets/Notifications'; export notificationsReducer, * as notificationsModule from './redux/modules/notifications'; export { MediaPlayer } from './widgets/MediaPlayer'; export MediaPlayerControlBar from './widgets/MediaPlayer/DefaultControlBar'; export EngineOutputExport, { EngineOutputExportWidget } from './widgets/EngineOutputExport'; export engineOutputExportReducer, * as engineOutputExportModule from './redux/modules/engineOutputExport'; export { SchedulerWidget } from './widgets/Scheduler'; export { UserProfileWidget } from './widgets/UserProfile';
JavaScript
0
@@ -567,30 +567,8 @@ rt %7B - TableWidget as Table, Tab
35d0626d1bf44fcd9876766e1d2a9a7ac4d6678b
use inherited calendar url method
workers/county_parks/index.js
workers/county_parks/index.js
var log4js = require("log4js"), log = log4js.getLogger("megapis-worker"), request = require("request"), moment = require("moment-timezone"), util = require("util"); var MegapisWorker = require("megapis-worker").MegapisWorker; function Worker(config) { Worker.super_.call(this, config); } util.inherits(Worker, MegapisWorker); exports.createWorker = function(config) { return new Worker(config); }; Worker.prototype.getConfigKeys = function() { return ["output"]; }; Worker.prototype.run = function() { var self = this; request(this.config.url, function(error, response, body) { if (error) { log.error("error loading url ", error); return; } var events = eval(body); var today = moment().format("YYYYMMDD"); var maxDate = moment().add(10, "days").format("YYYYMMDD"); var upcoming = []; sccgovEventsCalendar.forEach(function(ev) { if (ev.eventDate < today || ev.eventDate > maxDate) { return; } var dt = moment(ev.eventDate, "YYYYMMDD"); // 20140127T224000Z/20140320T221500Z var startDt = moment(ev.eventDate+" "+ev.start, "YYYYMMDD hh:mm A"); var endDt = moment(ev.eventDate+" "+ev.end, "YYYYMMDD hh:mm A"); var calDate = startDt.tz("UTC").format("YYYYMMDDTHHmm00")+"Z/"+ endDt.tz("UTC").format("YYYYMMDDTHHmm00")+"Z"; var calendarUrl = "https://www.google.com/calendar/render?action=TEMPLATE&text="+ encodeURI(ev.eventDescription)+"&dates="+calDate+"&details="+ encodeURI(ev.desc)+"&location="+encodeURI(ev.locname)+ "&sf=true&output=xml"; upcoming.push({ date: dt.format("ddd M/D"), dt: ev.eventDate, url: ev.url, calendarUrl: calendarUrl, description: ev.desc, title: ev.eventDescription, time: ev.start+' - '+ev.end, location: ev.locname }); }); // sort by date upcoming.sort(function(a, b) { return a.dt - b.dt; }); log.info("found "+upcoming.length+" county parks events"); self.saveAndForward(upcoming); //self.saveAndForward([{x:1}]); }); };
JavaScript
0.000001
@@ -487,19 +487,26 @@ %22output%22 +, %22url%22 %5D;%0A - %7D;%0A%0AWork @@ -1321,429 +1321,8 @@ A%22); -%0A var calDate = startDt.tz(%22UTC%22).format(%22YYYYMMDDTHHmm00%22)+%22Z/%22+%0A endDt.tz(%22UTC%22).format(%22YYYYMMDDTHHmm00%22)+%22Z%22;%0A var calendarUrl = %22https://www.google.com/calendar/render?action=TEMPLATE&text=%22+%0A encodeURI(ev.eventDescription)+%22&dates=%22+calDate+%22&details=%22+%0A encodeURI(ev.desc)+%22&location=%22+encodeURI(ev.locname)+%0A %22&sf=true&output=xml%22; %0A%0A @@ -1483,17 +1483,25 @@ darUrl: -c +self.getC alendarU @@ -1502,16 +1502,74 @@ endarUrl +(startDt, endDt, ev.eventDescription, ev.desc, ev.locname) ,%0A @@ -1924,24 +1924,24 @@ s events%22);%0A + self @@ -1971,48 +1971,8 @@ g);%0A - //self.saveAndForward(%5B%7Bx:1%7D%5D);%0A
c5b2eed2d9a6fd6209b94b79213c17b505830a09
Add configuration for MAX_CONCURRENT_OFFERS
bin/storjshare.js
bin/storjshare.js
#!/usr/bin/env node 'use strict'; var fs = require('fs'); var path = require('path'); var program = require('commander'); var storj = require('storj'); var platform = require('os').platform(); var prompt = require('prompt'); var colors = require('colors/safe'); var Logger = require('kad-logger-json'); var WizardSchema = require('../lib/wizard-schema'); var UnlockSchema = require('../lib/unlock-schema'); var TelemetryReporter = require('storj-telemetry-reporter'); var reporter = require('../lib/reporter'); var utils = require('../lib/utils'); var log = require('../lib/logger'); var HOME = platform !== 'win32' ? process.env.HOME : process.env.USERPROFILE; var CONFNAME = 'config.json'; prompt.message = colors.bold.cyan(' [...]'); prompt.delimiter = colors.cyan(' > '); program.version( 'StorjShare: ' + require('../package').version + '\n' + 'Core: ' + storj.version.software + '\n' + 'Protocol: ' + storj.version.protocol ); var ACTIONS = { start: function start(env) { if (!fs.existsSync(env.datadir)) { log( 'error', 'The datadir does not exist, run: storjshare setup --datadir %s', [env.datadir] ); process.exit(); } if (!fs.existsSync(path.join(env.datadir, CONFNAME))) { log( 'error', 'No configuration found in datadir, run: storjshare setup --datadir %s', [env.datadir] ); process.exit(); } var config = JSON.parse( fs.readFileSync(path.join(env.datadir, CONFNAME)).toString() ); var privkey = fs.readFileSync(config.keypath).toString(); function open(passwd, privkey) { try { privkey = utils.decrypt(passwd, privkey); } catch (err) { log('error', 'Failed to unlock private key, incorrect password'); process.exit(); } var keypair = storj.KeyPair(privkey); var farmerconf = { keypair: keypair, payment: { address: config.address }, storage: { path: env.datadir, size: config.storage.size, unit: config.storage.unit }, address: config.network.address, port: config.network.port, seeds: config.network.seeds, noforward: !config.network.forward, logger: new Logger(config.loglevel), tunport: config.network.tunnelport, tunnels: config.network.tunnels, gateways: config.network.gateways, opcodes: !Array.isArray(config.network.opcodes) ? storj.FarmerInterface.DEFAULTS.opcodes : config.network.opcodes.map(utils.opcodeUpdate) }; farmerconf.logger.pipe(process.stdout); var farmer = new storj.FarmerInterface(farmerconf); farmer.join(function(err) { if (err) { log('error', err.message); process.exit(); } }); if (config.telemetry.enabled) { try { reporter.report(TelemetryReporter( config.telemetry.service, keypair ), config, farmer); } catch (err) { farmerconf.logger.error( 'telemetry reporter failed, reason: %s', err.message ); } } } if (env.password) { open(env.password, privkey); } else { prompt.start(); prompt.get(UnlockSchema(program), function(err, result) { if (err) { return log('error', err.message); } open(result.password, privkey); }); } }, setup: function setup(env) { if (typeof env === 'string') { return log('error', 'Invalid argument supplied: %s', [env]); } if (!fs.existsSync(env.datadir)) { prompt.start(); prompt.get(WizardSchema(env), function(err, result) { if (err) { return log('error', err.message); } var size = parseFloat(result.space); var unit = result.space.split(size.toString())[1]; var config = { keypath: result.keypath, address: result.payto, storage: { path: result.datadir, size: size, unit: unit }, network: { address: result.address, port: result.port, seeds: result.seed ? [result.seed] : [], opcodes: ['0f01020202', '0f02020202', '0f03020202'], forward: result.forward, tunnels: result.tunnels, tunnelport: result.tunnelport, gateways: { min: result.gatewaysmin, max: result.gatewaysmax } }, telemetry: { service: 'https://status.storj.io', enabled: result.telemetry }, loglevel: result.loglevel }; fs.writeFileSync( path.join(result.datadir, CONFNAME), JSON.stringify(config, null, 2) ); fs.writeFileSync( config.keypath, utils.encrypt(result.password, storj.KeyPair().getPrivateKey()) ); log( 'info', 'Setup complete! Start farming with: storjshare start --datadir %s', [result.datadir] ); }); } else { log('error', 'Directory %s already exists', [env.datadir]); } }, fallthrough: function fallthrough(command) { log( 'error', 'Unknown command "%s", please use --help for assistance', command ); program.help(); } }; program .command('start') .description('begins farming data using the provided datadir') .option( '-d, --datadir <path>', 'Set configuration and storage path', path.join(HOME, '.storjshare') ) .option( '-p, --password [password]', 'Password to unlock your private key', '' ) .action(ACTIONS.start); program .command('setup') .description('launches interactive configuration wizard') .option( '-d, --datadir [path]', 'Set configuration and storage path', path.join(HOME, '.storjshare') ) .action(ACTIONS.setup); program .command('*') .description('prints the usage information to the console') .action(ACTIONS.fallthrough); program.parse(process.argv); if (process.argv.length < 3) { return program.help(); }
JavaScript
0.000023
@@ -2124,32 +2124,198 @@ etwork.address,%0A + concurrency: !config.network.concurrency ?%0A storj.FarmerInterface.DEFAULTS.concurrency :%0A config.network.concurrency,%0A port: co
fb706c23873afa65ed83f351184448670f202540
Use self instead of this to refer to state constants
XMLHttpRequest.js
XMLHttpRequest.js
/** * Wrapper for built-in http.js to emulate the browser XMLHttpRequest object. * * This can be used with JS designed for browsers to improve reuse of code and * allow the use of existing libraries. * * Usage: include("XMLHttpRequest.js") and use XMLHttpRequest per W3C specs. * * @todo SSL Support * @author Dan DeFelippi <[email protected]> * @license MIT */ exports.XMLHttpRequest = function() { /** * Private variables */ var self = this; var http = require('http'); // Holds http.js objects var client; var request; var response; // Request settings var settings = {}; // Set some default headers var defaultHeaders = { "User-Agent": "node.js", "Accept": "*/*", }; var headers = defaultHeaders; /** * Constants */ this.UNSENT = 0; this.OPENED = 1; this.HEADERS_RECEIVED = 2; this.LOADING = 3; this.DONE = 4; /** * Public vars */ // Current state this.readyState = this.UNSENT; // default ready state change handler in case one is not set or is set late this.onreadystatechange = function() {}; // Result & response this.responseText = ""; this.responseXML = ""; this.status = null; this.statusText = null; /** * Open the connection. Currently supports local server requests. * * @param string method Connection method (eg GET, POST) * @param string url URL for the connection. * @param boolean async Asynchronous connection. Default is true. * @param string user Username for basic authentication (optional) * @param string password Password for basic authentication (optional) */ this.open = function(method, url, async, user, password) { settings = { "method": method, "url": url, "async": async, "user": user, "password": password }; this.abort(); setState(this.OPENED); }; /** * Sets a header for the request. * * @param string header Header name * @param string value Header value */ this.setRequestHeader = function(header, value) { headers[header] = value; }; /** * Gets a header from the server response. * * @param string header Name of header to get. * @return string Text of the header or null if it doesn't exist. */ this.getResponseHeader = function(header) { if (this.readyState > this.OPENED && response.headers[header]) { return header + ": " + response.headers[header]; } return null; }; /** * Gets all the response headers. * * @return string */ this.getAllResponseHeaders = function() { if (this.readyState < this.HEADERS_RECEIVED) { throw "INVALID_STATE_ERR: Headers have not been received."; } var result = ""; for (var i in response.headers) { result += i + ": " + response.headers[i] + "\r\n"; } return result.substr(0, result.length - 2); }; /** * Sends the request to the server. * * @param string data Optional data to send as request body. */ this.send = function(data) { if (this.readyState != this.OPENED) { throw "INVALID_STATE_ERR: connection must be opened before send() is called"; } /** setState(this.OPENED); * Figure out if a host and/or port were specified. * Regex borrowed from parseUri and modified. Needs additional optimization. * @see http://blog.stevenlevithan.com/archives/parseuri */ var loc = /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?([^?#]*)/.exec(settings.url); // Determine the server switch (loc[1]) { case 'http': var host = loc[6]; break; case undefined: case '': var host = "localhost"; break; case 'https': throw "SSL is not implemented."; break; default: throw "Protocol not supported."; } // Default to port 80. If accessing localhost on another port be sure to // use http://localhost:port/path var port = loc[7] ? loc[7] : 80; // Set the URI, default to / var uri = loc[8] ? loc[8] : "/"; // Set the Host header or the server may reject the request headers["Host"] = host; client = http.createClient(port, host); client.addListener('error', function (error) { //Error checking self.status=503; self.statusText=error; self.responseText=error.stack; setState(self.DONE); //throw error; }) // Set content length header if (settings.method == "GET" || settings.method == "HEAD") { data = null; } else if (data) { headers["Content-Length"] = data.length; if (!headers["Content-Type"]) { headers["Content-Type"] = "text/plain;charset=UTF-8"; } } // Use the correct request method switch (settings.method) { case 'GET': request = client.request("GET",uri, headers); break; case 'POST': request = client.request("POST",uri, headers); break; case 'HEAD': request = client.request("HEAD",uri, headers); break; case 'PUT': request = client.request("PUT",uri, headers); break; case 'DELETE': request = client.request("DELETE",uri, headers); break; default: throw "Request method is unsupported."; } // Send data to the server if (data) { request.write(data); } request.addListener('response', function(resp) { response = resp; response.setEncoding("utf8"); setState(this.HEADERS_RECEIVED); self.status = response.statusCode; response.addListener("data", function(chunk) { // Make sure there's some data if (chunk) { self.responseText += chunk; } setState(self.LOADING); }); response.addListener("end", function() { setState(self.DONE); }); }); request.end(); }; /** * Aborts a request. */ this.abort = function() { headers = defaultHeaders; this.readyState = this.UNSENT; this.responseText = ""; this.responseXML = ""; }; /** * Changes readyState and calls onreadystatechange. * * @param int state New state */ var setState = function(state) { self.readyState = state; self.onreadystatechange(); } };
JavaScript
0
@@ -5246,20 +5246,20 @@ etState( -this +self .HEADERS
7443a1f3176d894a841d57e759a3cd6a64d5f11a
add url.
sketches/theme/fluid/advect/index.js
sketches/theme/fluid/advect/index.js
var createCaption = require('vendors/utils').createCaption; var title = 'Fluid based on Perlin noise.'; var caption = ''; var url = 'https://github.com/kenjiSpecial/webgl-sketch-dojo/tree/master/sketches/theme/swap-renderer/app00'; createCaption({title : title, caption: caption, url : url}) var raf = require('raf'); var glslify = require('glslify'); var id; var scene, camera, renderer; var stats; var SwapRenderer = require('vendors/swapRenderer'); var swapRenderer, swapRenderer2; import PerlinMat from './materials/perlin/mat'; import AdvectMat from './materials/advect/mat'; import ShowMat from './materials/show/mat'; var perlinMat, advectMat, showMat; var mouse = new THREE.Vector2(-9999, -9999); var prevMouse; var dis = 0; var imageURLs = [ "assets/texture00.jpg", "assets/texture01.jpg", "assets/texture03.jpg", "assets/texture04.jpg", ]; var textures = []; var loader = new THREE.TextureLoader(); var originBuffer = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, {minFilter: THREE.NearestFilter, magFilter: THREE.NearestFilter, format: THREE.RGBAFormat, type:THREE.FloatType, stencilBuffer: false}); var mouse; function init(){ renderer = new THREE.WebGLRenderer({alpha: true}); renderer.setSize(window.innerWidth, window.innerHeight); swapRenderer = new SwapRenderer({width : window.innerWidth, height : window.innerHeight, renderer : renderer }); swapRenderer2 = new SwapRenderer({width : window.innerWidth, height : window.innerHeight, renderer : renderer }); perlinMat = new PerlinMat(); swapRenderer.swapUpdate(perlinMat); swapRenderer.swapUpdate(perlinMat); showMat = new ShowMat(); advectMat = new AdvectMat(); document.body.appendChild(renderer.domElement); var count = 0; imageURLs.forEach(function(imageURL, index){ loader.load(imageURL, function(texture){ textures.push(texture); count++; if(imageURLs.length == count) createTexture(texture); }) }); } var basicMat; function createTexture(texture){ basicMat = new THREE.MeshBasicMaterial({map : texture }); swapRenderer2.pass(basicMat, swapRenderer2.front); swapRenderer2.pass(basicMat, swapRenderer2.back); swapRenderer2.pass(basicMat, originBuffer); raf(animate); }; function animate(){ dis *= 0.95; if(!isMouseDown){ perlinMat.update(1/60); swapRenderer.swapUpdate(perlinMat); advectMat.updateMat(1/60, swapRenderer2.target, swapRenderer.target, originBuffer, mouse, dis ); swapRenderer2.swapUpdate(advectMat); } showMat.update(swapRenderer2.target); swapRenderer2.out(showMat); id = raf(animate); } init(); window.addEventListener('mousemove', function(event){ event.preventDefault(); mouse.x = ( event.clientX / window.innerWidth ); mouse.y = 1 - ( event.clientY / window.innerHeight ); if(prevMouse){ var dx = (mouse.x - prevMouse.x) * window.innerWidth; var dy = (mouse.y - prevMouse.y) * window.innerHeight; dis += Math.sqrt(dx * dx + dy * dy)/3; } prevMouse = mouse.clone(); }); var isMouseDown = false; window.addEventListener("mousedown", function(){ isMouseDown = true; basicMat.map = textures[parseInt(textures.length * Math.random())] swapRenderer2.pass(basicMat, swapRenderer2.front); swapRenderer2.pass(basicMat, swapRenderer2.back); swapRenderer2.pass(basicMat, originBuffer); }); window.addEventListener("mouseup", function(){ isMouseDown = false; });
JavaScript
0
@@ -207,27 +207,20 @@ eme/ -swap-renderer/app00 +fluid/advect ';%0Ac
3b6843bce7b80ed20a607841cc79fa56346cfbcd
Improve consumer#addTopics
lib/consumer.js
lib/consumer.js
'use strict'; var util = require('util'), _ = require('lodash'), events = require('events'), Client = require('./client'), protocol = require('./protocol'), Offset = require('./offset'), errors = require('./errors') var DEFAULTS = { groupId: 'kafka-node-group', // Auto commit config autoCommit: true, autoCommitMsgCount: 100, autoCommitIntervalMs: 5000, // Fetch message config fetchMaxWaitMs: 100, fetchMinBytes: 1, fetchMaxBytes: 1024 * 1024, fromOffset: false }; var nextId = (function () { var id = 0; return function () { return id++; } })(); var Consumer = function (client, topics, options) { if (!topics) { throw new Error('Must have payloads'); } this.fetchCount = 0; this.client = client; this.options = _.defaults( (options||{}), DEFAULTS ); this.ready = false; this.id = nextId(); this.payloads = this.buildPayloads(topics); this.connect(); } util.inherits(Consumer, events.EventEmitter); Consumer.prototype.buildPayloads = function (payloads) { var self = this; return payloads.map(function (p) { if (typeof p !== 'object') p = { topic: p }; p.partition = p.partition || 0; p.offset = p.offset || 0; p.maxBytes = self.options.fetchMaxBytes; p.metadata = 'm'; // metadata can be arbitrary return p; }); } Consumer.prototype.connect = function () { var self = this; //Client already exists this.ready = this.client.ready; if (this.ready) this.init(); this.client.on('ready', function () { if (!self.ready) self.init(); self.ready = true; }); this.client.on('error', function (err) { self.emit('error', err); }); this.client.on('close', function () { console.log('close'); }); this.client.on('brokersChanged', function () { var topicNames = self.payloads.map(function (p) { return p.topic; }); this.refreshMetadata(topicNames, function () { self.fetch(); }); }); // 'done' will be emit when a message fetch request complete this.on('done', function (topics) { self.updateOffsets(topics); setImmediate(function() { self.fetch(); }); }); } Consumer.prototype.init = function () { if (!this.payloads.length) { return; } var self = this , topics = self.payloads.map(function (p) { return p.topic; }) self.client.topicExists(topics, function (err, topics) { if (err) { return self.emit('error', new errors.TopicsNotExistError(topics)); } if (self.options.fromOffset) return self.fetch(); self.fetchOffset(self.payloads, function (err, topics) { if (err) { return self.emit('error', err); } self.updateOffsets(topics, true); self.fetch(); }); }); } /* * Update offset info in current payloads * @param {Object} Topic-partition-offset * @param {Boolean} Don't commit when initing consumer */ Consumer.prototype.updateOffsets = function (topics, initing) { this.payloads.forEach(function (p) { if (!_.isEmpty(topics[p.topic]) && topics[p.topic][p.partition] !== undefined) p.offset = topics[p.topic][p.partition] + 1; }); if (this.options.autoCommit && !initing) this.autoCommit(); } function autoCommit(force, cb) { if (this.committing && !force) return cb && cb('Offset committing'); this.committing = true; setTimeout(function () { this.committing = false; }.bind(this), this.options.autoCommitIntervalMs); var commits = this.payloads.reduce(function (out, p) { if (p.offset !== 0) out.push(_.defaults({ offset: p.offset-1 }, p)); return out; }, []); if (commits.length) { this.client.sendOffsetCommitRequest(this.options.groupId, commits, cb); } else { cb && cb(); } } Consumer.prototype.commit = Consumer.prototype.autoCommit = autoCommit; Consumer.prototype.fetch = function () { if (!this.ready) return; this.client.sendFetchRequest(this, this.payloads, this.options.fetchMaxWaitMs, this.options.fetchMinBytes); } Consumer.prototype.fetchOffset = function (payloads, cb) { this.client.sendOffsetFetchRequest(this.options.groupId, payloads, cb); } Consumer.prototype.addTopics = function (topics, cb) { var self = this; if (!this.ready) { setTimeout(function () { self.addTopics(topics,cb) } , 100); return; } this.client.addTopics( topics, function (err, added) { if (err) return cb && cb(err, added); var payloads = self.buildPayloads(topics); // update offset of topics that will be added self.fetchOffset(payloads, function (err, offsets) { if (err) return cb(err); payloads.forEach(function (p) { p.offset = offsets[p.topic][p.partition]; self.payloads.push(p); }); cb && cb(null, added); }); } ); } Consumer.prototype.removeTopics = function (topics, cb) { topics = typeof topics === 'string' ? [topics] : topics; this.payloads = this.payloads.filter(function (p) { return !~topics.indexOf(p.topic); }); this.client.removeTopicMetadata(topics, cb); } Consumer.prototype.close = function (force, cb) { this.ready = false; if (typeof force === 'function') { cb = force; force = false; } if (force) { this.commit(force, function (err) { this.client.close(cb); }.bind(this)); } else { this.client.close(cb); } } Consumer.prototype.setOffset = function (topic, partition, offset) { this.payloads.every(function (p) { if (p.topic === topic && p.partition === partition) { p.offset = offset; return false; } return true; }); } module.exports = Consumer;
JavaScript
0.000003
@@ -4839,32 +4839,81 @@ yloads(topics);%0A + var reFetch = !self.payloads.length;%0A // u @@ -5225,32 +5225,120 @@ %7D);%0A + self.updateOffsets(offsets);%0A if (reFetch) self.fetch();%0A
2665ac49e970de3c7092d96fefd820cdc84e9229
make null reader code suitable to use as return value code
lib/compile_text_parser.js
lib/compile_text_parser.js
var Types = require('./constants/types.js'); var Charsets = require('./constants/charsets.js'); var CharsetToEncoding = require('./constants/charset_encodings.js'); var srcEscape = require('./helpers').srcEscape; var genFunc = require('generate-function'); var typeNames = []; for (var t in Types) { typeNames[Types[t]] = t; } function compile(fields, options, config) { // node-mysql typeCast compatibility wrapper // see https://github.com/mysqljs/mysql/blob/96fdd0566b654436624e2375c7b6604b1f50f825/lib/protocol/packets/Field.js function wrap(field, type, packet, encoding) { return { type: type, length: field.columnLength, db: field.schema, table: field.table, name: field.name, string: function() { return packet.readLengthCodedString(encoding); }, buffer: function() { return packet.readLengthCodedBuffer(); }, geometry: function() { return packet.parseGeometryValue(); } }; } // use global typeCast if current query doesn't specify one if ( typeof config.typeCast === 'function' && typeof options.typeCast !== 'function' ) { options.typeCast = config.typeCast; } var parserFn = genFunc(); var i = 0; /* eslint-disable no-trailing-spaces */ /* eslint-disable no-spaced-func */ /* eslint-disable no-unexpected-multiline */ parserFn('(function () {')( 'return function TextRow(packet, fields, options, CharsetToEncoding) {' ); if (options.rowsAsArray) { parserFn('var result = new Array(' + fields.length + ')'); } if (typeof options.typeCast === 'function') { parserFn('var wrap = ' + wrap.toString()); } var resultTables = {}; var resultTablesArray = []; if (options.nestTables === true) { for (i = 0; i < fields.length; i++) { resultTables[fields[i].table] = 1; } resultTablesArray = Object.keys(resultTables); for (i = 0; i < resultTablesArray.length; i++) { parserFn('this[' + srcEscape(resultTablesArray[i]) + '] = {};'); } } var lvalue = ''; var fieldName = ''; for (i = 0; i < fields.length; i++) { fieldName = srcEscape(fields[i].name); parserFn('// ' + fieldName + ': ' + typeNames[fields[i].columnType]); if (typeof options.nestTables == 'string') { lvalue = 'this[' + srcEscape(fields[i].table + options.nestTables + fields[i].name) + ']'; } else if (options.nestTables === true) { lvalue = 'this[' + srcEscape(fields[i].table) + '][' + fieldName + ']'; } else if (options.rowsAsArray) { lvalue = 'result[' + i.toString(10) + ']'; } else { lvalue = 'this[' + fieldName + ']'; } var encodingExpr = 'CharsetToEncoding[fields[' + i + '].characterSet]'; var readCode = readCodeFor( fields[i].columnType, fields[i].characterSet, encodingExpr, config, options ); if (typeof options.typeCast === 'function') { parserFn( lvalue + ' = options.typeCast(wrap(fields[' + i + '], ' + srcEscape(typeNames[fields[i].columnType]) + ', packet, ' + encodingExpr + '), function() { return ' + readCode + ';})' ); } else if (options.typeCast === false) { parserFn(lvalue + ' = packet.readLengthCodedBuffer();'); } else { parserFn(lvalue + ' = ' + readCode + ';'); } } if (options.rowsAsArray) { parserFn('return result;'); } parserFn('};')('})()'); /* eslint-enable no-trailing-spaces */ /* eslint-enable no-spaced-func */ /* eslint-enable no-unexpected-multiline */ if (config.debug) { console.log('\n\nCompiled text protocol row parser:\n'); var cardinal = require('cardinal'); console.log(cardinal.highlight(parserFn.toString()) + '\n'); } return parserFn.toFunction(); } function readCodeFor(type, charset, encodingExpr, config, options) { var supportBigNumbers = options.supportBigNumbers || config.supportBigNumbers; var bigNumberStrings = options.bigNumberStrings || config.bigNumberStrings; switch (type) { case Types.TINY: case Types.SHORT: case Types.LONG: case Types.INT24: case Types.YEAR: return 'packet.parseLengthCodedIntNoBigCheck()'; case Types.LONGLONG: if (supportBigNumbers && bigNumberStrings) { return 'packet.parseLengthCodedIntString()'; } return 'packet.parseLengthCodedInt(' + supportBigNumbers + ')'; case Types.FLOAT: case Types.DOUBLE: return 'packet.parseLengthCodedFloat()'; case Types.NULL: return 'null; packet.skip(1)'; case Types.DECIMAL: case Types.NEWDECIMAL: if (config.decimalNumbers) { return 'packet.parseLengthCodedFloat()'; } return 'packet.readLengthCodedString("ascii")'; case Types.DATE: if (config.dateStrings) { return 'packet.readLengthCodedString("ascii")'; } return 'packet.parseDate()'; case Types.DATETIME: case Types.TIMESTAMP: if (config.dateStrings) { return 'packet.readLengthCodedString("ascii")'; } return 'packet.parseDateTime()'; case Types.TIME: return 'packet.readLengthCodedString("ascii")'; case Types.GEOMETRY: return 'packet.parseGeometryValue()'; case Types.JSON: // Since for JSON columns mysql always returns charset 63 (BINARY), // we have to handle it according to JSON specs and use "utf8", // see https://github.com/sidorares/node-mysql2/issues/409 return 'JSON.parse(packet.readLengthCodedString("utf8"))'; default: if (charset == Charsets.BINARY) { return 'packet.readLengthCodedBuffer()'; } else { return 'packet.readLengthCodedString(' + encodingExpr + ')'; } } } module.exports = compile;
JavaScript
0.000003
@@ -4627,27 +4627,37 @@ rn ' -null; packet. -skip(1 +readLengthCodedNumber( )';%0A
a6b1b5d67a3f423b6b282aebb7af74976dbdc1dc
Revert "Revert "Delays enabling fetching of more data for high velocity scrolling""
aura-components/src/main/components/ui/scrollerLib/InfiniteLoading.js
aura-components/src/main/components/ui/scrollerLib/InfiniteLoading.js
/* * Copyright (C) 2013 salesforce.com, inc. * * 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. */ function lib(w) { //eslint-disable-line no-unused-vars 'use strict'; w || (w = window); var SCROLLER = w.__S || (w.__S = {}), PLUGINS = SCROLLER.plugins || (SCROLLER.plugins = {}), Logger = SCROLLER.Logger, CONFIG_DEFAULTS = { labelNoData : 'No more data to display', labelIdle : '', labelLoading : 'Loading more...', threshold : 0 }, CLASS_LOADING = 'loading', CLASS_IDLE = 'il'; function InfiniteLoading () {} InfiniteLoading.prototype = { init: function () { this._mergeInfiniteLoading(); this.on('_initialize', this._initializeInfiniteLoading); }, _mergeInfiniteLoading: function () { this.opts.infiniteLoadingConfig = this._mergeConfigOptions( CONFIG_DEFAULTS, this.opts.infiniteLoadingConfig ); }, _createInfiniteLoadingMarkup: function () { var il_container = w.document.createElement('div'), label = document.createElement('span'), idleLabel = this.opts.infiniteLoadingConfig.labelIdle; label.className = CLASS_IDLE; label.textContent = idleLabel; il_container.className = 'infinite-loading'; il_container.appendChild(label); return il_container; }, _initializeInfiniteLoading: function () { var ilConfig = this.opts.infiniteLoadingConfig, thresholdCheck = this.opts.gpuOptimization ? this._checkItemsthreshold : this._checkLoadingThreshold; if (!this.opts.infiniteLoading || !ilConfig.dataProvider) { Logger.log('warn', 'InfiniteLoading will not work because there is no data provider or is not activated'); return; } this.on('scrollMove', thresholdCheck); this.on('scrollEnd', thresholdCheck); this._itemsThreshold = this.items && this.items.length || 10; this._appendInfiniteLoading(); this._setSize(); }, _appendInfiniteLoading: function () { var il_container = this._createInfiniteLoadingMarkup(), target = this.scroller; target.appendChild(il_container); this.ilDOM = il_container; this.ilLabel = il_container.firstChild; this._ilSize = il_container.offsetHeight; //relayout }, _setState: function (loading) { this._loading = loading; if (loading) { this.ilDOM.classList.add(CLASS_LOADING); this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelLoading; } else { this.ilDOM.classList.remove(CLASS_LOADING); this.ilLabel.textContent = this.opts.infiniteLoadingConfig.labelIdle; } }, _appendData: function (items) { var docfrag = w.document.createDocumentFragment(), scrollerContainer = this.scroller, container = this.ilDOM; items.forEach(function (i) { docfrag.appendChild(i); }); scrollerContainer.insertBefore(docfrag, container); }, _getCustomAppendedElements: function () { return 2; }, _triggerInfiniteLoadingDataProvider: function () { var self = this, ilDataProvider = this.opts.infiniteLoadingConfig.dataProvider, callback = function() { self._infiniteLoadingTriggerCallback.apply(self, arguments); }; if (ilDataProvider) { Logger.log('fetching data'); this._ilFetchingData = true; this._setState(true/*loading*/); ilDataProvider(callback); } else { this._infiniteLoadingTriggerCallback('noop'); } }, _infiniteLoadingTriggerCallback: function (payload) { if (payload) { var data = payload instanceof Array ? payload: payload.data; if (data && data.length) { this.appendItems(payload); } if (payload === 'refresh' || payload.refresh) { this.refresh(); } if (payload === 'nomoredata' || payload.noMoreData) { this.lockFetchData(); } if (payload.labelIdle) { this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle; } if (payload.labelLoading) { this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading; } } this._setState(false/*loading*/); this._ilFetchingData = false; }, // This check is done when surfaceManager is enabled _checkItemsthreshold: function () { if (this._ilNoMoreData || this._ilFetchingData) { return; } var lastIndex = this._positionedSurfacesLast().contentIndex, count = this.items.length - 1, threshold = this._itemsThreshold; if (count - lastIndex < threshold) { this._triggerInfiniteLoadingDataProvider(); } }, // This check is done when surfaceManager is disabled _checkLoadingThreshold: function (action, x, y) { if (this._ilNoMoreData || this._ilFetchingData) { return; } var config = this.opts.infiniteLoadingConfig, pos, size, wrapper; x || (x = this.x); y || (y = this.y); if (this.scrollHorizontal) { pos = x; size = this.scrollerWidth; wrapper = this.wrapperWidth; } else { pos = y; size = this.scrollerHeight; wrapper = this.wrapperHeight; } var scrollable = size - wrapper; // Total scrollable pixels var left = scrollable + pos; // Remaining px to scroll // Make sure that the provided thershold is never bigger // than the scrollable pixels to avoid extra provider calls var threshold = config.threshold < scrollable ? config.threshold : 0; Logger.log('left: ', left, 'tr: ', threshold); // If we have pixels to scroll // and less than the threshold trigger provider. if (this.distY !== 0 && left <= threshold) { Logger.log('triggerDataProvider'); this._triggerInfiniteLoadingDataProvider(); } }, /* PUBLIC API */ fetchData: function () { this._triggerInfiniteLoadingDataProvider(); }, unlockFetchData: function () { this._ilNoMoreData = false; }, lockFetchData: function () { this._ilNoMoreData = true; }, updateLabels:function(payload) { if (typeof (payload.labelIdle) !== "undefined") { this.opts.infiniteLoadingConfig.labelIdle = payload.labelIdle; } if (typeof (payload.labelLoading) !== "undefined") { this.opts.infiniteLoadingConfig.labelLoading = payload.labelLoading; } // in order to redraw the label we have to call _setState this._setState(this._loading); } }; PLUGINS.InfiniteLoading = InfiniteLoading; }
JavaScript
0
@@ -4293,36 +4293,16 @@ tion() %7B - %0A @@ -4375,16 +4375,83 @@ ments);%0A + Logger.log('InfiniteLoading callback called');%0A @@ -5657,32 +5657,85 @@ se/*loading*/);%0A + w.requestAnimationFrame(function() %7B%0A this @@ -5752,32 +5752,59 @@ ngData = false;%0A + %7D.bind(this));%0A %7D,%0A
d1d726d434e31d0b7c47b713dd23eefbf4d73982
Fix missing required param.
lib/assets/javascripts/cartodb3/editor/editor-map-view.js
lib/assets/javascripts/cartodb3/editor/editor-map-view.js
var _ = require('underscore'); var Backbone = require('backbone'); var CoreView = require('backbone/core-view'); var EditorView = require('./editor-view'); var AddAnalysisView = require('../components/modals/add-analysis/add-analysis-view'); var StackLayoutView = require('../components/stack-layout/stack-layout-view'); var BasemapContentView = require('./layers/basemap-content-view'); var LayerContentView = require('./layers/layer-content-view'); var WidgetsFormContentView = require('./widgets/widgets-form/widgets-form-content-view'); var Notifier = require('../components/notifier/notifier'); var REQUIRED_OPTS = [ 'userActions', 'editorModel', 'visDefinitionModel', 'layerDefinitionsCollection', 'analysisDefinitionNodesCollection', 'legendDefinitionsCollection', 'widgetDefinitionsCollection', 'mapcapsCollection', 'privacyCollection', 'modals', 'onboardings', 'userModel', 'configModel', 'editorModel', 'pollingModel', 'mapDefinitionModel' ]; module.exports = CoreView.extend({ className: 'MapEditor Editor-panel', events: { 'click .js-add-analysis': '_onAddAnalysisClicked' }, initialize: function (opts) { _.each(REQUIRED_OPTS, function (item) { if (opts[item] === undefined) throw new Error(item + ' is required'); this['_' + item] = opts[item]; }, this); this._initBinds(); }, render: function () { var self = this; var stackViewCollection = new Backbone.Collection([{ createStackView: function (stackLayoutModel, opts) { var selectedTabItem = opts[0] || 'layers'; return new EditorView({ className: 'Editor-content', modals: self._modals, userModel: self._userModel, userActions: self._userActions, configModel: self._configModel, editorModel: self._editorModel, pollingModel: self._pollingModel, visDefinitionModel: self._visDefinitionModel, layerDefinitionsCollection: self._layerDefinitionsCollection, analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection, widgetDefinitionsCollection: self._widgetDefinitionsCollection, mapcapsCollection: self._mapcapsCollection, privacyCollection: self._privacyCollection, mapStackLayoutModel: stackLayoutModel, selectedTabItem: selectedTabItem }); } }, { createStackView: function (stackLayoutModel, opts) { var viewType = opts[1]; switch (viewType) { case 'basemaps': return new BasemapContentView({ className: 'Editor-content', basemaps: self._basemaps, layerDefinitionsCollection: self._layerDefinitionsCollection, stackLayoutModel: stackLayoutModel, customBaselayersCollection: self._userModel.layers, modals: self._modals }); case 'layer-content': var layerDefinitionModel = opts[0]; var analysisPayload = opts[2]; return new LayerContentView({ className: 'Editor-content', userActions: self._userActions, userModel: self._userModel, layerDefinitionModel: layerDefinitionModel, mapDefinitionModel: self._mapDefinitionModel, widgetDefinitionsCollection: self._widgetDefinitionsCollection, layerDefinitionsCollection: self._layerDefinitionsCollection, analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection, legendDefinitionsCollection: self._legendDefinitionsCollection, analysis: self._analysis, modals: self._modals, onboardings: self._onboardings, stackLayoutModel: stackLayoutModel, analysisPayload: analysisPayload, configModel: self._configModel, editorModel: self._editorModel }); case 'widget-content': var widgetDefinitionModel = opts[0]; return new WidgetsFormContentView({ className: 'Editor-content', modals: self._modals, userActions: self._userActions, widgetDefinitionModel: widgetDefinitionModel, layerDefinitionsCollection: self._layerDefinitionsCollection, analysisDefinitionNodesCollection: self._analysisDefinitionNodesCollection, stackLayoutModel: stackLayoutModel }); case 'element-content': console.log(viewType + 'view is not implemented yet'); break; default: console.log(viewType + 'view doesn\'t exist'); } } }]); this._stackLayoutView = new StackLayoutView({ className: 'Editor-content', collection: stackViewCollection }); this.$el.append(this._stackLayoutView.render().$el); this.addView(this._stackLayoutView); var notifierView = Notifier.getView(); this.$el.append(notifierView.render().el); this.addView(notifierView); return this; }, _initBinds: function () { this._editorModel.on('change:edition', this._changeStyle, this); this.add_related_model(this._editorModel); }, _changeStyle: function () { this.$el.toggleClass('is-dark', this._editorModel.isEditing()); }, _onAddAnalysisClicked: function (ev) { this._onboardings.destroy(); var layerId = ev.currentTarget && ev.currentTarget.dataset.layerId; if (!layerId) throw new Error('missing data-layer-id on element to open add-analysis modal, the element was: ' + ev.currentTarget.outerHTML); var layerDefinitionModel = this._layerDefinitionsCollection.get(layerId); if (!layerDefinitionModel) throw new Error('no layer-definition found for id' + layerId + ', available layer ids are: ' + this._layerDefinitionsCollection.pluck('id') + ')'); var generateAnalysisOptions = this._userModel.featureEnabled('generate_analysis_options'); this._modals.create(function (modalModel) { return new AddAnalysisView({ generateAnalysisOptions: generateAnalysisOptions, modalModel: modalModel, layerDefinitionModel: layerDefinitionModel }); }); this._modals.onDestroyOnce(function (analysisFormAttrs) { if (analysisFormAttrs) { // A analysis option was seleted, redirect to layer-content view with new attrs this._stackLayoutView.model.goToStep(1, layerDefinitionModel, 'layer-content', analysisFormAttrs); } }, this); } });
JavaScript
0.000001
@@ -632,35 +632,32 @@ ctions',%0A ' -editorModel +basemaps ',%0A 'visDef
fc3254e8c2271e45c749cab1c88c1f3b2c16e195
Put front page images in static folder.
src/js/hutmap/controllers/controllers.js
src/js/hutmap/controllers/controllers.js
'use strict'; (function () { angular.module('hutmap'). controller('HutmapCtrl', ['$scope', '$route', '$location', '$timeout', '$log', 'angulargmContainer', function($scope, $route, $location, $timeout, $log, angulargmContainer) { $scope.$route = $route; $scope.loading = 0; $scope.incLoading = function() { $scope.loading++; }; $scope.decLoading = function() { $scope.loading--; }; // Of the form { type: 'error', msg: 'message' } $scope.alerts = [ ]; $scope.addAlert = function(type, msg) { $scope.alerts.push({type:type,msg:msg}); }; $scope.closeAlert = function(index) { $scope.alerts.splice(index, 1); }; }]). controller('CarouselCtrl', ['$scope', '$route', function($scope, $route) { $scope.carouselInterval = 6000; $scope.slides = [ {title: 'Big Hut', text: 'lorem ipsum dolor', image: 'https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.3&disp=inline&realattid=f_haswzj3n2&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715869360&sads=7jqjo-uAUQ2mWgLwJ-5zPIGflA0'}, {title: 'Joe River Chickee', text: 'lorem ipsum dolor', image: 'https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.5&disp=inline&realattid=f_haswzj3u4&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715863132&sads=kmhkET9W_d5-f6HLhAIZpt5kx2U'}, {title: 'John Muir Shelter', text: 'lorem ipsum dolor', image: 'https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.6&disp=inline&realattid=f_haswzj3v5&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715851827&sads=yGOzj2H_sDdau-G_UX0F2mW-MrE&sadssc=1'}, ]; }]). controller('HutInfoCtrl', ['$scope', function($scope) { $scope.accuracy_tooltip = [ 'Coordinates provided, but unverifiable.', 'Wild ass guess.', 'Slightly better than a wild ass guess.', 'Found structure on satellite or topo map.', 'Surveyed with GPS by the Hutmap team.', 'Found on a map and surveyed by the Hutmap team.' ]; }]); })();
JavaScript
0
@@ -891,921 +891,272 @@ e: ' -https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.3&disp=inline&realattid=f_haswzj3n2&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715869360&sads=7jqjo-uAUQ2mWgLwJ-5zPIGflA0'%7D,%0A %7Btitle: 'Joe River Chickee', text: 'lorem ipsum dolor', image: 'https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.5&disp=inline&realattid=f_haswzj3u4&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715863132&sads=kmhkET9W_d5-f6HLhAIZpt5kx2U'%7D,%0A %7Btitle: 'John Muir Shelter', text: 'lorem ipsum dolor', image: 'https://mail-attachment.googleusercontent.com/attachment/u/0/?ui=2&ik=8768b5ed5b&view=att&th=13ba670d57d0c5f1&attid=0.6&disp=inline&realattid=f_haswzj3v5&safe=1&zw&saduie=AG9B_P9lJiRTwBR09D1jE4IKml8C&sadet=1363715851827&sads=yGOzj2H_sDdau-G_UX0F2mW-MrE&sadssc=1 +/static/img/carousel/Big Hut.JPG'%7D,%0A %7Btitle: 'Joe River Chickee', text: 'lorem ipsum dolor', image: '/static/img/carousel/Joe River Chickee.JPG'%7D,%0A %7Btitle: 'John Muir Shelter', text: 'lorem ipsum dolor', image: '/static/img/carousel/John Muir Shelter.JPG '%7D,%0A
d747e6a22fcd43e9ff126eeb439446f3e5bb5ffe
Add default video skins.
app/index.js
app/index.js
require('./main.scss'); var Rx = require('rx'); require('rx-dom'); var $ = require('jquery'); var videojs = require('videojs'); var GIPHY = { searchUri: 'http://api.giphy.com/v1/gifs/search?q=', apiKey: 'dc6zaTOxFJmzC' } var $adjective = $('#adjective'), $noun = $('#noun'); var adjectiveUp = observableFromInput($adjective); var nounUp = observableFromInput($noun); var comboUp = Rx.Observable.combineLatest( adjectiveUp, nounUp ); comboUp.subscribe(function(x) { Rx.DOM.ajax({ url: GIPHY.searchUri + x.join('+') + '&api_key=' + GIPHY.apiKey, responseType: 'json' }) .subscribe( function giphySuccess(results) { console.log(results); var view = $('#view').html(''); results.response.data.forEach(function(item) { var video = document.createElement('video'); video.classList.add('vjs-big-play-centered'); videojs(video, { 'autoload': 'auto', 'controls': true, 'loop': true }, function() { var player = this; player.bigPlayButton.show(); player.on('pause', function() { player.bigPlayButton.show(); }); player.on('play', function() { player.bigPlayButton.hide(); }); player.src(item.images.fixed_height.mp4); view.append(video); }); }); }, function giphyError(error) { console.log(error); }); }); function observableFromInput(inputElement){ return Rx.Observable.fromEvent(inputElement, 'keyup') .map(function (e) { return e.target.value; }) .filter(function (text) { return text.length > 2; }) .debounce(750); } // var subscription; // subscription = Rxhr.subscribe( // function (data) { // data.response.forEach(function (twt) { // console.log(twt); // }); // }, // function (err) { // console.log(err); // useTestData(); // } // ); // function useTestData(){ // var p = Promise.resolve(window.testData); // subscription = Rx.Observable.fromPromise(p).subscribe( // function (data) { // data.response.forEach(function (twt) { // console.log(twt); // }); // } // ); // }
JavaScript
0
@@ -1315,16 +1315,93 @@ ht.mp4); +%0A%0A video.classList.add('vjs-default-skin', 'vjs-big-play-centered'); %0A
15b55f09ba97c7cabe368900bcdc4c120f988d47
fix deprecation export messages (#29563)
packages/gatsby/cache-dir/gatsby-browser-entry.js
packages/gatsby/cache-dir/gatsby-browser-entry.js
import React from "react" import PropTypes from "prop-types" import Link, { withPrefix, withAssetPrefix, navigate, push, replace, navigateTo, parsePath, } from "gatsby-link" import { useScrollRestoration } from "gatsby-react-router-scroll" import PageRenderer from "./public-page-renderer" import loader from "./loader" const prefetchPathname = loader.enqueue const StaticQueryContext = React.createContext({}) function StaticQueryDataRenderer({ staticQueryData, data, query, render }) { const finalData = data ? data.data : staticQueryData[query] && staticQueryData[query].data return ( <React.Fragment> {finalData && render(finalData)} {!finalData && <div>Loading (StaticQuery)</div>} </React.Fragment> ) } const StaticQuery = props => { const { data, query, render, children } = props return ( <StaticQueryContext.Consumer> {staticQueryData => ( <StaticQueryDataRenderer data={data} query={query} render={render || children} staticQueryData={staticQueryData} /> )} </StaticQueryContext.Consumer> ) } const useStaticQuery = query => { if ( typeof React.useContext !== `function` && process.env.NODE_ENV === `development` ) { throw new Error( `You're likely using a version of React that doesn't support Hooks\n` + `Please update React and ReactDOM to 16.8.0 or later to use the useStaticQuery hook.` ) } const context = React.useContext(StaticQueryContext) // query is a stringified number like `3303882` when wrapped with graphql, If a user forgets // to wrap the query in a grqphql, then casting it to a Number results in `NaN` allowing us to // catch the misuse of the API and give proper direction if (isNaN(Number(query))) { throw new Error(`useStaticQuery was called with a string but expects to be called using \`graphql\`. Try this: import { useStaticQuery, graphql } from 'gatsby'; useStaticQuery(graphql\`${query}\`); `) } if (context[query]?.data) { return context[query].data } else { throw new Error( `The result of this StaticQuery could not be fetched.\n\n` + `This is likely a bug in Gatsby and if refreshing the page does not fix it, ` + `please open an issue in https://github.com/gatsbyjs/gatsby/issues` ) } } StaticQuery.propTypes = { data: PropTypes.object, query: PropTypes.string.isRequired, render: PropTypes.func, children: PropTypes.func, } function graphql() { throw new Error( `It appears like Gatsby is misconfigured. Gatsby related \`graphql\` calls ` + `are supposed to only be evaluated at compile time, and then compiled away. ` + `Unfortunately, something went wrong and the query was left in the compiled code.\n\n` + `Unless your site has a complex or custom babel/Gatsby configuration this is likely a bug in Gatsby.` ) } export { Link, withAssetPrefix, withPrefix, graphql, parsePath, navigate, push, // TODO replace for v3 replace, // TODO remove replace for v3 navigateTo, // TODO: remove navigateTo for v3 useScrollRestoration, StaticQueryContext, StaticQuery, PageRenderer, useStaticQuery, prefetchPathname, }
JavaScript
0
@@ -3014,128 +3014,8 @@ te,%0A - push, // TODO replace for v3%0A replace, // TODO remove replace for v3%0A navigateTo, // TODO: remove navigateTo for v3%0A us
64e0eddedf50e93d4fb7ff3e5f57c65548936183
Remove trailing whitespace
generators.js
generators.js
/* jshint node: true */ 'use strict'; var detect = require('./detect'); var defaults = require('cog/defaults'); var mappings = { offer: { // audio toggle // { audio: false } in peer connection config turns off audio audio: function(c) { c.mandatory = c.mandatory || {}; c.mandatory.OfferToReceiveAudio = true; }, // video toggle // { video: false } in peer connection config turns off video video: function(c) { c.mandatory = c.mandatory || {}; c.mandatory.OfferToReceiveVideo = true; } }, create: { // data enabler data: function(c) { if (! detect.moz) { c.optional = (c.optional || []).concat({ RtpDataChannels: true }); } }, dtls: function(c) { if (! detect.moz) { c.optional = (c.optional || []).concat({ DtlsSrtpKeyAgreement: true }); } } } }; // initialise known flags var knownFlags = ['video', 'audio', 'data']; /** ## rtc/generators The generators package provides some utility methods for generating constraint objects and similar constructs. ```js var generators = require('rtc/generators'); ``` **/ /** ### generators.config(config) Generate a configuration object suitable for passing into an W3C RTCPeerConnection constructor first argument, based on our custom config. **/ exports.config = function(config) { return defaults(config, { iceServers: [] }); }; /** ### generators.connectionConstraints(flags, constraints) This is a helper function that will generate appropriate connection constraints for a new `RTCPeerConnection` object which is constructed in the following way: ```js var conn = new RTCPeerConnection(flags, constraints); ``` In most cases the constraints object can be left empty, but when creating data channels some additional options are required. This function can generate those additional options and intelligently combine any user defined constraints (in `constraints`) with shorthand flags that might be passed while using the `rtc.createConnection` helper. **/ exports.connectionConstraints = function(flags, constraints) { var generated = {}; var m = mappings.create; // iterate through the flags and apply the create mappings Object.keys(flags || {}).forEach(function(key) { if (m[key]) { m[key](generated); } }); return defaults({}, constraints, generated); }; /** ### generators.mediaConstraints(flags, context) Generate mediaConstraints appropriate for the context in which they are being called (i.e. either constructing an RTCPeerConnection object, or on the `createOffer` or `createAnswer` calls). **/ exports.mediaConstraints = function(flags, context) { // create an empty constraints object var constraints = { optional: [{ DtlsSrtpKeyAgreement: true }] }; // provide default mandatory constraints for the offer if (context === 'offer') { constraints.mandatory = { OfferToReceiveVideo: false, OfferToReceiveAudio: false }; } // get the mappings for the context (defaulting to the offer context) var contextMappings = mappings[context || 'offer'] || {}; // if we haven't been passed an array for flags, then return the constraints if (! Array.isArray(flags)) { flags = parseFlags(flags); } flags.map(function(flag) { if (typeof contextMappings[flag] == 'function') { // mutate the constraints contextMappings[flag](constraints); } }); return constraints; }; /** ### parseFlags(opts) This is a helper function that will extract known flags from a generic options object. **/ var parseFlags = exports.parseFlags = function(options) { // ensure we have opts var opts = options || {}; // default video and audio flags to true if undefined opts.video = opts.video || typeof opts.video == 'undefined'; opts.audio = opts.audio || typeof opts.audio == 'undefined'; return Object.keys(opts || {}) .filter(function(flag) { return opts[flag]; }) .map(function(flag) { return flag.toLowerCase(); }) .filter(function(flag) { return knownFlags.indexOf(flag) >= 0; }); };
JavaScript
0.999999
@@ -1254,18 +1254,17 @@ o an W3C - %0A + RTCPee @@ -2085,18 +2085,16 @@ per.%0A**/ - %0Aexports @@ -2546,17 +2546,16 @@ they are - %0A being @@ -3537,24 +3537,24 @@ lags(opts)%0A%0A + This is a @@ -3613,17 +3613,16 @@ generic - %0A optio
65f4fa81e08793f2774c1d0c079c3cd657870faa
remove testing change
js/utils/bulkCoinUpdate.js
js/utils/bulkCoinUpdate.js
import $ from 'jquery'; import { Events } from 'backbone'; import { openSimpleMessage } from '../views/modals/SimpleMessage'; import app from '../app'; const events = { ...Events, }; export { events }; let bulkCoinUpdateSave; export function isBulkCoinUpdating() { return bulkCoinUpdateSave && bulkCoinUpdateSave.state() === 'pending'; } export function bulkCoinUpdate(coins) { if (!Array.isArray(coins) || !coins.length) { throw new Error('Please provide an array of accepted cryptocurrency codes.'); } // dedupe the list const newCoins = [...new Set(coins)]; if (isBulkCoinUpdating()) { throw new Error('An update is in process, new updates must wait until it is finished.'); } else { events.trigger('bulkCoinUpdating'); bulkCoinUpdateSave = $.post({ url: app.getServerUrl('ob/xxxbulkupdatecurrency'), data: JSON.stringify({ currencies: newCoins }), dataType: 'json', }).done(() => { events.trigger('bulkCoinUpdateDone'); }).fail((xhr) => { const reason = xhr.responseJSON && xhr.responseJSON.reason || xhr.statusText || ''; const message = app.polyglot.t('settings.storeTab.bulkListingCoinUpdate.errors.errorMessage'); const title = app.polyglot.t('settings.storeTab.bulkListingCoinUpdate.errors.errorTitle'); const reasonMsg = app.polyglot.t('settings.storeTab.bulkListingCoinUpdate.errors.reasonForError', { reason }); const msg = `${message} ${reason ? `<br>${reasonMsg}` : ''}`; openSimpleMessage(title, msg); events.trigger('bulkCoinUpdateFailed'); }); } return bulkCoinUpdateSave; }
JavaScript
0.000001
@@ -821,11 +821,8 @@ 'ob/ -xxx bulk
68ca9f8b7e86344f4b26cfa82b5e0f5056d975aa
Fix react/no-unknown-property
client/components/Common/Modal.js
client/components/Common/Modal.js
import React from 'react' export default class Modal extends React.Component { constructor(props) { super(props) this.state = { modalShown: false, } } render() { if (!this.state.modalShown) { return '' } return ( <div class="modal in" id="renamePage" style="display: block;"> <div class="modal-dialog"> <div class="modal-content"> <form role="form" id="renamePageForm" onsubmit="return false;"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-hidden="true"> × </button> <h4 class="modal-title">Rename page</h4> </div> <div class="modal-body"> <div class="form-group"> <label for="">Current page name</label> <br /> <code>/user/sotarok/memo/2017/04/24</code> </div> <div class="form-group"> <label for="newPageName">New page name</label> <br /> <div class="input-group"> <span class="input-group-addon">http://localhost:3000</span> <input type="text" class="form-control" name="new_path" id="newPageName" value="/user/sotarok/memo/2017/04/24" /> </div> </div> <div class="checkbox"> <label> <input name="create_redirect" value="1" type="checkbox" /> Redirect </label> <p class="help-block"> {' '} Redirect to new page if someone accesses <code>/user/sotarok/memo/2017/04/24</code> </p> </div> </div> <div class="modal-footer"> <p> <small class="pull-left" id="newPageNameCheck" /> </p> <input type="hidden" name="_csrf" value="RCs7uFdR-4nacCnqKfREe8VIlcYLP2J8xzpU" /> <input type="hidden" name="path" value="/user/sotarok/memo/2017/04/24" /> <input type="hidden" name="page_id" value="58fd0bd74c844b8f94c2e5b3" /> <input type="hidden" name="revision_id" value="58fd126385edfb9d8a0c073a" /> <input type="submit" class="btn btn-primary" value="Rename!" /> </div> </form> </div> </div> </div> ) } }
JavaScript
0.00014
@@ -264,24 +264,28 @@ %3Cdiv class +Name =%22modal in%22 @@ -335,32 +335,36 @@ %3Cdiv class +Name =%22modal-dialog%22%3E @@ -376,32 +376,36 @@ %3Cdiv class +Name =%22modal-content%22 @@ -462,30 +462,28 @@ %22 on -s +S ubmit= -%22return +%7B() =%3E false -;%22 +%7D %3E%0A @@ -496,32 +496,36 @@ %3Cdiv class +Name =%22modal-header%22%3E @@ -568,16 +568,20 @@ n%22 class +Name =%22close%22 @@ -689,24 +689,28 @@ %3Ch4 class +Name =%22modal-titl @@ -766,32 +766,36 @@ %3Cdiv class +Name =%22modal-body%22%3E%0A @@ -811,32 +811,36 @@ %3Cdiv class +Name =%22form-group%22%3E%0A @@ -859,25 +859,29 @@ %3Clabel -f +htmlF or=%22%22%3ECurren @@ -1031,24 +1031,28 @@ %3Cdiv class +Name =%22form-group @@ -1079,17 +1079,21 @@ %3Clabel -f +htmlF or=%22newP @@ -1172,24 +1172,28 @@ %3Cdiv class +Name =%22input-grou @@ -1227,16 +1227,20 @@ an class +Name =%22input- @@ -1369,16 +1369,20 @@ class +Name =%22form-c @@ -1623,16 +1623,20 @@ iv class +Name =%22checkb @@ -1807,16 +1807,20 @@ %3Cp class +Name =%22help-b @@ -2047,16 +2047,20 @@ iv class +Name =%22modal- @@ -2118,16 +2118,20 @@ ll class +Name =%22pull-l @@ -2591,16 +2591,20 @@ t%22 class +Name =%22btn bt
1c886954a36b41a4caee717b43267f7af71a202d
Fix Shameless search
app/scripts/src/content/item.js
app/scripts/src/content/item.js
'use strict'; /* This was necessary to priorize Star Wars: The Clone Wars (2008) over Star Wars: Clone Wars (2003). I left this object because it could be useful for other movies/shows */ var fullTitles = { 'Star Wars: The Clone Wars': '"Star Wars: The Clone Wars"', 'The Office (U.S.)': 'The Office (US)', 'The Blind Side': '"The Blind Side"', 'The Avengers': '"The Avengers"', 'The Seven Deadly Sins': '"The Seven Deadly Sins"', 'Young and Hungry': '"Young and Hungry"', 'The 100': '"The 100"', 'The House of Cards Trilogy (BBC)': 'The House of Cards' } function Item(options) { this.title = fullTitles[options.title] || options.title; this.type = options.type; if (this.type === 'show') { this.epTitle = options.epTitle; this.season = options.season; this.episode = options.episode; } } module.exports = Item;
JavaScript
0.000016
@@ -565,16 +565,51 @@ f Cards' +,%0A 'Shameless (U.S.)': 'Shameless' %0A%7D%0A%0Afunc
91e28a45c1ef6cc520c2bf20f5ee4d3fa2b3a024
remove chalk from formatWebpackMessages (#10198)
packages/react-dev-utils/formatWebpackMessages.js
packages/react-dev-utils/formatWebpackMessages.js
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ 'use strict'; const chalk = require('chalk'); const friendlySyntaxErrorLabel = 'Syntax error:'; function isLikelyASyntaxError(message) { return message.indexOf(friendlySyntaxErrorLabel) !== -1; } // Cleans up webpack error messages. function formatMessage(message) { let lines = message.split('\n'); // Strip webpack-added headers off errors/warnings // https://github.com/webpack/webpack/blob/master/lib/ModuleError.js lines = lines.filter(line => !/Module [A-z ]+\(from/.test(line)); // Transform parsing error into syntax error // TODO: move this to our ESLint formatter? lines = lines.map(line => { const parsingError = /Line (\d+):(?:(\d+):)?\s*Parsing error: (.+)$/.exec( line ); if (!parsingError) { return line; } const [, errorLine, errorColumn, errorMessage] = parsingError; return `${friendlySyntaxErrorLabel} ${errorMessage} (${errorLine}:${errorColumn})`; }); message = lines.join('\n'); // Smoosh syntax errors (commonly found in CSS) message = message.replace( /SyntaxError\s+\((\d+):(\d+)\)\s*(.+?)\n/g, `${friendlySyntaxErrorLabel} $3 ($1:$2)\n` ); // Clean up export errors message = message.replace( /^.*export '(.+?)' was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$2'.` ); message = message.replace( /^.*export 'default' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$2' does not contain a default export (imported as '$1').` ); message = message.replace( /^.*export '(.+?)' \(imported as '(.+?)'\) was not found in '(.+?)'.*$/gm, `Attempted import error: '$1' is not exported from '$3' (imported as '$2').` ); lines = message.split('\n'); // Remove leading newline if (lines.length > 2 && lines[1].trim() === '') { lines.splice(1, 1); } // Clean up file name lines[0] = lines[0].replace(/^(.*) \d+:\d+-\d+$/, '$1'); // Cleans up verbose "module not found" messages for files and packages. if (lines[1] && lines[1].indexOf('Module not found: ') === 0) { lines = [ lines[0], lines[1] .replace('Error: ', '') .replace('Module not found: Cannot find file:', 'Cannot find file:'), ]; } // Add helpful message for users trying to use Sass for the first time if (lines[1] && lines[1].match(/Cannot find module.+node-sass/)) { lines[1] = 'To import Sass files, you first need to install node-sass.\n'; lines[1] += 'Run `npm install node-sass` or `yarn add node-sass` inside your workspace.'; } lines[0] = chalk.inverse(lines[0]); message = lines.join('\n'); // Internal stacks are generally useless so we strip them... with the // exception of stacks containing `webpack:` because they're normally // from user code generated by webpack. For more information see // https://github.com/facebook/create-react-app/pull/1050 message = message.replace( /^\s*at\s((?!webpack:).)*:\d+:\d+[\s)]*(\n|$)/gm, '' ); // at ... ...:x:y message = message.replace(/^\s*at\s<anonymous>(\n|$)/gm, ''); // at <anonymous> lines = message.split('\n'); // Remove duplicated newlines lines = lines.filter( (line, index, arr) => index === 0 || line.trim() !== '' || line.trim() !== arr[index - 1].trim() ); // Reassemble the message message = lines.join('\n'); return message.trim(); } function formatWebpackMessages(json) { const formattedErrors = json.errors.map(formatMessage); const formattedWarnings = json.warnings.map(formatMessage); const result = { errors: formattedErrors, warnings: formattedWarnings }; if (result.errors.some(isLikelyASyntaxError)) { // If there are any syntax errors, show just them. result.errors = result.errors.filter(isLikelyASyntaxError); } return result; } module.exports = formatWebpackMessages;
JavaScript
0
@@ -196,40 +196,8 @@ ';%0A%0A -const chalk = require('chalk');%0A cons @@ -2726,47 +2726,8 @@ %7D%0A%0A - lines%5B0%5D = chalk.inverse(lines%5B0%5D);%0A%0A me
d7e2221203de3f69a952ae02562d8e6556ae1087
Set up tests to log in on first getting to the site
test/functional/cucumber/step_definitions/commonSteps.js
test/functional/cucumber/step_definitions/commonSteps.js
var chai = require('chai'); var chaiAsPromised = require('chai-as-promised'); chai.use(chaiAsPromised); var expect = chai.expect; module.exports = function() { disclaimer = element(by.css('div.disclaimer')); this.Given(/^that I am at the HMDA homepage$/, function(next) { browser.get('http://dev.hmda-pilot.ec2.devis.com/#/'); //Prevents 'are you sure you want to leave?' window from popping up browser.executeScript('window.onbeforeunload = function(){};').then(function(){ next(); }); }); this.Then(/^I will see a disclaimer at the top$/, function (next) { expect(disclaimer.isPresent()).to.eventually.be.true.notify(next); }); };
JavaScript
0
@@ -269,32 +269,145 @@ unction(next) %7B%0A + passwordBox = element.all(by.id('txt-pwd'));%0A loginButton = element.all(by.css('.login-button'))%0A%0A browser. @@ -453,16 +453,17 @@ m/#/');%0A +%0A @@ -634,25 +634,222 @@ -next();%0A %7D +if(passwordBox.count() !== 0)%7B%0A //Log in if we have not already done so%0A passwordBox.sendKeys('p1l0t');%0A loginButton.click();%0A %7D%0A %7D);%0A next( );%0A
027b57266d434f156665c3c78bef52f10885a206
delete debug lines for comment paging
lib/fetching/content-services/comments-content-service.js
lib/fetching/content-services/comments-content-service.js
var request = require('request'); var ContentService = require('../content-service'); var util = require('util'); var logger = require('../../logger'); var Report = require('../../../models/report'); var config = require('../../../config/secrets'); var { completeUrl, authenticate, getJWTToken } = require('../../comments'); var CommentContentService = function(options) { this.fetchType = 'pull'; this.interval = 10000; const { count, lastFetchDate, lastAuthoredDate } = config.get().comments; this._count = count; if (lastFetchDate) { this._lastFetchDate = new Date(lastFetchDate); this._lastAuthoredDate = new Date(lastAuthoredDate); } ContentService.call(this, options) } CommentContentService.prototype._doFetch = function(_, callback) { const commentUrl = completeUrl('comment'); const options = { body: { count: this._count }, json: true }; if (this._lastFetchDate && this._lastAuthoredDate) { options.body = { ...options.body, acqAfter: this._lastFetchDate.getTime(), authAfter: this._lastAuthoredDate.getTime(), } } this._sendRequest(commentUrl, options, callback); } CommentContentService.prototype._sendRequest = function(url, opts, callback) { if (typeof getJWTToken() !== 'string') { authenticate((err) => { if (err) { this.emit('error', err); return callback([]); } this._sendRequest(url, opts, callback); }); return; } opts.auth = { bearer: getJWTToken(), } request(url, opts, (err, res, body) => { if (err) { this.emit('error', new Error('HTTP error: ' + err.message)); return callback([]); } else if (res.statusCode === 401) { jwtToken = null; this._sendRequest(url, opts, callback); return; } else if (res.statusCode !== 200) { this.emit('error', new Error.HTTP(res.statusCode)); return callback([]); } var comments = body; try { if (typeof comments === 'string') { comments = JSON.parse(comments); } if (!Array.isArray(comments)) { this.emit('error', new Error('Wrong data')); return callback([]); } } catch (e) { this.emit('error', new Error('Parse error: ' + e.message)); return callback([]); } var remaining = comments.length; var reports = []; if (comments.length === 0) { return callback([]); } this.cache = {}; const { acquiredAt, timestamp } = comments[comments.length - 1]; console.log(`acquiredAt: ${acquiredAt}`); console.log(`timestamp: ${timestamp}`); console.log(`length: ${comments.length}`); // TODO rewrite with async/await to avoid callback hell comments.forEach((doc) => { this._parse(doc, (report) => { reports.push(report); if (--remaining === 0) { config.update( 'comments:lastFetchDate', this._lastFetchDate.getTime(), (err) => { if (err) { logger.error(err); } config.update( 'comments:lastAuthoredDate', this._lastAuthoredDate.getTime(), (err) => { if (err) { logger.error(err); } this._lastFetchDate = new Date(acquiredAt); this._lastAuthoredDate = new Date(timestamp); callback(reports); } ); } ); } }); }); }); } CommentContentService.prototype._parse = function(doc, callback) { var metadata = {} if (typeof doc.media === 'object') { const ext = doc.media.ext; const type = (doc.media.ext === 'mp4') ? 'video' : 'photo'; const mediaUrl = completeUrl(`static/${doc._id}.${ext}`); metadata.mediaUrl = [{ type, mediaUrl }]; } var content = doc.text || 'No Content'; var { post: postUrl, url } = doc; const report = { authoredAt: new Date(doc.timestamp), fetchedAt: new Date(), content, url, metadata, } const post = this.cache[postUrl]; if (!post) { Report.findOne({ url: postUrl }, (err, doc) => { if (err) { logger.error(err); } const { _id, content } = doc; report.commentTo = _id; report.originalPost = content; this.cache[postUrl] = { _id, content }; callback(report); }); } else { const { _id, content } = post; report.commentTo = _id; report.originalPost = content; callback(report); } } util.inherits(CommentContentService, ContentService); module.exports = CommentContentService;
JavaScript
0
@@ -2817,158 +2817,8 @@ %5D;%0A%0A - console.log(%60acquiredAt: $%7BacquiredAt%7D%60);%0A console.log(%60timestamp: $%7Btimestamp%7D%60);%0A console.log(%60length: $%7Bcomments.length%7D%60);%0A%0A
e53deb5d90fa7d6751bb753415dda5274a2b2cb5
increase window size and login in wait time
test/nightwatch_tests/custom-commands/auth/loginToGUI.js
test/nightwatch_tests/custom-commands/auth/loginToGUI.js
// 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. exports.command = LoginToGui; function LoginToGui (user, pw) { const client = this; const waitTime = client.globals.maxWaitTime; const baseUrl = client.globals.test_settings.launch_url; const username = user || client.globals.test_settings.fauxton_username; const password = pw || client.globals.test_settings.password; client .url(baseUrl + '/#/login') .waitForElementPresent('a[href="#/login"]', waitTime, false) .click('a[href="#/login"]') .waitForElementVisible('.couch-login-wrapper', waitTime, false) .waitForElementVisible('#username', waitTime, false) .setValue('.couch-login-wrapper #username', [username]) .waitForElementVisible('#password', waitTime, false) .setValue('.couch-login-wrapper #password', [password]) .clickWhenVisible('#submit') .closeNotification() .waitForElementPresent('[data-name="jump-to-db"]', waitTime, false) // important! wait for the db page to fully load. This was the cause of many bugs .waitForElementVisible('#dashboard-content table.databases', waitTime, false); return this; };
JavaScript
0
@@ -890,16 +890,46 @@ client%0A + .resizeWindow(1200, 1200)%0A .url @@ -995,32 +995,29 @@ #/login%22%5D', -waitTime +50000 , false)%0A
bc9a30c5658c717b7461e5048206ec65d2c63d2d
fix bug in reading db config file
src/lib/modules/connection/repository.js
src/lib/modules/connection/repository.js
'use strict'; const _ = require('underscore'); const Promise = require('bluebird'); const uuid = require('node-uuid'); const fileUtils = require('lib/utils/fileUtils'); const appConfig = require('src/config/appConfig'); const errors = require('lib/errors'); const Connection = require('lib/entities/connection'); const DB_CONNECTIONS = appConfig.dbConfigPath; /** * @class ConnectionRepository */ class ConnectionRepository { /** * @constructor ConnectionRepository */ constructor() {} /** * @method findById */ findById(id) { let _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); return _this.list() .then((connections) => { return findConnectionById(id, connections); }) .then(resolve) .catch(reject); }); } /** * @method create */ create(options) { let _this = this; return new Promise((resolve, reject) => { if (!options) return reject(new errors.InternalServiceError('options is required')); let connections; let newConnection; options.id = uuid.v4(); //assign a "unique" id return _this.list() .then((_connections) => { connections = _connections; return createConnection(options, _connections); }) .then((_connection) => { newConnection = _connection; connections.push(newConnection); return convertConnectionInstancesIntoConfig(connections); }) .then(writeConfigFile) .then(() => { return new Promise((resolve1) => { return resolve1(newConnection); }); }) .then(resolve) .catch(reject); }); } /** * @method list */ list() { return getConnectionInstances(); } /** * @method update * @param {String} id - id of the connection to update */ update(id, options) { var _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); if (!options) return reject(new errors.InvalidArugmentError('options is required')); var connection; return _this.list() .then((connections) => { return findConnectionById(id, connections) .then(function(_connection) { connection = _connection; return updateConnection(_connection, options, connections); }); }) .then(convertConnectionInstancesIntoConfig) .then(writeConfigFile) .then(() => { return resolve(connection); }) .catch(reject); }); } /** * @method delete * @param {String} id - id of the connection to delete */ delete(id) { var _this = this; return new Promise((resolve, reject) => { if (!id) return reject(new errors.InvalidArugmentError('id is required')); return _this.list() .then((connections) => { return findConnectionById(id, connections) .then(function(connection) { return removeConnection(connection, connections); }); }) .then(convertConnectionInstancesIntoConfig) .then(writeConfigFile) .then(() => { return resolve(null); }) .catch(reject); }); } /** * @method existsByName * @param {String} name */ existsByName(name) { var _this = this; return _this.list() .then((connections) => { return new Promise((resolve) => { var existingConnection = _.findWhere(connections, { name: name }); return resolve(existingConnection ? true : false); }); }); } } function readConfigFile() { return new Promise((resolve, reject) => { fileUtils.readJsonFile(DB_CONNECTIONS, (err, data) => { if (err) return reject(err); return resolve(data); }); }); } function writeConfigFile(data) { return new Promise((resolve, reject) => { fileUtils.writeJsonFile(DB_CONNECTIONS, data, (err, data) => { if (err) return reject(err); return resolve(data); }); }); } function getConnectionInstances() { return readConfigFile() .then((connectionConfigs) => { return new Promise((resolve) => { return resolve(connectionConfigs.map(generateConnectionInstanceFromConfig)); }); }); } function generateConnectionInstanceFromConfig(connectionConfig) { var newConn = new Connection({ id: connectionConfig.id || uuid.v4(), name: connectionConfig.name, host: connectionConfig.host, port: connectionConfig.port }); _.each(connectionConfig.databases, (databaseConfig) => { newConn.addDatabase({ id: databaseConfig.id || uuid.v4(), name: databaseConfig.name, host: connectionConfig.host, port: connectionConfig.port, auth: databaseConfig.auth }); }); return newConn; } function convertConnectionInstancesIntoConfig(connections) { return new Promise((resolve) => { return resolve(connections.map(convertConnectionInstanceIntoConfig)); }); } function convertConnectionInstanceIntoConfig(connection) { //unique id's are added to the entities to emulate //storing them in a real database that would assign unique ids //the app relies on the various entities to have unique ids so //until I change to storing these in something that assigns ids //we have to manually add them return { id: connection.id || uuid.v4(), name: connection.name, host: connection.host, port: connection.port, databases: connection.databases ? connection.databases.map((database) => { var db = { name: database.name }; if (database.auth) { db.auth = { id: database.id || uuid.v4(), username: database.auth.username, password: database.auth.password }; } return db; }) : [] }; } function findConnectionById(connectionId, connections) { return new Promise((resolve, reject) => { var foundConnection = _.findWhere(connections, { id: connectionId }); if (foundConnection) { return resolve(foundConnection); } else { return reject(new errors.ObjectNotFoundError('Connection not found')); } }); } function createConnection(options) { return new Promise((resolve) => { var newConn = new Connection(options); newConn.addDatabase({ id: uuid.v4(), name: options.databaseName, host: options.host, port: options.port, auth: options.auth }); return resolve(newConn); }); } function removeConnection(connection, connections) { return new Promise((resolve) => { var index = connections.indexOf(connection); connections.splice(index, 1); return resolve(connections); }); } function updateConnection(connection, options, connections) { return new Promise((resolve) => { connection = _.extend(connection, options); return resolve(connections); }); } /** * @exports */ module.exports = new ConnectionRepository();
JavaScript
0
@@ -3855,177 +3855,45 @@ urn -new Promise((resolve, reject) =%3E %7B%0A fileUtils.readJsonFile(DB_CONNECTIONS, (err, data) =%3E %7B%0A if (err) return reject(err);%0A return resolve(data);%0A %7D);%0A %7D +fileUtils.readJsonFile(DB_CONNECTIONS );%0A%7D @@ -3940,47 +3940,8 @@ urn -new Promise((resolve, reject) =%3E %7B%0A file @@ -3984,101 +3984,8 @@ data -, (err, data) =%3E %7B%0A if (err) return reject(err);%0A return resolve(data);%0A %7D);%0A %7D );%0A%7D @@ -4163,16 +4163,64 @@ nConfigs + && connectionConfigs.length ? connectionConfigs .map(gen @@ -4249,24 +4249,29 @@ eFromConfig) + : %5B%5D );%0A %7D);
a45b78779bdd813dbf2fbaa1145c1c523a9c3d38
Clean up DiscordRESTError
lib/errors/DiscordRESTError.js
lib/errors/DiscordRESTError.js
"use strict"; let a = { "code": 50035, "errors": { "embed": { "color": { "_errors": [ { "code": "NUMBER_TYPE_COERCE", "message": "Value \"#1234\" is not int." } ] } } }, "message": "Invalid Form Body" } let b = { "code": 50035, "errors": { "name": { "_errors": [ { "code": "BASE_TYPE_BAD_LENGTH", "message": "Must be between 2 and 100 in length." }, { "code": "CHANNEL_NAME_INVALID", "message": "Text channel names must be alphanumeric with dashes or underscores." } ] } }, "message": "Invalid Form Body" } class DiscordAPIError extends Error { constructor(req, res, response, stack) { super(); Object.defineProperty(this, "req", { enumerable: false, value: req, writable: false }); Object.defineProperty(this, "res", { enumerable: false, value: res, writable: false }); Object.defineProperty(this, "response", { enumerable: false, value: response, writable: false }); Object.defineProperty(this, "code", { value: +response.code || -1, writable: false }); var message = this.name + ": " + (response.message || "Unknown error"); if(response.errors) { message += "\n " + this.flattenErrors(response.errors).join("\n "); } else { var errors = this.flattenErrors(response); if(errors.length > 0) { message += "\n " + errors.join("\n "); } } Object.defineProperty(this, "message", { value: message, writable: false }); if(stack) { Object.defineProperty(this, "stack", { value: this.message + "\n" + stack, writable: false }); } else { Error.captureStackTrace(this, DiscordAPIError); } } get name() { return `${this.constructor.name} [${this.code}]`; } flattenErrors(errors, keyPrefix) { keyPrefix = keyPrefix || ""; var messages = []; for(var fieldName in errors) { if(fieldName === "message" || fieldName === "code") { continue; } if(errors[fieldName]._errors) { messages = messages.concat(errors[fieldName]._errors.map((obj) => `${keyPrefix + fieldName}: ${obj.message}`)); } else if(Array.isArray(errors[fieldName])) { messages = messages.concat(errors[fieldName].map((str) => `${keyPrefix + fieldName}: ${str}`)); } else if(typeof errors[fieldName] === "object") { messages = messages.concat(this.flattenErrors(errors, keyPrefix + fieldName + ".")); } } return messages; } } module.exports = DiscordAPIError;
JavaScript
0.999879
@@ -12,894 +12,25 @@ %22;%0A%0A -let a = %7B%0A %22code%22: 50035,%0A %22errors%22: %7B%0A %22embed%22: %7B%0A %22color%22: %7B%0A %22_errors%22: %5B%0A %7B%0A %22code%22: %22NUMBER_TYPE_COERCE%22,%0A %22message%22: %22Value %5C%22#1234%5C%22 is not int.%22%0A %7D%0A %5D%0A %7D%0A %7D%0A %7D,%0A %22message%22: %22Invalid Form Body%22%0A%7D%0Alet b = %7B%0A %22code%22: 50035,%0A %22errors%22: %7B%0A %22name%22: %7B%0A %22_errors%22: %5B%0A %7B%0A %22code%22: %22BASE_TYPE_BAD_LENGTH%22,%0A %22message%22: %22Must be between 2 and 100 in length.%22%0A %7D,%0A %7B%0A %22code%22: %22CHANNEL_NAME_INVALID%22,%0A %22message%22: %22Text channel names must be alphanumeric with dashes or underscores.%22%0A %7D%0A %5D%0A %7D%0A %7D,%0A %22message%22: %22Invalid Form Body%22%0A%7D%0A%0Aclass DiscordAPI +class DiscordREST Erro @@ -1401,27 +1401,28 @@ his, Discord -API +REST Error);%0A @@ -2357,11 +2357,12 @@ cord -API +REST Erro
07ed62a4b92537a0132d5a85e50b6248c8d6349d
Call refresh() when the value of the excludeInvisible option changes. Fixes #6199.
js/widgets/controlgroup.js
js/widgets/controlgroup.js
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); //>>description: Visually groups sets of buttons, checks, radios, etc. //>>label: Controlgroups //>>group: Forms //>>css.structure: ../css/structure/jquery.mobile.controlgroup.css //>>css.theme: ../css/themes/default/jquery.mobile.theme.css define( [ "jquery", "./addFirstLastClasses", "../jquery.mobile.registry", "../jquery.mobile.widget" ], function( jQuery ) { //>>excludeEnd("jqmBuildExclude"); (function( $, undefined ) { $.widget( "mobile.controlgroup", $.extend( { options: { enhanced: false, theme: null, shadow: false, corners: true, excludeInvisible: true, type: "vertical", mini: false, initSelector: ":jqmData(role='controlgroup')" }, _create: function() { var elem = this.element, opts = this.options; $.extend( this, { _ui: null, _classes: "", _initialRefresh: true }); if ( opts.enhanced ) { this._ui = { groupLegend: elem.children( ".ui-controlgroup-label" ).children(), childWrapper: elem.children( ".ui-controlgroup-controls" ) }; this._applyOptions( opts, true ); } else { this._ui = { groupLegend: elem.children( "legend" ), childWrapper: elem .wrapInner( "<div class='ui-controlgroup-controls'></div>" ) .addClass( "ui-controlgroup" ) .children() }; if ( this._ui.groupLegend.length > 0 ) { $( "<div role='heading' class='ui-controlgroup-label'></div>" ) .append( this._ui.groupLegend ) .prependTo( elem ); } this._setOptions( opts ); } }, _init: function() { this.refresh(); }, _applyOptions: function( options, internal ) { var callRefresh, opts, classes = ""; // Must not be able to unset the type of the controlgroup if ( options.type === null ) { options.type = undefined; } opts = $.extend( {}, this.options, options ); if ( opts.type != null ) { classes += " ui-controlgroup-" + opts.type; // No need to call refresh if the type hasn't changed if ( this.options.type !== options.type ) { callRefresh = true; } } if ( opts.theme != null && opts.theme !== "none" ) { classes += " ui-group-theme-" + opts.theme; } if ( opts.corners ) { classes += " ui-corner-all"; } if ( opts.mini ) { classes += " ui-mini"; } if ( !( opts.shadow === undefined || internal ) ) { this._ui.childWrapper.toggleClass( "ui-shadow", opts.shadow ); } if ( internal ) { this._classes = classes; } else { this._toggleClasses( this.element, "_classes", classes ); if ( callRefresh ) { this.refresh(); } } return this; }, _setOptions: function( options ) { return this ._applyOptions( options ) ._super( options ); }, container: function() { return this._ui.childWrapper; }, refresh: function() { var $el = this.container(), els = $el.find( ".ui-btn" ).not( ".ui-slider-handle" ), create = this._initialRefresh; if ( $.mobile.checkboxradio ) { $el.find( ":mobile-checkboxradio" ).checkboxradio( "refresh" ); } this._addFirstLastClasses( els, this.options.excludeInvisible ? this._getVisibles( els, create ) : els, create ); this._initialRefresh = false; }, // Caveat: If the legend is not the first child of the controlgroup at enhance // time, it will be after _destroy(). _destroy: function() { var ui, buttons; if ( this.options.enhanced ) { return this; } ui = this._ui; buttons = this.element .removeClass( "ui-controlgroup " + this._classes ) .find( ".ui-btn" ) .not( ".ui-slider-handle" ); this._removeFirstLastClasses( buttons ); ui.groupLegend.unwrap(); ui.childWrapper.children().unwrap(); } }, $.mobile.behaviors.addFirstLastClasses ) ); $.mobile.controlgroup.initSelector = ":jqmData(role='controlgroup')"; $.mobile._enhancer.add( "mobile.controlgroup", { dependencies: [ "mobile.selectmenu", "mobile.button", "mobile.checkboxradio" ] }); })(jQuery); //>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude); }); //>>excludeEnd("jqmBuildExclude");
JavaScript
0
@@ -2027,24 +2027,62 @@ ns.type ) %7B%0A +%09%09%09%09this.options.type = options.type;%0A %09%09%09%09callRefr @@ -2444,24 +2444,163 @@ dow );%0A%09%09%7D%0A%0A +%09%09if ( options.excludeInvisible !== undefined ) %7B%0A%09%09%09this.options.excludeInvisible = options.excludeInvisible;%0A%09%09%09callRefresh = true;%0A%09%09%7D%0A%0A %09%09if ( inter
2fd279b5a01c27646946a33c3ed7d9a319173d6e
add todo tag
script.js
script.js
var apiKey = "FtHwuH8w1RDjQpOr0y0gF3AWm8sRsRzncK3hHh9"; var xhr = new XMLHttpRequest(); xhr.open("GET", "http://www.boruili.com/", false); xhr.send(); console.log(xhr.status); console.log(xhr.statusText); function showResponse(response) { var responseString = JSON.stringify(response, '', 2); document.getElementById('response').innerHTML += responseString; } function onClientLoad() { gapi.client.load('youtube', 'v3', onYouTubeApiLoad); } // add a api key
JavaScript
0
@@ -452,16 +452,22 @@ );%0A%7D%0A%0A// + TODO: add a a
e67259ce629fd1f7f922b6ef9386a0627bb29937
Fix empty favourites bug
www/js/services/favourites.js
www/js/services/favourites.js
var services = angular.module('services.favourites', []); services.factory('FavouritesService', function ($window) { var service = { favourites: [], getFavourites: function () { return service.favourites; }, isFavourite: function (id) { var index = service.favourites.indexOf(id); if (index > -1) { console.log("Is Favourite."); return true; } console.log("Is NOT Favourite."); return false; }, resaveFavourites: function () { $window.localStorage.favourites = angular.toJson(service.favourites); }, addFavourite: function (value) { service.favourites.push(value); service.resaveFavourites(); }, removeFavourite: function (value) { var index = service.favourites.indexOf(value); if (index > -1) { service.favourites.splice(index, 1); } service.resaveFavourites(); }, loadFavourites: function () { service.favourites = angular.fromJson($window.localStorage.favourites); }, removeAll: function () { delete $window.localStorage.favourites; service.resaveFavourites(); } }; return service; });
JavaScript
0.000002
@@ -291,36 +291,40 @@ -var index = +angular.forEach( service.favo @@ -333,98 +333,71 @@ ites -.indexOf(id);%0A if (index %3E -1) %7B%0A console.log(%22Is Favourite.%22);%0A +, function(value, key) %7B%0A if (id == value) %7B%0A @@ -404,24 +404,25 @@ + return true; @@ -422,16 +422,20 @@ n true;%0A + @@ -456,39 +456,9 @@ -console.log(%22Is NOT Favourite.%22 +%7D );%0A @@ -1068,34 +1068,24 @@ -service.favourites +var data = angul @@ -1122,32 +1122,153 @@ ge.favourites);%0A + angular.forEach(data, function(value, key) %7B%0A service.favourites.push(value);%0A %7D);%0A %7D,%0A%0A
4844c57a9a3b906465b9bcc1911f5530bf53a3a3
use correct config when file present
app/index.js
app/index.js
'use strict'; var genUtils = require('../util'); var path = require('path'); var yeoman = require('yeoman-generator'); var bangAscii = require('./ascii'); var chalk = require('chalk'); function bangLog (msg, color) { console.log('[' + chalk.blue('bangular') + ']: ' + chalk[color](msg)); } var BangularGenerator = yeoman.generators.Base.extend({ initializing: { getVars: function () { this.appname = this.appname || path.basename(process.cwd()); this.filters = {}; this.pkg = require('../package.json'); }, info: function () { if (this.options.skipLog) { return ; } this.log(bangAscii); }, checkConfig: function () { if (this.config.get('filters')) { var done = this.async(); var self = this; this.prompt([{ type: 'confirm', name: 'skipConfig', message: 'You have a .yo-rc file in this directory, do you want to skip install steps?', default: true }], function (props) { self.skipConfig = props.skipConfig; done(); }); } } }, prompting: function () { if (this.skipConfig) { return ; } var done = this.async(); var self = this; this.prompt([{ type: 'input', name: 'name', message: 'Your project name', default: self.appname }, { type: 'list', name: 'backend', message: 'Choose a backend type', choices: [{ value: 'mongo', name: 'MongoDb, with Mongoose as ODM' }, { value: 'json', name: 'Good old JSON' }, { value: 'restock', name: 'Restock.io, for mocking purpose' }] }, { type: 'checkbox', name: 'modules', message: 'Which module do you want to load?', choices: [{ value: 'ngCookies', name: 'angular-cookies', checked: false }, { value: 'ngResource', name: 'angular-resource', checked: false }, { value: 'ngSanitize', name: 'angular-sanitize', checked: false }, { value: 'ngAnimate', name: 'angular-animate', checked: false }] }], function (props) { self.appname = self._.camelize(self._.slugify(self._.humanize(props.name))); self.filters.backend = props.backend; if (props.modules.length) { props.modules.forEach(function (module) { self.filters[module] = true; }); } if (props.backend === 'mongo') { self.prompt([{ type: 'confirm', name: 'sockets', message: 'Do you want to add socket support?', default: false }, { type: 'confirm', name: 'auth', message: 'Do you want to scaffold a passport authentication process?', default: false }], function (props) { self.filters.sockets = props.sockets; self.filters.auth = props.auth; if (props.auth) { self.filters.ngCookies = true; } done(); }); } else { done(); } }); }, saveSettings: function () { if (this.skipConfig) { return ; } this.config.set('version', this.pkg.version); this.config.set('filters', this.filters); }, generate: function () { this.sourceRoot(path.join(__dirname, './templates')); genUtils.processDirectory(this, '.', '.'); this.mkdir('client/assets/fonts'); this.mkdir('client/assets/images'); }, end: function () { /* istanbul ignore if */ if (!this.options.skipInstall) { bangLog('Installing dependencies...', 'yellow'); } this.installDependencies({ skipInstall: this.options.skipInstall, skipMessage: true, callback: function () { bangLog('Everything is ready !\n', 'green'); } }); } }); module.exports = BangularGenerator;
JavaScript
0.000002
@@ -1048,16 +1048,69 @@ Config;%0A + self.filters = self.config.get('filters');%0A
307f643f677cc23443dde5b6bb4ba80d9b5b4b36
Update tools and pre-processors
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var spaw = require('child_process').spaw; var chalk = require('chalk'); var globule = require('globule'); var shelljs = require('shelljs'); var yeoman = require('yeoman-generator'); var bundle = false; var errr = chalk.bold.red; var MilagroGenerator = module.exports = function MilagroGenerator(args, options, config) { var dependenciesInstalled = ['bundle', 'ruby'].every(function (depend) { return shelljs.which(depend); }); if (!dependenciesInstalled) { console.log(errr('Erro!') + ' Certifique-se de ter instalado: ' + chalk.white('Ruby') + ' e ' +chalk.white('Bundler (gem)') + '.'); shelljs.exit(1); } yeoman.generators.Base.apply(this, arguments); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); this.appname = path.basename(process.cwd()); this.gitInfo = { name: this.user.git.username, email: this.user.git.email, }; this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'] }); if (bundle === false) { console.log(errr('Erro! Bundle install failed! ') + 'Execute o comando manualmente, \'gem install bundle\''); } }); }; util.inherits(MilagroGenerator, yeoman.generators.Base); // Questions! MilagroGenerator.prototype.askForProject = function askForProject() { var cb = this.async(); var prompts = [{ name: 'project', message: 'Nome do projeto: ' }, { name: 'client', message: 'Nome do cliente' }]; this.prompt(prompts, function (props) { this.project = props.project; this.client = props.client; cb(); }.bind(this)); }; // MilagroGenerator.prototype.askFor = function askFor() { // var cb = this.async(); // // have Yeoman greet the user. // console.log(this.yeoman); // var prompts = [{ // type: 'confirm', // name: 'someOption', // message: 'Would you like to enable this option?', // default: true // }]; // this.prompt(prompts, function (props) { // this.someOption = props.someOption; // cb(); // }.bind(this)); // }; // MilagroGenerator.prototype.app = function app() { // this.mkdir('app'); // this.mkdir('app/templates'); // this.copy('_package.json', 'package.json'); // this.copy('_bower.json', 'bower.json'); // }; // MilagroGenerator.prototype.projectfiles = function projectfiles() { // this.copy('editorconfig', '.editorconfig'); // this.copy('jshintrc', '.jshintrc'); // };
JavaScript
0
@@ -1681,24 +1681,410 @@ this));%0A%7D;%0A%0A +MilagroGenerator.prototype.askForTools = function askForTools() %7B%0A var cb = this.async();%0A var prompts = %5B%7B%0A name: 'cssPre',%0A type: 'list',%0A message: 'Pr%C3%A9-processadores CSS?',%0A choices: %5B'Compass', 'Sass', 'None'%5D%0A %7D,%0A %7B%0A name: 'autoPre',%0A type: 'confirm',%0A message: 'CSS Autoprefixer?'%0A %7D%5D;%0A%0A console.log(chalk.blue('Ferramentas e pr%C3%A9-processadores: '));%0A%7D%0A%0A // MilagroGe
7e43e6f681a34fead0ec3644844cb1b7df306929
Update touch.js
html5-2/touch.js
html5-2/touch.js
document.getElementById("id_logic_version").innerHTML = "Logic version: 2018.11.26.10"; var canvas = document.getElementById("id_canvas"); canvas.addEventListener("touchstart", on_touch_start); canvas.addEventListener("touchmove", on_touch_move); canvas.addEventListener("touchend", on_touch_end); var canvas_bounding_rect = canvas.getBoundingClientRect(); var last_pos_array = []; //------------------------------------ function on_touch_start(e) { for (var i = 0; i < e.changedTouches.length; i++){ var context = canvas.getContext("2d"); context.beginPath(); context.fillStyle = "black"; context.arc(e.changedTouches[i].pageX - canvas_bounding_rect.left, e.changedTouches[i].pageY - canvas_bounding_rect.top, 10, 0, 2 * Math.PI); context.fill(); context.stroke(); var last_pos = {x: e.changedTouches[i].pageX, y: e.changedTouches[i].pageY, id: e.changedTouches[i].identifier}; last_pos_array.push(last_pos); } } //------------------------------------ function on_touch_move(e) { e.preventDefault(); for (var i = 0; i < e.changedTouches.length; i++){ var j = 0; for (; j < last_pos_array.length; j++) if (last_pos_array[j].id == e.changedTouches[i].identifier) break; var context = canvas.getContext("2d"); context.beginPath(); context.lineWidth = 20; context.moveTo(last_pos_array[j].x - canvas_bounding_rect.left, last_pos_array[j].y - canvas_bounding_rect.top); context.lineTo(e.changedTouches[i].pageX - canvas_bounding_rect.left, e.changedTouches[i].pageY - canvas_bounding_rect.top); context.stroke(); context.beginPath(); context.lineWidth = 1; context.fillStyle = "black"; context.arc(e.changedTouches[i].pageX - canvas_bounding_rect.left, e.changedTouches[i].pageY - canvas_bounding_rect.top, 10, 0, 2 * Math.PI); context.fill(); context.stroke(); last_pos_array[j].x = e.changedTouches[i].pageX; last_pos_array[j].y = e.changedTouches[i].pageY; } } //-------------------------------------- function on_touch_end(e) { for (var i = 0; i < e.changedTouches.length; i++){ var j = 0; for (; j < last_pos_array.length; j++) if (last_pos_array[j].id == e.changedTouches[i].identifier) break; last_pos_array.splice(j, 1); } } //--------------------------------------
JavaScript
0.000001
@@ -77,17 +77,17 @@ .11.26.1 -0 +1 %22;%0Avar c @@ -568,36 +568,348 @@ ;%0A%09%09 -context.fillStyle = %22black%22; +var last_pos = %7Bx: e.changedTouches%5Bi%5D.pageX, %0A%09%09%09%09%09%09y: e.changedTouches%5Bi%5D.pageY, %0A%09%09%09%09%09%09id: e.changedTouches%5Bi%5D.identifier,%0A%09%09%09%09%09%09color: get_random_color()%7D;%0A%09%09last_pos_array.push(last_pos);%0A%0A%09%09context.fillStyle = last_pos_array%5Blast_pos_array.length - 1%5D.color;%0A%09%09context.strokeStyle = last_pos_array%5Blast_pos_array.length - 1%5D.color;%0A%09%09 %0A%09%09c @@ -1106,170 +1106,8 @@ ();%0A -%09%09var last_pos = %7Bx: e.changedTouches%5Bi%5D.pageX, %0A%09%09%09%09%09%09y: e.changedTouches%5Bi%5D.pageY, %0A%09%09%09%09%09%09id: e.changedTouches%5Bi%5D.identifier%7D;%0A%0A%09%09last_pos_array.push(last_pos); %0A%09%7D%0A @@ -1471,16 +1471,112 @@ h = 20;%0A +%09%09context.fillStyle = last_pos_array%5Bj%5D.color;%0A%09%09context.strokeStyle = last_pos_array%5Bj%5D.color;%0A %09%09contex @@ -1913,16 +1913,82 @@ e = -%22black%22; +last_pos_array%5Bj%5D.color;%0A%09%09context.strokeStyle = last_pos_array%5Bj%5D.color;%0A %0A%09%09c
3b6babfd8563a1e95a0f7d9b55b79b86bf6f8e77
Update namespace
lib/node_modules/@stdlib/number/float64/base/lib/index.js
lib/node_modules/@stdlib/number/float64/base/lib/index.js
/** * @license Apache-2.0 * * Copyright (c) 2018 The Stdlib Authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ 'use strict'; /* * When adding modules to the namespace, ensure that they are added in alphabetical order according to module name. */ // MODULES // var setReadOnly = require( '@stdlib/utils/define-read-only-property' ); // MAIN // /** * Top-level namespace. * * @namespace ns */ var ns = {}; /** * @name exponent * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/exponent} */ setReadOnly( ns, 'exponent', require( '@stdlib/number/float64/base/exponent' ) ); /** * @name fromBinaryString * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/from-binary-string} */ setReadOnly( ns, 'fromBinaryString', require( '@stdlib/number/float64/base/from-binary-string' ) ); /** * @name fromWords * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/from-words} */ setReadOnly( ns, 'fromWords', require( '@stdlib/number/float64/base/from-words' ) ); /** * @name getHighWord * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/get-high-word} */ setReadOnly( ns, 'getHighWord', require( '@stdlib/number/float64/base/get-high-word' ) ); /** * @name getLowWord * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/get-low-word} */ setReadOnly( ns, 'getLowWord', require( '@stdlib/number/float64/base/get-low-word' ) ); /** * @name normalize * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/normalize} */ setReadOnly( ns, 'normalize', require( '@stdlib/number/float64/base/normalize' ) ); /** * @name setHighWord * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/set-high-word} */ setReadOnly( ns, 'setHighWord', require( '@stdlib/number/float64/base/set-high-word' ) ); /** * @name setLowWord * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/set-low-word} */ setReadOnly( ns, 'setLowWord', require( '@stdlib/number/float64/base/set-low-word' ) ); /** * @name signbit * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/signbit} */ setReadOnly( ns, 'signbit', require( '@stdlib/number/float64/base/signbit' ) ); /** * @name toBinaryString * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/to-binary-string} */ setReadOnly( ns, 'toBinaryString', require( '@stdlib/number/float64/base/to-binary-string' ) ); /** * @name float64ToFloat32 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/to-float32} */ setReadOnly( ns, 'float64ToFloat32', require( '@stdlib/number/float64/base/to-float32' ) ); /** * @name float64ToInt32 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/to-int32} */ setReadOnly( ns, 'float64ToInt32', require( '@stdlib/number/float64/base/to-int32' ) ); /** * @name float64ToUint32 * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/to-uint32} */ setReadOnly( ns, 'float64ToUint32', require( '@stdlib/number/float64/base/to-uint32' ) ); /** * @name toWords * @memberof ns * @readonly * @type {Function} * @see {@link module:@stdlib/number/float64/base/to-words} */ setReadOnly( ns, 'toWords', require( '@stdlib/number/float64/base/to-words' ) ); // EXPORTS // module.exports = ns;
JavaScript
0.000001
@@ -3605,32 +3605,278 @@ to-int32' ) );%0A%0A +/**%0A* @name float64ToInt64Bytes%0A* @memberof ns%0A* @readonly%0A* @type %7BFunction%7D%0A* @see %7B@link module:@stdlib/number/float64/base/to-int64-bytes%7D%0A*/%0AsetReadOnly( ns, 'float64ToInt64Bytes', require( '@stdlib/number/float64/base/to-int64-bytes' ) );%0A%0A /**%0A* @name floa
60a2f60cebd3d17a897ca9df75dac619378d1edf
Add convert time helper function for remaining time in fileUploadFactory.js
client/app/components/client_utilities/factories/fileUploadFactory.js
client/app/components/client_utilities/factories/fileUploadFactory.js
angular.module('utils.fileUpload', ['utils.fileReader']) .factory('fileUpload', ['fileReader', 'fileTransfer', function(fileReader, fileTransfer) { var fileUploadObj = {}; fileUploadObj.getFiles = function() { return document.getElementById('filesId').files; }; fileUploadObj.convertFromBinary = function(data) { var kit = {}; kit.href = URL.createObjectURL(data.file); kit.name = data.name; kit.size = data.size; return kit; }; fileUploadObj.convert = function(num) { if (num > 1000000000) { return (num / 1000000000).toFixed(2) + ' GB' } else if (num > 1000000) { return (num / 1000000).toFixed(2) + ' MB' } else { return (num / 1000).toFixed(2) + ' KB' } }; fileUploadObj.acceptFileOffer = function(offer) { offer.conn.send({ name: offer.name, size: offer.rawSize, type: 'file-accepted' }); var index = fileTransfer.offers.indexOf(offer); fileTransfer.offers.splice(index, 1); }; fileUploadObj.rejectFileOffer = function(offer) { var index = fileTransfer.offers.indexOf(offer); fileTransfer.offers.splice(index, 1); }; fileUploadObj.getTransferRate = function(transferObj) { var currentTime = Date.now(); var timeToWait = 100; // ms if (currentTime >= transferObj.nextTime) { transferObj.nextTime = Date.now() + timeToWait; var pastBytes = transferObj.stored; transferObj.stored = transferObj.progress; var rate = ((transferObj.stored - pastBytes)) / (timeToWait) // B/ms (KB/s) console.log('CURRENT BYTES', transferObj.stored); console.log('PASTCOUNT', pastBytes); console.log('DIFFERENCE', transferObj.stored - pastBytes); var maxFileSize = transferObj.size; timeRemaining = (maxFileSize - transferObj.stored) / rate; // bytes / bytes/ms -> ms console.log('maxFileSize', maxFileSize); console.log('REMAINING BYTES', maxFileSize - transferObj.stored); var convertedRate = function(rate) { if (rate > 1000) { return (rate / 1000).toString() + ' MB/s'; } else { return (rate.toString() + " KB/s") } } console.log('RATE:', convertedRate(rate)); console.log('TIME REMAINING:', (timeRemaining / 1000).toFixed(0), 's') } } return fileUploadObj; }]);
JavaScript
0
@@ -1263,16 +1263,17 @@ 100 +0 ; // ms%0A @@ -1264,24 +1264,24 @@ 1000; // ms%0A - if (curr @@ -1815,34 +1815,31 @@ rate -; // bytes / bytes/ms + / 1000; // ms/1000 -%3E -m s%0A @@ -1968,26 +1968,24 @@ var convert -ed Rate = funct @@ -1992,24 +1992,48 @@ ion(rate) %7B%0A + // expects KB/s%0A if ( @@ -2176,24 +2176,25 @@ %7D%0A %7D%0A +%0A consol @@ -2215,18 +2215,16 @@ convert -ed Rate(rat @@ -2227,16 +2227,701 @@ (rate)); +%0A%0A var convertTime = function(time) %7B%0A // expects seconds%0A%0A var sec_num = parseInt(time, 10); // don't forget the second param%0A var hours = Math.floor(sec_num / 3600);%0A var minutes = Math.floor((sec_num - (hours * 3600)) / 60);%0A var seconds = sec_num - (hours * 3600) - (minutes * 60);%0A%0A if (hours %3C 10) %7B%0A hours = %220%22 + hours;%0A %7D%0A if (minutes %3C 10) %7B%0A minutes = %220%22 + minutes;%0A %7D%0A if (seconds %3C 10) %7B%0A seconds = %220%22 + seconds;%0A %7D%0A var time = minutes + ':' + seconds;%0A if (hours %3E 0) %7B%0A time = hours + ':' + time;%0A %7D%0A return time;%0A %7D%0A %0A c @@ -2950,16 +2950,27 @@ NING:', +convertTime (timeRem @@ -2979,32 +2979,9 @@ ning - / 1000).toFixed(0), 's' +) )%0A
21ff6819850dcdfb4641cbc0f43a33b341cb07ad
fix reference to checkLintStagedRc
packages/pluginsdk/scripts/check-plugin/linters/lint.lintstagedrc.json.js
packages/pluginsdk/scripts/check-plugin/linters/lint.lintstagedrc.json.js
const { assertFileExists } = require('../asserters/assertFileExists'); function checkLintStaged(report) { assertFileExists(report, '.lintstagedrc.json'); } module.exports = { checkLintStaged };
JavaScript
0
@@ -89,16 +89,18 @@ ntStaged +Rc (report) @@ -189,12 +189,14 @@ ntStaged +Rc %7D;%0A
7bd34e1674507d90741fa341618c7132dcf8e5d0
remove init function, use constructor function
jslibraryboilerplate_js.js
jslibraryboilerplate_js.js
/*! * JavaScript Library Boilerplate * Copyright (c) 2013 Denis Ciccale (@tdecs) * Released under MIT license (https://raw.github.com/dciccale/jslibraryboilerplate/master/LICENSE.txt) */ (function (window) { var document = window.document, // helper methods push = [].push, slice = [].slice, splice = [].splice, forEach = [].forEach; // handle the use of $(...) function JSLB(selector) { // auto-create new instance without the 'new' keyword if (!(this instanceof JSLB)) { return new JSLB.prototype.init(selector); } // no selector, return empty JSLB object if (!selector) { return this; } // already a JSLB object if (selector instanceof JSLB) { return selector; } // already a dom element? if (selector.nodeType) { this[0] = selector; this.length = 1; return this; } // is css selector, query the dom if (typeof selector === 'string') { // find elements, turn NodeList to array and push them to JSLB return push.apply(this, slice.call(document.querySelectorAll(selector))); } // it's a function, call it when DOM is ready if (typeof selector === 'function') { return JSLB(document).ready(selector); } }; JSLB.prototype = { // default length of a JSLB object is 0 length: 0, // document ready method ready: function (callback) { // first check if already loaded if (/t/.test(document.readyState)) { callback(JSLB); // listen when it loads } else { document.addEventListener('DOMContentLoaded', function () { callback(JSLB); }, false); } }, // iterate JSLB object each: function (callback) { forEach.call(this, function (el, i) { callback.call(el, i, el); }); }, // sample method to get/set the text of an element text: function (value) { // no element if (!this[0]) { return this; } // get value if (!value) { return this[0].textContent; // set value to all elements on the collection } else { return this.each(function () { this.textContent = value; }); } } }; // abbreviate "prototype" to "fn" JSLB.fn = JSLB.prototype; // just to have an array like instanceof JSLB object JSLB.prototype.splice = splice; // expose to global object window.JSLB = window.$ = JSLB; }(window));
JavaScript
0.000001
@@ -531,23 +531,8 @@ JSLB -.prototype.init (sel
1d28bcaa7d4aa6dd0182c9cc0ebc47faa3c46e36
Add throws annotation and directly require join
lib/node_modules/@stdlib/utils/configdir/lib/configdir.js
lib/node_modules/@stdlib/utils/configdir/lib/configdir.js
'use strict'; // MODULES // var path = require( 'path' ); var isWindows = require( '@stdlib/utils/is-windows' ); var isString = require( '@stdlib/utils/is-string' ).isPrimitive; var platform = require( '@stdlib/utils/platform' ); var homedir = require( '@stdlib/utils/homedir' ); // MAIN // /** * Returns a directory for user-specific configuration files. * * @param {string} [p] - path to append to a base directory * @returns {(string|null)} directory * * @example * var dir = configdir(); * // e.g., returns '/Users/<username>/Library/Preferences' * @example * var dir = configdir( 'appname/config' ); * // e.g., returns '/Users/<username>/Library/Preferences/appname/config' */ function configdir( p ) { var append; var home; var dir; var env; env = process.env; if ( arguments.length ) { if ( !isString( p ) ) { throw new TypeError( 'invalid input argument. Must provide a string primitive. Value: `' + p + '`.' ); } append = p; } else { append = ''; } if ( isWindows ) { // http://blogs.msdn.com/b/patricka/archive/2010/03/18/where-should-i-store-my-data-and-configuration-files-if-i-target-multiple-os-versions.aspx // https://en.wikipedia.org/wiki/Environment_variable#Windows dir = env[ 'LOCALAPPDATA' ] || env[ 'APPDATA' ]; return ( dir ) ? path.join( dir, append ) : null; } home = homedir(); if ( home === null ) { return null; } if ( platform === 'darwin' ) { // http://stackoverflow.com/questions/410013/where-do-osx-applications-typically-store-user-configuration-data return path.join( home, 'Library', 'Preferences', append ); } // http://www.pathname.com/fhs/ // http://www.pathname.com/fhs/pub/fhs-2.3.html // http://standards.freedesktop.org/basedir-spec/basedir-spec-latest.html dir = env[ 'XDG_CONFIG_HOME' ] || path.join( home, '.config' ); return path.join( dir, append ); } // end FUNCTION configdir() // EXPORTS // module.exports = configdir;
JavaScript
0
@@ -27,20 +27,20 @@ //%0A%0Avar -path +join = requi @@ -51,16 +51,21 @@ 'path' ) +.join ;%0Avar is @@ -420,16 +420,80 @@ rectory%0A +* @throws %7BTypeError%7D first argument must be a string primitive%0A * @retur @@ -1347,21 +1347,16 @@ dir ) ? -path. join( di @@ -1589,29 +1589,24 @@ ta%0A%09%09return -path. join( home, @@ -1836,21 +1836,16 @@ E' %5D %7C%7C -path. join( ho @@ -1873,13 +1873,8 @@ urn -path. join
5437696a75f7e50cb781405ba20db78d6a2b3d45
Make staticRoot configurable
geotwitter.js
geotwitter.js
#!/usr/bin/env node 'use strict'; /*jslint node: true, es5: true, indent: 2 */ var amulet = require('amulet'); var fs = require('fs'); var http = require('http-enhanced'); var logger = require('winston'); var mime = require('mime'); var path = require('path'); var sv = require('sv'); var socketio = require('socket.io'); var util = require('util'); var Cookies = require('cookies'); var Router = require('regex-router'); var TwitterPool = require('./twitter-pool'); var argv = require('optimist').default({ port: 3600, hostname: '127.0.0.1', accounts: '~/.twitter', }).argv; // minify: true, amulet.set({root: path.join(__dirname, 'templates')}); mime.default_type = 'text/plain'; var staticRoot = 'http://127.0.0.1:3601'; var static_buffers = []; // set up some local static file handling. var R = new Router(); R.get(/^\/favicon.ico/, function(m, req, res) { res.die(404, '404, chromebuddy.'); }); R.get(/^\/static\/(.+)/, function(m, req, res) { var filepath = m[1].replace(/\.{2,}/g, ''); var content_type = mime.lookup(filepath); res.writeHead(200, {'Content-Type': content_type}); if (static_buffers[filepath]) { res.end(static_buffers[filepath]); } else { fs.readFile(path.join('static', filepath), function (err, data) { if (err) throw err; static_buffers[filepath] = data; res.end(data); }); } }); // and render basic static page R.default = function(m, req, res) { var ctx = {staticRoot: staticRoot}; amulet.stream(['layout.mu', 'show.mu'], ctx).pipe(res); }; // quickstart the simple server var server = http.createServer(function(req, res) { // req.cookies = new Cookies(req, res); var started = Date.now(); res.on('finish', function() { logger.info('duration', {url: req.url, method: req.method, ms: Date.now() - started}); }); R.route(req, res); }).listen(argv.port, argv.hostname, function() { logger.info('GeoTwitter ready at ' + argv.hostname + ':' + argv.port); }); // this is the bit that pulls in Twitter var twitter_pool = new TwitterPool(); sv.Parser.readToEnd(argv.accounts, {encoding: 'utf8'}, function(err, accounts) { if (err) throw err; twitter_pool.accounts = accounts; logger.info('Read ' + accounts.length + ' accounts'); }); var BOUNDS = { // sw.lon,sw.lat,ne.lon,ne.lat global: '-180,-90,180,90', usa: '-126.3867,24.7668,-65.8301,49.4967', illinois: '-91.5131,36.9703,-87.4952,42.5083' }; // mostly pull things from the twitter pipe and push them over into all sockets var io = socketio.listen(server); // it will log every emitted payload at the default log level (crazy!) io.set('log level', 1); io.sockets.on('connection', function (socket) { logger.info('New socket connection established'); socket.emit('greeting', {text: 'Hello.', connected: Object.keys(io.connected).length}); logger.info('twitter_pool.responses', {responses: twitter_pool.responses.length}); function ready() { var current_req = twitter_pool.responses[0].request; logger.info('current request', current_req.form); socket.emit('filter', current_req.form); } // if anybody is listening and we aren't already streaming tweets, start a default one if (twitter_pool.responses.length === 0) { var form = {locations: BOUNDS.illinois, stall_warnings: true}; logger.debug('Starting default filter.', form); twitter_pool.addPersistent(form, ready); } else { ready(); } socket.on('filter', function (form) { logger.info('filtering', form); twitter_pool.removeAll(); // var form = {stall_warnings: true}; // data.type should be either 'locations' or 'track' // form[data.type] = data.query; twitter_pool.addPersistent(form); io.sockets.emit('filter', form); }); socket.on('chat', function (data) { logger.info('Socket emitted "chat" message:', data); // "broadcast." just means emit only to the others with connections // socket.broadcast.emit('chat', data); io.sockets.emit('chat', data); }); }); twitter_pool.on('data', function(data) { io.sockets.emit('tweet', data); });
JavaScript
0.000004
@@ -568,16 +568,55 @@ itter',%0A + staticRoot: 'http://127.0.0.1:3601',%0A %7D).argv; @@ -728,50 +728,8 @@ ';%0A%0A -var staticRoot = 'http://127.0.0.1:3601';%0A var @@ -1447,16 +1447,21 @@ icRoot: +argv. staticRo
1bf43b1bfe8b90d199239f39acbd4c8338db0ddd
Update TODO list (preparation for GA task)
app/index.js
app/index.js
/* * TODO: * - h5bp via bower + add variable to settings * - mixins * - open sublime when ready * - modernizr custom build/CDN * - do I need to include normalize, h5bp, foundation & compass resets? * - separate print styles and add media element for IE8- * - print.scss, ie.scss (if supported) * - support IE desktops https://github.com/jtangelder/grunt-stripmq, http://robin.medvedi.eu/mobile-first-and-ie8-solution-introducing-grunt-legacssy/ * - uncss, class names minification * - README - grunt commands, file system * - humans.txt - rel attr, humans.txt, button possibility, http://humanstxt.org/Im-human.html * - https://github.com/gruntjs/grunt-contrib-bump * - rev * - GA * - git initialization * - Gruntfile.js - open * - use https://github.com/buildingblocks/grunt-combine-media-queries to minify media queries to one * */ 'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var WebProjectGenerator = module.exports = function WebProjectGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(WebProjectGenerator, yeoman.generators.Base); WebProjectGenerator.prototype.askFor = function askFor() { var cb = this.async(); // welcome message console.log(this.yeoman); console.log('Foundation5 with Compass and HTML5 Boilerplate are prepared!'); var prompts = [{ type: 'confirm', name: 'localizeCZ', message: 'Would you like to use Czech?', default: false }, { type: 'confirm', name: 'createSublimeTextProjectFile', message: 'Create Sublime Text project file?', default: true }, { name: 'htmlTitle', message: 'Your HTML <title>?', default: this.appname }]; this.prompt(prompts, function (answers) { // // manually deal with the response, get back and store the results. // // we change a bit this way of doing to automatically do this in the self.prompt() method. this.language = answers.localizeCZ ? 'cs' : 'en'; this.createSublimeTextProjectFile = answers.createSublimeTextProjectFile; this.htmlTitle = answers.htmlTitle; cb(); }.bind(this)); }; WebProjectGenerator.prototype.gruntfile = function gruntfile() { this.template('Gruntfile.js'); }; WebProjectGenerator.prototype.packageJSON = function packageJSON() { this.template('_package.json', 'package.json'); }; WebProjectGenerator.prototype.SassConfig = function SassConfig() { this.copy('config.rb', 'config.rb'); }; WebProjectGenerator.prototype.git = function git() { this.copy('gitignore', '.gitignore'); this.copy('gitattributes', '.gitattributes'); }; WebProjectGenerator.prototype.bower = function bower() { this.copy('bowerrc', '.bowerrc'); this.template('_bower.json', 'bower.json'); }; WebProjectGenerator.prototype.editor = function editor() { this.copy('editorconfig', '.editorconfig'); if (this.createSublimeTextProjectFile) this.template('project.sublime-project', this._.slugify(this.appname) + '.sublime-project'); }; WebProjectGenerator.prototype.assets = function assets() { this.mkdir('assets'); this.mkdir('assets/font'); this.mkdir('assets/img'); this.mkdir('assets/js'); this.mkdir('assets/scss'); this.mkdir('assets/scss/settings'); this.mkdir('assets/scss/vendor'); }; WebProjectGenerator.prototype.files = function files() { this.copy('404_' + this.language + '.html', '404.html'); this.copy('favicon.ico', 'favicon.ico'); this.copy('apple-touch-icon-precomposed.png', 'apple-touch-icon-precomposed.png'); this.copy('htaccess', '.htaccess'); this.copy('robots.txt', 'robots.txt'); this.copy('crossdomain.xml', 'crossdomain.xml'); this.template('settings.scss', 'assets/scss/settings/_foundation.scss'); this.copy('h5bp.scss', 'assets/scss/vendor/_h5bp.scss'); this.copy('foundation.scss', 'assets/scss/vendor/_foundation.scss'); this.copy('main.scss', 'assets/scss/main.scss'); this.copy('ie8.scss', 'assets/scss/ie8.scss'); this.copy('main.js', 'assets/js/main.js'); this.copy('plugins.js', 'assets/js/plugins.js'); this.copy('jquery-2.1.0.js', 'assets/js/jquery.js'); // for dev CDN fallback, for production compiled by grunt from bower_components this.copy('jquery-1.8.0.js', 'assets/js/jquery-1.8.0.js'); this.copy('selectivizr-1.0.3b.js', 'assets/js/selectivizr-1.0.3b.js'); }; WebProjectGenerator.prototype.index = function index() { this.copy('index.html', 'index.html'); }; WebProjectGenerator.prototype.install = function () { var done = this.async(); this.installDependencies({ callback: done }); };
JavaScript
0
@@ -53,16 +53,270 @@ ettings%0A + * - GA (https://github.com/dciccale/grunt-processhtml, https://github.com/changer/grunt-targethtml) + ask for key%0A * - new task (%22dploy%22/%22production%22), because of build is sometimes being used for testing final product (don't wanna analyze this :))%0A * - mi @@ -952,17 +952,8 @@ rev%0A - * - GA%0A *
5b5f3fe2e54db752c74ea2d2d7edcd7d64ec3c51
Use consistent selection argument style
js/id/renderer/background.js
js/id/renderer/background.js
iD.Background = function() { var tileSize = [256, 256]; var tile = d3.geo.tile(), projection, cache = {}, offset = [0, 0], transformProp = iD.util.prefixCSSProperty('Transform'), source = d3.functor(''); function tileSizeAtZoom(d, z) { return Math.ceil(tileSize[0] * Math.pow(2, z - d[2])) / tileSize[0]; } function atZoom(t, distance) { var power = Math.pow(2, distance); var az = [ Math.floor(t[0] * power), Math.floor(t[1] * power), t[2] + distance]; return az; } function lookUp(d) { for (var up = -1; up > -d[2]; up--) { if (cache[atZoom(d, up)] !== false) return atZoom(d, up); } } function uniqueBy(a, n) { var o = [], seen = {}; for (var i = 0; i < a.length; i++) { if (seen[a[i][n]] === undefined) { o.push(a[i]); seen[a[i][n]] = true; } } return o; } function addSource(d) { d.push(source(d)); return d; } // derive the tiles onscreen, remove those offscreen and position tiles // correctly for the currentstate of `projection` function background() { var sel = this, tiles = tile .scale(projection.scale()) .scaleExtent((source.data && source.data.scaleExtent) || [1, 17]) .translate(projection.translate())(), requests = [], scaleExtent = tile.scaleExtent(), z = Math.max(Math.log(projection.scale()) / Math.log(2) - 8, 0), rz = Math.max(scaleExtent[0], Math.min(scaleExtent[1], Math.floor(z))), ts = tileSize[0] * Math.pow(2, z - rz), tile_origin = [ projection.scale() / 2 - projection.translate()[0], projection.scale() / 2 - projection.translate()[1]]; tiles.forEach(function(d) { addSource(d); requests.push(d); if (!cache[d[3]] && lookUp(d)) { requests.push(addSource(lookUp(d))); } }); requests = uniqueBy(requests, 3).filter(function(r) { // don't re-request tiles which have failed in the past return cache[r[3]] !== false; }); var pixeloffset = [ Math.round(offset[0] * Math.pow(2, z)), Math.round(offset[1] * Math.pow(2, z)) ]; function load(d) { cache[d[3]] = true; d3.select(this) .on('load', null) .classed('tile-loaded', true); background.apply(sel); } function error(d) { cache[d[3]] = false; d3.select(this).on('load', null); d3.select(this).remove(); background.apply(sel); } function imageTransform(d) { var _ts = tileSize[0] * Math.pow(2, z - d[2]); var scale = tileSizeAtZoom(d, z); return 'translate(' + (Math.round((d[0] * _ts) - tile_origin[0]) + pixeloffset[0]) + 'px,' + (Math.round((d[1] * _ts) - tile_origin[1]) + pixeloffset[1]) + 'px)' + 'scale(' + scale + ',' + scale + ')'; } var image = this .selectAll('img') .data(requests, function(d) { return d[3]; }); image.exit() .style(transformProp, imageTransform) .classed('tile-loaded', false) .each(function() { var tile = this; window.setTimeout(function() { // this tile may already be removed if (tile.parentNode) { tile.parentNode.removeChild(tile); } }, 300); }); image.enter().append('img') .attr('class', 'tile') .attr('src', function(d) { return d[3]; }) .on('error', error) .on('load', load); image.style(transformProp, imageTransform); } background.offset = function(_) { if (!arguments.length) return offset; offset = _; return background; }; background.nudge = function(_, zoomlevel) { offset[0] += _[0] / Math.pow(2, zoomlevel); offset[1] += _[1] / Math.pow(2, zoomlevel); return background; }; background.projection = function(_) { if (!arguments.length) return projection; projection = _; return background; }; background.size = function(_) { if (!arguments.length) return tile.size(); tile.size(_); return background; }; function setPermalink(source) { var tag = source.data.sourcetag; var q = iD.util.stringQs(location.hash.substring(1)); if (tag) { location.replace('#' + iD.util.qsString(_.assign(q, { layer: tag }), true)); } else { location.replace('#' + iD.util.qsString(_.omit(q, 'layer'), true)); } } background.source = function(_) { if (!arguments.length) return source; source = _; setPermalink(source); return background; }; return background; };
JavaScript
0.000001
@@ -1259,16 +1259,25 @@ kground( +selection ) %7B%0A @@ -1288,32 +1288,8 @@ var -sel = this,%0A tile @@ -2663,34 +2663,34 @@ background -.apply(sel +(selection );%0A %7D @@ -2779,16 +2779,33 @@ ct(this) +%0A .on('loa @@ -2813,17 +2813,16 @@ ', null) -; %0A @@ -2826,31 +2826,20 @@ -d3.select(this) + .remove( @@ -2867,18 +2867,18 @@ ound -.apply(sel +(selection );%0A @@ -3322,20 +3322,25 @@ image = -this +selection %0A
0208d952c1d2f657aec88bb246f6e38cd5c48857
Simplify and generalise component inference logic
src/exitable.es3.js
src/exitable.es3.js
window.m = ( function( mithril ){ // Registry of controllers and corresponding root nodes var roots = new Map() // A record of recent view outputs for every root-level component var history = new WeakMap() // Whether the current draw is being used to revert to its previous state var reverting = false // Register views to bind their roots to the above // so we can provide exit animations with the right DOM reference function register( view ){ return function registeredView( ctrl ){ var output = view.apply( this, arguments ) // In case of a registered exit animation... if( ctrl.exit ){ var node = output // If the view output is an array, deal with the first element while( node.length ) node = node[ 0 ] var config = node.attrs.config // Map the root / first child element to the component instance node.attrs.config = function superConfig( el ){ roots.set( ctrl, el ) if( config ) return config.apply( this, arguments ) } } return output } } // Root components (those mounted or routed) are the source of redraws. // Before they draw, there is no stateful virtual DOM. // Therefore their view execution is the source of all truth in what is currently rendered. function root( component ){ var view = component.view component.view = rootView return component function rootView( ctrl ){ // If we are in the middle of a reversion, we just want to patch // Mithril's internal virtual DOM HEAD to what it was before the // last output if( reverting ) return history.get( ctrl ) // All previously registered exitable components are saved here var previous = array( roots ) // Then we reset roots.clear() // Execute the view, registering all exitables var output = register( view ).apply( this, arguments ) // Record the output, we will need to return to this state if the next draw has exits history.set( ctrl, output ) // Now, set up a list of confirmed exits var exits = [] // For every previous exitable instance... for( var i = 0; i < previous.length; i++ ) // ...if it hasn't re-registered... if( !roots.has( previous[ i ][ 0 ] ) ) // It's gone! Call the exit method and keep its output. exits.push( previous[ i ][ 0 ].exit( previous[ i ][ 1 ] ) ) // If we have exits... if( exits.length ){ // Noop this draw output = { subtree : 'retain' } // ...and all subsequent ones... mithril.startComputation() // ...until all exits have resolved mithril.sync( exits ).then( function(){ // We now need to revert Mithril's internal virtual DOM head so that // it will correctly patch the live DOM to match the state in which // components are removed: it currently believes that already happend // Because it ran the diff before we told it to retain the subtree at // the last minute reverting = true // Next draw should not patch, only diff mithril.redraw.strategy( 'none' ) // Force a synchronous draw despite being frozen mithril.redraw( true ) // Now it's as if we were never here to begin with reverting = false // Resume business as usual mithril.endComputation() } ) } return output } } // Helper: transform each value in an object. Even in ES7, this is painfully contrived. function reduce( object, transformer ){ var output = {} for( var key in object ) if( Object.prototype.hasOwnProperty.call( object, key ) ) output[ key ] = transformer( object[ key ] ) return output } // Helper: array from map function array( map ){ var array = [] var entries = map.entries() while( true ){ var entry = entries.next() if( entry.done ) break array.push( entry.value ) } return array } // Core m function needs to sniff out components... function m( first ){ if( Object.prototype.hasOwnProperty.call( first, 'view' ) ) return m.component.apply( this, arguments ) var output = mithril.apply( this, arguments ) for( var i = 0; i < output.children.length; i++ ) if( output.children[ i ].view ) // ...and get their views to register controllers and root nodes output.children[ i ].view = register( output.children[ i ].view ) return output } // Then we have all the m methods for( var key in mithril ) if( Object.prototype.hasOwnProperty.call( mithril, key ) ) m[ key ] = mithril[ key ] // m.component invocations produce virtual DOM. // We need to intercede to get at the view. m.component = function( component ){ component.view = register( component.view ) // I don't know how I coped without ES6 spread operator.... return mithril.component.apply( mithril, [ component ].concat( [].slice.call( arguments, 1 ) ) ) } // Mount and Route need to register root components for snapshot logic m.mount = function( el, component ){ return mithril.mount( el, root( component ) ) } m.route = function( el, path, map ){ if( map ){ return mithril.route( el, path, reduce( map, root ) ) } else { return mithril.route.apply( this, arguments ) } } // Export a patched Mithril API return m }( m ) );
JavaScript
0.000005
@@ -4238,62 +4238,19 @@ if( - Object.prototype.hasOwnProperty.call( first -, ' +. view -' ) )%0A
fe09495399896d9a1aaaf43bce156acf60d79bde
Stringify all msg and parse them without checking msg type
lib/helpers/message-parsers.js
lib/helpers/message-parsers.js
module.exports.in = function(_msg) { if (_msg.properties.contentType === 'application/json') { return JSON.parse(_msg.content.toString()); } return _msg.content.toString(); }; module.exports.out = function(content, options) { if (typeof content === 'object') { content = JSON.stringify(content); options.contentType = 'application/json'; } return new Buffer(content); };
JavaScript
0.999469
@@ -87,24 +87,36 @@ on/json') %7B%0A + try %7B%0A return J @@ -151,16 +151,34 @@ ing());%0A + %7D catch(e) %7B%7D%0A %7D%0A%0A r @@ -272,35 +272,15 @@ if ( -typeof content === 'object' +content ) %7B%0A
d4ba538d15b4eedd28be6cecabcef8509118f6ca
Add method to get all members of the circuit-element
js/models/circuit-element.js
js/models/circuit-element.js
(function(app) { 'use strict'; var circuit = require('circuit'); var Wrapper = function(obj, self) { obj.unwrap = Wrapper.unwrap.bind(self); return obj; }; Wrapper.unwrap = function(key) { if (key === Wrapper.KEY) return this; }; Wrapper.KEY = {}; var CircuitElementMember = function(props) { this.label = props.label; this.name = props.name; this.type = props.type; this.callee = circuit[props.type](props.arg); this.sources = []; this.targets = []; this.wrapper = new Wrapper(CircuitElementMember.prototype.call.bind(this), this); }; CircuitElementMember.prototype.call = function() { return this.callee.apply(null, arguments); }; var CircuitElement = function(members) { var memberTable = {}; var names = []; members.slice().reverse().forEach(function(props) { var name = props.name; if (name in memberTable) return; memberTable[name] = new CircuitElementMember(props); names.unshift(name); }); this.memberTable = memberTable; this.names = names; }; CircuitElement.prototype.get = function(name) { var member = this.memberTable[name]; if (!member) return null; return member.wrapper; }; CircuitElement.empty = function() { return new CircuitElement([]); }; if (typeof module !== 'undefined' && module.exports) module.exports = CircuitElement; else app.CircuitElement = CircuitElement; })(this.app || (this.app = {}));
JavaScript
0
@@ -1244,32 +1244,194 @@ .wrapper;%0A %7D;%0A%0A + CircuitElement.prototype.getAll = function() %7B%0A return this.names.map(function(name) %7B%0A return this.memberTable%5Bname%5D.wrapper;%0A %7D.bind(this));%0A %7D;%0A%0A CircuitElement
c596901ffce073b75635fe86000b5911e2d98cf7
Refactor layout controllers layout attributes to static members
packages/app/source/client/controllers/layout-controller.js
packages/app/source/client/controllers/layout-controller.js
Space.Object.extend('Todos.LayoutController', { mixin: [ Space.messaging.EventSubscribing ], dependencies: { layout: 'Layout', _: 'underscore' }, Constructor() { this._currentLayout = null; this._currentSections = {}; }, eventSubscriptions() { return [{ 'Todos.RouteTriggered': function(event) { switch (event.routeName) { //case 'routeName': this._routeHanlder(); break; default: this._renderIndexPage(); } } }]; }, _renderIndexPage() { this._render('index', { input: 'input', todo_list: 'todo_list', footer: 'footer' }); }, _render(layout, sections) { this._currentLayout = layout; this._.extend(this._currentSections, sections); this.layout.render(this._currentLayout, this._currentSections); }, _updateSections(sections) { this._render(this._currentLayout, sections); } });
JavaScript
0
@@ -168,33 +168,8 @@ %0A%0A -Constructor() %7B%0A this. _cur @@ -182,26 +182,19 @@ yout - = +: null -;%0A this. +,%0A%0A _cur @@ -209,17 +209,11 @@ ions - = %7B%7D;%0A +: %7B %7D,%0A%0A
6fab2088cd670b8d74919fb0c17212c64baa9cc0
Fix source map
starter-kit/hmr/webpack.config.js
starter-kit/hmr/webpack.config.js
var path = require('path'); var webpack = require('webpack'); var merge = require('webpack-merge'); var HtmlWebpackPlugin = require('html-webpack-plugin'); var CopyWebpackPlugin = require('copy-webpack-plugin'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var poststylus = require('poststylus'); var TARGET_ENV = process.env.npm_lifecycle_event === 'build' ? 'production' : 'development'; var commonConfig = { devtool: 'source-map', output: { path: path.join(__dirname, "public"), publicPath: "", filename: "[hash].js" }, module: { preLoaders: [ { test: /\.js$/, exclude: /node_modules/, loader: "source-map-loader", include: "path.join(__dirname, 'public')" } ], loaders: [ { test: /\.(eot|ttf|woff|woff2|svg|png)$/, exclude: /node_modules/, loader: 'file-loader' } ] }, plugins: [ new HtmlWebpackPlugin({ template: 'Source/static/index.html', inject: 'body', filename: 'index.html' }), new CopyWebpackPlugin([ { from: 'Source/static/img/', to: 'img/' } ]) ], stylus: { use: [poststylus(['autoprefixer'])] } }; if ( TARGET_ENV === 'development' ) { console.log( 'Serving locally...'); module.exports = merge(commonConfig, { entry: [ './Source/static/index.js', 'webpack/hot/dev-server', 'webpack-dev-server/client?http://localhost:8080/', ], module: { loaders: [ { test: /\.styl$/, exclude: /node_modules/, loaders: [ 'style-loader', 'css-loader', 'stylus-loader' ] } ] }, plugins: [ new webpack.HotModuleReplacementPlugin(), ] }); } if ( TARGET_ENV === 'production' ) { console.log( 'Building for prod...'); module.exports = merge( commonConfig, { entry: path.join( __dirname, 'Source/static/index.js' ), module: { loaders: [ { test: /\.styl$/, loader: ExtractTextPlugin.extract( 'style-loader', [ 'css-loader', 'stylus-loader' ]) } ] }, plugins: [ new CopyWebpackPlugin([ { from: 'src/static/img/', to: 'static/img/' } ]), new webpack.optimize.OccurenceOrderPlugin(), // extract CSS into a separate file new ExtractTextPlugin( './[hash].css', { allChunks: true } ), // minify & mangle JS/CSS new webpack.optimize.UglifyJsPlugin({ minimize: true, compressor: { warnings: false } // mangle: true }) ] }); }
JavaScript
0.000001
@@ -688,59 +688,8 @@ der%22 -,%0A include: %22path.join(__dirname, 'public')%22 %0A
a63df61988e7e4120d2ac2491e5de94bac439039
move partials to be first in parse chain
lib/end-dash.js
lib/end-dash.js
var Parser = require("./parser") , AttributeReaction = require("./reactions/attribute") , CollectionReaction = require("./reactions/collection") , ModelReaction = require("./reactions/model") , VariableReaction = require("./reactions/variable") , ConditionalReaction = require("./reactions/conditional") , ContentPartialReaction = require("./reactions/content_partials") , ViewReaction = require("./reactions/views") , ScopeReaction = require("./reactions/scope") Parser.registerReaction(ScopeReaction) Parser.registerReaction(AttributeReaction) Parser.registerReaction(CollectionReaction) Parser.registerReaction(ModelReaction) Parser.registerReaction(VariableReaction) Parser.registerReaction(ConditionalReaction) Parser.registerReaction(ContentPartialReaction) Parser.registerReaction(ViewReaction) module.exports = Parser
JavaScript
0
@@ -474,16 +474,64 @@ cope%22)%0A%0A +Parser.registerReaction(ContentPartialReaction)%0A Parser.r @@ -778,56 +778,8 @@ on)%0A -Parser.registerReaction(ContentPartialReaction)%0A Pars
f5c5ac3bef466dcdc83145b90b0b91cbdab4d18f
Fix migrate warning on non-html arg to $()
static/js/impala/addon_details.js
static/js/impala/addon_details.js
$(function () { if (!$("body").hasClass('addon-details')) return; $('#background-wrapper').css('height', $('.amo-header').height() + $('#addon-description-header').height() + 20 + 'px'); $(".previews").zCarousel({ btnNext: ".previews .next", btnPrev: ".previews .prev", itemsPerPage: 3 }); (function() { var $document = $(document), $lightbox = $("#lightbox"), $content = $("#lightbox .content"), $caption = $("#lightbox .caption span"), $previews = $('.previews'), current, $strip, lbImage = template('<img id="preview{0}" src="{1}" alt="">'); if (!$lightbox.length) return; function showLightbox() { $lightbox.show(); showImage(this); $(window).bind('keydown.lightboxDismiss', function(e) { switch(e.which) { case z.keys.ESCAPE: e.preventDefault(); hideLightbox(); break; case z.keys.LEFT: e.preventDefault(); showPrev(); break; case z.keys.RIGHT: e.preventDefault(); showNext(); break; } }); //I want to ensure the lightbox is painted before fading it in. setTimeout(function () { $lightbox.addClass("show"); },0); } function hideLightbox() { $lightbox.removeClass("show"); // We can't trust transitionend to fire in all cases. setTimeout(function() { $lightbox.hide(); }, 500); $(window).unbind('keydown.lightboxDismiss'); } function showImage(a) { var $a = $(a), $oldimg = $lightbox.find("img"); current = $a.parent().index(); $strip = $a.closest("ul").find("li"); $previews.find('.panel').removeClass('active') .eq(current).addClass('active'); var $img = $("#preview"+current); if ($img.length) { $oldimg.css({"opacity": "0", "z-index": "0"}); $img.css({ "opacity": "1", "z-index": "1" }); } else { $img = $(lbImage([current, $a.attr("href")])); $content.append($img); $img.load(function(e) { $oldimg.css({"opacity": "0", "z-index": "0"}); $img.css({ "opacity": "1", "z-index": "1" }); for (var i=0; i<$strip.length; i++) { if (i != current) { var $p = $strip.eq(i).find("a"); $content.append(lbImage([i, $p.attr("href")])); } } }); } $caption.text($a.attr("title")); $lightbox.find(".control").removeClass("disabled"); if (current < 1) { $lightbox.find(".control.prev").addClass("disabled"); } if (current == $strip.length-1){ $lightbox.find(".control.next").addClass("disabled"); } } function showNext() { if (current < $strip.length-1) { showImage($strip.eq(current+1).find("a")); if (!this.window) { $(this).blur(); } } } function showPrev() { if (current > 0) { showImage($strip.eq(current-1).find("a")); if (!this.window) { $(this).blur(); } } } $("#lightbox .next").click(_pd(showNext)); $("#lightbox .prev").click(_pd(showPrev)); $(".previews ul a").click(_pd(showLightbox)); $('#lightbox').click(_pd(function(e) { if ($(e.target).is('.close, #lightbox')) { hideLightbox(); } })); })(); if ($('#more-webpage').exists()) { var $moreEl = $('#more-webpage'); url = $moreEl.attr('data-more-url'); $.get(url, function(resp) { var $document = $(document); var scrollTop = $document.scrollTop(); var origHeight = $document.height(); // We need to correct scrolling position if the user scrolled down // already (e.g. by using a link with anchor). This correction is // only necessary if the scrolling position is below the element we // replace or the user scrolled down to the bottom of the document. var shouldCorrectScrolling = scrollTop > $moreEl.offset().top; if (scrollTop && scrollTop >= origHeight - $(window).height()) { shouldCorrectScrolling = true; } var $newContent = $(resp); $moreEl.replaceWith($newContent); $newContent.find('.listing-grid h3').truncate( {dir: 'h'} ); $newContent.find('.install').installButton(); $newContent.find('.listing-grid').each(listing_grid); $('#reviews-link').addClass('scrollto').attr('href', '#reviews'); if (shouldCorrectScrolling) { // User scrolled down already, adjust scrolling position so // that the same content stays visible. var heightDifference = $document.height() - origHeight; $document.scrollTop(scrollTop + heightDifference); } }); } if ($('#review-add-box').exists()) $('#review-add-box').modal('#add-review', { delegate: '#page', width: '650px' }); if ($('#privacy-policy').exists()) $('#privacy-policy').modal('.privacy-policy', { width: '500px' }); // Show add-on ID when icon is clicked if ($("#addon[data-id], #persona[data-id]").exists()) { $("#addon .icon").click(function() { window.location.hash = "id=" + $("#addon, #persona").attr("data-id"); }); } $('#abuse-modal').modal('#report-abuse', {delegate: '#page'}); });
JavaScript
0
@@ -5108,24 +5108,135 @@ %7D%0A%0A + // Strip the leading whitespace so that $() treats this as html and%0A // not a selector.%0A @@ -5259,16 +5259,23 @@ = $(resp +.trim() );%0A
2d307501d2fc1f6e2caf5a139cc12f160d3633df
copy Socket files and templates to project, and modify prompt messages a bit
app/index.js
app/index.js
'use strict'; var util = require('util'); var path = require('path'); var yeoman = require('yeoman-generator'); var VinelabGenerator = module.exports = function VinelabGenerator(args, options, config) { yeoman.generators.Base.apply(this, arguments); this.on('end', function () { this.installDependencies({ skipInstall: options['skip-install'], callback: function () { this.spawnCommand('./node_modules/.bin/webdriver-manager', ['update']); }.bind(this) }); }); this.pkg = JSON.parse(this.readFileAsString(path.join(__dirname, '../package.json'))); }; util.inherits(VinelabGenerator, yeoman.generators.Base); VinelabGenerator.prototype.askFor = function askFor() { var cb = this.async(); // have Yeoman greet the user. console.log(this.yeoman); var prompts = [ { name: 'name', message: 'Name your app', }, { name: 'description', message: 'Describe it with a small description', } ]; this.prompt(prompts, function (props) { this.customize = props.customize; this.name = props.name; this.description = props.description; cb(); }.bind(this)); }; VinelabGenerator.prototype.app = function app() { this.mkdir('app'); this.copy('app/bootstrap.coffee', 'app/bootstrap.coffee'); }; VinelabGenerator.prototype.views = function views() { this.mkdir('app/views'); this.copy('app/views/_main.html', 'app/views/main.html'); }; VinelabGenerator.prototype.config = function config() { this.mkdir('app/config'); this.copy('app/config/default.yml', 'app/config/default.yml'); this.copy('app/config/development.yml', 'app/config/development.yml'); this.copy('app/config/production.yml', 'app/config/production.yml'); }; VinelabGenerator.prototype.assets = function assets() { this.mkdir('app/assets'); this.mkdir('app/assets/styles'); this.copy('app/assets/styles/base.less', 'app/assets/styles/base.less'); }; VinelabGenerator.prototype.sourcefiles = function sourcefiles() { this.mkdir('app/src'); this.mkdir('app/src/Main'); this.mkdir('app/src/Config'); this.mkdir('app/src/Storage'); this.copy('app/src/App.coffee', 'app/src/App.coffee'); this.copy('app/src/Config/Config.coffee', 'app/src/Config/Config.coffee'); this.copy('app/src/Main/controllers/MainController.coffee', 'app/src/Main/controllers/MainController.coffee'); this.copy('app/src/Storage/StorageService.coffee', 'app/src/Storage/StorageService.coffee'); }; VinelabGenerator.prototype.deps = function deps() { this.template('_bower.json', 'bower.json'); this.template('_package.json', 'package.json'); this.copy('bowerrc', '.bowerrc'); this.copy('Gruntfile.coffee', 'Gruntfile.coffee'); }; VinelabGenerator.prototype.projectfiles = function projectfiles() { this.copy('gitignore', '.gitignore'); this.template('_index.html', 'index.html'); }; VinelabGenerator.prototype.tests = function tests() { this.mkdir('tests'); // unit tests this.mkdir('tests/unit'); this.mkdir('tests/unit/config'); this.mkdir('tests/unit/Main/controllers'); this.copy('tests/unit/config/karma.conf.coffee', 'tests/unit/config/karma.conf.coffee'); this.copy('tests/unit/Main/controllers/MainControllerTest.coffee', 'tests/unit/Main/controllers/MainControllerTest.coffee'); // e2e tests this.mkdir('tests/e2e'); this.mkdir('tests/e2e/config'); // browsers configs this.copy('tests/e2e/config/e2e.chrome.js', 'tests/e2e/config/e2e.chrome.js'); this.copy('tests/e2e/config/e2e.firefox.js', 'tests/e2e/config/e2e.firefox.js'); this.copy('tests/e2e/config/e2e.phantom.js', 'tests/e2e/config/e2e.phantom.js'); this.copy('tests/e2e/config/e2e.safari.js', 'tests/e2e/config/e2e.safari.js'); this.copy('tests/e2e/mainTest.coffee', 'tests/e2e/mainTest.coffee'); };
JavaScript
0
@@ -932,19 +932,46 @@ your app + (CamelCase with no spaces) ',%0A - @@ -1054,32 +1054,14 @@ it -with a small description +for us ',%0A @@ -1358,28 +1358,32 @@ );%0A this. -copy +template ('app/bootst @@ -1532,17 +1532,16 @@ p/views/ -_ main.htm @@ -2234,32 +2234,66 @@ p/src/Config');%0A + this.mkdir('app/src/Socket');%0A this.mkdir(' @@ -2566,36 +2566,40 @@ fee');%0A this. -copy +template ('app/src/Storag @@ -2658,32 +2658,182 @@ rvice.coffee');%0A + this.copy('app/src/Socket/io.coffee', 'app/src/Socket/io.coffee');%0A this.copy('app/src/Socket/Socket.coffee', 'app/src/Socket/Socket.coffee');%0A %7D;%0A%0AVinelabGener @@ -3199,17 +3199,16 @@ mplate(' -_ index.ht @@ -3437,24 +3437,61 @@ ntrollers'); +%0A this.mkdir('tests/unit/Socket'); %0A%0A this.c @@ -3574,36 +3574,137 @@ fee');%0A this. -copy +template('tests/unit/Socket/SocketTest.coffee', 'tests/unit/Socket/SocketTest.coffee');%0A this.template ('tests/unit/Mai
f2a99f578ea06415978eec1c3bac3226bdb2e29f
Revert "updated one last place where backend host was defined."
client/src/js/states/preloader.js
client/src/js/states/preloader.js
/** * Created by petermares on 20/02/2016. */ module.exports = (function() { var settings = require('../../settings'); var o = {}; var _images = { logo: 'assets/logo.png', sky: 'assets/sky.png', diamond: 'assets/diamond.png', heart: 'assets/heart.png', star: 'assets/star.png', signpost: 'assets/avatar.png', mainmenu_bkg: 'assets/mm_bg.png' //btn_crissy_normal: 'assets/mm_c3_off.png', //btn_peter_normal: 'assets/mm_c2_off.png', //btn_ricardo_normal: 'assets/mm_c1_off.png', //btn_crissy_hover: 'assets/mm_c3_on.png', //btn_peter_hover: 'assets/mm_c2_on.png', //btn_ricardo_hover: 'assets/mm_c1_on.png' }; var _spritesheets = { baddie: { file: 'assets/baddie.png', width: 32, height: 32 }, dude: { file: 'assets/peter.png', width: 48, height: 64 }, btn_peter: { file: 'assets/mm_c2.png', width: 230, height: 230 }, btn_crissy: { file: 'assets/mm_c3.png', width: 230, height: 230 }, btn_ricardo: { file: 'assets/mm_c1.png', width: 230, height: 230 } }; var element; o.preload = function() { console.log('Preloader.preload'); // load images var k; for ( k in _images ) { this.load.image(k, _images[k]); } // load the sprite sheets for ( k in _spritesheets ) { this.load.spritesheet(k, _spritesheets[k].file, _spritesheets[k].width, _spritesheets[k].height); } this.game.load.json('server_version', 'http://' + process.env.GITRUNNER_BACKEND_HOST + '/version'); }; o.create = function() { console.log('Preloader.create'); element = this.game.add.sprite(this.scale.width/2, this.scale.height/2, 'logo'); element.anchor.set(0.5); this.state.start('mainmenu'); }; return o; })();
JavaScript
0
@@ -1806,42 +1806,57 @@ ' + -process.env.GITRUNNER_BACKEND_HOST +settings.server.host + ':' + settings.server.port + '
8502d941df7f18db9c644f409c5cd4856499807c
add object detection to remove error
client/views/public/field/list.js
client/views/public/field/list.js
Template.FieldList.rendered = function() { $('.draggable').draggable(); $('.droppable').droppable({ drop: function(event, ui) { $(this) .addClass('ui-state-highlight') .find('div') .html('dropped'); } }); }; Template.FieldList.helpers({ // if there is a team return false // so we can hide the add team form cGame: function() { if (Meteor.user()) { return Games.findOne({ _id: Session.get('sGameId') }); } } }); Template.StartingFieldList.rendered = function(evt, template) { // what items we want droppable on the field $(".starting-lineup div").droppable({ activeClass: "active", hoverClass: "hover", drop: function(event, ui) { // grab the current game id var currentGameId = Session.get('sGameId'); // which player are we about to drop (their id) var starterId = Session.get('sPlayerId'); var playerDoc = Players.findOne({ _id: starterId }); var playerName = playerDoc.fullName; // we need the current position in the div // we are about to drop because on the server // we need to update this div and the way we do that // is we query by the value currently in this position // (this is how you only show documents with specific properties) var currPos = Games.findOne({ _id: Session.get('sGameId') }, { playerGameInfo: 1 }); // which div id are we dropping on? // with this info we can dynamically create our server // update of this div var playerContainer = this.id; // we need 1) that number of the player div we are altering // by dropping on this div // we need 2) the playerId we are dropping // we grab from our collection cursor the current position name // that we plan on overwriting var playerInfo = { playerDivNum: playerContainer, playerId: starterId, playerFullName: playerName, oldPlayerId: currPos.playerGameInfo[0][this.id].playerId, oldPlayerFullName: currPos.playerGameInfo[0][this.id].playerFullName } // because we are using the mongo $ (position query) // and had security problems doing this on the client // we create a server method call and call the method // pass our game id and the 3 properties we gathered in our // playerInfo object Meteor.call('updateStarter', currentGameId, playerInfo, function(error, id) { if (error) { return alert(error.reason); } // if the div has children don't append anything to DOM if ($('#' + playerContainer).children().length > 0) { return false; } else { $('#' + playerContainer).append("<span class='starter'>" + playerName + "</span>"); } }); } }); } // needed to make sure data is loaded (also has if subready in template) Template.StartingFieldList.onCreated(function() { this.subscribe('current-game'); }); // Template.StartingFieldList.rendered = function() { // // var currGame = Games.findOne({ // // _id: Session.get('sGameId') // // }, { // // playerGameInfo: 1 // // }); // var currentGame = Games.findOne({ // _id: Session.get('sGameId') // }); // // var myTest = currGame.playerGameInfo[0]["player02"].playerFullName; // }; Template.StartingFieldList.helpers({ // if there is a team return false // so we can hide the add team form cGame: function() { return Games.findOne({ _id: Session.get('sGameId') }); }, sGameId: function() { return Session.get('sGameId'); }, cPlayerGameInfo: function() { var currentGame = Games.findOne({ _id: Session.get('sGameId') }); if (currentGame.playerGameInfo[0]) { var allPlayerGameInfo = currentGame.playerGameInfo[0]; return allPlayerGameInfo; } } });
JavaScript
0.000001
@@ -236,18 +236,16 @@ ;%0A %7D%0A -%0A%0A %7D);%0A%0A%7D @@ -3163,405 +3163,8 @@ );%0A%0A -// Template.StartingFieldList.rendered = function() %7B%0A%0A // // var currGame = Games.findOne(%7B%0A // // _id: Session.get('sGameId')%0A // // %7D, %7B%0A // // playerGameInfo: 1%0A // // %7D);%0A // var currentGame = Games.findOne(%7B%0A // _id: Session.get('sGameId')%0A // %7D);%0A%0A%0A%0A%0A // // var myTest = currGame.playerGameInfo%5B0%5D%5B%22player02%22%5D.playerFullName;%0A%0A // %7D;%0A%0A%0A Temp @@ -3540,25 +3540,69 @@ d')%0A %7D);%0A -%0A + if (currentGame.playerGameInfo%5B0%5D) %7B %0A if (curr @@ -3632,24 +3632,26 @@ 0%5D) %7B%0A + + var allPlaye @@ -3695,24 +3695,26 @@ o%5B0%5D;%0A + return allPl @@ -3727,16 +3727,57 @@ meInfo;%0A + %7D%0A %7D else %7B%0A return false;%0A %7D%0A%0A
da4cc3b456f630b0b462c83ccd2854c76c1bd6c7
Remove broken memento property.
js/foam/ui/Window.js
js/foam/ui/Window.js
/** * @license * Copyright 2014 Google Inc. All Rights Reserved. * * 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. */ CLASS({ package: 'foam.ui', name: 'Window', exports: [ '$$', '$', 'addStyle', 'animate', 'cancelAnimationFrame', 'clearInterval', 'clearTimeout', 'console', 'document', 'dynamic', 'error', 'info', 'installedModels', 'log', 'lookup', 'memento', 'requestAnimationFrame', 'setInterval', 'setTimeout', 'warn', 'window', 'as FOAMWindow' ], properties: [ { name: 'registeredModels', factory: function() { return {}; } }, { model_: 'StringProperty', name: 'name', defaultValue: 'window' }, { name: 'window', postSet: function(_, w) { // TODO: This would be better if ChromeApp.js added this behaviour // in a SubModel of Window, ie. ChromeAppWindow if ( this.X.subDocument ) this.X.subDocument(w.document); w.X = this.Y; this.document = w.document; } }, { name: 'document' // postSet to reset installedModels? }, { name: 'installedModels', documentation: "Each new Window context introduces a new document and resets installedModels so models will install again in the new document.", factory: function() { return {}; } }, { model_: 'BooleanProperty', name: 'isBackground', defaultValue: false }, { name: 'console', lazyFactory: function() { return this.window.console; } }, { name: 'memento', lazyFactory: function() { this.window.WindowHashValue.create({window: this.window}); } } ], methods: { lookup: function(key) { var ret = GLOBAL.lookup.call(this.Y, key); // var ret = this.X.lookup(key); if ( ret && ! this.registeredModels[key] ) { // console.log('Registering Model: ', key); this.registeredModels[key] = true; } return ret; }, addStyle: function(css) { if ( ! this.document || ! this.document.createElement ) return; var s = this.document.createElement('style'); s.innerHTML = css; this.document.head.insertBefore( s, this.document.head.firstElementChild); }, log: function() { this.console.log.apply(this.console, arguments); }, warn: function() { this.console.warn.apply(this.console, arguments); }, info: function() { this.console.info.apply(this.console, arguments); }, error: function() { this.console.error.apply(this.console, arguments); }, $: function(id) { return ( this.document.FOAM_OBJECTS && this.document.FOAM_OBJECTS[id] ) ? this.document.FOAM_OBJECTS[id] : this.document.getElementById(id); }, $$: function(cls) { return this.document.getElementsByClassName(cls); }, dynamic: function(fn, opt_fn) { return Events.dynamic(fn, opt_fn, this.Y); }, animate: function(duration, fn, opt_interp, opt_onEnd) { return Movement.animate(duration, fn, opt_interp, opt_onEnd, this.Y); }, setTimeout: function(f, t) { return this.window.setTimeout.apply(this.window, arguments); }, clearTimeout: function(id) { this.window.clearTimeout(id); }, setInterval: function(f, t) { return this.window.setInterval.apply(this.window, arguments); }, clearInterval: function(id) { this.window.clearInterval(id); }, requestAnimationFrame: function(f) { if ( this.isBackground ) return this.setTimeout(f, 16); console.assert( this.window.requestAnimationFrame, 'requestAnimationFrame not defined'); return this.window.requestAnimationFrame(f); }, cancelAnimationFrame: function(id) { if ( this.isBackground ) { this.clearTimeout(id); return; } this.window.cancelAnimationFrame && this.window.cancelAnimationFrame(id); } } }); // Using the existence of 'process' to determine that we're running in Node. (function() { var w = foam.ui.Window.create( { window: window, name: 'DEFAULT WINDOW', isBackground: typeof process === 'object' }, X ); FObject.X = X = w.Y; })();
JavaScript
0
@@ -928,23 +928,8 @@ p',%0A - 'memento',%0A @@ -2086,136 +2086,8 @@ %7D,%0A - %7B%0A name: 'memento',%0A lazyFactory: function() %7B this.window.WindowHashValue.create(%7Bwindow: this.window%7D); %7D%0A %7D%0A %5D,
de3ddd3e8a30de9397aa32a0b1ff552c8cb04df0
Copy config to avoid mutating options
src/fetch-client.js
src/fetch-client.js
import 'isomorphic-fetch' import Url from 'url' import QS from 'qs' import { map } from 'lodash' import extendify from 'extendify' const merge = extendify({ inPlace: false, isDeep: true, arrays: 'concat' }) const methods = ['get', 'post', 'put', 'patch', 'delete', 'del'] export default class FetchClient { static defaults = { server: { protocol: 'http', host: 'localhost', pathname: '/', port: process.env.API_PORT || process.env.PORT || 5000 }, client: { pathname: '/' } }; static requestDefaults = { method : 'get', mode : 'same-origin', credentials : 'same-origin', redirect : 'follow', cache : 'default', as : 'json', type : 'json', headers : {} } constructor(options, store, http) { if (http) { this.setHttp(http) } this.store = store this.options = merge({}, FetchClient.defaults, options) methods.forEach(method => { this[method] = this.genericMethod.bind(this, method) }) } setHTTP(http) { delete this.req delete this.res this.req = http.req this.res = http.res } isExternal(path) { return /^https?:\/\//i.test(path) } buildOptions(method, path, opts) { let options = merge({}, FetchClient.requestDefaults, opts) let external = this.isExternal(path) options.url = this.formatUrl(path) options.method = method.toUpperCase() if (options.method === 'DEL') { options.method = 'DELETE' } if (options.query) { options.url += ('?' + QS.stringify(options.query)) delete options.query } if (options.headers) { if (__SERVER__ && this.req.get('cookie')) { options.headers.cookie = this.req.get('cookie') } if (this.options.auth && typeof this.options.auth.getBearer === 'function') { let token = this.options.auth.getBearer(this.store) if (token && token.length && !external) { options.headers['Authorization'] = `Bearer ${token}` } } options.headers = new Headers(options.headers) } if (options.data && !options.body) { options.body = options.data } if (options.body && typeof options.body !== 'string' && options.type.toLowerCase() === 'json') { options.body = JSON.stringify(options.body) options.headers.set('Content-Type', 'application/json') } if (external) { options.mode = 'cors' } return options } genericMethod(method, path, opts = {}) { let req = this.req let options = this.buildOptions(method, path, opts) let url = ''+options.url delete options.url let request = new Request(url, options) return fetch(request).then(response => { if (!response.ok) { return Promise.reject(response) } switch(options.as) { case 'json': return response.json() case 'text': return response.text() case 'blob': return response.blob() default: return response } }) } formatUrl(path) { if (this.isExternal(path)) { return path } let config = __SERVER__ ? this.options.server : this.options.client const adjustedPath = path[0] === '/' ? path.slice(1) : path if (config.base) { config.pathname = config.base } if (config.host && config.port) { config.host = `${config.host}:${config.port}` } const baseUrl = Url.format(config) return baseUrl + adjustedPath } }
JavaScript
0.000001
@@ -3220,24 +3220,69 @@ path%0A %7D%0A%0A + // Copy config to avoid mutating options%0A let conf @@ -3306,16 +3306,21 @@ ? +%7B ... this.opt @@ -3331,16 +3331,17 @@ .server +%7D %0A : @@ -3341,16 +3341,21 @@ : +%7B ... this.opt @@ -3365,16 +3365,18 @@ s.client + %7D %0A%0A co
e4ec495dc16eea0e873b651a83e4a894f1575e84
Cleanup stringify
lib/favicons.js
lib/favicons.js
'use strict'; var loaderUtils = require('loader-utils'); var favicons = require('favicons/es5'); var faviconPersitenceCache = require('./cache'); module.exports = function (content) { var self = this; self.cacheable && this.cacheable(); if (!self.emitFile) throw new Error('emitFile is required from module system'); if (!self.async) throw new Error('async is required'); var callback = self.async(); var query = loaderUtils.parseQuery(self.query); var pathPrefix = loaderUtils.interpolateName(self, query.outputFilePrefix, { context: query.context || this.rootContext || this.options.context, content: content, regExp: query.regExp }); var fileHash = loaderUtils.interpolateName(self, '[hash]', { context: query.context || this.rootContext || this.options.context, content: content, regExp: query.regExp }); var cacheFile = pathPrefix + '.cache'; faviconPersitenceCache.loadIconsFromDiskCache(self, query, cacheFile, fileHash, function (err, cachedResult) { if (err) return callback(err); if (cachedResult) { return callback(null, 'module.exports = ' + JSON.stringify(cachedResult)); } // Generate icons generateIcons(self, content, pathPrefix, query, function (err, iconResult) { if (err) return callback(err); faviconPersitenceCache.emitCacheInformationFile(self, query, cacheFile, fileHash, iconResult); callback(null, 'module.exports = ' + JSON.stringify(iconResult)); }); }); }; function getPublicPath (compilation) { var publicPath = compilation.outputOptions.publicPath || ''; if (publicPath.length && publicPath.substr(-1) !== '/') { publicPath += '/'; } return publicPath; } function generateIcons (loader, imageFileStream, pathPrefix, query, callback) { var publicPath = getPublicPath(loader._compilation); favicons(imageFileStream, { path: '', url: '', icons: query.icons, background: query.background, appName: query.appName }, function (err, result) { if (err) return callback(err); var html = result.html.filter(function (entry) { return entry.indexOf('manifest') === -1; }) .map(function (entry) { return entry.replace(/(href=[""])/g, '$1' + publicPath + pathPrefix); }); var loaderResult = { outputFilePrefix: pathPrefix, html: html, files: [] }; result.images.forEach(function (image) { loaderResult.files.push(pathPrefix + image.name); loader.emitFile(pathPrefix + image.name, image.contents); }); result.files.forEach(function (file) { loaderResult.files.push(pathPrefix + file.name); loader.emitFile(pathPrefix + file.name, file.contents); }); callback(null, loaderResult); }); } module.exports.raw = true;
JavaScript
0.999999
@@ -1090,33 +1090,34 @@ (null, ' -module.exports = +// LOADER START // ' + JSON @@ -1136,24 +1136,45 @@ achedResult) + + '// LOADER END //' );%0A %7D%0A @@ -1320,51 +1320,17 @@ -faviconPersitenceCache.emitCacheInformation +emitCache File @@ -1399,33 +1399,34 @@ (null, ' -module.exports = +// LOADER START // ' + JSON @@ -1447,16 +1447,37 @@ nResult) + + '// LOADER END //' );%0A %7D @@ -1678,16 +1678,16 @@ /';%0A %7D%0A - return @@ -1702,16 +1702,1134 @@ ath;%0A%7D%0A%0A +function emitCacheFile (loader, query, cacheFile, fileHash, iconResult) %7B%0A if (!query.persistentCache) %7B%0A return;%0A %7D%0A loader.emitFile(cacheFile, JSON.stringify(%7B%0A hash: fileHash,%0A optionHash: hashOptions(query),%0A result: iconResult%0A %7D));%0A%7D%0A%0A/**%0A * Try to load the file from the disc cache%0A */%0Afunction loadIconsFromDiskCache (loader, query, cacheFile, fileHash, callback) %7B%0A // Stop if cache is disabled%0A if (!query.persistentCache) return callback(null);%0A var resolvedCacheFile = path.resolve(__dirname, loader._compiler.parentCompilation.compiler.outputPath, cacheFile);%0A%0A fs.exists(resolvedCacheFile, function (exists) %7B%0A if (!exists) return callback(null);%0A fs.readFile(resolvedCacheFile, function (err, content) %7B%0A if (err) return callback(err);%0A try %7B%0A var cache = JSON.parse(content);%0A // Bail out if the file or the option changed%0A if (cache.hash !== fileHash %7C%7C cache.optionHash !== hashOptions(query)) %7B%0A return callback(null);%0A %7D%0A callback(null, cache.result);%0A %7D catch (e) %7B%0A callback(e);%0A %7D%0A %7D);%0A %7D);%0A%7D%0A%0A function
43f085629080f1e43d93a53712a83fc13005e749
Fix failure if there's no content-type returned
lib/ensure_content_type.js
lib/ensure_content_type.js
'use strict'; const cType = require('content-type'); const mwUtil = require('./mwUtil'); // Utility function to split path & version suffix from a profile parameter. function splitProfile(profile) { const match = /^(.*)\/([0-9.]+)$/.exec(profile); return { path: match[1], version: match[2], }; } /** * Simple content type enforcement * * - Assumes that the first `produces` array entry is the latest. * - Repeats request with `no-cache` header set if the content-type does not * match the latest version. */ function checkContentType(hyper, req, next, expectedContentType, responsePromise) { return responsePromise .then((res) => { // Do not check or re-render if the response was only rendered within // the last two minutes. if (res.headers && res.headers.etag && Date.now() - mwUtil.extractDateFromEtag(res.headers.etag) < 120000) { return res; } function updateSpecWarning() { // Returned content type version is higher than what the // spec promises. if (Math.random() < 0.001) { // Log a warning about the need to update the spec. Sampled 1:1000. hyper.log('warn/content-type/spec_outdated', { msg: 'The Swagger spec needs updating to reflect latest content type' + ' returned by the service.', expected: expectedContentType, actual: res.headers['content-type'] }); } // Don't fail the request. return res; } if (res.headers && res.headers['content-type'] !== expectedContentType) { // Parse the expected & response content type, and compare profiles. const expectedProfile = cType.parse(expectedContentType).parameters.profile; const actualProfile = cType.parse(res.headers['content-type']).parameters.profile; if (actualProfile && actualProfile !== expectedProfile) { if (!expectedProfile) { return updateSpecWarning(); } // Check if actual content type is newer than the spec const actualProfileParts = splitProfile(actualProfile); const expectedProfileParts = splitProfile(expectedProfile); if (actualProfileParts.path === expectedProfileParts.path && actualProfileParts.version > expectedProfileParts.version) { return updateSpecWarning(); } } // Re-try request with no-cache header if (!mwUtil.isNoCacheRequest(req)) { req.headers['cache-control'] = 'no-cache'; return checkContentType(hyper, req, next, expectedContentType, next(hyper, req)); } else { // Log issue hyper.log('warn/content-type/upgrade_failed', { msg: 'Could not update the content-type', expected: expectedContentType, actual: res.headers['content-type'] }); // Disable response caching, as we aren't setting a vary // either. res.headers['cache-control'] = 'max-age=0, s-maxage=0'; } } // Default: Just return. return res; }); } module.exports = (hyper, req, next, options, specInfo) => { const produces = specInfo.spec.produces; const expectedContentType = Array.isArray(produces) && produces[0]; const responsePromise = next(hyper, req); if (expectedContentType) { // Found a content type. Ensure that we return the latest profile. return checkContentType(hyper, req, next, expectedContentType, responsePromise); } else { return responsePromise; } };
JavaScript
0.003347
@@ -1654,32 +1654,210 @@ (res.headers && + res.headers === undefined) %7B%0A delete res.headers%5B'content-type'%5D;%0A %7D%0A%0A if (res.headers%0A && res.headers%5B'content-type'%5D%0A && res.headers%5B'co
3e7b8483439f1c2505e27b33353288a29a2013c4
Fix typo
lib/fetchAll.js
lib/fetchAll.js
"use strict"; const throat = require("throat"); const fetch = require("./fetch"); module.exports = function fetchAll(options) { return Promise.all( options.url.map( throat( options.config.concurrency, u => fetch(Object.assign({}, options, { url: u, indeex: options.siblings.indexOf(u) })) ) ) ); };
JavaScript
0.999999
@@ -298,17 +298,16 @@ inde -e x: optio
914a282b9d8af81a930b32d3e4fae26809aa3b02
Update Polish locale
source/js/Core/Language/locale/pl.js
source/js/Core/Language/locale/pl.js
/* Polish LANGUAGE ================================================== */ if(typeof VMM != 'undefined') { VMM.Language = { lang: "pl", api: { wikipedia: "pl" }, date: { month: ["Stycznia", "Lutego", "Marca", "Kwietnia", "Maja", "Czerwca", "Lipca", "Sierpnia", "Września", "Października", "Listopada", "Grudnia"], month_abbr: ["Sty.", "Lut.", "Mar.", "Kwi.", "Maj.", "Cze.", "Lip.", "Sie.", "Wrz.", "Paź.", "Lis.", "Gru."], day: ["Niedziela", "Poniedziałek", "Wtorek", "Środa", "Czwartek", "Piątek", "Sobota"], day_abbr: ["Nie.", "Pon.", "Wto.", "Śro.", "Czw.", "Pią.", "Sob."] }, dateformats: { year: "yyyy", month_short: "mmm", month: "mmmm yyyy", full_short: "d mmm", full: "d mmmm yyyy", time_short: "HH:MM:ss", time_no_seconds_short: "HH:MM", time_no_seconds_small_date: "HH:MM'<br/><small>'d mmmm yyyy'</small>'", full_long: "dddd',' d mmm yyyy 'um' HH:MM", full_long_small_date: "HH:MM'<br/><small>'dddd',' d mmm yyyy'</small>'" }, messages:{ loading_timeline: "Ładowanie Timeline... ", return_to_title: "Wróć do tytułu", expand_timeline: "Powiększ Timeline", contract_timeline: "Zmniejsz Timeline", wikipedia: "Z Wikipedii, wolnej encyklopedii", loading_content: "Ładowanie zawartości", loading: "Ładowanie" } } }
JavaScript
0
@@ -1037,24 +1037,25 @@ dowanie -Timeline +osi czasu ... %22,%0A%09 @@ -1121,24 +1121,24 @@ owi%C4%99ksz -Timeline +o%C5%9B czasu %22,%0A%09%09%09co @@ -1159,17 +1159,18 @@ e: %22 -Z +Po mniejsz Time @@ -1169,16 +1169,16 @@ jsz -Timeline +o%C5%9B czasu %22,%0A%09 @@ -1301,9 +1301,10 @@ %0A%09%09%7D%0A%09%7D%0A - %7D +%0A
f48cabde39938a3117229309a290216b27d7421f
clean markdown code
gulp/markdown.js
gulp/markdown.js
'use strict'; var gulp = require('gulp'); var path = require('path'); var _ = require('lodash'); var fs = require('fs'); var $ = require('gulp-load-plugins')({ pattern: ['gulp-*', 'del'] }); module.exports = function(options) { function markdown(files,dest,folder,env){ return function markdown(){ var stream = gulp.src(files) .pipe($.markdown({ highlight: function(code) { return require('highlight.js').highlightAuto(code).value; }, header: true })); _.each([ 'String', 'Number', 'Boolean', 'Object', 'Array', 'Phaser.Group', ],function(val,i){ stream.pipe($.replace(new RegExp("<"+val+">",'g'), "<span class='paramter-type'>&lt;"+val+"&gt;</span>")) }) stream.pipe($.cheerio(function ($$, file) { // var firstTitle = $$('h1').eq(0).text(); // if(!firstTitle) firstTitle=path.basename(file.path,path.extname(file.path)); var firstTitle=path.basename(file.path,path.extname(file.path)); file.path = path.join(path.dirname(file.path), folder, firstTitle.replace(/[\$|\.]/g,''), '/index'+path.extname(file.path) ); })) // .pipe($.if(function(){ // return env=='dist' // }, $.replace('src="images/', 'src="../src/images/'))) .pipe(gulp.dest(dest)); return stream; } } gulp.task('clean:docs', function (done) { return $.del([ options.tmp + '/site/posts', options.tmp + '/site/portfolio-posts', options.tmp + '/site/partials', ],{force:true}); }); gulp.task('markdown:portfolio', gulp.series(markdown([ 'src/portfolio-posts/*.md', ], options.tmp+'/site', "/portfolio-posts/" ))); gulp.task('markdown:posts', gulp.series(markdown([ 'src/posts/*.md', ], options.tmp+'/site', "/posts/" ))); // gulp.task('markdown:mainPage', gulp.series(markdown([ // 'src/partials/main.md', // ], // options.tmp+'/site', // "/partials/" // ))); gulp.task('markdown:mainPage', function(){ return gulp.src(['src/partials/main.md']) .pipe($.markdown({ highlight: function(code) { return require('highlight.js').highlightAuto(code).value; }, header: true })) .pipe(gulp.dest(options.tmp+'/site/partials')); }); gulp.task('markdown', gulp.series( 'clean:docs', gulp.parallel( 'markdown:portfolio', 'markdown:mainPage', 'markdown:posts' ) )); };
JavaScript
0.000018
@@ -1754,19 +1754,16 @@ %09)));%0A%0A%09 -// gulp.tas @@ -1809,19 +1809,16 @@ down(%5B%0A%09 -// %09%09'src/p @@ -1840,19 +1840,13 @@ ',%0A%09 -// %09%5D,%0A%09 -// %09opt @@ -1864,19 +1864,16 @@ site',%0A%09 -// %09%22/parti @@ -1883,18 +1883,18 @@ /%22%0A%09 -// )));%0A%0A%09 +// gulp @@ -1929,24 +1929,27 @@ unction()%7B%0A%09 +// %09return gulp @@ -1980,16 +1980,19 @@ .md'%5D)%0A%09 +// %09.pipe($ @@ -2004,16 +2004,19 @@ down(%7B%0A%09 +// %09%09highli @@ -2038,16 +2038,19 @@ ode) %7B%0A%09 +// %09%09%09retur @@ -2103,22 +2103,28 @@ value;%0A%09 +// %09%09%7D,%0A%09 +// %09%09header @@ -2131,22 +2131,28 @@ : true%0A%09 +// %09%7D))%0A%09 +// %09.pipe(g @@ -2189,24 +2189,27 @@ rtials'));%0A%09 +// %7D);%0A%0A%09gulp.t
5ade9b9e846eccdb7139d6bb612fc6db4c450c93
Use git config properties to determine default projectAuthor.
app/index.js
app/index.js
'use strict'; var path = require('path'); var yeoman = require('yeoman-generator'); var yosay = require('yosay'); // var chalk = require('chalk'); var YuiGenerator = yeoman.generators.Base.extend({ init: function () { this.pkg = require('../package.json'); this.on('end', function () { if (!this.options['skip-install']) { this.installDependencies(); } }); }, askFor: function () { var done = this.async(); // Have Yeoman greet the user. this.log(yosay('Welcome to the marvelous YUI generator!')); var prompts = [ { name: 'projectName', message: 'Project name', default: path.basename(process.cwd()) }, { name: 'projectTitle', message: 'Project title (if different)', default: function (props) { return props.projectName; } }, { name: 'projectAuthor', message: 'Project author', default: 'Rockstar Developer <[email protected]>' }, { name: 'projectDescription', message: 'Project description', default: 'The best YUI-based project ever.' }, { name: 'projectRepository', message: 'Project repository URL', default: '' }, { name: 'projectVersion', message: 'Project version', default: '0.0.0' }, { type: 'confirm', name: 'cleanBuild', message: 'Version build directory?', default: true, filter: function (input) { // inverts answer return !input; } }, { type: 'confirm', name: 'yuiRelease', message: 'Support YUI release tasks?', default: true }, { name: 'copyrightOwner', message: 'Copyright owner', default: 'Yahoo! Inc.' }, { name: 'yuiVersion', message: 'YUI version', default: '3.13.0' } ]; this.prompt(prompts, function (props) { this.projectName = props.projectName; this.projectTitle = props.projectTitle; this.projectAuthor = props.projectAuthor; this.projectDescription = props.projectDescription; this.projectRepository = props.projectRepository; this.projectVersion = props.projectVersion; this.cleanBuild = props.cleanBuild; this.yuiRelease = props.yuiRelease; this.copyrightOwner = props.copyrightOwner; this.yuiVersion = props.yuiVersion; done(); }.bind(this)); }, app: function () { this.mkdir('src'); this.template('_package.json', 'package.json'); this.template('_bower.json', 'bower.json'); this.template('_BUILD.md', 'BUILD.md'); this.template('_README.md', 'README.md'); this.template('_Gruntfile.js', 'Gruntfile.js'); }, projectfiles: function () { this.copy('editorconfig', '.editorconfig'); this.copy('gitignore', '.gitignore'); this.copy('jshintrc', '.jshintrc'); this.copy('yeti.json', '.yeti.json'); } }); module.exports = YuiGenerator;
JavaScript
0
@@ -487,16 +487,49 @@ async(); +%0A var git = this.user.git; %0A%0A @@ -1172,53 +1172,504 @@ lt: -'Rockstar Developer %[email protected]%3E' +function () %7B%0A var name = git.name %7C%7C git.username, // generator v0.17.0 uses 'name'%0A email = git.email,%0A author = 'Rockstar Developer %[email protected]%3E';%0A if (name) %7B%0A author = name;%0A if (email) %7B%0A author += (' %3C' + email + '%3E');%0A %7D%0A %7D%0A return author;%0A %7D %0A
6b3ad70d9bd6c0559adc067fc432174689e3012b
Set each slide to have it's own z-index.
angular-web-applications/src/scripts/app.js
angular-web-applications/src/scripts/app.js
(function () { // Set to true to show console.log for debugging var DEBUG_MODE = true; 'use strict'; var Slide = function (title) { // Constructor this.title = title; this.eleRef = null; }; Slide.prototype.SetReference = function (dom) { this.eleRef = dom; }; Slide.prototype.MoveLeft = function () {}; Slide.prototype.MoveRight = function () {}; Slide.prototype.TransitionLeft = function () {}; Slide.prototype.TransitionRight = function () {}; ///////////////// /// APP START /// ///////////////// var slides = []; var currentSlideIdx = 0; /** * Initialize App */ function Initialize() { GetSlides(); } /** * Get slide DOM reference */ function GetSlides() { var slidesDOM = document.getElementsByClassName('slide'); setTimeout(function () { for (var i = 0, limit = slidesDOM.length; i < limit; ++i) { var newSlide = new Slide(slidesDOM[i].dataset.title); newSlide.SetReference(slidesDOM[i]); slides.push(newSlide); } }, 0); } Initialize(); }());
JavaScript
0
@@ -1002,32 +1002,131 @@ %0A + // Set z-index for each slide%0A slidesDOM%5Bi%5D.style.zIndex = 10 + i;%0A%0A
cf3a64135025666baf9d3537a7327a5c6b6ca19a
Fix progress link to README
lib/generate/site/index.js
lib/generate/site/index.js
var util = require("util"); var path = require("path"); var Q = require("q"); var _ = require("lodash"); var swig = require('swig'); var fs = require("../fs"); var parse = require("../../parse"); var BaseGenerator = require("../generator"); var indexer = require('./search_indexer'); // Swig filter for returning the count of lines in a code section swig.setFilter('lines', function(content) { return content.split('\n').length; }); // Swig filter for returning a link to the associated html file of a markdown file swig.setFilter('mdLink', function(link) { return link.replace(".md", ".html"); }); var Generator = function() { BaseGenerator.apply(this, arguments); // Attach methods to instance _.bindAll(this); this.revision = Date.now(); this.indexer = indexer(); // Load base template this.template = swig.compileFile(path.resolve(this.options.theme, 'templates/site.html')); this.langsTemplate = swig.compileFile(path.resolve(this.options.theme, 'templates/langs.html')); }; util.inherits(Generator, BaseGenerator); // Generate a template Generator.prototype._writeTemplate = function(tpl, options, output) { var that = this; return Q() .then(function(sections) { return tpl(_.extend({ revision: that.revision, title: that.options.title, description: that.options.description, githubAuthor: that.options.github.split("/")[0], githubId: that.options.github, githubHost: that.options.githubHost, summary: that.options.summary, allNavigation: that.options.navigation }, options)); }) .then(function(html) { return fs.writeFile( output, html ); }); }; Generator.prototype.indexPage = function(lexed, pagePath) { this.indexer.add(lexed, pagePath); return Q(); }; // Convert a markdown file to html Generator.prototype.convertFile = function(content, _input) { var that = this; var progress = parse.progress(this.options.navigation, _input); _output = _input.replace(".md", ".html"); if (_output == "README.html") _output = "index.html"; var input = path.join(this.options.input, _input); var output = path.join(this.options.output, _output); var basePath = path.relative(path.dirname(output), this.options.output) || "."; return Q() .then(function() { // Lex page return parse.lex(content); }) .then(function(lexed) { // Index page in search return that.indexPage(lexed, _output) .then(_.constant(lexed)); }) .then(function(lexed) { // Get HTML generated sections return parse.page(lexed, { repo: that.options.githubId, dir: path.dirname(_input) || '/', outdir: path.dirname(_input) || '/', }); }) .then(function(sections) { return that._writeTemplate(that.template, { progress: progress, _input: _input, content: sections, basePath: basePath, staticBase: path.join(basePath, "gitbook"), }, output); }); }; // Generate languages index Generator.prototype.langsIndex = function(langs) { var that = this; var basePath = "."; return this._writeTemplate(this.langsTemplate, { langs: langs.list, basePath: basePath, staticBase: path.join(basePath, "gitbook"), }, path.join(this.options.output, "index.html")) .then(function() { // Copy assets return that.copyAssets(); }); }; // Copy assets Generator.prototype.copyAssets = function() { var that = this; return fs.copy( path.join(that.options.theme, "assets"), path.join(that.options.output, "gitbook") ); }; // Dump search index to disk Generator.prototype.writeSearchIndex = function() { return fs.writeFile( path.join(this.options.output, 'search_index.json'), this.indexer.dump() ); }; Generator.prototype.finish = function() { return this.copyAssets() .then(this.writeSearchIndex); }; module.exports = Generator;
JavaScript
0.000001
@@ -563,22 +563,26 @@ ) %7B%0A -return +var link = link.re @@ -604,16 +604,85 @@ html%22);%0A + if (link == %22README.html%22) link = %22index.html%22;%0A return link;%0A %7D);%0A%0Avar
149a10359f8558e6df71bfa4b8a0cc6062071fd5
Update frontier.js
lib/frontier.js
lib/frontier.js
//Licensed under the ISC license. //Copyright 2014 Yuki Ahmed var WORLD_STATUS = "http://frontier.ffxiv.com/worldStatus/current_status.json", LOBBY_STATUS = "http://frontier.ffxiv.com/worldStatus/gate_status.json", LOGIN_STATUS = "http://frontier.ffxiv.com/worldStatus/login_status.json", HEADLINE_URL = "http://frontier.ffxiv.com/news/headline.json?lang=en-us", ARTICLE_INFO = "http://frontier.ffxiv.com/news/article.json?id=";
JavaScript
0.000001
@@ -202,32 +202,43 @@ gate_status.json +?lang=en-us %22,%0A LOGIN_STA @@ -444,14 +444,25 @@ le.json? +lang=en-us& id=%22;%0A
333ab79004a9a27cb70262c81c8948bf3d3928e9
Fix HubSpot script url
corehq/apps/analytics/static/analytix/js/hubspot.js
corehq/apps/analytics/static/analytix/js/hubspot.js
/* globals window */ /** * Instatiates the Hubspot analytics platform. */ hqDefine('analytix/js/hubspot', [ 'underscore', 'analytix/js/initial', 'analytix/js/logging', 'analytix/js/utils', ], function ( _, initialAnalytics, logging, utils ) { 'use strict'; var _get = initialAnalytics.getFn('hubspot'), _global = initialAnalytics.getFn('global'), logger = logging.getLoggerForApi('Hubspot'), _data = {}; var _hsq = window._hsq = window._hsq || []; var __init__ = function () { _data.apiId = _get('apiId'); if (_data.apiId) { _data.scriptSrc = '//js.hs-analytics.net/analytics/' + utils.getDateHash() + '/' + _data.apiId; utils.insertScript(_data.scriptSrc, logger.debug.log, { id: 'hs-analytics', }); } }; $(function() { if (_global('isEnabled')) { __init__(); logger.debug.log('Initialized'); } }); /** * Sends data to Hubspot to identify the current session. * @param {object} data */ var identify = function (data) { logger.debug.log(data, "Identify"); _hsq.push(['identify', data]); }; /** * Tracks an event through the Hubspot API * @param {string} eventId - The ID of the event. If you created the event in HubSpot, use the numerical ID of the event. * @param {integer|float} value - This is an optional argument that can be used to track the revenue of an event. */ var trackEvent = function (eventId, value) { if (_global('isEnabled')) { logger.debug.log(logger.fmt.labelArgs(["Event ID", "Value"], arguments), 'Track Event'); _hsq.push(['trackEvent', { id: eventId, value: value, }]); } }; return { logger: logger, identify: identify, trackEvent: trackEvent, }; });
JavaScript
0.007367
@@ -716,16 +716,24 @@ ta.apiId + + '.js' ;%0A
45001258ffba7aa98c7a3d07ad6325dabe45ea9d
Fix the condition because `projectId` in the localStorage is null when starting app for the first time
app/index.js
app/index.js
(function() { 'use strict'; const DEFAULT_FETCH_INTERVAL_SEC = 600; const NOTIE_DISPLAY_SEC = 1.5; const COLOR_ICON_FILENAME_64 = 'redmine_icon_color_64.png'; var remote = window.require('remote'); var shell = remote.require('shell'); var fs = require('fs'); var notie = require('notie'); var notifier = require('node-notifier'); /** * Initialize the RedmineNotifier object. * @constructor */ function RedmineNotifier() { this._lastExecutionTime = null; this._settings = null; this._fetchTimer = null; } /** * Initialize the event listeners. */ RedmineNotifier.prototype.initEventListener = function() { var _this = this; document.getElementById('save-button').addEventListener('click', function() { _this.readScreenSettings(); if (_this.validateSettings()) { _this.initFetch(); _this.updateSettings(); } else { _this.readStoredSettings(); } notie.alert(1, 'Settings have been saved.', NOTIE_DISPLAY_SEC); }); document.getElementById('close-button').addEventListener('click', function() { _this.readStoredSettings(); _this.displaySettings(); remote.getCurrentWindow().hide(); }); document.getElementById('test-connection-button').addEventListener('click', function() { _this.testConnection(); }); }; /** * Display the default settings on the screen. */ RedmineNotifier.prototype.displayDefaultSettings = function() { document.getElementById('default-fetch-interval-sec').innerHTML = DEFAULT_FETCH_INTERVAL_SEC; }; /** * Display the settings on the screen. */ RedmineNotifier.prototype.displaySettings = function() { document.getElementById('url').value = this._settings.url; document.getElementById('api-key').value = this._settings.apiKey; document.getElementById('project-id').value = this._settings.projectId; document.getElementById('fetch-interval-sec').value = this._settings.fetchIntervalSec; }; /** * Get the settings from the screen. */ RedmineNotifier.prototype.getPageSettings = function() { return { url: document.getElementById('url').value, apiKey: document.getElementById('api-key').value, projectId: document.getElementById('project-id').value, fetchIntervalSec: document.getElementById('fetch-interval-sec').value }; }; /** * Read the settings from the screen. */ RedmineNotifier.prototype.readScreenSettings = function() { this._settings = this.getPageSettings(); }; /** * Read the settings from the localStorage. */ RedmineNotifier.prototype.readStoredSettings = function() { this._settings = { url: localStorage.getItem('url'), apiKey: localStorage.getItem('apiKey'), projectId: localStorage.getItem('projectId'), fetchIntervalSec: localStorage.getItem('fetchIntervalSec') }; }; /** * Update the stored last execution time. */ RedmineNotifier.prototype.updateLastExecutionTime = function() { this._lastExecutionTime = (new Date()).toISOString().replace(/\.\d+Z$/, 'Z'); localStorage.setItem('lastExecutionTime', this._lastExecutionTime); }; /** * Update the stored settings. */ RedmineNotifier.prototype.updateSettings = function() { localStorage.setItem('url', this._settings.url); localStorage.setItem('apiKey', this._settings.apiKey); localStorage.setItem('projectId', this._settings.projectId); localStorage.setItem('fetchIntervalSec', this._settings.fetchIntervalSec); }; /** * Validate the settings. */ RedmineNotifier.prototype.validateSettings = function() { if (this._settings.url && this._settings.apiKey) { return true; } else { notie.alert(3, 'Please enter required fields.', NOTIE_DISPLAY_SEC); return false; } }; /** * Initialize the fetch function. */ RedmineNotifier.prototype.initFetch = function() { var _this = this; var intervalMsec = 1000 * (this._settings.fetchIntervalSec || DEFAULT_FETCH_INTERVAL_SEC); clearInterval(this._fetchTimer); this._fetchTimer = setInterval(function() { _this.fetch(); }, intervalMsec); }; /** * Fetch updated issues by using Redmine REST API. */ RedmineNotifier.prototype.fetch = function() { var _this = this; var xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { _this.notify(JSON.parse(xhr.responseText).issues); } }; xhr.open('GET', this._settings.url + '/issues.json' + this.getRequestParams(this._settings.projectId)); xhr.setRequestHeader('X-Redmine-API-Key', this._settings.apiKey); xhr.send(); this.updateLastExecutionTime(); }; /** * Test the connection to the Redmine. */ RedmineNotifier.prototype.testConnection = function() { var xhr = new XMLHttpRequest(); var pageSettings = this.getPageSettings(); xhr.onreadystatechange = function() { var style = 3; var message = 'Connection failed.'; if (xhr.readyState === 4) { if (xhr.status === 200) { style = 1; message = 'Connection succeeded.'; } notie.alert(style, message, NOTIE_DISPLAY_SEC); } }; xhr.open('GET', pageSettings.url + '/issues.json' + this.getRequestParams(pageSettings.projectId)); xhr.setRequestHeader('X-Redmine-API-Key', pageSettings.apiKey); xhr.send(); }; /** * Get the request parameters. * @param {string} projectId - Project ID (a numeric value, not a project identifier). * @return {string} Request parameters. */ RedmineNotifier.prototype.getRequestParams = function(projectId) { var params = [ 'updated_on=%3E%3D' + this._lastExecutionTime, 'sort=updated_on:desc' ]; if (projectId !== '') { params.unshift('project_id=' + projectId); } return '?' + params.join('&'); }; /** * Send the desktop notification. * @param {Object} issues - All of updated issues. */ RedmineNotifier.prototype.notify = function(issues) { var _this = this; var issueCount = issues.length; if (issueCount === 0) return; var appDir = __dirname + '.unpacked'; // Production try { fs.statSync(appDir); } catch(e) { appDir = __dirname; // Development } // Display the latest issue's subject only notifier.notify({ title: '(' + issueCount + ') Redmine Notifier', message: issues[0].subject, icon: appDir + '/images/' + COLOR_ICON_FILENAME_64, wait: true }); notifier.removeAllListeners(); notifier.once('click', function(notifierObject, options) { shell.openExternal(_this._settings.url + '/issues/' + issues[0].id); notifier.removeAllListeners(); }); notifier.once('timeout', function(notifierObject, options) { notifier.removeAllListeners(); }); }; window.onload = function() { var redmineNotifier = new RedmineNotifier(); redmineNotifier.initEventListener(); redmineNotifier.displayDefaultSettings(); redmineNotifier.updateLastExecutionTime(); redmineNotifier.readStoredSettings(); redmineNotifier.displaySettings(); if (redmineNotifier.validateSettings()) { redmineNotifier.initFetch(); } }; }());
JavaScript
0.000137
@@ -5870,16 +5870,49 @@ if ( +typeof projectId === 'string' && projectI