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
bfe4fb2bb1ead89da54918631daea9556211e1a3
Work directly with transformers config in file.js.
bin/file.js
bin/file.js
var Transformer = require('./../lib/transformer'); var _ = require('lodash'); module.exports = function (program, file) { // Enable all transformers by default var options = { transformers: { classes: true, stringTemplates: true, arrowFunctions: true, let: true, defaultArguments: true, objectMethods: true } }; // When --no-classes used, disable classes transformer if(! program.classes) { options.transformers.classes = false; } // When --transformers used turn off everything besides the specified tranformers if (program.transformers) { options.transformers = _.mapValues(options.transformers, _.constant(false)); program.transformers.forEach(function (name) { if (!options.transformers.hasOwnProperty(name)) { console.error("Unknown transformer '" + name + "'."); } options.transformers[name] = true; }); } var transformer = new Transformer(options); transformer.readFile(file[0]); transformer.applyTransformations(); transformer.writeFile(program.outFile); console.log('The file "' + program.outFile + '" has been written.'); };
JavaScript
0
@@ -166,24 +166,8 @@ var -options = %7B%0A tran @@ -178,18 +178,17 @@ mers -: + = %7B%0A - clas @@ -194,26 +194,24 @@ sses: true,%0A - stringTe @@ -229,18 +229,16 @@ ue,%0A - - arrowFun @@ -255,18 +255,16 @@ ue,%0A - let: tru @@ -270,18 +270,16 @@ ue,%0A - - defaultA @@ -298,18 +298,16 @@ ue,%0A - objectMe @@ -318,22 +318,16 @@ s: true%0A - %7D%0A %7D;%0A%0A @@ -407,32 +407,24 @@ sses) %7B%0A -options. transformers @@ -560,32 +560,24 @@ mers) %7B%0A -options. transformers @@ -591,24 +591,16 @@ pValues( -options. transfor @@ -688,24 +688,16 @@ if (! -options. transfor @@ -805,16 +805,8 @@ -options. tran @@ -881,15 +881,36 @@ mer( -options +%7Btransformers: transformers%7D );%0A
b4bb171d7b8143c7183eed3ec34a809d1dc450fd
Fix keycloak sample code eslint issues
examples/keycloak-auth-hook.js
examples/keycloak-auth-hook.js
'use strict'; /** * Keycloak hook for securing an Unleash server * * This example assumes that all users authenticating via * keycloak should have access. You would probably limit access * to users you trust. * * The implementation assumes the following environement variables: * * - AUTH_HOST * - AUTH_REALM * - AUTH_CLIENT_ID */ // const { User, AuthenticationRequired } = require('unleash-server'); const { User, AuthenticationRequired } = require('../lib/server-impl.js'); const KeycloakStrategy = require("@exlinc/keycloak-passport"); const passport = require('passport'); const kcConfig = { host: "http://" + process.env.AUTH_HOST, realm: process.env.AUTH_REALM, clientId: process.env.AUTH_CLIENT_ID, contextPath: '', // Use when Unleash is hosted on an url like /unleash/ clientSecret: "", }; passport.use( "keycloak", new KeycloakStrategy( { host: kcConfig.host, realm: kcConfig.realm, clientID: kcConfig.clientId, clientSecret: "We don't need that, but is required", callbackURL: `${kcConfig.contextPath}/api/auth/callback`, authorizationURL: `${kcConfig.host}/auth/realms/hamis/protocol/openid-connect/auth`, tokenURL: `${kcConfig.host}/auth/realms/hamis/protocol/openid-connect/token`, userInfoURL: `${kcConfig.host}/auth/realms/hamis/protocol/openid-connect/userinfo` }, (accessToken, refreshToken, profile, done) => { done( null, new User({ name: profile.fullName, email: profile.email, }) ); } ) ); function enableKeycloakOauth(app) { app.use(passport.initialize()); app.use(passport.session()); passport.serializeUser((user, done) => done(null, user)); passport.deserializeUser((user, done) => done(null, user)); app.get('/api/admin/login', passport.authenticate('keycloak')); app.get('/api/auth/callback', passport.authenticate('keycloak'), (req, res, next) => { res.redirect(`${kcConfig.contextPath}/`); }); app.use('/api/admin/', (req, res, next) => { if (req.user) { next(); } else { // Instruct unleash-frontend to pop-up auth dialog return res .status('401') .json( new AuthenticationRequired({ path: `${kcConfig.contextPath}/api/admin/login`, type: 'custom', message: `You have to identify yourself in order to use Unleash. Click the button and follow the instructions.`, }) ) .end(); } }); } module.exports = enableKeycloakOauth;
JavaScript
0.000001
@@ -262,17 +262,16 @@ environ -e ment var @@ -488,17 +488,16 @@ .js');%0A%0A -%0A const Ke @@ -521,17 +521,17 @@ require( -%22 +' @exlinc/ @@ -547,17 +547,17 @@ passport -%22 +' );%0Aconst @@ -600,43 +600,25 @@ nst -kcConfig = %7B%0A host: %22 +host = %60 http:// -%22 + +$%7B proc @@ -638,20 +638,25 @@ HOST -,%0A +%7D%60;%0Aconst realm -: + = pro @@ -674,21 +674,23 @@ TH_REALM -,%0A +;%0Aconst clientI @@ -690,17 +690,18 @@ clientId -: + = process @@ -719,21 +719,23 @@ LIENT_ID -,%0A +;%0Aconst context @@ -742,93 +742,35 @@ Path -: '', // Use when Unleash is hosted on an url like /unleash/%0A clientSecret: %22%22,%0A%7D + = process.env.CONTEXT_PATH ;%0A%0Ap @@ -790,17 +790,17 @@ -%22 +' keycloak %22,%0A @@ -795,17 +795,17 @@ keycloak -%22 +' ,%0A ne @@ -850,23 +850,8 @@ -host: kcConfig. host @@ -873,57 +873,22 @@ ealm -: kcConfig.realm,%0A clientID: kcConfig. +,%0A clie @@ -982,33 +982,24 @@ backURL: %60$%7B -kcConfig. contextPath%7D @@ -1048,33 +1048,24 @@ tionURL: %60$%7B -kcConfig. host%7D/auth/r @@ -1128,33 +1128,24 @@ okenURL: %60$%7B -kcConfig. host%7D/auth/r @@ -1216,25 +1216,16 @@ URL: %60$%7B -kcConfig. host%7D/au @@ -1273,16 +1273,17 @@ serinfo%60 +, %0A @@ -1778,24 +1778,25 @@ ll, user));%0A +%0A app.get( @@ -1860,24 +1860,33 @@ app.get( +%0A '/api/auth/c @@ -1894,16 +1894,24 @@ llback', +%0A passpor @@ -1937,16 +1937,24 @@ cloak'), +%0A (req, r @@ -1951,37 +1951,35 @@ (req, res -, next ) =%3E %7B%0A + res. @@ -1990,25 +1990,16 @@ rect(%60$%7B -kcConfig. contextP @@ -2011,17 +2011,26 @@ %60);%0A -%7D + %7D%0A );%0A%0A @@ -2361,17 +2361,8 @@ %60$%7B -kcConfig. cont
cf46a6ea82cbbb38bcd66069fdf06438edbc922c
Clean up spacing
server/db/apiController.js
server/db/apiController.js
/* eslint strict: 0*/ const api = require('../../API_KEYS'); const httpRequest = require('http-request'); const parseString = require('xml2js').parseString; module.exports = { dictionary: (req, res) => { 'use strict'; const reqWord = req.params.word; const webster = `http://www.dictionaryapi.com/api/v1/references/collegiate/xml/${reqWord}?key=${api.websterDictionaryAPI}`; httpRequest.get(webster, (err, data) => { if (err) { return; } parseString(data.buffer, (error, result) => { if (error) { res.send(error); return; } const dictionaryEntries = result.entry_list.entry[0].def[0].dt; for (let i = 0; i < dictionaryEntries.length; i ++) { if (typeof dictionaryEntries[i] === 'string') { const defWithColon = dictionaryEntries[i]; const defWithoutColon = defWithColon.slice(1, defWithColon.length); res.send(defWithoutColon); return; } } for (let j = 0; j < dictionaryEntries.length; j ++) { if (dictionaryEntries[j]._.length > 2) { const defWithColon = dictionaryEntries[j]._; const defWithoutColon = defWithColon.slice(1, defWithColon.length); res.send(defWithoutColon); return; } } }); }); }, thesaurus: (req, res) => { const reqWord = req.params.word; const webster = `http://www.dictionaryapi.com/api/v1/references/thesaurus/xml/${reqWord}?key=${api.websterThesaurusAPI}`; httpRequest.get(webster, (err, data) => { if (err) { res.send(err); return; } parseString(data.buffer, (error, result) => { if (error) { res.send(error); return; } const thesaurusEntries = result.entry_list.entry; const thesaurusObj = {}; if (thesaurusEntries.length === 1) { if (typeof thesaurusEntries[0].sens[0].syn[0] === 'object') { thesaurusObj.syns = thesaurusEntries[0].sens[0].syn[0][0]; } else { thesaurusObj.syns = thesaurusEntries[0].sens[0].syn[0]; } thesaurusObj.pos = thesaurusEntries[0].fl[0]; } else { if (typeof thesaurusEntries[1].sens[0].syn[0] === 'object') { thesaurusObj.syns = thesaurusEntries[1].sens[0].syn[0]._; } else { thesaurusObj.syns = thesaurusEntries[1].sens[0].syn[0]; } thesaurusObj.pos = thesaurusEntries[1].fl[0]; } res.send(thesaurusObj); }); }); }, };
JavaScript
0.000454
@@ -1883,16 +1883,64 @@ j = %7B%7D;%0A + if (thesaurusEntries !== undefined) %7B%0A @@ -1978,32 +1978,34 @@ 1) %7B%0A + + if (typeof thesa @@ -2054,32 +2054,34 @@ ) %7B%0A + thesaurusObj.syn @@ -2125,32 +2125,34 @@ %5D%5B0%5D;%0A + + %7D else %7B%0A @@ -2136,32 +2136,34 @@ %7D else %7B%0A + thes @@ -2216,34 +2216,38 @@ n%5B0%5D;%0A + + %7D%0A + thesau @@ -2286,32 +2286,34 @@ .fl%5B0%5D;%0A + + %7D else %7B%0A @@ -2297,32 +2297,34 @@ %7D else %7B%0A + if (ty @@ -2383,32 +2383,34 @@ ) %7B%0A + + thesaurusObj.syn @@ -2453,32 +2453,34 @@ 0%5D._;%0A + %7D else %7B%0A @@ -2464,32 +2464,34 @@ %7D else %7B%0A + thes @@ -2544,34 +2544,38 @@ n%5B0%5D;%0A -%7D%0A + %7D%0A thesau @@ -2614,34 +2614,38 @@ .fl%5B0%5D;%0A -%7D%0A + %7D%0A res.send @@ -2660,16 +2660,68 @@ usObj);%0A + %7D else %7B%0A res.send('-');%0A %7D%0A %7D)
0dfa91dad41ea89316a58a7b1aa3cce6d87931a6
Allow CSS to work offline
htmlifier/offlineifier.js
htmlifier/offlineifier.js
function offlineify ({ log = console.log } = {}) { function toDataURI (response) { return response.blob().then(blob => new Promise(resolve => { const reader = new FileReader() reader.addEventListener('load', e => { resolve(reader.result) }, { once: true }) reader.readAsDataURL(blob) })) } function toText (response) { return response.ok ? response.text() : Promise.reject(new Error(response.status)) } function removeScriptTag (js) { return js.replace(/<\/script>/g, '') } log('Getting all required files') return Promise.all([ fetch('./index.html').then(toText), fetch('https://sheeptester.github.io/scratch-vm/16-9/vm.min.js') .then(toText) .then(async vmCode => { let extensionWorker const extensionWorkerMatch = vmCode.match(extensionWorkerGet) if (!extensionWorkerMatch) return Promise.reject(new Error('Cannot find extension-worker.js')) const workerCode = await fetch('https://sheeptester.github.io/scratch-vm/16-9/' + extensionWorkerMatch[1]) .then(r => r.text()) return [vmCode, workerCode].map(removeScriptTag) }), fetch('./hacky-file-getter.js').then(toText).then(removeScriptTag), fetch('./download.js').then(toText).then(removeScriptTag), fetch('./template.html').then(toDataURI) ]).then(([html, [vm, extensionWorker], hackyFileGetter, downloader, template]) => { html = html .replace('<body>', '<body class="offline">') // Using functions to avoid $ substitution .replace('<script src="./hacky-file-getter.js" charset="utf-8"></script>', () => `<script>${hackyFileGetter}</script>`) .replace('<script src="./download.js" charset="utf-8"></script>', () => `<script>${downloader}</script>`) // . wildcard in regex doesn't include newlines lol // https://stackoverflow.com/a/45981809 .replace(/<!-- no-offline -->[^]*?<!-- \/no-offline -->/g, '') .replace(/\/\* no-offline \*\/[^]*?\/\* \/no-offline \*\//g, '') .replace('// [offline-vm-src]', `Promise.resolve(document.getElementById('vm-src').innerHTML)`) .replace('// [offline-extension-worker-src]', `const workerCode = document.getElementById('worker-src').innerHTML`) .replace('// [template]', () => JSON.stringify(template)) // Do this last because it phat // javascript/worker: https://www.html5rocks.com/en/tutorials/workers/basics/ .replace('<script src="https://sheeptester.github.io/scratch-vm/16-9/vm.min.js" charset="utf-8"></script>', () => `<script id="vm-src">${vm}</script><script id="worker-src" type="javascript/worker">${extensionWorker}</script>`) log('Attempting to download...') download(html, 'htmlifier-offline.html', 'text/html') log('All good!') }) }
JavaScript
0.000001
@@ -1340,16 +1340,54 @@ DataURI) +,%0A fetch('./main.css').then(toText) %0A %5D).th @@ -1457,16 +1457,21 @@ template +, css %5D) =%3E %7B%0A @@ -2292,16 +2292,107 @@ rHTML%60)%0A + .replace('%3Clink rel=%22stylesheet%22 href=%22./main.css%22%3E', () =%3E %60%3Cstyle%3E$%7Bcss%7D%3C/style%3E%60)%0A .r
9ddae47086699d1a8e578b87cec0b828e6fe067d
Remove route.currentModel
src/classes/route.js
src/classes/route.js
'use strict' const Http = require('./http') const middleware = new WeakMap() /** * The Ash route class extends the @see Http class and so has access * to request and response properties. * * Routes execute via a series of hooks in the following order * * 1. deserialize * 2. beforeModel * 3. model * 4. afterModel * 5. serialize * * If a hook returns a promise, the subsequent hook will not execute until the promise has resolved. * * All hooks are optional except for `model` and amything returned from the `model` hook will be returned * to the client. * * Routes support the following: * - mixins (@see Mixin) * - services (@see Service) * - middleware (@see Middleware) * * @class Route * @extends Http * @constructor */ module.exports = class Route extends Http { /** * * @method constructor */ constructor (context) { super(context) const mw = [] this.constructor.middleware(middleware => mw.push(middleware)) middleware.set(this, mw) } /** * @method hasMiddleware * @private */ get hasMiddleware () { return middleware.get(this).length > 0 } /** * @method registeredMiddleware * @private */ get registeredMiddleware () { return middleware.get(this) } /** * Route middleware * * You can use this to register route specific middleware. ie. middleware specified here * will only run for this route. You can register the same piece of middleware in multiple * routes but you must do so explicitly by registering it in that routes `middleware` method. * * Call `register` with the name of the middleware in the `app/middleware` directory that * you want to load. You can call register multiple times to register more than one middleware * and middleware will be executed in the order registered. * * Example * * Example: registering middleware on a route * ``` * * // app/routes/my-route.js * const Ash = require('@ash-framework/ash') * * module.exports = class MyRoute extends Ash.Route { * static middleware (register) { * register('my-middleware') * } * } * ``` * * @method middleware * @static * @param {Function} register */ static middleware (register) { } /** * The first hook to be executed during the lifecycle of a route. * This hook should generally be used to perform operations on an incoming * request body. As such it makes more sense to use this hook for POSTs, PUTs and PATCHs * rather than GETs and DELETEs. * * @method {Function} deserialize */ deserialize () { } /** * @method beforeModel */ beforeModel () { } /** * @method model */ model () { console.log(`Route '${this.name}' must define a 'model' method`) } /** * @method afterModel * @param {Object} model */ afterModel (model) { } /** * @method serialize * @param {Object} model */ serialize (model) { } /** * @method error * @param {Object} error */ error (error) { return error } /** * The model for the route as returned from the model hook. * Provided for access in later hooks such as `afterModel` or `serialize` * * Example: * ``` * * afterModel () { * this.currentModel.color = 'red' * } * ``` * * @property {Mixed} currentModel */ /** * The name of the route. This is the same as the name of the route js file (without the .js) * and not the name of the exported class. For the name of the class use `this.name` * * @property {String} routeName */ }
JavaScript
0.000001
@@ -3074,309 +3074,8 @@ %7D%0A%0A - /**%0A * The model for the route as returned from the model hook.%0A * Provided for access in later hooks such as %60afterModel%60 or %60serialize%60%0A *%0A * Example:%0A * %60%60%60%0A *%0A * afterModel () %7B%0A * this.currentModel.color = 'red'%0A * %7D%0A * %60%60%60%0A *%0A * @property %7BMixed%7D currentModel%0A */%0A%0A /*
53dc2e279cee360554b2c42a5ec5897e24de78b1
Enable API authentication in production mode
server/boot/authentication.js
server/boot/authentication.js
module.exports = function enableAuthentication(server) { // enable authentication server.enableAuth(); };
JavaScript
0.000001
@@ -56,33 +56,55 @@ %7B%0A -// enable authentication%0A +if (process.env.NODE_ENV === 'production') %7B%0A se @@ -122,11 +122,15 @@ Auth();%0A + %7D%0A %7D;%0A
81a261dd37fff88f4bf958111e94c9b94ecb9a89
update geoFactory
client/components/geoFactory/geoFactory.service.js
client/components/geoFactory/geoFactory.service.js
'use strict'; angular.module('hackshareApp') .factory('geoFactory', function ($rootScope, $http, $q) { // Service logic var geocoder; var map; var infowindow = new google.maps.InfoWindow(); var marker; var initialized = false; function initialize() { geocoder = new google.maps.Geocoder(); var latlng = new google.maps.LatLng(40.730885,-73.997383); var mapOptions = { zoom: 8, center: latlng }; map = new google.maps.Map(document.getElementById("map-canvas"), mapOptions); } // Public API here return { getPosition: function() { return $q(function(resolve, reject) { if(!initialized) initialize(); if (Modernizr.geolocation) { navigator.geolocation.getCurrentPosition(function (position) { console.log("Latitude: " + position.coords.latitude + "\nLongitude: " + position.coords.longitude); $rootScope.location = position; console.log(position); resolve(position); }); } else { // no native support; maybe try a fallback? console.warn('No location support, user must select location manually'); reject(); } }) }, getLocation: function(position) { var latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude); geocoder.geocode({'latLng': latlng}, function(results, status) { if (status == google.maps.GeocoderStatus.OK) { if (results[1]) { console.log(results); map.setZoom(11); marker = new google.maps.Marker({ position: latlng, map: map }); infowindow.setContent(results[1].formatted_address); infowindow.open(map, marker); } } else { alert("Geocoder failed due to: " + status); } }); } }; });
JavaScript
0.000001
@@ -541,16 +541,18 @@ +// map = ne @@ -1608,32 +1608,90 @@ ion(position) %7B%0A + return $q(function(resolve, reject) %7B%0A @@ -1788,32 +1788,36 @@ + geocoder.geocode @@ -1881,24 +1881,28 @@ + + if (status = @@ -1956,24 +1956,28 @@ + if (results%5B @@ -1976,17 +1976,17 @@ results%5B -1 +0 %5D) %7B%0A @@ -2002,42 +2002,8 @@ - console.log(results);%0A @@ -2014,28 +2014,18 @@ - +// map.setZ @@ -2033,16 +2033,20 @@ om(11);%0A + @@ -2131,16 +2131,20 @@ + position @@ -2185,16 +2185,20 @@ + map: map @@ -2218,36 +2218,44 @@ + + %7D);%0A + @@ -2296,17 +2296,17 @@ results%5B -1 +0 %5D.format @@ -2339,32 +2339,38 @@ + // infowindow.open( @@ -2383,16 +2383,70 @@ arker);%0A + resolve(results);%0A @@ -2455,32 +2455,36 @@ %7D%0A + @@ -2488,32 +2488,36 @@ %7D else %7B%0A + @@ -2564,24 +2564,72 @@ + status);%0A + reject(status);%0A @@ -2630,32 +2630,36 @@ %7D%0A + @@ -2654,32 +2654,51 @@ %7D);%0A + %7D)%0A %7D%0A
0b4c6f31ccbfa6a0837984881563c379b11c1cf2
Fix classic JavaScript bug
server/lib/userIntroducer.js
server/lib/userIntroducer.js
// // Copyright 2014 Ilkka Oksanen <[email protected]> // // 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'; const UserGId = require('../models/userGId'); const log = require('./log'); const conf = require('./conf'); const User = require('../models/user'); const nicksService = require('../services/nicks'); const redis = require('./redis').createClient(); const notification = require('../lib/notification'); const networks = [ 'MAS', ...Object.keys(conf.get('irc:networks')) ]; exports.introduce = async function introduce(user, userGId, session) { await introduceUsers(user, [ userGId ], session, null); }; exports.scanAndIntroduce = async function scanAndIntroduce(user, msg, session, socket) { await introduceUsers(user, scanUserGIds(msg), session, socket); }; async function introduceUsers(user, userGIds, session, socket) { if (session) { // If no session is given, force broadcast userGids without remembering them session.knownUserGIds = session.knownUserGIds || {}; } const newUsers = {}; for (const userGId of userGIds) { if (!session || !session.knownUserGIds[userGId.toString()]) { if (session) { session.knownUserGIds[userGId.toString()] = true; } const entry = { nick: {} }; if (userGId.isMASUser) { const foundUser = await User.fetch(userGId.id); entry.name = foundUser.get('name'); entry.gravatar = foundUser.get('emailMD5'); for (const network of networks) { const currentNick = await nicksService.getCurrentNick(foundUser, network); // Fallback to default nick. This solves the situation where the user joins // a new IRC network during the session. In that case his own userGId is in // knownUserGIds table but with null nick for that IRC network. Fallback works // because if the user's nick changes for any reason from the default, that is // communicated separately to the client. entry.nick[network] = currentNick || foundUser.get('nick'); } } else { entry.name = 'IRC User'; entry.gravatar = ''; let nick = await redis.hget(`ircuser:${userGId}`, 'nick'); if (userGId.id === 0) { nick = 'server'; } for (const network of networks) { entry.nick[network] = nick; // shortcut, ircUserId is scoped by network } } newUsers[userGId] = entry; } } if (Object.keys(newUsers).length > 0) { const ntf = { id: 'USERS', mapping: newUsers }; log.info(user, `Emitted USERS ${JSON.stringify(ntf)}`); if (socket) { socket.emit('ntf', ntf); } else if (session) { await notification.send(user, session.id, ntf); } else { await notification.broadcast(user, ntf); } } } function scanUserGIds(msg) { return Object.keys(scan(msg)) .map(userGIdString => UserGId.create(userGIdString)) .filter(userGId => userGId && userGId.valid); } function scan(msg) { const res = {}; Object.keys(msg).forEach(key => { const value = msg[key]; if (typeof value === 'object') { Object.assign(res, scan(value)); } else if (key === 'userId' && value) { res[value] = true; } }); return res; }
JavaScript
0.000018
@@ -4003,16 +4003,34 @@ 'object' + && value !== null ) %7B%0A
30c6893bd91ded7fa38709bcad85c19b64e2e6c7
update bin to remove favoritism
bin/gulp.js
bin/gulp.js
#!/usr/bin/env node var path = require('path'); var argv = require('optimist').argv; var completion = require('../lib/completion'); var semver = require('semver'); if (argv.completion) { return completion(argv.completion); } var resolve = require('resolve'); var findup = require('findup-sync'); var gutil = require('gulp-util'); var prettyTime = require('pretty-hrtime'); var tasks = argv._; var cliPkg = require('../package.json'); var localBaseDir = process.cwd(); loadRequires(argv.require, localBaseDir); var gulpFile = getGulpFile(localBaseDir); // find the local gulp var localGulp = findLocalGulp(gulpFile); var localPkg = findLocalGulpPackage(gulpFile); // print some versions and shit if (argv.v || argv.version) { gutil.log('CLI version', cliPkg.version); if (localGulp) { gutil.log('Local version', localPkg.version); } process.exit(0); } if (!localGulp) { gutil.log(gutil.colors.red('No local gulp install found in'), getLocalBase(gulpFile)); gutil.log(gutil.colors.red('Perhaps do: npm install gulp')); process.exit(1); } // check for semver difference in CLI vs local and warn if CLI > local if (semver.gt(cliPkg.version, localPkg.version)) { gutil.log(gutil.colors.red('CLI Gulp version is higher than the local one')); gutil.log('CLI version', cliPkg.version); gutil.log('Local version', localPkg.version); process.exit(1); } if (!gulpFile) { gutil.log(gutil.colors.red('No Gulpfile found')); process.exit(1); } // Wire up logging for tasks // on local gulp singleton logEvents(localGulp); // Load their gulpfile and run it gutil.log('Using file', gutil.colors.magenta(gulpFile)); loadGulpFile(localGulp, gulpFile, tasks); function loadRequires(requires, baseDir) { if (typeof requires === 'undefined') requires = []; if (!Array.isArray(requires)) requires = [requires]; return requires.map(function(modName){ gutil.log('Requiring external module', gutil.colors.magenta(modName)); var mod = findLocalModule(modName, baseDir); if (typeof mod === 'undefined') { gutil.log('Failed to load external module', gutil.colors.magenta(modName)); } }); } function getLocalBase(gulpFile) { return path.resolve(path.dirname(gulpFile)); } function findLocalGulp(gulpFile){ var baseDir = getLocalBase(gulpFile); return findLocalModule('gulp', baseDir); } function findLocalModule(modName, baseDir){ try { return require(resolve.sync(modName, {basedir: baseDir})); } catch(e) {} return; } function findLocalGulpPackage(gulpFile){ var baseDir = getLocalBase(gulpFile); var packageBase; try { packageBase = path.dirname(resolve.sync('gulp', {basedir: baseDir})); return require(path.join(packageBase, 'package.json')); } catch(e) {} return; } function loadGulpFile(localGulp, gulpFile, tasks){ var gulpFileCwd = path.dirname(gulpFile); process.chdir(gulpFileCwd); gutil.log('Working directory changed to', gutil.colors.magenta(gulpFileCwd)); var theGulpfile = require(gulpFile); // just for good measure process.nextTick(function(){ localGulp.run.apply(localGulp, tasks); }); return theGulpfile; } function getGulpFile(baseDir) { var extensions; if (require.extensions) { extensions = Object.keys(require.extensions).join(','); } else { extensions = ['.js','.coffee']; } var gulpFile = findup('Gulpfile{'+extensions+'}', {nocase: true}); return gulpFile; } // format orchestrator errors function formatError (e) { if (!e.err) return e.message; if (e.err.message) return e.err.message; return JSON.stringify(e.err); } // wire up logging events function logEvents(gulp) { gulp.on('task_start', function(e){ gutil.log('Running', "'"+gutil.colors.cyan(e.task)+"'..."); }); gulp.on('task_stop', function(e){ var time = prettyTime(e.hrDuration); gutil.log('Finished', "'"+gutil.colors.cyan(e.task)+"'", 'in', gutil.colors.magenta(time)); }); gulp.on('task_err', function(e){ var msg = formatError(e); var time = prettyTime(e.hrDuration); gutil.log('Errored', "'"+gutil.colors.cyan(e.task)+"'", 'in', gutil.colors.magenta(time), gutil.colors.red(msg)); }); gulp.on('task_not_found', function(err){ gutil.log(gutil.colors.red("Task '"+err.task+"' was not defined in your gulpfile but you tried to run it.")); gutil.log('Please check the documentation for proper gulpfile formatting.'); process.exit(1); }); }
JavaScript
0
@@ -3307,18 +3307,8 @@ .js' -,'.coffee' %5D;%0A
4ee51720a355351f13b678663643cb35c958b576
Use const instead of var in Vue instance
resources/assets/js/app.js
resources/assets/js/app.js
/** * First we will load all of this project's JavaScript dependencies which * include Vue and Vue Resource. This gives a great starting point for * building robust, powerful web applications using Vue and Laravel. */ require('./bootstrap'); /** * Next, we will create a fresh Vue application instance and attach it to * the body of the page. From here, you may begin adding components to * the application, or feel free to tweak this setup for your needs. */ Vue.component('example', require('./components/Example.vue')); var app = new Vue({ el: 'body' });
JavaScript
0
@@ -533,11 +533,13 @@ );%0A%0A -var +const app
d98c5ab50f71254a3e54227dc0713fdcb66752a4
create build
dist/angular-swiper.js
dist/angular-swiper.js
!function(e,i,t){"use strict";function n(){for(var e=[],i="0123456789abcdef",t=0;36>t;t++)e[t]=i.substr(Math.floor(16*Math.random()),1);e[14]="4",e[19]=i.substr(3&e[19]|8,1),e[8]=e[13]=e[18]=e[23]="-";var n=e.join("");return n}function r(e){return{restrict:"E",transclude:!0,scope:{onReady:"&",slidesPerView:"=",slidesPerColumn:"=",spaceBetween:"=",paginationIsActive:"=",paginationClickable:"=",showNavButtons:"=",loop:"=",autoplay:"=",initialSlide:"=",containerCls:"@",paginationCls:"@",slideCls:"@",direction:"@",swiper:"=",overrideParameters:"="},controller:["$scope","$element",function(e,n){this.buildSwiper=function(){var r={slidesPerView:e.slidesPerView||1,slidesPerColumn:e.slidesPerColumn||1,spaceBetween:e.spaceBetween||0,direction:e.direction||"horizontal",loop:e.loop||!1,initialSlide:e.initialSlide||0,showNavButtons:!1};e.autoplay===!0&&(r=i.extend({},r,{autoplay:!0})),e.paginationIsActive===!0&&(r=i.extend({},r,{paginationClickable:e.paginationClickable||!0,pagination:"#paginator-"+e.swiper_uuid})),e.showNavButtons===!0&&(r.nextButton="#nextButton-"+e.swiper_uuid,r.prevButton="#prevButton-"+e.swiper_uuid),e.overrideParameters&&(r=i.extend({},r,e.overrideParameters));{var o;e.containerCls||""}i.isObject(e.swiper)?(e.swiper=new Swiper(n[0].firstChild,r),o=e.swiper):o=new Swiper(n[0].firstChild,r),e.onReady!==t&&e.onReady({swiper:o})}}],link:function(e,t,r){var o=n();e.swiper_uuid=o;var s="paginator-"+o,a="prevButton-"+o,l="nextButton-"+o;i.element(t[0].querySelector(".swiper-pagination")).attr("id",s),i.element(t[0].querySelector(".swiper-button-next")).attr("id",l),i.element(t[0].querySelector(".swiper-button-prev")).attr("id",a)},template:'<div class="swiper-container {{containerCls}}"><div class="swiper-wrapper" ng-transclude></div><div class="swiper-pagination"></div><div class="swiper-button-next" ng-show="showNavButtons"></div><div class="swiper-button-prev" ng-show="showNavButtons"></div></div>'}}function o(e){return{restrict:"E",require:"^ksSwiperContainer",transclude:!0,template:"<div ng-transclude></div>",replace:!0,link:function(i,t,n,r){i.$last===!0&&e(function(){r.buildSwiper()},0)}}}i.module("ksSwiper",[]).directive("ksSwiperContainer",r).directive("ksSwiperSlide",o),r.$inject=["$log"],o.$inject=["$timeout"]}(window,angular,void 0);
JavaScript
0.000012
@@ -338,24 +338,60 @@ Between:%22=%22, +parallax:%22=%22,parallaxTransition:%22@%22, paginationIs @@ -1223,17 +1223,17 @@ ));%7Bvar -o +a ;e.conta @@ -1305,17 +1305,17 @@ hild,r), -o +a =e.swipe @@ -1317,17 +1317,17 @@ swiper): -o +a =new Swi @@ -1382,17 +1382,17 @@ %7Bswiper: -o +a %7D)%7D%7D%5D,li @@ -1414,17 +1414,17 @@ ,r)%7Bvar -o +a =n();e.s @@ -1434,17 +1434,17 @@ er_uuid= -o +a ;var s=%22 @@ -1459,11 +1459,11 @@ r-%22+ -o,a +a,o =%22pr @@ -1473,17 +1473,17 @@ utton-%22+ -o +a ,l=%22next @@ -1491,17 +1491,17 @@ utton-%22+ -o +a ;i.eleme @@ -1687,17 +1687,17 @@ tr(%22id%22, -a +o )%7D,templ @@ -1749,24 +1749,121 @@ Cls%7D%7D%22%3E%3Cdiv +class=%22parallax-bg%22 data-swiper-parallax=%22%7B%7Bparallax-transition%7D%7D%22 ng-show=%22parallax%22%3E%3C/div%3E%3Cdiv class=%22swipe @@ -1922,16 +1922,34 @@ gination + %7B%7BpaginationCls%7D%7D %22%3E%3C/div%3E @@ -2092,17 +2092,17 @@ unction -o +a (e)%7Bretu @@ -2363,17 +2363,17 @@ rSlide%22, -o +a ),r.$inj @@ -2385,17 +2385,17 @@ %22$log%22%5D, -o +a .$inject
caef599fb389998bc88ac05f0e805863170ba8cf
Update HighfathersMachination.js
src/Parser/Core/Modules/Items/HighfathersMachination.js
src/Parser/Core/Modules/Items/HighfathersMachination.js
import SPELLS from 'common/SPELLS'; import ITEMS from 'common/ITEMS'; import React from 'react'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; class HighfathersMachination extends Analyzer { static dependencies = { combatants: Combatants, }; healing = 0; procUsed = 0; totalProc = 0; on_initialized() { this.active = this.combatants.selected.hasTrinket(ITEMS.HIGHFATHERS_MACHINATION.id); } on_byPlayer_heal(event) { const spellId = event.ability.guid; if (spellId === SPELLS.AMANTHULS_PRESENCEHEAL.id) { this.procUsed++; this.healing += (event.amount || 0) + (event.absorbed || 0); } } on_byPlayer_applybuff(event) { const spellId = event.ability.guid; if (spellId === SPELLS.AMANTHULS_PRESENCEBUFF.id) { this.totalProc++; } } on_byPlayer_applybuffstack(event) { const spellId = event.ability.guid; if (spellId === SPELLS.AMANTHULS_PRESENCEBUFF.id) { this.totalProc++; } } item() { return { item: ITEMS.HIGHFATHERS_MACHINATION, result: ( <dfn data-tip={`The trinket applied a total of ${this.totalProc} healing stacks. ${this.procUsed} stacks were used to heal a total amount of ${this.healing}. ${this.totalProc - this.procUsed} stacks wasted.`}> {this.owner.formatItemHealingDone(this.healing)} </dfn>), }; } } export default HighfathersMachination;
JavaScript
0
@@ -90,16 +90,61 @@ react';%0A +import %7B formatNumber %7D from 'common/format'; %0Aimport @@ -1262,17 +1262,20 @@ stacks. - +%3Cbr%3E $%7Bthis.p @@ -1324,24 +1324,37 @@ amount of $%7B +formatNumber( this.healing @@ -1357,11 +1357,15 @@ ling +) %7D. - +%3Cbr%3E $%7Bth
d88e9822432dbd2c846725026fc49110ebb9db02
Improve unique() function
day3_1.js
day3_1.js
/* Puzzle input - check /input/day3.js */ var input = require('./input/day3.js'); /* Variables */ var santasVisits = [ [ 0, 0 ] ], coordX = 0, coordY = 0; // Function to uniquify an array function unique(array){ var uniqueArray = array; for (var i = 0; i < array.length; i++) { if (uniqueArray.indexOf(array[i] !== -1)) { uniqueArray.splice(i, 1); }; }; return uniqueArray; } // For each character in puzzle input for (var i = 0; i < input.length; i++) { var nextDirection = input[i]; // Adjust coordinates on X and Y axis acoording to the direction characters if (nextDirection === '>') { // to east => X axis + 1 coordX++; } else if (nextDirection === '<') { // to west => X axis - 1 coordX--; } else if (nextDirection === '^') { // to north => Y axis + 1 coordY++; } else if (nextDirection === 'v') { // to south => Y axis - 1 coordY--; } // Store coordination pair var currentLocation = [coordX, coordY]; // ... and push to santasVisits array santasVisits.push(currentLocation); }; // Call unique() function to sort out duplicate visits console.log(unique(santasVisits).length);
JavaScript
0.000183
@@ -235,21 +235,18 @@ Array = -array +%5B%5D ;%0A%0A for @@ -323,17 +323,17 @@ y%5Bi%5D - ! +) = == -1) -) %7B%0A @@ -353,27 +353,29 @@ ray. -splice(i, 1 +push(array%5Bi%5D );%0A %7D ;%0A @@ -374,14 +374,12 @@ %7D -; %0A %7D -; %0A%0A
d4418ab3399cfeff1afb05a602cce7faf6c3b2f2
Update SeparableConv2d_test.js
CNN/SeparableConv2d_test.js
CNN/SeparableConv2d_test.js
var inChannels = 4; var intParams = [ 2, 3, 2, 7, 6, 3 ]; var intDepthwiseFilter = [ 111, 112, 113, 114, 115, 116, 121, 122, 123, 124, 125, 126, 211, 212, 213, 214, 215, 216, 221, 222, 223, 224, 225, 226, 311, 312, 313, 314, 315, 316, 321, 322, 323, 324, 325, 326, 411, 412, 413, 414, 415, 416, 421, 422, 423, 424, 425, 426 ]; var intPointwiseFilter = [ 1151, 1152, 1153, 1154, 1155, 1156, 1157, 1158, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358 ]; var intBias = [ 2171, 2172, 2173 ]; var integerWeights = intParams.concat( intDepthwiseFilter, intPointwiseFilter, intBias ); var encodedWeightBase = 36; var encodedWeightCharCount = 5; var encodedWeights = integerWeights.map( integerWeight => integerWeight.toString(encodedWeightBase).padStart(encodedWeightCharCount, "0") ); var strEncodedWeights = "".concat(...encodedWeights); // For converting to the integer itself. var weightValueOffset = 0; var weightValueDivisor = 1; var theEntities = SeparableConv2d.Layer.StringArrayToSeparableConv2dEntities( strEncodedWeights, encodedWeightCharCount, encodedWeightBase, weightValueOffset, weightValueDivisor ); var entity = theEntities[0]; tf.util.assert( entity.params.filterHeight == intParams[0], `entity.params.filterHeight ${entity.params.filterHeight} != ${intParams[0]}`); tf.util.assert( entity.params.filterWidth == intParams[1], `entity.params.filterWidth ${entity.params.filterWidth} != ${intParams[1]}`); tf.util.assert( entity.params.channelMultiplier == intParams[2], `entity.params.channelMultiplier ${entity.params.channelMultiplier} != ${intParams[2]}`); tf.util.assert( entity.params.dilationHeight == intParams[3], `entity.params.dilationHeight ${entity.params.dilationHeight} != ${intParams[3]}`); tf.util.assert( entity.params.dilationWidth == intParams[4], `entity.params.dilationWidth ${entity.params.dilationWidth} != ${intParams[4]}`); tf.util.assert( entity.params.outChannels == intParams[5], `entity.params.outChannels ${entity.params.outChannels} != ${intParams[5]}`); var theDepthwiseShape = [intParams[0], intParams[1], inChannels, intParams[2]]; tf.util.assert( tf.util.arraysEqual(entity.depthwise.shape, theDepthwiseShape), `entity.depthwise.shape ${entity.depthwise.shape} != ${theDepthwiseShape}`); tf.util.assert( tf.util.arraysEqual(entity.depthwise.filter, intDepthwiseFilter), `entity.depthwise.filter ${entity.depthwise.filter} != ${intDepthwiseFilter}`); var thePointwiseShape = [1, 1, inChannels * intParams[2], intParams[3]]; tf.util.assert( tf.util.arraysEqual(entity.pointwise.shape, thePointwiseShape), `entity.pointwise.shape ${entity.pointwise.shape} != ${thePointwiseShape}`); tf.util.assert( tf.util.arraysEqual(entity.pointwise.filter, intPointwiseFilter), `entity.pointwise.filter ${entity.pointwise.filter} != ${intPointwiseFilter}`); var theBiasShape = [1, 1, intParams[5]]; tf.util.assert( tf.util.arraysEqual(entity.bias.shape, theBiasShape), `entity.bias.shape ${entity.bias.shape} != ${theBiasShape}`); tf.util.assert( tf.util.arraysEqual(entity.bias.filter, intBias), `entity.bias.filter ${entity.bias.filter} != ${intBias}`);
JavaScript
0
@@ -1115,16 +1115,17 @@ (%0A +%5B strEncod @@ -1133,16 +1133,17 @@ dWeights +%5D , encode
400823ce78721769bb07ca7df437e9f6a636b2f9
Add user Settings
server/config/route.config.js
server/config/route.config.js
'use strict'; const controllers = require('../controllers/base.controller'); const csrf = require('csurf') ({ cookie: true }); const auth = { isAuthenticated: (req, res, next) => { if (req.isAuthenticated()) { next(); } else { res.redirect('/'); } }, isInRole: (role) => { return (req, res, next) => { if (req.isAuthenticated() && req.user.roles.indexof(role) > -1) { next(); } else { res.redirect('/'); } } } }; module.exports = (app) => { app .get('/', controllers.home.index) .get('/about', controllers.home.about) .get('/user/register', controllers.user.register) .post('/user/register', controllers.user.create) .get('/user/login', controllers.user.login) .post('/user/login', controllers.user.authenticate) .post('/user/logout', auth.isAuthenticated, controllers.user.logout) .get('/user/profile', csrf, auth.isAuthenticated, controllers.user.showProfile) .post('/user/profile', csrf, auth.isAuthenticated, controllers.user.updateProfile) .get('/developer/portfolio', controllers.portfolio.index) .get('/developer/scope', controllers.scope.index) .get('/error', function(req, res) { res.render('partial/404', { message: "The page was not found", mainTitle: "Error 404", status: "404" }) }) .all('*', (req, res) => { res.redirect('/error'); }) }
JavaScript
0.000003
@@ -1158,32 +1158,159 @@ .updateProfile)%0A + .get('/user/settings', controllers.user.showSettings)%0A .post('/user/settings', controllers.user.updateSettings)%0A .get('/d
657e7209768ed5e41b06054c8a5b789bd12a07d4
Remove custom Table#all implementation
lib/assets/javascripts/monarch/relations/table.js
lib/assets/javascripts/monarch/relations/table.js
(function(Monarch) { Monarch.Relations.Table = new JS.Class('Monarch.Relations.Table', Monarch.Relations.Relation, { initialize: function(recordClass) { this.recordClass = recordClass; this.name = recordClass.displayName; this.remoteName = _.underscoreAndPluralize(recordClass.displayName); this.columnsByName = {}; this.column('id', 'integer'); this.defaultOrderBy('id'); this.activate(); }, column: function(name, type) { return this.columnsByName[name] = new Monarch.Expressions.Column(this, name, type); }, syntheticColumn: function(name, definition) { return this.columnsByName[name] = new Monarch.Expressions.SyntheticColumn(this, name, definition); }, getColumn: function(name) { return this.columnsByName[name]; }, columns: function() { return _.values(this.columnsByName); }, eachColumn: function(f, ctx) { _.each(this.columnsByName, f, ctx); }, defaultOrderBy: function() { var orderByStrings = _.toArray(arguments).concat(['id']); this.orderByExpressions = _.map(orderByStrings, function(orderByString) { return new Monarch.Expressions.OrderBy(this, orderByString); }, this); this._contents = this.buildContents(); }, buildContents: function() { return new Monarch.Util.SkipList(this.buildComparator()); }, all: function() { return this.contents().values(); }, inferJoinColumns: function(columns) { for (var i = 0; i < columns.length; i++) { var name = columns[i].name; var match = name.match(/^(.+)Id$/) if (match && _.camelize(match[1]) === this.name) { return [this.getColumn('id'), columns[i]]; } } }, deactivateIfNeeded: function() { // no-op } }); })(Monarch);
JavaScript
0
@@ -1399,77 +1399,8 @@ %7D,%0A%0A - all: function() %7B%0A return this.contents().values();%0A %7D,%0A%0A
fad04548c801beef1284922be4a914cc9e11ada9
Remove custom UA (see #47)
ice/modules/ice-config.js
ice/modules/ice-config.js
/** * @file Ingress-ICE, configurations * @license MIT */ /*global fs */ /*global quit */ /*global args */ var cookiespath = '.iced_cookies'; var config = configure(args[1]); // Check if no login/password/link provided if (config.login === '' || config.password === '' || config.area === '') { quit('No login/password/area link specified. You need to reconfigure ice:\n - Double-click reconfigure.cmd on Windows;\n - Start ./ingress-ice -r on Linux/Mac OS X/*BSD;'); } var folder = fs.workingDirectory + '/'; var ssnum = 0; if (args[2]) { ssnum = parseInt(args[2], 10); } var configver = (config.SACSID === '' || config.SACSID === undefined) ? 1 : 2; /** * Counter for number of screenshots */ var curnum = 0; /** * Delay between logging in and checking if successful * @default */ var loginTimeout = 10 * 1000; /** * twostep auth trigger */ var twostep = 0; var webpage = require('webpage'); var page = webpage.create(); page.onConsoleMessage = function () {}; page.onError = function () {}; /** * aborting unnecessary API * @since 4.0.0 * @author c2nprds */ page.onResourceRequested = function(requestData, request) { if (requestData.url.match(/(getGameScore|getPlexts|getPortalDetails)/g)) { request.abort(); } }; page.settings.userAgent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.85 Safari/537.36'; /** @function setVieportSize */ if (!config.iitc) { page.viewportSize = { width: config.width + 42, height: config.height + 167 }; } else { page.viewportSize = { width: config.width, height: config.height }; } /** * Parse the configuration .conf file * @since 4.0.0 * @param {String} path */ function configure(path) { var settings = {}; var settingsfile = fs.open(path, 'r'); while(!settingsfile.atEnd()) { var line = settingsfile.readLine(); if (!(line[0] === '#' || line[0] === '[' || line.indexOf('=', 1) === -1)) { var pos = line.indexOf('=', 1); var key = line.substring(0,pos); var value = line.substring(pos + 1); if (value == 'false') { settings[key] = false; } else if (/^-?[\d.]+(?:e-?\d+)?$/.test(value) && value !== '') { settings[key] = parseInt(value, 10); } else { settings[key] = value; } } } settingsfile.close(); return settings; }
JavaScript
0
@@ -1258,16 +1258,18 @@ %7D%0A%7D;%0A%0A +// page.set
a67f2b69996d6356f73ff6729043c1b492d52a42
support new usage format
bin/help.js
bin/help.js
var path = require('path'), fs = require('fs'); fs.existsSync || (fs.existsSync = path.existsSync); var help = function(args, callback) { if (args.length >= 1) { var cmd = args[0], cmdPath = path.join(__dirname, cmd + ".js"); if (fs.existsSync(cmdPath)) { console.log(require(cmdPath).usage); } else { callback("Command '" + cmd + "' not found."); } } else { callback(true); } }; help.usage = "rappidjs help <command>"; module.exports = help;
JavaScript
0.000003
@@ -307,20 +307,20 @@ -console.log( +var usage = requ @@ -337,18 +337,160 @@ h).usage -) ; +%0A%0A if (usage instanceof Function) %7B%0A usage();%0A %7D else %7B%0A console.log(usage);%0A %7D%0A %0A
4964b40009dd9e876df4233a91a7097494c85f8d
Update demo.js
demo/demo.js
demo/demo.js
$(function() { $.getJSON('http://www.bbc.co.uk/bbcone/programmes/schedules/london/today.json', function(data) { console.log(data); $('textarea').html(JSON.stringify(data, null, ' ')); }); });
JavaScript
0.000001
@@ -111,31 +111,8 @@ ) %7B%0A - console.log(data);%0A @@ -174,8 +174,9 @@ %7D);%0A%7D); +%0A
bbc949fb4415aac92b04dbd91935fb044e79a5bc
Save scroll position of the preview mode
javascripts/default.js
javascripts/default.js
var strings = { // Titles "import-button-title-plain" : "Import a text file from your system", "import-button-title-textile" : "Import a Textile file from your system", "import-button-title-markdown" : "Import a Markdown file from your system", // Menus "export-text-plain" : "Text file", "export-text-textile" : "Textile file", "export-text-markdown" : "Markdown file" } $(document).ready(function() { var renderMode = "textile"; $('#language-textile').append(" ✓"); // jQuery uniform controls (http://pixelmatrixdesign.com/uniform) $("select, input:checkbox, input:radio, input:file").uniform(); // Tooltips (http://onehackoranother.com/projects/jquery/tipsy) $('#import-button').tipsy({opacity: 1, trigger: 'manual'}); $('#import-button').bind('mouseenter', function (e) { var allMenus = $('.opener'); // Check if there is a menu opened if (allMenus.filter('.open').length != 0) { // Hide all opened menus but add a class to enable linked menus allMenus.each(function() { hideWindow($(this)); $(this).addClass('menu-link'); }); } $(this).tipsy("show"); }); $('#import-button').bind('mouseleave', function (e) { $(this).tipsy("hide"); }); // Hide all opened menus when clicking anywhere $(document).click( function(e) { var allMenus = $('.opener'); allMenus.each(function() { hideWindow($(this)); }); }); var converter = new Showdown.converter(); // Editor var editor = CodeMirror.fromTextArea('code', { parserfile: ["javascripts/modes/markdown.js", "javascripts/modes/textile.js"], stylesheet: "stylesheets/modes/default.css", basefiles: ["javascripts/codemirror/codemirror_base.js"], textWrapping: true, indentUnit: 4, parserConfig: {'strictErrors': true}, iframeClass: "editor", height: '100%', initCallback: init }); function render(val) { switch(renderMode) { case "plain": val = val.replace(/\r\n|\r|\n/g,"<br />"); // Newlines val = val.replace(/ /g, "&nbsp;&nbsp;"); // Whitespaces $('#paper').html("<p></p>" + val); $('#import-button').attr("title", strings['import-button-title-plain']); $('#export-text').text(strings['export-text-plain']); break; case "textile": editor.setParser('TextileParser'); $('#paper').html(textile(val)); $('#import-button').attr("title", strings['import-button-title-textile']); $('#export-text').text(strings['export-text-textile']); break; case "markdown": editor.setParser('MarkdownParser'); $('#paper').html(converter.makeHtml(val)); $('#import-button').attr("title", strings['import-button-title-markdown']); $('#export-text').text(strings['export-text-markdown']); break; case "latex": break; } } // Switch $('#switch').iphoneSwitch("on", function() { $('.editor').hide(); $('#preview').show(); render(editor.getCode()); $('#preview').css('top', '0px'); $('#preview').focus(); }, function() { $('#preview').hide(); $('.editor').show(); $('.editor').focus(); }, editor.win.document, { switch_path: 'images/switch.png' } ); // Manage click events $('.language').click(function() { $('.language').each(function() { $(this).text($(this).text().replace(' ✓','')); }) $(this).append(" ✓"); switch(this.id) { case "language-plain": renderMode = "plain"; break; case "language-textile": renderMode = "textile"; break; case "language-markdown": renderMode = "markdown"; break; case "language-latex": renderMode = "latex"; break; } render(editor.getCode()); }); $('.editor').hide(); function init() { render($('#code').val()); // Show & hide toolbar $('#toolbar-area').mouseover(function() { $('#toolbar').slideDown('fast'); }); $(editor.win.document).click(function() { setTimeout(function() { $('#toolbar').slideUp('fast'); }, 500); }); $('#preview').click(function() { setTimeout(function() { $('#toolbar').slideUp('fast'); }, 500); }); } });
JavaScript
0
@@ -451,16 +451,37 @@ xtile%22;%0A + var scrollPos = 0;%0A $('#la @@ -3156,27 +3156,131 @@ -%7D,%0A function() %7B + $('#preview').attr(%7B scrollTop: scrollPos %7D);%0A %7D,%0A function() %7B%0A scrollPos = $('#preview').attr('scrollTop');%0A %0A
9e51fb666780a10bc1799a9398ddd1125348e34c
Update guildbot messages
server/services/discord.js
server/services/discord.js
// 3rd const debug = require('debug')('app:services:discord') const assert = require('better-assert') // 1st const Client = require('../discord/client') const config = require('../config') const pre = require('../presenters') // // TODO: DRY up these functions. // TODO: Avoid the #staff-channel lookup on every function call. // //////////////////////////////////////////////////////////// function makeClient () { return new Client({botToken: config.DISCORD_BOT_TOKEN}) } //////////////////////////////////////////////////////////// // nuker and spambot are users exports.broadcastManualNuke = async ({nuker, spambot}) => { assert(nuker) assert(spambot) pre.presentUser(nuker) pre.presentUser(spambot) const client = makeClient() // Find the #staff-only channel const channel = await client.listGuildChannels(config.DISCORD_GUILD_ID) .then((cs) => cs.find((c) => c.name === 'staff-only')) if (!channel) { console.error(`Could not find a #staff-only channel for broadcast.`) return } const content = `@here :hammer: ${nuker.uname} nuked ${config.HOST}${spambot.url} :radioactive:` console.log(content) // Broadcast await client.createMessage(channel.id, { content }) } //////////////////////////////////////////////////////////// // nuker and spambot are users exports.broadcastManualUnnuke = async ({nuker, spambot}) => { assert(nuker) assert(spambot) pre.presentUser(nuker) pre.presentUser(spambot) const client = makeClient() // Find the #staff-only channel const channel = await client.listGuildChannels(config.DISCORD_GUILD_ID) .then((cs) => cs.find((c) => c.name === 'staff-only')) if (!channel) { console.error(`Could not find a #staff-only channel for broadcast.`) return } const content = `@here :white_check_mark: ${nuker.uname} UN-nuked ${config.HOST}${spambot.url}` // Broadcast await client.createMessage(channel.id, { content }) } //////////////////////////////////////////////////////////// // Info is an object of arbitrary data about the analysis // to be sent along with the broadcast for debugging purposes. exports.broadcastAutoNuke = async (user, postId, info) => { assert(user) assert(Number.isInteger(postId)) // Need url pre.presentUser(user) if (!config.IS_DISCORD_CONFIGURED) { console.error(` Called services.discord.js#broadcastAutoNuke but Discord is not configured. `) return } const client = makeClient() // Find the #staff-only channel const channel = await client.listGuildChannels(config.DISCORD_GUILD_ID) .then((cs) => cs.find((c) => c.name === 'staff-only')) if (!channel) { console.error(`Could not find a #staff-only channel for broadcast.`) return } const content = `@here :robot: User ${config.HOST}${user.url} was auto-nuked for this post: ${config.HOST}/posts/${postId} :radioactive: \`\`\` ${JSON.stringify(info, null, 2)} \`\`\` `.trim() // Broadcast await client.createMessage(channel.id, { content }) } //////////////////////////////////////////////////////////// exports.broadcastUserJoin = async (user) => { // Need url pre.presentUser(user) if (!config.IS_DISCORD_CONFIGURED) { console.error(` Called services.discord.js#broadcastUserJoin but Discord is not configured. `) return } const client = makeClient() // Find the #staff-only channel const channel = await client.listGuildChannels(config.DISCORD_GUILD_ID) .then((cs) => cs.find((c) => c.name === 'staff-only')) if (!channel) { console.error(`Could not find a #staff-only channel for broadcast.`) return } // Broadcast await client.createMessage(channel.id, { content: `@here :baby: A new user joined: ${config.HOST}${user.url}` }) } //////////////////////////////////////////////////////////// exports.broadcastIntroTopic = async (user, topic) => { // Need url pre.presentUser(user) pre.presentTopic(topic) const client = makeClient() const channel = await client.listGuildChannels(config.DISCORD_GUILD_ID) .then((cs) => cs.find((c) => c.name === 'general')) if (!channel) { console.error(`Could not find a #general channel for broadcast.`) return } // Broadcast await client.createMessage(channel.id, { content: `Howdy, :wave: ${user.uname} created an Introduce Yourself thread: ${config.HOST}${topic.url}. Please help us welcome them!` }) }
JavaScript
0
@@ -1054,16 +1054,18 @@ hammer: +** $%7Bnuker. @@ -1070,16 +1070,18 @@ r.uname%7D +** nuked $ @@ -1812,16 +1812,18 @@ k_mark: +** $%7Bnuker. @@ -1828,16 +1828,18 @@ r.uname%7D +** UN-nuke @@ -4319,16 +4319,18 @@ :wave: +** $%7Buser.u @@ -4334,16 +4334,18 @@ r.uname%7D +** created
63669ea4d0a2b23157275e7f7869e24f0dee96df
Convert to Glimmer component
ember/app/components/cesium-button.js
ember/app/components/cesium-button.js
import Component from '@ember/component'; import { action } from '@ember/object'; export default class CesiumButton extends Component { tagName = ''; @action toggle() { if (this.enabled) { this.onDisable(); } else { this.onEnable(); } } }
JavaScript
0.998266
@@ -1,24 +1,25 @@ import -Component +%7B action %7D from '@ @@ -28,56 +28,58 @@ ber/ -componen +objec t';%0A +%0A import -%7B action %7D from '@ember/objec +Component from '@glimmer/componen t';%0A @@ -137,25 +137,8 @@ t %7B%0A - tagName = '';%0A%0A @a @@ -167,16 +167,21 @@ f (this. +args. enabled) @@ -194,16 +194,21 @@ this. +args. onDisabl @@ -236,16 +236,21 @@ this. +args. onEnable
fc4480cbd9d3bfabc9cc471270a4ce9399b21d35
Fix minification errors in confEditor
app/js/arethusa.conf_editor/routes/conf_editor.js
app/js/arethusa.conf_editor/routes/conf_editor.js
'use strict'; angular.module('arethusa.core').constant('CONF_ROUTE', { controller: 'ConfEditorCtrl', templateUrl: 'templates/conf_editor.html', resolve: { load: function ($http, configurator) { var url = './static/configs/conf_editor/1.json'; return $http.get(url).then(function (res) { configurator.defineConfiguration(res.data, url); }); } } });
JavaScript
0.000038
@@ -163,16 +163,42 @@ load: + %5B'$http', 'configurator', functio @@ -400,16 +400,17 @@ );%0A %7D +%5D %0A %7D%0A%7D);
74eb1b52dc7cf61fd12ddcc989d87f3d1f14822a
Update isAtonement.js
src/Parser/DisciplinePriest/Modules/Core/isAtonement.js
src/Parser/DisciplinePriest/Modules/Core/isAtonement.js
import SPELLS from 'common/SPELLS'; export default function isAtonement(event) { return [SPELLS.ATONEMENT_HEAL_NON_CRIT.id, SPELLS.ATONEMENT_HEAL_CRIT.id].indexOf(event.ability.guid) > -1; }
JavaScript
0.000001
@@ -183,9 +183,11 @@ id) -%3E +!== -1;
c57a6f8d0cccdbbe184a1f69960e4b61404865b4
improve console tools
bin/i18n.js
bin/i18n.js
"use strict"; const fs = require('fs'); const logger = require('./logger'); const google = require('./google'); let items = require('./../src/data/items.json'); function sort(object) { let keys = Object.keys(object), result = {}; keys.sort((a, b) => { if (a === b) { return 0; } return a > b ? 1 : -1; }); keys.map((key) => { result[key] = object[key]; }); return result; } const i18nExport = function (args = {}) { if (!args['l'] || typeof args['l'] !== 'string') { logger.fatal('language is missing'); } let i18n = `./../src/i18n/${args['l']}.json`, template = `INFORMATION\tTRANSLATION\tKEY\n`, tsv = { items: template, events: template, heroes: template, interface: template, }; if (!fs.existsSync(i18n)) { logger.fatal(`'${i18n}' does not exists`); } i18n = require(i18n); for (let i in i18n) if (i18n.hasOwnProperty(i)) { if (i === 'items') { Object.values(items).map((item) => { tsv[i] += [ `${(item.hero ? `${item.hero} ` : '')}${item.type} ${item.name}`, `${i18n[i][item.uid]}`, `${item.uid}`, ].join('\t') + '\n'; }); } else { Object.keys(i18n[i]).map((key) => { tsv[i] += [ 'INFORMATION', i18n[i][key].replace(/(\n)+/g, ' '), key, ].join('\t') + '\n'; }); } fs.writeFileSync(`./${args['l']}.${i}.tsv`, tsv[i]); logger.success(`'./${args['l']}.${i}.tsv' created`); } }; const i18nImport = function (args = {}) { if (!args['t'] || typeof args['t'] !== 'string') { logger.fatal('type is missing'); } if (!args['l'] || typeof args['l'] !== 'string') { logger.fatal('language is missing'); } if (!args['f'] || typeof args['f'] !== 'string') { logger.fatal('tsv file is missing'); } if (!fs.existsSync(args['f'])) { logger.fatal(`'${args['f']}' does not exists`); } let path = `./../src/i18n/${args['l']}.json`, i18n, addedCount = 0, updatedCount = 0; if (!fs.existsSync(path)) { logger.warn(`'${path}' does not exists and will be created`); i18n = {}; } else { i18n = require(path); } fs.readFileSync(args['f'], 'utf-8').split('\n').map((line, index) => { if (index === 0) { return; } if (!i18n.hasOwnProperty(args['t'])) { i18n[args['t']] = {}; } line = line.split('\t'); if (line.length < 3) { return; } line[2] = line[2].replace('\r', ''); if (!i18n[args['t']][line[2]]) { addedCount++; i18n[args['t']][line[2]] = line[1]; } else if (i18n[args['t']][line[2]] !== line[1]) { updatedCount++; i18n[args['t']][line[2]] = line[1]; } }); if (addedCount === 0 && updatedCount === 0) { logger.info('nothing to update'); } else { if (['interface', 'heroes',].indexOf(args['t']) !== -1) { i18n[args['t']] = sort(i18n[args['t']]); } fs.writeFileSync(path, JSON.stringify(i18n, null, 2)); if (addedCount) { logger.success(`${addedCount} item(s) added`); } if (updatedCount) { logger.success(`${updatedCount} item(s) updated`); } } }; const i18nSync = function (args = {}) { google.getTranslations().then((translations) => { for (let i in translations) if (translations.hasOwnProperty(i)) { for (let j in translations[i]) if (translations[i].hasOwnProperty(j)) { if (['interface', 'heroes',].indexOf(j.toLowerCase()) !== -1) { translations[i][j] = sort(translations[i][j]); } } fs.writeFileSync( `./../src/i18n/${i}.json`, JSON.stringify(translations[i], null, 2) ); } }).catch(logger.fatal); }; const i18nSet = function (args = {}) { if (!args['k'] || typeof args['k'] !== 'string') { logger.fatal('key is missing'); } if (!args['v'] || typeof args['v'] !== 'string') { logger.fatal('value is missing'); } let i18n; fs.readdirSync(`./../src/i18n/`).map((file) => { if (file.match(/[a-z]{2}_[A-Z]{2}\.json/)) { i18n = require(`./../src/i18n/${file}`); if (!i18n.hasOwnProperty('interface')) { i18n.interface = {}; } i18n.interface[args['k']] = args['v']; i18n.interface = sort(i18n.interface); fs.writeFileSync(`./../src/i18n/${file}`, JSON.stringify(i18n, null, 2)); } }); logger.success(`${args['k']} setted to "${args['v']}"`); }; const i18nRemove = function (args = {}) { if (!args['k'] || typeof args['k'] !== 'string') { logger.fatal('key is missing'); } let i18n; fs.readdirSync(`./../src/i18n/`).map((file) => { if (file.match(/[a-z]{2}_[A-Z]{2}\.json/)) { i18n = require(`./../src/i18n/${file}`); if (!i18n.hasOwnProperty('interface') || !i18n.interface[args['k']]) { logger.warn(`${args['k']} not found in '${file}'`); } delete i18n.interface[args['k']]; i18n.interface = sort(i18n.interface); fs.writeFileSync(`./../src/i18n/${file}`, JSON.stringify(i18n, null, 2)); } }); logger.success(`${args['k']} deleted`); }; module.exports = { export: i18nExport, import: i18nImport, sync: i18nSync, set: i18nSet, remove: i18nRemove, };
JavaScript
0.000003
@@ -4246,16 +4246,66 @@ ); +%0A%0A logger.success(%60$%7Bi%7D synchronized%60); %0A
e1f17426e3e097d1c5e30825087c0405cc7de64f
fix typo in comment
packages/lesswrong/lib/index.js
packages/lesswrong/lib/index.js
import './collections/subscription_fields.js'; // Notifications import Notifications from './collections/notifications/collection.js'; import './collections/notifications/custom_fields.js'; import './collections/notifications/views.js'; // Inbox import Messages from './collections/messages/collection.js' import './collections/messages/views.js'; import Conversations from './collections/conversations/collection.js' import './collections/conversations/views.js'; // Subscriptions import './subscriptions/mutations.js'; import './subscriptions/permissions.js'; // Posts import './collections/posts/custom_fields.js'; import './collections/posts/views.js'; // Commensts import './collections/comments/custom_fields.js'; // Internationalization import './i18n-en-us/en_US.js'; // General import './modules/fragments.js'; import './modules/callbacks.js'; import './helpers.js' import './components.js'; import './routes.js'; import './views.js'; export { Conversations, Messages, Notifications }
JavaScript
0.001377
@@ -667,17 +667,16 @@ / Commen -s ts%0Aimpor
935b5c8fefe7644756c6051be669a9b612bc2c54
use event delegation
public/js/common.js
public/js/common.js
// Ugis Germanis // My javascript var music = { selected: "byartist", sort: new Event('sort'), playlist: null, request: new XMLHttpRequest(), url: document.location.protocol+ "//"+ window.location.host, current: 0, slider: null, sliderDrag: false, render: function(){ $("#playlist").empty(); for (i=0; i<this.playlist.length; i++) { $("#playlist").append("<li class='song'></li>"); $(".song").last().attr('id', "sound"+i); $(".song").last().attr('index', i); $(".song").last().append(this.playlist[i].Title+ " - "+ this.playlist[i].Artist); document.getElementById("sound"+i).addEventListener('click', function(e){ music.current= e.target.getAttribute("index"); playSong(music.current); }); } }, }; music.request.onloadend = function(){ if (this.readyState = 4 && this.status == 200) { music.playlist = JSON.parse(this.responseText); $("#playlist").attr('loading', true); music.render(); $("#playlist").attr('loading', false); } } document.addEventListener("sort", function(e){ console.log("sort event: ", music.selected); music.request.open("GET", music.url + "/api?sort=" + music.selected); music.request.send(); }, false) window.addEventListener('WebComponentsReady', function(e) { console.log('webcomponents are ready!!!'); //Init the default music.slider = document.getElementById("slider"); slider.addEventListener("mousedown", function(){ music.sliderDrag = true; }); slider.addEventListener("mouseup", function(){ music.sliderDrag = false; }); slider.addEventListener("change", function(e){ var estimate = soundManager.getSoundById("sound"+music.current).durationEstimate; soundManager.getSoundById("sound"+music.current).setPosition((estimate/1000) * e.target.value); music.sliderDrag = false; }); document.getElementById(music.selected).active=true; document.dispatchEvent(music.sort); //Nifty button stuff var sorter = document.getElementsByClassName("sorter"); for (i=0; i< sorter.length; i++) { sorter[i].addEventListener("change", function(e){ for(j=0; j<sorter.length; j++){ if (sorter[j].id == e.target.id) { continue } sorter[j].active=false; } e.target.active=true; if (music.selected == e.target.id){ return } music.selected = e.target.id document.dispatchEvent(music.sort); }, false); } }); function playSong(id){ soundManager.stopAll(); soundManager.createSound({ id: "sound"+id, url: music.url+ "/stream?id="+ music.playlist[id].ID, multiShot:false, onfinish: function() { if (music.current == (music.playlist.length - 1)) { music.current = 0; } else { music.current++; } playSong(music.current); $("#sound"+id).attr("playing", false); this.destruct(); }, onstop: function(){ $("#sound"+id).attr("playing", false); this.destruct(); }, whileplaying: function(){ if (music.sliderDrag == false){ music.slider.value = (this.position / this.durationEstimate) * 1000; } }, }); $("#sound"+id).attr("playing", true); soundManager.play("sound"+id); document.getElementsByTagName("body")[0].style.backgroundImage = "url("+music.url+"/art?id="+music.playlist[id].ID+")"; } function playnext(){ if (music.current == (music.playlist.length - 1)) { music.current = 0; } else { music.current++; } playSong(music.current); } function playprevious(){ if (music.current == 0) { music.current = music.playlist.length - 1 } else { music.current--; } playSong(music.current); } function play(){ if (soundManager.getSoundById("sound"+music.current) === undefined){ playSong(music.current); } else { soundManager.getSoundById("sound"+music.current).resume(); } } function pause(){ soundManager.getSoundById("sound"+music.current).pause(); }
JavaScript
0.000002
@@ -631,32 +631,38 @@ i%5D.Artist);%0A + %7D%0A document @@ -678,24 +678,25 @@ ntById(%22 -sound%22+i +playlist%22 ).addEve @@ -720,32 +720,96 @@ ', function(e)%7B%0A + if(e.target && e.target.nodeName == %22LI%22) %7B%0A @@ -863,32 +863,36 @@ + + playSong(music.c @@ -908,27 +908,29 @@ -%7D); + %7D %0A %7D%0A @@ -923,24 +923,26 @@ %7D%0A %7D +); %0A %7D,%0A%7D;%0A%0A
9ce2991579a2770af04d9cf58d7fd679b8a61956
change 'get' to 'value'
src/decoratorFactory.js
src/decoratorFactory.js
'use strict'; import { forOwn, isFunction, partial } from 'lodash'; import settings from './settings'; const TYPE_MAP = { // Methods where the function is the last argument or the first // and all other arguments come before or after. post: (fn, target, value, ...args) => fn(...args, value), pre: (fn, target, value, ...args) => fn(value, ...args), // Partials are slightly different. They partial an existing function // on the object referenced by string name. partial: (fn, target, value, ...args) => fn(resolveFunction(args[0], target), ...args.slice(1)), // Wrap is a different case since the original function value // needs to be given to the wrap method. wrap: (fn, target, value, ...args) => fn(resolveFunction(args[0], target), value), replace: (fn, target, value, ...args) => fn(...args), // Calls the function with key functions and the value compose: (fn, target, value, ...args) => fn(value, ...args.map(method => resolveFunction(method, target))), partialed: (fn, target, value, ...args) => partial(fn, value, ...args) }; TYPE_MAP.single = TYPE_MAP.pre; function resolveFunction(method, target) { return isFunction(method) ? method : target[method]; } function isGetter(getter) { return Boolean(getter[`${settings.annotationPrefix}isGetter`]); } /** * Used to copy over meta data from function to function. * If meta data is attached to a function. This can get lost * when wrapping functions. This tries to persist that. */ function copyMetaData(from, to) { forOwn(from, (value, key) => to[key] = from[key]); } /** * Creates a generic decorator for a method on an object. * * @param {Object} root The root object the method resides on. * @param {String} method The method. * @param {String} [type=post] How to wrap the function. * @returns {Function} Decorator function */ function createDecorator(root, method, type = 'pre') { return type === 'single' ? wrapper() : wrapper; function wrapper(...args) { return function decorator(target, name, descriptor) { const { value, get } = descriptor; if (get) { const toWrap = isGetter(get) ? get : get.call(this); descriptor.get = TYPE_MAP[type](root[method], target, toWrap, ...args); copyMetaData(toWrap, descriptor.get); } else if (value) { descriptor.value = TYPE_MAP[type](root[method], target, value, ...args); copyMetaData(value, descriptor.get); } return descriptor; }; }; } function createInstanceDecorator(root, method, type = 'pre') { return type === 'single' ? wrapper() : wrapper; function wrapper(...args) { return function decorator(target, name, descriptor) { const { value, get } = descriptor; const action = TYPE_MAP[type]; const getterAnnotation = `${settings.annotationPrefix}isGetter`; if (get) { copyMetaData(get, getter); } return { get: getter, configurable: true }; function getter() { const isGetter = Boolean(getter[getterAnnotation]); const newDescriptor = { configurable: true }; if (isFunction(get)) { const toWrap = isGetter ? get : get.call(this); newDescriptor.get = action(root[method], this, toWrap, ...args); copyMetaData(toWrap, newDescriptor.get); Object.defineProperty(this, name, newDescriptor); return isGetter ? newDescriptor.get() : newDescriptor.get; } newDescriptor.value = action(root[method], this, value, ...args); copyMetaData(value, newDescriptor.value); Object.defineProperty(this, name, newDescriptor); return newDescriptor.value; } }; }; } export default { createDecorator, createInstanceDecorator, copyMetaData };
JavaScript
0
@@ -2417,35 +2417,37 @@ lue, descriptor. -get +value );%0A %7D%0A%0A
3d14fbc40ba3de9c47f5604f55999958aedff3af
Delete failed server backup attempts
server/src/cron/backups.js
server/src/cron/backups.js
// @flow import fs from 'fs'; import childProcess from 'child_process'; import zlib from 'zlib'; import dateFormat from 'dateformat'; import StreamCache from 'stream-cache'; import { promisify } from 'util'; import invariant from 'invariant'; import dbConfig from '../../secrets/db_config'; const readdir = promisify(fs.readdir); const lstat = promisify(fs.lstat); const unlink = promisify(fs.unlink); let importedBackupConfig = undefined; async function importBackupConfig() { if (importedBackupConfig !== undefined) { return importedBackupConfig; } try { // $FlowFixMe const backupExports = await import('../../facts/backups'); if (importedBackupConfig === undefined) { importedBackupConfig = backupExports.default; } } catch { if (importedBackupConfig === undefined) { importedBackupConfig = null; } } return importedBackupConfig; } async function backupDB() { const backupConfig = await importBackupConfig(); if (!backupConfig || !backupConfig.enabled) { return; } const mysqlDump = childProcess.spawn( 'mysqldump', ['-u', dbConfig.user, `-p${dbConfig.password}`, dbConfig.database], { stdio: ['ignore', 'pipe', 'ignore'], }, ); const cache = new StreamCache(); mysqlDump.stdout.pipe(zlib.createGzip()).pipe(cache); const dateString = dateFormat('yyyy-mm-dd-HH:MM'); const filename = `${backupConfig.directory}/squadcal.${dateString}.sql.gz`; await saveBackup(filename, cache); } async function saveBackup( filePath: string, cache: StreamCache, retries: number = 2, ): Promise<void> { try { await trySaveBackup(filePath, cache); } catch (e) { if (e.code !== 'ENOSPC') { throw e; } if (!retries) { throw e; } await deleteOldestBackup(); await saveBackup(filePath, cache, retries - 1); } } function trySaveBackup(filePath: string, cache: StreamCache): Promise<void> { const writeStream = fs.createWriteStream(filePath); return new Promise((resolve, reject) => { cache .pipe(writeStream) .on('finish', resolve) .on('error', reject); }); } async function deleteOldestBackup() { const backupConfig = await importBackupConfig(); invariant(backupConfig, 'backupConfig should be non-null'); const files = await readdir(backupConfig.directory); let oldestFile; for (let file of files) { if (!file.endsWith('.sql.gz') || !file.startsWith('squadcal.')) { continue; } const stat = await lstat(`${backupConfig.directory}/${file}`); if (stat.isDirectory()) { continue; } if (!oldestFile || stat.mtime < oldestFile.mtime) { oldestFile = { file, mtime: stat.mtime }; } } if (!oldestFile) { return; } try { await unlink(`${backupConfig.directory}/${oldestFile.file}`); } catch (e) { // Check if it's already been deleted if (e.code !== 'ENOENT') { throw e; } } } export { backupDB };
JavaScript
0
@@ -1444,16 +1444,26 @@ l.gz%60;%0A%0A + try %7B%0A await @@ -1491,16 +1491,64 @@ cache);%0A + %7D catch (e) %7B%0A await unlink(filename);%0A %7D%0A %7D%0A%0Aasync
883933783e513b0a5d5b24293d1dc92ef585d587
fix data not available
server/util/wolframHelper.js
server/util/wolframHelper.js
import wajs from 'wajs'; import secrets from '../../secrets'; export const WA_APP_ID = secrets.wolframAlphaId; export const waClient = new wajs(WA_APP_ID); export const QUERY_OPTIONS = { format: 'plaintext', podState: '100@More', ignoreCase: true, // includePodId: ['Result'] }; export const formatQuery = (query) => query //`list of ${query}`; export const formatResponse = (response) => { if (!response.pods()[1]){ console.log('no results? ', response) return false; } let queryString = response.pods()[1].subpod[0].plaintext[0]; console.log('querystring', queryString) const totalIndex = queryString.indexOf('(total:'); if (totalIndex > -1) { queryString = queryString.substring(0, totalIndex); } queryString = queryString.trim(); let resultArray = queryString.split(' | '); if (resultArray.length === 1) { resultArray = queryString.split('\n'); } return resultArray; }
JavaScript
0.000002
@@ -428,50 +428,8 @@ %5D)%7B%0A - console.log('no results? ', response)%0A @@ -551,16 +551,85 @@ String)%0A + if (queryString === '(data not available)')%7B%0A return false;%0A %7D%0A const
277bf5926d17b1f56a89ee5d665bcd21be540e77
Fix typo in test
test/tests/integration/providers/github-oauth2-test.js
test/tests/integration/providers/github-oauth2-test.js
var torii, container; import toriiContainer from 'test/helpers/torii-container'; import configuration from 'torii/configuration'; var originalConfiguration = configuration.providers['github-oauth2']; var opened, mockPopup = { open: function(){ opened = true; return Ember.RSVP.resolve({}); } }; module('Github - Integration', { setup: function(){ container = toriiContainer(); container.register('torii-service:mock-popup', mockPopup, {instantiate: false}); container.injection('torii-provider', 'popup', 'torii-service:mock-popup'); torii = container.lookup("torii:main"); configuration.providers['github-oauth2'] = {apiKey: 'dummy'}; }, teardown: function(){ opened = false; configuration.providers['github-oauth2'] = originalConfiguration; Ember.run(container, 'destroy'); } }); test("Opens a popup to Google", function(){ Ember.run(function(){ torii.open('github-oauth2').finally(function(){ ok(opened, "Popup service is opened"); }); }); });
JavaScript
0.020738
@@ -861,13 +861,13 @@ to G -oogle +itHub %22, f
a1ef57a4023b39e250d9ffd0bcc31e488af3a762
fix "Skip to Content" link
app/jsx/runOnEveryPageButDontBlockAnythingElse.js
app/jsx/runOnEveryPageButDontBlockAnythingElse.js
/* * Copyright (C) 2019 - present Instructure, Inc. * * This file is part of Canvas. * * Canvas is free software: you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License as published by the Free * Software Foundation, version 3 of the License. * * Canvas is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU Affero General Public License for more * details. * * You should have received a copy of the GNU Affero General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ // code in this file is stuff that needs to run on every page but that should // not block anything else from loading. It will be loaded by webpack as an // async chunk so it will always be loaded eventually, but not necessarily before // any other js_bundle code runs. and by moving it into an async chunk, // the critical code to display a page will be executed sooner import _ from 'underscore' import $ from 'jquery' import updateSubnavMenuToggle from './subnav_menu/updateSubnavMenuToggle' import preventDefault from 'compiled/fn/preventDefault' // modules that do their own thing on every page that simply need to be required import 'media_comments' import 'reminders' import 'instructure' import 'page_views' import 'compiled/behaviors/authenticity_token' import 'compiled/behaviors/ujsLinks' import 'compiled/behaviors/admin-links' import 'compiled/behaviors/elementToggler' import 'compiled/behaviors/ic-super-toggle' import 'compiled/behaviors/instructure_inline_media_comment' import 'compiled/behaviors/ping' import 'compiled/behaviors/broken-images' import 'LtiThumbnailLauncher' // preventDefault so we dont change the hash // this will make nested apps that use the hash happy $('#skip_navigation_link').on( 'click', preventDefault(() => { $($(this).attr('href')) .attr('tabindex', -1) .focus() }) ) // show and hide the courses vertical menu when the user clicks the hamburger button // This was in the courses bundle, but it sometimes needs to work in places that don't // load that bundle. const WIDE_BREAKPOINT = 1200 function resetMenuItemTabIndexes() { // in testing this, it seems that $(document).width() returns 15px less than what it should. const tabIndex = $('body').hasClass('course-menu-expanded') || $(document).width() >= WIDE_BREAKPOINT - 15 ? 0 : -1 $('#section-tabs li a').attr('tabIndex', tabIndex) } $(resetMenuItemTabIndexes) $(window).on('resize', _.debounce(resetMenuItemTabIndexes, 50)) $('body').on('click', '#courseMenuToggle', () => { $('body').toggleClass('course-menu-expanded') updateSubnavMenuToggle() $('#left-side').css({ display: $('body').hasClass('course-menu-expanded') ? 'block' : 'none' }) resetMenuItemTabIndexes() })
JavaScript
0.000005
@@ -1947,21 +1947,27 @@ Default( -() =%3E +function () %7B%0A $
6a0b6034a0d8cb24b78ea1ce0d9d94d8320fb545
Update testsA.js
nodejs_app/testsA.js
nodejs_app/testsA.js
var t = 0; const exec = require('child_process').exec; exec('node nodejs_app/app.js', function(error, stdout, stderr){ if (error) { console.error('exec error: ${error}'); t =1; return 1; } else{ console.log('stdout: ${stdout}'); console.log('stderr: ${stderr}'); return 0; } }); exec('node nodejs_app/app.js', function(error, stdout, stderr){ if (error) { console.error('exec error: ${error}'+error); t =1; exec('killall node'); return 1; } else{ console.log('stdout: ${stdout}'); console.log('stderr: ${stderr}'); return 0; } });
JavaScript
0.000001
@@ -1,8 +1,9 @@ +%0A var t = @@ -459,33 +459,33 @@ e');%0A return -1 +0 ;%0A %7D%0A else%7B%0A%09 %0A @@ -560,26 +560,26 @@ ');%0A%09 %0A return -0 +1 ;%0A %7D%0A%7D);%0A
b7778d950ef59cd0b4d55e034c2bcfccbaf47434
test in safari a bit; clean up var names
www/javascript/dogeared.document.js
www/javascript/dogeared.document.js
// https://developer.mozilla.org/en-US/docs/Web/API/window.getSelection var wtf = ""; function dogeared_document_init(){ $(document).bind('mouseup', dogeared_document_onselected); // This does not work well at all yet (20140503/straup) // http://stackoverflow.com/questions/8991511/how-to-bind-a-handler-to-a-selection-change-on-window $(document).bind('selectionchange', dogeared_document_onselected); } function dogeared_document_onselected(e){ // console.log(e.type); var target = e.target; if (target.nodeName == 'BUTTON'){ dogeared_document_add_highlight(); return; } $(".highlight").remove(); var sel = window.getSelection(); var txt = sel.toString(); if (txt == ""){ return; } if (txt == current_selection){ return; } current_selection = txt; // http://stackoverflow.com/questions/3597116/insert-html-after-a-selection range = window.getSelection().getRangeAt(0); expandedSelRange = range.cloneRange(); range.collapse(false); var el = document.createElement("div"); el.innerHTML = "<span class=\"highlight\"> <button id=\"highlight\" class=\"btn btn-sm\">Highlight</button> </span>"; var frag = document.createDocumentFragment(), node, lastNode; while ((node = el.firstChild)){ lastNode = frag.appendChild(node); } range.insertNode(frag); // this causes the highlight button to be hidden in iOS... if (lastNode){ expandedSelRange.setEndAfter(lastNode.previousSibling); sel.removeAllRanges(); sel.addRange(expandedSelRange); } } function dogeared_document_add_highlight(){ var doc = $("#document"); var id = doc.attr("data-document-id"); var s = window.getSelection(); var t = s.toString(); // This requires grabbing 'current_selection' in ios var method = 'dogeared.highlights.addHighlight'; var args = { 'document_id': id, 'text': t }; console.log(args); // TO DO: something... var on_success = function(rsp){ console.log(rsp); }; dogeared_api_call(method, args, on_success); }
JavaScript
0
@@ -74,11 +74,25 @@ var -wtf +current_selection = %22 @@ -359,24 +359,27 @@ -window%0A%0A + // $(document) @@ -476,24 +476,91 @@ lected(e)%7B%0A%0A + // selection change is triggered on desktop safari because...%0A%0A // conso
19851926742154a189cc1571b04f8eb78e275cd6
Fix event emiter example
event-driven/event-emitter-demo-00.js
event-driven/event-emitter-demo-00.js
var events = require('events'); var eventEmitter = new events.EventEmitter(); var ringBell = function () { console.log('ring ring ring'); }; eventEmitter.on('doorOpen1', ringBell); eventEmitter.on('doorOpen2', function (ring) { console.log(ring); }); eventEmitter.emit('doorOpen1'); //No needed the second argument. eventEmitter.emit('doorOpen2', 'rong rong rong rong'); //We just pass the arguments in the emit() method.
JavaScript
0.000003
@@ -256,73 +256,145 @@ );%0A%0A -eventEmitter.emit('doorOpen1'); //No needed the second argument.%0A +// Here no needed the second argument.%0AeventEmitter.emit('doorOpen1');%0A%0A// Here we need to pass the second argument in the emit() method. %0Aeve @@ -448,55 +448,4 @@ g'); - //We just pass the arguments in the emit() method.
abcea73890e6f99b3548a8fedb5376ecbd103902
fix networkhandler
lib/businessTier/networkHandler/networkHandler.js
lib/businessTier/networkHandler/networkHandler.js
/*jshint node: true, -W106 */ 'use strict'; /* * Name : networkHandler.js * Module : NetworkHandler * Location : /lib/businessTier/networkHandler * * History : * * Version Date Programmer Description * ========================================================= * 0.0.1 2015-05-19 Matteo Furlan Initial code * ========================================================= */ var Socket=require('../../presentationTier/socket.js'); var Routes=require('../../presentationTier/routes.js'); function NetworkHandler(app,io,norrisNamespace){ if(app===undefined || io===undefined || norrisNamespace===undefined || typeof app !== 'function' || app.lazyrouter===undefined || typeof io !== 'object' || io.nsps===undefined || typeof norrisNamespace !== 'string' || norrisNamespace.length<2 || norrisNamespace.indexOf('/')!==0 ){ console.log('Error: 811'); return; } this._app = app; this._io=io; this._norrisNamespace=norrisNamespace; this._routes=new Routes(this._app,this._norrisNamespace); this._routes.addRoutingPath(this._norrisNamespace,'pageList'); //page is pageList.ejs; } NetworkHandler.prototype.addPageToRouting = function(namespacePage) { if(typeof namespacePage !== 'string' || namespacePage.length<2 || namespacePage.indexOf('/')!==0){ return false; } return this._routes.addRoutingPath(namespacePage,'page'); //page is page.ejs; }; NetworkHandler.prototype.createSocket = function(namespace,attachedObject) { var sock=new Socket(this._io,namespace); sock.attachedObject(attachedObject,'configPageList'); return sock; }; module.exports = NetworkHandler;
JavaScript
0.000001
@@ -1506,26 +1506,24 @@ %09sock.attach -ed Object(attac
d62927cb890746646dc87938bb21206098799643
Remove unused cycleId
server/reports/playerStats.js
server/reports/playerStats.js
/* eslint-disable camelcase */ import r from 'src/db/connect' import { lookupChapterId, lookupCycleId, writeCSV, parseArgs, shortenedPlayerId, } from './util' import { avgProjHours, avgHealthCulture, avgHealthTeamPlay, estimationBias, estimationAccuracy, avgProjCompleteness, avgProjQuality, playerReviewCount, recentCycleIds, recentProjectIds, recentProjStats, projReviewCounts, } from './playerStatHelpers' const HEADERS = [ 'cycle_no', 'player_id', 'xp', // FIXME: We'd rather have `avg_cycle_hours` than `avg_proj_hours`. 'avg_proj_hours', 'avg_proj_comp', 'avg_proj_qual', 'health_culture', 'health_team_play', 'health_technical', 'est_accuracy', 'est_bias', 'no_proj_rvws', 'elo', ] export default function requestHandler(req, res) { return runReport(req.query, res) .then(result => writeCSV(result, res, {headers: HEADERS})) } async function runReport(args) { const {cycleNumber, chapterName} = parseArgs(args) const chapterId = await lookupChapterId(chapterName) const cycleId = await lookupCycleId(chapterId, cycleNumber) return await statReport({chapterId, cycleId, cycleNumber}) } async function statReport(params) { const {chapterId, cycleNumber} = params const latestProjIds = recentProjectIds(recentCycleIds(chapterId, cycleNumber)) const reviewCount = projReviewCounts() return await r.table('players') .filter(r.row('chapterId').eq(chapterId) .and(r.row('active').eq(true) .and(r.row('stats').hasFields('projects')))) .merge(avgProjHours) .merge(recentProjStats(latestProjIds)) .merge(avgHealthCulture) .merge(avgHealthTeamPlay) .merge(estimationBias) .merge(estimationAccuracy) .merge(playerReviewCount(reviewCount)) .merge(avgProjCompleteness) .merge(avgProjQuality) .map(player => { return { cycle_no: cycleNumber, player_id: shortenedPlayerId(player('id')), xp: player('stats')('xp'), health_culture: player('health_culture'), health_team_play: player('health_team_play'), est_bias: player('est_bias'), est_accuracy: player('est_accuracy'), avg_proj_hours: player('avg_proj_hours'), avg_proj_comp: player('avg_proj_comp'), avg_proj_qual: player('avg_proj_qual'), no_proj_rvws: player('no_proj_rvws'), elo: player('stats')('elo')('rating'), } }) }
JavaScript
0.000001
@@ -89,25 +89,8 @@ Id,%0A - lookupCycleId,%0A wr @@ -1028,70 +1028,8 @@ ame) -%0A const cycleId = await lookupCycleId(chapterId, cycleNumber) %0A%0A @@ -1067,17 +1067,8 @@ rId, - cycleId, cyc
99fba54ae4aa1bd194a1f8bd0b8e23a681494b5c
send data to server
public/js/player.js
public/js/player.js
//Create browser compatible event listener function listener(elem, evnt, func, parentSocketConnection) { if (elem.addEventListener) elem.addEventListener(evnt,func,false); else if (elem.attachEvent) // For IE return elem.attachEvent("on" + evnt, func); } function player(properties){ //define public vars this.monsters = []; this.x = 0; this.y = 0; this.health = 0; this.maxhealth = 0; this.color = "#FFFFFF"; //define constructor if (properties.hasOwnProperty("x")) { this.x = properties.x; } if (properties.hasOwnProperty("y")) { this.y = properties.y; } if (properties.hasOwnProperty("color")) { this.color = properties.color; } if (properties.hasOwnProperty("health")) { this.health = properties.health; } if (properties.hasOwnProperty("maxhealth")) { this.maxhealth = properties.maxhealth; } if (properties.hasOwnProperty("monsters")) { if (Array.isArray(properties.monsters)) { } } if (properties.hasOwnProperty('canvas')) { this.canvas = properties.canvas; } if (properties.hasOwnProperty('parentSocketConnection')) { this.parentSocketConnection = properties.parentSocketConnection; } this.draw(); function movePlayer(e){ console.log(e); } /* Keyboard event listener */ listener(document, 'keydown', movePlayer,this.parentSocketConnection); } player.prototype.draw = function () { var canvas = document.getElementById(String(this.canvas)); var ctx = canvas.getContext("2d"); ctx.fillStyle = String(this.color); ctx.fillRect(this.x*10,this.y*10,10,10); }
JavaScript
0
@@ -35,16 +35,39 @@ listener + with parameter passing %0Afunctio @@ -102,30 +102,111 @@ par -entSocketConnection)%0A%7B +ameters)%0A%7B%0A elem.socketConnection = parameters%5B0%5D;%0A elem.x = parameters%5B1%5D;%0A elem.x = parameters%5B2%5D; %0A i @@ -230,16 +230,19 @@ istener) + %7B%0A %0A e @@ -281,16 +281,20 @@ alse);%0A + %7D else if @@ -312,16 +312,18 @@ chEvent) + %7B // For @@ -325,16 +325,17 @@ For IE%0A +%0A re @@ -376,16 +376,22 @@ func);%0A + %7D%0A %7D%0Afuncti @@ -1352,25 +1352,272 @@ %7B%0A - console.log(e); +switch (e.keyCode) %7B%0A case 38:%0A //up%0A e.target.socketConnection.socket.emit('action', %7B%0A %22type%22:%22move%22,%0A %22direction%22:%22up%22%0A %7D);%0A break;%0A case 38:%0A //up%0A break;%0A default:%0A %7D%0A //send action to server%0A%0A%0A %0A %7D @@ -1692,16 +1692,18 @@ ePlayer, + %5B this.par @@ -1721,16 +1721,31 @@ nnection +,this.x,this.y%5D );%0A%0A%7D%0Apl
c0daae273ca8a6a10e250c962a8fa7c83b75a56b
Update demo.js
demo/demo.js
demo/demo.js
$(function () { var data = [ { "Name": "John Smith", "Age": 45 }, { "Name": "Mary Johnson", "Age": 32 }, { "Name": "Bob Ferguson", "Age": 27 } ]; $("#grid").igGrid({ dataSource: data //JSON Array defined above }); });
JavaScript
0.000001
@@ -224,16 +224,55 @@ %5D;%0A + console.log(%22creating grid%22); %0A
71b8f23db7644c747075ea617e435758c9418eb0
Update testsA.js
nodejs_app/testsA.js
nodejs_app/testsA.js
var t = 0; const exec = require('child_process').exec; exec('node nodejs_app/app.js', (error, stdout, stderr)=>{ if (error) { console.error('exec error: ${error}'); t =1; return; } console.log('stdout: ${stdout}'); console.log('stderr: ${stderr}'); }); exec('killall node'); return t;
JavaScript
0.000001
@@ -79,16 +79,24 @@ pp.js', +function (error, @@ -114,10 +114,8 @@ err) -=%3E %7B%0A @@ -269,16 +269,16 @@ ');%0A%7D);%0A - exec('ki @@ -288,16 +288,204 @@ ll node' +,function(error, stdout, stderr)%7B%0A if (error) %7B%0A console.error('exec error: $%7Berror%7D');%0A%09t =1;%0A return;%0A %7D%0A console.log('stdout: $%7Bstdout%7D');%0A console.log('stderr: $%7Bstderr%7D');%0A%7D ); %0Aretu
346083aecea1c038bbe6aa13eb341a7ba60185fa
Return test.
tests/e2e/specs/editor/media/insertMediaFromLibrary.js
tests/e2e/specs/editor/media/insertMediaFromLibrary.js
/* * Copyright 2020 Google LLC * * 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 * * https://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. */ /** * External dependencies */ //import { percySnapshot } from '@percy/puppeteer'; /** * Internal dependencies */ import { createNewStory } from '../../../utils'; describe('Inserting Media from Media Library', () => { // Uses the existence of the element's frame element as an indicator for successful insertion. it('should insert an image by clicking on it', async () => { await createNewStory(); await expect(page).not.toMatchElement('[data-testid="FrameElement"]'); // Clicking will only act on the first element. await expect(page).toClick('[data-testid="mediaElement"]'); // First match is for the background element, second for the image. await expect(page).toMatchElement( '[data-testid="frameElement"]:nth-of-type(2)' ); // TODO: Enable once https://github.com/google/web-stories-wp/issues/1206 is merged. //await percySnapshot(page, 'Inserting Media from Media Library'); }); });
JavaScript
0.000016
@@ -622,18 +622,16 @@ ies%0A */%0A -// import %7B @@ -1372,99 +1372,8 @@ -// TODO: Enable once https://github.com/google/web-stories-wp/issues/1206 is merged.%0A // awai
e78ec392f234d09d7689c6b49b0debaf845665dc
Fix default avatar selection
public/js/script.js
public/js/script.js
/* this variable represents the current script element */ var me = {}; /* relative path to the element whose script is currently being processed.*/ if (typeof document.currentScript != "undefined" && document.currentScript != null) { var str = document.currentScript.src; me.path = (str.lastIndexOf("/") == -1) ? "." : str.substring(0, str.lastIndexOf("/")); } else { /* alternative method to get the currentScript (older browsers) */ // ... /* else get the URL path */ me.path = '.'; } /* Get index path based on current script url and requested url */ var indexPath = ''; var size = me.path.length - 1; for (var i = 0; i <= size; i++) { if (me.path[i] == document.URL[i]) indexPath += me.path[i]; } /* Get dirname of index path based on public folder */ var rootPath = 'http://localhost:8080/git/Talker-Town/'; /* Security BUG */ var comet; $(function(){ comet = new jRender.ajax.Comet({ url: indexPath + "application/index/backend" /* For remote requests (Cross domain) */ //url: "http://www.example.com/backend.php", //jsonp: true }); var settings = { data: {}, callback: { success: function(data) { // Connection established if (typeof data != "object") data = $.parseJSON(data); $("#state").text("Online"); if (!($("#" + data["timestamp"]).length)) { if ($('#content').length) { $('#content').append(data["msg"]); $('#content')[0].scrollTop = 9999999; if (data["user"] !== $.cookie("username")) { $("#notification-audio")[0].load(); $("#notification-audio")[0].play(); } } } $("#online_users").empty(); for (var i = data["online_users"].length - 1; i >= 0; i--) { var user = data["online_users"][i]; var bg_x, bg_y; // Get user's configuration $.getJSON(rootPath + 'data/cache/' + user + '.json', function(data) { var i = parseInt(data["avatar"].toString().charAt(0)) - 1; var j = parseInt(data["avatar"].toString().charAt(1)) - 1; var x = j; var y = i; bg_x = ( -30 * x ); bg_y = ( -(315/11) * y ) + 1; var nitem = "<div class='item'>" + "<img class='ui avatar image' style='background-position: " + bg_x + "px " + bg_y + "px' />" + "<div class='content'>" + "<div class='header'>" + data["username"] + "</div>" + "</div>" + "<div>"; $("#online_users").append(nitem); }); }; }, error: function(jqXHR, textStatus, errorThrown) { // Connection unestablished setTimeout(function(){ if (!comet.state) $("#state").text("Offline"); }, 3000); }, complete: function() { // For each request if (comet.state) $("#state").text("Online"); } } } // To connect only if the cookie exists if (typeof $.cookie('username') != 'undefined') comet.connect(settings); // Connect only if the session exists $.ajax({ url: indexPath + 'application/index/getIdentityInformation', dataType: 'json', success: function(data) { if (typeof data != "object") data = $.parseJSON(data); if (data.username != null) comet.connect(settings); } }) $("#chat").submit(function(event){ event.preventDefault(); if ($('#word').val().trim() != "") { var message = $('#word').val(); $('#word').val('').attr('disabled', 'disabled'); $('#content').append("<p id='loading-message-status'>" + message + " <i class='spinner icon'></i><p>"); $('#content')[0].scrollTop = 9999999; settings = { data: { msg: message }, callback: { success: function(data) { $('#content').append(data["msg"]); }, error: function(jqXHR, textStatus, errorThrown) { $('#loading-message-status i').attr('class', 'remove icon'); $('#loading-message-status').removeAttr('id'); $('#content').append("<div class='ui small compact red message'><strong>Error!</strong> The message was not sent.</div>"); }, complete: function() { if ($('#loading-message-status i').attr('class') != 'remove icon') $('#loading-message-status').remove(); $('#word').removeAttr('disabled'); $('#content')[0].scrollTop = 9999999; $('#word').focus(); } } } comet.doRequest(settings); } return false; }); /* Semantic ui tools */ $('.ui.sidebar').sidebar(); $("#show-users").click(function(){ $('.ui.sidebar').sidebar('toggle'); }); $('.ui.dropdown').dropdown(); $j.ready(function(){ if ($("#file_reader_response").length) { var Reader = $j.reader; var _files = new Reader.File({ fileBox: document.querySelector("#file-reader-onchange"), // input[type='file'] dropBox: document.querySelector("#file-reader-ondrop"), // dropbox preview: document.querySelector("#file-reader-ondrop"), // preview url: 'source/file-upload.php', size: 104857600, }); _files.addDropEvent(function(files){ _files.upload(files); }); _files.addChangeEvent(function(files){ _files.upload(files, function(uploadedFiles) { uploadedFiles = $.parseJSON(uploadedFiles); var links = "<div>"; for (var i = uploadedFiles.length - 1; i >= 0; i--) { links += "<a target='_blank' class='ui basic button' href='public/img/user/" + uploadedFiles[i] + "'>" + uploadedFiles[i] + " </a> "; }; links += "</div>"; $("#file_reader_response").append(links); }); }); } }); /* Avatar gallery */ $("body").delegate(".tk-gallery.selectable .item", "click", function(event){ event.preventDefault(); var input = $(this).parent().attr('data-input'); $(".tk-gallery.selectable").find(".item").addClass("unselected").removeClass("selected"); $(this).removeClass("unselected").addClass("selected"); $("#"+input).val($(this).attr('data-value')); }); $(".tk-gallery.selectable").find(".control-right").click(function(event){ event.preventDefault(); var me = $(this); me.addClass("disabled"); var items = $(".tk-gallery.selectable").find('.item'); var item = items.first().clone() $(".tk-gallery.selectable").find(".items").append(item); items.first().animate({ width: 0 }, 200, function(){ items.first().remove(); me.removeClass("disabled"); }); }); $(".tk-gallery.selectable").find(".control-left").click(function(event){ event.preventDefault(); var me = $(this); me.addClass("disabled"); var items = $(".tk-gallery.selectable").find('.item'); var item = items.last().clone() $(".tk-gallery.selectable").find(".items").prepend(item); item.css('width', 0); item.animate({ width: parseInt(items.last().css('width')) }, 200, function(){ items.last().remove(); me.removeClass("disabled"); }); }); });
JavaScript
0.000001
@@ -6872,16 +6872,25 @@ arent(). +parent(). attr('da
334c0e2084b5aed6773d7dae6115a89ec8b856c2
add TRASH Constants
frontend/src/javascripts/constants/NoteeConstants.js
frontend/src/javascripts/constants/NoteeConstants.js
var keyMirror = require('keymirror'); module.exports = keyMirror({ // notee POST_CREATE: null, POST_CREATE_FAILED: null, POST_UPDATE: null, POST_UPDATE_FAILED: null, POST_DELETE: null, POST_DELETE_FAILED: null, // category CATEGORY_CREATE: null, CATEGORY_CREATE_FAILED: null, CATEGORY_UPDATE: null, CATEGORY_UPDATE_FAILED: null, CATEGORY_DELETE: null, CATEGORY_DELETE_FAILED: null, // user USER_CREATE: null, USER_CREATE_FAILED: null, USER_UPDATE: null, USER_UPDATE_FAILED: null, USER_DELETE: null, USER_DELETE_FAILED: null, // image IMAGE_CREATE: null, IMAGE_CREATE_FAILED: null, IMAGE_DELETE: null, IMAGE_DELETE_FAILED: null, // comment COMMENT_UPDATE: null, COMMENT_UPDATE_FAILED: null, COMMENT_DELETE: null, COMMENT_DELETE_FAILED: null });
JavaScript
0.000004
@@ -862,14 +862,83 @@ ED: null +,%0A%0A // trash%0A TRASH_UPDATE: null,%0A TRASH_UPDATE_FAILED: null %0A%0A%7D);%0A
0149f4850e86a49c4e1d995cec3be80c4cd08fdb
Substitute the model in its corresponding place.
directive.js
directive.js
'use strict'; var dragula = require('dragula'); /*jshint unused: false*/ function register (angular) { return ['dragulaService', function angularDragula (dragulaService) { return { restrict: 'A', scope: { dragulaScope: '=', dragulaModel: '=' }, link: link }; function link (scope, elem, attrs) { var dragulaScope = scope.dragulaScope || scope.$parent; var container = elem[0]; var name = scope.$eval(attrs.dragula); var bag = dragulaService.find(dragulaScope, name); if (bag) { var drake = bag.drake; drake.containers.push(container); } else { var drake = dragula({ containers: [container] }); dragulaService.add(dragulaScope, name, drake); } scope.$watch('dragulaModel', function(model) { if(model){ if(drake.models){ drake.models.push(model); }else{ drake.models = [model]; } } }); } }]; } module.exports = register;
JavaScript
0.999999
@@ -831,21 +831,34 @@ unction( -model +newValue, oldValue ) %7B%0A @@ -864,21 +864,24 @@ if( -model +newValue )%7B%0A @@ -919,31 +919,112 @@ -drake.models.push(model +var modelIndex = drake.models.indexOf(oldValue);%0A drake.models.splice(modelIndex, 1, newValue );%0A @@ -1067,21 +1067,24 @@ dels = %5B -model +newValue %5D;%0A
c5068479cf8fe091a756e1d5c7dacde1448db0b7
delete require of superagent
routes/routers/register.js
routes/routers/register.js
'use strict'; var express = require('express'); var router = express.Router(); var request = require('superagent'); var lang = require('../../mixin/lang-message/chinese'); var constant = require('../../mixin/constant').backConstant; var async = require('async'); var validate = require('validate.js'); var md5 = require('js-md5'); var constraint = require('../../mixin/register-constraint'); var httpStatus = require('../../mixin/constant').httpCode; var User = require('../../models/user'); function checkRegisterInfo(registerInfo) { var pass = true; var valObj = {}; valObj.email = registerInfo.email; valObj.mobilePhone = registerInfo.mobilePhone; valObj.password = registerInfo.password; var result = validate(valObj, constraint); if (result !== undefined) { pass = false; } if (registerInfo.password.length < constant.PASSWORD_MIN_LENGTH || registerInfo.password.length > constant.PASSWORD_MAX_LENGTH) { pass = false; } return pass; } //注册 router.post('/', (req, res, next) => { var registerInfo = req.body; var result = {}; result.data = {}; if (checkRegisterInfo((registerInfo))) { var isMobilePhoneExist; var isEmailExist; async.waterfall([ (done)=> { //第一步去数据库中查询看是否有该手机号 User.find({mobilePhone: registerInfo.mobilePhone}, (err, doc)=> { if (err) { done(err, null); } if (doc.length !== 0) { isMobilePhoneExist = true; } done(null, null); }) }, (data, done)=> { //第二步去数据库中查询看是否有该邮箱 User.find({email: registerInfo.email}, (err, doc)=> { if (err) { done(err, null); } if (doc.length !== 0) { isEmailExist = true; } done(null, null); }) }, (data, done)=> { //如果有电话或者邮箱存在就抛错 if (isMobilePhoneExist || isEmailExist) { done(true, null); } else { done(null, null); } }, (data, done)=> { registerInfo.password = md5(registerInfo.password); var user = new User(registerInfo); user.save(function (err, doc) { //参数3个 done(null, doc); }); }, (data, done)=> { //记录一条登录信息 done(null, data); }, (data, done)=> { //设置session req.session.user = { id: data._id //userInfo: '12' //token: data.headers.token }; done(null, null); } ], (err, data)=> { if (err === true) { res.send({ status: constant.FAILING_STATUS, message: lang.EXIST, data: { isEmailExist: isEmailExist, isMobilePhoneExist: isMobilePhoneExist } }); } else if (err) { res.status(httpStatus.INTERNAL_SERVER_ERROR).send({ message: lang.REGISTER_FAILED, status: constant.SERVER_ERROR }); } else { res.send({ status: httpStatus.OK, message: lang.REGISTER_SUCCESS }); } }) } }); //查找mongodb数据库,看是否有已经注册的手机号 router.get('/validate-mobile-phone', (req, res, next) => { var mobilePhone = req.query.mobilePhone; User.find({mobilePhone: mobilePhone}, (err, doc)=> { if (err) { next(err); return; } else { if (doc.length === 0) { res.send({ status: httpStatus.NOT_FOUND //404 代表未注册 }) } else { res.send({ status: httpStatus.OK //200 代表已经注册 }) } } }); }); //查找mongodb数据库,看是否有已经注册的邮箱 router.get('/validate-email', (req, res, next)=> { var email = req.query.email; User.find({email: email}, (err, doc)=> { if (err) { next(err); return; } else { if (doc.length === 0) { res.send({ status: httpStatus.NOT_FOUND //404 代表未注册 }) } else { res.send({ status: httpStatus.OK //200 代表已经注册 }) } } }); }); module.exports = router;
JavaScript
0.000004
@@ -77,45 +77,8 @@ ();%0A -var request = require('superagent');%0A var
3bde929a83ee04655b485dc57712776407252d2d
Create and call toggleSelectedArrItem function
public/js/select.js
public/js/select.js
var selectMode = false; var selected = []; var selectModeToggle = document.getElementById('selectModeToggle'); var deleteButton = document.getElementById('delete'); var emoticonsContainer = document.getElementById('emoticons'); selectModeToggle.addEventListener('click', function() { if (selectMode) { selectMode = false; // change style of select link to indicate select mode is OFF somehow deleteButton.classList.add('hide'); } else { selectMode = true; deleteButton.classList.remove('hide'); emoticonsContainer.addEventListener('click', function(event) { if (event.target.matches('.emoticon')) { event.stopPropagation(); event.target.classList.toggle('selected'); } }); } });
JavaScript
0
@@ -222,16 +222,202 @@ ons');%0A%0A +function toggleSelectedArrItems(emoticon) %7B%0A var index = selected.indexOf(emoticon);%0A if (index === -1) %7B%0A selected.push(emoticon);%0A %7D else %7B%0A selected.splice(index, 1);%0A %7D%0A%7D%0A%0A selectMo @@ -656,16 +656,89 @@ = true;%0A + // change style of select link to indicate select mode is ON somehow%0A dele @@ -919,16 +919,16 @@ tion();%0A - @@ -966,24 +966,80 @@ selected');%0A + toggleSelectedArrItems(event.target.innerHTML);%0A %7D%0A
bcb55153f7b15fcf77f5e6c08672f7bdccc6c919
Fix bug with multiple quizes in a row
frontend/src/main-components/StudyModeGameHandler.js
frontend/src/main-components/StudyModeGameHandler.js
let Quiz; let currentQuizWord = {}; let currentArray = 0; let test = 0; async function startQuiz(folderKey) { await fetch(`/study?folderKey=${folderKey}`) .then(res => res.json()) .then(result => { Quiz = result; console.log(Quiz[0].length); return Quiz.length; }).catch("Could not find any cards"); } function nextQuizWord() { let nextWord = {}; if (Quiz[currentArray].length != 0) { nextWord = Quiz[currentArray].shift(); } else { currentArray++; if (currentArray >= Quiz.length) { return "!@end"; } else { nextWord = Quiz[currentArray].shift(); } } currentQuizWord = nextWord; return nextWord; } function updateWordQueues(correct, cardKey) { if (correct == "false" && currentArray < Quiz.length - 1) { Quiz[currentArray + 1].push(currentQuizWord); } // Updates the card's familarity score fetch('/study', { method: 'POST', body: `cardKey=${cardKey}&answeredCorrectly=${correct}`, headers: { 'Content-type': 'application/x-www-form-urlencoded' } }); } function getRound() { return currentArray; } export { startQuiz, updateWordQueues, nextQuizWord, getRound };
JavaScript
0
@@ -49,26 +49,8 @@ rray - = 0;%0Alet test = 0 ;%0A%0Aa @@ -86,16 +86,38 @@ rKey) %7B%0A + currentArray = 0;%0A await fe @@ -234,46 +234,8 @@ lt;%0A - console.log(Quiz%5B0%5D.length);%0A
a25e7179ad8e000fed149d714df8a9371b5af5aa
Update dashboard simple.js
angular/themes/dashboard/simple/simple.js
angular/themes/dashboard/simple/simple.js
/** * Created by anonymoussc on 26/11/15 5:40. */ (function() { 'use strict'; angular.module('app.controllers').controller('DashboardSimpleCtrl', function($scope, $timeout, $mdSidenav, $log) { $scope.toggleLeft = buildDelayedToggler('left'); $scope.toggleRight = buildToggler('right'); $scope.isOpenRight = function() { return $mdSidenav('right').isOpen(); }; /** * Supplies a function that will continue to operate until the * time is up. */ function debounce(func, wait, context) { var timer; return function debounced() { var context = $scope, args = Array.prototype.slice.call(arguments); $timeout.cancel(timer); timer = $timeout(function() { timer = undefined; func.apply(context, args); }, wait || 10); }; } /** * Build handler to open/close a SideNav; when animation finishes * report completion in console */ function buildDelayedToggler(navID) { return debounce(function() { $mdSidenav(navID) .toggle() .then(function() { $log.debug("toggle " + navID + " is done"); }); }, 200); } function buildToggler(navID) { return function() { $mdSidenav(navID) .toggle() .then(function() { $log.debug("toggle " + navID + " is done"); }); }; } }); })();
JavaScript
0.000001
@@ -1329,32 +1329,35 @@ + // $log.debug(%22tog @@ -1638,16 +1638,19 @@ + // $log.de
bc560feb331bfec47db49611fefd41366e283324
fix sidebar icon overlapping
services/ui/src/pages/_app.js
services/ui/src/pages/_app.js
import 'isomorphic-unfetch'; import App, { Container } from 'next/app'; import React from 'react'; import Head from 'next/head'; import getConfig from 'next/config'; import { ApolloProvider } from 'react-apollo'; import ApolloClient from 'apollo-boost'; import Typekit from 'react-typekit'; import withKeycloak from '../lib/withKeycloak'; import withApollo from '../lib/withApollo'; import NotAuthenticated from '../components/NotAuthenticated'; import { bp, color, fontSize } from '../variables'; const { serverRuntimeConfig, publicRuntimeConfig } = getConfig(); class MyApp extends App { render() { const { Component, pageProps, apolloClient, keycloak } = this.props; return ( <Container> <Head> <link rel="stylesheet" href="/static/normalize.css" /> <Typekit kitId="ggo2pml" /> <script type="text/javascript" src={`${publicRuntimeConfig.KEYCLOAK_API}/js/keycloak.js`} /> </Head> {(apolloClient && ( <ApolloProvider client={apolloClient}> <Component {...pageProps} keycloak={keycloak}/> </ApolloProvider> )) || <NotAuthenticated />} <style jsx global>{` * { box-sizing: border-box; } body { color: ${color.black}; font-family: 'source-sans-pro', sans-serif; ${fontSize(16)}; height: 100%; line-height: 1.25rem; overflow-x: hidden; .content-wrapper { background-color: ${color.almostWhite}; flex: 1 0 auto; width: 100%; } #__next { display: flex; flex-direction: column; min-height: 100vh; } a { color: ${color.black}; text-decoration: none; &.hover-state { position: relative; transition: all 0.2s ease-in-out; &::before, &::after { content: ''; position: absolute; bottom: 0; width: 0px; height: 1px; transition: all 0.2s ease-in-out; transition-duration: 0.75s; opacity: 0; } &::after { left: 0; background-color: ${color.linkBlue}; } &:hover { &::before, &::after { width: 100%; opacity: 1; } } } } p { margin: 0 0 1.25rem; } p a { text-decoration: none; transition: background 0.3s ease-out; } strong { font-weight: normal; } em { font-style: normal; } h2 { ${fontSize(36, 42)}; font-weight: normal; margin: 0 0 38px; } h3 { ${fontSize(30, 42)}; font-weight: normal; margin: 0 0 36px; } h4 { ${fontSize(25, 38)}; font-weight: normal; margin: 4px 0 0; } ul { list-style: none; margin: 0 0 1.25rem; padding-left: 0; li { background-size: 8px; margin-bottom: 1.25rem; padding-left: 20px; a { text-decoration: none; } } } ol { margin: 0 0 1.25rem; padding-left: 20px; li { margin-bottom: 1.25rem; a { text-decoration: none; } } } .box { border: 1px solid ${color.lightestGrey}; box-shadow: 0px 4px 8px 0px rgba(0, 0, 0, 0.03); border-radius: 3px; position: relative; width: 100%; &::after { bottom: 4px; content: ''; display: block; height: 20px; left: 15px; position: absolute; transition: box-shadow 0.5s ease; width: calc(100% - 30px); } &:hover { border: 1px solid ${color.brightBlue}; &::after { box-shadow: 0px 12px 40px 0px rgba(73, 127, 250, 0.5); } } a { background-color: ${color.white}; border-radius: 3px; display: block; height: 100%; overflow: hidden; padding: 16px 20px; position: relative; transition: background-image 0.5s ease-in-out; z-index: 10; } } .field { line-height: 25px; a { color: ${color.linkBlue}; } } label { color: ${color.darkGrey}; font-family: 'source-code-pro', sans-serif; ${fontSize(13)}; text-transform: uppercase; } .field-wrapper { display: flex; margin-bottom: 18px; @media ${bp.xs_smallUp} { margin-bottom: 30px; } &::before { @media ${bp.xs_smallUp} { background-position: top 11px right 14px; background-repeat: no-repeat; background-size: 20px; border-right: 1px solid ${color.midGrey}; content: ''; display: block; height: 60px; left: 0; margin-right: 14px; min-width: calc((100vw / 16) * 1.5); padding-right: 14px; position: absolute; width: calc((100vw / 16) * 1.5); } } & > div { @media ${bp.xs_smallUp} { margin-top: 8px; } } } } `}</style> </Container> ); } } export default withKeycloak(withApollo(MyApp));
JavaScript
0
@@ -6141,27 +6141,55 @@ margin- -right: 14 +left: calc(((100vw / 16) * 1.5) - 25 px +) ;%0A @@ -6205,42 +6205,25 @@ m -in-width: calc((100vw / 16) * 1.5) +argin-right: 14px ;%0A @@ -6326,32 +6326,12 @@ th: -calc((100vw / 16) * 1.5) +25px ;%0A
511f51bc5132a76bf27a90fc94440e36be13350c
Update funcoesGlobal.js
assets/js/funcoesGlobal.js
assets/js/funcoesGlobal.js
$().ready(function () { setTimeout(function () { $('div.alert').delay(1500).fadeOut(400); // "div.alert" é a div que tem a class alert do elemento que deseja manipular. }, 2500); // O valor é representado em milisegundos. });
JavaScript
0
@@ -234,8 +234,9 @@ dos.%0A%7D); +%0A
af69cfdb388353a60f106a9848827c9454e057f4
fix offset
packages/utils/snappers/grid.js
packages/utils/snappers/grid.js
export default (grid) => { const coordFields = [ ['x', 'y'], ['left', 'top'], ['right', 'bottom'], ['width', 'height'], ].filter(([xField, yField]) => xField in grid || yField in grid); return function (x, y) { const { range, limits = { left : -Infinity, right : Infinity, top : -Infinity, bottom: Infinity, }, } = grid; const offset = offset || { x: 0, y: 0 }; const result = { range }; for (const [xField, yField] of coordFields) { const gridx = Math.round((x - offset.x) / grid[xField]); const gridy = Math.round((y - offset.y) / grid[yField]); result[xField] = Math.max(limits.left, Math.min(limits.right , gridx * grid[xField] + offset.x)); result[yField] = Math.max(limits.top, Math.min(limits.bottom , gridy * grid[yField] + offset.y)); } return result; }; };
JavaScript
0.000001
@@ -394,63 +394,49 @@ -%7D = grid;%0A%0A const offset = offset %7C%7C %7B x: 0, y: 0 %7D; + offset = %7B x: 0, y: 0 %7D,%0A %7D = grid;%0A %0A
28a1a7e7eb13e3019dd25bc83a9ad0e7acb5892a
Fix empty state link
assets/js/autocomplete.js
assets/js/autocomplete.js
--- --- $(document).ready(function() { 'use strict'; var client = algoliasearch('KDWVSZVS1I', 'ce4d584b0de36ca3f8b4727fdb83c658'); var index = client.initIndex('grantmakers_io'); autocomplete('#autocomplete-input', { hint: false, openOnFocus: false, minLength: 1 }, [ { source: function(q, cb) { if (q === '') { cb([ // { organization_name: 'NOVO FOUNDATION' }, // { organization_name: 'ABBOTT FAMILY FOUNDATION' }, // { organization_name: 'BILL AND MELINDA GATES FOUNDATION' } ]); } else { var defaultHits = autocomplete.sources.hits(index, { hitsPerPage: 5 }); defaultHits(q, cb); } }, displayKey: 'organization_name', templates: { suggestion: function(suggestion) { return autocomplete.escapeHighlightedString(suggestion._highlightResult) && autocomplete.escapeHighlightedString(suggestion._highlightResult.organization_name.value) || autocomplete.escapeHighlightedString(suggestion.organization_name); }, footer: function(){ return '<div class="algolia-logo-autocomplete center-align small">Search powered by <a href="https://www.algolia.com/" class="algolia-powered-by-link" title="Algolia"><img class="algolia-logo" src="{{site.url}}{{site.baseurl}}/assets/img/algolia-light-bg.svg" alt="Algolia" style="width: 60px;height: 16px;" /></a></div>' }, empty: function(){ return '<div class="empty">Not finding what you need? Try our <a href="{{ site.baseurl }}">full search</a>.</div>'; } } } ]).on('autocomplete:selected', function(event, suggestion, dataset) { var ein = suggestion.ein; var target = 'https://www.grantmakers.io/profiles/' + ein; if(ein) { location.href = target; } else { var $toastContent = $('<span>Something went wrong</span>').add($('<button class="btn-flat toast-action toast-action-redirect">Try main search page</button>')); Materialize.toast($toastContent, 10000); $('.toast-action-redirect').on('click', function(){ location.href = 'https://www.grantmakers.io'; }); } }); });
JavaScript
0.000368
@@ -1555,20 +1555,16 @@ %7B%7B site. -base url %7D%7D%22%3E
7b47cf576b67f4b4914bc0d032113ec5eb65741b
bump ??? distribution dist/snuggsi.min.es.js
dist/snuggsi.min.es.js
dist/snuggsi.min.es.js
class TokenList{constructor(e,t){const n=[],s=/{(\w+|#)}/,o=e=>[].slice.call(e).map(e=>s.test(e.value)&&n.push(e)),r=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.tagName?o(e.attributes):s.test(e.textContent)&&n.push(e),null);for(;r.nextNode(););for(e of n)(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e))}bind(e){Object.keys(this).map(e=>this[e].map(e=>e.textContent=e.text)&&e).map(t=>this[t].map(n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t])))}}const HTMLElement=(e=>{function t(){}return t.prototype=e,t})(window.HTMLElement.prototype);(e=>{function t(e,t,n){for(n of this.querySelectorAll("[slot]"))(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]").outerHTML=n.outerHTML;this.innerHTML=e.innerHTML}const n=new XMLHttpRequest;for(let s of document.querySelectorAll('link[id*="-"]'))n.open("GET",s.href),n.responseType="document",n.onload=function(){const e=this.response.querySelectorAll.bind(this.response),n=this.link,s=n.nextSibling;for(let o of document.querySelectorAll(n.id))t.call(o,e("template")[0].cloneNode(!0));for(let t of e("style,link,script")){let e=t.getAttribute("as"),o=document.createElement(t.localName);["src","href","textContent","rel"].map(((e,t)=>n=>t[n]&&(e[n]=t[n]))(o,t)),"style"==e&&(o.rel="stylesheet"),n.parentNode.insertBefore(o,s),"script"==e&&(n.parentNode.insertBefore(document.createElement("script"),s).src=t.href)}},n.link=s,n.send()})();const Template=function(e){return e.length&&(e=document.querySelector("template[name="+e+"]")),e.hidden=!0,e.HTML=e.innerHTML,e.bind=function(e,t){const n=document.createElement("section");for(let s of this.dependents||[])s.parentNode.removeChild(s);n.innerHTML=[].concat(e).reduce((e,t,n)=>{let s=this.HTML;"object"!=typeof t&&(t={self:t}),t["#"]=n;for(let o in t)s=s.split("{"+o+"}").join(t[o]);return e+s},""),t=this.nextSibling;for(let s of this.dependents=[].slice.call(n.childNodes))this.parentNode.insertBefore(s,t)}.bind(e),e};!window.customElements&&(window.customElements={}),new class{constructor({define:e,get:t,whenDefined:n}=customElements){window.customElements.define=this._define(void 0).bind(this)}_define(e=(e=>{})){return(t,n)=>e.apply(window.customElements,this.register(t,n))}register(e,t){return(this[e]=t).localName=e,"loading"===document.readyState?document.addEventListener("DOMContentLoaded",this.queue(...arguments)):this.queue(...arguments)(),arguments}queue(e,t){return n=>[].slice.call(document.getElementsByTagName(e)).map(this.upgrade(t))}upgrade(e){return t=>Object.setPrototypeOf(t,e.prototype).connectedCallback&&t.connectedCallback()}swizzle(e,...t){}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){return this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect(),this}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of e.attributes)/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect().render()}render(e){for(e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),[this,...this.selectAll("*")].map(this.register,this),super.onidle&&super.onidle()}},Element=(e=>{const t=(e,t)=>n=>window.customElements.define(e+"",Custom(n),{constructor:t});return t.prototype=e.prototype,t})(window.Element);
JavaScript
0.000007
@@ -1,12 +1,103 @@ +const HTMLElement=(e=%3E%7Bfunction t()%7B%7Dreturn t.prototype=window.HTMLElement.prototype,t%7D)(); class TokenL @@ -618,100 +618,8 @@ ))%7D%7D -const HTMLElement=(e=%3E%7Bfunction t()%7B%7Dreturn t.prototype=e,t%7D)(window.HTMLElement.prototype); (e=%3E
30c1e5e8e15e198ac6b0167541868171b4eadcfb
Fix WYSIWYG popup var
cms/apps/media/static/media/js/jquery.cms.media.js
cms/apps/media/static/media/js/jquery.cms.media.js
/* TinyMCE filebrowser implementation. */ (function($) { // Define the filebrowser plugin. $.cms.media = {} // Closes the filebrowser and sends the information back to the TinyMCE editor. $.cms.media.complete = function(permalink, title) { // Get the important values from TinyMCE. var win = tinyMCEPopup.getWindowArg("window"); // Get the input from the opening window. var input = $("#" + tinyMCEPopup.getWindowArg("input"), win.document); input.attr("value", permalink); // Set the link dialogue values. $("#linktitle", win.document).attr("value", title); // Set the image dialogue values. if (typeof(win.ImageDialog) != "undefined") { if (win.ImageDialog.getImageData) { win.ImageDialog.getImageData(); } if (win.ImageDialog.showPreviewImage) { win.ImageDialog.showPreviewImage(permalink); } } // Close the dialogue. tinyMCEPopup.close(); } // Initializes the popup file browser. $.cms.media.initBrowser = function() { if (tinyMCEPopup.getWindowArg("tinymce_active")) { // Make the changelist links clickable and remove the original inline click listener. $("div#changelist tr.row1 a, div#changelist tr.row2 a").attr("onclick", null).click(function() { var img = $("img", this); var title = img.attr("title"); var permalink = img.attr("cms:permalink"); $.cms.media.complete(permalink, title) return false; }); // Made the add link flagged for TinyMCE. $("a.addlink").attr("href", $("a.addlink").attr("href") + "&_tinymce=1"); } } // Add in the filebrowser plugin to the rich text editor. $.fn.cms.htmlWidget.extensions.file_browser_callback = function(field_name, url, type, win) { var browserURL = "/admin/media/file/?pop=1"; if (type == "image") { browserURL = browserURL + '&file__iregex=\x5C.(png|gif|jpg|jpeg)$'; } if (type == "media") { browserURL = browserURL + '&file__iregex=\x5C.(swf|flv|m4a|mov|wmv)$'; } tinyMCE.activeEditor.windowManager.open({ file: browserURL, title: "Select file", width: 800, height: 600, resizable: "yes", inline: "yes", close_previous: "no", popup_css: false }, { window: win, input: field_name, tinymce_active: true }); return false; } }(django.jQuery));
JavaScript
0
@@ -2023,19 +2023,22 @@ a/file/? +_ pop +up =1%22;%0A @@ -2723,8 +2723,9 @@ Query)); +%0A
01dd232947895052939d7279ba699565db6a8d77
Fix the value stat getter when no records available
services/value-stat-getter.js
services/value-stat-getter.js
'use strict'; var _ = require('lodash'); var P = require('bluebird'); var FilterParser = require('./filter-parser'); function ValueStatGetter(model, params, opts) { function getAggregateField() { // jshint sub: true return params['aggregate_field'] || '_id'; } this.perform = function () { return new P(function (resolve, reject) { var query = model.aggregate(); if (params.filters) { _.each(params.filters, function (filter) { query = new FilterParser(model, opts).perform(query, filter.field, filter.value, 'match'); }); } var sum = 1; if (params['aggregate_field']) { sum = '$' + params['aggregate_field']; } query .group({ _id: null, total: { $sum: sum } }) .exec(function (err, records) { if (err) { return reject(err); } resolve({ value: records[0].total }); }); }); }; } module.exports = ValueStatGetter;
JavaScript
0.00019
@@ -886,16 +886,94 @@ err); %7D%0A + if (!records %7C%7C !records.length) %7B return resolve(%7B value: 0 %7D); %7D%0A%0A
d0b101824a3a8c469c48b99650f6b84863bb7892
This should be body not data
services/message_broker.js
services/message_broker.js
var callbacks = []; module.exports = function(router) { var message_broker = {}; router.post('/', function(req, res) { console.log("YES: " + req.data); notify(req.data); res.json(["OKAY", 200]); }); message_broker.registerCallback = function(callback) { callbacks.push(callback); } return message_broker; } function notify(data) { callbacks.forEach(function(element, index, array) { element(data); }); }
JavaScript
0.999998
@@ -145,28 +145,28 @@ ES: %22 + req. -data +body );%0A notif @@ -171,20 +171,20 @@ ify(req. -data +body );%0A r
b8c7162496262871a2339fa71796ed69d7ed2442
capitalize Sidebar collection names
lib/jekyll/admin/public/src/containers/Sidebar.js
lib/jekyll/admin/public/src/containers/Sidebar.js
import React, { Component, PropTypes } from 'react'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import { Link } from 'react-router'; import _ from 'underscore'; // Constants import { ADMIN_PREFIX } from '../constants'; // Components import Splitter from '../components/Splitter'; // Actions import { fetchCollections } from '../actions/collections'; export class Sidebar extends Component { componentDidMount() { const { fetchCollections } = this.props; fetchCollections(); } renderCollections() { const { collections } = this.props; if (collections.length) { return _.chain(collections) .filter(col => col.label != 'posts') // TODO .map((col, i) => { return ( <li key={i}> <Link activeClassName="active" to={`${ADMIN_PREFIX}/collections/${col.label}`}> <i className="fa fa-book"></i>{col.label} </Link> </li> ); }).value(); } } render() { return ( <div className="sidebar"> <Link className="logo" to={`${ADMIN_PREFIX}/pages`} /> <div className="routes"> <ul> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/pages`}><i className="fa fa-file-text"></i>Pages</Link> </li> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/collections/posts`}><i className="fa fa-thumb-tack"></i>Posts</Link> </li> {this.renderCollections()} <Splitter /> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/data`}><i className="fa fa-database"></i>Data</Link> </li> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/static-files`}><i className="fa fa-file"></i>Static Files</Link> </li> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/plugins`}><i className="fa fa-plug"></i>Plugins</Link> </li> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/git`}><i className="fa fa-git-square"></i>Git</Link> </li> <Splitter /> <li> <Link activeClassName="active" to={`${ADMIN_PREFIX}/configuration`}><i className="fa fa-cog"></i>Configuration</Link> </li> </ul> </div> </div> ); } } Sidebar.propTypes = { collections: PropTypes.array.isRequired, fetchCollections: PropTypes.func.isRequired }; function mapStateToProps(state) { const { collections } = state; return { collections: collections.collections }; } function mapDispatchToProps(dispatch) { return bindActionCreators({ fetchCollections }, dispatch); } export default connect( mapStateToProps, mapDispatchToProps, null, {pure:false})(Sidebar); // fix this when react-router 3.0.0
JavaScript
0.99999
@@ -387,16 +387,64 @@ ions';%0A%0A +import %7B capitalize %7D from '../utils/helpers';%0A%0A export c @@ -956,16 +956,27 @@ k%22%3E%3C/i%3E%7B +capitalize( col.labe @@ -976,16 +976,17 @@ ol.label +) %7D%0A
febac211599b3d1316dd7ca07ebea8f1698c86b7
fix compatibility with node-webkit
src/editor/fileUtils.js
src/editor/fileUtils.js
// //var hasLibPng FIRE.savePng = function (canvas, filename, path, pixelBuffer, zip, callback) { function getLibpng(callback) { if (typeof(libpng) !== 'undefined') { callback(libpng); return true; } else if (FIRE.isnode === false && require) { require(['libpng'], callback); return true; } return false; } var usingLibpng = getLibpng(function (libpng) { // encode by libpng console.time('libpng encode ' + filename); var png = libpng.createWriter(canvas.width, canvas.height); png.set_filter(libpng.FILTER_NONE); png.set_compression_level(3); png.write_imageData(pixelBuffer); png.write_end(); console.timeEnd('libpng encode ' + filename); //console.log('Bytes: ' + png.data.length); if (FIRE.isnode) { if (zip) { zip.file(filename, png.data); // TODO: test } else { Fs.writeFileSync(path, new Buffer(png.data)); //, {'encoding': 'base64'} } } else { if (zip) { zip.file(filename, png.data); } else { var blob = new Blob([new Uint8Array(png.data)], {type: 'image/png'}); FIRE.downloadBlob(blob, filename); } } if (callback) { callback(); } }); if (usingLibpng === false) { var dataUrl, base64; if (!canvas) { throw 'no png encoder nor canvas'; } // encode by canvas if (FIRE.isnode) { dataUrl = canvas.toDataURL('image/png'); base64 = FIRE.imgDataUrlToBase64(dataUrl); if (zip) { zip.file(filename, base64, { base64: true }); } else { Fs.writeFileSync(path, base64, {'encoding': 'base64'}); } } else { if (zip) { dataUrl = canvas.toDataURL('image/png'); base64 = FIRE.imgDataUrlToBase64(dataUrl); zip.file(filename, base64, { base64: true }); } else { FIRE.downloadCanvas(canvas, filename); } } if (callback) { callback(); } } }; FIRE.saveText = function (text, filename, path) { if (FIRE.isnode) { Fs.writeFileSync(path, text, {'encoding': 'ascii'}); } else { var blob = new Blob([text], {type: "text/plain;charset=utf-8"}); // not support 'application/json' FIRE.downloadBlob(blob, filename); } };
JavaScript
0
@@ -287,16 +287,18 @@ require +js ) %7B%0A @@ -312,16 +312,18 @@ require +js (%5B'libpn
ffecf0877c099491a8b096cac4559fe84c31638c
Fix operator permissions in permission map
app/src/pages/common/membersPage/modals/permissionMapModal/permissionMap/permissions.js
app/src/pages/common/membersPage/modals/permissionMapModal/permissionMap/permissions.js
/* * Copyright 2019 EPAM Systems * * 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. */ import { PROJECT_MANAGER, OPERATOR, CUSTOMER, MEMBER } from 'common/constants/projectRoles'; import { ALL, OWNER } from 'common/constants/permissions'; export const ACTIONS = { EDIT_SETTINGS: 'EDIT_SETTINGS', ACTIONS_WITH_MEMBERS: 'ACTIONS_WITH_MEMBERS', VIEW_INFO_ABOUT_MEMBERS: 'VIEW_INFO_ABOUT_MEMBERS', REPORT_LAUNCH: 'REPORT_LAUNCH', VIEW_LAUNCH_IN_DEBUG_MODE: 'VIEW_LAUNCH_IN_DEBUG_MODE', MOVE_LAUNCH_TO_DEBUG_DEFAULT: 'MOVE_LAUNCH_TO_DEBUG_DEFAULT', ACTIONS_WITH_LAUNCH: 'ACTIONS_WITH_LAUNCH', MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT: 'MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT', ACTIONS_WITH_ITEM: 'ACTIONS_WITH_ITEM', INVESTIGATION_ACTIONS: 'INVESTIGATION_ACTIONS', CREATE_SHARE_ITEM: 'CREATE_SHARE_ITEM', EDIT_DELETE_SHARED_ITEM: 'EDIT_DELETE_SHARED_ITEM', DELETE_SHARED_ITEM: 'DELETE_SHARED_ITEM', RERUN_LAUNCHES: 'RERUN_LAUNCHES', CHANGE_STATUS: 'CHANGE_STATUS', }; export const PERMISSIONS_MAP = { [PROJECT_MANAGER]: { [ACTIONS.EDIT_SETTINGS]: OWNER, [ACTIONS.ACTIONS_WITH_MEMBERS]: OWNER, [ACTIONS.VIEW_INFO_ABOUT_MEMBERS]: OWNER, [ACTIONS.REPORT_LAUNCH]: OWNER, [ACTIONS.VIEW_LAUNCH_IN_DEBUG_MODE]: ALL, [ACTIONS.MOVE_LAUNCH_TO_DEBUG_DEFAULT]: ALL, [ACTIONS.ACTIONS_WITH_LAUNCH]: ALL, [ACTIONS.MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT]: ALL, [ACTIONS.ACTIONS_WITH_ITEM]: ALL, [ACTIONS.INVESTIGATION_ACTIONS]: ALL, [ACTIONS.CREATE_SHARE_ITEM]: OWNER, [ACTIONS.EDIT_DELETE_SHARED_ITEM]: ALL, [ACTIONS.RERUN_LAUNCHES]: ALL, [ACTIONS.CHANGE_STATUS]: ALL, }, [MEMBER]: { [ACTIONS.VIEW_INFO_ABOUT_MEMBERS]: OWNER, [ACTIONS.REPORT_LAUNCH]: OWNER, [ACTIONS.VIEW_LAUNCH_IN_DEBUG_MODE]: ALL, [ACTIONS.MOVE_LAUNCH_TO_DEBUG_DEFAULT]: OWNER, [ACTIONS.ACTIONS_WITH_LAUNCH]: OWNER, [ACTIONS.MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT]: ALL, [ACTIONS.ACTIONS_WITH_ITEM]: OWNER, [ACTIONS.INVESTIGATION_ACTIONS]: ALL, [ACTIONS.CREATE_SHARE_ITEM]: OWNER, [ACTIONS.EDIT_DELETE_SHARED_ITEM]: OWNER, [ACTIONS.RERUN_LAUNCHES]: OWNER, [ACTIONS.CHANGE_STATUS]: ALL, }, [OPERATOR]: { [ACTIONS.VIEW_INFO_ABOUT_MEMBERS]: OWNER, [ACTIONS.VIEW_LAUNCH_IN_DEBUG_MODE]: ALL, [ACTIONS.MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT]: ALL, [ACTIONS.INVESTIGATION_ACTIONS]: ALL, [ACTIONS.CREATE_SHARE_ITEM]: OWNER, [ACTIONS.EDIT_DELETE_SHARED_ITEM]: OWNER, [ACTIONS.RERUN_LAUNCHES]: OWNER, [ACTIONS.CHANGE_STATUS]: ALL, }, [CUSTOMER]: { [ACTIONS.REPORT_LAUNCH]: OWNER, [ACTIONS.ACTIONS_WITH_LAUNCH]: OWNER, [ACTIONS.MANUAL_ANALYSIS_EXPORT_COMPARE_IMPORT]: ALL, [ACTIONS.ACTIONS_WITH_ITEM]: OWNER, [ACTIONS.INVESTIGATION_ACTIONS]: ALL, [ACTIONS.CREATE_SHARE_ITEM]: OWNER, [ACTIONS.EDIT_DELETE_SHARED_ITEM]: OWNER, [ACTIONS.RERUN_LAUNCHES]: OWNER, [ACTIONS.CHANGE_STATUS]: ALL, }, };
JavaScript
0
@@ -2973,45 +2973,8 @@ ER,%0A - %5BACTIONS.RERUN_LAUNCHES%5D: OWNER,%0A
5746bcd3b30f14f315bb460017537b66c9845135
Fix requires of nodeca.loader
assets/js/nodeca/loader.js
assets/js/nodeca/loader.js
/** * nodeca.loader * * This module provides namespace assets loading for nodeca/nlib based * applcations. **/ //= depend_on nodeca //= require minimizer /*global window, $, _, Modernizr, yepnope, nodeca*/ (function () { 'use strict'; // list of already loaded assets // TODO: cache loaded assets in the LocalStorage var loaded = []; // Builds RegExp used to find assets for given namespace function build_namespace_regexp(namespace) { var locale = nodeca.runtime.locale, theme = nodeca.runtime.theme, parts = []; // common-wide parts.push('views/' + locale + '/' + theme + '/layouts.js'); parts.push('views/' + locale + '/' + theme + '/common.js'); parts.push('common/i18n/' + locale + '.js'); parts.push('common/app.(?:js|css)'); parts.push('app.(?:js|css)'); // namespace-specific parts.push('views/' + locale + '/' + theme + '/' + namespace + '.js'); parts.push(namespace + '/i18n/' + locale + '.js'); parts.push(namespace + 'app.(?:js|css)'); return new RegExp('^(?:' + parts.join('|') + ')$'); } // Returns list of assets that should be loaded by yepnope function find_assets(namespace) { var assets = [], regexp = build_namespace_regexp(namespace); _.each(nodeca.config.assets, function (digestPath, logicalPath) { if (-1 < loaded.indexOf(digestPath) && regexp.test(logicalPath)) { assets.push(nodeca.runtime.ASSETS_BASEURL + digestPath); } }); return assets; } // loader that requries assets for given namespace nodeca.load = function load(namespace, callback) { var assets = find_assets(namespace); // TODO: load assets from localStorage if some were found. // LocalStorage should be something like: // { <logicalPath>: [<digestPath>, <timestamp>, <data>] } yepnope({load: assets, complete: function () { loaded = loaded.concat(assets); callback(); }}); }; }());
JavaScript
0.000001
@@ -152,15 +152,15 @@ re m -inimize +oderniz r%0A%0A%0A
143fbe713e5aefc643c67448a996c3b1f049fef8
Fix blacks in following style
shared/searchv3/shared.js
shared/searchv3/shared.js
// @flow import * as Constants from '../constants/searchv3' import {globalColors} from '../styles' const followingStateToStyle = (followingState: Constants.FollowingState) => { return { Following: { color: globalColors.green2, }, NoState: { color: globalColors.black_40, }, NotFollowing: { color: globalColors.blue, }, You: { fontStyle: 'italic', color: globalColors.black, }, }[followingState] } export {followingStateToStyle}
JavaScript
0.999616
@@ -291,10 +291,10 @@ ack_ -40 +75 ,%0A @@ -426,16 +426,19 @@ rs.black +_75 ,%0A %7D,
a075aa0601e2c05e8630ff577d41939a6cdc41fa
Allow decimals for commission percentage
btcprice.js
btcprice.js
// Create global namespace for mybtcprice if (!window.mybtcprice) { window.mybtcprice = {}; } $(document).ready(function() { bitcoinprices.init({ // Where we get bitcoinaverage data url: "https://api.bitcoinaverage.com/ticker/all", // Which of bitcoinaverages value we use to present prices marketRateVariable: "last", // Which currencies are in shown to the user currencies: ["USD", "BTC"], // Special currency symbol artwork //symbols: { // "BTC": "<i class='fa fa-btc'>B</i>" //}, // Which currency we show user by the default if // no currency is selected defaultCurrency: "USD", // How the user is able to interact with the prices ux : { // Make everything with data-btc-price HTML attribute clickable clickPrices : true, // Build Bootstrap dropdown menu for currency switching menu : true, // Allow user to cycle through currency choices in currency: clickableCurrencySymbol: true }, // Allows passing the explicit jQuery version to bitcoinprices. // This is useful if you are using modular javascript (AMD/UMD/require()), // but for most normal usage you don't need this jQuery: jQuery, // Price source data attribute priceAttribute: "data-btc-price", // Price source currency for data-btc-price attribute. // E.g. if your shop prices are in USD // but converted to BTC when you do Bitcoin // checkout, put USD here. priceOrignalCurrency: "BTC" }); // Reload price on clicking "Refresh" $( "#refresh" ).click(function() { $('#refresh').text('Refreshing'); $('#time').text('Refreshing time'); bitcoinprices.loadData(); }); // What happens when the price is updated? $(document).bind("marketdataavailable", function() { myTime = new Date(bitcoinprices.data.timestamp); $('#time').text(myTime); $('#refresh').text('Refresh'); calculate(); }); // Trigger calculation on text change. $( "input" ).change(function() { calculate(this.name); }); $( "input" ).on('input', function() { calculate(this.name); }); // Rounding value to the nearest x function nearest(n, v) { n = n / v; n = Math.round(n) * v; return n; } // Rounding value to the x decimal function precision(n, dp) { dp = Math.pow(10, dp); n = n * dp; n = Math.round(n); n = n / dp; return n; } function init() { // Set the commission $("input[name='commission']").val(mybtcprice.commission); $("input[name='commission']").prop('disabled', mybtcprice.commission_locked); } // Calculate other fields based on the "change" parameter. // "change" is the name of the field which has changed. function calculate(change) { buy_amount_USD = Number($("input[name='buy_amount_USD']").val()); buy_amount_BTC = Number($("input[name='buy_amount_BTC']").val()); buy_amount_mBTC = Number($("input[name='buy_amount_mBTC']").val()); total_USD = Number($("input[name='total_USD']").val()); commission = Number($("input[name='commission']").val()); rate = bitcoinprices.data.USD.last; // If the user knows how much BTC they want. if (change == 'buy_amount_BTC') { // buy_amount_BTC * rate buy_amount_USD = precision(buy_amount_BTC * rate, 2); } if (change == 'buy_amount_mBTC') { // (buy_amount_mBTC / 1000) * rate buy_amount_USD = precision((buy_amount_mBTC / 1000) * rate, 2); } if (change != 'total_USD') { // buy_amount_USD * (1 + commission / 100) total_USD = nearest(buy_amount_USD / (1 - (commission / 100)), 1); total_USD = (total_USD <= buy_amount_USD && buy_amount_USD !== 0) ? total_USD + 5 : total_USD; $("input[name='total_USD']").val(total_USD); } if (change != 'buy_amount_USD') { // total_USD / (1 + commission / 100) buy_amount_USD = nearest(total_USD * (1 - (commission / 100)), 1); $("input[name='buy_amount_USD']").val(buy_amount_USD); } if (change != 'buy_amount_BTC' && change != 'buy_amount_mBTC') { // rate / buy_amount_USD buy_amount_BTC = precision(buy_amount_USD / rate, 8); $("input[name='buy_amount_BTC']").val(buy_amount_BTC); } if (change != 'buy_amount_BTC' && change == 'buy_amount_mBTC') { // buy_amount_mBTC / 1000 buy_amount_BTC = precision(buy_amount_mBTC / 1000, 8); $("input[name='buy_amount_BTC']").val(buy_amount_BTC); } if (change != 'buy_amount_mBTC') { // buy_amount_BTC * 1000 buy_amount_mBTC = precision(buy_amount_BTC * 1000, 8); $("input[name='buy_amount_mBTC']").val(buy_amount_mBTC); } // total_USD - buy_amount_USD $('#fee_total').text(total_USD - buy_amount_USD); } init(); });
JavaScript
0.001677
@@ -3634,32 +3634,35 @@ commission / 100 +.00 )), 1);%0A to @@ -3958,16 +3958,19 @@ on / 100 +.00 )), 1);%0A
6cef6a46b1664012098b2df60b6fa0e8d65e6ba8
Fix integer parsing that gave incorrect results
graph_ui/js/Graph.js
graph_ui/js/Graph.js
/** * Graph.js * * @author Andrew Bowler, Alberto Gomez-Estrada */ 'use strict'; var React = require('react'); var ReactDOM = require('react-dom'); var Vis = require('vis'); var Graph = React.createClass({ componentDidMount: function() { var element = ReactDOM.findDOMNode(this); this.setState({ network: new Vis.Network(element, this.props.graphData, this.props.options) }); }, hasFilterOptions: function() { if (this.props.filter) { return this.props.filter.property && this.props.filter.option && this.props.filter.value; } else return false; }, /** * If there are any filter options passed in, perform filtering. Otherwise do nothing. */ doFilter: function() { if(this.hasFilterOptions() && !this.isGraphEmpty()) { var property = this.props.filter.property; var nodeObjects = this.props.graphData.nodes; console.log(nodeObjects); var nodeIDs = this.props.graphData.nodes.get({returnType: 'Object'}); switch (this.props.filter.option) { case '>': for (var nodeID in nodeIDs) { if (this.props.graphData.nodes.get(nodeID)[property] > this.props.filter.value) { console.log(nodeObjects.get(nodeID)); nodeObjects.update({id: nodeID, color: 'red'}); console.log(nodeObjects.get(nodeID)); } } break; default: break; } } }, isGraphEmpty: function() { return this.props.graphData.nodes.length == 0 && this.props.graphData.edges.length == 0; }, shouldComponentUpdate: function(nextProps, nextState) { return (this.props.graphData != nextProps.graphData) || (this.props.filter != nextProps.filter); }, componentDidUpdate: function() { this.state.network.setData({ nodes: this.props.graphData.nodes, edges: this.props.graphData.edges }); this.doFilter(); this.state.network.on('selectNode', function(event) { var nodeID = event.nodes[0]; var node = this.state.network.body.data.nodes.get(nodeID); this.props.updateSelectedNode(node); }.bind(this)); // Called when Vis is finished drawing the graph this.state.network.on('afterDrawing', function(event) { this.props.logger('Graph finished drawing'); }.bind(this)); }, getDefaultProps: function() { return { options: { nodes: { shape: 'dot', fixed: true }, edges: { arrows: { to: { scaleFactor: 0.5 } }, smooth: { type: 'continuous' } }, physics: false, interaction: { dragNodes: false, } } } }, getInitialState: function() { return { network: {} }; }, render: function() { return (<div></div>); } }); module.exports = Graph;
JavaScript
0.028343
@@ -880,40 +880,8 @@ es;%0A - console.log(nodeObjects);%0A @@ -1060,28 +1060,47 @@ -if ( +var propertyToFilter = this.props.g @@ -1139,89 +1139,79 @@ rty%5D - %3E this.props.filter.value) %7B%0A console.log(nodeObjects.get(nodeID)); +;%0A if (parseInt(propertyToFilter) %3E this.props.filter.value) %0A @@ -1285,61 +1285,76 @@ - console.log(nodeObjects.get(nodeID));%0A %7D +else %0A nodeObjects.update(%7Bid: nodeID, color: 'gray'%7D); %0A @@ -2557,32 +2557,60 @@ %7D%0A %7D,%0A + color: '#848484',%0A smooth
4aadc3ff43ad9dab2a05e9830bc409100aaa043f
clean js
app/assets/javascripts/chaskiq/chaskiq.js
app/assets/javascripts/chaskiq/chaskiq.js
window.Chaskiq = { Helpers: {} } // Custom scripts $(document).ready(function () { // MetsiMenu $('#side-menu').metisMenu(); // Collapse ibox function $('.collapse-link').click( function() { var ibox = $(this).closest('div.ibox'); var button = $(this).find('i'); var content = ibox.find('div.ibox-content'); content.slideToggle(200); button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down'); ibox.toggleClass('').toggleClass('border-bottom'); setTimeout(function () { ibox.resize(); ibox.find('[id^=map-]').resize(); }, 50); }); // Close ibox function $('.close-link').click( function() { var content = $(this).closest('div.ibox'); content.remove(); }); // Small todo handler $('.check-link').click( function(){ var button = $(this).find('i'); var label = $(this).next('span'); button.toggleClass('fa-check-square').toggleClass('fa-square-o'); label.toggleClass('todo-completed'); return false; }); // Append config box / Only for demo purpose // $.get("skin-config.html", function (data) { // $('body').append(data); // }); // minimalize menu $('.navbar-minimalize').click(function () { $("body").toggleClass("mini-navbar"); SmoothlyMenu(); }) // tooltips $('.tooltip-demo').tooltip({ selector: "[data-toggle=tooltip]", container: "body" }) // Move modal to body // Fix Bootstrap backdrop issu with animation.css $('.modal').appendTo("body") // Full height of sidebar function fix_height() { var heightWithoutNavbar = $("body > #wrapper").height() - 61; $(".sidebard-panel").css("min-height", heightWithoutNavbar + "px"); } fix_height(); // Fixed Sidebar // unComment this only whe you have a fixed-sidebar // $(window).bind("load", function() { // if($("body").hasClass('fixed-sidebar')) { // $('.sidebar-collapse').slimScroll({ // height: '100%', // railOpacity: 0.9, // }); // } // }) $(window).bind("load resize click scroll", function() { if(!$("body").hasClass('body-small')) { fix_height(); } }) $("[data-toggle=popover]") .popover(); $('.input-group.date').datepicker({ todayBtn: "linked", keyboardNavigation: false, }); }); // For demo purpose - animation css script function animationHover(element, animation){ element = $(element); element.hover( function() { element.addClass('animated ' + animation); }, function(){ //wait for animation to finish before removing classes window.setTimeout( function(){ element.removeClass('animated ' + animation); }, 2000); }); } // Minimalize menu when screen is less than 768px $(function() { $(window).bind("load resize", function() { if ($(this).width() < 769) { $('body').addClass('body-small') } else { $('body').removeClass('body-small') } }) }) function SmoothlyMenu() { if (!$('body').hasClass('mini-navbar') || $('body').hasClass('body-small')) { // Hide menu in order to smoothly turn on when maximize menu $('#side-menu').hide(); // For smoothly turn on menu setTimeout( function () { $('#side-menu').fadeIn(400); }, 100); } else if ($('body').hasClass('fixed-sidebar')){ $('#side-menu').hide(); setTimeout( function () { $('#side-menu').fadeIn(400); }, 300); } else { // Remove all inline style from jquery fadeIn function to reset menu state $('#side-menu').removeAttr('style'); } } var sendFile; sendFile = function(file, callback) { var data; data = new FormData(); data.append("image", file); return $.ajax({ url: $('.summernote').data('upload-path'), data: data, cache: false, contentType: false, processData: false, type: 'POST', success: function(data) { return callback(data); } }); }; window.InitSummernote = function(){ $('.summernote').summernote({ toolbar: [ ['style', ['color', 'bold', 'italic', 'underline', 'fontsize']], ['font', ['strikethrough']], ['insert', ['picture', 'link']], ['fontsize', ['fontsize']], ['para', ['ul', 'ol', 'paragraph']], ] , onImageUpload: function(files, editor, $editable) { sendFile(files[0], function(data){ url = data.image.url console.log($editable) console.log(url) editor.insertImage($editable, url) }) //console.log('image upload:', files, editor, $editable); } }); }
JavaScript
0.000001
@@ -90,2294 +90,153 @@ // -MetsiMenu%0A $('#side-menu').metisMenu();%0A%0A // Collapse ibox function%0A $('.collapse-link').click( function() %7B%0A var ibox = $(this).closest('div.ibox');%0A var button = $(this).find('i');%0A var content = ibox.find('div.ibox-content');%0A content.slideToggle(200);%0A button.toggleClass('fa-chevron-up').toggleClass('fa-chevron-down');%0A ibox.toggleClass('').toggleClass('border-bottom');%0A setTimeout(function () %7B%0A ibox.resize();%0A ibox.find('%5Bid%5E=map-%5D').resize();%0A %7D, 50);%0A %7D);%0A%0A // Close ibox function%0A $('.close-link').click( function() %7B%0A var content = $(this).closest('div.ibox');%0A content.remove();%0A %7D);%0A%0A // Small todo handler%0A $('.check-link').click( function()%7B%0A var button = $(this).find('i');%0A var label = $(this).next('span');%0A button.toggleClass('fa-check-square').toggleClass('fa-square-o');%0A label.toggleClass('todo-completed');%0A return false;%0A %7D);%0A%0A // Append config box / Only for demo purpose%0A// $.get(%22skin-config.html%22, function (data) %7B%0A// $('body').append(data);%0A// %7D);%0A%0A // minimalize menu%0A $('.navbar-minimalize').click(function () %7B%0A $(%22body%22).toggleClass(%22mini-navbar%22);%0A SmoothlyMenu();%0A %7D)%0A%0A // tooltips%0A $('.tooltip-demo').tooltip(%7B%0A selector: %22%5Bdata-toggle=tooltip%5D%22,%0A container: %22body%22%0A %7D)%0A%0A // Move modal to body%0A // Fix Bootstrap backdrop issu with animation.css%0A $('.modal').appendTo(%22body%22)%0A%0A // Full height of sidebar%0A function fix_height() %7B%0A var heightWithoutNavbar = $(%22body %3E #wrapper%22).height() - 61;%0A $(%22.sidebard-panel%22).css(%22min-height%22, heightWithoutNavbar + %22px%22);%0A %7D%0A fix_height();%0A%0A // Fixed Sidebar%0A // unComment this only whe you have a fixed-sidebar%0A // $(window).bind(%22load%22, function() %7B%0A // if($(%22body%22).hasClass('fixed-sidebar')) %7B%0A // $('.sidebar-collapse').slimScroll(%7B%0A // height: '100%25',%0A // railOpacity: 0.9,%0A // %7D);%0A // %7D%0A // %7D)%0A%0A $(window).bind(%22load resize click scroll%22, function() %7B%0A if(!$(%22body%22).hasClass('body-small')) %7B%0A fix_height();%0A %7D%0A %7D) +Close ibox function%0A $('.close-link').click( function() %7B%0A var content = $(this).closest('div.ibox');%0A content.remove();%0A %7D); %0A%0A @@ -285,17 +285,16 @@ ver();%0A%0A -%0A $('. @@ -403,1442 +403,8 @@ ;%0A%0A%0A -// For demo purpose - animation css script%0Afunction animationHover(element, animation)%7B%0A element = $(element);%0A element.hover(%0A function() %7B%0A element.addClass('animated ' + animation);%0A %7D,%0A function()%7B%0A //wait for animation to finish before removing classes%0A window.setTimeout( function()%7B%0A element.removeClass('animated ' + animation);%0A %7D, 2000);%0A %7D);%0A%7D%0A%0A// Minimalize menu when screen is less than 768px%0A$(function() %7B%0A $(window).bind(%22load resize%22, function() %7B%0A if ($(this).width() %3C 769) %7B%0A $('body').addClass('body-small')%0A %7D else %7B%0A $('body').removeClass('body-small')%0A %7D%0A %7D)%0A%7D)%0A%0Afunction SmoothlyMenu() %7B%0A if (!$('body').hasClass('mini-navbar') %7C%7C $('body').hasClass('body-small')) %7B%0A // Hide menu in order to smoothly turn on when maximize menu%0A $('#side-menu').hide();%0A // For smoothly turn on menu%0A setTimeout(%0A function () %7B%0A $('#side-menu').fadeIn(400);%0A %7D, 100);%0A %7D else if ($('body').hasClass('fixed-sidebar'))%7B%0A $('#side-menu').hide();%0A setTimeout(%0A function () %7B%0A $('#side-menu').fadeIn(400);%0A %7D, 300);%0A %7D else %7B%0A // Remove all inline style from jquery fadeIn function to reset menu state%0A $('#side-menu').removeAttr('style');%0A %7D%0A%7D%0A%0A var
322942ca09d17123b18c711e1b9631d619806c35
Support \n EOL
bin/test.js
bin/test.js
#!/usr/bin/env node /** * Glayzzle : the PHP engine on NodeJS * * Copyright (C) 2014 Glayzzle * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * @url http://glayzzle.com * @license GNU-2 */ var util = require('util'); var fs = require('fs'); var path = require('path'); var engine = require('../main'); // help screen function printHelp() { util.puts('Usage: test [options] [-f] <file>'); util.puts(''); util.puts(' -f <file> Parse and test the specified file'); util.puts(' -d <path> Parse each file in the specified path'); util.puts(' -r Use recursivity with the specified path'); util.puts(' -h, --help Print help and exit'); } // aborts the execution with the specified error message function abort(message) { util.error(message); process.exit(1); } /* Arguments */ var options = { debug: 0, filename: null, path: null, recursive: false }; var args = process.argv.slice(2); // Trim 'node' and the script path. function isOption(arg) { return (/^-/).test(arg); } function nextArg() { args.shift(); } // Reading arguments while (args.length > 0 && isOption(args[0])) { switch(args[0]) { case '-f': nextArg(); options.filename = args[0]; break; case '--debug': nextArg(); options.debug = args[0]; break; case '-d': nextArg(); options.path = args[0]; break; case '-r': options.recusive = true; break; case '-h': case '--help': printHelp(); process.exit(0); break; default: abort('Unknown option: ' + args[0] + '.'); } nextArg(); } // Checking last parameters if ( args.length > 0 ) { if ( args.length == 1 && !options.filename ) { options.filename = args[0]; } else { abort('Too many arguments.'); } } if ( !options.filename && !options.path ) { abort('Expecting a filename or a path.'); } process.env.DEBUG = options.debug; // Load tests handlers var engines = [ require('./formats/parser') , require('./formats/phpt') , require('./formats/token') , require('./formats/php') , require('./formats/ast') ]; // gets the extension of the specified filename function getExtension(filename) { var i = filename.lastIndexOf('.'); return (i < 0) ? '' : filename.substr(i); } // run a test over the specified file function test(filename) { console.log(' + ' + filename); try { if (options.ast) { return engines[4].run( filename , engine ); } var extension = getExtension(filename); for(var i = 0; i<engines.length; i++) { if (engines[i].handles(filename, extension)) { if (engines[i].explode) { return engines[i].run( fs.readFileSync(filename).toString().split('\r\n') , filename , engine ); } else { return engines[i].run(filename, engine); } } } console.info('\n(i) IGNORED : unrecognized extension "'+getExtension(filename)+'" for ' + filename); return false; } catch(e) { util.error( (e.stack || e) + '\n' ); throw e; return false; } } // run tests console.log('\n*** START TESTING ***\n'); if (options.filename) { if (!test(options.filename)) { abort('Error: test FAILED !!!'); } else { console.log('Success'); } } else if (options.path) { var testFiles = function(path) { fs.readdir(path, function(err, files) { if (err) throw err; for(var i = 0; i < files.length; i ++) { var file = files[i]; if (file[0] != '.') { var stat = fs.statSync(path + file); if (!stat.isDirectory()) { test(path + file); } else if (options.recusive) { testFiles(path + file + '/'); } } } }); }; testFiles(options.path); }
JavaScript
0
@@ -3303,24 +3303,71 @@ on(filename) +,%0A isWin = /%5Ewin/.test(process.platform) ;%0A for(va @@ -3579,14 +3579,57 @@ lit( -'%5Cr%5Cn' +%0A isWin ? '%5Cr%5Cn' : '%5Cn'%0A )%0A
509d142e0fbb20942cc0ac3ecb64c15d2300c3cf
remove console.log
ui/cockpit/client/scripts/directives/processDiagram.js
ui/cockpit/client/scripts/directives/processDiagram.js
'use strict'; var fs = require('fs'); var template = fs.readFileSync(__dirname + '/processDiagram.html', 'utf8'); var angular = require('camunda-commons-ui/vendor/angular'); var DirectiveController = ['$scope', '$compile', 'Views', function( $scope, $compile, Views) { $scope.vars = { read: [ 'processData', 'bpmnElement', 'pageData', 'viewer' ] }; $scope.overlayProviders = Views.getProviders({ component: $scope.overlayProviderComponent }); var overlay = '<div class="bpmn-overlay"><div view ng-repeat="overlayProvider in overlayProviders" provider="overlayProvider" vars="vars"></div></div>'; var actions = '<ul><li view ng-repeat="actionProvider in actionProviders" provider="actionProvider" vars="vars"></li></ul>'; var bpmnElements, selection; $scope.$on('$destroy', function() { $scope.processDiagram = null; $scope.overlayProviders = null; }); $scope.control = {}; $scope.$on('collapse-change', function() { console.log('bpmn collapse change!'); $scope.control.resetZoom(); }); /** * If the process diagram changes, then the diagram will be rendered. */ $scope.$watch('processDiagram', function(newValue) { if (newValue && newValue.$loaded !== false) { bpmnElements = newValue.bpmnElements; $scope.diagramData = newValue.bpmnDefinition; } }); $scope.onLoad = function() { $scope.viewer = $scope.control.getViewer(); decorateDiagram($scope.processDiagram.bpmnElements); if ($scope.actionProviderComponent) { addActions(); } // update selection in case it has been provided earlier updateSelection(selection); }; var isElementSelectable = function(element) { return element.isSelectable || ( $scope.selectAll && element.$instanceOf('bpmn:FlowNode') ); }; $scope.onClick = function(element, $event) { safeApply(function() { if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) { $scope.onElementClick({id: element.businessObject.id, $event: $event}); } else { $scope.onElementClick({id: null, $event: $event}); } }); }; function safeApply(fn) { if (!$scope.$$phase) { $scope.$apply(fn); } else { fn(); } } $scope.onMouseEnter = function(element) { if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id])) { $scope.control.getViewer().get('canvas').addMarker(element.businessObject.id, 'selectable'); $scope.control.highlight(element.businessObject.id); } }; $scope.onMouseLeave = function(element) { if(bpmnElements[element.businessObject.id] && isElementSelectable(bpmnElements[element.businessObject.id]) && (!selection || selection.indexOf(element.businessObject.id) === -1) && (!selection || selection.indexOf(element.businessObject.id + '#multiInstanceBody') === -1)) { $scope.control.clearHighlight(element.businessObject.id); } }; /*------------------- Decorate diagram ---------------------*/ function decorateDiagram(bpmnElements) { angular.forEach(bpmnElements, decorateBpmnElement); } function decorateBpmnElement(bpmnElement) { var elem = $scope.control.getElement(bpmnElement.id); if(elem) { var childScope = $scope.$new(); childScope.bpmnElement = bpmnElement; var newOverlay = angular.element(overlay); newOverlay.css({ width: elem.width, height: elem.height }); $compile(newOverlay)(childScope); try { $scope.control.createBadge(bpmnElement.id, { html: newOverlay, position: { top: 0, left: 0 } }); } catch (exception) { // do nothing } } } /*------------------- Add actions ------------------------------------*/ function addActions() { $scope.actionProviders = Views.getProviders({ component: $scope.actionProviderComponent }); var actionElement = angular.element(actions); var childScope = $scope.$new(); $compile(actionElement)(childScope); $scope.control.addAction( { html : actionElement }); } /*------------------- Handle selected activity id---------------------*/ $scope.$watch('selection.activityIds', function(newValue) { updateSelection(newValue); }); function updateSelection(newSelection) { if ($scope.control.isLoaded()) { if (selection) { angular.forEach(selection, function(elementId) { if(elementId.indexOf('#multiInstanceBody') !== -1 && elementId.indexOf('#multiInstanceBody') === elementId.length - 18) { elementId = elementId.substr(0, elementId.length - 18); } if(bpmnElements[elementId]) { $scope.control.clearHighlight(elementId); } }); } if (newSelection) { angular.forEach(newSelection, function(elementId) { if(elementId.indexOf('#multiInstanceBody') !== -1 && elementId.indexOf('#multiInstanceBody') === elementId.length - 18) { elementId = elementId.substr(0, elementId.length - 18); } if(bpmnElements[elementId]) { $scope.control.highlight(elementId); } }); } } $scope.$root.$emit('instance-diagram-selection-change', newSelection); selection = newSelection; } /*------------------- Handle scroll to bpmn element ---------------------*/ $scope.$watch('selection.scrollToBpmnElement', function(newValue) { if (newValue) { scrollToBpmnElement(newValue); } }); function scrollToBpmnElement(bpmnElementId) { if ($scope.control.isLoaded() && bpmnElementId) { scrollTo(bpmnElementId); } } function scrollTo(elementId) { if(bpmnElements[elementId]) { $scope.control.scrollToElement(elementId); } } }]; var Directive = function() { return { restrict: 'EAC', scope: { processDiagram: '=', processDiagramOverlay: '=', onElementClick: '&', selection: '=', processData: '=', pageData: '=', overlayProviderComponent: '@', actionProviderComponent: '@', selectAll: '&' }, controller: DirectiveController, template: template, link: function($scope) { $scope.selectAll = $scope.$eval($scope.selectAll); } }; }; module.exports = Directive;
JavaScript
0.000001
@@ -961,50 +961,8 @@ ) %7B%0A - console.log('bpmn collapse change!');%0A
e175b07d0dba42a55c4a6c0b69130192b39c54de
add some extra modules to conform with the playback spec
src/chromecast_playback.js
src/chromecast_playback.js
import {Events, Log, Playback, template} from 'Clappr' import chromecastHTML from './public/chromecast.html' var TICK_INTERVAL = 100 export default class ChromecastPlayback extends Playback { get name() { return 'chromecast_playback' } get template() { return template(chromecastHTML) } get attributes() { return { class: 'chromecast-playback' } } constructor(options) { super(options) this.options = options this.src = options.src this.currentMedia = options.currentMedia this.mediaControl = options.mediaControl this.currentMedia.addUpdateListener(() => this.onMediaStatusUpdate()) } render() { var template = this.template() this.$el.html(template) if (this.options.poster) { this.$el.find('.chromecast-playback-background').css('background-image', 'url(' + this.options.poster + ')') } else { this.$el.find('.chromecast-playback-background').css('background-color', '#666') } } play() { this.currentMedia.play() } pause() { this.stopTimer() this.currentMedia.pause() } stop() { this.stopTimer() this.currentMedia.stop() } seek(time) { this.stopTimer() var request = new chrome.cast.media.SeekRequest() request.currentTime = time this.currentMedia.seek(request, () => this.startTimer(), () => Log.warn('seek failed')) } startTimer() { this.timer = setInterval(() => this.updateMediaControl(), TICK_INTERVAL) } stopTimer() { clearInterval(this.timer) this.timer = null } getDuration() { return this.currentMedia.media.duration } isPlaying() { return this.currentMedia.playerState === 'PLAYING' || this.currentMedia.playerState === 'BUFFERING' } onMediaStatusUpdate() { this.mediaControl.changeTogglePlay() if (this.isPlaying() && !this.timer) { this.startTimer() } if (this.currentMedia.playerState === 'BUFFERING') { this.isBuffering = true this.trigger(Events.PLAYBACK_BUFFERING, this.name) } else if (this.currentMedia.playerState === 'PLAYING') { if (this.isBuffering) { this.isBuffering = false this.trigger(Events.PLAYBACK_BUFFERFULL, this.name) } this.trigger(Events.PLAYBACK_PLAY, this.name) } else if (this.currentMedia.playerState === 'IDLE') { if (this.isBuffering) { this.isBuffering = false this.trigger(Events.PLAYBACK_BUFFERFULL, this.name) } this.trigger(Events.PLAYBACK_ENDED, this.name) } } updateMediaControl() { var position = this.currentMedia.getEstimatedTime() var duration = this.currentMedia.media.duration this.trigger(Events.PLAYBACK_TIMEUPDATE, {current: position, total: duration}, this.name) } show() { this.$el.show() } hide() { this.$el.hide() } }
JavaScript
0
@@ -103,19 +103,21 @@ .html'%0A%0A -var +const TICK_IN @@ -353,16 +353,49 @@ k' %7D %7D%0A%0A + get isReady() %7B return true %7D%0A%0A constr @@ -648,16 +648,366 @@ date())%0A + this.settings = options.settings%0A let noVolume = (name) =%3E name != 'volume'%0A this.settings.default && (this.settings.default = this.settings.default.filter(noVolume))%0A this.settings.left && (this.settings.left = this.settings.left.filter(noVolume))%0A this.settings.right && (this.settings.right = this.settings.right.filter(noVolume))%0A %7D%0A%0A r @@ -1020,19 +1020,19 @@ ) %7B%0A -var +let templat @@ -1555,19 +1555,19 @@ r()%0A -var +let request @@ -1735,24 +1735,199 @@ led'))%0A %7D%0A%0A + seekPercentage(percentage) %7B%0A if (percentage %3E= 0 && percentage %3C= 100) %7B%0A let duration = this.getDuration()%0A this.seek(percentage * duration / 100)%0A %7D%0A %7D%0A%0A startTimer @@ -2278,16 +2278,124 @@ G'%0A %7D%0A%0A + getPlaybackType() %7B%0A return this.currentMedia.streamType == 'LIVE' ? Playback.LIVE : Playback.VOD%0A %7D%0A%0A onMedi @@ -3199,19 +3199,19 @@ ) %7B%0A -var +let positio @@ -3259,11 +3259,11 @@ -var +let dur
ff378128375647a858e5b7c35106188c63eee1ba
update tabswitch
assets/js/src/tabswitch.js
assets/js/src/tabswitch.js
/*! * tab indicator animation * requires bootstrap's (v4.0.0-alpha.3) tab.js */ const Tabswitch = (($) => { // constants >>> const DATA_KEY = 'md.tabswitch'; const NAME = 'tabswitch'; const NO_CONFLICT = $.fn[NAME]; const TRANSITION_DURATION = 450; const ClassName = { ANIMATE : 'animate', IN : 'in', INDICATOR : 'nav-tabs-indicator', MATERIAL : 'nav-tabs-material', REVERSE : 'reverse', SCROLLABLE : 'nav-tabs-scrollable' }; const Event = { SHOW_BS_TAB : 'show.bs.tab' }; const Selector = { DATA_TOGGLE : '.nav-tabs [data-toggle="tab"]', TAB_NAV : '.nav-tabs' }; // <<< constants class Tabswitch { constructor(nav) { if (typeof $.fn.tab === 'undefined') { throw new Error('Material\'s JavaScript requires Bootstrap\'s tab.js'); }; this._nav = nav; this._navindicator = null; } switch(element, relatedTarget) { let supportsTransition = Util.supportsTransitionEnd(); if (!this._navindicator) { this._createIndicator(); } let elLeft = $(element).offset().left; let elWidth = $(element).outerWidth(); let navLeft = $(this._nav).offset().left; let navScrollLeft = $(this._nav).scrollLeft(); let navWidth = $(this._nav).outerWidth(); if (relatedTarget !== undefined) { let relatedLeft = $(relatedTarget).offset().left; let relatedWidth = $(relatedTarget).outerWidth(); $(this._navindicator).css({ left : ((relatedLeft + navScrollLeft) - navLeft), right : (navWidth - ((relatedLeft + navScrollLeft) - navLeft + relatedWidth)) }); $(this._navindicator).addClass(ClassName.IN); Util.reflow(this._navindicator); if (supportsTransition) { $(this._navindicator).addClass(ClassName.ANIMATE); if (relatedLeft > elLeft) { $(this._navindicator).addClass(ClassName.REVERSE); } } } $(this._navindicator).css({ left : ((elLeft + navScrollLeft) - navLeft), right : (navWidth - ((elLeft + navScrollLeft) - navLeft + elWidth)) }); let complete = () => { $(this._navindicator).removeClass(ClassName.ANIMATE).removeClass(ClassName.IN).removeClass(ClassName.REVERSE); } if (!supportsTransition) { complete(); return; } $(this._navindicator) .one(Util.TRANSITION_END, complete) .emulateTransitionEnd(TRANSITION_DURATION); } _createIndicator() { this._navindicator = document.createElement('div'); $(this._navindicator) .addClass(ClassName.INDICATOR) .appendTo(this._nav); $(this._nav).addClass(ClassName.MATERIAL); } static _jQueryInterface(relatedTarget) { return this.each(function () { let nav = $(this).closest(Selector.TAB_NAV)[0]; if (!nav) { return; } let data = $(nav).data(DATA_KEY); if (!data) { data = new Tabswitch(nav); $(nav).data(DATA_KEY, data); } data.switch(this, relatedTarget); }); } } $(document).on(Event.SHOW_BS_TAB, Selector.DATA_TOGGLE, function (event) { Tabswitch._jQueryInterface.call($(event.target), event.relatedTarget); }); $.fn[NAME] = Tabswitch._jQueryInterface; $.fn[NAME].Constructor = Tabswitch; $.fn[NAME].noConflict = function () { $.fn[NAME] = NO_CONFLICT; return Tabswitch._jQueryInterface; }; return Tabswitch; })(jQuery);
JavaScript
0.000001
@@ -81,25 +81,25 @@ */%0Aconst Tab -s +S witch = (($) @@ -741,25 +741,25 @@ %0A class Tab -s +S witch %7B%0A @@ -3154,25 +3154,25 @@ ta = new Tab -s +S witch(nav);%0A @@ -3364,25 +3364,25 @@ t) %7B%0A Tab -s +S witch._jQuer @@ -3469,25 +3469,25 @@ = Tab -s +S witch._jQuer @@ -3524,25 +3524,25 @@ ructor = Tab -s +S witch;%0A $.f @@ -3617,25 +3617,25 @@ return Tab -s +S witch._jQuer @@ -3664,17 +3664,17 @@ turn Tab -s +S witch;%0A%7D
51c531a8a8bd7bcf93e08e7876badf2d6ec87d37
change arrow
assets/js/pages/search.js
assets/js/pages/search.js
var currentPackage = 1; var currentFunction = 1; function reloadPackages(){ $.ajax({ url: "/api/searchpackages?"+window.location.href.slice(window.location.href.indexOf('?') + 1)+ "&page=" + currentPackage, context: document.body }).done(function(result){ $('.packagedata').empty(); $('.packagepages').empty(); for(var i = 0; i < result.packages.length; i++) { var hit = result.packages[i]; var versionURI = '/packages/' + encodeURIComponent(hit.fields.package_name) + '/versions/' + encodeURIComponent(hit.fields.version); var html =""; html += "<section class='search-result--item'>"; html += "<h5 class=\"search-result--item-header\">"; html += "Package "; html += "<a href=" + versionURI +'>'+hit.fields.package_name+'&nbsp;v'+hit.fields.version+'</a>'; html += "</h5>"; html += "<dl>"; for(highlight in hit.highlight) { html += "<dt>"+highlight+"</dt>"; html += "<dd>"+hit.highlight[highlight].toString()+"</dd>"; } html += "</dl>"; html += "</section>"; $('.packagedata').append(html); } if(currentPackage>1){ $('.packagepages') .append("<a class=\'resultarrow left\'><i class=\"fa fa-chevron-left\"></i>Previous Results </a>"); $('.packagepages .left').click(function(){ currentPackage--; reloadPackages(); }); } $('.packagepages') .append("<a class='resultarrow pull-right right'>Next Results <i class=\"fa fa-chevron-right\"></i></a>"); $('.packagepages .right').click(function(){ currentPackage++; reloadPackages(); }); }); }; function reloadFunctions(){ $.ajax({ url: "/api/searchfunctions?"+window.location.href.slice(window.location.href.indexOf('?') + 1)+ "&page=" + currentFunction, context: document.body }).done(function(result){ $('.functiondata').empty(); $('.functionpages').empty(); for(var i = 0; i < result.functions.length; i++) { var hit = result.functions[i]; var versionURI = '/packages/' + encodeURIComponent(hit.fields.package_name) + '/versions/' + encodeURIComponent(hit.fields.version); var html =""; html += "<section class='search-result--item'>"; html += "<h5 class=\"search-result--item-header\">"; html += "Function "; html += "<a href=" + versionURI + '/topics/' + encodeURIComponent(hit.fields.name) +'>'+hit.fields.name+'</a>'; html += "<span><a href="+ versionURI +'> ['+ hit.fields.package_name +'&nbsp;v'+ hit.fields.version +']</a></span>'; html += "</h5>"; html += "<dl>"; for(highlight in hit.highlight) { html += "<dt>"+highlight+"</dt>"; html += "<dd>"+hit.highlight[highlight].toString()+"</dd>"; } html += "</dl>"; html += "</section>"; $('.functiondata').append(html); } if(currentFunction>1){ $('.functionpages') .append("<a class=\'resultarrow left\'><i class=\"fa fa-chevron-left\"></i>Previous Results </a>"); $('.functionpages .left').click(function(){ currentFunction--; reloadFunctions(); }); } $('.functionpages') .append("<a class='resultarrow pull-right right'>Next Results <i class=\"fa fa-chevron-right\"></i></a>"); $('.functionpages .right').click(function(){ currentFunction++; reloadFunctions(); }); }); }; $(document).ready(function() { reloadPackages(); reloadFunctions(); $("#packagetab").attr("href",document.location.href+"#packages"); $("#functiontab").attr("href",document.location.href+"#functions"); $("#searchtabs").tabs(); });
JavaScript
0.000015
@@ -1323,32 +1323,33 @@ vron-left%5C%22%3E%3C/i%3E + Previous Results @@ -3150,16 +3150,17 @@ t%5C%22%3E%3C/i%3E + Previous
03759e57e1f999e98e8ca2167c590a8661d864f1
Comment out paste plain text line and give the option to paste with formatting.
app/assets/javascripts/ckeditor/config.js
app/assets/javascripts/ckeditor/config.js
CKEDITOR.editorConfig = function( config ) { config.allowedContent = true; config.removeFormatTags = ""; config.protectedSource.push(/<r:([\S]+).*<\/r:\1>/g); config.protectedSource.push(/<r:[^>/]*\/>/g); config.forcePasteAsPlainText = true; // if you want to remove clipboard, you have to remove all of these: // clipboard, pastetext, pastefromword config.removePlugins = "save, newpage, preview, print, templates, forms, flash, smiley, language, pagebreak, iframe, bidi"; var startupMode = $.cookie('ckeditor.startupMode'); if (startupMode == 'source' || startupMode == 'wysiwyg' ) { config.startupMode = startupMode; } this.on('mode', function(){ $.cookie('ckeditor.startupMode', this.mode); }) };
JavaScript
0
@@ -206,18 +206,57 @@ %5C/%3E/g);%0A -%0A + //let paste from word be available%0A // config. @@ -275,27 +275,28 @@ PlainText = -tru +fals e;%0A // if y
946541a0dc299ff3cfa537f45c2b61a2acee4725
use named exports
src/js/conversion.js
src/js/conversion.js
import mapConstants from './mapConstants'; const lerp = (minVal, maxVal, pos_r) => pos_r * (maxVal - minVal) + minVal; const reverseLerp = (minVal, maxVal, pos) => (pos - minVal) / (maxVal - minVal); const latLonToWorld = coordinate => { const x_r = lerp(mapConstants.map_x_boundaries[0], mapConstants.map_x_boundaries[1], coordinate[0] / mapConstants.map_w), y_r = lerp(mapConstants.map_y_boundaries[0], mapConstants.map_y_boundaries[1], (mapConstants.map_h - coordinate[1]) / mapConstants.map_h); return [x_r, y_r]; } const worldToLatLon = coordinate => { const x = reverseLerp(mapConstants.map_x_boundaries[0], mapConstants.map_x_boundaries[1], coordinate[0]) * mapConstants.map_w, y = mapConstants.map_h - reverseLerp(mapConstants.map_y_boundaries[0], mapConstants.map_y_boundaries[1], coordinate[1]) * mapConstants.map_h; return [x, y]; } const getTileRadius = r => parseInt(Math.floor(r / 64)); const getScaledRadius = r => r / (mapConstants.map_x_boundaries[1] - mapConstants.map_x_boundaries[0]) * mapConstants.map_w; const calculateDistance = (order, units, measure) => { if (order == 1) { if (units == "km") { return measure * mapConstants.scale * 1000; } return measure * mapConstants.scale; } return measure * mapConstants.scale; } export { lerp, reverseLerp, latLonToWorld, worldToLatLon, getTileRadius, getScaledRadius, calculateDistance }
JavaScript
0.002851
@@ -37,16 +37,23 @@ ants';%0A%0A +export const le @@ -121,16 +121,23 @@ inVal;%0A%0A +export const re @@ -206,24 +206,31 @@ - minVal);%0A%0A +export const latLon @@ -550,24 +550,31 @@ r, y_r%5D;%0A%7D%0A%0A +export const worldT @@ -902,16 +902,23 @@ y%5D;%0A%7D%0A%0A +export const ge @@ -967,16 +967,23 @@ 64));%0A%0A +export const ge @@ -1100,16 +1100,23 @@ map_w;%0A%0A +export const ca @@ -1376,143 +1376,4 @@ e;%0A%7D -%0A%0Aexport %7B%0A lerp,%0A reverseLerp,%0A latLonToWorld,%0A worldToLatLon,%0A getTileRadius,%0A getScaledRadius,%0A calculateDistance%0A%7D
8aa297915064b1f3c0c9de8d07028ded9f6ce3a0
Remove duplicated code
polyfill.js
polyfill.js
'use strict'; var d = require('d/d') , defineProperties = Object.defineProperties , generateName, Symbol; generateName = (function () { var created = Object.create(null); return function (desc) { var postfix = 0; while (created[desc + (postfix || '')]) ++postfix; desc += (postfix || ''); created[desc] = true; return '@@' + desc; }; }()); module.exports = Symbol = function (description) { if (!(this instanceof Symbol)) return new Symbol(description); description = (description === undefined ? '' : String(description)); return defineProperties(this, { __description__: d('', description), __name__: d('', generateName(description)) }); }; Object.defineProperties(Symbol, { create: d('', new Symbol('create')), hasInstance: d('', new Symbol('hasInstance')), isConcatSpreadable: d('', new Symbol('isConcatSpreadable')), isRegExp: d('', new Symbol('isRegExp')), iterator: d('', new Symbol('iterator')), toPrimitive: d('', new Symbol('toPrimitive')), toStringTag: d('', new Symbol('toStringTag')), unscopables: d('', new Symbol('unscopables')) }); defineProperties(Symbol.prototype, { properToString: d(function () { return 'Symbol (' + this.__description__ + ')'; }), toString: d('', function () { return this.__name__; }) }); Object.defineProperty(Symbol.prototype, 'originalToString', d(function () { return 'Symbol (' + this.__description__ + ')'; })); Object.defineProperty(Symbol.prototype, Symbol.toPrimitive, d('', function (hint) { throw new TypeError("Conversion of symbol objects is not allowed"); })); Object.defineProperty(Symbol.prototype, Symbol.toStringTag, d('c', 'Symbol'));
JavaScript
0.002603
@@ -1269,138 +1269,8 @@ %7D);%0A -Object.defineProperty(Symbol.prototype, 'originalToString', d(function () %7B%0A%09return 'Symbol (' + this.__description__ + ')';%0A%7D));%0A Obje
472b217391c918f915797e83e1e39d487bcca086
Use nns after drag and drop
src/js/mylibs/map.js
src/js/mylibs/map.js
window.Map = function (divId) { this.divId = divId; }; _.extend(window.Map.prototype, { map: null, dataLayer: null, currentRouteString: null, routeFeature: null, getMap: function () { return this.map; }, /** * Initialize and draw map */ draw: function () { OpenLayers.ImgPath = "img/openlayers/"; this.map = new OpenLayers.Map("map", { projection: new OpenLayers.Projection("EPSG:4326") }); var mapLayer = new OpenLayers.Layer.OSM("OSM Tiles", "http://gerbera.informatik.uni-stuttgart.de/osm/tiles/${z}/${x}/${y}.png", { numZoomLevels: 19 }); /* add maplayer and set center of the map */ this.map.addLayer(mapLayer); /* create and add a layer for markers */ this.dataLayer = new OpenLayers.Layer.Vector("Markers"); this.map.addLayer(this.dataLayer); this.map.setCenter(new OpenLayers.LonLat(1169980, 6640717), 6); var that = this; var selectFeature = new OpenLayers.Control.SelectFeature(this.dataLayer, { hover: true, callbacks: { over: function (feature) { feature.style.graphicOpacity = 1; this.layer.drawFeature(feature); }, out: function (feature) { feature.style.graphicOpacity = 0.7; this.layer.drawFeature(feature); } } }); this.map.addControl(selectFeature); selectFeature.activate(); var controlFeature = new OpenLayers.Control.DragFeature(this.dataLayer, { //geometryTypes: ['OpenLayers.Feature.Vector'], onStart: function(feature) { window.mapModel.setDataViewMarker(feature.data.mark); }, onComplete: function(feature, pix) { var lonlat = this.map.getLonLatFromPixel(pix); feature.data.mark.set({ lonlat: lonlat }); } }); this.map.addControl(controlFeature); controlFeature.activate(); }, /** * Resets all Routes drawed in the vectorLayer */ resetRoute: function () { if (!_.isNull(this.routeFeature)) this.dataLayer.removeFeatures([this.routeFeature]); this.currentRouteString = this.routeFeature = null; }, /** * Reset all Markers drawed in dataLayer */ resetMarkers: function () { // - remove all features (route and markers) // - then draw route back this.dataLayer.removeAllFeatures(); if (!_.isNull(this.routeFeature)) this.dataLayer.addFeatures(this.routeFeature); }, /** * Forces Map to update itself. * Needed, when the div of this map getting resized */ refresh: function () { this.map.updateSize(); }, /** * Draw markers given in markList */ drawMarkers: function () { var markList = window.markList; for (var i = 0; i < markList.length; i++) { var mark = markList.at(i); var size = new OpenLayers.Size(21, 25); // Icons generated with: http://mapicons.nicolasmollet.com/numbers-letters/?style=default&custom_color=e89733 var iconPath = 'img/mark.png'; if (i === 0) { iconPath = 'img/startmark.png'; } else if (i == markList.length - 1) { iconPath = 'img/targetmark.png'; } var feature = new OpenLayers.Feature.Vector( new OpenLayers.Geometry.Point(mark.get('lonlat').lon, mark.get('lonlat').lat), {mark: mark}, {externalGraphic: iconPath, graphicHeight: size.h, graphicWidth: size.w, graphicXOffset: -(size.w/2), graphicYOffset: -size.h, graphicOpacity: 0.7 } ); this.dataLayer.addFeatures(feature); } }, /** * Draws the route defined by list of vertices * PARAM: List of Vertices */ drawRoute: function (vertexString) { // exit, when there is nothing to parse if (_.isNull(vertexString) || _.isUndefined(vertexString) || vertexString.length === 0) return; // parse string of vertices var pointList = []; if (_.isString(vertexString)) vertexString = JSON.parse(vertexString); var proj = new OpenLayers.Projection("EPSG:4326"); for (var i = 0; i < vertexString.way.length; i++) { // transform points var p = vertexString.way[i]; var point = new OpenLayers.Geometry.Point(p.ln / 1e7, p.lt / 1e7); point.transform(proj, this.map.getProjectionObject()); pointList.push(point); } //this.drawMarkers(); // draw route on a layer and add it to map var geometry = new OpenLayers.Geometry.LineString(pointList); this.routeFeature = new OpenLayers.Feature.Vector(geometry, null, { strokeColor: "#0000ff", strokeOpacity: 1.7, strokeWidth: 2.5 }); this.dataLayer.addFeatures(this.routeFeature); this.currentRouteString = vertexString; }, setCenter: function(lonlat, bb) { this.map.setCenter(this.transformFrom1984(new OpenLayers.LonLat(lonlat.lon, lonlat.lat))); if (arguments.length >= 2) { var bounds = new OpenLayers.Bounds(bb[2], bb[0], bb[3], bb[1]).transform(new OpenLayers.Projection("EPSG:4326"), this.map.getProjectionObject()); this.map.zoomToExtent(bounds); } }, /** * Zoom into map, so that the whole route is visible */ zoomToRoute: function() { if (!_.isNull(this.dataLayer.getDataExtent())) { this.map.zoomToExtent(this.dataLayer.getDataExtent()); } }, getLonLatFromPos: function (posX, posY) { var pixel = new OpenLayers.Pixel(posX, posY); var lonlat = this.map.getLonLatFromPixel(pixel); // convert to "correct" projection var proj = new OpenLayers.Projection("EPSG:4326"); lonlat.transform(this.map.getProjectionObject(), proj); return lonlat; }, transformTo1984: function (lonlat) { var proj = new OpenLayers.Projection("EPSG:4326"); var lonlatClone = lonlat.clone(); lonlatClone.transform(this.map.getProjectionObject(), proj); return lonlatClone; }, transformFrom1984: function (lonlat) { var proj = new OpenLayers.Projection("EPSG:4326"); var lonlatClone = lonlat.clone(); lonlatClone.transform(proj, this.map.getProjectionObject()); return lonlatClone; } });
JavaScript
0
@@ -2057,32 +2057,90 @@ %7D);%0A + feature.data.mark.findNearestNeighbour();%0A %7D%0A
a4ce12b9c2671be6788d4c36f888296e92f5f579
fix wrong variable `originServerPath`/`originClientPath`
lib/components/protobuf.js
lib/components/protobuf.js
var fs = require('fs'); var path = require('path'); var protobuf = require('pomelo-protobuf'); var Constants = require('../util/constants'); var crypto = require('crypto'); var logger = require('pomelo-logger').getLogger('pomelo', __filename); module.exports = function(app, opts) { return new Component(app, opts); }; var Component = function(app, opts) { this.app = app; opts = opts || {}; this.watchers = {}; this.serverProtos = {}; this.clientProtos = {}; this.version = ""; var env = app.get(Constants.RESERVED.ENV); var originServerPath = path.join(app.getBase(), Constants.FILEPATH.SERVER_PROTOS); var presentServerPath = path.join(Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.SERVER_PROTOS)); var originClientPath = path.join(app.getBase(), Constants.FILEPATH.CLIENT_PROTOS); var presentClientPath = path.join(Constants.FILEPATH.CONFIG_DIR, env, path.basename(Constants.FILEPATH.CLIENT_PROTOS)); this.serverProtosPath = opts.serverProtos || (fs.existsSync(originClientPath) ? Constants.FILEPATH.SERVER_PROTOS : presentServerPath); this.clientProtosPath = opts.clientProtos || (fs.existsSync(originServerPath) ? Constants.FILEPATH.CLIENT_PROTOS : presentClientPath); this.setProtos(Constants.RESERVED.SERVER, path.join(app.getBase(), this.serverProtosPath)); this.setProtos(Constants.RESERVED.CLIENT, path.join(app.getBase(), this.clientProtosPath)); protobuf.init({encoderProtos:this.serverProtos, decoderProtos:this.clientProtos}); }; var pro = Component.prototype; pro.name = '__protobuf__'; pro.encode = function(key, msg) { return protobuf.encode(key, msg); }; pro.encode2Bytes = function(key, msg) { return protobuf.encode2Bytes(key, msg); }; pro.decode = function(key, msg) { return protobuf.decode(key, msg); }; pro.getProtos = function() { return { server : this.serverProtos, client : this.clientProtos, version : this.version }; }; pro.getVersion = function() { return this.version; }; pro.setProtos = function(type, path) { if(!fs.existsSync(path)) { return; } if(type === Constants.RESERVED.SERVER) { this.serverProtos = protobuf.parse(require(path)); } if(type === Constants.RESERVED.CLIENT) { this.clientProtos = protobuf.parse(require(path)); } var protoStr = JSON.stringify(this.clientProtos) + JSON.stringify(this.serverProtos); this.version = crypto.createHash('md5').update(protoStr).digest('base64'); //Watch file var watcher = fs.watch(path, this.onUpdate.bind(this, type, path)); if (this.watchers[type]) { this.watchers[type].close(); } this.watchers[type] = watcher; }; pro.onUpdate = function(type, path, event) { if(event !== 'change') { return; } var self = this; fs.readFile(path, 'utf8' ,function(err, data) { try { var protos = protobuf.parse(JSON.parse(data)); if(type === Constants.RESERVED.SERVER) { protobuf.setEncoderProtos(protos); self.serverProtos = protos; } else { protobuf.setDecoderProtos(protos); self.clientProtos = protos; } var protoStr = JSON.stringify(self.clientProtos) + JSON.stringify(self.serverProtos); self.version = crypto.createHash('md5').update(protoStr).digest('base64'); logger.info('change proto file , type : %j, path : %j, version : %j', type, path, self.version); } catch(e) { logger.warn("change proto file error! path : %j", path); logger.warn(e); } }); }; pro.stop = function(force, cb) { for (var type in this.watchers) { this.watchers[type].close(); } this.watchers = {}; process.nextTick(cb); };
JavaScript
0
@@ -1015,30 +1015,30 @@ sSync(origin -Client +Server Path) ? Cons @@ -1148,38 +1148,38 @@ xistsSync(origin -Server +Client Path) ? Constant
5bda6891f6e699a8d1f0bdc626972031a745de71
Replace persistent border after un-show-all (#452)
src/code/elementFocuser.js
src/code/elementFocuser.js
import { defaultBorderSettings } from './defaults' export default function ElementFocuser(doc, borderDrawer) { const momentaryBorderTime = 2000 let borderType = defaultBorderSettings.borderType // cached for simplicity let managingBorders = true // draw and remove borders by default let currentElementInfo = null let borderRemovalTimer = null // // Options handling // // Take a local copy of the border type option at the start (this means // that 'gets' of options don't need to be done asynchronously in the rest // of the code). browser.storage.sync.get(defaultBorderSettings, function(items) { borderType = items['borderType'] }) browser.storage.onChanged.addListener(function(changes) { if ('borderType' in changes) { borderType = changes.borderType.newValue ?? defaultBorderSettings.borderType borderTypeChange() } }) // // Public API // // Set focus on the selected landmark element. It takes an element info // object, as returned by the various LandmarksFinder functions. // // Note: this should only be called if landmarks were found. The check // for this is done in the main content script, as it involves UI // activity, and couples finding and focusing. this.focusElement = function(elementInfo) { if (managingBorders) this.clear() // Ensure that the element is focusable const originalTabindex = elementInfo.element.getAttribute('tabindex') if (originalTabindex === null || originalTabindex === '0') { elementInfo.element.setAttribute('tabindex', '-1') } elementInfo.element.scrollIntoView() // always go to the top of it elementInfo.element.focus() // Add the border and set a timer to remove it (if required by user) if (managingBorders && borderType !== 'none') { borderDrawer.addBorder(elementInfo) if (borderType === 'momentary') { clearTimeout(borderRemovalTimer) borderRemovalTimer = setTimeout(function() { borderDrawer.removeBorderOn(currentElementInfo.element) }, momentaryBorderTime) } } // Restore tabindex value if (originalTabindex === null) { elementInfo.element.removeAttribute('tabindex') } else if (originalTabindex === '0') { elementInfo.element.setAttribute('tabindex', '0') } currentElementInfo = elementInfo } // By default, this object will ask for borders to be drawn and removed // according to user preferences (and reflect changes in preferences). If // it shouldn't (i.e. because all borders are being shown, and managed by // other code) then this can be turned off - though it will still manage // element focusing. this.manageBorders = function(canManageBorders) { managingBorders = canManageBorders if (!canManageBorders) { clearTimeout(borderRemovalTimer) } } this.isManagingBorders = function() { return managingBorders } this.clear = function() { if (currentElementInfo) { resetEverything() } } // When the document is changed, the currently-focused element may have // been removed, or at least changed size/position. // Note: this doesn't call the border drawer to refresh all borders, as // this object is mainly concerned with just the current one, but // after a mutation, any borders that are drawn should be refreshed. this.refreshFocusedElement = function() { if (currentElementInfo) { if (!doc.body.contains(currentElementInfo.element)) { resetEverything() } } } // // Private API // // Used internally when we know we have a currently selected element function resetEverything() { clearTimeout(borderRemovalTimer) borderDrawer.removeBorderOn(currentElementInfo.element) currentElementInfo = null } // Should a border be added/removed? function borderTypeChange() { if (currentElementInfo && managingBorders) { if (borderType === 'persistent') { borderDrawer.addBorder(currentElementInfo) } else { borderDrawer.removeBorderOn(currentElementInfo.element) } } } }
JavaScript
0.000001
@@ -2751,16 +2751,222 @@ lTimer)%0A +%09%09%7D else if (borderType === 'persistent') %7B%0A%09%09%09// When we stop showing all landmarks at once, ensure the last%0A%09%09%09// single one is put back if it was permanent.%0A%09%09%09borderDrawer.addBorder(currentElementInfo)%0A %09%09%7D%0A%09%7D%0A%0A
4584944de13b3db5e9fd3938b0f9588d5a95ed76
Add featureStory header to listview in Home
simul/app/components/home.js
simul/app/components/home.js
import React, { Component } from 'react'; import { StyleSheet, Text, View, ListView, TouchableHighlight, } from 'react-native'; import Search from './search.js' class Home extends Component{ constructor(props) { super(props); const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2}); this.state = { dataSource: ds.cloneWithRows([ 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli','Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli', 'Bilbo', 'Aragorn', 'Frodo', 'Legolas', 'Saruman', 'Elrond', 'Smeagol', 'Gimli' ]) }; } _onPressLogin() { } _onPressRegister() { } _onPressStory() { // this.props.navigator.push({ // title: 'Story', // component: Story // }) } render() { return ( <View style={styles.container}> <Text style={styles.title}>HOME YA</Text> <TouchableHighlight onPress={ () => this._onPressLogin()}><Text style={styles.nav}>Login</Text></TouchableHighlight> <TouchableHighlight onPress={ () => this._onPressRegister()}><Text style={styles.nav}>Register</Text></TouchableHighlight> <ListView style={styles.listItems} dataSource={this.state.dataSource} renderRow={(rowData) => <TouchableHighlight onPress={ () => this._onPressStory()}><Text style={ styles.listText}>{rowData}</Text></TouchableHighlight>} renderHeader={ () => <Search />} /> </View> ) } }; var styles = StyleSheet.create({ container: { flex: 1, flexDirection: 'column', backgroundColor: '#27c2dc', paddingTop: 22, }, title: { flex: .5, backgroundColor: 'white', fontSize: 20, textAlign: 'center', }, listItems: { flex: 9, backgroundColor: 'powderblue', }, listText: { color: '#32161F', textAlign: 'center', }, nav: { flex: .25, alignItems: 'center', color: 'white', fontFamily: 'Farah', backgroundColor: '#FFB30F', textAlign: 'center', } }); module.exports = Home;
JavaScript
0
@@ -1060,16 +1060,339 @@ %7D)%0A %7D%0A%0A + featuredStory() %7B%0A return(%0A %3CView style=%7B%7BbackgroundColor: 'lightgrey'%7D%7D%3E%0A %3CText%3E%22My day today was very interesting. First I woke up late and I couldn't find my clean clothes and my mom......%22%3C/Text%3E%0A %3CText style=%7B%7Bcolor: 'purple', textAlign: 'right'%7D%7D%3E-Ahmed%3C/Text%3E%0A %3C/View%3E%0A )%0A %7D%0A render @@ -1392,24 +1392,24 @@ render() %7B%0A - return ( @@ -1753,17 +1753,35 @@ hlight%3E%0A + %3CSearch /%3E %0A - @@ -2076,26 +2076,37 @@ %7B () =%3E -%3CSearch /%3E +this.featuredStory() %7D /%3E%0A
25a74e13d800581cba299cddd2a0d07f6319ccd5
Add AJAX call for login
js/app/routes/login.js
js/app/routes/login.js
define([], function() { Path.map("#!/login").to(function(){ }).enter(function() { require(['tpl!template/login.html'], function(tpl){ $('#main').append($(tpl.apply())); $('header').hide(); $('#main').addClass('transparent-background'); $('footer').hide(); $('#signupCheck').on('click', function(){ if ($(this).is(':checked')){ $('#pass').hide(); $('#loginBtn').addClass('hide'); $('#resetBtn').removeClass('hide'); }else{ $('#pass').show(); $('#loginBtn').removeClass('hide'); $('#resetBtn').addClass('hide'); } }); $('form').on('submit', function(){ // 1. Check for login or reset password // 2. Perform action accordingly return false; }) }); }).exit(function() { // Exit from route $('header').show(); $('#main').off().empty().removeClass('transparent-background'); $('footer').show(); }); });
JavaScript
0.000001
@@ -718,16 +718,328 @@ e;%0A%09%09%09%7D) +;%0A%0A%09%09%09$('#login').on('submit', function() %7B%0A%09%09%09%09$.ajax(%7B%0A%09%09%09%09%09url: '/api/index.php/login',%0A%09%09%09%09%09dataType: 'json',%0A%09%09%09%09%09type: 'POST',%0A%09%09%09%09%09data: JSON.stringify(%7B%0A%09%09%09%09%09%09username: $('#email').val(),%0A%09%09%09%09%09%09password: $('#pass').val()%0A%09%09%09%09%09%7D)%0A%09%09%09%09%7D).always(function() %7B%0A%09%09%09%09%09console.debug(arguments);%0A%09%09%09%09%7D);%0A%09%09%09%7D);%09%09%09 %0A%09%09%7D);%0A%09
deb47bf4adb43ebc5810e48e20d053dfed9c9ecd
Set initial global bar cookie with helper function
app/assets/javascripts/global-bar-init.js
app/assets/javascripts/global-bar-init.js
//= require libs/GlobalBarHelper.js 'use strict' window.GOVUK = window.GOVUK || {} // Bump this if you are releasing a major change to the banner // This will reset the view count so all users will see the banner, even if previously seen var BANNER_VERSION = 3; var globalBarInit = { getBannerVersion: function() { return BANNER_VERSION }, getLatestCookie: function() { var currentCookie = document.cookie.match("(?:^|[ ;])(?:global_bar_seen=)(.+?)(?:(?=;|$))") if (currentCookie == null) { return currentCookie } else { return currentCookie[1] } }, blacklistedUrl: function() { var paths = [ "/register-to-vote", "/done", "/transition", "/transition-check" ] return new RegExp(paths.join("|")).test(window.location.pathname) }, setBannerCookie: function() { var eighty_four_days = 84*24*60*60*1000 var expiryDate = new Date(Date.now() + eighty_four_days).toUTCString() var value = JSON.stringify({count: 0, version: globalBarInit.getBannerVersion()}) var cookieString = "global_bar_seen=" + value + "; expires=" + expiryDate + ";" document.cookie=cookieString }, makeBannerVisible: function() { document.documentElement.className = document.documentElement.className.concat(" show-global-bar") }, init: function() { if (!globalBarInit.blacklistedUrl()) { if (globalBarInit.getLatestCookie() === null) { globalBarInit.setBannerCookie() globalBarInit.makeBannerVisible() } else { var currentCookieVersion = parseCookie(globalBarInit.getLatestCookie()).version if (currentCookieVersion !== globalBarInit.getBannerVersion()) { globalBarInit.setBannerCookie() } var newCookieCount = parseCookie(globalBarInit.getLatestCookie()).count if (newCookieCount < 3) { globalBarInit.makeBannerVisible() } } } } } window.GOVUK.globalBarInit = globalBarInit;
JavaScript
0.00039
@@ -28,16 +28,77 @@ elper.js +%0A//= require govuk_publishing_components/lib/cookie-functions %0A%0A'use s @@ -909,125 +909,8 @@ %7B%0A - var eighty_four_days = 84*24*60*60*1000%0A var expiryDate = new Date(Date.now() + eighty_four_days).toUTCString()%0A @@ -995,31 +995,38 @@ )%7D)%0A +%0A -var cookieString = + window.GOVUK.setCookie( %22glo @@ -1041,86 +1041,30 @@ seen -=%22 + +%22, value - + %22; expires=%22 + expiryDate + %22;%22%0A%0A document.cookie=cookieString +, %7Bdays: 84%7D); %0A %7D
8b305a86eb4d8165fe58140675729b1d9c9e3cc7
Update dynamic_carousel.js
js/dynamic_carousel.js
js/dynamic_carousel.js
var duree = "longue"; var duration_longue = true; var duration_courte = false; $(document).ready(function(){ //on initialise les variables avec les valeurs par défaut var duree = "longue"; var pub = "adu"; var nbDePersonnes = 16; var sce = 1; //on appuie les boutons en conséquence $("#dur_lon").addClass("active"); $("#pub_adu").addClass("active"); $("#sce_1").addClass("active"); //$("#car").load('carousel_long.html'); //On remplit le champ du bouton +/- avec la valeur par défaut $("#inputnb").val(nbDePersonnes); //var carousel_c = $.get("carousel_court.html"); //var carousel_l = $.get("carousel_long.html"); //On change la valeur des variables en fonction des actions utilisateurs //Pour la durée : $("#dur_cou").click(function(e){ duree = "courte"; duration_courte = true; duration_longue = false; $("#dur_lon").removeClass("active"); $("#dur_cou").addClass("active"); //var code = load("carousel_court.html"); //$("#myCarousel").replaceWith("<div id=" + "car" + "> <strong>This text is strong</strong> </br> <i>This text is italic</i> </div>"); //alert(carousel_c); //$("#car").empty(); $("#car").load('carousel_court.html'); $("#p1").show(); alert("Chargement terminé \n Guide pour atelier court !"); $("#rest").hide(); $("#plusbtn, #minubtn").click(function(){$("#rest").show();}); }); $("#dur_lon").click(function(e){ duree = "longue"; duration_longue = true; duration_courte =false; $("#dur_cou").removeClass("active"); $("#dur_lon").addClass("active"); //$("#myCarousel").replaceWith(carousel_l); //$("#car").empty(); $("#car").load('carousel_long.html'); $("#p1").show(); alert("Chargement terminé \n Guide pour atelier long !"); $("#rest").hide(); $("#plusbtn, #minubtn").click(function(){$("#rest").show();}) }); //Pour le public : $("#pub_enf").click(function(e){ pub = "enf"; $("#pub_adu").removeClass("active"); $("#pub_enf").addClass("active"); }); $("#pub_adu").click(function(e){ pub = "adu"; $("#pub_enf").removeClass("active"); $("#pub_adu").addClass("active"); }); //Pour le scénario : $("#sce_2").click(function(e){ sce = 2; $("#sce_1").removeClass("active"); $("#sce_2").addClass("active"); }); $("#sce_1").click(function(e){ sce = 1; $("#sce_2").removeClass("active"); $("#sce_1").addClass("active"); }); $("#pointLien").click(function(e){ if(pub == "enf"){ $("#pointLien").attr('href','graphiques_enfants.html'); }else{ $("#pointLien").attr('href','graphiques_adultes.html'); } }); });
JavaScript
0
@@ -2794,12 +2794,1127 @@ %7D);%0A%0A %7D);%0A +%0A%0A%0A%0Afunction demoFromHTML() %7B%0A %0A%0A%0A doc = new jsPDF('p', 'pt', 'a4', false); %0A %0A %0A if(duration_longue)%7B%0A var logo = new Image();%0A logo.src = %22../donnes/1.png%22;%0A doc.addImage(logo, 'JPEG', 2, 2, 590,850);%0A doc.addPage();%0A var logo = new Image();%0A logo.src = %222.png%22;%0A doc.addImage(logo, 'JPEG', 2, 2, 590,850);%0A %0A %0A %7Delse if(duration_courte) %7B%0A logo.src = %22../donnes/2.png%22;%0A doc.addImage(logo, 'JPEG', 2, 2, 590,850);%0A doc.addPage();%0A logo.src = %223.png%22;%0A doc.addImage(logo, 'JPEG', 2, 2, 590,850);%0A%0A %7D%0A%0A var uno= 1;%0A%0A%0A%0A%0A var paso;%0A for (paso = 4; paso %3C 6; paso++) %7B%0A doc.addPage();%0A var logo = new Image();%0A logo.src = paso+%22.png%22;%0A doc.addImage(logo, 'JPEG', 2, 2, 590,850);%0A // Se ejecuta 5 veces, con valores desde paso desde 0 hasta 4.%0A %0A %7D;%0A%0A%0A doc.output(%22dataurlnewwindow%22);%0A%0A %7D%0A
c36eb34bf4c096e4845c7aae9cd70de366a5685c
Add imagesloaded, eventEmitter and eventie to demo, otherwise demo won't load
demo/main.js
demo/main.js
config = { baseUrl: '/src', paths: { "jquery": "bower_components/jquery/jquery", "logging": "bower_components/logging/src/logging", "jquery.form": "bower_components/jquery-form/jquery.form", "jquery.anythingslider": "bower_components/AnythingSlider/js/jquery.anythingslider", "jcrop": "bower_components/jcrop/js/jquery.Jcrop", "klass": "bower_components/klass/src/klass", "photoswipe": "legacy/photoswipe", "parsley": "bower_components/parsleyjs/parsley", "parsley.extend": "bower_components/parsleyjs/parsley.extend", "patternslib.slides": "bower_components/slides/src/slides", "modernizr": "bower_components/modernizr/modernizr", "less": "bower_components/less.js/dist/less-1.6.2", "prefixfree": "bower_components/prefixfree/prefixfree.min", "Markdown.Converter": "legacy/Markdown.Converter", "Markdown.Extra": "legacy/Markdown.Extra", "Markdown.Sanitizer": "legacy/Markdown.Sanitizer", "select2": "bower_components/select2/select2.min", "jquery.chosen": "bower_components/chosen/chosen/chosen.jquery", "jquery.fullcalendar": "bower_components/fullcalendar/fullcalendar.min", "jquery.fullcalendar.dnd": "bower_components/fullcalendar/lib/jquery-ui.custom.min", "jquery.placeholder": "bower_components/jquery-placeholder/jquery.placeholder.min", "jquery.textchange": "bower_components/jquery-textchange/jquery.textchange", "tinymce": "bower_components/jquery.tinymce/jscripts/tiny_mce/jquery.tinymce", "spectrum": "bower_components/spectrum/spectrum", // Core "pat-utils": "core/utils", "pat-compat": "core/compat", "pat-jquery-ext": "core/jquery-ext", "pat-logger": "core/logger", "pat-parser": "core/parser", "pat-remove": "core/remove", "pat-url": "core/url", "pat-store": "core/store", "pat-registry": "core/registry", "pat-htmlparser": "lib/htmlparser", "pat-depends_parse": "lib/depends_parse", "pat-dependshandler": "lib/dependshandler", "pat-input-change-events": "lib/input-change-events", // Patterns "patterns": "patterns", "pat-ajax": "pat/ajax", "pat-autofocus": "pat/autofocus", "pat-autoscale": "pat/autoscale", "pat-autosubmit": "pat/autosubmit", "pat-autosuggest": "pat/autosuggest", "pat-breadcrumbs": "pat/breadcrumbs", "pat-bumper": "pat/bumper", "pat-carousel": "pat/carousel", "pat-checkedflag": "pat/checkedflag", "pat-checklist": "pat/checklist", "pat-chosen": "pat/chosen", "pat-collapsible": "pat/collapsible", "pat-colour-picket": "pat/colour-picker", "pat-depends": "pat/depends", "pat-edit-tinymce": "pat/edit-tinymce", "pat-equaliser": "pat/equaliser", "pat-expandable": "pat/expandable", "pat-focus": "pat/focus", "pat-formstate": "pat/form-state", "pat-forward": "pat/forward", "pat-fullcalendar": "pat/fullcalendar", "pat-gallery": "pat/gallery", "pat-image-crop": "pat/image-crop", "pat-inject": "pat/inject", "pat-legend": "pat/legend", "pat-markdown": "pat/markdown", "pat-menu": "pat/menu", "pat-modal": "pat/modal", "pat-navigation": "pat/navigation", "pat-notification": "pat/notification", "pat-placeholder": "pat/placeholder", "pat-selectbox": "pat/selectbox", "pat-skeleton": "pat/skeleton", "pat-slides": "pat/slides", "pat-slideshow-builder": "pat/slideshow-builder", "pat-sortable": "pat/sortable", "pat-stacks": "pat/stacks", "pat-subform": "pat/subform", "pat-switch": "pat/switch", "pat-toggle": "pat/toggle", "pat-tooltip": "pat/tooltip", "pat-validate": "pat/validate", "pat-zoom": "pat/zoom", // Calendar pattern "moment": "bower_components/moment/moment", "moment-timezone": "bower_components/moment-timezone/moment-timezone", "pat-calendar": "pat/calendar/calendar", "pat-calendar-dnd": "pat/calendar/dnd", "pat-calendar-moment-timezone-data": "pat/calendar/moment-timezone-data" }, shim: { "jcrop": { deps: ["jquery"] }, "jquery": { exports: ["jQuery"] }, "jquery.anythingslider": { deps: ["jquery"] }, "jquery.chosen": { deps: ["jquery"] }, "jquery.fullcalendar.dnd": { deps: ["jquery"] }, "jquery.placeholder": { deps: ["jquery"] }, "jquery.textchange": { deps: ["jquery"] }, "parsley": { deps: ["jquery"] }, "parsley.extend": { deps: ["jquery"] }, "photoswipe": { deps: ["klass"] }, "select2": { deps: ["jquery"] }, "spectrum": { deps: ["jquery"] }, "tinymce": { deps: ["jquery"] } }, }; if (typeof(require) !== 'undefined') { require.config(config); require(["patterns"], function(patterns) {}); }
JavaScript
0
@@ -1642,24 +1642,198 @@ /spectrum%22,%0A + %22imagesloaded%22: %22bower_components/imagesloaded/imagesloaded%22,%0A %22eventEmitter%22: %22bower_components/eventEmitter%22,%0A %22eventie%22: %22bower_components/eventie%22,%0A // C
2645465b509d279aaf1fae9dbd613d5abfa54812
create virtual dom is this
dist/moon.js
dist/moon.js
/* * Moon 0.0.0 * Copyright 2016, Kabir Shah * https://github.com/KingPixil/moon/ * Free to use under the MIT license. * https://kingpixil.github.io/license */ "use strict"; (function(window) { function Moon(opts) { var _el = opts.el; var _data = opts.data; var _methods = opts.methods; this.$el = document.getElementById(_el); this.dom = {type: this.$el.nodeName, children: [], node: this.$el}; // Change state when $data is changed Object.defineProperty(this, '$data', { get: function() { return _data; }, set: function(value) { _data = value; this.build(this.dom.children); } }); // Utility: Raw Attributes -> Key Value Pairs var extractAttrs = function(node) { var attrs = {}; if(!node.attributes) return attrs; var rawAttrs = node.attributes; for(var i = 0; i < rawAttrs.length; i++) { attrs[rawAttrs[i].name] = rawAttrs[i].value } return attrs; } // Utility: Create Elements Recursively For all Children var recursiveChildren = function(children) { var recursiveChildrenArr = []; for(var i = 0; i < children.length; i++) { var child = children[i]; recursiveChildrenArr.push(this.createElement(child.nodeName, recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child)); } return recursiveChildrenArr; } // Utility: Create Virtual DOM Instance var createVirtualDOM = function(node) { var vdom = this.createElement(node.nodeName, recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node); this.dom = vdom; } // Build the DOM with $data this.build = function(children) { var tempData = this.$data; for(var i = 0; i < children.length; i++) { var el = children[i]; if(el.type === "#text") { var tmpVal = el.val; el.val.replace(/{{(\w+)}}/gi, function(match, p1) { var newVal = tmpVal.replace(match, tempData[p1]); el.node.textContent = newVal; tmpVal = newVal; }); } else { for(var prop in el.props) { var tmpVal = el.props[prop]; el.props[prop].replace(/{{(\w+)}}/gi, function(match, p1) { var dataToAdd = tempData[p1]; var newVal = tmpVal.replace(new RegExp(match, "gi"), dataToAdd); el.node.setAttribute(prop, newVal); tmpVal = newVal; }); } this.build(el.children); } } } // Create Virtual DOM Object from Params this.createElement = function(type, children, val, props, node) { return {type: type, children: children, val: val, props: props, node: node}; } // Set any value in $data this.set = function(key, val) { this.$data[key] = val; this.build(this.dom.children); } // Get any value in $data this.get = function(key) { return this.$data[key]; } // Make AJAX GET/POST requests this.ajax = function(method, url, params, cb) { var xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); if(typeof params === "function") { cb = params; } var urlParams = "?"; if(method === "POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); for(var param in params) { urlParams += param + "=" + params[param] + "&"; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) cb(JSON.parse(xmlHttp.responseText)); } xmlHttp.open(method, url, true); xmlHttp.send(method === "POST" ? urlParams : null); } // Call a method defined in _methods this.method = function(method) { _methods[method](); } // Initialize createVirtualDOM(this.$el); this.build(this.dom.children); } window.Moon = Moon; window.$ = function(el) { el = document.querySelectorAll(el); return el.length === 1 ? el[0] : el; } })(window);
JavaScript
0.000009
@@ -1648,16 +1648,21 @@ var +this. createVi
a3906c4d9cd7440295c215b01f66ee38b3c0599a
bump build number
src/front/app.config.js
src/front/app.config.js
import 'dotenv/config'; const bundleId = 'gov.dts.ugrc.utahwvcr'; const buildNumber = 520; export default { name: 'WVC Reporter', slug: 'wildlife-vehicle-collision-reporter', description: 'A mobile application for reporting and removing animal carcasses.', // this needs to be different from the bundleId, otherwise android presents two options for redirect // Ref: https://forums.expo.dev/t/app-appears-twice-on-open-with-list-after-google-auth/55659/6?u=agrc scheme: bundleId.split('.').pop(), facebookScheme: `fb${process.env.FACEBOOK_OAUTH_CLIENT_ID}`, facebookAppId: process.env.FACEBOOK_OAUTH_CLIENT_ID, facebookDisplayName: 'Utah WVC Reporter', githubUrl: 'https://github.com/agrc/roadkill-mobile', version: '3.0.0', orientation: 'portrait', icon: './assets/icon.png', splash: { image: './assets/splash.png', resizeMode: 'contain', backgroundColor: '#ffffff', }, updates: { fallbackToCacheTimeout: 0, }, assetBundlePatterns: ['**/*'], ios: { bundleIdentifier: bundleId, googleServicesFile: process.env.GOOGLE_SERVICES_IOS, buildNumber: buildNumber.toString(), supportsTablet: true, config: { usesNonExemptEncryption: false, googleMapsApiKey: process.env.GOOGLE_MAPS_API_KEY_IOS, }, infoPlist: { NSLocationAlwaysUsageDescription: 'The app uses your location in the background for tracking routes. *Note* this is only applicable for agency employees or contractors. Background location is not used for public users.', NSLocationWhenInUseUsageDescription: 'The app uses your location to help record the location of the animal that you are reporting.', }, }, android: { package: bundleId, googleServicesFile: process.env.GOOGLE_SERVICES_ANDROID, versionCode: buildNumber, softwareKeyboardLayoutMode: 'pan', adaptiveIcon: { foregroundImage: './assets/adaptive-icon.png', backgroundColor: '#FFFFFF', }, permissions: [ 'ACCESS_FINE_LOCATION', 'ACCESS_COARSE_LOCATION', 'FOREGROUND_SERVICE', 'CAMERA', 'READ_EXTERNAL_STORAGE', 'WRITE_EXTERNAL_STORAGE', ], config: { googleMaps: { apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID, }, }, }, // this is only to enable logEvent calls during development in Expo Go // ref: https://docs.expo.io/versions/latest/sdk/firebase-analytics/#expo-go-limitations--configuration web: { config: { firebase: { apiKey: process.env.GOOGLE_MAPS_API_KEY_ANDROID ?? '', measurementId: process.env.FIREBASE_MEASUREMENT_ID ?? 'G-XXXXXXXXXX', }, }, }, hooks: { postPublish: [ { file: 'sentry-expo/upload-sourcemaps', config: { organization: 'utah-agrc', project: 'roadkill', authToken: process.env.SENTRY_AUTH_TOKEN, }, }, ], }, plugins: ['sentry-expo', 'expo-community-flipper'], };
JavaScript
0.000083
@@ -83,17 +83,17 @@ ber = 52 -0 +1 ;%0A%0Aexpor
b620b75469882da508f78e6cde2a0f8294eaeb66
add gulp folder
gulp/tasks/eslint.js
gulp/tasks/eslint.js
/* eslint import/no-extraneous-dependencies: ["error", {"devDependencies": true}] */ import gulp from 'gulp'; import eslint from 'gulp-eslint'; import config from '../config'; gulp.task('eslint', () => gulp.src(config.files.js) .pipe(eslint()) .pipe(eslint.format()) .pipe(eslint.failAfterError()));
JavaScript
0.000001
@@ -205,16 +205,26 @@ ulp.src( +%5B%5D.concat( config.f @@ -230,16 +230,37 @@ files.js +, %5B'./gulp/**/*.js'%5D) )%0A .p
e7b57bcade8367baa6c7e126c1f6cef42fdf99f3
Refactor MenuView to use tokenIsPresent() instead of loggedIn flag.
app/assets/javascripts/views/user/menu.js
app/assets/javascripts/views/user/menu.js
Teikei.module("User", function(User, App, Backbone, Marionette, $, _) { User.MenuView = Marionette.View.extend({ el: "#user", ui: { signInToggle: "#signin", signUpToggle: "#signup", currentUserMenuItem: "#current_user", participateMenuItem: "#participate", newEntryMenuItem: "#new-entry", myEntriesMenuItem: "#my-entries" }, events: { "click #signin": "toggleAuth", "click #signup": "onSignUp", "click #add-farm": "addFarm", "click #add-depot": "addDepot", "click #my-entries": "showEntryList", "click #participate-depot": "onParticipateDepot", "click #participate-farm": "onParticipateFarm" }, initialize: function() { this.bindUIElements(); if (this.model.get("loggedIn")){ this.onSignIn(); } this.updateUserName(); App.vent.on("user:signin:success", this.onSignIn, this); App.vent.on("user:logout:success", this.onLogout, this); }, toggleAuth: function(event) { event.preventDefault(); var loggedIn = this.model.get("loggedIn"); if (!loggedIn) { this.trigger("signin:selected"); } else { this.trigger("logout:selected"); } }, addFarm: function(event) { event.preventDefault(); App.vent.trigger("user:add:farm"); }, addDepot: function(event) { event.preventDefault(); App.vent.trigger("user:add:depot"); }, showEntryList: function() { event.preventDefault(); App.vent.trigger("user:show:entrylist"); }, onParticipateDepot: function(event) { event.preventDefault(); App.vent.trigger("participate:for:citizens"); }, onParticipateFarm: function(event) { event.preventDefault(); App.vent.trigger("participate:for:farmers"); }, onSignUp: function(event) { var loggedIn = this.model.get("loggedIn"); if (!loggedIn) { event.preventDefault(); this.trigger("signup:selected"); } }, onSignIn: function() { this.ui.signInToggle.text("Abmelden"); this.ui.signInToggle.attr("href", "/users/sign_out"); this.ui.signUpToggle.text("Konto anpassen"); this.ui.signUpToggle.attr("href", "/users/edit"); this.updateUserName(); this.ui.participateMenuItem.hide(); this.ui.newEntryMenuItem.show(); this.ui.myEntriesMenuItem.show(); }, onLogout: function() { this.ui.signInToggle.text("Anmelden"); this.ui.signInToggle.attr("href", "/users/sign_in"); this.ui.signUpToggle.text("Registrieren"); this.ui.signUpToggle.attr("href", "/users/sign_up"); this.updateUserName(); this.ui.participateMenuItem.show(); this.ui.newEntryMenuItem.hide(); this.ui.myEntriesMenuItem.hide(); }, updateUserName: function() { userName = this.model.get("name"); this.ui.currentUserMenuItem.parent().show(); if (userName === null || userName === undefined) { userName = ""; this.ui.currentUserMenuItem.parent().hide(); } this.ui.currentUserMenuItem.text(userName); } }); });
JavaScript
0
@@ -761,98 +761,22 @@ -if ( this. -model.get(%22loggedIn%22))%7B%0A this.onSignIn();%0A %7D%0A this.updateUserNam +invalidat e(); @@ -822,24 +822,26 @@ %22, this. -onSignIn +invalidate , this); @@ -887,24 +887,26 @@ %22, this. -onLogout +invalidate , this); @@ -980,32 +980,28 @@ lt();%0A -var logg +sign edIn = this. @@ -1002,38 +1002,39 @@ this.model. -get(%22loggedIn%22 +tokenIsPresent( );%0A if @@ -1027,36 +1027,36 @@ t();%0A if (! -logg +sign edIn) %7B%0A @@ -1162,24 +1162,306 @@ %7D%0A %7D,%0A%0A + invalidate: function() %7B%0A signedIn = this.model.tokenIsPresent();%0A if (signedIn) %7B%0A userName = this.model.get(%22name%22);%0A this.renderSignedInState(userName);%0A %7D%0A else %7B%0A this.renderSignedOutState();%0A %7D%0A console.log(%22 %22);%0A %7D,%0A%0A addFarm: @@ -2250,16 +2250,27 @@ -onSignIn +renderSignedInState : fu @@ -2268,32 +2268,40 @@ State: function( +userName ) %7B%0A this.u @@ -2504,37 +2504,8 @@ %22);%0A - this.updateUserName();%0A @@ -2629,24 +2629,137 @@ -%7D,%0A%0A onLogout + this.ui.currentUserMenuItem.text(userName);%0A this.ui.currentUserMenuItem.parent().show();%0A %7D,%0A%0A renderSignedOutState : fu @@ -2985,37 +2985,8 @@ %22);%0A - this.updateUserName();%0A @@ -3110,224 +3110,54 @@ -%7D,%0A%0A%0A updateUserName: function() %7B%0A userName = this.model.get(%22name%22);%0A this.ui.currentUserMenuItem.parent().show();%0A if (userName === null %7C%7C userName === undefined) %7B%0A userName = + this.ui.currentUserMenuItem.text( %22%22 +) ;%0A th @@ -3148,26 +3148,24 @@ (%22%22);%0A - - this.ui.curr @@ -3201,66 +3201,8 @@ ();%0A - %7D%0A this.ui.currentUserMenuItem.text(userName);%0A
b29ddeb002c914fb25819f49df8d6a9e0f7e2395
make the default "compiled" dir be overridable
bindings.js
bindings.js
/** * Module dependencies. */ var fs = require('fs') , path = require('path') , join = path.join , dirname = path.dirname , exists = fs.existsSync || path.existsSync , defaults = { arrow: process.env.NODE_BINDINGS_ARROW || ' → ' , compiled: 'compiled' , platform: process.platform , arch: process.arch , version: parseVersion(process.versions.node) , bindings: 'bindings.node' , try: [ // node-gyp's linked version in the "build" dir [ 'module_root', 'build', 'bindings' ] // node-waf and gyp_addon (a.k.a node-gyp) , [ 'module_root', 'build', 'Debug', 'bindings' ] , [ 'module_root', 'build', 'Release', 'bindings' ] // Debug files, for development (legacy behavior, remove for node v0.9) , [ 'module_root', 'out', 'Debug', 'bindings' ] , [ 'module_root', 'Debug', 'bindings' ] // Release files, but manually compiled (legacy behavior, remove for node v0.9) , [ 'module_root', 'out', 'Release', 'bindings' ] , [ 'module_root', 'Release', 'bindings' ] // Legacy from node-waf, node <= 0.4.x , [ 'module_root', 'build', 'default', 'bindings' ] // Production "Release" buildtype binary (meh...) , [ 'module_root', 'compiled', 'version', 'platform', 'arch', 'bindings' ] ] } /** * The main `bindings()` function loads the compiled bindings for a given module. * It uses V8's Error API to determine the parent filename that this function is * being invoked from, which is then used to find the root directory. */ function bindings (opts) { // Argument surgery if (typeof opts == 'string') { opts = { bindings: opts } } else if (!opts) { opts = {} } opts.__proto__ = defaults // Get the module root if (!opts.module_root) { opts.module_root = exports.getRoot(exports.getFileName()) } // Ensure the given bindings name ends with .node if (path.extname(opts.bindings) != '.node') { opts.bindings += '.node' } var tries = [] , i = 0 , l = opts.try.length , n for (; i<l; i++) { n = join.apply(null, opts.try[i].map(function (p) { return opts[p] || p })) tries.push(n) try { var b = require(n) b.path = n return b } catch (e) { if (!/not find/i.test(e.message)) { throw e } } } var err = new Error('Could not load the bindings file. Tried:\n' + tries.map(function (a) { return opts.arrow + a }).join('\n')) err.tries = tries throw err } module.exports = exports = bindings /** * Gets the filename of the JavaScript file that invokes this function. * Used to help find the root directory of a module. */ exports.getFileName = function getFileName () { var origPST = Error.prepareStackTrace , dummy = {} , fileName Error.prepareStackTrace = function (e, st) { for (var i=0, l=st.length; i<l; i++) { fileName = st[i].getFileName() if (fileName !== __filename) { return } } } // run the 'prepareStackTrace' function above Error.captureStackTrace(dummy) dummy.stack // cleanup Error.prepareStackTrace = origPST return fileName } /** * Gets the root directory of a module, given an arbitrary filename * somewhere in the module tree. The "root directory" is the directory * containing the `package.json` file. * * In: /home/nate/node-native-module/lib/index.js * Out: /home/nate/node-native-module */ exports.getRoot = function getRoot (file) { var dir = dirname(file) , prev while (true) { if (dir === '.') { // Avoids an infinite loop in rare cases, like the REPL dir = process.cwd() } if (exists(join(dir, 'package.json')) || exists(join(dir, 'node_modules'))) { // Found the 'package.json' file or 'node_modules' dir; we're done return dir } if (prev === dir) { // Got to the top throw new Error('Could not find module root given file: "' + file + '". Do you have a `package.json` file? ') } // Try the parent dir next prev = dir dir = join(dir, '..') } } /** * Accepts a String like "v0.10.4" and returns a String * containing the major and minor versions ("0.10"). */ function parseVersion (str) { var m = String(str).match(/(\d+)\.(\d+)/) return m ? m[0] : null } exports.parseVersion = parseVersion
JavaScript
0.998502
@@ -261,16 +261,58 @@ ompiled: + process.env.NODE_BINDINGS_COMPILED_DIR %7C%7C 'compil
cd3073987f6d317affc519e395cee89793c6a90c
Rebuild js.
vendor/assets/javascripts/jquery.turbolinks.js
vendor/assets/javascripts/jquery.turbolinks.js
// Generated by CoffeeScript 1.6.3 /* jQuery.Turbolinks ~ https://github.com/kossnocorp/jquery.turbolinks jQuery plugin for drop-in fix binded events problem caused by Turbolinks The MIT License Copyright (c) 2012-2013 Sasha Koss & Rico Sta. Cruz */ (function() { var $, $document; $ = window.jQuery || (typeof require === "function" ? require('jquery') : void 0); $document = $(document); $.turbo = { version: '2.0.0', isReady: false, use: function(load, fetch) { return $document.off('.turbo').on("" + load + ".turbo", this.onLoad).on("" + fetch + ".turbo", this.onFetch); }, addCallback: function(callback) { if ($.turbo.isReady) { return callback($); } else { return $document.on('turbo:ready', function() { return callback($); }); } }, onLoad: function() { $.turbo.isReady = true; return $document.trigger('turbo:ready'); }, onFetch: function() { return $.turbo.isReady = false; }, register: function() { $(this.onLoad); return $.fn.ready = this.addCallback; } }; $.turbo.register(); $.turbo.use('page:load', 'page:fetch'); }).call(this);
JavaScript
0.000001
@@ -28,11 +28,12 @@ t 1. -6.3 +7.1%0A %0A/*%0A @@ -246,13 +246,13 @@ ruz%0A + */%0A%0A -%0A (fun @@ -428,17 +428,17 @@ n: '2.0. -0 +1 ',%0A i
13bcd3c652b29785416039aedf893a9f47eb1cc5
Remove unused code
app/client/front/js/ov/VideoController.js
app/client/front/js/ov/VideoController.js
'use strict'; (function(app) { /** * * @param {type} $scope * @param {type} $locale * @param {type} $timeout * @param {type} $location * @returns {VideoController_L3.VideoController} */ function VideoController($scope, $http, $locale, $timeout, $location, $analytics, videoService, searchService, $sce, webServiceBasePath) { $scope.defaultMode = 'both'; if ($scope.video.metadata) { var template = $scope.video.metadata.template || ''; if (template.match(/^mix-/)) $scope.defaultMode = 'media'; } if ($scope.video.category) { searchService.getCategoryName($scope.video.category).then(function(val) { $scope.categoryName = val; }); } $scope.dialIsOpen = false; $scope.language = $locale.id; $scope.shareOpen = false; $scope.shareItems = [ {name: 'UI.LINK', icon: 'link', direction: 'bottom', action: function(video) { delete $scope.shareText; var port = ($location.port() != 80 && $location.port() != 443) ? ':' + $location.port() : ''; $scope.shareLink = $location.protocol() + '://' + $location.host() + port + '/video/' + video.id; $scope.shareOpen = !$scope.shareOpen; }}, {name: 'UI.CODE', icon: 'code', direction: 'bottom', action: function(video) { delete $scope.shareLink; var port = ($location.port() != 80 && $location.port() != 443) ? ':' + $location.port() : ''; $scope.shareText = '<iframe width="768" height="500" ' + 'src="' + $location.protocol() + '://' + $location.host() + port + '/video/' + video.id + '?iframe&hidedetail" frameborder="0"></iframe>'; $scope.shareOpen = !$scope.shareOpen; }} ]; $scope.showFullInfos = false; $scope.toggleFullInfosLabel = 'UI.MORE'; $scope.toggleFullInfos = function() { $scope.showFullInfos = !$scope.showFullInfos; $scope.toggleFullInfosLabel = $scope.showFullInfos ? 'UI.LESS' : 'UI.MORE'; }; var myPlayer = document.getElementById('openveo-player'); var playerController; var videoDuration; angular.element(myPlayer).on('needPoiConversion', function(event, duration) { $http .post(webServiceBasePath + 'videos/' + $scope.video.id + '/poi/convert', {duration: duration}) .then(function(response) { $scope.video = response.data.entity; }); }); /** * Executes, safely, the given function in AngularJS process. * * @param {Function} functionToExecute The function to execute as part of * the angular digest process. */ function safeApply(functionToExecute) { // Execute each apply on a different loop $timeout(function() { // Make sure we're not on a digestion cycle var phase = $scope.$root.$$phase; if (phase === '$apply' || phase === '$digest') functionToExecute(); else $scope.$apply(functionToExecute); }, 1); } angular.element(myPlayer).on('durationChange', function(event, duration) { safeApply(function() { videoDuration = duration; // only gets called once if (!playerController || duration) { playerController = angular.element(myPlayer).controller('ovPlayer'); } }); }); angular.element(myPlayer).on('play', function(event) { $analytics.pageTrack($location.path()); $analytics.eventTrack('play', {value: $scope.video.id}); videoService.increaseVideoView($scope.video.id, videoDuration); }); // Listen to player errors // If an error occurs go back to catalog with an alert angular.element(myPlayer).on('error', function(event, error) { $scope.$emit('setAlert', 'danger', error && error.message, 8000); }); $scope.$watch('vctl.dialIsOpen', function(newValue, oldValue) { if (newValue === true) { $scope.shareOpen = false; } }); $scope.trustedHTML = function(string) { return $sce.trustAsHtml(string); }; } app.controller('VideoController', VideoController); VideoController.$inject = [ '$scope', '$http', '$locale', '$timeout', '$location', '$analytics', 'videoService', 'searchService', '$sce', 'webServiceBasePath' ]; })(angular.module('ov.portal'));
JavaScript
0.000006
@@ -2365,34 +2365,8 @@ ');%0A - var playerController;%0A @@ -3412,176 +3412,8 @@ ion; -%0A%0A // only gets called once%0A if (!playerController %7C%7C duration) %7B%0A playerController = angular.element(myPlayer).controller('ovPlayer');%0A %7D %0A
6a87482243e3648507754641c8675af30e675104
implement setPosition, setTarget, setZoom
src/gltf/user_camera.js
src/gltf/user_camera.js
import { vec3 } from 'gl-matrix'; import { gltfCamera } from './camera.js'; import { jsToGl, clamp } from './utils.js'; import { getSceneExtents } from './gltf_utils.js'; const VecZero = vec3.create(); const PanSpeedDenominator = 1200; const MaxNearFarRatio = 10000; class UserCamera extends gltfCamera { constructor( target = [0, 0, 0], xRot = 0, yRot = 0, zoom = 1) { super(); this.target = jsToGl(target); this.xRot = xRot; this.yRot = yRot; this.zoom = zoom; this.zoomFactor = 1.04; this.rotateSpeed = 1 / 180; this.panSpeed = 1; this.sceneExtents = { min: vec3.create(), max: vec3.create() }; } getPosition() { // calculate direction from focus to camera (assuming camera is at positive z) // yRot rotates *around* x-axis, xRot rotates *around* y-axis const direction = vec3.fromValues(0, 0, this.zoom); this.toLocalRotation(direction); const position = vec3.create(); vec3.add(position, this.target, direction); return position; } lookAt(from, to) { // up is implicitly (0, 1, 0) this.target = to; const difference = vec3.create(); vec3.subtract(difference, from, to); const projectedDifference = vec3.fromValues(from[0] - to[0], 0, from[2] - to[2]); this.yRot = vec3.angle(difference, projectedDifference); this.xRot = vec3.angle(projectedDifference, vec3.fromValues(1.0, 0.0, 0.0)); this.zoom = vec3.length(difference); } setRotation(yaw, pitch) { // Rotates target instead of position const difference = vec3.create(); vec3.subtract(difference, this.target, this.position); vec3.rotateY(difference, difference, VecZero, -yaw * this.rotateSpeed); vec3.rotateX(difference, difference, VecZero, -pitch * this.rotateSpeed); vec3.add(this.target, this.position, difference); } reset(gltf, sceneIndex) { this.xRot = 0; this.yRot = 0; this.fitViewToScene(gltf, sceneIndex, true); } zoomBy(value) { if (value > 0) { this.zoom *= this.zoomFactor; } else { this.zoom /= this.zoomFactor; } this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max); } orbit(x, y) { const yMax = Math.PI / 2 - 0.01; this.xRot += (x * this.rotateSpeed); this.yRot += (y * this.rotateSpeed); this.yRot = clamp(this.yRot, -yMax, yMax); // const difference = vec3.create(); // vec3.subtract(difference, this.position, this.target); // vec3.rotateY(difference, difference, VecZero, -x * this.rotateSpeed); // vec3.rotateX(difference, difference, VecZero, -y * this.rotateSpeed); // vec3.add(this.position, this.target, difference); } pan(x, y) { const left = vec3.fromValues(-1, 0, 0); this.toLocalRotation(left); vec3.scale(left, left, x * this.panSpeed); const up = vec3.fromValues(0, 1, 0); this.toLocalRotation(up); vec3.scale(up, up, y * this.panSpeed); vec3.add(this.target, this.target, up); vec3.add(this.target, this.target, left); } fitPanSpeedToScene(min, max) { const longestDistance = vec3.distance(min, max); this.panSpeed = longestDistance / PanSpeedDenominator; } fitViewToScene(gltf, sceneIndex) { getSceneExtents(gltf, sceneIndex, this.sceneExtents.min, this.sceneExtents.max); this.fitCameraTargetToExtents(this.sceneExtents.min, this.sceneExtents.max); this.fitZoomToExtents(this.sceneExtents.min, this.sceneExtents.max); const direction = vec3.fromValues(0, 0, this.zoom); vec3.add(this.getPosition(), this.target, direction); this.fitPanSpeedToScene(this.sceneExtents.min, this.sceneExtents.max); this.fitCameraPlanesToExtents(this.sceneExtents.min, this.sceneExtents.max); } toLocalRotation(vector) { vec3.rotateX(vector, vector, VecZero, -this.yRot); vec3.rotateY(vector, vector, VecZero, -this.xRot); } getLookAtTarget() { return this.target; } fitZoomToExtents(min, max) { const maxAxisLength = Math.max(max[0] - min[0], max[1] - min[1]); this.zoom = this.getFittingZoom(maxAxisLength); } fitCameraTargetToExtents(min, max) { for (const i of [0, 1, 2]) { this.target[i] = (max[i] + min[i]) / 2; } } fitCameraPlanesToExtents(min, max) { // depends only on scene min/max and the camera zoom // Manually increase scene extent just for the camera planes to avoid camera clipping in most situations. const longestDistance = 10 * vec3.distance(min, max); let zNear = this.zoom - (longestDistance * 0.6); let zFar = this.zoom + (longestDistance * 0.6); // minimum near plane value needs to depend on far plane value to avoid z fighting or too large near planes zNear = Math.max(zNear, zFar / MaxNearFarRatio); this.znear = zNear; this.zfar = zFar; } getFittingZoom(axisLength) { const yfov = this.yfov; const xfov = this.yfov * this.aspectRatio; const yZoom = axisLength / 2 / Math.tan(yfov / 2); const xZoom = axisLength / 2 / Math.tan(xfov / 2); return Math.max(xZoom, yZoom); } } export { UserCamera };
JavaScript
0.000001
@@ -1620,24 +1620,191 @@ ce);%0A %7D%0A%0A + setPosition(position)%0A %7B%0A this.lookAt(position, this.target);%0A %7D%0A%0A setTarget(target)%0A %7B%0A this.lookAt(target, this.getPosition());%0A %7D%0A%0A setRotat @@ -2202,24 +2202,81 @@ ce);%0A %7D%0A%0A + setZoom(zoom)%0A %7B%0A this.zoom = zoom;%0A %7D%0A%0A reset(gl
85e70a5913d3b8373db761c19f7df9c59f9bd86d
Update bits-oder-functions.js
js/bits-oder-functions.js
js/bits-oder-functions.js
//////////////////////////////////////////////////////////////////////////////////////////////////////////// function oid() { //Get Token Balance $("#tokenBal").html(allTokens.balanceTokens.totalEarned.toFixed(2) + " tokens"); //Load Wallet $(".walletToast").remove(); if (localStorage.getItem('bits-user-name') == null) { console.log("Not logged in") } else { Materialize.toast('Unlock wallet <span class="right" style="color:yellow;" onclick="unlockWallet()">Unlock</span>', null, 'walletToast') } if (window.location.hash != undefined) { //check if hash is oid var type = window.location.hash.substr(1); // split the hash var fields = type.split('='); var htpe = fields[0]; var hval = fields[1]; if (htpe == "oid") { //get the shop and the oder details var shop = getBitsWinOpt('s') // oid $(".otitle").html(""); $(".otitle").append("Your Order"); $(".of").html(""); //var uid = JSON.parseInt(hval) var od = getObjectStore('data', 'readwrite').get('bits-user-orders-' + localStorage.getItem("bits-user-name")); od.onsuccess = function (event) { try { var odData = JSON.parse(event.target.result); for (var ii = 0; ii < odData.length; ++ii) { var xx = odData[ii].items var xid = odData[ii].id //makeOrder(products) // match oid to url id var urloid = getBitsOpt("oid") if (urloid == xid) { makeOrder(JSON.parse(xx), odData[ii].location) } else { console.log("no match") } } } catch (err) {} }; od.onerror = function () {}; //makeOrder(hval) } else { console.log("we dont know this hash") } } else {} } function unlockWallet() { walletFunctions(90).then(function (e) { loadGdrive(); $(".walletToast").remove(); }) } function getUserOders(f) { doFetch({ action: 'getAllOrders', uid: localStorage.getItem("bits-user-name") }).then(function (e) { if (e.status == "ok") { xx = e.data; //var earnedPoints = 0; for (var ii in allTokens) { allTokens[ii].totalEarned = 0; } for (var ii in xx) { var items = xx[ii].points; try { var typeofCoin = JSON.parse(items).coin; } catch (err) { console.log(err); continue; } try { var purchasePoints = JSON.parse(items).purchase; if (purchasePoints == undefined) { var purchasePoints = 0; } } catch (err) { console.log('this order does not have any purchase rewards', err); var purchasePoints = 0; } try { var deliveryPoints = JSON.parse(items).delivery; if (deliveryPoints == undefined) { var deliveryPoints = 0; } } catch (err) { console.log('this order does not have any delivery rewards', err); var deliveryPoints = 0; } try { allTokens[typeofCoin].totalEarned = allTokens[typeofCoin].totalEarned + purchasePoints + deliveryPoints; } catch (err) { console.log('this coin had not been included in the rewards since its currently inactive', typeofCoin); continue; } console.log(typeofCoin, purchasePoints, deliveryPoints); }; var setdb = getObjectStore('data', 'readwrite').put(JSON.stringify(xx), 'bits-user-orders-' + localStorage.getItem("bits-user-name")); setdb.onsuccess = function () { oid(); } setTimeout(function () { updateEarnedTokens(f) }, 1500); } else { swal("Cancelled", "an error occcured", "error"); } }) } // var gtod = localStorage.getItem('bits-user-orders-'+localStorage.getItem("bits-user-name")); // function updateEarnedTokens(f) { $('.coinlist').html(''); var at = allTokens['allContracts']; var i = 0; var tCe = 0; tBal = 0; for(var i in at) { if(!(location.origin+'/').includes(allTokens[allTokens['allContracts'][at[i]]].webpage)){ continue; } try{ var rate = allTokens[at[i]].rate; var coinName = allTokens[at[i]].name; //if i have 1000 kobos //var koboBalance = 1000; // console.log((rate*e.data.baseEx*koboBalance).toFixed(2)+' KES'); var koboRate = Math.floor(rate * baseX); var qq = rate * baseX; var xx = qq.toFixed(2); var coinId = at[i]; var tA = allTokens[coinId].totalEarned + (allTokens[coinId].balance / Math.pow(10, allTokens[coinId].decimals)); if (tA > 0) { //only display the coin if the user has a balance $('.coinlist').append('<span><div class="coinImg" style=" position: absolute ;margin-top: 5px;"><img src="/bitsAssets/images/currencies/' + coinName + '.png" alt="" style=" padding-left: 12px; height:30px;"></div><a href="" class="" class="" onclick=""><span style=" padding-left: 42px; text-transform: capitalize; ">' + coinName + '</span><span class="coin-' + coinId + '-bal" style=" float:right; line-height: 3.3;position: absolute;right: 15px;"></span></a></span>') $('.coin-' + coinId + '-bal').html('').append(tA.toFixed(5)); } $('.coin-' + coinId + '-xrate').html('').append('1 ' + coinName + ' = ' + xx + ' ' + baseCd); tBal = tBal + (tA * allTokens[coinId].rate * baseX); }catch(e){ console.log(e) } i++; } $('.balance-coins').html('').append(numberify(tBal,2) + ' ' + baseCd); } //Check Bal Interval var checkBal = window.setInterval(function () { if ($("#checkBal")[0].innerHTML == "") { updateEarnedTokens() } else { clearInterval(checkBal); } }, 7000);
JavaScript
0.000001
@@ -4874,41 +4874,14 @@ ens%5B -allTokens%5B'allContracts'%5D%5B at%5Bi%5D%5D -%5D .web
ecfef54d382b3b7b4c8c99405f329b6634ca9765
Include the object in ROW_CLICK events. Default to CitationView instead of DetailView.
js/foam/u2/DAOListView.js
js/foam/u2/DAOListView.js
/** * @license * Copyright 2015 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.u2', name: 'DAOListView', extends: 'foam.u2.View', requires: [ 'foam.u2.DetailView', 'foam.u2.md.CitationView', ], imports: [ 'selection$', ], constants: { ROW_CLICK: ['row-click'], }, properties: [ { model_: 'foam.core.types.DAOProperty', name: 'data', postSet: function(old, nu) { this.dao = nu; }, }, { // Separate from data so it can be a DAOProperty. model_: 'foam.core.types.DAOProperty', name: 'dao', }, { name: 'daoListener_', lazyFactory: function() { return { put: this.onDAOPut, remove: this.onDAORemove, reset: this.onDAOReset }; } }, { type: 'ViewFactory', name: 'rowView', }, { name: 'rows', factory: function() { return {}; } }, ['nodeName', 'div'] ], templates: [ function CSS() {/* .foam-u2-DAOListView { } */} ], methods: [ function initE() { this.dao$Proxy.pipe(this.daoListener_); this.cls('foam-u2-DAOListView'); }, ], listeners: [ { name: 'onDAOPut', code: function(obj) { if ( this.rows[obj.id] ) { this.rows[obj.id].data = obj; return; } var Y = this.Y.sub({ data: obj }); var child = this.rowView ? this.rowView({ data: obj }, Y) : obj.toRowE ? obj.toRowE(Y) : obj.toE ? obj.toE(Y) : this.DetailView.create({ data: obj }, Y); child.on('click', function() { this.publish(this.ROW_CLICK); this.selection = obj; }.bind(this)); this.rows[obj.id] = child; this.add(child); } }, { name: 'onDAORemove', code: function(obj) { if ( this.rows[obj.id] ) { this.removeChild(this.rows[obj.id]); delete this.rows[obj.id]; } } }, { name: 'onDAOReset', code: function(obj) { this.removeAllChildren(); this.rows = {}; this.dao.select(this.daoListener_); } } ] });
JavaScript
0
@@ -2165,22 +2165,24 @@ this. -Detail +Citation View.cre @@ -2281,16 +2281,21 @@ OW_CLICK +, obj );%0A
701cf0e0ba2866a0e6f9ed1e05de3c6b959e67c9
Fix foam.u2.md.TextArea after focused was added to Element.
js/foam/u2/md/TextArea.js
js/foam/u2/md/TextArea.js
/** * @license * Copyright 2015 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.u2.md', name: 'TextArea', extends: 'foam.u2.md.Input', properties: [ { name: 'displayHeight', type: 'Int', defaultValue: 10 } ], requires: [ 'foam.u2.TextArea' ], methods: [ function fromProperty(p) { this.displayHeight = p.displayHeight; return this.SUPER(p); }, function inputE() { var self = this; return this.start('textarea') .cls(this.myCls('textarea')) .attrs({ rows: this.displayHeight }) .on('focus', function() { self.focused_ = true; }) .on('blur', function() { self.focused_ = false; }); } ], templates: [ function CSS() {/* $ { align-items: center; display: flex; margin: 8px; padding: 32px 8px 8px 8px; position: relative; } $-label { color: #999; flex-grow: 1; font-size: 14px; font-weight: 500; position: absolute; top: 32px; transition: font-size 0.5s, top 0.5s; z-index: 0; } $-label-offset { font-size: 85%; top: 8px; } $-no-label { padding-top: 8px; } $-textarea { background: transparent; border-bottom: 1px solid #e0e0e0; border-left: none; border-top: none; border-right: none; color: #444; flex-grow: 1; font-family: inherit; font-size: inherit; margin-bottom: -8px; padding: 0 0 7px 0; resize: none; z-index: 1; } $-textarea:focus { border-bottom: 2px solid #4285f4; padding: 0 0 6px 0; outline: none; } */} ] });
JavaScript
0
@@ -1191,17 +1191,16 @@ .focused -_ = true; @@ -1252,9 +1252,8 @@ used -_ = f
eb934e09eeed76a6a66033d1b00c2ed7c94e9da4
Add main doc block
cangraph.js
cangraph.js
JavaScript
0
@@ -0,0 +1,222 @@ +/**%0A * Cangraph%0A *%0A * Graphing and function plotting for the HTML5 canvas. Main function plotting%0A * engine was taken from the link below and modified.%0A *%0A * @link http://www.javascripter.net/faq/plotafunctiongraph.htm%0A */
a74e4192cb40ca1582489db1c276fc5b4ae38e30
Remove debugger
js/templateSelector.js
js/templateSelector.js
/** * The UI Element for browsing and selecting pre-defined Pedigree templates * * @class TemplateSelector * @constructor * @param {Boolean} isStartupTemplateSelector Set to True if no pedigree has been loaded yet */ var TemplateSelector = Class.create({ initialize: function (isStartupTemplateSelector) { this._isStartupTemplateSelector = isStartupTemplateSelector; this.mainDiv = new Element('div', {'class': 'template-picture-container'}); this.mainDiv.update("Loading list of templates..."); var closeShortcut = isStartupTemplateSelector ? [] : ['Esc']; this.dialog = new PhenoTips.widgets.ModalPopup(this.mainDiv, {close: {method: this.hide.bind(this), keys: closeShortcut}}, {extraClassName: "pedigree-template-chooser", title: "Please select a pedigree template", displayCloseButton: !isStartupTemplateSelector, verticalPosition: "top"}); isStartupTemplateSelector && this.show(); //Commented by Soheil for GEL(GenomicsEngland) //ge the right path instead of using xWiki path //new Ajax.Request(new XWiki.Document('WebHome').getRestURL('objects/PhenoTips.PedigreeClass/index.xml').substring(1), { var settings = new Settings(); //Commented by Soheil for GEL(GenomicsEngland) //ge the right path instead of using xWiki path //new Ajax.Request(new XWiki.Document('WebHome').getRestURL('objects/PhenoTips.PedigreeClass/index.xml').substring(1), { var settings = new Settings(); debugger var newURL = settings.getAbsoluteURL("/" + new XWiki.Document('WebHome').getRestURL('objects/PhenoTips.PedigreeClass/index.xml').substring(1)); new Ajax.Request(newURL , { method: 'GET', onSuccess: this._onTemplateListAvailable.bind(this) }); }, /** * Returns True if this template selector is the one displayed on startup * * @method isStartupTemplateSelector * @return {Boolean} */ isStartupTemplateSelector: function () { return this._isStartupTemplateSelector; }, /** * Displays the templates once they have been downloaded * * @param response * @private */ _onTemplateListAvailable: function (response) { this.mainDiv.update(); var objects = response.responseXML.documentElement.getElementsByTagName('objectSummary'); for (var i = 0; i < objects.length; ++i) { var pictureBox = new Element('div', {'class': 'picture-box'}); pictureBox.update("Loading..."); this.mainDiv.insert(pictureBox); var href = getSelectorFromXML(objects[i], "link", "rel", "http://www.xwiki.org/rel/properties").getAttribute("href"); // Use only the path, since the REST module returns the wrong host behind a reverse proxy var path = href.substring(href.indexOf("/", href.indexOf("//") + 2)); var settings = new Settings(); debugger var newURL = settings.getAbsoluteURL("/rest" + path); //new Ajax.Request(href, { new Ajax.Request(newURL, { method: 'GET', onSuccess: this._onTemplateAvailable.bind(this, pictureBox) }); } }, /** * Creates a clickable template thumbnail once the information has been downloaded * * @param pictureBox * @param response * @private */ _onTemplateAvailable: function (pictureBox, response) { pictureBox.innerHTML = getSubSelectorTextFromXML(response.responseXML, "property", "name", "image", "value").replace(/&amp;/, '&'); pictureBox.pedigreeData = getSubSelectorTextFromXML(response.responseXML, "property", "name", "data", "value"); pictureBox.type = 'internal'; pictureBox.description = getSubSelectorTextFromXML(response.responseXML, "property", "name", "description", "value"); pictureBox.title = pictureBox.description; //console.log("[Data from Template] - " + Helpers.stringifyObject(pictureBox.pedigreeData)); // TODO: render images with JavaScript instead if (window.SVGSVGElement && document.implementation.hasFeature("http://www.w3.org/TR/SVG11/feature#Image", "1.1")) { pictureBox.update(getSubSelectorTextFromXML(response.responseXML, "property", "name", "image", "value")); } else { pictureBox.innerHTML = "<table bgcolor='#FFFAFA'><tr><td><br>&nbsp;" + pictureBox.description + "&nbsp;<br><br></td></tr></table>"; } pictureBox.observe('click', this._onTemplateSelected.bindAsEventListener(this, pictureBox)); }, /** * Loads the template once it has been selected * * @param event * @param pictureBox * @private */ _onTemplateSelected: function (event, pictureBox) { //console.log("observe onTemplateSelected"); this.dialog.close(); if (pictureBox.type == 'internal') { editor.getSaveLoadEngine().createGraphFromSerializedData(pictureBox.pedigreeData, false /* add to undo stack */, true /*center around 0*/); } else if (pictureBox.type == 'simpleJSON') { editor.getSaveLoadEngine().createGraphFromImportData(pictureBox.pedigreeData, 'simpleJSON', {}, false /* add to undo stack */, true /*center around 0*/); } }, /** * Displays the template selector * * @method show */ show: function () { var availableHeight = document.viewport.getHeight() - 80; this.mainDiv.setStyle({'max-height': availableHeight + 'px', 'overflow-y': 'auto'}); this.dialog.show(); }, /** * Removes the the template selector * * @method hide */ hide: function () { this.dialog.closeDialog(); } }); // TODO: replace XML loading with a service providing JSONs function unescapeRestData(data) { // http://stackoverflow.com/questions/4480757/how-do-i-unescape-html-entities-in-js-change-lt-to var tempNode = document.createElement('div'); tempNode.innerHTML = data.replace(/&amp;/, '&'); return tempNode.innerText || tempNode.text || tempNode.textContent; } function getSelectorFromXML(responseXML, selectorName, attributeName, attributeValue) { if (responseXML.querySelector) { // modern browsers return responseXML.querySelector(selectorName + "[" + attributeName + "='" + attributeValue + "']"); } else { // IE7 && IE8 && some other older browsers // http://www.w3schools.com/XPath/xpath_syntax.asp // http://msdn.microsoft.com/en-us/library/ms757846%28v=vs.85%29.aspx var query = ".//" + selectorName + "[@" + attributeName + "='" + attributeValue + "']"; try { return responseXML.selectSingleNode(query); } catch (e) { // Firefox v3.0- alert("your browser is unsupported"); window.stop && window.stop(); throw "Unsupported browser"; } } } function getSubSelectorTextFromXML(responseXML, selectorName, attributeName, attributeValue, subselectorName) { var selector = getSelectorFromXML(responseXML, selectorName, attributeName, attributeValue); var value = selector.innerText || selector.text || selector.textContent; if (!value) // fix IE behavior where (undefined || "" || undefined) == undefined value = ""; return value; }
JavaScript
0.00001
@@ -1412,27 +1412,16 @@ ings();%0A -%09%09debugger%0A %09%09var ne @@ -2689,20 +2689,8 @@ ();%0A -%09%09%09debugger%0A %09%09%09v
82ad6a6eb3f09c073eb3cf8e7626bfd05ef04fa7
remove console
js/saiku/views/Upgrade.js
js/saiku/views/Upgrade.js
/* * Copyright 2012 OSBI Ltd * * 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. */ /** * The global toolbar */ var Upgrade = Backbone.View.extend({ tagName: "div", events: { 'click .upgradeheader' : 'call' }, template: function() { var template = $("#template-upgrade").html() || ""; return _.template(template)(); }, initialize: function() { }, render: function() { if (!Settings.UPGRADE) return this; var timeout = Saiku.session.upgradeTimeout; var localStorageUsed = false; var first = true; if (typeof localStorage !== "undefined" && localStorage) { if (localStorage.getItem("saiku.upgradeTimeout") !== null) { timeout = localStorage.getItem("saiku.upgradeTimeout"); } localStorageUsed = true; } var current = (new Date()).getTime(); console.log("timeout: " + (!timeout) + " localstorage: " + localStorageUsed + " : diff " + (current - timeout)); if (!timeout || (current - timeout) > (10 * 60 * 1000)) { $(this.el).html(this.template()); Saiku.session.upgradeTimeout = current; if (typeof localStorage !== "undefined" && localStorage) { localStorage.setItem("saiku.upgradeTimeout", current); } } return this; }, call: function(e) { $(".upgradeheader").slideUp("slow"); setTimeout("showIt()",15000); } });
JavaScript
0.000002
@@ -1470,129 +1470,8 @@ ();%0A - console.log(%22timeout: %22 + (!timeout) + %22 localstorage: %22 + localStorageUsed + %22 : diff %22 + (current - timeout));%0A
a9920a53764c39c826a7e85048984ac71cf59386
fix #3
js/src/partition/hoare.js
js/src/partition/hoare.js
/** * HYP : i < j */ var hoare = function ( predicate, a, i, j ) { var x, t, o; o = i; x = a[o]; while ( true ) { while ( true ) { --j; if ( i >= j ) { t = a[o]; a[o] = a[j]; a[j] = t; return j; } if ( predicate( a[j], x ) ) { break; } } while ( true ) { ++i; if ( i >= j ) { t = a[o]; a[o] = a[j]; a[j] = t; return j; } if ( predicate( x, a[i] ) ) { break; } } // invariant i < j t = a[i]; a[i] = a[j]; a[j] = t; } }; exports.hoare = hoare; exports.partition = hoare;
JavaScript
0.000003
@@ -231,32 +231,37 @@ urn j;%0A%09%09%09%7D%0A%0A%09%09%09 +else if ( predicate( @@ -410,24 +410,29 @@ j;%0A%09%09%09%7D%0A%0A%09%09%09 +else if ( predica
381d33fe6cb2dce497d092647534310cd9cd4bf8
Implement d3 updates for grouped bars
src/components/BarChart.js
src/components/BarChart.js
import React, { PropTypes } from 'react' import Faux from 'react-faux-dom' import * as d3 from 'd3' import styled from 'styled-components' const { arrayOf, array, string, number } = PropTypes const BarChart = React.createClass({ mixins: [Faux.mixins.core, Faux.mixins.anim], propTypes: { data: arrayOf(array), xDomain: array, colors: arrayOf(string), className: string, xLabel: string, yLabel: string, width: number, height: number }, getInitialState () { return { look: 'stacked', chart: 'loading...' } }, componentDidMount () { this.renderD3(true) }, componentDidUpdate (prevProps, prevState) { if (this.props !== prevProps) { this.renderD3(false) } }, render () { return ( <div> <button onClick={this.toggle}>Toggle</button> {this.state.chart} </div> ) }, toggle () { if (this.state.look === 'stacked') { this.setState({ look: 'grouped' }) this.transitionGrouped() } else { this.setState({ look: 'stacked' }) this.transitionStacked() } }, renderD3 (firstRender) { const n = this.props.data.length // number of layers const stack = d3.layout.stack() const layers = stack(this.props.data) const yGroupMax = d3.max(layers, layer => d3.max(layer, d => d.y)) const yStackMax = d3.max(layers, layer => d3.max(layer, d => d.y0 + d.y)) const margin = { top: 20, right: 10, bottom: 50, left: 50 } const width = this.props.width - margin.left - margin.right const height = this.props.height - margin.top - margin.bottom const x = d3.scale.ordinal().domain(this.props.xDomain).rangeRoundBands([0, width], 0.08) const y = d3.scale.linear().domain([0, yStackMax]).range([height, 0]) const color = d3.scale.linear().domain([0, n - 1]).range(this.props.colors) const xAxis = d3.svg.axis().scale(x).orient('bottom') const yAxis = d3.svg.axis().scale(y).orient('left') // create a faux div and store its virtual DOM in state.chart let faux = this.connectFauxDOM('div', 'chart') let svg = firstRender ? d3 .select(faux) .append('svg') .attr('class', this.props.className) .attr('width', width + margin.left + margin.right) .attr('height', height + margin.top + margin.bottom) .append('g') .attr('transform', `translate(${margin.left}, ${margin.top})`) : d3.select(faux).select('svg').select('g') let layer = svg.selectAll('.layer').data(layers) layer.enter().append('g').attr('class', 'layer').style('fill', (d, i) => color(i)) let rect = layer.selectAll('rect').data(d => d) rect.enter().append('rect').attr('x', d => x(d.x)).attr('y', height).attr('width', x.rangeBand()).attr('height', 0) rect .transition() .delay((d, i) => i * 10) .attr('y', d => y(d.y0 + d.y)) .attr('height', d => y(d.y0) - y(d.y0 + d.y)) this.animateFauxDOM(800) if (firstRender) { svg.append('g').attr('class', 'x axis').attr('transform', `translate(0, ${height})`).call(xAxis) svg .append('text') .attr('transform', `translate(${width / 2} ,${height + margin.bottom - 5})`) .style('text-anchor', 'middle') .text(this.props.xLabel) svg.append('g').attr('class', 'y axis').attr('transform', 'translate(0, 0)').call(yAxis) svg .append('text') .attr('transform', 'rotate(-90)') .attr('y', 0 - margin.left) .attr('x', 0 - height / 2) .attr('dy', '1em') .style('text-anchor', 'middle') .text(this.props.yLabel) } else { svg.select('g.x.axis').call(xAxis) svg.select('g.y.axis').call(yAxis) } this.transitionGrouped = () => { y.domain([0, yGroupMax]) rect .transition() .duration(500) // .delay((d, i) => i * 10) .attr('x', (d, i, j) => x(d.x) + x.rangeBand() / n * j) .attr('width', x.rangeBand() / n) .transition() .attr('y', d => y(d.y)) .attr('height', d => height - y(d.y)) this.animateFauxDOM(2000) } this.transitionStacked = () => { y.domain([0, yStackMax]) rect .transition() .duration(500) // .delay((d, i) => i * 10) .attr('y', d => y(d.y0 + d.y)) .attr('height', d => y(d.y0) - y(d.y0 + d.y)) .transition() .attr('x', d => x(d.x)) .attr('width', x.rangeBand()) this.animateFauxDOM(2000) } } }) const StyledBarChart = styled(BarChart)` .x.axis line, .x.axis path, .y.axis line, .y.axis path { fill: none; stroke: #000; } ` export default StyledBarChart
JavaScript
0
@@ -2808,16 +2808,59 @@ ht', 0)%0A + if (this.state.look === 'stacked') %7B%0A rect @@ -2856,24 +2856,26 @@ %0A rect%0A + .trans @@ -2888,16 +2888,18 @@ )%0A + .delay(( @@ -2917,24 +2917,26 @@ * 10)%0A + + .attr('y', d @@ -2950,24 +2950,26 @@ .y0 + d.y))%0A + .attr( @@ -3004,24 +3004,187 @@ .y0 + d.y))%0A + %7D else %7B%0A rect%0A .transition()%0A .delay((d, i) =%3E i * 10)%0A .attr('y', d =%3E y(d.y))%0A .attr('height', d =%3E height - y(d.y))%0A %7D%0A this.ani
bfb279f700d5e3addef8e0df72a429b518cffef7
add compatibility comment
src/select/select.js
src/select/select.js
import {bindable, customAttribute} from 'aurelia-templating'; import {BindingEngine} from 'aurelia-binding'; import {inject} from 'aurelia-dependency-injection'; import {TaskQueue} from 'aurelia-task-queue'; import * as LogManager from 'aurelia-logging'; import {fireEvent} from '../common/events'; import {DOM} from 'aurelia-pal'; @inject(Element, LogManager, BindingEngine, TaskQueue) @customAttribute('md-select') export class MdSelect { @bindable() disabled = false; @bindable() label = ''; _suspendUpdate = false; subscriptions = []; input = null; dropdownMutationObserver = null; constructor(element, logManager, bindingEngine, taskQueue) { this.element = element; this.taskQueue = taskQueue; this.handleChangeFromViewModel = this.handleChangeFromViewModel.bind(this); this.handleChangeFromNativeSelect = this.handleChangeFromNativeSelect.bind(this); this.handleBlur = this.handleBlur.bind(this); this.log = LogManager.getLogger('md-select'); this.bindingEngine = bindingEngine; } attached() { this.subscriptions.push(this.bindingEngine.propertyObserver(this.element, 'value').subscribe(this.handleChangeFromViewModel)); // this.subscriptions.push(this.bindingEngine.propertyObserver(this.element, 'selectedOptions').subscribe(this.notifyBindingEngine.bind(this))); // $(this.element).material_select(() => { // this.log.warn('materialize callback', $(this.element).val()); // this.handleChangeFromNativeSelect(); // }); this.createMaterialSelect(false); if (this.label) { let wrapper = $(this.element).parent('.select-wrapper'); let div = $('<div class="input-field"></div>'); let va = this.element.attributes.getNamedItem('validate'); if (va) { div.attr(va.name, va.label); } wrapper.wrap(div); $(`<label>${this.label}</label>`).insertAfter(wrapper); } $(this.element).on('change', this.handleChangeFromNativeSelect); } detached() { $(this.element).off('change', this.handleChangeFromNativeSelect); this.observeVisibleDropdownContent(false); this.dropdownMutationObserver = null; $(this.element).material_select('destroy'); this.subscriptions.forEach(sub => sub.dispose()); } refresh() { this.taskQueue.queueTask(() => { this.createMaterialSelect(true); }); } disabledChanged(newValue) { this.toggleControl(newValue); } notifyBindingEngine() { this.log.debug('selectedOptions changed', arguments); } handleChangeFromNativeSelect() { if (!this._suspendUpdate) { this.log.debug('handleChangeFromNativeSelect', this.element.value, $(this.element).val()); this._suspendUpdate = true; fireEvent(this.element, 'change'); this._suspendUpdate = false; } } handleChangeFromViewModel(newValue) { this.log.debug('handleChangeFromViewModel', newValue, $(this.element).val()); if (!this._suspendUpdate) { this.createMaterialSelect(false); } } toggleControl(disable) { let $wrapper = $(this.element).parent('.select-wrapper'); if ($wrapper.length > 0) { if (disable) { $('.caret', $wrapper).addClass('disabled'); $('input.select-dropdown', $wrapper).attr('disabled', 'disabled'); $wrapper.attr('disabled', 'disabled'); } else { $('.caret', $wrapper).removeClass('disabled'); $('input.select-dropdown', $wrapper).attr('disabled', null); $wrapper.attr('disabled', null); $('.select-dropdown', $wrapper).dropdown({'hover': false, 'closeOnClick': false}); } } } createMaterialSelect(destroy) { this.observeVisibleDropdownContent(false); if (destroy) { $(this.element).material_select('destroy'); } $(this.element).material_select(); this.toggleControl(this.disabled); this.observeVisibleDropdownContent(true); } observeVisibleDropdownContent(attach) { if (attach) { if (!this.dropdownMutationObserver) { this.dropdownMutationObserver = DOM.createMutationObserver(mutations => { let isHidden = false; for (let mutation of mutations) { if (window.getComputedStyle(mutation.target).getPropertyValue('display') === 'none') { isHidden = true; } } if (isHidden) { this.dropdownMutationObserver.takeRecords(); this.handleBlur(); } }); } this.dropdownMutationObserver.observe(this.element.parentElement.querySelector('.dropdown-content'), { attributes: true, attributeFilter: ['style'] }); } else { if (this.dropdownMutationObserver) { this.dropdownMutationObserver.disconnect(); this.dropdownMutationObserver.takeRecords(); } } } // // Firefox sometimes fire blur several times in a row // observable at http://localhost:3000/#/samples/select/ // when enable 'Disable Functionality', open that list and // then open 'Basic use' list. // Chrome - ok // IE ? // _taskqueueRunning = false; handleBlur() { if (this._taskqueueRunning) return; this._taskqueueRunning = true; this.taskQueue.queueTask(() => { this.log.debug('fire blur event'); fireEvent(this.element, 'blur'); this._taskqueueRunning = false; }); } }
JavaScript
0
@@ -5053,16 +5053,34 @@ // IE +11 - ok%0A // Edge ?%0A //%0A
35e3f37c93adae953af210ef28f1d930300022f0
Clean up code styles
autoHeightWebView/utils.js
autoHeightWebView/utils.js
'use strict'; import { Dimensions, Platform } from 'react-native'; const domMutationObserveScript = ` var MutationObserver = window.MutationObserver || window.WebKitMutationObserver; var observer = new MutationObserver(updateSize); observer.observe(document, { subtree: true, attributes: true }); `; const updateSizeWithMessage = element => ` var lastHeight = 0; var heightTheSameTimes = 0; var maxHeightTheSameTimes = 5; var forceRefreshDelay = 1000; var forceRefreshTimeout; function updateSize(event) { if ( !window.hasOwnProperty('ReactNativeWebView') || !window.ReactNativeWebView.hasOwnProperty('postMessage') ) { setTimeout(updateSize, 200); return; } height = ${element}.offsetHeight || document.documentElement.offsetHeight; width = ${element}.offsetWidth || document.documentElement.offsetWidth; window.ReactNativeWebView.postMessage(JSON.stringify({ width: width, height: height })); // Make additional height checks (required to fix issues wit twitter embeds) clearTimeout(forceRefreshTimeout); if (lastHeight !== height) { heightTheSameTimes = 1; } else { heightTheSameTimes++; } lastHeight = height; if (heightTheSameTimes <= maxHeightTheSameTimes) { forceRefreshTimeout = setTimeout( updateSize, heightTheSameTimes * forceRefreshDelay ); } } `; // add viewport setting to meta for WKWebView const makeScalePageToFit = zoomable => ` var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width, user-scalable=${ zoomable ? 'yes' : 'no' }'); document.getElementsByTagName('head')[0].appendChild(meta); `; const getBaseScript = ({ style, zoomable }) => ` ; if (!document.getElementById("rnahw-wrapper")) { var wrapper = document.createElement('div'); wrapper.id = 'rnahw-wrapper'; while (document.body.firstChild instanceof Node) { wrapper.appendChild(document.body.firstChild); } document.body.appendChild(wrapper); } ${updateSizeWithMessage('wrapper')} window.addEventListener('load', updateSize); window.addEventListener('resize', updateSize); ${domMutationObserveScript} ${makeScalePageToFit(zoomable)} updateSize(); `; const appendFilesToHead = ({ files, script }) => files.reduceRight((combinedScript, file) => { const { rel, type, href } = file; return ` var link = document.createElement('link'); link.rel = '${rel}'; link.type = '${type}'; link.href = '${href}'; document.head.appendChild(link); ${combinedScript} `; }, script); const screenWidth = Dimensions.get('window').width; const bodyStyle = ` body { margin: 0; padding: 0; } `; const appendStylesToHead = ({ style, script }) => { const currentStyles = style ? bodyStyle + style : bodyStyle; // Escape any single quotes or newlines in the CSS with .replace() const escaped = currentStyles.replace(/\'/g, "\\'").replace(/\n/g, '\\n'); return ` var styleElement = document.createElement('style'); styleElement.innerHTML = '${escaped}'; document.head.appendChild(styleElement); ${script} `; }; const getInjectedSource = ({ html, script }) => ` ${html} <script> // prevents code colissions with global scope (() => { ${script} })(); </script> `; const getScript = ({ files, customStyle, customScript, style, zoomable }) => { let script = getBaseScript({ style, zoomable }); script = files && files.length > 0 ? appendFilesToHead({ files, script }) : script; script = appendStylesToHead({ style: customStyle, script }); customScript && (script = customScript + script); return script; }; export const getWidth = style => { return style && style.width ? style.width : screenWidth; }; export const isSizeChanged = ({ height, previousHeight, width, previousWidth }) => { if (!height || !width) { return; } return height !== previousHeight || width !== previousWidth; }; export const reduceData = props => { const { source } = props; const script = getScript(props); const { html, baseUrl } = source; if (html) { return { currentSource: { baseUrl, html: getInjectedSource({ html, script }) } }; } else { return { currentSource: source, script }; } }; export const shouldUpdate = ({ prevProps, nextProps }) => { if (!(prevProps && nextProps)) { return true; } for (const prop in nextProps) { if (nextProps[prop] !== prevProps[prop]) { if (typeof nextProps[prop] === 'object' && typeof prevProps[prop] === 'object') { if (shouldUpdate({ prevProps: prevProps[prop], nextProps: nextProps[prop] })) { return true; } } else { return true; } } } return false; };
JavaScript
0.000001
@@ -1443,22 +1443,8 @@ meta - for WKWebView %0Acon
42d122b9ea4684ef417e9b6b3b5df4e0e630ddba
Make ComponentName components link to the API section about it
demo/src/components/ComponentName/ComponentName.js
demo/src/components/ComponentName/ComponentName.js
import React, { PropTypes } from 'react'; import './ComponentName.scss'; const ComponentName = ({ children }) => ( <span className="ComponentName">{`<${children}>`}</span> ); ComponentName.propTypes = { children: PropTypes.string.isRequired, }; export default ComponentName;
JavaScript
0
@@ -114,20 +114,116 @@ =%3E (%0A %3C -span +a%0A href=%7B%60https://github.com/joshwcomeau/react-collection-helpers#$%7Bchildren.toLowerCase()%7D%60%7D%0A classNa @@ -240,17 +240,25 @@ entName%22 -%3E +%0A %3E%0A %7B%60%3C$%7Bchi @@ -270,14 +270,14 @@ %7D%3E%60%7D -%3C/span +%0A %3C/a %3E%0A);
b3836d895528f1fa001ae532dbe1b2fa5a7304bf
Fix typo
src/components/Settings.js
src/components/Settings.js
'use strict'; import React, { Component, TouchableOpacity, StyleSheet, Text, View, Alert } from 'react-native'; // import css variables import design from '../design'; import * as ideaActions from '../actions/ideaActions'; import {bindActionCreators} from 'redux'; import { connect } from 'react-redux'; import ActivityView from 'react-native-activity-view'; class Settings extends Component { constructor(props) { super(props); } _handleShare() { const { state } = this.props; var ideasString = state.ideas.map((idea, index) => { return state.ideas.length - parseInt(index) + '-' + idea.title; }).reverse().join('\n'); ideasString = 'My idea list:\n\n' + ideasString; console.log('ideasString', ideasString); ActivityView.show({ text: ideasString }); } _handleResetIdeas() { const { actions } = this.props; Alert.alert( 'Confirm suppression', 'Are you sure you want to delete all of your ideas?', [{ text: 'OK', onPress: () => { actions.reset(); this.props.navigator.pop(); } }, { text: 'Cancel' }] ); } render() { return ( <View style={styles.container}> <Text style={styles.inputLabel}> Send or share your idea list: </Text> <TouchableOpacity onPress={this._handleShare.bind(this)} style={design.designComp.button}> <Text style={design.designComp.buttonText}>Email/Share</Text> </TouchableOpacity> <Text style={styles.inputLabel}> Delete your idea list: </Text> <TouchableOpacity onPress={this._handleResetIdeas.bind(this)} style={design.designComp.button}> <Text style={design.designComp.buttonText}>Reset ideas</Text> </TouchableOpacity> </View> ); } } export default connect( state => ({ state: state.ideas }), (dispatch) => ({ actions: bindActionCreators(ideaActions, dispatch) }) )(Settings); const styles = StyleSheet.create({ container: { flex: 1 }, inputLabel: { paddingLeft: 17, paddingTop: 24, fontSize: 20 } });
JavaScript
0.999999
@@ -508,19 +508,19 @@ s;%0A%0A -var +let ideasSt @@ -717,54 +717,8 @@ ing; -%0A%0A console.log('ideasString', ideasString); %0A