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
|
|---|---|---|---|---|---|
Javascript
|
Javascript
|
fix merge issue
|
114abeeb4d1023b3da8f5ac22686c83ff78356a7
|
<ide><path>lib/optimize/EnsureChunkConditionsPlugin.js
<ide> class EnsureChunkConditionsPlugin {
<ide> let changed = false;
<ide> chunks.forEach((chunk) => {
<ide> for(const module of chunk.modulesIterable) {
<del> if(!module.chunkCondition) return;
<add> if(!module.chunkCondition) continue;
<ide> if(!module.chunkCondition(chunk)) {
<ide> let usedChunks = triesMap.get(module);
<ide> if(!usedChunks) triesMap.set(module, usedChunks = new Set());
| 1
|
Ruby
|
Ruby
|
handle url with specs hash
|
283ff9e3adef34fb8d53063fbd5a3f2e3ac64c92
|
<ide><path>Library/Homebrew/dev-cmd/bump-formula-pr.rb
<ide> def bump_formula_pr
<ide>
<ide> if new_mirrors.present?
<ide> replacement_pairs << [
<del> /^( +)(url "#{Regexp.escape(new_url)}"\n)/m,
<add> /^( +)(url "#{Regexp.escape(new_url)}"[^\n]*?\n)/m,
<ide> "\\1\\2\\1mirror \"#{new_mirrors.join("\"\n\\1mirror \"")}\"\n",
<ide> ]
<ide> end
<ide> def bump_formula_pr
<ide> ]
<ide> elsif new_url.present?
<ide> [
<del> /^( +)(url "#{Regexp.escape(new_url)}"\n)/m,
<add> /^( +)(url "#{Regexp.escape(new_url)}"[^\n]*?\n)/m,
<ide> "\\1\\2\\1version \"#{new_version}\"\n",
<ide> ]
<ide> elsif new_revision.present?
| 1
|
Javascript
|
Javascript
|
add tests to callbacks of the life cycles
|
fd077d7492ae9398d596ba34352f79114e73fa87
|
<ide><path>src/core/__tests__/ReactCompositeComponentState-test.js
<ide> describe('ReactCompositeComponent-state', function() {
<ide> }
<ide> },
<ide>
<add> peekAtCallback: function(from) {
<add> return () => this.peekAtState(from);
<add> },
<add>
<ide> setFavoriteColor: function(nextColor) {
<del> this.setState({color: nextColor});
<add> this.setState(
<add> {color: nextColor},
<add> this.peekAtCallback('setFavoriteColor')
<add> );
<ide> },
<ide>
<ide> getInitialState: function() {
<ide> describe('ReactCompositeComponent-state', function() {
<ide>
<ide> componentWillMount: function() {
<ide> this.peekAtState('componentWillMount-start');
<del> this.setState({color: 'sunrise'});
<add> this.setState(
<add> {color: 'sunrise'},
<add> this.peekAtCallback('setState-sunrise')
<add> );
<ide> this.peekAtState('componentWillMount-after-sunrise');
<del> this.setState({color: 'orange'});
<add> this.setState(
<add> {color: 'orange'},
<add> this.peekAtCallback('setState-orange')
<add> );
<ide> this.peekAtState('componentWillMount-end');
<ide> },
<ide>
<ide> componentDidMount: function() {
<ide> this.peekAtState('componentDidMount-start');
<del> this.setState({color: 'yellow'});
<add> this.setState(
<add> {color: 'yellow'},
<add> this.peekAtCallback('setState-yellow')
<add> );
<ide> this.peekAtState('componentDidMount-end');
<ide> },
<ide>
<ide> componentWillReceiveProps: function(newProps) {
<ide> this.peekAtState('componentWillReceiveProps-start');
<ide> if (newProps.nextColor) {
<del> this.setState({color: newProps.nextColor});
<add> this.setState(
<add> {color: newProps.nextColor},
<add> this.peekAtCallback('setState-receiveProps')
<add> );
<ide> }
<ide> this.peekAtState('componentWillReceiveProps-end');
<ide> },
<ide> describe('ReactCompositeComponent-state', function() {
<ide> document.documentElement.appendChild(container);
<ide>
<ide> var stateListener = mocks.getMockFunction();
<del> var instance = <TestComponent stateListener={stateListener} />;
<del> instance = React.render(instance, container);
<del> instance.setProps({nextColor: 'green'});
<add> var instance = React.render(
<add> <TestComponent stateListener={stateListener} />,
<add> container,
<add> function peekAtInitialCallback() {
<add> this.peekAtState('initial-callback');
<add> }
<add> );
<add> instance.setProps(
<add> {nextColor: 'green'},
<add> instance.peekAtCallback('setProps')
<add> );
<ide> instance.setFavoriteColor('blue');
<del> instance.forceUpdate();
<add> instance.forceUpdate(instance.peekAtCallback('forceUpdate'));
<ide>
<ide> React.unmountComponentAtNode(container);
<ide>
<ide> describe('ReactCompositeComponent-state', function() {
<ide> // pending state has been applied
<ide> [ 'render', 'orange', null ],
<ide> [ 'componentDidMount-start', 'orange', null ],
<add> // setState-sunrise and setState-orange should be called here,
<add> // after the bug in #
<ide> // componentDidMount() called setState({color:'yellow'}), currently this
<ide> // occurs inline.
<ide> // In a future where setState() is async, this test result will change.
<ide> describe('ReactCompositeComponent-state', function() {
<ide> [ 'render', 'yellow', null ],
<ide> [ 'componentDidUpdate-currentState', 'yellow', null ],
<ide> [ 'componentDidUpdate-prevState', 'orange' ],
<add> [ 'setState-yellow', 'yellow', null ],
<ide> // componentDidMount() finally closes.
<ide> [ 'componentDidMount-end', 'yellow', null ],
<add> [ 'initial-callback', 'yellow', null ],
<ide> [ 'componentWillReceiveProps-start', 'yellow', null ],
<ide> // setState({color:'green'}) only enqueues a pending state.
<ide> [ 'componentWillReceiveProps-end', 'yellow', 'green' ],
<ide> describe('ReactCompositeComponent-state', function() {
<ide> [ 'render', 'green', null ],
<ide> [ 'componentDidUpdate-currentState', 'green', null ],
<ide> [ 'componentDidUpdate-prevState', 'yellow' ],
<add> [ 'setState-receiveProps', 'green', null ],
<add> [ 'setProps', 'green', null ],
<ide> // setFavoriteColor('blue')
<ide> [ 'shouldComponentUpdate-currentState', 'green', null ],
<ide> [ 'shouldComponentUpdate-nextState', 'blue' ],
<ide> describe('ReactCompositeComponent-state', function() {
<ide> [ 'render', 'blue', null ],
<ide> [ 'componentDidUpdate-currentState', 'blue', null ],
<ide> [ 'componentDidUpdate-prevState', 'green' ],
<add> [ 'setFavoriteColor', 'blue', null ],
<ide> // forceUpdate()
<ide> [ 'componentWillUpdate-currentState', 'blue', null ],
<ide> [ 'componentWillUpdate-nextState', 'blue' ],
<ide> [ 'render', 'blue', null ],
<ide> [ 'componentDidUpdate-currentState', 'blue', null ],
<ide> [ 'componentDidUpdate-prevState', 'blue' ],
<add> [ 'forceUpdate', 'blue', null ],
<ide> // unmountComponent()
<ide> // state is available within `componentWillUnmount()`
<ide> [ 'componentWillUnmount', 'blue', null ]
| 1
|
Javascript
|
Javascript
|
add flowtests for hostcomponent
|
79e08f3c15e155ac077be1811c785d201df76a7f
|
<ide><path>Libraries/Renderer/__flowtests__/ReactNativeTypes-flowtest.js
<add>/**
<add> * Copyright (c) Facebook, Inc. and its affiliates.
<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> * @format
<add> */
<add>
<add>'use strict';
<add>
<add>import * as React from 'react';
<add>import type {
<add> HostComponent,
<add> ReactNativeComponentClass_ForTestsOnly,
<add>} from '../shims/ReactNativeTypes';
<add>
<add>function takesHostComponentInstance(
<add> instance: React$ElementRef<HostComponent<mixed>> | null,
<add>): void {}
<add>
<add>const MyHostComponent = (('Host': any): HostComponent<mixed>);
<add>
<add><MyHostComponent
<add> ref={hostComponentRef => {
<add> takesHostComponentInstance(hostComponentRef);
<add>
<add> if (hostComponentRef == null) {
<add> return;
<add> }
<add>
<add> hostComponentRef.measureLayout(hostComponentRef, () => {});
<add> }}
<add>/>;
<add>
<add>declare var NativeComponent: ReactNativeComponentClass_ForTestsOnly<{}>;
<add>class MyNativeComponent extends NativeComponent {}
<add>
<add><MyNativeComponent
<add> ref={nativeComponentRef => {
<add> // $FlowExpectedError - NativeComponent cannot be passed as HostComponent.
<add> takesHostComponentInstance(nativeComponentRef);
<add>
<add> if (nativeComponentRef == null) {
<add> return;
<add> }
<add>
<add> // $FlowExpectedError - NativeComponent cannot be passed as HostComponent.
<add> nativeComponentRef.measureLayout(nativeComponentRef, () => {});
<add> }}
<add>/>;
<ide><path>Libraries/Renderer/shims/ReactNativeTypes.js
<ide> class ReactNativeComponent<Props> extends React.Component<Props> {
<ide> setNativeProps(nativeProps: Object): void {}
<ide> }
<ide>
<add>// This type is only used for FlowTests. It shouldn't be imported directly
<add>export type ReactNativeComponentClass_ForTestsOnly<Props> = Class<
<add> ReactNativeComponent<Props>,
<add>>;
<add>
<ide> /**
<ide> * This type keeps HostComponent and NativeMethodsMixin in sync.
<ide> * It can also provide types for ReactNative applications that use NMM or refs.
| 2
|
Ruby
|
Ruby
|
enhance errors while retrieving database config
|
7d6592ebd0b04aab2415fce8098e21212bc8c5c3
|
<ide><path>railties/lib/rails/application/configuration.rb
<ide> def database_configuration
<ide> raise "YAML syntax error occurred while parsing #{paths["config/database"].first}. " \
<ide> "Please note that YAML must be consistently indented using spaces. Tabs are not allowed. " \
<ide> "Error: #{e.message}"
<add> rescue => e
<add> raise e, "Cannot load `Rails.application.database_configuration`:\n#{e.message}", e.backtrace
<ide> end
<ide>
<ide> def log_level
| 1
|
Javascript
|
Javascript
|
fix parser double-free in _http_client.js
|
5ce4eed54dceb15c34d3508e733124edd282601b
|
<ide><path>lib/_http_client.js
<ide> function createHangUpError() {
<ide>
<ide> function socketCloseListener() {
<ide> var socket = this;
<del> var parser = socket.parser;
<ide> var req = socket._httpMessage;
<ide> debug('HTTP socket close');
<ide>
<ide> function socketCloseListener() {
<ide> // is a no-op if no final chunk remains.
<ide> socket.read();
<ide>
<add> // NOTE: Its important to get parser here, because it could be freed by
<add> // the `socketOnData`.
<add> var parser = socket.parser;
<ide> req.emit('close');
<ide> if (req.res && req.res.readable) {
<ide> // Socket closed before we emitted 'end' below.
<ide> function socketOnData(d) {
<ide> var req = this._httpMessage;
<ide> var parser = this.parser;
<ide>
<del> assert(parser);
<add> assert(parser && parser.socket === socket);
<ide>
<ide> var ret = parser.execute(d);
<ide> if (ret instanceof Error) {
<ide><path>test/simple/test-http-client-parser-double-free.js
<add>// Copyright Joyent, Inc. and other Node contributors.
<add>//
<add>// Permission is hereby granted, free of charge, to any person obtaining a
<add>// copy of this software and associated documentation files (the
<add>// "Software"), to deal in the Software without restriction, including
<add>// without limitation the rights to use, copy, modify, merge, publish,
<add>// distribute, sublicense, and/or sell copies of the Software, and to permit
<add>// persons to whom the Software is furnished to do so, subject to the
<add>// following conditions:
<add>//
<add>// The above copyright notice and this permission notice shall be included
<add>// in all copies or substantial portions of the Software.
<add>//
<add>// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
<add>// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
<add>// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
<add>// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
<add>// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
<add>// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
<add>// USE OR OTHER DEALINGS IN THE SOFTWARE.
<add>
<add>var common = require('../common');
<add>var assert = require('assert');
<add>var http = require('http');
<add>var http_common = require('_http_common');
<add>
<add>var receivedError = 0;
<add>var receivedClose = 0;
<add>
<add>var buf = new Buffer(64 * 1024);
<add>buf.fill('A');
<add>
<add>var server = http.createServer(function(req, res) {
<add> res.write(buf, function() {
<add> res.socket.write(buf);
<add> res.end(function() {
<add> req.socket.destroy();
<add> server.close();
<add> });
<add> });
<add>}).listen(common.PORT, function() {
<add> var req = http.request({ port: common.PORT, agent: false }, function(res) {
<add> res.once('readable', function() {
<add> /* read only one buffer */
<add> res.read(1);
<add> });
<add> });
<add> req.end();
<add> req.on('close', function() {
<add> receivedClose++;
<add> });
<add> req.on('error', function() {
<add> receivedError++;
<add> });
<add>});
<add>
<add>process.on('exit', function() {
<add> assert.equal(receivedError, 1);
<add> assert.equal(receivedClose, 1);
<add> assert.equal(http_common.parsers.list.length, 2);
<add>});
| 2
|
Javascript
|
Javascript
|
simplify import paths
|
07ce117b56ee4aa0f22f5d64a733c716836b1b48
|
<ide><path>src/utils/bindActionCreators.js
<del>import mapValues from '../utils/mapValues'
<add>import mapValues from './mapValues'
<ide>
<ide> function bindActionCreator(actionCreator, dispatch) {
<ide> return (...args) => dispatch(actionCreator(...args))
<ide><path>src/utils/combineReducers.js
<ide> import { ActionTypes } from '../createStore'
<del>import isPlainObject from '../utils/isPlainObject'
<del>import mapValues from '../utils/mapValues'
<del>import pick from '../utils/pick'
<add>import isPlainObject from './isPlainObject'
<add>import mapValues from './mapValues'
<add>import pick from './pick'
<ide>
<ide> /* eslint-disable no-console */
<ide>
| 2
|
Javascript
|
Javascript
|
move fs-readfile.js to fs/readfile.js
|
6d116be7cf26abf3a4940e9e75ec329248de96d8
|
<ide><path>benchmark/fs-readfile.js
<del>// Call fs.readFile over and over again really fast.
<del>// Then see how many times it got called.
<del>// Yes, this is a silly benchmark. Most benchmarks are silly.
<del>
<del>var path = require('path');
<del>var filename = path.resolve(__dirname, 'http.sh');
<del>var fs = require('fs');
<del>var count = 0;
<del>var go = true;
<del>var len = -1;
<del>var assert = require('assert');
<del>
<del>var concurrency = 1;
<del>var encoding = null;
<del>var time = 10;
<del>
<del>for (var i = 2; i < process.argv.length; i++) {
<del> var arg = process.argv[i];
<del> if (arg.match(/^-e$/)) {
<del> encoding = process.argv[++i] || null;
<del> } else if (arg.match(/^-c$/)) {
<del> concurrency = ~~process.argv[++i];
<del> if (concurrency < 1) concurrency = 1;
<del> } else if (arg === '-t') {
<del> time = ~~process.argv[++i];
<del> if (time < 1) time = 1;
<del> }
<del>}
<del>
<del>
<del>setTimeout(function() {
<del> go = false;
<del>}, time * 1000);
<del>
<del>function round(n) {
<del> return Math.floor(n * 100) / 100;
<del>}
<del>
<del>var start = process.hrtime();
<del>while (concurrency--) readFile();
<del>
<del>function readFile() {
<del> if (!go) {
<del> process.stdout.write('\n');
<del> console.log('read the file %d times (higher is better)', count);
<del> var end = process.hrtime();
<del> var elapsed = [end[0] - start[0], end[1] - start[1]];
<del> var ns = elapsed[0] * 1E9 + elapsed[1];
<del> var nsper = round(ns / count);
<del> console.log('%d ns per read (lower is better)', nsper);
<del> var readsper = round(count / (ns / 1E9));
<del> console.log('%d reads per sec (higher is better)', readsper);
<del> process.exit(0);
<del> return;
<del> }
<del>
<del> if (!(count % 1000)) {
<del> process.stdout.write('.');
<del> }
<del>
<del> if (encoding) fs.readFile(filename, encoding, then);
<del> else fs.readFile(filename, then);
<del>
<del> function then(er, data) {
<del> assert.ifError(er);
<del> count++;
<del> // basic sanity test: we should get the same number of bytes each time.
<del> if (count === 1) len = data.length;
<del> else assert(len === data.length);
<del> readFile();
<del> }
<del>}
<ide><path>benchmark/fs/readfile.js
<add>// Call fs.readFile over and over again really fast.
<add>// Then see how many times it got called.
<add>// Yes, this is a silly benchmark. Most benchmarks are silly.
<add>
<add>var path = require('path');
<add>var common = require('../common.js');
<add>var filename = path.resolve(__dirname, '.removeme-benchmark-garbage');
<add>var fs = require('fs');
<add>
<add>var bench = common.createBenchmark(main, {
<add> dur: [1, 3],
<add> len: [1024, 16 * 1024 * 1024],
<add> concurrent: [1, 10]
<add>});
<add>
<add>function main(conf) {
<add> var len = +conf.len;
<add> try { fs.unlinkSync(filename); } catch (e) {}
<add> var data = new Buffer(len);
<add> data.fill('x');
<add> fs.writeFileSync(filename, data);
<add> data = null;
<add>
<add> var reads = 0;
<add> bench.start();
<add> setTimeout(function() {
<add> bench.end(reads);
<add> try { fs.unlinkSync(filename); } catch (e) {}
<add> }, +conf.dur * 1000);
<add>
<add> function read() {
<add> fs.readFile(filename, afterRead);
<add> }
<add>
<add> function afterRead(er, data) {
<add> if (er)
<add> throw er;
<add>
<add> if (data.length !== len)
<add> throw new Error('wrong number of bytes returned');
<add>
<add> reads++;
<add> read();
<add> }
<add>
<add> var cur = +conf.concurrent;
<add> while (cur--) read();
<add>}
| 2
|
Ruby
|
Ruby
|
update reverse order with new arel nodes
|
2e0840dd0450b883800d6115a18d8867159c9812
|
<ide><path>activerecord/lib/active_record/relation/query_methods.rb
<ide> def reverse_sql_order(order_query)
<ide>
<ide> order_query.map do |o|
<ide> case o
<del> when Arel::Nodes::Ordering
<add> when Arel::Nodes::Ascending
<add> when Arel::Nodes::Descending
<ide> o.reverse
<ide> when String, Symbol
<ide> o.to_s.split(',').collect do |s|
| 1
|
Text
|
Text
|
fix references to transformerlistener
|
28e4ba72702485d5379309967bc751b5d6f48a9f
|
<ide><path>website/docs/usage/embeddings-transformers.md
<ide> def configure_custom_sent_spans(max_length: int):
<ide> start += max_length
<ide> end += max_length
<ide> if start < len(sent):
<del> spans[-1].append(sent[start : len(sent)])
<add> spans[-1].append(sent[start:len(sent)])
<ide> return spans
<ide>
<ide> return get_custom_sent_spans
<ide> The same idea applies to task models that power the **downstream components**.
<ide> Most of spaCy's built-in model creation functions support a `tok2vec` argument,
<ide> which should be a Thinc layer of type ~~Model[List[Doc], List[Floats2d]]~~. This
<ide> is where we'll plug in our transformer model, using the
<del>[Tok2VecListener](/api/architectures#Tok2VecListener) layer, which sneakily
<add>[TransformerListener](/api/architectures#TransformerListener) layer, which sneakily
<ide> delegates to the `Transformer` pipeline component.
<ide>
<ide> ```ini
<ide> maxout_pieces = 3
<ide> use_upper = false
<ide>
<ide> [nlp.pipeline.ner.model.tok2vec]
<del>@architectures = "spacy-transformers.Tok2VecListener.v1"
<add>@architectures = "spacy-transformers.TransformerListener.v1"
<ide> grad_factor = 1.0
<ide>
<ide> [nlp.pipeline.ner.model.tok2vec.pooling]
<ide> @layers = "reduce_mean.v1"
<ide> ```
<ide>
<del>The [Tok2VecListener](/api/architectures#Tok2VecListener) layer expects a
<add>The [TransformerListener](/api/architectures#TransformerListener) layer expects a
<ide> [pooling layer](https://thinc.ai/docs/api-layers#reduction-ops) as the argument
<ide> `pooling`, which needs to be of type ~~Model[Ragged, Floats2d]~~. This layer
<ide> determines how the vector for each spaCy token will be computed from the zero or
| 1
|
Ruby
|
Ruby
|
remove extra `homebrew_no_dev_cmd_message` line
|
81d89803db83510f58360993176c3719449364c6
|
<ide><path>Library/Homebrew/dev-cmd/tests.rb
<ide> def tests
<ide> ENV.delete(env)
<ide> end
<ide>
<del> ENV["HOMEBREW_NO_DEV_CMD_MESSAGE"] = "1"
<ide> ENV["HOMEBREW_NO_ANALYTICS_THIS_RUN"] = "1"
<ide> ENV["HOMEBREW_NO_COMPAT"] = "1" if args.no_compat?
<ide> ENV["HOMEBREW_TEST_GENERIC_OS"] = "1" if args.generic?
| 1
|
Go
|
Go
|
move the makeprivate to pkg/mount
|
930a756ad55ad5f4e5e6391b41673743d7254c2b
|
<ide><path>daemon/graphdriver/aufs/aufs.go
<ide> func Init(root string, options []string) (graphdriver.Driver, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if err := graphdriver.MakePrivate(root); err != nil {
<add> if err := mountpk.MakePrivate(root); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>daemon/graphdriver/btrfs/btrfs.go
<ide> func Init(home string, options []string) (graphdriver.Driver, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if err := graphdriver.MakePrivate(home); err != nil {
<add> if err := mount.MakePrivate(home); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>daemon/graphdriver/devmapper/driver.go
<ide> func Init(home string, options []string) (graphdriver.Driver, error) {
<ide> return nil, err
<ide> }
<ide>
<del> if err := graphdriver.MakePrivate(home); err != nil {
<add> if err := mount.MakePrivate(home); err != nil {
<ide> return nil, err
<ide> }
<ide>
<ide><path>daemon/graphdriver/driver.go
<ide> import (
<ide> "path"
<ide>
<ide> "github.com/docker/docker/pkg/archive"
<del> "github.com/docker/docker/pkg/mount"
<ide> )
<ide>
<ide> type FsMagic uint64
<ide> func New(root string, options []string) (driver Driver, err error) {
<ide> }
<ide> return nil, fmt.Errorf("No supported storage backend found")
<ide> }
<del>
<del>func MakePrivate(mountPoint string) error {
<del> mounted, err := mount.Mounted(mountPoint)
<del> if err != nil {
<del> return err
<del> }
<del>
<del> if !mounted {
<del> if err := mount.Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil {
<del> return err
<del> }
<del> }
<del>
<del> return mount.ForceMount("", mountPoint, "none", "private")
<del>}
<ide><path>pkg/mount/sharedsubtree_linux.go
<add>// +build linux
<add>
<add>package mount
<add>
<add>func MakePrivate(mountPoint string) error {
<add> mounted, err := Mounted(mountPoint)
<add> if err != nil {
<add> return err
<add> }
<add>
<add> if !mounted {
<add> if err := Mount(mountPoint, mountPoint, "none", "bind,rw"); err != nil {
<add> return err
<add> }
<add> }
<add>
<add> return ForceMount("", mountPoint, "none", "private")
<add>}
| 5
|
Go
|
Go
|
fix a typos in layer_windows.go
|
7c5cf583280aad6f38311e88d58d7aaec0bfa90e
|
<ide><path>layer/layer_windows.go
<ide> import (
<ide> // Getter is an interface to get the path to a layer on the host.
<ide> type Getter interface {
<ide> // GetLayerPath gets the path for the layer. This is different from Get()
<del> // since that returns an interface to account for umountable layers.
<add> // since that returns an interface to account for unmountable layers.
<ide> GetLayerPath(id string) (string, error)
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
add default utf-8 charset. (#270)
|
e0455823a0388ce2e9c96472c7ed393d821389f4
|
<ide><path>lib/head.js
<ide> class Head extends React.Component {
<ide> }
<ide> }
<ide>
<add>export function defaultHead () {
<add> return [<meta charSet='utf-8' className='next-head' />]
<add>}
<add>
<ide> function reduceComponents (components) {
<ide> return components
<ide> .map((c) => c.props.children)
<ide> .filter((c) => !!c)
<ide> .map((children) => React.Children.toArray(children))
<ide> .reduce((a, b) => a.concat(b), [])
<ide> .reverse()
<add> .concat(...defaultHead())
<ide> .filter(unique())
<ide> .reverse()
<ide> .map((c) => {
<ide><path>server/render.js
<ide> import read from './read'
<ide> import getConfig from './config'
<ide> import Router from '../lib/router'
<ide> import Document from '../lib/document'
<del>import Head from '../lib/head'
<add>import Head, {defaultHead} from '../lib/head'
<ide> import App from '../lib/app'
<ide>
<ide> export async function render (url, ctx = {}, {
<ide> export async function render (url, ctx = {}, {
<ide> return (staticMarkup ? renderToStaticMarkup : renderToString)(app)
<ide> })
<ide>
<del> const head = Head.rewind() || []
<add> const head = Head.rewind() || defaultHead()
<ide> const config = await getConfig(dir)
<ide>
<ide> const doc = createElement(Document, {
<ide><path>test/fixtures/basic/pages/head.js
<ide> import Head from 'next/head'
<ide>
<ide> export default () => <div>
<ide> <Head>
<add> <meta charSet='iso-8859-5' />
<ide> <meta content='my meta' />
<ide> </Head>
<ide> <h1>I can haz meta tags</h1>
<ide><path>test/index.js
<ide> test.before(() => build(dir))
<ide>
<ide> test(async t => {
<ide> const html = await render('/stateless')
<add> t.true(html.includes('<meta charset="utf-8" class="next-head"/>'))
<ide> t.true(html.includes('<h1>My component!</h1>'))
<ide> })
<ide>
<ide> test(async t => {
<ide>
<ide> test(async t => {
<ide> const html = await (render('/head'))
<add> t.true(html.includes('<meta charset="iso-8859-5" class="next-head"/>'))
<ide> t.true(html.includes('<meta content="my meta" class="next-head"/>'))
<ide> t.true(html.includes('<div><h1>I can haz meta tags</h1></div>'))
<ide> })
| 4
|
Ruby
|
Ruby
|
fix test_env on 10.7/xcode 4
|
0e2258f0fa6f94d43f9e0991f2da250c0f655e4f
|
<ide><path>Library/Homebrew/test/test_ENV.rb
<ide> class EnvironmentTests < Test::Unit::TestCase
<ide> def test_ENV_options
<ide> ENV.gcc_4_0
<del> ENV.gcc_4_2
<add> begin
<add> ENV.gcc_4_2
<add> rescue RuntimeError => e
<add> if `sw_vers -productVersion` =~ /10\.(\d+)/ and $1.to_i < 7
<add> raise e
<add> end
<add> end
<ide> ENV.O3
<ide> ENV.minimal_optimization
<ide> ENV.no_optimization
| 1
|
Text
|
Text
|
eliminate use of "note that" from child_process.md
|
921f448d0de5dcbca21dba100e7df2ac08c7fcb0
|
<ide><path>doc/api/child_process.md
<ide> the event loop until the spawned process either exits or is terminated.
<ide>
<ide> For convenience, the `child_process` module provides a handful of synchronous
<ide> and asynchronous alternatives to [`child_process.spawn()`][] and
<del>[`child_process.spawnSync()`][]. Note that each of these alternatives are
<del>implemented on top of [`child_process.spawn()`][] or
<del>[`child_process.spawnSync()`][].
<add>[`child_process.spawnSync()`][]. Each of these alternatives are implemented on
<add>top of [`child_process.spawn()`][] or [`child_process.spawnSync()`][].
<ide>
<ide> * [`child_process.exec()`][]: spawns a shell and runs a command within that
<ide> shell, passing the `stdout` and `stderr` to a callback function when
<ide> its own console window. Once enabled for a child process, it cannot be
<ide> disabled.
<ide>
<ide> On non-Windows platforms, if `options.detached` is set to `true`, the child
<del>process will be made the leader of a new process group and session. Note that
<del>child processes may continue running after the parent exits regardless of
<del>whether they are detached or not. See setsid(2) for more information.
<add>process will be made the leader of a new process group and session. Child
<add>processes may continue running after the parent exits regardless of whether
<add>they are detached or not. See setsid(2) for more information.
<ide>
<ide> By default, the parent will wait for the detached child to exit. To prevent the
<ide> parent from waiting for a given `subprocess` to exit, use the
<ide> pipes between the parent and child. The value is one of the following:
<ide> 5. {Stream} object - Share a readable or writable stream that refers to a tty,
<ide> file, socket, or a pipe with the child process. The stream's underlying
<ide> file descriptor is duplicated in the child process to the fd that
<del> corresponds to the index in the `stdio` array. Note that the stream must
<del> have an underlying descriptor (file streams do not until the `'open'`
<del> event has occurred).
<add> corresponds to the index in the `stdio` array. The stream must have an
<add> underlying descriptor (file streams do not until the `'open'` event has
<add> occurred).
<ide> 6. Positive integer - The integer value is interpreted as a file descriptor
<ide> that is currently open in the parent process. It is shared with the child
<ide> process, similar to how {Stream} objects can be shared.
<ide> The `child_process.execSync()` method is generally identical to
<ide> [`child_process.exec()`][] with the exception that the method will not return
<ide> until the child process has fully closed. When a timeout has been encountered
<ide> and `killSignal` is sent, the method won't return until the process has
<del>completely exited. Note that if the child process intercepts and handles the
<del>`SIGTERM` signal and doesn't exit, the parent process will wait until the child
<del>process has exited.
<add>completely exited. If the child process intercepts and handles the `SIGTERM`
<add>signal and doesn't exit, the parent process will wait until the child process
<add>has exited.
<ide>
<ide> If the process times out or has a non-zero exit code, this method will throw.
<ide> The [`Error`][] object will contain the entire result from
<ide> The `child_process.spawnSync()` method is generally identical to
<ide> [`child_process.spawn()`][] with the exception that the function will not return
<ide> until the child process has fully closed. When a timeout has been encountered
<ide> and `killSignal` is sent, the method won't return until the process has
<del>completely exited. Note that if the process intercepts and handles the
<del>`SIGTERM` signal and doesn't exit, the parent process will wait until the child
<del>process has exited.
<add>completely exited. If the process intercepts and handles the `SIGTERM` signal
<add>and doesn't exit, the parent process will wait until the child process has
<add>exited.
<ide>
<ide> **If the `shell` option is enabled, do not pass unsanitized user input to this
<ide> function. Any input containing shell metacharacters may be used to trigger
<ide> exited, `code` is the final exit code of the process, otherwise `null`. If the
<ide> process terminated due to receipt of a signal, `signal` is the string name of
<ide> the signal, otherwise `null`. One of the two will always be non-null.
<ide>
<del>Note that when the `'exit'` event is triggered, child process stdio streams
<del>might still be open.
<add>When the `'exit'` event is triggered, child process stdio streams might still be
<add>open.
<ide>
<del>Also, note that Node.js establishes signal handlers for `SIGINT` and
<del>`SIGTERM` and Node.js processes will not terminate immediately due to receipt
<del>of those signals. Rather, Node.js will perform a sequence of cleanup actions
<del>and then will re-raise the handled signal.
<add>Node.js establishes signal handlers for `SIGINT` and `SIGTERM` and Node.js
<add>processes will not terminate immediately due to receipt of those signals.
<add>Rather, Node.js will perform a sequence of cleanup actions and then will
<add>re-raise the handled signal.
<ide>
<ide> See waitpid(2).
<ide>
<ide> The `'disconnect'` event will be emitted when there are no messages in the
<ide> process of being received. This will most often be triggered immediately after
<ide> calling `subprocess.disconnect()`.
<ide>
<del>Note that when the child process is a Node.js instance (e.g. spawned using
<add>When the child process is a Node.js instance (e.g. spawned using
<ide> [`child_process.fork()`]), the `process.disconnect()` method can be invoked
<ide> within the child process to close the IPC channel as well.
<ide>
<ide> is not an error but may have unforeseen consequences. Specifically, if the
<ide> process identifier (PID) has been reassigned to another process, the signal will
<ide> be delivered to that process instead which can have unexpected results.
<ide>
<del>Note that while the function is called `kill`, the signal delivered to the
<del>child process may not actually terminate the process.
<add>While the function is called `kill`, the signal delivered to the child process
<add>may not actually terminate the process.
<ide>
<ide> See kill(2) for reference.
<ide>
<ide> added: v0.1.90
<ide>
<ide> A `Writable Stream` that represents the child process's `stdin`.
<ide>
<del>Note that if a child process waits to read all of its input, the child will not
<del>continue until this stream has been closed via `end()`.
<add>If a child process waits to read all of its input, the child will not continue
<add>until this stream has been closed via `end()`.
<ide>
<ide> If the child was spawned with `stdio[0]` set to anything other than `'pipe'`,
<ide> then this will be `null`.
<ide> added: v0.7.10
<ide>
<ide> A sparse array of pipes to the child process, corresponding with positions in
<ide> the [`stdio`][] option passed to [`child_process.spawn()`][] that have been set
<del>to the value `'pipe'`. Note that `subprocess.stdio[0]`, `subprocess.stdio[1]`,
<del>and `subprocess.stdio[2]` are also available as `subprocess.stdin`,
<add>to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and
<add>`subprocess.stdio[2]` are also available as `subprocess.stdin`,
<ide> `subprocess.stdout`, and `subprocess.stderr`, respectively.
<ide>
<ide> In the following example, only the child's fd `1` (stdout) is configured as a
| 1
|
Go
|
Go
|
fix golint nit in term_windows.go
|
35e498beca13de4ef8cecf45c0d132cc38daf0d5
|
<ide><path>pkg/term/term_windows.go
<ide> func SetWinsize(fd uintptr, ws *Winsize) error {
<ide> }
<ide>
<ide> // Narrow the sizes to that used by Windows
<del> var width winterm.SHORT = winterm.SHORT(ws.Width)
<del> var height winterm.SHORT = winterm.SHORT(ws.Height)
<add> width := winterm.SHORT(ws.Width)
<add> height := winterm.SHORT(ws.Height)
<ide>
<ide> // Set the dimensions while ensuring they remain within the bounds of the backing console buffer
<ide> // -- Shrinking will always succeed. Growing may push the edges past the buffer boundary. When that occurs,
| 1
|
Javascript
|
Javascript
|
fix a typo in the warning header
|
90f947b18699d0fd93a2fdb8c7167e128587afec
|
<ide><path>src/ng/compile.js
<ide> * *
<ide> * Does the change somehow allow for arbitrary javascript to be executed? *
<ide> * Or allows for someone to change the prototype of built-in objects? *
<del> * Or gives undesired access to variables likes document or window? *
<add> * Or gives undesired access to variables like document or window? *
<ide> * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
<ide>
<ide> /* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
| 1
|
Ruby
|
Ruby
|
fix output representation [ci skip]
|
ea2850b96a97d1c454d1f6ca0c8c7958cc63ea70
|
<ide><path>activemodel/lib/active_model/attribute_assignment.rb
<ide> module AttributeAssignment
<ide> # cat = Cat.new
<ide> # cat.assign_attributes(name: "Gorby", status: "yawning")
<ide> # cat.name # => 'Gorby'
<del> # cat.status => 'yawning'
<add> # cat.status # => 'yawning'
<ide> # cat.assign_attributes(status: "sleeping")
<ide> # cat.name # => 'Gorby'
<del> # cat.status => 'sleeping'
<add> # cat.status # => 'sleeping'
<ide> def assign_attributes(new_attributes)
<ide> if !new_attributes.respond_to?(:stringify_keys)
<ide> raise ArgumentError, "When assigning attributes, you must pass a hash as an argument."
| 1
|
Javascript
|
Javascript
|
remove items that don't have any changes
|
f4138018364161a0821c3526d35ee0b8d0c0d3f1
|
<ide><path>src/git-repository-async.js
<ide> export default class GitRepositoryAsync {
<ide> const cachedStatus = this.pathStatusCache[relativePath] || 0
<ide> const status = statuses[0] ? statuses[0].statusBit() : Git.Status.STATUS.CURRENT
<ide> if (status !== cachedStatus) {
<del> this.pathStatusCache[relativePath] = status
<add> if (status === Git.Status.STATUS.CURRENT) {
<add> delete this.pathStatusCache[relativePath]
<add> } else {
<add> this.pathStatusCache[relativePath] = status
<add> }
<add>
<ide> this.emitter.emit('did-change-status', {path: _path, pathStatus: status})
<ide> }
<ide>
| 1
|
Javascript
|
Javascript
|
fix version control with anchors
|
5469369480d01b357947ac938e6069e117d154d8
|
<ide><path>docs/source/_static/js/custom.js
<ide> function addVersionControl() {
<ide> const parts = location.toString().split('/');
<ide> let versionIndex = parts.length - 2;
<ide> // Index page may not have a last part with filename.html so we need to go up
<del> if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html$|^search.html?/)) {
<add> if (parts[parts.length - 1] != "" && ! parts[parts.length - 1].match(/\.html/)) {
<ide> versionIndex = parts.length - 1;
<ide> }
<ide> // Main classes and models are nested so we need to go deeper
| 1
|
Ruby
|
Ruby
|
remove duplicate test
|
eb8cd81859bd9f7df8cc08602200847e41e85f0d
|
<ide><path>activesupport/test/caching_test.rb
<ide> def test_clear_without_cache_dir
<ide> @cache.clear
<ide> end
<ide>
<del> def test_long_keys
<del> @cache.write("a"*10000, 1)
<del> assert_equal 1, @cache.read("a"*10000)
<del> end
<del>
<ide> def test_long_uri_encoded_keys
<ide> @cache.write("%"*870, 1)
<ide> assert_equal 1, @cache.read("%"*870)
| 1
|
Python
|
Python
|
add serialization tests for stringstore and vocab
|
acd65c00f62bd3e77a87efc199ec29255118dfc9
|
<ide><path>spacy/tests/serialize/test_serialize_stringstore.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>from ..util import make_tempdir
<add>from ...strings import StringStore
<add>
<add>import pytest
<add>
<add>
<add>test_strings = [([], []), (['rats', 'are', 'cute'], ['i', 'like', 'rats'])]
<add>
<add>
<add>@pytest.mark.parametrize('strings1,strings2', test_strings)
<add>def test_serialize_stringstore_roundtrip_bytes(strings1,strings2):
<add> sstore1 = StringStore(strings=strings1)
<add> sstore2 = StringStore(strings=strings2)
<add> sstore1_b = sstore1.to_bytes()
<add> sstore2_b = sstore2.to_bytes()
<add> if strings1 == strings2:
<add> assert sstore1_b == sstore2_b
<add> else:
<add> assert sstore1_b != sstore2_b
<add> sstore1 = sstore1.from_bytes(sstore1_b)
<add> assert sstore1.to_bytes() == sstore1_b
<add> new_sstore1 = StringStore().from_bytes(sstore1_b)
<add> assert new_sstore1.to_bytes() == sstore1_b
<add> assert list(new_sstore1) == strings1
<add>
<add>
<add>@pytest.mark.parametrize('strings1,strings2', test_strings)
<add>def test_serialize_stringstore_roundtrip_disk(strings1,strings2):
<add> sstore1 = StringStore(strings=strings1)
<add> sstore2 = StringStore(strings=strings2)
<add> with make_tempdir() as d:
<add> file_path1 = d / 'strings1'
<add> file_path2 = d / 'strings2'
<add> sstore1.to_disk(file_path1)
<add> sstore2.to_disk(file_path2)
<add> sstore1_d = StringStore().from_disk(file_path1)
<add> sstore2_d = StringStore().from_disk(file_path2)
<add> assert list(sstore1_d) == list(sstore1)
<add> assert list(sstore2_d) == list(sstore2)
<add> if strings1 == strings2:
<add> assert list(sstore1_d) == list(sstore2_d)
<add> else:
<add> assert list(sstore1_d) != list(sstore2_d)
<ide><path>spacy/tests/serialize/test_serialize_vocab.py
<add># coding: utf-8
<add>from __future__ import unicode_literals
<add>
<add>from ..util import make_tempdir
<add>from ...vocab import Vocab
<add>
<add>import pytest
<add>
<add>
<add>test_strings = [([], []), (['rats', 'are', 'cute'], ['i', 'like', 'rats'])]
<add>test_strings_attrs = [(['rats', 'are', 'cute'], 'Hello')]
<add>
<add>
<add>@pytest.mark.parametrize('strings1,strings2', test_strings)
<add>def test_serialize_vocab_roundtrip_bytes(strings1,strings2):
<add> vocab1 = Vocab(strings=strings1)
<add> vocab2 = Vocab(strings=strings2)
<add> vocab1_b = vocab1.to_bytes()
<add> vocab2_b = vocab2.to_bytes()
<add> if strings1 == strings2:
<add> assert vocab1_b == vocab2_b
<add> else:
<add> assert vocab1_b != vocab2_b
<add> vocab1 = vocab1.from_bytes(vocab1_b)
<add> assert vocab1.to_bytes() == vocab1_b
<add> new_vocab1 = Vocab().from_bytes(vocab1_b)
<add> assert new_vocab1.to_bytes() == vocab1_b
<add> assert len(new_vocab1) == len(strings1)
<add> assert sorted([lex.text for lex in new_vocab1]) == sorted(strings1)
<add>
<add>
<add>@pytest.mark.parametrize('strings1,strings2', test_strings)
<add>def test_serialize_vocab_roundtrip_disk(strings1,strings2):
<add> vocab1 = Vocab(strings=strings1)
<add> vocab2 = Vocab(strings=strings2)
<add> with make_tempdir() as d:
<add> file_path1 = d / 'vocab1'
<add> file_path2 = d / 'vocab2'
<add> vocab1.to_disk(file_path1)
<add> vocab2.to_disk(file_path2)
<add> vocab1_d = Vocab().from_disk(file_path1)
<add> vocab2_d = Vocab().from_disk(file_path2)
<add> assert list(vocab1_d) == list(vocab1)
<add> assert list(vocab2_d) == list(vocab2)
<add> if strings1 == strings2:
<add> assert list(vocab1_d) == list(vocab2_d)
<add> else:
<add> assert list(vocab1_d) != list(vocab2_d)
<add>
<add>
<add>@pytest.mark.parametrize('strings,lex_attr', test_strings_attrs)
<add>def test_serialize_vocab_lex_attrs_bytes(strings, lex_attr):
<add> vocab1 = Vocab(strings=strings)
<add> vocab2 = Vocab()
<add> vocab1[strings[0]].norm_ = lex_attr
<add> assert vocab1[strings[0]].norm_ == lex_attr
<add> assert vocab2[strings[0]].norm_ != lex_attr
<add> vocab2 = vocab2.from_bytes(vocab1.to_bytes())
<add> assert vocab2[strings[0]].norm_ == lex_attr
<add>
<add>
<add>@pytest.mark.parametrize('strings,lex_attr', test_strings_attrs)
<add>def test_serialize_vocab_lex_attrs_disk(strings, lex_attr):
<add> vocab1 = Vocab(strings=strings)
<add> vocab2 = Vocab()
<add> vocab1[strings[0]].norm_ = lex_attr
<add> assert vocab1[strings[0]].norm_ == lex_attr
<add> assert vocab2[strings[0]].norm_ != lex_attr
<add> with make_tempdir() as d:
<add> file_path = d / 'vocab'
<add> vocab1.to_disk(file_path)
<add> vocab2 = vocab2.from_disk(file_path)
<add> assert vocab2[strings[0]].norm_ == lex_attr
| 2
|
PHP
|
PHP
|
remove double space
|
2b3bf29177fdf15d58e43e267d73b1fa039d92d2
|
<ide><path>tests/TestCase/View/Helper/PaginatorHelperTest.php
<ide> public function testDefaultSortRemovedFromUrl() {
<ide> $result = $this->Paginator->next('Next');
<ide> $expected = array(
<ide> 'li' => array('class' => 'next'),
<del> 'a' => array('rel' => 'next', 'href' => '/articles/index?page=2'),
<add> 'a' => array('rel' => 'next', 'href' => '/articles/index?page=2'),
<ide> 'Next',
<ide> '/a',
<ide> '/li'
| 1
|
Javascript
|
Javascript
|
improve test stability
|
ad4b8063acf36555c204c834f0b54754b9ec29b0
|
<ide><path>test/watchCases/cache/add-defines/webpack.config.js
<ide> const { DefinePlugin } = require("../../../../");
<add>const currentWatchStep = require("../../../helpers/currentWatchStep");
<ide>
<ide> /** @type {import("../../../../").Configuration} */
<ide> module.exports = {
<ide> module.exports = {
<ide> compiler => {
<ide> const base = {
<ide> DEFINE: "{}",
<del> RUN: DefinePlugin.runtimeValue(() => 3 - defines.length, [])
<add> RUN: DefinePlugin.runtimeValue(() => +(currentWatchStep.step || 0), [])
<ide> };
<ide> const defines = [
<ide> {
<ide> module.exports = {
<ide> }
<ide> ];
<ide> compiler.hooks.compilation.tap("webpack.config", (...args) => {
<del> const plugin = new DefinePlugin(defines.shift());
<add> const plugin = new DefinePlugin(defines[+(currentWatchStep.step || 0)]);
<ide> plugin.apply(
<ide> /** @type {any} */ ({
<ide> hooks: {
| 1
|
Go
|
Go
|
add test for applydiff
|
a69d86e0b19d804819d37a2a9edc03803267f579
|
<ide><path>aufs/aufs_test.go
<ide> func TestDiffSize(t *testing.T) {
<ide> t.Fatalf("Expected size to be %d got %d", size, diffSize)
<ide> }
<ide> }
<add>
<add>func TestApplyDiff(t *testing.T) {
<add> d := newDriver(t)
<add> defer os.RemoveAll(tmp)
<add> defer d.Cleanup()
<add>
<add> if err := d.Create("1", ""); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> diffPath, err := d.Get("1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Add a file to the diff path with a fixed size
<add> size := int64(1024)
<add>
<add> f, err := os.Create(path.Join(diffPath, "test_file"))
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> f.Truncate(size)
<add> f.Close()
<add>
<add> diff, err := d.Diff("1")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := d.Create("2", ""); err != nil {
<add> t.Fatal(err)
<add> }
<add> if err := d.Create("3", "2"); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> if err := d.ApplyDiff("3", diff); err != nil {
<add> t.Fatal(err)
<add> }
<add>
<add> // Ensure that the file is in the mount point for id 3
<add>
<add> mountPoint, err := d.Get("3")
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> if _, err := os.Stat(path.Join(mountPoint, "test_file")); err != nil {
<add> t.Fatal(err)
<add> }
<add>}
| 1
|
Python
|
Python
|
implement rich comparison operators
|
68fe9b8d11f87b95d9904a7abb2972d5ddc2d6ef
|
<ide><path>airflow/models.py
<ide> def __init__(self, event, task_instance):
<ide> self.owner = task_instance.task.owner
<ide>
<ide>
<add>@functools.total_ordering
<ide> class BaseOperator(object):
<ide> """
<ide> Abstract base class for all operators. Since operators create objects that
<ide> def __init__(
<ide> self._upstream_list = []
<ide> self._downstream_list = []
<ide>
<add> self._comps = {
<add> 'task_id',
<add> 'dag_id',
<add> 'owner',
<add> 'email',
<add> 'email_on_retry',
<add> 'retry_delay',
<add> 'start_date',
<add> 'schedule_interval',
<add> 'depends_on_past',
<add> 'wait_for_downstream',
<add> 'adhoc',
<add> 'priority_weight',
<add> 'sla',
<add> 'execution_timeout',
<add> 'on_failure_callback',
<add> 'on_success_callback',
<add> 'on_retry_callback',
<add> }
<add>
<add> def __eq__(self, other):
<add> return (
<add> type(self) == type(other) and
<add> all(self.__dict__[c] == other.__dict__[c] for c in self._comps))
<add>
<add> def __neq__(self, other):
<add> return not self == other
<add>
<add> def __lt__(self, other):
<add> return (type(self) == type(other) and self.task_id < other.task_id)
<add>
<add> def __hash__(self):
<add> return hash(tuple(getattr(self, c, None) for c in self._comps))
<add>
<ide> @property
<ide> def schedule_interval(self):
<ide> """
<ide> def priority_weight_total(self):
<ide> for t in self.get_flat_relatives(upstream=False)
<ide> ]) + self.priority_weight
<ide>
<del> def __cmp__(self, other):
<del> blacklist = {
<del> '_sa_instance_state', '_upstream_list', '_downstream_list', 'dag'}
<del> for k in set(self.__dict__) - blacklist:
<del> if self.__dict__[k] != other.__dict__[k]:
<del> logging.debug(str((
<del> self.dag_id,
<del> self.task_id,
<del> k,
<del> self.__dict__[k],
<del> other.__dict__[k])))
<del> return -1
<del> return 0
<del>
<ide> def pre_execute(self, context):
<ide> """
<ide> This is triggered right before self.execute, it's mostly a hook
<ide> def get_current(cls, dag_id):
<ide> return obj
<ide>
<ide>
<add>@functools.total_ordering
<ide> class DAG(object):
<ide> """
<ide> A dag (directed acyclic graph) is a collection of tasks with directional
<ide> def __init__(
<ide> self.parent_dag = None # Gets set when DAGs are loaded
<ide> self.last_loaded = datetime.now()
<ide>
<add> self._comps = {
<add> 'dag_id',
<add> 'tasks',
<add> 'parent_dag',
<add> 'start_date',
<add> 'schedule_interval'
<add> 'full_filepath',
<add> 'template_searchpath',
<add> 'last_loaded',
<add> }
<add>
<ide> def __repr__(self):
<ide> return "<DAG: {self.dag_id}>".format(self=self)
<ide>
<add> def __eq__(self, other):
<add> return (
<add> type(self) == type(other) and
<add> all(self.__dict__[c] == other.__dict__[c] for c in self._comps))
<add>
<add> def __neq__(self, other):
<add> return not self == other
<add>
<add> def __lt__(self, other):
<add> return (type(self) == type(other) and self.dag_id < other.dag_id)
<add>
<add> def __hash__(self):
<add> return hash(tuple(getattr(self, c, None) for c in self._comps))
<add>
<ide> @property
<ide> def task_ids(self):
<ide> return [t.task_id for t in self.tasks]
<ide> def get_task(self, task_id):
<ide> return task
<ide> raise AirflowException("Task {task_id} not found".format(**locals()))
<ide>
<del> def __cmp__(self, other):
<del> blacklist = {'_sa_instance_state', 'end_date', 'last_pickled', 'tasks'}
<del> for k in set(self.__dict__) - blacklist:
<del> if self.__dict__[k] != other.__dict__[k]:
<del> return -1
<del>
<del> if len(self.tasks) != len(other.tasks):
<del> return -1
<del> i = 0
<del> for task in self.tasks:
<del> if task != other.tasks[i]:
<del> return -1
<del> i += 1
<del> logging.info("Same as before")
<del> return 0
<del>
<ide> def pickle(self, main_session=None):
<ide> session = main_session or settings.Session()
<ide> dag = session.query(
| 1
|
Ruby
|
Ruby
|
add cross-references and documentation for scope
|
38d728fb944b08b7faabf19c8ba5ef2e69e29c16
|
<ide><path>actionpack/lib/action_dispatch/routing.rb
<ide> module ActionDispatch
<ide> # resources :posts, :comments
<ide> # end
<ide> #
<add> # Alternately, you can add prefixes to your path without using a separate
<add> # directory by using +scope+. +scope+ takes additional options which
<add> # apply to all enclosed routes.
<add> #
<add> # scope :path => "/cpanel", :as => 'admin' do
<add> # resources :posts, :comments
<add> # end
<add> #
<add> # For more, see <tt>Routing::Mapper::Resources#resources</tt>,
<add> # <tt>Routing::Mapper::Scoping#namespace</tt>, and
<add> # <tt>Routing::Mapper::Scoping#scope</tt>.
<add> #
<ide> # == Named routes
<ide> #
<ide> # Routes can be named by passing an <tt>:as</tt> option,
| 1
|
Java
|
Java
|
android scrollview fix for pagingenabled
|
e0170a944501bb487e899b92363bf5aa64b29299
|
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactHorizontalScrollView.java
<ide> public boolean onTouchEvent(MotionEvent ev) {
<ide> @Override
<ide> public void fling(int velocityX) {
<ide> if (mPagingEnabled) {
<del> smoothScrollAndSnap(velocityX);
<add> flingAndSnap(velocityX);
<ide> } else if (mScroller != null) {
<ide> // FB SCROLLVIEW CHANGE
<ide>
<ide> public void run() {
<ide> // Only if we have pagingEnabled and we have not snapped to the page do we
<ide> // need to continue checking for the scroll. And we cause that scroll by asking for it
<ide> mSnappingToPage = true;
<del> smoothScrollAndSnap(0);
<add> flingAndSnap(0);
<ide> ViewCompat.postOnAnimationDelayed(ReactHorizontalScrollView.this,
<ide> this,
<ide> ReactScrollViewHelper.MOMENTUM_DELAY);
<ide> public void run() {
<ide> ReactScrollViewHelper.MOMENTUM_DELAY);
<ide> }
<ide>
<del> /**
<del> * This will smooth scroll us to the nearest snap offset point
<del> * It currently just looks at where the content is and slides to the nearest point.
<del> * It is intended to be run after we are done scrolling, and handling any momentum scrolling.
<del> */
<del> private void smoothScrollAndSnap(int velocityX) {
<del> if (getChildCount() <= 0) {
<del> return;
<del> }
<del>
<del> int maximumOffset = Math.max(0, computeHorizontalScrollRange() - getWidth());
<del> int targetOffset = 0;
<del> int smallerOffset = 0;
<del> int largerOffset = maximumOffset;
<del> int firstOffset = 0;
<del> int lastOffset = maximumOffset;
<del>
<add> private int predictFinalScrollPosition(int velocityX) {
<ide> // ScrollView can *only* scroll for 250ms when using smoothScrollTo and there's
<ide> // no way to customize the scroll duration. So, we create a temporary OverScroller
<ide> // so we can predict where a fling would land and snap to nearby that point.
<ide> OverScroller scroller = new OverScroller(getContext());
<ide> scroller.setFriction(1.0f - mDecelerationRate);
<ide>
<ide> // predict where a fling would end up so we can scroll to the nearest snap offset
<add> int maximumOffset = Math.max(0, computeHorizontalScrollRange() - getWidth());
<ide> int width = getWidth() - getPaddingStart() - getPaddingEnd();
<ide> scroller.fling(
<ide> getScrollX(), // startX
<ide> private void smoothScrollAndSnap(int velocityX) {
<ide> width/2, // overX
<ide> 0 // overY
<ide> );
<del> targetOffset = scroller.getFinalX();
<add> return scroller.getFinalX();
<add> }
<add>
<add> /**
<add> * This will smooth scroll us to the nearest snap offset point
<add> * It currently just looks at where the content is and slides to the nearest point.
<add> * It is intended to be run after we are done scrolling, and handling any momentum scrolling.
<add> */
<add> private void smoothScrollAndSnap(int velocity) {
<add> double interval = (double) getSnapInterval();
<add> double currentOffset = (double) getScrollX();
<add> double targetOffset = (double) predictFinalScrollPosition(velocity);
<add>
<add> int previousPage = (int) Math.floor(currentOffset / interval);
<add> int nextPage = (int) Math.ceil(currentOffset / interval);
<add> int currentPage = (int) Math.round(currentOffset / interval);
<add> int targetPage = (int) Math.round(targetOffset / interval);
<add>
<add> if (velocity > 0 && nextPage == previousPage) {
<add> nextPage ++;
<add> } else if (velocity < 0 && previousPage == nextPage) {
<add> previousPage --;
<add> }
<add>
<add> if (
<add> // if scrolling towards next page
<add> velocity > 0 &&
<add> // and the middle of the page hasn't been crossed already
<add> currentPage < nextPage &&
<add> // and it would have been crossed after flinging
<add> targetPage > previousPage
<add> ) {
<add> currentPage = nextPage;
<add> }
<add> else if (
<add> // if scrolling towards previous page
<add> velocity < 0 &&
<add> // and the middle of the page hasn't been crossed already
<add> currentPage > previousPage &&
<add> // and it would have been crossed after flinging
<add> targetPage < nextPage
<add> ) {
<add> currentPage = previousPage;
<add> }
<add>
<add> targetOffset = currentPage * interval;
<add> if (targetOffset != currentOffset) {
<add> mActivelyScrolling = true;
<add> smoothScrollTo((int) targetOffset, getScrollY());
<add> }
<add> }
<add>
<add> private void flingAndSnap(int velocityX) {
<add> if (getChildCount() <= 0) {
<add> return;
<add> }
<add>
<add> // pagingEnabled only allows snapping one interval at a time
<add> if (mSnapInterval == 0 && mSnapOffsets == null) {
<add> smoothScrollAndSnap(velocityX);
<add> return;
<add> }
<add>
<add> int maximumOffset = Math.max(0, computeHorizontalScrollRange() - getWidth());
<add> int targetOffset = predictFinalScrollPosition(velocityX);
<add> int smallerOffset = 0;
<add> int largerOffset = maximumOffset;
<add> int firstOffset = 0;
<add> int lastOffset = maximumOffset;
<add> int width = getWidth() - getPaddingStart() - getPaddingEnd();
<ide>
<ide> // offsets are from the right edge in RTL layouts
<ide> boolean isRTL = TextUtilsCompat.getLayoutDirectionFromLocale(Locale.getDefault()) == ViewCompat.LAYOUT_DIRECTION_RTL;
<ide><path>ReactAndroid/src/main/java/com/facebook/react/views/scroll/ReactScrollView.java
<ide> public void getClippingRect(Rect outClippingRect) {
<ide> @Override
<ide> public void fling(int velocityY) {
<ide> if (mPagingEnabled) {
<del> smoothScrollAndSnap(velocityY);
<add> flingAndSnap(velocityY);
<ide> } else if (mScroller != null) {
<ide> // FB SCROLLVIEW CHANGE
<ide>
<ide> public void run() {
<ide> // Only if we have pagingEnabled and we have not snapped to the page do we
<ide> // need to continue checking for the scroll. And we cause that scroll by asking for it
<ide> mSnappingToPage = true;
<del> smoothScrollAndSnap(0);
<add> flingAndSnap(0);
<ide> ViewCompat.postOnAnimationDelayed(ReactScrollView.this,
<ide> this,
<ide> ReactScrollViewHelper.MOMENTUM_DELAY);
<ide> public void run() {
<ide> ReactScrollViewHelper.MOMENTUM_DELAY);
<ide> }
<ide>
<del> /**
<del> * This will smooth scroll us to the nearest snap offset point
<del> * It currently just looks at where the content is and slides to the nearest point.
<del> * It is intended to be run after we are done scrolling, and handling any momentum scrolling.
<del> */
<del> private void smoothScrollAndSnap(int velocityY) {
<del> if (getChildCount() <= 0) {
<del> return;
<del> }
<del>
<del> int maximumOffset = getMaxScrollY();
<del> int targetOffset = 0;
<del> int smallerOffset = 0;
<del> int largerOffset = maximumOffset;
<del> int firstOffset = 0;
<del> int lastOffset = maximumOffset;
<del>
<add> private int predictFinalScrollPosition(int velocityY) {
<ide> // ScrollView can *only* scroll for 250ms when using smoothScrollTo and there's
<ide> // no way to customize the scroll duration. So, we create a temporary OverScroller
<ide> // so we can predict where a fling would land and snap to nearby that point.
<ide> OverScroller scroller = new OverScroller(getContext());
<ide> scroller.setFriction(1.0f - mDecelerationRate);
<ide>
<ide> // predict where a fling would end up so we can scroll to the nearest snap offset
<add> int maximumOffset = getMaxScrollY();
<ide> int height = getHeight() - getPaddingBottom() - getPaddingTop();
<ide> scroller.fling(
<ide> getScrollX(), // startX
<ide> private void smoothScrollAndSnap(int velocityY) {
<ide> 0, // overX
<ide> height/2 // overY
<ide> );
<del> targetOffset = scroller.getFinalY();
<add> return scroller.getFinalY();
<add> }
<add>
<add> /**
<add> * This will smooth scroll us to the nearest snap offset point
<add> * It currently just looks at where the content is and slides to the nearest point.
<add> * It is intended to be run after we are done scrolling, and handling any momentum scrolling.
<add> */
<add> private void smoothScrollAndSnap(int velocity) {
<add> double interval = (double) getSnapInterval();
<add> double currentOffset = (double) getScrollY();
<add> double targetOffset = (double) predictFinalScrollPosition(velocity);
<add>
<add> int previousPage = (int) Math.floor(currentOffset / interval);
<add> int nextPage = (int) Math.ceil(currentOffset / interval);
<add> int currentPage = (int) Math.round(currentOffset / interval);
<add> int targetPage = (int) Math.round(targetOffset / interval);
<add>
<add> if (velocity > 0 && nextPage == previousPage) {
<add> nextPage ++;
<add> } else if (velocity < 0 && previousPage == nextPage) {
<add> previousPage --;
<add> }
<add>
<add> if (
<add> // if scrolling towards next page
<add> velocity > 0 &&
<add> // and the middle of the page hasn't been crossed already
<add> currentPage < nextPage &&
<add> // and it would have been crossed after flinging
<add> targetPage > previousPage
<add> ) {
<add> currentPage = nextPage;
<add> }
<add> else if (
<add> // if scrolling towards previous page
<add> velocity < 0 &&
<add> // and the middle of the page hasn't been crossed already
<add> currentPage > previousPage &&
<add> // and it would have been crossed after flinging
<add> targetPage < nextPage
<add> ) {
<add> currentPage = previousPage;
<add> }
<add>
<add> targetOffset = currentPage * interval;
<add> if (targetOffset != currentOffset) {
<add> mActivelyScrolling = true;
<add> smoothScrollTo(getScrollX(), (int) targetOffset);
<add> }
<add> }
<add>
<add> private void flingAndSnap(int velocityY) {
<add> if (getChildCount() <= 0) {
<add> return;
<add> }
<add>
<add> // pagingEnabled only allows snapping one interval at a time
<add> if (mSnapInterval == 0 && mSnapOffsets == null) {
<add> smoothScrollAndSnap(velocityY);
<add> return;
<add> }
<add>
<add> int maximumOffset = getMaxScrollY();
<add> int targetOffset = predictFinalScrollPosition(velocityY);
<add> int smallerOffset = 0;
<add> int largerOffset = maximumOffset;
<add> int firstOffset = 0;
<add> int lastOffset = maximumOffset;
<add> int height = getHeight() - getPaddingBottom() - getPaddingTop();
<ide>
<ide> // get the nearest snap points to the target offset
<ide> if (mSnapOffsets != null) {
| 2
|
Python
|
Python
|
add `multi_gpu_model` utility
|
3dd3e8331677e68e7dec6ed4a1cbf16b7ef19f7f
|
<ide><path>keras/utils/__init__.py
<ide> from .vis_utils import plot_model
<ide> from .np_utils import to_categorical
<ide> from .np_utils import normalize
<add>from .training_utils import multi_gpu_model
<ide><path>keras/utils/training_utils.py
<add>from ..layers.merge import concatenate
<add>from .. import backend as K
<add>from ..layers.core import Lambda
<add>from ..engine.training import Model
<add>
<add>
<add>def _get_available_devices():
<add> from tensorflow.python.client import device_lib
<add> local_device_protos = device_lib.list_local_devices()
<add> return [x.name for x in local_device_protos]
<add>
<add>
<add>def multi_gpu_model(model, gpus):
<add> """Replicates a model on different GPUs.
<add>
<add> Specifically, this function implements single-machine
<add> multi-GPU data parallelism. It works in the following way:
<add>
<add> - Divide the model's input(s) into multiple sub-batches.
<add> - Apply a model copy on each sub-batch. Every model copy
<add> is executed on a dedicated GPU.
<add> - Concatenate the results (on CPU) into one big batch.
<add>
<add> E.g. if your `batch_size` is 64 and you use `gpus=2`,
<add> then we will divide the input into 2 sub-batches of 32 samples,
<add> process each sub-batch on one GPU, then return the full
<add> batch of 64 processed samples.
<add>
<add> This induces quasi-linear speedup on up to 8 GPUs.
<add>
<add> This function is only available with the TensorFlow backend
<add> for the time being.
<add>
<add> # Arguments
<add> model: A Keras model instance. To avoid OOM errors,
<add> this model could have been built on CPU, for instance
<add> (see usage example below).
<add> gpus: Integer >= 2, number of on GPUs on which to create
<add> model replicas.
<add>
<add> # Returns
<add> A Keras `Model` instance which can be used just like the initial
<add> `model` argument, but which distributes its workload on multiple GPUs.
<add>
<add> # Example
<add>
<add> ```python
<add> import tensorflow as tf
<add> from keras.applications import Xception
<add>
<add> num_samples = 1000
<add> height = 224
<add> width = 224
<add> num_classes = 1000
<add>
<add> # Instantiate the base model
<add> # (here, we do it on CPU, which is optional).
<add> with tf.device('/cpu:0'):
<add> model = Xception(weights=None,
<add> input_shape=(height, width, 3),
<add> classes=num_classes)
<add>
<add> # Replicates the model on 8 GPUs.
<add> # This assumes that your machine has 8 available GPUs.
<add> parallel_model = multi_gpu_model(model, gpus=8)
<add> parallel_model.compile(loss='categorical_crossentropy',
<add> optimizer='rmsprop')
<add>
<add> # Generate dummy data.
<add> x = np.random.random((num_samples, height, width, 3))
<add> y = np.random.random((num_samples, num_classes))
<add>
<add> # This `fit` call will be distributed on 8 GPUs.
<add> # Since the batch size is 256, each GPU will process 32 samples.
<add> parallel_model.fit(x, y, epochs=20, batch_size=256)
<add> ```
<add> """
<add> if K.backend() != 'tensorflow':
<add> raise ValueError('`multi_gpu_model` is only available '
<add> 'with the TensorFlow backend.')
<add> if gpus <= 1:
<add> raise ValueError('For multi-gpu usage to be effective, '
<add> 'call `multi_gpu_model` with `gpus >= 2`. '
<add> 'Received: `gpus=%d`' % gpus)
<add>
<add> import tensorflow as tf
<add>
<add> target_devices = ['/cpu:0'] + ['/gpu:%d' % i for i in range(gpus)]
<add> available_devices = _get_available_devices()
<add> for device in target_devices:
<add> if device not in available_devices:
<add> raise ValueError(
<add> 'To call `multi_gpu_model` with `gpus=%d`, '
<add> 'we expect the following devices to be available: %s. '
<add> 'However this machine only has: %s. '
<add> 'Try reducing `gpus`.' % (gpus,
<add> target_devices,
<add> available_devices))
<add>
<add> def get_slice(data, i, parts):
<add> shape = tf.shape(data)
<add> batch_size = shape[:1]
<add> input_shape = shape[1:]
<add> step = batch_size // parts
<add> if i == gpus - 1:
<add> size = batch_size - step * i
<add> else:
<add> size = step
<add> size = tf.concat([size, input_shape], axis=0)
<add> stride = tf.concat([step, input_shape * 0], axis=0)
<add> start = stride * i
<add> return tf.slice(data, start, size)
<add>
<add> all_outputs = []
<add> for i in range(len(model.outputs)):
<add> all_outputs.append([])
<add>
<add> # Place a copy of the model on each GPU,
<add> # each getting a slice of the inputs.
<add> for i in range(gpus):
<add> with tf.device('/gpu:%d' % i):
<add> with tf.name_scope('replica_%d' % i):
<add> inputs = []
<add> # Retrieve a slice of the input.
<add> for x in model.inputs:
<add> input_shape = tuple(x.get_shape().as_list())[1:]
<add> slice_i = Lambda(get_slice,
<add> output_shape=input_shape,
<add> arguments={'i': i,
<add> 'parts': gpus})(x)
<add> inputs.append(slice_i)
<add>
<add> # Apply model on slice
<add> # (creating a model replica on the target device).
<add> outputs = model(inputs)
<add> if not isinstance(outputs, list):
<add> outputs = [outputs]
<add>
<add> # Save the outputs for merging back together later.
<add> for o in range(len(outputs)):
<add> all_outputs[o].append(outputs[o])
<add>
<add> # Merge outputs on CPU.
<add> with tf.device('/cpu:0'):
<add> merged = []
<add> for outputs in all_outputs:
<add> merged.append(concatenate(outputs,
<add> axis=0))
<add> return Model(model.inputs, merged)
<ide><path>tests/keras/utils/multi_gpu_test.py
<add>"""These tests are not meant to be run on CI.
<add>"""
<add>from __future__ import print_function
<add>
<add>import keras
<add>from keras import backend as K
<add>from keras.utils import multi_gpu_model
<add>
<add>import numpy as np
<add>import pytest
<add>import time
<add>import tensorflow as tf
<add>from keras.preprocessing.image import ImageDataGenerator
<add>
<add>
<add>def multi_gpu_test_simple_model():
<add> print('####### test simple model')
<add> num_samples = 1000
<add> input_dim = 10
<add> output_dim = 1
<add> hidden_dim = 10
<add> gpus = 8
<add> epochs = 2
<add> model = keras.models.Sequential()
<add> model.add(keras.layers.Dense(hidden_dim,
<add> input_shape=(input_dim,)))
<add> model.add(keras.layers.Dense(output_dim))
<add>
<add> x = np.random.random((num_samples, input_dim))
<add> y = np.random.random((num_samples, output_dim))
<add> parallel_model = multi_gpu_model(model, gpus=gpus)
<add>
<add> parallel_model.compile(loss='mse', optimizer='rmsprop')
<add> parallel_model.fit(x, y, epochs=epochs)
<add>
<add>
<add>def multi_gpu_test_multi_io_model():
<add> print('####### test multi-io model')
<add> num_samples = 1000
<add> input_dim_a = 10
<add> input_dim_b = 5
<add> output_dim_a = 1
<add> output_dim_b = 2
<add> hidden_dim = 10
<add> gpus = 8
<add> epochs = 2
<add>
<add> input_a = keras.Input((input_dim_a,))
<add> input_b = keras.Input((input_dim_b,))
<add> a = keras.layers.Dense(hidden_dim)(input_a)
<add> b = keras.layers.Dense(hidden_dim)(input_b)
<add> c = keras.layers.concatenate([a, b])
<add> output_a = keras.layers.Dense(output_dim_a)(c)
<add> output_b = keras.layers.Dense(output_dim_b)(c)
<add> model = keras.models.Model([input_a, input_b], [output_a, output_b])
<add>
<add> a_x = np.random.random((num_samples, input_dim_a))
<add> b_x = np.random.random((num_samples, input_dim_b))
<add> a_y = np.random.random((num_samples, output_dim_a))
<add> b_y = np.random.random((num_samples, output_dim_b))
<add>
<add> parallel_model = multi_gpu_model(model, gpus=gpus)
<add> parallel_model.compile(loss='mse', optimizer='rmsprop')
<add> parallel_model.fit([a_x, b_x], [a_y, b_y], epochs=epochs)
<add>
<add>
<add>def multi_gpu_test_invalid_devices():
<add> input_shape = (1000, 10)
<add> model = keras.models.Sequential()
<add> model.add(keras.layers.Dense(10,
<add> activation='relu',
<add> input_shape=input_shape[1:]))
<add> model.add(keras.layers.Dense(1, activation='sigmoid'))
<add> model.compile(loss='mse', optimizer='rmsprop')
<add>
<add> x = np.random.random(input_shape)
<add> y = np.random.random((input_shape[0], 1))
<add> with pytest.raises(ValueError):
<add> parallel_model = multi_gpu_model(model, gpus=10)
<add> parallel_model.fit(x, y, epochs=2)
<add>
<add>
<add>def multi_gpu_application_np_array_benchmark():
<add> print('####### Xception benchmark - np i/o')
<add> model_cls = keras.applications.Xception
<add>
<add> num_samples = 1000
<add> height = 224
<add> width = 224
<add> num_classes = 1000
<add> epochs = 4
<add> batch_size = 40
<add> x = np.random.random((num_samples, height, width, 3))
<add> y = np.random.random((num_samples, num_classes))
<add>
<add> # Baseline
<add> model = model_cls(weights=None,
<add> input_shape=(height, width, 3),
<add> classes=num_classes)
<add> model.compile(loss='categorical_crossentropy',
<add> optimizer='rmsprop')
<add>
<add> # Training
<add> start_time = time.time()
<add> model.fit(x, y, epochs=epochs)
<add> total_time = time.time() - start_time
<add> print('baseline training:', total_time)
<add>
<add> # Inference
<add> start_time = time.time()
<add> model.predict(x)
<add> total_time = time.time() - start_time
<add> print('baseline inference:', total_time)
<add>
<add> for i in range(8, 9):
<add> K.clear_session()
<add> with tf.device('/cpu:0'):
<add> model = model_cls(weights=None,
<add> input_shape=(height, width, 3),
<add> classes=num_classes)
<add> parallel_model = multi_gpu_model(model, gpus=i)
<add> parallel_model.compile(loss='categorical_crossentropy',
<add> optimizer='rmsprop')
<add>
<add> start_time = time.time()
<add> parallel_model.fit(x, y, epochs=epochs, batch_size=batch_size)
<add> total_time = time.time() - start_time
<add> print('%d gpus training:' % i, total_time)
<add>
<add> # Inference
<add> start_time = time.time()
<add> parallel_model.predict(x, batch_size=batch_size)
<add> total_time = time.time() - start_time
<add> print('%d gpus inference:' % i, total_time)
<add>
<add>
<add>def multi_gpu_application_folder_generator_benchmark():
<add> """Before running this test:
<add>
<add> wget https://s3.amazonaws.com/img-datasets/cats_and_dogs_small.zip
<add> unzip cats_and_dogs_small.zip
<add> """
<add> print('####### Xception benchmark - folder generator i/o')
<add> model_cls = keras.applications.Xception
<add>
<add> height = 150
<add> width = 150
<add> num_classes = 2
<add> epochs = 3
<add> steps_per_epoch = 100
<add> batch_size = 64
<add>
<add> # Baseline
<add> model = model_cls(weights=None,
<add> input_shape=(height, width, 3),
<add> classes=num_classes)
<add> model.compile(loss='categorical_crossentropy',
<add> optimizer='rmsprop')
<add>
<add> datagen = ImageDataGenerator(
<add> rotation_range=40,
<add> width_shift_range=0.2,
<add> height_shift_range=0.2,
<add> shear_range=0.2,
<add> zoom_range=0.2,
<add> horizontal_flip=True,
<add> fill_mode='nearest')
<add> train_dir = '/home/ubuntu/cats_and_dogs_small/train' # Change this
<add> train_gen = datagen.flow_from_directory(
<add> train_dir,
<add> target_size=(height, width),
<add> batch_size=batch_size,
<add> class_mode='categorical')
<add>
<add> # Training
<add> start_time = time.time()
<add> model.fit_generator(train_gen,
<add> steps_per_epoch=steps_per_epoch,
<add> epochs=epochs,
<add> workers=4)
<add> total_time = time.time() - start_time
<add> print('baseline training:', total_time)
<add>
<add> for i in range(2, 9):
<add> K.clear_session()
<add> with tf.device('/cpu:0'):
<add> model = model_cls(weights=None,
<add> input_shape=(height, width, 3),
<add> classes=num_classes)
<add> parallel_model = multi_gpu_model(model, gpus=i)
<add> parallel_model.compile(loss='categorical_crossentropy',
<add> optimizer='rmsprop')
<add>
<add> train_gen = datagen.flow_from_directory(
<add> train_dir,
<add> target_size=(height, width),
<add> batch_size=batch_size,
<add> class_mode='categorical')
<add>
<add> start_time = time.time()
<add> parallel_model.fit_generator(
<add> train_gen,
<add> steps_per_epoch=steps_per_epoch,
<add> epochs=epochs,
<add> workers=4 * i)
<add> total_time = time.time() - start_time
<add> print('%d gpus training:' % i, total_time)
<add>
<add>
<add>if __name__ == '__main__':
<add> multi_gpu_test_simple_model()
<add> multi_gpu_test_multi_io_model()
<add> multi_gpu_test_invalid_devices()
<add> multi_gpu_application_np_array_benchmark()
<add> multi_gpu_application_folder_generator_benchmark()
| 3
|
Text
|
Text
|
improve translation for russian locale
|
6e8f8a5bd90104e80cdaf3e33cc56ce92a83bc1b
|
<ide><path>curriculum/challenges/russian/02-javascript-algorithms-and-data-structures/functional-programming/use-the-reduce-method-to-analyze-data.russian.md
<ide> id: 587d7da9367417b2b2512b68
<ide> title: Use the reduce Method to Analyze Data
<ide> challengeType: 1
<ide> videoUrl: ''
<del>localeTitle: Используйте метод уменьшения для анализа данных
<add>localeTitle: Используйте метод reduce для анализа данных
<ide> ---
<ide>
<del>## Description
<del><section id="description"> <code>Array.prototype.reduce()</code> или просто <code>reduce()</code> , является наиболее общей из всех операций с массивами в JavaScript. Вы можете решить практически любую проблему обработки массива с помощью метода <code>reduce</code> . Это не относится к методам <code>filter</code> и <code>map</code> поскольку они не позволяют взаимодействовать между двумя различными элементами массива. Например, если вы хотите сравнить элементы массива или добавить их вместе, <code>filter</code> или <code>map</code> не смогут обработать это. Метод <code>reduce</code> позволяет использовать более общие формы обработки массивов, и можно показать, что как <code>filter</code> и <code>map</code> могут быть получены как специальное приложение <code>reduce</code> . Однако, прежде чем мы доберемся туда, давайте сначала будем использовать <code>reduce</code> . </section>
<add>## Описание
<add><section id="description"> <code>Array.prototype.reduce()</code> или просто <code>reduce()</code>, является наиболее общей из всех операций с массивами в JavaScript. Вы можете решить практически любую проблему обработки массива с помощью метода <code>reduce</code> . Это не относится к методам <code>filter</code> и <code>map</code> поскольку они не позволяют взаимодействовать между двумя различными элементами массива. Например, если вы хотите сравнить элементы массива или добавить их вместе, <code>filter</code> или <code>map</code> не смогут обработать это. Метод <code>reduce</code> позволяет использовать более общие формы обработки массивов, и можно показать, что как <code>filter</code>, так и <code>map</code> могут быть реализованы через <code>reduce</code>. Однако, прежде чем мы перейдем к этому, давайте сначала научимся использовать <code>reduce</code>. </section>
<ide>
<del>## Instructions
<del><section id="instructions"> Переменная <code>watchList</code> содержит массив объектов с информацией о нескольких фильмах. Используйте <code>reduce</code> чтобы найти средний рейтинг IMDB фильмов <strong>режиссера Кристофера Нолана</strong> . Вспомните предыдущие проблемы, как <code>filter</code> данные и <code>map</code> их, чтобы вытащить то, что вам нужно. Возможно, вам придется создавать другие переменные, но сохранить окончательное среднее значение в переменной <code>averageRating</code> . Обратите внимание, что значения рейтинга сохраняются как строки в объекте и должны быть преобразованы в числа, прежде чем они будут использоваться в любых математических операциях. </section>
<add>## Указания
<add><section id="instructions"> Переменная <code>watchList</code> содержит массив объектов с информацией о нескольких фильмах. Используйте <code>reduce</code> чтобы найти средний рейтинг IMDB фильмов <strong>режиссера Кристофера Нолана</strong>. Вспомните предыдущие задачи, как применять к данным <code>filter</code> и <code>map</code>, чтобы вытащить то, что вам нужно. Возможно, вам придется создавать другие переменные, но сохранить окончательное среднее значение в переменной <code>averageRating</code>. Обратите внимание, что значения рейтинга сохраняются как строки в объекте и должны быть преобразованы в числа, прежде чем они будут использоваться в любых математических операциях. </section>
<ide>
<del>## Tests
<add>## Тесты
<ide> <section id='tests'>
<ide>
<ide> ```yml
<ide> tests:
<ide> - text: Переменная <code>watchList</code> не должна изменяться.
<ide> testString: 'assert(watchList[0].Title === "Inception" && watchList[4].Director == "James Cameron", "The <code>watchList</code> variable should not change.");'
<del> - text: Ваш код должен использовать метод <code>reduce</code> .
<add> - text: Ваш код должен использовать метод <code>reduce</code>.
<ide> testString: 'assert(code.match(/\.reduce/g), "Your code should use the <code>reduce</code> method.");'
<ide> - text: <code>averageRating</code> должно равняться 8.675.
<ide> testString: 'assert(averageRating == 8.675, "The <code>averageRating</code> should equal 8.675.");'
<del> - text: Ваш код не должен использовать цикл <code>for</code> .
<add> - text: Ваш код не должен использовать цикл <code>for</code>.
<ide> testString: 'assert(!code.match(/for\s*?\(.*\)/g), "Your code should not use a <code>for</code> loop.");'
<ide>
<ide> ```
<ide>
<ide> </section>
<ide>
<del>## Challenge Seed
<add>## Исходные данные
<ide> <section id='challengeSeed'>
<ide>
<ide> <div id='js-seed'>
<ide> console.log(averageRating);
<ide>
<ide> </section>
<ide>
<del>## Solution
<add>## Решение
<ide> <section id='solution'>
<ide>
<ide> ```js
| 1
|
Javascript
|
Javascript
|
fix typo in comments (ot -> to)
|
93eb6a5637f67df55f47ccf8181ee31aefc38334
|
<ide><path>src/addons/transitions/ReactTransitionKeySet.js
<ide> var ReactTransitionKeySet = {
<ide>
<ide> /**
<ide> * When you're adding or removing children some may be added or removed in the
<del> * same render pass. We want ot show *both* since we want to simultaneously
<add> * same render pass. We want to show *both* since we want to simultaneously
<ide> * animate elements in and out. This function takes a previous set of keys
<ide> * and a new set of keys and merges them with its best guess of the correct
<ide> * ordering. In the future we may expose some of the utilities in
| 1
|
Python
|
Python
|
improve error message in recurrent.py
|
2143046261e91e8b893bc9cbeedf08b732555e36
|
<ide><path>keras/layers/recurrent.py
<ide> def get_output(self, train=False):
<ide> if not self.input_shape[1]:
<ide> raise Exception('When using TensorFlow, you should define ' +
<ide> 'explicitly the number of timesteps of ' +
<del> 'your sequences. Make sure the first layer ' +
<del> 'has a "batch_input_shape" argument ' +
<del> 'including the samples axis.')
<add> 'your sequences.\n' +
<add> 'If your first layer is an Embedding, ' +
<add> 'make sure to pass it an "input_length" ' +
<add> 'argument. Otherwise, make sure ' +
<add> 'the first layer has ' +
<add> 'an "input_shape" or "batch_input_shape" ' +
<add> 'argument, including the time axis.')
<ide> if self.stateful:
<ide> initial_states = self.states
<ide> else:
| 1
|
PHP
|
PHP
|
add missing methods and tests
|
71f3e62aa8bd580c19087ef51517b933dcf6472b
|
<ide><path>src/Illuminate/Routing/Router.php
<ide> public function current()
<ide> return $this->current;
<ide> }
<ide>
<add> /**
<add> * Determine if the current route matches a given name.
<add> *
<add> * @param string $name
<add> * @return bool
<add> */
<add> public function currentRouteNamed($name)
<add> {
<add> return $this->current()->getName() == $name;
<add> }
<add>
<add> /**
<add> * Determine if the current route action matches a given action.
<add> *
<add> * @param string $action
<add> * @return bool
<add> */
<add> public function currentRouteUses($action)
<add> {
<add> $current = $this->current()->getAction();
<add>
<add> return isset($current['controller']) && $current['controller'] == $action;
<add> }
<add>
<ide> /**
<ide> * Get the request currently being dispatched.
<ide> *
<ide><path>tests/Routing/RoutingRouteTest.php
<ide> public function testBasicDispatchingOfRoutes()
<ide> $this->assertEquals('30', $router->dispatch(Request::create('30', 'GET'))->getContent());
<ide>
<ide> $router = $this->getRouter();
<del> $router->get('{foo?}/{baz?}', function($name = 'taylor', $age = 25) { return $name.$age; });
<add> $router->get('{foo?}/{baz?}', array('as' => 'foo', function($name = 'taylor', $age = 25) { return $name.$age; }));
<ide> $this->assertEquals('taylor25', $router->dispatch(Request::create('/', 'GET'))->getContent());
<ide> $this->assertEquals('fred25', $router->dispatch(Request::create('fred', 'GET'))->getContent());
<ide> $this->assertEquals('fred30', $router->dispatch(Request::create('fred/30', 'GET'))->getContent());
<add> $this->assertTrue($router->currentRouteNamed('foo'));
<ide> }
<ide>
<ide>
<ide> public function testDispatchingOfControllers()
<ide> $router->disableFilters();
<ide> $router->get('bar', 'RouteTestControllerDispatchStub@bar');
<ide> $this->assertEquals('baz', $router->dispatch(Request::create('bar', 'GET'))->getContent());
<add>
<add> $this->assertTrue($router->currentRouteUses('RouteTestControllerDispatchStub@bar'));
<ide> }
<ide>
<ide>
| 2
|
Javascript
|
Javascript
|
es6ify the contextreplacementplugin
|
376d31fb6c94423414f23b93c5601d5b76dade3b
|
<ide><path>lib/ContextReplacementPlugin.js
<ide> MIT License http://www.opensource.org/licenses/mit-license.php
<ide> Author Tobias Koppers @sokra
<ide> */
<del>var path = require("path");
<del>var ContextElementDependency = require("./dependencies/ContextElementDependency");
<add>"use strict";
<ide>
<del>function ContextReplacementPlugin(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) {
<del> this.resourceRegExp = resourceRegExp;
<del> if(typeof newContentResource === "function") {
<del> this.newContentCallback = newContentResource;
<del> } else if(typeof newContentResource === "string" && typeof newContentRecursive === "object") {
<del> this.newContentResource = newContentResource;
<del> this.newContentCreateContextMap = function(fs, callback) {
<del> callback(null, newContentRecursive);
<del> };
<del> } else if(typeof newContentResource === "string" && typeof newContentRecursive === "function") {
<del> this.newContentResource = newContentResource;
<del> this.newContentCreateContextMap = newContentRecursive;
<del> } else {
<del> if(typeof newContentResource !== "string") {
<del> newContentRegExp = newContentRecursive;
<del> newContentRecursive = newContentResource;
<del> newContentResource = undefined;
<del> }
<del> if(typeof newContentRecursive !== "boolean") {
<del> newContentRegExp = newContentRecursive;
<del> newContentRecursive = undefined;
<add>const path = require("path");
<add>const ContextElementDependency = require("./dependencies/ContextElementDependency");
<add>
<add>class ContextReplacementPlugin {
<add> constructor(resourceRegExp, newContentResource, newContentRecursive, newContentRegExp) {
<add> this.resourceRegExp = resourceRegExp;
<add>
<add> if(typeof newContentResource === "function") {
<add> this.newContentCallback = newContentResource;
<add> } else if(typeof newContentResource === "string" && typeof newContentRecursive === "object") {
<add> this.newContentResource = newContentResource;
<add> this.newContentCreateContextMap = (fs, callback) => {
<add> callback(null, newContentRecursive);
<add> };
<add> } else if(typeof newContentResource === "string" && typeof newContentRecursive === "function") {
<add> this.newContentResource = newContentResource;
<add> this.newContentCreateContextMap = newContentRecursive;
<add> } else {
<add> if(typeof newContentResource !== "string") {
<add> newContentRegExp = newContentRecursive;
<add> newContentRecursive = newContentResource;
<add> newContentResource = undefined;
<add> }
<add> if(typeof newContentRecursive !== "boolean") {
<add> newContentRegExp = newContentRecursive;
<add> newContentRecursive = undefined;
<add> }
<add> this.newContentResource = newContentResource;
<add> this.newContentRecursive = newContentRecursive;
<add> this.newContentRegExp = newContentRegExp;
<ide> }
<del> this.newContentResource = newContentResource;
<del> this.newContentRecursive = newContentRecursive;
<del> this.newContentRegExp = newContentRegExp;
<ide> }
<del>}
<del>module.exports = ContextReplacementPlugin;
<del>ContextReplacementPlugin.prototype.apply = function(compiler) {
<del> var resourceRegExp = this.resourceRegExp;
<del> var newContentCallback = this.newContentCallback;
<del> var newContentResource = this.newContentResource;
<del> var newContentRecursive = this.newContentRecursive;
<del> var newContentRegExp = this.newContentRegExp;
<del> var newContentCreateContextMap = this.newContentCreateContextMap;
<del> compiler.plugin("context-module-factory", function(cmf) {
<del> cmf.plugin("before-resolve", function(result, callback) {
<del> if(!result) return callback();
<del> if(resourceRegExp.test(result.request)) {
<del> if(typeof newContentResource !== "undefined")
<del> result.request = newContentResource;
<del> if(typeof newContentRecursive !== "undefined")
<del> result.recursive = newContentRecursive;
<del> if(typeof newContentRegExp !== "undefined")
<del> result.regExp = newContentRegExp;
<del> if(typeof newContentCallback === "function") {
<del> newContentCallback(result);
<del> } else {
<del> result.dependencies.forEach(function(d) {
<del> if(d.critical)
<del> d.critical = false;
<del> });
<add>
<add> apply(compiler) {
<add> const resourceRegExp = this.resourceRegExp;
<add> const newContentCallback = this.newContentCallback;
<add> const newContentResource = this.newContentResource;
<add> const newContentRecursive = this.newContentRecursive;
<add> const newContentRegExp = this.newContentRegExp;
<add> const newContentCreateContextMap = this.newContentCreateContextMap;
<add>
<add> compiler.plugin("context-module-factory", (cmf) => {
<add> cmf.plugin("before-resolve", (result, callback) => {
<add> if(!result) return callback();
<add> if(resourceRegExp.test(result.request)) {
<add> if(typeof newContentResource !== "undefined")
<add> result.request = newContentResource;
<add> if(typeof newContentRecursive !== "undefined")
<add> result.recursive = newContentRecursive;
<add> if(typeof newContentRegExp !== "undefined")
<add> result.regExp = newContentRegExp;
<add> if(typeof newContentCallback === "function") {
<add> newContentCallback(result);
<add> } else {
<add> result.dependencies.forEach((d) => {
<add> if(d.critical)
<add> d.critical = false;
<add> });
<add> }
<ide> }
<del> }
<del> return callback(null, result);
<del> });
<del> cmf.plugin("after-resolve", function(result, callback) {
<del> if(!result) return callback();
<del> if(resourceRegExp.test(result.resource)) {
<del> if(typeof newContentResource !== "undefined")
<del> result.resource = path.resolve(result.resource, newContentResource);
<del> if(typeof newContentRecursive !== "undefined")
<del> result.recursive = newContentRecursive;
<del> if(typeof newContentRegExp !== "undefined")
<del> result.regExp = newContentRegExp;
<del> if(typeof newContentCreateContextMap === "function")
<del> result.resolveDependencies = createResolveDependenciesFromContextMap(newContentCreateContextMap);
<del> if(typeof newContentCallback === "function") {
<del> var origResource = result.resource;
<del> newContentCallback(result);
<del> if(result.resource !== origResource) {
<del> result.resource = path.resolve(origResource, result.resource);
<add> return callback(null, result);
<add> });
<add> cmf.plugin("after-resolve", (result, callback) => {
<add> if(!result) return callback();
<add> if(resourceRegExp.test(result.resource)) {
<add> if(typeof newContentResource !== "undefined")
<add> result.resource = path.resolve(result.resource, newContentResource);
<add> if(typeof newContentRecursive !== "undefined")
<add> result.recursive = newContentRecursive;
<add> if(typeof newContentRegExp !== "undefined")
<add> result.regExp = newContentRegExp;
<add> if(typeof newContentCreateContextMap === "function")
<add> result.resolveDependencies = createResolveDependenciesFromContextMap(newContentCreateContextMap);
<add> if(typeof newContentCallback === "function") {
<add> const origResource = result.resource;
<add> newContentCallback(result);
<add> if(result.resource !== origResource) {
<add> result.resource = path.resolve(origResource, result.resource);
<add> }
<add> } else {
<add> result.dependencies.forEach((d) => {
<add> if(d.critical)
<add> d.critical = false;
<add> });
<ide> }
<del> } else {
<del> result.dependencies.forEach(function(d) {
<del> if(d.critical)
<del> d.critical = false;
<del> });
<ide> }
<del> }
<del> return callback(null, result);
<add> return callback(null, result);
<add> });
<ide> });
<del> });
<del>};
<add> }
<add>}
<ide>
<del>function createResolveDependenciesFromContextMap(createContextMap) {
<add>const createResolveDependenciesFromContextMap = (createContextMap) => {
<ide> return function resolveDependenciesFromContextMap(fs, resource, recursive, regExp, callback) {
<del> createContextMap(fs, function(err, map) {
<add> createContextMap(fs, (err, map) => {
<ide> if(err) return callback(err);
<del> var dependencies = Object.keys(map).map(function(key) {
<add> const dependencies = Object.keys(map).map((key) => {
<ide> return new ContextElementDependency(map[key], key);
<ide> });
<ide> callback(null, dependencies);
<ide> });
<ide> };
<del>}
<add>};
<add>
<add>module.exports = ContextReplacementPlugin;
| 1
|
Ruby
|
Ruby
|
add extmodel helper
|
655c6f79b435364cfaf23808f0e5650e3a6d0f72
|
<ide><path>Library/Homebrew/os/mac/hardware.rb
<ide> def family
<ide> end
<ide> end
<ide>
<add> def extmodel
<add> @extmodel ||= `/usr/sbin/sysctl -n machdep.cpu.extmodel`.to_i
<add> end
<add>
<ide> def cores
<ide> @cores ||= `/usr/sbin/sysctl -n hw.ncpu`.to_i
<ide> end
| 1
|
Text
|
Text
|
fix copyright notice and travis badge
|
05c72a5d303490270c9d56b81964ee59fc1ab253
|
<ide><path>README.md
<ide> This change will not affect user code, so long as it's following the recommended
<ide>
<ide> # License
<ide>
<del>Copyright (c) 2011, Tom Christie
<add>Copyright (c) 2011-2013, Tom Christie
<ide> All rights reserved.
<ide>
<ide> Redistribution and use in source and binary forms, with or without
<ide> CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
<ide> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide>
<del>[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
<add>[build-status-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
<ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
<ide> [twitter]: https://twitter.com/_tomchristie
<ide> [group]: https://groups.google.com/forum/?fromgroups#!forum/django-rest-framework
<ide><path>docs/index.md
<ide> Paid support is also available from [DabApps], and can include work on REST fram
<ide>
<ide> ## License
<ide>
<del>Copyright (c) 2011-2012, Tom Christie
<add>Copyright (c) 2011-2013, Tom Christie
<ide> All rights reserved.
<ide>
<ide> Redistribution and use in source and binary forms, with or without
<ide> OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
<ide> OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
<ide>
<ide> [travis]: http://travis-ci.org/tomchristie/django-rest-framework?branch=master
<del>[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=restframework2
<add>[travis-build-image]: https://secure.travis-ci.org/tomchristie/django-rest-framework.png?branch=master
<ide> [urlobject]: https://github.com/zacharyvoase/urlobject
<ide> [markdown]: http://pypi.python.org/pypi/Markdown/
<ide> [yaml]: http://pypi.python.org/pypi/PyYAML
| 2
|
PHP
|
PHP
|
update config check to not skip tests
|
74c6effd22ba9687cb6295c339bc8df15378a139
|
<ide><path>tests/TestCase/Database/Schema/MysqlSchemaTest.php
<ide> class MysqlSchemaTest extends TestCase {
<ide> */
<ide> protected function _needsConnection() {
<ide> $config = ConnectionManager::config('test');
<del> $this->skipIf(strpos($config['className'], 'Mysql') === false, 'Not using Mysql for test config');
<add> $this->skipIf(strpos($config['driver'], 'Mysql') === false, 'Not using Mysql for test config');
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/SqliteSchemaTest.php
<ide> class SqliteSchemaTest extends TestCase {
<ide> */
<ide> protected function _needsConnection() {
<ide> $config = ConnectionManager::config('test');
<del> $this->skipIf(strpos($config['className'], 'Sqlite') === false, 'Not using Sqlite for test config');
<add> $this->skipIf(strpos($config['driver'], 'Sqlite') === false, 'Not using Sqlite for test config');
<ide> }
<ide>
<ide> /**
| 2
|
Ruby
|
Ruby
|
fix typo in amo docs [ci skip]
|
a6da73f975892635e6a0bcbfe8eb8410fcbb07a4
|
<ide><path>activemodel/lib/active_model/attribute_methods.rb
<ide> def attribute_alias(name)
<ide> # private
<ide> #
<ide> # def clear_attribute(attr)
<del> # send("#{attr}", nil)
<add> # send("#{attr}=", nil)
<ide> # end
<ide> # end
<ide> def define_attribute_methods(*attr_names)
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
327031084cb24584ef7683137d72a260ff62a314
|
<ide><path>src/Illuminate/Broadcasting/BroadcastEvent.php
<ide> use ReflectionProperty;
<ide> use Illuminate\Bus\Queueable;
<ide> use Illuminate\Contracts\Queue\Job;
<del>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Contracts\Queue\ShouldQueue;
<add>use Illuminate\Contracts\Support\Arrayable;
<ide> use Illuminate\Contracts\Broadcasting\Broadcaster;
<ide>
<ide> class BroadcastEvent implements ShouldQueue
| 1
|
Javascript
|
Javascript
|
prevent extensions to fiber in dev
|
ddf59c403a99efa0eae873e38b7293b52d1e00b7
|
<ide><path>src/renderers/shared/fiber/ReactFiber.js
<ide> var createFiber = function(tag : TypeOfWork, key : null | string) : Fiber {
<ide> fiber._debugID = debugCounter++;
<ide> fiber._debugSource = null;
<ide> fiber._debugOwner = null;
<add> if (typeof Object.preventExtensions === 'function') {
<add> Object.preventExtensions(fiber);
<add> }
<ide> }
<ide>
<add>
<ide> return fiber;
<ide> };
<ide>
| 1
|
Python
|
Python
|
start work on testing ufuncs
|
24726567344dbd821d2a1a1b4f36bf1e89b0585a
|
<ide><path>numpy/core/tests/test_ufunc.py
<ide> def logical_and(self, obj) :
<ide> # check PyUFunc_On_Om
<ide> # fixme -- I don't know how to do this yet
<ide>
<add> def check_all_ufunc(self) :
<add> """Try to check presence and results of all ufuncs.
<add>
<add> The list of ufuncs comes from generate_umath.py and is as follows:
<add>
<add> add
<add> subtract
<add> multiply
<add> divide
<add> floor_divide
<add> true_divide
<add> conjugate
<add> fmod
<add> square
<add> reciprocal
<add> ones_like
<add> power
<add> absolute
<add> negative
<add> sign
<add> greater
<add> greate_equal
<add> less
<add> less_equal
<add> equal
<add> not_equal
<add> logical_and
<add> logical_or
<add> logical_xor
<add> maximum
<add> minimum
<add> bitwise_and
<add> bitwise_or
<add> bitwise_xor
<add> invert
<add> left_shift
<add> right_shift
<add> degrees
<add> radians
<add> arccos
<add> arccosh
<add> arcsin
<add> arcsinh
<add> arctan
<add> arctanh
<add> cos
<add> sin
<add> tan
<add> cosh
<add> sinh
<add> tanh
<add> exp
<add> expm1
<add> log
<add> log10
<add> log1p
<add> sqrt
<add> ceil
<add> fabs
<add> floor
<add> rint
<add> arctan2
<add> remainder
<add> hypot
<add> isnan
<add> isinf
<add> isfinite
<add> signbit
<add> modf
<add>
<add> """
<add> pass
<add>
<ide> if __name__ == "__main__":
<ide> NumpyTest().run()
| 1
|
PHP
|
PHP
|
fix docblock formatting
|
edb7e2def3beb83098db0a7b10463e65b544ed73
|
<ide><path>src/View/Helper/FormHelper.php
<ide> public function contextFactory(?ContextFactory $instance = null, array $contexts
<ide> *
<ide> * @param mixed $context The context for which the form is being defined.
<ide> * Can be a ContextInterface instance, ORM entity, ORM resultset, or an
<del> * array of meta data. You can use `null `to make a context-less form.
<add> * array of meta data. You can use `null` to make a context-less form.
<ide> * @param array $options An array of html attributes and options.
<ide> * @return string An formatted opening FORM tag.
<ide> * @link https://book.cakephp.org/3.0/en/views/helpers/form.html#Cake\View\Helper\FormHelper::create
| 1
|
Text
|
Text
|
add analytics link
|
d37f2e7ae7b6915063960998df16b3cf4f76115c
|
<ide><path>docs/New-Maintainer-Checklist.md
<ide> If they accept, follow a few steps to get them set up:
<ide> - Invite them to the [`homebrew-dev` private maintainers mailing list](https://groups.google.com/forum/#!managemembers/homebrew-dev/invite)
<ide> - Invite them to the [`machomebrew` private maintainers Slack](https://machomebrew.slack.com/admin/invites)
<ide> - Invite them to the [`homebrew` private maintainers 1Password](https://homebrew.1password.com/signin)
<add>- Invite them to [Google Analytics](https://analytics.google.com/analytics/web/?authuser=1#management/Settings/a76679469w115400090p120682403/%3Fm.page%3DAccountUsers/)
<ide> - Add them to [Homebrew's README](https://github.com/Homebrew/brew/edit/master/README.md)
<ide>
<ide> After a few weeks/months with no problems consider making them [owners on the Homebrew GitHub organisation](https://github.com/orgs/Homebrew/people).
| 1
|
Ruby
|
Ruby
|
fix docs in collection_radio_buttons
|
9ab63547e5ca52dc4d50d885c3b2da751b9381fc
|
<ide><path>actionview/lib/action_view/helpers/form_options_helper.rb
<ide> def time_zone_options_for_select(selected = nil, priority_zones = nil, model = :
<ide> # The HTML specification says when nothing is select on a collection of radio buttons
<ide> # web browsers do not send any value to server.
<ide> # Unfortunately this introduces a gotcha:
<del> # if a +User+ model has a +category_id+ field, and in the form none category is selected no +category_id+ parameter is sent. So,
<del> # any strong parameters idiom like
<add> # if a +User+ model has a +category_id+ field and in the form no category is selected, no +category_id+ parameter is sent. So,
<add> # any strong parameters idiom like:
<ide> #
<ide> # params.require(:user).permit(...)
<ide> #
<del> # will raise an error since no +{user: ...}+ will be present.
<add> # will raise an error since no <tt>{user: ...}</tt> will be present.
<ide> #
<ide> # To prevent this the helper generates an auxiliary hidden field before
<ide> # every collection of radio buttons. The hidden field has the same name as collection radio button and blank value.
| 1
|
Text
|
Text
|
fix the wrong title with docker swarm
|
f469021f88ef4765f9871c36b61e4f0138528a7b
|
<ide><path>docs/reference/glossary.md
<ide> environment.
<ide>
<ide> ## service discovery
<ide>
<del>Swarm mode [service discovery](https://docs.docker.com/engine/swarm/networking/) is a DNS component
<add>Swarm mode [service discovery](https://docs.docker.com/engine/swarm/networking/#use-swarm-mode-service-discovery) is a DNS component
<ide> internal to the swarm that automatically assigns each service on an overlay
<ide> network in the swarm a VIP and DNS entry. Containers on the network share DNS
<ide> mappings for the service via gossip so any container on the network can access
<ide> automatically distributes requests to the service VIP among the active tasks.
<ide>
<ide> A [swarm](https://docs.docker.com/engine/swarm/) is a cluster of one or more Docker Engines running in [swarm mode](#swarm-mode).
<ide>
<del>## Swarm
<add>## Docker Swarm
<ide>
<ide> Do not confuse [Docker Swarm](https://github.com/docker/swarm) with the [swarm mode](#swarm-mode) features in Docker Engine.
<ide>
| 1
|
Javascript
|
Javascript
|
fix syntax error
|
ab240196bf5cdbe85a18bfd7e7a6a287bf5c22f7
|
<ide><path>src/auto/injector.js
<ide> function annotate(fn, strictDi, name) {
<ide> * expect($injector.get('$injector')).toBe($injector);
<ide> * expect($injector.invoke(function($injector) {
<ide> * return $injector;
<del> * }).toBe($injector);
<add> * })).toBe($injector);
<ide> * ```
<ide> *
<ide> * # Injection Function Annotation
| 1
|
Ruby
|
Ruby
|
remove deprecated `selectmanager#joins`
|
36d3452f0471b9e2c151abf43e0392cb54f1f422
|
<ide><path>lib/arel/select_manager.rb
<ide> def source
<ide> @ctx.source
<ide> end
<ide>
<del> def joins manager
<del> if $VERBOSE
<del> warn "joins is deprecated and will be removed in 4.0.0"
<del> warn "please remove your call to joins from #{caller.first}"
<del> end
<del> manager.join_sql
<del> end
<del>
<ide> class Row < Struct.new(:data) # :nodoc:
<ide> def id
<ide> data['id']
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
a25f58690b4ae49869ef7022103381018b14b580
|
<ide><path>src/Illuminate/Redis/Connections/PhpRedisConnection.php
<ide> public function set($key, $value, $expireResolution = null, $expireTTL = null, $
<ide> return $this->command('set', [
<ide> $key,
<ide> $value,
<del> $expireResolution ? [$expireResolution, $flag => $expireTTL] : null
<add> $expireResolution ? [$expireResolution, $flag => $expireTTL] : null,
<ide> ]);
<ide> }
<ide>
<ide> public function zadd($key, array $membersAndScoresDictionary)
<ide> public function evalsha($script, $numkeys, ...$arguments)
<ide> {
<ide> return $this->command('evalsha', [
<del> $this->script('load', $script), $arguments, $numkeys
<add> $this->script('load', $script), $arguments, $numkeys,
<ide> ]);
<ide> }
<ide>
| 1
|
PHP
|
PHP
|
switch tasks from using execute() to using main()
|
2b40223a921ae8ea705c604b92f6de5bc6579800
|
<ide><path>src/Console/Command/Task/BakeTask.php
<ide> public function getPath() {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute() {
<add> public function main() {
<ide> foreach ($this->args as $i => $arg) {
<ide> if (strpos($arg, '.')) {
<ide> list($this->params['plugin'], $this->args[$i]) = pluginSplit($arg);
<ide><path>src/Console/Command/Task/ControllerTask.php
<ide> class ControllerTask extends BakeTask {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($name = null) {
<del> parent::execute();
<add> public function main($name = null) {
<add> parent::main();
<ide>
<ide> if (!isset($this->connection)) {
<ide> $this->connection = 'default';
<ide><path>src/Console/Command/Task/ExtractTask.php
<ide> protected function _getPaths() {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute() {
<add> public function main() {
<ide> if (!empty($this->params['exclude'])) {
<ide> $this->_exclude = explode(',', $this->params['exclude']);
<ide> }
<ide><path>src/Console/Command/Task/FixtureTask.php
<ide> public function getOptionParser() {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($name = null) {
<del> parent::execute();
<add> public function main($name = null) {
<add> parent::main();
<ide> if (!isset($this->connection)) {
<ide> $this->connection = 'default';
<ide> }
<ide><path>src/Console/Command/Task/ModelTask.php
<ide> class ModelTask extends BakeTask {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($name = null) {
<del> parent::execute();
<add> public function main($name = null) {
<add> parent::main();
<ide>
<ide> if (!isset($this->connection)) {
<ide> $this->connection = 'default';
<ide><path>src/Console/Command/Task/PluginTask.php
<ide> public function initialize() {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($name = null) {
<add> public function main($name = null) {
<ide> if (empty($name)) {
<ide> $this->err('<error>You must provide a plugin name in CamelCase format.</error>');
<ide> $this->err('To make an "Example" plugin, run <info>Console/cake bake plugin Example</info>.');
<ide><path>src/Console/Command/Task/ProjectTask.php
<ide> class ProjectTask extends BakeTask {
<ide> *
<ide> * @return mixed
<ide> */
<del> public function execute() {
<add> public function main() {
<ide> $project = null;
<ide> if (isset($this->args[0])) {
<ide> $project = $this->args[0];
<ide><path>src/Console/Command/Task/SimpleBakeTask.php
<ide> public function templateData() {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($name = null) {
<del> parent::execute();
<add> public function main($name = null) {
<add> parent::main();
<ide> if (empty($name)) {
<ide> return $this->error('You must provide a name to bake a ' . $this->name());
<ide> }
<ide><path>src/Console/Command/Task/TestTask.php
<ide> class TestTask extends BakeTask {
<ide> *
<ide> * @return void
<ide> */
<del> public function execute($type = null, $name = null) {
<del> parent::execute();
<add> public function main($type = null, $name = null) {
<add> parent::main();
<ide> if (empty($type) && empty($name)) {
<ide> return $this->outputTypeChoices();
<ide> }
<ide><path>src/Console/Command/Task/ViewTask.php
<ide> public function initialize() {
<ide> *
<ide> * @return mixed
<ide> */
<del> public function execute($name = null, $template = null, $action = null) {
<del> parent::execute();
<add> public function main($name = null, $template = null, $action = null) {
<add> parent::main();
<ide>
<ide> if (!isset($this->connection)) {
<ide> $this->connection = 'default';
<ide><path>src/Console/Shell.php
<ide> public function runCommand($argv) {
<ide> if ($this->hasTask($command) && isset($subcommands[$command])) {
<ide> $this->startup();
<ide> $command = Inflector::camelize($command);
<del> $argv[0] = 'execute';
<add> array_shift($argv);
<ide> return $this->{$command}->runCommand($argv);
<ide> }
<ide>
<ide><path>tests/TestCase/Console/ShellTest.php
<ide> public function testRunCommandHittingTaskInSubcommand() {
<ide> $parser->addSubcommand('slice');
<ide>
<ide> $shell = $this->getMock('Cake\Console\Shell', ['hasTask', 'startup', 'getOptionParser'], [], '', false);
<del> $task = $this->getMock('Cake\Console\Shell', ['execute', 'runCommand'], [], '', false);
<del> $task->expects($this->any())
<add> $task = $this->getMock('Cake\Console\Shell', ['main', 'runCommand'], [], '', false);
<add> $task->expects($this->once())
<ide> ->method('runCommand')
<del> ->with(['execute', 'one']);
<add> ->with(['one']);
<ide>
<ide> $shell->expects($this->once())->method('getOptionParser')
<ide> ->will($this->returnValue($parser));
| 12
|
Go
|
Go
|
remove trimleft as it's go1.1
|
854039b6ba9c707af07f9966b39150ce23150920
|
<ide><path>changes.go
<ide> func Changes(layers []string, rw string) ([]Change, error) {
<ide> file := filepath.Base(path)
<ide> // If there is a whiteout, then the file was removed
<ide> if strings.HasPrefix(file, ".wh.") {
<del> originalFile := strings.TrimPrefix(file, ".wh.")
<add> originalFile := file[len(".wh."):]
<ide> change.Path = filepath.Join(filepath.Dir(path), originalFile)
<ide> change.Kind = ChangeDelete
<ide> } else {
| 1
|
Javascript
|
Javascript
|
send referrer for internal links [ci skip]
|
232a029de68e7e238dfb066a74185ae78c75da49
|
<ide><path>website/src/components/link.js
<ide> import Icon from './icon'
<ide> import classes from '../styles/link.module.sass'
<ide> import { isString } from './util'
<ide>
<add>const internalRegex = /(http(s?)):\/\/(prodi.gy|spacy.io|irl.spacy.io)/gi
<add>
<ide> const Whitespace = ({ children }) => (
<ide> // Ensure that links are always wrapped in spaces
<ide> <> {children} </>
<ide> const Link = ({
<ide> </Wrapper>
<ide> )
<ide> }
<add> const isInternal = internalRegex.test(dest)
<add> const rel = isInternal ? null : 'noopener nofollow noreferrer'
<ide> return (
<ide> <Wrapper>
<ide> <OutboundLink
<ide> href={dest}
<ide> className={linkClassNames}
<ide> target="_blank"
<del> rel="noopener nofollow noreferrer"
<add> rel={rel}
<ide> {...other}
<ide> >
<ide> {content}
| 1
|
Mixed
|
Javascript
|
expose stats times as numbers
|
47b9772f52aba7693eed4df535b35de65ac22c49
|
<ide><path>doc/api/fs.md
<ide> argument to `fs.createReadStream()`. If `path` is passed as a string, then
<ide> ## Class: fs.Stats
<ide> <!-- YAML
<ide> added: v0.1.21
<add>changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/13173
<add> description: Added times as numbers.
<ide> -->
<ide>
<del>Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and their
<del>synchronous counterparts are of this type.
<add>Objects returned from [`fs.stat()`][], [`fs.lstat()`][] and [`fs.fstat()`][] and
<add>their synchronous counterparts are of this type.
<ide>
<ide> - `stats.isFile()`
<ide> - `stats.isDirectory()`
<ide> Stats {
<ide> size: 527,
<ide> blksize: 4096,
<ide> blocks: 8,
<add> atimeMs: 1318289051000.1,
<add> mtimeMs: 1318289051000.1,
<add> ctimeMs: 1318289051000.1,
<add> birthtimeMs: 1318289051000.1,
<ide> atime: Mon, 10 Oct 2011 23:24:11 GMT,
<ide> mtime: Mon, 10 Oct 2011 23:24:11 GMT,
<ide> ctime: Mon, 10 Oct 2011 23:24:11 GMT,
<ide> birthtime: Mon, 10 Oct 2011 23:24:11 GMT }
<ide> ```
<ide>
<del>Please note that `atime`, `mtime`, `birthtime`, and `ctime` are
<del>instances of [`Date`][MDN-Date] object and appropriate methods should be used
<del>to compare the values of these objects. For most general uses
<del>[`getTime()`][MDN-Date-getTime] will return the number of milliseconds elapsed
<del>since _1 January 1970 00:00:00 UTC_ and this integer should be sufficient for
<del>any comparison, however there are additional methods which can be used for
<del>displaying fuzzy information. More details can be found in the
<del>[MDN JavaScript Reference][MDN-Date] page.
<add>*Note*: `atimeMs`, `mtimeMs`, `ctimeMs`, `birthtimeMs` are [numbers][MDN-Number]
<add>that hold the corresponding times in milliseconds. Their precision is platform
<add>specific. `atime`, `mtime`, `ctime`, and `birthtime` are [`Date`][MDN-Date]
<add>object alternate representations of the various times. The `Date` and number
<add>values are not connected. Assigning a new number value, or mutating the `Date`
<add>value, will not be reflected in the corresponding alternate representation.
<add>
<ide>
<ide> ### Stat Time Values
<ide>
<ide> The following constants are meant for use with the [`fs.Stats`][] object's
<ide> [FS Constants]: #fs_fs_constants_1
<ide> [MDN-Date-getTime]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getTime
<ide> [MDN-Date]: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date
<add>[MDN-Number]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type
<ide> [MSDN-Rel-Path]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa365247.aspx#fully_qualified_vs._relative_paths
<ide> [Readable Stream]: stream.html#stream_class_stream_readable
<ide> [Writable Stream]: stream.html#stream_class_stream_writable
<ide><path>lib/fs.js
<ide> function Stats(
<ide> this.ino = ino;
<ide> this.size = size;
<ide> this.blocks = blocks;
<add> this.atimeMs = atim_msec;
<add> this.mtimeMs = mtim_msec;
<add> this.ctimeMs = ctim_msec;
<add> this.birthtimeMs = birthtim_msec;
<ide> this.atime = new Date(atim_msec + 0.5);
<ide> this.mtime = new Date(mtim_msec + 0.5);
<ide> this.ctime = new Date(ctim_msec + 0.5);
<ide><path>test/parallel/test-fs-stat.js
<ide> fs.open('.', 'r', undefined, common.mustCall(function(err, fd) {
<ide> assert.fail(err);
<ide> }
<ide> if (stats) {
<del> console.dir(stats);
<ide> assert.ok(stats.mtime instanceof Date);
<ide> }
<ide> fs.close(fd, assert.ifError);
<ide> }));
<ide>
<del>console.log(`stating: ${__filename}`);
<ide> fs.stat(__filename, common.mustCall(function(err, s) {
<ide> assert.ifError(err);
<del>
<del> console.dir(s);
<del>
<del> console.log(`isDirectory: ${JSON.stringify(s.isDirectory())}`);
<ide> assert.strictEqual(false, s.isDirectory());
<del>
<del> console.log(`isFile: ${JSON.stringify(s.isFile())}`);
<ide> assert.strictEqual(true, s.isFile());
<del>
<del> console.log(`isSocket: ${JSON.stringify(s.isSocket())}`);
<ide> assert.strictEqual(false, s.isSocket());
<del>
<del> console.log(`isBlockDevice: ${JSON.stringify(s.isBlockDevice())}`);
<ide> assert.strictEqual(false, s.isBlockDevice());
<del>
<del> console.log(`isCharacterDevice: ${JSON.stringify(s.isCharacterDevice())}`);
<ide> assert.strictEqual(false, s.isCharacterDevice());
<del>
<del> console.log(`isFIFO: ${JSON.stringify(s.isFIFO())}`);
<ide> assert.strictEqual(false, s.isFIFO());
<del>
<del> console.log(`isSymbolicLink: ${JSON.stringify(s.isSymbolicLink())}`);
<ide> assert.strictEqual(false, s.isSymbolicLink());
<del>
<del> assert.ok(s.mtime instanceof Date);
<add> const keys = [
<add> 'dev', 'mode', 'nlink', 'uid',
<add> 'gid', 'rdev', 'ino', 'size',
<add> 'atime', 'mtime', 'ctime', 'birthtime',
<add> 'atimeMs', 'mtimeMs', 'ctimeMs', 'birthtimeMs'
<add> ];
<add> if (!common.isWindows) {
<add> keys.push('blocks', 'blksize');
<add> }
<add> const numberFields = [
<add> 'dev', 'mode', 'nlink', 'uid', 'gid', 'rdev', 'ino', 'size',
<add> 'atimeMs', 'mtimeMs', 'ctimeMs', 'birthtimeMs'
<add> ];
<add> const dateFields = ['atime', 'mtime', 'ctime', 'birthtime'];
<add> keys.forEach(function(k) {
<add> assert.ok(k in s, `${k} should be in Stats`);
<add> assert.notStrictEqual(s[k], undefined, `${k} should not be undefined`);
<add> assert.notStrictEqual(s[k], null, `${k} should not be null`);
<add> });
<add> numberFields.forEach((k) => {
<add> assert.strictEqual(typeof s[k], 'number', `${k} should be a number`);
<add> });
<add> dateFields.forEach((k) => {
<add> assert.ok(s[k] instanceof Date, `${k} should be a Date`);
<add> });
<add> const jsonString = JSON.stringify(s);
<add> const parsed = JSON.parse(jsonString);
<add> keys.forEach(function(k) {
<add> assert.notStrictEqual(parsed[k], undefined, `${k} should not be undefined`);
<add> assert.notStrictEqual(parsed[k], null, `${k} should not be null`);
<add> });
<add> numberFields.forEach((k) => {
<add> assert.strictEqual(typeof parsed[k], 'number', `${k} should be a number`);
<add> });
<add> dateFields.forEach((k) => {
<add> assert.strictEqual(typeof parsed[k], 'string', `${k} should be a string`);
<add> });
<ide> }));
| 3
|
Javascript
|
Javascript
|
limit math.asin inputs to the range [-1, 1]
|
df4944786709fb2b3a9038e6676f5491d9243a14
|
<ide><path>src/core/core.scale.js
<ide> export default class Scale extends Element {
<ide> - tickOpts.padding - getTitleHeight(options.title, me.chart.options.font);
<ide> maxLabelDiagonal = Math.sqrt(maxLabelWidth * maxLabelWidth + maxLabelHeight * maxLabelHeight);
<ide> labelRotation = toDegrees(Math.min(
<del> Math.asin(Math.min((labelSizes.highest.height + 6) / tickWidth, 1)),
<del> Math.asin(Math.min(maxHeight / maxLabelDiagonal, 1)) - Math.asin(maxLabelHeight / maxLabelDiagonal)
<add> Math.asin(_limitValue((labelSizes.highest.height + 6) / tickWidth, -1, 1)),
<add> Math.asin(_limitValue(maxHeight / maxLabelDiagonal, -1, 1)) - Math.asin(_limitValue(maxLabelHeight / maxLabelDiagonal, -1, 1))
<ide> ));
<ide> labelRotation = Math.max(minRotation, Math.min(maxRotation, labelRotation));
<ide> }
| 1
|
Text
|
Text
|
update devops steps
|
df8bbdb2c8470e93f6797ef066bebd3a40c33891
|
<ide><path>docs/flight-manuals/working-on-virtual-machines.md
<ide> Provisioning VMs with the Code
<ide> ```console
<ide> git clone https://github.com/freeCodeCamp/freeCodeCamp.git
<ide> cd freeCodeCamp
<add> git checkout production-current # or any other branch to be deployed
<ide> ```
<ide>
<ide> 4. Create the `.env` from the secure credentials storage.
<ide>
<del>5. Install dependencies
<add>5. Create the `google-credentials.json` from the secure credentials storage.
<add>
<add>6. Install dependencies
<ide>
<ide> ```console
<ide> npm ci
<ide> ```
<ide>
<del>6. Build the server
<add>7. Build the server
<ide>
<ide> ```console
<ide> npm run ensure-env && npm run build:server
<ide> ```
<ide>
<del>7. Start Instances
<add>8. Start Instances
<ide>
<ide> ```console
<ide> cd api-server
| 1
|
PHP
|
PHP
|
apply fixes from styleci
|
e83703e49862f62246b49a74b42ca03422b8d995
|
<ide><path>src/Illuminate/Http/Concerns/InteractsWithInput.php
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Http\UploadedFile;
<del>use Symfony\Component\HttpFoundation\ParameterBag;
<ide>
<ide> trait InteractsWithInput
<ide> {
<ide><path>src/Illuminate/Http/Request.php
<ide>
<ide> use Closure;
<ide> use ArrayAccess;
<del>use SplFileInfo;
<ide> use RuntimeException;
<ide> use Illuminate\Support\Arr;
<ide> use Illuminate\Support\Str;
| 2
|
PHP
|
PHP
|
fix flakey tests
|
56c6314eefea7e5b298a0d84d742371d5d54ff6f
|
<ide><path>tests/Integration/Queue/ThrottlesExceptionsWithRedisTest.php
<ide> public function testCircuitResetsAfterSuccess()
<ide> $this->assertJobRanSuccessfully(CircuitBreakerWithRedisSuccessfulJob::class, $key);
<ide> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key);
<ide> $this->assertJobWasReleasedImmediately(CircuitBreakerWithRedisTestJob::class, $key);
<del> $this->assertJobWasReleasedWithDelay(CircuitBreakerWithRedisTestJob::class, $key);
<add>
<add> retry(2, function () use ($key) {
<add> $this->assertJobWasReleasedWithDelay(CircuitBreakerWithRedisTestJob::class, $key);
<add> });
<ide> }
<ide>
<ide> protected function assertJobWasReleasedImmediately($class, $key)
| 1
|
Python
|
Python
|
use config fixture, get plugin via unregister
|
604cc758fb6601782745572452715fc295dda011
|
<ide><path>tests/test_logging.py
<ide>
<ide>
<ide> @pytest.fixture(autouse=True)
<del>def reset_logging(monkeypatch):
<add>def reset_logging(pytestconfig):
<ide> root_handlers = logging.root.handlers[:]
<add> logging.root.handlers = []
<ide> root_level = logging.root.level
<ide>
<ide> logger = logging.getLogger('flask.app')
<ide> logger.handlers = []
<ide> logger.setLevel(logging.NOTSET)
<ide>
<del> logging_plugin = pytest.config.pluginmanager.getplugin('logging-plugin')
<del> pytest.config.pluginmanager.unregister(name='logging-plugin')
<del> logging.root.handlers = []
<add> logging_plugin = pytestconfig.pluginmanager.unregister(
<add> name='logging-plugin')
<ide>
<ide> yield
<ide>
<ide> def reset_logging(monkeypatch):
<ide> logger.setLevel(logging.NOTSET)
<ide>
<ide> if logging_plugin:
<del> pytest.config.pluginmanager.register(logging_plugin, 'logging-plugin')
<add> pytestconfig.pluginmanager.register(logging_plugin, 'logging-plugin')
<ide>
<ide>
<ide> def test_logger(app):
| 1
|
Python
|
Python
|
fix ticket #408 --- chararray problem with argsort
|
77295888c6913b2bccaf69571fc97f87d211aa62
|
<ide><path>numpy/core/defchararray.py
<ide> def __mod__(self, other):
<ide> def __rmod__(self, other):
<ide> return NotImplemented
<ide>
<add> def argsort(self, axis=-1, kind='quicksort', order=None):
<add> return self.__array__().argsort(axis, kind, order)
<add>
<ide> def _generalmethod(self, name, myiter):
<ide> res = [None]*myiter.size
<ide> maxsize = -1
| 1
|
Javascript
|
Javascript
|
remove repeated code
|
ed811a5aa8f5437755b7d1001fb62ffdb15c31a4
|
<ide><path>lib/ContextModule.js
<ide> class ContextModule extends Module {
<ide> return fakeMap;
<ide> }
<ide>
<add> getFakeMapInitStatement(fakeMap) {
<add> return typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : "";
<add> }
<add>
<ide> getReturnModuleObjectSource(fakeMap, fakeMapDataExpression = "fakeMap[id]") {
<ide> const strict = this.options.namespaceObject === "strict";
<ide> const getReturn = type => {
<ide> class ContextModule extends Module {
<ide> const returnModuleObject = `${this.getReturnModuleObjectSource(fakeMap)};`;
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<del>${typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""}
<add>${this.getFakeMapInitStatement(fakeMap)}
<ide>
<ide> function webpackContext(req) {
<ide> var id = webpackContextResolve(req);
<ide> webpackContext.id = ${JSON.stringify(id)};`;
<ide> const returnModuleObject = `${this.getReturnModuleObjectSource(fakeMap)};`;
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<del>${typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""}
<add>${this.getFakeMapInitStatement(fakeMap)}
<ide>
<ide> function webpackContext(req) {
<ide> var id = webpackContextResolve(req);
<ide> module.exports = webpackContext;`;
<ide> const returnModuleObject = `${this.getReturnModuleObjectSource(fakeMap)};`;
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<del>${typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""}
<add>${this.getFakeMapInitStatement(fakeMap)}
<ide>
<ide> function webpackAsyncContext(req) {
<ide> return webpackAsyncContextResolve(req).then(function(id) {
<ide> module.exports = webpackAsyncContext;`;
<ide> }` :
<ide> "__webpack_require__";
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<del>${typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""}
<add>${this.getFakeMapInitStatement(fakeMap)}
<ide>
<ide> function webpackAsyncContext(req) {
<ide> return webpackAsyncContextResolve(req).then(${thenFunction});
<ide> module.exports = webpackAsyncContext;`;
<ide> "__webpack_require__";
<ide>
<ide> return `var map = ${JSON.stringify(map, null, "\t")};
<del>${typeof fakeMap === "object" ? `var fakeMap = ${JSON.stringify(fakeMap, null, "\t")};` : ""}
<add>${this.getFakeMapInitStatement(fakeMap)}
<ide>
<ide> function webpackAsyncContext(req) {
<ide> return webpackAsyncContextResolve(req).then(${thenFunction});
| 1
|
Javascript
|
Javascript
|
propagate --debug-port= to debuggee
|
18fb4f9a912e775dde49e31bf749a9060b2c59e6
|
<ide><path>lib/_debugger.js
<ide> exports.start = function(argv, stdin, stdout) {
<ide> stdin = stdin || process.stdin;
<ide> stdout = stdout || process.stdout;
<ide>
<del> const args = ['--debug-brk'].concat(argv);
<add> const args = [`--debug-brk=${exports.port}`].concat(argv);
<ide> const interface_ = new Interface(stdin, stdout, args);
<ide>
<ide> stdin.resume();
<ide> exports.start = function(argv, stdin, stdout) {
<ide> });
<ide> };
<ide>
<del>exports.port = 5858;
<add>exports.port = process.debugPort;
<ide>
<ide>
<ide> //
<ide><path>test/parallel/test-debug-port-numbers.js
<add>'use strict';
<add>
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const path = require('path');
<add>const spawn = require('child_process').spawn;
<add>
<add>const children = [];
<add>for (let i = 0; i < 4; i += 1) {
<add> const port = common.PORT + i;
<add> const args = [`--debug-port=${port}`, '--interactive', 'debug', __filename];
<add> const child = spawn(process.execPath, args, { stdio: 'pipe' });
<add> child.test = { port: port, stdout: '' };
<add> child.stdout.setEncoding('utf8');
<add> child.stdout.on('data', function(s) { child.test.stdout += s; update(); });
<add> child.stdout.pipe(process.stdout);
<add> child.stderr.pipe(process.stderr);
<add> children.push(child);
<add>}
<add>
<add>function update() {
<add> // Debugger prints relative paths except on Windows.
<add> const filename = path.basename(__filename);
<add>
<add> let ready = 0;
<add> for (const child of children)
<add> ready += RegExp(`break in .*?${filename}:1`).test(child.test.stdout);
<add>
<add> if (ready === children.length)
<add> for (const child of children)
<add> child.kill();
<add>}
<add>
<add>process.on('exit', function() {
<add> for (const child of children) {
<add> const one = RegExp(`Debugger listening on port ${child.test.port}`);
<add> const two = RegExp(`connecting to 127.0.0.1:${child.test.port}`);
<add> assert(one.test(child.test.stdout));
<add> assert(two.test(child.test.stdout));
<add> }
<add>});
| 2
|
Javascript
|
Javascript
|
remove usused dependency
|
c0b01d91230ebebc4c7b549f4f46e9ab02cd40a8
|
<ide><path>src/ngAnimate/ngAnimateSwap.js
<ide> * </file>
<ide> * </example>
<ide> */
<del>var ngAnimateSwapDirective = ['$animate', '$rootScope', function($animate, $rootScope) {
<add>var ngAnimateSwapDirective = ['$animate', function($animate) {
<ide> return {
<ide> restrict: 'A',
<ide> transclude: 'element',
| 1
|
Python
|
Python
|
fix version checks in configure.py
|
d769ebc2b7be23d66033d8df71f70e0564436e72
|
<ide><path>configure.py
<ide> import bz2
<ide>
<ide> from distutils.spawn import find_executable as which
<add>from distutils.version import StrictVersion
<ide>
<ide> # If not run from node/, cd to node/.
<ide> os.chdir(os.path.dirname(__file__) or '.')
<ide> def without_ssl_error(option):
<ide> # supported asm compiler for AVX2. See https://github.com/openssl/openssl/
<ide> # blob/OpenSSL_1_1_0-stable/crypto/modes/asm/aesni-gcm-x86_64.pl#L52-L69
<ide> openssl110_asm_supported = \
<del> ('gas_version' in variables and float(variables['gas_version']) >= 2.23) or \
<del> ('xcode_version' in variables and float(variables['xcode_version']) >= 5.0) or \
<del> ('llvm_version' in variables and float(variables['llvm_version']) >= 3.3) or \
<del> ('nasm_version' in variables and float(variables['nasm_version']) >= 2.10)
<add> ('gas_version' in variables and StrictVersion(variables['gas_version']) >= StrictVersion('2.23')) or \
<add> ('xcode_version' in variables and StrictVersion(variables['xcode_version']) >= StrictVersion('5.0')) or \
<add> ('llvm_version' in variables and StrictVersion(variables['llvm_version']) >= StrictVersion('3.3')) or \
<add> ('nasm_version' in variables and StrictVersion(variables['nasm_version']) >= StrictVersion('2.10'))
<ide>
<ide> if is_x86 and not openssl110_asm_supported:
<ide> error('''Did not find a new enough assembler, install one or build with
| 1
|
Text
|
Text
|
add changelog entry for
|
f274fbd240a1c4c52fe22eec181db2f429baf8da
|
<ide><path>activerecord/CHANGELOG.md
<add>* Return a non zero status when running `rake db:migrate:status` and migration table does
<add> not exist.
<add>
<add> *Paul B.*
<add>
<ide> * Keep track of dirty attributes after transaction is rollback.
<ide>
<ide> Related #13166.
| 1
|
Java
|
Java
|
introduce alias for 'value' attribute in @header
|
60a5ec87d03e4dea9a1a3550bec06797c889e66f
|
<ide><path>spring-jms/src/test/java/org/springframework/jms/config/MethodJmsListenerEndpointTests.java
<ide> public void resolveCustomHeaderNameAndPayload() throws JMSException {
<ide> assertDefaultListenerMethodInvocation();
<ide> }
<ide>
<add> @Test
<add> public void resolveCustomHeaderNameAndPayloadWithHeaderNameSet() throws JMSException {
<add> MessagingMessageListenerAdapter listener = createDefaultInstance(String.class, int.class);
<add>
<add> Session session = mock(Session.class);
<add> StubTextMessage message = createSimpleJmsTextMessage("my payload");
<add> message.setIntProperty("myCounter", 24);
<add> listener.onMessage(message, session);
<add> assertDefaultListenerMethodInvocation();
<add> }
<add>
<ide> @Test
<ide> public void resolveHeaders() throws JMSException {
<ide> MessagingMessageListenerAdapter listener = createDefaultInstance(String.class, Map.class);
<ide> public void resolveCustomHeaderNameAndPayload(@Payload String content, @Header("
<ide> assertEquals("Wrong @Header resolution", 24, counter);
<ide> }
<ide>
<add> public void resolveCustomHeaderNameAndPayloadWithHeaderNameSet(@Payload String content, @Header(name = "myCounter") int counter) {
<add> invocations.put("resolveCustomHeaderNameAndPayloadWithHeaderNameSet", true);
<add> assertEquals("Wrong @Payload resolution", "my payload", content);
<add> assertEquals("Wrong @Header resolution", 24, counter);
<add> }
<add>
<ide> public void resolveHeaders(String content, @Headers Map<String, Object> headers) {
<ide> invocations.put("resolveHeaders", true);
<ide> assertEquals("Wrong payload resolution", "my payload", content);
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/Header.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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.lang.annotation.RetentionPolicy;
<ide> import java.lang.annotation.Target;
<ide>
<add>import org.springframework.core.annotation.AliasFor;
<add>
<ide> /**
<ide> * Annotation which indicates that a method parameter should be bound to a message header.
<ide> *
<ide> * @author Rossen Stoyanchev
<add> * @author Sam Brannen
<ide> * @since 4.0
<ide> */
<ide> @Target(ElementType.PARAMETER)
<ide> public @interface Header {
<ide>
<ide> /**
<del> * The name of the request header to bind to.
<add> * Alias for {@link #name}.
<ide> */
<add> @AliasFor(attribute = "name")
<ide> String value() default "";
<ide>
<add> /**
<add> * The name of the request header to bind to.
<add> * @since 4.2
<add> */
<add> @AliasFor(attribute = "value")
<add> String name() default "";
<add>
<ide> /**
<ide> * Whether the header is required.
<del> * <p>Default is {@code true}, leading to an exception if the header missing. Switch this
<del> * to {@code false} if you prefer a {@code null} in case of the header missing.
<add> * <p>Default is {@code true}, leading to an exception if the header is
<add> * missing. Switch this to {@code false} if you prefer a {@code null}
<add> * value in case of a header missing.
<add> * @see #defaultValue
<ide> */
<ide> boolean required() default true;
<ide>
<ide> /**
<del> * The default value to use as a fallback. Supplying a default value implicitly
<del> * sets {@link #required} to {@code false}.
<add> * The default value to use as a fallback.
<add> * <p>Supplying a default value implicitly sets {@link #required} to {@code false}.
<ide> */
<ide> String defaultValue() default ValueConstants.DEFAULT_NONE;
<ide>
<ide><path>spring-messaging/src/main/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolver.java
<ide> protected void handleMissingValue(String headerName, MethodParameter parameter,
<ide> private static class HeaderNamedValueInfo extends NamedValueInfo {
<ide>
<ide> private HeaderNamedValueInfo(Header annotation) {
<del> super(annotation.value(), annotation.required(), annotation.defaultValue());
<add> super(annotation.name(), annotation.required(), annotation.defaultValue());
<ide> }
<ide> }
<ide>
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/handler/annotation/support/HeaderMethodArgumentResolverTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> public void resolveDefaultValueSystemProperty() throws Exception {
<ide> @SuppressWarnings("unused")
<ide> private void handleMessage(
<ide> @Header String param1,
<del> @Header(value = "name", defaultValue = "bar") String param2,
<del> @Header(value = "name", defaultValue="#{systemProperties.systemProperty}") String param3,
<add> @Header(name = "name", defaultValue = "bar") String param2,
<add> @Header(name = "name", defaultValue = "#{systemProperties.systemProperty}") String param3,
<ide> String param4,
<ide> @Header("nativeHeaders.param1") String nativeHeaderParam1) {
<ide> }
<ide><path>spring-messaging/src/test/java/org/springframework/messaging/simp/annotation/support/SimpAnnotationMethodMessageHandlerTests.java
<ide> /*
<del> * Copyright 2002-2014 the original author or authors.
<add> * Copyright 2002-2015 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> public void headers(@Header String foo, @Headers Map<String, Object> headers) {
<ide> }
<ide>
<ide> @MessageMapping("/optionalHeaders")
<del> public void optionalHeaders(@Header(value="foo", required=false) String foo1, @Header(value="foo") Optional<String> foo2) {
<add> public void optionalHeaders(@Header(name="foo", required=false) String foo1, @Header("foo") Optional<String> foo2) {
<ide> this.method = "optionalHeaders";
<ide> this.arguments.put("foo1", foo1);
<ide> this.arguments.put("foo2", (foo2.isPresent() ? foo2.get() : null));
| 5
|
Javascript
|
Javascript
|
add "aspath" information to url objects
|
2cfcc6bd5eeb5f2a0b3597100ff715d65abc8a73
|
<ide><path>lib/app.js
<ide> function createUrl (router) {
<ide> return {
<ide> query: router.query,
<ide> pathname: router.pathname,
<add> asPath: router.asPath,
<ide> back: () => {
<ide> warn(`Warning: 'url.back()' is deprecated. Use "window.history.back()"`)
<ide> router.back()
| 1
|
Javascript
|
Javascript
|
add safari 12 & ios 12 results
|
3ac907864c4d36b4fcb58826d9cb0e4ed62334b2
|
<ide><path>test/unit/support.js
<ide> testIframe(
<ide> "reliableMarginLeft": true,
<ide> "scrollboxSize": true
<ide> },
<del> safari_11: {
<add> safari: {
<ide> "ajax": true,
<ide> "boxSizingReliable": true,
<ide> "checkClone": true,
<ide> testIframe(
<ide> "reliableMarginLeft": false,
<ide> "scrollboxSize": true
<ide> },
<del> ios_11: {
<add> ios: {
<ide> "ajax": true,
<ide> "boxSizingReliable": true,
<ide> "checkClone": true,
<ide> testIframe(
<ide> // Catches Chrome on Android as well (i.e. the default
<ide> // Android browser on Android >= 4.4).
<ide> expected = expectedMap.chrome;
<del> } else if ( /\b11\.\d(\.\d+)* safari/i.test( userAgent ) ) {
<del> expected = expectedMap.safari_11;
<add> } else if ( /\b(?:11|12)\.\d(\.\d+)* safari/i.test( userAgent ) ) {
<add> expected = expectedMap.safari;
<ide> } else if ( /\b(?:9|10)\.\d(\.\d+)* safari/i.test( userAgent ) ) {
<ide> expected = expectedMap.safari_9_10;
<ide> } else if ( /firefox\/(?:52|60)/i.test( userAgent ) ) {
<ide> expected = expectedMap.firefox_60;
<ide> } else if ( /firefox/i.test( userAgent ) ) {
<ide> expected = expectedMap.firefox;
<del> } else if ( /(?:iphone|ipad);.*(?:iphone)? os 11_/i.test( userAgent ) ) {
<del> expected = expectedMap.ios_11;
<add> } else if ( /(?:iphone|ipad);.*(?:iphone)? os (?:11|12)_/i.test( userAgent ) ) {
<add> expected = expectedMap.ios;
<ide> } else if ( /iphone os (?:9|10)_/i.test( userAgent ) ) {
<ide> expected = expectedMap.ios_9_10;
<ide> } else if ( /iphone os 8_/i.test( userAgent ) ) {
| 1
|
Javascript
|
Javascript
|
remove remaining angular directives
|
bfb19668eb1f895933bde0d5db0dca121ee9c203
|
<ide><path>public/js/main_0.0.3.js
<ide> $(document).ready(function() {
<ide> });
<ide> };
<ide>
<del>
<del>
<ide> $(window).resize(function(){
<ide> reBindModals();
<ide> });
<ide> $(document).ready(function() {
<ide> function defCheck(a){
<ide> if(a !== 'undefined'){return(true);}else{return(false);}
<ide> }
<del>
<del>var profileValidation = angular.module('profileValidation',
<del> ['ui.bootstrap']);
<del>profileValidation.controller('profileValidationController', ['$scope', '$http',
<del> function($scope, $http) {
<del> $http.get('/account/api').success(function(data) {
<del> $scope.user = data.user;
<del> $scope.user.username = $scope.user.username ? $scope.user.username.toLowerCase() : undefined;
<del> $scope.storedUsername = data.user.username;
<del> $scope.storedEmail = data.user.email;
<del> $scope.user.email = $scope.user.email ? $scope.user.email.toLowerCase() : undefined;
<del> $scope.user.twitterHandle = $scope.user.twitterHandle ? $scope.user.twitterHandle.toLowerCase() : undefined;
<del> $scope.asyncComplete = true;
<del> });
<del> }
<del>]);
<del>
<del>profileValidation.controller('pairedWithController', ['$scope',
<del> function($scope) {
<del> $scope.existingUser = null;
<del> }
<del>]);
<del>
<del>profileValidation.controller('emailSignUpController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.controller('emailSignInController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.controller('URLSubmitController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.controller('nonprofitFormController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.controller('doneWithFirst100HoursFormController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.controller('submitStoryController', ['$scope',
<del> function($scope) {
<del>
<del> }
<del>]);
<del>
<del>profileValidation.directive('uniqueUsername', ['$http', function($http) {
<del> return {
<del> restrict: 'A',
<del> require: 'ngModel',
<del> link: function (scope, element, attrs, ngModel) {
<del> element.bind("keyup", function (event) {
<del> ngModel.$setValidity('unique', true);
<del> var username = element.val();
<del> if (username) {
<del> var config = { params: { username: username } };
<del> $http
<del> .get('/api/users/exists', config)
<del> .success(function (result) {
<del> if (username === scope.storedUsername) {
<del> ngModel.$setValidity('unique', true);
<del> } else if (result.exists) {
<del> ngModel.$setValidity('unique', false);
<del> }
<del> });
<del> }
<del> });
<del> }
<del> };
<del>}]);
<del>
<del>profileValidation.directive('existingUsername',
<del> ['$http', function($http) {
<del> return {
<del> restrict: 'A',
<del> require: 'ngModel',
<del> link: function (scope, element, attrs, ngModel) {
<del> element.bind('keyup', function (event) {
<del> if (element.val().length > 0) {
<del> ngModel.$setValidity('exists', false);
<del> } else {
<del> element.removeClass('ng-dirty');
<del> ngModel.$setPristine();
<del> }
<del> var username = element.val();
<del> if (username) {
<del> var config = { params: { username: username } };
<del> $http
<del> .get('/api/users/exists', config)
<del> .success(function(result) {
<del> ngModel.$setValidity('exists', result.exists);
<del> });
<del> }
<del> });
<del> }
<del> };
<del> }]);
<del>
<del>profileValidation.directive('uniqueEmail', ['$http', function($http) {
<del> return {
<del> restrict: 'A',
<del> require: 'ngModel',
<del> link: function getUnique (scope, element, attrs, ngModel) {
<del> element.bind("keyup", function (event) {
<del> ngModel.$setValidity('unique', true);
<del> var email = element.val();
<del> if (email) {
<del> var config = { params: { email: email } };
<del> $http
<del> .get('/api/users/exists', config)
<del> .success(function(result) {
<del> if (email === scope.storedEmail) {
<del> ngModel.$setValidity('unique', true);
<del> } else if (result.exists) {
<del> ngModel.$setValidity('unique', false);
<del> }
<del> });
<del> };
<del> });
<del> }
<del> }
<del>}]);
| 1
|
Javascript
|
Javascript
|
log abnormal closes to metro websocket
|
3982a2c6bd116a6dcc6ee6889e4a246b710b70a7
|
<ide><path>Libraries/Utilities/HMRClient.js
<ide> Error: ${e.message}`;
<ide> }
<ide> });
<ide>
<del> client.on('close', data => {
<add> client.on('close', closeEvent => {
<ide> LoadingView.hide();
<del> setHMRUnavailableReason('Disconnected from Metro.');
<add>
<add> // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.4.1
<add> // https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5
<add> const isNormalOrUnsetCloseReason =
<add> closeEvent.code === 1000 ||
<add> closeEvent.code === 1005 ||
<add> closeEvent.code == null;
<add>
<add> if (isNormalOrUnsetCloseReason) {
<add> setHMRUnavailableReason('Disconnected from Metro.');
<add> } else {
<add> setHMRUnavailableReason(
<add> `Disconnected from Metro (${closeEvent.code}: "${closeEvent.reason}").`,
<add> );
<add> }
<ide> });
<ide>
<ide> if (isEnabled) {
<ide><path>Libraries/WebSocket/WebSocket.js
<ide> const CLOSED = 3;
<ide>
<ide> const CLOSE_NORMAL = 1000;
<ide>
<add>// Abnormal closure where no code is provided in a control frame
<add>// https://www.rfc-editor.org/rfc/rfc6455.html#section-7.1.5
<add>const CLOSE_ABNORMAL = 1006;
<add>
<ide> const WEBSOCKET_EVENTS = ['close', 'error', 'message', 'open'];
<ide>
<ide> let nextWebSocketId = 0;
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> new WebSocketEvent('close', {
<ide> code: ev.code,
<ide> reason: ev.reason,
<add> // TODO: missing `wasClean` (exposed on iOS as `clean` but missing on Android)
<ide> }),
<ide> );
<ide> this._unregisterEvents();
<ide> class WebSocket extends (EventTarget(...WEBSOCKET_EVENTS): any) {
<ide> );
<ide> this.dispatchEvent(
<ide> new WebSocketEvent('close', {
<del> message: ev.message,
<add> code: CLOSE_ABNORMAL,
<add> reason: ev.message,
<add> // TODO: Expose `wasClean`
<ide> }),
<ide> );
<ide> this._unregisterEvents();
| 2
|
Python
|
Python
|
use reverse() in auth views. patch from davenaff
|
bb308054529ad01c079bdaedfb41a85eb5ae97a9
|
<ide><path>django/contrib/auth/views.py
<ide> from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm, PasswordChangeForm, AdminPasswordChangeForm
<ide> from django.contrib.auth.tokens import default_token_generator
<ide> from django.core.exceptions import PermissionDenied
<add>from django.core.urlresolvers import reverse
<ide> from django.shortcuts import render_to_response, get_object_or_404
<ide> from django.contrib.sites.models import Site, RequestSite
<ide> from django.http import HttpResponseRedirect, Http404
<ide> def password_reset(request, is_admin_site=False, template_name='registration/pas
<ide> if not Site._meta.installed:
<ide> opts['domain_override'] = RequestSite(request).domain
<ide> form.save(**opts)
<del> return HttpResponseRedirect('%sdone/' % request.path)
<add> return HttpResponseRedirect(reverse('django.contrib.auth.views.password_reset_done'))
<ide> else:
<ide> form = password_reset_form()
<ide> return render_to_response(template_name, {
<ide> def password_reset_confirm(request, uidb36=None, token=None, template_name='regi
<ide> form = set_password_form(user, request.POST)
<ide> if form.is_valid():
<ide> form.save()
<del> return HttpResponseRedirect("../done/")
<add> return HttpResponseRedirect(reverse('django.contrib.auth.views.password_reset_complete'))
<ide> else:
<ide> form = set_password_form(None)
<ide> else:
<ide> def password_change(request, template_name='registration/password_change_form.ht
<ide> form = PasswordChangeForm(request.user, request.POST)
<ide> if form.is_valid():
<ide> form.save()
<del> return HttpResponseRedirect('%sdone/' % request.path)
<add> return HttpResponseRedirect(reverse('django.contrib.auth.views.password_change_done'))
<ide> else:
<ide> form = PasswordChangeForm(request.user)
<ide> return render_to_response(template_name, {
| 1
|
Mixed
|
Javascript
|
fix key object wrapping in sync keygen
|
7afdfaec083310baa66c05daf33409a7b55528dd
|
<ide><path>doc/api/crypto.md
<ide> changes:
<ide> - `publicExponent`: {number} Public exponent (RSA). **Default:** `0x10001`.
<ide> - `divisorLength`: {number} Size of `q` in bits (DSA).
<ide> - `namedCurve`: {string} Name of the curve to use (EC).
<del> - `publicKeyEncoding`: {Object}
<del> - `type`: {string} Must be one of `'pkcs1'` (RSA only) or `'spki'`.
<del> - `format`: {string} Must be `'pem'` or `'der'`.
<del> - `privateKeyEncoding`: {Object}
<del> - `type`: {string} Must be one of `'pkcs1'` (RSA only), `'pkcs8'` or
<del> `'sec1'` (EC only).
<del> - `format`: {string} Must be `'pem'` or `'der'`.
<del> - `cipher`: {string} If specified, the private key will be encrypted with
<del> the given `cipher` and `passphrase` using PKCS#5 v2.0 password based
<del> encryption.
<del> - `passphrase`: {string | Buffer} The passphrase to use for encryption, see
<del> `cipher`.
<add> - `publicKeyEncoding`: {Object} See [`keyObject.export()`][].
<add> - `privateKeyEncoding`: {Object} See [`keyObject.export()`][].
<ide> * Returns: {Object}
<ide> - `publicKey`: {string | Buffer | KeyObject}
<ide> - `privateKey`: {string | Buffer | KeyObject}
<ide>
<ide> Generates a new asymmetric key pair of the given `type`. Only RSA, DSA and EC
<ide> are currently supported.
<ide>
<del>It is recommended to encode public keys as `'spki'` and private keys as
<del>`'pkcs8'` with encryption:
<add>If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function
<add>behaves as if [`keyObject.export()`][] had been called on its result. Otherwise,
<add>the respective part of the key is returned as a [`KeyObject`].
<add>
<add>When encoding public keys, it is recommended to use `'spki'`. When encoding
<add>private keys, it is recommended to use `'pks8'` with a strong passphrase, and to
<add>keep the passphrase confidential.
<ide>
<ide> ```js
<ide> const { generateKeyPairSync } = require('crypto');
<ide><path>lib/internal/crypto/keygen.js
<ide> function handleError(impl, wrap) {
<ide> if (err !== undefined)
<ide> throw err;
<ide>
<del> return { publicKey, privateKey };
<add> // If no encoding was chosen, return key objects instead.
<add> return {
<add> publicKey: wrapKey(publicKey, PublicKeyObject),
<add> privateKey: wrapKey(privateKey, PrivateKeyObject)
<add> };
<ide> }
<ide>
<ide> function parseKeyEncoding(keyType, options) {
<ide><path>test/parallel/test-crypto-keygen.js
<ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
<ide> testSignVerify(publicKey, privateKey);
<ide> }
<ide>
<add>{
<add> // Test sync key generation with key objects.
<add> const { publicKey, privateKey } = generateKeyPairSync('rsa', {
<add> modulusLength: 512
<add> });
<add>
<add> assert.strictEqual(typeof publicKey, 'object');
<add> assert.strictEqual(publicKey.type, 'public');
<add> assert.strictEqual(publicKey.asymmetricKeyType, 'rsa');
<add>
<add> assert.strictEqual(typeof privateKey, 'object');
<add> assert.strictEqual(privateKey.type, 'private');
<add> assert.strictEqual(privateKey.asymmetricKeyType, 'rsa');
<add>}
<add>
<ide> {
<ide> const publicKeyEncoding = {
<ide> type: 'pkcs1',
| 3
|
Javascript
|
Javascript
|
fix param type to domelement
|
074648ef579582198cb8b48732c6b43c1bbfe064
|
<ide><path>src/Angular.js
<ide> function angularInit(element, bootstrap) {
<ide> * </file>
<ide> * </example>
<ide> *
<del> * @param {Element} element DOM element which is the root of angular application.
<add> * @param {DOMElement} element DOM element which is the root of angular application.
<ide> * @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
<ide> * Each item in the array should be the name of a predefined module or a (DI annotated)
<ide> * function that will be invoked by the injector as a run block.
| 1
|
Ruby
|
Ruby
|
remove outdated comment
|
7f43485508a277c43c046c5a701f6bdb6aed1ede
|
<ide><path>activerecord/lib/active_record/connection_adapters/mysql2_adapter.rb
<ide> def disconnect!
<ide> # DATABASE STATEMENTS ======================================
<ide> #++
<ide>
<del> # FIXME: re-enable the following once a "better" query_cache solution is in core
<del> #
<del> # The overrides below perform much better than the originals in AbstractAdapter
<del> # because we're able to take advantage of mysql2's lazy-loading capabilities
<del> #
<del> # # Returns a record hash with the column names as keys and column values
<del> # # as values.
<del> # def select_one(sql, name = nil)
<del> # result = execute(sql, name)
<del> # result.each(as: :hash) do |r|
<del> # return r
<del> # end
<del> # end
<del> #
<del> # # Returns a single value from a record
<del> # def select_value(sql, name = nil)
<del> # result = execute(sql, name)
<del> # if first = result.first
<del> # first.first
<del> # end
<del> # end
<del> #
<del> # # Returns an array of the values of the first column in a select:
<del> # # select_values("SELECT id FROM companies LIMIT 3") => [1,2,3]
<del> # def select_values(sql, name = nil)
<del> # execute(sql, name).map { |row| row.first }
<del> # end
<del>
<ide> # Returns a record hash with the column names as keys and column values
<ide> # as values.
<ide> def select_one(arel, name = nil, binds = [])
| 1
|
Javascript
|
Javascript
|
add accessibilityvalue prop on touchables
|
3042407f43b69994abc00350681f1f0a79683bfd
|
<ide><path>Libraries/Components/Touchable/TouchableBounce.js
<ide> const TouchableBounce = ((createReactClass({
<ide> accessibilityState={this.props.accessibilityState}
<ide> accessibilityActions={this.props.accessibilityActions}
<ide> onAccessibilityAction={this.props.onAccessibilityAction}
<add> accessibilityValue={this.props.accessibilityValue}
<ide> nativeID={this.props.nativeID}
<ide> testID={this.props.testID}
<ide> hitSlop={this.props.hitSlop}
<ide><path>Libraries/Components/Touchable/TouchableHighlight.js
<ide> const TouchableHighlight = ((createReactClass({
<ide> accessibilityHint={this.props.accessibilityHint}
<ide> accessibilityRole={this.props.accessibilityRole}
<ide> accessibilityState={this.props.accessibilityState}
<add> accessibilityValue={this.props.accessibilityValue}
<ide> accessibilityActions={this.props.accessibilityActions}
<ide> onAccessibilityAction={this.props.onAccessibilityAction}
<ide> style={StyleSheet.compose(
<ide><path>Libraries/Components/Touchable/TouchableNativeFeedback.android.js
<ide> const TouchableNativeFeedback = createReactClass({
<ide> accessibilityState: this.props.accessibilityState,
<ide> accessibilityActions: this.props.accessibilityActions,
<ide> onAccessibilityAction: this.props.onAccessibilityAction,
<add> accessibilityValue: this.props.accessibilityValue,
<ide> children,
<ide> testID: this.props.testID,
<ide> onLayout: this.props.onLayout,
<ide><path>Libraries/Components/Touchable/TouchableOpacity.js
<ide> const TouchableOpacity = ((createReactClass({
<ide> accessibilityState={this.props.accessibilityState}
<ide> accessibilityActions={this.props.accessibilityActions}
<ide> onAccessibilityAction={this.props.onAccessibilityAction}
<add> accessibilityValue={this.props.accessibilityValue}
<ide> style={[this.props.style, {opacity: this.state.anim}]}
<ide> nativeID={this.props.nativeID}
<ide> testID={this.props.testID}
<ide><path>Libraries/Components/Touchable/TouchableWithoutFeedback.js
<ide> import type {
<ide> AccessibilityState,
<ide> AccessibilityActionInfo,
<ide> AccessibilityActionEvent,
<add> AccessibilityValue,
<ide> } from '../View/ViewAccessibility';
<ide>
<ide> type TargetEvent = SyntheticEvent<
<ide> const OVERRIDE_PROPS = [
<ide> 'accessibilityState',
<ide> 'accessibilityActions',
<ide> 'onAccessibilityAction',
<add> 'accessibilityValue',
<ide> 'hitSlop',
<ide> 'nativeID',
<ide> 'onBlur',
<ide> export type Props = $ReadOnly<{|
<ide> accessibilityRole?: ?AccessibilityRole,
<ide> accessibilityState?: ?AccessibilityState,
<ide> accessibilityActions?: ?$ReadOnlyArray<AccessibilityActionInfo>,
<add> accessibilityValue?: ?AccessibilityValue,
<ide> children?: ?React.Node,
<ide> delayLongPress?: ?number,
<ide> delayPressIn?: ?number,
<ide> const TouchableWithoutFeedback = ((createReactClass({
<ide> accessibilityState: PropTypes.object,
<ide> accessibilityActions: PropTypes.array,
<ide> onAccessibilityAction: PropTypes.func,
<add> accessibilityValue: PropTypes.object,
<ide> /**
<ide> * When `accessible` is true (which is the default) this may be called when
<ide> * the OS-specific concept of "focus" occurs. Some platforms may not have
<ide><path>RNTester/js/examples/Accessibility/AccessibilityExample.js
<ide> class FakeSliderExample extends React.Component {
<ide> }}>
<ide> <Text>Fake Slider</Text>
<ide> </View>
<del> <View
<add> <TouchableWithoutFeedback
<ide> accessible={true}
<ide> accessibilityLabel="Equalizer"
<ide> accessibilityRole="adjustable"
<ide> class FakeSliderExample extends React.Component {
<ide> }
<ide> }}
<ide> accessibilityValue={{text: this.state.textualValue}}>
<del> <Text>Equalizer</Text>
<del> </View>
<add> <View>
<add> <Text>Equalizer</Text>
<add> </View>
<add> </TouchableWithoutFeedback>
<ide> </View>
<ide> );
<ide> }
| 6
|
Ruby
|
Ruby
|
fix typo in test name
|
683e1c7d18168912c691a65164fae578fc4b4183
|
<ide><path>activerecord/test/cases/calculations_test.rb
<ide> def test_group_by_with_limit_and_offset
<ide> assert_equal expected, actual
<ide> end
<ide>
<del> def test_group_by_with_qouted_count_and_order_by_alias
<add> def test_group_by_with_quoted_count_and_order_by_alias
<ide> quoted_posts_id = Post.connection.quote_table_name("posts.id")
<ide> expected = { "SpecialPost" => 1, "StiPost" => 1, "Post" => 9 }
<ide> actual = Post.group(:type).order("count_posts_id").count(quoted_posts_id)
| 1
|
Python
|
Python
|
remove obsolete test
|
c76293a5bd59f979e477951ad5acc1037cb7753d
|
<ide><path>t/unit/app/test_defaults.py
<ide> def test_any(self):
<ide> val = object()
<ide> assert self.defaults.Option.typemap['any'](val) is val
<ide>
<del> @mock.sys_platform('darwin')
<del> @mock.pypy_version((1, 4, 0))
<del> def test_default_pool_pypy_14(self):
<del> assert self.defaults.DEFAULT_POOL == 'solo'
<del>
<del> @mock.sys_platform('darwin')
<del> @mock.pypy_version((1, 5, 0))
<del> def test_default_pool_pypy_15(self):
<del> assert self.defaults.DEFAULT_POOL == 'prefork'
<del>
<ide> def test_compat_indices(self):
<ide> assert not any(key.isupper() for key in DEFAULTS)
<ide> assert not any(key.islower() for key in _OLD_DEFAULTS)
| 1
|
Javascript
|
Javascript
|
fix incorrect message in equals test
|
dff8edefdf0c25aa206719cbca85934596936432
|
<ide><path>packages/ember-runtime/tests/suites/enumerable/contains.js
<ide> suite.test('contains returns true if items is in enumerable', function() {
<ide> suite.test('contains returns false if item is not in enumerable', function() {
<ide> var data = this.newFixture(1);
<ide> var obj = this.newObject(this.newFixture(3));
<del> equals(obj.contains(data[0]), false, 'should return true if not contained');
<add> equals(obj.contains(data[0]), false, 'should return false if not contained');
<ide> });
<ide>
| 1
|
Text
|
Text
|
update broken jsfiddle in why react blog post
|
13692d59add7cfffe06e69f8d4fe2488d0a55514
|
<ide><path>docs/_posts/2013-06-05-why-react.md
<ide> to the DOM.
<ide> > lightweight description of what the DOM should look like.
<ide>
<ide> We call this process **reconciliation**. Check out
<del>[this jsFiddle](http://jsfiddle.net/fv6RD/3/) to see an example of
<add>[this jsFiddle](http://jsfiddle.net/2h6th4ju/) to see an example of
<ide> reconciliation in action.
<ide>
<ide> Because this re-render is so fast (around 1ms for TodoMVC), the developer
| 1
|
Python
|
Python
|
remove unused import
|
4a6b094e094242f1f18542eb8682da3cd9531829
|
<ide><path>spacy/language.py
<ide> from thinc.neural import Model
<ide> from thinc.neural.optimizers import Adam
<ide>
<del>from .strings import StringStore
<ide> from .tokenizer import Tokenizer
<ide> from .vocab import Vocab
<ide> from .lemmatizer import Lemmatizer
| 1
|
Javascript
|
Javascript
|
add tests for relativedates
|
76bcfa865937aa94c6818964c1fdbde112bb0e52
|
<ide><path>lang/test/en.js
<ide> test("fromNow", 2, function() {
<ide> equal(moment().add({d:5}).fromNow(), "in 5 days", "in 5 days");
<ide> });
<ide>
<add>test("xxx", 14, function() {
<add> var getTodayAtTwo, prefixDay;
<add>
<add> getTodayAtTwo = function () {
<add> return moment().hours(2).minutes(0).seconds(0);
<add> };
<add>
<add> prefixDay = function (moment, string, nextOrLast) {
<add> if(typeof nextOrLast == "undefined") {
<add> nextOrLast = '';
<add> } else {
<add> switch(nextOrLast) {
<add> case 'next':
<add> nextOrLast = "next ";
<add> break;
<add> case 'last':
<add> nextOrLast = "last ";
<add> break;
<add> default:
<add> nextOrLast = '';
<add> }
<add> }
<add>
<add> return nextOrLast + moment.format('ddd') + string;
<add> };
<add>
<add> moment.lang('en');
<add> equal(getTodayAtTwo().xxx(), "Today at 02:00", "today at the same time");
<add> equal(getTodayAtTwo().add({ m: 25 }).xxx(), "Today at 02:25", "Now plus 25 min");
<add> equal(getTodayAtTwo().add({ h: 1 }).xxx(), "Today at 03:00", "Now plus 1 hour");
<add> equal(getTodayAtTwo().add({ d: 1 }).xxx(), "Tomorrow at 02:00", "tomorrow at the same time");
<add> equal(getTodayAtTwo().subtract({ h: 1 }).xxx(), "Today at 01:00", "Now minus 1 hour");
<add> equal(getTodayAtTwo().subtract({ d: 1 }).xxx(), "Yesterday at 02:00", "yesterday at the same time");
<add>
<add> var nextTomorrow = getTodayAtTwo().add({ d: 2 });
<add> equal(nextTomorrow.xxx(), prefixDay(nextTomorrow, " at 02:00"), "now - 2days at the same time");
<add>
<add> var previousYesterday = getTodayAtTwo().subtract({ d: 2 });
<add> equal(previousYesterday.xxx(), prefixDay(previousYesterday, " at 02:00"), "now - 2days yesterday at the same time");
<add>
<add> // Next / Last week
<add> equal(getTodayAtTwo().add({ w: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1 }), "", "next"), "next week at the same time");
<add> equal(getTodayAtTwo().add({ w: 1, d: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1, d: 1 }), "", "next"), "next week at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1 }), "", "last"), "next week at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 1, d: 1 }).xxx(), prefixDay(getTodayAtTwo().add({ w: 1, d: 1 }), "", "last"), "next week at the same time");
<add>
<add>
<add> // More than 2 weeks
<add> equal(getTodayAtTwo().add({ w: 2 }).xxx(), getTodayAtTwo().add({ w: 2 }).format('L'), "in 2 weeks at the same time");
<add> equal(getTodayAtTwo().subtract({ w: 2 }).xxx(), getTodayAtTwo().subtract({ w: 2 }).format('L'), "before 2 weeks at the same time");
<add>
<add>})
| 1
|
Java
|
Java
|
improve documentation of @bean 'lite' mode
|
e8f8559a2e1c5fa5c559f887756cdc085c90f26b
|
<ide><path>spring-context/src/main/java/org/springframework/context/annotation/Bean.java
<ide> * <p>{@code @Bean} methods may also be declared within classes that are <em>not</em>
<ide> * annotated with {@code @Configuration}. For example, bean methods may be declared
<ide> * in a {@code @Component} class or even in a <em>plain old class</em>. In such cases,
<del> * a {@code @Bean} method will get processed in a configuration class <em>'lite'</em>
<del> * mode.
<del> *
<del> * <p>In contrast to bean methods in {@code @Configuration} classes as described
<del> * above, bean methods in <em>lite</em> mode will be called as plain <em>factory
<del> * methods</em> from the container (similar to {@code factory-method} declarations
<del> * in XML) but with <b><em>prototype</em></b> semantics. The containing class remains
<del> * unmodified in this case, and there are no unusual constraints for factory methods;
<del> * however, scoping semantics are <b>not</b> respected as described above for
<del> * 'inter-bean method invocations in this mode. For example:
<add> * a {@code @Bean} method will get processed in a so-called <em>'lite'</em> mode.
<add> *
<add> * <p>In contrast to the semantics for bean methods in {@code @Configuration} classes
<add> * as described above, bean methods in <em>lite</em> mode will be called as plain
<add> * <em>factory methods</em> from the container (similar to {@code factory-method}
<add> * declarations in XML) but with <b><em>prototype</em></b> semantics. The containing
<add> * class remains unmodified in this case, and there are no unusual constraints for
<add> * factory methods; however, scoping semantics are <b>not</b> respected as described
<add> * above for 'inter-bean method' invocations in this mode. For example:
<ide> *
<ide> * <pre class="code">
<ide> * @Component
| 1
|
Javascript
|
Javascript
|
add regex to assert.throws
|
22819446123efb68313f2ae385e57d1e780f6b50
|
<ide><path>test/parallel/test-vm-run-in-new-context.js
<ide> assert.strictEqual('passed', result);
<ide> console.error('thrown error');
<ide> assert.throws(function() {
<ide> vm.runInNewContext('throw new Error(\'test\');');
<del>});
<add>}, /^Error: test$/);
<ide>
<ide> global.hello = 5;
<ide> vm.runInNewContext('hello = 2');
| 1
|
Javascript
|
Javascript
|
add glsl comment tag
|
99a213e2b6ec8f997f634a5e6454a4c7d74ccd66
|
<ide><path>src/materials/ShaderMaterial.js
<ide> function ShaderMaterial( parameters ) {
<ide> this.defines = {};
<ide> this.uniforms = {};
<ide>
<del> this.vertexShader = 'void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}';
<del> this.fragmentShader = 'void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}';
<add> this.vertexShader = /* glsl */ `
<add> void main() {
<add> gl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );
<add> }
<add> `;
<add>
<add> this.fragmentShader = /* glsl */ `
<add> void main() {
<add> gl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );
<add> }
<add> `;
<ide>
<ide> this.linewidth = 1;
<ide>
| 1
|
Java
|
Java
|
fix timezone offset in cronexpressiontests
|
f982fd99d7d3bed6e879b00f7599cb8c587228cc
|
<ide><path>spring-context/src/test/java/org/springframework/scheduling/support/CronExpressionTests.java
<ide> public void daylightSaving() {
<ide> CronExpression cronExpression = CronExpression.parse("0 0 9 * * *");
<ide>
<ide> ZonedDateTime last = ZonedDateTime.parse("2021-03-27T09:00:00+01:00[Europe/Amsterdam]");
<del> ZonedDateTime expected = ZonedDateTime.parse("2021-03-28T09:00:00+01:00[Europe/Amsterdam]");
<add> ZonedDateTime expected = ZonedDateTime.parse("2021-03-28T09:00:00+02:00[Europe/Amsterdam]");
<ide> ZonedDateTime actual = cronExpression.next(last);
<ide> assertThat(actual).isNotNull();
<ide> assertThat(actual).isEqualTo(expected);
<ide>
<del> last = ZonedDateTime.parse("2021-10-30T09:00:00+01:00[Europe/Amsterdam]");
<del> expected = ZonedDateTime.parse("2021-10-31T09:00:00+02:00[Europe/Amsterdam]");
<add> last = ZonedDateTime.parse("2021-10-30T09:00:00+02:00[Europe/Amsterdam]");
<add> expected = ZonedDateTime.parse("2021-10-31T09:00:00+01:00[Europe/Amsterdam]");
<ide> actual = cronExpression.next(last);
<ide> assertThat(actual).isNotNull();
<ide> assertThat(actual).isEqualTo(expected);
| 1
|
PHP
|
PHP
|
add default value to order_by direction
|
904588a51a97e679d8b6e135937248b0d513f87c
|
<ide><path>system/db/query.php
<ide> private function dynamic_where($method, $parameters)
<ide> * @param string $direction
<ide> * @return Query
<ide> */
<del> public function order_by($column, $direction)
<add> public function order_by($column, $direction = 'asc')
<ide> {
<ide> $this->orderings[] = $this->wrap($column).' '.strtoupper($direction);
<ide> return $this;
| 1
|
Text
|
Text
|
add changelog entry for [ci-skip]
|
09152576d61e741b769e47bc09b46c71340064c7
|
<ide><path>actioncable/CHANGELOG.md
<add>* The `connected()` callback can now take a `{reconnected}` parameter to differentiate
<add> connections from reconnections.
<add>
<add> ```js
<add> import consumer from "./consumer"
<add>
<add> consumer.subscriptions.create("ExampleChannel", {
<add> connected({reconnected}) {
<add> if (reconnected) {
<add> ...
<add> } else {
<add> ...
<add> }
<add> }
<add> })
<add> ```
<add>
<add> *Mansa Keïta*
<add>
<ide> * The Redis adapter is now compatible with redis-rb 5.0
<ide>
<ide> Compatibility with redis-rb 3.x was dropped.
| 1
|
Ruby
|
Ruby
|
use cgi.escapehtml for html escape
|
51152fc0f8517b24af4a619faa9df9879920f5d1
|
<ide><path>activesupport/lib/active_support/core_ext/string/output_safety.rb
<ide> class ERB
<ide> module Util
<ide> HTML_ESCAPE = { '&' => '&', '>' => '>', '<' => '<', '"' => '"', "'" => ''' }
<ide> JSON_ESCAPE = { '&' => '\u0026', '>' => '\u003e', '<' => '\u003c', "\u2028" => '\u2028', "\u2029" => '\u2029' }
<del> HTML_ESCAPE_REGEXP = /[&"'><]/
<ide> HTML_ESCAPE_ONCE_REGEXP = /["><']|&(?!([a-zA-Z]+|(#\d+)|(#[xX][\dA-Fa-f]+));)/
<ide> JSON_ESCAPE_REGEXP = /[\u2028\u2029&><]/u
<ide>
<ide> def unwrapped_html_escape(s) # :nodoc:
<ide> if s.html_safe?
<ide> s
<ide> else
<del> ActiveSupport::Multibyte::Unicode.tidy_bytes(s).gsub(HTML_ESCAPE_REGEXP, HTML_ESCAPE)
<add> CGI.escapeHTML(ActiveSupport::Multibyte::Unicode.tidy_bytes(s))
<ide> end
<ide> end
<ide> module_function :unwrapped_html_escape
<ide> def #{unsafe_method}!(*args) # def capitalize!(*args)
<ide> private
<ide>
<ide> def html_escape_interpolated_argument(arg)
<del> (!html_safe? || arg.html_safe?) ? arg :
<del> arg.to_s.gsub(ERB::Util::HTML_ESCAPE_REGEXP, ERB::Util::HTML_ESCAPE)
<add> (!html_safe? || arg.html_safe?) ? arg : CGI.escapeHTML(arg.to_s)
<ide> end
<ide> end
<ide> end
| 1
|
Python
|
Python
|
fix polygon division. closes ticket #553
|
eb12ad4a3656aafe1260e0a981bd5c0dc136de0c
|
<ide><path>numpy/core/tests/test_regression.py
<ide> def check_numeric_random(self, level=rlevel):
<ide> from numpy.oldnumeric.random_array import randint
<ide> randint(0,50,[2,3])
<ide>
<add> def check_poly_div(self, level=rlevel):
<add> """Ticket #553"""
<add> u = N.poly1d([1,2,3])
<add> v = N.poly1d([1,2,3,4,5])
<add> q,r = N.polydiv(u,v)
<add> assert_equal(q*v + r, u)
<add>
<ide> def check_poly_eq(self, level=rlevel):
<ide> """Ticket #554"""
<ide> x = N.poly1d([1,2,3])
<ide><path>numpy/lib/polynomial.py
<ide> def polydiv(u, v):
<ide> m = len(u) - 1
<ide> n = len(v) - 1
<ide> scale = 1. / v[0]
<del> q = NX.zeros((m-n+1,), float)
<add> q = NX.zeros((max(m-n+1,1),), float)
<ide> r = u.copy()
<ide> for k in range(0, m-n+1):
<ide> d = scale * r[k]
| 2
|
Javascript
|
Javascript
|
improve error boundaries tests
|
0c031c55b897307ded97c2a681bee3c19e902ec6
|
<ide><path>src/renderers/shared/stack/reconciler/__tests__/ReactErrorBoundaries-test.js
<ide>
<ide> var React;
<ide> var ReactDOM;
<del>var ReactDOMServer;
<ide>
<ide> describe('ReactErrorBoundaries', function() {
<ide>
<ide> beforeEach(function() {
<ide> ReactDOM = require('ReactDOM');
<del> ReactDOMServer = require('ReactDOMServer');
<ide> React = require('React');
<ide> });
<ide>
<ide> describe('ReactErrorBoundaries', function() {
<ide> }
<ide> render() {
<ide> if (!this.state.error) {
<del> return (<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>);
<add> return (
<add> <div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
<add> );
<ide> } else {
<del> return (<div>Happy Birthday!</div>);
<add> return <div>Happy Birthday!</div>;
<ide> }
<ide> }
<ide> onClick() {
<ide> describe('ReactErrorBoundaries', function() {
<ide> expect(EventPluginHub.putListener).not.toBeCalled();
<ide> });
<ide>
<del> it('renders an error state (ssr)', function() {
<add> it('renders an error state', function() {
<add> var log = [];
<ide> class Angry extends React.Component {
<ide> render() {
<add> log.push('Angry render');
<ide> throw new Error('Please, do not render me.');
<ide> }
<add> componentDidMount() {
<add> log.push('Angry componentDidMount');
<add> }
<add> componentWillUnmount() {
<add> log.push('Angry componentWillUnmount');
<add> }
<ide> }
<ide>
<ide> class Boundary extends React.Component {
<ide> describe('ReactErrorBoundaries', function() {
<ide> this.state = {error: false};
<ide> }
<ide> render() {
<add> log.push('Boundary render');
<ide> if (!this.state.error) {
<del> return (<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>);
<add> return (
<add> <div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
<add> );
<ide> } else {
<del> return (<div>Happy Birthday!</div>);
<add> return <div>Happy Birthday!</div>;
<ide> }
<ide> }
<add> componentDidMount() {
<add> log.push('Boundary componentDidMount');
<add> }
<add> componentWillUnmount() {
<add> log.push('Boundary componentWillUnmount');
<add> }
<ide> onClick() {
<ide> /* do nothing */
<ide> }
<ide> describe('ReactErrorBoundaries', function() {
<ide> }
<ide> }
<ide>
<del> var EventPluginHub = require('EventPluginHub');
<ide> var container = document.createElement('div');
<del> EventPluginHub.putListener = jest.fn();
<del> container.innerHTML = ReactDOMServer.renderToString(<Boundary />);
<add> ReactDOM.render(<Boundary />, container);
<ide> expect(container.firstChild.innerHTML).toBe('Happy Birthday!');
<del> expect(EventPluginHub.putListener).not.toBeCalled();
<add> expect(log).toEqual([
<add> 'Boundary render',
<add> 'Angry render',
<add> 'Boundary render',
<add> 'Boundary componentDidMount',
<add> ]);
<ide> });
<ide>
<ide> it('will catch exceptions in componentWillUnmount', function() {
<ide> describe('ReactErrorBoundaries', function() {
<ide> super();
<ide> this.state = {error: false};
<ide> }
<del>
<add>
<ide> render() {
<ide> if (!this.state.error) {
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> return <div>Error has been caught</div>;
<ide> }
<del>
<add>
<ide> unstable_handleError() {
<ide> this.setState({error: true});
<ide> }
<ide> describe('ReactErrorBoundaries', function() {
<ide> });
<ide>
<ide> it('expect uneventful render to succeed', function() {
<add> var log = [];
<ide> class Boundary extends React.Component {
<ide> constructor(props) {
<ide> super(props);
<ide> this.state = {error: false};
<ide> }
<ide> render() {
<del> return (<div><button onClick={this.onClick}>ClickMe</button></div>);
<add> log.push('Boundary render');
<add> return <div><button onClick={this.onClick}>ClickMe</button></div>;
<ide> }
<ide> onClick() {
<ide> /* do nothing */
<ide> }
<add> componentDidMount() {
<add> log.push('Boundary componentDidMount');
<add> }
<add> componentWillUnmount() {
<add> log.push('Boundary componentWillUnmount');
<add> }
<ide> unstable_handleError() {
<ide> this.setState({error: true});
<ide> }
<ide> }
<ide>
<del> var EventPluginHub = require('EventPluginHub');
<ide> var container = document.createElement('div');
<del> EventPluginHub.putListener = jest.fn();
<ide> ReactDOM.render(<Boundary />, container);
<del> expect(EventPluginHub.putListener).toBeCalled();
<add> expect(log).toEqual([
<add> 'Boundary render',
<add> 'Boundary componentDidMount',
<add> ]);
<ide> });
<ide>
<ide> it('correctly handles composite siblings', function() {
<ide> describe('ReactErrorBoundaries', function() {
<ide> super();
<ide> this.state = {error: false};
<ide> }
<del>
<add>
<ide> render() {
<ide> if (!this.state.error) {
<ide> return <div>{this.props.children}</div>;
<ide> }
<ide> return <div>Error has been caught</div>;
<ide> }
<del>
<add>
<ide> unstable_handleError() {
<ide> this.setState({error: true});
<ide> }
<ide><path>src/renderers/testing/__tests__/ReactTestRenderer-test.js
<ide> describe('ReactTestRenderer', function() {
<ide> });
<ide>
<ide> it('supports error boundaries', function() {
<add> var log = [];
<ide> class Angry extends React.Component {
<ide> render() {
<add> log.push('Angry render');
<ide> throw new Error('Please, do not render me.');
<ide> }
<add> componentDidMount() {
<add> log.push('Angry componentDidMount');
<add> }
<add> componentWillUnmount() {
<add> log.push('Angry componentWillUnmount');
<add> }
<ide> }
<ide>
<ide> class Boundary extends React.Component {
<ide> describe('ReactTestRenderer', function() {
<ide> this.state = {error: false};
<ide> }
<ide> render() {
<add> log.push('Boundary render');
<ide> if (!this.state.error) {
<del> return (<div><button onClick={this.onClick}>ClickMe</button><Angry /></div>);
<add> return (
<add> <div><button onClick={this.onClick}>ClickMe</button><Angry /></div>
<add> );
<ide> } else {
<del> return (<div>Happy Birthday!</div>);
<add> return <div>Happy Birthday!</div>;
<ide> }
<ide> }
<add> componentDidMount() {
<add> log.push('Boundary componentDidMount');
<add> }
<add> componentWillUnmount() {
<add> log.push('Boundary componentWillUnmount');
<add> }
<ide> onClick() {
<ide> /* do nothing */
<ide> }
<ide> describe('ReactTestRenderer', function() {
<ide> }
<ide> }
<ide>
<del> var EventPluginHub = require('EventPluginHub');
<del> EventPluginHub.putListener = jest.fn();
<ide> var renderer = ReactTestRenderer.create(<Boundary />);
<ide> expect(renderer.toJSON()).toEqual({
<ide> type: 'div',
<ide> props: {},
<ide> children: ['Happy Birthday!'],
<ide> });
<del> expect(EventPluginHub.putListener).not.toBeCalled();
<add> expect(log).toEqual([
<add> 'Boundary render',
<add> 'Angry render',
<add> 'Boundary render',
<add> 'Boundary componentDidMount',
<add> ]);
<ide> });
<ide>
<ide> });
| 2
|
Text
|
Text
|
remove extrernal link to github pug
|
05bde54e9febd3293bfa36f6a19f280ac593cdbd
|
<ide><path>curriculum/challenges/english/06-quality-assurance/advanced-node-and-express/use-a-template-engines-powers.md
<ide> One of the greatest features of using a template engine is being able to pass va
<ide>
<ide> In your Pug file, you're able to use a variable by referencing the variable name as `#{variable_name}` inline with other text on an element or by using an equal sign on the element without a space such as `p=variable_name` which assigns the variable's value to the p element's text.
<ide>
<del>We strongly recommend looking at the syntax and structure of Pug [here](https://github.com/pugjs/pug) on GitHub's README. Pug is all about using whitespace and tabs to show nested elements and cutting down on the amount of code needed to make a beautiful site.
<add> Pug is all about using whitespace and tabs to show nested elements and cutting down on the amount of code needed to make a beautiful site. Read the Pug documentation for more information on usage and syntax.
<add>
<add> Here is an example:
<add>
<add> ```html
<add> <!--Typing this using Pug-->
<add> head
<add> script(type='text/javascript').
<add> if (foo) bar(1 + 5);
<add> body
<add> if youAreUsingPug
<add> p You are amazing
<add> else
<add> p Get on it!
<add>
<add><!--will lead to creating this code-->
<add> <head>
<add> <script type="text/javascript">
<add> if (foo) bar(1 + 5);
<add> </script>
<add> </head>
<add> <body>
<add> <p>You are amazing</p>
<add> </body>
<add> ```
<ide>
<del>Looking at our pug file 'index.pug' included in your project, we used the variables *title* and *message*.
<add>Looking at our pug file `index.pug` included in your project, we used the variables `title` and `message`.
<ide>
<del>To pass those along from our server, you will need to add an object as a second argument to your *res.render* with the variables and their values. For example, pass this object along setting the variables for your index view: `{title: 'Hello', message: 'Please login'}`
<add>To pass those along from our server, you will need to add an object as a second argument to your `res.render` with the variables and their values. For example, pass this object along setting the variables for your index view: `{title: 'Hello', message: 'Please login'}`
<ide>
<del>It should look like: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Now refresh your page and you should see those values rendered in your view in the correct spot as laid out in your index.pug file!
<add>It should look like: `res.render(process.cwd() + '/views/pug/index', {title: 'Hello', message: 'Please login'});` Now refresh your page and you should see those values rendered in your view in the correct spot as laid out in your `index.pug` file!
<ide>
<del>Submit your page when you think you've got it right. If you're running into errors, you can check out the project completed up to this point [here](https://gist.github.com/camperbot/4af125119ed36e6e6a8bb920db0c0871).
<add>Submit your page when you think you've got it right. If you're running into errors, you can check out the [project completed up to this point](https://gist.github.com/camperbot/4af125119ed36e6e6a8bb920db0c0871).
<ide>
<ide> # --hints--
<ide>
| 1
|
Python
|
Python
|
evaluate loaded class, to ensure save/load works
|
5e4312feede7c2511b4d61a5723077c1b16c142d
|
<ide><path>spacy/cli/train.py
<ide> def train(_, lang, output_dir, train_data, dev_data, n_iter=20, n_sents=0,
<ide> pbar.update(len(docs))
<ide>
<ide> with nlp.use_params(optimizer.averages):
<del> scorer = nlp.evaluate(corpus.dev_docs(nlp, gold_preproc=False))
<ide> with (output_path / ('model%d.pickle' % i)).open('wb') as file_:
<ide> dill.dump(nlp, file_, -1)
<del>
<del>
<add> with (output_path / ('model%d.pickle' % i)).open('rb') as file_:
<add> nlp_loaded = dill.load(file_)
<add> scorer = nlp_loaded.evaluate(corpus.dev_docs(nlp_loaded, gold_preproc=False))
<ide> print_progress(i, losses, scorer.scores)
<ide> finally:
<ide> print("Saving model...")
| 1
|
PHP
|
PHP
|
move comment to match logout method
|
55d28abb7568f5625ea63063d55847e8b5f95ebe
|
<ide><path>src/Illuminate/Auth/SessionGuard.php
<ide> public function logoutCurrentDevice()
<ide> {
<ide> $user = $this->user();
<ide>
<add> $this->clearUserDataFromStorage();
<add>
<ide> // If we have an event dispatcher instance, we can fire off the logout event
<ide> // so any further processing can be done. This allows the developer to be
<ide> // listening for anytime a user signs out of this application manually.
<del> $this->clearUserDataFromStorage();
<del>
<ide> if (isset($this->events)) {
<ide> $this->events->dispatch(new Events\CurrentDeviceLogout($this->name, $user));
<ide> }
| 1
|
PHP
|
PHP
|
add path option to reminderscontrollercommand
|
cff5fb356458f8ef9fefb1734358cc1c1026acb7
|
<ide><path>src/Illuminate/Auth/Console/RemindersControllerCommand.php
<ide>
<ide> use Illuminate\Console\Command;
<ide> use Illuminate\Filesystem\Filesystem;
<add>use Symfony\Component\Console\Input\InputOption;
<ide>
<ide> class RemindersControllerCommand extends Command {
<ide>
<ide> class RemindersControllerCommand extends Command {
<ide> /**
<ide> * Create a new reminder table command instance.
<ide> *
<del> * @param \Illuminate\Filesystem\Filesystem $files
<del> * @return void
<add> * @param \Illuminate\Filesystem\Filesystem $files
<add> * @return \Illuminate\Auth\Console\RemindersControllerCommand
<ide> */
<ide> public function __construct(Filesystem $files)
<ide> {
<ide> public function __construct(Filesystem $files)
<ide> */
<ide> public function fire()
<ide> {
<del> $destination = $this->laravel['path'].'/controllers/RemindersController.php';
<add> $destination = $this->getPath() . '/RemindersController.php';
<ide>
<ide> if ( ! $this->files->exists($destination))
<ide> {
<ide> public function fire()
<ide> }
<ide> }
<ide>
<add> /**
<add> * Get the path to the migration directory.
<add> *
<add> * @return string
<add> */
<add> private function getPath()
<add> {
<add> if ( ! $path = $this->input->getOption('path'))
<add> {
<add> $path = $this->laravel['path'].'/controllers';
<add> }
<add>
<add> return $path;
<add> }
<add>
<add> /**
<add> * Get the console command options.
<add> *
<add> * @return array
<add> */
<add> protected function getOptions()
<add> {
<add> return array(
<add> array('path', null, InputOption::VALUE_OPTIONAL, 'The path to controllers.', null),
<add> );
<add> }
<add>
<ide> }
| 1
|
Ruby
|
Ruby
|
add progress message when searching git history
|
a8563afc9e60abc749bff43177c768c0af69dab9
|
<ide><path>Library/Homebrew/dev-cmd/extract.rb
<ide> def extract
<ide> file = repo/"Formula/#{name}.rb"
<ide>
<ide> if args.version
<add> ohai "Searching repository history"
<ide> version = args.version
<ide> rev = "HEAD"
<ide> test_formula = nil
<ide> def extract
<ide> version = Formulary.factory(file).version
<ide> result = File.read(file)
<ide> else
<add> ohai "Searching repository history"
<ide> rev = Git.last_revision_commit_of_file(repo, file)
<ide> version = formula_at_revision(repo, name, file, rev).version
<ide> odie "Could not find #{name}! The formula or version may not have existed." if rev.empty?
| 1
|
Python
|
Python
|
add blender logging handlers only once
|
688cde2f6cbed70b2ce0ca74e13d585a22cca15f
|
<ide><path>utils/exporters/blender/addons/io_three/logger.py
<ide> def init(filename, level=constants.DEBUG):
<ide> LOGGER = logging.getLogger('Three.Export')
<ide> LOGGER.setLevel(LEVELS[level])
<ide>
<del> stream = logging.StreamHandler()
<del> stream.setLevel(LEVELS[level])
<add> if not LOGGER.handlers:
<add> stream = logging.StreamHandler()
<add> stream.setLevel(LEVELS[level])
<ide>
<del> format_ = '%(asctime)s - %(name)s - %(levelname)s: %(message)s'
<del> formatter = logging.Formatter(format_)
<add> format_ = '%(asctime)s - %(name)s - %(levelname)s: %(message)s'
<add> formatter = logging.Formatter(format_)
<ide>
<del> stream.setFormatter(formatter)
<add> stream.setFormatter(formatter)
<ide>
<del> file_handler = logging.FileHandler(LOG_FILE)
<del> file_handler.setLevel(LEVELS[level])
<del> file_handler.setFormatter(formatter)
<add> file_handler = logging.FileHandler(LOG_FILE)
<add> file_handler.setLevel(LEVELS[level])
<add> file_handler.setFormatter(formatter)
<ide>
<del> LOGGER.addHandler(stream)
<del> LOGGER.addHandler(file_handler)
<add> LOGGER.addHandler(stream)
<add> LOGGER.addHandler(file_handler)
<ide>
<ide>
<ide> def info(*args):
| 1
|
Go
|
Go
|
change ownership to root for add file/directory
|
026aebdebbaa05eab25134949ed5d5bda655ba67
|
<ide><path>server/buildfile.go
<ide> func (b *buildFile) addContext(container *runtime.Container, orig, dest string,
<ide> return err
<ide> }
<ide>
<add> chownR := func(destPath string, uid, gid int) error {
<add> return filepath.Walk(destPath, func(path string, info os.FileInfo, err error) error {
<add> if err := os.Lchown(path, uid, gid); err != nil {
<add> return err
<add> }
<add> return nil
<add> })
<add> }
<add>
<ide> if fi.IsDir() {
<ide> if err := archive.CopyWithTar(origPath, destPath); err != nil {
<ide> return err
<ide> }
<add> if err := chownR(destPath, 0, 0); err != nil {
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide> func (b *buildFile) addContext(container *runtime.Container, orig, dest string,
<ide> if err := archive.CopyWithTar(origPath, destPath); err != nil {
<ide> return err
<ide> }
<add>
<add> if err := chownR(destPath, 0, 0); err != nil {
<add> return err
<add> }
<ide> return nil
<ide> }
<ide>
<ide> func (b *buildFile) CmdAdd(args string) error {
<ide> )
<ide>
<ide> if utils.IsURL(orig) {
<add> // Initiate the download
<ide> isRemote = true
<ide> resp, err := utils.Download(orig)
<ide> if err != nil {
<ide> return err
<ide> }
<add>
<add> // Create a tmp dir
<ide> tmpDirName, err := ioutil.TempDir(b.contextPath, "docker-remote")
<ide> if err != nil {
<ide> return err
<ide> }
<add>
<add> // Create a tmp file within our tmp dir
<ide> tmpFileName := path.Join(tmpDirName, "tmp")
<ide> tmpFile, err := os.OpenFile(tmpFileName, os.O_RDWR|os.O_CREATE|os.O_EXCL, 0600)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> defer os.RemoveAll(tmpDirName)
<del> if _, err = io.Copy(tmpFile, resp.Body); err != nil {
<add>
<add> // Download and dump result to tmp file
<add> if _, err := io.Copy(tmpFile, resp.Body); err != nil {
<ide> tmpFile.Close()
<ide> return err
<ide> }
<del> origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
<ide> tmpFile.Close()
<ide>
<add> origPath = path.Join(filepath.Base(tmpDirName), filepath.Base(tmpFileName))
<add>
<ide> // Process the checksum
<ide> r, err := archive.Tar(tmpFileName, archive.Uncompressed)
<ide> if err != nil {
| 1
|
Javascript
|
Javascript
|
remove unused variables
|
dec8a0eb72594577b05108bb92cf2e2f34c1ce24
|
<ide><path>src/ng/parse.js
<ide> Parser.prototype = {
<ide> }
<ide> };
<ide>
<del>var getterFnCacheDefault = createMap();
<del>var getterFnCacheExpensive = createMap();
<del>
<ide> function isPossiblyDangerousMemberName(name) {
<ide> return name == 'constructor';
<ide> }
<ide><path>test/ng/parseSpec.js
<ide>
<ide> describe('parser', function() {
<ide>
<del> beforeEach(function() {
<del> /* global getterFnCacheDefault: true */
<del> /* global getterFnCacheExpensive: true */
<del> // clear caches
<del> getterFnCacheDefault = createMap();
<del> getterFnCacheExpensive = createMap();
<del> });
<del>
<del>
<ide> describe('lexer', function() {
<ide> var lex;
<ide>
| 2
|
Text
|
Text
|
react dev tools
|
91900d117283fd29b616fdb3f5ce79b110ba70c4
|
<ide><path>errors/url-deprecated.md
<ide> In versions prior to 6.x the `url` property got magically injected into every `P
<ide>
<ide> The reason this is going away is that we want to make things very predictable and explicit. Having a magical url property coming out of nowhere doesn't aid that goal.
<ide>
<add>*Note:* In some cases using React Dev Tools may trigger this warning even if you do not reference `url` anywhere in your code. Try temporarily disabling the extension and see if the warning persists.
<add>
<ide> #### Possible Ways to Fix It
<ide>
<ide> https://github.com/zeit/next-codemod#url-to-withrouter
| 1
|
PHP
|
PHP
|
add default unauthenticated stub method
|
11b0de0485632d5712f7fb59071a4acbc4af2bdc
|
<ide><path>src/Illuminate/Foundation/Exceptions/Handler.php
<ide> protected function prepareException(Exception $e)
<ide> return $e;
<ide> }
<ide>
<add> /**
<add> * Convert an authentication exception into a response.
<add> *
<add> * @param \Illuminate\Http\Request $request
<add> * @param \Illuminate\Auth\AuthenticationException $exception
<add> * @return \Illuminate\Http\Response
<add> */
<add> protected function unauthenticated($request, AuthenticationException $exception)
<add> {
<add> return $request->expectsJson()
<add> ? response()->json(['message' => 'Unauthenticated.'], 401)
<add> : redirect()->guest(route('login'));
<add> }
<add>
<ide> /**
<ide> * Create a response object from the given validation exception.
<ide> *
| 1
|
Javascript
|
Javascript
|
add multiline repl input regression test
|
92c86fd84d5f9be1a22388dd5ebb91ee8039e839
|
<ide><path>test/parallel/test-repl-multiline.js
<add>'use strict';
<add>const common = require('../common');
<add>const assert = require('assert');
<add>const repl = require('repl');
<add>const inputStream = new common.ArrayStream();
<add>const outputStream = new common.ArrayStream();
<add>const input = ['var foo = {', '};', 'foo;'];
<add>let output = '';
<add>
<add>outputStream.write = (data) => { output += data.replace('\r', ''); };
<add>
<add>const r = repl.start({
<add> prompt: '',
<add> input: inputStream,
<add> output: outputStream,
<add> terminal: true,
<add> useColors: false
<add>});
<add>
<add>r.on('exit', common.mustCall(() => {
<add> const actual = output.split('\n');
<add>
<add> // Validate the output, which contains terminal escape codes.
<add> assert.strictEqual(actual.length, 6);
<add> assert.ok(actual[0].endsWith(input[0]));
<add> assert.ok(actual[1].includes('... '));
<add> assert.ok(actual[1].endsWith(input[1]));
<add> assert.strictEqual(actual[2], 'undefined');
<add> assert.ok(actual[3].endsWith(input[2]));
<add> assert.strictEqual(actual[4], '{}');
<add> // Ignore the last line, which is nothing but escape codes.
<add>}));
<add>
<add>inputStream.run(input);
<add>r.close();
| 1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.