content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Go | Go | remove testdockersuite func | 9b428a3d33acd4ca55f178bf3ad7fdac241f88bd | <ide><path>integration-cli/check_test.go
<ide> func ensureTestEnvSetup(t *testing.T) {
<ide> })
<ide> }
<ide>
<del>func TestDockerSuite(t *testing.T) {
<del> ensureTestEnvSetup(t)
<del> suite.Run(t, &DockerAPISuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerBenchmarkSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIAttachSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIBuildSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLICommitSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLICpSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLICreateSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIEventSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIExecSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIHealthSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIHistorySuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIImagesSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIImportSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIInfoSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIInspectSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLILinksSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLILoginSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLILogsSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLINetmodeSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLINetworkSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPluginLogDriverSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPluginsSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPortSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIProxySuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPruneSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPsSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPullSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIPushSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIRestartSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIRmiSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIRunSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLISaveLoadSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLISearchSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLISNISuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIStartSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIStatsSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLITopSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIUpdateSuite{ds: &DockerSuite{}})
<del> suite.Run(t, &DockerCLIVolumeSuite{ds: &DockerSuite{}})
<del>}
<del>
<ide> func TestDockerAPISuite(t *testing.T) {
<ide> ensureTestEnvSetup(t)
<ide> suite.Run(t, &DockerAPISuite{ds: &DockerSuite{}}) | 1 |
Javascript | Javascript | move meta viewport to _app.js | 3922fa0584ff481f15cd1b4de689967df88159b5 | <ide><path>examples/with-react-native-web/pages/_app.js
<add>import * as React from 'react'
<add>import Head from 'next/head'
<add>
<add>function MyApp({ Component, pageProps }) {
<add> return (
<add> <>
<add> <Head>
<add> <meta name="viewport" content="width=device-width, initial-scale=1" />
<add> </Head>
<add> <Component {...pageProps} />
<add> </>
<add> )
<add>}
<add>
<add>export default MyApp
<ide><path>examples/with-react-native-web/pages/_document.js
<ide> export default class MyDocument extends Document {
<ide> render() {
<ide> return (
<ide> <html style={{ height: '100%' }}>
<del> <Head>
<del> <meta name="viewport" content="width=device-width, initial-scale=1" />
<del> </Head>
<add> <Head />
<ide> <body style={{ height: '100%', overflow: 'hidden' }}>
<ide> <Main />
<ide> <NextScript /> | 2 |
Mixed | Javascript | add es6 class transform | d9c13c73b6f6c1e928258f6686939dd5503e7408 | <ide><path>npm-react-codemod/README.md
<ide> are using the master version (>0.13.1) of React as it is using
<ide> namespaced name for the mixin. `mixins: [React.addons.PureRenderMixin]` will
<ide> not currently work.
<ide>
<add>`class.js` transforms `React.createClass` calls into ES6 classes.
<add>
<add> * `react-codemod class <file>`
<add> * If `--no-super-class=true` is specified it will not extend
<add> `React.Component` if `setState` and `forceUpdate` aren't being called in a
<add> class. We do recommend always extending from `React.Component`, especially
<add> if you are using or planning to use [Flow](http://flowtype.org/). Also make
<add> sure you are not calling `setState` anywhere outside of your component.
<add>
<add>All scripts take an option `--no-explicit-require=true` if you don't have a
<add>`require('React')` statement in your code files and if you access React as a
<add>global.
<add>
<add>### Explanation of the ES6 class transform
<add>
<add> * Ignore components with calls to deprecated APIs. This is very defensive, if
<add> the script finds any identifiers called `isMounted`, `getDOMNode`,
<add> `replaceProps`, `replaceState` or `setProps` it will skip the component.
<add> * Replaces `var A = React.createClass(spec)` with
<add> `class A (extends React.Component) {spec}`.
<add> * Pulls out all statics defined on `statics` plus the few special cased
<add> statics like `propTypes`, `childContextTypes`, `contextTypes` and
<add> `displayName` and assigns them after the class is created.
<add> `class A {}; A.foo = bar;`
<add> * Takes `getDefaultProps` and inlines it as a static `defaultProps`.
<add> If `getDefaultProps` is defined as a function with a single statement that
<add> returns an object, it optimizes and transforms
<add> `getDefaultProps() { return {foo: 'bar'}; }` into
<add> `A.defaultProps = {foo: 'bar'};`. If `getDefaultProps` contains more than
<add> one statement it will transform into a self-invoking function like this:
<add> `A.defaultProps = function() {…}();`. Note that this means that the function
<add> will be executed only a single time per app-lifetime. In practice this
<add> hasn't caused any issues – `getDefaultProps` should not contain any
<add> side-effects.
<add> * Binds class methods to the instance if methods are referenced without being
<add> called directly. It checks for `this.foo` but also traces variable
<add> assignments like `var self = this; self.foo`. It does not bind functions
<add> from the React API and ignores functions that are being called directly
<add> (unless it is both called directly and passed around to somewhere else)
<add> * Creates a constructor if necessary. This is necessary if either
<add> `getInitialState` exists in the `React.createClass` spec OR if functions
<add> need to be bound to the instance.
<add> * When `--no-super-class=true` is passed it only optionally extends
<add> `React.Component` when `setState` or `forceUpdate` are used within the
<add> class.
<add>
<add>The constructor logic is as follows:
<add> * Call `super(props, context)` if the base class needs to be extended.
<add> * Bind all functions that are passed around,
<add> like `this.foo = this.foo.bind(this)`
<add> * Inline `getInitialState` (and remove `getInitialState` from the spec). It
<add> also updates access of `this.props.foo` to `props.foo` and adds `props` as
<add> argument to the constructor. This is necessary in the case when the base
<add> class does not need to be extended where `this.props` will only be set by
<add> React after the constructor has been run.
<add> * Changes `return StateObject` from `getInitialState` to assign `this.state`
<add> directly.
<add>
<ide> ### Recast Options
<ide>
<ide> Options to [recast](https://github.com/benjamn/recast)'s printer can be provided
<ide><path>npm-react-codemod/test/__tests__/transform-tests.js
<ide> describe('Transform Tests', () => {
<ide> });
<ide> });
<ide>
<add> it('transforms the "class" tests correctly', () => {
<add> test('class', 'class-test');
<add>
<add> test('class', 'class-test2', {
<add> 'no-super-class': true,
<add> });
<add>
<add> test('class', 'class-test3');
<add> });
<ide>
<ide> });
<ide><path>npm-react-codemod/test/class-test.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>var Relay = require('Relay');
<add>
<add>var Image = require('Image.react');
<add>
<add>/*
<add> * Multiline
<add> */
<add>var MyComponent = React.createClass({
<add> getInitialState: function() {
<add> var x = this.props.foo;
<add> return {
<add> heyoo: 23,
<add> };
<add> },
<add>
<add> foo: function() {
<add> this.setState({heyoo: 24});
<add> }
<add>});
<add>
<add>// Class comment
<add>var MyComponent2 = React.createClass({
<add> getDefaultProps: function() {
<add> return {a: 1};
<add> },
<add> foo: function() {
<add> pass(this.foo);
<add> this.forceUpdate();
<add> }
<add>});
<add>
<add>var MyComponent3 = React.createClass({
<add> statics: {
<add> someThing: 10,
<add> foo: function() {},
<add> },
<add> propTypes: {
<add> highlightEntities: React.PropTypes.bool,
<add> linkifyEntities: React.PropTypes.bool,
<add> text: React.PropTypes.shape({
<add> text: React.PropTypes.string,
<add> ranges: React.PropTypes.array
<add> }).isRequired
<add> },
<add>
<add> getDefaultProps: function() {
<add> foo();
<add> return {
<add> linkifyEntities: true,
<add> highlightEntities: false
<add> };
<add> },
<add>
<add> getInitialState: function() {
<add> this.props.foo();
<add> return {
<add> heyoo: 23,
<add> };
<add> },
<add>
<add> _renderText: function(text) {
<add> return <Text text={text} />;
<add> },
<add>
<add> _renderImageRange: function(text, range) {
<add> var image = range.image;
<add> if (image) {
<add> return (
<add> <Image
<add> src={image.uri}
<add> height={image.height / image.scale}
<add> width={image.width / image.scale}
<add> />
<add> );
<add> }
<add> },
<add>
<add> autobindMe: function() {},
<add> dontAutobindMe: function() {},
<add>
<add> // Function comment
<add> _renderRange: function(text, range) {
<add> var self = this;
<add>
<add> self.dontAutobindMe();
<add> call(self.autobindMe);
<add>
<add> var type = rage.type;
<add> var {highlightEntities} = this.props;
<add>
<add> if (type === 'ImageAtRange') {
<add> return this._renderImageRange(text, range);
<add> }
<add>
<add> if (this.props.linkifyEntities) {
<add> text =
<add> <Link href={usersURI}>
<add> {text}
<add> </Link>;
<add> } else {
<add> text = <span>{text}</span>;
<add> }
<add>
<add> return text;
<add> },
<add>
<add> /* This is a comment */
<add> render: function() {
<add> var content = this.props.text;
<add> return (
<add> <BaseText
<add> {...this.props}
<add> textRenderer={this._renderText}
<add> rangeRenderer={this._renderRange}
<add> text={content.text}
<add> />
<add> );
<add> }
<add>});
<add>
<add>module.exports = Relay.createContainer(MyComponent, {
<add> queries: {
<add> me: Relay.graphql`this is not graphql`,
<add> }
<add>});
<ide><path>npm-react-codemod/test/class-test.output.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>var Relay = require('Relay');
<add>
<add>var Image = require('Image.react');
<add>
<add>/*
<add> * Multiline
<add> */
<add>class MyComponent extends React.Component {
<add> constructor(props, context) {
<add> super(props, context);
<add> var x = props.foo;
<add>
<add> this.state = {
<add> heyoo: 23,
<add> };
<add> }
<add>
<add> foo() {
<add> this.setState({heyoo: 24});
<add> }
<add>}
<add>
<add>// Class comment
<add>class MyComponent2 extends React.Component {
<add> constructor(props, context) {
<add> super(props, context);
<add> this.foo = this.foo.bind(this);
<add> }
<add>
<add> foo() {
<add> pass(this.foo);
<add> this.forceUpdate();
<add> }
<add>}
<add>
<add>MyComponent2.defaultProps = {a: 1};
<add>
<add>class MyComponent3 extends React.Component {
<add> constructor(props, context) {
<add> super(props, context);
<add> this._renderRange = this._renderRange.bind(this);
<add> this._renderText = this._renderText.bind(this);
<add> this.autobindMe = this.autobindMe.bind(this);
<add> props.foo();
<add>
<add> this.state = {
<add> heyoo: 23,
<add> };
<add> }
<add>
<add> _renderText(text) {
<add> return <Text text={text} />;
<add> }
<add>
<add> _renderImageRange(text, range) {
<add> var image = range.image;
<add> if (image) {
<add> return (
<add> <Image
<add> src={image.uri}
<add> height={image.height / image.scale}
<add> width={image.width / image.scale}
<add> />
<add> );
<add> }
<add> }
<add>
<add> autobindMe() {}
<add> dontAutobindMe() {}
<add>
<add> // Function comment
<add> _renderRange(text, range) {
<add> var self = this;
<add>
<add> self.dontAutobindMe();
<add> call(self.autobindMe);
<add>
<add> var type = rage.type;
<add> var {highlightEntities} = this.props;
<add>
<add> if (type === 'ImageAtRange') {
<add> return this._renderImageRange(text, range);
<add> }
<add>
<add> if (this.props.linkifyEntities) {
<add> text =
<add> <Link href={usersURI}>
<add> {text}
<add> </Link>;
<add> } else {
<add> text = <span>{text}</span>;
<add> }
<add>
<add> return text;
<add> }
<add>
<add> /* This is a comment */
<add> render() {
<add> var content = this.props.text;
<add> return (
<add> <BaseText
<add> {...this.props}
<add> textRenderer={this._renderText}
<add> rangeRenderer={this._renderRange}
<add> text={content.text}
<add> />
<add> );
<add> }
<add>}
<add>
<add>MyComponent3.defaultProps = function() {
<add> foo();
<add> return {
<add> linkifyEntities: true,
<add> highlightEntities: false
<add> };
<add>}();
<add>
<add>MyComponent3.foo = function() {};
<add>
<add>MyComponent3.propTypes = {
<add> highlightEntities: React.PropTypes.bool,
<add> linkifyEntities: React.PropTypes.bool,
<add> text: React.PropTypes.shape({
<add> text: React.PropTypes.string,
<add> ranges: React.PropTypes.array
<add> }).isRequired
<add>};
<add>
<add>MyComponent3.someThing = 10;
<add>
<add>module.exports = Relay.createContainer(MyComponent, {
<add> queries: {
<add> me: Relay.graphql`this is not graphql`,
<add> }
<add>});
<ide><path>npm-react-codemod/test/class-test2.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>var IdontNeedAParent = React.createClass({
<add> render: function() {
<add> return <div />;
<add> }
<add>});
<add>
<add>var ButIDo = React.createClass({
<add> foo: function() {
<add> this.setState({banana: '?'});
<add> },
<add>
<add> render: function() {
<add> return <div />;
<add> }
<add>});
<add>
<add>var IAccessProps = React.createClass({
<add>
<add> getInitialState: function() {
<add> return {
<add> relayReleaseDate: this.props.soon,
<add> };
<add> },
<add>
<add> render: function() {
<add> return
<add> }
<add>
<add>});
<ide><path>npm-react-codemod/test/class-test2.output.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>class IdontNeedAParent {
<add> render() {
<add> return <div />;
<add> }
<add>}
<add>
<add>class ButIDo extends React.Component {
<add> foo() {
<add> this.setState({banana: '?'});
<add> }
<add>
<add> render() {
<add> return <div />;
<add> }
<add>}
<add>
<add>class IAccessProps {
<add> constructor(props) {
<add> this.state = {
<add> relayReleaseDate: props.soon,
<add> };
<add> }
<add>
<add> render() {
<add> return
<add> }
<add>}
<ide><path>npm-react-codemod/test/class-test3.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>// Comment
<add>module.exports = React.createClass({
<add> propTypes: {
<add> foo: React.PropTypes.bool,
<add> },
<add>
<add> getInitialState: function() {
<add> return {
<add> foo: 'bar',
<add> };
<add> },
<add>
<add> render: function() {
<add> return <div />;
<add> }
<add>});
<ide><path>npm-react-codemod/test/class-test3.output.js
<add>'use strict';
<add>
<add>var React = require('React');
<add>
<add>// Comment
<add>module.exports = class __exports extends React.Component {
<add> constructor(props, context) {
<add> super(props, context);
<add>
<add> this.state = {
<add> foo: 'bar',
<add> };
<add> }
<add>
<add> render() {
<add> return <div />;
<add> }
<add>};
<add>
<add>module.exports.propTypes = {
<add> foo: React.PropTypes.bool,
<add>};
<ide><path>npm-react-codemod/transforms/class.js
<add>/*eslint-disable no-comma-dangle*/
<add>
<add>'use strict';
<add>
<add>function updateReactCreateClassToES6(file, api, options) {
<add> const j = api.jscodeshift;
<add>
<add> require('./utils/array-polyfills');
<add> const ReactUtils = require('./utils/ReactUtils')(j);
<add>
<add> const printOptions = options.printOptions || {quote: 'single'};
<add> const root = j(file.source);
<add>
<add> const AUTOBIND_IGNORE_KEYS = {
<add> componentDidMount: true,
<add> componentDidUpdate: true,
<add> componentWillReceiveProps: true,
<add> componentWillMount: true,
<add> componentWillUpdate: true,
<add> componentWillUnmount: true,
<add> getDefaultProps: true,
<add> getInitialState: true,
<add> render: true,
<add> shouldComponentUpdate: true,
<add> };
<add>
<add> const BASE_COMPONENT_METHODS = ['setState', 'forceUpdate'];
<add>
<add> const DEFAULT_PROPS_FIELD = 'getDefaultProps';
<add> const DEFAULT_PROPS_KEY = 'defaultProps';
<add> const GET_INITIAL_STATE_FIELD = 'getInitialState';
<add>
<add> const DEPRECATED_APIS = [
<add> 'getDOMNode',
<add> 'isMounted',
<add> 'replaceProps',
<add> 'replaceState',
<add> 'setProps',
<add> ];
<add>
<add> const STATIC_KEYS = {
<add> childContextTypes: true,
<add> contextTypes: true,
<add> displayName: true,
<add> propTypes: true,
<add> };
<add>
<add> // ---------------------------------------------------------------------------
<add> // Checks if the module uses mixins or accesses deprecated APIs.
<add> const checkDeprecatedAPICalls = classPath =>
<add> DEPRECATED_APIS.reduce(
<add> (acc, name) =>
<add> acc + j(classPath)
<add> .find(j.Identifier, {name})
<add> .size(),
<add> 0
<add> ) > 0;
<add>
<add> const callsDeprecatedAPIs = classPath => {
<add> if (checkDeprecatedAPICalls(classPath)) {
<add> console.log(
<add> file.path + ': "' + ReactUtils.getComponentName(classPath) + '" ' +
<add> 'skipped because of deprecated API calls. Remove calls to ' +
<add> DEPRECATED_APIS.join(', ') + ' in your React component and re-run ' +
<add> 'this script.'
<add> );
<add> return false;
<add> }
<add> return true;
<add> };
<add>
<add> const hasMixins = classPath => {
<add> if (ReactUtils.hasMixins(classPath)) {
<add> console.log(
<add> file.path + ': "' + ReactUtils.getComponentName(classPath) + '" ' +
<add> ' skipped because of mixins.'
<add> );
<add> return false;
<add> }
<add> return true;
<add> };
<add>
<add> // ---------------------------------------------------------------------------
<add> // Helpers
<add> const createFindPropFn = prop => property => (
<add> property.key &&
<add> property.key.type === 'Identifier' &&
<add> property.key.name === prop
<add> );
<add>
<add> const filterDefaultPropsField = node =>
<add> createFindPropFn(DEFAULT_PROPS_FIELD)(node);
<add>
<add> const filterGetInitialStateField = node =>
<add> createFindPropFn(GET_INITIAL_STATE_FIELD)(node);
<add>
<add> const findGetDefaultProps = specPath =>
<add> specPath.properties.find(createFindPropFn(DEFAULT_PROPS_FIELD));
<add>
<add> const findGetInitialState = specPath =>
<add> specPath.properties.find(createFindPropFn(GET_INITIAL_STATE_FIELD));
<add>
<add> // This is conservative; only check for `setState` and `forceUpdate` literals
<add> // instead of also checking which objects they are called on.
<add> const shouldExtendReactComponent = classPath =>
<add> BASE_COMPONENT_METHODS.some(name => (
<add> j(classPath)
<add> .find(j.Identifier, {name})
<add> .size() > 0
<add> ));
<add>
<add> const withComments = (to, from) => {
<add> to.comments = from.comments;
<add> return to;
<add> };
<add>
<add> // ---------------------------------------------------------------------------
<add> // Collectors
<add> const isFunctionExpression = node => (
<add> node.key &&
<add> node.key.type === 'Identifier' &&
<add> node.value &&
<add> node.value.type === 'FunctionExpression'
<add> );
<add>
<add> const collectStatics = specPath => {
<add> const statics = specPath.properties.find(createFindPropFn('statics'));
<add> const staticsObject =
<add> (statics && statics.value && statics.value.properties) || [];
<add>
<add> const getDefaultProps = findGetDefaultProps(specPath);
<add> if (getDefaultProps) {
<add> staticsObject.push(createDefaultProps(getDefaultProps));
<add> }
<add>
<add> return (
<add> staticsObject.concat(specPath.properties.filter(property =>
<add> property.key && STATIC_KEYS[property.key.name]
<add> ))
<add> .sort((a, b) => a.key.name < b.key.name)
<add> );
<add> };
<add>
<add> const collectFunctions = specPath => specPath.properties
<add> .filter(prop =>
<add> !(filterDefaultPropsField(prop) || filterGetInitialStateField(prop))
<add> )
<add> .filter(isFunctionExpression);
<add>
<add> const findAutobindNamesFor = (root, fnNames, literalOrIdentifier) => {
<add> const node = literalOrIdentifier;
<add> const autobindNames = {};
<add>
<add> j(root)
<add> .find(j.MemberExpression, {
<add> object: node.name ? {
<add> type: node.type,
<add> name: node.name,
<add> } : {type: node.type},
<add> property: {
<add> type: 'Identifier',
<add> },
<add> })
<add> .filter(path => path.value.property && fnNames[path.value.property.name])
<add> .filter(path => {
<add> const call = path.parent.value;
<add> return !(
<add> call &&
<add> call.type === 'CallExpression' &&
<add> call.callee.type === 'MemberExpression' &&
<add> call.callee.object.type === node.type &&
<add> call.callee.object.name === node.name &&
<add> call.callee.property.type === 'Identifier' &&
<add> call.callee.property.name === path.value.property.name
<add> );
<add> })
<add> .forEach(path => autobindNames[path.value.property.name] = true);
<add>
<add> return Object.keys(autobindNames);
<add> };
<add>
<add> const collectAutoBindFunctions = (functions, classPath) => {
<add> const fnNames = {};
<add> functions
<add> .filter(fn => !AUTOBIND_IGNORE_KEYS[fn.key.name])
<add> .forEach(fn => fnNames[fn.key.name] = true);
<add>
<add> const autobindNames = {};
<add> const add = name => autobindNames[name] = true;
<add>
<add> // Find `this.<foo>`
<add> findAutobindNamesFor(classPath, fnNames, j.thisExpression()).forEach(add);
<add>
<add> // Find `self.<foo>` if `self = this`
<add> j(classPath)
<add> .findVariableDeclarators()
<add> .filter(path => (
<add> path.value.id.type === 'Identifier' &&
<add> path.value.init &&
<add> path.value.init.type === 'ThisExpression'
<add> ))
<add> .forEach(path =>
<add> findAutobindNamesFor(
<add> j(path).closest(j.FunctionExpression).get(),
<add> fnNames,
<add> path.value.id
<add> ).forEach(add)
<add> );
<add>
<add> return Object.keys(autobindNames).sort();
<add> };
<add>
<add> // ---------------------------------------------------------------------------
<add> // Boom!
<add> const createMethodDefinition = fn =>
<add> withComments(j.methodDefinition(
<add> '',
<add> fn.key,
<add> fn.value
<add> ), fn);
<add>
<add> const createBindAssignment = name =>
<add> j.expressionStatement(
<add> j.assignmentExpression(
<add> '=',
<add> j.memberExpression(
<add> j.thisExpression(),
<add> j.identifier(name),
<add> false
<add> ),
<add> j.callExpression(
<add> j.memberExpression(
<add> j.memberExpression(
<add> j.thisExpression(),
<add> j.identifier(name),
<add> false
<add> ),
<add> j.identifier('bind'),
<add> false
<add> ),
<add> [j.thisExpression()]
<add> )
<add> )
<add> );
<add>
<add> const createSuperCall = shouldAddSuperCall =>
<add> !shouldAddSuperCall ?
<add> [] :
<add> [j.expressionStatement(
<add> j.callExpression(
<add> j.identifier('super'),
<add> [j.identifier('props'), j.identifier('context')]
<add> )
<add> )];
<add>
<add> const updatePropsAccess = getInitialState =>
<add> getInitialState ?
<add> j(getInitialState)
<add> .find(j.MemberExpression, {
<add> object: {
<add> type: 'ThisExpression',
<add> },
<add> property: {
<add> type: 'Identifier',
<add> name: 'props',
<add> },
<add> })
<add> .forEach(path => j(path).replaceWith(j.identifier('props')))
<add> .size() > 0 :
<add> false;
<add>
<add> const inlineGetInitialState = getInitialState => {
<add> if (!getInitialState) {
<add> return [];
<add> }
<add>
<add> return getInitialState.value.body.body.map(statement => {
<add> if (statement.type === 'ReturnStatement') {
<add> return j.expressionStatement(
<add> j.assignmentExpression(
<add> '=',
<add> j.memberExpression(
<add> j.thisExpression(),
<add> j.identifier('state'),
<add> false
<add> ),
<add> statement.argument
<add> )
<add> );
<add> }
<add>
<add> return statement;
<add> });
<add> };
<add>
<add> const createConstructorArgs = (shouldAddSuperClass, hasPropsAccess) => {
<add> if (shouldAddSuperClass) {
<add> return [j.identifier('props'), j.identifier('context')];
<add> } else if (hasPropsAccess) {
<add> return [j.identifier('props')];
<add> } else {
<add> return [];
<add> }
<add> };
<add>
<add> const createConstructor = (
<add> getInitialState,
<add> autobindFunctions,
<add> shouldAddSuperClass
<add> ) => {
<add> if (!getInitialState && !autobindFunctions.length) {
<add> return [];
<add> }
<add>
<add> const hasPropsAccess = updatePropsAccess(getInitialState);
<add> return [createMethodDefinition({
<add> key: j.identifier('constructor'),
<add> value: j.functionExpression(
<add> null,
<add> createConstructorArgs(shouldAddSuperClass, hasPropsAccess),
<add> j.blockStatement(
<add> [].concat(
<add> createSuperCall(shouldAddSuperClass),
<add> autobindFunctions.map(createBindAssignment),
<add> inlineGetInitialState(getInitialState)
<add> )
<add> )
<add> ),
<add> })];
<add> };
<add>
<add> const createES6Class = (
<add> name,
<add> functions,
<add> getInitialState,
<add> autobindFunctions,
<add> comments,
<add> shouldAddSuperClass
<add> ) =>
<add> withComments(j.classDeclaration(
<add> // ast-types does not yet support empty class names
<add> // See: https://github.com/benjamn/ast-types/pull/102
<add> name ? j.identifier(name) : j.identifier('__exports'),
<add> j.classBody(
<add> [].concat(
<add> createConstructor(
<add> getInitialState,
<add> autobindFunctions,
<add> shouldAddSuperClass
<add> ),
<add> functions.map(createMethodDefinition)
<add> )
<add> ),
<add> shouldAddSuperClass ? j.memberExpression(
<add> j.identifier('React'),
<add> j.identifier('Component'),
<add> false
<add> ) : null
<add> ), {comments});
<add>
<add> const createStaticAssignment = (name, staticProperty) =>
<add> withComments(j.expressionStatement(
<add> j.assignmentExpression(
<add> '=',
<add> j.memberExpression(
<add> name,
<add> j.identifier(staticProperty.key.name),
<add> false
<add> ),
<add> staticProperty.value
<add> )
<add> ), staticProperty);
<add>
<add> const createStaticAssignmentExpressions = (name, statics) =>
<add> statics.map(staticProperty => createStaticAssignment(name, staticProperty));
<add>
<add> const hasSingleReturnStatement = value => (
<add> value.type === 'FunctionExpression' &&
<add> value.body &&
<add> value.body.type === 'BlockStatement' &&
<add> value.body.body &&
<add> value.body.body.length === 1 &&
<add> value.body.body[0].type === 'ReturnStatement' &&
<add> value.body.body[0].argument &&
<add> value.body.body[0].argument.type === 'ObjectExpression'
<add> );
<add>
<add> const createDefaultPropsValue = value => {
<add> if (hasSingleReturnStatement(value)) {
<add> return value.body.body[0].argument;
<add> } else {
<add> return j.callExpression(
<add> value,
<add> []
<add> );
<add> }
<add> };
<add>
<add> const createDefaultProps = prop =>
<add> withComments(
<add> j.property(
<add> 'init',
<add> j.identifier(DEFAULT_PROPS_KEY),
<add> createDefaultPropsValue(prop.value)
<add> ),
<add> prop
<add> );
<add>
<add> const getComments = classPath => {
<add> if (classPath.value.comments) {
<add> return classPath.value.comments;
<add> }
<add> const declaration = j(classPath).closest(j.VariableDeclaration);
<add> if (declaration.size()) {
<add> return declaration.get().value.comments;
<add> }
<add> return null;
<add> };
<add>
<add> const createModuleExportsMemberExpression = () =>
<add> j.memberExpression(
<add> j.identifier('module'),
<add> j.identifier('exports'),
<add> false
<add> );
<add>
<add> const updateToES6Class = (classPath, shouldExtend, isModuleExports) => {
<add> const specPath = ReactUtils.getReactCreateClassSpec(classPath);
<add> const name = ReactUtils.getComponentName(classPath);
<add> const statics = collectStatics(specPath);
<add> const functions = collectFunctions(specPath);
<add> const comments = getComments(classPath);
<add>
<add> const autobindFunctions = collectAutoBindFunctions(functions, classPath);
<add> const getInitialState = findGetInitialState(specPath);
<add>
<add> const staticName =
<add> name ? j.identifier(name) : createModuleExportsMemberExpression();
<add>
<add> var path;
<add> if (isModuleExports) {
<add> path = ReactUtils.findReactCreateClassCallExpression(classPath);
<add> } else {
<add> path = j(classPath).closest(j.VariableDeclaration);
<add> }
<add>
<add> path.replaceWith(
<add> createES6Class(
<add> name,
<add> functions,
<add> getInitialState,
<add> autobindFunctions,
<add> comments,
<add> shouldExtend || shouldExtendReactComponent(classPath)
<add> )
<add> );
<add>
<add> const staticAssignments =
<add> createStaticAssignmentExpressions(staticName, statics);
<add> if (isModuleExports) {
<add> const body = root.get().value.body;
<add> body.push.apply(body, staticAssignments);
<add> } else {
<add> staticAssignments
<add> .forEach(expression => path = path.insertAfter(expression));
<add> }
<add> };
<add>
<add> if (
<add> options['no-explicit-require'] || ReactUtils.hasReact(root)
<add> ) {
<add> const apply = (path, isModuleExports) =>
<add> path
<add> .filter(hasMixins)
<add> .filter(callsDeprecatedAPIs)
<add> .forEach(classPath => updateToES6Class(
<add> classPath,
<add> !options['no-super-class'],
<add> isModuleExports
<add> ));
<add>
<add> const didTransform = (
<add> apply(ReactUtils.findReactCreateClass(root), false).size() +
<add> apply(ReactUtils.findReactCreateClassModuleExports(root), true).size()
<add> ) > 0;
<add>
<add> if (didTransform) {
<add> return root.toSource(printOptions) + '\n';
<add> }
<add> }
<add>
<add> return null;
<add>}
<add>
<add>module.exports = updateReactCreateClassToES6; | 9 |
Javascript | Javascript | remove unused argument to oneway | 7d15e7d99cab555bf6c86d56b6bb30f5c57280e7 | <ide><path>packages/ember-metal/lib/binding.js
<ide> Binding.prototype = /** @scope Ember.Binding.prototype */ {
<ide> means that if you change the "to" side directly, the "from" side may have
<ide> a different value.
<ide>
<del> @param {Boolean} flag
<del> (Optional) passing nothing here will make the binding oneWay. You can
<del> instead pass false to disable oneWay, making the binding two way again.
<del>
<ide> @returns {Ember.Binding} receiver
<ide> */
<del> oneWay: function(flag) {
<add> oneWay: function() {
<ide> this._oneWay = true;
<ide> return this;
<ide> }, | 1 |
Python | Python | fix dag audit_log route | c5878315f3df0854a0902d91668cc369e7466405 | <ide><path>airflow/www/views.py
<ide> def robots(self):
<ide> (permissions.ACTION_CAN_READ, permissions.RESOURCE_AUDIT_LOG),
<ide> ]
<ide> )
<add> def legacy_audit_log(self):
<add> """Redirect from url param."""
<add> return redirect(url_for('Airflow.audit_log', **request.args))
<add>
<add> @expose('/dags/<string:dag_id>/audit_log')
<add> @auth.has_access(
<add> [
<add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_DAG),
<add> (permissions.ACTION_CAN_READ, permissions.RESOURCE_AUDIT_LOG),
<add> ]
<add> )
<ide> @provide_session
<del> def audit_log(self, session=None):
<del> dag_id = request.args.get('dag_id')
<add> def audit_log(self, dag_id: str, session=None):
<ide> dag = get_airflow_app().dag_bag.get_dag(dag_id, session=session)
<ide> dag_model = DagModel.get_dagmodel(dag_id, session=session)
<ide> if not dag:
<ide> flash(f'DAG "{dag_id}" seems to be missing from DagBag.', "error")
<ide> return redirect(url_for('Airflow.index'))
<ide>
<del> included_events = conf.get('webserver', 'audit_view_included_events', fallback=None)
<del> excluded_events = conf.get('webserver', 'audit_view_excluded_events', fallback=None)
<add> included_events_raw = conf.get('webserver', 'audit_view_included_events', fallback=None)
<add> excluded_events_raw = conf.get('webserver', 'audit_view_excluded_events', fallback=None)
<ide>
<ide> query = session.query(Log).filter(Log.dag_id == dag_id)
<del> if included_events:
<del> included_events = {event.strip() for event in included_events.split(',')}
<add> if included_events_raw:
<add> included_events = {event.strip() for event in included_events_raw.split(',')}
<ide> query = query.filter(Log.event.in_(included_events))
<del> elif excluded_events:
<del> excluded_events = {event.strip() for event in excluded_events.split(',')}
<add> elif excluded_events_raw:
<add> excluded_events = {event.strip() for event in excluded_events_raw.split(',')}
<ide> query = query.filter(Log.event.notin_(excluded_events))
<ide>
<ide> dag_audit_logs = query.all()
<del> content = self.render_template(
<add> return self.render_template(
<ide> 'airflow/dag_audit_log.html',
<ide> dag=dag,
<ide> dag_model=dag_model,
<ide> def audit_log(self, session=None):
<ide> dag_logs=dag_audit_logs,
<ide> page_size=PAGE_SIZE,
<ide> )
<del> return content
<ide>
<ide>
<ide> class ConfigurationView(AirflowBaseView):
<ide><path>tests/www/views/test_views_home.py
<ide> def test_dashboard_flash_messages_type(user_client):
<ide>
<ide>
<ide> def test_audit_log_view(user_client, working_dags):
<del> url = 'audit_log?dag_id=filter_test_1'
<del> resp = user_client.get(url, follow_redirects=True)
<add> resp = user_client.get('/dags/filter_test_1/audit_log')
<ide> check_content_in_response('Dag Audit Log', resp)
<ide>
<ide> | 2 |
Java | Java | add classpath check for context-propagation | 6c3a7192b726c96db7069ba3dd77bba91b999b23 | <ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/ReactiveTypeHandler.java
<ide> import org.springframework.http.server.ServerHttpResponse;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.util.ClassUtils;
<ide> import org.springframework.util.CollectionUtils;
<ide> import org.springframework.util.MimeType;
<ide> import org.springframework.web.HttpMediaTypeNotAcceptableException;
<ide> class ReactiveTypeHandler {
<ide> private static final List<MediaType> JSON_STREAMING_MEDIA_TYPES =
<ide> Arrays.asList(MediaType.APPLICATION_NDJSON, MediaType.APPLICATION_STREAM_JSON);
<ide>
<add> private static final boolean isContextPropagationPresent = ClassUtils.isPresent(
<add> "io.micrometer.context.ContextSnapshot", ReactiveTypeHandler.class.getClassLoader());
<add>
<ide> private static final Log logger = LogFactory.getLog(ReactiveTypeHandler.class);
<ide>
<ide>
<ide> public ResponseBodyEmitter handleValue(Object returnValue, MethodParameter retur
<ide> ReactiveAdapter adapter = this.adapterRegistry.getAdapter(clazz);
<ide> Assert.state(adapter != null, () -> "Unexpected return value type: " + clazz);
<ide>
<del> if (Mono.class.isAssignableFrom(clazz)) {
<del> ContextSnapshot snapshot = ContextSnapshot.captureAll();
<del> returnValue = ((Mono<?>) returnValue).contextWrite(snapshot::updateContext);
<del> }
<del> else if (Flux.class.isAssignableFrom(clazz)) {
<del> ContextSnapshot snapshot = ContextSnapshot.captureAll();
<del> returnValue = ((Flux<?>) returnValue).contextWrite(snapshot::updateContext);
<add> if (isContextPropagationPresent) {
<add> returnValue = ContextSnapshotHelper.writeReactorContext(returnValue);
<ide> }
<ide>
<ide> ResolvableType elementType = ResolvableType.forMethodParameter(returnType).getGeneric();
<ide> public ResolvableType getReturnType() {
<ide> }
<ide> }
<ide>
<add>
<add> private static class ContextSnapshotHelper {
<add>
<add> public static Object writeReactorContext(Object returnValue) {
<add> if (Mono.class.isAssignableFrom(returnValue.getClass())) {
<add> ContextSnapshot snapshot = ContextSnapshot.captureAll();
<add> return ((Mono<?>) returnValue).contextWrite(snapshot::updateContext);
<add> }
<add> else if (Flux.class.isAssignableFrom(returnValue.getClass())) {
<add> ContextSnapshot snapshot = ContextSnapshot.captureAll();
<add> return ((Flux<?>) returnValue).contextWrite(snapshot::updateContext);
<add> }
<add> else {
<add> return returnValue;
<add> }
<add> }
<add> }
<add>
<ide> } | 1 |
Go | Go | move "load" to graph/load.go | f2029f7be19c75ccc291608d1bd07bc0de220276 | <ide><path>graph/load.go
<add>package graph
<add>
<add>import (
<add> "encoding/json"
<add> "io"
<add> "io/ioutil"
<add> "os"
<add> "path"
<add>
<add> "github.com/docker/docker/archive"
<add> "github.com/docker/docker/engine"
<add> "github.com/docker/docker/image"
<add> "github.com/docker/docker/utils"
<add>)
<add>
<add>// Loads a set of images into the repository. This is the complementary of ImageExport.
<add>// The input stream is an uncompressed tar ball containing images and metadata.
<add>func (s *TagStore) CmdLoad(job *engine.Job) engine.Status {
<add> tmpImageDir, err := ioutil.TempDir("", "docker-import-")
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> defer os.RemoveAll(tmpImageDir)
<add>
<add> var (
<add> repoTarFile = path.Join(tmpImageDir, "repo.tar")
<add> repoDir = path.Join(tmpImageDir, "repo")
<add> )
<add>
<add> tarFile, err := os.Create(repoTarFile)
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> if _, err := io.Copy(tarFile, job.Stdin); err != nil {
<add> return job.Error(err)
<add> }
<add> tarFile.Close()
<add>
<add> repoFile, err := os.Open(repoTarFile)
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add> if err := os.Mkdir(repoDir, os.ModeDir); err != nil {
<add> return job.Error(err)
<add> }
<add> if err := archive.Untar(repoFile, repoDir, nil); err != nil {
<add> return job.Error(err)
<add> }
<add>
<add> dirs, err := ioutil.ReadDir(repoDir)
<add> if err != nil {
<add> return job.Error(err)
<add> }
<add>
<add> for _, d := range dirs {
<add> if d.IsDir() {
<add> if err := s.recursiveLoad(job.Eng, d.Name(), tmpImageDir); err != nil {
<add> return job.Error(err)
<add> }
<add> }
<add> }
<add>
<add> repositoriesJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", "repositories"))
<add> if err == nil {
<add> repositories := map[string]Repository{}
<add> if err := json.Unmarshal(repositoriesJson, &repositories); err != nil {
<add> return job.Error(err)
<add> }
<add>
<add> for imageName, tagMap := range repositories {
<add> for tag, address := range tagMap {
<add> if err := s.Set(imageName, tag, address, true); err != nil {
<add> return job.Error(err)
<add> }
<add> }
<add> }
<add> } else if !os.IsNotExist(err) {
<add> return job.Error(err)
<add> }
<add>
<add> return engine.StatusOK
<add>}
<add>
<add>func (s *TagStore) recursiveLoad(eng *engine.Engine, address, tmpImageDir string) error {
<add> if err := eng.Job("image_get", address).Run(); err != nil {
<add> utils.Debugf("Loading %s", address)
<add>
<add> imageJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", address, "json"))
<add> if err != nil {
<add> utils.Debugf("Error reading json", err)
<add> return err
<add> }
<add>
<add> layer, err := os.Open(path.Join(tmpImageDir, "repo", address, "layer.tar"))
<add> if err != nil {
<add> utils.Debugf("Error reading embedded tar", err)
<add> return err
<add> }
<add> img, err := image.NewImgJSON(imageJson)
<add> if err != nil {
<add> utils.Debugf("Error unmarshalling json", err)
<add> return err
<add> }
<add> if img.Parent != "" {
<add> if !s.graph.Exists(img.Parent) {
<add> if err := s.recursiveLoad(eng, img.Parent, tmpImageDir); err != nil {
<add> return err
<add> }
<add> }
<add> }
<add> if err := s.graph.Register(imageJson, layer, img); err != nil {
<add> return err
<add> }
<add> }
<add> utils.Debugf("Completed processing %s", address)
<add>
<add> return nil
<add>}
<ide><path>graph/service.go
<ide> func (s *TagStore) Install(eng *engine.Engine) error {
<ide> eng.Register("history", s.CmdHistory)
<ide> eng.Register("images", s.CmdImages)
<ide> eng.Register("viz", s.CmdViz)
<add> eng.Register("load", s.CmdLoad)
<ide> return nil
<ide> }
<ide>
<ide><path>server/image.go
<ide> package server
<ide>
<ide> import (
<del> "encoding/json"
<ide> "fmt"
<ide> "io"
<ide> "io/ioutil"
<ide> func (srv *Server) Build(job *engine.Job) engine.Status {
<ide> return engine.StatusOK
<ide> }
<ide>
<del>// Loads a set of images into the repository. This is the complementary of ImageExport.
<del>// The input stream is an uncompressed tar ball containing images and metadata.
<del>func (srv *Server) ImageLoad(job *engine.Job) engine.Status {
<del> tmpImageDir, err := ioutil.TempDir("", "docker-import-")
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> defer os.RemoveAll(tmpImageDir)
<del>
<del> var (
<del> repoTarFile = path.Join(tmpImageDir, "repo.tar")
<del> repoDir = path.Join(tmpImageDir, "repo")
<del> )
<del>
<del> tarFile, err := os.Create(repoTarFile)
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> if _, err := io.Copy(tarFile, job.Stdin); err != nil {
<del> return job.Error(err)
<del> }
<del> tarFile.Close()
<del>
<del> repoFile, err := os.Open(repoTarFile)
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del> if err := os.Mkdir(repoDir, os.ModeDir); err != nil {
<del> return job.Error(err)
<del> }
<del> if err := archive.Untar(repoFile, repoDir, nil); err != nil {
<del> return job.Error(err)
<del> }
<del>
<del> dirs, err := ioutil.ReadDir(repoDir)
<del> if err != nil {
<del> return job.Error(err)
<del> }
<del>
<del> for _, d := range dirs {
<del> if d.IsDir() {
<del> if err := srv.recursiveLoad(job.Eng, d.Name(), tmpImageDir); err != nil {
<del> return job.Error(err)
<del> }
<del> }
<del> }
<del>
<del> repositoriesJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", "repositories"))
<del> if err == nil {
<del> repositories := map[string]graph.Repository{}
<del> if err := json.Unmarshal(repositoriesJson, &repositories); err != nil {
<del> return job.Error(err)
<del> }
<del>
<del> for imageName, tagMap := range repositories {
<del> for tag, address := range tagMap {
<del> if err := srv.daemon.Repositories().Set(imageName, tag, address, true); err != nil {
<del> return job.Error(err)
<del> }
<del> }
<del> }
<del> } else if !os.IsNotExist(err) {
<del> return job.Error(err)
<del> }
<del>
<del> return engine.StatusOK
<del>}
<del>
<del>func (srv *Server) recursiveLoad(eng *engine.Engine, address, tmpImageDir string) error {
<del> if err := eng.Job("image_get", address).Run(); err != nil {
<del> utils.Debugf("Loading %s", address)
<del>
<del> imageJson, err := ioutil.ReadFile(path.Join(tmpImageDir, "repo", address, "json"))
<del> if err != nil {
<del> utils.Debugf("Error reading json", err)
<del> return err
<del> }
<del>
<del> layer, err := os.Open(path.Join(tmpImageDir, "repo", address, "layer.tar"))
<del> if err != nil {
<del> utils.Debugf("Error reading embedded tar", err)
<del> return err
<del> }
<del> img, err := image.NewImgJSON(imageJson)
<del> if err != nil {
<del> utils.Debugf("Error unmarshalling json", err)
<del> return err
<del> }
<del> if img.Parent != "" {
<del> if !srv.daemon.Graph().Exists(img.Parent) {
<del> if err := srv.recursiveLoad(eng, img.Parent, tmpImageDir); err != nil {
<del> return err
<del> }
<del> }
<del> }
<del> if err := srv.daemon.Graph().Register(imageJson, layer, img); err != nil {
<del> return err
<del> }
<del> }
<del> utils.Debugf("Completed processing %s", address)
<del>
<del> return nil
<del>}
<del>
<ide> func (srv *Server) ImageTag(job *engine.Job) engine.Status {
<ide> if len(job.Args) != 2 && len(job.Args) != 3 {
<ide> return job.Errorf("Usage: %s IMAGE REPOSITORY [TAG]\n", job.Name)
<ide><path>server/init.go
<ide> func InitServer(job *engine.Job) engine.Status {
<ide> "tag": srv.ImageTag, // FIXME merge with "image_tag"
<ide> "info": srv.DockerInfo,
<ide> "log": srv.Log,
<del> "load": srv.ImageLoad,
<ide> "build": srv.Build,
<ide> "pull": srv.ImagePull,
<ide> "import": srv.ImageImport, | 4 |
Javascript | Javascript | convert values to uint, not int | d6df1b91579e95283768935ec3f43eb34e2dc818 | <ide><path>lib/buffer.js
<ide> exports.INSPECT_MAX_BYTES = 50;
<ide>
<ide>
<ide> Buffer.poolSize = 8 * 1024;
<del>var poolSize = Buffer.poolSize;
<del>var poolOffset = 0;
<del>var allocPool = alloc({}, poolSize);
<add>var poolSize, poolOffset, allocPool;
<ide>
<ide>
<ide> function createPool() {
<ide> poolSize = Buffer.poolSize;
<ide> allocPool = alloc({}, poolSize);
<ide> poolOffset = 0;
<ide> }
<add>createPool();
<ide>
<ide>
<ide> function Buffer(subject, encoding) {
<ide> if (!util.isBuffer(this))
<ide> return new Buffer(subject, encoding);
<ide>
<ide> if (util.isNumber(subject))
<del> this.length = subject > 0 ? Math.floor(subject) : 0;
<add> this.length = subject > 0 ? subject >>> 0 : 0;
<ide> else if (util.isString(subject))
<ide> this.length = Buffer.byteLength(subject, encoding = encoding || 'utf8');
<ide> else if (util.isObject(subject))
<ide> function Buffer(subject, encoding) {
<ide> 'size: 0x' + kMaxLength.toString(16) + ' bytes');
<ide> }
<ide>
<del> if (this.length < Buffer.poolSize / 2 && this.length > 0) {
<add> if (this.length <= (Buffer.poolSize >>> 1) && this.length > 0) {
<ide> if (this.length > poolSize - poolOffset)
<ide> createPool();
<ide> this.parent = sliceOnto(allocPool,
<ide> Buffer.concat = function(list, length) {
<ide> for (var i = 0; i < list.length; i++)
<ide> length += list[i].length;
<ide> } else {
<del> length = ~~length;
<add> length = length >>> 0;
<ide> }
<ide>
<del> if (length < 0) length = 0;
<del>
<ide> if (list.length === 0)
<ide> return new Buffer(0);
<ide> else if (list.length === 1)
<ide> var writeMsg = '.write(string, encoding, offset, length) is deprecated.' +
<ide> Buffer.prototype.write = function(string, offset, length, encoding) {
<ide> // Buffer#write(string);
<ide> if (util.isUndefined(offset)) {
<del> offset = 0;
<ide> encoding = 'utf8';
<add> length = this.length;
<add> offset = 0;
<ide>
<ide> // Buffer#write(string, encoding)
<ide> } else if (util.isUndefined(length) && util.isString(offset)) {
<ide> encoding = offset;
<add> length = this.length;
<ide> offset = 0;
<ide>
<ide> // Buffer#write(string, offset[, length][, encoding])
<ide> } else if (isFinite(offset)) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (isFinite(length)) {
<del> length = ~~length;
<add> length = length >>> 0;
<ide> if (util.isUndefined(encoding))
<ide> encoding = 'utf8';
<ide> } else {
<ide> Buffer.prototype.write = function(string, offset, length, encoding) {
<ide>
<ide> var swap = encoding;
<ide> encoding = offset;
<del> offset = ~~length;
<add> offset = length >>> 0;
<ide> length = swap;
<ide> }
<ide>
<ide> Buffer.prototype.write = function(string, offset, length, encoding) {
<ide> encoding = !!encoding ? (encoding + '').toLowerCase() : 'utf8';
<ide>
<ide> if (string.length > 0 && (length < 0 || offset < 0))
<del> throw new RangeError('attempt to write beyond buffer bounds');
<add> throw new RangeError('attempt to write outside buffer bounds');
<ide>
<ide> var ret;
<ide> switch (encoding) {
<ide> Buffer.prototype.slice = function(start, end) {
<ide>
<ide>
<ide> function checkOffset(offset, ext, length) {
<del> if (offset < 0 || offset + ext > length)
<add> if (offset + ext > length)
<ide> throw new RangeError('index out of range');
<ide> }
<ide>
<ide>
<ide> Buffer.prototype.readUInt8 = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 1, this.length);
<ide> return this[offset];
<ide> function readUInt16(buffer, offset, isBigEndian) {
<ide>
<ide>
<ide> Buffer.prototype.readUInt16LE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 2, this.length);
<ide> return readUInt16(this, offset, false, noAssert);
<ide> };
<ide>
<ide>
<ide> Buffer.prototype.readUInt16BE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 2, this.length);
<ide> return readUInt16(this, offset, true, noAssert);
<ide> function readUInt32(buffer, offset, isBigEndian) {
<ide>
<ide>
<ide> Buffer.prototype.readUInt32LE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<ide> return readUInt32(this, offset, false);
<ide> };
<ide>
<ide>
<ide> Buffer.prototype.readUInt32BE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<ide> return readUInt32(this, offset, true);
<ide> Buffer.prototype.readUInt32BE = function(offset, noAssert) {
<ide> */
<ide>
<ide> Buffer.prototype.readInt8 = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 1, this.length);
<del> if (!(this[offset] & 0x80))
<del> return (this[offset]);
<del> return ((0xff - this[offset] + 1) * -1);
<add> var val = this[offset];
<add> return !(val & 0x80) ? val : (0xff - val + 1) * -1;
<ide> };
<ide>
<ide>
<ide> function readInt16(buffer, offset, isBigEndian) {
<ide> var val = readUInt16(buffer, offset, isBigEndian);
<del> if (!(val & 0x8000))
<del> return val;
<del> return (0xffff - val + 1) * -1;
<add> return !(val & 0x8000) ? val : (0xffff - val + 1) * -1;
<ide> }
<ide>
<ide>
<ide> Buffer.prototype.readInt16LE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 2, this.length);
<ide> return readInt16(this, offset, false);
<ide> };
<ide>
<ide>
<ide> Buffer.prototype.readInt16BE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 2, this.length);
<ide> return readInt16(this, offset, true);
<ide> Buffer.prototype.readInt16BE = function(offset, noAssert) {
<ide>
<ide> function readInt32(buffer, offset, isBigEndian) {
<ide> var val = readUInt32(buffer, offset, isBigEndian);
<del> if (!(val & 0x80000000))
<del> return (val);
<del> return (0xffffffff - val + 1) * -1;
<add> return !(val & 0x80000000) ? val : (0xffffffff - val + 1) * -1;
<ide> }
<ide>
<ide>
<ide> Buffer.prototype.readInt32LE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<ide> return readInt32(this, offset, false);
<ide> };
<ide>
<ide>
<ide> Buffer.prototype.readInt32BE = function(offset, noAssert) {
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkOffset(offset, 4, this.length);
<ide> return readInt32(this, offset, true);
<ide> };
<ide>
<ide>
<ide> function checkInt(buffer, value, offset, ext, max, min) {
<add> if (!(buffer instanceof Buffer))
<add> throw new TypeError('buffer must be a Buffer instance');
<ide> if (value > max || value < min)
<ide> throw new TypeError('value is out of bounds');
<del> if (offset < 0 || offset + ext > buffer.length || buffer.length + offset < 0)
<add> if (offset + ext > buffer.length)
<ide> throw new RangeError('index out of range');
<ide> }
<ide>
<ide>
<ide> Buffer.prototype.writeUInt8 = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 1, 0xff, 0);
<ide> this[offset] = value;
<ide> function writeUInt16(buffer, value, offset, isBigEndian) {
<ide>
<ide> Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 2, 0xffff, 0);
<ide> return writeUInt16(this, value, offset, false);
<ide> Buffer.prototype.writeUInt16LE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeUInt16BE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 2, 0xffff, 0);
<ide> return writeUInt16(this, value, offset, true);
<ide> function writeUInt32(buffer, value, offset, isBigEndian) {
<ide>
<ide> Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 4, 0xffffffff, 0);
<ide> return writeUInt32(this, value, offset, false);
<ide> Buffer.prototype.writeUInt32LE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 4, 0xffffffff, 0);
<ide> return writeUInt32(this, value, offset, true);
<ide> Buffer.prototype.writeUInt32BE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 1, 0x7f, -0x80);
<ide> if (value < 0) value = 0xff + value + 1;
<ide> Buffer.prototype.writeInt8 = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 2, 0x7fff, -0x8000);
<ide> if (value < 0) value = 0xffff + value + 1;
<ide> Buffer.prototype.writeInt16LE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 2, 0x7fff, -0x8000);
<ide> if (value < 0) value = 0xffff + value + 1;
<ide> Buffer.prototype.writeInt16BE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
<ide> if (value < 0) value = 0xffffffff + value + 1;
<ide> Buffer.prototype.writeInt32LE = function(value, offset, noAssert) {
<ide>
<ide> Buffer.prototype.writeInt32BE = function(value, offset, noAssert) {
<ide> value = +value;
<del> offset = ~~offset;
<add> offset = offset >>> 0;
<ide> if (!noAssert)
<ide> checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000);
<ide> if (value < 0) value = 0xffffffff + value + 1; | 1 |
Javascript | Javascript | use number type for bitfields | 488b973d6838610a8f651d1c812fa82d74cf8bbd | <ide><path>src/renderers/shared/fiber/ReactTypeOfInternalContext.js
<ide>
<ide> 'use strict';
<ide>
<del>export type TypeOfInternalContext = 0 | 1;
<add>export type TypeOfInternalContext = number;
<ide>
<ide> module.exports = {
<ide> NoContext: 0,
<ide><path>src/renderers/shared/fiber/ReactTypeOfSideEffect.js
<ide>
<ide> 'use strict';
<ide>
<del>export type TypeOfSideEffect = 0 | 1 | 2 | 3 | 4 | 8 | 16 | 32 | 64;
<add>export type TypeOfSideEffect = number;
<ide>
<ide> module.exports = {
<del> NoEffect: 0, // 0b0000000
<del> Placement: 1, // 0b0000001
<del> Update: 2, // 0b0000010
<add> NoEffect: 0, // 0b0000000
<add> Placement: 1, // 0b0000001
<add> Update: 2, // 0b0000010
<ide> PlacementAndUpdate: 3, // 0b0000011
<del> Deletion: 4, // 0b0000100
<del> ContentReset: 8, // 0b0001000
<del> Callback: 16, // 0b0010000
<del> Err: 32, // 0b0100000
<del> Ref: 64, // 0b1000000
<add> Deletion: 4, // 0b0000100
<add> ContentReset: 8, // 0b0001000
<add> Callback: 16, // 0b0010000
<add> Err: 32, // 0b0100000
<add> Ref: 64, // 0b1000000
<ide> }; | 2 |
Ruby | Ruby | remove tests for `brew cask search` | a8bfe09c499d725972543c1857365768d5739329 | <ide><path>Library/Homebrew/test/cask/cli/search_spec.rb
<del>require_relative "shared_examples/invalid_option"
<del>
<del>describe Hbc::CLI::Search, :cask do
<del> before do
<del> allow(Tty).to receive(:width).and_return(0)
<del> end
<del>
<del> it_behaves_like "a command that handles invalid options"
<del>
<del> it "lists the available Casks that match the search term" do
<del> allow(GitHub).to receive(:search_code).and_return([])
<del>
<del> expect {
<del> Hbc::CLI::Search.run("local")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> ==> Matches
<del> local-caffeine
<del> local-transmission
<del> EOS
<del> end
<del>
<del> it "outputs a plain list when stdout is not a TTY" do
<del> allow(GitHub).to receive(:search_code).and_return([])
<del>
<del> expect {
<del> Hbc::CLI::Search.run("local")
<del> }.to output(<<~EOS).to_stdout
<del> local-caffeine
<del> local-transmission
<del> EOS
<del> end
<del>
<del> it "returns matches even when online search failed" do
<del> allow(GitHub).to receive(:search_code).and_raise(GitHub::Error.new("reason"))
<del>
<del> expect {
<del> Hbc::CLI::Search.run("local")
<del> }.to output(<<~EOS).to_stdout
<del> local-caffeine
<del> local-transmission
<del> EOS
<del> .and output(/^Warning: Error searching on GitHub: reason/).to_stderr
<del> end
<del>
<del> it "shows that there are no Casks matching a search term that did not result in anything" do
<del> expect {
<del> Hbc::CLI::Search.run("foo-bar-baz")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> No Cask found for "foo-bar-baz".
<del> EOS
<del> end
<del>
<del> it "doesn't output anything to non-TTY stdout when there are no matches" do
<del> allow(GitHub).to receive(:search_code).and_return([])
<del>
<del> expect { Hbc::CLI::Search.run("foo-bar-baz") }
<del> .to not_to_output.to_stdout
<del> .and not_to_output.to_stderr
<del> end
<del>
<del> it "lists all Casks available offline with no search term" do
<del> allow(GitHub).to receive(:search_code).and_raise(GitHub::Error.new("reason"))
<del> expect { Hbc::CLI::Search.run }
<del> .to output(/local-caffeine/).to_stdout.as_tty
<del> .and not_to_output.to_stderr
<del> end
<del>
<del> it "ignores hyphens in search terms" do
<del> expect {
<del> Hbc::CLI::Search.run("lo-cal-caffeine")
<del> }.to output(/local-caffeine/).to_stdout.as_tty
<del> end
<del>
<del> it "ignores hyphens in Cask tokens" do
<del> expect {
<del> Hbc::CLI::Search.run("localcaffeine")
<del> }.to output(/local-caffeine/).to_stdout.as_tty
<del> end
<del>
<del> it "accepts multiple arguments" do
<del> expect {
<del> Hbc::CLI::Search.run("local caffeine")
<del> }.to output(/local-caffeine/).to_stdout.as_tty
<del> end
<del>
<del> it "accepts a regexp argument" do
<del> expect {
<del> Hbc::CLI::Search.run("/^local-c[a-z]ffeine$/")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> ==> Matches
<del> local-caffeine
<del> EOS
<del> end
<del>
<del> it "returns both exact and partial matches" do
<del> expect {
<del> Hbc::CLI::Search.run("test-opera")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> ==> Matches
<del> test-opera
<del> test-opera-mail
<del> EOS
<del> end
<del>
<del> it "does not search the Tap name" do
<del> expect {
<del> Hbc::CLI::Search.run("caskroom")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> No Cask found for "caskroom".
<del> EOS
<del> end
<del>
<del> it "highlights installed packages" do
<del> Hbc::CLI::Install.run("local-caffeine")
<del>
<del> expect {
<del> Hbc::CLI::Search.run("local-caffeine")
<del> }.to output(<<~EOS).to_stdout.as_tty
<del> ==> Matches
<del> local-caffeine ✔
<del> EOS
<del> end
<del>end | 1 |
PHP | PHP | remove failing test | 7c593cbf4dea40f87d9bd2bfa65e56c9ae7f19be | <ide><path>tests/TestCase/Collection/CollectionTest.php
<ide> public function testTransposeUnEvenLengthShouldThrowException()
<ide>
<ide> $collection->transpose();
<ide> }
<del>
<del> /**
<del> * Tests the chunk method with preserved keys
<del> *
<del> * @return void
<del> */
<del> public function testChunkPreserveKeys()
<del> {
<del> $collection = new Collection(['a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5, 'f' => 6, 'g' => 7]);
<del> $chunked = $collection->chunk(2, true)->toList();
<del> $expected = [['a' => 1, 'b' => 2], ['c' => 3, 'd' => 4], ['e' => 5, 'f' => 6], ['g' => 7]];
<del> $this->assertEquals($expected, $chunked);
<del> }
<ide> } | 1 |
Javascript | Javascript | write variable names in correct manner | 3522ce6f34b63f5d9922835307f31980de1fe0b9 | <ide><path>api-server/src/server/utils/donation.test.js
<ide> describe('donation', () => {
<ide> Authorization: `Bearer ${mockAccessToken}`
<ide> }
<ide> };
<del> const successVerificationResponce = {
<add> const successVerificationResponse = {
<ide> data: {
<ide> verification_status: 'SUCCESS'
<ide> }
<ide> };
<del> const failedVerificationResponce = {
<add> const failedVerificationResponse = {
<ide> data: {
<ide> verification_status: 'FAILED'
<ide> }
<ide> };
<ide>
<ide> it('calls paypal for Webhook verification', async () => {
<ide> axios.post.mockImplementationOnce(() =>
<del> Promise.resolve(successVerificationResponce)
<add> Promise.resolve(successVerificationResponse)
<ide> );
<ide>
<ide> await expect(
<ide> describe('donation', () => {
<ide> });
<ide> it('throws error if verification not successful', async () => {
<ide> axios.post.mockImplementationOnce(() =>
<del> Promise.resolve(failedVerificationResponce)
<add> Promise.resolve(failedVerificationResponse)
<ide> );
<ide>
<ide> await expect( | 1 |
Go | Go | check symlink error when saving layer | 8616b0690a3ac905fc6ee06ff7524c837fcb8c92 | <ide><path>image/tarexport/save.go
<ide> import (
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/system"
<ide> "github.com/docker/docker/reference"
<add> "github.com/pkg/errors"
<ide> )
<ide>
<ide> type imageDescriptor struct {
<ide> func (s *saveSession) saveLayer(id layer.ChainID, legacyImg image.V1Image, creat
<ide> if err != nil {
<ide> return distribution.Descriptor{}, err
<ide> }
<del> os.Symlink(relPath, layerPath)
<add> if err := os.Symlink(relPath, layerPath); err != nil {
<add> return distribution.Descriptor{}, errors.Wrap(err, "error creating symlink while saving layer")
<add> }
<ide> } else {
<ide> // Use system.CreateSequential rather than os.Create. This ensures sequential
<ide> // file access on Windows to avoid eating into MM standby list. | 1 |
Go | Go | fix issue with exec tty caused by 15446 | 5ffcecf130aea8c0b92d1be728e2c302cf2c6c70 | <ide><path>api/server/exec.go
<ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response
<ide> }
<ide> var (
<ide> execName = vars["name"]
<del> stdin, inStream io.ReadCloser
<add> stdin io.ReadCloser
<ide> stdout, stderr, outStream io.Writer
<ide> )
<ide>
<ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response
<ide> if !execStartCheck.Detach {
<ide> var err error
<ide> // Setting up the streaming http interface.
<del> inStream, outStream, err = hijackServer(w)
<add> inStream, outStream, err := hijackServer(w)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (s *Server) postContainerExecStart(version version.Version, w http.Response
<ide> fmt.Fprintf(outStream, "HTTP/1.1 200 OK\r\nContent-Type: application/vnd.docker.raw-stream\r\n\r\n")
<ide> }
<ide>
<add> stdin = inStream
<add> stdout = outStream
<ide> if !execStartCheck.Tty {
<ide> stderr = stdcopy.NewStdWriter(outStream, stdcopy.Stderr)
<ide> stdout = stdcopy.NewStdWriter(outStream, stdcopy.Stdout)
<ide> }
<del> stdin = inStream
<ide> }
<ide>
<ide> // Now run the user process in container.
<ide><path>integration-cli/docker_cli_exec_unix_test.go
<ide> func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) {
<ide> c.Fatal("timed out running docker exec")
<ide> }
<ide> }
<add>
<add>func (s *DockerSuite) TestExecTTY(c *check.C) {
<add> dockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top")
<add>
<add> cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh")
<add> p, err := pty.Start(cmd)
<add> c.Assert(err, check.IsNil)
<add> defer p.Close()
<add>
<add> _, err = p.Write([]byte("cat /foo && exit\n"))
<add> c.Assert(err, check.IsNil)
<add>
<add> chErr := make(chan error)
<add> go func() {
<add> chErr <- cmd.Wait()
<add> }()
<add> select {
<add> case err := <-chErr:
<add> c.Assert(err, check.IsNil)
<add> case <-time.After(3 * time.Second):
<add> c.Fatal("timeout waiting for exec to exit")
<add> }
<add>
<add> buf := make([]byte, 256)
<add> read, err := p.Read(buf)
<add> c.Assert(err, check.IsNil)
<add> c.Assert(bytes.Contains(buf, []byte("hello")), check.Equals, true, check.Commentf(string(buf[:read])))
<add>} | 2 |
Java | Java | fix bug that ignored custom json prefix | ead0124b393fab17e71f6d879af54a7eefb28d56 | <ide><path>spring-web/src/main/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverter.java
<ide> import java.lang.reflect.Type;
<ide> import java.nio.charset.Charset;
<ide>
<del>import com.fasterxml.jackson.core.JsonEncoding;
<del>import com.fasterxml.jackson.core.JsonGenerator;
<del>import com.fasterxml.jackson.core.JsonProcessingException;
<del>import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
<del>import com.fasterxml.jackson.databind.JavaType;
<del>import com.fasterxml.jackson.databind.ObjectMapper;
<del>import com.fasterxml.jackson.databind.SerializationFeature;
<del>
<ide> import org.springframework.http.HttpInputMessage;
<ide> import org.springframework.http.HttpOutputMessage;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.util.Assert;
<ide>
<add>import com.fasterxml.jackson.core.JsonEncoding;
<add>import com.fasterxml.jackson.core.JsonGenerator;
<add>import com.fasterxml.jackson.core.JsonProcessingException;
<add>import com.fasterxml.jackson.core.util.DefaultPrettyPrinter;
<add>import com.fasterxml.jackson.databind.JavaType;
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>import com.fasterxml.jackson.databind.SerializationFeature;
<add>
<ide> /**
<ide> * Implementation of {@link org.springframework.http.converter.HttpMessageConverter HttpMessageConverter} that
<ide> * can read and write JSON using <a href="http://jackson.codehaus.org/">Jackson 2.x's</a> {@link ObjectMapper}.
<ide> protected void writeInternal(Object object, HttpOutputMessage outputMessage)
<ide>
<ide> try {
<ide> if (this.jsonPrefix != null) {
<del> jsonGenerator.writeRaw("{} && ");
<add> jsonGenerator.writeRaw(this.jsonPrefix);
<ide> }
<ide> this.objectMapper.writeValue(jsonGenerator, object);
<ide> }
<ide><path>spring-web/src/main/java/org/springframework/http/converter/json/MappingJacksonHttpMessageConverter.java
<ide> import org.codehaus.jackson.map.ObjectMapper;
<ide> import org.codehaus.jackson.map.SerializationConfig;
<ide> import org.codehaus.jackson.type.JavaType;
<del>
<ide> import org.springframework.http.HttpInputMessage;
<ide> import org.springframework.http.HttpOutputMessage;
<ide> import org.springframework.http.MediaType;
<ide> protected void writeInternal(Object object, HttpOutputMessage outputMessage)
<ide>
<ide> try {
<ide> if (this.jsonPrefix != null) {
<del> jsonGenerator.writeRaw("{} && ");
<add> jsonGenerator.writeRaw(this.jsonPrefix);
<ide> }
<ide> this.objectMapper.writeValue(jsonGenerator, object);
<ide> }
<ide><path>spring-web/src/test/java/org/springframework/http/converter/json/AbstractMappingJacksonHttpMessageConverterTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide>
<ide> package org.springframework.http.converter.json;
<ide>
<del>import static org.junit.Assert.assertArrayEquals;
<del>import static org.junit.Assert.assertEquals;
<del>import static org.junit.Assert.assertTrue;
<del>
<ide> import java.io.IOException;
<ide> import java.nio.charset.Charset;
<ide> import java.util.ArrayList;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<ide> import org.springframework.http.converter.HttpMessageNotReadableException;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * Base class for Jackson and Jackson 2 converter tests.
<ide> *
<ide><path>spring-web/src/test/java/org/springframework/http/converter/json/MappingJackson2HttpMessageConverterTests.java
<ide> /*
<del> * Copyright 2002-2012 the original author or authors.
<add> * Copyright 2002-2013 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> import java.util.ArrayList;
<ide> import java.util.List;
<ide>
<del>import com.fasterxml.jackson.databind.JavaType;
<del>import com.fasterxml.jackson.databind.ObjectMapper;
<del>import static org.junit.Assert.*;
<ide> import org.junit.Test;
<del>
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.MockHttpInputMessage;
<ide> import org.springframework.http.MockHttpOutputMessage;
<ide>
<add>import com.fasterxml.jackson.databind.JavaType;
<add>import com.fasterxml.jackson.databind.ObjectMapper;
<add>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * Jackson 2.x converter tests.
<ide> *
<ide> public void prettyPrint() throws Exception {
<ide> assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result);
<ide> }
<ide>
<add> @Test
<add> public void prefixJson() throws Exception {
<add> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<add> getConverter().setPrefixJson(true);
<add> getConverter().writeInternal("foo", outputMessage);
<add>
<add> assertEquals("{} && \"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8")));
<add> }
<add>
<add> @Test
<add> public void prefixJsonCustom() throws Exception {
<add> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<add> getConverter().setJsonPrefix(")]}',");
<add> getConverter().writeInternal("foo", outputMessage);
<add>
<add> assertEquals(")]}',\"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8")));
<add> }
<add>
<ide>
<ide> public static class PrettyPrintBean {
<ide>
<ide><path>spring-web/src/test/java/org/springframework/http/converter/json/MappingJacksonHttpMessageConverterTests.java
<ide>
<ide> import org.codehaus.jackson.map.type.TypeFactory;
<ide> import org.codehaus.jackson.type.JavaType;
<del>import static org.junit.Assert.*;
<ide> import org.junit.Test;
<del>
<ide> import org.springframework.core.ParameterizedTypeReference;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.MockHttpInputMessage;
<ide> import org.springframework.http.MockHttpOutputMessage;
<ide>
<add>import static org.junit.Assert.*;
<add>
<ide> /**
<ide> * Jackson 1.x converter tests.
<ide> *
<ide> public void prettyPrint() throws Exception {
<ide> assertEquals("{" + NEWLINE_SYSTEM_PROPERTY + " \"name\" : \"Jason\"" + NEWLINE_SYSTEM_PROPERTY + "}", result);
<ide> }
<ide>
<add> @Test
<add> public void prefixJson() throws Exception {
<add> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<add> getConverter().setPrefixJson(true);
<add> getConverter().writeInternal("foo", outputMessage);
<add>
<add> assertEquals("{} && \"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8")));
<add> }
<add>
<add> @Test
<add> public void prefixJsonCustom() throws Exception {
<add> MockHttpOutputMessage outputMessage = new MockHttpOutputMessage();
<add> getConverter().setJsonPrefix(")]}',");
<add> getConverter().writeInternal("foo", outputMessage);
<add>
<add> assertEquals(")]}',\"foo\"", outputMessage.getBodyAsString(Charset.forName("UTF-8")));
<add> }
<add>
<ide>
<ide> public static class PrettyPrintBean {
<ide> | 5 |
Ruby | Ruby | use yield instead block argument | f0eaf11c0e29e6f30a82b52f7e63d24b9675281f | <ide><path>activerecord/lib/active_record/identity_map.rb
<ide> def current
<ide> repositories[current_repository_name] ||= Weakling::WeakHash.new
<ide> end
<ide>
<del> def with_repository(name = :default, &block)
<add> def with_repository(name = :default)
<ide> old_repository = self.current_repository_name
<ide> self.current_repository_name = name
<ide>
<del> block.call(current)
<add> yield if block_given?
<ide> ensure
<ide> self.current_repository_name = old_repository
<ide> end
<ide>
<del> def without(&block)
<add> def without
<ide> old, self.enabled = self.enabled, false
<ide>
<del> block.call
<add> yield if block_given?
<ide> ensure
<ide> self.enabled = old
<ide> end | 1 |
Javascript | Javascript | improve the coverage of the validator | 302fd02f7140ff06d511eaae807944e335682177 | <ide><path>lib/internal/validators.js
<ide> const validateInteger = hideStackFrames(
<ide> const validateInt32 = hideStackFrames(
<ide> (value, name, min = -2147483648, max = 2147483647) => {
<ide> // The defaults for min and max correspond to the limits of 32-bit integers.
<add> if (typeof value !== 'number') {
<add> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<add> }
<ide> if (!isInt32(value)) {
<del> if (typeof value !== 'number') {
<del> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<del> }
<ide> if (!NumberIsInteger(value)) {
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<ide> }
<ide> const validateInt32 = hideStackFrames(
<ide> );
<ide>
<ide> const validateUint32 = hideStackFrames((value, name, positive) => {
<add> if (typeof value !== 'number') {
<add> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<add> }
<ide> if (!isUint32(value)) {
<del> if (typeof value !== 'number') {
<del> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<del> }
<ide> if (!NumberIsInteger(value)) {
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<ide> }
<ide><path>test/parallel/test-validators.js
<ide> const {
<ide> validateNumber,
<ide> validateObject,
<ide> validateString,
<add> validateInt32,
<add> validateUint32,
<ide> } = require('internal/validators');
<ide> const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;
<ide> const outOfRangeError = {
<ide> const invalidArgValueError = {
<ide> // validateInteger() works with unsafe integers.
<ide> validateInteger(MAX_SAFE_INTEGER + 1, 'foo', 0, MAX_SAFE_INTEGER + 1);
<ide> validateInteger(MIN_SAFE_INTEGER - 1, 'foo', MIN_SAFE_INTEGER - 1);
<add>
<add> // validateInt32() and validateUint32()
<add> [
<add> Symbol(), 1n, {}, [], false, true, undefined, null, () => {}, '', '1',
<add> ].forEach((val) => assert.throws(() => validateInt32(val, 'name'), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> }));
<add> [
<add> 2147483647 + 1, -2147483648 - 1, NaN,
<add> ].forEach((val) => assert.throws(() => validateInt32(val, 'name'), {
<add> code: 'ERR_OUT_OF_RANGE'
<add> }));
<add> [
<add> 0, 1, -1,
<add> ].forEach((val) => validateInt32(val, 'name'));
<add> [
<add> Symbol(), 1n, {}, [], false, true, undefined, null, () => {}, '', '1',
<add> ].forEach((val) => assert.throws(() => validateUint32(val, 'name'), {
<add> code: 'ERR_INVALID_ARG_TYPE'
<add> }));
<add> [
<add> 4294967296, -1, NaN,
<add> ].forEach((val) => assert.throws(() => validateUint32(val, 'name'), {
<add> code: 'ERR_OUT_OF_RANGE'
<add> }));
<add> [
<add> 0, 1,
<add> ].forEach((val) => validateUint32(val, 'name'));
<ide> }
<ide>
<ide> { | 2 |
Text | Text | fix corepack grammar for `--force` flag | 43a267f67344faeebf0996069aab2ff2ee0d147e | <ide><path>doc/api/corepack.md
<ide> install. To avoid this problem, consider one of the following options:
<ide> binaries anyway and will ensure that the requested versions are always
<ide> available, so installing the package managers explicitly isn't needed anymore.
<ide>
<del>* Add the `--force` to `npm install`; this will tell npm that it's fine to
<add>* Add the `--force` flag to `npm install`; this will tell npm that it's fine to
<ide> override binaries, but you'll erase the Corepack ones in the process (should
<ide> that happen, run [`corepack enable`][] again to add them back).
<ide> | 1 |
Javascript | Javascript | add param name | 3c6821b9ad10331a37a995b87a92b1cb7594a70c | <ide><path>src/ngAnimate/animate.js
<ide> angular.module('ngAnimate', ['ng'])
<ide> * @methodOf ngAnimate.$animate
<ide> * @function
<ide> *
<del> * @param {boolean=} If provided then set the animation on or off.
<add> * @param {boolean=} value If provided then set the animation on or off.
<ide> * @return {boolean} Current animation state.
<ide> *
<ide> * @description | 1 |
Javascript | Javascript | use object writer for thrown errors | a0778a97e19fb6e661a4277f18f758443d20470c | <ide><path>lib/repl.js
<ide> function REPLServer(prompt,
<ide> (_, pre, line) => pre + (line - 1));
<ide> }
<ide> }
<del> errStack = util.inspect(e);
<add> errStack = self.writer(e);
<ide>
<ide> // Remove one line error braces to keep the old style in place.
<ide> if (errStack[errStack.length - 1] === ']') {
<ide> function REPLServer(prompt,
<ide> }
<ide>
<ide> if (errStack === '') {
<del> errStack = `Thrown: ${util.inspect(e)}\n`;
<add> errStack = `Thrown: ${self.writer(e)}\n`;
<ide> } else {
<ide> const ln = errStack.endsWith('\n') ? '' : '\n';
<ide> errStack = `Thrown:\n${errStack}${ln}`;
<ide><path>test/parallel/test-repl-pretty-stack.js
<ide> const assert = require('assert');
<ide> const repl = require('repl');
<ide>
<ide>
<del>function run({ command, expected }) {
<add>function run({ command, expected, ...extraREPLOptions }) {
<ide> let accum = '';
<ide>
<ide> const inputStream = new ArrayStream();
<ide> function run({ command, expected }) {
<ide> input: inputStream,
<ide> output: outputStream,
<ide> terminal: false,
<del> useColors: false
<add> useColors: false,
<add> ...extraREPLOptions
<ide> });
<ide>
<ide> r.write(`${command}\n`);
<ide> const tests = [
<ide> command: 'throw new Error(\'Whoops!\')',
<ide> expected: 'Thrown:\nError: Whoops!\n'
<ide> },
<add> {
<add> command: '(() => { const err = Error(\'Whoops!\'); ' +
<add> 'err.foo = \'bar\'; throw err; })()',
<add> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22 foo: \'bar\' }\n',
<add> },
<add> {
<add> command: '(() => { const err = Error(\'Whoops!\'); ' +
<add> 'err.foo = \'bar\'; throw err; })()',
<add> expected: 'Thrown:\n{ Error: Whoops!\n at repl:1:22 foo: ' +
<add> "\u001b[32m'bar'\u001b[39m }\n",
<add> useColors: true
<add> },
<ide> {
<ide> command: 'foo = bar;',
<ide> expected: 'Thrown:\nReferenceError: bar is not defined\n' | 2 |
Java | Java | use valid example in javadoc for @enablewebflux | 91c0fbaadbb5e17f1f44261f3ae641fbad9aae22 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/config/EnableWebFlux.java
<ide> * @EnableWebFlux
<ide> * @ComponentScan(basePackageClasses = MyConfiguration.class)
<ide> * public class MyConfiguration implements WebFluxConfigurer {
<add> *
<add> * private ObjectMapper objectMapper;
<ide> *
<ide> * @Override
<del> * public void configureMessageWriters(List<HttpMessageWriter<?>> messageWriters) {
<del> * messageWriters.add(new MyHttpMessageWriter());
<add> * public void configureHttpMessageCodecs(ServerCodecConfigurer configurer) {
<add> * configurer.defaultCodecs().jackson2JsonEncoder(
<add> * new Jackson2JsonEncoder(objectMapper)
<add> * );
<add> * configurer.defaultCodecs().jackson2JsonDecoder(
<add> * new Jackson2JsonDecoder(objectMapper)
<add> * );
<ide> * }
<ide> *
<ide> * // ... | 1 |
Python | Python | fix common backend styles | 01e2148732e4083b4850345e5ce4dd499cb5999e | <ide><path>keras/backend/common.py
<ide>
<ide>
<ide> def epsilon():
<del> """Returns the value of the fuzz
<del> factor used in numeric expressions.
<add> """Returns the value of the fuzz factor used in numeric expressions.
<ide>
<ide> # Returns
<ide> A float.
<ide> def epsilon():
<ide>
<ide>
<ide> def set_epsilon(e):
<del> """Sets the value of the fuzz
<del> factor used in numeric expressions.
<add> """Sets the value of the fuzz factor used in numeric expressions.
<ide>
<ide> # Arguments
<ide> e: float. New value of epsilon.
<ide><path>keras/backend/tensorflow_backend.py
<ide> import numpy as np
<ide> import os
<ide>
<del>from .common import floatx
<del>from .common import _EPSILON
<add>from .common import floatx, epsilon
<ide> from .common import image_data_format
<ide> from ..utils.generic_utils import has_arg
<ide>
<ide> def categorical_crossentropy(target, output, from_logits=False):
<ide> axis=len(output.get_shape()) - 1,
<ide> keep_dims=True)
<ide> # manual computation of crossentropy
<del> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
<del> output = tf.clip_by_value(output, epsilon, 1. - epsilon)
<add> _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
<add> output = tf.clip_by_value(output, _epsilon, 1. - _epsilon)
<ide> return - tf.reduce_sum(target * tf.log(output),
<ide> axis=len(output.get_shape()) - 1)
<ide> else:
<ide> def sparse_categorical_crossentropy(target, output, from_logits=False):
<ide> # Note: tf.nn.sparse_softmax_cross_entropy_with_logits
<ide> # expects logits, Keras expects probabilities.
<ide> if not from_logits:
<del> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
<del> output = tf.clip_by_value(output, epsilon, 1 - epsilon)
<add> _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
<add> output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
<ide> output = tf.log(output)
<ide>
<ide> output_shape = output.get_shape()
<ide> def binary_crossentropy(target, output, from_logits=False):
<ide> # expects logits, Keras expects probabilities.
<ide> if not from_logits:
<ide> # transform back to logits
<del> epsilon = _to_tensor(_EPSILON, output.dtype.base_dtype)
<del> output = tf.clip_by_value(output, epsilon, 1 - epsilon)
<add> _epsilon = _to_tensor(epsilon(), output.dtype.base_dtype)
<add> output = tf.clip_by_value(output, _epsilon, 1 - _epsilon)
<ide> output = tf.log(output / (1 - output))
<ide>
<ide> return tf.nn.sigmoid_cross_entropy_with_logits(labels=target,
<ide><path>keras/backend/theano_backend.py
<ide> from theano.sandbox.softsign import softsign as T_softsign
<ide>
<ide> import numpy as np
<del>from .common import _FLOATX, floatx, _EPSILON, image_data_format
<add>from .common import floatx, epsilon, image_data_format
<ide> from ..utils.generic_utils import has_arg
<ide> # Legacy functions
<ide> from .common import set_image_dim_ordering, image_dim_ordering
<ide>
<ide>
<ide> # INTERNAL UTILS
<del>theano.config.floatX = _FLOATX
<add>theano.config.floatX = floatx()
<ide> _LEARNING_PHASE = T.scalar(dtype='uint8', name='keras_learning_phase') # 0 = test, 1 = train
<ide> _UID_PREFIXES = defaultdict(int)
<ide>
<ide> def categorical_crossentropy(target, output, from_logits=False):
<ide> # scale preds so that the class probas of each sample sum to 1
<ide> output /= output.sum(axis=-1, keepdims=True)
<ide> # avoid numerical instability with _EPSILON clipping
<del> output = T.clip(output, _EPSILON, 1.0 - _EPSILON)
<add> output = T.clip(output, epsilon(), 1.0 - epsilon())
<ide> return T.nnet.categorical_crossentropy(output, target)
<ide>
<ide>
<ide> def binary_crossentropy(target, output, from_logits=False):
<ide> if from_logits:
<ide> output = T.nnet.sigmoid(output)
<ide> # avoid numerical instability with _EPSILON clipping
<del> output = T.clip(output, _EPSILON, 1.0 - _EPSILON)
<add> output = T.clip(output, epsilon(), 1.0 - epsilon())
<ide> return T.nnet.binary_crossentropy(output, target)
<ide>
<ide>
<ide> def dropout(x, level, noise_shape=None, seed=None):
<ide>
<ide> def l2_normalize(x, axis=None):
<ide> square_sum = T.sum(T.square(x), axis=axis, keepdims=True)
<del> norm = T.sqrt(T.maximum(square_sum, _EPSILON))
<add> norm = T.sqrt(T.maximum(square_sum, epsilon()))
<ide> return x / norm
<ide>
<ide> | 3 |
Python | Python | update download_url for beta | 5a55922baa5356d34d1c5b6c0ffee29fb7f7c66a | <ide><path>setup.py
<ide> def fullsplit(path, result=None):
<ide> author = 'Django Software Foundation',
<ide> author_email = 'foundation@djangoproject.com',
<ide> description = 'A high-level Python Web framework that encourages rapid development and clean, pragmatic design.',
<del> download_url = 'http://media.djangoproject.com/releases/1.3/Django-1.3-alpha-1.tar.gz',
<add> download_url = 'http://media.djangoproject.com/releases/1.3/Django-1.3-beta-1.tar.gz',
<ide> packages = packages,
<ide> cmdclass = cmdclasses,
<ide> data_files = data_files, | 1 |
Python | Python | add exception handling for bbox values | 5e941bece26cee3edc08e7f9fb3c1e03c1742ad7 | <ide><path>src/transformers/modeling_layoutlm.py
<ide> def forward(
<ide>
<ide> words_embeddings = inputs_embeds
<ide> position_embeddings = self.position_embeddings(position_ids)
<del> left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])
<del> upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])
<del> right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])
<del> lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])
<add> try:
<add> left_position_embeddings = self.x_position_embeddings(bbox[:, :, 0])
<add> upper_position_embeddings = self.y_position_embeddings(bbox[:, :, 1])
<add> right_position_embeddings = self.x_position_embeddings(bbox[:, :, 2])
<add> lower_position_embeddings = self.y_position_embeddings(bbox[:, :, 3])
<add> except IndexError as e:
<add> raise IndexError("The :obj:`bbox`coordinate values should be within 0-1000 range.") from e
<add>
<ide> h_position_embeddings = self.h_position_embeddings(bbox[:, :, 3] - bbox[:, :, 1])
<ide> w_position_embeddings = self.w_position_embeddings(bbox[:, :, 2] - bbox[:, :, 0])
<ide> token_type_embeddings = self.token_type_embeddings(token_type_ids) | 1 |
Python | Python | add debug message for glances server announce | d503fca2b0afa5e57c184540919ecb87b64c18a3 | <ide><path>glances/core/glances_autodiscover.py
<ide> def get_servers_list(self):
<ide>
<ide> def add_server(self, name, ip, port):
<ide> """Add a new server to the dict"""
<del> self._server_dict[name] = {'name': name.split(':')[0], 'ip': ip, 'port': port}
<del> logger.debug("Servers list: %s" % self._server_dict)
<add> try:
<add> self._server_dict[name] = {'name': name.split(':')[0], 'ip': ip, 'port': port}
<add> logger.debug("Servers list: %s" % self._server_dict)
<add> except KeyError:
<add> pass
<ide>
<ide> def remove_server(self, name):
<ide> """Remove a server from the dict"""
<del> del(self._server_dict[name])
<del> logger.debug("Servers list: %s" % self._server_dict)
<add> try:
<add> del(self._server_dict[name])
<add> logger.debug("Servers list: %s" % self._server_dict)
<add> except KeyError:
<add> pass
<ide>
<ide>
<ide> class GlancesAutoDiscoverListener(object):
<ide> def __init__(self, hostname, args=None):
<ide> zeroconf_bind_address = netifaces.ifaddresses(netifaces.interfaces()[1])[netifaces.AF_INET][0]['addr']
<ide> except:
<ide> zeroconf_bind_address = args.bind_address
<del> # /!!!
<add> print("Announce the Glances server on the local area network (using %s IP address)" % zeroconf_bind_address)
<add> # /!!!
<ide>
<ide> if zeroconf_tag:
<ide> logger.info( | 1 |
Javascript | Javascript | remove an extra allocation for open source bundles | f93e34e98052d7bb6594bd02012e13432e039445 | <ide><path>packages/react-dom/src/events/EventListener.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>export function addEventBubbleListener(
<add> element: Element,
<add> eventType: string,
<add> listener: Function,
<add>): void {
<add> element.addEventListener(eventType, listener, false);
<add>}
<add>
<add>export function addEventCaptureListener(
<add> element: Element,
<add> eventType: string,
<add> listener: Function,
<add>): void {
<add> element.addEventListener(eventType, listener, true);
<add>}
<ide><path>packages/react-dom/src/events/ReactDOMEventListener.js
<ide> import {batchedUpdates} from 'events/ReactGenericBatching';
<ide> import {isFiberMounted} from 'react-reconciler/reflection';
<ide> import {HostRoot} from 'shared/ReactTypeOfWork';
<del>import EventListener from 'fbjs/lib/EventListener';
<ide>
<add>import {addEventBubbleListener, addEventCaptureListener} from './EventListener';
<ide> import getEventTarget from './getEventTarget';
<ide> import {getClosestInstanceFromNode} from '../client/ReactDOMComponentTree';
<ide>
<ide> export function trapBubbledEvent(topLevelType, handlerBaseName, element) {
<ide> if (!element) {
<ide> return null;
<ide> }
<del> return EventListener.listen(
<add> addEventBubbleListener(
<ide> element,
<ide> handlerBaseName,
<ide> dispatchEvent.bind(null, topLevelType),
<ide> export function trapCapturedEvent(topLevelType, handlerBaseName, element) {
<ide> if (!element) {
<ide> return null;
<ide> }
<del> return EventListener.capture(
<add> addEventCaptureListener(
<ide> element,
<ide> handlerBaseName,
<ide> dispatchEvent.bind(null, topLevelType),
<ide><path>packages/react-dom/src/events/forks/EventListener-www.js
<add>/**
<add> * Copyright (c) 2013-present, Facebook, Inc.
<add> *
<add> * This source code is licensed under the MIT license found in the
<add> * LICENSE file in the root directory of this source tree.
<add> *
<add> * @flow
<add> */
<add>
<add>var EventListenerWWW = require('EventListener');
<add>
<add>import typeof * as EventListenerType from '../EventListener';
<add>import typeof * as EventListenerShimType from './EventListener-www';
<add>
<add>export function addEventBubbleListener(
<add> element: Element,
<add> eventType: string,
<add> listener: Function,
<add>): void {
<add> EventListenerWWW.listen(element, eventType, listener);
<add>}
<add>
<add>export function addEventCaptureListener(
<add> element: Element,
<add> eventType: string,
<add> listener: Function,
<add>): void {
<add> EventListenerWWW.capture(element, eventType, listener);
<add>}
<add>
<add>// Flow magic to verify the exports of this file match the original version.
<add>// eslint-disable-next-line no-unused-vars
<add>type Check<_X, Y: _X, X: Y = _X> = null;
<add>// eslint-disable-next-line no-unused-expressions
<add>(null: Check<EventListenerShimType, EventListenerType>);
<ide><path>scripts/flow/environment.js
<ide> declare module 'ReactFiberErrorDialog' {
<ide> showErrorDialog: (error: mixed) => boolean,
<ide> };
<ide> }
<add>
<add>// EventListener www fork
<add>declare module 'EventListener' {
<add> declare module.exports: {
<add> listen: (target: Element, type: string, callback: Function) => mixed,
<add> capture: (target: Element, type: string, callback: Function) => mixed,
<add> };
<add>}
<ide><path>scripts/rollup/forks.js
<ide> const forks = Object.freeze({
<ide> return null;
<ide> }
<ide> },
<add>
<add> // We wrap top-level listeners into guards on www.
<add> 'react-dom/src/events/EventListener': (bundleType, entry) => {
<add> switch (bundleType) {
<add> case FB_DEV:
<add> case FB_PROD:
<add> // Use the www fork which is integrated with TimeSlice profiling.
<add> return 'react-dom/src/events/forks/EventListener-www.js';
<add> default:
<add> return null;
<add> }
<add> },
<ide> });
<ide>
<ide> module.exports = forks; | 5 |
Go | Go | fix delete on nonexistent container | 1d9546fc62c559dbcbb3dbdce40318fb7c4d67a2 | <ide><path>container/view.go
<ide> func (db *memDB) Delete(c *Container) error {
<ide> txn.Delete(memdbNamesTable, nameAssociation{name: name})
<ide> }
<ide>
<del> if err := txn.Delete(memdbContainersTable, NewBaseContainer(c.ID, c.Root)); err != nil {
<del> return err
<del> }
<add> // Ignore error - the container may not actually exist in the
<add> // db, but we still need to clean up associated names.
<add> txn.Delete(memdbContainersTable, NewBaseContainer(c.ID, c.Root))
<ide> return nil
<ide> })
<ide> }
<ide><path>container/view_test.go
<ide> func TestNames(t *testing.T) {
<ide>
<ide> view = db.Snapshot()
<ide> assert.Equal(t, map[string][]string{"containerid1": {"name1", "name3", "name4"}, "containerid4": {"name2"}}, view.GetAllNames())
<add>
<add> // Release containerid1's names with Delete even though no container exists
<add> assert.NoError(t, db.Delete(&Container{ID: "containerid1"}))
<add>
<add> // Reusing one of those names should work
<add> assert.NoError(t, db.ReserveName("name1", "containerid4"))
<add> view = db.Snapshot()
<add> assert.Equal(t, map[string][]string{"containerid4": {"name1", "name2"}}, view.GetAllNames())
<ide> } | 2 |
Ruby | Ruby | remove unneeded tests | 4edb4976762dcb94c8aa2deca4dc96d498d6418a | <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
<ide> def test_connection_no_db
<ide> end
<ide> end
<ide>
<del> def test_connection_no_adapter
<del> assert_raises(ArgumentError) do
<del> Base.sqlite3_connection :database => ':memory:'
<del> end
<del> end
<del>
<del> def test_connection_wrong_adapter
<del> assert_raises(ArgumentError) do
<del> Base.sqlite3_connection :database => ':memory:',:adapter => 'vuvuzela'
<del> end
<del> end
<del>
<ide> def test_bad_timeout
<ide> assert_raises(TypeError) do
<ide> Base.sqlite3_connection :database => ':memory:', | 1 |
Javascript | Javascript | fix drawerlayoutandroid method parameter | d66b94472711d2d85d75a1e3b314c4f4cef8616a | <ide><path>Libraries/Components/DrawerAndroid/DrawerLayoutAndroid.android.js
<ide> var DrawerLayoutAndroid = React.createClass({
<ide> /**
<ide> * Opens the drawer.
<ide> */
<del> openDrawer: function(test: number) {
<add> openDrawer: function() {
<ide> UIManager.dispatchViewManagerCommand(
<ide> this._getDrawerLayoutHandle(),
<ide> UIManager.AndroidDrawerLayout.Commands.openDrawer, | 1 |
Go | Go | fix circular import for windows vfs graphdriver | 49834e8d5922f8c256124177b188d89007af03f6 | <ide><path>daemon/daemon.go
<ide> import (
<ide> "github.com/docker/docker/daemon/execdriver"
<ide> "github.com/docker/docker/daemon/execdriver/execdrivers"
<ide> "github.com/docker/docker/daemon/graphdriver"
<add> _ "github.com/docker/docker/daemon/graphdriver/vfs"
<ide> "github.com/docker/docker/daemon/logger"
<ide> "github.com/docker/docker/daemon/network"
<ide> "github.com/docker/docker/graph"
<ide><path>daemon/daemon_unix.go
<ide> import (
<ide> "github.com/Sirupsen/logrus"
<ide> "github.com/docker/docker/autogen/dockerversion"
<ide> "github.com/docker/docker/daemon/graphdriver"
<del> _ "github.com/docker/docker/daemon/graphdriver/vfs"
<ide> "github.com/docker/docker/graph"
<ide> "github.com/docker/docker/pkg/archive"
<ide> "github.com/docker/docker/pkg/fileutils"
<ide><path>daemon/graphdriver/driver_windows.go
<ide> package graphdriver
<ide>
<del>import (
<del> _ "github.com/docker/docker/daemon/graphdriver/vfs"
<del>
<del> // TODO Windows - Add references to real graph driver when PR'd
<del>)
<del>
<ide> type DiffDiskDriver interface {
<ide> Driver
<ide> CopyDiff(id, sourceId string) error | 3 |
Python | Python | fix syntax error and update docs | ef714529bbf6a7060230a327415a3c955f9f643d | <ide><path>celery/backends/tyrant.py
<ide>
<ide>
<ide> class Backend(BaseBackend):
<del> """Tokyo Cabinet based task backend store."""
<add> """Tokyo Cabinet based task backend store.
<add>
<add> .. attribute:: tyrant_host
<add>
<add> The hostname to the Tokyo Tyrant server.
<add>
<add> .. attribute:: tyrant_port
<add>
<add> The port to the Tokyo Tyrant server.
<add>
<add> """
<ide> tyrant_host = None
<ide> tyrant_port = None
<ide>
<del> def __init__(self, *args, **kwargs):
<add> def __init__(self, tyrant_host=None, tyrant_port=None):
<ide> self.tyrant_host = kwargs.get("tyrant_host",
<ide> getattr(settings, "TT_HOST", self.tyrant_host))
<ide> self.tyrant_port = kwargs.get("tyrant_port",
<ide> def __init__(self, *args, **kwargs):
<ide> self._cache = {}
<ide>
<ide> def get_server(self):
<add> """Get :class:`pytyrant.PyTyrant`` instance with the current
<add> server configuration."""
<ide> return pytyrant.PyTyrant.open(self.tyrant_host, self.tyrant_port)
<ide>
<ide> def _cache_key(self, task_id): | 1 |
Javascript | Javascript | preserve prototype chain when copying objects | b59b04f98a0b59eead53f6a53391ce1bbcbe9b57 | <ide><path>src/Angular.js
<ide> function copy(source, destination, stackSource, stackDest) {
<ide> } else if (isRegExp(source)) {
<ide> destination = new RegExp(source.source);
<ide> } else if (isObject(source)) {
<del> destination = copy(source, {}, stackSource, stackDest);
<add> var emptyObject = Object.create(Object.getPrototypeOf(source));
<add> destination = copy(source, emptyObject, stackSource, stackDest);
<ide> }
<ide> }
<ide> } else {
<ide> function copy(source, destination, stackSource, stackDest) {
<ide> delete destination[key];
<ide> });
<ide> for ( var key in source) {
<del> result = copy(source[key], null, stackSource, stackDest);
<del> if (isObject(source[key])) {
<del> stackSource.push(source[key]);
<del> stackDest.push(result);
<add> if(source.hasOwnProperty(key)) {
<add> result = copy(source[key], null, stackSource, stackDest);
<add> if (isObject(source[key])) {
<add> stackSource.push(source[key]);
<add> stackDest.push(result);
<add> }
<add> destination[key] = result;
<ide> }
<del> destination[key] = result;
<ide> }
<ide> setHashKey(destination,h);
<ide> }
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide> expect(copy([], arr)).toBe(arr);
<ide> });
<ide>
<add> it("should preserve prototype chaining", function() {
<add> var GrandParentProto = {};
<add> var ParentProto = Object.create(GrandParentProto);
<add> var obj = Object.create(ParentProto);
<add> expect(ParentProto.isPrototypeOf(copy(obj))).toBe(true);
<add> expect(GrandParentProto.isPrototypeOf(copy(obj))).toBe(true);
<add> var Foo = function() {};
<add> expect(copy(new Foo()) instanceof Foo).toBe(true);
<add> });
<add>
<ide> it("should copy Date", function() {
<ide> var date = new Date(123);
<ide> expect(copy(date) instanceof Date).toBeTruthy(); | 2 |
Java | Java | allow binary messages in stompsubprotocolhandler | 4a29e164a8ca222fd8b0d2043e1d44494e84544e | <ide><path>spring-websocket/src/main/java/org/springframework/web/socket/messaging/StompSubProtocolHandler.java
<ide> import org.springframework.messaging.support.MessageHeaderAccessor;
<ide> import org.springframework.messaging.support.MessageHeaderInitializer;
<ide> import org.springframework.util.Assert;
<add>import org.springframework.web.socket.BinaryMessage;
<ide> import org.springframework.web.socket.CloseStatus;
<ide> import org.springframework.web.socket.TextMessage;
<ide> import org.springframework.web.socket.WebSocketMessage;
<ide> public void handleMessageFromClient(WebSocketSession session,
<ide>
<ide> List<Message<byte[]>> messages;
<ide> try {
<del> Assert.isInstanceOf(TextMessage.class, webSocketMessage);
<del> TextMessage textMessage = (TextMessage) webSocketMessage;
<del> ByteBuffer byteBuffer = ByteBuffer.wrap(textMessage.asBytes());
<add> ByteBuffer byteBuffer;
<add> if (webSocketMessage instanceof TextMessage) {
<add> byteBuffer = ByteBuffer.wrap(((TextMessage) webSocketMessage).asBytes());
<add> }
<add> else if (webSocketMessage instanceof BinaryMessage) {
<add> byteBuffer = ((BinaryMessage) webSocketMessage).getPayload();
<add> }
<add> else {
<add> throw new IllegalArgumentException("Unexpected WebSocket message type: " + webSocketMessage);
<add> }
<ide>
<ide> BufferingStompDecoder decoder = this.decoders.get(session.getId());
<ide> if (decoder == null) { | 1 |
PHP | PHP | fix some docblocks | 53ee4fa0dbe028fe91d1ec93d1196f2cb635b6e1 | <ide><path>src/Illuminate/Routing/UrlGenerator.php
<ide> public function previous()
<ide> *
<ide> * @param string $path
<ide> * @param mixed $extra
<del> * @param bool $secure
<add> * @param bool|null $secure
<ide> * @return string
<ide> */
<ide> public function to($path, $extra = array(), $secure = null)
<ide> public function secure($path, $parameters = array())
<ide> * Generate a URL to an application asset.
<ide> *
<ide> * @param string $path
<del> * @param bool $secure
<add> * @param bool|null $secure
<ide> * @return string
<ide> */
<ide> public function asset($path, $secure = null)
<ide> public function secureAsset($path)
<ide> /**
<ide> * Get the scheme for a raw URL.
<ide> *
<del> * @param bool $secure
<add> * @param bool|null $secure
<ide> * @return string
<ide> */
<ide> protected function getScheme($secure) | 1 |
PHP | PHP | add test to prove | 7df6477526d15861cfa23e085f6ffb19cfa79cc2 | <ide><path>lib/Cake/Test/Case/View/Helper/FormHelperTest.php
<ide> public function testCreateCustomRoute() {
<ide> */
<ide> public function testCreateWithInputDefaults() {
<ide> $this->Form->create('User', array(
<del> 'inputDefaults' => array('div' => false, 'label' => false)
<add> 'inputDefaults' => array(
<add> 'div' => false,
<add> 'label' => false,
<add> 'error' => array('attributes' => array('wrap' => 'small', 'class' => 'error')),
<add> 'format' => array('before', 'label', 'between', 'input', 'after', 'error')
<add> )
<ide> ));
<ide> $result = $this->Form->input('username');
<ide> $expected = array(
<ide> public function testCreateWithInputDefaults() {
<ide> '/div'
<ide> );
<ide> $this->assertTags($result, $expected);
<add>
<add> $result = $this->Form->input('username', array('label' => 'Username', 'format' => array('input', 'label')));
<add> $expected = array(
<add> 'input' => array('type' => 'text', 'name' => 'data[User][username]', 'id' => 'UserUsername'),
<add> 'label' => array('for' => 'UserUsername'), 'Username', '/label',
<add> );
<add> $this->assertTags($result, $expected);
<ide> }
<ide>
<ide> /** | 1 |
Javascript | Javascript | increase browserstack timeout to 10min | fd4b99936e6ef14e9ff04e10a95410d31f063d71 | <ide><path>karma-shared.conf.js
<ide> module.exports = function(config, specificOptions) {
<ide> startTunnel: false,
<ide> project: 'AngularJS',
<ide> name: specificOptions.testName,
<del> build: process.env.TRAVIS_BUILD_NUMBER
<add> build: process.env.TRAVIS_BUILD_NUMBER,
<add> timeout: 600 // 10min
<ide> },
<ide>
<ide> // For more browsers on Sauce Labs see: | 1 |
Java | Java | remove view managers from @reactmodulelist | c91a2b36d7eea0712fd1b70dc0844ebc1f88905a | <ide><path>ReactAndroid/src/main/java/com/facebook/react/module/annotations/ReactModuleList.java
<ide> * @return List of Native modules in the package.
<ide> */
<ide> Class<? extends NativeModule>[] nativeModules();
<del>
<del> /**
<del> * The View Managers in this list should be annotated with {@link ReactModule}.
<del> * @return List of view manager in the package.
<del> */
<del> Class<? extends NativeModule>[] viewManagers() default {};
<ide> } | 1 |
Javascript | Javascript | set directive param name to directive name | e0cc84ad7b7cdeb22cc56a75ab0775b90791da06 | <ide><path>src/directive/ngBind.js
<ide> * `<span ng-bind="expression"></span>` when the template is compiled.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate.
<add> * @param {expression} ng-bind {@link guide/dev_guide.expressions Expression} to evaluate.
<ide> *
<ide> * @example
<ide> * Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<ide> var ngBindDirective = ngDirective(function(scope, element, attr) {
<ide> * See {@link angular.module.ng.$sanitize $sanitize} docs for examples.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate.
<add> * @param {expression} ng-bind-html-unsafe {@link guide/dev_guide.expressions Expression} to evaluate.
<ide> */
<ide> var ngBindHtmlUnsafeDirective = ngDirective(function(scope, element, attr) {
<ide> element.addClass('ng-binding').data('$binding', attr.ngBindHtmlUnsafe);
<ide> var ngBindHtmlUnsafeDirective = ngDirective(function(scope, element, attr) {
<ide> * See {@link angular.module.ng.$sanitize $sanitize} docs for examples.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate.
<add> * @param {expression} ng-bind-html {@link guide/dev_guide.expressions Expression} to evaluate.
<ide> */
<ide> var ngBindHtmlDirective = ['$sanitize', function($sanitize) {
<ide> return function(scope, element, attr) {
<ide> var ngBindHtmlDirective = ['$sanitize', function($sanitize) {
<ide> * can not have SPAN elements such as TITLE, or OPTION to name a few.)
<ide> *
<ide> * @element ANY
<del> * @param {string} template of form
<add> * @param {string} ng-bind-template template of form
<ide> * <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
<ide> *
<ide> * @example
<ide> var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
<ide> *
<ide> *
<ide> * @element ANY
<del> * @param {string} attribute_json one or more JSON key-value pairs representing
<add> * @param {string} ng-bind-attr one or more JSON key-value pairs representing
<ide> * the attributes to replace with expressions. Each key matches an attribute
<ide> * which needs to be replaced. Each value is a text template of
<ide> * the attribute with the embedded
<ide><path>src/directive/ngClass.js
<ide> function classDirective(name, selector) {
<ide> * new classes are added.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
<add> * @param {expression} ng-class {@link guide/dev_guide.expressions Expression} to eval. The result
<ide> * of the evaluation can be a string representing space delimited class
<ide> * names, an array, or a map of class names to boolean values.
<ide> *
<ide> var ngClassDirective = classDirective('', true);
<ide> * {@link angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat}.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
<add> * @param {expression} ng-class-odd {@link guide/dev_guide.expressions Expression} to eval. The result
<ide> * of the evaluation can be a string representing space delimited class names or an array.
<ide> *
<ide> * @example
<ide> var ngClassOddDirective = classDirective('Odd', 0);
<ide> *
<ide> * @description
<ide> * The `ng-class-odd` and `ng-class-even` works exactly as
<del> * {@link angular.module.ng.$compileProvider.directive.ng-class ng-class}, except it works in conjunction with `ng-repeat` and
<del> * takes affect only on odd (even) rows.
<add> * {@link angular.module.ng.$compileProvider.directive.ng-class ng-class}, except it works in
<add> * conjunction with `ng-repeat` and takes affect only on odd (even) rows.
<ide> *
<ide> * This directive can be applied only within a scope of an
<ide> * {@link angular.module.ng.$compileProvider.directive.ng-repeat ng-repeat}.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval. The result
<del> * of the evaluation can be a string representing space delimited class names or an array.
<add> * @param {expression} ng-class-even {@link guide/dev_guide.expressions Expression} to eval. The
<add> * result of the evaluation can be a string representing space delimited class names or an array.
<ide> *
<ide> * @example
<ide> <doc:example>
<ide><path>src/directive/ngController.js
<ide> *
<ide> * @element ANY
<ide> * @scope
<del> * @param {expression} expression Name of a globally accessible constructor function or an
<add> * @param {expression} ng-controller Name of a globally accessible constructor function or an
<ide> * {@link guide/dev_guide.expressions expression} that on the current scope evaluates to a
<ide> * constructor function.
<ide> *
<ide><path>src/directive/ngEventDirs.js
<ide> * element is clicked.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-click {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * click. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * The ng-dblclick allows you to specify custom behavior on dblclick event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-dblclick {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * dblclick. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * The ng-mousedown allows you to specify custom behavior on mousedown event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mousedown {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mousedown. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * Specify custom behavior on mouseup event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mouseup {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mouseup. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * Specify custom behavior on mouseover event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mouseover {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mouseover. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * Specify custom behavior on mouseenter event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mouseenter {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mouseenter. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * Specify custom behavior on mouseleave event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mouseleave {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mouseleave. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * Specify custom behavior on mousemove event.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to evaluate upon
<add> * @param {expression} ng-mousemove {@link guide/dev_guide.expressions Expression} to evaluate upon
<ide> * mousemove. (Event object is available as `$event`)
<ide> *
<ide> * @example
<ide> forEach(
<ide> * server and reloading the current page).
<ide> *
<ide> * @element form
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
<add> * @param {expression} ng-submit {@link guide/dev_guide.expressions Expression} to eval.
<ide> *
<ide> * @example
<ide> <doc:example>
<ide><path>src/directive/ngInit.js
<ide> * before the template enters execution mode during bootstrap.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} to eval.
<add> * @param {expression} ng-init {@link guide/dev_guide.expressions Expression} to eval.
<ide> *
<ide> * @example
<ide> <doc:example>
<ide><path>src/directive/ngRepeat.js
<ide> * @element ANY
<ide> * @scope
<ide> * @priority 1000
<del> * @param {string} repeat_expression The expression indicating how to enumerate a collection. Two
<add> * @param {repeat_expression} ng-repeat The expression indicating how to enumerate a collection. Two
<ide> * formats are currently supported:
<ide> *
<ide> * * `variable in expression` – where variable is the user defined loop variable and `expression`
<ide><path>src/directive/ngShowHide.js
<ide> * conditionally.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression If the {@link guide/dev_guide.expressions expression} is truthy
<add> * @param {expression} ng-show If the {@link guide/dev_guide.expressions expression} is truthy
<ide> * then the element is shown or hidden respectively.
<ide> *
<ide> * @example
<ide> var ngShowDirective = ngDirective(function(scope, element, attr){
<ide> * of the HTML conditionally.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression If the {@link guide/dev_guide.expressions expression} truthy then
<add> * @param {expression} ng-hide If the {@link guide/dev_guide.expressions expression} truthy then
<ide> * the element is shown or hidden respectively.
<ide> *
<ide> * @example
<ide><path>src/directive/ngStyle.js
<ide> * The ng-style allows you to set CSS style on an HTML element conditionally.
<ide> *
<ide> * @element ANY
<del> * @param {expression} expression {@link guide/dev_guide.expressions Expression} which evals to an
<add> * @param {expression} ng-style {@link guide/dev_guide.expressions Expression} which evals to an
<ide> * object whose keys are CSS style names and values are corresponding values for those CSS
<ide> * keys.
<ide> * | 8 |
Javascript | Javascript | fix linting errors (using new stricter settings) | a5d7e0ff7effbe9d26a38d94c8453ddf8dfe24ff | <ide><path>bin/run-tests.js
<ide> #!/usr/bin/env node
<del>
<add>/* globals QUnit */
<ide> /* eslint-disable no-console */
<ide>
<ide> var execa = require('execa');
<ide><path>packages/ember-environment/lib/index.js
<del>/* globals module */
<ide> import global from './global';
<ide> import { defaultFalse, defaultTrue, normalizeExtendPrototypes } from './utils';
<ide> /**
<ide><path>packages/ember-metal/lib/map.js
<ide> class Map {
<ide> let guid = guidFor(key);
<ide>
<ide> // ensure we don't store -0
<del> let k = key === -0 ? 0 : key;
<add> let k = key === -0 ? 0 : key; // eslint-disable-line no-compare-neg-zero
<ide>
<ide> keys.add(k, guid);
<ide>
<ide><path>packages/ember-testing/lib/adapters/qunit.js
<add>/* globals QUnit */
<add>
<ide> import { inspect } from 'ember-utils';
<ide> import Adapter from './adapter';
<ide> /**
<ide><path>packages/ember/lib/index.js
<ide> runLoadHooks('Ember');
<ide> */
<ide> export default Ember;
<ide>
<del>/* globals module */
<ide> if (IS_NODE) {
<ide> module.exports = Ember;
<ide> } else {
<ide><path>packages/node-module/lib/node-module.js
<del>/*global enifed */
<add>/*global enifed, module */
<ide> enifed('node-module', ['exports'], function(_exports) {
<ide> var IS_NODE = typeof module === 'object' && typeof module.require === 'function';
<ide> if (IS_NODE) {
<ide> enifed('node-module', ['exports'], function(_exports) {
<ide> _exports.module = null;
<ide> _exports.IS_NODE = IS_NODE;
<ide> }
<del>});
<ide>\ No newline at end of file
<add>});
<ide><path>rollup.config.js
<del>import * as fs from 'fs';
<del>import * as path from 'path';
<add>'use strict';
<ide>
<del>export default {
<add>const fs = require('fs');
<add>const path = require('path');
<add>
<add>module.exports = {
<ide> input: 'dist/es/ember/index.js',
<ide> plugins: [emberPackage()],
<ide> output: { | 7 |
Javascript | Javascript | add documentation for onmomentumscrollend | b8118d1b79f0bac567fc747b95a7dbd03033db7d | <ide><path>Libraries/Components/ScrollView/ScrollView.js
<ide> const ScrollView = createReactClass({
<ide> * @platform ios
<ide> */
<ide> minimumZoomScale: PropTypes.number,
<add> /**
<add> * Called when the momentum scroll ends (scroll which occurs as the ScrollView glides to a stop).
<add> */
<add> onMomentumScrollEnd: PropTypes.func,
<ide> /**
<ide> * Fires at most once per frame during scrolling. The frequency of the
<ide> * events can be controlled using the `scrollEventThrottle` prop. | 1 |
Text | Text | add spacy contributor agreement | b639b4c6b4027b5cedeb3d6035bce709a20eb5d1 | <ide><path>.github/contributors/MathiasDesch.md
<add># spaCy contributor agreement
<add>
<add>This spaCy Contributor Agreement (**"SCA"**) is based on the
<add>[Oracle Contributor Agreement](http://www.oracle.com/technetwork/oca-405177.pdf).
<add>The SCA applies to any contribution that you make to any product or project
<add>managed by us (the **"project"**), and sets out the intellectual property rights
<add>you grant to us in the contributed materials. The term **"us"** shall mean
<add>[ExplosionAI UG (haftungsbeschränkt)](https://explosion.ai/legal). The term
<add>**"you"** shall mean the person or entity identified below.
<add>
<add>If you agree to be bound by these terms, fill in the information requested
<add>below and include the filled-in version with your first pull request, under the
<add>folder [`.github/contributors/`](/.github/contributors/). The name of the file
<add>should be your GitHub username, with the extension `.md`. For example, the user
<add>example_user would create the file `.github/contributors/example_user.md`.
<add>
<add>Read this agreement carefully before signing. These terms and conditions
<add>constitute a binding legal agreement.
<add>
<add>## Contributor Agreement
<add>
<add>1. The term "contribution" or "contributed materials" means any source code,
<add>object code, patch, tool, sample, graphic, specification, manual,
<add>documentation, or any other material posted or submitted by you to the project.
<add>
<add>2. With respect to any worldwide copyrights, or copyright applications and
<add>registrations, in your contribution:
<add>
<add> * you hereby assign to us joint ownership, and to the extent that such
<add> assignment is or becomes invalid, ineffective or unenforceable, you hereby
<add> grant to us a perpetual, irrevocable, non-exclusive, worldwide, no-charge,
<add> royalty-free, unrestricted license to exercise all rights under those
<add> copyrights. This includes, at our option, the right to sublicense these same
<add> rights to third parties through multiple levels of sublicensees or other
<add> licensing arrangements;
<add>
<add> * you agree that each of us can do all things in relation to your
<add> contribution as if each of us were the sole owners, and if one of us makes
<add> a derivative work of your contribution, the one who makes the derivative
<add> work (or has it made will be the sole owner of that derivative work;
<add>
<add> * you agree that you will not assert any moral rights in your contribution
<add> against us, our licensees or transferees;
<add>
<add> * you agree that we may register a copyright in your contribution and
<add> exercise all ownership rights associated with it; and
<add>
<add> * you agree that neither of us has any duty to consult with, obtain the
<add> consent of, pay or render an accounting to the other for any use or
<add> distribution of your contribution.
<add>
<add>3. With respect to any patents you own, or that you can license without payment
<add>to any third party, you hereby grant to us a perpetual, irrevocable,
<add>non-exclusive, worldwide, no-charge, royalty-free license to:
<add>
<add> * make, have made, use, sell, offer to sell, import, and otherwise transfer
<add> your contribution in whole or in part, alone or in combination with or
<add> included in any product, work or materials arising out of the project to
<add> which your contribution was submitted, and
<add>
<add> * at our option, to sublicense these same rights to third parties through
<add> multiple levels of sublicensees or other licensing arrangements.
<add>
<add>4. Except as set out above, you keep all right, title, and interest in your
<add>contribution. The rights that you grant to us under these terms are effective
<add>on the date you first submitted a contribution to us, even if your submission
<add>took place before the date you sign these terms.
<add>
<add>5. You covenant, represent, warrant and agree that:
<add>
<add> * Each contribution that you submit is and shall be an original work of
<add> authorship and you can legally grant the rights set out in this SCA;
<add>
<add> * to the best of your knowledge, each contribution will not violate any
<add> third party's copyrights, trademarks, patents, or other intellectual
<add> property rights; and
<add>
<add> * each contribution shall be in compliance with U.S. export control laws and
<add> other applicable export and import laws. You agree to notify us if you
<add> become aware of any circumstance which would make any of the foregoing
<add> representations inaccurate in any respect. We may publicly disclose your
<add> participation in the project, including the fact that you have signed the SCA.
<add>
<add>6. This SCA is governed by the laws of the State of California and applicable
<add>U.S. Federal law. Any choice of law rules will not apply.
<add>
<add>7. Please place an “x” on one of the applicable statement below. Please do NOT
<add>mark both statements:
<add>
<add> * [x] I am signing on behalf of myself as an individual and no other person
<add> or entity, including my employer, has or will have rights with respect to my
<add> contributions.
<add>
<add> * [ ] I am signing on behalf of my employer or a legal entity and I have the
<add> actual authority to contractually bind that entity.
<add>
<add>## Contributor Details
<add>
<add>| Field | Entry |
<add>|------------------------------- | -------------------- |
<add>| Name | Mathias Deschamps |
<add>| Company name (if applicable) | |
<add>| Title or role (if applicable) | |
<add>| Date | 9 November 2017 |
<add>| GitHub username | MathiasDesch |
<add>| Website (optional) | | | 1 |
Javascript | Javascript | move enumerable mixin methods into array mixins | 1a29eb96a49e642ad8a7b8d07a96ffc0f3f2a6a4 | <ide><path>packages/ember-runtime/lib/mixins/array.js
<ide> @module @ember/array
<ide> */
<ide>
<del>// ..........................................................
<del>// HELPERS
<del>//
<ide> import { symbol, toString } from 'ember-utils';
<del>import Ember, { // ES6TODO: Ember.A
<add>import {
<ide> get,
<add> set,
<ide> computed,
<ide> isNone,
<add> aliasMethod,
<ide> Mixin,
<ide> propertyWillChange,
<ide> propertyDidChange,
<ide> import Ember, { // ES6TODO: Ember.A
<ide> } from 'ember-metal';
<ide> import { assert } from 'ember-debug';
<ide> import Enumerable from './enumerable';
<add>import compare from '../compare';
<add>import require from 'require';
<add>
<add>
<add>// Required to break a module cycle
<add>let _A;
<add>function A() {
<add> if (_A === undefined) {
<add> _A = require('ember-runtime/system/native_array').A;
<add> }
<add> return _A();
<add>}
<ide>
<ide> function arrayObserversHelper(obj, target, opts, operation, notify) {
<ide> let willChange = (opts && opts.willChange) || 'arrayWillChange';
<ide> export function isEmberArray(obj) {
<ide> return obj && obj[EMBER_ARRAY];
<ide> }
<ide>
<add>const contexts = [];
<add>
<add>function popCtx() {
<add> return contexts.length === 0 ? {} : contexts.pop();
<add>}
<add>
<add>function pushCtx(ctx) {
<add> contexts.push(ctx);
<add> return null;
<add>}
<add>
<add>function iter(key, value) {
<add> let valueProvided = arguments.length === 2;
<add>
<add> return valueProvided ?
<add> (item)=> value === get(item, key) :
<add> (item)=> !!get(item, key);
<add>}
<add>
<ide> // ..........................................................
<ide> // ARRAY
<ide> //
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> return indexes.map(idx => objectAt(this, idx));
<ide> },
<ide>
<del> // overrides Enumerable version
<add> /**
<add> @method nextObject
<add> @param {Number} index the current index of the iteration
<add> @param {Object} previousObject the value returned by the last call to
<add> `nextObject`.
<add> @param {Object} context a context object you can use to maintain state.
<add> @return {Object} the next object in the iteration or undefined
<add> @private
<add> */
<ide> nextObject(idx) {
<ide> return objectAt(this, idx);
<ide> },
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> }
<ide> }),
<ide>
<add> /**
<add> The first object in the array, or `undefined` if the array is empty.
<add>
<add> @property firstObject
<add> @return {Object | undefined} The first object in the array
<add> @public
<add> */
<ide> firstObject: computed(function() {
<ide> return objectAt(this, 0);
<ide> }).readOnly(),
<ide>
<add> /**
<add> The last object in the array, or `undefined` if the array is empty.
<add>
<add> @property lastObject
<add> @return {Object | undefined} The last object in the array
<add> @public
<add> */
<ide> lastObject: computed(function() {
<ide> return objectAt(this, get(this, 'length') - 1);
<ide> }).readOnly(),
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> @public
<ide> */
<ide> slice(beginIndex, endIndex) {
<del> let ret = Ember.A();
<add> let ret = A();
<ide> let length = get(this, 'length');
<ide>
<ide> if (isNone(beginIndex)) {
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> return arrayContentDidChange(this, startIdx, removeAmt, addAmt);
<ide> },
<ide>
<add> /**
<add> Invoke this method just before the contents of your enumerable will
<add> change. You can either omit the parameters completely or pass the objects
<add> to be removed or added if available or just a count.
<add>
<add> @method enumerableContentWillChange
<add> @param {Enumerable|Number} removing An enumerable of the objects to
<add> be removed or the number of items to be removed.
<add> @param {Enumerable|Number} adding An enumerable of the objects to be
<add> added or the number of items to be added.
<add> @chainable
<add> @private
<add> */
<add> enumerableContentWillChange(removing, adding) {
<add> let removeCnt, addCnt, hasDelta;
<add>
<add> if ('number' === typeof removing) {
<add> removeCnt = removing;
<add> } else if (removing) {
<add> removeCnt = get(removing, 'length');
<add> } else {
<add> removeCnt = removing = -1;
<add> }
<add>
<add> if ('number' === typeof adding) {
<add> addCnt = adding;
<add> } else if (adding) {
<add> addCnt = get(adding, 'length');
<add> } else {
<add> addCnt = adding = -1;
<add> }
<add>
<add> hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
<add>
<add> if (removing === -1) {
<add> removing = null;
<add> }
<add>
<add> if (adding === -1) {
<add> adding = null;
<add> }
<add>
<add> propertyWillChange(this, '[]');
<add>
<add> if (hasDelta) {
<add> propertyWillChange(this, 'length');
<add> }
<add>
<add> return this;
<add> },
<add>
<add> /**
<add> Invoke this method when the contents of your enumerable has changed.
<add> This will notify any observers watching for content changes. If you are
<add> implementing an ordered enumerable (such as an array), also pass the
<add> start and end values where the content changed so that it can be used to
<add> notify range observers.
<add>
<add> @method enumerableContentDidChange
<add> @param {Enumerable|Number} removing An enumerable of the objects to
<add> be removed or the number of items to be removed.
<add> @param {Enumerable|Number} adding An enumerable of the objects to
<add> be added or the number of items to be added.
<add> @chainable
<add> @private
<add> */
<add> enumerableContentDidChange(removing, adding) {
<add> let removeCnt, addCnt, hasDelta;
<add>
<add> if ('number' === typeof removing) {
<add> removeCnt = removing;
<add> } else if (removing) {
<add> removeCnt = get(removing, 'length');
<add> } else {
<add> removeCnt = removing = -1;
<add> }
<add>
<add> if ('number' === typeof adding) {
<add> addCnt = adding;
<add> } else if (adding) {
<add> addCnt = get(adding, 'length');
<add> } else {
<add> addCnt = adding = -1;
<add> }
<add>
<add> hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
<add>
<add> if (removing === -1) {
<add> removing = null;
<add> }
<add>
<add> if (adding === -1) {
<add> adding = null;
<add> }
<add>
<add> if (hasDelta) {
<add> propertyDidChange(this, 'length');
<add> }
<add>
<add> propertyDidChange(this, '[]');
<add>
<add> return this;
<add> },
<add>
<add>
<add> /**
<add> Iterates through the enumerable, calling the passed function on each
<add> item. This method corresponds to the `forEach()` method defined in
<add> JavaScript 1.6.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> @method forEach
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Object} receiver
<add> @public
<add> */
<add> forEach(callback, target) {
<add> assert('Enumerable#forEach expects a function as first argument.', typeof callback === 'function');
<add>
<add> let context = popCtx();
<add> let len = get(this, 'length');
<add> let last = null;
<add>
<add> if (target === undefined) {
<add> target = null;
<add> }
<add>
<add> for (let idx = 0; idx < len; idx++) {
<add> let next = this.nextObject(idx, last, context);
<add> callback.call(target, next, idx, this);
<add> last = next;
<add> }
<add>
<add> last = null;
<add> context = pushCtx(context);
<add>
<add> return this;
<add> },
<add>
<add> /**
<add> Alias for `mapBy`
<add>
<add> @method getEach
<add> @param {String} key name of the property
<add> @return {Array} The mapped array.
<add> @public
<add> */
<add> getEach: aliasMethod('mapBy'),
<add>
<add> /**
<add> Sets the value on the named property for each member. This is more
<add> ergonomic than using other methods defined on this helper. If the object
<add> implements Observable, the value will be changed to `set(),` otherwise
<add> it will be set directly. `null` objects are skipped.
<add>
<add> @method setEach
<add> @param {String} key The key to set
<add> @param {Object} value The object to set
<add> @return {Object} receiver
<add> @public
<add> */
<add> setEach(key, value) {
<add> return this.forEach(item => set(item, key, value));
<add> },
<add>
<add> /**
<add> Maps all of the items in the enumeration to another value, returning
<add> a new array. This method corresponds to `map()` defined in JavaScript 1.6.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> It should return the mapped value.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> @method map
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Array} The mapped array.
<add> @public
<add> */
<add> map(callback, target) {
<add> assert('Enumerable#map expects a function as first argument.', typeof callback === 'function');
<add>
<add> let ret = A();
<add>
<add> this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Similar to map, this specialized function returns the value of the named
<add> property on all items in the enumeration.
<add>
<add> @method mapBy
<add> @param {String} key name of the property
<add> @return {Array} The mapped array.
<add> @public
<add> */
<add> mapBy(key) {
<add> return this.map(next => get(next, key));
<add> },
<add>
<add> /**
<add> Returns an array with all of the items in the enumeration that the passed
<add> function returns true for. This method corresponds to `filter()` defined in
<add> JavaScript 1.6.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> It should return `true` to include the item in the results, `false`
<add> otherwise.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> @method filter
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Array} A filtered array.
<add> @public
<add> */
<add> filter(callback, target) {
<add> assert('Enumerable#filter expects a function as first argument.', typeof callback === 'function');
<add>
<add> let ret = A();
<add>
<add> this.forEach((x, idx, i) => {
<add> if (callback.call(target, x, idx, i)) {
<add> ret.push(x);
<add> }
<add> });
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Returns an array with all of the items in the enumeration where the passed
<add> function returns false. This method is the inverse of filter().
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - *item* is the current item in the iteration.
<add> - *index* is the current index in the iteration
<add> - *enumerable* is the enumerable object itself.
<add>
<add> It should return a falsey value to include the item in the results.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as "this" on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> @method reject
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Array} A rejected array.
<add> @public
<add> */
<add> reject(callback, target) {
<add> assert('Enumerable#reject expects a function as first argument.', typeof callback === 'function');
<add>
<add> return this.filter(function() {
<add> return !(callback.apply(target, arguments));
<add> });
<add> },
<add>
<add> /**
<add> Returns an array with just the items with the matched property. You
<add> can pass an optional second argument with the target value. Otherwise
<add> this will match any property that evaluates to `true`.
<add>
<add> @method filterBy
<add> @param {String} key the property to test
<add> @param {*} [value] optional value to test against.
<add> @return {Array} filtered array
<add> @public
<add> */
<add> filterBy(key, value) { // eslint-disable-line no-unused-vars
<add> return this.filter(iter.apply(this, arguments));
<add> },
<add>
<add> /**
<add> Returns an array with the items that do not have truthy values for
<add> key. You can pass an optional second argument with the target value. Otherwise
<add> this will match any property that evaluates to false.
<add>
<add> @method rejectBy
<add> @param {String} key the property to test
<add> @param {String} [value] optional value to test against.
<add> @return {Array} rejected array
<add> @public
<add> */
<add> rejectBy(key, value) {
<add> let exactValue = item => get(item, key) === value;
<add> let hasValue = item => !!get(item, key);
<add> let use = (arguments.length === 2 ? exactValue : hasValue);
<add>
<add> return this.reject(use);
<add> },
<add>
<add> /**
<add> Returns the first item in the array for which the callback returns true.
<add> This method works similar to the `filter()` method defined in JavaScript 1.6
<add> except that it will stop working on the array once a match is found.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> It should return the `true` to include the item in the results, `false`
<add> otherwise.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> @method find
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Object} Found item or `undefined`.
<add> @public
<add> */
<add> find(callback, target) {
<add> assert('Enumerable#find expects a function as first argument.', typeof callback === 'function');
<add>
<add> let len = get(this, 'length');
<add>
<add> if (target === undefined) {
<add> target = null;
<add> }
<add>
<add> let context = popCtx();
<add> let found = false;
<add> let last = null;
<add> let next, ret;
<add>
<add> for (let idx = 0; idx < len && !found; idx++) {
<add> next = this.nextObject(idx, last, context);
<add>
<add> found = callback.call(target, next, idx, this);
<add> if (found) {
<add> ret = next;
<add> }
<add>
<add> last = next;
<add> }
<add>
<add> next = last = null;
<add> context = pushCtx(context);
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Returns the first item with a property matching the passed value. You
<add> can pass an optional second argument with the target value. Otherwise
<add> this will match any property that evaluates to `true`.
<add>
<add> This method works much like the more generic `find()` method.
<add>
<add> @method findBy
<add> @param {String} key the property to test
<add> @param {String} [value] optional value to test against.
<add> @return {Object} found item or `undefined`
<add> @public
<add> */
<add> findBy(key, value) { // eslint-disable-line no-unused-vars
<add> return this.find(iter.apply(this, arguments));
<add> },
<add>
<add> /**
<add> Returns `true` if the passed function returns true for every item in the
<add> enumeration. This corresponds with the `every()` method in JavaScript 1.6.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> It should return the `true` or `false`.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> Example Usage:
<add>
<add> ```javascript
<add> if (people.every(isEngineer)) {
<add> Paychecks.addBigBonus();
<add> }
<add> ```
<add>
<add> @method every
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Boolean}
<add> @public
<add> */
<add> every(callback, target) {
<add> assert('Enumerable#every expects a function as first argument.', typeof callback === 'function');
<add>
<add> return !this.find((x, idx, i) => !callback.call(target, x, idx, i));
<add> },
<add>
<add> /**
<add> Returns `true` if the passed property resolves to the value of the second
<add> argument for all items in the enumerable. This method is often simpler/faster
<add> than using a callback.
<add>
<add> Note that like the native `Array.every`, `isEvery` will return true when called
<add> on any empty enumerable.
<add>
<add> @method isEvery
<add> @param {String} key the property to test
<add> @param {String} [value] optional value to test against. Defaults to `true`
<add> @return {Boolean}
<add> @since 1.3.0
<add> @public
<add> */
<add> isEvery(key, value) { // eslint-disable-line no-unused-vars
<add> return this.every(iter.apply(this, arguments));
<add> },
<add>
<add> /**
<add> Returns `true` if the passed function returns true for any item in the
<add> enumeration.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(item, index, enumerable);
<add> ```
<add>
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> It must return a truthy value (i.e. `true`) to include an item in the
<add> results. Any non-truthy return value will discard the item from the
<add> results.
<add>
<add> Note that in addition to a callback, you can also pass an optional target
<add> object that will be set as `this` on the context. This is a good way
<add> to give your iterator function access to the current object.
<add>
<add> Usage Example:
<add>
<add> ```javascript
<add> if (people.any(isManager)) {
<add> Paychecks.addBiggerBonus();
<add> }
<add> ```
<add>
<add> @method any
<add> @param {Function} callback The callback to execute
<add> @param {Object} [target] The target object to use
<add> @return {Boolean} `true` if the passed function returns `true` for any item
<add> @public
<add> */
<add> any(callback, target) {
<add> assert('Enumerable#any expects a function as first argument.', typeof callback === 'function');
<add>
<add> let len = get(this, 'length');
<add> let context = popCtx();
<add> let found = false;
<add> let last = null;
<add> let next;
<add>
<add> if (target === undefined) {
<add> target = null;
<add> }
<add>
<add> for (let idx = 0; idx < len && !found; idx++) {
<add> next = this.nextObject(idx, last, context);
<add> found = callback.call(target, next, idx, this);
<add> last = next;
<add> }
<add>
<add> next = last = null;
<add> context = pushCtx(context);
<add> return found;
<add> },
<add>
<add> /**
<add> Returns `true` if the passed property resolves to the value of the second
<add> argument for any item in the enumerable. This method is often simpler/faster
<add> than using a callback.
<add>
<add> @method isAny
<add> @param {String} key the property to test
<add> @param {String} [value] optional value to test against. Defaults to `true`
<add> @return {Boolean}
<add> @since 1.3.0
<add> @public
<add> */
<add> isAny(key, value) { // eslint-disable-line no-unused-vars
<add> return this.any(iter.apply(this, arguments));
<add> },
<add>
<add> /**
<add> This will combine the values of the enumerator into a single value. It
<add> is a useful way to collect a summary value from an enumeration. This
<add> corresponds to the `reduce()` method defined in JavaScript 1.8.
<add>
<add> The callback method you provide should have the following signature (all
<add> parameters are optional):
<add>
<add> ```javascript
<add> function(previousValue, item, index, enumerable);
<add> ```
<add>
<add> - `previousValue` is the value returned by the last call to the iterator.
<add> - `item` is the current item in the iteration.
<add> - `index` is the current index in the iteration.
<add> - `enumerable` is the enumerable object itself.
<add>
<add> Return the new cumulative value.
<add>
<add> In addition to the callback you can also pass an `initialValue`. An error
<add> will be raised if you do not pass an initial value and the enumerator is
<add> empty.
<add>
<add> Note that unlike the other methods, this method does not allow you to
<add> pass a target object to set as this for the callback. It's part of the
<add> spec. Sorry.
<add>
<add> @method reduce
<add> @param {Function} callback The callback to execute
<add> @param {Object} initialValue Initial value for the reduce
<add> @param {String} reducerProperty internal use only.
<add> @return {Object} The reduced value.
<add> @public
<add> */
<add> reduce(callback, initialValue, reducerProperty) {
<add> assert('Enumerable#reduce expects a function as first argument.', typeof callback === 'function');
<add>
<add> let ret = initialValue;
<add>
<add> this.forEach(function(item, i) {
<add> ret = callback(ret, item, i, this, reducerProperty);
<add> }, this);
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Invokes the named method on every object in the receiver that
<add> implements it. This method corresponds to the implementation in
<add> Prototype 1.6.
<add>
<add> @method invoke
<add> @param {String} methodName the name of the method
<add> @param {Object...} args optional arguments to pass as well.
<add> @return {Array} return values from calling invoke.
<add> @public
<add> */
<add> invoke(methodName, ...args) {
<add> let ret = A();
<add>
<add> this.forEach((x, idx) => {
<add> let method = x && x[methodName];
<add>
<add> if ('function' === typeof method) {
<add> ret[idx] = args.length ? method.apply(x, args) : x[methodName]();
<add> }
<add> }, this);
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Simply converts the enumerable into a genuine array. The order is not
<add> guaranteed. Corresponds to the method implemented by Prototype.
<add>
<add> @method toArray
<add> @return {Array} the enumerable as an array.
<add> @public
<add> */
<add> toArray() {
<add> let ret = A();
<add>
<add> this.forEach((o, idx) => ret[idx] = o);
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Returns a copy of the array with all `null` and `undefined` elements removed.
<add>
<add> ```javascript
<add> let arr = ['a', null, 'c', undefined];
<add> arr.compact(); // ['a', 'c']
<add> ```
<add>
<add> @method compact
<add> @return {Array} the array without null and undefined elements.
<add> @public
<add> */
<add> compact() {
<add> return this.filter(value => value != null);
<add> },
<add>
<ide> /**
<ide> Returns `true` if the passed object can be found in the array.
<ide> This method is a Polyfill for ES 2016 Array.includes.
<ide> const ArrayMixin = Mixin.create(Enumerable, {
<ide> return false;
<ide> },
<ide>
<add> /**
<add> Converts the enumerable into an array and sorts by the keys
<add> specified in the argument.
<add>
<add> You may provide multiple arguments to sort by multiple properties.
<add>
<add> @method sortBy
<add> @param {String} property name(s) to sort on
<add> @return {Array} The sorted array.
<add> @since 1.2.0
<add> @public
<add> */
<add> sortBy() {
<add> let sortKeys = arguments;
<add>
<add> return this.toArray().sort((a, b) => {
<add> for (let i = 0; i < sortKeys.length; i++) {
<add> let key = sortKeys[i];
<add> let propA = get(a, key);
<add> let propB = get(b, key);
<add> // return 1 or -1 else continue to the next sortKey
<add> let compareValue = compare(propA, propB);
<add>
<add> if (compareValue) {
<add> return compareValue;
<add> }
<add> }
<add> return 0;
<add> });
<add> },
<add>
<add> /**
<add> Returns a new enumerable that contains only unique values. The default
<add> implementation returns an array regardless of the receiver type.
<add>
<add> ```javascript
<add> let arr = ['a', 'a', 'b', 'b'];
<add> arr.uniq(); // ['a', 'b']
<add> ```
<add>
<add> This only works on primitive data types, e.g. Strings, Numbers, etc.
<add>
<add> @method uniq
<add> @return {Enumerable}
<add> @public
<add> */
<add> uniq() {
<add> let ret = A();
<add>
<add> let seen = new Set();
<add> this.forEach(item => {
<add> if (!seen.has(item)) {
<add> seen.add(item);
<add> ret.push(item);
<add> }
<add> });
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Returns a new enumerable that contains only items containing a unique property value.
<add> The default implementation returns an array regardless of the receiver type.
<add>
<add> ```javascript
<add> let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
<add> arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
<add> ```
<add>
<add> @method uniqBy
<add> @return {Enumerable}
<add> @public
<add> */
<add>
<add> uniqBy(key) {
<add> let ret = A();
<add> let seen = new Set();
<add>
<add> this.forEach((item) => {
<add> let val = get(item, key);
<add> if (!seen.has(val)) {
<add> seen.add(val);
<add> ret.push(item);
<add> }
<add> });
<add>
<add> return ret;
<add> },
<add>
<add> /**
<add> Returns a new enumerable that excludes the passed value. The default
<add> implementation returns an array regardless of the receiver type.
<add> If the receiver does not contain the value it returns the original enumerable.
<add>
<add> ```javascript
<add> let arr = ['a', 'b', 'a', 'c'];
<add> arr.without('a'); // ['b', 'c']
<add> ```
<add>
<add> @method without
<add> @param {Object} value
<add> @return {Enumerable}
<add> @public
<add> */
<add> without(value) {
<add> if (!this.includes(value)) {
<add> return this; // nothing to do
<add> }
<add>
<add> let ret = A();
<add>
<add> this.forEach(k => {
<add> // SameValueZero comparison (NaN !== NaN)
<add> if (!(k === value || k !== k && value !== value)) {
<add> ret[ret.length] = k;
<add> }
<add> });
<add>
<add> return ret;
<add> },
<add>
<ide> /**
<ide> Returns a special object that can be used to observe individual properties
<ide> on the array. Just get an equivalent property on this object and it will
<ide><path>packages/ember-runtime/lib/mixins/enumerable.js
<add>import { Mixin } from 'ember-metal';
<add>
<ide> /**
<del>@module @ember/enumerable
<del>@private
<add>@module ember
<ide> */
<ide>
<del>// ..........................................................
<del>// HELPERS
<del>//
<del>
<del>import {
<del> get,
<del> set,
<del> Mixin,
<del> aliasMethod,
<del> computed,
<del> propertyWillChange,
<del> propertyDidChange
<del>} from 'ember-metal';
<del>import { assert } from 'ember-debug';
<del>import compare from '../compare';
<del>import require from 'require';
<del>
<del>let _emberA;
<del>
<del>function emberA() {
<del> if (_emberA === undefined) {
<del> _emberA = require('ember-runtime/system/native_array').A;
<del> }
<del> return _emberA();
<del>}
<del>
<del>const contexts = [];
<del>
<del>function popCtx() {
<del> return contexts.length === 0 ? {} : contexts.pop();
<del>}
<del>
<del>function pushCtx(ctx) {
<del> contexts.push(ctx);
<del> return null;
<del>}
<del>
<del>function iter(key, value) {
<del> let valueProvided = arguments.length === 2;
<del>
<del> return valueProvided ?
<del> (item)=> value === get(item, key) :
<del> (item)=> !!get(item, key);
<del>}
<del>
<ide> /**
<del> This mixin defines the common interface implemented by enumerable objects
<del> in Ember. Most of these methods follow the standard Array iteration
<del> API defined up to JavaScript 1.8 (excluding language-specific features that
<del> cannot be emulated in older versions of JavaScript).
<del>
<del> This mixin is applied automatically to the Array class on page load, so you
<del> can use any of these methods on simple arrays. If Array already implements
<del> one of these methods, the mixin will not override them.
<del>
<del> ## Writing Your Own Enumerable
<del>
<del> To make your own custom class enumerable, you need two items:
<del>
<del> 1. You must have a length property. This property should change whenever
<del> the number of items in your enumerable object changes. If you use this
<del> with an `EmberObject` subclass, you should be sure to change the length
<del> property using `set().`
<del>
<del> 2. You must implement `nextObject().` See documentation.
<del>
<del> Once you have these two methods implemented, apply the `Enumerable` mixin
<del> to your class and you will be able to enumerate the contents of your object
<del> like any other collection.
<del>
<del> ## Using Ember Enumeration with Other Libraries
<del>
<del> Many other libraries provide some kind of iterator or enumeration like
<del> facility. This is often where the most common API conflicts occur.
<del> Ember's API is designed to be as friendly as possible with other
<del> libraries by implementing only methods that mostly correspond to the
<del> JavaScript 1.8 API.
<add> The methods in this mixin have been moved to MutableArray. This mixin has
<add> been intentionally preserved to avoid breaking Enumerable.detect checks
<add> until the community migrates away from them.
<ide>
<ide> @class Enumerable
<del> @since Ember 0.9
<add> @namespace Ember
<ide> @private
<ide> */
<del>const Enumerable = Mixin.create({
<del>
<del> /**
<del> __Required.__ You must implement this method to apply this mixin.
<del>
<del> Implement this method to make your class enumerable.
<del>
<del> This method will be called repeatedly during enumeration. The index value
<del> will always begin with 0 and increment monotonically. You don't have to
<del> rely on the index value to determine what object to return, but you should
<del> always check the value and start from the beginning when you see the
<del> requested index is 0.
<del>
<del> The `previousObject` is the object that was returned from the last call
<del> to `nextObject` for the current iteration. This is a useful way to
<del> manage iteration if you are tracing a linked list, for example.
<del>
<del> Finally the context parameter will always contain a hash you can use as
<del> a "scratchpad" to maintain any other state you need in order to iterate
<del> properly. The context object is reused and is not reset between
<del> iterations so make sure you setup the context with a fresh state whenever
<del> the index parameter is 0.
<del>
<del> Generally iterators will continue to call `nextObject` until the index
<del> reaches the current length-1. If you run out of data before this
<del> time for some reason, you should simply return undefined.
<del>
<del> The default implementation of this method simply looks up the index.
<del> This works great on any Array-like objects.
<del>
<del> @method nextObject
<del> @param {Number} index the current index of the iteration
<del> @param {Object} previousObject the value returned by the last call to
<del> `nextObject`.
<del> @param {Object} context a context object you can use to maintain state.
<del> @return {Object} the next object in the iteration or undefined
<del> @private
<del> */
<del> nextObject: null,
<del>
<del> /**
<del> Helper method returns the first object from a collection. This is usually
<del> used by bindings and other parts of the framework to extract a single
<del> object if the enumerable contains only one item.
<del>
<del> If you override this method, you should implement it so that it will
<del> always return the same value each time it is called. If your enumerable
<del> contains only one object, this method should always return that object.
<del> If your enumerable is empty, this method should return `undefined`.
<del>
<del> ```javascript
<del> let arr = ['a', 'b', 'c'];
<del> arr.get('firstObject'); // 'a'
<del>
<del> let arr = [];
<del> arr.get('firstObject'); // undefined
<del> ```
<del>
<del> @property firstObject
<del> @return {Object} the object or undefined
<del> @readOnly
<del> @public
<del> */
<del> firstObject: computed('[]', function() {
<del> if (get(this, 'length') === 0) {
<del> return undefined;
<del> }
<del>
<del> // handle generic enumerables
<del> let context = popCtx();
<del> let ret = this.nextObject(0, null, context);
<del>
<del> pushCtx(context);
<del>
<del> return ret;
<del> }).readOnly(),
<del>
<del> /**
<del> Helper method returns the last object from a collection. If your enumerable
<del> contains only one object, this method should always return that object.
<del> If your enumerable is empty, this method should return `undefined`.
<del>
<del> ```javascript
<del> let arr = ['a', 'b', 'c'];
<del> arr.get('lastObject'); // 'c'
<del>
<del> let arr = [];
<del> arr.get('lastObject'); // undefined
<del> ```
<del>
<del> @property lastObject
<del> @return {Object} the last object or undefined
<del> @readOnly
<del> @public
<del> */
<del> lastObject: computed('[]', function() {
<del> let len = get(this, 'length');
<del>
<del> if (len === 0) {
<del> return undefined;
<del> }
<del>
<del> let context = popCtx();
<del> let idx = 0;
<del> let last = null;
<del> let cur;
<del>
<del> do {
<del> last = cur;
<del> cur = this.nextObject(idx++, last, context);
<del> } while (cur !== undefined);
<del>
<del> pushCtx(context);
<del>
<del> return last;
<del> }).readOnly(),
<del>
<del> /**
<del> Iterates through the enumerable, calling the passed function on each
<del> item. This method corresponds to the `forEach()` method defined in
<del> JavaScript 1.6.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> @method forEach
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Object} receiver
<del> @public
<del> */
<del> forEach(callback, target) {
<del> assert('Enumerable#forEach expects a function as first argument.', typeof callback === 'function');
<del>
<del> let context = popCtx();
<del> let len = get(this, 'length');
<del> let last = null;
<del>
<del> if (target === undefined) {
<del> target = null;
<del> }
<del>
<del> for (let idx = 0; idx < len; idx++) {
<del> let next = this.nextObject(idx, last, context);
<del> callback.call(target, next, idx, this);
<del> last = next;
<del> }
<del>
<del> last = null;
<del> context = pushCtx(context);
<del>
<del> return this;
<del> },
<del>
<del> /**
<del> Alias for `mapBy`
<del>
<del> @method getEach
<del> @param {String} key name of the property
<del> @return {Array} The mapped array.
<del> @public
<del> */
<del> getEach: aliasMethod('mapBy'),
<del>
<del> /**
<del> Sets the value on the named property for each member. This is more
<del> ergonomic than using other methods defined on this helper. If the object
<del> implements Observable, the value will be changed to `set(),` otherwise
<del> it will be set directly. `null` objects are skipped.
<del>
<del> @method setEach
<del> @param {String} key The key to set
<del> @param {Object} value The object to set
<del> @return {Object} receiver
<del> @public
<del> */
<del> setEach(key, value) {
<del> return this.forEach(item => set(item, key, value));
<del> },
<del>
<del> /**
<del> Maps all of the items in the enumeration to another value, returning
<del> a new array. This method corresponds to `map()` defined in JavaScript 1.6.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> It should return the mapped value.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> @method map
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Array} The mapped array.
<del> @public
<del> */
<del> map(callback, target) {
<del> assert('Enumerable#map expects a function as first argument.', typeof callback === 'function');
<del>
<del> let ret = emberA();
<del>
<del> this.forEach((x, idx, i) => ret[idx] = callback.call(target, x, idx, i));
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Similar to map, this specialized function returns the value of the named
<del> property on all items in the enumeration.
<del>
<del> @method mapBy
<del> @param {String} key name of the property
<del> @return {Array} The mapped array.
<del> @public
<del> */
<del> mapBy(key) {
<del> return this.map(next => get(next, key));
<del> },
<del>
<del> /**
<del> Returns an array with all of the items in the enumeration that the passed
<del> function returns true for. This method corresponds to `filter()` defined in
<del> JavaScript 1.6.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> It should return `true` to include the item in the results, `false`
<del> otherwise.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> @method filter
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Array} A filtered array.
<del> @public
<del> */
<del> filter(callback, target) {
<del> assert('Enumerable#filter expects a function as first argument.', typeof callback === 'function');
<del>
<del> let ret = emberA();
<del>
<del> this.forEach((x, idx, i) => {
<del> if (callback.call(target, x, idx, i)) {
<del> ret.push(x);
<del> }
<del> });
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Returns an array with all of the items in the enumeration where the passed
<del> function returns false. This method is the inverse of filter().
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - *item* is the current item in the iteration.
<del> - *index* is the current index in the iteration
<del> - *enumerable* is the enumerable object itself.
<del>
<del> It should return a falsey value to include the item in the results.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as "this" on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> @method reject
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Array} A rejected array.
<del> @public
<del> */
<del> reject(callback, target) {
<del> assert('Enumerable#reject expects a function as first argument.', typeof callback === 'function');
<del>
<del> return this.filter(function() {
<del> return !(callback.apply(target, arguments));
<del> });
<del> },
<del>
<del> /**
<del> Returns an array with just the items with the matched property. You
<del> can pass an optional second argument with the target value. Otherwise
<del> this will match any property that evaluates to `true`.
<del>
<del> @method filterBy
<del> @param {String} key the property to test
<del> @param {*} [value] optional value to test against.
<del> @return {Array} filtered array
<del> @public
<del> */
<del> filterBy(key, value) { // eslint-disable-line no-unused-vars
<del> return this.filter(iter.apply(this, arguments));
<del> },
<del>
<del> /**
<del> Returns an array with the items that do not have truthy values for
<del> key. You can pass an optional second argument with the target value. Otherwise
<del> this will match any property that evaluates to false.
<del>
<del> @method rejectBy
<del> @param {String} key the property to test
<del> @param {String} [value] optional value to test against.
<del> @return {Array} rejected array
<del> @public
<del> */
<del> rejectBy(key, value) {
<del> let exactValue = item => get(item, key) === value;
<del> let hasValue = item => !!get(item, key);
<del> let use = (arguments.length === 2 ? exactValue : hasValue);
<del>
<del> return this.reject(use);
<del> },
<del>
<del> /**
<del> Returns the first item in the array for which the callback returns true.
<del> This method works similar to the `filter()` method defined in JavaScript 1.6
<del> except that it will stop working on the array once a match is found.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> It should return the `true` to include the item in the results, `false`
<del> otherwise.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> @method find
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Object} Found item or `undefined`.
<del> @public
<del> */
<del> find(callback, target) {
<del> assert('Enumerable#find expects a function as first argument.', typeof callback === 'function');
<del>
<del> let len = get(this, 'length');
<del>
<del> if (target === undefined) {
<del> target = null;
<del> }
<del>
<del> let context = popCtx();
<del> let found = false;
<del> let last = null;
<del> let next, ret;
<del>
<del> for (let idx = 0; idx < len && !found; idx++) {
<del> next = this.nextObject(idx, last, context);
<del>
<del> found = callback.call(target, next, idx, this);
<del> if (found) {
<del> ret = next;
<del> }
<del>
<del> last = next;
<del> }
<del>
<del> next = last = null;
<del> context = pushCtx(context);
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Returns the first item with a property matching the passed value. You
<del> can pass an optional second argument with the target value. Otherwise
<del> this will match any property that evaluates to `true`.
<del>
<del> This method works much like the more generic `find()` method.
<del>
<del> @method findBy
<del> @param {String} key the property to test
<del> @param {String} [value] optional value to test against.
<del> @return {Object} found item or `undefined`
<del> @public
<del> */
<del> findBy(key, value) { // eslint-disable-line no-unused-vars
<del> return this.find(iter.apply(this, arguments));
<del> },
<del>
<del> /**
<del> Returns `true` if the passed function returns true for every item in the
<del> enumeration. This corresponds with the `every()` method in JavaScript 1.6.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> It should return the `true` or `false`.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> Example Usage:
<del>
<del> ```javascript
<del> if (people.every(isEngineer)) {
<del> Paychecks.addBigBonus();
<del> }
<del> ```
<del>
<del> @method every
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Boolean}
<del> @public
<del> */
<del> every(callback, target) {
<del> assert('Enumerable#every expects a function as first argument.', typeof callback === 'function');
<del>
<del> return !this.find((x, idx, i) => !callback.call(target, x, idx, i));
<del> },
<del>
<del> /**
<del> Returns `true` if the passed property resolves to the value of the second
<del> argument for all items in the enumerable. This method is often simpler/faster
<del> than using a callback.
<del>
<del> Note that like the native `Array.every`, `isEvery` will return true when called
<del> on any empty enumerable.
<del>
<del> @method isEvery
<del> @param {String} key the property to test
<del> @param {String} [value] optional value to test against. Defaults to `true`
<del> @return {Boolean}
<del> @since 1.3.0
<del> @public
<del> */
<del> isEvery(key, value) { // eslint-disable-line no-unused-vars
<del> return this.every(iter.apply(this, arguments));
<del> },
<del>
<del> /**
<del> Returns `true` if the passed function returns true for any item in the
<del> enumeration.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(item, index, enumerable);
<del> ```
<del>
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> It must return a truthy value (i.e. `true`) to include an item in the
<del> results. Any non-truthy return value will discard the item from the
<del> results.
<del>
<del> Note that in addition to a callback, you can also pass an optional target
<del> object that will be set as `this` on the context. This is a good way
<del> to give your iterator function access to the current object.
<del>
<del> Usage Example:
<del>
<del> ```javascript
<del> if (people.any(isManager)) {
<del> Paychecks.addBiggerBonus();
<del> }
<del> ```
<del>
<del> @method any
<del> @param {Function} callback The callback to execute
<del> @param {Object} [target] The target object to use
<del> @return {Boolean} `true` if the passed function returns `true` for any item
<del> @public
<del> */
<del> any(callback, target) {
<del> assert('Enumerable#any expects a function as first argument.', typeof callback === 'function');
<del>
<del> let len = get(this, 'length');
<del> let context = popCtx();
<del> let found = false;
<del> let last = null;
<del> let next;
<del>
<del> if (target === undefined) {
<del> target = null;
<del> }
<del>
<del> for (let idx = 0; idx < len && !found; idx++) {
<del> next = this.nextObject(idx, last, context);
<del> found = callback.call(target, next, idx, this);
<del> last = next;
<del> }
<del>
<del> next = last = null;
<del> context = pushCtx(context);
<del> return found;
<del> },
<del>
<del> /**
<del> Returns `true` if the passed property resolves to the value of the second
<del> argument for any item in the enumerable. This method is often simpler/faster
<del> than using a callback.
<del>
<del> @method isAny
<del> @param {String} key the property to test
<del> @param {String} [value] optional value to test against. Defaults to `true`
<del> @return {Boolean}
<del> @since 1.3.0
<del> @public
<del> */
<del> isAny(key, value) { // eslint-disable-line no-unused-vars
<del> return this.any(iter.apply(this, arguments));
<del> },
<del>
<del> /**
<del> This will combine the values of the enumerator into a single value. It
<del> is a useful way to collect a summary value from an enumeration. This
<del> corresponds to the `reduce()` method defined in JavaScript 1.8.
<del>
<del> The callback method you provide should have the following signature (all
<del> parameters are optional):
<del>
<del> ```javascript
<del> function(previousValue, item, index, enumerable);
<del> ```
<del>
<del> - `previousValue` is the value returned by the last call to the iterator.
<del> - `item` is the current item in the iteration.
<del> - `index` is the current index in the iteration.
<del> - `enumerable` is the enumerable object itself.
<del>
<del> Return the new cumulative value.
<del>
<del> In addition to the callback you can also pass an `initialValue`. An error
<del> will be raised if you do not pass an initial value and the enumerator is
<del> empty.
<del>
<del> Note that unlike the other methods, this method does not allow you to
<del> pass a target object to set as this for the callback. It's part of the
<del> spec. Sorry.
<del>
<del> @method reduce
<del> @param {Function} callback The callback to execute
<del> @param {Object} initialValue Initial value for the reduce
<del> @param {String} reducerProperty internal use only.
<del> @return {Object} The reduced value.
<del> @public
<del> */
<del> reduce(callback, initialValue, reducerProperty) {
<del> assert('Enumerable#reduce expects a function as first argument.', typeof callback === 'function');
<del>
<del> let ret = initialValue;
<del>
<del> this.forEach(function(item, i) {
<del> ret = callback(ret, item, i, this, reducerProperty);
<del> }, this);
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Invokes the named method on every object in the receiver that
<del> implements it. This method corresponds to the implementation in
<del> Prototype 1.6.
<del>
<del> @method invoke
<del> @param {String} methodName the name of the method
<del> @param {Object...} args optional arguments to pass as well.
<del> @return {Array} return values from calling invoke.
<del> @public
<del> */
<del> invoke(methodName, ...args) {
<del> let ret = emberA();
<del>
<del> this.forEach((x, idx) => {
<del> let method = x && x[methodName];
<del>
<del> if ('function' === typeof method) {
<del> ret[idx] = args.length ? method.apply(x, args) : x[methodName]();
<del> }
<del> }, this);
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Simply converts the enumerable into a genuine array. The order is not
<del> guaranteed. Corresponds to the method implemented by Prototype.
<del>
<del> @method toArray
<del> @return {Array} the enumerable as an array.
<del> @public
<del> */
<del> toArray() {
<del> let ret = emberA();
<del>
<del> this.forEach((o, idx) => ret[idx] = o);
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Returns a copy of the array with all `null` and `undefined` elements removed.
<del>
<del> ```javascript
<del> let arr = ['a', null, 'c', undefined];
<del> arr.compact(); // ['a', 'c']
<del> ```
<del>
<del> @method compact
<del> @return {Array} the array without null and undefined elements.
<del> @public
<del> */
<del> compact() {
<del> return this.filter(value => value != null);
<del> },
<del>
<del> /**
<del> Returns a new enumerable that excludes the passed value. The default
<del> implementation returns an array regardless of the receiver type.
<del> If the receiver does not contain the value it returns the original enumerable.
<del>
<del> ```javascript
<del> let arr = ['a', 'b', 'a', 'c'];
<del> arr.without('a'); // ['b', 'c']
<del> ```
<del>
<del> @method without
<del> @param {Object} value
<del> @return {Enumerable}
<del> @public
<del> */
<del> without(value) {
<del> if (!this.includes(value)) {
<del> return this; // nothing to do
<del> }
<del>
<del> let ret = emberA();
<del>
<del> this.forEach(k => {
<del> // SameValueZero comparison (NaN !== NaN)
<del> if (!(k === value || k !== k && value !== value)) {
<del> ret[ret.length] = k;
<del> }
<del> });
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Returns a new enumerable that contains only unique values. The default
<del> implementation returns an array regardless of the receiver type.
<del>
<del> ```javascript
<del> let arr = ['a', 'a', 'b', 'b'];
<del> arr.uniq(); // ['a', 'b']
<del> ```
<del>
<del> This only works on primitive data types, e.g. Strings, Numbers, etc.
<del>
<del> @method uniq
<del> @return {Enumerable}
<del> @public
<del> */
<del> uniq() {
<del> let ret = emberA();
<del>
<del> let seen = new Set();
<del> this.forEach(item => {
<del> if (!seen.has(item)) {
<del> seen.add(item);
<del> ret.push(item);
<del> }
<del> });
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> This property will trigger anytime the enumerable's content changes.
<del> You can observe this property to be notified of changes to the enumerable's
<del> content.
<del>
<del> For plain enumerables, this property is read only. `Array` overrides
<del> this method.
<del>
<del> @property []
<del> @type Array
<del> @return this
<del> @private
<del> */
<del> '[]': computed({
<del> get(key) { return this; } // eslint-disable-line no-unused-vars
<del> }),
<del>
<del> // ..........................................................
<del> // ENUMERABLE OBSERVERS
<del> //
<del>
<del> /**
<del> Invoke this method just before the contents of your enumerable will
<del> change. You can either omit the parameters completely or pass the objects
<del> to be removed or added if available or just a count.
<del>
<del> @method enumerableContentWillChange
<del> @param {Enumerable|Number} removing An enumerable of the objects to
<del> be removed or the number of items to be removed.
<del> @param {Enumerable|Number} adding An enumerable of the objects to be
<del> added or the number of items to be added.
<del> @chainable
<del> @private
<del> */
<del> enumerableContentWillChange(removing, adding) {
<del> let removeCnt, addCnt, hasDelta;
<del>
<del> if ('number' === typeof removing) {
<del> removeCnt = removing;
<del> } else if (removing) {
<del> removeCnt = get(removing, 'length');
<del> } else {
<del> removeCnt = removing = -1;
<del> }
<del>
<del> if ('number' === typeof adding) {
<del> addCnt = adding;
<del> } else if (adding) {
<del> addCnt = get(adding, 'length');
<del> } else {
<del> addCnt = adding = -1;
<del> }
<del>
<del> hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
<del>
<del> if (removing === -1) {
<del> removing = null;
<del> }
<del>
<del> if (adding === -1) {
<del> adding = null;
<del> }
<del>
<del> propertyWillChange(this, '[]');
<del>
<del> if (hasDelta) {
<del> propertyWillChange(this, 'length');
<del> }
<del>
<del> return this;
<del> },
<del>
<del> /**
<del> Invoke this method when the contents of your enumerable has changed.
<del> This will notify any observers watching for content changes. If you are
<del> implementing an ordered enumerable (such as an array), also pass the
<del> start and end values where the content changed so that it can be used to
<del> notify range observers.
<del>
<del> @method enumerableContentDidChange
<del> @param {Enumerable|Number} removing An enumerable of the objects to
<del> be removed or the number of items to be removed.
<del> @param {Enumerable|Number} adding An enumerable of the objects to
<del> be added or the number of items to be added.
<del> @chainable
<del> @private
<del> */
<del> enumerableContentDidChange(removing, adding) {
<del> let removeCnt, addCnt, hasDelta;
<del>
<del> if ('number' === typeof removing) {
<del> removeCnt = removing;
<del> } else if (removing) {
<del> removeCnt = get(removing, 'length');
<del> } else {
<del> removeCnt = removing = -1;
<del> }
<del>
<del> if ('number' === typeof adding) {
<del> addCnt = adding;
<del> } else if (adding) {
<del> addCnt = get(adding, 'length');
<del> } else {
<del> addCnt = adding = -1;
<del> }
<del>
<del> hasDelta = addCnt < 0 || removeCnt < 0 || addCnt - removeCnt !== 0;
<del>
<del> if (removing === -1) {
<del> removing = null;
<del> }
<del>
<del> if (adding === -1) {
<del> adding = null;
<del> }
<del>
<del> if (hasDelta) {
<del> propertyDidChange(this, 'length');
<del> }
<del>
<del> propertyDidChange(this, '[]');
<del>
<del> return this;
<del> },
<del>
<del> /**
<del> Converts the enumerable into an array and sorts by the keys
<del> specified in the argument.
<del>
<del> You may provide multiple arguments to sort by multiple properties.
<del>
<del> @method sortBy
<del> @param {String} property name(s) to sort on
<del> @return {Array} The sorted array.
<del> @since 1.2.0
<del> @public
<del> */
<del> sortBy() {
<del> let sortKeys = arguments;
<del>
<del> return this.toArray().sort((a, b) => {
<del> for (let i = 0; i < sortKeys.length; i++) {
<del> let key = sortKeys[i];
<del> let propA = get(a, key);
<del> let propB = get(b, key);
<del> // return 1 or -1 else continue to the next sortKey
<del> let compareValue = compare(propA, propB);
<del>
<del> if (compareValue) {
<del> return compareValue;
<del> }
<del> }
<del> return 0;
<del> });
<del> },
<del>
<del> /**
<del> Returns a new enumerable that contains only items containing a unique property value.
<del> The default implementation returns an array regardless of the receiver type.
<del>
<del> ```javascript
<del> let arr = [{ value: 'a' }, { value: 'a' }, { value: 'b' }, { value: 'b' }];
<del> arr.uniqBy('value'); // [{ value: 'a' }, { value: 'b' }]
<del> ```
<del>
<del> @method uniqBy
<del> @return {Enumerable}
<del> @public
<del> */
<del>
<del> uniqBy(key) {
<del> let ret = emberA();
<del> let seen = new Set();
<del>
<del> this.forEach((item) => {
<del> let val = get(item, key);
<del> if (!seen.has(val)) {
<del> seen.add(val);
<del> ret.push(item);
<del> }
<del> });
<del>
<del> return ret;
<del> },
<del>
<del> /**
<del> Returns `true` if the passed object can be found in the enumerable.
<del>
<del> ```javascript
<del> [1, 2, 3].includes(2); // true
<del> [1, 2, 3].includes(4); // false
<del> [1, 2, undefined].includes(undefined); // true
<del> [1, 2, null].includes(null); // true
<del> [1, 2, NaN].includes(NaN); // true
<del> ```
<del>
<del> @method includes
<del> @param {Object} obj The object to search for.
<del> @return {Boolean} `true` if object is found in the enumerable.
<del> @public
<del> */
<del> includes(obj) {
<del> assert('Enumerable#includes cannot accept a second argument "startAt" as enumerable items are unordered.', arguments.length === 1);
<del>
<del> let len = get(this, 'length');
<del> let idx, next;
<del> let last = null;
<del> let found = false;
<del>
<del> let context = popCtx();
<del>
<del> for (idx = 0; idx < len && !found; idx++) {
<del> next = this.nextObject(idx, last, context);
<del>
<del> found = obj === next || (obj !== obj && next !== next);
<del>
<del> last = next;
<del> }
<del>
<del> next = last = null;
<del> context = pushCtx(context);
<del>
<del> return found;
<del> }
<del>});
<del>
<del>export default Enumerable;
<add>export default Mixin.create();
<ide><path>packages/ember-runtime/lib/mixins/mutable_array.js
<ide> @module @ember/array
<ide> */
<ide>
<del>
<del>const OUT_OF_RANGE_EXCEPTION = 'Index out of range';
<del>const EMPTY = [];
<del>
<del>// ..........................................................
<del>// HELPERS
<del>//
<del>
<ide> import {
<ide> get,
<del> Mixin
<add> Mixin,
<add> beginPropertyChanges,
<add> endPropertyChanges
<ide> } from 'ember-metal';
<del>import EmberArray, { objectAt } from './array';
<del>import MutableEnumerable from './mutable_enumerable';
<ide> import Enumerable from './enumerable';
<add>import MutableEnumerable from './mutable_enumerable';
<add>import EmberArray, { objectAt } from './array';
<ide> import { Error as EmberError } from 'ember-debug';
<ide>
<add>const OUT_OF_RANGE_EXCEPTION = 'Index out of range';
<add>const EMPTY = [];
<add>
<ide> export function removeAt(array, start, len) {
<ide> if ('number' === typeof start) {
<ide> if ((start < 0) || (start >= get(array, 'length'))) {
<ide> export function removeAt(array, start, len) {
<ide>
<ide> @class MutableArray
<ide> @uses EmberArray
<del> @uses Ember.MutableEnumerable
<add> @uses MutableEnumerable
<ide> @public
<ide> */
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> return this;
<ide> },
<ide>
<add> /**
<add> Removes each object in the passed array from the receiver.
<add>
<add> @method removeObjects
<add> @param {EmberArray} objects the objects to remove
<add> @return {EmberArray} receiver
<add> @public
<add> */
<add> removeObjects(objects) {
<add> beginPropertyChanges(this);
<add> for (let i = objects.length - 1; i >= 0; i--) {
<add> this.removeObject(objects[i]);
<add> }
<add> endPropertyChanges(this);
<add> return this;
<add> },
<add>
<ide> /**
<ide> Push the object onto the end of the array if it is not already
<ide> present in the array.
<ide> export default Mixin.create(EmberArray, MutableEnumerable, {
<ide> this.pushObject(obj);
<ide> }
<ide>
<add> return this;
<add> },
<add>
<add> /**
<add> Adds each object in the passed array to the receiver.
<add>
<add> @method addObjects
<add> @param {EmberArray} objects the objects to add.
<add> @return {EmberArray} receiver
<add> @public
<add> */
<add> addObjects(objects) {
<add> beginPropertyChanges(this);
<add> objects.forEach(obj => this.addObject(obj));
<add> endPropertyChanges(this);
<ide> return this;
<ide> }
<ide> });
<ide><path>packages/ember-runtime/lib/mixins/mutable_enumerable.js
<ide> import Enumerable from './enumerable';
<del>import {
<del> Mixin,
<del> beginPropertyChanges,
<del> endPropertyChanges
<del>} from 'ember-metal';
<add>import { Mixin } from 'ember-metal';
<ide>
<ide> /**
<ide> @module ember
<ide> */
<ide>
<ide> /**
<del> This mixin defines the API for modifying generic enumerables. These methods
<del> can be applied to an object regardless of whether it is ordered or
<del> unordered.
<del>
<del> Note that an Enumerable can change even if it does not implement this mixin.
<del> For example, a MappedEnumerable cannot be directly modified but if its
<del> underlying enumerable changes, it will change also.
<del>
<del> ## Adding Objects
<del>
<del> To add an object to an enumerable, use the `addObject()` method. This
<del> method will only add the object to the enumerable if the object is not
<del> already present and is of a type supported by the enumerable.
<del>
<del> ```javascript
<del> set.addObject(contact);
<del> ```
<del>
<del> ## Removing Objects
<del>
<del> To remove an object from an enumerable, use the `removeObject()` method. This
<del> will only remove the object if it is present in the enumerable, otherwise
<del> this method has no effect.
<del>
<del> ```javascript
<del> set.removeObject(contact);
<del> ```
<del>
<del> ## Implementing In Your Own Code
<del>
<del> If you are implementing an object and want to support this API, just include
<del> this mixin in your class and implement the required methods. In your unit
<del> tests, be sure to apply the MutableEnumerableTests to your object.
<add> The methods in this mixin have been moved to MutableArray. This mixin has
<add> been intentionally preserved to avoid breaking MutableEnumerable.detect
<add> checks until the community migrates away from them.
<ide>
<ide> @class MutableEnumerable
<ide> @namespace Ember
<ide> @uses Enumerable
<ide> @private
<ide> */
<del>export default Mixin.create(Enumerable, {
<del>
<del> /**
<del> __Required.__ You must implement this method to apply this mixin.
<del>
<del> Attempts to add the passed object to the receiver if the object is not
<del> already present in the collection. If the object is present, this method
<del> has no effect.
<del>
<del> If the passed object is of a type not supported by the receiver,
<del> then this method should raise an exception.
<del>
<del> @method addObject
<del> @param {Object} object The object to add to the enumerable.
<del> @return {Object} the passed object
<del> @public
<del> */
<del> addObject: null,
<del>
<del> /**
<del> Adds each object in the passed enumerable to the receiver.
<del>
<del> @method addObjects
<del> @param {Enumerable} objects the objects to add.
<del> @return {Object} receiver
<del> @public
<del> */
<del> addObjects(objects) {
<del> beginPropertyChanges(this);
<del> objects.forEach(obj => this.addObject(obj));
<del> endPropertyChanges(this);
<del> return this;
<del> },
<del>
<del> /**
<del> __Required.__ You must implement this method to apply this mixin.
<del>
<del> Attempts to remove the passed object from the receiver collection if the
<del> object is present in the collection. If the object is not present,
<del> this method has no effect.
<del>
<del> If the passed object is of a type not supported by the receiver,
<del> then this method should raise an exception.
<del>
<del> @method removeObject
<del> @param {Object} object The object to remove from the enumerable.
<del> @return {Object} the passed object
<del> @public
<del> */
<del> removeObject: null,
<del>
<del>
<del> /**
<del> Removes each object in the passed enumerable from the receiver.
<del>
<del> @method removeObjects
<del> @param {Enumerable} objects the objects to remove
<del> @return {Object} receiver
<del> @public
<del> */
<del> removeObjects(objects) {
<del> beginPropertyChanges(this);
<del> for (let i = objects.length - 1; i >= 0; i--) {
<del> this.removeObject(objects[i]);
<del> }
<del> endPropertyChanges(this);
<del> return this;
<del> }
<del>});
<add>export default Mixin.create(Enumerable); | 4 |
Python | Python | fix train loop to avoid swallowing tracebacks | c04bab6bae214ca31ba5c11ce6e46e4cb23923ac | <ide><path>spacy/training/loop.py
<ide> def train(
<ide> batcher = T["batcher"]
<ide> train_logger = T["logger"]
<ide> before_to_disk = create_before_to_disk_callback(T["before_to_disk"])
<add>
<add> # Helper function to save checkpoints. This is a closure for convenience,
<add> # to avoid passing in all the args all the time.
<add> def save_checkpoint(is_best):
<add> with nlp.use_params(optimizer.averages):
<add> before_to_disk(nlp).to_disk(output_path / DIR_MODEL_LAST)
<add> if is_best:
<add> # Avoid saving twice (saving will be more expensive than
<add> # the dir copy)
<add> if (output_path / DIR_MODEL_BEST).exists():
<add> shutil.rmtree(output_path / DIR_MODEL_BEST)
<add> shutil.copytree(output_path / DIR_MODEL_LAST, output_path / DIR_MODEL_BEST)
<add>
<ide> # Components that shouldn't be updated during training
<ide> frozen_components = T["frozen_components"]
<ide> # Create iterator, which yields out info after each optimization step.
<ide> def train(
<ide> if is_best_checkpoint is not None and output_path is not None:
<ide> with nlp.select_pipes(disable=frozen_components):
<ide> update_meta(T, nlp, info)
<del> with nlp.use_params(optimizer.averages):
<del> nlp = before_to_disk(nlp)
<del> nlp.to_disk(output_path / DIR_MODEL_LAST)
<del> if is_best_checkpoint:
<del> with nlp.use_params(optimizer.averages):
<del> nlp.to_disk(output_path / DIR_MODEL_BEST)
<del>
<add> save_checkpoint(is_best_checkpoint)
<ide> except Exception as e:
<ide> if output_path is not None:
<del> # We don't want to swallow the traceback if we don't have a
<del> # specific error, but we do want to warn that we're trying
<del> # to do something here.
<ide> stdout.write(
<ide> msg.warn(
<ide> f"Aborting and saving the final best model. "
<del> f"Encountered exception: {str(e)}"
<add> f"Encountered exception: {repr(e)}"
<ide> )
<ide> + "\n"
<ide> )
<ide> raise e
<ide> finally:
<ide> finalize_logger()
<del> if optimizer.averages:
<del> nlp.use_params(optimizer.averages)
<del> if output_path is not None:
<del> final_model_path = output_path / DIR_MODEL_LAST
<del> nlp.to_disk(final_model_path)
<del> # This will only run if we don't hit an error
<del> stdout.write(
<del> msg.good("Saved pipeline to output directory", final_model_path) + "\n"
<del> )
<del> return (nlp, final_model_path)
<del> else:
<del> return (nlp, None)
<add> save_checkpoint(False)
<add> # This will only run if we did't hit an error
<add> if optimizer.averages:
<add> nlp.use_params(optimizer.averages)
<add> if output_path is not None:
<add> stdout.write(
<add> msg.good("Saved pipeline to output directory", output_path / DIR_MODEL_LAST)
<add> + "\n"
<add> )
<add> return (nlp, output_path / DIR_MODEL_LAST)
<add> else:
<add> return (nlp, None)
<ide>
<ide>
<ide> def train_while_improving( | 1 |
PHP | PHP | add testcase for network/email/cakeemail.php | f541260350e132d60ac42f8ec006aafe1fd2b337 | <ide><path>lib/Cake/Test/Case/Network/Email/CakeEmailTest.php
<ide> public function testHeaderEncoding() {
<ide> }
<ide>
<ide> public function testWrapLongLine() {
<del> $message = '<a href="http://cakephp.org">' . str_repeat('1234567890', 100) . "</a>";
<add> $message = '<a href="http://cakephp.org">' . str_repeat('x', CakeEmail::LINE_LENGTH_MUST) . "</a>";
<ide>
<ide> $this->CakeEmail->reset();
<ide> $this->CakeEmail->transport('Debug');
<ide> public function testWrapLongLine() {
<ide> $this->CakeEmail->subject('Wordwrap Test');
<ide> $this->CakeEmail->config(array('empty'));
<ide> $result = $this->CakeEmail->send($message);
<del> $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('1234567890', 100) . "\r\n</a>\r\n\r\n";
<add> $expected = "<a\r\n" . 'href="http://cakephp.org">' . str_repeat('x', CakeEmail::LINE_LENGTH_MUST) . "\r\n</a>\r\n\r\n";
<add> $this->assertEquals($expected, $result['message']);
<add> }
<add>
<add> public function testWrapIncludeTag() {
<add> $message = '<a href="http://cakephp.org">CakePHP</a>';
<add>
<add> $this->CakeEmail->reset();
<add> $this->CakeEmail->transport('Debug');
<add> $this->CakeEmail->from('cake@cakephp.org');
<add> $this->CakeEmail->to('cake@cakephp.org');
<add> $this->CakeEmail->subject('Wordwrap Test');
<add> $this->CakeEmail->config(array('empty'));
<add> $result = $this->CakeEmail->send($message);
<add> $expected = "{$message}\r\n\r\n";
<add> $this->assertEquals($expected, $result['message']);
<add>
<add> $message = 'foo<bar';
<add>
<add> $result = $this->CakeEmail->send($message);
<add> $expected = "{$message}\r\n\r\n";
<ide> $this->assertEquals($expected, $result['message']);
<ide> }
<ide> | 1 |
Python | Python | update the tf backend documentation | 9090704f1d4f36958ee9080f8a3ba89866512cca | <ide><path>keras/backend/tensorflow_backend.py
<ide> def clear_session():
<ide>
<ide>
<ide> def manual_variable_initialization(value):
<del> '''Returns a boolean:
<del> whether variables should be initialized
<add> '''Sets the manual variable initialization flag.
<add>
<add> This boolean flag determines whether
<add> variables should be initialized
<ide> as they are instantiated (default), or if
<ide> the user should handle the initialization
<del> (e.g. via tf.initialize_all_variables()).
<add> (e.g. via `tf.initialize_all_variables()`).
<add>
<add> # Arguments
<add> value: Python boolean.
<ide> '''
<ide> global _MANUAL_VAR_INIT
<ide> _MANUAL_VAR_INIT = value
<ide> def get_session():
<ide>
<ide> # Returns
<ide> A TensorFlow session.
<del>
<ide> '''
<ide> global _SESSION
<ide> if tf.get_default_session() is not None:
<ide> def is_sparse(tensor):
<ide> '''Returns whether a tensor is a sparse tensor.
<ide>
<ide> # Arguments
<del> tensor: a Keras tensor.
<add> tensor: A tensor instance.
<ide>
<ide> # Returns
<del> Boolean.
<add> A boolean.
<ide>
<ide> # Example
<ide> ```python
<del> >>> a = keras.backend.placeholder((2, 2), sparse=False)
<del> >>> print(keras.backend.is_sparse(a))
<add> >>> from keras import backend as K
<add> >>> a = K.placeholder((2, 2), sparse=False)
<add> >>> print(K.is_sparse(a))
<ide> False
<del> >>> b = keras.backend.placeholder((2, 2), sparse=True)
<del> >>> print(keras.backend.is_sparse(b))
<add> >>> b = K.placeholder((2, 2), sparse=True)
<add> >>> print(K.is_sparse(b))
<ide> True
<ide> ```
<del>
<ide> '''
<ide> return isinstance(tensor, tf.SparseTensor)
<ide>
<ide>
<ide> def to_dense(tensor):
<del> '''Converts a Keras tensor into a Keras dense tensor
<add> '''Converts a sparse tensor into a dense tensor
<ide> and returns it.
<ide>
<ide> # Arguments
<del> tensor: Keras tensor.
<add> tensor: A tensor instance (potentially sparse).
<ide>
<ide> # Returns
<del> A Keras dense tensor.
<add> A dense tensor.
<ide>
<ide> # Examples
<ide> ```python
<del> >>> b = keras.backend.placeholder((2, 2), sparse=True)
<del> >>> print(keras.backend.is_sparse(b))
<add> >>> from keras import backend as K
<add> >>> b = K.placeholder((2, 2), sparse=True)
<add> >>> print(K.is_sparse(b))
<ide> True
<del> >>> c = keras.backend.to_dense(b)
<del> >>> print(keras.backend.is_sparse(c))
<add> >>> c = K.to_dense(b)
<add> >>> print(K.is_sparse(c))
<ide> False
<ide> ```
<ide> '''
<ide> def to_dense(tensor):
<ide>
<ide>
<ide> def variable(value, dtype=_FLOATX, name=None):
<del> '''Instantiates a tensor and returns it.
<add> '''Instantiates a variable and returns it.
<ide>
<ide> # Arguments
<del> value: numpy array, initial value of the tensor.
<del>
<del> dtype: tensor type.
<del>
<del> name: optional name string for the tensor.
<add> value: Numpy array, initial value of the tensor.
<add> dtype: Tensor type.
<add> name: Optional name string for the tensor.
<ide>
<ide> # Returns
<del> A Keras variable instance.
<add> A variable instance (with Keras metadata included).
<ide>
<ide> # Examples
<ide> ```python
<ide> >>> from keras import backend as K
<ide> >>> val = np.array([[1, 2], [3, 4]])
<del> >>> kvar = K.variable(value=val, dtype='float64', name='example_kvar')
<add> >>> kvar = K.variable(value=val, dtype='float64', name='example_var')
<ide> >>> K.dtype(kvar)
<ide> 'float64'
<ide> >>> print(kvar)
<del> example_kvar
<add> example_var
<ide> >>> kvar.eval()
<ide> array([[ 1., 2.],
<ide> [ 3., 4.]])
<ide> def variable(value, dtype=_FLOATX, name=None):
<ide> sparse_coo = value.tocoo()
<ide> indices = np.concatenate((np.expand_dims(sparse_coo.row, 1),
<ide> np.expand_dims(sparse_coo.col, 1)), 1)
<del> # SparseTensor doesn't need initialization
<ide> v = tf.SparseTensor(indices=indices,
<ide> values=sparse_coo.data,
<ide> shape=sparse_coo.shape)
<ide> v._dims = len(sparse_coo.shape)
<add> v._keras_shape = sparse_coo.shape
<add> v._uses_learning_phase = False
<ide> return v
<ide> v = tf.Variable(value, dtype=_convert_string_dtype(dtype), name=name)
<add> if isinstance(value, np.array):
<add> v._keras_shape = value.shape
<add> elif hasattr(value, 'get_shape'):
<add> v._keras_shape = tuple(map(int, value.get_shape()))
<add> v._uses_learning_phase = False
<ide> return v
<ide>
<ide>
<ide> def _initialize_variables():
<ide>
<ide>
<ide> def placeholder(shape=None, ndim=None, dtype=_FLOATX, sparse=False, name=None):
<del> '''Instantiates a placeholder (Keras tensor) and returns it.
<add> '''Instantiates a placeholder tensor and returns it.
<ide>
<ide> # Arguments
<del> shape: shape of the placeholder
<add> shape: Shape of the placeholder
<ide> (integer tuple, may include `None` entries).
<del>
<del> ndim: number of axes of the tensor.
<add> ndim: Number of axes of the tensor.
<ide> At least one of {`shape`, `ndim`} must be specified.
<ide> If both are specified, `shape` is used.
<del>
<del> dtype: placeholder type.
<del>
<del> name: optional name string for the placeholder.
<add> dtype: Placeholder type.
<add> name: Optional name string for the placeholder.
<ide>
<ide> # Returns
<del> Keras tensor instance.
<add> Tensor instance (with Keras metadata included).
<ide>
<ide> # Examples
<ide> ```python
<del> >>> input = keras.backend.placeholder(shape=(2, 4, 5))
<del> >>> input._keras_shape
<add> >>> from keras import backend as K
<add> >>> input_ph = K.placeholder(shape=(2, 4, 5))
<add> >>> input_ph._keras_shape
<ide> (2, 4, 5)
<del> >>> input
<add> >>> input_ph
<ide> <tf.Tensor 'Placeholder_4:0' shape=(2, 4, 5) dtype=float32>
<ide> ```
<ide> '''
<ide> def placeholder(shape=None, ndim=None, dtype=_FLOATX, sparse=False, name=None):
<ide>
<ide>
<ide> def shape(x):
<del> '''Returns the symbolic shape of a Keras tensor or variable.
<add> '''Returns the symbolic shape of a tensor or variable.
<ide>
<ide> # Arguments
<del> x: A Keras tensor or variable.
<add> x: A tensor or variable.
<ide>
<ide> # Returns
<del> A symbolic shape.
<add> A symbolic shape (which is itself a tensor).
<ide>
<ide> # Examples
<ide> ```
<ide> def shape(x):
<ide> def int_shape(x):
<ide> '''Returns the shape of a Keras tensor or a Keras variable as a tuple of
<ide> integers or None entries.
<del> Note that this function only works with TensorFlow.
<ide>
<ide> # Arguments
<del> x: A Keras tensor or variable.
<add> x: Tensor or variable.
<ide>
<ide> # Returns
<ide> A tuple of integers.
<ide> def ndim(x):
<ide> '''Returns the number of axes in a tensor, as an integer.
<ide>
<ide> # Arguments
<del> x: Keras tensor or variable.
<add> x: Tensor or variable.
<ide>
<ide> # Returns
<del> integer (scalar), number of dimensions.
<add> Integer (scalar), number of axes.
<ide>
<ide> # Examples
<ide> ```python
<ide> def dtype(x):
<ide> '''Returns the dtype of a Keras tensor or variable, as a string.
<ide>
<ide> # Arguments
<del> x: Keras tensor or variable.
<add> x: Tensor or variable.
<ide>
<ide> # Returns
<ide> String, dtype of `x`.
<ide>
<ide> # Examples
<ide> ```python
<ide> >>> from keras import backend as K
<del> # Keras tensor
<ide> >>> K.dtype(K.placeholder(shape=(2,4,5)))
<ide> 'float32'
<ide> >>> K.dtype(K.placeholder(shape=(2,4,5), dtype='float32'))
<ide> def dtype(x):
<ide>
<ide>
<ide> def eval(x):
<del> '''Evaluates the value of a Keras variable.
<add> '''Evaluates the value of a variable.
<ide> Returns a Numpy array.
<ide>
<ide> # Arguments
<del> x: A Keras variable.
<add> x: A variable.
<ide>
<ide> # Returns
<ide> A Numpy array.
<ide> def eval(x):
<ide>
<ide>
<ide> def zeros(shape, dtype=_FLOATX, name=None):
<del> '''Instantiates an all-zeros Keras variable and returns it.
<add> '''Instantiates an all-zeros variable and returns it.
<ide>
<ide> # Arguments
<ide> shape: Tuple of integers, shape of returned Keras variable
<del>
<ide> dtype: String, data type of returned Keras variable
<del>
<ide> name: String, name of returned Keras variable
<ide>
<ide> # Returns
<del> A Keras variable, filled with `0.0`
<add> A variable (including Keras metadata), filled with `0.0`.
<ide>
<ide> # Example
<ide> ```python
<ide> def count_params(x):
<ide>
<ide>
<ide> def cast(x, dtype):
<del> '''Casts a Keras tensor to a tensor of a different dtype and returns it.
<add> '''Casts a tensor to a different dtype and returns it.
<ide>
<ide> You can cast a Keras variable but it still returns a Keras tensor.
<ide>
<ide> # Arguments
<ide> x: Keras tensor (or variable).
<del>
<ide> dtype: String, either (`'float16'`, `'float32'`, or `'float64'`).
<ide>
<ide> # Returns
<del> Keras tensor with dtype of `dtype`.
<add> Keras tensor with dtype `dtype`.
<ide>
<ide> # Example
<ide> ```python
<add> >>> from keras import backend as K
<ide> >>> input = K.placeholder((2, 3), dtype='float32')
<ide> >>> input
<ide> <tf.Tensor 'Placeholder_2:0' shape=(2, 3) dtype=float32>
<ide> def dot(x, y):
<ide> with a ND tensor, it reproduces the Theano behavior.
<ide> (e.g. (2, 3).(4, 3, 5) = (2, 4, 5))
<ide>
<del> Like `K.cast()`, it can take Keras variables as inputs but the
<del> returned object is a Keras tensor.
<del>
<ide> # Arguments
<del> x: Keras tensor (or variable).
<del>
<del> y: Keras tensor (or variable).
<add> x: Tensor or variable.
<add> y: Tensor or variable.
<ide>
<ide> # Returns
<del> A Keras tensor, dot product of `x` and `y`.
<add> A tensor, dot product of `x` and `y`.
<ide>
<ide> # Examples
<ide> ```python
<del> # dot product between Keras tensors
<add> # dot product between tensors
<ide> >>> x = K.placeholder(shape=(2, 3))
<ide> >>> y = K.placeholder(shape=(3, 4))
<ide> >>> xy = K.dot(x, y)
<ide> def dot(x, y):
<ide> ```
<ide>
<ide> ```python
<del> # dot product between Keras tensors
<add> # dot product between tensors
<ide> >>> x = K.placeholder(shape=(32, 28, 3))
<ide> >>> y = K.placeholder(shape=(3, 4))
<ide> >>> xy = K.dot(x, y)
<ide> def dot(x, y):
<ide> ```
<ide>
<ide> ```python
<del> # dot product between Keras tensor and Keras variable
<del> >>> input = K.placeholder((2, 3))
<del> >>> y = K.random_uniform_variable(shape=(3, 4), low=0, high=1)
<del> >>> xy = K.dot(x, y)
<del> # It returns a Keras tensor
<del> >>> xy
<del> <tf.Tensor 'MatMul_1:0' shape=(2, 4) dtype=float32>
<del> ```
<del>
<del> ```python
<del> # The Theano behavior example
<add> # Theano-like behavior example
<ide> >>> x = K.random_uniform_variable(shape=(2, 3), low=0, high=1)
<ide> >>> y = K.ones((4, 3, 5))
<ide> >>> xy = K.dot(x, y)
<ide> def batch_dot(x, y, axes=None):
<ide> than the input. If the number of dimensions is reduced to 1,
<ide> we use `expand_dims` to make sure that ndim is at least 2.
<ide>
<del> With TensorFlow backend, `batch_dot()` only supports `ndim >= 3` inputs.
<del>
<ide> # Arguments
<ide> x, y: Keras tensors or variables with `ndim >= 2`
<ide> (With TensorFlow backend, `batch_dot()` only supports `ndim >= 3`)
<del>
<ide> axes: list of (or single) int with target dimensions.
<ide> The lengths of `axes[0]` and `axes[1]` should be the same.
<ide>
<ide> # Returns
<ide> A tensor with shape equal to the concatenation of `x`'s shape
<ide> (less the dimension that was summed over) and `y`'s shape
<ide> (less the batch dimension and the dimension that was summed over).
<del>
<ide> If the final rank is 1, we reshape it to `(batch_size, 1)`.
<ide>
<ide> # Examples
<ide> def batch_dot(x, y, axes=None):
<ide>
<ide>
<ide> def transpose(x):
<del> '''Transposes a matrix and returns it.
<add> '''Transposes a tensor and returns it.
<ide>
<ide> # Arguments
<del> x: Keras tensor or variable.
<add> x: Tensor or variable.
<ide>
<ide> # Returns
<del> Keras tensor or variable, transposed.
<add> A tensor.
<ide>
<ide> # Examples
<ide> ```python
<ide> def transpose(x):
<ide>
<ide>
<ide> def gather(reference, indices):
<del> '''Retrieves the vectors of indices `indices`
<del> in the 2D tensor `reference`.
<add> '''Retrieves the elements of indices `indices`
<add> in the tensor `reference`.
<ide>
<ide> # Arguments
<del> reference: a 2D tensor.
<del> indices: an int tensor of indices.
<add> reference: A tensor.
<add> indices: An integer tensor of indices.
<ide>
<ide> # Returns
<del> A 3D tensor of same type as `reference`.
<add> A tensor of same type as `reference`.
<ide> '''
<ide> return tf.gather(reference, indices)
<ide>
<ide> def cos(x):
<ide>
<ide> def normalize_batch_in_training(x, gamma, beta,
<ide> reduction_axes, epsilon=1e-3):
<del> '''Compute mean and std for batch then apply batch_normalization on batch.
<add> '''Computes mean and std for batch then apply batch_normalization on batch.
<ide> '''
<ide> mean, var = tf.nn.moments(x, reduction_axes,
<ide> shift=None, name=None, keep_dims=False)
<ide> def normalize_batch_in_training(x, gamma, beta,
<ide>
<ide>
<ide> def batch_normalization(x, mean, var, beta, gamma, epsilon=1e-3):
<del> '''Apply batch normalization on x given mean, var, beta and gamma:
<add> '''Applies batch normalization on x given mean, var, beta and gamma:
<ide>
<ide> output = (x - mean) / (sqrt(var) + epsilon) * gamma + beta
<ide> '''
<ide> def batch_normalization(x, mean, var, beta, gamma, epsilon=1e-3):
<ide> # SHAPE OPERATIONS
<ide>
<ide> def concatenate(tensors, axis=-1):
<del> '''Concantes a list of tensors alongside the specified axis.
<add> '''Concatenates a list of tensors alongside the specified axis.
<ide> '''
<ide> if axis < 0:
<ide> dims = ndim(tensors[0])
<ide> def resize_images(X, height_factor, width_factor, dim_ordering):
<ide>
<ide>
<ide> def resize_volumes(X, depth_factor, height_factor, width_factor, dim_ordering):
<del> '''Resize the volume contained in a 5D tensor of shape
<add> '''Resizes the volume contained in a 5D tensor of shape
<ide> - [batch, channels, depth, height, width] (for 'th' dim_ordering)
<ide> - [batch, depth, height, width, channels] (for 'tf' dim_ordering)
<ide> by a factor of (depth_factor, height_factor, width_factor). | 1 |
Java | Java | fix white space in reactimagemanager.java | ebb92ad2cce8e35ec2bd9ff17170e2c18ea94b1e | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageManager.java
<ide> public ReactImageView createViewInstance(ThemedReactContext context) {
<ide> public void setSource(ReactImageView view, @Nullable String source) {
<ide> view.setSource(source);
<ide> }
<del>
<add>
<ide> @ReactProp(name = "borderColor", customType = "Color")
<ide> public void setBorderColor(ReactImageView view, @Nullable Integer borderColor) {
<ide> if (borderColor == null) {
<ide> public void setBorderColor(ReactImageView view, @Nullable Integer borderColor) {
<ide> view.setBorderColor(borderColor);
<ide> }
<ide> }
<del>
<add>
<ide> @ReactProp(name = "borderWidth")
<ide> public void setBorderWidth(ReactImageView view, float borderWidth) {
<ide> view.setBorderWidth(borderWidth); | 1 |
Ruby | Ruby | add additional specs for `path` | 9f1b64a9d44650ac36f8bfacfc325c67364a2837 | <ide><path>Library/Homebrew/PATH.rb
<ide> def reject(&block)
<ide> end
<ide>
<ide> def to_ary
<del> @paths
<add> @paths.dup.to_ary
<ide> end
<ide> alias to_a to_ary
<ide>
<ide><path>Library/Homebrew/test/PATH_spec.rb
<ide> it "returns a PATH array" do
<ide> expect(described_class.new("/path1", "/path2").to_ary).to eq(["/path1", "/path2"])
<ide> end
<add>
<add> it "does not allow mutating the original" do
<add> path = described_class.new("/path1", "/path2")
<add> path.to_ary << "/path3"
<add>
<add> expect(path).not_to include("/path3")
<add> end
<ide> end
<ide>
<ide> describe "#to_str" do
<ide> end
<ide> end
<ide>
<add> describe "#==" do
<add> it "always returns false when comparing against something which does not respons to `#to_ary` or `#to_str`" do
<add> expect(described_class.new).not_to eq Object.new
<add> end
<add> end
<add>
<ide> describe "#include?" do
<ide> it "returns true if a path is included" do
<ide> path = described_class.new("/path1", "/path2") | 2 |
Javascript | Javascript | loosen timeout in spawnsync-test for freebsd | ccc91aea35c70fbae152a09253879da96f41dfd9 | <ide><path>test/parallel/test-child-process-spawnsync-timeout.js
<ide> var assert = require('assert');
<ide> var spawnSync = require('child_process').spawnSync;
<ide>
<ide> var TIMER = 200;
<del>var SLEEP = 1000;
<add>var SLEEP = 5000;
<ide>
<ide> switch (process.argv[2]) {
<ide> case 'child': | 1 |
Go | Go | add map() method to layerstore interface | 148aef9199ef0af6d03ea53e616c9fbd23b7c5ec | <ide><path>distribution/xfer/download_test.go
<ide> func createChainIDFromParent(parent layer.ChainID, dgsts ...layer.DiffID) layer.
<ide> return createChainIDFromParent(layer.ChainID(dgst), dgsts[1:]...)
<ide> }
<ide>
<add>func (ls *mockLayerStore) Map() map[layer.ChainID]layer.Layer {
<add> layers := map[layer.ChainID]layer.Layer{}
<add>
<add> for k, v := range ls.layers {
<add> layers[k] = v
<add> }
<add>
<add> return layers
<add>}
<add>
<ide> func (ls *mockLayerStore) Register(reader io.Reader, parentID layer.ChainID) (layer.Layer, error) {
<ide> return ls.RegisterWithDescriptor(reader, parentID, distribution.Descriptor{})
<ide> }
<ide><path>layer/layer.go
<ide> type MountInit func(root string) error
<ide> type Store interface {
<ide> Register(io.Reader, ChainID) (Layer, error)
<ide> Get(ChainID) (Layer, error)
<add> Map() map[ChainID]Layer
<ide> Release(Layer) ([]Metadata, error)
<ide>
<ide> CreateRWLayer(id string, parent ChainID, mountLabel string, initFunc MountInit, storageOpt map[string]string) (RWLayer, error)
<ide><path>layer/layer_store.go
<ide> func (ls *layerStore) Get(l ChainID) (Layer, error) {
<ide> return layer.getReference(), nil
<ide> }
<ide>
<add>func (ls *layerStore) Map() map[ChainID]Layer {
<add> ls.layerL.Lock()
<add> defer ls.layerL.Unlock()
<add>
<add> layers := map[ChainID]Layer{}
<add>
<add> for k, v := range ls.layerMap {
<add> layers[k] = v
<add> }
<add>
<add> return layers
<add>}
<add>
<ide> func (ls *layerStore) deleteLayer(layer *roLayer, metadata *Metadata) error {
<ide> err := ls.driver.Remove(layer.cacheID)
<ide> if err != nil { | 3 |
Go | Go | remove unused remote.rootdir | 7b0bd43a27ceb6d713a6589e73352658e1d0b704 | <ide><path>libcontainerd/supervisor/remote_daemon.go
<ide> type remote struct {
<ide> daemonStartCh chan error
<ide> daemonStopCh chan struct{}
<ide>
<del> rootDir string
<ide> stateDir string
<ide> }
<ide>
<ide> type DaemonOpt func(c *remote) error
<ide> // Start starts a containerd daemon and monitors it
<ide> func Start(ctx context.Context, rootDir, stateDir string, opts ...DaemonOpt) (Daemon, error) {
<ide> r := &remote{
<del> rootDir: rootDir,
<ide> stateDir: stateDir,
<ide> Config: config.Config{
<ide> Version: 2, | 1 |
Text | Text | add nodeedkeygenparams to cryptokey.algorithm | f825341bab8839c3a9a02c26bbacdf3553054e63 | <ide><path>doc/api/webcrypto.md
<ide> added: v15.0.0
<ide>
<ide> <!--lint disable maximum-line-length remark-lint-->
<ide>
<del>* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams}
<add>* Type: {AesKeyGenParams|RsaHashedKeyGenParams|EcKeyGenParams|HmacKeyGenParams|NodeDsaKeyGenParams|NodeDhKeyGenParams|NodeEdKeyGenParams}
<ide>
<ide> <!--lint enable maximum-line-length remark-lint-->
<ide> | 1 |
Ruby | Ruby | fix ant_dep for linux | 54a086e2fe06218c8a336fb7033da60078db7d78 | <ide><path>Library/Homebrew/dependency_collector.rb
<ide> def parse_class_spec(spec, tags)
<ide> end
<ide>
<ide> def ant_dep(spec, tags)
<del> if MacOS.version >= :mavericks
<add> if MacOS.version >= :mavericks || !OS.mac?
<ide> Dependency.new(spec.to_s, tags)
<ide> end
<ide> end
<ide><path>Library/Homebrew/test/test_dependency_collector.rb
<ide> def test_x11_min_version_and_tag
<ide> assert_predicate dep, :optional?
<ide> end
<ide>
<add> def test_ant_dep_mavericks_or_newer
<add> skip "Only for Mac OS" unless OS.mac?
<add> MacOS.stubs(:version).returns(MacOS::Version.new("10.9"))
<add> @d.add :ant => :build
<add> assert_equal find_dependency("ant"), Dependency.new("ant", [:build])
<add> end
<add>
<add> def test_ant_dep_pre_mavericks
<add> skip "Only for Mac OS" unless OS.mac?
<add> MacOS.stubs(:version).returns(MacOS::Version.new("10.7"))
<add> @d.add :ant => :build
<add> assert_nil find_dependency("ant")
<add> end
<add>
<ide> def test_raises_typeerror_for_unknown_classes
<ide> assert_raises(TypeError) { @d.add(Class.new) }
<ide> end | 2 |
Javascript | Javascript | increase coverage for events | 7c767622bf81cbe379fe63d6b904844fbf9f45b3 | <ide><path>test/parallel/test-event-emitter-max-listeners.js
<ide> for (const obj of throwsObjs) {
<ide> }
<ide>
<ide> e.emit('maxListeners');
<add>
<add>{
<add> const { EventEmitter, defaultMaxListeners } = events;
<add> for (const obj of throwsObjs) {
<add> assert.throws(() => EventEmitter.setMaxListeners(obj), {
<add> code: 'ERR_OUT_OF_RANGE',
<add> });
<add> }
<add>
<add> assert.throws(
<add> () => EventEmitter.setMaxListeners(defaultMaxListeners, 'INVALID_EMITTER'),
<add> { code: 'ERR_INVALID_ARG_TYPE' }
<add> );
<add>}
<ide><path>test/parallel/test-events-once.js
<ide> async function onceAnEvent() {
<ide> strictEqual(ee.listenerCount('myevent'), 0);
<ide> }
<ide>
<add>async function onceAnEventWithNullOptions() {
<add> const ee = new EventEmitter();
<add>
<add> process.nextTick(() => {
<add> ee.emit('myevent', 42);
<add> });
<add>
<add> const [value] = await once(ee, 'myevent', null);
<add> strictEqual(value, 42);
<add>}
<add>
<add>
<ide> async function onceAnEventWithTwoArgs() {
<ide> const ee = new EventEmitter();
<ide>
<ide> async function eventTargetAbortSignalAfterEvent() {
<ide>
<ide> Promise.all([
<ide> onceAnEvent(),
<add> onceAnEventWithNullOptions(),
<ide> onceAnEventWithTwoArgs(),
<ide> catchesErrors(),
<ide> stopListeningAfterCatchingError(),
<ide><path>test/parallel/test-events-static-geteventlisteners.js
<ide> const common = require('../common');
<ide>
<ide> const {
<ide> deepStrictEqual,
<add> throws
<ide> } = require('assert');
<ide>
<ide> const { getEventListeners, EventEmitter } = require('events');
<ide> const { getEventListeners, EventEmitter } = require('events');
<ide> deepStrictEqual(getEventListeners(target, 'bar'), []);
<ide> deepStrictEqual(getEventListeners(target, 'baz'), [fn1]);
<ide> }
<add>
<add>{
<add> throws(() => {
<add> getEventListeners('INVALID_EMITTER');
<add> }, /ERR_INVALID_ARG_TYPE/);
<add>}
<ide><path>test/parallel/test-eventtarget.js
<ide> const {
<ide>
<ide> const { once } = require('events');
<ide>
<del>const { promisify } = require('util');
<add>const { promisify, inspect } = require('util');
<ide> const delay = promisify(setTimeout);
<ide>
<ide> // The globals are defined.
<ide> let asyncTest = Promise.resolve();
<ide> et.addEventListener('foo', listener);
<ide> et.dispatchEvent(new Event('foo'));
<ide> }
<add>
<add>{
<add> const ev = new Event('test');
<add> const evConstructorName = inspect(ev, {
<add> depth: -1
<add> });
<add> strictEqual(evConstructorName, 'Event');
<add>
<add> const inspectResult = inspect(ev, {
<add> depth: 1
<add> });
<add> ok(inspectResult.includes('Event'));
<add>}
<add>
<add>{
<add> const et = new EventTarget();
<add> const inspectResult = inspect(et, {
<add> depth: 1
<add> });
<add> ok(inspectResult.includes('EventTarget'));
<add>}
<add>
<add>{
<add> const ev = new Event('test');
<add> strictEqual(ev.constructor.name, 'Event');
<add>
<add> const et = new EventTarget();
<add> strictEqual(et.constructor.name, 'EventTarget');
<add>} | 4 |
Javascript | Javascript | change loop var to let | b6c407b90f5f1542cb6b1766fbea58672d7bd393 | <ide><path>lib/internal/tls.js
<ide> const { Object } = primordials;
<ide> function parseCertString(s) {
<ide> const out = Object.create(null);
<ide> const parts = s.split('\n');
<del> for (var i = 0, len = parts.length; i < len; i++) {
<add> for (let i = 0, len = parts.length; i < len; i++) {
<ide> const sepIndex = parts[i].indexOf('=');
<ide> if (sepIndex > 0) {
<ide> const key = parts[i].slice(0, sepIndex);
<ide><path>lib/internal/url.js
<ide> class URLSearchParams {
<ide> // Need to use reflection APIs for full spec compliance.
<ide> this[searchParams] = [];
<ide> const keys = Reflect.ownKeys(init);
<del> for (var i = 0; i < keys.length; i++) {
<add> for (let i = 0; i < keys.length; i++) {
<ide> const key = keys[i];
<ide> const desc = Reflect.getOwnPropertyDescriptor(init, key);
<ide> if (desc !== undefined && desc.enumerable) {
<ide> class URLSearchParams {
<ide>
<ide> const list = this[searchParams];
<ide> const output = [];
<del> for (var i = 0; i < list.length; i += 2)
<add> for (let i = 0; i < list.length; i += 2)
<ide> output.push(`${innerInspect(list[i])} => ${innerInspect(list[i + 1])}`);
<ide>
<ide> const length = output.reduce(
<ide> Object.defineProperties(URL.prototype, {
<ide> ...options
<ide> };
<ide> const ctx = this[context];
<del> var ret = ctx.scheme;
<add> let ret = ctx.scheme;
<ide> if (ctx.host !== null) {
<ide> ret += '//';
<ide> const has_username = ctx.username !== '';
<ide> Object.defineProperties(URL.prototype, {
<ide> configurable: true,
<ide> get() {
<ide> const ctx = this[context];
<del> var ret = ctx.host || '';
<add> let ret = ctx.host || '';
<ide> if (ctx.port !== null)
<ide> ret += `:${ctx.port}`;
<ide> return ret;
<ide> function initSearchParams(url, init) {
<ide> // Ref: https://url.spec.whatwg.org/#concept-urlencoded-parser
<ide> function parseParams(qs) {
<ide> const out = [];
<del> var pairStart = 0;
<del> var lastPos = 0;
<del> var seenSep = false;
<del> var buf = '';
<del> var encoded = false;
<del> var encodeCheck = 0;
<del> var i;
<add> let pairStart = 0;
<add> let lastPos = 0;
<add> let seenSep = false;
<add> let buf = '';
<add> let encoded = false;
<add> let encodeCheck = 0;
<add> let i;
<ide> for (i = 0; i < qs.length; ++i) {
<ide> const code = qs.charCodeAt(i);
<ide>
<ide> function serializeParams(array) {
<ide> const firstEncodedValue = encodeStr(array[1], noEscape, paramHexTable);
<ide> let output = `${firstEncodedParam}=${firstEncodedValue}`;
<ide>
<del> for (var i = 2; i < len; i += 2) {
<add> for (let i = 2; i < len; i += 2) {
<ide> const encodedParam = encodeStr(array[i], noEscape, paramHexTable);
<ide> const encodedValue = encodeStr(array[i + 1], noEscape, paramHexTable);
<ide> output += `&${encodedParam}=${encodedValue}`;
<ide> function defineIDLClass(proto, classStr, obj) {
<ide> function merge(out, start, mid, end, lBuffer, rBuffer) {
<ide> const sizeLeft = mid - start;
<ide> const sizeRight = end - mid;
<del> var l, r, o;
<add> let l, r, o;
<ide>
<ide> for (l = 0; l < sizeLeft; l++)
<ide> lBuffer[l] = out[start + l];
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide>
<ide> const list = this[searchParams];
<ide> name = toUSVString(name);
<del> for (var i = 0; i < list.length;) {
<add> for (let i = 0; i < list.length;) {
<ide> const cur = list[i];
<ide> if (cur === name) {
<ide> list.splice(i, 2);
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide>
<ide> const list = this[searchParams];
<ide> name = toUSVString(name);
<del> for (var i = 0; i < list.length; i += 2) {
<add> for (let i = 0; i < list.length; i += 2) {
<ide> if (list[i] === name) {
<ide> return list[i + 1];
<ide> }
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide> const list = this[searchParams];
<ide> const values = [];
<ide> name = toUSVString(name);
<del> for (var i = 0; i < list.length; i += 2) {
<add> for (let i = 0; i < list.length; i += 2) {
<ide> if (list[i] === name) {
<ide> values.push(list[i + 1]);
<ide> }
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide>
<ide> const list = this[searchParams];
<ide> name = toUSVString(name);
<del> for (var i = 0; i < list.length; i += 2) {
<add> for (let i = 0; i < list.length; i += 2) {
<ide> if (list[i] === name) {
<ide> return true;
<ide> }
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide> // If there are any name-value pairs whose name is `name`, in `list`, set
<ide> // the value of the first such name-value pair to `value` and remove the
<ide> // others.
<del> var found = false;
<del> for (var i = 0; i < list.length;) {
<add> let found = false;
<add> for (let i = 0; i < list.length;) {
<ide> const cur = list[i];
<ide> if (cur === name) {
<ide> if (!found) {
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide> // 100 is found through testing.
<ide> // Simple stable in-place insertion sort
<ide> // Derived from v8/src/js/array.js
<del> for (var i = 2; i < len; i += 2) {
<del> var curKey = a[i];
<del> var curVal = a[i + 1];
<del> var j;
<add> for (let i = 2; i < len; i += 2) {
<add> const curKey = a[i];
<add> const curVal = a[i + 1];
<add> let j;
<ide> for (j = i - 2; j >= 0; j -= 2) {
<ide> if (a[j] > curKey) {
<ide> a[j + 2] = a[j];
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide> // Bottom-up iterative stable merge sort
<ide> const lBuffer = new Array(len);
<ide> const rBuffer = new Array(len);
<del> for (var step = 2; step < len; step *= 2) {
<del> for (var start = 0; start < len - 2; start += 2 * step) {
<del> var mid = start + step;
<del> var end = mid + step;
<add> for (let step = 2; step < len; step *= 2) {
<add> for (let start = 0; start < len - 2; start += 2 * step) {
<add> const mid = start + step;
<add> let end = mid + step;
<ide> end = end < len ? end : len;
<ide> if (mid > end)
<ide> continue;
<ide> defineIDLClass(URLSearchParams.prototype, 'URLSearchParams', {
<ide>
<ide> let list = this[searchParams];
<ide>
<del> var i = 0;
<add> let i = 0;
<ide> while (i < list.length) {
<ide> const key = list[i];
<ide> const value = list[i + 1];
<ide> const forwardSlashRegEx = /\//g;
<ide>
<ide> function getPathFromURLWin32(url) {
<ide> const hostname = url.hostname;
<del> var pathname = url.pathname;
<del> for (var n = 0; n < pathname.length; n++) {
<add> let pathname = url.pathname;
<add> for (let n = 0; n < pathname.length; n++) {
<ide> if (pathname[n] === '%') {
<del> var third = pathname.codePointAt(n + 2) | 0x20;
<add> const third = pathname.codePointAt(n + 2) | 0x20;
<ide> if ((pathname[n + 1] === '2' && third === 102) || // 2f 2F /
<ide> (pathname[n + 1] === '5' && third === 99)) { // 5c 5C \
<ide> throw new ERR_INVALID_FILE_URL_PATH(
<ide> function getPathFromURLWin32(url) {
<ide> return `\\\\${domainToUnicode(hostname)}${pathname}`;
<ide> } else {
<ide> // Otherwise, it's a local path that requires a drive letter
<del> var letter = pathname.codePointAt(1) | 0x20;
<del> var sep = pathname[2];
<add> const letter = pathname.codePointAt(1) | 0x20;
<add> const sep = pathname[2];
<ide> if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z || // a..z A..Z
<ide> (sep !== ':')) {
<ide> throw new ERR_INVALID_FILE_URL_PATH('must be absolute');
<ide> function getPathFromURLPosix(url) {
<ide> throw new ERR_INVALID_FILE_URL_HOST(platform);
<ide> }
<ide> const pathname = url.pathname;
<del> for (var n = 0; n < pathname.length; n++) {
<add> for (let n = 0; n < pathname.length; n++) {
<ide> if (pathname[n] === '%') {
<del> var third = pathname.codePointAt(n + 2) | 0x20;
<add> const third = pathname.codePointAt(n + 2) | 0x20;
<ide> if (pathname[n + 1] === '2' && third === 102) {
<ide> throw new ERR_INVALID_FILE_URL_PATH(
<ide> 'must not include encoded / characters' | 2 |
Ruby | Ruby | provide file name for fixture erb | 32045717e6bb62d9f3bec6e003dd6c4a74369ae2 | <ide><path>activerecord/lib/active_record/fixture_set/file.rb
<ide> def raw_rows
<ide> end
<ide> end
<ide>
<add> def prepare_erb(content)
<add> erb = ERB.new(content)
<add> erb.filename = @file
<add> erb
<add> end
<add>
<ide> def render(content)
<ide> context = ActiveRecord::FixtureSet::RenderContext.create_subclass.new
<del> ERB.new(content).result(context.get_binding)
<add> prepare_erb(content).result(context.get_binding)
<ide> end
<ide>
<ide> # Validate our unmarshalled data.
<ide><path>activerecord/test/cases/fixture_set/file_test.rb
<ide> def test_extracts_model_class_from_config_row
<ide> end
<ide> end
<ide>
<add> def test_erb_filename
<add> filename = 'filename.yaml'
<add> erb = File.new(filename).send(:prepare_erb, "<% Rails.env %>\n")
<add> assert_equal erb.filename, filename
<add> end
<add>
<ide> private
<ide> def tmp_yaml(name, contents)
<ide> t = Tempfile.new name | 2 |
Ruby | Ruby | remove docker mediatype | 07639e8cebd5c791ab3bee9f6f4802688c3e5fe4 | <ide><path>Library/Homebrew/github_packages.rb
<ide> def write_image_config(platform_hash, tar_sha256, blobs)
<ide>
<ide> def write_image_index(manifests, blobs, annotations)
<ide> image_index = {
<del> # Currently needed for correct multi-arch display in GitHub Packages UI
<del> mediaType: "application/vnd.docker.distribution.manifest.list.v2+json",
<ide> schemaVersion: 2,
<ide> manifests: manifests,
<ide> annotations: annotations, | 1 |
PHP | PHP | use method to detect the application environment | a879fd1428713913bd0d67b2eb7612d1dd4edd19 | <ide><path>src/Illuminate/Console/ConfirmableTrait.php
<ide> public function confirmToProceed($warning = 'Application In Production!', $callb
<ide> protected function getDefaultConfirmCallback()
<ide> {
<ide> return function () {
<del> return $this->getLaravel()->environment() === 'production';
<add> return $this->getLaravel()->isProduction();
<ide> };
<ide> }
<ide> }
<ide><path>src/Illuminate/Foundation/Bootstrap/HandleExceptions.php
<ide> public function bootstrap(Application $app)
<ide>
<ide> register_shutdown_function([$this, 'handleShutdown']);
<ide>
<del> if (! $app->environment('testing')) {
<add> if (! $app->runningUnitTests()) {
<ide> ini_set('display_errors', 'Off');
<ide> }
<ide> } | 2 |
Go | Go | remove /containers/ps from the api router | b5cc077864665290456c5ec724427c1f0d7bc96b | <ide><path>api/server/server.go
<ide> func createRouter(s *Server) *mux.Router {
<ide> "/images/{name:.*}/get": s.getImagesGet,
<ide> "/images/{name:.*}/history": s.getImagesHistory,
<ide> "/images/{name:.*}/json": s.getImagesByName,
<del> "/containers/ps": s.getContainersJSON,
<ide> "/containers/json": s.getContainersJSON,
<ide> "/containers/{name:.*}/export": s.getContainersExport,
<ide> "/containers/{name:.*}/changes": s.getContainersChanges, | 1 |
Ruby | Ruby | fix .subdomain regression | 6b79463ed8d04c7807c0695fcb3d4c11e4be9fa2 | <ide><path>actionpack/lib/action_dispatch/http/url.rb
<ide> def subdomains(tld_length = @@tld_length)
<ide> # such as 2 to catch <tt>["www"]</tt> instead of <tt>"www.rubyonrails"</tt>
<ide> # in "www.rubyonrails.co.uk".
<ide> def subdomain(tld_length = @@tld_length)
<del> subdomains(tld_length)
<add> subdomains(tld_length).join(".")
<ide> end
<ide> end
<ide> end
<ide><path>actionpack/test/dispatch/request_test.rb
<ide> def url_for(options = {})
<ide> test "subdomains" do
<ide> request = stub_request 'HTTP_HOST' => "www.rubyonrails.org"
<ide> assert_equal %w( www ), request.subdomains
<add> assert_equal "www", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => "www.rubyonrails.co.uk"
<ide> assert_equal %w( www ), request.subdomains(2)
<add> assert_equal "www", request.subdomain(2)
<ide>
<ide> request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk"
<ide> assert_equal %w( dev www ), request.subdomains(2)
<add> assert_equal "dev.www", request.subdomain(2)
<ide>
<ide> request = stub_request 'HTTP_HOST' => "dev.www.rubyonrails.co.uk", :tld_length => 2
<ide> assert_equal %w( dev www ), request.subdomains
<add> assert_equal "dev.www", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => "foobar.foobar.com"
<ide> assert_equal %w( foobar ), request.subdomains
<add> assert_equal "foobar", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => "192.168.1.200"
<ide> assert_equal [], request.subdomains
<add> assert_equal "", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => "foo.192.168.1.200"
<ide> assert_equal [], request.subdomains
<add> assert_equal "", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => "192.168.1.200.com"
<ide> assert_equal %w( 192 168 1 ), request.subdomains
<add> assert_equal "192.168.1", request.subdomain
<ide>
<ide> request = stub_request 'HTTP_HOST' => nil
<ide> assert_equal [], request.subdomains
<add> assert_equal "", request.subdomain
<ide> end
<ide>
<ide> test "standard_port" do | 2 |
Python | Python | use tuple, not a list | 0ac17ff5a770142cb1433a9ef4f019e5a6a605b2 | <ide><path>libcloud/compute/ssh.py
<ide>
<ide> PARAMIKO_VERSION_TUPLE = tuple([int(x) for x in paramiko.__version__.split(".")])
<ide> except ImportError:
<del> PARAMIKO_VERSION_TUPLE = []
<add> PARAMIKO_VERSION_TUPLE = ()
<ide>
<ide> # Depending on your version of Paramiko, it may cause a deprecation
<ide> # warning on Python 2.6. | 1 |
PHP | PHP | remove celltrait from controller | 0e90bbfe8c4ce2903f8c83057152b7fc97a84ee8 | <ide><path>src/Controller/Controller.php
<ide> use Cake\Routing\Router;
<ide> use Cake\Utility\Inflector;
<ide> use Cake\Utility\MergeVariablesTrait;
<del>use Cake\View\CellTrait;
<ide> use Cake\View\View;
<ide> use Cake\View\ViewVarsTrait;
<ide>
<ide> */
<ide> class Controller implements EventListener {
<ide>
<del> use CellTrait;
<ide> use LogTrait;
<ide> use MergeVariablesTrait;
<ide> use ModelAwareTrait; | 1 |
Javascript | Javascript | add $provide.service() for registering a class | 0bfaa579c04d1b7cd21fbe16bfbc47a684f223b3 | <ide><path>src/Injector.js
<ide> function inferInjectionArgs(fn) {
<ide> *
<ide> * A short hand for configuring services if only `$get` method is required.
<ide> *
<del> * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
<add> * @param {string} name The name of the instance.
<ide> * @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand for
<ide> * `$provide.provider(name, {$get: $getFn})`.
<ide> * @returns {Object} registered provider instance
<ide> */
<ide>
<ide>
<add>/**
<add> * @ngdoc method
<add> * @name angular.module.AUTO.$provide#service
<add> * @methodOf angular.module.AUTO.$provide
<add> * @description
<add> *
<add> * A short hand for registering service of given class.
<add> *
<add> * @param {string} name The name of the instance.
<add> * @param {Function} constructor A class (constructor function) that will be instantiated.
<add> * @returns {Object} registered provider instance
<add> */
<add>
<add>
<ide> /**
<ide> * @ngdoc method
<ide> * @name angular.module.AUTO.$provide#value
<ide> function inferInjectionArgs(fn) {
<ide> *
<ide> * A short hand for configuring services if the `$get` method is a constant.
<ide> *
<del> * @param {string} name The name of the instance. NOTE: the provider will be available under `name + 'Provider'` key.
<add> * @param {string} name The name of the instance.
<ide> * @param {*} value The value.
<ide> * @returns {Object} registered provider instance
<ide> */
<ide> function createInjector(modulesToLoad) {
<ide> $provide: {
<ide> provider: supportObject(provider),
<ide> factory: supportObject(factory),
<add> service: supportObject(service),
<ide> value: supportObject(value),
<ide> constant: supportObject(constant),
<ide> decorator: decorator
<ide> function createInjector(modulesToLoad) {
<ide>
<ide> function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
<ide>
<add> function service(name, constructor) {
<add> return factory(name, ['$injector', function($injector) {
<add> return $injector.instantiate(constructor);
<add> }]);
<add> }
<add>
<ide> function value(name, value) { return factory(name, valueFn(value)); }
<ide>
<ide> function constant(name, value) {
<ide><path>src/loader.js
<ide> function setupModuleLoader(window) {
<ide> * @param {string} name service name
<ide> * @param {Function} providerFunction Function for creating new instance of the service.
<ide> * @description
<del> * See {@link angular.module.AUTO.$provide#service $provide.factory()}.
<add> * See {@link angular.module.AUTO.$provide#factory $provide.factory()}.
<ide> */
<ide> factory: invokeLater('$provide', 'factory'),
<ide>
<add> /**
<add> * @ngdoc method
<add> * @name angular.Module#service
<add> * @methodOf angular.Module
<add> * @param {string} name service name
<add> * @param {Function} constructor A constructor function that will be instantiated.
<add> * @description
<add> * See {@link angular.module.AUTO.$provide#service $provide.service()}.
<add> */
<add> service: invokeLater('$provide', 'service'),
<add>
<ide> /**
<ide> * @ngdoc method
<ide> * @name angular.Module#value
<ide><path>test/InjectorSpec.js
<ide> describe('injector', function() {
<ide> });
<ide>
<ide>
<add> describe('service', function() {
<add> it('should register a class', function() {
<add> var Type = function(value) {
<add> this.value = value;
<add> };
<add>
<add> var instance = createInjector([function($provide) {
<add> $provide.value('value', 123);
<add> $provide.service('foo', Type);
<add> }]).get('foo');
<add>
<add> expect(instance instanceof Type).toBe(true);
<add> expect(instance.value).toBe(123);
<add> });
<add>
<add>
<add> it('should register a set of classes', function() {
<add> var Type = function() {};
<add>
<add> var injector = createInjector([function($provide) {
<add> $provide.service({
<add> foo: Type,
<add> bar: Type
<add> });
<add> }]);
<add>
<add> expect(injector.get('foo') instanceof Type).toBe(true);
<add> expect(injector.get('bar') instanceof Type).toBe(true);
<add> });
<add> });
<add>
<add>
<ide> describe('provider', function() {
<ide> it('should configure $provide provider object', function() {
<ide> expect(createInjector([function($provide) {
<ide><path>test/loaderSpec.js
<ide> describe('module loader', function() {
<ide> expect(myModule.
<ide> provider('sk', 'sv').
<ide> factory('fk', 'fv').
<add> service('a', 'aa').
<ide> value('k', 'v').
<ide> filter('f', 'ff').
<ide> directive('d', 'dd').
<ide> describe('module loader', function() {
<ide> ['$injector', 'invoke', ['config'] ],
<ide> ['$provide', 'provider', ['sk', 'sv'] ],
<ide> ['$provide', 'factory', ['fk', 'fv'] ],
<add> ['$provide', 'service', ['a', 'aa'] ],
<ide> ['$provide', 'value', ['k', 'v'] ],
<ide> ['$filterProvider', 'register', ['f', 'ff'] ],
<ide> ['$compileProvider', 'directive', ['d', 'dd'] ], | 4 |
Go | Go | identify tty correctly, fix resize problem | 0532dcf3dc1fa34fab5a9cdee6c4d87af66a6cdf | <ide><path>pkg/term/winconsole/console_windows.go
<ide> func StdStreams() (stdIn io.ReadCloser, stdOut io.Writer, stdErr io.Writer) {
<ide> }
<ide> handler.screenBufferInfo = screenBufferInfo
<ide>
<del> // Set the window size
<del> SetWindowSize(stdoutHandle, DEFAULT_WIDTH, DEFAULT_HEIGHT, DEFAULT_HEIGHT)
<ide> buffer = make([]CHAR_INFO, screenBufferInfo.MaximumWindowSize.X*screenBufferInfo.MaximumWindowSize.Y)
<ide>
<ide> stdOut = &terminalWriter{
<ide> func GetHandleInfo(in interface{}) (uintptr, bool) {
<ide> isTerminalIn = IsTerminal(inFd)
<ide> }
<ide> }
<add> if tr, ok := in.(*terminalWriter); ok {
<add> if file, ok := tr.wrappedWriter.(*os.File); ok {
<add> inFd = file.Fd()
<add> isTerminalIn = IsTerminal(inFd)
<add> }
<add> }
<ide> return inFd, isTerminalIn
<ide> }
<ide> | 1 |
Ruby | Ruby | add test for cookie being modified by rotation | 36b25aa1c4863cc70c74fd783fb54ba44a3a128e | <ide><path>actionpack/test/dispatch/cookies_test.rb
<ide> def test_encrypted_cookie_rotating_secret
<ide> assert_equal 45, encryptor.decrypt_and_verify(@response.cookies["foo"])
<ide> end
<ide>
<add> def test_cookie_with_hash_value_not_modified_by_rotation
<add> @request.env["action_dispatch.signed_cookie_digest"] = "SHA256"
<add> @request.env["action_dispatch.cookies_rotations"].rotate :signed, digest: "SHA1"
<add>
<add> key_generator = @request.env["action_dispatch.key_generator"]
<add> old_secret = key_generator.generate_key(@request.env["action_dispatch.signed_cookie_salt"])
<add> old_value = ActiveSupport::MessageVerifier.new(old_secret).generate(bar: "baz")
<add>
<add> @request.headers["Cookie"] = "foo=#{old_value}"
<add> get :get_signed_cookie
<add> assert_equal({ bar: "baz" }, @controller.send(:cookies).signed[:foo])
<add> end
<add>
<ide> def test_cookie_with_all_domain_option
<ide> get :set_cookie_with_domain
<ide> assert_response :success | 1 |
PHP | PHP | remove default options from scriptstart() | 0a2158ef5c3437c36248ce4221e7297e4b2d0643 | <ide><path>src/View/Helper/HtmlHelper.php
<ide> public function scriptBlock($script, array $options = [])
<ide> *
<ide> * ### Options
<ide> *
<del> * - `safe` Whether the code block should contain a CDATA
<add> * - `safe` (boolean) Whether or not the $script should be wrapped in `<![CDATA[ ]]>`.
<add> * See scriptBlock().
<ide> * - `block` Set to true to append output to view block "script" or provide
<ide> * custom block name.
<ide> *
<ide> public function scriptBlock($script, array $options = [])
<ide> */
<ide> public function scriptStart(array $options = [])
<ide> {
<del> $options += ['safe' => true, 'block' => null];
<ide> $this->_scriptBlockOptions = $options;
<ide> ob_start();
<ide> } | 1 |
PHP | PHP | use boolean for switch conditions sort and verbose | e7c82062da0401ced0bf2a168dd6493503d6b945 | <ide><path>src/Command/RoutesCommand.php
<ide> public function execute(Arguments $args, ConsoleIo $io): ?int
<ide> $methods,
<ide> ];
<ide>
<del> if ($args->getOption('verbose') !== null) {
<add> if ($args->getOption('verbose') === true) {
<ide> ksort($route->defaults);
<ide> $item[] = json_encode($route->defaults);
<ide> }
<ide>
<ide> $output[] = $item;
<ide> }
<ide>
<del> if ($args->getOption('sort') !== null) {
<add> if ($args->getOption('sort') === true) {
<ide> usort($output, function ($a, $b) {
<ide> return strcasecmp($a[0], $b[0]);
<ide> });
<ide> public function buildOptionParser(ConsoleOptionParser $parser): ConsoleOptionPar
<ide> ->addOption('sort', [
<ide> 'help' => 'Sorts alphabetically by route name A-Z',
<ide> 'short' => 's',
<add> 'boolean' => true,
<ide> ]);
<ide>
<ide> return $parser; | 1 |
Text | Text | add section of ci builds | 1ee9223348c81c903a1d53d3378032beb16c3cbe | <ide><path>README.md
<ide> See the [Micro-Benchmarks](https://github.com/spring-projects/spring-framework/w
<ide>
<ide> See the [Build from Source](https://github.com/spring-projects/spring-framework/wiki/Build-from-Source) Wiki page and the [CONTRIBUTING.md](CONTRIBUTING.md) file.
<ide>
<add>## Continuous Integration Builds
<add>
<add>Information regarding CI builds can be found in the [Spring Framework Concourse pipeline](ci/README.adoc) documentation.
<add>
<ide> ## Stay in Touch
<ide>
<ide> Follow [@SpringCentral](https://twitter.com/springcentral), [@SpringFramework](https://twitter.com/springframework), and its [team members](https://twitter.com/springframework/lists/team/members) on Twitter. In-depth articles can be found at [The Spring Blog](https://spring.io/blog/), and releases are announced via our [news feed](https://spring.io/blog/category/news). | 1 |
Javascript | Javascript | minimize allocation of imperative functions | 7bcc6f9b4dd2f973d8439c07e836e867f3662eb7 | <ide><path>Libraries/Components/TextInput/TextInput.js
<ide> function InternalTextInput(props: Props): React.Node {
<ide> }
<ide> }, [inputRef]);
<ide>
<del> function clear(): void {
<del> if (inputRef.current != null) {
<del> viewCommands.setTextAndSelection(
<del> inputRef.current,
<del> mostRecentEventCount,
<del> '',
<del> 0,
<del> 0,
<del> );
<del> }
<del> }
<del>
<del> function setSelection(start: number, end: number): void {
<del> if (inputRef.current != null) {
<del> viewCommands.setTextAndSelection(
<del> inputRef.current,
<del> mostRecentEventCount,
<del> null,
<del> start,
<del> end,
<del> );
<add> const setLocalRef = (ref: TextInputInstance | null) => {
<add> inputRef.current = ref;
<add>
<add> /*
<add> Hi reader from the future. I'm sorry for this.
<add>
<add> This is a hack. Ideally we would forwardRef to the underlying
<add> host component. However, since TextInput has it's own methods that can be
<add> called as well, if we used the standard forwardRef then these
<add> methods wouldn't be accessible and thus be a breaking change.
<add>
<add> We have a couple of options of how to handle this:
<add> - Return a new ref with everything we methods from both. This is problematic
<add> because we need React to also know it is a host component which requires
<add> internals of the class implementation of the ref.
<add> - Break the API and have some other way to call one set of the methods or
<add> the other. This is our long term approach as we want to eventually
<add> get the methods on host components off the ref. So instead of calling
<add> ref.measure() you might call ReactNative.measure(ref). This would hopefully
<add> let the ref for TextInput then have the methods like `.clear`. Or we do it
<add> the other way and make it TextInput.clear(textInputRef) which would be fine
<add> too. Either way though is a breaking change that is longer term.
<add> - Mutate this ref. :( Gross, but accomplishes what we need in the meantime
<add> before we can get to the long term breaking change.
<add> */
<add> if (ref != null) {
<add> // $FlowFixMe[incompatible-use] - See the explanation above.
<add> Object.assign(ref, {
<add> clear(): void {
<add> if (inputRef.current != null) {
<add> viewCommands.setTextAndSelection(
<add> inputRef.current,
<add> mostRecentEventCount,
<add> '',
<add> 0,
<add> 0,
<add> );
<add> }
<add> },
<add> // TODO: Fix this returning true on null === null, when no input is focused
<add> isFocused(): boolean {
<add> return TextInputState.currentlyFocusedInput() === inputRef.current;
<add> },
<add> getNativeRef(): ?React.ElementRef<HostComponent<mixed>> {
<add> return inputRef.current;
<add> },
<add> setSelection(start: number, end: number): void {
<add> if (inputRef.current != null) {
<add> viewCommands.setTextAndSelection(
<add> inputRef.current,
<add> mostRecentEventCount,
<add> null,
<add> start,
<add> end,
<add> );
<add> }
<add> },
<add> });
<ide> }
<del> }
<del>
<del> // TODO: Fix this returning true on null === null, when no input is focused
<del> function isFocused(): boolean {
<del> return TextInputState.currentlyFocusedInput() === inputRef.current;
<del> }
<del>
<del> function getNativeRef(): ?React.ElementRef<HostComponent<mixed>> {
<del> return inputRef.current;
<del> }
<add> };
<ide>
<ide> const _setNativeRef = setAndForwardRef({
<ide> getForwardedRef: () => props.forwardedRef,
<del> setLocalRef: ref => {
<del> inputRef.current = ref;
<del>
<del> /*
<del> Hi reader from the future. I'm sorry for this.
<del>
<del> This is a hack. Ideally we would forwardRef to the underlying
<del> host component. However, since TextInput has it's own methods that can be
<del> called as well, if we used the standard forwardRef then these
<del> methods wouldn't be accessible and thus be a breaking change.
<del>
<del> We have a couple of options of how to handle this:
<del> - Return a new ref with everything we methods from both. This is problematic
<del> because we need React to also know it is a host component which requires
<del> internals of the class implementation of the ref.
<del> - Break the API and have some other way to call one set of the methods or
<del> the other. This is our long term approach as we want to eventually
<del> get the methods on host components off the ref. So instead of calling
<del> ref.measure() you might call ReactNative.measure(ref). This would hopefully
<del> let the ref for TextInput then have the methods like `.clear`. Or we do it
<del> the other way and make it TextInput.clear(textInputRef) which would be fine
<del> too. Either way though is a breaking change that is longer term.
<del> - Mutate this ref. :( Gross, but accomplishes what we need in the meantime
<del> before we can get to the long term breaking change.
<del> */
<del> if (ref != null) {
<del> Object.assign(ref, {
<del> clear,
<del> isFocused,
<del> getNativeRef,
<del> setSelection,
<del> });
<del> }
<del> },
<add> setLocalRef,
<ide> });
<ide>
<ide> const _onChange = (event: ChangeEvent) => { | 1 |
Text | Text | fix typo in networking.md | cbdce9912d9f904b237e29dd2a1196367337628b | <ide><path>docs/sources/articles/networking.md
<ide> bridge* that automatically forwards packets between any other network
<ide> interfaces that are attached to it. This lets containers communicate
<ide> both with the host machine and with each other. Every time Docker
<ide> creates a container, it creates a pair of “peer” interfaces that are
<del>like opposite ends of a pipe — a packet send on one will be received on
<add>like opposite ends of a pipe — a packet sent on one will be received on
<ide> the other. It gives one of the peers to the container to become its
<ide> `eth0` interface and keeps the other peer, with a unique name like
<ide> `vethAQI2QT`, out in the namespace of the host machine. By binding | 1 |
Java | Java | simplify some control flow code | 87f28ce48ebc672ffaea31f9524a6e770a01aa1f | <ide><path>spring-web/src/main/java/org/springframework/web/bind/support/WebRequestDataBinder.java
<ide> public void bind(WebRequest request) {
<ide> */
<ide> private boolean isMultipartRequest(WebRequest request) {
<ide> String contentType = request.getHeader("Content-Type");
<del> return (contentType != null && StringUtils.startsWithIgnoreCase(contentType, "multipart"));
<add> return StringUtils.startsWithIgnoreCase(contentType, "multipart");
<ide> }
<ide>
<ide> private void bindParts(HttpServletRequest request, MutablePropertyValues mpvs) {
<ide><path>spring-web/src/main/java/org/springframework/web/util/pattern/RegexPathElement.java
<ide> public boolean matches(int pathIndex, MatchingContext matchingContext) {
<ide> if (matches) {
<ide> if (isNoMorePattern()) {
<ide> if (matchingContext.determineRemainingPath &&
<del> (this.variableNames.isEmpty() ? true : textToMatch.length() > 0)) {
<add> (this.variableNames.isEmpty() || textToMatch.length() > 0)) {
<ide> matchingContext.remainingPathIndex = pathIndex + 1;
<ide> matches = true;
<ide> } | 2 |
Ruby | Ruby | use tap abstraction | b52af53e711d442f2b7097a449a6c077664eb7f3 | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> require "extend/ENV"
<ide> require "formula_cellar_checks"
<ide> require "official_taps"
<del>require "tap_migrations"
<ide> require "cmd/search"
<ide> require "date"
<del>require "formula_renames"
<ide>
<ide> module Homebrew
<ide> def audit
<ide> def audit_caveats
<ide> end
<ide>
<ide> def audit_reverse_migration
<del> # Only enforce for new formula being re-added to core
<add> # Only enforce for new formula being re-added to core and official taps
<ide> return unless @strict
<del> return unless formula.core_formula?
<add> return unless formula.tap && formula.tap.official?
<ide>
<del> if TAP_MIGRATIONS.key?(formula.name)
<add> if formula.tap.tap_migrations.key?(formula.name)
<ide> problem <<-EOS.undent
<ide> #{formula.name} seems to be listed in tap_migrations.rb!
<ide> Please remove #{formula.name} from present tap & tap_migrations.rb
<ide><path>Library/Homebrew/cmd/migrate.rb
<ide> require "migrator"
<del>require "formula_renames"
<ide>
<ide> module Homebrew
<ide> def migrate
<ide><path>Library/Homebrew/formula.rb
<ide> require "pkg_version"
<ide> require "tap"
<ide> require "core_formula_repository"
<del>require "formula_renames"
<ide> require "keg"
<ide> require "migrator"
<ide>
<ide><path>Library/Homebrew/formulary.rb
<ide> require "digest/md5"
<del>require "formula_renames"
<ide> require "tap"
<ide> require "core_formula_repository"
<ide>
<ide><path>Library/Homebrew/migrator.rb
<ide> require "formula_lock"
<ide> require "keg"
<ide> require "tab"
<del>require "tap_migrations"
<ide>
<ide> class Migrator
<ide> class MigrationNeededError < RuntimeError
<ide> def from_same_taps?
<ide> if formula.tap == old_tap
<ide> true
<ide> # Homebrew didn't use to update tabs while performing tap-migrations,
<del> # so there can be INSTALL_RECEIPT's containing wrong information about
<del> # tap (tap is Homebrew/homebrew if installed formula migrates to a tap), so
<del> # we check if there is an entry about oldname migrated to tap and if
<add> # so there can be INSTALL_RECEIPT's containing wrong information about tap,
<add> # so we check if there is an entry about oldname migrated to tap and if
<ide> # newname's tap is the same as tap to which oldname migrated, then we
<ide> # can perform migrations and the taps for oldname and newname are the same.
<del> elsif TAP_MIGRATIONS && (rec = TAP_MIGRATIONS[formula.oldname]) \
<del> && formula.tap == rec && old_tap == "Homebrew/homebrew"
<add> elsif formula.tap && old_tap && formula.tap == old_tap.tap_migrations[formula.oldname]
<ide> fix_tabs
<ide> true
<ide> else | 5 |
Go | Go | fix issue with mkdir within docker build | 9a394041270d2a8ba648f215dacc186473140552 | <ide><path>buildfile.go
<ide> func (b *buildFile) CmdAdd(args string) error {
<ide> origPath := path.Join(b.context, orig)
<ide> destPath := path.Join(container.RootfsPath(), dest)
<ide>
<del> if err := os.MkdirAll(path.Dir(destPath), 0700); err != nil {
<del> return err
<del> }
<del>
<ide> fi, err := os.Stat(origPath)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> if fi.IsDir() {
<add> if err := os.MkdirAll(destPath, 0700); err != nil {
<add> return err
<add> }
<add>
<ide> files, err := ioutil.ReadDir(path.Join(b.context, orig))
<ide> if err != nil {
<ide> return err
<ide> func (b *buildFile) CmdAdd(args string) error {
<ide> }
<ide> }
<ide> } else {
<add> if err := os.MkdirAll(path.Dir(destPath), 0700); err != nil {
<add> return err
<add> }
<ide> if err := utils.CopyDirectory(origPath, destPath); err != nil {
<ide> return err
<ide> } | 1 |
Python | Python | fix typo in schemas | 0f5dfe8b3cc8a635208b1e24aa27eb465d4fb5ab | <ide><path>rest_framework/schemas/generators.py
<ide> def is_api_view(callback):
<ide> coreapi.Link for URL path {value_url} cannot be inserted into schema.
<ide> Position conflicts with coreapi.Link for URL path {target_url}.
<ide>
<del>Attemped to insert link with keys: {keys}.
<add>Attempted to insert link with keys: {keys}.
<ide>
<ide> Adjust URLs to avoid naming collision or override `SchemaGenerator.get_keys()`
<ide> to customise schema structure.
<ide><path>rest_framework/schemas/inspectors.py
<ide> def __set__(self, instance, other):
<ide> @property
<ide> def view(self):
<ide> """View property."""
<del> assert self._view is not None, "Schema generation REQUIRES a view instance. (Hint: you accessed `schema` from the view class rather than an instance.)"
<add> assert self._view is not None, (
<add> "Schema generation REQUIRES a view instance. (Hint: you accessed "
<add> "`schema` from the view class rather than an instance.)"
<add> )
<ide> return self._view
<ide>
<ide> @view.setter
<ide> class AutoSchema(ViewInspector):
<ide> """
<ide> Default inspector for APIView
<ide>
<del> Responsible for per-view instrospection and schema generation.
<add> Responsible for per-view introspection and schema generation.
<ide> """
<ide> def __init__(self, manual_fields=None):
<ide> """
<ide> def __init__(self, fields, description='', encoding=None):
<ide> Parameters:
<ide>
<ide> * `fields`: list of `coreapi.Field` instances.
<del> * `descripton`: String description for view. Optional.
<add> * `description`: String description for view. Optional.
<ide> """
<ide> super(ManualSchema, self).__init__()
<ide> assert all(isinstance(f, coreapi.Field) for f in fields), "`fields` must be a list of coreapi.Field instances"
<ide> def __get__(self, instance, owner):
<ide> return result
<ide>
<ide> inspector_class = api_settings.DEFAULT_SCHEMA_CLASS
<del> assert issubclass(inspector_class, ViewInspector), "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass"
<add> assert issubclass(inspector_class, ViewInspector), (
<add> "DEFAULT_SCHEMA_CLASS must be set to a ViewInspector (usually an AutoSchema) subclass"
<add> )
<ide> inspector = inspector_class()
<ide> inspector.view = instance
<ide> return inspector | 2 |
Text | Text | add a "tip" section to the article | 8e4b2795ab644be4be357c7ace118548c1b11114 | <ide><path>guide/english/bash/bash-cat/index.md
<ide> title: Bash Cat
<ide>
<ide> ## Bash Cat
<ide>
<del>Cat is one of the most frequently used commands in Unix operating systems.
<add>`cat` is one of the most frequently used commands in Unix operating systems.
<ide>
<del>Cat is used to read a file sequentially and print it to the standard output.
<add>`cat` is used to read a file sequentially and print it to the standard output.
<ide> The name is derived from its function to con**cat**enate files.
<ide>
<ide> ### Usage
<ide> Concatenate the content of the two files and display the result in terminal:
<ide> cat file1.txt file2.txt
<ide> ```
<ide>
<add>**Tip**: Using `cat` on a directory will cause error, so make sure it's a readable file.
<add>
<ide> #### More Information:
<ide> * Wikipedia: https://en.wikipedia.org/wiki/Cat_(Unix)
<add>
<add> | 1 |
Python | Python | improve test coverage for complex fpe cast errors | b463a7fcee642eb75ec7fd5faa33f3fabbcfb258 | <ide><path>numpy/core/tests/test_casting_floatingpoint_errors.py
<ide> def values_and_dtypes():
<ide> yield param(np.finfo(np.longdouble).max, "float64",
<ide> id="longdouble-to-f8")
<ide>
<add> # Cast to complex32:
<add> yield param(2e300, "complex64", id="float-to-c8")
<add> yield param(2e300+0j, "complex64", id="complex-to-c8")
<add> yield param(2e300j, "complex64", id="complex-to-c8")
<add> yield param(np.longdouble(2e300), "complex64", id="longdouble-to-c8")
<add>
<ide> # Invalid float to integer casts:
<ide> with np.errstate(over="ignore"):
<ide> for to_dt in np.typecodes["AllInteger"]: | 1 |
Python | Python | fix indent and improve error message | 9bc0bc308b86bcd3ad8da1154f1c4807d9288ae6 | <ide><path>keras/layers/convolutional.py
<ide> def call(self, inputs):
<ide> if self.data_format == 'channels_first':
<ide> if ((inputs.shape[2] is not None and sum(self.cropping[0]) >= inputs.shape[2]) or
<ide> (inputs.shape[3] is not None and sum(self.cropping[1]) >= inputs.shape[3])):
<del> raise ValueError('cropping parameter of Cropping layer must be '
<del> 'greater than the input shape. Received: inputs.shape='
<del> f'{inputs.shape}, and cropping={self.cropping}')
<add> raise ValueError('Argument `cropping` must be '
<add> 'greater than the input shape. Received: inputs.shape='
<add> f'{inputs.shape}, and cropping={self.cropping}')
<ide> if self.cropping[0][1] == self.cropping[1][1] == 0:
<ide> return inputs[:, :, self.cropping[0][0]:, self.cropping[1][0]:]
<ide> elif self.cropping[0][1] == 0:
<ide> def call(self, inputs):
<ide> else:
<ide> if ((inputs.shape[1] is not None and sum(self.cropping[0]) >= inputs.shape[1]) or
<ide> (inputs.shape[2] is not None and sum(self.cropping[1]) >= inputs.shape[2])):
<del> raise ValueError('cropping parameter of Cropping layer must be '
<del> 'greater than the input shape. Received: inputs.shape='
<del> f'{inputs.shape}, and cropping={self.cropping}')
<add> raise ValueError('Argument `cropping` must be '
<add> 'greater than the input shape. Received: inputs.shape='
<add> f'{inputs.shape}, and cropping={self.cropping}')
<ide> if self.cropping[0][1] == self.cropping[1][1] == 0:
<ide> return inputs[:, self.cropping[0][0]:, self.cropping[1][0]:, :]
<ide> elif self.cropping[0][1] == 0: | 1 |
Java | Java | add materialize() and dematerialize() | bc9d59441c189ede38b986ba9839017719126f37 | <ide><path>src/main/java/io/reactivex/Completable.java
<ide> import io.reactivex.internal.operators.completable.*;
<ide> import io.reactivex.internal.operators.maybe.*;
<ide> import io.reactivex.internal.operators.mixed.*;
<del>import io.reactivex.internal.operators.single.SingleDelayWithCompletable;
<add>import io.reactivex.internal.operators.single.*;
<ide> import io.reactivex.internal.util.ExceptionHelper;
<ide> import io.reactivex.observers.TestObserver;
<ide> import io.reactivex.plugins.RxJavaPlugins;
<ide> public final Completable lift(final CompletableOperator onLift) {
<ide> return RxJavaPlugins.onAssembly(new CompletableLift(this, onLift));
<ide> }
<ide>
<add> /**
<add> * Maps the signal types of this Completable into a {@link Notification} of the same kind
<add> * and emits it as a single success value to downstream.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @param <T> the intended target element type of the notification
<add> * @return the new Single instance
<add> * @since 2.2.4 - experimental
<add> * @see Single#dematerialize(Function)
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final <T> Single<Notification<T>> materialize() {
<add> return RxJavaPlugins.onAssembly(new CompletableMaterialize<T>(this));
<add> }
<add>
<ide> /**
<ide> * Returns a Completable which subscribes to this and the other Completable and completes
<ide> * when both of them complete or one emits an error.
<ide><path>src/main/java/io/reactivex/Maybe.java
<ide> public final <R> Maybe<R> map(Function<? super T, ? extends R> mapper) {
<ide> return RxJavaPlugins.onAssembly(new MaybeMap<T, R>(this, mapper));
<ide> }
<ide>
<add> /**
<add> * Maps the signal types of this Maybe into a {@link Notification} of the same kind
<add> * and emits it as a single success value to downstream.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @return the new Single instance
<add> * @since 2.2.4 - experimental
<add> * @see Single#dematerialize(Function)
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Single<Notification<T>> materialize() {
<add> return RxJavaPlugins.onAssembly(new MaybeMaterialize<T>(this));
<add> }
<add>
<ide> /**
<ide> * Flattens this and another Maybe into a single Flowable, without any transformation.
<ide> * <p>
<ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> delaySubscription(long time, TimeUnit unit, Scheduler sch
<ide> return delaySubscription(Observable.timer(time, unit, scheduler));
<ide> }
<ide>
<add> /**
<add> * Maps the {@link Notification} success value of this Single back into normal
<add> * {@code onSuccess}, {@code onError} or {@code onComplete} signals as a
<add> * {@link Maybe} source.
<add> * <p>
<add> * The intended use of the {@code selector} function is to perform a
<add> * type-safe identity mapping (see example) on a source that is already of type
<add> * {@code Notification<T>}. The Java language doesn't allow
<add> * limiting instance methods to a certain generic argument shape, therefore,
<add> * a function is used to ensure the conversion remains type safe.
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code dematerialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * <p>
<add> * Example:
<add> * <pre><code>
<add> * Single.just(Notification.createOnNext(1))
<add> * .dematerialize(notification -> notification)
<add> * .test()
<add> * .assertResult(1);
<add> * </code></pre>
<add> * @param <R> the result type
<add> * @param selector the function called with the success item and should
<add> * return a {@link Notification} instance.
<add> * @return the new Maybe instance
<add> * @since 2.2.4 - experimental
<add> * @see #materialize()
<add> */
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> @Experimental
<add> public final <R> Maybe<R> dematerialize(Function<? super T, Notification<R>> selector) {
<add> ObjectHelper.requireNonNull(selector, "selector is null");
<add> return RxJavaPlugins.onAssembly(new SingleDematerialize<T, R>(this, selector));
<add> }
<add>
<ide> /**
<ide> * Calls the specified consumer with the success item after this item has been emitted to the downstream.
<ide> * <p>
<ide> public final <R> Single<R> map(Function<? super T, ? extends R> mapper) {
<ide> return RxJavaPlugins.onAssembly(new SingleMap<T, R>(this, mapper));
<ide> }
<ide>
<add> /**
<add> * Maps the signal types of this Single into a {@link Notification} of the same kind
<add> * and emits it as a single success value to downstream.
<add> * <p>
<add> * <img width="640" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/materialize.png" alt="">
<add> * <dl>
<add> * <dt><b>Scheduler:</b></dt>
<add> * <dd>{@code materialize} does not operate by default on a particular {@link Scheduler}.</dd>
<add> * </dl>
<add> * @return the new Single instance
<add> * @since 2.2.4 - experimental
<add> * @see #dematerialize(Function)
<add> */
<add> @Experimental
<add> @CheckReturnValue
<add> @SchedulerSupport(SchedulerSupport.NONE)
<add> public final Single<Notification<T>> materialize() {
<add> return RxJavaPlugins.onAssembly(new SingleMaterialize<T>(this));
<add> }
<add>
<ide> /**
<ide> * Signals true if the current Single signals a success value that is Object-equals with the value
<ide> * provided.
<ide><path>src/main/java/io/reactivex/internal/operators/completable/CompletableMaterialize.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.completable;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.internal.operators.mixed.MaterializeSingleObserver;
<add>
<add>/**
<add> * Turn the signal types of a Completable source into a single Notification of
<add> * equal kind.
<add> *
<add> * @param <T> the element type of the source
<add> * @since 2.2.4 - experimental
<add> */
<add>@Experimental
<add>public final class CompletableMaterialize<T> extends Single<Notification<T>> {
<add>
<add> final Completable source;
<add>
<add> public CompletableMaterialize(Completable source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Notification<T>> observer) {
<add> source.subscribe(new MaterializeSingleObserver<T>(observer));
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/maybe/MaybeMaterialize.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.internal.operators.mixed.MaterializeSingleObserver;
<add>
<add>/**
<add> * Turn the signal types of a Maybe source into a single Notification of
<add> * equal kind.
<add> *
<add> * @param <T> the element type of the source
<add> * @since 2.2.4 - experimental
<add> */
<add>@Experimental
<add>public final class MaybeMaterialize<T> extends Single<Notification<T>> {
<add>
<add> final Maybe<T> source;
<add>
<add> public MaybeMaterialize(Maybe<T> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Notification<T>> observer) {
<add> source.subscribe(new MaterializeSingleObserver<T>(observer));
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/mixed/MaterializeSingleObserver.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.mixed;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>
<add>/**
<add> * A consumer that implements the consumer types of Maybe, Single and Completable
<add> * and turns their signals into Notifications for a SingleObserver.
<add> * @param <T> the element type of the source
<add> * @since 2.2.4 - experimental
<add> */
<add>@Experimental
<add>public final class MaterializeSingleObserver<T>
<add>implements SingleObserver<T>, MaybeObserver<T>, CompletableObserver, Disposable {
<add>
<add> final SingleObserver<? super Notification<T>> downstream;
<add>
<add> Disposable upstream;
<add>
<add> public MaterializeSingleObserver(SingleObserver<? super Notification<T>> downstream) {
<add> this.downstream = downstream;
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.validate(upstream, d)) {
<add> this.upstream = d;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onComplete() {
<add> downstream.onSuccess(Notification.<T>createOnComplete());
<add> }
<add>
<add> @Override
<add> public void onSuccess(T t) {
<add> downstream.onSuccess(Notification.<T>createOnNext(t));
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> downstream.onSuccess(Notification.<T>createOnError(e));
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return upstream.isDisposed();
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> upstream.dispose();
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleDematerialize.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.disposables.Disposable;
<add>import io.reactivex.exceptions.Exceptions;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.disposables.DisposableHelper;
<add>import io.reactivex.internal.functions.ObjectHelper;
<add>
<add>/**
<add> * Maps the success value of the source to a Notification, then
<add> * maps it back to the corresponding signal type.
<add> * @param <T> the element type of the source
<add> * @param <R> the element type of the Notification and result
<add> * @since 2.2.4 - experimental
<add> */
<add>@Experimental
<add>public final class SingleDematerialize<T, R> extends Maybe<R> {
<add>
<add> final Single<T> source;
<add>
<add> final Function<? super T, Notification<R>> selector;
<add>
<add> public SingleDematerialize(Single<T> source, Function<? super T, Notification<R>> selector) {
<add> this.source = source;
<add> this.selector = selector;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(MaybeObserver<? super R> observer) {
<add> source.subscribe(new DematerializeObserver<T, R>(observer, selector));
<add> }
<add>
<add> static final class DematerializeObserver<T, R> implements SingleObserver<T>, Disposable {
<add>
<add> final MaybeObserver<? super R> downstream;
<add>
<add> final Function<? super T, Notification<R>> selector;
<add>
<add> Disposable upstream;
<add>
<add> DematerializeObserver(MaybeObserver<? super R> downstream,
<add> Function<? super T, Notification<R>> selector) {
<add> this.downstream = downstream;
<add> this.selector = selector;
<add> }
<add>
<add> @Override
<add> public void dispose() {
<add> upstream.dispose();
<add> }
<add>
<add> @Override
<add> public boolean isDisposed() {
<add> return upstream.isDisposed();
<add> }
<add>
<add> @Override
<add> public void onSubscribe(Disposable d) {
<add> if (DisposableHelper.validate(upstream, d)) {
<add> upstream = d;
<add> downstream.onSubscribe(this);
<add> }
<add> }
<add>
<add> @Override
<add> public void onSuccess(T t) {
<add> Notification<R> notification;
<add>
<add> try {
<add> notification = ObjectHelper.requireNonNull(selector.apply(t), "The selector returned a null Notification");
<add> } catch (Throwable ex) {
<add> Exceptions.throwIfFatal(ex);
<add> downstream.onError(ex);
<add> return;
<add> }
<add> if (notification.isOnNext()) {
<add> downstream.onSuccess(notification.getValue());
<add> } else if (notification.isOnComplete()) {
<add> downstream.onComplete();
<add> } else {
<add> downstream.onError(notification.getError());
<add> }
<add> }
<add>
<add> @Override
<add> public void onError(Throwable e) {
<add> downstream.onError(e);
<add> }
<add> }
<add>}
<ide><path>src/main/java/io/reactivex/internal/operators/single/SingleMaterialize.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.annotations.Experimental;
<add>import io.reactivex.internal.operators.mixed.MaterializeSingleObserver;
<add>
<add>/**
<add> * Turn the signal types of a Single source into a single Notification of
<add> * equal kind.
<add> *
<add> * @param <T> the element type of the source
<add> * @since 2.2.4 - experimental
<add> */
<add>@Experimental
<add>public final class SingleMaterialize<T> extends Single<Notification<T>> {
<add>
<add> final Single<T> source;
<add>
<add> public SingleMaterialize(Single<T> source) {
<add> this.source = source;
<add> }
<add>
<add> @Override
<add> protected void subscribeActual(SingleObserver<? super Notification<T>> observer) {
<add> source.subscribe(new MaterializeSingleObserver<T>(observer));
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/completable/CompletableMaterializeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.completable;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.subjects.CompletableSubject;
<add>
<add>public class CompletableMaterializeTest {
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void error() {
<add> TestException ex = new TestException();
<add> Completable.error(ex)
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnError(ex));
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void empty() {
<add> Completable.complete()
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnComplete());
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeCompletableToSingle(new Function<Completable, SingleSource<Notification<Object>>>() {
<add> @Override
<add> public SingleSource<Notification<Object>> apply(Completable v) throws Exception {
<add> return v.materialize();
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> TestHelper.checkDisposed(CompletableSubject.create().materialize());
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/maybe/MaybeMaterializeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.maybe;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.subjects.MaybeSubject;
<add>
<add>public class MaybeMaterializeTest {
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void success() {
<add> Maybe.just(1)
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnNext(1));
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void error() {
<add> TestException ex = new TestException();
<add> Maybe.error(ex)
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnError(ex));
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void empty() {
<add> Maybe.empty()
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnComplete());
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeMaybeToSingle(new Function<Maybe<Object>, SingleSource<Notification<Object>>>() {
<add> @Override
<add> public SingleSource<Notification<Object>> apply(Maybe<Object> v) throws Exception {
<add> return v.materialize();
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> TestHelper.checkDisposed(MaybeSubject.create().materialize());
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleDematerializeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.internal.functions.Functions;
<add>import io.reactivex.subjects.SingleSubject;
<add>
<add>public class SingleDematerializeTest {
<add>
<add> @Test
<add> public void success() {
<add> Single.just(Notification.createOnNext(1))
<add> .dematerialize(Functions.<Notification<Integer>>identity())
<add> .test()
<add> .assertResult(1);
<add> }
<add>
<add> @Test
<add> public void empty() {
<add> Single.just(Notification.<Integer>createOnComplete())
<add> .dematerialize(Functions.<Notification<Integer>>identity())
<add> .test()
<add> .assertResult();
<add> }
<add>
<add> @Test
<add> public void error() {
<add> Single.<Notification<Integer>>error(new TestException())
<add> .dematerialize(Functions.<Notification<Integer>>identity())
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void errorNotification() {
<add> Single.just(Notification.<Integer>createOnError(new TestException()))
<add> .dematerialize(Functions.<Notification<Integer>>identity())
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeSingleToMaybe(new Function<Single<Object>, MaybeSource<Object>>() {
<add> @SuppressWarnings({ "unchecked", "rawtypes" })
<add> @Override
<add> public MaybeSource<Object> apply(Single<Object> v) throws Exception {
<add> return v.dematerialize((Function)Functions.identity());
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> TestHelper.checkDisposed(SingleSubject.<Notification<Integer>>create().dematerialize(Functions.<Notification<Integer>>identity()));
<add> }
<add>
<add> @Test
<add> public void selectorCrash() {
<add> Single.just(Notification.createOnNext(1))
<add> .dematerialize(new Function<Notification<Integer>, Notification<Integer>>() {
<add> @Override
<add> public Notification<Integer> apply(Notification<Integer> v) throws Exception {
<add> throw new TestException();
<add> }
<add> })
<add> .test()
<add> .assertFailure(TestException.class);
<add> }
<add>
<add> @Test
<add> public void selectorNull() {
<add> Single.just(Notification.createOnNext(1))
<add> .dematerialize(Functions.justFunction((Notification<Integer>)null))
<add> .test()
<add> .assertFailure(NullPointerException.class);
<add> }
<add>
<add> @Test
<add> public void selectorDifferentType() {
<add> Single.just(Notification.createOnNext(1))
<add> .dematerialize(new Function<Notification<Integer>, Notification<String>>() {
<add> @Override
<add> public Notification<String> apply(Notification<Integer> v) throws Exception {
<add> return Notification.createOnNext("Value-" + 1);
<add> }
<add> })
<add> .test()
<add> .assertResult("Value-1");
<add> }
<add>}
<ide><path>src/test/java/io/reactivex/internal/operators/single/SingleMaterializeTest.java
<add>/**
<add> * Copyright (c) 2016-present, RxJava Contributors.
<add> *
<add> * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
<add> * compliance with the License. You may obtain a copy of the License at
<add> *
<add> * http://www.apache.org/licenses/LICENSE-2.0
<add> *
<add> * Unless required by applicable law or agreed to in writing, software distributed under the License is
<add> * distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See
<add> * the License for the specific language governing permissions and limitations under the License.
<add> */
<add>
<add>package io.reactivex.internal.operators.single;
<add>
<add>import org.junit.Test;
<add>
<add>import io.reactivex.*;
<add>import io.reactivex.exceptions.TestException;
<add>import io.reactivex.functions.Function;
<add>import io.reactivex.subjects.SingleSubject;
<add>
<add>public class SingleMaterializeTest {
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void success() {
<add> Single.just(1)
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnNext(1));
<add> }
<add>
<add> @Test
<add> @SuppressWarnings("unchecked")
<add> public void error() {
<add> TestException ex = new TestException();
<add> Maybe.error(ex)
<add> .materialize()
<add> .test()
<add> .assertResult(Notification.createOnError(ex));
<add> }
<add>
<add> @Test
<add> public void doubleOnSubscribe() {
<add> TestHelper.checkDoubleOnSubscribeSingle(new Function<Single<Object>, SingleSource<Notification<Object>>>() {
<add> @Override
<add> public SingleSource<Notification<Object>> apply(Single<Object> v) throws Exception {
<add> return v.materialize();
<add> }
<add> });
<add> }
<add>
<add> @Test
<add> public void dispose() {
<add> TestHelper.checkDisposed(SingleSubject.create().materialize());
<add> }
<add>} | 12 |
Text | Text | update description of our community and curriculum | cd9db324c80966626e276fda306ad4d78d93a19b | <ide><path>README.md
<ide> Welcome to Free Code Camp's open source codebase and curriculum!
<ide> =======================
<ide>
<del>Free Code Camp is an open-source community where you learn to code and help nonprofits.
<add>Free Code Camp is a friendly open-source community where you learn to code and help nonprofits.
<add>
<add>**We help our campers build job-worthy portfolios of real apps used by real people, while helping nonprofits.**
<ide>
<ide> You start by working through our self-paced, browser-based full stack JavaScript curriculum.
<ide>
<del>After you complete the first 400 hours worth of challenges (which involves building 10 single-page apps), you'll earn your Front End Development Certification.
<add>### By working through our curriculum, you can earn four certifications:
<add>##### 1. Front End Certification
<add>The first section will teach you the basics of how webpages work and also introduce you to JavaScript programming.
<ide>
<del>After you complete the second 400 hours worth of challenges (which involves building and deploying 5 full stack apps), you'll earn your Full Stack Development Certification.
<add>Skills you'll practice include `HTML, CSS, JavaScript, jQuery` and `Bootstrap`.
<ide>
<del>Then we'll pair you with another camper, an agile project manager, and a stakeholder from a nonprofit organization. Together, you'll plan and build an app that helps that nonprofit carry out its mission more effectively.
<add>To earn this certification you'll build **10 front-end projects** and implement many **JavaScript algorithms**
<ide>
<del>**We help our campers build job-worthy portfolios of real apps used by real people, while helping nonprofits.**
<add>##### 2. Data Visualization Certification
<add>The second section builds upon the first and introduce you to more advanced topics such as `Sass, React` and `D3`.
<add>
<add>To earn this certification you'll build **5 React-apps** and **5 Data visualization apps** using `D3.js`.
<add>
<add>##### 3. Back End Certification
<add>The third section introduces you to back end development using `Node.js, Express, MongoDB` but also teach you about the important concept of source control using `Git`.
<add>
<add>To earn this certification you'll build **5 API:s** and **5 full stack JavaScript apps**.
<add>
<add>##### 4. Full Stack Certification
<add>The fourth section is where you'll get **real world experience** by working on projects for **Non-profits**.
<add>We'll pair you with another camper, an agile project manager, and a stakeholder from a nonprofit organization. Together, you'll plan, build and maintain apps that helps that nonprofit carry out its mission more effectively.
<add>
<add>For this certification you'll work on **two projects from scratch** and then **maintain/upgrade two existing projects**.
<add>
<add>---
<ide>
<ide> This code is running live at [FreeCodeCamp.com](http://www.FreeCodeCamp.com). We also have [Gitter](https://gitter.im/FreeCodeCamp/FreeCodeCamp), a [Medium publication](http://medium.freecodecamp.com), and even a [Twitch.tv channel](http://twitch.tv/freecodecamp).
<ide>
<del>[Join our community here](http://www.freecodecamp.com/signin).
<add>### [Join our community here](http://www.freecodecamp.com/signin).
<ide>
<ide> Wiki
<ide> ------------ | 1 |
Javascript | Javascript | remove unused dependency | 61cd5961377e04f0bc91b88c78a8e6b8a8094de4 | <ide><path>Libraries/Components/TextInput/AndroidTextInputNativeComponent.js
<ide> import type {ColorValue} from '../../StyleSheet/StyleSheet';
<ide> import requireNativeComponent from '../../ReactNative/requireNativeComponent';
<ide> import codegenNativeCommands from '../../Utilities/codegenNativeCommands';
<ide> import type {TextInputNativeCommands} from './TextInputNativeCommands';
<del>import * as React from 'react';
<ide> import AndroidTextInputViewConfig from './AndroidTextInputViewConfig';
<ide> const ReactNativeViewConfigRegistry = require('../../Renderer/shims/ReactNativeViewConfigRegistry');
<ide> | 1 |
Ruby | Ruby | add test case for | 787617760cb63b46bc176b94d8ebbf59b5c848cc | <ide><path>actionpack/test/controller/mime_responds_test.rb
<ide> def all_types_with_layout
<ide> end
<ide> end
<ide>
<del>
<ide> def iphone_with_html_response_type
<ide> request.format = :iphone if request.env["HTTP_ACCEPT"] == "text/iphone"
<ide>
<ide> class PostController < AbstractPostController
<ide> around_filter :with_iphone
<ide>
<ide> def index
<del> respond_to(:html, :iphone)
<add> respond_to(:html, :iphone, :js)
<ide> end
<ide>
<ide> protected
<ide> def test_format_with_inherited_layouts
<ide> get :index
<ide> assert_equal '<html><div id="super_iphone">Super iPhone</div></html>', @response.body
<ide> end
<add>
<add> def test_non_navigational_format_with_no_template_fallbacks_to_html_template_with_no_layout
<add> get :index, :format => :js
<add> assert_equal "Hello Firefox", @response.body
<add> end
<ide> end
<ide>
<ide> class FlashResponder < ActionController::Responder | 1 |
Javascript | Javascript | fix @babel/env modules config | a9b1383b5d27aea18b5509b09f118a9be69dfdab | <ide><path>build/babel/preset.js
<ide> module.exports = (context, opts = {}) => ({
<ide> [require('@babel/preset-env').default, {
<ide> // In the test environment `modules` is often needed to be set to true, babel figures that out by itself using the `'auto'` option
<ide> // In production/development this option is set to `false` so that webpack can handle import/export with tree-shaking
<del> modules: isDevelopment && isProduction ? false : 'auto',
<add> modules: isDevelopment || isProduction ? false : 'auto',
<ide> ...opts['preset-env']
<ide> }],
<ide> [require('@babel/preset-react'), { | 1 |
Javascript | Javascript | fix lint error | 228f12eb61b5212d0831a2a7d204bdf2a99263f6 | <ide><path>src/tree-sitter-language-mode.js
<ide> class TreeSitterLanguageMode {
<ide> }
<ide>
<ide> if (end.column < lineText.length) {
<del> for (const _ of iterator.getCloseScopeIds()) {
<add> const closeScopeCount = iterator.getCloseScopeIds().length;
<add> for (let i = 0; i < closeScopeCount; i++) {
<ide> scopes.pop();
<ide> }
<ide> scopes.push(...iterator.getOpenScopeIds()); | 1 |
Java | Java | use httpmessagenotwritableexception instead of ise | c32299f734521e907585de50d70a46dcd8018f13 | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/result/method/annotation/AbstractMessageWriterResultHandler.java
<ide> import org.springframework.core.codec.Hints;
<ide> import org.springframework.http.MediaType;
<ide> import org.springframework.http.codec.HttpMessageWriter;
<add>import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.lang.Nullable;
<ide> import org.springframework.util.Assert;
<ide> import org.springframework.web.reactive.accept.RequestedContentTypeResolver;
<ide> protected Mono<Void> writeBody(@Nullable Object body, MethodParameter bodyParame
<ide>
<ide> MediaType contentType = exchange.getResponse().getHeaders().getContentType();
<ide> if (contentType != null && contentType.equals(bestMediaType)) {
<del> return Mono.error(new IllegalStateException(
<add> return Mono.error(new HttpMessageNotWritableException(
<ide> "No Encoder for [" + elementType + "] with preset Content-Type '" + contentType + "'"));
<ide> }
<ide>
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/ResponseEntityResultHandlerTests.java
<ide> import org.springframework.http.codec.ResourceHttpMessageWriter;
<ide> import org.springframework.http.codec.json.Jackson2JsonEncoder;
<ide> import org.springframework.http.codec.xml.Jaxb2XmlEncoder;
<add>import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.mock.web.test.server.MockServerWebExchange;
<ide> import org.springframework.util.ObjectUtils;
<ide> import org.springframework.web.reactive.HandlerResult;
<ide> public void handleWithPresetContentTypeShouldFailWithServerError() {
<ide>
<ide> StepVerifier.create(resultHandler.handleResult(exchange, result))
<ide> .consumeErrorWith(ex -> assertThat(ex)
<del> .isInstanceOf(IllegalStateException.class)
<add> .isInstanceOf(HttpMessageNotWritableException.class)
<ide> .hasMessageContaining("with preset Content-Type"))
<ide> .verify();
<ide> }
<ide><path>spring-webmvc/src/main/java/org/springframework/web/servlet/mvc/method/annotation/AbstractMessageConverterMethodProcessor.java
<ide> protected <T> void writeWithMessageConverters(T value, MethodParameter returnTyp
<ide> * @throws IOException thrown in case of I/O errors
<ide> * @throws HttpMediaTypeNotAcceptableException thrown when the conditions indicated
<ide> * by the {@code Accept} header on the request cannot be met by the message converters
<add> * @throws HttpMessageNotWritableException thrown if a given message cannot
<add> * be written by a converter, or if the content-type chosen by the server
<add> * has no compatible converter.
<ide> */
<ide> @SuppressWarnings({"rawtypes", "unchecked"})
<ide> protected <T> void writeWithMessageConverters(@Nullable T value, MethodParameter returnType,
<ide> else if (mediaType.isPresentIn(ALL_APPLICATION_MEDIA_TYPES)) {
<ide>
<ide> if (body != null) {
<ide> if (isContentTypePreset) {
<del> throw new IllegalStateException(
<add> throw new HttpMessageNotWritableException(
<ide> "No converter for [" + valueType + "] with preset Content-Type '" + contentType + "'");
<ide> }
<ide> throw new HttpMediaTypeNotAcceptableException(this.allSupportedMediaTypes);
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/annotation/HttpEntityMethodProcessorMockTests.java
<ide> import org.springframework.http.RequestEntity;
<ide> import org.springframework.http.ResponseEntity;
<ide> import org.springframework.http.converter.HttpMessageConverter;
<add>import org.springframework.http.converter.HttpMessageNotWritableException;
<ide> import org.springframework.mock.web.test.MockHttpServletRequest;
<ide> import org.springframework.mock.web.test.MockHttpServletResponse;
<ide> import org.springframework.web.HttpMediaTypeNotAcceptableException;
<ide> import static java.time.format.DateTimeFormatter.RFC_1123_DATE_TIME;
<ide> import static org.assertj.core.api.Assertions.assertThat;
<ide> import static org.assertj.core.api.Assertions.assertThatExceptionOfType;
<del>import static org.assertj.core.api.Assertions.assertThatIllegalStateException;
<add>import static org.assertj.core.api.Assertions.assertThatThrownBy;
<ide> import static org.mockito.ArgumentMatchers.any;
<ide> import static org.mockito.ArgumentMatchers.anyCollection;
<ide> import static org.mockito.ArgumentMatchers.argThat;
<ide> public void shouldFailWithServerErrorIfContentTypeFromResponseEntity() {
<ide> given(stringHttpMessageConverter.canWrite(String.class, null)).willReturn(true);
<ide> given(stringHttpMessageConverter.getSupportedMediaTypes()).willReturn(Collections.singletonList(TEXT_PLAIN));
<ide>
<del> assertThatIllegalStateException()
<del> .isThrownBy(() ->
<del> processor.handleReturnValue(returnValue, returnTypeResponseEntity, mavContainer, webRequest))
<del> .withMessageContaining("with preset Content-Type");
<add> assertThatThrownBy(() ->
<add> processor.handleReturnValue(
<add> returnValue, returnTypeResponseEntity, mavContainer, webRequest))
<add> .isInstanceOf(HttpMessageNotWritableException.class)
<add> .hasMessageContaining("with preset Content-Type");
<ide> }
<ide>
<ide> @Test | 4 |
Text | Text | use pk for url conf and views. | 3f6004c5a9edab6336e93da85ce3849dee0b1311 | <ide><path>docs/tutorial/1-serialization.md
<ide> Note that because we want to be able to POST to this view from clients that won'
<ide> We'll also need a view which corresponds to an individual snippet, and can be used to retrieve, update or delete the snippet.
<ide>
<ide> @csrf_exempt
<del> def snippet_detail(request, id):
<add> def snippet_detail(request, pk):
<ide> """
<ide> Retrieve, update or delete a code snippet.
<ide> """
<ide> try:
<del> snippet = Snippet.objects.get(id=id)
<add> snippet = Snippet.objects.get(pk=pk)
<ide> except Snippet.DoesNotExist:
<ide> return HttpResponse(status=404)
<ide>
<ide> Finally we need to wire these views up. Create the `snippets/urls.py` file:
<ide>
<ide> urlpatterns = [
<ide> url(r'^snippets/$', views.snippet_list),
<del> url(r'^snippets/(?P<id>[0-9]+)/$', views.snippet_detail),
<add> url(r'^snippets/(?P<pk>[0-9]+)/$', views.snippet_detail),
<ide> ]
<ide>
<ide> We also need to wire up the root urlconf, in the `tutorial/urls.py` file, to include our snippet app's URLs.
<ide><path>docs/tutorial/2-requests-and-responses.md
<ide> Our instance view is an improvement over the previous example. It's a little mo
<ide> Here is the view for an individual snippet, in the `views.py` module.
<ide>
<ide> @api_view(['GET', 'PUT', 'DELETE'])
<del> def snippet_detail(request, id):
<add> def snippet_detail(request, pk):
<ide> """
<ide> Retrieve, update or delete a snippet instance.
<ide> """
<ide> try:
<del> snippet = Snippet.objects.get(id=id)
<add> snippet = Snippet.objects.get(pk=pk)
<ide> except Snippet.DoesNotExist:
<ide> return Response(status=status.HTTP_404_NOT_FOUND)
<ide>
<ide> Start by adding a `format` keyword argument to both of the views, like so.
<ide>
<ide> and
<ide>
<del> def snippet_detail(request, id, format=None):
<add> def snippet_detail(request, pk, format=None):
<ide>
<ide> Now update the `urls.py` file slightly, to append a set of `format_suffix_patterns` in addition to the existing URLs.
<ide>
<ide> Now update the `urls.py` file slightly, to append a set of `format_suffix_patter
<ide>
<ide> urlpatterns = [
<ide> url(r'^snippets/$', views.snippet_list),
<del> url(r'^snippets/(?P<id>[0-9]+)$', views.snippet_detail),
<add> url(r'^snippets/(?P<pk>[0-9]+)$', views.snippet_detail),
<ide> ]
<ide>
<ide> urlpatterns = format_suffix_patterns(urlpatterns)
<ide><path>docs/tutorial/3-class-based-views.md
<ide> So far, so good. It looks pretty similar to the previous case, but we've got be
<ide> """
<ide> Retrieve, update or delete a snippet instance.
<ide> """
<del> def get_object(self, id):
<add> def get_object(self, pk):
<ide> try:
<del> return Snippet.objects.get(id=id)
<add> return Snippet.objects.get(pk=pk)
<ide> except Snippet.DoesNotExist:
<ide> raise Http404
<ide>
<del> def get(self, request, id, format=None):
<del> snippet = self.get_object(id)
<add> def get(self, request, pk, format=None):
<add> snippet = self.get_object(pk)
<ide> serializer = SnippetSerializer(snippet)
<ide> return Response(serializer.data)
<ide>
<del> def put(self, request, id, format=None):
<del> snippet = self.get_object(id)
<add> def put(self, request, pk, format=None):
<add> snippet = self.get_object(pk)
<ide> serializer = SnippetSerializer(snippet, data=request.data)
<ide> if serializer.is_valid():
<ide> serializer.save()
<ide> return Response(serializer.data)
<ide> return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
<ide>
<del> def delete(self, request, id, format=None):
<del> snippet = self.get_object(id)
<add> def delete(self, request, pk, format=None):
<add> snippet = self.get_object(pk)
<ide> snippet.delete()
<ide> return Response(status=status.HTTP_204_NO_CONTENT)
<ide>
<ide> We'll also need to refactor our `urls.py` slightly now we're using class-based v
<ide>
<ide> urlpatterns = [
<ide> url(r'^snippets/$', views.SnippetList.as_view()),
<del> url(r'^snippets/(?P<id>[0-9]+)/$', views.SnippetDetail.as_view()),
<add> url(r'^snippets/(?P<pk>[0-9]+)/$', views.SnippetDetail.as_view()),
<ide> ]
<ide>
<ide> urlpatterns = format_suffix_patterns(urlpatterns)
<ide><path>docs/tutorial/4-authentication-and-permissions.md
<ide> Make sure to also import the `UserSerializer` class
<ide> Finally we need to add those views into the API, by referencing them from the URL conf. Add the following to the patterns in `urls.py`.
<ide>
<ide> url(r'^users/$', views.UserList.as_view()),
<del> url(r'^users/(?P<id>[0-9]+)/$', views.UserDetail.as_view()),
<add> url(r'^users/(?P<pk>[0-9]+)/$', views.UserDetail.as_view()),
<ide>
<ide> ## Associating Snippets with Users
<ide>
<ide><path>docs/tutorial/5-relationships-and-hyperlinked-apis.md
<ide> We'll add a url pattern for our new API root in `snippets/urls.py`:
<ide>
<ide> And then add a url pattern for the snippet highlights:
<ide>
<del> url(r'^snippets/(?P<id>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
<add> url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', views.SnippetHighlight.as_view()),
<ide>
<ide> ## Hyperlinking our API
<ide>
<ide> After adding all those names into our URLconf, our final `snippets/urls.py` file
<ide> url(r'^snippets/$',
<ide> views.SnippetList.as_view(),
<ide> name='snippet-list'),
<del> url(r'^snippets/(?P<id>[0-9]+)/$',
<add> url(r'^snippets/(?P<pk>[0-9]+)/$',
<ide> views.SnippetDetail.as_view(),
<ide> name='snippet-detail'),
<del> url(r'^snippets/(?P<id>[0-9]+)/highlight/$',
<add> url(r'^snippets/(?P<pk>[0-9]+)/highlight/$',
<ide> views.SnippetHighlight.as_view(),
<ide> name='snippet-highlight'),
<ide> url(r'^users/$',
<ide> views.UserList.as_view(),
<ide> name='user-list'),
<del> url(r'^users/(?P<id>[0-9]+)/$',
<add> url(r'^users/(?P<pk>[0-9]+)/$',
<ide> views.UserDetail.as_view(),
<ide> name='user-detail')
<ide> ])
<ide><path>docs/tutorial/6-viewsets-and-routers.md
<ide> Now that we've bound our resources into concrete views, we can register the view
<ide> urlpatterns = format_suffix_patterns([
<ide> url(r'^$', api_root),
<ide> url(r'^snippets/$', snippet_list, name='snippet-list'),
<del> url(r'^snippets/(?P<id>[0-9]+)/$', snippet_detail, name='snippet-detail'),
<del> url(r'^snippets/(?P<id>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
<add> url(r'^snippets/(?P<pk>[0-9]+)/$', snippet_detail, name='snippet-detail'),
<add> url(r'^snippets/(?P<pk>[0-9]+)/highlight/$', snippet_highlight, name='snippet-highlight'),
<ide> url(r'^users/$', user_list, name='user-list'),
<del> url(r'^users/(?P<id>[0-9]+)/$', user_detail, name='user-detail')
<add> url(r'^users/(?P<pk>[0-9]+)/$', user_detail, name='user-detail')
<ide> ])
<ide>
<ide> ## Using Routers | 6 |
PHP | PHP | add test for loadmodel() exception | 824d41e5f5d40c8952d42e7e21ea7ba1ab3cb8cf | <ide><path>tests/TestCase/Datasource/ModelAwareTraitTest.php
<ide> public function testLoadModel()
<ide> $this->assertSame('PaginatorPosts', $result->getAlias());
<ide> }
<ide>
<add> /**
<add> * Test that calling loadModel() without $modelClass argument when default
<add> * $modelClass property is empty generates exception.
<add> *
<add> * @return void
<add> */
<add> public function testLoadModelException()
<add> {
<add> $this->expectException(\UnexpectedValueException::class);
<add> $this->expectExceptionMessage('Default modelClass is empty');
<add>
<add> $stub = new Stub();
<add> $stub->setProps('');
<add> $stub->setModelType('Table');
<add>
<add> $stub->loadModel();
<add> }
<add>
<ide> /**
<ide> * test loadModel() with plugin prefixed models
<ide> * | 1 |
Python | Python | resolve model name properly in cli.info | e39ad78267c49c5b340a78cd28e22f0c95b16998 | <ide><path>spacy/cli/info.py
<ide>
<ide> def info(model=None, markdown=False):
<ide> if model:
<del> data_path = util.get_data_path()
<del> data = util.parse_package_meta(data_path / model, require=True)
<del> model_path = Path(__file__).parent / data_path / model
<add> model_path = util.resolve_model_path(model)
<add> meta = util.parse_package_meta(model_path)
<ide> if model_path.resolve() != model_path:
<del> data['link'] = path2str(model_path)
<del> data['source'] = path2str(model_path.resolve())
<add> meta['link'] = path2str(model_path)
<add> meta['source'] = path2str(model_path.resolve())
<ide> else:
<del> data['source'] = path2str(model_path)
<del> print_info(data, 'model %s' % model, markdown)
<add> meta['source'] = path2str(model_path)
<add> print_info(meta, 'model %s' % model, markdown)
<ide> else:
<ide> data = {'spaCy version': about.__version__,
<ide> 'Location': path2str(Path(__file__).parent.parent), | 1 |
Go | Go | fix typo to run tests grouped by rununprivileged | a36f6a140bb7987c18a8177115cbc315672f9e53 | <ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunPrivilegedCanMknod(c *check.C) {
<ide> }
<ide> }
<ide>
<del>func (s *DockerSuite) TestRunUnPrivilegedCanMknod(c *check.C) {
<add>func (s *DockerSuite) TestRunUnprivilegedCanMknod(c *check.C) {
<ide> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok")
<ide> out, _, err := runCommandWithOutput(cmd)
<ide> if err != nil {
<ide> func (s *DockerSuite) TestRunPrivilegedCanMount(c *check.C) {
<ide> }
<ide> }
<ide>
<del>func (s *DockerSuite) TestRunUnPrivilegedCannotMount(c *check.C) {
<add>func (s *DockerSuite) TestRunUnprivilegedCannotMount(c *check.C) {
<ide> cmd := exec.Command(dockerBinary, "run", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok")
<ide> out, _, err := runCommandWithOutput(cmd)
<ide> if err == nil { | 1 |
Javascript | Javascript | use native class for promise inheritance test | d4645deaf0f3c7d462895c63a08b0bd20338001d | <ide><path>packages/ember-runtime/tests/mixins/promise_proxy_test.js
<ide> QUnit.test('unhandled rejects still propagate to RSVP.on(\'error\', ...) ', func
<ide> });
<ide>
<ide> QUnit.test('should work with promise inheritance', function(assert) {
<del> function PromiseSubclass() {
<del> RSVP.Promise.apply(this, arguments);
<del> }
<del>
<del> PromiseSubclass.prototype = Object.create(RSVP.Promise.prototype);
<del> PromiseSubclass.prototype.constructor = PromiseSubclass;
<add> class PromiseSubclass extends RSVP.Promise { }
<ide>
<ide> let proxy = ObjectPromiseProxy.create({
<ide> promise: new PromiseSubclass(() => { }) | 1 |
Java | Java | make configurationclassbeandefinitionreader public | 4f7bdbd3de8e1ca91ad84ea41afc4f525e1b4fd8 | <ide><path>org.springframework.context/src/main/java/org/springframework/context/annotation/ConfigurationClassBeanDefinitionReader.java
<ide> * @since 3.0
<ide> * @see ConfigurationClassParser
<ide> */
<del>class ConfigurationClassBeanDefinitionReader {
<add>public class ConfigurationClassBeanDefinitionReader {
<ide>
<ide> private static final String CONFIGURATION_CLASS_FULL = "full";
<ide> | 1 |
Mixed | Text | add valid suffixes for remaining duration options | 32b12a28fcab98b79c9176fb78b5620a46906916 | <ide><path>cli/command/service/opts.go
<ide> func addServiceFlags(cmd *cobra.Command, opts *serviceOptions) {
<ide> flags.Var(&opts.resources.limitMemBytes, flagLimitMemory, "Limit Memory")
<ide> flags.Var(&opts.resources.resCPU, flagReserveCPU, "Reserve CPUs")
<ide> flags.Var(&opts.resources.resMemBytes, flagReserveMemory, "Reserve Memory")
<del> flags.Var(&opts.stopGrace, flagStopGracePeriod, "Time to wait before force killing a container")
<add> flags.Var(&opts.stopGrace, flagStopGracePeriod, "Time to wait before force killing a container (ns|us|ms|s|m|h)")
<ide>
<ide> flags.Var(&opts.replicas, flagReplicas, "Number of tasks")
<ide>
<ide> flags.StringVar(&opts.restartPolicy.condition, flagRestartCondition, "", "Restart when condition is met (none, on-failure, or any)")
<del> flags.Var(&opts.restartPolicy.delay, flagRestartDelay, "Delay between restart attempts")
<add> flags.Var(&opts.restartPolicy.delay, flagRestartDelay, "Delay between restart attempts (ns|us|ms|s|m|h)")
<ide> flags.Var(&opts.restartPolicy.maxAttempts, flagRestartMaxAttempts, "Maximum number of restarts before giving up")
<del> flags.Var(&opts.restartPolicy.window, flagRestartWindow, "Window used to evaluate the restart policy")
<add> flags.Var(&opts.restartPolicy.window, flagRestartWindow, "Window used to evaluate the restart policy (ns|us|ms|s|m|h)")
<ide>
<ide> flags.Uint64Var(&opts.update.parallelism, flagUpdateParallelism, 1, "Maximum number of tasks updated simultaneously (0 to update all at once)")
<ide> flags.DurationVar(&opts.update.delay, flagUpdateDelay, time.Duration(0), "Delay between updates (ns|us|ms|s|m|h) (default 0s)")
<ide> func addServiceFlags(cmd *cobra.Command, opts *serviceOptions) {
<ide> flags.Var(&opts.logDriver.opts, flagLogOpt, "Logging driver options")
<ide>
<ide> flags.StringVar(&opts.healthcheck.cmd, flagHealthCmd, "", "Command to run to check health")
<del> flags.Var(&opts.healthcheck.interval, flagHealthInterval, "Time between running the check")
<del> flags.Var(&opts.healthcheck.timeout, flagHealthTimeout, "Maximum time to allow one check to run")
<add> flags.Var(&opts.healthcheck.interval, flagHealthInterval, "Time between running the check (ns|us|ms|s|m|h)")
<add> flags.Var(&opts.healthcheck.timeout, flagHealthTimeout, "Maximum time to allow one check to run (ns|us|ms|s|m|h)")
<ide> flags.IntVar(&opts.healthcheck.retries, flagHealthRetries, 0, "Consecutive failures needed to report unhealthy")
<ide> flags.BoolVar(&opts.healthcheck.noHealthcheck, flagNoHealthcheck, false, "Disable any container-specified HEALTHCHECK")
<ide>
<ide><path>docs/reference/commandline/service_create.md
<ide> Options:
<ide> --env-file list Read in a file of environment variables (default [])
<ide> --group list Set one or more supplementary user groups for the container (default [])
<ide> --health-cmd string Command to run to check health
<del> --health-interval duration Time between running the check (default none)
<add> --health-interval duration Time between running the check (ns|us|ms|s|m|h) (default none)
<ide> --health-retries int Consecutive failures needed to report unhealthy
<del> --health-timeout duration Maximum time to allow one check to run (default none)
<add> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default none)
<ide> --help Print usage
<ide> --host list Set one or more custom host-to-IP mappings (host:ip) (default [])
<ide> --hostname string Container hostname
<ide> Options:
<ide> --reserve-cpu decimal Reserve CPUs (default 0.000)
<ide> --reserve-memory bytes Reserve Memory (default 0 B)
<ide> --restart-condition string Restart when condition is met (none, on-failure, or any)
<del> --restart-delay duration Delay between restart attempts (default none)
<add> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) (default none)
<ide> --restart-max-attempts uint Maximum number of restarts before giving up (default none)
<del> --restart-window duration Window used to evaluate the restart policy (default none)
<add> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) (default none)
<ide> --secret value Specify secrets to expose to the service (default [])
<del> --stop-grace-period duration Time to wait before force killing a container (default none)
<add> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) (default none)
<ide> -t, --tty Allocate a pseudo-TTY
<ide> --update-delay duration Delay between updates (ns|us|ms|s|m|h) (default 0s)
<ide> --update-failure-action string Action on update failure (pause|continue) (default "pause")
<ide><path>docs/reference/commandline/service_update.md
<ide> Options:
<ide> --group-add list Add an additional supplementary user group to the container (default [])
<ide> --group-rm list Remove a previously added supplementary user group from the container (default [])
<ide> --health-cmd string Command to run to check health
<del> --health-interval duration Time between running the check (default none)
<add> --health-interval duration Time between running the check (ns|us|ms|s|m|h) (default none)
<ide> --health-retries int Consecutive failures needed to report unhealthy
<del> --health-timeout duration Maximum time to allow one check to run (default none)
<add> --health-timeout duration Maximum time to allow one check to run (ns|us|ms|s|m|h) (default none)
<ide> --help Print usage
<ide> --host-add list Add or update a custom host-to-IP mapping (host:ip) (default [])
<ide> --host-rm list Remove a custom host-to-IP mapping (host:ip) (default [])
<ide> Options:
<ide> --reserve-cpu decimal Reserve CPUs (default 0.000)
<ide> --reserve-memory bytes Reserve Memory (default 0 B)
<ide> --restart-condition string Restart when condition is met (none, on-failure, or any)
<del> --restart-delay duration Delay between restart attempts (default none)
<add> --restart-delay duration Delay between restart attempts (ns|us|ms|s|m|h) (default none)
<ide> --restart-max-attempts uint Maximum number of restarts before giving up (default none)
<del> --restart-window duration Window used to evaluate the restart policy (default none)
<add> --restart-window duration Window used to evaluate the restart policy (ns|us|ms|s|m|h) (default none)
<ide> --rollback Rollback to previous specification
<ide> --secret-add list Add a secret (default [])
<ide> --secret-rm list Remove a secret (default [])
<del> --stop-grace-period duration Time to wait before force killing a container (default none)
<add> --stop-grace-period duration Time to wait before force killing a container (ns|us|ms|s|m|h) (default none)
<ide> -t, --tty Allocate a pseudo-TTY
<ide> --update-delay duration Delay between updates (ns|us|ms|s|m|h) (default 0s)
<ide> --update-failure-action string Action on update failure (pause|continue) (default "pause") | 3 |
Text | Text | add 2.16.0 to changelog.md | 64dfd70b4e875c8b5b0fe0def3da5b358fdea904 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<del>### 2.16.0-beta.2 (October, 2, 2017)
<add>### 2.16.0 (October 9, 2017)
<ide>
<add>- [#15604](https://github.com/emberjs/ember.js/pull/15604) Data Adapter: Only trigger model type update if the record live array count actually changed
<add>- [#15610](https://github.com/emberjs/ember.js/pull/15610) [BUGFIX] add inflection to dependencies
<add>- [#15695](https://github.com/emberjs/ember.js/pull/15695) [BUGFIX] Avoid creating event dispatcher in FastBoot with Engines
<add>- [#15702](https://github.com/emberjs/ember.js/pull/15702) [BUGFIX] Correctly escape values in `Ember.CoreObject` assertions
<add>- [#15718](https://github.com/emberjs/ember.js/pull/15718) [BUGFIX] bump backburner (fixes clock + autorun interop)
<ide> - [#15577](https://github.com/emberjs/ember.js/pull/15577) [BUGFIX] Include missing sourcemaps in vendorTree.
<ide> - [#15552](https://github.com/emberjs/ember.js/pull/15552) [FEATURE] Update blueprints and tests to RFC #176.
<ide> - [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX] ensure “pause on exception” pauses in the right place.
<ide> - [#15616](https://github.com/emberjs/ember.js/pull/15616) [DOC release] Improve documentation for RouterService and mount helper.
<del>- [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX LTS] ensure “pause on exception” pauses in the right place.
<add>- [#15600](https://github.com/emberjs/ember.js/pull/15600) [BUGFIX] ensure “pause on exception” pauses in the right place.
<ide> - [#15667](https://github.com/emberjs/ember.js/pull/15667) [BUGFIX] Allow `0` to work with `get` helper.
<ide> - [#15676](https://github.com/emberjs/ember.js/pull/15676) [BUGFIX] Fix `<input type="range">` so that it can properly bind `min`, `max`, and `value`.
<ide> - [#15689](https://github.com/emberjs/ember.js/pull/15689) [BUGFIX] Mark error as handled before transition for error routes and substates.
<del>
<del>
<del>### 2.16.0-beta.1 (August 31, 2017)
<del>
<ide> - [#14764](https://github.com/emberjs/ember.js/pull/14764) Fixed string capitalize for accented characters.
<ide> - [#15528](https://github.com/emberjs/ember.js/pull/15528) [DEPRECATION] Deprecate `Controller#content` alias.
<ide> - [#15552](https://github.com/emberjs/ember.js/pull/15552) [FEATURE] Update blueprints and tests to RFC #176. | 1 |
Text | Text | fix changelog for csp pr [ci skip] | 5910c1d24107d7e5e0f43fb342c37bdb388e56bf | <ide><path>actionpack/CHANGELOG.md
<ide> about the Content-Security-Policy header see MDN:
<ide>
<ide> https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy
<del>
<add>
<ide> Example global policy:
<del>
<add>
<ide> # config/initializers/content_security_policy.rb
<del> Rails.application.config.content_security_policy do
<add> Rails.application.config.content_security_policy do |p|
<ide> p.default_src :self, :https
<ide> p.font_src :self, :https, :data
<ide> p.img_src :self, :https, :data
<ide> p.object_src :none
<ide> p.script_src :self, :https
<ide> p.style_src :self, :https, :unsafe_inline
<ide> end
<del>
<add>
<ide> Example controller overrides:
<del>
<add>
<ide> # Override policy inline
<ide> class PostsController < ApplicationController
<ide> content_security_policy do |p|
<ide> p.base_uri :self, -> { "https://#{current_user.domain}.example.com" }
<ide> end
<ide> end
<del>
<add>
<ide> Allows you to also only report content violations for migrating
<ide> legacy content using the `content_security_policy_report_only`
<ide> configuration attribute, e.g;
<del>
<add>
<ide> # config/initializers/content_security_policy.rb
<ide> Rails.application.config.content_security_policy_report_only = true
<del>
<add>
<ide> # controller override
<ide> class PostsController < ApplicationController
<ide> self.content_security_policy_report_only = true
<ide> end
<del>
<add>
<ide> Note that this feature does not validate the header for performance
<ide> reasons since the header is calculated at runtime.
<del>
<add>
<ide> *Andrew White*
<ide>
<ide> * Make `assert_recognizes` to traverse mounted engines | 1 |
Python | Python | add files via upload | 0e857d89053016397f1f339a2c9ec6729c5b0ce7 | <ide><path>dynamic_programming/max_sub_array.py
<add>"""
<add>author : Mayank Kumar Jha (mk9440)
<add>"""
<add>
<add>import time
<add>import matplotlib.pyplot as plt
<add>from random import randint
<add>def find_max_sub_array(A,low,high):
<add> if low==high:
<add> return low,high,A[low]
<add> else :
<add> mid=(low+high)//2
<add> left_low,left_high,left_sum=find_max_sub_array(A,low,mid)
<add> right_low,right_high,right_sum=find_max_sub_array(A,mid+1,high)
<add> cross_left,cross_right,cross_sum=find_max_cross_sum(A,low,mid,high)
<add> if left_sum>=right_sum and left_sum>=cross_sum:
<add> return left_low,left_high,left_sum
<add> elif right_sum>=left_sum and right_sum>=cross_sum :
<add> return right_low,right_high,right_sum
<add> else:
<add> return cross_left,cross_right,cross_sum
<add>
<add>def find_max_cross_sum(A,low,mid,high):
<add> left_sum,max_left=-999999999,-1
<add> right_sum,max_right=-999999999,-1
<add> summ=0
<add> for i in range(mid,low-1,-1):
<add> summ+=A[i]
<add> if summ > left_sum:
<add> left_sum=summ
<add> max_left=i
<add> summ=0
<add> for i in range(mid+1,high+1):
<add> summ+=A[i]
<add> if summ > right_sum:
<add> right_sum=summ
<add> max_right=i
<add> return max_left,max_right,(left_sum+right_sum)
<add>
<add>
<add>if __name__=='__main__':
<add> inputs=[10,100,1000,10000,50000,100000,200000,300000,400000,500000]
<add> tim=[]
<add> for i in inputs:
<add> li=[randint(1,i) for j in range(i)]
<add> strt=time.time()
<add> (find_max_sub_array(li,0,len(li)-1))
<add> end=time.time()
<add> tim.append(end-strt)
<add> print("No of Inputs Time Taken")
<add> for i in range(len(inputs)):
<add> print(inputs[i],'\t\t',tim[i])
<add> plt.plot(inputs,tim)
<add> plt.xlabel("Number of Inputs");plt.ylabel("Time taken in seconds ")
<add> plt.show()
<add>
<add>
<add>
<add> | 1 |
Text | Text | fix typo in active_job_basics.md | cdfecb800cf21ee988db8d47634c45a85a834e3c | <ide><path>guides/source/active_job_basics.md
<ide> class GuestsCleanupJob < ApplicationJob
<ide> #....
<ide> end
<ide>
<del># Now your job will use `resque` as it's backend queue adapter overriding what
<add># Now your job will use `resque` as its backend queue adapter overriding what
<ide> # was configured in `config.active_job.queue_adapter`.
<ide> ```
<ide> | 1 |
Ruby | Ruby | pass busy timeout for sqlite3 integration tests | f08bd27398f11420a2bae5ac0be5f169650683a6 | <ide><path>actionpack/test/active_record_unit.rb
<ide> def setup
<ide>
<ide> def setup_connection
<ide> if Object.const_defined?(:ActiveRecord)
<add> defaults = { :database => ':memory:' }
<ide> begin
<del> connection_options = {:adapter => 'sqlite3', :dbfile => ':memory:'}
<del> ActiveRecord::Base.establish_connection(connection_options)
<del> ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => connection_options }
<add> options = defaults.merge :adapter => 'sqlite3', :timeout => 500
<add> ActiveRecord::Base.establish_connection(options)
<add> ActiveRecord::Base.configurations = { 'sqlite3_ar_integration' => options }
<ide> ActiveRecord::Base.connection
<ide> rescue Exception # errors from establishing a connection
<ide> $stderr.puts 'SQLite 3 unavailable; trying SQLite 2.'
<del> connection_options = {:adapter => 'sqlite', :dbfile => ':memory:'}
<del> ActiveRecord::Base.establish_connection(connection_options)
<del> ActiveRecord::Base.configurations = { 'sqlite2_ar_integration' => connection_options }
<add> options = defaults.merge :adapter => 'sqlite'
<add> ActiveRecord::Base.establish_connection(options)
<add> ActiveRecord::Base.configurations = { 'sqlite2_ar_integration' => options }
<ide> ActiveRecord::Base.connection
<ide> end
<ide>
<ide> Object.send(:const_set, :QUOTED_TYPE, ActiveRecord::Base.connection.quote_column_name('type')) unless Object.const_defined?(:QUOTED_TYPE)
<ide> else
<del> raise "Couldn't locate ActiveRecord."
<add> raise "Can't setup connection since ActiveRecord isn't loaded."
<ide> end
<ide> end
<ide>
<ide> def require_fixture_models
<ide> end
<ide> end
<ide>
<del># Test case for inheiritance
<add># Test case for inheritance
<ide> class ActiveRecordTestCase < Test::Unit::TestCase
<ide> # Set our fixture path
<ide> if ActiveRecordTestConnector.able_to_connect | 1 |
PHP | PHP | add info about csrf protection technique used | e52cbce5e55493f75030e95bff43cbad7e61e0c3 | <ide><path>src/Http/Middleware/CsrfProtectionMiddleware.php
<ide> * Provides CSRF protection & validation.
<ide> *
<ide> * This middleware adds a CSRF token to a cookie. The cookie value is compared to
<del> * request data, or the X-CSRF-Token header on each PATCH, POST,
<del> * PUT, or DELETE request.
<add> * token in request data, or the X-CSRF-Token header on each PATCH, POST,
<add> * PUT, or DELETE request. This is known as "double submit cookie" technique.
<ide> *
<ide> * If the request data is missing or does not match the cookie data,
<ide> * an InvalidCsrfTokenException will be raised.
<ide> *
<ide> * This middleware integrates with the FormHelper automatically and when
<ide> * used together your forms will have CSRF tokens automatically added
<ide> * when `$this->Form->create(...)` is used in a view.
<add> *
<add> * @see https://cheatsheetseries.owasp.org/cheatsheets/Cross-Site_Request_Forgery_Prevention_Cheat_Sheet.html#double-submit-cookie
<ide> */
<ide> class CsrfProtectionMiddleware implements MiddlewareInterface
<ide> { | 1 |
PHP | PHP | remove tags for removed components | c8201ae8047306c1422dd0dfec09b19431228e03 | <ide><path>src/Controller/Controller.php
<ide> * Called after each action is complete and after the view is rendered.
<ide> *
<ide> * @property \Cake\Controller\Component\AuthComponent $Auth
<del> * @property \Cake\Controller\Component\CookieComponent $Cookie
<del> * @property \Cake\Controller\Component\CsrfComponent $Csrf
<ide> * @property \Cake\Controller\Component\FlashComponent $Flash
<ide> * @property \Cake\Controller\Component\PaginatorComponent $Paginator
<ide> * @property \Cake\Controller\Component\RequestHandlerComponent $RequestHandler | 1 |
Python | Python | add cinder support libcloud-874 | 1761c77c836faa0af53f390bc9ae012ab56e653b | <ide><path>libcloud/compute/drivers/openstack.py
<ide> class OpenStackNetworkConnection(OpenStackBaseConnection):
<ide> service_region = 'RegionOne'
<ide>
<ide>
<del>class OpenStackVolumeConnection(OpenStackBaseConnection):
<del> service_type = 'volume'
<add>class OpenStackVolumeV2Connection(OpenStackBaseConnection):
<add> service_type = 'volumev2'
<ide> service_name = 'cinder'
<ide> service_region = 'RegionOne'
<ide>
<ide> def encode_data(self, data):
<ide> return json.dumps(data)
<ide>
<ide>
<del>class OpenStack_2_VolumeConnection(OpenStackVolumeConnection):
<add>class OpenStack_2_VolumeV2Connection(OpenStackVolumeV2Connection):
<ide> responseCls = OpenStack_1_1_Response
<ide> accept_format = 'application/json'
<ide> default_content_type = 'application/json; charset=UTF-8'
<ide> class OpenStack_2_NodeDriver(OpenStack_1_1_NodeDriver):
<ide> # compute API
<ide> # See https://developer.openstack.org/api-ref/compute/
<ide> # For example, volume management are made in the cinder service
<del> volume_connectionCls = OpenStack_2_VolumeConnection
<del> volume_connection = None
<add> volumev2_connectionCls = OpenStack_2_VolumeV2Connection
<add> volumev2_connection = None
<ide>
<ide> type = Provider.OPENSTACK
<ide>
<ide> def __init__(self, *args, **kwargs):
<ide> self.image_connection = self.connection
<ide>
<ide> # We run the init once to get the Cinder V2 API connection
<del> # and put that on the object under self.volume_connection.
<add> # and put that on the object under self.volumev2_connection.
<ide> if original_ex_force_base_url or kwargs.get('ex_force_volume_url'):
<ide> kwargs['ex_force_base_url'] = \
<ide> str(kwargs.pop('ex_force_volume_url',
<ide> original_ex_force_base_url))
<del> self.connectionCls = self.volume_connectionCls
<add> self.connectionCls = self.volumev2_connectionCls
<ide> super(OpenStack_2_NodeDriver, self).__init__(*args, **kwargs)
<del> self.volume_connection = self.connection
<add> self.volumev2_connection = self.connection
<ide>
<ide> # We run the init once to get the Neutron V2 API connection
<ide> # and put that on the object under self.network_connection. | 1 |
PHP | PHP | remove unused variables | 4d305df1a0f00e90553d34370aef3249236a650b | <ide><path>src/Controller/Component/RequestHandlerComponent.php
<ide> public function respondAs($type, array $options = []): bool
<ide> $cType = $type;
<ide> $controller = $this->getController();
<ide> $response = $controller->getResponse();
<del> $request = $controller->getRequest();
<ide>
<ide> if (strpos($type, '/') === false) {
<ide> $cType = $response->getMimeType($type);
<ide><path>src/Database/Type/DateTimeType.php
<ide> public function marshal($value): ?DateTimeInterface
<ide>
<ide> $class = $this->_className;
<ide> try {
<del> $compare = $date = false;
<add> $date = false;
<ide> if ($value === '' || $value === null || $value === false || $value === true) {
<ide> return null;
<ide> } | 2 |
Ruby | Ruby | fix typo in test | 469befa7efd20860dd48a9bf8a87f1d7c955e09d | <ide><path>activesupport/test/callbacks_test.rb
<ide> def test_save
<ide>
<ide> class PerKeyOptionDeprecationTest < ActiveSupport::TestCase
<ide>
<del> def test_per_key_option_deprecaton
<add> def test_per_key_option_deprecation
<ide> assert_raise NotImplementedError do
<ide> Phone.class_eval do
<ide> set_callback :save, :before, :before_save1, :per_key => {:if => "true"} | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.