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
|
---|---|---|---|---|---|---|---|
a2c1d2288033a53d70faad194075e88e044d6ec9
|
Enable onClick events for sideNav headerLink and superHeaderLink
|
packages/side-nav/src/presenters/SideNav.js
|
packages/side-nav/src/presenters/SideNav.js
|
import React, { Component } from "react";
import PropTypes from "prop-types";
import { css } from "emotion";
import { ThemeContext } from "@hig/theme-context";
import { Back24 } from "@hig/icons";
import Typography from "@hig/typography";
import TextLink from "@hig/text-link";
import IconButton from "@hig/icon-button";
import stylesheet from "./stylesheet";
export default class SideNav extends Component {
static propTypes = {
/** Additional content to include below navigation items */
children: PropTypes.node,
/** Copyright text to include */
copyright: PropTypes.node,
/** 0 or more SideNav Groups */
groups: PropTypes.node,
/** Subtitle at the top of the SideNav */
headerLabel: PropTypes.string,
/** An href for the SideNav Subtitle */
headerLink: PropTypes.string,
/** 0 or more SideNav Links */
links: PropTypes.node,
/** Called when minimize button is clicked */
onMinimize: PropTypes.func,
/** A SideNav Search element */
search: PropTypes.node,
/** Renders a button to minimize the SideNav */
showMinimizeButton: PropTypes.bool,
/** Title at the top of the SideNav */
superHeaderLabel: PropTypes.string,
/** An href for the SideNav Title */
superHeaderLink: PropTypes.string
};
static defaultProps = {
onMinimize: () => {},
showMinimizeButton: false
};
_renderHeader = (link, label, styles) => {
if (!label) {
return null;
}
if (link) {
return (
<TextLink link={link} style={styles}>
{label}
</TextLink>
);
}
return <Typography style={styles}>{label}</Typography>;
};
_renderHeaders = resolvedRoles => {
const {
headerLabel,
headerLink,
superHeaderLabel,
superHeaderLink
} = this.props;
if (!(superHeaderLabel || headerLabel)) {
return null;
}
return (
<div>
{this._renderHeader(
superHeaderLink,
superHeaderLabel,
stylesheet({ isLink: superHeaderLink, ...this.props }, resolvedRoles)
.headers.super
)}
{this._renderHeader(
headerLink,
headerLabel,
stylesheet({ isLink: headerLink, ...this.props }, resolvedRoles)
.headers.normal
)}
</div>
);
};
render() {
const {
children,
copyright,
groups,
links,
onMinimize,
search,
showMinimizeButton
} = this.props;
return (
<ThemeContext.Consumer>
{({ resolvedRoles }) => {
const styles = stylesheet(this.props, resolvedRoles);
return (
<nav className={css(styles.sideNav)}>
<div className={css(styles.overflow)}>
{this._renderHeaders(resolvedRoles)}
{groups && <div>{groups}</div>}
{children && <div className={css(styles.slot)}>{children}</div>}
{links && <div className={css(styles.links)}>{links}</div>}
{copyright && (
<div className={css(styles.copyright)}>{copyright}</div>
)}
</div>
{search}
{showMinimizeButton && (
<div className={css(styles.minimize)}>
<IconButton
icon={<Back24 />}
title="Minimize"
aria-label="Minimize"
onClick={onMinimize}
/>
</div>
)}
</nav>
);
}}
</ThemeContext.Consumer>
);
}
}
|
JavaScript
| 0 |
@@ -805,32 +805,112 @@
opTypes.string,%0A
+ /** Called when headerLink is clicked */%0A onClickHeader: PropTypes.func,%0A
/** 0 or mor
@@ -1354,16 +1354,106 @@
s.string
+,%0A /** Called when superHeaderLink is clicked */%0A onClickSuperHeader: PropTypes.func
%0A %7D;%0A%0A
@@ -1577,16 +1577,25 @@
, styles
+, onClick
) =%3E %7B%0A
@@ -1649,16 +1649,27 @@
if (link
+ %7C%7C onClick
) %7B%0A
@@ -1723,16 +1723,34 @@
%7Bstyles%7D
+ onClick=%7BonClick%7D
%3E%0A
@@ -1946,24 +1946,45 @@
headerLink,%0A
+ onClickHeader,%0A
superH
@@ -2016,16 +2016,42 @@
aderLink
+,%0A onClickSuperHeader
%0A %7D =
@@ -2351,16 +2351,46 @@
rs.super
+,%0A onClickSuperHeader
%0A
@@ -2569,16 +2569,41 @@
s.normal
+,%0A onClickHeader
%0A
|
74b1bcc050e76b1e2f18df2efbdf38685e410bb7
|
align remove page styles with other pages
|
src/pages/RemovePage.js
|
src/pages/RemovePage.js
|
import React, { useState } from 'react';
import { Helmet } from 'react-helmet';
import { useQuery, useMutation } from '@apollo/client';
import { loader } from 'graphql.macro';
import config from '../config';
import history from '../history';
import PageLayout from '../components/PageLayout';
import Notification from '../components/Notification';
const FIND_LOO_BY_ID = loader('./findLooById.graphql');
const REMOVE_LOO_MUTATION = loader('./removeLoo.graphql');
const RemovePage = function (props) {
const [reason, setReason] = useState('');
const { loading: loadingLoo, data: looData, error: looError } = useQuery(
FIND_LOO_BY_ID,
{
variables: {
id: props.match.params.id,
},
}
);
const [
doRemove,
{ loading: loadingRemove, error: removeError },
] = useMutation(REMOVE_LOO_MUTATION, {
onCompleted: () => {
props.history.push(`/loos/${props.match.params.id}?message=removed`);
},
});
const updateReason = (evt) => {
setReason(evt.currentTarget.value);
};
const onSubmit = (e) => {
e.preventDefault();
doRemove({
variables: {
id: looData.loo.id,
reason,
},
});
};
if (removeError || looError) {
console.error(removeError || looError);
}
if (loadingLoo || looError) {
return (
<PageLayout>
<Notification>
{loadingLoo ? 'Fetching Toilet Data' : 'Error finding toilet.'}
</Notification>
</PageLayout>
);
}
if (!looData.loo.active) {
history.push('/');
}
return (
<PageLayout>
<Helmet>
<title>{config.getTitle('Remove Toilet')}</title>
</Helmet>
<div>
<h2>Toilet Remover</h2>
<p>
Please let us know why you're removing this toilet from the map using
the form below.
</p>
<form onSubmit={onSubmit}>
<label>
Reason for removal
<textarea
type="text"
name="reason"
value={reason}
onChange={updateReason}
required
/>
</label>
<button type="submit">Remove</button>
</form>
{loadingRemove && (
<Notification>Submitting removal report…</Notification>
)}
{removeError && (
<Notification>
Oops. We can't submit your report at this time. Try again later.
</Notification>
)}
</div>
</PageLayout>
);
};
export default RemovePage;
|
JavaScript
| 0.000001 |
@@ -284,24 +284,198 @@
ageLayout';%0A
+import Container from '../components/Container';%0Aimport Spacer from '../components/Spacer';%0Aimport Text from '../components/Text';%0Aimport Button from '../components/Button';%0A
import Notif
@@ -1841,21 +1841,136 @@
%0A %3C
-div%3E%0A
+Container maxWidth=%7B845%7D%3E%0A %3CSpacer mb=%7B5%7D /%3E%0A%0A %3CText fontSize=%7B6%7D fontWeight=%22bold%22 textAlign=%22center%22%3E%0A
@@ -1971,17 +1971,17 @@
%3Ch
-2
+1
%3EToilet
@@ -1994,9 +1994,52 @@
r%3C/h
-2
+1%3E%0A %3C/Text%3E%0A%0A %3CSpacer mb=%7B5%7D /
%3E%0A%0A
@@ -2169,16 +2169,43 @@
%3C/p%3E%0A%0A
+ %3CSpacer mb=%7B3%7D /%3E%0A%0A
@@ -2261,16 +2261,19 @@
+%3Cb%3E
Reason f
@@ -2282,16 +2282,20 @@
removal
+%3C/b%3E
%0A
@@ -2453,16 +2453,118 @@
equired%0A
+ css=%7B%7B%0A height: '100px',%0A width: '100%25',%0A %7D%7D%0A
@@ -2601,17 +2601,46 @@
%3C
-b
+Spacer mb=%7B3%7D /%3E%0A%0A %3CB
utton ty
@@ -2659,17 +2659,17 @@
Remove%3C/
-b
+B
utton%3E%0A
@@ -2974,11 +2974,17 @@
%3C/
-div
+Container
%3E%0A
|
316d2c2c0762669ad927d7157b515a6b9133ef2f
|
Add more insertAtHead tests
|
tests/linkedlist-test.js
|
tests/linkedlist-test.js
|
var assert = require("assert");
var ll = require('../dstructs/linkedlist');
var LinkedList = ll.LinkedList;
describe('LinkedList', function() {
describe('empty LinkedList', function() {
it('should return an empty array after initialized', function() {
assert.equal(0, (new LinkedList()).toArray().length);
});
it('should return an object which is instanceof Array', function() {
assert.equal(true, (new LinkedList()).toArray() instanceof Array);
});
});
describe('one item in linkedlist', function() {
it('should have length of 1', function(){
var list = new LinkedList();
list.insertAtTail(1);
assert.equal(1, list.toArray().length);
});
it('should be found at index 0', function() {
var list = new LinkedList();
list.insertAtTail(2);
assert.equal(0, list.search(2));
});
it('random other node should return index -1', function() {
var list = new LinkedList();
list.insertAtTail(1);
assert.equal(-1, list.search(3));
});
it('random other nodes should return index -1', function() {
var list = new LinkedList();
list.insertAtTail(3);
assert.equal(-1, list.search(1));
});
it('search should not remove any items', function() {
var list = new LinkedList();
list.insertAtTail(3); //new LinkedListNode(3)
list.search(1);
assert.equal(1, list.toArray().length);
});
});
describe('insertAtHead', function() {
it('search after insert at head with 0 items initially', function() {
var list = new LinkedList();
list.insertAtHead(2);
assert.equal(0, list.search(2));
});
it('insert 3 items at head items initially', function() {
var list = new LinkedList();
list.insertAtHead(2);
list.insertAtHead(3);
list.insertAtHead(4);
assert.equal(0, list.search(4));
assert.equal(1, list.search(3));
assert.equal(2, list.search(2));
});
});
});
|
JavaScript
| 0 |
@@ -1945,32 +1945,99 @@
ist.search(2));%0A
+ list.insertAtHead(2);%0A assert.equal(0, list.search(2));%0A
%7D);%0A %7D);%0A%7D)
|
b40bb2629baddfc7545998a1dad88243cbb7d8d0
|
add related model
|
lib/assets/javascripts/cartodb3/editor/layers/layer-content-views/infowindow/infowindow-fields-view.js
|
lib/assets/javascripts/cartodb3/editor/layers/layer-content-views/infowindow/infowindow-fields-view.js
|
var FieldView = require('./infowindow-field-view.js');
var template = require('./infowindow-fields.tpl');
var cdb = require('cartodb.js');
var Backbone = require('backbone');
var _ = require('underscore');
var $ = require('jquery');
require('jquery-ui/sortable');
module.exports = cdb.core.View.extend({
initialize: function (opts) {
if (!opts.layerInfowindowModel) throw new Error('layerInfowindowModel is required');
if (!opts.querySchemaModel) throw new Error('querySchemaModel is required');
if (!opts.layerDefinitionModel) throw new Error('layerDefinitionModel is required');
this._layerInfowindowModel = opts.layerInfowindowModel;
this._querySchemaModel = opts.querySchemaModel;
this._layerDefinitionModel = opts.layerDefinitionModel;
this._columnsCollection = this._querySchemaModel.columnsCollection;
// An internal collection to keep track of the columns and their order
this._sortedFields = new Backbone.Collection();
this._sortedFields.comparator = function (model) {
return model.get('position');
};
this._layerInfowindowModel.bind('change', _.debounce(function () {
this._layerDefinitionModel.save();
}, 20), this);
},
render: function () {
this._destroySortable();
this.clearSubViews();
this.$el.html(template);
this._renderFields();
this._initSortable();
this._storeSortedFields();
return this;
},
_initSortable: function () {
this.$('.js-fields').sortable({
axis: 'y',
items: '> li',
opacity: 0.8,
update: this._onSortableFinish.bind(this),
forcePlaceholderSize: false
}).disableSelection();
},
_destroySortable: function () {
if (this.$('.js-fields').data('ui-sortable')) {
this.$('.js-fields').sortable('destroy');
}
},
_onSortableFinish: function () {
var self = this;
this._sortedFields.reset([]);
this.$('.js-fields > .js-field').each(function (index, item) {
var view = self._subviews[$(item).data('view-cid')];
self._layerInfowindowModel.setFieldProperty(view.fieldName, 'position', index);
view.position = index;
self._sortedFields.add({
name: view.fieldName,
position: index
});
});
},
_getSortedColumnNames: function () {
var self = this;
var names = this._getColumnNames();
if (self._layerInfowindowModel.fieldCount() > 0) {
names.sort(function (a, b) {
var pos_a = self._layerInfowindowModel.getFieldPos(a);
var pos_b = self._layerInfowindowModel.getFieldPos(b);
return pos_a - pos_b;
});
}
return names;
},
_storeSortedFields: function () {
var self = this;
this._sortedFields.reset([]);
var names = this._getSortedColumnNames();
_(names).each(function (name, position) {
self._sortedFields.add({
name: name,
position: position
});
});
},
_getColumnNames: function () {
var self = this;
var columns = this._columnsCollection.models;
var filteredColumns = _(columns).filter(function (c) {
return !_.contains(self._layerInfowindowModel.SYSTEM_COLUMNS, c.get('name'));
});
var columnNames = [];
_(filteredColumns).each(function (m) {
columnNames.push(m.get('name'));
});
return columnNames;
},
_renderFields: function () {
var self = this;
var names = this._getColumnNames();
// If there isn't any valid column available
// show the message in the background
// if (names.length == 0) {
// this._showNoContent();
// return false;
// }
names.sort(function (a, b) {
var pos_a = self._layerInfowindowModel.getFieldPos(a);
var pos_b = self._layerInfowindowModel.getFieldPos(b);
return pos_a - pos_b;
});
_(names).each(function (f, i) {
var title = false;
if (self._layerInfowindowModel.containsField(f)) {
var pos = _.indexOf(_(self._layerInfowindowModel.get('fields')).pluck('name'), f);
title = self._layerInfowindowModel.get('fields')[pos] && self._layerInfowindowModel.get('fields')[pos].title;
}
var view = new FieldView({
layerInfowindowModel: self._layerInfowindowModel,
field: { name: f, title: title },
position: self._layerInfowindowModel.getFieldPos(f)
});
self.addView(view);
self.$('.js-fields').append(view.render().el);
});
},
clean: function () {
this._destroySortable();
cdb.core.View.prototype.clean.apply(this);
}
});
|
JavaScript
| 0 |
@@ -1188,24 +1188,81 @@
20), this);
+%0A%0A this.add_related_model(this._layerInfowindowModel);
%0A %7D,%0A%0A ren
|
22b67eb2a6ab04d8e4d65c7c9a291ec35ed13840
|
support target-dir for resource-file
|
cordova-lib/src/plugman/platforms/ubuntu.js
|
cordova-lib/src/plugman/platforms/ubuntu.js
|
/*
*
* Copyright 2013 Canonical Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
*/
/* jshint node:true, bitwise:true, undef:true, trailing:true, quotmark:true,
indent:4, unused:vars, latedef:nofunc,
laxcomma:true, sub:true
*/
function replaceAt(str, index, char) {
return str.substr(0, index) + char + str.substr(index + char.length);
}
function toCamelCase(str) {
return str.split('-').map(function(str) {
return replaceAt(str, 0, str[0].toUpperCase());
}).join('');
}
var shell = require('shelljs')
, fs = require('fs')
, path = require('path')
, common = require('./common')
, events = require('../../events')
, xml_helpers = require(path.join(__dirname, '..', '..', 'util', 'xml-helpers'));
module.exports = {
www_dir:function(project_dir) {
return path.join(project_dir, 'www');
},
package_name:function (project_dir) {
var config_path = path.join(project_dir, 'config.xml');
var widget_doc = xml_helpers.parseElementtreeSync(config_path);
return widget_doc._root.attrib['id'];
},
'source-file':{
install:function(source_el, plugin_dir, project_dir, plugin_id) {
var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(source_el.attrib.src));
common.copyFile(plugin_dir, source_el.attrib.src, project_dir, dest);
},
uninstall:function(source_el, project_dir, plugin_id) {
var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
shell.rm(path.join(dest, path.basename(source_el.attrib.src)));
}
},
'header-file':{
install:function(source_el, plugin_dir, project_dir, plugin_id) {
var dest = path.join('build', 'src', 'plugins', plugin_id, path.basename(source_el.attrib.src));
common.copyFile(plugin_dir, source_el.attrib.src, project_dir, dest);
var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
var src = String(fs.readFileSync(plugins));
src = src.replace('INSERT_HEADER_HERE', '#include "plugins/' + plugin_id + '/' + path.basename(source_el.attrib.src) +'"\nINSERT_HEADER_HERE');
var class_name = plugin_id.match(/\.[^.]+$/)[0].substr(1);
class_name = toCamelCase(class_name);
src = src.replace('INSERT_PLUGIN_HERE', 'INIT_PLUGIN(' + class_name + ');INSERT_PLUGIN_HERE');
fs.writeFileSync(plugins, src);
},
uninstall:function(source_el, project_dir, plugin_id) {
var dest = path.join(project_dir, 'build', 'src', 'plugins', plugin_id);
shell.rm(path.join(dest, path.basename(source_el.attrib.src)));
var plugins = path.join(project_dir, 'build', 'src', 'coreplugins.cpp');
var src = String(fs.readFileSync(plugins));
src = src.replace('#include "plugins/' + plugin_id + '/' + path.basename(source_el.attrib.src) +'"', '');
var class_name = plugin_id.match(/\.[^.]+$/)[0].substr(1);
class_name = toCamelCase(class_name);
src = src.replace('INIT_PLUGIN(' + class_name + ');', '');
fs.writeFileSync(plugins, src);
}
},
'resource-file':{
install:function(source_el, plugin_dir, project_dir, plugin_id) {
var dest = path.join('qml', path.basename(source_el.attrib.src));
common.copyFile(plugin_dir, source_el.attrib.src, project_dir, dest);
},
uninstall:function(source_el, project_dir, plugin_id) {
var dest = path.join(project_dir, 'qml');
shell.rm(path.join(dest, path.basename(source_el.attrib.src)));
}
},
'framework': {
install:function(source_el, plugin_dir, project_dir, plugin_id) {
events.emit('verbose', 'framework.install is not supported for ubuntu');
},
uninstall:function(source_el, project_dir, plugin_id) {
events.emit('verbose', 'framework.uninstall is not supported for ubuntu');
}
},
'lib-file': {
install:function(source_el, plugin_dir, project_dir, plugin_id) {
events.emit('verbose', 'lib-file.install is not supported for ubuntu');
},
uninstall:function(source_el, project_dir, plugin_id) {
events.emit('verbose', 'lib-file.uninstall is not supported for ubuntu');
}
}
};
|
JavaScript
| 0.000001 |
@@ -3922,32 +3922,183 @@
l.attrib.src));%0A
+ if (source_el.attrib%5B'target-dir'%5D)%0A dest = path.join(source_el.attrib%5B'target-dir'%5D, path.basename(source_el.attrib.src));%0A
comm
@@ -4288,24 +4288,151 @@
ir, 'qml');%0A
+ if (source_el.attrib%5B'target-dir'%5D)%0A dest = path.join(project_dir, source_el.attrib%5B'target-dir'%5D);%0A
|
33a39f0d39beeeb4f22ef285c0ad36528357bb44
|
remove only
|
tests/mount-deep.test.js
|
tests/mount-deep.test.js
|
/* eslint-env jest */
import React from 'react';
import Enzyme, {mount} from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import mountToJson from '../src/mount';
import {
BasicPure,
BasicWithUndefined,
BasicWithAList,
ComponentWithAZeroChildren,
ArrayRender,
} from './fixtures/pure-function';
import {
BasicClass,
ClassWithPure,
ClassWithDirectPure,
ClassWithDirectComponent,
ClassWithNull,
ClassArrayRender,
} from './fixtures/class';
import {ForwardRefWithDefaultProps} from './fixtures/forwardRef';
import {BasicMemo, ArrayMemo} from './fixtures/memo';
Enzyme.configure({adapter: new Adapter()});
const deepOptions = {mode: 'deep'};
it('converts basic pure mount', () => {
const mounted = mount(
<BasicPure className="pure">
<strong>Hello!</strong>
</BasicPure>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts pure mount with mixed children', () => {
const mounted = mount(<BasicPure>Hello {'world'}!</BasicPure>);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts basic class mount', () => {
const mounted = mount(
<BasicClass className="class">
<strong>Hello!</strong>
</BasicClass>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts class mount with mixed children', () => {
const mounted = mount(<BasicClass>Hello {'world'}!</BasicClass>);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts a class mount with a pure function in it', () => {
const mounted = mount(
<ClassWithPure className="class">
<strong>Hello!</strong>
</ClassWithPure>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts a class mount with a pure function in it as a direct child', () => {
const mounted = mount(
<ClassWithDirectPure className="class">
<strong>Hello!</strong>
</ClassWithDirectPure>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts a class mount with a class component in it as a direct child', () => {
const mounted = mount(
<ClassWithDirectComponent className="class">
<strong>Hello!</strong>
</ClassWithDirectComponent>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts function components with render returning top level arrays', () => {
const mounted = mount(
<ArrayRender>
<strong>Hello!</strong>
</ArrayRender>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('converts class components with render returning top level arrays', () => {
const mounted = mount(
<ClassArrayRender>
<strong>Hello!</strong>
</ClassArrayRender>,
);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('handles a component which returns null', () => {
const mounted = mount(<ClassWithNull />);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('includes undefined props', () => {
const mounted = mount(<BasicWithUndefined>Hello!</BasicWithUndefined>);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('renders zero-children', () => {
const mounted = mount(<ComponentWithAZeroChildren />);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it('renders multiple elements as a result of find', () => {
const mounted = mount(<BasicWithAList />);
expect(mountToJson(mounted.find('li'), deepOptions)).toMatchSnapshot();
});
it('excludes forwardRef node but renders wrapped component', () => {
const mounted = mount(<ForwardRefWithDefaultProps />);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it.only('excludes memo node but renders wrapped component', () => {
const mounted = mount(<BasicMemo className="foo" />);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
it.only('excludes memo node but renders wrapped top level array properly', () => {
const mounted = mount(<ArrayMemo className="foo" />);
expect(mountToJson(mounted, deepOptions)).toMatchSnapshot();
});
|
JavaScript
| 0.000001 |
@@ -3712,37 +3712,32 @@
pshot();%0A%7D);%0A%0Ait
-.only
('excludes memo
@@ -3912,13 +3912,8 @@
%0A%0Ait
-.only
('ex
|
a0d5e48b2c6f3ce829112fb7c2caa3f0f86c5754
|
Move occasions method to bottom for easier readability
|
src/jquery.occasions.js
|
src/jquery.occasions.js
|
/*
* Copyright (c) 2014 Stephen Peasley (http://www.speasley.com)
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
*
* Version 2.0.0
* Made in Canada
*/
;(function($) {
'use strict';
$.fn.occasions = function() {
$element = this;
var settings = $.extend({
country: 'none',
internals: false,
path: '',
sect: 'none',
onSuccess: function() {}
}, arguments[0] || {});
if (settings.internals) {
return internals;
}
return this.each(function() {
init(settings,$element);
});
};
var $element = null;
var occasions = null;
// internal functions
var internals = {}
var init = internals.init = function(settings,element) {
var files = ['occasions.json'];
if(settings.country != 'none') { files.push(settings.country.toLowerCase()+'.json'); }
if(settings.sect != 'none') { files.push(settings.sect.toLowerCase()+'.json'); }
var loaded = 0;
for (var i=0; i < files.length; i++) {
$.ajax({
async: true,
url: settings.path+files[i],
type:'get',
dataType:'json',
success: function(data) {
if(occasions == null) {
occasions = data;
}else{
mergeHashes(occasions,data);
}
loaded++;
if(loaded===files.length) {
main(settings,element);
}
}
});
}
}
var mergeHashes = internals.mergeHashes = function(obj, src) {
Object.keys(src).forEach(function(key) { obj[key] = src[key]; });
return obj;
}
var todaysDate = internals.todaysDate = function(override) {
var today = new Date();
var now_month = today.getMonth()+1;
var now_day = today.getDate();
var now_date = (now_month<10 ? '0' : '') + now_month + '/' + (now_day<10 ? '0' : '') + now_day;
if (override) {
now_date = override;
}
return now_date;
}
var timestamp = internals.timestamp = function(month,day) {
var today = new Date();
var ts = new Date(today.getFullYear()+'-'+today.getMonth()+'-'+today.getDate()).getTime() / 1000;
return ts;
};
var main = internals.main = function(settings,element) {
var todays_date = todaysDate(settings.date_override);
if(occasions[todays_date]!=null) {
console.log(element.css({'background':'red'}));
element.addClass(occasions[todays_date]);
element.occasion = occasions[todays_date];
settings.onSuccess.call(element);
}
}
})(jQuery);
|
JavaScript
| 0 |
@@ -298,382 +298,8 @@
';%0A%0A
- $.fn.occasions = function() %7B %0A%0A $element = this;%0A%0A var settings = $.extend(%7B%0A country: 'none',%0A internals: false,%0A path: '',%0A sect: 'none',%0A onSuccess: function() %7B%7D%0A %7D, arguments%5B0%5D %7C%7C %7B%7D);%0A%0A if (settings.internals) %7B%0A return internals;%0A %7D%0A%0A return this.each(function() %7B%0A init(settings,$element);%0A %7D);%0A %0A %7D;%0A%0A
va
@@ -2221,16 +2221,390 @@
%7D%0A %7D%0A%0A
+ $.fn.occasions = function() %7B %0A%0A $element = this;%0A%0A var settings = $.extend(%7B%0A country: 'none',%0A internals: false,%0A path: '',%0A sect: 'none',%0A onSuccess: function() %7B%7D%0A %7D, arguments%5B0%5D %7C%7C %7B%7D);%0A%0A if (settings.internals) %7B%0A return internals;%0A %7D%0A%0A return this.each(function() %7B%0A init(settings,$element);%0A %7D);%0A %0A %7D;%0A%0A
%7D)(jQuer
|
5051b70888861b48ee4e75e39aac319a9c9df43e
|
Fix bug of lazy image loading with tables
|
src/js/content/image.js
|
src/js/content/image.js
|
/**
*
* Content Style - Image (JS)
*
* @author Takuto Yanagida @ Space-Time Inc.
* @version 2018-02-16
*
*/
document.addEventListener('DOMContentLoaded', function () {
const TARGET_SELECTOR = '.stile';
initializeLazyImageLoading();
modifyFigureStyle();
// -------------------------------------------------------------------------
// Figure Styles
function modifyFigureStyle() {
const figs = document.querySelectorAll(TARGET_SELECTOR + ' figure');
for (let i = 0; i < figs.length; i += 1) {
figs[i].style.width = '';
}
}
// -------------------------------------------------------------------------
// Lazy Image Loading
function initializeLazyImageLoading() {
const OFFSET = 100;
const imgs = document.querySelectorAll(TARGET_SELECTOR + ' img');
const winY = window.scrollY | window.pageYOffset;
for (let i = 0; i < imgs.length; i += 1) {
const img = imgs[i];
if (elementTopOnWindow(img) >= winY + window.innerHeight + OFFSET) hide(img);
}
window.addEventListener('scroll', onScroll);
onScroll();
function onScroll() {
const winY = window.scrollY | window.pageYOffset;
for (let i = 0; i < imgs.length; i += 1) {
const img = imgs[i];
if (!img.dataset.src) continue;
if (elementTopOnWindow(img) < winY + window.innerHeight + OFFSET) show(img);
}
}
doBeforePrint(onPrint);
function onPrint() {
for (let i = 0; i < imgs.length; i += 1) {
const img = imgs[i];
if (!img.dataset.src) continue;
show(img);
}
}
}
function hide(img) {
img.dataset['src'] = img.src;
img.src = 'data:image/gif;base64,R0lGODdhAQABAPAAAP///wAAACwAAAAAAQABAEACAkQBADs=';
if (img.srcset) {
img.dataset['srcset'] = img.srcset;
img.srcset = '';
}
img.style.opacity = 0;
const h = img.getAttribute('height');
if (h) img.style.minHeight = h + 'px';
}
function show(img) {
if (img.dataset.srcset) {
img.srcset = img.dataset.srcset;
img.dataset.srcset = '';
}
img.src = img.dataset.src;
img.dataset.src = '';
img.style.minHeight = '';
setTimeout((function (img) {return function () {img.style.opacity = '';};})(img), 200);
}
function elementTopOnWindow(elm) {
let top = 0;
while (elm) {
top += elm.offsetTop;
elm = elm.offsetParent;
}
return top;
}
function doBeforePrint(func, forceMediaCheck = true) {
window.addEventListener('beforeprint', func, false);
if (forceMediaCheck || !('onbeforeprint' in window)) {
let printMedia;
if (window.matchMedia && (printMedia = matchMedia('print')) && printMedia.addListener) {
printMedia.addListener(function () {if (printMedia.matches) func();});
}
}
}
});
|
JavaScript
| 0 |
@@ -100,12 +100,12 @@
18-0
-2-16
+4-03
%0A *%0A
@@ -777,16 +777,95 @@
' img');
+%0A%09%09const imgsInTbl = document.querySelectorAll(TARGET_SELECTOR + ' table img');
%0A%0A%09%09cons
@@ -979,16 +979,73 @@
mgs%5Bi%5D;%0A
+%09%09%09if (%5B%5D.indexOf.call(imgsInTbl, img) !== -1) continue;%0A
%09%09%09if (e
@@ -1371,20 +1371,29 @@
ue;%0A%09%09%09%09
-if (
+const imgY =
elementT
@@ -1407,16 +1407,30 @@
dow(img)
+;%0A%09%09%09%09if (imgY
%3C winY
@@ -2214,32 +2214,8 @@
out(
-(function (img) %7Breturn
func
@@ -2251,16 +2251,8 @@
'';%7D
-;%7D)(img)
, 20
|
6495f02fd719d181ab3342c78823fba469f7cb00
|
Fix JSHint error
|
src/js/views/listing.js
|
src/js/views/listing.js
|
(function (App) {
'use strict';
var Listing = Backbone.Marionette.ItemView.extend({
template: '#listing-tpl',
tagName: 'article',
className: 'listing',
events : {
'click .info' : 'loadSubmission',
'click .upvote': 'upvote',
'click .downvote': 'downvote',
},
ui : {
voting : '.voting'
},
initialize : function() {
this.model.on('change', this.render, this);
},
loadSubmission: function(e) {
$('#submission').removeClass('hidden').addClass('shown');
$('#submission').html('<iframe nwdisable nwfaketop src="'+ this.model.get('url')+ '"/>')
//App.vent.trigger('main:getsubmission', this.model.get('id'), {});
},
upvote: function(e) {
e.stopPropagation();
var _this = this;
if(_this.model.get('likes')){
return _this.unvote();
}
else {
App.vent.trigger('main:upvote', _this.model.get('name'), function() {
if(_this.model.get('likes') != null && _this.model.get('likes') === false) { // was downvoted before
_this.model.set('score', _this.model.get('score') + 2);
}
else {
_this.model.set('score', _this.model.get('score') + 1);
}
_this.model.set('likes', true);
});
}
},
downvote: function(e) {
var _this = this;
e.stopPropagation();
if(_this.model.get('likes') != null && _this.model.get('likes') === false) {
return _this.unvote();
}
else {
App.vent.trigger('main:downvote', _this.model.get('name'), function() {
if(_this.model.get('likes')) { // was upvoted before downvoting
_this.model.set('score', _this.model.get('score') - 2);
}
else {
_this.model.set('score', _this.model.get('score') - 1);
}
_this.model.set('likes', false);
});
}
},
unvote: function() {
var _this = this;
App.vent.trigger('main:unvote', _this.model.get('name'), function() {
if(_this.model.get('likes')) {
_this.model.set('score', _this.model.get('score') - 1);
}
else {
_this.model.set('score', _this.model.get('score') + 1);
}
_this.model.set('likes', null);
});
},
});
App.View.Listing = Listing;
})(window.App);
|
JavaScript
| 0.000007 |
@@ -578,16 +578,17 @@
+ '%22/%3E')
+;
%0A%09%09%09//Ap
|
b751dff456e1a17daab8e9a9bc775e7ae581054f
|
increase logging for edge cases
|
lib/instrumentation/transaction.js
|
lib/instrumentation/transaction.js
|
'use strict'
var uuid = require('node-uuid')
var debug = require('debug')('opbeat')
var Trace = require('./trace')
module.exports = Transaction
function Transaction (agent, name, type, result) {
Object.defineProperty(this, 'name', {
configurable: true,
enumerable: true,
get: function () {
return this._customName || this._defaultName
},
set: function (name) {
debug('setting transaction name %o', { uuid: this._uuid, name: name })
this._customName = name
}
})
this._defaultName = name
this.type = type
this.result = result
this.traces = []
this.ended = false
this._uuid = uuid.v4()
this._agent = agent
debug('start transaction %o', { uuid: this._uuid, name: name, type: type, result: result })
// Don't leak traces from previous transactions
this._agent._instrumentation.currentTrace = null
// A transaction should always have a root trace spanning the entire
// transaction.
this._rootTrace = new Trace(this)
this._rootTrace.start('transaction', 'transaction')
this._start = this._rootTrace._start
this.duration = this._rootTrace.duration.bind(this._rootTrace)
}
Transaction.prototype.end = function () {
if (this.ended) return debug('cannot end already ended transaction %o', { uuid: this._uuid })
this._rootTrace.end()
this.ended = true
var trace = this._agent._instrumentation.currentTrace
if (!trace || trace.transaction !== this) {
// This should normally not happen, but if the hooks into Node.js doesn't
// work as intended it might. In that case we want to gracefully handle it.
// That involves ignoring all traces under the given transaction as they
// will most likely be incomplete. We still want to send the transaction
// without any traces to Opbeat as it's still valuable data.
debug('transaction is out of sync %o', { uuid: this._uuid })
this.traces = []
}
this._agent._instrumentation.addEndedTransaction(this)
debug('ended transaction %o', { uuid: this._uuid, type: this.type, result: this.result })
}
Transaction.prototype._recordEndedTrace = function (trace) {
if (this.ended) {
debug('Can\'t record ended trace after parent transaction have ended - ignoring %o', { uuid: this._uuid })
return
}
this.traces.push(trace)
}
|
JavaScript
| 0.000001 |
@@ -1388,64 +1388,33 @@
ace%0A
+%0A
-if (!trace %7C%7C trace.transaction !== this) %7B%0A // Thi
+// These two edge-case
s sh
@@ -1460,16 +1460,21 @@
oks into
+%0A //
Node.js
@@ -1481,23 +1481,16 @@
doesn't
-%0A //
work as
@@ -1532,16 +1532,21 @@
want to
+%0A //
gracefu
@@ -1559,23 +1559,16 @@
ndle it.
-%0A //
That in
@@ -1609,16 +1609,21 @@
he given
+%0A //
transac
@@ -1634,23 +1634,16 @@
as they
-%0A //
will mo
@@ -1688,16 +1688,21 @@
to send
+%0A //
the tra
@@ -1713,15 +1713,8 @@
tion
-%0A //
wit
@@ -1768,16 +1768,156 @@
e data.%0A
+ if (!trace) %7B%0A debug('no active trace found %25o', %7B uuid: this._uuid %7D)%0A this.traces = %5B%5D%0A %7D else if (trace.transaction !== this) %7B%0A
debu
|
9cf1fe31598e76e58098c3598bf8ff0529f26e63
|
Remove redundant blit from AfterimagePass
|
examples/js/postprocessing/AfterimagePass.js
|
examples/js/postprocessing/AfterimagePass.js
|
/**
* @author HypnosNova / https://www.threejs.org.cn/gallery/
*/
THREE.AfterimagePass = function ( damp ) {
THREE.Pass.call( this );
if ( THREE.AfterimageShader === undefined )
console.error( "THREE.AfterimagePass relies on THREE.AfterimageShader" );
this.shader = THREE.AfterimageShader;
this.uniforms = THREE.UniformsUtils.clone( this.shader.uniforms );
this.uniforms[ "damp" ].value = damp !== undefined ? damp : 0.96;
this.textureComp = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, {
minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat
} );
this.textureOld = new THREE.WebGLRenderTarget( window.innerWidth, window.innerHeight, {
minFilter: THREE.LinearFilter,
magFilter: THREE.NearestFilter,
format: THREE.RGBAFormat
} );
this.shaderMaterial = new THREE.ShaderMaterial( {
uniforms: this.uniforms,
vertexShader: this.shader.vertexShader,
fragmentShader: this.shader.fragmentShader
} );
this.compFsQuad = new THREE.Pass.FullScreenQuad( this.shaderMaterial );
var material = new THREE.MeshBasicMaterial( {
map: this.textureComp.texture
} );
this.screenFsQuad = new THREE.Pass.FullScreenQuad( material );
};
THREE.AfterimagePass.prototype = Object.assign( Object.create( THREE.Pass.prototype ), {
constructor: THREE.AfterimagePass,
render: function ( renderer, writeBuffer, readBuffer ) {
this.uniforms[ "tOld" ].value = this.textureOld.texture;
this.uniforms[ "tNew" ].value = readBuffer.texture;
renderer.setRenderTarget( this.textureComp );
this.compFsQuad.render( renderer );
renderer.setRenderTarget( this.textureOld );
this.screenFsQuad.render( renderer );
if ( this.renderToScreen ) {
renderer.setRenderTarget( null );
this.screenFsQuad.render( renderer );
} else {
renderer.setRenderTarget( writeBuffer );
if ( this.clear ) renderer.clear();
this.screenFsQuad.render( renderer );
}
},
setSize: function ( width, height ) {
this.textureComp.setSize( width, height );
this.textureOld.setSize( width, height );
}
} );
|
JavaScript
| 0 |
@@ -1113,46 +1113,8 @@
ial(
- %7B%0A%09%09map: this.textureComp.texture%0A%09%7D
);%0A%09
@@ -1114,30 +1114,28 @@
al();%0A%09this.
-screen
+copy
FsQuad = new
@@ -1572,91 +1572,63 @@
%0A%0A%09%09
-renderer.setRenderTarget( this.textureOld );%0A%09%09this.screenFsQuad.render( renderer )
+this.copyFsQuad.material.map = this.textureComp.texture
;%0A%0A%09
@@ -1695,38 +1695,36 @@
null );%0A%09%09%09this.
-screen
+copy
FsQuad.render( r
@@ -1844,14 +1844,12 @@
his.
-screen
+copy
FsQu
@@ -1877,16 +1877,204 @@
;%0A%0A%09%09%7D%0A%0A
+%09%09// Swap buffers.%0A%09%09var temp = this.textureOld;%0A%09%09this.textureOld = this.textureComp;%0A%09%09this.textureComp = temp;%0A%09%09// Now textureOld contains the latest image, ready for the next frame.%0A%0A
%09%7D,%0A%0A%09se
|
0d28baa1974afcecba0d45eb81e978b7db0c8ed1
|
fix doc comment missing
|
src/classes/Display.js
|
src/classes/Display.js
|
'use strict';
/**
* Create the test DPI element
* @function
*/
function createTestDPIElement(){
testDPIElement = $('<div/>')
.attr('id','dpi-test')
.css({
position: 'absolute',
top: '-100%',
left: '-100%',
height: '1in',
width: '1in',
border: 'red 1px solid'
});
$('body').prepend(testDPIElement);
}
/**
* @constructor
*/
function Display(_document){
this.document = _document;
this._setScreenDPI();
}
/**
* @property
* @private
*/
var testDPIElement;
/**
* @method
* @return the screen DPI
*/
Display.prototype._setScreenDPI = function(){
createTestDPIElement();
if (testDPIElement[0].offsetWidth !== testDPIElement[0].offsetHeight)
throw new Error('FATAL ERROR: Bad Screen DPI !');
this.screenDPI = testDPIElement[0].offsetWidth;
};
/**
* @method
* @param DOMDocument _document
* @param String unit
*
* @return `_document` body height in `unit` unit
*/
Display.prototype.height = function(unit){
if (!unit) throw new Error('Explicit unit for getting document height is required');
var pixels = $('body',this.document).height();
if (unit === 'px') return pixels;
if (unit === 'mm') return this.px2mm(pixels);
};
/**
* Converts pixels amount to milimeters, in function of current display DPI
*
* Calculus rule
* 1 dpi := pixel / inch
* 1 in = 254 mm
* size in mm = pixels * 254 / DPI
*
* @method
* @param {Number} px The amount of pixels to Converts
* @return {Number} The amount of milimeters converted
*/
Display.prototype.px2mm = function(px){
if (!this.screenDPI)
throw new Error('Screen DPI is not defined. Is Display object instantied ?');
return px * 254 / this.screenDPI;
};
/**
* Converts milimeters amount in pixels, in function of current display DPI
*
* Calculus rule
* 1 dpi := pixel / inch
* 1 in = 254 mm
* size in px = mm * DPI / 254
*
* @method
* @param {Number} mm The amount of milimeters to converts
* @return {Number} px The amount of pixels converted
*/
Display.prototype.mm2px = function(mm){
if (!this.screenDPI)
throw new Error('Screen DPI is not defined. Is Display object instantied ?');
return mm * this.screenDPI / 254;
};
module.exports = Display;
|
JavaScript
| 0 |
@@ -457,16 +457,26 @@
property
+ %7BElement%7D
%0A * @pri
|
5bbd318518c908a061cf9b989d84151b6d7bbebf
|
Update message
|
src/client/app/safe.js
|
src/client/app/safe.js
|
/**
* ブラウザの検証
*/
// Detect an old browser
if (!('fetch' in window)) {
alert(
'お使いのブラウザが古いためMisskeyを動作させることができません。' +
'バージョンを最新のものに更新するか、別のブラウザをお試しください。' +
'\n\n' +
'Your browser seems outdated. ' +
'To run Misskey, please update your browser to latest version or try other browsers.');
}
// Detect Edge
if (navigator.userAgent.toLowerCase().indexOf('edge') != -1) {
alert(
'現在、お使いのブラウザ(Microsoft Edge)ではMisskeyは正しく動作しません。' +
'サポートしているブラウザ: Google Chrome, Mozilla Firefox, Apple Safari など' +
'\n\n' +
'Currently, Misskey cannot run correctly on your browser (Microsoft Edge). ' +
'Supported browsers: Google Chrome, Mozilla Firefox, Apple Safari, etc');
}
// Check whether cookie enabled
if (!navigator.cookieEnabled) {
alert(
'Misskeyを利用するにはCookieを有効にしてください。' +
'\n\n' +
'To use Misskey, please enable Cookie.');
}
|
JavaScript
| 0 |
@@ -85,16 +85,23 @@
%E3%81%8A%E4%BD%BF%E3%81%84%E3%81%AE%E3%83%96%E3%83%A9%E3%82%A6%E3%82%B6
+(%E3%81%BE%E3%81%9F%E3%81%AFOS)
%E3%81%8C%E5%8F%A4%E3%81%84%E3%81%9F%E3%82%81Mis
@@ -189,16 +189,29 @@
browser
+ (or your OS)
seems o
|
c1155e89f28c4f4dee7626fb48e4edc646fc7aad
|
Clarify CornerPopup constructor id parameter
|
src/lib/corner-popup.js
|
src/lib/corner-popup.js
|
/* global $:false, _:false */
(function (window, undefined) {
/*
* A popup that displays a message in a window corner.
*
* Always-on-top, yet unobtrusive.
*
* May be shown and hidden.
*
* Parameters:
* - id (string): The id of the corner popup. Used for determining order. (required)
*/
function CornerPopup(id) {
var containerId = 'b83edd14-d692-4775-a488-9bb3d146dc6d';
this.$container = $('#' + containerId);
if (!this.$container.length) {
this.$container = $('<div>', { id: containerId }).css({
'position': 'fixed',
'z-index': 0x7fffffff, // In most browsers: max z-index === max 32-bit signed integer
'top': 0,
'right': 0,
'width': 'auto',
'height': 'auto',
'margin': 0,
'padding': 0,
'border': 'none',
'outline': 'none',
'box-shadow': 'none',
'background-color': 'inherit',
'font-size': '14px',
'line-height': 1,
'text-decoration': 'none',
'vertical-align': 'baseline',
'user-select': 'none',
'pointer-events': 'none',
'border-radius': 0
});
this.$container.appendTo(document.body);
}
this.$popup = $('<div>', { id: id }).css({
'text-align': 'right',
'width': 'auto',
'height': 'auto',
'margin': 0,
'padding': '6px',
'border': 'none',
'outline': 'none',
'box-shadow': 'none',
'color': '#333',
'background-color': 'rgba(255, 255, 255, 0.8)',
'font-family': 'Menlo, Consolas, "Liberation Mono", monospace',
'font-size': 'inherit',
'line-height': 'inherit',
'text-decoration': 'inherit',
'vertical-align': 'inherit',
'user-select': 'inherit',
'pointer-events': 'inherit',
'border-radius': 0
});
this.namespace = containerId + '-' + id;
this.isShowing = false;
}
/*
* Ensure the popup is located at top of window.
*
* Fixed CSS positioning does not always hold, so force the correct absolute
* position if necessary.
*/
CornerPopup.prototype.setToWindowTop = function () {
var popupTop = this.$container.offset().top;
var scrollTop = window.scrollY;
if (popupTop !== scrollTop && scrollTop >= 0) {
this.$container.css({
'position': 'absolute',
'top': scrollTop
});
}
};
/*
* Inserts an element underneath a container element in position maintains
* sorted order of child elements by given attr.
*
* Assumptions:
* - Existing children of container are sorted by attr
*
* Parameters:
* - element: The element to be inserted (required)
* - container: The element under which element will be inserted (required)
* - attr (string): The attribute by which child elements are sorted (default: id)
*/
CornerPopup.prototype.insertSortedByAttr = function (element, container, attr) {
attr = attr || 'id';
var $element = $(element);
var $container = $(container);
var $children = $($container.children());
var childIds = $children.map(function (index, child) {
return(child.id);
});
var index = _.sortedIndex(childIds, $element.attr(attr));
if (!index) {
$element.prependTo($container);
} else {
$element.insertAfter($($children[index - 1]));
}
};
/*
* Display message in popup.
*
* If message is falsy, popup will be hidden.
*
* Parameters:
* - message (string): The message to be displayed (required)
*/
CornerPopup.prototype.show = function (message) {
if (!message) {
this.hide();
}
this.$popup.html(message);
if (!this.isShowing) {
this.isShowing = true;
this.insertSortedByAttr(this.$popup, this.$container);
this.setToWindowTop();
// Ensure that popup stays where it should be when scrolling
var self = this;
$(window).on('scroll.' + this.namespace, function () {
self.setToWindowTop();
});
}
};
/*
* Hide popup
*/
CornerPopup.prototype.hide = function () {
// When hidden, don't listen to scroll events to limit performance impact
$(window).off('scroll.' + this.namespace);
this.$popup.remove();
this.isShowing = false;
};
window.CornerPopup = CornerPopup;
})(this);
|
JavaScript
| 0.000001 |
@@ -242,36 +242,8 @@
ng):
- The id of the corner popup.
Use
@@ -264,14 +264,21 @@
ing
+content
order
-.
(re
@@ -275,32 +275,56 @@
order (required
+ for consistent ordering
)%0A */%0A functi
|
8662e22e5e1bb4420cd1debca41e57a8191fd763
|
Update main.js
|
examples/plain/app/components/scenes/main.js
|
examples/plain/app/components/scenes/main.js
|
import React, { PropTypes } from 'react';
import { View, StyleSheet } from 'react-native';
import { Navigator } from 'react-native-deprecated-custom-components';
import { List } from 'react-native-elements';
import ListItem from '../list_item';
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
justifyContent: 'space-between',
flex: 1,
alignSelf: 'stretch',
},
});
const Main = ({ navigator }) =>
<View style={styles.container}>
<List>
<ListItem
title="Fetch Example"
onPress={navigator.push.bind(null, {id: 'Repos', title: 'Repos'})}
subtitle="Tracking network requests and errors"
accessibilityLabel="Go to crashy page"
leftIcon={{name: 'refresh', type: 'font-awesome'}}
/>
<ListItem
title="Identify User"
onPress={navigator.push.bind(null, {id: 'Register', title: 'Simulate User Registration'})}
subtitle="Simulate user registeration and identification"
accessibilityLabel="Go to crashy page"
leftIcon={{name: 'user', type: 'font-awesome'}}
/>
<ListItem
title="Trigger Exception"
onPress={navigator.push.bind(null, {id: 'Crashy', title: 'Trigger Exception'})}
subtitle="A simple screen that will crash"
accessibilityLabel="Go to crashy page"
leftIcon={{name: 'exclamation-circle', type: 'font-awesome'}}
/>
{ /* Add a button to a non existent route to trigger the manual bugsnag.notify() */ }
<ListItem
title="Broken Route"
onPress={navigator.push.bind(null, {id: 'Bogus', title: 'Bogus'})}
subtitle="This item is broken. This route doesn't exist!"
accessibilityLabel="Go to crashy page"
leftIcon={{name: 'chain-broken', type: 'font-awesome'}}
/>
</List>
</View>
Main.propTypes = {
navigator: PropTypes.instanceOf(Navigator),
};
export default Main;
|
JavaScript
| 0.000001 |
@@ -9,23 +9,8 @@
eact
-, %7B PropTypes %7D
fro
@@ -222,16 +222,52 @@
t_item';
+%0Aimport PropTypes from 'prop-types';
%0A%0Aconst
|
55e914d250ea5d3ff4a9bd3be574deaca2668e11
|
Add http request info req
|
DCBw7M351.js
|
DCBw7M351.js
|
const Discord = require("discord.js");
const client = new Discord.Client();
const http = require("http");
const auth = require("./auth.json");
const jsdom = require("jsdom");
const { JSDOM } = jsdom;
const prefix = "§";
parseargs = (x, delimiter='"') =>
x.split(" ").reduce(
(arr, val) => {
let strEnd = val[val.length-1] === delimiter && val[val.length-2] !== "\\";
if (strEnd) val = val.substring(0, val.length - 1);
return ((arr[arr.length-1] || "")[0] !== delimiter) ? arr.concat([val]) : [arr.pop().substring(strEnd ? 1 : 0) + " " + val, ...(arr.reverse()) ].reverse() },
[] ).map(x => x.replace(new RegExp('\\\\' + delimiter, 'gm'), delimiter).replace(/\\\\/gm, "\\"));
class Command {
constructor (name, func, desc="", syntax="", argdesc={}, argcheck=()=>true, perms=0b0) {
this.name = name;
Command._commands[name] = this;
this.func = func; this.permissions = perms; this.syntax = syntax;
this.description = desc; this.argcheck = argcheck; this.argdesc = argdesc;
}
run(member, args, message) {
if (args[0] === "/?") return this.help(message);
let validation = this.argcheck.apply(args);
if (validation === false) {message.channel.send("Nesprávná syntax"); this.help(message); return false;}
if (!auth_check(member)) return message.channel.send("Nedostatečné oprávnění")
func.call(message.channel, message, args)
}
auth_check(member){
return member.permissions.has(this.permissions);
}
help(message){
return message.channel.send(
this.name + ": " +
this.description + "\n" +
this.name + " " + this.syntax + "\n\n" +
Object.keys(this.argdesc)
.map(k => k.padEnd(10) + this.argdesc[k]).join("\n")
);
}
}
Command._commands = {};
(()=>{
function ping() { this.send("pong!") }
function supl() { this.send("Na hledači suplování se stále tvrdě pracuje.") }
function help(message, [cmdname])
{
if (cmdname === undefined) return this.send("Pro zadání parametrů příkazů obsahující mezery ohraničte parametr uvozovkami: `" + prefix + "role přidat \"Velký okoun\"`\nDostupné příkazy:\n\n" + Object.values(Command._commands).map(cmd => cmd.name.padEnd(10)+cmd.description).join("\n"));
if (Command._commands.hasOwnProperty(cmdname)) Command._commands[cmdname].help(message);
else this.send("Neznámý příkaz. Napište '" + prefix + "help' pro seznam všech příkazů.");
}
function selfrole(message, [action, rolequery]){
let role = Object.entries(this.guild.roles).filter( ([ID, rolename]) => rolename === rolequery );
if (role.length > 1) return this.send("Existuje více rolí s tímto jménem. Prosím obtěžujte administrátory, ať toto nedopatření napraví.");
if (role.length === 0) return this.send(`Role "${rolequery}" neexistuje.`);
[role] = role;
let member = message.member;
let availroles = Object.entries(arguments.callee._roles)
.filter( ([perms, roles]) => perms & member.permissions === perms )
.reduce( ([perms, roles], cur) => cur.concat(roles), [] );
if (availroles.indexOf(role) === -1) return this.send(`Role "${rolequery}" není dostupná.`);
if (action === "přidat") member.addRole(role, "Bot self-assignment");
else member.removeRole(role, "Bot self-unassignment");
return true;
}
selfrole._roles = {
0b0: []
}
new Command("ping", ping, "Pošle zpět odezvu");
new Command("supl", supl, "[WIP] Zobrazí personalizované suplování"
);
new Command("help", help, "Vypíše seznam všech dostupných příkazů, nebo vypíše nápovědu k zadanému příkazu.", "help *příkaz*",
{"*příkaz*": "Jméno příkazu, k němuž se má zobrazit nápověda."});
new Command("role", selfrole, "Umožní uživateli si přidat či odebrat dostupné role / označení.",
"role přidat/odebrat *role*", {"přidat": "Umožní přidání role", "odebrat": "Umožní odebrání role" , "*role*": "Role, která se má uživateli přidat/odebrat"},
(action) => action === "přidat" || action === "odebrat" );
})()
/*const commands = {
"echo": (message, args) => {
var a = [];
for (var i in args) if(i!=0) a.push(args[i]);;
message.channel.send(a.join(" "))
}
}*/
class Reaction{
constructor (check, react){}
}
const reactions = {
/*"zacina noc": "drž hubu!",
"začíná noc": "drž hubu!",
"la nuit commence": "tais toi!",
"the game": "I just lost.",
"klutzy": "Draconequus",
"supl": "Did somepone say supl?",
"knock, knock": "Who's there?"*/
}
client.on("message", message => {
console.log("Message detected: " + message.content);
let prefix = "§";
if(message.content.substring(0, prefix.length) === prefix) {
console.log("Detected command call");
var args = message.content.substring(prefix.length).split(" ");
var cmd = args.shift();
console.log(`Detected "${cmd}" command call`);
args = parseargs(args.join(" "))
console.log("Arguments: " + args.join("+"));
console.log("Command exists: " + Command._commands.hasOwnProperty(cmd));
if(Command._commands.hasOwnProperty(cmd))
Commands._commands[cmd].run(message.member, args, message);
else message.channel.send("Neznámý příkaz, pro seznam příkazů napiš '" + prefix + "help'.");
}
else {
for(var k in reactions) {
if(message.content.toLowerCase().includes(k) && !message.member.roles.some(x=>x.name==="Bot")){
message.reply(reactions[k]);
break;
}
}
}
});
console.log("Bot started");
client.login(auth.token);
|
JavaScript
| 0 |
@@ -133,24 +133,58 @@
uth.json%22);%0A
+const req = require(%22./req.json%22)%0A
const jsdom
|
54a143bb3f61ebd6c46a0f440417e624139b8f89
|
Reset locate strategy for page objects before calling callback
|
lib/page-object/command-wrapper.js
|
lib/page-object/command-wrapper.js
|
module.exports = new (function() {
/**
* Given an element name, returns that element object
*
* @param {Object} parent The parent page or section
* @param {string} elementName Name of element
* @returns {Object} The element object
*/
function getElement(parent, elementName) {
elementName = elementName.substring(1);
if (!(elementName in parent.elements)) {
throw new Error(elementName + ' was not found in "' + parent.name +
'". Available elements: ' + Object.keys(parent.elements));
}
return parent.elements[elementName];
}
/**
* Given a section name, returns that section object
*
* @param {Object} parent The parent page or section
* @param {string} sectionName Name of section
* @returns {Object} The section object
*/
function getSection(parent, sectionName) {
sectionName = sectionName.substring(1);
if (!(sectionName in parent.section)) {
throw new Error(sectionName + ' was not found in "' + parent.name +
'". Available sections: ' + Object.keys(parent.sections));
}
return parent.section[sectionName];
}
/**
* Calls use(Css|Xpath|Recursion) command
*
* Uses `useXpath`, `useCss`, and `useRecursion` commands.
*
* @param {Object} client The Nightwatch instance
* @param {string} desiredStrategy (css selector|xpath|recursion)
* @returns {null}
*/
function setLocateStrategy(client, desiredStrategy) {
var methodMap = {
xpath : 'useXpath',
'css selector' : 'useCss',
recursion : 'useRecursion'
};
if (desiredStrategy in methodMap) {
client.api[methodMap[desiredStrategy]]();
}
}
/**
* Creates a closure that enables calling commands and assertions on the page or section.
* For all element commands and assertions, it fetches element's selector and locate strategy
* For elements nested under sections, it sets 'recursion' as the locate strategy and passes as its first argument to the command an array of its ancestors + self
* If the command or assertion is not on an element, it calls it with the untouched passed arguments
*
* @param {Object} parent The parent page or section
* @param {function} commandFn The actual command function
* @param {string} commandName The name of the command ("click", "containsText", etc)
* @param {Boolean} [isChaiAssertion]
* @returns {parent}
*/
function makeWrappedCommand(parent, commandFn, commandName, isChaiAssertion) {
return function() {
var args = Array.prototype.slice.call(arguments);
var isElementCommand = args[0].toString().indexOf('@') === 0;
var prevLocateStrategy = parent.client.locateStrategy;
if (isElementCommand) {
var firstArg;
var desiredStrategy;
var elementOrSectionName = args.shift();
var getter = (isChaiAssertion && commandName === 'section') ? getSection : getElement;
var elementOrSection = getter(parent, elementOrSectionName);
var ancestors = getAncestorsWithElement(elementOrSection);
if (ancestors.length === 1) {
firstArg = elementOrSection.selector;
desiredStrategy = elementOrSection.locateStrategy;
} else {
firstArg = ancestors;
desiredStrategy = 'recursion';
}
setLocateStrategy(parent.client, desiredStrategy);
args.unshift(firstArg);
}
var c = commandFn.apply(parent.client, args);
if (isElementCommand) {
setLocateStrategy(parent.client, prevLocateStrategy);
}
return (isChaiAssertion ? c : parent);
};
}
/**
* Retrieves an array of ancestors of the supplied element. The last element in the array is the element object itself
*
* @param {Object} element The element
* @returns {Array}
*/
function getAncestorsWithElement(element) {
var elements = [];
function addElement(e) {
elements.unshift(e);
if (e.parent && e.parent.selector) {
addElement(e.parent);
}
}
addElement(element);
return elements;
}
/**
* Adds commands (elements commands, assertions, etc) to the page or section
*
* @param {Object} parent The parent page or section
* @param {Object} target What the command is added to (parent|section or assertion object on parent|section)
* @param {Object} commands
* @returns {null}
*/
function applyCommandsToTarget(parent, target, commands) {
Object.keys(commands).forEach(function(commandName) {
if (isValidAssertion(commandName)) {
target[commandName] = target[commandName] || {};
var isChaiAssertion = commandName === 'expect';
var assertions = commands[commandName];
Object.keys(assertions).forEach(function(assertionName) {
target[commandName][assertionName] = addCommand(target[commandName], assertions[assertionName], assertionName, parent, isChaiAssertion);
});
} else {
target[commandName] = addCommand(target, commands[commandName], commandName, parent, false);
}
});
}
function addCommand(target, commandFn, commandName, parent, isChaiAssertion) {
if (target[commandName]) {
parent.client.results.errors++;
var error = new Error('The command "' + commandName + '" is already defined!');
parent.client.errors.push(error.stack);
throw error;
}
return makeWrappedCommand(parent, commandFn, commandName, isChaiAssertion);
}
function isValidAssertion(commandName) {
return ['assert', 'verify', 'expect'].indexOf(commandName) > -1;
}
/**
* Entrypoint to add commands (elements commands, assertions, etc) to the page or section
*
* @param {Object} parent The parent page or section
* @param {function} commandLoader function that retrieves commands
* @returns {null}
*/
this.addWrappedCommands = function (parent, commandLoader) {
var commands = {};
commands = commandLoader(commands);
applyCommandsToTarget(parent, parent, commands);
};
})();
|
JavaScript
| 0 |
@@ -2746,29 +2746,17 @@
firstArg
-;%0A var
+,
desired
@@ -2755,32 +2755,42 @@
desiredStrategy
+, callback
;%0A var el
@@ -3399,168 +3399,366 @@
g);%0A
-
+%0A
-%7D%0A%0A var c = commandFn.apply(parent.client, args);%0A if (isElementCommand) %7B%0A setLocateStrategy(parent.client, prevLocateStrategy);%0A %7D
+ if (typeof args%5Bargs.length-1%5D === 'function') %7B%0A callback = args.pop();%0A %7D%0A%0A args.push(function() %7B%0A parent.client.locateStrategy = prevLocateStrategy;%0A if (callback) %7B%0A callback.apply(parent.client, arguments);%0A %7D%0A %7D);%0A %7D%0A%0A var c = commandFn.apply(parent.client, args);
%0A
|
af6e466ea8ca6edbbfb2ade8f74b619e9da877d1
|
Fix break on XHR
|
extension/content/firebug/net/netDebugger.js
|
extension/content/firebug/net/netDebugger.js
|
/* See license.txt for terms of usage */
define([
"firebug/lib/object",
"firebug/firebug",
"firebug/lib/domplate",
"firebug/lib/locale",
"firebug/lib/events",
"firebug/lib/url",
"firebug/lib/css",
"firebug/lib/dom",
"firebug/lib/array",
"firebug/net/netUtils",
],
function(Obj, Firebug, Domplate, Locale, Events, Url, Css, Dom, Arr, NetUtils) {
// ********************************************************************************************* //
// Constants
const Cc = Components.classes;
const Ci = Components.interfaces;
const Cr = Components.results;
var panelName = "net";
// ********************************************************************************************* //
// Breakpoints
function NetBreakpointGroup()
{
this.breakpoints = [];
}
NetBreakpointGroup.prototype = Obj.extend(new Firebug.Breakpoint.BreakpointGroup(),
{
name: "netBreakpoints",
title: Locale.$STR("net.label.XHR Breakpoints"),
addBreakpoint: function(href)
{
this.breakpoints.push(new Breakpoint(href));
},
removeBreakpoint: function(href)
{
var bp = this.findBreakpoint(href);
Arr.remove(this.breakpoints, bp);
},
matchBreakpoint: function(bp, args)
{
var href = args[0];
return bp.href == href;
}
});
// ********************************************************************************************* //
function Breakpoint(href)
{
this.href = href;
this.checked = true;
this.condition = "";
this.onEvaluateFails = Obj.bind(this.onEvaluateFails, this);
this.onEvaluateSucceeds = Obj.bind(this.onEvaluateSucceeds, this);
}
Breakpoint.prototype =
{
evaluateCondition: function(context, file)
{
try
{
var scope = {};
var params = file.urlParams;
for (var i=0; params && i<params.length; i++)
{
var param = params[i];
scope[param.name] = param.value;
}
scope["$postBody"] = NetUtils.getPostText(file, context);
// The properties of scope are all strings; we pass them in then
// unpack them using 'with'. The function is called immediately.
var expr = "(function (){var scope = " + JSON.stringify(scope) +
"; with (scope) { return " + this.condition + ";}})();"
// The callbacks will set this if the condition is true or if the eval faults.
delete context.breakingCause;
var rc = Firebug.CommandLine.evaluateInSandbox(expr, context, null, context.window,
this.onEvaluateSucceeds, this.onEvaluateFails );
if (FBTrace.DBG_NET)
FBTrace.sysout("net.evaluateCondition; rc " + rc, {expr: expr,scope: scope,
json: JSON.stringify(scope)});
return !!context.breakingCause;
}
catch (err)
{
if (FBTrace.DBG_NET)
FBTrace.sysout("net.evaluateCondition; EXCEPTION "+err, err);
}
return false;
},
onEvaluateSucceeds: function(result, context)
{
// Don't break if the result is false.
if (!result)
return;
context.breakingCause = {
title: Locale.$STR("net.Break On XHR"),
message: this.condition
};
},
onEvaluateFails: function(result, context)
{
// Break if there is an error when evaluating the condition (to display the error).
context.breakingCause = {
title: Locale.$STR("net.Break On XHR"),
message: "Breakpoint condition evaluation fails ",
prevValue: this.condition,
newValue:result
};
},
}
// ********************************************************************************************* //
// Breakpoint UI
with (Domplate) {
var BreakpointRep = domplate(Firebug.Rep,
{
inspectable: false,
tag:
DIV({"class": "breakpointRow focusRow", _repObject: "$bp",
role: "option", "aria-checked": "$bp.checked"},
DIV({"class": "breakpointBlockHead", onclick: "$onEnable"},
INPUT({"class": "breakpointCheckbox", type: "checkbox",
_checked: "$bp.checked", tabindex : "-1"}),
SPAN({"class": "breakpointName", title: "$bp|getTitle"}, "$bp|getName"),
IMG({"class": "closeButton", src: "blank.gif", onclick: "$onRemove"})
),
DIV({"class": "breakpointCondition"},
SPAN("$bp.condition")
)
),
getTitle: function(bp)
{
return bp.href;
},
getName: function(bp)
{
return Url.getFileName(bp.href);
},
onRemove: function(event)
{
Events.cancelEvent(event);
if (!Css.hasClass(event.target, "closeButton"))
return;
var bpPanel = Firebug.getElementPanel(event.target);
var context = bpPanel.context;
// Remove from list of breakpoints.
var row = Dom.getAncestorByClass(event.target, "breakpointRow");
var bp = row.repObject;
context.netProgress.breakpoints.removeBreakpoint(bp.href);
bpPanel.refresh();
var panel = context.getPanel(panelName, true);
if (!panel)
return;
panel.enumerateRequests(function(file)
{
if (file.getFileURL() == bp.href)
{
file.row.removeAttribute("breakpoint");
file.row.removeAttribute("disabledBreakpoint");
}
})
},
onEnable: function(event)
{
var checkBox = event.target;
if (!Css.hasClass(checkBox, "breakpointCheckbox"))
return;
var bpPanel = Firebug.getElementPanel(event.target);
var context = bpPanel.context;
var bp = Dom.getAncestorByClass(checkBox, "breakpointRow").repObject;
bp.checked = checkBox.checked;
var panel = context.getPanel(panelName, true);
if (!panel)
return;
// xxxsz: Needs a better way to update display of breakpoint than invalidate
// the whole panel's display
// xxxHonza
panel.context.invalidatePanels("breakpoints");
panel.enumerateRequests(function(file)
{
if (file.getFileURL() == bp.href)
file.row.setAttribute("disabledBreakpoint", bp.checked ? "false" : "true");
});
},
supportsObject: function(object, type)
{
return object instanceof Breakpoint;
}
})};
// ********************************************************************************************* //
// Registration
Firebug.registerRep(BreakpointRep);
return {
NetBreakpointGroup: NetBreakpointGroup
};
// ********************************************************************************************* //
});
|
JavaScript
| 0.000001 |
@@ -2565,17 +2565,8 @@
uate
-InSandbox
(exp
|
0c4380b5fc3d45f75e85f5106ad349ea7a595685
|
Fix bundle outside of the bastion directory
|
src/commands/bundle.js
|
src/commands/bundle.js
|
import path from 'path'
import webpack from 'webpack'
import WebpackDevServer from 'webpack-dev-server'
export default function build (entry, bundle, options) {
const entries = {
all: [
'babel-polyfill',
entry
],
development: [
'webpack-dev-server/client?http://localhost:8080/',
'webpack/hot/only-dev-server'
]
}
const plugins = {
default: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
],
development: [
new webpack.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('development')
}
}),
new webpack.HotModuleReplacementPlugin()
]
}
const loaders = {
all: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'babel',
query: {
plugins: [
'transform-runtime'
],
presets: [
'es2015',
'stage-0',
'react'
]
}
}
],
development: [
{
test: /\.js$/,
exclude: /node_modules/,
loader: 'react-hot'
}
]
}
const compiler = webpack({
entry: options.dev ? entries.development.concat(entries.all) : entries.all,
plugins: options.dev ? plugins.development : plugins.default,
devtool: 'source-map',
output: {
path: path.dirname(path.resolve(bundle)),
filename: path.basename(bundle)
},
module: {
loaders: options.dev ? loaders.development.concat(loaders.all) : loaders.all
}
})
if (options.dev) {
const server = new WebpackDevServer(compiler, {
contentBase: options.base || './',
hot: true
})
server.listen(8080)
} else {
compiler.run((err, stats) => {
if (err) {
console.error(err)
process.exit(1)
} else {
console.info(stats.toString({
colors: true,
errorDetails: true
}))
}
})
}
}
|
JavaScript
| 0 |
@@ -96,16 +96,239 @@
-server'
+%0Aimport %7Bmap%7D from 'lodash'%0A%0Aconst localModules = path.resolve(path.join(__dirname, '../../node_modules'))%0A%0Afunction prefixModule (prefix) %7B%0A return (name) =%3E %7B%0A return path.join(localModules, %60$%7Bprefix%7D-$%7Bname%7D%60)%0A %7D%0A%7D
%0A%0Aexport
@@ -378,16 +378,70 @@
ions) %7B%0A
+ const resolvers = %7B%0A fallback: localModules%0A %7D%0A%0A
const
@@ -1273,16 +1273,20 @@
lugins:
+map(
%5B%0A
@@ -1319,24 +1319,55 @@
%5D,
+ prefixModule('babel-plugin')),
%0A p
@@ -1374,16 +1374,20 @@
resets:
+map(
%5B%0A
@@ -1456,16 +1456,47 @@
%5D
+, prefixModule('babel-preset'))
%0A
@@ -2049,21 +2049,75 @@
ers.all%0A
-
%7D
+,%0A resolve: resolvers,%0A resolveLoader: resolvers
%0A %7D)%0A%0A
|
73b59f0de22c6ab8c7317de712c80acf35665cd0
|
change stats to use reduce for consistency
|
src/compile/compile.js
|
src/compile/compile.js
|
'use strict';
var summary = module.exports = require('datalib/src/summary');
var globals = require('../globals');
module.exports = compile;
var Encoding = require('../Encoding'),
axis = compile.axis = require('./axis'),
filter = compile.filter = require('./filter'),
legend = compile.legend = require('./legend'),
marks = compile.marks = require('./marks'),
scale = compile.scale = require('./scale');
compile.aggregate = require('./aggregate');
compile.bin = require('./bin');
compile.facet = require('./facet');
compile.group = require('./group');
compile.layout = require('./layout');
compile.sort = require('./sort');
compile.stack = require('./stack');
compile.style = require('./style');
compile.subfacet = require('./subfacet');
compile.template = require('./template');
compile.time = require('./time');
function compile(spec, stats, theme) {
return compile.encoding(Encoding.fromSpec(spec, theme), stats);
}
compile.shorthand = function (shorthand, stats, config, theme) {
return compile.encoding(Encoding.fromShorthand(shorthand, config, theme), stats);
};
compile.encoding = function (encoding, stats) {
// no need to pass stats if you pass in the data
if (!stats && encoding.hasValues()) {
stats = {};
summary(encoding.data('values')).forEach(function(p) {
stats[p.field] = p;
});
}
var layout = compile.layout(encoding, stats),
style = compile.style(encoding, stats),
spec = compile.template(encoding, layout, stats),
group = spec.marks[0],
mark = marks[encoding.marktype()],
mdefs = marks.def(mark, encoding, layout, style),
mdef = mdefs[0]; // TODO: remove this dirty hack by refactoring the whole flow
filter.addFilters(spec, encoding);
var sorting = compile.sort(spec, encoding, stats);
var hasRow = encoding.has(ROW), hasCol = encoding.has(COL);
for (var i = 0; i < mdefs.length; i++) {
group.marks.push(mdefs[i]);
}
compile.bin(spec.data[1], encoding);
var lineType = marks[encoding.marktype()].line;
spec = compile.time(spec, encoding);
// handle subfacets
var aggResult = compile.aggregate(spec, encoding),
details = aggResult.details,
hasDetails = details && details.length > 0,
stack = hasDetails && compile.stack(spec, encoding, mdef, aggResult.facets);
if (hasDetails && (stack || lineType)) {
//subfacet to group stack / line together in one group
compile.subfacet(group, mdef, details, stack, encoding);
}
// auto-sort line/area values
//TODO(kanitw): have some config to turn off auto-sort for line (for line chart that encodes temporal information)
if (lineType) {
var f = (encoding.isMeasure(X) && encoding.isDimension(Y)) ? Y : X;
if (!mdef.from) mdef.from = {};
// TODO: why - ?
mdef.from.transform = [{type: 'sort', by: '-' + encoding.field(f)}];
}
// Small Multiples
if (hasRow || hasCol) {
spec = compile.facet(group, encoding, layout, style, sorting, spec, mdef, stack, stats);
spec.legends = legend.defs(encoding);
} else {
group.scales = scale.defs(scale.names(mdef.properties.update), encoding, layout, style, sorting,
{stack: stack, stats: stats});
group.axes = axis.defs(axis.names(mdef.properties.update), encoding, layout, stats);
group.legends = legend.defs(encoding);
}
filter.filterLessThanZero(spec, encoding);
return spec;
};
|
JavaScript
| 0 |
@@ -1232,24 +1232,16 @@
stats =
- %7B%7D;%0A
summary
@@ -1270,15 +1270,14 @@
')).
-forEach
+reduce
(fun
@@ -1282,16 +1282,19 @@
unction(
+s,
p) %7B%0A
@@ -1296,20 +1296,16 @@
%7B%0A
-stat
s%5Bp.fiel
@@ -1316,16 +1316,36 @@
p;%0A
+ return s;%0A %7D, %7B
%7D);%0A %7D%0A
|
3af51dafdbf00ba74f1bdabeeed1946edc8ac970
|
Fix MediaSet (#55)
|
src/plugins/MediaSet.js
|
src/plugins/MediaSet.js
|
import Plugin from "./../Plugin";
import Util from "./../Util";
export default class MediaSet extends Plugin {
static get plugin() {
return {
name: "MediaSet",
description: "Media-capable set command",
help: '/mset `trigger`',
needs: {
database: true
}
};
}
start() {
if (!this.db.triggers)
this.db.triggers = {};
if (!this.db.pendingRequests)
this.db.pendingRequests = {};
}
onText(message, reply) {
const text = message.text;
const triggers = this.db.triggers[message.chat.id] || {};
for (let trigger in triggers) {
if (text.indexOf(trigger) === -1) continue;
const re = new RegExp("(?:\\b|^)(" + Util.escapeRegExp(trigger) + ")(?:\\b|$)", "g");
const match = re.exec(text);
if (!match) continue;
const media = triggers[trigger];
this.log.verbose("Match on " + Util.buildPrettyChatName(message.chat));
reply({type: media.type, [media.type]: media.fileId});
}
this.setStepOne(message, reply);
// this.unset(message, reply);
}
onAudio(message, reply) {
this.setStepTwo(message, reply, "audio");
}
onDocument(message, reply) {
this.setStepTwo(message, reply, "document");
}
onPhoto(message, reply) {
this.setStepTwo(message, reply, "photo");
}
onSticker(message, reply) {
this.setStepTwo(message, reply, "sticker");
}
onVideo(message, reply) {
this.setStepTwo(message, reply, "video");
}
onVoice(message, reply) {
this.setStepTwo(message, reply, "voice");
}
setStepOne(message, reply) {
const args = Util.parseCommand(message.text, "mset");
if (!args) return;
if (args.length !== 2) {
reply({
type: "text",
text: "Syntax: /mset `trigger`",
options: {
parse_mode: "Markdown"
}
});
return;
}
this.log.verbose("Triggered stepOne on " + Util.buildPrettyChatName(message.chat));
if (!this.db.pendingRequests[message.chat.id])
this.db.pendingRequests[message.chat.id] = {};
reply({
type: "text",
text: "Perfect! Now send me the media as a reply to this message!"
})
.then(message => {
this.db.pendingRequests[message.chat.id][message.message_id] = args[1];
});
}
setStepTwo(message, reply, mediaType) {
// is this a reply for a "now send media" message?
if (!message.hasOwnProperty('reply_to_message')) return;
// are there pending requests for this chat?
if (!this.db.pendingRequests[message.chat.id]) return;
// foreach request (identified by the "now send media" message id)
for (let request in this.db.pendingRequests[message.chat.id]) {
// if the message is not replying just continue
if (message.reply_to_message.message_id !== request) continue;
const trigger = this.db.pendingRequests[message.chat.id][request];
// do we have triggers for this chat?
if (!this.db.triggers[message.chat.id])
this.db.triggers[message.chat.id] = {};
// build the trigger
var fileId = null;
if (mediaType === "photo")
fileId = message.photo[0].file_id;
else
fileId = message[mediaType].file_id;
this.log.verbose("Added trigger on " + Util.buildPrettyChatName(message.chat));
// set the trigger
this.db.triggers[message.chat.id][trigger] = {
type: mediaType,
fileId: fileId
};
// delete pending request
delete this.db.pendingRequests[message.chat.id][request];
this.synchronize();
reply({type: "text", text: "Done! Enjoy!"});
return;
}
}
/*
unset(message, reply) {
const text = message.text;
const args = Util.parseCommand(text, "munset");
if (!args) return;
if (args.length != 2) {
reply({type: "text", text: "Syntax: /munset trigger"});
return;
}
const key = String(args[1]);
if (this.replacements[ID]) {
this.replacements.splice(ID, 1);
reply({type: "text", text: "Deleted."})
} else {
reply({type: "text", text: "No such expression."})
}
}
*/
}
|
JavaScript
| 0 |
@@ -2335,32 +2335,113 @@
chat.id%5D = %7B%7D;%0A%0A
+ this.db.pendingRequests%5Bmessage.chat.id%5D%5Bmessage.message_id%5D = args%5B1%5D;%0A%0A
reply(%7B%0A
|
46e1779577ff8b498d1a89de0c8a64b24d527250
|
Update DarkmoonDeckPromises.js
|
src/Parser/RestoDruid/Modules/Legendaries/DarkmoonDeckPromises.js
|
src/Parser/RestoDruid/Modules/Legendaries/DarkmoonDeckPromises.js
|
import React from 'react';
import ITEMS from 'common/ITEMS';
import { formatPercentage, formatNumber, formatThousands } from 'common/format';
import DarkmoonDeckPromisesCore from 'Parser/Core/Modules/Items/DarkmoonDeckPromises';
import HealingDone from 'Parser/Core/Modules/HealingDone';
class DarkmoonDeckPromises extends DarkmoonDeckPromisesCore {
static dependencies = {
healingDone: HealingDone,
};
// The actual savings
savings = 0;
on_byPlayer_cast(event) {
super.on_byPlayer_cast(event);
if (event.classResources && event.classResources[0]) {
const resource = event.classResources[0];
const newSavings = this.manaGained;
const manaLeftAfterCast = resource.amount - resource.cost;
const savingsUsed = newSavings - manaLeftAfterCast;
if (savingsUsed > 0) {
this.manaGained = newSavings - savingsUsed;
this.savings = this.savings + savingsUsed;
} else {
this.manaGained = newSavings;
}
}
}
item() {
const rejuvenationManaCost = 22000;
const oneRejuvenationThroughput = this.owner.getPercentageOfTotalHealingDone(this.owner.modules.treeOfLife.totalHealingFromRejuvenationEncounter) / this.owner.modules.treeOfLife.totalRejuvenationsEncounter;
const promisesThroughput = (this.savings / rejuvenationManaCost) * oneRejuvenationThroughput;
return {
item: ITEMS.DARKMOON_DECK_PROMISES,
result: (
<dfn data-tip={`The actual mana gained is ${formatThousands(this.savings + this.manaGained)}. The numbers shown may actually be lower if you did not utilize the promises effect fully, i.e. not needing the extra mana gained.`}>
{formatThousands(this.savings)} mana saved ({formatThousands(this.savings / this.owner.fightDuration * 1000 * 5)} MP5)<br />
{formatPercentage(promisesThroughput)}% / {formatNumber((this.healingDone.total.effective * promisesThroughput) / this.owner.fightDuration * 1000)} HPS
</dfn>
),
};
}
}
export default DarkmoonDeckPromises;
|
JavaScript
| 0 |
@@ -144,16 +144,20 @@
%0Aimport
+Core
Darkmoon
@@ -168,20 +168,16 @@
Promises
-Core
from 'P
@@ -319,16 +319,20 @@
extends
+Core
Darkmoon
@@ -343,20 +343,16 @@
Promises
-Core
%7B%0A sta
@@ -372,16 +372,62 @@
ies = %7B%0A
+ ...CoreDarkmoonDeckPromises.dependencies,%0A
heal
|
8aada85c23142474eb40465408a6a33747469c90
|
add CollectionCursor.toArray()
|
lib/CarbonClient.js
|
lib/CarbonClient.js
|
var RestClient = require('carbon-client')
var util = require('util')
var fibrous = require('fibrous');
/****************************************************************************************************
* monkey patch the endpoint class to support sync get/post/put/delete/head/patch
*/
var Endpoint = RestClient.super_
/****************************************************************************************************
* syncifyClassMethod
*
* @param clazz the class
* @param methodName name of the method to syncify
*/
function syncifyClassMethod(clazz, methodName){
var asyncMethod = clazz.prototype[methodName]
clazz.prototype[methodName] = function() {
// if last argument is a callback then run async
if (arguments && (typeof(arguments[arguments.length-1]) === 'function') ) {
asyncMethod.apply(this, arguments);
} else { // sync call!
return asyncMethod.sync.apply(this, arguments);
}
}
}
// syncify all Endpoint methods
var ENDPOINT_METHODS = [
"get",
"post",
"head",
"put",
"delete",
"patch"
]
ENDPOINT_METHODS.forEach(function(m) { syncifyClassMethod(Endpoint, m) })
// syncify Collection methods
var COLLECTION_METHODS = [
"insert",
"update",
"remove"
]
var Collection = Endpoint.collectionClass
var CollectionCursor = Collection.collectionCursorClass
COLLECTION_METHODS.forEach(function(m) { syncifyClassMethod(Collection, m) })
syncifyClassMethod(CollectionCursor, "next")
/****************************************************************************************************
* exports
*/
module.exports = RestClient
|
JavaScript
| 0 |
@@ -1456,16 +1456,64 @@
%22next%22)
+%0AsyncifyClassMethod(CollectionCursor, %22toArray%22)
%0A%0A/*****
|
1a20a86d505df480804c136433bc7b8e543fd220
|
fix sync issues when panning
|
leaflet-mapbox-gl.js
|
leaflet-mapbox-gl.js
|
L.MapboxGL = L.Class.extend({
initialize: function (options) {
L.setOptions(this, options);
if (options.token) {
mapboxgl.accessToken = options.token;
} else {
throw new Error('You should provide a Mapbox GL access token as a token option.')
}
},
onAdd: function (map) {
this._map = map;
if (!this._glContainer) {
this._initContainer();
}
map._panes.overlayPane.appendChild(this._glContainer);
map.on('zoomanim', this._animateZoom, this);
map.on('move', this._update, this);
this._initGL();
},
onRemove: function (map) {
map.getPanes().overlayPane.removeChild(this._glContainer);
map.off('zoomanim', this._animateZoom, this);
map.off('move', this._update, this);
},
addTo: function (map) {
map.addLayer(this);
return this;
},
_initContainer: function () {
var container = this._glContainer = L.DomUtil.create('div', 'leaflet-gl-layer');
var size = this._map.getSize();
container.style.width = size.x + 'px';
container.style.height = size.y + 'px';
},
_initGL: function () {
var center = this._map.getCenter();
var options = L.extend({}, this.options, {
container: this._glContainer,
interactive: false,
center: [center.lat, center.lng],
zoom: this._map.getZoom() - 1
});
this._glMap = new mapboxgl.Map(options);
},
_update: function () {
var size = this._map.getSize(),
container = this._glContainer,
gl = this._glMap,
topLeft = this._map.containerPointToLayerPoint([0, 0]);
L.DomUtil.setPosition(container, topLeft);
if (gl.transform.width !== size.x || gl.transform.width !== size.y) {
container.style.width = size.x + 'px';
container.style.height = size.y + 'px';
gl.resize();
}
var center = this._map.getCenter();
gl.setView([center.lat, center.lng], this._map.getZoom() - 1, 0);
},
_animateZoom: function (e) {
var origin = e.origin.add(this._map._getMapPanePos()).subtract(map.getSize().divideBy(2));
this._glMap.zoomTo(e.zoom - 1, {
duration: 250,
offset: [origin.x, origin.y],
easing: [0, 0, 0.25, 1]
});
}
});
L.mapboxGL = function (options) {
return new L.MapboxGL(options);
};
|
JavaScript
| 0.000001 |
@@ -1476,16 +1476,55 @@
om() - 1
+,%0A attributionControl: false
%0A
@@ -2113,24 +2113,27 @@
();%0A%0A
+ //
gl.setView(
@@ -2187,16 +2187,271 @@
1, 0);%0A
+ // calling setView directly causes sync issues because it uses requestAnimFrame%0A%0A var tr = gl.transform;%0A tr.center = mapboxgl.LatLng.convert(%5Bcenter.lat, center.lng%5D);%0A tr.zoom = this._map.getZoom() - 1;%0A gl.render();%0A
%7D,%0A%0A
|
61eb5a7ed1e91dfeffec235ad5b0f68ec6865724
|
Maintain the current context `this` context when giving the module its own scope
|
chaingun.js
|
chaingun.js
|
(function() {
function chaingun(obj) {
function _chained_(v) {
function _chain_() { return curr; }
var curr = v;
if (typeof obj == 'function') curr = obj.apply(this, arguments);
return extend(_chain_, obj, function(fn) {
if (typeof fn != 'function') return;
return function() {
Array.prototype.unshift.call(arguments, curr);
curr = fn.apply(this, arguments);
return this;
};
});
}
return extend(_chained_, obj);
}
function extend(target, source, fn) {
var result;
fn = fn || identity;
for (var k in source) {
if (!source.hasOwnProperty(k)) return;
result = fn.call(this, source[k]);
if (typeof result != 'undefined') target[k] = result;
}
return target;
}
function identity(v) { return v; }
if (typeof module != 'undefined')
module.exports = chaingun;
else if (typeof define == 'function' && define.amd)
define(function() { return chaingun; });
else
this.chaingun = chaingun;
})();
|
JavaScript
| 0.001225 |
@@ -1044,12 +1044,21 @@
ngun;%0A%7D)
-(
+.call(this
);%0A
|
71469591951bd0b5785fb16597fda6d008b50901
|
comment cleanup
|
src/components/Form.js
|
src/components/Form.js
|
// dependencies
//
import React from 'react';
import update from 'react-addons-update';
import uniqueId from 'lodash/uniqueId';
import classnames from 'classnames';
import Alert from './Alert';
import Button from './form/Button';
import CheckboxGroup from './form/CheckboxGroup';
import Dropdown from './form/Dropdown';
import RadioButtonGroup from './form/RadioButtonGroup';
import SubmitButton from './form/SubmitButton';
import TextInput from './form/TextInput';
// @TODO added labelColumns, inputColumns to Form
// @TODO changing values of children via props should trigger re-validation
/**
* The Form component
*/
class Form extends React.Component {
/**
* Construct the Form component instance
* @param {Object} props The component properties
*/
constructor(props) {
super(props);
// initialize the state, which consists of the validation messages for
// any children. This is just an empty object now, but as child
// components are mounted, they will "call in" via the
// `onChildValidationEvent` handler, at which time this state will
// become populated with values
//
this.state = {
validation: {},
hasValidated: {},
};
// bind `this` to the `isValid` method
//
this.isValid = this.isValid.bind(this);
// bind `this` to the onChildValidationEvent handler
//
this.onChildValidationEvent = this.onChildValidationEvent.bind(this);
}
/**
* Get the child context values
*
* These values are availabe for use by children of the Form component.
*
* @return {Object} The child context values
*/
getChildContext() {
return {
isValid: this.isValid(),
labelColumns: this.props.labelColumns,
onChildValidationEvent: this.onChildValidationEvent,
};
}
/**
* Handle a validation event from one of the children of this Form
* @param {String} validationKey A unique key identifying the child
* component
* @param {[type]} childHasValidated A flag to indicate whether the
* component has validated in response to
* user input
* @param {String|null} message The validation error message, or null
* if the component is valid
*/
onChildValidationEvent(validationKey, childHasValidated, message) {
// build a change event to update the `validation` and `hasValidated`
// state
//
const validation = {};
validation[validationKey] = { $set: message };
const hasValidated = {};
hasValidated[validationKey] = { $set: !!childHasValidated };
const delta = { validation, hasValidated };
// update the Form component state
//
this.setState((state) => update(state, delta));
}
/**
* Determine if the form is valid
* @return {Boolean} If true, then all form components are valid
*/
isValid() {
// get the list of keys from the validation state
//
const keys = Object.keys(this.state.validation);
// iterate over the list of keys
//
for (let idx = 0; idx < keys.length; idx++) {
// do we have a validation error message for the current item? if
// so, return false, since we have at least one component which has
// failed validation
//
if (this.state.validation[keys[idx]]) {
return false;
}
}
// if we get here, then none of the children have failed validation.
// Return true
//
return true;
}
/**
* Build a list of validation errors for the Form
* @return {Array} An array of validation errors (possibly empty, if all
* components are valid)
*/
validationErrors() {
// declare an array to hold the error messages
//
const errors = [];
// iterate through the keys of the validation state and add non-null
// messages for children which have validated to the array
//
Object.keys(this.state.validation).forEach((key) => {
if (this.state.hasValidated[key] && this.state.validation[key]) {
errors.push(this.state.validation[key]);
}
});
// return the list of error messages
//
return errors;
}
/**
* Render the component
* @return {React.Element} The React element describing the component
*/
render() {
// get the list of validation error messages for the form
//
const errors = this.validationErrors();
// if we have errors, then add an Alert component describing the
// problems
//
const alert = errors.length > 0
? <Alert style="error">
<p>Please correct the following problems:</p>
<ul>
{errors.map((err) => <li key={uniqueId()}>{err}</li>)}
</ul>
</Alert>
: '';
// render the component and return it
//
return (
<div
className={classnames({
'form-inline': this.props.inline,
'form-horizontal': this.props.horizontal,
})}
>
{alert}
{this.props.children}
</div>
);
}
}
// set the property types for the component
//
Form.propTypes = {
inline: React.PropTypes.bool,
horizontal: React.PropTypes.bool,
labelColumns: React.PropTypes.number,
children: React.PropTypes.oneOfType([
React.PropTypes.arrayOf(React.PropTypes.node),
React.PropTypes.node,
]).isRequired,
};
// set the child context types to propagate to the children
//
Form.childContextTypes = {
isValid: React.PropTypes.bool,
onChildValidationEvent: React.PropTypes.func,
labelColumns: React.PropTypes.number,
};
// register the "sub-components" so that they can be imported as part of the
// same package
//
Form.Button = Button;
Form.CheckboxGroup = CheckboxGroup;
Form.Dropdown = Dropdown;
Form.RadioButtonGroup = RadioButtonGroup;
Form.SubmitButton = SubmitButton;
Form.TextInput = TextInput;
// export the component
//
export default Form;
|
JavaScript
| 0 |
@@ -480,42 +480,28 @@
ded
-labelColumns, inputColumns to Form
+configurable columns
%0A//
|
a4da9737508b15d882224452ce2715c60200818c
|
make things always be on one line
|
src/components/List.js
|
src/components/List.js
|
import React, {Component} from 'react';
import styled from 'styled-components';
import icons from '../img/icons';
import {colors, sizes, zIndex} from '../constants';
const Wrapper = styled.div`
width: 100%;
height: 100%;
background-color: ${colors.black};
color: ${colors.white};
z-index: ${zIndex.list};
flex-basis: ${sizes.list.height};
flex-grow: 0;
display: flex;
flex-direction: column;
`;
const Container = styled.div`
overflow: hidden;
display: flex;
flex-direction: ${props => props.direction};
width: 100%;
height: 100%;
`;
const Item = styled.div`
flex-grow: 1;
max-width: 50vw;
display: flex;
flex-direction: column;
&:nth-of-type(even) {
background-color: ${colors.lightGrey};
}
&:nth-of-type(odd) {
background-color: ${colors.darkGrey};
}
`;
const Heading = styled.div`
font-size: .8em;
padding: .4rem;
padding-bottom: 0;
color: ${colors.veryLightGrey};
`;
const Info = styled.div`
padding: 0 .4rem;
flex-grow: 1;
display: flex;
align-items: center;
`;
const Text = styled.span`
margin: 0 .4rem;
font-weight: 700;
`;
const InfoItem = styled.div`
padding: .4rem;
width: ${sizes.list.info.width};
background-color: ${colors.red};
color: ${colors.white};
display: flex;
justify-content: center;
align-items: center;
`;
export default class List extends Component {
renderInbound() {
const {inbound} = this.props.queries;
return inbound.map((query,index) => (
<Item key={index}>
<Heading>{query.destination.name}</Heading>
<Info>
<img src={icons.right} alt='inbound request' style={{width: sizes.icon.width, height: sizes.icon.height}}/>
<Text>{query.origin.name}</Text>
</Info>
</Item>
));
}
renderOutbound() {
const {outbound} = this.props.queries;
return outbound.map((query,index) => (
<Item key={index}>
<Heading>{query.origin.name}</Heading>
<Info>
<img src={icons.right} alt='outbound request' style={{width: sizes.icon.width, height: sizes.icon.height}}/>
<Text>{query.destination.name}</Text>
</Info>
</Item>
));
}
render() {
return (
<Wrapper>
<Container direction="row">
<InfoItem>
<img src={icons.outbound} alt="outbound requests" style={{height: '100%', width: '100%'}}/>
</InfoItem>
{this.renderOutbound()}
</Container>
<Container direction="row-reverse">
<InfoItem>
<img src={icons.inbound} alt="inbound requests" style={{height: '100%', width: '100%'}}/>
</InfoItem>
{this.renderInbound()}
</Container>
</Wrapper>
);
}
}
|
JavaScript
| 0.000022 |
@@ -927,16 +927,39 @@
tGrey%7D;%0A
+ white-space: nowrap;%0A
%60;%0A%0Acons
@@ -1124,16 +1124,39 @@
t: 700;%0A
+ white-space: nowrap;%0A
%60;%0A%0Acons
|
29b56400b00add1ba2b3926f4bdd5b418001d4b5
|
fix the 'null' issue reported by @kiang ... this time for real !
|
src/components/Quiz.js
|
src/components/Quiz.js
|
import React from 'react'
import { Redirect } from 'react-router'
import { HashLink as Link } from 'react-router-hash-link'
import { Progress } from 'semantic-ui-react'
import PropTypes from 'prop-types'
import * as options from '../settings/Option'
import Option from './Option'
const Quiz = ({rawQuizID, quizID, quiz, nextStep, quizIndex, totalStep, answer, onOptionClick}) => {
if (quizID === 'report') {
return (<Redirect to='/report' push />)
}
if (quizID !== rawQuizID) {
return (<Redirect to={`/${quizID}`} push />)
}
const next = quiz.next.length > 0 ? quiz.next : nextStep
let userInput, inputValue
if (quiz.type === 'select') {
const routes = quiz.route.split(';')
userInput = (
<div>
{
Object.keys(options[quiz.option]).map((key, index) => (
<Option
key={`${quizID}-${key}`}
title={options[quiz.option][key]}
link={routes[index] || next}
status={localStorage.getItem(quizID) === key ? 'teal' : ''}
onClick={() => onOptionClick(quizID, key)}
/>
))
}
</div>
)
} else if (quiz.type === 'input') {
userInput = (
<div className='ui action input' key={quizID}>
<input type='text' placeholder={localStorage.getItem(quizID) ? localStorage.getItem(quizID) : 'number...'} onChange={(e) => {inputValue = e.target.value}} />
<Link to={`/${next}`} className='ui icon button' onClick={() => {inputValue = inputValue || localStorage.getItem(quizID); onOptionClick(quizID, inputValue)}}>
<i className='icon check'></i>
</Link>
</div>
)
}
return (
<section className='Quiz'>
<Progress value={quizIndex + 1} total={totalStep} size='tiny' color='teal' />
<div className='ui two column stackable grid'>
<div className='four wide column'>
<p style={{fontSize: '5rem', fontFamily: 'serif', lineHeight: '1', textAlign: 'right', paddingRight: '1rem', borderRight: '4px #ccc solid'}}>Q</p>
</div>
<div className='eight wide column'>
<h2 className='ui header' style={{marginTop: '1rem'}} >
{quiz.title.length > 0 ? quiz.title : quiz.id}
</h2>
<p>
{quiz.description}
</p>
{userInput}
</div>
</div>
<hr className='ui hidden divider' />
</section>
)
}
Quiz.proptypes = {
}
export default Quiz
|
JavaScript
| 0 |
@@ -1163,24 +1163,240 @@
'input') %7B%0A
+ let placeholder = 'number...'%0A if (localStorage.getItem(quizID) && localStorage.getItem(quizID).length %3E 0 && localStorage.getItem(quizID) !== 'null') %7B%0A placeholder = localStorage.getItem(quizID)%0A %7D %0A
userInpu
@@ -1496,81 +1496,19 @@
er=%7B
-localStorage.getItem(quizID) ? localStorage.getItem(quizID) : 'number...'
+placeholder
%7D on
|
7fadc3b70bd3f0ee0f97c766449becb90b7890da
|
Fix transaction confirmations
|
src/js/modules/core/filters/confirmations/confirmations.filter.js
|
src/js/modules/core/filters/confirmations/confirmations.filter.js
|
(function () {
"use strict";
angular.module("blocktrail.core")
.filter("confirmations", confirmations);
function confirmations(walletsManagerService) {
var activeWallet = walletsManagerService.getActiveWallet();
var walletData = activeWallet.getReadOnlyWalletData();
return function(input) {
if (input) {
return (parseInt(walletData.blockHeight) - parseInt(input)) + 1;
} else {
return 0;
}
};
}
})();
|
JavaScript
| 0.000733 |
@@ -163,24 +163,90 @@
rService) %7B%0A
+ return function(input) %7B%0A if (input) %7B%0A
var
@@ -301,16 +301,24 @@
llet();%0A
+
@@ -377,66 +377,8 @@
);%0A%0A
- return function(input) %7B%0A if (input) %7B%0A
|
07f06e00c482da5538ebb4b0210c6c4a626f8f82
|
Remove local state from component
|
src/components/list.js
|
src/components/list.js
|
const React = require('react')
import { connect } from 'react-redux'
import {iteratedList} from "./util"
import Link from "./link"
import * as actions from "../actions"
/* An array of expansions that can be "examined." Accepts an array and
reveals items one-by-one. Arrays may be nested one-level deep; if the current
item is an array, each value will be displayed separated by commas and ending
with "and". When only one item remains, nextUnit is fired (which may be null)
in which case no event is triggered.
Each time an expansion is revealed, onSetExpansions is called and onUpdateInventory
sets the inventory property `key` to the current selected value. */
class _List extends React.Component {
constructor(props) {
super(props)
this.handleChange = this.handleChange.bind(this)
this.state = {
currentExpansion: this.props.currentExpansion,
}
}
componentWillMount() {
this.props.onSetExpansions(this.props.expansions, this.props.tag, this.props.currentExpansion)
}
componentWillReceiveProps(newProps) {
if (newProps.currentExpansion != this.state.currentExpansion) {
this.setState({currentExpansion: newProps.currentExpansion})
}
}
handleChange(e) {
e.preventDefault()
// Move the expansion counter by one unless we're already there
const atLastExpansion = this.state.currentExpansion === this.props.expansions.length - 1
var currentExpansion = !atLastExpansion ? this.state.currentExpansion + 1 : this.state.currentExpansion
this.props.onSetExpansions(this.props.expansions, this.props.tag, currentExpansion)
this.props.onUpdateInventory(e.target.textContent, this.props.tag)
// Are we at the last set? If so, there may be some events to fire
if (!atLastExpansion && currentExpansion === this.props.expansions.length - 1) {
if (this.props.nextUnit === "chapter") {
this.props.onCompleteChapter()
}
else if (this.props.nextUnit === "section") {
this.props.onCompleteSection()
}
// The no-op version just expands in place (usually because another selector)
// will do the expansion
else {
// no-op
}
}
if (this.props.config && this.props.config.hasOwnProperty('identifier')) {
const s = {}
s[this.props.config.identifier] = this.props.counter
history.pushState(s, "", "")
}
this.props.onUpdateCounter()
this.setState({
currentExpansion: currentExpansion
})
}
render () {
let text = this.props.expansions[this.state.currentExpansion]
let handler = this.props.persistLast || this.state.currentExpansion < this.props.expansions.length - 1 ? this.handleChange : null
if (typeof(text) === "string") {
return <Link handler={handler} text={text}/>
}
else {
return iteratedList(text, handler, this.props.conjunction)
}
}
}
_List.propTypes = {
nextUnit: React.PropTypes.oneOf(['chapter', 'section', 'none']),
tag: React.PropTypes.string.isRequired,
expansions: React.PropTypes.array.isRequired,
config: React.PropTypes.object,
currentExpansion: React.PropTypes.number,
conjunction: React.PropTypes.string,
persistLast: React.PropTypes.bool
}
_List.defaultProps = {
nextUnit: 'section',
conjunction: 'and',
persistLast: false
}
const mapStateToProps = (state, ownProps, currentExpansion=0) => {
if (state.expansions.present.hasOwnProperty(ownProps.tag)) {
currentExpansion = state.expansions.present[ownProps.tag].currentExpansion
}
return {
currentExpansion: currentExpansion,
counter: state.counter.present,
config: state.config
}
}
export const List = connect(
mapStateToProps,
{
onSetExpansions: actions.setExpansions,
onUpdateInventory: actions.updateInventory,
onCompleteSection: actions.showNextSection,
onCompleteChapter: actions.showNextChapter,
onUpdateCounter: actions.updateStateCounter
}
)(_List)
export default List
/* Special export for unit tests */
export const TestList = _List
|
JavaScript
| 0.000006 |
@@ -796,400 +796,8 @@
is)%0A
- this.state = %7B%0A currentExpansion: this.props.currentExpansion,%0A %7D%0A %7D%0A componentWillMount() %7B%0A this.props.onSetExpansions(this.props.expansions, this.props.tag, this.props.currentExpansion)%0A %7D%0A componentWillReceiveProps(newProps) %7B%0A if (newProps.currentExpansion != this.state.currentExpansion) %7B%0A this.setState(%7BcurrentExpansion: newProps.currentExpansion%7D)%0A %7D%0A
%7D%0A
@@ -839,16 +839,17 @@
fault()%0A
+%0A
// M
@@ -937,29 +937,29 @@
sion = this.
-state
+props
.currentExpa
@@ -1048,29 +1048,29 @@
sion ? this.
-state
+props
.currentExpa
@@ -1082,29 +1082,29 @@
+ 1 : this.
-state
+props
.currentExpa
@@ -1701,17 +1701,16 @@
selector
-)
%0A /
@@ -1728,24 +1728,25 @@
he expansion
+)
%0A else
@@ -1774,24 +1774,117 @@
%7D%0A %7D%0A
+ // Update the counter in the browser (if check is a workaround to avoid test complaints)%0A
if (this
@@ -2077,104 +2077,81 @@
-this.props.onUpdateCounter()%0A%0A this.setState(%7B%0A currentExpansion: currentExpansion%0A %7D
+// Update the counter in the global store%0A this.props.onUpdateCounter(
)%0A
@@ -2204,29 +2204,29 @@
nsions%5Bthis.
-state
+props
.currentExpa
@@ -2281,21 +2281,21 @@
%7C%7C this.
-state
+props
.current
@@ -3098,24 +3098,109 @@
ops.tag)) %7B%0A
+ if (state.expansions.present%5BownProps.tag%5D.hasOwnProperty('currentExpansion')) %7B%0A
currentE
@@ -3266,16 +3266,22 @@
pansion%0A
+ %7D%0A
%7D%0A re
|
39978aebce29c5a4923b3612d44159b7ff7b577f
|
Fix playing midi
|
src/components/main.js
|
src/components/main.js
|
import angular from 'angular';
import Firebase from 'firebase';
import toMatrix from '../utils/to-matrix';
const template = `
<div>
<div style="position: absolute; left: 10px; top: 500px;">
<md-button class="md-fab" ng-click="main.togglePlay()">
<md-icon>play_arrow</md-icon>
</md-button>
<md-button class="md-fab" ng-click="main.clearNotes()">
<md-icon>clear</md-icon>
</md-button>
<md-button class="md-fab" ng-click="main.setScale('major')">
<p>1</p>
</md-button>
<md-button class="md-fab" ng-click="main.setScale('blues')">
<p>2</p>
</md-button>
</div>
<visualizer style="position: absolute; left: 0; top: 0; height: 500px; width: 500px;"></visualizer>
<grid grid="main.grid" style="position: absolute; left: 500px; top: 0; right: 0; bottom: 10px;"></grid>
</div>
`;
class MainController {
constructor($scope, $window, midi, numRow, numCol, grid, Player) {
this.$scope = $scope;
this.$window = $window;
this.numRow = numRow;
this.numCol = numCol;
this.playing = false;
this.grid = grid;
this.Player = Player;
let colOffset = 0;
midi.addHandler(({rowIndex, velocity, channel}) => {
grid.$add({
channel,
col: colOffset,
row: rowIndex,
velocity
});
colOffset = (colOffset + 1) % numCol;
});
grid.$watch(() => {
$scope.$broadcast('grid-update');
});
let lastTick = -1;
$scope.$on('tick', (e, tick) => {
const colIndex = (time) => Math.floor(time / 125),
i0 = colIndex(lastTick),
i = colIndex(tick);
const matrix = toMatrix(grid, numCol, numRow);
if (i !== i0) {
const enter = [],
exit = [];
if (i === 0) {
const col = matrix[i];
for (let j = 0; j < numRow; ++j) {
if (col[j].mask) {
enter.push(j);
}
}
} else if (i >= numCol) {
const col0 = matrix[i - 1];
for (let j = 0; j < numRow; ++j) {
if (col0[j].mask) {
exit.push(j);
}
}
} else {
const col0 = matrix[i - 1],
col = matrix[i];
for (let j = 0; j < numRow; ++j) {
if (col[j].mask && !col0[j].mask) {
enter.push(j);
}
if (!col[j].mask && col0[j].mask) {
exit.push(j);
}
}
}
if (enter.length > 0) {
$scope.$broadcast('note-on', {
colIndex: i,
notes: enter.map((j) => {
return {
rowIndex: j,
velocity: Math.floor(Math.random() * 128),
channel: matrix[i][j].channel
};
})
});
}
if (exit.length > 0) {
$scope.$broadcast('note-off', {
colIndex: i,
notes: exit.map((j) => {
return {
rowIndex: j,
channel: matrix[i - 1][j].channel
};
})
});
}
}
lastTick = tick;
});
this.addEventListener();
}
addEventListener() {
this.$scope.$on('note-on', (ev, arg) => {
this.Player.noteon(arg.notes);
});
this.$scope.$on('note-off', (ev, arg) => {
this.Player.noteoff(arg.notes);
});
}
togglePlay() {
if (this.playing) {
this.$window.cancelAnimationFrame(this.requestId);
}
this.playing = true;
this.startTime = new Date();
const tick = () => {
const now = new Date(),
delta = now - this.startTime;
if (delta < 125 * this.numCol) {
this.requestId = this.$window.requestAnimationFrame(tick);
} else {
this.playing = false;
}
this.$scope.$broadcast('tick', delta);
};
tick();
}
clearNotes() {
for (let i = this.grid.length; i >= 0; --i) {
this.grid.$remove(i);
}
}
setScale(scale) {
this.Player.setScale(scale);
}
}
const modName = 'app.components.main';
angular.module(modName, [])
.controller('MainController', MainController)
.config(($routeProvider) => {
$routeProvider.when('/', {
template: template,
controller: 'MainController',
controllerAs: 'main',
resolve: {
grid: ($firebaseArray) => {
const ref = new Firebase('https://ngkyoto-wm4.firebaseio.com/unko');
return $firebaseArray(ref).$loaded();
}
}
});
});
export default modName;
|
JavaScript
| 0.000004 |
@@ -1836,27 +1836,29 @@
if (
+!
col%5Bj%5D.
-mask
+empty
) %7B%0A
@@ -2041,24 +2041,25 @@
if (
+!
col0%5Bj%5D.
mask) %7B%0A
@@ -2042,36 +2042,37 @@
if (!col0%5Bj%5D.
-mask
+empty
) %7B%0A
@@ -2262,32 +2262,33 @@
if (
+!
col%5Bj%5D.
-mask
+empty
&&
-!
col0%5Bj%5D.
mask
@@ -2275,36 +2275,37 @@
mpty && col0%5Bj%5D.
-mask
+empty
) %7B%0A
@@ -2355,32 +2355,33 @@
if (
-!
col%5Bj%5D.
-mask
+empty
&&
+!
col0%5Bj%5D.
mask
@@ -2380,12 +2380,13 @@
%5Bj%5D.
-mask
+empty
) %7B%0A
|
bd431af2dcdf95a8de73caf52e9757e92b5c9f01
|
Fix react warning.
|
src/components/page.js
|
src/components/page.js
|
import React from 'react';
export default class Page extends React.Component {
render() {
let {kataGroups} = this.props;
return (
<body>
<h1>ES6 Katas</h1>
<p>Just learn a bit of ES6 daily, take one kata a day and fix it away.</p>
<KataGroups groups={kataGroups} />
<footer>an <a href="http://uxebu.com">uxebu</a> project, using <a href="http://tddbin.com">tddbin</a></footer>
<script src="./index.js" type="application/javascript"></script>
</body>
);
}
}
class KataGroups extends React.Component {
render() {
const {groups} = this.props;
return (
<div>
{groups.map((group) => <KataGroup group={group}/>)}
</div>
);
}
}
class KataGroup extends React.Component {
render() {
const name = this.props.group.name;
const kataLinks = this.props.group.kataLinks;
return (
<div className="group">
<h2>{name}</h2>
{kataLinks.map((link) => <KataLink {...link}/>)}
</div>
);
}
}
class KataLink extends React.Component {
render() {
const {url, text} = this.props;
return <a href={url}>{text}</a>;
}
}
|
JavaScript
| 0 |
@@ -690,16 +690,33 @@
=%7Bgroup%7D
+ key=%7Bgroup.name%7D
/%3E)%7D%0A
@@ -1003,16 +1003,32 @@
...link%7D
+ key=%7Blink.text%7D
/%3E)%7D%0A
|
2e9d3ff76f84df130e15fe886766158b3e35c105
|
Fix bug which prevented package.json opening post initialize
|
lib/actions/init.js
|
lib/actions/init.js
|
'use babel';
import yarnInit from '../yarn/init';
import activeProjectFolder from '../atom/active-project-folder';
import outputViewManager from '../atom/output-view-manager.js';
import path from 'path';
export default function() {
const projectFolder = activeProjectFolder();
if (!projectFolder) {
atom.notifications.addError('Unable to determine active project folder.');
return;
}
const init = yarnInit(projectFolder);
init.on('done', success => {
if (!success) {
outputViewManager.show();
atom.notifications.addError(
`An error occurred whilst initializing. See output for more information.`
);
return;
}
atom.notifications.addSuccess(`Created package.json with default values`);
atom.open(path.join(projectFolder, 'package.json'));
});
init.on('output', outputViewManager.write);
init.on('error', outputViewManager.write);
}
|
JavaScript
| 0.000059 |
@@ -760,16 +760,37 @@
om.open(
+%7B%0A pathsToOpen:
path.joi
@@ -821,16 +821,22 @@
e.json')
+%0A %7D
);%0A %7D);
|
ad68b879138167a29455041a844390fb885a58a4
|
Update announcement structure.
|
lib/announcement.js
|
lib/announcement.js
|
/**
* Announcement module.
* The main purpose of this module is to define a spec for services.
*/
var Announcement = module.exports = function(service) {
this.name = service.name
this.version = service.version
this.baseUrl = service.baseUrl
this.upgradeUrl = service.upgradeUrl
}
/**
* Name of the service
* @type {String}
* @required
*/
Announcement.prototype.name = undefined
/**
* Version of the service
* @type {String}
* @required
*/
Announcement.prototype.version = undefined
/**
* Path of the service package
* @type {String}
* @required
*/
Announcement.prototype.packagePath = undefined
/**
* Name of the framework
* @type {String}
* @optional
*/
Announcement.prototype.framework = undefined
/**
* Base url for web requests include route, upgrade, middleware but not for asset
*
* @type {String}
* @optional
*/
Announcement.prototype.baseUrl = undefined
/**
* Define endpoint which accepts upgrade request (websockets).
*
* @type {String}
* @optional
*/
Announcement.prototype.upgradeUrl = undefined
/**
* The route definition object.
* @type {Object}
* @optional
*/
Announcement.prototype.route = undefined
/**
* The balancer middleware rules.
* @type {Object}
* @optional
*/
Announcement.prototype.use = undefined
/**
* Defines what middleware this service provides.
* @type {Object}
* @optional
*/
Announcement.prototype.middleware = undefined
/**
* The info of client side resources.
* @type {Object}
* @optional
*/
Announcement.prototype.asset = undefined
/**
* The rpc definition object.
* @type {Object}
* @optional
*/
Announcement.prototype.rpc = undefined
|
JavaScript
| 0 |
@@ -215,80 +215,8 @@
ion%0A
- this.baseUrl = service.baseUrl%0A this.upgradeUrl = service.upgradeUrl%0A
%7D%0A%0A/
@@ -437,147 +437,42 @@
%0A *
-Path of the service package%0A * @type %7BString%7D%0A * @required%0A */%0AAnnouncement.prototype.packagePath = undefined%0A%0A/**%0A * Name of the framework
+The info of client side resources.
%0A *
@@ -470,38 +470,38 @@
rces.%0A * @type %7B
-String
+Object
%7D%0A * @optional%0A
@@ -530,17 +530,13 @@
ype.
-framework
+asset
= u
@@ -556,89 +556,31 @@
%0A *
-Base url for web requests include route, upgrade, middleware but not for asset%0A *
+Web related information
%0A *
@@ -578,38 +578,38 @@
ation%0A * @type %7B
-String
+Object
%7D%0A * @optional%0A
@@ -638,99 +638,67 @@
ype.
-baseUrl = undefined%0A%0A/**%0A * Define endpoint which accepts upgrade request (websockets).%0A *%0A
+web = %7B%0A /**%0A * Middleware used on the balancer side.%0A
* @
@@ -699,32 +699,34 @@
* @type %7B
-String%7D%0A
+Object%7D%0A
* @optional
@@ -730,47 +730,20 @@
nal%0A
+
*/%0A
-Announcement.prototype.upgradeUrl =
+ use:
und
@@ -740,38 +740,43 @@
use: undefined
+,
%0A%0A
+
/**%0A
+
* The route def
@@ -783,32 +783,34 @@
inition object.%0A
+
* @type %7BObject
@@ -803,32 +803,34 @@
@type %7BObject%7D%0A
+
* @optional%0A */
@@ -830,42 +830,22 @@
nal%0A
+
*/%0A
-Announcement.prototype.
+
route
- =
+:
und
@@ -854,66 +854,66 @@
ined
+,
%0A%0A
+
/**%0A
-* The balancer middleware rules.%0A * @type %7BObject%7D%0A
+ * Name of the framework%0A * @type %7BString%7D%0A
* @
@@ -925,40 +925,26 @@
nal%0A
+
*/%0A
-Announcement.prototype.use =
+ framework:
und
@@ -949,22 +949,27 @@
ndefined
+,
%0A%0A
+
/**%0A
+
* Defin
@@ -1006,24 +1006,26 @@
e provides.%0A
+
* @type %7BOb
@@ -1022,32 +1022,34 @@
@type %7BObject%7D%0A
+
* @optional%0A */
@@ -1049,35 +1049,16 @@
nal%0A
+
*/%0A
-Announcement.prototype.
+
midd
@@ -1063,18 +1063,17 @@
ddleware
- =
+:
undefin
@@ -1078,70 +1078,109 @@
ined
+,
%0A%0A
+
/**%0A
-* The info of client side resources.%0A * @type %7BObject%7D%0A
+ * Define endpoint which accepts upgrade request (websockets).%0A *%0A * @type %7BString%7D%0A
* @
@@ -1192,42 +1192,27 @@
nal%0A
+
*/%0A
-Announcement.prototype.asset =
+ upgradeUrl:
und
@@ -1209,32 +1209,34 @@
deUrl: undefined
+%0A%7D
%0A%0A/**%0A * The rpc
|
191074a3e897dc39797905f9499cdbfe9518a249
|
Make attributes private
|
lib/beehive/view.js
|
lib/beehive/view.js
|
(function(BeeHive) {
function BeeHiveView(element) {
this.element = element;
var events = {};
function set(attr, value) {
this[attr] = value;
this.trigger(attr + ':change');
return this;
}
this.set = set;
function get(attr) { return this[attr]; }
this.get = get;
function trigger(event_id) {
var callbacks = events[event_id];
for (var i in callbacks) {
var callback = callbacks[i];
callback.apply(this);
}
}
this.trigger = trigger;
function on(event_id, callback) {
var current_callbacks = events[event_id];
if (current_callbacks) {
current_callbacks.push(callback);
}
else {
events[event_id] = [callback];
}
}
this.on = on;
}
BeeHive.View = BeeHiveView;
})(window.BeeHive = window.BeeHive || {});
|
JavaScript
| 0 |
@@ -76,19 +76,16 @@
lement;%0A
- %0A
var
@@ -97,16 +97,42 @@
s = %7B%7D;%0A
+ var attributes = %7B%7D;%0A%0A
func
@@ -161,19 +161,25 @@
%7B%0A
-thi
+attribute
s%5Battr%5D
@@ -270,20 +270,16 @@
= set;%0A
-
%0A fun
@@ -303,19 +303,25 @@
return
-thi
+attribute
s%5Battr%5D;
@@ -343,18 +343,16 @@
= get;%0A
-
%0A fun
|
2be928eea1660c37f73ab7c98d37668e942424ba
|
Fix poll timers
|
lib/channel/poll.js
|
lib/channel/poll.js
|
var ChannelModule = require("./module");
var Poll = require("../poll").Poll;
const TYPE_NEW_POLL = {
title: "string",
timeout: "number,optional",
obscured: "boolean",
opts: "array"
};
const TYPE_VOTE = {
option: "number"
};
function PollModule(channel) {
ChannelModule.apply(this, arguments);
this.poll = null;
if (this.channel.modules.chat) {
this.channel.modules.chat.registerCommand("poll", this.handlePollCmd.bind(this, false));
this.channel.modules.chat.registerCommand("hpoll", this.handlePollCmd.bind(this, true));
}
}
PollModule.prototype = Object.create(ChannelModule.prototype);
PollModule.prototype.load = function (data) {
if ("poll" in data) {
if (data.poll !== null) {
this.poll = new Poll(data.poll.initiator, "", [], data.poll.obscured);
this.poll.title = data.poll.title;
this.poll.options = data.poll.options;
this.poll.counts = data.poll.counts;
this.poll.votes = data.poll.votes;
}
}
};
PollModule.prototype.save = function (data) {
if (this.poll === null) {
data.poll = null;
return;
}
data.poll = {
title: this.poll.title,
initiator: this.poll.initiator,
options: this.poll.options,
counts: this.poll.counts,
votes: this.poll.votes,
obscured: this.poll.obscured
};
};
PollModule.prototype.onUserPostJoin = function (user) {
this.sendPoll([user]);
user.socket.typecheckedOn("newPoll", TYPE_NEW_POLL, this.handleNewPoll.bind(this, user));
user.socket.typecheckedOn("vote", TYPE_VOTE, this.handleVote.bind(this, user));
user.socket.on("closePoll", this.handleClosePoll.bind(this, user));
};
PollModule.prototype.sendPoll = function (users) {
if (!this.poll) {
return;
}
var obscured = this.poll.packUpdate(false);
var unobscured = this.poll.packUpdate(true);
var perms = this.channel.modules.permissions;
users.forEach(function (u) {
u.socket.emit("closePoll");
if (perms.canViewHiddenPoll(u)) {
u.socket.emit("newPoll", unobscured);
} else {
u.socket.emit("newPoll", obscured);
}
});
};
PollModule.prototype.sendPollUpdate = function (users) {
if (!this.poll) {
return;
}
var obscured = this.poll.packUpdate(false);
var unobscured = this.poll.packUpdate(true);
var perms = this.channel.modules.permissions;
users.forEach(function (u) {
if (perms.canViewHiddenPoll(u)) {
u.socket.emit("updatePoll", unobscured);
} else {
u.socket.emit("updatePoll", obscured);
}
});
};
PollModule.prototype.handleNewPoll = function (user, data) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
var title = data.title.substring(0, 255);
var opts = data.opts.map(function (x) { return (""+x).substring(0, 255); });
var obscured = data.obscured;
var poll = new Poll(user.getName(), title, opts, obscured);
var self = this;
if (data.hasOwnProperty("timeout") && !isNaN(data.timeout) && data.timeout > 0) {
poll.timer = setTimeout(function () {
if (self.poll === poll) {
self.handleClosePoll({
getName: function () { return "[poll timer]" },
account: { effectiveRank: 255 }
});
}
}, data.timeout * 1000);
}
this.poll = poll;
this.sendPoll(this.channel.users);
this.channel.logger.log("[poll] " + user.getName() + " opened poll: '" + poll.title + "'");
};
PollModule.prototype.handleVote = function (user, data) {
if (!this.channel.modules.permissions.canVote(user)) {
return;
}
if (this.poll) {
this.poll.vote(user.ip, data.option);
this.sendPollUpdate(this.channel.users);
}
};
PollModule.prototype.handleClosePoll = function (user) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
if (this.poll) {
if (this.poll.obscured) {
this.poll.obscured = false;
this.channel.broadcastAll("updatePoll", this.poll.packUpdate(true));
}
if (this.poll.timer) {
clearTimeout(this.poll.timer);
}
this.channel.broadcastAll("closePoll");
this.channel.logger.log("[poll] " + user.getName() + " closed the active poll");
this.poll = null;
}
};
PollModule.prototype.handlePollCmd = function (obscured, user, msg, meta) {
if (!this.channel.modules.permissions.canControlPoll(user)) {
return;
}
msg = msg.replace(/^\/h?poll/, "");
var args = msg.split(",");
var title = args.shift();
var poll = new Poll(user.getName(), title, args, obscured);
this.poll = poll;
this.sendPoll(this.channel.users);
this.channel.logger.log("[poll] " + user.getName() + " opened poll: '" + poll.title + "'");
};
module.exports = PollModule;
|
JavaScript
| 0.000024 |
@@ -3402,19 +3402,8 @@
- account: %7B
eff
@@ -3417,18 +3417,16 @@
ank: 255
- %7D
%0A
|
cf83a2093089f895295a3a85af081bf56065f260
|
Update file-set docs with more information
|
lib/cli/file-set.js
|
lib/cli/file-set.js
|
/**
* @author Titus Wormer
* @copyright 2015 Titus Wormer
* @license MIT
* @module mdast:cli:file-set
* @fileoverview Collection of virtual files.
*/
'use strict';
/*
* Dependencies.
*/
var ware = require('ware');
var toVFile = require('to-vfile');
var filePipeline = require('./file-pipeline');
/**
* Locked `VFile#move`.
*
* @this {VFile}
* @memberof {VFile}
* @return {VFile} - Context object.
*/
function locked() {
return this;
}
/**
* Utility invoked when a single file has completed it's
* pipeline, invoking `fileSet.done` when all files are
* done.
*
* @example
* var fileSet = new FileSet(cli);
* fileSet.done = function () {console.log('done!');}
*
* fileSet.add(new File())
* fileSet.add(new File())
*
* one(fileSet);
* one(fileSet);
* // 'done!'
*
* @param {FileSet} fileSet - Set in which a file
* completed.
*/
function one(fileSet) {
fileSet.count++;
if (fileSet.count >= fileSet.length && fileSet.done) {
fileSet.done();
fileSet.done = null;
}
}
/**
* Construct a new file-set.
*
* @example
* var fileSet = new FileSet(cli);
*
* @constructor
* @class {FileSet}
* @param {CLI|Object} cli - As returned by `lib/cli/cli`.
*/
function FileSet(cli) {
var self = this;
self.contents = [];
self.sourcePaths = [];
self.cli = cli;
self.length = 0;
self.count = 0;
self.pipeline = ware();
}
/**
* Create an array representation of `fileSet`.
*
* @example
* var fileSet = new FileSet(cli);
* fileSet.valueOf() // []
* fileSet.toJSON() // []
*
* @this {FileSet}
* @return {Array.<File>} - Value at the `contents` property
* in context.
*/
function valueOf() {
return this.contents;
}
/**
* Attach middleware to the pipeline on `fileSet`.
*
* A plug-in (function) can have an `pluginId` property,
* which is used to ignore duplicate attachment.
*
* This pipeline will later be run when when all attached
* files are after the transforming stage.
*
* @example
* var fileSet = new FileSet(cli);
* fileSet.use(console.log);
*
* @this {FileSet}
* @param {Function} plugin - Middleware.
* @return {FileSet} - `this`; context object.
*/
function use(plugin) {
var self = this;
var pipeline = self.pipeline;
var duplicate = false;
if (plugin && plugin.pluginId) {
duplicate = pipeline.fns.some(function (fn) {
return fn.pluginId === plugin.pluginId;
});
}
if (!duplicate && pipeline.fns.indexOf(plugin) !== -1) {
duplicate = true;
}
if (!duplicate) {
pipeline.use(plugin);
}
return this;
}
/**
* Add a file to be processed.
*
* Ignores duplicate files (based on the `filePath` at time
* of addition).
*
* Only runs `file-pipeline` on files which have not
* `failed` before addition.
*
* @example
* var fileSet = new FileSet(cli);
* var fileA = new File({
* 'directory': '~',
* 'filename': 'example',
* 'extension': 'md'
* });
* var fileB = new File({
* 'directory': '~',
* 'filename': 'example',
* 'extension': 'md'
* });
*
* fileSet.add(fileA);
* fileSet.length; // 1
*
* fileSet.add(fileB);
* fileSet.length; // 1
*
* @this {FileSet}
* @param {File|string} file - Virtual file, or path.
* @return {FileSet} - `this`; context object.
*/
function add(file) {
var self = this;
var paths = self.sourcePaths;
var sourcePath;
var context;
if (typeof file === 'string') {
file = toVFile(file);
}
sourcePath = file.filePath();
if (paths.indexOf(sourcePath) !== -1) {
return self;
}
paths.push(sourcePath);
file.sourcePath = sourcePath;
if (!file.namespace('mdast:cli').providedByUser) {
file.move = locked;
}
self.length++;
self.valueOf().push(file);
context = {
'file': file,
'fileSet': self
};
filePipeline.run(context, function (err) {
if (err) {
file.fail(err);
}
one(self);
});
return self;
}
/*
* Expose methods.
*/
FileSet.prototype.valueOf = valueOf;
FileSet.prototype.toJSON = valueOf;
FileSet.prototype.use = use;
FileSet.prototype.add = add;
/*
* Expose.
*/
module.exports = FileSet;
|
JavaScript
| 0 |
@@ -1284,54 +1284,578 @@
-self.contents = %5B%5D;%0A self.sourcePaths = %5B%5D;
+/**%0A * Files in the set.%0A *%0A * @member %7BArray.%3CVFile%3E%7D contents%0A */%0A self.contents = %5B%5D;%0A%0A /**%0A * Number of files in the set.%0A *%0A * @member %7Bnumber%7D length%0A */%0A self.length = 0;%0A%0A /**%0A * Number of processed files.%0A *%0A * @member %7Bnumber%7D count%0A */%0A self.count = 0;%0A%0A /**%0A * File-paths to the original location of files in%0A * the set.%0A *%0A * @member %7BArray.%3Cstring%3E%7D soucePaths%0A */%0A self.sourcePaths = %5B%5D;%0A%0A /**%0A * CLI executing the set.%0A *%0A * @member %7BCLI%7D cli%0A */
%0A
@@ -1875,48 +1875,138 @@
li;%0A
+%0A
-self.length = 0;%0A self.count = 0;
+/**%0A * Pipeline to run when all files in the file-set%0A * are processed.%0A *%0A * @member %7BWare%7D pipeline%0A */
%0A
|
f3b63234bfd37f4fbee9c30b73bf82d2a76414c5
|
Add unsuspend as a helper function in users.
|
lib/client/users.js
|
lib/client/users.js
|
//users.js: Client for the zendesk API.
var util = require('util'),
Client = require('./client').Client,
defaultUser = require('./helpers').defaultUser;
var Users = exports.Users = function (options) {
this.jsonAPIName = 'users';
this.jsonAPIName2 = 'user';
Client.call(this, options);
};
// Inherit from Client base object
util.inherits(Users, Client);
Users.prototype.auth = function (cb) {
this.request('GET', ['users', 'me'], cb);
};
Users.prototype.list = function (cb) {
this.requestAll('GET', ['users'], cb);
};
Users.prototype.listByGroup = function (id, cb) {
this.requestAll('GET', ['groups', id, 'users'], cb);
};
Users.prototype.listByOrganization = function (id, cb) {
this.requestAll('GET', ['organizations', id, 'users'], cb);
};
Users.prototype.show = function (id, cb) {
this.request('GET', ['users', id], cb);
};
Users.prototype.create = function (user, cb) {
this.request('POST', ['users'], user, cb);
};
Users.prototype.createMany = function (users, cb) {
this.request('POST', ['users', 'create_many'], users, cb);
};
Users.prototype.update = function (id, user, cb) {
this.request('PUT', ['users', id], user, cb);
};
Users.prototype.suspend = function (id, cb) {
this.request('PUT', ['users'], {"user": {"suspended": true} }, cb);
};
Users.prototype.delete = function (id, cb) {
this.request('DEL', ['users', id], cb);
};
Users.prototype.search = function (params, cb) {
this.requestAll('GET', ['users', 'search', params], cb);
};
Users.prototype.me = function (cb) {
this.request('GET', ['users', 'me'], cb);
};
|
JavaScript
| 0.000001 |
@@ -1308,32 +1308,154 @@
ue%7D %7D, cb);%0A%7D;%0A%0A
+Users.prototype.unsuspend = function (id, cb) %7B%0A this.request('PUT', %5B'users'%5D, %7B%22user%22: %7B%22suspended%22: false%7D %7D, cb);%0A%7D;%0A
%0AUsers.prototype
|
16abfcbe75dd8c7cc52fa9debf6bed548aa5b9ad
|
Revert "add scrollbar before scroller to not cover it"
|
lib/ace/scrollbar.js
|
lib/ace/scrollbar.js
|
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Ajax.org Code Editor (ACE).
*
* The Initial Developer of the Original Code is
* Ajax.org B.V.
* Portions created by the Initial Developer are Copyright (C) 2010
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Fabian Jakobs <fabian AT ajax DOT org>
* Irakli Gozalishvili <[email protected]> (http://jeditoolkit.com)
*
* Alternatively, the contents of this file may be used under the terms of
* either the GNU General Public License Version 2 or later (the "GPL"), or
* the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the MPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the MPL, the GPL or the LGPL.
*
* ***** END LICENSE BLOCK ***** */
define(function(require, exports, module) {
var oop = require("./lib/oop");
var dom = require("./lib/dom");
var event = require("./lib/event");
var EventEmitter = require("./lib/event_emitter").EventEmitter;
var ScrollBar = function(parent) {
this.element = dom.createElement("div");
this.element.className = "ace_sb";
this.inner = dom.createElement("div");
this.element.appendChild(this.inner);
// in OSX lion the scrollbars appear to have no width. In this case resize
// the to show the scrollbar but still pretend that the scrollbar has a width
// of 0px
// in Firefox 6+ scrollbar is hidden if element has the same width as scrollbar
// make element a little bit wider to retain scrollbar when page is zoomed
// and insert it before other siblings to not cover them
this.width = dom.scrollbarWidth(parent.ownerDocument);
this.element.style.width = (this.width || 15) + 5 + "px";
parent.insertBefore(this.element, parent.firstChild);
event.addListener(this.element, "scroll", this.onScroll.bind(this));
};
(function() {
oop.implement(this, EventEmitter);
this.onScroll = function() {
this._dispatchEvent("scroll", {data: this.element.scrollTop});
};
this.getWidth = function() {
return this.width;
};
this.setHeight = function(height) {
this.element.style.height = height + "px";
};
this.setInnerHeight = function(height) {
this.inner.style.height = height + "px";
};
this.setScrollTop = function(scrollTop) {
this.element.scrollTop = scrollTop;
};
}).call(ScrollBar.prototype);
exports.ScrollBar = ScrollBar;
});
|
JavaScript
| 0 |
@@ -2211,24 +2211,63 @@
is.inner);%0A%0A
+ parent.appendChild(this.element);%0A%0A
// in OS
@@ -2597,69 +2597,8 @@
ed %0A
- // and insert it before other siblings to not cover them%0A
@@ -2719,67 +2719,8 @@
%22;%0A%0A
- parent.insertBefore(this.element, parent.firstChild);%0A%0A
|
9fb714770297af2e74bc217fb3fed71f4fcbb969
|
Fix prefix operator error on react native (#5)
|
lib/amazon-s3-uri.js
|
lib/amazon-s3-uri.js
|
'use strict'
const url = require('url')
const ENDPOINT_PATTERN = /^(.+\.)?s3[.-]([a-z0-9-]+)\./
const DEFAULT_REGION = 'us-east-1'
// TODO: support versionId
// TODO: encode uri before testing
// TODO: support dualstack http://docs.aws.amazon.com/AmazonS3/latest/dev/dual-stack-endpoints.html
/**
* A URI wrapper that can parse out information about an S3 URI
*
* Directly adapted from https://github.com/aws/aws-sdk-java/blob/master/aws-java-sdk-s3/src/main/java/com/amazonaws/services/s3/AmazonS3URI.java
*
* @param {String} uri - the URI to parse
* @throws {TypeError|Error}
*/
function AmazonS3URI (uri) {
if (!new.target) {
return new AmazonS3URI(uri)
}
this.uri = url.parse(uri)
if (this.uri.protocol === 's3:') {
this.region = DEFAULT_REGION
this.isPathStyle = false
this.bucket = this.uri.host
if (!this.bucket) {
throw new Error(`Invalid S3 URI: no bucket: ${uri}`)
}
if (!this.uri.path || this.uri.path.length <= 1) {
// s3://bucket or s3://bucket/
this.key = null
} else {
// s3://bucket/key
// Remove the leading '/'.
this.key = this.uri.path.substring(1)
}
if (this.key !== null) {
this.key = decodeURIComponent(this.key)
}
return
}
if (!this.uri.host) {
throw new Error(`Invalid S3 URI: no hostname: ${uri}`)
}
const matches = this.uri.host.match(ENDPOINT_PATTERN)
if (!matches) {
throw new Error(`Invalid S3 URI: hostname does not appear to be a valid S3 endpoint: ${uri}`)
}
const prefix = matches[1]
if (!prefix) {
// No bucket name in the host; parse it from the path.
this.isPathStyle = true
if (this.uri.path === '/') {
this.bucket = null
this.key = null
} else {
const index = this.uri.path.indexOf('/', 1)
if (index === -1) {
// https://s3.amazonaws.com/bucket
this.bucket = this.uri.path.substring(1)
this.key = null
} else if (index === this.uri.path.length - 1) {
// https://s3.amazonaws.com/bucket/
this.bucket = this.uri.path.substring(1, index)
this.key = null
} else {
// https://s3.amazonaws.com/bucket/key
this.bucket = this.uri.path.substring(1, index);
this.key = this.uri.path.substring(index + 1);
}
}
} else {
// Bucket name was found in the host; path is the key.
this.isPathStyle = false;
// Remove the trailing '.' from the prefix to get the bucket.
this.bucket = prefix.substring(0, prefix.length - 1)
if (!this.uri.path || this.uri.path === '/') {
this.key = null;
} else {
// Remove the leading '/'.
this.key = this.uri.path.substring(1)
}
}
if (matches[2] !== 'amazonaws') {
this.region = matches[2]
} else {
this.region = DEFAULT_REGION
}
if (this.key !== null) {
this.key = decodeURIComponent(this.key)
}
}
AmazonS3URI.prototype.DEFAULT_REGION = DEFAULT_REGION
exports = module.exports = AmazonS3URI
|
JavaScript
| 0 |
@@ -620,17 +620,16 @@
%7B%0A if (
-!
new.targ
@@ -630,16 +630,30 @@
w.target
+ === undefined
) %7B%0A
|
311b85b70ec126d70ce457eb21c7a492076a0b8c
|
Fix error with setting up collections
|
lib/amity-mongodb.js
|
lib/amity-mongodb.js
|
'use strict';
var async = require('async'),
MongoClient = require('mongodb').MongoClient,
feathersMongoDBs = require('feathers-mongo-databases'),
feathersMongoColls = require('feathers-mongo-collections'),
feathersMongo = require('feathers-mongodb'),
mongoURI = require('mongo-uri');
/**
* Amity-MongoDB connects to a MongoDB server and uses several Feathers
* service types to manage either the entire server (multiple databases)
* or a single database.
*
* The modules used are as follows:
* amity-mongodb - This module. In charge of the overall MongoDB server.
* feathers-mongodb-databases - to manage databases on the server
* feathers-mongodb-collections - to manage collections in those databases
* feathers-mongodb - to manage documents in each collection
* feathers-mongodb-users - to manage user permissions
*
* Each instance will manage up to one full server. (It might manage a partial server.)
*
* @param {Object} config - Can be either the hostname of the server or the
* server connection details. The app will
* connect to this MongoDB server with the supplied
* credentials.
* @return {Object} An Adapter to be registered on the Amity app.
*/
module.exports = function(config) {
var amityMongo = {
type:'mongodb',
scope:'server',
uri: '',
db:null,
namespace:'',
connect: function(callback){
var self = this;
// Get a list of the servers.
MongoClient.connect(this.uri, function(err, db) {
if (err) {
console.log(err);
}
console.log('Amity-MongoDB connected to server ' + self.namespace);
// Access to the db after it has been set up.
self.db = db;
var adminDB = db.admin();
// Get a list of databases to register collection managers on.
adminDB.listDatabases(function(err, dbs){
if (err) {
console.error(err);
} else if (dbs.databases){
// Add the db manager to the list of amity_ services.
self.amity_dbManager.push({'name':'_databases', service:feathersMongoDBs(db, 'server')});
// Setup a collection service on each database.
async.each(dbs.databases, setupCollectionService, function(err){
if (err) {
return callback(err);
}
// Get collections for each database.
async.each(dbs.databases, listCollections, function(err){
if (err) {
return callback(err);
}
callback(null, self);
});
});
// We only have access to one database.
} else {
// Add the db manager to the list of amity_ services.
self.amity_dbManager.push({'name':'_databases', service:feathersMongoDBs(db, 'database')});
// Ready a service for managing the collections on the db.
setupCollectionService(db, function(err){
if (err) {
return callback(err);
}
listCollections(db, function(err){
if (err) {
callback(err);
} else {
callback(null, self);
}
});
});
}
});
});
},
getStatus: function(callback){
var adminDB = this.db.admin();
adminDB.serverStatus(function(err, status){
callback(status);
});
},
amity_dbManager:[],
amity_collManager:[],
amity_collections:[],
amity_users:[]
};
var listCollections = function(database, cb){
// If there is a databaseName, we have access to only one db.
var db = database.databaseName ? database : amityMongo.db.db(database.name);
// Get the collections from the database.
db.listCollections().toArray(function(err, collections) {
// Set up a document service for each collection.
async.each(collections, setupDocumentService, function(err){
if (err) {
cb(err);
} else {
cb();
}
});
});
};
// Prepares a service to manage collections on the database.
// This service will be set up by the Amity server.
var setupCollectionService = function(database, callback){
var dbName = database.databaseName || database.name;
var options = {
name:dbName + '/_collections',
service:feathersMongoColls(amityMongo.db.db(dbName))
};
amityMongo.amity_collManager.push(options);
callback();
};
// Prepares a service to manage documents in the provided collection.
// This service will be set up by the Amity server.
var setupDocumentService = function(collection, callback){
// Prep the collection name.
var colName = collection.name.split('.');
var dbName = colName.shift();
colName = colName.join('.');
var database = amityMongo.db.db(dbName);
var options = {
name:dbName + '/' + colName,
service:feathersMongo({collection:database.collection(colName)})
};
amityMongo.amity_collections.push(options);
callback();
};
var createNamespace = function(connectionString){
// Parse the connectionString.
uri = mongoURI.parse(connectionString);
amityMongo.namespace = config.nickname || uri.hosts[0] + ':' + uri.ports[0];
};
// If the config is a string, it's the MongoDB URI
var uri;
if (typeof config === 'string') {
// Put the URI in place for connect().
amityMongo.uri = config;
createNamespace(config);
// Otherwise, if a uri attribute was passed in...
} else if(config.uri) {
// ... put the URI in place for connect().
amityMongo.uri = config.uri;
createNamespace(config.uri);
}
// This deferred must resolve with the fully-connected adapter.
return amityMongo;
};
|
JavaScript
| 0.000001 |
@@ -4433,33 +4433,34 @@
e Amity server.%0A
-%09
+
var setupDocumen
@@ -4803,17 +4803,25 @@
tion(col
-N
+lection.n
ame)%7D)%0A
|
22e3a5329fc718fc97321ad681f3726a5533caf9
|
Update copyright year
|
docs/src/app/Master.js
|
docs/src/app/Master.js
|
import React, {Component} from 'react';
import PropTypes from 'prop-types';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import spacing from 'material-ui/styles/spacing';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {lightWhite, grey900, white} from 'material-ui/styles/colors';
import AppNavDrawer from './AppNavDrawer';
import FullWidthSection from './FullWidthSection';
import withWidth, {MEDIUM, LARGE} from 'material-ui/utils/withWidth';
import NavigationClose from 'material-ui/svg-icons/navigation/menu';
import ForTeachersMenu from './ForTeachersMenu';
import ForStudentsMenu from './ForStudentsMenu';
import ForMakersMenu from './ForMakersMenu';
import DocumentationMenu from './DocumentationMenu';
require('./icon.css');
require('./menu.css');
class Master extends Component {
static propTypes = {
children: PropTypes.node,
location: PropTypes.object,
width: PropTypes.number.isRequired,
};
static contextTypes = {
router: PropTypes.object.isRequired,
};
static childContextTypes = {
muiTheme: PropTypes.object,
};
state = {
navDrawerOpen: false,
};
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
}
componentWillMount() {
this.setState({
muiTheme: getMuiTheme({
palette: {
primary1Color: '#a5cf47',
accent1Color: '#00728a',
}
}),
});
}
componentWillReceiveProps(nextProps, nextContext) {
const newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({
muiTheme: newMuiTheme,
});
}
getStyles() {
const styles = {
appBar: {
position: 'fixed',
// Needed to overlap the examples
zIndex: this.state.muiTheme.zIndex.appBar + 1,
top: 0,
},
root: {
paddingTop: spacing.desktopKeylineIncrement,
minHeight: 400,
},
content: {
margin: spacing.desktopGutter,
},
contentWhenMedium: {
margin: `${spacing.desktopGutter * 2}px ${spacing.desktopGutter * 3}px`,
},
footer: {
backgroundColor: grey900,
color: white,
textAlign: 'center',
maxHeight: 200,
withWidth: 900,
},
a: {
color: white,
},
p: {
margin: '0 auto',
padding: 0,
color: white,
maxWidth: 356,
},
browserstack: {
display: 'flex',
alignItems: 'flex-start',
justifyContent: 'center',
margin: '25px 15px 0',
padding: 0,
color: lightWhite,
lineHeight: '25px',
fontSize: 12,
},
browserstackLogo: {
margin: '0 3px',
},
iconButton: {
color: white,
minWidth: 'auto',
},
iconStyles: {
marginRight: 24,
},
};
if (this.props.width === MEDIUM || this.props.width === LARGE) {
styles.content = Object.assign(styles.content, styles.contentWhenMedium);
}
return styles;
}
handleTouchTapLeftIconButton = () => {
this.setState({
navDrawerOpen: !this.state.navDrawerOpen,
});
};
handleChangeRequestNavDrawer = (open) => {
this.setState({
navDrawerOpen: open,
});
};
handleChangeList = (event, value) => {
this.context.router.push(value);
this.setState({
navDrawerOpen: false,
});
};
handleChangeMuiTheme = (muiTheme) => {
this.setState({
muiTheme: muiTheme,
});
};
render() {
const {
location,
children,
} = this.props;
let {
navDrawerOpen,
} = this.state;
const {
prepareStyles,
} = this.state.muiTheme;
const router = this.context.router;
const styles = this.getStyles();
const title =
router.isActive('/getstarted') ? 'Getting Started' :
router.isActive('/teachers') ? 'For Teachers' :
router.isActive('/students') ? 'For Students' :
router.isActive('/makers') ? 'For Makers' :
router.isActive('/help') ? 'Help' :
router.isActive('/devices') ? 'Devices' :
router.isActive('/bluetoothle') ? 'BluetoothLE' :
router.isActive('/microbit') ? 'Micro Bit' :
router.isActive('/arduino101') ? 'Arduino 101' :
router.isActive('/faq') ? 'FAQ' :
router.isActive('/forum') ? 'Forum' : '';
let docked = false;
let showMenuIconButton = true;
if (this.props.width === LARGE && title !== '') {
docked = true;
navDrawerOpen = true;
showMenuIconButton = false;
styles.navDrawer = {
zIndex: styles.appBar.zIndex - 1,
};
styles.root.paddingLeft = 256;
styles.footer.paddingLeft = 256;
}
// noinspection JSAnnotator
return (
<div>
<AppBar
onLeftIconButtonTouchTap={this.handleTouchTapLeftIconButton}
title={
<div style={styles.title}><a id="home" href="#"><span className="title big-only">Internet of Things</span><span className="title small-only">IoT</span></a>
<div className="nav-container"><nav>
<FlatButton
style={{minWidth: 'auto'}}
labelStyle={styles.iconButton}
href="#/getstarted/intro"
children={<span>Getting Started</span>}
/>
<ForTeachersMenu />
<ForStudentsMenu />
<ForMakersMenu />
<DocumentationMenu />
<FlatButton
style={{minWidth: 'auto'}}
labelStyle={styles.iconButton}
href="#/help/intro"
children={<span>Help</span>}
/>
</nav></div>
</div>
}
zDepth={1}
iconElementLeft={
<IconButton><NavigationClose /></IconButton>
}
iconElementRight={
<a href="http://appinventor.mit.edu" style={prepareStyles(styles.browserstackLogo)} target="_blank">
<span className="aim-icon" />
</a>
}
style={
styles.appBar
}
className="app-bar"
showMenuIconButton={
showMenuIconButton
}
/>
{title !== '' ?
<div style={prepareStyles(styles.root)}>
<div style={prepareStyles(styles.content)}>
{React.cloneElement(children, {
onChangeMuiTheme: this.handleChangeMuiTheme,
})}
</div>
</div> :
children
}
<AppNavDrawer
style={styles.navDrawer}
location={location}
docked={docked}
onRequestChangeNavDrawer={this.handleChangeRequestNavDrawer}
onChangeList={this.handleChangeList}
open={navDrawerOpen}
/>
<FullWidthSection style={styles.footer}>
<a href="https://creativecommons.org/licenses/by/4.0/">
<img alt="Creative Commons License" src="images/4.0_88x31.png" /></a>
<font color="a5cf47">
<br />This work is licensed under a <a href="http://creativecommons.org/licenses/by/4.0/">
<font color="a5cf47">Creative Commons Attribution 4.0 International License</font></a>
<br /> © 2017 <a href="http://web.mit.edu/">
<font color="a5cf47">Massachusetts Institute of Technology</font></a>
<br />
<a href="http://appinventor.mit.edu/explore/contact.html"><font color="a5cf47">Contact Us</font></a>
</font>
</FullWidthSection>
</div>
);
}
}
export default withWidth()(Master);
|
JavaScript
| 0.000001 |
@@ -7518,16 +7518,21 @@
%3E %C2%A9 2017
+-2018
%3Ca href
|
88d0728774210377c6aed122e6a2d0a138c069ae
|
make utils.js lint free
|
lib/config/utils.js
|
lib/config/utils.js
|
// convert structured configuration into a plain object
// by calling the .write() methods of structured classes
// properties ending in _ are considered private
// NB may be less convoluted just to make these explicit
module.exports.extractObj = function extractObj(obj, host) {
var out = {};
for (var p in obj) {
if (!obj.hasOwnProperty(p))
continue;
if (p.substr(0, 2) == '__')
continue;
var val = obj[p];
if (typeof val == 'string')
out[p] = val;
else if (typeof val == 'object') {
if (typeof val.write == 'function')
out[p] = val.write();
else if (val instanceof Array)
out[p] = val;
else
out[p] = extractObj(val, {});
}
}
for (var p in host)
if (!(p in out))
out[p] = host[p];
return out;
};
|
JavaScript
| 0.000001 |
@@ -385,16 +385,17 @@
0, 2) ==
+=
'__')%0A
@@ -454,16 +454,17 @@
f val ==
+=
'string
@@ -512,16 +512,17 @@
f val ==
+=
'object
@@ -555,16 +555,17 @@
write ==
+=
'functi
@@ -717,16 +717,17 @@
%7D%0A %7D%0A
+%0A
for (v
@@ -725,25 +725,25 @@
%0A for (var
-p
+h
in host)%0A
@@ -752,11 +752,37 @@
if (
+host.hasOwnProperty(h) &&
!(
-p
+h
in
@@ -793,25 +793,25 @@
)%0A out%5B
-p
+h
%5D = host%5Bp%5D;
@@ -807,20 +807,21 @@
= host%5B
-p
+h
%5D;%0A
+%0A
return
|
ccd113c26d88d06f9b98adf6c54bba9b2702ce02
|
support node-webkit
|
lib/configurator.js
|
lib/configurator.js
|
const merge = require('deepmerge');
const defaults = require('./config');
const utils = require('./utils');
const loaderDefaults = defaults.loader;
const isomorphicSpriteModule = require.resolve('../runtime/sprite.build');
const isomorphicSymbolModule = require.resolve('svg-baker-runtime/symbol');
const isTargetBrowser = target => target === 'web' || target === 'electron-renderer' || target === 'node-webkit' || target === 'nwjs';
/**
* @param {Object} params
* @param {Object} [params.config] Parsed loader config {@see SVGSpriteLoaderConfig}
* @param {LoaderContext} context Loader context {@see https://webpack.js.org/api/loaders/#the-loader-context}
* @return {Object}
*/
module.exports = function configurator({ config, context, target }) {
const module = context._module;
const compiler = context._compiler;
const compilerName = compiler.name;
const autoConfigured = {
spriteModule: isTargetBrowser(target) ? loaderDefaults.spriteModule : isomorphicSpriteModule,
symbolModule: isTargetBrowser(target) ? loaderDefaults.symbolModule : isomorphicSymbolModule,
extract: utils.isModuleShouldBeExtracted(module),
esModule: context.version && context.version >= 2
};
const finalConfig = merge.all([loaderDefaults, autoConfigured, config || {}]);
/**
* esModule should be `false` when compiles via extract-text-webpack-plugin or html-webpack-plugin.
* Because this compilers executes module as usual node module so export should be always in commonjs style.
* This could be dropped when Node.js will support ES modules natively :)
* @see https://git.io/vS7Sn
* @see https://git.io/v9w60
*/
if (compilerName && (
compilerName.includes('extract-text-webpack-plugin') ||
compilerName.includes('html-webpack-plugin')
)) {
finalConfig.esModule = false;
}
return finalConfig;
};
|
JavaScript
| 0.000001 |
@@ -379,16 +379,17 @@
nderer'
+%0A
%7C%7C targe
|
5e071c3ca583d607bf37794b18f697bc0c882944
|
reset takeScreenshot flag after webdrivercss command finished
|
lib/asyncCallback.js
|
lib/asyncCallback.js
|
/**
* run workflow again or execute callback function
*/
var workflow = require('./workflow.js'),
endSession = require('./endSession.js');
module.exports = function(err,res) {
var that = this;
/**
* if error occured don't do another shot (if multiple screen width are set)
*/
/*istanbul ignore next*/
if(err) {
return this.cb(err);
}
/**
* on multiple screenWidth or multiple page elements
* repeat workflow
*/
if(this.screenWidth && this.screenWidth.length) {
/**
* if multiple screen widths are given
* start workflow all over again with same parameter
*/
this.queuedShots[0].screenWidth = this.screenWidth;
return workflow.call(this.self, this.pagename, this.queuedShots, this.cb);
} else if (this.queuedShots.length > 1) {
/**
* if multiple page modules are given
*/
return endSession.call(this, function() {
that.queuedShots.shift();
return workflow.call(that.self, that.pagename, that.queuedShots, that.cb);
});
}
/**
* finish command
*/
return endSession.call(this, function(err) {
that.cb(err, that.self.resultObject);
that.self.resultObject = {};
});
};
|
JavaScript
| 0 |
@@ -1194,32 +1194,78 @@
function(err) %7B%0A
+ that.self.takeScreenshot = undefined;%0A
that.cb(
|
7f80504f92ad0c43e6514d3c3070d9b56935dadb
|
Increase whitespace on Bios
|
src/containers/Team.js
|
src/containers/Team.js
|
import React from 'react'
import {
ThemeProvider,
Section,
Heading,
Box,
Container,
mediaQueries
} from '@hackclub/design-system'
import { Head, Link } from 'react-static'
import Nav from '../components/Nav'
import Bio from '../components/Bio'
import Footer from '../components/Footer'
const Header = Box.extend`
padding-top: 0 !important;
background-color: ${props => props.theme.colors.blue[5]};
background-image: linear-gradient(
-8deg,
${props => props.theme.colors.indigo[4]} 0%,
${props => props.theme.colors.blue[6]} 50%,
${props => props.theme.colors.blue[7]} 100%
);
`
const Base = Container.extend`
display: grid;
grid-gap: 1rem;
justify-content: center;
${mediaQueries[1]} {
grid-template-columns: repeat(2, 1fr);
}
`
export default () => (
<ThemeProvider>
<Head>
<title>Team – Hack Club</title>
</Head>
<Header pb={[3, 4]}>
<Nav />
<Heading.h2 color="white" align="center" caps mt={3}>
<Box f={4}>Hack Club</Box>
<Box f={6}>Team</Box>
</Heading.h2>
</Header>
<Base py={[4, 5]} px={3}>
<Bio
img="/team/zach.png"
name="Zach Latta"
role="Executive Director"
text="Zach dropped out of high school after his freshman year to work in the technology industry and had over 5 million people using his software by the time he turned 17. He founded Hack Club to build the program he wish he had in high school and has been awarded the Thiel Fellowship and Forbes 30 Under 30 for his work."
bg="red"
/>
<Bio
img="/team/max.jpg"
name="Max Wofford"
role="Operations"
text="Tapping into the hacking community, Max has found a common goal with Hack Club and his passion for amplifying people’s ideas. He loves helping students scale their ideas into even more awesome products."
bg="yellow"
/>
<Bio
img="/team/lachlan.jpg"
name="Lachlan Campbell"
role="Web Designer"
text="Lachlan, a club leader from State College, PA, joined the team to work on Hack Club’s website. They care about bringing coding to more people and making tools to make information more accessible."
bg="blue"
/>
<Bio
img="/team/mingjie.jpg"
name="Mingjie Jiang"
role="Social Media"
text="Mingjie leads a local club at Wootton High School in Rockville, Maryland. Aside from trying to engage more students into the world of hacking, he also cares about building a unique public identity for Hack Club."
bg="orange"
/>
<Bio
img="/team/athul.jpg"
name="Athul Blesson"
role="Indian Region"
text="Athul leads some of our largest clubs in India. After graduating from high school, he joined as our Regional Manager in India. He is passionate about bringing more students into the world of coding."
bg="violet"
/>
<Bio
img="/team/victor.png"
name="Victor Truong"
role="Finance"
text="Victor is a club leader at Rosemead High School in Los Angeles, CA. He aims to make Hack Club’s finances as transparent as possible by letting people know how every penny is being spent."
bg="green"
/>
</Base>
<Footer />
</ThemeProvider>
)
|
JavaScript
| 0.99841 |
@@ -725,16 +725,36 @@
s%5B1%5D%7D %7B%0A
+ grid-gap: 2rem;%0A
grid
|
b441e26baed85f790a9b7a34cfead08e8d16cedf
|
add nodify feature
|
lib/command/watch.js
|
lib/command/watch.js
|
'use strict';
var watch = module.exports = {};
// var node_fs = require('fs');
var node_path = require('path');
var stares = require('stares');
var cortex_json = require('read-cortex-json');
var pf = require('cortex-package-files');
var handler = require('cortex-command-errors');
var expand = require('fs-expand');
var async = require('async');
var ignore = require('ignore');
var glob = require('glob');
// @param {Object} options
// - cwd: {Array.<path>}
watch.run = function(options, callback) {
this._createWatcher(options);
options.stop ?
this.unwatch(options, callback) :
this.watch(options, callback);
};
// Creates a instance of `stares`
watch._createWatcher = function (options) {
if (this.watcher) {
return;
}
var self = this;
this.watcher = stares({
port: self.profile.get('watcher_rpc_port')
// only emitted on master watcher process
})
.on('all', function(event, filepath) {
var dir = node_path.dirname(filepath);
// cortex commander will santitize filepath to the right root directory of the repo
self._rebuild(options, dir);
})
// only emitted on master watcher process
.on('message', function(msg) {
if (~['watch', 'unwatch'].indexOf(msg.task)) {
if (process.pid !== msg.pid) {
self.logger.info('incomming {{cyan ' + msg.task + '}} request from process <' + msg.pid + '>.');
}
}
})
.on('listening', function () {
self.master = true;
})
.on('connect', function () {
if (!self.master) {
self.logger.info('\nBuilding processes will be delegated to the >>{{cyan MASTER}}<< process.\n');
}
});
};
watch.watchFile = function (files, callback) {
var self = this;
this.watcher.watch(files, function(err) {
if (err) {
return callback(err);
}
self.logger.debug('watched', arguments);
callback(null);
});
};
watch.watch = function(options, callback) {
var self = this;
var init_build = options['init-build'];
var profile = self.profile;
var watched = profile.get('watched');
async.each(options.cwd, function(cwd, done) {
if (~watched.indexOf(cwd)) {
self.logger.warn('The current directory has already been watched.');
return done(null);
}
self.logger.info('{{cyan watching}}', cwd, '...');
if (init_build) {
self._rebuild(options, cwd, true);
}
self._get_files(cwd, function(err, files) {
if (err) {
return done(err);
}
self.watchFile(files, done);
});
}, callback);
};
watch._get_files = function(cwd, callback) {
glob('**', {
cwd: cwd,
// include .dot files
dot: true,
// Adds a `/` character to directory matches
mark: true
}, function(err, files) {
if (err) {
return callback(err);
}
var filter = ignore()
// #420
// We only filter a few directories even if user ignores them in .gitignore,
// because most of files will affect the final result of builder.
.addPattern([
'/node_modules',
'/neurons'
])
.createFilter();
var REGEX_ENDS_BACKSLASH = /\/$/;
files = files
// Filter dirs
.filter(function (file) {
return !REGEX_ENDS_BACKSLASH.test(file);
})
.filter(filter);
files = files.map(function (f) {
return node_path.join(cwd, f);
});
callback(null, files);
});
};
watch.unwatch = function(options, callback) {
var self = this;
var profile = self.profile;
async.each(options.cwd, function(cwd, done) {
self._get_files(cwd, function(err, files) {
if (err) {
return done(err);
}
self.watcher.unwatch(files, function(err, msg) {
if (err) {
(err);
}
self.logger.info(cwd, '{{cyan unwatched}}');
self.logger.debug('unwatched', arguments);
done(null);
});
});
}, callback);
};
// There will be only one master process of `cortex watch`,
// so, it is ok to use a global variable of flags.
// Use this trick to prevent endless rebuilding
var locked = {};
watch._lock = function(id) {
locked[id] = true;
};
watch._release = function(id) {
locked[id] = false;
};
watch._is_locked = function(id) {
return locked[id];
};
watch._rebuild = function(options, cwd, init) {
var self = this;
cortex_json.package_root(cwd, function (root) {
if (root === null) {
return self.logger.info('directory "' + cwd + '" is not inside a project.');
}
cwd = root;
// If the current directory is already under building,
// just ignore new tasks
if (self._is_locked(cwd)) {
return;
}
// lock it
self._lock(cwd);
// mock process.argv
var argv = [
'', '',
'build',
// Use --force to prevent grunt task interrupt the current process
'--force',
'--cwd', cwd
];
var prerelease = options.prerelease;
if (prerelease) {
argv.push("--prerelease", prerelease);
}
var commander = self.commander;
var parsed = commander.parse(argv, function(err, result, details) {
if (err) {
// #421
setImmediate(function() {
self._release(cwd);
});
return self.logger.info('{{red|bold ERR!}}', err);
}
var real_cwd = result.options.cwd;
// if `cwd` is the same as `real_cwd`,
// skip checking because we already have checked that
if (real_cwd !== cwd) {
if (self._is_locked(real_cwd)) {
return;
}
// also lock the root directory of a repo
self._lock(real_cwd);
}
if (init) {
self.logger.info('{{cyan build}} the project when begins to watch...');
} else {
self.logger.info('file "' + cwd + '" changed,', '{{cyan rebuild project...}}');
}
// exec cortex.commands.build method
commander.command('build', result.options, function(err) {
setImmediate(function() {
self._release(cwd);
self._release(real_cwd);
});
if (err) {
handler({
logger: self.logger,
harmony: true
})(err);
}
});
});
});
};
|
JavaScript
| 0 |
@@ -6144,16 +6144,42 @@
harmony:
+ true,%0A nodify:
true%0A
|
3a7daa1c038d80138e14ac805befdec535de6647
|
add boop emoji to boop command
|
lib/commands/boop.js
|
lib/commands/boop.js
|
const Clapp = require('../modules/clapp-discord');
const utilties = require('../utlities');
module.exports = new Clapp.Command(
{
name: "boop",
desc: "Boop",
fn: (argv, context) => {
return {
message: {
type: 'message',
message: utilties.getRandomResponse('boop'),
},
context: context,
}
},
}
);
|
JavaScript
| 0.999303 |
@@ -191,16 +191,295 @@
t) =%3E %7B%0A
+ let message = utilties.getRandomResponse('boop');%0A%0A let guildEmoji = context.msg.guild.emojis;%0A let boopEmoji = guildEmoji.find(emoji =%3E emoji.name.toLowerCase() === 'boop');%0A%0A if(boopEmoji) %7B%0A message = boopEmoji.toString() + ' ' + message;%0A %7D%0A%0A
re
@@ -554,42 +554,15 @@
ge:
-utilties.getRandomResponse('boop')
+message
,%0A
|
b32ef4f769057281ff27d9c272974180b45f13ed
|
Fix two issues: No game and fuzzy searcher
|
lib/commands/info.js
|
lib/commands/info.js
|
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
console.log('Building info.js');
const _ = require('lodash');
exports.name = 'info';
exports.exec = async (msg, {send, guild, Discord, member, args}) =>{
let id = member.id;
if(msg.mentions.users.first())
id = msg.mentions.users.first().id;
else if(args[1]){
for(const [i,m] of guild.members)
if(
args[1] === i ||
new RegExp(_.escapeRegExp(m.user.username),'i').test(args[1]) ||
new RegExp(_.escapeRegExp(m.user.tag),'i').test(args[1]) ||
new RegExp(_.escapeRegExp(m.user.displayName),'i').test(args[1])
){
id = i;
break;
}
}
let targetMember = guild.members.get(id);
if(!id||!targetMember) return await send('Please ensure you have specified a valid member');
let targetUser = targetMember.user;
let nick = targetMember.displayName;
let embed = new Discord.RichEmbed;
if (args[0] === "server") {
embed.setColor(targetMember.displayColor||1290103);
embed.setTitle(`${guild.name}`).setDescription(`Created on ${guild.createdAt}`);
embed.addField('Owner ',`${guild.owner}`);
embed.addField('Member Count ', `${guild.memberCount}`);
embed.addField('Location ',`${guild.region}`);
embed.addField('Verification Level ',`${guild.verificationLevel}`);
embed.setThumbnail(`${guild.iconURL}`);
embed.setFooter(`Guild ID:${guild.id}`);
} else if (args[0]==="user") {
embed.setColor(member&&member.displayColor?member.displayColor:1290103);
embed.setTitle(`${targetUser.username}`).setDescription(nick);
embed.addField(`Account Creation`,`${targetUser.createdAt}`);
embed.addField(`Joined ${guild.name}`,`${targetMember.joinedAt}`);
embed.addField(`Highest Role`,`${targetMember.highestRole}`);
embed.addField(`Status`, `${targetUser.presence.status}`);
embed.addField(`Currently Playing`,`${targetUser.presence.game.name}`);
embed.setThumbnail(`${targetUser.displayAvatarURL}`);
} else
return send("I do not recognize that sub-command.");
return await send({embed});
};
|
JavaScript
| 0.999995 |
@@ -224,14 +224,90 @@
args
-%7D) =%3E%7B
+, content%7D) =%3E%7B%0A if(!guild) return send('You must use this command in a server');
%0A l
@@ -455,16 +455,79 @@
members)
+ %7B%0A const q = content.substring(content.indexOf(args%5B1%5D));
%0A i
@@ -584,24 +584,37 @@
scapeRegExp(
+q),'i').test(
m.user.usern
@@ -617,35 +617,16 @@
sername)
-,'i').test(args%5B1%5D)
%7C%7C%0A
@@ -659,18 +659,9 @@
Exp(
-m.user.tag
+q
),'i
@@ -668,23 +668,26 @@
').test(
-args%5B1%5D
+m.user.tag
) %7C%7C%0A
@@ -721,45 +721,34 @@
Exp(
-m.user.displayName),'i').test(args%5B1%5D
+q),'i').test(m.displayName
)%0A
@@ -793,16 +793,22 @@
%7D%0A
+ %7D%0A
%7D%0A le
@@ -2059,18 +2059,74 @@
ence
-.game.name
+&&targetUser.presence.game?targetUser.presence.game.name:'nothing'
%7D%60);
|
bbe65e46fc386db125ac2c6c9b4f13e8192325f0
|
Fix bug with [object] for stale backend
|
src/middleware/proxy.js
|
src/middleware/proxy.js
|
var utils = require('../utils');
var HtmlParserProxy = require('./htmlparser');
var HttpStatus = require('http-status-codes');
var ReliableGet = require('reliable-get');
var url = require('url');
module.exports = function backendProxyMiddleware(config, eventHandler) {
var reliableGet = new ReliableGet(config),
htmlParserMiddleware = HtmlParserProxy.getMiddleware(config, reliableGet, eventHandler);
reliableGet.on('log', eventHandler.logger);
reliableGet.on('stat', eventHandler.stats);
return function(req, res) {
htmlParserMiddleware(req, res, function() {
req.tracer = req.headers['x-tracer'];
var DEFAULT_LOW_TIMEOUT = 5000,
referer = req.headers.referer || 'direct',
userAgent = req.headers['user-agent'] || 'unknown',
remoteAddress = req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress,
remoteIp = req.headers['x-forwarded-for'] || remoteAddress,
backend = req.backend,
targetUrl = backend.target + (backend.dontPassUrl ? '' : req.url),
targetHost = url.parse(backend.target).hostname,
host = backend.host || targetHost,
backendHeaders = {
'x-forwarded-host': req.headers.host,
host: host,
'x-tracer': req.tracer
},
targetCacheKey = utils.urlToCacheKey(targetUrl),
targetCacheTTL = utils.timeToMillis(backend.ttl || '30s'),
options;
if (config.cdn && config.cdn.url) { backendHeaders['x-cdn-url'] = config.cdn.url; }
eventHandler.logger('info', 'GET ' + req.url, {tracer: req.tracer, referer: referer, remoteIp: remoteIp, userAgent: userAgent});
options = {
url: targetUrl,
cacheKey: targetCacheKey,
cacheTTL: targetCacheTTL,
timeout: utils.timeToMillis(backend.timeout || DEFAULT_LOW_TIMEOUT),
headers: backendHeaders,
tracer: req.tracer,
type: 'backend',
statsdKey: 'backend_' + utils.urlToCacheKey(host),
eventHandler: eventHandler
};
var handleError = function(err, oldCacheData) {
if (req.backend.quietFailure && oldCacheData) {
res.parse(oldCacheData);
eventHandler.logger('error', 'Backend FAILED but serving STALE content: ' + err.message, {
tracer: req.tracer
});
} else {
// Check to see if we have any statusCode handlers defined, they come next
if(err.statusCode && config.statusCodeHandlers && config.statusCodeHandlers[err.statusCode]) {
var handlerDefn = config.statusCodeHandlers[err.statusCode];
var handlerFn = config.functions && config.functions[handlerDefn.fn];
if(handlerFn) {
return handlerFn(req, res, req.templateVars, handlerDefn.data, options, err);
}
}
if (!res.headersSent) {
res.writeHead(err.statusCode || HttpStatus.INTERNAL_SERVER_ERROR);
res.end(err.message);
}
eventHandler.logger('error', 'Backend FAILED to respond: ' + err.message, {
tracer: req.tracer
});
}
}
reliableGet.get(options, function(err, response) {
if(err) {
handleError(err, response);
} else {
req.templateVars = utils.updateTemplateVariables(req.templateVars, response.headers);
res.parse(response.content);
}
});
});
}
}
|
JavaScript
| 0 |
@@ -2306,16 +2306,24 @@
acheData
+.content
);%0A
|
a184459311689311bed323e7c818d3a726f93c2d
|
Update logger
|
lib/config/logger.js
|
lib/config/logger.js
|
/*jshint esversion:6, node:true*/
'use strict';
var winston = require('winston');
var config = require('winston/lib/winston/config');
var Message = require('../logger').Message;
/*
* Winston:
* We use the Console and daily rotate file transports
* and if provided, we also use Honeybadger.
*/
var transports = [
new (winston.transports.Console)({
handleExceptions: true,
prettyPrint: true,
silent: false,
level: 'silly',
timestamp: 'hh:mm:ss',
colorize: true,
json: false,
formatter: function(options) {
var message = new Message()
.setColorizer(config.colorize)
.setColors(config.allColors)
// .setColor('error-msg', ['bgRed', 'bold', 'white'])
// .setColor('warn-msg', ['inverse', 'bold'])
.setTime(options.timestamp)
.setLabel(options.label)
.setLevel(options.level)
.setFrom(options.from)
.setMessage(options.message);
if(options.meta){
if(options.meta.loggerName) {
message.setLoggerName(options.meta.loggerName);
}
}
return message.toString();
}
}),
new (winston.transports.File)({
filename: 'debug.log',
// filename: './${app.name}-debug.log',
name: 'file.debug',
level: 'debug',
maxsize: 1024000,
maxFiles: 3,
handleExceptions: true,
json: false
})
];
module.exports = {
transports: transports,
exceptionHandlers: [
new winston.transports.File({
filename: 'exceptions.log',
maxsize: 1024000,
maxFiles: 3,
name: 'file.exceptions',
json: false
})
]
};
/*
* This get's executed after we have solved
* our dependencies and before we return the
* final config object.
*/
module.exports.afterSolver = function(config){
/*
* If we are in production, get rid of the
*/
if(config.get('environment', 'production') === 'production'){
var transports = [];
config.logger.transports.map((tr)=> {
if(tr.name === 'file.debug') return;
transports.push(tr);
});
config.logger.transports = transports;
}
};
|
JavaScript
| 0.000001 |
@@ -1075,16 +1075,17 @@
ns.meta)
+
%7B%0A
|
2d35c7e4db1d6c8807f0a9960bef42aa02858a9e
|
Update octane.js (#996)
|
lib/config/octane.js
|
lib/config/octane.js
|
'use strict';
module.exports = {
rules: {
'deprecated-render-helper': true,
'link-rel-noopener': 'strict',
'link-href-attributes': true,
'no-abstract-roles': true,
'no-action': true,
'no-args-paths': true,
'no-attrs-in-components': true,
'no-curly-component-invocation': {
requireDash: false,
},
'no-debugger': true,
'no-duplicate-attributes': true,
'no-extra-mut-helper-argument': true,
'no-html-comments': true,
'no-implicit-this': true,
'no-inline-styles': true,
'no-input-block': true,
'no-input-tagname': true,
'no-invalid-interactive': true,
'no-log': true,
'no-nested-interactive': true,
'no-obsolete-elements': true,
'no-outlet-outside-routes': true,
'no-partial': true,
'no-positive-tabindex': true,
'no-quoteless-attributes': true,
'no-shadowed-elements': true,
'no-triple-curlies': true,
'no-unbound': true,
'no-unnecessary-component-helper': true,
'no-unused-block-params': true,
'require-iframe-title': true,
'require-valid-alt-text': true,
'simple-unless': true,
'style-concatenation': true,
'table-groups': true,
},
};
|
JavaScript
| 0 |
@@ -614,32 +614,95 @@
ractive': true,%0A
+ 'no-invalid-link-text': true,%0A 'no-invalid-meta': true,%0A
'no-log': tr
|
3867a87c7c1b5def6cfe08a7d4c53583cea4e962
|
Update bound model errorful-set detection to be in line with the query flag->opts change
|
src/model/core/bound.js
|
src/model/core/bound.js
|
/**
* model/core/bound.js
*/
var boundModel = models.bound = baseModel.extend({
/**
* Constructor function to initialize each new model instance.
* @return {[type]}
*/
initialize: function () {
var self = this;
/**
* Queue the autorun of update. We want this to happen after the current JS module
* is loaded but before anything else gets updated. We can't do that with setTimeout
* or _.defer because that could possibly fire after drainQueue.
*/
self.scope = autorun(self.update, self.scopePriority, self,
self.Name && 'model_' + self.Name,
self.onScopeExecute, self, true);
},
scopePriority: BASE_PRIORITY_MODEL_SYNC,
/**
* Wake up this model as well as (recursively) any models that depend on
* it. Any view that is directly or indirectly depended on by the current
* model may now be able to be awoken based on the newly-bound listener to
* this model.
* @param {Object.<string, Boolean>} woken Hash map of model IDs already awoken
*/
wake: function (woken) {
// Wake up this model if it was sleeping
if (this.sleeping) {
this.sleeping = false;
this.reset();
}
/**
* Wake up models that depend directly on this model that have not already
* been woken up.
* XXX - how does this work?
*/
_.each((this.scope && this.scope.lookups) || [], function (lookup) {
var bindable = lookup.obj;
if (bindable && !woken[uniqueId(bindable)]) {
woken[uniqueId(bindable)] = true;
bindable.wake(woken);
}
});
},
onScopeExecute: function (scope) {
if (TBONE_DEBUG) {
log(INFO, this, 'lookups', scope.lookups);
}
},
update: function () {
var self = this;
self.sleeping = self.sleepEnabled && !hasViewListener(self);
if (self.sleeping) {
/**
* This model will not update itself until there's a view listener
* waiting for data (directly or through a chain of other models)
* from this model.
*/
if (TBONE_DEBUG) {
log(INFO, self, 'sleep');
}
} else {
self._update();
}
},
_update: function () {
var opts = this.assumeChanged ? {assumeChanged : true} : {};
this.query(opts, QUERY_SELF, this.state());
if (TBONE_DEBUG) {
log(VERBOSE, this, 'updated', this.attributes);
}
},
/**
* Triggers scope re-execution.
*/
reset: function () {
if (this.scope) {
this.scope.trigger();
}
},
destroy: function () {
if (this.scope) {
this.scope.destroy();
}
this.unset(QUERY_SELF);
},
/**
* returns the new state, synchronously
*/
state: noop,
sleepEnabled: false
});
if (TBONE_DEBUG) {
boundModel.disableSleep = function () {
// This is intended to be used only interactively for development.
if (this.sleepEnabled) {
log(WARN, this, 'disableSleep', 'Disabling sleep mode for <%-Name%>.', this);
this.sleepEnabled = false;
this.wake();
}
};
boundModel.query = function (flag, prop) {
var args = _.toArray(arguments);
if (!this.isMutable) {
// This is a short version of the start of the `query` function, and it would be nice
// to refactor that to incorporate this feature without a duplication of that logic.
var isSet = arguments.length === 3;
if (typeof flag !== 'number') {
prop = flag;
if (arguments.length === 2) {
isSet = true;
}
}
if (isSet) {
prop = (prop || '').replace('__self__', '');
var setProp = isSet ? prop : null;
if (setProp && !prop.match(/^__/)) {
log(WARN, this, 'boundModelSet', 'Attempting to set property <%-prop%> of bound model!', {
prop: setProp
});
}
}
}
return query.apply(this, args);
};
}
|
JavaScript
| 0 |
@@ -3456,20 +3456,20 @@
nction (
-flag
+opts
, prop)
@@ -3812,24 +3812,24 @@
eof
-flag !== 'number
+opts === 'string
') %7B
@@ -3856,12 +3856,12 @@
p =
-flag
+opts
;%0A
|
58e81b68077d576573baf344f626a8b5fa0c687c
|
Set load metadata by default in HTML5 videos
|
js/VISH.Renderer.js
|
js/VISH.Renderer.js
|
VISH.Renderer = (function(V,$,undefined){
var SLIDE_CONTAINER = null;
/**
* Function to initialize the renderer
* Only gets the section element from the html page
*/
var init = function(){
SLIDE_CONTAINER = $('.slides');
}
/**
* slides.html only have a section element and in this function we add an article element
* with the proper content for the slide
*/
var renderSlide = function(slide){
var content = "";
var classes = "";
for(el in slide.elements){
if(slide.elements[el].type === "text"){
content += _renderText(slide.elements[el],slide.template);
}
else if(slide.elements[el].type === "image"){
content += _renderImage(slide.elements[el],slide.template);
}
else if(slide.elements[el].type === "video"){
content += _renderVideo(slide.elements[el],slide.template);
}
else if(slide.elements[el].type === "swf"){
content += _renderSwf(slide.elements[el],slide.template);
classes += "swf ";
}
else if(slide.elements[el].type === "applet"){
content += _renderApplet(slide.elements[el],slide.template);
classes += "applet ";
}
else if(slide.elements[el].type === "flashcard"){
content = _renderFlashcard(slide.elements[el],slide.template);
classes += "flashcard";
}
else if(slide.elements[el].type === "openquestion"){
content = _renderOpenquestion(slide.elements[el],slide.template);
}
else if(slide.elements[el].type === "mcquestion"){
content = _renderMcquestion(slide.elements[el],slide.template);
}
}
SLIDE_CONTAINER.append("<article class='"+classes+"' id='"+slide.id+"'>"+content+"</article>");
};
/**
* Function to render text inside an article (a slide)
*/
var _renderText = function(element, template){
return "<div id='"+element['id']+"' class='"+template+"_"+element['areaid']+" "+template+"_text"+"'>"+element['body']+"</div>";
};
/**
* Function to render an image inside an article (a slide)
*/
var _renderImage = function(element, template){
return "<div id='"+element['id']+"' class='"+template+"_"+element['areaid']+"'><img class='"+template+"_image' src='"+element['body']+"' style='"+element['style']+"' /></div>";
};
/**
* Function to render a video inside an article (a slide)
*/
var _renderVideo = function(element, template){
var rendered = "<div id='"+element['id']+"' class='"+template+"_"+element['areaid']+"'>"
var controls=(element['controls'])?"controls='controls' ":""
var autoplay=(element['autoplay'])?"autoplayonslideenter='true' ":""
var poster=(element['poster'])?"poster='" + element['poster'] + "' ":""
var loop=(element['loop'])?"loop='loop' ":""
var sources = JSON.parse(element['sources'])
rendered = rendered + "<video class='" + template + "_video' preload='none' " + controls + autoplay + poster + loop + ">"
$.each(sources, function(index, value) {
rendered = rendered + "<source src='" + value.src + "' type='" + value.mimetype + "'>"
});
if(sources.length>0){
rendered = rendered + "<p>Your browser does not support HTML5 video.</p>"
}
rendered = rendered + "</video>"
return rendered
};
/**
* Function to render a flash object inside an article (a slide)
* the flash object is not really inside the article but in the src attribute of the div
* when entering a slide with a swf class we call V.SWFPlayer.loadSWF (see VISH.SlideManager._onslideenter) and it will add the src inside the div
*/
var _renderSwf = function(element, template){
return "<div id='"+element['id']+"' class='swfelement "+template+"_"+element['areaid']+"' templateclass='"+template+"_swf"+"' src='"+element['body']+"'></div>";
};
/**
* Function to render an applet inside an article (a slide)
* the applet object and its params are not really inside the article but in the archive attribute, width, height and params of the div
* when entering a slide with an applet class we call V.AppletPlayer.loadSWF (see VISH.SlideManager._onslideenter) and it will add the params inside the div
*/
var _renderApplet = function(element, template){
return "<div id='"+element['id']+"' class='appletelement "+template+"_"+element['areaid']+"' code='"+element['code']+"' width='"+element['width']+"' height='"+element['height']+"' archive='"+element['archive']+"' params='"+element['params']+"' ></div>";
};
/**
* Function to render a flashcard inside an article (a slide)
* we only add canvas inside the div element
* the flashcard will be drawn inside the canvas element
*/
var _renderFlashcard = function(element, template){
return "<div id='"+element['id']+"' class='template_flashcard'><canvas id='"+element['canvasid']+"'>Your browser does not support canvas</canvas></div>";
};
/**
* Function to render an open question form inside an article (a slide)
*/
var _renderOpenquestion = function(element, template){
var ret = "<div id='"+element['id']+"' class='question_title'>"+element['body']+"</div>";
ret += "<form action='"+element['posturl']+"' method='post'>";
ret += "<label class='question_name'>Name: </label>";
ret += "<input id='pupil_name' class='question_name_input'></input>";
ret += "<label class='question_answer'>Answer: </label>";
ret += "<textarea class='question_answer_input'></textarea>";
ret += "<button type='button' class='question_button'>Send</button>";
return ret;
};
/**
* Function to render a multiple choice question form inside an article (a slide)
*/
var _renderMcquestion = function(element, template){
var ret = "<div id='"+element['id']+"' class='question_title'>"+element['body']+"</div>";
ret += "<form action='"+element['posturl']+"' method='post'>";
ret += "<label class='question_name'>Name: </label>";
ret += "<input id='pupil_name' class='question_name_input'></input>";
for(var i = 0; i<element['options'].length; i++){
ret += "<label class='mc_answer'><input type='radio' name='mc_radio' value='0'>"+element['options'][i]+"</label>";
}
ret += "<button type='button' class='question_button'>Send</button>";
return ret;
};
return {
init : init,
renderSlide : renderSlide
};
}) (VISH,jQuery);
|
JavaScript
| 0 |
@@ -2857,12 +2857,16 @@
ad='
-none
+metadata
' %22
|
7dec26d8b373f4ffbcef7392b724d781a63a9d9a
|
set toolbar icon title to productName + version
|
desktop/electron-app.js
|
desktop/electron-app.js
|
/* teamcity-tray-notifier main process */
const electron = require('electron');
const {app} = electron;
const {BrowserWindow} = electron;
const ipc = electron.ipcMain;
const path = require('path');
const clipboard = require('electron').clipboard;
let notificationsWin;
let loginWin;
let appIcon = null;
let pkg = require('./package');
let productNameVersion = pkg.productName + ' v' + pkg.version;
function putInTray() {
const iconPath = path.join(__dirname,'icon.png');
appIcon = new electron.Tray(iconPath);
const contextMenu = electron.Menu.buildFromTemplate([
{
label: productNameVersion,
click: function () {
clipboard.writeText(productNameVersion);
}
},
{
type: 'separator'
},
{
label: 'Login...',
click: function () {
createLoginWindow();
}
},
{
type: 'separator'
},
{
label: 'Send test notification',
click: function () {
notificationsWin.webContents.send('test-notification');
}
},
{
type: 'separator'
},
{
label: 'Quit',
click: function () {
app.quit();
}
}
]);
appIcon.setToolTip('teamcity-tray-notifier');
appIcon.setContextMenu(contextMenu);
}
ipc.on('put-in-tray', putInTray);
ipc.on('remove-tray', () => {
appIcon.destroy();
});
function createNotificationsWindow() {
notificationsWin = new BrowserWindow({
width: 100,
height: 100,
show: false
});
notificationsWin.loadURL(`file://${__dirname}/notifications/test.html`);
notificationsWin.on('closed', () => {
notificationsWin = null;
});
}
function createLoginWindow() {
loginWin = new BrowserWindow({
width: 450,
height: 430
});
loginWin.loadURL('http://unit-631:8111/bs/win32/userStatus.html');
// loginWin.loadURL('http://unit-631:8111/bs/win32/login.html');
loginWin.on('closed', () => {
loginWin = null;
});
}
app.on('ready', function() {
createNotificationsWindow();
putInTray();
});
app.dock && app.dock.hide();
|
JavaScript
| 0.000001 |
@@ -1367,32 +1367,26 @@
Tip(
-'teamcity-tray-notifier'
+productNameVersion
);%0A
|
b085c66bfeef195829790a7251e84828aa0f442a
|
Use our new method in remote-require
|
src/renderer-require.js
|
src/renderer-require.js
|
import path from 'path';
import {AsyncSubject, Observable, Subject} from 'rx';
import {createProxyForRemote, executeJavaScriptMethod, executeJavaScriptMethodObservable, RecursiveProxyHandler} from './execute-js-func';
import './custom-operators';
const d = require('debug-electron')('electron-remote:renderer-require');
const BrowserWindow = process.type === 'renderer' ?
require('electron').remote.BrowserWindow :
require('electron').BrowserWindow;
/**
* Creates a BrowserWindow, requires a module in it, then returns a Proxy
* object that will call into it. You probably want to use {requireTaskPool}
* instead.
*
* @param {string} modulePath The path of the module to include.
*
* @return {Object} Returns an Object with a `module` which is a Proxy
* object, and a `dispose` method that will clean up
* the window.
*/
export async function rendererRequireDirect(modulePath) {
let bw = new BrowserWindow({width: 500, height: 500, show: false});
let fullPath = require.resolve(modulePath);
let ready = new Promise((res,rej) => {
bw.webContents.once('did-finish-load', () => res(true));
bw.webContents.once('did-fail-load', (ev, errCode, errMsg) => rej(new Error(errMsg)));
});
/* Uncomment for debugging!
bw.show();
bw.openDevTools();
*/
let preloadFile = path.join(__dirname, 'renderer-require-preload.html');
bw.loadURL(`file:///${preloadFile}?module=${encodeURIComponent(fullPath)}`);
await ready;
let fail = await executeJavaScriptMethod(bw, 'window.moduleLoadFailure');
if (fail) {
let msg = await executeJavaScriptMethod(bw, 'window.moduleLoadFailure.message');
throw new Error(msg);
}
return {
module: createProxyForRemote(bw).requiredModule,
executeJavaScriptMethod: (chain, ...args) => executeJavaScriptMethod(bw, chain, ...args),
executeJavaScriptMethodObservable: (chain, ...args) => executeJavaScriptMethodObservable(bw, 240*1000, chain, ...args),
dispose: () => bw.close()
};
}
/**
* requires a module in BrowserWindows that are created/destroyed as-needed, and
* returns a Proxy object that will secretly marshal invocations to other processes
* and marshal back the result. This is the cool method in this library.
*
* Note that since the global context is created / destroyed, you *cannot* rely
* on module state (i.e. global variables) to be consistent
*
* @param {string} modulePath The path to the module. You may have to
* `require.resolve` it.
* @param {Number} maxConcurrency The maximum number of concurrent processes
* to run. Defaults to 4.
*
* @return {Proxy} An ES6 Proxy object representing the module.
*/
export function requireTaskPool(modulePath, maxConcurrency=4) {
return new RendererTaskpoolItem(modulePath, maxConcurrency).moduleProxy;
}
/**
* This class implements the scheduling logic for queuing and dispatching method
* invocations to various background windows. It is complicated. But in like,
* a cool way.
*/
class RendererTaskpoolItem {
constructor(modulePath, maxConcurrency) {
const freeWindowList = [];
const invocationQueue = new Subject();
const completionQueue = new Subject();
// This method will find a window that is currently idle or if it doesn't
// exist, create one.
const getOrCreateWindow = () => {
let item = freeWindowList.pop();
if (item) return Observable.return(item);
return Observable.fromPromise(rendererRequireDirect(modulePath));
};
// Here, we set up a pipeline that maps a stream of invocations (i.e.
// something we can pass to executeJavaScriptMethod) => stream of Future
// Results from various windows => Stream of completed results, for which we
// throw the Window that completed the result back onto the free window stack.
invocationQueue
.map(({chain, args, retval}) => Observable.defer(() => {
return getOrCreateWindow()
.flatMap((wnd) => {
d(`Actually invoking ${chain.join('.')}(${JSON.stringify(args)})`);
let ret = wnd.executeJavaScriptMethodObservable(chain, ...args);
ret.multicast(retval).connect();
return ret.map(() => wnd).catch(Observable.return(wnd));
});
}))
.merge(maxConcurrency)
.subscribe((wnd) => {
if (!wnd || !wnd.dispose) throw new Error("Bogus!");
freeWindowList.push(wnd);
completionQueue.onNext(true);
});
// Here, we create a version of RecursiveProxyHandler that will turn method
// invocations into something we can push onto our invocationQueue pipeline.
// This is the object that ends up being returned to the caller of
// requireTaskPool.
this.moduleProxy = RecursiveProxyHandler.create('__removeme__', (methodChain, args) => {
let chain = methodChain.splice(1);
d(`Queuing ${chain.join('.')}(${JSON.stringify(args)})`);
let retval = new AsyncSubject();
invocationQueue.onNext({ chain: ['requiredModule'].concat(chain), args, retval });
return retval.toPromise();
});
// If we haven't received any invocations within a certain idle timeout
// period, burn all of our BrowserWindow instances
completionQueue.guaranteedThrottle(5*1000).subscribe(() => {
d(`Freeing ${freeWindowList.length} taskpool processes`);
while (freeWindowList.length > 0) {
let wnd = freeWindowList.pop();
if (wnd) wnd.dispose();
}
});
}
}
|
JavaScript
| 0 |
@@ -71,16 +71,65 @@
om 'rx';
+%0Aimport %7BfromRemoteWindow%7D from './remote-event';
%0A%0Aimport
@@ -736,25 +736,24 @@
include.%0A *
-%0A
* @return %7B
@@ -1146,59 +1146,51 @@
y =
-new Promise((res,rej) =%3E %7B%0A bw.webContents.once(
+Observable.merge(%0A fromRemoteWindow(bw,
'did
@@ -1208,87 +1208,90 @@
d',
-() =%3E res(
true)
-);
+,
%0A
-bw.webContents.once('did-fail-load', (ev, errCode
+fromRemoteWindow(bw, 'did-fail-load', true)%0A .flatMap((%5B,
, errMsg
) =%3E
@@ -1290,16 +1290,30 @@
rMsg
+%5D
) =%3E
-rej
+Observable.throw
(new
@@ -1328,21 +1328,39 @@
rrMsg)))
-;
%0A
-%7D
+).take(1).toPromise(
);%0A%0A /*
|
1f5b3db974ec1874f2f33aee520a7981fdd0eefc
|
make sure to only inject button on view page
|
src/content-script/content-script.js
|
src/content-script/content-script.js
|
function start () {
if ($('#ytmp3').size() === 0) {
var TEMPLATE = _.template(
'<div id="ytmp3">' +
'<button id="ytmp3-button" class="yt-uix-button yt-uix-button-size-default yt-uix-button-default">Download MP3</button>' +
'</div>'
);
var container = $(TEMPLATE({}));
var button = container.find('#ytmp3-button');
button.on('click', function(e) {
e.stopPropagation();
e.preventDefault();
var downloadWindow = window.open('http://www.youtube-mp3.org/?url=' + encodeURIComponent(window.location.toString()), '', 'width=10,height=10,resizable=no');
downloadWindow.resizeTo(0, 0);
downloadWindow.moveTo(0, window.screen.availHeight + 10);
downloadWindow.blur();
self.focus();
});
function injectButton () {
if ($('#watch-headline-title').size() > 0) {
return $('#watch-headline-title').append(container);
}
return _.defer(injectButton);
}
injectButton();
}
}
$(function() {
start();
setInterval(start, 1000);
});
|
JavaScript
| 0 |
@@ -15,24 +15,69 @@
() %7B%0A if (
+/%5C?v=.+/.test(window.location.toString()) &&
$('#ytmp3').
|
8ddf10fc04bb83676504cd2ed4b35386d8ea4648
|
Fix taint testing
|
src/renderers/Canvas.js
|
src/renderers/Canvas.js
|
_html2canvas.Renderer.Canvas = function(options) {
options = options || {};
var doc = document,
safeImages = [],
testCanvas = document.createElement("canvas"),
testctx = testCanvas.getContext("2d"),
canvas = options.canvas || doc.createElement('canvas');
function createShape(ctx, args) {
ctx.beginPath();
args.forEach(function(arg) {
ctx[arg.name].apply(ctx, arg['arguments']);
});
ctx.closePath();
}
function safeImage(item) {
if (safeImages.indexOf(item['arguments'][0].src ) === -1) {
testctx.drawImage(item['arguments'][0], 0, 0);
try {
testctx.getImageData(0, 0, 1, 1);
} catch(e) {
testCanvas = doc.createElement("canvas");
testctx = testCanvas.getContext("2d");
return false;
}
safeImages.push(item['arguments'][0].src);
}
return true;
}
function isTransparent(backgroundColor) {
return (backgroundColor === "transparent" || backgroundColor === "rgba(0, 0, 0, 0)");
}
function renderItem(ctx, item) {
switch(item.type){
case "variable":
ctx[item.name] = item['arguments'];
break;
case "function":
if (item.name === "createPattern") {
if (item['arguments'][0].width > 0 && item['arguments'][0].height > 0) {
try {
ctx.fillStyle = ctx.createPattern(item['arguments'][0], "repeat");
}
catch(e) {
h2clog("html2canvas: Renderer: Error creating pattern", e.message);
}
}
} else if (item.name === "drawShape") {
createShape(ctx, item['arguments']);
} else if (item.name === "drawImage") {
if (item['arguments'][8] > 0 && item['arguments'][7] > 0) {
if (options.taintTest || (options.taintTest && safeImage(item))) {
ctx.drawImage.apply( ctx, item['arguments'] );
}
}
} else {
ctx[item.name].apply(ctx, item['arguments']);
}
break;
}
}
return function(zStack, options, doc, queue, _html2canvas) {
var ctx = canvas.getContext("2d"),
storageContext,
i,
queueLen,
newCanvas,
bounds,
fstyle;
canvas.width = canvas.style.width = options.width || zStack.ctx.width;
canvas.height = canvas.style.height = options.height || zStack.ctx.height;
fstyle = ctx.fillStyle;
ctx.fillStyle = (isTransparent(zStack.backgroundColor) && options.background !== undefined) ? options.background : zStack.backgroundColor;
ctx.fillRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = fstyle;
if ( options.svgRendering && zStack.svgRender !== undefined ) {
// TODO: enable async rendering to support this
ctx.drawImage( zStack.svgRender, 0, 0 );
} else {
for ( i = 0, queueLen = queue.length; i < queueLen; i+=1 ) {
storageContext = queue.splice(0, 1)[0];
storageContext.canvasPosition = storageContext.canvasPosition || {};
// set common settings for canvas
ctx.textBaseline = "bottom";
if (storageContext.clip){
ctx.save();
ctx.beginPath();
// console.log(storageContext);
ctx.rect(storageContext.clip.left, storageContext.clip.top, storageContext.clip.width, storageContext.clip.height);
ctx.clip();
}
if (storageContext.ctx.storage) {
storageContext.ctx.storage.forEach(renderItem.bind(null, ctx));
}
if (storageContext.clip){
ctx.restore();
}
}
}
h2clog("html2canvas: Renderer: Canvas renderer done - returning canvas obj");
queueLen = options.elements.length;
if (queueLen === 1) {
if (typeof options.elements[0] === "object" && options.elements[0].nodeName !== "BODY") {
// crop image to the bounds of selected (single) element
bounds = _html2canvas.Util.Bounds(options.elements[0]);
newCanvas = doc.createElement('canvas');
newCanvas.width = bounds.width;
newCanvas.height = bounds.height;
ctx = newCanvas.getContext("2d");
ctx.drawImage(canvas, bounds.left, bounds.top, bounds.width, bounds.height, 0, 0, bounds.width, bounds.height);
canvas = null;
return newCanvas;
}
}
return canvas;
};
};
|
JavaScript
| 0.000004 |
@@ -1764,16 +1764,17 @@
if (
+!
options.
|
0c712189d21b0e7351c2caba0dc4d9adff837b99
|
Update bootstrap-386.js
|
js/bootstrap-386.js
|
js/bootstrap-386.js
|
_386 = { onePass: true, speedFactor: 1.25 };
self._386 = self._386 || {};
$(function(){
var character = { height: 20, width: 12.4 };
function scrollLock() {
var last = 0;
$(window).bind('scroll', function(e) {
var func, off = $(window).scrollTop();
console.log(off, last, off < last ? "up" : "down");
// this determines whether the user is intending to go up or down.
func = off < last ? "floor" : "ceil";
// make sure we don't run this from ourselves
if(off % character.height === 0) {
return;
}
last = off;
window.scrollTo(
0,
Math[func](off / character.height) * character.height
);
});
}
function loading() {
if(true) {
document.body.style.visibility='visible';
return;
}
var
onePass = true,
speedFactor = 1 / (_386.speedFactor || 1) * 165000;
wrap = document.createElement('div'),
bar = wrap.appendChild(document.createElement('div')),
cursor = document.createElement('div'),
// If the user specified that the visibility is hidden, then we
// start at the first pass ... otherwise we just do the
// cursor fly-by
pass = ($(document.body).css('visibility') == 'visible') ? 1 : 0,
height = $(window).height(),
width = $(window).width(),
// this makes the loading of the screen proportional to the real-estate of the window.
// it helps keep the cool sequence there while not making it waste too much time.
rounds = (height * width / speedFactor),
column = width, row = height - character.height;
wrap.id = "wrap386";
bar.id = "bar386";
cursor.id = "cursor386";
cursor.innerHTML = bar.innerHTML = '▄';
// only inject the wrap if the pass is 0
if(pass === 0) {
document.body.appendChild(wrap);
document.body.style.visibility='visible';
} else {
document.body.appendChild(cursor);
rounds /= 2;
character.height *= 4;
}
var ival = setInterval(function(){
for(var m = 0; m < rounds; m++) {
column -= character.width;
if(column <= 0) {
column = width;
row -= character.height;
}
if(row <= 0) {
pass++;
row = height - character.height;
if(pass == 2) {
document.body.removeChild(cursor);
clearInterval(ival);
} else {
wrap.parentNode.removeChild(wrap);
if(onePass) {
clearInterval(ival);
} else {
document.body.appendChild(cursor);
rounds /= 2;
character.height *= 4;
}
}
}
if(pass === 0) {
bar.style.width = column + "px";
wrap.style.height = row + "px";
} else {
cursor.style.right = column + "px";
cursor.style.bottom = row + "px";
}
}
}, 1);
}
loading();
});
|
JavaScript
| 0.000001 |
@@ -1,12 +1,14 @@
+//
_386 = %7B one
|
6acc8f74cb5351c3fbf31fd9903881132ff0a613
|
Clarify some comments
|
lib/editor-linter.js
|
lib/editor-linter.js
|
'use babel'
import {TextEditor, Emitter, CompositeDisposable} from 'atom'
export default class EditorLinter {
constructor(editor) {
if (!(editor instanceof TextEditor)) {
throw new Error('Given editor is not really an editor')
}
this.editor = editor
this.emitter = new Emitter()
this.messages = new Set()
this.markers = new WeakMap()
this.gutter = null
this.subscriptions = new CompositeDisposable
this.subscriptions.add(atom.config.observe('linter.underlineIssues', underlineIssues =>
this.underlineIssues = underlineIssues
))
this.subscriptions.add(this.editor.onDidDestroy(() =>
this.destroy()
))
this.subscriptions.add(this.editor.onDidSave(() =>
this.emitter.emit('should-lint', false)
))
this.subscriptions.add(this.editor.onDidChangeCursorPosition(({oldBufferPosition, newBufferPosition}) => {
if (newBufferPosition.row !== oldBufferPosition.row) {
this.emitter.emit('should-update-line-messages')
}
this.emitter.emit('should-update-bubble')
}))
this.subscriptions.add(atom.config.observe('linter.gutterEnabled', gutterEnabled => {
this.gutterEnabled = gutterEnabled
this.handleGutter()
}))
// Using onDidChange here 'cause the same function is invoked above
this.subscriptions.add(atom.config.onDidChange('linter.gutterPosition', () =>
this.handleGutter()
))
this.subscriptions.add(this.onDidMessageAdd(message => {
if (!this.underlineIssues && !this.gutterEnabled) {
return // No-Op
}
const marker = this.editor.markBufferRange(message.range, {invalidate: 'inside'})
this.markers.set(message, marker)
if (this.underlineIssues) {
this.editor.decorateMarker(marker, {
type: 'highlight',
class: `linter-highlight ${message.class}`
})
}
if (this.gutterEnabled) {
const item = document.createElement('span')
item.className = `linter-gutter linter-highlight ${message.class}`
//item.innerHTML = ' '
this.gutter.decorateMarker(marker, {
class: 'linter-row',
item
})
}
}))
this.subscriptions.add(this.onDidMessageRemove(message => {
if (this.markers.has(message)) {
this.markers.get(message).destroy()
this.markers.delete(message)
}
}))
// Atom invokes the onDidStopChanging callback immediately on creation. So we wait a moment
setImmediate(() => {
this.subscriptions.add(this.editor.onDidStopChanging(() =>
this.emitter.emit('should-lint', true)
))
})
}
handleGutter() {
if (this.gutter !== null) {
this.removeGutter()
}
if (atom.config.get('linter.gutterEnabled')) {
this.addGutter()
}
}
addGutter() {
const position = atom.config.get('linter.gutterPosition')
this.gutter = this.editor.addGutter({
name: 'linter',
priority: position === 'Left' ? -100 : 100
})
}
removeGutter() {
if (this.gutter !== null) {
try {
this.gutter.destroy()
// Atom throws when we try to remove a container from a closed text editor
} catch (err) {}
this.gutter = null
}
}
getMessages() {
return this.messages
}
addMessage(message) {
if (!this.messages.has(message)) {
this.messages.add(message)
this.emitter.emit('did-message-add', message)
this.emitter.emit('did-message-change', {message, type: 'add'})
}
}
removeMessage(message) {
if (this.messages.has(message)) {
this.messages.delete(message)
this.emitter.emit('did-message-remove', message)
this.emitter.emit('did-message-change', {message, type: 'remove'})
}
}
lint(onChange = false) {
this.emitter.emit('should-lint', onChange)
}
onDidMessageAdd(callback) {
return this.emitter.on('did-message-add', callback)
}
onDidMessageRemove(callback) {
return this.emitter.on('did-message-remove', callback)
}
onDidMessageChange(callback) {
return this.emitter.on('did-message-change', callback)
}
onShouldUpdateBubble(callback) {
return this.emitter.on('should-update-bubble', callback)
}
onShouldUpdateLineMessages(callback) {
return this.emitter.on('should-update-line-messages', callback)
}
onShouldLint(callback) {
return this.emitter.on('should-lint', callback)
}
onDidDestroy(callback) {
return this.emitter.on('did-destroy', callback)
}
destroy() {
this.emitter.emit('did-destroy')
this.dispose()
}
dispose() {
if (this.markers.size) {
this.markers.forEach(marker => marker.destroy())
this.markers.clear()
}
this.removeGutter()
this.subscriptions.dispose()
this.messages.clear()
this.emitter.dispose()
}
}
|
JavaScript
| 0.000074 |
@@ -1255,16 +1255,35 @@
dChange
+instead of observe
here 'ca
@@ -2475,16 +2475,23 @@
tely on
+Editor
creation
@@ -3181,16 +3181,23 @@
emove a
+gutter
containe
|
9fda9070c1ba1ddc86d40b3fe5ab86d097262f8a
|
remove old tests
|
js/client/app/components/volunteer/volunteer.spec.js
|
js/client/app/components/volunteer/volunteer.spec.js
|
import VolunteerModule from './volunteer'
import VolunteerController from './volunteer.controller';
import VolunteerComponent from './volunteer.component';
import VolunteerTemplate from './volunteer.html';
import _ from 'lodash';
describe('Volunteer', () => {
let $rootScope, $state, makeController;
beforeEach(window.module(VolunteerModule.name));
beforeEach(inject((_$rootScope_, _$state_) => {
$rootScope = _$rootScope_;
$state = _$state_;
makeController = (volunteerId) => {
$state.params.volunteerId = volunteerId;
return new VolunteerController($state);
};
}));
describe('Module', () => {
// top-level specs: i.e., routes, injection, naming
});
describe('Controller', () => {
// controller specs
it('has a volunteerId property', () => {
let controller = makeController(0);
expect(controller.volunteerId).to.equal(0);
controller = makeController(1);
expect(controller.volunteerId).to.equal(1);
controller = makeController('1234');
expect(controller.volunteerId).to.equal(1234);
});
it('mocks a volunteer', () => {
let controller = makeController(0);
expect(controller.volunteer).to.exist;
expect(controller.volunteer.id).to.equal(0);
expect(controller.volunteer.firstName).to.equal("Bill");
expect(controller.volunteer.lastName).to.equal("Brown");
expect(controller.volunteer.languages).to.eql(["German"]);
});
it('generates a volunteer', () => {
let controller = makeController('19582');
expect(controller.volunteer).to.exist;
let volunteerParams = [
controller.volunteer.id,
controller.volunteer.firstName,
controller.volunteer.lastName,
controller.volunteer.languages,
controller.volunteer.birthday,
controller.volunteer.gender,
controller.volunteer.role,
controller.volunteer.volunteerLevel,
controller.volunteer.createdAt,
controller.volunteer.notes,
controller.volunteer.contact.street,
controller.volunteer.contact.city,
controller.volunteer.contact.state,
controller.volunteer.contact.zip,
controller.volunteer.contact.phoneNumber,
controller.volunteer.contact.email,
controller.volunteer.contact.preferredContact
];
_(volunteerParams).forEach((param) => {
expect(param).to.exist;
});
expect(controller.volunteer.hours).to.be.within(30,60);
});
});
describe('Template', () => {
it('displays name in template', () => {
expect(VolunteerTemplate).to.match(/{{\s?vm\.volunteer.firstName\s?}}/g);
expect(VolunteerTemplate).to.match(/{{\s?vm\.volunteer.middleName\s?}}/g);
expect(VolunteerTemplate).to.match(/{{\s?vm\.volunteer.lastName\s?}}/g);
});
});
describe('Component', () => {
// component/directive specs
let component = VolunteerComponent;
it('includes the intended template',() => {
expect(component.template).to.equal(VolunteerTemplate);
});
it('uses `controllerAs` syntax', () => {
expect(component).to.have.property('controllerAs');
});
it('invokes the right controller', () => {
expect(component.controller).to.equal(VolunteerController);
});
});
});
|
JavaScript
| 0.000743 |
@@ -730,2117 +730,8 @@
%7B%0A%0A
- // controller specs%0A it('has a volunteerId property', () =%3E %7B %0A let controller = makeController(0);%0A expect(controller.volunteerId).to.equal(0);%0A%0A controller = makeController(1);%0A expect(controller.volunteerId).to.equal(1);%0A%0A controller = makeController('1234');%0A expect(controller.volunteerId).to.equal(1234);%0A %7D);%0A%0A it('mocks a volunteer', () =%3E %7B%0A let controller = makeController(0);%0A%0A expect(controller.volunteer).to.exist;%0A expect(controller.volunteer.id).to.equal(0);%0A expect(controller.volunteer.firstName).to.equal(%22Bill%22);%0A expect(controller.volunteer.lastName).to.equal(%22Brown%22);%0A expect(controller.volunteer.languages).to.eql(%5B%22German%22%5D);%0A %7D);%0A%0A it('generates a volunteer', () =%3E %7B%0A let controller = makeController('19582');%0A%0A expect(controller.volunteer).to.exist;%0A%0A let volunteerParams = %5B%0A controller.volunteer.id,%0A controller.volunteer.firstName,%0A controller.volunteer.lastName,%0A controller.volunteer.languages,%0A controller.volunteer.birthday,%0A controller.volunteer.gender,%0A controller.volunteer.role,%0A controller.volunteer.volunteerLevel,%0A controller.volunteer.createdAt,%0A controller.volunteer.notes,%0A controller.volunteer.contact.street,%0A controller.volunteer.contact.city,%0A controller.volunteer.contact.state,%0A controller.volunteer.contact.zip,%0A controller.volunteer.contact.phoneNumber,%0A controller.volunteer.contact.email,%0A controller.volunteer.contact.preferredContact%0A %5D;%0A%0A _(volunteerParams).forEach((param) =%3E %7B%0A expect(param).to.exist;%0A %7D);%0A%0A expect(controller.volunteer.hours).to.be.within(30,60);%0A %0A %7D);%0A %7D);%0A%0A describe('Template', () =%3E %7B%0A it('displays name in template', () =%3E %7B%0A expect(VolunteerTemplate).to.match(/%7B%7B%5Cs?vm%5C.volunteer.firstName%5Cs?%7D%7D/g);%0A expect(VolunteerTemplate).to.match(/%7B%7B%5Cs?vm%5C.volunteer.middleName%5Cs?%7D%7D/g);%0A expect(VolunteerTemplate).to.match(/%7B%7B%5Cs?vm%5C.volunteer.lastName%5Cs?%7D%7D/g);%0A %7D);%0A
%7D)
|
4c3c9d337d43380ddf52a62861aef3243ff31525
|
Add log2
|
lib/exprs/prelude.js
|
lib/exprs/prelude.js
|
/*
* ExpStats lib/exprs/prelude.js
* copyright (c) 2015 Susisu
*/
"use strict";
function endModule() {
module.exports = Object.freeze(prelude);
}
var exprs = require("./exprs.js");
var Exception = exprs.Exception;
var prelude = Object.create(null);
function unaryOp(func) {
return function op(x) {
if (x instanceof Array) {
return x.map(function (elem) {
return op(elem);
});
}
else if (typeof x === "number") {
return func(x);
}
else {
throw new Exception([], "type error");
}
};
}
function binaryOp(func) {
return function op(x) {
return function op_(y) {
if (x instanceof Array) {
if (y instanceof Array) {
var len = Math.min(x.length, y.length);
var res = new Array(len);
for (var i = 0; i < len; i++) {
res[i] = op(x[i])(y[i]);
}
return res;
}
else if (typeof y === "number") {
return x.map(function (xelem) {
return op(xelem)(y);
});
}
else {
throw new Exception([], "type error");
}
}
else if (typeof x === "number") {
if (y instanceof Array) {
return y.map(function (yelem) {
return op(x)(yelem);
});
}
else if (typeof y === "number") {
return func(x, y);
}
else {
throw new Exception([], "type error");
}
}
else {
throw new Exception([], "type error");
}
};
};
}
function accumOp(accum, init) {
return function op(x) {
if (x instanceof Array) {
return x.reduce(function (x, y) {
if (typeof x === "number" && typeof y === "number") {
return accum(x, y);
}
else {
throw new Exception([], "type error");
}
}, init);
}
else if (typeof x === "number") {
return x;
}
else {
throw new Exception([], "type error");
}
};
}
prelude["pos"] = unaryOp(function (x) { return +x; });
prelude["neg"] = unaryOp(function (x) { return -x; });
prelude["floor"] = unaryOp(function (x) { return Math.floor(x); });
prelude["ceil"] = unaryOp(function (x) { return Math.ceil(x); });
prelude["round"] = unaryOp(function (x) { return Math.round(x); });
prelude["log"] = unaryOp(function (x) { return Math.log(x); });
prelude["log10"] = unaryOp(function (x) { return Math.log(x) / Math.log(10); });
prelude["exp"] = unaryOp(function (x) { return Math.exp(x); });
prelude["sqrt"] = unaryOp(function (x) { return Math.sqrt(x); });
prelude["add"] = binaryOp(function (x, y) { return x + y; });
prelude["sub"] = binaryOp(function (x, y) { return x - y; });
prelude["mul"] = binaryOp(function (x, y) { return x * y; });
prelude["div"] = binaryOp(function (x, y) { return x / y; });
prelude["mod"] = binaryOp(function (x, y) { return x % y; });
prelude["pow"] = binaryOp(function (x, y) { return Math.pow(x, y); });
prelude["at"] = function at(x) {
return function at_(y) {
if (x instanceof Array) {
if (typeof y === "number") {
if (y < 0 || x.length <= y) {
throw new Exception([], "range error");
}
else {
return x[y];
}
}
else {
throw new Exception([], "type error: invalid index");
}
}
else {
throw new Exception([], "type error: '" + x.toString() + "' is not a vector");
}
};
};
prelude["sum"] = accumOp(function (x, y) { return x + y; }, 0);
prelude["prod"] = accumOp(function (x, y) { return x * y; }, 1);
prelude["avg"] = function (x) {
if (x instanceof Array) {
var sum = prelude["sum"](x);
return sum / x.length;
}
else if (typeof x === "number") {
return x;
}
else {
throw new Exception([], "type error");
}
};
prelude["var"] = function (x) {
if (x instanceof Array) {
var avg = prelude["avg"](x);
var dev = prelude["^"](prelude["-"](x)(avg))(2);
return prelude["avg"](dev);
}
else if (typeof x === "number") {
return 0;
}
else {
throw new Exception([], "type error");
}
};
endModule();
|
JavaScript
| 0.000037 |
@@ -2851,32 +2851,112 @@
ath.log(x); %7D);%0A
+prelude%5B%22log2%22%5D = unaryOp(function (x) %7B return Math.log(x) / Math.log(2); %7D);%0A
prelude%5B%22log10%22%5D
|
360d0ec42e9fbf0b73829dde9bcaf3cb10e192a6
|
Optimize for compilers/compressors
|
plugins/buttons/src/jquery.jcarousel.buttons.js
|
plugins/buttons/src/jquery.jcarousel.buttons.js
|
/*!
* jCarousel Buttons Plugin v@VERSION
* http://sorgalla.com/jcarousel/
*
* Copyright 2011, Jan Sorgalla
* Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
* or GPL Version 2 (http://www.opensource.org/licenses/gpl-2.0.php) licenses.
*
* Date: @DATE
*/
(function($) {
var $j = $.jcarousel;
$.extend($j.options, {
next: '.jcarousel-next',
prev: '.jcarousel-prev',
nextEvent: 'click',
prevEvent: 'click'
});
$j.hook('reloadend', function(e) {
if (e.isDefaultPrevented()) {
return;
}
var self = this,
o = this.options;
if ($.isFunction(o.next)) {
o.next = o.next.call(this);
}
if ($.isFunction(o.prev)) {
o.prev = o.prev.call(this);
}
this.nextButton = null;
this.prevButton = null;
if (o.next) {
this.nextButton = (o.next.jquery ? o.next : this.element.parent().find(o.next)).unbind('.jcarousel');
if (o.nextEvent) {
this.nextButton.bind(o.nextEvent + '.jcarousel', function() {
if ($(this).data('jcarouselbuttonenabled') === true) {
self.next();
}
return false;
});
}
}
if (o.prev) {
this.prevButton = (o.prev.jquery ? o.prev : this.element.parent().find(o.prev)).unbind('.jcarousel');
if (o.prevEvent) {
this.prevButton.bind(o.prevEvent + '.jcarousel', function() {
if ($(this).data('jcarouselbuttonenabled') === true) {
self.prev();
}
return false;
});
}
}
});
$j.hook('reloadend scrollend scrolltailend', function(e) {
if (e.isDefaultPrevented()) {
return;
}
var o = this.options,
s = this.size(),
n = s > 0 && ((o.wrap && o.wrap !== 'first') || (this.index(this.last) < (s - 1)) || (this.tail && !this.inTail)) ? true : false,
p = s > 0 && ((o.wrap && o.wrap !== 'last') || (this.index(this.first) > 0) || (this.tail && this.inTail)) ? true : false;
if (this.nextButton && this.nextButton.data('jcarouselbuttonenabled') !== n) {
this.nextButton
.data('jcarouselbuttonenabled', n)
.data('jcarouselbuttondisabled', !n)
.trigger('jcarouselbutton' + (n ? 'enabled' : 'disabled'));
}
if (this.prevButton && this.prevButton.data('jcarouselbuttonenabled') !== p) {
this.prevButton
.data('jcarouselbuttonenabled', p)
.data('jcarouselbuttondisabled', !p)
.trigger('jcarouselbutton' + (p ? 'enabled' : 'disabled'));
}
});
$j.hook('destroy', function(e) {
if (e.isDefaultPrevented()) {
return;
}
if (this.nextButton) {
this.nextButton
.removeData('jcarouselbuttonenabled')
.removeData('jcarouselbuttondisabled')
.unbind('.jcarousel');
}
if (this.prevButton) {
this.prevButton
.removeData('jcarouselbuttonenabled')
.removeData('jcarouselbuttondisabled')
.unbind('.jcarousel');
}
});
$.each(['enabled', 'disabled'], function(i, name) {
$.expr.filters['jcarouselbutton' + name] = function(elem) {
return $.data(elem, 'jcarouselbutton' + name);
};
});
})(jQuery);
|
JavaScript
| 0.000004 |
@@ -329,16 +329,112 @@
carousel
+,%0A btnEnabled = 'jcarouselbuttonenabled',%0A btnDisabled = 'jcarouselbuttondisabled'
;%0A%0A $
@@ -727,17 +727,16 @@
= this,
-
%0A
@@ -1288,32 +1288,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
) ==
@@ -1733,32 +1733,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
) ==
@@ -2424,32 +2424,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
) !=
@@ -2491,32 +2491,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
, n
@@ -2525,33 +2525,19 @@
ata(
-'jcarouselbuttond
+btnD
isabled
-'
, !n
@@ -2563,56 +2563,36 @@
ger(
-'jcarouselbutton' + (n ? 'e
+n ? btnE
nabled
-'
:
-'d
+btnD
isabled
-')
);%0A
@@ -2657,32 +2657,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
) !=
@@ -2724,32 +2724,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
, p
@@ -2758,33 +2758,19 @@
ata(
-'jcarouselbuttond
+btnD
isabled
-'
, !p
@@ -2796,56 +2796,36 @@
ger(
-'jcarouselbutton' + (p ? 'e
+p ? btnE
nabled
-'
:
-'d
+btnD
isabled
-')
);%0A
@@ -3035,32 +3035,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
)%0A
@@ -3071,33 +3071,19 @@
ata(
-'jcarouselbuttond
+btnD
isabled
-'
)%0A
@@ -3213,32 +3213,18 @@
ata(
-'jcarouselbuttone
+btnE
nabled
-'
)%0A
@@ -3249,33 +3249,19 @@
ata(
-'jcarouselbuttond
+btnD
isabled
-'
)%0A
@@ -3323,36 +3323,33 @@
$.e
-ach(%5B'enabled', 'dis
+xpr.filters%5BbtnEn
abled
-'%5D,
+%5D =
fun
@@ -3358,23 +3358,67 @@
ion(
-i, name) %7B
+elem) %7B%0A return !!$.data(elem, btnEnabled);
%0A
+%7D;%0A%0A
@@ -3436,33 +3436,19 @@
ers%5B
-'jcarouselbutton' + name
+btnDisabled
%5D =
@@ -3472,27 +3472,25 @@
-
return
+!!
$.data(e
@@ -3498,53 +3498,27 @@
em,
-'jcarouselbutton' + name
+btnDisabled
);%0A
-
- %7D;%0A %7D)
+%7D
;%0A%0A%7D
|
d77ae7459fc673e85ba53395690f806e9df33fae
|
add es6-shim to browsersupport too
|
plugins/c9.ide.browsersupport/browsersupport.js
|
plugins/c9.ide.browsersupport/browsersupport.js
|
define(function(require, exports, module) {
"use strict";
main.consumes = ["Plugin"];
main.provides = ["browsersupport"];
return main;
function main(options, imports, register) {
var Plugin = imports.Plugin;
require("ace/lib/es5-shim");
var useragent = require("ace/lib/useragent");
var dom = require("ace/lib/dom");
if (useragent.isGecko)
dom.addCssClass(document.body, "ua_gecko");
else if (useragent.isWebkit)
dom.addCssClass(document.body, "ua_webkit");
else if (useragent.isIE)
dom.addCssClass(document.body, "ua_ie");
function getIEVersion() {
return useragent.isIE;
}
var plugin = new Plugin("Ajax.org", main.consumes);
/**
* Browser compatibility support.
*/
plugin.freezePublicAPI({
/**
* Gets Internet Explorer's major version, e.g. 10,
* or returns null if a different browser is used.
*
* @return {Number}
*/
getIEVersion: getIEVersion
});
register(null, { browsersupport: plugin });
}
});
// Support __defineGetter__ et al. on IE9
// (always triggers when packed)
try {
if (!Object.prototype.__defineGetter__ &&
Object.defineProperty({},"x",{get: function(){return true}}).x) {
// Setter
Object.defineProperty(
Object.prototype,
"__defineSetter__",
{
enumerable: false,
configurable: true,
value: function(name,func) {
Object.defineProperty(this,name,{set:func,enumerable: true,configurable: true});
// Adding the property to the list (for __lookupSetter__)
if (!this.setters) this.setters = {};
this.setters[name] = func;
}
}
);
// Lookupsetter
Object.defineProperty(
Object.prototype,
"__lookupSetter__",
{
enumerable: false,
configurable: true,
value: function(name) {
if (!this.setters) return false;
return this.setters[name];
}
}
);
// Getter
Object.defineProperty(
Object.prototype,
"__defineGetter__",
{
enumerable: false,
configurable: true,
value: function(name,func) {
Object.defineProperty(this,name,{get:func,enumerable: true,configurable: true});
// Adding the property to the list (for __lookupSetter__)
if (!this.getters) this.getters = {};
this.getters[name] = func;
}
}
);
// Lookupgetter
Object.defineProperty(
Object.prototype,
"__lookupGetter__",
{
enumerable: false,
configurable: true,
value: function(name) {
if (!this.getters) return false;
return this.getters[name];
}
}
);
}
} catch (defPropException) {
// Forget about it
}
|
JavaScript
| 0 |
@@ -277,24 +277,61 @@
es5-shim%22);%0A
+ require(%22ace/lib/es6-shim%22);%0A
var
|
7111dd9043b719e61a933cd8087e61d0b3febd06
|
add spaces when bulding tag meta
|
lib/format-header.js
|
lib/format-header.js
|
module.exports = function formatHeader(page, opts) {
var url = pageURL(page.output)
var title = "<a href='" + url + "'><h1>" + page.content.title + "</h1></a>"
var metaList = buildMeta(page).join(" ")
var meta = "<ul>" + metaList + "</ul>"
var header = "<div class='post-header'>"
+ title + meta + "</div>"
var newContent = header + page.content.content
page.content.content = newContent
return (page)
}
function pageURL(pageDir) {
var parts = pageDir.split('/')
var url = parts.pop()
return url
}
function buildMeta(page) {
var meta = []
if (page.content.author) {
meta.push("<li>" + page.content.author + "</li>")
}
if (page.content.date) {
meta.push("<li>" + page.content.date + "</li>")
}
if (page.content.tags) {
meta.push("<li>" + page.content.tags +"</li>")
}
return meta
}
|
JavaScript
| 0.000004 |
@@ -803,16 +803,27 @@
ent.tags
+.join(%22, %22)
+%22%3C/li%3E
|
e907f26bd0048b28d54aa6e9cace1186f1a406f1
|
Add extra info to ls -l
|
lib/fs/usr/bin/ls.js
|
lib/fs/usr/bin/ls.js
|
var FS = require('zsh.js/lib/fs');
var File = require('zsh.js/lib/file');
return function (args, stdin, stdout, stderr, next) {
var outputs = [];
if (!args.arguments.length) {
args.arguments.push('.');
}
args.arguments.forEach(function (arg) {
var dir = File.open(arg);
if (!dir.exists()) {
stderr.write(FS.notFound('ls', arg));
} else if (dir.isFile()) {
stderr.write(FS.error('ls', arg, 'Is a file'));
} else {
var files = Object.keys(dir.read());
if (!args.options.a) {
files = files.filter(function (file) {
return file[0] !== '.';
});
}
if (args.arguments.length > 1) {
stdout.write(arg + ':');
}
stdout.write(files.join(args.options.l ? '\n' : ' '));
}
});
next();
};
|
JavaScript
| 0 |
@@ -702,24 +702,336 @@
);%0A %7D%0A%0A
+ if (args.options.l) %7B%0A files = files.map(function (name) %7B%0A var file = dir.open(name);%0A var type = file.isDir() ? 'd' : '-';%0A var perms = type + 'rw-r--r--';%0A%0A return perms + ' guest guest ' + file.length() + ' ' + file.mtime() + ' ' + name;%0A %7D);%0A %7D%0A%0A
stdout
|
a2148ebe368f53f1994f71e82452539529bdfe16
|
remove console.logs to Auth.js
|
src/routes/auth/Auth.js
|
src/routes/auth/Auth.js
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import Session from '../../core/Session';
import history from '../../history';
class Auth extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
accessToken: PropTypes.string.isRequired,
accessTokenSecret: PropTypes.string.isRequired
};
constructor(props) {
super(props);
}
componentDidMount() {
console.log('props!', this.props);
Session.setUser('charrr');
Session.setAccessToken(this.props.accessToken);
Session.setAccessTokenSecret(this.props.accessTokenSecret);
console.log('Session!!', Session.getAccessToken());
history.replace('/');
}
render() {
return (
<div style={{height: '500px'}}>
</div>
);
}
}
export default Auth;
|
JavaScript
| 0.000001 |
@@ -678,78 +678,8 @@
) %7B%0A
- console.log('props!', this.props);%0A Session.setUser('charrr');%0A
@@ -793,65 +793,8 @@
et);
-%0A%0A console.log('Session!!', Session.getAccessToken());
%0A
|
6be4d828edf4c3b427ca7e504a5a610aebc95dcc
|
remove 'should' dependency completely
|
lib/keys/keypair.js
|
lib/keys/keypair.js
|
/**
* Created by bmf on 11/2/13.
*/
/* jslint node: true */
'use strict';
var assert = require('assert');
var CryptoBaseBuffer = require('../crypto-base-buffer');
module.exports = function KeyPair() {
var self = this;
/** secret key */
self.secretKey = new CryptoBaseBuffer();
self.secretKeySize = 0;
/** public key */
self.publicKey = new CryptoBaseBuffer();
self.publicKeySize = 0;
self.type = undefined;
/** default encoding to use in all string operations */
self.defaultEncoding = undefined;
self.init = function(options) {
options = options || {};
if( !options.type ) {
throw new Error('[KeyPair] type not given in init');
}
self.type = options.type;
if( !options.publicKeySize ) {
throw new Error('[KeyPair] public key size not given');
}
self.publicKeySize = options.publicKeySize;
if( !options.secretKeySize ) {
throw new Error('[KeyPair] secret key size not given');
}
self.secretKeySize = options.secretKeySize;
// init both buffers
self.publicKey.init({
expectedSize: options.publicKeySize,
type: self.type + 'PublicKey'
});
self.secretKey.init({
expectedSize: options.secretKeySize,
type: self.type + 'SecretKey'
});
// We will only accept hex string representations of keys
self.publicKey.setValidEncodings(['hex', 'base64']);
self.secretKey.setValidEncodings(['hex', 'base64']);
// the default encoding to us in all string set/toString methods is Hex
self.publicKey.setEncoding('base64');
self.secretKey.setEncoding('base64');
// Public Key
self.setPublicKey(options.publicKey, options.encoding);
// Secret Key
self.setSecretKey(options.secretKey, options.encoding);
};
/** Box Public Key buffer size in bytes */
self.publicKeyBytes = function() {
return self.publicKeySize;
};
/** Box Public Key buffer size in bytes */
self.secretKeyBytes = function() {
return self.secretKeySize;
};
/* Aliases */
self.pkBytes = self.publicKeyBytes;
self.skBytes = self.secretKeyBytes;
/**
* Set the default encoding to use in all string conversions
* @param {String} encoding encoding to use
*/
self.setEncoding = function(encoding) {
assert(!!encoding.match(/^(?:utf8|ascii|binary|hex|utf16le|ucs2|base64)$/), 'Encoding ' + encoding + ' is currently unsupported.');
self.defaultEncoding = encoding;
self.publicKey.setEncoding(encoding);
self.secretKey.setEncoding(encoding);
};
/**
* Get the current default encoding
* @returns {undefined|String}
*/
self.getEncoding = function() {
return self.defaultEncoding;
};
/**
* Check if key pair is valid
* @param keys {Object} an object with secrteKey, and publicKey members
* @returns {boolean} true is both public and secret keys are valid
*/
self.isValid = function(keys, encoding) {
keys.should.have.type('object');
keys.should.have.properties('publicKey', 'secretKey');
encoding = encoding || self.defaultEncoding;
return self.publicKey.isValid(keys.publicKey, encoding) &&
self.secretKey.isValid(keys.secretKey, encoding);
};
/**
* Wipe keys securely
*/
self.wipe = function() {
self.publicKey.wipe();
self.secretKey.wipe();
};
/**
* Generate a random key pair
*/
self.generate = function() {
throw new Error('KeyPair: this method should be implemented in each sub class');
};
/**
* Getter for the public key
* @returns {undefined| Buffer} public key
*/
self.getPublicKey = function() {
return self.publicKey;
};
/**
* Getter for the secretKey
* @returns {undefined| Buffer} secret key
*/
self.getSecretKey = function() {
return self.secretKey;
};
self.pk = self.getPublicKey;
self.sk = self.getSecretKey;
/**
* Getter for the key pair
* @returns {Object} with both public and private keys
*/
self.get = function() {
return {
'publicKey' : self.publicKey.get(),
'secretKey' : self.secretKey.get()
};
};
/**
* Set the secret key to a known value
* @param v {String|Buffer|Array} the secret key
* @param encoding {String} optional. If v is a string you can specify the encoding
*/
self.set = function(keys, encoding) {
keys.should.have.type('object');
if( keys instanceof KeyPair ) {
self.secretKey.set(keys.sk(), encoding);
self.publicKey.set(keys.pk(), encoding);
}
else {
encoding = encoding || self.defaultEncoding;
if( typeof keys === 'object' ) {
if( keys.secretKey ) {
self.secretKey.set(keys.secretKey, encoding);
}
if( keys.publicKey ) {
self.publicKey.set(keys.publicKey, encoding);
}
}
}
};
self.setPublicKey = function(key, encoding) {
if( key instanceof KeyPair ) {
self.publicKey = key.pk();
}
else if( key instanceof CryptoBaseBuffer ) {
if( key.size() == self.publicKeySize ) {
self.publicKey = key;
}
}
else {
self.publicKey.init({
expectedSize: self.publicKeySize,
buffer: key,
encoding: encoding,
type: self.type + 'PublicKey'
});
}
};
self.setSecretKey = function(key, encoding) {
if( key instanceof KeyPair ) {
self.secretKey = key.sk();
}
else if( key instanceof CryptoBaseBuffer ) {
if( key.size() == self.secretKeySize ) {
self.secretKey = key;
}
}
else {
self.secretKey.init({
expectedSize: self.secretKeySize,
buffer: key,
encoding: encoding,
type: self.type + 'SecretKey'
});
}
};
/**
* Convert the secret key to a string object
* @param encoding {String} optional sting encoding. defaults to 'hex'
*/
self.toString = function(encoding) {
encoding = encoding || self.defaultEncoding;
return self.secretKey.toString(encoding) + "," +
self.publicKey.toString(encoding);
};
/**
* Convert the secret key to a JSON object
* @param encoding {String} optional sting encoding. defaults to 'hex'
*/
self.toJson = function(encoding) {
encoding = encoding || self.defaultEncoding;
var out = '{';
if( self.secretKey ) {
out += '"secretKey" :"' + self.secretKey.toString(encoding) + '"';
}
if( self.secretKey && self.publicKey ) {
out += ', ';
}
if( self.publicKey ) {
out += '"publicKey" :"' + self.publicKey.toString(encoding) + '"';
}
out += '}';
return out;
};
};
|
JavaScript
| 0.000055 |
@@ -3158,32 +3158,34 @@
ding) %7B%0A
+//
keys.should.have
@@ -3201,32 +3201,34 @@
ject');%0A
+//
keys.should.have
@@ -4710,16 +4710,18 @@
+//
keys.sho
|
4693a13a03936d92be16652500c82f50833775d5
|
Clear all global Relay state along with expectations
|
lib/relay-network-layer-manager.js
|
lib/relay-network-layer-manager.js
|
import util from 'util';
import {Environment, Network, RecordSource, Store} from 'relay-runtime';
import moment from 'moment';
const LODASH_ISEQUAL = 'lodash.isequal';
let isEqual = null;
const relayEnvironmentPerURL = new Map();
const tokenPerURL = new Map();
const fetchPerURL = new Map();
const responsesByQuery = new Map();
function logRatelimitApi(headers) {
const remaining = headers.get('x-ratelimit-remaining');
const total = headers.get('x-ratelimit-limit');
const resets = headers.get('x-ratelimit-reset');
const resetsIn = moment.unix(parseInt(resets, 10)).from();
// eslint-disable-next-line no-console
console.debug(`GitHub API Rate Limit: ${remaining}/${total} — resets ${resetsIn}`);
}
export function expectRelayQuery(operationPattern, response) {
let resolve, reject;
const handler = typeof response === 'function' ? response : () => ({data: response});
const promise = new Promise((resolve0, reject0) => {
resolve = resolve0;
reject = reject0;
});
const existing = responsesByQuery.get(operationPattern.name) || [];
existing.push({
promise,
handler,
variables: operationPattern.variables || {},
trace: operationPattern.trace,
});
responsesByQuery.set(operationPattern.name, existing);
const disable = () => responsesByQuery.delete(operationPattern.name);
return {promise, resolve, reject, disable};
}
export function clearRelayExpectations() {
responsesByQuery.clear();
}
function createFetchQuery(url) {
if (atom.inSpecMode()) {
return function specFetchQuery(operation, variables, _cacheConfig, _uploadables) {
const expectations = responsesByQuery.get(operation.name) || [];
const match = expectations.find(expectation => {
if (isEqual === null) {
// Lazily require lodash.isequal so we can keep it as a dev dependency.
// Require indirectly to trick electron-link into not following this.
isEqual = require(LODASH_ISEQUAL);
}
return isEqual(expectation.variables, variables);
});
if (!match) {
// eslint-disable-next-line no-console
console.log(
`GraphQL query ${operation.name} was:\n ${operation.text.replace(/\n/g, '\n ')}\n` +
util.inspect(variables),
);
const e = new Error(`Unexpected GraphQL query: ${operation.name}`);
e.rawStack = e.stack;
throw e;
}
const responsePromise = match.promise.then(() => {
return match.handler(operation);
});
if (match.trace) {
// eslint-disable-next-line no-console
console.log(`[Relay] query "${operation.name}":\n${operation.text}`);
responsePromise.then(result => {
// eslint-disable-next-line no-console
console.log(`[Relay] response "${operation.name}":`, result);
}, err => {
// eslint-disable-next-line no-console
console.error(`[Relay] error "${operation.name}":\n${err.stack || err}`);
throw err;
});
}
return responsePromise;
};
}
return async function fetchQuery(operation, variables, _cacheConfig, _uploadables) {
const currentToken = tokenPerURL.get(url);
let response;
try {
response = await fetch(url, {
method: 'POST',
headers: {
'content-type': 'application/json',
'Authorization': `bearer ${currentToken}`,
'Accept': 'application/vnd.github.antiope-preview+json',
},
body: JSON.stringify({
query: operation.text,
variables,
}),
});
} catch (e) {
// A network error was encountered. Mark it so that QueryErrorView and ErrorView can distinguish these, because
// the errors from "fetch" are TypeErrors without much information.
e.network = true;
e.rawStack = e.stack;
throw e;
}
try {
atom && atom.inDevMode() && logRatelimitApi(response.headers);
} catch (_e) { /* do nothing */ }
if (response.status !== 200) {
const e = new Error(`GraphQL API endpoint at ${url} returned ${response.status}`);
e.response = response;
e.responseText = await response.text();
e.rawStack = e.stack;
throw e;
}
const payload = await response.json();
if (payload && payload.errors && payload.errors.length > 0) {
const e = new Error(`GraphQL API endpoint at ${url} returned an error for query ${operation.name}.`);
e.response = response;
e.errors = payload.errors;
e.rawStack = e.stack;
throw e;
}
return payload;
};
}
export default class RelayNetworkLayerManager {
static getEnvironmentForHost(endpoint, token) {
const url = endpoint.getGraphQLRoot();
let {environment, network} = relayEnvironmentPerURL.get(url) || {};
tokenPerURL.set(url, token);
if (!environment) {
if (!token) {
throw new Error(`You must authenticate to ${endpoint.getHost()} first.`);
}
const source = new RecordSource();
const store = new Store(source);
network = Network.create(this.getFetchQuery(endpoint, token));
environment = new Environment({network, store});
relayEnvironmentPerURL.set(url, {environment, network});
}
return environment;
}
static getFetchQuery(endpoint, token) {
const url = endpoint.getGraphQLRoot();
tokenPerURL.set(url, token);
let fetch = fetchPerURL.get(url);
if (!fetch) {
fetch = createFetchQuery(url);
fetchPerURL.set(fetch);
}
return fetch;
}
}
|
JavaScript
| 0 |
@@ -1450,16 +1450,124 @@
lear();%0A
+ relayEnvironmentPerURL.clear();%0A tokenPerURL.clear();%0A fetchPerURL.clear();%0A responsesByQuery.clear();%0A
%7D%0A%0Afunct
|
d59de7b5bec9b57a21b0f297ddeba8d4e2949da1
|
Test if member exists (#224)
|
src/define/class/attributes/check.js
|
src/define/class/attributes/check.js
|
/**
* @file Attributes management in a class
*/
/*#ifndef(UMD)*/
"use strict";
/*global _gpfArrayForEach*/ // Almost like [].forEach (undefined are also enumerated)
/*global _gpfAttribute*/ // Shortcut for gpf.attributes.Attribute
/*global _GpfClassDefinition*/ // Class definition
/*global _gpfErrorDeclare*/ // Declare new gpf.Error names
/*global _gpfIsArrayLike*/
/*#endif*/
// Done as a feature
_gpfErrorDeclare("define/class/attributes", {
/**
* ### Summary
*
* The attributes are set on an unknwon member
*
* ### Description
*
* Attributes are allowed only on existing members or at the class level using $attributes
*/
unknownAttributesSpecification: "Unknown attributes specification",
/**
* ### Summary
*
* The attributes specification is invalid
*
* ### Description
*
* Attributes are specified using an array of {@link gpf.attributes.Attribute} instances
*/
invalidAttributesSpecification: "Invalid attributes specification"
});
//region define/class/check
var _GPF_DEFINE_CLASS_ATTRIBUTES_SPEFICIATION = "attributes",
_gpfDefineClassAttributesClassCheckMemberName = _GpfClassDefinition.prototype._checkMemberName,
_gpfDefineClassAttributesClassCheckMemberValue = _GpfClassDefinition.prototype._checkMemberValue,
_gpfDefineClassAttributesClassCheck$Property = _GpfClassDefinition.prototype._check$Property;
Object.assign(_GpfClassDefinition.prototype, {
/**
* Given the member name, tells if the property introduces attributes
*
* @param {String} name property name
* @return {String|undefined} Real property name if attributes specification, undefined otherwise
*/
_isAttributeSpecification: function (name) {
var length = name.length;
if (name.charAt(0) === "[" && name.charAt(length - 1) === "]") {
return name.substr(1, length - 2);
}
},
/** @inheritdoc */
_checkMemberName: function (name) {
var attributeName = this._isAttributeSpecification(name);
if (attributeName) {
_gpfDefineClassAttributesClassCheckMemberName.call(this, attributeName);
} else {
_gpfDefineClassAttributesClassCheckMemberName.call(this, name);
}
},
/**
* Verify that the attributes specification fits the requirements:
* - Must be an array
* - The array must contain only instances of {@link gpf.attributes.Attribute}
*
* @param {*} attributes The attributes specification to validate
* @throws {gpf.Error.InvalidAttributesSpecification}
*/
_checkAttributesSpecification: function (attributes) {
if (!_gpfIsArrayLike(attributes)) {
gpf.Error.invalidAttributesSpecification();
}
_gpfArrayForEach(attributes, function (attribute) {
if (!(attribute instanceof _gpfAttribute)) {
gpf.Error.invalidAttributesSpecification();
}
});
},
/** @inheritdoc */
_checkMemberValue: function (name, value) {
if (this._isAttributeSpecification(name)) {
this._checkAttributesSpecification(value);
} else {
_gpfDefineClassAttributesClassCheckMemberValue.call(this, name, value);
}
},
/** @inheritdoc */
_check$Property: function (name, value) {
if (_GPF_DEFINE_CLASS_ATTRIBUTES_SPEFICIATION === name) {
this._checkAttributesSpecification(value);
} else {
_gpfDefineClassAttributesClassCheck$Property.call(this, name, value);
}
}
});
_GpfClassDefinition.prototype._allowed$Properties.push(_GPF_DEFINE_CLASS_ATTRIBUTES_SPEFICIATION);
//endregion
|
JavaScript
| 0.000001 |
@@ -395,16 +395,83 @@
feature
+ 'on top' of normal class definition to be able to remove it easily
%0A%0A_gpfEr
@@ -1662,24 +1662,22 @@
g%7D name
-property
+Member
name%0A
@@ -1997,32 +1997,457 @@
%7D%0A %7D,%0A%0A
+ /**%0A * Given the member name, tells if it exists%0A *%0A * @param %7BString%7D name property name%0A * @throws %7Bgpf.Error.unknownAttributesSpecification%7D%0A */%0A _checkMemberExist: function (name) %7B%0A if ((!this._extend %7C%7C this._extend.prototype%5Bname%5D === undefined)%0A && !this._initialDefinition.hasOwnProperty(name)) %7B%0A gpf.Error.unknownAttributesSpecification();%0A %7D%0A %7D,%0A%0A
/** @inherit
@@ -2584,24 +2584,24 @@
buteName) %7B%0A
-
@@ -2669,24 +2669,75 @@
ibuteName);%0A
+ this._checkMemberExist(attributeName);%0A
%7D el
|
da184f002417a7c911678831d972a5a668eb6b8d
|
Remove unnecessary pre-zip task.
|
gulp-tasks/zip.js
|
gulp-tasks/zip.js
|
/**
* External dependencies
*/
import gulp from 'gulp';
import zip from 'gulp-zip';
import del from 'del';
import fs from 'fs';
import path from 'path';
import getRepoInfo from 'git-repo-info';
function getPluginVersion() {
return fs.readFileSync( path.resolve( __dirname, '../google-site-kit.php' ), 'utf8' )
.match( /Version:\s+([0-9\.\w-]+)/ )
[ 1 ];
}
function getGit() {
const { abbreviatedSha, branch, committerDate } = getRepoInfo();
return {
branch: branch.replace( /[\\\/]/, '|' ),
date: committerDate.replace( 'T', '~' ).replace( /\..*/, '' ),
shortSha: abbreviatedSha,
};
}
function generateFilename() {
const version = getPluginVersion();
const { branch, date, shortSha } = getGit();
return `google-site-kit.v${ version }:${ branch }@${ shortSha }_${ date }.zip`;
}
gulp.task( 'pre-zip', () => {
del.sync( [ './release/google-site-kit/**' ] );
return gulp.src( 'release/**' )
.pipe( gulp.dest( 'release/google-site-kit/' ) );
} );
gulp.task( 'zip', () => {
const filename = generateFilename();
del.sync( path.resolve( __dirname, `../${ filename }` ) );
gulp.src(
[ 'release/google-site-kit/**' ],
{ base: 'release/' }
)
.pipe( zip( generateFilename() ) )
.pipe( gulp.dest( './' ) );
// eslint-disable-next-line no-console
console.log( `Generated ${ filename }` );
} );
|
JavaScript
| 0.000011 |
@@ -798,178 +798,8 @@
%0A%7D%0A%0A
-%0Agulp.task( 'pre-zip', () =%3E %7B%0A%09del.sync( %5B './release/google-site-kit/**' %5D );%0A%0A%09return gulp.src( 'release/**' )%0A%09%09.pipe( gulp.dest( 'release/google-site-kit/' ) );%0A%7D );
%0A%0Agu
|
08cbe66f0fa27f2989cb1e6e41404a1e32663d20
|
Update controller.js
|
generators/app/templates/model/controller.js
|
generators/app/templates/model/controller.js
|
const Controller = require('../../lib/controller');
const <%= model.camelName %>Model = require('./<%= model.slugName %>-facade');
class <%= model.pascalName %>Controller extends Controller {}
module.exports = new <%= model.pascalName %>Controller(<%= model.camelName %>Model);
|
JavaScript
| 0.000001 |
@@ -73,21 +73,22 @@
lName %25%3E
-Mo
+Faca
de
-l
= requ
@@ -272,12 +272,13 @@
e %25%3E
-Mo
+Faca
de
-l
);%0A
|
7264bad40c2558c95883225193823e75b5280181
|
Replace deprecated node type simpleSelector with selector
|
lib/rules/placeholder-in-extend.js
|
lib/rules/placeholder-in-extend.js
|
'use strict';
var helpers = require('../helpers');
module.exports = {
'name': 'placeholder-in-extend',
'defaults': {},
'detect': function (ast, parser) {
var result = [];
ast.traverseByType('atkeyword', function (keyword, i, parent) {
keyword.forEach(function (item) {
if (item.content === 'extend') {
parent.forEach('simpleSelector', function (selector) {
var placeholder = false;
selector.content.forEach(function (selectorPiece) {
if (selectorPiece.type === 'placeholder') {
placeholder = true;
}
});
if (!placeholder) {
result = helpers.addUnique(result, {
'ruleId': parser.rule.name,
'line': selector.start.line,
'column': selector.start.column,
'message': '@extend must be used with a %placeholder',
'severity': parser.severity
});
}
});
}
});
});
return result;
}
};
|
JavaScript
| 0 |
@@ -358,14 +358,8 @@
h('s
-impleS
elec
|
0ca29231468b9d670858b14a638e1fa32d1e7bda
|
Update mano-legacy package
|
node_modules/mano-legacy/reset-controls.js
|
node_modules/mano-legacy/reset-controls.js
|
'use strict';
var dispatch = require('./dispatch-event')
, forEach = Array.prototype.forEach
, resetInput, resetValue, resetSelect, resetOption;
resetOption = function (el) {
var nu, old = el.selected;
if (el.hasAttribute) nu = el.hasAttribute('selected');
else nu = Boolean(el.getAttribute('select'));
if (old === nu) return false;
el.selected = nu;
return true;
};
resetValue = function (el) {
var nu = el.getAttribute('value') || '';
if (el.value === nu) return;
el.value = nu;
dispatch(el, 'change');
};
resetSelect = function (el) {
var changed;
forEach.call(el.options, function (option) {
if (resetOption(option)) changed = true;
});
if (changed) dispatch(el, 'change');
};
resetInput = function (input) {
var old, nu;
switch (input.type) {
case 'checkbox':
case 'radio':
old = input.checked;
if (input.hasAttribute) nu = input.hasAttribute('checked');
else nu = Boolean(input.getAttribute('checked'));
if (old !== nu) {
input.checked = nu;
dispatch(input, 'change');
}
return;
case 'button':
case 'image':
case 'reset':
case 'submit':
return;
default:
resetValue(input);
}
};
module.exports = function (el) {
if (!el || !el.nodeName) throw new TypeError(el + " is not a DOM Node");
switch (el.nodeName.toLowerCase()) {
case 'input':
resetInput(el);
return;
case 'textarea':
resetValue(el);
return;
case 'select':
resetSelect(el);
return;
case 'option':
case 'br':
case 'button':
case 'hr':
case 'img':
case 'object':
case 'video':
return;
default:
if (typeof el.getElementsByTagName !== 'function') return;
forEach.call(el.getElementsByTagName('input'), resetInput);
forEach.call(el.getElementsByTagName('select'), resetSelect);
forEach.call(el.getElementsByTagName('textarea'), resetValue);
}
};
|
JavaScript
| 0 |
@@ -118,16 +118,30 @@
etValue,
+ resetContent,
resetSe
@@ -159,16 +159,16 @@
Option;%0A
-
%0AresetOp
@@ -531,24 +531,181 @@
ange');%0A%7D;%0A%0A
+resetContent = function (el) %7B%0A%09var nu = el.firstChild ? el.firstChild.data : '';%0A%09if (el.value === nu) return;%0A%09el.value = nu;%0A%09dispatch(el, 'change');%0A%7D;%0A%0A
resetSelect
@@ -1521,21 +1521,23 @@
%0A%09%09reset
-Value
+Content
(el);%0A%09%09
@@ -1953,21 +1953,23 @@
), reset
-Value
+Content
);%0A%09%7D%0A%7D;
|
17d77aa39ff76bbc1360a9191c68c7e4f7a4052e
|
Update logging for slack API
|
dist/api/slack/index.js
|
dist/api/slack/index.js
|
const express = require('express');
const SlackBot = require('slackbots');
const Logger = require('../../lib/logger');
const NODE_ENV = process.env.NODE_ENV || 'development';
let log = new Logger(NODE_ENV === 'production' ? 4 : (NODE_ENV === 'development' ? 1 : 2));
let router = express.Router();
/**
* @api {get} /api/slack Get channels, groups, and users from Slack
* @apiName GetSlackInfo
* @apiGroup Slack
*
* @apiSuccess {Object} channels Hash of channel ids to channel names
* @apiSuccess {Object} groups Hash of group ids to group names
* @apiSuccess {Object} users Hash of user ids to user names
*/
router.get('', (req, res) => {
try {
let bot = new SlackBot({ token: req.query.token });
log.debug('Retrieving Slack information');
let slack = {
channels: {},
groups: {},
users: {}
};
bot.on('start', () => {
Promise.all([bot.getChannels(), bot.getGroups(), bot.getUsers()])
.then(values => {
values[0].channels
.filter(channel =>
channel['is_channel'] && channel['is_member'])
.forEach(channel =>
{ slack.channels[channel.id] = `#${channel.name}`; });
values[1].groups
.filter(group =>
group['is_group'] &&
!group['is_archived'] &&
group['is_open'] &&
!group['is_mpim'])
.forEach(group =>
{ slack.groups[group.id] = group.name; });
values[2].members
.filter(member =>
!member.deleted && !member['is_bot'])
.forEach(member =>
{ slack.users[member.id] = `@${member.name}`; });
log.debug(`Returning ${slack.channels.length} channels, ${slack.groups.length} groups, and ${slack.users.length} users`);
return res.json(slack);
})
.catch(e => res.status(500).end(e))
.then(() => bot.close());
});
} catch (e) {
log.error(e);
return res.status(500).end(e);
}
});
/**
* @api {get} /api/slack/user Get user info from token
* @apiName GetUserInfo
* @apiGroup Slack
*
* @apiSuccess {String} id User ID
* @apiSuccess {String} name User's username
* @apiSuccess {String} realName User's real name
* @apiSuccess {String} imageUrl URL of user's profile image
*/
router.get('/user', (req, res) => {
log.debug('Looking up user info');
try {
let bot = new SlackBot({ token: req.query.token });
bot.on('start', () => {
bot.getUser(bot.self.name)
.then(user => {
log.debug(`Returning user info for ${bot.self.name}`);
return res.json({
id: bot.self.id,
name: bot.self.name,
realName: user.profile['real_name'],
imageUrl: user.profile['image_original']
});
})
.catch(() => res.status(500).end())
.then(() => bot.close());
});
} catch (e) {
log.error(e);
return res.status(500).end(e);
}
});
module.exports = router;
|
JavaScript
| 0 |
@@ -1992,20 +1992,28 @@
ug(%60
-Returning $%7B
+Found $%7BObject.keys(
slac
@@ -2022,16 +2022,17 @@
channels
+)
.length%7D
@@ -2044,16 +2044,28 @@
nels, $%7B
+Object.keys(
slack.gr
@@ -2068,16 +2068,17 @@
k.groups
+)
.length%7D
@@ -2092,16 +2092,28 @@
, and $%7B
+Object.keys(
slack.us
@@ -2115,16 +2115,17 @@
ck.users
+)
.length%7D
|
328136743fc1aaa3c93c0bb44ffd47061cbc5221
|
Update file.js
|
lib/file.js
|
lib/file.js
|
'use strict';
var path = require('path');
var fs = require('fs');
// File is responsible to gather all information related to a given parsed file, as:
// - its dir and name
// - its content
// - the search paths where referecned resource will be looked at
// - the list of parsed blocks
//
//
// Returns an array object of all the directives for the given html.
// Each item of the array has the following form:
//
//
// {
// type: 'css',
// dest: 'css/site.css',
// src: [
// 'css/normalize.css',
// 'css/main.css'
// ],
// raw: [
// ' <!-- build:css css/site.css -->',
// ' <link rel="stylesheet" href="css/normalize.css">',
// ' <link rel="stylesheet" href="css/main.css">',
// ' <!-- endbuild -->'
// ]
// }
//
// Note also that dest is expressed relatively from the root. I.e., if the block starts with:
// <!-- build:css /foo/css/site.css -->
// then dest will equal foo/css/site.css (note missing trailing /)
//
var getBlocks = function (content) {
// start build pattern: will match
// * <!-- build:[target] output -->
// * <!-- build:[target](alternate search path) output -->
// The following matching param are set when there's a match
// * 0 : the whole matched expression
// * 1 : the target (i.e. type)
// * 2 : the alternate search path
// * 3 : the output
//
var regbuild = /<!--\s*build:(\w+)(?:\(([^\)]+)\))?\s*([^\s]+)\s*-->/;
// end build pattern -- <!-- endbuild -->
var regend = /<!--\s*endbuild\s*-->/;
var lines = content.replace(/\r\n/g, '\n').split(/\n/);
var block = false;
var sections = [];
var last;
lines.forEach(function (l) {
var indent = (l.match(/^\s*/) || [])[0];
var build = l.match(regbuild);
var endbuild = regend.test(l);
var startFromRoot = false;
// discard empty lines
if (build) {
block = true;
// Handle absolute path (i.e. with respect to the server root)
// if (build[3][0] === '/') {
// startFromRoot = true;
// build[3] = build[3].substr(1);
// }
last = {
type: build[1],
dest: build[3],
startFromRoot: startFromRoot,
indent: indent,
searchPath: [],
src: [],
raw: []
};
if (build[2]) {
// Alternate search path
last.searchPath.push(build[2]);
}
}
// Check IE conditionals
var isConditionalStart = l.match(/<!--\[[^\]]+\]>/);
var isConditionalEnd = l.match(/<!\[endif\]-->/);
if (block && isConditionalStart) {
last.conditionalStart = isConditionalStart;
}
if (block && isConditionalEnd) {
last.conditionalEnd = isConditionalEnd;
}
// switch back block flag when endbuild
if (block && endbuild) {
last.raw.push(l);
sections.push(last);
block = false;
}
if (block && last) {
var asset = l.match(/(href|src)=["']([^'"]+)["']/);
if (asset && asset[2]) {
last.src.push(asset[2]);
var media = l.match(/media=['"]([^'"]+)['"]/);
// FIXME: media attribute should be present for all members of the block *and* having the same value
if (media) {
last.media = media[1];
}
// preserve defer attribute
var defer = / defer/.test(l);
if (defer && last.defer === false || last.defer && !defer) {
throw new Error('Error: You are not suppose to mix deferred and non-deferred scripts in one block.');
} else if (defer) {
last.defer = true;
} else {
last.defer = false;
}
// preserve async attribute
var async = / async/.test(l);
if (async && last.async === false || last.async && !async) {
throw new Error('Error: You are not suppose to mix asynced and non-asynced scripts in one block.');
} else if (async) {
last.async = true;
} else {
last.async = false;
}
// RequireJS uses a data-main attribute on the script tag to tell it
// to load up the main entry point of the amp app
//
// If we find one, we must record the name of the main entry point,
// as well the name of the destination file, and treat
// the furnished requirejs as an asset (src)
var main = l.match(/data-main=['"]([^'"]+)['"]/);
if (main) {
throw new Error('require.js blocks are no more supported.');
}
}
last.raw.push(l);
}
});
return sections;
};
module.exports = function (filepath) {
this.dir = path.dirname(filepath);
this.name = path.basename(filepath);
// By default referenced content will be looked at relative to the location
// of the file
this.searchPath = [this.dir];
this.content = fs.readFileSync(filepath).toString();
// Let's parse !!!
this.blocks = getBlocks(this.content);
};
|
JavaScript
| 0 |
@@ -2496,16 +2496,37 @@
%5E%5C%5D%5D+%5C%5D%3E
+%3C!--%3E%7C%3C!--%5C%5B%5B%5E%5C%5D%5D+%5C%5D%3E
/);%0A
|
9018a26630c33314dd976f697c4cafc734093a09
|
remove debug log from server
|
lib/hariko/server.js
|
lib/hariko/server.js
|
var _ = require('lodash'),
express = require('express'),
http = require('http'),
bodyParser = require('body-parser'),
colors = require('colors');
var selfAssertive = require('./server-middleware/self-assertive'),
cors = require('./server-middleware/cors'),
logging = require('./server-middleware/logging'),
routing = require('./server-middleware/routing'),
proxy = require('./server-middleware/proxy');
var logger = require('../logger');
function HarikoServer (resource, options) {
if (!resource) throw new Error('Undefined resources. Server cannot run.');
this.resource = resource;
this.options = _.defaults(options, {
port: 3000,
host: 'localhost',
cors: false,
proxy: false,
verbose: false
});
this.app = express();
}
HarikoServer.prototype = {
setup: function () {
if (this.options.verbose) {
this.app.all('*', logging());
}
if (this.options.cors) {
var corsOpts = typeof this.options.cors === 'object' ? this.options.cors : {};
this.app.use(cors(corsOpts));
}
if (this.options.proxy) {
this.app.all('*', proxy(this.options.proxy, this.resource));
}
this.app.use(bodyParser.urlencoded({ extended: true }));
this.app.use(bodyParser.json());
this.app.use(selfAssertive());
this.app.use(routing(this.resource));
},
start: function (cb) {
logger.verbose('Starting server ...');
logger.verbose(' options:', this.options);
this.setup();
this._server = http.createServer(this.app);
this._server.on('listening', function () {
var url = 'http://' + this.options.host + ':' + this.options.port;
logger.info('Running Hariko Server ... ' + url.cyan);
}.bind(this));
this._server.on('close', function () {
logger.info('Stoping Hariko Server')
}.bind(this));
this._server.listen(this.options.port, this.options.host || 'localhost', function () { if (cb) cb(); });
},
stop: function () {
console.log(this._server.close);
this._server.close();
this._server = null;
},
reload: function (entries) {
this.stop();
this.start(entries);
}
};
exports.HarikoServer = HarikoServer;
exports.create = function (entries, options) {
return new HarikoServer(entries, options);
}
|
JavaScript
| 0.000001 |
@@ -2050,45 +2050,8 @@
) %7B%0A
- console.log(this._server.close);%0A
|
872d7987ae136f6c886a8b7b414340c4d1b6eb63
|
remove class
|
html/index.js
|
html/index.js
|
var React = require('react');
var ReactDOM = require('react-dom');
var $ = require('jquery');
var _ = require('lodash');
var querystring = require('querystring');
var Alert = require('react-bootstrap').Alert;
var Grid = require('react-bootstrap').Grid;
var Row = require('react-bootstrap').Row;
var Col = require('react-bootstrap').Col;
var Map = require('react-leaflet').Map;
var TileLayer = require('react-leaflet').TileLayer;
var Promise = (window && window.Promise) || require('promise-js');
function geocoding(searchTerm){
return new Promise(function(resolve, reject) {
var url = 'http://nominatim.openstreetmap.org/search.php?' + querystring.stringify({
q:searchTerm,
format:'jsonv2'
});
$.ajax(url, {error:reject, success:resolve });
});
}
var ViewShed = React.createClass({
render: function(){
return (
<Grid bsClass="fill-height" fluid={true} style={{height:"100%"}}>
<Row>
<Col md={8}><code><{'Col xs={12} md={8}'} /></code></Col>
<Col md={4}><code><{'Col xs={6} md={4}'} /></code></Col>
</Row>
<Row style={{height:"100%"}}>
<Col md={12} style={{height:"100%"}}>
<Map center={[51.505, -0.09]} zoom={12} style={{height:"100%"}}>
<TileLayer url='http://{s}.tile.osm.org/{z}/{x}/{y}.png' attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'/>
</Map>
</Col>
</Row>
</Grid>
)
}
});
$(function(){ReactDOM.render(<ViewShed/>, document.getElementById("application"));})
_.extend(window, {
'_':_,
'geocoding':geocoding,
'$':$,
'Promise':Promise
});
|
JavaScript
| 0.00035 |
@@ -855,30 +855,8 @@
Grid
- bsClass=%22fill-height%22
flu
|
fb1c405ef61cf4c3cc64cbccda81fe483f1f29cb
|
fix filter node able to mutate to non existent filter type
|
src/nodes/filterNode.js
|
src/nodes/filterNode.js
|
var Utils = require('asNEAT/utils')['default'],
Node = require('asNEAT/nodes/node')['default'],
name = "FilterNode",
freqMin = 0,
freqMax = 1500,
qMin = 0.0001,
qMax = 20,
gainMin = -5,
gainMax = 5;
var FilterNode = function(parameters) {
Node.call(this, parameters);
};
FilterNode.prototype = Object.create(Node.prototype);
FilterNode.prototype.name = name;
FilterNode.prototype.defaultParameters = {
type: 0,
frequency: 500,
detune: 0,
q: 1,
gain: 1,
mutatableParameters: [{
name: 'type',
mutationDeltaChance: 0,
randomMutationRange: {min: 0, max: 8},
allowRandomInverse: false,
discreteMutation: true
},{
name: 'frequency',
mutationDeltaChance: 0.8,
mutationDeltaInterpolationType: Utils.InterpolationType.EXPONENTIAL,
mutationDelta: {min: [10, 100], max: [300, 700]},
mutationDeltaAllowableRange: {min: freqMin, max: freqMax},
allowDeltaInverse: true,
randomMutationRange: {min: freqMin, max: freqMax}
}],
connectableParameters: [{
name: "frequency",
deltaRange: {min: [10, 100], max: [300, 700]},
randomRange: {min: freqMin, max: freqMax},
mutationDeltaAllowableRange: {min: freqMin, max: freqMax},
},{
name: "Q",
deltaRange: {min: [0.0001, 1], max: [3, 10]},
randomRange: {min: qMin, max: qMax},
mutationDeltaAllowableRange: {min: qMin, max: qMax},
},{
name: "gain",
deltaRange: {min: [0.1, 1], max: [2, 6]},
randomRange: {min: gainMin, max: gainMax},
mutationDeltaAllowableRange: {min: gainMin, max: gainMax},
}]
};
FilterNode.prototype.clone = function() {
return new FilterNode({
id: this.id,
type: this.type,
frequency: this.frequency,
detune: this.detune,
q: this.q,
gain: this.gain,
mutatableParameters: _.cloneDeep(this.mutatableParameters)
});
};
// Refreshes the cached node to be played again
FilterNode.prototype.refresh = function(contextPair) {
refresh.call(this, contextPair);
};
FilterNode.prototype.offlineRefresh = function(contextPair) {
refresh.call(this, contextPair, "offline");
};
function refresh(contextPair, prefix) {
var node = contextPair.context.createBiquadFilter();
node.type = this.type;
node.frequency.value = this.frequency;
node.detune.value = this.detune;
node.Q.value = this.q;
node.gain.value = this.gain;
var nodeName = prefix ? (prefix+'Node') : 'node';
this[nodeName] = node;
}
FilterNode.prototype.getParameters = function() {
return {
name: name,
id: this.id,
type: FilterNode.TYPES.nameFor(this.type),
frequency: this.frequency,
detune: this.detune,
q: this.q,
gain: this.gain,
};
};
FilterNode.prototype.toString = function() {
return this.id+": FilterNode("+this.type+","+this.frequency.toFixed(2)+")";
};
FilterNode.TYPES = [
"lowpass",
"highpass",
"bandpass",
"lowshelf",
"highshelf",
"peaking",
"notch",
"allpass"
];
FilterNode.TYPES.nameFor = function(type) {
if (typeof type ==="string") return type;
return FilterNode.TYPES[type];
};
FilterNode.random = function() {
var typeI = Utils.randomIndexIn(0,FilterNode.TYPES.length),
// A0 to C8
freq = Utils.randomIn(freqMin, freqMax),
q = Utils.randomIn(qMin, qMax),
gain = Utils.randomIn(gainMin, gainMax);
// frequency - 350Hz, with a nominal range of 10 to the Nyquist frequency (half the sample-rate).
// Q - 1, with a nominal range of 0.0001 to 1000.
// gain - 0, with a nominal range of -40 to 40.
return new FilterNode({
type: FilterNode.TYPES[typeI],
frequency: freq,
// TODO: specefic ranges based on type
q: q,
gain: gain
//detune: 0,
});
};
export default FilterNode;
|
JavaScript
| 0 |
@@ -611,17 +611,17 @@
0, max:
-8
+7
%7D,%0A
|
60bbf94aa83c0a218259e04647fb4e594408ff9a
|
Improve jsdoc for else/orElse, use then directly
|
lib/flow.js
|
lib/flow.js
|
/** @license MIT License (c) copyright 2010-2013 original author or authors */
/**
* Licensed under the MIT License at:
* http://www.opensource.org/licenses/mit-license.php
*
* @author Brian Cavalier
* @author John Hann
*/
(function(define) { 'use strict';
define(function() {
return function flow(Promise) {
/**
* Handle the ultimate fulfillment value or rejection reason, and assume
* responsibility for all errors. If an error propagates out of handleResult
* or handleFatalError, it will be rethrown to the host, resulting in a
* loud stack track on most platforms and a crash on some.
* @param {function?} handleResult
* @param {function?} handleError
* @returns {undefined}
*/
Promise.prototype.done = function(handleResult, handleError) {
this.then(handleResult, handleError)['catch'](this._fatal);
};
/**
* Ensures that onFulfilledOrRejected will be called regardless of whether
* this promise is fulfilled or rejected. onFulfilledOrRejected WILL NOT
* receive the promises' value or reason. Any returned value will be disregarded.
* onFulfilledOrRejected may throw or return a rejected promise to signal
* an additional error.
* @param {function} onFulfilledOrRejected handler to be called regardless of
* fulfillment or rejection
* @returns {Promise}
*/
Promise.prototype['finally'] = Promise.prototype.ensure = function(onFulfilledOrRejected) {
return typeof onFulfilledOrRejected === 'function'
? this.then(injectHandler, injectHandler)['yield'](this)
: this;
function injectHandler() {
// prevent argument passing to finally handler
return onFulfilledOrRejected();
}
};
/**
* Recover from a failure by returning a defaultValue
* @param {*} defaultValue
* @returns {Promise} a promise that fulfills in all cases
*/
Promise.prototype['else'] = Promise.prototype.orElse = function(defaultValue) {
return this['catch'](function() {
return defaultValue;
});
};
/**
* Shortcut for .then(function() { return value; })
* @param {*} value
* @return {Promise} a promise that:
* - is fulfilled if value is not a promise, or
* - if value is a promise, will fulfill with its value, or reject
* with its reason.
*/
Promise.prototype['yield'] = function(value) {
return this.then(function() {
return value;
});
};
/**
* Runs a side effect when this promise fulfills, without changing the
* fulfillment value.
* @param {function} onFulfilledSideEffect
* @returns {Promise}
*/
Promise.prototype.tap = function(onFulfilledSideEffect) {
return this.then(onFulfilledSideEffect)['yield'](this);
};
return Promise;
};
});
}(typeof define === 'function' && define.amd ? define : function(factory) { module.exports = factory(); }));
|
JavaScript
| 0 |
@@ -1750,24 +1750,86 @@
alue
-%0A%09%09 * @param %7B*%7D
+. If defaultValue%0A%09%09 * is a promise, it's fulfillment value will be used. If
def
@@ -1841,69 +1841,165 @@
alue
+ is
%0A%09%09 *
-@returns %7BPromise%7D a promise that fulfills in all ca
+a promise that rejects, the returned promise will reject with the%0A%09%09 * same reason.%0A%09%09 * @param %7B*%7D defaultValue%0A%09%09 * @returns %7BPromise%7D new promi
se
-s
%0A%09%09
@@ -2097,26 +2097,30 @@
urn this
-%5B'catch'%5D(
+.then(void 0,
function
|
b77c0878859341d7717b2f4d8ba4393004069daf
|
Update stock.js
|
html/stock.js
|
html/stock.js
|
String.prototype.format = function () {
var s = this,
i = arguments.length;
while (i--) {
s = s.replace(new RegExp('\\{' + i + '\\}', 'gm'), arguments[i]);
}
return s;
};
$.fn.fade = function () {
var src = arguments[0];
this.fadeOut('slow', function () {
$(this).attr("src", src).fadeIn('slow');
});
};
function createCharts(row, stockNum, scheme) {
var output = "<tr>";
var newUrl;
var id;
if (stockNum != undefined) {
$.each(CHARTTYPES, function (key, chart) {
id = row + "_" + key;
newUrl = chart.url.format(stockNum, scheme) + '&chartwidth=' + CONFIG.imgWidth + '&chartheight=' + CONFIG.imgHeight + '&ttt=' + new Date().getTime();
if (chart.active) {
output = output + TEMPLATES.img_holder.format(id, newUrl, id);
}
})
console.log("Stock " + stockNum + " added.");
} else {
output = output + TEMPLATES.separater.format(CONFIG.separatorColor);
}
output = output + "</tr>";
return output;
}
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function reload(id) {
var imgTag = $("#" + id);
newUrl = imgTag.attr("src").replace(/&ttt=.*$/g, '&ttt=' + new Date().getTime());
imgTag.fade(newUrl);
};
var TEMPLATES = {
separater: '<td colspan="99" bgcolor="{0}"> </td>',
img_holder: "<td><img id='stockImage_{0}' src='{1}' onclick=\"javascript:reload('stockImage_{2}')\"/></td>"
};
var CHARTTYPES = {
// charts are ordered
three_month: {
active: true,
url: "http://charts.aastocks.com/servlet/Charts?fontsize=11&15MinDelay=T&lang=1&titlestyle=1&vol=1&scheme={1}&com=100&stockid={0}.HK&period=7&type=1&logoStyle=1",
},
ten_day_per_one_hr: {
active: true,
url: "http://charts.aastocks.com/servlet/Charts?fontsize=11&15MinDelay=T&lang=1&titlestyle=1&vol=1&scheme={1}&com=100&stockid={0}.HK&period=4&type=1&logoStyle=1",
},
one_day_per_one_min: {
active: true,
url: "http://charts.aastocks.com/servlet/Charts?fontsize=11&15MinDelay=F&lang=1&titlestyle=1&vol=1&scheme={1}&com=100&stockid={0}.HK&period=5000&type=1&logoStyle=1",
}
};
var NIGHTMODE_SCHEME = {
ON: '3',
OFF: '1'
}
$(document).ready(function () {
if (!CONFIG.logEnable) {
console.log = function () {};
}
var scheme;
var container = $('.default');
console.log(container);
if (CONFIG.nightMode) {
scheme = NIGHTMODE_SCHEME.ON;
container.toggleClass('darkSwitch');
console.log('1 ' + CONFIG.nightMode);
} else {
scheme = NIGHTMODE_SCHEME.OFF;
container.toggleClass('lightSwitch');
console.log('2 ' + CONFIG.nightMode);
}
console.log(scheme);
$.each(WATCH_LIST, function (row, stockNum) {
$('#stockList > tbody:last-child').append(createCharts(row, stockNum, scheme));
});
setInterval(function () {
interval = getRandomInt(0, $('img').length);
$.each($('img'), function (index, value) {
if (!CONFIG.randomRefresh || index == interval) {;
reload($(this).attr("id"));
}
});
}, CONFIG.reloadIntervalInSecond * 1000);
});
|
JavaScript
| 0.000001 |
@@ -1481,19 +1481,27 @@
ee_month
-: %7B
+_with_sma:%EF%BD%9B
%0D%0A%09%09acti
@@ -1503,32 +1503,344 @@
%09active: true,%0D%0A
+%09%09url: %22http://charts.aastocks.com/servlet/Charts?fontsize=11&15MinDelay=T&lang=1&titlestyle=1&vol=1&Indicator=1&indpara1=10&indpara2=20&indpara3=50&indpara4=100&indpara5=150&scheme=%7B1%7D&com=100&stockid=%7B0%7D.HK&period=7&type=1&indicator3=10&ind3para1=112.88&logoStyle=1&%22,%0D%0A%09%7D,%0D%0A%09three_month: %7B%0D%0A%09%09active: false,%0D%0A
%09%09url: %22http://c
|
438233818e88d9383c6c4e17c4cbd6bdc6b23eb7
|
fix pulse navigation
|
src/redactions/pulse.js
|
src/redactions/pulse.js
|
/* global config */
import 'whatwg-fetch';
import find from 'lodash/find';
import compact from 'lodash/compact';
import flatten from 'lodash/flatten';
// We should merge the layerSpecPulse with the response of the layers
import layerSpecPulse from 'utils/layers/layerSpecPulse.json';
/**
* CONSTANTS
*/
const GET_LAYERS_SUCCESS = 'planetpulse/GET_LAYERS_SUCCESS';
const GET_LAYERS_ERROR = 'planetpulse/GET_LAYERS_ERROR';
const GET_LAYERS_LOADING = 'planetpulse/GET_LAYERS_LOADING';
const SET_ACTIVE_LAYER = 'planetpulse/SET_ACTIVE_LAYER';
/**
* REDUCER
*/
const initialState = {
layers: [],
loading: false,
error: false,
layerActive: null
};
export default function (state = initialState, action) {
switch (action.type) {
case GET_LAYERS_SUCCESS:
return Object.assign({}, state, { layers: action.payload, loading: false, error: false });
case GET_LAYERS_ERROR:
return Object.assign({}, state, { error: true, loading: false });
case GET_LAYERS_LOADING:
return Object.assign({}, state, { loading: true, error: false });
case SET_ACTIVE_LAYER:
return Object.assign({}, state, {
layerActive: (state.layerActive !== action.payload) ? action.payload : null
});
default:
return state;
}
}
/**
* ACTIONS
* - getLayers
* - setActiveDataset
*/
export function getLayers() {
function getLayerFromDataset(dataset) {
const hasVocabulary = dataset.attributes.vocabulary && dataset.attributes.vocabulary.length;
if (hasVocabulary) {
const vocabulary = dataset.attributes.vocabulary.find(v => v.attributes.name === 'legacy');
if (vocabulary) {
const hasRealtime = vocabulary.attributes.tags.includes('real_time');
debugger;
if (hasRealtime) {
return compact(dataset.attributes.layer.map((layer) => {
if (!layer.attributes.default && layer.attributes.staticImageConfig) {
const layerSpec = find(layerSpecPulse, { id: layer.attributes.id });
return Object.assign({}, layerSpec, layer.attributes);
}
return null;
}));
}
}
}
return null;
}
return (dispatch) => {
// Waiting for fetch from server -> Dispatch loading
dispatch({ type: GET_LAYERS_LOADING });
// TODO: remove the date now
fetch(new Request(`${config.API_URL}/dataset?application=rw&status=saved&includes=vocabulary,layer&page[size]=${Date.now() / 100000}`))
.then((response) => {
if (response.ok) return response.json();
throw new Error(response.statusText);
})
.then((response) => {
const datasets = response.data;
const layers = compact(flatten(datasets.map(getLayerFromDataset)));
dispatch({
type: GET_LAYERS_SUCCESS,
payload: layers
});
})
.catch((err) => {
// Fetch from server ko -> Dispatch error
dispatch({
type: GET_LAYERS_ERROR,
payload: err.message
});
});
};
}
export function toggleActiveLayer(id) {
return {
type: SET_ACTIVE_LAYER,
payload: id
};
}
|
JavaScript
| 0.000001 |
@@ -1636,134 +1636,8 @@
) %7B%0A
-%0A const hasRealtime = vocabulary.attributes.tags.includes('real_time');%0A debugger;%0A if (hasRealtime) %7B%0A
@@ -1693,26 +1693,24 @@
layer) =%3E %7B%0A
-
if
@@ -1774,26 +1774,24 @@
geConfig) %7B%0A
-
@@ -1845,28 +1845,15 @@
yer.
-attributes.
id %7D);%0A
-
@@ -1921,30 +1921,26 @@
;%0A
- %7D%0A
+%7D%0A
re
@@ -1962,25 +1962,13 @@
-
%7D));%0A
- %7D%0A
@@ -2157,16 +2157,16 @@
ate now%0A
-
fetc
@@ -2260,16 +2260,45 @@
y,layer&
+vocabulary%5Blegacy%5D=real_time&
page%5Bsiz
|
c4b34b08ac84d44f4c8c3181142810a98a38ba34
|
Fix ODR#742: Add switchDevices/postInstallCommands in the options list of install esx task
|
lib/task-data/tasks/install-esx.js
|
lib/task-data/tasks/install-esx.js
|
// Copyright 2015, EMC, Inc.
'use strict';
module.exports = {
friendlyName: 'Install Esx',
injectableName: 'Task.Os.Install.Esx',
implementsTask: 'Task.Base.Os.Install',
options: {
osType: 'esx', //readonly option, should avoid change it
profile: 'install-esx.ipxe',
installScript: 'esx-ks',
installScriptUri: '{{api.templates}}/{{options.installScript}}',
completionUri: '{{options.installScript}}',
rackhdCallbackScript: 'esx.rackhdcallback',
esxBootConfigTemplate: 'esx-boot-cfg',
esxBootConfigTemplateUri: '{{api.templates}}/{{options.esxBootConfigTemplate}}',
comport: 'com1',
comportaddress: '0x3f8', //com1=0x3f8, com2=0x2f8, com3=0x3e8, com4=0x2e8
version: null,
repo: '{{api.server}}/esxi/{{options.version}}',
hostname: 'localhost',
domain: 'rackhd',
rootPassword: "RackHDRocks!",
rootSshKey: null,
users: [],
networkDevices: [],
dnsServers: [],
installDisk: null
},
properties: {
os: {
hypervisor: {
type: 'esx'
}
}
}
};
|
JavaScript
| 0 |
@@ -1044,16 +1044,770 @@
sk: null
+,%0A%0A // If specified, this contains an array of objects with switchName and uplinks (optional)%0A // parameters. If 'uplinks' is omitted, the vswitch will be created with no uplinks.%0A // - switchName (required): The name of vswitch%0A // - uplinks (optional): The array of vmnic# devices to set as the uplinks%0A //%0A // example:%0A // %7B%0A // %22switchName%22: %22vSwitch0%22,%0A // %22uplinks%22: %5B%22vmnic0%22, %22vmnic1%22%5D%0A // %7D%0A switchDevices: %5B%5D,%0A%0A //If specified, this contains an array of string commands that will be run at the end of the%0A //post installation step. This can be used by the customer to tweak final system%0A //configuration.%0A postInstallCommands: %5B%5D
%0A %7D,%0A
|
c08a1fc1bf2f82de5f89e65bf3a278e5ed92a01b
|
fix kget composer info
|
lyric_engine_js/modules/kget.js
|
lyric_engine_js/modules/kget.js
|
const util = require('util');
const iconv = require('iconv-lite');
const he = require('he');
const rp = require('request-promise');
const striptags = require('striptags');
const LyricBase = require('../include/lyric_base');
const keyword = 'kget';
class Lyric extends LyricBase {
async find_lyric(url, html) {
const prefix = '<div id="lyric-trunk">';
const suffix = '</div>';
let lyric = this.find_string_by_prefix_suffix(html, prefix, suffix, false);
lyric = he.decode(lyric);
lyric = striptags(lyric);
lyric = lyric.trim();
this.lyric = lyric;
return true;
}
async find_info(url, html) {
const pattern = '<h1.*?>(.*)</h1>';
const value = this.get_first_group_by_pattern(html, pattern);
if (value) {
this.title = striptags(he.decode(value)).trim();
} else {
console.warn('Failed to parse title of url:', url);
return false;
}
const prefix = '<table class="lyric-data">';
const suffix = '</table>';
const table_str = this.find_string_by_prefix_suffix(html, prefix, suffix, false);
const patterns = {
'artist': '">([^<]*)</a></span></td></tr>',
'lyricist': 'td>([^<]*)<br></td></tr>',
'composer': 'td>([^<]*)<br></td></tr>',
}
for (let key in patterns) {
const key_for_pattern = patterns[key];
let value = this.get_first_group_by_pattern(table_str, key_for_pattern);
value = striptags(he.decode(value)).trim();
if (value) {
this[key] = value;
}
}
}
async parse_page() {
const url = this.url;
const html = await rp(url);
await this.find_lyric(url, html);
await this.find_info(url, html);
return true;
}
}
exports.keyword = keyword;
exports.Lyric = Lyric;
if (require.main === module) {
(async function() {
const url = 'http://www.kget.jp/lyric/11066/';
const obj = new Lyric(url);
const lyric = await obj.get();
console.log(lyric);
})();
}
|
JavaScript
| 0 |
@@ -1262,24 +1262,33 @@
lyricist': '
+%3E%E4%BD%9C%E8%A9%9E%3C/th%3E%3C
td%3E(%5B%5E%3C%5D*)%3Cb
@@ -1327,16 +1327,25 @@
oser': '
+%3E%E4%BD%9C%E6%9B%B2%3C/th%3E%3C
td%3E(%5B%5E%3C%5D
|
0ce6df417b6016687add2b7820b8786cf414a6be
|
rename `.hyperterm_modules` to `.hyperterm_plugins`
|
plugins.js
|
plugins.js
|
const { dialog } = require('electron');
const { homedir } = require('os');
const { resolve, basename } = require('path');
const { writeFileSync } = require('fs');
const config = require('./config');
const { sync: mkdirpSync } = require('mkdirp');
const { exec } = require('child_process');
const Config = require('electron-config');
const ms = require('ms');
const notify = require('./notify');
// local storage
const cache = new Config();
// modules path
const path = resolve(homedir(), '.hyperterm_modules');
const localPath = resolve(homedir(), '.hyperterm_modules', 'local');
// init plugin directories if not present
mkdirpSync(path);
mkdirpSync(localPath);
// caches
let plugins = config.getPlugins();
let paths = getPaths(plugins);
let id = getId(plugins);
let modules = requirePlugins();
function getId (plugins_) {
return JSON.stringify(plugins_);
}
const watchers = [];
// we listen on configuration updates to trigger
// plugin installation
config.subscribe(() => {
const plugins_ = config.getPlugins();
if (plugins !== plugins_) {
const id_ = getId(plugins_);
if (id !== id_) {
id = id_;
plugins = plugins_;
updatePlugins();
}
}
});
let updating = false;
function updatePlugins ({ force = false } = {}) {
if (updating) return notify('Plugin update in progress');
updating = true;
syncPackageJSON();
const id_ = id;
install((err) => {
updating = false;
if (err) {
console.error(err.stack);
notify(
'Error updating plugins.',
'Check `~/.hyperterm_modules/npm-debug.log` for more information.'
);
} else {
// flag successful plugin update
cache.set('plugins', id_);
// cache paths
paths = getPaths(plugins);
// clear require cache
clearCache();
// cache modules
modules = requirePlugins();
const loaded = modules.length;
const total = paths.plugins.length + paths.localPlugins.length;
const pluginVersions = JSON.stringify(getPluginVersions());
const changed = cache.get('plugin-versions') !== pluginVersions && loaded === total;
cache.set('plugin-versions', pluginVersions);
// notify watchers
if (force || changed) {
if (changed) {
notify(
'Plugins Updated',
'Restart the app or hot-reload with "Plugins" > "Reload Now" to enjoy the updates!'
);
} else {
notify(
'Plugins Updated',
'No changes!'
);
}
watchers.forEach((fn) => fn(err, { force }));
}
}
});
}
function getPluginVersions () {
const paths_ = paths.plugins.concat(paths.localPlugins);
return paths_.map((path) => {
let version = null;
try {
version = require(resolve(path, 'package.json')).version;
} catch (err) { }
return [
basename(path),
version
];
});
}
function clearCache (mod) {
for (const entry in require.cache) {
if (entry.indexOf(path) === 0 || entry.indexOf(localPath) === 0) {
delete require.cache[entry];
}
}
}
exports.updatePlugins = updatePlugins;
// we schedule the initial plugins update
// a bit after the user launches the terminal
// to prevent slowness
if (cache.get('plugins') !== id || process.env.HYPERTERM_FORCE_UPDATE) {
// install immediately if the user changed plugins
console.log('plugins have changed / not init, scheduling plugins installation');
setTimeout(() => {
updatePlugins();
}, 5000);
}
// otherwise update plugins every 5 hours
setInterval(updatePlugins, ms('5h'));
function syncPackageJSON () {
const dependencies = toDependencies(plugins);
const pkg = {
name: 'hyperterm-plugins',
description: 'Auto-generated from `~/.hyperterm.js`!',
private: true,
version: '0.0.1',
repository: 'zeit/hyperterm',
license: 'MIT',
homepage: 'https://hyperterm.org',
dependencies
};
const file = resolve(path, 'package.json');
try {
writeFileSync(file, JSON.stringify(pkg, null, 2));
} catch (err) {
alert(`An error occurred writing to ${file}`);
}
}
function alert (message) {
dialog.showMessageBox({
message,
buttons: ['Ok']
});
}
function toDependencies (plugins) {
const obj = {};
plugins.plugins.forEach((plugin) => {
const pieces = plugin.split('#');
obj[pieces[0]] = null == pieces[1] ? 'latest' : pieces[1];
});
return obj;
}
function install (fn) {
const prefix = 'darwin' === process.platform ? 'eval `/usr/libexec/path_helper -s` && ' : '';
exec(prefix + 'npm prune && npm install --production', {
cwd: path
}, (err, stdout, stderr) => {
if (err) alert(err.stack);
if (err) return fn(err);
fn(null);
});
}
exports.subscribe = function (fn) {
watchers.push(fn);
return () => {
watchers.splice(watchers.indexOf(fn), 1);
};
};
function getPaths () {
return {
plugins: plugins.plugins.map((name) => {
return resolve(path, 'node_modules', name.split('#')[0]);
}),
localPlugins: plugins.localPlugins.map((name) => {
return resolve(localPath, name);
})
};
}
// expose to renderer
exports.getPaths = getPaths;
// get paths from renderer
exports.getBasePaths = function () {
return { path, localPath };
};
function requirePlugins () {
const { plugins, localPlugins } = paths;
const load = (path) => {
let mod;
try {
mod = require(path);
if (!mod || (!mod.onApp && !mod.onWindow && !mod.onUnload &&
!mod.middleware &&
!mod.decorateConfig && !mod.decorateMenu &&
!mod.decorateTerm && !mod.decorateHyperTerm &&
!mod.decorateTab && !mod.decorateNotification &&
!mod.decorateNotifications && !mod.decorateTabs &&
!mod.decorateConfig)) {
notify('Plugin error!', `Plugin "${basename(path)}" does not expose any ` +
'HyperTerm extension API methods');
return;
}
return mod;
} catch (err) {
notify('Plugin error!', `Plugin "${basename(path)}" failed to load (${err.message})`);
}
};
return plugins.map(load)
.concat(localPlugins.map(load))
.filter(v => !!v);
}
exports.onApp = function (app) {
modules.forEach((plugin) => {
if (plugin.onApp) {
plugin.onApp(app);
}
});
};
exports.onWindow = function (win, app) {
modules.forEach((plugin) => {
if (plugin.onWindow) {
plugin.onWindow(app);
}
});
};
exports.decorateMenu = function (tpl) {
let decorated = tpl;
modules.forEach((plugin) => {
if (plugin.decorateMenu) {
const res = plugin.decorateMenu(decorated);
if (res) {
decorated = res;
} else {
console.error('incompatible response type for `decorateMenu`');
}
}
});
return decorated;
};
exports.decorateConfig = function (config) {
let decorated = config;
modules.forEach((plugin) => {
if (plugin.decorateConfig) {
const res = plugin.decorateConfig(decorated);
if (res) {
decorated = res;
} else {
console.error('incompatible response type for `decorateConfig`');
}
}
});
return decorated;
};
|
JavaScript
| 0.000001 |
@@ -495,22 +495,22 @@
perterm_
-module
+plugin
s');%0Acon
@@ -555,22 +555,22 @@
perterm_
-module
+plugin
s', 'loc
@@ -1544,22 +1544,22 @@
perterm_
-module
+plugin
s/npm-de
|
0ede51c40290113d7fe3323f037f17bd8588b579
|
Fix JS var
|
src/view/frontend/web/js/view/payment/method-renderer/hipay-cc.js
|
src/view/frontend/web/js/view/payment/method-renderer/hipay-cc.js
|
/*
* HiPay fullservice SDK
*
* NOTICE OF LICENSE
*
* This source file is subject to the MIT License
* that is bundled with this package in the file LICENSE.txt.
* It is also available through the world-wide-web at this URL:
* http://opensource.org/licenses/mit-license.php
*
* @copyright Copyright (c) 2016 - HiPay
* @license http://opensource.org/licenses/mit-license.php MIT License
*
*/
define(
[
'ko',
'jquery',
'HiPay_FullserviceMagento/js/view/payment/cc-form',
'hipay_tpp',
'mage/storage',
'Magento_Checkout/js/model/full-screen-loader'
],
function (ko, $,Component,TPP,storage,fullScreenLoader) {
'use strict';
return Component.extend({
defaults: {
template: 'HiPay_FullserviceMagento/payment/hipay-cc',
showCcForm: true,
apiUsernameTokenJs: window.checkoutConfig.payment.hipayCc.apiUsernameTokenJs ,
apiPasswordTokenJs: window.checkoutConfig.payment.hipayCc.apiPasswordTokenJs
},
placeOrderHandler: null,
validateHandler: null,
/**
* @param {Function} handler
*/
setPlaceOrderHandler: function (handler) {
this.placeOrderHandler = handler;
},
/**
* @param {Function} handler
*/
setValidateHandler: function (handler) {
this.validateHandler = handler;
},
/**
* @override
*/
initObservable: function () {
var self = this;
this._super();
this.showCcForm = ko.computed(function () {
return !(self.useOneclick() && self.customerHasCard()) ||
self.selectedCard() === undefined ||
self.selectedCard() === '';
}, this);
return this;
},
/**
* @returns {Boolean}
*/
isActive: function () {
return true;
},
/**
* @returns {Boolean}
*/
isShowLegend: function () {
return true;
},
context: function() {
return this;
},
hasSsCardType: function() {
return false;
},
getCcAvailableTypes: function() {
return window.checkoutConfig.payment.hipayCc.availableTypes;
},
/**
* @override
*/
getCode: function () {
return 'hipay_cc';
},
getData: function() {
return this._super();
},
/**
* Display error message
* @param {*} error - error message
*/
addError: function (error) {
if (_.isObject(error)) {
this.messageContainer.addErrorMessage(error);
} else {
this.messageContainer.addErrorMessage({
message: error
});
}
},
/**
* After place order callback
*/
afterPlaceOrder: function () {
$.mage.redirect(this.getAfterPlaceOrderUrl());
},
generateToken: function (data,event){
var self = this,
isTokenizeProcessing = null;
if (event) {
event.preventDefault();
}
if(this.validateHandler()){
if(this.creditCardToken()){
self.placeOrder(self.getData(),self.redirectAfterPlaceOrder);
return;
}
isTokenizeProcessing = $.Deferred();
$.when(isTokenizeProcessing).done(
function () {
self.placeOrder(self.getData(),self.redirectAfterPlaceOrder);
}
).fail(
function (error) {
self.addError(error);
}
);
fullScreenLoader.startLoader();
TPP.setTarget(window.checkoutConfig.payment.hipayCc.env);
TPP.setCredentials(apiUsernameTokenJs,apiPasswordTokenJs);
TPP.create({
card_number: this.creditCardNumber(),
cvc: this.creditCardVerificationNumber(),
card_expiry_month:this.creditCardExpMonth(),
card_expiry_year: this.creditCardExpYear(),
card_holder: '',
multi_use: '0'
},
function (response) {
if(response.token){
self.creditCardToken(response.token);
isTokenizeProcessing.resolve();
}
else{
var error = response;
isTokenizeProcessing.reject(error);
}
fullScreenLoader.stopLoader();
},
function (response) {
var error = response;
isTokenizeProcessing.reject(error);
fullScreenLoader.stopLoader();
}
);
}
}
});
}
);
|
JavaScript
| 0.000345 |
@@ -4607,16 +4607,21 @@
entials(
+this.
apiUsern
@@ -4631,16 +4631,21 @@
TokenJs,
+this.
apiPassw
|
6694efed867dd79b7b9878fe0bf2139a7d968a17
|
FIx translation preview for detected language
|
main/plugins/translate/index.js
|
main/plugins/translate/index.js
|
import React from 'react';
import icon from './icon.png';
import translate from './translate';
import detectLanguage from './detectLanguage';
import toLanguageCode from './toLanguageCode';
import Preview from './Preview';
import { id, order, REGEXP } from './constants.js';
const translatePlugin = (term, callback) => {
const match = term.match(REGEXP);
if (match) {
// Show translation in results list
// TODO: check why using const here throws undefined variable text in production build
var text = match[1];
const targetLang = toLanguageCode(match[2]);
detectLanguage(text).then(sourceLang =>
translate(text, `${sourceLang}-${targetLang}`)
).then(({lang, text}) => {
const translation = text[0];
const [sourceLang, targetLang] = lang.split('-')[0];
const options = {
text,
sourceLang,
targetLang,
translation
}
callback({
id,
icon,
title: `${translation}`,
getPreview: () => <Preview {...options} />
});
});
return;
}
// Fallback result with lower priority for every request
callback({
id,
icon,
// Low priority for fallback result
order: 3,
title: `Translate ${term}`,
getPreview: () => <Preview text={term} />
});
};
export default {
fn: translatePlugin,
};
|
JavaScript
| 0 |
@@ -788,19 +788,16 @@
lit('-')
-%5B0%5D
;%0A
|
4f3df7e1f2e8af99a5b33510f0284904de37e657
|
handle custom reducers
|
src/reducers/reducer.js
|
src/reducers/reducer.js
|
import immutable from 'seamless-immutable';
import reduce from 'lodash/reduce';
import container from '../container';
import { PREFIX } from '../constants/actionTypes';
const INITIAL_STATE = {};
const handleCustomReducers = (state, action) => {
if (!container.hasDefinition('reducers')) {
return state;
}
const additionalReducers = container.getDefinition('reducers');
return reduce(additionalReducers, (s, additionalReducer, key) => {
if (s[key]) {
return s.setIn([key], additionalReducer(s[key], action));
}
return s;
}, state);
};
const reducer = (state = immutable(INITIAL_STATE), action) => {
const key = action.key;
// If action has no 'key', or doesn't include our custom prefix,
// we're not interested and we can return the state
if (!key || action.type.indexOf(PREFIX) === -1) {
return handleCustomReducers(state, action);
}
const allRequestConfigs = container.getDefinition('requestMethods').getArguments();
const stateLeaf = reduce(allRequestConfigs, (s, requestConfig) =>
requestConfig.reducer(s, action),
state[key]);
return handleCustomReducers(state.set(key, stateLeaf), action);
};
export default reducer;
|
JavaScript
| 0 |
@@ -374,16 +374,31 @@
ducers')
+.getArguments()
;%0A%0A ret
|
50c518cebfb0c667da9273a444c0f015169f3cfb
|
add user endpoint
|
api/user.js
|
api/user.js
|
const express = require('express');
const { GraphQLClient } = require('graphql-request');
const jwt = require('jwt-decode');
const router = express.Router();
const endpoint = 'https://api.graph.cool/simple/v1/ffconf';
const client = new GraphQLClient(endpoint, { headers: {} });
module.exports = router;
router.get('/', (req, res, next) => {
res.status(400).send(false);
});
router.delete('/', (req, res) => {
res.cookie('token', '', { expires: new Date() });
res.status(200).json(true);
});
router.get('/notes', (req, res, next) => {
const userId = jwt(req.cookies.token).userId;
const query = `query {
User(id:"${userId}") {
note {
id
contents
session {
title
slug
}
}
}
}`;
const client = new GraphQLClient(endpoint, {
headers: {
authorization: `Bearer ${req.cookies.token}`,
},
});
client
.request(query)
.then(results => res.json(results.User.note))
.catch(next);
});
router.post('/', (req, res, next) => {
const { email, password } = req.body;
const query = `mutation auth($email: String!, $password: String!) {
authenticateUser(email: $email, password: $password) {
token
}
}
`;
client
.request(query, { password, email })
.catch(() => {
const query = `mutation signIn($email: String!, $password: String!) {
signupUser(email: $email, password: $password) {
id
token
}
}`;
return client.request(query, { password, email });
})
.then(reply => {
let root = reply.signupUser ? 'signupUser' : 'authenticateUser';
res.cookie('token', reply[root].token, { httpOnly: false });
res
.status(root === 'signupUser' ? 201 : 200)
.send({ token: reply[root].token });
})
.catch(e => {
next({ error: e.response.errors[0].functionError });
});
});
|
JavaScript
| 0.000029 |
@@ -345,34 +345,481 @@
%7B%0A
-res.status(400).send(false
+if (!req.cookies.token) %7B%0A return res.status(400).json(%7B error: 'invalid token' %7D);%0A %7D%0A%0A const %7B userId %7D = jwt(req.cookie.token);%0A%0A const client = new GraphQLClient(endpoint, %7B%0A headers: %7B%0A authorization: %60Bearer $%7Breq.cookies.token%7D%60,%0A %7D,%0A %7D);%0A%0A const query = %60query getUser($userId:ID!) %7B%0A User(id:$userId) %7B%0A email%0A avatar%0A %7D%0A %7D%60;%0A%0A client%0A .request(query, %7B userId %7D)%0A .then(results =%3E res.json(results.User))%0A .catch(next
);%0A%7D
|
bc020d2c069c9ba564d47f253e8cbff3c2c32dcf
|
Fix fatal error when loading a remote doc
|
lib/util/remote-document-loader.js
|
lib/util/remote-document-loader.js
|
'use strict'
// logging
const winston = require('winston')
// parsing utils
const CSON = require('cson')
const YAML = require('js-yaml')
// HTTP utils
const request = require('request')
const filesize = require('filesize')
// constants
const MAX_REMOTE_FILE_SIZE = process.env.MAX_REMOTE_FILE_SIZE || 32 * 1024 // 32 kb
const MAX_REMOTE_FILE_SIZE_HUMAN_READABLE = filesize(MAX_REMOTE_FILE_SIZE)
const DEFAULT_REMOTE_FILE_FORMAT = process.env.DEFAULT_REMOTE_FILE_FORMAT || 'json'
const FORMATTERS = {
plain: (data) => {
let p = new Promise()
p.resolve(data)
return p
},
cson: (data) => {
let p = new Promise()
let parsedData = data
//parsedData = normalizeCSON(data) // DEBUG
parsedData = CSON.parse(parsedData)
if (parsedData)
p.resolve(parsedData)
else
p.reject(new Error('Invalid CSON!'))
return p
},
json: (data) => {
let p = new Promise()
let parsedData = ''
try {
parsedData = JSON.parse(data)
p.resolve(parsedData)
} catch (err) {
p.reject(err)
}
return p
},
yaml: (data) => {
let p = new Promise()
let parsedData = ''
try {
parsedData = YAML.safeLoad(data)
p.resolve(parsedData)
} catch (err) {
p.reject(err)
}
return p
}
}
function getFormatter(format) {
return FORMATTERS[format] || null
}
// function normalizeCSON(csonData) {
// let lines = csonData.split(`\n`)
//
// // normalize indentation
// lines = lines.map(function(line) {
// return line.replace(/^\s/, ' ')
// })
//
// return lines.join(`\n`)
// }
function handleRemoteResponse(response, formatter) {
const p = new Promise()
// reject overly large responses
const contentLength = response.headersSent && response.getHeader('content-length')
if (contentLength && parseInt(contentLength) > MAX_REMOTE_FILE_SIZE) {
winston.warn(`Response too large! Content length: ${contentLength}`)
p.reject(new Error(`The remote file must be smaller than ${MAX_REMOTE_FILE_SIZE_HUMAN_READABLE}`))
return p
}
let body = ''
response.on('data', (data) => {
body += data
// check payload against limit
if (body.length > MAX_REMOTE_FILE_SIZE) {
response.pause()
winston.warn(`Response too large! Total bytes loaded: ${body.length}`)
p.reject(new Error(`The remote file must be smaller than ${MAX_REMOTE_FILE_SIZE_HUMAN_READABLE}`))
body = null
}
})
response.on('end', () => {
formatter(body)
.then(
(parsedData) => {
p.resolve(parsedData)
},
(err) => {
p.reject(err)
}
)
})
response.on('error', (err) => {
p.reject(err)
})
return p
}
function loadAndParse(url, format) {
format = format || DEFAULT_REMOTE_FILE_FORMAT
const p = new Promise()
const formatter = getFormatter(format)
if (!formatter) {
p.reject(new Error(`Unrecognized format: ${format}`))
}
request(url)
.on('error', (err) => {
p.reject(err)
})
.on('response', (response) => {
handleRemoteResponse(response, formatter)
.then(
p.resolve,
p.reject
)
})
return p
}
module.exports = {
loadAndParse: loadAndParse
}
|
JavaScript
| 0.000006 |
@@ -527,35 +527,22 @@
-let p = new Promise()%0A p
+return Promise
.res
@@ -552,29 +552,16 @@
e(data)%0A
- return p%0A
%7D,%0A c
@@ -573,39 +573,38 @@
(data) =%3E %7B%0A
-let p =
+return
new Promise()%0A
@@ -592,34 +592,57 @@
urn new Promise(
-)%0A
+(resolve, reject) =%3E %7B%0A
let parsedDa
@@ -655,16 +655,18 @@
ata%0A
+
//parsed
@@ -701,24 +701,26 @@
/ DEBUG%0A
+
parsedData =
@@ -743,24 +743,26 @@
edData)%0A
+
if (parsedDa
@@ -763,34 +763,34 @@
rsedData)%0A
-p.
+
resolve(parsedDa
@@ -797,16 +797,18 @@
ta)%0A
+
else%0A
@@ -806,26 +806,26 @@
else%0A
-p.
+
reject(new E
@@ -847,32 +847,26 @@
SON!'))%0A
-return p
+%7D)
%0A %7D,%0A json
@@ -875,39 +875,38 @@
(data) =%3E %7B%0A
-let p =
+return
new Promise()%0A
@@ -894,34 +894,57 @@
urn new Promise(
-)%0A
+(resolve, reject) =%3E %7B%0A
let parsedDa
@@ -947,38 +947,42 @@
edData = ''%0A
+
try %7B%0A
+
parsedData
@@ -999,34 +999,34 @@
rse(data)%0A
-p.
+
resolve(parsedDa
@@ -1021,32 +1021,34 @@
lve(parsedData)%0A
+
%7D catch (err
@@ -1049,34 +1049,34 @@
h (err) %7B%0A
-p.
+
reject(err)%0A
@@ -1071,38 +1071,34 @@
ct(err)%0A
+
%7D%0A
-return p
+%7D)
%0A %7D,%0A yaml
@@ -1119,15 +1119,14 @@
-let p =
+return
new
@@ -1134,18 +1134,41 @@
Promise(
-)%0A
+(resolve, reject) =%3E %7B%0A
let
@@ -1183,30 +1183,34 @@
ta = ''%0A
+
try %7B%0A
+
parsed
@@ -1238,26 +1238,26 @@
data)%0A
-p.
+
resolve(pars
@@ -1260,24 +1260,26 @@
parsedData)%0A
+
%7D catch
@@ -1284,34 +1284,34 @@
h (err) %7B%0A
-p.
+
reject(err)%0A
@@ -1314,22 +1314,17 @@
+
%7D%0A
-return p
+%7D
%0A %7D
|
4055a4d7b913f861fad647f2c1995408c57eb375
|
Add arrowCreator attribute to SourceAnchor.arrowCreator
|
src/wirecloud/static/js/wirecloud/ui/WiringEditor/SourceAnchor.js
|
src/wirecloud/static/js/wirecloud/ui/WiringEditor/SourceAnchor.js
|
/*
* (C) Copyright 2012 Universidad Politécnica de Madrid
*
* This file is part of Wirecloud Platform.
*
* Wirecloud Platform is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Wirecloud 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 Wirecloud Platform. If not, see
* <http://www.gnu.org/licenses/>.
*
*/
/*global StyledElements, Wirecloud */
(function () {
"use strict";
/*************************************************************************
* Constructor SourceAnchor
*************************************************************************/
/*
* SourceAnchor Class
*/
var SourceAnchor = function SourceAnchor(context, arrowCreator) {
this.context = context;
Wirecloud.ui.WiringEditor.Anchor.call(this, false, arrowCreator);
};
SourceAnchor.prototype = new Wirecloud.ui.WiringEditor.Anchor(true);
/*************************************************************************
* Public methods
*************************************************************************/
SourceAnchor.prototype.repaint = function repaint(temporal) {
var i, coordinates;
coordinates = this.getCoordinates(document.getElementsByClassName('grid')[0]);
for (i = 0; i < this.arrows.length; i += 1) {
if (this.arrows[i].startMulti == null) {
this.arrows[i].setStart(coordinates);
this.arrows[i].redraw();
}
if (this.arrows[i].endMulti != null) {
this.context.iObject.wiringEditor.multiconnectors[this.arrows[i].endMulti].repaint();
}
}
};
/*************************************************************************
* Make SourceAnchor public
*************************************************************************/
Wirecloud.ui.WiringEditor.SourceAnchor = SourceAnchor;
})();
|
JavaScript
| 0 |
@@ -1324,16 +1324,58 @@
eator);%0A
+ this.arrowCreator = arrowCreator;%0A
%7D;%0A
|
01d34e1f901bbe9f72b5b3ddd213db97cec247a4
|
add note of caveat of using Prompt component
|
lib/components/user/monitored-trip/trip-basics-pane.js
|
lib/components/user/monitored-trip/trip-basics-pane.js
|
import { Field } from 'formik'
import FormikErrorFocus from 'formik-error-focus'
import React, { Component } from 'react'
import {
ControlLabel,
FormControl,
FormGroup,
Glyphicon,
HelpBlock,
ProgressBar
} from 'react-bootstrap'
import { connect } from 'react-redux'
import { Prompt } from 'react-router'
import styled from 'styled-components'
import * as userActions from '../../../actions/user'
import { getErrorStates } from '../../../util/ui'
import TripStatus from './trip-status'
import TripSummary from './trip-summary'
// Styles.
const TripDayLabel = styled.label`
border: 1px solid #ccc;
border-left: none;
box-sizing: border-box;
display: inline-block;
font-weight: inherit;
float: left;
height: 3em;
max-width: 150px;
min-width: 14.28%;
text-align: center;
& > span:first-of-type {
display: block;
width: 100%;
}
&:first-of-type {
border-left: 1px solid #ccc;
}
`
const allDays = [
{ name: 'monday', text: 'Mon.', fullText: 'Mondays' },
{ name: 'tuesday', text: 'Tue.', fullText: 'Tuesdays' },
{ name: 'wednesday', text: 'Wed.', fullText: 'Wednesdays' },
{ name: 'thursday', text: 'Thu.', fullText: 'Thursdays' },
{ name: 'friday', text: 'Fri.', fullText: 'Fridays' },
{ name: 'saturday', text: 'Sat.', fullText: 'Saturdays' },
{ name: 'sunday', text: 'Sun.', fullText: 'Sundays' }
]
/**
* This component shows summary information for a trip
* and lets the user edit the trip name and day.
*/
class TripBasicsPane extends Component {
/**
* For new trips only, update the Formik state to
* uncheck days for which the itinerary is not available.
*/
_updateNewTripItineraryExistence = prevProps => {
const { isCreating, itineraryExistence, setFieldValue } = this.props
if (isCreating &&
itineraryExistence &&
itineraryExistence !== prevProps.itineraryExistence
) {
allDays.forEach(({ name }) => {
if (!itineraryExistence[name].valid) {
setFieldValue(name, false)
}
})
}
}
componentDidMount () {
// Check itinerary availability (existence) for all days.
const { checkItineraryExistence, values: monitoredTrip } = this.props
checkItineraryExistence(monitoredTrip)
}
componentDidUpdate (prevProps) {
this._updateNewTripItineraryExistence(prevProps)
}
componentWillUnmount () {
this.props.clearItineraryExistence()
}
render () {
const {
canceled,
dirty,
errors,
isCreating,
isSubmitting,
itineraryExistence,
values: monitoredTrip
} = this.props
const { itinerary } = monitoredTrip
// Prevent user from leaving when form has been changed,
// but don't show it when they click submit or cancel.
const unsavedChanges = dirty && !isSubmitting && !canceled
// Message changes depending on if the new or existing trip is being edited
const unsavedChangesNewTripMessage = 'You haven\'t saved your new trip yet. If you leave, it will be lost.'
const unsavedChangesExistingTripMessage = 'You haven\'t saved your trip yet. If you leave, changes will be lost.'
const unsavedChangesMessage = isCreating ? unsavedChangesNewTripMessage : unsavedChangesExistingTripMessage
if (!itinerary) {
return <div>No itinerary to display.</div>
} else {
// Show an error indication when
// - monitoredTrip.tripName is not blank and that tripName is not already used.
// - no day is selected (show a combined error indication).
const errorStates = getErrorStates(this.props)
let monitoredDaysValidationState = null
allDays.forEach(({ name }) => {
if (!monitoredDaysValidationState) {
monitoredDaysValidationState = errorStates[name]
}
})
return (
<div>
<Prompt
when={unsavedChanges}
message={unsavedChangesMessage}
/>
{/* Do not show trip status when saving trip for the first time
(it doesn't exist in backend yet). */}
{!isCreating && <TripStatus monitoredTrip={monitoredTrip} />}
<ControlLabel>Selected itinerary:</ControlLabel>
<TripSummary monitoredTrip={monitoredTrip} />
<FormGroup validationState={errorStates.tripName}>
<ControlLabel>Please provide a name for this trip:</ControlLabel>
{/* onBlur, onChange, and value are passed automatically. */}
<Field as={FormControl} name='tripName' />
<FormControl.Feedback />
{errors.tripName && <HelpBlock>{errors.tripName}</HelpBlock>}
</FormGroup>
<FormGroup validationState={monitoredDaysValidationState}>
<ControlLabel>What days do you take this trip?</ControlLabel>
<div>
{allDays.map(({ name, fullText, text }, index) => {
const isDayDisabled = itineraryExistence && !itineraryExistence[name].valid
const boxClass = isDayDisabled ? 'alert-danger' : (monitoredTrip[name] ? 'bg-primary' : '')
const notAvailableText = isDayDisabled ? `Trip not available on ${fullText}` : null
return (
<TripDayLabel className={boxClass} key={index} title={notAvailableText}>
<span>{text}</span>
{ // Let users save an existing trip, even though it may not be available on some days.
// TODO: improve checking trip availability.
isDayDisabled && isCreating
? <Glyphicon aria-label={notAvailableText} glyph='ban-circle' />
: <Field name={name} type='checkbox' />
}
</TripDayLabel>
)
})}
<div style={{clear: 'both'}} />
</div>
<HelpBlock>
{itineraryExistence
? (
<>Your trip is available on the days of the week as indicated above.</>
) : (
<ProgressBar active label='Checking itinerary existence for each day of the week...' now={100} />
)
}
</HelpBlock>
{monitoredDaysValidationState && <HelpBlock>Please select at least one day to monitor.</HelpBlock>}
{/* Scroll to the trip name/days fields if submitting and there is an error on these fields. */}
<FormikErrorFocus align='middle' duration={200} />
</FormGroup>
</div>
)
}
}
}
// Connect to redux store
const mapStateToProps = (state, ownProps) => {
const { itineraryExistence } = state.user
return {
itineraryExistence
}
}
const mapDispatchToProps = {
checkItineraryExistence: userActions.checkItineraryExistence,
clearItineraryExistence: userActions.clearItineraryExistence
}
export default connect(mapStateToProps, mapDispatchToProps)(TripBasicsPane)
|
JavaScript
| 0 |
@@ -3794,32 +3794,197 @@
(%0A %3Cdiv%3E%0A
+ %7B/* TODO: This component does not block navigation on reload or using the back button.%0A This will have to be done at a higher level. See #376 */%7D%0A
%3CPromp
|
da82ce81c715178e7c66ced9e6ba710f1505aee8
|
use delete instead of setting node to null on pop
|
lib/heap.js
|
lib/heap.js
|
var maxHeap = function()
{
// properties
this._tree = new Array();
this._size = 0;
}
/**
* Core Heap functions.
*/
/**
* @return the root node, or the highest valued node.
*/
maxHeap.prototype.peek = function()
{
return this._tree[1];
};
/**
* @return the root node, or highest valued node. Remove it from tree.
*/
maxHeap.prototype.pop = function()
{
// Catch when heap is empty so we don't get a negative _size.
if(this._size > 0){
var to_return = this.peek();
this._tree[1] = this._tree[this._size];
this._tree[this._size] = null;
this._size--;
this.bubbleDown(1);
return to_return;
}
console.log("heap is empty");
};
/**
* @param value to insert.
*/
maxHeap.prototype.push = function(value)
{
if(this._tree[1] === null){
// Base case: The tree is empty and we just add to root.
this._tree[1] = value;
this._size++;
} else {
this._size++;
this._tree[this._size] = value;
this.buildMaxHeap();
}
};
/**
* Calls maxHeapify for each non-leaf node (i=n/2).
*/
maxHeap.prototype.buildMaxHeap = function()
{
var i = Math.floor(this._size / 2);
for(i; i > 0; i--){
this.maxHeapify(i);
}
};
/**
* Bubbles down a low value to proper level in the tree.
* O(log n) time.
*
* @param key to start bubbling down at (default to root)
*/
maxHeap.prototype.bubbleDown = function(key)
{
var node = this._tree[key];
var left_key = getLeft(key);
var left_value = this._tree[left_key];
var right_key = getRight(key);
var right_value = this._tree[right_key];
this.maxHeapify(key);
if(left_value > node && left_value !== null){
this.bubbleDown(left_key);
}
if(right_value > node && right_value !== null){
this.bubbleDown(right_key);
}
};
/**
* Looks at a given node's childern, and then swaps itself with a
* child if the child is bigger.
*
* @param key of node to heapify.
*/
maxHeap.prototype.maxHeapify = function(key)
{
var node = this._tree[key];
var left_child = this._tree[getLeft(key)];
var right_child = this._tree[getRight(key)];
// Base case: If current node is greater than both of its
// children.
if(node < left_child || node < right_child){
if(left_child > right_child || right_child == null){
// swap left child with node
this._tree[key] = left_child;
setLeft(this._tree, key, node);
} else if(right_child > node){
// swap right child with node
this._tree[key] = right_child;
setRight(this._tree, key, node);
}
}
};
/**
* Tree operations.
*/
function getParent(key)
{
return Math.floor(key / 2);
}
function setParent(tree, key, value)
{
tree[Math.floor(key / 2)] = value;
}
function getLeft(key)
{
return 2 * key;
}
function setLeft(tree, key, value)
{
tree[2*key] = value;
}
function getRight(key)
{
return 2 * key + 1;
}
function setRight(tree, key, value)
{
tree[2 * key + 1] = value;
}
exports.maxHeap = maxHeap;
//exports.minHeap = minHeap;
|
JavaScript
| 0 |
@@ -523,16 +523,53 @@
peek();%0D
+%0A var last_node = this._size;%0D
%0A%0D%0A
@@ -598,25 +598,24 @@
s._tree%5B
-this._siz
+last_nod
e%5D;%0D%0A
@@ -611,32 +611,39 @@
node%5D;%0D%0A
+delete
this._tree%5Bthis.
@@ -641,26 +641,18 @@
ree%5B
-this._size%5D = null
+last_node%5D
;%0D%0A
|
1de7537210a5db3e1abcb19ae93493029f3d159e
|
Copy the default labels to the meeting series when inserting a new series
|
imports/collections/meetingseries_private.js
|
imports/collections/meetingseries_private.js
|
import { Meteor } from 'meteor/meteor';
import { Mongo } from 'meteor/mongo';
import { MeetingSeries } from './../meetingseries';
import { Minutes } from './../minutes';
import { MeetingSeriesSchema } from './meetingseries.schema';
import { UserRoles } from "./../userroles";
export var MeetingSeriesCollection = new Mongo.Collection("meetingSeries",
{
// inject methods of class MeetingSeries to all returned collection docs
transform: function (doc) {
return new MeetingSeries(doc);
}
}
);
if (Meteor.isServer) {
Meteor.publish('meetingSeries', function meetingSeriesPublication() {
return MeetingSeriesCollection.find(
{visibleFor: {$in: [this.userId]}});
});
}
if (Meteor.isClient) {
Meteor.subscribe('meetingSeries');
}
MeetingSeriesCollection.attachSchema(MeetingSeriesSchema);
Meteor.methods({
'meetingseries.insert'(doc, optimisticUICallback) {
console.log("meetingseries.insert");
// Make sure the user is logged in before changing collections
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
// the user should not be able to define the date when this series was create - or should he?
// -> so we overwrite this field if it was set previously
let currentDate = new Date();
doc.createdAt = currentDate;
doc.lastMinutesDate = formatDateISO8601(currentDate);
// limit visibility of this meeting series (see server side publish)
// array will be expanded by future invites
doc.visibleFor = [Meteor.userId()];
// Every logged in user is allowed to create a new meeting series.
MeetingSeriesCollection.insert(doc, function(error, newMeetingSeriesID) {
if (error) {
throw error;
}
if (Meteor.isClient && optimisticUICallback) {
optimisticUICallback(newMeetingSeriesID);
}
doc._id = newMeetingSeriesID;
// Make creator of this meeting series the first moderator
Roles.addUsersToRoles(Meteor.userId(), UserRoles.USERROLES.Moderator, newMeetingSeriesID);
});
},
'meetingseries.update'(doc) {
if (!doc) {
console.log('meetingseries.update: no data given');
return;
}
console.log("meetingseries.update:", doc.minutes);
let id = doc._id;
delete doc._id; // otherwise collection.update will fail
if (!id) {
return;
}
// TODO: fix security issue: it is not allowed to modify (e.g. remove) elements from the minutes array!
// Make sure the user is logged in before changing collections
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
// Ensure user can not update documents of other users
let userRoles = new UserRoles(Meteor.userId());
if (userRoles.isModeratorOf(id)) {
MeetingSeriesCollection.update(id, {$set: doc});
} else {
throw new Meteor.Error("Cannot update meeting series", "You are not moderator of this meeting series.");
}
},
'meetingseries.remove'(id) {
console.log("meetingseries.remove:"+id);
if (id == undefined || id == "")
return;
// Make sure the user is logged in before changing collections
if (!Meteor.userId()) {
throw new Meteor.Error('not-authorized');
}
// Ensure user can not update documents of other users
let userRoles = new UserRoles(Meteor.userId());
if (userRoles.isModeratorOf(id)) {
UserRoles.removeAllRolesFor(id);
MeetingSeriesCollection.remove(id);
} else {
throw new Meteor.Error("Cannot remove meeting series", "You are not moderator of this meeting series.");
}
},
'meetingseries.removeMinutesFromArray'(meetingSeriesId, minutesId) {
console.log("meetingseries.removeMinutesFromArray: MeetingSeries ("
+ meetingSeriesId + "), Minutes (" + minutesId + ")");
// Minutes can only be removed as long as they are not finalized
let aMin = new Minutes(minutesId);
if (aMin.isFinalized) return;
// Ensure user can not update documents of other users
let userRoles = new UserRoles(Meteor.userId());
if (userRoles.isModeratorOf(meetingSeriesId)) {
MeetingSeriesCollection.update(meetingSeriesId, {$pull: {'minutes': minutesId}});
} else {
throw new Meteor.Error("Cannot remove minutes from meeting series", "You are not moderator of this meeting series.");
}
}
});
|
JavaScript
| 0 |
@@ -268,16 +268,69 @@
rroles%22;
+%0Aimport %7B GlobalSettings %7D from %22./../GlobalSettings%22
%0A%0Aexport
@@ -1677,16 +1677,377 @@
Id()%5D;%0A%0A
+ if (Meteor.isServer) %7B%0A // copy the default labels to the series%0A doc.availableLabels = GlobalSettings.getDefaultLabels();%0A doc.availableLabels.forEach((label) =%3E %7B%0A label._id = Random.id();%0A label.isDefaultLabel = true;%0A label.isDisabled = false;%0A %7D);%0A %7D%0A%0A
|
b469d4e553d07ba62c07c16b5e8a64deda9232dd
|
Enable button on success mode
|
lib/js/countastic.js
|
lib/js/countastic.js
|
/*
*
* Countastic
* Provides a twitter-like character counter for any text input or textarea
*
* Version: 1.0.0
* Homepage: http://github.com/rbmrclo/countastic
* Author: Robbie Marcelo (www.robbiemarcelo.com)
*
* Copyright (c) 2013 Robbie Marcelo
* Licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
*
*/
(function () {
var Countastic = function (options) {
this._init(options);
};
Countastic.prototype = {
_settings: {
countable: null, //
counter: "#counter", // Id of counter
button: "#counter-btn", // Button for disable and enable callback
maxCount: 160, // Maximum limit of chars
warningCount: 20, // Warning point
strictMax: false, // If true, will trigger a callback
countDirection: 'down', // Decrement or Increment
successClass: 'success', // CSS class before reaching maxCount
warningClass: 'warning', // CSS class when warning reached
alertClass: 'alert', // CSS class after reaching maxCount
onWarning: function(){}, // Do whatever you like on warning
onSuccess: function(){}, // Do whatever you like on success
onMaxCount: function(){} // Do whatever you like when exactly maxCount
},
_init: function (options) {
this._settings = this.merge(this._settings, options);
var countable = document.querySelector(this._settings.countable);
// Throw an error if countable textfield is not on the DOM
if (!countable) {
throw new Error('missing parameters: countable input field');
}
var counter = document.querySelector(this._settings.counter);
if (!counter) {
throw new Error('missing parameters: counter');
}
this.attachEventHandlers(counter, countable);
},
merge: function (obj1, obj2) {
var obj3 = {},
attrname;
for (attrname in obj1) { obj3[attrname] = obj1[attrname]; }
for (attrname in obj2) { obj3[attrname] = obj2[attrname]; }
return obj3;
},
attachEventHandlers: function (counter, countable) {
countable.addEventListener('keyup', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
countable.addEventListener('keydown', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
countable.addEventListener('keypress', (function () { setTimeout(this.refreshCounter(counter, countable), 5); }).bind(this, false) );
countable.addEventListener('remove', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
countable.addEventListener('change', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
countable.addEventListener('focus', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
countable.addEventListener('select', (function () { this.refreshCounter(counter, countable); }).bind(this, false) );
},
refreshCounter: function (counter, countable) {
var count, revCount, maxCount, strictMax, button;
maxCount = this._settings.maxCount;
strictMax = this._settings.strictMax;
button = document.querySelector(this._settings.button);
// Count by characters
count = maxCount - countable.value.length;
revCount = this.reverseCount(count);
// If strictMax set restrict further characters
if (strictMax && count <= 0){
if (count < 0) {
this._settings.onMaxCount(this.countInt(revCount, count), this, counter);
}
}
// We change the value of the counter
counter.innerHTML = this.numberFormat(this.countInt(revCount, count));
this.setCssAndCallbacks(count, this._settings);
},
reverseCount: function (val) {
return val - (val * 2) + this._settings.maxCount;
},
countInt: function (revCount, count) {
return (this._settings.countDirection === 'up') ? revCount : count;
},
numberFormat: function (val) {
val += '';
splitted = val.split('.');
x = splitted[0];
y = splitted.length > 1 ? '.' + splitted[1] : '';
var regex = /(\d+)(\d{3})/;
while (regex.test(x)) {
x = x.replace(regex, '$1' + ',' + '$2');
}
return x + y;
},
enableButton: function(button) {
if (!button) { return false; }
else { button.disabled = false; }
},
disableButton: function(button) {
if (!button) { return false; }
else { button.disabled = true; }
},
// Set CSS class rules and callbacks
//
setCssAndCallbacks: function (count, settings) {
var counter = document.querySelector(settings.counter);
var button = document.querySelector(settings.button);
var revCount = this.reverseCount(count);
if (count == settings.maxCount) {
counter.classList.remove(settings.alertClass);
counter.classList.add(settings.successClass);
}
if (!counter.classList.contains(settings.successClass) && !counter.classList.contains(settings.alertClass) && !counter.classList.contains(settings.warningClass)) {
if (count > settings.warningCount && count > 0) { counter.classList.add(settings.successClass); }
else if (count > 0 && count <= settings.warningCount) { counter.classList.add(settings.warningClass); }
else if (count <= 0) { counter.classList.add(settings.alertClass); }
}
else if (count > 0 && count <= settings.warningCount) {
if (counter.classList.contains(settings.successClass)) {
counter.classList.remove(settings.successClass);
counter.classList.add(settings.warningClass);
}
else if (counter.classList.contains(settings.alertClass)) {
counter.classList.remove(settings.alertClass);
counter.classList.add(settings.warningClass);
}
settings.onWarning(this.countInt(revCount, count), this, counter);
this.enableButton(button);
}
else if (count <= 0 && counter.classList.contains(settings.warningClass)) {
counter.classList.remove(settings.warningClass);
counter.classList.add(settings.alertClass);
settings.onMaxCount(this.countInt(revCount, count), this, counter);
this.disableButton(button);
}
else if (count > settings.warningCount && counter.classList.contains(settings.warningClass)) {
counter.classList.remove(settings.warningClass);
counter.classList.add(settings.successClass);
settings.onSuccess(this.countInt(revCount, count), this, counter);
}
}
};
this.Countastic = Countastic;
})();
|
JavaScript
| 0.000001 |
@@ -6835,24 +6835,59 @@
, counter);%0A
+ this.enableButton(button);%0A
%7D%0A
|
377b73dcddfd431c46fb35dc35e316ce5eada542
|
fix exceptions under some circumstances
|
src/service/xhr.bulk.js
|
src/service/xhr.bulk.js
|
'use strict';
/**
* @workInProgress
* @ngdoc service
* @name angular.service.$xhr.bulk
* @requires $xhr
* @requires $xhr.error
* @requires $log
*
* @description
*
* @example
*/
angularServiceInject('$xhr.bulk', function($xhr, $error, $log){
var requests = [],
scope = this;
function bulkXHR(method, url, post, success, error) {
if (isFunction(post)) {
error = success;
success = post;
post = null;
}
var currentQueue;
forEach(bulkXHR.urls, function(queue){
if (isFunction(queue.match) ? queue.match(url) : queue.match.exec(url)) {
currentQueue = queue;
}
});
if (currentQueue) {
if (!currentQueue.requests) currentQueue.requests = [];
var request = {
method: method,
url: url,
data: post,
success: success};
if (error) request.error = error;
currentQueue.requests.push(request);
} else {
$xhr(method, url, post, success, error);
}
}
bulkXHR.urls = {};
bulkXHR.flush = function(success, error) {
forEach(bulkXHR.urls, function(queue, url) {
var currentRequests = queue.requests;
if (currentRequests && currentRequests.length) {
queue.requests = [];
queue.callbacks = [];
$xhr('POST', url, {requests: currentRequests},
function(code, response) {
forEach(response, function(response, i) {
try {
if (response.status == 200) {
(currentRequests[i].success || noop)(response.status, response.response);
} else if (isFunction(currentRequests[i].error)) {
currentRequests[i].error(response.status, response.response);
} else {
$error(currentRequests[i], response);
}
} catch(e) {
$log.error(e);
}
});
(success || noop)();
},
function(code, response) {
forEach(currentRequests, function(request, i) {
try {
if (isFunction(request.error)) {
request.error(code, response);
} else {
$error(request, response);
}
} catch(e) {
$log.error(e);
}
});
(error || noop)();
});
scope.$eval();
}
});
};
this.$watch(bulkXHR.flush);
return bulkXHR;
}, ['$xhr', '$xhr.error', '$log']);
|
JavaScript
| 0 |
@@ -1048,27 +1048,129 @@
ccess, error
-) %7B
+back) %7B%0A assertArgFn(success = success %7C%7C noop, 0);%0A assertArgFn(errorback = errorback %7C%7C noop, 1);
%0A forEach
@@ -2023,25 +2023,15 @@
-(
success
- %7C%7C noop)
();%0A
@@ -2451,24 +2451,13 @@
- (error %7C%7C
noop
-)
();%0A
@@ -2474,31 +2474,8 @@
%7D);%0A
- scope.$eval();%0A
@@ -2505,16 +2505,28 @@
.$watch(
+function()%7B
bulkXHR.
@@ -2530,16 +2530,21 @@
HR.flush
+(); %7D
);%0A ret
|
341a639400d5e8de14697a32ba1b29027ed45213
|
Remove uploadOnlyNewFiles for gulp upload task
|
gulpfile.babel.js
|
gulpfile.babel.js
|
import gulp from 'gulp';
import eslint from 'gulp-eslint';
import util from 'gulp-util';
import plumber from 'gulp-plumber';
import uglify from 'gulp-uglify';
import rename from 'gulp-rename';
import babel from 'gulp-babel';
import buffer from 'gulp-buffer';
import del from 'del';
import webpack from 'webpack';
import gulpWebpack from 'webpack-stream';
import s3Upload from 'gulp-s3-upload';
import banner from 'gulp-banner';
import pkg from './package.json';
import bump from 'gulp-bump';
import tag from 'gulp-tag-version';
import { argv as args } from 'yargs';
function errorHandler(err) {
util.log(err.toString());
this.emit('end');
}
gulp.task('lint', () => {
const stream = gulp.src('src/**/*.js')
.pipe(eslint())
.pipe(eslint.format())
.pipe(eslint.failAfterError());
return stream;
});
gulp.task('clean', (done) => del([
'es5',
'dist',
'coverage',
'test.tap'
], done));
gulp.task('build', ['clean', 'lint'], () => {
const stream = gulp.src('src/**/*.js')
.pipe(babel())
.pipe(gulp.dest('./es5'));
return stream;
});
gulp.task('bundle', ['build'], () => {
const header = '/**\n'
+ ` * <%= pkg.name %> v<%= pkg.version %>\n`
+ ' * <%= pkg.description %>\n'
+ ' * <%= pkg.homepage %>\n'
+ ' *\n'
+ ' * Copyright (c) 2016, <%= pkg.author %>.\n'
+ ' * All rights reserved.\n'
+ ' *\n'
+ ' * Released under the <%= pkg.license %> license.\n'
+ ' */\n';
const stream = gulp.src('./es5/index.js')
.pipe(gulpWebpack({
context: `${__dirname}/es5`,
entry: [
'babel-regenerator-runtime/runtime.js',
'./index.js'
],
output: {
filename: 'kinvey-angular-sdk.js'
},
module: {
loaders: [
{ test: /\.json$/, loader: 'json' }
]
}
}, webpack))
.pipe(banner(header, { pkg: pkg }))
.pipe(gulp.dest(`${__dirname}/dist`))
.pipe(rename(`kinvey-angular-sdk-${pkg.version}.js`))
.pipe(gulp.dest(`${__dirname}/dist`))
.pipe(rename('kinvey-angular-sdk.min.js'))
.pipe(buffer())
.pipe(uglify())
.pipe(banner(header, { pkg: pkg }))
.pipe(gulp.dest(`${__dirname}/dist`))
.pipe(rename(`kinvey-angular-sdk-${pkg.version}.min.js`))
.pipe(gulp.dest(`${__dirname}/dist`))
.on('error', errorHandler);
return stream;
});
gulp.task('bump', () => {
if (!args.type && !args.version) {
args.type = 'patch';
}
const stream = gulp.src(['./package.json', './bower.json'])
.pipe(bump({
preid: 'beta',
type: args.type,
version: args.version
}))
.pipe(gulp.dest(`${__dirname}/`))
.on('error', errorHandler);
return stream;
});
gulp.task('tag', () => {
const stream = gulp.src('./package.json')
.pipe(tag())
.on('error', errorHandler);
return stream;
});
gulp.task('upload', ['bundle'], () => {
const s3 = s3Upload({
accessKeyId: process.env.S3_ACCESSKEYID,
secretAccessKey: process.env.S3_SECRETACCESSKEY
});
const stream = gulp.src([
`dist/kinvey-angular-sdk-${pkg.version}.js`,
`dist/kinvey-angular-sdk-${pkg.version}.min.js`,
])
.pipe(plumber())
.pipe(s3({
Bucket: 'kinvey-downloads/js',
uploadNewFilesOnly: true
}, (error, data) => {
if (error) {
return errorHandler(error);
}
return data;
}))
.on('error', errorHandler);
return stream;
});
gulp.task('default', ['bundle']);
|
JavaScript
| 0 |
@@ -3184,40 +3184,8 @@
/js'
-,%0A uploadNewFilesOnly: true
%0A
|
5dcc820c0a08d21be83e8ff34d38ed0ae781dff6
|
fix clickCircle
|
scripts/geoleaflet-client.js
|
scripts/geoleaflet-client.js
|
/* @flow */
/*global L, initReact, Array, detailView, topojson, georeactor, valuesForField, clickCircle */
(function() {
var map;
mapJSONfile = function(gj) {
dataLayer = L.geoJson(gj, {
style: function (feature) {
return {
fillColor: '#f00',
fillOpacity: 0,
color: '#444',
weight: 2
}
},
onEachFeature: function (feature, layer) {
layer.on('click', function() {
if (clickCircle) {
map.removeLayer(clickCircle);
}
if(feature.geometry.type === 'Point') {
var coord = feature.geometry.coordinates.concat([]);
coord.reverse();
clickCircle = L.circleMarker(coord, {
radius: 80,
strokeColor: '#f00',
fillColor: '#f00'
}).addTo(map);
}
fitBounds(feature.properties.bounds);
detailView.setState({ selectFeature: feature });
dataLayer.setStyle(function (styler) {
var fillOpacity = 0;
if (feature === styler) {
fillOpacity = 0.2;
}
return {
fillColor: '#f00',
fillOpacity: fillOpacity,
color: '#444',
weight: 1
}
});
});
}
}).addTo(map);
return dataLayer;
};
initMap = function() {
map = L.map(georeactor.div)
.setView([0, 0], 5);
map.attributionControl.setPrefix('');
new L.Hash(map);
if (!georeactor.tiles || !georeactor.tiles.length) {
osm = L.tileLayer('//tile-{s}.openstreetmap.fr/hot/{z}/{x}/{y}.png', {
attribution: 'Map data © OpenStreetMap contributors',
maxZoom: 17
}).addTo(map);
sat = L.tileLayer('//{s}.tiles.mapbox.com/v3/mapmeld.map-a6ineq7y/{z}/{x}/{y}.png?updated=65f7243', {
attribution: 'Map data © OpenStreetMap contributors; satellite from MapBox',
maxZoom: 17
});
L.control.layers({
"OpenStreetMap": osm,
"Satellite": sat
}, {}).addTo(map);
var layerControl = document.getElementsByClassName("leaflet-control-layers-toggle")[0];
setTimeout(function() {
layerControl.style.backgroundImage = 'url(styles/lib/images/layers.png)';
}, 200);
map.on('baselayerchange', function() {
/* update default lines */
});
} else {
/* custom tiles */
}
fitBounds = function(bounds) {
map.fitBounds(L.latLngBounds(
L.latLng(bounds[1], bounds[0]),
L.latLng(bounds[3], bounds[2])
));
}
for (var d = 0; d < georeactor.data.length; d++) {
makeRequestFor(georeactor.data[d], function(gj) {
mapJSONfile(gj);
});
}
initReact();
};
})();
|
JavaScript
| 0.000001 |
@@ -87,21 +87,8 @@
ield
-, clickCircle
*/%0A
@@ -111,16 +111,29 @@
var map
+, clickCircle
;%0A%0A map
|
48d18597234bed153e3cf10531fb283095b9738a
|
Load enviroment variables into config
|
src/site/store/index.js
|
src/site/store/index.js
|
import Vue from 'vue';
import Vuex from 'vuex';
const state = {
loggedIn: false,
user: {},
token: null,
config: null
};
/* eslint-disable no-shadow */
const mutations = {
loggedIn(state, payload) {
state.loggedIn = payload;
},
user(state, payload) {
if (!payload) {
state.user = {};
localStorage.removeItem('lolisafe-user');
return;
}
localStorage.setItem('lolisafe-user', JSON.stringify(payload));
state.user = payload;
},
token(state, payload) {
if (!payload) {
localStorage.removeItem('lolisafe-token');
state.token = null;
return;
}
localStorage.setItem('lolisafe-token', payload);
setAuthorizationHeader(payload);
state.token = payload;
},
config(state, payload) {
state.config = payload;
}
};
const actions = {
nuxtServerInit({ commit }, { req }) {
/* TODO: Get env variables from context/process */
const config = require('~/config.js');
commit('config', config);
}
};
const setAuthorizationHeader = payload => {
console.log('hihi');
Vue.axios.defaults.headers.common.Authorization = payload ? `Bearer ${payload}` : '';
};
const store = () => new Vuex.Store({
state,
mutations,
actions
});
export default store;
|
JavaScript
| 0.000002 |
@@ -810,125 +810,338 @@
%7B%0A%09%09
-/* TODO: Get env variables from context/process */%0A%09%09const config = require('~/config.js');%0A%09%09commit('config', config
+commit('config', %7B%0A%09%09%09version: process.env.npm_package_version,%0A%09%09%09URL: process.env.DOMAIN,%0A%09%09%09baseURL: %60$%7Bprocess.env.DOMAIN%7D$%7Bprocess.env.ROUTE_PREFIX%7D%60,%0A%09%09%09serviceName: process.env.SERVICE_NAME,%0A%09%09%09maxFileSize: process.env.MAX_SIZE,%0A%09%09%09chunkSize: process.env.CHUNK_SIZE,%0A%09%09%09maxLinksPerAlbum: process.env.MAX_LINKS_PER_ALBUM%0A%09%09%7D
);%0A%09
|
70f226ca1e8e6b8798f0a7be8e063211f7156ddc
|
merge with global tags instead of overriding
|
lib/loggly/client.js
|
lib/loggly/client.js
|
/*
* client.js: Core client functions for accessing Loggly
*
* (C) 2010 Nodejitsu Inc.
* MIT LICENSE
*
*/
var events = require('events'),
util = require('util'),
qs = require('querystring'),
common = require('./common'),
loggly = require('../loggly'),
Search = require('./search').Search;
//
// function createClient (options)
// Creates a new instance of a Loggly client.
//
exports.createClient = function (options) {
return new Loggly(options);
};
//
// ### function Loggly (options)
// #### @options {Object} Options for this Loggly client
// #### @subdomain
// #### @token
// #### @json
// #### @auth
// #### @tags
// Constructor for the Loggly object
//
var Loggly = exports.Loggly = function (options) {
if (!options || !options.subdomain || !options.token) {
throw new Error('options.subdomain and options.token are required.');
}
events.EventEmitter.call(this);
this.subdomain = options.subdomain;
this.token = options.token;
this.host = options.host || 'logs-01.loggly.com';
this.json = options.json || null;
this.auth = options.auth || null;
this.userAgent = 'node-loggly ' + loggly.version;
this.useTagHeader = "useTagHeader" in options ? options.useTagHeader : true;
//
// Set the tags on this instance.
//
this.tags = options.tags
? this.tagFilter(options.tags)
: null;
var url = 'https://' + this.host,
api = options.api || 'apiv2';
this.urls = {
default: url,
log: [url, 'inputs', this.token].join('/'),
bulk: [url, 'bulk', this.token].join('/'),
api: 'https://' + [this.subdomain, 'loggly', 'com'].join('.') + '/' + api
};
};
//
// Inherit from events.EventEmitter
//
util.inherits(Loggly, events.EventEmitter);
//
// ### function log (msg, tags, callback)
// #### @msg {string|Object} Data to log
// #### @tags {Array} **Optional** Tags to send with this msg
// #### @callback {function} Continuation to respond to when complete.
// Logs the message to the token associated with this instance. If
// the message is an Object we will attempt to serialize it. If any
// `tags` are supplied they will be passed via the `X-LOGGLY-TAG` header.
// - http://www.loggly.com/docs/api-sending-data/
//
Loggly.prototype.log = function (msg, tags, callback) {
if (!callback && typeof tags === 'function') {
callback = tags;
tags = null;
}
var self = this,
logOptions;
//
// Remark: Have some extra logic for detecting if we want to make a bulk
// request to loggly
//
var isBulk = Array.isArray(msg);
function serialize (msg) {
if (msg instanceof Object) {
return self.json ? JSON.stringify(msg) : common.serialize(msg);
}
else {
return self.json ? JSON.stringify({ message : msg }) : msg;
}
};
msg = isBulk ? msg.map(serialize).join('\n') : serialize(msg);
logOptions = {
uri: isBulk ? this.urls.bulk : this.urls.log,
method: 'POST',
body: msg,
headers: {
'host': this.host,
'accept': '*/*',
'user-agent': this.userAgent,
'content-type': this.json ? 'application/json' : 'text/plain',
'content-length': Buffer.byteLength(msg)
}
};
//
// Remark: if tags are passed in run the filter or just use default tags if
// they exist
//
tags = tags
? this.tagFilter(tags)
: this.tags;
//
// Optionally send `X-LOGGLY-TAG` if we have them
//
if (tags) {
//decide whether to add tags as http headers or add them to the URI.
if (this.useTagHeader) {
logOptions.headers['x-loggly-tag'] = tags.join(',');
}
else {
logOptions.uri += "/tag/" + tags.join(",") + "/";
}
}
common.loggly(logOptions, callback, function (res, body) {
try {
var result = JSON.parse(body);
self.emit('log', result);
if (callback) {
callback(null, result);
}
}
catch (ex) {
if (callback) {
callback(new Error('Unspecified error from Loggly: ' + ex));
}
}
});
return this;
};
//
// ### function tag (tags)
// #### @tags {Array} Tags to use for `X-LOGGLY-TAG`
// Sets the tags on this instance
//
Loggly.prototype.tagFilter = function (tags) {
var isSolid = /^[\w\d][\w\d-_.]+/;
tags = !Array.isArray(tags)
? [tags]
: tags;
//
// TODO: Filter against valid tag names with some Regex
// http://www.loggly.com/docs/tags/
// Remark: Docs make me think we dont need this but whatevs
//
return tags.filter(function (tag) {
//
// Remark: length may need to use Buffer.byteLength?
//
return isSolid.test(tag) && tag.length <= 64;
});
};
//
// ### function customer (callback)
// ### @callback {function} Continuation to respond to.
// Retrieves the customer information from the Loggly API:
// - http://www.loggly.com/docs/api-account-info/
//
Loggly.prototype.customer = function (callback) {
common.loggly({
uri: this.logglyUrl('customer'),
auth: this.auth
}, callback, function (res, body) {
var customer;
try { customer = JSON.parse(body) }
catch (ex) { return callback(ex) }
callback(null, customer);
});
};
//
// function search (query, callback)
// Returns a new search object which can be chained
// with options or called directly if @callback is passed
// initially.
//
// Sample Usage:
//
// client.search('404', function () { /* ... */ })
// .on('rsid', function (rsid) { /* ... */ })
//
// client.search({ query: '404', rows: 100 })
// .on('rsid', function (rsid) { /* ... */ })
// .run(function () { /* ... */ });
//
Loggly.prototype.search = function (query, callback) {
var options = typeof query === 'string'
? { query: query }
: query;
options.callback = callback;
return new Search(options, this);
};
//
// function logglyUrl ([path, to, resource])
// Helper method that concats the string params into a url
// to request against a loggly serverUrl.
//
Loggly.prototype.logglyUrl = function (/* path, to, resource */) {
var args = Array.prototype.slice.call(arguments);
return [this.urls.api].concat(args).join('/');
};
|
JavaScript
| 0 |
@@ -3313,16 +3313,71 @@
filter
+on them and concat%0A // with any tags that were passed
or just
@@ -3395,21 +3395,16 @@
tags if
-%0A //
they ex
@@ -3436,27 +3436,82 @@
?
-this.tagFilter(tags
+(this.tags ? this.tags.concat(this.tagFilter(tags)) : this.tagFilter(tags)
)%0A
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.