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 |
|---|---|---|---|---|---|---|---|
e11b39a248dd133f8ac08782935d0b522dd85fd8 | Fix rgb values | core/js/placeholder.js | core/js/placeholder.js | /**
* ownCloud
*
* @author John Molakvoæ
* @copyright 2016 John Molakvoæ <fremulon@protonmail.com>
* @author Morris Jobke
* @copyright 2013 Morris Jobke <morris.jobke@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU AFFERO GENERAL PUBLIC LICENSE
* License as published by the Free Software Foundation; either
* version 3 of the License, or any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU AFFERO GENERAL PUBLIC LICENSE for more details.
*
* You should have received a copy of the GNU Affero General Public
* License along with this library. If not, see <http://www.gnu.org/licenses/>.
*
*/
/*
* Adds a background color to the element called on and adds the first character
* of the passed in string. This string is also the seed for the generation of
* the background color.
*
* You have following HTML:
*
* <div id="albumart"></div>
*
* And call this from Javascript:
*
* $('#albumart').imageplaceholder('The Album Title');
*
* Which will result in:
*
* <div id="albumart" style="background-color: hsl(123, 90%, 65%); ... ">T</div>
*
* You may also call it like this, to have a different background, than the seed:
*
* $('#albumart').imageplaceholder('The Album Title', 'Album Title');
*
* Resulting in:
*
* <div id="albumart" style="background-color: hsl(123, 90%, 65%); ... ">A</div>
*
*/
/*
* Alternatively, you can use the prototype function to convert your string to hsl colors:
*
* "a6741a86aded5611a8e46ce16f2ad646".toHsl()
*
* Will return the hsl parameters within an array:
*
* [290, 60, 68]
*
*/
(function ($) {
String.prototype.toHsl = function() {
var hash = this.toLowerCase().replace(/[^0-9a-f]+/g, '');
// Already a md5 hash?
if( !hash.match(/^[0-9a-f]{32}$/g) ) {
hash = md5(hash);
}
function rgbToHsl(r, g, b) {
r /= 255, g /= 255, b /= 255;
var max = Math.max(r, g, b), min = Math.min(r, g, b);
var h, s, l = (max + min) / 2;
if(max === min) {
h = s = 0; // achromatic
} else {
var d = max - min;
s = l > 0.5 ? d / (2 - max - min) : d / (max + min);
switch(max) {
case r: h = (g - b) / d + (g < b ? 6 : 0); break;
case g: h = (b - r) / d + 2; break;
case b: h = (r - g) / d + 4; break;
}
h /= 6;
}
return [h, s, l];
}
// Init vars
var result = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
var rgb = [0, 0, 0];
var sat = 80;
var lum = 68;
var modulo = 16;
// Splitting evenly the string
for(var i in hash) {
result[i%modulo] = result[i%modulo] + parseInt(hash.charAt(i), 16).toString();
}
// Converting our data into a usable rgb format
// Start at 1 because 16%3=1 but 15%3=0 and makes the repartition even
for(var count=1;count<modulo;count++) {
rgb[count%3] += parseInt(result[count]);
}
var hsl = rgbToHsl(rgb[0], rgb[1], rgb[2]);
// Classic formulla to check the brigtness for our eye
// If too bright, lower the sat
var bright = Math.sqrt( 0.299 * Math.pow(rgb[0], 2) + 0.587 * Math.pow(rgb[1], 2) + 0.114 * Math.pow(rgb[2], 2) );
if (bright >= 200) {
sat = 60;
}
return [parseInt(hsl[0] * 360), sat, lum];
};
$.fn.imageplaceholder = function(seed, text, size) {
text = text || seed;
// Compute the hash
var hsl = seed.toHsl();
this.css('background-color', 'hsl('+hsl[0]+', '+hsl[1]+'%, '+hsl[2]+'%)');
// Placeholders are square
var height = this.height() || size || 32;
this.height(height);
this.width(height);
// CSS rules
this.css('color', '#fff');
this.css('font-weight', 'normal');
this.css('text-align', 'center');
// calculate the height
this.css('line-height', height + 'px');
this.css('font-size', (height * 0.55) + 'px');
if(seed !== null && seed.length) {
this.html(text[0].toUpperCase());
}
};
}(jQuery));
| JavaScript | 0 | @@ -2624,17 +2624,17 @@
r sat =
-8
+7
0;%0A%09%09var
@@ -3020,16 +3020,135 @@
%5D);%0A%09%09%7D%0A
+%0A%09%09// Reduce values bigger than rgb requirements%0A%09%09rgb%5B0%5D = rgb%5B0%5D%25255;%0A%09%09rgb%5B1%5D = rgb%5B1%5D%25255;%0A%09%09rgb%5B2%5D = rgb%5B2%5D%25255;%0A%0A
%09%09var hs
|
57da431eb5af025766f6935c8678be7828f4c4b1 | Update Comments, Add Score | javascript/script.js | javascript/script.js | var lastId;
function load(params) {
params = params || {};
if(textbox.value == ""){
var subreddit = "all";
}else{
var subreddit = textbox.value;
}
$.getJSON("http://www.reddit.com/r/"+subreddit+"/.json?limit=75", params, function (data) {
var children = data.data.children;
$.each(children, function (i, item) {
//LowerCase() so if the user puts in a link LiKE ThIS then the system will be able to handle it.
if (item.data.url.toLowerCase().indexOf(".jpeg") >= 0 || item.data.url.toLowerCase().indexOf(".jpg") >= 0 || item.data.url.toLowerCase().indexOf(".png") >= 0 && item.data.url.toLowerCase().indexOf(".gifv") < 0){
$('#images').append('<div class="item"><img src='+item.data.url+'></img><span class="caption">'+item.data.title+'</span></div>');
}
});
if (children && children.length > 0) {
//Last id = the last element of the children ids.
//Children in this case
lastId = children[children.length - 1].data.id;
} else { lastId = undefined; }
});
}
//Function to check scrolling:
$(window).scroll(function () {
//If the user gets 5px above the bottom of the page:
if ($(window).scrollTop() >= $(document).height() - $(window).height() - 5) {
if (lastId) {
//Load the next batch of posts:
load({ after: 't3_' + lastId });
}
}
});
//Call the load function
//This is the function that loads all the images into #images:
load();
function cleanImages(){
$("#images").html("");
}
function search(){
cleanImages();
load();
}
function wasEnter(key) {
if (key.keyCode == 13) {
cleanImages();
load();
return false;
}
} | JavaScript | 0 | @@ -57,16 +57,119 @@
%7C%7C %7B%7D;%0A
+ //If this gets called and textbox.value is empty, declare a var and set it equal to textbox.value:%0A
%09if(text
@@ -872,16 +872,46 @@
title+'%3C
+br%3EScore: '+item.data.score+'%3C
/span%3E%3C/
@@ -1561,16 +1561,110 @@
oad();%0A%0A
+//This function just removes everything in the div%0A//This pretty much will remove the images.%0A
function
@@ -1862,9 +1862,10 @@
;%0A %7D%0A
-
%7D
+%0A
|
57edfe0244b1908c03daf9d602fa5b5d797868ac | update pagelayout mutation to match new structure | graphql/resolvers/mutations/update-page-layout.js | graphql/resolvers/mutations/update-page-layout.js | const { insert, update } = require('../../../data/udify')
const ExposedError = require('../../../data/exposed-error')
const pageLayout = require('../queries/page-layout')
module.exports = async function updatePageLayout(obj, { pathname, input }, { log, state }) {
// Find all component ids
const [ results ] = await state.dbPool.execute('SELECT id FROM bm_web_page_layouts WHERE pathname = ? LIMIT 1',
[ pathname ])
if (!results.length) throw new ExposedError('Page Layout does not exist')
const conn = await state.dbPool.getConnection()
try {
await conn.beginTransaction()
const devices = Object.keys(input)
const components = []
devices.forEach(device => {
// @TODO Validate component is allowed in this pathname
input[device].forEach(({ id, component, x, y, w, textAlign, colour, meta }) => {
const data = {
pathname
, device
, component
, x
, y
, w
, textAlign: textAlign || null
, colour: colour || null
, meta: meta || null
}
if (id) data.id = id
components.push(data)
})
})
await Promise.each(components, (component) => {
if (component.id) {
return update(conn, 'bm_web_page_layouts', component, { id: component.id })
}
return insert(conn, 'bm_web_page_layouts', component)
})
await conn.commit()
} catch (e) {
log.error(e)
if (!conn.connection._fatalError) {
conn.rollback()
}
throw e
} finally {
conn.release()
}
return pageLayout(obj, { pathname }, { state })
}
| JavaScript | 0 | @@ -770,16 +770,27 @@
device%5D.
+components.
forEach(
@@ -1105,16 +1105,418 @@
d = id%0A%0A
+ components.push(data)%0A %7D)%0A%0A input%5Bdevice%5D.unusedComponents.forEach((%7B id, component, x, w, textAlign, colour, meta %7D) =%3E %7B%0A const data = %7B%0A pathname%0A , device%0A , component%0A , x%0A , y: -1%0A , w%0A , textAlign: textAlign %7C%7C null%0A , colour: colour %7C%7C null%0A , meta: meta %7C%7C null%0A %7D%0A%0A if (id) data.id = id%0A%0A
|
2c0be1958b78376f2f5ea38fd8615105407524c4 | Update library-list.js | src/library-list.js | src/library-list.js | window.jsLibs = [
{
url: 'https://code.jquery.com/jquery-3.2.1.min.js',
label: 'jQuery',
type: 'js'
},
{
url: 'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js',
label: 'Bootstrap 3',
type: 'js'
},
{
url:
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js',
label: 'Bootstrap 4',
type: 'js'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/js/foundation.min.js',
label: 'Foundation',
type: 'js'
},
{
url: 'https://semantic-ui.com/dist/semantic.min.js',
label: 'Semantic UI',
type: 'js'
},
{
url: 'https://ajax.googleapis.com/ajax/libs/angularjs/1.6.5/angular.min.js',
label: 'Angular',
type: 'js'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/react/16.2.0/umd/react.production.min.js',
label: 'React',
type: 'js'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.2.0/umd/react-dom.production.min.js',
label: 'React DOM',
type: 'js'
},
{
url: 'https://unpkg.com/vue',
label: 'Vue.js',
type: 'js'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/three.js/89/three.min.js',
label: 'Three.js',
type: 'js'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/d3/4.13.0/d3.min.js',
label: 'D3',
type: 'js'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js',
label: 'Underscore',
type: 'js'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/gsap/1.20.3/TweenMax.min.js',
label: 'Greensock TweenMax',
type: 'js'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/js/uikit.min.js',
label: 'UIkit 2',
type: 'js'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.40/js/uikit.min.js',
label: 'UIkit 3',
type: 'js'
}
];
window.cssLibs = [
{
url:
'https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css',
label: 'Bootstrap 3',
type: 'css'
},
{
url:
'https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css',
label: 'Bootstrap 4',
type: 'css'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/foundation/6.4.3/css/foundation.min.css',
label: 'Foundation',
type: 'css'
},
{
url: 'https://semantic-ui.com/dist/semantic.min.css',
label: 'Semantic UI',
type: 'css'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/bulma/0.6.2/css/bulma.min.css',
label: 'Bulma',
type: 'css'
},
{
url: 'https://cdnjs.cloudflare.com/ajax/libs/hint.css/2.5.0/hint.min.css',
label: 'Hint.css',
type: 'css'
},
{
url: 'https://cdn.jsdelivr.net/npm/tailwindcss/dist/tailwind.min.css',
label: 'Tailwind.css',
type: 'css'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/uikit/2.27.4/css/uikit.min.css',
label: 'UIkit 2',
type: 'css'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/uikit/3.0.0-beta.40/css/uikit.min.css',
label: 'UIkit 3',
type: 'css'
},
{
url:
'https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css',
label: 'Animate.css',
type: 'css'
},
{
url:
'https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css',
label: 'FontAwesome 4',
type: 'css'
},
{
url:
'https://use.fontawesome.com/releases/v5.0.7/css/all.css',
label: 'FontAwesome 5',
type: 'css'
}
];
| JavaScript | 0.000002 | @@ -3220,17 +3220,17 @@
es/v5.0.
-7
+8
/css/all
|
ae7a5f140178d7d7ff81781e8ef82a52a2159869 | Update build configuration. | assets/js/app.build.js | assets/js/app.build.js | ({
appDir: "../",
baseUrl: "js",
dir: "../../build/public",
modules: [
{
name: "main"
}
],
paths: {
'jquery' : "jquery-1.7.1.min",
'jquery-ui' : "jquery-ui-1.8.16.custom.min",
'mustache' : "require-mustache"
}
})
| JavaScript | 0 | @@ -161,16 +161,24 @@
'jquery'
+
@@ -218,16 +218,24 @@
uery-ui'
+
: %22
@@ -260,24 +260,83 @@
ustom.min%22,%0A
+ 'jquery-temporaryClass' : %22jquery.temporaryClass%22,%0A
'mus
@@ -341,16 +341,24 @@
ustache'
+
:
@@ -376,16 +376,321 @@
stache%22%0A
+ %7D,%0A shim: %7B%0A 'jquery' : %7B%0A exports: %22jQuery%22,%0A %7D,%0A 'jquery-ui' : %7B%0A exports: %22jQuery.ui%22,%0A deps: %5B%22jquery%22%5D,%0A %7D,%0A 'jquery-temporaryClass' : %7B%0A exports: %22jQuery.fn.temporaryClass%22,%0A deps: %5B%22jquery%22%5D%0A %7D%0A
%7D%0A%7D)
|
fb1d3af48385afab7cdb4b3b40a6c73ef1ca2ebe | remove dead code from location picker | app/hotels/src/allHotels/searchForm/locationPicker/LocationPickerScreen.js | app/hotels/src/allHotels/searchForm/locationPicker/LocationPickerScreen.js | // @flow
import * as React from 'react';
import { View } from 'react-native';
import {
Text,
Touchable,
StyleSheet,
Color,
TextInput,
} from '@kiwicom/react-native-app-shared';
import { type NavigationType } from '@kiwicom/react-native-app-navigation';
import { PublicApiRenderer } from '@kiwicom/react-native-app-relay';
import { connect } from '@kiwicom/react-native-app-redux';
import Translation from '@kiwicom/react-native-app-translations';
import { graphql } from 'react-relay';
import idx from 'idx';
import type { LocationPickerScreen_cities_QueryResponse as LocationSuggestions } from './__generated__/LocationPickerScreen_cities_Query.graphql';
import SuggestionList from './SuggestionList';
type Props = {|
navigation: NavigationType,
onCitySelected: (cityId: string, cityName: string) => void,
|};
type NavigationProps = {|
cityId: string,
cityName: string,
navigation: NavigationType,
|};
type State = {|
search: string,
|};
const styles = StyleSheet.create({
cancelButton: {
padding: 8,
},
headerButtonText: {
fontSize: 17,
color: Color.white,
lineHeight: 20,
ios: {
fontFamily: 'SFProText-Regular',
},
},
confirmButtonText: {
ios: {
fontFamily: 'SFProText-Semibold',
},
android: {
fontWeight: '600',
},
},
confirmButton: {
padding: 8,
paddingRight: 10,
},
disabled: {
opacity: 0.4,
},
container: {
flex: 1,
},
textInputContainer: {
backgroundColor: Color.white,
padding: 10,
},
input: {
borderRadius: 2,
borderWidth: 1,
borderColor: '#c0c8d1',
paddingLeft: 11,
paddingBottom: 10,
paddingTop: 13,
},
});
export class LocationPicker extends React.Component<Props, State> {
state = {
search: '',
};
static navigationOptions = ({ navigation }: NavigationProps) => {
function goBack() {
navigation.goBack();
}
function headerLeft() {
return (
<Touchable
borderlessRipple
onPress={goBack}
style={styles.cancelButton}
>
<Text style={[styles.headerButtonText, styles.confirmButtonText]}>
<Translation id="HotelsSearch.LocationPicker.Cancel" />
</Text>
</Touchable>
);
}
return {
headerLeft: headerLeft(),
title: 'Where',
};
};
componentDidMount = () => {
const location =
idx(this.props.navigation, _ => _.state.params.location) || '';
this.setState({ search: location });
};
onTextChange = (search: string) => {
this.setState({ search });
};
onCitySelected = (cityId: string, cityName: string) => {
this.props.onCitySelected(cityId, cityName);
this.props.navigation.goBack();
};
renderSuggestions = (rendererProps: LocationSuggestions) => {
return (
<SuggestionList
data={rendererProps}
onCitySelected={this.onCitySelected}
search={this.state.search}
/>
);
};
render = () => {
return (
<View style={styles.container}>
<View style={styles.textInputContainer}>
<TextInput
value={this.state.search}
onChangeText={this.onTextChange}
placeholder="Where"
style={styles.input}
placeholderTextColor={Color.textLight}
autoFocus
/>
</View>
{!this.state.cityId && (
<PublicApiRenderer
query={graphql`
query LocationPickerScreen_cities_Query($prefix: String!) {
...SuggestionList_data @arguments(prefix: $prefix)
}
`}
render={this.renderSuggestions}
variables={{ prefix: this.state.search }}
/>
)}
</View>
);
};
}
const action = dispatch => ({
onCitySelected: (cityId: string, cityName: string) =>
dispatch({
type: 'setLocationAndCityId',
cityId,
location: cityName,
}),
});
export default connect(null, action)(LocationPicker);
| JavaScript | 0 | @@ -3369,43 +3369,8 @@
ew%3E%0A
- %7B!this.state.cityId && (%0A
@@ -3398,26 +3398,24 @@
r%0A
-
query=%7Bgraph
@@ -3418,18 +3418,16 @@
raphql%60%0A
-
@@ -3504,18 +3504,16 @@
-
...Sugge
@@ -3571,14 +3571,10 @@
- %7D%0A
+%7D%0A
@@ -3582,18 +3582,16 @@
%60%7D%0A
-
@@ -3634,18 +3634,16 @@
-
variable
@@ -3688,23 +3688,10 @@
- /%3E%0A )%7D
+/%3E
%0A
|
7f260e1185284f6b1fea35bfacbc06f705ea2f06 | test case for lifecycle hook events | test/unit/features/options/lifecycle.spec.js | test/unit/features/options/lifecycle.spec.js | import Vue from 'vue'
describe('Options lifecyce hooks', () => {
let spy
beforeEach(() => {
spy = jasmine.createSpy('hook')
})
describe('beforeCreate', () => {
it('should allow modifying options', () => {
const vm = new Vue({
data: {
a: 1
},
beforeCreate () {
spy()
expect(this.a).toBeUndefined()
this.$options.computed = {
b () {
return this.a + 1
}
}
}
})
expect(spy).toHaveBeenCalled()
expect(vm.b).toBe(2)
})
})
describe('created', () => {
it('should have completed observation', () => {
new Vue({
data: {
a: 1
},
created () {
expect(this.a).toBe(1)
spy()
}
})
expect(spy).toHaveBeenCalled()
})
})
describe('beforeMount', () => {
it('should not have mounted', () => {
const vm = new Vue({
render () {},
beforeMount () {
spy()
expect(this._isMounted).toBe(false)
expect(this.$el).toBeUndefined() // due to empty mount
expect(this._vnode).toBeNull()
expect(this._watcher).toBeNull()
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
})
describe('mounted', () => {
it('should have mounted', () => {
const vm = new Vue({
template: '<div></div>',
mounted () {
spy()
expect(this._isMounted).toBe(true)
expect(this.$el.tagName).toBe('DIV')
expect(this._vnode.tag).toBe('div')
}
})
expect(spy).not.toHaveBeenCalled()
vm.$mount()
expect(spy).toHaveBeenCalled()
})
// #3898
it('should call for manually mounted instance with parent', () => {
const parent = new Vue()
expect(spy).not.toHaveBeenCalled()
new Vue({
parent,
template: '<div></div>',
mounted () {
spy()
}
}).$mount()
expect(spy).toHaveBeenCalled()
})
it('should mount child parent in correct order', () => {
const calls = []
new Vue({
template: '<div><test></test><div>',
mounted () {
calls.push('parent')
},
components: {
test: {
template: '<nested></nested>',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('child')
},
components: {
nested: {
template: '<div></div>',
mounted () {
expect(this.$el.parentNode).toBeTruthy()
calls.push('nested')
}
}
}
}
}
}).$mount()
expect(calls).toEqual(['nested', 'child', 'parent'])
})
})
describe('beforeUpdate', () => {
it('should be called before update', done => {
const vm = new Vue({
template: '<div>{{ msg }}</div>',
data: { msg: 'foo' },
beforeUpdate () {
spy()
expect(this.$el.textContent).toBe('foo')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
})
describe('updated', () => {
it('should be called after update', done => {
const vm = new Vue({
template: '<div>{{ msg }}</div>',
data: { msg: 'foo' },
updated () {
spy()
expect(this.$el.textContent).toBe('bar')
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.msg = 'bar'
expect(spy).not.toHaveBeenCalled() // should be async
waitForUpdate(() => {
expect(spy).toHaveBeenCalled()
}).then(done)
})
})
describe('beforeDestroy', () => {
it('should be called before destroy', () => {
const vm = new Vue({
render () {},
beforeDestroy () {
spy()
expect(this._isBeingDestroyed).toBe(false)
expect(this._isDestroyed).toBe(false)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
describe('destroyed', () => {
it('should be called after destroy', () => {
const vm = new Vue({
render () {},
destroyed () {
spy()
expect(this._isBeingDestroyed).toBe(true)
expect(this._isDestroyed).toBe(true)
}
}).$mount()
expect(spy).not.toHaveBeenCalled()
vm.$destroy()
vm.$destroy()
expect(spy).toHaveBeenCalled()
expect(spy.calls.count()).toBe(1)
})
})
})
| JavaScript | 0 | @@ -4890,12 +4890,683 @@
%7D)%0A %7D)
+%0A%0A it('should emit hook events', () =%3E %7B%0A const created = jasmine.createSpy()%0A const mounted = jasmine.createSpy()%0A const destroyed = jasmine.createSpy()%0A const vm = new Vue(%7B%0A render () %7B%7D,%0A beforeCreate () %7B%0A this.$on('hook:created', created)%0A this.$on('hook:mounted', mounted)%0A this.$on('hook:destroyed', destroyed)%0A %7D%0A %7D)%0A%0A expect(created).toHaveBeenCalled()%0A expect(mounted).not.toHaveBeenCalled()%0A expect(destroyed).not.toHaveBeenCalled()%0A%0A vm.$mount()%0A expect(mounted).toHaveBeenCalled()%0A expect(destroyed).not.toHaveBeenCalled()%0A%0A vm.$destroy()%0A expect(destroyed).toHaveBeenCalled()%0A %7D)
%0A%7D)%0A
|
c10688cf8b2fd84c08fc0a29c077fe233481fe3f | Fix version | app/javascript/components/widgets/climate/emissions-deforestation/index.js | app/javascript/components/widgets/climate/emissions-deforestation/index.js | import { fetchAnalysisEndpoint } from 'services/analysis';
import { getLoss } from 'services/analysis-cached';
import biomassLossIsos from 'data/biomass-isos.json';
import {
POLITICAL_BOUNDARIES_DATASET,
BIOMASS_LOSS_DATASET
} from 'data/layers-datasets';
import {
DISPUTED_POLITICAL_BOUNDARIES,
POLITICAL_BOUNDARIES,
BIOMASS_LOSS
} from 'data/layers';
import { getYearsRange } from 'components/widgets/utils/data';
import { shouldQueryPrecomputedTables } from 'components/widgets/utils/helpers';
import getWidgetProps from './selectors';
const getDataFromAPI = params =>
fetchAnalysisEndpoint({
...params,
name: 'Umd',
params,
slug: ['wdpa', 'use', 'geostore'].includes(params.type)
? 'biomass-loss'
: 'umd-loss-gain',
version: ['wdpa', 'use', 'geostore'].includes(params.type) ? 'v1' : 'v3',
aggregate: false
}).then(response => {
const { attributes: data } =
(response && response.data && response.data.data) || {};
let loss = [];
if (['wdpa', 'use', 'geostore'].includes(params.type)) {
const biomassData = data.biomassLossByYear;
const emissionsData = data.co2LossByYear;
loss = Object.keys(biomassData).map(l => ({
year: parseInt(l, 10),
emissions: emissionsData[l],
biomassLoss: biomassData[l]
}));
} else {
loss = data.years;
}
const { startYear, endYear, range } = getYearsRange(loss);
return {
loss,
settings: {
startYear,
endYear
},
options: {
years: range
}
};
});
export default {
widget: 'emissionsDeforestation',
title: 'Emissions from biomass loss in {location}',
categories: ['climate'],
types: ['country', 'geostore', 'use', 'wdpa'],
admins: ['adm0', 'adm1', 'adm2'],
chartType: 'composedChart',
settingsConfig: [
{
key: 'unit',
label: 'unit',
type: 'switch',
whitelist: ['co2LossByYear', 'biomassLoss']
},
{
key: 'years',
label: 'years',
endKey: 'endYear',
startKey: 'startYear',
type: 'range-select',
border: true
},
{
key: 'threshold',
label: 'canopy density',
type: 'mini-select',
metaKey: 'widget_canopy_density'
}
],
datasets: [
{
dataset: POLITICAL_BOUNDARIES_DATASET,
layers: [DISPUTED_POLITICAL_BOUNDARIES, POLITICAL_BOUNDARIES],
boundary: true
},
// biomass loss
{
dataset: BIOMASS_LOSS_DATASET,
layers: [BIOMASS_LOSS]
}
],
pendingKeys: ['threshold', 'unit'],
refetchKeys: ['threshold'],
visible: ['dashboard', 'analysis'],
metaKey: 'widget_carbon_emissions_tree_cover_loss',
dataType: 'loss',
colors: 'climate',
sortOrder: {
climate: 2
},
sentences:
'Between {startYear} and {endYear}, a total of {value} of {type} was released into the atmosphere as a result of tree cover loss in {location}. This is equivalent to {annualAvg} per year.',
settings: {
unit: 'co2LossByYear',
threshold: 30,
startYear: 2001,
endYear: 2018
},
whitelists: {
adm0: biomassLossIsos
},
getData: params => {
if (shouldQueryPrecomputedTables(params)) {
return getLoss(params).then(response => {
const loss = response.data.data;
const { startYear, endYear, range } = getYearsRange(loss);
return {
loss,
settings: {
startYear,
endYear
},
options: {
years: range
}
};
});
}
return getDataFromAPI(params);
},
getDataURL: params => [getLoss({ ...params, download: true })],
getWidgetProps
};
| JavaScript | 0.000001 | @@ -825,17 +825,17 @@
pe) ? 'v
-1
+2
' : 'v3'
|
a43fc19848313a2aaf4537a34d90eb9797492c28 | Fix check all issue of fixed table head | admin/views/assets/javascripts/qor/qor-fixer.js | admin/views/assets/javascripts/qor/qor-fixer.js | (function (factory) {
if (typeof define === 'function' && define.amd) {
// AMD. Register as anonymous module.
define(['jquery'], factory);
} else if (typeof exports === 'object') {
// Node / CommonJS
factory(require('jquery'));
} else {
// Browser globals.
factory(jQuery);
}
})(function ($) {
'use strict';
var NAMESPACE = 'qor.fixer';
var EVENT_ENABLE = 'enable.' + NAMESPACE;
var EVENT_DISABLE = 'disable.' + NAMESPACE;
var EVENT_RESIZE = 'resize.' + NAMESPACE;
var EVENT_SCROLL = 'scroll.' + NAMESPACE;
function QorFixer(element, options) {
this.$element = $(element);
this.options = $.extend({}, QorFixer.DEFAULTS, $.isPlainObject(options) && options);
this.$clone = null;
this.init();
}
QorFixer.prototype = {
constructor: QorFixer,
init: function () {
var options = this.options;
var $this = this.$element;
if ($this.is(':hidden') || $this.find('tbody > tr:visible').length <= 1) {
return;
}
this.$thead = $this.find('thead:first');
this.$tbody = $this.find('tbody:first');
this.$header = $(options.header);
this.$content = $(options.content);
this.resize();
this.bind();
},
bind: function () {
this.$content.
on(EVENT_SCROLL, $.proxy(this.toggle, this)).
on(EVENT_RESIZE, $.proxy(this.resize, this));
},
unbind: function () {
this.$content.
off(EVENT_SCROLL, this.toggle).
off(EVENT_RESIZE, this.resize);
},
build: function () {
var $this = this.$element;
var $thead = this.$thead;
var $clone = this.$clone;
var $items = $thead.find('> tr').children();
if (!$clone) {
this.$clone = $clone = $thead.clone().prependTo($this);
}
this.offsetTop = $this.offset().top - this.$header.outerHeight();
$clone.
addClass('is-fixed').
find('> tr').
children().
each(function (i) {
$(this).width($items.eq(i).width());
});
},
unbuild: function () {
this.$clone.remove();
},
toggle: function () {
var $this = this.$element;
var $clone = this.$clone;
var scrollTop = this.$content.scrollTop();
var min = this.offsetTop;
var max = scrollTop + $this.outerHeight();
if (scrollTop > min && scrollTop < max) {
$clone.css('top', (scrollTop - min)).show();
} else {
$clone.hide();
}
},
resize: function () {
this.build();
this.toggle();
},
destroy: function () {
this.unbind();
this.unbuild();
this.$element.removeData(NAMESPACE);
},
};
QorFixer.DEFAULTS = {
header: false,
content: false,
};
QorFixer.plugin = function (options) {
return this.each(function () {
var $this = $(this);
var data = $this.data(NAMESPACE);
var fn;
if (!data) {
$this.data(NAMESPACE, (data = new QorFixer(this, options)));
}
if (typeof options === 'string' && $.isFunction(fn = data[options])) {
fn.call(data);
}
});
};
$(function () {
var selector = '.qor-table';
var options = {
header: '.mdl-layout__header',
content: '.mdl-layout__content',
};
$(document).
on(EVENT_DISABLE, function (e) {
QorFixer.plugin.call($(selector, e.target), 'destroy');
}).
on(EVENT_ENABLE, function (e) {
QorFixer.plugin.call($(selector, e.target), options);
}).
triggerHandler(EVENT_ENABLE);
});
return QorFixer;
});
| JavaScript | 0 | @@ -450,32 +450,74 @@
.' + NAMESPACE;%0A
+ var EVENT_CLICK = 'click.' + NAMESPACE;%0A
var EVENT_RESI
@@ -536,32 +536,32 @@
.' + NAMESPACE;%0A
-
var EVENT_SCRO
@@ -1288,32 +1288,97 @@
: function () %7B%0A
+ this.$element.on(EVENT_CLICK, $.proxy(this.check, this));%0A%0A
this.$cont
@@ -1516,32 +1516,83 @@
: function () %7B%0A
+ this.$element.off(EVENT_CLICK, this.check);%0A%0A
this.$cont
@@ -2239,32 +2239,32 @@
: function () %7B%0A
-
this.$clon
@@ -2279,24 +2279,429 @@
();%0A %7D,%0A%0A
+ check: function (e) %7B%0A var $target = $(e.target);%0A var checked;%0A%0A if ($target.is('.qor-action__check-all')) %7B%0A checked = $target.prop('checked');%0A%0A $target.%0A closest('thead').%0A siblings('thead').%0A find('.qor-action__check-all').prop('checked', checked).%0A closest('.mdl-checkbox').toggleClass('is-checked', checked);%0A %7D%0A %7D,%0A%0A
toggle:
|
d3c2de67d6c6ce71272849062c779c0c143b2238 | Fix comment | src/inverted-index.js | src/inverted-index.js | /**
* This is a class that defines the methods for an object that
* creates the inverted index
*/
class InvertedIndex {
/**
* Constructor for the Inverted Index class
*/
constructor() {
// Object to store all indexes created
this.indexes = {};
}
/**
* Removes non alphanumeric chracters from a string and tokenizes it
*
* @param {String} text - Words to get tokens from
* @return {Array} An array of sorted strings without non-alphanumeric symbols
*/
static clean(text) {
return text.replace(/[^a-z0-9\s]+/gi, '')
.replace(/\s{2,}/g, ' ')
.toLowerCase()
.split(' ')
.sort();
}
/**
* Removes duplicate strings from an array of strings
*
* @param {Array} words - An array of strings
* @return {Array} uniqueWords - An array non-duplicate strings
*/
static removeDuplicates(words) {
return words.filter((item, index) => words.indexOf(item) === index);
}
/**
* Sorts the keys of an Object
*
* @param {Object} index - Efizi function to sort an Object
* @return {Object} sortedObject - Object with keys sorted
*/
static sortObjectKeys(index) {
const sortedKeys = Object.keys(index).sort();
// Object that will contain the sorted object
const sortedObject = {};
sortedKeys.forEach((key) => {
sortedObject[key] = index[key];
});
return (sortedObject);
}
/**
* Checks if a file is empty or invalid
*
* @param {Object} file - JSON object from which index is to be created
* @returns{string} A string describing the file's status
*/
static validateFile(file) {
if (file.length === 0) {
return 'Empty file';
}
// get keys of all objects in JSON file
let keys = [];
file.forEach((doc) => {
keys.push(Object.keys(doc));
});
// 'flatten' it to an array`
keys = keys.toString().split(',');
if (keys.includes('title') || keys.includes('text')) {
return 'Valid file';
}
return 'Invalid file';
}
/**
* Creates the Inverted Index data structure
*
* @param{String} filename - Name of the file for which index is to be created
* @param{Object} fileToIndex - JSON file
* @returns{undefined} - This function does not return anything it just
* updates the this.indexes Object
*/
createIndex(filename, fileToIndex) {
// This object stores the index of the current document
let index = {};
// Ensure JSON file is not empty or invalid
if (InvertedIndex.validateFile(fileToIndex) === 'Empty file') {
this.indexes[filename] = ['JSON file is empty'];
} else if (InvertedIndex.validateFile(fileToIndex) === 'Invalid file') {
this.indexes[filename] = ['JSON file is invalid'];
} else {
fileToIndex.forEach((doc, docIndex) => {
const cleanWords = InvertedIndex.clean(`${doc.title} ${doc.text}`);
const uniqueWords = InvertedIndex.removeDuplicates(cleanWords);
uniqueWords.forEach((word) => {
/**
* If word does not exist as a key in the index object, first create
* an empty array value for it
*/
if (!Object.keys(index).includes(word)) {
index[word] = [];
}
index[word].push(docIndex + 1);
});
});
// Sort the index keys
index = InvertedIndex.sortObjectKeys(index);
/**
* Simply update the this.indexes object
* Don't return it yet
*/
this.indexes[filename] = index;
}
}
/**
* Returns all indexes or an index for a specified file
*
* @param{String} filename - Optional parameter specifying a file whose index is required
* @returns{Object} - Object that contains all indexes or a required index
*/
getIndex(filename) {
return (filename === undefined) ? this.indexes : this.indexes[filename];
}
/**
* Checks that index for file exists before search
*
* @param{String} file - Name of file which we want to search
* @returns{Boolean} - A boolean indicating whether or not index for that file exists
*/
indexExists(file) {
return (Object.keys(this.getIndex()).includes(file));
}
/**
* Searches all the indexes created or a particular index
*
* @param{Array} args - This is an array that can contain an infinite
* number of arguments. The first element of this array maybe a filename,
* if it is not all files are searched
* @returns{Object} - The results of the search
*/
searchIndex(...args) {
// This regex allows us to split on both whitespace and commas
const allArgs = args.toString().toLowerCase().split(/[\s,]+/);
const searchResults = {};
let filesToSearch;
/**
* Query is an array that contains the terms we want to search for
* It is simply a copy of the allArgs array
*/
const query = allArgs.slice();
if (allArgs[0].slice(-5) === '.json') {
/**
* Assign filesToSearch to the first element of allArgs if it is a
* filename
*/
filesToSearch = Array(allArgs[0]);
// Remove the filename because we don't want to search for it
query.shift();
// check that index for the file exists before search
if (!this.indexExists(allArgs[0])) {
return ('Index for file does not exist');
}
} else {
filesToSearch = Object.keys(this.getIndex());
}
filesToSearch.forEach((file) => {
searchResults[file] = {};
query.forEach((term) => {
if (term in this.getIndex(file)) {
searchResults[file][term] = this.getIndex(file)[term];
} else {
searchResults[file][term] = 'Word not found!';
}
});
});
return (allArgs[0].slice(-5) === '.json') ? searchResults[allArgs[0]] : searchResults;
}
}
| JavaScript | 0 | @@ -4941,29 +4941,8 @@
ign
-filesToSearch to the
firs
@@ -4962,16 +4962,52 @@
allArgs
+array to the filesToSearch variable
if it is
|
3ea729393dfada994ed08ee7430fd5b25d208a4c | Add isNewUpdate function | akvo/rsr/static/scripts-src/my-results/utils.js | akvo/rsr/static/scripts-src/my-results/utils.js | /*
Akvo RSR is covered by the GNU Affero General Public License.
See more details in the license.txt file located at the root folder of the
Akvo RSR module. For additional details on the GNU license please see
< http://www.gnu.org/licenses/agpl.html >.
*/
import fetch from 'isomorphic-fetch';
let months;
export function displayDate(dateString) {
// Display a dateString like "25 Jan 2016"
if (!months) {
months = months = JSON.parse(document.getElementById('i18nMonths').innerHTML);
}
if (dateString) {
const locale = "en-gb";
const date = new Date(dateString.split(".")[0].replace("/", /-/g));
const day = date.getUTCDate();
const month = months[date.getUTCMonth()];
const year = date.getUTCFullYear();
return day + " " + month + " " + year;
}
return "Unknown date";
}
export function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie !== '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = cookies[i].trim();
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
export function APICall(method, url, data, callback, retries) {
function modify(method, url, data){
return fetch(url, {
credentials: 'same-origin',
method: method,
headers: {
'Content-Type': 'application/json',
"X-CSRFToken": getCookie('csrftoken')
},
body: JSON.stringify(data),
})
}
let handler;
switch (method) {
case "GET":
handler = () => fetch(url, {
credentials: 'same-origin',
method: 'GET',
headers: {'Content-Type': 'application/json'},
});
break;
case "POST":
handler = () => modify('POST', url, data);
break;
case "PUT":
handler = () => modify('PUT', url, data);
break;
case "PATCH":
handler = () => modify('PATCH', url, data);
break;
case "DELETE":
handler = () => fetch(url, {
credentials: 'same-origin',
method: 'DELETE',
headers: {
'Content-Type': 'application/json',
"X-CSRFToken": getCookie('csrftoken')
}
});
break;
}
handler()
//TODO: error handling? See https://www.tjvantoll.com/2015/09/13/fetch-and-errors/
.then(function(response) {
if (response.status != 204)
return response.json();
else
return response;
}).then(callback);
}
// Object holds callback URL functions as values, most of them called with an id parameter
// Usage: endpoints.result(17) -> "http://rsr.akvo.org/rest/v1/result/17/?format=json"
export const endpoints = {
"result": (id) => `/rest/v1/result/${id}/?format=json`,
"results": (id) => `/rest/v1/result/?format=json&project=${id}`,
"indicators": (id) => `/rest/v1/indicator/?format=json&result__project=${id}`,
"periods": (id) => `/rest/v1/indicator_period/?format=json&indicator__result__project=${id}`,
"updates": (id) => `/rest/v1/indicator_period_data/?format=json&period__indicator__result__project=${id}`,
"comments": (id) => `/rest/v1/indicator_period_data_comment/?format=json&data__period__indicator__result__project=${id}`,
"period": (id) => `/rest/v1/indicator_period/${id}/?format=json`,
"update_and_comments": (id) => `/rest/v1/indicator_period_data_framework/${id}/?format=json`,
"updates_and_comments": () => `/rest/v1/indicator_period_data_framework/?format=json`,
"user": (id) => `/rest/v1/user/${id}/?format=json`,
"partnerships": (id) => `/rest/v1/partnership/?format=json&project=${id}`,
"file_upload": (id) => `/rest/v1/indicator_period_data/${id}/upload_file/?format=json`
};
export function displayNumber(numberString) {
// Add commas to numbers of 1000 or higher.
if (numberString !== undefined && numberString !== null) {
var locale = "en-gb";
var float = parseFloat(numberString);
if (!isNaN(float)) {
return float.toLocaleString(locale);
}
}
return numberString;
}
let strings;
// Translation a la python. Let's hope we never need lodash...
export function _(s) {
if (!strings) {
strings = JSON.parse(document.getElementById('translation-texts').innerHTML);
}
return strings[s];
}
| JavaScript | 0 | @@ -445,25 +445,16 @@
months =
- months =
JSON.pa
@@ -4591,28 +4591,18 @@
return
-numberString
+''
;%0A%7D%0A%0Alet
@@ -4831,12 +4831,107 @@
rings%5Bs%5D;%0A%7D%0A
+%0Aexport const isNewUpdate = (update) =%3E %7Breturn update.id.toString().substr(0, 4) === 'new-'%7D;%0A
|
6cc03b97dc5bdb53dcdd2e0f486ce6a726d10171 | Update case progress to Array in test | test/unit/services/test-get-case-progress.js | test/unit/services/test-get-case-progress.js | const expect = require('chai').expect
const sinon = require('sinon')
require('sinon-bluebird')
const proxyquire = require('proxyquire')
const breadcrumbHelper = require('../../helpers/breadcrumb-helper')
const CASE_PROGRESS = [
{
communityLast16Weeks: 1,
licenseLast16Weeks: 2,
totalCases: 3,
warrantsTotal: 4,
unpaidWorkTotal: 5,
overdueTerminationsTotal: 6
}
]
var id = 1
var organisationalUnit = 'offender-manager'
var breadcrumbs = breadcrumbHelper.OFFENDER_MANAGER_BREADCRUMBS
var expectedTitle = breadcrumbs[0].title
var expectedSubNav = [{id: '1', link: 'link'}]
var getCaseProgress
var getCaseProgressRow
var getBreadcrumbs
var getSubNav
before(function () {
getCaseProgressRow = sinon.stub()
getBreadcrumbs = sinon.stub().returns(breadcrumbs)
getSubNav = sinon.stub().returns(expectedSubNav)
getCaseProgress =
proxyquire('../../../app/services/get-case-progress',
{'./data/get-individual-caseload-progress': getCaseProgressRow,
'./get-breadcrumbs': getBreadcrumbs,
'./get-sub-nav': getSubNav})
getCaseProgressRow.resolves(CASE_PROGRESS)
})
describe('services/get-case-progress', function () {
it('should return a result object with a case progress row and title for offender manager', function () {
getCaseProgress(id, organisationalUnit).then(function (result) {
expect(result.caseProgress).to.be.an('object')
expect(result.title).to.equal(expectedTitle)
})
})
it('should return a result object with expected breadcrumbs for offender manager', function () {
getCaseProgress(id, organisationalUnit).then(function (result) {
expect(result.breadcrumbs).to.be.an('Array')
expect(result.breadcrumbs).to.eql(breadcrumbs)
})
})
})
| JavaScript | 0 | @@ -1394,22 +1394,21 @@
.be.an('
-object
+Array
')%0A
|
6b8df980b2395e258924fd333a746c1bfba63bdd | Add input focus events to GA | assets/js/ga-events.js | assets/js/ga-events.js | $(document).ready(function() {
// Profile header links (except scrolly click events for center three links...already included in profile.js)
$('.navbar [data-ga]').on('click', function() {
ga('send', 'event', {
'eventCategory': 'Profile Events',
'eventAction': 'Profile Header Click',
'eventLabel': $(this).data('ga'),
});
});
// Clicks to foundation websites
$('.js-ga-website-click').on('click', function() {
ga('send', 'event', {
'eventCategory': 'Profile Events',
'eventAction': 'Profile Org Website Click',
'eventLabel': $(this).data('ga'),
});
});
// Table sort
$('#grantsTable th').on('click', function() {
ga('send', 'event', {
'eventCategory': 'Profile Events',
'eventAction': 'Profile Table Sort Click',
'eventLabel': $(this).find('span').text(),
});
});
// Tax filings
$('#filings ul li a').on('click', function() {
ga('send', 'event', {
'eventCategory': 'Profile Events',
'eventAction': 'Profile Tax Filings Click',
'eventLabel': $(this).data('ga'),
});
});
// Footer links
$('footer a, .footer-terms a').on('click', function() {
ga('send', 'event', {
'eventCategory': 'Profile Events',
'eventAction': 'Profile Footer Click',
'eventLabel': $(this).text(),
});
});
});
| JavaScript | 0 | @@ -853,24 +853,524 @@
%7D);%0A %7D);%0A%0A
+ // Algolia grants search box%0A $('#search-input').on('focus', function() %7B%0A ga('send', 'event', %7B%0A 'eventCategory': 'Profile Events',%0A 'eventAction': 'Profile Search Focus',%0A 'eventLabel': 'Grants search',%0A %7D);%0A %7D);%0A%0A // Algolia Autocomplete search box%0A $('#autocomplete-input').on('focus', function() %7B%0A ga('send', 'event', %7B%0A 'eventCategory': 'Profile Events',%0A 'eventAction': 'Profile Search Focus',%0A 'eventLabel': 'Autocomplete search',%0A %7D);%0A %7D);%0A%0A
// Tax fil
|
da57ae740d30b1c8d1616028139eb96e82157170 | Add `ast: true` to transform options for jest | jest/preprocessor.js | jest/preprocessor.js | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
/* eslint-env node */
'use strict';
const {transformSync: babelTransformSync} = require('@babel/core');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const babelRegisterOnly = require('metro/src/babelRegisterOnly');
/* $FlowFixMe(>=0.54.0 site=react_native_oss) This comment suppresses an error
* found when Flow v0.54 was deployed. To see the error delete this comment and
* run Flow. */
const createCacheKeyFunction = require('fbjs-scripts/jest/createCacheKeyFunction');
const generate = require('@babel/generator').default;
const nodeFiles = RegExp([
'/local-cli/',
'/metro(?:-[^\/]*)?/', // metro, metro-core, metro-source-map, metro-etc
].join('|'));
const nodeOptions = babelRegisterOnly.config([nodeFiles]);
babelRegisterOnly([]);
/* $FlowFixMe(site=react_native_oss) */
const transformer = require('metro/src/transformer.js');
module.exports = {
process(src/*: string*/, file/*: string*/) {
if (nodeFiles.test(file)) { // node specific transforms only
return babelTransformSync(
src,
Object.assign({filename: file}, nodeOptions)
).code;
}
const {ast} = transformer.transform({
filename: file,
localPath: file,
options: {
assetDataPlugins: [],
dev: true,
inlineRequires: true,
minify: false,
platform: '',
projectRoot: '',
retainLines: true,
},
src,
plugins: [
[require('@babel/plugin-transform-block-scoping')],
// the flow strip types plugin must go BEFORE class properties!
// there'll be a test case that fails if you don't.
[require('@babel/plugin-transform-flow-strip-types')],
[
require('@babel/plugin-proposal-class-properties'),
// use `this.foo = bar` instead of `this.defineProperty('foo', ...)`
{loose: true},
],
[require('@babel/plugin-transform-computed-properties')],
[require('@babel/plugin-transform-destructuring')],
[require('@babel/plugin-transform-function-name')],
[require('@babel/plugin-transform-literals')],
[require('@babel/plugin-transform-parameters')],
[require('@babel/plugin-transform-shorthand-properties')],
[require('@babel/plugin-transform-react-jsx')],
[require('@babel/plugin-transform-regenerator')],
[require('@babel/plugin-transform-sticky-regex')],
[require('@babel/plugin-transform-unicode-regex')],
[
require('@babel/plugin-transform-modules-commonjs'),
{strict: false, allowTopLevelThis: true},
],
[require('@babel/plugin-transform-classes')],
[require('@babel/plugin-transform-arrow-functions')],
[require('@babel/plugin-transform-spread')],
[require('@babel/plugin-proposal-object-rest-spread')],
[
require('@babel/plugin-transform-template-literals'),
{loose: true}, // dont 'a'.concat('b'), just use 'a'+'b'
],
[require('@babel/plugin-transform-exponentiation-operator')],
[require('@babel/plugin-transform-object-assign')],
[require('@babel/plugin-transform-for-of'), {loose: true}],
[require('@babel/plugin-transform-react-display-name')],
[require('@babel/plugin-transform-react-jsx-source')],
],
});
return generate(ast, {
code: true,
comments: false,
compact: false,
filename: file,
retainLines: true,
sourceFileName: file,
sourceMaps: true,
}, src).code;
},
getCacheKey: createCacheKeyFunction([
__filename,
require.resolve('metro/src/transformer.js'),
require.resolve('@babel/core/package.json'),
]),
};
| JavaScript | 0.00023 | @@ -1549,16 +1549,164 @@
ns: %5B%5D,%0A
+ ast: true, // needed for open source (?) https://github.com/facebook/react-native/commit/f8d6b97140cffe8d18b2558f94570c8d1b410d5c#r28647044%0A
|
0841d496537f5b0b9c57d573b040bf1666be64ed | Fix lunar-en.js layout (#1356) | assets/js/lunr-en.js | assets/js/lunr-en.js | ---
---
var idx = lunr(function () {
this.field('title', {boost: 10})
this.field('excerpt')
this.field('categories')
this.field('tags')
this.ref('id')
});
{% assign count = 0 %}
{% for c in site.collections %}
{% assign docs = c.docs %}
{% for doc in docs %}
idx.add({
title: {{ doc.title | jsonify }},
excerpt: {{ doc.content | strip_html | truncatewords: 20 | jsonify }},
categories: {{ doc.categories | jsonify }},
tags: {{ doc.tags | jsonify }},
id: {{ count }}
});
{% assign count = count | plus: 1 %}
{% endfor %}
{% endfor %}
console.log( jQuery.type(idx) );
var store = [
{% for c in site.collections %}
{% if forloop.last %}
{% assign l = true %}
{% endif %}
{% assign docs = c.docs %}
{% for doc in docs %}
{% if doc.header.teaser %}
{% capture teaser %}{{ doc.header.teaser }}{% endcapture %}
{% else %}
{% assign teaser = site.teaser %}
{% endif %}
{
"title": {{ doc.title | jsonify }},
"url": {{ doc.url | absolute_url | jsonify }},
"excerpt": {{ doc.content | strip_html | truncatewords: 20 | jsonify }},
"teaser":
{% if teaser contains "://" %}
{{ teaser | jsonify }}
{% else %}
{{ teaser | absolute_url | jsonify }}
{% endif %}
}{% unless forloop.last and l %},{% endunless %}
{% endfor %}
{% endfor %}]
$(document).ready(function() {
$('input#search').on('keyup', function () {
var resultdiv = $('#results');
var query = $(this).val();
var result = idx.search(query);
resultdiv.empty();
resultdiv.prepend('<p>'+result.length+' {{ site.data.ui-text[site.locale].results_found | default: "Result(s) found" }}</p>');
for (var item in result) {
var ref = result[item].ref;
if(store[ref].teaser){
var searchitem =
'<div class="list__item">'+
'<article class="archive__item" itemscope itemtype="http://schema.org/CreativeWork">'+
'<h2 class="archive__item-title" itemprop="headline">'+
'<a href="'+store[ref].url+'" rel="permalink">'+store[ref].title+'</a>'+
'</h2>'+
'<div class="archive__item-teaser">'+
'<img src="'+store[ref].teaser+'" alt="">'+
'</div>'+
'<p class="archive__item-excerpt" itemprop="description">'+store[ref].excerpt+'</p>'+
'</article>'+
'</div>';
}
else{
var searchitem =
'<div class="list__item">'+
'<article class="archive__item" itemscope itemtype="http://schema.org/CreativeWork">'+
'<h2 class="archive__item-title" itemprop="headline">'+
'<a href="'+store[ref].url+'" rel="permalink">'+store[ref].title+'</a>'+
'</h2>'+
'<p class="archive__item-excerpt" itemprop="description">'+store[ref].excerpt+'</p>'+
'</article>'+
'</div>';
}
resultdiv.append(searchitem);
}
});
});
| JavaScript | 0 | @@ -1,12 +1,25 @@
---%0A
+layout: null%0A
---%0A%0Avar
|
323733c86c65eb42231986cfab89e4c86937ee8b | Fix for IE not parsing JSON | assets/js/lw-custom.js | assets/js/lw-custom.js | // This custom JavaScript file provides some functionality not available from the Jekyll theme
// IE compatible fetch command
var getJSON = function (url, callback) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url, true);
xhr.responseType = 'json';
xhr.onload = function () {
var status = xhr.status;
if (status === 200) {
callback(null, xhr.response);
} else {
callback(status, xhr.response);
}
};
xhr.send();
};
var addCSS = function (url) {
var head = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = url;
head.appendChild(link);
};
var updateDates = function () {
// Get the current page
var data_attributes = document.querySelectorAll('[data-updated]');
if (data_attributes && data_attributes.length > 0) {
// For each one we have to call the Github API to get the latest commit
data_attributes.forEach(function (span) {
// Find the first instance appearing in our commits
var file = span.dataset.updated;
if (file) {
var folder = file.split('_')[0];
var file = file.replace(folder + '_', '') + '.csv';
getJSON('https://api.github.com/repos/librarieswest/opendata/commits?path=' + folder + '/' + file,
function (err, data) {
if (data && data.length && data.length > 0) {
var latest = data[0];
var date = new Date(latest.commit.committer.date);
txt = document.createTextNode(date.toLocaleDateString("en-GB"));
span.appendChild(txt);
}
});
}
});
}
};
var createMemberMap = function () {
// First get LSOA JSON
getJSON('/downloads/LibrariesWestLSOAsWithPop.geojson',
function (err, lsoa_data) {
if (lsoa_data) {
// Then we get our latest members CSV
Papa.parse('https://raw.githubusercontent.com/LibrariesWest/opendata/master/membership/members.csv', {
download: true,
complete: function (members) {
// First do our processing on the geojson
let member_data = members.data;
for (var i = 0; i < lsoa_data.features.length; i++) {
lsoa_data.features[i].properties.users = {};
// For each feature (LSOA) we need to add all the libraries
var population = lsoa_data.features[i].properties['LSOAPopulation_All Ages'];
var user_count = 0;
for (var y = 0; y < member_data.length; y++) {
if (member_data[y][11] === lsoa_data.features[i].properties.lsoa11cd) {
var users = member_data[y][12];
if (users !== '*') user_count = (user_count + parseInt(users));
if (users === '*') user_count = (user_count + 1); // For suppressed data assume 1
lsoa_data.features[i].properties.users[member_data[y][1]] = member_data[y][1];
}
}
lsoa_data.features[i].properties.population_percentage = Math.round(user_count / population * 100);
lsoa_data.features[i].properties.opacity = Math.round((user_count / population), 1);
}
// Now add the map
// mapboxgl.accessToken = 'pk.eyJ1IjoiZHhyb3dlIiwiYSI6ImNqMnI5Y2p2cDAwMHQzMm11cjZlOGQ2b2oifQ.uxhJoz3QCO6cARRQ8uKdzw';
const map = new mapboxgl.Map({
container: "map",
style: 'https://librarieswest.github.io/assets/json/light.json',
center: [-3.00, 51.13],
zoom: 12
});
map.addControl(new mapboxgl.FullscreenControl());
var nav = new mapboxgl.NavigationControl();
map.addControl(nav, 'top-left');
map.on('load', function () {
document.getElementById('map-loader').innerHTML = '';
['#FFEDA0', '#FED976', '#FEB24C', '#FD8D3C', '#FC4E2A', '#E31A1C', '#BD0026', '#800026'];
map.addSource('lsoas', { type: 'geojson', data: lsoa_data });
map.addLayer({
"id": "lsoas",
"type": "fill",
"source": "lsoas",
'paint': {
'fill-color': [
'interpolate',
['linear'],
['get', 'population_percentage'],
0, '#FFEDA0',
4, '#FED976',
8, '#FEB24C',
12, '#FD8D3C',
18, '#FC4E2A',
22, '#E31A1C',
26, '#BD0026',
30, '#800026'
],
'fill-opacity': 0.5
}
});
// Create a popup, but don't add it to the map yet.
var popup = new mapboxgl.Popup({
closeButton: false,
closeOnClick: false
});
map.on('mousemove', 'lsoas', function (e) {
var lsoas = map.queryRenderedFeatures(e.point, {
layers: ['lsoas']
});
if (lsoas.length > 0) {
// Change the cursor style as a UI indicator.
map.getCanvas().style.cursor = 'pointer';
var description = '<strong>Library users <em>' + lsoas[0].properties.population_percentage + '</strong> percent of population</em>';
popup.setLngLat(map.unproject(e.point))
.setHTML(description)
.addTo(map);
} else {
map.getCanvas().style.cursor = '';
popup.remove();
}
});
});
}
});
}
});
};
document.addEventListener("DOMContentLoaded", function () {
// Get the current page
var path = window.location.pathname;
if (path === '/data/') {
updateDates();
}
if (path === '/map/') {
addCSS('https://cdnjs.cloudflare.com/ajax/libs/mapbox-gl/0.46.0/mapbox-gl.css');
addCSS('/assets/css/lw-custom.css');
createMemberMap();
}
}); | JavaScript | 0.000002 | @@ -305,16 +305,37 @@
status;%0A
+%09%09var response = %5B%5D;%0A
%09%09if (st
@@ -350,16 +350,98 @@
200) %7B%0A
+%09%09%09if (typeof xhr.response === 'string') %7B response = JSON.parse(xhr.response); %7D%0A
%09%09%09callb
@@ -450,20 +450,16 @@
k(null,
-xhr.
response
@@ -492,20 +492,16 @@
status,
-xhr.
response
|
788fb8c608ba705d2731401eb631205a27abec8f | Fix oilpro submit url | src/jQuery-BEShare.js | src/jQuery-BEShare.js | /* jshint browser:true,jquery:true */
;(function($, window, document, undefined) {
"use strict";
/*jshint scripturl:true, -W084*/
var $window = $(window), $document = $(document);
var TARGETS = {
'Facebook': 'https://www.facebook.com/sharer/sharer.php?u={$url}&t={$title}',
'Twitter': 'https://twitter.com/intent/tweet?text={$title}&url={$url}',
'LinkedIn': 'https://www.linkedin.com/shareArticle?mini=true&url={$url}&title={$title}',
'Google+': 'https://plus.google.com/share?url={$url}',
'OilPro': 'http://oilpro.com/links/submit?url={$url}&title={&title}',
'Print': 'javascript:window.print()',
'Email': 'mailto:?subject={$title}&body={$url}'
};
var PLUGIN_NAME = 'BEShare';
var defaults = {
'type': 'popup',
'targets': ['Facebook', 'Twitter'],
'class': PLUGIN_NAME,
'prefix': 'icon-',
'suffix': '',
'width': '626',
'height': '436',
'onShare': null
};
// Mini template engine.
function template(tpl, data) {
var re = /\{\$([^}]+)?\}/g, match;
while(match = re.exec(tpl)) {
tpl = tpl.replace(match[0], data[match[1]]);
}
return tpl;
}
function move($element, offset) {
if (!offset) {
offset = {
'top': '-9999px',
'left': '-9999px'
};
}
$element.css(offset);
}
function Plugin(element, options) {
this.element = $(element);
this.options = $.extend({}, defaults, options);
this._name = PLUGIN_NAME;
this.init();
}
Plugin.prototype.init = function() {
var options = this.options, $container;
if (options.type === "inline") {
$container = this.element;
} else {
$container = $('<div/>');
$container.appendTo(document.body);
$container.css({
'position': 'absolute'
});
move($container);
}
this.container = $container;
$container.addClass(options['class']);
var targets = options.targets;
if ($.type(targets) === 'string') {
// @TODO: Parse string 'ServiceA,ServiceB|ServiceC,ServiceD'
}
var i, total = targets.length;
for (i = 0; i < total; i++) {
this.add(targets[i]);
}
if (options.type === 'popup') {
this.element.on('click.'+PLUGIN_NAME, function(event) {
// Stop the event from bubbling up to the below handler.
event.stopPropagation();
var position = $(this).offset();
move($container, position);
$container.addClass('active');
});
// Clicking anywhere outside will close the popup.
$document.on('click.'+PLUGIN_NAME, function(event) {
if(!$(event.target).closest('.'+options['class']).length) {
if ($container.hasClass('active')) {
$container.removeClass('active');
move($container);
}
}
});
}
};
Plugin.prototype.add = function(targetName) {
var options = this.options;
var target = TARGETS[targetName];
if (!target) {
// Any string not of a target is output as is.
this.container.append(targetName);
return this;
}
var url = template(target, {
url: encodeURIComponent(document.location.href),
title: encodeURIComponent(document.title),
});
var $link = $('<a href="' + url + '"><span>' + targetName + '</span></a>');
$link.attr('title', 'Share this page on ' + targetName);
if (url.indexOf('http') === 0) {
// External links
$link.attr('target', '_blank');
$link.on('click.'+PLUGIN_NAME, function() {
window.open(url, PLUGIN_NAME, 'toolbar=0,status=0,width='+options.width+',height='+options.height);
if (options.onShare) {
options.onShare(targetName);
}
return false;
});
}
$link.addClass(options.prefix + targetName.toLowerCase().replace('+','plus') + options.suffix);
$link.appendTo(this.container);
return this;
};
$.fn[PLUGIN_NAME] = function(options) {
return this.each(function() {
if (!$.data(this, 'plugin_' + PLUGIN_NAME)) {
$.data(this, 'plugin_' + PLUGIN_NAME,
new Plugin( this, options ));
}
});
};
})(jQuery, window, document);
| JavaScript | 0 | @@ -570,23 +570,8 @@
url%7D
-&title=%7B&title%7D
',%0A
|
95a00ccc1726e11e066c89767fccb13392b10473 | fix bug with line endpoints not getting selected | core/getClosestEntity.js | core/getClosestEntity.js |
function vec(p, q) {
return q.clone().subtract(p)
}
function norm(vec) {
return vec.clone().rotateRight().unit()
}
function perpComp(norm, offset) {
return norm.dot(offset);
}
function project(u, v) {
let lengthSq = v.lengthSq()
return lengthSq > 0 ? v.clone().mulS(u.dot(v) / v.lengthSq()) : lengthSq
}
export function getDistanceFromWire(wire, point, r) {
// true if part or all of the line is in the given radius
let offset = vec(point, wire.p).mulS(-1)
let wireVec = vec(wire.p, wire.q)
let pComp = perpComp(norm(wireVec), offset);
// not within distance of infinite line
if (r != null && Math.abs(pComp) > r) {
return null;
}
let linePos = wireVec.dot(offset) / wireVec.lengthSq()
// within boundaries of endpoints or radius of either endpoints
if (linePos > 0 && linePos < 1) {
return pComp * pComp;
}
let rSq = r * r;
// within radius of either endpoints
let dist = Math.min(wire.p.distanceSq(point), wire.q.distanceSq(point))
if (r == null && dist < rSq) {
return dist
}
return null
}
export default function getClosestEntity({balls, wires}, point, maxRadius) {
let [d1, closestBall] = balls.reduce(([closestDistanceSq, closestBall], ball) => {
let distanceSq = ball.p.distanceSq(point)
if (closestBall == null && distanceSq < maxRadius * maxRadius) return [distanceSq, ball]
return distanceSq < closestDistanceSq ? [distanceSq, ball] : [closestDistanceSq, closestBall]
}, [null, null])
let [d2, closestWire] = wires.reduce(([closestDistanceSq, closestWire], wire) => {
let distanceSq = getDistanceFromWire(wire, point, maxRadius)
if (closestWire == null && distanceSq != null) return [distanceSq, wire]
return distanceSq != null && distanceSq < closestDistanceSq ? [distanceSq, wire] : [closestDistanceSq, closestWire]
}, [null, null])
if (closestBall && !closestWire) return closestBall
if (closestWire && !closestBall) return closestWire
if (closestWire && closestBall) {
if (d1 < d2) {
return closestBall
}
return closestWire
}
return null
}
| JavaScript | 0 | @@ -669,352 +669,342 @@
let
-linePos = wireVec.dot(offset) / wireVec.lengthSq()%0A // within boundaries of endpoints or radius of either end
+rSq = r * r;%0A // within radius of either endpoints%0A let dist = Math.min(wire.p.distanceSq(point), wire.q.distanceSq(
point
-s
+))
%0A if (
-linePos %3E 0 && linePos %3C 1) %7B%0A return pComp * pComp;%0A %7D%0A let rSq = r * r;%0A // within radius of either endpoints%0A let dist = Math.min(wire.p.distanceSq(point), wire.q.distanceSq(
+r != null && dist %3C rSq) %7B%0A return dist%0A %7D%0A let linePos = wireVec.dot(offset) / wireVec.lengthSq()%0A // within boundaries of endpoints or radius of either end
point
-))
+s
%0A if (
-r == null && dist %3C rSq
+linePos %3E 0 && linePos %3C 1
) %7B%0A
@@ -1010,28 +1010,38 @@
%0A return
-dist
+pComp * pComp;
%0A %7D%0A retur
|
bc3cc6d436a6a955fe012a9f2653b97344caeadf | change RemoteRobotStore getMotors and getPeripherals to return arrays | app/client/dashboard/stores/RemoteRobotStore.js | app/client/dashboard/stores/RemoteRobotStore.js | /**
* Stores data sourced from a physical remote robot.
* Includes motor and sensor data.
*/
import AppDispatcher from '../../dispatcher/AppDispatcher';
import DashboardConstants from '../constants/DashboardConstants';
import {EventEmitter} from 'events';
import assign from 'object-assign';
var ActionTypes = DashboardConstants.ActionTypes;
// Private data.
var motors = {};
var peripherals = {};
var RemoteRobotStore = assign({}, EventEmitter.prototype, {
emitChange() {
this.emit('change');
},
getMotors() {
return motors;
},
getPeripherals() {
return peripherals;
}
});
/**
* Remove the motor from the motors list. Helper for handleUpdateMotor.
*/
function reapMotor(id) {
motors[id].disconnected = true;
motors[id].reaper = setTimeout(() => {
delete motors[id];
RemoteRobotStore.emitChange();
}, 3000);
RemoteRobotStore.emitChange();
}
/**
* Handles receiving an UPDATE_MOTOR action. */
function handleUpdateMotor(action) {
// Get the motor from the motors dictionary.
var motor = motors[action.id];
// Check if our motor exists and has a reaper.
// If so, stop the reaper.
// If not, make a new empty object and call that the motor.
if (motor != null && motor.reaper != null) {
clearTimeout(motor.reaper);
} else {
motor = {id: action.id, peripheralType: DashboardConstants.PeripheralTypes.MOTOR_SCALAR};
motors[action.id] = motor;
}
// Motor is not disconnected.
motor.disconnected = false;
// Assign properties from the action.
motor.value = action.value;
// Assign a new reaper, which will remove this motor if
// no updates are received after some number of milliseconds.
motor.reaper = setTimeout(reapMotor, 500, action.id);
// Notify listeners that the motors have been updated.
RemoteRobotStore.emitChange();
}
/**
* Handles receiving an UPDATE_PERIPHERAL action.
*/
function handleUpdatePeripheral(action) {
var peripheral = action.peripheral;
peripherals[peripheral.id] = peripheral;
RemoteRobotStore.emitChange();
}
RemoteRobotStore.dispatchToken = AppDispatcher.register((action) => {
switch (action.type) {
case ActionTypes.UPDATE_MOTOR:
handleUpdateMotor(action);
break;
case ActionTypes.UPDATE_PERIPHERAL:
handleUpdatePeripheral(action);
break;
}
});
export default RemoteRobotStore;
| JavaScript | 0 | @@ -288,16 +288,40 @@
ssign';%0A
+import _ from 'lodash';%0A
var Acti
@@ -554,22 +554,33 @@
return
+_.toArray(
motors
+)
;%0A %7D,%0A
@@ -610,16 +610,26 @@
return
+_.toArray(
peripher
@@ -631,17 +631,64 @@
ipherals
-;
+); // not that efficient, rewrite if bottleneck.
%0A %7D%0A%7D);
|
6cc0e683842a3130ece3028a2107aa05ff85c57e | Make barRight optional. | src/page/mixin/cartridge-behaviour.js | src/page/mixin/cartridge-behaviour.js | import {isFunction} from 'lodash/lang';
import {dispatcher} from 'focus-core';
import {component as Empty} from '../../common/empty';
export default {
/**
* Updates the cartridge using the cartridgeConfiguration.
*/
_registerCartridge() {
this.cartridgeConfiguration = this.cartridgeConfiguration || this.props.cartridgeConfiguration;
if (!isFunction(this.cartridgeConfiguration)) {
this.cartridgeConfiguration = () => ({});
console.warn(`
Your detail page does not have any cartrige configuration, this is not mandarory but recommended.
It should be a component attribute return by a function.
function cartridgeConfiguration(){
var cartridgeConfiguration = {
summary: {component: "A React Component", props: {id: this.props.id}},
cartridge: {component: "A React Component"},
actions: {components: "react actions"}
};
return cartridgeConfiguration;
}
`);
}
let cartridgeConf = this.cartridgeConfiguration();
dispatcher.handleViewAction({
data: {
cartridgeComponent: cartridgeConf.cartridge || {component: Empty},
summaryComponent: cartridgeConf.summary || {component: Empty},
actions: cartridgeConf.actions || {primary: [], secondary: []},
barContentLeftComponent: cartridgeConf.barLeft || {component: Empty},
barContentRightComponent: cartridgeConf.barRight || {component: Empty},
headerSize: cartridgeConf.headerSize || 'medium'
},
type: 'update'
});
},
/**
* Registers the cartridge upon mounting.
*/
componentWillMount() {
this._registerCartridge();
}
};
| JavaScript | 0 | @@ -1189,62 +1189,21 @@
-dispatcher.handleViewAction(%7B%0A
+let
data
-:
+ =
%7B%0A
-
@@ -1285,28 +1285,24 @@
-
summaryCompo
@@ -1356,36 +1356,32 @@
y%7D,%0A
-
-
actions: cartrid
@@ -1428,20 +1428,16 @@
y: %5B%5D%7D,%0A
-
@@ -1526,83 +1526,56 @@
- barContentRightComponent: cartridgeConf.barRight %7C%7C %7Bcomponent: Empty%7D,
+headerSize: cartridgeConf.headerSize %7C%7C 'medium'
%0A
@@ -1575,32 +1575,36 @@
um'%0A
+%7D;%0A%0A
headerSize:
@@ -1587,36 +1587,28 @@
%7D;%0A%0A
-headerSize:
+if (
cartridgeCon
@@ -1613,45 +1613,87 @@
onf.
-headerSize %7C%7C 'medium'%0A %7D,
+barRight) %7B%0A data.barContentRightComponent = cartridgeConf.barRight;
%0A
@@ -1697,19 +1697,61 @@
+%7D%0A%0A
+ dispatcher.handleViewAction(%7Bdata,
type: '
@@ -1757,25 +1757,16 @@
'update'
-%0A
%7D);%0A
|
4b9e722c4074d3ed6882413daf798d233bc06509 | Remove unused import comment | cmd/tchaik/ui/static/js/src/stores/PlayingStatusStore.js | cmd/tchaik/ui/static/js/src/stores/PlayingStatusStore.js | 'use strict';
var AppDispatcher = require('../dispatcher/AppDispatcher');
var EventEmitter = require('eventemitter3').EventEmitter;
var assign = require('object-assign');
var NowPlayingConstants = require('../constants/NowPlayingConstants.js');
var PlaylistConstants = require('../constants/PlaylistConstants.js');
var NowPlayingStore = require('../stores/NowPlayingStore.js');
// var CtrlConstants = require('../constants/ControlConstants.js');
var CHANGE_EVENT = 'change';
var _defaultTrackState = {
buffered: 0.0,
duration: 0.0,
};
var _trackState = _defaultTrackState;
var _currentTime = null;
function setCurrentTime(time) {
_currentTime = time;
localStorage.setItem("currentTime", time);
}
function currentTime() {
if (_currentTime !== null) {
return _currentTime;
}
_currentTime = 0;
var t = localStorage.getItem("currentTime");
if (t !== null) {
_currentTime = parseFloat(t);
}
return _currentTime;
}
var PlayingStatusStore = assign({}, EventEmitter.prototype, {
getTime: function() {
return currentTime();
},
getBuffered: function() {
return _trackState.buffered;
},
getDuration: function() {
return _trackState.duration;
},
emitChange: function(type) {
this.emit(CHANGE_EVENT, type);
},
/**
* @param {function} callback
*/
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
/**
* @param {function} callback
*/
removeChangeListener: function(callback) {
this.removeListener(CHANGE_EVENT, callback);
},
});
PlayingStatusStore.dispatchToken = AppDispatcher.register(function(payload) {
var action = payload.action;
var source = payload.source;
if (source === 'VIEW_ACTION') {
switch (action.actionType) {
case NowPlayingConstants.ENDED:
if (action.source !== "playlist") {
break;
}
/* falls through */
case PlaylistConstants.PREV:
/* falls through */
case PlaylistConstants.NEXT:
/* falls through */
case PlaylistConstants.PLAY_NOW:
/* falls through */
case NowPlayingConstants.SET_CURRENT_TRACK:
AppDispatcher.waitFor([
NowPlayingStore.dispatchToken,
]);
setCurrentTime(0);
PlayingStatusStore.emitChange();
break;
case NowPlayingConstants.RESET:
_trackState = {
buffered: 0,
duration: 0,
};
PlayingStatusStore.emitChange();
break;
case NowPlayingConstants.SET_DURATION:
_trackState.duration = action.duration;
PlayingStatusStore.emitChange();
break;
case NowPlayingConstants.SET_BUFFERED:
_trackState.buffered = action.buffered;
PlayingStatusStore.emitChange();
break;
case NowPlayingConstants.STORE_CURRENT_TIME:
setCurrentTime(action.currentTime);
PlayingStatusStore.emitChange();
break;
default:
break;
}
}
return true;
});
module.exports = PlayingStatusStore;
| JavaScript | 0 | @@ -379,77 +379,8 @@
);%0A%0A
-// var CtrlConstants = require('../constants/ControlConstants.js');%0A%0A
var
|
24bc2b5bd368cb5b3f89cd113e5812ec3d6b72f2 | Add ListviewSearchingExample Button to UsageScreen & clean up | ignite-base/App/Containers/UsageExamplesScreen.js | ignite-base/App/Containers/UsageExamplesScreen.js | // @flow
import React, { PropTypes } from 'react'
import { View, ScrollView, Text, TouchableOpacity, Image } from 'react-native'
import { connect } from 'react-redux'
import LoginActions, { isLoggedIn } from '../Redux/LoginRedux'
import TemperatureActions from '../Redux/TemperatureRedux'
import { Actions as NavigationActions } from 'react-native-router-flux'
import { Colors, Images, Metrics } from '../Themes'
import RoundedButton from '../Components/RoundedButton'
// external libs
import Icon from 'react-native-vector-icons/FontAwesome'
import * as Animatable from 'react-native-animatable'
// Enable when you have configured Xcode
// import PushNotification from 'react-native-push-notification'
import I18n from 'react-native-i18n'
// Styles
import styles from './Styles/UsageExamplesScreenStyle'
class UsageExamplesScreen extends React.Component {
componentWillReceiveProps (nextProps) {
// Request push premissions only if the user has logged in.
const { loggedIn } = nextProps
if (loggedIn) {
/*
* If you have turned on Push in Xcode, http://i.imgur.com/qFDRhQr.png
* uncomment this code below and import at top
*/
// if (__DEV__) console.log('Requesting push notification permissions.')
// PushNotification.requestPermissions()
}
}
// fires when we tap the rocket!
handlePressRocket = () => {
this.props.requestTemperature('Boise')
}
// fires when tap send
handlePressSend = () => {
this.props.requestTemperature('Toronto')
}
// fires when tap star
handlePressStar = () => {
this.props.requestTemperature('New Orleans')
}
renderLoginButton () {
return (
<RoundedButton onPress={NavigationActions.login}>
{I18n.t('signIn')}
</RoundedButton>
)
}
renderLogoutButton () {
return (
<RoundedButton onPress={this.props.logout}>
{I18n.t('logOut')}
</RoundedButton>
)
}
renderHeader (title) {
return (
<View style={styles.componentLabelContainer}>
<Text style={styles.componentLabel}>{title}</Text>
</View>
)
}
renderUsageExamples () {
const { loggedIn, temperature, city } = this.props
return (
<View>
{this.renderHeader(I18n.t('loginLogoutExampleTitle'))}
{loggedIn ? this.renderLogoutButton() : this.renderLoginButton()}
{this.renderHeader('I18n Locale')}
<View style={styles.groupContainer}>
<Text style={styles.locale}>{I18n.locale}</Text>
</View>
{this.renderHeader(I18n.t('api') + `: ${city}`)}
<View style={[styles.groupContainer, {height: 50}]}>
<Text style={styles.temperature}>{temperature && `${temperature} ${I18n.t('tempIndicator')}`}</Text>
</View>
{this.renderHeader(I18n.t('rnVectorIcons'))}
<View style={styles.groupContainer}>
<TouchableOpacity onPress={this.handlePressRocket}>
<Icon name='rocket' size={Metrics.icons.medium} color={Colors.ember} />
</TouchableOpacity>
<TouchableOpacity onPress={this.handlePressSend}>
<Icon name='send' size={Metrics.icons.medium} color={Colors.error} />
</TouchableOpacity>
<TouchableOpacity onPress={this.handlePressStar}>
<Icon name='star' size={Metrics.icons.medium} color={Colors.snow} />
</TouchableOpacity>
<Icon name='trophy' size={Metrics.icons.medium} color={Colors.error} />
<Icon name='warning' size={Metrics.icons.medium} color={Colors.ember} />
</View>
<View style={styles.groupContainer}>
<Icon.Button name='facebook' style={styles.facebookButton} backgroundColor={Colors.facebook} onPress={() => window.alert('Facebook')}>
{I18n.t('loginWithFacebook')}
</Icon.Button>
</View>
{this.renderHeader(I18n.t('rnAnimatable'))}
<View style={styles.groupContainer}>
<Animatable.Text animation='fadeIn' iterationCount='infinite' direction='alternate' style={styles.subtitle}>{I18n.t('rnAnimatable')}</Animatable.Text>
<Animatable.Image animation='pulse' iterationCount='infinite' source={Images.logo} />
<Animatable.View animation='jello' iterationCount='infinite' >
<Icon name='cab' size={Metrics.icons.medium} color={Colors.snow} />
</Animatable.View>
</View>
{this.renderHeader(I18n.t('igniteGenerated'))}
<RoundedButton text='Listview' onPress={NavigationActions.listviewExample} />
<RoundedButton text='Listview Grid' onPress={NavigationActions.listviewGridExample} />
<RoundedButton text='Listview Sections' onPress={NavigationActions.listviewSectionsExample} />
</View>
)
}
render () {
return (
<View style={styles.mainContainer}>
<Image source={Images.background} style={styles.backgroundImage} resizeMode='stretch' />
<ScrollView style={styles.container}>
<View style={styles.section}>
<Text style={styles.sectionText} >
The Usage Examples screen is a playground for 3rd party libs and logic proofs.
Items on this screen can be composed of multiple components working in concert. Functionality demos of libs and practices
</Text>
</View>
{this.renderUsageExamples()}
</ScrollView>
</View>
)
}
}
UsageExamplesScreen.propTypes = {
loggedIn: PropTypes.bool,
temperature: PropTypes.number,
city: PropTypes.string,
logout: PropTypes.func,
requestTemperature: PropTypes.func
}
const mapStateToProps = (state) => {
return {
loggedIn: isLoggedIn(state.login),
temperature: state.temperature.temperature,
city: state.temperature.city
}
}
const mapDispatchToProps = (dispatch) => {
return {
logout: () => dispatch(LoginActions.logout()),
requestTemperature: (city) => dispatch(TemperatureActions.temperatureRequest(city))
}
}
export default connect(mapStateToProps, mapDispatchToProps)(UsageExamplesScreen)
| JavaScript | 0 | @@ -4711,24 +4711,129 @@
Example%7D /%3E%0A
+ %3CRoundedButton text='Listview Searching' onPress=%7BNavigationActions.listviewSearchingExample%7D /%3E%0A
%3C/View
|
f3c92acacf350a1f9f34ee50ee8340c271afb868 | Fix fetching daemon settings bug | src/renderer/redux/actions/settings.js | src/renderer/redux/actions/settings.js | import * as ACTIONS from 'constants/action_types';
import * as SETTINGS from 'constants/settings';
import Lbry from 'lbry';
import Fs from 'fs';
import Http from 'http';
export function doFetchDaemonSettings() {
return function(dispatch) {
Lbry.settings_get().then(settings => {
dispatch({
type: ACTIONS.DAEMON_SETTINGS_RECEIVED,
data: {
settings,
},
});
});
};
}
export function doSetDaemonSetting(key, value) {
return function(dispatch) {
const settings = {};
settings[key] = value;
Lbry.settings_set(settings).then(settings);
Lbry.settings_get().then(remoteSettings => {
dispatch({
type: ACTIONS.DAEMON_SETTINGS_RECEIVED,
data: {
remoteSettings,
},
});
});
};
}
export function doSetClientSetting(key, value) {
return {
type: ACTIONS.CLIENT_SETTING_CHANGED,
data: {
key,
value,
},
};
}
export function doGetThemes() {
return function(dispatch) {
const themes = ['light', 'dark'];
dispatch(doSetClientSetting(SETTINGS.THEMES, themes));
};
}
export function doDownloadLanguage(langFile) {
return function(dispatch) {
const destinationPath = `${app.i18n.directory}/${langFile}`;
const language = langFile.replace('.json', '');
const errorHandler = () => {
Fs.unlink(destinationPath, () => {}); // Delete the file async. (But we don't check the result)
dispatch({
type: ACTIONS.DOWNLOAD_LANGUAGE_FAILED,
data: { language },
});
};
const req = Http.get(
{
headers: {
'Content-Type': 'text/html',
},
host: 'i18n.lbry.io',
path: `/langs/${langFile}`,
},
response => {
if (response.statusCode === 200) {
const file = Fs.createWriteStream(destinationPath);
file.on('error', errorHandler);
file.on('finish', () => {
file.close();
// push to our local list
dispatch({
type: ACTIONS.DOWNLOAD_LANGUAGE_SUCCEEDED,
data: { language },
});
});
response.pipe(file);
} else {
errorHandler(new Error('Language request failed.'));
}
}
);
req.setTimeout(30000, () => {
req.abort();
});
req.on('error', errorHandler);
req.end();
};
}
export function doDownloadLanguages() {
return function() {
// temporarily disable i18n so I can get a working build out -- Jeremy
// if (!Fs.existsSync(app.i18n.directory)) {
// Fs.mkdirSync(app.i18n.directory);
// }
//
// function checkStatus(response) {
// if (response.status >= 200 && response.status < 300) {
// return response;
// }
// throw new Error(
// __("The list of available languages could not be retrieved.")
// );
// }
//
// function parseJSON(response) {
// return response.json();
// }
//
// return fetch("http://i18n.lbry.io")
// .then(checkStatus)
// .then(parseJSON)
// .then(files => {
// const actions = files.map(doDownloadLanguage);
// dispatch(batchActions(...actions));
// });
};
}
export function doChangeLanguage(language) {
return function(dispatch) {
dispatch(doSetClientSetting(SETTINGS.LANGUAGE, language));
app.i18n.setLocale(language);
};
}
| JavaScript | 0 | @@ -95,34 +95,8 @@
gs';
-%0A%0Aimport Lbry from 'lbry';
%0Aimp
@@ -139,16 +139,42 @@
http';%0A%0A
+import Lbry from 'lbry';%0A%0A
export f
@@ -507,17 +507,20 @@
const
-s
+newS
ettings
@@ -525,25 +525,28 @@
s = %7B%7D;%0A
-s
+newS
ettings%5Bkey%5D
@@ -577,17 +577,20 @@
ngs_set(
-s
+newS
ettings)
@@ -591,25 +591,28 @@
tings).then(
-s
+newS
ettings);%0A
@@ -638,23 +638,17 @@
().then(
-remoteS
+s
ettings
@@ -747,15 +747,9 @@
-remoteS
+s
etti
|
1d2bee8bdf36f98feb1d4f3c45ede5786c59b7e7 | Send feedback when user register new business | app/components/BusinessList/RegisterBusiness.js | app/components/BusinessList/RegisterBusiness.js | // @flow
import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import RaisedButton from 'material-ui/RaisedButton';
import DatePicker from 'material-ui/DatePicker';
import TextField from 'material-ui/TextField';
import styles from './BusinessList.css';
// Data - Cliente - Tipo de Pagemento - Valor - Data Pagamento - Dia Pagamento
const upper = value => value && value.toUpperCase();
const DateTimeFormat = global.Intl.DateTimeFormat;
const formatDate = date => Intl.DateTimeFormat('PT-BR').format(date);
const renderDatePicker = ({
input,
floatingLabelText,
hintText,
container,
}) => (
<DatePicker
hintText={hintText}
container={container}
DateTimeFormat={DateTimeFormat}
formatDate={formatDate}
floatingLabelText={floatingLabelText}
style={customStyle.fullRow}
textFieldStyle={customStyle.fullWidth}
okLabel="OK"
cancelLabel="Cancelar"
locale="pt-br"
onChange={(event, value) => input.onChange(value)}
/>
);
const renderTextField = ({
input,
floatingLabelText,
type,
}) =>
(<TextField
floatingLabelText={floatingLabelText}
style={customStyle.fullRow}
type={type}
{...input}
/>);
const customStyle = {
fullRow: {
width: '95%',
marginLeft: '2.5%',
},
fullWidth: {
width: '100%'
},
btn: {
minWidth: '95%',
margin: '2.5%'
},
};
const validate = values => {
const errors = {};
if (!values.clientName) {
errors.clientName = 'Nome do cliente é obrigatório';
}
if (!values.typePayment) {
errors.typePayment = 'Tipo de pagamento é obrigatório';
}
if (!values.billingDate) {
errors.billingDate = 'Dia do pagamento é obrigatório';
}
if (!values.price) {
errors.price = 'Preço da venda é obritório';
}
return errors;
};
class RegisterBusiness extends Component {
submit: () => void;
props: {
saveBusiness: () => void,
handleSubmit: () => void
}
constructor() {
super();
this.submit = this.submit.bind(this);
}
submit(payload: object) {
this.props.saveBusiness(payload);
}
render() {
return (
<form onSubmit={this.props.handleSubmit(this.submit)} className={styles.form}>
<Field
name="dateRB"
floatingLabelText="DATA"
hintText="DATA"
container="inline"
component={renderDatePicker}
/>
<Field
name="clientName"
floatingLabelText="NOME DO CLIENTE"
type="text"
component={renderTextField}
normalize={upper}
/>
<Field
name="typePayment"
floatingLabelText="TIPO DE PAGAMENTO"
type="text"
component={renderTextField}
normalize={upper}
/>
<Field
name="price"
floatingLabelText="VALOR"
type="number"
component={renderTextField}
/>
<Field
name="billingDate"
floatingLabelText="DATA DO PAGAMENTO"
hintText="DATA"
container="inline"
component={renderDatePicker}
/>
<Field
name="paidDate"
floatingLabelText="DIA DO PAGAMENTO"
hintText="DATA"
container="inline"
component={renderDatePicker}
/>
<RaisedButton style={customStyle.btn} type="submit" label="Salvar" primary />
</form>
);
}
}
export default reduxForm({
form: 'RegisterBusiness',
validate
})(RegisterBusiness);
| JavaScript | 0 | @@ -69,16 +69,23 @@
eduxForm
+, reset
%7D from
@@ -98,16 +98,16 @@
-form';%0A
-
import R
@@ -368,16 +368,161 @@
amento%0A%0A
+const afterSubmit = (result, dispatch) =%3E %7B%0A window.alert('Venda cadastrada com sucesso!!!');%0A return dispatch(reset('RegisterBusiness'));%0A%7D;%0A%0A
const up
@@ -2122,16 +2122,60 @@
uper();%0A
+ this.state = %7B%0A open: false%0A %7D;%0A
this
@@ -2284,16 +2284,130 @@
);%0A %7D%0A%0A
+ openTouch() %7B%0A this.setState(%7B open: true %7D);%0A %7D%0A%0A closeTouch() %7B%0A this.setState(%7B open: false %7D);%0A %7D%0A%0A
render
@@ -3745,16 +3745,16 @@
xForm(%7B%0A
-
form:
@@ -3773,16 +3773,48 @@
iness',%0A
+ onSubmitSuccess: afterSubmit,%0A
valida
|
df4a9c1a457dbaee3146afc7d3a4a66c74c7a087 | add a period | app/components/browserwarning/browserwarning.js | app/components/browserwarning/browserwarning.js | /**
* Copyright (c) 2016, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
*/
import React, { Component } from 'react'
import utils from '../../core/utils';
const COPY_STATUS_NULL = 0;
const COPY_STATUS_SUCCESS = 10;
const COPY_STATUS_FAIL = 20;
export default class BrowserWarning extends Component {
constructor(props) {
super(props);
this.state = {
copyStatus: COPY_STATUS_NULL
};
}
render() {
var self = this;
var downloadCopy = <div className="browser-warning-chrome-image"></div>;
var copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>Copy link</button>;
if (this.state.copyStatus === COPY_STATUS_SUCCESS) {
copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>Copied!</button>
} else if (this.state.copyStatus === COPY_STATUS_FAIL) {
copyButton = <button className="btn browser-warning-copy-button" onClick={() => self.copyText()}>Please press Ctrl + C now</button>
}
if (!utils.isMobile()) {
downloadCopy = (<div>
<a href="https://www.google.com/intl/en/chrome/browser/desktop/index.html" target="_blank">
<div className="browser-warning-chrome-image"></div>
</a>
<div className="browser-warning-text">
<span className="dark-text">Copy and paste</span>
<input type="text" className="blip-link-text" value="blip.tidepool.org"></input>
<span className="dark-text">into Chrome.</span>
</div>
{copyButton}
<div className="browser-warning-download-text">Or download Chrome <a href="https://www.google.com/intl/en/chrome/browser/desktop/index.html" target="_blank">here</a></div>
</div>);
}
return (
<div className="browser-warning js-terms">
<div className="browser-warning-content browser-warning-box">
<h1 className="browser-warning-title">Blip's visualization is only certified to work on Chrome browser on a computer.</h1>
{downloadCopy}
</div>
</div>
);
}
copyText() {
var copyText = document.querySelector('.blip-link-text');
copyText.select();
try {
var copyCmd = document.execCommand('copy');
this.setState( {
copyStatus: (copyCmd) ? COPY_STATUS_SUCCESS : COPY_STATUS_FAIL
});
} catch (err) {
console.log('Unable to copy - unsupported browser');
this.setState({
copyStatus: COPY_STATUS_FAIL
});
}
}
} | JavaScript | 0.999999 | @@ -2302,16 +2302,17 @@
here%3C/a%3E
+.
%3C/div%3E%0A
@@ -2331,20 +2331,16 @@
;%0A %7D%0A
-
%0A ret
@@ -3086,8 +3086,9 @@
%7D%0A %7D%0A%7D
+%0A
|
ff47a461884f38409c768600457c31d35c94f3ef | fix TabixIndexedFile unit tests | tests/js_tests/spec/TabixIndexedFile.spec.js | tests/js_tests/spec/TabixIndexedFile.spec.js | require({
packages: [{ name: 'jDataView', main: 'jdataview', location: '../jDataView/src' }]
},
[
'dojo/_base/array',
'JBrowse/Browser',
'JBrowse/Store/TabixIndexedFile',
'JBrowse/Model/XHRBlob'
],function( array, Browser, TabixIndexedFile, XHRBlob ) {
describe( "tabix-indexed file", function() {
var f;
beforeEach( function() {
f = new TabixIndexedFile({
browser: new Browser({ unitTestMode: true }),
tbi: new XHRBlob( '../../sample_data/raw/volvox/volvox.test.vcf.gz.tbi' ),
file: new XHRBlob( '../../sample_data/raw/volvox/volvox.test.vcf.gz' )
});
});
it( 'can read ctgA:1000..4000', function() {
var items = [];
f.getLines( 'ctgA', 1000, 4000,
function(i) {
items.push(i);
},
function() {
items.done = true;
}
);
waitsFor( function(){ return items.done; } );
runs(function() {
expect( items.length ).toEqual( 8 );
array.forEach( items, function( item,i ) {
expect( item.ref ).toEqual('ctgA');
expect( item.start ).toBeGreaterThan( 999 );
expect( item.start ).toBeLessThan( 4001 );
});
});
});
});
}); | JavaScript | 0 | @@ -119,16 +119,50 @@
%5B%0A
+ 'dojo/_base/declare',%0A
@@ -317,16 +317,25 @@
unction(
+ declare,
array,
@@ -420,16 +420,269 @@
on() %7B%0A%0A
+var VCFIndexedFile = declare( TabixIndexedFile, %7B%0A parseItem: function() %7B%0A var i = this.inherited( arguments );%0A if( i ) %7B%0A i.start--;%0A i.end = i.start + i.fields%5B3%5D.length;%0A %7D%0A return i;%0A %7D%0A%7D);%0A%0A
var
@@ -729,21 +729,19 @@
f = new
-Tabix
+VCF
IndexedF
@@ -1618,17 +1618,20 @@
Equal('c
-t
+onti
gA');%0A
|
d30e8305689053d5ca9c7130189d211e27df9d07 | fix setting date facets | app/facet_selector/facet_selector.controller.js | app/facet_selector/facet_selector.controller.js | 'use strict';
(function() {
angular.module('facetController', ['tagService']).
controller('FacetController', ['$scope', 'Transfer', 'Facet', 'Tag', function($scope, Transfer, Facet, Tag) {
$scope.remove_facet = function(name, id) {
Facet.remove_by_id(name, id);
Transfer.filter();
};
$scope.Facet = Facet;
$scope.transfers = Transfer;
$scope.tags = Tag;
var format_date = function(start, end) {
var s;
if (!start) {
s = ' -';
} else {
s = start + ' -';
}
if (end) {
s += ' ' + end;
}
return s;
};
$scope.set_date_filter = function(start_date, end_date) {
if (!start_date && !end_date) {
return;
}
start_date = Date.parse(start_date || '0');
end_date = Date.parse(end_date || '999999999');
var facet_fn = function(data) {
// TODO: handle unparseable dates
var date_as_int = Date.parse(date);
return date_as_int > start_date && date_as_int < end_date;
};
Facet.remove('date');
Facet.add('date', facet_fn, {name: 'Date', text: format_date($scope.date_start, $scope.date_end)});
Transfer.filter();
};
$scope.$watch('tag_facet', function(selected) {
if (!selected) {
return;
}
Facet.add('tags', selected, {name: 'Tag', text: selected});
Transfer.filter();
});
}]);
})();
| JavaScript | 0 | @@ -653,240 +653,549 @@
-$scope.set_date_filter = function(start_date, end_date) %7B%0A if (!start_date && !end_date) %7B%0A return;%0A %7D%0A start_date = Date.parse(start_date %7C%7C '0');%0A end_date = Date.parse(end_date %7C%7C '999999999')
+var date_is_valid = function(date) %7B%0A if (date === undefined) %7B%0A return false;%0A %7D else %7B%0A return date.length %3C 4 ? false : true;%0A %7D%0A %7D%0A%0A $scope.set_date_filter = function(start_date, end_date) %7B%0A var default_start_date = -62167219200000; // BC 1%0A var default_end_date = 3093496473600000; // AD 99999%0A start_date = date_is_valid(start_date) ? Date.parse(start_date) : default_start_date;%0A end_date = date_is_valid(end_date) ? Date.parse(end_date) : default_end_date
;%0A%0A
@@ -1228,17 +1228,17 @@
tion(dat
-a
+e
) %7B%0A
@@ -1353,16 +1353,17 @@
as_int %3E
+=
start_d
@@ -1382,16 +1382,17 @@
as_int %3C
+=
end_dat
|
c14a586fa66205bd470960628913e813cc7fe83f | update th right way | app/assets/javascripts/fae/form/inputs/_text.js | app/assets/javascripts/fae/form/inputs/_text.js | /* global Fae, SimpleMDE, toolbarBuiltInButtons */
'use strict';
/**
* Fae form text
* @namespace form.text
* @memberof form
*/
Fae.form.text = {
init: function() {
this.slugger();
this.overrideMarkdownDefaults();
this.initMarkdown();
},
/**
* Attach listeners to inputs and update slug fields with original safe values from the original inputs
*/
slugger: function() {
var _this = this;
$('.slug').each(function() {
var $form = $(this).closest('form');
var $sluggers = $form.find('.slugger');
var $slug = $form.find('.slug');
var $select_slugger = $('.select.slugger');
if ($slug.val() !== '') {
$sluggers.removeClass('slugger');
} else {
// If it's a text field, listen for type input
$sluggers.keyup(function(){
var text = _this._digestSlug( $sluggers );
$slug.val( text );
});
// If it's a select field, listen for the change
if ($select_slugger.length) {
$select_slugger.change(function(){
var text = _this._digestSlug( $sluggers );
$slug.val( text );
});
};
}
});
},
/**
* Convert a group of selects or text fields into one slug string
* @access protected
* @param {jQuery} $sluggers - Input or inputs that should be converted into a URL-safe string
* @return {String}
*/
_digestSlug: function($sluggers) {
var slug_text = []
$sluggers.each(function() {
var $this = $(this);
if ($this.val().length) {
if ($this.is('input')) {
slug_text.push( $this.val() );
} else {
slug_text.push( $this.find('option:selected').text() );
}
}
});
// Combine all active slug fields for the query
// Make them lowercase
// Remove slashes, quotes or periods
// Replace white spaces with a dash
// Remove leading and trailing dashes
slug_text = slug_text
.join(' ')
.toLowerCase()
.replace(/(\\)|(\')|(\.)/g, '')
.replace(/[^a-zA-Z0-9]+/g, '-')
.replace(/(-$)|(^-)/g, '');
return slug_text;
},
/**
* Override SimpleMDE's preference for font-awesome icons and use a modal for the guide
* @see {@link modals.markdownModal}
*/
overrideMarkdownDefaults: function() {
toolbarBuiltInButtons['bold'].className = 'icon-bold';
toolbarBuiltInButtons['italic'].className = 'icon-italic';
toolbarBuiltInButtons['heading'].className = 'icon-font';
toolbarBuiltInButtons['code'].className = 'icon-code';
toolbarBuiltInButtons['unordered-list'].className = 'icon-list-ul';
toolbarBuiltInButtons['ordered-list'].className = 'icon-list-ol';
toolbarBuiltInButtons['link'].className = 'icon-link';
toolbarBuiltInButtons['image'].className = 'icon-image';
toolbarBuiltInButtons['quote'].className = 'icon-quote';
toolbarBuiltInButtons['fullscreen'].className = 'icon-fullscreen no-disable no-mobile';
toolbarBuiltInButtons['horizontal-rule'].className = 'icon-minus';
toolbarBuiltInButtons['preview'].className = 'icon-eye no-disable';
toolbarBuiltInButtons['side-by-side'].className = 'icon-columns no-disable no-mobile';
toolbarBuiltInButtons['guide'].className = 'icon-question';
// Override SimpleMDE's default guide and use a homegrown modal
toolbarBuiltInButtons['guide'].action = Fae.modals.markdownModal;
},
/**
* Find all markdown fields and initialize them with a markdown GUI
* @has_test {features/form_helpers/fae_input_spec.rb}
*/
initMarkdown: function() {
var fields = document.getElementsByClassName('js-markdown-editor');
for(var i = 0; i < fields.length; i++) {
if (!FCH.hasClass('mde-enabled', fields[i])) {
var editor = new SimpleMDE({
element: fields[i],
autoDownloadFontAwesome: false,
status: false,
spellChecker: false,
hideIcons: ['image', 'side-by-side', 'fullscreen', 'preview']
});
FCH.addClass('markdown-enabled', fields[i]);
}
}
}
};
| JavaScript | 0 | @@ -3742,16 +3742,27 @@
asClass(
+fields%5Bi%5D,
'mde-ena
@@ -3766,27 +3766,16 @@
enabled'
-, fields%5Bi%5D
)) %7B%0A
@@ -4045,37 +4045,32 @@
ass(
-'markdown-enabled', fields%5Bi%5D
+fields%5Bi%5D, 'mde-enabled'
);%0A
|
90a44b85bd9b75ad19f6cd89c5adf8960f74f2f9 | use app domain variable to render slug redirect on domain form | client/mobilizations/components/form-domain.js | client/mobilizations/components/form-domain.js | import React, { PropTypes } from 'react'
import { reduxForm } from 'redux-form'
import { FormGroup, ControlLabel, FormControl } from '~client/components/forms'
const FormDomain = ({
formComponent: FormComponent,
fields: { custom_domain: customDomain },
mobilization,
...formProps
}) => (
<FormComponent {...formProps}>
<p className='h5'>
Aqui você pode personalizar o endereço da sua mobilização caso já tenha um domínio próprio.
Por exemplo, se você já comprou www.nomedoseuprojeto.com.br, você pode usá-lo para este BONDE.
Demais, né?
</p>
<FormGroup controlId='customDomain' {...customDomain}>
<ControlLabel>Domínio personalizado</ControlLabel>
<FormControl
type='text'
placeholder='www.meudominio.com.br'
/>
</FormGroup>
<div className='separator' />
<div className='h5'>
<p>
<strong>Não esqueça</strong>: você vai precisar configurar este domínio no servidor de
registro para que ele redirecione a URL para a página da sua mobilização no BONDE.
Pra isso, você vai precisar dessas informações aqui embaixo, anote aí:
</p>
<table className='col-12 left-align'>
<tbody>
<tr>
<th>Nome</th>
<th>Tipo</th>
<th>Dados</th>
</tr>
<tr>
<td><code>{customDomain ? customDomain.value : ''}</code></td>
<td><code>CNAME</code></td>
<td><code>{mobilization.slug}.reboo.org</code></td>
</tr>
</tbody>
</table>
<p>
Se tiver alguma dúvida, dá uma olhada no tópico "Configurando seu domínio no BONDE",
no nosso tutorial, o <a href='https://trilho.bonde.org' target='_blank'>
Trilho <i className='fa fa-external-link' style={{ fontSize: '.7rem' }} />
</a>.
</p>
</div>
</FormComponent>
)
FormDomain.propTypes = {
formComponent: PropTypes.any.isRequired,
fields: PropTypes.shape({
custom_domain: PropTypes.object.isRequired
}).isRequired,
mobilization: PropTypes.object.isRequired
}
export default FormDomain
| JavaScript | 0 | @@ -73,16 +73,58 @@
x-form'%0A
+import ServerConfig from '~server/config'%0A
import %7B
@@ -1532,17 +1532,32 @@
ug%7D.
-reboo.org
+%7BServerConfig.appDomain%7D
%3C/co
|
bd19a22a275b7e4a308b75ea3c3d49dc52d363a3 | fix disabled seconds | app/components/settings/SettingsDataTimeRage.js | app/components/settings/SettingsDataTimeRage.js | // @flow
import React, {Component, PropTypes} from 'react';
import {DatePicker} from 'antd';
import moment from "moment";
import * as app from './../../constants/app';
//TODO: ресет значений, если отмена
//TODO: время для сегодняшнего дня
class SettingsDataTimeRage extends Component {
createRange = (start, end) => {
const result = [];
for (let i = start; i < end; i++) {
result.push(i);
}
return result;
};
disabledRangeTime = (current, type, range) => {
let disabled = {
disabledSeconds: () => {
return this.createRange(0, 60);
}
};
if (range && Array.isArray(current) && current[type === 'start' ? 0 : 1].format('YYYY-MM-DD') === range[type].format('YYYY-MM-DD')) {
let rangeHour = range[type].hour();
let rangeMinute = range[type].minute();
disabled.disabledHours = () => {
return type === 'start' ? this.createRange(0, rangeHour) : this.createRange(rangeHour + 1, 24);
};
disabled.disabledMinutes = (selectedHour) => {
if (selectedHour === rangeHour) {
return type === 'start' ? this.createRange(0, rangeMinute) : this.createRange(rangeMinute + 1, 60);
}
};
}
return disabled;
};
disabledRangeDate = (current, range) => {
let currentDate = current.clone().startOf('date');
let rangeDate = range ? {
start: range[0].clone().startOf('date'),
end: range[1].clone().startOf('date'),
} : null;
let nowDate = moment().startOf('date');
return this.filterRangeDataTime(currentDate, rangeDate, nowDate);
};
filterRangeDataTime = (current, range, now) => {
let result = true;
if (current) {
let currentMs = current.valueOf();
if (range) {
let rangeMs = [
range.start.valueOf(),
range.end.valueOf()
];
result = !currentMs.between(rangeMs, true);
} else {
let nowMs = now.valueOf();
result = current > nowMs;
}
}
return result;
};
render = () => {
return (
<DatePicker.RangePicker
disabledDate={(item) => this.disabledRangeDate(item, this.props.valueLimit)}
disabledTime={(date, type) => this.disabledRangeTime(date, type, this.props.valueLimit)}
showTime={{hideDisabledOptions: true}}
format={app.FORMAT_DATE_INPUT}
placeholder={['Start time', 'End time']}
{...this.props}
/>
);
}
}
SettingsDataTimeRage.propTypes = {
valueLimit: PropTypes.array,
};
SettingsDataTimeRage.defaultProps = {
valueLimit: null,
};
export default SettingsDataTimeRage;
| JavaScript | 0 | @@ -566,17 +566,17 @@
teRange(
-0
+1
, 60);%0A
|
342845def34b391aae6c000d57f5c6e94efa97cc | Set all textures to use nearest filter. | examples/platformer/content.js | examples/platformer/content.js | /*The MIT License (MIT)
Copyright (c) 2016 Jens Malmborg
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.*/
'use strict';
var $ = require('/../../lib/import.js').library();
class Content {
load() {
this.buffers = {
bounce: new SoundBuffer('/content/sounds/bounce.wav'),
coin: new SoundBuffer('/content/sounds/coin.wav')
};
this.textures = {
dirt: new Texture2D('/content/graphics/dirt.png'),
grass: new Texture2D('/content/graphics/grass.png'),
jump: new Texture2D('/content/graphics/jump.png'),
idle: new Texture2D('/content/graphics/idle.png'),
walk: new Texture2D('/content/graphics/walk.png'),
coin: new Texture2D('/content/graphics/coin.png'),
platform: new Texture2D('/content/graphics/platform.png'),
sky: new Texture2D('/content/graphics/sky.png'),
clouds: new Texture2D('/content/graphics/clouds.png')
};
this.sheets = {
idle: new $.SpriteSheet({
texture: this.textures.idle,
width: 16,
height: 16
}),
jump: new $.SpriteSheet({
texture: this.textures.jump,
width: 16,
height: 16
}),
walk: new $.SpriteSheet({
texture: this.textures.walk,
width: 16,
height: 16
})
};
}
}
module.exports.Content = new Content(); | JavaScript | 0 | @@ -2250,16 +2250,105 @@
%0A %7D;%0A
+ for (var key in this.textures) %7B%0A this.textures%5Bkey%5D.filter = 'nearest';%0A %7D;%0A
%7D%0A%7D%0A%0Am
|
3e1698dd13d084d8c468fc7fcdc86df03d35e5c2 | remove disabling of websockets on espruino.com, since they were needed for Espruino relay | core/serial_websocket.js | core/serial_websocket.js | /*
Gordon Williams (gw@pur3.co.uk)
*/
(function() {
if (typeof window == "undefined" || typeof WebSocket == undefined) return;
if (window.location.origin=="https://www.espruino.com" ||
window.location.origin=="https://espruino.github.io") {
console.log("Running from github/espruino.com - WebSocket support disabled");
return;
}
console.log("WebSockets support enabled - running in web browser");
var WS_ENABLED = true;
var ws;
var dataWrittenCallbacks = [];
var str2ab=function(str) {
var buf=new ArrayBuffer(str.length);
var bufView=new Uint8Array(buf);
for (var i=0; i<str.length; i++) {
var ch = str.charCodeAt(i);
if (ch>=256) {
console.warn("Attempted to send non-8 bit character - code "+ch);
ch = "?".charCodeAt(0);
}
bufView[i] = ch;
}
return buf;
};
var getPorts=function(callback) {
if (Espruino.Config.RELAY_KEY) {
callback([{path:'Web IDE Relay', description:'BLE connection via a phone', type : "bluetooth"}]);
} else {
if (!WS_ENABLED) return callback([]);
Espruino.Core.Utils.getJSONURL("/serial/ports", function(ports) {
if (ports===undefined) {
console.log("/serial/ports doesn't exist - disabling WebSocket support");
WS_ENABLED = false;
callback([]);
return;
}
if (!Array.isArray(ports)) callback([]);
else callback(ports);
});
}
};
var openSerial=function(serialPort, openCallback, receiveCallback, disconnectCallback) {
if (Espruino.Config.RELAY_KEY) {
ws = new WebSocket("wss://" + window.location.host + ":8443/", "espruino");
} else {
ws = new WebSocket("ws://" + window.location.host + "/" + serialPort, "serial");
}
dataWrittenCallbacks = [];
ws.onerror = function(event) {
connectCallback(undefined);
ws = undefined;
};
ws.onopen = function() {
if (Espruino.Config.RELAY_KEY) {
ws.send("\x10"+Espruino.Config.RELAY_KEY);
}
Espruino.callProcessor("connected", {port:serialPort}, function() {
openCallback("Hello");
});
ws.onerror = undefined;
ws.onmessage = function (event) {
//console.log("MSG:"+event.data);
if (event.data[0]=="\x00") {
receiveCallback(str2ab(event.data.substr(1)));
} else if (event.data[0]=="\x02") {
// if it's a data written callback, execute it
var c = dataWrittenCallbacks.shift();
if (c) c();
}
};
ws.onclose = function(event) {
currentDevice = undefined;
Espruino.callProcessor("disconnected", undefined, function() {
disconnectCallback();
});
ws = undefined;
};
}
};
var closeSerial=function(callback) {
if (ws) {
ws.close();
ws = undefined;
}
};
var writeSerial = function(data, callback) {
dataWrittenCallbacks.push(callback);
if (ws) ws.send("\x01"+data);
};
// ----------------------------------------------------------
Espruino.Core.Serial.devices.push({
"name" : "Websocket",
"getPorts": getPorts,
"open": openSerial,
"write": writeSerial,
"close": closeSerial,
});
if (window.location.host.substr(-16) == "www.espruino.com") {
Espruino.Core.SerialWebSocket = {
"init": function() {
Espruino.Core.Config.add("RELAY_KEY", {
section : "Communications",
name : "Relay Key",
description : "The key displayed when https://www.espruino.com/ide/relay is viewed on a phone. You'll then be able to use the Web IDE on your PC",
type : "string",
defaultValue : ""
});
}
};
}
})();
| JavaScript | 0 | @@ -128,24 +128,26 @@
n;%0A %0A if (
+/*
window.locat
@@ -187,16 +187,19 @@
.com%22 %7C%7C
+ */
%0A w
@@ -293,22 +293,8 @@
thub
-/espruino.com
- W
|
138c5e4c08d4d9cc44dc6c63bfc8279572222bf4 | Add initial game class | src/js/models/game.js | src/js/models/game.js | JavaScript | 0 | @@ -0,0 +1,2499 @@
+'use strict';%0A%0Avar Frame = require('./frame');%0A%0A/**%0A * @class Game%0A * @constructor%0A */%0Avar Game = function () %7B%0A this.frames = %5B%5D;%0A this.pinsLeftInFrame = 10;%0A%7D;%0A%0AGame.prototype = %7B%0A%0A /**%0A * Sets up game to begin%0A * @method init%0A */%0A init: function () %7B%0A this.frames = this.createFrames();%0A %7D,%0A%0A /**%0A * Adds a new roll to the game%0A * @method roll%0A */%0A roll: function () %7B%0A var rollNumber = this.getRandomNumber(this.pinsLeftInFrame);%0A%0A this.pinsLeftInFrame = this.frames%5B0%5D.roll(rollNumber);%0A%0A if (this.pinsLeftInFrame === 0) %7B%0A // If there are no pins left in the frame, the game is finished%0A this.finish();%0A %7D%0A %7D,%0A%0A /**%0A * Announce the completion of the game%0A * @method finish%0A */%0A finish: function () %7B%0A console.log('Game finished with a score of ' + this.getScore());%0A %7D,%0A%0A /**%0A * Returns the overall score of the game%0A * @method getScore%0A * @returns %7BNumber%7D%0A */%0A getScore: function () %7B%0A var score = 0,%0A iterator;%0A%0A for (iterator = 0; iterator %3C this.frames.length; iterator++) %7B%0A score += this.frames%5Biterator%5D.getScore();%0A %7D%0A%0A return score;%0A %7D,%0A%0A /**%0A * Returns a %22random%22 whole number up to a given maximum%0A * @method getRandomNumber%0A * @param %7BNumber%7D max The largest acceptable random number%0A * @returns %7BNumber%7D%0A */%0A getRandomNumber: function (max) %7B%0A return Math.floor(Math.random() * (max + 1));%0A %7D,%0A%0A /**%0A * Return a series of 10 game frames, properly linked and ready to play%0A * @method createFrames%0A * @returns %7BArray%7D%0A */%0A createFrames: function () %7B%0A var frames = %5B%5D,%0A iterator;%0A%0A // Create all ten game frames%0A for (iterator = 0; iterator %3C 10; iterator++) %7B%0A frames.push(new Frame());%0A %7D%0A%0A // Loop through frames and set up references to each frames right sibling%0A for (iterator = 0; iterator %3C 10; iterator++) %7B%0A // First frame begins as the current frame%0A if (iterator === 0) %7B%0A frames%5Binterator%5D.setCurrentFrame(true);%0A %7D%0A%0A // All frames (bar the last) must contain a pointer to the next frame in the list%0A if (iterator %3C 9) %7B%0A frames%5Biterator%5D.setNextFrame(frames%5Biterator+1%5D);%0A %7D%0A %7D%0A%0A return frames;%0A %7D%0A%7D;%0A%0Amodule.exports = Game;%0A
| |
c87155d6f9937339186d1df5d22ca27f93586685 | Fix chart rendering | app/public/angular/directive/directive.chart.js | app/public/angular/directive/directive.chart.js | var async = require("async");
var uuid = require("uuid");
angular.module('AngularApp.directives')
.directive('chart', function($rootScope, $timeout, $compile, chartData) {
return {
scope: {
data: "=",
layout: "=",
chartLayout: "="
},
restrict: "E",
replace: false,
template: '<div class="chart-wrapper chart-{{chartLayout.type}}"><b>{{chartLayout.name}}</b><div class="chart-inner"></div></div>',
//templateUrl: "html/widgets/chart.html",
link: function (scope, element, attrs) {
scope.uuid = uuid.v4();
//chartLayout: {
// name: "Histogram of Average Scores",
// type: "histogram",
// x: "avg",
// min: 0,
// max: 1,
// resolution: 0.05,
// c3: { bar: { width: { ratio: 0.5 } } }
//}
var timeoutId = null;
["chartLayout","layout","data"].forEach(function(variable) {
scope.$watch(variable, function() {
$timeout.cancel(timeoutId);
timeoutId = $timeout(function() { //
console.log("directive.chart.js:32:", "scope.chartLayout", variable, scope.chartLayout);
switch( scope.chartLayout && scope.chartLayout.type ) {
default: {
console.log("directive.chart.js:21:", "scope.chartLayout", scope.chartLayout);
break;
}
case "histogram": {
scope.chart = c3.generate($.extend(true, {
bindto: element.find('.chart-inner')[0],
data: chartData.histogram(scope.data, scope.chartLayout, scope.layout.fields)
}, scope.chartLayout.c3));
break;
}
}
}, 100);
})
})
}
}
})
.factory('chartData', function($rootScope) {
return {
histogram: function(data, chartLayout, fields) {
var x_label = fields && fields[chartLayout.x] || chartLayout.x;
var values = _.pluck(data, chartLayout.x);
var buckets = {};
if( chartLayout.hasOwnProperty("min") ) { buckets[chartLayout.min] = 0; }
if( chartLayout.hasOwnProperty("max") ) { buckets[chartLayout.max] = 0; }
for( var i=0, n=values.length; i<n; i++ ) {
var value = values[i];
if( chartLayout.precision ) {
value = parseFloat(Number(value).toPrecision(chartLayout.precision));
} else if( chartLayout.resolution ) {
value = Math.round( value / chartLayout.resolution ) * chartLayout.resolution;
value = parseFloat(Number(value).toPrecision(8)); // avoid floating point errors
}
buckets[value] = (buckets[value] || 0) + 1;
}
var output = {
x: 'x',
columns: [
Array.concat("x", _.map(_.keys(buckets), Number.parseFloat) ),
Array.concat(x_label, _.values(buckets))
],
type: 'bar'
};
console.log("directive.chart.js:76:histogram", "output", output)
return output;
}
}
})
| JavaScript | 0.000001 | @@ -1009,209 +1009,70 @@
-%5B%22chartLayout%22,%22layout%22,%22data%22%5D.forEach(function(variable) %7B%0A scope.$watch(variable, function() %7B%0A $timeout.cancel(timeoutId);%0A timeoutId = $timeout
+scope.$watchCollection(%22%5BchartLayout,layout,data%5D%22, _.debounce
(fun
@@ -1084,20 +1084,9 @@
() %7B
- //%0A
+%0A
@@ -1159,18 +1159,8 @@
ut%22,
- variable,
sco
@@ -1192,24 +1192,16 @@
-
switch(
@@ -1268,24 +1268,16 @@
-
default:
@@ -1275,32 +1275,24 @@
default: %7B%0A
-
@@ -1402,32 +1402,24 @@
-
break;%0A
@@ -1433,34 +1433,18 @@
- %7D%0A
+%7D%0A
@@ -1495,32 +1495,24 @@
-
scope.chart
@@ -1570,24 +1570,16 @@
-
bindto:
@@ -1611,24 +1611,16 @@
r')%5B0%5D,%0A
-
@@ -1743,24 +1743,16 @@
-
%7D, scope
@@ -1794,39 +1794,23 @@
- break;%0A
+break;%0A
@@ -1835,32 +1835,24 @@
-
%7D%0A
@@ -1861,36 +1861,45 @@
- %7D, 100);%0A
+$timeout(function() %7B scope.$apply();
%7D)%0A
@@ -1911,17 +1911,24 @@
%7D
-)
+, 100));
%0A
@@ -2162,13 +2162,11 @@
= _.
-pluck
+map
(dat
|
953ed56e5f4e9878b4b87cc34d6a0c2f7d168190 | Update PermissionsModal with connectURL. | assets/js/components/permissions-modal/index.js | assets/js/components/permissions-modal/index.js | /**
* PermissionsModal component.
*
* Site Kit by Google, Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* WordPress dependencies
*/
import { __ } from '@wordpress/i18n';
import { useCallback } from '@wordpress/element';
/**
* Internal dependencies
*/
import Data from 'googlesitekit-data';
import { STORE_NAME as CORE_USER } from '../../googlesitekit/datastore/user';
import Dialog from '../dialog';
import Modal from '../modal';
const { useSelect, useDispatch } = Data;
const PermissionsModal = ( { dataStoreToSnapshot } ) => {
const permissionsError = useSelect( ( select ) => select( CORE_USER ).getPermissionScopeError() );
const { clearPermissionScopeError } = useDispatch( CORE_USER );
// TODO: This should come from the API response or a router, not a prop.
const { takeSnapshot } = useDispatch( dataStoreToSnapshot );
const onCancel = useCallback( () => {
clearPermissionScopeError();
}, [ clearPermissionScopeError ] );
const onConfirm = useCallback( async () => {
// If we have a datastores to snapshot before navigating away to the
// authorization page, do that first.
if ( dataStoreToSnapshot ) {
await takeSnapshot();
}
// TODO: Add provisioning API URL here.
global.location.assign( permissionsError.data.scopes.join( ',' ) );
}, [ dataStoreToSnapshot, permissionsError ] );
if ( ! permissionsError ) {
return null;
}
// If there aren't any scopes for us to request, there's no reason to show
// the modal. Log a console warning if this happens and return `null`.
if ( permissionsError && permissionsError.data && permissionsError.data.scopes && permissionsError.data.scopes.length === 0 ) {
global.console.warn( 'permissionsError lacks scopes array to use for redirect, so not showing the PermissionsModal. permissionsError was:', permissionsError );
return null;
}
return (
<Modal>
<Dialog
dialogActive={ true }
handleConfirm={ onConfirm }
handleDialog={ onCancel }
title={ __( 'Additional Permissions Required', 'google-site-kit' ) }
subtitle={ permissionsError.message }
confirmButton={ __( 'Authorize additional permissions', 'google-site-kit' ) }
provides={ [] }
/>
</Modal>
);
};
export default PermissionsModal;
| JavaScript | 0 | @@ -1180,16 +1180,176 @@
or() );%0A
+%09const additionalScopes = permissionsError?.data?.scopes;%0A%09const connectURL = useSelect( ( select ) =%3E select( CORE_USER ).getConnectURL( additionalScopes ) );%0A
%09const %7B
@@ -1874,114 +1874,42 @@
%0A%0A%09%09
-// TODO: Add provisioning API URL here.%0A%09%09global.location.assign( permissionsError.data.scopes.join( ',' )
+global.location.assign( connectURL
);%0A
@@ -1935,32 +1935,26 @@
apshot,
-permissionsError
+connectURL
%5D );%0A%0A%09
|
1fc46db23a6a3520661c0e0ac97112237f5c47f7 | Rebase mistakes | src/js/structs/Job.js | src/js/structs/Job.js | import DateUtil from '../utils/DateUtil';
import Item from './Item';
import JobActiveRunList from './JobActiveRunList';
module.exports = class Job extends Item {
getActiveRuns() {
return new JobActiveRunList({items: this.get('activeRuns')});
}
getCommand() {
const {cmd} = this.get('run') || {};
return cmd;
}
getCpus() {
// Default to the minimum number of cpus per Mesos offer
const {cpus = 0.01} = this.get('run') || {};
return cpus;
}
getDescription() {
return this.get('description');
}
getDocker() {
const {docker = {}} = this.get('run') || {};
return docker;
}
getDisk() {
const {disk = 0} = this.get('run') || {};
return disk;
}
getId() {
return this.get('id');
}
getLabels() {
return this.get('labels') || {};
}
getMem() {
const {mem = 32} = this.get('run') || {};
return mem;
}
getLastRunStatus() {
let {lastFailureAt = null, lastSuccessAt = null} = this.getStatus();
let status = 'N/A';
let time = null;
if (lastFailureAt !== null) {
lastFailureAt = DateUtil.strToMs(lastFailureAt);
}
if (lastSuccessAt !== null) {
lastSuccessAt = DateUtil.strToMs(lastSuccessAt);
}
if (lastFailureAt !== null || lastSuccessAt !== null) {
if (lastFailureAt > lastSuccessAt) {
status = 'Failed';
time = lastFailureAt;
} else {
status = 'Success';
time = lastSuccessAt;
}
}
return {status, time};
}
getLastRunStatus() {
let {lastFailureAt, lastSuccessAt} = this.get('status');
lastFailureAt = DateUtil.strToMs(lastFailureAt);
lastSuccessAt = DateUtil.strToMs(lastSuccessAt);
if (lastFailureAt > lastSuccessAt) {
return {status: 'Failed', time: lastFailureAt};
}
return {status: 'Success', time: lastSuccessAt};
}
getName() {
return this.getId().split('.').pop();
}
getSchedules() {
return this.get('schedules') || [];
}
getScheduleStatus() {
let activeRuns = this.getActiveRuns();
if (activeRuns.getItems().length > 0) {
let longestRunningActiveRun = activeRuns.getLongestRunningActiveRun();
return longestRunningActiveRun.getStatus();
}
if (this.getSchedules().length > 0) {
let schedule = this.getSchedules()[0];
if (!!schedule && schedule.enabled) {
return 'scheduled';
}
}
return 'completed';
}
getStatus() {
return this.get('status') || {};
}
};
| JavaScript | 0.000004 | @@ -1551,16 +1551,23 @@
ailureAt
+ = null
, lastSu
@@ -1573,16 +1573,23 @@
uccessAt
+ = null
%7D = this
@@ -1604,16 +1604,98 @@
atus');%0A
+ let status = 'N/A';%0A let time = null;%0A%0A if (lastFailureAt !== null) %7B%0A
last
@@ -1735,24 +1735,67 @@
FailureAt);%0A
+ %7D%0A%0A if (lastSuccessAt !== null) %7B%0A
lastSucc
@@ -1834,16 +1834,22 @@
cessAt);
+%0A %7D
%0A%0A if
@@ -1856,33 +1856,43 @@
(lastFailureAt
-%3E
+!== null %7C%7C
lastSuccessAt)
@@ -1881,32 +1881,41 @@
%7C%7C lastSuccessAt
+ !== null
) %7B%0A return
@@ -1908,31 +1908,69 @@
%7B%0A
-return %7B
+if (lastFailureAt %3E lastSuccessAt) %7B%0A
status
-:
+ =
'Failed
@@ -1970,23 +1970,32 @@
'Failed'
-,
+;%0A
time
-:
+ =
lastFai
@@ -2004,37 +2004,41 @@
reAt
-%7D
;%0A
+
%7D
-%0A%0A return %7B
+ else %7B%0A
status
-:
+ =
'Su
@@ -2047,15 +2047,24 @@
ess'
-,
+;%0A
time
-:
+ =
las
@@ -2073,16 +2073,57 @@
uccessAt
+;%0A %7D%0A %7D%0A%0A return %7Bstatus, time
%7D;%0A %7D%0A%0A
|
d0e0a1bb7995cad2f06e361a6ef314db6eb6fb2d | Connect project storages counter to sidebar label (WAL-52) | app/scripts/controllers/projects-controllers.js | app/scripts/controllers/projects-controllers.js | 'use strict';
(function() {
angular.module('ncsaas')
.controller('ProjectAddController', [
'projectsService',
'currentStateService',
'baseControllerAddClass',
'$rootScope',
'$state',
'ncUtilsFlash',
ProjectAddController]);
function ProjectAddController(
projectsService,
currentStateService,
baseControllerAddClass,
$rootScope,
$state,
ncUtilsFlash) {
var controllerScope = this;
var ProjectController = baseControllerAddClass.extend({
userRole: 'admin',
init: function() {
this.service = projectsService;
this.controllerScope = controllerScope;
this._super();
this.detailsState = 'project.details';
this.redirectToDetailsPage = true;
this.project = this.instance;
},
activate: function() {
var vm = this;
currentStateService.getCustomer().then(function(customer) {
vm.project.customer = customer.url;
});
},
afterSave: function(project) {
$rootScope.$broadcast('refreshProjectList', {
model: project, new: true, current: true
});
this._super();
},
onError: function(errorObject) {
ncUtilsFlash.error(errorObject.data.detail);
},
cancel: function() {
currentStateService.getCustomer().then(function(customer) {
$state.go('organization.projects', {uuid: customer.uuid});
});
}
});
controllerScope.__proto__ = new ProjectController();
}
})();
(function() {
angular.module('ncsaas')
.controller('ProjectDetailsController', ProjectDetailsController);
ProjectDetailsController.$inject = [
'$scope', 'currentStateService', 'tabCounterService',
'eventsService', 'projectsService', '$state', 'AppStoreUtilsService'
];
function ProjectDetailsController(
$scope, currentStateService, tabCounterService,
eventsService, projectsService, $state, AppStoreUtilsService) {
activate();
function activate() {
$scope.items = [
{
icon: "fa-th-large",
label: "Dashboard",
link: "project.details({uuid: context.project.uuid})",
},
{
icon: "fa-shopping-cart",
label: "Service store",
feature: "appstore",
action: AppStoreUtilsService.openDialog,
state: "appstore",
},
{
label: "Resources",
icon: "fa-files-o",
link: "project.resources",
children: [
{
link: "project.resources.vms({uuid: context.project.uuid})",
icon: "fa-desktop",
label: "Virtual machines",
feature: "vms",
countFieldKey: "vms"
},
{
link: "project.resources.clouds({uuid: context.project.uuid})",
icon: "fa-cloud",
label: "Private clouds",
feature: "private_clouds",
countFieldKey: "private_clouds"
},
{
link: "project.resources.apps({uuid: context.project.uuid})",
icon: "fa-cube",
label: "Applications",
feature: "apps",
countFieldKey: "apps"
},
{
link: "project.resources.storage({uuid: context.project.uuid})",
icon: "fa-hdd-o",
label: "Storage",
feature: "storage"
}
]
},
{
link: "project.support({uuid: context.project.uuid})",
icon: "fa-question-circle",
label: "Support",
feature: "premiumSupport",
countFieldKey: "premium_support_contracts"
},
{
link: "project.events({uuid: context.project.uuid})",
icon: "fa-bell-o",
label: "Audit logs",
feature: "eventlog"
},
{
link: "project.alerts({uuid: context.project.uuid})",
icon: "fa-fire",
label: "Alerts",
feature: "alerts",
countFieldKey: "alerts"
},
{
link: "project.delete({uuid: context.project.uuid})",
icon: "fa-wrench",
label: "Manage"
}
];
$scope.$on('currentProjectUpdated', function() {
refreshProject();
});
$scope.$on('authService:signin', function() {
refreshProject();
});
refreshProject();
}
function refreshProject() {
currentStateService.getProject().then(function(project) {
$scope.currentProject = project;
$scope.context = {project: project};
connectCounters(project);
});
}
function connectCounters(project) {
if ($scope.timer) {
tabCounterService.cancel($scope.timer);
}
$scope.timer = tabCounterService.connect({
$scope: $scope,
tabs: $scope.items,
getCounters: getCounters.bind(null, project),
getCountersError: getCountersError
});
}
function getCounters(project) {
var query = angular.extend(
{UUID: project.uuid},
eventsService.defaultFilter
);
return projectsService.getCounters(query);
}
function getCountersError(error) {
if (error.status == 404) {
projectsService.getFirst().then(function(project) {
$state.go('project.details', {uuid: project.uuid});
});
} else {
tabCounterService.cancel($scope.timer);
}
}
}
})();
| JavaScript | 0 | @@ -3470,24 +3470,65 @@
e: %22storage%22
+,%0A countFieldKey: %22storages%22
%0A
|
4fc25e12f38ab101f8788d6b729b701c6c5e01fe | Make specifiedByUrl in IntrospectionScalarType's flow type optional (#2788) | src/utilities/getIntrospectionQuery.js | src/utilities/getIntrospectionQuery.js | import type { DirectiveLocationEnum } from '../language/directiveLocation';
export type IntrospectionOptions = {|
// Whether to include descriptions in the introspection result.
// Default: true
descriptions?: boolean,
// Whether to include `specifiedByUrl` in the introspection result.
// Default: false
specifiedByUrl?: boolean,
// Whether to include `isRepeatable` field on directives.
// Default: false
directiveIsRepeatable?: boolean,
// Whether to include `description` field on schema.
// Default: false
schemaDescription?: boolean,
|};
export function getIntrospectionQuery(options?: IntrospectionOptions): string {
const optionsWithDefault = {
descriptions: true,
specifiedByUrl: false,
directiveIsRepeatable: false,
schemaDescription: false,
...options,
};
const descriptions = optionsWithDefault.descriptions ? 'description' : '';
const specifiedByUrl = optionsWithDefault.specifiedByUrl
? 'specifiedByUrl'
: '';
const directiveIsRepeatable = optionsWithDefault.directiveIsRepeatable
? 'isRepeatable'
: '';
const schemaDescription = optionsWithDefault.schemaDescription
? descriptions
: '';
return `
query IntrospectionQuery {
__schema {
${schemaDescription}
queryType { name }
mutationType { name }
subscriptionType { name }
types {
...FullType
}
directives {
name
${descriptions}
${directiveIsRepeatable}
locations
args {
...InputValue
}
}
}
}
fragment FullType on __Type {
kind
name
${descriptions}
${specifiedByUrl}
fields(includeDeprecated: true) {
name
${descriptions}
args {
...InputValue
}
type {
...TypeRef
}
isDeprecated
deprecationReason
}
inputFields {
...InputValue
}
interfaces {
...TypeRef
}
enumValues(includeDeprecated: true) {
name
${descriptions}
isDeprecated
deprecationReason
}
possibleTypes {
...TypeRef
}
}
fragment InputValue on __InputValue {
name
${descriptions}
type { ...TypeRef }
defaultValue
}
fragment TypeRef on __Type {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
ofType {
kind
name
}
}
}
}
}
}
}
}
`;
}
export type IntrospectionQuery = {|
+__schema: IntrospectionSchema,
|};
export type IntrospectionSchema = {|
+description?: ?string,
+queryType: IntrospectionNamedTypeRef<IntrospectionObjectType>,
+mutationType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>,
+subscriptionType: ?IntrospectionNamedTypeRef<IntrospectionObjectType>,
+types: $ReadOnlyArray<IntrospectionType>,
+directives: $ReadOnlyArray<IntrospectionDirective>,
|};
export type IntrospectionType =
| IntrospectionScalarType
| IntrospectionObjectType
| IntrospectionInterfaceType
| IntrospectionUnionType
| IntrospectionEnumType
| IntrospectionInputObjectType;
export type IntrospectionOutputType =
| IntrospectionScalarType
| IntrospectionObjectType
| IntrospectionInterfaceType
| IntrospectionUnionType
| IntrospectionEnumType;
export type IntrospectionInputType =
| IntrospectionScalarType
| IntrospectionEnumType
| IntrospectionInputObjectType;
export type IntrospectionScalarType = {|
+kind: 'SCALAR',
+name: string,
+description?: ?string,
+specifiedByUrl: ?string,
|};
export type IntrospectionObjectType = {|
+kind: 'OBJECT',
+name: string,
+description?: ?string,
+fields: $ReadOnlyArray<IntrospectionField>,
+interfaces: $ReadOnlyArray<
IntrospectionNamedTypeRef<IntrospectionInterfaceType>,
>,
|};
export type IntrospectionInterfaceType = {|
+kind: 'INTERFACE',
+name: string,
+description?: ?string,
+fields: $ReadOnlyArray<IntrospectionField>,
+interfaces: $ReadOnlyArray<
IntrospectionNamedTypeRef<IntrospectionInterfaceType>,
>,
+possibleTypes: $ReadOnlyArray<
IntrospectionNamedTypeRef<IntrospectionObjectType>,
>,
|};
export type IntrospectionUnionType = {|
+kind: 'UNION',
+name: string,
+description?: ?string,
+possibleTypes: $ReadOnlyArray<
IntrospectionNamedTypeRef<IntrospectionObjectType>,
>,
|};
export type IntrospectionEnumType = {|
+kind: 'ENUM',
+name: string,
+description?: ?string,
+enumValues: $ReadOnlyArray<IntrospectionEnumValue>,
|};
export type IntrospectionInputObjectType = {|
+kind: 'INPUT_OBJECT',
+name: string,
+description?: ?string,
+inputFields: $ReadOnlyArray<IntrospectionInputValue>,
|};
export type IntrospectionListTypeRef<
T: IntrospectionTypeRef = IntrospectionTypeRef,
> = {|
+kind: 'LIST',
+ofType: T,
|};
export type IntrospectionNonNullTypeRef<
T: IntrospectionTypeRef = IntrospectionTypeRef,
> = {|
+kind: 'NON_NULL',
+ofType: T,
|};
export type IntrospectionTypeRef =
| IntrospectionNamedTypeRef<>
| IntrospectionListTypeRef<>
| IntrospectionNonNullTypeRef<
IntrospectionNamedTypeRef<> | IntrospectionListTypeRef<>,
>;
export type IntrospectionOutputTypeRef =
| IntrospectionNamedTypeRef<IntrospectionOutputType>
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>
| IntrospectionNonNullTypeRef<
| IntrospectionNamedTypeRef<IntrospectionOutputType>
| IntrospectionListTypeRef<IntrospectionOutputTypeRef>,
>;
export type IntrospectionInputTypeRef =
| IntrospectionNamedTypeRef<IntrospectionInputType>
| IntrospectionListTypeRef<IntrospectionInputTypeRef>
| IntrospectionNonNullTypeRef<
| IntrospectionNamedTypeRef<IntrospectionInputType>
| IntrospectionListTypeRef<IntrospectionInputTypeRef>,
>;
export type IntrospectionNamedTypeRef<
T: IntrospectionType = IntrospectionType,
> = {|
+kind: $PropertyType<T, 'kind'>,
+name: string,
|};
export type IntrospectionField = {|
+name: string,
+description?: ?string,
+args: $ReadOnlyArray<IntrospectionInputValue>,
+type: IntrospectionOutputTypeRef,
+isDeprecated: boolean,
+deprecationReason: ?string,
|};
export type IntrospectionInputValue = {|
+name: string,
+description?: ?string,
+type: IntrospectionInputTypeRef,
+defaultValue: ?string,
|};
export type IntrospectionEnumValue = {|
+name: string,
+description?: ?string,
+isDeprecated: boolean,
+deprecationReason: ?string,
|};
export type IntrospectionDirective = {|
+name: string,
+description?: ?string,
+isRepeatable?: boolean,
+locations: $ReadOnlyArray<DirectiveLocationEnum>,
+args: $ReadOnlyArray<IntrospectionInputValue>,
|};
| JavaScript | 0 | @@ -4016,16 +4016,17 @@
iedByUrl
+?
: ?strin
|
26fa595f3166e2d7fa7d8d16319ff57fef015dc7 | Update validation util function definitions. | assets/js/modules/tagmanager/util/validation.js | assets/js/modules/tagmanager/util/validation.js | /**
* Validation utilities.
*
* Site Kit by Google, Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* Internal dependencies
*/
import { ACCOUNT_CREATE, CONTAINER_CREATE, CONTEXT_WEB, CONTEXT_AMP } from '../datastore/constants';
/**
* Checks the given value to see if it is a positive integer.
*
* @since n.e.x.t
*
* @param {*} input Value to check.
* @return {boolean} Validity.
*/
const isValidNumericID = function( input ) {
const id = parseInt( input, 10 ) || 0;
return id > 0;
};
/**
* Checks if the given account ID appears to be a valid Tag Manager account.
*
* @since n.e.x.t
*
* @param {(string|number)} accountID Account ID to test.
* @return {boolean} Whether or not the given account ID is valid.
*/
export { isValidNumericID as isValidAccountID };
/**
* Checks if the given value is a valid selection for an Account.
*
* @since n.e.x.t
*
* @param {?string} value Selected value
* @return {boolean} True if valid, otherwise false.
*/
export function isValidAccountSelection( value ) {
if ( value === ACCOUNT_CREATE ) {
return true;
}
return isValidNumericID( value );
}
/**
* Checks if the given container ID appears to be a valid GTM container.
*
* @since n.e.x.t
*
* @param {string} containerID Container ID to check.
* @return {boolean} Whether or not the given container ID is valid.
*/
export function isValidContainerID( containerID ) {
return !! containerID?.toString?.()?.match?.( /^GTM-[A-Z0-9]+$/ );
}
/**
* Checks if the given value is a valid selection for a container.
*
* @since n.e.x.t
*
* @param {?string} value Selected value
* @return {boolean} True if valid, otherwise false.
*/
export function isValidContainerSelection( value ) {
if ( value === CONTAINER_CREATE ) {
return true;
}
return isValidContainerID( value );
}
/**
* Checks if the given internal container ID appears to be valid.
*
* @since n.e.x.t
*
* @param {(string|number)} internalContainerID Internal container ID to test.
* @return {boolean} Whether or not the given ID is valid.
*/
export { isValidNumericID as isValidInternalContainerID };
/**
* Checks if the given context is a valid container usage context.
*
* @since n.e.x.t
*
* @param {string} context A usage context to check.
* @return {boolean} Whether or not the given context is valid.
*/
export function isValidUsageContext( context ) {
return [ CONTEXT_WEB, CONTEXT_AMP ].includes( context );
}
| JavaScript | 0 | @@ -1277,33 +1277,40 @@
%0A */%0Aexport
-%7B
+function
isValid
NumericID as
@@ -1301,29 +1301,60 @@
alid
-Numeric
+Account
ID
+(
a
-s isValidA
+ccountID ) %7B%0A%09return isValidNumericID( a
ccou
@@ -1358,18 +1358,20 @@
countID
+);%0A
%7D
-;
%0A%0A/**%0A *
@@ -1672,31 +1672,31 @@
turn isValid
-Numeric
+Account
ID( value );
@@ -2639,38 +2639,96 @@
ort
-%7B isValidNumericID as isValidI
+function isValidInternalContainerID( internalContainerID ) %7B%0A%09return isValidNumericID( i
nter
@@ -2742,18 +2742,20 @@
ainerID
+);%0A
%7D
-;
%0A%0A/**%0A *
|
c931b25351aab1bfe643c7b6ed38750f433e6260 | Align to center | src/routes/StudentInfo/StudentInfo.js | src/routes/StudentInfo/StudentInfo.js | import React, { Component, PropTypes } from 'react'
// import Table from '../../../components/table/Table'
import { staticID } from '../../utils/unique'
import { studentHeader } from '../../routes/Student/components/studentHeader'
import { Line } from 'react-chartjs-2'
import TableFrame from '../../components/table/TableFrame/'
const gpaGraphOption = {
maintainAspectRatio: false,
elements: {
line: {
tension: 0.00001,
borderWidth: 1
},
point: {
radius: 4,
hitRadius: 10,
hoverRadius: 4,
backgroundColor: '#FFF'
}
},
scales: {
yAxes: [{
display: true,
ticks: {
beginAtZero: true,
max: 4
}
}]
}
}
function convertHex (hex, opacity) {
hex = hex.replace('#', '')
var r = parseInt(hex.substring(0, 2), 16)
var g = parseInt(hex.substring(2, 4), 16)
var b = parseInt(hex.substring(4, 6), 16)
var result = 'rgba(' + r + ',' + g + ',' + b + ',' + opacity + ')'
return result
}
class StudentInfo extends Component {
static propTypes = {
params: PropTypes.object.isRequired
}
constructor (props) {
super(props)
this.state = {
data: {},
enrollTableData: [],
gradeData: []
}
this.enrollTableHeader = [
{ title: 'รหัสวิชา', prop: 'course_no' },
{ title: 'ชื่อวิชา', prop: 'course_name' },
{ title: 'รายละเอียด', prop: 'course_description' },
{ title: 'ประเภท', prop: 'course_type' },
{ title: 'เกรด', prop: 'grade' }
]
this.tableID = staticID('StudentInfo.table')
fetch(`/api/student/id/${props.params.id}`)
.then((result) => result.json())
.then((result) => {
this.setState({
data: result.data
})
})
.catch((err) => {
console.error(err)
})
fetch(`/api/student/enrolls/${props.params.id}`)
.then((result) => result.json())
.then((result) => {
this.setState({
enrollTableData: result.data
})
})
.catch((err) => {
console.error(err)
})
fetch(`/api/student/grade/${props.params.id}`)
.then((result) => result.json())
.then((result) => {
console.log(result.data)
this.setState({
gradeData: result.data
})
})
.catch((err) => {
console.error(err)
})
}
getChartData () {
let gpaBar = []
let gpaxBar = []
let dataLabel = []
for (const grade of this.state.gradeData) {
gpaBar.push(grade.gpa)
gpaxBar.push(grade.gpax)
dataLabel.push(`${grade.year}-${grade.semester}`)
}
return {
labels: dataLabel,
datasets: [
{
data: gpaBar,
label: 'GPA',
borderColor: '#63c2de',
backgroundColor: convertHex('#63c2de', 0.15),
pointBackgroundColor: '#fff',
borderWidth: 1
},
{
data: gpaxBar,
label: 'GPAX',
borderColor: '#ad42f4',
backgroundColor: convertHex('#ad42f4', 0.15),
pointBackgroundColor: '#fff',
borderWidth: 1
}
]
}
}
userInfoContent () {
if (!this.state.data) {
return <i>This user is not available.</i>
} else {
let contentResult = []
for (const prop in this.state.data) {
let thaiProp = studentHeader.find((x) => x.prop === prop)
if (!thaiProp) continue
thaiProp = thaiProp.title ? thaiProp.title : ''
contentResult.push(<dt className='col-sm-4' key={prop}>{thaiProp}</dt>)
contentResult.push(<dd className='col-sm-8' key={prop + 'dd'}>{this.state.data[prop] || ''}</dd>)
}
return <dl className='row'>{contentResult}</dl>
}
}
render () {
// const config = TableConfig
// return (<Table id={this.tableID} config={config} />)
return <div className='row'>
<div className='col-md-8'>
<div className='card'>
<div className='card-block'>
<div className='row'>
<div className='col-sm-5'>
<h4 className='card-title mb-0'>Student Information</h4>
<div className='small text-muted'>Summary information of student</div>
</div>
</div>
{(this.state.data && this.state.data.hasOwnProperty('student_id')
? (
<div>
<div className='row mt-4'>
<div className='col-sm-3'>
<img src={`/img/placeholder/profile-${this.state.data.gender}.png`} className='img-fluid' />
</div>
<div className='col-sm-9'>
{this.userInfoContent()}
</div>
</div>
<hr />
<div className='chart-wrapper' style={{ margin: '1em 0' }}>
<h3 className='mb-3'>Student GPA & GPAX</h3>
<div>
<Line data={this.getChartData()} options={gpaGraphOption} height={300} />
</div>
</div>
<hr />
<div>
<h4 className='mb-3'>Enrolled Courses</h4>
<TableFrame
className='table table-responsive table-bordered table-striped table-md'
header={this.enrollTableHeader}
data={this.state.enrollTableData} />
</div>
</div>
)
: (<div style={{ margin: '1em 0' }}><i>Student is not available.</i></div>)
)}
</div>
</div>
</div>
</div>
}
}
export default StudentInfo
| JavaScript | 0.000001 | @@ -3902,16 +3902,28 @@
col-md-8
+ offset-md-2
'%3E%0A
|
c080287933678db12031229f3ab54d4ce9e6596a | Fix typo | src/rules/no-useless-path-segments.js | src/rules/no-useless-path-segments.js | /**
* @fileOverview Ensures that there are no useless path segments
* @author Thomas Grainger
*/
import path from 'path'
import sumBy from 'lodash/sumBy'
import resolve from 'eslint-module-utils/resolve'
import moduleVisitor from 'eslint-module-utils/moduleVisitor'
/**
* convert a potentialy relative path from node utils into a true
* relative path.
*
* ../ -> ..
* ./ -> .
* .foo/bar -> ./.foo/bar
* ..foo/bar -> ./..foo/bar
* foo/bar -> ./foo/bar
*
* @param rel {string} relative posix path potentially missing leading './'
* @returns {string} relative posix path that always starts with a ./
**/
function toRel(rel) {
const stripped = rel.replace(/\/$/g, '')
return /^((\.\.)|(\.))($|\/)/.test(stripped) ? stripped : `./${stripped}`
}
function normalize(fn) {
return toRel(path.posix.normalize(fn))
}
const countRelParent = x => sumBy(x, v => v === '..')
module.exports = {
meta: { fixable: 'code' },
create: function (context) {
const currentDir = path.dirname(context.getFilename())
function checkSourceValue(source) {
const { value } = source
function report(proposed) {
context.report({
node: source,
message: `Useless path segments for "${value}", should be "${proposed}"`,
fix: fixer => fixer.replaceText(source, JSON.stringify(proposed)),
})
}
if (!value.startsWith('.')) {
return
}
const resolvedPath = resolve(value, context)
const normed = normalize(value)
if (normed !== value && resolvedPath === resolve(normed, context)) {
return report(normed)
}
if (value.startsWith('./')) {
return
}
if (resolvedPath === undefined) {
return
}
const expected = path.relative(currentDir, resolvedPath)
const expectedSplit = expected.split(path.sep)
const valueSplit = value.replace(/^\.\//, '').split('/')
const valueNRelParents = countRelParent(valueSplit)
const expectedNRelParents = countRelParent(expectedSplit)
const diff = valueNRelParents - expectedNRelParents
if (diff <= 0) {
return
}
return report(
toRel(valueSplit
.slice(0, expectedNRelParents)
.concat(valueSplit.slice(valueNRelParents + diff))
.join('/'))
)
}
return moduleVisitor(checkSourceValue, context.options[0])
},
}
| JavaScript | 0.999999 | @@ -290,16 +290,17 @@
otential
+l
y relati
|
a6b24f6af3b3fc1bc2d42e8fecf7a5609329ec34 | Make callbacks-baseline correct | benchmark/madeup-parallel/callbacks-baseline.js | benchmark/madeup-parallel/callbacks-baseline.js | require('../lib/fakes');
module.exports = function upload(stream, idOrPath, tag, done) {
var tx = db.begin();
var current = 0;
var total = global.parallelQueries;
function callback(err) {
if( err ) {
tx.rollback();
done(err);
}
else {
current++;
if( current === total ) {
tx.commit();
done();
}
}
}
for( var i = 0; i < total; ++i ) {
FileVersion.insert({index: i}).execWithin(tx, callback);
}
}
| JavaScript | 0.999908 | @@ -174,45 +174,220 @@
s;%0A%0A
+%0A%0A
f
-unction callback(err) %7B%0A
+or( var i = 0; i %3C total; ++i ) %7B%0A FileVersion.insert(%7Bindex: i%7D).execWithin(tx, function onComplete(err) %7B%0A if (onComplete.called) return;%0A onComplete.called = true;%0A
if(
@@ -378,24 +378,27 @@
e;%0A
+
if( err ) %7B%0A
@@ -393,24 +393,28 @@
if( err ) %7B%0A
+
@@ -436,24 +436,28 @@
+
+
done(err);%0A
@@ -455,16 +455,20 @@
e(err);%0A
+
@@ -477,16 +477,20 @@
+
else %7B%0A
@@ -500,16 +500,20 @@
+
+
current+
@@ -515,16 +515,20 @@
rent++;%0A
+
@@ -573,16 +573,20 @@
+
+
tx.commi
@@ -586,24 +586,28 @@
x.commit();%0A
+
@@ -631,131 +631,40 @@
- %7D%0A
-
%7D%0A
-%7D%0A%0A
-for( var i = 0; i %3C total; ++i ) %7B%0A FileVersion.insert(%7Bindex: i%7D).execWithin(tx, callback
+ %7D%0A %7D
);%0A
|
fa037453fcc3b91a91a8c94741ea03f6ab2a57a9 | Switch to fetch() to remove axios dependency | src/web/store/splatoon/data.js | src/web/store/splatoon/data.js | import axios from 'axios';
let updateDataTimer;
export const namespaced = true;
// State, actions, and mutators are identical for each data source, so this module
// generates them automatically from a list of data sources.
let dataSources = [
{
name: 'schedules',
url: '/data/schedules.json',
},
{
name: 'coop_schedules',
url: '/data/coop-schedules.json',
},
{
name: 'timeline',
url: '/data/timeline.json',
},
{
name: 'festivals',
url: '/data/festivals.json',
},
{
name: 'merchandises',
url: '/data/merchandises.json',
},
];
// Automatically determine the update action name and mutation name
for (let source of dataSources) {
// Action: updateSourceName
source.actionName = 'update' + source.name[0].toUpperCase() + source.name.substr(1);
// Mutation: UPDATE_SOURCENAME
source.mutationName = 'UPDATE_' + source.name.toUpperCase();
}
export const state = { };
export const actions = {
updateLanguage({ dispatch, rootGetters }) {
let language = rootGetters['splatoon/languages/selectedLanguage'];
if (language) {
axios.get(`/data/locale/${language.language}.json`)
.then(response => dispatch('i18n/addLocale', {
locale: language.language,
translations: { splatnet: response.data },
}, { root: true }))
.catch(e => console.error(e));
}
},
updateAll({ dispatch }) {
return Promise.all([
dispatch('updateLanguage'),
...dataSources.map(source => dispatch(source.actionName)),
]);
},
startUpdatingData({ dispatch }) {
if (updateDataTimer)
return;
dispatch('updateAll');
let date = new Date;
// If we're more than 20 seconds past the current hour, schedule the update for the next hour
if (date.getMinutes() !== 0 || date.getSeconds() >= 20)
date.setHours(date.getHours() + 1);
date.setMinutes(0);
// Random number of seconds past the hour (so all open browsers don't hit the server at the same time)
let minSec = 25;
let maxSec = 60;
date.setSeconds(Math.floor(Math.random() * (maxSec - minSec + 1)) + minSec);
// Set the timeout
updateDataTimer = setTimeout(() => {
updateDataTimer = null;
dispatch('startUpdatingData');
}, (date - new Date));
},
stopUpdatingData() {
clearInterval(updateDataTimer);
updateDataTimer = null;
},
};
export const mutations = { };
for (let source of dataSources) {
// State
state[source.name] = null;
// Actions
actions[source.actionName] = ({ commit }) => {
axios.get(source.url)
.then(({ data }) => commit(source.mutationName, { data }))
.catch(e => console.error(e));
};
// Mutations
mutations[source.mutationName] = (state, { data }) => {
state[source.name] = data;
};
}
| JavaScript | 0 | @@ -1,32 +1,4 @@
-import axios from 'axios';%0A%0A
let
@@ -1154,25 +1154,21 @@
-axios.get
+fetch
(%60/data/
@@ -1231,24 +1231,71 @@
(response =%3E
+ response.json())%0A .then(data =%3E
dispatch('i
@@ -1405,25 +1405,16 @@
latnet:
-response.
data %7D,%0A
@@ -1452,54 +1452,8 @@
%7D))
-%0A .catch(e =%3E console.error(e))
;%0A
@@ -2802,16 +2802,22 @@
nName%5D =
+ async
(%7B comm
@@ -2839,17 +2839,13 @@
-axios.get
+fetch
(sou
@@ -2875,18 +2875,59 @@
hen(
-(%7B
+response =%3E response.json())%0A .then(
data
- %7D)
=%3E
@@ -2968,50 +2968,8 @@
%7D))
-%0A .catch(e =%3E console.error(e))
;%0A
|
aa7363e1213bc4d1dc81f648473c1ee35dd83f2c | add contentful attribution | src/layouts/footer.js | src/layouts/footer.js | import React, { Component } from "react";
import styled from "styled-components";
import SoftBricksLogo from "../components/softbricks-logo";
import ResponsiveContainer from "../components/responsive-container";
import Nav from "../components/nav";
import Text from "../components/text";
import Center from "../components/center";
import Inset from "../components/inset";
import Toolbar from "../components/toolbar";
import colors from "../constants/colors";
const FooterContainer = styled.footer`
background-color: ${colors.black};
padding: 32px 0;
`;
const Copyright = styled(Text.Detail)`
padding: 32px 0 0;
color: ${colors.white5};
`
export default class Footer extends Component {
render() {
return (
<FooterContainer>
<ResponsiveContainer>
<Toolbar>
<SoftBricksLogo />
<div className="footer-links">
<Nav />
</div>
</Toolbar>
<Center>
<Copyright>© 2017 SoftBricks. All Rights Reserved</Copyright>
</Center>
</ResponsiveContainer>
</FooterContainer>
);
}
}
| JavaScript | 0.000001 | @@ -361,24 +361,65 @@
nts/inset%22;%0A
+import Stack from %22../components/stack%22;%0A
import Toolb
@@ -447,24 +447,24 @@
s/toolbar%22;%0A
-
import color
@@ -680,16 +680,17 @@
ite5%7D;%0A%60
+;
%0A%0Aexport
@@ -978,32 +978,85 @@
%3CCenter%3E%0A
+ %3CStack alignItems=%22center%22 scale=%22xl%22%3E%0A
%3CCop
@@ -1113,16 +1113,527 @@
yright%3E%0A
+ %3Ca%0A href=%22https://www.contentful.com/%22%0A rel=%22nofollow%22%0A target=%22_blank%22%0A %3E%0A %3Cimg%0A src=%22https://images.contentful.com/fo9twyrwpveg/7Htleo27dKYua8gio8UEUy/0797152a2d2f8e41db49ecbf1ccffdaa/PoweredByContentful_DarkBackground_MonochromeLogo.svg%22%0A style=%7B%7B maxWidth: 100, width: '100%25' %7D%7D%0A alt=%22Powered by Contentful%22%0A /%3E%0A %3C/a%3E%0A %3C/Stack%3E%0A
|
42ec17758da48c2dea1ba80f3d62eecaebd5bf87 | Use MatCSS text initialization | app_server/public/src/js/modules/pages/login.js | app_server/public/src/js/modules/pages/login.js | const m = require('mithril');
const Login = module.exports = {
controller: function () {},
view: function (ctrl) {
return m('div.row', [
m('form.col offset-s3 s6', [
m('div.input-field col s12', [
m('input#username', {type: 'text'}),
m('label', {for: 'username'}, 'Username')
]),
m('div.input-field col s12', [
m('input#password', {type: 'password'}),
m('label', {for: 'password'}, 'Password')
]),
m('button.btn col s12', {type: 'submit'}, 'Log In')
])
]);
}
};
| JavaScript | 0 | @@ -24,16 +24,56 @@
ril');%0A%0A
+const mz = require('../utils/mzInit');%0A%0A
const Lo
@@ -176,16 +176,25 @@
iv.row',
+ mz.text,
%5B%0A
|
c0e7db1bb76455bfb8e66508eb8d4b99a8cb4f67 | removed geo nesting | src/server/app/shared/models/event.js | src/server/app/shared/models/event.js | import { Schema } from 'mongoose';
// TO-DO: replace Strings with more appropriate data types
const eventSchema = new Schema({
type: {
type: String,
required: true,
enum: [
'sweep',
'targeted',
'checkpoint',
'traffic',
'i9',
'action',
'other'
],
},
description: {
type: String,
intl: true
},
present: {
type: [{
// TO-DO: implement Agency stub in bootstrap.js
// _id: false,
// agency: {
// type: Schema.Types.ObjectId,
// ref: 'Agency'
// }
agency: String
}]
},
created: {
at: {
type: Date,
default: Date.now
},
by: {
group: {
type: Schema.Types.ObjectId,
ref: 'Group',
required: false
},
user: {
type: Schema.Types.ObjectId,
ref: 'User',
required: false
}
},
},
updated: {
at: {
type: Date,
default: Date.now
},
by: {
type: Schema.Types.ObjectId,
ref: 'User',
required: false
},
},
expire: {
at: Date,
deleteOnExpire: Boolean
},
verified: {
type: [{
_id: false,
required: false,
by: {
type: Schema.Types.ObjectId,
ref: 'User'
},
at: {
type: Date,
default: Date.now,
},
}]
},
location: {
address_1: String,
address_2: String,
city: String,
state: String,
zipcode: Number,
geo: {
latitude: Number,
longitude: Number
},
description: {
type: String,
intl: true
}
}
});
eventSchema.getAuthLevel = (payload, doc)=> {
if (payload && doc && payload.user && doc.created) {
const userGroup = payload.user.belongs.find({ to: doc.created.by.group });
const userRole = userGroup ? userGroup.as : false;
const userRoleInDoc = userRole ? doc.permissions[userRole] : false;
if (userGroup && userRole && userRoleInDoc) return userRole;
}
}
export default eventSchema;
| JavaScript | 0.999992 | @@ -1472,21 +1472,8 @@
er,%0A
- geo: %7B%0A
@@ -1494,18 +1494,16 @@
er,%0A
-
longitud
@@ -1511,22 +1511,16 @@
: Number
-%0A %7D
,%0A de
|
be6bc61e0be6226af1c1b6fbbee0ffbfee38248c | Bring back useRawDomain for Voyager2 | src/services/config/config.service.js | src/services/config/config.service.js | 'use strict';
// Service for the spec config.
// We keep this separate so that changes are kept even if the spec changes.
angular.module('vlui')
.factory('Config', function() {
var Config = {};
Config.data = {};
Config.config = {};
Config.getConfig = function() {
return {};
};
Config.getData = function() {
return Config.data;
};
Config.large = function() {
return {
cell: {
width: 300,
height: 300
},
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.small = function() {
return {
facet: {
cell: {
width: 150,
height: 150
}
},
overlay: {line: true},
scale: {useRawDomain: false}
};
};
Config.updateDataset = function(dataset, type) {
if (dataset.values) {
Config.data.values = dataset.values;
delete Config.data.url;
Config.data.formatType = undefined;
} else {
Config.data.url = dataset.url;
delete Config.data.values;
Config.data.formatType = type;
}
};
return Config;
});
| JavaScript | 0 | @@ -886,36 +886,35 @@
%7BuseRawDomain:
-fals
+tru
e%7D%0A %7D;%0A
|
1a68f55fb8749db4d80f6b97d9c03358e2e554bd | fix issue with cached query, but no results | src/spicy-datatable/SpicyDatatable.js | src/spicy-datatable/SpicyDatatable.js | /**
* @fileoverview SpicyDatatable
* Main entry file for `spicy-datatable` package. Renders a tabele given a tableKey, columns, and rows prop.
* For complete documentation of how to use this, refer to the `README.md` or check out the examples in `App.ja`
*/
import React, { Component, PropTypes } from 'react';
import Pagination from './Pagination.js';
import DatatableOptions from './DatatableOptions.js';
import { filterRows, getSafely, setSafely } from './utils.js';
import style from './table.css';
const miniCache = {};
const defaultNoEntiresLabel = 'No entries to show.';
const defaultEntryCountLabels = ['Showing', 'to', 'of', 'entries.'];
export default class SpicyDatatable extends Component {
static propTypes = {
tableKey: PropTypes.string.isRequired,
columns: PropTypes.arrayOf(PropTypes.shape({
key: PropTypes.string,
label: PropTypes.string,
})).isRequired,
rows: PropTypes.array.isRequired,
config: PropTypes.shape({
itemsPerPageOptions: PropTypes.arrayOf(PropTypes.number),
itemsPerPageLabel: PropTypes.string,
nextPageLabel: PropTypes.string,
previousPageLabel: PropTypes.string,
searchLabel: PropTypes.string,
searchPlaceholder: PropTypes.string,
noEntriesLabel: PropTypes.string,
entryCountLabels: PropTypes.arrayOf(PropTypes.string),
customFilter: PropTypes.func
}),
};
constructor(props) {
super(props);
const itemsPerPage =
getSafely(miniCache, props.tableKey).itemsPerPage ||
props.config && props.config.itemsPerPageOptions ?
props.config.itemsPerPageOptions[0] : 10;
this.state = {
itemsPerPage,
currentPage: getSafely(miniCache, props.tableKey).currentPage || 1,
searchQuery: getSafely(miniCache, props.tableKey).searchQuery || '',
};
}
componentWillUnmount() {
clearTimeout(this.scheduleQueryChange);
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.tableKey !== this.props.tableKey) {
const itemsPerPage =
getSafely(miniCache, this.props.tableKey).itemsPerPage ||
this.props.config && this.props.config.itemsPerPageOptions ?
this.props.config.itemsPerPageOptions[0] : 10;
const currentPage = getSafely(miniCache, this.props.tableKey).currentPage || 1;
this.setState({ currentPage, itemsPerPage });
}
}
render() {
const { columns, rows: originalRows = [], config = {} } = this.props;
const { itemsPerPage, currentPage, searchQuery = '', filteredRows: stateFilteredRows = []} = this.state || {};
const {
itemsPerPageOptions, itemsPerPageLabel,
nextPageLabel, previousPageLabel,
searchLabel, searchPlaceholder,
noEntriesLabel, entryCountLabels,
customFilter
} = config;
const isFilterActive = searchQuery.length > 0;
const filteredRows = isFilterActive ? stateFilteredRows : originalRows;
const maxOnPage = currentPage * itemsPerPage;
const rows = filteredRows && filteredRows.length > 0 ? filteredRows.slice((currentPage - 1) * itemsPerPage, maxOnPage) : [];
const total = isFilterActive ? filteredRows.length : originalRows.length;
const fromEntries = ((currentPage - 1) * itemsPerPage) + 1;
const toEntries = maxOnPage > total ? total : maxOnPage;
const entriesLabels = entryCountLabels || defaultEntryCountLabels;
return (
<div>
<DatatableOptions
itemsPerPage={itemsPerPage}
itemsPerPageOptions={itemsPerPageOptions}
itemsPerPageLabel={itemsPerPageLabel}
onPageSizeChange={this.handlePageSizeChange.bind(this)}
onSearch={this.handleSearchQueryChange.bind(this)}
searchValue={searchQuery}
searchLabel={searchLabel}
searchPlaceholder={searchPlaceholder}
/>
<table className="spicy-datatable">
<thead>
<tr>
{columns.map(c =>
<th key={c.key}>
{c.label}
</th>
)}
</tr>
</thead>
<tbody>
{rows.map((r, i) =>
<tr
key={i}
onClick={r.onClickHandler ? r.onClickHandler : () => undefined}
style={{ cursor: r.onClickHandler ? 'pointer' : 'default' }}
className={r.isActive ? 'spicy-datatable--selected-row' : ''}
>
{columns.map((c, i) =>
<td key={i}>
{r[c.key]}
</td>
)}
</tr>
)}
</tbody>
</table>
<div className="spicy-datatable-counter">
{total > 0 ?
<p>
{entriesLabels[0]} {fromEntries} {entriesLabels[1]} {toEntries} {entriesLabels[2]} {total} {entriesLabels[3]}
</p> : <p>{noEntriesLabel || defaultNoEntiresLabel}</p>}
</div>
<Pagination
onPage={this.handlePagination.bind(this)}
itemsPerPage={itemsPerPage}
total={total}
activePage={currentPage}
nextPageLabel={nextPageLabel}
previousPageLabel={previousPageLabel}
/>
</div>
);
}
handlePagination(nextPage) {
const { tableKey } = this.props;
this.setState({
currentPage: nextPage,
});
setSafely(miniCache, tableKey, 'currentPage', nextPage);
}
handleSearchQueryChange(e) {
const { columns, rows, config = {} } = this.props;
const { value } = e.target;
const { tableKey } = this.props;
const { customFilter } = config
if (this.scheduleQueryChange) {
clearTimeout(this.scheduleQueryChange);
}
this.scheduleQueryChange = setTimeout(() => {
const filterFunction = customFilter ? customFilter : filterRows;
const filteredRows = (value.length === 0 ? [] : filterFunction(rows, columns, value)) || [];
this.setState({ filteredRows, searchQuery: value, currentPage: 1 });
setSafely(miniCache, tableKey, 'searchQuery', value);
setSafely(miniCache, tableKey, 'currentPage', 1);
}, 200);
}
handlePageSizeChange(e) {
const { value } = e.target;
const { tableKey } = this.props;
this.setState({ itemsPerPage: Number(value), currentPage: 1 });
setSafely(miniCache, tableKey, 'itemsPerPage', Number(value));
setSafely(miniCache, tableKey, 'currentPage', 1);
}
}
| JavaScript | 0.000001 | @@ -1813,16 +1813,296 @@
%0A %7D;%0A
+ if (this.state.searchQuery.length %3E 0) %7B%0A const filterFunction = props.customFilter ? props.customFilter : filterRows;%0A const filteredRows = filterFunction(props.rows, props.columns, this.state.searchQuery) %7C%7C %5B%5D;%0A this.state.filteredRows = filteredRows;%0A %7D%0A
%7D%0A%0A c
|
4581e624f3c853c2b3a904696e4abeab73130439 | Remove nested <div>s to avoid Chrome active link state bug | src/static/js/ace/widget_outsource.js | src/static/js/ace/widget_outsource.js |
function makeOutsourceWidget(userlist, sendRequest, options) {
var outsourceWidget = {};
var dialogContainer;
var lineNo;
var reqTxt;
var button;
outsourceWidget.createRequest = function(selection) {
_close();
_init(selection);
_show();
};
function _init(selection) {
var details = $("<div id='outsource-details' />")
.append("<input type='radio' id='outsource-mode' checked='checked' />")
.append("<label for='outsource-mode'>Direct editing & automatic integration</label>");
dialogContainer = $("<div id='outsource-container' />")
.append($("<input id='outsource-file' type='text' disabled='disabled' />").val(clientVars.editorFile))
.append("<label for='outsource-line'>line</label>")
.append(lineNo = $("<input id='outsource-line' type='text' />").val(selection.start[0]+1))
.append(reqTxt = $("<textarea id='outsource-request'>Details...</textarea>"))
.append(details)
.append($("<button id='outsource-cancel' type='button'>Cancel</button>").click(_close))
.append(button = $("<button id='outsource-next' type='button'>Outsource</button>").click(_makeRequest));
lineNo.keyup(_handleKeys);
reqTxt.keyup(_handleKeys);
reqTxt.data('default', reqTxt.val())
.css('color', 'gray')
.focus(function() {
if ( ! reqTxt.data('edited')) { reqTxt.val(''); }
reqTxt.css('color', '');
})
.change(function() {
reqTxt.data('edited', reqTxt.val() != '');
button.attr('disabled', reqTxt.val() == '');
})
.keyup(function() {
reqTxt.data('edited', reqTxt.val() != '');
button.attr('disabled', reqTxt.val() == '');
})
.blur(function() {
if ( ! reqTxt.data('edited')) {
reqTxt.val(reqTxt.data('default'));
reqTxt.css('color', 'gray');
}
})
.val(selection.text.replace(/^\s+|\s+$/gm, '')).change();
}
function _show() {
$("#editorcontainerbox").append(dialogContainer);
$("label", dialogContainer).css('font-family', lineNo.css('font-family'));
reqTxt.focus().select();
}
function _handleKeys(evt) {
if (evt.keyCode == 27) { // escape key
_close();
}
}
function _close() {
$("#outsource-container").remove();
}
function _makeRequest() {
sendRequest({ lineNo: lineNo.val(), reqTxt: reqTxt.val() });
_close();
}
var statusContainer = $('#outsourcedcontainer');
var nodes = {};
function _makeChat(userInfo, text) {
return $('<a href="#" class="reqdetail"></a>')
.text(text + ' ' + userInfo.userName)
.prepend($('<div class="chatbutton"></div>')
.css('background-color', options.colorPalette[userInfo.colorId]))
.click(function() {
userlist.chat(userInfo);
return false;
});
}
outsourceWidget.updateRequests = function(requests) {
$.each(requests, function(idx, req) {
var node = $('<div>');
node.addClass('outsrcreq');
var state = req.completed ? 'completed' : req.assigned ? 'assigned' : 'new';
node.data('state', state).addClass(state);
if (req.requester.userId == clientVars.userId || req.worker.userId == clientVars.userId) {
node.addClass('mine');
}
node.append($('<div class="reqdesc">').text(req.description));
var worker = $('<div class="reqworker">');
var avatar = $('<div class="reqavatar">');
worker.append(avatar);
node.append(worker);
var location = $('<div class="reqdetail">');
if (req.location) {
var filename = req.location.substring(req.location.lastIndexOf('/')+1);
location.append($('<a href="' + req.location + '">').text(filename));
} else {
location.html('<i>unknown</i>');
}
node.append(location);
if (req.worker.userId) {
worker.append($('<div>').text(req.worker.userName));
avatar.css('background-color', options.colorPalette[req.worker.colorId]);
if (state == 'assigned') {
if (req.worker.userId == clientVars.userId) {
node.append(_makeChat(req.requester, 'Chat with requester:'));
} else if (req.requester.userId == clientVars.userId) {
node.append(_makeChat(req.worker, 'Chat with'));
}
}
} else if (state == 'new') {
avatar.css('background-color', '#fff');
}
if (req.worker.userId && req.requester.userId == clientVars.userId) {
var changes = $('<div class="reqdetail">');
var href = '/contrib:' + req.worker.userId + ':';
if (req.assigned) { href += req.assigned; }
if (req.completed) { href += '..' + req.completed; }
href += '/' + clientVars.editorProject;
var link = $('<a>').attr('href', '#').click(function() { return Layout.hoverOpen(href); });
var filenames = [];
$.each(req.deltas, function(filename) { filenames.push(filename); });
$.each(filenames.sort(), function(idx, filename) {
var delta = req.deltas[filename];
var line = $('<div>').text(filename.substring(filename.lastIndexOf('/')+1));
if (delta.ins) { line.append($('<span class="deltains">').text(' +'+delta.ins)); }
if (delta.del) { line.append($('<span class="deltadel">').text(' -'+delta.del)); }
link.append(line);
});
node.append(changes.append(link));
}
if (req.id in nodes) {
var old = nodes[req.id].replaceWith(node);
if (state != old.data('state')) {
node.prepend($('<div class="reqhighlight">').fadeIn(1000).delay(1000).fadeOut(2000));
}
} else {
statusContainer.prepend(node);
}
nodes[req.id] = node;
});
};
return outsourceWidget;
}
$(document).ready(function() { // on task framing page
function start() {
$('#overlay').hide();
$('#done').removeAttr('disabled');
}
$('#intro #start').bind('click', start);
if (clientVars.skipIntro) {
start();
}
});
| JavaScript | 0 | @@ -5113,27 +5113,28 @@
line = $('%3C
-div
+span
%3E').text(fil
@@ -5392,16 +5392,32 @@
end(line
+.append('%3Cbr/%3E')
);%0A
|
b688d2708bc0a2179b3c6d3060140f5fabc0dfb1 | remove unneeded function, this all gets wrapped in a library-wide function so is already hidden to the outside world | src/libs/polyfills.js | src/libs/polyfills.js | (function(){
/** If no implementation of a method called (methodName) exists fill it in with the
* implementation given as (filler).
*/
function polyfill(type, methodName, filler) {
var proto = type.prototype;
proto[methodName] = proto[methodName] || filler;
}
/**
* Here we have a minimal set of polyfills needed to let the code run in older browsers such
* as IE8.
*
* If you already have polyfills in your webapp or you don't need to support bad browsers, feel free
* to make a custom build without this. However, it is as small as it can be to get the job done.
*
*/
// Array.forEach has to be a polyfill, clarinet expects it
// Ignoring all but function argument since not needed, eg can't take a context
// Clarinet needs this
polyfill(Array, 'forEach', function( func ){
for( var i = 0 ; i < len(this) ; i++ ) {
func(this[i]);
}
});
// Array.filter has to be a polyfill, clarinet expects it.
// Ignoring all but function argument since not needed, eg can't take a context
// Clarinet needs this
polyfill(Array, 'filter', function( filterCondition ){
var passes = [];
// let's use the .forEach we declared above to implement .filter:
this.forEach(function(item){
if( filterCondition( item ) ) {
passes.push(item);
}
});
return passes;
});
// allow binding. Minimal version which includes binding of context only, not arguments as well
polyfill(Function, 'bind', function( context /*, arg1, arg2 ... */ ){
var f = this;
return function( /* yet more arguments */ ) {
return f.apply(context, arguments);
}
});
})(); | JavaScript | 0 | @@ -1,23 +1,11 @@
-(function()%7B%0A%0A /*
+%0A/** %0A
* If
@@ -82,22 +82,18 @@
ith the%0A
-
*
-
impleme
@@ -123,19 +123,13 @@
r).%0A
-
*/ %0A
-
func
@@ -170,19 +170,16 @@
ller) %7B%0A
-
var p
@@ -204,19 +204,16 @@
ype;%0A
-
-
proto%5Bme
@@ -257,24 +257,15 @@
er;%0A
- %7D%0A%0A
+%7D%0A%0A
/**%0A
-
* H
@@ -353,19 +353,16 @@
rs such%0A
-
* as IE
@@ -364,26 +364,20 @@
as IE8.%0A
-
* %0A
-
* If yo
@@ -470,19 +470,16 @@
l free %0A
-
* to ma
@@ -573,25 +573,19 @@
e.%0A
- * %0A
+* %0A
*/ %0A%0A
%0A
@@ -580,22 +580,17 @@
*/ %0A%0A
- %0A
+%0A
// Array
@@ -640,19 +640,16 @@
ects it%0A
-
// Ignor
@@ -712,35 +712,32 @@
take a context%0A
-
// Clarine
@@ -759,19 +759,16 @@
%0A
-
polyfill
@@ -809,23 +809,17 @@
)%7B%0A
-
%0A
-
for(
@@ -866,19 +866,16 @@
%0A
-
func(thi
@@ -888,19 +888,16 @@
%0A
-
-
%7D
@@ -900,27 +900,24 @@
%0A
-
%7D);
@@ -927,18 +927,10 @@
- %0A %0A
+%0A%0A
// A
@@ -984,19 +984,16 @@
cts it.%0A
-
// Ignor
@@ -1064,19 +1064,16 @@
context%0A
-
//
@@ -1093,19 +1093,16 @@
ds this%0A
-
polyfill
@@ -1157,26 +1157,20 @@
%0A
- %0A
+%0A
-
var pass
@@ -1178,23 +1178,17 @@
s = %5B%5D;%0A
- %0A
+%0A
// le
@@ -1248,19 +1248,16 @@
filter:%0A
-
this.
@@ -1292,19 +1292,16 @@
%0A
-
-
if( filt
@@ -1333,19 +1333,16 @@
-
passes.p
@@ -1358,19 +1358,16 @@
;%0A
-
-
%7D
@@ -1378,19 +1378,16 @@
%0A
-
%7D);%0A
@@ -1388,23 +1388,17 @@
%7D);%0A
- %0A
+%0A
retur
@@ -1410,23 +1410,17 @@
ses;%0A
- %0A
+%0A
%7D); %0A
@@ -1425,23 +1425,17 @@
- %0A
+%0A
// allow
@@ -1522,19 +1522,16 @@
as well%0A
-
polyfill
@@ -1595,19 +1595,16 @@
/ )%7B%0A
-
-
var f =
@@ -1609,23 +1609,17 @@
= this;%0A
- %0A
+%0A
retur
@@ -1689,19 +1689,16 @@
%0A
-
return f
@@ -1732,25 +1732,13 @@
%0A
-
- %7D%0A
+%7D%0A
%7D); %0A
-%0A%7D)();
|
e0e230fd6ded24d4f3cac0398a451bf21d873935 | fix wrong variables name | src/libs/talkative.js | src/libs/talkative.js | import config from '../../config.json';
function commandValid(args) {
if (args.length < 3) {
return false;
}
if (!Array.isArray(args)) {
return false;
}
return true;
}
export function send(status = 'ERROR', msg) {
return {
status,
msg,
}
}
export function analyzeNeed(msg) {
try {
const args = msg.trim().split(' ');
// [laguage] [mode] [command]
// check command pattern is valid
if (!commandValid(args)) {
throw 'Valid Command';
}
let language = args[0];
language = language.toLowerCase();
const mode = args[1];
const query = args.slice(2).join(' ');
if (config.LANGUAGES.indexOf(language) < 0) {
throw [
`Sorry, "${language}" is not avaiable right now.`,
'Here, there are avaiable languages.',
...LANGUAGES,
]
}
if (config.MODES.indexOf(mode.toLowerCase()) < 0) {
throw [
`Sorry, ${mode} is not avaiable right now.`,
'Here, there are avaiable modes.',
...config.MODES,
]
}
return send('OK', {
language,
mode,
query,
});
} catch (e) {
return send('ERROR', e);
}
}
function Talkative() {
}
export default Talkative; | JavaScript | 0.996902 | @@ -806,16 +806,23 @@
...
+config.
LANGUAGE
|
42be45ee0a225b141bb44a7de2d8a6e1073dabf9 | Add debug menu | src/menus/mainMenu.js | src/menus/mainMenu.js | const { remote } = window.require("electron")
const { Menu, dialog, process, app } = remote
export default function mainMenu(song, dispatch) {
const template = [
{
label: "File",
submenu: [
{
label: "New",
click: () => {
dispatch("CREATE_SONG")
}
},
{
label: "Open",
click: () => {
dialog.showOpenDialog({
filters: [{
name: "Standard MIDI File",
extensions: ["mid", "midi"]
}]
}, files => {
if (files) {
dispatch("OPEN_SONG", { filepath: files[0] })
}
})
}
},
{
label: "Save",
click: () => {
dispatch("SAVE_SONG", { filepath: song.filepath })
}
},
{
label: "Save As",
click: () => {
dialog.showSaveDialog({
defaultPath: song.filepath,
filters: [{
name: "Standard MIDI File",
extensions: ["mid", "midi"]
}]
}, filepath => {
dispatch("SAVE_SONG", { filepath })
})
}
}
]
},
{
label: "Edit",
submenu: [
{
label: "Undo",
click: () => dispatch("UNDO")
},
{
label: "Redo",
click: () => dispatch("REDO")
}
]
}
]
if (process.platform === "darwin") {
template.unshift({
label: app.getName(),
submenu: [
{role: "about"},
{type: "separator"},
{role: "services", submenu: []},
{type: "separator"},
{role: "hide"},
{role: "hideothers"},
{role: "unhide"},
{type: "separator"},
{role: "quit"}
]
})
// Window menu
template.push({
label: "Window",
submenu: [
{role: "close"},
{role: "minimize"},
{role: "zoom"},
{type: "separator"},
{role: "front"}
]
})
}
return Menu.buildFromTemplate(template)
} | JavaScript | 0.000001 | @@ -1,16 +1,51 @@
+import isDev from %22helpers/isDev%22%0A%0A
const %7B remote %7D
@@ -2141,16 +2141,393 @@
%7D)%0A %7D%0A
+ %0A if (isDev()) %7B%0A template.push(%7B%0A label: %22Debug%22,%0A submenu: %5B%0A %7B%0A label: 'Toggle Developer Tools',%0A accelerator: process.platform === 'darwin' ? 'Alt+Command+I' : 'Ctrl+Shift+I',%0A click (item, focusedWindow) %7B%0A if (focusedWindow) focusedWindow.webContents.toggleDevTools()%0A %7D%0A %7D%0A %5D%0A %7D)%0A %7D%0A%0A
return
|
b50697acc38c3c19e6e2f4c6eef4b47a33ee46dc | Update JS references to Site Verification REST routes to use new module. | assets/js/components/setup/site-verification.js | assets/js/components/setup/site-verification.js | /**
* SiteVerification component.
*
* Site Kit by Google, Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import data from 'GoogleComponents/data';
import Button from 'GoogleComponents/button';
import ProgressBar from 'GoogleComponents/progress-bar';
import { TextField, Input } from 'SiteKitCore/material-components';
import PropTypes from 'prop-types';
import {
validateJSON,
sendAnalyticsTrackingEvent,
} from 'GoogleUtil';
import HelpLink from 'GoogleComponents/help-link';
const { __ } = wp.i18n;
const { Component, Fragment } = wp.element;
class SiteVerification extends Component {
constructor( props ) {
super( props );
const { isAuthenticated, shouldSetup } = this.props;
this.state = {
loading: isAuthenticated && shouldSetup,
loadingMsg: __( 'Getting your verified sites...', 'google-site-kit' ),
siteURL: ' ', // Space allows TextField label to look right.
selectedUrl: '',
errorCode: false,
errorMsg: '',
};
this.onProceed = this.onProceed.bind( this );
}
componentDidMount() {
const { isAuthenticated, shouldSetup } = this.props;
if ( ! isAuthenticated || ! shouldSetup ) {
return;
}
this.requestSitePropertyList();
}
requestSitePropertyList() {
const { setErrorMessage } = this.props;
( async () => {
try {
const responseData = await data.get( 'modules', 'search-console',
'siteverification-list' );
const { verified, identifier } = responseData;
// Our current siteURL has been verified. Proceed to next step.
if ( verified ) {
sendAnalyticsTrackingEvent( 'verification_setup', 'verification_check_true' );
const response = await this.insertSiteVerification( identifier );
if ( true === response.updated ) {
this.props.siteVerificationSetup( true );
return true;
}
} else {
sendAnalyticsTrackingEvent( 'verification_setup', 'verification_check_false' );
}
this.setState( {
loading: false,
siteURL: responseData.identifier,
} );
} catch ( err ) {
let message = err.message;
if ( validateJSON( err.message ) ) {
const errorJson = JSON.parse( err.message );
message = errorJson.error.message || err.message;
}
setErrorMessage( message );
this.setState( {
loading: false,
errorCode: err.code,
errorMsg: message,
siteURL: googlesitekit.admin.siteURL, // Fallback to site URL from the settings.
} );
}
} )();
}
async insertSiteVerification( siteURL ) {
return await data.set( 'modules', 'search-console', 'siteverification', { siteURL } );
}
async onProceed() {
const { setErrorMessage } = this.props;
// Try to get siteURL from state, and if blank get from the settings.
const siteURL = this.state.siteURL ? this.state.siteURL : googlesitekit.admin.siteURL;
setErrorMessage( '' );
this.setState( {
loading: true,
loadingMsg: __( 'Verifying...', 'google-site-kit' ),
errorCode: false,
errorMsg: '',
} );
try {
const response = await this.insertSiteVerification( siteURL );
if ( true === response.updated ) {
sendAnalyticsTrackingEvent( 'verification_setup', 'verification_insert_tag' );
// We have everything we need here. go to next step.
this.props.siteVerificationSetup( true );
}
} catch ( err ) {
let message = err.message;
if ( validateJSON( err.message ) ) {
const errorJson = JSON.parse( err.message );
message = errorJson.error.message || err.message;
}
setErrorMessage( message );
this.setState( {
loading: false,
errorCode: err.code,
errorMsg: message,
} );
}
}
renderForm() {
const { loading, loadingMsg, siteURL } = this.state;
const loadingDiv = (
<Fragment>
{ loadingMsg &&
<p>{ loadingMsg }</p>
}
<ProgressBar />
</Fragment>
);
// If the site is verified then we continue to next step. show loading div.
if ( loading ) {
return loadingDiv;
}
return (
<Fragment>
<div className="googlesitekit-wizard-step__inputs">
<TextField
label={ __( 'Website Address', 'google-site-kit' ) }
name="siteProperty"
floatingLabelClassName="mdc-floating-label--float-above"
outlined
disabled
>
<Input
value={ siteURL }
/>
</TextField>
</div>
<div className="googlesitekit-wizard-step__action googlesitekit-wizard-step__action--justify">
<Button onClick={ this.onProceed }>{ __( 'Continue', 'google-site-kit' ) }</Button>
<HelpLink />
</div>
</Fragment>
);
}
static renderSetupDone() {
return (
<Fragment>
<h2 className="
googlesitekit-heading-3
googlesitekit-wizard-step__title
">
{ __( 'Verify URL', 'google-site-kit' ) }
</h2>
<p className="googlesitekit-wizard-step__text">{ __( 'Congratulations, your site has been verified!', 'google-site-kit' ) }</p>
</Fragment>
);
}
render() {
const { isAuthenticated, shouldSetup } = this.props;
const { errorMsg } = this.state;
if ( ! shouldSetup ) {
return SiteVerification.renderSetupDone();
}
return (
<Fragment>
<h2 className="
googlesitekit-heading-3
googlesitekit-wizard-step__title
">
{ __( 'Verify URL', 'google-site-kit' ) }
</h2>
<p className="googlesitekit-wizard-step__text">{ __( 'We will need to verify your URL for Site Kit.', 'google-site-kit' ) }</p>
{
errorMsg && 0 < errorMsg.length &&
<p className="googlesitekit-error-text">
{ errorMsg }
</p>
}
{ isAuthenticated && this.renderForm() }
</Fragment>
);
}
}
SiteVerification.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
shouldSetup: PropTypes.bool.isRequired,
siteVerificationSetup: PropTypes.func.isRequired,
completeSetup: PropTypes.func,
setErrorMessage: PropTypes.func.isRequired,
};
export default SiteVerification;
| JavaScript | 0 | @@ -1910,29 +1910,32 @@
les', 's
-earch-console
+ite-verification
',%0A%09%09%09%09%09
@@ -3098,21 +3098,24 @@
, 's
-earch-console
+ite-verification
', '
|
a21bd0254259d5fc967947cd15faaf59c6a398c7 | Use `toString` if environment doesn't support `JSON.stringify` | packages/ember-data/lib/adapters/fixture_adapter.js | packages/ember-data/lib/adapters/fixture_adapter.js | require("ember-data/core");
require("ember-data/system/adapter");
require('ember-data/serializers/fixture_serializer');
var get = Ember.get, fmt = Ember.String.fmt;
/**
`DS.FixtureAdapter` is an adapter that loads records from memory.
Its primarily used for development and testing. You can also use
`DS.FixtureAdapter` while working on the API but are not ready to
integrate yet. It is a fully functioning adapter. All CRUD methods
are implemented. You can also implement query logic that a remote
system would do. Its possible to do develop your entire application
with `DS.FixtureAdapter`.
*/
DS.FixtureAdapter = DS.Adapter.extend({
simulateRemoteResponse: true,
latency: 50,
serializer: DS.FixtureSerializer,
/*
Implement this method in order to provide data associated with a type
*/
fixturesForType: function(type) {
if (type.FIXTURES) {
var fixtures = Ember.A(type.FIXTURES);
return fixtures.map(function(fixture){
if(!fixture.id){
throw new Error(fmt('the id property must be defined for fixture %@', [JSON.stringify(fixture)]));
}
fixture.id = fixture.id + '';
return fixture;
});
}
return null;
},
/*
Implement this method in order to query fixtures data
*/
queryFixtures: function(fixtures, query, type) {
Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.');
},
updateFixtures: function(type, fixture) {
if(!type.FIXTURES) {
type.FIXTURES = [];
}
var fixtures = type.FIXTURES;
this.deleteLoadedFixture(type, fixture);
fixtures.push(fixture);
},
/*
Implement this method in order to provide provide json for CRUD methods
*/
mockJSON: function(type, record) {
return this.serialize(record, { includeId: true });
},
/*
Adapter methods
*/
generateIdForRecord: function(store, record) {
return Ember.guidFor(record);
},
find: function(store, type, id) {
var fixtures = this.fixturesForType(type),
fixture;
Ember.warn("Unable to find fixtures for model type " + type.toString(), fixtures);
if (fixtures) {
fixture = Ember.A(fixtures).findProperty('id', id);
}
if (fixture) {
this.simulateRemoteCall(function() {
this.didFindRecord(store, type, fixture, id);
}, this);
}
},
findMany: function(store, type, ids) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
if (fixtures) {
fixtures = fixtures.filter(function(item) {
return ids.indexOf(item.id) !== -1;
});
}
if (fixtures) {
this.simulateRemoteCall(function() {
this.didFindMany(store, type, fixtures);
}, this);
}
},
findAll: function(store, type) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
this.simulateRemoteCall(function() {
this.didFindAll(store, type, fixtures);
}, this);
},
findQuery: function(store, type, query, array) {
var fixtures = this.fixturesForType(type);
Ember.assert("Unable to find fixtures for model type "+type.toString(), !!fixtures);
fixtures = this.queryFixtures(fixtures, query, type);
if (fixtures) {
this.simulateRemoteCall(function() {
this.didFindQuery(store, type, fixtures, array);
}, this);
}
},
createRecord: function(store, type, record) {
var fixture = this.mockJSON(type, record);
this.updateFixtures(type, fixture);
this.simulateRemoteCall(function() {
this.didCreateRecord(store, type, record, fixture);
}, this);
},
updateRecord: function(store, type, record) {
var fixture = this.mockJSON(type, record);
this.updateFixtures(type, fixture);
this.simulateRemoteCall(function() {
this.didUpdateRecord(store, type, record, fixture);
}, this);
},
deleteRecord: function(store, type, record) {
var fixture = this.mockJSON(type, record);
this.deleteLoadedFixture(type, fixture);
this.simulateRemoteCall(function() {
this.didDeleteRecord(store, type, record);
}, this);
},
/*
@private
*/
deleteLoadedFixture: function(type, record) {
var id = this.extractId(type, record);
var existingFixture = this.findExistingFixture(type, record);
if(existingFixture) {
var index = type.FIXTURES.indexOf(existingFixture);
type.FIXTURES.splice(index, 1);
return true;
}
},
findExistingFixture: function(type, record) {
var fixtures = this.fixturesForType(type);
var id = this.extractId(type, record);
return this.findFixtureById(fixtures, id);
},
findFixtureById: function(fixtures, id) {
var adapter = this;
return Ember.A(fixtures).find(function(r) {
if(''+get(r, 'id') === ''+id) {
return true;
} else {
return false;
}
});
},
simulateRemoteCall: function(callback, context) {
if (get(this, 'simulateRemoteResponse')) {
// Schedule with setTimeout
Ember.run.later(context, callback, get(this, 'latency'));
} else {
// Asynchronous, but at the of the runloop with zero latency
Ember.run.once(context, callback);
}
}
});
| JavaScript | 0 | @@ -157,16 +157,114 @@
ring.fmt
+,%0A dump = Ember.get(window, 'JSON.stringify') %7C%7C function(object) %7B return object.toString(); %7D
;%0A%0A/**%0A
@@ -1172,30 +1172,20 @@
e %25@', %5B
-JSON.stringify
+dump
(fixture
|
ad9d2a0ef77bc067a3b4d36f4c679c5bd4939f33 | simplify component w/ v2 changes | troposphere/static/js/components/projects/detail/resources/tableData/instance/Size.react.js | troposphere/static/js/components/projects/detail/resources/tableData/instance/Size.react.js | /** @jsx React.DOM */
define(
[
'react',
'backbone',
'stores/SizeStore'
],
function (React, Backbone, SizeStore) {
return React.createClass({
propTypes: {
instance: React.PropTypes.instanceOf(Backbone.Model).isRequired
},
render: function () {
var identity = this.props.instance.get('identity');
var providerId = identity.provider;
var identityId = identity.id;
var sizes = SizeStore.getAllFor(providerId, identityId);
if(sizes) {
var sizeId = this.props.instance.get('size_alias');
var size = sizes.get(sizeId);
if(size) {
return (
<span>{size.get('name')}</span>
);
}else{
return (
<span></span>
)
}
}
return (
<div className="loading-tiny-inline"></div>
);
}
});
});
| JavaScript | 0.000005 | @@ -72,18 +72,8 @@
ores
-/SizeStore
'%0A
@@ -104,25 +104,22 @@
ckbone,
-SizeS
+s
tore
+s
) %7B%0A%0A
@@ -289,23 +289,23 @@
var i
-dentity
+nstance
= this.
@@ -322,298 +322,77 @@
ance
-.get('identity');%0A var providerId = identity.provider;%0A var identityId = identity.id;%0A var sizes = SizeStore.getAllFor(providerId, identityId);%0A%0A if(sizes) %7B%0A var sizeId = this.props.instance.get('size_alias');%0A var size = sizes.get(sizeI
+,%0A size = stores.SizeStore.get(instance.get('size').i
d);%0A
-
+%0A
@@ -402,18 +402,16 @@
if(
+!
size)
-
%7B%0A
-
@@ -441,40 +441,50 @@
- %3Cspan%3E%7Bsize.get('name')%7D%3C/span
+%3Cdiv className=%22loading-tiny-inline%22%3E%3C/div
%3E%0A
@@ -487,26 +487,24 @@
%3E%0A
-
-
);%0A
@@ -506,21 +506,11 @@
- %7Delse%7B%0A
+%7D%0A%0A
@@ -536,132 +536,38 @@
-
-
%3Cspan%3E
-%3C/span%3E%0A )%0A %7D%0A %7D%0A%0A return (%0A %3Cdiv className=%22loading-tiny-inline%22%3E%3C/div
+%7Bsize.get('name')%7D%3C/span
%3E%0A
|
86474e1195d0a73ba9c879fe3b45fe9f4dc8ce0c | Fix blog urls for nav | src/static/MainNavNew/Submenu/MagazineDisplay/index.js | src/static/MainNavNew/Submenu/MagazineDisplay/index.js | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Spacer from 'atoms/Spacer';
import Layout from 'atoms/Layout';
import Col from 'atoms/Layout/Col';
import Hide from 'wrappers/Hide';
import BlogIntro from '../Intro/Blog';
import LinkList from '../LinkList';
import ArticleImage from '../ArticleImage';
import MobileBack from '../MobileBack';
import { fetchPosts } from '../../utils/fetchMagazinePosts';
import styles from '../ProductDisplay/product_display.module.scss';
class MagazineDisplay extends Component {
constructor() {
super();
this.state = {
'latest-magazine': {
loading: true,
data: [],
},
'money-magazine': {
loading: true,
data: [],
},
'tech-magazine': {
loading: true,
data: [],
},
'health-magazine': {
loading: true,
data: [],
},
'auto-magazine': {
loading: true,
data: [],
},
'pet-magazine': {
loading: true,
data: [],
},
'insurance-magazine': {
loading: true,
data: [],
},
};
}
componentWillReceiveProps(nextProps) {
const emptyPosts = this.state[this.props.activeName].data.length === 0;
if (nextProps.isActive && emptyPosts) {
Promise.all([
fetchPosts({
featured: 'false',
tag: this.props.tag,
limit: 4,
}),
fetchPosts({
featured: 'true',
tag: this.props.tag,
limit: 2,
})
])
.then((data) => {
const recommendedPosts = data[0].posts.map((p) => {
const post = p;
post.url = p.url;
return post;
});
this.setState({
[this.props.activeName]: {
loading: false,
data: [
{
type: 'list',
header: 'Recommended',
posts: recommendedPosts,
},
{
type: 'featured',
post: data[1].posts[0],
},
{
type: 'featured',
post: data[1].posts[1],
}
]
}
});
});
}
}
get list() {
const {
activeName,
mobileCollapsedMenu,
} = this.props;
const data = this.state[activeName].data;
return (
data.map((item) => {
if (item.type === 'list') {
return (
<Col
fullwidth
key={item.header}
className={styles['display-list']}
>
<LinkList
item={item}
/>
</Col>
);
}
if (item.type === 'featured') {
return (
<Col
key={item.post.url}
fullwidth={mobileCollapsedMenu}
>
<ArticleImage
header={item.post.title}
imgProps={{
src: `${item.post.feature_image}?fit=crop&w=640&h=360`,
}}
link={item.post.url}
/>
</Col>
);
}
return null;
})
);
}
render() {
const {
headerText,
setMobileCollapsedMenu,
intro,
isActive,
activeName,
mobileCollapsedMenu,
} = this.props;
const displayClasses = classnames(
styles['submenu-display'],
isActive && styles['submenu-display-active'],
mobileCollapsedMenu === activeName && styles['mobile-collapsed'],
);
return (
<div className={displayClasses}>
<MobileBack
setMobileCollapsedMenu={setMobileCollapsedMenu}
text='Magazine'
/>
<Spacer size={36} />
<Layout
fullwidth
smallCols={[ 12 ]}
largeCols={[ 4, 8 ]}
className={styles.content}
>
<Col
className={styles.intro}
>
<Hide hideOn='tablet desktop'>
<Spacer size={24} />
</Hide>
<Hide hideOn='mobile tablet'>
<Spacer size={36} />
<Spacer size={12} />
</Hide>
<BlogIntro
intro={intro}
headerText={headerText}
/>
<Hide hideOn='desktop'>
<Spacer size={60} />
</Hide>
</Col>
<Col
fullwidth
>
<Layout
fullwidth
smallCols={[ 12 ]}
mediumCols={[ 4 ]}
>
{ this.list }
</Layout>
</Col>
</Layout>
<Spacer size={36} />
<Spacer size={12} />
</div>
);
}
}
MagazineDisplay.propTypes = {
isActive: PropTypes.bool,
activeName: PropTypes.string,
tag: PropTypes.string,
headerText: PropTypes.string,
setMobileCollapsedMenu: PropTypes.func,
intro: PropTypes.object,
mobileCollapsedMenu: PropTypes.string,
};
export default MagazineDisplay;
| JavaScript | 0.000002 | @@ -469,16 +469,67 @@
ePosts';
+%0Aimport fullBlogUrl from '../../utils/fullBlogUrl';
%0A%0Aimport
@@ -1789,13 +1789,26 @@
l =
+fullBlogUrl(
p.url
+)
;%0A%0A
|
bdbd821464726ae6024f27501a151a8f2cd5433e | Fix IE incompatibility. | src/test/test-obviel-template-perf.js | src/test/test-obviel-template-perf.js | /* performance benchmarks loosely based on these:
http://genshi.edgewall.org/wiki/GenshiPerformance
*/
/*global module:false obviel:false test:false ok:false same:false $:false
equal:false raises:false asyncTest:false start:false deepEqual: false
stop:false */
module("Template Performance", {
setup: function() {
$('#jsview-area').html('<div id="viewdiv"></div>');
},
teardown: function() {
}
});
var module = obviel.template;
/* it's hard to replicate a server-side test, because:
* we have logic-less templates that don't involve calling any code
(in most areas)
* we don't construct a full HTML page
*/
// // count starting with 1
// // XXX special class in case 'last' is reached
// // all really in the same tag with an each: tricky unless preprocess data!
// var basic = module.Template(
// '<div>{user}</div>' +
// '<div>{me}</div>' +
// '<div>{world}</div>' +
// '<h2>Loop</h2>' +
// '<ul data-if="items">' +
// ' <li data-each="items" class="@nr">{content}</li>' +
// '</ul>');
var big_table_nested = new module.Template(
'<table>\n' +
'<tr data-each="table">' +
'<td data-each="@.">{@.}</td>' +
'</tr>' +
'</table>');
var big_table_flat = new module.Template(
'<table>\n' +
'<tr data-each="table">' +
'<td>{a}</td>' +
'<td>{b}</td>' +
'<td>{c}</td>' +
'<td>{d}</td>' +
'<td>{e}</td>' +
'<td>{f}</td>' +
'<td>{g}</td>' +
'<td>{h}</td>' +
'<td>{i}</td>' +
'<td>{j}</td>' +
'</tr>' +
'</table>'
);
var big_table_flat_view = new module.Template(
'<table>\n' +
'<tr data-each="table" data-view="@.">' +
'</tr>' +
'</table>'
);
var data = {
table: []
};
var data_flat = {
table: []
};
for (var i = 0; i < 1000; i++) {
data.table.push([1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
data_flat.table.push({
iface: 'row',
a: 1,
b: 2,
c: 3,
d: 4,
e: 5,
f: 6,
g: 7,
h: 8,
i: 9,
j: 10
});
};
test('big table nested', function() {
big_table_nested.render($('<div></div>'), data);
expect(0);
});
test('big table flat without view', function() {
big_table_flat.render($('<div></div>'), data_flat);
expect(0);
});
test('big table flat with view', function() {
obviel.view({
iface: 'row',
render: function() {
this.el.append('<td>' + this.obj.a + '</td>');
}
});
big_table_flat_view.render($('<div></div>'), data_flat);
expect(0);
});
var simple_data = {
first: {
a: "Hello A",
b: "Hello B",
c: "Hello C",
d: "Hello D",
e: "Hello E",
f: "Hello F",
g: "Hello G",
h: "Hello H",
i: "Hello I",
j: "Hello J"
},
second: {
a: "Bye A",
b: "Bye B",
c: "Bye C",
d: "Bye D",
e: "Bye E",
f: "Bye F",
g: "Bye G",
h: "Bye H",
i: "Bye I",
j: "Bye J"
},
flag: true
};
var simple_template = new module.Template(
'<div class="all">' +
'<div class="always" data-with="first">' +
'<p>A: {a}</p>' +
'<p>B: {b}</p>' +
'<p>C: {c}</p>' +
'<p>D: {d}</p>' +
'<p>E: {e}</p>' +
'<p>F: {f}</p>' +
'<p>G: {g}</p>' +
'<p>H: {h}</p>' +
'<p>I: {i}</p>' +
'<p>J: {j}</p>' +
'</div>' +
'<div class="sometimes" data-if="flag" data-with="second">' +
'<p>A: {a}</p>' +
'<p>B: {b}</p>' +
'<p>C: {c}</p>' +
'<p>D: {d}</p>' +
'<p>E: {e}</p>' +
'<p>F: {f}</p>' +
'<p>G: {g}</p>' +
'<p>H: {h}</p>' +
'<p>I: {i}</p>' +
'<p>J: {j}</p>' +
'</div>' +
'</div>'
);
test('simple template repeated', function() {
var el = $('<div></div>');
for (var i = 0; i < 1000; i++) {
simple_template.render(el, simple_data);
}
expect(0);
});
| JavaScript | 0 | @@ -430,22 +430,22 @@
);%0A%0Avar
-module
+obtemp
= obvie
@@ -1056,30 +1056,30 @@
ested = new
-module
+obtemp
.Template(%0A'
@@ -1196,30 +1196,30 @@
_flat = new
-module
+obtemp
.Template(%0A'
@@ -1479,30 +1479,30 @@
_view = new
-module
+obtemp
.Template(%0A'
@@ -2978,22 +2978,22 @@
e = new
-module
+obtemp
.Templat
|
532fb8e2150c70c627d57f9f72f8232606976a4a | Fix error when unmuting a domain without listing muted domains first | app/javascript/flavours/glitch/reducers/domain_lists.js | app/javascript/flavours/glitch/reducers/domain_lists.js | import {
DOMAIN_BLOCKS_FETCH_SUCCESS,
DOMAIN_BLOCKS_EXPAND_SUCCESS,
DOMAIN_UNBLOCK_SUCCESS,
} from '../actions/domain_blocks';
import { Map as ImmutableMap, OrderedSet as ImmutableOrderedSet } from 'immutable';
const initialState = ImmutableMap({
blocks: ImmutableMap(),
});
export default function domainLists(state = initialState, action) {
switch(action.type) {
case DOMAIN_BLOCKS_FETCH_SUCCESS:
return state.setIn(['blocks', 'items'], ImmutableOrderedSet(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_BLOCKS_EXPAND_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.union(action.domains)).setIn(['blocks', 'next'], action.next);
case DOMAIN_UNBLOCK_SUCCESS:
return state.updateIn(['blocks', 'items'], set => set.delete(action.domain));
default:
return state;
}
};
| JavaScript | 0.000001 | @@ -270,16 +270,55 @@
ableMap(
+%7B%0A items: ImmutableOrderedSet(),%0A %7D
),%0A%7D);%0A%0A
|
e1471abba9de41694bd5a4b864119780bfaad5f3 | drop submission clone all then | app/modules/submissions/actions/submission-clone-all.js | app/modules/submissions/actions/submission-clone-all.js | import { selected } from "../selectors"
import { submissionCloneFunc } from "./submission-clone"
import { clone } from "../../../lib/cloneutils"
import Promise from "bluebird"
const submissionClone = submissionCloneFunc(clone)
// PUBLIC: Async thunk action for cloning all selected submissions.
export const submissionCloneAll = () => {
return (dispatch, getState) => {
var selectedSubmissions = selected(getState())
return Promise.map(selectedSubmissions, submission => {
return dispatch(submissionClone(submission))
},
{concurrency: 2}).then()
}
}
| JavaScript | 0 | @@ -561,15 +561,8 @@
2%7D)
-.then()
%0A %7D
|
b895ee783b13a50d4ab0a92c2ea15c2ff7f1e8ae | Fix defaultFontFamily misspelled in createTypography (#13260) | packages/material-ui/src/styles/createTypography.js | packages/material-ui/src/styles/createTypography.js | import deepmerge from 'deepmerge'; // < 1kb payload overhead when lodash/merge is > 3kb.
import warning from 'warning';
function round(value) {
return Math.round(value * 1e5) / 1e5;
}
const caseAllCaps = {
textTransform: 'uppercase',
};
const defaultFontFamiliy = '"Roboto", "Helvetica", "Arial", sans-serif';
/**
* @see @link{https://material.io/design/typography/the-type-system.html}
* @see @link{https://material.io/design/typography/understanding-typography.html}
*/
export default function createTypography(palette, typography) {
const {
fontFamily = defaultFontFamiliy,
// The default font size of the Material Specification.
fontSize = 14, // px
fontWeightLight = 300,
fontWeightRegular = 400,
fontWeightMedium = 500,
// Tell Material-UI what's the font-size on the html element.
// 16px is the default font-size used by browsers.
htmlFontSize = 16,
// eslint-disable-next-line no-underscore-dangle
useNextVariants = Boolean(global.__MUI_USE_NEXT_TYPOGRAPHY_VARIANTS__),
// Private option to prevent noise in the console from the default theme.
suppressWarning = false,
// Apply the CSS properties to all the variants.
allVariants,
...other
} = typeof typography === 'function' ? typography(palette) : typography;
warning(
useNextVariants || suppressWarning,
'Material-UI: you are using the deprecated typography variants ' +
'that will be removed in the next major release.' +
'\nPlease read the migration guide under https://material-ui.com/style/typography#migration-to-typography-v2',
);
const coef = fontSize / 14;
const pxToRem = size => `${(size / htmlFontSize) * coef}rem`;
const buildVariant = (fontWeight, size, lineHeight, letterSpacing, casing) => ({
color: palette.text.primary,
fontFamily,
fontWeight,
fontSize: pxToRem(size),
// Unitless following http://meyerweb.com/eric/thoughts/2006/02/08/unitless-line-heights/
lineHeight,
// The letter spacing was designed for the Roboto font-family. Using the same letter-spacing
// across font-families can cause issues with the kerning.
...(fontFamily === defaultFontFamiliy
? { letterSpacing: `${round(letterSpacing / size)}em` }
: {}),
...casing,
...allVariants,
});
const nextVariants = {
h1: buildVariant(fontWeightLight, 96, 1, -1.5),
h2: buildVariant(fontWeightLight, 60, 1, -0.5),
h3: buildVariant(fontWeightRegular, 48, 1.04, 0),
h4: buildVariant(fontWeightRegular, 34, 1.17, 0.25),
h5: buildVariant(fontWeightRegular, 24, 1.33, 0),
h6: buildVariant(fontWeightMedium, 20, 1.6, 0.15),
subtitle1: buildVariant(fontWeightRegular, 16, 1.75, 0.15),
subtitle2: buildVariant(fontWeightMedium, 14, 1.57, 0.1),
body1Next: buildVariant(fontWeightRegular, 16, 1.5, 0.15),
body2Next: buildVariant(fontWeightRegular, 14, 1.5, 0.15),
buttonNext: buildVariant(fontWeightMedium, 14, 1.5, 0.4, caseAllCaps),
captionNext: buildVariant(fontWeightRegular, 12, 1.66, 0.4),
overline: buildVariant(fontWeightRegular, 12, 2.66, 1, caseAllCaps),
};
// To remove in v4
const oldVariants = {
display4: {
fontSize: pxToRem(112),
fontWeight: fontWeightLight,
fontFamily,
letterSpacing: '-.04em',
lineHeight: `${round(128 / 112)}em`,
marginLeft: '-.04em',
color: palette.text.secondary,
...allVariants,
},
display3: {
fontSize: pxToRem(56),
fontWeight: fontWeightRegular,
fontFamily,
letterSpacing: '-.02em',
lineHeight: `${round(73 / 56)}em`,
marginLeft: '-.02em',
color: palette.text.secondary,
...allVariants,
},
display2: {
fontSize: pxToRem(45),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(51 / 45)}em`,
marginLeft: '-.02em',
color: palette.text.secondary,
...allVariants,
},
display1: {
fontSize: pxToRem(34),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(41 / 34)}em`,
color: palette.text.secondary,
...allVariants,
},
headline: {
fontSize: pxToRem(24),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(32.5 / 24)}em`,
color: palette.text.primary,
...allVariants,
},
title: {
fontSize: pxToRem(21),
fontWeight: fontWeightMedium,
fontFamily,
lineHeight: `${round(24.5 / 21)}em`,
color: palette.text.primary,
...allVariants,
},
subheading: {
fontSize: pxToRem(16),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(24 / 16)}em`,
color: palette.text.primary,
...allVariants,
},
body2: {
fontSize: pxToRem(14),
fontWeight: fontWeightMedium,
fontFamily,
lineHeight: `${round(24 / 14)}em`,
color: palette.text.primary,
...allVariants,
},
body1: {
fontSize: pxToRem(14),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(20.5 / 14)}em`,
color: palette.text.primary,
...allVariants,
},
caption: {
fontSize: pxToRem(12),
fontWeight: fontWeightRegular,
fontFamily,
lineHeight: `${round(16.5 / 12)}em`,
color: palette.text.secondary,
...allVariants,
},
button: {
fontSize: pxToRem(14),
textTransform: 'uppercase',
fontWeight: fontWeightMedium,
fontFamily,
color: palette.text.primary,
...allVariants,
},
};
return deepmerge(
{
pxToRem,
round,
fontFamily,
fontSize,
fontWeightLight,
fontWeightRegular,
fontWeightMedium,
...oldVariants,
...nextVariants,
...(useNextVariants
? {
body1: nextVariants.body1Next,
body2: nextVariants.body2Next,
button: nextVariants.buttonNext,
caption: nextVariants.captionNext,
}
: {}),
useNextVariants,
},
other,
{
clone: false, // No need to clone deep
},
);
}
| JavaScript | 0 | @@ -258,17 +258,16 @@
ontFamil
-i
y = '%22Ro
@@ -581,17 +581,16 @@
ontFamil
-i
y,%0A /
@@ -2175,17 +2175,16 @@
ontFamil
-i
y%0A
|
f3d466103c7ad4b4eadba27f993d410b8a38485f | fix path resolving | packages/migration/scripts/utils/updateTemplates.js | packages/migration/scripts/utils/updateTemplates.js | /*
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* External dependencies
*/
import { readdirSync, readFileSync, writeFileSync, lstatSync } from 'fs';
import { join } from 'path';
/**
* Internal dependencies
*/
// eslint-disable-next-line import/no-unresolved
import { migrate, DATA_VERSION } from '../module.js';
function updateTemplates(templatesDir) {
const fileNamePattern = /^.*\.json$/;
const getFiles = (dir) =>
readdirSync(dir).map((fileOrDir) =>
lstatSync(join(dir, fileOrDir)).isDirectory()
? getFiles(join(dir, fileOrDir))
: join(dir, fileOrDir)
);
const templateFiles = getFiles(templatesDir)
.flat()
.filter((file) => fileNamePattern.test(file));
for (const file of templateFiles) {
const template = JSON.parse(readFileSync(file, 'utf8'));
if (Number(template.version) === Number(DATA_VERSION)) {
continue;
}
// This ensures that the version number is always at the top.
const updatedTemplate = {
version: DATA_VERSION,
...migrate(template, template.version),
};
updatedTemplate.version = DATA_VERSION;
const templateFileContent = JSON.stringify(updatedTemplate);
writeFileSync(file, templateFileContent);
}
}
export default updateTemplates;
| JavaScript | 0.000001 | @@ -709,16 +709,25 @@
t %7B join
+, resolve
%7D from
@@ -1160,39 +1160,165 @@
%0A%0A
-const templateFiles = getFiles(
+// templatesDir is relative from the project root,%0A // heence going two levels up.%0A const templateFiles = getFiles(%0A resolve(process.cwd(), '..', '..',
temp
@@ -1323,24 +1323,28 @@
mplatesDir)%0A
+ )%0A
.flat()%0A
|
975666d02d5b31e5cf0721993664d30b99f26f3b | add semi | packages/zent-datetimepicker/src/DateRangePicker.js | packages/zent-datetimepicker/src/DateRangePicker.js | import React, { Component } from 'react';
import classNames from 'zent-utils/classnames';
import DatePanel from './date/DatePanel';
import PanelFooter from './common/PanelFooter';
import { goMonths, isFunction, isArray } from './utils';
import { formatDate, parseDate } from './utils/format';
import clickOutside from './utils/clickOutside';
import { RANGE_PROPS, TIME_PROPS } from './constants';
class DateRangePicker extends Component {
static defaultProps = RANGE_PROPS
constructor(props) {
super(props);
let showPlaceholder;
let selected = [];
let actived = [];
if (props.value) {
showPlaceholder = false;
const tmp = [parseDate(props.value[0], props.format), parseDate(props.value[1], props.format)];
selected = tmp.slice();
actived = tmp.slice();
} else {
showPlaceholder = true;
let now = new Date();
actived = [now, goMonths(now, 1)];
}
this.state = {
value: [],
range: [],
selected,
actived,
activedTime: actived.slice(),
openPanel: false,
showPlaceholder
};
}
componentWillReceiveProps(next) {
if (next.value) {
const showPlaceholder = false;
const selected = [new Date(next.value[0]), new Date(next.value[1])];
this.setState({
value: [
formatDate(selected[0], next.format || this.props.format),
formatDate(selected[1], next.format || this.props.format)
],
selected,
actived: selected.slice(),
activedTime: selected.slice(),
openPanel: false,
showPlaceholder
});
}
}
clickOutside = e => {
if (!this.picker.contains(e.target)) {
this.setState({
openPanel: false
});
}
}
onHover = (val) => {
const { selected, range } = this.state;
const scp = selected.slice();
const rcp = range.slice();
if (scp.length !== 1) {
rcp.splice(0, 2);
return false;
}
if (rcp[0] && rcp[0] < val) {
rcp.splice(1, 1, val);
this.setState({
range: rcp
});
}
}
onSelect = (val) => {
const { selected, actived, range } = this.state;
const scp = selected.slice();
const acp = actived.slice();
const rcp = range.slice();
if (scp.length === 2) {
scp.splice(0, 2, val);
rcp.splice(0, 2, val);
acp.splice(0, 2, val, goMonths(val, 1));
} else if (scp[0] && scp[0] < val) {
scp.splice(1, 1, val);
if (scp[0].getMonth() < val.getMonth()) {
acp.splice(1, 1, val);
}
} else {
scp.splice(0, 1, val);
rcp.splice(0, 1, val);
acp.splice(0, 1, val, goMonths(val, 1));
}
this.setState({
selected: scp,
actived: acp,
range: rcp
});
}
isDisabled = (val) => {
const props = this.props;
if (props.disabledDate) {
if (isFunction(props.disabledDate)) {
return props.disabledDate(val);
}
if (isArray(props.disabledDate)) {
return !(val > new Date(props.disabledDate[0]) && val < new Date(props.disabledDate[1]));
}
}
return false;
}
onChangeDate = (val, i) => {
const { actived } = this.state;
const acp = actived.slice();
acp.splice(i, 1, val);
this.setState({
actived: acp
});
}
onChangeStart = (val) => {
this.onChangeDate(val, 0);
}
onChangeEnd = (val) => {
this.onChangeDate(val, 1);
}
onChangeTime = (val, i) => {
const { activedTime } = this.state;
const tcp = activedTime.slice();
tcp.splice(i, 1, val);
this.setState({
activedTime: tcp
});
}
onChangeStartTime = (val) => {
this.onChangeTime(val, 0);
}
onChangeEndTime = (val) => {
this.onChangeTime(val, 1);
}
onClickInput = () => {
this.setState({
openPanel: !this.state.openPanel
});
}
onConfirm = () => {
const { value, selected, activedTime } = this.state;
const props = this.props;
if (selected.length !== 2) {
return false;
}
const getDateTime = (date, time) => {
return new Date(
date.getFullYear(),
date.getMonth(),
date.getDate(),
time.getHours(),
time.getMinutes(),
time.getSeconds()
);
};
let vcp = value.slice();
if (props.showTime) {
const tmp = [
getDateTime(selected[0], activedTime[0]),
getDateTime(selected[1], activedTime[1])
];
const tmpFormat = `${props.format} ${props.showTime.format || TIME_PROPS.format}`;
vcp = [formatDate(tmp[0], tmpFormat), formatDate(tmp[1], tmpFormat)];
} else {
vcp = [formatDate(selected[0], props.format), formatDate(selected[1], props.format)];
}
this.setState({
value: vcp,
showPlaceholder: false,
openPanel: false
});
this.props.onChange(vcp);
}
render() {
const state = this.state;
const props = this.props;
const prefixCls = `${props.prefix}-datetime-picker ${props.className}`;
const inputCls = classNames({
'picker-input--range picker-input': true,
'picker-input--empty': state.showPlaceholder,
'picker-input--showTime': props.showTime
});
let rangePicker;
const getTimeConfig = (type) => {
const timeFnMap = {
start: this.onChangeStartTime,
end: this.onChangeEndTime
};
const indexMap = {
start: 0,
end: 1
};
return Object.assign({},
{
actived: state.activedTime[indexMap[type]],
format: TIME_PROPS.format,
disabledTime: TIME_PROPS.disabledTime
},
props.showTime || {},
{
disabledTime: props.disabledTime && props.disabledTime(type),
onChange: timeFnMap[type]
}
);
};
if (state.openPanel) {
const pickerCls = classNames({
'range-picker': true,
'range-picker--showTime': props.showTime
})
rangePicker = (
<div className={pickerCls}>
<div className="date-picker">
<DatePanel
range={state.range}
showTime={getTimeConfig('start')}
actived={state.actived[0]}
selected={state.selected}
disabledDate={this.isDisabled}
onSelect={this.onSelect}
onChange={this.onChangeStart}
onHover={this.onHover}
/>
</div>
<div className="date-picker">
<DatePanel
range={state.range}
showTime={getTimeConfig('end')}
actived={state.actived[1]}
selected={state.selected}
disabledDate={this.isDisabled}
onSelect={this.onSelect}
onChange={this.onChangeEnd}
onHover={this.onHover}
/>
</div>
<PanelFooter
onClickButton={this.onConfirm}
/>
</div >
);
}
return (
<div className={prefixCls} ref={ref => this.picker = ref}>
<div className="picker-wrapper">
<div className={inputCls} onClick={this.onClickInput}>
{state.showPlaceholder ? props.placeholder.join(' ~ ') : state.value.join(' ~ ')}
<span className="zenticon zenticon-calendar-o"></span>
</div>
{state.openPanel ? rangePicker : ''}
</div>
</div>
);
}
}
export default clickOutside(DateRangePicker);
| JavaScript | 0.999982 | @@ -5936,16 +5936,17 @@
%7D)
+;
%0A r
|
381a4f332e7c78dd81841a312f51348cc34600ef | Use UpdateUserNodeController | assets/js/app/settings/snapshots/snapshot-controller.js | assets/js/app/settings/snapshots/snapshot-controller.js | /**
* This file contains all necessary Angular controller definitions for 'frontend.admin.login-history' module.
*
* Note that this file should only contain controllers and nothing else.
*/
(function() {
'use strict';
angular.module('frontend.settings')
.controller('SnapshotController', [
'_','$scope', '$rootScope','$q','$log','$ngBootbox',
'SocketHelperService','MessageService','SnapshotsService',
'$state','$uibModal','DialogService','Snapshot',
'_snapshot',
function controller(_,$scope, $rootScope,$q,$log,$ngBootbox,
SocketHelperService, MessageService,SnapshotsService,
$state, $uibModal,DialogService,Snapshot,
_snapshot) {
$log.debug("Snapshot",_snapshot)
$scope.snapshot = _snapshot
// Hide the orderlist attribute of upstreams for faster rendering
if($scope.snapshot.data.upstreams) {
$scope.snapshot.data.upstreams.forEach(function(item){
item.orderlist = '( Not shown for faster DOM rendering... )'
})
}
$scope.downloadSnapshot = function() {
var dataStr = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONC.compress( $scope.snapshot )));
var dlAnchorElem = document.getElementById('downloadAnchorElem');
dlAnchorElem.setAttribute("href", dataStr );
dlAnchorElem.setAttribute("download", "snapshot_" + $scope.snapshot.name + ".jsonc");
dlAnchorElem.click();
}
$scope.showRestoreModal = function() {
var modalInstance = $uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'js/app/settings/snapshots/snapshot-apply-modal.html',
controller: function($scope,$uibModalInstance,SnapshotsService,UserService,_snapshot){
$scope.user = UserService.user()
$scope.ready = false;
$scope.imports = []
$scope.objects = {}
Object.keys(_snapshot.data).forEach(function(item){
$scope.objects[item] = {
isChecked : false
}
})
$scope.updateImports = function(){
$scope.imports = []
Object.keys($scope.objects).forEach(function(key){
if($scope.objects[key].isChecked) {
$scope.imports.push(key)
}
})
}
$scope.close = function(){
$uibModalInstance.dismiss()
}
$scope.selectNode = function() {
$uibModal.open({
animation: true,
ariaLabelledBy: 'modal-title',
ariaDescribedBy: 'modal-body',
templateUrl: 'js/app/settings/modals/connections-modal.html',
controller: ['$scope','$uibModalInstance','$log','NodeModel','InfoService','UserService','$localStorage','_nodes',
function($scope,$uibModalInstance,$log,NodeModel,InfoService,UserService,$localStorage,_nodes){
$scope.connections = _nodes
$scope.user = UserService.user()
$scope.node = $scope.user.node
$log.debug("connections",$scope.connections)
$scope.close = function(){
$uibModalInstance.dismiss()
}
$scope.closeAlert = function(index) {
$scope.alerts.splice(index, 1);
};
$scope.activateConnection = function(node) {
$scope.alerts = [];
if(node.active || node.checkingConnection) return false;
// Check if the connection is valid
node.checkingConnection = true;
InfoService.nodeStatus({
kong_admin_url : node.kong_admin_url
}).then(function(response){
$log.debug("Check connection:success",response)
node.checkingConnection = false;
NodeModel
.update(node.id,{active:!node.active})
.then(
function onSuccess(result) {
$localStorage.credentials.user.node = result.data
$rootScope.$broadcast('user.node.updated',result.data)
$scope.close()
},function(err){
$scope.busy = false
NodeModel.handleError($scope,err)
}
)
;
}).catch(function(error){
$log.debug("Check connection:error",error)
node.checkingConnection = false;
$scope.alerts.push({ type: 'danger', msg: 'Oh snap! Cannot connect to the selected node.' })
})
}
}],
controllerAs: '$ctrl',
resolve: {
_nodes: [
'_',
'ListConfig','SocketHelperService',
'NodeModel',
function resolve(
_,
ListConfig,SocketHelperService,
NodeModel
) {
return NodeModel.load({
sort: 'createdAt DESC'
});
}
]
}
});
}
$scope.restore = function () {
$scope.ready = true;
$scope.restoring = true
SnapshotsService.restoreSnapshot(_snapshot.id, $scope.imports)
.then(function(success){
$scope.results = success.data
$scope.restoring = false;
})
.catch(function(err){
$log.debug("restoreSnapshot:error",err)
$scope.restoring = false;
})
}
//restore()
},
resolve : {
_snapshot : function() {
return $scope.snapshot
}
}
});
modalInstance.result.then(function (d) {
}, function (result) {
});
}
}
])
;
}()); | JavaScript | 0.000001 | @@ -3727,3417 +3727,34 @@
er:
-%5B'$scope','$uibModalInstance','$log','NodeModel','InfoService','UserService','$localStorage','_nodes',%0A function($scope,$uibModalInstance,$log,NodeModel,InfoService,UserService,$localStorage,_nodes)%7B%0A%0A $scope.connections = _nodes%0A $scope.user = UserService.user()%0A $scope.node = $scope.user.node%0A%0A $log.debug(%22connections%22,$scope.connections)%0A%0A $scope.close = function()%7B%0A $uibModalInstance.dismiss()%0A %7D%0A%0A $scope.closeAlert = function(index) %7B%0A $scope.alerts.splice(index, 1);%0A %7D;%0A%0A $scope.activateConnection = function(node) %7B%0A%0A $scope.alerts = %5B%5D;%0A%0A if(node.active %7C%7C node.checkingConnection) return false;%0A%0A%0A // Check if the connection is valid%0A node.checkingConnection = true;%0A InfoService.nodeStatus(%7B%0A kong_admin_url : node.kong_admin_url%0A %7D).then(function(response)%7B%0A $log.debug(%22Check connection:success%22,response)%0A node.checkingConnection = false;%0A%0A%0A NodeModel%0A .update(node.id,%7Bactive:!node.active%7D)%0A .then(%0A function onSuccess(result) %7B%0A%0A $localStorage.credentials.user.node = result.data%0A $rootScope.$broadcast('user.node.updated',result.data)%0A $scope.close()%0A%0A %7D,function(err)%7B%0A $scope.busy = false%0A NodeModel.handleError($scope,err)%0A %7D%0A )%0A ;%0A%0A %7D).catch(function(error)%7B%0A $log.debug(%22Check connection:error%22,error)%0A node.checkingConnection = false;%0A $scope.alerts.push(%7B type: 'danger', msg: 'Oh snap! Cannot connect to the selected node.' %7D)%0A %7D)%0A %7D%0A %7D%5D
+'UpdateUserNodeController'
,%0A
|
79eb0bef6a2322feb6458e65e48e12d1848dc1a5 | revert slide show speed back to 9s | public/js/home-hero.js | public/js/home-hero.js | import carouselNavigation from "./carousel-navigation.js";
const homeHero = {
init() {
this.heroEl = document.querySelector(".js-home-hero");
this.heroFeatures = JSON.parse(
this.heroEl.getAttribute("data-hero-features")
);
this.heroOverlayEl = document.querySelector(".js-home-hero-overlay");
this.heroImageEl = document.querySelector(".js-home-hero-image");
this.headerEl = document.querySelector(".js-header");
this.heroEntryLinkEl = document.querySelector(
".js-home-hero-image-credit__entry-link"
);
this.heroCreditEl = document.querySelector(".js-home-hero-image-credit");
this.heroCountryEl = document.querySelector(
".js-home-hero-image-credit__country"
);
this.heroCreditTextEl = document.querySelector(
".js-home-hero-image-credit__credit"
);
window.addEventListener("resize", () => this.adjustHeight());
this.adjustHeight();
this.preloadImages();
this.initSlideshow();
},
preloadImages() {
this.heroFeatures.forEach(entry => {
const img = new Image();
img.src = entry.imageUrl;
});
},
initSlideshow() {
const carouselNav = Object.create(carouselNavigation);
carouselNav.init({
numItems: this.heroFeatures.length,
shouldShowArrows: false,
el: this.heroEl,
autoAdvanceIntervalinMs: 4000,
onChange: index => {
this.updateHero(index);
},
});
},
updateHero(index) {
const newEntry = this.heroFeatures[index];
// set opacity for transition
this.heroOverlayEl.style.opacity = 1;
this.heroCreditEl.style.opacity = 0;
setTimeout(() => {
// update image
if (this.heroImageEl) {
this.heroImageEl.style.backgroundImage = `url(${newEntry.imageUrl})`;
}
// update title
if (this.heroEntryLinkEl) {
this.heroEntryLinkEl.innerText = newEntry.entryTitle;
}
// update credit
if (this.heroCreditTextEl) {
if (newEntry.imageCredit) {
const i18nImageCredit = this.heroCreditTextEl.getAttribute("data-i18n-image-credit");
this.heroCreditTextEl.innerText = `${i18nImageCredit}: ${
newEntry.imageCredit
}`;
} else {
this.heroCreditTextEl.innerText = "";
}
}
// update country
if (this.heroCountryEl) {
if (newEntry.country) {
this.heroCountryEl.innerText = newEntry.country;
} else {
this.heroCountryEl.innerText = "";
}
}
// update link
if (this.heroEntryLinkEl) {
this.heroEntryLinkEl.setAttribute("href", newEntry.entryUrl);
}
// fade opacity back up to initial
this.heroOverlayEl.style.opacity = 0.5;
this.heroCreditEl.style.opacity = 1;
}, 250);
},
adjustHeight() {
// hero image should be the
// height of the browser window - the height of the header
const height = window.innerHeight - this.headerEl.offsetHeight;
this.heroEl.style.height = `${height}px`;
this.heroOverlayEl.style.height = `${height}px`;
this.heroImageEl.style.height = `${height}px`;
},
};
export default homeHero;
| JavaScript | 0 | @@ -1347,9 +1347,9 @@
Ms:
-4
+9
000,
|
837fbe84c8884ae12dbf9c306347aab532f9ad38 | Fix wrong reference to Image in InputSample | src/onyx-samples/src/InputSample.js | src/onyx-samples/src/InputSample.js | var
kind = require('enyo/kind'),
utils = require('enyo/utils');
var
EnyoImage = require('enyo/Image');
var
Checkbox = require('onyx/Checkbox'),
Groupbox = require('onyx/Groupbox'),
GroupboxHeader = require('onyx/GroupboxHeader'),
Input = require('onyx/Input'),
InputDecorator = require('onyx/InputDecorator'),
RichText = require('onyx/RichText'),
TextArea = require('onyx/TextArea');
module.exports = kind({
name: 'onyx.sample.InputSample',
classes: 'onyx onyx-sample',
components: [
{classes: 'onyx-sample-divider', content: 'Inputs'},
{classes: 'onyx-toolbar-inline', components: [
{kind: InputDecorator, components: [
{kind: Input, placeholder: 'Enter text here', onchange: 'inputChanged'}
]},
{kind: InputDecorator, components: [
{kind: Input, placeholder: 'Search term', onchange: 'inputChanged'},
{kind: EnyoImage, src: '@../assets/search-input-search.png'}
]},
{kind: InputDecorator, components: [
{kind: Input, type: 'password', placeholder: 'Enter password', onchange: 'inputChanged'}
]},
{content: 'alwaysLookFocused: '},
{kind: Checkbox, onchange: 'changeFocus'}
]},
{classes: 'onyx-toolbar-inline', components: [
{kind: InputDecorator, components: [
{kind: Input, disabled: true, value: 'Disabled input'}
]},
{kind: InputDecorator, components: [
{content: 'Left: '},
{kind: Input, value: 'Input Area', onchange: 'inputChanged'},
{content: ' :Right'}
]}
]},
{tag: 'br'},
{classes: 'onyx-sample-divider', content: 'RichTexts'},
{classes: 'onyx-toolbar-inline', components: [
{kind: InputDecorator, components: [
{kind: RichText, style: 'width: 200px;', placeholder: 'Enter text here', onchange: 'inputChanged'}
]},
{kind: InputDecorator, components: [
{kind: RichText, style: 'width: 200px;', placeholder: 'Search term', onchange: 'inputChanged'},
{kind: Image, src: '@../assets/search-input-search.png'}
]}
]},
{tag: 'br'},
{classes: 'onyx-sample-divider', content: 'TextAreas'},
{classes: 'onyx-toolbar-inline', components: [
{kind: InputDecorator, components: [
{kind: TextArea, placeholder: 'Enter text here', onchange: 'inputChanged'}
]},
{kind: InputDecorator, components: [
{kind: TextArea, placeholder: 'Search term', onchange: 'inputChanged'},
{kind: Image, src: '@../assets/search-input-search.png'}
]}
]},
{tag: 'br'},
{kind: Groupbox, classes: 'onyx-sample-result-box', components: [
{kind: GroupboxHeader, content: 'Result'},
{name: 'result', classes: 'onyx-sample-result', content: 'No input entered yet.'}
]}
],
inputChanged: function (sender, ev) {
this.$.result.setContent('Input: ' + sender.getValue());
},
changeFocus: function (sender, ev) {
utils.forEach([this.$.inputDecorator, this.$.inputDecorator2, this.$.inputDecorator3], function(inItem) {
inItem.setAlwaysLooksFocused(sender.getValue());
// If disabling alwaysLooksFocused, we need to blur the
// InputDecorator for the setting to go into effect
if (!sender.getValue()) {
inItem.triggerHandler('onblur');
}
});
}
}); | JavaScript | 0.000005 | @@ -1871,32 +1871,36 @@
d'%7D,%0A%09%09%09%09%7Bkind:
+Enyo
Image, src: '@..
@@ -2320,16 +2320,20 @@
%09%7Bkind:
+Enyo
Image, s
|
704030c432809f15581b17f6d90005f24e92acdd | Fix the factory function so that Sequelize 4.x is supported (#139) | src/hooks/hydrate.js | src/hooks/hydrate.js | const factory = (Model, include = null) => {
return item => {
if (!(item instanceof Model.Instance)) {
return Model.build(item, { isNewRecord: false, include });
}
return item;
};
};
export default options => {
options = options || {};
return function (hook) {
if (hook.type !== 'after') {
throw new Error('feathers-sequelize hydrate() - should only be used as an "after" hook');
}
const makeInstance = factory(this.Model, options.include);
switch (hook.method) {
case 'find':
if (hook.result.data) {
hook.result.data = hook.result.data.map(makeInstance);
} else {
hook.result = hook.result.map(makeInstance);
}
break;
case 'get':
case 'update':
hook.result = makeInstance(hook.result);
break;
case 'create':
case 'patch':
if (Array.isArray(hook.result)) {
hook.result = hook.result.map(makeInstance);
} else {
hook.result = makeInstance(hook.result);
}
break;
}
return Promise.resolve(hook);
};
};
| JavaScript | 0.000001 | @@ -65,45 +65,353 @@
-if (!(item instanceof Model.Instance)
+// (Darren): We have to check that the Model.Instance static property exists%0A // first since it's been deprecated in Sequelize 4.x.%0A // See: http://docs.sequelizejs.com/manual/tutorial/upgrade-to-v4.html%0A const shouldBuild = Model.Instance%0A ? !(item instanceof Model.Instance)%0A : !(item instanceof Model);%0A%0A if (shouldBuild
) %7B%0A
@@ -475,22 +475,23 @@
ude %7D);%0A
-
%7D%0A
+%0A
retu
|
08eaac64daa1b7bb5137261967cd7c655b7dbc1f | Use jQuery helpers for simplification and compat | jquery.sortBy-0.1.js | jquery.sortBy-0.1.js | /* uses schwartzian transform to sort the selected elements in-place */
(function($) {
$.fn.sortBy = function(sortfn) {
var values = [],
$self = this;
this.children().each(function(i,o) {
values.push([ $(o), sortfn($(o)) ]);
});
values.sort(function(a,b) {
return a[1] > b[1] ? 1
: a[1] == b[1] ? 0
: -1;
});
$.each(values, function(_,o) {
$self.append(o[0]);
});
};
})(jQuery);
| JavaScript | 0 | @@ -153,16 +153,25 @@
his;%0A%0A%09%09
+values =
this.chi
@@ -178,20 +178,19 @@
ldren().
-each
+map
(functio
@@ -195,18 +195,16 @@
ion(
-i,
o) %7B%0A%09%09%09
valu
@@ -203,20 +203,15 @@
%0A%09%09%09
-values.push(
+return
%5B $(
@@ -228,17 +228,16 @@
($(o)) %5D
-)
;%0A%09%09%7D);%0A
@@ -243,20 +243,23 @@
%0A%0A%09%09
-values.sort(
+$.sort(values,
func
|
69a349f1865e59c5751e6ec685e41b57bb1b1f9a | Update exampe with new react-filter-box version | js-example/server.js | js-example/server.js | var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true
}).listen(3011, 'localhost', function (err, result) {
if (err) {
return console.log(err);
}
console.log('Listening at http://localhost:3000/');
});
| JavaScript | 0 | @@ -260,10 +260,10 @@
n(30
-11
+00
, 'l
|
47fea97fdf28b3cfa89d97e307bb8e3f34370a31 | Change logged text data to object | js/NetworkManager.js | js/NetworkManager.js | import Logger from './Logger';
/**
* The NetworkManager handles the socket connection and
* dispatches receiving events
*/
export default class NetworkManager {
/**
* Default constructor
*/
constructor() {
this.logger = Logger.create({
prefix: '[NETWORK]'
});
this.connectCounter = 0;
}
async init() {
this.ckeckConfigExists();
this.connect();
}
ckeckConfigExists() {
if(CastleCrush.CONFIG) return true;
throw new Error('CONFIG is missing! Please set the correct path ' +
'or create one in the root folder!');
}
connect() {
this.state = 'connecting';
this.connectCounter++;
this.connection = new WebSocket(CastleCrush.CONFIG.SOCKET_ADDRESS);
this.connection.onopen = this.onopen.bind(this);
this.connection.onerror = this.onerror.bind(this);
this.connection.onmessage = this.onmessage.bind(this);
}
onopen() {
this.logger.info('You are successfully connected to the socket server!');
this.state = 'connected';
}
/**
* [onerror description]
*
* @param {[type]} error [description]
*/
onerror(error) {
if(
this.state == 'connecting' &&
this.connection.readyState === 3 &&
this.connectCounter < 5
) {
this.logger.warn('Server is not running! Attempt to start it');
fetch(CastleCrush.CONFIG.SERVER_START_ADDRESS)
.then(res => res.text())
.then(res => {
this.logger.info('Server says: ', res);
this.logger.info('Connecting again!');
this.connect();
})
.catch(error => {
CastleCrush.ViewManager.showError(
'Can not connect to socket server! ' +
'Open the log for more information!'
);
this.logger.error('Can not start socket server!');
this.logger.error(
'Maybe the SERVER_START_ADDRESS is not correct:',
CastleCrush.CONFIG.SERVER_START_ADDRESS
);
this.logger.error('The error is:', error.message);
throw error;
});
}
else {
CastleCrush.ViewManager.showError(
'You have a problem with your socket connection! ' +
'Open the log for more information!'
);
this.logger.error('You have a problem with your socket connection!');
this.logger.error('The error is:', error.message || error);
throw error;
}
}
onmessage(event) {
this.logger.info('You received a message: ', event.data);
event = JSON.parse(event.data);
CastleCrush.EventManager.dispatch(event.type, event, false);
}
send(data) {
this.logger.info('You are sending a message: ', JSON.stringify(data));
this.connection.send(JSON.stringify(data));
}
}
| JavaScript | 0.000001 | @@ -2265,24 +2265,58 @@
ge(event) %7B%0A
+%09%09event = JSON.parse(event.data);%0A
%09%09this.logge
@@ -2359,48 +2359,8 @@
vent
-.data);%0A%0A%09%09event = JSON.parse(event.data
);%0A%09
@@ -2489,37 +2489,21 @@
age: ',
-JSON.stringify(
data)
-)
;%0A%0A%09%09thi
|
2def3584fdad8caeb31c157befd40904c283eb9d | make the default widget factory of the select column public so other people can use it | src/ui/widgets/table/select_column.js | src/ui/widgets/table/select_column.js | goog.provide('recoil.ui.widgets.table.SelectColumn');
goog.require('recoil.frp.Debug');
goog.require('recoil.frp.struct');
goog.require('recoil.ui.widgets.SelectorWidget');
goog.require('recoil.ui.widgets.table.Column');
/**
*
* @param {recoil.structs.table.ColumnKey} key
* @param {string} name
* @param {recoil.frp.Behaviour<!Array<T>>|Array<T>} list
* @param {(recoil.frp.Behaviour<Object>|Object)=} opt_options
* @implements {recoil.ui.widgets.table.Column}
* @template T
* @constructor
*/
recoil.ui.widgets.table.SelectColumn = function(key, name, list, opt_options) {
this.key_ = key;
this.name_ = name;
this.list_ = list;
this.options_ = opt_options || {};
};
/**
*
* @param {recoil.ui.WidgetScope} scope
* @param {!recoil.frp.Behaviour<recoil.structs.table.TableCell>} cellB
* @return {recoil.ui.Widget}
* @private
*/
recoil.ui.widgets.table.SelectColumn.defaultWidgetFactory_ = function(scope, cellB) {
var frp = scope.getFrp();
var widget = new recoil.ui.widgets.SelectorWidget(scope);
var value = recoil.frp.table.TableCell.getValue(frp, cellB);
var metaData = recoil.frp.table.TableCell.getMeta(frp, cellB);
widget.attachStruct(recoil.frp.struct.extend(frp, metaData, {value: value}));
return widget;
};
/**
* adds all the meta information that a column should need
* this should at least include cellWidgetFactory
* other meta data can include:
* headerDecorator
* cellDecorator
* and anything else specific to this column such as options for a combo box
*
* @param {Object} curMeta
* @return {Object}
*/
recoil.ui.widgets.table.SelectColumn.prototype.getMeta = function(curMeta) {
var meta = {name: this.name_, list: this.list_,
cellWidgetFactory: recoil.ui.widgets.table.SelectColumn.defaultWidgetFactory_};
goog.object.extend(meta, this.options_, curMeta);
return meta;
};
/**
* @return {recoil.structs.table.ColumnKey}
*/
recoil.ui.widgets.table.SelectColumn.prototype.getKey = function() {
return this.key_;
};
| JavaScript | 0 | @@ -841,20 +841,8 @@
et%7D%0A
- * @private%0A
*/%0A
@@ -898,17 +898,16 @@
tFactory
-_
= funct
@@ -1786,17 +1786,16 @@
tFactory
-_
%7D;%0A%0A
|
38edd6de8818965b253cfc671b7b4dd2a6f4de11 | add android loc strat sanity test | test/functional/apidemos/basic.js | test/functional/apidemos/basic.js | /*global it:true */
"use strict";
var path = require('path')
, appPath = path.resolve(__dirname, "../../../sample-code/apps/ApiDemos/bin/ApiDemos-debug.apk")
, appPkg = "com.example.android.apis"
, appAct = "ApiDemos"
, describeWd = require("../../helpers/driverblock.js").describeForApp(appPath,
"android", appPkg, appAct)
, should = require('should');
describeWd('basic', function(h) {
it('should get device size', function(done) {
h.driver.getWindowSize(function(err, size) {
should.not.exist(err);
size.width.should.be.above(0);
size.height.should.be.above(0);
done();
});
});
it('should die with short command timeout', function(done) {
var params = {timeout: 3};
h.driver.execute("mobile: setCommandTimeout", [params], function(err) {
should.not.exist(err);
var next = function() {
h.driver.elementByName('Animation', function(err) {
should.exist(err);
[13, 6].should.include(err.status);
done();
});
};
setTimeout(next, 4000);
});
});
});
| JavaScript | 0 | @@ -1075,12 +1075,460 @@
;%0A %7D);%0A
+ it('should not fail even when bad locator strats sent in', function(done) %7B%0A h.driver.elementByLinkText(%22foobar%22, function(err) %7B%0A should.exist(err);%0A err.status.should.equal(13);%0A err.cause.value.origValue.should.eql(%22link text is not a supported selector strategy%22);%0A h.driver.elementByName(%22Animation%22, function(err, el) %7B%0A should.not.exist(err);%0A should.exist(el);%0A done();%0A %7D);%0A %7D);%0A %7D);%0A
%7D);%0A
|
c129970b63ccdfbcedca9565d3796f36931362c1 | make sure .uri references are injected | source/application/layouts/index.js | source/application/layouts/index.js | import path from 'path';
export default layout;
function layout(props) {
const styleRefs = (props.reference.style || []).filter(isReference);
const scriptRefs = (props.reference.script || []).filter(isReference);
return `<!doctype html>
<html>
<head>
<title>${props.title}</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
<link rel="icon" href="data:;base64,iVBORw0KGgo=">
${styleRefs
.filter(isAbsolute)
.map(style => `<link rel="stylesheet" href="/api/resource/${style.id}.css">`)
.join('\n')}
${styleRefs
.filter(isRelative)
.map(style => `<link rel="stylesheet" href="${style.id}">`)
.join('\n')}
${(props.content.style || [])
.map(style => style.wrap === false ? style.content : `<style>${style.content}</style>`)
.join('\n')}
${(props.reference.markup || [])
.map(m => `<link rel="m" href="/api/resource/${m.uri}.html">`)
.join('\n')}
</head>
<body>
${(props.content.markup || [])
.map(markup => markup.content)
.join('\n')}
${scriptRefs
.filter(isAbsolute)
.map(script => `<script src="/api/resource/${script.id}.js"></script>`)
.join('\n')}
${scriptRefs
.filter(isRelative)
.map(script => `<script src="${script.id}"></script>`)
.join('\n')}
${props.content.script || []
.filter(Boolean)
.filter(script => Boolean(script.content))
.map(script => script.wrap === false ? script.content : `<script>${script.content}</script>`)
.join('\n')}
</body>
</html>
`;
}
function isAbsolute(reference) {
return !isRelative(reference);
}
function isReference(reference) {
return 'id' in reference;
}
function isRelative(reference) {
return (reference.id || '').charAt(0) === '.';
}
| JavaScript | 0 | @@ -1610,16 +1610,38 @@
ference)
+ && !hasUri(reference)
;%0A%7D%0A%0Afun
@@ -1683,16 +1683,38 @@
urn 'id'
+ in reference %7C%7C 'uri'
in refe
@@ -1802,12 +1802,93 @@
=== '.'
+ %7C%7C%C2%A0hasUri(reference);%0A%7D%0A%0Afunction hasUri(reference) %7B%0A%09return 'uri' in reference
;%0A%7D%0A
|
04a01b66d2f0f8d629f5a1076c40c2b65027bcd0 | Fix tshirt card names | js/app/CardsModel.js | js/app/CardsModel.js | (function (stampit, spoker) {
spoker.CardsModel = stampit.compose(spoker.Model, stampit().enclose(function () {
function fibonacci(test, acc) {
var val;
if (acc.length < 2) {
val = 1;
} else {
val = acc[acc.length - 2] + acc[acc.length - 1];
}
if (test(val)) {
acc.push(val);
return fibonacci(test, acc);
}
return acc;
}
function getFibonacciCards() {
return fibonacci(function (last) {
return last < 100; // generate fibonacci until last item is less then 100
}, [0]).reduce(function (prev, current, index, array) {
var arr = prev || [prev];
if (arr.indexOf(current) === -1) {
return arr.concat(current);
}
return arr;
}, ['?', 0.5]);
}
function getTshirtCards() {
return ['XS', 'S', 'M', 'L', 'XL', 'XL', '?'];
}
function getStandardCards() {
return ['coffe', '?', 0, 0.5, 1, 2, 3, 5, 8, 13, 20, 40, 100, Infinity];
}
this.getStandard = getStandardCards;
this.getTshirt = getTshirtCards;
this.getFibonacci = getFibonacciCards;
}));
}(window.stampit, window.spoker || {}));
| JavaScript | 0.000028 | @@ -1039,24 +1039,25 @@
'L', 'XL', '
+X
XL', '?'%5D;%0A
|
c270947ca4113c00e2a7616ccedc10ba27943946 | Remove unused var | static/js/states/jobDetails.js | static/js/states/jobDetails.js | define([
'app',
'utils/sortArray'
], function(app, sortArray) {
'use strict';
var BUFFER_SIZE = 10000;
return {
url: "jobs/:job_id/",
parent: 'build_details',
templateUrl: 'partials/job-details.html',
controller: function($scope, $http, $filter, projectData, buildData, Collection,
jobData, phaseList, ItemPoller, PageTitle, Pagination) {
function updateJob(data){
if (data.id !== $scope.job.id) {
return;
}
$scope.$apply(function() {
$scope.job = data;
});
}
function getPageTitle(build, job) {
if (build.number) {
return 'Job #' + build.number + '.' + job.number +' - ' + projectData.name;
}
return 'Job ' + job.id + ' - ' + projectData.name;
}
function processPhase(phase) {
if (phase.isVisible === undefined) {
phase.isVisible = phase.status.id != 'finished' || phase.result.id != 'passed';
}
phase.steps = new Collection(phase.steps, {
sortFunc: function(arr) {
function getScore(object) {
return [object.result.id == 'failed' ? 1 : 2, object.name];
}
return sortArray(arr, getScore, false);
}
});
phase.totalSteps = phase.steps.length;
var finishedSteps = 0;
$.each(phase.steps, function(_, step){
if (step.status.id == 'finished') {
finishedSteps += 1;
}
});
phase.finishedSteps = finishedSteps;
}
$.map(phaseList, processPhase);
$scope.job = jobData;
$scope.phaseList = new Collection(phaseList, {
sortFunc: function(arr) {
function getScore(object) {
return [new Date(object.dateStarted || object.dateCreated).getTime()];
}
return sortArray(arr, getScore);
}
});
$scope.testFailures = jobData.testFailures;
$scope.previousRuns = new Collection(jobData.previousRuns);
PageTitle.set(getPageTitle(buildData, $scope.job));
// TODO(dcramer): support long polling with offsets
var poller = new ItemPoller({
$scope: $scope,
endpoint: '/api/0/jobs/' + jobData.id + '/',
update: function(response) {
if (response.dateModified < $scope.job.dateModified) {
return;
}
$.extend(true, $scope.job, response);
$.extend(true, $scope.testFailures, response.testFailures);
$scope.previousRuns.extend(response.previousRuns);
}
});
var phasesPoller = new ItemPoller({
$scope: $scope,
endpoint: '/api/0/jobs/' + jobData.id + '/phases/',
update: function(response) {
$scope.phaseList.extend(response);
$.map($scope.phaseList, processPhase);
}
});
},
resolve: {
jobData: function($http, $stateParams) {
return $http.get('/api/0/jobs/' + $stateParams.job_id + '/').then(function(response){
return response.data;
});
},
phaseList: function($http, $stateParams) {
return $http.get('/api/0/jobs/' + $stateParams.job_id + '/phases/').then(function(response){
return response.data;
});
}
}
};
});
| JavaScript | 0.000001 | @@ -82,36 +82,8 @@
';%0A%0A
- var BUFFER_SIZE = 10000;%0A%0A
re
|
df9ccd50c5fb6475a88f4aac77cd0848e2bf7682 | Update img path | js/canvasServices.js | js/canvasServices.js | /*global noiseServices*/
var canvasServices = (function () {
'use strict';
var canvas = document.getElementById('mainCanvas'),
ctx = canvas.getContext('2d'),
fps = 0,
lastCalledTime,
hasBasePicture = true,
hasNoise = true,
hasHueVariation = false,
requestId = 0,
unalteredData = [],
loopIndex = 0,
speed = 0,
intensity = 0,
privateMethods = {
saveUnalteredData: function () {
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height);
unalteredData = imgData.data;
},
draw: function () {
var imgData = ctx.getImageData(0, 0, canvas.width, canvas.height),
data = imgData.data,
x,
y,
cell,
noiseValue = 0;
privateMethods.updateFps();
loopIndex += speed;
for (x = 0; x < canvas.width; x += 1) {
for (y = 0; y < canvas.height; y += 1) {
cell = (x + y * canvas.width) * 4;
if (hasNoise) {
noiseValue = Math.abs(noiseServices.getNoiseValue(x, y, loopIndex)) * 256;
}
data[cell] = privateMethods.getNewDataCell(cell, noiseValue, privateMethods.getHueVariation(0));
data[cell + 1] = privateMethods.getNewDataCell(cell + 1, noiseValue, privateMethods.getHueVariation(10));
data[cell + 2] = privateMethods.getNewDataCell(cell + 2, noiseValue, privateMethods.getHueVariation(20));
}
}
ctx.putImageData(imgData, 0, 0);
requestId = window.requestAnimationFrame(privateMethods.draw);
},
updateFps: function () {
if (!lastCalledTime) {
lastCalledTime = Date.now();
fps = 0;
return;
}
var delta = (Date.now() - lastCalledTime) / 1000;
lastCalledTime = Date.now();
fps = 1 / delta;
},
getNewDataCell: function (cell, noiseValue, hueVariation) {
var dataCell = 0;
if (!hasBasePicture && hasNoise) {
dataCell = noiseValue * intensity * hueVariation;
} else if (hasBasePicture && !hasNoise) {
dataCell = Math.max(Math.min(unalteredData[cell] * hueVariation, 255), 0);
} else if (hasBasePicture && hasNoise) {
dataCell = Math.max(Math.min(unalteredData[cell] * (1 + intensity) - noiseValue * intensity * hueVariation, 255), 0);
}
return dataCell;
},
getHueVariation: function (index) {
if (!hasHueVariation) {
return 1;
}
return (hasHueVariation) ? (noiseServices.getSimpleNoise(loopIndex + speed * index, loopIndex + speed * index) + 1) * 2 : 1;
}
};
return {
createImage: function (imgName, size, callback) {
if (typeof size === 'undefined' || parseInt(size, 10) === 0) {
size = 9999999;
}
var img = new Image();
img.crossOrigin = 'Anonymous';
img.src = 'img/' + imgName + '.jpg';
img.onload = function () {
var divWidth = document.getElementById('canvasContainer').offsetWidth - 30,
width = Math.min(divWidth, img.width, size),
height = img.height * width / img.width;
canvas.width = width;
canvas.height = height;
ctx.drawImage(img, 0, 0, width, height);
privateMethods.saveUnalteredData();
if (callback) {
callback(width);
}
};
},
run: function () {
if (requestId === 0) {
requestId = window.requestAnimationFrame(privateMethods.draw);
}
},
getFps: function () {
return fps;
},
updateModes: function (newHasBasePicture, newHasNoise, newHasHueVariation) {
hasBasePicture = newHasBasePicture;
hasNoise = newHasNoise;
hasHueVariation = newHasHueVariation;
},
updateSpeed: function (newSpeed) {
speed = newSpeed;
},
updateIntensity: function (newIntensity) {
intensity = newIntensity;
}
};
}());
| JavaScript | 0.000001 | @@ -3495,16 +3495,18 @@
.src = '
+./
img/' +
|
7f706e824de78494ee7fb66bc528aac5161a0bdb | Use exact types for options | packager/src/ModuleGraph/types.flow.js | packager/src/ModuleGraph/types.flow.js | /**
* Copyright (c) 2016-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @flow
*/
'use strict';
import type {SourceMap} from './output/source-map';
import type {Ast} from 'babel-core';
import type {Console} from 'console';
export type Callback<A = void, B = void>
= (Error => void)
& ((null | void, A, B) => void);
type Dependency = {|
id: string,
path: string,
|};
export type File = {|
code: string,
map?: ?Object,
path: string,
type: FileTypes,
|};
type FileTypes = 'module' | 'script';
export type GraphFn = (
entryPoints: Iterable<string>,
platform: string,
options?: ?GraphOptions,
callback?: Callback<GraphResult>,
) => void;
type GraphOptions = {|
log?: Console,
optimize?: boolean,
skip?: Set<string>,
|};
export type GraphResult = {
entryModules: Array<Module>,
modules: Array<Module>,
};
export type IdForPathFn = {path: string} => number;
export type LoadFn = (
file: string,
options: LoadOptions,
callback: Callback<File, Array<string>>,
) => void;
type LoadOptions = {|
log?: Console,
optimize?: boolean,
platform?: string,
|};
export type Module = {|
dependencies: Array<Dependency>,
file: File,
|};
export type OutputFn = (
modules: Iterable<Module>,
filename?: string,
idForPath: IdForPathFn,
) => OutputResult;
type OutputResult = {
code: string,
map: SourceMap,
};
export type PackageData = {|
browser?: Object | string,
main?: string,
name?: string,
'react-native'?: Object | string,
|};
export type ResolveFn = (
id: string,
source: ?string,
platform: string,
options?: ResolveOptions,
callback: Callback<string>,
) => void;
type ResolveOptions = {
log?: Console,
};
export type TransformerResult = {
ast: ?Ast,
code: string,
map: ?SourceMap,
};
export type Transformer = {
transform: (
sourceCode: string,
filename: string,
options: ?{},
plugins?: Array<string | Object | [string | Object, any]>,
) => {ast: ?Ast, code: string, map: ?SourceMap}
};
export type TransformResult = {|
code: string,
dependencies: Array<string>,
dependencyMapName?: string,
map: ?Object,
|};
export type TransformResults = {[string]: TransformResult};
export type TransformVariants = {[key: string]: Object};
export type TransformedFile = {
code: string,
file: string,
hasteID: ?string,
package?: PackageData,
transformed: TransformResults,
type: FileTypes,
};
| JavaScript | 0 | @@ -1012,17 +1012,18 @@
sult = %7B
+%7C
%0A
-
entryM
@@ -1071,19 +1071,20 @@
odule%3E,%0A
+%7C
%7D;%0A
-
%0Aexport
@@ -1550,24 +1550,25 @@
utResult = %7B
+%7C
%0A code: str
@@ -1582,35 +1582,36 @@
map: SourceMap,%0A
+%7C
%7D;%0A
-
%0Aexport type Pac
@@ -1955,16 +1955,17 @@
sult = %7B
+%7C
%0A ast:
@@ -2005,16 +2005,17 @@
rceMap,%0A
+%7C
%7D;%0A%0Aexpo
|
b31eb0d508c3a7faea8acdca194847c9e56de07a | Correct discovery URL for observe example | js/client.observe.js | js/client.observe.js | var intervalId,
iotivity = require( "iotivity" ),
handle = {};
// Construct the absolute URL for the resource from the OCDoResource() response
function getAbsoluteUrl( response ) {
var ipv4Bytes = [],
portHolder = {};
if ( iotivity.OCStackResult.OC_STACK_OK !==
iotivity.OCDevAddrToIPv4Addr( response.addr, ipv4Bytes ) ) {
return;
}
if ( iotivity.OCStackResult.OC_STACK_OK !==
iotivity.OCDevAddrToPort( response.addr, portHolder ) ) {
return;
}
return "coap://" +
ipv4Bytes[ 0 ] + "." + ipv4Bytes[ 1 ] + "." + ipv4Bytes[ 2 ] + "." + ipv4Bytes[ 3 ] + ":" +
portHolder.port + JSON.parse( response.resJSONPayload ).oic[ 0 ].href;
}
iotivity.OCInit( null, 0, iotivity.OCMode.OC_CLIENT );
intervalId = setInterval( function() {
iotivity.OCProcess();
}, 100 );
// Initial call by which we discover the resource we wish to observe
iotivity.OCDoResource(
handle,
iotivity.OCMethod.OC_REST_GET,
"/oc/core",
null,
null,
iotivity.OCConnectivityType.OC_ALL,
iotivity.OCQualityOfService.OC_HIGH_QOS,
function( handle, response ) {
var observeHandle = {},
absoluteUrl = getAbsoluteUrl( response );
console.log( "OCDoResource() handler for discovery: Entering" );
console.log( "absolute url discovered: " + absoluteUrl );
if ( absoluteUrl ) {
// With this second call we request notifications for this resource
iotivity.OCDoResource(
observeHandle,
iotivity.OCMethod.OC_REST_OBSERVE,
absoluteUrl,
null,
null,
response.connType,
iotivity.OCQualityOfService.OC_HIGH_QOS,
function( handle, response ) {
console.log( "OCDoResource() handler for notification: Entering" );
console.log( response );
return iotivity.OCStackApplicationResult.OC_STACK_KEEP_TRANSACTION;
},
null,
0 );
}
return iotivity.OCStackApplicationResult.OC_STACK_DELETE_TRANSACTION;
},
null,
0 );
process.on( "SIGINT", function() {
console.log( "SIGINT: Quitting..." );
clearInterval( intervalId );
iotivity.OCStop();
process.exit( 0 );
} );
| JavaScript | 0 | @@ -921,14 +921,14 @@
%09%22/o
+i
c/
-co
re
+s
%22,%0A%09
|
23c2bad44cf66c05de53f5be6ed590697b1b383d | add back removed login check | source/views/stoprint/print-jobs.js | source/views/stoprint/print-jobs.js | // @flow
import React from 'react'
import {Platform, SectionList} from 'react-native'
import {connect} from 'react-redux'
import {type ReduxState} from '../../flux'
import {updatePrintJobs} from '../../flux/parts/stoprint'
import {type PrintJob, STOPRINT_HELP_PAGE} from '../../lib/stoprint'
import {
ListRow,
ListSeparator,
ListSectionHeader,
Detail,
Title,
} from '../components/list'
import LoadingView from '../components/loading'
import type {TopLevelViewPropsType} from '../types'
import delay from 'delay'
import openUrl from '../components/open-url'
import {StoPrintErrorView, StoPrintNoticeView} from './components'
import groupBy from 'lodash/groupBy'
import toPairs from 'lodash/toPairs'
import sortBy from 'lodash/sortBy'
type ReactProps = TopLevelViewPropsType
type ReduxStateProps = {
jobs: Array<PrintJob>,
error: ?string,
loading: boolean,
loginState: string,
}
type ReduxDispatchProps = {
updatePrintJobs: () => Promise<any>,
}
type Props = ReactProps & ReduxDispatchProps & ReduxStateProps
class PrintJobsView extends React.PureComponent<Props> {
static navigationOptions = {
title: 'Print Jobs',
headerBackTitle: 'Jobs',
}
componentDidMount() {
this.fetchData()
}
refresh = async (): any => {
let start = Date.now()
await this.fetchData()
// console.log('data returned')
// wait 0.5 seconds – if we let it go at normal speed, it feels broken.
let elapsed = start - Date.now()
if (elapsed < 500) {
await delay(500 - elapsed)
}
}
fetchData = () => this.props.updatePrintJobs()
keyExtractor = (item: PrintJob) => item.id.toString()
openSettings = () => this.props.navigation.navigate('SettingsView')
handleJobPress = (job: PrintJob) => {
if (job.statusFormatted === 'Pending Release') {
this.props.navigation.navigate('PrinterListView', {job: job})
} else {
this.props.navigation.navigate('PrintJobReleaseView', {job: job})
}
}
renderItem = ({item}: {item: PrintJob}) => (
<ListRow onPress={() => this.handleJobPress(item)}>
<Title>{item.documentName}</Title>
<Detail>
{item.usageTimeFormatted} {' • '} {item.usageCostFormatted} {' • '}
{item.totalPages} {item.totalPages === 1 ? 'page' : 'pages'} {'\n'}
{item.statusFormatted}
</Detail>
</ListRow>
)
renderSectionHeader = ({section: {title}}: any) => (
<ListSectionHeader title={title} />
)
render() {
if (this.props.loginState === 'checking') {
return <LoadingView text="Logging in…" />
} else if (this.props.loading && this.props.jobs.length === 0) {
return <LoadingView text="Fetching stoPrint Jobs…" />
}
if (this.props.error) {
return (
<StoPrintErrorView
navigation={this.props.navigation}
refresh={this.fetchData}
/>
)
}
if (this.props.jobs.length === 0) {
const instructions =
Platform.OS === 'android'
? 'using the Mobility Print app'
: 'using the Print option in the Share Sheet'
const descriptionText = `You can print from a computer, or by ${instructions}.`
return (
<StoPrintNoticeView
buttonText="Learn how to use stoPrint"
description={descriptionText}
header="Nothing to Print!"
onPress={() => openUrl(STOPRINT_HELP_PAGE)}
refresh={this.fetchData}
text="Need help getting started?"
/>
)
}
const grouped = groupBy(this.props.jobs, j => j.statusFormatted || 'Other')
let groupedJobs = toPairs(grouped).map(([title, data]) => ({
title,
data,
}))
let sortedGroupedJobs = sortBy(groupedJobs, [
group => group.title !== 'Pending Release', // puts 'Pending Release' jobs at the top
])
return (
<SectionList
ItemSeparatorComponent={ListSeparator}
keyExtractor={this.keyExtractor}
onRefresh={this.refresh}
refreshing={this.props.loading}
renderItem={this.renderItem}
renderSectionHeader={this.renderSectionHeader}
sections={sortedGroupedJobs}
/>
)
}
}
function mapStateToProps(state: ReduxState): ReduxStateProps {
return {
jobs: state.stoprint ? state.stoprint.jobs : [],
error: state.stoprint ? state.stoprint.error : null,
loading: state.stoprint ? state.stoprint.loadingJobs : false,
loginState: state.settings ? state.settings.loginState : 'logged-out',
}
}
function mapDispatchToProps(dispatch): ReduxDispatchProps {
return {
updatePrintJobs: () => dispatch(updatePrintJobs()),
}
}
export const ConnectedPrintJobsView = connect(
mapStateToProps,
mapDispatchToProps,
)(PrintJobsView)
| JavaScript | 0.000001 | @@ -2731,32 +2731,347 @@
%3E%0A%09%09%09)%0A%09%09%7D%0A%09%09if
+(this.props.loginState !== 'logged-in') %7B%0A%09%09%09return (%0A%09%09%09%09%3CStoPrintNoticeView%0A%09%09%09%09%09buttonText=%22Open Settings%22%0A%09%09%09%09%09header=%22You are not logged in%22%0A%09%09%09%09%09onPress=%7Bthis.openSettings%7D%0A%09%09%09%09%09refresh=%7Bthis.fetchData%7D%0A%09%09%09%09%09text=%22You must be logged in to your St. Olaf account to access this feature%22%0A%09%09%09%09/%3E%0A%09%09%09)%0A%09%09%7D else if
(this.props.jobs
|
675055a587d399c81cfe1535307c0c1575a37c5a | Patch for Pong in preso2 (better) | js/foam/flow/Pong.js | js/foam/flow/Pong.js |
/**
* @license
* Copyright 2015 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*/
CLASS({
name: 'Pong',
package: 'foam.flow',
extendsModel: 'foam.flow.Section',
requires: [
'foam.flow.CodeView',
'foam.flow.QuoteCode',
'foam.flow.ExpandableSection',
'foam.ui.md.SectionView'
],
properties: [
{
name: 'mode',
defaultValue: 'read-only'
}
],
imports: [
'FOAMWindow'
],
methods: {
init: function() {
this.SUPER.apply(this, arguments);
this.X.registerModel(this.CodeView.xbind({
readOnlyMinLines: 1,
readOnlyMaxLines: 100
}), 'foam.flow.CodeView');
this.X.registerModel(this.SectionView.xbind({
expandedIconUrl: 'https://www.gstatic.com/images/icons/material/system/1x/expand_less_black_36dp.png'
}), 'foam.ui.md.SectionView');
// TODO: Remove this stuff once the template parser understand unknown tags
// better
this.CodeView.getProperty('registerElement').documentInstallFn.call(
this.CodeView.getPrototype(), this.X);
this.QuoteCode.getProperty('registerElement').documentInstallFn.call(
this.QuoteCode.getPrototype(), this.X);
this.ExpandableSection.getProperty('registerElement').documentInstallFn.call(
this.ExpandableSection.getPrototype(), this.X);
}
},
templates: [
{ name: 'toInnerHTML' },
{
name: 'CSS',
template: multiline(function() {/*
pong { position: absolute; top: 0px }
pong p { padding: 10px; }
pong code, pong code-view {
font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;
}
pong expandable-section {
padding: 0px 30px;
}
pong li, pong heading, pong heading * {
font-size: 30px;
margin: 4px 0px 2px 0px;
}
pong p, pong li * {
font-size: 14px;
font-family: arial, sans-serif;
}
*/})
}
]
});
| JavaScript | 0 | @@ -1673,24 +1673,30 @@
%7B/*%0A
+.card
pong %7B posit
|
eb02ab83145067d048cf5ff79f523ad90f1f1749 | Update gulp module configuration | js/forum/Gulpfile.js | js/forum/Gulpfile.js | var gulp = require('flarum-gulp');
gulp({
modulePrefix: 'tags'
});
| JavaScript | 0 | @@ -48,22 +48,42 @@
dule
-Prefix: 'tags'
+s: %7B%0A 'tags': 'src/**/*.js'%0A %7D
%0A%7D);
|
db20033a727fb0abebaf793bd12a4ea31eae8e56 | update annotation text per feedback | js/plot/util/annotations/annotationdefinitions.js | js/plot/util/annotations/annotationdefinitions.js | /*
* == BSD2 LICENSE ==
* Copyright (c) 2014, Tidepool Project
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the associated License, which is identical to the BSD 2-Clause
* License as published by the Open Source Initiative at opensource.org.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the License for more details.
*
* You should have received a copy of the License along with this program; if
* not, you can obtain one from Tidepool Project at tidepool.org.
* == BSD2 LICENSE ==
*/
// You can view the full text of each annotation by running mocha test/annotations_test.js
var format = require('../../../data/util/format');
var definitions = {
LEAD_TEXT: {
'stats-insufficient-data': function() {
return 'Why is this grey?';
},
'stats-how-calculated': function() {
return 'What is this?';
}
},
MAIN_TEXT: {
'carelink/basal/fabricated-from-schedule': function(source, defs) {
var a = "We are calculating the basal rates here using the active basal schedule in your pump settings (and applying the percentage of an active temp basal where applicable), but ";
var b = " did not directly provide us with these rate changes.";
return defs.stitch(a, b, source);
},
'carelink/basal/fabricated-from-suppressed': function(source, defs) {
var a = "We are deriving the basal rate to display here assuming that your pump resumed to the basal that was active before the pump was suspended, but ";
var b = " did not directly provide us with this rate change.";
return defs.stitch(a, b, source);
},
'carelink/basal/off-schedule-rate': function(source, defs) {
var a = "You may have changed pumps recently - perhaps because you had to have your pump replaced due to malfuction. As a result of how ";
var b = " reports the data, we can't be 100% certain of your basal rate here.";
return defs.stitch(a, b, source);
},
'carelink/bolus/missing-square-component': function(source, defs) {
var a = "Because of how ";
var b = " reports bolus and wizard data, we may have failed to combine a square-wave bolus with this normal bolus to display a dual-wave bolus.";
return defs.stitch(a, b, source);
},
'carelink/wizard/long-search': function(source, defs) {
var a = "Because of how ";
var b = " reports bolus and wizard data, we can't be 100% certain that the bolus wizard information here (e.g., carbs, suggested dose) corresponds with the bolus.";
return defs.stitch(a, b, source);
},
'basal/intersects-incomplete-susppend': function() {
return "Within this basal segment, we are omitting a suspend event that didn't end. This may have resulted from switching to a new device. As a result, this basal segment may be inaccurate.";
},
'basal/mismatched-series': function() {
return "A basal rate segment may be missing here because it wasn't reported to the Tidepool API in sequence. We can't be 100% certain of your basal rate here.";
},
'basal/unknown-duration': function(source, defs) {
var a = "Because of how ";
var b = " reports the data, we could not determine the duration of this basal rate segment.";
return defs.stitch(a, b, source);
},
'stats-insufficient-data': function() {
return 'There is not enough data to show this statistic.';
},
'stats-how-calculated-ratio': function() {
return 'Basal insulin keeps your glucose within your target range when you are not eating. Bolus insulin is mostly used to cover the carbohydrates you eat or to bring a high glucose back into your target range. This ratio allows you to compare how much of the insulin you are taking is used for each purpose. We will only show numbers if there is enough basal data - 24 hours in the one day view and 7 days in the two week view.';
},
'stats-how-calculated-range-cbg': function() {
return 'With diabetes, any time in range is hard to achieve! This shows the percentage of time your CGM was in range, which can help you see how you are doing overall. We will only show a number if there is enough data - readings for at least 75% of the day in the one day view, and 75% of the day for at least half of the days shown in the two week view.';
},
'stats-how-calculated-range-smbg': function() {
return 'With diabetes, any reading in range is hard to achieve! If you don’t wear a CGM or don’t have enough CGM data, this shows how many of your fingerstick readings were in range, which can help you see how you are doing overall. We will only show a number if there is enough data - at least 4 readings in the one day view, and at least 4 readings for at least half of the days shown in the two week view.';
},
'stats-how-calculated-average-cbg': function() {
return 'To get one number that gives you a rough idea of your glucose level we add together all of the CGM glucose readings you have and then divide them by the number of glucose readings. We will only show a number if there is enough data - readings for at least 75% of the day in the one day view, and readings for at least 75% of the day for at least half of the days shown in the two week view.';
},
'stats-how-calculated-average-smbg': function() {
return 'If you don’t wear a CGM or don’t have enough CGM data, to get one number that gives you a rough idea of your glucose level, we add together all of the fingerstick readings you have and then divide them by the number of readings. We will only show a number if there is enough data - at least 4 readings in the one day view, and at least 4 readings for at least half of the days shown in the two week view.';
}
},
default: function(source) {
if (source == null) {
return "We can't be 100% certain of the data displayed here.";
}
var a = "We can't be 100% certain of the data displayed here because of how ";
var b = " reports the data.";
return this.stitch(a, b, source);
},
main: function(annotation, source) {
var a, b;
if (this.MAIN_TEXT[annotation.code] != null) {
return this.MAIN_TEXT[annotation.code](source, this);
}
else {
return this.default(source);
}
},
stitch: function(a, b, source) {
var sourceText = source === 'carelink' ? ' CareLink' : format.capitalize(source);
return a + sourceText + b;
},
lead: function(code) {
code = code || '';
if (this.LEAD_TEXT[code] != null) {
return this.LEAD_TEXT[code]();
}
else {
return false;
}
}
};
module.exports = definitions;
| JavaScript | 0 | @@ -2287,91 +2287,83 @@
ta,
-we may have failed to combine a square-wave bolus with this normal bolus to display
+this normal and square-wave bolus may not be properly combined to appear as
a d
|
fb11cea191a87815f07f9a64bb7be42d86ee5934 | use provided providerFields in my-provider-fields directive | coopr-ui/app/directives/providerfields/providerfields.js | coopr-ui/app/directives/providerfields/providerfields.js | /**
* myProviderFields
*/
angular.module(PKG.name+'.commons').directive('myProviderFields',
function myProviderFieldsDirective () {
return {
restrict: 'E',
templateUrl: 'providerfields/providerfields.html',
scope: {
model: '=',
provider: '='
},
controller: function ($scope, myApi) {
var allTypes, typeReqs = [];
myApi.ProviderType.query(function (result) {
allTypes = result;
$scope.$watch('provider', setFields);
$scope.$watchCollection('model', setRequired);
});
function setFields () {
var fields = {},
model = {},
providerType = allTypes.filter(function (type) {
return $scope.provider && type.name === $scope.provider.providertype;
})[0];
typeReqs = [];
angular.forEach(['user', 'admin'], function (role) {
var p = providerType && providerType.parameters[role];
if(p) {
if(p.required) {
typeReqs = typeReqs.concat(p.required);
}
angular.forEach(p.fields, function (val, key) {
if(role==='user' || val.override) {
fields[key] = val;
}
});
}
});
$scope.fields = fields;
angular.forEach(fields, function (field, key) {
if(field.default) {
model[key] = field.default;
}
});
$scope.model = model;
}
function setRequired (newVal) {
var out = {};
angular.forEach(newVal, function (val, key) {
if(val && !out[key]) {
angular.forEach(typeReqs, function (set) {
if(set.indexOf(key)>=0) {
angular.forEach(set, function (want) {
out[want] = true;
});
}
});
}
});
$scope.required = out;
}
}
};
});
| JavaScript | 0 | @@ -87,17 +87,16 @@
Fields',
-
%0Afunctio
@@ -1467,16 +1467,167 @@
model;%0A%0A
+ angular.forEach($scope.provider.provisioner, function (v, k) %7B%0A if(v!=='') %7B%0A $scope.model%5Bk%5D = v;%0A %7D%0A %7D);%0A
%7D%0A
|
acd4f0a9952be65ece37dee1b42aa294308a83a4 | Fix problem with timeline event | extension/src/handlers/sync.js | extension/src/handlers/sync.js | import config from '../config';
const INTERVAL = config.FLUSH_INTERVAL;
var state = {
user: null,
timeline: null,
position: 1,
events: []
};
function handleUser (type, e) {
state.user = e;
}
function handlePost (type, e) {
var post = Object.assign({
impressionOrder: state.position++,
visibility: type,
visibilityInfo: e.visibilityInfo,
type: 'impression',
timelineId: state.timeline.id
}, e.data);
if (post.visibility === 'public') {
post.html = e.element.html();
}
state.events.push(post);
}
function handleTimeline (type, e) {
state.position = 1;
state.timeline = {
type: 'timeline',
id: e.uuid,
location: window.location.href
};
state.events.push(state.timeline);
}
function sync (hub) {
if (state.events.length) {
// Send timelines to the page handling the communication with the API.
// This might be refactored using something compatible to the HUB architecture.
chrome.runtime.sendMessage({ type: 'sync', payload: state.events, userId: state.user.id },
(response) => hub.event('syncResponse', response));
state.events = [];
}
}
export function register (hub) {
hub.register('user', handleUser);
hub.register('newPost', handlePost);
hub.register('newTimeline', handleTimeline);
hub.register('windowUnload', sync.bind(null, hub));
window.setInterval(sync.bind(null, hub), INTERVAL);
}
| JavaScript | 0.006671 | @@ -710,16 +710,48 @@
e.uuid,%0A
+ startTime: e.startTime,%0A
|
763a28997d832800600925bfa70b059238d90236 | update to 0.0.3 | benchmark/benchmark.js | benchmark/benchmark.js | var cdeps = require('../index');
var detective = require('detective');
var Benchmark = require('benchmark');
var tests = {
'normal': 'require("a");require(\'b"\');require("c\\"");function require(require){return require;}',
'reg & comment': '(1)/*\n*/ / require("a");function require(require){return require;}',
'after return': "return require('highlight.js').highlightAuto(code).value;function require(require){return require;}",
'in quote': '"require(\'a\')";function require(require){return require;}',
'in comment': 'require("a");function require(require){return require;}//require("a");',
'in multi comment': '/*\nrequire("a")*/require("a");function require(require){return require;}',
'in reg': '/require("a")/;function require(require){return require;}',
'in ifstmt with no {}': 'if(true)/require("a")/;function require(require){return require;}',
'in dostmt with no {}': 'do /require("a")/.test(s); while(false);function require(require){return require;}',
'reg / reg': '/require("a")/ / /require("b")/; function require(require){return require;}',
'ignore variable': 'require("a" + b);function require(require){return require;}'
};
var results = {
'normal': 3,
'reg & comment': 1,
'after return': 1,
'in quote': 0,
'in comment': 0,
'in multi comment': 0,
'in reg': 0,
'in ifstmt with no {}': 0,
'in dostmt with no {}': 0,
'reg / reg': 0,
'ignore variable': 0
};
Object.keys(tests).forEach(function (key){
var suite = new Benchmark.Suite;
var s = tests[key];
// add tests
suite.add('cmd-deps: ' + key, function (){
return cdeps(s).length === results[key];
}).add('detective: ' + key, function (){
return detective(s).length === results[key];
})
// add listeners
.on('cycle', function (event){
console.log(String(event.target));
})
.on('complete', function (){
console.log(' Fastest is ' + this.filter('fastest').pluck('name').toString().replace(/:.*/, ''));
})
.run();
}); | JavaScript | 0.000002 | @@ -894,17 +894,17 @@
%7B%7D': 'do
-
+%7B
/require
@@ -918,16 +918,17 @@
test(s);
+%7D
while(f
|
bf652822ebfe028077b3f8f77523c7cda2771d2a | Refactor stylesheets gulp task | gulp/tasks/stylesheets.js | gulp/tasks/stylesheets.js | import gulp from 'gulp';
import plumber from 'gulp-plumber';
import postcss from 'gulp-postcss';
import notify from 'gulp-notify';
import config from '../config';
import autoprefixer from 'autoprefixer-core';
import pxtorem from 'postcss-pxtorem';
gulp.task('stylesheets', () => {
const processors = [
require('postcss-import'),
require('postcss-mixins'),
require('postcss-nested'),
require('postcss-simple-vars'),
require('postcss-color-function'),
autoprefixer({ browsers: ['last 2 versions'] }),
pxtorem({
root_value: 13,
replace: false
})
];
gulp.src(`${config.appDir}/stylesheets/application.css`)
.pipe(plumber())
.pipe(postcss(processors))
.on('error', notify.onError())
.pipe(gulp.dest(config.publicDir));
});
| JavaScript | 0.000001 | @@ -168,44 +168,242 @@
ort
-autoprefixer from 'autoprefixer-core
+postcssImport from 'postcss-import';%0Aimport postcssMixins from 'postcss-mixins';%0Aimport postcssNested from 'postcss-nested';%0Aimport postcssSimpleVars from 'postcss-simple-vars';%0Aimport postcssColorFunction from 'postcss-color-function
';%0Ai
@@ -409,16 +409,23 @@
import p
+ostcssP
xtorem f
@@ -446,16 +446,62 @@
xtorem';
+%0Aimport autoprefixer from 'autoprefixer-core';
%0A%0Agulp.t
@@ -558,230 +558,122 @@
-require('
postcss
--i
+I
mport
-')
,%0A
-require('
postcss
--m
+M
ixins
-')
,%0A
-require('
postcss
--n
+N
ested
-')
,%0A
-require('
postcss
--s
+S
imple
--v
+V
ars
-')
,%0A
-require('
postcss
--c
+C
olor
--f
+F
unction
-')
,%0A
-autoprefixer(%7B browsers: %5B'last 2 versions'%5D %7D),%0A p
+postcssP
xtor
@@ -726,16 +726,69 @@
e%0A %7D)
+,%0A autoprefixer(%7B browsers: %5B'last 2 versions'%5D %7D)
%0A %5D;%0A%0A
|
3ab9c8973409c1a753c1eaf6f3bd2a4b1472a894 | Remove tests for such functionality | test/policies/proxy/proxy.test.js | test/policies/proxy/proxy.test.js | const path = require('path');
const fs = require('fs');
const request = require('supertest');
const should = require('should');
const config = require('../../../lib/config');
const gateway = require('../../../lib/gateway');
const { findOpenPortNumbers } = require('../../common/server-helper');
const originalGatewayConfig = config.gatewayConfig;
const serverKeyFile = path.join(__dirname, '../../fixtures/certs/server', 'server.key');
const serverCertFile = path.join(__dirname, '../../fixtures/certs/server', 'server.crt');
const invalidClientCertFile = path.join(__dirname, '../../fixtures', 'agent1-cert.pem');
const clientKeyFile = path.join(__dirname, '../../fixtures/certs/client', 'client.key');
const clientCertFile = path.join(__dirname, '../../fixtures/certs/client', 'client.crt');
const chainFile = path.join(__dirname, '../../fixtures/certs/chain', 'chain.pem');
let backendServerPort;
function expectedResponse (app, status, contentType) {
return request(app).get('/endpoint').expect(status).expect('Content-Type', contentType);
}
describe('@proxy policy', () => {
const defaultProxyOptions = {
target: {
keyFile: clientKeyFile,
certFile: clientCertFile,
caFile: chainFile
}
};
let app, backendServer;
before('start HTTP server', (done) => {
findOpenPortNumbers(1).then((ports) => {
const https = require('https');
const express = require('express');
const expressApp = express();
backendServerPort = ports[0];
expressApp.all('*', function (req, res) {
res.status(200).json();
});
backendServer = https.createServer({
key: fs.readFileSync(serverKeyFile),
cert: fs.readFileSync(serverCertFile),
ca: fs.readFileSync(chainFile),
requestCert: true,
rejectUnauthorized: true
}, expressApp);
backendServer.listen(backendServerPort, done);
});
});
after('clean up', (done) => {
config.gatewayConfig = originalGatewayConfig;
backendServer.close(done);
});
describe('proxyOptions', () => {
it('raises an error when incorrect TLS file paths are provided', (done) => {
const serviceOptions = { target: { keyFile: '/non/existent/file.key' } };
setupGateway(serviceOptions).catch(err => {
should(err.message).match(/no such file or directory/);
done();
});
});
describe('when incorrect proxy options are provided', () => {
before(() => {
const serviceOptions = { target: { certFile: invalidClientCertFile } };
return setupGateway(serviceOptions).then(apps => {
app = apps.app;
});
});
after((done) => app.close(done));
it('responds with a bad gateway error', () => {
return expectedResponse(app, 502, /text\/html/);
});
});
describe('when proxy options are specified on the serviceEndpoint', () => {
before(() => {
return setupGateway(defaultProxyOptions).then(apps => {
app = apps.app;
});
});
after((done) => {
app.close(done);
});
it('passes options to proxy', () => {
return expectedResponse(app, 200, /json/);
});
});
describe('When proxy options are specified on the policy action', () => {
describe('and no proxy options are specified on the serviceEndpoint', () => {
before(() => {
return setupGateway({}, defaultProxyOptions).then(apps => {
app = apps.app;
});
});
after((done) => {
app.close(done);
});
it('passes options to proxy', () => {
return expectedResponse(app, 200, /json/);
});
});
describe('and proxy options are also specified on the serviceEndpoint', () => {
before(() => {
const serviceOptions = { target: { certFile: invalidClientCertFile } };
return setupGateway(serviceOptions, defaultProxyOptions).then(apps => {
app = apps.app;
});
});
after((done) => {
app.close(done);
});
it('uses both configurations, with policy proxy options taking precedence', () => {
return expectedResponse(app, 200, /json/);
});
});
});
});
});
const setupGateway = (serviceOptions = {}, policyOptions = {}) =>
findOpenPortNumbers(1).then(([port]) => {
config.gatewayConfig = {
http: { port },
apiEndpoints: {
test: {}
},
serviceEndpoints: {
backend: {
url: `https://localhost:${backendServerPort}`,
proxyOptions: serviceOptions
}
},
policies: ['proxy'],
pipelines: {
pipeline1: {
apiEndpoints: ['test'],
policies: [{
proxy: [{
action: { proxyOptions: policyOptions, serviceEndpoint: 'backend' }
}]
}]
}
}
};
return gateway();
});
| JavaScript | 0.000001 | @@ -2130,28 +2130,24 @@
provided', (
-done
) =%3E %7B%0A
@@ -2228,16 +2228,30 @@
%0A%0A
+return should(
setupGat
@@ -2274,111 +2274,94 @@
ons)
-.catch(err =%3E %7B%0A should(err.message).match(/no such file or directory/);%0A done();%0A %7D
+).be.rejectedWith('ENOENT: no such file or directory, open %5C'/non/existent/file.key%5C''
);%0A
@@ -2463,39 +2463,36 @@
-const serviceOptions =
+return setupGateway(
%7B target
@@ -2534,53 +2534,8 @@
%7D %7D
-;%0A%0A return setupGateway(serviceOptions
).th
@@ -2777,25 +2777,25 @@
describe('
-w
+W
hen proxy op
@@ -2817,39 +2817,37 @@
fied on the
-serviceEndpoint
+policy action
', () =%3E %7B%0A
@@ -3156,1148 +3156,53 @@
%7D);%0A
-%0A
- describe('When proxy options are specified on the policy action', () =%3E %7B%0A describe('and no proxy options are specified on the serviceEndpoint', () =%3E %7B%0A before(() =%3E %7B%0A return setupGateway(%7B%7D, defaultProxyOptions).then(apps =%3E %7B%0A app = apps.app;%0A %7D);%0A %7D);%0A%0A after((done) =%3E %7B%0A app.close(done);%0A %7D);%0A%0A it('passes options to proxy', () =%3E %7B%0A return expectedResponse(app, 200, /json/);%0A %7D);%0A %7D);%0A%0A describe('and proxy options are also specified on the serviceEndpoint', () =%3E %7B%0A before(() =%3E %7B%0A const serviceOptions = %7B target: %7B certFile: invalidClientCertFile %7D %7D;%0A return setupGateway(serviceOptions, defaultProxyOptions).then(apps =%3E %7B%0A app = apps.app;%0A %7D);%0A %7D);%0A%0A after((done) =%3E %7B%0A app.close(done);%0A %7D);%0A%0A it('uses both configurations, with policy proxy options taking precedence', () =%3E %7B%0A return expectedResponse(app, 200, /json/);%0A %7D);%0A %7D);%0A %7D);%0A %7D);%0A%7D);%0A%0Aconst setupGateway = (serviceOptions = %7B%7D, policyOptions = %7B%7D
+%7D);%0A%7D);%0A%0Aconst setupGateway = (proxyOptions
) =%3E
@@ -3449,48 +3449,8 @@
rt%7D%60
-,%0A proxyOptions: serviceOptions
%0A
@@ -3651,23 +3651,8 @@
ions
-: policyOptions
, se
|
659d60b2351446af3d4b037785fae7c742ddc518 | Make it possible to show the changelog directly via /about?tab=changelog | public/viewjs/about.js | public/viewjs/about.js | $('[data-toggle="collapse-next"]').on("click", function(e)
{
e.preventDefault();
$(this).parent().next().collapse("toggle");
});
| JavaScript | 0.000285 | @@ -125,8 +125,150 @@
%22);%0A%7D);%0A
+%0Aif ((typeof GetUriParam(%22tab%22) !== %22undefined%22 && GetUriParam(%22tab%22) === %22changelog%22))%0A%7B%0A%09$(%22.nav-tabs a%5Bhref='#changelog'%5D%22).tab(%22show%22);%0A%7D%0A
|
361ff8930f870c67d5e8ed40a49f8c21ff3314df | Add lint task to run all other lint tasks | gulpfile.js/tasks/lint.js | gulpfile.js/tasks/lint.js | 'use strict'
var gulp = require('gulp')
var standard = require('gulp-standard')
var config = require('../config')
gulp.task('lint:gulpTasks', function () {
return gulp.src(config.scripts.gulpTasks)
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}))
})
gulp.task('lint:scripts', function () {
var scripts = config.scripts.src.concat([
config.scripts.entryPoint,
'!**/*.polyfill.js'
])
return gulp.src(scripts)
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}))
})
gulp.task('lint:tests', function () {
return gulp.src(config.test.src)
.pipe(standard())
.pipe(standard.reporter('default', {
breakOnError: true
}))
})
| JavaScript | 0.000049 | @@ -109,16 +109,93 @@
nfig')%0A%0A
+gulp.task('lint', %5B%0A 'lint:gulpTasks',%0A 'lint:scripts',%0A 'lint:tests'%0A%5D)%0A%0A
gulp.tas
|
45ddce08f8a2002d2e3b4b0c784a5519f5cab7f9 | add trim to appendContext action | modules/builtin/src/actions/appendContext.js | modules/builtin/src/actions/appendContext.js | const _ = require('lodash')
/**
* Appends the provided context(s) to the list of contexts that will be used by the NLU Engine
* for the next messages for that chat session.
*
* The TTL (Time-To-Live) represents how long the contexts will be valid before they are automatically removed.
* For example, the default value of `1` will listen for that context only once (the next time the user speaks).
*
* If a context was already present in the list, the higher TTL will win.
* To force override a specific context, use the `removeContext` action before this action.
*
* This method is contextual to the current user and chat session.
*
* You can specify more than one context by separating them with a comma.
*
* @title Append Context
* @category NLU
* @author Botpress, Inc.
* @param {string} contexts - Comma-separated list of contextss
* @param {string} [ttl=1] - Time-To-Live of the context in number of dialog turns. Put `0` to disable expiry.
*/
const appendContext = (contexts, ttl) => {
const existing = event.state.session.nluContexts || []
const add = contexts.split(',')
const merged = [
...existing,
...add.map(x => ({
context: x,
ttl: isNaN(Number(ttl)) ? 1000 : Number(ttl)
}))
]
const final = []
const visited = {}
for (const ctx of merged) {
if (visited[ctx.context]) {
continue
}
final.push(
_.chain(merged)
.filter(x => x.context === ctx.context)
.orderBy('ttl', 'desc')
.first()
.value()
)
visited[ctx.context] = true
}
event.state.session.nluContexts = final
}
return appendContext(args.contexts, args.ttl)
| JavaScript | 0 | @@ -1086,16 +1086,23 @@
ontexts.
+trim().
split(',
|
eebf9cf5b52053837ae516afd4c951000d4e3a63 | Add docs | cd/src/pipeline-events-handler/deltas/deltas.js | cd/src/pipeline-events-handler/deltas/deltas.js | const getStackFamily = require('./stack-family');
const getChangeSetFamily = require('./change-set-family');
const deltaArrow = require('./delta-arrow');
const deltaValue = require('./delta-value');
/**
* Returns a multi-line string describing the parameters that have changed
* @param {ParameterDeltas} deltas
* @returns {String}
*/
function parameterDeltasList(deltas) {
if (!deltas.length) {
return 'This change set contained no meaningful parameter deltas.';
}
// Text blocks within attachments have a 3000 character limit. If the text is
// too large, try creating the list without links to reduce the size.
const withLinks = deltas
.map((d) => {
const oldValue = deltaValue(d.parameter, d.stackValue);
const arrow = deltaArrow(d);
const newValue = deltaValue(d.parameter, d.changeSetValue);
const label = d.stackName.includes('-root-')
? d.parameter
: `${d.stackName}::${d.parameter}`;
return `*${label}*: ${oldValue} ${arrow} ${newValue}`;
})
.join('\n');
if (withLinks.length < 2900) {
return withLinks;
} else {
return deltas
.map((d) => {
const oldValue = deltaValue(d.parameter, d.stackValue, true);
const arrow = deltaArrow(d, true);
const newValue = deltaValue(d.parameter, d.changeSetValue, true);
return `*${d.stackName}::${d.parameter}*: ${oldValue} ${arrow} ${newValue}`;
})
.join('\n');
}
}
module.exports = {
async nestedParameterDeltaText(stackName, changeSetName) {
let stackFamily = await getStackFamily(stackName);
const changeSetFamily = await getChangeSetFamily(stackName, changeSetName);
const changeSetFamilyStackIds = changeSetFamily.map((c) => c.StackId);
// When there's only a single change set, it likely means that nested
// change sets was disabled for the given change set. In these cases, only
// the root stack's parameters should be included in the deltas, because
// there won't be anything to compare the child stacks to, and all
// parameters will look like they've changed.
if (changeSetFamily.length === 1) {
stackFamily = [stackFamily[0]];
}
/** @type {ParameterDeltas} */
const deltas = [];
// Iterate through all existing stack parameters and create a delta for
// each one, which includes the current value.
for (const stack of stackFamily) {
// Not all nested stacks are guaranteed to be have a change set. If a
// stack in the stack family does not have a corresponding change set,
// and the deltas are determined strictly by finding matching values in
// the stack and change set families, all parameters for that stack would
// appear to be unmatched. So, if there is no corresponding change set
// for a given stack, that stack's parameters should not be included in
// the deltas. (If there is a change set with no corresponding stack,
// those deltas *will* still be included below.)
if (changeSetFamilyStackIds.includes(stack.StackId)) {
for (const param of stack.Parameters || []) {
deltas.push({
stackName: stack.StackName,
stackId: stack.StackId,
parameter: param.ParameterKey,
stackValue: param.ResolvedValue || param.ParameterValue,
changeSetValue: null,
});
}
}
}
// Iterate through all the change set parameters. If a delta already exists
// for a given stack+parameter key, add the value from the change set to
// that delta. If not, make a new delta.
for (const changeSet of changeSetFamily) {
for (const param of changeSet.Parameters || []) {
const delta = deltas.find(
(d) =>
param.ParameterKey === d.parameter &&
changeSet.StackName === d.stackName,
);
if (delta) {
delta.changeSetValue = param.ResolvedValue || param.ParameterValue;
} else {
deltas.push({
stackName: changeSet.StackName,
stackId: changeSet.StackId,
parameter: param.ParameterKey,
stackValue: null,
changeSetValue: param.ResolvedValue || param.ParameterValue,
});
}
}
}
// Filter down to only deltas where the values are different
const changeDeltas = deltas.filter(
(d) => d.stackValue !== d.changeSetValue,
);
// When using nested change sets, not all parameters in nested stacks are
// correctly resolved. Any parameter values that depend on a stack or
// resource output will be included in the change set parameters with an
// unresolved value that looks like "{{IntrinsicFunction:…". Unless or until
// AWS makes nested change sets smarter, we have to just ignore these,
// because there's no way to compare the actual existing value from the stack
// to the hypothetical future value that will be resolved when the change set
// executes.
//
// Any parameters effected by this limitation are filtered out.
const cleanedDeltas = changeDeltas.filter(
(d) => !(d.changeSetValue || '').match(/\{\{IntrinsicFunction\:/),
);
const allowedDeltas = cleanedDeltas.filter(
(d) =>
!['PipelineExecutionNonce', 'TemplateUrlBase'].includes(d.parameter),
);
return parameterDeltasList(allowedDeltas);
},
};
| JavaScript | 0.000001 | @@ -5201,24 +5201,130 @@
/),%0A );%0A%0A
+ // Some additional parameters that don't make sense to display in Slack are%0A // also filtered out.%0A
const al
|
aea72df1496f7d1b306fc3168cce01cb0a7f3be3 | Reimplement throwing to the CI script | tools/scripts/ci/ensure-guide-page-naming.js | tools/scripts/ci/ensure-guide-page-naming.js | const path = require('path');
const fs = require('fs');
const readdirp = require('readdirp-walk');
const guideRoot = path.resolve(__dirname, '../../../guide');
const allowedLangDirNames = [
'arabic',
'chinese',
'english',
'portuguese',
'russian',
'spanish'
];
function checkDirName(dirName, fullPath) {
if (dirName.replace(/(\s|\_)/, '') !== dirName) {
const newDirName = dirName.replace(/\s/g, '-');
fs.renameSync(fullPath, fullPath.replace(dirName, newDirName));
// throw new Error(
// `Invalid character found in a folder named '${dirName}', please use '-' for spaces
// ${fullPath}
// `
// );
return;
}
if (dirName.toLowerCase() !== dirName) {
const newPath = fullPath.replace(dirName, dirName.toLowerCase());
console.log(`renaming ${dirName} to ${dirName.toLowerCase()}`);
fs.renameSync(fullPath, newPath);
}
}
function checkFileName(fileName, fullPath) {
if (fileName !== 'index.md') {
throw new Error(
`${fileName} is not a valid file name, please use 'index.md'
${fullPath}
`
);
}
}
function checkFile(file) {
const { stat, depth, name, fullPath } = file;
if (depth === 1) {
if (stat.isFile()) {
throw new Error(`${name} is not valid in the ${guideRoot} directory`);
}
if (!allowedLangDirNames.includes(name)) {
throw new Error(`${name} should not be in the ${guideRoot} directory`);
}
}
if (stat.isDirectory()) {
return checkDirName(name, fullPath);
}
return checkFileName(name, fullPath);
}
readdirp({ root: guideRoot })
.on('data', checkFile)
.on('end', () => {
/* eslint-disable no-process-exit */
process.exit(0);
});
| JavaScript | 0 | @@ -370,131 +370,8 @@
%0A
- const newDirName = dirName.replace(/%5Cs/g, '-');%0A fs.renameSync(fullPath, fullPath.replace(dirName, newDirName));%0A //
thr
@@ -383,27 +383,18 @@
w Error(
-%0A //
%60
+%0A
Invalid
@@ -416,23 +416,8 @@
in
-a folder named
'$%7Bd
@@ -452,22 +452,30 @@
spaces%0A
+%0A
- //
+Found in:%0A
$%7Bful
@@ -485,39 +485,10 @@
th%7D%0A
- // %60%0A // );%0A return
+%60)
;%0A
@@ -540,99 +540,56 @@
-const newPath = fullPath.replace(dirName, dirName.toLowerCase());%0A console.log(%60renam
+throw new Error(%60%0AUpper case characters found
in
-g
$%7Bd
@@ -599,75 +599,77 @@
ame%7D
- to $%7BdirName.toL
+, all folder names must be l
ower
-Case()%7D%60);%0A fs.renameSync(fullPath, newPath
+ case%0A%0A Found in :%0A $%7BfullPath%7D%0A%60
);%0A
@@ -840,18 +840,29 @@
dex.md'%0A
+%0A
+Found in:%0A
$%7Bfu
@@ -869,22 +869,16 @@
llPath%7D%0A
-
%60%0A );
|
999807608956dabdd958d723f069f4b9d34f21a9 | add mean and median to benchmark | benchmark/sub.js | benchmark/sub.js |
var ss = require('..')
, sock = ss.socket('sub');
sock.connect(3000);
var n = 0;
var ops = 200;
var t = process.hrtime();
sock.on('message', function(msg){
if (n++ % ops == 0) {
t = process.hrtime(t);
var ms = t[1] / 1000 / 1000;
process.stdout.write('\r [' + (ops * (1000 / ms) | 0) + ' ops/s] [' + n + ']');
t = process.hrtime();
}
}); | JavaScript | 0.000176 | @@ -120,16 +120,34 @@
rtime();
+%0Avar results = %5B%5D;
%0A%0Asock.o
@@ -258,16 +258,84 @@
/ 1000;%0A
+ var persec = (ops * (1000 / ms) %7C 0);%0A results.push(persec);%0A
proc
@@ -361,39 +361,22 @@
r %5B' +
-(ops * (1000 / ms) %7C 0)
+persec
+ ' ops
@@ -427,8 +427,425 @@
%0A %7D%0A%7D);
+%0A%0Afunction sum(arr) %7B%0A return arr.reduce(function(sum, n)%7B%0A return sum + n;%0A %7D);%0A%7D%0A%0Afunction mean(arr) %7B%0A return sum(arr) / arr.length %7C 0;%0A%7D%0A%0Afunction median(arr) %7B%0A arr = arr.sort();%0A return arr%5Barr.length / 2 %7C 0%5D;%0A%7D%0A%0Aprocess.on('SIGINT', function()%7B%0A console.log('%5Cn');%0A console.log(' mean: %25d', mean(results));%0A console.log(' median: %25d', median(results));%0A console.log();%0A process.exit();%0A%7D);
|
994034d5abb44b1f008951397d34d43d65884461 | Make Google sponsored ads clickable | app/adBlock.js | app/adBlock.js | /* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this file,
* You can obtain one at http://mozilla.org/MPL/2.0/. */
'use strict'
const URL = require('url')
const ABPFilterParserLib = require('abp-filter-parser-cpp')
const ABPFilterParser = ABPFilterParserLib.ABPFilterParser
const FilterOptions = ABPFilterParserLib.FilterOptions
const DataFile = require('./dataFile')
const Filtering = require('./filtering')
module.exports.resourceName = 'adblock'
let adblock
let mapFilterType = {
mainFrame: FilterOptions.document,
subFrame: FilterOptions.subdocument,
stylesheet: FilterOptions.stylesheet,
script: FilterOptions.script,
image: FilterOptions.image,
object: FilterOptions.object,
xhr: FilterOptions.xmlHttpRequest,
other: FilterOptions.other
}
const startAdBlocking = () => {
Filtering.registerFilteringCB(details => {
const firstPartyUrl = URL.parse(details.firstPartyUrl)
const shouldBlock = firstPartyUrl.protocol &&
firstPartyUrl.protocol.startsWith('http') &&
mapFilterType[details.resourceType] !== undefined &&
adblock.matches(details.url, mapFilterType[details.resourceType], firstPartyUrl.host)
DataFile.debug(details, shouldBlock)
return {
shouldBlock,
resourceName: module.exports.resourceName
}
})
}
module.exports.init = () => {
adblock = new ABPFilterParser()
DataFile.init(module.exports.resourceName, startAdBlocking,
data => adblock.deserialize(data))
}
| JavaScript | 0.99992 | @@ -1030,24 +1030,70 @@
protocol &&%0A
+ details.resourceType !== 'mainFrame' &&%0A
firstP
|
98b93af35284ceb2d345534e05f13cbce1c8f4c2 | test all the locals | test/tests/components/Dropdown.js | test/tests/components/Dropdown.js | import expect from 'expect';
import Dropdown, { Props } from '../../../src/dropdown';
import { newComponent } from '../helpers';
describe('Dropdown', function () {
describe('locals', () => {
const exampleProps = {
id: '12345',
className: 'fancy-class-name',
style: { margin: 10, position: 'relative' }
};
const componentDropdown = new Dropdown(exampleProps);
it('should pass props', () => {
const locals = componentDropdown.getLocals();
expect(locals.id).toBe(exampleProps.id);
expect(locals.style).toEqual(exampleProps.style);
});
it('should compute className', () => {
const { className } = componentDropdown.getLocals();
expect(className).toInclude('dropdown');
expect(className).toInclude('fancy-class-name');
});
});
});
| JavaScript | 0.00004 | @@ -320,17 +320,245 @@
ative' %7D
+,%0A value: %7B value: 'test', label: 'Test' %7D,%0A onChange: () =%3E %7B%7D,%0A options: %5B%0A %7B value: 'test', label: 'Test' %7D,%0A %7B value: 'test1', label: 'Test1' %7D,%0A %7B value: 'test2', label: 'Test2' %7D%0A %5D
%0A
-
%7D;%0A
@@ -807,16 +807,138 @@
style);%0A
+ expect(locals.options).toEqual(exampleProps.options);%0A expect(locals.onChange).toEqual(exampleProps.onChange);%0A
%7D);%0A
@@ -1083,24 +1083,24 @@
dropdown');%0A
-
expect
@@ -1151,16 +1151,1049 @@
%7D);%0A%0A
+ it('should compute value', () =%3E %7B%0A const %7B value %7D = componentDropdown.getLocals();%0A expect(value).toBeA(Object);%0A expect(value).toEqual(exampleProps.value);%0A %7D);%0A%0A it('should compute value as string', () =%3E %7B%0A const dropdown = newComponent(Dropdown, %7B%0A value: 'test',%0A options: %5B%0A %7B value: 'test', label: 'Test' %7D,%0A %7B value: 'test1', label: 'Test1' %7D,%0A %7B value: 'test2', label: 'Test2' %7D%0A %5D%0A %7D);%0A const %7B value, options %7D = dropdown.getLocals();%0A expect(value).toBeA(Object);%0A expect(value).toEqual(options%5B0%5D);%0A %7D);%0A%0A it('should compute value as number', () =%3E %7B%0A const dropdown = newComponent(Dropdown, %7B%0A value: 2,%0A options: %5B%0A %7B value: 0, label: 'Test' %7D,%0A %7B value: 1, label: 'Test1' %7D,%0A %7B value: 2, label: 'Test2' %7D%0A %5D%0A %7D);%0A const %7B value, options %7D = dropdown.getLocals();%0A expect(value).toBeA(Object);%0A expect(value).toEqual(options%5B2%5D);%0A %7D);%0A%0A
%7D);%0A%0A%7D
|
00b741dbc7c987614467406bf20201678b1b3807 | fix bug in browse/query request code that caused success callback to be undefined | js/openbibl.query.js | js/openbibl.query.js | (function() {
"use strict";
window.obp.query.subscribers = [];
window.obp.query.init = function(file, subscribers){
var obp_query = this;
this.subscribers = subscribers;
if (window.obp.config.query.data === null) {
this.request_query_data(file);
} else {
this.notify_subscribers();
}
};
window.obp.query.request_query_data = function(file) {
$.ajax({
"url": file,
"async": true,
"type": "GET",
"dataType": "json",
"success": window.obp.query.handle_query_success,
"error" : function(jqXHR, textStatus, errorThrown) {
console.log('File "' + + '" not available. Requesting index data be generated.');
window.obp.query.request_saxon_query
}
});
};
window.obp.query.handle_query_success = function(data) {
window.obp.config.query.data = data;
window.obp.query.notify_subscribers();
};
window.obp.query.notify_subscribers = function() {
var subscribers = window.obp.query.subscribers || [];
for (var i = 0; i < subscribers.length; i++)
subscribers[i].handle_query_data();
};
window.obp.query.request_saxon_query = function() {
window.obp.SaxonCE.requestQueryTransform(
window.obp.config.paths['query_xsl'],
window.obp.bibliographies.xml,
[],
function(data) {
var json;
try {
json = JSON.parse(data.getResultDocument().textContent);
} catch (e) {
console.log('Failure to generate query data: ' + e.toString());
}
this.handle_query_success(json);
}
);
};
})();
| JavaScript | 0 | @@ -722,16 +722,20 @@
le %22' +
+file
+ '%22 n
@@ -839,16 +839,19 @@
on_query
+();
%0A
@@ -1329,170 +1329,22 @@
-window.obp.SaxonCE.requestQueryTransform(%0A window.obp.config.paths%5B'query_xsl'%5D,%0A window.obp.bibliographies.xml,%0A %5B%5D,%0A
+var callback =
fun
@@ -1353,28 +1353,24 @@
ion(data) %7B%0A
-
@@ -1391,20 +1391,16 @@
-
try %7B%0A
@@ -1413,20 +1413,16 @@
-
-
json = J
@@ -1470,20 +1470,16 @@
ntent);%0A
-
@@ -1504,36 +1504,32 @@
-
console.log('Fai
@@ -1580,36 +1580,32 @@
));%0A
-
-
%7D%0A
@@ -1602,24 +1602,32 @@
- this
+window.obp.query
.handle_
@@ -1647,37 +1647,214 @@
(json);%0A
+%7D;%0A
-%7D
+ window.obp.SaxonCE.requestQueryTransform(%0A window.obp.config.paths%5B'query_xsl'%5D,%0A window.obp.bibliographies.xml,%0A %5B%5D,%0A callback
%0A );%0A
|
cc806ae0da5dcb53a8a95e88d044c77e17ecc949 | Save tags (#248) | res/sources/source.js | res/sources/source.js | gpf.require.define({}, function () {
"use strict";
//region Source and SourceArray definitions
return gpf.define({
$class: "Source",
constructor: function (array, source, dependencies) {
this._array = array;
this._name = source.name;
this._index = array.getLength();
if (source.load !== false) {
this._load = true;
}
if (source.test !== false) {
this._test = true;
}
if (source.tags) {
this._tags = source.tags.split(" ");
}
if (dependencies) {
this._processDependencies(dependencies);
}
},
/**
* Source array
*
* @type {SourceArray}
*/
_array: null,
/** Source name */
_name: "",
/** @gpf:read _name */
getName: function () {
return this._name;
},
/** Source index */
_index: -1,
/** @gpf:read _index */
getIndex: function () {
return this._index;
},
/** @gpf:write _index */
setIndex: function (value) {
this._index = value;
},
/** Source is loaded */
_load: false,
/** @gpf:read _load */
getLoad: function () {
return this._load;
},
/** Source has a test counterpart */
_test: false,
/** @gpf:read _test */
getTest: function () {
return this._test;
},
/** Tags */
_tags: [],
/** @gpf:read _tags */
getTags: function () {
return this._tags;
},
/**
* List of dependencies (boot is excluded)
*
* @type {String[]}
*/
_dependsOn: [],
/** @gpf:read _dependsOn */
getDependencies: function () {
return this._dependsOn;
},
/**
* List of module dependencies
*
* @type {String[]}
*/
_dependencyOf: [],
/** @gpf:read _dependencyOf */
getDependencyOf: function () {
return this._dependencyOf;
},
/**
* Extract from the dependencies dictionary
*
* @param {Object} dependencies dictionary
*/
_processDependencies: function (dependencies) {
this._dependsOn = dependencies[this._name] || [];
this._dependencyOf = [];
Object.keys(dependencies).forEach(function (name) {
var nameDependencies = dependencies[name];
if (nameDependencies.indexOf(this._name) > -1) {
this._dependencyOf.push(name);
}
}, this);
},
/**
* Change the load setting
*
* @param {Boolean} value New value for the setting
* @return {Boolean} Update done
*/
_setLoad: function (value) {
if (!value) {
// Allow only if all dependencies are not loaded
if (this._dependencyOf.some(function (name) {
return this._array.byName(name).getLoad();
}, this)) {
return false;
}
}
this._load = value;
return true;
},
/**
* Change the load setting
*
* @param {Boolean} value New value for test
* @return {Boolean} Update done
*/
_setTest: function (value) {
this._test = value;
return true;
},
/** Checked state (exists, obsolete, new) */
_checkedState: "",
/**
* Create the exported version of the source
*
* @return {Object} Object to be converted to JSON and saved
*/
"export": function () {
var result = {
name: this._name
};
if (this._load) {
if (!this._test) {
result.test = false;
}
} else {
result.load = false;
}
return result;
},
isReadOnly: function () {
return this._name === "boot";
},
testProperty: function (propertyName) {
if (!this._load) {
return false;
}
if ("test" === propertyName) {
return this._test;
}
return true;
},
setProperty: function (propertyName, value) {
if ("load" === propertyName) {
return this._setLoad(value);
}
if ("test" === propertyName) {
return this._setTest(value);
}
},
hasDependencies: function () {
return this._dependsOn.length > 0;
},
isReferenced: function () {
return this._dependencyOf.length > 0;
},
setCheckedState: function (checkedState) {
this._checkedState = checkedState;
},
getCheckedState: function () {
return this._checkedState;
}
});
});
| JavaScript | 0 | @@ -4229,32 +4229,135 @@
;%0A %7D%0A
+ if (this._tags.length) %7B%0A result.tags = this._tags.join(%22 %22);%0A %7D%0A
retu
|
8b2ee68642f4014bbfdf57b29641548798dcc000 | update code for $off | angular-off.js | angular-off.js |
(function () {
angular.injector(['ng']).injector.get('$rootScope')
.constructor.prototype.$off = function(eventName, fn) {
if(this.$$listeners) {
if (arguments.length > 1) {
var namedListeners = this.$$listeners[eventName];
if(namedListeners) {
for(var i = 0; i < namedListeners.length; i++) {
if(namedListeners[i] === fn) {
namedListeners.splice(i, 1);
}
}
}
} else {
this.$$listeners[eventName] === null;
}
}
}
}());
| JavaScript | 0 | @@ -1,9 +1,8 @@
-%0A
(functio
@@ -306,184 +306,61 @@
-for(var i = 0; i %3C namedListeners.length; i++) %7B%0A if(namedListeners%5Bi%5D === fn) %7B%0A namedListeners.splice(i, 1);%0A %7D%0A %7D
+namedListeners.splice(namedListeners.indexOf(fn), 1);
%0A
@@ -430,18 +430,16 @@
tName%5D =
-==
null;%0A
@@ -462,16 +462,50 @@
%7D
-%0A %7D
+ // end if $$listeners%0A %7D; //end $off
%0A%7D()
|
db3c4a9bb0448d9dfa2896afb0c7ca8e4980d119 | Prepare archive helpers on the relavant pages | helpers/archive_helper.js | helpers/archive_helper.js | var _ = require("underscore");
var helper_utils = require("punch").Utils.Helper;
var blog_content_handler = require("punch-blog-content-handler");
var all_posts = [];
var last_modified = null;
var fetch_all_posts = function(callback) {
//reset posts list
blog_content_handler.allPosts = {};
blog_content_handler.getAllPosts(function(err, posts_obj, posts_last_modified) {
if (!err) {
all_posts = _.values(posts_obj);
last_modified = posts_last_modified;
}
return callback();
});
}
var tag_helpers = {
years: function() {
return _.keys(blog_content_handler.postDates).reverse();
},
top_tags: function() {
var tag_counts = blog_content_handler.tagCounts;
return _.sortBy(_.keys(tag_counts), function(tag) {
return tag_counts[tag];
}).reverse();
}
};
module.exports = {
directAccess: function() {
return { "block_helpers": {}, "tag_helpers": {}, "options": {} };
},
get: function(basepath, file_extension, options, callback) {
var self = this;
fetch_all_posts(function() {
return callback(null, { "tag": tag_helpers }, {}, last_modified);
});
}
}
| JavaScript | 0 | @@ -188,16 +188,407 @@
null;%0A%0A
+// TODO: This code is duplicated from punch-blog-content-handler.%0A// Consider moving it to its own helper.%0Avar match_patterns = function(basepath, patterns) %7B%0A%09if (Array.isArray(patterns)) %7B%0A%09%09return _.any(patterns, function(pattern) %7B%0A%09%09%09return basepath.match(pattern) != null;%0A%09%09%7D);%0A%09%7D else %7B%0A%09%09// assume a single pattern given and match directly%0A%09%09return basepath.match(patterns);%0A%09%7D%0A%7D;%0A%0A
var fetc
@@ -1376,16 +1376,221 @@
this;%0A%0A
+%09%09var archive_url_regexs = _.map(blog_content_handler.archiveUrls, function(url) %7B%0A%09%09%09return new RegExp(%22%5E%22 + url.pattern + %22%5C%5C/index$%22, %22g%22);%0A%09%09%7D);%0A%0A%09%09if (match_patterns(basepath, archive_url_regexs)) %7B%0A%09
%09%09fetch_
@@ -1608,24 +1608,25 @@
unction() %7B%0A
+%09
%09%09%09return ca
@@ -1684,18 +1684,74 @@
ied);%0A%09%09
+%09
%7D);%0A
+%09%09%7D else %7B%0A%09%09%09return callback(null, %7B%7D, %7B%7D, null);%0A%09%09%7D%0A
%09%7D%0A%0A%7D%0A
|
1e2b39eddf90c8c1edf3b8a1aa96dce624741b83 | Fix linting error | commands/publish.js | commands/publish.js | 'use strict';
var
chalk = require('chalk'),
request = require('request');
module.exports = function(program) {
var publish;
publish = program.command('publish');
publish
.description('Publish a theme')
.option('-t, --tenant [tenant]', 'required - which tenant to use')
.option('-k, --apiKey [apiKey]', 'required - which API key to use (for corresponding tenant)')
.action(function(options) {
var
tenant = options.tenant,
apiKey = options.apiKey;
// Validates inputs
if (!options || !apiKey) {
console.log(chalk.yellow('\n Missing parameter. Both tenant and API key need to be specified to publish:'));
publish.outputHelp();
return;
}
var magicConstants = {
completedMsg : 'PUBLISH COMPLETED',
errorMsgPrefix : 'ERROR',
themeStatusSuccessCode: 200,
deploySuccessCode : 202,
pollingInterval : 500
};
console.log('Publishing theme for %s with key %s', chalk.blue(tenant), chalk.blue(apiKey));
// HTTP Basic Auth
var auth = apiKey + ':' + apiKey + '@';
// Gets the theme status log, outputting each logItem to `cb`
// TODO: Rewrite to promises instead of callbacks, use less callbacks
var getStatus = function(cb, doneCb) {
request({
uri: 'https://' + auth + 'app.referralsaasquatch.com/api/v1/' + tenant + '/theme/publish_status',
method: 'GET'
}, function(error, response, body) {
if (error) {
console.log('Unhandled error polling publish status', error);
return;
}
if (response.statusCode !== magicConstants.themeStatusSuccessCode) {
console.log('Unhandled HTTP response polling publish status', response);
return;
}
var data = JSON.parse(body);
for (var line = data.log.length; line > 0; --line) {
var logItem = data.log[line];
if (logItem) {
cb(logItem);
}
}
if (doneCb) {
doneCb();
}
});
};
// Recursively watched
var watchStatusLog = function(sinceTime) {
var thisLoopLatest = null;
var lastMsg = '';
getStatus(function(logItem) {
if (logItem.timestamp > sinceTime) {
lastMsg = logItem.message;
thisLoopLatest = logItem.timestamp;
if (logItem.message === magicConstants.completedMsg) {
console.log(chalk.green(logItem.message));
} else {
console.log(logItem.message);
}
}
}, function() {
if (lastMsg === magicConstants.completedMsg) {
return; // Quit with success
} else if (lastMsg.indexOf(magicConstants.errorMsgPrefix) === 0) {
return; // Quit with Error
} else {
var newSinceTime = thisLoopLatest ? thisLoopLatest : sinceTime;
// NOTE -- This is recursion
setTimeout(function(){ watchStatusLog(newSinceTime); }, magicConstants.pollingInterval);
}
});
};
var previousDeployTime = 0;
getStatus(function(logItem) {
if (logItem.timestamp > previousDeployTime) {
previousDeployTime = logItem.timestamp;
}
}, function() {
request({
uri: 'https://' + auth + 'app.referralsaasquatch.com/api/v1/' + tenant + '/theme/publish',
method: 'POST',
json: {}
}, function(error, response, body) {
if (error) {
console.log('Unhandled error publishing theme', error);
return;
}
if (response.statusCode !== magicConstants.deploySuccessCode){
console.log('Unhandled HTTP response to publishing theme', response);
return;
}
// Triggers log polling since `previousDeployTime`
watchStatusLog(previousDeployTime + 1);
});
});
});
return publish;
};
| JavaScript | 0.000015 | @@ -3601,38 +3601,32 @@
(error, response
-, body
) %7B%0A if
|
f8dfb91df9f16837889da959a0fad16c4b9ed981 | Tweak tests for iojs | packages/baby-tolk/test/tolk-basics.js | packages/baby-tolk/test/tolk-basics.js | 'use strict';
var Path = require('path');
var expect = require('unexpected').clone();
expect.installPlugin(require('unexpected-promise'));
expect.addAssertion('string', 'to begin with', function (expect, subject, cmp) {
expect(cmp, 'to be a string');
expect(subject.substr(0, cmp.length), 'to be', cmp);
});
var tolk = require('../lib/tolk');
function getPath(path) {
return Path.join(process.cwd(), 'fixtures/source', path);
}
describe('readCompiled', function () {
it('should read a file directly if there is no adapter', function () {
return expect(tolk.read(getPath('unchanged.txt')), 'to be resolved with', {
result: 'I am the same\n'
});
});
it('should throw when reading a file that does not exist', function () {
return expect(tolk.read(getPath('does-not-exist.txt')), 'when rejected', 'to satisfy', {
code: 'ENOENT',
path: /fixtures\/source\/does-not-exist\.txt$/,
message: /^ENOENT, open '.+?fixtures\/source\/does-not-exist\.txt'$/
});
});
it('should compile a file if there is an adapter', function () {
return expect(tolk.read(getPath('babel/simplest.jsx')), 'to be resolved with', {
result: expect.it('to begin with', '\'use strict\';\n\nvar foo = \'bar\';\n//# sourceMappingURL=data:application/json;base64,')
});
});
it('should throw when compiling a file that does not exist', function () {
return expect(tolk.read(getPath('does-not-exist.scss')), 'when rejected', 'to satisfy', {
code: 'ENOENT',
path: /fixtures\/source\/does-not-exist\.scss$/,
message: /^ENOENT, open '.+?fixtures\/source\/does-not-exist\.scss'$/
});
});
it('should throw when compiling a file with syntax errors', function () {
return expect(tolk.read(getPath('scss/syntaxerror.scss')), 'when rejected', 'to exhaustively satisfy', {
status: 1,
file: /fixtures\/source\/scss\/syntaxerror\.scss$/,
line: 2,
column: 3,
message: 'property "color" must be followed by a \':\'',
code: 1
});
});
it('should autoprefix uncompiled CSS output', function () {
return expect(tolk.read(getPath('basic.css')), 'to be resolved with', {
result: 'body {\n -webkit-transform: rotate(-1deg);\n transform: rotate(-1deg);\n}\n'
});
});
it('should autoprefix compiled CSS output', function () {
return expect(tolk.read(getPath('scss/autoprefix.scss')), 'to be resolved with', {
result: expect.it('to begin with', 'body {\n -webkit-transform: rotate(-1deg);\n transform: rotate(-1deg); }\n\n/*# sourceMappingURL=data:application/json;base64,')
});
});
});
| JavaScript | 0 | @@ -932,32 +932,35 @@
essage: /%5EENOENT
+.*?
, open '.+?fixtu
@@ -1582,16 +1582,19 @@
/%5EENOENT
+.*?
, open '
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.