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
dc8ab40e241f8a4d9cd1c6771b85f1a1657da0e0
Add note regarding username/password interchange.
recipes/sentiment_analysis/config.default.js
recipes/sentiment_analysis/config.default.js
// User-specific configuration exports.sentiment_keyword = "education"; // keyword to monitor in Twitter exports.sentiment_analysis_frequency_sec = 30; // analyze sentiment every N seconds // Create the credentials object for export exports.credentials = {}; // Watson Tone Analyzer // https://www.ibm.com/watson/developercloud/tone-analyzer.html exports.credentials.tone_analyzer = { password: '', username: '' }; // Twitter exports.credentials.twitter = { consumer_key: '', consumer_secret: '', access_token_key: '', access_token_secret: '' };
JavaScript
0
@@ -1,11 +1,11 @@ / -/ +*%0A User-spe @@ -24,16 +24,277 @@ uration%0A + ** IMPORTANT NOTE ********************%0A * Please ensure you do not interchange your username and password.%0A * Hint: Your username is the lengthy value ~ 36 digits including a hyphen%0A * Hint: Your password is the smaller value ~ 12 characters%0A*/ %0A%0A%0A exports.
8e17093451f397771b9cd556b505f83e64edc34d
remove map option from gmap
app/directives/gmap.js
app/directives/gmap.js
define(['./module.js', 'async!http://maps.google.com/maps/api/js?v=3.exp&sensor=false', '../util/colors.js', 'underscore'], function(module, google, colors, _) { return module.directive('gmap', ['$window', function($window, regions) { var map, currentFeatures = null, infowindow, gmapsListeners = [], geojsonCache, defaultStyle = { strokeColor: null, strokeOpacity: 0.75, strokeWeight: 2, fillColor: null, fillOpacity: 0.25 }; function init(rootEl) { infowindow = new $window.google.maps.InfoWindow(); map = new $window.google.maps.Map(rootEl, { zoom: 2, center: new $window.google.maps.LatLng(13.6036603, -101.313101), mapTypeId: $window.google.maps.MapTypeId.SATELLITE }); } function setInfoWindow(event) { var content = '<div id="infoBox">', key, CBDbaseUrl = 'https://chm.cbd.int/database/record?documentID=', ebsaID = event.feature.getProperty('KEY'); event.feature.forEachProperty(function(propVal, propName) { if (propName == 'NAME') { content += '<strong>' + propVal + '</strong><br /><br />'; } else if (_.indexOf(['KEY', 'style', 'WORKSHOP'] !== -1)) { return; } else { content += propName + ': ' + propVal + '<br /><br />'; } }); content += '<a class="pull-right" target="_blank" href="' + CBDbaseUrl + ebsaID + '">Details »</a>'; content += '</div>'; infowindow.setContent(content); infowindow.setPosition(event.latLng); infowindow.open(map); } function cleanupListeners(e) { $window.google.maps.event.removeListener(listener); } function clearMap(map) { if (infowindow.getMap()) infowindow.close(); map.data.forEach(function(feature) { map.data.remove(feature); }); } var listener; function displayRegion(regionData, regionName) { map.data.addGeoJson(regionData); listener = map.data.addListener('click', setInfoWindow); } function applyStyles() { map.data.setStyle(function(feature) { return angular.extend({}, defaultStyle, feature.getProperty('style')); }); } function updateSelectedRegion(regionName) { if (!geojsonCache) return; clearMap(map); if (!regionName) { angular.forEach(geojsonCache, function(regionData, regionName) { displayRegion(regionData, regionName); }); applyStyles(); return; } displayRegion(geojsonCache[regionName], regionName); applyStyles(); } return { restrict: 'EA', template: '<div id="map"></div>', replace: true, scope: { regions: '=', selectedRegion: '=' }, link: function(scope, element, attrs) { init(element.get(0)); scope.$watch('selectedRegion', updateSelectedRegion); scope.$watch('regions', function(regions) { if (!regions) return; geojsonCache = regions; updateSelectedRegion(null); }); scope.$on('$destroy', cleanupListeners); } }; } ]); });
JavaScript
0.000001
@@ -871,16 +871,136 @@ ATELLITE +,%0A mapTypeControlOptions: %7B%0A mapTypeIds: %5B$window.google.maps.MapTypeId.SATELLITE%5D%0A %7D %0A
7dd0f249af018e2befb06bf7755fba464bb03735
Update the DateRangeSelector component.
assets/js/components/DateRangeSelector.js
assets/js/components/DateRangeSelector.js
/** * Date range selector component. * * Site Kit by Google, Copyright 2021 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 { useClickAway } from 'react-use'; /** * WordPress dependencies */ import { useCallback, useRef, useState } from '@wordpress/element'; import { ESCAPE, TAB } from '@wordpress/keycodes'; /** * Internal dependencies */ import Data from 'googlesitekit-data'; import DateRangeIcon from '../../svg/date-range.svg'; import Menu from './Menu'; import { getAvailableDateRanges } from '../util/date-range'; import { CORE_USER } from '../googlesitekit/datastore/user/constants'; import { useKeyCodesInside } from '../hooks/useKeyCodesInside'; import Button from './Button'; const { useSelect, useDispatch } = Data; function DateRangeSelector() { const ranges = getAvailableDateRanges(); const dateRange = useSelect( ( select ) => select( CORE_USER ).getDateRange() ); const { setDateRange } = useDispatch( CORE_USER ); const [ menuOpen, setMenuOpen ] = useState( false ); const menuWrapperRef = useRef(); useClickAway( menuWrapperRef, () => setMenuOpen( false ) ); useKeyCodesInside( [ ESCAPE, TAB ], menuWrapperRef, () => setMenuOpen( false ) ); const handleMenu = useCallback( () => { setMenuOpen( ! menuOpen ); }, [ menuOpen ] ); const handleMenuItemSelect = useCallback( ( index ) => { setDateRange( Object.values( ranges )[ index ].slug ); setMenuOpen( false ); }, [ ranges, setDateRange ] ); const currentDateRangeLabel = ranges[ dateRange ]?.label; const menuItems = Object.values( ranges ).map( ( range ) => range.label ); return ( <div ref={ menuWrapperRef } className="googlesitekit-date-range-selector googlesitekit-dropdown-menu mdc-menu-surface--anchor" > <Button className="googlesitekit-header__date-range-selector-menu mdc-button--dropdown googlesitekit-header__dropdown" text onClick={ handleMenu } icon={ <DateRangeIcon width="18" height="20" /> } aria-haspopup="menu" aria-expanded={ menuOpen } aria-controls="date-range-selector-menu" > { currentDateRangeLabel } </Button> <Menu menuOpen={ menuOpen } menuItems={ menuItems } onSelected={ handleMenuItemSelect } id="date-range-selector-menu" className="googlesitekit-width-auto" /> </div> ); } export default DateRangeSelector;
JavaScript
0
@@ -795,16 +795,28 @@ useState +, useContext %7D from @@ -1019,96 +1019,8 @@ g';%0A -import Menu from './Menu';%0Aimport %7B getAvailableDateRanges %7D from '../util/date-range';%0A impo @@ -1161,32 +1161,217 @@ ort -Button from './Button';%0A +%7B getAvailableDateRanges %7D from '../util/date-range';%0Aimport ViewContextContext from './Root/ViewContextContext';%0Aimport Menu from './Menu';%0Aimport Button from './Button';%0Aimport %7B trackEvent %7D from '../util'; %0Acon @@ -1409,16 +1409,31 @@ Data;%0A%0A +export default function @@ -1722,16 +1722,71 @@ seRef(); +%0A%09const viewContext = useContext( ViewContextContext ); %0A%0A%09useCl @@ -2064,16 +2064,22 @@ back(%0A%09%09 +async ( index @@ -2088,19 +2088,25 @@ =%3E %7B%0A%09%09%09 -set +const new DateRang @@ -2106,17 +2106,18 @@ ateRange -( + = Object. @@ -2146,19 +2146,204 @@ x %5D.slug - ); +;%0A%09%09%09if ( dateRange !== newDateRange ) %7B%0A%09%09%09%09await trackEvent(%0A%09%09%09%09%09%60$%7B viewContext %7D_headerbar%60,%0A%09%09%09%09%09'change_daterange',%0A%09%09%09%09%09newDateRange%0A%09%09%09%09);%0A%0A%09%09%09%09setDateRange( newDateRange );%0A%09%09%09%7D%0A %0A%09%09%09setM @@ -2389,16 +2389,40 @@ ateRange +, viewContext, dateRange %5D%0A%09);%0A%0A @@ -3274,39 +3274,4 @@ ;%0A%7D%0A -%0Aexport default DateRangeSelector;%0A
21e534466ee35b049d9fc0ef30de589a237bfd06
Disable visibility by default.
src/example/containers/dev-tools.js
src/example/containers/dev-tools.js
import React from 'react'; // Exported from redux-devtools import { createDevTools } from 'redux-devtools'; // Monitors are separate packages, and you can make a custom one import DockMonitor from 'redux-devtools-dock-monitor'; import MultipleMonitors from 'redux-devtools-multiple-monitors'; import Inspector from 'redux-devtools-inspector'; import Dispatcher from 'redux-devtools-dispatch'; import * as projectActions from '../actions/user-actions'; import * as formActions from '../../actions/form'; // createDevTools takes a monitor and produces a DevTools component const DevTools = createDevTools( // Monitors are individually adjustable with props. // Consult their repositories to learn about those props. // Here, we put LogMonitor inside a DockMonitor. <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q' defaultSize={0.5}> <MultipleMonitors> <Inspector /> <Dispatcher actionCreators={{...projectActions, ...formActions}} /> </MultipleMonitors> </DockMonitor> ); export default DevTools;
JavaScript
0
@@ -864,9 +864,34 @@ =%7B0. -5 +4%7D defaultIsVisible=%7Bfalse %7D%3E%0A
7b6835522d40340cbba96bced91284adff67d76e
improve log for server creation
run_bot.js
run_bot.js
#!/usr/bin/nodejs /** * Part of the evias/nem-nodejs-bot package. * * NOTICE OF LICENSE * * Licensed under MIT License. * * This source file is subject to the MIT License that is * bundled with this package in the LICENSE file. * * @package evias/nem-nodejs-bot * @author Grégory Saive <[email protected]> * @license MIT License * @copyright (c) 2017, Grégory Saive <[email protected]> * @link http://github.com/evias/nem-nodejs-bot */ var app = require('express')(), server = require('http').createServer(app), path = require('path'), auth = require("http-auth"), bodyParser = require("body-parser"), SecureConf = require("secure-conf"), fs = require("fs"), pw = require("pw"); // core dependencies var logger = require('./src/utils/logger.js'); var __smartfilename = path.basename(__filename); var serverLog = function(req, msg, type) { var logMsg = "[" + type + "] " + msg + " (" + (req.headers ? req.headers['x-forwarded-for'] : "?") + " - " + (req.connection ? req.connection.remoteAddress : "?") + " - " + (req.socket ? req.socket.remoteAddress : "?") + " - " + (req.connection && req.connection.socket ? req.connection.socket.remoteAddress : "?") + ")"; logger.info(__smartfilename, __line, logMsg); }; // define a helper to get the blockchain service var chainDataLayers = {}; var getChainService = function(config) { var thisBot = config.bot.walletAddress; if (! chainDataLayers.hasOwnProperty(thisBot)) { var blockchain = require('./src/blockchain/service.js'); chainDataLayers[thisBot] = new blockchain.service(config); } return chainDataLayers[thisBot]; }; /** * Delayed route configuration. This will only be triggered when * the configuration file can be decrypted. * * Following is where we set our Bot's API endpoints. The API * routes list will change according to the Bot's "mode" config * value. */ var serveAPI = function(config) { // configure body-parser usage for POST API calls. app.use(bodyParser.urlencoded({ extended: true })); /** * API Routes * * Following routes are used for handling the business/data * layer provided by this NEM Bot. */ app.get("/api/v1/ping", function(req, res) { res.setHeader('Content-Type', 'application/json'); res.send(JSON.stringify({item: {pong: new Date().valueOf()}})); }); //XXX read config and serve given API endpoints. }; /** * Delayed Server listener configuration. This will only be triggered when * the configuration file can be decrypted. * * Following is where we Start the express Server and where the routes will * be registered. */ var startBotServer = function(config) { /** * Now listen for connections on the Web Server. * * This starts the NodeJS server and makes the Game * available from the Browser. */ var port = process.env['PORT'] = process.env.PORT || 29081; server.listen(port, function() { var network = getChainService(config).getNetwork(); var blockchain = network.isTest ? "Testnet Blockchain" : network.isMijin ? "Mijin Private Blockchain" : "NEM Mainnet Public Blockchain"; var botWallet = getChainService(config).getBotWallet(); console.log("------------------------------------------------------------------------"); console.log("-- NEM Bot by eVias --"); console.log("------------------------------------------------------------------------"); console.log("-"); console.log("- NEM Bot Server listening on Port %d in %s mode", this.address().port, app.settings.env); console.log("- NEM Bot is using blockchain: " + blockchain); console.log("- NEM Bot Wallet is: " + botWallet); console.log("-") console.log("------------------------------------------------------------------------"); }); }; var encryptConfig = function(pass) { var dec = fs.readFileSync("config/bot.json"); var enc = sconf.encryptContent(dec, pass); if (enc === undefined) { logger.error(__smartfilename, __line, "Configuration file config/bot.json could not be encrypted."); logger.warn(__smartfilename, __line, "NEM Bot now aborting."); return false; } fs.writeFileSync("config/bot.json.enc", enc); if (app.settings.env == "production") // don't delete in development mode fs.unlink("config/bot.json"); return true; }; var startBot = function(pass) { if (fs.existsSync("config/bot.json.enc")) { // Only start the bot in case the file is found // and can be decrypted. var enc = fs.readFileSync("config/bot.json.enc", {encoding: "utf8"}); var dec = sconf.decryptContent(enc, pass); if (dec === undefined) { logger.error(__smartfilename, __line, "Configuration file config/bot.json could not be decrypted."); logger.warn(__smartfilename, __line, "NEM Bot now aborting."); } else { try { var config = JSON.parse(dec); serveAPI(config); startBotServer(config); } catch (e) { logger.error(__smartfilename, __line, "Error with NEM Bot configuration: " + e); logger.warn(__smartfilename, __line, "NEM Bot now aborting."); } } } }; /** * This Bot will only start serving its API when the configuration * file is encrypted and can be decrypted. * * In case the configuration file is not encrypted yet, it will be encrypted * and the original file will be deleted. */ var sconf = new SecureConf(); var pass = process.env["ENCRYPT_PASS"] || ""; if (typeof pass == 'undefined' || ! pass.length) { // get enc-/dec-rypt password from console if (! fs.existsSync("config/bot.json.enc")) { // encrypted configuration file not yet created console.log("Please enter a password for Encryption: "); pw(function(password) { encryptConfig(password); startBot(password); }); } else { // encrypted file exists, ask password for decryption console.log("Please enter your password: "); pw(function(password) { startBot(password); }); } } else { // use environment variable password if (! fs.existsSync("config/bot.json.enc")) // encrypted file must be created encryptConfig(pass); startBot(pass); }
JavaScript
0
@@ -3153,16 +3153,110 @@ allet(); +%0A%09%09%09var hostname = app.settings.env == 'development' ? %22localhost%22 : this.address().address; %0A%0A%09%09%09con @@ -3600,16 +3600,33 @@ Port %25d +with hostname %25s in %25s mo @@ -3650,16 +3650,26 @@ ().port, + hostname, app.set
6b2cf2bdc4149e704533523a73c0831c93010300
test production url
opw-dashboard-jquery/public_html/js/config.js
opw-dashboard-jquery/public_html/js/config.js
var debug = false; var token = "d171794c5c1f7a50aeb8f7056ab84a4fbcd6fbd594b1999bddaefdd03efc0591"; var jsonURL = "http://91.250.114.134:8080/opw/service/wynik/complete"; var cfg = { vertical: { tooltip: {isHtml: true}, legend: 'none', hAxis: { slantedText:true, slantedTextAngle:20 }, vAxis: {format: '#%'}, chartArea: {width: '90%', top: 10, height: '80%'}, seriesType: "bars", colors: ['#5CB85C'] }, map: { region: 'PL', resolution: 'provinces', colorAxis: {colors: ['#5CB85C', '#F0AD4E','#D9534F']}, backgroundColor: '#337AB7', legend: { numberFormat: "#.#'%" } } }; var okrInWoj = [ [1,2,3,4], [5,6,7], [8,9,10,11], [12,13], [14,15,16,17], [18,19,20], [21,22,23,24,25,26], [27], [28,29,30,31], [32,33,34], [35,36,37,38], [39,40,41], [42], [43,44], [45,46,47,48,49], [50,51] ]; var wojName = ['dolnośląskie','kujawsko-pomorskie','lubelskie','lubuskie', 'łódzkie','małopolskie','mazowieckie','opolskie', 'podkarpackie','podlaskie','pomorskie','śląskie', 'świętokrzyskie','warmińsko-mazurskie','wielkopolskie','zachodniopomorskie'];
JavaScript
0.000001
@@ -119,27 +119,20 @@ p:// -91.250.114.134:8080 +otwartapw.pl /opw
24d7c44009835acf57b8c5a752f962bdcfaae38e
use textContent over innerText
assets/js/components/Navigation/Search.js
assets/js/components/Navigation/Search.js
class Search { /** * Constructs Search * @param {Navigation} mainController The main navigation controller * @param {DOMElement} element The DOMElement to bind to */ constructor(mainController, element) { this.mainController = mainController; this.element = element; this.init(); } // -------------------------------------------------------------------------- /** * Initlaises the sidebar search * @returns {Search} */ init() { this.element .addEventListener('keyup', (e) => { clearTimeout(this.debounce); this.debounce = setTimeout(() => { let keywords = this.normaliseSearchString(e.srcElement.value); if (this.keywords !== keywords) { this.keywords = keywords; this.search(keywords); } }, 250); }); return this; } // -------------------------------------------------------------------------- /** * Performs a search * @param {string} keywords The search keywords * @returns {Search} */ search(keywords) { if (keywords.length) { this.filter(keywords); } else { this.reset(); } return this; } // -------------------------------------------------------------------------- /** * Filters the sidebar sections by the given keywords * @param {string} keywords * @returns {Search} */ filter(keywords) { this.mainController.adminController.log(`Filtering nav sections by: ${keywords}`); this.mainController .disableAnimation() .disableSorting(); this.hideToggles(); let regex = new RegExp(keywords, 'gi'); this.mainController .sections .forEach((section) => { section.instance.box.container .querySelectorAll('li') .forEach((item) => { let link = item.querySelector('a'); let text = this.normaliseSearchString( item.innerText + link.dataset['search-terms'] ); if (regex.test(text)) { item.classList.remove('hidden'); } else { item.classList.add('hidden'); } }); // If there are no visible options, hide the box let visible = section.instance.box.container .querySelectorAll('li:not(.hidden)') if (visible.length) { section.instance.box.element.classList.remove('hidden', 'closed'); // Size the box to accommodate visible options let height = section.instance.box.container.querySelector('ul').offsetHeight; section.instance.box.container.style.height = `${height}px`; } else { section.instance.box.element.classList.add('hidden'); } }); return this; } // -------------------------------------------------------------------------- /** * Resets the sidebar to how it was prior to searching * @returns {Search} */ reset() { this.mainController.adminController.log('Resetting...'); this.mainController .sections .forEach((section) => { section.instance.box.element .classList.remove('hidden'); section.instance.box.container .querySelectorAll('li') .forEach((item) => { item.classList.remove('hidden'); }); if (section.instance.isOpen()) { section.instance.open(); } else { section.instance.close(); } }); this.showToggles(); this.mainController .enableAnimation() .enableSorting(); return this; } // -------------------------------------------------------------------------- /** * Normalises the search term * @param searchString * @returns {string} */ normaliseSearchString(searchString) { return searchString.replace(/[^a-zA-Z0-9]/g, '').toLowerCase(); }; // -------------------------------------------------------------------------- /** * Hides all the section tiggles * @returns {Search} */ hideToggles() { this.mainController .sections .forEach((section) => { section.instance.hideToggles(); }); return this; } // -------------------------------------------------------------------------- /** * Shows all the section tiggles * @returns {Search} */ showToggles() { this.mainController .sections .forEach((section) => { section.instance.showToggles(); }); return this; } } export default Search;
JavaScript
0
@@ -2244,24 +2244,26 @@ -item.innerText + +%5Blink.textContent, lin @@ -2287,16 +2287,26 @@ -terms'%5D +%5D.join('') %0A
c7de629d48878e78742899599e13849af661be80
extract walletBar
app/javascripts/app.js
app/javascripts/app.js
// PUT YOUR UNIQUE ID HERE // (from the devadmin page, the one with '-edgware' appended) var dappId = 'pubcrawl-edgware'; // PUT YOUR CALLBACK URL HERE var callbackUrl = 'http://localhost:8080'; var web3; // the callback must EXACTLY match the string configured in the devadmin web UI. // e.g. be careful of trailing slashes // PUT YOUR CONTRACT ADDRESS HERE var contractAddress = '0x5480389cbd36a9babac289ce9ee482129acf9d7b'; window.onload = function() { var walletBar = new WalletBar({ dappNamespace: dappId, authServiceCallbackUrl: callbackUrl, containerName:'#signInId' }); web3 = new Web3(); web3.setProvider(walletBar.getHook('edgware')); //var myContract = myWeb3.eth.contract(abi).at(contractAddress); var account = walletBar.getCurrentAccount(); console.log(account); }
JavaScript
0.999993
@@ -206,16 +206,27 @@ var web3 +, walletBar ;%0A// the @@ -474,20 +474,16 @@ n() %7B%0A -var walletBa
a67e00ec3f242835025fc3050462ac4ef92c4c4c
fix merge conflicts on auth
js/client/auth.js
js/client/auth.js
/** * auth.js * Handles all of the authentication functions the client needs * to perform in conjunction with the server. * Author: Nick Rabb <[email protected]> * Yes And Games (C) 2016 * [email protected] */ /*global $*/ /*global yag_api_endpoint*/ /*global dataCacheRetrieve*/ /*global dataCacheStore*/ /*global dataCacheAuthVar*/ // Private variables var RESPONSE_OK = 0; var RESPONSE_INVALID_LOGIN = 1; var RESPONSE_UNKNOWN_ERROR = 2; var RESPONSE_SERVER_UPDATING = 3; var RESPONSE_USERNAME_TAKEN = 4; var RESPONSE_ACCOUNT_CREATED = 5; var RESPONSE_LOGGED_IN = 6; /** * Attempt to authenticate a user. * @author Nick Rabb <[email protected]> * @param {string} username The username to send to the server. * @param {string} password The password to authenticate this user with. * @param {function} callback Code to run with the login response. */ function authLogin(username, password, callback) { 'use strict'; var settings = { "async": true, "crossDomain": true, "url": yag_api_endpoint + "auth/login", "method": "POST", "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n \"username\": \"" + username + "\",\n \"password\": \"" + password + "\"\n}" }; // Make sure the user isn't already logged in if (dataCacheRetrieve(dataCacheAuthVar) !== 'undefined') { $.ajax(settings).done(function (response) { if (response !== 'undefined') { switch (response[0].loginResponse) { case (RESPONSE_OK): dataCacheStore(dataCacheAuthVar, response[0]); break; } callback(response[0].loginResponse); } }); } else { callback(RESPONSE_LOGGED_IN); } } /** * Attempt to create a user account. * @author Nick Rabb <[email protected]> * @param {string} username The username to send to the server. * @param {string} password The password to use for this user account. * @param {string} email The email to use for this user. * @param {function} callback Code to run after the with the create account response. */ function authCreateAccount(username, password, email, callback) { 'use strict'; var settings = { "async": true, "crossDomain": true, "url": yag_api_endpoint + "auth/create", "method": "POST", "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n \"username\": \"" + username + "\",\n \"password\": \"" + password + "\",\n \"email\": \"" + email + "\n}" }; $.ajax(settings).done(function (response) { if (response !== 'undefined') { switch (response.loginResponse) { case (RESPONSE_ACCOUNT_CREATED): dataCacheStore(dataCacheAuthVar, response); break; } callback(response.loginResponse); } }); } /** * Confirm a user's account. * @author Nick Rabb <[email protected]> * @param {string} confirmUUID A unique ID to confirm the account. * @param {function} callback Code to run after the with the create account response. */ function authConfirmAccount(confirmUUID, callback) { 'use strict'; var settings = { "async": true, "crossDomain": true, "url": yag_api_endpoint + "auth/confirm", "method": "POST", "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n \"confirmUUID\": \"" + confirmUUID + "\"\n}" }; $.ajax(settings).success(function (response, textStatus, xhr) { console.log(response); if (typeof response !== 'undefined') { callback(response, xhr.status); } }); } /** * Request a password change for a user. * @author Nick Rabb <[email protected]> * @param {string} username The username to send to the server. * @param {string} password The password to use for this user account. * @param {function} callback Code to run after the with the create account response. */ function authRequestPasswordChange(username, password, callback) { 'use strict'; var settings = { "async": true, "crossDomain": true, "url": yag_api_endpoint + "auth/" + username + "/password", "method": "POST", "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n \"password\": \"" + password + "\n}" }; $.ajax(settings).done(function (response, status) { if (response !== 'undefined') { callback(response); } }); } /** * Submit a user's password change. * @author Nick Rabb <[email protected]> * @param {string} username The username to send to the server. * @param {string} oldPass The user's old password * @param {string} newPass The user's new password * @param {function} callback Code to run after the with the create account response. */ function authChangePassword(username, oldPass, newPass) { 'use strict'; var settings = { "async": true, "crossDomain": true, "url": yag_api_endpoint + "auth/" + username + "/password/change", "method": "POST", "headers": { "content-type": "application/json" }, "processData": false, "data": "{\n \"oldPassword\": \"" + oldPass + "\",\n \"newPassword\": \"" + newPass + "\n}" }; $.ajax(settings).done(function (response) { if (response !== 'undefined') { callback(response); } }); }
JavaScript
0.000001
@@ -3493,33 +3493,32 @@ %22%5C%22%5Cn%7D%22%0A %7D;%0A -%0A $.ajax(setti @@ -3552,57 +3552,11 @@ onse -, textStatus, xhr) %7B%0A console.log(response); +) %7B %0A @@ -3589,32 +3589,32 @@ 'undefined') %7B%0A + callba @@ -3628,20 +3628,8 @@ onse -, xhr.status );%0A
51e66eea2cdda13212003ae40c9c8c183600d11c
remove whitespace
src/foam/nanos/crunch/Capability.js
src/foam/nanos/crunch/Capability.js
/** * @license * Copyright 2019 The FOAM Authors. All Rights Reserved. * http://www.apache.org/licenses/LICENSE-2.0 */ foam.CLASS({ package: 'foam.nanos.crunch', name: 'Capability', imports: [ 'capabilityDAO', 'prerequisiteCapabilityJunctionDAO' ], javaImports: [ 'foam.core.FObject', 'foam.core.X', 'foam.dao.ArraySink', 'foam.dao.DAO', 'foam.dao.Sink', 'foam.mlang.sink.Count', 'foam.nanos.crunch.Capability', 'foam.nanos.crunch.CapabilityCapabilityJunction', 'java.util.List', 'static foam.mlang.MLang.*' ], implements: [ 'foam.mlang.Expressions' ], tableColumns: [ 'id', 'description', 'version', 'enabled', 'visible', 'expiry', 'daoKey' ], properties: [ { name: 'id', class: 'String' }, { name: 'icon', class: 'Image', documentation: `Path to capability icon` }, { name: 'description', class: 'String', documentation: `Description of capability` }, { name: 'notes', class: 'String', view: { class: 'foam.u2.tag.TextArea', rows: 12, cols: 120 } }, { name: 'version', class: 'String' }, { name: 'enabled', class: 'Boolean', value: true, documentation: `Capability is ignored by system when enabled is false. user will lose permissions implied by this capability and upper level capabilities will ignore this prerequisite` }, { name: 'visible', class: 'Boolean', documentation: `Hide sub-capabilities which aren't top-level and individually selectable. when true, capability is visible to the user` }, { name: 'expiry', class: 'DateTime', documentation: `Datetime of when capability is no longer valid` }, { name: 'duration', class: 'Int', documentation: `To be used in the case where expiry is duration-based, represents the number of DAYS a junction is valid for before expiring. The UserCapabilityJunction object will have its expiry configured to a DateTime based on the lower value of the two, expiry and duration` }, { name: 'of', class: 'Class', documentation: `Model used to store information required by this credential` }, { name: 'permissionsGranted', class: 'StringArray', documentation: `List of permissions granted by this capability` }, { name: 'daoKey', class: 'String', visibility: 'RO' } ], methods: [ { name: 'implies', type: 'Boolean', args: [ { name: 'x', type: 'Context' }, { name: 'permission', type: 'String' } ], documentation: `Checks if a permission or capability string is implied by the current capability`, javaCode: ` if ( ! this.getEnabled() ) return false; // check if permission is a capability string implied by this permission if ( this.stringImplies(this.getId(), permission) ) return true; String[] permissionsGranted = this.getPermissionsGranted(); for ( String permissionName : permissionsGranted ) { if ( this.stringImplies(permissionName, permission) ) return true; } List<CapabilityCapabilityJunction> prereqs = ((ArraySink) this.getPrerequisites(x).getJunctionDAO().where(EQ(CapabilityCapabilityJunction.SOURCE_ID, (String) this.getId())).select(new ArraySink())).getArray(); DAO capabilityDAO = (DAO) x.get("capabilityDAO"); for ( CapabilityCapabilityJunction prereqJunction : prereqs ) { Capability capability = (Capability) capabilityDAO.find(prereqJunction.getTargetId()); if ( capability.implies(x, permission) ) return true; } return false; ` }, { name: 'stringImplies', type: 'Boolean', args: [ {name: 's1', type: 'String'}, {name: 's2', type: 'String'} ], documentation: `check if s1 implies s2 where s1 and s2 are permission or capability strings`, javaCode: ` if ( s1.equals(s2) ) return true; if ( s1.charAt( s1.length() - 1) != '*' || ( s1.length() - 2 > s2.length() ) ) return false; if ( s2.length() <= s1.length() - 2 ) return s1.substring( 0, s1.length() -2 ).equals( s2.substring( 0, s1.length() - 2 ) ); else return s1.substring( 0, s1.length() - 1 ).equals( s2.substring( 0, s1.length() -1 ) ); ` }, { name: 'isDeprecated', type: 'Boolean', args: [ {name: 'x', type: 'Context'} ], documentation: 'check if a given capability is deprecated', javaCode: ` Sink count = new Count(); count = this.getDeprecating(x).getJunctionDAO() .where( EQ(Capability.ID, (String) this.getId()) ).select(count); return ((Count) count).getValue() > 0; ` }, ] }); foam.RELATIONSHIP({ package: 'foam.nanos.crunch', sourceModel: 'foam.nanos.auth.User', targetModel: 'foam.nanos.crunch.Capability', cardinality: '*:*', forwardName: 'capabilities', inverseName: 'users', sourceProperty: { section: 'administrative' } }); foam.RELATIONSHIP({ sourceModel: 'foam.nanos.crunch.Capability', targetModel: 'foam.nanos.crunch.Capability', cardinality: '*:*', forwardName: 'deprecated', inverseName: 'deprecating', junctionDAOKey: 'deprecatedCapabilityJunctionDAO' }); foam.RELATIONSHIP({ sourceModel: 'foam.nanos.crunch.Capability', targetModel: 'foam.nanos.crunch.Capability', cardinality: '*:*', forwardName: 'prerequisites', inverseName: 'dependents', junctionDAOKey: 'prerequisiteCapabilityJunctionDAO' });
JavaScript
0.999999
@@ -2921,18 +2921,16 @@ false;%0A - %0A
80f37d08022ee20128cd8ed4b1c09298ecb7ebc4
Update watch-list.js
html/2.0/watch-list.js
html/2.0/watch-list.js
var WATCH_JSON_LIST = [ [110000, 28501], [772], [6060], [451], [221004], [110010], [700], [5], [175], [1211, 16904], [1918], [1919], [2777], [3333], [1], [388], [3988], [293], [1523], [802], [1150], [1165], [3800] ];
JavaScript
0.000001
@@ -37,16 +37,24 @@ 28501%5D,%0A +%5B1720%5D,%0A %5B772%5D,%0D%0A
6fe8ab075bfa2d263a5a1e29c73df37c1dbe3bf7
tweak debugging a bit
html/assets/js/cave.js
html/assets/js/cave.js
// cave // a text adventure engine, by Fox Wilson var settings = { debug: true }; var message = function(msg){$(".well").prepend(msg + "<br />");}; var d = function(m){if(settings.debug)message("<i>debug: " + m + "</i>");}; var welcome = function(game) { if(game.welcome) message(game.welcome); else { message("Welcome to " + game.title + ", by " + game.author); } }; $(document).ready(function() { message("cave initializing"); $.get("/game.json", function(data) { message("cave initialization complete, entering game"); welcome(data); }); });
JavaScript
0.000001
@@ -195,16 +195,23 @@ ssage(%22%3C +small%3E%3C i%3Edebug: @@ -224,16 +224,24 @@ + %22%3C/i%3E +%3C/small%3E %22);%7D;%0A%0A%0A @@ -444,34 +444,62 @@ -message(%22cave initializing +d(%22cave v0.0.1 starting up, loading data at /game.json %22);%0A @@ -551,60 +551,28 @@ -message(%22cave initialization complete, entering game +d(%22game data loaded. %22);%0A
b00273529d02586906dcf11d6536f927bf08a922
Update tinto-view.js
tinto-view.js
tinto-view.js
"use strict"; angular.module("Tinto", ['ngRoute']).directive("tintoView", function($route, $compile, $controller) { return { restrict: "ECA", terminal: true, priority: 400, transclude: "element", compile: function(element, attr, linker) { return function(scope, $element, attr) { var currentElement, keepPreviousView; var storedElements = {}; scope.$on("$routeChangeSuccess", update); update(); function cleanupLastView() { if (currentElement) { currentElement = null; } } function update() { if (typeof $route.current == "undefined") return; if (storedElements[$route.current.viewName] && $route.current.hideOnly) { for (attr in storedElements) { if (attr != $route.current.viewName) { storedElements[attr].removeClass("ng-show").addClass("ng-hide"); storedElements[attr].scope().$emit("leave"); } } storedElements[$route.current.viewName].removeClass("ng-hide").addClass("ng-show"); storedElements[$route.current.viewName].scope().$emit("enter"); if (currentElement && !keepPreviousView) { currentElement.remove(); } keepPreviousView = $route.current.hideOnly; return; } if (typeof storedElements[$route.current.viewName] == "undefined" && keepPreviousView) { for (attr in storedElements) { storedElements[attr].removeClass("ng-show").addClass("ng-hide"); storedElements[attr].scope().$emit("leave"); } } var locals = $route.current && $route.current.locals, template = locals && locals.$template; if (template) { var newScope = scope.$new(); linker(newScope, function(clone) { clone.html(template); $element.parent().append(clone); if (currentElement) { if (!$route.current.hideOnly) { if (!keepPreviousView) { currentElement.remove(); } } else { if (!keepPreviousView) { currentElement.remove(); } } } var link = $compile(clone.contents()), current = $route.current; cleanupLastView(); currentElement = clone; if ($route.current.hideOnly) { storedElements[$route.current.viewName] = clone; } current.scope = newScope; if (current.controller) { locals.$scope = newScope; var controller = $controller(current.controller, locals); clone.data("$ngControllerController", controller); clone.children().data("$ngControllerController", controller); } link(newScope); newScope.$emit("$viewContentLoaded"); newScope.$emit("enter"); }); } else { cleanupLastView(); } if (typeof $route.current != "undefined") { keepPreviousView = $route.current.hideOnly; } } }; } }; });
JavaScript
0
@@ -102,28 +102,73 @@ $controller +, $window, $timeout, $location, $anchorScroll ) %7B%0A - return %7B @@ -470,16 +470,388 @@ s = %7B%7D;%0A + var scrollPosCache = %7B%7D;%0A%0A scope.$on('$routeChangeStart', function() %7B%0A // store scroll position for the current view%0A if ($route.current) %7B%0A scrollPosCache%5B$route.current.loadedTemplateUrl%5D = %5B$window.pageXOffset, $window.pageYOffset%5D;%0A %7D%0A %7D);%0A%0A @@ -1986,32 +1986,32 @@ %7D%0A - @@ -2053,32 +2053,671 @@ urrent.hideOnly; +%0A%0A // if hash is specified explicitly, it trumps previously stored scroll position%0A if ($location.hash()) %7B%0A $anchorScroll();%0A // else get previous scroll position; if none, scroll to the top of the page%0A %7D else %7B%0A var prevScrollPos = scrollPosCache%5B$route.current.loadedTemplateUrl%5D %7C%7C %5B 0, 0 %5D;%0A $timeout(function() %7B%0A $window.scrollTo(prevScrollPos%5B0%5D, prevScrollPos%5B1%5D);%0A %7D, 0);%0A %7D %0A @@ -5369,8 +5369,9 @@ %7D;%0A%7D); +%0A
c468cc1a21b20f17c55fde31c89ffc16b019e5de
fix plot pane
lib/plots/pane.js
lib/plots/pane.js
'use babel' /** @jsx etch.dom */ import etch from 'etch' import PaneItem from '../util/pane-item' import { toView, Toolbar, Button, Icon, BackgroundMessage } from '../util/etch' export default class PlotPane extends PaneItem { static activate() { this.pane = PlotPane.fromId('default') atom.workspace.addOpener(uri => { if (uri.startsWith('atom://ink/plots')) { return this.pane } }); } constructor() { super() etch.initialize(this) this.element.setAttribute('tabindex', -1) } update() {} render() { let buttons = [ <div className='btn-group'> <Button icon='arrow-left' alt='Previous' disabled /> <Button icon='arrow-right' alt='Next' disabled /> </div>, <Button icon='circle-slash' alt='Forget Plot' onclick={() => this.show()} /> ]; if (this.item && this.item.toolbar) buttons.push(toView(this.item.toolbar)) return <span className='ink-plot-pane'><Toolbar items={buttons}> {toView(this.item)} </Toolbar></span> } show(view) { if (this.item && this.item.destroy) this.item.destroy() this.item = view etch.update(this) } getTitle() { return 'Plots' } getIconName() { return 'graph' } }
JavaScript
0.000001
@@ -174,16 +174,33 @@ /etch'%0A%0A +let defaultPane%0A%0A export d @@ -267,22 +267,24 @@ ) %7B%0A -this.p +defaultP ane = Pl @@ -413,14 +413,16 @@ urn -this.p +defaultP ane%0A @@ -435,17 +435,16 @@ %7D%0A %7D) -; %0A %7D%0A%0A @@ -1260,8 +1260,33 @@ '%0A %7D%0A%7D%0A +%0APlotPane.registerView()%0A
27d1a9586769cf630fc0310023b1b47b82eec754
Fix args[0] case in $http signature formatter
src/instrumentation/angular/http.js
src/instrumentation/angular/http.js
var utils = require('../utils') module.exports = function ($provide, traceBuffer) { // HTTP Instrumentation $provide.decorator('$http', ['$delegate', '$injector', function ($delegate, $injector) { return utils.instrumentModule($delegate, $injector, { type: 'ext.$http', prefix: '$http', traceBuffer: traceBuffer, signatureFormatter: function (key, args) { var text = [] if (args.length) { if (typeof args[0] === 'object') { if (!args[0].method) { args[0].method = 'get' } text = ['$http', args[0].method.toUpperCase(), args[0].url] } else { text = ['$http', args[0]] } } return text.join(' ') } }) }]) }
JavaScript
0.000306
@@ -445,16 +445,36 @@ if ( +args%5B0%5D !== null && typeof a
bc6d6a8c9c2bad90f73e90ae8c23fa837b15749a
Add @see link
src/js/SGoogleMapMarkerComponent.js
src/js/SGoogleMapMarkerComponent.js
import SGoogleMapComponentBase from 'coffeekraken-s-google-map-component-base' import __whenAttribute from 'coffeekraken-sugar/js/dom/whenAttribute' /** * @name Google Map Marker * Display a simple google map with a simple marker * @styleguide Components / Google Map * @example html * <s-google-map center="{lat: -25.363, lng: 131.044}"> * <s-google-map-marker position="{lat: -25.363, lng: 131.044}"></s-google-map-marker> * </s-google-map> * @author Olivier Bossel <[email protected]> */ export default class SGoogleMapMarkerComponent extends SGoogleMapComponentBase { /** * Default props * @definition SWebComponent.defaultProps */ static get defaultProps() { return {}; } /** * Mount dependencies * @definition SWebComponent.mountDependencies */ static get mountDependencies() { return [function() { return __whenAttribute(this.parentNode, 'inited'); }]; } /** * Physical props * @definition SWebComponent.physicalProps */ static get physicalProps() { return []; } /** * Component will mount * @definition SWebComponent.componentWillMount */ componentWillMount() { super.componentWillMount(); } /** * Mount component * @definition SWebComponent.componentMount */ componentMount() { super.componentMount(); // get the map instance to use for this marker. // this is grabed from the parent node that need to be a google-map component if ( ! this.map) { throw `The "${this._componentNameDash}" component has to be a direct child of a "SGoogleMapComponent"`; } // add the marker to the map // load the map api if ( ! this._marker) { this._initMarker(); } else { this._marker.setMap(this.map); } } /** * Component unmount * @definition SWebComponent.componentUnmount */ componentUnmount() { super.componentUnmount(); } /** * Component will receive props * @definition SWebComponent.componentWillReceiveProps */ componentWillReceiveProps(nextProps, previousProps) { if ( ! this._marker) return; this._marker.setOptions(nextProps); } /** * Render the component * Here goes the code that reflect the this.props state on the actual html element * @definition SWebComponent.render */ render() { super.render(); } /** * Init the marker */ _initMarker() { this._marker = new this._google.maps.Marker(this.props); this._marker.setMap(this.map); } /** * Access the google map instance * @return {Map} The google map instance */ get map() { return this.parentNode.map; } } // // STemplate integration // sTemplateIntegrator.registerComponentIntegration(SGoogleMapMarkerComponent, (component) => { // if (component._mapElm) { // sTemplateIntegrator.ignore(component._mapElm); // } // if (component._placeholder) { // sTemplateIntegrator.ignore(component._placeholder); // } // });
JavaScript
0
@@ -452,16 +452,89 @@ le-map%3E%0A + * @see %09%09%09https://github.com/Coffeekraken/s-google-map-marker-component%0A * @auth
0629f719f972dedc7bbb905ff3e5aa899bd69b88
Include the formId with file uploads
src/js/common/schemaform/actions.js
src/js/common/schemaform/actions.js
import Raven from 'raven-js'; import _ from 'lodash/fp'; import { transformForSubmit } from './helpers'; import environment from '../helpers/environment.js'; export const SET_EDIT_MODE = 'SET_EDIT_MODE'; export const SET_DATA = 'SET_DATA'; export const SET_PRIVACY_AGREEMENT = 'SET_PRIVACY_AGREEMENT'; export const SET_SUBMISSION = 'SET_SUBMISSION'; export const SET_SUBMITTED = 'SET_SUBMITTED'; export function setData(data) { return { type: SET_DATA, data }; } export function setEditMode(page, edit, index = null) { return { type: SET_EDIT_MODE, edit, page, index }; } export function setSubmission(field, value) { return { type: SET_SUBMISSION, field, value }; } export function setPrivacyAgreement(privacyAgreementAccepted) { return { type: SET_PRIVACY_AGREEMENT, privacyAgreementAccepted }; } export function setSubmitted(response) { return { type: SET_SUBMITTED, response: typeof response.data !== 'undefined' ? response.data : response }; } export function submitForm(formConfig, form) { const body = formConfig.transformForSubmit ? formConfig.transformForSubmit(formConfig, form) : transformForSubmit(formConfig, form); return dispatch => { dispatch(setSubmission('status', 'submitPending')); window.dataLayer.push({ event: `${formConfig.trackingPrefix}-submission`, }); const fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-Key-Inflection': 'camel' }, body }; const userToken = sessionStorage.userToken; if (userToken) { fetchOptions.headers.Authorization = `Token token=${userToken}`; } return fetch(`${environment.API_URL}${formConfig.submitUrl}`, fetchOptions) .then(res => { if (res.ok) { window.dataLayer.push({ event: `${formConfig.trackingPrefix}-submission-successful`, }); return res.json(); } return Promise.reject(new Error(`vets_server_error: ${res.statusText}`)); }) .then(resp => dispatch(setSubmitted(resp))) .catch(error => { // overly cautious const errorMessage = _.get('message', error); const clientError = errorMessage && !errorMessage.startsWith('vets_server_error'); Raven.captureException(error, { extra: { clientError } }); window.dataLayer.push({ event: `${formConfig.trackingPrefix}-submission-failed${clientError ? '-client' : ''}`, }); dispatch(setSubmission('status', clientError ? 'clientError' : 'error')); }); }; } export function uploadFile(file, filePath, uiOptions = {}) { return (dispatch, getState) => { if (file.size > uiOptions.maxSize) { dispatch( setData(_.set(filePath, { errorMessage: 'File is too large to be uploaded' }, getState().form.data)) ); return Promise.reject(); } dispatch( setData(_.set(filePath, { uploading: true }, getState().form.data)) ); const payload = new FormData(); payload.append('file', file); return fetch(`${environment.API_URL}${uiOptions.endpoint}`, { method: 'POST', headers: { 'X-Key-Inflection': 'camel' }, body: payload }).then(resp => { if (resp.ok) { return resp.json(); } return Promise.reject(new Error(`vets_upload_error: ${resp.statusText}`)); }).then(fileInfo => { dispatch( setData(_.set(filePath, { name: fileInfo.data.attributes.name, size: fileInfo.data.attributes.size, confirmationCode: fileInfo.data.attributes.confirmationCode }, getState().form.data)) ); }).catch(error => { dispatch( setData(_.set(filePath, { errorMessage: error.message.replace('vets_upload_error: ', '') }, getState().form.data)) ); Raven.captureException(error); }); }; }
JavaScript
0
@@ -3121,16 +3121,71 @@ , file); +%0A payload.append('form_id', getState().form.formId); %0A%0A re
260a796ff24130dbfa003482e2d5f0e490eee5d8
simplify sleep
src/Util.js
src/Util.js
const crypto = require('crypto') /** * @module Util */ module.exports = { /** * Performs string formatting for things like custom nicknames. * * @param {string} formatString The string to format (contains replacement strings) * @param {object} data The data to replace the string replacements with * @param {GuildMember} member The guild member this string is being formatted for * @returns {string} The processed string */ formatDataString (formatString, data, member) { let replacements = { '%USERNAME%': data.robloxUsername, '%USERID%': data.robloxId, '%DISCORDNAME%': data.discordName || '', '%DISCORDID%': data.discordId || '' } if (member != null) { replacements['%DISCORDNAME%'] = member.user.username replacements['%DISCORDID%'] = member.id replacements['%SERVER%'] = member.guild.name } return formatString.replace(/%\w+%/g, (all) => { return replacements[all] || all }) }, /** * Returns a promise that resolves after the given time in milliseconds. * @param {int} sleepTime The amount of time until the promise resolves * @returns Promise */ async sleep (sleepTime) { return new Promise(resolve => { setTimeout(() => { resolve() }, sleepTime) }) }, /** * Takes an array of numbers and simplifies it into a string containing ranges, e.g.: * [0, 1, 2, 4, 6, 7, 8] --> "0-2, 4, 6-8" * @param {array} numbers The input numbers * @returns {string} The output string */ simplifyNumbers (numbers) { let output = [] let rangeStart for (let i = 0; i < numbers.length; i++) { let number = numbers[i] let next = numbers[i + 1] if (rangeStart != null && (next - number !== 1 || next == null)) { output.push(`${rangeStart}-${number}`) rangeStart = null } else if (next == null || next - number !== 1) { output.push(`${number}`) } else if (rangeStart == null) { rangeStart = number } } return output.join(', ') }, md5 (string) { return crypto.createHash('md5').update(string).digest('hex') } }
JavaScript
0.000858
@@ -1249,41 +1249,15 @@ out( -() =%3E %7B%0A resolve()%0A %7D +resolve , sl
d27b77ad1c0b0fc6060e5e8dc6a901a6fe187f3c
Add an instance of createIndex
src/main.js
src/main.js
window.onload = () => { var instance = new Index(); var filePath = document.getElementById('filePath'); var createIndexButton = document.getElementById('createIndexButton'); var terms = document.getElementById('terms'); var searchButton = document.getElementById('searchButton'); var display = document.getElementById('display'); createIndexButton.addEventListener('click', function(e) { instance.createIndex(filePath.files[0]); }); searchButton.addEventListener('click', function(e) { instance.searchIndex(terms.value); }); }
JavaScript
0.000008
@@ -410,32 +410,49 @@ ion(e) %7B%0A + var indexArray = instance.create @@ -482,24 +482,25 @@ );%0A %7D);%0A%0A +%0A searchBu
04918a8e9010fec51ef9429d5213e4a0dd2399fe
Remove debug log
src/main.js
src/main.js
'use strict'; const fs = require('fs'); const pathToken = process.env.SLACK_AVALON_BOT_TOKEN; let token; try { token = pathToken || fs.readFileSync('token.txt', 'utf8').trim(); } catch (error) { console.log("Your API token should be placed in a 'token.txt' file, which is missing."); return; } const express = require('express'); const app = express(); const bodyParser = require('body-parser'); const Bot = require('./bot'); const bot = new Bot(token); bot.login(); app.set('view engine', 'pug'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(express.static('public')); app.get('/', (req, res) => { if (!bot.isLoggedOn()) { res.render('error', { error: 'Avalon Bot is initializing. Reload in a bit...' }); return; } else if (bot.channels.length == 0) { res.render('error', { error: 'Avalon Bot is in no valid slack channel' }); return; } let users = bot.getPotentialPlayers(); res.render('index', { users: users }); }); app.post('/start', (req, res) => { if (req.body.players instanceof Array) { bot.gameConfig.specialRoles = req.body.roles instanceof Array ? req.body.roles : []; bot.startGame(req.body.players).subscribe(res.end('success'), res.end('failure')); } }); app.post('/approve', (req, res) => { let dm; if (bot.game && req.body.user_id && (dm = bot.game.playerDms[req.body.user_id])) { bot.slack.emit('message', { user: req.body.user_id, text: 'approve', type: 'message', channel: dm.id }); } res.end(); }); app.post('/reject', (req, res) => { let dm; if (bot.game && req.body.user_id && (dm = bot.game.playerDms[req.body.user_id])) { bot.slack.emit('message', { user: req.body.user_id, text: 'reject', type: 'message', channel: dm.id }); } res.end(); }); app.post('/succeed', (req, res) => { let dm; if (bot.game && req.body.user_id && (dm = bot.game.playerDms[req.body.user_id])) { console.log(req.body) bot.slack.emit('message', { user: req.body.user_id, text: 'succeed', type: 'message', channel: dm.id }); } res.end(); }); app.post('/fail', (req, res) => { let dm; if (bot.game && req.body.user_id && (dm = bot.game.playerDms[req.body.user_id])) { bot.slack.emit('message', { user: req.body.user_id, text: 'fail', type: 'message', channel: dm.id }); } res.end(); }); app.listen(process.env.PORT || 5000);
JavaScript
0.000002
@@ -1917,34 +1917,8 @@ ) %7B%0A - console.log(req.body)%0A
feb3f37bf41ffef3b31d9339df9d3acbebd7ef4d
Update systemjs.config.js
chapter7/auction/systemjs.config.js
chapter7/auction/systemjs.config.js
System.config({ transpiler: 'typescript', typescriptOptions: { emitDecoratorMetadata: true, module: 'system', target: "ES5" }, map: { '@angular': 'node_modules/@angular' }, paths: { 'node_modules/@angular/*': 'node_modules/@angular/*/bundles' }, meta: { '@angular/*': {'format': 'cjs'} }, packages: { 'app' : {main: 'main', defaultExtension: 'ts'}, '@angular/common' : {main: 'common.umd.min.js'}, '@angular/compiler' : {main: 'compiler.umd.min.js'}, '@angular/core' : {main: 'core.umd.min.js'}, '@angular/forms' : {main: 'forms.umd.min.js'}, '@angular/platform-browser' : {main: 'platform-browser.umd.min.js'}, '@angular/platform-browser-dynamic': {main: 'platform-browser-dynamic.umd.min.js'}, '@angular/router' : {main: 'router.umd.min.js'} } });
JavaScript
0.000002
@@ -117,27 +117,8 @@ tem' -,%0A target: %22ES5%22 %0A %7D
ff49506638e207fa99cda9ec18ff9f09612b11c9
fix window state saving on windows
src/main.js
src/main.js
var app = require('app'); var BrowserWindow = require('browser-window'); var appMenu = require('./ui/menus/app-menu.js'); var Logger = require('./utils/logger.js'); var Settings = require('./utils/settings.js'); // get this working later? requires submit URL // require('crash-reporter').start(); var mainWindow = null; var title = app.getName() + ' [v' + app.getVersion() + ']'; app.on('window-all-closed', function() { if(process.platform !== 'darwin') { app.quit(); } }); app.on('before-quit', function() { if (!mainWindow.isFullScreen()) { Settings.set('lastWindowState', mainWindow.getBounds(), function(err) { if(err) { Logger.error('Failed to save lastWindowState.'); Logger.error(err); } }); } }); app.on('ready', function() { Settings.get('lastWindowState', function(err, data) { var lastWindowsState = err && {width: 800, height: 600} || data; mainWindow = new BrowserWindow({ x: lastWindowsState.x, y: lastWindowsState.y, width: lastWindowsState.width, height: lastWindowsState.height, minWidth: 400, minHeight: 300, autoHideMenuBar: true }); mainWindow.loadURL('file://' + __dirname + '/../../static/index.html'); mainWindow.on('closed', function() { mainWindow = null; }); mainWindow.webContents.on('did-finish-load', function() { mainWindow.setTitle(title); }); mainWindow.on('focus', function() { mainWindow.flashFrame(false); }); // register main app menu appMenu.register(); }); });
JavaScript
0
@@ -485,280 +485,8 @@ );%0A%0A -app.on('before-quit', function() %7B%0A if (!mainWindow.isFullScreen()) %7B%0A Settings.set('lastWindowState', mainWindow.getBounds(), function(err) %7B%0A if(err) %7B%0A Logger.error('Failed to save lastWindowState.');%0A Logger.error(err);%0A %7D%0A %7D);%0A %7D%0A%7D);%0A%0A app. @@ -1225,24 +1225,371 @@ );%0A %7D);%0A%0A + function preserveWindowState() %7B%0A Settings.set('lastWindowState', mainWindow.getBounds(), function(err) %7B%0A if(err) %7B%0A Logger.error('Failed to save lastWindowState.');%0A Logger.error(err);%0A %7D%0A %7D);%0A %7D%0A%0A mainWindow.on('move', preserveWindowState);%0A mainWindow.on('resize', preserveWindowState);%0A%0A // regis
abdcd068fc262eb4a0ba1520c820063e144016ff
Fix - initial rendering was throwing exception
src/main.js
src/main.js
import {Events, Styler, UICorePlugin, template} from 'Clappr' import pluginHtml from './public/level-selector.html' import pluginStyle from './public/style.scss' const AUTO = -1 export default class LevelSelector extends UICorePlugin { static get version() { return VERSION } get name() { return 'level_selector' } get template() { return template(pluginHtml) } get attributes() { return { 'class': this.name, 'data-level-selector': '' } } get events() { return { 'click [data-level-selector-select]': 'onLevelSelect', 'click [data-level-selector-button]': 'onShowLevelSelectMenu' } } bindEvents() { this.listenTo(this.core, Events.CORE_READY, this.bindPlaybackEvents) this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED, this.reload) this.listenTo(this.core.mediaControl, Events.MEDIACONTROL_RENDERED, this.render) } unBindEvents() { this.stopListening(this.core, Events.CORE_READY) this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_CONTAINERCHANGED) this.stopListening(this.core.mediaControl, Events.MEDIACONTROL_RENDERED) this.stopListening(this.core.getCurrentPlayback(), Events.PLAYBACK_LEVELS_AVAILABLE) this.stopListening(this.core.getCurrentPlayback(), Events.PLAYBACK_LEVEL_SWITCH_START) this.stopListening(this.core.getCurrentPlayback(), Events.PLAYBACK_LEVEL_SWITCH_END) } bindPlaybackEvents() { var currentPlayback = this.core.getCurrentPlayback() this.listenTo(currentPlayback, Events.PLAYBACK_LEVELS_AVAILABLE, this.fillLevels) this.listenTo(currentPlayback, Events.PLAYBACK_LEVEL_SWITCH_START, this.startLevelSwitch) this.listenTo(currentPlayback, Events.PLAYBACK_LEVEL_SWITCH_END, this.stopLevelSwitch) var playbackLevelsAvaialbeWasTriggered = currentPlayback.levels && currentPlayback.levels.length > 0 playbackLevelsAvaialbeWasTriggered && this.fillLevels(currentPlayback.levels) } reload() { this.unBindEvents() this.bindEvents() } shouldRender() { if (!this.core.getCurrentContainer()) return false var currentPlayback = this.core.getCurrentPlayback() if (!currentPlayback) return false var respondsToCurrentLevel = currentPlayback.currentLevel !== undefined var hasLevels = !!(currentPlayback.levels && currentPlayback.levels.length > 0) return respondsToCurrentLevel && hasLevels } render() { if (this.shouldRender()) { var style = Styler.getStyleFor(pluginStyle, {baseUrl: this.core.options.baseUrl}) this.$el.html(this.template({'levels':this.levels, 'title': this.getTitle()})) this.$el.append(style) this.core.mediaControl.$('.media-control-right-panel').append(this.el) this.updateText(this.selectedLevelId) } return this } fillLevels(levels, initialLevel = AUTO) { this.selectedLevelId = initialLevel this.levels = levels this.configureLevelsLabels() this.render() } configureLevelsLabels() { if (this.core.options.levelSelectorConfig === undefined) return for (var levelId in (this.core.options.levelSelectorConfig.labels || {})) { levelId = parseInt(levelId, 10) var thereIsLevel = !!this.findLevelBy(levelId) thereIsLevel && this.changeLevelLabelBy(levelId, this.core.options.levelSelectorConfig.labels[levelId]) } } findLevelBy(id) { var foundLevel this.levels.forEach((level) => { if (level.id === id) {foundLevel = level} }) return foundLevel } changeLevelLabelBy(id, newLabel) { this.levels.forEach((level, index) => { if (level.id === id) { this.levels[index].label = newLabel } }) } onLevelSelect(event) { this.selectedLevelId = parseInt(event.target.dataset.levelSelectorSelect, 10) this.core.getCurrentPlayback().currentLevel = this.selectedLevelId this.toggleContextMenu() this.updateText(this.selectedLevelId) event.stopPropagation() return false } onShowLevelSelectMenu(event) { this.toggleContextMenu() } toggleContextMenu() { this.$('.level_selector ul').toggle() } buttonElement() { return this.$('.level_selector button') } getTitle() { return (this.core.options.levelSelectorConfig || {}).title } startLevelSwitch() { this.buttonElement().addClass('changing') } stopLevelSwitch() { this.buttonElement().removeClass('changing') this.updateText(this.selectedLevelId) } updateText(level) { if (level === AUTO) { var playbackLevel = this.core.getCurrentPlayback().currentLevel; this.buttonElement().text('AUTO (' + this.findLevelBy(playbackLevel).label + ')') } else { this.buttonElement().text(this.findLevelBy(level).label) } } }
JavaScript
0
@@ -2318,49 +2318,27 @@ !!( -currentPlayback.levels && currentPlayback +this.levels && this .lev @@ -4581,16 +4581,52 @@ ().text( +(playbackLevel === AUTO) ? 'AUTO' : 'AUTO ('
0a9d8817f48f9036831f71eb8aeb31490e19ec30
fix typo
src/maze.js
src/maze.js
var Maze = function(scene, textureLoader) { this.imgServer = 'https://raw.githubusercontent.com/marekpagel/Music-Maze/master/img'; this.scene = scene; this.textureLoader = textureLoader; this.width = 20; this.len = 100; this.wallColor = [0x555555, 0x333333]; this.ceilingColor = 0x111111; this.ceilingTexture = textureLoader.load(this.imgServer + "ceiling.jpg", function(texture) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(2, 10); texture.needsUpdate = true; }); this.wallTexture = textureLoader.load(this.imgServer + "wall.jpg", function(texture) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.needsUpdate = true; }); this.floorTexture = textureLoader.load(this.imgServer + "floor.jpg", function(texture) { texture.wrapS = THREE.RepeatWrapping; texture.wrapT = THREE.RepeatWrapping; texture.repeat.set(1, 4); texture.needsUpdate = true; }) return { /** * Draw next iteration of the maze at a given position * prob is an array that decides probabilities of left, right and straight connectors (can have all 3, at least 1) * * returns array of open connector points */ next: function(position, rotation, prob) { var halfPi = Math.PI / 2; var mesh = new THREE.Mesh(); var connectors = []; var leftRnd = Math.random(); //leftRnd = 1; if (leftRnd < prob[0]) { // Todo: place the connector at a random spot in [20,80] range var leftWall1 = this._createWall(self.wallColor[0], self.len/5, self.width); leftWall1.position.set(-10, 0, 4*self.len/5); leftWall1.rotation.set(0, halfPi, 0); leftWall1.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(leftWall1); var leftWall2 = this._createWall(self.wallColor[0], 3*self.len/5, self.width); leftWall2.position.set(-10, 0, self.len/5); leftWall2.rotation.set(0, halfPi, 0); leftWall2.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(leftWall2); //connectors.push([position[0]-self.len,position[1],position[2]+3*self.len/5]); connectors.push([]); } else { var leftWall = this._createWall(self.wallColor[0], self.len, self.width); leftWall.position.set(-10, 0, 40); leftWall.rotation.set(0, halfPi, 0); leftWall.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(leftWall); } var rightRnd = Math.random(); //rightRnd = 1; if (rightRnd < prob[1]) { // Todo: place the connector at a random spot in [20,80] range var rightWall1 = this._createWall(self.wallColor[1], 1*self.len/5, self.width); rightWall1.position.set(10, 0, 4*self.len/5); rightWall1.rotation.set(0, -halfPi, 0); rightWall1.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(rightWall1); var rightWall2 = this._createWall(self.wallColor[1], 3*self.len/5, self.width); rightWall2.position.set(10, 0, 1*self.len/5); rightWall2.rotation.set(0, -halfPi, 0); rightWall2.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(rightWall2); connectors.push([]); } else { var rightWall = this._createWall(self.wallColor[1], self.len, self.width); rightWall.position.set(10, 0, 40); rightWall.rotation.set(0, -halfPi, 0); rightWall.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(rightWall); } var frontRnd = Math.random(); if (frontRnd < prob[2]) { connectors.push([]); } else { var backWall = this._createWall(0x444444, self.width, self.width); backWall.position.set(0, 0, -10); backWall.material = new THREE.MeshLambertMaterial({ map: self.wallTexture }); mesh.add(backWall); } var ceiling = this._createWall(self.ceilingColor, self.width, self.len); ceiling.position.set(0, 10, 40); ceiling.rotation.set(halfPi, 0, 0); ceiling.material = new THREE.MeshLambertMaterial({ map: self.ceilingTexture }); mesh.add(ceiling); var floor = this._createWall(0x222222, self.width, self.len); floor.position.set(0, -10, 40); floor.rotation.set(-halfPi, 0, 0); floor.material = new THREE.MeshLambertMaterial({ map: self.floorTexture }); mesh.add(floor); mesh.position.set(position[0],position[1],position[2]); mesh.rotation.set(rotation[0],rotation[1],rotation[2]); scene.add(mesh); }, _createWall: function(colorCode, width, height) { var geometry = new THREE.PlaneGeometry(width, height, width, height); var material = new THREE.MeshBasicMaterial({color: colorCode}); var wall = new THREE.Mesh(geometry, material); return wall; } }; };
JavaScript
0.999991
@@ -125,16 +125,17 @@ ster/img +/ ';%0A%0A
faeda501760f77cb766ffb4287cac3f61fcad083
update to use task id as rest id
client/app/scripts/services/task.js
client/app/scripts/services/task.js
'use strict'; /** * @ngdoc service * @name clientApp.Task * @description * # Task * Factory in the clientApp. */ angular.module('clientApp') .factory('Task', function ($resource) { return $resource('http://localhost:8080/api/tasks/:id'); });
JavaScript
0.000054
@@ -241,16 +241,27 @@ sks/:id' +,%7Bid:'@id'%7D );%0A %7D);
a8a3c9ad19eebaa2ab6a346d2c1ec474993b8a20
fix default value
client/components/cards/minicard.js
client/components/cards/minicard.js
// Template.cards.events({ // 'click .member': Popup.open('cardMember') // }); BlazeComponent.extendComponent({ template() { return 'minicard'; }, formattedCurrencyCustomFieldValue(definition) { const customField = this.data() .customFieldsWD() .find(f => f._id === definition._id); const customFieldTrueValue = customField && customField.trueValue ? customField.trueValue : ''; const locale = TAPi18n.getLanguage(); return new Intl.NumberFormat(locale, { style: 'currency', currency: definition.settings.currencyCode, }).format(customFieldTrueValue); }, formattedStringtemplateCustomFieldValue(definition) { const customField = this.data() .customFieldsWD() .find(f => f._id === definition._id); const customFieldTrueValue = customField && customField.trueValue ? customField.trueValue : ''; return customFieldTrueValue // .replace(/\r\n|\n\r|\n|\r/g, '\n') // .split('\n') .filter(value => !!value.trim()) .map(value => definition.settings.stringtemplateFormat.replace(/%\{value\}/gi, value)) .join(definition.settings.stringtemplateSeparator ?? ''); }, events() { return [ { 'click .js-linked-link'() { if (this.data().isLinkedCard()) Utils.goCardId(this.data().linkedId); else if (this.data().isLinkedBoard()) Utils.goBoardId(this.data().linkedId); }, }, { 'click .js-toggle-minicard-label-text'() { if (window.localStorage.getItem('hiddenMinicardLabelText')) { window.localStorage.removeItem('hiddenMinicardLabelText'); //true } else { window.localStorage.setItem('hiddenMinicardLabelText', 'true'); //true } }, }, ]; }, }).register('minicard'); Template.minicard.helpers({ showDesktopDragHandles() { currentUser = Meteor.user(); if (currentUser) { return (currentUser.profile || {}).showDesktopDragHandles; } else if (window.localStorage.getItem('showDesktopDragHandles')) { return true; } else { return false; } }, hiddenMinicardLabelText() { currentUser = Meteor.user(); if (currentUser) { return (currentUser.profile || {}).hiddenMinicardLabelText; } else if (window.localStorage.getItem('hiddenMinicardLabelText')) { return true; } else { return false; } }, });
JavaScript
0.000003
@@ -875,26 +875,26 @@ trueValue : -'' +%5B%5D ;%0A%0A retur
646611a8ed8e40fbe7dabbe6d1e1569b469fd7ce
Fix file update in FilesContainer
client/containers/FilesContainer.js
client/containers/FilesContainer.js
import React from 'react' import {bindActionCreators} from 'redux' import {connect} from 'react-redux' import BaseLayout from 'client/components/layout/BaseLayout' import { Typography, TextField, SimpleList, SimpleSelect, Row, Col, FolderIcon, InsertDriveFileIcon } from 'ui/admin' import Util from 'client/util' import {COMMAND_QUERY} from '../constants' import PropTypes from 'prop-types' import * as NotificationAction from 'client/actions/NotificationAction' import config from 'gen/config-client' import {Query, client} from '../middleware/graphql' import FileDrop from '../components/FileDrop' import Async from '../components/Async' const CodeEditor = (props) => <Async {...props} load={import(/* webpackChunkName: "codeeditor" */ '../components/CodeEditor')}/> class FilesContainer extends React.Component { static spaces = [{value:'./',name:'Application'}, {value:config.HOSTRULES_ABSPATH,name:'Hostrules'}, {value:config.WEBROOT_ABSPATH,name:'Webroot'}, {value:'/etc/lunuc/',name:'Config (etc)'}, ] constructor(props) { super(props) this.state = { file: props.file, dir: '', searchText: '', space: props.space || './' } } formatBytes(bytes, decimals) { if (bytes == 0) return '0 Bytes'; const k = 1024, dm = decimals || 2, sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'], i = Math.floor(Math.log(bytes) / Math.log(k)); return parseFloat((bytes / Math.pow(k, i)).toFixed(dm)) + ' ' + sizes[i]; } render() { const {embedded, editOnly} = this.props const {file, dir, searchText, space} = this.state let command = 'ls -l ' + space + dir if (searchText) { command = `find ${space+dir} -size -1M -type f -name '*.*' ! -path "./node_modules/*" ! -path "./bower_components/*" -exec grep -ril "${searchText}" {} \\;` } let fileEditor = file && <Query query={COMMAND_QUERY} fetchPolicy="cache-and-network" variables={{sync: true, command: 'less -f -L ' + space+dir + '/' + file}}> {({loading, error, data}) => { if (loading) return 'Loading...' if (error) return `Error! ${error.message}` if (!data.run) return 'No data' const ext = file.slice((file.lastIndexOf('.') - 1 >>> 0) + 2) return <CodeEditor lineNumbers onChange={c => { this.fileChange(space+dir + '/' + file, c) }} type={ext || 'text' }>{data.run.response}</CodeEditor> }} </Query> let content if (editOnly) { content = fileEditor } else { content = <Row spacing={3}> <Col sm={4}> <SimpleSelect label="Select aspace" fullWidth={true} value={space} onChange={(e, v) => { this.setState({space:e.target.value}) }} items={FilesContainer.spaces} /> <TextField type="search" helperText={'Search for file content'} disabled={false} fullWidth placeholder="Search" name="searchText" onKeyPress={(e) => { if (e.key === 'Enter') { console.log(e) this.setState({searchText: e.target.value}) } }}/> <Query query={COMMAND_QUERY} fetchPolicy="cache-and-network" variables={{sync: true, command}}> {({loading, error, data}) => { if (loading) { this._loading = true return 'Loading...' } this._loading = false if (error) return `Error! ${error.message}` if (!data.run) return 'No data' const rows = data.run.response.split('\n') let listItems = [] if (searchText) { listItems = rows.reduce((a, fileRow) => { if (fileRow) { const b = fileRow.split(' ').filter(x => x) a.push({ icon: <InsertDriveFileIcon />, selected: false, primary: fileRow, onClick: () => { this.setState({file: fileRow}) } }) } return a }, []) } else { rows.shift() listItems = rows.reduce((a, fileRow) => { if (fileRow) { const b = fileRow.split(' ').filter(x => x) a.push({ icon: b[0].indexOf('d') === 0 ? <FolderIcon /> : <InsertDriveFileIcon />, selected: false, primary: b[8], onClick: () => { if (b[0].indexOf('d') === 0) { //change dir this.setState({file:null, dir: dir + '/' + b[8]}) } else { this.setState({file: b[8]}) } }, secondary: this.formatBytes(b[4])/*, actions: <DeleteIconButton onClick={this.handlePostDeleteClick.bind(this, post)}/>, disabled: ['creating', 'deleting'].indexOf(post.status) > -1*/ }) } return a }, []) if (dir.indexOf('/') >= 0) { listItems.unshift({ icon: <FolderIcon />, selected: false, primary: '..', onClick: () => { this.setState({file:null, dir: dir.substring(0, dir.lastIndexOf('/'))}) } }) } } return <SimpleList items={listItems} count={listItems.length}/> }} </Query> <FileDrop maxSize={10000000} style={{width: '15rem', height: '10rem'}} accept="*/*" uploadTo="/graphql/upload" data={{keepFileName: true, createMediaEntry: false, uploadDir:space+dir}} resizeImages={false} label="Drop file here"/> </Col> <Col sm={8}> {fileEditor} </Col> </Row> } if (embedded) { // without layout return content } else { return <BaseLayout key="baseLayout"> <Typography variant="h3" gutterBottom>Files</Typography> {content} </BaseLayout> } } handleInputChange = (e) => { const target = e.target const value = target.type === 'checkbox' ? target.checked : target.value const name = target.name this.setState({ [target.name]: value }, () => { }) } fileChange(file, content) { clearTimeout(this._fileChange) this._fileChange = setTimeout(() => { client.query({ fetchPolicy: 'no-cache', query: COMMAND_QUERY, variables: { sync: true, command: `printf %s "${Util.escapeDoubleQuotes(content.replace(/\$/g, '\\$').replace(/`/g, '\\`'))}" > "${file}"` } }).then(response => { this.props.notificationAction.addNotification({key: 'fileChange', message: `File "${file}" saved`}) }) }, 1500) } } FilesContainer.propTypes = { notificationAction: PropTypes.object.isRequired, file: PropTypes.string, space: PropTypes.string, embedded: PropTypes.bool, editOnly: PropTypes.bool } /** * Map the state to props. */ const mapStateToProps = () => { return {} } /** * Map the actions to props. */ const mapDispatchToProps = (dispatch) => ({ notificationAction: bindActionCreators(NotificationAction, dispatch) }) /** * Connect the component to * the Redux store. */ export default connect( mapStateToProps, mapDispatchToProps )(FilesContainer)
JavaScript
0
@@ -2531,17 +2531,16 @@ 0) + 2)%0A -%0A @@ -2582,16 +2582,27 @@ Numbers +controlled onChange
c1ce417ed7012cf84e7ec052355d9be6e74378ba
Remove unused code
src/util.js
src/util.js
var fs = require('fs'), util = require('util'), _ = require('lodash'), request = require('request'), vow = require('vow'), md = require('marked'), fsExtra = require('fs-extra'), logger = require('./logger'), errors = require('./errors').Util; /** * Returns array of available languages * @returns {Array} */ exports.getLanguages = function () { return ['en', 'ru']; }; /** * Recurcively removes given folder with all nested files and folders * @param {String} p - path to folder * @returns {*} */ exports.removeDir = function (p) { var def = vow.defer(); fsExtra.remove(p, function (err) { if (err) { errors.createError(errors.CODES.REMOVE_DIR, { err: err }).log(); def.reject(err); } else { def.resolve(); } }); return def.promise(); }; /** * Copy all files from source folder to target folder * @param {String} source - path to source folder * @param {String} target - path to target folder * @returns {*} */ exports.copyDir = function (source, target) { var def = vow.defer(); fsExtra.copy(source, target, function (err) { if (err) { errors.createError(errors.CODES.COPY_DIR, { err: err }).log(); def.reject(err); } else { def.resolve(); } }); return def.promise(); }; /** * Loads data from gh to file on local filesystem via https request * @param {Object} options * @returns {*} */ exports.loadFromRepoToFile = function (options) { var def = vow.defer(), repo = options.repository, file = options.file, getUrl = function (type) { return { 'public': 'https://raw.githubusercontent.com/%s/%s/%s/%s', 'private': 'https://github.yandex-team.ru/%s/%s/raw/%s/%s' }[type]; }, url = util.format(getUrl(repo.type), repo.user, repo.repo, repo.ref, repo.path); request.get(url).pipe(fs.createWriteStream(file)) .on('error', function (err) { errors.createError(errors.LOAD_FROM_URL_TO_FILE, { url: url, file: file }).log(); def.reject(err); }) .on('close', function () { logger.debug(util.format('Success loading from url %s to file %s', url, file), module); def.resolve(); }); return def.promise(); }; /** * Compile *.md files to html with marked module * @param {String} content of *.md file * @param {Object} conf - configuration object * @returns {String} html string */ exports.mdToHtml = function (content, conf) { return md(content, _.extend({ gfm: true, pedantic: false, sanitize: false }, conf)); }; /** * Return compiled date in milliseconds from date in dd-mm-yyyy format * @param {String} dateStr - staring date in dd-mm-yyy format * @return {Number} date in milliseconds */ exports.dateToMilliseconds = function (dateStr) { var re = /[^\w]+|_+/, date = new Date(), dateParse = dateStr.split(re), dateMaskFrom = 'dd-mm-yyyy'.split(re); dateMaskFrom.forEach(function (elem, indx) { switch (elem) { case 'dd': date.setDate(dateParse[indx]); break; case 'mm': date.setMonth(dateParse[indx] - 1); break; default: if (dateParse[indx].length === 2) { if (date.getFullYear() % 100 >= dateParse[indx]) { date.setFullYear('20' + dateParse[indx]); }else { date.setFullYear('19' + dateParse[indx]); } }else { date.setFullYear(dateParse[indx]); } } }); return date.valueOf(); };
JavaScript
0.000006
@@ -1,114 +1,27 @@ var -fs = require('fs'),%0A util = require('util'),%0A%0A _ = require('lodash'),%0A request = require('request +_ = require('lodash '),%0A @@ -112,43 +112,8 @@ a'), -%0A%0A logger = require('./logger'), %0A @@ -1253,1026 +1253,8 @@ %7D;%0A%0A -/**%0A * Loads data from gh to file on local filesystem via https request%0A * @param %7BObject%7D options%0A * @returns %7B*%7D%0A */%0Aexports.loadFromRepoToFile = function (options) %7B%0A var def = vow.defer(),%0A repo = options.repository,%0A file = options.file,%0A getUrl = function (type) %7B%0A return %7B%0A 'public': 'https://raw.githubusercontent.com/%25s/%25s/%25s/%25s',%0A 'private': 'https://github.yandex-team.ru/%25s/%25s/raw/%25s/%25s'%0A %7D%5Btype%5D;%0A %7D,%0A url = util.format(getUrl(repo.type), repo.user, repo.repo, repo.ref, repo.path);%0A%0A request.get(url).pipe(fs.createWriteStream(file))%0A .on('error', function (err) %7B%0A errors.createError(errors.LOAD_FROM_URL_TO_FILE, %7B url: url, file: file %7D).log();%0A def.reject(err);%0A %7D)%0A .on('close', function () %7B%0A logger.debug(util.format('Success loading from url %25s to file %25s', url, file), module);%0A def.resolve();%0A %7D);%0A return def.promise();%0A%7D;%0A%0A /**%0A
16fb48a0c418f7fe3ca2ddd250f3a3154e0382f4
Add assert() function. Add Class.className attribute to all classes
src/util.js
src/util.js
(function () { if (! window.TowTruck) { window.TowTruck = {}; } var TowTruck = window.TowTruck; var $ = window.jQuery; $.noConflict(); TowTruck.$ = $; var _ = window._; _.noConflict(); TowTruck._ = _; /* A simple class pattern, use like: var Foo = TowTruck.Class({ constructor: function (a, b) { init the class }, otherMethod: ... }); You can also give a superclass as the optional first argument. Instantiation does not require "new" */ TowTruck.Class = function (superClass, prototype) { if (prototype === undefined) { prototype = superClass; } else { var newPrototype = Object.create(superClass); for (var a in prototype) { newPrototype[a] = prototype[a]; } prototype = newPrototype; } return function () { var obj = Object.create(prototype); obj.constructor.apply(obj, arguments); return obj; }; }; /* Trim whitespace from a string */ TowTruck.trim = function trim(s) { return s.replace(/^\s+/, "").replace(/\s+$/, ""); }; /* Convert a string into something safe to use as an HTML class name */ TowTruck.safeClassName = function safeClassName(name) { return name.replace(/[^a-zA-Z0-9_\-]/g, "_") || "class"; }; /* Generates a random ID */ TowTruck.generateId = function (length) { length = length || 10; var letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUV0123456789'; var s = ''; for (var i=0; i<length; i++) { s += letters.charAt(Math.floor(Math.random() * letters.length)); } return s; }; TowTruck.mixinEvents = function (proto) { proto.on = function on(name, callback) { if (name.search(" ") != -1) { var names = name.split(/ +/g); names.forEach(function (n) { this.on(n, callback); }, this); return; } if (! this._listeners) { this._listeners = {}; } if (! this._listeners[name]) { this._listeners[name] = []; } this._listeners[name].push(callback); }; proto.off = proto.removeListener = function off(name, callback) { if (name.search(" ") != -1) { var names = name.split(/ +/g); names.forEach(function (n) { this.off(n, callback); }, this); return; } if ((! this._listeners) || ! this._listeners[name]) { return; } var l = this._listeners[name], _len = l.length; for (var i=0; i<_len; i++) { if (l[i] == callback) { l.splice(i, 1); break; } } }; proto.emit = function emit(name) { if ((! this._listeners) || ! this._listeners[name]) { return; } var args = Array.prototype.slice.call(arguments, 1); var l = this._listeners[name], _len = l.length; for (var i=0; i<_len; i++) { l[i].apply(this, args); } }; return proto; }; })();
JavaScript
0.000001
@@ -807,22 +807,33 @@ %7D%0A -return +var ClassObject = functio @@ -951,16 +951,181 @@ %0A %7D;%0A + ClassObject.prototype = prototype;%0A if (prototype.constructor.name) %7B%0A ClassObject.className = prototype.constructor.name;%0A %7D%0A return ClassObject;%0A %7D;%0A%0A @@ -1452,24 +1452,281 @@ ass%22;%0A %7D;%0A%0A + TowTruck.assert = function (cond) %7B%0A if (! cond) %7B%0A var args = %5B%22Assertion error:%22%5D.concat(Array.prototype.slice.call(arguments, 1));%0A console.error.apply(console, args);%0A throw %22Assertion error: %22 + (arguments%5B1%5D %7C%7C %22?%22);%0A %7D%0A %7D;%0A %0A /* Generat
23f84d796fcf6b56d7c1cbb9221b1c4513499db5
Fix CSL Preview pane
chrome/content/zotero/tools/cslpreview.js
chrome/content/zotero/tools/cslpreview.js
/* ***** BEGIN LICENSE BLOCK ***** Copyright © 2009 Center for History and New Media George Mason University, Fairfax, Virginia, USA http://zotero.org This file is part of Zotero. Zotero 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, either version 3 of the License, or (at your option) any later version. Zotero 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 Zotero. If not, see <http://www.gnu.org/licenses/>. ***** END LICENSE BLOCK ***** Contributed by Julian Onions */ var Zotero_CSL_Preview = new function() { this.init = init; this.refresh = refresh; this.generateBibliography = generateBibliography; function init() { var menulist = document.getElementById("locale-menu"); Zotero.Styles.populateLocaleList(menulist); menulist.value = Zotero.Prefs.get('export.lastLocale');; var iframe = document.getElementById('zotero-csl-preview-box'); iframe.contentDocument.documentElement.innerHTML = '<html><head><title></title></head><body><p>' + Zotero.getString('styles.preview.instructions') + '</p></body></html>'; } function refresh() { var iframe = document.getElementById('zotero-csl-preview-box'); var items = Zotero.getActiveZoteroPane().getSelectedItems(); if (items.length === 0) { iframe.contentDocument.documentElement.innerHTML = '<html><head><title></title></head><body><p style="color: red">' + Zotero.getString('styles.editor.warning.noItems') + '</p></body></html>'; return; } var progressWin = new Zotero.ProgressWindow(); // XXX needs its own string really! progressWin.changeHeadline(Zotero.getString("pane.items.menu.createBib.multiple")); var icon = 'chrome://zotero/skin/treeitem-attachment-file.png'; progressWin.addLines(document.title, icon); progressWin.show(); progressWin.startCloseTimer(); var f = function() { var styles = Zotero.Styles.getAll(); // XXX needs its own string really for the title! var str = '<html><head><title></title></head><body>'; for (let style of styles) { if (style.source) { continue; } Zotero.debug("Generate Bib for " + style.title); var cite = generateBibliography(style); if (cite) { str += '<h3>' + style.title + '</h3>'; str += cite; str += '<hr>'; } } str += '</body></html>'; iframe.contentDocument.documentElement.innerHTML = str; }; // Give progress window time to appear setTimeout(f, 100); } function generateBibliography(style) { var iframe = document.getElementById('zotero-csl-preview-box'); var items = Zotero.getActiveZoteroPane().getSelectedItems(); if (items.length === 0) { return ''; } var citationFormat = document.getElementById("citation-format").selectedItem.value; if (citationFormat != "all" && citationFormat != style.categories) { Zotero.debug("CSL IGNORE: citation format is " + style.categories); return ''; } var locale = document.getElementById("locale-menu").value; var styleEngine = style.getCiteProc(locale); // Generate multiple citations var citations = styleEngine.previewCitationCluster( { citationItems: items.map(item => ({ id: item.id })), properties: {} }, [], [], "html" ); // Generate bibliography var bibliography = ''; if(style.hasBibliography) { styleEngine.updateItems(items.map(item => item.id)); bibliography = Zotero.Cite.makeFormattedBibliography(styleEngine, "html"); } return '<p>' + citations + '</p>' + bibliography; } }();
JavaScript
0
@@ -2339,11 +2339,15 @@ .get -All +Visible ();%0A
2085655b3b56d5e6e091aeddebad3e742fb295ce
Implement removeAttachment spec
test/api.js
test/api.js
'use strict'; var self = this; describe('Angular-aware PouchDB public API', function() { var db; function shouldBeOK(response) { expect(response.ok).toBe(true); } function shouldNotBeCalled(rejection) { self.fail(rejection); } function shouldBeMissing(response) { expect(response.status).toBe(404); } function rawPut(cb) { function put($window) { var rawDB = new $window.PouchDB('db'); var doc = {_id: 'test'}; rawDB.put(doc, function(err, result) { if (err) { throw err; } cb(result); }); } inject(put); } beforeEach(function() { var $injector = angular.injector(['ng', 'pouchdb']); var pouchDB = $injector.get('pouchDB'); db = pouchDB('db'); }); it('should wrap destroy', function(done) { db.destroy() .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap put', function(done) { db.put({_id: '1'}) .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap post', function(done) { db.post({}) .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap get', function(done) { db.get('') .then(shouldNotBeCalled) .catch(shouldBeMissing) .finally(done); }); it('should wrap remove', function(done) { db.remove('') .then(shouldNotBeCalled) .catch(shouldBeMissing) .finally(done); }); it('should wrap bulkDocs', function(done) { var docs = [{}, {}]; function success(response) { expect(response.length).toBe(2); response.forEach(shouldBeOK); } db.bulkDocs(docs) .then(success) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap allDocs', function(done) { function success(response) { expect(response.total_rows).toBe(1); expect(response.rows[0].key).toBe('test'); } function allDocs() { db.allDocs() .then(success) .catch(shouldNotBeCalled) .finally(done); } rawPut(allDocs); }); it('should wrap putAttachment', function(done) { function putAttachment(putDocResult) { var id = putDocResult.id; var rev = putDocResult.rev; var attachment = new Blob(['test']); db.putAttachment(id, 'test', rev, attachment, 'text/plain') .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); } rawPut(putAttachment); }); it('should wrap getAttachment', function(done) { function getAttachment() { return db.getAttachment('test', 'test'); } function success(response) { expect(response.type).toBe('text/plain'); } function putAttachment(putDocResult) { var id = putDocResult.id; var rev = putDocResult.rev; var attachment = new Blob(['test']); db.putAttachment(id, 'test', rev, attachment, 'text/plain') .then(getAttachment) .then(success) .catch(shouldNotBeCalled) .finally(done); } rawPut(putAttachment); }); it('should wrap removeAttachment', function() { self.fail('Spec unimplemented'); }); it('should wrap query', function() { self.fail('Spec unimplemented'); }); it('should wrap viewCleanup', function(done) { db.viewCleanup() .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap info', function(done) { function success(response) { expect(response.db_name).toBe('db'); } db.info() .then(success) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap compact', function(done) { db.compact() .then(shouldBeOK) .catch(shouldNotBeCalled) .finally(done); }); it('should wrap revsDiff', function(done) { var diff = {test: ['1']}; function success(response) { expect(response.test.missing[0]).toBe('1'); } db.revsDiff(diff) .then(success) .catch(shouldNotBeCalled) .finally(done); }); afterEach(function(done) { function tearDown($window) { // Use raw PouchDB (and callback) as a sanity check $window.PouchDB.destroy('db', function(err, info) { if (err) { throw err; } expect(info.ok).toBe(true); done(); }); } inject(tearDown); }); });
JavaScript
0.000001
@@ -3159,32 +3159,36 @@ ', function( +done ) %7B%0A self.fail('S @@ -3179,38 +3179,483 @@ -self.fail('Spec unimplemented' +function removeAttachment(response) %7B%0A return db.removeAttachment('test', 'test', response.rev);%0A %7D%0A%0A function putAttachment(putDocResult) %7B%0A var id = putDocResult.id;%0A var rev = putDocResult.rev;%0A var attachment = new Blob(%5B'test'%5D);%0A%0A db.putAttachment(id, 'test', rev, attachment, 'text/plain')%0A .then(removeAttachment)%0A .then(shouldBeOK)%0A .catch(shouldNotBeCalled)%0A .finally(done);%0A %7D%0A%0A rawPut(putAttachment );%0A
e29e95d39ed9fa246f4f2e561b8a8dc597fe9767
Revert JSON.stringify of default value
SettingsHelper.js
SettingsHelper.js
const args = require('args-parser')(process.argv); const settings = require('./settings.json'); module.exports = function () { const fields = [ // Webapp settings { local: 'webroot', env: 'WEB_ROOT', default: '' }, { local: 'webapp_port', env: 'WEB_PORT', default: '8088' }, { local: 'accessUrl', env: 'WEB_ACCESSURL', default: '' }, { local: 'autoJoin', env: 'AUTOJOIN_ENABLED', default: 'false' }, { local: 'autoJoinServer', env: 'AUTOJOIN_SERVERURL', default: '' }, { local: 'autoJoinRoom', env: 'AUTOJOIN_ROOM', default: '' }, { local: 'autoJoinPassword', env: 'AUTOJOIN_PASSWORD', default: '' }, { local: 'authentication', env: 'AUTHENTICATION', default: JSON.stringify({ mechanism: 'none' }) }, { local: 'customServer', env: 'CUSTOM_SERVER', default: '' }, { local: 'servers', env: 'SERVERS', default: '' }, // Server settings { local: 'serverroot', env: 'SERVER_ROOT', default: '/slserver' }, { local: 'server_port', env: 'SERVER_PORT', default: '8089' } ]; // Load and export our settings in preference of Args -> ENV -> Settings file -> Default const output = {}; for (let i = 0; i < fields.length; i++) { const setting = fields[i]; // console.log('Processing setting', setting); // console.log(`Args: '${args[setting.env]}'; '${args[setting.local]}'`); // console.log(`ENV: '${process.env[setting.env]}'; '${process.env[setting.local]}'`); // console.log(`Settings: '${settings[setting.local]}'; '${setting.default}'`); output[setting.local] = args[setting.env] || args[setting.local] || process.env[setting.env] || process.env[setting.local] || settings[setting.env] || settings[setting.local] || setting.default; // Make sure these settings are properly formatted if(output[setting.local]) { // Make sure these settings are properly formatted to JSON let jsonSettings = ['authentication', 'customServer']; if(jsonSettings.includes(setting.local) && output[setting.local]) { if(typeof output[setting.local] !== "object") { console.log(`${setting.local}/${setting.env} must be a JSON object. Attempting to convert it for you.`); try { let parsed = JSON.parse(output[setting.local]); output[setting.local] = parsed; } catch(e) { console.log(`- Unable to parse '${output[setting.local]}'`); console.log(`- Please check your syntax. Reverting to default.`); } console.log(`- Done.`); } } // Make sure these settings are properly formatted to an Array // This currently is only coded to handle the servers setting which is an Array of JSON objects let arraySettings = ['servers']; if(arraySettings.includes(setting.local)) { if(!Array.isArray(output[setting.local])) { console.log(`${setting.local}/${setting.env} must be an Array of JSON objects. Attempting to convert it for you.`); let temp = output[setting.local].trim(); temp = temp.replace("[", ""); temp = temp.replace("]", ""); let tempArr = temp.split("},"); if(tempArr.length > 0) { let tempOutArr = []; tempArr.forEach(element => { try { if(!element.endsWith('}')) { element = element + '}'; } let parsed = JSON.parse(element); tempOutArr.push(parsed); } catch(e) { console.log(`- Unable to parse '${element}'`); console.log(`- Please check your syntax. Skipping...`); } }); if(tempOutArr.length == 0) { console.log(`- No elements to use. Reverting to default.`); } output[setting.local] = tempOutArr; } else { console.log(`No array elements found =(. Reverting to default.`); output[setting.local] = setting.default; } console.log(`- Done.`); } } } // Backwards compatibilty for PORT ENV setting if(setting.local == 'webapp_port' && output[setting.local] == 8088) { let port = args['PORT'] || process.env['PORT'] || settings['PORT']; if(port && port !== 8088) { console.log(`Please change 'PORT' to 'WEB_PORT'. Setting WEB_PORT to '${port}'`) output[setting.local] = port; } } // Remove trailing slashes, if they exist if ((setting.local == 'webroot' || setting.local == 'accessUrl') && output[setting.local].endsWith("/")) { console.log(`${setting.local}/${setting.env} should not end in '/'. Removing trailing slash(es) for you.`); output[setting.local] = output[setting.local].replace(/\/+$/, ""); console.log(`- Done.`); } // Add leading slash, if not provided if (setting.local == 'webroot' && output[setting.local].length > 1 && !output[setting.local].startsWith("/")) { console.log(`${setting.local}/${setting.env} should always start with '/'. Adding the leading slash for you.`); // Make sure it starts with one leading slash output[setting.local] = `/${output[setting.local]}`; console.log(`- Done.`); } // Make sure 'webroot' and 'serverroot' aren't set to '/'. Revert to default if they do. if ((setting.local == 'webroot' || setting.local == 'serverroot') && output[setting.local] == '/') { console.log(`${setting.local}/${setting.env} cannot be set to '/'. Reverting to default: '${setting.default}'`); output[setting.local] = setting.default; console.log(`- Done.`); } process.env[setting.env] = typeof output[setting.local] === 'object' ? JSON.stringify(output[setting.local]) : output[setting.local]; } //console.log('Our settings are', output) return output; };
JavaScript
0.000001
@@ -865,31 +865,16 @@ efault: -JSON.stringify( %7B%0A @@ -900,17 +900,16 @@ %0A %7D -) %0A %7D,%0A
be7e984ded391d85aaf67c16f69f810b639fe1a2
Update husickaVdovka.child.js
components/animals/husickaVdovka.child.js
components/animals/husickaVdovka.child.js
import React, { Component } from 'react'; import { Text } from 'react-native'; import styles from '../../styles/styles'; import InPageImage from '../inPageImage'; import AnimalText from '../animalText'; import AnimalTemplate from '../animalTemplate'; const IMAGES = [ require('../../images/animals/husickaVdovka/01.jpg'), require('../../images/animals/husickaVdovka/02.jpg'), require('../../images/animals/husickaVdovka/03.jpg'), ]; const THUMBNAILS = [ require('../../images/animals/husickaVdovka/01-thumb.jpg'), require('../../images/animals/husickaVdovka/02-thumb.jpg'), require('../../images/animals/husickaVdovka/03-thumb.jpg'), ]; var AnimalDetail = React.createClass({ render() { return ( <AnimalTemplate firstIndex={[0]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator}> <AnimalText> V&nbsp;naší zoo si husičky vdovky žijí společně s&nbsp;plameňáky. Mají pro sebe velké jezírko. Plameňáci jsou jejich kamarádi, podávají husičkám informace o&nbsp;všem, co se děje. Protože jsou větší a více toho vidí. </AnimalText> <AnimalText> Husička miluje plavání ve vodě, proto se zdržuje především u&nbsp;jezer, bažin či větších řek. Taková místa jsou pro ni výhodná, protože tam roste vysoká, hustá tráva, kam chodí ráda odpočívat. Často si tam udělá svoje hnízdo, které je jenom jednoduchým důlkem v&nbsp;zemi. </AnimalText> <InPageImage indexes={[1]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Děti, jestli z&nbsp;domova, od babičky nebo alespoň z&nbsp;učebnice znáte husu domácí, musíte uznat, že tahle je úplně jiná, taková menší a drobnější. Má velmi krátký ocas a moc dlouhé nohy. Dokonce nejsou ani oranžové, ale šedomodré. Také má úplně jinak zbarvené peří. Čím to je? Tím, že je to jiný druh husy, který se u&nbsp;nás běžně nevyskytuje. </AnimalText> <AnimalText> Samečka a samičku husičky vdovky od sebe nerozeznáte, protože mají úplně stejně barevné peří. Jenom jejich mláďata ho mají na hlavě méně nápadné. </AnimalText> <AnimalText> Husička vdovka je všežravá a často se potápí do jezírka, aby si ulovila svoji potravu. Její strava se skládá především z&nbsp;vodního hmyzu, vodních měkkýšů, rostlin a semen. </AnimalText> <InPageImage indexes={[2]} thumbnails={THUMBNAILS} images={IMAGES} navigator={this.props.navigator} /> <AnimalText> Když sameček a samička chtějí mláďátka, samička snese 4–13&nbsp;vajec do hnízda na zemi nebo na stromě. Pak skoro měsíc trvá, než se housata vylíhnou. V&nbsp;sezení se střídají oba rodiče, aby vejce byla neustále v&nbsp;teple. Když se jim vylíhnou malá housátka, rodiče začnou trochu pelichat – ztrácet peří. Nějaký čas proto nemohou létat, musí počkat, než jim dorostou pírka nová a krásná. </AnimalText> <AnimalText> Všimněte si, děti, že peří na hlavě husičky vypadá, jako by měla kolem hlavy uvázaný černý šátek. A když se zaposloucháte, možná také uslyšíte, že vdovka vydává nápadné hvízdavé zvuky. Díky jejímu zbarvení peří a tomuto hvízdání ji vždycky zaručeně poznáte. </AnimalText> </AnimalTemplate> ); } }); module.exports = AnimalDetail;
JavaScript
0
@@ -1856,67 +1856,106 @@ %C5%BEe -je to jin%C3%BD druh husy, kter%C3%BD se u&nbsp;n%C3%A1s b%C4%9B%C5%BEn%C4%9B nevyskytuje +to vlastn%C4%9B ani husa nen%C3%AD, jen m%C3%A1 podobn%C3%A9 jm%C3%A9no, ale k hus%C3%A1m m%C3%A1 stejn%C4%9B daleko jako t%C5%99eba ke kachn%C3%A1m .%0A
4150081cf5eb2aeac699c35ec514e4279aec396c
revert some
Tlht/tlht-algo.js
Tlht/tlht-algo.js
"use strict"; var SHA1 = require("../modules/cryptography/sha1-crypto-js"); var BitArray = require("../modules/multivalue/bitArray"); var Bytes = require("../modules/multivalue/bytes"); var Aes = require("../modules/cryptography/aes-sjcl"); var invariant = require("../modules/invariant"); var TlecAlgo = require("./../Tlec/tlec-algo"); var DecryptionFailedError = require('./decryption-failed-error'); function TlhtAlgo(random) { this._random = random; this._dhAesKey = null; this._hashStart = null; this._hashEnd = null; } TlhtAlgo.prototype.init = function (key) { invariant(this._random, "rng is not set"); this._dhAesKey = key; } TlhtAlgo.prototype.generate = function () { this._hashStart = this._random.bitArray(128); var hashEnd = this._hashStart, i; for (i = 0; i < TlecAlgo.HashCount; i += 1) { hashEnd = this._hash(hashEnd); } return hashEnd; } TlhtAlgo.prototype.isHashReady = function () { return !!this._hashStart && !!this._hashEnd; } TlhtAlgo.prototype.getHashReady = function () { return { hashStart: this._hashStart, hashEnd: this._hashEnd }; } TlhtAlgo.prototype.createMessage = function (raw) { var hx = new Bytes([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0]); return this._encrypt(hx.concat(raw)); } TlhtAlgo.prototype.processMessage = function (bytes) { var decryptedData = this._decrypt(bytes); return decryptedData.bitSlice(128, decryptedData.bitLength()); } TlhtAlgo.prototype.setHashEnd = function (hashEnd) { this._hashEnd = hashEnd; } TlhtAlgo.prototype.deserialize = function (data) { this._dhAesKey = data.dhAesKey ? Hex.deserialize(data.dhAesKey) : null; this._hashStart = data.hashStart ? Hex.deserialize(data.hashStart) : null; this._hashEnd = data.hashEnd ? Hex.deserialize(data.hashEnd) : null; } TlhtAlgo.prototype.serialize = function () { return { dhAesKey: this._dhAesKey ? this._dhAesKey.as(Hex).serialize() : null, hashStart: this._hashStart ? this._hashStart.as(Hex).serialize() : null, hashEnd: this._hashEnd ? this._hashEnd.as(Hex).serialize() : null }; } TlhtAlgo.prototype._encrypt = function (bytes) { invariant(this._dhAesKey, "channel is not configured"); var iv = this._random.bitArray(128); var aes = new Aes(this._dhAesKey); var encryptedData = aes.encryptCbc(bytes, iv); return iv.as(Bytes).concat(encryptedData); } TlhtAlgo.prototype._decrypt = function (bytes) { invariant(this._dhAesKey, "channel is not configured"); var dataBitArray = bytes.as(BitArray); var iv = dataBitArray.bitSlice(0, 128); var encryptedData = dataBitArray.bitSlice(128, dataBitArray.bitLength()); var aes = new Aes(this._dhAesKey); try { return aes.decryptCbc(encryptedData, iv); } catch (ex) { throw new DecryptionFailedError(ex); } } TlhtAlgo.prototype._hash = function (value) { return SHA1(value).as(BitArray).bitSlice(0, 128); } module.exports = TlhtAlgo;
JavaScript
0.000001
@@ -69,24 +69,73 @@ ypto-js%22);%0D%0A +var Hex = require(%22../modules/multivalue/hex%22);%0D%0A var BitArray
c686973d28d5559e13202711371a4d17701abf3a
add async callback to repeate test
server/response/tests/asynchronous.spec.js
server/response/tests/asynchronous.spec.js
/*globals describe, it*/ var request = require('superagent-bluebird-promise'); var chai = require('chai'); var _ = require('lodash'); var helper = require('../../tests/helpers'); var expect = chai.expect; describe('Asynchronous', function () { helper.serverSpecHelper(); it('should respond with 202 then 201', function (done) { request.get(helper.getUrl('/v1/route6')) .then(function(res) { expect(res.status).to.be.equal(202); expect(_.isEqual(res.body,{'c': 3})).to.be.ok; return request.get(helper.getUrl('/v1/route6')); }) .then(function(res) { expect(res.status).to.be.equal(201); expect(_.isEqual(res.body, {'d': 4})).to.be.ok; done(); }); }); it('should repeate dummy-response1.json x3 followed by a dummy-response2', function () { request.get(helper.getUrl('/v1/route8')) .then(function (res) { expect(res.status).to.equal(202); expect(_.isEqual(res.body, {'a': 1})).to.be.ok; return request.get(helper.getUrl('/v1/route8')); }).then(function (res) { expect(res.status).to.equal(202); expect(_.isEqual(res.body, {'a': 1})).to.be.ok; return request.get(helper.getUrl('/v1/route8')); }).then(function (res) { expect(res.status).to.equal(202); expect(_.isEqual(res.body, {'a': 1})).to.be.ok; return request.get(helper.getUrl('/v1/route8')); }).then(function (res) { expect(res.status).to.equal(201); expect(_.isEqual(res.body, {'b': 2})).to.be.ok; return request.get(helper.getUrl('/v1/route8')); done(); }); }); });
JavaScript
0
@@ -750,17 +750,16 @@ d repeat -e dummy-r @@ -773,16 +773,17 @@ 1.json x + 3 follow @@ -814,24 +814,28 @@ , function ( +done ) %7B%0A requ @@ -1560,65 +1560,8 @@ ok;%0A - return request.get(helper.getUrl('/v1/route8'));%0A
afcf840b08847ffd99048225cd36b55d2361763a
Update flairs
modules/flair.js
modules/flair.js
module.exports = { csgo: { type: 'author_flair_text', list: [ '/r/globaloffensive janitor', '/r/globaloffensive moderator', '/r/globaloffensive monsorator', '3dmax fan', '400k hype', '5 year subreddit veteran', 'astana dragons fan', 'astralis fan', 'baggage veteran', 'banner competition #1 winner', 'banner competition #2 first place winner', 'banner competition #2 second place winner', 'banner competition #2 third place winner', 'bloodhound', 'bravado gaming fan', 'bravo', 'cache veteran', 'cheeky moderator', 'chroma', 'clan-mystik fan', 'cloud9 fan', 'cloud9 g2a fan', 'cobblestone veteran', 'complexity fan', 'copenhagen wolves fan', 'counter logic gaming fan', 'dat team fan', 'dust 2 veteran', 'envyus fan', 'epsilon esports fan', 'esc gaming fan', 'extra life tournament caster', 'extra life tournament finalist', 'faze clan fan', 'flipsid3 tactics fan', 'flipside tactics fan', 'fnatic fan', 'fnatic fanatic', 'g2 esports fan', 'gambit gaming fan', 'gamers2 fan', 'godsent fan', 'guardian 2', 'guardian elite', 'guardian', 'hellraisers fan', 'ibuypower fan', 'inferno veteran', 'italy veteran', 'keyd stars fan', 'kinguin fan', 'ldlc fan', 'legendary chicken master', 'legendary lobster master', 'lgb esports fan', 'london consipracy fan', 'london conspiracy fan', 'luminosity gaming fan', 'militia veteran', 'mirage veteran', 'moderator', 'mousesports fan', 'myxmg fan', 'n!faculty fan', 'natus vincere fan', 'ninjas in pyjamas fan', 'nuke vetera', 'nuke veteran', 'office veteran', 'official dunkmaster', 'one bot to rule them all', 'optic gaming fan', 'overpass veteran', 'penta esports fan', 'penta sports fan', 'phoenix', 'planetkey dynamics fan', 'reason gaming fan', 'recursive fan', 'renegades fan', 'sk gaming fan', 'splyce fan', 'tactics', 'team astralis fan', 'team dignitas fan', 'team ebettle fan', 'team envyus fan', 'team immunity fan', 'team kinguin fan', 'team liquid fan', 'team solomid fan', 'team wolf fan', 'titan fan', 'train veteran', 'trial moderator', 'tsm kinguin fan', 'universal soldiers fan', 'valeria', 'verygames fan', 'vexed gaming fan', 'victory', 'virtus pro fan', 'virtus.pro fan', 'vox eminor fan', 'xapso fan', ] }, rainbow6: { type: 'author_flair_css_class', list: [ 'ash', 'ashnew', 'bandit', 'banditnew', 'blackbeard', 'blackbeardnew', 'blitz', 'blitznew', 'buck', 'bucknew', 'capitao', 'capitaonew', 'castle', 'castlenew', 'caveira', 'caveiranew', 'doc', 'docnew', 'frost', 'frostnew', 'fuze', 'fuzenew', 'glaz', 'glaznew', 'iq', 'iqnew', 'jager', 'jagernew', 'kapkan', 'kapkannew', 'mod', 'montagne', 'montagnenew', 'mute', 'mutenew', 'pulse', 'pulsenew', 'recruit', 'rook', 'rooknew', 'sledge', 'sledgenew', 'smoke', 'smokenew', 'tachanka', 'tachankanew', 'thatcher', 'thatchernew', 'thermite', 'thermitenew', 'twitch', 'twitchnew', 'valkyrie', 'valkyrienew', ] }, battlefield1: { type: 'author_flair_css_class', list: [ 'xbox', 'origin', 'psn', ] }, ark: { type: 'author_flair_css_class', list: [ 'arkstone', 'dodo-blue', 'dodo-cyan', 'dodo-default', 'dodo-lime', 'dodo-red', 'dodo-yellow', 'mushroom', 'woodsign', ] }, rimworld: { type: 'author_flair_css_class', list: [ 'fun', 'gold', 'granite', 'jade', 'limestone', 'marble', 'mod', 'plasteel', 'sandstone', 'mod2', 'silver', 'slate', 'steel', 'uranium', 'war', 'wood', ] }, elite: { type: 'author_flair_css_class', list: [ 'bot img', 'cmdr img alliance', 'cmdr img cobra', 'cmdr img empire', 'cmdr img federation', 'cmdr img sidey', 'cmdr img skull', 'cmdr img viper', 'cmdr', 'img viper cmdr', 'mostlyharmless cmdr', 'star', ] }, };
JavaScript
0
@@ -2244,32 +2244,57 @@ n pyjamas fan',%0A + 'north fan',%0A 'nuk
b7f84223b850222ef3671ee4745a8d1c52e97c0f
Remove default Router export
modules/index.js
modules/index.js
/* components */ export Router from './Router' export Link from './Link' export IndexLink from './IndexLink' /* components (configuration) */ export IndexRedirect from './IndexRedirect' export IndexRoute from './IndexRoute' export Redirect from './Redirect' export Route from './Route' /* mixins */ export History from './History' export Lifecycle from './Lifecycle' export RouteContext from './RouteContext' /* utils */ export useRoutes from './useRoutes' export { createRoutes } from './RouteUtils' export RouterContext from './RouterContext' export RoutingContext from './RoutingContext' export PropTypes from './PropTypes' export match from './match' export useRouterHistory from './useRouterHistory' export { formatPattern } from './PatternUtils' /* histories */ export browserHistory from './browserHistory' export hashHistory from './hashHistory' export createMemoryHistory from './createMemoryHistory' export default from './Router'
JavaScript
0
@@ -911,36 +911,4 @@ ry'%0A -%0Aexport default from './Router'%0A
8758e45dfe0235f9f76b6073bd94094e9d2f04fe
prueba 2
js/ausencias.js
js/ausencias.js
function ausencias(){ this.id_tipo this.nombre this.descripcion this.foto this.getTiposAusencias = function(){ alert(sessionStorage.getItem('id_notificacion')); var xhr = new XMLHttpRequest(); xhr.open('POST', path + 'app/getTiposAusencias'); xhr.setRequestHeader('Cache-Control', 'no-cache'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.send(); xhr.timeout = 10000; xhr.onprogress = function(e){ $.mobile.loading('show'); } xhr.ontimeout = function(e){ navigator.notification.alert('Se detecto un problema, intentelo nuevamente',function(){},'Atención','OK'); } xhr.onload = function(e){ $.mobile.loading('hide'); if(this.status == 200){ if(this.response && JSON.parse(this.response)){ var json = JSON.parse(this.response); var now = +(new Date); var inc = ''; for(var i = 0; i < json.length; i++ ){ inc += "<li data-icon='false'>"; inc += "<a href='#'>"; inc += "<img src='jquerymobile/img-dportes/justificacion/"+json[i].foto+'?timestamp=' + now + "'>"; inc += "<h2>"+json[i].nombre+"</h2>"; inc += "<p>"+json[i].descripcion+"</p>"; inc += "</a>"; inc += "</li>"; } $("#just-content").html(inc).listview('refresh'); } } } } }
JavaScript
0
@@ -130,49 +130,8 @@ ert( -sessionStorage.getItem('id_notificacion') );%0A%09 @@ -1047,16 +1047,146 @@ ='false' + onclick='setAusencia(%22+json%5Bi%5D.id_tipo_ausencia+%22,%22+sessionStorage.getItem('id_notificacion')+%22,%22+localStorage.getItem('id')+%22);' %3E%22;%0A @@ -1678,8 +1678,111 @@ %7D%0A%09%7D%0A%7D +%0A%0A%0Afunction setAusencia(id,notifica,usuario)%7B%0A alert(id);%0A alert(notifica);%0A alert(usuario);%0A%7D
375d66256cac855096e9865a349a0d04804ebf21
Allow react-native-macos package.json shims
packager/react-packager/src/node-haste/Package.js
packager/react-packager/src/node-haste/Package.js
'use strict'; const isAbsolutePath = require('absolute-path'); const path = require('./fastpath'); class Package { constructor({ file, fastfs, cache }) { this.path = path.resolve(file); this.root = path.dirname(this.path); this._fastfs = fastfs; this.type = 'Package'; this._cache = cache; } getMain() { return this.read().then(json => { var replacements = getReplacements(json); if (typeof replacements === 'string') { return path.join(this.root, replacements); } let main = json.main || 'index'; if (replacements && typeof replacements === 'object') { main = replacements[main] || replacements[main + '.js'] || replacements[main + '.json'] || replacements[main.replace(/(\.js|\.json)$/, '')] || main; } return path.join(this.root, main); }); } isHaste() { return this._cache.get(this.path, 'package-haste', () => this.read().then(json => !!json.name) ); } getName() { return this._cache.get(this.path, 'package-name', () => this.read().then(json => json.name) ); } invalidate() { this._cache.invalidate(this.path); } redirectRequire(name) { return this.read().then(json => { var replacements = getReplacements(json); if (!replacements || typeof replacements !== 'object') { return name; } if (name[0] !== '/') { const replacement = replacements[name]; // support exclude with "someDependency": false return replacement === false ? false : replacement || name; } if (!isAbsolutePath(name)) { throw new Error(`Expected ${name} to be absolute path`); } const relPath = './' + path.relative(this.root, name); let redirect = replacements[relPath]; // false is a valid value if (redirect == null) { redirect = replacements[relPath + '.js']; if (redirect == null) { redirect = replacements[relPath + '.json']; } } // support exclude with "./someFile": false if (redirect === false) { return false; } if (redirect) { return path.join( this.root, redirect ); } return name; }); } read() { if (!this._reading) { this._reading = this._fastfs.readFile(this.path) .then(jsonStr => JSON.parse(jsonStr)); } return this._reading; } } function getReplacements(pkg) { let rn = pkg['react-native']; let browser = pkg.browser; if (rn == null) { return browser; } if (browser == null) { return rn; } if (typeof rn === 'string') { rn = { [pkg.main]: rn }; } if (typeof browser === 'string') { browser = { [pkg.main]: browser }; } // merge with "browser" as default, // "react-native" as override return { ...browser, ...rn }; } module.exports = Package;
JavaScript
0.00066
@@ -2533,16 +2533,55 @@ (pkg) %7B%0A + let rnm = pkg%5B'react-native-macos'%5D;%0A let rn @@ -2633,22 +2633,40 @@ rowser;%0A + %0A if ( +rnm == null && rn == nu @@ -2695,23 +2695,40 @@ er;%0A %7D%0A + %0A if ( +rnm == null && browser @@ -2754,24 +2754,153 @@ rn rn;%0A %7D%0A%0A + if (rn == null && browser == null) %7B%0A return rnm;%0A %7D%0A%0A if (typeof rnm === 'string') %7B%0A rnm = %7B %5Bpkg.main%5D: rnm %7D;%0A %7D%0A%0A if (typeof @@ -3103,16 +3103,58 @@ override + 1%0A // %22react-native-macos%22 as override 2 %0A retur @@ -3174,16 +3174,24 @@ r, ...rn +, ...rnm %7D;%0A%7D%0A%0Am
0124256d39a6386d110a8748e32cf383b725eb15
fix new error handling; fixes #31
feedFetchTrimmer.js
feedFetchTrimmer.js
/* eslint-env node */ var FeedParser = require('feedparser'); // to parse feeds var request = require('requestretry'); // TODO let's abstract this so that we can switch it out (e.g., to fs.readFile ) var Feed = require('rss'); // to write feeds (but not necessary to require here because we should get a Feed object from app.js -- which seems wrong) var fs = require('fs'); var iconv = require('iconv-lite'); var zlib = require('zlib'); var sanitize = require('sanitize-filename'); var feedFetchTrimmer = function(feedUrl, callback) { 'use strict'; // thanks to example from feedparser: // done, maybeDecompress, maybeTranslate, getParams var error = {}; // Define our streams function done(err) { if (err) { error = err; console.log('feedFetchTrimmer: ' + feedUrl + ' : ' + error); callback(); // return this.emit('error', new Error('Feedparser ERROR: ' + feedUrl + ' THREW ' + err + '\n')); } // return; } function maybeDecompress(res, encoding) { var decompress; if (encoding.match(/\bdeflate\b/)) { decompress = zlib.createInflate(); } else if (encoding.match(/\bgzip\b/)) { decompress = zlib.createGunzip(); } return decompress ? res.pipe(decompress) : res; } function maybeTranslate(res, charset) { // var iconv; // Use iconv-lite if its not utf8 already. if (!iconv && charset && !/utf-*8/i.test(charset)) { try { console.log('Feedparser: ' + feedUrl + ': Converting from charset %s to utf-8', charset); res = res.pipe(iconv.decodeStream(charset)); } catch (err) { console.log('feedFetchTrimmer: ' + feedUrl + ' : ' + err); } } return res; } function getParams(str) { var params = str.split(';').reduce(function(parameters, param) { var parts = param.split('=').map(function(part) { return part.trim(); }); if (parts.length === 2) { parameters[parts[0]] = parts[1]; } return parameters; }, {}); return params; } // set up request to fetch feed var options = { url: feedUrl, headers: { 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.63 Safari/537.36', 'accept': 'text/html,application/xhtml+xml' }, timeout: 10000, //setMaxListeners: 10, maxAttempts: 10, // (default) try 5 times retryDelay: 10000, // (default) wait for 5s before trying again retryStrategy: request.RetryStrategies.HTTPOrNetworkError }; var req = request(options); var feedparser = new FeedParser(); var feedObject; // Define our handlers req.on('error', done); req.on('response', function(res) { if (res.statusCode !== 200) { return this.emit('error' + req.url, new Error('Bad status code')); } var encoding = res.headers['content-encoding'] || 'identity', charset = getParams(res.headers['content-type'] || '').charset; res = maybeDecompress(res, encoding); res = maybeTranslate(res, charset); res.pipe(feedparser); }); feedparser.on('error', done); feedparser.on('end', done); feedparser.on('meta', function() { var meta = this.meta; // **NOTE** the "meta" is always available in the context of the feedparser instance var feedOptions = { title: meta.title, description: meta.description, link: meta.link, pubDate: meta.date, feed_url: meta.xmlurl, // image: meta.image.url, copyright: meta.copyright, // feedObject.author.email = meta.author.email; // author.link: meta.author.link, author: meta.author }; feedObject = new Feed(feedOptions); }); feedparser.on('readable', function() { // console.log(feedUrl); // This is where the action is! var stream = this; var today = new Date(); var cutoff = new Date(today.getTime() - 31 * 24 * 60 * 60 * 1000); // only posts from past 30 days (ignoring leap seconds etc.) var item; while ((item = stream.read())) { var itemDate = item.pubdate || item.date; // console.log(cutoff, itemDate, cutoff < itemDate); if ((cutoff < itemDate) && !(today < itemDate)) { var itemOptions = { date: itemDate, title: item.title, url: item.link, description: null, // item.description || null author: item.author || null }; feedObject.item(itemOptions); } } }); feedparser.on('finish', function() { if (Object.keys(error).length > 0) { feedObject.items.sort(function(a, b) { //sort by date for creating pages later return b.date - a.date; }); var xml = feedObject.xml({ indent: true }); // console.log(xml); var filename = sanitize(feedUrl) + '.xml'; // console.log(filename); fs.writeFile('./feeds/' + filename, xml, {mode:0o664}, function(err) { if (err) { console.log('feedFetchTrimmer: ' + feedUrl + ' : ' + err); } callback(); // console.log('SUCCESS: "' + filename + '" was saved!'); }); } }); }; module.exports = feedFetchTrimmer;
JavaScript
0
@@ -655,18 +655,20 @@ error = -%7B%7D +null ;%0A // D @@ -4527,37 +4527,14 @@ if ( -Object.keys(error).length %3E 0 +!error ) %7B%0A
c35ea5036e03e422e56080c4ec49921b54a631f2
Remove _id from kill result
app/kills/killModel.js
app/kills/killModel.js
"use strict"; var applicationStorage = process.require("core/applicationStorage.js"); /** * Get on kill * @param tier * @param criteria * @param callback */ module.exports.findOne = function (raid, criteria, callback) { var collection = applicationStorage.mongo.collection(raid); collection.findOne(criteria, function (error, kill) { callback(error, kill); }); }; /** * Insert a kill * @param tier * @param obj * @param callback */ module.exports.insertOne = function (raid, obj, callback) { obj.region = obj.region.toLowerCase(); var collection = applicationStorage.mongo.collection(raid); collection.insertOne(obj, function (error) { callback(error); }); }; module.exports.aggregateKills = function (raid, difficulty, boss, region, realm, name, callback) { var collection = applicationStorage.mongo.collection(raid); collection.aggregate([ { $match: { region: region, guildRealm: realm, guildName: name, difficulty: difficulty, boss: boss } }, { $group: { _id: "$timestamp", count: {$sum: 1} } }, { $sort: { _id: 1 } }, ]).toArray(function (error, result) { callback(error, result); }); }; module.exports.getRoster = function (raid, region, realm, name, difficulty, boss, timestamps, callback) { var collection = applicationStorage.mongo.collection(raid); var criteria = {region: region, guildRealm: realm, guildName: name, difficulty: difficulty, boss: boss}; if (timestamps.length == 1) { criteria["timestamp"] = parseInt(timestamps,10); } else { criteria["$or"] = []; timestamps.forEach(function (timestamp) { criteria["$or"].push({timestamp: parseInt(timestamp,10)}) }); } var projection = { characterRealm: 1, characterName: 1, characterSpec: 1, characterRole: 1, characterLevel: 1, characterClass: 1, characterAverageItemLevelEquipped: 1 }; collection.find(criteria, projection).sort({characterName: 1}).toArray(function (error, players) { callback(error, players); }) };
JavaScript
0.000001
@@ -2197,24 +2197,40 @@ lEquipped: 1 +,%0A _id:-1 %0A %7D;%0A%0A
4c4ca5af80cfdea9d1927b4945b21c300beaaddd
test $log.
spec/calculator-spec.js
spec/calculator-spec.js
describe('calculator', function(){ it('should add two numbers', function(){ expect(add(1,2)).toBe(3); }); }); describe('my test', function(){ it('should return 1', function(){ expect(add(2,-1)).toBe(1); }); }); describe('JavaScript date', function(){ beforeEach(module('ngMock')); it('should display happy new year message', function(){ expect(angular).toBeTruthy(); expect(angular.mock).toBeTruthy(); expect(angular.mock.TzDate).toBeTruthy(); var date = new angular.mock.TzDate(0, '2015-01-01T00:00:00Z'); expect(date.getHours()).toBe(0); }); });
JavaScript
0.000001
@@ -24,20 +24,23 @@ function + () + %7B%0A + it('s @@ -71,26 +71,28 @@ function + () + %7B%0A expect(a @@ -79,24 +79,26 @@ () %7B%0A + + expect(add(1 @@ -98,16 +98,17 @@ t(add(1, + 2)).toBe @@ -112,16 +112,17 @@ oBe(3);%0A + %7D);%0A%7D @@ -149,26 +149,28 @@ t', function + () + %7B%0A it('sh @@ -193,20 +193,23 @@ function + () + %7B%0A + e @@ -220,16 +220,17 @@ t(add(2, + -1)).toB @@ -280,26 +280,28 @@ e', function + () + %7B%0A%0A befor @@ -381,18 +381,20 @@ function + () + %7B%0A%0A @@ -632,20 +632,718 @@ oBe(0);%0A%0A %7D);%0A%7D); +%0A%0Adescribe('$log', function () %7B%0A%0A beforeEach(module('ngMock'));%0A%0A beforeEach(inject(function (_$log_) %7B%0A this.$log = _$log_;%0A %7D));%0A%0A it('should log message', function () %7B%0A expect(this.$log).toBeTruthy();%0A this.$log.info(%22Messing from angular $log service%22);%0A expect(this.$log.info.logs.length).toBe(1);%0A %7D);%0A%0A it('should log debug message', function()%7B%0A%0A this.$log.debug(%22Messing from angular $log service%22);%0A expect(this.$log.debug.logs.length).toBe(1);%0A %7D);%0A%0A it('can be cleared', function()%7B%0A this.$log.info(%22Messing from angular $log service%22);%0A this.$log.reset();%0A this.$log.assertEmpty();%0A %7D);%0A%0A%0A%0A%7D);
3d343dbddf1dda3c91736d6832db1981ceba707f
use es8
.eslintrc.js
.eslintrc.js
module.exports = { env: { browser: true, es6: true, }, extends: ['plugin:jsx-a11y/recommended'], plugins: ['react', 'jsx-a11y'], globals: { graphql: false, }, parserOptions: { sourceType: 'module', ecmaFeatures: { experimentalObjectRestSpread: true, jsx: true, }, }, };
JavaScript
0.001336
@@ -237,24 +237,46 @@ Features: %7B%0A + ecmaVersion: 8,%0A experi
584986ce0a53fb2303376a1521b911039858f648
use User.fieldsToPublish in publications
conversation-model/server/publications.js
conversation-model/server/publications.js
/* eslint-disable import/no-unresolved */ import { Meteor } from 'meteor/meteor'; import { check, Match } from 'meteor/check'; import { User } from 'meteor/socialize:user-model'; import { publishComposite } from 'meteor/reywood:publish-composite'; import { ParticipantsCollection } from '../../participant-model/common/participant-model.js'; import { Conversation, ConversationsCollection } from '../../conversation-model/common/conversation-model.js'; let SyntheticMutator; if (ParticipantsCollection.configureRedisOplog) { SyntheticMutator = require('meteor/cultofcoders:redis-oplog').SyntheticMutator; // eslint-disable-line } const optionsArgumentCheck = { limit: Match.Optional(Number), skip: Match.Optional(Number), sort: Match.Optional(Object), }; publishComposite('socialize.conversation', function publishConversation(conversationId) { check(conversationId, String); if (this.userId) { const user = User.createEmpty(this.userId); if (user.isParticipatingIn(conversationId)) { return { find() { return ConversationsCollection.find({ _id: conversationId }, { limit: 1 }); }, children: [ { find(conversation) { return conversation.participants(); }, children: [{ find(participant) { return Meteor.users.find({ _id: participant.userId }, { fields: { username: true, status: true } }); }, }], }, { find(conversation) { return conversation.messages({ limit: 1, sort: { createdAt: -1 } }); }, }, ], }; } } return this.ready(); }); publishComposite('socialize.conversations', function publishConversations(options = { limit: 10, sort: { createdAt: -1 } }) { check(options, optionsArgumentCheck); if (!this.userId) { return this.ready(); } return { find() { return ParticipantsCollection.find({ userId: this.userId, deleted: { $exists: false } }, options); }, children: [ { find(participant) { return ConversationsCollection.find({ _id: participant.conversationId }); }, children: [ { find(conversation) { return conversation.participants(); }, children: [ { find(participant) { return Meteor.users.find({ _id: participant.userId }, { fields: { username: true } }); }, }, ], }, { find(conversation) { return conversation.messages({ limit: 1, sort: { createdAt: -1 } }); }, }, ], }, ], }; }); publishComposite('socialize.unreadConversations', function publishUnreadConversations() { if (!this.userId) { return this.ready(); } return { find() { return ParticipantsCollection.find({ userId: this.userId, deleted: { $exists: false }, read: false }); }, children: [ { find(participant) { return ConversationsCollection.find({ _id: participant.conversationId }); }, children: [ { find(conversation) { return conversation.participants(); }, children: [ { find(participant) { return Meteor.users.find({ _id: participant.userId }, { fields: { username: true } }); }, }, ], }, { find(conversation) { return conversation.messages({ limit: 1, sort: { createdAt: -1 } }); }, }, ], }, ], }; }); Meteor.publish('socialize.messagesFor', function publishMessageFor(conversationId, options = { limit: 30, sort: { createdAt: -1 } }) { check(conversationId, String); check(options, optionsArgumentCheck); if (this.userId) { const user = User.createEmpty(this.userId); const conversation = Conversation.createEmpty(conversationId); if (user.isParticipatingIn(conversationId)) { return conversation.messages(options); } } return this.ready(); }); /** * This publication when subscribed to, updates the state of the participant * to keep track of the last message read by the user and whether they are viewing * it at this current moment. When the publication stops it updates the participant * to indicate they are no longer viewing the conversation * * @param {String} conversationId The _id of the conversation the user is viewing */ Meteor.publish('socialize.viewingConversation', function viewingConversationPublication(conversationId) { check(conversationId, String); if (this.userId) { const user = User.createEmpty(this.userId); if (user.isParticipatingIn(conversationId)) { const sessionId = this._session.id; ParticipantsCollection.update({ conversationId, userId: this.userId, }, { $addToSet: { observing: sessionId }, $set: { read: true }, }); this.onStop(() => { ParticipantsCollection.update({ conversationId, userId: this.userId, }, { $pull: { observing: sessionId }, }); }); } } this.ready(); }); /** * This publication when subscribed to sets the typing state of a participant in a conversation to true. When stopped it sets it to false. * @param {String} conversationId The _id of the participant */ Meteor.publish('socialize.typing', function typingPublication(conversationId) { check(conversationId, String); if (this.userId) { const user = User.createEmpty(this.userId); if (user.isParticipatingIn(conversationId)) { const participant = ParticipantsCollection.findOne({ conversationId, userId: this.userId }, { fields: { _id: true } }); const sessionId = this._session.id; const typingModifier = { $addToSet: { typing: sessionId }, }; const notTypingModifier = { $pull: { typing: sessionId }, }; const collectionName = participant.getCollectionName(); if (SyntheticMutator) { SyntheticMutator.update(`conversations::${conversationId}::${collectionName}`, participant._id, typingModifier); this.onStop(() => { SyntheticMutator.update(`conversations::${conversationId}::${collectionName}`, participant._id, notTypingModifier); }); } else { participant.update(typingModifier); this.onStop(() => { participant.update(notTypingModifier); }); } } } this.ready(); });
JavaScript
0
@@ -1557,40 +1557,28 @@ ds: -%7B username: true, status: true %7D +User.fieldsToPublish %7D); @@ -2921,34 +2921,36 @@ fields: -%7B username: true %7D +User.fieldsToPublish %7D);%0A @@ -4231,26 +4231,28 @@ ds: -%7B username: true %7D +User.fieldsToPublish %7D);
eea46db1f75951a6f489fdcd9400112f5df449af
Move the file once it's closed
scripts/androidBeforeInstall.js
scripts/androidBeforeInstall.js
module.exports = function(ctx) { var fs = ctx.requireCordovaModule('fs'), path = ctx.requireCordovaModule('path'), os = require("os"), readline = require("readline"), deferral = ctx.requireCordovaModule('q').defer(); var platformRoot = path.join(ctx.opts.projectRoot, 'www'); var settingsFile = path.join(platformRoot, 'google-services.json'); fs.stat(settingsFile, function(err,stats) { if (err) { deferral.reject("To use this plugin on android you'll need to add a google-services.json file with the FCM project_info and place that into your www folder"); } else { fs.createReadStream(settingsFile).pipe(fs.createWriteStream('platforms/android/google-services.json')); var lineReader = readline.createInterface({ input : fs.createReadStream('platforms/android/build.gradle') }); lineReader.on("line", function(line) { fs.appendFileSync('./build.gradle', line.toString() + os.EOL); if (/.*\ dependencies \{.*/.test(line)) { fs.appendFileSync('./build.gradle', '\t\tclasspath "com.google.gms:google-services:3.0.0"' + os.EOL); fs.appendFileSync('./build.gradle', '\t\tclasspath "com.android.tools.build:gradle:1.2.3+"' + os.EOL); } }); fs.rename('./build.gradle', 'platforms/android/build.gradle', deferral.resolve); } }); return deferral.promise; };
JavaScript
0.000002
@@ -1367,27 +1367,55 @@ %7D) -;%0A%0A +.on(%22close%22, function () %7B%0A @@ -1495,16 +1495,33 @@ solve);%0A + %7D);%0A%0A
86160967e25410df300d676bd030ada974f606d5
Fix in the actor spec to handle closing.
spec/unit/actor.spec.js
spec/unit/actor.spec.js
'use strict'; describe('ProAct.Actor', function () { describe('#on', function () { it ('adds observer to the actor', function () { var actor = new ProAct.Actor(), res = []; actor.on(function (event) { res.push(event); }); actor.update(null); expect(res.length).toEqual(1); expect(res[0].target).toEqual(actor); }); }); describe('#off', function () { it ('removes observer from the actor', function () { var actor = new ProAct.Actor(), res = [], observer = function (event) { res.push(event); }; actor.on(observer); actor.off(observer); actor.update(null); expect(res.length).toBe(0); }); }); describe('#update', function () { it ('notifies only the passed types of actions', function () { var actor = new ProAct.Actor(), res = []; actor.on('one', function () { res.push('1'); }); actor.on('two', function () { res.push('2'); }); actor.on('three', function () { res.push('3'); }); actor.update(null, ['one', 'three']); expect(res.length).toBe(2); expect(res).toEqual(['1', '3']); }); it ('it notifies only for defined actions', function () { var actor = new ProAct.Actor(), res = []; actor.on('one', function () { res.push('1'); }); actor.update(null, ['one', 'two']); expect(res.length).toBe(1); expect(res).toEqual(['1']); }); }); describe('special queue support', function () { beforeEach(function () { ProAct.flow.addQueue('test'); }); it ('executes all updates in the special queue of the actor', function () { var actor1 = new ProAct.Actor(), actor2 = new ProAct.Actor('test'), res = [], up = function (val) { res.push(val.source); }; actor1.on(up); actor2.on(up); actor2.on(function () { actor1.update(3); }); ProAct.flow.run(function () { actor2.update(2); actor1.update(1); }); expect(res).toEqual([1, 2, 3]); }); }); describe('destroying', function () { it ('cleans up all the resources', function () { var actor1 = new ProAct.Actor(), actor2 = new ProAct.Actor(), res = [], listener = function (val) { res.push(val); }; actor1.makeListener = function () { return listener; }; actor1.into(actor2); expect(actor2.listeners.change[0]).toBe(listener); actor2.destroy(); expect(actor2.state).toBe(ProAct.States.destroyed); expect(actor2.listeners).toBe(undefined); expect(actor2.listener).toBe(undefined); expect(actor2.errListener).toBe(undefined); expect(actor2.closeListener).toBe(undefined); expect(actor2.parent).toBe(undefined); expect(actor2.queueName).toBe(undefined); expect(actor2.transforms).toBe(undefined); }); it ('lazily cleans listeners of destoyed actors', function () { var actor1 = new ProAct.Actor(), actor2 = new ProAct.Actor(), res = [], listener = function (val) { res.push(val); }; actor1.makeListener = function () { if (!this.listener) { this.listener = listener; } return this.listener; }; actor1.into(actor2); expect(actor2.listeners.change).toEqual([listener]); actor1.destroy(); actor2.update(); expect(actor2.listeners.change).toEqual([]); }); it ('Close event destroys the actor on it was triggered', function () { var actor = new ProAct.Actor(); actor.update(null, 'close'); expect(actor.state).toBe(ProAct.States.destroyed); }); }); });
JavaScript
0
@@ -3621,32 +3621,75 @@ l(%5B%5D);%0A %7D);%0A%0A + %7D);%0A%0A describe('closing', function () %7B%0A it ('Close e @@ -3693,23 +3693,21 @@ e event -destroy +close s the ac @@ -3857,39 +3857,36 @@ e(ProAct.States. -destroy +clos ed);%0A %7D);%0A %7D
e7c11809ac93baa0574393d386cf1536af22b89e
remove console output
public/games/controllers/games.js
public/games/controllers/games.js
'use strict'; angular.module('mean.games').controller('GamesController', ['$scope', '$stateParams', '$location', 'Global', 'Games', function ($scope, $stateParams, $location, Global, Games) { $scope.global = Global; $scope.create = function(user) { var game = new Games({ date: new Date(), player: this.player.email }); game.$save(function(response) { $location.path('games/' + response._id); }); }; $scope.find = function() { Games.query(function(games) { $scope.games = games; }); $scope.games = []; }; $scope.findOne = function() { Games.get({ gameId: $stateParams.gameId }, function(game) { $scope.game = game; }); }; $scope.players = function() { Games.opponents(function(users) { console.log(users); $scope.players = users; }); $scope.players = []; } $scope.decline = function(game) { var game = $scope.game; game.status = 3; game.$update(function() { $location.path('games/' + game._id); }); } $scope.accept = function(game) { var game = $scope.game; game.status = 1; game.$update(function() { $location.path('games/' + game._id); }); } }]);
JavaScript
0.000031
@@ -884,40 +884,8 @@ ) %7B%0A - console.log(users);%0A
9c79958d71a7ce317ac2a3432c2f9da0d9215569
fix tournament player info games numbers
ui/tournament/src/view/playerInfo.js
ui/tournament/src/view/playerInfo.js
var m = require('mithril'); var partial = require('chessground').util.partial; var util = require('./util'); var status = require('game').status; function result(win, stat) { switch (win) { case true: return '1'; case false: return '0'; default: return stat >= status.ids.mate ? '½' : '*'; } } module.exports = function(ctrl) { var data = ctrl.vm.playerInfo.data; if (!data || data.player.id !== ctrl.vm.playerInfo.id) return m('span.square-spin'); var nb = data.player.nb; var avgOp = nb.game ? Math.round(data.pairings.reduce(function(a, b) { return a + b.op.rating; }, 0) / data.pairings.length) : null; return m('div.player', { config: function(el, isUpdate) { if (!isUpdate) $('body').trigger('lichess.content_loaded'); } }, [ m('h2', [m('span.rank', data.player.rank + '. '), util.player(data.player)]), m('div.stats', m('table', [ m('tr', [m('th', 'Games played'), m('td', nb.game)]), nb.game ? [ m('tr', [m('th', 'Win rate'), m('td', util.ratio2percent(nb.win / nb.game))]), m('tr', [m('th', 'Berserk rate'), m('td', util.ratio2percent(nb.berserk / nb.game))]), m('tr', [m('th', 'Average opponent'), m('td', avgOp)]) ] : null ])), m('div.scroll-shadow-soft', m('table.pairings', data.pairings.map(function(p, i) { var res = result(p.win, p.status); return m('tr', { onclick: function() { window.open('/' + p.id + '/' + p.color, '_blank'); }, class: res === '1' ? 'win' : (res === '0' ? 'loss' : '') }, [ m('th', nb.game - i), m('td', (p.op.title ? p.op.title + ' ' : '') + p.op.name), m('td', p.op.rating), m('td', { 'class': 'is color-icon ' + p.color }), m('td', res) ]); }))) ]); };
JavaScript
0.000001
@@ -519,23 +519,68 @@ var -avgOp = nb.game +pairingsLen = data.pairings.length%0A var avgOp = pairingsLen ? M @@ -665,29 +665,24 @@ %7D, 0) / -data. pairings .length) @@ -673,23 +673,19 @@ pairings -.length +Len ) : null @@ -1635,23 +1635,46 @@ m('th', -nb.game +Math.max(nb.game, pairingsLen) - i),%0A
48f49c3430a61a6a9b27d6dbcf33e98bb33b021f
Update auth.js
routes/auth.js
routes/auth.js
var mongoose = require('mongoose'), crypto = require('crypto'); mongoose.connect('mongodb://***:****@ds061258.mongolab.com:61258/spblogjs'); mongoose.connection.on('error', function (err) { console.error('Mongoose connection error %s', err); }); var len = 128; var iterations = 12000; function pass(passwd, salt, cb) { if (arguments.length != 3) { cb = salt; crypto.randomBytes(len, function (err, salt) { if (err) return cb(err); salt = salt.toString('base64'); crypto.pbkdf2(passwd, salt, iterations, len, function (err, pwdHash) { if (err) return cb(err); cb(null, salt, pwdHash.toString('base64')); }); }); } else { crypto.pbkdf2(passwd, salt, iterations, len, function (err, pwdHash) { if (err) return cb(err); cb(null, salt, pwdHash.toString('base64')); }); } }; var UserSchema = mongoose.Schema({ email: String, password: String }, {collectin: 'users'}); var UserModel = mongoose.model('User', UserSchema); var router = { base: '/', routes: { 'get': { 'auth': 'auth', 'signin': 'signin', 'singup': 'signup', 'logout': 'logout' }, 'post': { 'signin': 'signin', 'singup': 'signup' } }, auth: function (req, res) { if (req.session.auth) res.redirect('/blogs'); else { if (req.session.err) { var email = req.session.err.email; if (email) { res.render('auth', {email: email}); delete req.session.err; return; } } res.render('auth'); } }, signin: function (req, res) { //@todo - auth signin var email = req.body.email, password = req.body.password; if (email && password) { pass(password, "dasdas34234sfsQWWASfafa341", function (err, salt, hash) { if (!err && hash) { UserModel.findOne({email: email, password: hash}, function (err, user) { if (err || user == null) { res.redirect('auth#error'); } else { req.session.regenerate(function () { req.session.user = user; res.redirect('blogs'); }); } }); } }); } else { res.redirect('auth#error'); } }, signup: function (reg, res) { //@todo - auth signup }, logout: function (reg, res) { //@todo - auth logout } }; module.exports = router;
JavaScript
0.000001
@@ -97,17 +97,16 @@ /***:*** -* @ds06125
e9aa56d8bd74d9106921a7a3c57961da0d1eb6e1
Fix bug filename : App -> app
packages/react-hot-boilerplate/scripts/index.js
packages/react-hot-boilerplate/scripts/index.js
'use strict'; var React = require('react'), App = require('./App'); React.render(<App />, document.body);
JavaScript
0.000208
@@ -59,17 +59,17 @@ uire('./ -A +a pp');%0A%0AR @@ -104,8 +104,9 @@ t.body); +%0A
08be6cf9bcb7a869808b97971f5e961cf7b7b0f4
Set extent berfore features
src/ol/VectorTile.js
src/ol/VectorTile.js
/** * @module ol/VectorTile */ import Tile from './Tile.js'; import TileState from './TileState.js'; /** * @const * @type {import("./extent.js").Extent} */ const DEFAULT_EXTENT = [0, 0, 4096, 4096]; class VectorTile extends Tile { /** * @param {import("./tilecoord.js").TileCoord} tileCoord Tile coordinate. * @param {TileState} state State. * @param {string} src Data source url. * @param {import("./format/Feature.js").default} format Feature format. * @param {import("./Tile.js").LoadFunction} tileLoadFunction Tile load function. * @param {import("./Tile.js").Options=} opt_options Tile options. */ constructor(tileCoord, state, src, format, tileLoadFunction, opt_options) { super(tileCoord, state, opt_options); /** * @type {number} */ this.consumers = 0; /** * @private * @type {import("./extent.js").Extent} */ this.extent_ = null; /** * @private * @type {import("./format/Feature.js").default} */ this.format_ = format; /** * @private * @type {Array<import("./Feature.js").default>} */ this.features_ = null; /** * @private * @type {import("./featureloader.js").FeatureLoader} */ this.loader_; /** * Data projection * @private * @type {import("./proj/Projection.js").default} */ this.projection_ = null; /** * @private * @type {import("./Tile.js").LoadFunction} */ this.tileLoadFunction_ = tileLoadFunction; /** * @private * @type {string} */ this.url_ = src; } /** * @inheritDoc */ disposeInternal() { this.setState(TileState.ABORT); super.disposeInternal(); } /** * Gets the extent of the vector tile. * @return {import("./extent.js").Extent} The extent. * @api */ getExtent() { return this.extent_ || DEFAULT_EXTENT; } /** * Get the feature format assigned for reading this tile's features. * @return {import("./format/Feature.js").default} Feature format. * @api */ getFormat() { return this.format_; } /** * Get the features for this tile. Geometries will be in the projection returned * by {@link module:ol/VectorTile~VectorTile#getProjection}. * @return {Array<import("./Feature.js").FeatureLike>} Features. * @api */ getFeatures() { return this.features_; } /** * @inheritDoc */ getKey() { return this.url_; } /** * Get the feature projection of features returned by * {@link module:ol/VectorTile~VectorTile#getFeatures}. * @return {import("./proj/Projection.js").default} Feature projection. * @api */ getProjection() { return this.projection_; } /** * @inheritDoc */ load() { if (this.state == TileState.IDLE) { this.setState(TileState.LOADING); this.tileLoadFunction_(this, this.url_); this.loader_(null, NaN, null); } } /** * Handler for successful tile load. * @param {Array<import("./Feature.js").default>} features The loaded features. * @param {import("./proj/Projection.js").default} dataProjection Data projection. * @param {import("./extent.js").Extent} extent Extent. */ onLoad(features, dataProjection, extent) { this.setProjection(dataProjection); this.setFeatures(features); this.setExtent(extent); } /** * Handler for tile load errors. */ onError() { this.setState(TileState.ERROR); } /** * Function for use in an {@link module:ol/source/VectorTile~VectorTile}'s * `tileLoadFunction`. Sets the extent of the vector tile. This is only required * for tiles in projections with `tile-pixels` as units. The extent should be * set to `[0, 0, tilePixelSize, tilePixelSize]`, where `tilePixelSize` is * calculated by multiplying the tile size with the tile pixel ratio. For * sources using {@link module:ol/format/MVT~MVT} as feature format, the * {@link module:ol/format/MVT~MVT#getLastExtent} method will return the correct * extent. The default is `[0, 0, 4096, 4096]`. * @param {import("./extent.js").Extent} extent The extent. * @api */ setExtent(extent) { this.extent_ = extent; } /** * Function for use in an {@link module:ol/source/VectorTile~VectorTile}'s `tileLoadFunction`. * Sets the features for the tile. * @param {Array<import("./Feature.js").default>} features Features. * @api */ setFeatures(features) { this.features_ = features; this.setState(TileState.LOADED); } /** * Function for use in an {@link module:ol/source/VectorTile~VectorTile}'s `tileLoadFunction`. * Sets the projection of the features that were added with * {@link module:ol/VectorTile~VectorTile#setFeatures}. * @param {import("./proj/Projection.js").default} projection Feature projection. * @api */ setProjection(projection) { this.projection_ = projection; } /** * Set the feature loader for reading this tile's features. * @param {import("./featureloader.js").FeatureLoader} loader Feature loader. * @api */ setLoader(loader) { this.loader_ = loader; } } export default VectorTile;
JavaScript
0
@@ -3320,53 +3320,53 @@ .set -Features(features);%0A this.setExtent(extent +Extent(extent);%0A this.setFeatures(features );%0A
c0bb44cf589a387be73afb627e84abe86fddb170
add audit checks, es6 styling, and code formatting to room invitations
collections/room-invitations.es6.js
collections/room-invitations.es6.js
RoomInvitations = new Meteor.Collection('room_invitations'); Meteor.methods({ 'roomInvitation': function (targetUserId, targetRoomId) { var targetUser = Meteor.users.findOne(targetUserId); var room = Rooms.findOne(targetRoomId); if (!room) { throw new Meteor.Error("Room could not be found."); } if (!targetUser) { throw new Meteor.Error("User could not be found."); } if (room.direct){ throw new Meteor.Error("Can not invite to direct message rooms."); } // currentUser has to have permission on targetRoom if (room.isPrivate && !_(room.invited).contains(Meteor.userId())) { throw new Meteor.Error("You don't have permission to invite to that room."); } if (_(room.users).contains(targetUser._id)){ throw new Meteor.Error("User in that room."); } var roomInvitation = { invitingUser: Meteor.userId(), invitedUser: targetUser._id, roomId: room._id, timestamp: new Date(), active: true }; check(roomInvitation, Schemas.roomInvitation); var existingInvitation = RoomInvitations.findOne({ invitingUser: roomInvitation.invitingUser, invitedUser: roomInvitation.invitedUser, roomId: roomInvitation.roomId, active: true // NOTE: This could be harassed, reconsider later }); if (existingInvitation) { throw new Meteor.Error("You've already invited that user to that room."); } RoomInvitations.insert(roomInvitation); Rooms.update({_id: room._id}, {$addToSet: {invited: targetUser._id}}); }, 'acceptRoomInvitation': function (roomInvitationId) { updateRoomInvitation(roomInvitationId, true); }, 'dismissRoomInvitation': function (roomInvitationId) { updateRoomInvitation(roomInvitationId,false); } }); function updateRoomInvitation(id,accepted){ var roomInvitation = RoomInvitations.findOne({_id:id}); if(!roomInvitation){ throw new Meteor.Error("Can't find room invitation."); } if(roomInvitation.invitedUser !== Meteor.userId()){ throw new Meteor.Error("Can only update your own invitations."); } RoomInvitations.update({_id: id}, { $set: { didAccept: accepted, completedTime: new Date(), active: false } }); if(accepted){ Meteor.call('joinRoom',roomInvitation.roomId); } } Schemas.roomInvitation = new SimpleSchema({ invitingUser: { type: String, label: "Inviting User", }, invitedUser: { type: String, label: "Invited User", }, roomId: { type: String, label: "Room Id", }, timestamp: { type: Date, label: "Timestamp", }, active: { type: Boolean, label: "Active" }, completedTime: { type: Date, label: "Completed Time", optional: true // deferred until completion }, didAccept: { type: Boolean, label: "Accepted or Rejected", optional: true // deferred until completion } });
JavaScript
0
@@ -76,17 +76,16 @@ s(%7B%0A -' roomInvi @@ -90,28 +90,16 @@ vitation -': function (targetU @@ -105,16 +105,83 @@ UserId, +targetRoomId) %7B%0A check(targetUserId, String);%0A check( targetRo @@ -176,35 +176,43 @@ eck(targetRoomId -) %7B +, String);%0A %0A var tar @@ -526,16 +526,17 @@ .direct) + %7B%0A @@ -905,16 +905,17 @@ er._id)) + %7B%0A @@ -1814,17 +1814,16 @@ %7D,%0A -' acceptRo @@ -1830,36 +1830,58 @@ omInvitation -': function +(roomInvitationId) %7B%0A check (roomInvitat @@ -1877,35 +1877,42 @@ roomInvitationId -) %7B +, String); %0A updateR @@ -1961,17 +1961,16 @@ %7D,%0A -' dismissR @@ -1986,20 +1986,42 @@ tion -': function +(roomInvitationId) %7B%0A check (roo @@ -2025,35 +2025,42 @@ roomInvitationId -) %7B +, String); %0A updateR @@ -2090,16 +2090,17 @@ ationId, + false);%0A @@ -2142,16 +2142,17 @@ tion(id, + accepted @@ -2148,24 +2148,25 @@ d, accepted) + %7B%0A var ro @@ -2209,16 +2209,17 @@ ne(%7B_id: + id%7D);%0A%0A @@ -2223,16 +2223,17 @@ %0A%0A if + (!roomIn @@ -2241,16 +2241,17 @@ itation) + %7B%0A @@ -2319,16 +2319,17 @@ %7D%0A if + (roomInv @@ -2368,16 +2368,17 @@ serId()) + %7B%0A @@ -2629,16 +2629,17 @@ ;%0A if + (accepte @@ -2640,16 +2640,17 @@ ccepted) + %7B%0A @@ -2674,16 +2674,17 @@ inRoom', + roomInvi
612caeaf2b19013bdc5caad1ade26663c126aab7
Set focus for error example pages
public/javascripts/application.js
public/javascripts/application.js
function ShowHideContent() { var self = this; self.escapeElementName = function(str) { result = str.replace('[', '\\[').replace(']', '\\]') return(result); }; self.showHideRadioToggledContent = function () { $(".block-label input[type='radio']").each(function () { var $radio = $(this); var $radioGroupName = $radio.attr('name'); var $radioLabel = $radio.parent('label'); var dataTarget = $radioLabel.attr('data-target'); // Add ARIA attributes // If the data-target attribute is defined if (dataTarget) { // Set aria-controls $radio.attr('aria-controls', dataTarget); $radio.on('click', function () { // Select radio buttons in the same group $radio.closest('form').find(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () { var $this = $(this); var groupDataTarget = $this.parent('label').attr('data-target'); var $groupDataTarget = $('#' + groupDataTarget); // Hide toggled content $groupDataTarget.hide(); // Set aria-expanded and aria-hidden for hidden content $this.attr('aria-expanded', 'false'); $groupDataTarget.attr('aria-hidden', 'true'); }); var $dataTarget = $('#' + dataTarget); $dataTarget.show(); // Set aria-expanded and aria-hidden for clicked radio $radio.attr('aria-expanded', 'true'); $dataTarget.attr('aria-hidden', 'false'); }); } else { // If the data-target attribute is undefined for a radio button, // hide visible data-target content for radio buttons in the same group $radio.on('click', function () { // Select radio buttons in the same group $(".block-label input[name=" + self.escapeElementName($radioGroupName) + "]").each(function () { var groupDataTarget = $(this).parent('label').attr('data-target'); var $groupDataTarget = $('#' + groupDataTarget); // Hide toggled content $groupDataTarget.hide(); // Set aria-expanded and aria-hidden for hidden content $(this).attr('aria-expanded', 'false'); $groupDataTarget.attr('aria-hidden', 'true'); }); }); } }); } self.showHideCheckboxToggledContent = function () { $(".block-label input[type='checkbox']").each(function() { var $checkbox = $(this); var $checkboxLabel = $(this).parent(); var $dataTarget = $checkboxLabel.attr('data-target'); // Add ARIA attributes // If the data-target attribute is defined if (typeof $dataTarget !== 'undefined' && $dataTarget !== false) { // Set aria-controls $checkbox.attr('aria-controls', $dataTarget); // Set aria-expanded and aria-hidden $checkbox.attr('aria-expanded', 'false'); $('#'+$dataTarget).attr('aria-hidden', 'true'); // For checkboxes revealing hidden content $checkbox.on('click', function() { var state = $(this).attr('aria-expanded') === 'false' ? true : false; // Toggle hidden content $('#'+$dataTarget).toggle(); // Update aria-expanded and aria-hidden attributes $(this).attr('aria-expanded', state); $('#'+$dataTarget).attr('aria-hidden', !state); }); } }); } } $(document).ready(function() { // Turn off jQuery animation jQuery.fx.off = true; // Use GOV.UK selection-buttons.js to set selected // and focused states for block labels var $blockLabels = $(".block-label input[type='radio'], .block-label input[type='checkbox']"); new GOVUK.SelectionButtons($blockLabels); // Details/summary polyfill // See /javascripts/vendor/details.polyfill.js // Where .block-label uses the data-target attribute // to toggle hidden content var toggleContent = new ShowHideContent(); toggleContent.showHideRadioToggledContent(); toggleContent.showHideCheckboxToggledContent(); });
JavaScript
0.000004
@@ -4115,12 +4115,545 @@ ent();%0A%0A%7D);%0A +%0A$(window).load(function() %7B%0A%0A // Only set focus for the error example pages%0A if ($(%22.js-error-example%22).length) %7B%0A%0A // If there is an error summary, set focus to the summary%0A if ($(%22.error-summary%22).length) %7B%0A $(%22.error-summary%22).focus();%0A $(%22.error-summary a%22).click(function(e) %7B%0A e.preventDefault();%0A var href = $(this).attr(%22href%22);%0A $(href).focus();%0A %7D);%0A %7D%0A // Otherwise, set focus to the field with the error%0A else %7B%0A $(%22.error input:first%22).focus();%0A %7D%0A %7D%0A%0A%7D);%0A%0A
345f2a92dcac232a584465d812e0bb27226a00df
Fix shadows temporarily
packages/game-ui/lib/player-hand.js
packages/game-ui/lib/player-hand.js
// Abstract class representing a displayable container of cards "use strict"; function PlayerHand(cardsData, noRandomize) { this.Container_constructor(); this._cardSlots = []; this._openSlotIdx = 0; this._randomize = !noRandomize; this._addCards(cardsData); } var p = createjs.extend(PlayerHand, createjs.Container); createjs.EventDispatcher.initialize(p); p._addToOpenSlot = function(dispCard) { if(!this._hasOpenSlot()) this._cardSlots.push(null); dispCard.on("rollover", this._cardMouseOver.bind(this, this._openSlotIdx)); dispCard.on("rollout", this._cardMouseOut.bind(this, this._openSlotIdx)); this._cardSlots[this._openSlotIdx++] = dispCard; this.addChild(dispCard); }; p._cardMouseOver = function(idx) { this.dispatchEvent({ type: "card-mouseover", cardIndex: idx }); }; p._cardMouseOut = function(idx) { this.dispatchEvent({ type: "card-mouseout", cardIndex: idx }); }; p._hasOpenSlot = function() { return this._openSlotIdx !== this._cardSlots.length; }; p._rearrangeCards = function(transitionTime) { if(transitionTime === undefined) transitionTime = 0; for(var i = 0; i < this._cardSlots.length; ++i) { var dispCard = this._cardSlots[i]; if(!dispCard) continue; var coords = this._getCoordsForCard(i); this._randomizeCoords(coords); createjs.Tween.get(dispCard, { override: true }) .to(coords, transitionTime, createjs.Ease.cubicOut); } }; // Randomize coords a bit more a slightly more realistic look p._randomizeCoords = function(coords) { if(this._randomize) { coords.x += (Math.random() * 9) - 4; coords.y += (Math.random() * 9) - 4; coords.rotation += (Math.random() * 5) - 2; } }; p.makeSpaceForCard = function(transitionTime) { this._cardSlots.push(null); this._rearrangeCards(transitionTime); return this._getCoordsForCard(this._cardSlots.length - 1); }; p.putCardInBlankSpace = function(qNewCard) { return qNewCard.then(function(newCard) { if(this._openSlotIdx === this._cardSlots.length) throw new Error("No open slots in car display"); if(newCard.parent) newCard.parent.removeChild(newCard); var coords = this._getCoordsForCard(this._openSlotIdx); newCard.x = coords.x; newCard.y = coords.y; newCard.rotation = coords.rotation; this._addToOpenSlot(newCard); }.bind(this)); }; p._addCards = unimplemented; function unimplemented() { throw new Error("Method not implemented"); } module.exports = createjs.promote(PlayerHand, "Container");
JavaScript
0.000001
@@ -1412,16 +1412,8 @@ ime, -%0A cre @@ -1468,20 +1468,19 @@ s a bit -m +f or -e a sligh @@ -1644,32 +1644,35 @@ () * 9) - 4;%0A + // coords.rotation @@ -1700,16 +1700,88 @@ 5) - 2;%0A + coords.rotation = 0; // TODO: turn back on when Chrome bug is fixed%0A %7D%0A%7D;%0A%0A
aec2d80beea9c86a970d9a482acec7be52af1aae
remove static route, base route defaults to doc display
server-api/configuration/routes.js
server-api/configuration/routes.js
'use strict'; var controllersPath = '../app/controllers/'; var routes = []; var _ = require('underscore'); function loginRoutes(server) { var loginController = require(controllersPath + 'login-controller')(server); _.each(loginController.routes, function (route) { server.route(route); }); } function systemRoutes(server) { var systemController = require(controllersPath + 'system-controller')(server); _.each(systemController.routes, function (route) { server.route(route); }); } var ResolveRoutes = function (server) { var cors = server.settings.connections.routes.cors; var headers = [].concat(cors.headers).concat(cors.additionalHeaders); // favicon server.route({ method: 'GET', path: '/favicon.ico', handler: { file: './favicon.ico' }, config: { cache: { expiresIn: 86400000 } } }); // spa support server.route({ method: 'GET', path: '/{param*}', handler: { directory: { path: './static' } } }); // requried for angularjs preflight calls server.route({ method: 'OPTIONS', path: '/{param*}', handler: function (request, reply) { reply() .type('text/plain') .header('Access-Control-Allow-Origin', cors.origin.join(' ')) .header('Access-Control-Allow-Headers', headers.join(', ')); } }); // loginRoutes(server); systemRoutes(server); return routes; }; module.exports = function () { var _this = exports; _this.resolveRoutes = ResolveRoutes; return _this; };
JavaScript
0
@@ -954,206 +954,8 @@ );%0A%0A - // spa support%0A server.route(%7B%0A method: 'GET',%0A path: '/%7Bparam*%7D',%0A handler: %7B%0A directory: %7B%0A path: './static'%0A %7D%0A %7D%0A %7D);%0A%0A
d9d34bf4353aef3cbdbb3932138985fd91e150e7
remove unused option from new commans
packages/gluestick/src/cli/index.js
packages/gluestick/src/cli/index.js
const commander = require('commander'); const process = require('process'); const { highlight } = require('./colorScheme'); const cliHelpers = require('./helpers'); const execWithConfig = require('./execWithConfig'); const debugServerOption = ['-D, --debug-server', 'debug server side rendering with built-in node inspector']; const debugServerPortOption = ['-p, --debug-port <n>', 'port on which to run node inspector']; const skipBuildOption = ['-P, --skip-build', 'skip build when running in production mode']; const statelessFunctionalOption = ['-F, --functional', '(generate component) stateless functional component']; const logLevelOption = ['-L, --log-level <level>', 'set the logging level', /^(error|warn|success|info|debug)$/, null]; const entrypointsOption = ['-E, --entrypoints <entrypoints>', 'Enter specific entrypoint or a group']; commander .version(cliHelpers.getVersion()); commander .command('new') .description('generate a new application') .arguments('<appName>') .option('-d, --dev <path>', 'path to dev version of gluestick') .option('--yarn', 'use yarn instead of npm') .action((...commandArguments) => { execWithConfig( require('../commands/new'), commandArguments, { useGSConfig: true, skipProjectConfig: true, skipPlugins: true }, ); }); commander .command('generate <container|component|reducer|generator>') .description('generate a new entity from given template') .arguments('<name>') .option('-E --entry-point <entryPoint>', 'entry point for generated files') .option(...statelessFunctionalOption) .option('-O, --gen-options <value>', 'options to pass to the generator') .action((...commandArguments) => { execWithConfig( require('../commands/generate'), commandArguments, { useGSConfig: true, skipProjectConfig: true, skipPlugins: true }, ); }); commander .command('destroy <container|component|reducer>') .description('destroy a generated container') .arguments('<name>') .option('-E --entry-point <entryPoint>', 'entry point for generated files') .action((...commandArguments) => { execWithConfig( require('../commands/destroy'), commandArguments, { useGSConfig: true, skipProjectConfig: true, skipPlugins: true }, ); }); commander .command('start') .alias('s') .description('start everything') .option('-T, --run-tests', 'run test hook') .option('--dev', 'disable gluestick verion check') .option('-C --coverage', 'create test coverage') .option(...entrypointsOption) .option(...logLevelOption) .option(...debugServerOption) .option(...debugServerPortOption) .option(...skipBuildOption) .action((...commandArguments) => { execWithConfig( require('../commands/start'), commandArguments, { useGSConfig: true, useWebpackConfig: false, skipPlugins: true, skipClientEntryGeneration: true, skipServerEntryGeneration: true, }, ); }); commander .command('build') .description('create production asset build') .action((...commandArguments) => { execWithConfig( require('../commands/build'), commandArguments, { useGSConfig: true, useWebpackConfig: true }, ); }); commander .command('bin') .allowUnknownOption(true) .description('access dependencies bin directory') .action((...commandArguments) => { execWithConfig( require('../commands/bin'), commandArguments, { skipProjectConfig: true, skipPlugins: true }, ); }); commander .command('dockerize') .description('create docker image') .arguments('<name>') .action((...commandArguments) => { execWithConfig( require('../commands/dockerize'), commandArguments, { useGSConfig: true, skipProjectConfig: true, skipPlugins: true }, ); }); commander .command('start-client', null, { noHelp: true }) .description('start client') .option(...logLevelOption) .option(...entrypointsOption) .action((...commandArguments) => { process.env.COMMAND = 'start-client'; execWithConfig( require('../commands/start-client'), commandArguments, { useGSConfig: true, useWebpackConfig: true, skipServerEntryGeneration: true }, ); }); commander .command('start-server', null, { noHelp: true }) .description('start server') .option(...logLevelOption) .option(...entrypointsOption) .option(...debugServerOption) .option(...debugServerPortOption) .action((...commandArguments) => { process.env.COMMAND = 'start-server'; execWithConfig( require('../commands/start-server'), commandArguments, { useGSConfig: true, useWebpackConfig: true, skipClientEntryGeneration: true }); }); commander .command('test') .allowUnknownOption() .option('-D, --debug-test', 'debug tests with built-in node inspector') .description('start tests') .action((...commandArguments) => { execWithConfig( require('../commands/test'), commandArguments, { useGSConfig: true, useWebpackConfig: true, skipClientEntryGeneration: true, skipServerEntryGeneration: true, }, ); }); // This is a catch all command. DO NOT PLACE ANY COMMANDS BELOW THIS commander .command('*', null, { noHelp: true }) .action((cmd) => { process.stderr.write(`Command '${highlight(cmd)}' not recognized`); commander.help(); }); commander.parse(process.argv);
JavaScript
0
@@ -1060,55 +1060,8 @@ k')%0A - .option('--yarn', 'use yarn instead of npm')%0A .a
78f05b7a90ad82abfb4ddda41181d8b7e6cb5d36
update index.js / Fix grammer (stratch -> scratch) (#3345)
www/src/pages/index.js
www/src/pages/index.js
import React from 'react'; import Button from 'react-bootstrap/lib/Button'; import Container from 'react-bootstrap/lib/Container'; import Row from 'react-bootstrap/lib/Row'; import Col from 'react-bootstrap/lib/Col'; import Jumbotron from 'react-bootstrap/lib/Jumbotron'; import { styled } from 'css-literal-loader/styled'; import withProps from 'recompose/withProps'; import pkg from '../../../package.json'; import withLayout from '../withLayout'; const MastHead = styled(Jumbotron)` @import '../css/theme'; background-color: $dark; padding: 0; color: white; padding-bottom: 0.5rem; `; const Content = styled('div')` composes: px-4 from global; background-image: url('../assets/logo-subtle.svg'); background-repeat: no-repeat; background-position: center; background-size: 60%; display: flex; flex-direction: column; justify-content: center; min-height: 450px; margin: 0 auto; max-width: 800px; @media (max-width: 800px) { padding: 0 40px; text-align: center; } `; const Heading = styled('h1')` @import '../css/theme'; color: $brand; font-weight: bold; font-size: 3.2rem; margin: 2rem 0; `; const SubHeading = styled('p')` composes: lead from global; line-height: 2; font-size: 1.6rem; `; const BrandButton = styled(Button)` @import '../css/theme'; &:global(.btn-brand) { @include button-outline-variant($brand, $dark); } `; const FeatureCard = withProps({ md: 4 })( styled(Col)` @import '../css/theme'; composes: px-4 py-3 from global; font-weight: 400; line-height: 1.6; & h2 { font-size: 1.6rem; color: $subtle; font-weight: 300; margin-bottom: 0.6rem; } `, ); const ButtonToolbar = styled('div')` @import '../css/theme'; @include media-breakpoint-down(sm) { margin: -1rem; & > * { width: 100%; max-width: 300px; margin: 1rem; } } `; export default withLayout( class HomePage extends React.Component { render() { return ( <main id="rb-docs-content"> <MastHead fluid> <Content> <Heading>React Bootstrap</Heading> <SubHeading> The most popular front-end framework <br /> <strong>Rebuilt</strong> for React. </SubHeading> <ButtonToolbar> <BrandButton size="lg" variant="brand" className="mr-3 px-5" href="/getting-started/introduction" > Get started </BrandButton> <Button size="lg" href="/components/alerts" className="px-5" variant="outline-light" > Components </Button> </ButtonToolbar> <div className="text-muted mt-3"> Current version: {pkg.version} </div> </Content> </MastHead> <Container> <Row> <FeatureCard> <h2>Rebuilt with React</h2> <p> React bootstrap replaces the Bootstrap javascript. Each component has been built from stratch as true React components, without uneeded dependencies like jQuery. </p> <p> As one of the oldest React libraries, react bootstrap has evolved and grown along-side React, making it an exellent choice as your UI foundation. </p> </FeatureCard> <FeatureCard> <h2>Bootstrap at its core</h2> <p> Built with compatibility in mind, we embrace our bootstrap core and strive to be compatible with the world's largest UI ecosystem. </p> <p> By relying entirely on the Bootstrap stylesheet, React bootstrap, just works with the thousands of bootstrap themes you already love. </p> <p /> </FeatureCard> <FeatureCard> <h2>Accessible by default</h2> <p> The React component model gives us more control over form and function of each component. </p> <p> Each component is implemented with accessibilty in mind. The result is a set of accessible-by-default components, over what is possible from plain Bootstrap. </p> </FeatureCard> </Row> </Container> </main> ); } }, );
JavaScript
0
@@ -3315,17 +3315,17 @@ t from s -t +c ratch as
942c71e269a88ad32fc3229f71cb6398bec02dce
Fix root route header partial missing param issue.
routes/root.js
routes/root.js
/** * Created by Edmundo on 4/8/2016 */ exports.root = function(req, res) { res.render('index'); };
JavaScript
0
@@ -92,14 +92,52 @@ ('index' +, %7B%0A routes: %7B root: 'active' %7D%0A %7D );%0A%7D;%0A
5a5324b019496516ac1f24e43ef2ba0962d650e3
Add more accurate time to unit observations
src/modules/home/components/Time.js
src/modules/home/components/Time.js
import React from 'react'; import moment from 'moment'; import {translate} from 'react-i18next'; const formatTime = (time: Date, t: Function) => { const now = moment(); let lookup = 'TIME.'; let options = {}; if(now.diff(time, 'days') === 0) { lookup += 'TODAY'; } else if (now.diff(time, 'days') === 1) { lookup += 'YESTERDAY'; } else if (now.diff(time, 'weeks') === 0) { lookup += 'DAYS_AGO'; options.days = now.diff(time, 'days'); } else if (now.diff(time, 'months') === 0) { lookup += 'WEEKS_AGO'; options.weeks = now.diff(time, 'weeks'); } else if (now.diff(time, 'years' > 1)) { lookup += 'NOT_AVAILABLE'; } else { lookup += 'MONTHS_AGO'; options.months = now.diff(time, 'months'); } return t(lookup, options); }; const Time = translate()(({time, t}) => <time dateTime={time.toISOString()}> { formatTime(time, t) } </time> ); export default Time;
JavaScript
0.000001
@@ -892,16 +892,99 @@ )%0A %7D%0A + %7Bmoment().diff(time, 'days') %3C 2 && ' '+time.getHours()+':'+time.getMinutes()%7D%0A %3C/time
db5746656a3c7e7eece859fb50d04d1213e5a88c
Add a `--show-startpage` / `-S` parameter to `qx serve` to show the startpage even if there is only one application.
source/class/qx/tool/cli/commands/Serve.js
source/class/qx/tool/cli/commands/Serve.js
/* ************************************************************************ qooxdoo - the new era of web development http://qooxdoo.org Copyright: 2017 Zenesis Ltd License: MIT: https://opensource.org/licenses/MIT See the LICENSE file in the project's top-level directory for details. Authors: * John Spackman ([email protected], @johnspackman) ************************************************************************ */ require("@qooxdoo/framework"); const path = require("upath"); const process = require("process"); const express = require("express"); const http = require("http"); require("app-module-path").addPath(process.cwd() + "/node_modules"); require("./Compile"); /** * Handles compilation of the project by qxcompiler */ qx.Class.define("qx.tool.cli.commands.Serve", { extend: qx.tool.cli.commands.Compile, statics: { getYargsCommand: function() { return { command : "serve [configFile]", describe : "runs a webserver to run the current application with continuous compilation, using compile.json", builder : { "target": { "default": "source", describe: "Set the target type: source or build or class name", requiresArg: true, type: "string" }, "output-path": { describe: "Base path for output", nargs: 1, requiresArg: true, type: "string" }, "locale": { describe: "Compile for a given locale", nargs: 1, requiresArg: true, type: "string", array: true }, "update-po-files": { describe: "enables detection of translations and writing them out into .po files", type: "boolean", default: false, alias: "u" }, "write-all-translations": { describe: "enables output of all translations, not just those that are explicitly referenced", type: "boolean" }, "set": { describe: "sets an environment value", nargs: 1, requiresArg: true, type: "string", array: true }, "machine-readable": { describe: "output compiler messages in machine-readable format", type: "boolean" }, "verbose": { alias: "v", describe: "enables additional progress output to console", type: "boolean" }, "minify": { describe: "disables minification (for build targets only)", choices: ["off", "minify", "mangle", "beautify"], default: "mangle" }, "save-unminified": { describe: "Saves a copy of the unminified version of output files (build target only)", type: "boolean", default: false }, "erase": { describe: "Enabled automatic deletion of the output directory when compiler version changes", type: "boolean", default: true }, "typescript": { describe: "Outputs typescript definitions in qooxdoo.d.ts", type: "boolean" }, "add-created-at": { describe: "Adds code to populate object's $$createdAt", type: "boolean" }, "clean": { describe: "Deletes the target dir before compile", type: "boolean" }, "listen-port": { describe: "The port for the web browser to listen on", type: "number", default: 8080 }, "write-library-info": { describe: "Write library information to the script, for reflection", type: "boolean", default: true }, "bundling": { describe: "Whether bundling is enabled", type: "boolean", default: true } }, handler: function(argv) { return new qx.tool.cli.commands.Serve(argv) .process() .catch(e => { console.error(e.stack || e.message); process.exit(1); }); } }; } }, members: { /* * @Override */ process: async function() { this.argv.watch = true; this.argv["machine-readable"] = false; this.argv["feedback"] = false; await this.base(arguments); await this.runWebServer(); }, /** * * @returns */ /* @ignore qx.tool.$$resourceDir */ runWebServer: async function() { var maker = this._getMaker(); var config = this._getConfig(); var target = maker.getTarget(); var apps = maker.getApplications(); const app = express(); if ((apps.length === 1) && apps[0].getWriteIndexHtmlToRoot()) { app.use("/", express.static(target.getOutputDir())); } else { app.use("/docs", express.static(path.join(await this.getAppQxPath(), "../docs"))); app.use("/", express.static(path.join(qx.tool.$$resourceDir, "cli/serve/build"))); app.use("/" + target.getOutputDir(), express.static(target.getOutputDir())); var obj = { target: { type: target.getType(), outputDir: "/" + target.getOutputDir() }, apps: apps.map(app => ({ name: app.getName(), type: app.getType(), title: app.getTitle() || app.getName(), outputPath: target.getProjectDir(app) + "/" })) }; app.get("/serve.api/apps.json", (req, res) => { res.set("Content-Type", "application/json"); res.send(JSON.stringify(obj, null, 2)); }); } this.addListenerOnce("made", e => { let server = http.createServer(app); server.on("error", e => { if (e.code == "EADDRINUSE") { qx.tool.compiler.Console.print("qx.tool.cli.serve.webAddrInUse", config.serve.listenPort); process.exit(-1); } else { console.log("Error when starting web server: " + e); } }); server.listen(config.serve.listenPort, () => qx.tool.compiler.Console.print("qx.tool.cli.serve.webStarted", "http://localhost:" + config.serve.listenPort)); }); } }, defer: function(statics) { qx.tool.compiler.Console.addMessageIds({ "qx.tool.cli.serve.webStarted": "Web server started, please browse to %1", "qx.tool.cli.serve.webAddrInUse": "Web server cannot start because port %1 is already in use" }); } });
JavaScript
0
@@ -2571,32 +2571,256 @@ n%22%0A %7D,%0A + %22show-startpage%22: %7B%0A alias: %22S%22,%0A describe: %22Show the startpage with the list of applications and additional information%22,%0A type: %22boolean%22,%0A default: false%0A %7D,%0A %22minif @@ -5139,17 +5139,16 @@ if -( (apps.le @@ -5157,17 +5157,16 @@ th === 1 -) && apps @@ -5194,16 +5194,53 @@ ToRoot() + && this.argv.showStartpage === false ) %7B%0A
fe7afa5b7e186aa293ec4acea93b14535d8ca683
make bold/italic/ol/ul also work in FF
src/patterns/edit.js
src/patterns/edit.js
define([ 'require', '../logging', '../patterns' ], function(require) { var log = require('../logging').getLogger('edit'); // create a div after the textarea // copy the textarea's content unquoted to the div // hide the textarea // copy content back before form is serialized var text2div = function($el) { // hide textarea $el.hide(); // make sure textarea has an id // XXX: generate something proper var id = $el.attr('id'); if (!id) { id = "my-id-that-should-be-replaced-by-something-unique"; $el.attr({id: id}); } // create contenteditable div var editid = 'edit-' + id, $edit = $('<div id="' + editid + '" contenteditable="true"/>').insertAfter($el); $edit.html($el.val()); $edit.attr({style: 'min-height: 50px'}); // ensure form is ajaxified and copy content back before serialize var ajaxify = require('../patterns').ajaxify.init, $form = $el.parents('form'); ajaxify($form); $form.on('form-pre-serialize', function() { $el.html($edit.html()); }); return $edit; }; // utility method for determining if something is contenteditable var is_contenteditable = function(el) { return $(el).is("[contenteditable=true]") || ( $(el).parents("[contenteditable=true]").length > 0 ); }; // simply replaces // rather than toggles, but // theres no reason you couldn't have // it do both! var wrap_selection = function(wrap_html){ var selection_node = $(window.getSelection().anchorNode); if(is_contenteditable(selection_node)) { // You just want to unwrap if your // parent is already selected if(selection_node.parent().is(wrap_html)) { selection_node.unwrap(); } else { selection_node.wrap("<" + wrap_html + ">"); } } // wrap() normally breaks contentEditable // this is a hacky replacement selection_node.attr('contenteditable', true); }; var init = function($el, opts) { var $edit = text2div($el); var $ctrls = $('.editor-controls'), buttons = {}; buttons.bold = $ctrls.find('.strong'); buttons.italic = $ctrls.find('.emphasised'); buttons.insertorderedlist = $ctrls.find('.list-ordered'); buttons.insertunorderedlist = $ctrls.find('.list-unordered'); //buttons.insertparagraph = $ctrls.find('.paragraph'); buttons.clear = $ctrls.find('.clear'); buttons.inserth1 = $ctrls.find('.header_1'); buttons.inserth2 = $ctrls.find('.header_2'); buttons.inserth3 = $ctrls.find('.header_3'); buttons.upload_image = $ctrls.find('.upload_image'); buttons.link_image = $ctrls.find('.link_image'); var button_handler = { 'bold' : function(){ document.execCommand('bold'); }, 'italic' : function(){ document.execCommand('italic'); }, 'insertparagraph' : function(){ return 0; }, 'insertorderedlist' : function(){ document.execCommand('insertorderedlist'); }, 'insertunorderedlist' : function(){ document.execCommand('insertunorderedlist'); }, 'inserth1' : function(){ wrap_selection('h1') }, 'inserth2' : function(){ wrap_selection('h2') }, 'inserth3' : function(){ wrap_selection('h3') }, 'clear' : function(){ var selection_node = $(window.getSelection().anchorNode); document.execCommand('removeformat'); if (is_contenteditable(selection_node)) { selection_node.unwrap(); if (!$(selection_node).parent().is("p")) { $(selection_node).wrap('<p>'); } } }, 'upload_image' : function(){ document.execCommand(); }, 'link_image' : function(){ var source = prompt('URL of Image'); if(source) { document.execCommand('insertImage', false, source); } } }; // lame helper that // toggles the class, // triggers the handler var button_click = function(element) { buttons[element].toggleClass('selected'); button_handler[element](); }; // bind click to button_click()/1 for (var key in buttons) { buttons[key].click(function(element){ return function() { log.debug('clicked', element); button_click(element); }; }(key)); } // Enables contentEditable $('form').attr('contenteditable','true'); var setstate = function(selection) { var markup = selection.markupEffectiveAtStart; if (!markup) return; $ctrls.find('*').removeClass('selected'); $.each(markup, function(idx, el) { var tag = el.nodeName.toLowerCase(), $button = buttons[tag]; if ($button) $button.addClass('selected'); log.debug('selected', tag); }); }; }; var pattern = { markup_trigger: 'form textarea.edit', initialised_class: 'edit', init: init }; return pattern; });
JavaScript
0.000002
@@ -3169,16 +3169,27 @@ d('bold' +, false, '' ); %7D,%0A @@ -3265,16 +3265,27 @@ 'italic' +, false, '' ); %7D,%0A @@ -3427,32 +3427,43 @@ sertorderedlist' +, false, '' ); %7D,%0A @@ -3544,16 +3544,27 @@ redlist' +, false, '' ); %7D,%0A
568891aa9c3823a5d70dd3886c14ccb0177c78d9
Update footer link
packages/gdl-frontend/components/Layout/Footer.js
packages/gdl-frontend/components/Layout/Footer.js
// @flow /** * Part of GDL gdl-frontend. * Copyright (C) 2017 GDL * * See LICENSE */ import * as React from 'react'; import styled from 'react-emotion'; import { Trans } from '@lingui/react'; import config from '../../config'; import Container from '../../elements/Container'; import CCLogo from './cc-logo.svg'; import { colors } from '../../style/theme'; import media from '../../style/media'; import FaFacebookSquare from 'react-icons/lib/fa/facebook-square'; import FaTwitterSquare from 'react-icons/lib/fa/twitter-square'; import FaYoutubeSquare from 'react-icons/lib/fa/youtube-square'; const FooterStyle = styled('footer')` display: flex; flex-wrap: wrap; justify-content: space-between; align-items: center; margin-top: 40px; margin-bottom: 50px; a { text-decoration: none; color: ${colors.text.default}; &:hover { text-decoration: underline; } } `; const WrappingList = styled('ul')` display: flex; justify-content: space-between; flex-grow: 3; flex-wrap: wrap; order: 2; font-size: 0.8rem; padding: 0; margin-left: 28px; list-style: none; li { padding: 8px; } ${media.tablet` li { width: 33%; } `} ${media.mobile` li { width: 50%; } margin-top: 20px;mh `}; `; const SocialMediaIcons = styled('div')` display: flex; justify-content: space-between; flex-grow: 1; margin: 14px 36px 20px 36px; a { font-size: 2.25rem; color: ${colors.text.subtle}; &:hover { color: ${colors.default}; } } ${media.tablet` order: 4; `}; ${media.mobile` order: 1; `}; `; const CreativeCommons = styled('div')` order: 3; flex-grow: 1; text-align: center; a { &:hover { fill: ${colors.default}; } ${media.mobile` width: 100%; `} `; const Footer = () => { return ( <Container size="large" stickToEdgeOnLargeScreens width="100%" // https://philipwalton.com/articles/normalizing-cross-browser-flexbox-bugs/ css={{ flexShrink: '0' }} > <FooterStyle> <div css={[ { order: 2, width: '100%', borderBottom: `1px solid ${colors.base.grayLight}`, margin: '10px' }, media.tablet({ display: 'none' }) ]} /> <WrappingList> <li> <a href="https://home.digitallibrary.io/the-global-digital-library-uses-cookies/"> <Trans>Cookie policy</Trans> </a> </li> <li> <a href="https://home.digitallibrary.io/privacy/"> <Trans>Privacy policy</Trans> </a> </li> <li> <a href="https://blog.digitallibrary.io/cc/"> <Trans>Licensing and reuse</Trans> </a> </li> <li> <a href={config.zendeskUrl}> <Trans>Report issues</Trans> </a> </li> <li> <a href="https://home.digitallibrary.io/about/"> <Trans>About</Trans> </a> </li> <li> <a href="https://blog.digitallibrary.io/"> <Trans>Blog</Trans> </a> </li> </WrappingList> <CreativeCommons> <a href="https://creativecommons.org/" component="a" aria-label="Creative Commons" > <CCLogo css={{ width: '100px' }} /> </a> </CreativeCommons> <SocialMediaIcons> <a title="Facebook" aria-label="Facebook" href="https://nb-no.facebook.com/globaldigitallibrary/" > <FaFacebookSquare /> </a> <a title="Twitter" aria-label="Twitter" href="https://www.facebook.com/globaldigitallibrary/" > <FaTwitterSquare /> </a> <a title="YouTube" aria-label="YouTube" href="https://www.youtube.com/channel/UCN5RyDXS_aKA37YwIPzQPTg" > <FaYoutubeSquare /> </a> </SocialMediaIcons> </FooterStyle> </Container> ); }; export default Footer;
JavaScript
0
@@ -2743,36 +2743,36 @@ a href=%22https:// -blog +home .digitallibrary.
61dd51dc94f1887e93606a8a7924cfd54d03b7b9
fix newline issue
dialogflow-cx-webhook-nodejs/revive-previous-session-state.js
dialogflow-cx-webhook-nodejs/revive-previous-session-state.js
// Copyright 2021 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 // // 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'; async function main(projectId, location, agentId, query, languageCode) { // [START dialogflow_revive_previous_session_state_async] // projectId = 'my-project'; // location = 'global'; // agentId = 'my-agent'; // query = 'Hello!'; // languageCode = 'en'; // Imports the Google Cloud Dialogflow CX API library const {SessionsClient} = require('@google-cloud/dialogflow-cx'); /** * Example for regional endpoint: * const location = 'us-central1' * const client = new SessionsClient({apiEndpoint: 'us-central1-dialogflow.googleapis.com'}) */ const client = new SessionsClient(); const uuid = require('uuid'); // Create a function that can marshal the current session state to JSON: function marshalSession(response) { const sessionRestartData = { currentPage: response.queryResult.currentPage.name, parameters: response.queryResult.parameters, }; return sessionRestartData; } async function detectFirstSessionIntent() { // Marshal the current state: const sessionId = uuid.v4(); const sessionPath = client.projectLocationAgentSessionPath( projectId, location, agentId, sessionId ); console.info(sessionPath); // Send request: const request = { session: sessionPath, queryParams: { parameters: { fields: { firstName: {kind: 'stringValue', stringValue: 'John'}, lastName: {kind: 'stringValue', stringValue: 'Doe'}, }, }, }, queryInput: { text: { text: query, }, languageCode, }, }; const [response] = await client.detectIntent(request); console.log(`User Query: ${query}`); for (const message of response.queryResult.responseMessages) { if (message.text) { console.log(`Agent Response: ${message.text.text}`); } } if (response.queryResult.match.intent) { console.log( `Matched Intent: ${response.queryResult.match.intent.displayName}` ); } return marshalSession(response); } async function revivePreviousSessionState() { // Unmarshal the saved state: const sessionStateDict = await detectFirstSessionIntent(); const currentPage = sessionStateDict['currentPage']; const parameters = sessionStateDict['parameters']; const queryParams = { currentPage: currentPage, parameters: parameters, }; const sessionId = uuid.v4().toString; const secondRequest = { session: client.projectLocationAgentSessionPath( projectId, location, agentId, sessionId ), queryInput: { text: { text: 'Hello 60 minutes later!', }, languageCode: 'en-US', }, queryParams: queryParams, }; const [secondResponse] = await client.detectIntent(secondRequest); console.log(` Revived Session Parameters: ${JSON.stringify(secondResponse.queryResult.parameters)}`); console.log(` Revived Session Query Text: ${JSON.stringify(secondResponse.queryResult.text)}`); } revivePreviousSessionState(); // [END dialogflow_revive_previous_session_state_async] } process.on('unhandledRejection', err => { console.error(err.message); process.exitCode = 1; }); main(...process.argv.slice(2));
JavaScript
0
@@ -3941,8 +3941,9 @@ ice(2)); +%0A
ab21201f8eba26bf63f3d6e235ce0ddea330af75
remove trash
routes/user.js
routes/user.js
// Create app var app = require('express').Router(); var api = require('../utils/api'); var await = require('asyncawait/await'); // Include models var User = require('../models/User'); var FS = require('../utils/FS'); var Google = require('../utils/Google'); // Sample API var i = 0; app.get('/:id', api((req, res) => { // Step 1: update user state var id = req.params.id; var rs = await(User.setState(id, 'count = ' + ++ i)); console.log(rs); if (rs.affectedRows != 1) return res.err(1, 'update user failed'); // Step 2: get user by id, read test.txt, google pizza at the same time try { var [user, file, google] = await([User(id), FS('test.txt'), Google('pizza')]); } catch (e) { return res.err(-1, 'unknown error', e); } var result = {user: user, file: file, google: google.length}; console.log(result); res.ok(result); })); module.exports = app;
JavaScript
0.000009
@@ -599,18 +599,8 @@ ime%0A - try %7B%0A va @@ -680,72 +680,8 @@ %5D);%0A - %7D catch (e) %7B%0A return res.err(-1, 'unknown error', e);%0A %7D%0A va
6e7ad53f9ec366305473d06a63f34b62caf16f9b
object is not a function
models/profile.js
models/profile.js
module.exports = profile var callresp = require('cluster-callresp') , gravatar = require('gravatar') function profile (name, cb) { // get the most recent data for this req. callresp({ cmd: 'registry.get' , name: '/-/user/org.couchdb.user:' + name , maxAge: 0 , stale: false }, function (er, data) { if (er || !data) return cb(er, data) if (data.email) { data.gravatar = gravatar(data.email, {s:50, d:'retro'}, true) } cb(er, data) }) }
JavaScript
0.999999
@@ -94,16 +94,20 @@ avatar') +.url %0A%0Afuncti
ffe85b1a874a48037725a9b80ce5955cc15c1c10
fix rejection reason issue
app/models/item.js
app/models/item.js
import Ember from 'ember'; import DS from 'ember-data'; import '../computed/foreign-key'; import config from '../config/environment'; var attr = DS.attr, belongsTo = DS.belongsTo, hasMany = DS.hasMany, foreignKey = Ember.computed.foreignKey; export default DS.Model.extend({ donorDescription: attr('string'), state: attr('string'), rejectReason: attr('string'), rejectionComments: attr('string'), createdAt: attr('date'), updatedAt: attr('date'), packages: hasMany('package', { async: false }), messages: hasMany('message', { async: true }), images: hasMany('image', { async: false }), offer: belongsTo('offer', { async: false }), packageType: belongsTo('package_type', { async: false }), donorCondition: belongsTo('donor_condition', { async: false }), donorConditionId: foreignKey('donorCondition.id'), rejectionReason: belongsTo('rejection_reason', { async: false }), state_event: attr('string'), isAccepted: Ember.computed.equal("state", "accepted"), isRejected: Ember.computed.equal("state", "rejected"), isDrafted: Ember.computed.equal("state", "draft"), appName: config.APP.NAME, removePrivateMessage: Ember.observer('messages.[]', '[email protected]', function() { if(this.get('appName') === "app.goodcity") { this.get("messages").forEach(msg => { if(msg && msg.get('isPrivate') === undefined) { this.store.unloadRecord(msg); } }); } }), canUpdated: Ember.computed("hasReceivedPackages", "offer.state", function(){ return !(this.get("hasReceivedPackages") || this.get("offer.isFinished") || this.get('offer.state') === 'receiving'); }), isDraft: Ember.computed('offer.state', function(){ return this.get('offer.state') === 'draft'; }), isSubmitted: Ember.computed('state', 'offer.state', function(){ return this.get('state') === 'submitted' && this.get('offer.state') === 'submitted'; }), isUnderReview: Ember.computed('state', 'offer.state', function(){ return this.get('state') === 'submitted' && this.get('offer.state') === 'under_review'; }), hasReceivedPackages: Ember.computed('[email protected]', function(){ return this.get('packages').filterBy('isReceived', true).length > 0; }), displayImage: Ember.computed('[email protected]', function(){ return this.get("images").filterBy("favourite").get("firstObject") || this.get("images").sortBy("id").get("firstObject") || null; }), nonFavouriteImages: Ember.computed('[email protected]', function(){ return this.get("images").rejectBy("favourite", true); }), displayImageUrl: Ember.computed('displayImage', 'displayImage.thumbImageUrl', function(){ return this.get('displayImage.thumbImageUrl') || "assets/images/default_item.jpg"; }), imageCount: Ember.computed.alias("images.length"), // unread messages unreadMessages: Ember.computed('[email protected]', function(){ return this.get('messages').filterBy('state', 'unread').sortBy('createdAt'); }), // unread offer-messages by donor hasUnreadDonorMessages: Ember.computed('unreadMessages', function(){ return this.get('unreadMessages').filterBy('isPrivate', false).length > 0; }), // unread offer-messages by supervisor-reviewer hasUnreadPrivateMessages: Ember.computed('unreadMessages', function(){ return this.get('unreadMessages').filterBy('isPrivate', true).length > 0; }), unreadMessagesCount: Ember.computed('unreadMessages', function(){ var count = this.get('unreadMessages').length; return count > 0 ? count : null ; }), // last message lastMessage: Ember.computed('messages.[]', function(){ return this.get('messages').sortBy('createdAt').get('lastObject'); }), // to sort on offer-details page for updated-item and latest-message latestUpdatedTime: Ember.computed('lastMessage', function(){ var value; switch(Ember.compare(this.get('lastMessage.createdAt'), this.get('updatedAt'))) { case 0 : case 1 : value = this.get('lastMessage.createdAt'); break; case -1 : value = this.get('updatedAt'); break; } return value; }), statusBarClass: Ember.computed("state", function(){ if(this.get("offer.isCancelled")) { return "is-closed"; } else if(this.get("isSubmitted")) { return "is-submitted"; } else if(this.get("isUnderReview")) { return "is-under-review"; } else if(this.get("isAccepted")) { return "is-accepted"; } else if(this.get("isRejected")) { return "is-rejected"; } }), pageLink: Ember.computed("state", function(){ return this.get("isRejected") ? 'review_item.reject' : 'review_item.accept'; }) });
JavaScript
0.000005
@@ -3795,16 +3795,39 @@ ges.%5B%5D', + '[email protected]', functio
2ba951e3dbb309e26acc97e2d62e1409e5e2c5af
return `active` flag with player info
server/actions/getPlayerInfo.js
server/actions/getPlayerInfo.js
import config from 'src/config' import {graphQLFetcher} from 'src/server/util/graphql' export default function getPlayerInfo(playerIds) { return graphQLFetcher(config.server.idm.baseURL)({ query: 'query ($playerIds: [ID]!) { getUsersByIds(ids: $playerIds) { id handle name } }', variables: {playerIds}, }).then(result => result.data.getUsersByIds) }
JavaScript
0.000004
@@ -261,16 +261,23 @@ s) %7B id +active handle n
5527f9b0df42a7a6e3ed625908457335b3465e13
use a local domain
public/javascripts/controllers.js
public/javascripts/controllers.js
'use strict'; var cagewebControllers = angular.module('cagewebControllers', []); cagewebControllers.controller('IndexCtrl', ['$scope', '$http', function($scope, $http) { $http.get('http://localhost:9000/entity/activity'). success(function(data, status, headers, config) { $scope.activity = data; console.log($scope.activity); }); } ]);
JavaScript
0
@@ -181,40 +181,125 @@ -$http.get('http://localhost:9000 +// hardcoded path to my local cmf server returning json of activities%0A $http.get('http://storage.bigboi.lvh.me /ent
27a5923db1ca209276f16a315a044c41470e103e
Add port
servant.js
servant.js
var express = require('express') var app = express app.get('/payload', function(req, res) { console.log(req); })
JavaScript
0.000001
@@ -108,8 +108,26 @@ req);%0A%7D) +%0A%0Aapp.listen(9000)
f4f5cd39dfd88f6fa5d7e6c0db25c47434dab16c
Update chart view on state changes.
js/ChartView.js
js/ChartView.js
'use strict'; var React = require('react'); // Styles var compStyles = require('./ChartView.module.css'); var ChartView = React.createClass({ shouldComponentUpdate: function () { return false; }, componentDidMount: function () { var {appState, callback} = this.props, {root} = this.refs; require.ensure(['./chart'], function () { var chart = require('./chart'); chart(root, callback, {xena: JSON.stringify(appState)}); }); }, render: function () { return <div ref='root' className={compStyles.ChartView}/>; } }); module.exports = ChartView;
JavaScript
0
@@ -37,16 +37,53 @@ react'); +%0Avar _ = require('./underscore_ext'); %0A%0A// Sty @@ -267,16 +267,323 @@ on () %7B%0A +%09%09this.chartRender(this.props);%0A%09%7D,%0A%09componentWillReceiveProps(newProps) %7B%0A%09%09// Updating this way is clumsy. Need to refactor chart view.%0A%09%09if (!_.isEqual(_.omit(this.props.appState, 'chartState'),%0A%09%09%09%09_.omit(newProps.appState, 'chartState'))) %7B%0A%09%09%09this.chartRender(newProps);%0A%09%09%7D%0A%09%7D,%0A%09chartRender(props) %7B%0A %09%09var %7Ba @@ -603,21 +603,16 @@ back%7D = -this. props,%0A%09 @@ -677,16 +677,16 @@ on () %7B%0A - %09%09%09var c @@ -712,16 +712,40 @@ hart');%0A +%09%09%09root.innerHTML = '';%0A %09%09%09chart
39af635cf843caff3ac261a21e9fd511309553e4
add createdAt property to Inquiry relationship
server/src/db/models/inquiry.js
server/src/db/models/inquiry.js
import Promise from 'bluebird' import db from '../db' import { updateStringObject } from '../../middleware/utils' export default { // function for a user to create an inquiry createInquiry: (trippeeId, trippianId, inquiryProps) => { return new Promise((resolve, reject) => { db.relateAsync(trippeeId, 'INQUIRY', trippianId, inquiryProps) .then((inquiry) => { if (inquiry) { resolve(inquiry) } else { reject(new Error('inquiry could not be sent')) } }) }) }, // function that gets back all the inquiries given a trippian id getAllInquiriesForTrippian: (trippianId) => { return new Promise((resolve, reject) => { db.relationshipsAsync(trippianId, 'in', 'INQUIRY') .then((inquiries) => { if (inquiries) { resolve(inquiries) } else { reject(new Error('user has no inquiries at this time')) } }) }) }, getAllInquiries: () => { return new Promise((resolve, reject) => { let cypher = `match ()-[i:INQUIRY]->() return i` db.queryAsync(cypher) .then(allInquiries => { if (allInquiries.length) { resolve(allInquiries) } }) .catch(error => { console.error(error) }) }) }, // function that deletes the inquiry from db if trippian rejects the request deleteInquiry: (inquiryId) => { return new Promise((resolve, reject) => { let cypher = `match (u:User)-[r:INQUIRY]->() where id(r)=${inquiryId} delete r;` db.queryAsync(cypher) .then((deleted) => { if (deleted) { resolve(deleted) } else { reject(new Error('inquiry was not deleted or does not exist')) } }) }) }, // function for trippians to accept inquiry on put request acceptInquiry: (inquiryId) => { return new Promise((resolve, reject) => { let cypher = `match (u1:User)-[r:INQUIRY]->(u2:User) where id(r)=${inquiryId} create (u2)-[t:TOURED]->(u1) set t = r return t` db.queryAsync(cypher) .then((touredRelationship) => { if (touredRelationship) { resolve(touredRelationship) } else { reject(new Error('inquiry could not be accepted or does not exist')) } }) }) }, updateInquiry: (details, inquiryId) => { let updateString = updateStringObject(details, '') return new Promise((resolve, reject) => { let cypher = `match ()-[r:INQUIRY]->() where id(r)=${inquiryId} set r += {${updateString}} return r;` db.queryAsync(cypher) .then((updatedInquiry) => { if (updatedInquiry) { resolve(updatedInquiry) } else { reject(new Error('inquiry could not be updated')) } }) .catch(function(error) { console.error(error) }) }) } }
JavaScript
0
@@ -227,24 +227,61 @@ Props) =%3E %7B%0A + inquiryProps.createdAt = Date();%0A return n
574f3dcf367d93753a8c07876cd7b344ec355f86
Complete solution routes.
server/solutions/solutionRoutes.js
server/solutions/solutionRoutes.js
var Solution = require('./solutionModel'); module.exports = function(app) { app.param('qid', function(req, res, next, qid) { Solution.find({questionId: qid}).populate('questionId').populate('userId') .exec(function(err, data) { if (err) { //res.send(500, err); res.status(500).send(err); } else { req.solutionData = data; next(); } }); }); app.get('/solutions/:qid', function(req, res, next) { res.status(200); res.send(req.solutionData); }); app.get('/solutions', function(req, res, next) { Solution.find({}).exec(function(err, data) { if (err) { res.send(500, err); } else { res.json(data); } }) }); //Expect POST object like: //{ // "content": "sample regex answer", // "questionId": 1, // "userId": 3 //} app.post('/solutions', function(req, res, next) { //var solution = { // content: req.body.content, // questionId: req.body.questionId, // userId: req.body.userId, // votes: req.body.votes //}; //var newSolution = Solution.create(solution, function(err, solution) { // res.send(solution); //}); var data = req.body; var addSolution = Solution.create({ content: data.content, questionId: data.questionId, userId: data.userId, votes: data.votes }, function(err, newSolution) { res.send(newSolution); }); //var newSolution = new Solution(solution); //newSolution.save(function(err, newEntry) { // if (err) { // res.send(500, err); // } else { // //res.send(200, newEntry); // res.status(200).send(newEntry); // } //}) }); app.put('/solutions', function(req, res) { var id = req.body._id; Solution.findByIdAndUpdate(id, req.body, function(err) { if (err) { return res.send(500, err); } }); res.send(req.body); }); };
JavaScript
0
@@ -590,10 +590,8 @@ ind( -%7B%7D ).ex @@ -713,16 +713,17 @@ %7D%0A %7D) +; %0A %7D);%0A%0A @@ -904,808 +904,261 @@ -//var solution = %7B%0A // content: req.body.content,%0A // questionId: req.body.questionId,%0A // userId: req.body.userId,%0A // votes: req.body.votes%0A //%7D;%0A //var newSolution = Solution.create(solution, function(err, solution) %7B%0A // res.send(solution);%0A //%7D);%0A var data = req.body;%0A%0A var addSolution = Solution.create(%7B%0A content: data.content,%0A questionId: data.questionId,%0A userId: data.userId,%0A votes: data.votes%0A %7D,%0A function(err, newSolution) %7B%0A res.send(newSolution);%0A %7D);%0A%0A //var newSolution = new Solution(solution);%0A //newSolution.save(function(err, newEntry) %7B%0A // if (err) %7B%0A // res.send(500, err);%0A // %7D else %7B%0A // //res.send(200, newEntry);%0A // res.status(200).send(newEntry);%0A // %7D%0A //%7D) +var data = req.body;%0A%0A var addSolution = Solution.create(%7B%0A content: data.content,%0A questionId: data.questionId,%0A userId: data.userId,%0A votes: data.votes%0A %7D,%0A function(err, newSolution) %7B%0A res.send(newSolution);%0A %7D); %0A %7D
a8864eef8d937f9f1dc5f4291b92d0c415c2bff8
Fix sig and eol clocks not being deleted properly
public/js/siggy.activity.thera.js
public/js/siggy.activity.thera.js
/* * @license Proprietary * @copyright Copyright (c) 2014 borkedLabs - All Rights Reserved */ siggy2.Activity = siggy2.Activity || {}; siggy2.Activity.Thera = function(core) { var $this = this; this.key = 'thera'; this._updateTimeout = null; this.core = core; this.sigClocks = {}; this.eolClocks = {}; this.updateRate = 30000; this.templateRow = Handlebars.compile( $("#template-thera-table-row").html() ); this.table = $('#thera-exits-table tbody'); var tableSorterHeaders = { 0: { sortInitialOrder: 'asc' } }; $('#thera-exits-table').tablesorter( { headers: tableSorterHeaders }); $('#thera-exits-table').trigger("sorton", [ [[0,0]] ]); $('#activity-thera-import').click( function() { $this.dialogImport(); }); this.setupDialogImport(); } siggy2.Activity.Thera.prototype.setupDialogImport = function() { var $this = this; $('#dialog-import-thera button[type=submit]').click( function(e) { e.stopPropagation(); var data = { 'clean': $('#dialog-import-thera input[name=clean]').val(), 'chainmap': $('#dialog-import-thera select[name=chainmap]').val() }; $.post($this.core.settings.baseUrl + 'thera/import_to_chainmap', data, function (ret) { $.unblockUI(); }); return false; }); $('#dialog-import-thera button[type=reset]').click( function() { $.unblockUI(); return false; }); } siggy2.Activity.Thera.prototype.dialogImport = function() { this.core.openBox('#dialog-import-thera'); var sel = siggy2.Maps.getSelectDropdown(siggy2.Maps.selected, "(current map)"); $('#dialog-import-thera select[name=chainmap]').html(sel.html()); $('#dialog-import-thera select[name=chainmap]').val(sel.val()); } siggy2.Activity.Thera.prototype.start = function() { $('#activity-' + this.key).show(); this.update(); } siggy2.Activity.Thera.prototype.stop = function() { clearTimeout(this._updateTimeout); $('#activity-' + this.key).hide(); } siggy2.Activity.Thera.prototype.update = function() { var $this = this; $.ajax({ url: this.core.settings.baseUrl + 'thera/latest_exits', dataType: 'json', cache: false, async: true, method: 'get', success: function (data) { $this.updateTable(data); $this._updateTimeout = setTimeout(function(thisObj) { thisObj.update() }, $this.updateRate, $this); } }); } siggy2.Activity.Thera.prototype.updateTable = function( exits ) { var $this = this; $('#thera-exits-table tbody tr').each(function() { var id = $(this).data('id'); if( typeof exits[id] == 'undefined' ) { $(this).children('td.wormhole-type').qtip('destroy'); if( typeof $this.sigClocks[id] != 'undefined' ) { $this.sigClocks[i].destroy(); delete $this.sigClocks[i]; } if( typeof $this.eolClocks[id] != 'undefined' ) { $this.eolClocks[i].destroy(); delete $this.eolClocks[i]; } $(this).remove(); } else { exits[id].row_already_exists = true; $(this).children('td.jumps').text( exits[id].jumps ); } }); for( var i in exits ) { var exit = exits[i]; if( exit.row_already_exists ) continue; var wh = siggy2.StaticData.getWormholeByID(exit.wormhole_type); if( wh != null ) { desc_tooltip = siggy2.StaticData.templateWormholeInfoTooltip(wh); exit.wormhole_name = wh.name; } var row = this.templateRow( exit ); this.table.append(row); this.sigClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, null, '#thera-sig-' + exit.id + ' td.age span.age-clock', "test"); if( wh != null ) { var endDate = parseInt(exit.created_at)+(3600*wh.lifetime); this.eolClocks[exit.id] = new siggy2.Timer(exit.created_at * 1000, endDate* 1000, '#thera-sig-' + exit.id + ' td.age p.eol-clock', "test"); } $('#thera-sig-' + exit.id + ' td.wormhole-type').qtip({ content: { text: desc_tooltip }, position: { target: 'mouse', adjust: { x: 5, y: 5 }, viewport: $(window) } }); } $('#thera-exits-table').trigger('update'); }
JavaScript
0
@@ -2658,32 +2658,33 @@ this.sigClocks%5Bi +d %5D.destroy();%0A%09%09%09 @@ -2700,32 +2700,33 @@ this.sigClocks%5Bi +d %5D;%0A%09%09%09%7D%0A%0A%09%09%09if( @@ -2795,16 +2795,17 @@ Clocks%5Bi +d %5D.destro @@ -2837,16 +2837,17 @@ Clocks%5Bi +d %5D;%0A%09%09%09%7D%0A
5dac072be3e338bb88329c9385daa77629a974f6
Use 'TextEncoder' to measure correct length of UTF-8 strings
source/renderer/app/api/ada/lib/request.js
source/renderer/app/api/ada/lib/request.js
// @flow import https from 'https'; import { size, has, get, omit } from 'lodash'; import querystring from 'querystring'; import { encryptPassphrase } from './encryptPassphrase'; export type RequestOptions = { hostname: string, method: string, path: string, port: number, ca: string, headers?: { 'Content-Type': string, 'Content-Length': number, }, }; function typedRequest<Response>( httpOptions: RequestOptions, queryParams?: {}, rawBodyParams?: any ): Promise<Response> { return new Promise((resolve, reject) => { const options: RequestOptions = Object.assign({}, httpOptions); let hasRequestBody = false; let requestBody = ''; let queryString = ''; if (queryParams && size(queryParams) > 0) { // Handle passphrase if (has(queryParams, 'passphrase')) { const passphrase = get(queryParams, 'passphrase'); // If passphrase is present it must be encrypted and included in options.path if (passphrase) { const encryptedPassphrase = encryptPassphrase(passphrase); queryString = `?passphrase=${encryptedPassphrase}`; } // Passphrase must be ommited from rest query params queryParams = omit(queryParams, 'passphrase'); if (size(queryParams > 1) && passphrase) { queryString += `&${querystring.stringify(queryParams)}`; } } else { queryString = `?${querystring.stringify(queryParams)}`; } if (queryString) options.path += queryString; } // Handle raw body params if (rawBodyParams) { hasRequestBody = true; requestBody = JSON.stringify(rawBodyParams); options.headers = { 'Content-Length': requestBody.length, 'Content-Type': 'application/json', }; } const httpsRequest = https.request(options); if (hasRequestBody) { httpsRequest.write(requestBody); } httpsRequest.on('response', (response) => { let body = ''; // Cardano-sl returns chunked requests, so we need to concat them response.on('data', (chunk) => (body += chunk)); // Reject errors response.on('error', (error) => reject(error)); // Resolve JSON results and handle weird backend behavior // of "Left" (for errors) and "Right" (for success) properties response.on('end', () => { try { const parsedBody = JSON.parse(body); if (has(parsedBody, 'Right')) { // "Right" means 200 ok (success) -> also handle if Right: false (boolean response) resolve(parsedBody.Right); } else if (has(parsedBody, 'Left')) { // "Left" means error case -> return error with contents (exception on nextUpdate) if (parsedBody.Left.contents) { reject(new Error(parsedBody.Left.contents)); } else { reject(new Error('Unknown response from backend.')); } } else { // TODO: investigate if that can happen! (no Right or Left in a response) reject(new Error('Unknown response from backend.')); } } catch (error) { // Handle internal server errors (e.g. HTTP 500 - 'Something went wrong') reject(new Error(error)); } }); }); httpsRequest.on('error', (error) => reject(error)); httpsRequest.end(); }); } export const request = typedRequest;
JavaScript
0.000005
@@ -1703,16 +1703,43 @@ ength': +(new TextEncoder()).encode( requestB @@ -1741,16 +1741,17 @@ uestBody +) .length,
fea04292268128f464a9bf24a1b1a33be5f58ded
Correct month value used in generated file names, e.g. migrations
Alloy/commands/generate/generateUtils.js
Alloy/commands/generate/generateUtils.js
var basePath = '../../'; var path = require('path'), fs = require('fs'), wrench = require('wrench'), xml2tss = require('xml2tss'), alloyRoot = path.join(__dirname,'..','..'), _ = require(basePath + 'lib/alloy/underscore')._, U = require(basePath + 'utils'), CONST = require(basePath + 'common/constants'), logger = require(basePath + 'logger'); function pad(x) { if (x < 10) { return '0' + x; } return x; } exports.generateMigrationFileName = function(t) { var d = new Date(); var s = String(d.getUTCFullYear()) + String(pad(d.getUTCMonth())) + String(pad(d.getUTCDate())) + String(pad(d.getUTCHours())) + String(pad(d.getUTCMinutes())) + String(d.getUTCMilliseconds()); return s + '_' + t; }; exports.generate = function(name, type, program, args) { args = args || {}; var ext = '.'+CONST.FILE_EXT[type]; var paths = U.getAndValidateProjectPaths(program.outputPath); var templatePath = path.join(alloyRoot,'template',type.toLowerCase()+ext); // ALOY-372 - Support 'alloy generate' command for widget components var widgetPath = (program.widgetname) ? CONST.DIR['WIDGET']+path.sep+program.widgetname : ''; if(widgetPath && !fs.existsSync(path.join(paths.app,widgetPath))) { U.die('No widget named ' + program.widgetname + ' in this project.'); } var dir = path.join(paths.app,widgetPath,CONST.DIR[type]); // add the platform-specific folder to the path, if necessary if (program.platform) { if (_.contains(['VIEW','CONTROLLER','STYLE'],type)) { dir = path.join(dir,program.platform); } else { logger.warn('platform "' + program.platform + '" ignored, not used with type "' + type + '"'); } } // get the final file name var file = path.join(dir,name + ext); var viewFile = path.join(paths.app, CONST.DIR['VIEW'], name + "." + CONST.FILE_EXT['VIEW']); // see if the file already exists if (fs.existsSync(file) && !program.force && !(type === "STYLE" && fs.existsSync(viewFile))) { U.die(" file already exists: " + file); } // make sure the target folder exists var fullDir = path.dirname(file); if (!fs.existsSync(fullDir)) { wrench.mkdirSyncRecursive(fullDir); } // only use xml2tss to generate style if the partner view exists if (type === "STYLE" && fs.existsSync(viewFile)) { xml2tss.updateFile(viewFile, file, function(err,ok) { if (ok) { logger.info('Generated style named ' + name); } else { logger.warn('Style named ' + name + ' already up-to-date'); } }); } else { // write the file out based on the given template var templateContents = fs.readFileSync(templatePath,'utf8'); if (args.templateFunc) { templateContents = args.templateFunc(templateContents); } var code = _.template(templateContents, args.template || {}); fs.writeFileSync(file, code); return { file: file, dir: fullDir, code: code }; } };
JavaScript
0
@@ -550,16 +550,20 @@ CMonth() + + 1 )) +%0A%09%09S
46c81397791113bc7f89464a59a693c5058763a6
Fix bug for currency value formatter assuming 2 decimal places.
js/Formatter.js
js/Formatter.js
/** * Class Humble Formatter * * Helper class to format values. */ Humble( function () { // Class Constants var BILLION = 1000000000, TRILLION = 1000000000000; // Constructor var Formatter = function () { } // Methods Formatter.prototype = { currencyNumeric : function (value) { value = Math.round(value * 100); return (value !== 0) ? value / 100 : value; }, currency : function (value, large) { if (value > BILLION && large) { return this.currencyHuge(value); } if (value != 0) { value = value.toString(); valueParts = value.split('.'); if (!large) { if (!valueParts[1]) { value = value+'.00'; } else if (valueParts[1].length < 2) { value = value+'0'; } } else { value = valueParts[0]; value = this.addCommas(value); } } return '$'+value; }, currencyHuge : function (value) { if (value > TRILLION) { value = value / TRILLION; if (value < 10) { value = Math.round(value * 10) / 10; } else { value = Math.round(value); } value = '$' + value.toString() + ' Trillion' } else if (value > BILLION) { value = value / BILLION; if (value < 10) { value = Math.round(value * 10) / 10; } else { value = Math.round(value); } value = '$' + value.toString() + ' Billion' } return value; }, addCommas : function (value) { value = value.toString(); value = this.reverse(value); value = value.split(/(\d{3})/); value = _.reject(value, function (item) { return (item === ""); }); value = value.join(','); value = this.reverse(value); return value; }, reverse : function (value) { value = value.toString(); return value.split('').reverse().join(''); } } // Namespace Hook Humble.Formatter = Formatter; });
JavaScript
0.000001
@@ -487,24 +487,74 @@ , large) %7B%0A%0A + value = this.currencyNumeric(value);%0A%0A
4b6e682ca18c8cdc0655c3420f1dd64fc310e16b
add to search -> filter search
public/javascripts/ui/metadata/entity_dialog.js
public/javascripts/ui/metadata/entity_dialog.js
dc.ui.EntityDialog = dc.ui.Dialog.extend({ callbacks : { '.ok.click': 'close', '.add_to_search.click': 'addToSearch' }, constructor : function(entity) { _.bindAll(this, '_openDocument'); this.model = entity; this.base({ mode : 'custom', title : this.model.displayTitle(), className : 'dialog entity_view custom_dialog' }); }, render : function() { this.base(); var instances = this.model.selectedInstances(); $('.custom', this.el).html(JST.entity_dialog({entity : this.model, instances : instances})); $('.controls', this.el).append($.el('button', {'class' : 'add_to_search'}, 'add to search')); var list = $('.document_list', this.el); var instances = _.sortBy(instances, function(inst) { return -inst.relevance; }); _.each(instances, _.bind(function(inst) { var doc = Documents.get(inst.document_id); var view = (new dc.ui.Document({model : doc, noCallbacks : true})).render(); $('.source', view.el).html('Relevance to document: ' + inst.relevance); $(view.el).click(_.bind(this._openDocument, this, inst, doc)); list.append(view.el); }, this)); this.center(); this.setCallbacks(); return this; }, addToSearch : function() { dc.app.searchBox.addToSearch(this.model.toSearchQuery()); this.close(); }, _openDocument : function(instance, doc) { window.open(doc.get('document_viewer_url') + "?entity=" + instance.id); } });
JavaScript
0
@@ -96,22 +96,22 @@ ,%0A '. -add_to +filter _search. @@ -119,21 +119,22 @@ lick': ' -addTo +filter Search'%0A @@ -649,14 +649,14 @@ : ' -add_to +filter _sea @@ -667,14 +667,14 @@ %7D, ' -add to +filter sea @@ -1258,21 +1258,22 @@ %7D,%0A%0A -addTo +filter Search :
936068d4f81b5711b5cb952deac4893d7a4698d2
Remove unnecessary abs(), see https://github.com/phetsims/scenery-phet/issues/432
js/GaugeNode.js
js/GaugeNode.js
// Copyright 2013-2019, University of Colorado Boulder /** * GaugeNode is a circular gauge that depicts some dynamic value. * This was originally ported from the speedometer node in forces-and-motion-basics. * * @author Sam Reid (PhET Interactive Simulations) * @author John Blanco (PhET Interactive Simulations) */ define( function( require ) { 'use strict'; // modules var Circle = require( 'SCENERY/nodes/Circle' ); var inherit = require( 'PHET_CORE/inherit' ); var Matrix3 = require( 'DOT/Matrix3' ); var Node = require( 'SCENERY/nodes/Node' ); var Path = require( 'SCENERY/nodes/Path' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var Property = require( 'AXON/Property' ); var Range = require( 'DOT/Range' ); var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); var Shape = require( 'KITE/Shape' ); var Tandem = require( 'TANDEM/Tandem' ); var Text = require( 'SCENERY/nodes/Text' ); var Util = require( 'DOT/Util' ); /** * @param {Property.<number>} valueProperty - the portrayed value * @param {string} label - label to display (scaled to fit if necessary) * @param {Range} range * @param {Object} [options] * @constructor */ function GaugeNode( valueProperty, label, range, options ) { options = _.extend( { // Defaults radius: 100, backgroundFill: 'white', backgroundStroke: 'rgb( 85, 85, 85 )', backgroundLineWidth: 2, maxLabelWidthScale: 1.3, // {number} defines max width of the label, relative to the radius // 10 ticks each on the right side and left side, plus one in the center numberOfTicks: 21, // the top half of the gauge, plus PI/8 extended below the top half on each side span: Math.PI + Math.PI / 4, // {number} the visible span of the gauge value range, in radians majorTickLength: 10, minorTickLength: 5, majorTickLineWidth: 2, minorTickLineWidth: 1, // Determines whether the gauge will be updated when the value changes. // Use this to (for example) disable updates while a gauge is not visible. updateEnabledProperty: new Property( true ), tandem: Tandem.required }, options ); assert && assert( range instanceof Range, 'range must be of type Range: ' + range ); assert && assert( options.span <= 2 * Math.PI, 'options.span must be <= 2 * Math.PI: ' + options.span ); Node.call( this ); // @public (read-only) {number} this.radius = options.radius; var anglePerTick = options.span / options.numberOfTicks; var tandem = options.tandem; this.addChild( new Circle( this.radius, { fill: options.backgroundFill, stroke: options.backgroundStroke, lineWidth: options.backgroundLineWidth } ) ); var foregroundNode = new Node( { pickable: false, tandem: tandem.createTandem( 'foregroundNode' ) } ); this.addChild( foregroundNode ); var needle = new Path( Shape.lineSegment( 0, 0, this.radius, 0 ), { stroke: 'red', lineWidth: 3 } ); foregroundNode.addChild( needle ); var labelNode = new Text( label, { font: new PhetFont( 20 ), maxWidth: this.radius * options.maxLabelWidthScale, tandem: tandem.createTandem( 'labelNode' ) } ).mutate( { centerX: 0, centerY: -this.radius / 3 } ); foregroundNode.addChild( labelNode ); var pin = new Circle( 2, { fill: 'black' } ); foregroundNode.addChild( pin ); var totalAngle = ( options.numberOfTicks - 1 ) * anglePerTick; var startAngle = -1 / 2 * Math.PI - totalAngle / 2; var endAngle = startAngle + totalAngle; var scratchMatrix = new Matrix3(); var updateNeedle = function() { if ( options.updateEnabledProperty.get() ) { if ( typeof( valueProperty.get() ) === 'number' ) { assert && assert( valueProperty.get() >= 0, 'GaugeNode representing negative values indicates a logic error' ); needle.visible = true; var needleAngle = Util.linear( range.min, range.max, startAngle, endAngle, Math.abs( valueProperty.get() ) ); // 2d rotation, but reusing our matrix above needle.setMatrix( scratchMatrix.setToRotationZ( needleAngle ) ); } else { // Hide the needle if there is no value number value to portray. needle.visible = false; } } }; valueProperty.link( updateNeedle ); options.updateEnabledProperty.link( updateNeedle ); // Render all of the ticks into two layers (since they have different strokes) // see https://github.com/phetsims/energy-skate-park-basics/issues/208 var bigTicksShape = new Shape(); var smallTicksShape = new Shape(); // Add the tick marks for ( var i = 0; i < options.numberOfTicks; i++ ) { var tickAngle = i * anglePerTick + startAngle; var tickLength = i % 2 === 0 ? options.majorTickLength : options.minorTickLength; var x1 = ( this.radius - tickLength ) * Math.cos( tickAngle ); var y1 = ( this.radius - tickLength ) * Math.sin( tickAngle ); var x2 = this.radius * Math.cos( tickAngle ); var y2 = this.radius * Math.sin( tickAngle ); if ( i % 2 === 0 ) { bigTicksShape.moveTo( x1, y1 ); bigTicksShape.lineTo( x2, y2 ); } else { smallTicksShape.moveTo( x1, y1 ); smallTicksShape.lineTo( x2, y2 ); } } foregroundNode.addChild( new Path( bigTicksShape, { stroke: 'gray', lineWidth: options.majorTickLineWidth } ) ); foregroundNode.addChild( new Path( smallTicksShape, { stroke: 'gray', lineWidth: options.minorTickLineWidth } ) ); this.mutate( options ); // @private this.disposeGaugeNode = function() { if ( valueProperty.hasListener( updateNeedle ) ) { valueProperty.unlink( updateNeedle ); } if ( options.updateEnabledProperty.hasListener( updateNeedle ) ) { options.updateEnabledProperty.unlink( updateNeedle ); } }; } sceneryPhet.register( 'GaugeNode', GaugeNode ); return inherit( Node, GaugeNode, { // @public dispose: function() { this.disposeGaugeNode(); Node.prototype.dispose.call( this ); } } ); } );
JavaScript
0.000001
@@ -4051,18 +4051,8 @@ gle, - Math.abs( val @@ -4067,18 +4067,16 @@ ty.get() - ) );%0A%0A
4551ec29f044f2be0f82cf4eacfc558430397fe8
fix for issue #10
src/renderers/dom.js
src/renderers/dom.js
/** * A pathetically simple dom renderer */ Physics.renderer('dom', function( proto ){ // utility methods var thePrefix = {} ,tmpdiv = document.createElement("div") ,toTitleCase = function toTitleCase(str) { return str.replace(/(?:^|\s)\w/g, function(match) { return match.toUpperCase(); }); } // return the prefixed name for the specified css property ,pfx = function pfx(prop) { if (thePrefix[prop]){ return thePrefix[prop]; } var arrayOfPrefixes = ['Webkit', 'Moz', 'Ms', 'O'] ,name ; for (var i = 0, l = arrayOfPrefixes.length; i < l; ++i) { name = arrayOfPrefixes[i] + toTitleCase(prop); if (name in tmpdiv.style){ return thePrefix[prop] = name; } } if (name in tmpdiv.style){ return thePrefix[prop] = prop; } return false; } ; var classpfx = 'pjs-' ,px = 'px' ,cssTransform = pfx('transform') ; var newEl = function( node, content ){ var el = document.createElement(node || 'div'); if (content){ el.innerHTML = content; } return el; } ,drawBody ; // determine which drawBody method we can use if (cssTransform){ drawBody = function( body, view ){ var pos = body.state.pos; view.style[cssTransform] = 'translate('+pos.get(0)+'px,'+pos.get(1)+'px) rotate('+body.state.angular.pos+'rad)'; }; } else { drawBody = function( body, view ){ var pos = body.state.pos; view.style.left = pos.get(0) + px; view.style.top = pos.get(1) + px; }; } return { /** * Initialization * @param {Object} options Config options passed by initializer * @return {void} */ init: function( options ){ // call proto init proto.init.call(this, options); var viewport = this.el; viewport.style.position = 'relative'; viewport.style.overflow = 'hidden'; viewport.style.width = this.options.width + px; viewport.style.height = this.options.height + px; this.els = {}; if (options.meta){ var stats = newEl(); stats.className = 'pjs-meta'; this.els.fps = newEl('span'); this.els.ipf = newEl('span'); stats.appendChild(newEl('span', 'fps: ')); stats.appendChild(this.els.fps); stats.appendChild(newEl('br')); stats.appendChild(newEl('span', 'ipf: ')); stats.appendChild(this.els.ipf); viewport.appendChild(stats); } }, /** * Set dom element style properties for a circle * @param {HTMLElement} el The element * @param {Geometry} geometry The bodie's geometry * @return {void} */ circleProperties: function( el, geometry ){ var aabb = geometry.aabb(); el.style.width = (aabb.halfWidth * 2) + px; el.style.height = (aabb.halfHeight * 2) + px; el.style.marginLeft = (-aabb.halfWidth) + px; el.style.marginTop = (-aabb.halfHeight) + px; }, /** * Create a dom element for the specified geometry * @param {Geometry} geometry The bodie's geometry * @return {HTMLElement} The element */ createView: function( geometry ){ var el = newEl() ,fn = geometry.name + 'Properties' ; el.className = classpfx + geometry.name; el.style.position = 'absolute'; el.style.top = '0px'; el.style.left = '0px'; if (this[ fn ]){ this[ fn ](el, geometry); } this.el.appendChild( el ); return el; }, /** * Draw the meta data * @param {Object} meta The meta data * @return {void} */ drawMeta: function( meta ){ this.els.fps.innerHTML = meta.fps.toFixed(2); this.els.ipf.innerHTML = meta.ipf; }, /** * Update dom element to reflect bodie's current state * @param {Body} body The body to draw * @param {HTMLElement} view The view for that body * @return {void} */ drawBody: drawBody }; });
JavaScript
0
@@ -2317,16 +2317,95 @@ idden';%0A + viewport.style%5BcssTransform%5D = 'translateZ(0)'; // force GPU accel%0A
34c801549bc297067cf6175eeb8a7bac7b07f83b
Change temporal ordering of add and remove
src/Groups/allcadets.js
src/Groups/allcadets.js
//MongoDB scrip to Update allcadets group //This should really be replaced by a new Class in mims.py //History: // 19Aug19 MEG Created. var db = db.getSiblingDB( 'NHWG'); // Google Group of intereste var baseGroupName = 'allcadets'; var googleGroup = baseGroupName + '@nhwg.cap.gov'; var groupsCollection = 'GoogleGroups'; // Member type of interest var memberType = 'CADET'; // import date math functions load( db.ENV.findOne( {name:'DATEFNS'} ).value ); // look past 30 days expired members after this remove member from group. var lookbackdate = dateFns.subDays( new Date(), 30 ); // Aggregation pipeline find all ACTIVE members PRIMARY EMAIL addresses. var memberPipeline = // Pipeline [ // Stage 1 { $match: { CAPID: { $gt: NumberInt(100000)}, Type: memberType, MbrStatus:"ACTIVE", } }, // Stage 2 { $lookup: // Equality Match { from: "MbrContact", localField: "CAPID", foreignField: "CAPID", as: "Contacts" } }, // Stage 3 { $unwind: { path : "$Contacts", preserveNullAndEmptyArrays : false } }, // Stage 4 { $match: { "Contacts.Priority": "PRIMARY", "Contacts.Type": "EMAIL", } }, // Stage 5 { $unwind: { path : "$Contacts", preserveNullAndEmptyArrays : false } }, // Stage 6 { $project: { // specifications CAPID:1, NameLast:1, NameFirst:1, NameSuffix:1, "email": "$Contacts.Contact", } }, ]; // Aggregate a list of all emails for the Google group of interest var groupMemberPipeline = [ { "$match" : { "group" : googleGroup } }, { "$project" : { "Email" : "$email" } } ]; // pipeline options var options = { "allowDiskUse" : false }; function isActiveMember( capid ) { // Check to see if member is active. // This function needs to be changed for each group depending // on what constitutes "active". var m = db.getCollection( "Member").findOne( { "CAPID": capid, "MbrStatus": "ACTIVE" } ); if ( m == null ) { return false; } return true; } function isGroupMember( group, email ) { // Check if email is already in the group var email = email.toLowerCase(); var rx = new RegExp( email, 'i' ); return db.getCollection( groupsCollection ).findOne( { 'group': group, 'email': rx } ); } function addMembers( collection, pipeline, options, group ) { // Scans looking for active members // if member is not currently on the mailing list generate gam command to add member. var cursor = db.getCollection( collection ).aggregate( pipeline, options ); while ( cursor.hasNext() ) { var m = cursor.next(); if ( ! isActiveMember( m.CAPID ) ) { continue; } if ( isGroupMember( googleGroup, m.email ) ) { continue; } // Print gam command to add new member print("gam update group", googleGroup, "add member", m.email ); } } function removeMembers( collection, pipeline, options, group ) { // for each member of the group // check active status, if not generate a gam command to remove member. var m = db.getCollection( collection ).aggregate( pipeline, options ); while ( m.hasNext() ) { var e = m.next().Email; var rgx = new RegExp( e, "i" ); var r = db.getCollection( 'MbrContact' ).findOne( { Type: 'EMAIL', Priority: 'PRIMARY', Contact: rgx } ); if ( r ) { var a = db.getCollection( 'Member' ).findOne( { CAPID: r.CAPID, Type: memberType } ); if ( a == null || isActiveMember( r.CAPID ) ) { continue; } if ( a.Expiration < lookbackdate ) { print( '#INFO:', a.CAPID, a.NameLast, a.NameFirst, a.NameSuffix, 'Expiration:', a.Expiration ); print( 'gam update group', googleGroup, 'delete member', e ); } } else { print( '#INFO: Unknown email:', e, 'removed' ); print( 'gam update group', googleGroup, 'delete member', e ); } } } // Main here print("# Update group:", googleGroup ); print("# Add new members"); addMembers( "Member", memberPipeline, options, googleGroup ); print( "# Remove inactive members") ; removeMembers( groupsCollection, groupMemberPipeline, options, googleGroup );
JavaScript
0
@@ -105,16 +105,95 @@ istory:%0A +// 18Nov19 MEG Change temporal ordering of add and remove to fix Google issue.%0A // 19Aug @@ -4262,16 +4262,126 @@ in here%0A +// Do NOT change the temporal order or remove and add operations.%0A// Google plays games with %22.%22 in user id's%0A print(%22# @@ -4422,18 +4422,27 @@ int( + %22# -Add new +Remove inactive mem @@ -4451,13 +4451,17 @@ rs%22) + ;%0A -add +remove Memb @@ -4469,19 +4469,32 @@ rs( -%22Member%22, m +groupsCollection, groupM embe @@ -4534,35 +4534,26 @@ ;%0Aprint( - %22# -Remove inactive +Add new members @@ -4550,33 +4550,29 @@ ew members%22) - ;%0A -remove +add Members( gro @@ -4572,32 +4572,19 @@ rs( -groupsCollection, groupM +%22Member%22, m embe
cacf36e84924a189e3e1add89e6a6fc9e18e8d5c
move jsdoc cleanup
js/GaugeNode.js
js/GaugeNode.js
// Copyright 2013-2016, University of Colorado Boulder /** * The gauge node is a scenery node that represents a circular gauge that * depicts some dynamic value. This was originally ported from the * speedometer node in forces-and-motion-basics. * * @author Sam Reid * @author John Blanco */ define( function( require ) { 'use strict'; // modules var Circle = require( 'SCENERY/nodes/Circle' ); var Node = require( 'SCENERY/nodes/Node' ); var Text = require( 'SCENERY/nodes/Text' ); var Path = require( 'SCENERY/nodes/Path' ); var Shape = require( 'KITE/Shape' ); var Matrix3 = require( 'DOT/Matrix3' ); var inherit = require( 'PHET_CORE/inherit' ); var Util = require( 'DOT/Util' ); var PhetFont = require( 'SCENERY_PHET/PhetFont' ); var Property = require( 'AXON/Property' ); var sceneryPhet = require( 'SCENERY_PHET/sceneryPhet' ); /** * @param {Property.<number>} valueProperty which is portrayed * @param {Object} [options] typical Node layout and display options * @param {string} label label to display (scaled to fit if necessary) * @param {Object} range contains min and max values that define the range * @constructor */ function GaugeNode( valueProperty, label, range, options ) { Node.call( this ); options = _.extend( { // Defaults radius: 67, backgroundFill: 'white', backgroundStroke: 'rgb( 85, 85, 85 )', backgroundLineWidth: 2, anglePerTick: Math.PI * 2 / 4 / 8, // 8 ticks goes to 9 o'clock (on the left side), and two more ticks appear below that mark. // The ticks are duplicated for the right side, and one tick appears in the middle at the top numTicks: ( 8 + 2 ) * 2 + 1, // Determines whether the gauge will be updated when the value changes. // Use this to (for example) disable updates while a gauge is not visible. updateEnabledProperty: new Property( true ) }, options ); this.addChild( new Circle( options.radius, { fill: options.backgroundFill, stroke: options.backgroundStroke, lineWidth: options.backgroundLineWidth } ) ); var foregroundNode = new Node( { pickable: false } ); this.addChild( foregroundNode ); var needle = new Path( Shape.lineSegment( 0, 0, options.radius, 0 ), { stroke: 'red', lineWidth: 3 } ); foregroundNode.addChild( needle ); var labelNode = new Text( label, { font: new PhetFont( 20 ), maxWidth: options.radius * 1.3 } ).mutate( { centerX: 0, centerY: -options.radius / 3 } ); foregroundNode.addChild( labelNode ); var pin = new Circle( 2, { fill: 'black' } ); foregroundNode.addChild( pin ); var totalAngle = (options.numTicks - 1) * options.anglePerTick; var startAngle = -1 / 2 * Math.PI - totalAngle / 2; var endAngle = startAngle + totalAngle; var scratchMatrix = new Matrix3(); var updateNeedle = function() { if ( options.updateEnabledProperty.get() ) { if ( typeof( valueProperty.get() ) === 'number' ) { needle.visible = true; var needleAngle = Util.linear( range.min, range.max, startAngle, endAngle, Math.abs( valueProperty.get() ) ); // 2d rotation, but reusing our matrix above needle.setMatrix( scratchMatrix.setToRotationZ( needleAngle ) ); } else { // Hide the needle if there is no value number value to portray. needle.visible = false; } } }; var valueObserver = function( value ) { updateNeedle(); }; valueProperty.link( valueObserver ); var updateEnabledObserver = function( updateEnabled ) { updateNeedle(); }; options.updateEnabledProperty.link( updateEnabledObserver ); // Render all of the ticks into two layers (since they have different strokes) // see https://github.com/phetsims/energy-skate-park-basics/issues/208 var bigTicksShape = new Shape(); var smallTicksShape = new Shape(); // Add the tick marks for ( var i = 0; i < options.numTicks; i++ ) { var tickAngle = i * options.anglePerTick + startAngle; var tickLength = i % 2 === 0 ? 10 : 5; var x1 = (options.radius - tickLength) * Math.cos( tickAngle ); var y1 = (options.radius - tickLength) * Math.sin( tickAngle ); var x2 = options.radius * Math.cos( tickAngle ); var y2 = options.radius * Math.sin( tickAngle ); if ( i % 2 === 0 ) { bigTicksShape.moveTo( x1, y1 ); bigTicksShape.lineTo( x2, y2 ); } else { smallTicksShape.moveTo( x1, y1 ); smallTicksShape.lineTo( x2, y2 ); } } foregroundNode.addChild( new Path( bigTicksShape, { stroke: 'gray', lineWidth: 2 } ) ); foregroundNode.addChild( new Path( smallTicksShape, { stroke: 'gray', lineWidth: 1 } ) ); this.mutate( options ); // @private this.disposeGaugeNode = function() { valueProperty.unlink( valueObserver ); options.updateEnabledProperty.unlink( updateEnabledObserver ); }; } sceneryPhet.register( 'GaugeNode', GaugeNode ); return inherit( Node, GaugeNode, { // @public dispose: function() { this.disposeGaugeNode(); } } ); } );
JavaScript
0
@@ -940,79 +940,8 @@ yed%0A - * @param %7BObject%7D %5Boptions%5D typical Node layout and display options%0A * @@ -1086,16 +1086,47 @@ e range%0A + * @param %7BObject%7D %5Boptions%5D%0A * @co
791e7ee645282b7ef9ab430bbbd03ba5e9fbae74
update deprecated rule wrap-multilines
rules/react.js
rules/react.js
module.exports = { 'env': { 'browser': true }, 'plugins': ['react'], 'ecmaFeatures': { 'jsx': true }, 'rules': { // Enforce boolean attributes notation in JSX 'react/jsx-boolean-value': 2, // Disallow undeclared variables in JSX 'react/jsx-no-undef': 2, // Prevent React to be incorrectly marked as unused 'react/jsx-uses-react': 2, // Prevent variables used in JSX to be incorrectly marked as unused 'react/jsx-uses-vars': 2, // Prevent usage of setState in componentDidMount 'react/no-did-mount-set-state': 2, // Prevent usage of setState in componentDidUpdate 'react/no-did-update-set-state': 2, // Prevent usage of unknown DOM property 'react/no-unknown-property': 2, // Prevent missing props validation in a React component definition 'react/prop-types': 2, // Prevent missing React when using JSX 'react/react-in-jsx-scope': 2, // Prevent missing parentheses around multilines JSX 'react/wrap-multilines': 2, // specify whether double or single quotes should be used in JSX attributes 'jsx-quotes': 2 } };
JavaScript
0
@@ -987,16 +987,20 @@ 'react/ +jsx- wrap-mul
a4f831e0dcca6d46384dea97ecfcf321e7844425
Refactor base price validation.
src/MarkupCalculator.js
src/MarkupCalculator.js
function MarkupCalculator () { // Predefined flat markup on all jobs this.flatMarkup = 0.05; // Predefined markup per person on a job this.peopleMarkup = 0.012; // Predefined markup for specific categories this.categoryMarkupsMap = { drugs: 0.075, food: 0.13, electronics: 0.02 }; } /** * Calculate cost of a packaging job * @param {object} options: * basePrice {float} - defaults to 0 * people {integer} - defaults to 1 * category {string} - optional * */ MarkupCalculator.prototype.calculate = function (options) { var basePrice = options.basePrice || 0, people = options.people || 1, category = options.category, basePlusFlat = 0, total = 0; if (basePrice < 0) { throw new Error("invalid base price"); } basePlusFlat = basePrice + this.calculateFlatMarkup(basePrice); total += basePlusFlat; total += this.calculatePeopleMarkup(basePlusFlat, people); total += this.calculateCategoryMarkup(basePlusFlat, category); return roundToTwoDecimalPlaces(total); }; /** * Calculate flat markup price based on base price * @param {integer} basePrice */ MarkupCalculator.prototype.calculateFlatMarkup = function (basePrice) { return basePrice * this.flatMarkup; }; /** * Calculate people markup price based on (base price + flat markup) * and number of people * @param {float} basePlusFlat * @param {integer} people */ MarkupCalculator.prototype.calculatePeopleMarkup = function (basePlusFlat, people) { if (people < 1) { throw new Error("invalid people number"); } return basePlusFlat * (people * this.peopleMarkup); }; /** * Calculate category markup price based on (base price + flat markup) * and category type * @param {float} basePlusFlat * @param {string} category */ MarkupCalculator.prototype.calculateCategoryMarkup = function (basePlusFlat, category) { var markup = this.categoryMarkupsMap[category] || 0; return basePlusFlat * markup; }; /** * Round a number to two decimal places. * @param {float} number */ function roundToTwoDecimalPlaces (number) { return parseFloat(number.toFixed(2)); }
JavaScript
0
@@ -493,17 +493,43 @@ ional%0A * + @return %7Bfloat%7Cinteger%7D %0A - */%0AMark @@ -745,77 +745,38 @@ %0A%0A -if (basePrice %3C 0) %7B%0A throw new Error(%22invalid +validateBasePrice( base - p +P rice -%22 );%0A - %7D%0A%0A ba @@ -1121,16 +1121,45 @@ sePrice%0A + * @return %7Bfloat%7Cinteger%7D%0A */%0AMark @@ -1427,16 +1427,45 @@ people%0A + * @return %7Bfloat%7Cinteger%7D%0A */%0AMark @@ -1834,16 +1834,45 @@ ategory%0A + * @return %7Bfloat%7Cinteger%7D%0A */%0AMark @@ -2045,24 +2045,229 @@ arkup;%0A%7D;%0A%0A%0A +%0A/**%0A * Validate base price is a positive float or zero%0A * @param %7Bfloat%7D basePrice%0A */%0Afunction validateBasePrice (basePrice) %7B%0A if (basePrice %3C 0) %7B%0A throw new Error(%22invalid base price%22);%0A %7D%0A%7D%0A%0A%0A /**%0A * Round @@ -2297,17 +2297,16 @@ l places -. %0A * @p @@ -2325,16 +2325,45 @@ number%0A + * @return %7Bfloat%7Cinteger%7D%0A */%0Afunc
949b2da531894322df6733e9249f012b150fe29c
delete javascript variable to avoid memory issues
js/mpdplayer.js
js/mpdplayer.js
var pollInterval = null; // do we need this in window scope? $(document).ready(function(){ nowPlayingSongId = 0; pollMpdData(); $('body').on('click', '.mpd-ctrl-seekbar', function(e){ // TODO: how to respect parents padding (15px) on absolute positioned div with width 100% ? var percent = Math.round((e.pageX - $(this).offset().left) / (($(this).width()+15)/100)); $.ajax({ url: '/mpdctrl/seekPercent/' + percent }).done(function(response){ refreshInterval(); }); $('.mpd-status-progressbar').css('width', 'calc('+ percent+'% - 15px)'); }); }); function refreshInterval() { clearInterval(pollInterval); pollMpdData(); } // IMPORTANT TODO: how to avoid growing memory consumption on those frequent poll-requests? function pollMpdData(){ $.get('/mpdstatus', function(data) { data = JSON.parse(data); ['repeat', 'random', 'consume'].forEach(function(prop) { if(data[prop] == '1') { $('.mpd-status-'+prop).addClass('active'); } else { $('.mpd-status-'+prop).removeClass('active'); } }); if(data.state == 'play') { $('.mpd-status-playpause').addClass('fa-pause'); $('.mpd-status-playpause').removeClass('fa-play'); } else { $('.mpd-status-playpause').removeClass('fa-pause'); $('.mpd-status-playpause').addClass('fa-play'); } $('.mpd-status-elapsed').text(formatTime(data.elapsed)); $('.mpd-status-total').text(formatTime(data.duration)); // TODO: simulate seamless progressbar-growth and seamless secondscounter // TODO: how to respect parents padding on absolute positioned div with width 100% ? $('.mpd-status-progressbar').css('width', 'calc('+ data.percent+'% - 15px)'); // TODO: is this the right place for trigger local-player-favicon-update? - for now it is convenient to use this existing interval... drawFavicon(data.percent, data.state); // update trackinfo only onTrackChange() if(nowPlayingSongId != data.songid) { nowPlayingSongId = data.songid; $.ajax({ url: '/markup/mpdplayer' }).done(function(response){ //console.log(response); $('.player-mpd').html(response); }); } pollInterval = setTimeout(pollMpdData, 2000); }); }
JavaScript
0
@@ -1083,16 +1083,227 @@ %09%7D);%0A%09%09%0A +%09%09%0A%09%09// TODO: find out why this snippet does not work%0A%09%09//if(data.state !== 'play' && $('.mpd-status-playpause').hasClass('fa-pause')) %7B%0A%09%09//%09$('.mpd-status-playpause').toggleClass('fa-pause fa-play');%0A%09%09//%7D%0A%09%09%0A %09%09if(dat @@ -2440,24 +2440,36 @@ %09%7D%0A %09 +delete data; %0A pol
28de5eae538d5eaad52268bfbe3a4112af96bb5a
Use expanding buffer for subsaga result channel (#7421)
shared/actions/engine/helper.js
shared/actions/engine/helper.js
// @flow // Handles sending requests to the daemon import * as Creators from './creators' import {mapValues} from 'lodash' import {RPCTimeoutError} from '../../util/errors' import engine, {EngineChannel} from '../../engine' import * as Saga from '../../util/saga' import {channel, delay} from 'redux-saga' import {call, put, cancelled, fork, join, take, cancel} from 'redux-saga/effects' import * as SagaTypes from '../../constants/types/saga' import * as FluxTypes from '../../constants/types/flux' // If a sub saga returns bail early, then the rpc will bail early const BailEarly = {type: '@@engineRPCCall:bailEarly'} const BailedEarly = {type: '@@engineRPCCall:bailedEarly', payload: undefined} const rpcResult = (args: any) => ({type: '@@engineRPCCall:respondResult', payload: args}) const rpcError = (args: any) => ({type: '@@engineRPCCall:respondError', payload: args}) const rpcCancel = (args: any) => ({type: '@@engineRPCCall:respondCancel', payload: args}) const _subSagaFinished = (args: any) => ({type: '@@engineRPCCall:subSagaFinished', payload: args}) const _isResult = ({type} = {}) => type === '@@engineRPCCall:respondResult' const _isError = ({type} = {}) => type === '@@engineRPCCall:respondError' const _isCancel = ({type} = {}) => type === '@@engineRPCCall:respondCancel' type Finished = FluxTypes.NoErrorTypedAction< '@@engineRPCCall:finished', { error: ?any, params: ?any, } > const finished = ({error, params}) => ({type: '@@engineRPCCall:finished', payload: {error, params}}) const isFinished = (a: any) => a.type === '@@engineRPCCall:finished' type RpcRunResult = Finished | FluxTypes.NoErrorTypedAction<'@@engineRPCCall:bailedEarly', void> function _sagaWaitingDecorator(rpcNameKey, saga) { return function*(...args: any) { yield put(Creators.waitingForRpc(rpcNameKey, false)) yield call(saga, ...args) yield put(Creators.waitingForRpc(rpcNameKey, true)) } } // This decorator deals with responding to the rpc function _handleRPCDecorator(rpcNameKey, saga) { return function*({params, response}) { const returnVal = yield call(saga, params) const payload = (returnVal || {}).payload if (_isResult(returnVal)) { yield call([response, response.result], payload) } else if (_isCancel(returnVal)) { const engineInst = yield call(engine) yield call([engineInst, engineInst.cancelRPC], response, payload) } else if (_isError(returnVal)) { yield call([response, response.error], payload) } else { throw new Error(`SubSaga for ${rpcNameKey} did not return a response to the rpc!`) } } } // This decorator to put the result on a channel function _putReturnOnChan(chan, saga) { return function*(...args: any) { const returnVal = yield call(saga, ...args) yield put(chan, _subSagaFinished(returnVal)) } } function passthroughResponseSaga() { return rpcResult() } class EngineRpcCall { _subSagas: SagaTypes.SagaMap _chanConfig: SagaTypes.ChannelConfig<*> _rpc: Function _rpcNameKey: string // Used for the waiting state and error messages. _request: any _subSagaChannel: SagaTypes.Channel<*> _engineChannel: EngineChannel _cleanedUp: boolean constructor(sagaMap: SagaTypes.SagaMap, rpc: any, rpcNameKey: string, request: any) { this._chanConfig = Saga.singleFixedChannelConfig(Object.keys(sagaMap)) this._rpcNameKey = rpcNameKey this._rpc = rpc this._cleanedUp = false this._request = request this._subSagaChannel = channel() // $FlowIssue with this this.run = this.run.bind(this) // In case we mess up and forget to do call([ctx, ctx.run]) const {finished: finishedSaga, ...subSagas} = sagaMap if (finishedSaga) { throw new Error( 'Passed in a finished saga that will never be used. Instead the result of .run() will give you finished' ) } const decoratedSubSagas = mapValues(subSagas, saga => _putReturnOnChan( this._subSagaChannel, _sagaWaitingDecorator(rpcNameKey, _handleRPCDecorator(rpcNameKey, saga)) ) ) this._subSagas = decoratedSubSagas } *_cleanup(subSagaTasks: Array<any>): Generator<any, any, any> { if (!this._cleanedUp) { this._cleanedUp = true // TODO(mm) should we respond to the pending rpc with error if we hit this? // Nojima and Marco think it's okay for now - maybe discuss with core what we should do. yield cancel(...subSagaTasks) this._engineChannel.close() this._subSagaChannel.close() yield put(Creators.waitingForRpc(this._rpcNameKey, false)) } else { console.error('Already cleaned up') } } *run(timeout: ?number): Generator<any, RpcRunResult, any> { this._engineChannel = yield call(this._rpc, [...Object.keys(this._subSagas), 'finished'], this._request) const subSagaTasks: Array<any> = [] while (true) { try { // Race against a subSaga task returning by taking on // We want to cancel that task if another message comes in // We also want to check to see if the last task tells us to bail early const incoming = yield call([this._engineChannel, this._engineChannel.race], { // If we have a task currently running, we don't want to race with the timeout timeout: subSagaTasks.filter(t => t.isRunning()).length ? undefined : timeout, racers: {subSagaFinished: take(this._subSagaChannel)}, }) if (incoming.timeout) { yield call([this, this._cleanup], subSagaTasks) throw new RPCTimeoutError(this._rpcNameKey, timeout) } if (incoming.finished) { // Wait for all the subSagas to finish yield join(...subSagaTasks) yield call([this, this._cleanup], subSagaTasks) const {error, params} = incoming.finished return finished({error, params}) } const raceWinner = Object.keys(incoming)[0] const result = incoming[raceWinner] if (raceWinner === 'subSagaFinished') { const result = incoming.subSagaFinished.payload if (_isCancel(result) || _isError(result)) { yield call([this, this._cleanup], subSagaTasks) return BailedEarly } else { // Put a delay(0) so a task that is just about finished will correctly return false for .isRunning() yield delay(0) continue } } if (!raceWinner) { throw new Error('Undefined race winner', raceWinner) } // Should be impossible if (!this._subSagas[raceWinner]) { throw new Error('No subSaga to handle the raceWinner', raceWinner) } // We could have multiple things told to us! const subSagaTask = yield fork(this._subSagas[raceWinner], result) subSagaTasks.push(subSagaTask) } finally { if (yield cancelled()) { yield call([this, this._cleanup], subSagaTasks) } } } // This is here to make flow happy // But it makes eslint sad, so let's tell disable eslint // eslint-disable-next-line return BailedEarly } } export { EngineRpcCall, isFinished, BailEarly, BailedEarly, rpcResult, rpcCancel, rpcError, passthroughResponseSaga, }
JavaScript
0
@@ -274,16 +274,25 @@ channel, + buffers, delay%7D @@ -3503,16 +3503,37 @@ channel( +buffers.expanding(10) )%0A //
9c13c74afdf7773c20eed7b2af7e83d9adccb584
remove script tags from analytics
js/analytics.js
js/analytics.js
<script> (function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){ (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o), m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m) })(window,document,'script','https://www.google-analytics.com/analytics.js','ga'); ga('create', 'UA-81316909-1', 'auto'); ga('send', 'pageview'); </script>
JavaScript
0.000001
@@ -1,13 +1,4 @@ -%3Cscript%3E%0A (f @@ -392,15 +392,4 @@ ');%0A -%0A%3C/script%3E%0A
27155d0bbc31ad7431478a5dedfaaeeecb8aee54
Add resetStyle method
leaflet-indoor.js
leaflet-indoor.js
/** * A layer that will display indoor data * * addData takes a GeoJSON feature collection, each feature must have a level * property that indicates the level. * * getLevels can be called to get the array of levels that are present. */ L.Indoor = L.Class.extend({ options: { getLevel: function(feature) { return feature.properties.level; } }, initialize: function(data, options) { L.setOptions(this, options); options = this.options; var layers = this._layers = {}; this._map = null; if ("level" in this.options) { this._level = this.options.level; } else { this._level = null; } if ("onEachFeature" in this.options) var onEachFeature = this.options.onEachFeature; this.options.onEachFeature = function(feature, layer) { if (onEachFeature) onEachFeature(feature, layer); if ("markerForFeature" in options) { var marker = options.markerForFeature(feature); if (typeof(marker) !== 'undefined') { marker.on('click', function(e) { layer.fire('click', e); }); var level = options.getLevel(feature); if (typeof(level) === 'undefined') { console.warn("level undefined for"); console.log(feature); } else { function addToLevel(level) { layers[level].addLayer(marker); } if (L.Util.isArray(level)) { level.forEach(addToLevel); } else { addToLevel(level); } } } } }; this.addData(data); }, addTo: function (map) { map.addLayer(this); return this; }, onAdd: function (map) { this._map = map; if (this._level === null) { var levels = this.getLevels(); if (levels.length !== 0) { this._level = levels[0]; } } if (this._level !== null) { if (this._level in this._layers) { this._map.addLayer(this._layers[this._level]); } } }, onRemove: function (map) { if (this._level in this._layers) { this._map.removeLayer(this._layers[this._level]); } this._map = null; }, addData: function(data) { var layers = this._layers; var options = this.options; var features = L.Util.isArray(data) ? data : data.features; features.forEach(function (part) { var level = options.getLevel(part); var layer; if (typeof level === 'undefined' || level === null) return; if (!("geometry" in part)) { return; } if (L.Util.isArray(level)) { level.forEach(function(level) { if (level in layers) { layer = layers[level]; } else { layer = layers[level] = L.geoJson({ type: "FeatureCollection", features: [] }, options); } layer.addData(part); }); } else { if (level in layers) { layer = layers[level]; } else { layer = layers[level] = L.geoJson({ type: "FeatureCollection", features: [] }, options); } layer.addData(part); } }); }, getLevels: function() { return Object.keys(this._layers); }, getLevel: function() { return this._level; }, setLevel: function(level) { if (typeof(level) === 'object') { level = level.newLevel; } if (this._level === level) return; var oldLayer = this._layers[this._level]; var layer = this._layers[level]; if (this._map !== null) { if (this._map.hasLayer(oldLayer)) { this._map.removeLayer(oldLayer); } if (layer) { this._map.addLayer(layer); } } this._level = level; } }); L.indoor = function(data, options) { return new L.Indoor(data, options); }; L.Control.Level = L.Control.extend({ includes: L.Mixin.Events, options: { position: 'bottomright', parseLevel: function(level) { return parseInt(level, 10); } }, initialize: function(options) { L.setOptions(this, options); this._map = null; this._buttons = {}; this._listeners = []; this._level = options.level; this.addEventListener("levelchange", this._levelChange, this); }, onAdd: function(map) { var div = L.DomUtil.create('div', 'leaflet-bar leaflet-control'); div.style.font = "18px 'Lucida Console',Monaco,monospace"; var buttons = this._buttons; var activeLevel = this._level; var self = this; var levels = []; for (var i=0; i<this.options.levels.length; i++) { var level = this.options.levels[i]; var levelNum = self.options.parseLevel(level); levels.push({ num: levelNum, label: level }); } levels.sort(function(a, b) { return a.num - b.num; }); for (i=levels.length-1; i>=0; i--) { var level = levels[i].num; var originalLevel = levels[i].label; var levelBtn = L.DomUtil.create('a', 'leaflet-button-part', div); if (level === activeLevel || originalLevel === activeLevel) { levelBtn.style.backgroundColor = "#b0b0b0"; } levelBtn.appendChild(levelBtn.ownerDocument.createTextNode(originalLevel)); (function(level) { levelBtn.onclick = function() { self.setLevel(level); }; })(level); buttons[level] = levelBtn; } return div; }, _levelChange: function(e) { if (this._map !== null) { if (typeof e.oldLevel !== "undefined") this._buttons[e.oldLevel].style.backgroundColor = "#FFFFFF"; this._buttons[e.newLevel].style.backgroundColor = "#b0b0b0"; } }, setLevel: function(level) { if (level === this._level) return; var oldLevel = this._level; this._level = level; this.fireEvent("levelchange", { oldLevel: oldLevel, newLevel: level }); }, getLevel: function() { return this._level; } }); L.Control.level = function (options) { return new L.Control.Level(options); };
JavaScript
0
@@ -4661,24 +4661,423 @@ el = level;%0A + %7D,%0A resetStyle: function (layer) %7B%0A // reset any custom styles%0A layer.options = layer.defaultOptions;%0A this._setLayerStyle(layer, this.options.style);%0A return this;%0A %7D,%0A _setLayerStyle: function (layer, style) %7B%0A if (typeof style === 'function') %7B%0A style = style(layer.feature);%0A %7D%0A if (layer.setStyle) %7B%0A layer.setStyle(style);%0A %7D%0A %7D%0A%7D);%0A%0AL
829cef894a40ed3acf50c6165a6d86893f447a49
update per linter
run/install.js
run/install.js
'use strict'; const spawnSync = require('child_process').spawnSync; const fs = require('fs-extra'); const path = require('path'); const yaml = require('js-yaml'); const fepperNpmPath = path.resolve('node_modules', 'fepper'); const excludesDir = path.resolve(fepperNpmPath, 'excludes'); const indexJs = path.resolve(fepperNpmPath, 'index.js'); const confFile = 'conf.yml'; const confFileSrc = path.resolve(excludesDir, confFile); if (!fs.existsSync(confFile)) { fs.copySync(confFileSrc, confFile); } const confUiFile = 'patternlab-config.json'; const confUiFileSrc = path.resolve(excludesDir, confUiFile); if (!fs.existsSync(confUiFile)) { fs.copySync(confUiFileSrc, confUiFile); } const prefFile = 'pref.yml'; const prefFileSrc = path.resolve(excludesDir, prefFile); if (!fs.existsSync(prefFile)) { fs.copySync(prefFileSrc, prefFile); } const argv = [indexJs, 'install']; const conf = {}; const spawnedObj = spawnSync('node', argv, {stdio: 'inherit'}); // Output to install.log. const installLog = 'install.log'; if (spawnedObj.stderr) { fs.appendFileSync(installLog, `${spawnedObj.stderr}\n`); } fs.appendFileSync(installLog, `Process exited with status ${spawnedObj.status}.\n`); // Only run ui:compile if source dir is populated. (A base install will have it be empty at this point.) const confUiStr = fs.readFileSync(confUiFile, 'utf8'); try { conf.ui = JSON.parse(confUiStr); } catch (err) { throw err; } const sourceDirContent = fs.readdirSync(conf.ui.paths.source.root); if (sourceDirContent.length) { spawnSync('node', [indexJs, 'ui:compile'], {stdio: 'inherit'}); }
JavaScript
0
@@ -127,41 +127,8 @@ h'); -%0Aconst yaml = require('js-yaml'); %0A%0Aco
63dda5fa0bb0bf74b652b30c32a8fbc421d979ff
Update copyright year
js/copyright.js
js/copyright.js
/** * Displays the current year automatically. */ function copyrightYear() { var d = new Date(); var y = d.getFullYear(); document.getElementById("copyright").innerHTML = '&copy; 2018 – ' + y; } copyrightYear();
JavaScript
0.000001
@@ -193,9 +193,9 @@ 201 -8 +5 %E2%80%93 '
5bca53c2a5eed301ebd6d1f5dc0d565dd2348fee
Update instructions for using mock data
pkg/packagekit/mock-updates.es6
pkg/packagekit/mock-updates.es6
/*jshint esversion: 6 */ /* * Mock "available updates" entries for interactively testing layout changes with large updates * To use it, import it in updates.jsx: * * import { injectMockUpdates } from "./mock-updates.es6"; * * and call it in loadUpdates()'s Finished: Handler: * * Finished: () => { * injectMockUpdates(updates); * let pkg_ids = Object.keys(updates); */ export function injectMockUpdates(updates) { // some security updates updates["security-one;2.3-4"] = { name: "security-one", version: "2.3-4", bug_urls: [], cve_urls: ["https://cve.example.com?name=CVE-2014-123456", "https://cve.example.com?name=CVE-2017-9999"], vendor_urls: ["https://access.redhat.com/security/updates/classification/#critical", "critical", "https://access.redhat.com/errata/RHSA-2000:0001", "https://access.redhat.com/errata/RHSA-2000:0002"], severity: 8, description: "This will wreck your data center!", }; updates["security-two;1-2+sec1"] = { name: "security-two", version: "1-2+sec1", bug_urls: [], cve_urls: ["https://cve.example.com?name=CVE-2014-54321"], vendor_urls: ["https://access.redhat.com/security/updates/classification/#bogus", "bogus", "https://access.redhat.com/security/updates/classification/#low", "low"], severity: 8, description: "Mostly Harmless", }; updates["security-three;5-2"] = { name: "security-three", version: "5-2", bug_urls: [], vendor_urls: ["https://access.redhat.com/security/updates/classification/#low", "low", "https://access.redhat.com/security/updates/classification/#important", "important"], severity: 8, description: "This update will make you sleep more peacefully.", }; // no vendor URLs, default severity updates["security-four;42"] = { name: "security-four", version: "42", cve_urls: ["https://cve.example.com?name=CVE-2014-54321"], vendor_urls: [], severity: 8, description: "Yet another weakness fixed.", }; // source with many binaries for (let i = 1; i < 50; ++i) { let name = `manypkgs${i}`; updates[name + ";1-1"] = { name: name, version: "1-1", bug_urls: [], cve_urls: [], severity: 4, description: "Make [everything](http://everything.example.com) *better*\n\n * more packages\n * more `bugs`\n * more fun!", markdown: true, }; } // long changelog updates["verbose;1-1"] = { name: "verbose", version: "1-1", bug_urls: [], cve_urls: [], severity: 6, description: ("Some longish explanation of some boring technical change. " + "This is total technobabble gibberish for layman users.\n\n").repeat(30) }; // many bug fixes var bugs = []; for (let i = 10000; i < 10025; ++i) bugs.push("http://bugzilla.example.com/" + i); updates["buggy;1-1"] = { name: "buggy", version: "1-1", bug_urls: bugs, cve_urls: [], severity: 6, description: "This is FUBAR", }; }
JavaScript
0
@@ -260,25 +260,20 @@ tes()'s -Finished: +then Handler @@ -289,18 +289,14 @@ -Finished: +.then( () =
191d6d842f2a1e5c3a90864a15e2663825d2d69b
fix type checks. sorry
level-packager.js
level-packager.js
const util = require('util') const levelup = require('levelup') function packager (leveldown) { function Level (location, options, callback) { if (util.isFunction(options)) callback = options if (!util.isObject(options)) options = {} options.db = leveldown return levelup(location, options, callback) } [ 'destroy', 'repair' ].forEach(function (m) { if (util.isFunction(leveldown[m])) { Level[m] = function (location, callback) { leveldown[m](location, callback || function () {}) } } }) return Level } module.exports = packager
JavaScript
0.9991
@@ -1,36 +1,4 @@ -const util = require('util')%0A cons @@ -122,32 +122,37 @@ if ( -util.isFunction(options) +typeof options === 'function' )%0A @@ -186,31 +186,55 @@ if ( -!util.isObject(options) +typeof options === 'object' && options !== null )%0A @@ -394,40 +394,43 @@ if ( -util.isFunction(leveldown%5Bm%5D)) %7B +typeof leveldown%5Bm%5D === 'function') %0A
036bdae641fdadc897c6fb8da2e36118094e258d
debug output
shaaaaa.js
shaaaaa.js
/** * shaaaaa.js * * Checks a domain for its certificate algorithm. * * Depends on openssl installed and accessible on the PATH. */ // used to call out to openssl var exec = require("child_process").exec; var fs = require('fs'); // loads root certs // yorkie's fork, includes signatureAlgorithm var x509 = require("x509"); var Shaaa = { // root cert bundle, loaded when this file is required roots: null, // load root bundle, parse each cert loadRoots: function() { Shaaa.roots = []; // store a fingerprint of each one var certs = fs.readFileSync("./ca-bundle.crt", "utf-8").split("\n\n"); for (var i=0; i<certs.length; i++) Shaaa.roots.push(x509.parseCert(certs[i]).fingerPrint); }, // takes x509-parsed cert, compares fingerprint isRoot: function(cert) { return (Shaaa.roots.indexOf(cert.fingerPrint) > -1); }, // fingerprints of SHA-1 intermediate certs with known SHA-2 replacements fingerprints: null, loadFingerprints: function() { Shaaa.fingerprints = JSON.parse(fs.readFileSync('./fingerprints.json', 'utf-8')).certificates; }, algorithms: [ // new gold standards "sha256", "sha224", "sha384", "sha512", "sha1", // common, but deprecated "md5", // old, broken "md2" // so old, so broken ], // given e.g. 'sha256WithRSAEncryption', return // {algorithm: 'sha256', raw: 'sha256WithRSAEncryption', good: true} algorithm: function(raw) { var raw_compare = raw.toLowerCase(); var answer; for (var i=0; i<Shaaa.algorithms.length; i++) { var algorithm = Shaaa.algorithms[i]; if (raw_compare.indexOf(algorithm) == 0) answer = algorithm; if (raw_compare == ("ecdsa-with-" + algorithm)) answer = algorithm; } if (!answer) answer = "unknown"; var good = ( (answer == "sha256") || (answer == "sha224") || (answer == "sha384") || (answer == "sha512") ); return {algorithm: answer, raw: raw, good: good}; }, certs: function(domain, callback, options) { if (!options) options = {}; // This accounts for -servername/SNI, which cannot have a port var server_name = domain.replace(/[^\w\.\-]|[$:\d+]/g, ''); // This accounts for -connect, which can have a port var server_connect = domain.replace(/[^\w\.\-:]/g, ''); // If the address does not have a port defined, add default :443 if (server_connect.match(/:\d+^/g) === null) { server_connect += ":443"; } // adapted from http://askubuntu.com/a/201923/3096 var command = "" + // piping into openssl tells it not to hold an open connection "echo -n" + // connect to given domain on port 443 " | openssl s_client -connect " + server_connect + // specify hostname in case server uses SNI " -servername " + server_name + // ask for the full cert chain " -showcerts"; if (options.verbose || options.debug) console.log(command + "\n"); exec(command, function(error, stdout, stderr) { if (error) return callback(error); // stdout is a long block of openssl output - grab the certs var certs = []; // using multiline workaround: http://stackoverflow.com/a/1068308/16075 var regex = /(\-+BEGIN CERTIFICATE\-+[\s\S]*?\-+END CERTIFICATE\-+)/g var match = regex.exec(stdout); while (match != null) { certs.push(match[1]); match = regex.exec(stdout); } callback(null, certs); }); }, sha2URL: function(fingerprint) { console.log(fingerprint); for (var i=0; i<Shaaa.fingerprints.length; i++) { if (Shaaa.fingerprints[i].sha1 == fingerprint) return Shaaa.fingerprints[i].url; } }, cert: function(text) { var cert = x509.parseCert(text); var answer = Shaaa.algorithm(cert.signatureAlgorithm); var root = Shaaa.isRoot(cert); var replacement = (root ? null : Shaaa.sha2URL(cert.fingerPrint)); return { algorithm: answer.algorithm, raw: answer.raw, good: (root || answer.good), root: root, replacement: replacement, expires: cert.notAfter, name: cert.subject.commonName }; }, /** * Desired output: * { * domain: shaaaaaaaaaaaaa.com, * cert: { * algorithm: 'sha256', * raw: 'sha256WithRSAEncryption', * good: true, * root: false, * replacement: null, * expires: Tue Aug 18 2015 19:59:59 GMT-0400 (EDT), * name: "www.konklone.com" * }, * intermediates: [ * { ... } // same form as above * ] * } */ from: function(domain, callback, options) { if (!options) options = {}; var data = {domain: domain}; Shaaa.certs(domain, function(error, certs) { if (error) return callback(error); data.cert = Shaaa.cert(certs[0]); data.intermediates = []; certs.slice(1).forEach(function(cert) { data.intermediates.push(Shaaa.cert(cert)); }); var intergood = true; for (var i=0; i<data.intermediates.length; i++) { if (!data.intermediates[i].good) { if (i == 0) { intergood = false; break; } } } if (data.cert.good && intergood) data.diagnosis = "good"; else if (data.cert.good && !intergood) data.diagnosis = "almost"; else data.diagnosis = "bad"; if (callback) callback(null, data); else console.log(data); }, options); } } // load roots and fingerprints on first require Shaaa.loadRoots(); Shaaa.loadFingerprints(); module.exports = Shaaa;
JavaScript
0.000011
@@ -3508,38 +3508,8 @@ ) %7B%0A - console.log(fingerprint);%0A
fb61f21ac25aae999065927ea368a8e90661aff8
make notification icon darker
GitHubWhiteNavBar.user.js
GitHubWhiteNavBar.user.js
// ==UserScript== // @name GitHub's Black Navbar to White // @namespace https://victorli.nl // @version 1.2 // @description Change GitHub's black navbar back to the original white // @author Victor Li // @match https://github.com/* // @match https://gist.github.com/* // @run-at document-start // @grant GM_addStyle // ==/UserScript== /*jshint multistr: true */ GM_addStyle('\ .Header {\ background-color: #f5f5f5;\ border-bottom: 1px solid #e5e5e5;\ }\ \ .HeaderNavlink {\ color: #555;\ }\ .HeaderNavlink:hover {\ color: #4078c0;\ }\ .header-logo-invertocat {\ color: #555;\ }\ .header-logo-invertocat:hover {\ color: #4078c0;\ }\ .header-logo-wordmark {\ color: #555;\ }\ .header-logo-wordmark:hover {\ color: #4078c0;\ }\ .HeaderNavlink:hover .dropdown-caret, .HeaderNavlink:focus .dropdown-caret {\ border-top-color: #4078c0;\ }\ .HeaderNavlink:hover .octicon-plus, .HeaderNavlink:focus .octicon-plus {\ border-top-color: #4078c0;\ }\ .HeaderNavlink:hover, .HeaderNavlink:focus {\ color: #4078c0;\ }\ .Header .header-search-wrapper {\ min-height: 0;\ font-size: 14px;\ color: #333;\ background-color: #fff;\ border: 1px solid #ddd;\ box-shadow: inset 0 1px 2px rgba(0,0,0,0.075);\ }\ .header-search-input::placeholder {\ color: #333;\ }\ .Header .header-search-input::placeholder {\ color: #999;\ }\ .Header .header-search-input::-webkit-input-placeholder {\ color: #999;\ }\ .Header .header-search-scope {\ font-size: 12px;\ line-height: 20px;\ color: #767676;\ border-right-color: #eee;\ }\ .Header .header-search-wrapper.focus .header-search-scope {\ color: #4078c0;\ border-right-color: #c6d7ec;\ }\ .notification-indicator .mail-status {\ border: 2px solid #f3f3f3;\ }\ ');
JavaScript
0
@@ -1742,16 +1742,63 @@ ec;%5C%0A%7D%5C%0A +.notification-indicator %7B%5C%0A%09 color: #555;%5C%0A%7D%5C%0A .notific
473c71ab5d11534753a81352629de0a99d8672d1
Check if localized field is already set, otherwise don't reset
lib/Contentful.js
lib/Contentful.js
/** * Contentful configuration and library */ const contentful = require('contentful'); const merge = require('deepmerge'); const flatten = (array) => { return array.reduce((a, b) => { return a.concat(Array.isArray(b) ? flatten(b) : b); }, []); }; class Contentful { /** * Constructor * @param {Object} config Configuration * @param {Array} locales Locales to check for * @return {void} */ constructor (config, locales) { const clientConfig = { space: config.space, accessToken: config.accessToken, host: config.host }; /** * Create a new client */ this.client = contentful.createClient(clientConfig); /** * Set the locales */ this.locales = locales; } /** * Get all entries of a specific type * @param {String} categoryId Content type id * @return {Promise} */ getEntries (categoryId) { return new Promise((fulfill, reject) => { this.client .getEntries({ content_type: categoryId, locale: '*' }) .then((entries) => { let data = entries.items.map((entry) => { let localizedEntries = []; delete entry.sys.space; delete entry.sys.contentType; if (!this.locales) { return merge(entry.sys, entry.fields); } // Generate entries for all locales this.locales.forEach((locale) => { let fields = this._getFieldsForLocale(entry.fields, locale); localizedEntries.push(merge(entry.sys, fields)); }); return localizedEntries; }); data = flatten(data); fulfill(data); }) .catch(reject); }); } /** * Get all fields for a configured locale * @param {Object} fields All fields in all availabe languages * @param {Array} locale Locale configuration * @return {Object} Localized fieldset */ _getFieldsForLocale (fields, locale) { let entry = {}; for (let key in fields) { entry[key] = this._getLocaleString(fields[key], locale); } entry.locale = locale[0]; return entry; } /** * Get local string * @param {[type]} field [description] * @param {[type]} locale [description] * @return {[type]} [description] */ _getLocaleString (field, locale) { let localizedField; if (locale.constructor !== Array) { locale = [locale]; } locale.forEach((currentLocale) => { if (field[currentLocale]) { localizedField = field[currentLocale]; return; } }); return localizedField; } } /** * Exports * @type {Class} */ module.exports = Contentful;
JavaScript
0.000001
@@ -2568,16 +2568,35 @@ tLocale%5D + && !localizedField ) %7B%0A @@ -2642,24 +2642,8 @@ e%5D;%0A - return;%0A
eca76ce385b0b0d4aa0680b92afae43dbcfd909d
Update ingestion.js
src/tap/ingestion.js
src/tap/ingestion.js
/** * ingestion.js * expects: * 1. path of directory * 2. parentpid * 3. namespace * 4. model * output: * log of drush run * * @param target directory path * @param parentpid * @param namespace * @param model * @return $message * */ function ingestion(target,parentpid,namespace,model) { // build command pieces // serveruri is the location of the drupal_home on the drupal server let drupalhome = '/vhosts/digital/web/collections'; let serveruri = 'http://dlwork.lib.utk.edu/dev/'; let parentpid = ''; // namespace let namespace = ''; // target is the local directory holding the ingest files let target = ''; var $message = 'ingest did not happen'; var contentmodel = ''; if ((model)&& (model==='basic')) { contentmodel = 'islandora:sp_basic_image'; } if ((model)&&(model==='large')) { contentmodel = 'islandora:sp_Large_image'; } // execute first drush command var exec = require('child_process').exec; var cmd = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' ibsp --content_models='.contentmodel.' --type=directory --parent='.parentpid.' --namespace='.namespace.' --target='target; if (target!='') { exec(cmd, function(error, stdout, stderr) { // command output is in stdout //console.log(stdout); $message = 'ingest prep drush command success'; status.push("$message"); }); }// end if // exec second drush command //var exec2 = require('child_process').exec; var cmd2 = 'drush -r '.drupalhome.'-v -u=1 --uri='.serveruri.' islandora_batch_ingest'; if ($message = 'ingest prep drush command success') { exec(cmd2, function(error, stdout, stderr) { // command output is in stdout console.log(stdout); $message = 'ingest drush command success'; status.push("$message"); }); }// end if return $message; }// end function export default ingestion;
JavaScript
0.000001
@@ -532,41 +532,133 @@ ;%0A -// namespace%0A let namespace = '' +console.log('parentpid = '.parentpid.'%5Cn');%0A // namespace%0A let namespace = '';%0A console.log('namespace = '.namespace.'%5Cn') ;%0A @@ -734,16 +734,57 @@ t = '';%0A + console.log('target = '.target.'%5Cn');%0A%0A var $m @@ -1020,16 +1020,54 @@ e';%0A %7D%0A + console.log('model = '.model.'%5Cn');%0A // exe @@ -1559,16 +1559,147 @@ end if%0A + else %7B%0A console.log('parameters for first command missing%5Cn');%0A $message = 'parameters for first command missing';%0A %7D%0A // exe
8f124e05b9ea10aa97fdb170f412f525c078aed5
Update download-count.js to make the request asynchronously
_includes/download-count.js
_includes/download-count.js
var xmlHttp = new XMLHttpRequest(); xmlHttp.open("GET", "https://api.github.com/repos/LiveSplit/LiveSplit/releases", false); xmlHttp.send(null); var releasesData = JSON.parse(xmlHttp.responseText); var totalDownloads = releasesData.reduce( function (total, current) { return total + current.assets[0].download_count; }, 145579 // pre-GitHub download total ); document.getElementById("download-count").innerText = totalDownloads + " downloads";
JavaScript
0
@@ -29,16 +29,17 @@ uest();%0A +%0A xmlHttp. @@ -43,109 +43,79 @@ tp.o -pen(%22GET%22, %22https://api.github.com/repos/LiveSplit/LiveSplit/releases%22, false);%0AxmlHttp.send(null);%0A%0A +nreadystatechange = function() %7B%0A if (xmlHttp.readyState === 4) %7B%0A var @@ -163,16 +163,20 @@ eText);%0A + var tota @@ -209,16 +209,20 @@ reduce(%0A + functi @@ -239,24 +239,28 @@ current) %7B%0A + return t @@ -306,11 +306,19 @@ ;%0A -%7D,%0A + %7D,%0A 14 @@ -351,20 +351,32 @@ d total%0A -);%0A%0A + );%0A %0A document @@ -452,8 +452,114 @@ loads%22;%0A + %7D%0A%7D;%0A%0AxmlHttp.open(%22GET%22, %22https://api.github.com/repos/LiveSplit/LiveSplit/releases%22);%0AxmlHttp.send();%0A
25660781e6e08a2f6c2a48095d358d3ed9a8131c
remove unnecessary lines
lib/LogEmitter.js
lib/LogEmitter.js
var EventEmitter = require('events').EventEmitter; var extend = require('util-extend'); var defaultLogBaseObject = { type: 'log', severity: 'log' }; function LogEmitter() { EventEmitter.call(this); var logBaseObject = defaultLogBaseObject; Object.defineProperty(this, 'logBaseObject', { get: function () { return logBaseObject; }, set: function (value) { var base = extend({}, defaultLogBaseObject); logBaseObject = extend(base, value); } }); var originalEmit = this.emit.bind(this); this.emit = function (event, payload) { var result = payload; if (event === 'log') { var base = extend({}, this.logBaseObject); result = extend(base, payload); } originalEmit(event, result); }.bind(this); } LogEmitter.prototype = Object.create(EventEmitter.prototype); LogEmitter.prototype.log = function (message) { this.emit('log', { type: 'log', severity: 'log', message: message }); }; LogEmitter.prototype.info = function (message) { this.emit('log', { type: 'log', severity: 'info', message: message }); }; LogEmitter.prototype.debug = function (message) { this.emit('log', { type: 'log', severity: 'debug', message: message }); }; LogEmitter.prototype.error = function (message) { this.emit('log', { type: 'log', severity: 'error', message: message }); }; module.exports = LogEmitter;
JavaScript
0.999144
@@ -982,37 +982,16 @@ log', %7B%0A - type: 'log',%0A @@ -999,32 +999,32 @@ everity: 'log',%0A + message: @@ -1116,37 +1116,16 @@ log', %7B%0A - type: 'log',%0A @@ -1252,37 +1252,16 @@ log', %7B%0A - type: 'log',%0A @@ -1358,32 +1358,32 @@ ion (message) %7B%0A + this.emit('l @@ -1393,29 +1393,8 @@ , %7B%0A - type: 'log',%0A
ac3bde06281011d8d885a02462d0ccedbc4dc761
update Percent
src/_Percent/Percent.js
src/_Percent/Percent.js
/** * @file Percent component * @author chao([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; class Percent extends Component { static Status = { LOADING: 'loading', SUCCESS: 'success', FAILURE: 'failure' }; constructor(props, ...restArgs) { super(props, ...restArgs); this.state = { percent: 0 }; } /** * 百分比数字递增 */ numberChange = () => { if (this.state.percent < 100) { if (this.state.percent < this.props.endNum) { this.setState({ percent: this.state.percent + 1 }); const time = 300 / (this.props.endNum - this.state.percent); this.timer = setTimeout(() => this.numberChange(), time); return; } this.timer = setTimeout(() => this.numberChange(), 30); } }; componentDidMount() { this.timer = setTimeout(() => this.numberChange(), 30); } componentWillUnmount() { clearTimeout(this.timer); } render() { const {className, style, move, endNum, status, showIcon, successIcon, failureIcon} = this.props, {percent} = this.state, wrapperClassName = classNames('circular-progress-percent', { [className]: className, [status]: status }), wrapperStyle = move === true ? { width: endNum + '%', textAlign: 'right', ...style } : {...style}; return ( <div className={wrapperClassName} style={wrapperStyle}> {React.Children.map(this.props.children, child => <span>{child}</span>)} { status === 'loading' ? <span>{percent}%</span> : null } { showIcon && status === 'success' ? <i className={successIcon || 'fa fa-check-circle'}></i> : null } { showIcon && status === 'failure' ? <i className={failureIcon || 'fa fa-times-circle'}></i> : null } </div> ); } } Percent.propTypes = { className: PropTypes.string, style: PropTypes.object, /** * The status of loading. */ status: PropTypes.oneOf(Object.keys(Percent.Status).map(key => Percent.Status[key])), endNum: PropTypes.number, move: PropTypes.bool }; Percent.defaultProps = { endNum: 100, move: false }; export default Percent;
JavaScript
0.000003
@@ -477,39 +477,8 @@ %7D%0A%0A - /**%0A * %E7%99%BE%E5%88%86%E6%AF%94%E6%95%B0%E5%AD%97%E9%80%92%E5%A2%9E%0A */%0A @@ -1299,17 +1299,17 @@ is.state -, +; %0A%0A @@ -1314,28 +1314,43 @@ - wrapperC +return (%0A %3Cdiv c lassName = c @@ -1345,19 +1345,18 @@ lassName - = +=%7B classNam @@ -1476,18 +1476,17 @@ %7D) -,%0A +%7D %0A @@ -1494,23 +1494,20 @@ -wrapperS + s tyle - = +=%7B move @@ -1517,35 +1517,20 @@ = true ? -%0A %7B%0A + @@ -1582,16 +1582,17 @@ + textAlig @@ -1627,78 +1627,17 @@ -...style%0A %7D%0A :%0A %7B + ...style %7D;%0A%0A @@ -1632,19 +1632,16 @@ ...style -%7D;%0A %0A @@ -1645,95 +1645,22 @@ -return (%0A %3Cdiv className=%7BwrapperClassName%7D%0A style=%7BwrapperS + %7D : s tyle @@ -2449,24 +2449,54 @@ pTypes = %7B%0A%0A + children: PropTypes.any,%0A%0A classNam @@ -2737,16 +2737,119 @@ pes.bool +,%0A%0A showIcon: PropTypes.string,%0A successIcon: PropTypes.string,%0A failureIcon: PropTypes.string %0A%0A%7D;%0A%0APe @@ -2931,8 +2931,9 @@ Percent; +%0A
35ae332a9d17bfe7e129c352f8f7ddf0b1fa5242
Delete the warning message for unsaving
website/static/js/filepage/editor.js
website/static/js/filepage/editor.js
var m = require('mithril'); var Raven = require('raven-js'); var $osf = require('js/osfHelpers'); var ShareJSDoc = require('js/pages/ShareJSDocFile.js'); require('ace-noconflict'); require('ace-mode-markdown'); require('ace-ext-language_tools'); require('addons/wiki/static/ace-markdown-snippets.js'); var Markdown = require('pagedown-ace-converter'); Markdown.getSanitizingConverter = require('pagedown-ace-sanitizer').getSanitizingConverter; require('imports?Markdown=pagedown-ace-converter!pagedown-ace-editor'); var util = require('./util.js'); var model = {}; var FileEditor = { controller: function(contentUrl, shareWSUrl, editorMeta, observables) { var self = {}; self.url = contentUrl; self.loaded = false; self.initialText = ''; self.editorMeta = editorMeta; self.observables = observables; self.unthrottledStatus = self.observables.status; $osf.throttle(self.observables.status, 4000, {leading: false}); self.bindAce = function(element, isInitialized, context) { if (isInitialized) { return; } model.editor = ace.edit(element.id); model.editor.setValue(self.initialText, -1); new ShareJSDoc(shareWSUrl, self.editorMeta, model.editor, self.observables); }; self.reloadFile = function() { self.loaded = false; $.ajax({ type: 'GET', url: self.url, dataType: 'text', beforeSend: $osf.setXHRAuthorization, }).done(function (parsed, status, response) { m.startComputation(); self.loaded = true; self.initialText = response.responseText; if (model.editor) { model.editor.setValue(self.initialText); } m.endComputation(); }).fail(function (xhr, textStatus, error) { $osf.growl('Error','The file content could not be loaded.'); Raven.captureMessage('Could not GET file contents.', { url: self.url, textStatus: textStatus, error: error }); }); }; self.saveFile = $osf.throttle(function() { if(self.changed()) { var oldstatus = self.observables.status(); model.editor.setReadOnly(true); self.unthrottledStatus('saving'); m.redraw(); var request = $.ajax({ type: 'PUT', url: self.url, data: model.editor.getValue(), beforeSend: $osf.setXHRAuthorization }).done(function () { model.editor.setReadOnly(false); self.unthrottledStatus(oldstatus); $(document).trigger('fileviewpage:reload'); self.initialText = model.editor.getValue(); m.redraw(); }).fail(function(xhr, textStatus, err) { var message; if (xhr.status === 507) { message = 'Could not update file. Insufficient storage space in your Dropbox.'; } else { message = 'The file could not be updated.'; } model.editor.setReadOnly(false); self.unthrottledStatus(oldstatus); $(document).trigger('fileviewpage:reload'); model.editor.setValue(self.initialText); $osf.growl('Error', message); Raven.captureMessage('Could not PUT file content.', { textStatus: textStatus, url: self.url }); m.redraw(); }); } else { alert('There are no changes to save.'); } }, 500); self.changed = function() { var file1 = self.initialText; var file2 = !model.editor ? '' : model.editor.getValue(); var clean1 = typeof file1 === 'string' ? file1.replace(/(\r\n|\n|\r)/gm, '\n') : ''; var clean2 = typeof file2 === 'string' ? file2.replace(/(\r\n|\n|\r)/gm, '\n') : ''; return clean1 !== clean2; }; self.reloadFile(); return self; }, view: function(ctrl) { if (!ctrl.loaded) { return util.Spinner; } return m('.editor-pane.panel-body', [ m('.wiki-connected-users', m('.row', m('.col-sm-12', [ m('.ul.list-inline', {style: {'margin-top': '10px'}}, [ ctrl.observables.activeUsers().map(function(user) { return m('li', m('a', {href: user.url}, [ m('img', { title: user.name, src: user.gravatar, 'data-container': 'body', 'data-placement': 'top', 'data-toggle': 'tooltip', style: {border: '1px solid black'} }) ])); }) ]) ]))), m('', {style: {'padding-top': '10px'}}, [ m('.wmd-input.wiki-editor#editor', {config: ctrl.bindAce}) ]), m('br'), m('[style=position:inherit]', [ m('.row', m('.col-sm-12', [ m('.pull-right', [ m('button#fileEditorRevert.btn.btn-sm.btn-danger', {onclick: function(){ctrl.reloadFile();}}, 'Revert'), ' ', m('button#fileEditorSave.btn.btn-sm.btn-success', {onclick: function() {ctrl.saveFile();}}, 'Save') ]) ])) ]) ]); } }; module.exports = FileEditor;
JavaScript
0.000004
@@ -3960,84 +3960,8 @@ %7D -else %7B%0A alert('There are no changes to save.');%0A %7D %0A
dce3057c090214ad813a07925b0dea1cc9449d84
Fix promises queue changes through promises handler
source/class/core/event/Promise.js
source/class/core/event/Promise.js
/* ================================================================================================== Core - JavaScript Foundation Copyright 2013 Sebastian Fastner ================================================================================================== */ /** * Promises implementation of A+ specification passing Promises/A+ test suite. * Very efficient due to object pooling. * http://promises-aplus.github.com/promises-spec/ */ core.Class("core.event.Promise", { pooling : true, construct : function() { // Initialize lists on new Promises if (this.__onFulfilledQueue == null) { this.__onFulfilledQueue = []; this.__onRejectedQueue = []; } }, members : { /** {=String} Current state */ __state : "pending", /** {=Boolean} Whether the promise is locked */ __locked : false, /** {=any} Any value */ __valueOrReason : null, /** * {any} Returns the value of the promise */ getValue : function() { return this.__valueOrReason; }, /** * {String} Returns the current state. One of pending, fulfilled or rejected. */ getState : function() { return this.__state; }, /** * Fulfill promise with @value {any?}. */ fulfill : function(value) { if (!this.__locked) { this.__locked = true; this.__state = "fulfilled"; this.__valueOrReason = value; core.util.Function.immediate(this.__execute, this); } }, /** * Reject promise with @reason {String|any?}. */ reject : function(reason) { if (!this.__locked) { this.__locked = true; this.__state = "rejected"; this.__valueOrReason = reason; core.util.Function.immediate(this.__execute, this); } }, /** * Executes a single fulfillment or rejection queue @entry {Array} * with the give @valueOrReason {any} and state {String}. */ __executeEntry : function(entry, valueOrReason, state) { var child = entry[0]; var callback = entry[1]; if (callback === null) { if (state == "rejected") { child.reject(valueOrReason); } else { child.fulfill(valueOrReason); } } else { try { var context = entry[2]; var retval = context ? callback.call(context, valueOrReason) : callback(valueOrReason); if (retval && retval.then && typeof retval.then == "function") { var retstate = retval.getState ? retval.getState() : "pending"; if (retstate == "pending") { retval.then(function(value) { child.fulfill(value); }, function(reason) { child.reject(reason); }); } else if (retstate == "fulfilled") { child.fulfill(retval.getValue()); } else if (retstate == "rejected") { child.reject(retval.getValue()); } } else { child.fulfill(retval); } } catch (ex) { child.reject(ex); } } }, /** * Handle fulfillment or rejection of promise * Runs all registered then handlers */ __execute : function() { // Shorthands var rejectedQueue = this.__onRejectedQueue; var fullfilledQueue = this.__onFulfilledQueue; var valueOrReason = this.__valueOrReason; var state = this.__state; // Process the relevant queue var queue = this.__state == "rejected" ? rejectedQueue : fullfilledQueue; for (var i=0, l=queue.length; i<l; i++) { this.__executeEntry(queue[i], valueOrReason, state); } // Cleanup lists for next usage rejectedQueue.length = 0; fullfilledQueue.length = 0; // Cleanup internal state this.__state = "pending"; this.__locked = false; // Auto release promise after fulfill/reject and all handlers being processed this.release(); }, /** * {core.event.Promise} Register fulfillment handler {function} @onFulfilled * and rejection handler {function} @onRejected returning new child promise. */ then : function(onFulfilled, onRejected, context) { var child = core.event.Promise.obtain(); var fullfilledQueue = this.__onFulfilledQueue; var rejectedQueue = this.__onRejectedQueue; if (onFulfilled && typeof onFulfilled == "function") { fullfilledQueue.push([child, onFulfilled, context]); } else { fullfilledQueue.push([child]); } if (onRejected && typeof onRejected == "function") { rejectedQueue.push([child, onRejected, context]); } else { rejectedQueue.push([child]); } return child; } } });
JavaScript
0.000001
@@ -3363,16 +3363,96 @@ dQueue;%0A +%09%09%09// Always repeat queue length check as queue could be changed within handler%0A %09%09%09for ( @@ -3462,12 +3462,12 @@ i=0 -, l= +; i%3C queu @@ -3479,13 +3479,8 @@ gth; - i%3Cl; i++