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
|
---|---|---|---|---|---|---|---|
6a5c7a0725b6158bfb60af86cad0ad327195d2a9
|
Add FormData stub
|
elm-io-ports.js
|
elm-io-ports.js
|
/* Implementation from: https://github.com/laszlopandy/elm-console/blob/master/elm-io.sh */
module.exports =
"(function(){\n" +
" window = {Date: Date, addEventListener: function() {}, removeEventListener: function() {}};\n" +
" if (typeof XMLHttpRequest === \"undefined\") { XMLHttpRequest = function() { return { addEventListener: function() {}, open: function() {}, send: function() {} }; }; }\n" +
" if (typeof Elm === \"undefined\") { throw \"elm-io config error: Elm is not defined. Make sure you call elm-io with a real Elm output file\"}\n" +
" if (typeof Elm.Main === \"undefined\" ) { throw \"Elm.Main is not defined, make sure your module is named Main.\" };\n" +
" var worker = Elm.worker(Elm.Main);\n" +
"})();\n";
|
JavaScript
| 0 |
@@ -403,24 +403,225 @@
; %7D; %7D%5Cn%22 +%0A
+ %22 if (typeof FormData === %5C%22undefined%5C%22) %7B FormData = function () %7B this._data = %5B%5D; %7D; FormData.prototype.append = function () %7B this._data.push(Array.prototype.slice.call(arguments)); %7D; %7D%5Cn%22 +%0A
%22 if (t
|
fb928f897b5721124b8b9b15c9d0f280c4356fbb
|
add on event, like ajax
|
modules/recognizer/node_helper.js
|
modules/recognizer/node_helper.js
|
var NodeHelper = require("node_helper");
const exec = require('child_process').exec;
const path = require('path');
const request = require('request');
const fs = require('fs');
const FormData = require('form-data');
module.exports = NodeHelper.create({
socketNotificationReceived: function(notification) {
if (notification === "RECOGNIZER_STARTUP"){
console.log("Recognizer Node Helper initialized, awaiting Activation");
this.sendSocketNotification("RECOGNIZER_CONNECTED");
}
else if(notification === "RECOGNIZE_PICTURE") {
console.log("===Selfie is being taken now====");
var image = exec("fswebcam -r 1280x720 --no-banner ./public/webcam_pic.jpg");
thingy = this.callForMatches();
console.log("callForMatches returns:" + thingy.results)
}
},
callForMatches: function() {
console.log("Recognizer Node Helper is calling api")
var options = {
api_key: "9oOudn2moC5eM-pQwLy_ugUs6rYRT7aj",
api_secret: "ROglv8QFta3JmGAppEYTpoPY68DjERzX",
image_file: fs.createReadStream(__dirname + '/../../public/webcam_pic.jpg'),
outer_id: "mirrormirror"
};
var url = "https://api-us.faceplusplus.com/facepp/v3/search";
var response = request.post({url: url, formData: options}, function(err, httpRes, body) {
var json = JSON.parse(body);
console.log(json);
return json;
});
return response;
},
translateRecognition: function(recogResult) {
console.log("translating:" + recogResult);
var confidence = recogResult.results[0].confidence;
var memberToken = recogResult.results[0].face_token;
}
});
|
JavaScript
| 0 |
@@ -777,24 +777,16 @@
+ thingy
-.results
)%0A %7D%0A
@@ -1296,24 +1296,94 @@
, body) %7B%0A
+ %7D).on('response', function(response) %7B%0A console.log(response);%0A
var js
@@ -1402,17 +1402,19 @@
rse(
-body
+response
);%0A
-
@@ -1432,41 +1432,21 @@
og(j
-son);%0A return j
+o
son
+)
;%0A %7D)
;%0A
@@ -1445,30 +1445,9 @@
%7D)
-;%0A return response;
+%0A
%0A %7D
@@ -1666,8 +1666,79 @@
%7D%0A%0A%7D);%0A
+%0A// var json = JSON.parse(body);%0A// console.log(json);%0A// return json;%0A
|
43bc532cdae0520048d338c3223b4ddd52dd9297
|
remove fast-click
|
pet-projects/xylo-stars/js/main.js
|
pet-projects/xylo-stars/js/main.js
|
$(function() {
FastClick.attach(document.body);
// $.fn.checkPosition = function() {
// var top = this[0].getBoundingClientRect().top;
// var left = this[0].getBoundingClientRect().left;
// var right = this[0].getBoundingClientRect().right;
// var bottom = this[0].getBoundingClientRect().bottom;
// // console.log(top, right, bottom, left)
// }
buzz.defaults.formats = ['wav'];
var xyloSounds = [];
var sounds = ['a', 'b', 'c', 'c2', 'd1', 'e1', 'f', 'g'];
for (var i = 0; i < sounds.length; i++) {
var sound = sounds[i];
xyloSounds.push(new buzz.sound('audio/' + sound));
}
var starRatio = 228/225;
var countStars = getRandomInt(7, 20);
var securityZoneSize = getRandomInt(10, 100);
divideArea(securityZoneSize, countStars);
$(window).on('resize', function() {
countStars = getRandomInt(7, 20);
securityZoneSize = getRandomInt(10, 100);
$('.star').remove();
divideArea(securityZoneSize, countStars);
});
$('.star').on('mousedown', function() {
var concreteSound = getRandomInt(0, sounds.length);
if (xyloSounds[concreteSound].isPaused()) {
xyloSounds[concreteSound].play();
} else {
xyloSounds[concreteSound].stop().play();
}
});
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function getRandom() {
return Math.random() > 0.5 ? Math.random() : Math.random() -1;
}
function setSquare(topCoord, leftCoord, $elementSide) {
var newSquare = document.createElement('div');
$(newSquare).addClass('star');
$(newSquare).css({
'top': topCoord + 100 * getRandom(),
'left': leftCoord + 10 * getRandom(),
'width': $elementSide * starRatio,
'height': $elementSide
});
$('.sky').append(newSquare);
}
function divideArea(securityZoneSize, numberOfSquares) {
var $width = $(window).width() - securityZoneSize;
var $height = $(window).height() - securityZoneSize;
var $square = $width * $height;
var $elementSquare = parseInt($square / numberOfSquares);
var $elementSide = parseInt(Math.sqrt($elementSquare));
for (var i = securityZoneSize; i < $width - $elementSide; i+= $elementSide) {
for (var j = securityZoneSize; j < $height - $elementSide; j+= $elementSide) {
setSquare(j, i, $elementSide);
}
}
}
});
|
JavaScript
| 0.000001 |
@@ -12,16 +12,19 @@
) %7B%0A%0A
+ //
FastCli
@@ -1923,16 +1923,79 @@
mentSide
+,%0A 'transform-rotate': getRandomInt(10, 360) + 'deg'
%0A
|
b74e1a19e2022ffbcc72ad53cd0662430f2f2bac
|
Delete also Pipes connected to the element deleted
|
src/reducers/workspace/addRemoveElementReducer.js
|
src/reducers/workspace/addRemoveElementReducer.js
|
import {
Brick as BrickDefaults,
Primitive as PrimitiveDefaults
} from '../../components/constants'
import {
BRICK,
SELECTABLE_PIPE,
PRIMITIVE
} from '../../utils/componentsEnum'
import { nextId } from './workspaceReducerUtils'
export const appendToInner = (workspace, element) => {
const mainBrickId = workspace.mainBrickId
const mainBrick = workspace.entities[mainBrickId]
return Object.assign({}, workspace, {
...workspace,
entities: {
...workspace.entities,
[mainBrickId]: {
...mainBrick,
inner: [
...mainBrick.inner,
element.id
]
},
[element.id]: element
}
})
}
export const newBrick = (brick) => {
const { arity, name } = brick
let inputSlots = []
for(var i=0; i < arity; i++)
inputSlots.push({ id: nextId() })
return {
Component: BRICK,
id: nextId(),
inputSlots,
name,
outputSlots: [
{ id: nextId() }
],
position: BrickDefaults.defaultPosition,
size: BrickDefaults.defaultSize
}
}
export const newPrimitive = (type) => {
return {
Component: PRIMITIVE,
id: nextId(),
position: PrimitiveDefaults.defaultPosition,
size: PrimitiveDefaults.defaultSize,
type: type,
// react or redux ignore pair with value `undefined`
value: null
}
}
export const newPipe = (workspace) => {
const { input, output } = workspace.selectionState.pipe
return {
Component: SELECTABLE_PIPE,
id: nextId(),
input,
type: null,
output,
value: null
}
}
export const removeElementInWorkspace = (workspace, payload) => {
const { elementId } = payload
const { entities, mainBrickId } = workspace
const mainBrick = entities[mainBrickId]
let newEntities = {}
for(let key in entities) {
if(key != elementId)
newEntities[key] = entities[key]
}
return Object.assign({}, workspace, {
...workspace,
entities: {
...newEntities,
[mainBrickId]: {
...mainBrick,
inner: mainBrick.inner.filter((id) => id != elementId)
}
}
})
}
|
JavaScript
| 0 |
@@ -1789,16 +1789,130 @@
-if
+const element = entities%5Bkey%5D%0A%0A // Skip if key is the elementId or is a pipe connected to this elementId%0A if(!
(key
-!
+=
= el
@@ -1910,32 +1910,79 @@
key == elementId
+ %7C%7C pipeConnectedToElement(element, elementId))
)%0A newEntit
@@ -1993,28 +1993,22 @@
key%5D = e
-ntities%5Bkey%5D
+lement
%0A %7D%0A%0A
@@ -2158,80 +2158,371 @@
-inner: mainBrick.inner.filter((id) =%3E id != elementId)%0A %7D%0A %7D%0A %7D
+// Remove from mainBrick.inner all the entities removed by%0A // the loop above%0A inner: mainBrick.inner.filter((id) =%3E newEntities%5Bid%5D)%0A %7D%0A %7D%0A %7D)%0A%7D%0A%0Aconst pipeConnectedToElement = (element, elementId) =%3E %7B%0A return element.Component == SELECTABLE_PIPE &&%0A (element.input.elementId == elementId %7C%7C%0A element.output.elementId == elementId
)%0A%7D%0A
|
ac417b1cf5be82d6e29dd82c65d5ae4b06572aed
|
remove incorrect session
|
materials/2-bmp085-n2/device.js
|
materials/2-bmp085-n2/device.js
|
var config = require('./config')
, nitrogen = require('nitrogen')
, BMP085Device = require('nitrogen-bmp085');
// The nitrogen-bmp085 module wraps the bmp085 module into a Nitrogen device that emits messages.
var bmp085 = new BMP085Device({
name: 'BMP085 Device',
nickname: 'bmp085',
api_key: '/* 1. Add your API Key from the Nitrogen Web Admin here */'
});
var service = new nitrogen.Service(config);
// This establishes a session for your device with the Nitrogen service.
service.connect(bmp085, function(err, session) {
if (err) return console.log('Failed to connect device: ' + err);
setInterval(function() {
// Nitrogen sensor devices take measurements and then callback with a set of Nitrogen messages.
bmp085.measure(session, function(err, messages) {
// 2. Write the code to send these messages to the Nitrogen service.
// HINT: see http://nitrogen.io/.../ for an example.
});
}, 30 * 1000);
});
|
JavaScript
| 0.000022 |
@@ -25,17 +25,16 @@
config')
-
%0A ,%09nit
@@ -749,17 +749,8 @@
ure(
-session,
func
@@ -922,10 +922,9 @@
%09%7D,
-30
+5
* 1
|
c43f441b86ec0c094d7e33819d1cc7701c4f819a
|
Remove an extra console.log in bin/cucumber.js that was causing the build to fail.
|
bin/cucumber.js
|
bin/cucumber.js
|
#!/usr/bin/env node
var Cucumber = require('../lib/cucumber');
var cli = Cucumber.Cli(process.argv);
cli.run(function(succeeded) {
var code = succeeded ? 0 : 1;
process.on('exit', function() {
console.log("exiting, succeeded: " + succeeded + " code: " + code);
process.exit(code);
});
var timeoutId = setTimeout(function () {
console.error('Cucumber process timed out after waiting 60 seconds for the node.js event loop to empty. There may be a resource leak. Have all resources like database connections and network connections been closed properly?');
process.exit(code);
}, 60 * 1000);
if (timeoutId.unref) {
timeoutId.unref();
}
else {
clearTimeout(timeoutId);
}
});
|
JavaScript
| 0 |
@@ -202,84 +202,8 @@
) %7B%0A
- console.log(%22exiting, succeeded: %22 + succeeded + %22 code: %22 + code);%0A
|
9025ec48a8a52a3923bcceabec8aea89db6ed1f7
|
fix a bug after opensourcing
|
bin/gensokyo.js
|
bin/gensokyo.js
|
#! /usr/bin/env node
/**
* XadillaX created at 2014-10-09 14:23
*
* Copyright (c) 2014 Huaban.com, all rights
* reserved.
*/
var path = require("path");
var opts = require("nomnom").script("gensokyo").option("action", {
position: 0,
callback: function(val) {
return (val === "new") ? undefined : "You can only create a Gensokyo Project via `new` so far.";
},
list: false,
help: "only `new` is supported so far.",
required: true
}).option("name", {
position: 1,
callback: function(name) {
return path.dirname(name) !== "." ? "Wrong project name." : undefined;
},
default: "gensokyo",
help: "project name (directory name as well)."
}).parse();
var projectName = opts.name;
var fs = require("fs");
try {
fs.mkdirSync(projectName);
} catch(e) {
if(e.message.indexOf("file already exists") === -1) {
console.log(e.message);
process.exit(0);
}
}
if(!fs.existsSync(projectName)) {
console.log("Can't create project \"" + projectName + "\".");
process.exit(0);
}
try {
var result = fs.readdirSync(projectName);
} catch(e) {
console.log(e.message);
process.exit(0);
}
if(result.length !== 0) {
console.log("Not an empty directory.");
process.exit(0);
}
// file templates
var run = require("sync-runner");
run("cp -R " + __dirname + "/../_template/* " + projectName);
var walker = require("walk").walk(projectName);
walker.on("file", function(root, fileStats, next) {
var filename = root + "/" + fileStats.name;
var text = fs.readFileSync(filename, { encoding: "utf8" });
text = text.replace(/\{\{\%project name\%\}\}/g, projectName);
text = text.replace(/\{\{\%project name lowercase\%\}\}/g, projectName.toLowerCase());
fs.writeFileSync(filename, text, { encoding: "utf8" });
next();
});
walker.on("end", function() {
var pkg = require("../package");
var npmPackage = {
name: projectName,
version: "0.0.1",
description: projectName + " is yet another service.",
main: "gensokyo.js",
dependencies: {
gensokyo: "^" + pkg.version,
nomnom: "^1.8.0"
},
keywords: ["gensokyo", "service"]
};
fs.writeFile(projectName + "/package.json", JSON.stringify(npmPackage, true, 2), { encoding: "utf8" });
console.log("Installing dependencies...");
var childProcess = require("child_process");
childProcess.exec("npm install --registry=http://registry.npm.huaban.org", {
cwd: process.cwd() + "/" + projectName + "/"
}, function(err, stdout) {
console.log(stdout);
console.log(err ? err.message : "Done.");
});
});
|
JavaScript
| 0.000004 |
@@ -2463,50 +2463,8 @@
tall
- --registry=http://registry.npm.huaban.org
%22, %7B
|
431b396015c672faa12473c6ab7a5ac971ce3158
|
Remove duplicate case
|
src/__tests__/recaptcha-wrapper.spec.js
|
src/__tests__/recaptcha-wrapper.spec.js
|
import recaptcha, { createRecaptcha } from '../recaptcha-wrapper'
const WIDGET_ID = 'widgetId'
const recaptchaMock = {
render: jest.fn(() => WIDGET_ID),
reset: jest.fn(),
execute: jest.fn()
}
describe('recaptcha', () => {
describe('#createRecaptcha', () => {
let ins
beforeEach(() => {
ins = createRecaptcha()
})
describe('#assertRecaptchaLoad', () => {
describe('When Recaptcha not loaded', () => {
it('Throw', () => {
expect(() => {
ins.assertRecaptchaLoad()
}).toThrow()
})
})
describe('When Recaptcha loaded', () => {
it('Not throw', () => {
ins.setRecaptcha(recaptchaMock)
expect(() => {
ins.assertRecaptchaLoad()
}).not.toThrow()
})
})
})
describe('#checkRecaptchaLoad', () => {
describe('When Recaptcha not loaded', () => {
it('Not load Recaptcha into it', () => {
ins.checkRecaptchaLoad()
expect(() => {
ins.assertRecaptchaLoad()
}).toThrow()
})
})
describe('When Recaptcha loaded', () => {
beforeEach(() => {
window.grecaptcha = recaptchaMock
})
afterEach(() => delete window.grecaptcha)
it('Load Recaptcha', () => {
ins.checkRecaptchaLoad()
expect(() => {
ins.assertRecaptchaLoad()
}).not.toThrow()
})
})
})
describe('#getRecaptcha', () => {
describe('Recaptcha not loaded', () => {
it('Return defered object', () => {
const spy = jest.fn()
// Since it return thenable, not Promise. Here must wrap it as Promise
const promise = Promise.resolve(ins.getRecaptcha()).then(spy)
expect(spy).not.toHaveBeenCalled()
ins.setRecaptcha(recaptchaMock)
return promise.then(() => {
expect(spy).toHaveBeenCalled()
})
})
})
})
describe('#setRecaptcha', () => {
it('Set recaptcha', () => {
ins.setRecaptcha(recaptchaMock)
return Promise.resolve(ins.getRecaptcha()).then((recap) => {
expect(recap).toBe(recaptchaMock)
})
})
})
describe('#assertRecaptchaLoad', () => {
describe('When ReCAPTCHA not loaded', () => {
it('Throw error', () => {
expect(() => {
ins.assertRecaptchaLoad()
}).toThrow()
})
})
describe('When ReCAPTCHA loaded', () => {
it('Not throw error', () => {
ins.setRecaptcha(recaptchaMock)
expect(() => {
ins.assertRecaptchaLoad()
}).not.toThrow()
})
})
})
describe('#render', () => {
it('Render ReCAPTCHA', () => {
const ele = document.createElement('div')
const sitekey = 'foo'
ins.setRecaptcha(recaptchaMock)
return ins.render(ele, {sitekey}, (widgetId) => {
expect(recaptchaMock.render).toBeCalled()
expect(widgetId).toBe(WIDGET_ID)
})
})
})
describe('#reset', () => {
describe('When pass widget id', () => {
it('Reset ReCAPTCHA', () => {
jest.resetAllMocks()
ins.setRecaptcha(recaptchaMock)
ins.reset(WIDGET_ID)
expect(recaptchaMock.reset).toBeCalled()
})
})
describe('When not pass widget id', () => {
it('Do nothing', () => {
jest.resetAllMocks()
ins.setRecaptcha(recaptchaMock)
ins.reset()
expect(recaptchaMock.reset).not.toBeCalled()
})
})
})
describe('#execute', () => {
describe('When pass widget id', () => {
it('Execute ReCAPTCHA', () => {
jest.resetAllMocks()
ins.setRecaptcha(recaptchaMock)
ins.execute(WIDGET_ID)
expect(recaptchaMock.execute).toBeCalled()
})
})
describe('When not pass widget id', () => {
it('Do nothing', () => {
jest.resetAllMocks()
ins.setRecaptcha(recaptchaMock)
ins.execute()
expect(recaptchaMock.execute).not.toBeCalled()
})
})
})
})
describe('window.vueRecaptchaApiLoaded', () => {
beforeEach(() => {
window.grecaptcha = recaptchaMock
})
afterEach(() => delete window.grecaptcha)
it('Load grecaptcha', () => {
window.vueRecaptchaApiLoaded()
expect(() => recaptcha.assertRecaptchaLoad()).not.toThrow()
})
})
})
|
JavaScript
| 0.000006 |
@@ -396,39 +396,39 @@
escribe('When Re
-captcha
+CAPTCHA
not loaded', ()
@@ -446,24 +446,30 @@
it('Throw
+ error
', () =%3E %7B%0A
@@ -589,39 +589,39 @@
escribe('When Re
-captcha
+CAPTCHA
loaded', () =%3E
@@ -643,16 +643,22 @@
ot throw
+ error
', () =%3E
@@ -694,32 +694,33 @@
(recaptchaMock)%0A
+%0A
expect
@@ -2260,492 +2260,8 @@
%7D)%0A%0A
- describe('#assertRecaptchaLoad', () =%3E %7B%0A describe('When ReCAPTCHA not loaded', () =%3E %7B%0A it('Throw error', () =%3E %7B%0A expect(() =%3E %7B%0A ins.assertRecaptchaLoad()%0A %7D).toThrow()%0A %7D)%0A %7D)%0A%0A describe('When ReCAPTCHA loaded', () =%3E %7B%0A it('Not throw error', () =%3E %7B%0A ins.setRecaptcha(recaptchaMock)%0A%0A expect(() =%3E %7B%0A ins.assertRecaptchaLoad()%0A %7D).not.toThrow()%0A %7D)%0A %7D)%0A %7D)%0A
%0A
|
6364c13cb6b690afac4fdd5c438e719f1e8498c1
|
bump ??? distribution dist/snuggsi.min.es.js
|
dist/snuggsi.min.es.js
|
dist/snuggsi.min.es.js
|
const HTMLElement=(e=>{function t(){}return t.prototype=window.HTMLElement.prototype,t})();class TokenList{constructor(e){const t=e=>/{(\w+|#)}/.test(e.textContent)&&(e.text=e.textContent).match(/[^{]+(?=})/g).map(t=>(this[t]||(this[t]=[])).push(e)),n=document.createNodeIterator(e,NodeFilter.SHOW_ELEMENT|NodeFilter.SHOW_TEXT,e=>e.attributes&&[].slice.call(e.attributes).map(t)||t(e),null);for(;n.nextNode(););}bind(e){const t=t=>n=>n.textContent=n.textContent.split("{"+t+"}").join(e[t]),n=e=>(e.textContent=e.text)&&e;for(let s in this)this[s].map(n).map(t(s))}}(e=>{function t(e){let t=new XMLHttpRequest;t.link=e,t.onload=n,t.open("GET",e.href),t.responseType="document",t.send()}function n(e){e=this.link;let t=this.response,n=e.nextChild,l=e.content=t.querySelector("template");for(let o of document.querySelectorAll(e.id))l&&s.call(o,l);for(let s of t.querySelectorAll("style,link,script"))!function(e,t,n){let s=t.getAttribute("as"),l=document.createElement("script"==s?s:t.localName);["id","rel","href","src","textContent","as","defer","crossOrigin"].map(e=>t[e]&&e in l&&(l[e]=t[e])),"style"==s&&(l.rel="stylesheet"),"script"==s&&(l.src=l.href),e.parentNode.insertBefore(l,n)}(e,s,n)}function s(e){e=document.importNode(e,!0);let t;[].slice.call(e.attributes).map(e=>!this.attributes[e.name]&&this.setAttribute(e.name,e.value));for(let n of this.querySelectorAll("[slot]"))(t=(e.content||e).querySelector("slot[name="+n.getAttribute("slot")+"]"))&&t.parentNode.replaceChild(n,t);return this.innerHTML=e.innerHTML}new MutationObserver(e=>{for(let n of e)for(let e of n.addedNodes)/^p/.test(e.rel)&&/\-/.test(e.id)&&t(e),/\-/.test(e.localName)&&(link=document.querySelector("#"+e.localName))&&link.content&&s.call(e,link.content)&&customElements.upgrade(e)}).observe(document.documentElement,{childList:!0,subtree:!0}),[].slice.call(document.querySelectorAll('[rel^=pre][id~="-"]')).map(t)})();const Template=e=>{e.length&&(e=document.querySelector("template[name="+e+"]"));let t=e.innerHTML,n=e.nextSibling;return e.innerHTML="",e.bind=function(e){const s=document.createElement("section");for(let t of this.dependents||[])t.parentNode.removeChild(t);s.innerHTML=[].concat(e).reduce((e,n,s)=>{let l=t;"object"!=typeof n&&(n={self:n}),n["#"]=s;for(let t in n)l=l.split("{"+t+"}").join(n[t]);return e+l},"");for(let t of this.dependents=[].slice.call(s.childNodes))this.parentNode.insertBefore(t,n)}.bind(e),e};window.customElements=window.customElements||{},new class{constructor(){customElements.define=this.define.bind(this),customElements.upgrade=this.upgrade.bind(this)}define(e,t){this[e]=t,[].slice.call(document.querySelectorAll(e)).map(this.upgrade,this)}upgrade(e){this[e.localName]&&Object.setPrototypeOf(e,this[e.localName].prototype).connectedCallback()}};const ParentNode=e=>class extends e{select(){return this.selectAll(...arguments)[0]}selectAll(e,...t){return e=[].concat(e),[].slice.call(this.querySelectorAll(t.reduce((t,n)=>t+n+e.shift(),e.shift())))}},EventTarget=e=>class extends e{on(e,t){this.addEventListener(e,this.renderable(t))}renderable(e){return t=>!1!==e.call(this,t)&&t.defaultPrevented||this.render()}},GlobalEventHandlers=e=>class extends e{onconnect(){this.templates=this.selectAll("template[name]").map(Template),this.tokens=new TokenList(this),super.onconnect&&super.onconnect()}reflect(e){/^on/.test(e)&&e in HTMLElement.prototype&&this.on(e.substr(2),this[e])}register(e,t,n){for(let s of[].slice.call(e.attributes))/^on/.test(n=s.name)&&(t=(/{\s*(\w+)/.exec(e[n])||[])[1])&&(e[n]=this.renderable(this[t]))}},Custom=e=>class extends(ParentNode(EventTarget(GlobalEventHandlers(e)))){connectedCallback(){this.context={},super.initialize&&super.initialize(),Object.getOwnPropertyNames(e.prototype).map(this.reflect,this),this.onconnect(),this.render()}render(){for(let e of this.templates)e.bind(this[e.getAttribute("name")]);this.tokens.bind(this),this.register(this),this.selectAll("*").map(this.register,this),super.onidle&&super.onidle()}},Element=e=>t=>customElements.define(e+"",Custom(t));
|
JavaScript
| 0.000007 |
@@ -486,39 +486,8 @@
%5Bt%5D)
-,n=e=%3E(e.textContent=e.text)&&e
;for
@@ -491,17 +491,17 @@
for(let
-s
+n
in this
@@ -510,24 +510,51 @@
his%5B
-s
+n
%5D.map(
-n
+e=%3E(e.textContent=e.text)&&e
).map(t(
s))%7D
@@ -549,17 +549,17 @@
).map(t(
-s
+n
))%7D%7D(e=%3E
|
0b797aa59d6f7687d45a8eb8441451d39e6efdcf
|
add actions for deleting chat messages (by id, user, all)
|
src/actions/ModerationActionCreators.js
|
src/actions/ModerationActionCreators.js
|
import { post } from '../utils/Request';
import { djSelector } from '../selectors/boothSelectors';
import { tokenSelector } from '../selectors/userSelectors';
import {
SKIP_DJ_START, SKIP_DJ_COMPLETE
} from '../constants/actionTypes/moderation';
export function skipCurrentDJ(reason = '') {
return (dispatch, getState) => {
const jwt = tokenSelector(getState());
const dj = djSelector(getState());
if (!dj) {
return;
}
const payload = { userID: dj._id, reason };
dispatch({
type: SKIP_DJ_START,
payload
});
post(jwt, `/v1/booth/skip`, payload)
.then(res => res.json())
.then(() => dispatch({
type: SKIP_DJ_COMPLETE,
payload
}))
.catch(error => dispatch({
type: SKIP_DJ_COMPLETE,
error: true,
payload: error,
meta: payload
}));
};
}
|
JavaScript
| 0 |
@@ -1,16 +1,21 @@
import %7B
+ del,
post %7D
@@ -39,16 +39,16 @@
quest';%0A
-
import %7B
@@ -248,16 +248,114 @@
tion';%0A%0A
+import %7B%0A removeMessage, removeMessagesByUser, removeAllMessages%0A%7D from './ChatActionCreators';%0A%0A
export f
@@ -924,16 +924,16 @@
error,%0A
-
@@ -964,8 +964,1129 @@
%0A %7D;%0A%7D%0A
+%0Aexport function deleteChatMessage(id) %7B%0A return (dispatch, getState) =%3E %7B%0A const jwt = tokenSelector(getState());%0A del(jwt, %60/v1/chat/$%7Bid%7D%60)%0A .then(res =%3E res.json())%0A .then(() =%3E dispatch(removeMessage(id)))%0A .catch(error =%3E dispatch(%7B%0A type: undefined,%0A error: true,%0A payload: error,%0A meta: %7B id %7D%0A %7D));%0A %7D;%0A%7D%0A%0Aexport function deleteChatMessagesByUser(userID) %7B%0A return (dispatch, getState) =%3E %7B%0A const jwt = tokenSelector(getState());%0A del(jwt, %60/v1/chat/user/$%7BuserID%7D%60)%0A .then(res =%3E res.json())%0A .then(() =%3E dispatch(removeMessagesByUser(userID)))%0A .catch(error =%3E dispatch(%7B%0A type: undefined,%0A error: true,%0A payload: error,%0A meta: %7B userID %7D%0A %7D));%0A %7D;%0A%7D%0A%0Aexport function deleteAllChatMessages() %7B%0A return (dispatch, getState) =%3E %7B%0A const jwt = tokenSelector(getState());%0A del(jwt, %60/v1/chat%60)%0A .then(res =%3E res.json())%0A .then(() =%3E dispatch(removeAllMessages()))%0A .catch(error =%3E dispatch(%7B%0A type: undefined,%0A error: true,%0A payload: error%0A %7D));%0A %7D;%0A%7D%0A
|
7e455447b5590c8716424cc38828c69a60b41941
|
verify method
|
src/algorithms/RsaHashedKeyAlgorithm.js
|
src/algorithms/RsaHashedKeyAlgorithm.js
|
/**
* Package dependencies
*/
const RSA = require('node-rsa')
const crypto = require('crypto')
/**
* Local dependencies
*/
const {buf2ab} = require('../encodings')
const CryptoKey = require('../CryptoKey')
const CryptoKeyPair = require('../CryptoKeyPair')
const KeyAlgorithm = require('./KeyAlgorithm')
const RsaKeyAlgorithm = require('./RsaKeyAlgorithm')
const OperationError = require('../errors/OperationError')
const InvalidAccessError = require('../errors/InvalidAccessError')
/**
* RsaHashedKeyAlgorithm
*/
class RsaHashedKeyAlgorithm extends RsaKeyAlgorithm {
/**
* constructor
*
* @param {object} algorithm
*/
constructor (algorithm) {
super(algorithm)
// validate hash
if (!(this.hash instanceof KeyAlgorithm)) {
throw new Error('hash of RsaHashedKeyAlgorithm must be a KeyAlgorithm')
}
}
/**
* sign
*
* @description
* Create an RSA digital signature
*
* @param {CryptoKey} key
* @param {BufferSource} data
*
* @returns {string}
*/
sign (key, data) {
if (key.type !== 'private') {
throw new InvalidAccessError()
}
try {
let pem = key.key
let signer = crypto.createSign('RSA-SHA256')
signer.update(data.toString())
return buf2ab(signer.sign(pem))
} catch (error) {
throw new OperationError()
}
}
/**
* verify
*
* @description
*
* @param {}
*
* @returns {}
*/
verify () {
// TODO
}
/**
* generateKey
*
* @description
* Generate an RSA key pair
*
* @param {RsaHashedKeyGenParams} params
* @returns {CryptoKeyPair}
*/
generateKey (params, extractable, usages) {
// validate usages
usages.forEach(usage => {
if (usage !== 'sign' && usage !== 'verify') {
throw new SyntaxError()
}
})
let keypair
// Generate RSA keypair
try {
// TODO
// - fallback on system OpenSSL + child_process
// - what is this bit option, where do we get the value from in this api?
let key = new RSA({b:512})
let {modulusLength,publicExponent} = params
keypair = key.generateKeyPair(modulusLength, publicExponent)
// cast error
} catch (error) {
throw new OperationError()
}
// cast params to algorithm
let algorithm = new RsaHashedKeyAlgorithm(params)
// instantiate publicKey
let publicKey = new CryptoKey({
type: 'public',
algorithm,
extractable: true,
usages: ['verify'],
key: keypair.exportKey('public')
})
// instantiate privateKey
let privateKey = new CryptoKey({
type: 'private',
algorithm,
// TODO is there a typo in the spec?
// it says "extractable" instead of "false"
extractable: false,
usages: ['sign'],
key: keypair.exportKey('private')
})
// return a new keypair
return new CryptoKeyPair({publicKey,privateKey})
}
/**
* importKey
*
* @description
* @param {}
* @returns {}
*/
importKey () {
// TODO
}
/**
* exportKey
*
* @description
* @param {}
* @returns {}
*/
exportKey () {
// TODO
}
}
/**
* Export
*/
module.exports = RsaHashedKeyAlgorithm
|
JavaScript
| 0.000002 |
@@ -134,16 +134,23 @@
%7Bbuf2ab
+,ab2buf
%7D = requ
@@ -1405,25 +1405,107 @@
* @param %7B
-%7D
+CryptoKey%7D key%0A * @param %7BBufferSource%7D signature%0A * @param %7BBufferSource%7D data
%0A *%0A * @
@@ -1505,32 +1505,39 @@
%0A * @returns %7B
+Boolean
%7D%0A */%0A verify
@@ -1538,31 +1538,348 @@
verify (
-) %7B%0A // TODO
+key, signature, data) %7B%0A if (key.type !== 'public') %7B%0A throw new InvalidAccessError()%0A %7D%0A%0A try %7B%0A let pem = key.key%0A let verifier = crypto.createVerify('RSA-SHA256')%0A%0A verifier.update(data)%0A return verifier.verify(pem, ab2buf(signature))%0A %7D catch (error) %7B%0A throw new OperationError()%0A %7D
%0A %7D%0A%0A
|
64c96a35f75aed9c062a5a6bac177d7f32a4fe21
|
Remove query from pagename
|
get-list/Special-Search-Pagename.js
|
get-list/Special-Search-Pagename.js
|
javascript:
(function() {
var defaultadd = "$1\\n";
var add = prompt('格式化列表:\n$1, 顯示為\nA, B,\n\n*[[$1]]\\n 顯示為\n*[[A]]\n*[[B]]', defaultadd);
if (add === null) {
return;
}
add = add.replace(/\\n/g, "<br>");
var prefix = (mw.config.get('wgServer') + mw.config.get('wgArticlePath')).replace(/^\/\//, "").replace("$1", "");
var text = "";
$(".mw-search-result-heading>a").each(function(i, e) {
var page = decodeURI(e.href.split(prefix)[1]);
text += add.replace(/\$1/g, page);
});
var win = window.open("", "Search Result");
win.document.body.innerHTML = text;
})();
|
JavaScript
| 0.000001 |
@@ -447,16 +447,58 @@
x)%5B1%5D);%0A
+%09%09page = page.replace(/%5C?.+$/, '', page);%0A
%09%09text +
|
42ada2bab3a9b5b22ae321e3a0350fb5e80b451e
|
Add error callback to geoloc
|
src/app/modules/home/home.controller.js
|
src/app/modules/home/home.controller.js
|
class HomeCtrl {
constructor(AppConstants, NetworkRequests, $localStorage) {
'ngInject';
this._NetworkRequests = NetworkRequests;
this._storage = $localStorage;
this.appName = AppConstants.appName;
// Detect recommended browsers
let isChrome = /Chrome/.test(navigator.userAgent) && /Google Inc/.test(navigator.vendor);
let isSafari = /Safari/.test(navigator.userAgent) && /Apple Computer/.test(navigator.vendor);
let isFirefox = /Firefox/.test(navigator.userAgent);
// If no recommended browser used, open modal
if(!isChrome && !isSafari && !isFirefox) {
$('#noSupportModal').modal({
backdrop: 'static',
keyboard: false
});
}
// Get position and closest nodes if no mainnet node in local storage
if (navigator.geolocation && !this._storage.selectedMainnetNode) {
// Get position
navigator.geolocation.getCurrentPosition((res) => {
// Get the closest nodes
this._NetworkRequests.getNearestNodes(res.coords).then((res) => {
// Pick a random node in the array
let node = res.data[Math.floor(Math.random()*res.data.length)];
// Set the node in local storage
this._storage.selectedMainnetNode = 'http://'+node.ip+':7778';
}, (err) => {
// If error it will use default node
console.log(err)
});
});
}
}
}
export default HomeCtrl;
|
JavaScript
| 0 |
@@ -70,16 +70,26 @@
lStorage
+, $timeout
) %7B%0A
@@ -1528,32 +1528,144 @@
%7D);%0A
+ %7D, (err) =%3E %7B%0A // If error it will use default node%0A console.log(err)%0A
%7D);%0A
@@ -1708,9 +1708,8 @@
omeCtrl;
-%0A
|
e4c62929a99d33f6c77261ca0e6cbd0d027bdaf9
|
Fix null callback for native notifications. Closes #103.
|
src/app/notification/native_provider.js
|
src/app/notification/native_provider.js
|
const { ipcMain } = require('electron');
const windowManager = require('../ui/window_manager');
class NativeNotificationProvider {
constructor() {
this.callbacks = new Map();
ipcMain.on('__displayNotificationCallback', (event, callback_info) => {
callback = this.callbacks.get(callback_info.id);
callback();
this.callbacks.delete(callback_info.id);
});
this.currentId = 1;
}
displayNotification(notification, callback) {
notification.id = this.currentId;
this.callbacks.set(this.currentId, callback);
windowManager.notifyWindow('__displayNotification', notification);
this.currentId += 1;
}
}
module.exports = NativeNotificationProvider;
|
JavaScript
| 0 |
@@ -265,32 +265,38 @@
%3E %7B%0A
+const
callback = this.
@@ -314,35 +314,32 @@
et(callback_info
-.id
);%0A c
@@ -396,19 +396,16 @@
ack_info
-.id
);%0A
|
710159d4f725d801d76000112c502df2977d0327
|
remove a *
|
bot/advisors.js
|
bot/advisors.js
|
const fetch = require('./fetch');
const process = require('process');
const _ = require('lodash');
class Advisors {
constructor() {
this.data = null;
this.lastFetch = null;
this.fetchActivity = fetch.curryType('Activity');
}
init(controller, bot) {
this.getData(true);
controller.hears(['nightfall'], ['direct_mention','direct_message'], (bot, message) => {
this.nightfall(this.data).then((nf) => {
bot.reply(message, nf);
})
});
controller.hears(['heroic strike', 'weekly heroic'], ['direct_mention','direct_message'], (bot, message) => {
this.heroicstrike(this.data).then((heroicstrike) => {
bot.reply(message, heroicstrike);
})
});
controller.hears(['daily mission'], ['direct_mention','direct_message'], (bot, message) => {
this.dailymission(this.data).then((daily) => {
bot.reply(message, daily);
})
});
controller.hears(['daily crucible'], ['direct_mention','direct_message'], (bot, message) => {
this.dailycrucible(this.data).then((daily) => {
bot.reply(message, daily);
})
});
controller.hears(['weekly crucible'], ['direct_mention','direct_message'], (bot, message) => {
this.weeklycrucible(this.data).then((weeklycrucible) => {
bot.reply(message, weeklycrucible);
})
});
controller.hears(['bust it'], ['direct_mention','direct_message'], (bot, message) => {
this.getData(true).then( () => {
bot.reply(message, 'https://halloweenshindig.files.wordpress.com/2015/06/gb_bustin1.gif');
});
});
}
getData(bustCache) {
if(bustCache || this.data == null) {
return fetch(null, null, 'https://www.bungie.net/Platform/Destiny/Advisors/V2/').then(
(data) => {
return this.parse(data);
}
);
}else{
return this.parse(data);
}
}
parse(data) {
let parsed = _.get(data, 'Response.data.activities', {});
this.data = parsed;
return parsed;
}
skullList(modifiers) {
return _.map(_.get(modifiers, '[0].skulls', []), (skull) => {
return {
fallback: '*'+skull.displayName+'*'+'\n'+skull.description+'\n\n',
title: skull.displayName,
text: skull.description,
color: 'danger'
// thumb_url: 'https://www.bungie.net'+skull.icon
};
});
}
nightfall(data) {
let id = _.get(data, 'nightfall.display.activityHash', '');
return this.fetchActivity(id).then(
(rawactivity) => {
let activity = _.get(rawactivity, 'Response.data.activity', {});
let attachments = _.concat(
[{
'title': 'Strike',
'text': _.get(activity, 'activityName', 'Unknown')+'*' }],
this.skullList(_.get(data, 'nightfall.extended.skullCategories',[]))
);
return {
'attachments': attachments
};
}
);
}
trials(data) {
}
heroicstrike(data) {
let id = _.get(data, 'heroicstrike.display.activityHash', '');
let message = '';
return this.fetchActivity(id).then(
(rawactivity) => {
let activity = _.get(rawactivity, 'Response.data.activity', {});
message += 'This week\'s weekly heroic is: *'+_.get(activity, 'activityName', 'Unknown')+'*'+'\n\n';
return {
'text': message,
'attachments': this.skullList(_.get(data, 'heroicstrike.extended.skullCategories',[]))
};
}
);
}
dailymission(data) {
let id = _.get(data, 'dailychapter.display.activityHash', '');
let message = 'Today\'s daily mission:\n\n';
return this.fetchActivity(id).then(
(rawactivity) => {
let activity = _.get(rawactivity, 'Response.data.activity', {});
message += '*'+_.get(activity, 'activityName', 'Unknown')+'*'+'\n\n';
return message;
}
);
}
dailycrucible(data) {
let id = _.get(data, 'dailycrucible.display.activityHash', '');
let message = 'Daily Crucible is: ';
return this.fetchActivity(id).then(
(rawactivity) => {
let activity = _.get(rawactivity, 'Response.data.activity', {});
message += '*'+_.get(activity, 'activityName', 'Unknown')+'*'+'\n\n';
return message;
}
);
}
weeklycrucible(data) {
let id = _.get(data, 'weeklycrucible.display.activityHash', '');
let message = 'Weekly Crucible is: ';
return this.fetchActivity(id).then(
(rawactivity) => {
let activity = _.get(rawactivity, 'Response.data.activity', {});
message += '*'+_.get(activity, 'activityName', 'Unknown')+'*'+'\n\n';
return message;
}
);
}
xur(data) {
}
poe(data) {
}
coe(data) {
}
}
module.exports = Advisors;
|
JavaScript
| 0.000026 |
@@ -3122,20 +3122,37 @@
nknown')
-+'*'
+ %0A
%7D%5D,%0A
|
46d047792d4837fa74e952d6841218faa9cfc03e
|
improve onRemove
|
bouncemarker.js
|
bouncemarker.js
|
/**
* Copyright (C) 2013 Maxime Hadjinlian <[email protected]>
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* - Redistributions of source code must retain the above copyright notice,
* this list of conditions and the following disclaimer.
*
* - Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
(function () {
// Retain the value of the original onAdd and onRemove functions
var originalOnAdd = L.Marker.prototype.onAdd;
var originalOnRemove = L.Marker.prototype.onRemove;
// Add bounceonAdd options
L.Marker.mergeOptions({
bounceOnAdd: false,
bounceOnAddOptions: {
duration: 1000,
height: -1
},
bounceOnAddCallback: function() {}
});
L.Marker.include({
_toPoint: function (latlng) {
return this._map.latLngToContainerPoint(latlng);
},
_toLatLng: function (point) {
return this._map.containerPointToLatLng(point);
},
_motionStep: function (timestamp, opts) {
var self = this;
var timePassed = new Date() - opts.start;
var progress = timePassed / opts.duration;
if (progress > 1) {
progress = 1;
}
var delta = self._easeOutBounce(progress);
opts.step(delta);
if (progress === 1) {
opts.end();
return;
}
L.Util.requestAnimFrame(function(timestamp) {
self._motionStep(timestamp, opts);
});
},
_bounceMotion: function (duration, callback) {
var original = L.latLng(this._origLatlng);
var start_y = this._dropPoint.y;
var start_x = this._dropPoint.x;
var distance = this._point.y - start_y;
var self = this;
L.Util.requestAnimFrame(function(timestamp) {
self._motionStep(timestamp, {
delay: 10,
duration: duration || 1000, // 1 sec by default
start: new Date(),
step: function (delta) {
self._dropPoint.y =
start_y
+ (distance * delta)
- (self._map.project(self._map.getCenter()).y - self._origMapCenter.y);
self._dropPoint.x =
start_x
- (self._map.project(self._map.getCenter()).x - self._origMapCenter.x);
self.setLatLng(self._toLatLng(self._dropPoint));
},
end: function () {
self.setLatLng(original);
if (typeof callback === "function") callback();
}
});
});
},
// Many thanks to Robert Penner for this function
_easeOutBounce: function (pos) {
if ((pos) < (1 / 2.75)) {
return (7.5625 * pos * pos);
} else if (pos < (2 / 2.75)) {
return (7.5625 * (pos -= (1.5 / 2.75)) * pos + 0.75);
} else if (pos < (2.5 / 2.75)) {
return (7.5625 * (pos -= (2.25 / 2.75)) * pos + 0.9375);
} else {
return (7.5625 * (pos -= (2.625 / 2.75)) * pos + 0.984375);
}
},
// Bounce : if options.height in pixels is not specified, drop from top.
// If options.duration is not specified animation is 1s long.
bounce: function(options, endCallback) {
this._origLatlng = this.getLatLng();
this._bounce(options, endCallback);
},
_bounce: function (options, endCallback) {
if (typeof options === "function") {
endCallback = options;
options = null;
}
options = options || {duration: 1000, height: -1};
//backward compatibility
if (typeof options === "number") {
options.duration = arguments[0];
options.height = arguments[1];
}
// Keep original map center
this._origMapCenter = this._map.project(this._map.getCenter());
this._dropPoint = this._getDropPoint(options.height);
this._bounceMotion(options.duration, endCallback);
},
// This will get you a drop point given a height.
// If no height is given, the top y will be used.
_getDropPoint: function (height) {
// Get current coordidates in pixel
this._point = this._toPoint(this._origLatlng);
var top_y;
if (height === undefined || height < 0) {
top_y = this._toPoint(this._map.getBounds()._northEast).y;
} else {
top_y = this._point.y - height;
}
return new L.Point(this._point.x, top_y);
},
onAdd: function (map) {
this._map = map;
// Keep original latitude and longitude
this._origLatlng = this._latlng;
// We need to have our drop point BEFORE adding the marker to the map
// otherwise, it would create a flicker. (The marker would appear at final
// location then move to its drop location, and you may be able to see it.)
if (this.options.bounceOnAdd === true) {
// backward compatibility
if (typeof this.options.bounceOnAddDuration !== "undefined") {
this.options.bounceOnAddOptions.duration = this.options.bounceOnAddDuration;
}
// backward compatibility
if (typeof this.options.bounceOnAddHeight !== "undefined") {
this.options.bounceOnAddOptions.height = this.options.bounceOnAddHeight;
}
this._dropPoint = this._getDropPoint(this.options.bounceOnAddOptions.height);
this.setLatLng(this._toLatLng(this._dropPoint));
}
// Call leaflet original method to add the Marker to the map.
originalOnAdd.call(this, map);
if (this.options.bounceOnAdd === true) {
this._bounce(this.options.bounceOnAddOptions, this.options.bounceOnAddCallback);
}
},
onRemove: function (map) {
clearInterval(this._intervalId);
originalOnRemove.call(this, map);
}
});
})();
|
JavaScript
| 0 |
@@ -2367,24 +2367,44 @@
%7D%0A%0A
+ self._animationId =
L.Util.requ
@@ -6643,41 +6643,227 @@
-clearInterval(this._interval
+// We may have modified the marker; so we need to place it where it%0A // belongs so next time its coordinates are not changed.%0A this.setLatLng(this._origLatlng);%0A cancelAnimationFrame(this._animation
Id);%0A
+%0A
|
09e92cedfc4cd084a8a1e364998a6fe4f0daa325
|
Update to latest JBDS snapshot
|
browser/main.js
|
browser/main.js
|
'use strict';
import angular from 'angular';
import uiRouter from 'angular-ui-router';
import base64 from 'angular-base64';
import acctCtrl from './pages/account/controller';
import confCtrl from './pages/confirm/controller';
import instCtrl from './pages/install/controller';
import startCtrl from './pages/start/controller';
import progressBar from './directives/progressBar';
import breadcrumb from './directives/breadcrumb';
import InstallerDataService from './services/data';
import VirtualBoxInstall from './model/virtualbox';
import JdkInstall from './model/jdk-install';
import JbdsInstall from './model/jbds';
import VagrantInstall from './model/vagrant';
import CygwinInstall from './model/cygwin';
import CDKInstall from './model/cdk';
let mainModule =
angular.module('devPlatInstaller', ['ui.router', 'base64'])
.controller(acctCtrl.name, acctCtrl)
.controller(confCtrl.name, confCtrl)
.controller(instCtrl.name, instCtrl)
.controller(startCtrl.name, startCtrl)
.factory('installerDataSvc', InstallerDataService.factory)
.directive(progressBar.name, progressBar)
.directive(breadcrumb.name, ['$state', breadcrumb])
.config( ["$stateProvider", "$urlRouterProvider", ($stateProvider, $urlRouterProvider) => {
$urlRouterProvider.otherwise('/account');
$stateProvider
.state('account', {
url: '/account',
controller: 'AccountController as acctCtrl',
templateUrl: 'pages/account/account.html',
data: {
displayName: 'Install Setup'
}
})
.state('confirm', {
url: '/confirm',
controller: 'ConfirmController as confCtrl',
templateUrl: 'pages/confirm/confirm.html',
data: {
displayName: 'Confirmation'
}
})
.state('install', {
url: '/install',
controller: 'InstallController as instCtrl',
templateUrl: 'pages/install/install.html',
data: {
displayName: 'Download & Install'
}
})
.state('start', {
url: '/start',
controller: 'StartController as startCtrl',
templateUrl: 'pages/start/start.html',
data: {
displayName: 'Get Started'
}
});
}])
.run( ['$rootScope', '$location', '$timeout', 'installerDataSvc', ($rootScope, $location, $timeout, installerDataSvc) => {
installerDataSvc.addItemToInstall(
'cdk',
new CDKInstall(installerDataSvc,
$timeout,
'https://developers.redhat.com/download-manager/jdf/file/cdk-2.0.0-beta3.zip?workflow=direct',
'https://developers.redhat.com/download-manager/jdf/file/rhel-cdk-kubernetes-7.2-6.x86_64.vagrant-virtualbox.box?workflow=direct',
'https://github.com/openshift/origin/releases/download/v1.1.0.1/openshift-origin-v1.1.0.1-bf56e23-windows-amd64.zip',
null)
);
installerDataSvc.addItemToInstall(
'vagrant',
new VagrantInstall(installerDataSvc,
'https://github.com/redhat-developer-tooling/vagrant-distribution/archive/1.7.4.zip',
null)
);
installerDataSvc.addItemToInstall(
'virtualbox',
new VirtualBoxInstall('5.0.8',
'103449',
installerDataSvc,
'http://download.virtualbox.org/virtualbox/${version}/VirtualBox-${version}-${revision}-Win.exe',
null)
);
installerDataSvc.addItemToInstall(
'jdk',
new JdkInstall(installerDataSvc,
'http://cdn.azulsystems.com/zulu/bin/zulu1.8.0_66-8.11.0.1-win64.zip',
null)
);
installerDataSvc.addItemToInstall(
'jbds',
new JbdsInstall(installerDataSvc,
'https://devstudio.redhat.com/9.0/snapshots/builds/devstudio.product_9.0.mars/latest/all/jboss-devstudio-9.1.0.Beta1-v20151122-1948-B143-installer-standalone.jar',
null)
);
installerDataSvc.addItemToInstall(
'cygwin',
new CygwinInstall(installerDataSvc,
'https://cygwin.com/setup-x86_64.exe',
null)
);
}]);
export default mainModule;
|
JavaScript
| 0 |
@@ -4636,21 +4636,21 @@
0151
-122-1948-B143
+203-0439-B156
-ins
|
98cd41ffc67d8da78ff1ad088ede2d0f4e82cab7
|
Remove debug marker from the map
|
src/components/LeafletMap/LeafletMap.js
|
src/components/LeafletMap/LeafletMap.js
|
import React from 'react'
import Leaflet from 'leaflet'
import { Map, WMSTileLayer, TileLayer, Marker, Popup, ZoomControl, ScaleControl } from 'react-leaflet'
require('leaflet/dist/leaflet.css')
Leaflet.Icon.Default.imagePath = '//cdnjs.cloudflare.com/ajax/libs/leaflet/1.0.0/images/'
const LeafletMap = ({ mapProperties, showMenu, showSidebarRight, layers, orderByLayerOrder }) => {
// initial position and zoom
const position = mapProperties ? [mapProperties.initialCoordinates.lat, mapProperties.initialCoordinates.lng] : [0,0]
const zoom = mapProperties ? mapProperties.initialCoordinates.zoom : 10
// Geoserver config
const ENDPOINT = __API__
const IMAGE_FORMAT = 'image/png'
// DEBUG
showSidebarRight = true
// map class
let leafletMapClassName = 'module-leafletMap'
if (showMenu) {
leafletMapClassName += ' sidebar-left-opened'
}
if (showSidebarRight) {
leafletMapClassName += ' sidebar-right-opened'
}
return (
<div className={leafletMapClassName}>
<Map center={position} zoom={zoom} zoomControl={false}>
{/*base layer OSM*/}
<TileLayer
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
/>
{/*state highlight layer*/}
<WMSTileLayer
url={ENDPOINT}
layers={"plataforma:retangulo"}
styles={"plataforma:retangulo"}
format={IMAGE_FORMAT}
transparent={true}
opacity={0.7}
/>
{/*active layers*/}
{orderByLayerOrder(layers).map((layer, index) => {
return (
<WMSTileLayer
url={ENDPOINT}
layers={layer.layerName}
styles={layer.styles[layer.selectedLayerStyleId].name}
format={IMAGE_FORMAT}
key={index}
transparent={true}
/>
)
})}
{/*DEBUG*/}
<Marker position={position}>
<Popup>
<span>Hello world</span>
</Popup>
</Marker>
{/*Other controls*/}
<ScaleControl position="bottomleft"/>
<ZoomControl position="bottomright"/>
</Map>
</div>
)
}
export default LeafletMap
|
JavaScript
| 0.000001 |
@@ -2320,16 +2320,19 @@
+%7B/*
%3CMarker
@@ -2483,16 +2483,19 @@
/Marker%3E
+*/%7D
%0A%0A
|
f23a5d2e990c79bda99d346fc4662996b0c2a0e1
|
Set products state with every style update
|
src/components/VehicleResults/Result.js
|
src/components/VehicleResults/Result.js
|
import React, { Component, PropTypes } from 'react';
import cx from 'classnames';
import VehicleStore from '../../stores/VehicleStore';
import s from './Result.scss';
import withStyles from '../../decorators/withStyles';
import PartResults from '../PartResults';
@withStyles(s)
class Result extends Component {
static propTypes = {
result: PropTypes.object.isRequired,
activeIndex: PropTypes.number,
className: PropTypes.string,
fitments: PropTypes.array,
iconParts: PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.array,
]),
};
constructor() {
super();
this.state = {
products: [],
};
this.updateStyle = this.updateStyle.bind(this);
}
componentWillReceiveProps(props) {
const products = [];
if (props.fitments && props.fitments.length > 0) {
props.fitments.map((ft) => {
if (!ft.product || !ft.product.categories || ft.product.categories.length === 0) {
return;
}
console.log(ft);
const prod = ft.product.categories.filter((p) => p.id === props.result.category.id);
if (prod.length > 0) {
ft.product.iconLayer = this.props.iconParts ? this.props.iconParts[ft.product.part_number] : '';
products.push(ft.product);
}
});
}
if (products.length !== this.state.products.length) {
this.setState({
products,
});
}
}
updateStyle(e) {
e.preventDefault();
VehicleStore.fetchFitments(this.props.result, this.refs.style.value);
}
renderStyles() {
if (
!this.props.result.style_options ||
this.props.result.style_options.length === 0
) {
return null;
}
if (this.props.result.style_options[0].style.toLowerCase() === 'all') {
return null;
}
return (
<div className={'form-group'}>
<select ref="style" onChange={this.updateStyle} className="form-control">
<option value="">- Select Style -</option>
{this.props.result.style_options.map((so, i) => <option key={i}>{so.style.toUpperCase()}</option>)}
</select>
</div>
);
}
render() {
if (
!this.props.activeIndex ||
!this.props.result.category
) {
return <div></div>;
}
return (
<div
className={cx(
s.root,
this.props.className,
(this.props.activeIndex === this.props.result.category.id) ? s.active : '',
)}
>
<div className={s.header}>
<span>{this.props.result.category.title}</span>
{this.renderStyles()}
</div>
<PartResults className={`test`} parts={this.state.products} iconParts={this.props.iconParts} />
</div>
);
}
}
export default Result;
|
JavaScript
| 0 |
@@ -936,29 +936,8 @@
%09%09%7D%0A
-%09%09%09%09console.log(ft);%0A
%09%09%09%09
@@ -1226,38 +1226,11 @@
gth
-!== this.state.products.length
+%3E 0
) %7B%0A
@@ -1317,17 +1317,16 @@
ault();%0A
-%0A
%09%09Vehicl
|
498013ccd5ed28efe47fafd7680a765373239139
|
comment cleanup
|
src/components/form/RadioButtonGroup.js
|
src/components/form/RadioButtonGroup.js
|
// dependencies
//
import React from 'react';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';
/**
* The RadioButtonGroup component
*/
class RadioButtonGroup extends React.Component {
/**
* Construct the component instance
* @param {Object} props The component props
*/
constructor(props) {
super(props);
// generate a unique ID for this element (used to tie the label to the
// input elements)
//
this.id = uniqueId('form-radiobuttongroup-');
// build a list of permitted values from the options
//
this.permittedValues = this.props.options.map((opt) => `${opt.value}`);
// initialize the component state
//
this.state = {
value: this.isPermittedValue(this.props.value)
? `${this.props.value}`
: `${this.props.options[0].value}`,
};
// bind `this` to the onChange event handler
//
this.onChange = this.onChange.bind(this);
}
/**
* Handle a change to the input elements
* @param {Object} event The event object
*/
onChange(event) {
// get the current value & make sure it's a string
//
const value = `${event.target.value}`;
// has the value changed? if so, then update the state & call the
// onChange handler
//
if (value !== this.state.value) {
// update the component state
//
this.setState({ value });
// do we have an onChange handler? if so, call it
//
if (this.props.onChange) {
this.props.onChange(value);
}
}
}
/**
* Check a value to see if it's one of the permitted values
* @param {String} value The value to check
* @return {Boolean} True if it's a permitted value; false otherwise
*/
isPermittedValue(value) {
return this.permittedValues.findIndex((val) => val === `${value}`) !== -1;
}
/**
* Render the component
* @return {React.Element} The React element describing the component
*/
render() {
// get the important values from the component properties
//
const { label, options } = this.props;
const labelElement = label
? (<label
htmlFor={this.id}
className={classnames('control-label', {
[`col-xs-${this.context.labelColumns}`]: this.context.labelColumns,
})}
>{label}</label>)
: null;
let radios = options.map((opt) => (
<div key={uniqueId('form-radiobuttongroup-option-')} className="radio">
<label>
<input
type="radio"
name={this.id}
value={opt.value}
checked={this.state.value === opt.value}
onChange={this.onChange}
/>
<span>{opt.name}</span>
</label>
</div>
));
if (this.context.labelColumns) {
radios = (
<div
className={classnames(
'form-radiobuttongroup-input-columns',
`col-xs-${12 - this.context.labelColumns}`
)}
>
{radios}
</div>
);
}
// render the component & return it
//
return (
<div className="form-group">
{labelElement}
{radios}
</div>
);
}
}
// define the property types for the component
//
RadioButtonGroup.propTypes = {
label: React.PropTypes.string,
options: React.PropTypes.array,
value: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
]),
onChange: React.PropTypes.func,
};
// set the context types for values received from higher up the food chain
//
RadioButtonGroup.contextTypes = {
labelColumns: React.PropTypes.number,
};
// export the component
//
export default RadioButtonGroup;
|
JavaScript
| 0 |
@@ -2324,16 +2324,81 @@
props;%0A%0A
+ // render the label element for the component%0A //%0A
@@ -2420,24 +2420,24 @@
ent = label%0A
-
@@ -2696,16 +2696,96 @@
null;%0A%0A
+ // render the set of radio button elements for the component%0A //%0A
@@ -3307,24 +3307,160 @@
));%0A%0A
+ // do we have columns for this component? if so, wrap the radio buttons%0A // in a div to implement the columns%0A //%0A
if (
@@ -3815,32 +3815,33 @@
);%0A %7D%0A
+%0A
// rende
@@ -3838,32 +3838,38 @@
// render the
+whole
component & retu
@@ -4046,18 +4046,15 @@
%7D%0A%0A/
-/ define t
+**%0A * T
he p
@@ -4085,17 +4085,36 @@
mponent%0A
-/
+ * @type %7BObject%7D%0A *
/%0ARadioB
@@ -4372,15 +4372,15 @@
;%0A%0A/
-/ set t
+**%0A * T
he c
@@ -4400,55 +4400,42 @@
for
-values received from higher up the food chain%0A/
+the component%0A * @type %7BObject%7D%0A *
/%0ARa
|
46adee5bf4705577689e1539f3457dad52b76e45
|
Update common.js
|
07-notifications/code/public/js/common.js
|
07-notifications/code/public/js/common.js
|
const serverUrl = 'http://localhost:3000/';
function apiClient(url, options) {
options = options || {};
if (!('fetch' in window)) {
// Real fetch polyfill: https://github.com/github/fetch
return new Promise( (resolve, reject) => {
let request = new XMLHttpRequest();
request.open(options.method || 'get', url);
request.setRequestHeader('Content-type', 'application/json');
request.onload = () => {
resolve(response());
};
request.onerror = reject;
request.send(options.body);
function response() {
return {
ok: (request.status/200|0) == 1, // 200-299
status: request.status,
statusText: request.statusText,
url: request.responseURL,
clone: response,
text: () => Promise.resolve(request.responseText),
json: () => Promise.resolve(request.responseText).then(JSON.parse),
blob: () => Promise.resolve(new Blob([request.response]))
};
};
});
}
return fetch(url, options);
}
function saveExpense(expense, cb) {
apiClient(`${serverUrl}api/expense/${expense.id || ''}`, {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(expense)
})
.then(response => response.json())
.then(cb);
}
function deleteExpenses(cb) {
apiClient(`${serverUrl}api/expense`, { method: 'DELETE' })
.then(response => response.json())
.then(cb)
.catch(() => alert("Error deleting expenses"));
}
function getExpenses(cb) {
apiClient(`${serverUrl}api/expense`)
.catch(() => caches.match(`${serverUrl}api/expense`))
.then(response => response.json())
.then(cb);
}
function getExpense(expenseId, cb) {
apiClient(`${serverUrl}api/expense/${expenseId}`)
.catch(() => caches.match(`${serverUrl}api/expense/${expenseId}`))
.then(response => response.json())
.then(cb);
}
function createNewExpense() {
return {
name: 'Nombre',
details: []
};
}
function getExpenseTotal(expense) {
let total = 0;
if (expense && expense.details) {
expense.details.forEach( item => {
total += item.cost;
});
}
return total;
}
function getTotal(expenses) {
let total = 0;
expenses.forEach( expense => {
total += getExpenseTotal(expense);
});
return total;
}
function share(title) {
const url = window.location.href;
if (navigator.share) {
navigator.share({
title: title,
url: url,
})
.then(() => console.log('Successful share'))
.catch((error) => console.log('Error sharing', error));
} else {
window.open("https://twitter.com/intent/tweet?text=" + encodeURIComponent(title) + "&url=" + encodeURIComponent(url), '_blank');
}
}
let swRegistration;
function displayNotification(title, body) {
if ('serviceWorker' in navigator && 'PushManager' in window) {
navigator.serviceWorker.getRegistration().then(function(reg) {
swRegistration = reg;
swRegistration.pushManager.getSubscription()
.then(function (subscription) {
if (Notification.permission === 'granted') {
createNotification(title, body);
} else {
if (Notification.permission !== 'denied') {
subscribeUser().then(function (subscription) {
if (Notification.permission === "granted") {
createNotification(title, body);
}
})
}
}
});
});
}
}
function createNotification(title, body) {
const options = {
body: body,
icon: 'img/logo-512.png',
vibrate: [100, 50, 100]
};
swRegistration.showNotification(title, options);
}
const VAPID_VALID_PUBLIC_KEY = "BGUjD5uW7jQs1YXTppItASnTCJvtIkjxvRJYqq_QKusQLsVib7ESQhyWcSXnxp0YtHjeiBB30pUC0HJrGFcCRSQ";
function subscribeUser() {
return swRegistration.pushManager.subscribe({
userVisibleOnly: true,
applicationServerKey: urlB64ToUint8Array(VAPID_VALID_PUBLIC_KEY)
})
}
|
JavaScript
| 0.000001 |
@@ -4283,96 +4283,56 @@
= %22
-BGUjD5uW7jQs1YXTppItASnTCJvtIkjxvRJYqq_QKusQLsVib7ESQhyWcSXnxp0YtHjeiBB30pUC0HJrGFcCRSQ%22
+Reemplazar por la public key del paso anterior%22;
;%0Afu
|
c53875278738c9ccdfedd735605e06775d5b2924
|
Store last connected client count interval
|
util/WebsocketServer.js
|
util/WebsocketServer.js
|
const socketIO = require("socket.io");
function WebsocketServer(app, httpServer) {
var server = socketIO(httpServer);
console.log("Websocket server attached to HTTP server.");
let obj = {
server: server,
connectedClients: 0,
setup: function() {
var a = this;
this.server.on('connection', socket => {
a.connectedClients++;
socket.on('disconnect', function () {
a.connectedClients--;
});
});
setInterval(() => a.checkUserCount(), 1000);
},
sendConnectedClientBroadcast: function() {
this.broadcast("user_change", { count: this.connectedClients });
},
broadcast: function(name, payload) {
this.server.sockets.emit(name, payload);
},
checkUserCount: function() {
if(!this.lastConnectedClientBroadcastCount || this.lastConnectedClientBroadcastCount != this.connectedClients) this.sendConnectedClientBroadcast();
}
}
obj.setup();
return obj;
}
WebsocketServer.prototype = Object.create(WebsocketServer.prototype);
module.exports = WebsocketServer;
|
JavaScript
| 0 |
@@ -1004,16 +1004,109 @@
Clients)
+ %7B%0A this.lastConnectedClientBroadcastCount = connectedClients;%0A
this.se
@@ -1131,24 +1131,38 @@
roadcast();%0A
+ %7D%0A
%7D%0A
|
f8b4638d44ef1903486d48b4ec4ca309af61c1e4
|
Update server.js
|
src/api/server.js
|
src/api/server.js
|
'use strict';
const koa = require('koa');
const router = require('./router');
const bodyParser = require('koa-body');
const compress = require('koa-compress');
const responseTime = require('koa-response-time');
const kcors = require('kcors');
const config = require('../config/config').globalConfig;
const app = koa();
app.use(compress());
app.use(responseTime());
app.use(kcors());
app.use(bodyParser({
jsonLimit: '100mb'
}));
if (config.server && config.server.middleware) {
config.server.middleware.forEach(middleware => app.use(middleware));
}
app.use(router.routes());
module.exports = app;
|
JavaScript
| 0.000001 |
@@ -374,16 +374,97 @@
e(kcors(
+Object.assign(%7B%7D, %7Bcredentials: true%7D, config.server ? config.server.cors : null)
));%0Aapp.
|
6ad67987cd95ca629ba1ade64628dc80aef76f31
|
Comment out isomorphic fetch because of error message
|
client/app/lib/Form/actions/submitAjaxForm.js
|
client/app/lib/Form/actions/submitAjaxForm.js
|
const submitAjaxFormRequest = function(formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_REQUEST',
formObjectName
}
}
const submitAjaxFormFailure = function(error, formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_FAILURE',
error,
formObjectName
}
}
const submitAjaxFormSuccess = function(response, formObjectName) {
return {
type: 'SUBMIT_AJAX_FORM_SUCCESS',
response,
formObjectName
}
}
export default function submitAjaxForm(url, data, formObject) {
const formObjectName = formObject.constructor.name
return function(dispatch) {
dispatch(submitAjaxFormRequest(formObjectName))
const fetch = require('isomorphic-fetch') // regular import breaks in SSR
return fetch(url + '.json', {
method: (data.get('_method')),
body: data,
credentials: 'same-origin'
}).then(
function(response) {
const { status, statusText } = response
if (status >= 400) {
dispatch(submitAjaxFormFailure(response, formObjectName))
throw new Error(`Submit Ajax Form Error ${status}: ${statusText}`)
}
return response.json()
}
).then(json => {
console.log('json', json)
dispatch(submitAjaxFormSuccess(json, formObjectName))
})
}
}
|
JavaScript
| 0 |
@@ -629,24 +629,26 @@
Name))%0A%0A
+//
const fetch
|
b675cb76427a1c4a60b35758f4100b2eb47f0bf4
|
fix break detail nav
|
App/Containers/BreakDetailScreen.js
|
App/Containers/BreakDetailScreen.js
|
import React from 'react'
import { ScrollView, View, Text, Image, TouchableOpacity } from 'react-native'
import PurpleGradient from '../Components/PurpleGradient'
import { NavigationActions } from 'react-navigation'
import { connect } from 'react-redux'
// Add Actions - replace 'Your' with whatever your reducer is called :)
// import YourActions from '../Redux/YourRedux'
import { Images } from '../Themes'
import styles from './Styles/BreakDetailScreenStyle'
class BreakDetail extends React.Component {
static navigationOptions = {
tabBar: {
label: 'Schedule',
icon: ({ focused }) => (
<Image source={focused ? Images.activeScheduleIcon : Images.inactiveScheduleIcon} />
)
}
}
goBack = () => {
this.props.navigation.dispatch(NavigationActions.back())
}
render () {
return (
<PurpleGradient style={styles.linearGradient}>
<ScrollView>
<View style={styles.container}>
<TouchableOpacity style={styles.backButton} onPress={this.goBack}>
<Image style={styles.backButtonIcon} source={Images.arrowIcon} />
<Text style={styles.backButtonText}>Back</Text>
</TouchableOpacity>
<View style={styles.cardShadow1} />
<View style={styles.cardShadow2} />
<View style={styles.card}>
<View style={styles.mainImageContainer}>
<Image style={styles.mainImage} source={Images.lunch} />
<View style={styles.mainHeadingContainer}>
<Text style={styles.breakHeading}>
{this.props.type.toUpperCase()} BREAK
</Text>
<Text style={styles.breakDuration}>
12:00 - 1:00<Text style={styles.meridiem}>PM</Text>
</Text>
</View>
</View>
<View style={styles.content}>
<Text style={styles.heading}>
Lunch Options
</Text>
<Text style={styles.description}>
{`\u2022 Green Eggs & Ham On Rye\n`}
{`\u2022 Green Eggs & Ham On Rye\n`}
{`\u2022 Green Eggs & Ham On Rye\n`}
{`\u2022 Green Eggs & Ham On Rye\n`}
{`\u2022 Green Eggs & Ham On Rye\n`}
{`\u2022 Green Eggs & Ham On Rye`}
</Text>
<Text style={styles.heading}>
Vegan Options
</Text>
<Text style={styles.description}>
{`\u2022 Tap Water\n`}
{`\u2022 Assorted Leaves`}
</Text>
</View>
</View>
</View>
</ScrollView>
</PurpleGradient>
)
}
}
const mapStateToProps = (state) => {
return {
...state.schedule.selectedEvent
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(BreakDetail)
|
JavaScript
| 0 |
@@ -546,19 +546,9 @@
bBar
-: %7B%0A l
+L
abel
@@ -569,11 +569,15 @@
- i
+tabBarI
con:
@@ -596,18 +596,16 @@
%7D) =%3E (%0A
-
%3CI
@@ -695,17 +695,9 @@
- )%0A %7D
+)
%0A %7D
|
3542aa6f70039665e118de4a9848e897bb5397f4
|
Make youtube-dl exec buffer unlimited
|
downloader.js
|
downloader.js
|
const fs = require('fs');
const path = require('path');
const progress = require('progress-stream');
const Promise = require('yaku/lib/yaku.core');
const shortId = require('shortid');
const youtubeDl = require('youtube-dl');
// Default download options
const defaultOptions = {
directory: path.join(__dirname, 'downloads'),
args: [],
binDir: path.join(require('electron').remote.app.getPath('userData'), 'bin')
};
/**
* Download the video at the given URL
*
* @param {String} url The URL of the video
* @param {String} options.directory The path to set as youtube-dl's working directory
* @param {String} options.filename The output filename
* @param {Array} options.args Args to pass to youtube-dl. Format: ['--format=22', '...']
* @param {Array} options.binDir The directory that has the youtube-dl binary
* @return {Stream} The download progress stream
*/
function download(url, options = {}) {
options = Object.assign({}, defaultOptions, options);
const execOptions = {
cwd: options.directory,
binDir: options.binDir,
maxBuffer: 1024 * (1024 * 2) // 2MB
};
const downloadPath = path.join(
options.directory,
options.filename ? options.filename : (shortId.generate() + '.part')
);
const progressStream = progress({ time: 300 });
const fileStream = fs.createWriteStream(downloadPath);
const downloadStream = youtubeDl(url, options.args, execOptions);
let hasDownloadError = false;
let wasCancelled = false;
let filename = '';
// Emitted when the video info is initially retrieved
downloadStream.on('info', info => {
// Set the filename for later rename
filename = info._filename;
// Set the length (for the progress stream to work) and emit the info
progressStream.setLength(info.size);
progressStream.emit('info', info, downloadPath);
});
// Emitted on error from youtube-dl or http download
downloadStream.on('error', err => {
// Set the error status (for later clean up)
hasDownloadError = true;
// Emit the error and close the file stream
progressStream.emit('error', err);
fileStream.end();
});
// Emitted when the download/file being resumed is complete
downloadStream.on('complete', item => {
progressStream.emit('resume-complete', item);
});
// Emitted when the current video in a playlist ends and the next video should begin.
// Call download() to with the video object to download the next video
downloadStream.on('next', video => {
progressStream.emit('next-video', video);
});
// Emitted when the file stream is closed, either when the download is complete
// or when there was an error downloading
fileStream.on('finish', () => {
// Clean up if there was an error or the download was aborted
if (hasDownloadError || wasCancelled) {
fs.unlink(downloadPath, err => {
if (err) {
console.error('Error deleting part download file', err);
} else {
progressStream.emit('part-file-deleted');
}
});
return;
}
// The download was successful, rename the file to it's actual name
const newName = path.join(options.directory, filename);
fs.rename(downloadPath, newName, err => {
if (err) {
console.error('Error renaming downloaded file', err);
} else {
progressStream.emit('file-renamed', newName);
}
});
});
// Manually abort the download
progressStream.cancel = function cancel() {
// Assuming the following abort() call will be successful. Set here early because abort()
// will trigger end() on the file stream, which will call the fileStream.on('finish')
// handler which needs to know if the download was cancelled.
wasCancelled = true;
downloadStream._source.stream.abort();
// Tried wrapping this in a .on('aborted') event for the stream, but the event
// doesn't seem to be triggered with .abort() is called.
progressStream.emit('cancelled');
};
// Pipe the download stream (an HTTP response) to the progress stream and then to a file
downloadStream.pipe(progressStream).pipe(fileStream);
return progressStream;
}
/**
* Get the info of the video at the given url
*
* @param {String} url The URL of the video
* @param {Array} options.args Args to pass to youtube-dl. Format: ['--format=22', '...']
* @param {Array} options.binDir The directory that has the youtube-dl binary
* @return {Promise}
*/
function getInfo(url, options) {
options = Object.assign({}, defaultOptions, options);
return new Promise((resolve, reject) => {
const execOptions = {
binDir: options.binDir,
maxBuffer: 1024 * (1024 * 2) // 2MB
};
youtubeDl.getInfo(url, options.args, execOptions, (err, info) => {
if (err) {
return reject(err);
}
const transformed = [].concat(info).map(video => {
return {
id: video.id,
title: video.title,
url: video.webpage_url,
fileurl: video.url,
thumbnail: video.thumbnail,
description: video.description,
filename: video._filename,
extension: video.ext,
format: {
id: video.format_id,
note: video.format_note,
resolution: video.width + 'x' + video.height
},
site: video.extractor_key,
uploader: video.uploader,
uploaderUrl: video.uploader_url,
duration: video.duration
};
});
resolve(transformed.length > 1 ? transformed : transformed[0]);
});
});
}
// Example usage:
// download('https://www.youtube.com/watch?v=dxWvtMOGAhw')
// .on('info', info => { console.log('Downloading:', info._filename); })
// .on('progress', p => { console.log(p.percentage); })
// .on('finish', () => { console.log('Finished'); })
// .on('part-file-deleted', () => { console.log('Cleaned up after error'); })
// .on('file-renamed', () => { console.log('Renamed'); })
// .on('error', err => { console.log('Error', JSON.stringify(err, null, ' ')) });
module.exports = {
download: download,
getInfo: getInfo
};
|
JavaScript
| 0.000137 |
@@ -1140,32 +1140,50 @@
er:
-1024 * (1024 * 2) // 2MB
+Infinity // Unlimited stdout/stderr buffer
%0A
@@ -5059,32 +5059,50 @@
er:
-1024 * (1024 * 2) // 2MB
+Infinity // Unlimited stdout/stderr buffer
%0A
|
c06e4488dbdec526ddd94a16d0899331cebc21c9
|
increase coverage for test reducer
|
client/modules/tasks/__test__/reducer.test.js
|
client/modules/tasks/__test__/reducer.test.js
|
// @flow
import { reducer, initialState } from '../reducer'
import { CREATE_TASK, REMOVE_TASK } from '../actionTypes'
describe('tasks reducer', () => {
it('returns `initialState` on initial call', () => {
expect(reducer(undefined, {})).toEqual(initialState)
})
it('adds `action.payload` to `list` on `CREATE_TASK`', () => {
const state = { list: [] }
const action = { type: CREATE_TASK, payload: { id: '1', name: 'Test' } }
expect(reducer(state, action)).toHaveProperty('list', [action.payload])
})
it('adds `action.payload` to `list` on `REMOVE_TASK`', () => {
const state = { list: [{ id: '1', name: 'Test' }] }
const action = { type: REMOVE_TASK, id: '1' }
expect(reducer(state, action)).toHaveProperty('list', [])
})
})
|
JavaScript
| 0 |
@@ -256,32 +256,98 @@
ialState)%0A %7D)%0A%0A
+ describe('CREATE_TASK', () =%3E %7B%0A const type = CREATE_TASK%0A%0A
it('adds %60acti
@@ -371,25 +371,8 @@
ist%60
- on %60CREATE_TASK%60
', (
@@ -370,32 +370,34 @@
list%60', () =%3E %7B%0A
+
const state
@@ -407,24 +407,26 @@
list: %5B%5D %7D%0A
+
const ac
@@ -442,21 +442,8 @@
type
-: CREATE_TASK
, pa
@@ -474,24 +474,26 @@
'Test' %7D %7D%0A%0A
+
expect(r
@@ -560,24 +560,35 @@
d%5D)%0A
+
%7D)%0A%0A
+
it(
-'
+%22doesn't
add
-s
%60ac
@@ -615,23 +615,258 @@
st%60
-on %60REMOVE_TASK
+when payload isn't defined%22, () =%3E %7B%0A const state = %7B list: %5B%5D %7D%0A const action = %7B type %7D%0A%0A expect(reducer(state, action)).toHaveProperty('list', %5B%5D)%0A %7D)%0A %7D)%0A%0A describe('REMOVE_TASK', () =%3E %7B%0A it('removes %60action.id%60 from %60list
%60',
@@ -865,32 +865,34 @@
list%60', () =%3E %7B%0A
+
const state
@@ -931,24 +931,26 @@
t' %7D%5D %7D%0A
+
const action
@@ -980,24 +980,26 @@
id: '1' %7D%0A%0A
+
expect(r
@@ -1048,16 +1048,23 @@
t', %5B%5D)%0A
+ %7D)%0A
%7D)%0A%7D)%0A
|
d1696d5bd80e2050aeab2943ccfefe52e2b0b37f
|
Add some extra logging
|
data/context.js
|
data/context.js
|
//
// Registration Class
//
function Context() {
}
exports.build = function(req) {
var c = new Context();
c.registrationId = req.tcapi_param('registration');
c.activityId = req.tcapi_param('activityId');
c.stateId = req.tcapi_param('stateId');
c.statementId = req.tcapi_param('statementId');
c.actor = req.tcapi_param('actor');
console.log(c);
return c;
}
|
JavaScript
| 0.000001 |
@@ -104,16 +104,132 @@
text();%0A
+%0A console.log(%22* QUERY *%22);%0A console.log(req.query);%0A%0A console.log(%22* RAW BODY *%22);%0A console.log(req.rawBody);%0A%0A
c.regi
|
b46b6eecbf037cfab651ab60f60197ba766e9755
|
Add radioClass to dunder set
|
example/dunder.js
|
example/dunder.js
|
var ElementProxy = {
get: function (tgt, key, rcv) {
switch(key) {
case '..':
return __(tgt.parentNode);
case 'parent':
return function (sel) {
for(node = tgt.parentNode; node && !node.matches(sel); node = node.parentNode) {}
return node;
}.bind(tgt);
case 'delegate':
return function (event, child, handler) {
tgt.addEventListener(event, function (ev) {
if(ev.target.matches(child)) handler.call(tgt, ev, this);
});
}
case 'on':
return tgt.addEventListener.bind(tgt);
default:
var attr = tgt[key];
return (typeof attr === 'function') ? attr.bind(tgt) : attr;
}
},
set: function (tgt, key, value, rcv) {
tgt[key] = value;
}
};
// ElementProxy.prototype = Reflect.prototype;
var ElementListProxy = {
'get': function (tgt, key, value, rcv) {
switch(key) {
case 'forEach':
return Array.apply(null, tgt).forEach;
case 'addClass':
return function (cls) {
Array.apply(null, tgt).forEach(function (el) {
el.classList.add(cls);
});
}
case 'removeClass':
return function (cls) {
Array.apply(null, tgt).forEach(function (el) {
el.classList.remove(cls);
});
}
case 'toggleClass':
return function (cls) {
Array.apply(null, tgt).forEach(function (el) {
el.classList.toggle(cls);
});
}
default:
tgt[key] = value;
}
}
};
// ElementListProxy.prototype = Reflect.prototype;
function __(el) {
return new Proxy(el, ElementProxy);
}
__.get = function (sel, root) {
root = root || document;
var el = root.querySelector(sel);
return new Proxy(el, ElementProxy);
};
__.select = function (sel, root) {
root = root || document;
var els = root.querySelectorAll(sel);
return new Proxy(els, ElementListProxy);
};
__.onstart = function(handler) {
document.addEventListener('DOMContentLoaded', handler);
};
|
JavaScript
| 0 |
@@ -1702,32 +1702,271 @@
;%0A %7D%0A
+ case 'radioClass':%0A return function (cls, sel) %7B%0A Array.apply(null, tgt).forEach(function (el) %7B%0A el.classList%5Bel.matches(sel) ? 'add' : 'remove'%5D(cls);%0A %7D)%0A %7D%0A
default:
|
8c1e9a36a54bac5c722b6ae2211619098a27dc13
|
allow spaces/tabs before the closing ***/
|
mstring.js
|
mstring.js
|
/* Copyright (c) 2012 Richard Rodger */
var errmsg = "mstring: required format is function (){/*** ... ***/}, this is invalid: "
module.exports = function(f){
if( !_.isFunction(f) ) {
throw new Error(errmsg+f)
}
var fs = f.toString()
var m = fs.match(/^function\s*\(\)\s*\{\s*\/\*\*\*\n([\s\S]*)\n\*\*\*\/\s*\}$/)
if( m && _.isString(m[1]) ) {
return m[1]
}
else throw new Error(errmsg+f);
}
var _ = {}
_.isFunction = function(obj) {
return !!(obj && obj.constructor && obj.call && obj.apply);
};
_.isString = function(obj) {
return !!(obj === '' || (obj && obj.charCodeAt && obj.substr));
};
|
JavaScript
| 0 |
@@ -239,16 +239,17 @@
String()
+;
%0A var m
@@ -296,16 +296,17 @@
%5C*%5C*%5C*%5Cn
++
(%5B%5Cs%5CS%5D*
@@ -309,16 +309,19 @@
%5CS%5D*)%5Cn%5C
+s*%5C
*%5C*%5C*%5C/%5C
@@ -327,17 +327,17 @@
%5Cs*%5C%7D$/)
-
+;
%0A if( m
@@ -376,16 +376,17 @@
urn m%5B1%5D
+;
%0A %7D%0A e
@@ -420,16 +420,16 @@
f);%0A%7D%0A%0A%0A
-
var _ =
@@ -430,16 +430,17 @@
r _ = %7B%7D
+;
%0A_.isFun
|
7b2d49049a9bd6d549d52071c3626bb9090ce8f4
|
add note
|
Algorithms/JS/trees/postOrderTraversal.js
|
Algorithms/JS/trees/postOrderTraversal.js
|
// How to perform postOrder traversal
// 23
// / \
// 16 45
// / \ / \
// 3 22 37 99
// Postorder traversal:
// 3 22 16 37 99 45 23
// A postorder traversal visits all of the child nodes of the left subtree up to the root node,
// and then visits all of the child nodes of the right subtree up to the root node.
function postOrder( node ){
if( node ){
postorder( node.left );
postorder( node.right );
console.log( node.value ); // print out current node, then traverse
}
}
|
JavaScript
| 0 |
@@ -32,16 +32,38 @@
versal%0A%0A
+// post order: L R P%0A%0A
%0A//
|
fc31e5688639d761da54df3f38fc4233fc101e09
|
tweak mocha approvals to be a little more fluent
|
lib/Approvals.js
|
lib/Approvals.js
|
var _ = require("underscore");
var osTools = require("./osTools.js");
var defaultConfig = {
reporters: ["p4merge", "opendiff", "tortisemerge", "gitdiff"],
appendEOL: osTools.isWindows ? true : false,
EOL: require('os').EOL
};
exports.options = _.defaults({}, defaultConfig);
exports.configure = function (options) {
var newConfig = _.defaults(options, defaultConfig);
exports.options = newConfig;
return exports;
};
exports.mocha = function (dir) {
return require("./Providers/Mocha/Approvals.Mocha.js")(exports.options, dir);
};
exports.verify = function () {
throw 'awesome will happen...soon...';
};
|
JavaScript
| 0 |
@@ -478,23 +478,16 @@
r) %7B%0D%0A
-return
require(
@@ -550,16 +550,35 @@
dir);%0D%0A
+ return exports;%0D%0A
%7D;%0D%0A%0D%0Aex
|
5f17320f2ea653c19eda8762bfb321b906a53124
|
remove debug statement
|
packages/api-lib/libs/ingest.js
|
packages/api-lib/libs/ingest.js
|
const fs = require('fs')
const request = require('sync-request')
const highland = require('highland')
const isUrl = require('is-url')
const path = require('path')
// this should be passed in as a backend parameter
const backend = require('./es')
function readFile(filename) {
if (isUrl(filename)) {
const data = JSON.parse(request('GET', filename).getBody('utf8'))
return data
}
return JSON.parse(fs.readFileSync(filename, 'utf8'))
}
// iterator through every node in a Catalog tree
let nCat = 0
let nCol = 0
let nItem = 0
function* readCatalog(filename, root = false) {
const fname = filename.toString()
const cat = readFile(fname)
if (cat.hasOwnProperty('extent')) {
nCol += 1
} else if (cat.hasOwnProperty('geometry')) {
nItem += 1
} else {
nCat += 1
}
if (nItem < 50) {
yield cat
} else {
return true
}
let index = 0
for (index = 0; index < cat.links.length; index += 1) {
const link = cat.links[index]
if (link.rel === 'child' || link.rel === 'item') {
if (path.isAbsolute(link.href)) {
yield* readCatalog(link.href)
} else {
yield* readCatalog(`${path.dirname(fname)}/${link.href}`)
}
}
}
if (root) {
console.log(`Read ${nCat} catalogs, ${nCol} collections, ${nItem} items.`)
}
return true
}
async function prepare() {
await backend.prepare('collections')
await backend.prepare('items')
}
async function ingest(url) {
const catStream = highland(readCatalog(url, true))
// prepare backend
await prepare()
await backend.stream(catStream)
}
module.exports = { ingest, prepare }
|
JavaScript
| 0.000517 |
@@ -580,24 +580,61 @@
= false) %7B%0A
+ console.log(%60Reading $%7Bfilename%7D%60)%0A
const fnam
@@ -836,70 +836,17 @@
%7D%0A
-if (nItem %3C 50) %7B%0A yield cat%0A %7D else %7B%0A return true%0A %7D
+yield cat
%0A l
|
e6067e31273051cd682426d3351d55f351b426a4
|
Fix chart color for Free Mobile.
|
web/js/charts.js
|
web/js/charts.js
|
// Load the Visualization API.
google.load('visualization', '1', {
'packages' : [ 'corechart' ]
});
var CHART_OPTIONS = {
width : 800,
height : 350,
pieSliceText: 'none',
legend: 'labeled',
chartArea : {
left : (940 - 550) / 2,
top : 15,
width : 550,
height : "325"
}
};
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(initChart);
var sliderInitialized = false;
function getLimitDates() {
var $dateRangePicker = $('#date-range-picker');
var limitDates = $dateRangePicker.text().split(' -> ');
var startDate = limitDates[0].split('/');
var endDate = limitDates[1].split('/');
return [startDate.reverse().join(''), endDate.reverse().join('')];
}
function initDateRangePicker() {
var $dateRangePicker = $('#date-range-picker');
var start = moment().subtract(6, 'days');
var end = moment();
$dateRangePicker.dateRangePicker({
format: 'DD/MM/YYYY',
startOfWeek: 'monday',
separator: ' -> ',
getValue: function() {
return this.innerHTML;
},
setValue: function(s) {
this.innerHTML = s;
}
})
.bind('datepicker-change', function() {
loadData();
})
.data('dateRangePicker').setDateRange(start.format('DD/MM/YYYY'), end.format('DD/MM/YYYY'));
}
function initChart() {
initDateRangePicker();
loadData();
}
function loadData() {
var limitDates = getLimitDates();
$.get('/2/chart/network-usage?start_date=' + limitDates[0] + '&end_date=' + limitDates[1] + '', drawCharts).error(dataLoadError);
}
function dataLoadError() {
var networkUsageSpinner = $("#network-usage-spinner");
networkUsageSpinner.empty();
networkUsageSpinner.append("Données non disponibles pour le moment");
}
function drawCharts(jsonData) {
var usersElement = $("#users");
var stats_global = jsonData["stats_global"];
var stats_4g = jsonData["stats_4g"];
var users = stats_global["users"];
var users4g = stats_4g["users"];
usersElement.text(users);
var limitDates = getLimitDates();
var days = moment(limitDates[1], 'YYYYMMDD').diff(moment(limitDates[0], 'YYYYMMDD'), 'days') + 1;
$("#days").text(days);
var $chartsSlider = $('.charts-slider');
$chartsSlider.show();
drawNetworkUsageChart(stats_global["time_on_orange"], stats_global["time_on_free_mobile"],
stats_global["time_on_free_mobile_femtocell"]);
draw4gNetworkUsageChart(stats_4g["time_on_orange"], stats_4g["time_on_free_mobile_3g"],
stats_4g["time_on_free_mobile_4g"], stats_4g["time_on_free_mobile_femtocell"]);
$("#network-usage-spinner").remove();
if (!sliderInitialized) {
// A bit hacky, but it seems to be the only way to workaround the greedy Google Chart which paints over the
// slider by default.
$chartsSlider.slick({infinite: true});
sliderInitialized = true;
}
$("#network-usage-chart").fadeIn(function() {
$("#chart-help").slideDown();
});
$chartsSlider.on('beforeChange', function (event, slick, oldIndex, newIndex) {
if (newIndex === 0) {
usersElement.text(users);
}
else if (newIndex === 1) {
usersElement.text(users4g);
}
});
}
function drawNetworkUsageChart(onOrange, onFreeMobile, onFreeMobileFemtocell) {
var data = new google.visualization.DataTable();
data.addColumn("string", "Réseau");
data.addColumn("number", "Utilisation");
data.addRows(3);
data.setCell(0, 0, "Orange");
data.setCell(0, 1, onOrange, "");
data.setCell(1, 0, "Free Mobile");
data.setCell(1, 1, onFreeMobile, "");
data.setCell(2, 0, "Femtocell");
data.setCell(2, 1, onFreeMobileFemtocell, "");
var chart = new google.visualization.PieChart($("#network-usage-chart").get(0));
var options = CHART_OPTIONS;
options.colors = [ "#FF6600", "#CD1E25", "#D2343A" ];
chart.draw(data, options);
}
function draw4gNetworkUsageChart(onOrange, onFreeMobile3g, onFreeMobile4g, onFreeMobileFemtocell) {
var data = new google.visualization.DataTable();
data.addColumn("string", "Type de réseau");
data.addColumn("number", "Utilisation");
data.addRows(4);
data.setCell(0, 0, "Orange");
data.setCell(0, 1, onOrange, "");
data.setCell(1, 0, "Femtocell");
data.setCell(1, 1, onFreeMobileFemtocell, "");
data.setCell(2, 0, "3G Free Mobile");
data.setCell(2, 1, onFreeMobile3g, "");
data.setCell(3, 0, "4G Free Mobile");
data.setCell(3, 1, onFreeMobile4g, "");
var chart = new google.visualization.PieChart($("#network-4g-usage-chart").get(0));
var options = CHART_OPTIONS;
options.colors = [ "#FF6600", "#CD1E25", "#660F12", "#D2343A" ];
chart.draw(data, options);
}
|
JavaScript
| 0 |
@@ -4851,32 +4851,43 @@
s = %5B %22#FF6600%22,
+ %22#D2343A%22,
%22#CD1E25%22, %22#66
@@ -4891,27 +4891,16 @@
#660F12%22
-, %22#D2343A%22
%5D;%0A
|
29627450cfd21dca609e840c54f973223448bade
|
bump version
|
build/progress.min.js
|
build/progress.min.js
|
/*! Progress 0.0.5 | (c) 2015 Pedro Rogério | MIT License */
!function(a,b){"use strict";"function"==typeof define&&define.amd?define([],b):"object"==typeof exports?module.exports=b():a.Progress=b()}(this,function(){"use strict";function a(a){var b=j.createEvent("HTMLEvents");b.initEvent(a,!0,!1),i.dispatchEvent(b)}function b(a){var b=126*a;k.style.strokeDashoffset=126-b,l.innerHTML=Math.round(100*a)+"%"}function c(){f=i.innerHeight,g=j.body.offsetHeight,h=g-f}function d(){c(),a("scroll")}var e,f,g,h,i=window,j=document,k=document.querySelector(".animated-circle"),l=document.querySelector(".progress-count");return e=function(){var a,e,f=["DOMContentLoaded","load","resize"];c(),i.addEventListener("scroll",function(){a=this.pageYOffset||j.documentElement.scrollTop,e=Math.max(0,Math.min(1,a/h)),b(e)},!1),f.map(function(a){i.addEventListener(a,d,!1)})},{init:e}});
|
JavaScript
| 0.000001 |
@@ -10,17 +10,17 @@
ess 0.0.
-5
+6
%7C (c) 2
@@ -24,10 +24,10 @@
) 20
+2
1
-5
Ped
@@ -54,16 +54,17 @@
ense */%0A
+%0A
!functio
@@ -69,11 +69,11 @@
ion(
-a,b
+e,t
)%7B%22u
@@ -131,17 +131,17 @@
fine(%5B%5D,
-b
+t
):%22objec
@@ -178,13 +178,13 @@
rts=
-b():a
+t():e
.Pro
@@ -189,17 +189,17 @@
rogress=
-b
+t
()%7D(this
@@ -227,187 +227,127 @@
ct%22;
-function a(a)%7Bvar b=j.createEvent(%22HTMLEvents%22);b.initEvent(a,!0,!1),i.dispatchEvent(b)%7Dfunction b(a)%7Bvar b=126*a;k.style.strokeDashoffset=126-b,l.innerHTML=Math.round(100*a)+%22%25%22%7D
+var e,t,n,o=window,i=document,r=document.querySelector(%22.animated-circle%22),s=document.querySelector(%22.progress-count%22);
func
@@ -359,11 +359,11 @@
c()%7B
-f=i
+e=o
.inn
@@ -375,11 +375,11 @@
ght,
-g=j
+t=i
.bod
@@ -397,13 +397,13 @@
ght,
-h=g-f
+n=t-e
%7Dfun
@@ -416,22 +416,30 @@
d()%7B
+var e,t;
c(),
-a(
+e=
%22scroll%22
)%7Dva
@@ -438,203 +438,113 @@
oll%22
-)%7Dvar e,f,g,h,i=window,j=document,k=document.querySelector(%22.animated-circle%22),l=document.querySelector(%22.progress-count%22);return e=function()%7Bvar a,e,f=%5B%22DOMContentLoaded%22,%22load%22,%22resize%22%5D
+,(t=i.createEvent(%22HTMLEvents%22)).initEvent(e,!0,!1),o.dispatchEvent(t)%7Dreturn%7Binit:function()%7Bvar t
;c(),
-i
+o
.add
@@ -577,17 +577,23 @@
ction()%7B
-a
+var e;t
=this.pa
@@ -603,17 +603,17 @@
Offset%7C%7C
-j
+i
.documen
@@ -631,17 +631,17 @@
rollTop,
-e
+t
=Math.ma
@@ -659,25 +659,128 @@
n(1,
-a/h)),b(e)%7D,!1),f
+t/n)),e=t,r.style.strokeDashoffset=126-126*e,s.innerHTML=Math.round(100*e)+%22%25%22%7D,!1),%5B%22DOMContentLoaded%22,%22load%22,%22resize%22%5D
.map
@@ -793,12 +793,12 @@
ion(
-a)%7Bi
+e)%7Bo
.add
@@ -811,17 +811,17 @@
istener(
-a
+e
,d,!1)%7D)
@@ -825,16 +825,8 @@
)%7D)%7D
-,%7Binit:e
%7D%7D);
|
a59e59e17b9be10f47d2c6834cd997a69bc2dd22
|
fix eslint error
|
src/__tests__/github_issues/181-test.js
|
src/__tests__/github_issues/181-test.js
|
/* @flow */
import { schemaComposer, InputTypeComposer } from 'graphql-compose';
import {
processFilterOperators,
OPERATORS_FIELDNAME,
} from '../../resolvers/helpers/filterOperators';
let itc: InputTypeComposer<any>;
beforeEach(() => {
schemaComposer.clear();
itc = schemaComposer.createInputTC({
name: 'UserFilterInput',
fields: {
_id: 'String',
employment: 'String',
name: 'String',
age: 'Int',
skills: ['String'],
},
});
});
describe(`issue #181 - Cannot read property '_operators' of null`, () => {
it('should call query.find if operator value is null', () => {
const filter = {
[OPERATORS_FIELDNAME]: { age: { ne: null } },
};
expect(processFilterOperators(filter)).toEqual({ age: { $ne: null } });
});
});
|
JavaScript
| 0.000009 |
@@ -33,27 +33,8 @@
oser
-, InputTypeComposer
%7D f
@@ -169,42 +169,8 @@
';%0A%0A
-let itc: InputTypeComposer%3Cany%3E;%0A%0A
befo
@@ -215,14 +215,8 @@
);%0A
- itc =
sch
|
ee7dc6ec20282c901229f243d13a5cb754f67462
|
Add width to photo
|
App/Containers/AboutScreen.js
|
App/Containers/AboutScreen.js
|
import React from 'react'
import {
ScrollView,
TouchableOpacity,
Image,
View,
Text,
Linking
} from 'react-native'
import LinearGradient from 'react-native-linear-gradient'
import RoundedButton from '../Components/RoundedButton'
import PurpleGradient from '../Components/PurpleGradient'
import { Images } from '../Themes'
import { connect } from 'react-redux'
// Add Actions - replace 'Your' with whatever your reducer is called :)
// import YourActions from '../Redux/YourRedux'
// Styles
import styles from './Styles/AboutScreenStyle'
class AboutScreen extends React.Component {
static navigationOptions = {
tabBarLabel: 'General Info',
tabBarIcon: ({ focused }) => (
<Image source={focused ? Images.activeInfoIcon : Images.inactiveInfoIcon} />
)
}
tweetWithHashtag () {
const appURL = 'twitter://post?hashtags=ChainReactConf'
const webURL = 'https://twitter.com/intent/tweet?hashtags=ChainReactConf'
Linking.canOpenURL(appURL).then((supported) =>
supported ? Linking.openURL(appURL) : Linking.openURL(webURL)
)
}
render () {
const gradient = ['#136EB5', 'rgba(1,192,182,0.88)']
return (
<PurpleGradient style={[styles.linearGradient, {flex: 1}]}>
<ScrollView>
<View style={styles.container}>
<LinearGradient
colors={gradient}
start={{x: 0, y: 1}}
end={{x: 1, y: 0}}
style={styles.slack}>
<Image style={styles.slackIcon} source={Images.slack} />
<Text style={styles.heading}>Join Us On Slack</Text>
<RoundedButton
text='Join the IR Slack Community'
onPress={() => Linking.openURL('http://community.infinite.red')}
style={styles.slackButton}
/>
</LinearGradient>
<Image source={Images.squarespacePhoto}>
<View style={styles.afterPartyContainer}>
<View style={styles.partyHeader}>
<Image source={Images.sqspLogo} />
<Text style={styles.welcomeParty}>WELCOME PARTY</Text>
<Text style={styles.partyDescription}>AT SQUARESPACE PDX</Text>
</View>
<View style={styles.partyInfo}>
<Text style={styles.partyDescription}>SUNDAY, JULY 9 | 4-8PM</Text>
<Text style={styles.partyDescription}>311 SW WASHINGTON STREET</Text>
</View>
</View>
</Image>
<RoundedButton
onPress={() => Linking.openURL('https://chainreact.squarespace.com')}
style={styles.partyButton}
>
<Text style={styles.partyButtonText}>I WANT TO GO</Text>
</RoundedButton>
<View style={styles.twitter}>
<Image style={styles.blowhorn} source={Images.blowhorn} />
<TouchableOpacity onPress={() => this.tweetWithHashtag()}>
<Text style={styles.heading}>
#ChainReactConf
</Text>
</TouchableOpacity>
<Text style={styles.description}>
Make your friends jealous by tweeting, posting,
or whatever it is you do with the hashtag
<Text style={styles.hashtag} onPress={() => this.tweetWithHashtag()}>
#chainreactconf
</Text>.
</Text>
</View>
<View style={styles.sponsors}>
<Text style={styles.heading}>Our Sponsors</Text>
<Text style={styles.description}>
We love the sponsors we got for this conference.
They make all of this fun stuff possible, and we
couldn’t have done it without them.
</Text>
<Text style={styles.sponsorTierTitle}>Platinum Level</Text>
<View style={styles.sponsorTier}>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://www.squarespace.com/')}>
<Image source={Images.squarespaceSponsor} />
</TouchableOpacity>
</View>
<Text style={styles.sponsorTierTitle}>Gold Level</Text>
<View style={styles.sponsorTier}>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://nativebase.io/')}>
<Image style={styles.goldSponsor} source={Images.nativeBaseSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://formidable.com/')}>
<Image style={styles.goldSponsor} source={Images.formidableSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://moduscreate.com/')}>
<Image style={styles.goldSponsor} source={Images.modusSponsor} />
</TouchableOpacity>
</View>
<Text style={styles.sponsorTierTitle}>Silver Level</Text>
<View style={styles.sponsorTier}>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://aws.amazon.com/')}>
<Image source={Images.amazonSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('http://reactnative.training/')}>
<Image source={Images.trainingSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://gudog.co.uk/')}>
<Image source={Images.gudogSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://rangle.io/')}>
<Image source={Images.rangleSponsor} />
</TouchableOpacity>
</View>
<Text style={styles.sponsorTierTitle}>Bronze Level</Text>
<View style={styles.sponsorTier}>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://echobind.com/')}>
<Image source={Images.echobindSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://www.salesforce.com/')}>
<Image source={Images.salesforceSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://www.capitalone.com/')}>
<Image source={Images.capitalOneSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://www.instrument.com/')}>
<Image source={Images.instrumentSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('https://www.paypal.com/us/home')}>
<Image source={Images.paypalSponsor} />
</TouchableOpacity>
<TouchableOpacity
style={styles.sponsor}
onPress={() => Linking.openURL('http://www.qlik.com/us/')}>
<Image source={Images.qlikSponsor} />
</TouchableOpacity>
</View>
</View>
</View>
</ScrollView>
</PurpleGradient>
)
}
}
const mapStateToProps = (state) => {
return {
}
}
const mapDispatchToProps = (dispatch) => {
return {
}
}
export default connect(mapStateToProps, mapDispatchToProps)(AboutScreen)
|
JavaScript
| 0 |
@@ -306,16 +306,25 @@
%7B Images
+, Metrics
%7D from
@@ -1899,16 +1899,53 @@
cePhoto%7D
+ style=%7B%7Bwidth: Metrics.screenWidth%7D%7D
%3E%0A
|
7b119a282e3db03ad2d8096d9f89e625a2402ccf
|
Handle empty image URL in last.fm response.
|
www/app/coverart/lastfm.js
|
www/app/coverart/lastfm.js
|
;(function(module) {
'use strict';
var sizes = {
small: 34,
medium: 64,
large: 126,
extralarge: 252,
mega: undefined
};
var mapping = {
'Album': function(album) {
if (album.musicbrainz_id) {
return {method: 'album.getInfo', mbid: album.musicbrainz_id};
} else if (album.name && album.artists && album.artists.length) {
return {method: 'album.getInfo', album: album.name, artist: album.artists[0].name};
} else {
return undefined;
}
},
'Artist': function(artist) {
if (artist.musicbrainz_id) {
return {method: 'artist.getInfo', mbid: artist.musicbrainz_id};
} else if (artist.name) {
return {method: 'artist.getInfo', artist: artist.name};
} else {
return undefined;
}
},
'Track': function(track) {
var album = track.album;
if (album && album.musicbrainz_id) {
return {method: 'album.getInfo', mbid: track.album.musicbrainz_id};
} else if (album && album.name && album.artists && album.artists.length) {
return {method: 'album.getInfo', album: album.name, artist: album.artists[0].name};
} else if (album && album.name && track.artists && track.artists.length) {
return {method: 'album.getInfo', album: album.name, artist: track.artists[0].name};
} else if (track.musicbrainz_id) {
return {method: 'track.getInfo', mbid: track.musicbrainz_id};
} else if (track.name && track.artists && track.artists.length) {
return {method: 'track.getInfo', track: track.name, artist: track.artists[0].name};
} else {
return undefined;
}
},
'Ref': function(/*ref*/) {
return undefined;
}
};
function createImage(image) {
return {
uri: image['#text'],
width: sizes[image.size],
height: sizes[image.size]
};
}
/* @ngInject */
module.service('coverart.lastfm', function($http, $q) {
function getImages(params) {
var config = {params: angular.extend(params, {
format: 'json',
callback: 'JSON_CALLBACK',
api_key: 'fd01fd0378426f85397626d5f8bcc692'
})};
return $http.jsonp('http://ws.audioscrobbler.com/2.0/', config).then(function(result) {
var data = result.data;
if (data.album && data.album.image) {
return data.album.image.map(createImage);
} else if (data.artist && data.artist.image) {
return data.artist.image.map(createImage);
} else if (data.track && data.track.image) {
return data.track.image.map(createImage);
} else if (data.track && data.track.album && data.track.album.image) {
return data.track.album.image.map(createImage);
} else {
return [];
}
});
}
return function(models) {
var images = {};
var promises = {};
models.forEach(function(model) {
var params = mapping[model.__model__](model);
if (params) {
var key = angular.toJson(params);
if (key in promises) {
images[model.uri] = promises[key];
} else {
images[model.uri] = promises[key] = getImages(params);
}
}
});
return $q.all(images);
};
});
})(angular.module('app.coverart.lastfm', []));
|
JavaScript
| 0 |
@@ -1879,16 +1879,136 @@
%7D;%0A %7D%0A%0A
+ function filterImage(image) %7B%0A return image%5B'#text'%5D; // last.fm return empty URIs for podcasts, for example%0A %7D%0A%0A
/* @ng
@@ -2068,16 +2068,22 @@
n($http,
+ $log,
$q) %7B%0A%0A
@@ -2488,32 +2488,52 @@
ata.album.image.
+filter(filterImage).
map(createImage)
@@ -2620,24 +2620,44 @@
rtist.image.
+filter(filterImage).
map(createIm
@@ -2745,24 +2745,44 @@
track.image.
+filter(filterImage).
map(createIm
@@ -2906,16 +2906,36 @@
m.image.
+filter(filterImage).
map(crea
@@ -3471,16 +3471,130 @@
(images)
+.catch(function(error) %7B%0A $log.error('Error loading last.fm cover art', error);%0A return %7B%7D;%0A %7D)
;%0A %7D;
|
44fa14f77545e9bfc87cad90f6c7c26d0bbeb90c
|
Allow to use substanceGlobals in a worker.
|
util/substanceGlobals.js
|
util/substanceGlobals.js
|
import _isDefined from './_isDefined'
/**
A place to store global variables.
*/
const _global = (typeof global !== 'undefined') ? global : window
const substanceGlobals = _isDefined(_global.Substance) ? _global.Substance : _global.Substance = {}
export default substanceGlobals
|
JavaScript
| 0 |
@@ -1,8 +1,26 @@
+/* global self */%0A
import _
@@ -157,14 +157,99 @@
l :
-window
+(typeof window !== 'undefined') ? window : (typeof self !== 'undefined') ? self : undefined
%0Acon
|
8af1efc4f42a9e6996bea1785e322e9e8273226e
|
add description
|
Algorithms/JS/trees/breadthFirstSearch.js
|
Algorithms/JS/trees/breadthFirstSearch.js
|
breadthFirstSearch.js
|
JavaScript
| 0.000004 |
@@ -1,22 +1,427 @@
-b
+// Suppose you%E2%80%99d like to traverse through a family tree in JavaScript, printing each generation of children on a single line.%0A%0A// B
readth
-F
+-f
irst
-Search.js
+ search (BFS) is an algorithm for traversing or searching tree or graph data structures.%0A// It starts at the tree root (or some arbitrary node of a graph, sometimes referred to as a 'search key'%5B1%5D)%0A// and explores the neighbor nodes first, before moving to the next level neighbors.
%0A
|
c79266bb91e5b62dde8c67c59e26a5e18425e946
|
update ButtonCheckbox
|
src/ButtonCheckbox/ButtonCheckbox.js
|
src/ButtonCheckbox/ButtonCheckbox.js
|
/**
* @file ButtonCheckbox component
* @author liangxiaojun([email protected])
*/
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import RaisedButton from '../RaisedButton';
import Theme from '../Theme';
import Util from '../_vendors/Util';
class ButtonCheckbox extends Component {
static Theme = Theme;
constructor(props, ...restArgs) {
super(props, ...restArgs);
this.state = {
value: !!props.value
};
this.touchTapHandler = ::this.touchTapHandler;
}
touchTapHandler() {
const value = !this.state.value;
this.setState({
value
}, () => {
!this.props.disabled && this.props.onChange && this.props.onChange(value);
});
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.state.value) {
this.setState({
value: !!nextProps.value
});
}
}
render() {
const {className, style, theme, activatedTheme, text, disabled} = this.props,
{value} = this.state,
buttonClassName = classNames('button-checkbox', {
activated: value,
[className]: className
});
return (
<RaisedButton className={buttonClassName}
style={style}
value={text}
disabled={disabled}
isRounded={true}
theme={value ? activatedTheme : theme}
onClick={this.touchTapHandler}/>
);
}
}
ButtonCheckbox.propTypes = {
/**
* The CSS class name of the root element.
*/
className: PropTypes.string,
/**
* Override the styles of the root element.
*/
style: PropTypes.object,
/**
* The ButtonCheckbox theme.
*/
theme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The ButtonCheckbox activated theme.
*/
activatedTheme: PropTypes.oneOf(Util.enumerateValue(Theme)),
/**
* The name of the toggleButton.
*/
// name: PropTypes.string,
/**
* The text of the button.
*/
text: PropTypes.string,
/**
* If true,the button will be in active status.
*/
value: PropTypes.bool,
/**
* Disables the button if set to true.
*/
disabled: PropTypes.bool,
/**
* Callback function fired when the button is touch-tapped.
*/
onChange: PropTypes.func
};
ButtonCheckbox.defaultProps = {
theme: Theme.DEFAULT,
activatedTheme: Theme.PRIMARY,
value: false,
disabled: false
};
export default ButtonCheckbox;
|
JavaScript
| 0 |
@@ -531,64 +531,8 @@
%7D;%0A%0A
- this.touchTapHandler = ::this.touchTapHandler;%0A%0A
@@ -553,18 +553,24 @@
pHandler
-()
+ = () =%3E
%7B%0A
@@ -766,24 +766,25 @@
%7D);%0A %7D
+;
%0A%0A compon
|
7e0715c9651bdc0a6926b1fa3fbff942fa1077e6
|
Fix issue with button click passing through to underlying link
|
openure.js
|
openure.js
|
Openure = {
allViews: [],
currentView: "",
listener: "",
trackedViewsIDs: [],
previousView: null,
stackSize: 0,
maxStackSize: 30,
findViewsInArray: function(array) {
//for x in array.len....
//this.findViewsInView(region.currentView);
},
registerView: function(view) {
if (view.cid && _.lastIndexOf(this.trackedViewsIDs, view.cid) == -1) {
this.trackedViewsIDs.push(view.cid);
this.allViews.push(view);
}
},
findViewsInObject: function(obj) {
this.stackSize++;
if (this.stackSize < this.maxStackSize) {
for(var prop in obj) {
if(obj.nodeName) {
//this is an html element, and continuing will blow up
return;
}
if (obj[prop] instanceof Backbone.View) {
this.registerView(obj[prop]);
this.findViewsInObject(obj[prop]);
} else if (obj[prop] instanceof Array) {
this.findViewsInArray(obj[prop]);
} else if (obj[prop] instanceof Function) {
//skip
} else if (obj[prop] instanceof Object) {
this.findViewsInObject(obj[prop]);
}
}
}
this.stackSize--;
},
applySelectedView: function() {
clearInterval(this.listener);
console.log("rock the view - " + this.currentView.cid);
//Remove the current console when clicking a new one.
if($('#console').length) {
this.previousView.el.removeChild($('#console')[0]);
}
//For now, close it by clicking the same view again.
if(this.previousView && this.previousView.cid === this.currentView.cid){
this.previousView = null;
return;
}
var jqconsole = document.createElement('div');
var width = this.currentView.$el.css('width');
width = width.substr(0, width.indexOf('px')); //pull off the px
var consoleWidth = parseInt(width, 10) - 5;
jqconsole.style.cssText = 'width:' + consoleWidth + 'px;z-index:99';
jqconsole.id = "console";
this.currentView.el.appendChild(jqconsole);
// Creating the console.
var header = 'Welcome to Openure in JQConsole!\n' +
'The variable "view" is now in context\n' +
'here and in the chrome console.\n' +
'As is model, collection, and options.\n';
this.jqconsole = $('#console').jqconsole(header, 'JS> ');
var that = this;
// Abort prompt on Ctrl+Z.
this.jqconsole.RegisterShortcut('Z', function() {
that.jqconsole.AbortPrompt();
handler();
});
// Move to line start Ctrl+A.
this.jqconsole.RegisterShortcut('A', function() {
that.jqconsole.MoveToStart();
handler();
});
// Move to line end Ctrl+E.
this.jqconsole.RegisterShortcut('E', function() {
that.jqconsole.MoveToEnd();
handler();
});
// Close console
this.jqconsole.RegisterShortcut('W', function() {
that.previousView.el.removeChild($('#console')[0]);
});
this.jqconsole.RegisterShortcut('Q', function() {
that.previousView.el.removeChild($('#console')[0]);
});
this.jqconsole.RegisterMatching('{', '}', 'brace');
this.jqconsole.RegisterMatching('(', ')', 'paran');
this.jqconsole.RegisterMatching('[', ']', 'bracket');
isObject = function(obj) {
return obj === Object(obj);
};
// Handle a command.
var handler = _.bind(function(command) {
var result;
if (command) {
try {
result = window.eval(command);
} catch (e) {
this.jqconsole.Write('ERROR: ' + e.message + '\n');
}
try {
if(isObject(result)) {
result = JSON.stringify(result, function(k, v) {
return (k === '$el' || k === 'el' || k === '_events' || k === '_listeners') ? undefined : v;
}, 2);
}
} catch (e) {
if (e.message === 'Converting circular structure to JSON') {
this.jqconsole.Write('ERROR: ' + e.message + '\n');
this.jqconsole.Write('Please try the same command in the chrome console.\n');
}
else {
this.jqconsole.Write('ERROR: ' + e.message + '\n');
}
}
this.jqconsole.Write(result);
this.jqconsole.Write('\n');
}
this.jqconsole.Prompt(true, handler, function(command) {
// Continue line if can't compile the command.
try {
Function(command);
} catch (e) {
if (/[\[\{\(]$/.test(command)) {
return 1;
} else {
return 0;
}
}
return false;
});
}, this);
// Initiate the first prompt.
handler();
model = this.currentView.model;
view = this.currentView;
collection = this.currentView.collection;
options = this.currentView.options;
this.previousView = view;
},
go: function() {
var backbone_app_key;
var openureKey = $('openure_keys');
if((openureKey.length < 1 || openureKey.text() === "") && !openure_key){
console.log('No Openure keys are configured. Go to the Chrome extensions page and add the key to the Openure options page.');
}
else {
backbone_app_key = openureKey.text() || openure_key;
}
console.log('Running Openure against global variable: ' + backbone_app_key);
this.findViewsInObject(eval(backbone_app_key));
_.each(this.allViews, function(view) {
view.$el[0].addEventListener('click', _.bind(function(e) {
if(e.metaKey && e.shiftKey) {
var ownIt = _.bind(this.applySelectedView, this);
clearInterval(this.listener);
this.listener = setInterval(ownIt, 100);
e.preventDefault();
this.currentView = view;
}
}, this), true);
}, this);
}
};
$(function () {
Openure.go();
});
|
JavaScript
| 0 |
@@ -5639,24 +5639,64 @@
tDefault();%0A
+ e.stopImmediatePropagation();%0A
th
|
f486731c5b7cf3982f6cb914967d21429db9349b
|
Add xsrf-token to delete as well
|
contrib/src/frontend/actions/UploadActions.js
|
contrib/src/frontend/actions/UploadActions.js
|
/* global XMLHttpRequest FormData */
import Credentials from '../constants/Credentials'
import * as types from '../constants/ActionTypes'
import generateId from '../utils/generateId'
import getCookie from '../utils/getCookie'
export const startUpload = (id, file) => ({
type: types.UPLOAD_STARTED,
payload: { id, file }
})
export const uploadFinished = (id, finishedUpload) => ({
type: types.UPLOAD_SUCCESS,
payload: { id, finishedUpload }
})
export const uploadError = (id, error) => ({
type: types.UPLOAD_ERROR,
payload: { id, error },
error: true
})
export const uploadProgress = (id, progress) => ({
type: types.UPLOAD_PROGRESS,
payload: { progress, id }
})
export const uploadFile = file => (dispatch, getState) => {
const id = generateId()
dispatch(startUpload(id, file.name))
const url = `/api/v1/file/${Credentials.USER && Credentials.API_KEY
? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
: ''}`
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
const checkAborted = setInterval(() => {
if (
getState().uploads.find(upload => upload.id === id).status ===
'Aborting'
) {
xhr.abort()
}
})
let nextTenthOfSecond = 0
xhr.upload.onprogress = event => {
if (new Date().getMilliseconds() / 10 < nextTenthOfSecond) return
nextTenthOfSecond = new Date().getSeconds() / 10 + 10
dispatch(
uploadProgress(id, Math.floor(event.loaded / event.total * 1000) / 10)
)
}
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
dispatch(uploadProgress(id, 100))
clearInterval(checkAborted)
if (xhr.status === 201) {
setTimeout(() => resolve(JSON.parse(xhr.response)), 1000)
} else {
reject(Error('Something went wrong uploading'))
}
} else {
clearInterval(checkAborted)
reject(Error(xhr.statusText))
}
}
xhr.onabort = () => {
clearInterval(checkAborted)
dispatch(uploadAborted(id))
}
xhr.onerror = () => {
clearInterval(checkAborted)
reject(Error('Network error'))
}
xhr.open('post', url, true)
xhr.setRequestHeader('accept', '*/*')
xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))
const formData = new FormData()
formData.append('file', file)
xhr.send(formData)
})
.then(response => dispatch(uploadFinished(id, response)))
.catch(error => dispatch(uploadError(id, error)))
}
export const requestDeleteUpload = id => ({
type: types.REQUEST_DELETE_UPLOAD,
payload: {
id
}
})
export const uploadDeleted = id => ({
type: types.UPLOAD_DELETED,
payload: {
id
}
})
export const deleteUploadError = (id, error) => ({
type: types.DELETE_UPLOAD_ERROR,
payload: { id, error },
error: true
})
export const deleteUpload = id => dispatch => {
dispatch(requestDeleteUpload(id))
const url = `/api/v1/file/${id}/${Credentials.USER && Credentials.API_KEY
? `?username=${Credentials.USER}&api_key=${Credentials.API_KEY}`
: ''}`
return new Promise((resolve, reject) => {
const xhr = new XMLHttpRequest()
xhr.onload = () => {
if (xhr.readyState === XMLHttpRequest.DONE) {
resolve()
} else {
reject(Error(xhr.statusText))
}
}
xhr.onerror = () => {
reject(Error('Network error'))
}
xhr.open('delete', url, true)
xhr.setRequestHeader('accept', '*/*')
xhr.send()
})
.then(() => dispatch(uploadDeleted(id)))
.catch(error => dispatch(deleteUploadError(id, error)))
}
export const abortUpload = id => ({
type: types.ABORT_UPLOAD,
payload: {
id
}
})
export const uploadAborted = id => ({
type: types.UPLOAD_ABORTED,
payload: {
id
}
})
export const changeUploadStatus = (id, status) => ({
type: types.CHANGE_UPLOAD_STATUS,
payload: {
id,
status
}
})
export const removeUpload = id => ({
type: types.REMOVE_UPLOAD,
payload: {
id
}
})
|
JavaScript
| 0 |
@@ -3496,32 +3496,96 @@
accept', '*/*')%0A
+ xhr.setRequestHeader('X-CSRFToken', getCookie('csrftoken'))%0A
xhr.send()%0A
|
bd66f37a7d7df0eca02e3758766446f427771f33
|
Update iam_listusers.js
|
javascript/example_code/iam/iam_listusers.js
|
javascript/example_code/iam/iam_listusers.js
|
/*
Copyright 2010-2018 Amazon.com, Inc. or its affiliates. All Rights Reserved.
This file is licensed under the Apache License, Version 2.0 (the "License").
You may not use this file except in compliance with the License. A copy of
the License is located at
http://aws.amazon.com/apache2.0/
This file 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.
ABOUT THIS NODE.JS SAMPLE: This sample is part of the SDK for JavaScript Developer Guide topic at
https://docs.aws.amazon.com/sdk-for-javascript/v2/developer-guide/iam-examples-managing-users.html
*/
// Load the AWS SDK for Node.js
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({region: 'REGION'});
// Create the IAM service object
var iam = new AWS.IAM({apiVersion: '2010-05-08'});
var params = {
MaxItems: 10
};
iam.listUsers(params, function(err, data) {
if (err) {
console.log("Error", err);
} else {
console.log("User " + data.Users[0].UserName + " created", data.Users[0].CreateDate);
}
});
|
JavaScript
| 0.000001 |
@@ -1,9 +1,6 @@
/
-*%0A
+/
Cop
@@ -77,26 +77,12 @@
ed.%0A
-%0A This file is l
+// L
icen
@@ -105,428 +105,80 @@
ache
- License, Version 2.0 (the %22License%22).%0A You may not use this file except in compliance with the License. A copy of%0A the License is located at%0A%0A http://aws.amazon.com/apache2.0/%0A%0A This file is distributed on an %22AS IS%22 BASIS, WITHOUT WARRANTIES OR%0A CONDITIONS OF ANY KIND, either express or implied. See the License for the%0A specific language governing permissions and limitations under the License.%0A %0A
+-2.0 License on an %22AS IS%22 BASIS, WITHOUT WARRANTIES OF ANY KIND. %0A%0A//
ABO
@@ -272,18 +272,18 @@
opic at%0A
-
+//
https:/
@@ -378,12 +378,8 @@
tml%0A
-*/%0A%0A
// L
|
deed4d25057bf64b19088aa24c3e1de5eeafaa56
|
Make navigation through input
|
src/components.js
|
src/components.js
|
import type { Page } from './Page'
import type { Command } from './Command'
import React from 'react'
import ReactDOM from 'react-dom'
import marked from 'marked'
const Debug = (props) =>
<pre> {JSON.stringify(props, null, " ")} </pre>
const Nav = ({name, platform}: Command) => (
<nav>
{name}
</nav>
)
const TldrPage = ({body, path}: Page) => (
<pre dangerouslySetInnerHTML={{__html: marked(body)}}></pre>
)
const NotFound = (props) => (
<h1> Oops! Page not found! </h1>
)
const TldrApp = (props) => (
<section>
<Nav {...props.state.command} />
{ props.found && <TldrPage {...props.page} /> }
{ !props.found && <NotFound {...props} /> }
<Debug {...props} />
</section>
)
export default (opts) => {
ReactDOM.render((
<TldrApp {...opts} />
), document.getElementById('tldr'))
}
|
JavaScript
| 0.00001 |
@@ -254,57 +254,193 @@
= (%7B
-name, platform%7D: Command) =%3E (%0A %3Cnav%3E%0A %7Bname%7D
+history, command: %7Bname%7D%7D) =%3E (%0A %3Cnav%3E%0A %3Cinput%0A type=%22text%22%0A onChange=%7B (%7Btarget: %7Bvalue%7D%7D) =%3E %7B history.push(%7Bpathname: %60/$%7Bvalue%7D%60%7D) %7D %7D%0A defaultValue=%7Bname%7D%0A /%3E
%0A %3C
@@ -694,16 +694,8 @@
tate
-.command
%7D /%3E
|
e9dd2454342c2233041e433a8c0be3956f635472
|
Add lagda extension
|
packages/core/spec/Dicy_spec.js
|
packages/core/spec/Dicy_spec.js
|
/* @flow */
import 'babel-polyfill'
import path from 'path'
import readdir from 'readdir-enhanced'
import childProcess from 'child_process'
import { DiCy, File } from '../src/main'
import { cloneFixtures, customMatchers } from './helpers'
const ASYNC_TIMEOUT = 50000
function doCheck (command: string): Promise<boolean> {
return new Promise(resolve => {
childProcess.exec(command, error => resolve(!error))
})
}
describe('DiCy', () => {
let dicy: DiCy
let fixturesPath: string
const testPath: string = path.join(__dirname, 'fixtures', 'builder-tests')
let tests: Array<string> = readdir.sync(testPath, { filter: /\.(lhs|tex|Rnw)$/i })
beforeEach(async (done) => {
fixturesPath = await cloneFixtures()
// $FlowIgnore
jasmine.addMatchers(customMatchers)
done()
})
describe('can successfully build', () => {
for (const name of tests) {
const spec = it(name, async (done) => {
let expected = { types: [], events: [] }
let events = []
const filePath = path.resolve(fixturesPath, 'builder-tests', name)
// Initialize dicy and listen for messages
dicy = await DiCy.create(filePath)
dicy.state.env.HOME = fixturesPath
// Load the event archive
const eventFilePath = dicy.resolvePath('$DIR/$NAME-events.yaml')
if (await File.canRead(eventFilePath)) {
expected = await File.safeLoad(eventFilePath)
for (const type of expected.types) {
dicy.on(type, event => { events.push(event) })
}
}
// Run the builder
expect(await dicy.run('load')).toBeTruthy()
for (const command of dicy.options.check || []) {
if (!await doCheck(command)) {
// $FlowIgnore
spec.pend(`Skipped test since required program is not available (\`${command}\` was not successful).`)
done()
return
}
}
expect(await dicy.run('build', 'log', 'save')).toBeTruthy()
// $FlowIgnore
if (expected.types.length !== 0) expect(events).toReceiveEvents(expected.events)
done()
// $FlowIgnore
}, ASYNC_TIMEOUT)
}
})
})
|
JavaScript
| 0 |
@@ -641,16 +641,22 @@
%7Ctex%7CRnw
+%7Clagda
)$/i %7D)%0A
|
6ea892edec8fa928d672d9aef0f97ab38c721bc9
|
Move remove from localStorage after setting currency
|
src/javascript/app/pages/user/set_currency.js
|
src/javascript/app/pages/user/set_currency.js
|
const BinaryPjax = require('../../base/binary_pjax');
const Client = require('../../base/client');
const Header = require('../../base/header');
const BinarySocket = require('../../base/socket');
const getCurrencyName = require('../../common/currency').getCurrencyName;
const isCryptocurrency = require('../../common/currency').isCryptocurrency;
const localize = require('../../../_common/localize').localize;
const State = require('../../../_common/storage').State;
const Url = require('../../../_common/url');
const SetCurrency = (() => {
let is_new_account;
const onLoad = () => {
is_new_account = localStorage.getItem('is_new_account');
localStorage.removeItem('is_new_account');
const el = is_new_account ? 'show' : 'hide';
$(`#${el}_new_account`).setVisibility(1);
if (Client.get('currency')) {
if (is_new_account) {
$('#set_currency_loading').remove();
$('#has_currency, #set_currency').setVisibility(1);
} else {
BinaryPjax.loadPreviousUrl();
}
return;
}
BinarySocket.wait('payout_currencies').then((response) => {
const payout_currencies = response.payout_currencies;
const $fiat_currencies = $('<div/>');
const $cryptocurrencies = $('<div/>');
payout_currencies.forEach((c) => {
(isCryptocurrency(c) ? $cryptocurrencies : $fiat_currencies)
.append($('<div/>', { class: 'gr-3 currency_wrapper', id: c })
.append($('<div/>').append($('<img/>', { src: Url.urlForStatic(`images/pages/set_currency/${c.toLowerCase()}.svg`) })))
.append($('<div/>', { class: 'currency-name', html: (isCryptocurrency(c) ? `${getCurrencyName(c)}<br />(${c})` : c) })));
});
const fiat_currencies = $fiat_currencies.html();
if (fiat_currencies) {
$('#fiat_currencies').setVisibility(1);
$('#fiat_currency_list').html(fiat_currencies);
}
const crytpo_currencies = $cryptocurrencies.html();
if (crytpo_currencies) {
$('#crypto_currencies').setVisibility(1);
$('#crypto_currency_list').html(crytpo_currencies);
}
$('#set_currency_loading').remove();
$('#set_currency, .select_currency').setVisibility(1);
const $currency_list = $('.currency_list');
$('.currency_wrapper').on('click', function () {
$currency_list.find('> div').removeClass('selected');
$(this).addClass('selected');
});
const $form = $('#frm_set_currency');
const $error = $form.find('.error-msg');
$form.on('submit', (evt) => {
evt.preventDefault();
$error.setVisibility(0);
const $selected_currency = $currency_list.find('.selected');
if ($selected_currency.length) {
BinarySocket.send({ set_account_currency: $selected_currency.attr('id') }).then((response_c) => {
if (response_c.error) {
$error.text(response_c.error.message).setVisibility(1);
} else {
Client.set('currency', response_c.echo_req.set_account_currency);
BinarySocket.send({ balance: 1 });
BinarySocket.send({ payout_currencies: 1 }, { forced: true });
Header.displayAccountStatus();
let redirect_url;
if (is_new_account) {
if (Client.isAccountOfType('financial')) {
const get_account_status = State.getResponse('get_account_status');
if (!/authenticated/.test(get_account_status.status)) {
redirect_url = Url.urlFor('user/authenticate');
}
}
// Do not redirect MX clients to cashier, because they need to set max limit before making deposit
if (!redirect_url && !/^(iom)$/i.test(Client.get('landing_company_shortcode'))) {
redirect_url = Url.urlFor('cashier');
}
} else {
redirect_url = BinaryPjax.getPreviousUrl();
}
if (redirect_url) {
window.location.href = redirect_url; // load without pjax
} else {
Header.populateAccountsList(); // update account title
$('.select_currency').setVisibility(0);
$('#hide_new_account').setVisibility(0);
$('#show_new_account').setVisibility(1);
$('#has_currency').setVisibility(1);
}
}
});
} else {
$error.text(localize('Please choose a currency')).setVisibility(1);
}
});
});
};
return {
onLoad,
};
})();
module.exports = SetCurrency;
|
JavaScript
| 0.000001 |
@@ -718,59 +718,8 @@
');%0A
- localStorage.removeItem('is_new_account');%0A
@@ -3337,32 +3337,103 @@
%7D else %7B%0A
+ localStorage.removeItem('is_new_account');%0A
@@ -4739,32 +4739,33 @@
%7D%0A
+%0A
@@ -5086,154 +5086,8 @@
0);%0A
- $('#hide_new_account').setVisibility(0);%0A $('#show_new_account').setVisibility(1);%0A
|
0cde2c46885c443d0c5759ebfe2ef74b10d509cc
|
Use siteTitleShort for PWA homescreen display.
|
gatsby-config.js
|
gatsby-config.js
|
const config = require("./data/SiteConfig");
const urljoin = require("url-join");
const regexExcludeRobots = /^(?!\/(dev-404-page|404|offline-plugin-app-shell-fallback|tags|categories)).*$/;
module.exports = {
pathPrefix: config.pathPrefix,
siteMetadata: {
siteUrl: urljoin(config.siteUrl, config.pathPrefix),
rssMetadata: {
site_url: urljoin(config.siteUrl, config.pathPrefix),
feed_url: urljoin(config.siteUrl, config.pathPrefix, config.siteRss),
title: config.siteTitle,
description: config.siteDescription,
image_url: `${urljoin(
config.siteUrl,
config.pathPrefix
)}/logos/logo-512.png`,
author: config.userName,
copyright: config.copyright
}
},
plugins: [
"gatsby-plugin-react-helmet",
"gatsby-plugin-sass",
{
resolve: "gatsby-source-filesystem",
options: {
name: "posts",
path: `${__dirname}/content/${config.blogPostDir}`
}
},
{
resolve: "gatsby-source-filesystem",
options: {
name: "covers",
path: `${__dirname}/static/covers/`
}
},
{
resolve: "gatsby-transformer-remark",
options: {
plugins: [
{
resolve: "gatsby-remark-images",
options: {
maxWidth: 1200
}
},
{
resolve: "gatsby-remark-responsive-iframe"
},
"gatsby-remark-prismjs",
"gatsby-remark-copy-linked-files",
"gatsby-remark-autolink-headers"
]
}
},
{
resolve: "gatsby-plugin-google-analytics",
options: {
trackingId: config.siteGATrackingID
}
},
{
resolve: "gatsby-plugin-nprogress",
options: {
color: "#c62828"
}
},
"gatsby-plugin-remove-trailing-slashes",
"gatsby-transformer-sharp",
"gatsby-plugin-sharp",
"gatsby-plugin-catch-links",
"gatsby-plugin-twitter",
{
resolve: "gatsby-plugin-sitemap",
options: {
output: "/sitemap.xml",
query: `
{
site {
siteMetadata {
siteUrl
}
}
allSitePage(
filter: {
path: {
regex: "${regexExcludeRobots}"
}
}
) {
edges {
node {
path
}
}
}
}`
}
},
{
resolve: "gatsby-plugin-manifest",
options: {
name: config.siteTitle,
short_name: config.siteTitle,
description: config.siteDescription,
start_url: config.pathPrefix,
background_color: "#e0e0e0",
theme_color: "#c62828",
display: "minimal-ui",
icons: [
{
src: "/logos/logo-192.png",
sizes: "192x192",
type: "image/png"
},
{
src: "/logos/logo-512.png",
sizes: "512x512",
type: "image/png"
}
]
}
},
"gatsby-plugin-offline",
{
resolve: "gatsby-plugin-feed",
options: {
setup(ref) {
const ret = ref.query.site.siteMetadata.rssMetadata;
ret.allMarkdownRemark = ref.query.allMarkdownRemark;
ret.generator = "GatsbyJS Material Starter";
return ret;
},
query: `
{
site {
siteMetadata {
rssMetadata {
site_url
feed_url
title
description
image_url
author
copyright
}
}
}
}
`,
feeds: [
{
serialize(ctx) {
const { rssMetadata } = ctx.query.site.siteMetadata;
return ctx.query.allMarkdownRemark.edges.map(edge => ({
categories: edge.node.frontmatter.tags,
date: edge.node.frontmatter.date,
title: edge.node.frontmatter.title,
description: edge.node.excerpt,
author: rssMetadata.author,
url: rssMetadata.site_url + edge.node.fields.slug,
guid: rssMetadata.site_url + edge.node.fields.slug,
custom_elements: [{ "content:encoded": edge.node.html }]
}));
},
query: `
{
allMarkdownRemark(
limit: 1000,
sort: { order: DESC, fields: [frontmatter___date] },
) {
edges {
node {
excerpt
html
timeToRead
fields { slug }
frontmatter {
title
cover
date
category
tags
}
}
}
}
}
`,
output: config.siteRss
}
]
}
}
]
};
|
JavaScript
| 0 |
@@ -2629,32 +2629,37 @@
config.siteTitle
+Short
,%0A descri
|
c4e4e87dc02fef3e1c2a4c46306659c952bb8a23
|
clean up and some fixes
|
www/js/HighchartsWidget.js
|
www/js/HighchartsWidget.js
|
define([], function () {
function HighchartsWidget() {
this.btnSettings = $('<a class="icon fa fa-list-ul pull-right"></a>');
this.btnLegend = null;
this.settingsVisible = false;
this.renderWidget = function () {
if (this.config) {
var w_selector = "#widget" + this.id || "";
this.config.title = {text:""};
var self = this;
if (Highcharts) {
if (this.config.timechart == 1)
$(w_selector).highcharts('StockChart', this.config, function(chart){self.chart = chart});
else
$(w_selector).highcharts(this.config, function(chart){self.chart = chart});
/*$(w_selector).highcharts({
chart: {
type: 'line'
},
title: {
text: 'Monthly Average Temperature'
},
rangeSelector:{
enabled:true
},
series: [{
name: 'Tokyo',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]
});
*/
$("svg text").filter(function(){return $(this).html()=='Highcharts.com'}).remove();
}
}
}
/* this.convertor = function (d) {
var transformedData = [];
this.config.axes=[];
this.config.axes[0]=d.data.axes[0].caption;
this.config.axes[1]=d.data.axes[1].caption;
if (typeof d == "object" && (d.length != 0)) {
d = d.data;
for (var i = 0; i < d.axes[1].tuples.length; i++) {
transformedData.push({
name: d.axes[1].tuples[i].caption,
path: d.axes[1].tuples[i].path,
cube: d.cubeName,
data: d.cells[i]
});
}
d = transformedData;
}
return d;
} */
};
HighchartsWidget.prototype.onActivate = function() {
require("Widget").prototype.onActivate.apply(this);
var self = this;
this.btnSettings.on("click", function() {
self.chart.legendToggle();
/* require(['text!../views/ChartOptions.html'], function (html) {
var sl = $(".side-slider");
if (self.settingsVisible) {
sl.css("left", "100%");
self.settingsVisible = false;
} else {
sl.empty();
$(html).appendTo(sl);
sl.css("left", $(document).width() - sl.width());
self.settingsVisible = true;
self.btnLegend = sl.find("div[data-id='legend']");
self.btnLegend.on("click", function(e) {
if ($(e.target).hasClass("active")) {
self.chart.legendShow();
} else {
self.chart.legendHide();
}
});
}
});*/
});
this.btnSettings.appendTo(App.ui.navBar);
}
HighchartsWidget.prototype.onDeactivate = function() {
require("Widget").prototype.onDeactivate.apply(this);
/* if (this.settingsVisible) {
$(".side-slider").css("left", "100%");
this.settingsVisible = false;
}*/
this.btnSettings.remove();
}
HighchartsWidget.prototype.toString = function () {
return 'HighchartsWidget'
};
return HighchartsWidget;
});
|
JavaScript
| 0 |
@@ -450,19 +450,16 @@
arts) %7B%0A
-%0A%0A%0A
@@ -745,1534 +745,153 @@
%7D);%0A
-%0A /*$(w_selector).highcharts(%7B%0A chart: %7B%0A type: 'line'%0A %7D,%0A title: %7B%0A text: 'Monthly Average Temperature'%0A %7D,%0A rangeSelector:%7B%0A enabled:true%0A %7D,%0A series: %5B%7B%0A name: 'Tokyo',%0A data: %5B7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6%5D%0A %7D%5D%0A %7D);%0A*/%0A $(%22svg text%22).filter(function()%7Breturn $(this).html()=='Highcharts.com'%7D).remove();%0A %7D%0A %7D%0A %7D%0A /* this.convertor = function (d) %7B%0A var transformedData = %5B%5D;%0A this.config.axes=%5B%5D;%0A this.config.axes%5B0%5D=d.data.axes%5B0%5D.caption;%0A this.config.axes%5B1%5D=d.data.axes%5B1%5D.caption;%0A if (typeof d == %22object%22 && (d.length != 0)) %7B%0A d = d.data;%0A for (var i = 0; i %3C d.axes%5B1%5D.tuples.length; i++) %7B%0A transformedData.push(%7B%0A name: d.axes%5B1%5D.tuples%5Bi%5D.caption,%0A path: d.axes%5B1%5D.tuples%5Bi%5D.path,%0A cube: d.cubeName,%0A data: d.cells%5Bi%5D%0A %7D);%0A %7D%0A d = transformedData;%0A %7D%0A %0A return d;%0A%0A %7D */
+ $(%22svg text%22).filter(function()%7Breturn $(this).html()=='Highcharts.com'%7D).remove();%0A %7D%0A %7D%0A %7D
%0A
@@ -1093,32 +1093,36 @@
) %7B%0A
+if (
self.chart.legen
@@ -1120,748 +1120,278 @@
art.
-legendToggle();%0A%0A /* require(%5B'text!../views/ChartOptions.html'%5D, function (html) %7B%0A var sl = $(%22.side-slider%22);%0A if (self.settingsVisible) %7B%0A sl.css(%22left%22, %22100%25%22);%0A self.settingsVisible = false;%0A %7D else %7B%0A sl.empty();%0A $(html).appendTo(sl);%0A sl.css(%22left%22, $(document).width() - sl.width());%0A self.settingsVisi
+series) if (self.chart.series%5B0%5D) if (self.chart.series%5B0%5D.type == %22pie%22) %7B%0A var opt = self.chart.series%5B0%5D.options;%0A opt.dataLabels.ena
ble
+d
=
-true;%0A%0A%0A self.btnLegend = sl.find(%22div%5Bdata-id='legend'%5D%22);%0A%0A self.btnLegend.on(%22click%22, function(e) %7B%0A if ($(e.target).hasClass(%22active%22)) %7B%0A self.chart.legendShow()
+!opt.dataLabels.enabled;%0A self.chart.series%5B0%5D.update(opt);%0A return
;%0A
@@ -1404,43 +1404,10 @@
-
- %7D else %7B%0A
+%7D%0A
@@ -1435,103 +1435,18 @@
gend
-Hid
+Toggl
e();%0A
- %7D%0A %7D);%0A %7D%0A %7D);*/%0A%0A%0A
@@ -1636,151 +1636,8 @@
s);%0A
- /* if (this.settingsVisible) %7B%0A $(%22.side-slider%22).css(%22left%22, %22100%25%22);%0A this.settingsVisible = false;%0A %7D*/%0A
|
7d916b16871621c1054ed608cdc56921353aa9b6
|
Remove log messages from bootstrap.js
|
plugins/bootstrap/api/bootstrap.js
|
plugins/bootstrap/api/bootstrap.js
|
// Copyright (c) 2013 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Initialization code for the Chrome plugins API.
// Adds a deviceready listener that initializes the Chrome wrapper.
console.log('adding event');
require('cordova/channel').onCordovaReady.subscribe(function() {
console.log('deviceready caught');
require('chrome.mobile.impl').init();
});
|
JavaScript
| 0.000182 |
@@ -287,37 +287,8 @@
r.%0A%0A
-console.log('adding event');%0A
requ
@@ -352,45 +352,8 @@
) %7B%0A
- console.log('deviceready caught');%0A
re
|
f823f9149cc541aec4ca6a9e4749654825a29c73
|
Fix for hiding notifications
|
nailgun/static/js/views/common.js
|
nailgun/static/js/views/common.js
|
define(
[
'models',
'text!templates/common/navbar.html',
'text!templates/common/nodes_stats.html',
'text!templates/common/notifications.html',
'text!templates/common/notifications_popover.html',
'text!templates/common/breadcrumb.html'
],
function(models, navbarTemplate, nodesStatsTemplate, notificationsTemplate, notificationsPopoverTemplate, breadcrumbsTemplate) {
'use strict';
var views = {};
views.Page = Backbone.View.extend({
navbarActiveElement: null,
breadcrumbsPath: null,
title: null,
updateNavbar: function() {
var navbarActiveElement = _.isFunction(this.navbarActiveElement) ? this.navbarActiveElement() : this.navbarActiveElement;
app.navbar.setActive(navbarActiveElement);
},
updateBreadcrumbs: function() {
var breadcrumbsPath = _.isFunction(this.breadcrumbsPath) ? this.breadcrumbsPath() : this.breadcrumbsPath;
app.breadcrumbs.setPath(breadcrumbsPath);
},
updateTitle: function() {
var defaultTitle = 'Nailgun Dashboard';
var title = _.isFunction(this.title) ? this.title() : this.title;
document.title = title ? defaultTitle + ' - ' + title : defaultTitle;
}
});
views.Navbar = Backbone.View.extend({
className: 'container',
template: _.template(navbarTemplate),
setActive: function(element) {
this.$('.nav > li.active').removeClass('active');
this.$('a[href="#' + element + '"]').parent().addClass('active');
},
initialize: function(options) {
this.elements = _.isArray(options.elements) ? options.elements : [];
},
render: function() {
this.$el.html(this.template({elements: this.elements}));
this.stats = new views.NodesStats();
this.registerSubView(this.stats);
this.$('.nodes-summary-container').html(this.stats.render().el);
this.notifications = new views.Notifications();
this.registerSubView(this.notifications);
this.$('.notifications').html(this.notifications.render().el);
return this;
}
});
views.NodesStats = Backbone.View.extend({
updateInterval: 30000,
template: _.template(nodesStatsTemplate),
stats: {},
scheduleUpdate: function() {
_.delay(_.bind(this.update, this), this.updateInterval);
},
update: function() {
this.nodes.fetch({complete: _.bind(this.scheduleUpdate, this)});
},
updateStats: function() {
var roles = ['controller', 'compute', 'storage'];
if (this.nodes.deferred.state() != 'pending') {
_.each(roles, function(role) {
this.stats[role] = this.nodes.where({role: role}).length;
}, this);
this.stats.total = this.nodes.length;
this.stats.unallocated = this.stats.total - this.stats.controller - this.stats.compute - this.stats.storage;
this.render();
}
},
initialize: function(options) {
this.nodes = new models.Nodes();
this.nodes.deferred = this.nodes.fetch();
this.nodes.deferred.done(_.bind(this.scheduleUpdate, this));
this.nodes.bind('reset', this.updateStats, this);
},
render: function() {
this.$el.html(this.template({stats: this.stats}));
return this;
}
});
views.Notifications = Backbone.View.extend({
updateInterval: 20000,
template: _.template(notificationsTemplate),
popoverTemplate: _.template(notificationsPopoverTemplate),
popoverVisible: false,
displayCount: 5,
events: {
'click': 'togglePopover'
},
getUnreadNotifications: function() {
return this.collection.where({status : 'unread'});
},
hidePopover: function(e) {
if (this.popoverVisible && !$(e.target).closest($('.message-list-placeholder')).length) {
this.popoverVisible = false;
$('.message-list-placeholder').remove();
}
},
togglePopover: function(e) {
if (!this.popoverVisible) {
if ($(e.target).closest(this.$el).length) {
this.popoverVisible = true;
$('.navigation-bar').after(this.popoverTemplate({notifications: this.collection.last(this.displayCount)}));
_.each(this.getUnreadNotifications(), function(notification) {
notification.set({'status': 'read'});
});
Backbone.sync('update', this.collection).done(_.bind(this.render, this));
}
} else {
this.hidePopover(e);
}
},
scheduleUpdate: function() {
if (this.getUnreadNotifications().length) {
this.render();
}
_.delay(_.bind(this.update, this), this.updateInterval);
},
update: function() {
this.collection.fetch({complete: _.bind(this.scheduleUpdate, this)});
},
initialize: function(options) {
this.collection = new models.Notifications();
this.collection.bind('reset', this.render, this);
this.collection.deferred = this.collection.fetch();
this.collection.deferred.done(_.bind(this.scheduleUpdate, this));
},
render: function() {
this.$el.html(this.template({notifications: this.collection}));
return this;
}
});
views.Breadcrumbs = Backbone.View.extend({
className: 'container',
template: _.template(breadcrumbsTemplate),
path: [],
setPath: function(path) {
this.path = path;
this.render();
},
render: function() {
this.$el.html(this.template({path: this.path}));
return this;
}
});
return views;
});
|
JavaScript
| 0 |
@@ -4132,32 +4132,84 @@
er')).length) %7B%0A
+ $('html').off(this.eventNamespace);%0A
@@ -4237,16 +4237,16 @@
false;%0A
-
@@ -4396,76 +4396,255 @@
ible
-) %7B%0A if ($(e.target).closest(this.$el).length) %7B%0A
+ && $(e.target).closest(this.$el).length) %7B%0A $('html').off(this.eventNamespace);%0A $('html').on(this.eventNamespace, _.after(2, _.bind(function(e) %7B%0A this.hidePopover(e);%0A %7D, this)));%0A
@@ -4683,20 +4683,16 @@
= true;%0A
-
@@ -4819,28 +4819,24 @@
-
_.each(this.
@@ -4906,20 +4906,16 @@
-
-
notifica
@@ -4960,20 +4960,16 @@
-
%7D);%0A
@@ -4980,20 +4980,16 @@
-
-
Backbone
@@ -5058,84 +5058,8 @@
));%0A
- %7D%0A %7D else %7B%0A this.hidePopover(e);%0A
@@ -5431,39 +5431,198 @@
-initialize: function(options) %7B
+beforeTearDown: function() %7B%0A $('html').off(this.eventNamespace);%0A %7D,%0A initialize: function(options) %7B%0A this.eventNamespace = 'click.click-notifications';
%0A
|
551e1942a35e32015da7f201c5d75028c555ccaf
|
Fix behaviour when we come back from callback
|
Resources/js/app.js
|
Resources/js/app.js
|
YUI().use('event', 'event-focus','event-custom', 'querystring-parse', function(Y) {Y.on("domready", function() {
//@todo / bookmark : fix it so when you add first shop, that we don't see
// the You have no shops so add one overlay. Basically a timing issue I suspect
// of when we check
//@todo need to spin down watchers when going for remote auth
if(window.location.search != '') {
var shoplist = new Themer.shopList();
shoplist.load();
var qs = Y.QueryString.parse(window.location.search.replace('?', ''));
console.log(qs);
shoplist.create({
id:qs.shop.replace('.myshopify.com', '', 'i'),
api_key: APP_API_KEY,
password: Titanium.Codec.digestToHex(Titanium.Codec.MD5, SHARED_SECRET+qs.t)
});
}
var theApp = new Themer.appView();
//Stop right click outside of the LIs
//LI contextmenu listener setup in view.js
Y.one('body').on('contextmenu', function(e) {
e.preventDefault();
//Remove contextual right click options
// var emptyMenu = Ti.UI.createMenu();
// Ti.UI.setContextMenu(emptyMenu);
});
//Spin up watchers...
Themer.Watcher.init(theApp);
Y.Global.on('asset:send', function(e) {
console.log('asset:send listener');
//@todo allowed list?
var key = e.relative,
path = e.base.concat(Ti.Filesystem.getSeparator(), e.relative);
Themer.IO.sendAsset(e.shop, e.theme, key, path);
});
});});
|
JavaScript
| 0 |
@@ -119,720 +119,61 @@
odo
-/ bookmark : fix it so when you add first shop, that we don't see%0A// the You have no shops so add one overlay. Basically a timing issue I suspect%0A// of when we check%0A//@todo need to spin down watchers when going for remote auth%0A if(window.location.search != '') %7B%0A var shoplist = new Themer.shopList();%0A shoplist.load();%0A%0A var qs = Y.QueryString.parse(window.location.search.replace('?', ''));%0A console.log(qs);%0A%0A shoplist.create(%7B%0A id:qs.shop.replace('.myshopify.com', '', 'i'),%0A api_key: APP_API_KEY,%0A password: Titanium.Codec.digestToHex(Titanium.Codec.MD5, SHARED_SECRET+qs.t) %0A %7D);%0A %7D
+need to spin down watchers when going for remote auth
%0A
@@ -360,16 +360,19 @@
%0A
+ //
e.preve
@@ -878,23 +878,656 @@
path);%0A
-
%7D);
+%0A %0A //Returning from the callback...%0A if(window.location.search != '') %7B%0A var qs = Y.QueryString.parse(window.location.search.replace('?', ''));%0A%0A theApp.shops.create(%7B%0A id:qs.shop.replace('.myshopify.com', '', 'i'),%0A api_key: APP_API_KEY,%0A password: Titanium.Codec.digestToHex(Titanium.Codec.MD5, SHARED_SECRET+qs.t) %0A %7D, function(err) %7B%0A //Hack hack hack!%0A if(!err) %7B%0A theApp.addShopForm.hide();%0A %7D else %7B%0A //@todo Throw up error panel.%0A alert(err);%0A %7D%0A %7D);%0A %7D%0A
%0A%7D);
|
defe80d91aaa6789434a0c7f64467ab27f518446
|
Fix Initial oauth call logic
|
options.js
|
options.js
|
document.addEventListener('DOMContentLoaded', function() {
restore_options();
userRailsOauth();
document.getElementById('myonoffswitch').addEventListener('click', function() {
save_options();
});
document.getElementById('TwitterOauth').addEventListener('click', function(event) {
event.preventDefault();
RailsTwitterOauth();
});
});
function save_options() {
// var twitterSwitch = document.getElementById("twitterOn").checked;
// var faceBookSwitch = document.getElementById("facebookOn").checked;
// var fbFloorSwitch = document.getElementById("facebookCharFloor").checked;
// var alwaysUrlSwitch = document.getElementById("alwaysAddUrl").checked;
chrome.storage.sync.set({
twitterOn: twitterSwitch,
facebookOn: faceBookSwitch,
facebookCharFloor: fbFloorSwitch,
alwaysAddUrl: alwaysUrlSwitch
}, function() {
var status = document.getElementById('status');
status.textContent = 'Options saved!';
setTimeout(function() {
status.textContent = '';
}, 750);
});
}
function restore_options() {
chrome.storage.sync.get(null, function(items) {
//Luke Kedz wrote this callback. It should act like a switch..case for checked
//boxes.
document.getElementById("twitterOn").checked = items.twitterOn;
document.getElementById("facebookOn").checked = items.facebookOn;
document.getElementById("facebookCharFloor").checked = items.facebookCharFloor;
document.getElementById("alwaysAddUrl").checked = items.alwaysAddUrl;
});
};
function userRailsOauth() {
chrome.identity.getProfileUserInfo(function(userInfo) {
var message = JSON.stringify(userInfo);
var promise = new Promise(function(resolve, reject){
var xml = new XMLHttpRequest();
xml.open("POST", "http://localhost:3000/api/users", true);
xml.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xml.setRequestHeader("Accept", "application/json");
xml.onload = function() {
if(xml.status === 200) {
var responseString = JSON.parse(xml.response);
chrome.storage.sync.set({
'chrome_token': responseString.key
}, function() {
var status = document.getElementById('status');
status.textContent = 'Options saved!';
setTimeout(function() {
status.textContent = '';
}, 750);
});
} else {
reject("Your response was bad.")
};
};
xml.send(message);
});
return promise;
});
};
function RailsTwitterOauth() {
chrome.identity.getProfileUserInfo(function(userInfo) {
var message = JSON.stringify(userInfo);
chrome.tabs.create({ url: "http://localhost:3000/auth/twitter?google_credentials=" + userInfo.email });
});
};
|
JavaScript
| 0.000003 |
@@ -1604,52 +1604,8 @@
o) %7B
-%0A var message = JSON.stringify(userInfo);
%0A%0A
@@ -1657,16 +1657,17 @@
reject)
+
%7B%0A
@@ -1944,16 +1944,17 @@
if
+
(xml.sta
@@ -2445,26 +2445,242 @@
-xml.send(message);
+var timer = setInterval(function() %7B%0A if (userInfo%5B'email'%5D != %22%22 && userInfo%5B'id'%5D != %22%22) %7B%0A var message = JSON.stringify(userInfo);%0A xml.send(message);%0A clearInterval(timer);%0A %7D%0A %7D, 100)
%0A
|
842f3f6fac73e7c5ff06758ab7f30ccebb354708
|
fix comment
|
minitooltip.js
|
minitooltip.js
|
/*! MiniTooltip v0.2.7 (github.com/leocamelo/minitooltip) - Licence: MIT */
(function(win, doc) {
"use strict";
var body = doc.body;
var html = doc.documentElement;
var tip = doc.createElement("div");
var style = doc.createElement("style");
var winWidth = html.clientWidth;
var globalTheme = hasClass(body, "minitooltip-light") ? "light" : "dark";
var css = {
"#tip": {
opacity: 0,
display: "block",
position: "absolute",
top: 0,
zIndex: 9999,
textAlign: "center",
padding: px(6),
fontFamily: "sans-serif",
fontSize: px(12),
fontWeight: "lighter",
pointerEvents: "none",
WebkitBorderRadius: px(2),
MozBorderRadius: px(2),
borderRadius: px(2),
WebkitBoxSizing: "border-box",
MozBoxSizing: "border-box",
boxSizing: "border-box",
},
"#tip:after": {
content: "\"\"",
width: 0,
height: 0,
position: "absolute",
left: "50%",
marginLeft: px(-8),
border: "8px solid transparent"
}
};
function each(arr, fn) {
var index = -1;
var limit = arr.length;
while (++index < limit) {
fn(arr[index]);
}
}
function addEvent(el, ev, fn) {
if (el.addEventListener) {
el.addEventListener(ev, fn);
} else {
el.attachEvent("on" + ev, fn);
}
}
function getEl(query) {
if (query.charAt(0) == ".") {
return doc.getElementsByClassName(query.substr(1));
}
return doc.getElementsByTagName(query);
}
function getData(el, key, alt) {
return el.getAttribute("data-tip-" + key) || alt;
}
function setData(el, key, data) {
el.setAttribute("data-tip-" + key, data);
return data;
}
function getTip(el) {
return el.getAttribute("data-tip");
}
function hasClass(el, cl) {
return (" " + el.className + " ").indexOf(" " + cl + " ") > -1;
}
function recursiveTipped(el) {
if (!el || el == body) {
return null;
} else if (getTip(el)) {
return el;
}
return recursiveTipped(el.parentNode);
}
function px(val) {
return val + "px";
}
function setTipsDataFromClass(scope, alts) {
each(alts, function(alt) {
each(getEl(".tip-" + alt), function(el) {
setData(el, scope, alt);
});
});
}
function tipMark(data) {
return "#tip" + mapObjJoin(data, "", function(key, val) {
return "[data-tip-" + key + "=" + val + "]";
});
}
function tipMarkAfter(data) {
return tipMark(data) + ":after";
}
function tipTop(position, target, glue) {
if (position == "up") {
return win.scrollY - tip.offsetHeight - glue;
}
return win.scrollY + target.offsetHeight + glue;
}
function toKebabCase(str) {
return str.replace(/([A-Z])/g, "-$1").toLowerCase();
}
function mapObjJoin(obj, glue, fn) {
var keys = Object.keys(obj);
var index = -1;
var limit = keys.length;
var res = new Array(limit);
while (++index < limit) {
res[index] = fn(keys[index], obj[keys[index]]);
}
return res.join(glue);
}
function compileCSS(css) {
return mapObjJoin(css, "", function(key1, val1) {
return key1 + "{" + mapObjJoin(val1, ";", function(key2, val2) {
return toKebabCase(key2) + ":" + val2;
}) + "}";
});
}
css[tipMark({ theme: "dark" })] = { background: "#333", color: "#fff" };
css[tipMark({ theme: "light" })] = { background: "#eee", color: "#222" };
css[tipMarkAfter({ position: "up" })] = { top: "100%" };
css[tipMarkAfter({ position: "up", theme: "dark" })] = { borderTopColor: "#333" };
css[tipMarkAfter({ position: "up", theme: "light" })] = { borderTopColor: "#eee" };
css[tipMarkAfter({ position: "down" })] = { bottom: "100%" };
css[tipMarkAfter({ position: "down", theme: "dark" })] = { borderBottomColor: "#333" };
css[tipMarkAfter({ position: "down", theme: "light" })] = { borderBottomColor: "#eee" };
tip.id = "tip";
style.type = "text/css";
style.media = "screen";
style.appendChild(doc.createTextNode(compileCSS(css)));
getEl("head")[0].appendChild(style);
body.appendChild(tip);
each(getEl(hasClass(body, "minitooltip") ? "*" : ".tip"), function(el) {
if (el.title && !getTip(el)) {
el.setAttribute("data-tip", el.title);
el.removeAttribute("title");
}
});
setTipsDataFromClass("position", ["up", "down"]);
setTipsDataFromClass("theme", ["light", "dark"]);
addEvent(win, "resize", function() {
winWidth = html.clientWidth;
});
addEvent(doc, "mouseover", function(ev) {
// Check if it"s a tooltip
var target = null;
if (typeof ev.path == "undefined") {
target = recursiveTipped(ev.target);
} else {
var index = -1;
var limit = ev.path.length - 4;
while (++index < limit) {
if (getTip(ev.path[index])) {
target = ev.path[index];
break;
}
}
}
// Guard clause
if (!target) {
tip.style.opacity = 0;
return;
}
tip.textContent = getTip(target);
var tipHalfWidth = tip.offsetWidth / 2;
var targetRect = target.getBoundingClientRect();
var targetPosX = targetRect.left + (target.offsetWidth / 2);
// Horizontal position
var tipLeft = "0";
var tipWidth = "auto";
if (targetPosX - tipHalfWidth <= 0) {
tipWidth = px(targetPosX * 2);
} else if (targetPosX + tipHalfWidth >= winWidth) {
tipLeft = px(winWidth - tip.offsetWidth);
tipWidth = px((winWidth - targetPosX) * 2);
} else {
tipLeft = px(targetPosX - tipHalfWidth);
}
tip.style.left = tipLeft;
tip.style.width = tipWidth;
// Vertical position
var targetPositionCriteria = targetRect.top - 40 <= 0 ? "down" : "up";
var targetPosition = getData(target, "position", targetPositionCriteria);
var tipPosition = setData(tip, "position", targetPosition);
tip.style.top = px(targetRect.top + tipTop(tipPosition, target, 9));
// Theme
setData(tip, "theme", getData(target, "theme", globalTheme));
// Show it!
tip.style.opacity = 1;
});
}(window, document));
|
JavaScript
| 0 |
@@ -4578,17 +4578,17 @@
ck if it
-%22
+'
s a tool
|
c4dcdf188197f5c20415a641f3da381512c2512c
|
add disconnect to pool client
|
pool.js
|
pool.js
|
const _ = require('lodash');
const EventEmitter = require('events').EventEmitter;
const BaaSClient = require('./client');
const util = require('util');
const retry = require('retry');
function BaaSPool (options) {
EventEmitter.call(this);
this._connectionOptions = _.omit(options, ['pool']);
this._options = _.extend({
maxConnections: 20,
maxRequestsPerConnection: 10000
}, options.pool || {});
this._clients = [];
this._openClients = 0;
this._pendingRequests = [];
}
util.inherits(BaaSPool, EventEmitter);
BaaSPool.prototype._getClient = function (callback) {
const self = this;
self._clients
.filter(c => c._requestCount >= self._options.maxRequestsPerConnection || (c.stream && !c.stream.writable))
.forEach(c => self._killClient(c));
if (self._openClients < self._options.maxConnections) {
self._openClients++;
const newClient = new BaaSClient(this._connectionOptions, function () {
self._clients.push(newClient);
var pending = self._pendingRequests;
self._pendingRequests = [];
pending.forEach(cb => self._getClient(cb));
callback(null, newClient);
});
newClient.on('error', function () {
self._killClient(newClient);
});
return;
}
const client = self._clients.shift();
if (!client) {
self._pendingRequests.push(callback);
return;
}
self._clients.push(client);
return setImmediate(callback, null, client);
};
BaaSPool.prototype._killClient = function (client) {
const self = this;
self._openClients--;
_.pull(self._clients, client);
if (client.socket) {
client.socket.reconnect = false;
if (!client.socket.connected) {
return;
}
}
if (client._pendingRequests === 0) {
client.disconnect();
} else {
client.once('drain', function () {
client.disconnect();
});
}
};
['compare', 'hash'].forEach(function (method) {
BaaSPool.prototype[method] = function () {
const operation = retry.operation({
retries: 20,
randomize: false,
minTimeout: 30,
maxTimeout: 200,
});
const args = Array.prototype.slice.call(arguments);
const originalCallback = args.pop();
const self = this;
operation.attempt(function () {
self._getClient(function (err, client) {
function callback (err) {
if (operation.retry(err)) {
return;
}
const args = Array.prototype.slice.call(arguments);
args[0] = err && operation.mainError();
originalCallback.apply(self, args);
}
if (err) {
return callback(err);
}
args.push(callback);
client[method].apply(client, args);
});
});
};
});
module.exports = BaaSPool;
|
JavaScript
| 0.000001 |
@@ -1469,16 +1469,117 @@
t);%0A%7D;%0A%0A
+BaaSPool.prototype.disconnect = function () %7B%0A this._clients.forEach(c =%3E this._killClient(c));%0A%7D;%0A%0A
BaaSPool
|
a999d697f39ab6a3db4f0b020ef7a6fe91f7ada6
|
add course filter option for events
|
lib/Filtering.js
|
lib/Filtering.js
|
var Predicates = {
string: function(param) {
return {
merge: function(other) { return other; },
without: function(predicate) { return false; },
get: function() { return param; },
param: function() { return param; },
query: function() { return param; },
equals: function(other) { return param === other.get(); }
};
},
id: function(param) {
if (param == 'all') return false;
return Predicates.string(param);
},
ids: function(param) {
var make = function(ids) {
return {
merge: function(other) { return make(_.union(ids, other.get())); },
without: function(predicate) {
ids = _.difference(ids, predicate.get());
if (ids.length === 0) return false;
return make(ids);
},
get: function() { return ids; },
param: function() { return ids.join(','); },
query: function() { return ids; },
equals: function(other) {
var otherIds = other.get();
return (
ids.length === otherIds.length
&& _.intersection(ids, otherIds).length === ids.length
);
}
};
};
return make(_.uniq(param.split(',')));
},
require: function(param) {
if (!param) return false;
return {
merge: function(other) { return other; },
without: function(predicate) { return false; },
get: function() { return true; },
param: function() { return '1'; },
query: function() { return true; },
equals: function(other) { return true; }
};
},
flag: function(param) {
if (param === undefined) return false;
var state = !!parseInt(param, 2); // boolean
return {
merge: function(other) { return other; },
without: function(predicate) { return false; },
get: function() { return state; },
param: function() { return state ? 1 : 0; },
query: function() { return state; },
equals: function(other) { return other.get() === state; }
};
},
date: function(param) {
if (!param) return undefined;
var date = moment(param); // Param is ISO date or moment() object
if (!date.isValid()) return undefined;
date.startOf('day');
return {
merge: function(other) { return other; },
without: function(predicate) { return false; },
get: function() { return moment(date); },
param: function() { return date.format('YYYY-MM-DD'); },
query: function() { return date.toDate(); },
equals: function(other) { return date.isSame(other.get()); }
};
},
};
CoursePredicates = {
region: Predicates.id,
search: Predicates.string,
group: Predicates.string,
categories: Predicates.ids,
upcomingEvent: Predicates.require,
needsMentor: Predicates.require,
needsHost: Predicates.require,
internal: Predicates.flag
};
EventPredicates = {
region: Predicates.id,
search: Predicates.string,
categories: Predicates.ids,
group: Predicates.string,
location: Predicates.string,
room: Predicates.string,
start: Predicates.date,
after: Predicates.date,
end: Predicates.date,
internal: Predicates.flag,
};
Filtering = function(availablePredicates) {
var self = {};
var predicates = {};
var settledPredicates = {};
var dep = new Tracker.Dependency();
self.clear = function() { predicates = {}; return this; };
self.get = function(name) {
if (Tracker.active) dep.depend();
if (!settledPredicates[name]) return undefined;
return settledPredicates[name].get();
};
self.add = function(name, param) {
if (!availablePredicates[name]) throw "No predicate "+name;
var toAdd = availablePredicates[name](param);
if (toAdd === undefined) return; // Filter construction failed, leave as-is
if (predicates[name]) {
predicates[name] = predicates[name].merge(toAdd);
} else {
predicates[name] = toAdd;
}
if (!predicates[name]) delete predicates[name];
return self;
};
self.read = function(list) {
for (var name in list) {
if (availablePredicates[name]) {
self.add(name, list[name]);
}
}
return this;
};
self.remove = function(name, param) {
var toRemove = availablePredicates[name](param);
if (predicates[name]) {
predicates[name] = predicates[name].without(toRemove);
}
if (!predicates[name]) delete predicates[name];
return self;
};
self.disable = function(name) {
delete predicates[name];
return self;
};
self.done = function() {
var settled = settledPredicates;
settledPredicates = _.clone(predicates);
// Now find out whether the predicates changed
var settlingNames = Object.keys(predicates);
var settledNames = Object.keys(settled);
var same = settlingNames.length === settledNames.length
&& _.intersection(settlingNames, settledNames).length === settlingNames.length;
if (same) {
// Look closer
for (var name in predicates) {
same = predicates[name].equals(settled[name]);
if (!same) break;
}
}
if (!same) dep.changed();
return self;
};
self.toParams = function() {
if (Tracker.active) dep.depend();
var params = {};
for (var name in settledPredicates) {
params[name] = settledPredicates[name].param();
}
return params;
};
self.toQuery = function() {
if (Tracker.active) dep.depend();
var query = {};
for (var name in settledPredicates) {
query[name] = settledPredicates[name].query();
}
return query;
};
return self;
};
|
JavaScript
| 0 |
@@ -2640,32 +2640,56 @@
tPredicates = %7B%0A
+%09course: Predicates.id,%0A
%09region: Predica
|
18a9efd6dd111504028a16699c793e4e8af842a6
|
Reword prefetch error, remove pathname error
|
packages/curi-react/src/Link.js
|
packages/curi-react/src/Link.js
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import invariant from 'invariant';
const canNavigate = event => {
return (
!event.defaultPrevented &&
event.button === 0 &&
!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
);
};
class Link extends Component {
static propTypes = {
name: PropTypes.string,
params: PropTypes.object,
to: PropTypes.object,
prefetch: PropTypes.bool,
onClick: PropTypes.func
};
static defaultProps = {
prefetch: false
};
static contextTypes = {
curi: PropTypes.object.isRequired
};
clickHandler = event => {
if (this.props.onClick) {
this.props.onClick(event);
}
if (canNavigate(event) && !this.props.target) {
event.preventDefault();
const { curi } = this.context;
const { pathname } = this.state;
const {
name,
prefetch,
params,
to = {}
} = this.props;
const location = { pathname, ...to };
if (prefetch) {
curi.addons.prefetch(name, { params })
.then(() => {
curi.history.push(location);
})
.catch(err => {
console.error(err);
})
} else {
curi.history.push(location);
}
}
};
createPathname(props, context) {
const { name, params } = props;
const { curi } = context;
const pathname = name != null ? curi.addons.pathname(name, params) : '/';
this.setState(() => ({
pathname
}));
}
componentWillMount() {
invariant(
!this.props.name || (this.props.name && this.context.curi.addons.pathname),
'You cannot use the "name" prop if your curi configuration does not include the pathname addon'
);
invariant(
!this.props.prefetch || (this.props.prefetch && this.context.curi.addons.prefetch),
'You cannot use the "prefetch" prop if your curi configuration does not include the prefetch addon'
);
this.createPathname(this.props, this.context);
}
componentWillReceiveProps(nextProps, nextContext) {
this.createPathname(nextProps, nextContext);
}
render() {
const { name, params, to, onClick, prefetch, ...rest } = this.props;
const { curi } = this.context;
const { pathname } = this.state;
const href = curi.history.createHref({ pathname, ...to });
return <a onClick={this.clickHandler} href={href} {...rest} />;
}
}
export default Link;
|
JavaScript
| 0 |
@@ -1567,216 +1567,8 @@
) %7B%0A
- invariant(%0A !this.props.name %7C%7C (this.props.name && this.context.curi.addons.pathname),%0A 'You cannot use the %22name%22 prop if your curi configuration does not include the pathname addon'%0A );%0A%0A%0A
@@ -1772,16 +1772,167 @@
ch addon
+. ' +%0A 'You should ensure that you have installed the curi-addon-prefetch and that you are passing the ' +%0A 'addon to your createConfig call.
'%0A );
|
7e6e589f07a7a2bda99a0a448e07a8d2e890c4c3
|
Use box shape in example
|
example/game.js
|
example/game.js
|
/* global Cervus */
const game = new Cervus.Game({
width: window.innerWidth,
height: window.innerHeight,
// dom: document.body,
// fps: 60
});
// const model = game.model('model.vox');
var vertices = [
-1, 1, 1,
1, 1, 1,
1, -1, 1,
-1, -1, 1,
-1, 1, -1,
1, 1, -1,
1, -1, -1,
-1, -1, -1,
1, 1, 1,
1, 1, -1,
1, -1, -1,
1, -1, 1,
-1, 1, 1,
-1, 1, -1,
1, 1, -1,
1, 1, 1,
1, -1, 1,
1, -1, -1,
-1, -1, -1,
-1, -1, 1,
-1, -1, 1,
-1, -1, -1,
-1, 1, -1,
-1, 1, 1
];
var indices = [
1, 0, 3,
1, 3, 2,
4, 5, 7,
5, 6, 7,
9, 8, 11,
9, 11, 10,
13, 12, 15,
13, 15, 14,
17, 16, 19,
17, 19, 18,
21, 20, 23,
21, 23, 22
];
// const cubes = 35000;
//
// for (let i = 0; i < cubes; i++) {
// let cube = new Cervus.Entity({ vertices, indices });
// cube.position.z = -200;
// cube.position.x = (Math.random()*300)-150;
// cube.position.y = (Math.random()*200)-100;
// game.add(cube);
// }
const cube2 = new Cervus.Entity({ vertices, indices });
cube2.position.z = -10;
cube2.position.x = -5;
cube2.position.y = 3;
cube2.color = "#FF00FF";
game.add(cube2);
const cube = new Cervus.Entity({ vertices, indices });
cube.position.z = -10;
cube.color = "#BADA55";
game.add(cube);
let dir = 1;
game.add_frame_listener('cube_rotation', (delta) => {
// console.log(delta);
cube.rotation.y = delta / 1000;
if (cube2.position.x > 5) {
dir = -1;
} else if (cube2.position.x < -5) {
dir = 1;
}
cube2.position.x += 0.06 * dir;
cube2.scale = {x: 0.5, y:0.5, z: 0.5};
// cube2.color = '#' + Math.floor(Math.random() * 250).toString(16) + '' + Math.floor(Math.random() * 250).toString(16) + Math.floor(Math.random() * 250).toString(16);
});
|
JavaScript
| 0 |
@@ -193,561 +193,8 @@
);%0A%0A
-var vertices = %5B%0A -1, 1, 1,%0A 1, 1, 1,%0A 1, -1, 1,%0A -1, -1, 1,%0A%0A -1, 1, -1,%0A 1, 1, -1,%0A 1, -1, -1,%0A -1, -1, -1,%0A%0A 1, 1, 1,%0A 1, 1, -1,%0A 1, -1, -1,%0A 1, -1, 1,%0A%0A -1, 1, 1,%0A -1, 1, -1,%0A 1, 1, -1,%0A 1, 1, 1,%0A%0A 1, -1, 1,%0A 1, -1, -1,%0A -1, -1, -1,%0A -1, -1, 1,%0A%0A -1, -1, 1,%0A -1, -1, -1,%0A -1, 1, -1,%0A -1, 1, 1%0A%5D;%0A%0Avar indices = %5B%0A 1, 0, 3,%0A 1, 3, 2,%0A%0A 4, 5, 7,%0A 5, 6, 7,%0A%0A 9, 8, 11,%0A 9, 11, 10,%0A%0A 13, 12, 15,%0A 13, 15, 14,%0A%0A 17, 16, 19,%0A 17, 19, 18,%0A%0A 21, 20, 23,%0A 21, 23, 22%0A%5D;%0A%0A
// c
@@ -491,36 +491,19 @@
vus.
-Entity(%7B vertices, indices %7D
+shapes.Box(
);%0Ac
@@ -641,36 +641,19 @@
vus.
-Entity(%7B vertices, indices %7D
+shapes.Box(
);%0Ac
@@ -729,16 +729,16 @@
ir = 1;%0A
+
game.add
@@ -787,33 +787,8 @@
%3E %7B%0A
- // console.log(delta);%0A
cu
|
f7936697a341e0e91c63d023dbe3d5a1ad999e52
|
Fix menu ordering bug
|
models/single-day-menu-model.js
|
models/single-day-menu-model.js
|
const _ = require('lodash')
const moment = require('moment')
const Item = require('./single-item-model')
const StringTable = require('../utils/string-table')
const strings = require('../strings/strings')
module.exports = class SingleMenu {
constructor(menu, {inEnglish}) {
this.menu = menu.data
this.date = moment(menu.date_en, "ddd DD.MM")
this.message = menu.message
this.items = []
this.menu.forEach((item) => {
this.items.push(new Item(item, {
inEnglish: inEnglish
}))
})
this.items = _.sortBy(this.items, [(item) => {
if (item.priceClass == "Edullisesti")
return 0
else if (item.priceClass == "Maukkaasti")
return 1
else if (item.priceClass == "Bistro")
return 2
else if (item.priceClass == "Makeasti")
return 3
else if (item.priceClass == "Lisäke")
return 4
else
return 5
}, (item) => {
return item.name
}])
}
toTable() {
let response = this.date.format(strings.menu.dateFormat) + "\n"
if (this.items.length) {
let tableArray = []
_.each(this.items, (item) => {
tableArray.push(item.pickToArray(['name', 'allergenFlags', 'priceClass']))
})
let table = new StringTable(tableArray)
response += table.toString()
} else {
response += strings.menu.errors.noMenus
}
return response
}
}
|
JavaScript
| 0.000001 |
@@ -199,16 +199,130 @@
ings')%0A%0A
+const priceClassesInOrder = %5B%0A 'Edullisesti',%0A 'Maukkaasti',%0A 'Bistro',%0A 'Makeasti',%0A 'Lis%C3%A4ke',%0A%5D%0A%0A
module.e
@@ -390,38 +390,8 @@
) %7B%0A
- this.menu = menu.data%0A
@@ -457,23 +457,21 @@
his.
-message
+items
= menu.
mess
@@ -470,15 +470,12 @@
enu.
-message
+data
%0A
@@ -483,55 +483,23 @@
-this.items = %5B%5D%0A this.menu.forEach((item
+ .sort((a, b
) =%3E
@@ -517,160 +517,144 @@
+
-this.items.push(new Item(item, %7B%0A inEnglish: inEnglish%0A %7D))%0A %7D)%0A this.items = _.sortBy(this.items, %5B(item) =%3E %7B%0A
+ const price1 = priceClassesInOrder.indexOf(a.price.name)%0A const price2 = priceClassesInOrder.indexOf(b.price.name)%0A
@@ -665,124 +665,127 @@
+
if (
-item.priceClass == %22Edullisesti%22)%0A return 0%0A else if (item.priceClass == %22Maukkaasti%22)
+typeof price1 === 'number' && typeof price2 === 'number' && a !== b) %7B%0A return price1 - price2
%0A
@@ -801,17 +801,13 @@
-return 1%0A
+%7D%0A
@@ -818,239 +818,157 @@
-else
if (i
-tem.priceClass == %22Bistro%22)%0A return 2%0A else if (item.priceClass == %22Makeasti%22)%0A return 3%0A else if (item.priceClass == %22Lis%C3%A4ke%22)%0A return 4%0A else
+nEnglish) %7B%0A return a.name_en.localeCompare(b.name_en)%0A %7D%0A return a.name.localeCompare(b.name)
%0A
@@ -980,29 +980,23 @@
+%7D)%0A
-return 5%0A
%7D, (
@@ -995,11 +995,13 @@
-%7D,
+.map(
(ite
@@ -1010,47 +1010,71 @@
=%3E
-%7B%0A return item.name%0A
+new Item(item, %7B%0A inEnglish: inEnglish%0A
%7D%5D)%0A
@@ -1073,10 +1073,13 @@
-%7D%5D
+ %7D)
)%0A
|
a5dbfbb82d82657360c5c793141d183af527c106
|
Fix UI-doc generation
|
website/generate-uidocs.js
|
website/generate-uidocs.js
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
*/
const reactDocs = require('react-docgen');
const glob = require('glob');
const fs = require('fs');
const babylon = require('@babel/parser');
const docblockParser = require('docblock-parser');
const HEADER = `---
id: ui-components
title: UI Components
---
Flipper has a lot of built in React components to build UIs. You can import them directly using e.g. \`import {Button} from 'flipper'\`.`;
const TARGET = __dirname + '/../docs/extending/ui-components.md';
glob(__dirname + '/../src/ui/components/**/*.tsx', (err, files) => {
const content = files
.map(f => [f, fs.readFileSync(f)])
.map(([name, file]) => {
try {
const doc = reactDocs.parse(file, null, null, {filename: name});
console.log(`✅ ${name}`);
return doc;
} catch (e) {
const doc = parseHOC(name, file);
if (doc) {
console.log(`✅ HOC: ${name}`);
return doc;
} else {
console.error(`❌ ${name}: ${e.message}`);
return null;
}
}
})
.filter(Boolean)
.map(generateMarkdown)
.reduce((acc, cv) => acc + cv, '');
fs.writeFileSync(TARGET, HEADER + content);
});
// HOC are not supported by react-docgen. This means, styled-components will not
// work. This is why we implement our own parser to information from these HOCs.
function parseHOC(name, file) {
try {
const ast = babylon.parse(file.toString(), {
sourceType: 'module',
plugins: ['typescript', 'objectRestSpread', 'classProperties'],
});
// find the default export from the file
const exportDeclaration = ast.program.body.find(
node => node.type === 'ExportDefaultDeclaration',
);
if (exportDeclaration) {
// find doc comment right before the export
const comment = ast.comments.find(
c => c.end + 1 === exportDeclaration.start,
);
if (comment) {
return {
// use the file's name as name for the component
displayName: name
.split('/')
.reverse()[0]
.replace(/\.js$/, ''),
description: docblockParser.parse(comment.value).text,
};
}
}
} catch (e) {}
return null;
}
function generateMarkdown(component) {
let props;
if (component.props && Object.keys(component.props).length > 0) {
props = '| Property | Type | Description |\n';
props += '|---------|------|-------------|\n';
Object.keys(component.props).forEach(prop => {
let {tsType, description} = component.props[prop];
let type = '';
if (tsType) {
if (tsType.nullable) {
type += '?';
}
type +=
tsType.name === 'signature' ||
tsType.name === 'union' ||
tsType.name === 'Array'
? tsType.raw
: tsType.name;
}
// escape pipes and new lines because they will break tables
type = type.replace(/\n/g, ' ').replace(/\|/g, '⎮');
description = description
? description.replace(/\n/g, ' ').replace(/\|/g, '⎮')
: '';
props += `| \`${prop}\` | \`${type}\` | ${description} |\n`;
});
}
return `
## ${component.displayName}
${component.description || ''}
${props || ''}
`;
}
|
JavaScript
| 0.000005 |
@@ -683,16 +683,28 @@
+ '/../
+desktop/app/
src/ui/c
|
bcc5e0f03eba1c684e421000dfb66769531faad6
|
add format option to getCommitMessage()
|
helpers/get-commit-message/index.js
|
helpers/get-commit-message/index.js
|
"use strict";
const execa = require("execa");
module.exports = getCommitMessage;
function getCommitMessage(cwd) {
return execa("git", ["show", "--no-patch", "--pretty=%B"], { cwd }).then(result => result.stdout.trim());
}
|
JavaScript
| 0.000001 |
@@ -106,16 +106,31 @@
sage(cwd
+, format = %22%25B%22
) %7B%0A re
@@ -139,16 +139,23 @@
rn execa
+.stdout
(%22git%22,
@@ -160,30 +160,21 @@
, %5B%22
-show
+log
%22, %22-
--no-patch%22, %22
+1%22, %60
--pr
@@ -182,58 +182,35 @@
tty=
-%25B%22%5D, %7B cwd %7D).then(result =%3E result.stdout.trim()
+format:$%7Bformat%7D%60%5D, %7B cwd %7D
);%0A%7D
|
80921414ba56cf8e4829dd93af18798e2d598c94
|
Fix barrier NaN issue
|
src/javascript/binary/pages/trade/barriers.js
|
src/javascript/binary/pages/trade/barriers.js
|
/*
* Handles barrier processing and display
*
* It process `Contract.barriers` and display them if its applicable
* for current `Contract.form()
*/
var Barriers = (function () {
'use strict';
var isBarrierUpdated = false;
var display = function (barrierCategory) {
var barriers = Contract.barriers()[Defaults.get('underlying')],
formName = Contract.form();
if (barriers && formName && Defaults.get('formname')!=='risefall') {
var barrier = barriers[formName];
if(barrier) {
var unit = document.getElementById('duration_units'),
end_time = document.getElementById('expiry_date'),
currentTick = Tick.quote(),
indicativeBarrierTooltip = document.getElementById('indicative_barrier_tooltip'),
indicativeHighBarrierTooltip = document.getElementById('indicative_high_barrier_tooltip'),
indicativeLowBarrierTooltip = document.getElementById('indicative_low_barrier_tooltip'),
decimalPlaces = countDecimalPlaces(currentTick);
if (barrier.count === 1) {
document.getElementById('high_barrier_row').style.display = 'none';
document.getElementById('low_barrier_row').style.display = 'none';
document.getElementById('barrier_row').setAttribute('style', '');
var barrier_def = Defaults.get('barrier') || barrier['barrier'];
var elm = document.getElementById('barrier'),
tooltip = document.getElementById('barrier_tooltip'),
span = document.getElementById('barrier_span');
if ((unit && unit.value === 'd') || (end_time && moment(end_time.value).isAfter(moment(),'day'))) {
if (currentTick && !isNaN(currentTick) && barrier_def.match(/^[+-]/)) {
elm.value = (parseFloat(currentTick) + parseFloat(barrier_def)).toFixed(decimalPlaces);
elm.textContent = (parseFloat(currentTick) + parseFloat(barrier_def)).toFixed(decimalPlaces);
} else {
elm.value = parseFloat(barrier_def);
elm.textContent = parseFloat(barrier_def);
}
tooltip.style.display = 'none';
span.style.display = 'inherit';
// no need to display indicative barrier in case of absolute barrier
indicativeBarrierTooltip.textContent = '';
} else {
elm.value = barrier_def;
elm.textContent = barrier_def;
span.style.display = 'none';
tooltip.style.display = 'inherit';
if (currentTick && !isNaN(currentTick)) {
indicativeBarrierTooltip.textContent = (parseFloat(currentTick) + parseFloat(barrier_def)).toFixed(decimalPlaces);
} else {
indicativeBarrierTooltip.textContent = '';
}
}
Defaults.set('barrier', elm.value);
Defaults.remove('barrier_high', 'barrier_low');
return;
} else if (barrier.count === 2) {
document.getElementById('barrier_row').style.display = 'none';
document.getElementById('high_barrier_row').setAttribute('style', '');
document.getElementById('low_barrier_row').setAttribute('style', '');
var high_elm = document.getElementById('barrier_high'),
low_elm = document.getElementById('barrier_low'),
high_tooltip = document.getElementById('barrier_high_tooltip'),
high_span = document.getElementById('barrier_high_span'),
low_tooltip = document.getElementById('barrier_low_tooltip'),
low_span = document.getElementById('barrier_low_span');
var barrier_high = Defaults.get('barrier_high') || barrier['barrier'],
barrier_low = Defaults.get('barrier_low') || barrier['barrier1'];
if (unit && unit.value === 'd') {
if (currentTick && !isNaN(currentTick) && barrier_high.match(/^[+-]/)) {
high_elm.value = (parseFloat(currentTick) + parseFloat(barrier_high)).toFixed(decimalPlaces);
high_elm.textContent = (parseFloat(currentTick) + parseFloat(barrier_high)).toFixed(decimalPlaces);
low_elm.value = (parseFloat(currentTick) + parseFloat(barrier_low)).toFixed(decimalPlaces);
low_elm.textContent = (parseFloat(currentTick) + parseFloat(barrier_low)).toFixed(decimalPlaces);
} else {
high_elm.value = parseFloat(barrier_high);
high_elm.textContent = parseFloat(barrier_high);
low_elm.value = parseFloat(barrier_low);
low_elm.textContent = parseFloat(barrier_low);
}
high_tooltip.style.display = 'none';
high_span.style.display = 'inherit';
low_tooltip.style.display = 'none';
low_span.style.display = 'inherit';
indicativeHighBarrierTooltip.textContent = '';
indicativeLowBarrierTooltip.textContent = '';
} else {
high_elm.value = barrier_high;
high_elm.textContent = barrier_high;
low_elm.value = barrier_low;
low_elm.textContent = barrier_low;
high_span.style.display = 'none';
high_tooltip.style.display = 'inherit';
low_span.style.display = 'none';
low_tooltip.style.display = 'inherit';
if (currentTick && !isNaN(currentTick)) {
indicativeHighBarrierTooltip.textContent = (parseFloat(currentTick) + parseFloat(barrier_high)).toFixed(decimalPlaces);
indicativeLowBarrierTooltip.textContent = (parseFloat(currentTick) + parseFloat(barrier_low)).toFixed(decimalPlaces);
} else {
indicativeHighBarrierTooltip.textContent = '';
indicativeLowBarrierTooltip.textContent = '';
}
}
Defaults.set('barrier_high', high_elm.value);
Defaults.set('barrier_low', low_elm.value);
Defaults.remove('barrier');
return;
}
}
}
var elements = document.getElementsByClassName('barrier_class');
for (var i = 0; i < elements.length; i++){
elements[i].style.display = 'none';
}
Defaults.remove('barrier', 'barrier_high', 'barrier_low');
};
return {
display: display,
isBarrierUpdated: function () { return isBarrierUpdated; },
setBarrierUpdate: function (flag) {
isBarrierUpdated = flag;
}
};
})();
|
JavaScript
| 0.000003 |
@@ -1450,27 +1450,32 @@
var
+defaults_
barrier
-_def
= Defau
@@ -1492,19 +1492,121 @@
arrier')
- %7C%7C
+;%0A var barrier_def = defaults_barrier && !isNaN(defaults_barrier) ? defaults_barrier :
barrier
@@ -4331,32 +4331,41 @@
var
+defaults_
barrier_high = D
@@ -4391,19 +4391,189 @@
r_high')
- %7C%7C
+, defaults_barrier_low = Defaults.get('barrier_low');%0A var barrier_high = defaults_barrier_high && !isNaN(defaults_barrier_high) ? defaults_barrier_high :
barrier
@@ -4624,30 +4624,57 @@
_low =
-D
+d
efaults
-.get('
+_barrier_low && !isNaN(defaults_
barrier_
@@ -4680,14 +4680,36 @@
_low
-'
)
-%7C%7C
+? defaults_barrier_low :
bar
|
9be2f2c0b2ce69c59980d44e0582a227612a4dd4
|
Abort if first token is not autocompletable (comment, string)
|
src/ae_console/js/get_current_tokens.js
|
src/ae_console/js/get_current_tokens.js
|
define(['ace/ace'], function (ace) {
var TokenIterator = ace.require('ace/token_iterator').TokenIterator;
var space = /^\s+$/,
comma = /^,\s*$/,
semicolon = /^;\s*$/,
bracketOpen = /^[\(\[\{]$/,
bracketClose = /^[\)\]\}]$/,
bracketMatching = {'(': ')', ')': '(', '[': ']', ']': '[', '{': '}', '}': '{'},
indexAccessor = /^[\[\]]$/;
/**
* Get the current token from token iterator and correct it if necessary.
* Ace's Ruby tokenizer incorrectly splits some tokens, for example methods ending with question marks or exclamation marks.
*/
function getCorrectedCurrentToken (tokenIterator) {
// Check the next token to make sure we have the complete current token.
// Detecting setter methods however is ambiguous to distinguish from local variable assignments.
var currentToken = tokenIterator.getCurrentToken(); // An object {type: string, value: string, index: number, start: number}
if (currentToken == null) return null;
var tokenString = currentToken.value;
var nextToken = tokenIterator.stepForward();
if (nextToken != null) {
switch (nextToken.value) {
case '?': tokenString += '?'; break;
case '?.': tokenString += '?'; break;
case '!': tokenString += '!'; break;
case '!.': tokenString += '!'; break;
default: break; // null or non-matching
}
}
tokenIterator.stepBackward(); // again the old currentToken
return tokenString;
}
/**
* Get a list of continuous tokens preceding the given position in the editor.
* The token list includes – if possible – all tokens needed for a valid object/class/module or chained methods.
* @returns {Array<string>} - An array of string.
*/
function getCurrentTokens (aceEditor) {
var position = aceEditor.getCursorPosition();
var tokenIterator = new TokenIterator(aceEditor.getSession(), position.row, position.column);
var tokens = [];
var bracketStack = [];
var token = getCorrectedCurrentToken(tokenIterator);
if (token == null) return tokens;
tokens.unshift(token);
if (bracketClose.test(token)) {
bracketStack.push(token);
}
// Walk from the caret position backwards and collect tokens. Skip everything within brackets.
var currentToken; // An object {type: string, value: string, index: number, start: number}
while (true) {
currentToken = tokenIterator.stepBackward();
if (currentToken == null) break;
var token = currentToken.value;
// TODO: How to handle line breaks? If there is not a dot or double colon before or after, we should break.
// Since we walk backwards, closing brackets are added to the stack.
if (bracketClose.test(token)) {
bracketStack.push(token);
// And opening brackets that match the top stack element, remove it from the stack.
} else if (bracketOpen.test(token)) {
var last = bracketStack[bracketStack.length - 1];
if (last == bracketMatching[token]) {
bracketStack.pop();
if (indexAccessor.test(token) && bracketStack.length == 0) {
if (tokens[0] == ']') {
if (tokens[1] == '=') {
tokens.shift();
tokens[0] = '[]=';
} else {
tokens[0] = '[]';
}
}
}
} else {
break;
}
} else if (space.test(token) ||
comma.test(token) ||
semicolon.test(token)) {
break;
} else if (bracketStack.length == 0) {
// TODO: add [] methods? Does it handle []=, \w= ?
switch (tokens[0]) {
case '?.':
tokens[0] = '.';
tokens.unshift(token + '?');
break;
case '?':
tokens[0] = token + '?';
break;
case '!.':
tokens[0] = '.';
tokens.unshift(token + '!');
break;
case '!':
tokens[0] = token + '!';
break;
case '=':
tokens[0] = token + '=';
break;
default:
// Words outside of brackets. We want to collect those.
tokens.unshift(token);
}
}
}
return tokens;
}
return getCurrentTokens;
});
|
JavaScript
| 0 |
@@ -182,24 +182,119 @@
= /%5E;%5Cs*$/,%0A
+ endOfLineComment = /%5E#/,%0A isString = /%5E%5C%22(?:%5C%5C%22%7C%5B%5E%22%5D)*%5C%22$%7C%5E%5C'(?:%5C%5C'%7C%5B%5E'%5D)*%5C'$/,%0A
brac
@@ -2321,24 +2321,183 @@
urn tokens;%0A
+ // Abort if the token is not autocompletable.%0A if (endOfLineComment.test(token) %7C%7C isString.test(token)) %7B%0A return tokens;%0A %7D%0A
toke
@@ -4212,32 +4212,87 @@
olon.test(token)
+ %7C%7C%0A endOfLineComment.test(token)
) %7B%0A
|
3bf4eccf79d9c9805d0ccd4f5d98c5a06f01e42c
|
Add `user.requiredDocuments` property
|
prototype/model/user.js
|
prototype/model/user.js
|
'use strict';
var Map = require('es6-map')
, db = require('mano').db
, User = require('mano-auth/model/user')
, DateType = require('dbjs-ext/date-time/date')(db)
, StringLine = require('dbjs-ext/string/string-line')(db)
, Email = require('dbjs-ext/string/string-line/email')(db)
, UsDollar = require('dbjs-ext/number/currency/us-dollar')(db)
, UInteger = require('dbjs-ext/number/integer/u-integer')(db)
, SquareMeters = require('dbjs-ext/number/square-meters')(db)
, Document = require('./document')
, Submission = require('./submission')
, user = User.prototype
, BusinessActivity, BusinessActivityCategory, CompanyType, Partner, bcAgencyBusiness, bcInsurance;
require('dbjs-ext/create-enum')(db);
BusinessActivityCategory = db.Object.extend('BusinessActivityCategory', {
label: { type: StringLine, required: true }
});
bcAgencyBusiness = BusinessActivityCategory.newNamed('bcAgencyBusiness',
{ label: "Agency Business" });
bcInsurance = BusinessActivityCategory.newNamed('bcInsurance', { label: "Insurance" });
BusinessActivity = db.Object.extend('BusinessActivity', {
label: { type: StringLine, required: true },
category: { type: BusinessActivityCategory, required: true }
});
BusinessActivity.newNamed('baComissionAgent', {
label: "Comission agent",
category: bcAgencyBusiness
});
BusinessActivity.newNamed('baAirCharterAgent', {
label: "Air charter agent",
category: bcAgencyBusiness
});
BusinessActivity.newNamed('baGeneralInsurance', {
label: "General insurance and assurance",
category: bcInsurance
});
BusinessActivity.newNamed('baReassurance', {
label: "Re-assurance & endowment",
category: bcInsurance
});
CompanyType = StringLine.createEnum('CompanyType', new Map([
['private', { label: "Private limited company" }],
['public', { label: "Public company" }]
]));
user.defineProperties({
firstName: { type: StringLine, required: true, label: "First Name" },
lastName: { type: StringLine, required: true, label: "Last Name" },
// Guide
businessActivity: { type: BusinessActivity, required: true, label: "Business activity" },
isOwner: { type: db.Boolean, trueLabel: "I am the owner", falseLabel: "I rent it",
label: "Owner of business premises" },
inventory: { type: UsDollar, label: "Inventory value", required: true, step: 1 },
surfaceArea: { type: SquareMeters, label: "Area used for the activity", required: true },
members: { type: UInteger, label: "Quantity of members", required: true },
companyType: { type: CompanyType, label: "Registration type", required: true },
isShoppingGallery: { type: db.Boolean, label: "A shopping gallery", required: true,
trueLabel: "Yes", falseLabel: "No" },
isARequested: { type: db.Boolean, label: "Registration A", required: true },
isBRequested: { type: db.Boolean, label: "Registration B", required: true },
dateOfBirth: { type: DateType, label: "Date of birth", required: true },
userEmail: { type: Email, label: "Email" },
registerIds: { type: StringLine, multiple: true, label: "Padrón", pattern: /^\d{8}$/,
inputMask: '88888888' }
});
module.exports = User;
Partner = db.User.extend('Partner');
user.define('partners', {
type: Partner,
multiple: true
});
user.partners.add(new Partner({ firstName: "Frank", lastName: "Grozel" }));
user.partners.add(new Partner({ firstName: "Bita", lastName: "Mortazavi" }));
Submission.extend('DocumentASubmission', {},
{ Document: { value: Document.extend('DocumentA', {}, { label: "Document A" }) } });
Submission.extend('DocumentBSubmission', {},
{ Document: { value: Document.extend('DocumentB', {}, { label: "Document B" }) } });
Submission.extend('DocumentCSubmission', {},
{ Document: { value: Document.extend('DocumentC', {}, { label: "Document C" }) } });
user.define('submissions', {
type: db.Object,
nested: true
});
user.submissions.defineProperties({
documentA: { type: db.DocumentASubmission, nested: true },
documentB: { type: db.DocumentBSubmission, nested: true },
documentC: { type: db.DocumentCSubmission, nested: true }
});
|
JavaScript
| 0.000001 |
@@ -4057,20 +4057,202 @@
nested: true %7D%0A%7D);%0A
+user.define('requiredSubmissions', %7B%0A%09type: db.DocumentASubmission,%0A%09multiple: true,%0A%09value: %5Buser.submissions.documentA, user.submissions.documentB, user.submissions.documentC%5D%0A%7D);%0A
|
4e9ce9ad7616a76b9f53abb060a8539d23c16d65
|
Fix bug where messages from other people have min length
|
native/chat/text-message.react.js
|
native/chat/text-message.react.js
|
// @flow
import type { ThreadInfo } from 'lib/types/thread-types';
import { threadInfoPropType } from 'lib/types/thread-types';
import type { ChatMessageInfoItemWithHeight } from './message-list.react';
import { chatMessageItemPropType } from '../selectors/chat-selectors';
import type { TooltipItemData } from '../components/tooltip.react';
import React from 'react';
import {
Text,
StyleSheet,
View,
TouchableOpacity,
Clipboard,
} from 'react-native';
import invariant from 'invariant';
import PropTypes from 'prop-types';
import Color from 'color';
import Hyperlink from 'react-native-hyperlink';
import { colorIsDark } from 'lib/shared/thread-utils';
import { messageKey } from 'lib/shared/message-utils';
import { stringForUser } from 'lib/shared/user-utils';
import { messageType } from 'lib/types/message-types';
import Tooltip from '../components/tooltip.react';
function textMessageItemHeight(
item: ChatMessageInfoItemWithHeight,
viewerID: ?string,
) {
let height = 17 + item.textHeight; // for padding, margin, and text
if (!item.messageInfo.creator.isViewer && item.startsCluster) {
height += 25; // for username
}
if (item.endsCluster) {
height += 7; // extra padding at the end of a cluster
}
return height;
}
type Props = {
item: ChatMessageInfoItemWithHeight,
focused: bool,
toggleFocus: (messageKey: string) => void,
threadInfo: ThreadInfo,
};
class TextMessage extends React.PureComponent<Props> {
static propTypes = {
item: chatMessageItemPropType.isRequired,
focused: PropTypes.bool.isRequired,
toggleFocus: PropTypes.func.isRequired,
threadInfo: threadInfoPropType.isRequired,
};
tooltipConfig: $ReadOnlyArray<TooltipItemData>;
tooltip: ?Tooltip;
constructor(props: Props) {
super(props);
invariant(
props.item.messageInfo.type === messageType.TEXT,
"TextMessage should only be used for messageType.TEXT",
);
this.tooltipConfig = [
{ label: "Copy", onPress: this.onPressCopy },
];
}
componentWillReceiveProps(nextProps: Props) {
invariant(
nextProps.item.messageInfo.type === messageType.TEXT,
"TextMessage should only be used for messageType.TEXT",
);
}
render() {
const isViewer = this.props.item.messageInfo.creator.isViewer;
let containerStyle = null,
messageStyle = {},
textStyle = {};
let darkColor = false;
if (isViewer) {
containerStyle = { alignSelf: 'flex-end' };
messageStyle.backgroundColor = `#${this.props.threadInfo.color}`;
darkColor = colorIsDark(this.props.threadInfo.color);
textStyle.color = darkColor ? 'white' : 'black';
} else {
containerStyle = { alignSelf: 'flex-start' };
messageStyle.backgroundColor = "#DDDDDDBB";
textStyle.color = 'black';
}
let authorName = null;
if (!isViewer && this.props.item.startsCluster) {
authorName = (
<Text style={styles.authorName}>
{stringForUser(this.props.item.messageInfo.creator)}
</Text>
);
}
messageStyle.borderTopRightRadius =
isViewer && !this.props.item.startsCluster ? 0 : 8;
messageStyle.borderBottomRightRadius =
isViewer && !this.props.item.endsCluster ? 0 : 8;
messageStyle.borderTopLeftRadius =
!isViewer && !this.props.item.startsCluster ? 0 : 8;
messageStyle.borderBottomLeftRadius =
!isViewer && !this.props.item.endsCluster ? 0 : 8;
messageStyle.marginBottom = this.props.item.endsCluster ? 12 : 5;
if (this.props.focused) {
messageStyle.backgroundColor =
Color(messageStyle.backgroundColor).darken(0.15).hex();
}
textStyle.height = this.props.item.textHeight;
invariant(
this.props.item.messageInfo.type === messageType.TEXT,
"TextMessage should only be used for messageType.TEXT",
);
const text = this.props.item.messageInfo.text;
const linkStyle = darkColor ? styles.lightLinkText : styles.darkLinkText;
const content = (
<View style={[styles.message, messageStyle]}>
<Hyperlink linkDefault={true} linkStyle={linkStyle}>
<Text
onPress={this.onPress}
onLongPress={this.onPress}
style={[styles.text, textStyle]}
>{text}</Text>
</Hyperlink>
</View>
);
return (
<View style={containerStyle}>
{authorName}
<Tooltip
buttonComponent={content}
items={this.tooltipConfig}
labelStyle={styles.popoverLabelStyle}
onOpenTooltipMenu={this.onFocus}
onCloseTooltipMenu={this.onBlur}
ref={this.tooltipRef}
/>
</View>
);
}
tooltipRef = (tooltip: ?Tooltip) => {
this.tooltip = tooltip;
}
onFocus = () => {
if (!this.props.focused) {
this.props.toggleFocus(messageKey(this.props.item.messageInfo));
}
}
onBlur = () => {
if (this.props.focused) {
this.props.toggleFocus(messageKey(this.props.item.messageInfo));
}
}
onPressCopy = () => {
invariant(
this.props.item.messageInfo.type === messageType.TEXT,
"TextMessage should only be used for messageType.TEXT",
);
Clipboard.setString(this.props.item.messageInfo.text);
}
onPress = () => {
const tooltip = this.tooltip;
invariant(tooltip, "tooltip should be set");
if (this.props.focused) {
tooltip.hideModal();
} else {
tooltip.openModal();
}
}
}
const styles = StyleSheet.create({
text: {
fontSize: 18,
fontFamily: 'Arial',
},
message: {
overflow: 'hidden',
paddingVertical: 6,
paddingHorizontal: 12,
marginHorizontal: 12,
},
authorName: {
color: '#777777',
fontSize: 14,
paddingHorizontal: 24,
paddingVertical: 4,
height: 25,
},
darkLinkText: {
color: "#036AFF",
textDecorationLine: "underline",
},
lightLinkText: {
color: "#129AFF",
textDecorationLine: "underline",
},
popoverLabelStyle: {
textAlign: 'center',
color: '#444',
},
});
export {
TextMessage,
textMessageItemHeight,
};
|
JavaScript
| 0 |
@@ -4604,16 +4604,65 @@
onBlur%7D%0A
+ componentWrapperStyle=%7BcontainerStyle%7D%0A
|
20f63eabf29d49c4e97bfa52177370eda08c50cc
|
Set RU lang for FB js sdk
|
web/js/social.js
|
web/js/social.js
|
// VKontakte with app Id
VK.init({apiId: 5103140, onlyWidgets: true});
// Facebook js sdk
window.fbAsyncInit = function() {
FB.init({
appId : '778342298941480',
xfbml : true,
version : 'v2.5'
});
};
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));
|
JavaScript
| 0 |
@@ -430,13 +430,13 @@
net/
-en_US
+ru_RU
/sdk
|
ccfe59f6ff9bc934b2ac8e5c338c7512909b21cc
|
check cached business unit on session check
|
packages/app-extensions/src/login/sagas.js
|
packages/app-extensions/src/login/sagas.js
|
import {consoleLogger} from 'tocco-util'
import {takeLatest, call, all, put} from 'redux-saga/effects'
import notification from '../notification'
import * as actions from './actions'
export function doRequest(url, options) {
return fetch(url, options)
.then(resp => resp.json())
.catch(e => {
consoleLogger.logError('Failed to execute request', e)
return ({success: false})
})
}
export function* doSessionRequest() {
return yield call(doRequest, `${__BACKEND_URL__}/nice2/session`, getOptions())
}
export function getOptions() {
return {
method: 'POST',
headers: new Headers({
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
}),
credentials: 'include'
}
}
export function* sessionCheck() {
const sessionResponse = yield call(doSessionRequest)
yield put(actions.setLoggedIn(sessionResponse.success))
if (sessionResponse.success) {
yield put(notification.connectSocket())
}
}
export default function* mainSagas() {
yield all([
takeLatest(actions.DO_SESSION_CHECK, sessionCheck)
])
}
|
JavaScript
| 0 |
@@ -14,16 +14,23 @@
leLogger
+, cache
%7D from '
@@ -776,31 +776,39 @@
const
-sessionResponse
+%7Bsuccess, businessUnit%7D
= yield
@@ -837,86 +837,248 @@
)%0A
-yield put(actions.setLoggedIn(sessionResponse.success))%0A if (sessionResponse.
+const cachedPrincipal = cache.getShortTerm('session', 'principal')%0A if (cachedPrincipal && cachedPrincipal.currentBusinessUnit.id !== businessUnit) %7B%0A yield call(cache.clearShortTerm)%0A %7D%0A yield put(actions.setLoggedIn(success))%0A if (
succ
|
72850b332af8e68b3d9b072b352f2024fb44ecbb
|
fix bug : token invalid notification doesn't open popup provider
|
app/assets/javascripts/controllers/NotificationController.js
|
app/assets/javascripts/controllers/NotificationController.js
|
'use strict';
define(["app"], function(app) {
app.controller('NotificationController', [
"$scope", "$rootScope", "ArrayUtils", "PopupProvider", "$filter",
function($scope, $rootScope, $arrayUtils, $popupProvider, $filter) {
$scope.notifications = [];
$rootScope.$on('tokenInvalid', function(evt, data) {
$scope.$apply(function() {
data.title = $filter('i18n')('DISCONNECT');
data.footer = $filter('i18n')('CLICK_TO_RECONNECT');
data.type = "tokenInvalid";
if(!$arrayUtils.exist($scope.notifications, data, "providerName")) {
$scope.notifications.push(data);
}
});
});
$rootScope.$on('newToken', function(evt, data) {
$scope.$apply(function() {
var index = $arrayUtils.indexOf($scope.notifications, data, "providerName");
if(index > -1) {
$scope.notifications.splice(index, 1);
}
});
});
$rootScope.$on('error', function(evt, data) {
$scope.$apply(function() {
if(data.type == "RateLimit" ||
data.type == "Timeout" ||
data.type == "Unknown" ||
data.type == "Parser" ||
data.type == "NoParser" ||
data.type == "Post" ||
data.type == "Star" ||
data.type == "Comment") {
data.title = $filter('i18n')(data.type);
} else {
data.title = "UNKNOW ERROR TYPE "+data.type;
}
data.footer = $filter('i18n')('CLICK_TO_HIDE');
var exist = $arrayUtils.existWith($scope.notifications, data, function(inArray, data) {
return inArray.providerName == data.providerName && inArray.title == data.title;
});
if(!exist) {
$scope.notifications.push(data);
}
});
});
$rootScope.$on('disconnect', function(evt, data) {
$scope.$apply(function() {
data.title = $filter('i18n')('DISCONNECT');
data.footer = $filter('i18n')('CLICK_TO_RECONNECT');
data.type = "disconnect";
data.providerName = "skimbo";
var exist = $arrayUtils.existWith($scope.notifications, data, function(inArray, data) {
return inArray.providerName == data.providerName && inArray.title == data.title;
});
if(!exist) {
$scope.notifications.push(data);
}
});
});
$scope.clickOnNotification = function(notification) {
if(notification.isError == false && notification.providerName != "skimbo") {
$popupProvider.openPopup({"name": notification.providerName});
} else if(notification.isError == false && notification.providerName == "skimbo") {
if(notification.forceIdentification == true) {
window.location.href = "/logout";
} else {
window.location.href = "/";
}
} else {
var index = $arrayUtils.indexOfWith($scope.notifications, notification, function(inArray, data) {
return inArray.providerName == data.providerName && inArray.msg == data.msg;
});
if(index > -1) {
$scope.notifications.splice(index, 1);
}
}
}
$scope.closeNotification = function(notification) {
var index = $arrayUtils.indexOfWith($scope.notifications, notification, function(inArray, data) {
return inArray.providerName == data.providerName && inArray.msg == data.msg;
});
if(index > -1) {
$scope.notifications.splice(index, 1);
}
}
}]);
return app;
});
|
JavaScript
| 0 |
@@ -2423,64 +2423,29 @@
ion.
-isError == false && notification.providerName != %22skimbo
+type == %22tokenInvalid
%22) %7B
@@ -2549,64 +2549,27 @@
ion.
-isError == false && notification.providerName == %22skimbo
+type == %22disconnect
%22) %7B
|
8df3d9e11c8473513d3610e5edf8b4840b08c9f8
|
fix barrier not showing for higher lower
|
src/javascript/binary/pages/trade/contract.js
|
src/javascript/binary/pages/trade/contract.js
|
/*
* Contract object mocks the trading form we have on our website
* It parses the contracts json we get from socket.send({contracts_for: 'R_50'})
* and gives back barriers, startDate, durations etc
*
*
* Usage:
*
* use `Contract.details` to populate this object
*
* then use
*
* `Contract.durations()` to get durations like seconds, hours etc
* `Contract.open()` `Contract.close()`
* `Contract.barriers` if applicable for current underlying
*/
var Contract = (function () {
'use strict';
var open, close, contractDetails = [], durations = {}, startDates = [], barriers = {}, contractType = {};
var details = function (contractObject, expiryType) {
var contracts = contractObject['contracts_for'], contractsArray = [], sendAll = true;
open = contracts['open'];
close = contracts['close'];
var formName = Offerings.form(),
barrierCategory = Offerings.barrier();
if (formName) {
contracts.available.forEach(function (currentObj) {
if (!durations[currentObj['expiry_type']]) {
durations[currentObj['expiry_type']] = {};
}
if(!durations[currentObj['expiry_type']][currentObj['contract_category']]) {
durations[currentObj['expiry_type']][currentObj['contract_category']] = {};
}
if(!durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']]) {
durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']] = {};
}
if(!durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']][currentObj['start_type']]) {
durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']][currentObj['start_type']] = {};
}
durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']][currentObj['start_type']]['max_contract_duration'] = currentObj['max_contract_duration'];
durations[currentObj['expiry_type']][currentObj['contract_category']][currentObj['barrier_category']][currentObj['start_type']]['min_contract_duration'] = currentObj['min_contract_duration'];
if(formName === currentObj['contract_category']) {
if (expiryType) {
if (expiryType === currentObj['expiry_type']) {
contractsArray.push(currentObj);
}
} else {
contractsArray.push(currentObj);
}
sendAll = false;
}
if (currentObj.forward_starting_options && currentObj['start_type'] === 'forward') {
startDates = currentObj.forward_starting_options;
}
if (formName === currentObj['contract_category']) {
var barrier = {};
if (currentObj.barriers === 1) {
if (!barriers.hasOwnProperty(currentObj['contract_category'])) {
barrier['count'] = 1;
barrier['barrier'] = currentObj['barrier'];
barrier['barrier_category'] = currentObj['barrier_category'];
barriers[formName] = barrier;
}
} else if (currentObj.barriers === 2) {
if (!barriers.hasOwnProperty(currentObj['contract_category'])) {
barrier['count'] = 2;
barrier['barrier'] = currentObj['high_barrier'];
barrier['barrier1'] = currentObj['low_barrier'];
barrier['barrier_category'] = currentObj['barrier_category'];
barriers[formName] = barrier;
}
}
if (!contractType[currentObj['contract_category']]) {
contractType[currentObj['contract_category']] = {};
}
if (!contractType[currentObj['contract_category']].hasOwnProperty(currentObj['contract_type'])) {
contractType[currentObj['contract_category']][currentObj['contract_type']] = currentObj['contract_display'];
}
}
if (barrierCategory && barriers && barriers[formName] && !barriers[formName][barrierCategory] ) {
barriers = {};
}
});
if(expiryType) {
var obj = {};
obj[expiryType] = durations[expiryType];
durations = obj;
}
if (barrierCategory) {
var j = contractsArray.length;
while (j--) {
if (barrierCategory !== contractsArray[j]['barrier_category']) {
contractsArray.splice(j, 1);
}
}
}
}
if (sendAll) {
contractDetails = contracts.available;
} else {
contractDetails = contractsArray;
}
};
return {
details: details,
open: function () { return open; },
close: function () { return close; },
contracts: function () { return contractDetails; },
durations: function () { return durations; },
startDates: function () { return startDates; },
barriers: function () { return barriers; },
contractType: function () { return contractType; }
};
})();
|
JavaScript
| 0 |
@@ -4564,174 +4564,8 @@
%7D%0A%0A
- if (barrierCategory && barriers && barriers%5BformName%5D && !barriers%5BformName%5D%5BbarrierCategory%5D ) %7B%0A barriers = %7B%7D;%0A %7D
%0A
@@ -4576,16 +4576,17 @@
%7D);
+%0A
%0A%0A
@@ -4774,24 +4774,195 @@
Category) %7B%0A
+%0A if (barriers && barriers%5BformName%5D && barriers%5BformName%5D%5B'barrier_category'%5D !== barrierCategory) %7B%0A barriers = %7B%7D;%0A %7D%0A%0A
|
6d0d0f5c6cb21ace59ea4df157b28908f99d3a28
|
Update sass cms source files
|
grunt/sass.js
|
grunt/sass.js
|
module.exports = {
options: {
includePaths: [
'bower_components/'
],
sourcemap: false
},
dev: {
options: {
outputStyle: 'nested',
sourceComments: true,
sourceMap: true
},
files: [{
expand: true,
flatten: true,
extDot: 'last',
cwd: '<%= globalConfig.source.css %>/',
src: [
'styleguide.scss',
'**/app.scss',
'**/*.app.scss'
],
dest: '<%= globalConfig.public.css %>/',
ext: '.css'
}]
},
cms: {
options: {
outputStyle: 'compressed'
},
files: [{
expand: true,
flatten: true,
extDot: 'last',
cwd: '<%= globalConfig.source.css %>/',
src: [
'**/*.app.scss'
],
dest: '<%= globalConfig.cms.css %>/',
ext: '.css'
}]
}
};
|
JavaScript
| 0 |
@@ -883,32 +883,63 @@
src: %5B%0A
+ '**/app.scss',%0A
|
1fd961ed1142e192aa2d740a50383328eba6bc56
|
Fix whitespace
|
config.example.js
|
config.example.js
|
var config = {
servers: [{
name: "Varnish",
host: null,
port: 6085,
user: "varnish_agent_user",
pass: "varnish_agent_pass"
}],
groups: [],
update_freq: 2000,
max_points: 100,
default_log_fetch: 10000,
default_log_display: 100,
show_bans_page: true,
show_manage_server_page: true,
show_vcl_page: true,
show_stats_page: true,
show_params_page: true,
show_logs_page: true,
show_restart_varnish_btn: true
};
|
JavaScript
| 0.999999 |
@@ -8,17 +8,18 @@
fig = %7B%0A
-%09
+
servers:
@@ -22,18 +22,20 @@
ers: %5B%7B%0A
-%09%09
+
name: %22V
@@ -43,18 +43,20 @@
rnish%22,%0A
-%09%09
+
host: nu
@@ -59,18 +59,20 @@
: null,%0A
-%09%09
+
port: 60
@@ -75,18 +75,20 @@
: 6085,%0A
-%09%09
+
user: %22v
@@ -111,10 +111,12 @@
r%22,%0A
-%09%09
+
pass
@@ -142,14 +142,16 @@
ss%22%0A
-%09
+
%7D%5D,%0A
-%09
+
grou
@@ -158,17 +158,18 @@
ps: %5B%5D,%0A
-%09
+
update_f
@@ -179,17 +179,18 @@
: 2000,%0A
-%09
+
max_poin
@@ -194,26 +194,24 @@
oints: 100,%0A
-
default_lo
@@ -226,18 +226,16 @@
10000,%0A
-
defaul
@@ -254,17 +254,18 @@
y: 100,%0A
-%09
+
show_ban
@@ -274,25 +274,26 @@
page: true,%0A
-%09
+
show_manage_
@@ -307,25 +307,26 @@
page: true,%0A
-%09
+
show_vcl_pag
@@ -330,25 +330,26 @@
page: true,%0A
-%09
+
show_stats_p
@@ -355,25 +355,26 @@
page: true,%0A
-%09
+
show_params_
@@ -381,25 +381,26 @@
page: true,%0A
-%09
+
show_logs_pa
@@ -413,9 +413,10 @@
ue,%0A
-%09
+
show
|
ed7bedfd39ccd49e906d383aa2fb27d5cb76bac1
|
handle no user and no entities
|
app/components/Tweet.js
|
app/components/Tweet.js
|
import React, { Component } from 'react';
export default class Tweet extends Component {
returnLinkedText(text, urls = []) {
let str = text;
urls.reverse().forEach((url) => {
str = str.substr(0, url.indices[0]) + `<a href="${url.url}" target="_blank" >${url.display_url}</a>` + str.substr(url.indices[1]);
});
return str;
}
getTime(date) {
return `${date.getHours()}:${date.getMinutes()}`;
}
postFavorites(tweetId, favorited) {
this.props.postFavorites(tweetId, favorited);
}
postRetweet(tweetId) {
this.props.postRetweet(tweetId);
}
render() {
const {tweet} = this.props;
return (
<li className="List__item">
<dl>
<dt className="Tweet__meta">
<span className="Tweet__name">{tweet.user.name}</span>
<span className="Tweet__screenName ml5px">@{tweet.user.screen_name}</span>
<span className="Tweet__createdAt ml5px">{this.getTime(new Date(tweet.created_at))}</span>
</dt>
<dd className="Tweet__text" dangerouslySetInnerHTML={{__html : this.returnLinkedText(tweet.text, tweet.entities.urls)}}></dd>
<dd className="Tweet__actions">
<ul>
<li className="Tweet__action">
<a className={tweet.favorited ? 'isActioned' : ''} href="javascript:void(0);" onClick={this.postFavorites.bind(this, tweet.id_str, tweet.favorited)}>
<svg height="12px" version="1.1" viewBox="0 0 23.218 20.776"><path d="M11.608,20.776c-22.647-12.354-6.268-27.713,0-17.369 C17.877-6.937,34.257,8.422,11.608,20.776z"/></svg>
</a>
<a href="" className="Tweet__actionCount">
{tweet.favorite_count}
</a>
</li>
<li className="Tweet__action">
<a className={tweet.retweeted ? 'isActioned' : ''} href="javascript:void(0);" onClick={tweet.retweeted ? false : this.postRetweet.bind(this, tweet.id_str)}>
<svg height="10px" version="1.1" viewBox="0 0 100 60"><path d="M24.9,46V19.9H35L17.5,0L0,19.9h10.1V50c0,5.523,4.476,10,10,10H65L52.195,46H24.9z M89.9,40.1V10c0-5.523-4.477-10-10-10 H35l12.804,14h27.295v26.1H65L82.5,60L100,40.1H89.9z"/></svg>
</a>
<a href="" className="Tweet__actionCount">
{tweet.retweet_count}
</a>
</li>
</ul>
</dd>
</dl>
</li>
);
}
}
|
JavaScript
| 0.000005 |
@@ -606,21 +606,23 @@
const %7B
+
tweet
+
%7D = this
@@ -781,16 +781,30 @@
eet.user
+ && tweet.user
.name%7D%3C/
@@ -875,16 +875,30 @@
eet.user
+ && tweet.user
.screen_
@@ -1135,16 +1135,34 @@
et.text,
+ tweet.entities &&
tweet.e
@@ -1683,32 +1683,51 @@
%3Ca href=%22
+javascript:void(0);
%22 className=%22Twe
@@ -2350,16 +2350,35 @@
a href=%22
+javascript:void(0);
%22 classN
|
86cc6821a5985afbc47f04df8f77e35dc7824673
|
move register debug further down
|
examples/index.js
|
examples/index.js
|
/*jshint esversion:6*/
'use strict';
var Application = require('..').Application;
//config here is a gkeypath Wrapper instance
var config = Application.loadConfig({}, true);
var app = new Application({config});
//use ioc
app.register(require('debug')('application-core'), 'debug');
app.on('run.post', function(){
this.logger.log('--------');
this.logger.log(this.name);
this.logger.log('--------');
});
app.run();
|
JavaScript
| 0 |
@@ -217,16 +217,53 @@
use ioc%0A
+%0A%0Aapp.on('run.post', function()%7B%0A
app.regi
@@ -318,40 +318,8 @@
g');
-%0A%0Aapp.on('run.post', function()%7B
%0A
|
9992a4153cc0dfa43215669273e40fc1687d8f23
|
Add flash selector to local header
|
test/functional/cypress/selectors/local-header.js
|
test/functional/cypress/selectors/local-header.js
|
module.exports = () => {
const localHeaderSelector = '[data-auto-id="localHeader"]'
return {
heading: `${localHeaderSelector} h1.c-local-header__heading`,
headingAfter: `${localHeaderSelector} p.c-local-header__heading-after`,
badge: (number) => `${localHeaderSelector} span.c-badge:nth-child(${number})`,
description: {
paragraph: (number) => `${localHeaderSelector} .c-local-header__description p:nth-child(${number})`,
},
viewFullBusinessDetailsLink: (companyId) => `${localHeaderSelector} [href="/companies/${companyId}/business-details"]`,
}
}
|
JavaScript
| 0 |
@@ -572,14 +572,39 @@
ils%22%5D%60,%0A
+ flash: '.c-message',%0A
%7D%0A%7D%0A
|
c7175f5f439a5bafe2dabec91f049c016e4b5958
|
Delete code that repositioned window on last message.
|
zephyr/static/js/hotkey.js
|
zephyr/static/js/hotkey.js
|
/*global
process_goto_hotkey: false,
process_compose_hotkey: false,
process_key_in_input: false */
// We don't generally treat these as global.
// Tell JSLint they are, to break the mutual recursion.
var pressed_keys = {};
function num_pressed_keys() {
var size = 0, key;
for (key in pressed_keys) {
if (pressed_keys.hasOwnProperty(key))
size++;
}
return size;
}
var directional_hotkeys = {
40: get_next_visible, // down arrow
74: get_next_visible, // 'j'
38: get_prev_visible, // up arrow
75: get_prev_visible, // 'k'
36: get_first_visible, // Home
35: get_last_visible // End
};
function simulate_keypress(keycode) {
$(document).trigger($.Event('keydown', {keyCode: keycode}));
}
function process_hotkey(code) {
var next_zephyr;
if (directional_hotkeys.hasOwnProperty(code)) {
next_zephyr = directional_hotkeys[code](selected_zephyr);
if (next_zephyr.length !== 0) {
select_zephyr(next_zephyr, true);
}
if ((next_zephyr.length === 0) && (code === 40)) {
// At the last zephyr, scroll to the bottom so we have
// lots of nice whitespace for new zephyrs coming in.
//
// FIXME: this doesn't work for End because get_last_visible()
// always returns a zephyr.
$("#main_div").scrollTop($("#main_div").prop("scrollHeight"));
}
return process_hotkey;
}
if (num_pressed_keys() > 1) {
// If you are already holding down another key, none of these
// actions apply.
return false;
}
switch (code) {
case 33: // Page Up
keep_pointer_in_view();
return false; // We want the browser to actually page up and down
case 34: // Page Down
keep_pointer_in_view();
return false;
case 27: // Esc: hide compose pane
hide_compose();
return process_hotkey;
case 67: // 'c': compose
compose_button();
return process_compose_hotkey;
case 82: // 'r': respond to zephyr
respond_to_zephyr();
return process_key_in_input;
case 71: // 'g': start of "go to" command
return process_goto_hotkey;
}
return false;
}
var goto_hotkeys = {
67: narrow_by_recipient, // 'c'
73: narrow_instance, // 'i'
80: narrow_all_personals, // 'p'
65: show_all_messages, // 'a'
27: hide_compose // Esc
};
function process_goto_hotkey(code) {
if (goto_hotkeys.hasOwnProperty(code))
goto_hotkeys[code]();
/* Always return to the initial hotkey mode, even
with an unrecognized "go to" command. */
return process_hotkey;
}
function process_key_in_input(code) {
if (code === 27) {
// User hit Escape key
hide_compose();
return process_hotkey;
}
return false;
}
function process_compose_hotkey(code) {
if (code === 9) { // Tab: toggle between class and huddle compose tabs.
toggle_compose();
return process_compose_hotkey;
} else {
set_keydown_in_input(true);
simulate_keypress(code);
}
}
$(document).keydown(function (e) {
pressed_keys[e.which] = true;
});
$(document).keyup(function (e) {
pressed_keys = {};
});
/* The current handler function for keydown events.
It should return a new handler, or 'false' to
decline to handle the event. */
var keydown_handler = process_hotkey;
function set_keydown_in_input(flag) {
// No argument should behave like 'true'.
if (flag === undefined)
flag = true;
if (flag) {
keydown_handler = process_key_in_input;
} else {
keydown_handler = process_hotkey;
}
}
$(document).keydown(function (event) {
var result = keydown_handler(event.keyCode);
if (typeof result === 'function') {
keydown_handler = result;
event.preventDefault();
}
});
|
JavaScript
| 0 |
@@ -1040,415 +1040,8 @@
%7D%0A
- if ((next_zephyr.length === 0) && (code === 40)) %7B%0A // At the last zephyr, scroll to the bottom so we have%0A // lots of nice whitespace for new zephyrs coming in.%0A //%0A // FIXME: this doesn't work for End because get_last_visible()%0A // always returns a zephyr.%0A $(%22#main_div%22).scrollTop($(%22#main_div%22).prop(%22scrollHeight%22));%0A %7D%0A
|
a27ce0c43a7f59dab5118545ee8483eef4cd3513
|
remove empty line.
|
example/main.js
|
example/main.js
|
import "babel-core/polyfill";
import React from "react";
import Recaptcha from "../src";
// specifying your onload callback function
let callback = () => {
console.log('Done!!!!');
};
let verifyCallback = (response) => {
console.log(response);
};
let App = React.createClass({
render() {
return (
<div>
<Recaptcha
sitekey="xxxxxxxxxxxxxxxxxxx"
render="explicit"
verifyCallback={verifyCallback}
onloadCallback={callback}
/>
</div>
);
}
});
React.render(<App />, document.getElementById('app'));
|
JavaScript
| 0.00157 |
@@ -247,17 +247,16 @@
e);%0A%7D;%0A%0A
-%0A
let App
|
e7112d6b515f8309a911e0b42151df5c9961d4ce
|
add docs
|
lib/Installer.js
|
lib/Installer.js
|
/**
* Module dependencies.
*/
var Emitter = require('events').EventEmitter
, dirname = require('path').dirname
, basename = require('path').basename
, extname = require('path').extname
, mkdir = require('mkdirp').mkdirp
, request = require('superagent')
, debug = require('debug')('component:installer')
, fs = require('fs');
/**
* Expose installer.
*/
module.exports = Installer;
/**
* Initialize a new `Installer` with
* the given `pkg` name and `dest` dir.
*
* @param {String} pkg
* @param {String} dest
* @api private
*/
function Installer(pkg, dest) {
debug('installing %s to %s', pkg, dest);
if (!pkg) throw new Error('pkg required');
if (!dest) throw new Error('destination required');
this.name = pkg;
this.dest = dest;
this.version = 'master';
}
/**
* Inherit from `Emitter.prototype`.
*/
Installer.prototype.__proto__ = Emitter.prototype;
/**
* Return URL to the component.json
*
* @param {Type} name
* @return {Type}
* @api public
*/
Installer.prototype.jsonURL = function(){
return 'https://raw.github.com/' + this.name + '/' + this.version + '/component.json';
};
Installer.prototype.getJSON = function(fn){
var self = this;
var url = this.jsonURL();
request.get(url, function(res){
if (res.ok) {
fn(null, JSON.parse(res.text));
} else {
fn(new Error('failed to fetch ' + url));
}
});
};
/**
* Install the component.
*
* @api public
*/
Installer.prototype.install = function(){
var self = this;
this.getJSON(function(err, json){
if (err) return self.emit('error', err);
console.log(json);
});
};
|
JavaScript
| 0.000001 |
@@ -1128,16 +1128,118 @@
n';%0A%7D;%0A%0A
+/**%0A * Get component.json and callback %60fn(err, obj)%60.%0A *%0A * @param %7BFunction%7D fn%0A * @api public%0A */%0A%0A
Installe
|
ecfef7abbab160585f147387904b67d6f014d8d7
|
fix transition animation when going to next post
|
addons/website_blog/static/src/js/website_blog.js
|
addons/website_blog/static/src/js/website_blog.js
|
odoo.define('website_blog.website_blog', function (require) {
'use strict';
var publicWidget = require('web.public.widget');
publicWidget.registry.websiteBlog = publicWidget.Widget.extend({
selector: '.website_blog',
events: {
'click #o_wblog_next_container': '_onNextBlogClick',
'click #o_wblog_post_content_jump': '_onContentAnchorClick',
'click .o_twitter, .o_facebook, .o_linkedin, .o_google, .o_twitter_complete, .o_facebook_complete, .o_linkedin_complete, .o_google_complete': '_onShareArticle',
},
/**
* @override
*/
start: function () {
$('.js_tweet, .js_comment').share({});
return this._super.apply(this, arguments);
},
//--------------------------------------------------------------------------
// Handlers
//--------------------------------------------------------------------------
/**
* @private
* @param {Event} ev
*/
_onNextBlogClick: function (ev) {
ev.preventDefault();
var self = this;
var $el = $(ev.currentTarget);
var nexInfo = $el.find('#o_wblog_next_post_info').data();
$el.find('.o_record_cover_container').addClass(nexInfo.size + ' ' + nexInfo.text).end()
.find('.o_wblog_toggle').toggleClass('d-none');
// Appending a placeholder so that the cover can scroll to the top of the
// screen, regardless of its height.
const placeholder = document.createElement('div');
placeholder.style.minHeight = '100vh';
this.$('#o_wblog_next_container').append(placeholder);
// Use _.defer to calculate the 'offset()'' only after that size classes
// have been applyed and that $el has been resized.
_.defer(function () {
self._forumScrollAction($el, 300, function () {
window.location.href = nexInfo.url;
});
});
},
/**
* @private
* @param {Event} ev
*/
_onContentAnchorClick: function (ev) {
ev.preventDefault();
ev.stopImmediatePropagation();
var $el = $(ev.currentTarget.hash);
this._forumScrollAction($el, 500, function () {
window.location.hash = 'blog_content';
});
},
/**
* @private
* @param {Event} ev
*/
_onShareArticle: function (ev) {
ev.preventDefault();
var url = '';
var $element = $(ev.currentTarget);
var blogPostTitle = encodeURIComponent($('#o_wblog_post_name').html() || '');
var articleURL = encodeURIComponent(window.location.href);
if ($element.hasClass('o_twitter')) {
url = 'https://twitter.com/intent/tweet?tw_p=tweetbutton&text=Amazing blog article : ' + blogPostTitle + "! " + articleURL;
} else if ($element.hasClass('o_facebook')) {
url = 'https://www.facebook.com/sharer/sharer.php?u=' + articleURL;
} else if ($element.hasClass('o_linkedin')) {
url = 'https://www.linkedin.com/shareArticle?mini=true&url=' + articleURL + '&title=' + blogPostTitle;
}
window.open(url, '', 'menubar=no, width=500, height=400');
},
//--------------------------------------------------------------------------
// Utils
//--------------------------------------------------------------------------
/**
* @private
* @param {JQuery} $el - the element we are scrolling to
* @param {Integer} duration - scroll animation duration
* @param {Function} callback - to be executed after the scroll is performed
*/
_forumScrollAction: function ($el, duration, callback) {
var $mainNav = $('#wrapwrap > header');
var gap = $mainNav.height() + $mainNav.offset().top;
$('html, body').stop().animate({
scrollTop: $el.offset().top - gap
}, duration, 'swing', function () {
callback();
});
},
});
});
|
JavaScript
| 0.000005 |
@@ -3639,20 +3639,19 @@
-var
+const
$main
-Nav
= $
@@ -3668,14 +3668,12 @@
p %3E
-header
+main
');%0A
@@ -3699,44 +3699,58 @@
main
-Nav.height() + $mainNav.offset().top
+.offset().top + parseInt($main.css('padding-top'))
;%0A%0A
|
c985e68c2454510cfc64c51af08a9a2bcc515a21
|
fix initialization using nonexistent 'has' method
|
lib/Models/initialization.js
|
lib/Models/initialization.js
|
const { default: PQueue } = require('p-queue');
const Guild = require('./Guild');
const Channel = require('./Channel');
const loaded = { guilds: false, channels: false };
const createQueue = () =>
new PQueue({
concurrency: 5,
autoStart: false,
});
const addGuilds = async bot => {
const queue = createQueue();
const guilds = await Guild.fetchAll();
queue.addAll(
bot.guilds
.array()
.filter(g => g && g.id && !guilds.get(g.id))
.map(g => () => Guild.create(g))
);
await queue.start();
};
const addChannels = async bot => {
const queue = createQueue();
const channels = await Channel.fetchAll();
queue.addAll(
bot.channels
.array()
.filter(ch => ch && ch.id && !channels.get(ch.id))
.map(ch => () => Channel.create(ch))
);
await queue.start();
};
module.exports = async bot => {
if (!loaded.guilds) {
loaded.guilds = true;
bot.on('guildDelete', async guild => {
if (!guild || !guild.available) return;
await Guild.delete(guild, false);
});
bot.on('guildCreate', async guild => {
if (!guild || !guild.available) return;
if (await Guild.has(guild)) return;
await Guild.create(g);
});
await addGuilds(bot);
}
if (!loaded.channels) {
loaded.channels = true;
bot.on('channelDelete', async channel => {
if (!channel || channel.type !== 'text') return;
await Channel.delete(channel, false);
});
bot.on('channelCreate', async channel => {
if (!channel || channel.type !== 'text') return;
if (await Channel.has(channel)) return;
await Channel.create(channel);
});
await addChannels(bot);
}
};
|
JavaScript
| 0.000048 |
@@ -1274,19 +1274,20 @@
t Guild.
-has
+find
(guild))
@@ -1764,11 +1764,12 @@
nel.
-has
+find
(cha
|
79284e2e7862daffad0034375f46ec74dd220792
|
Bump to version 0.0.6
|
package.js
|
package.js
|
Package.describe({
name: 'cfs:micro-queue',
version: '0.0.5',
summary: 'Micro-queue provides a small, fast queue/list built for Power-Queue',
git: 'https://github.com/CollectionFS/Meteor-micro-queue.git'
});
Package.onUse(function (api) {
api.versionsFrom('1.0');
api.use('deps', ['client', 'server']);
api.export('MicroQueue');
api.addFiles(['micro-queue.js'], ['client', 'server']);
});
Package.onTest(function (api) {
api.use('cfs:micro-queue');
api.use('test-helpers', 'server');
api.use('tinytest');
api.addFiles('tests.js');
});
|
JavaScript
| 0 |
@@ -59,9 +59,9 @@
0.0.
-5
+6
',%0A
|
0f2dcfadb37d6633f7959f4a096369a6d2202d7b
|
handle serial port buffer overrun (#574)
|
providers/serialport.js
|
providers/serialport.js
|
/*
* Copyright 2014-2015 Fabian Tollenaar <[email protected]>
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/* Usage: This is the first pipeElement in a PipedProvider. Used to pass data input from Serial
* to the next pipeElement.
* Reads data from a serial device and allows writing back to serial with the "toStdout" option
* It takes two options; "device" and "baudrate".
*
* The "toStdout" option is not mandatory. It routes events emitted on app with that name to
* serial output, followed by newline. toStdout can be a string or an array of strings.
*
* Example:
{
"type": "providers/serialport",
"options": {
"device": "/dev/ttyUSB0",
"baudrate": 4800,
"toStdout": "nmea0183out1"
},
"optionMappings": [
{
"fromAppProperty": "argv.nmeadevice",
"toOption": "device"
},
{
"fromAppProperty": "argv.nmeabaudrate",
"toOption": "baudrate"
}
]
},
*/
const Transform = require('stream').Transform
const SerialPort = require('serialport')
const isArray = require('lodash').isArray
function SerialStream (options) {
if (!(this instanceof SerialStream)) {
return new SerialStream(options)
}
Transform.call(this, options)
this.reconnect = options.reconnect || true
this.serial = null
this.options = options
this.start()
}
require('util').inherits(SerialStream, Transform)
SerialStream.prototype.start = function () {
if (this.serial !== null) {
this.serial.unpipe(this)
this.serial.removeAllListeners()
this.serial = null
}
if (this.reconnect === false) {
return
}
this.serial = new SerialPort(this.options.device, {
baudRate: this.options.baudrate
})
this.serial.on(
'open',
function () {
const parser = new SerialPort.parsers.Readline()
this.serial.pipe(parser).pipe(this)
}.bind(this)
)
this.serial.on('error', function (x) {
console.log(x)
})
this.serial.on('close', this.start.bind(this))
var that = this
const stdOutEvent = this.options.toStdout
if (stdOutEvent) {
;(isArray(stdOutEvent) ? stdOutEvent : [stdOutEvent]).forEach(event => {
console.log(event)
that.options.app.on(event, d => that.serial.write(d + '\r\n'))
})
}
}
SerialStream.prototype.end = function () {
this.serial.close()
}
SerialStream.prototype._transform = function (chunk, encoding, done) {
this.push(chunk)
done()
}
module.exports = SerialStream
|
JavaScript
| 0 |
@@ -1586,16 +1586,69 @@
.isArray
+%0Aconst debug = require('debug')('signalk:serialport')
%0A%0Afuncti
@@ -1882,16 +1882,72 @@
options%0A
+ this.maxPendingWrites = options.maxPendingWrites %7C%7C 5%0A
this.s
@@ -2622,16 +2622,40 @@
= this%0A
+ let pendingWrites = 0%0A
const
@@ -2817,75 +2817,379 @@
nt)%0A
- that.options.app.on(event, d =%3E that.serial.write(d + '%5Cr%5Cn')
+%0A const onDrain = () =%3E %7B%0A pendingWrites--%0A %7D%0A%0A that.options.app.on(event, d =%3E %7B%0A if (pendingWrites %3E that.maxPendingWrites) %7B%0A debug('Buffer overflow, not writing:' + d)%0A return%0A %7D%0A debug('Writing:' + d)%0A that.serial.write(d + '%5Cr%5Cn')%0A pendingWrites++%0A that.serial.drain(onDrain)%0A %7D
)%0A
|
91d29d5f7e9f23af4852fa5c43264703058ca54a
|
Use `applicationMenu` property of app to set the current menu
|
example/main.js
|
example/main.js
|
const electron = require('electron');
const app = electron.app;
const Menu = electron.Menu;
const BrowserWindow = electron.BrowserWindow;
const join = require('path').join;
// Replace '..' with 'about-window'
const openAboutWindow = require('..').default;
app.once('window-all-closed', function() {
app.quit();
});
app.once('ready', function() {
let w = new BrowserWindow();
w.once('closed', function() {
w = null;
});
w.loadURL('file://' + join(__dirname, 'index.html'));
const options = {
icon_path: join(__dirname, 'icon.png'),
copyright: 'Copyright (c) 2015 rhysd',
package_json_dir: __dirname,
win_options: {
resizable: false,
minimizable: false,
maximizable: false,
movable: false,
parent: w,
modal: true,
}
}
const menu = Menu.buildFromTemplate([
{
label: 'Example',
submenu: [
{
label: 'About This App',
click: () =>
openAboutWindow({
icon_path: join(__dirname, 'icon.png'),
copyright: 'Copyright (c) 2015 rhysd',
package_json_dir: __dirname,
open_devtools: process.env.NODE_ENV !== 'production',
}),
},
{
label: 'About This App (modal with close)',
click: () =>
openAboutWindow({
icon_path: join(__dirname, 'icon.png'),
copyright: 'Copyright (c) 2015 rhysd',
package_json_dir: __dirname,
win_options: {
parent: w,
modal: true,
},
show_close_button: "Close"
}),
},
{
label: 'About This App (modal with options)',
click: () =>
openAboutWindow(options),
},
],
},
]);
Menu.setApplicationMenu(menu);
});
|
JavaScript
| 0.000001 |
@@ -2267,17 +2267,13 @@
-Menu.setA
+app.a
ppli
@@ -2286,14 +2286,15 @@
Menu
-(
+ =
menu
-)
;%0A%7D)
|
b994e896d723cff455a0798f1555bd8674dcbf1e
|
Add custom events to make it easy to trigger something after open/close
|
modal.js
|
modal.js
|
/*!
* CSS Modal
* http://drublic.github.com/css-modal
*
* @author Hans Christian Reinl - @drublic
* @version 1.0
*/
(function () {
'use strict';
// Storage variable
var modal = {};
// Store for currently active element
modal.lastActive = undefined;
modal.activeElement = undefined;
// Polyfill addEventListener for IE8 (only very basic)
document._addEventListener = document.addEventListener || function (event, callback) {
document.attachEvent('on' + event, callback);
};
// Hide overlay when ESC is pressed
document._addEventListener('keyup', function (event) {
var hash = window.location.hash.replace('#', '');
// If hash is not set
if (hash === '' || hash === '!') {
return;
}
// If key ESC is pressed
if (event.keyCode === 27) {
window.location.hash = '!';
// Unfocus
modal.removeFocus();
}
}, false);
// When showing overlay, prevent background from scrolling
window.onhashchange = function () {
var hash = window.location.hash.replace('#', '');
var modalChild;
// If hash is set
if (hash !== '' && hash !== '!') {
// Get first element in selected element
modalChild = document.getElementById(hash).children[0];
// When we deal with a modal and class `has-overlay` is not set on html yet
if (modalChild && modalChild.className.match(/modal-inner/) && !document.documentElement.className.match(/has-overlay/)) {
// Set an html class to prevent scrolling
document.documentElement.className += ' has-overlay';
// Mark modal as active
document.getElementById(hash).className += ' is-active';
modal.activeElement = document.getElementById(hash);
// Set the focus to the modal
modal.setFocus(hash);
}
} else {
document.documentElement.className = document.documentElement.className.replace(' has-overlay', '');
// If activeElement is already defined, delete it
if (modal.activeElement) {
modal.activeElement.className = modal.activeElement.className.replace(' is-active', '');
modal.activeElement = null;
// Unfocus
modal.removeFocus();
}
}
};
/*
* Accessability
*/
// Focus modal
modal.setFocus = function (hash) {
if (modal.activeElement &&
typeof modal.activeElement.contains === 'function' &&
!modal.activeElement.contains(hash)) {
// Set element with last focus
modal.lastActive = document.activeElement;
// New focussing
modal.activeElement.focus();
}
};
// Unfocus
modal.removeFocus = function () {
if (modal.lastActive) {
modal.lastActive.focus();
}
};
}());
|
JavaScript
| 0 |
@@ -856,16 +856,359 @@
alse);%0A%0A
+%09// Conveniance function to trigger event%0A%09modal._dispatchEvent = function (event, modal) %7B%0A%09%09var eventTigger;%0A%0A%09%09if (!document.createEvent) %7B%0A%09%09%09return;%0A%09%09%7D%0A%0A%09%09eventTigger = document.createEvent('Event');%0A%0A%09%09eventTigger.initEvent(event, true, true);%0A%09%09eventTigger.customData = %7B 'modal': modal %7D;%0A%0A%09%09document.dispatchEvent(eventTigger);%0A%09%7D;%0A%0A
%0A%09// Whe
@@ -2047,16 +2047,102 @@
s(hash);
+%0A%0A%09%09%09%09// Fire an event%0A%09%09%09%09modal._dispatchEvent('cssmodal:show', modal.activeElement);
%0A%09%09%09%7D%0A%09%09
@@ -2430,16 +2430,131 @@
e', '');
+%0A%0A%09%09%09%09// Fire an event%0A%09%09%09%09modal._dispatchEvent('cssmodal:hide', modal.activeElement);%0A%0A%09%09%09%09// Reset active element
%0A%09%09%09%09mod
|
9dabb2b12ee2a9649d3139ab55322b1c14268000
|
Add subject: further math
|
view/CIESubjects.data.js
|
view/CIESubjects.data.js
|
/*
List of all CIE subjects that SchSrch officially maintain.
If you want SchSrch to include additional subjects, report with either GitHub issues or on-site feedback.
SchSrch will do its best to keep all contents up-to-date.
*/
module.exports = [
{
id: '0400',
level: 'IGCSE',
name: 'Art & Design',
},
{
id: '0410',
level: 'IGCSE',
name: 'Music'
},
{
id: '0450',
level: 'IGCSE',
name: 'Business Studies'
},
{
id: '0452',
level: 'IGCSE',
name: 'Accounting'
},
{
id: '0460',
level: 'IGCSE',
name: 'Geography'
},
{
id: '0470',
level: 'IGCSE',
name: 'History'
},
{
id: '0486',
level: 'IGCSE',
name: 'English - Literature'
},
{
id: '0495',
level: 'IGCSE',
name: 'Sociology'
},
{
id: '0500',
level: 'IGCSE',
name: 'English - First Language'
},
{
id: '0511',
level: 'IGCSE',
name: 'English as a Second Language'
},
{
id: '0522',
level: 'IGCSE',
name: 'English - First Language (UK)'
},
{
id: '0530',
level: 'IGCSE',
name: 'Spanish - Foreign Language'
},
{
id: '0580',
level: 'IGCSE',
name: 'Mathematics'
},
{
id: '0606',
level: 'IGCSE',
name: 'Mathematics - Additional'
},
{
id: '0610',
level: 'IGCSE',
name: 'Biology'
},
{
id: '0620',
level: 'IGCSE',
name: 'Chemistry'
},
{
id: '0625',
level: 'IGCSE',
name: 'Physics'
},
{
id: '8987',
level: 'AS',
name: 'Global Perspectives (AS Level only)',
deprecation: {
successor: '9239',
final: 'w15'
}
},
{
id: '9239',
level: 'A/s',
name: 'Global Perspectives and Research'
},
{
id: '9389',
level: 'A/s',
name: 'History'
},
{
id: '9609',
level: 'A/s',
name: 'Business'
},
{
id: '9697',
level: 'A/s',
name: 'History',
deprecation: {
successor: '9389',
final: 'w14'
}
},
{
id: '9699',
level: 'A/s',
name: 'Sociology'
},
{
id: '9700',
level: 'A/s',
name: 'Biology'
},
{
id: '9701',
level: 'A/s',
name: 'Chemistry'
},
{
id: '9702',
level: 'A/s',
name: 'Physics'
},
{
id: '9707',
level: 'A/s',
name: 'Business Studies',
deprecation: {
successor: '9609',
final: 'w15'
}
},
{
id: '9708',
level: 'A/s',
name: 'Economics'
},
{
id: '9709',
level: 'A/s',
name: 'Mathematics'
}
]
|
JavaScript
| 0.999797 |
@@ -1645,32 +1645,109 @@
%0A %7D%0A %7D,%0A %7B%0A
+ id: '9231',%0A level: 'A/s',%0A name: 'Mathematics - Further'%0A %7D,%0A %7B%0A
id: '9239',%0A
|
07a190238630227102bcd367a84d340984022376
|
Add stroke to the marker
|
web/app/view/map/Map.js
|
web/app/view/map/Map.js
|
/*
* Copyright 2015 Anton Tananaev ([email protected])
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
Ext.define('Traccar.view.map.Map', {
extend: 'Ext.form.Panel',
xtype: 'map-view',
title: strings.map_title,
layout: 'fit',
/*update: function() {
Ext.Ajax.request({
scope: this,
url: '/api/async',
success: function(response) {
var data = Ext.decode(response.responseText).data;
var i;
for (i = 0; i < data.length; i++) {
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point([30, 30])
});
this.vectorSource.addFeature(iconFeature);
}
this.update();
},
failure: function() {
// error
}
});
},*/
listeners: {
afterrender: function() {
var transform = this.transform;
/*var bindKey = 'AseEs0DLJhLlTNoxbNXu7DGsnnH4UoWuGue7-irwKkE3fffaClwc9q_Mr6AyHY8F';
var layer = new ol.layer.Tile({ source: new ol.source.BingMaps({
key: bindKey,
imagerySet: 'Road'
})});
var layer = new ol.layer.Tile({ source: new ol.source.BingMaps({
key: bindKey,
imagerySet: 'Aerial'
})});*/
var layer = new ol.layer.Tile({ source: new ol.source.OSM({
})});
this.vectorSource = new ol.source.Vector({});
var vectorLayer = new ol.layer.Vector({
source: this.vectorSource,
style: new ol.style.Style({
text: new ol.style.Text({
text: '\uf041',
font: 'normal 32px FontAwesome',
textBaseline: 'Bottom',
fill: new ol.style.Fill({
color: 'green'
})
})
})
});
var view = new ol.View({
center: ol.proj.fromLonLat(styles.map_center),
zoom: styles.map_zoom,
maxZoom: styles.map_max_zoom
});
this.map = new ol.Map({
target: this.body.dom.id,
layers: [ layer, vectorLayer ],
view: view
});
var iconFeature = new ol.Feature({
geometry: new ol.geom.Point(ol.proj.fromLonLat([-1.257778, 51.751944]))
});
this.vectorSource.addFeature(iconFeature);
//this.update();
},
resize: function() {
this.map.updateSize();
}
}
});
|
JavaScript
| 0.000013 |
@@ -2559,14 +2559,175 @@
r: '
-g
re
-en'
+d'%0A %7D),%0A stroke: new ol.style.Stroke(%7B%0A color: 'black',%0A width: 2
%0A
|
ce6b1b603b84d14f614d51422e4abadd307207a9
|
Update plugin.js
|
app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js
|
app/assets/javascripts/tinymce/plugins/uploadimage/plugin.js
|
(function() {
tinymce.PluginManager.requireLangPack('uploadimage');
tinymce.create('tinymce.plugins.UploadImage', {
UploadImage: function(ed, url) {
var form,
iframe,
win,
throbber,
editor = ed;
function showDialog() {
win = editor.windowManager.open({
title: ed.translate('Insert an image from your computer'),
width: 500 + parseInt(editor.getLang('uploadimage.delta_width', 0), 10),
height: 180 + parseInt(editor.getLang('uploadimage.delta_height', 0), 10),
body: [
{type: 'iframe', url: 'javascript:void(0)'},
{type: 'textbox', name: 'file', label: ed.translate('Choose an image'), subtype: 'file'},
//{type: 'listbox', id: 'size', name: 'size', label: ed.translate('Image Size'),values: [
// {text: 'Medium', value: 'medium', name: 'size'},
// {text: 'Large', value: 'large'},
// {text: 'Original', value: 'original'}
//]},
{type: 'textbox', id: 'alt', name: 'alt', label: ed.translate('Image description') },
{type: 'textbox', id: 'size', name: 'size', label: ed.translate('Medium, Large or Original') },
{type: 'container', classes: 'error', html: "<p style='color: #b94a48;'> </p>"},
],
buttons: [
{
text: ed.translate('Insert'),
onclick: insertImage,
subtype: 'primary'
},
{
text: ed.translate('Cancel'),
onclick: ed.windowManager.close
}
],
}, {
plugin_url: url
});
// TinyMCE likes pointless submit handlers
win.off('submit');
win.on('submit', insertImage);
/* WHY DO YOU HATE <form>, TINYMCE!? */
iframe = win.find("iframe")[0];
form = createElement('form', {
action: ed.getParam("uploadimage_form_url", "/tinymce_assets"),
target: iframe._id,
method: "POST",
enctype: 'multipart/form-data',
accept_charset: "UTF-8",
});
// Might have several instances on the same page,
// so we TinyMCE create unique IDs and use those.
iframe.getEl().name = iframe._id;
// Create some needed hidden inputs
form.appendChild(createElement('input', {type: "hidden", name: "utf8", value: "✓"}));
form.appendChild(createElement('input', {type: 'hidden', name: 'authenticity_token', value: getMetaContents('csrf-token')}));
form.appendChild(createElement('input', {type: 'hidden', name: 'hint', value: ed.getParam("uploadimage_hint", "")}));
var el = win.getEl();
var body = document.getElementById(el.id + "-body");
// Copy everything TinyMCE made into our form
var containers = body.getElementsByClassName('mce-container');
for(var i = 0; i < containers.length; i++) {
form.appendChild(containers[i]);
}
// Fix inputs, since TinyMCE hates HTML and forms
var inputs = form.getElementsByTagName('input');
for(var i = 0; i < inputs.length; i++) {
var ctrl = inputs[i];
if(ctrl.tagName.toLowerCase() == 'input' && ctrl.type != "hidden") {
ctrl.name = ctrl.type == "file" ? "file" : // "alt";
ctrl.name = ctrl.id == "alt" ? "alt" : "size";
}
}
body.appendChild(form);
}
function insertImage() {
if(getInputValue("file") == "") {
return handleError('You must choose a file');
}
throbber = new top.tinymce.ui.Throbber(win.getEl());
throbber.show();
clearErrors();
/* Add event listeners.
* We remove the existing to avoid them being called twice in case
* of errors and re-submitting afterwards.
*/
var target = iframe.getEl();
if(target.attachEvent) {
target.detachEvent('onload', uploadDone);
target.attachEvent('onload', uploadDone);
} else {
target.removeEventListener('load', uploadDone);
target.addEventListener('load', uploadDone, false);
}
form.submit();
}
function uploadDone() {
if(throbber) {
throbber.hide();
}
var target = iframe.getEl();
if(target.document || target.contentDocument) {
var doc = target.contentDocument || target.contentWindow.document;
handleResponse(doc.getElementsByTagName("body")[0].innerHTML);
} else {
handleError("Didn't get a response from the server");
}
}
function handleResponse(ret) {
console.group("Handling response");
console.log("Raw", ret)
try {
var json = tinymce.util.JSON.parse(ret);
console.log("Parsed", json);
if(json["error"]) {
console.log("It has an error!", json["error"]["message"]);
handleError(json["error"]["message"]);
} else {
console.log("Inserting", buildHTML(json));
ed.execCommand('mceInsertContent', false, buildHTML(json));
ed.windowManager.close();
}
} catch(e) {
console.log("Bad response :(", e);
handleError('Got a bad response from the server');
}
console.groupEnd();
}
function clearErrors() {
var message = win.find(".error")[0].getEl();
if(message)
message.getElementsByTagName("p")[0].innerHTML = " ";
}
function handleError(error) {
console.log("Handling error", error);
var message = win.find(".error")[0].getEl();
if(message)
message.getElementsByTagName("p")[0].innerHTML = ed.translate(error);
}
function createElement(element, attributes) {
var el = document.createElement(element);
for(var property in attributes) {
if (!(attributes[property] instanceof Function)) {
el[property] = attributes[property];
}
}
return el;
}
function buildHTML(json) {
var default_class = ed.getParam("uploadimage_default_img_class", "");
var alt_text = getInputValue("alt");
var size_text = getInputValue("size");
var imgstr = "<a href='" + json["image"]["url"] + "'";
imgstr += " rel='" + "lightbox" + "'";
imgstr += " title='" + json["image"]["title"] + "'";
imgstr += " class='" + "cboxElement" + "'";
imgstr += "/>";
imgstr += "<img src='" + json["image"]["url"] + "'";
if(default_class != "")
imgstr += " class='" + default_class + "'";
if(json["image"]["height"])
imgstr += " height='" + json["image"]["height"] + "'";
if(json["image"]["width"])
imgstr += " width='" + json["image"]["width"] + "'";
imgstr += " size='" + size_text + "'";
imgstr += " alt='" + alt_text + "'/>";
imgstr += "</a>";
return imgstr;
}
function getInputValue(name) {
var inputs = form.getElementsByTagName("input");
for(var i in inputs)
if(inputs[i].name == name)
return inputs[i].value;
return "";
}
function getMetaContents(mn) {
var m = document.getElementsByTagName('meta');
for(var i in m)
if(m[i].name == mn)
return m[i].content;
return null;
}
// Add a button that opens a window
editor.addButton('uploadimage', {
tooltip: ed.translate('Insert an image from your computer'),
icon : 'image',
onclick: showDialog
});
// Adds a menu item to the tools menu
editor.addMenuItem('uploadimage', {
text: ed.translate('Insert an image from your computer'),
icon : 'image',
context: 'insert',
onclick: showDialog
});
}
});
tinymce.PluginManager.add('uploadimage', tinymce.plugins.UploadImage);
})();
|
JavaScript
| 0.000001 |
@@ -6434,34 +6434,39 @@
json%5B%22image%22%5D%5B%22
-ur
+origina
l%22%5D + %22'%22;%0A
|
7d83dd928cde167b3ef75e7732c0971403473184
|
Add minified test
|
mocha.entry.js
|
mocha.entry.js
|
/*eslint-env node, mocha*/
var ModernizrWebpackPlugin = require('./index');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var Promise = require('bluebird');
var assign = require('object-assign');
var path = require('path');
var fs = Promise.promisifyAll(require('fs'));
var del = require('del');
var expect = require('chai').expect;
var OUTPUT_PATH = path.resolve(__dirname, 'temp');
var webpack = Promise.promisify(require('webpack'));
var webpackConfig;
var webpackConfigBase = {
context: __dirname,
entry: {
'entry-bundle': './tests/entry.js'
},
output: {
filename: '[name].js',
path: OUTPUT_PATH
}
};
describe('[ModernizrWebpackPlugin] Build Tests', function () {
beforeEach(function (done) {
// reset config to base status
webpackConfig = assign({}, webpackConfigBase);
del(OUTPUT_PATH).then(function () {
done();
});
});
it('should output a hashed filename', function (done) {
var config = {filename: 'testing[hash]'};
webpackConfig.plugins = [
new HtmlWebpackPlugin(),
new ModernizrWebpackPlugin(config)
];
webpack(webpackConfig).then(function (stats) {
var hashDigestLength = stats.compilation.outputOptions.hashDigestLength;
return fs.readdirAsync(OUTPUT_PATH).then(function (files) {
var regexp = new RegExp('^testing[\\w\\d]{' + hashDigestLength + '}\\.js$');
files = files.filter(function (file) {
return regexp.test(file);
});
expect(files.length).to.equal(1);
done();
})
}).catch(done);
});
it('should include public path with html-webpack-plugin', function (done) {
webpackConfig.plugins = [
new HtmlWebpackPlugin(),
new ModernizrWebpackPlugin()
];
webpackConfig.output.publicPath = 'public/';
webpackConfig.plugins.push(new ModernizrWebpackPlugin());
webpack(webpackConfig).then(function () {
fs.readFileAsync(path.resolve(OUTPUT_PATH, 'index.html'), 'utf8').then(function (data) {
expect(/<script\ssrc="public\/modernizr-bundle.js">/.test(data)).to.be.true;
done();
})
}).catch(done);
});
});
|
JavaScript
| 0.000003 |
@@ -1804,70 +1804,8 @@
/';%0A
- webpackConfig.plugins.push(new ModernizrWebpackPlugin());%0A
@@ -1842,24 +1842,24 @@
nction () %7B%0A
+
fs.rea
@@ -2071,18 +2071,435 @@
(done);%0A
-
%7D);%0A%0A
+ it('should output minified modernizr package', function (done) %7B%0A webpackConfig.plugins = %5B%0A new ModernizrWebpackPlugin(%7B%0A minify:true%0A %7D)%0A %5D;%0A webpack(webpackConfig).then(function () %7B%0A fs.readFileAsync(path.resolve(OUTPUT_PATH, 'modernizr-bundle.js'), 'utf8').then(function (data) %7B%0A expect(/%5Cr%7C%5Cn/.test(data)).to.be.false;%0A done();%0A %7D);%0A %7D).catch(done)%0A %7D)%0A%0A
%7D);
|
09be8529e17ac5f9260c9c9d27cb0a832fa0fb11
|
Add passive option for touchmove events on der-reader #86
|
modules/der-reader/src/index.js
|
modules/der-reader/src/index.js
|
'use strict'
var webspeechapi, vibrateWebApi, DerReader
webspeechapi = require('./../../tts.webapi/tts.webapi.js')
vibrateWebApi = require('./../../vibrate.webapi/vibrate.webapi.js')
DerReader = require('./der-reader.js')
DerReader.init({
container: 'der-reader',
derFile: null,
tts: webspeechapi,
vibrate: vibrateWebApi,
defaultMode: 0,
format: 'A4',
exit: function () {}
})
function move_handler(ev) {
ev.preventDefault();
}
const el = document.getElementById('der-reader');
el.ontouchmove = move_handler;
|
JavaScript
| 0 |
@@ -495,18 +495,34 @@
r');%0Ael.
-on
+addEventListener(%22
touchmov
@@ -522,18 +522,18 @@
ouchmove
- =
+%22,
move_ha
@@ -537,10 +537,31 @@
_handler
+, %7B passive: false %7D)
;%0A
|
714b13e4e97a9ff103dfd4b52b5a4482b389f83d
|
allow client_id of 18 characters. datacite/lupo#291
|
app/models/client.js
|
app/models/client.js
|
import { computed } from '@ember/object';
import DS from 'ember-data';
import ENV from 'bracco/config/environment';
import { validator, buildValidations } from 'ember-cp-validations';
const Validations = buildValidations({
symbol: [
validator('presence', true),
validator('client-id', true),
validator('unique-client-id', {
presence: true,
disabled: computed('model', function() {
return !this.model.get('isNew');
})
}),
validator('format', {
regex: /^[A-Z]+\.[A-Z0-9]+(-[A-Z0-9]+)?$/,
message: 'The Client ID must start with the Provider ID, followed by a dot. It can then contain only upper case letters, numbers, and at most one hyphen.'
}),
validator('length', {
min: 5,
max: 17
})
],
confirmSymbol: [
validator('presence', {
presence: true,
disabled: computed('model', function() {
return this.model.get('isNew');
})
}),
validator('confirmation', {
on: 'symbol',
message: 'Client ID does not match',
disabled: computed('model', function() {
return this.model.get('isNew');
})
})
],
passwordInput: [
validator('presence', {
presence: true,
disabled: computed('model', function() {
return this.model.get('keepPassword');
})
}),
validator('length', {
min: 8,
disabled: computed('model', function() {
return this.model.get('keepPassword');
})
})
],
confirmPasswordInput: [
validator('presence', {
presence: true,
disabled: computed('model', function() {
return this.model.get('keepPassword');
})
}),
validator('confirmation', {
on: 'passwordInput',
message: 'Password does not match',
disabled: computed('model', function() {
return this.model.get('keepPassword');
})
})
],
name: validator('presence', true),
domains: validator('presence', true),
contactName: validator('presence', true),
contactEmail: [
validator('presence', true),
validator('format', {
type: 'email',
allowNonTld: true
})
]
});
export default DS.Model.extend(Validations, {
provider: DS.belongsTo('provider', {
async: true
}),
repository: DS.belongsTo('repository', {
async: true
}),
meta: DS.attr(),
name: DS.attr('string'),
symbol: DS.attr('string'),
domains: DS.attr('string', { defaultValue: '*' }),
contactName: DS.attr('string'),
contactEmail: DS.attr('string'),
year: DS.attr('number'),
description: DS.attr('string'),
url: DS.attr('string'),
software: DS.attr('string'),
isActive: DS.attr('boolean', { defaultValue: true }),
passwordInput: DS.attr('string'),
hasPassword: DS.attr('boolean'),
keepPassword: DS.attr('boolean', { defaultValue: true }),
created: DS.attr('date'),
updated: DS.attr('date'),
targetId: DS.attr(),
domainList: computed('domains', function() {
return this.domains.split(",").map(function(item) {
return item.trim();
});
}),
// 'provider-id': Ember.defineProperty('id', function() {
// return this.get('id').split('.').get('firstObject');
// }),
doiCount: computed('meta.dois', function() {
return this.get('meta.dois');
}),
totalDoiCount: computed('meta.dois', function() {
return this.get('meta.dois').reduce(function (a, b) {
return a + b.count;
}, 0);
}),
badgeUrl: computed('repository', function() {
if (this.repository) {
return ENV.RE3DATA_API_URL + '/repositories/' + this.repository.get('id') + '/badge';
} else {
return null;
}
})
});
|
JavaScript
| 0.000001 |
@@ -759,9 +759,9 @@
x: 1
-7
+8
%0A
|
28729996210a239896989843f4a075dd4cedc5ed
|
add momentjs as dependency
|
package.js
|
package.js
|
Package.describe({
name: "gildaspk:autoform-materialize",
summary: "Materialize theme for Autoform",
version: "0.0.25",
git: "https://github.com/djhi/meteor-autoform-materialize.git"
})
Package.onUse(function(api) {
api.versionsFrom("1.0")
api.use(["templating", "underscore"], "client")
api.use("aldeed:[email protected]")
api.addFiles([
// utility
'utilities/utility.js',
'utilities/initialize-select.js',
// utility template helpers
'utilities/dsk.js',
'utilities/selected-atts-adjust.js',
'utilities/atts-toggle-invalid-class.js',
'utilities/atts-check-selected.js',
'utilities/option-atts.js',
// input types
'inputTypes/boolean-checkbox/boolean-checkbox.html',
'inputTypes/boolean-checkbox/boolean-checkbox.js',
'inputTypes/boolean-radios/boolean-radios.html',
'inputTypes/boolean-radios/boolean-radios.js',
'inputTypes/boolean-select/boolean-select.html',
'inputTypes/boolean-select/boolean-select.js',
'inputTypes/button/button.html',
'inputTypes/color/color.html',
'inputTypes/color/color.js',
'inputTypes/contenteditable/contenteditable.html',
'inputTypes/date/date.html',
'inputTypes/date/date.js',
'inputTypes/datetime/datetime.html',
'inputTypes/datetime/datetime.js',
'inputTypes/datetime-local/datetime-local.html',
'inputTypes/datetime-local/datetime-local.js',
'inputTypes/email/email.html',
'inputTypes/email/email.js',
'inputTypes/file/file.html',
'inputTypes/hidden/hidden.html',
'inputTypes/icon/icon.html',
'inputTypes/image/image.html',
'inputTypes/month/month.html',
'inputTypes/month/month.js',
'inputTypes/number/number.html',
'inputTypes/number/number.js',
'inputTypes/password/password.html',
'inputTypes/password/password.js',
'inputTypes/radio/radio.html',
'inputTypes/radio/radio.js',
'inputTypes/range/range.html',
'inputTypes/reset/reset.html',
'inputTypes/search/search.html',
'inputTypes/select/select.html',
'inputTypes/select/select.js',
'inputTypes/select-checkbox/select-checkbox.html',
'inputTypes/select-checkbox/select-checkbox.js',
'inputTypes/select-checkbox-inline/select-checkbox-inline.html',
'inputTypes/select-checkbox-inline/select-checkbox-inline.js',
'inputTypes/select-multiple/select-multiple.html',
'inputTypes/select-multiple/select-multiple.js',
'inputTypes/select-radio/select-radio.html',
'inputTypes/select-radio/select-radio.js',
'inputTypes/select-radio-inline/select-radio-inline.html',
'inputTypes/select-radio-inline/select-radio-inline.js',
'inputTypes/submit/submit.html',
'inputTypes/tel/tel.html',
'inputTypes/tel/tel.js',
'inputTypes/text/text.html',
'inputTypes/text/text.js',
'inputTypes/textarea/textarea.html',
'inputTypes/textarea/textarea.js',
'inputTypes/time/time.html',
'inputTypes/time/time.js',
'inputTypes/url/url.html',
'inputTypes/url/url.js',
'inputTypes/week/week.html',
'inputTypes/week/week.js',
'inputTypes/switch/switch.html',
'inputTypes/switch/switch.js',
'inputTypes/pickadate/pickadate.html',
'inputTypes/pickadate/pickadate.js',
'inputTypes/label/label.html',
'inputTypes/label/label.js',
// components that render a form
'components/autoForm/autoForm.html',
'components/quickForm/quickForm.html',
'components/quickForm/quickForm.js',
// components that render controls within a form
'components/afArrayField/afArrayField.html',
'components/afFormGroup/afFormGroup.html',
'components/afFormGroup/afFormGroup.js',
'components/afObjectField/afObjectField.html',
'components/afQuickField/afQuickField.html'
], "client")
})
|
JavaScript
| 0.000001 |
@@ -294,16 +294,45 @@
lient%22)%0A
+ api.use('momentjs:moment')%0A
api.us
|
b2610597901af15ca5c46af5eae7e00eda6466c7
|
Set the odd/even strips after sorting.
|
src/encoded/static/libs/table_sorter.js
|
src/encoded/static/libs/table_sorter.js
|
/********* Table sorter script *************/
/*
* Apply sorting controls to a table.
* When user clicks on a th without 'nosort' class,
* it sort table values using the td 'data-sortabledata' attribute,
* or the td text content
*
*/
(function($) {
function sortable(cell) {
// convert a cell a to something sortable
// use data-sortabledata attribute if it is defined
var text = cell.attr('data-sortabledata');
if (text === undefined) { text = cell.text(); }
// A number, but not a date?
if (text.charAt(4) !== '-' && text.charAt(7) !== '-' && !isNaN(parseFloat(text))) {
return parseFloat(text);
}
return text.toLowerCase();
}
function sort() {
var th, colnum, table, tbody, reverse, index, data, usenumbers, tsorted;
th = $(this).closest('th');
colnum = $('th', $(this).closest('tr')).index(th);
table = $(this).parents('table:first');
tbody = table.find('tbody:first');
tsorted = parseInt(table.attr('sorted') || '-1', 10);
reverse = tsorted === colnum;
$(this).parent().find('th:not(.nosort) .sortdirection')
.removeClass('icon-chevron-up icon-chevron-down');
$(this).children('.sortdirection')
.removeClass('icon-chevron-up icon-chevron-down')
.addClass(reverse ? 'icon-chevron-up' : 'icon-chevron-down');
index = $(this).parent().children('th').index(this),
data = [],
usenumbers = true;
tbody.find('tr').each(function() {
var cells, sortableitem;
cells = $(this).children('td');
sortableitem = sortable(cells.slice(index,index+1));
if (isNaN(sortableitem)) { usenumbers = false; }
data.push([
sortableitem,
// crude way to sort by surname and name after first choice
sortable(cells.slice(1,2)), sortable(cells.slice(0,1)),
this]);
});
if (data.length) {
if (usenumbers) {
data.sort(function(a,b) {return a[0]-b[0];});
} else {
data.sort();
}
if (reverse) { data.reverse(); }
table.attr('sorted', reverse ? '' : colnum);
// appending the tr nodes in sorted order will remove them from their old ordering
tbody.append($.map(data, function(a) { return a[3]; }));
}
}
// jQuery plugins
// --------------
$.fn.setoddeven = function() {
return this.each(function() {
// jquery :odd and :even are 0 based
$(this).children(':not(.hidden)').removeClass('odd even')
.filter(':odd').addClass('even').end()
.filter(':even').addClass('odd');
});
};
$.fn.table_sorter = function () {
// set up blank spaceholder gif
var blankarrow = $('<i></i>').addClass('sortdirection icon-').css({float: 'right', 'margin-left': '1em'});
// all listing tables not explicitly nosort, all sortable th cells
// give them a pointer cursor and blank cell and click event handler
// the first one of the cells gets a up arrow instead.
return this.each(function () {
var $this = jQuery(this);
$this.find('thead tr:not(.nosort) th:not(.nosort)')
.append(blankarrow.clone())
.css('cursor', 'pointer')
.click(sort);
$this.find('tbody').setoddeven();
});
};
})(jQuery);
|
JavaScript
| 0 |
@@ -757,24 +757,50 @@
rted
-;%0A%0A%09th = $(this)
+, $this;%0A%0A $this = $(this);%0A%09th = $this
.clo
@@ -833,22 +833,20 @@
('th', $
-(
this
-)
.closest
@@ -873,30 +873,28 @@
table = $
-(
this
-)
.parents('ta
@@ -1043,22 +1043,20 @@
;%0A%0A $
-(
this
-)
.parent(
@@ -1156,30 +1156,28 @@
own');%0A $
-(
this
-)
.children('.
@@ -1334,22 +1334,20 @@
ndex = $
-(
this
-)
.parent(
@@ -2275,16 +2275,41 @@
);%0A %7D
+%0A%0A tbody.setoddeven();
%0A%7D%0A%0A// j
|
4eef525b5759d5d9ad09638fc300d4a2faae570a
|
Update tests
|
test/unit/controllers/MobileAppController.test.js
|
test/unit/controllers/MobileAppController.test.js
|
var root = require('root-path')
var setup = require(root('test/setup'))
var factories = require(root('test/setup/factories'))
var MobileAppController = require(root('api/controllers/MobileAppController'))
describe('MobileAppController', () => {
var req, res
beforeEach(() => {
req = factories.mock.request()
res = factories.mock.response()
})
describe('checkShouldUpdate', () => {
describe('calls the resultBuilder with the right params', () => {
it('returns the expected object for ios suggest update', () => {
var expected = {
type: 'suggest',
title: 'An update is available',
message: 'The version you are using is not longer up to date. Please go to the App Store to update.',
link: 'https://itunes.apple.com/app/id1002185140'
}
req.params = {'ios-version': '2.0'}
MobileAppController.checkShouldUpdate(req, res)
expect(res.body).to.deep.equal(expected)
})
it('returns the expected object for ios force update', () => {
var expected = {
type: 'force',
title: 'A new version of the app is available',
message: 'The version you are using is no longer compatible with the site. Please go to the App Store now to update',
link: 'https://itunes.apple.com/app/id1002185140'
}
req.params = {'ios-version': '1.9'}
MobileAppController.checkShouldUpdate(req, res)
expect(res.body).to.deep.equal(expected)
})
it('returns the expected object for android suggest update', () => {
var expected = {
type: 'suggest',
title: 'An update is available',
message: 'The version you are using is not longer up to date. Please go to the Play Store to update.',
link: 'https://play.google.com/store/apps/details?id=com.hylo.reactnative'
}
req.params = {'android-version': '2.0'}
MobileAppController.checkShouldUpdate(req, res)
expect(res.body).to.deep.equal(expected)
})
it('returns the expected object for android force update', () => {
var expected = {
type: 'force',
title: 'A new version of the app is available',
message: 'The version you are using is no longer compatible with the site. Please go to the Play Store now to update',
link: 'https://play.google.com/store/apps/details?id=com.hylo.reactnative'
}
req.params = {'android-version': '1.9'}
MobileAppController.checkShouldUpdate(req, res)
expect(res.body).to.deep.equal(expected)
})
})
})
})
|
JavaScript
| 0.000001 |
@@ -463,24 +463,27 @@
) =%3E %7B%0A
+ //
it('returns
@@ -533,32 +533,35 @@
', () =%3E %7B%0A
+ //
var expected
@@ -561,32 +561,35 @@
pected = %7B%0A
+ //
type: 'sugg
@@ -592,36 +592,39 @@
suggest',%0A
+//
+
title: 'An updat
@@ -637,32 +637,35 @@
vailable',%0A
+ //
message: 'T
@@ -752,32 +752,35 @@
update.',%0A
+ //
link: 'http
@@ -819,38 +819,52 @@
85140'%0A
+ //
%7D%0A
+ //
%0A
+//
+
req.params =
@@ -884,32 +884,35 @@
n': '2.0'%7D%0A
+ //
MobileAppCont
@@ -943,32 +943,35 @@
(req, res)%0A
+ //
expect(res.bo
@@ -995,32 +995,35 @@
(expected)%0A
+ //
%7D)%0A it('re
@@ -1541,32 +1541,35 @@
)%0A %7D)%0A
+ //
it('returns the
@@ -1619,32 +1619,35 @@
', () =%3E %7B%0A
+ //
var expected
@@ -1647,32 +1647,35 @@
pected = %7B%0A
+ //
type: 'sugg
@@ -1678,36 +1678,39 @@
suggest',%0A
+//
+
title: 'An updat
@@ -1723,32 +1723,35 @@
vailable',%0A
+ //
message: 'T
@@ -1839,32 +1839,35 @@
update.',%0A
+ //
link: 'http
@@ -1931,38 +1931,52 @@
ative'%0A
+ //
%7D%0A
+ //
%0A
+//
+
req.params =
@@ -2000,32 +2000,35 @@
n': '2.0'%7D%0A
+ //
MobileAppCont
@@ -2059,32 +2059,35 @@
(req, res)%0A
+ //
expect(res.bo
@@ -2111,32 +2111,35 @@
(expected)%0A
+ //
%7D)%0A it('re
|
59cdc191dfe824c03fd0bc7f4b9a73d11d834457
|
Improve sub error message.
|
_setup/utils/get-sub-error-message.js
|
_setup/utils/get-sub-error-message.js
|
'use strict';
module.exports = function (error) { return error.key + ': ' + error.message; };
|
JavaScript
| 0.000001 |
@@ -43,17 +43,64 @@
error) %7B
-
+%0A%09if (error.key == null) return error.message;%0A%09
return e
@@ -131,12 +131,12 @@
message;
-
+%0A
%7D;%0A
|
81711d7eac9b5b65bc1c820921fda59fd0fdc51e
|
enable bootstrap.js
|
config/env/all.js
|
config/env/all.js
|
'use strict';
module.exports = {
app: {
title: 'Studio Center Auditions',
description: 'Full-Stack JavaScript with MongoDB, Express, AngularJS, and Node.js',
keywords: 'MongoDB, Express, AngularJS, Node.js'
},
port: process.env.PORT || 3000,
templateEngine: 'swig',
sessionSecret: 'MEAN',
sessionCollection: 'sessions',
assets: {
lib: {
css: [
'public/lib/bootstrap/dist/css/bootstrap.css',
'public/lib/bootstrap/dist/css/bootstrap-theme.css',
'public/lib/soundmanager/demo/demo/play-mp3-links/css/inlineplayer.css',
'public/lib/soundmanager/demo/flashblock/flashblock.css',
'public/lib/angular-bootstrap-datetimepicker/src/css/datetimepicker.css'
],
js: [
'public/lib/moment/moment.js',
'public/lib/moment-timezone/moment-timezone-with-data.min.js',
'public/lib/angular/angular.js',
'public/lib/angular-moment/angular-moment.min.js',
'public/lib/ng-file-upload-shim/angular-file-upload-shim.min.js',
'public/lib/ng-file-upload/angular-file-upload.min.js',
'public/lib/jquery/dist/jquery.min.js',
'public/lib/angular-resource/angular-resource.js',
'public/lib/angular-cookies/angular-cookies.js',
'public/lib/angular-animate/angular-animate.js',
'public/lib/angular-touch/angular-touch.js',
'public/lib/angular-sanitize/angular-sanitize.js',
'public/lib/angular-ui-router/release/angular-ui-router.js',
'public/lib/angular-ui-utils/ui-utils.js',
//'public/lib/bootstrap/dist/js/bootstrap.min.js',
'public/lib/angular-bootstrap/ui-bootstrap-tpls.js',
'public/lib/ngAudio/app/angular.audio.js',
'public/lib/angular-encode-uri/dist/angular-encode-uri.min.js',
'public/lib/angular-bootstrap-datetimepicker/src/js/datetimepicker.js'
]
},
css: [
'public/modules/**/css/*.css'
],
js: [
'public/config.js',
'public/application.js',
'public/modules/*/*.js',
'public/modules/*/*[!tests]*/*.js'
],
tests: [
'public/lib/angular-mocks/angular-mocks.js',
'public/modules/*/tests/*.js'
]
}
};
|
JavaScript
| 0.000004 |
@@ -1418,45 +1418,50 @@
lib/
-angular-ui-utils/ui-utils
+bootstrap/dist/js/bootstrap.min
.js',
+
%0A%09%09%09%09
-//
'pub
@@ -1472,45 +1472,38 @@
lib/
-bootstrap/dist/js/bootstrap.min
+angular-ui-utils/ui-utils
.js',
-
%0A%09%09%09
|
1ea71fd030cfbeb61a1a1d90ec80ddc8da6fa284
|
use two slashes in RegExp strings for escapement (see http://stackoverflow.com/questions/7735749/fix-jslint-bad-escapement-warning-in-regex)
|
lib/OpenLayers/SingleFile.js
|
lib/OpenLayers/SingleFile.js
|
/* Copyright (c) 2006-2012 by OpenLayers Contributors (see authors.txt for
* full list of contributors). Published under the Clear BSD license.
* See http://svn.openlayers.org/trunk/openlayers/license.txt for the
* full text of the license. */
var OpenLayers = {
/**
* Constant: VERSION_NUMBER
*/
VERSION_NUMBER: "$Revision$",
/**
* Constant: singleFile
* TODO: remove this in 3.0 when we stop supporting build profiles that
* include OpenLayers.js
*/
singleFile: true,
/**
* Method: _getScriptLocation
* Return the path to this script. This is also implemented in
* OpenLayers.js
*
* Returns:
* {String} Path to this script
*/
_getScriptLocation: (function() {
var r = new RegExp("(^|(.*?\\/))(OpenLayers.*?\.js)(\\?|$)"),
s = document.getElementsByTagName('script'),
src, m, l = "";
for(var i=0, len=s.length; i<len; i++) {
src = s[i].getAttribute('src');
if(src) {
m = src.match(r);
if(m) {
l = m[1];
break;
}
}
}
return (function() { return l; });
})(),
/**
* Property: ImgPath
* {String} Set this to the path where control images are stored, a path
* given here must end with a slash. If set to '' (which is the default)
* OpenLayers will use its script location + "img/".
*
* You will need to set this property when you have a singlefile build of
* OpenLayers that either is not named "OpenLayers.js" or if you move
* the file in a way such that the image directory cannot be derived from
* the script location.
*
* If your custom OpenLayers build is named "my-custom-ol.js" and the images
* of OpenLayers are in a folder "/resources/external/images/ol" a correct
* way of including OpenLayers in your HTML would be:
*
* (code)
* <script src="/path/to/my-custom-ol.js" type="text/javascript"></script>
* <script type="text/javascript">
* // tell OpenLayers where the control images are
* // remember the trailing slash
* OpenLayers.ImgPath = "/resources/external/images/ol/";
* </script>
* (end code)
*
* Please remember that when your OpenLayers script is not named
* "OpenLayers.js" you will have to make sure that the default theme is
* loaded into the page by including an appropriate <link>-tag,
* e.g.:
*
* (code)
* <link rel="stylesheet" href="/path/to/default/style.css" type="text/css">
* (end code)
*/
ImgPath : ''
};
|
JavaScript
| 0 |
@@ -808,16 +808,17 @@
yers.*?%5C
+%5C
.js)(%5C%5C?
|
88d26c4300603b6c32235be94899882a5bac60a3
|
change version to 0.1.2
|
package.js
|
package.js
|
Package.describe({
summary: "Login service for Odnoklassniki.ru accounts (https://ok.ru)",
version: "0.1.1",
git: "https://github.com/mike1pol/meteor-accounts-ok.git",
name: "mikepol:accounts-ok"
});
Package.on_use(function(api) {
api.versionsFrom('[email protected]');
api.use('accounts-base', ['client', 'server']);
api.imply('accounts-base', ['client', 'server']);
api.use('accounts-oauth', ['client', 'server']);
api.imply('accounts-oauth', ['client', 'server']);
api.use('jparker:[email protected]', ['server']);
api.use('oauth2', ['client', 'server']);
api.use('oauth', ['client', 'server']);
api.use('http', ['server']);
api.use('underscore', 'server');
api.use('random', 'client');
api.use('service-configuration', ['client', 'server']);
api.use('templating', 'client');
api.add_files("lib/accounts_ok.js");
api.add_files('lib/ok_client.js', 'client');
api.add_files('lib/ok_server.js', 'server');
api.export('OK');
api.add_files(['lib/ok_configure.html', 'lib/ok_configure.js', 'lib/ok_styles.css'], 'client');
});
|
JavaScript
| 0.000336 |
@@ -106,17 +106,17 @@
n: %220.1.
-1
+2
%22,%0A g
|
9698eec91dae3cecb188257d28292c48b7bf4775
|
Update devel.js
|
gulp/devel.js
|
gulp/devel.js
|
'use strict';
var gulp = require('gulp'),
gulpLoadPlugins = require('gulp-load-plugins');
var del = require('del');
var plugins = gulpLoadPlugins();
var paths = gulp.paths;
//var defaultTasks = ['clean', 'jshint', 'less', 'csslint', 'develop', 'watch'];
var defaultTasks = ['clean', 'jshint', 'csslint','develop','watch'];
gulp.task('clean', function (cb) {
return del(['bower_components/build'], cb);
});
gulp.task('jshint', function () {
return gulp.src(paths.js)
.pipe(plugins.jshint())
.pipe(plugins.jshint.reporter('jshint-stylish'))
.pipe(plugins.jshint.reporter('fail'))
.pipe(count('jshint', 'files lint free'));
});
gulp.task('csslint', function () {
return gulp.src(paths.css)
.pipe(plugins.csslint('.csslintrc'))
.pipe(plugins.csslint.reporter())
.pipe(count('csslint', 'files lint free'));
});
gulp.task('develop', ['env:develop'], function () {
plugins.nodemon({
script: 'server.js',
ext: 'html js',
env: { 'NODE_ENV': 'development' } ,
ignore: ['./node_modules/**'],
nodeArgs: ['--debug']
});
});
gulp.task('watch', function () {
gulp.watch(paths.js, ['jshint']).on('change', plugins.livereload.changed);
gulp.watch(paths.html).on('change', plugins.livereload.changed);
gulp.watch(paths.css, ['csslint']).on('change', plugins.livereload.changed);
gulp.watch(paths.less, ['less']).on('change', plugins.livereload.changed);
plugins.livereload.listen({interval: 500});
});
gulp.task('default', defaultTasks);
function count(taskName, message) {
var fileCount = 0;
function countFiles(file) {
fileCount++; // jshint ignore:line
}
function endStream() {
gutil.log(gutil.colors.cyan(taskName + ': ') + fileCount + ' ' + message || 'files processed.');
this.emit('end'); // jshint ignore:line
}
return through(countFiles, endStream);
}
|
JavaScript
| 0 |
@@ -251,16 +251,56 @@
atch'%5D;%0A
+gulp.task('help', plugins.taskListing);%0A
var defa
|
4f679c891ce3233d798e507fcd1a80a13c0e4572
|
Set maxAge for session
|
config/env/all.js
|
config/env/all.js
|
'use strict';
var path = require('path'),
rootPath = path.normalize(__dirname + '/../..');
module.exports = {
root: rootPath,
port: process.env.PORT || 3000,
hostname: process.env.HOST || process.env.HOSTNAME,
db: process.env.MONGOHQ_URL,
templateEngine: 'swig',
// The secret should be set to a non-guessable string that
// is used to compute a session hash
sessionSecret: 'MEAN',
// The name of the MongoDB collection to store sessions in
sessionCollection: 'sessions',
// The session cookie settings
sessionCookie: {
path: '/',
httpOnly: true,
// If secure is set to true then it will cause the cookie to be set
// only when SSL-enabled (HTTPS) is used, and otherwise it won't
// set a cookie. 'true' is recommended yet it requires the above
// mentioned pre-requisite.
secure: false,
// Only set the maxAge to null if the cookie shouldn't be expired
// at all. The cookie will expunge when the browser is closed.
maxAge: null
},
// The session cookie name
sessionName: 'connect.sid'
};
|
JavaScript
| 0 |
@@ -989,20 +989,41 @@
maxAge:
-null
+1000 * 60 * 60 * 24 * 365
%0A %7D,%0A%0A
|
3d7ef67360ce4dbf60f1f133e03ca9c524ad1448
|
Update versions
|
package.js
|
package.js
|
// Meteor package definition.
Package.describe({
name: 'urbanetic:bismuth-utility',
version: '1.0.0',
summary: 'A set of utilities for working with GIS apps.',
git: 'https://github.com/urbanetic/bismuth-reports.git'
});
Npm.depends({
'request': '2.37.0',
'concat-stream': '1.4.7'
});
Package.onUse(function (api) {
api.versionsFrom('[email protected]');
api.use([
'[email protected]_1',
'underscore',
'aramk:[email protected]_1',
'aramk:[email protected]_1',
'[email protected]',
'urbanetic:[email protected]',
'urbanetic:[email protected]',
'urbanetic:[email protected]'
], ['client', 'server']);
// TODO(aramk) Weak dependency on aramk:[email protected], but causes cyclic dependencies.
api.use([
'urbanetic:[email protected]',
'urbanetic:[email protected]',
'peerlibrary:[email protected]_1'
], ['client', 'server'], {weak: true});
api.use([
'jquery',
'less',
'[email protected]'
], 'client');
// TODO(aramk) Perhaps expose the charts through the Vega object only to avoid cluttering the
// namespace.
api.export([
'Csv'
], 'client');
api.export([
'Request',
'S3Utils'
], 'server');
api.export([
'CounterLog',
'DocMap',
'EntityImporter',
'EntityUtils',
'ItemBuffer',
'TaskRunner',
'ProjectUtils'
], ['client', 'server']);
api.addFiles([
'src/Csv.coffee'
], 'client');
api.addFiles([
'src/Request.coffee',
'src/S3Utils.coffee'
], 'server');
api.addFiles([
'src/AccountsUtil.coffee',
'src/CounterLog.coffee',
'src/DocMap.coffee',
'src/EntityImporter.coffee',
'src/EntityUtils.coffee',
'src/ItemBuffer.coffee',
'src/TaskRunner.coffee',
'src/ProjectUtils.coffee'
], ['client', 'server']);
});
|
JavaScript
| 0.000001 |
@@ -91,25 +91,25 @@
rsion: '1.0.
-0
+1
',%0A summary
@@ -525,24 +525,26 @@
[email protected]
+_1
',%0A 'urba
|
a2d055b1bd9a71b18ba5be9a86d61c1a57d24632
|
Refactor getting model properties.
|
app/controllers/post.js
|
app/controllers/post.js
|
import Ember from 'ember';
export default Ember.ObjectController.extend({
netVotes: function() {
var model = this.get('model');
return model.get('upVotes') - model.get('downVotes');
}.property('downVotes', 'upVotes')
});
|
JavaScript
| 0 |
@@ -101,19 +101,14 @@
-var model =
+return
thi
@@ -123,34 +123,9 @@
odel
-');%0A return model.get('
+.
upVo
@@ -136,19 +136,24 @@
) -
-model
+this
.get('
+model.
down
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.