content_type stringclasses 8
values | main_lang stringclasses 7
values | message stringlengths 1 50 | sha stringlengths 40 40 | patch stringlengths 52 962k | file_count int64 1 300 |
|---|---|---|---|---|---|
Go | Go | use index=off if possible | 8422d85087bfa770b62ef4e1daaca95ee6783d86 | <ide><path>daemon/graphdriver/overlay2/overlay.go
<ide> var (
<ide>
<ide> useNaiveDiffLock sync.Once
<ide> useNaiveDiffOnly bool
<add>
<add> indexOff string
<ide> )
<ide>
<ide> func init() {
<ide> func Init(home string, options []string, uidMaps, gidMaps []idtools.IDMap) (grap
<ide> return nil, fmt.Errorf("Storage Option overlay2.size only supported for backingFS XFS. Found %v", backingFs)
<ide> }
<ide>
<del> logger.Debugf("backingFs=%s, projectQuotaSupported=%v", backingFs, projectQuotaSupported)
<add> // figure out whether "index=off" option is recognized by the kernel
<add> _, err = os.Stat("/sys/module/overlay/parameters/index")
<add> switch {
<add> case err == nil:
<add> indexOff = "index=off,"
<add> case os.IsNotExist(err):
<add> // old kernel, no index -- do nothing
<add> default:
<add> logger.Warnf("Unable to detect whether overlay kernel module supports index parameter: %s", err)
<add> }
<add>
<add> logger.Debugf("backingFs=%s, projectQuotaSupported=%v, indexOff=%q", backingFs, projectQuotaSupported, indexOff)
<ide>
<ide> return d, nil
<ide> }
<ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e
<ide> for i, s := range splitLowers {
<ide> absLowers[i] = path.Join(d.home, s)
<ide> }
<del> opts := fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", strings.Join(absLowers, ":"), path.Join(dir, "diff"), path.Join(dir, "work"))
<add> opts := indexOff + "lowerdir=" + strings.Join(absLowers, ":") + ",upperdir=" + path.Join(dir, "diff") + ",workdir=" + path.Join(dir, "work")
<ide> mountData := label.FormatMountLabel(opts, mountLabel)
<ide> mount := unix.Mount
<ide> mountTarget := mergedDir
<ide> func (d *Driver) Get(id, mountLabel string) (_ containerfs.ContainerFS, retErr e
<ide> // fit within a page and relative links make the mount data much
<ide> // smaller at the expense of requiring a fork exec to chroot.
<ide> if len(mountData) > pageSize {
<del> opts = fmt.Sprintf("lowerdir=%s,upperdir=%s,workdir=%s", string(lowers), path.Join(id, "diff"), path.Join(id, "work"))
<add> opts = indexOff + "lowerdir=" + string(lowers) + ",upperdir=" + path.Join(id, "diff") + ",workdir=" + path.Join(id, "work")
<ide> mountData = label.FormatMountLabel(opts, mountLabel)
<ide> if len(mountData) > pageSize {
<ide> return nil, fmt.Errorf("cannot mount layer, mount label too large %d", len(mountData)) | 1 |
Javascript | Javascript | add some todos, add hash type | 96c5dd1cb027234facf3a61eba73a08a1c845294 | <ide><path>lib/Compilation.js
<ide> const ModuleDependency = require("./dependencies/ModuleDependency");
<ide> /** @typedef {import("./DependenciesBlock")} DependenciesBlock */
<ide> /** @typedef {import("./AsyncDependenciesBlock")} AsyncDependenciesBlock */
<ide> /** @typedef {import("./Dependency").DependencyLocation} DependencyLocation */
<add>/** @typedef {import("./util/createHash").Hash} Hash */
<ide>
<ide> // TODO use @callback
<ide> /** @typedef {{[assetName: string]: Source}} CompilationAssets */
<ide> class Compilation extends Tapable {
<ide> /** @type {AsyncSeriesHook} */
<ide> afterSeal: new AsyncSeriesHook([]),
<ide>
<del> /** @type {SyncHook<Chunk, any>} */
<add> /** @type {SyncHook<Chunk, Hash>} */
<ide> chunkHash: new SyncHook(["chunk", "chunkHash"]),
<ide> /** @type {SyncHook<Module, string>} */
<ide> moduleAsset: new SyncHook(["module", "filename"]),
<ide> /** @type {SyncHook<Chunk, string>} */
<ide> chunkAsset: new SyncHook(["chunk", "filename"]),
<ide>
<del> /** @type {SyncWaterfallHook<string, any>} */
<add> /** @type {SyncWaterfallHook<string, TODO>} */
<ide> assetPath: new SyncWaterfallHook(["filename", "data"]), // TODO MainTemplate
<ide>
<ide> /** @type {SyncBailHook} */ | 1 |
Mixed | Go | remove unsued sysinit package | 29af9c14e442f5cf3760f439d8c0fffaf84e2268 | <ide><path>sysinit/README.md
<del>Sys Init code
<del>
<del>This code is run INSIDE the container and is responsible for setting
<del>up the environment before running the actual process
<ide><path>sysinit/sysinit.go
<del>package sysinit
<del>
<del>import (
<del> "fmt"
<del> "os"
<del> "runtime"
<del>)
<del>
<del>// Sys Init code
<del>// This code is run INSIDE the container and is responsible for setting
<del>// up the environment before running the actual process
<del>func SysInit() {
<del> // The very first thing that we should do is lock the thread so that other
<del> // system level options will work and not have issues, i.e. setns
<del> runtime.LockOSThread()
<del>
<del> if len(os.Args) <= 1 {
<del> fmt.Println("You should not invoke dockerinit manually")
<del> os.Exit(1)
<del> }
<del>
<del>} | 2 |
Javascript | Javascript | make regular elements like identity elements | 87e021a83559001dec692e6872a69ce2752f8f59 | <ide><path>packages/ember-htmlbars/lib/hooks/component.js
<ide> import ComponentNodeManager from 'ember-htmlbars/node-managers/component-node-manager';
<del>import buildComponentTemplate from 'ember-views/system/build-component-template';
<add>import buildComponentTemplate, { buildHTMLTemplate } from 'ember-views/system/build-component-template';
<ide>
<ide> export default function componentHook(renderNode, env, scope, _tagName, params, attrs, templates, visitor) {
<ide> var state = renderNode.state;
<ide> export default function componentHook(renderNode, env, scope, _tagName, params,
<ide> isDasherized = true;
<ide> }
<ide>
<del> var parentView = env.view;
<add> let parentView = env.view;
<ide>
<del> if (isTopLevel && tagName === env.view.tagName || !isDasherized) {
<del> let component = env.view;
<add> // | Top-level | Invocation: <foo-bar> | Invocation: {{foo-bar}} |
<add> // ----------------------------------------------------------------------
<add> // | <div> | <div> is component el | no special semantics (a) |
<add> // | <foo-bar> | <foo-bar> is identity el | EWTF |
<add> // | <bar-baz> | recursive invocation | no special semantics |
<add> // | {{anything}} | EWTF | no special semantics |
<add> //
<add> // (a) needs to be implemented specially, because the usual semantics of
<add> // <div> are defined by the compiled template, and we need to emulate
<add> // those semantics.
<add>
<add> let component = env.view;
<add> let isInvokedWithAngles = component && component._isAngleBracket;
<add> let isInvokedWithCurlies = component && !component._isAngleBracket;
<add>
<add> // <div> at the top level of a <foo-bar> invocation
<add> let isComponentHTMLElement = isAngleBracket && !isDasherized && isInvokedWithAngles;
<add>
<add> // <foo-bar> at the top level of a <foo-bar> invocation
<add> let isComponentIdentityElement = isAngleBracket && isTopLevel && tagName === env.view.tagName;
<add>
<add> // <div> at the top level of a {{foo-bar}} invocation
<add> let isNormalHTMLElement = isAngleBracket && !isDasherized && isInvokedWithCurlies;
<add>
<add> if (isComponentIdentityElement || isComponentHTMLElement) {
<ide> let templateOptions = {
<ide> component,
<ide> tagName,
<ide> export default function componentHook(renderNode, env, scope, _tagName, params,
<ide>
<ide> let { block } = buildComponentTemplate(templateOptions, attrs, contentOptions);
<ide> block(env, [], undefined, renderNode, scope, visitor);
<add> } else if (isNormalHTMLElement) {
<add> let block = buildHTMLTemplate(tagName, attrs, { templates, scope });
<add> block(env, [], undefined, renderNode, scope, visitor);
<ide> } else {
<add> // "No special semantics" aka we are invoking a component
<add>
<ide> var manager = ComponentNodeManager.create(renderNode, env, {
<ide> tagName,
<ide> params,
<ide><path>packages/ember-template-compiler/lib/plugins/transform-top-level-components.js
<ide> TransformTopLevelComponents.prototype.transform = function TransformTopLevelComp
<ide> hasSingleComponentNode(ast.body, component => {
<ide> if (component.type === 'ComponentNode') {
<ide> component.tag = `@${component.tag}`;
<add> component.isStatic = true;
<ide> }
<ide> }, element => {
<del> // TODO: Properly copy loc from children
<del> let program = b.program(element.children);
<del> return b.component(`@<${element.tag}>`, element.attributes, program, element.loc);
<add> let hasTripleCurlies = element.attributes.some(attr => attr.value.escaped === false);
<add>
<add> if (element.modifiers.length || hasTripleCurlies) {
<add> return element;
<add> } else {
<add> // TODO: Properly copy loc from children
<add> let program = b.program(element.children);
<add> let component = b.component(`@<${element.tag}>`, element.attributes, program, element.loc);
<add> component.isStatic = true;
<add> return component;
<add> }
<ide> });
<ide>
<ide> return ast;
<ide><path>packages/ember-views/lib/system/build-component-template.js
<ide> export default function buildComponentTemplate({ component, tagName, layout, isA
<ide> return { createdElement: !!tagName, block: blockToRender };
<ide> }
<ide>
<add>export function buildHTMLTemplate(tagName, _attrs, content) {
<add> let attrs = {};
<add>
<add> for (let prop in _attrs) {
<add> let val = _attrs[prop];
<add>
<add> if (typeof val === 'string') {
<add> attrs[prop] = val;
<add> } else {
<add> attrs[prop] = ['value', val];
<add> }
<add> }
<add>
<add> let childTemplate = content.templates.default;
<add> let elementTemplate = internal.manualElement(tagName, attrs, childTemplate.isEmpty);
<add>
<add> if (childTemplate.isEmpty) {
<add> return blockFor(elementTemplate, { scope: content.scope });
<add> } else {
<add> let blockToRender = blockFor(content.templates.default, content);
<add> return blockFor(elementTemplate, { yieldTo: blockToRender, scope: content.scope });
<add> }
<add>}
<add>
<ide> function mergeAttrs(innerAttrs, outerAttrs) {
<ide> let result = assign({}, innerAttrs, outerAttrs);
<ide> | 3 |
Java | Java | support decoding mono in jaxb2xmldecoder | af0cb5374271ddeaab09541eb155cba4a8204d61 | <ide><path>spring-web/src/main/java/org/springframework/http/codec/xml/Jaxb2XmlDecoder.java
<ide> public Flux<Object> decode(Publisher<DataBuffer> inputStream, ResolvableType ele
<ide> return splitEvents.map(events -> unmarshal(events, outputClass));
<ide> }
<ide>
<add> @Override
<add> public Mono<Object> decodeToMono(Publisher<DataBuffer> inputStream, ResolvableType elementType,
<add> @Nullable MimeType mimeType, @Nullable Map<String, Object> hints) {
<add> return decode(inputStream, elementType, mimeType, hints).singleOrEmpty();
<add> }
<add>
<ide> private Object unmarshal(List<XMLEvent> events, Class<?> outputClass) {
<ide> try {
<ide> Unmarshaller unmarshaller = this.jaxbContexts.createUnmarshaller(outputClass);
<ide><path>spring-web/src/test/java/org/springframework/http/codec/xml/Jaxb2XmlDecoderTests.java
<ide>
<ide> import org.junit.Test;
<ide> import reactor.core.publisher.Flux;
<add>import reactor.core.publisher.Mono;
<ide> import reactor.test.StepVerifier;
<ide>
<ide> import org.springframework.core.ResolvableType;
<ide> private static void assertCharacters(XMLEvent event, String expectedData) {
<ide> @Test
<ide> public void decodeSingleXmlRootElement() throws Exception {
<ide> Flux<DataBuffer> source = Flux.just(stringBuffer(POJO_ROOT));
<del> Flux<Object> output = this.decoder.decode(source, ResolvableType.forClass(Pojo.class),
<add> Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(Pojo.class),
<ide> null, Collections.emptyMap());
<ide>
<ide> StepVerifier.create(output)
<ide> public void decodeSingleXmlRootElement() throws Exception {
<ide> @Test
<ide> public void decodeSingleXmlTypeElement() throws Exception {
<ide> Flux<DataBuffer> source = Flux.just(stringBuffer(POJO_ROOT));
<del> Flux<Object> output = this.decoder.decode(source, ResolvableType.forClass(TypePojo.class),
<add> Mono<Object> output = this.decoder.decodeToMono(source, ResolvableType.forClass(TypePojo.class),
<ide> null, Collections.emptyMap());
<ide>
<ide> StepVerifier.create(output)
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/method/annotation/RequestMappingMessageConversionIntegrationTests.java
<ide> public void personTransformWithMono() throws Exception {
<ide> JSON, Person.class).getBody());
<ide> }
<ide>
<add> @Test // SPR-16759
<add> public void personTransformWithMonoAndXml() throws Exception {
<add> assertEquals(new Person("ROBERT"),
<add> performPost("/person-transform/mono", MediaType.APPLICATION_XML, new Person("Robert"),
<add> MediaType.APPLICATION_XML, Person.class).getBody());
<add> }
<add>
<ide> @Test
<ide> public void personTransformWithSingle() throws Exception {
<ide> assertEquals(new Person("ROBERT"), | 3 |
PHP | PHP | update description of filled rule | 90886732cf6df6d8694287c3f9d92496a4f1c61b | <ide><path>resources/lang/en/validation.php
<ide> 'email' => 'The :attribute must be a valid email address.',
<ide> 'exists' => 'The selected :attribute is invalid.',
<ide> 'file' => 'The :attribute must be a file.',
<del> 'filled' => 'The :attribute field is required.',
<add> 'filled' => 'The :attribute field must have a value.',
<ide> 'image' => 'The :attribute must be an image.',
<ide> 'in' => 'The selected :attribute is invalid.',
<ide> 'in_array' => 'The :attribute field does not exist in :other.', | 1 |
PHP | PHP | update default datasource file | baffc963dc7a93f302995fefe344e7648f22cca3 | <ide><path>App/Config/datasources.default.php
<ide> * by all models.
<ide> */
<ide> Configure::write('Datasource.default', [
<del> 'datasource' => 'Database/Mysql',
<add> 'datasource' => 'Cake\Database\Driver\Mysql',
<ide> 'persistent' => false,
<ide> 'host' => 'localhost',
<ide> 'login' => 'user',
<ide> * while running unit and integration tests.
<ide> */
<ide> Configure::write('Datasource.test', [
<del> 'datasource' => 'Database/Mysql',
<add> 'datasource' => 'Cake\Database\Driver\Mysql',
<ide> 'persistent' => false,
<ide> 'host' => 'localhost',
<ide> 'login' => 'user',
<ide><path>lib/Cake/Console/Templates/skel/Config/datasources.default.php
<ide> * by all models.
<ide> */
<ide> Configure::write('Datasource.default', [
<del> 'datasource' => 'Database/Mysql',
<add> 'datasource' => 'Cake\Datasource\Driver\Mysql',
<ide> 'persistent' => false,
<ide> 'host' => 'localhost',
<ide> 'login' => 'user',
<ide> * while running unit and integration tests.
<ide> */
<ide> Configure::write('Datasource.test', [
<del> 'datasource' => 'Database/Mysql',
<add> 'datasource' => 'Cake\Datasource\Driver\Mysql',
<ide> 'persistent' => false,
<ide> 'host' => 'localhost',
<ide> 'login' => 'user', | 2 |
Python | Python | add test for ticket | 78a867887f58e564622ebfb2ef6c753a22f14971 | <ide><path>numpy/core/tests/test_regression.py
<ide> def test_dtype_keyerrors_(self):
<ide> assert_raises(IndexError, dt.__getitem__, 1)
<ide> assert_raises(ValueError, dt.__getitem__, 0.0)
<ide>
<add> def test_lexsort_buffer_length(self):
<add> """Ticket #1217, don't segfault."""
<add> a = np.ones(100, dtype=np.int8)
<add> b = np.ones(100, dtype=np.int32)
<add> i = np.lexsort((a[::-1], b))
<add> assert_equal(i, np.arange(100, dtype=np.int))
<add>
<ide> if __name__ == "__main__":
<ide> run_module_suite() | 1 |
Javascript | Javascript | fix nested yield | 7f2fa488945b3dfb8ebc91560ca6137cee22def0 | <ide><path>packages/ember-handlebars/lib/helpers/yield.js
<ide> var get = Ember.get, set = Ember.set;
<ide> inserting the view's own rendered output at the `{{yield}}` location.
<ide>
<ide> An empty `<body>` and the following application code:
<del>
<add>
<ide> ```javascript
<ide> AView = Ember.View.extend({
<ide> classNames: ['a-view-with-layout'],
<ide> layout: Ember.Handlebars.compile('<div class="wrapper">{{yield}}</div>'),
<ide> template: Ember.Handlebars.compile('<span>I am wrapped</span>')
<ide> });
<del>
<add>
<ide> aView = AView.create();
<ide> aView.appendTo('body');
<ide> ```
<del>
<add>
<ide> Will result in the following HTML output:
<del>
<add>
<ide> ```html
<ide> <body>
<ide> <div class='ember-view a-view-with-layout'>
<ide> var get = Ember.get, set = Ember.set;
<ide> </div>
<ide> </body>
<ide> ```
<del>
<add>
<ide> The `yield` helper cannot be used outside of a template assigned to an
<ide> `Ember.View`'s `layout` property and will throw an error if attempted.
<del>
<add>
<ide> ```javascript
<ide> BView = Ember.View.extend({
<ide> classNames: ['a-view-with-layout'],
<ide> template: Ember.Handlebars.compile('{{yield}}')
<ide> });
<del>
<add>
<ide> bView = BView.create();
<ide> bView.appendTo('body');
<del>
<add>
<ide> // throws
<del> // Uncaught Error: assertion failed:
<add> // Uncaught Error: assertion failed:
<ide> // You called yield in a template that was not a layout
<ide> ```
<ide>
<ide> ### Use with Ember.Component
<ide> When designing components `{{yield}}` is used to denote where, inside the component's
<ide> template, an optional block passed to the component should render:
<del>
<add>
<ide> ```handlebars
<ide> <!-- application.hbs -->
<ide> {{#labeled-textfield value=someProperty}}
<ide> First name:
<ide> {{/my-component}}
<ide> ```
<del>
<add>
<ide> ```handlebars
<ide> <!-- components/my-component.hbs -->
<ide> <label>
<ide> {{yield}} {{input value=value}}
<ide> </label>
<ide> ```
<del>
<add>
<ide> Result:
<del>
<add>
<ide> ```html
<ide> <label>
<ide> First name: <input type="text" />
<ide> <label>
<ide> ```
<del>
<add>
<ide> @method yield
<ide> @for Ember.Handlebars.helpers
<ide> @param {Hash} options
<ide> Ember.Handlebars.registerHelper('yield', function(options) {
<ide> var view = options.data.view;
<ide>
<ide> while (view && !get(view, 'layout')) {
<del> view = get(view, 'parentView');
<add> if (view._contextView) {
<add> view = view._contextView;
<add> } else {
<add> view = get(view, 'parentView');
<add> }
<ide> }
<ide>
<ide> Ember.assert("You called yield in a template that was not a layout", !!view);
<ide><path>packages/ember-handlebars/tests/helpers/yield_test.js
<ide> module("Support for {{yield}} helper (#307)", {
<ide> },
<ide> teardown: function() {
<ide> Ember.run(function() {
<add> Ember.TEMPLATES = {};
<ide> if (view) {
<ide> view.destroy();
<del> }}
<del> );
<add> }
<add> });
<ide>
<ide> Ember.lookup = originalLookup;
<ide> }
<ide> test("yield should work for views even if _parentView is null", function() {
<ide> equal(view.$().text(), "Layout: View Content");
<ide>
<ide> });
<add>
<add>module("Component {{yield}}", {
<add> setup: function() {},
<add> teardown: function() {
<add> Ember.run(function() {
<add> if (view) {
<add> view.destroy();
<add> }
<add> delete Ember.Handlebars.helpers['inner-component'];
<add> delete Ember.Handlebars.helpers['outer-component'];
<add> });
<add> }
<add>});
<add>
<add>test("yield with nested components (#3220)", function(){
<add> var count = 0;
<add> var InnerComponent = Ember.Component.extend({
<add> layout: Ember.Handlebars.compile("{{yield}}"),
<add> _yield: function (context, options) {
<add> count++;
<add> if (count > 1) throw new Error('is looping');
<add> return this._super(context, options);
<add> }
<add> });
<add>
<add> Ember.Handlebars.helper('inner-component', InnerComponent);
<add>
<add> var OuterComponent = Ember.Component.extend({
<add> layout: Ember.Handlebars.compile("{{#inner-component}}<span>{{yield}}</span>{{/inner-component}}")
<add> });
<add>
<add> Ember.Handlebars.helper('outer-component', OuterComponent);
<add>
<add> view = Ember.View.create({
<add> template: Ember.Handlebars.compile(
<add> "{{#outer-component}}Hello world{{/outer-component}}"
<add> )
<add> });
<add>
<add> Ember.run(function() {
<add> view.appendTo('#qunit-fixture');
<add> });
<add>
<add> equal(view.$('div > span').text(), "Hello world");
<add>});
<ide><path>packages/ember-views/lib/views/component.js
<ide> Ember.Component = Ember.View.extend(Ember.TargetActionSupport, {
<ide> view.appendChild(Ember.View, {
<ide> isVirtual: true,
<ide> tagName: '',
<add> _contextView: parentView,
<ide> template: get(this, 'template'),
<ide> context: get(parentView, 'context'),
<ide> controller: get(parentView, 'controller'),
<ide><path>packages/ember-views/tests/views/component_test.js
<ide> test("Calling sendAction on a component with a context", function() {
<ide> component.sendAction('playing', testContext);
<ide>
<ide> strictEqual(actionContext, testContext, "context was sent with the action");
<del>});
<ide>\ No newline at end of file
<add>}); | 4 |
Go | Go | fix printf verbs of wrong types | 5759b95e7e7c269af48a095773961ed8d13f8798 | <ide><path>integration-cli/docker_cli_create_test.go
<ide> func (s *DockerSuite) TestCreateWithPortRange(c *check.C) {
<ide> c.Fatalf("Expected 1 ports binding, for the port %s but found %s", k, v)
<ide> }
<ide> if k.Port() != v[0].HostPort {
<del> c.Fatalf("Expected host port %d to match published port %d", k.Port(), v[0].HostPort)
<add> c.Fatalf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort)
<ide> }
<ide> }
<ide>
<ide> func (s *DockerSuite) TestCreateWithiLargePortRange(c *check.C) {
<ide> c.Fatalf("Expected 1 ports binding, for the port %s but found %s", k, v)
<ide> }
<ide> if k.Port() != v[0].HostPort {
<del> c.Fatalf("Expected host port %d to match published port %d", k.Port(), v[0].HostPort)
<add> c.Fatalf("Expected host port %s to match published port %s", k.Port(), v[0].HostPort)
<ide> }
<ide> }
<ide>
<ide><path>integration-cli/docker_cli_run_test.go
<ide> func (s *DockerSuite) TestRunAllowPortRangeThroughExpose(c *check.C) {
<ide> c.Fatalf("Port %d is out of range ", portnum)
<ide> }
<ide> if binding == nil || len(binding) != 1 || len(binding[0].HostPort) == 0 {
<del> c.Fatalf("Port is not mapped for the port %d", port)
<add> c.Fatalf("Port is not mapped for the port %s", port)
<ide> }
<ide> }
<ide> } | 2 |
Go | Go | remove unused test-utilities | bca161d7cb219258d2ed208c92998db47c1b05d5 | <ide><path>runconfig/config_test.go
<ide> import (
<ide> "github.com/docker/docker/api/types/container"
<ide> networktypes "github.com/docker/docker/api/types/network"
<ide> "github.com/docker/docker/api/types/strslice"
<del> "gotest.tools/assert"
<del> is "gotest.tools/assert/cmp"
<ide> )
<ide>
<ide> type f struct {
<ide> func callDecodeContainerConfigIsolation(isolation string) (*container.Config, *c
<ide> }
<ide> return decodeContainerConfig(bytes.NewReader(b))
<ide> }
<del>
<del>type decodeConfigTestcase struct {
<del> doc string
<del> wrapper ContainerConfigWrapper
<del> expectedErr string
<del> expectedConfig *container.Config
<del> expectedHostConfig *container.HostConfig
<del> goos string
<del>}
<del>
<del>func runDecodeContainerConfigTestCase(testcase decodeConfigTestcase) func(t *testing.T) {
<del> return func(t *testing.T) {
<del> raw := marshal(t, testcase.wrapper, testcase.doc)
<del> config, hostConfig, _, err := decodeContainerConfig(bytes.NewReader(raw))
<del> if testcase.expectedErr != "" {
<del> if !assert.Check(t, is.ErrorContains(err, "")) {
<del> return
<del> }
<del> assert.Check(t, is.Contains(err.Error(), testcase.expectedErr))
<del> return
<del> }
<del> assert.Check(t, err)
<del> assert.Check(t, is.DeepEqual(testcase.expectedConfig, config))
<del> assert.Check(t, is.DeepEqual(testcase.expectedHostConfig, hostConfig))
<del> }
<del>}
<del>
<del>func marshal(t *testing.T, w ContainerConfigWrapper, doc string) []byte {
<del> b, err := json.Marshal(w)
<del> assert.NilError(t, err, "%s: failed to encode config wrapper", doc)
<del> return b
<del>}
<del>
<del>func containerWrapperWithVolume(volume string) ContainerConfigWrapper {
<del> return ContainerConfigWrapper{
<del> Config: &container.Config{
<del> Volumes: map[string]struct{}{
<del> volume: {},
<del> },
<del> },
<del> HostConfig: &container.HostConfig{},
<del> }
<del>}
<del>
<del>func containerWrapperWithBind(bind string) ContainerConfigWrapper {
<del> return ContainerConfigWrapper{
<del> Config: &container.Config{
<del> Volumes: map[string]struct{}{},
<del> },
<del> HostConfig: &container.HostConfig{
<del> Binds: []string{bind},
<del> },
<del> }
<del>} | 1 |
Ruby | Ruby | standardize the use of current_adapter? | bb38df89bfbfc37913babe2edf6ad73b0dc80358 | <ide><path>activerecord/test/cases/adapters/mysql/active_schema_test.rb
<ide> def test_drop_table
<ide> assert_equal "DROP TABLE `people`", drop_table(:people)
<ide> end
<ide>
<del> if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> def test_create_mysql_database_with_encoding
<ide> assert_equal "CREATE DATABASE `matt` DEFAULT CHARACTER SET `utf8`", create_database(:matt)
<ide> assert_equal "CREATE DATABASE `aimonetti` DEFAULT CHARACTER SET `latin1`", create_database(:aimonetti, {:charset => 'latin1'})
<ide><path>activerecord/test/cases/associations/belongs_to_associations_test.rb
<ide> def test_belongs_to_with_primary_key
<ide>
<ide> def test_belongs_to_with_primary_key_joins_on_correct_column
<ide> sql = Client.joins(:firm_with_primary_key).to_sql
<del> if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> assert_no_match(/`firm_with_primary_keys_companies`\.`id`/, sql)
<ide> assert_match(/`firm_with_primary_keys_companies`\.`name`/, sql)
<ide> elsif current_adapter?(:OracleAdapter)
<ide><path>activerecord/test/cases/base_test.rb
<ide> def test_primary_key_with_no_id
<ide> assert_nil Edge.primary_key
<ide> end
<ide>
<del> unless current_adapter?(:PostgreSQLAdapter,:OracleAdapter,:SQLServerAdapter)
<add> unless current_adapter?(:PostgreSQLAdapter, :OracleAdapter, :SQLServerAdapter)
<ide> def test_limit_with_comma
<ide> assert Topic.limit("1,2").to_a
<ide> end
<ide> def test_limit_should_sanitize_sql_injection_for_limit_with_comas
<ide> end
<ide> end
<ide>
<del> unless current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
<add> unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> def test_limit_should_allow_sql_literal
<ide> assert_equal 1, Topic.limit(Arel.sql('2-1')).to_a.length
<ide> end
<ide> def test_preserving_time_objects
<ide> )
<ide>
<ide> # For adapters which support microsecond resolution.
<del> if current_adapter?(:PostgreSQLAdapter) || current_adapter?(:SQLite3Adapter)
<add> if current_adapter?(:PostgreSQLAdapter, :SQLite3Adapter)
<ide> assert_equal 11, Topic.find(1).written_on.sec
<ide> assert_equal 223300, Topic.find(1).written_on.usec
<ide> assert_equal 9900, Topic.find(2).written_on.usec
<ide> def test_singular_table_name_guesses_for_individual_table
<ide> Post.reset_table_name
<ide> end
<ide>
<del> if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> def test_update_all_with_order_and_limit
<ide> assert_equal 1, Topic.limit(1).order('id DESC').update_all(:content => 'bulk updated!')
<ide> end
<ide><path>activerecord/test/cases/connection_specification/resolver_test.rb
<ide> def resolve(spec)
<ide> end
<ide>
<ide> def test_url_host_no_db
<del> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> spec = resolve 'mysql://foo?encoding=utf8'
<ide> assert_equal({
<ide> :adapter => "mysql",
<ide> def test_url_host_no_db
<ide> end
<ide>
<ide> def test_url_host_db
<del> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> spec = resolve 'mysql://foo/bar?encoding=utf8'
<ide> assert_equal({
<ide> :adapter => "mysql",
<ide> def test_url_host_db
<ide> end
<ide>
<ide> def test_url_port
<del> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> spec = resolve 'mysql://foo:123?encoding=utf8'
<ide> assert_equal({
<ide> :adapter => "mysql",
<ide> def test_url_port
<ide> end
<ide>
<ide> def test_encoded_password
<del> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> skip "only if mysql is available" unless current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> password = 'am@z1ng_p@ssw0rd#!'
<ide> encoded_password = URI.encode_www_form_component(password)
<ide> spec = resolve "mysql://foo:#{encoded_password}@localhost/bar"
<ide><path>activerecord/test/cases/defaults_test.rb
<ide> def test_multiline_default_text
<ide> end
<ide> end
<ide>
<del>if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add>if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> class DefaultsTestWithoutTransactionalFixtures < ActiveRecord::TestCase
<ide> # ActiveRecord::Base#create! (and #save and other related methods) will
<ide> # open a new transaction. When in transactional fixtures mode, this will
<ide><path>activerecord/test/cases/migration/change_schema_test.rb
<ide> def test_create_table_with_not_null_column
<ide>
<ide> def test_create_table_with_defaults
<ide> # MySQL doesn't allow defaults on TEXT or BLOB columns.
<del> mysql = current_adapter?(:MysqlAdapter) || current_adapter?(:Mysql2Adapter)
<add> mysql = current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide>
<ide> connection.create_table :testings do |t|
<ide> t.column :one, :string, :default => "hello"
<ide> def test_create_table_with_limits
<ide> assert_equal 'smallint', one.sql_type
<ide> assert_equal 'integer', four.sql_type
<ide> assert_equal 'bigint', eight.sql_type
<del> elsif current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> assert_match 'int(11)', default.sql_type
<ide> assert_match 'tinyint', one.sql_type
<ide> assert_match 'int', four.sql_type
<ide><path>activerecord/test/cases/primary_keys_test.rb
<ide> def test_set_primary_key_with_no_connection
<ide> end
<ide> end
<ide>
<del>if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add>if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> class PrimaryKeyWithAnsiQuotesTest < ActiveRecord::TestCase
<ide> self.use_transactional_fixtures = false
<del>
<add>
<ide> def test_primaery_key_method_with_ansi_quotes
<ide> con = ActiveRecord::Base.connection
<ide> con.execute("SET SESSION sql_mode='ANSI_QUOTES'")
<ide> assert_equal "id", con.primary_key("topics")
<ide> ensure
<ide> con.reconnect!
<ide> end
<del>
<add>
<ide> end
<ide> end
<ide>
<ide><path>activerecord/test/cases/query_cache_test.rb
<ide> def test_cache_does_not_wrap_string_results_in_arrays
<ide> # Oracle adapter returns count() as Fixnum or Float
<ide> if current_adapter?(:OracleAdapter)
<ide> assert_kind_of Numeric, Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
<del> elsif current_adapter?(:SQLite3Adapter) || current_adapter?(:Mysql2Adapter)
<add> elsif current_adapter?(:SQLite3Adapter, :Mysql2Adapter)
<ide> # Future versions of the sqlite3 adapter will return numeric
<ide> assert_instance_of Fixnum,
<ide> Task.connection.select_value("SELECT count(*) AS count_all FROM tasks")
<ide><path>activerecord/test/cases/schema_dumper_test.rb
<ide> def test_schema_dump_includes_limit_constraint_for_integer_columns
<ide>
<ide> assert_match %r{c_int_4.*}, output
<ide> assert_no_match %r{c_int_4.*limit:}, output
<del> elsif current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> elsif current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> assert_match %r{c_int_1.*limit: 1}, output
<ide> assert_match %r{c_int_2.*limit: 2}, output
<ide> assert_match %r{c_int_3.*limit: 3}, output
<ide> def test_schema_dump_should_honor_nonstandard_primary_keys
<ide> assert_match %r(primary_key: "movieid"), match[1], "non-standard primary key not preserved"
<ide> end
<ide>
<del> if current_adapter?(:MysqlAdapter) or current_adapter?(:Mysql2Adapter)
<add> if current_adapter?(:MysqlAdapter, :Mysql2Adapter)
<ide> def test_schema_dump_should_not_add_default_value_for_mysql_text_field
<ide> output = standard_dump
<ide> assert_match %r{t.text\s+"body",\s+null: false$}, output | 9 |
Go | Go | propagate cpushares in mergeconfig | eef8b0d406412ffe6622ed1f2c858540eb7f75f1 | <ide><path>builder.go
<ide> func (builder *Builder) mergeConfig(userConf, imageConf *Config) {
<ide> if userConf.MemorySwap == 0 {
<ide> userConf.MemorySwap = imageConf.MemorySwap
<ide> }
<add> if userConf.CpuShares == 0 {
<add> userConf.CpuShares = imageConf.CpuShares
<add> }
<ide> if userConf.PortSpecs == nil || len(userConf.PortSpecs) == 0 {
<ide> userConf.PortSpecs = imageConf.PortSpecs
<ide> } | 1 |
Text | Text | fix example in repl documentation | 73b0182553da673b12f5c07583dc34e01bb1d396 | <ide><path>doc/api/repl.md
<ide> const repl = require('repl');
<ide> var msg = 'message';
<ide>
<ide> const r = repl.start('> ');
<del>Object.defineProperty(r, 'm', {
<add>Object.defineProperty(r.context, 'm', {
<ide> configurable: false,
<ide> enumerable: true,
<ide> value: msg | 1 |
Java | Java | add marble diagram to the single.filter method | c8a98520ee38152d8acce56bdb0a9e9127ccf7cc | <ide><path>src/main/java/io/reactivex/Single.java
<ide> public final Single<T> doOnDispose(final Action onDispose) {
<ide> * Filters the success item of the Single via a predicate function and emitting it if the predicate
<ide> * returns true, completing otherwise.
<ide> * <p>
<del> * <img width="640" height="310" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/filter.png" alt="">
<add> * <img width="640" height="457" src="https://raw.github.com/wiki/ReactiveX/RxJava/images/rx-operators/Single.filter.png" alt="">
<ide> * <dl>
<ide> * <dt><b>Scheduler:</b></dt>
<ide> * <dd>{@code filter} does not operate by default on a particular {@link Scheduler}.</dd> | 1 |
Javascript | Javascript | fix iterable hook | 19316037b03cf7e012dd8342c6764a3159603f45 | <ide><path>packages/ember-glimmer/lib/environment.js
<ide> export default class Environment extends GlimmerEnvironment {
<ide> return ConditionalReference.create(reference);
<ide> }
<ide>
<del> iterableFor(ref, args) {
<del> let keyPath = args.named.get('key').value();
<del> return createIterable(ref, keyPath);
<add> iterableFor(ref, key) {
<add> return createIterable(ref, key);
<ide> }
<ide>
<ide> scheduleInstallModifier() { | 1 |
Ruby | Ruby | remove unused webrick_server file | 746a3856782293b7b81706498ebaf58b51da294e | <ide><path>railties/lib/rails/webrick_server.rb
<del># Donated by Florian Gross
<del>
<del>require 'webrick'
<del>require 'cgi'
<del>require 'stringio'
<del>require 'dispatcher'
<del>
<del>include WEBrick
<del>
<del>class CGI #:nodoc:
<del> def stdinput
<del> @stdin || $stdin
<del> end
<del>
<del> def env_table
<del> @env_table || ENV
<del> end
<del>
<del> def initialize(type = "query", table = nil, stdin = nil)
<del> @env_table, @stdin = table, stdin
<del>
<del> if defined?(MOD_RUBY) && !ENV.key?("GATEWAY_INTERFACE")
<del> Apache.request.setup_cgi_env
<del> end
<del>
<del> extend QueryExtension
<del> @multipart = false
<del> if defined?(CGI_PARAMS)
<del> warn "do not use CGI_PARAMS and CGI_COOKIES"
<del> @params = CGI_PARAMS.dup
<del> @cookies = CGI_COOKIES.dup
<del> else
<del> initialize_query() # set @params, @cookies
<del> end
<del> @output_cookies = nil
<del> @output_hidden = nil
<del> end
<del>end
<del>
<del># A custom dispatch servlet for use with WEBrick. It dispatches requests
<del># (using the Rails Dispatcher) to the appropriate controller/action. By default,
<del># it restricts WEBrick to a managing a single Rails request at a time, but you
<del># can change this behavior by setting ActionController::Base.allow_concurrency
<del># to true.
<del>class DispatchServlet < WEBrick::HTTPServlet::AbstractServlet
<del> # Start the WEBrick server with the given options, mounting the
<del> # DispatchServlet at <tt>/</tt>.
<del> def self.dispatch(options = {})
<del> Socket.do_not_reverse_lookup = true # patch for OS X
<del>
<del> params = { :Port => options[:port].to_i,
<del> :ServerType => options[:server_type],
<del> :BindAddress => options[:ip] }
<del> params[:MimeTypes] = options[:mime_types] if options[:mime_types]
<del>
<del> server = WEBrick::HTTPServer.new(params)
<del> server.mount('/', DispatchServlet, options)
<del>
<del> trap("INT") { server.shutdown }
<del> server.start
<del> end
<del>
<del> def initialize(server, options) #:nodoc:
<del> @server_options = options
<del> @file_handler = WEBrick::HTTPServlet::FileHandler.new(server, options[:server_root])
<del> # Change to the Rails.root, since Webrick::Daemon.start does a Dir::cwd("/")
<del> # OPTIONS['working_directory'] is an absolute path of the Rails.root, set in railties/lib/commands/servers/webrick.rb
<del> Dir.chdir(OPTIONS['working_directory']) if defined?(OPTIONS) && File.directory?(OPTIONS['working_directory'])
<del> super
<del> end
<del>
<del> def service(req, res) #:nodoc:
<del> unless handle_file(req, res)
<del> unless handle_dispatch(req, res)
<del> raise WEBrick::HTTPStatus::NotFound, "`#{req.path}' not found."
<del> end
<del> end
<del> end
<del>
<del> def handle_file(req, res) #:nodoc:
<del> begin
<del> req = req.dup
<del> path = req.path.dup
<del>
<del> # Add .html if the last path piece has no . in it
<del> path << '.html' if path != '/' && (%r{(^|/)[^./]+$} =~ path)
<del> path.gsub!('+', ' ') # Unescape + since FileHandler doesn't do so.
<del>
<del> req.instance_variable_set(:@path_info, path) # Set the modified path...
<del>
<del> @file_handler.send(:service, req, res)
<del> return true
<del> rescue HTTPStatus::PartialContent, HTTPStatus::NotModified => err
<del> res.set_error(err)
<del> return true
<del> rescue => err
<del> return false
<del> end
<del> end
<del>
<del> def handle_dispatch(req, res, origin = nil) #:nodoc:
<del> data = StringIO.new
<del> Dispatcher.dispatch(
<del> CGI.new("query", create_env_table(req, origin), StringIO.new(req.body || "")),
<del> ActionController::CgiRequest::DEFAULT_SESSION_OPTIONS,
<del> data
<del> )
<del>
<del> header, body = extract_header_and_body(data)
<del>
<del> set_charset(header)
<del> assign_status(res, header)
<del> res.cookies.concat(header.delete('set-cookie') || [])
<del> header.each { |key, val| res[key] = val.join(", ") }
<del>
<del> res.body = body
<del> return true
<del> rescue => err
<del> p err, err.backtrace
<del> return false
<del> end
<del>
<del> private
<del> def create_env_table(req, origin)
<del> env = req.meta_vars.clone
<del> env.delete "SCRIPT_NAME"
<del> env["QUERY_STRING"] = req.request_uri.query
<del> env["REQUEST_URI"] = origin if origin
<del> return env
<del> end
<del>
<del> def extract_header_and_body(data)
<del> data.rewind
<del> data = data.read
<del>
<del> raw_header, body = *data.split(/^[\xd\xa]{2}/on, 2)
<del> header = WEBrick::HTTPUtils::parse_header(raw_header)
<del>
<del> return header, body
<del> end
<del>
<del> def set_charset(header)
<del> ct = header["content-type"]
<del> if ct.any? { |x| x =~ /^text\// } && ! ct.any? { |x| x =~ /charset=/ }
<del> ch = @server_options[:charset] || "UTF-8"
<del> ct.find { |x| x =~ /^text\// } << ("; charset=" + ch)
<del> end
<del> end
<del>
<del> def assign_status(res, header)
<del> if /^(\d+)/ =~ header['status'][0]
<del> res.status = $1.to_i
<del> header.delete('status')
<del> end
<del> end
<del>end | 1 |
Python | Python | update eye and tri to take dtype in mlab | 1a83cc8b5cfc71b5a7f01a5dcefcd4de4e306cfd | <ide><path>numpy/oldnumeric/mlab.py
<ide> from numpy.linalg import eig, svd
<ide> from numpy.random import rand, randn
<ide>
<del>from typeconv import oldtype2dtype as o2d
<add>from typeconv import convtypecode
<ide>
<del>def eye(N, M=None, k=0, typecode=None):
<add>def eye(N, M=None, k=0, typecode=None, dtype=None):
<ide> """ eye returns a N-by-M 2-d array where the k-th diagonal is all ones,
<ide> and everything else is zeros.
<ide> """
<del> dtype = o2d[typecode]
<add> dtype = convtypecode(typecode, dtype)
<ide> if M is None: M = N
<ide> m = nn.equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k)
<ide> if m.dtype != dtype:
<ide> return m.astype(dtype)
<ide>
<del>def tri(N, M=None, k=0, typecode=None):
<add>def tri(N, M=None, k=0, typecode=None, dtype=None):
<ide> """ returns a N-by-M array where all the diagonals starting from
<ide> lower left corner up to the k-th are all ones.
<ide> """
<del> dtype = o2d[typecode]
<add> dtype = convtypecode(typecode, dtype)
<ide> if M is None: M = N
<ide> m = nn.greater_equal(nn.subtract.outer(nn.arange(N), nn.arange(M)),-k)
<ide> if m.dtype != dtype: | 1 |
Text | Text | replace stub with init summary and examples | 8605ddfbfe7d2d58c7dd686c7fc683042c085aed | <ide><path>client/src/pages/guide/english/computer-hardware/rom/index.md
<ide> title: ROM
<ide> ---
<ide> ## Read Only Memory
<ide>
<del>This is a stub. <a href='https://github.com/freecodecamp/guides/tree/master/src/pages/computer-hardware/rom/index.md' target='_blank' rel='nofollow'>Help our community expand it</a>.
<add>Read-only Memory (ROM) is a self descriptive type of memory that references the idea that a computer and its appliations can only read data from it. This is in direct contrast to other memory types, where it is possibe to read and write data and store it in memory.
<ide>
<del><a href='https://github.com/freecodecamp/guides/blob/master/README.md' target='_blank' rel='nofollow'>This quick style guide will help ensure your pull request gets accepted</a>.
<add>### Examples of ROM
<add>
<add>#### BIOS ROM
<add>In the early days of modern computers, one of the most common ROM chips used was the BIOS (Basic Input Output System) ROM. The chip would hold specific instructions that a computer needed in order to start up and it was critical that the information could not be accidentally modified. Once the BIOS ROM chip was installed (generally soldered to the motherboard), it could not be modified. Fast forward to the 2000's and BIOS technology had improved to where a BIOS could now use EPROM (An erasable type of ROM) where the instructions could be updated in a controlled fashion by the manufacturer, but the operation of the chip would still have the same behavior in being read-only. The act of "updating the BIOS" for a computer is infact updating the programmaing of the EPROM Bios.
<add>
<add>#### CD-ROM
<add>The CD-ROM is a type of compact disc storage object that requires the use of an optical laser to read the data off the disc. The devices used to read the data house the lasers and are called CD-ROM Drives. The disc itself is generally created in a factory and once made, is read only. This is in contrast to the CD-R (compact disc recordables) medium which has the additional ability to hold new data.
<ide>
<ide> <!-- The article goes here, in GitHub-flavored Markdown. Feel free to add YouTube videos, images, and CodePen/JSBin embeds -->
<ide>
<ide> #### More Information:
<ide> <!-- Please add any articles you think might be helpful to read before writing the article -->
<add><a href='https://en.wikipedia.org/wiki/Read-only_memory' target='_blank' rel='nofollow'>Read-only memory</a>
<add><a href='https://en.wikipedia.org/wiki/BIOS' target='_blank' rel='nofollow'>BIOS</a>
<add><a href='https://en.wikipedia.org/wiki/CD-ROM' target='_blank' rel='nofollow'>CD-ROM</a> | 1 |
Text | Text | add v4.4.0-beta.1 to changelog | 97aa2436b08e7569e4f6d4e8e692e32dc1d0e909 | <ide><path>CHANGELOG.md
<ide> # Ember Changelog
<ide>
<add>### v4.4.0-beta.1 (March 24, 2022)
<add>
<add>- [#19882](https://github.com/emberjs/ember.js/pull/19882) / [#20005](https://github.com/emberjs/ember.js/pull/20005) [FEATURE] Implement the `unique-id` helper per [RFC #0659](https://github.com/emberjs/rfcs/blob/master/text/0659-unique-id-helper.md).
<add>- [#19981](https://github.com/emberjs/ember.js/pull/19981) [FEATURE] Facilitate custom test setups per [RFC #0637](https://github.com/emberjs/rfcs/blob/master/text/0637-customizable-test-setups.md).
<add>- [#16879](https://github.com/emberjs/ember.js/pull/16879) [BUGFIX] isEmpty on nested objects
<add>- [#17978](https://github.com/emberjs/ember.js/pull/17978) Make hasListeners public
<add>- [#20014](https://github.com/emberjs/ember.js/pull/20014) Log `until` for deprecations
<add>
<ide> ### v4.3.0 (March 21, 2022)
<ide>
<ide> - [#20025](https://github.com/emberjs/ember.js/pull/20025) [BUGFIX] Fix a memory leak in the Router Service class | 1 |
Text | Text | add oxford comma | c562b63b7fdd7ba438b0c0be1bfe6a891b432d80 | <ide><path>.github/PULL_REQUEST_TEMPLATE.md
<ide> <!--
<del>Pull Requests without a descriptive title, thorough description or tests will be closed.
<add>Pull Requests without a descriptive title, thorough description, or tests will be closed.
<ide>
<ide> Please include the benefit to end users; the reasons it does not break any existing features; how it makes building web applications easier, etc.
<ide> --> | 1 |
Javascript | Javascript | add notes to remove in v5 | 3b2e3317908d1d6b1bb70b55306e03ba85401568 | <ide><path>lib/webpack.js
<ide> const defineMissingPluginError = (pluginName, errorMessage) => {
<ide> });
<ide> };
<ide>
<add>// TODO remove in webpack 5
<ide> defineMissingPluginError(
<ide> "UglifyJsPlugin",
<ide> "webpack.optimize.UglifyJsPlugin has been removed, please use config.optimization.minimize instead."
<ide> );
<ide>
<add>// TODO remove in webpack 5
<ide> defineMissingPluginError(
<ide> "CommonsChunkPlugin",
<ide> "webpack.optimize.CommonsChunkPlugin has been removed, please use config.optimization.splitChunks instead." | 1 |
Ruby | Ruby | build fix for plugin new generator change | a6c41601fe7d39320cc44091952e360ea2bae726 | <ide><path>railties/test/generators/plugin_new_generator_test.rb
<ide> def test_invalid_plugin_name_raises_an_error
<ide>
<ide> content = capture(:stderr){ run_generator [File.join(destination_root, "things4.3")] }
<ide> assert_equal "Invalid plugin name things4.3. Please give a name which use only alphabetic or numeric or \"_\" characters.\n", content
<del>
<add>
<ide> content = capture(:stderr){ run_generator [File.join(destination_root, "43things")] }
<ide> assert_equal "Invalid plugin name 43things. Please give a name which does not start with numbers.\n", content
<ide> end
<ide> def test_create_mountable_application_with_mountable_option
<ide> def test_creating_gemspec
<ide> run_generator
<ide> assert_file "bukkits.gemspec", /s.name\s+= "bukkits"/
<del> assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*"\]/
<add> assert_file "bukkits.gemspec", /s.files = Dir\["\{app,config,db,lib\}\/\*\*\/\*", "MIT-LICENSE", "Rakefile", "README\.rdoc"\]/
<ide> assert_file "bukkits.gemspec", /s.test_files = Dir\["test\/\*\*\/\*"\]/
<ide> assert_file "bukkits.gemspec", /s.version\s+ = Bukkits::VERSION/
<ide> end | 1 |
Ruby | Ruby | fix version audit for version subclasses | 132e6a3a8eff2b1887f7d59ddce3806098e7cbde | <ide><path>Library/Homebrew/cmd/audit.rb
<ide> def audit_specs
<ide> else
<ide> version_text = s.version unless s.version.detected_from_url?
<ide> version_url = Version.parse(s.url)
<del> if version_url.to_s == version_text.to_s
<add> if version_url.to_s == version_text.to_s && s.version.instance_of?(Version)
<ide> problem "#{spec} version #{version_text} is redundant with version scanned from URL"
<ide> end
<ide> end | 1 |
Ruby | Ruby | extend #ds_file? in pathname | 56a0afe5792d398d1682426bbebb1e53346b34d5 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def install_metafiles(from = Pathname.pwd)
<ide> end
<ide> end
<ide>
<add> def ds_store?
<add> basename.to_s == ".DS_Store"
<add> end
<add>
<ide> # https://bugs.ruby-lang.org/issues/9915
<ide> if RUBY_VERSION == "2.0.0"
<ide> prepend Module.new {
<ide><path>Library/Homebrew/test/pathname_test.rb
<ide> def test_cp_path_sub_directory
<ide> @dir.cp_path_sub @src, @dst
<ide> assert_predicate @dst/@dir.basename, :directory?
<ide> end
<add>
<add> def test_ds_store
<add> refute_predicate @file, :ds_store?
<add> assert_predicate @src/".DS_Store", :ds_store?
<add> end
<ide> end
<ide>
<ide> class PathnameInstallTests < Homebrew::TestCase | 2 |
Go | Go | use canonical names for http headers | 948c2c45bb9215b2f08d1f605215249da926760f | <ide><path>client/request.go
<ide> func (cli *Client) addHeaders(req *http.Request, headers headers) *http.Request
<ide> // Add CLI Config's HTTP Headers BEFORE we set the Docker headers
<ide> // then the user can't change OUR headers
<ide> for k, v := range cli.customHTTPHeaders {
<del> if versions.LessThan(cli.version, "1.25") && k == "User-Agent" {
<add> if versions.LessThan(cli.version, "1.25") && http.CanonicalHeaderKey(k) == "User-Agent" {
<ide> continue
<ide> }
<ide> req.Header.Set(k, v)
<ide> }
<ide>
<ide> for k, v := range headers {
<del> req.Header[k] = v
<add> req.Header[http.CanonicalHeaderKey(k)] = v
<ide> }
<ide> return req
<ide> } | 1 |
Javascript | Javascript | remove duplicated client code | 45f80409dca104aa824cfbbca13baaf102f2c077 | <ide><path>packages/next/client/index.js
<ide> export async function render (props) {
<ide> export async function renderError (props) {
<ide> const { App, err } = props
<ide>
<add> // In development runtime errors are caught by react-error-overlay
<add> // In production we catch runtime errors using componentDidCatch which will trigger renderError
<ide> if (process.env.NODE_ENV !== 'production') {
<ide> return webpackHMR.reportRuntimeError(webpackHMR.prepareError(err))
<ide> }
<ide> async function doRender ({ App, Component, props, err }) {
<ide> appProps
<ide> })
<ide>
<del> // In development runtime errors are caught by react-error-overlay
<del> if (process.env.NODE_ENV === 'development') {
<del> renderReactElement(
<del> <AppContainer>
<del> <App {...appProps} />
<del> </AppContainer>,
<del> appElement
<del> )
<del> } else {
<del> // In production we catch runtime errors using componentDidCatch which will trigger renderError
<del> renderReactElement(
<del> <AppContainer>
<del> <App {...appProps} />
<del> </AppContainer>,
<del> appElement
<del> )
<del> }
<add> // We catch runtime errors using componentDidCatch which will trigger renderError
<add> renderReactElement(
<add> <AppContainer>
<add> <App {...appProps} />
<add> </AppContainer>,
<add> appElement
<add> )
<ide>
<ide> emitter.emit('after-reactdom-render', { Component, ErrorComponent, appProps })
<ide> } | 1 |
Javascript | Javascript | remove superfluous elses | cc00e6610021fb998ad019408ced7301f95d3f99 | <ide><path>d3.js
<ide> d3 = function() {
<ide> if (!dx && q < 0) return;
<ide> r = -q / dx;
<ide> if (dx < 0) {
<del> if (r < t0) return; else if (r < t1) t1 = r;
<add> if (r < t0) return;
<add> if (r < t1) t1 = r;
<ide> } else if (dx > 0) {
<del> if (r > t1) return; else if (r > t0) t0 = r;
<add> if (r > t1) return;
<add> if (r > t0) t0 = r;
<ide> }
<ide> q = x1 - ax;
<ide> if (!dx && q < 0) return;
<ide> r = q / dx;
<ide> if (dx < 0) {
<del> if (r > t1) return; else if (r > t0) t0 = r;
<add> if (r > t1) return;
<add> if (r > t0) t0 = r;
<ide> } else if (dx > 0) {
<del> if (r < t0) return; else if (r < t1) t1 = r;
<add> if (r < t0) return;
<add> if (r < t1) t1 = r;
<ide> }
<ide> q = ay - y0;
<ide> if (!dy && q < 0) return;
<ide> r = -q / dy;
<ide> if (dy < 0) {
<del> if (r < t0) return; else if (r < t1) t1 = r;
<add> if (r < t0) return;
<add> if (r < t1) t1 = r;
<ide> } else if (dy > 0) {
<del> if (r > t1) return; else if (r > t0) t0 = r;
<add> if (r > t1) return;
<add> if (r > t0) t0 = r;
<ide> }
<ide> q = y1 - ay;
<ide> if (!dy && q < 0) return;
<ide> r = q / dy;
<ide> if (dy < 0) {
<del> if (r > t1) return; else if (r > t0) t0 = r;
<add> if (r > t1) return;
<add> if (r > t0) t0 = r;
<ide> } else if (dy > 0) {
<del> if (r < t0) return; else if (r < t1) t1 = r;
<add> if (r < t0) return;
<add> if (r < t1) t1 = r;
<ide> }
<ide> if (t0 > 0) line.a = {
<ide> x: ax + t0 * dx,
<ide><path>src/geom/clip-line.js
<ide> function d3_geom_clipLine(x0, y0, x1, y1) {
<ide> r = -q / dx;
<ide> if (dx < 0) {
<ide> if (r < t0) return;
<del> else if (r < t1) t1 = r;
<add> if (r < t1) t1 = r;
<ide> } else if (dx > 0) {
<ide> if (r > t1) return;
<del> else if (r > t0) t0 = r;
<add> if (r > t0) t0 = r;
<ide> }
<ide>
<ide> q = x1 - ax;
<ide> if (!dx && q < 0) return;
<ide> r = q / dx;
<ide> if (dx < 0) {
<ide> if (r > t1) return;
<del> else if (r > t0) t0 = r;
<add> if (r > t0) t0 = r;
<ide> } else if (dx > 0) {
<ide> if (r < t0) return;
<del> else if (r < t1) t1 = r;
<add> if (r < t1) t1 = r;
<ide> }
<ide>
<ide> q = ay - y0;
<ide> if (!dy && q < 0) return;
<ide> r = -q / dy;
<ide> if (dy < 0) {
<ide> if (r < t0) return;
<del> else if (r < t1) t1 = r;
<add> if (r < t1) t1 = r;
<ide> } else if (dy > 0) {
<ide> if (r > t1) return;
<del> else if (r > t0) t0 = r;
<add> if (r > t0) t0 = r;
<ide> }
<ide>
<ide> q = y1 - ay;
<ide> if (!dy && q < 0) return;
<ide> r = q / dy;
<ide> if (dy < 0) {
<ide> if (r > t1) return;
<del> else if (r > t0) t0 = r;
<add> if (r > t0) t0 = r;
<ide> } else if (dy > 0) {
<ide> if (r < t0) return;
<del> else if (r < t1) t1 = r;
<add> if (r < t1) t1 = r;
<ide> }
<ide>
<ide> if (t0 > 0) line.a = {x: ax + t0 * dx, y: ay + t0 * dy}; | 2 |
Javascript | Javascript | add redux wiring for legacy certs | c2ffd6471b91047206150548d72b227c307d0f03 | <ide><path>client/src/components/settings/Certification.js
<ide> class CertificationSettings extends Component {
<ide> const isCertClaimed = this.getUserIsCertMap()[certName];
<ide> const initialObject = {};
<ide> let filledforms = 0;
<del> legacyProjectMap[certName].forEach(element => {
<add> legacyProjectMap[certName].forEach(project => {
<ide> let completedProject = find(completedChallenges, function(challenge) {
<del> return challenge['id'] === element['id'];
<add> return challenge['id'] === project['id'];
<ide> });
<ide> if (!completedProject) {
<del> initialObject[element.title] = '';
<add> initialObject[project.title] = '';
<ide> } else {
<del> initialObject[element.title] = completedProject.solution;
<add> initialObject[project.title] = completedProject.solution;
<ide> filledforms++;
<ide> }
<ide> });
<ide><path>client/src/redux/index.js
<ide> export const reducer = handleActions(
<ide> error: payload
<ide> }
<ide> }),
<del> [types.submitComplete]: (state, { payload: { id } }) => {
<add> [types.submitComplete]: (state, { payload: { id, challArray } }) => {
<add> let submitedchallneges = [{ id }];
<add> if (challArray) {
<add> submitedchallneges = challArray;
<add> }
<add> console.log(...submitedchallneges);
<add> const { appUsername } = state;
<add> return {
<add> ...state,
<add> completionCount: state.completionCount + 1,
<add> user: {
<add> ...state.user,
<add> [appUsername]: {
<add> ...state.user[appUsername],
<add> completedChallenges: uniqBy(
<add> [
<add> ...submitedchallneges,
<add> ...state.user[appUsername].completedChallenges
<add> ],
<add> 'id'
<add> )
<add> }
<add> }
<add> };
<add> },
<add> [settingsTypes.updateLegacyCertificateComplete]: (state, { payload }) => {
<ide> const { appUsername } = state;
<ide> return {
<ide> ...state,
<ide> export const reducer = handleActions(
<ide> [appUsername]: {
<ide> ...state.user[appUsername],
<ide> completedChallenges: uniqBy(
<del> [...state.user[appUsername].completedChallenges, { id }],
<add> [...state.user[appUsername].completedChallenges, payload],
<ide> 'id'
<ide> )
<ide> }
<ide><path>client/src/redux/settings/update-legacy-certificate-saga.js
<ide> import { takeEvery, select, call, put } from 'redux-saga/effects';
<ide>
<ide> import { putUpdateLegacyCertificate } from '../../utils/ajax';
<del>import { completedChallengesSelector } from '../';
<add>import { completedChallengesSelector, submitComplete } from '../';
<ide> import { legacyProjectMap } from '../../resources/certProjectMap';
<ide> import { createFlashMessage } from '../../components/Flash/redux';
<del>import {
<del> updateLegacyCertificateComplete,
<del> updateLegacyCertificateError
<del>} from './';
<add>import standardErrorMessage from '../../utils/reallyWeirdErrorMessage';
<add>import { updateLegacyCertificateError } from './';
<ide>
<ide> const completedChallenges = state => completedChallengesSelector(state);
<ide>
<ide> function* updateLegacyCertificateSaga({ payload }) {
<ide> break;
<ide> }
<ide> }
<add>
<ide> // make an object with keys as challenge ids and values as solutions
<ide> let idsToSolutions = {};
<ide> for (let i of Object.keys(payload)) {
<ide> function* updateLegacyCertificateSaga({ payload }) {
<ide> }
<ide> }
<ide> }
<add>
<ide> // find how many challnegs have been updated and how many are new
<ide> let completed = yield select(completedChallenges);
<del> let newSubmissions = 0;
<ide> let challengesToUpdate = {};
<ide> let newChalleneFound = true;
<ide> for (let j of Object.keys(idsToSolutions)) {
<ide> function* updateLegacyCertificateSaga({ payload }) {
<ide> }
<ide> if (newChalleneFound && idsToSolutions[j] !== '') {
<ide> challengesToUpdate[j] = idsToSolutions[j];
<del> newSubmissions++;
<ide> }
<ide> newChalleneFound = true;
<ide> }
<del> console.log(newSubmissions);
<ide>
<del> // shape the body of the http calls so it is consumable by api
<add> // shape the body of the http call so it is consumable by api
<ide> const body = {
<ide> projects: {
<ide> [legacyCert]: challengesToUpdate
<ide> }
<ide> };
<ide>
<add> // shape to update completed challenges
<add> let reduxShape = [];
<add> for (let obj in challengesToUpdate) {
<add> if (challengesToUpdate.hasOwnProperty(obj)) {
<add> reduxShape.push({ id: obj, solution: challengesToUpdate[obj] });
<add> }
<add> }
<add>
<ide> try {
<del> const response = yield call(putUpdateLegacyCertificate, body);
<del> yield put(
<del> updateLegacyCertificateComplete({ updatedChallenges: challengesToUpdate })
<del> );
<add> const { data: response } = yield call(putUpdateLegacyCertificate, body);
<add> yield put(submitComplete({ challArray: reduxShape }));
<ide> yield put(createFlashMessage(response));
<ide> } catch (e) {
<ide> yield put(updateLegacyCertificateError(e));
<add> yield put(createFlashMessage(standardErrorMessage));
<ide> }
<ide> }
<ide> | 3 |
Go | Go | reset stdin config before running build actions | 0f293f9eb31bdf8ff7adcb31baafca3f6fde3aab | <ide><path>builder/dockerfile/internals.go
<ide> func (b *Builder) processImageFrom(img builder.Image) error {
<ide> onBuildTriggers := b.runConfig.OnBuild
<ide> b.runConfig.OnBuild = []string{}
<ide>
<add> // Reset stdin settings as all build actions run without stdin
<add> b.runConfig.OpenStdin = false
<add> b.runConfig.StdinOnce = false
<add>
<ide> // parse the ONBUILD triggers by invoking the parser
<ide> for _, step := range onBuildTriggers {
<ide> ast, err := parser.Parse(strings.NewReader(step), &b.directive) | 1 |
PHP | PHP | update doc blocks | b6d1d1c7158e62035813bad1515fced87ee9e53f | <ide><path>lib/Cake/Database/Schema/MysqlSchema.php
<ide> public function extraSchemaColumns() {
<ide> /**
<ide> * Generate the SQL to create a table.
<ide> *
<del> * @param Table $table Table instance
<add> * @param Cake\Database\Schema\Table $table Table instance
<ide> * @param array $columns The columns to go inside the table.
<ide> * @param array $constraints The constraints for the table.
<ide> * @param array $indexes The indexes for the table.
<del> * @return array A complete CREATE TABLE statement(s)
<add> * @return array Complete CREATE TABLE statement(s)
<ide> */
<ide> public function createTableSql($table, $columns, $constraints, $indexes) {
<ide> $content = implode(",\n", array_merge($columns, $constraints, $indexes));
<ide><path>lib/Cake/Database/Schema/PostgresSchema.php
<ide> public function constraintSql(Table $table, $name) {
<ide> /**
<ide> * Generate the SQL to create a table.
<ide> *
<del> * @param string $table The name of the table.
<add> * @param Cake\Database\Schema\Table $table Table instance.
<ide> * @param array $columns The columns to go inside the table.
<ide> * @param array $constraints The constraints for the table.
<ide> * @param array $indexes The indexes for the table.
<del> * @return string A complete CREATE TABLE statement
<add> * @return string Complete CREATE TABLE statement
<ide> */
<del> public function createTableSql($table, $columns, $constraints, $indexes) {
<add> public function createTableSql(Table $table, $columns, $constraints, $indexes) {
<ide> $content = array_merge($columns, $constraints);
<ide> $content = implode(",\n", array_filter($content));
<ide> $tableName = $this->_driver->quoteIdentifier($table->name());
<ide><path>lib/Cake/Database/Schema/SqliteSchema.php
<ide> public function indexSql(Table $table, $name) {
<ide> /**
<ide> * Generate the SQL to create a table.
<ide> *
<del> * @param Table $table Table instance
<add> * @param Table $table Cake\Database\Schema\Table instance
<ide> * @param array $columns The columns to go inside the table.
<ide> * @param array $constraints The constraints for the table.
<ide> * @param array $indexes The indexes for the table.
<del> * @return array A complete CREATE TABLE statement(s)S
<add> * @return array Complete CREATE TABLE statement(s)S
<ide> */
<ide> public function createTableSql($table, $columns, $constraints, $indexes) {
<ide> $lines = array_merge($columns, $constraints); | 3 |
Javascript | Javascript | fix tests when inspector is disabled | 7c8a60851c459ea18afbfc54bfc8cf7394ea56c3 | <ide><path>test/parallel/test-repl-history-navigation.js
<ide> const tests = [
<ide> env: { NODE_REPL_HISTORY: defaultHistoryPath },
<ide> test: ['const util = {}', ENTER,
<ide> 'ut', RIGHT, ENTER],
<del> expected: common.hasIntl && common.hasCrypto ? [
<add> expected: [
<ide> prompt, ...'const util = {}',
<ide> 'undefined\n',
<del> prompt, ...'ut', ' // il', '\n// {}',
<del> 'il', '\n// {}',
<add> prompt, ...'ut', ...(prev ? [' // il', '\n// {}',
<add> 'il', '\n// {}'] : [' // il', 'il']),
<ide> '{}\n',
<ide> prompt,
<del> ] : [],
<add> ],
<ide> clean: false
<ide> },
<ide> {
<ide> const tests = [
<ide> 'globalThis.util = {}', ENTER,
<ide> 'ut', RIGHT, ENTER,
<ide> 'Reflect.defineProperty(globalThis, "util", utilDesc)', ENTER],
<del> expected: common.hasIntl && common.hasCrypto ? [
<add> expected: [
<ide> prompt, ...'const utilDesc = ' +
<ide> 'Reflect.getOwnPropertyDescriptor(globalThis, "util")',
<ide> 'undefined\n',
<ide> const tests = [
<ide> prompt, ...'Reflect.defineProperty(globalThis, "util", utilDesc)',
<ide> 'true\n',
<ide> prompt,
<del> ] : [],
<add> ],
<ide> clean: false
<ide> },
<ide> ]; | 1 |
Javascript | Javascript | use setter function | a31539c59f4e26b89a8add347ecde70d3a527e86 | <ide><path>examples/jsm/math/MeshSurfaceSampler.js
<ide> var MeshSurfaceSampler = ( function () {
<ide> }
<ide>
<ide> this.geometry = geometry;
<add> this.randomFunction = Math.random;
<ide>
<ide> this.positionAttribute = this.geometry.getAttribute( 'position' );
<ide> this.weightAttribute = null;
<ide> var MeshSurfaceSampler = ( function () {
<ide>
<ide> },
<ide>
<del> getRandomNumber: function () {
<add> setRandomFunction: function ( randomFunction ) {
<ide>
<del> return Math.random();
<add> this.randomFunction = randomFunction;
<add> return this;
<ide>
<ide> },
<ide>
<ide> sample: function ( targetPosition, targetNormal ) {
<ide>
<ide> var cumulativeTotal = this.distribution[ this.distribution.length - 1 ];
<ide>
<del> var faceIndex = this.binarySearch( this.getRandomNumber() * cumulativeTotal );
<add> var faceIndex = this.binarySearch( this.randomFunction() * cumulativeTotal );
<ide>
<ide> return this.sampleFace( faceIndex, targetPosition, targetNormal );
<ide>
<ide> var MeshSurfaceSampler = ( function () {
<ide>
<ide> sampleFace: function ( faceIndex, targetPosition, targetNormal ) {
<ide>
<del> var u = this.getRandomNumber();
<del> var v = this.getRandomNumber();
<add> var u = this.randomFunction();
<add> var v = this.randomFunction();
<ide>
<ide> if ( u + v > 1 ) {
<ide> | 1 |
Python | Python | add predict paths to _ml models | a21d8f3f0b2b470ce1fd17df96429a2300b04018 | <ide><path>spacy/_ml.py
<ide> def drop_layer_fwd(X, drop=0.):
<ide> return layer.begin_update(X, drop=drop)
<ide> else:
<ide> return X, lambda dX, sgd=None: dX
<del> return wrap(drop_layer_fwd, layer)
<add>
<add> model = wrap(drop_layer_fwd, layer)
<add> model.predict = layer
<add> return model
<ide>
<ide>
<ide> def Tok2Vec(width, embed_size, preprocess=None):
<ide> def fine_tune_bwd(d_output, sgd=None):
<ide> sgd(model._mem.weights, model._mem.gradient, key=model.id)
<ide> return [d_o * model.mix[0] for d_o in d_output]
<ide> return output, fine_tune_bwd
<add>
<add> def fine_tune_predict(docs_tokvecs):
<add> docs, tokvecs = docs_tokvecs
<add> vecs = embedding(docs)
<add> return [model.mix[0]*tv+model.mix[1]*v
<add> for tv, v in zip(tokvecs, vecs)]
<add>
<ide> model = wrap(fine_tune_fwd, embedding)
<ide> model.mix = model._mem.add((model.id, 'mix'), (2,))
<ide> model.mix.fill(0.5)
<ide> model.d_mix = model._mem.add_gradient((model.id, 'd_mix'), (model.id, 'mix'))
<add> model.predict = fine_tune_predict
<ide> return model
<ide>
<ide> | 1 |
Text | Text | fix a typo in dockerfile.5.md | c4340de04faec1b9d54da62a8a2174da4d6a301b | <ide><path>docs/man/Dockerfile.5.md
<ide> or
<ide> whitespace.
<ide> The ADD instruction copies new files, directories
<ide> or remote file URLs to the filesystem of the container at path <dest>.
<del> Mutliple <src> resources may be specified but if they are files or directories
<add> Multiple <src> resources may be specified but if they are files or directories
<ide> then they must be relative to the source directory that is being built
<ide> (the context of the build). The <dest> is the absolute path, or path relative
<ide> to `WORKDIR`, into which the source is copied inside the target container. | 1 |
Java | Java | fix checkstyle error | 0a7fdb380f78321a943f070fb89485f039265b96 | <ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/HttpHeadResponseDecoratorTests.java
<ide> import java.nio.charset.StandardCharsets;
<ide>
<ide> import io.netty.buffer.PooledByteBufAllocator;
<del>import org.junit.After;
<add>import org.junit.jupiter.api.AfterEach;
<ide> import org.junit.jupiter.api.Test;
<ide> import reactor.core.publisher.Flux;
<ide>
<ide> public class HttpHeadResponseDecoratorTests {
<ide> new HttpHeadResponseDecorator(new MockServerHttpResponse(this.bufferFactory));
<ide>
<ide>
<del> @After
<add> @AfterEach
<ide> public void tearDown() {
<ide> this.bufferFactory.checkForLeaks();
<ide> } | 1 |
Python | Python | fix typo in "make_mask" documentation | 88c2cb10958de6a063a2f42f81cf8e2eb4dca080 | <ide><path>numpy/ma/core.py
<ide> def make_mask(m, copy=False, shrink=True, dtype=MaskType):
<ide> Return `m` as a boolean mask, creating a copy if necessary or requested.
<ide> The function can accept any sequence that is convertible to integers,
<ide> or ``nomask``. Does not require that contents must be 0s and 1s, values
<del> of 0 are interepreted as False, everything else as True.
<add> of 0 are interpreted as False, everything else as True.
<ide>
<ide> Parameters
<ide> ---------- | 1 |
PHP | PHP | add test for spread operator as well | 19daf251030fdec427444bb00815dd1462b85d64 | <ide><path>tests/TestCase/Controller/ControllerFactoryTest.php
<ide> public function testInvokeInjectParametersRequiredWithPassedParameters()
<ide> */
<ide> public function testInvokeInjectPassedParametersVariadic()
<ide> {
<del> $this->container->add(stdClass::class, json_decode('{"key":"value"}'));
<ide> $request = new ServerRequest([
<ide> 'url' => 'test_plugin_three/dependencies/optionalDep',
<ide> 'params' => [
<ide> public function testInvokeInjectPassedParametersVariadic()
<ide> $this->assertNotNull($data);
<ide> $this->assertSame(['one', 'two'], $data->args);
<ide> }
<add>
<add> /**
<add> * Test that routing parameters are passed into controller action using spread operator
<add> *
<add> * @return void
<add> */
<add> public function testInvokeInjectPassedParametersSpread()
<add> {
<add> $request = new ServerRequest([
<add> 'url' => 'test_plugin_three/dependencies/optionalDep',
<add> 'params' => [
<add> 'plugin' => null,
<add> 'controller' => 'Dependencies',
<add> 'action' => 'spread',
<add> 'pass' => ['one', 'two'],
<add> ],
<add> ]);
<add> $controller = $this->factory->create($request);
<add> $result = $this->factory->invoke($controller);
<add> $data = json_decode((string)$result->getBody());
<add>
<add> $this->assertNotNull($data);
<add> $this->assertSame(['one', 'two'], $data->args);
<add> }
<ide> }
<ide><path>tests/test_app/TestApp/Controller/DependenciesController.php
<ide> public function variadic()
<ide> {
<ide> return $this->response->withStringBody(json_encode(['args' => func_get_args()]));
<ide> }
<add>
<add> public function spread(...$args)
<add> {
<add> return $this->response->withStringBody(json_encode(['args' => $args]));
<add> }
<ide> } | 2 |
Ruby | Ruby | catch all exceptions in brew | fe283686979c59dd86861d111a3211d93ccb47b2 | <ide><path>Library/Homebrew/brewkit.rb
<ide> def brew
<ide> yield self
<ide> end
<ide> end
<del> rescue Interrupt, RuntimeError
<del> if ARGV.include? '--debug'
<add> rescue => e
<add> if e.kind_of? Interrupt and ARGV.include? '--debug'
<ide> # debug mode allows the packager to intercept a failed build and
<ide> # investigate the problems
<ide> puts "Rescued build at: #{tmp}" | 1 |
PHP | PHP | add tobase method to the eloquent builder | 19958d826c6e8a83dc50dc256f6ce669424f3410 | <ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public function getQuery()
<ide> return $this->query;
<ide> }
<ide>
<add> /**
<add> * Get a base query builder instance.
<add> *
<add> * @return \Illuminate\Database\Query\Builder
<add> */
<add> public function toBase()
<add> {
<add> return $this->applyScopes()->getQuery();
<add> }
<add>
<ide> /**
<ide> * Set the underlying query builder instance.
<ide> *
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
<ide>
<ide> use Carbon\Carbon;
<ide> use Illuminate\Database\Connection;
<add>use Illuminate\Database\Query\Builder;
<ide> use Illuminate\Database\Eloquent\SoftDeletes;
<ide> use Illuminate\Database\Capsule\Manager as DB;
<ide> use Illuminate\Database\Eloquent\Model as Eloquent;
<ide> public function testSoftDeletesAreNotRetrieved()
<ide> $this->assertNull(SoftDeletesTestUser::find(1));
<ide> }
<ide>
<add> public function testSoftDeletesAreNotRetrievedFromBaseQuery()
<add> {
<add> $this->createUsers();
<add>
<add> $query = SoftDeletesTestUser::query()->toBase();
<add>
<add> $this->assertInstanceOf(Builder::class, $query);
<add> $this->assertCount(1, $query->get());
<add> }
<add>
<ide> public function testWithTrashedReturnsAllRecords()
<ide> {
<ide> $this->createUsers(); | 2 |
Text | Text | add additional cra info to todos example | a44c4f4ec9bfe6e0fe4d5bd155a3f399ab123fbe | <ide><path>examples/todos/README.md
<ide> # Redux Todos Example
<ide>
<del>This project template was built with [Create React App](https://github.com/facebookincubator/create-react-app).
<add>This project template was built with [Create React App](https://github.com/facebookincubator/create-react-app), which provides a simple way to start React projects with no build configuration needed.
<add>
<add>Projects built with Create-React-App include support for ES6 syntax, as well as several unofficial / not-yet-final forms of Javascript syntax such as Class Properties and JSX. See the list of [language features and polyfills supported by Create-React-App](https://github.com/facebookincubator/create-react-app/blob/master/packages/react-scripts/template/README.md#supported-language-features-and-polyfills) for more information.
<ide>
<ide> ## Available Scripts
<ide> | 1 |
Ruby | Ruby | prepare bottle tooling for formula revisions | 44dc21ca5d231d7860f0abe82fcb1406eee955f7 | <ide><path>Library/Homebrew/bottles.rb
<ide> def bottle_filename f, options={}
<ide> options = { :tag => bottle_tag }.merge(options)
<ide> name = f.name.downcase
<del> version = f.stable.version
<add> version = PkgVersion.new(f.stable.version, f.revision)
<ide> options[:revision] ||= f.bottle.revision.to_i if f.bottle
<ide> "#{name}-#{version}#{bottle_native_suffix(options)}"
<ide> end
<ide><path>Library/Homebrew/cmd/bottle.rb
<ide> def bottle_formula f
<ide> if ARGV.include? '--no-revision'
<ide> bottle_revision = 0
<ide> else
<del> max = f.bottle_version_map('origin/master')[f.version].max
<add> max = f.bottle_version_map('origin/master')[f.pkg_version].max
<ide> bottle_revision = max ? max + 1 : 0
<ide> end
<ide>
<ide> def bottle_formula f
<ide> HOMEBREW_CELLAR.cd do
<ide> # Use gzip, faster to compress than bzip2, faster to uncompress than bzip2
<ide> # or an uncompressed tarball (and more bandwidth friendly).
<del> safe_system 'tar', 'czf', bottle_path, "#{f.name}/#{f.version}"
<add> safe_system 'tar', 'czf', bottle_path, "#{f.name}/#{f.pkg_version}"
<ide> end
<ide>
<ide> if File.size?(bottle_path) > 1*1024*1024
<ide><path>Library/Homebrew/formula.rb
<ide> def initialize name='__UNKNOWN__', path=self.class.path(name)
<ide> unless bottle.checksum.nil? || bottle.checksum.empty?
<ide> @bottle = bottle
<ide> bottle.url ||= bottle_url(self, bottle.current_tag)
<del> bottle.version = stable.version
<add> bottle.version = PkgVersion.new(stable.version, revision)
<ide> end
<ide> end
<ide>
<ide> @active_spec = determine_active_spec
<ide> validate_attributes :url, :name, :version
<ide> @build = determine_build_options
<del> @pkg_version = PkgVersion.new(version, revision)
<add>
<add> # TODO: @pkg_version is already set for bottles, since constructing it
<add> # requires passing in the active_spec version. This should be fixed by
<add> # making the bottle an attribute of SoftwareSpec rather than a separate
<add> # spec itself.
<add> @pkg_version = PkgVersion.new(version, revision) unless active_spec == bottle
<ide>
<ide> @pin = FormulaPin.new(self)
<ide> | 3 |
Java | Java | allow plugging in custom requestexpectationmanager | 08a08725be865a620373e36ceec0820e36f1fd83 | <ide><path>spring-test/src/main/java/org/springframework/test/web/client/AbstractRequestExpectationManager.java
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<del> * Base class for {@code RequestExpectationManager} implementations.
<del> * Creates and contains expectations and stores actual requests.
<add> * Base class for {@code RequestExpectationManager} implementations responsible
<add> * for storing expectations and requests.
<ide> *
<del> * <p>Sub-classes are responsible for matching actual to expected requests and
<del> * for verifying remaining expectations at the end.
<add> * <p>Sub-classes are responsible for matching requests to expectations and
<add> * verifying there are no remaining expectations at the end.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> public abstract class AbstractRequestExpectationManager implements RequestExpect
<ide> private final List<ClientHttpRequest> requests = new LinkedList<ClientHttpRequest>();
<ide>
<ide>
<del> public AbstractRequestExpectationManager() {
<del> }
<del>
<del> public AbstractRequestExpectationManager(List<RequestExpectation> expectations) {
<del> this.expectations.addAll(expectations);
<del> }
<del>
<del>
<del> public List<RequestExpectation> getExpectations() {
<add> protected List<RequestExpectation> getExpectations() {
<ide> return this.expectations;
<ide> }
<ide>
<del> public List<ClientHttpRequest> getRequests() {
<add> protected List<ClientHttpRequest> getRequests() {
<ide> return this.requests;
<ide> }
<ide>
<ide> @Override
<ide> public ResponseActions expectRequest(RequestMatcher requestMatcher) {
<ide> Assert.state(getRequests().isEmpty(), "Cannot add more expectations after actual requests are made.");
<del> DefaultResponseActions expectation = new DefaultResponseActions(requestMatcher);
<add> RequestExpectation expectation = createExpectation(requestMatcher);
<ide> getExpectations().add(expectation);
<ide> return expectation;
<ide> }
<ide>
<add> protected RequestExpectation createExpectation(RequestMatcher requestMatcher) {
<add> return new DefaultRequestExpectation(requestMatcher);
<add> }
<add>
<ide> @Override
<ide> public ClientHttpResponse validateRequest(ClientHttpRequest request) throws IOException {
<ide> ClientHttpResponse response = validateRequestInternal(request);
<add><path>spring-test/src/main/java/org/springframework/test/web/client/DefaultRequestExpectation.java
<del><path>spring-test/src/main/java/org/springframework/test/web/client/DefaultResponseActions.java
<ide> import org.springframework.util.Assert;
<ide>
<ide> /**
<del> * Default implementation of {@code ResponseActions} that is also a composite
<del> * {@code RequestMatcher}, invoking all request matchers it contains, as well as
<del> * a {@code ResponseCreator} delegating to the response creator it contains.
<add> * Default implementation of {@code RequestExpectation} that simply delegates
<add> * to the request matchers and the response creator it contains.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> */
<del>class DefaultResponseActions implements ResponseActions, RequestExpectation {
<add>public class DefaultRequestExpectation implements RequestExpectation {
<ide>
<ide> private final List<RequestMatcher> requestMatchers = new LinkedList<RequestMatcher>();
<ide>
<ide> private ResponseCreator responseCreator;
<ide>
<ide>
<del> public DefaultResponseActions(RequestMatcher requestMatcher) {
<add> public DefaultRequestExpectation(RequestMatcher requestMatcher) {
<ide> Assert.notNull(requestMatcher, "RequestMatcher is required");
<ide> this.requestMatchers.add(requestMatcher);
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/MockRestServiceServer.java
<ide> public static MockRestServiceServer createServer(RestGatewaySupport restGateway)
<ide> public interface MockRestServiceServerBuilder {
<ide>
<ide> /**
<del> * When this option is set, requests can be executed in any order, i.e.
<del> * not matching the order in which expected requests are declared.
<add> * Allow expected requests to be executed in any order not necessarily
<add> * matching the order of declaration. This is a shortcut for:<br>
<add> * {@code builder.expectationManager(new UnorderedRequestExpectationManager)}
<ide> */
<del> MockRestServiceServerBuilder ignoreExpectOrder();
<add> MockRestServiceServerBuilder unordered();
<add>
<add> /**
<add> * Configure a custom {@code RequestExpectationManager}.
<add> * <p>By default {@link SimpleRequestExpectationManager} is used. It is
<add> * also possible to switch to {@link UnorderedRequestExpectationManager}
<add> * by setting {@link #unordered()}.
<add> */
<add> MockRestServiceServerBuilder expectationManager(RequestExpectationManager manager);
<ide>
<ide> /**
<ide> * Build the {@code MockRestServiceServer} and setting up the underlying
<ide> private static class DefaultBuilder implements MockRestServiceServerBuilder {
<ide>
<ide> private final AsyncRestTemplate asyncRestTemplate;
<ide>
<del> private boolean ignoreExpectOrder;
<add> private RequestExpectationManager expectationManager = new SimpleRequestExpectationManager();
<ide>
<ide>
<ide> public DefaultBuilder(RestTemplate restTemplate) {
<ide> public DefaultBuilder(AsyncRestTemplate asyncRestTemplate) {
<ide>
<ide>
<ide> @Override
<del> public MockRestServiceServerBuilder ignoreExpectOrder() {
<del> this.ignoreExpectOrder = true;
<add> public MockRestServiceServerBuilder unordered() {
<add> expectationManager(new UnorderedRequestExpectationManager());
<ide> return this;
<ide> }
<ide>
<add> @Override
<add> public MockRestServiceServerBuilder expectationManager(RequestExpectationManager manager) {
<add> Assert.notNull(manager, "'manager' is required.");
<add> this.expectationManager = manager;
<add> return this;
<add> }
<ide>
<ide> @Override
<ide> public MockRestServiceServer build() {
<del>
<del> MockRestServiceServer server = (this.ignoreExpectOrder ?
<del> new MockRestServiceServer(new UnorderedRequestExpectationManager()) :
<del> new MockRestServiceServer());
<del>
<add> MockRestServiceServer server = new MockRestServiceServer(this.expectationManager);
<ide> MockClientHttpRequestFactory factory = server.new MockClientHttpRequestFactory();
<ide> if (this.restTemplate != null) {
<ide> this.restTemplate.setRequestFactory(factory);
<ide> }
<ide> if (this.asyncRestTemplate != null) {
<ide> this.asyncRestTemplate.setAsyncRequestFactory(factory);
<ide> }
<del>
<ide> return server;
<ide> }
<ide> }
<ide>
<ide>
<ide> /**
<ide> * Mock ClientHttpRequestFactory that creates requests by iterating
<del> * over the list of expected {@link DefaultResponseActions}'s.
<add> * over the list of expected {@link DefaultRequestExpectation}'s.
<ide> */
<ide> private class MockClientHttpRequestFactory implements ClientHttpRequestFactory, AsyncClientHttpRequestFactory {
<ide>
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/RequestExpectation.java
<ide> package org.springframework.test.web.client;
<ide>
<ide> /**
<del> * A contract that combines {@code RequestMatcher} with {@code ResponseCreator}
<del> * to define an expected request and a response to use for it.
<add> * An extension of {@code ResponseActions} that also implements
<add> * {@code RequestMatcher} and {@code ResponseCreator}
<add> *
<add> * <p>{@code ResponseActions} is the API for defining expectations while
<add> * {@code RequestExpectation} is the internal SPI to match those expectations
<add> * to actual requests and to create responses.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> */
<del>public interface RequestExpectation extends RequestMatcher, ResponseCreator {
<add>public interface RequestExpectation extends ResponseActions, RequestMatcher, ResponseCreator {
<ide>
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/SimpleRequestExpectationManager.java
<ide> import org.springframework.http.client.ClientHttpResponse;
<ide>
<ide> /**
<del> * {@code RequestExpectationManager} that expects requests to follow the order
<del> * in which expected requests were declared.
<add> * Simple {@code RequestExpectationManager} that matches requests to expectations
<add> * sequentially, i.e. in the order of declaration of expectations.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> public ClientHttpResponse validateRequestInternal(ClientHttpRequest request) thr
<ide> if (!this.iterator.hasNext()) {
<ide> HttpMethod method = request.getMethod();
<ide> URI uri = request.getURI();
<del> throw new AssertionError("No further requests expected: HTTP " + method + " " + uri);
<add> String firstLine = "No further requests expected: HTTP " + method + " " + uri + "\n";
<add> throw new AssertionError(createErrorMessage(firstLine));
<ide> }
<ide> RequestExpectation expectation = this.iterator.next();
<ide> expectation.match(request);
<ide> public void verify() {
<ide> if (getExpectations().isEmpty() || getExpectations().size() == getRequests().size()) {
<ide> return;
<ide> }
<del> throw new AssertionError(getVerifyMessage());
<add> throw new AssertionError(createErrorMessage("Further request(s) expected\n"));
<ide> }
<ide>
<del> private String getVerifyMessage() {
<del> StringBuilder sb = new StringBuilder("Further request(s) expected\n");
<add> private String createErrorMessage(String firstLine) {
<add> StringBuilder sb = new StringBuilder(firstLine);
<ide> if (getRequests().size() > 0) {
<ide> sb.append("The following ");
<ide> }
<ide><path>spring-test/src/main/java/org/springframework/test/web/client/UnorderedRequestExpectationManager.java
<ide> import org.springframework.http.client.ClientHttpResponse;
<ide>
<ide> /**
<del> * {@code RequestExpectationManager} that tries to match actual requests to
<del> * expected requests regardless of the order in which expected requests were
<del> * declared.
<add> * {@code RequestExpectationManager} that matches requests to expectations
<add> * regardless of the order of declaration of expectations.
<ide> *
<ide> * @author Rossen Stoyanchev
<ide> * @since 4.3
<ide> public class UnorderedRequestExpectationManager extends AbstractRequestExpectati
<ide> private final List<RequestExpectation> remainingExpectations = new LinkedList<RequestExpectation>();
<ide>
<ide>
<del> public UnorderedRequestExpectationManager() {
<del> }
<del>
<del> public UnorderedRequestExpectationManager(List<RequestExpectation> expectations) {
<del> super(expectations);
<add> protected List<RequestExpectation> getRemainingExpectations() {
<add> return this.remainingExpectations;
<ide> }
<ide>
<ide>
<ide> @Override
<ide> public ClientHttpResponse validateRequestInternal(ClientHttpRequest request) throws IOException {
<ide> if (getRequests().isEmpty()) {
<del> this.remainingExpectations.addAll(getExpectations());
<add> getRemainingExpectations().addAll(getExpectations());
<ide> }
<ide> for (RequestExpectation expectation : getExpectations()) {
<ide> try {
<ide> expectation.match(request);
<del> this.remainingExpectations.remove(expectation);
<add> getRemainingExpectations().remove(expectation);
<ide> return expectation.createResponse(request);
<ide> }
<ide> catch (AssertionError error) {
<add><path>spring-test/src/test/java/org/springframework/test/web/client/SimpleRequestExpectationManagerTests.java
<del><path>spring-test/src/test/java/org/springframework/test/web/client/OrderedRequestExpectationManagerTests.java
<ide> * Unit tests for {@link AbstractRequestExpectationManager}.
<ide> * @author Rossen Stoyanchev
<ide> */
<del>public class OrderedRequestExpectationManagerTests {
<add>public class SimpleRequestExpectationManagerTests {
<ide>
<ide> private SimpleRequestExpectationManager manager = new SimpleRequestExpectationManager();
<ide>
<ide> public void validateWithUnexpectedRequest() throws Exception {
<ide> this.manager.validateRequest(request(HttpMethod.GET, "/foo"));
<ide> }
<ide> catch (AssertionError error) {
<del> assertEquals("No further requests expected: HTTP GET /foo", error.getMessage());
<add> assertEquals("No further requests expected: HTTP GET /foo\n" +
<add> "0 out of 0 were executed", error.getMessage());
<ide> }
<ide> }
<ide> | 7 |
Javascript | Javascript | fix missing controllermodel usage | fb84d84123f8b433b83c6ffa133a765a00ac380e | <ide><path>examples/jsm/webxr/XRControllerModelFactory.js
<ide> var XRControllerModelFactory = ( function () {
<ide> null,
<ide> () => {
<ide>
<del> throw new Error( `Asset ${motionController.assetUrl} missing or malformed.` );
<add> throw new Error( `Asset ${controllerModel.motionController.assetUrl} missing or malformed.` );
<ide>
<ide> } );
<ide> | 1 |
Ruby | Ruby | use parser to parse args | 78b41b07f12d503bb130170f1cde87176e8fec0c | <ide><path>Library/Homebrew/dev-cmd/man.rb
<ide> require "formula"
<ide> require "erb"
<ide> require "ostruct"
<add>require "cli_parser"
<ide>
<ide> module Homebrew
<ide> module_function
<ide> module Homebrew
<ide> TARGET_DOC_PATH = HOMEBREW_REPOSITORY/"docs"
<ide>
<ide> def man
<add> @args = Homebrew::CLI::Parser.new do
<add> switch "--fail-if-changed"
<add> switch "--link"
<add> end.parse
<add>
<ide> raise UsageError unless ARGV.named.empty?
<ide>
<del> if ARGV.flag? "--link"
<add> if @args.link?
<ide> odie "`brew man --link` is now done automatically by `brew update`."
<ide> end
<ide>
<ide> regenerate_man_pages
<ide>
<ide> if system "git", "-C", HOMEBREW_REPOSITORY, "diff", "--quiet", "docs/Manpage.md", "manpages"
<ide> puts "No changes to manpage output detected."
<del> elsif ARGV.include?("--fail-if-changed")
<add> elsif @args.fail_if_changed?
<ide> Homebrew.failed = true
<ide> end
<ide> end
<ide> def convert_man_page(markup, target)
<ide>
<ide> # Set the manpage date to the existing one if we're checking for changes.
<ide> # This avoids the only change being e.g. a new date.
<del> date = if ARGV.include?("--fail-if-changed") &&
<add> date = if @args.fail_if_changed? &&
<ide> target.extname == ".1" && target.exist?
<ide> /"(\d{1,2})" "([A-Z][a-z]+) (\d{4})" "#{organisation}" "#{manual}"/ =~ target.read
<ide> Date.parse("#{Regexp.last_match(1)} #{Regexp.last_match(2)} #{Regexp.last_match(3)}") | 1 |
Javascript | Javascript | make ngswitch compatible with controller bc module | 9b7c1d0f7ce442d4ad2ec587e66d2d335e64fa4e | <ide><path>src/ng/directive/ngSwitch.js
<ide> var NG_SWITCH = 'ng-switch';
<ide> var ngSwitchDirective = valueFn({
<ide> restrict: 'EA',
<ide> require: 'ngSwitch',
<del> controller: function ngSwitchController() {
<add> // asks for $scope to fool the BC controller module
<add> controller: ['$scope', function ngSwitchController() {
<ide> this.cases = {};
<del> },
<add> }],
<ide> link: function(scope, element, attr, ctrl) {
<ide> var watchExpr = attr.ngSwitch || attr.on,
<ide> selectedTransclude, | 1 |
Javascript | Javascript | fix comment typos and code format | 9e7fd8e810dc5f2365201e09ad3eaa6d34c52e14 | <ide><path>benchmark/common.js
<ide> function Benchmark(fn, options) {
<ide> Benchmark.prototype._parseArgs = function(argv, options) {
<ide> const cliOptions = Object.assign({}, options);
<ide>
<del> // Parse configuarion arguments
<add> // Parse configuration arguments
<ide> for (const arg of argv) {
<ide> const match = arg.match(/^(.+?)=([\s\S]*)$/);
<ide> if (!match || !match[1]) {
<ide> Benchmark.prototype._queue = function(options) {
<ide> const queue = [];
<ide> const keys = Object.keys(options);
<ide>
<del> // Perform a depth-first walk though all options to genereate a
<add> // Perform a depth-first walk though all options to generate a
<ide> // configuration list that contains all combinations.
<ide> function recursive(keyIndex, prevConfig) {
<ide> const key = keys[keyIndex];
<ide> Benchmark.prototype._run = function() {
<ide> };
<ide>
<ide> Benchmark.prototype.start = function() {
<del> if (this._started)
<add> if (this._started) {
<ide> throw new Error('Called start more than once in a single benchmark');
<del>
<add> }
<ide> this._started = true;
<ide> this._time = process.hrtime();
<ide> };
<ide> Benchmark.prototype.end = function(operations) {
<ide> };
<ide>
<ide> function formatResult(data) {
<del> // Construct confiuration string, " A=a, B=b, ..."
<add> // Construct configuration string, " A=a, B=b, ..."
<ide> let conf = '';
<ide> for (const key of Object.keys(data.conf)) {
<ide> conf += ' ' + key + '=' + JSON.stringify(data.conf[key]);
<ide><path>benchmark/compare.js
<ide> console.log('"binary", "filename", "configuration", "rate", "time"');
<ide> }
<ide> conf = conf.slice(1);
<ide>
<del> // Escape qoutes (") for correct csv formatting
<add> // Escape quotes (") for correct csv formatting
<ide> conf = conf.replace(/"/g, '""');
<ide>
<ide> console.log(`"${job.binary}", "${job.filename}", "${conf}", ` + | 2 |
Text | Text | add changelog for unreleased commits | 7bdf93b17a35a5d8fcf0ceae0bf48ed5e6b16688 | <ide><path>CHANGELOG.md
<ide> Click to see more.
<ide> </summary>
<ide>
<del>No unreleased changes yet.
<add>### All Packages
<add>
<add>* Fix an accidental extra global variable in the UMD builds. ([@gaearon](https://github.com/gaearon) in [#10935](https://github.com/facebook/react/pull/10935))
<add>
<add>### React DOM
<add>
<add>* Fix `null` showing up in a warning instead of the component stack. ([@gaearon](https://github.com/gaearon) in [#10915](https://github.com/facebook/react/pull/10915))
<add>* Fix IE11 crash in development mode. ([@leidegre](https://github.com/leidegre) in [#10921](https://github.com/facebook/react/pull/10921))
<add>* Minor bundle size improvements. ([@gaearon](https://github.com/gaearon) in [#10802](https://github.com/facebook/react/pull/10802), [#10803](https://github.com/facebook/react/pull/10803))
<ide>
<ide> </details>
<ide> | 1 |
Ruby | Ruby | use class name as xml_type_names key | 25cce680134fb97cf2e2b5be03e0043272eaa710 | <ide><path>activerecord/lib/active_record/xml_serialization.rb
<ide> def compute_value
<ide> end
<ide> end
<ide> end
<del>
<add>
<ide> class MethodAttribute < Attribute #:nodoc:
<ide> protected
<ide> def compute_type
<del> Hash::XML_TYPE_NAMES[@record.send(name).class] || :string
<add> Hash::XML_TYPE_NAMES[@record.send(name).class.name] || :string
<ide> end
<ide> end
<ide> end
<ide><path>activerecord/test/base_test.rb
<ide> def test_array_to_xml_including_has_many_association
<ide>
<ide> def test_array_to_xml_including_methods
<ide> xml = [ topics(:first), topics(:second) ].to_xml(:indent => 0, :skip_instruct => true, :methods => [ :topic_id ])
<del> assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>))
<del> assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>))
<add> assert xml.include?(%(<topic-id type="integer">#{topics(:first).topic_id}</topic-id>)), xml
<add> assert xml.include?(%(<topic-id type="integer">#{topics(:second).topic_id}</topic-id>)), xml
<ide> end
<ide>
<ide> def test_array_to_xml_including_has_one_association | 2 |
Java | Java | remove deprecated warnings | 75c88ffbeba845c49c4869400d7206ff240339cd | <ide><path>spring-context/src/test/java/org/springframework/aop/target/CommonsPoolTargetSourceTests.java
<ide> * @author Rob Harrop
<ide> * @author Chris Beams
<ide> */
<add>@SuppressWarnings("deprecation")
<ide> public class CommonsPoolTargetSourceTests {
<ide>
<ide> /** | 1 |
Java | Java | register lazy @jmslistener components | 5c9f09c2c778be2dc0def9c471ceb3061fc8472a | <ide><path>spring-jms/src/main/java/org/springframework/jms/config/JmsListenerEndpointRegistrar.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 org.springframework.beans.factory.BeanFactory;
<ide> import org.springframework.beans.factory.BeanFactoryAware;
<ide> import org.springframework.beans.factory.InitializingBean;
<add>import org.springframework.beans.factory.config.ConfigurableBeanFactory;
<ide> import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
<ide> import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory;
<ide> import org.springframework.util.Assert;
<ide> public class JmsListenerEndpointRegistrar implements BeanFactoryAware, Initializ
<ide> private final List<JmsListenerEndpointDescriptor> endpointDescriptors =
<ide> new ArrayList<JmsListenerEndpointDescriptor>();
<ide>
<add> private boolean startImmediately;
<add>
<add> private Object mutex = endpointDescriptors;
<add>
<ide>
<ide> /**
<ide> * Set the {@link JmsListenerEndpointRegistry} instance to use.
<ide> public void setContainerFactoryBeanName(String containerFactoryBeanName) {
<ide> @Override
<ide> public void setBeanFactory(BeanFactory beanFactory) {
<ide> this.beanFactory = beanFactory;
<add> if (beanFactory instanceof ConfigurableBeanFactory) {
<add> ConfigurableBeanFactory cbf = (ConfigurableBeanFactory) beanFactory;
<add> this.mutex = cbf.getSingletonMutex();
<add> }
<ide> }
<ide>
<ide>
<ide> public void afterPropertiesSet() {
<ide> }
<ide>
<ide> protected void registerAllEndpoints() {
<del> for (JmsListenerEndpointDescriptor descriptor : this.endpointDescriptors) {
<del> this.endpointRegistry.registerListenerContainer(descriptor.endpoint, resolveContainerFactory(descriptor));
<add> synchronized (this.mutex) {
<add> for (JmsListenerEndpointDescriptor descriptor : this.endpointDescriptors) {
<add> this.endpointRegistry.registerListenerContainer(
<add> descriptor.endpoint, resolveContainerFactory(descriptor));
<add> }
<add> startImmediately = true; // trigger immediate startup
<ide> }
<ide> }
<ide>
<ide> public void registerEndpoint(JmsListenerEndpoint endpoint, JmsListenerContainerF
<ide> Assert.notNull(endpoint, "Endpoint must be set");
<ide> Assert.hasText(endpoint.getId(), "Endpoint id must be set");
<ide> // Factory may be null, we defer the resolution right before actually creating the container
<del> this.endpointDescriptors.add(new JmsListenerEndpointDescriptor(endpoint, factory));
<add> JmsListenerEndpointDescriptor descriptor = new JmsListenerEndpointDescriptor(endpoint, factory);
<add> synchronized (this.mutex) {
<add> if (startImmediately) { // Register and start immediately
<add> this.endpointRegistry.registerListenerContainer(descriptor.endpoint,
<add> resolveContainerFactory(descriptor), true);
<add> }
<add> else {
<add> this.endpointDescriptors.add(descriptor);
<add> }
<add> }
<ide> }
<ide>
<ide> /**
<ide><path>spring-jms/src/main/java/org/springframework/jms/config/JmsListenerEndpointRegistry.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>
<ide> import java.util.Collection;
<ide> import java.util.Collections;
<del>import java.util.LinkedHashMap;
<ide> import java.util.Map;
<add>import java.util.concurrent.ConcurrentHashMap;
<ide> import java.util.concurrent.atomic.AtomicInteger;
<ide>
<ide> import org.apache.commons.logging.Log;
<ide> public class JmsListenerEndpointRegistry implements DisposableBean, SmartLifecyc
<ide> protected final Log logger = LogFactory.getLog(getClass());
<ide>
<ide> private final Map<String, MessageListenerContainer> listenerContainers =
<del> new LinkedHashMap<String, MessageListenerContainer>();
<add> new ConcurrentHashMap<String, MessageListenerContainer>();
<ide>
<ide> private int phase = Integer.MAX_VALUE;
<ide>
<ide> public Collection<MessageListenerContainer> getListenerContainers() {
<ide> * Create a message listener container for the given {@link JmsListenerEndpoint}.
<ide> * <p>This create the necessary infrastructure to honor that endpoint
<ide> * with regards to its configuration.
<add> * <p>The {@code startImmediately} flag determines if the container should be
<add> * started immediately.
<ide> * @param endpoint the endpoint to add
<add> * @param factory the listener factory to use
<add> * @param startImmediately start the container immediately if necessary
<ide> * @see #getListenerContainers()
<ide> * @see #getListenerContainer(String)
<ide> */
<del> public void registerListenerContainer(JmsListenerEndpoint endpoint, JmsListenerContainerFactory<?> factory) {
<add> public void registerListenerContainer(JmsListenerEndpoint endpoint, JmsListenerContainerFactory<?> factory,
<add> boolean startImmediately) {
<add>
<ide> Assert.notNull(endpoint, "Endpoint must not be null");
<ide> Assert.notNull(factory, "Factory must not be null");
<ide>
<ide> String id = endpoint.getId();
<ide> Assert.notNull(id, "Endpoint id must not be null");
<del> Assert.state(!this.listenerContainers.containsKey(id),
<del> "Another endpoint is already registered with id '" + id + "'");
<add> synchronized (this.listenerContainers) {
<add> Assert.state(!this.listenerContainers.containsKey(id),
<add> "Another endpoint is already registered with id '" + id + "'");
<add> MessageListenerContainer container = createListenerContainer(endpoint, factory);
<add> this.listenerContainers.put(id, container);
<add> if (startImmediately) {
<add> startIfNecessary(container);
<add> }
<add> }
<add> }
<ide>
<del> MessageListenerContainer container = createListenerContainer(endpoint, factory);
<del> this.listenerContainers.put(id, container);
<add> /**
<add> * Create a message listener container for the given {@link JmsListenerEndpoint}.
<add> * <p>This create the necessary infrastructure to honor that endpoint
<add> * with regards to its configuration.
<add> * @param endpoint the endpoint to add
<add> * @param factory the listener factory to use
<add> * @see #registerListenerContainer(JmsListenerEndpoint, JmsListenerContainerFactory, boolean)
<add> */
<add> public void registerListenerContainer(JmsListenerEndpoint endpoint, JmsListenerContainerFactory<?> factory) {
<add> registerListenerContainer(endpoint, factory, false);
<ide> }
<ide>
<ide> /**
<ide> public boolean isAutoStartup() {
<ide> @Override
<ide> public void start() {
<ide> for (MessageListenerContainer listenerContainer : getListenerContainers()) {
<del> if (listenerContainer.isAutoStartup()) {
<del> listenerContainer.start();
<del> }
<add> startIfNecessary(listenerContainer);
<ide> }
<ide> }
<ide>
<ide> public boolean isRunning() {
<ide> return false;
<ide> }
<ide>
<add> /**
<add> * Start the specified {@link MessageListenerContainer} if it should be started
<add> * on startup.
<add> * @see MessageListenerContainer#isAutoStartup()
<add> */
<add> private static void startIfNecessary(MessageListenerContainer listenerContainer) {
<add> if (listenerContainer.isAutoStartup()) {
<add> listenerContainer.start();
<add> }
<add> }
<add>
<ide>
<ide> private static class AggregatingCallback implements Runnable {
<ide>
<ide><path>spring-jms/src/test/java/org/springframework/jms/annotation/EnableJmsTests.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 org.springframework.context.annotation.AnnotationConfigApplicationContext;
<ide> import org.springframework.context.annotation.Bean;
<ide> import org.springframework.context.annotation.Configuration;
<add>import org.springframework.context.annotation.Lazy;
<ide> import org.springframework.context.annotation.PropertySource;
<ide> import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
<ide> import org.springframework.jms.config.JmsListenerContainerTestFactory;
<ide> import org.springframework.jms.config.JmsListenerEndpointRegistrar;
<ide> import org.springframework.jms.config.JmsListenerEndpointRegistry;
<add>import org.springframework.jms.config.MessageListenerTestContainer;
<ide> import org.springframework.jms.config.SimpleJmsListenerEndpoint;
<ide> import org.springframework.jms.listener.adapter.ListenerExecutionFailedException;
<ide> import org.springframework.jms.listener.adapter.MessageListenerAdapter;
<ide> import org.springframework.messaging.handler.annotation.support.DefaultMessageHandlerMethodFactory;
<ide> import org.springframework.messaging.handler.annotation.support.MessageHandlerMethodFactory;
<ide> import org.springframework.messaging.handler.annotation.support.MethodArgumentNotValidException;
<add>import org.springframework.stereotype.Component;
<add>
<add>import static org.junit.Assert.*;
<ide>
<ide> /**
<ide> * @author Stephane Nicoll
<ide> public void unknownFactory() {
<ide> EnableJmsSampleConfig.class, CustomBean.class);
<ide> }
<ide>
<add> @Test
<add> public void lazyComponent() {
<add> ConfigurableApplicationContext context = new AnnotationConfigApplicationContext(
<add> EnableJmsDefaultContainerFactoryConfig.class, LazyBean.class);
<add> JmsListenerContainerTestFactory defaultFactory =
<add> context.getBean("jmsListenerContainerFactory", JmsListenerContainerTestFactory.class);
<add> assertEquals(0, defaultFactory.getListenerContainers().size());
<add>
<add> context.getBean(LazyBean.class); // trigger lazy resolution
<add> assertEquals(1, defaultFactory.getListenerContainers().size());
<add> MessageListenerTestContainer container = defaultFactory.getListenerContainers().get(0);
<add> assertTrue("Should have been started " + container, container.isStarted());
<add> context.close(); // Close and stop the listeners
<add> assertTrue("Should have been stopped " + container, container.isStopped());
<add> }
<add>
<ide> @EnableJms
<ide> @Configuration
<ide> static class EnableJmsSampleConfig {
<ide> public JmsListenerContainerTestFactory defaultFactory() {
<ide> }
<ide> }
<ide>
<add> @Component
<add> @Lazy
<add> static class LazyBean {
<add>
<add> @JmsListener(destination = "myQueue")
<add> public void handle(String msg) {
<add> }
<add> }
<add>
<ide> } | 3 |
Python | Python | update interp docstring | 1d901ee669aa1999d074bb26612d8196d8b27dc9 | <ide><path>numpy/lib/function_base.py
<ide> def interp(x, xp, fp, left=None, right=None, period=None):
<ide> The x-coordinates at which to evaluate the interpolated values.
<ide>
<ide> xp : 1-D sequence of floats
<del> The x-coordinates of the data points, must be increasing if argument
<del> `period` is not specified. Otherwise, `xp` is internally sorted after
<del> normalizing the periodic boundaries with ``xp = xp % period``.
<add> The x-coordinates of the data points, must be strictly increasing if
<add> argument `period` is not specified. Otherwise, `xp` is internally sorted
<add> after normalizing the periodic boundaries with ``xp = xp % period``.
<ide>
<ide> fp : 1-D sequence of float or complex
<ide> The y-coordinates of the data points, same length as `xp`. | 1 |
Ruby | Ruby | use array.wrap not array() | 41af6d9a78446a5219a321cf638945b1608cefd8 | <ide><path>actionmailer/lib/action_mailer/base.rb
<ide> require 'mail'
<ide> require 'action_mailer/tmail_compat'
<ide> require 'action_mailer/collector'
<add>require 'active_support/core_ext/array/wrap'
<ide>
<ide> module ActionMailer #:nodoc:
<ide> # Action Mailer allows you to send email from your application using a mailer model and views.
<ide> def collect_responses_and_parts_order(headers) #:nodoc:
<ide> end
<ide>
<ide> def each_template(paths, name, &block) #:nodoc:
<del> Array(paths).each do |path|
<add> Array.wrap(paths).each do |path|
<ide> templates = lookup_context.find_all(name, path)
<ide> templates = templates.uniq_by { |t| t.formats }
<ide>
<ide><path>actionmailer/lib/action_mailer/railties/log_subscriber.rb
<add>require 'active_support/core_ext/array/wrap'
<add>
<ide> module ActionMailer
<ide> module Railties
<ide> class LogSubscriber < Rails::LogSubscriber
<ide> def deliver(event)
<del> recipients = Array(event.payload[:to]).join(', ')
<add> recipients = Array.wrap(event.payload[:to]).join(', ')
<ide> info("\nSent mail to #{recipients} (%1.fms)" % event.duration)
<ide> debug(event.payload[:mail])
<ide> end
<ide> def logger
<ide> end
<ide> end
<ide> end
<del>end
<ide>\ No newline at end of file
<add>end
<ide><path>actionpack/lib/action_view/base.rb
<ide> require 'active_support/core_ext/module/attr_internal'
<ide> require 'active_support/core_ext/module/delegation'
<ide> require 'active_support/core_ext/class/attribute'
<add>require 'active_support/core_ext/array/wrap'
<ide>
<ide> module ActionView #:nodoc:
<ide> class NonConcattingString < ActiveSupport::SafeBuffer
<ide> def self.xss_safe? #:nodoc:
<ide> end
<ide>
<ide> def self.process_view_paths(value)
<del> ActionView::PathSet.new(Array(value))
<add> ActionView::PathSet.new(Array.wrap(value))
<ide> end
<ide>
<ide> def self.for_controller(controller) | 3 |
Ruby | Ruby | pull effective arch detection into a method | e0f86a1a86ec3c42e53fa4b6d29753925aaf2e09 | <ide><path>Library/Homebrew/extend/ENV/std.rb
<ide> def set_cpu_flags flags, default=DEFAULT_FLAGS, map=Hardware::CPU.optimization_f
<ide> remove flags, %r{-mssse3}
<ide> remove flags, %r{-msse4(\.\d)?}
<ide> append flags, xarch unless xarch.empty?
<add> append flags, map.fetch(effective_arch, default)
<add> end
<ide>
<add> def effective_arch
<ide> if ARGV.build_bottle?
<del> arch = ARGV.bottle_arch || Hardware.oldest_cpu
<del> append flags, Hardware::CPU.optimization_flags.fetch(arch)
<add> ARGV.bottle_arch || Hardware.oldest_cpu
<ide> elsif Hardware::CPU.intel? && !Hardware::CPU.sse4?
<ide> # If the CPU doesn't support SSE4, we cannot trust -march=native or
<ide> # -march=<cpu family> to do the right thing because we might be running
<ide> # in a VM or on a Hackintosh.
<del> append flags, Hardware::CPU.optimization_flags.fetch(Hardware.oldest_cpu)
<add> Hardware.oldest_cpu
<ide> else
<del> append flags, map.fetch(Hardware::CPU.family, default)
<add> Hardware::CPU.family
<ide> end
<ide> end
<ide> | 1 |
Text | Text | fix method markdown highlight | 5166a1b4461b55a2d3f073198aa05d0298200d22 | <ide><path>docs/docs/reference-react-component.md
<ide> In particular, `this.props.children` is a special prop, typically defined by the
<ide>
<ide> The state contains data specific to this component that may change over time. The state is user-defined, and it should be a plain JavaScript object.
<ide>
<del>If you don't use it in `render(), it shouldn't be on the state. For example, you can put timer IDs directly on the instance.
<add>If you don't use it in `render()`, it shouldn't be on the state. For example, you can put timer IDs directly on the instance.
<ide>
<ide> See [State and Lifecycle](/react/docs/state-and-lifecycle.html) for more information about the state.
<ide> | 1 |
PHP | PHP | add dropcolumns method on the schema class | fc600c4594f0122be5f455cbeb908d1af8373ffd | <ide><path>src/Illuminate/Database/Schema/Builder.php
<ide> public function blueprintResolver(Closure $resolver)
<ide> {
<ide> $this->resolver = $resolver;
<ide> }
<add>
<add> /**
<add> * Drop columns from a table schema.
<add> *
<add> * @param string $table
<add> * @param string|array $columns
<add> * @return void
<add> */
<add> public function dropColumns($table, $columns)
<add> {
<add> $this->table($table, function (Blueprint $blueprint) use ($table, $columns) {
<add> $blueprint->dropColumn($columns);
<add> });
<add> }
<ide> }
<ide><path>src/Illuminate/Support/Facades/Schema.php
<ide> * @method static \Illuminate\Database\Schema\Builder table(string $table, \Closure $callback)
<ide> * @method static bool hasColumn(string $table, string $column)
<ide> * @method static bool hasColumns(string $table, array $columns)
<add> * @method static bool dropColumns(string $table, array $columns)
<ide> * @method static bool hasTable(string $table)
<ide> * @method static void defaultStringLength(int $length)
<ide> * @method static void registerCustomDoctrineType(string $class, string $name, string $type) | 2 |
Javascript | Javascript | fix broken tests | a65cbb8c35ed0f7b8187c139cd82b3f7af1cb246 | <ide><path>src/test/moment/locale.js
<ide> test('duration deprecations', function (assert) {
<ide> });
<ide>
<ide> test('from and fromNow with invalid date', function (assert) {
<del> assert.equal(moment(NaN).from(), 'Invalid Date', 'moment.from with invalid moment');
<del> assert.equal(moment(NaN).fromNow(), 'Invalid Date', 'moment.fromNow with invalid moment');
<add> assert.equal(moment(NaN).from(), 'Invalid date', 'moment.from with invalid moment');
<add> assert.equal(moment(NaN).fromNow(), 'Invalid date', 'moment.fromNow with invalid moment');
<ide> });
<ide>
<ide> test('from relative time future', function (assert) { | 1 |
Javascript | Javascript | add automatic retry to download script | f8545f6eb8b2041df5efffe8987a3fcb63321190 | <ide><path>scripts/release/get-build-id-for-commit.js
<ide>
<ide> const fetch = require('node-fetch');
<ide>
<add>const POLLING_INTERVAL = 5 * 1000; // 5 seconds
<add>const RETRY_TIMEOUT = 10 * 60 * 1000; // 10 minutes
<add>
<add>function wait(ms) {
<add> return new Promise(resolve => {
<add> setTimeout(() => resolve(), ms);
<add> });
<add>}
<add>
<ide> async function getBuildIdForCommit(sha) {
<del> let ciBuildId = null;
<del> const statusesResponse = await fetch(
<del> `https://api.github.com/repos/facebook/react/commits/${sha}/status`
<del> );
<add> const retryLimit = Date.now() + RETRY_TIMEOUT;
<add> retry: while (true) {
<add> const statusesResponse = await fetch(
<add> `https://api.github.com/repos/facebook/react/commits/${sha}/status`
<add> );
<ide>
<del> if (!statusesResponse.ok) {
<del> throw Error('Could not find commit for: ' + sha);
<del> }
<add> if (!statusesResponse.ok) {
<add> throw Error('Could not find commit for: ' + sha);
<add> }
<ide>
<del> const {statuses, state} = await statusesResponse.json();
<del> if (state === 'failure') {
<del> throw new Error(`Base commit is broken: ${sha}`);
<del> }
<del> for (let i = 0; i < statuses.length; i++) {
<del> const status = statuses[i];
<del> if (status.context === `ci/circleci: process_artifacts_combined`) {
<del> if (status.state === 'success') {
<del> ciBuildId = /\/facebook\/react\/([0-9]+)/.exec(status.target_url)[1];
<del> break;
<del> }
<del> if (status.state === 'pending') {
<del> throw new Error(`Build job for base commit is still pending: ${sha}`);
<add> const {statuses, state} = await statusesResponse.json();
<add> if (state === 'failure') {
<add> throw new Error(`Base commit is broken: ${sha}`);
<add> }
<add> for (let i = 0; i < statuses.length; i++) {
<add> const status = statuses[i];
<add> if (status.context === `ci/circleci: process_artifacts_combined`) {
<add> if (status.state === 'success') {
<add> return /\/facebook\/react\/([0-9]+)/.exec(status.target_url)[1];
<add> }
<add> if (status.state === 'failure') {
<add> throw new Error(`Build job for commit failed: ${sha}`);
<add> }
<add> if (Date.now() < retryLimit) {
<add> await wait(POLLING_INTERVAL);
<add> continue retry;
<add> }
<add> throw new Error('Exceeded retry limit. Build job is still pending.');
<ide> }
<ide> }
<add> throw new Error('Could not find build for commit: ' + sha);
<ide> }
<del> return ciBuildId;
<ide> }
<ide>
<ide> module.exports = getBuildIdForCommit; | 1 |
Javascript | Javascript | add version of lumin | f8648ce40b18a403fb0ae27052acce88e33ed1c7 | <ide><path>examples/js/vr/HelioWebXRPolyfill.js
<ide> * @author mvilledieu / http://github.com/mvilledieu
<ide> */
<ide>
<del>if (/(Helio)/g.test(navigator.userAgent) && "xr" in navigator) {
<del> console.log("Helio WebXR Polyfill", navigator.xr);
<add>if ( /(Helio)/g.test( navigator.userAgent ) && "xr" in navigator ) {
<ide>
<del> // WebXRManager - XR.supportSession() Polyfill - WebVR.js line 147
<add> console.log( "Helio WebXR Polyfill (Lumin 0.96.0)", navigator.xr );
<ide>
<del> if (
<del> "supportsSession" in navigator.xr === false &&
<add> // WebXRManager - XR.supportSession() Polyfill - WebVR.js line 147
<add>
<add> if (
<add> "supportsSession" in navigator.xr === false &&
<ide> "supportsSessionMode" in navigator.xr
<del> ) {
<del> navigator.xr.supportsSession = navigator.xr.supportsSessionMode;
<del> }
<add> ) {
<add>
<add> navigator.xr.supportsSession = navigator.xr.supportsSessionMode;
<add>
<add> }
<add>
<add> if ( "requestSession" in navigator.xr ) {
<add>
<add> const tempRequestSession = navigator.xr.requestSession.bind( navigator.xr );
<add>
<add> navigator.xr.requestSession = function ( sessionType ) {
<add>
<add> return new Promise( ( resolve, reject ) => {
<add>
<add> tempRequestSession( {
<add> mode: sessionType
<add> } )
<add> .then( function ( session ) {
<add>
<add> // WebXRManager - xrFrame.getPose() Polyfill - line 279
<add>
<add> const tempRequestAnimationFrame = session.requestAnimationFrame.bind(
<add> session
<add> );
<add>
<add> session.requestAnimationFrame = function ( callback ) {
<add>
<add> return tempRequestAnimationFrame( function ( time, frame ) {
<add>
<add> // WebXRManager - xrFrame.getViewerPose() Polyfill - line 279
<add> // Transforms view.viewMatrix to view.transform.inverse.matrix
<add>
<add> const tempGetViewerPose = frame.getViewerPose.bind( frame );
<add>
<add> frame.getViewerPose = function ( referenceSpace ) {
<add>
<add> const pose = tempGetViewerPose( referenceSpace );
<add>
<add> pose.views.forEach( function ( view ) {
<add>
<add> view.transform = {
<add> inverse: {
<add> matrix: view.viewMatrix
<add> }
<add> };
<add>
<add> } );
<add>
<add> return pose;
<add>
<add> };
<add>
<add> // WebXRManager - xrFrame.getPose() Polyfill - line 259
<add>
<add> frame.getPose = function ( targetRaySpace, referenceSpace ) {
<add>
<add> const inputPose = frame.getInputPose(
<add> targetRaySpace,
<add> referenceSpace
<add> );
<add>
<add> inputPose.transform = {
<add> matrix: inputPose.targetRay.transformMatrix
<add> };
<add>
<add> return inputPose;
<add>
<add> };
<add>
<add> callback( time, frame );
<add>
<add> } );
<add>
<add> };
<add>
<add> // WebXRManager - xrFrame.getPose( inputSource.targetRaySpace, referenceSpace) Polyfill - line 279
<add>
<add> const tempGetInputSources = session.getInputSources.bind( session );
<add>
<add> session.getInputSources = function () {
<add>
<add> const res = tempGetInputSources();
<add>
<add> res.forEach( xrInputSource => {
<add>
<add> Object.defineProperty( xrInputSource, "targetRaySpace", {
<add> get: function () {
<add>
<add> return xrInputSource;
<add>
<add> }
<add> } );
<add>
<add> } );
<add>
<add> return res;
<add>
<add> };
<add>
<add> // WebXRManager - xrSession.getInputSources() Polyfill Line 132 - 136
<add>
<add> session.inputSources = Object.defineProperty(
<add> session,
<add> "inputSources",
<add> {
<add> get: session.getInputSources
<add> }
<add> );
<add>
<add> // WebXRManager - xrSession.updateRenderState() Polyfill Line 129
<add>
<add> session.updateRenderState = function ( { baseLayer } ) {
<add>
<add> session.baseLayer = baseLayer;
<add>
<add> // WebXRManager - xrSession.renderState.baseLayer Polyfill Line 219
<add>
<add> session.renderState = {
<add> baseLayer: baseLayer
<add> };
<add>
<add> };
<add>
<add> // WebXRManager - xrSession.requestReferenceSpace() Polyfill Line 130
<add>
<add> const tempRequestReferenceSpace = session.requestReferenceSpace.bind(
<add> session
<add> );
<add>
<add> session.requestReferenceSpace = function () {
<add>
<add> return tempRequestReferenceSpace( {
<add> type: "stationary",
<add> subtype: "floor-level"
<add> } );
<add>
<add> };
<add>
<add> resolve( session );
<add>
<add> } )
<add> .catch( function ( error ) {
<add>
<add> return reject( error );
<add>
<add> } );
<add>
<add> } );
<ide>
<del> if ("requestSession" in navigator.xr) {
<del> const tempRequestSession = navigator.xr.requestSession.bind(navigator.xr);
<add> };
<ide>
<del> navigator.xr.requestSession = function(sessionType) {
<del> return new Promise((resolve, reject) => {
<del> tempRequestSession({
<del> mode: sessionType
<del> })
<del> .then(function(session) {
<del> // WebXRManager - xrFrame.getPose() Polyfill - line 279
<add> }
<ide>
<del> const tempRequestAnimationFrame = session.requestAnimationFrame.bind(
<del> session
<del> );
<del>
<del> session.requestAnimationFrame = function(callback) {
<del> return tempRequestAnimationFrame(function(time, frame) {
<del> // WebXRManager - xrFrame.getViewerPose() Polyfill - line 279
<del> // Transforms view.viewMatrix to view.transform.inverse.matrix
<del>
<del> const tempGetViewerPose = frame.getViewerPose.bind(frame);
<del>
<del> frame.getViewerPose = function(referenceSpace) {
<del> const pose = tempGetViewerPose(referenceSpace);
<del>
<del> pose.views.forEach(function(view) {
<del> view.transform = {
<del> inverse: {
<del> matrix: view.viewMatrix
<del> }
<del> };
<del> });
<del>
<del> return pose;
<del> };
<del>
<del> // WebXRManager - xrFrame.getPose() Polyfill - line 259
<del>
<del> frame.getPose = function(targetRaySpace, referenceSpace) {
<del> const inputPose = frame.getInputPose(
<del> targetRaySpace,
<del> referenceSpace
<del> );
<del>
<del> inputPose.transform = {
<del> matrix: inputPose.targetRay.transformMatrix
<del> };
<del>
<del> return inputPose;
<del> };
<del>
<del> callback(time, frame);
<del> });
<del> };
<del>
<del> // WebXRManager - xrFrame.getPose( inputSource.targetRaySpace, referenceSpace) Polyfill - line 279
<del>
<del> const tempGetInputSources = session.getInputSources.bind(session);
<del>
<del> session.getInputSources = function() {
<del> const res = tempGetInputSources();
<del>
<del> res.forEach(xrInputSource => {
<del> Object.defineProperty(xrInputSource, "targetRaySpace", {
<del> get: function() {
<del> return xrInputSource;
<del> }
<del> });
<del> });
<del>
<del> return res;
<del> };
<del>
<del> // WebXRManager - xrSession.getInputSources() Polyfill Line 132 - 136
<del>
<del> session.inputSources = Object.defineProperty(
<del> session,
<del> "inputSources",
<del> {
<del> get: session.getInputSources
<del> }
<del> );
<del>
<del> // WebXRManager - xrSession.updateRenderState() Polyfill Line 129
<del>
<del> session.updateRenderState = function({ baseLayer }) {
<del> session.baseLayer = baseLayer;
<del>
<del> // WebXRManager - xrSession.renderState.baseLayer Polyfill Line 219
<del>
<del> session.renderState = {
<del> baseLayer: baseLayer
<del> };
<del> };
<del>
<del> // WebXRManager - xrSession.requestReferenceSpace() Polyfill Line 130
<del>
<del> const tempRequestReferenceSpace = session.requestReferenceSpace.bind(
<del> session
<del> );
<del>
<del> session.requestReferenceSpace = function() {
<del> return tempRequestReferenceSpace({
<del> type: "stationary",
<del> subtype: "floor-level"
<del> });
<del> };
<del>
<del> resolve(session);
<del> })
<del> .catch(function(error) {
<del> return reject(error);
<del> });
<del> });
<del> };
<del> }
<ide> } | 1 |
Ruby | Ruby | use travel_to to in date_helper_test.rb | 64f3bd0a8d8709ea2c6f082838461201bffcdcfa | <ide><path>actionview/test/template/date_helper_test.rb
<ide> def test_select_year
<ide> end
<ide>
<ide> def test_select_year_with_empty_hash_value_and_no_start_year
<del> expected = +%(<select id="date_year" name="date[year]">\n)
<del> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<del> expected << "</select>\n"
<add> travel_to Time.new(2019, 1, 1) do
<add> expected = +%(<select id="date_year" name="date[year]">\n)
<add> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<add> expected << "</select>\n"
<ide>
<del> Date.stub(:current, Date.new(2018, 12, 18)) do
<ide> assert_dom_equal expected, select_year({ year: nil, month: 4, day: nil }, { end_year: 2018 })
<ide> end
<ide> end
<ide>
<ide> def test_select_year_with_empty_object_value_and_no_start_year
<del> expected = +%(<select id="date_year" name="date[year]">\n)
<del> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<del> expected << "</select>\n"
<add> travel_to Time.new(2019, 1, 1) do
<add> expected = +%(<select id="date_year" name="date[year]">\n)
<add> expected << %(<option value="2014">2014</option>\n<option value="2015">2015</option>\n<option value="2016">2016</option>\n<option value="2017">2017</option>\n<option value="2018">2018</option>\n)
<add> expected << "</select>\n"
<ide>
<del> Date.stub(:current, Date.new(2018, 12, 18)) do
<ide> assert_dom_equal expected, select_year(ComposedDate.new(nil, 4, nil), end_year: 2018)
<ide> end
<ide> end | 1 |
PHP | PHP | move bindingresolutionexception exception | df8df9eb3a3da7c9f93669cc261b9658742da207 | <ide><path>src/Illuminate/Container/BindingResolutionException.php
<ide>
<ide> use Exception;
<ide>
<add>/**
<add> * @deprecated since version 5.1. Use Illuminate\Contracts\Container\BindingResolutionException.
<add> */
<ide> class BindingResolutionException extends Exception
<ide> {
<ide> }
<ide><path>src/Illuminate/Container/Container.php
<ide> use ReflectionParameter;
<ide> use InvalidArgumentException;
<ide> use Illuminate\Contracts\Container\Container as ContainerContract;
<add>use Illuminate\Contracts\Container\BindingResolutionException as BindingResolutionContractException;
<ide>
<ide> class Container implements ArrayAccess, ContainerContract
<ide> {
<ide> protected function getExtenders($abstract)
<ide> * @param array $parameters
<ide> * @return mixed
<ide> *
<del> * @throws BindingResolutionException
<add> * @throws \Illuminate\Contracts\Container\BindingResolutionException
<ide> */
<ide> public function build($concrete, array $parameters = [])
<ide> {
<ide> public function build($concrete, array $parameters = [])
<ide> if (!$reflector->isInstantiable()) {
<ide> $message = "Target [$concrete] is not instantiable.";
<ide>
<del> throw new BindingResolutionException($message);
<add> throw new BindingResolutionContractException($message);
<ide> }
<ide>
<ide> $this->buildStack[] = $concrete;
<ide> protected function getDependencies(array $parameters, array $primitives = [])
<ide> * @param \ReflectionParameter $parameter
<ide> * @return mixed
<ide> *
<del> * @throws BindingResolutionException
<add> * @throws \Illuminate\Contracts\Container\BindingResolutionException
<ide> */
<ide> protected function resolveNonClass(ReflectionParameter $parameter)
<ide> {
<ide> protected function resolveNonClass(ReflectionParameter $parameter)
<ide>
<ide> $message = "Unresolvable dependency resolving [$parameter] in class {$parameter->getDeclaringClass()->getName()}";
<ide>
<del> throw new BindingResolutionException($message);
<add> throw new BindingResolutionContractException($message);
<ide> }
<ide>
<ide> /**
<ide> protected function resolveNonClass(ReflectionParameter $parameter)
<ide> * @param \ReflectionParameter $parameter
<ide> * @return mixed
<ide> *
<del> * @throws BindingResolutionException
<add> * @throws \Illuminate\Contracts\Container\BindingResolutionException
<ide> */
<ide> protected function resolveClass(ReflectionParameter $parameter)
<ide> {
<ide> protected function resolveClass(ReflectionParameter $parameter)
<ide> // If we can not resolve the class instance, we will check to see if the value
<ide> // is optional, and if it is we will return the optional parameter value as
<ide> // the value of the dependency, similarly to how we do this with scalars.
<del> catch (BindingResolutionException $e) {
<add> catch (BindingResolutionContractException $e) {
<ide> if ($parameter->isOptional()) {
<ide> return $parameter->getDefaultValue();
<ide> }
<ide><path>src/Illuminate/Contracts/Container/BindingResolutionException.php
<add><?php
<add>
<add>namespace Illuminate\Contracts\Container;
<add>
<add>use Illuminate\Container\BindingResolutionException as BaseException;
<add>
<add>class BindingResolutionException extends BaseException
<add>{
<add>}
<ide><path>tests/Container/ContainerTest.php
<ide> public function testCreatingBoundConcreteClassPassesParameters()
<ide>
<ide> public function testInternalClassWithDefaultParameters()
<ide> {
<del> $this->setExpectedException('Illuminate\Container\BindingResolutionException', 'Unresolvable dependency resolving [Parameter #0 [ <required> $first ]] in class ContainerMixedPrimitiveStub');
<add> $this->setExpectedException('Illuminate\Contracts\Container\BindingResolutionException', 'Unresolvable dependency resolving [Parameter #0 [ <required> $first ]] in class ContainerMixedPrimitiveStub');
<ide> $container = new Container;
<ide> $parameters = [];
<ide> $container->make('ContainerMixedPrimitiveStub', $parameters); | 4 |
Javascript | Javascript | add banner to lint-md.js by rollup.config.js | 27cf6f7629e101de59b12f1a1bd053a5e6525b59 | <ide><path>tools/lint-md.js
<ide> 'use strict';
<ide>
<add>// Don't change this file manually,
<add>// it is generated from tools/node-lint-md-cli-rollup
<add>
<ide> function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
<ide>
<ide> var stream = _interopDefault(require('stream'));
<ide> var colorName$1 = {
<ide> "bisque": [255, 228, 196],
<ide> "black": [0, 0, 0],
<ide> "blanchedalmond": [255, 235, 205],
<del> "blue": [0, 0, 255],
<del> "blueviolet": [138, 43, 226],
<del> "brown": [165, 42, 42],
<add> "blue": [0, 0, 255],
<add> "blueviolet": [138, 43, 226],
<add> "brown": [165, 42, 42],
<ide> "burlywood": [222, 184, 135],
<ide> "cadetblue": [95, 158, 160],
<ide> "chartreuse": [127, 255, 0],
<ide> var colorName$1 = {
<ide> "springgreen": [0, 255, 127],
<ide> "steelblue": [70, 130, 180],
<ide> "tan": [210, 180, 140],
<del> "teal": [0, 128, 128],
<del> "thistle": [216, 191, 216],
<del> "tomato": [255, 99, 71],
<add> "teal": [0, 128, 128],
<add> "thistle": [216, 191, 216],
<add> "tomato": [255, 99, 71],
<ide> "turquoise": [64, 224, 208],
<ide> "violet": [238, 130, 238],
<ide> "wheat": [245, 222, 179],
<ide> function stringify$6(options) {
<ide>
<ide> var remark = unified_1().use(remarkParse).use(remarkStringify).freeze();
<ide>
<del>const name$1 = "remark";
<del>const version$1 = "12.0.0";
<add>const _args = [
<add> [
<add> "remark@12.0.0",
<add> "/Users/bytedance/Documents/code/github/node/tools/node-lint-md-cli-rollup"
<add> ]
<add>];
<add>const _from = "remark@12.0.0";
<add>const _id = "remark@12.0.0";
<add>const _inBundle = false;
<add>const _integrity = "sha512-oX4lMIS0csgk8AEbzY0h2jdR0ngiCHOpwwpxjmRa5TqAkeknY+tkhjRJGZqnCmvyuWh55/0SW5WY3R3nn3PH9A==";
<add>const _location = "/remark";
<add>const _phantomChildren = {
<add>};
<add>const _requested = {
<add> type: "version",
<add> registry: true,
<add> raw: "remark@12.0.0",
<add> name: "remark",
<add> escapedName: "remark",
<add> rawSpec: "12.0.0",
<add> saveSpec: null,
<add> fetchSpec: "12.0.0"
<add>};
<add>const _requiredBy = [
<add> "/"
<add>];
<add>const _resolved = "https://registry.npmjs.org/remark/-/remark-12.0.0.tgz";
<add>const _spec = "12.0.0";
<add>const _where = "/Users/bytedance/Documents/code/github/node/tools/node-lint-md-cli-rollup";
<add>const author = {
<add> name: "Titus Wormer",
<add> email: "tituswormer@gmail.com",
<add> url: "https://wooorm.com"
<add>};
<add>const bugs = {
<add> url: "https://github.com/remarkjs/remark/issues"
<add>};
<add>const contributors = [
<add> {
<add> name: "Titus Wormer",
<add> email: "tituswormer@gmail.com",
<add> url: "https://wooorm.com"
<add> }
<add>];
<add>const dependencies = {
<add> "remark-parse": "^8.0.0",
<add> "remark-stringify": "^8.0.0",
<add> unified: "^9.0.0"
<add>};
<ide> const description = "Markdown processor powered by plugins part of the unified collective";
<del>const license = "MIT";
<add>const files = [
<add> "index.js",
<add> "types/index.d.ts"
<add>];
<add>const funding = {
<add> type: "opencollective",
<add> url: "https://opencollective.com/unified"
<add>};
<add>const homepage = "https://remark.js.org";
<ide> const keywords = [
<ide> "unified",
<ide> "remark",
<ide> const keywords = [
<ide> "compile",
<ide> "process"
<ide> ];
<del>const homepage = "https://remark.js.org";
<del>const repository = "https://github.com/remarkjs/remark/tree/master/packages/remark";
<del>const bugs = "https://github.com/remarkjs/remark/issues";
<del>const funding = {
<del> type: "opencollective",
<del> url: "https://opencollective.com/unified"
<del>};
<del>const author = "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)";
<del>const contributors = [
<del> "Titus Wormer <tituswormer@gmail.com> (https://wooorm.com)"
<del>];
<del>const files = [
<del> "index.js",
<del> "types/index.d.ts"
<del>];
<del>const types = "types/index.d.ts";
<del>const dependencies = {
<del> "remark-parse": "^8.0.0",
<del> "remark-stringify": "^8.0.0",
<del> unified: "^9.0.0"
<add>const license = "MIT";
<add>const name$1 = "remark";
<add>const repository = {
<add> type: "git",
<add> url: "https://github.com/remarkjs/remark/tree/master/packages/remark"
<ide> };
<ide> const scripts = {
<ide> test: "tape test.js"
<ide> };
<add>const types = "types/index.d.ts";
<add>const version$1 = "12.0.0";
<ide> const xo = false;
<del>const _resolved = "https://registry.npmjs.org/remark/-/remark-12.0.0.tgz";
<del>const _integrity = "sha512-oX4lMIS0csgk8AEbzY0h2jdR0ngiCHOpwwpxjmRa5TqAkeknY+tkhjRJGZqnCmvyuWh55/0SW5WY3R3nn3PH9A==";
<del>const _from = "remark@12.0.0";
<ide> var _package = {
<del> name: name$1,
<del> version: version$1,
<del> description: description,
<del> license: license,
<del> keywords: keywords,
<del> homepage: homepage,
<del> repository: repository,
<del> bugs: bugs,
<del> funding: funding,
<add> _args: _args,
<add> _from: _from,
<add> _id: _id,
<add> _inBundle: _inBundle,
<add> _integrity: _integrity,
<add> _location: _location,
<add> _phantomChildren: _phantomChildren,
<add> _requested: _requested,
<add> _requiredBy: _requiredBy,
<add> _resolved: _resolved,
<add> _spec: _spec,
<add> _where: _where,
<ide> author: author,
<add> bugs: bugs,
<ide> contributors: contributors,
<del> files: files,
<del> types: types,
<ide> dependencies: dependencies,
<add> description: description,
<add> files: files,
<add> funding: funding,
<add> homepage: homepage,
<add> keywords: keywords,
<add> license: license,
<add> name: name$1,
<add> repository: repository,
<ide> scripts: scripts,
<del> xo: xo,
<del> _resolved: _resolved,
<del> _integrity: _integrity,
<del> _from: _from
<add> types: types,
<add> version: version$1,
<add> xo: xo
<ide> };
<ide>
<ide> var _package$1 = /*#__PURE__*/Object.freeze({
<ide> __proto__: null,
<del> name: name$1,
<del> version: version$1,
<del> description: description,
<del> license: license,
<del> keywords: keywords,
<del> homepage: homepage,
<del> repository: repository,
<del> bugs: bugs,
<del> funding: funding,
<add> _args: _args,
<add> _from: _from,
<add> _id: _id,
<add> _inBundle: _inBundle,
<add> _integrity: _integrity,
<add> _location: _location,
<add> _phantomChildren: _phantomChildren,
<add> _requested: _requested,
<add> _requiredBy: _requiredBy,
<add> _resolved: _resolved,
<add> _spec: _spec,
<add> _where: _where,
<ide> author: author,
<add> bugs: bugs,
<ide> contributors: contributors,
<del> files: files,
<del> types: types,
<ide> dependencies: dependencies,
<add> description: description,
<add> files: files,
<add> funding: funding,
<add> homepage: homepage,
<add> keywords: keywords,
<add> license: license,
<add> name: name$1,
<add> repository: repository,
<ide> scripts: scripts,
<add> types: types,
<add> version: version$1,
<ide> xo: xo,
<del> _resolved: _resolved,
<del> _integrity: _integrity,
<del> _from: _from,
<ide> 'default': _package
<ide> });
<ide>
<ide><path>tools/node-lint-md-cli-rollup/rollup.config.js
<ide> module.exports = {
<ide> }),
<ide> resolve(), // tells Rollup how to find date-fns in node_modules
<ide> commonjs(), // Converts date-fns to ES modules
<add> {
<add> name: 'banner',
<add> renderChunk(code) {
<add> const banner = '// Don\'t change this file manually,\n' +
<add> '// it is generated from tools/node-lint-md-cli-rollup';
<add> return code.replace('\'use strict\';', '\'use strict\';\n\n' + banner);
<add> }
<add> },
<ide> ]
<ide> }; | 2 |
PHP | PHP | implement arrayaccess on testresponse | f5c3c60d52eccd77274e586fc4c775374e826b0f | <ide><path>src/Illuminate/Foundation/Testing/TestResponse.php
<ide>
<ide> namespace Illuminate\Foundation\Testing;
<ide>
<add>use ArrayAccess;
<ide> use Closure;
<ide> use Illuminate\Contracts\View\View;
<ide> use Illuminate\Database\Eloquent\Model;
<ide> use Illuminate\Support\Str;
<ide> use Illuminate\Support\Traits\Macroable;
<ide> use Illuminate\Support\Traits\Tappable;
<add>use LogicException;
<ide> use Symfony\Component\HttpFoundation\StreamedResponse;
<ide>
<ide> /**
<ide> * @mixin \Illuminate\Http\Response
<ide> */
<del>class TestResponse
<add>class TestResponse implements ArrayAccess
<ide> {
<ide> use Tappable, Macroable {
<ide> __call as macroCall;
<ide> public function __isset($key)
<ide> return isset($this->baseResponse->{$key});
<ide> }
<ide>
<add> /**
<add> * Determine if the given offset exists.
<add> *
<add> * @param string $offset
<add> * @return bool
<add> */
<add> public function offsetExists($offset)
<add> {
<add> return isset($this->json()[$offset]);
<add> }
<add>
<add> /**
<add> * Get the value for a given offset.
<add> *
<add> * @param string $offset
<add> * @return mixed
<add> */
<add> public function offsetGet($offset)
<add> {
<add> return $this->json()[$offset];
<add> }
<add>
<add> /**
<add> * Set the value at the given offset.
<add> *
<add> * @param string $offset
<add> * @param mixed $value
<add> * @return void
<add> */
<add> public function offsetSet($offset, $value)
<add> {
<add> throw new LogicException('Response data may not be mutated using array access.');
<add> }
<add>
<add> /**
<add> * Unset the value at the given offset.
<add> *
<add> * @param string $offset
<add> * @return void
<add> */
<add> public function offsetUnset($offset)
<add> {
<add> throw new LogicException('Response data may not be mutated using array access.');
<add> }
<add>
<ide> /**
<ide> * Handle dynamic calls into macros or pass missing methods to the base response.
<ide> * | 1 |
Python | Python | add config to enable xla in tf 2.0 | dba24007f47e9de3eb123207ca46838b32f50ad9 | <ide><path>official/resnet/keras/keras_cifar_main.py
<ide> def run(flags_obj):
<ide> Returns:
<ide> Dictionary of training and eval stats.
<ide> """
<del> config = keras_common.get_config_proto()
<ide> # TODO(tobyboyd): Remove eager flag when tf 1.0 testing ends.
<ide> # Eager is default in tf 2.0 and should not be toggled
<del> if not keras_common.is_v2_0():
<add> if keras_common.is_v2_0():
<add> keras_common.set_config_v2()
<add> else:
<add> config = keras_common.get_config_proto_v1()
<ide> if flags_obj.enable_eager:
<ide> tf.compat.v1.enable_eager_execution(config=config)
<ide> else:
<ide> sess = tf.Session(config=config)
<ide> tf.keras.backend.set_session(sess)
<del> # TODO(haoyuzhang): Set config properly in TF2.0 when the config API is ready.
<ide>
<ide> dtype = flags_core.get_tf_dtype(flags_obj)
<ide> if dtype == 'fp16':
<ide><path>official/resnet/keras/keras_common.py
<ide> def on_batch_begin(self, batch, logs=None):
<ide> 'change learning rate to %s.', self.epochs, batch, lr)
<ide>
<ide>
<del>def get_config_proto():
<add>def get_config_proto_v1():
<ide> """Return config proto according to flag settings, or None to use default."""
<ide> config = None
<ide> if FLAGS.enable_xla:
<ide> # TODO(haoyuzhang): Remove this monkey patch when XLA OOM issue is fixed.
<ide> _monkey_patch_org_assert_broadcastable()
<ide>
<del> config = tf.ConfigProto()
<add> config = tf.compat.v1.ConfigProto()
<ide> config.graph_options.optimizer_options.global_jit_level = (
<ide> tf.OptimizerOptions.ON_2)
<ide> # Disable PinToHostOptimizer in grappler when enabling XLA because it causes
<ide> def get_config_proto():
<ide> return config
<ide>
<ide>
<add>def set_config_v2():
<add> """Config eager context according to flag values using TF 2.0 API."""
<add> if FLAGS.enable_xla:
<add> # TODO(haoyuzhang): Remove this monkey patch when XLA OOM issue is fixed.
<add> _monkey_patch_org_assert_broadcastable()
<add>
<add> tf.config.optimizer.set_jit(True)
<add> # Disable PinToHostOptimizer in grappler when enabling XLA because it
<add> # causes OOM and performance regression.
<add> tf.config.optimizer.set_experimental_options(
<add> {"pin_to_host_optimization": False}
<add> )
<add>
<add>
<ide> def get_optimizer():
<ide> """Returns optimizer to use."""
<ide> # The learning_rate is overwritten at the beginning of each step by callback.
<ide><path>official/resnet/keras/keras_imagenet_main.py
<ide> def run(flags_obj):
<ide> Returns:
<ide> Dictionary of training and eval stats.
<ide> """
<del> config = keras_common.get_config_proto()
<ide> # TODO(tobyboyd): Remove eager flag when tf 1.0 testing ends.
<ide> # Eager is default in tf 2.0 and should not be toggled
<del> if not keras_common.is_v2_0():
<add> if keras_common.is_v2_0():
<add> keras_common.set_config_v2()
<add> else:
<add> config = keras_common.get_config_proto_v1()
<ide> if flags_obj.enable_eager:
<ide> tf.compat.v1.enable_eager_execution(config=config)
<ide> else:
<ide> sess = tf.Session(config=config)
<ide> tf.keras.backend.set_session(sess)
<del> # TODO(haoyuzhang): Set config properly in TF2.0 when the config API is ready.
<ide>
<ide> dtype = flags_core.get_tf_dtype(flags_obj)
<ide> if dtype == 'float16': | 3 |
PHP | PHP | remove typehint on $linkmodel argument | 5a944734b8261079bb83d1b8b6dce1b6276e3c57 | <ide><path>lib/Cake/Model/Datasource/DboSource.php
<ide> public function buildAssociationQuery(Model $Model, $queryData) {
<ide> * String representing a query.
<ide> * True, when $external is false and association $type is 'hasOne' or 'belongsTo'.
<ide> */
<del> public function generateAssociationQuery(Model $Model, Model $LinkModel, $type, $association, $assocData, &$queryData, $external) {
<add> public function generateAssociationQuery(Model $Model, $LinkModel, $type, $association, $assocData, &$queryData, $external) {
<ide> $assocData = $this->_scrubQueryData($assocData);
<ide>
<ide> if ($external && !empty($assocData['finderQuery'])) { | 1 |
Ruby | Ruby | show invoked generators options on meta generators | c03585aa8da175888ad0893ef29d887f87fb749b | <ide><path>railties/lib/generators/base.rb
<ide> def self.source_root
<ide> #
<ide> def self.desc(description=nil)
<ide> return super if description
<del> usage = File.join(source_root, "..", "USAGE")
<add> usage = File.expand_path(File.join(source_root, "..", "USAGE"))
<ide>
<ide> @desc ||= if File.exist?(usage)
<ide> File.read(usage)
<ide> def self.namespace(name=nil)
<ide> #
<ide> # ruby script/generate controller Account --no-test-framework
<ide> #
<del> # ==== Another example
<del> #
<del> # Another example of invoke_for hooks is fixture replacement tools.
<del> # Consider this TestUnit model generator:
<del> #
<del> # class ModelGenerator < TestUnit::Generators::Base
<del> # hook_for :fixture_replacement, :aliases => "-r"
<del> # end
<del> #
<del> # When invoked as:
<del> #
<del> # ruby script/generate test_unit:model Account -r fixjour
<del> #
<del> # It will lookup for any of these generators:
<del> #
<del> # "test_unit:generators:fixjour", "fixjour:generators:model", "fixjour"
<del> #
<del> # Fixjour can choose any of these hooks to implement. For example, if
<del> # Fixjour has different output for rspec and test_unit, it will likely
<del> # implement the first hook. However if the output is the same for both,
<del> # it will implement the second or the third depending on the number of
<del> # generators it has.
<del> #
<ide> def self.hook_for(*names)
<ide> default_options = names.extract_options!
<ide> verbose = default_options.key?(:verbose) ? default_options[:verbose] : :blue
<add> invocations.concat(names)
<ide>
<ide> names.each do |name|
<ide> options = default_options.dup
<ide> def invoke_for_#{name}
<ide> def self.invoke_if(*names)
<ide> default_options = names.extract_options!
<ide> verbose = default_options.key?(:verbose) ? default_options[:verbose] : :blue
<add> invocations.concat(names)
<ide>
<ide> names.each do |name|
<ide> conditional_class_option name, default_options.dup
<ide> def self.generator_name
<ide> end
<ide> end
<ide>
<add> # Stores invocations for this class merging with superclass values.
<add> #
<add> def self.invocations #:nodoc:
<add> @invocations ||= from_superclass(:invocations, [])
<add> end
<add>
<ide> # Creates a conditional class option with type boolean, default value
<ide> # lookup and default description.
<ide> #
<ide> def self.conditional_class_option(name, options={})
<ide> class_option name, options.merge!(:type => :boolean, :default => DEFAULTS[name] || false)
<ide> end
<ide>
<add> # Overwrite class options help to allow invoked generators options to be
<add> # shown when invoking a generator. Only first level options and options
<add> # that belongs to the default group are shown.
<add> #
<add> def self.class_options_help(shell, ungrouped_name=nil, extra_group=nil)
<add> klass_options = Thor::CoreExt::OrderedHash.new
<add>
<add> invocations.each do |name|
<add> option = class_options[name]
<add>
<add> klass_name = option.type == :boolean ? name : option.default
<add> next unless klass_name
<add>
<add> klass = Rails::Generators.find_by_namespace(klass_name, base_name, generator_name)
<add> next unless klass
<add>
<add> human_name = klass_name.to_s.classify
<add>
<add> klass_options[human_name] ||= []
<add> klass_options[human_name] += klass.class_options.values.select do |option|
<add> class_options[option.human_name.to_sym].nil? && option.group.nil?
<add> end
<add> end
<add>
<add> klass_options.merge!(extra_group) if extra_group
<add> super(shell, ungrouped_name, klass_options)
<add> end
<add>
<ide> # Small macro to add ruby as an option to the generator with proper
<ide> # default value plus an instance helper method called shebang.
<ide> #
<ide> def self.add_shebang_option!
<ide> class_option :ruby, :type => :string, :aliases => "-r", :default => default,
<ide> :desc => "Path to the Ruby binary of your choice", :banner => "PATH"
<ide>
<del> no_tasks do
<del> define_method :shebang do
<del> "#!#{options[:ruby] || "/usr/bin/env ruby"}"
<add> class_eval <<-METHOD, __FILE__, __LINE__
<add> protected
<add> def shebang
<add> "#!\#{options[:ruby] || "/usr/bin/env ruby"}"
<ide> end
<del> end
<add> METHOD
<ide> end
<ide>
<ide> end
<ide><path>railties/lib/generators/named_base.rb
<ide> def check_class_collision(options={})
<ide> # superclass. The from_superclass method used below is from Thor.
<ide> #
<ide> def class_collisions #:nodoc:
<del> @class_collisions ||= from_superclass(:class_collisions, nil) rescue nil
<add> @class_collisions ||= from_superclass(:class_collisions, nil)
<ide> end
<ide> end
<ide>
<ide><path>railties/test/generators/controller_generator_test.rb
<ide>
<ide> class ControllerGeneratorTest < GeneratorsTestCase
<ide>
<add> def test_help_does_not_show_invoked_generators_options_if_they_already_exist
<add> content = run_generator ["--help"]
<add> assert_no_match /Helper options:/, content
<add> end
<add>
<ide> def test_controller_skeleton_is_created
<ide> run_generator
<ide> assert_file "app/controllers/account_controller.rb", /class AccountController < ApplicationController/
<ide><path>railties/test/generators/model_generator_test.rb
<ide>
<ide> class ModelGeneratorTest < GeneratorsTestCase
<ide>
<add> def test_help_shows_invoked_generators_options
<add> content = run_generator ["--help"]
<add> assert_match /ActiveRecord options:/, content
<add> assert_match /TestUnit options:/, content
<add> end
<add>
<ide> def test_invokes_default_orm
<ide> run_generator
<ide> assert_file "app/models/account.rb", /class Account < ActiveRecord::Base/ | 4 |
PHP | PHP | fix pivot when is force filled | a0673f2ac215066c80a4945c3c6510ab6aedb57a | <ide><path>src/Illuminate/Database/Eloquent/Relations/Pivot.php
<ide> public function __construct(Model $parent, $attributes, $table, $exists = false)
<ide> // The pivot model is a "dynamic" model since we will set the tables dynamically
<ide> // for the instance. This allows it work for any intermediate tables for the
<ide> // many to many relationship that are defined by this developer's classes.
<del> $this->forceFill($attributes);
<del>
<del> $this->syncOriginal();
<del>
<ide> $this->setTable($table);
<ide>
<ide> $this->setConnection($parent->getConnectionName());
<ide>
<add> $this->forceFill($attributes);
<add>
<add> $this->syncOriginal();
<add>
<ide> // We store off the parent instance so we will access the timestamp column names
<ide> // for the model, since the pivot model timestamps aren't easily configurable
<ide> // from the developer's point of view. We can use the parents to get these.
<ide><path>tests/Database/DatabaseEloquentPivotTest.php
<ide> public function testPropertiesAreSetCorrectly()
<ide> {
<ide> $parent = m::mock('Illuminate\Database\Eloquent\Model[getConnectionName]');
<ide> $parent->shouldReceive('getConnectionName')->once()->andReturn('connection');
<del> $pivot = new Pivot($parent, ['foo' => 'bar'], 'table', true);
<add> $pivot = new Pivot($parent, ['foo' => 'bar', 'created_at' => '2015-09-12'], 'table', true);
<ide>
<del> $this->assertEquals(['foo' => 'bar'], $pivot->getAttributes());
<add> $this->assertEquals(['foo' => 'bar', 'created_at' => '2015-09-12'], $pivot->getAttributes());
<ide> $this->assertEquals('connection', $pivot->getConnectionName());
<ide> $this->assertEquals('table', $pivot->getTable());
<ide> $this->assertTrue($pivot->exists); | 2 |
Python | Python | add test for issue-1959 | 7ba4111554cd8637763947d21decbab25bd95369 | <ide><path>spacy/tests/regression/test_issue1959.py
<add># coding: utf8
<add>from __future__ import unicode_literals
<add>import pytest
<add>
<add>from ..util import load_test_model
<add>
<add>
<add>@pytest.mark.models('en')
<add>def test_issue1959():
<add> texts = ['Apple is looking at buying U.K. startup for $1 billion.']
<add> nlp = load_test_model('en_core_web_sm')
<add> nlp.add_pipe(clean_component, name='cleaner', after='ner')
<add> doc = nlp(texts[0])
<add> doc_pipe = [doc_pipe for doc_pipe in nlp.pipe(texts)]
<add> assert doc == doc_pipe[0]
<add>
<add>
<add>def clean_component(doc):
<add> """ Clean up text. Make lowercase and remove punctuation and stopwords """
<add> # Remove punctuation, symbols (#) and stopwords
<add> doc = [tok.text.lower() for tok in doc if (not tok.is_stop
<add> and tok.pos_ != 'PUNCT' and
<add> tok.pos_ != 'SYM')]
<add> doc = ' '.join(doc)
<add> return doc | 1 |
Python | Python | adjust default attrs for textcat configs | 865691d169c3be413007f0d7324e03a7aac3b3cb | <ide><path>spacy/pipeline/textcat.py
<ide> [model.tok2vec.embed]
<ide> @architectures = "spacy.MultiHashEmbed.v2"
<ide> width = 64
<del>rows = [2000, 2000, 1000, 1000, 1000, 1000]
<del>attrs = ["ORTH", "LOWER", "PREFIX", "SUFFIX", "SHAPE", "ID"]
<add>rows = [2000, 2000, 500, 1000, 500]
<add>attrs = ["NORM", "LOWER", "PREFIX", "SUFFIX", "SHAPE"]
<ide> include_static_vectors = false
<ide>
<ide> [model.tok2vec.encode]
<ide><path>spacy/pipeline/textcat_multilabel.py
<ide> [model.tok2vec.embed]
<ide> @architectures = "spacy.MultiHashEmbed.v2"
<ide> width = 64
<del>rows = [2000, 2000, 1000, 1000, 1000, 1000]
<del>attrs = ["ORTH", "LOWER", "PREFIX", "SUFFIX", "SHAPE", "ID"]
<add>rows = [2000, 2000, 500, 1000, 500]
<add>attrs = ["NORM", "LOWER", "PREFIX", "SUFFIX", "SHAPE"]
<ide> include_static_vectors = false
<ide>
<ide> [model.tok2vec.encode] | 2 |
Ruby | Ruby | check dependencies for a compatible c++ stdlib | 7c3d6ea81c23d4c2c9daf4c9d97e75e6ac6320a5 | <ide><path>Library/Homebrew/build.rb
<ide> end
<ide>
<ide> require 'global'
<add>require 'cxxstdlib'
<ide> require 'debrew' if ARGV.debug?
<ide>
<ide> def main
<ide> def install
<ide> end
<ide> end
<ide>
<add> # We only support libstdc++ right now
<add> stdlib_in_use = CxxStdlib.new(:libstdcxx, ENV.compiler)
<add>
<add> # This is a bad place for this check, but we don't have access to
<add> # compiler selection within the formula installer, only inside the
<add> # build instance.
<add> stdlib_in_use.check_dependencies(f, deps)
<add>
<ide> f.brew do
<ide> if ARGV.flag? '--git'
<ide> system "git init"
<ide> def install
<ide>
<ide> begin
<ide> f.install
<del> Tab.create(f, ENV.compiler,
<add> Tab.create(f, :libstdcxx, ENV.compiler,
<ide> Options.coerce(ARGV.options_only)).write
<ide> rescue Exception => e
<ide> if ARGV.debug?
<ide><path>Library/Homebrew/exceptions.rb
<ide> def initialize formula, reqs
<ide> end
<ide> end
<ide>
<add>class IncompatibleCxxStdlibs < Homebrew::InstallationError
<add> def initialize(f, dep, wrong, right)
<add> super f, <<-EOS.undent
<add> #{f} dependency #{dep} was built with the following
<add> C++ standard library: #{wrong.type_string} (from #{wrong.compiler})
<add>
<add> This is incompatible with the standard library being used
<add> to build #{f}: #{right.type_string} (from #{right.compiler})
<add>
<add> Please reinstall #{dep} using a compatible compiler.
<add> hint: Check https://github.com/mxcl/homebrew/wiki/C++-Standard-Libraries
<add> EOS
<add> end
<add>end
<add>
<ide> class FormulaConflictError < Homebrew::InstallationError
<ide> attr_reader :f, :conflicts
<ide>
<ide><path>Library/Homebrew/formula_installer.rb
<ide> # encoding: UTF-8
<ide>
<add>require 'cxxstdlib'
<ide> require 'exceptions'
<ide> require 'formula'
<ide> require 'keg'
<ide> def install
<ide> raise "Unrecognized architecture for --bottle-arch: #{arch}"
<ide> end
<ide>
<add> if pour_bottle? true
<add> # TODO We currently only support building with libstdc++ as
<add> # the default case, and all Apple libstdc++s are compatible, so
<add> # this default is sensible.
<add> # In the future we need to actually provide a way to read this from
<add> # the bottle, or update the default should that change
<add> # at some other point.
<add> stdlib_in_use = CxxStdlib.new(:libstdcxx, :clang)
<add> stdlib_in_use.check_dependencies(f, f.deps)
<add> end
<add>
<ide> oh1 "Installing #{Tty.green}#{f}#{Tty.reset}" if show_header
<ide>
<ide> @@attempted << f | 3 |
Java | Java | remove synchronized block around pathpatternparser | 8db4b2f7ed4b3a8efb8eadf630ae8693048a641b | <ide><path>spring-webflux/src/main/java/org/springframework/web/reactive/function/server/RequestPredicates.java
<ide> public static RequestPredicate path(String pattern) {
<ide> */
<ide> public static Function<String, RequestPredicate> pathPredicates(PathPatternParser patternParser) {
<ide> Assert.notNull(patternParser, "'patternParser' must not be null");
<del> return pattern -> {
<del> synchronized (patternParser) {
<del> return new PathPatternPredicate(patternParser.parse(pattern));
<del> }
<del> };
<add> return pattern -> new PathPatternPredicate(patternParser.parse(pattern));
<ide> }
<ide>
<ide> /** | 1 |
PHP | PHP | unify exception formatting | ba0fa733243fd9b5abac67e40c9a1f7ba2ca0391 | <ide><path>src/Illuminate/Database/Connectors/ConnectionFactory.php
<ide> protected function createConnection($driver, $connection, $database, $prefix = '
<ide> return new SqlServerConnection($connection, $database, $prefix, $config);
<ide> }
<ide>
<del> throw new InvalidArgumentException("Unsupported driver [$driver]");
<add> throw new InvalidArgumentException("Unsupported driver [{$driver}]");
<ide> }
<ide> }
<ide><path>src/Illuminate/Database/DatabaseManager.php
<ide> protected function configuration($name)
<ide> $connections = $this->app['config']['database.connections'];
<ide>
<ide> if (is_null($config = Arr::get($connections, $name))) {
<del> throw new InvalidArgumentException("Database [$name] not configured.");
<add> throw new InvalidArgumentException("Database [{$name}] not configured.");
<ide> }
<ide>
<ide> return $config;
<ide><path>src/Illuminate/Database/Eloquent/Builder.php
<ide> public static function __callStatic($method, $parameters)
<ide> }
<ide>
<ide> if (! isset(static::$macros[$method])) {
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide>
<ide> if (static::$macros[$method] instanceof Closure) {
<ide><path>src/Illuminate/Database/Eloquent/Concerns/HasAttributes.php
<ide> protected function getRelationshipFromMethod($method)
<ide> $relation = $this->$method();
<ide>
<ide> if (! $relation instanceof Relation) {
<del> throw new LogicException(get_class($this).'::'.$method.' must return a relationship instance.');
<add> throw new LogicException(sprintf(
<add> '%s::%s must return a relationship instance.', static::class, $method
<add> ));
<ide> }
<ide>
<ide> return tap($relation->getResults(), function ($results) use ($method) {
<ide><path>src/Illuminate/Database/Query/Builder.php
<ide> public function __call($method, $parameters)
<ide> return $this->dynamicWhere($method, $parameters);
<ide> }
<ide>
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/Database/Query/JsonExpression.php
<ide> protected function getJsonBindingParameter($value)
<ide> return '?';
<ide> }
<ide>
<del> throw new InvalidArgumentException('JSON value is of illegal type: '.$type);
<add> throw new InvalidArgumentException("JSON value is of illegal type: {$type}");
<ide> }
<ide> }
<ide><path>src/Illuminate/Filesystem/FilesystemAdapter.php
<ide> protected function parseVisibility($visibility)
<ide> return AdapterInterface::VISIBILITY_PRIVATE;
<ide> }
<ide>
<del> throw new InvalidArgumentException('Unknown visibility: '.$visibility);
<add> throw new InvalidArgumentException("Unknown visibility: {$visibility}");
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Http/RedirectResponse.php
<ide> public function __call($method, $parameters)
<ide> return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
<ide> }
<ide>
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/Mail/Mailable.php
<ide> public function __call($method, $parameters)
<ide> return $this->with(Str::snake(substr($method, 4)), $parameters[0]);
<ide> }
<ide>
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/Notifications/Channels/BroadcastChannel.php
<ide> protected function getData($notifiable, Notification $notification)
<ide> return $notification->toArray($notifiable);
<ide> }
<ide>
<del> throw new RuntimeException(
<del> 'Notification is missing toArray method.'
<del> );
<add> throw new RuntimeException('Notification is missing toArray method.');
<ide> }
<ide> }
<ide><path>src/Illuminate/Notifications/Channels/DatabaseChannel.php
<ide> protected function getData($notifiable, Notification $notification)
<ide> return $notification->toArray($notifiable);
<ide> }
<ide>
<del> throw new RuntimeException(
<del> 'Notification is missing toDatabase / toArray method.'
<del> );
<add> throw new RuntimeException('Notification is missing toDatabase / toArray method.');
<ide> }
<ide> }
<ide><path>src/Illuminate/Redis/RedisManager.php
<ide> public function resolve($name = null)
<ide> return $this->resolveCluster($name);
<ide> }
<ide>
<del> throw new InvalidArgumentException(
<del> "Redis connection [{$name}] not configured."
<del> );
<add> throw new InvalidArgumentException("Redis connection [{$name}] not configured.");
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/Controller.php
<ide> public function callAction($method, $parameters)
<ide> */
<ide> public function __call($method, $parameters)
<ide> {
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/Routing/Middleware/ThrottleRequests.php
<ide> protected function resolveRequestSignature($request)
<ide> return sha1($route->getDomain().'|'.$request->ip());
<ide> }
<ide>
<del> throw new RuntimeException(
<del> 'Unable to generate the request signature. Route unavailable.'
<del> );
<add> throw new RuntimeException('Unable to generate the request signature. Route unavailable.');
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/Routing/RouteRegistrar.php
<ide> public function __call($method, $parameters)
<ide> return $this->attribute($method, $parameters[0]);
<ide> }
<ide>
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/Support/Manager.php
<ide> public function driver($driver = null)
<ide> $driver = $driver ?: $this->getDefaultDriver();
<ide>
<ide> if (is_null($driver)) {
<del> throw new InvalidArgumentException('Unable to resolve NULL driver for ['.get_class($this).'].');
<add> throw new InvalidArgumentException(sprintf(
<add> 'Unable to resolve NULL driver for [%s].', static::class
<add> ));
<ide> }
<ide>
<ide> // If the given driver has not been created before, we will create the instances
<ide><path>src/Illuminate/Support/Traits/Macroable.php
<ide> public static function hasMacro($name)
<ide> public static function __callStatic($method, $parameters)
<ide> {
<ide> if (! static::hasMacro($method)) {
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide>
<ide> if (static::$macros[$method] instanceof Closure) {
<ide> public static function __callStatic($method, $parameters)
<ide> public function __call($method, $parameters)
<ide> {
<ide> if (! static::hasMacro($method)) {
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide>
<ide> $macro = static::$macros[$method];
<ide><path>src/Illuminate/Validation/Validator.php
<ide> public function __call($method, $parameters)
<ide> return $this->callExtension($rule, $parameters);
<ide> }
<ide>
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide> }
<ide><path>src/Illuminate/View/Engines/EngineResolver.php
<ide> public function resolve($engine)
<ide> return $this->resolved[$engine] = call_user_func($this->resolvers[$engine]);
<ide> }
<ide>
<del> throw new InvalidArgumentException("Engine $engine not found.");
<add> throw new InvalidArgumentException("Engine [{$engine}] not found.");
<ide> }
<ide> }
<ide><path>src/Illuminate/View/Factory.php
<ide> public function exists($view)
<ide> public function getEngineFromPath($path)
<ide> {
<ide> if (! $extension = $this->getExtension($path)) {
<del> throw new InvalidArgumentException("Unrecognized extension in file: $path");
<add> throw new InvalidArgumentException("Unrecognized extension in file: {$path}");
<ide> }
<ide>
<ide> $engine = $this->extensions[$extension];
<ide><path>src/Illuminate/View/FileViewFinder.php
<ide> protected function parseNamespaceSegments($name)
<ide> $segments = explode(static::HINT_PATH_DELIMITER, $name);
<ide>
<ide> if (count($segments) != 2) {
<del> throw new InvalidArgumentException("View [$name] has an invalid name.");
<add> throw new InvalidArgumentException("View [{$name}] has an invalid name.");
<ide> }
<ide>
<ide> if (! isset($this->hints[$segments[0]])) {
<ide> protected function findInPaths($name, $paths)
<ide> }
<ide> }
<ide>
<del> throw new InvalidArgumentException("View [$name] not found.");
<add> throw new InvalidArgumentException("View [{$name}] not found.");
<ide> }
<ide>
<ide> /**
<ide><path>src/Illuminate/View/View.php
<ide> public function __unset($key)
<ide> public function __call($method, $parameters)
<ide> {
<ide> if (! Str::startsWith($method, 'with')) {
<del> $class = static::class;
<del>
<del> throw new BadMethodCallException("Method {$class}::{$method} does not exist.");
<add> throw new BadMethodCallException(sprintf(
<add> 'Method %s::%s does not exist.', static::class, $method
<add> ));
<ide> }
<ide>
<ide> return $this->with(Str::camel(substr($method, 4)), $parameters[0]); | 22 |
Javascript | Javascript | fix small typo in code example | 52c1498e25992f93ada72ea0621755ff2242b97f | <ide><path>src/ng/directive/input.js
<ide> function checkboxInputType(scope, element, attr, ctrl) {
<ide> <tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<ide> <tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<ide> <tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<del> <tt>myForm.userName.$error = {{myForm.lastName.$error}}</tt><br>
<add> <tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<ide> <tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<ide> <tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<ide> <tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br> | 1 |
Ruby | Ruby | return the installed path(s) from install | 435518252910b9839033cab4da1c4138d1a8bd99 | <ide><path>Library/Homebrew/pathname+yeast.rb
<ide> def rename newname
<ide>
<ide> def install src
<ide> if src.is_a? Array
<del> src.each {|src| install src }
<add> src.collect {|src| install src }
<ide> elsif File.exist? src
<ide> mkpath
<ide> if File.symlink? src
<ide> # we use the BSD mv command because FileUtils copies the target and
<ide> # not the link! I'm beginning to wish I'd used Python quite honestly!
<del> `mv #{src} #{to_s}`
<add> raise unless Kernel.system 'mv', src, to_s and $? == 0
<ide> else
<ide> # we mv when possible as it is faster and you should only be using
<ide> # this function when installing from the temporary build directory
<ide> FileUtils.mv src, to_s
<ide> end
<add> return self+src
<ide> end
<ide> end
<ide> | 1 |
Javascript | Javascript | fix template compiler | 8cb2c6b27e68c30f1528a55970a943eee1a6a9f2 | <ide><path>ember-cli-build.js
<ide> module.exports = function() {
<ide> 'container/lib/**',
<ide> 'ember-environment/index.js',
<ide> 'ember-environment/lib/**',
<add> 'ember-browser-environment/index.js',
<add> 'ember-browser-environment/lib/**',
<ide> 'ember-glimmer/index.js',
<ide> 'ember-glimmer/lib/**',
<ide> 'ember-metal/index.js',
<ide> module.exports = function() {
<ide> }),
<ide> rollupPackage(packagesES, 'container'),
<ide> rollupPackage(packagesES, 'ember-environment'),
<add> rollupPackage(packagesES, 'ember-browser-environment'),
<ide> rollupPackage(packagesES, 'ember-glimmer'),
<ide> rollupPackage(packagesES, 'ember-metal'),
<ide> rollupPackage(packagesES, 'ember-utils'),
<ide> module.exports = function() {
<ide> 'ember/version.js',
<ide> 'ember-debug/**',
<ide> 'ember-environment.js',
<add> 'ember-browser-environment.js',
<ide> 'ember-template-compiler/**',
<ide> 'ember-utils.js',
<ide> ], | 1 |
Ruby | Ruby | reduce calls to hash#[] | cf00da66924de0a4435391be70efe04ccfb12787 | <ide><path>lib/arel/engines/sql/christener.rb
<ide> def initialize
<ide> def name_for(relation)
<ide> table = relation.table
<ide> name = table.table_alias || table.name
<del> @names[name] ||= []
<add> list = @names[name] ||= []
<ide>
<del> @names[name] << table unless @names[name].include? table
<add> list << table unless list.include? table
<ide>
<del> idx = @names[name].index table
<add> idx = list.index table
<ide> name + (idx == 0 ? '' : "_#{idx + 1}")
<ide> end
<ide> end | 1 |
Javascript | Javascript | fix test-http-conn-reset.js on osx | 3a349726720b609fb19f06e0a870f6f400e19a6e | <ide><path>lib/http.js
<ide> ClientRequest.prototype.abort = function() {
<ide> }
<ide> };
<ide>
<add>
<add>function createHangUpError() {
<add> var error = new Error('socket hang up');
<add> error.code = 'ECONNRESET';
<add> return error;
<add>}
<add>
<add>
<ide> ClientRequest.prototype.onSocket = function(socket) {
<ide> var req = this;
<ide> process.nextTick(function () {
<ide> ClientRequest.prototype.onSocket = function(socket) {
<ide> if (!req.res) {
<ide> // If we don't have a response then we know that the socket
<ide> // ended prematurely and we need to emit an error on the request.
<del> req.emit('error', new Error("Request ended prematurely."));
<add> req.emit('error', createHangUpError());
<ide> req._hadError = true;
<ide> }
<ide> parser.finish();
<ide> ClientRequest.prototype.onSocket = function(socket) {
<ide> // This socket error fired before we started to
<ide> // receive a response. The error needs to
<ide> // fire on the request.
<del> var error = new Error('socket hang up');
<del> error.code = 'ECONNRESET';
<del> req.emit('error', error);
<add> req.emit('error', createHangUpError());
<ide> }
<ide> }
<ide> socket.on('close', closeListener);
<ide><path>test/simple/test-http-conn-reset.js
<ide> function onListen() {
<ide> assert.ok(false, 'this should never run');
<ide> });
<ide> req.on('error', function(err) {
<del> assert.equal(err.message, 'socket hang up');
<ide> assert.equal(err.code, 'ECONNRESET');
<add> assert.equal(err.message, 'socket hang up');
<ide> caughtError = true;
<ide> });
<ide> req.end(); | 2 |
Ruby | Ruby | remove unused variable step#@time | 4e927d9ce855cbd74b2f893237bb2b6489f88da8 | <ide><path>Library/Homebrew/dev-cmd/test-bot.rb
<ide> def resolve_test_tap
<ide> # Wraps command invocations. Instantiated by Test#test.
<ide> # Handles logging and pretty-printing.
<ide> class Step
<del> attr_reader :command, :name, :status, :output, :time
<add> attr_reader :command, :name, :status, :output
<ide>
<ide> # Instantiates a Step object.
<ide> # @param test [Test] The parent Test object
<ide> def initialize(test, command, options = {})
<ide> @name = command[1].delete("-")
<ide> @status = :running
<ide> @repository = options[:repository] || HOMEBREW_REPOSITORY
<del> @time = 0
<ide> end
<ide>
<ide> def log_file_path | 1 |
Text | Text | update line 1 | f194ddb7fc645ede9a18ab47f3ff7f121c03d221 | <ide><path>guide/english/computer-hardware/cpu/index.md
<ide> title: CPU
<ide> ---
<ide>
<ide> # CPU
<del>**The Central Processing Unit (CPU)** serves as the "brain" of a computer, allowing it to perform essential computational tasks.
<add>**The Central Processing Unit (CPU)** often refered to as the "brain" of a computer, performs essential computational tasks.
<ide>
<ide> CPUs are integrated circuits, which are complex circuits embedded on a single chip. They include registers, which store single values, and input/output pins. These pins allow them to talk to the rest of the computer. Due to the continued advancement of CPU technology, many computers today utilize a multi-processing unit. Multi-processors are single chips that contain two or more CPUs or "cores" that allow for increased processing capabilities.
<ide> | 1 |
Javascript | Javascript | use compilefunction over module.wrap | d345b0dc128d99afc8476f58ed5546b43d52d30a | <ide><path>lib/internal/modules/cjs/loader.js
<ide> Module.prototype._compile = function(content, filename) {
<ide>
<ide> content = stripShebang(content);
<ide>
<del> // create wrapper function
<del> var wrapper = Module.wrap(content);
<del>
<del> var compiledWrapper = vm.runInThisContext(wrapper, {
<del> filename: filename,
<del> lineOffset: 0,
<del> displayErrors: true,
<del> importModuleDynamically: experimentalModules ? async (specifier) => {
<del> if (asyncESM === undefined) lazyLoadESM();
<del> const loader = await asyncESM.loaderPromise;
<del> return loader.import(specifier, normalizeReferrerURL(filename));
<del> } : undefined,
<del> });
<add> const compiledWrapper = vm.compileFunction(content, [
<add> 'exports',
<add> 'require',
<add> 'module',
<add> '__filename',
<add> '__dirname',
<add> ], { filename });
<ide>
<ide> var inspectorWrapper = null;
<ide> if (process._breakFirstLine && process._eval == null) { | 1 |
Javascript | Javascript | log missing roots instead of extra roots twice | 8e15d9656acbf9524b83402dda7a0ab77af9d8ba | <ide><path>spec/main-process/atom-application.new.test.js
<ide> class LaunchScenario {
<ide> parts.push(`* extra roots ${shorten(comparison.extraRoots)}\n`)
<ide> }
<ide> if (comparison.missingRoots.length > 0) {
<del> parts.push(`* missing roots ${shorten(comparison.extraRoots)}\n`)
<add> parts.push(`* missing roots ${shorten(comparison.missingRoots)}\n`)
<ide> }
<ide> if (comparison.extraEditors.length > 0) {
<ide> parts.push(`* extra editors ${shorten(comparison.extraEditors)}\n`) | 1 |
Javascript | Javascript | add invalidate token handler | 09174c9687eb88cc4ba8c698b51ab8f65dfd957a | <ide><path>server/boot/user.js
<ide> module.exports = function(app) {
<ide> router.get('/email-signin', getEmailSignin);
<ide> router.get('/deprecated-signin', getDepSignin);
<ide> router.get('/update-email', getUpdateEmail);
<del> router.get('/passwordless-auth', getPasswordlessAuth);
<add> router.get('/passwordless-auth', invalidateAuthToken, getPasswordlessAuth);
<ide> api.post('/passwordless-auth', postPasswordlessAuth);
<ide> router.get(
<ide> '/delete-my-account',
<ide> module.exports = function(app) {
<ide> });
<ide> }
<ide>
<add> const defaultErrorMsg = [ 'Oops, something is not right, please request a ',
<add> 'fresh link to sign in / sign up.' ].join('');
<add>
<ide> function postPasswordlessAuth(req, res) {
<ide> if (req.user || !(req.body && req.body.email)) {
<ide> return res.redirect('/');
<ide> module.exports = function(app) {
<ide> })
<ide> .catch(err => {
<ide> debug(err);
<del> return res.status(200).send({
<del> message: 'Oops, something is not right, please try again later.'
<del> });
<add> return res.status(200).send({ message: defaultErrorMsg });
<ide> });
<ide> }
<ide>
<add> function invalidateAuthToken(req, res, next) {
<add> if (req.user) {
<add> res.redirect('/');
<add> }
<add>
<add> if (!req.query || !req.query.email || !req.query.token) {
<add> req.flash('info', { msg: defaultErrorMsg });
<add> return res.redirect('/email-signin');
<add> }
<add>
<add> const authTokenId = req.query.token;
<add> const authEmailId = req.query.email;
<add>
<add> return AccessToken.findOne$({ where: {id: authTokenId} })
<add> .map(authToken => {
<add> if (!authToken) {
<add> req.flash('info', { msg: defaultErrorMsg });
<add> return res.redirect('/email-signin');
<add> }
<add>
<add> const userId = authToken.userId;
<add> return User.findById(userId, (err, user) => {
<add> if (err) {
<add> debug(err);
<add> req.flash('info', { msg: defaultErrorMsg });
<add> return res.redirect('/email-signin');
<add> }
<add> if (user.email !== authEmailId) {
<add> req.flash('info', { msg: defaultErrorMsg });
<add> return res.redirect('/email-signin');
<add> }
<add> return authToken.validate((err, isValid) => {
<add> if (err) { throw err; }
<add> if (!isValid) {
<add> req.flash('info', { msg: [ 'Looks like the link you clicked has',
<add> 'expired, please request a fresh link, to sign in.'].join('')
<add> });
<add> return res.redirect('/email-signin');
<add> }
<add> return authToken.destroy((err) => {
<add> if (err) { debug(err); }
<add> next();
<add> });
<add> });
<add> });
<add> })
<add> .subscribe(
<add> () => {},
<add> next
<add> );
<add> }
<add>
<ide> function getPasswordlessAuth(req, res, next) {
<ide> if (req.user) {
<ide> req.flash('info', {
<ide> module.exports = function(app) {
<ide> return res.redirect('/');
<ide> }
<ide>
<del> const defaultErrorMsg = [ 'Oops, something is not right, please request a ',
<del> 'fresh link to sign in / sign up.' ].join('');
<del>
<ide> if (!req.query || !req.query.email || !req.query.token) {
<ide> req.flash('info', { msg: defaultErrorMsg });
<ide> return res.redirect('/email-signin'); | 1 |
Go | Go | use map for capabilities to simplify lookup | 72b1fb59fed262287d81e8628138fa7e3dd6b294 | <ide><path>oci/caps/utils.go
<ide> func init() {
<ide> }
<ide> capName := "CAP_" + strings.ToUpper(c.String())
<ide> allCaps[i] = capName
<del> capabilityList[i] = &CapabilityMapping{
<add> capabilityList[capName] = &CapabilityMapping{
<ide> Key: capName,
<ide> Value: c,
<ide> }
<ide> type (
<ide> Value capability.Cap `json:"value,omitempty"`
<ide> }
<ide> // Capabilities contains all CapabilityMapping
<del> Capabilities []*CapabilityMapping
<add> Capabilities map[string]*CapabilityMapping
<ide> )
<ide>
<ide> // String returns <key> of CapabilityMapping
<ide> func NormalizeLegacyCapabilities(caps []string) ([]string, error) {
<ide> if !strings.HasPrefix(c, "CAP_") {
<ide> c = "CAP_" + c
<ide> }
<del> if !inSlice(allCaps, c) {
<add> if _, ok := capabilityList[c]; !ok {
<ide> return nil, errdefs.InvalidParameter(fmt.Errorf("unknown capability: %q", c))
<ide> }
<ide> normalized = append(normalized, c) | 1 |
Text | Text | fix import names in integration example | d063f654cfd1b2f4e17f9bcd810680fcb5efbded | <ide><path>docs/docs/getting-started/integration.md
<ide> var myChart = new Chart(ctx, {...});
<ide> Chart.js 3 is tree-shakeable, so it is necessary to import and register the controllers, elements, scales and plugins you are going to use.
<ide>
<ide> ```javascript
<del>import { Chart, LineController, Line, Point, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend } from 'chart.js';
<add>import { Chart, LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend } from 'chart.js';
<ide>
<del>Chart.register(LineController, Line, Point, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend);
<add>Chart.register(LineController, LineElement, PointElement, LinearScale, CategoryScale, Title, Tooltip, Filler, Legend);
<ide>
<ide> var myChart = new Chart(ctx, {...});
<ide> ``` | 1 |
PHP | PHP | remove lies in paginatorhelper doc blocks | 9d5097698f2d05ce6c979ccb34a5fd19fff7b93e | <ide><path>Cake/View/Helper/PaginatorHelper.php
<ide> class PaginatorHelper extends Helper {
<ide> *
<ide> * The values that may be specified are:
<ide> *
<del> * - `format` Format of the counter. Supported formats are 'range' and 'pages'
<del> * and custom (default). In the default mode the supplied string is parsed and constants are replaced
<del> * by their actual values.
<del> * placeholders: %page%, %pages%, %current%, %count%, %start%, %end% .
<ide> * - `url` Url of the action. See Router::url()
<ide> * - `url['sort']` the key that the recordset is sorted.
<ide> * - `url['direction']` Direction of the sorting (default: 'asc'). | 1 |
PHP | PHP | use methods that exist | 219faee36f74e1962e3810297628fc40aded5d5f | <ide><path>src/Console/CommandCollection.php
<ide> public function autoDiscover()
<ide> $this->add($info['fullName'], $info['class']);
<ide> }
<ide> } catch (InvalidArgumentException $e) {
<del> Log::warn("Could not add {$info['class']} via autodiscovery. " . $e->getMessage());
<add> Log::warning("Could not add {$info['class']} via autodiscovery. " . $e->getMessage());
<ide> }
<ide> }
<ide> }; | 1 |
Ruby | Ruby | fix frozen string error | 7ab50ef6f611b88915112b8b96db93f198e43e1a | <ide><path>Library/Homebrew/rubocops/homepage.rb
<ide> def autocorrect(node)
<ide> lambda do |corrector|
<ide> return if node.nil?
<ide>
<del> homepage = string_content(node)
<add> homepage = string_content(node).dup
<ide> homepage.sub!("readthedocs.org", "readthedocs.io")
<ide> homepage.delete_suffix!(".git") if homepage.start_with?("https://github.com")
<ide> corrector.replace(node.source_range, "\"#{homepage}\"") | 1 |
Python | Python | change token.generate_key to a classmethod | 35c0abf24ea4a6c38e6fc2ee22b4aabe73776783 | <ide><path>rest_framework/authtoken/models.py
<ide> def save(self, *args, **kwargs):
<ide> self.key = self.generate_key()
<ide> return super().save(*args, **kwargs)
<ide>
<del> def generate_key(self):
<add> @classmethod
<add> def generate_key(cls):
<ide> return binascii.hexlify(os.urandom(20)).decode()
<ide>
<ide> def __str__(self):
<ide><path>tests/authentication/test_authentication.py
<ide> def test_generate_key_returns_string(self):
<ide> key = token.generate_key()
<ide> assert isinstance(key, str)
<ide>
<add> def test_generate_key_accessible_as_classmethod(self):
<add> key = self.model.generate_key()
<add> assert isinstance(key, str)
<add>
<ide> def test_token_login_json(self):
<ide> """Ensure token login view using JSON POST works."""
<ide> client = APIClient(enforce_csrf_checks=True) | 2 |
Python | Python | add server default for map_index in log table | f471d4f54dafdb57c04346421d89795381f79017 | <ide><path>airflow/models/log.py
<ide> # specific language governing permissions and limitations
<ide> # under the License.
<ide>
<del>from sqlalchemy import Column, Index, Integer, String, Text
<add>from sqlalchemy import Column, Index, Integer, String, Text, text
<ide>
<ide> from airflow.models.base import Base, StringID
<ide> from airflow.utils import timezone
<ide> class Log(Base):
<ide> dttm = Column(UtcDateTime)
<ide> dag_id = Column(StringID())
<ide> task_id = Column(StringID())
<del> map_index = Column(Integer)
<add> map_index = Column(Integer, server_default=text('NULL'))
<ide> event = Column(String(30))
<ide> execution_date = Column(UtcDateTime)
<ide> owner = Column(String(500)) | 1 |
Python | Python | allow newaxis indexing for `array_api` arrays | befef7b26773eddd2b656a3ab87f504e6cc173db | <ide><path>numpy/array_api/_array_object.py
<ide> _dtype_categories,
<ide> )
<ide>
<del>from typing import TYPE_CHECKING, Optional, Tuple, Union, Any
<add>from typing import TYPE_CHECKING, Optional, Tuple, Union, Any, SupportsIndex
<ide> import types
<ide>
<ide> if TYPE_CHECKING:
<ide> def _normalize_two_args(x1, x2) -> Tuple[Array, Array]:
<ide>
<ide> # Note: A large fraction of allowed indices are disallowed here (see the
<ide> # docstring below)
<del> @staticmethod
<del> def _validate_index(key, shape):
<add> def _validate_index(self, key):
<ide> """
<ide> Validate an index according to the array API.
<ide>
<ide> def _validate_index(key, shape):
<ide> https://data-apis.org/array-api/latest/API_specification/indexing.html
<ide> for the full list of required indexing behavior
<ide>
<del> This function either raises IndexError if the index ``key`` is
<del> invalid, or a new key to be used in place of ``key`` in indexing. It
<add> This function raises IndexError if the index ``key`` is invalid. It
<ide> only raises ``IndexError`` on indices that are not already rejected by
<ide> NumPy, as NumPy will already raise the appropriate error on such
<ide> indices. ``shape`` may be None, in which case, only cases that are
<ide> def _validate_index(key, shape):
<ide>
<ide> - Indices to not include an implicit ellipsis at the end. That is,
<ide> every axis of an array must be explicitly indexed or an ellipsis
<del> included.
<add> included. This behaviour is sometimes referred to as flat indexing.
<ide>
<ide> - The start and stop of a slice may not be out of bounds. In
<ide> particular, for a slice ``i:j:k`` on an axis of size ``n``, only the
<ide> def _validate_index(key, shape):
<ide> ``Array._new`` constructor, not this function.
<ide>
<ide> """
<del> if isinstance(key, slice):
<del> if shape is None:
<del> return key
<del> if shape == ():
<del> return key
<del> if len(shape) > 1:
<add> _key = key if isinstance(key, tuple) else (key,)
<add> for i in _key:
<add> if isinstance(i, bool) or not (
<add> isinstance(i, SupportsIndex) # i.e. ints
<add> or isinstance(i, slice)
<add> or i == Ellipsis
<add> or i is None
<add> or isinstance(i, Array)
<add> or isinstance(i, np.ndarray)
<add> ):
<ide> raise IndexError(
<del> "Multidimensional arrays must include an index for every axis or use an ellipsis"
<add> f"Single-axes index {i} has {type(i)=}, but only "
<add> "integers, slices (:), ellipsis (...), newaxis (None), "
<add> "zero-dimensional integer arrays and boolean arrays "
<add> "are specified in the Array API."
<ide> )
<del> size = shape[0]
<del> # Ensure invalid slice entries are passed through.
<del> if key.start is not None:
<del> try:
<del> operator.index(key.start)
<del> except TypeError:
<del> return key
<del> if not (-size <= key.start <= size):
<del> raise IndexError(
<del> "Slices with out-of-bounds start are not allowed in the array API namespace"
<del> )
<del> if key.stop is not None:
<del> try:
<del> operator.index(key.stop)
<del> except TypeError:
<del> return key
<del> step = 1 if key.step is None else key.step
<del> if (step > 0 and not (-size <= key.stop <= size)
<del> or step < 0 and not (-size - 1 <= key.stop <= max(0, size - 1))):
<del> raise IndexError("Slices with out-of-bounds stop are not allowed in the array API namespace")
<del> return key
<del>
<del> elif isinstance(key, tuple):
<del> key = tuple(Array._validate_index(idx, None) for idx in key)
<del>
<del> for idx in key:
<del> if (
<del> isinstance(idx, np.ndarray)
<del> and idx.dtype in _boolean_dtypes
<del> or isinstance(idx, (bool, np.bool_))
<del> ):
<del> if len(key) == 1:
<del> return key
<del> raise IndexError(
<del> "Boolean array indices combined with other indices are not allowed in the array API namespace"
<del> )
<del> if isinstance(idx, tuple):
<del> raise IndexError(
<del> "Nested tuple indices are not allowed in the array API namespace"
<del> )
<del>
<del> if shape is None:
<del> return key
<del> n_ellipsis = key.count(...)
<del> if n_ellipsis > 1:
<del> return key
<del> ellipsis_i = key.index(...) if n_ellipsis else len(key)
<ide>
<del> for idx, size in list(zip(key[:ellipsis_i], shape)) + list(
<del> zip(key[:ellipsis_i:-1], shape[:ellipsis_i:-1])
<del> ):
<del> Array._validate_index(idx, (size,))
<del> if n_ellipsis == 0 and len(key) < len(shape):
<add> nonexpanding_key = []
<add> single_axes = []
<add> n_ellipsis = 0
<add> key_has_mask = False
<add> for i in _key:
<add> if i is not None:
<add> nonexpanding_key.append(i)
<add> if isinstance(i, Array) or isinstance(i, np.ndarray):
<add> if i.dtype in _boolean_dtypes:
<add> key_has_mask = True
<add> single_axes.append(i)
<add> else:
<add> # i must not be an array here, to avoid elementwise equals
<add> if i == Ellipsis:
<add> n_ellipsis += 1
<add> else:
<add> single_axes.append(i)
<add>
<add> n_single_axes = len(single_axes)
<add> if n_ellipsis > 1:
<add> return # handled by ndarray
<add> elif n_ellipsis == 0:
<add> # Note boolean masks must be the sole index, which we check for
<add> # later on.
<add> if not key_has_mask and n_single_axes < self.ndim:
<ide> raise IndexError(
<del> "Multidimensional arrays must include an index for every axis or use an ellipsis"
<add> f"{self.ndim=}, but the multi-axes index only specifies "
<add> f"{n_single_axes} dimensions. If this was intentional, "
<add> "add a trailing ellipsis (...) which expands into as many "
<add> "slices (:) as necessary - this is what np.ndarray arrays "
<add> "implicitly do, but such flat indexing behaviour is not "
<add> "specified in the Array API."
<ide> )
<del> return key
<del> elif isinstance(key, bool):
<del> return key
<del> elif isinstance(key, Array):
<del> if key.dtype in _integer_dtypes:
<del> if key.ndim != 0:
<add>
<add> if n_ellipsis == 0:
<add> indexed_shape = self.shape
<add> else:
<add> ellipsis_start = None
<add> for pos, i in enumerate(nonexpanding_key):
<add> if not (isinstance(i, Array) or isinstance(i, np.ndarray)):
<add> if i == Ellipsis:
<add> ellipsis_start = pos
<add> break
<add> assert ellipsis_start is not None # sanity check
<add> ellipsis_end = self.ndim - (n_single_axes - ellipsis_start)
<add> indexed_shape = (
<add> self.shape[:ellipsis_start] + self.shape[ellipsis_end:]
<add> )
<add> for i, side in zip(single_axes, indexed_shape):
<add> if isinstance(i, slice):
<add> if side == 0:
<add> f_range = "0 (or None)"
<add> else:
<add> f_range = f"between -{side} and {side - 1} (or None)"
<add> if i.start is not None:
<add> try:
<add> start = operator.index(i.start)
<add> except TypeError:
<add> pass # handled by ndarray
<add> else:
<add> if not (-side <= start <= side):
<add> raise IndexError(
<add> f"Slice {i} contains {start=}, but should be "
<add> f"{f_range} for an axis of size {side} "
<add> "(out-of-bounds starts are not specified in "
<add> "the Array API)"
<add> )
<add> if i.stop is not None:
<add> try:
<add> stop = operator.index(i.stop)
<add> except TypeError:
<add> pass # handled by ndarray
<add> else:
<add> if not (-side <= stop <= side):
<add> raise IndexError(
<add> f"Slice {i} contains {stop=}, but should be "
<add> f"{f_range} for an axis of size {side} "
<add> "(out-of-bounds stops are not specified in "
<add> "the Array API)"
<add> )
<add> elif isinstance(i, Array):
<add> if i.dtype in _boolean_dtypes and len(_key) != 1:
<add> assert isinstance(key, tuple) # sanity check
<ide> raise IndexError(
<del> "Non-zero dimensional integer array indices are not allowed in the array API namespace"
<add> f"Single-axes index {i} is a boolean array and "
<add> f"{len(key)=}, but masking is only specified in the "
<add> "Array API when the array is the sole index."
<ide> )
<del> return key._array
<del> elif key is Ellipsis:
<del> return key
<del> elif key is None:
<del> raise IndexError(
<del> "newaxis indices are not allowed in the array API namespace"
<del> )
<del> try:
<del> key = operator.index(key)
<del> if shape is not None and len(shape) > 1:
<add> elif i.dtype in _integer_dtypes and i.ndim != 0:
<add> raise IndexError(
<add> f"Single-axes index {i} is a non-zero-dimensional "
<add> "integer array, but advanced integer indexing is not "
<add> "specified in the Array API."
<add> )
<add> elif isinstance(i, tuple):
<ide> raise IndexError(
<del> "Multidimensional arrays must include an index for every axis or use an ellipsis"
<add> f"Single-axes index {i} is a tuple, but nested tuple "
<add> "indices are not specified in the Array API."
<ide> )
<del> return key
<del> except TypeError:
<del> # Note: This also omits boolean arrays that are not already in
<del> # Array() form, like a list of booleans.
<del> raise IndexError(
<del> "Only integers, slices (`:`), ellipsis (`...`), and boolean arrays are valid indices in the array API namespace"
<del> )
<ide>
<ide> # Everything below this line is required by the spec.
<ide>
<ide> def __getitem__(
<ide> """
<ide> # Note: Only indices required by the spec are allowed. See the
<ide> # docstring of _validate_index
<del> key = self._validate_index(key, self.shape)
<add> self._validate_index(key)
<add> if isinstance(key, Array):
<add> # Indexing self._array with array_api arrays can be erroneous
<add> key = key._array
<ide> res = self._array.__getitem__(key)
<ide> return self._new(res)
<ide>
<ide> def __setitem__(
<ide> """
<ide> # Note: Only indices required by the spec are allowed. See the
<ide> # docstring of _validate_index
<del> key = self._validate_index(key, self.shape)
<add> self._validate_index(key)
<add> if isinstance(key, Array):
<add> # Indexing self._array with array_api arrays can be erroneous
<add> key = key._array
<ide> self._array.__setitem__(key, asarray(value)._array)
<ide>
<ide> def __sub__(self: Array, other: Union[int, float, Array], /) -> Array:
<ide><path>numpy/array_api/tests/test_array_object.py
<ide>
<ide> from numpy.testing import assert_raises
<ide> import numpy as np
<add>import pytest
<ide>
<del>from .. import ones, asarray, result_type, all, equal
<add>from .. import ones, asarray, reshape, result_type, all, equal
<ide> from .._array_object import Array
<ide> from .._dtypes import (
<ide> _all_dtypes,
<ide> int32,
<ide> int64,
<ide> uint64,
<add> bool as bool_,
<ide> )
<ide>
<ide>
<ide> def test_validate_index():
<ide> assert_raises(IndexError, lambda: a[[0, 1]])
<ide> assert_raises(IndexError, lambda: a[np.array([[0, 1]])])
<ide>
<del> # np.newaxis is not allowed
<del> assert_raises(IndexError, lambda: a[None])
<del> assert_raises(IndexError, lambda: a[None, ...])
<del> assert_raises(IndexError, lambda: a[..., None])
<del>
<ide> # Multiaxis indices must contain exactly as many indices as dimensions
<ide> assert_raises(IndexError, lambda: a[()])
<ide> assert_raises(IndexError, lambda: a[0,])
<ide> def test___array__():
<ide> b = np.asarray(a, dtype=np.float64)
<ide> assert np.all(np.equal(b, np.ones((2, 3), dtype=np.float64)))
<ide> assert b.dtype == np.float64
<add>
<add>def test_allow_newaxis():
<add> a = ones(5)
<add> indexed_a = a[None, :]
<add> assert indexed_a.shape == (1, 5)
<add>
<add>def test_disallow_flat_indexing_with_newaxis():
<add> a = ones((3, 3, 3))
<add> with pytest.raises(IndexError):
<add> a[None, 0, 0]
<add>
<add>def test_disallow_mask_with_newaxis():
<add> a = ones((3, 3, 3))
<add> with pytest.raises(IndexError):
<add> a[None, asarray(True)]
<add>
<add>@pytest.mark.parametrize("shape", [(), (5,), (3, 3, 3)])
<add>@pytest.mark.parametrize("index", ["string", False, True])
<add>def test_error_on_invalid_index(shape, index):
<add> a = ones(shape)
<add> with pytest.raises(IndexError):
<add> a[index]
<add>
<add>def test_mask_0d_array_without_errors():
<add> a = ones(())
<add> a[asarray(True)]
<add>
<add>@pytest.mark.parametrize(
<add> "i", [slice(5), slice(5, 0), asarray(True), asarray([0, 1])]
<add>)
<add>def test_error_on_invalid_index_with_ellipsis(i):
<add> a = ones((3, 3, 3))
<add> with pytest.raises(IndexError):
<add> a[..., i]
<add> with pytest.raises(IndexError):
<add> a[i, ...]
<add>
<add>def test_array_keys_use_private_array():
<add> """
<add> Indexing operations convert array keys before indexing the internal array
<add>
<add> Fails when array_api array keys are not converted into NumPy-proper arrays
<add> in __getitem__(). This is achieved by passing array_api arrays with 0-sized
<add> dimensions, which NumPy-proper treats erroneously - not sure why!
<add>
<add> TODO: Find and use appropiate __setitem__() case.
<add> """
<add> a = ones((0, 0), dtype=bool_)
<add> assert a[a].shape == (0,)
<add>
<add> a = ones((0,), dtype=bool_)
<add> key = ones((0, 0), dtype=bool_)
<add> with pytest.raises(IndexError):
<add> a[key] | 2 |
Javascript | Javascript | remove duplicated code in shaderlib | 158676fe0911ff735c2f1289c9d631d802055a42 | <ide><path>src/renderers/shaders/ShaderChunk.js
<ide> ].join("\n")
<ide>
<ide>
<del>};
<del>
<del>THREE.UniformsUtils = {
<del>
<del> merge: function ( uniforms ) {
<del>
<del> var u, p, tmp, merged = {};
<del>
<del> for ( u = 0; u < uniforms.length; u ++ ) {
<del>
<del> tmp = this.clone( uniforms[ u ] );
<del>
<del> for ( p in tmp ) {
<del>
<del> merged[ p ] = tmp[ p ];
<del>
<del> }
<del>
<del> }
<del>
<del> return merged;
<del>
<del> },
<del>
<del> clone: function ( uniforms_src ) {
<del>
<del> var u, p, parameter, parameter_src, uniforms_dst = {};
<del>
<del> for ( u in uniforms_src ) {
<del>
<del> uniforms_dst[ u ] = {};
<del>
<del> for ( p in uniforms_src[ u ] ) {
<del>
<del> parameter_src = uniforms_src[ u ][ p ];
<del>
<del> if ( parameter_src instanceof THREE.Color ||
<del> parameter_src instanceof THREE.Vector2 ||
<del> parameter_src instanceof THREE.Vector3 ||
<del> parameter_src instanceof THREE.Vector4 ||
<del> parameter_src instanceof THREE.Matrix4 ||
<del> parameter_src instanceof THREE.Texture ) {
<del>
<del> uniforms_dst[ u ][ p ] = parameter_src.clone();
<del>
<del> } else if ( parameter_src instanceof Array ) {
<del>
<del> uniforms_dst[ u ][ p ] = parameter_src.slice();
<del>
<del> } else {
<del>
<del> uniforms_dst[ u ][ p ] = parameter_src;
<del>
<del> }
<del>
<del> }
<del>
<del> }
<del>
<del> return uniforms_dst;
<del>
<del> }
<del>
<del>};
<add>};
<ide>\ No newline at end of file | 1 |
PHP | PHP | use bar "or" syntax | ea6c72149c67697c84c28c21afedf434d6184842 | <ide><path>src/Illuminate/Http/Response.php
<ide> protected function morphToJson($content)
<ide> */
<ide> protected function shouldBeJson($content)
<ide> {
<del> return ($content instanceof JsonableInterface or
<del> $content instanceof ArrayObject or
<del> is_array($content));
<add> return $content instanceof JsonableInterface ||
<add> $content instanceof ArrayObject ||
<add> is_array($content);
<ide> }
<ide>
<ide> /** | 1 |
Python | Python | remove wheel and pex files in fab clean | fbb67b1b4bd2ba3e62bc2bea50c31e4cfd4a9ecf | <ide><path>fabfile.py
<ide> def pex():
<ide>
<ide> def clean():
<ide> with lcd(path.dirname(__file__)):
<add> local('rm -f dist/*.whl')
<add> local('rm -f dist/*.pex')
<ide> with virtualenv(VENV_DIR) as venv_local:
<ide> venv_local('python setup.py clean --all')
<ide> | 1 |
Ruby | Ruby | initialize path to nil or a pathname | 0d08a5af00011679acd6d82714e9883f93b9fb7c | <ide><path>Library/Homebrew/formula.rb
<ide> def initialize name='__UNKNOWN__', path=nil
<ide> @name=name
<ide> validate_variable :name
<ide>
<del> @path=path
<add> @path = path.nil? ? nil : Pathname.new(path)
<ide>
<ide> set_instance_variable 'version'
<ide> @version ||= @spec_to_use.detect_version | 1 |
PHP | PHP | get default value | 607b23b74213a63f6cc363be39794faee78c5160 | <ide><path>system/session.php
<ide> public static function load()
<ide> static::$session = static::driver()->load($id);
<ide> }
<ide>
<del> // ---------------------------------------------------------
<ide> // If the session is invalid or expired, start a new one.
<del> // ---------------------------------------------------------
<ide> if (is_null($id) or is_null(static::$session) or static::expired(static::$session['last_activity']))
<ide> {
<ide> static::$session['id'] = Str::random(40);
<ide> static::$session['data'] = array();
<ide> }
<ide>
<del> // ---------------------------------------------------------
<del> // Create a CSRF token for the session if necessary. This
<del> // token is used by the Form class and filters to protect
<del> // against cross-site request forgeries.
<del> // ---------------------------------------------------------
<ide> if ( ! static::has('csrf_token'))
<ide> {
<ide> static::put('csrf_token', Str::random(16));
<ide> public static function get($key, $default = null)
<ide> return static::$session['data'][':new:'.$key];
<ide> }
<ide>
<del> return $default;
<add> return is_callable($default) ? call_user_func($default) : $default;
<ide> }
<ide>
<ide> /**
<ide> public static function flush()
<ide> */
<ide> public static function regenerate()
<ide> {
<del> // ---------------------------------------------------------
<del> // When regenerating the session ID, we go ahead and delete
<del> // the session data from storage. Then, we assign a new ID.
<del> //
<del> // The session will be re-written to storage at the end
<del> // of the request to the application.
<del> // ---------------------------------------------------------
<ide> static::driver()->delete(static::$session['id']);
<ide>
<ide> static::$session['id'] = Str::random(40);
<ide> public static function regenerate()
<ide> */
<ide> public static function close()
<ide> {
<del> // ---------------------------------------------------------
<del> // Flash the old input data to the session. This allows
<del> // the Input::old method to retrieve input from the
<del> // previous request made by the user.
<del> // ---------------------------------------------------------
<add> // Flash the old input data to the session. This allows the Input::old method to
<add> // retrieve the input from the previous request made by the user.
<ide> static::flash('laravel_old_input', Input::get());
<ide>
<ide> static::age_flash();
<ide>
<ide> static::driver()->save(static::$session);
<ide>
<del> // ---------------------------------------------------------
<del> // Send the session cookie the browser so we can remember
<del> // who the session belongs to on subsequent requests.
<del> // ---------------------------------------------------------
<ide> if ( ! headers_sent())
<ide> {
<ide> $minutes = (Config::get('session.expire_on_close')) ? 0 : Config::get('session.lifetime');
<ide>
<ide> Cookie::put('laravel_session', static::$session['id'], $minutes, Config::get('session.path'), Config::get('session.domain'), Config::get('session.https'));
<ide> }
<ide>
<del> // ---------------------------------------------------------
<del> // Perform session garbage collection (2% chance).
<del> // Session garbage collection removes all expired sessions.
<del> // ---------------------------------------------------------
<add> // 2% chance of performing session garbage collection...
<ide> if (mt_rand(1, 100) <= 2)
<ide> {
<ide> static::driver()->sweep(time() - (Config::get('session.lifetime') * 60));
<ide> public static function close()
<ide> */
<ide> private static function age_flash()
<ide> {
<del> // -----------------------------------------------------
<del> // Remove all of the :old: items from the session.
<del> // -----------------------------------------------------
<ide> foreach (static::$session['data'] as $key => $value)
<ide> {
<ide> if (strpos($key, ':old:') === 0)
<ide> private static function age_flash()
<ide> }
<ide> }
<ide>
<del> // -----------------------------------------------------
<del> // Copy all of the :new: items to :old: items and then
<del> // remove the :new: items from the session.
<del> // -----------------------------------------------------
<ide> foreach (static::$session['data'] as $key => $value)
<ide> {
<ide> if (strpos($key, ':new:') === 0) | 1 |
Go | Go | remove unused constants in plugin_responses | 9bb57aa3fef6c1f31e9e8344e06670c3d41e4395 | <ide><path>api/types/plugin_responses.go
<ide> import (
<ide> // PluginsListResponse contains the response for the Engine API
<ide> type PluginsListResponse []*Plugin
<ide>
<del>const (
<del> authzDriver = "AuthzDriver"
<del> graphDriver = "GraphDriver"
<del> ipamDriver = "IpamDriver"
<del> networkDriver = "NetworkDriver"
<del> volumeDriver = "VolumeDriver"
<del>)
<del>
<ide> // UnmarshalJSON implements json.Unmarshaler for PluginInterfaceType
<ide> func (t *PluginInterfaceType) UnmarshalJSON(p []byte) error {
<ide> versionIndex := len(p) | 1 |
Javascript | Javascript | add type checking for path inputs | eb995d682201018b2a47c44e921848cfa31486a2 | <ide><path>lib/path.js
<ide> 'use strict';
<ide>
<add>const util = require('util');
<ide> const isWindows = process.platform === 'win32';
<ide>
<add>function assertPath(path) {
<add> if (typeof path !== 'string') {
<add> throw new TypeError('Path must be a string. Received ' +
<add> util.inspect(path));
<add> }
<add>}
<add>
<ide> // resolves . and .. elements in a path array with directory names there
<ide> // must be no slashes or device names (c:\) in the array
<ide> // (so also no leading and trailing slashes - it does not distinguish
<ide> win32.resolve = function() {
<ide> }
<ide> }
<ide>
<del> // Skip empty and invalid entries
<del> if (typeof path !== 'string') {
<del> throw new TypeError('Arguments to path.resolve must be strings');
<del> } else if (!path) {
<add> assertPath(path);
<add>
<add> // Skip empty entries
<add> if (path === '') {
<ide> continue;
<ide> }
<ide>
<ide> win32.resolve = function() {
<ide>
<ide>
<ide> win32.normalize = function(path) {
<add> assertPath(path);
<add>
<ide> var result = splitDeviceRe.exec(path),
<ide> device = result[1] || '',
<ide> isUnc = device && device.charAt(1) !== ':',
<ide> win32.normalize = function(path) {
<ide>
<ide>
<ide> win32.isAbsolute = function(path) {
<add> assertPath(path);
<add>
<ide> var result = splitDeviceRe.exec(path),
<ide> device = result[1] || '',
<ide> isUnc = !!device && device.charAt(1) !== ':';
<ide> win32.join = function() {
<ide> // to = 'C:\\orandea\\impl\\bbb'
<ide> // The output of the function should be: '..\\..\\impl\\bbb'
<ide> win32.relative = function(from, to) {
<add> assertPath(from);
<add> assertPath(to);
<add>
<ide> from = win32.resolve(from);
<ide> to = win32.resolve(to);
<ide>
<ide> win32._makeLong = function(path) {
<ide>
<ide>
<ide> win32.dirname = function(path) {
<add> assertPath(path);
<add>
<ide> var result = win32SplitPath(path),
<ide> root = result[0],
<ide> dir = result[1];
<ide> win32.dirname = function(path) {
<ide>
<ide>
<ide> win32.basename = function(path, ext) {
<add> assertPath(path);
<add>
<add> if (ext !== undefined && typeof ext !== 'string')
<add> throw new TypeError('ext must be a string');
<add>
<ide> var f = win32SplitPath(path)[2];
<ide> // TODO: make this comparison case-insensitive on windows?
<ide> if (ext && f.substr(-1 * ext.length) === ext) {
<ide> win32.basename = function(path, ext) {
<ide>
<ide>
<ide> win32.extname = function(path) {
<add> assertPath(path);
<ide> return win32SplitPath(path)[3];
<ide> };
<ide>
<ide> win32.format = function(pathObject) {
<ide>
<ide>
<ide> win32.parse = function(pathString) {
<del> if (typeof pathString !== 'string') {
<del> throw new TypeError(
<del> "Parameter 'pathString' must be a string, not " + typeof pathString
<del> );
<del> }
<add> assertPath(pathString);
<add>
<ide> var allParts = win32SplitPath(pathString);
<ide> if (!allParts || allParts.length !== 4) {
<ide> throw new TypeError("Invalid path '" + pathString + "'");
<ide> posix.resolve = function() {
<ide> for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
<ide> var path = (i >= 0) ? arguments[i] : process.cwd();
<ide>
<del> // Skip empty and invalid entries
<del> if (typeof path !== 'string') {
<del> throw new TypeError('Arguments to path.resolve must be strings');
<del> } else if (!path) {
<add> assertPath(path);
<add>
<add> // Skip empty entries
<add> if (path === '') {
<ide> continue;
<ide> }
<ide>
<ide> posix.resolve = function() {
<ide> // path.normalize(path)
<ide> // posix version
<ide> posix.normalize = function(path) {
<add> assertPath(path);
<add>
<ide> var isAbsolute = posix.isAbsolute(path),
<ide> trailingSlash = path.substr(-1) === '/';
<ide>
<ide> posix.normalize = function(path) {
<ide>
<ide> // posix version
<ide> posix.isAbsolute = function(path) {
<add> assertPath(path);
<ide> return path.charAt(0) === '/';
<ide> };
<ide>
<ide> posix.join = function() {
<ide> // path.relative(from, to)
<ide> // posix version
<ide> posix.relative = function(from, to) {
<add> assertPath(from);
<add> assertPath(to);
<add>
<ide> from = posix.resolve(from).substr(1);
<ide> to = posix.resolve(to).substr(1);
<ide>
<ide> posix._makeLong = function(path) {
<ide>
<ide>
<ide> posix.dirname = function(path) {
<add> assertPath(path);
<add>
<ide> var result = posixSplitPath(path),
<ide> root = result[0],
<ide> dir = result[1];
<ide> posix.dirname = function(path) {
<ide>
<ide>
<ide> posix.basename = function(path, ext) {
<add> assertPath(path);
<add>
<add> if (ext !== undefined && typeof ext !== 'string')
<add> throw new TypeError('ext must be a string');
<add>
<ide> var f = posixSplitPath(path)[2];
<del> // TODO: make this comparison case-insensitive on windows?
<add>
<ide> if (ext && f.substr(-1 * ext.length) === ext) {
<ide> f = f.substr(0, f.length - ext.length);
<ide> }
<ide> posix.basename = function(path, ext) {
<ide>
<ide>
<ide> posix.extname = function(path) {
<add> assertPath(path);
<ide> return posixSplitPath(path)[3];
<ide> };
<ide>
<ide> posix.format = function(pathObject) {
<ide>
<ide>
<ide> posix.parse = function(pathString) {
<del> if (typeof pathString !== 'string') {
<del> throw new TypeError(
<del> "Parameter 'pathString' must be a string, not " + typeof pathString
<del> );
<del> }
<add> assertPath(pathString);
<add>
<ide> var allParts = posixSplitPath(pathString);
<ide> if (!allParts || allParts.length !== 4) {
<ide> throw new TypeError("Invalid path '" + pathString + "'");
<ide><path>test/parallel/test-path-parse-format.js
<ide> var unixPaths = [
<ide> ];
<ide>
<ide> var errors = [
<del> {method: 'parse', input: [null], message: /Parameter 'pathString' must be a string, not/},
<del> {method: 'parse', input: [{}], message: /Parameter 'pathString' must be a string, not object/},
<del> {method: 'parse', input: [true], message: /Parameter 'pathString' must be a string, not boolean/},
<del> {method: 'parse', input: [1], message: /Parameter 'pathString' must be a string, not number/},
<del> {method: 'parse', input: [], message: /Parameter 'pathString' must be a string, not undefined/},
<add> {method: 'parse', input: [null], message: /Path must be a string. Received null/},
<add> {method: 'parse', input: [{}], message: /Path must be a string. Received {}/},
<add> {method: 'parse', input: [true], message: /Path must be a string. Received true/},
<add> {method: 'parse', input: [1], message: /Path must be a string. Received 1/},
<add> {method: 'parse', input: [], message: /Path must be a string. Received undefined/},
<ide> // {method: 'parse', input: [''], message: /Invalid path/}, // omitted because it's hard to trigger!
<ide> {method: 'format', input: [null], message: /Parameter 'pathObject' must be an object, not/},
<ide> {method: 'format', input: [''], message: /Parameter 'pathObject' must be an object, not string/},
<ide><path>test/parallel/test-path.js
<ide> joinTests.forEach(function(test) {
<ide> // assert.equal(actual, expected, message);
<ide> });
<ide> assert.equal(failures.length, 0, failures.join(''));
<del>var joinThrowTests = [true, false, 7, null, {}, undefined, [], NaN];
<del>joinThrowTests.forEach(function(test) {
<del> assert.throws(function() {
<del> path.join(test);
<del> }, TypeError);
<add>
<add>// Test thrown TypeErrors
<add>var typeErrorTests = [true, false, 7, null, {}, undefined, [], NaN];
<add>
<add>function fail(fn) {
<add> var args = Array.prototype.slice.call(arguments, 1);
<add>
<ide> assert.throws(function() {
<del> path.resolve(test);
<add> fn.apply(null, args);
<ide> }, TypeError);
<add>}
<add>
<add>typeErrorTests.forEach(function(test) {
<add> fail(path.join, test);
<add> fail(path.resolve, test);
<add> fail(path.normalize, test);
<add> fail(path.isAbsolute, test);
<add> fail(path.dirname, test);
<add> fail(path.relative, test, 'foo');
<add> fail(path.relative, 'foo', test);
<add> fail(path.basename, test);
<add> fail(path.extname, test);
<add> fail(path.parse, test);
<add>
<add> // undefined is a valid value as the second argument to basename
<add> if (test !== undefined) {
<add> fail(path.basename, 'foo', test);
<add> }
<ide> });
<ide>
<ide> | 3 |
Javascript | Javascript | stabilize minimal server rendering api | 37cde3d864406f2af65dc03eae45a216ea969600 | <ide><path>src/core/React.js
<ide> var ReactCompositeComponent = require('ReactCompositeComponent');
<ide> var ReactComponent = require('ReactComponent');
<ide> var ReactDOM = require('ReactDOM');
<ide> var ReactMount = require('ReactMount');
<add>var ReactServerRendering = require('ReactServerRendering');
<ide>
<ide> var ReactDefaultInjection = require('ReactDefaultInjection');
<ide>
<ide> var React = {
<ide> constructAndRenderComponent: ReactMount.constructAndRenderComponent,
<ide> constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
<ide> renderComponent: ReactMount.renderComponent,
<add> renderComponentToString: ReactServerRendering.renderComponentToString,
<ide> unmountAndReleaseReactRootNode: ReactMount.unmountAndReleaseReactRootNode,
<ide> isValidComponent: ReactComponent.isValidComponent
<ide> };
<ide><path>src/core/ReactComponent.js
<ide> var ReactComponent = {
<ide> *
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {DOMElement} container DOM element to mount into.
<add> * @param {boolean} shouldReuseMarkup If true, do not insert markup
<ide> * @final
<ide> * @internal
<ide> * @see {ReactMount.renderComponent}
<ide> */
<del> mountComponentIntoNode: function(rootID, container) {
<add> mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
<ide> var transaction = ReactComponent.ReactReconcileTransaction.getPooled();
<ide> transaction.perform(
<ide> this._mountComponentIntoNode,
<ide> this,
<ide> rootID,
<ide> container,
<del> transaction
<add> transaction,
<add> shouldReuseMarkup
<ide> );
<ide> ReactComponent.ReactReconcileTransaction.release(transaction);
<ide> },
<ide> var ReactComponent = {
<ide> * @param {string} rootID DOM ID of the root node.
<ide> * @param {DOMElement} container DOM element to mount into.
<ide> * @param {ReactReconcileTransaction} transaction
<add> * @param {boolean} shouldReuseMarkup If true, do not insert markup
<ide> * @final
<ide> * @private
<ide> */
<del> _mountComponentIntoNode: function(rootID, container, transaction) {
<add> _mountComponentIntoNode: function(
<add> rootID,
<add> container,
<add> transaction,
<add> shouldReuseMarkup) {
<ide> var renderStart = Date.now();
<ide> var markup = this.mountComponent(rootID, transaction);
<ide> ReactMount.totalInstantiationTime += (Date.now() - renderStart);
<ide>
<add> if (shouldReuseMarkup) {
<add> return;
<add> }
<add>
<ide> var injectionStart = Date.now();
<ide> // Asynchronously inject markup by ensuring that the container is not in
<ide> // the document when settings its `innerHTML`.
<ide><path>src/core/ReactInstanceHandles.js
<ide> var SEPARATOR_LENGTH = SEPARATOR.length;
<ide> */
<ide> var MAX_TREE_DEPTH = 100;
<ide>
<add>/**
<add> * Size of the reactRoot ID space. We generate random numbers for React root
<add> * IDs and if there's a collision the events and DOM update system will
<add> * get confused. If we assume 100 React components per page, and a user
<add> * loads 1 page per minute 24/7 for 50 years, with a mount point space of
<add> * 9,999,999 the likelihood of never having a collision is 99.997%.
<add> */
<add>var GLOBAL_MOUNT_POINT_MAX = 9999999;
<add>
<add>/**
<add> * Creates a DOM ID prefix to use when mounting React components.
<add> *
<add> * @param {number} index A unique integer
<add> * @return {string} React root ID.
<add> * @internal
<add> */
<add>function getReactRootIDString(index) {
<add> return '.reactRoot[' + index + ']';
<add>}
<add>
<ide> /**
<ide> * Checks if a character in the supplied ID is a separator or the end.
<ide> *
<ide> function isValidID(id) {
<ide> );
<ide> }
<ide>
<del>/**
<del> * True if the supplied `node` is rendered by React.
<del> *
<del> * @param {DOMEventTarget} node DOM Element to check.
<del> * @return {boolean} True if the DOM Element appears to be rendered by React.
<del> * @private
<del> */
<del>function isRenderedByReact(node) {
<del> var id = getDOMNodeID(node);
<del> return id ? id.charAt(0) === SEPARATOR : false;
<del>}
<del>
<ide> /**
<ide> * Gets the parent ID of the supplied React DOM ID, `id`.
<ide> *
<ide> var ReactInstanceHandles = {
<ide>
<ide> separator: SEPARATOR,
<ide>
<add> createReactRootID: function() {
<add> return getReactRootIDString(
<add> Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX)
<add> );
<add> },
<add>
<add> /**
<add> * True if the supplied `node` is rendered by React.
<add> *
<add> * @param {DOMEventTarget} node DOM Element to check.
<add> * @return {boolean} True if the DOM Element appears to be rendered by React.
<add> * @private
<add> */
<add> isRenderedByReact: function(node) {
<add> var id = getDOMNodeID(node);
<add> return id ? id.charAt(0) === SEPARATOR : false;
<add> },
<add>
<ide> /**
<ide> * Traverses up the ancestors of the supplied node to find a node that is a
<ide> * DOM representation of a React component.
<ide> var ReactInstanceHandles = {
<ide> getFirstReactDOM: function(node) {
<ide> var current = node;
<ide> while (current && current.parentNode !== current) {
<del> if (isRenderedByReact(current)) {
<add> if (ReactInstanceHandles.isRenderedByReact(current)) {
<ide> return current;
<ide> }
<ide> current = current.parentNode;
<ide> var ReactInstanceHandles = {
<ide> );
<ide> return longestCommonID;
<ide> },
<del> /**
<del> * Creates a DOM ID to use when mounting React components.
<del> *
<del> * @param {number} mountPointCount The count of React renders so far.
<del> * @return {string} React root ID.
<del> * @internal
<del> */
<del> getReactRootID: function(mountPointCount) {
<del> return '.reactRoot[' + mountPointCount + ']';
<del> },
<ide>
<ide> /**
<ide> * Gets the DOM ID of the React component that is the root of the tree that
<ide><path>src/core/ReactMount.js
<ide> var ReactEventTopLevelCallback = require('ReactEventTopLevelCallback');
<ide>
<ide> var $ = require('$');
<ide>
<del>var globalMountPointCounter = 0;
<del>
<ide> /** Mapping from reactRoot DOM ID to React component instance. */
<ide> var instanceByReactRootID = {};
<ide>
<ide> /** Mapping from reactRoot DOM ID to `container` nodes. */
<ide> var containersByReactRootID = {};
<ide>
<add>/**
<add> * @param {DOMElement} container DOM element that may contain a React component
<add> * @return {?DOMElement} DOM element that may have the reactRoot ID, or null.
<add> */
<add>function getReactRootElementInContainer(container) {
<add> return container.firstChild;
<add>}
<add>
<ide> /**
<ide> * @param {DOMElement} container DOM element that may contain a React component.
<ide> * @return {?string} A "reactRoot" ID, if a React component is rendered.
<ide> */
<ide> function getReactRootID(container) {
<del> return container.firstChild && container.firstChild.id;
<add> var rootElement = getReactRootElementInContainer(container);
<add> return rootElement && rootElement.id;
<ide> }
<ide>
<ide> /**
<ide> var ReactMount = {
<ide> );
<ide> },
<ide>
<add> /**
<add> * Take a component that's already mounted into the DOM and replace its props
<add> * @param {ReactComponent} prevComponent component instance already in the DOM
<add> * @param {ReactComponent} nextComponent component instance to render
<add> * @param {DOMElement} container container to render into
<add> */
<add> _updateRootComponent: function(prevComponent, nextComponent, container) {
<add> var nextProps = nextComponent.props;
<add> ReactMount.scrollMonitor(container, function() {
<add> prevComponent.replaceProps(nextProps);
<add> });
<add> return prevComponent;
<add> },
<add>
<add> /**
<add> * Register a component into the instance map and start the events system.
<add> * @param {ReactComponent} nextComponent component instance to render
<add> * @param {DOMElement} container container to render into
<add> * @return {string} reactRoot ID prefix
<add> */
<add> _registerComponent: function(nextComponent, container) {
<add> ReactMount.prepareTopLevelEvents(ReactEventTopLevelCallback);
<add>
<add> var reactRootID = ReactMount.registerContainer(container);
<add> instanceByReactRootID[reactRootID] = nextComponent;
<add> return reactRootID;
<add> },
<add>
<add> /**
<add> * Render a new component into the DOM.
<add> * @param {ReactComponent} nextComponent component instance to render
<add> * @param {DOMElement} container container to render into
<add> * @param {boolean} shouldReuseMarkup if we should skip the markup insertion
<add> * @return {ReactComponent} nextComponent
<add> */
<add> _renderNewRootComponent: function(
<add> nextComponent,
<add> container,
<add> shouldReuseMarkup) {
<add> var reactRootID = ReactMount._registerComponent(nextComponent, container);
<add> nextComponent.mountComponentIntoNode(
<add> reactRootID,
<add> container,
<add> shouldReuseMarkup
<add> );
<add> return nextComponent;
<add> },
<add>
<ide> /**
<ide> * Renders a React component into the DOM in the supplied `container`.
<ide> *
<ide> var ReactMount = {
<ide> * @return {ReactComponent} Component instance rendered in `container`.
<ide> */
<ide> renderComponent: function(nextComponent, container) {
<del> var prevComponent = instanceByReactRootID[getReactRootID(container)];
<del> if (prevComponent) {
<del> if (prevComponent.constructor === nextComponent.constructor) {
<del> var nextProps = nextComponent.props;
<del> ReactMount.scrollMonitor(container, function() {
<del> prevComponent.replaceProps(nextProps);
<del> });
<del> return prevComponent;
<add> var registeredComponent = instanceByReactRootID[getReactRootID(container)];
<add>
<add> if (registeredComponent) {
<add> if (registeredComponent.constructor === nextComponent.constructor) {
<add> return ReactMount._updateRootComponent(
<add> registeredComponent,
<add> nextComponent,
<add> container
<add> );
<ide> } else {
<ide> ReactMount.unmountAndReleaseReactRootNode(container);
<ide> }
<ide> }
<ide>
<del> ReactMount.prepareTopLevelEvents(ReactEventTopLevelCallback);
<add> var reactRootElement = getReactRootElementInContainer(container);
<add> var containerHasReactMarkup =
<add> reactRootElement &&
<add> ReactInstanceHandles.isRenderedByReact(reactRootElement);
<ide>
<del> var reactRootID = ReactMount.registerContainer(container);
<del> instanceByReactRootID[reactRootID] = nextComponent;
<del> nextComponent.mountComponentIntoNode(reactRootID, container);
<del> return nextComponent;
<add> var shouldReuseMarkup = containerHasReactMarkup && !registeredComponent;
<add>
<add> return ReactMount._renderNewRootComponent(
<add> nextComponent,
<add> container,
<add> shouldReuseMarkup
<add> );
<ide> },
<ide>
<ide> /**
<ide> var ReactMount = {
<ide> }
<ide> if (!reactRootID) {
<ide> // No valid "reactRoot" ID found, create one.
<del> reactRootID = ReactInstanceHandles.getReactRootID(
<del> globalMountPointCounter++
<del> );
<add> reactRootID = ReactInstanceHandles.createReactRootID();
<ide> }
<ide> containersByReactRootID[reactRootID] = container;
<ide> return reactRootID;
<ide><path>src/environment/ReactServerRendering.js
<add>/**
<add> * @typechecks
<add> * @providesModule ReactServerRendering
<add> */
<add>"use strict";
<add>
<add>var ReactReconcileTransaction = require('ReactReconcileTransaction');
<add>var ReactInstanceHandles = require('ReactInstanceHandles');
<add>
<add>/**
<add> * @param {object} component
<add> * @param {function} callback
<add> */
<add>function renderComponentToString(component, callback) {
<add> // We use a callback API to keep the API async in case in the future we ever
<add> // need it, but in reality this is a synchronous operation.
<add> var id = ReactInstanceHandles.createReactRootID();
<add> var transaction = ReactReconcileTransaction.getPooled();
<add> transaction.reinitializeTransaction();
<add> try {
<add> transaction.perform(function() {
<add> callback(component.mountComponent(id, transaction));
<add> }, null);
<add> } finally {
<add> ReactReconcileTransaction.release(transaction);
<add> }
<add>}
<add>
<add>module.exports = {
<add> renderComponentToString: renderComponentToString
<add>};
<ide><path>src/environment/__tests__/ReactServerRendering-test.js
<add>/**
<add> * @jsx React.DOM
<add> * @emails react-core
<add> */
<add>
<add>"use strict";
<add>
<add>require('mock-modules')
<add> .dontMock('ExecutionEnvironment')
<add> .dontMock('React')
<add> .dontMock('ReactServerRendering')
<add> .dontMock('ReactTestUtils');
<add>
<add>var React;
<add>var ReactTestUtils;
<add>var ReactServerRendering;
<add>var ExecutionEnvironment;
<add>
<add>describe('ReactServerRendering', function() {
<add> beforeEach(function() {
<add> require('mock-modules').dumpCache();
<add> React = require('React');
<add> ReactTestUtils = require('ReactTestUtils');
<add> ExecutionEnvironment = require('ExecutionEnvironment');
<add> ExecutionEnvironment.canUseDOM = false;
<add> ReactServerRendering = require('ReactServerRendering');
<add> });
<add>
<add> it('should generate simple markup', function() {
<add> var response;
<add> ReactServerRendering.renderComponentToString(
<add> <span>hello world</span>,
<add> function(response_) {
<add> response = response_;
<add> }
<add> );
<add> expect(response).toMatch(
<add> '<span id="[^"]+">hello world</span>'
<add> );
<add> });
<add>
<add> it('should render composite components', function() {
<add> var Parent = React.createClass({
<add> render: function() {
<add> return <div><Child name="child" /></div>;
<add> }
<add> });
<add> var Child = React.createClass({
<add> render: function() {
<add> return <span>My name is {this.props.name}</span>;
<add> }
<add> });
<add> var response;
<add> ReactServerRendering.renderComponentToString(
<add> <Parent />,
<add> function(response_) {
<add> response = response_;
<add> }
<add> );
<add> expect(response).toMatch(
<add> '<div id="[^"]+"><span id="[^"]+"><span id="[^"]+">My name is </span>' +
<add> '<span id="[^"]+">child</span></span></div>'
<add> );
<add> });
<add>
<add> it('should only execute certain lifecycle methods', function() {
<add> var lifecycle = [];
<add> var TestComponent = React.createClass({
<add> componentWillMount: function() {
<add> lifecycle.push('componentWillMount');
<add> },
<add> componentDidMount: function() {
<add> lifecycle.push('componentDidMount');
<add> },
<add> getInitialState: function() {
<add> lifecycle.push('getInitialState');
<add> return {name: 'TestComponent'};
<add> },
<add> render: function() {
<add> lifecycle.push('render');
<add> return <span>Component name: {this.state.name}</span>;
<add> },
<add> componentWillUpdate: function() {
<add> lifecycle.push('componentWillUpdate');
<add> },
<add> componentDidUpdate: function() {
<add> lifecycle.push('componentDidUpdate');
<add> },
<add> shouldComponentUpdate: function() {
<add> lifecycle.push('shouldComponentUpdate');
<add> },
<add> componentWillReceiveProps: function() {
<add> lifecycle.push('componentWillReceiveProps');
<add> },
<add> componentWillUnmount: function() {
<add> lifecycle.push('componentWillUnmount');
<add> }
<add> });
<add>
<add> var response;
<add>
<add> ReactServerRendering.renderComponentToString(
<add> <TestComponent />,
<add> function (_response) {
<add> response = _response;
<add> }
<add> );
<add>
<add> expect(response).toMatch(
<add> '<span id="[^"]+"><span id="[^"]+">Component name: </span>' +
<add> '<span id="[^"]+">TestComponent</span></span>'
<add> );
<add> expect(lifecycle).toEqual(
<add> ['getInitialState', 'componentWillMount', 'render']
<add> );
<add> });
<add>
<add> it('should have the correct mounting behavior', function() {
<add> // This test is testing client-side behavior.
<add> ExecutionEnvironment.canUseDOM = true;
<add>
<add> var mountCount = 0;
<add> var numClicks = 0;
<add>
<add> var TestComponent = React.createClass({
<add> componentWillMount: function() {
<add> mountCount++;
<add> },
<add> click: function() {
<add> numClicks++;
<add> },
<add> render: function() {
<add> return (
<add> <span ref="span" onClick={this.click}>Name: {this.props.name}</span>
<add> );
<add> },
<add> });
<add>
<add> var element = document.createElement('div');
<add> React.renderComponent(<TestComponent />, element);
<add>
<add> var lastMarkup = element.innerHTML;
<add>
<add> // Exercise the update path. Markup should not change,
<add> // but some lifecycle methods should be run again.
<add> React.renderComponent(<TestComponent name="x" />, element);
<add> expect(mountCount).toEqual(1);
<add>
<add> // Unmount and remount. We should get another mount event and
<add> // we should get different markup, as the IDs are unique each time.
<add> React.unmountAndReleaseReactRootNode(element);
<add> expect(element.innerHTML).toEqual('');
<add> React.renderComponent(<TestComponent name="x" />, element);
<add> expect(mountCount).toEqual(2);
<add> expect(element.innerHTML).not.toEqual(lastMarkup);
<add>
<add> // Now kill the node and render it on top of the old markup, as if
<add> // we used server rendering. We should mount again, but the markup should be
<add> // unchanged.
<add> lastMarkup = element.innerHTML;
<add> React.unmountAndReleaseReactRootNode(element);
<add> expect(element.innerHTML).toEqual('');
<add> element.innerHTML = lastMarkup;
<add> // NOTE: we pass a different name here. This is to ensure that the markup
<add> // being generated is not replaced.
<add> var instance = React.renderComponent(<TestComponent name="y" />, element);
<add> expect(mountCount).toEqual(3);
<add> expect(element.innerHTML).toEqual(lastMarkup);
<add>
<add> // Ensure the events system works
<add> expect(numClicks).toEqual(0);
<add> ReactTestUtils.Simulate.click(instance.refs.span.getDOMNode());
<add> expect(numClicks).toEqual(1);
<add> });
<add>}); | 6 |
Ruby | Ruby | remove another call to `scope` | ae3269b79b32ecbb141a37b4c8ccf6e330b1a631 | <ide><path>actionpack/lib/action_dispatch/routing/mapper.rb
<ide> def scope(*args)
<ide> # controller "food" do
<ide> # match "bacon", action: :bacon, via: :get
<ide> # end
<del> def controller(controller, options={})
<del> options[:controller] = controller
<del> scope(options) { yield }
<add> def controller(controller)
<add> controller_scope(controller) do
<add> yield
<add> end
<ide> end
<ide>
<ide> # Scopes routes to a specific namespace. For example: | 1 |
Python | Python | update structured array docs to reflect , fixups | a08da3f34e8c1fe7e8997f254acf1c92eea520f9 | <ide><path>numpy/doc/structured_arrays.py
<ide> structured datatypes, and it may also be a :term:`sub-array` which behaves like
<ide> an ndarray of a specified shape. The offsets of the fields are arbitrary, and
<ide> fields may even overlap. These offsets are usually determined automatically by
<del>numpy, but can also be manually specified.
<add>numpy, but can also be specified.
<ide>
<ide> Structured Datatype Creation
<ide> ----------------------------
<ide> Each tuple has the form ``(fieldname, datatype, shape)`` where shape is
<ide> optional. ``fieldname`` is a string (or tuple if titles are used, see
<ide> :ref:`Field Titles <titles>` below), ``datatype`` may be any object
<del> convertible to a datatype, and shape (optional) is a tuple of integers
<del> specifying subarray shape.
<add> convertible to a datatype, and ``shape`` is a tuple of integers specifying
<add> subarray shape.
<ide>
<ide> >>> np.dtype([('x', 'f4'), ('y', np.float32), ('z', 'f4', (2,2))])
<ide> dtype=[('x', '<f4'), ('y', '<f4'), ('z', '<f4', (2, 2))])
<ide> and the overall itemsize of a structured datatype, depending on whether
<ide> ``align=True`` was specified as a keyword argument to :func:`numpy.dtype`.
<ide>
<del>By default (with ``align=False``), numpy will pack the fields together tightly
<del>such that each field starts at the byte offset the previous field ended, and the
<del>fields are contiguous in memory. ::
<add>By default (``align=False``), numpy will pack the fields together such that
<add>each field starts at the byte offset the previous field ended, and the fields
<add>are contiguous in memory. ::
<ide>
<ide> >>> def print_offsets(d):
<ide> ... print("offsets:", [d.fields[name][1] for name in d.names])
<ide> compilers would pad a C-struct. Aligned structures can give a performance
<ide> improvement in some cases, at the cost of increased datatype size. Padding
<ide> bytes are inserted between fields such that each field's byte offset will be a
<del>multiple of that field's alignment (usually equal to the field's size in bytes
<del>for simple datatypes, see :c:member:`PyArray_Descr.alignment`).
<del>The structure will also have trailing padding added so that its itemsize is a
<add>multiple of that field's alignment, which is usually equal to the field's size
<add>in bytes for simple datatypes, see :c:member:`PyArray_Descr.alignment`. The
<add>structure will also have trailing padding added so that its itemsize is a
<ide> multiple of the largest field's alignment. ::
<ide>
<ide> >>> print_offsets(np.dtype('u1,u1,i4,u1,i8,u2', align=True))
<ide> Note that although almost all modern C compilers pad in this way by default,
<ide> padding in C structs is C-implementation-dependent so this memory layout is not
<ide> guaranteed to exactly match that of a corresponding struct in a C program. Some
<del>massaging may be needed either on the numpy side or the C side to obtain exact
<add>work may be needed, either on the numpy side or the C side, to obtain exact
<ide> correspondence.
<ide>
<del>If offsets were specified manually using the optional ``offsets`` key in the
<add>If offsets were specified using the optional ``offsets`` key in the
<ide> dictionary-based dtype specification, setting ``align=True`` will check that
<ide> each field's offset is a multiple of its size and that the itemsize is a
<ide> multiple of the largest field size, and raise an exception if not.
<ide>
<ide> In addition to field names, fields may also have an associated :term:`title`,
<ide> an alternate name, which is sometimes used as an additional description or
<del>mnemonic for the field. The title may be used to index an array, just like a
<del>fieldname.
<add>alias for the field. The title may be used to index an array, just like a
<add>field name.
<ide>
<ide> To add titles when using the list-of-tuples form of dtype specification, the
<del>fieldname may be be specified as a tuple of two strings (instead of a single
<del>string), which will be the field's title and field name respectively. For
<add>field name may be be specified as a tuple of two strings instead of a single
<add>string, which will be the field's title and field name respectively. For
<ide> example::
<ide>
<ide> >>> np.dtype([(('my title', 'name'), 'f4')])
<ide> The ``dtype.fields`` dictionary will contain :term:`titles` as keys, if any
<ide> titles are used. This means effectively that a field with a title will be
<ide> represented twice in the fields dictionary. The tuple values for these fields
<del>will also have a third element, the field title.
<del>
<del>Because of this, and because the ``names`` attribute preserves the field order
<del>while the ``fields`` attribute may not, it is recommended to iterate through
<del>the fields of a dtype using the ``names`` attribute of the dtype (which will
<del>not list titles), as in::
<add>will also have a third element, the field title. Because of this, and because
<add>the ``names`` attribute preserves the field order while the ``fields``
<add>attribute may not, it is recommended to iterate through the fields of a dtype
<add>using the ``names`` attribute of the dtype, which will not list titles, as
<add>in::
<ide>
<ide> >>> for name in d.names:
<ide> ... print(d.fields[name][:2])
<ide> Assignment from Python Native Types (Tuples)
<ide> ```````````````````````````````````````````
<ide>
<del>The simplest way to assign values to a structured array is using python
<del>tuples. Each assigned value should be a tuple (and not a list or array, as
<del>these will trigger numpy's broadcasting rules) of length equal to the number of
<del>fields in the array. The tuple's elements are assigned to the successive fields
<add>The simplest way to assign values to a structured array is using python tuples.
<add>Each assigned value should be a tuple of length equal to the number of fields
<add>in the array, and not a list or array as these will trigger numpy's
<add>broadcasting rules. The tuple's elements are assigned to the successive fields
<ide> of the array, from left to right::
<ide>
<ide> >>> x = np.array([(1,2,3),(4,5,6)], dtype='i8,f4,f8')
<ide> ```````````````````````
<ide>
<ide> A scalar assigned to a structured element will be assigned to all fields. This
<del>happens when a scalar is assigned to a structured array, or when a scalar array
<del>is assigned to a structured array::
<add>happens when a scalar is assigned to a structured array, or when an
<add>unstructured array is assigned to a structured array::
<ide>
<ide> >>> x = np.zeros(2, dtype='i8,f4,?,S1')
<ide> >>> x[:] = 3
<ide> array([(0, 0.0, False, b'0'), (1, 1.0, True, b'1')],
<ide> dtype=[('f0', '<i8'), ('f1', '<f4'), ('f2', '?'), ('f3', 'S1')])
<ide>
<del>Structured arrays can also be assigned to scalar arrays, but only if the
<add>Structured arrays can also be assigned to unstructured arrays, but only if the
<ide> structured datatype has just a single field::
<ide>
<del> >>> x = np.zeros(2, dtype=[('A', 'i4'), ('B', 'i4')])
<del> >>> y = np.zeros(2, dtype=[('A', 'i4')])
<del> >>> a = np.zeros(2, dtype='i4')
<del> >>> a[:] = x
<add> >>> twofield = np.zeros(2, dtype=[('A', 'i4'), ('B', 'i4')])
<add> >>> onefield = np.zeros(2, dtype=[('A', 'i4')])
<add> >>> nostruct = np.zeros(2, dtype='i4')
<add> >>> nostruct[:] = twofield
<ide> ValueError: Can't cast from structure to non-structure, except if the structure only has a single field.
<del> >>> a[:] = y
<del> >>> a
<add> >>> nostruct[:] = onefield
<add> >>> nostruct
<ide> array([0, 0], dtype=int32)
<ide>
<ide> Assignment from other Structured Arrays
<ide> dtype=[('foo', '<i8'), ('bar', '<f4')])
<ide>
<ide> This view has the same dtype and itemsize as the indexed field, so it is
<del>typically a non-structured array (except in the case of nested structures).
<add>typically a non-structured array, except in the case of nested structures.
<ide>
<ide> >>> y.dtype, y.shape, y.strides
<ide> (dtype('float32'), (2,), (12,))
<ide> dtype=[('a', '<i8'), ('b', '<i4'), ('c', '<f8')])
<ide>
<ide> The resulting array is a view into the original array, such that assignment to
<del>the view modifies the original array. This view's fields will be in the order
<add>the view modifies the original array. The view's fields will be in the order
<ide> they were indexed. Note that unlike for single-field indexing, the view's dtype
<del>has the same itemsize as the original array and has fields at the same offsets
<add>has the same itemsize as the original array, and has fields at the same offsets
<ide> as in the original array, and unindexed fields are merely missing.
<ide>
<del>Since this view is a structured array itself, it obeys the assignment rules
<add>Since the view is a structured array itself, it obeys the assignment rules
<ide> described above. For example, this means that one can swap the values of two
<ide> fields using appropriate multi-field indexes::
<ide>
<ide> >>> type(scalar)
<ide> numpy.void
<ide>
<del>Importantly, unlike other numpy scalars, structured scalars are mutable and act
<del>like views into the original array, such that modifying the scalar will modify
<del>the original array. Structured scalars also support access and assignment by
<del>field name::
<add>Unlike other numpy scalars, structured scalars are mutable and act like views
<add>into the original array, such that modifying the scalar will modify the
<add>original array. Structured scalars also support access and assignment by field
<add>name::
<ide>
<ide> >>> x = np.array([(1,2),(3,4)], dtype=[('foo', 'i8'), ('bar', 'f4')])
<ide> >>> s = x[0]
<ide> 1
<ide> >>> scalar[1] = 4
<ide>
<del>Thus, tuples might be though of as the native Python equivalent to numpy's
<add>Thus, tuples might be thought of as the native Python equivalent to numpy's
<ide> structured types, much like native python integers are the equivalent to
<ide> numpy's integer types. Structured scalars may be converted to a tuple by
<ide> calling :func:`ndarray.item`::
<ide> Viewing Structured Arrays Containing Objects
<ide> --------------------------------------------
<ide>
<del>In order to prevent clobbering of object pointers in fields of
<add>In order to prevent clobbering object pointers in fields of
<ide> :class:`numpy.object` type, numpy currently does not allow views of structured
<ide> arrays containing objects.
<ide>
<ide> Structure Comparison
<ide> --------------------
<ide>
<del>If the dtypes of two structured arrays are equivalent, testing the equality of
<del>the arrays will result in a boolean array with the dimension of the original
<del>arrays, with elements set to True where all fields of the corresponding
<del>structures are equal. Structured dtypes are equivalent if the field names,
<add>If the dtypes of two void structured arrays are equal, testing the equality of
<add>the arrays will result in a boolean array with the dimensions of the original
<add>arrays, with elements set to ``True`` where all fields of the corresponding
<add>structures are equal. Structured dtypes are equal if the field names,
<ide> dtypes and titles are the same, ignoring endianness, and the fields are in
<ide> the same order::
<ide>
<ide> >>> a == b
<ide> array([False, False], dtype=bool)
<ide>
<del>Currently, if the dtypes of two arrays are not equivalent all comparisons will
<del>return ``False``. This behavior is deprecated as of numpy 1.10 and may change
<del>in the future.
<add>Currently, if the dtypes of two void structured arrays are not equivalent the
<add>comparison fails, returning the scalar value ``False``. This behavior is
<add>deprecated as of numpy 1.10 and will raise an error or perform elementwise
<add>comparison in the future.
<ide>
<del>Currently, the ``<`` and ``>`` operators will always return ``False`` when
<del>comparing structured arrays. Many other pairwise operators are not supported.
<add>The ``<`` and ``>`` operators always return ``False`` when comparing void
<add>structured arrays, and arithmetic and bitwise operations are not supported.
<ide>
<ide> Record Arrays
<ide> =============
<ide>
<ide> As an optional convenience numpy provides an ndarray subclass,
<ide> :class:`numpy.recarray`, and associated helper functions in the
<del>:mod:`numpy.rec` submodule, which allows access to fields of structured arrays
<del>by attribute, instead of only by index. Record arrays also use a special
<del>datatype, :class:`numpy.record`, which allows field access by attribute on the
<add>:mod:`numpy.rec` submodule, that allows access to fields of structured arrays
<add>by attribute instead of only by index. Record arrays also use a special
<add>datatype, :class:`numpy.record`, that allows field access by attribute on the
<ide> structured scalars obtained from the array.
<ide>
<ide> The simplest way to create a record array is with :func:`numpy.rec.array`:: | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.