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
|
---|---|---|---|---|---|
Python | Python | add __doc__ to minimum | 156af61c8d19024bb9a71436d645b019cf35670b | <ide><path>numpy/ma/core.py
<ide> class _extrema_operation(object):
<ide> `_minimum_operation`.
<ide>
<ide> """
<del>
<del> @property
<del> def __name__(self):
<del> return self.ufunc.__name__
<add> def __init__(self, ufunc, compare, fill_value):
<add> self.ufunc = ufunc
<add> self.compare = compare
<add> self.fill_value_func = fill_value
<add> self.__doc__ = ufunc.__doc__
<add> self.__name__ = ufunc.__name__
<ide>
<ide> def __call__(self, a, b=None):
<ide> "Executes the call behavior."
<ide> def outer(self, a, b):
<ide> result._mask = m
<ide> return result
<ide>
<del>
<del>class _minimum_operation(_extrema_operation):
<del>
<del> "Object to calculate minima"
<del>
<del> def __init__(self):
<del> """minimum(a, b) or minimum(a)
<del>In one argument case, returns the scalar minimum.
<del> """
<del> self.ufunc = umath.minimum
<del> self.compare = less
<del> self.fill_value_func = minimum_fill_value
<del>
<del>
<del>class _maximum_operation(_extrema_operation):
<del>
<del> "Object to calculate maxima"
<del>
<del> def __init__(self):
<del> """maximum(a, b) or maximum(a)
<del> In one argument case returns the scalar maximum.
<del> """
<del> self.ufunc = umath.maximum
<del> self.compare = greater
<del> self.fill_value_func = maximum_fill_value
<del>
<ide> def min(obj, axis=None, out=None, fill_value=None, keepdims=np._NoValue):
<ide> kwargs = {} if keepdims is np._NoValue else {'keepdims': keepdims}
<ide>
<ide> def __call__(self, a, *args, **params):
<ide> diagonal = _frommethod('diagonal')
<ide> harden_mask = _frommethod('harden_mask')
<ide> ids = _frommethod('ids')
<del>maximum = _maximum_operation()
<add>maximum = _extrema_operation(umath.maximum, greater, maximum_fill_value)
<ide> mean = _frommethod('mean')
<del>minimum = _minimum_operation()
<add>minimum = _extrema_operation(umath.minimum, less, minimum_fill_value)
<ide> nonzero = _frommethod('nonzero')
<ide> prod = _frommethod('prod')
<ide> product = _frommethod('prod') | 1 |
Python | Python | improve error message when scons command fails | 4db04374b605c4b7a11ff90afc48d169bcefacb9 | <ide><path>numpy/distutils/command/scons.py
<ide> def run(self):
<ide> log.info("======== Executing scons command for pkg %s =========", pkg_name)
<ide> st = os.system(cmdstr)
<ide> if st:
<del> print "status is %d" % st
<del> msg = "Error while executing scons command %s (see above)" \
<del> % cmdstr
<del> msg += """
<del> Try executing the scons command with --log-level option for more detailed
<del> output, for example --log-level=0; the lowest, the more detailed"""
<add> #print "status is %d" % st
<add> msg = "Error while executing scons command."
<add> msg += " See above for more information.\n"
<add> msg += """\
<add>If you think it is a problem in numscons, you can also try executing the scons
<add>command with --log-level option for more detailed output of what numscons is
<add>doing, for example --log-level=0; the lowest the level is, the more detailed
<add>the output it."""
<ide> raise DistutilsExecError(msg)
<ide> if post_hook:
<ide> post_hook(**{'pkg_name': pkg_name, 'scons_cmd' : self}) | 1 |
Go | Go | add some verbosity to the push/pull | 966cddf26bc5e86c47faab0ddc69b42e9bd8a9f2 | <ide><path>commands.go
<ide> func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> // If it fails, try to get the repository
<ide> if localRepo, exists := srv.runtime.repositories.Repositories[local]; exists {
<ide> fmt.Fprintf(stdout, "Pushing %s (%d tags) on %s...\n", local, len(localRepo), remote)
<del> if err := srv.runtime.graph.PushRepository(remote, localRepo, srv.runtime.authConfig); err != nil {
<add> if err := srv.runtime.graph.PushRepository(stdout, remote, localRepo, srv.runtime.authConfig); err != nil {
<ide> return err
<ide> }
<ide> fmt.Fprintf(stdout, "Push completed\n")
<ide> func (srv *Server) CmdPush(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> return nil
<ide> }
<ide> fmt.Fprintf(stdout, "Pushing image %s..\n", img.Id)
<del> err = srv.runtime.graph.PushImage(img, srv.runtime.authConfig)
<add> err = srv.runtime.graph.PushImage(stdout, img, srv.runtime.authConfig)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> func (srv *Server) CmdPull(stdin io.ReadCloser, stdout io.Writer, args ...string
<ide> }
<ide> // FIXME: Allow pull repo:tag
<ide> fmt.Fprintf(stdout, "Pulling %s...\n", remote)
<del> if err := srv.runtime.graph.PullRepository(remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
<add> if err := srv.runtime.graph.PullRepository(stdout, remote, "", srv.runtime.repositories, srv.runtime.authConfig); err != nil {
<ide> return err
<ide> }
<ide> fmt.Fprintf(stdout, "Pull completed\n")
<ide><path>registry.go
<ide> const REGISTRY_ENDPOINT = auth.REGISTRY_SERVER + "/v1"
<ide> func NewImgJson(src []byte) (*Image, error) {
<ide> ret := &Image{}
<ide>
<del> fmt.Printf("Json string: {%s}\n", src)
<add> Debugf("Json string: {%s}\n", src)
<ide> // FIXME: Is there a cleaner way to "puryfy" the input json?
<ide> src = []byte(strings.Replace(string(src), "null", "\"\"", -1))
<ide>
<ide> func (graph *Graph) PullImage(imgId string, authConfig *auth.AuthConfig) error {
<ide> }
<ide>
<ide> // FIXME: Handle the askedTag parameter
<del>func (graph *Graph) PullRepository(remote, askedTag string, repositories *TagStore, authConfig *auth.AuthConfig) error {
<add>func (graph *Graph) PullRepository(stdout io.Writer, remote, askedTag string, repositories *TagStore, authConfig *auth.AuthConfig) error {
<ide> client := &http.Client{}
<ide>
<del> fmt.Printf("Pulling repo: %s\n", REGISTRY_ENDPOINT+"/users/"+remote)
<add> fmt.Fprintf(stdout, "Pulling repo: %s\n", REGISTRY_ENDPOINT+"/users/"+remote)
<ide>
<ide> req, err := http.NewRequest("GET", REGISTRY_ENDPOINT+"/users/"+remote, nil)
<ide> if err != nil {
<ide> func (graph *Graph) PullRepository(remote, askedTag string, repositories *TagSto
<ide> }
<ide>
<ide> // Push a local image to the registry with its history if needed
<del>func (graph *Graph) PushImage(imgOrig *Image, authConfig *auth.AuthConfig) error {
<add>func (graph *Graph) PushImage(stdout io.Writer, imgOrig *Image, authConfig *auth.AuthConfig) error {
<ide> client := &http.Client{}
<ide>
<ide> // FIXME: Factorize the code
<ide> func (graph *Graph) PushImage(imgOrig *Image, authConfig *auth.AuthConfig) error
<ide> return fmt.Errorf("Error while retreiving the path for {%s}: %s", img.Id, err)
<ide> }
<ide>
<del> Debugf("Pushing image [%s] on {%s}\n", img.Id, REGISTRY_ENDPOINT+"/images/"+img.Id+"/json")
<add> fmt.Fprintf(stdout, "Pushing image [%s] on {%s}\n", img.Id, REGISTRY_ENDPOINT+"/images/"+img.Id+"/json")
<ide>
<ide> // FIXME: try json with UTF8
<ide> jsonData := strings.NewReader(string(jsonRaw))
<ide> func (graph *Graph) PushImage(imgOrig *Image, authConfig *auth.AuthConfig) error
<ide> "Error: Internal server error trying to push image {%s} (json): %s",
<ide> img.Id, err)
<ide> }
<del> fmt.Printf("Pushing return status: %d\n", res.StatusCode)
<add> Debugf("Pushing return status: %d\n", res.StatusCode)
<ide> switch res.StatusCode {
<ide> case 204:
<ide> // Case where the image is already on the Registry
<ide> // FIXME: Do not be silent?
<add> fmt.Fprintf(stdout, "The image %s is already up to date on the registry.\n", img.Id)
<ide> return nil
<ide> case 400:
<ide> return fmt.Errorf("Error: Invalid Json")
<ide> func (graph *Graph) pushTag(remote, revision, tag string, authConfig *auth.AuthC
<ide> }
<ide> return err
<ide> }
<del> fmt.Printf("Result of push tag: %d\n", res.StatusCode)
<add> Debugf("Result of push tag: %d\n", res.StatusCode)
<ide> switch res.StatusCode {
<ide> default:
<ide> return fmt.Errorf("Error %d\n", res.StatusCode)
<ide> func (graph *Graph) LookupRemoteRepository(remote string, authConfig *auth.AuthC
<ide> return true
<ide> }
<ide>
<del>func (graph *Graph) pushPrimitive(remote, tag, imgId string, authConfig *auth.AuthConfig) error {
<add>func (graph *Graph) pushPrimitive(stdout io.Writer, remote, tag, imgId string, authConfig *auth.AuthConfig) error {
<ide> // CHeck if the local impage exists
<ide> img, err := graph.Get(imgId)
<ide> if err != nil {
<ide> return err
<ide> }
<ide> // Push the image
<del> if err = graph.PushImage(img, authConfig); err != nil {
<add> if err = graph.PushImage(stdout, img, authConfig); err != nil {
<ide> return err
<ide> }
<ide> // And then the tag
<ide> func (graph *Graph) pushPrimitive(remote, tag, imgId string, authConfig *auth.Au
<ide>
<ide> // Push a repository to the registry.
<ide> // Remote has the format '<user>/<repo>
<del>func (graph *Graph) PushRepository(remote string, localRepo Repository, authConfig *auth.AuthConfig) error {
<add>func (graph *Graph) PushRepository(stdout io.Writer, remote string, localRepo Repository, authConfig *auth.AuthConfig) error {
<ide> // Check if the remote repository exists
<ide> // FIXME: @lopter How to handle this?
<ide> // if !graph.LookupRemoteRepository(remote, authConfig) {
<ide> func (graph *Graph) PushRepository(remote string, localRepo Repository, authConf
<ide>
<ide> // For each image within the repo, push them
<ide> for tag, imgId := range localRepo {
<del> if err := graph.pushPrimitive(remote, tag, imgId, authConfig); err != nil {
<add> if err := graph.pushPrimitive(stdout, remote, tag, imgId, authConfig); err != nil {
<ide> // FIXME: Continue on error?
<ide> return err
<ide> } | 2 |
Ruby | Ruby | add missing punctuation mark [ci skip] | 762f7daf55a91d2a20bedb4906c9dd04e031d74e | <ide><path>actionpack/lib/abstract_controller/base.rb
<ide> def inherited(klass) # :nodoc:
<ide> # instance methods on that abstract class. Public instance methods of
<ide> # a controller would normally be considered action methods, so methods
<ide> # declared on abstract classes are being removed.
<del> # (ActionController::Metal and ActionController::Base are defined as abstract)
<add> # (<tt>ActionController::Metal</tt> and ActionController::Base are defined as abstract)
<ide> def internal_methods
<ide> controller = self
<ide>
<ide> def action_methods
<ide>
<ide> # action_methods are cached and there is sometimes need to refresh
<ide> # them. ::clear_action_methods! allows you to do that, so next time
<del> # you run action_methods, they will be recalculated
<add> # you run action_methods, they will be recalculated.
<ide> def clear_action_methods!
<ide> @action_methods = nil
<ide> end
<ide><path>actionpack/lib/action_controller/metal.rb
<ide> def params=(val)
<ide>
<ide> alias :response_code :status # :nodoc:
<ide>
<del> # Basic url_for that can be overridden for more robust functionality
<add> # Basic url_for that can be overridden for more robust functionality.
<ide> def url_for(string)
<ide> string
<ide> end | 2 |
Javascript | Javascript | get backend challenge data on challenge mount | 71cf4495cbf19d785c83a4027348db83939db50c | <ide><path>client/src/templates/Challenges/redux/index.js
<ide> export const isResetModalOpenSelector = state => state[ns].modal.reset;
<ide> export const isBuildEnabledSelector = state => state[ns].isBuildEnabled;
<ide> export const successMessageSelector = state => state[ns].successMessage;
<ide>
<del>export const backendFormValuesSelector = state => state.form[backendNS];
<add>export const backendFormValuesSelector = state => state.form[backendNS] || {};
<ide> export const projectFormValuesSelector = state =>
<ide> state[ns].projectFormValues || {};
<ide>
<ide> export const challengeDataSelector = state => {
<ide> files: challengeFilesSelector(state)
<ide> };
<ide> } else if (challengeType === challengeTypes.backend) {
<del> const {
<del> solution: { value: url }
<del> } = backendFormValuesSelector(state);
<add> const { solution: { value: url } = {} } = backendFormValuesSelector(state);
<ide> challengeData = {
<ide> ...challengeData,
<ide> url | 1 |
PHP | PHP | add new style get methods to event | c013f513cbe3d44c6fa85230922892cca2acaac5 | <ide><path>src/Event/Event.php
<ide> public function __set($attribute, $value)
<ide> * Returns the name of this event. This is usually used as the event identifier
<ide> *
<ide> * @return string
<add> * @deprecated 3.4.0 use getName() instead.
<ide> */
<ide> public function name()
<ide> {
<ide> return $this->_name;
<ide> }
<ide>
<add> /**
<add> * Returns the name of this event. This is usually used as the event identifier
<add> *
<add> * @return string
<add> */
<add> public function getName()
<add> {
<add> return $this->_name;
<add> }
<add>
<ide> /**
<ide> * Returns the subject of this event
<ide> *
<ide> * @return object
<add> * @deprecated 3.4.0 use getSubject() instead.
<ide> */
<ide> public function subject()
<ide> {
<ide> return $this->_subject;
<ide> }
<ide>
<add> /**
<add> * Returns the subject of this event
<add> *
<add> * @return object
<add> */
<add> public function getSubject()
<add> {
<add> return $this->_subject;
<add> }
<add>
<ide> /**
<ide> * Stops the event from being used anymore
<ide> *
<ide> public function isStopped()
<ide> * The result value of the event listeners
<ide> *
<ide> * @return mixed
<add> * @deprecated 3.4.0 use getResult() instead.
<ide> */
<ide> public function result()
<ide> {
<ide> return $this->_result;
<ide> }
<ide>
<add> /**
<add> * The result value of the event listeners
<add> *
<add> * @return mixed
<add> */
<add> public function getResult()
<add> {
<add> return $this->_result;
<add> }
<add>
<ide> /**
<ide> * Listeners can attach a result value to the event.
<ide> *
<ide> public function setResult($value = null)
<ide> * @param string|null $key The data payload element to return, or null to return all data.
<ide> * @return array|mixed|null The data payload if $key is null, or the data value for the given $key. If the $key does not
<ide> * exist a null value is returned.
<add> * @deprecated 3.4.0 use getData() instead.
<ide> */
<ide> public function data($key = null)
<add> {
<add> return $this->getData($key);
<add> }
<add>
<add> /**
<add> * Access the event data/payload.
<add> *
<add> * @param string|null $key The data payload element to return, or null to return all data.
<add> * @return array|mixed|null The data payload if $key is null, or the data value for the given $key. If the $key does not
<add> * exist a null value is returned.
<add> */
<add> public function getData($key = null)
<ide> {
<ide> if ($key !== null) {
<ide> return isset($this->_data[$key]) ? $this->_data[$key] : null;
<ide><path>tests/TestCase/Event/EventTest.php
<ide> public function testName()
<ide> {
<ide> $event = new Event('fake.event');
<ide> $this->assertEquals('fake.event', $event->name());
<add> $this->assertEquals('fake.event', $event->getName());
<ide> }
<ide>
<ide> /**
<ide> public function testSubject()
<ide> {
<ide> $event = new Event('fake.event', $this);
<ide> $this->assertSame($this, $event->subject());
<add> $this->assertSame($this, $event->getSubject());
<ide>
<ide> $event = new Event('fake.event');
<ide> $this->assertNull($event->subject());
<ide> public function testEventData()
<ide> {
<ide> $event = new Event('fake.event', $this, ['some' => 'data']);
<ide> $this->assertEquals(['some' => 'data'], $event->data());
<add> $this->assertEquals(['some' => 'data'], $event->getData());
<add>
<add> $this->assertEquals('data', $event->getData('some'));
<add> $this->assertNull($event->getData('undef'));
<ide> }
<ide>
<ide> /** | 2 |
Text | Text | add localport to http.request() options | 9092afd1764a729c774f54a1e5cc4679d279c7bc | <ide><path>doc/api/http.md
<ide> changes:
<ide> avoided. See [`--insecure-http-parser`][] for more information.
<ide> **Default:** `false`
<ide> * `localAddress` {string} Local interface to bind for network connections.
<add> * `localPort` {number} Local port to connect from.
<ide> * `lookup` {Function} Custom lookup function. **Default:** [`dns.lookup()`][].
<ide> * `maxHeaderSize` {number} Optionally overrides the value of
<ide> [`--max-http-header-size`][] for requests received from the server, i.e. | 1 |
Python | Python | add paused column to `dags list` sub-command | 3ff5a35494271dac1b8a4d0051cfc8644a9d0aba | <ide><path>airflow/cli/commands/dag_command.py
<ide> def dag_list_dags(args):
<ide> "dag_id": x.dag_id,
<ide> "filepath": x.filepath,
<ide> "owner": x.owner,
<add> "paused": x.get_is_paused(),
<ide> },
<ide> )
<ide>
<ide><path>airflow/models/dag.py
<ide> def concurrency_reached(self):
<ide> return self.get_concurrency_reached()
<ide>
<ide> @provide_session
<del> def get_is_paused(self, session=None):
<add> def get_is_paused(self, session=None) -> Optional[None]:
<ide> """Returns a boolean indicating whether this DAG is paused"""
<ide> qry = session.query(DagModel).filter(DagModel.dag_id == self.dag_id)
<ide> return qry.value(DagModel.is_paused)
<ide><path>tests/cli/commands/test_dag_command.py
<ide> def test_cli_list_dags(self):
<ide> out = temp_stdout.getvalue()
<ide> self.assertIn("owner", out)
<ide> self.assertIn("airflow", out)
<add> self.assertIn("paused", out)
<ide> self.assertIn("airflow/example_dags/example_complex.py", out)
<add> self.assertIn("False", out)
<ide>
<ide> def test_cli_list_dag_runs(self):
<ide> dag_command.dag_trigger( | 3 |
Python | Python | add base for seq2seq finetuning | d889e0b71beb12511b7fcc346113035e0115ef0c | <ide><path>examples/run_seq2seq_finetuning.py
<add># coding=utf-8
<add># Copyright 2018 The Google AI Language Team Authors and The HuggingFace Inc. team.
<add># Copyright (c) 2018 Microsoft and The HuggingFace Inc. All rights reserved.
<add>#
<add># Licensed under the Apache License, Version 2.0 (the "License");
<add># you may not use this file except in compliance with the License.
<add># You may obtain a copy of the License at
<add>#
<add># http://www.apache.org/licenses/LICENSE-2.0
<add>#
<add># Unless required by applicable law or agreed to in writing, software
<add># distributed under the License is distributed on an "AS IS" BASIS,
<add># WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
<add># See the License for the specific language governing permissions and
<add># limitations under the License.
<add>""" Finetuning seq2seq models for sequence generation.
<add>
<add>We use the procedure described in [1] to finetune models for sequence
<add>generation. Let S1 and S2 be the source and target sequence respectively; we
<add>pack them using the start of sequence [SOS] and end of sequence [EOS] token:
<add>
<add> [SOS] S1 [EOS] S2 [EOS]
<add>
<add>We then mask a fixed percentage of token from S2 at random and learn to predict
<add>the masked words. [EOS] can be masked during finetuning so the model learns to
<add>terminate the generation process.
<add>
<add>[1] Dong Li, Nan Yang, Wenhui Wang, Furu Wei, Xiaodong Liu, Yu Wang, Jianfeng
<add>Gao, Ming Zhou, and Hsiao-Wuen Hon. “Unified Language Model Pre-Training for
<add>Natural Language Understanding and Generation.” (May 2019) ArXiv:1905.03197
<add>"""
<add>
<add>import logging
<add>import random
<add>
<add>import numpy as np
<add>import torch
<add>
<add>logger = logging.getLogger(__name__)
<add>
<add>
<add>def set_seed(args):
<add> random.seed(args.seed)
<add> np.random.seed(args.seed)
<add> torch.manual_seed(args.seed)
<add> if args.n_gpu > 0:
<add> torch.cuda.manual_seed_all(args.seed)
<add>
<add>
<add>def train(args, train_dataset, model, tokenizer):
<add> """ Fine-tune the pretrained model on the corpus. """
<add> # Data sampler
<add> # Data loader
<add> # Training
<add> raise NotImplementedError
<add>
<add>
<add>def evaluate(args, model, tokenizer, prefix=""):
<add> raise NotImplementedError
<add>
<add>
<add>def main():
<add> raise NotImplementedError
<add>
<add>
<add>def __main__():
<add> main() | 1 |
Go | Go | fix tests after cli update | 73e2f55543346b285585f350e53f82ae419f8849 | <ide><path>integration-cli/docker_cli_config_test.go
<ide> func (s *DockerSuite) TestConfigHTTPHeader(c *check.C) {
<ide> c.Assert(headers["User-Agent"], checker.NotNil, check.Commentf("Missing User-Agent"))
<ide>
<ide> //TODO(tiborvass): restore dockerversion.Version instead of library-import
<del> c.Assert(headers["User-Agent"][0], checker.Equals, "Docker-Client/library-import ("+runtime.GOOS+")", check.Commentf("Badly formatted User-Agent,out:%v", result.Combined()))
<add> c.Assert(headers["User-Agent"][0], checker.Equals, "Docker-Client/unknown-version ("+runtime.GOOS+")", check.Commentf("Badly formatted User-Agent,out:%v", result.Combined()))
<ide>
<ide> c.Assert(headers["Myheader"], checker.NotNil)
<ide> c.Assert(headers["Myheader"][0], checker.Equals, "MyValue", check.Commentf("Missing/bad header,out:%v", result.Combined()))
<ide><path>integration-cli/docker_cli_exec_test.go
<ide> func (s *DockerSuite) TestExecPausedContainer(c *check.C) {
<ide> ContainerID := strings.TrimSpace(out)
<ide>
<ide> dockerCmd(c, "pause", "testing")
<del> out, _, err := dockerCmdWithError("exec", "-i", "-t", ContainerID, "echo", "hello")
<add> out, _, err := dockerCmdWithError("exec", ContainerID, "echo", "hello")
<ide> c.Assert(err, checker.NotNil, check.Commentf("container should fail to exec new command if it is paused"))
<ide>
<ide> expected := ContainerID + " is paused, unpause the container before exec" | 2 |
Ruby | Ruby | add more test cases for adding primary key | 6783bcab7ab11f2ced4b711d3518422e35e3dc01 | <ide><path>activerecord/test/cases/adapters/sqlite3/sqlite3_adapter_test.rb
<ide> def test_copy_table_with_composite_primary_keys
<ide> Barcode.reset_column_information
<ide> end
<ide>
<add> def test_custom_primary_key_in_create_table
<add> connection = Barcode.connection
<add> connection.create_table :barcodes, id: false, force: true do |t|
<add> t.primary_key :id, :string
<add> end
<add>
<add> assert_equal "id", connection.primary_key("barcodes")
<add>
<add> custom_pk = Barcode.columns_hash["id"]
<add>
<add> assert_equal :string, custom_pk.type
<add> assert_not custom_pk.null
<add> ensure
<add> Barcode.reset_column_information
<add> end
<add>
<add> def test_custom_primary_key_in_change_table
<add> connection = Barcode.connection
<add> connection.create_table :barcodes, id: false, force: true do |t|
<add> t.integer :dummy
<add> end
<add> connection.change_table :barcodes do |t|
<add> t.primary_key :id, :string
<add> end
<add>
<add> assert_equal "id", connection.primary_key("barcodes")
<add>
<add> custom_pk = Barcode.columns_hash["id"]
<add>
<add> assert_equal :string, custom_pk.type
<add> assert_not custom_pk.null
<add> ensure
<add> Barcode.reset_column_information
<add> end
<add>
<add> def test_add_column_with_custom_primary_key
<add> connection = Barcode.connection
<add> connection.create_table :barcodes, id: false, force: true do |t|
<add> t.integer :dummy
<add> end
<add> connection.add_column :barcodes, :id, :string, primary_key: true
<add>
<add> assert_equal "id", connection.primary_key("barcodes")
<add>
<add> custom_pk = Barcode.columns_hash["id"]
<add>
<add> assert_equal :string, custom_pk.type
<add> assert_not custom_pk.null
<add> ensure
<add> Barcode.reset_column_information
<add> end
<add>
<ide> def test_supports_extensions
<ide> assert_not @conn.supports_extensions?, "does not support extensions"
<ide> end
<ide><path>activerecord/test/cases/migration/compatibility_test.rb
<ide> def change
<ide>
<ide> @migration.migrate(:up)
<ide>
<del> legacy_pk = LegacyPrimaryKey.columns_hash["id"]
<del> assert_not legacy_pk.bigint?
<del> assert_not legacy_pk.null
<add> assert_legacy_primary_key
<ide>
<ide> legacy_ref = LegacyPrimaryKey.columns_hash["legacy_ref_id"]
<ide> assert_not legacy_ref.bigint?
<ide> def change
<ide> assert_match %r{create_table "legacy_primary_keys", id: :integer, default: nil}, schema
<ide> end
<ide>
<del> if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
<del> def test_legacy_primary_key_in_create_table_should_be_integer
<del> @migration = Class.new(migration_class) {
<del> def change
<del> create_table :legacy_primary_keys, id: false do |t|
<del> t.primary_key :id
<del> end
<add> def test_legacy_primary_key_in_create_table_should_be_integer
<add> @migration = Class.new(migration_class) {
<add> def change
<add> create_table :legacy_primary_keys, id: false do |t|
<add> t.primary_key :id
<ide> end
<del> }.new
<add> end
<add> }.new
<ide>
<del> @migration.migrate(:up)
<add> @migration.migrate(:up)
<ide>
<del> schema = dump_table_schema "legacy_primary_keys"
<del> assert_match %r{create_table "legacy_primary_keys", id: :(?:integer|serial), (?!default: nil)}, schema
<del> end
<add> assert_legacy_primary_key
<add> end
<ide>
<del> def test_legacy_primary_key_in_change_table_should_be_integer
<del> @migration = Class.new(migration_class) {
<del> def change
<del> create_table :legacy_primary_keys, id: false do |t|
<del> t.integer :dummy
<del> end
<del> change_table :legacy_primary_keys do |t|
<del> t.primary_key :id
<del> end
<add> def test_legacy_primary_key_in_change_table_should_be_integer
<add> @migration = Class.new(migration_class) {
<add> def change
<add> create_table :legacy_primary_keys, id: false do |t|
<add> t.integer :dummy
<ide> end
<del> }.new
<del>
<del> @migration.migrate(:up)
<del>
<del> schema = dump_table_schema "legacy_primary_keys"
<del> assert_match %r{create_table "legacy_primary_keys", id: :(?:integer|serial), (?!default: nil)}, schema
<del> end
<del>
<del> def test_add_column_with_legacy_primary_key_should_be_integer
<del> @migration = Class.new(migration_class) {
<del> def change
<del> create_table :legacy_primary_keys, id: false do |t|
<del> t.integer :dummy
<del> end
<del> add_column :legacy_primary_keys, :id, :primary_key
<add> change_table :legacy_primary_keys do |t|
<add> t.primary_key :id
<ide> end
<del> }.new
<add> end
<add> }.new
<ide>
<del> @migration.migrate(:up)
<add> @migration.migrate(:up)
<ide>
<del> schema = dump_table_schema "legacy_primary_keys"
<del> assert_match %r{create_table "legacy_primary_keys", id: :(?:integer|serial), (?!default: nil)}, schema
<del> end
<add> assert_legacy_primary_key
<ide> end
<ide>
<del> if current_adapter?(:SQLite3Adapter)
<del> def test_add_column_with_legacy_primary_key_should_work
<del> @migration = Class.new(migration_class) {
<del> def change
<del> create_table :legacy_primary_keys, id: false do |t|
<del> t.integer :dummy
<del> end
<del> add_column :legacy_primary_keys, :id, :primary_key
<add> def test_add_column_with_legacy_primary_key_should_be_integer
<add> @migration = Class.new(migration_class) {
<add> def change
<add> create_table :legacy_primary_keys, id: false do |t|
<add> t.integer :dummy
<ide> end
<del> }.new
<add> add_column :legacy_primary_keys, :id, :primary_key
<add> end
<add> }.new
<ide>
<del> @migration.migrate(:up)
<add> @migration.migrate(:up)
<ide>
<del> assert_equal "id", LegacyPrimaryKey.primary_key
<del> legacy_pk = LegacyPrimaryKey.columns_hash["id"]
<del> assert_not legacy_pk.null
<del> end
<add> assert_legacy_primary_key
<ide> end
<ide>
<ide> def test_legacy_join_table_foreign_keys_should_be_integer
<ide> def change
<ide> assert_match %r{create_table "legacy_primary_keys", id: :bigint, default: nil}, schema
<ide> end
<ide> end
<add>
<add> private
<add> def assert_legacy_primary_key
<add> assert_equal "id", LegacyPrimaryKey.primary_key
<add>
<add> legacy_pk = LegacyPrimaryKey.columns_hash["id"]
<add>
<add> assert_equal :integer, legacy_pk.type
<add> assert_not legacy_pk.bigint?
<add> assert_not legacy_pk.null
<add>
<add> if current_adapter?(:Mysql2Adapter, :PostgreSQLAdapter)
<add> schema = dump_table_schema "legacy_primary_keys"
<add> assert_match %r{create_table "legacy_primary_keys", id: :(?:integer|serial), (?!default: nil)}, schema
<add> end
<add> end
<ide> end
<ide>
<ide> module LegacyPrimaryKeyTest | 2 |
PHP | PHP | use assertcount assertion | 872be61fb64b5d63da92134b216cdf36657e860f | <ide><path>tests/Database/DatabaseEloquentBelongsToManyTest.php
<ide> public function testFindManyMethod()
<ide>
<ide> $result = $relation->findMany(['foo', 'bar']);
<ide>
<del> $this->assertEquals(2, count($result));
<add> $this->assertCount(2, $result);
<ide> $this->assertInstanceOf(StdClass::class, $result->first());
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentIntegrationTest.php
<ide> public function testHasOnSelfReferencingBelongsToManyRelationship()
<ide>
<ide> $results = EloquentTestUser::has('friends')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testWhereHasOnSelfReferencingBelongsToManyRelationship()
<ide> $query->where('email', '[email protected]');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testHasOnNestedSelfReferencingBelongsToManyRelationship()
<ide>
<ide> $results = EloquentTestUser::has('friends.friends')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testWhereHasOnNestedSelfReferencingBelongsToManyRelationship()
<ide> $query->where('email', '[email protected]');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testHasOnSelfReferencingBelongsToManyRelationshipWithWherePivot(
<ide>
<ide> $results = EloquentTestUser::has('friendsOne')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testHasOnNestedSelfReferencingBelongsToManyRelationshipWithWhere
<ide>
<ide> $results = EloquentTestUser::has('friendsOne.friendsTwo')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('[email protected]', $results->first()->email);
<ide> }
<ide>
<ide> public function testHasOnSelfReferencingBelongsToRelationship()
<ide>
<ide> $results = EloquentTestPost::has('parentPost')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Child Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testWhereHasOnSelfReferencingBelongsToRelationship()
<ide> $query->where('name', 'Parent Post');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Child Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testHasOnNestedSelfReferencingBelongsToRelationship()
<ide>
<ide> $results = EloquentTestPost::has('parentPost.parentPost')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Child Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testWhereHasOnNestedSelfReferencingBelongsToRelationship()
<ide> $query->where('name', 'Grandparent Post');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Child Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testHasOnSelfReferencingHasManyRelationship()
<ide>
<ide> $results = EloquentTestPost::has('childPosts')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Parent Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testWhereHasOnSelfReferencingHasManyRelationship()
<ide> $query->where('name', 'Child Post');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Parent Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testHasOnNestedSelfReferencingHasManyRelationship()
<ide>
<ide> $results = EloquentTestPost::has('childPosts.childPosts')->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Grandparent Post', $results->first()->name);
<ide> }
<ide>
<ide> public function testWhereHasOnNestedSelfReferencingHasManyRelationship()
<ide> $query->where('name', 'Child Post');
<ide> })->get();
<ide>
<del> $this->assertEquals(1, count($results));
<add> $this->assertCount(1, $results);
<ide> $this->assertEquals('Grandparent Post', $results->first()->name);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentModelTest.php
<ide> public function testPushManyRelation()
<ide> $this->assertTrue($model->push());
<ide> $this->assertEquals(1, $model->id);
<ide> $this->assertTrue($model->exists);
<del> $this->assertEquals(2, count($model->relationMany));
<add> $this->assertCount(2, $model->relationMany);
<ide> $this->assertEquals([2, 3], $model->relationMany->pluck('id')->all());
<ide> }
<ide>
<ide><path>tests/Database/DatabaseEloquentSoftDeletesIntegrationTest.php
<ide> public function testWhereHasWithDeletedRelationship()
<ide> $post = $abigail->posts()->create(['title' => 'First Title']);
<ide>
<ide> $users = SoftDeletesTestUser::where('email', '[email protected]')->has('posts')->get();
<del> $this->assertEquals(0, count($users));
<add> $this->assertCount(0, $users);
<ide>
<ide> $users = SoftDeletesTestUser::where('email', '[email protected]')->has('posts')->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide>
<ide> $users = SoftDeletesTestUser::where('email', '[email protected]')->orHas('posts')->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide>
<ide> $users = SoftDeletesTestUser::whereHas('posts', function ($query) {
<ide> $query->where('title', 'First Title');
<ide> })->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide>
<ide> $users = SoftDeletesTestUser::whereHas('posts', function ($query) {
<ide> $query->where('title', 'Another Title');
<ide> })->get();
<del> $this->assertEquals(0, count($users));
<add> $this->assertCount(0, $users);
<ide>
<ide> $users = SoftDeletesTestUser::where('email', '[email protected]')->orWhereHas('posts', function ($query) {
<ide> $query->where('title', 'First Title');
<ide> })->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide>
<ide> // With Post Deleted...
<ide>
<ide> $post->delete();
<ide> $users = SoftDeletesTestUser::has('posts')->get();
<del> $this->assertEquals(0, count($users));
<add> $this->assertCount(0, $users);
<ide> }
<ide>
<ide> /**
<ide> public function testWhereHasWithNestedDeletedRelationshipAndOnlyTrashedCondition
<ide> $post->delete();
<ide>
<ide> $users = SoftDeletesTestUser::has('posts')->get();
<del> $this->assertEquals(0, count($users));
<add> $this->assertCount(0, $users);
<ide>
<ide> $users = SoftDeletesTestUser::whereHas('posts', function ($q) {
<ide> $q->onlyTrashed();
<ide> })->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide>
<ide> $users = SoftDeletesTestUser::whereHas('posts', function ($q) {
<ide> $q->withTrashed();
<ide> })->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide> }
<ide>
<ide> /**
<ide> public function testWhereHasWithNestedDeletedRelationship()
<ide> $comment->delete();
<ide>
<ide> $users = SoftDeletesTestUser::has('posts.comments')->get();
<del> $this->assertEquals(0, count($users));
<add> $this->assertCount(0, $users);
<ide>
<ide> $users = SoftDeletesTestUser::doesntHave('posts.comments')->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide> }
<ide>
<ide> /**
<ide> public function testWhereHasWithNestedDeletedRelationshipAndWithTrashedCondition
<ide> $post->delete();
<ide>
<ide> $users = SoftDeletesTestUserWithTrashedPosts::has('posts')->get();
<del> $this->assertEquals(1, count($users));
<add> $this->assertCount(1, $users);
<ide> }
<ide>
<ide> /**
<ide><path>tests/Database/DatabaseMySqlSchemaGrammarTest.php
<ide> public function testBasicCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate utf8_unicode_ci', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> public function testBasicCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `id` int unsigned not null auto_increment primary key, add `email` varchar(255) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testEngineCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate utf8_unicode_ci engine = InnoDB', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> public function testEngineCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8 collate utf8_unicode_ci engine = InnoDB', $statements[0]);
<ide> }
<ide>
<ide> public function testCharsetCollationCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null) default character set utf8mb4 collate utf8mb4_unicode_ci', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> public function testCharsetCollationCreateTable()
<ide>
<ide> $statements = $blueprint->toSql($conn, $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) character set utf8mb4 collate utf8mb4_unicode_ci not null) default character set utf8 collate utf8_unicode_ci', $statements[0]);
<ide> }
<ide>
<ide> public function testBasicCreateTableWithPrefix()
<ide>
<ide> $statements = $blueprint->toSql($conn, $grammar);
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table `prefix_users` (`id` int unsigned not null auto_increment primary key, `email` varchar(255) not null)', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTable()
<ide> $blueprint->drop();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table `users`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTableIfExists()
<ide> $blueprint->dropIfExists();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table if exists `users`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropColumn()
<ide> $blueprint->dropColumn('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop `foo`', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn(['foo', 'bar']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop `foo`, drop `bar`', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop `foo`, drop `bar`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropPrimary()
<ide> $blueprint->dropPrimary();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testDropUnique()
<ide> $blueprint->dropUnique('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop index `foo`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropIndex()
<ide> $blueprint->dropIndex('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop index `foo`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropForeign()
<ide> $blueprint->dropForeign('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop foreign key `foo`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestamps()
<ide> $blueprint->dropTimestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop `created_at`, drop `updated_at`', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestampsTz()
<ide> $blueprint->dropTimestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` drop `created_at`, drop `updated_at`', $statements[0]);
<ide> }
<ide>
<ide> public function testRenameTable()
<ide> $blueprint->rename('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('rename table `users` to `foo`', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingPrimaryKey()
<ide> $blueprint->primary('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add primary key `bar`(`foo`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingPrimaryKeyWithAlgorithm()
<ide> $blueprint->primary('foo', 'bar', 'hash');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add primary key `bar` using hash(`foo`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUniqueKey()
<ide> $blueprint->unique('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add unique `bar`(`foo`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndex()
<ide> $blueprint->index(['foo', 'bar'], 'baz');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add index `baz`(`foo`, `bar`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndexWithAlgorithm()
<ide> $blueprint->index(['foo', 'bar'], 'baz', 'hash');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add index `baz` using hash(`foo`, `bar`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingForeignKey()
<ide> $blueprint->foreign('foo_id')->references('id')->on('orders');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add constraint `users_foo_id_foreign` foreign key (`foo_id`) references `orders` (`id`)', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIncrementingID()
<ide> $blueprint->increments('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `id` int unsigned not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallIncrementingID()
<ide> $blueprint->smallIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `id` smallint unsigned not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigIncrementingID()
<ide> $blueprint->bigIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `id` bigint unsigned not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingColumnInTableFirst()
<ide> $blueprint->string('name')->first();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `name` varchar(255) not null first', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingColumnAfterAnotherColumn()
<ide> $blueprint->string('name')->after('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `name` varchar(255) not null after `foo`', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingGeneratedColumn()
<ide> $blueprint->integer('discounted_stored')->storedAs('price - 5');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `products` add `price` int not null, add `discounted_virtual` int as (price - 5), add `discounted_stored` int as (price - 5) stored', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingString()
<ide> $blueprint->string('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(255) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(100) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100)->nullable()->default('bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(100) null default \'bar\'', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100)->nullable()->default(new \Illuminate\Database\Query\Expression('CURRENT TIMESTAMP'));
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(100) null default CURRENT TIMESTAMP', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingText()
<ide> $blueprint->text('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` text not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigInteger()
<ide> $blueprint->bigInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` bigint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->bigInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` bigint not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingInteger()
<ide> $blueprint->integer('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` int not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->integer('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` int not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumInteger()
<ide> $blueprint->mediumInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` mediumint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->mediumInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` mediumint not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallInteger()
<ide> $blueprint->smallInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` smallint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->smallInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` smallint not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTinyInteger()
<ide> $blueprint->tinyInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` tinyint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->tinyInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` tinyint not null auto_increment primary key', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingFloat()
<ide> $blueprint->float('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` double(5, 2) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDouble()
<ide> $blueprint->double('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` double not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDoubleSpecifyingPrecision()
<ide> $blueprint->double('foo', 15, 8);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` double(15, 8) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDecimal()
<ide> $blueprint->decimal('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` decimal(5, 2) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBoolean()
<ide> $blueprint->boolean('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` tinyint(1) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingEnum()
<ide> $blueprint->enum('foo', ['bar', 'baz']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` enum(\'bar\', \'baz\') not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJson()
<ide> $blueprint->json('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` json not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJsonb()
<ide> $blueprint->jsonb('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` json not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDate()
<ide> $blueprint->date('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` date not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTime()
<ide> $blueprint->dateTime('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` datetime(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTimeTz()
<ide> $blueprint->dateTimeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` datetime(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTime()
<ide> $blueprint->time('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeTz()
<ide> $blueprint->timeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamp()
<ide> $blueprint->timestamp('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` timestamp(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampWithDefault()
<ide> $blueprint->timestamp('foo')->default('2015-07-22 11:43:17');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` timestamp(0) not null default \'2015-07-22 11:43:17\'', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTz()
<ide> $blueprint->timestampTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` timestamp(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTzWithDefault()
<ide> $blueprint->timestampTz('foo')->default('2015-07-22 11:43:17');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` timestamp(0) not null default \'2015-07-22 11:43:17\'', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamps()
<ide> $blueprint->timestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `created_at` timestamp(0) null, add `updated_at` timestamp(0) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampsTz()
<ide> $blueprint->timestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `created_at` timestamp(0) null, add `updated_at` timestamp(0) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingRememberToken()
<ide> $blueprint->rememberToken();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `remember_token` varchar(100) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBinary()
<ide> $blueprint->binary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` blob not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUuid()
<ide> $blueprint->uuid('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` char(36) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIpAddress()
<ide> $blueprint->ipAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(45) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMacAddress()
<ide> $blueprint->macAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table `users` add `foo` varchar(17) not null', $statements[0]);
<ide> }
<ide>
<ide><path>tests/Database/DatabasePostgresSchemaGrammarTest.php
<ide> public function testBasicCreateTable()
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "users" ("id" serial primary key not null, "email" varchar(255) not null)', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->increments('id');
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" serial primary key not null, add column "email" varchar(255) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTable()
<ide> $blueprint->drop();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTableIfExists()
<ide> $blueprint->dropIfExists();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table if exists "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropColumn()
<ide> $blueprint->dropColumn('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn(['foo', 'bar']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo", drop column "bar"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo", drop column "bar"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropPrimary()
<ide> $blueprint->dropPrimary();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop constraint "users_pkey"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropUnique()
<ide> $blueprint->dropUnique('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop constraint "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropIndex()
<ide> $blueprint->dropIndex('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop index "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropForeign()
<ide> $blueprint->dropForeign('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop constraint "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestamps()
<ide> $blueprint->dropTimestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "created_at", drop column "updated_at"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestampsTz()
<ide> $blueprint->dropTimestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "created_at", drop column "updated_at"', $statements[0]);
<ide> }
<ide>
<ide> public function testRenameTable()
<ide> $blueprint->rename('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" rename to "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingPrimaryKey()
<ide> $blueprint->primary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add primary key ("foo")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUniqueKey()
<ide> $blueprint->unique('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add constraint "bar" unique ("foo")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndex()
<ide> $blueprint->index(['foo', 'bar'], 'baz');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create index "baz" on "users" ("foo", "bar")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndexWithAlgorithm()
<ide> $blueprint->index(['foo', 'bar'], 'baz', 'hash');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create index "baz" on "users" using hash ("foo", "bar")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIncrementingID()
<ide> $blueprint->increments('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" serial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallIncrementingID()
<ide> $blueprint->smallIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" smallserial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumIncrementingID()
<ide> $blueprint->mediumIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" serial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigIncrementingID()
<ide> $blueprint->bigIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" bigserial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingString()
<ide> $blueprint->string('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar(255) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar(100) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100)->nullable()->default('bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar(100) null default \'bar\'', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingText()
<ide> $blueprint->text('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigInteger()
<ide> $blueprint->bigInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" bigint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->bigInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" bigserial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingInteger()
<ide> $blueprint->integer('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->integer('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" serial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumInteger()
<ide> $blueprint->mediumInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->mediumInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" serial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTinyInteger()
<ide> $blueprint->tinyInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" smallint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->tinyInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" smallserial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallInteger()
<ide> $blueprint->smallInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" smallint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->smallInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" smallserial primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingFloat()
<ide> $blueprint->float('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" double precision not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDouble()
<ide> $blueprint->double('foo', 15, 8);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" double precision not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDecimal()
<ide> $blueprint->decimal('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" decimal(5, 2) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBoolean()
<ide> $blueprint->boolean('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" boolean not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingEnum()
<ide> $blueprint->enum('foo', ['bar', 'baz']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar(255) check ("foo" in (\'bar\', \'baz\')) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDate()
<ide> $blueprint->date('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" date not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJson()
<ide> $blueprint->json('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" json not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJsonb()
<ide> $blueprint->jsonb('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" jsonb not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTime()
<ide> $blueprint->dateTime('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" timestamp(0) without time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTimeTz()
<ide> $blueprint->dateTimeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" timestamp(0) with time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTime()
<ide> $blueprint->time('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" time(0) without time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeTz()
<ide> $blueprint->timeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" time(0) with time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamp()
<ide> $blueprint->timestamp('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" timestamp(0) without time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTz()
<ide> $blueprint->timestampTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" timestamp(0) with time zone not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamps()
<ide> $blueprint->timestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "created_at" timestamp(0) without time zone null, add column "updated_at" timestamp(0) without time zone null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampsTz()
<ide> $blueprint->timestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "created_at" timestamp(0) with time zone null, add column "updated_at" timestamp(0) with time zone null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBinary()
<ide> $blueprint->binary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" bytea not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUuid()
<ide> $blueprint->uuid('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" uuid not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIpAddress()
<ide> $blueprint->ipAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" inet not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMacAddress()
<ide> $blueprint->macAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" macaddr not null', $statements[0]);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseSQLiteSchemaGrammarTest.php
<ide> public function testBasicCreateTable()
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "users" ("id" integer not null primary key autoincrement, "email" varchar not null)', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->increments('id');
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(2, count($statements));
<add> $this->assertCount(2, $statements);
<ide> $expected = [
<ide> 'alter table "users" add column "id" integer not null primary key autoincrement',
<ide> 'alter table "users" add column "email" varchar not null',
<ide> public function testDropTable()
<ide> $blueprint->drop();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTableIfExists()
<ide> $blueprint->dropIfExists();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table if exists "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropUnique()
<ide> $blueprint->dropUnique('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop index "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropIndex()
<ide> $blueprint->dropIndex('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop index "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testRenameTable()
<ide> $blueprint->rename('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" rename to "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingPrimaryKey()
<ide> $blueprint->string('foo')->primary();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "users" ("foo" varchar not null, primary key ("foo"))', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingForeignKey()
<ide> $blueprint->foreign('order_id')->references('id')->on('orders');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "users" ("foo" varchar not null, "order_id" varchar not null, foreign key("order_id") references "orders"("id"), primary key ("foo"))', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUniqueKey()
<ide> $blueprint->unique('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create unique index "bar" on "users" ("foo")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndex()
<ide> $blueprint->index(['foo', 'bar'], 'baz');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create index "baz" on "users" ("foo", "bar")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIncrementingID()
<ide> $blueprint->increments('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallIncrementingID()
<ide> $blueprint->smallIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumIncrementingID()
<ide> $blueprint->mediumIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigIncrementingID()
<ide> $blueprint->bigIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "id" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingString()
<ide> $blueprint->string('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100)->nullable()->default('bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar null default \'bar\'', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingText()
<ide> $blueprint->text('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigInteger()
<ide> $blueprint->bigInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->bigInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingInteger()
<ide> $blueprint->integer('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->integer('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumInteger()
<ide> $blueprint->mediumInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->mediumInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTinyInteger()
<ide> $blueprint->tinyInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->tinyInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallInteger()
<ide> $blueprint->smallInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->smallInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" integer not null primary key autoincrement', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingFloat()
<ide> $blueprint->float('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDouble()
<ide> $blueprint->double('foo', 15, 8);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" float not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDecimal()
<ide> $blueprint->decimal('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" numeric not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBoolean()
<ide> $blueprint->boolean('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" tinyint(1) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingEnum()
<ide> $blueprint->enum('foo', ['bar', 'baz']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJson()
<ide> $blueprint->json('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJsonb()
<ide> $blueprint->jsonb('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" text not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDate()
<ide> $blueprint->date('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" date not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTime()
<ide> $blueprint->dateTime('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTimeTz()
<ide> $blueprint->dateTimeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTime()
<ide> $blueprint->time('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeTz()
<ide> $blueprint->timeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamp()
<ide> $blueprint->timestamp('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTz()
<ide> $blueprint->timestampTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" datetime not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamps()
<ide> $blueprint->timestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(2, count($statements));
<add> $this->assertCount(2, $statements);
<ide> $expected = [
<ide> 'alter table "users" add column "created_at" datetime null',
<ide> 'alter table "users" add column "updated_at" datetime null',
<ide> public function testAddingTimeStampsTz()
<ide> $blueprint->timestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(2, count($statements));
<add> $this->assertCount(2, $statements);
<ide> $expected = [
<ide> 'alter table "users" add column "created_at" datetime null',
<ide> 'alter table "users" add column "updated_at" datetime null',
<ide> public function testAddingRememberToken()
<ide> $blueprint->rememberToken();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "remember_token" varchar null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBinary()
<ide> $blueprint->binary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" blob not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUuid()
<ide> $blueprint->uuid('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIpAddress()
<ide> $blueprint->ipAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMacAddress()
<ide> $blueprint->macAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add column "foo" varchar not null', $statements[0]);
<ide> }
<ide>
<ide><path>tests/Database/DatabaseSqlServerSchemaGrammarTest.php
<ide> public function testBasicCreateTable()
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "users" ("id" int identity primary key not null, "email" nvarchar(255) not null)', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->increments('id');
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "id" int identity primary key not null, "email" nvarchar(255) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> public function testBasicCreateTable()
<ide> $blueprint->string('email');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()->setTablePrefix('prefix_'));
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create table "prefix_users" ("id" int identity primary key not null, "email" nvarchar(255) not null)', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTable()
<ide> $blueprint->drop();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table "users"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->drop();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()->setTablePrefix('prefix_'));
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop table "prefix_users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTableIfExists()
<ide> $blueprint->dropIfExists();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = \'users\') drop table "users"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropIfExists();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar()->setTablePrefix('prefix_'));
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('if exists (select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = \'prefix_users\') drop table "prefix_users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropColumn()
<ide> $blueprint->dropColumn('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn(['foo', 'bar']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo", "bar"', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->dropColumn('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "foo", "bar"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropPrimary()
<ide> $blueprint->dropPrimary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop constraint "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropUnique()
<ide> $blueprint->dropUnique('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop index "foo" on "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropIndex()
<ide> $blueprint->dropIndex('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('drop index "foo" on "users"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropForeign()
<ide> $blueprint->dropForeign('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop constraint "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestamps()
<ide> $blueprint->dropTimestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "created_at", "updated_at"', $statements[0]);
<ide> }
<ide>
<ide> public function testDropTimestampsTz()
<ide> $blueprint->dropTimestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" drop column "created_at", "updated_at"', $statements[0]);
<ide> }
<ide>
<ide> public function testRenameTable()
<ide> $blueprint->rename('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('sp_rename "users", "foo"', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingPrimaryKey()
<ide> $blueprint->primary('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add constraint "bar" primary key ("foo")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUniqueKey()
<ide> $blueprint->unique('foo', 'bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create unique index "bar" on "users" ("foo")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIndex()
<ide> $blueprint->index(['foo', 'bar'], 'baz');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('create index "baz" on "users" ("foo", "bar")', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIncrementingID()
<ide> $blueprint->increments('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "id" int identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallIncrementingID()
<ide> $blueprint->smallIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "id" smallint identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumIncrementingID()
<ide> $blueprint->mediumIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "id" int identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigIncrementingID()
<ide> $blueprint->bigIncrements('id');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "id" bigint identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingString()
<ide> $blueprint->string('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(255) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(100) not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->string('foo', 100)->nullable()->default('bar');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(100) null default \'bar\'', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingText()
<ide> $blueprint->text('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(max) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBigInteger()
<ide> $blueprint->bigInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" bigint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->bigInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" bigint identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingInteger()
<ide> $blueprint->integer('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" int not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->integer('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" int identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMediumInteger()
<ide> $blueprint->mediumInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" int not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->mediumInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" int identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTinyInteger()
<ide> $blueprint->tinyInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" tinyint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->tinyInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" tinyint identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingSmallInteger()
<ide> $blueprint->smallInteger('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" smallint not null', $statements[0]);
<ide>
<ide> $blueprint = new Blueprint('users');
<ide> $blueprint->smallInteger('foo', true);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" smallint identity primary key not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingFloat()
<ide> $blueprint->float('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" float not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDouble()
<ide> $blueprint->double('foo', 15, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" float not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDecimal()
<ide> $blueprint->decimal('foo', 5, 2);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" decimal(5, 2) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBoolean()
<ide> $blueprint->boolean('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" bit not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingEnum()
<ide> $blueprint->enum('foo', ['bar', 'baz']);
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(255) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJson()
<ide> $blueprint->json('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(max) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingJsonb()
<ide> $blueprint->jsonb('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(max) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDate()
<ide> $blueprint->date('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" date not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTime()
<ide> $blueprint->dateTime('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" datetime2(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingDateTimeTz()
<ide> $blueprint->dateTimeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" datetimeoffset(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTime()
<ide> $blueprint->time('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeTz()
<ide> $blueprint->timeTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" time not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamp()
<ide> $blueprint->timestamp('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" datetime2(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampTz()
<ide> $blueprint->timestampTz('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" datetimeoffset(0) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStamps()
<ide> $blueprint->timestamps();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "created_at" datetime2(0) null, "updated_at" datetime2(0) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingTimeStampsTz()
<ide> $blueprint->timestampsTz();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "created_at" datetimeoffset(0) null, "updated_at" datetimeoffset(0) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingRememberToken()
<ide> $blueprint->rememberToken();
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "remember_token" nvarchar(100) null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingBinary()
<ide> $blueprint->binary('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" varbinary(max) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingUuid()
<ide> $blueprint->uuid('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" uniqueidentifier not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingIpAddress()
<ide> $blueprint->ipAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(45) not null', $statements[0]);
<ide> }
<ide>
<ide> public function testAddingMacAddress()
<ide> $blueprint->macAddress('foo');
<ide> $statements = $blueprint->toSql($this->getConnection(), $this->getGrammar());
<ide>
<del> $this->assertEquals(1, count($statements));
<add> $this->assertCount(1, $statements);
<ide> $this->assertEquals('alter table "users" add "foo" nvarchar(17) not null', $statements[0]);
<ide> }
<ide> | 8 |
Python | Python | fix exc_type in handle_failure | f2856773fd526d239dc7fb510b8ccba471a22cb8 | <ide><path>celery/task/trace.py
<ide> def handle_retry(self, task, store_errors=True):
<ide> def handle_failure(self, task, store_errors=True):
<ide> """Handle exception."""
<ide> req = task.request
<del> _, type_, tb = sys.exc_info()
<add> type_, _, tb = sys.exc_info()
<ide> try:
<ide> exc = self.retval
<ide> einfo = ExceptionInfo((type_, get_pickleable_exception(exc), tb)) | 1 |
Java | Java | add javadoc to pivot | b1c14f3a178e9f65c10add4a39ae78f10e2d630f | <ide><path>rxjava-core/src/main/java/rx/Observable.java
<ide> public final static <T> Observable<Observable<T>> parallelMerge(Observable<Obser
<ide> }
<ide>
<ide> /**
<del> * Pivot GroupedObservable streams without serializing/synchronizing to a single stream first.
<add> * Pivot GroupedObservable streams without serializing/synchronizing to a single stream first.
<add> *
<add> * For example an Observable such as this =>
<add> *
<add> * Observable<GroupedObservable<String, GroupedObservable<Boolean, Integer>>>:
<add> *
<add> * o1.odd: 1, 3, 5, 7, 9 on Thread 1
<add> * o1.even: 2, 4, 6, 8, 10 on Thread 1
<add> * o2.odd: 11, 13, 15, 17, 19 on Thread 2
<add> * o2.even: 12, 14, 16, 18, 20 on Thread 2
<add> *
<add> * is pivoted to become this =>
<add> *
<add> * Observable<GroupedObservable<Boolean, GroupedObservable<String, Integer>>>:
<add> *
<add> * odd.o1: 1, 3, 5, 7, 9 on Thread 1
<add> * odd.o2: 11, 13, 15, 17, 19 on Thread 2
<add> * even.o1: 2, 4, 6, 8, 10 on Thread 1
<add> * even.o2: 12, 14, 16, 18, 20 on Thread 2
<ide> *
<ide> * @param groups
<ide> * @return | 1 |
PHP | PHP | add option for double encode | 61f8477fab55a258f39a3d598f67f7cc0ffd6aca | <ide><path>src/Illuminate/Support/helpers.php
<ide> function dd(...$args)
<ide> * Escape HTML special characters in a string.
<ide> *
<ide> * @param \Illuminate\Contracts\Support\Htmlable|string $value
<add> * @param bool $doubleEncode
<ide> * @return string
<ide> */
<del> function e($value)
<add> function e($value, $doubleEncode = false)
<ide> {
<ide> if ($value instanceof Htmlable) {
<ide> return $value->toHtml();
<ide> }
<ide>
<del> return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', false);
<add> return htmlspecialchars($value, ENT_QUOTES, 'UTF-8', $doubleEncode);
<ide> }
<ide> }
<ide> | 1 |
Python | Python | set default celery_event_serializer to "json" | 2bec9c7a99b3d8116cdd83afc66eeb1d805ef366 | <ide><path>celery/conf.py
<ide> "CELERY_EVENT_EXCHANGE": "celeryevent",
<ide> "CELERY_EVENT_EXCHANGE_TYPE": "direct",
<ide> "CELERY_EVENT_ROUTING_KEY": "celeryevent",
<del> "CELERY_EVENT_SERIALIZER": "pickle",
<add> "CELERY_EVENT_SERIALIZER": "json",
<ide> "CELERY_RESULT_EXCHANGE": "celeryresults",
<ide> "CELERY_MAX_CACHED_RESULTS": 5000,
<ide> "CELERY_TRACK_STARTED": False, | 1 |
Text | Text | add weekly focus document for 2018-05-07 | e0f38409f4c683def738d9193c45fca0e8bef02e | <ide><path>docs/focus/2018-05-07.md
<add>## Highlights from the past week
<add>
<add>- Atom Core
<add> - Drafted Q2 plan for Atom Core
<add>- GitHub Package
<add>- Teletype
<add>- Reactor Duty
<add>
<add>## Focus for week ahead
<add>
<add>- Atom Core
<add> - Finish Atom CI experimentation
<add> - Experiment with new [Electron auto-update service](https://electronjs.org/blog/autoupdating-electron-apps)
<add> - Publish Atom Q2 plan
<add>- GitHub Package
<add>- Teletype
<add>- Tree-sitter | 1 |
Python | Python | fix treatment of main() and absl flags | 9af0aad11399816be70bf69d8505bd85c5994525 | <ide><path>official/mnist/mnist.py
<ide> def validate_batch_size_for_multi_gpu(batch_size):
<ide> raise ValueError(err)
<ide>
<ide>
<del>def main(flags_obj):
<add>def run_mnist(flags_obj):
<add> """Run MNIST training and eval loop.
<add>
<add> Args:
<add> flags_obj: An object containing parsed flag values.
<add> """
<add>
<ide> model_function = model_fn
<ide>
<ide> if flags_obj.multi_gpu:
<ide> def eval_input_fn():
<ide> mnist_classifier.export_savedmodel(flags_obj.export_dir, input_fn)
<ide>
<ide>
<add>def main(_):
<add> run_mnist(flags.FLAGS)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide> define_mnist_flags()
<ide><path>official/mnist/mnist_eager.py
<ide> def test(model, dataset):
<ide> tf.contrib.summary.scalar('accuracy', accuracy.result())
<ide>
<ide>
<del>def main(flags_obj):
<add>def run_mnist_eager(flags_obj):
<add> """Run MNIST training and eval loop in eager mode.
<add>
<add> Args:
<add> flags_obj: An object containing parsed flag values.
<add> """
<ide> tf.enable_eager_execution()
<ide>
<ide> # Automatically determine device and data_format
<ide> def define_mnist_eager_flags():
<ide> train_epochs=10,
<ide> )
<ide>
<add>
<add>def main(_):
<add> run_mnist_eager(flags.FLAGS)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> define_mnist_eager_flags()
<ide> absl_app.run(main=main)
<ide><path>official/resnet/cifar10_main.py
<ide> def define_cifar_flags():
<ide> batch_size=128)
<ide>
<ide>
<del>def main(flags_obj):
<add>def run_cifar(flags_obj):
<add> """Run ResNet CIFAR-10 training and eval loop.
<add>
<add> Args:
<add> flags_obj: An object containing parsed flag values.
<add> """
<ide> input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()
<ide> or input_fn)
<ide>
<ide> def main(flags_obj):
<ide> shape=[_HEIGHT, _WIDTH, _NUM_CHANNELS])
<ide>
<ide>
<add>def main(_):
<add> run_cifar(flags.FLAGS)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide> define_cifar_flags()
<ide><path>official/resnet/cifar10_test.py
<ide> def test_cifar10model_shape_v2(self):
<ide>
<ide> def test_cifar10_end_to_end_synthetic_v1(self):
<ide> integration.run_synthetic(
<del> main=cifar10_main.main, tmp_root=self.get_temp_dir(),
<add> main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '1']
<ide> )
<ide>
<ide> def test_cifar10_end_to_end_synthetic_v2(self):
<ide> integration.run_synthetic(
<del> main=cifar10_main.main, tmp_root=self.get_temp_dir(),
<add> main=cifar10_main.run_cifar, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '2']
<ide> )
<ide>
<ide><path>official/resnet/imagenet_main.py
<ide> def define_imagenet_flags():
<ide> flags_core.set_defaults(train_epochs=100)
<ide>
<ide>
<del>def main(flags_obj):
<add>def run_imagenet(flags_obj):
<add> """Run ResNet ImageNet training and eval loop.
<add>
<add> Args:
<add> flags_obj: An object containing parsed flag values.
<add> """
<ide> input_function = (flags_obj.use_synthetic_data and get_synth_input_fn()
<ide> or input_fn)
<ide>
<ide> def main(flags_obj):
<ide> shape=[_DEFAULT_IMAGE_SIZE, _DEFAULT_IMAGE_SIZE, _NUM_CHANNELS])
<ide>
<ide>
<add>def main(_):
<add> run_imagenet(flags.FLAGS)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide> define_imagenet_flags()
<ide><path>official/resnet/imagenet_test.py
<ide> def test_imagenetmodel_shape_v2(self):
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v1(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '1']
<ide> )
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v2(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '2']
<ide> )
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v1_tiny(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '1', '-rs', '18']
<ide> )
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v2_tiny(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '2', '-rs', '18']
<ide> )
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v1_huge(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '1', '-rs', '200']
<ide> )
<ide>
<ide> def test_imagenet_end_to_end_synthetic_v2_huge(self):
<ide> integration.run_synthetic(
<del> main=imagenet_main.main, tmp_root=self.get_temp_dir(),
<add> main=imagenet_main.run_imagenet, tmp_root=self.get_temp_dir(),
<ide> extra_flags=['-v', '2', '-rs', '200']
<ide> )
<ide>
<ide><path>official/wide_deep/wide_deep.py
<ide> def export_model(model, model_type, export_dir):
<ide> model.export_savedmodel(export_dir, example_input_fn)
<ide>
<ide>
<del>def main(flags_obj):
<add>def run_wide_deep(flags_obj):
<add> """Run Wide-Deep training and eval loop.
<add>
<add> Args:
<add> flags_obj: An object containing parsed flag values.
<add> """
<add>
<ide> # Clean up the model directory if present
<ide> shutil.rmtree(flags_obj.model_dir, ignore_errors=True)
<ide> model = build_estimator(flags_obj.model_dir, flags_obj.model_type)
<ide> def eval_input_fn():
<ide> export_model(model, flags_obj.model_type, flags_obj.export_dir)
<ide>
<ide>
<add>def main(_):
<add> run_wide_deep(flags.FLAGS)
<add>
<add>
<ide> if __name__ == '__main__':
<ide> tf.logging.set_verbosity(tf.logging.INFO)
<ide> define_wide_deep_flags() | 7 |
Ruby | Ruby | reduce allocations in to_json's include option | 8538dfdc084555673d18cfc3479ebef09f325c9c | <ide><path>activemodel/lib/active_model/serialization.rb
<ide> def serializable_add_includes(options = {}) #:nodoc:
<ide> return unless includes = options[:include]
<ide>
<ide> unless includes.is_a?(Hash)
<del> includes = Hash[Array(includes).flat_map { |n| n.is_a?(Hash) ? n.to_a : [[n, {}]] }]
<add> includes = Hash[Array(includes).flat_map { |n| n.is_a?(Hash) ? n.to_a : [[n, nil]] }]
<ide> end
<ide>
<ide> includes.each do |association, opts| | 1 |
Text | Text | update changelog for 2.13.0 | bf914c3f21f8050542b238790aabcf2452ed059d | <ide><path>CHANGELOG.md
<ide> Changelog
<ide> =========
<ide>
<add>### 2.13.0 [See full changelog](https://gist.github.com/ichernev/0132fcf5b61f7fc140b0bb0090480d49)
<add>
<add>## Enhancements:
<add>* [#2982](https://github.com/moment/moment/pull/2982) Add 'date' as alias to 'day' for startOf() and endOf().
<add>* [#2955](https://github.com/moment/moment/pull/2955) Add parsing negative components in durations when ISO 8601
<add>* [#2991](https://github.com/moment/moment/pull/2991) isBetween support for both open and closed intervals
<add>* [#3105](https://github.com/moment/moment/pull/3105) Add localeSorted argument to weekday listers
<add>* [#3102](https://github.com/moment/moment/pull/3102) Add k and kk formatting tokens
<add>
<add>## Bugfixes
<add>* [#3109](https://github.com/moment/moment/pull/3109) Fix [#1756](https://github.com/moment/moment/issues/1756) Resolved thread-safe issue on server side.
<add>* [#3078](https://github.com/moment/moment/pull/3078) Fix parsing for months/weekdays with weird characters
<add>* [#3098](https://github.com/moment/moment/pull/3098) Use Z suffix when in UTC mode ([#3020](https://github.com/moment/moment/issues/3020))
<add>* [#2995](https://github.com/moment/moment/pull/2995) Fix floating point rounding errors in durations
<add>* [#3059](https://github.com/moment/moment/pull/3059) fix bug where diff returns -0 in month-related diffs
<add>* [#3045](https://github.com/moment/moment/pull/3045) Fix mistaking any input for 'a' token
<add>* [#2877](https://github.com/moment/moment/pull/2877) Use explicit .valueOf() calls instead of coercion
<add>* [#3036](https://github.com/moment/moment/pull/3036) Year setter should keep time when DST changes
<add>
<add>Plus 3 new locales and locale fixes.
<add>
<ide> ### 2.12.0 [See full changelog](https://gist.github.com/ichernev/6e5bfdf8d6522fc4ac73)
<ide>
<ide> ## Enhancements: | 1 |
Javascript | Javascript | fix bracket placement | dd62944b79e0294880dd510961bd2a85df540f9f | <ide><path>src/scales/scale.linear.js
<ide> },
<ide> // Get the correct value. If the value type is object get the x or y based on whether we are horizontal or not
<ide> getRightValue: function(rawValue) {
<del> return typeof (rawValue === "object" && rawValue !== null) ? (this.isHorizontal() ? rawValue.x : rawValue.y) : rawValue;
<add> return (typeof (rawValue) === "object" && rawValue !== null) ? (this.isHorizontal() ? rawValue.x : rawValue.y) : rawValue;
<ide> },
<ide> getPixelForValue: function(value) {
<ide> // This must be called after fit has been run so that | 1 |
Java | Java | fix rounded image background (android) | 56971bbb152babb0ee745d7abd55f5a5d35ae004 | <ide><path>ReactAndroid/src/main/java/com/facebook/react/views/image/ReactImageView.java
<ide> import com.facebook.drawee.controller.ControllerListener;
<ide> import com.facebook.drawee.controller.ForwardingControllerListener;
<ide> import com.facebook.drawee.drawable.AutoRotateDrawable;
<add>import com.facebook.drawee.drawable.RoundedColorDrawable;
<add>
<ide> import com.facebook.drawee.drawable.ScalingUtils;
<ide> import com.facebook.drawee.generic.GenericDraweeHierarchy;
<ide> import com.facebook.drawee.generic.GenericDraweeHierarchyBuilder;
<ide> private class RoundedCornerPostprocessor extends BasePostprocessor {
<ide>
<ide> void getRadii(Bitmap source, float[] computedCornerRadii, float[] mappedRadii) {
<ide> mScaleType.getTransform(
<del> sMatrix,
<del> new Rect(0, 0, source.getWidth(), source.getHeight()),
<del> source.getWidth(),
<del> source.getHeight(),
<del> 0.0f,
<del> 0.0f);
<del> sMatrix.invert(sInverse);
<add> sMatrix,
<add> new Rect(0, 0, source.getWidth(), source.getHeight()),
<add> source.getWidth(),
<add> source.getHeight(),
<add> 0.0f,
<add> 0.0f);
<add> sMatrix.invert(sInverse);
<ide>
<del> mappedRadii[0] = sInverse.mapRadius(computedCornerRadii[0]);
<del> mappedRadii[1] = mappedRadii[0];
<add> mappedRadii[0] = sInverse.mapRadius(computedCornerRadii[0]);
<add> mappedRadii[1] = mappedRadii[0];
<ide>
<del> mappedRadii[2] = sInverse.mapRadius(computedCornerRadii[1]);
<del> mappedRadii[3] = mappedRadii[2];
<add> mappedRadii[2] = sInverse.mapRadius(computedCornerRadii[1]);
<add> mappedRadii[3] = mappedRadii[2];
<ide>
<del> mappedRadii[4] = sInverse.mapRadius(computedCornerRadii[2]);
<del> mappedRadii[5] = mappedRadii[4];
<add> mappedRadii[4] = sInverse.mapRadius(computedCornerRadii[2]);
<add> mappedRadii[5] = mappedRadii[4];
<ide>
<del> mappedRadii[6] = sInverse.mapRadius(computedCornerRadii[3]);
<del> mappedRadii[7] = mappedRadii[6];
<add> mappedRadii[6] = sInverse.mapRadius(computedCornerRadii[3]);
<add> mappedRadii[7] = mappedRadii[6];
<ide> }
<ide>
<ide> @Override
<ide> public void process(Bitmap output, Bitmap source) {
<ide>
<ide> output.setHasAlpha(true);
<ide> if (FloatUtil.floatsEqual(sComputedCornerRadii[0], 0f) &&
<del> FloatUtil.floatsEqual(sComputedCornerRadii[1], 0f) &&
<del> FloatUtil.floatsEqual(sComputedCornerRadii[2], 0f) &&
<del> FloatUtil.floatsEqual(sComputedCornerRadii[3], 0f)) {
<add> FloatUtil.floatsEqual(sComputedCornerRadii[1], 0f) &&
<add> FloatUtil.floatsEqual(sComputedCornerRadii[2], 0f) &&
<add> FloatUtil.floatsEqual(sComputedCornerRadii[3], 0f)) {
<ide> super.process(output, source);
<ide> return;
<ide> }
<ide> public void process(Bitmap output, Bitmap source) {
<ide> Path pathForBorderRadius = new Path();
<ide>
<ide> pathForBorderRadius.addRoundRect(
<del> new RectF(0, 0, source.getWidth(), source.getHeight()),
<del> radii,
<del> Path.Direction.CW);
<add> new RectF(0, 0, source.getWidth(), source.getHeight()),
<add> radii,
<add> Path.Direction.CW);
<ide>
<ide> canvas.drawPath(pathForBorderRadius, paint);
<ide> }
<ide> public CloseableReference<Bitmap> process(Bitmap source, PlatformBitmapFactory b
<ide> private @Nullable ImageSource mImageSource;
<ide> private @Nullable ImageSource mCachedImageSource;
<ide> private @Nullable Drawable mLoadingImageDrawable;
<add> private @Nullable RoundedColorDrawable mBackgroundImageDrawable;
<add> private int mBackgroundColor = 0x00000000;
<ide> private int mBorderColor;
<ide> private int mOverlayColor;
<ide> private float mBorderWidth;
<ide> public CloseableReference<Bitmap> process(Bitmap source, PlatformBitmapFactory b
<ide> // We can't specify rounding in XML, so have to do so here
<ide> private static GenericDraweeHierarchy buildHierarchy(Context context) {
<ide> return new GenericDraweeHierarchyBuilder(context.getResources())
<del> .setRoundingParams(RoundingParams.fromCornersRadius(0))
<del> .build();
<add> .setRoundingParams(RoundingParams.fromCornersRadius(0))
<add> .build();
<ide> }
<ide>
<ide> public ReactImageView(
<del> Context context,
<del> AbstractDraweeControllerBuilder draweeControllerBuilder,
<del> @Nullable GlobalImageLoadListener globalImageLoadListener,
<del> @Nullable Object callerContext) {
<add> Context context,
<add> AbstractDraweeControllerBuilder draweeControllerBuilder,
<add> @Nullable GlobalImageLoadListener globalImageLoadListener,
<add> @Nullable Object callerContext) {
<ide> super(context, buildHierarchy(context));
<ide> mScaleType = ImageResizeMode.defaultValue();
<ide> mDraweeControllerBuilder = draweeControllerBuilder;
<ide> public void setShouldNotifyLoadEvents(boolean shouldNotify) {
<ide> mControllerListener = null;
<ide> } else {
<ide> final EventDispatcher mEventDispatcher = ((ReactContext) getContext()).
<del> getNativeModule(UIManagerModule.class).getEventDispatcher();
<add> getNativeModule(UIManagerModule.class).getEventDispatcher();
<ide>
<ide> mControllerListener = new BaseControllerListener<ImageInfo>() {
<ide> @Override
<ide> public void onSubmit(String id, Object callerContext) {
<ide> mEventDispatcher.dispatchEvent(
<del> new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_START));
<add> new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD_START));
<ide> }
<ide>
<ide> @Override
<ide> public void onFinalImageSet(
<del> String id,
<del> @Nullable final ImageInfo imageInfo,
<del> @Nullable Animatable animatable) {
<add> String id,
<add> @Nullable final ImageInfo imageInfo,
<add> @Nullable Animatable animatable) {
<ide> if (imageInfo != null) {
<ide> mEventDispatcher.dispatchEvent(
<ide> new ImageLoadEvent(getId(), ImageLoadEvent.ON_LOAD,
<ide> public void setBlurRadius(float blurRadius) {
<ide> mIsDirty = true;
<ide> }
<ide>
<add> @Override
<add> public void setBackgroundColor(int backgroundColor) {
<add> if(mBackgroundColor != backgroundColor) {
<add> mBackgroundColor = backgroundColor;
<add> mBackgroundImageDrawable = new RoundedColorDrawable(backgroundColor);
<add> mIsDirty = true;
<add> }
<add> }
<add>
<ide> public void setBorderColor(int borderColor) {
<ide> mBorderColor = borderColor;
<ide> mIsDirty = true;
<ide> public void setSource(@Nullable ReadableArray sources) {
<ide> ReadableMap source = sources.getMap(idx);
<ide> String uri = source.getString("uri");
<ide> ImageSource imageSource = new ImageSource(
<del> getContext(),
<del> uri,
<del> source.getDouble("width"),
<del> source.getDouble("height"));
<add> getContext(),
<add> uri,
<add> source.getDouble("width"),
<add> source.getDouble("height"));
<ide> mSources.add(imageSource);
<ide> if (Uri.EMPTY.equals(imageSource.getUri())) {
<ide> warnImageSource(uri);
<ide> public void setSource(@Nullable ReadableArray sources) {
<ide> public void setLoadingIndicatorSource(@Nullable String name) {
<ide> Drawable drawable = ResourceDrawableIdHelper.getInstance().getResourceDrawable(getContext(), name);
<ide> mLoadingImageDrawable =
<del> drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null;
<add> drawable != null ? (Drawable) new AutoRotateDrawable(drawable, 1000) : null;
<ide> mIsDirty = true;
<ide> }
<ide>
<ide> public void maybeUpdateView() {
<ide> }
<ide>
<ide> boolean usePostprocessorScaling =
<del> mScaleType != ScalingUtils.ScaleType.CENTER_CROP &&
<add> mScaleType != ScalingUtils.ScaleType.CENTER_CROP &&
<ide> mScaleType != ScalingUtils.ScaleType.FOCUS_CROP;
<ide>
<ide> RoundingParams roundingParams = hierarchy.getRoundingParams();
<ide>
<add> cornerRadii(sComputedCornerRadii);
<add>
<add> roundingParams.setCornersRadii(sComputedCornerRadii[0], sComputedCornerRadii[1], sComputedCornerRadii[2], sComputedCornerRadii[3]);
<add>
<add> if (mBackgroundImageDrawable != null) {
<add> mBackgroundImageDrawable.setBorder(mBorderColor, mBorderWidth);
<add> mBackgroundImageDrawable.setRadii(roundingParams.getCornersRadii());
<add> hierarchy.setBackgroundImage(mBackgroundImageDrawable);
<add> }
<add>
<ide> if (usePostprocessorScaling) {
<ide> roundingParams.setCornersRadius(0);
<del> } else {
<del> cornerRadii(sComputedCornerRadii);
<del>
<del> roundingParams.setCornersRadii(sComputedCornerRadii[0], sComputedCornerRadii[1], sComputedCornerRadii[2], sComputedCornerRadii[3]);
<ide> }
<ide>
<ide> roundingParams.setBorder(mBorderColor, mBorderWidth);
<ide> if (mOverlayColor != Color.TRANSPARENT) {
<del> roundingParams.setOverlayColor(mOverlayColor);
<add> roundingParams.setOverlayColor(mOverlayColor);
<ide> } else {
<del> // make sure the default rounding method is used.
<del> roundingParams.setRoundingMethod(RoundingParams.RoundingMethod.BITMAP_ONLY);
<add> // make sure the default rounding method is used.
<add> roundingParams.setRoundingMethod(RoundingParams.RoundingMethod.BITMAP_ONLY);
<ide> }
<ide> hierarchy.setRoundingParams(roundingParams);
<ide> hierarchy.setFadeDuration(
<del> mFadeDurationMs >= 0
<del> ? mFadeDurationMs
<del> : mImageSource.isResource() ? 0 : REMOTE_IMAGE_FADE_DURATION_MS);
<add> mFadeDurationMs >= 0
<add> ? mFadeDurationMs
<add> : mImageSource.isResource() ? 0 : REMOTE_IMAGE_FADE_DURATION_MS);
<ide>
<ide> List<Postprocessor> postprocessors = new LinkedList<>();
<ide> if (usePostprocessorScaling) {
<ide> public void maybeUpdateView() {
<ide> ResizeOptions resizeOptions = doResize ? new ResizeOptions(getWidth(), getHeight()) : null;
<ide>
<ide> ImageRequestBuilder imageRequestBuilder = ImageRequestBuilder.newBuilderWithSource(mImageSource.getUri())
<del> .setPostprocessor(postprocessor)
<del> .setResizeOptions(resizeOptions)
<del> .setAutoRotateEnabled(true)
<del> .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled);
<add> .setPostprocessor(postprocessor)
<add> .setResizeOptions(resizeOptions)
<add> .setAutoRotateEnabled(true)
<add> .setProgressiveRenderingEnabled(mProgressiveRenderingEnabled);
<ide>
<ide> ImageRequest imageRequest = ReactNetworkImageRequest.fromBuilderWithHeaders(imageRequestBuilder, mHeaders);
<ide>
<ide> public void maybeUpdateView() {
<ide> mDraweeControllerBuilder.reset();
<ide>
<ide> mDraweeControllerBuilder
<del> .setAutoPlayAnimations(true)
<del> .setCallerContext(mCallerContext)
<del> .setOldController(getController())
<del> .setImageRequest(imageRequest);
<add> .setAutoPlayAnimations(true)
<add> .setCallerContext(mCallerContext)
<add> .setOldController(getController())
<add> .setImageRequest(imageRequest);
<ide>
<ide> if (mCachedImageSource != null) {
<ide> ImageRequest cachedImageRequest =
<ide> private boolean shouldResize(ImageSource imageSource) {
<ide> if (mResizeMethod == ImageResizeMethod.AUTO) {
<ide> return
<ide> UriUtil.isLocalContentUri(imageSource.getUri()) ||
<del> UriUtil.isLocalFileUri(imageSource.getUri());
<add> UriUtil.isLocalFileUri(imageSource.getUri());
<ide> } else if (mResizeMethod == ImageResizeMethod.RESIZE) {
<ide> return true;
<ide> } else {
<ide> private void warnImageSource(String uri) {
<ide> }
<ide> }
<ide> }
<add> | 1 |
Java | Java | avoid potential npe when onerror throws. | 5b8845d4cfdbc2d563b90ce27db978b7e383d9e0 | <ide><path>src/main/java/io/reactivex/subscribers/SafeSubscriber.java
<ide> public void onError(Throwable t) {
<ide> }
<ide> } catch (Throwable e) {
<ide> Exceptions.throwIfFatal(e);
<del> t2.suppress(e);
<del>
<add> if (t2 == null) {
<add> t2 = new CompositeException(t, e);
<add> } else {
<add> t2.suppress(e);
<add> }
<ide> RxJavaPlugins.onError(t2);
<ide> }
<ide> } | 1 |
Javascript | Javascript | initialize textdecoder once on blob.text() | 76229fc216ffefc9e470b79bcab1752fd78e68ae | <ide><path>lib/internal/blob.js
<ide> let ReadableStream;
<ide> let URL;
<ide>
<ide> const enc = new TextEncoder();
<add>let dec;
<ide>
<ide> // Yes, lazy loading is annoying but because of circular
<ide> // references between the url, internal/blob, and buffer
<ide> class Blob {
<ide> if (!isBlob(this))
<ide> throw new ERR_INVALID_THIS('Blob');
<ide>
<del> const dec = new TextDecoder();
<add> dec ??= new TextDecoder();
<add>
<ide> return dec.decode(await this.arrayBuffer());
<ide> }
<ide> | 1 |
Javascript | Javascript | add testids to first example in scrollviewexample | 2840e8abf91762814572d73db5be2a69eb78ec7c | <ide><path>packages/rn-tester/js/examples/ScrollView/ScrollViewExample.js
<ide> const {
<ide> const nullthrows = require('nullthrows');
<ide>
<ide> import {useState, useCallback} from 'react';
<add>import type {RNTesterExampleModuleItem} from '../../types/RNTesterTypes';
<ide> import type {ViewStyleProp} from 'react-native/Libraries/StyleSheet/StyleSheet';
<ide>
<ide> exports.displayName = 'ScrollViewExample';
<ide> exports.documentationURL = 'https://reactnative.dev/docs/scrollview';
<ide> exports.category = 'Basic';
<ide> exports.description =
<ide> 'Component that enables scrolling through child components';
<del>exports.examples = [
<add>exports.examples = ([
<ide> {
<add> name: 'scrollTo',
<ide> title: '<ScrollView>\n',
<ide> description:
<ide> 'To make content scrollable, wrap it within a <ScrollView> component',
<ide> exports.examples = [
<ide> console.log('onScroll!');
<ide> }}
<ide> scrollEventThrottle={200}
<del> style={styles.scrollView}>
<add> style={styles.scrollView}
<add> testID="scroll_vertical">
<ide> {ITEMS.map(createItemRow)}
<ide> </ScrollView>
<ide> <Button
<ide> label="Scroll to top"
<ide> onPress={() => {
<ide> nullthrows(_scrollView).scrollTo({y: 0});
<ide> }}
<add> testID="scroll_to_top_button"
<ide> />
<ide> <Button
<ide> label="Scroll to bottom"
<ide> onPress={() => {
<ide> nullthrows(_scrollView).scrollToEnd({animated: true});
<ide> }}
<add> testID="scroll_to_bottom_button"
<ide> />
<ide> <Button
<ide> label="Flash scroll indicators"
<ide> onPress={() => {
<ide> nullthrows(_scrollView).flashScrollIndicators();
<ide> }}
<add> testID="flash_scroll_indicators_button"
<ide> />
<ide> </View>
<ide> );
<ide> exports.examples = [
<ide> return <SnapToOptions />;
<ide> },
<ide> },
<del>];
<add>]: Array<RNTesterExampleModuleItem>);
<add>
<ide> if (Platform.OS === 'ios') {
<ide> exports.examples.push({
<ide> title: '<ScrollView> smooth bi-directional content loading\n',
<ide> let ITEMS = [...Array(12)].map((_, i) => `Item ${i}`);
<ide>
<ide> const createItemRow = (msg, index) => <Item key={index} msg={msg} />;
<ide>
<del>const Button = ({label, onPress}) => (
<del> <TouchableOpacity style={styles.button} onPress={onPress}>
<del> <Text>{label}</Text>
<add>const Button = (props: {
<add> label: string,
<add> onPress: () => void,
<add> testID?: string,
<add>}) => (
<add> <TouchableOpacity
<add> style={styles.button}
<add> onPress={props.onPress}
<add> testID={props.testID}>
<add> <Text>{props.label}</Text>
<ide> </TouchableOpacity>
<ide> );
<ide> | 1 |
Javascript | Javascript | add repeater dsl and fix typo | fe03ea0d1f8814817bee5a35d745db16858eb490 | <ide><path>src/scenario/DSL.js
<ide> angular.scenario.dsl.input = function(selector) {
<ide> };
<ide> };
<ide>
<del>angular.scenario.dsl.expect = function(selector) {
<del> return {
<del> toEqual: function(expected) {
<del> $scenario.addStep("Expect that " + selector + " equals '" + expected + "'", function(done){
<del> var attrName = selector.substring(2, selector.length - 2);
<del> var binding = this.testDocument.find('span[ng-bind=' + attrName + ']');
<del> if (binding.text() != expected) {
<del> this.result.fail("Expected '" + expected + "' but was '" + binding.text() + "'");
<add>angular.scenario.dsl.expect = {
<add> repeater: function(selector) {
<add> return {
<add> count: {
<add> toEqual: function(number) {
<add> $scenario.addStep("Expect to see " + number + " items repeated with selector '" + selector + "'", function(done) {
<add> var items = this.testDocument.find(selector);
<add> if (items.length != number) {
<add> this.result.fail("Expected " + number + " but was " + items.length);
<add> }
<add> done();
<add> });
<ide> }
<del> done();
<del> });
<del> }
<del> };
<add> }
<add> };
<add> }
<ide> };
<ide><path>test/scenario/DSLSpec.js
<ide> describe("DSL", function() {
<ide> expect(lastDocument.find(':radio:checked').val()).toEqual('female');
<ide> });
<ide> });
<del>});
<ide>\ No newline at end of file
<add>
<add> describe('expect', function() {
<add> var dslExpect = angular.scenario.dsl.expect;
<add> describe('repeater', function() {
<add> it('should check the count of repeated elements', function() {
<add> dslExpect.repeater('.repeater-row').count.toEqual(2);
<add> expect(lastStep.name).toEqual("Expect to see 2 items repeated with selector '.repeater-row'");
<add> var html = "<div class='repeater-row'>a</div><div class='repeater-row'>b</div>";
<add> executeStep(lastStep, html);
<add> });
<add> });
<add> });
<add>});
<ide><path>test/scenario/RunnerSpec.js
<ide> describe('Runner', function(){
<ide> expect(spec.name).toEqual('describe name: it should text');
<ide> });
<ide>
<del> it('should camplain on duplicate it', angular.noop);
<add> it('should complain on duplicate it', angular.noop);
<ide> it('should create a failing step if there is a javascript error', function(){
<ide> var spec;
<ide> Describe('D1', function(){ | 3 |
Javascript | Javascript | replace assert.throws with common.expectserror | 50afd901ea74b11352b4bc232c80cccede73f7fb | <ide><path>test/addons-napi/test_error/test.js
<ide> assert.throws(() => {
<ide> test_error.throwTypeError();
<ide> }, /^TypeError: type error$/);
<ide>
<del>assert.throws(
<add>common.expectsError(
<ide> () => test_error.throwErrorCode(),
<del> common.expectsError({
<add> {
<ide> code: 'ERR_TEST_CODE',
<ide> message: 'Error [error]'
<del> })
<del>);
<add> });
<ide>
<del>assert.throws(
<add>common.expectsError(
<ide> () => test_error.throwRangeErrorCode(),
<del> common.expectsError({
<add> {
<ide> code: 'ERR_TEST_CODE',
<ide> message: 'RangeError [range error]'
<del> })
<del>);
<add> });
<ide>
<del>assert.throws(
<add>common.expectsError(
<ide> () => test_error.throwTypeErrorCode(),
<del> common.expectsError({
<add> {
<ide> code: 'ERR_TEST_CODE',
<ide> message: 'TypeError [type error]'
<del> })
<del>);
<add> });
<ide>
<ide> let error = test_error.createError();
<ide> assert.ok(error instanceof Error, 'expected error to be an instance of Error'); | 1 |
PHP | PHP | fix lint issue | 53bde1293ef92964a98b9888e205beb29c95db5f | <ide><path>src/View/Form/EntityContext.php
<ide> */
<ide> namespace Cake\View\Form;
<ide>
<add>use ArrayAccess;
<ide> use Cake\Collection\Collection;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Http\ServerRequest;
<ide> use Cake\ORM\TableRegistry;
<ide> use Cake\Utility\Inflector;
<del>use ArrayAccess;
<ide> use RuntimeException;
<ide> use Traversable;
<ide> | 1 |
Python | Python | return valid openapi schema even when empty | d0b957760549710b90300b9a3a373d175238884c | <ide><path>rest_framework/schemas/openapi.py
<ide> def get_info(self):
<ide> def get_paths(self, request=None):
<ide> result = {}
<ide>
<del> paths, view_endpoints = self._get_paths_and_endpoints(request)
<del>
<del> # Only generate the path prefix for paths that will be included
<del> if not paths:
<del> return None
<del>
<add> _, view_endpoints = self._get_paths_and_endpoints(request)
<ide> for path, method, view in view_endpoints:
<ide> if not self.has_view_permissions(path, method, view):
<ide> continue
<ide> def get_schema(self, request=None, public=False):
<ide> self._initialise_endpoints()
<ide>
<ide> paths = self.get_paths(None if public else request)
<del> if not paths:
<del> return None
<del>
<ide> schema = {
<ide> 'openapi': '3.0.2',
<ide> 'info': self.get_info(),
<ide><path>tests/schemas/test_openapi.py
<ide> def test_schema_construction(self):
<ide> assert 'openapi' in schema
<ide> assert 'paths' in schema
<ide>
<add> def test_schema_with_no_paths(self):
<add> patterns = []
<add> generator = SchemaGenerator(patterns=patterns)
<add>
<add> request = create_request('/')
<add> schema = generator.get_schema(request=request)
<add>
<add> assert schema['paths'] == {}
<add>
<ide> def test_schema_information(self):
<ide> """Construction of the top level dictionary."""
<ide> patterns = [ | 2 |
Ruby | Ruby | make relative symlinks in pathname#install_symlink | aa7ed10968508f0390fba88c3bb2f2b0e8db9415 | <ide><path>Library/Homebrew/extend/pathname.rb
<ide> def install_symlink *sources
<ide> end
<ide> end
<ide>
<del> def install_symlink_p src, new_basename = nil
<del> if new_basename.nil?
<del> dst = self+File.basename(src)
<del> else
<del> dst = self+File.basename(new_basename)
<del> end
<add> def install_symlink_p src, new_basename=src
<add> dst = join File.basename(new_basename)
<ide> mkpath
<del> FileUtils.ln_s src.to_s, dst.to_s
<add> FileUtils.ln_s Pathname(src).relative_path_from(dst.parent), dst
<ide> end
<ide> protected :install_symlink_p
<ide>
<ide><path>Library/Homebrew/test/test_pathname.rb
<ide> def test_install_symlink
<ide> assert((@dst+'bin').directory?)
<ide> assert((@dst+'bin/a.txt').exist?)
<ide> assert((@dst+'bin/b.txt').exist?)
<add>
<add> assert((@dst+'bin').readlink.relative?)
<ide> end
<ide> end
<ide> | 2 |
Python | Python | fix recurrent tests | 64449c196e3ad7f5a9e85b9c01e8f0ac83335232 | <ide><path>keras/layers/recurrent.py
<ide> def get_config(self):
<ide> 'unroll': self.unroll,
<ide> 'consume_less': self.consume_less}
<ide> if self.stateful:
<del> config['batch_input_shape'] = self.input_shape
<add> config['batch_input_shape'] = self.input_spec[0].shape
<ide> else:
<ide> config['input_dim'] = self.input_dim
<ide> config['input_length'] = self.input_length
<ide> def build(self, input_shape):
<ide>
<ide> def reset_states(self):
<ide> assert self.stateful, 'Layer must be stateful.'
<del> input_shape = self.input_shape
<add> input_shape = self.input_spec[0].shape
<ide> if not input_shape[0]:
<ide> raise Exception('If a RNN is stateful, a complete ' +
<ide> 'input_shape must be provided (including batch size).')
<ide><path>tests/keras/layers/test_embeddings.py
<ide> import pytest
<del>import numpy as np
<del>from numpy.testing import assert_allclose
<del>from keras.models import Sequential
<del>from keras.layers.core import Dense, Activation, Flatten
<add>from keras.utils.test_utils import layer_test
<ide> from keras.layers.embeddings import Embedding
<del>from keras.constraints import unitnorm
<del>from keras import backend as K
<ide>
<ide>
<del>X1 = np.array([[1], [2]], dtype='int32')
<del>W1 = np.array([[0.1, 0.2], [0.3, 0.4], [0.5, 0.6]], dtype='float32')
<del>
<del>
<del>def test_unitnorm_constraint():
<del> lookup = Sequential()
<del> lookup.add(Embedding(3, 2, weights=[W1],
<del> W_constraint=unitnorm(),
<del> input_length=1))
<del> lookup.add(Flatten())
<del> lookup.add(Dense(1))
<del> lookup.add(Activation('sigmoid'))
<del> lookup.compile(loss='binary_crossentropy', optimizer='sgd',
<del> class_mode='binary')
<del> lookup.train_on_batch(X1, np.array([[1], [0]], dtype='int32'))
<del> norm = np.linalg.norm(K.get_value(lookup.trainable_weights[0]), axis=0)
<del> assert_allclose(norm, np.ones_like(norm).astype('float32'), rtol=1e-05)
<add>def test_embedding():
<add> layer_test(Embedding,
<add> kwargs={'output_dim': 4., 'input_dim': 10, 'input_length': 2},
<add> input_shape=(3, 2),
<add> input_dtype='int32')
<ide>
<ide>
<ide> if __name__ == '__main__':
<ide><path>tests/keras/layers/test_recurrent.py
<ide> import numpy as np
<ide> from numpy.testing import assert_allclose
<ide>
<add>from keras.utils.test_utils import layer_test
<ide> from keras.layers import recurrent, embeddings
<ide> from keras.models import Sequential
<ide> from keras.layers.core import Masking
<ide> from keras import regularizers
<ide>
<ide> from keras import backend as K
<del>from keras.models import Sequential, model_from_json
<ide>
<ide> nb_samples, timesteps, embedding_dim, output_dim = 3, 5, 10, 5
<ide> embedding_num = 12
<ide> def _runner(layer_class):
<ide> All the recurrent layers share the same interface,
<ide> so we can run through them with a single function.
<ide> """
<del> for ret_seq in [True, False]:
<del> layer = layer_class(output_dim, return_sequences=ret_seq,
<del> weights=None, input_shape=(timesteps, embedding_dim))
<del> layer.input = K.variable(np.ones((nb_samples, timesteps, embedding_dim)))
<del> layer.get_config()
<del>
<del> for train in [True, False]:
<del> out = K.eval(layer.get_output(train))
<del> # Make sure the output has the desired shape
<del> if ret_seq:
<del> assert(out.shape == (nb_samples, timesteps, output_dim))
<del> else:
<del> assert(out.shape == (nb_samples, output_dim))
<del>
<del> mask = layer.get_output_mask(train)
<add> # check return_sequences
<add> layer_test(layer_class,
<add> kwargs={'output_dim': output_dim,
<add> 'return_sequences': True},
<add> input_shape=(3, 2, 3))
<ide>
<ide> # check dropout
<del> for ret_seq in [True, False]:
<del> layer = layer_class(output_dim, return_sequences=ret_seq, weights=None,
<del> batch_input_shape=(nb_samples, timesteps, embedding_dim),
<del> dropout_W=0.5, dropout_U=0.5)
<del> layer.input = K.variable(np.ones((nb_samples, timesteps, embedding_dim)))
<del> layer.get_config()
<del>
<del> for train in [True, False]:
<del> out = K.eval(layer.get_output(train))
<del> # Make sure the output has the desired shape
<del> if ret_seq:
<del> assert(out.shape == (nb_samples, timesteps, output_dim))
<del> else:
<del> assert(out.shape == (nb_samples, output_dim))
<del>
<del> mask = layer.get_output_mask(train)
<add> layer_test(layer_class,
<add> kwargs={'output_dim': output_dim,
<add> 'dropout_U': 0.1,
<add> 'dropout_W': 0.1},
<add> input_shape=(3, 2, 3))
<ide>
<ide> # check statefulness
<ide> model = Sequential()
<ide> def _runner(layer_class):
<ide> assert_allclose(out7, out6, atol=1e-5)
<ide>
<ide> # check regularizers
<del> layer = layer_class(output_dim, return_sequences=ret_seq, weights=None,
<add> layer = layer_class(output_dim, return_sequences=False, weights=None,
<ide> batch_input_shape=(nb_samples, timesteps, embedding_dim),
<ide> W_regularizer=regularizers.WeightRegularizer(l1=0.01),
<ide> U_regularizer=regularizers.WeightRegularizer(l1=0.01),
<ide> b_regularizer='l2')
<del> layer.input = K.variable(np.ones((nb_samples, timesteps, embedding_dim)))
<del> out = K.eval(layer.get_output(train=True))
<add> shape = (nb_samples, timesteps, embedding_dim)
<add> layer.set_input(K.variable(np.ones(shape)),
<add> shape=shape)
<add> K.eval(layer.output)
<ide>
<ide>
<ide> def test_SimpleRNN():
<ide> def test_LSTM():
<ide> _runner(recurrent.LSTM)
<ide>
<ide>
<del>def test_batch_input_shape_serialization():
<del> model = Sequential()
<del> model.add(embeddings.Embedding(2, 2,
<del> mask_zero=True,
<del> input_length=2,
<del> batch_input_shape=(2, 2)))
<del> json_data = model.to_json()
<del> reconstructed_model = model_from_json(json_data)
<del> assert(reconstructed_model.input_shape == (2, 2))
<del>
<del>
<ide> def test_masking_layer():
<ide> ''' This test based on a previously failing issue here:
<ide> https://github.com/fchollet/keras/issues/1567 | 3 |
Python | Python | remove duplicated model declaration | 06b6b96f933088ba36d4c98e13893274f29bed6a | <ide><path>tests/models.py
<ide> class NullableOneToOneSource(RESTFrameworkModel):
<ide> class BasicModelSerializer(serializers.ModelSerializer):
<ide> class Meta:
<ide> model = BasicModel
<del>
<del>
<del># Models to test filters
<del>class FilterableItem(models.Model):
<del> text = models.CharField(max_length=100)
<del> decimal = models.DecimalField(max_digits=4, decimal_places=2)
<del> date = models.DateField() | 1 |
Javascript | Javascript | set hours to claim certs to 300 | 421c05e652ca4aba39982b13eabf139d82413f98 | <ide><path>api-server/server/boot/certificate.js
<ide> const completionHours = {
<ide> [certTypes.apisMicroservices]: 300,
<ide> [certTypes.qaV7]: 300,
<ide> [certTypes.infosecV7]: 300,
<del> [certTypes.sciCompPyV7]: 400,
<del> [certTypes.dataAnalysisPyV7]: 400,
<del> [certTypes.machineLearningPyV7]: 400
<add> [certTypes.sciCompPyV7]: 300,
<add> [certTypes.dataAnalysisPyV7]: 300,
<add> [certTypes.machineLearningPyV7]: 300
<ide> };
<ide>
<ide> function getCertById(anId, allChallenges) { | 1 |
Python | Python | add missing space in serializer error message | 03b5438d072843dd5c5cba56535263df0bbafa82 | <ide><path>rest_framework/serializers.py
<ide> def raise_errors_on_nested_writes(method_name, serializer, validated_data):
<ide> isinstance(validated_data[key], (list, dict))
<ide> for key, field in serializer.fields.items()
<ide> ), (
<del> 'The `.{method_name}()` method does not support writable nested'
<add> 'The `.{method_name}()` method does not support writable nested '
<ide> 'fields by default.\nWrite an explicit `.{method_name}()` method for '
<ide> 'serializer `{module}.{class_name}`, or set `read_only=True` on '
<ide> 'nested serializer fields.'.format( | 1 |
Text | Text | add teletype highlights from the past week | ae8c35b19adf73ff5a405623da7cd8e7621ba597 | <ide><path>docs/focus/2018-05-07.md
<ide> - Clear the branch name after a successful checkout [atom/github#1438](https://github.com/atom/github/pull/1438)
<ide> - Improve readability of console git diagnostic messages [atom/github#1439](https://github.com/atom/github/pull/1439)
<ide> - Teletype
<add> - Shipped [Teletype 0.13.2](https://github.com/atom/teletype/releases/tag/v0.13.2) to fix an issue that Fixed an issue that would sometimes occur when closing the WebRTC connection ([atom/teletype#368](https://github.com/atom/teletype/issues/368))
<ide> - Reactor Duty
<ide>
<ide> ## Focus for week ahead
<ide> - :robot: improve automation and chatops around Atom ecosystem build health
<ide> - Chatops to report flaky builds
<ide> - Improve failing build notifications
<del>- Teletype
<ide> - Tree-sitter | 1 |
Javascript | Javascript | make `model` an alias for `content` on controllers | 49dd221e8cc0453f0e6ba260b109d88108b927a4 | <ide><path>packages/ember-routing/lib/ext/controller.js
<del>var get = Ember.get;
<add>var get = Ember.get, set = Ember.set;
<ide>
<ide> Ember.ControllerMixin.reopen({
<ide> concatenatedProperties: ['needs'],
<ide> Ember.ControllerMixin.reopen({
<ide> controllerFor: function(controllerName) {
<ide> var container = get(this, 'container');
<ide> return container.lookup('controller:' + controllerName);
<del> }
<add> },
<add>
<add> model: Ember.computed(function(key, value) {
<add> if (arguments.length > 1) {
<add> return set(this, 'content', value);
<add> } else {
<add> return get(this, 'content');
<add> }
<add> }).property('content')
<ide> });
<ide>
<ide> function verifyDependencies(controller) { | 1 |
PHP | PHP | update usage to "type" to "typefactory" | 908acf9898cc0577acabba70687633351fb56c31 | <ide><path>src/Database/FieldTypeConverter.php
<ide> public function __construct(TypeMap $typeMap, Driver $driver)
<ide> {
<ide> $this->_driver = $driver;
<ide> $map = $typeMap->toArray();
<del> $types = Type::buildAll();
<add> $types = TypeFactory::buildAll();
<ide>
<ide> $simpleMap = $batchingMap = [];
<ide> $simpleResult = $batchingResult = [];
<ide><path>src/Database/Schema/MysqlSchema.php
<ide> public function convertOptionsDescription(TableSchema $schema, $row)
<ide> /**
<ide> * Convert a MySQL column type into an abstract type.
<ide> *
<del> * The returned type will be a type that Cake\Database\Type can handle.
<add> * The returned type will be a type that Cake\Database\TypeFactory can handle.
<ide> *
<ide> * @param string $column The column type + length
<ide> * @return array Array of column information.
<ide><path>src/Database/Schema/PostgresSchema.php
<ide> public function describeColumnSql($tableName, $config)
<ide> * Convert a column definition to the abstract types.
<ide> *
<ide> * The returned type will be a type that
<del> * Cake\Database\Type can handle.
<add> * Cake\Database\TypeFactory can handle.
<ide> *
<ide> * @param string $column The column type + length
<ide> * @throws \Cake\Database\Exception when column cannot be parsed.
<ide><path>src/Database/Schema/SqliteSchema.php
<ide> class SqliteSchema extends BaseSchema
<ide> * Convert a column definition to the abstract types.
<ide> *
<ide> * The returned type will be a type that
<del> * Cake\Database\Type can handle.
<add> * Cake\Database\TypeFactory can handle.
<ide> *
<ide> * @param string $column The column type + length
<ide> * @throws \Cake\Database\Exception when unable to parse column type
<ide><path>src/Database/Schema/SqlserverSchema.php
<ide> public function describeColumnSql($tableName, $config)
<ide> * Convert a column definition to the abstract types.
<ide> *
<ide> * The returned type will be a type that
<del> * Cake\Database\Type can handle.
<add> * Cake\Database\TypeFactory can handle.
<ide> *
<ide> * @param string $col The column type
<ide> * @param int|null $length the column length
<ide><path>src/Database/Schema/TableSchema.php
<ide>
<ide> use Cake\Database\Connection;
<ide> use Cake\Database\Exception;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide>
<ide> /**
<ide> * Represents a single table in a database schema.
<ide> public function baseColumnType($column)
<ide> return null;
<ide> }
<ide>
<del> if (Type::getMap($type)) {
<del> $type = Type::build($type)->getBaseType();
<add> if (TypeFactory::getMap($type)) {
<add> $type = TypeFactory::build($type)->getBaseType();
<ide> }
<ide>
<ide> return $this->_columns[$column]['baseType'] = $type;
<ide><path>src/Database/Type/DateType.php
<ide> class DateType extends DateTimeType
<ide> * class is constructed. After that use `useMutable()` or `useImmutable()` instead.
<ide> *
<ide> * @var string
<del> * @deprecated 3.2.0 Use DateType::useMutable() or DateType::useImmutable() instead.
<add> * @deprecated 3.2.0 Use DateTypeFactory::useMutable() or DateTypeFactory::useImmutable() instead.
<ide> */
<ide> public static $dateTimeClass = 'Cake\I18n\Date';
<ide>
<ide><path>src/Database/Type/ExpressionTypeCasterTrait.php
<ide> */
<ide> namespace Cake\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide>
<ide> /**
<ide> * Offers a method to convert values to ExpressionInterface objects
<ide> protected function _castToExpression($value, $type)
<ide> }
<ide>
<ide> $baseType = str_replace('[]', '', $type);
<del> $converter = Type::build($baseType);
<add> $converter = TypeFactory::build($baseType);
<ide>
<ide> if (!$converter instanceof ExpressionTypeInterface) {
<ide> return $value;
<ide> protected function _requiresToExpressionCasting($types)
<ide> $result = [];
<ide> $types = array_filter($types);
<ide> foreach ($types as $k => $type) {
<del> $object = Type::build($type);
<add> $object = TypeFactory::build($type);
<ide> if ($object instanceof ExpressionTypeInterface) {
<ide> $result[$k] = $object;
<ide> }
<ide><path>src/Database/TypeConverterTrait.php
<ide> trait TypeConverterTrait
<ide> public function cast($value, $type)
<ide> {
<ide> if (is_string($type)) {
<del> $type = Type::build($type);
<add> $type = TypeFactory::build($type);
<ide> }
<ide> if ($type instanceof TypeInterface) {
<ide> $value = $type->toDatabase($value, $this->_driver);
<ide><path>src/ORM/Behavior/TimestampBehavior.php
<ide> */
<ide> namespace Cake\ORM\Behavior;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\Type\DateTimeType;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Event\Event;
<ide> use Cake\I18n\Time;
<ide> protected function _updateField($entity, $field, $refreshTimestamp)
<ide> }
<ide>
<ide> /** @var \Cake\Database\Type\DateTimeType $type */
<del> $type = Type::build($columnType);
<add> $type = TypeFactory::build($columnType);
<ide>
<del> if (!$type instanceof Type\DateTimeType) {
<add> if (!$type instanceof DateTimeType) {
<ide> deprecationWarning('TimestampBehavior support for column types other than DateTimeType will be removed in 4.0.');
<ide> $entity->set($field, (string)$ts);
<ide>
<ide><path>src/ORM/Marshaller.php
<ide> use ArrayObject;
<ide> use Cake\Collection\Collection;
<ide> use Cake\Database\Expression\TupleComparison;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\InvalidPropertyInterface;
<ide> use Cake\ORM\Association\BelongsToMany;
<ide> protected function _buildPropertyMap($data, $options)
<ide> $columnType = $schema->getColumnType($prop);
<ide> if ($columnType) {
<ide> $map[$prop] = function ($value, $entity) use ($columnType) {
<del> return Type::build($columnType)->marshal($value);
<add> return TypeFactory::build($columnType)->marshal($value);
<ide> };
<ide> }
<ide> }
<ide><path>src/ORM/ResultSet.php
<ide> use Cake\Collection\Collection;
<ide> use Cake\Collection\CollectionTrait;
<ide> use Cake\Database\Exception;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\ResultSetInterface;
<ide> use SplFixedArray;
<ide><path>src/ORM/Table.php
<ide> use BadMethodCallException;
<ide> use Cake\Core\App;
<ide> use Cake\Database\Schema\TableSchema;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory ;
<ide> use Cake\Datasource\ConnectionInterface;
<ide> use Cake\Datasource\EntityInterface;
<ide> use Cake\Datasource\Exception\InvalidPrimaryKeyException;
<ide> protected function _insert($entity, $data)
<ide> if (!isset($data[$key])) {
<ide> $id = $statement->lastInsertId($this->getTable(), $key);
<ide> $type = $schema->getColumnType($key);
<del> $entity->set($key, Type::build($type)->toPHP($id, $driver));
<add> $entity->set($key, TypeFactory::build($type)->toPHP($id, $driver));
<ide> break;
<ide> }
<ide> }
<ide> protected function _newId($primary)
<ide> return null;
<ide> }
<ide> $typeName = $this->getSchema()->getColumnType($primary[0]);
<del> $type = Type::build($typeName);
<add> $type = TypeFactory::build($typeName);
<ide>
<ide> return $type->newId();
<ide> }
<ide><path>tests/TestCase/Database/ExpressionTypeCastingIntegrationTest.php
<ide> use Cake\Database\Driver;
<ide> use Cake\Database\Driver\Sqlserver;
<ide> use Cake\Database\Expression\FunctionExpression;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<add>use Cake\Database\Type\BaseType;
<ide> use Cake\Database\Type\ExpressionTypeInterface;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide> public function __construct($value)
<ide> /**
<ide> * Custom type class that maps between value objects, and SQL expressions.
<ide> */
<del>class OrderedUuidType extends Type implements ExpressionTypeInterface
<add>class OrderedUuidType extends BaseType implements ExpressionTypeInterface
<ide> {
<ide>
<ide> public function toPHP($value, Driver $d)
<ide> public function toExpression($value)
<ide> [$substr(15, 4), $substr(10, 4), $substr(1, 8), $substr(20, 4), $substr(25)]
<ide> );
<ide> }
<add>
<add> public function marshal($value)
<add> {
<add> return $value;
<add> }
<add>
<add> public function toDatabase($value, Driver $d)
<add> {
<add> return $value;
<add> }
<ide> }
<ide>
<ide> /**
<ide> public function setUp()
<ide> parent::setUp();
<ide> $this->connection = ConnectionManager::get('test');
<ide> $this->skipIf($this->connection->getDriver() instanceof Sqlserver, 'This tests uses functions specific to other drivers');
<del> Type::map('ordered_uuid', OrderedUuidType::class);
<add> TypeFactory::map('ordered_uuid', OrderedUuidType::class);
<ide> }
<ide>
<ide> protected function _insert()
<ide><path>tests/TestCase/Database/ExpressionTypeCastingTest.php
<ide> use Cake\Database\Expression\Comparison;
<ide> use Cake\Database\Expression\FunctionExpression;
<ide> use Cake\Database\Expression\ValuesExpression;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\ExpressionTypeInterface;
<ide> use Cake\Database\Type\StringType;
<ide> use Cake\Database\ValueBinder;
<ide> class ExpressionTypeCastingTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> Type::set('test', new TestType);
<add> TypeFactory::set('test', new TestType);
<ide> }
<ide>
<ide> /**
<ide><path>tests/TestCase/Database/Schema/TableSchemaTest.php
<ide> namespace Cake\Test\TestCase\Database\Schema;
<ide>
<ide> use Cake\Database\Schema\TableSchema;
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\IntegerType;
<ide> use Cake\Datasource\ConnectionManager;
<ide> use Cake\TestSuite\TestCase;
<ide> class TableTest extends TestCase
<ide>
<ide> public function setUp()
<ide> {
<del> $this->_map = Type::getMap();
<add> $this->_map = TypeFactory::getMap();
<ide> parent::setUp();
<ide> }
<ide>
<ide> public function tearDown()
<ide> {
<ide> $this->getTableLocator()->clear();
<del> Type::clear();
<del> Type::setMap($this->_map);
<add> TypeFactory::clear();
<add> TypeFactory::setMap($this->_map);
<ide> parent::tearDown();
<ide> }
<ide>
<ide> public function testBaseColumnType()
<ide> */
<ide> public function testBaseColumnTypeInherited()
<ide> {
<del> Type::map('foo', __NAMESPACE__ . '\FooType');
<add> TypeFactory::map('foo', __NAMESPACE__ . '\FooType');
<ide> $table = new TableSchema('articles');
<ide> $table->addColumn('thing', [
<ide> 'type' => 'foo',
<ide><path>tests/TestCase/Database/Type/BinaryTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class BinaryTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('binary');
<add> $this->type = TypeFactory::build('binary');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/BinaryUuidTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\BinaryUuidType;
<ide> use Cake\TestSuite\TestCase;
<ide> use Cake\Utility\Text;
<ide><path>tests/TestCase/Database/Type/BoolTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class BoolTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('boolean');
<add> $this->type = TypeFactory::build('boolean');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/DecimalTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\DecimalType;
<ide> use Cake\I18n\I18n;
<ide> use Cake\TestSuite\TestCase;
<ide> class DecimalTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('decimal');
<add> $this->type = TypeFactory::build('decimal');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> $this->localeString = I18n::getLocale();
<ide> $this->numberClass = DecimalType::$numberClass;
<ide><path>tests/TestCase/Database/Type/FloatTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\Type\FloatType;
<ide> use Cake\I18n\I18n;
<ide> use Cake\TestSuite\TestCase;
<ide> class FloatTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('float');
<add> $this->type = TypeFactory::build('float');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> $this->localeString = I18n::getLocale();
<ide> $this->numberClass = FloatType::$numberClass;
<ide><path>tests/TestCase/Database/Type/IntegerTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class IntegerTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('integer');
<add> $this->type = TypeFactory::build('integer');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/JsonTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class JsonTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('json');
<add> $this->type = TypeFactory::build('json');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/StringTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class StringTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('string');
<add> $this->type = TypeFactory::build('string');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/Type/UuidTypeTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide>
<ide> class UuidTypeTest extends TestCase
<ide> public function setUp()
<ide> {
<ide> parent::setUp();
<del> $this->type = Type::build('uuid');
<add> $this->type = TypeFactory::build('uuid');
<ide> $this->driver = $this->getMockBuilder('Cake\Database\Driver')->getMock();
<ide> }
<ide>
<ide><path>tests/TestCase/Database/TypeFactoryTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\Database;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory;
<ide> use Cake\Database\TypeInterface;
<ide> use Cake\TestSuite\TestCase;
<ide> use PDO;
<ide> class TypeFactoryTest extends TestCase
<ide> */
<ide> public function setUp()
<ide> {
<del> $this->_originalMap = Type::getMap();
<add> $this->_originalMap = TypeFactory::getMap();
<ide> parent::setUp();
<ide> }
<ide>
<ide> public function tearDown()
<ide> {
<ide> parent::tearDown();
<ide>
<del> Type::setMap($this->_originalMap);
<add> TypeFactory::setMap($this->_originalMap);
<ide> }
<ide>
<ide> /**
<ide> public function tearDown()
<ide> */
<ide> public function testBuildBasicTypes($name)
<ide> {
<del> $type = Type::build($name);
<add> $type = TypeFactory::build($name);
<ide> $this->assertInstanceOf(TypeInterface::class, $type);
<ide> $this->assertEquals($name, $type->getName());
<ide> $this->assertEquals($name, $type->getBaseType());
<ide> public function basicTypesProvider()
<ide> public function testBuildUnknownType()
<ide> {
<ide> $this->expectException(\InvalidArgumentException::class);
<del> Type::build('foo');
<add> TypeFactory::build('foo');
<ide> }
<ide>
<ide> /**
<ide> public function testBuildUnknownType()
<ide> */
<ide> public function testInstanceRecycling()
<ide> {
<del> $type = Type::build('integer');
<del> $this->assertSame($type, Type::build('integer'));
<add> $type = TypeFactory::build('integer');
<add> $this->assertSame($type, TypeFactory::build('integer'));
<ide> }
<ide>
<ide> /**
<ide> public function testInstanceRecycling()
<ide> */
<ide> public function testMapAndBuild()
<ide> {
<del> $map = Type::getMap();
<add> $map = TypeFactory::getMap();
<ide> $this->assertNotEmpty($map);
<ide> $this->assertArrayNotHasKey('foo', $map);
<ide>
<ide> $fooType = FooType::class;
<del> Type::map('foo', $fooType);
<del> $map = Type::getMap();
<add> TypeFactory::map('foo', $fooType);
<add> $map = TypeFactory::getMap();
<ide> $this->assertEquals($fooType, $map['foo']);
<del> $this->assertEquals($fooType, Type::getMap('foo'));
<add> $this->assertEquals($fooType, TypeFactory::getMap('foo'));
<ide>
<del> Type::map('foo2', $fooType);
<del> $map = Type::getMap();
<add> TypeFactory::map('foo2', $fooType);
<add> $map = TypeFactory::getMap();
<ide> $this->assertSame($fooType, $map['foo2']);
<del> $this->assertSame($fooType, Type::getMap('foo2'));
<add> $this->assertSame($fooType, TypeFactory::getMap('foo2'));
<ide>
<del> $type = Type::build('foo2');
<add> $type = TypeFactory::build('foo2');
<ide> $this->assertInstanceOf($fooType, $type);
<ide> }
<ide>
<ide> public function testMapAndBuild()
<ide> public function testReMapAndBuild()
<ide> {
<ide> $fooType = FooType::class;
<del> Type::map('foo', $fooType);
<del> $type = Type::build('foo');
<add> TypeFactory::map('foo', $fooType);
<add> $type = TypeFactory::build('foo');
<ide> $this->assertInstanceOf($fooType, $type);
<ide>
<ide> $barType = BarType::class;
<del> Type::map('foo', $barType);
<del> $type = Type::build('foo');
<add> TypeFactory::map('foo', $barType);
<add> $type = TypeFactory::build('foo');
<ide> $this->assertInstanceOf($barType, $type);
<ide> }
<ide>
<ide> public function testReMapAndBuild()
<ide> */
<ide> public function testClear()
<ide> {
<del> $map = Type::getMap();
<add> $map = TypeFactory::getMap();
<ide> $this->assertNotEmpty($map);
<ide>
<del> $type = Type::build('float');
<del> Type::clear();
<add> $type = TypeFactory::build('float');
<add> TypeFactory::clear();
<ide>
<del> $this->assertEmpty(Type::getMap());
<del> Type::setMap($map);
<del> $newMap = Type::getMap();
<add> $this->assertEmpty(TypeFactory::getMap());
<add> TypeFactory::setMap($map);
<add> $newMap = TypeFactory::getMap();
<ide>
<ide> $this->assertEquals(array_keys($map), array_keys($newMap));
<ide> $this->assertEquals($map['integer'], $newMap['integer']);
<del> $this->assertEquals($type, Type::build('float'));
<add> $this->assertEquals($type, TypeFactory::build('float'));
<ide> }
<ide>
<ide> /**
<ide> public function testBigintegerToPHP()
<ide> PHP_INT_SIZE === 4,
<ide> 'This test requires a php version compiled for 64 bits'
<ide> );
<del> $type = Type::build('biginteger');
<add> $type = TypeFactory::build('biginteger');
<ide> $integer = time() * time();
<ide> $driver = $this->getMockBuilder('\Cake\Database\Driver')->getMock();
<ide> $this->assertSame($integer, $type->toPHP($integer, $driver));
<ide> public function testBigintegerToPHP()
<ide> */
<ide> public function testBigintegerToStatement()
<ide> {
<del> $type = Type::build('biginteger');
<add> $type = TypeFactory::build('biginteger');
<ide> $integer = time() * time();
<ide> $driver = $this->getMockBuilder('\Cake\Database\Driver')->getMock();
<ide> $this->assertEquals(PDO::PARAM_INT, $type->toStatement($integer, $driver));
<ide> public function testBigintegerToStatement()
<ide> */
<ide> public function testDecimalToPHP()
<ide> {
<del> $type = Type::build('decimal');
<add> $type = TypeFactory::build('decimal');
<ide> $driver = $this->getMockBuilder('\Cake\Database\Driver')->getMock();
<ide>
<ide> $this->assertSame(3.14159, $type->toPHP('3.14159', $driver));
<ide> public function testDecimalToPHP()
<ide> */
<ide> public function testDecimalToStatement()
<ide> {
<del> $type = Type::build('decimal');
<add> $type = TypeFactory::build('decimal');
<ide> $string = '12.55';
<ide> $driver = $this->getMockBuilder('\Cake\Database\Driver')->getMock();
<ide> $this->assertEquals(PDO::PARAM_STR, $type->toStatement($string, $driver));
<ide> public function testDecimalToStatement()
<ide> public function testSet()
<ide> {
<ide> $instance = $this->getMockBuilder(TypeInterface::class)->getMock();
<del> Type::set('random', $instance);
<del> $this->assertSame($instance, Type::build('random'));
<add> TypeFactory::set('random', $instance);
<add> $this->assertSame($instance, TypeFactory::build('random'));
<ide> }
<ide> }
<ide><path>tests/TestCase/ORM/Behavior/TimestampBehaviorTest.php
<ide> */
<ide> namespace Cake\Test\TestCase\ORM\Behavior;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\TypeFactory ;
<ide> use Cake\Event\Event;
<ide> use Cake\I18n\Time;
<ide> use Cake\ORM\Behavior\TimestampBehavior;
<ide> public function testUseImmutable()
<ide> $entity = new Entity();
<ide> $event = new Event('Model.beforeSave');
<ide>
<del> Type::build('timestamp')->useImmutable();
<add> TypeFactory::build('timestamp')->useImmutable();
<ide> $entity->clean();
<ide> $this->Behavior->handleEvent($event, $entity);
<ide> $this->assertInstanceOf('Cake\I18n\FrozenTime', $entity->modified);
<ide>
<del> Type::build('timestamp')->useMutable();
<add> TypeFactory::build('timestamp')->useMutable();
<ide> $entity->clean();
<ide> $this->Behavior->handleEvent($event, $entity);
<ide> $this->assertInstanceOf('Cake\I18n\Time', $entity->modified);
<ide><path>tests/test_app/TestApp/Database/Type/BarType.php
<ide> */
<ide> namespace TestApp\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\Type\StringType;
<ide>
<del>class BarType extends Type
<add>class BarType extends StringType
<ide> {
<ide> public function getBaseType()
<ide> {
<ide><path>tests/test_app/TestApp/Database/Type/FooType.php
<ide> */
<ide> namespace TestApp\Database\Type;
<ide>
<del>use Cake\Database\Type;
<add>use Cake\Database\Type\StringType;
<ide>
<del>class FooType extends Type
<add>class FooType extends StringType
<ide> {
<ide> public function getBaseType()
<ide> { | 29 |
PHP | PHP | add test for request method() method | ad431e0267bb41eb97182bfdc33fe7853ef089a9 | <ide><path>tests/Http/HttpRequestTest.php
<ide> public function testInstanceMethod()
<ide> $this->assertSame($request, $request->instance());
<ide> }
<ide>
<add> public function testMethodMethod()
<add> {
<add> $request = Request::create('', 'GET');
<add> $this->assertSame('GET', $request->method());
<add>
<add> $request = Request::create('', 'HEAD');
<add> $this->assertSame('HEAD', $request->method());
<add>
<add> $request = Request::create('', 'POST');
<add> $this->assertSame('POST', $request->method());
<add>
<add> $request = Request::create('', 'PUT');
<add> $this->assertSame('PUT', $request->method());
<add>
<add> $request = Request::create('', 'PATCH');
<add> $this->assertSame('PATCH', $request->method());
<add>
<add> $request = Request::create('', 'DELETE');
<add> $this->assertSame('DELETE', $request->method());
<add>
<add> $request = Request::create('', 'OPTIONS');
<add> $this->assertSame('OPTIONS', $request->method());
<add> }
<add>
<ide> public function testRootMethod()
<ide> {
<ide> $request = Request::create('http://example.com/foo/bar/script.php?test'); | 1 |
Javascript | Javascript | extract fizz instruction set to build macro | a6bf466892c23a100991580895ddd80667c1b777 | <ide><path>packages/react-dom-bindings/src/server/ReactDOMServerFormatConfig.js
<ide> export {
<ide> hoistResourcesToRoot,
<ide> } from './ReactDOMFloatServer';
<ide>
<add>import completeSegmentFunction from './fizz-instruction-set/completeSegmentFunctionString';
<add>import completeBoundaryFunction from './fizz-instruction-set/completeBoundaryFunctionString';
<add>import styleInsertionFunction from './fizz-instruction-set/styleInsertionFunctionString';
<add>import clientRenderFunction from './fizz-instruction-set/clientRenderFunctionString';
<add>
<ide> import ReactDOMSharedInternals from 'shared/ReactDOMSharedInternals';
<ide> const ReactDOMCurrentDispatcher = ReactDOMSharedInternals.Dispatcher;
<ide>
<ide> export function writeEndSegment(
<ide> }
<ide> }
<ide>
<del>// Instruction Set
<del>
<del>// The following code is the source scripts that we then minify and inline below,
<del>// with renamed function names that we hope don't collide:
<del>
<del>// const COMMENT_NODE = 8;
<del>// const SUSPENSE_START_DATA = '$';
<del>// const SUSPENSE_END_DATA = '/$';
<del>// const SUSPENSE_PENDING_START_DATA = '$?';
<del>// const SUSPENSE_FALLBACK_START_DATA = '$!';
<del>// const LOADED = 'l';
<del>// const ERRORED = 'e';
<del>
<del>// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
<del>// // Find the fallback's first element.
<del>// const suspenseIdNode = document.getElementById(suspenseBoundaryID);
<del>// if (!suspenseIdNode) {
<del>// // The user must have already navigated away from this tree.
<del>// // E.g. because the parent was hydrated.
<del>// return;
<del>// }
<del>// // Find the boundary around the fallback. This is always the previous node.
<del>// const suspenseNode = suspenseIdNode.previousSibling;
<del>// // Tag it to be client rendered.
<del>// suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
<del>// // assign error metadata to first sibling
<del>// let dataset = suspenseIdNode.dataset;
<del>// if (errorDigest) dataset.dgst = errorDigest;
<del>// if (errorMsg) dataset.msg = errorMsg;
<del>// if (errorComponentStack) dataset.stck = errorComponentStack;
<del>// // Tell React to retry it if the parent already hydrated.
<del>// if (suspenseNode._reactRetry) {
<del>// suspenseNode._reactRetry();
<del>// }
<del>// }
<del>
<del>// resourceMap = new Map();
<del>// function completeBoundaryWithStyles(suspenseBoundaryID, contentID, styles) {
<del>// const precedences = new Map();
<del>// const thisDocument = document;
<del>// let lastResource, node;
<del>
<del>// // Seed the precedence list with existing resources
<del>// let nodes = thisDocument.querySelectorAll('link[data-rprec]');
<del>// for (let i = 0;node = nodes[i++];) {
<del>// precedences.set(node.dataset.rprec, lastResource = node);
<del>// }
<del>
<del>// let i = 0;
<del>// let dependencies = [];
<del>// let style, href, precedence, attr, loadingState, resourceEl;
<del>
<del>// function setStatus(s) {
<del>// this.s = s;
<del>// }
<del>
<del>// while (style = styles[i++]) {
<del>// let j = 0;
<del>// href = style[j++];
<del>// // We check if this resource is already in our resourceMap and reuse it if so.
<del>// // If it is already loaded we don't return it as a depenendency since there is nothing
<del>// // to wait for
<del>// loadingState = resourceMap.get(href);
<del>// if (loadingState) {
<del>// if (loadingState.s !== 'l') {
<del>// dependencies.push(loadingState);
<del>// }
<del>// continue;
<del>// }
<del>
<del>// // We construct our new resource element, looping over remaining attributes if any
<del>// // setting them to the Element.
<del>// resourceEl = thisDocument.createElement("link");
<del>// resourceEl.href = href;
<del>// resourceEl.rel = 'stylesheet';
<del>// resourceEl.dataset.rprec = precedence = style[j++];
<del>// while(attr = style[j++]) {
<del>// resourceEl.setAttribute(attr, style[j++]);
<del>// }
<del>
<del>// // We stash a pending promise in our map by href which will resolve or reject
<del>// // when the underlying resource loads or errors. We add it to the dependencies
<del>// // array to be returned.
<del>// loadingState = resourceEl._p = new Promise((re, rj) => {
<del>// resourceEl.onload = re;
<del>// resourceEl.onerror = rj;
<del>// })
<del>// loadingState.then(
<del>// setStatus.bind(loadingState, LOADED),
<del>// setStatus.bind(loadingState, ERRORED)
<del>// );
<del>// resourceMap.set(href, loadingState);
<del>// dependencies.push(loadingState);
<del>
<del>// // The prior style resource is the last one placed at a given
<del>// // precedence or the last resource itself which may be null.
<del>// // We grab this value and then update the last resource for this
<del>// // precedence to be the inserted element, updating the lastResource
<del>// // pointer if needed.
<del>// let prior = precedences.get(precedence) || lastResource;
<del>// if (prior === lastResource) {
<del>// lastResource = resourceEl
<del>// }
<del>// precedences.set(precedence, resourceEl)
<del>
<del>// // Finally, we insert the newly constructed instance at an appropriate location
<del>// // in the Document.
<del>// if (prior) {
<del>// prior.parentNode.insertBefore(resourceEl, prior.nextSibling);
<del>// } else {
<del>// let head = thisDocument.head;
<del>// head.insertBefore(resourceEl, head.firstChild);
<del>// }
<del>// }
<del>
<del>// Promise.all(dependencies).then(
<del>// completeBoundary.bind(null, suspenseBoundaryID, contentID, ''),
<del>// completeBoundary.bind(null, suspenseBoundaryID, contentID, "Resource failed to load")
<del>// );
<del>// }
<del>
<del>// function completeBoundary(suspenseBoundaryID, contentID, errorDigest) {
<del>// const contentNode = document.getElementById(contentID);
<del>// // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
<del>// // This might also help by not causing recalcing each time we move a child from here to the target.
<del>// contentNode.parentNode.removeChild(contentNode);
<del>
<del>// // Find the fallback's first element.
<del>// const suspenseIdNode = document.getElementById(suspenseBoundaryID);
<del>// if (!suspenseIdNode) {
<del>// // The user must have already navigated away from this tree.
<del>// // E.g. because the parent was hydrated. That's fine there's nothing to do
<del>// // but we have to make sure that we already deleted the container node.
<del>// return;
<del>// }
<del>// // Find the boundary around the fallback. This is always the previous node.
<del>// const suspenseNode = suspenseIdNode.previousSibling;
<del>
<del>// if (!errorDigest) {
<del>// // Clear all the existing children. This is complicated because
<del>// // there can be embedded Suspense boundaries in the fallback.
<del>// // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
<del>// // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
<del>// // They never hydrate anyway. However, currently we support incrementally loading the fallback.
<del>// const parentInstance = suspenseNode.parentNode;
<del>// let node = suspenseNode.nextSibling;
<del>// let depth = 0;
<del>// do {
<del>// if (node && node.nodeType === COMMENT_NODE) {
<del>// const data = node.data;
<del>// if (data === SUSPENSE_END_DATA) {
<del>// if (depth === 0) {
<del>// break;
<del>// } else {
<del>// depth--;
<del>// }
<del>// } else if (
<del>// data === SUSPENSE_START_DATA ||
<del>// data === SUSPENSE_PENDING_START_DATA ||
<del>// data === SUSPENSE_FALLBACK_START_DATA
<del>// ) {
<del>// depth++;
<del>// }
<del>// }
<del>
<del>// const nextNode = node.nextSibling;
<del>// parentInstance.removeChild(node);
<del>// node = nextNode;
<del>// } while (node);
<del>
<del>// const endOfBoundary = node;
<del>
<del>// // Insert all the children from the contentNode between the start and end of suspense boundary.
<del>// while (contentNode.firstChild) {
<del>// parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
<del>// }
<del>
<del>// suspenseNode.data = SUSPENSE_START_DATA;
<del>// } else {
<del>// suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
<del>// suspenseIdNode.setAttribute('data-dgst', errorDigest)
<del>// }
<del>
<del>// if (suspenseNode._reactRetry) {
<del>// suspenseNode._reactRetry();
<del>// }
<del>// }
<del>
<del>// function completeSegment(containerID, placeholderID) {
<del>// const segmentContainer = document.getElementById(containerID);
<del>// const placeholderNode = document.getElementById(placeholderID);
<del>// // We always expect both nodes to exist here because, while we might
<del>// // have navigated away from the main tree, we still expect the detached
<del>// // tree to exist.
<del>// segmentContainer.parentNode.removeChild(segmentContainer);
<del>// while (segmentContainer.firstChild) {
<del>// placeholderNode.parentNode.insertBefore(
<del>// segmentContainer.firstChild,
<del>// placeholderNode,
<del>// );
<del>// }
<del>// placeholderNode.parentNode.removeChild(placeholderNode);
<del>// }
<del>
<del>const completeSegmentFunction =
<del> 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
<del>const completeBoundaryFunction =
<del> 'function $RC(b,c,d){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(d)b.data="$!",a.setAttribute("data-dgst",d);else{d=b.parentNode;a=b.nextSibling;var e=0;do{if(a&&a.nodeType===8){var h=a.data;if(h==="/$")if(0===e)break;else e--;else h!=="$"&&h!=="$?"&&h!=="$!"||e++}h=a.nextSibling;d.removeChild(a);a=h}while(a);for(;c.firstChild;)d.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}}';
<del>const styleInsertionFunction =
<del> '$RM=new Map;function $RR(p,q,t){function r(l){this.s=l}for(var m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-rprec]"),d=0;e=f[d++];)m.set(e.dataset.rprec,g=e);e=0;f=[];for(var c,h,b,a;c=t[e++];){var k=0;h=c[k++];if(b=$RM.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.rprec=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,u){a.onload=l;a.onerror=u});b.then(r.bind(b,"l"),r.bind(b,"e"));$RM.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then($RC.bind(null,p,q,""),$RC.bind(null,p,q,"Resource failed to load"))}';
<del>const clientRenderFunction =
<del> 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
<del>
<ide> const completeSegmentScript1Full = stringToPrecomputedChunk(
<ide> completeSegmentFunction + ';$RS("',
<ide> );
<ide><path>packages/react-dom-bindings/src/server/fizz-instruction-set/clientRenderFunctionString.js
<add>// Instruction Set
<add>
<add>// The following code is the source scripts that we then minify and inline below,
<add>// with renamed function names that we hope don't collide:
<add>
<add>// const COMMENT_NODE = 8;
<add>// const SUSPENSE_START_DATA = '$';
<add>// const SUSPENSE_END_DATA = '/$';
<add>// const SUSPENSE_PENDING_START_DATA = '$?';
<add>// const SUSPENSE_FALLBACK_START_DATA = '$!';
<add>// const LOADED = 'l';
<add>// const ERRORED = 'e';
<add>
<add>// function clientRenderBoundary(suspenseBoundaryID, errorDigest, errorMsg, errorComponentStack) {
<add>// // Find the fallback's first element.
<add>// const suspenseIdNode = document.getElementById(suspenseBoundaryID);
<add>// if (!suspenseIdNode) {
<add>// // The user must have already navigated away from this tree.
<add>// // E.g. because the parent was hydrated.
<add>// return;
<add>// }
<add>// // Find the boundary around the fallback. This is always the previous node.
<add>// const suspenseNode = suspenseIdNode.previousSibling;
<add>// // Tag it to be client rendered.
<add>// suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
<add>// // assign error metadata to first sibling
<add>// let dataset = suspenseIdNode.dataset;
<add>// if (errorDigest) dataset.dgst = errorDigest;
<add>// if (errorMsg) dataset.msg = errorMsg;
<add>// if (errorComponentStack) dataset.stck = errorComponentStack;
<add>// // Tell React to retry it if the parent already hydrated.
<add>// if (suspenseNode._reactRetry) {
<add>// suspenseNode._reactRetry();
<add>// }
<add>// }
<add>
<add>// TODO: Generate this file with a build step.
<add>export default 'function $RX(b,c,d,e){var a=document.getElementById(b);a&&(b=a.previousSibling,b.data="$!",a=a.dataset,c&&(a.dgst=c),d&&(a.msg=d),e&&(a.stck=e),b._reactRetry&&b._reactRetry())}';
<ide><path>packages/react-dom-bindings/src/server/fizz-instruction-set/completeBoundaryFunctionString.js
<add>// Instruction Set
<add>
<add>// The following code is the source scripts that we then minify and inline below,
<add>// with renamed function names that we hope don't collide:
<add>
<add>// const COMMENT_NODE = 8;
<add>// const SUSPENSE_START_DATA = '$';
<add>// const SUSPENSE_END_DATA = '/$';
<add>// const SUSPENSE_PENDING_START_DATA = '$?';
<add>// const SUSPENSE_FALLBACK_START_DATA = '$!';
<add>// const LOADED = 'l';
<add>// const ERRORED = 'e';
<add>
<add>// function completeBoundary(suspenseBoundaryID, contentID, errorDigest) {
<add>// const contentNode = document.getElementById(contentID);
<add>// // We'll detach the content node so that regardless of what happens next we don't leave in the tree.
<add>// // This might also help by not causing recalcing each time we move a child from here to the target.
<add>// contentNode.parentNode.removeChild(contentNode);
<add>
<add>// // Find the fallback's first element.
<add>// const suspenseIdNode = document.getElementById(suspenseBoundaryID);
<add>// if (!suspenseIdNode) {
<add>// // The user must have already navigated away from this tree.
<add>// // E.g. because the parent was hydrated. That's fine there's nothing to do
<add>// // but we have to make sure that we already deleted the container node.
<add>// return;
<add>// }
<add>// // Find the boundary around the fallback. This is always the previous node.
<add>// const suspenseNode = suspenseIdNode.previousSibling;
<add>
<add>// if (!errorDigest) {
<add>// // Clear all the existing children. This is complicated because
<add>// // there can be embedded Suspense boundaries in the fallback.
<add>// // This is similar to clearSuspenseBoundary in ReactDOMHostConfig.
<add>// // TODO: We could avoid this if we never emitted suspense boundaries in fallback trees.
<add>// // They never hydrate anyway. However, currently we support incrementally loading the fallback.
<add>// const parentInstance = suspenseNode.parentNode;
<add>// let node = suspenseNode.nextSibling;
<add>// let depth = 0;
<add>// do {
<add>// if (node && node.nodeType === COMMENT_NODE) {
<add>// const data = node.data;
<add>// if (data === SUSPENSE_END_DATA) {
<add>// if (depth === 0) {
<add>// break;
<add>// } else {
<add>// depth--;
<add>// }
<add>// } else if (
<add>// data === SUSPENSE_START_DATA ||
<add>// data === SUSPENSE_PENDING_START_DATA ||
<add>// data === SUSPENSE_FALLBACK_START_DATA
<add>// ) {
<add>// depth++;
<add>// }
<add>// }
<add>
<add>// const nextNode = node.nextSibling;
<add>// parentInstance.removeChild(node);
<add>// node = nextNode;
<add>// } while (node);
<add>
<add>// const endOfBoundary = node;
<add>
<add>// // Insert all the children from the contentNode between the start and end of suspense boundary.
<add>// while (contentNode.firstChild) {
<add>// parentInstance.insertBefore(contentNode.firstChild, endOfBoundary);
<add>// }
<add>
<add>// suspenseNode.data = SUSPENSE_START_DATA;
<add>// } else {
<add>// suspenseNode.data = SUSPENSE_FALLBACK_START_DATA;
<add>// suspenseIdNode.setAttribute('data-dgst', errorDigest)
<add>// }
<add>
<add>// if (suspenseNode._reactRetry) {
<add>// suspenseNode._reactRetry();
<add>// }
<add>// }
<add>
<add>// TODO: Generate this file with a build step.
<add>export default 'function $RC(b,c,d){c=document.getElementById(c);c.parentNode.removeChild(c);var a=document.getElementById(b);if(a){b=a.previousSibling;if(d)b.data="$!",a.setAttribute("data-dgst",d);else{d=b.parentNode;a=b.nextSibling;var e=0;do{if(a&&a.nodeType===8){var h=a.data;if(h==="/$")if(0===e)break;else e--;else h!=="$"&&h!=="$?"&&h!=="$!"||e++}h=a.nextSibling;d.removeChild(a);a=h}while(a);for(;c.firstChild;)d.insertBefore(c.firstChild,a);b.data="$"}b._reactRetry&&b._reactRetry()}}';
<ide><path>packages/react-dom-bindings/src/server/fizz-instruction-set/completeSegmentFunctionString.js
<add>// Instruction Set
<add>
<add>// The following code is the source scripts that we then minify and inline below,
<add>// with renamed function names that we hope don't collide:
<add>
<add>// const COMMENT_NODE = 8;
<add>// const SUSPENSE_START_DATA = '$';
<add>// const SUSPENSE_END_DATA = '/$';
<add>// const SUSPENSE_PENDING_START_DATA = '$?';
<add>// const SUSPENSE_FALLBACK_START_DATA = '$!';
<add>// const LOADED = 'l';
<add>// const ERRORED = 'e';
<add>
<add>// function completeSegment(containerID, placeholderID) {
<add>// const segmentContainer = document.getElementById(containerID);
<add>// const placeholderNode = document.getElementById(placeholderID);
<add>// // We always expect both nodes to exist here because, while we might
<add>// // have navigated away from the main tree, we still expect the detached
<add>// // tree to exist.
<add>// segmentContainer.parentNode.removeChild(segmentContainer);
<add>// while (segmentContainer.firstChild) {
<add>// placeholderNode.parentNode.insertBefore(
<add>// segmentContainer.firstChild,
<add>// placeholderNode,
<add>// );
<add>// }
<add>// placeholderNode.parentNode.removeChild(placeholderNode);
<add>// }
<add>
<add>// TODO: Generate this file with a build step.
<add>export default 'function $RS(a,b){a=document.getElementById(a);b=document.getElementById(b);for(a.parentNode.removeChild(a);a.firstChild;)b.parentNode.insertBefore(a.firstChild,b);b.parentNode.removeChild(b)}';
<ide><path>packages/react-dom-bindings/src/server/fizz-instruction-set/styleInsertionFunctionString.js
<add>// Instruction Set
<add>
<add>// The following code is the source scripts that we then minify and inline below,
<add>// with renamed function names that we hope don't collide:
<add>
<add>// const COMMENT_NODE = 8;
<add>// const SUSPENSE_START_DATA = '$';
<add>// const SUSPENSE_END_DATA = '/$';
<add>// const SUSPENSE_PENDING_START_DATA = '$?';
<add>// const SUSPENSE_FALLBACK_START_DATA = '$!';
<add>// const LOADED = 'l';
<add>// const ERRORED = 'e';
<add>
<add>// resourceMap = new Map();
<add>// function completeBoundaryWithStyles(suspenseBoundaryID, contentID, styles) {
<add>// const precedences = new Map();
<add>// const thisDocument = document;
<add>// let lastResource, node;
<add>
<add>// // Seed the precedence list with existing resources
<add>// let nodes = thisDocument.querySelectorAll('link[data-rprec]');
<add>// for (let i = 0;node = nodes[i++];) {
<add>// precedences.set(node.dataset.rprec, lastResource = node);
<add>// }
<add>
<add>// let i = 0;
<add>// let dependencies = [];
<add>// let style, href, precedence, attr, loadingState, resourceEl;
<add>
<add>// function setStatus(s) {
<add>// this.s = s;
<add>// }
<add>
<add>// while (style = styles[i++]) {
<add>// let j = 0;
<add>// href = style[j++];
<add>// // We check if this resource is already in our resourceMap and reuse it if so.
<add>// // If it is already loaded we don't return it as a depenendency since there is nothing
<add>// // to wait for
<add>// loadingState = resourceMap.get(href);
<add>// if (loadingState) {
<add>// if (loadingState.s !== 'l') {
<add>// dependencies.push(loadingState);
<add>// }
<add>// continue;
<add>// }
<add>
<add>// // We construct our new resource element, looping over remaining attributes if any
<add>// // setting them to the Element.
<add>// resourceEl = thisDocument.createElement("link");
<add>// resourceEl.href = href;
<add>// resourceEl.rel = 'stylesheet';
<add>// resourceEl.dataset.rprec = precedence = style[j++];
<add>// while(attr = style[j++]) {
<add>// resourceEl.setAttribute(attr, style[j++]);
<add>// }
<add>
<add>// // We stash a pending promise in our map by href which will resolve or reject
<add>// // when the underlying resource loads or errors. We add it to the dependencies
<add>// // array to be returned.
<add>// loadingState = resourceEl._p = new Promise((re, rj) => {
<add>// resourceEl.onload = re;
<add>// resourceEl.onerror = rj;
<add>// })
<add>// loadingState.then(
<add>// setStatus.bind(loadingState, LOADED),
<add>// setStatus.bind(loadingState, ERRORED)
<add>// );
<add>// resourceMap.set(href, loadingState);
<add>// dependencies.push(loadingState);
<add>
<add>// // The prior style resource is the last one placed at a given
<add>// // precedence or the last resource itself which may be null.
<add>// // We grab this value and then update the last resource for this
<add>// // precedence to be the inserted element, updating the lastResource
<add>// // pointer if needed.
<add>// let prior = precedences.get(precedence) || lastResource;
<add>// if (prior === lastResource) {
<add>// lastResource = resourceEl
<add>// }
<add>// precedences.set(precedence, resourceEl)
<add>
<add>// // Finally, we insert the newly constructed instance at an appropriate location
<add>// // in the Document.
<add>// if (prior) {
<add>// prior.parentNode.insertBefore(resourceEl, prior.nextSibling);
<add>// } else {
<add>// let head = thisDocument.head;
<add>// head.insertBefore(resourceEl, head.firstChild);
<add>// }
<add>// }
<add>
<add>// Promise.all(dependencies).then(
<add>// completeBoundary.bind(null, suspenseBoundaryID, contentID, ''),
<add>// completeBoundary.bind(null, suspenseBoundaryID, contentID, "Resource failed to load")
<add>// );
<add>// }
<add>
<add>// TODO: Generate this file with a build step.
<add>export default '$RM=new Map;function $RR(p,q,t){function r(l){this.s=l}for(var m=new Map,n=document,g,e,f=n.querySelectorAll("link[data-rprec]"),d=0;e=f[d++];)m.set(e.dataset.rprec,g=e);e=0;f=[];for(var c,h,b,a;c=t[e++];){var k=0;h=c[k++];if(b=$RM.get(h))"l"!==b.s&&f.push(b);else{a=n.createElement("link");a.href=h;a.rel="stylesheet";for(a.dataset.rprec=d=c[k++];b=c[k++];)a.setAttribute(b,c[k++]);b=a._p=new Promise(function(l,u){a.onload=l;a.onerror=u});b.then(r.bind(b,"l"),r.bind(b,"e"));$RM.set(h,b);f.push(b);c=m.get(d)||g;c===g&&(g=a);m.set(d,a);c?c.parentNode.insertBefore(a,c.nextSibling):(d=n.head,d.insertBefore(a,d.firstChild))}}Promise.all(f).then($RC.bind(null,p,q,""),$RC.bind(null,p,q,"Resource failed to load"))}'; | 5 |
Ruby | Ruby | install python bindings properly | 623b21a7bd2c346427f88e8711fb1e2d90aaa6e0 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def hgpath
<ide> @path ||= %W[
<ide> #{which("hg")}
<ide> #{HOMEBREW_PREFIX}/bin/hg
<add> #{Formula.factory('mercurial').opt_prefix}/bin/hg
<ide> #{HOMEBREW_PREFIX}/share/python/hg
<ide> ].find { |p| File.executable? p }
<ide> end | 1 |
Java | Java | resolve @repeatable container in annotationutils | a0040245ca3bf968aec55db00f401e10b71a875f | <ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotatedElementUtils.java
<ide> public static Set<String> getMetaAnnotationTypes(AnnotatedElement element, Strin
<ide> final Set<String> types = new LinkedHashSet<String>();
<ide>
<ide> try {
<del> Annotation annotation = getAnnotation(element, annotationName);
<add> Annotation annotation = AnnotationUtils.getAnnotation(element, annotationName);
<ide> if (annotation != null) {
<ide> searchWithGetSemantics(annotation.annotationType(), annotationName, new SimpleAnnotationProcessor<Object>() {
<ide>
<ide> private static <T> T searchOnInterfaces(Method method, String annotationName, Pr
<ide> return null;
<ide> }
<ide>
<del> /**
<del> * @since 4.2
<del> */
<del> private static Annotation getAnnotation(AnnotatedElement element, String annotationName) {
<del> for (Annotation annotation : element.getAnnotations()) {
<del> if (annotation.annotationType().getName().equals(annotationName)) {
<del> return annotation;
<del> }
<del> }
<del> return null;
<del> }
<del>
<del>
<ide> /**
<ide> * Callback interface that is used to process annotations during a search.
<ide> *
<ide><path>spring-core/src/main/java/org/springframework/core/annotation/AnnotationUtils.java
<ide> public static Annotation[] getAnnotations(Method method) {
<ide> }
<ide>
<ide> /**
<del> * Delegates to {@link #getRepeatableAnnotations}.
<add> * Delegates to {@link #getRepeatableAnnotations(AnnotatedElement, Class, Class)}.
<ide> * @since 4.0
<del> * @deprecated As of Spring Framework 4.2, use {@link #getRepeatableAnnotations}
<del> * or {@link #getDeclaredRepeatableAnnotations} instead.
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @deprecated As of Spring Framework 4.2, use {@code getRepeatableAnnotations()}
<add> * or {@code getDeclaredRepeatableAnnotations()} instead.
<ide> */
<ide> @Deprecated
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method method,
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotation(Method metho
<ide> }
<ide>
<ide> /**
<del> * Delegates to {@link #getRepeatableAnnotations}.
<add> * Delegates to {@link #getRepeatableAnnotations(AnnotatedElement, Class, Class)}.
<ide> * @since 4.0
<del> * @deprecated As of Spring Framework 4.2, use {@link #getRepeatableAnnotations}
<del> * or {@link #getDeclaredRepeatableAnnotations} instead.
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @deprecated As of Spring Framework 4.2, use {@code getRepeatableAnnotations()}
<add> * or {@code getDeclaredRepeatableAnnotations()} instead.
<ide> */
<ide> @Deprecated
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedElement annotatedElement,
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedEle
<ide> /**
<ide> * Get the <em>repeatable</em> {@linkplain Annotation annotations} of
<ide> * {@code annotationType} from the supplied {@link AnnotatedElement}, where
<del> * such annotations are either <em>present</em> or <em>meta-present</em>
<del> * on the element.
<add> * such annotations are either <em>present</em>, <em>indirectly present</em>,
<add> * or <em>meta-present</em> on the element.
<add> * <p>This method mimics the functionality of Java 8's
<add> * {@link java.lang.reflect.AnnotatedElement#getAnnotationsByType(Class)}
<add> * with support for automatic detection of a <em>container annotation</em>
<add> * declared via @{@link java.lang.annotation.Repeatable} (when running on
<add> * Java 8 or higher) and with additional support for meta-annotations.
<add> * <p>Handles both single annotations and annotations nested within a
<add> * <em>container annotation</em>.
<add> * <p>Correctly handles <em>bridge methods</em> generated by the
<add> * compiler if the supplied element is a {@link Method}.
<add> * <p>Meta-annotations will be searched if the annotation is not
<add> * <em>present</em> on the supplied element.
<add> * @param annotatedElement the element to look for annotations on; never {@code null}
<add> * @param annotationType the annotation type to look for; never {@code null}
<add> * @return the annotations found or an empty set; never {@code null}
<add> * @since 4.2
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod
<add> * @see java.lang.annotation.Repeatable
<add> * @see java.lang.reflect.AnnotatedElement#getAnnotationsByType
<add> */
<add> public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedElement annotatedElement,
<add> Class<A> annotationType) {
<add> return getRepeatableAnnotations(annotatedElement, annotationType, null);
<add> }
<add>
<add> /**
<add> * Get the <em>repeatable</em> {@linkplain Annotation annotations} of
<add> * {@code annotationType} from the supplied {@link AnnotatedElement}, where
<add> * such annotations are either <em>present</em>, <em>indirectly present</em>,
<add> * or <em>meta-present</em> on the element.
<ide> * <p>This method mimics the functionality of Java 8's
<ide> * {@link java.lang.reflect.AnnotatedElement#getAnnotationsByType(Class)}
<ide> * with additional support for meta-annotations.
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotation(AnnotatedEle
<ide> * @param annotationType the annotation type to look for; never {@code null}
<ide> * @param containerAnnotationType the type of the container that holds
<ide> * the annotations; may be {@code null} if a container is not supported
<add> * or if it should be looked up via @{@link java.lang.annotation.Repeatable}
<add> * when running on Java 8 or higher
<ide> * @return the annotations found or an empty set; never {@code null}
<ide> * @since 4.2
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class)
<ide> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
<ide> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod
<ide> * @see java.lang.annotation.Repeatable
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedEl
<ide> return getRepeatableAnnotations(annotatedElement, annotationType, containerAnnotationType, false);
<ide> }
<ide>
<add> /**
<add> * Get the declared <em>repeatable</em> {@linkplain Annotation annotations}
<add> * of {@code annotationType} from the supplied {@link AnnotatedElement},
<add> * where such annotations are either <em>directly present</em>,
<add> * <em>indirectly present</em>, or <em>meta-present</em> on the element.
<add> * <p>This method mimics the functionality of Java 8's
<add> * {@link java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType(Class)}
<add> * with support for automatic detection of a <em>container annotation</em>
<add> * declared via @{@link java.lang.annotation.Repeatable} (when running on
<add> * Java 8 or higher) and with additional support for meta-annotations.
<add> * <p>Handles both single annotations and annotations nested within a
<add> * <em>container annotation</em>.
<add> * <p>Correctly handles <em>bridge methods</em> generated by the
<add> * compiler if the supplied element is a {@link Method}.
<add> * <p>Meta-annotations will be searched if the annotation is not
<add> * <em>present</em> on the supplied element.
<add> * @param annotatedElement the element to look for annotations on; never {@code null}
<add> * @param annotationType the annotation type to look for; never {@code null}
<add> * @return the annotations found or an empty set; never {@code null}
<add> * @since 4.2
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class)
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod
<add> * @see java.lang.annotation.Repeatable
<add> * @see java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType
<add> */
<add> public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(AnnotatedElement annotatedElement,
<add> Class<A> annotationType) {
<add> return getDeclaredRepeatableAnnotations(annotatedElement, annotationType, null);
<add> }
<add>
<ide> /**
<ide> * Get the declared <em>repeatable</em> {@linkplain Annotation annotations}
<ide> * of {@code annotationType} from the supplied {@link AnnotatedElement},
<ide> public static <A extends Annotation> Set<A> getRepeatableAnnotations(AnnotatedEl
<ide> * @param annotationType the annotation type to look for; never {@code null}
<ide> * @param containerAnnotationType the type of the container that holds
<ide> * the annotations; may be {@code null} if a container is not supported
<add> * or if it should be looked up via @{@link java.lang.annotation.Repeatable}
<add> * when running on Java 8 or higher
<ide> * @return the annotations found or an empty set; never {@code null}
<ide> * @since 4.2
<add> * @see #getRepeatableAnnotations(AnnotatedElement, Class)
<ide> * @see #getRepeatableAnnotations(AnnotatedElement, Class, Class)
<add> * @see #getDeclaredRepeatableAnnotations(AnnotatedElement, Class)
<ide> * @see org.springframework.core.BridgeMethodResolver#findBridgedMethod
<ide> * @see java.lang.annotation.Repeatable
<ide> * @see java.lang.reflect.AnnotatedElement#getDeclaredAnnotationsByType
<ide> public static <A extends Annotation> Set<A> getDeclaredRepeatableAnnotations(Ann
<ide> * @param annotationType the annotation type to look for; never {@code null}
<ide> * @param containerAnnotationType the type of the container that holds
<ide> * the annotations; may be {@code null} if a container is not supported
<add> * or if it should be looked up via @{@link java.lang.annotation.Repeatable}
<add> * when running on Java 8 or higher
<ide> * @param declaredMode {@code true} if only declared annotations (i.e.,
<ide> * directly or indirectly present) should be considered.
<ide> * @return the annotations found or an empty set; never {@code null}
<ide> static List<Method> getAttributeMethods(Class<? extends Annotation> annotationTy
<ide> return methods;
<ide> }
<ide>
<add> /**
<add> * Get the annotation with the supplied {@code annotationName} on the
<add> * supplied {@code element}.
<add> * @param element the element to search on
<add> * @param annotationName the fully qualified class name of the annotation
<add> * type to find; never {@code null} or empty
<add> * @return the annotation if found; {@code null} otherwise
<add> * @since 4.2
<add> */
<add> static Annotation getAnnotation(AnnotatedElement element, String annotationName) {
<add> for (Annotation annotation : element.getAnnotations()) {
<add> if (annotation.annotationType().getName().equals(annotationName)) {
<add> return annotation;
<add> }
<add> }
<add> return null;
<add> }
<add>
<ide> /**
<ide> * Determine if the supplied {@code method} is an annotation attribute method.
<ide> * @param method the method to check
<ide> public int hashCode() {
<ide>
<ide> private static class AnnotationCollector<A extends Annotation> {
<ide>
<add> private static final String REPEATABLE_CLASS_NAME = "java.lang.annotation.Repeatable";
<add>
<add>
<ide> private final Class<A> annotationType;
<ide>
<ide> private final Class<? extends Annotation> containerAnnotationType;
<ide> public int hashCode() {
<ide>
<ide> AnnotationCollector(Class<A> annotationType, Class<? extends Annotation> containerAnnotationType, boolean declaredMode) {
<ide> this.annotationType = annotationType;
<del> this.containerAnnotationType = containerAnnotationType;
<add> this.containerAnnotationType = (containerAnnotationType != null ? containerAnnotationType
<add> : resolveContainerAnnotationType(annotationType));
<ide> this.declaredMode = declaredMode;
<ide> }
<ide>
<add> @SuppressWarnings("unchecked")
<add> static Class<? extends Annotation> resolveContainerAnnotationType(Class<? extends Annotation> annotationType) {
<add> try {
<add> Annotation repeatable = getAnnotation(annotationType, REPEATABLE_CLASS_NAME);
<add> if (repeatable != null) {
<add> Object value = AnnotationUtils.getValue(repeatable);
<add> return (Class<? extends Annotation>) value;
<add> }
<add> }
<add> catch (Exception e) {
<add> handleIntrospectionFailure(annotationType, e);
<add> }
<add> return null;
<add> }
<add>
<ide> Set<A> getResult(AnnotatedElement element) {
<ide> process(element);
<ide> return Collections.unmodifiableSet(this.result);
<ide> else if (!isInJavaLangAnnotationPackage(ann)) {
<ide> @SuppressWarnings("unchecked")
<ide> private List<A> getValue(AnnotatedElement element, Annotation annotation) {
<ide> try {
<del> Method method = annotation.annotationType().getDeclaredMethod("value");
<del> ReflectionUtils.makeAccessible(method);
<del> A[] annotations = (A[]) method.invoke(annotation);
<del>
<ide> List<A> synthesizedAnnotations = new ArrayList<A>();
<del> for (A anno : annotations) {
<add> for (A anno : (A[]) AnnotationUtils.getValue(annotation)) {
<ide> synthesizedAnnotations.add(synthesizeAnnotation(anno, element));
<ide> }
<ide> return synthesizedAnnotations;
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/AnnotationUtilsTests.java
<ide> public void getRepeatableAnnotationsDeclaredOnClassWithMissingAttributeAliasDecl
<ide> public void getRepeatableAnnotationsDeclaredOnClassWithAttributeAliases() throws Exception {
<ide> final List<String> expectedLocations = Arrays.asList("A", "B");
<ide>
<del> Set<ContextConfig> annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, Hierarchy.class);
<add> Set<ContextConfig> annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, null);
<add> assertNotNull(annotations);
<add> assertEquals("size if container type is omitted: ", 0, annotations.size());
<add>
<add> annotations = getRepeatableAnnotations(ConfigHierarchyTestCase.class, ContextConfig.class, Hierarchy.class);
<ide> assertNotNull(annotations);
<ide>
<ide> List<String> locations = annotations.stream().map(ContextConfig::locations).collect(toList());
<ide> public void getRepeatableAnnotationsDeclaredOnClass() {
<ide> assertNotNull(set);
<ide> values = set.stream().map(MyRepeatable::value).collect(toList());
<ide> assertThat(values, is(expectedValuesSpring));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class);
<add> assertNotNull(set);
<add> values = set.stream().map(MyRepeatable::value).collect(toList());
<add> assertThat(values, is(expectedValuesSpring));
<ide> }
<ide>
<ide> @Test
<ide> public void getRepeatableAnnotationsDeclaredOnSuperclass() {
<ide> assertNotNull(set);
<ide> values = set.stream().map(MyRepeatable::value).collect(toList());
<ide> assertThat(values, is(expectedValuesSpring));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getRepeatableAnnotations(clazz, MyRepeatable.class);
<add> assertNotNull(set);
<add> values = set.stream().map(MyRepeatable::value).collect(toList());
<add> assertThat(values, is(expectedValuesSpring));
<ide> }
<ide>
<ide> @Test
<ide> public void getRepeatableAnnotationsDeclaredOnClassAndSuperclass() {
<ide> assertNotNull(set);
<ide> values = set.stream().map(MyRepeatable::value).collect(toList());
<ide> assertThat(values, is(expectedValuesSpring));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getRepeatableAnnotations(clazz, MyRepeatable.class);
<add> assertNotNull(set);
<add> values = set.stream().map(MyRepeatable::value).collect(toList());
<add> assertThat(values, is(expectedValuesSpring));
<ide> }
<ide>
<ide> @Test
<ide> public void getRepeatableAnnotationsDeclaredOnMultipleSuperclasses() {
<ide> assertNotNull(set);
<ide> values = set.stream().map(MyRepeatable::value).collect(toList());
<ide> assertThat(values, is(expectedValuesSpring));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getRepeatableAnnotations(clazz, MyRepeatable.class);
<add> assertNotNull(set);
<add> values = set.stream().map(MyRepeatable::value).collect(toList());
<add> assertThat(values, is(expectedValuesSpring));
<ide> }
<ide>
<ide> @Test
<ide> public void getDeclaredRepeatableAnnotationsDeclaredOnClass() {
<ide> assertNotNull(set);
<ide> values = set.stream().map(MyRepeatable::value).collect(toList());
<ide> assertThat(values, is(expectedValuesSpring));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getDeclaredRepeatableAnnotations(MyRepeatableClass.class, MyRepeatable.class);
<add> assertNotNull(set);
<add> values = set.stream().map(MyRepeatable::value).collect(toList());
<add> assertThat(values, is(expectedValuesSpring));
<ide> }
<ide>
<ide> @Test
<ide> public void getDeclaredRepeatableAnnotationsDeclaredOnSuperclass() {
<ide> Set<MyRepeatable> set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class, MyRepeatableContainer.class);
<ide> assertNotNull(set);
<ide> assertThat(set.size(), is(0));
<add>
<add> // When container type is omitted and therefore inferred from @Repeatable
<add> set = getDeclaredRepeatableAnnotations(clazz, MyRepeatable.class);
<add> assertNotNull(set);
<add> assertThat(set.size(), is(0));
<ide> }
<ide>
<ide> @Test | 3 |
Text | Text | add links to writing specs doc | 3a71b0470b4bcdbeb03289d2fec3401f29994667 | <ide><path>docs/index.md
<ide> * [Creating a Package](creating-a-package.md)
<ide> * [Creating a Theme](creating-a-theme.md)
<ide> * [Publishing a Package](publishing-a-package.md)
<add>* [Writing Specs](writing-specs.md)
<ide> * [Converting a TextMate Bundle](converting-a-text-mate-bundle.md)
<ide> * [Converting a TextMate Theme](converting-a-text-mate-theme.md)
<ide> * [Contributing](contributing.md)
<ide><path>docs/your-first-package.md
<ide> ASCII art professional!
<ide>
<ide> * [Getting your project on GitHub guide](http://guides.github.com/overviews/desktop)
<ide>
<add>* [Writing specs](writing-specs.md) for your package
<add>
<ide> * [Creating a package guide](creating-a-package.html) for more information
<ide> on the mechanics of packages
<ide> | 2 |
Text | Text | add esm code examples in url.md | df744dbb9520076857155acdb95f2de12af6c77a | <ide><path>doc/api/url.md
<ide> The `url` module provides utilities for URL resolution and parsing. It can be
<ide> accessed using:
<ide>
<del>```js
<add>```mjs
<add>import url from 'url';
<add>```
<add>
<add>```cjs
<ide> const url = require('url');
<ide> ```
<ide>
<ide> const myURL =
<ide>
<ide> Parsing the URL string using the Legacy API:
<ide>
<del>```js
<add>```mjs
<add>import url from 'url';
<add>const myURL =
<add> url.parse('https://user:[email protected]:8080/p/a/t/h?query=string#hash');
<add>```
<add>
<add>```cjs
<ide> const url = require('url');
<ide> const myURL =
<ide> url.parse('https://user:[email protected]:8080/p/a/t/h?query=string#hash');
<ide> const myURL = new URL('/foo', 'https://example.org/');
<ide> The URL constructor is accessible as a property on the global object.
<ide> It can also be imported from the built-in url module:
<ide>
<del>```js
<add>```mjs
<add>import { URL } from 'url';
<add>console.log(URL === globalThis.URL); // Prints 'true'.
<add>```
<add>
<add>```cjs
<ide> console.log(URL === require('url').URL); // Prints 'true'.
<ide> ```
<ide>
<ide> and [`url.format()`][] methods would produce.
<ide> The `toString()` method on the `URL` object returns the serialized URL. The
<ide> value returned is equivalent to that of [`url.href`][] and [`url.toJSON()`][].
<ide>
<del>Because of the need for standard compliance, this method does not allow users
<del>to customize the serialization process of the URL. For more flexibility,
<del>[`require('url').format()`][] method might be of interest.
<del>
<ide> #### `url.toJSON()`
<ide>
<ide> * Returns: {string}
<ide> invalid domain, the empty string is returned.
<ide>
<ide> It performs the inverse operation to [`url.domainToUnicode()`][].
<ide>
<del>```js
<add>```mjs
<add>import url from 'url';
<add>
<add>console.log(url.domainToASCII('español.com'));
<add>// Prints xn--espaol-zwa.com
<add>console.log(url.domainToASCII('中文.com'));
<add>// Prints xn--fiq228c.com
<add>console.log(url.domainToASCII('xn--iñvalid.com'));
<add>// Prints an empty string
<add>```
<add>
<add>```cjs
<ide> const url = require('url');
<add>
<ide> console.log(url.domainToASCII('español.com'));
<ide> // Prints xn--espaol-zwa.com
<ide> console.log(url.domainToASCII('中文.com'));
<ide> domain, the empty string is returned.
<ide>
<ide> It performs the inverse operation to [`url.domainToASCII()`][].
<ide>
<del>```js
<add>```mjs
<add>import url from 'url';
<add>
<add>console.log(url.domainToUnicode('xn--espaol-zwa.com'));
<add>// Prints español.com
<add>console.log(url.domainToUnicode('xn--fiq228c.com'));
<add>// Prints 中文.com
<add>console.log(url.domainToUnicode('xn--iñvalid.com'));
<add>// Prints an empty string
<add>```
<add>
<add>```cjs
<ide> const url = require('url');
<add>
<ide> console.log(url.domainToUnicode('xn--espaol-zwa.com'));
<ide> // Prints español.com
<ide> console.log(url.domainToUnicode('xn--fiq228c.com'));
<ide> added: v15.7.0
<ide> This utility function converts a URL object into an ordinary options object as
<ide> expected by the [`http.request()`][] and [`https.request()`][] APIs.
<ide>
<del>```js
<add>```mjs
<add>import { urlToHttpOptions } from 'url';
<add>const myURL = new URL('https://a:b@測試?abc#foo');
<add>
<add>console.log(urlToHttpOptions(myUrl));
<add>/**
<add>{
<add> protocol: 'https:',
<add> hostname: 'xn--g6w251d',
<add> hash: '#foo',
<add> search: '?abc',
<add> pathname: '/',
<add> path: '/?abc',
<add> href: 'https://a:b@xn--g6w251d/?abc#foo',
<add> auth: 'a:b'
<add>}
<add>*/
<add>```
<add>
<add>```cjs
<ide> const { urlToHttpOptions } = require('url');
<ide> const myURL = new URL('https://a:b@測試?abc#foo');
<ide>
<ide> changes:
<ide>
<ide> > Stability: 3 - Legacy: Use the WHATWG URL API instead.
<ide>
<del>The legacy `urlObject` (`require('url').Url`) is created and returned by the
<del>`url.parse()` function.
<add>The legacy `urlObject` (`require('url').Url` or `import { Url } from 'url'`) is
<add>created and returned by the `url.parse()` function.
<ide>
<ide> #### `urlObject.auth`
<ide>
<ide> console.log(myURL.origin);
<ide> [`https.request()`]: https.md#https_https_request_options_callback
<ide> [`new URL()`]: #url_new_url_input_base
<ide> [`querystring`]: querystring.md
<del>[`require('url').format()`]: #url_url_format_url_options
<ide> [`url.domainToASCII()`]: #url_url_domaintoascii_domain
<ide> [`url.domainToUnicode()`]: #url_url_domaintounicode_domain
<ide> [`url.format()`]: #url_url_format_urlobject | 1 |
PHP | PHP | use fewer lines to assign post/query params | d8f0b8ccbd11ff64cbc5729955a4086a4a98cf49 | <ide><path>src/Routing/RequestActionTrait.php
<ide> public function requestAction($url, array $extra = array()) {
<ide> ['autoRender' => 0, 'return' => 1, 'bare' => 1, 'requested' => 1],
<ide> $extra
<ide> );
<del> $post = $query = [];
<del> if (isset($extra['post'])) {
<del> $post = $extra['post'];
<del> }
<del> if (isset($extra['query'])) {
<del> $query = $extra['query'];
<del> }
<del> unset($extra['post'], $extra['query']);
<ide>
<ide> $baseUrl = Configure::read('App.fullBaseUrl');
<ide> if (is_string($url) && strpos($url, $baseUrl) === 0) {
<ide> public function requestAction($url, array $extra = array()) {
<ide> }
<ide> }
<ide>
<del> if (!empty($post)) {
<del> $params['post'] = $post;
<add> $params['post'] = $params['query'] = [];
<add> if (isset($extra['post'])) {
<add> $params['post'] = $extra['post'];
<ide> }
<del>
<del> if (!empty($query)) {
<del> $params['query'] = $query;
<add> if (isset($extra['query'])) {
<add> $params['query'] = $extra['query'];
<ide> }
<add> unset($extra['post'], $extra['query']);
<ide>
<ide> $params['session'] = isset($extra['session']) ? $extra['session'] : new Session();
<ide> | 1 |
Python | Python | remove dev log message | 7d09e4e1793e83b6f99a1ca8ef7d2b89c8724a1f | <ide><path>glances/outputs/glances_curses.py
<ide> def display(self, stats, cs_status=None):
<ide> if not self.args.disable_quicklook:
<ide> # Quick look is in the place !
<ide> quicklook_width = screen_x - (stats_width + 8 + stats_number * self.space_between_column)
<del> logger.info("Quicklook plugin size: %s" % quicklook_width)
<ide> try:
<ide> stats_quicklook = stats.get_plugin(
<ide> 'quicklook').get_stats_display(max_width=quicklook_width, args=self.args) | 1 |
Javascript | Javascript | use static number properties from primordials | 1f9a5ae7aadd073ac61933226687a4483f8eccf4 | <ide><path>lib/_http_client.js
<ide> const {
<ide> ArrayIsArray,
<ide> Boolean,
<add> NumberIsFinite,
<ide> ObjectAssign,
<ide> ObjectKeys,
<ide> ObjectSetPrototypeOf,
<ide> function ClientRequest(input, options, cb) {
<ide> // but only if the Agent will actually reuse the connection!
<ide> // If it's not a keepAlive agent, and the maxSockets==Infinity, then
<ide> // there's never a case where this socket will actually be reused
<del> if (!this.agent.keepAlive && !Number.isFinite(this.agent.maxSockets)) {
<add> if (!this.agent.keepAlive && !NumberIsFinite(this.agent.maxSockets)) {
<ide> this._last = true;
<ide> this.shouldKeepAlive = false;
<ide> } else {
<ide><path>lib/_stream_readable.js
<ide>
<ide> const {
<ide> ArrayIsArray,
<add> NumberIsInteger,
<add> NumberIsNaN,
<ide> ObjectDefineProperty,
<ide> ObjectSetPrototypeOf,
<ide> } = primordials;
<ide> function howMuchToRead(n, state) {
<ide> return 0;
<ide> if (state.objectMode)
<ide> return 1;
<del> if (Number.isNaN(n)) {
<add> if (NumberIsNaN(n)) {
<ide> // Only flow one buffer at a time
<ide> if (state.flowing && state.length)
<ide> return state.buffer.first().length;
<ide> Readable.prototype.read = function(n) {
<ide> // in this scenario, so we are doing it manually.
<ide> if (n === undefined) {
<ide> n = NaN;
<del> } else if (!Number.isInteger(n)) {
<add> } else if (!NumberIsInteger(n)) {
<ide> n = parseInt(n, 10);
<ide> }
<ide> const state = this._readableState;
<ide><path>lib/async_hooks.js
<ide> 'use strict';
<ide>
<ide> const {
<add> NumberIsSafeInteger,
<ide> ReflectApply,
<ide> } = primordials;
<ide>
<ide> class AsyncResource {
<ide>
<ide> // Unlike emitInitScript, AsyncResource doesn't supports null as the
<ide> // triggerAsyncId.
<del> if (!Number.isSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
<add> if (!NumberIsSafeInteger(triggerAsyncId) || triggerAsyncId < -1) {
<ide> throw new ERR_INVALID_ASYNC_ID('triggerAsyncId', triggerAsyncId);
<ide> }
<ide>
<ide><path>lib/buffer.js
<ide> const {
<ide> MathFloor,
<ide> MathMin,
<ide> MathTrunc,
<add> NumberIsNaN,
<add> NumberMAX_SAFE_INTEGER,
<add> NumberMIN_SAFE_INTEGER,
<ide> ObjectCreate,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> function showFlaggedDeprecation() {
<ide>
<ide> function toInteger(n, defaultVal) {
<ide> n = +n;
<del> if (!Number.isNaN(n) &&
<del> n >= Number.MIN_SAFE_INTEGER &&
<del> n <= Number.MAX_SAFE_INTEGER) {
<add> if (!NumberIsNaN(n) &&
<add> n >= NumberMIN_SAFE_INTEGER &&
<add> n <= NumberMAX_SAFE_INTEGER) {
<ide> return ((n % 1) === 0 ? n : MathFloor(n));
<ide> }
<ide> return defaultVal;
<ide> function fromArrayBuffer(obj, byteOffset, length) {
<ide> byteOffset = 0;
<ide> } else {
<ide> byteOffset = +byteOffset;
<del> if (Number.isNaN(byteOffset))
<add> if (NumberIsNaN(byteOffset))
<ide> byteOffset = 0;
<ide> }
<ide>
<ide> function bidirectionalIndexOf(buffer, val, byteOffset, encoding, dir) {
<ide> // Coerce to Number. Values like null and [] become 0.
<ide> byteOffset = +byteOffset;
<ide> // If the offset is undefined, "foo", {}, coerces to NaN, search whole buffer.
<del> if (Number.isNaN(byteOffset)) {
<add> if (NumberIsNaN(byteOffset)) {
<ide> byteOffset = dir ? 0 : buffer.length;
<ide> }
<ide> dir = !!dir; // Cast to bool.
<ide> function adjustOffset(offset, length) {
<ide> if (offset < length) {
<ide> return offset;
<ide> }
<del> return Number.isNaN(offset) ? 0 : length;
<add> return NumberIsNaN(offset) ? 0 : length;
<ide> }
<ide>
<ide> Buffer.prototype.slice = function slice(start, end) {
<ide><path>lib/child_process.js
<ide>
<ide> const {
<ide> ArrayIsArray,
<add> NumberIsInteger,
<ide> ObjectAssign,
<ide> ObjectDefineProperty,
<ide> ObjectPrototypeHasOwnProperty,
<ide> function execSync(command, options) {
<ide>
<ide>
<ide> function validateTimeout(timeout) {
<del> if (timeout != null && !(Number.isInteger(timeout) && timeout >= 0)) {
<add> if (timeout != null && !(NumberIsInteger(timeout) && timeout >= 0)) {
<ide> throw new ERR_OUT_OF_RANGE('timeout', 'an unsigned integer', timeout);
<ide> }
<ide> }
<ide><path>lib/events.js
<ide> const {
<ide> Array,
<ide> MathMin,
<add> NumberIsNaN,
<ide> ObjectCreate,
<ide> ObjectDefineProperty,
<ide> ObjectGetPrototypeOf,
<ide> ObjectDefineProperty(EventEmitter, 'defaultMaxListeners', {
<ide> return defaultMaxListeners;
<ide> },
<ide> set: function(arg) {
<del> if (typeof arg !== 'number' || arg < 0 || Number.isNaN(arg)) {
<add> if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) {
<ide> throw new ERR_OUT_OF_RANGE('defaultMaxListeners',
<ide> 'a non-negative number',
<ide> arg);
<ide> EventEmitter.init = function() {
<ide> // Obviously not all Emitters should be limited to 10. This function allows
<ide> // that to be increased. Set to zero for unlimited.
<ide> EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
<del> if (typeof n !== 'number' || n < 0 || Number.isNaN(n)) {
<add> if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) {
<ide> throw new ERR_OUT_OF_RANGE('n', 'a non-negative number', n);
<ide> }
<ide> this._maxListeners = n;
<ide><path>lib/fs.js
<ide>
<ide> const {
<ide> MathMax,
<add> NumberIsSafeInteger,
<ide> ObjectCreate,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> function read(fd, buffer, offset, length, position, callback) {
<ide>
<ide> validateOffsetLengthRead(offset, length, buffer.byteLength);
<ide>
<del> if (!Number.isSafeInteger(position))
<add> if (!NumberIsSafeInteger(position))
<ide> position = -1;
<ide>
<ide> function wrapper(err, bytesRead) {
<ide> function readSync(fd, buffer, offset, length, position) {
<ide>
<ide> validateOffsetLengthRead(offset, length, buffer.byteLength);
<ide>
<del> if (!Number.isSafeInteger(position))
<add> if (!NumberIsSafeInteger(position))
<ide> position = -1;
<ide>
<ide> const ctx = {};
<ide><path>lib/internal/async_hooks.js
<ide>
<ide> const {
<ide> FunctionPrototypeBind,
<add> NumberIsSafeInteger,
<ide> ObjectDefineProperty,
<ide> } = primordials;
<ide>
<ide> function validateAsyncId(asyncId, type) {
<ide> // Skip validation when async_hooks is disabled
<ide> if (async_hook_fields[kCheck] <= 0) return;
<ide>
<del> if (!Number.isSafeInteger(asyncId) || asyncId < -1) {
<add> if (!NumberIsSafeInteger(asyncId) || asyncId < -1) {
<ide> fatalError(new ERR_INVALID_ASYNC_ID(type, asyncId));
<ide> }
<ide> }
<ide> function clearDefaultTriggerAsyncId() {
<ide> function defaultTriggerAsyncIdScope(triggerAsyncId, block, ...args) {
<ide> if (triggerAsyncId === undefined)
<ide> return block(...args);
<del> // CHECK(Number.isSafeInteger(triggerAsyncId))
<add> // CHECK(NumberIsSafeInteger(triggerAsyncId))
<ide> // CHECK(triggerAsyncId > 0)
<ide> const oldDefaultTriggerAsyncId = async_id_fields[kDefaultTriggerAsyncId];
<ide> async_id_fields[kDefaultTriggerAsyncId] = triggerAsyncId;
<ide><path>lib/internal/crypto/random.js
<ide>
<ide> const {
<ide> MathMin,
<add> NumberIsNaN,
<ide> } = primordials;
<ide>
<ide> const { AsyncWrap, Providers } = internalBinding('async_wrap');
<ide> function assertOffset(offset, elementSize, length) {
<ide> offset *= elementSize;
<ide>
<ide> const maxLength = MathMin(length, kMaxPossibleLength);
<del> if (Number.isNaN(offset) || offset > maxLength || offset < 0) {
<add> if (NumberIsNaN(offset) || offset > maxLength || offset < 0) {
<ide> throw new ERR_OUT_OF_RANGE('offset', `>= 0 && <= ${maxLength}`, offset);
<ide> }
<ide>
<ide> function assertSize(size, elementSize, offset, length) {
<ide> validateNumber(size, 'size');
<ide> size *= elementSize;
<ide>
<del> if (Number.isNaN(size) || size > kMaxPossibleLength || size < 0) {
<add> if (NumberIsNaN(size) || size > kMaxPossibleLength || size < 0) {
<ide> throw new ERR_OUT_OF_RANGE('size',
<ide> `>= 0 && <= ${kMaxPossibleLength}`, size);
<ide> }
<ide><path>lib/internal/errors.js
<ide> const {
<ide> ArrayIsArray,
<ide> MathAbs,
<add> NumberIsInteger,
<ide> ObjectDefineProperty,
<ide> ObjectKeys,
<ide> } = primordials;
<ide> E('ERR_OUT_OF_RANGE',
<ide> let msg = replaceDefaultBoolean ? str :
<ide> `The value of "${str}" is out of range.`;
<ide> let received;
<del> if (Number.isInteger(input) && MathAbs(input) > 2 ** 32) {
<add> if (NumberIsInteger(input) && MathAbs(input) > 2 ** 32) {
<ide> received = addNumericalSeparator(String(input));
<ide> } else if (typeof input === 'bigint') {
<ide> received = String(input);
<ide><path>lib/internal/fs/promises.js
<ide> const {
<ide> MathMax,
<ide> MathMin,
<add> NumberIsSafeInteger,
<ide> } = primordials;
<ide>
<ide> const {
<ide> async function read(handle, buffer, offset, length, position) {
<ide>
<ide> validateOffsetLengthRead(offset, length, buffer.length);
<ide>
<del> if (!Number.isSafeInteger(position))
<add> if (!NumberIsSafeInteger(position))
<ide> position = -1;
<ide>
<ide> const bytesRead = (await binding.read(handle.fd, buffer, offset, length,
<ide><path>lib/internal/fs/streams.js
<ide> const {
<ide> Array,
<ide> MathMin,
<add> NumberIsInteger,
<add> NumberIsSafeInteger,
<ide> ObjectDefineProperty,
<ide> ObjectSetPrototypeOf,
<ide> } = primordials;
<ide> function allocNewPool(poolSize) {
<ide>
<ide> // Check the `this.start` and `this.end` of stream.
<ide> function checkPosition(pos, name) {
<del> if (!Number.isSafeInteger(pos)) {
<add> if (!NumberIsSafeInteger(pos)) {
<ide> validateNumber(pos, name);
<del> if (!Number.isInteger(pos))
<add> if (!NumberIsInteger(pos))
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', pos);
<ide> throw new ERR_OUT_OF_RANGE(name, '>= 0 and <= 2 ** 53 - 1', pos);
<ide> }
<ide><path>lib/internal/fs/utils.js
<ide> const {
<ide> ArrayIsArray,
<ide> DateNow,
<add> NumberIsFinite,
<ide> ObjectSetPrototypeOf,
<ide> ReflectOwnKeys,
<ide> } = primordials;
<ide> function toUnixTimestamp(time, name = 'time') {
<ide> if (typeof time === 'string' && +time == time) {
<ide> return +time;
<ide> }
<del> if (Number.isFinite(time)) {
<add> if (NumberIsFinite(time)) {
<ide> if (time < 0) {
<ide> return DateNow() / 1000;
<ide> }
<ide><path>lib/internal/process/per_thread.js
<ide>
<ide> const {
<ide> ArrayIsArray,
<add> NumberMAX_SAFE_INTEGER,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> ObjectFreeze,
<ide> function wrapProcessMethods(binding) {
<ide> // implementation always returns numbers <= Number.MAX_SAFE_INTEGER.
<ide> function previousValueIsValid(num) {
<ide> return typeof num === 'number' &&
<del> num <= Number.MAX_SAFE_INTEGER &&
<add> num <= NumberMAX_SAFE_INTEGER &&
<ide> num >= 0;
<ide> }
<ide>
<ide><path>lib/internal/readline/utils.js
<ide>
<ide> const {
<ide> Boolean,
<add> NumberIsInteger,
<ide> } = primordials;
<ide>
<ide> // Regex used for ansi escape code splitting
<ide> if (internalBinding('config').hasIntl) {
<ide> const icu = internalBinding('icu');
<ide> getStringWidth = function getStringWidth(str, options) {
<ide> options = options || {};
<del> if (Number.isInteger(str)) {
<add> if (NumberIsInteger(str)) {
<ide> // Provide information about the character with code point 'str'.
<ide> return icu.getStringWidth(
<ide> str,
<ide> if (internalBinding('config').hasIntl) {
<ide> * Returns the number of columns required to display the given string.
<ide> */
<ide> getStringWidth = function getStringWidth(str) {
<del> if (Number.isInteger(str))
<add> if (NumberIsInteger(str))
<ide> return isFullWidthCodePoint(str) ? 2 : 1;
<ide>
<ide> let width = 0;
<ide> if (internalBinding('config').hasIntl) {
<ide> isFullWidthCodePoint = function isFullWidthCodePoint(code) {
<ide> // Code points are derived from:
<ide> // http://www.unicode.org/Public/UNIDATA/EastAsianWidth.txt
<del> return Number.isInteger(code) && code >= 0x1100 && (
<add> return NumberIsInteger(code) && code >= 0x1100 && (
<ide> code <= 0x115f || // Hangul Jamo
<ide> code === 0x2329 || // LEFT-POINTING ANGLE BRACKET
<ide> code === 0x232a || // RIGHT-POINTING ANGLE BRACKET
<ide><path>lib/internal/repl.js
<ide> 'use strict';
<ide>
<ide> const {
<add> NumberIsNaN,
<ide> ObjectCreate,
<ide> } = primordials;
<ide>
<ide> function createRepl(env, opts, cb) {
<ide> }
<ide>
<ide> const historySize = Number(env.NODE_REPL_HISTORY_SIZE);
<del> if (!Number.isNaN(historySize) && historySize > 0) {
<add> if (!NumberIsNaN(historySize) && historySize > 0) {
<ide> opts.historySize = historySize;
<ide> } else {
<ide> opts.historySize = 1000;
<ide><path>lib/internal/streams/state.js
<ide>
<ide> const {
<ide> MathFloor,
<add> NumberIsInteger,
<ide> } = primordials;
<ide>
<ide> const { ERR_INVALID_OPT_VALUE } = require('internal/errors').codes;
<ide> function getDefaultHighWaterMark(objectMode) {
<ide> function getHighWaterMark(state, options, duplexKey, isDuplex) {
<ide> const hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
<ide> if (hwm != null) {
<del> if (!Number.isInteger(hwm) || hwm < 0) {
<add> if (!NumberIsInteger(hwm) || hwm < 0) {
<ide> const name = isDuplex ? duplexKey : 'highWaterMark';
<ide> throw new ERR_INVALID_OPT_VALUE(name, hwm);
<ide> }
<ide><path>lib/internal/timers.js
<ide> const {
<ide> MathMax,
<ide> MathTrunc,
<add> NumberMIN_SAFE_INTEGER,
<ide> ObjectCreate,
<ide> } = primordials;
<ide>
<ide> const kHasOutstanding = 2;
<ide> // Timeout values > TIMEOUT_MAX are set to 1.
<ide> const TIMEOUT_MAX = 2 ** 31 - 1;
<ide>
<del>let timerListId = Number.MIN_SAFE_INTEGER;
<add>let timerListId = NumberMIN_SAFE_INTEGER;
<ide>
<ide> const kRefed = Symbol('refed');
<ide>
<ide><path>lib/internal/util/inspect.js
<ide> const {
<ide> MathMin,
<ide> MathRound,
<ide> MathSqrt,
<add> NumberIsNaN,
<ide> NumberPrototypeValueOf,
<ide> ObjectAssign,
<ide> ObjectCreate,
<ide> function formatRaw(ctx, value, recurseTimes, typedArray) {
<ide> return ctx.stylize(base, 'regexp');
<ide> } else if (isDate(value)) {
<ide> // Make dates with properties first say the date
<del> base = Number.isNaN(DatePrototypeGetTime(value)) ?
<add> base = NumberIsNaN(DatePrototypeGetTime(value)) ?
<ide> DatePrototypeToString(value) :
<ide> DatePrototypeToISOString(value);
<ide> const prefix = getPrefix(constructor, tag, 'Date');
<ide><path>lib/internal/validators.js
<ide> 'use strict';
<ide>
<add>const {
<add> NumberIsInteger,
<add> NumberMAX_SAFE_INTEGER,
<add> NumberMIN_SAFE_INTEGER,
<add>} = primordials;
<add>
<ide> const {
<ide> hideStackFrames,
<ide> codes: {
<ide> const {
<ide> isArrayBufferView
<ide> } = require('internal/util/types');
<ide> const { signals } = internalBinding('constants').os;
<del>const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number;
<ide>
<ide> function isInt32(value) {
<ide> return value === (value | 0);
<ide> function parseMode(value, name, def) {
<ide> }
<ide>
<ide> const validateInteger = hideStackFrames(
<del> (value, name, min = MIN_SAFE_INTEGER, max = MAX_SAFE_INTEGER) => {
<add> (value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => {
<ide> if (typeof value !== 'number')
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<del> if (!Number.isInteger(value))
<add> if (!NumberIsInteger(value))
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<ide> if (value < min || value > max)
<ide> throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
<ide> const validateInt32 = hideStackFrames(
<ide> if (typeof value !== 'number') {
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<ide> }
<del> if (!Number.isInteger(value)) {
<add> if (!NumberIsInteger(value)) {
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<ide> }
<ide> throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value);
<ide> const validateUint32 = hideStackFrames((value, name, positive) => {
<ide> if (typeof value !== 'number') {
<ide> throw new ERR_INVALID_ARG_TYPE(name, 'number', value);
<ide> }
<del> if (!Number.isInteger(value)) {
<add> if (!NumberIsInteger(value)) {
<ide> throw new ERR_OUT_OF_RANGE(name, 'an integer', value);
<ide> }
<ide> const min = positive ? 1 : 0;
<ide><path>lib/net.js
<ide> const {
<ide> ArrayIsArray,
<ide> Boolean,
<add> NumberIsNaN,
<ide> ObjectDefineProperty,
<ide> ObjectSetPrototypeOf,
<ide> } = primordials;
<ide> function createServerHandle(address, port, addressType, fd, flags) {
<ide> handle = new Pipe(PipeConstants.SERVER);
<ide> if (process.platform === 'win32') {
<ide> const instances = parseInt(process.env.NODE_PENDING_PIPE_INSTANCES);
<del> if (!Number.isNaN(instances)) {
<add> if (!NumberIsNaN(instances)) {
<ide> handle.setPendingInstances(instances);
<ide> }
<ide> }
<ide><path>lib/perf_hooks.js
<ide> const {
<ide> ArrayIsArray,
<ide> Boolean,
<add> NumberIsSafeInteger,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> ObjectKeys,
<ide> function monitorEventLoopDelay(options = {}) {
<ide> throw new ERR_INVALID_ARG_TYPE('options.resolution',
<ide> 'number', resolution);
<ide> }
<del> if (resolution <= 0 || !Number.isSafeInteger(resolution)) {
<add> if (resolution <= 0 || !NumberIsSafeInteger(resolution)) {
<ide> throw new ERR_INVALID_OPT_VALUE.RangeError('resolution', resolution);
<ide> }
<ide> return new ELDHistogram(new _ELDHistogram(resolution));
<ide><path>lib/readline.js
<ide> const {
<ide> MathCeil,
<ide> MathFloor,
<ide> MathMax,
<add> NumberIsFinite,
<add> NumberIsNaN,
<ide> ObjectDefineProperty,
<ide> ObjectSetPrototypeOf,
<ide> } = primordials;
<ide> function Interface(input, output, completer, terminal) {
<ide> prompt = input.prompt;
<ide> }
<ide> if (input.escapeCodeTimeout !== undefined) {
<del> if (Number.isFinite(input.escapeCodeTimeout)) {
<add> if (NumberIsFinite(input.escapeCodeTimeout)) {
<ide> this.escapeCodeTimeout = input.escapeCodeTimeout;
<ide> } else {
<ide> throw new ERR_INVALID_OPT_VALUE(
<ide> function Interface(input, output, completer, terminal) {
<ide> }
<ide>
<ide> if (typeof historySize !== 'number' ||
<del> Number.isNaN(historySize) ||
<add> NumberIsNaN(historySize) ||
<ide> historySize < 0) {
<ide> throw new ERR_INVALID_OPT_VALUE.RangeError('historySize', historySize);
<ide> }
<ide><path>lib/repl.js
<ide> const {
<ide> ArrayIsArray,
<ide> MathMax,
<add> NumberIsNaN,
<ide> ObjectAssign,
<ide> ObjectCreate,
<ide> ObjectDefineProperty,
<ide> function REPLServer(prompt,
<ide> // display next prompt and return.
<ide> if (trimmedCmd) {
<ide> if (trimmedCmd.charAt(0) === '.' && trimmedCmd.charAt(1) !== '.' &&
<del> Number.isNaN(parseFloat(trimmedCmd))) {
<add> NumberIsNaN(parseFloat(trimmedCmd))) {
<ide> const matches = trimmedCmd.match(/^\.([^\s]+)\s*(.*)$/);
<ide> const keyword = matches && matches[1];
<ide> const rest = matches && matches[2];
<ide><path>lib/tty.js
<ide>
<ide> const {
<ide> Array,
<add> NumberIsInteger,
<ide> ObjectSetPrototypeOf,
<ide> } = primordials;
<ide>
<ide> const {
<ide> let readline;
<ide>
<ide> function isatty(fd) {
<del> return Number.isInteger(fd) && fd >= 0 && isTTY(fd);
<add> return NumberIsInteger(fd) && fd >= 0 && isTTY(fd);
<ide> }
<ide>
<ide> function ReadStream(fd, options) {
<ide><path>lib/util.js
<ide>
<ide> const {
<ide> ArrayIsArray,
<add> NumberIsSafeInteger,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> ObjectGetOwnPropertyDescriptors,
<ide> function callbackify(original) {
<ide>
<ide> function getSystemErrorName(err) {
<ide> validateNumber(err, 'err');
<del> if (err >= 0 || !Number.isSafeInteger(err)) {
<add> if (err >= 0 || !NumberIsSafeInteger(err)) {
<ide> throw new ERR_OUT_OF_RANGE('err', 'a negative integer', err);
<ide> }
<ide> return internalErrorName(err);
<ide><path>lib/zlib.js
<ide>
<ide> const {
<ide> MathMax,
<add> NumberIsFinite,
<add> NumberIsNaN,
<ide> ObjectDefineProperties,
<ide> ObjectDefineProperty,
<ide> ObjectFreeze,
<ide> const checkFiniteNumber = hideStackFrames((number, name) => {
<ide> return false;
<ide> }
<ide>
<del> if (Number.isFinite(number)) {
<add> if (NumberIsFinite(number)) {
<ide> return true; // Is a valid number
<ide> }
<ide>
<del> if (Number.isNaN(number)) {
<add> if (NumberIsNaN(number)) {
<ide> return false;
<ide> }
<ide>
<ide> function Brotli(opts, mode) {
<ide> if (opts && opts.params) {
<ide> for (const origKey of ObjectKeys(opts.params)) {
<ide> const key = +origKey;
<del> if (Number.isNaN(key) || key < 0 || key > kMaxBrotliParam ||
<add> if (NumberIsNaN(key) || key < 0 || key > kMaxBrotliParam ||
<ide> (brotliInitParamsArray[key] | 0) !== -1) {
<ide> throw new ERR_BROTLI_INVALID_PARAM(origKey);
<ide> } | 27 |
Python | Python | add regression test for the message options bug | 773a389f2ae69384f09cbada8b4b2615a7c430de | <ide><path>celery/tests/test_messaging.py
<add>import unittest
<add>from celery.messaging import MSG_OPTIONS, get_msg_options, extract_msg_options
<add>
<add>
<add>class TestMsgOptions(unittest.TestCase):
<add>
<add> def test_MSG_OPTIONS(self):
<add> self.assertTrue(MSG_OPTIONS)
<add>
<add> def test_extract_msg_options(self):
<add> testing = {"mandatory": True, "routing_key": "foo.xuzzy"}
<add> result = extract_msg_options(testing)
<add> self.assertEquals(result["mandatory"], True)
<add> self.assertEquals(result["routing_key"], "foo.xuzzy")
<add>
<add> | 1 |
Text | Text | fix dead links in packages.md | bf9ce95db77ab1e330a97530fd3d8f21dea50d3d | <ide><path>doc/api/packages.md
<ide> Any number of custom conditions can be set with repeat flags.
<ide>
<ide> The `"import"`, `"require"`, `"node"` and `"default"` conditions are defined
<ide> and implemented in Node.js core,
<del>[as specified above](#esm_conditional_exports).
<add>[as specified above](#packages_conditional_exports).
<ide>
<ide> Other condition strings are unknown to Node.js and thus ignored by default.
<ide> Runtimes or tools other than Node.js can use them at their discretion.
<ide> The preceding example uses explicit extensions `.mjs` and `.cjs`.
<ide> If your files use the `.js` extension, `"type": "module"` will cause such files
<ide> to be treated as ES modules, just as `"type": "commonjs"` would cause them
<ide> to be treated as CommonJS.
<del>See [Enabling](#esm_enabling).
<add>See [Enabling](esm.md#esm_enabling).
<ide>
<ide> ```cjs
<ide> // ./node_modules/pkg/index.cjs | 1 |
Text | Text | fix documentation for has_many dependant options | 391043ab04007bfd4c4c4c8e8d3308c1eae60175 | <ide><path>guides/source/association_basics.md
<ide> If you set the `:dependent` option to:
<ide>
<ide> * `:destroy`, when the object is destroyed, `destroy` will be called on its
<ide> associated objects.
<del>* `:delete`, when the object is destroyed, all its associated objects will be
<add>* `:delete_all`, when the object is destroyed, all its associated objects will be
<ide> deleted directly from the database without calling their `destroy` method.
<add>* `:nullify`, causes the foreign key to be set to `NULL`. Callbacks are not executed.
<add>* `:restrict_with_exception`, causes an exception to be raised if there is an associated record
<add>* `:restrict_with_error`, causes an error to be added to the owner if there is an associated object
<ide>
<ide> WARNING: You should not specify this option on a `belongs_to` association that is connected with a `has_many` association on the other class. Doing so can lead to orphaned records in your database.
<ide> | 1 |
Python | Python | remove unused stdlib imports | e07b0fce7844a227fa05e4f20772ec9cc5bf9912 | <ide><path>numpy/conftest.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>import warnings
<ide> import pytest
<ide> import numpy
<del>import importlib
<ide>
<ide> from numpy.core._multiarray_tests import get_fpu_mode
<ide>
<ide><path>numpy/core/setup.py
<ide> import sys
<ide> import pickle
<ide> import copy
<del>import sysconfig
<ide> import warnings
<ide> import platform
<ide> from os.path import join
<ide><path>numpy/ctypeslib.py
<ide> __all__ = ['load_library', 'ndpointer', 'test', 'ctypes_load_library',
<ide> 'c_intp', 'as_ctypes', 'as_array']
<ide>
<del>import sys, os
<add>import os
<ide> from numpy import integer, ndarray, dtype as _dtype, deprecate, array
<ide> from numpy.core.multiarray import _flagdict, flagsobj
<ide>
<ide><path>numpy/distutils/command/build_ext.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import os
<del>import sys
<del>import shutil
<ide> import subprocess
<ide> from glob import glob
<ide>
<ide><path>numpy/distutils/fcompiler/gnu.py
<ide> import base64
<ide> import subprocess
<ide> from subprocess import Popen, PIPE, STDOUT
<del>from copy import copy
<ide> from numpy.distutils.exec_command import filepath_from_subprocess_output
<ide> from numpy.distutils.fcompiler import FCompiler
<ide> from numpy.distutils.compat import get_exception
<ide><path>numpy/distutils/fcompiler/pg.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<ide> import sys
<del>import os
<ide>
<ide> from numpy.distutils.fcompiler import FCompiler, dummy_fortran_file
<ide> from sys import platform
<ide> def runtime_library_dir_option(self, dir):
<ide>
<ide>
<ide> if sys.version_info >= (3, 5):
<del> import subprocess
<del> import shlex
<ide> import functools
<ide>
<ide> class PGroupFlangCompiler(FCompiler):
<ide><path>numpy/distutils/lib2def.py
<ide>
<ide> import re
<ide> import sys
<del>import os
<ide> import subprocess
<ide>
<ide> __doc__ = """This module generates a DEF file from the symbols in
<ide><path>numpy/distutils/npy_pkg_config.py
<ide> import os
<ide>
<ide> if sys.version_info[0] < 3:
<del> from ConfigParser import RawConfigParser, NoOptionError
<add> from ConfigParser import RawConfigParser
<ide> else:
<del> from configparser import RawConfigParser, NoOptionError
<add> from configparser import RawConfigParser
<ide>
<ide> __all__ = ['FormatError', 'PkgNotFound', 'LibraryInfo', 'VariableSet',
<ide> 'read_config', 'parse_flags']
<ide><path>numpy/distutils/system_info.py
<ide> import re
<ide> import copy
<ide> import warnings
<del>import atexit
<ide> from glob import glob
<ide> from functools import reduce
<ide> if sys.version_info[0] < 3:
<ide><path>numpy/f2py/setup.py
<ide> """
<ide> from __future__ import division, print_function
<ide>
<del>import os
<del>import sys
<del>from distutils.dep_util import newer
<del>from numpy.distutils import log
<ide> from numpy.distutils.core import setup
<ide> from numpy.distutils.misc_util import Configuration
<ide>
<ide><path>numpy/lib/npyio.py
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>import io
<ide> import sys
<ide> import os
<ide> import re
<ide><path>numpy/matrixlib/setup.py
<ide> #!/usr/bin/env python
<ide> from __future__ import division, print_function
<ide>
<del>import os
<del>
<ide> def configuration(parent_package='', top_path=None):
<ide> from numpy.distutils.misc_util import Configuration
<ide> config = Configuration('matrixlib', parent_package, top_path)
<ide><path>numpy/polynomial/chebyshev.py
<ide> """
<ide> from __future__ import division, absolute_import, print_function
<ide>
<del>import numbers
<ide> import warnings
<ide> import numpy as np
<ide> import numpy.linalg as la
<ide><path>numpy/random/setup.py
<ide> from __future__ import division, print_function
<ide>
<del>from os.path import join, split, dirname
<del>import os
<add>from os.path import join
<ide> import sys
<ide> from distutils.dep_util import newer
<ide> from distutils.msvccompiler import get_build_version as get_msvc_build_version | 14 |
Go | Go | add pools for bufio readers & writers | 2d2016b81b1f313cda2c8f145844b162352ba234 | <ide><path>pkg/pools/pools.go
<add>// +build go1.3
<add>
<add>// Package pools provides a collection of pools which provide various
<add>// data types with buffers. These can be used to lower the number of
<add>// memory allocations and reuse buffers.
<add>//
<add>// New pools should be added to this package to allow them to be
<add>// shared across packages.
<add>//
<add>// Utility functions which operate on pools should be added to this
<add>// package to allow them to be reused.
<add>package pools
<add>
<add>import (
<add> "bufio"
<add> "io"
<add> "sync"
<add>
<add> "github.com/docker/docker/pkg/ioutils"
<add>)
<add>
<add>var (
<add> // Pool which returns bufio.Reader with a 32K buffer
<add> BufioReader32KPool *BufioReaderPool
<add> // Pool which returns bufio.Writer with a 32K buffer
<add> BufioWriter32KPool *BufioWriterPool
<add>)
<add>
<add>const buffer32K = 32 * 1024
<add>
<add>type BufioReaderPool struct {
<add> pool sync.Pool
<add>}
<add>
<add>func init() {
<add> BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K)
<add> BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K)
<add>}
<add>
<add>// newBufioReaderPoolWithSize is unexported because new pools should be
<add>// added here to be shared where required.
<add>func newBufioReaderPoolWithSize(size int) *BufioReaderPool {
<add> pool := sync.Pool{
<add> New: func() interface{} { return bufio.NewReaderSize(nil, size) },
<add> }
<add> return &BufioReaderPool{pool: pool}
<add>}
<add>
<add>// Get returns a bufio.Reader which reads from r. The buffer size is that of the pool.
<add>func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader {
<add> buf := bufPool.pool.Get().(*bufio.Reader)
<add> buf.Reset(r)
<add> return buf
<add>}
<add>
<add>// Put puts the bufio.Reader back into the pool.
<add>func (bufPool *BufioReaderPool) Put(b *bufio.Reader) {
<add> b.Reset(nil)
<add> bufPool.pool.Put(b)
<add>}
<add>
<add>// NewReadCloserWrapper returns a wrapper which puts the bufio.Reader back
<add>// into the pool and closes the reader if it's an io.ReadCloser.
<add>func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser {
<add> return ioutils.NewReadCloserWrapper(r, func() error {
<add> if readCloser, ok := r.(io.ReadCloser); ok {
<add> readCloser.Close()
<add> }
<add> bufPool.Put(buf)
<add> return nil
<add> })
<add>}
<add>
<add>type BufioWriterPool struct {
<add> pool sync.Pool
<add>}
<add>
<add>// newBufioWriterPoolWithSize is unexported because new pools should be
<add>// added here to be shared where required.
<add>func newBufioWriterPoolWithSize(size int) *BufioWriterPool {
<add> pool := sync.Pool{
<add> New: func() interface{} { return bufio.NewWriterSize(nil, size) },
<add> }
<add> return &BufioWriterPool{pool: pool}
<add>}
<add>
<add>// Get returns a bufio.Writer which writes to w. The buffer size is that of the pool.
<add>func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer {
<add> buf := bufPool.pool.Get().(*bufio.Writer)
<add> buf.Reset(w)
<add> return buf
<add>}
<add>
<add>// Put puts the bufio.Writer back into the pool.
<add>func (bufPool *BufioWriterPool) Put(b *bufio.Writer) {
<add> b.Reset(nil)
<add> bufPool.pool.Put(b)
<add>}
<add>
<add>// NewWriteCloserWrapper returns a wrapper which puts the bufio.Writer back
<add>// into the pool and closes the writer if it's an io.Writecloser.
<add>func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser {
<add> return ioutils.NewWriteCloserWrapper(w, func() error {
<add> buf.Flush()
<add> if writeCloser, ok := w.(io.WriteCloser); ok {
<add> writeCloser.Close()
<add> }
<add> bufPool.Put(buf)
<add> return nil
<add> })
<add>}
<ide><path>pkg/pools/pools_nopool.go
<add>// +build !go1.3
<add>
<add>package pools
<add>
<add>import (
<add> "bufio"
<add> "io"
<add>
<add> "github.com/docker/docker/pkg/ioutils"
<add>)
<add>
<add>var (
<add> BufioReader32KPool *BufioReaderPool
<add> BufioWriter32KPool *BufioWriterPool
<add>)
<add>
<add>const buffer32K = 32 * 1024
<add>
<add>type BufioReaderPool struct {
<add> size int
<add>}
<add>
<add>func init() {
<add> BufioReader32KPool = newBufioReaderPoolWithSize(buffer32K)
<add> BufioWriter32KPool = newBufioWriterPoolWithSize(buffer32K)
<add>}
<add>
<add>func newBufioReaderPoolWithSize(size int) *BufioReaderPool {
<add> return &BufioReaderPool{size: size}
<add>}
<add>
<add>func (bufPool *BufioReaderPool) Get(r io.Reader) *bufio.Reader {
<add> return bufio.NewReaderSize(r, bufPool.size)
<add>}
<add>
<add>func (bufPool *BufioReaderPool) Put(b *bufio.Reader) {
<add> b.Reset(nil)
<add>}
<add>
<add>func (bufPool *BufioReaderPool) NewReadCloserWrapper(buf *bufio.Reader, r io.Reader) io.ReadCloser {
<add> return ioutils.NewReadCloserWrapper(r, func() error {
<add> if readCloser, ok := r.(io.ReadCloser); ok {
<add> return readCloser.Close()
<add> }
<add> return nil
<add> })
<add>}
<add>
<add>type BufioWriterPool struct {
<add> size int
<add>}
<add>
<add>func newBufioWriterPoolWithSize(size int) *BufioWriterPool {
<add> return &BufioWriterPool{size: size}
<add>}
<add>
<add>func (bufPool *BufioWriterPool) Get(w io.Writer) *bufio.Writer {
<add> return bufio.NewWriterSize(w, bufPool.size)
<add>}
<add>
<add>func (bufPool *BufioWriterPool) Put(b *bufio.Writer) {
<add> b.Reset(nil)
<add>}
<add>
<add>func (bufPool *BufioWriterPool) NewWriteCloserWrapper(buf *bufio.Writer, w io.Writer) io.WriteCloser {
<add> return ioutils.NewWriteCloserWrapper(w, func() error {
<add> buf.Flush()
<add> if writeCloser, ok := w.(io.WriteCloser); ok {
<add> return writeCloser.Close()
<add> }
<add> return nil
<add> })
<add>} | 2 |
Java | Java | fix junit 4 to assertj migration bugs | 449377908fe20d6f0cae5822e6db204b2abf8e00 | <ide><path>spring-beans/src/test/java/org/springframework/beans/factory/support/DefinitionMetadataEqualsHashCodeTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> private void assertEqualsAndHashCodeContracts(Object master, Object equal, Objec
<ide> assertThat(equal.hashCode()).as("Hash code for equal instances should match").isEqualTo(master.hashCode());
<ide>
<ide> assertThat(notEqual).as("Should not be equal").isNotEqualTo(master);
<del> assertThat(notEqual.hashCode()).as("Hash code for non-equal instances should not match").isNotEqualTo((long) master.hashCode());
<add> assertThat(notEqual.hashCode()).as("Hash code for non-equal instances should not match").isNotEqualTo(master.hashCode());
<ide>
<ide> assertThat(subclass).as("Subclass should be equal").isEqualTo(master);
<ide> assertThat(subclass.hashCode()).as("Hash code for subclass should match").isEqualTo(master.hashCode());
<ide><path>spring-core/src/test/java/org/springframework/core/MethodParameterTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> void testHashCode() throws NoSuchMethodException {
<ide> Method method = getClass().getMethod("method", String.class, Long.TYPE);
<ide> MethodParameter methodParameter = new MethodParameter(method, 0);
<ide> assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode());
<del> assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode());
<add> assertThat(methodParameter.hashCode()).isNotEqualTo(longParameter.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-core/src/test/java/org/springframework/core/annotation/SynthesizingMethodParameterTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 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> void testHashCode() throws NoSuchMethodException {
<ide> Method method = getClass().getMethod("method", String.class, Long.TYPE);
<ide> SynthesizingMethodParameter methodParameter = new SynthesizingMethodParameter(method, 0);
<ide> assertThat(methodParameter.hashCode()).isEqualTo(stringParameter.hashCode());
<del> assertThat(methodParameter.hashCode()).isNotEqualTo((long) longParameter.hashCode());
<add> assertThat(methodParameter.hashCode()).isNotEqualTo(longParameter.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-expression/src/test/java/org/springframework/expression/spel/support/ReflectionHelperTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void testTypedValue() {
<ide> assertThat(tv1).isNotEqualTo(tv3);
<ide> assertThat(tv2).isNotEqualTo(tv3);
<ide> assertThat(tv2.hashCode()).isEqualTo(tv1.hashCode());
<del> assertThat(tv3.hashCode()).isNotEqualTo((long) tv1.hashCode());
<del> assertThat(tv3.hashCode()).isNotEqualTo((long) tv2.hashCode());
<add> assertThat(tv3.hashCode()).isNotEqualTo(tv1.hashCode());
<add> assertThat(tv3.hashCode()).isNotEqualTo(tv2.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-test/src/test/java/org/springframework/test/context/MergedContextConfigurationTests.java
<ide> class MergedContextConfigurationTests {
<ide> void hashCodeWithNulls() {
<ide> MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(null, null, null, null, null);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(null, null, null, null, null);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithNullArrays() {
<ide> MergedContextConfiguration mergedConfig1 = new MergedContextConfiguration(getClass(), null, null, null, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), null, null, null, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithEmptyArrays() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithEmptyArraysAndDifferentLoaders() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, new AnnotationConfigContextLoader());
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameLocations() {
<ide> EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations,
<ide> EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithDifferentLocations() {
<ide> EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), locations2,
<ide> EMPTY_CLASS_ARRAY, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameConfigClasses() {
<ide> EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, classes, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithDifferentConfigClasses() {
<ide> EMPTY_STRING_ARRAY, classes1, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, classes2, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameProfiles() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameProfilesReversed() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameDuplicateProfiles() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithDifferentProfiles() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles1, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, activeProfiles2, loader);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithSameInitializers() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> @Test
<ide> void hashCodeWithDifferentInitializers() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses1, EMPTY_STRING_ARRAY, loader);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(),
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, initializerClasses2, EMPTY_STRING_ARRAY, loader);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> /**
<ide> void hashCodeWithSameParent() {
<ide> EMPTY_STRING_ARRAY, EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
<ide> EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent);
<del> assertThat(mergedConfig2.hashCode()).isEqualTo(mergedConfig1.hashCode());
<add> assertThat(mergedConfig2).hasSameHashCodeAs(mergedConfig1);
<ide> }
<ide>
<ide> /**
<ide> void hashCodeWithDifferentParents() {
<ide> EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent1);
<ide> MergedContextConfiguration mergedConfig2 = new MergedContextConfiguration(getClass(), EMPTY_STRING_ARRAY,
<ide> EMPTY_CLASS_ARRAY, null, EMPTY_STRING_ARRAY, loader, null, parent2);
<del> assertThat(mergedConfig2.hashCode()).isNotEqualTo((long) mergedConfig1.hashCode());
<add> assertThat(mergedConfig2.hashCode()).isNotEqualTo(mergedConfig1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpRequestIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response)
<ide> URI uri = request.getURI();
<ide> assertThat(uri.getScheme()).isEqualTo("http");
<ide> assertThat(uri.getHost()).isNotNull();
<del> assertThat(uri.getPort()).isNotEqualTo((long) -1);
<add> assertThat(uri.getPort()).isNotEqualTo(-1);
<ide> assertThat(request.getRemoteAddress()).isNotNull();
<ide> assertThat(uri.getPath()).isEqualTo("/foo");
<ide> assertThat(uri.getQuery()).isEqualTo("param=bar");
<ide><path>spring-web/src/test/java/org/springframework/http/server/reactive/ServerHttpsRequestIntegrationTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public Mono<Void> handle(ServerHttpRequest request, ServerHttpResponse response)
<ide> URI uri = request.getURI();
<ide> assertThat(uri.getScheme()).isEqualTo("https");
<ide> assertThat(uri.getHost()).isNotNull();
<del> assertThat(uri.getPort()).isNotEqualTo((long) -1);
<add> assertThat(uri.getPort()).isNotEqualTo(-1);
<ide> assertThat(request.getRemoteAddress()).isNotNull();
<ide> assertThat(uri.getPath()).isEqualTo("/foo");
<ide> assertThat(uri.getQuery()).isEqualTo("param=bar");
<ide><path>spring-web/src/test/java/org/springframework/web/util/pattern/PathPatternParserTests.java
<ide> public void equalsAndHashcode() {
<ide> assertThat(pp2).isEqualTo(pp1);
<ide> assertThat(pp2.hashCode()).isEqualTo(pp1.hashCode());
<ide> assertThat(pp3).isNotEqualTo(pp1);
<del> assertThat(pp1.equals("abc")).isFalse();
<ide>
<ide> pp1 = caseInsensitiveParser.parse("/abc");
<ide> pp2 = caseSensitiveParser.parse("/abc");
<ide> assertThat(pp1.equals(pp2)).isFalse();
<del> assertThat(pp2.hashCode()).isNotEqualTo((long) pp1.hashCode());
<add> assertThat(pp2.hashCode()).isNotEqualTo(pp1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webflux/src/test/java/org/springframework/web/reactive/result/condition/RequestMappingInfoTests.java
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET, RequestMethod.POST)
<ide> .params("foo=bar").headers("foo=bar")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET)
<ide> .params("/NOOOOOO").headers("foo=bar")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET)
<ide> .params("foo=bar").headers("/NOOOOOO")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET)
<ide> .params("foo=bar").headers("foo=bar")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET)
<ide> .params("foo=bar").headers("foo=bar")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(RequestMethod.GET)
<ide> .params("foo=bar").headers("foo=bar")
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-webmvc/src/test/java/org/springframework/web/servlet/mvc/method/RequestMappingInfoTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void equals() {
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET, RequestMethod.POST)
<ide> .params("foo=bar", "customFoo=customBar").headers("foo=bar")
<ide> .consumes("text/plain").produces("text/plain")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET)
<ide> .params("/NOOOOOO", "customFoo=customBar").headers("foo=bar")
<ide> .consumes("text/plain").produces("text/plain")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET)
<ide> .params("foo=bar", "customFoo=customBar").headers("/NOOOOOO")
<ide> .consumes("text/plain").produces("text/plain")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET)
<ide> .params("foo=bar", "customFoo=customBar").headers("foo=bar")
<ide> .consumes("text/NOOOOOO").produces("text/plain")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET)
<ide> .params("foo=bar", "customFoo=customBar").headers("foo=bar")
<ide> .consumes("text/plain").produces("text/NOOOOOO")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide>
<ide> info2 = paths("/foo").methods(GET)
<ide> .params("foo=bar", "customFoo=NOOOOOO").headers("foo=bar")
<ide> .consumes("text/plain").produces("text/plain")
<ide> .build();
<ide>
<ide> assertThat(info1.equals(info2)).isFalse();
<del> assertThat(info2.hashCode()).isNotEqualTo((long) info1.hashCode());
<add> assertThat(info2.hashCode()).isNotEqualTo(info1.hashCode());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/server/support/OriginHandshakeInterceptorTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void originValueMatch() throws Exception {
<ide> List<String> allowed = Collections.singletonList("https://mydomain1.example");
<ide> OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(allowed);
<ide> assertThat(interceptor.beforeHandshake(request, response, wsHandler, attributes)).isTrue();
<del> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo((long) servletResponse.getStatus());
<add> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo(servletResponse.getStatus());
<ide> }
<ide>
<ide> @Test
<ide> public void originListMatch() throws Exception {
<ide> List<String> allowed = Arrays.asList("https://mydomain1.example", "https://mydomain2.example", "http://mydomain3.example");
<ide> OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(allowed);
<ide> assertThat(interceptor.beforeHandshake(request, response, wsHandler, attributes)).isTrue();
<del> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo((long) servletResponse.getStatus());
<add> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo(servletResponse.getStatus());
<ide> }
<ide>
<ide> @Test
<ide> public void originMatchAll() throws Exception {
<ide> OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor();
<ide> interceptor.setAllowedOrigins(Collections.singletonList("*"));
<ide> assertThat(interceptor.beforeHandshake(request, response, wsHandler, attributes)).isTrue();
<del> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo((long) servletResponse.getStatus());
<add> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo(servletResponse.getStatus());
<ide> }
<ide>
<ide> @Test
<ide> public void sameOriginMatchWithEmptyAllowedOrigins() throws Exception {
<ide> this.servletRequest.setServerName("mydomain2.example");
<ide> OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Collections.emptyList());
<ide> assertThat(interceptor.beforeHandshake(request, response, wsHandler, attributes)).isTrue();
<del> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo((long) servletResponse.getStatus());
<add> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo(servletResponse.getStatus());
<ide> }
<ide>
<ide> @Test
<ide> public void sameOriginMatchWithAllowedOrigins() throws Exception {
<ide> this.servletRequest.setServerName("mydomain2.example");
<ide> OriginHandshakeInterceptor interceptor = new OriginHandshakeInterceptor(Arrays.asList("http://mydomain1.example"));
<ide> assertThat(interceptor.beforeHandshake(request, response, wsHandler, attributes)).isTrue();
<del> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo((long) servletResponse.getStatus());
<add> assertThat(HttpStatus.FORBIDDEN.value()).isNotEqualTo(servletResponse.getStatus());
<ide> }
<ide>
<ide> @Test
<ide><path>spring-websocket/src/test/java/org/springframework/web/socket/sockjs/transport/handler/DefaultSockJsServiceTests.java
<ide> /*
<del> * Copyright 2002-2019 the original author or authors.
<add> * Copyright 2002-2020 the original author or authors.
<ide> *
<ide> * Licensed under the Apache License, Version 2.0 (the "License");
<ide> * you may not use this file except in compliance with the License.
<ide> public void handleTransportRequestWebsocket() throws Exception {
<ide> String sockJsPath = "/websocket";
<ide> setRequest("GET", sockJsPrefix + sockJsPath);
<ide> wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
<del> assertThat(this.servletResponse.getStatus()).isNotEqualTo((long) 403);
<add> assertThat(this.servletResponse.getStatus()).isNotEqualTo(403);
<ide>
<ide> resetRequestAndResponse();
<ide> List<String> allowed = Collections.singletonList("https://mydomain1.example");
<ide> public void handleTransportRequestWebsocket() throws Exception {
<ide> setRequest("GET", sockJsPrefix + sockJsPath);
<ide> this.servletRequest.addHeader(HttpHeaders.ORIGIN, "https://mydomain1.example");
<ide> wsService.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
<del> assertThat(this.servletResponse.getStatus()).isNotEqualTo((long) 403);
<add> assertThat(this.servletResponse.getStatus()).isNotEqualTo(403);
<ide>
<ide> resetRequestAndResponse();
<ide> setRequest("GET", sockJsPrefix + sockJsPath);
<ide> public void handleTransportRequestIframe() throws Exception {
<ide> String sockJsPath = "/iframe.html";
<ide> setRequest("GET", sockJsPrefix + sockJsPath);
<ide> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
<del> assertThat(this.servletResponse.getStatus()).isNotEqualTo((long) 404);
<add> assertThat(this.servletResponse.getStatus()).isNotEqualTo(404);
<ide> assertThat(this.servletResponse.getHeader("X-Frame-Options")).isEqualTo("SAMEORIGIN");
<ide>
<ide> resetRequestAndResponse();
<ide> public void handleTransportRequestIframe() throws Exception {
<ide> setRequest("GET", sockJsPrefix + sockJsPath);
<ide> this.service.setAllowedOrigins(Collections.singletonList("*"));
<ide> this.service.handleRequest(this.request, this.response, sockJsPath, this.wsHandler);
<del> assertThat(this.servletResponse.getStatus()).isNotEqualTo((long) 404);
<add> assertThat(this.servletResponse.getStatus()).isNotEqualTo(404);
<ide> assertThat(this.servletResponse.getHeader("X-Frame-Options")).isNull();
<ide> }
<ide> | 12 |
Go | Go | fix pid 0, -1, negative values | 735e25032659e4e46d8e1bf3c9fcc5b5ec785ec2 | <ide><path>pkg/process/process_test.go
<add>package process
<add>
<add>import (
<add> "fmt"
<add> "os"
<add> "os/exec"
<add> "runtime"
<add> "testing"
<add>)
<add>
<add>func TestAlive(t *testing.T) {
<add> for _, pid := range []int{0, -1, -123} {
<add> t.Run(fmt.Sprintf("invalid process (%d)", pid), func(t *testing.T) {
<add> if Alive(pid) {
<add> t.Errorf("PID %d should not be alive", pid)
<add> }
<add> })
<add> }
<add> t.Run("current process", func(t *testing.T) {
<add> if pid := os.Getpid(); !Alive(pid) {
<add> t.Errorf("current PID (%d) should be alive", pid)
<add> }
<add> })
<add> t.Run("exited process", func(t *testing.T) {
<add> if runtime.GOOS == "windows" {
<add> t.Skip("TODO: make this work on Windows")
<add> }
<add>
<add> // Get a PID of an exited process.
<add> cmd := exec.Command("echo", "hello world")
<add> err := cmd.Run()
<add> if err != nil {
<add> t.Fatal(err)
<add> }
<add> exitedPID := cmd.ProcessState.Pid()
<add> if Alive(exitedPID) {
<add> t.Errorf("PID %d should not be alive", exitedPID)
<add> }
<add> })
<add>}
<ide><path>pkg/process/process_unix.go
<ide> import (
<ide> "golang.org/x/sys/unix"
<ide> )
<ide>
<del>// Alive returns true if process with a given pid is running.
<add>// Alive returns true if process with a given pid is running. It only considers
<add>// positive PIDs; 0 (all processes in the current process group), -1 (all processes
<add>// with a PID larger than 1), and negative (-n, all processes in process group
<add>// "n") values for pid are never considered to be alive.
<ide> func Alive(pid int) bool {
<add> if pid < 1 {
<add> return false
<add> }
<ide> switch runtime.GOOS {
<ide> case "darwin":
<ide> // OS X does not have a proc filesystem. Use kill -0 pid to judge if the
<ide> func Alive(pid int) bool {
<ide> }
<ide> }
<ide>
<del>// Kill force-stops a process.
<add>// Kill force-stops a process. It only considers positive PIDs; 0 (all processes
<add>// in the current process group), -1 (all processes with a PID larger than 1),
<add>// and negative (-n, all processes in process group "n") values for pid are
<add>// ignored. Refer to [KILL(2)] for details.
<add>//
<add>// [KILL(2)]: https://man7.org/linux/man-pages/man2/kill.2.html
<ide> func Kill(pid int) error {
<add> if pid < 1 {
<add> return fmt.Errorf("invalid PID (%d): only positive PIDs are allowed", pid)
<add> }
<ide> err := unix.Kill(pid, unix.SIGKILL)
<ide> if err != nil && err != unix.ESRCH {
<ide> return err
<ide> }
<ide> return nil
<ide> }
<ide>
<del>// Zombie return true if process has a state with "Z"
<del>// http://man7.org/linux/man-pages/man5/proc.5.html
<add>// Zombie return true if process has a state with "Z". It only considers positive
<add>// PIDs; 0 (all processes in the current process group), -1 (all processes with
<add>// a PID larger than 1), and negative (-n, all processes in process group "n")
<add>// values for pid are ignored. Refer to [PROC(5)] for details.
<add>//
<add>// [PROC(5)]: https://man7.org/linux/man-pages/man5/proc.5.html
<ide> func Zombie(pid int) (bool, error) {
<add> if pid < 1 {
<add> return false, nil
<add> }
<ide> data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
<ide> if err != nil {
<ide> if os.IsNotExist(err) { | 2 |
Python | Python | fix multi-gpu evaluation in run_glue.py | 6fc3d34abd2a73303afe6f9d558b25e4a83ff93a | <ide><path>examples/run_glue.py
<ide> def evaluate(args, model, tokenizer, prefix=""):
<ide> eval_dataloader = DataLoader(eval_dataset, sampler=eval_sampler, batch_size=args.eval_batch_size)
<ide>
<ide> # multi-gpu eval
<del> if args.n_gpu > 1:
<add> if args.n_gpu > 1 and not isinstance(model, torch.nn.DataParallel):
<ide> model = torch.nn.DataParallel(model)
<ide>
<ide> # Eval! | 1 |
Python | Python | improve nested update and create testing | e1d98f77563abf49c4b19dcfb95f263515ae4087 | <ide><path>rest_framework/serializers.py
<ide> def create(self, validated_attrs):
<ide> # If we don't do this explicitly they'd likely get a confusing
<ide> # error at the point of calling `Model.objects.create()`.
<ide> assert not any(
<del> isinstance(field, BaseSerializer) and not field.read_only
<del> for field in self.fields.values()
<add> isinstance(field, BaseSerializer) and (key in validated_attrs)
<add> for key, field in self.fields.items()
<ide> ), (
<ide> 'The `.create()` method does not suport nested writable fields '
<ide> 'by default. Write an explicit `.create()` method for serializer '
<ide> def create(self, validated_attrs):
<ide> def update(self, instance, validated_attrs):
<ide> assert not any(
<ide> isinstance(field, BaseSerializer) and (key in validated_attrs)
<del> for key, field in self.fields.values()
<add> for key, field in self.fields.items()
<ide> ), (
<ide> 'The `.update()` method does not suport nested writable fields '
<ide> 'by default. Write an explicit `.update()` method for serializer ' | 1 |
Javascript | Javascript | show red boxes on hl mode | fe77ce1c62d6c6dc2a2eb6a3e532bbf39482b0d3 | <ide><path>Libraries/Utilities/HMRClient.js
<ide> URL: ${host}:${port}
<ide> Error: ${e.message}`
<ide> );
<ide> };
<del> activeWS.onmessage = (m) => {
<del> eval(m.data); // eslint-disable-line no-eval
<add> activeWS.onmessage = ({data}) => {
<add> data = JSON.parse(data);
<add> if (data.type === 'update') {
<add> eval(data.body); // eslint-disable-line no-eval
<add> return;
<add> }
<add>
<add> // TODO: add support for opening filename by clicking on the stacktrace
<add> const error = data.body;
<add> throw new Error(error.type + ' ' + error.description);
<ide> };
<ide> },
<ide> };
<ide><path>local-cli/server/util/attachHMRServer.js
<ide> function attachHMRServer({httpServer, path, packagerServer}) {
<ide> modules: modulesToUpdate,
<ide> });
<ide> })
<add> .then(update => {
<add> if (!client) {
<add> return;
<add> }
<add>
<add> // check we actually want to send an HMR update
<add> if (update) {
<add> return JSON.stringify({
<add> type: 'update',
<add> body: update,
<add> });
<add> }
<add> })
<add> .catch(error => {
<add> // send errors to the client instead of killing packager server
<add> let body;
<add> if (error.type === 'TransformError' ||
<add> error.type === 'NotFoundError' ||
<add> error.type === 'UnableToResolveError') {
<add> body = {
<add> type: error.type,
<add> description: error.description,
<add> filename: error.filename,
<add> lineNumber: error.lineNumber,
<add> };
<add> } else {
<add> console.error(error.stack || error);
<add> body = {
<add> type: 'InternalError',
<add> description: 'react-packager has encountered an internal error, ' +
<add> 'please check your terminal error output for more details',
<add> };
<add> }
<add>
<add> return JSON.stringify({type: 'error', body});
<add> })
<ide> .then(bundle => {
<ide> if (!client) {
<ide> return; | 2 |
Python | Python | convert as_strided input to array first | e8590311a7b312711c7a4f40c1a15496e34d0ee6 | <ide><path>numpy/lib/stride_tricks.py
<ide> def __init__(self, interface, base=None):
<ide> def as_strided(x, shape=None, strides=None, subok=False):
<ide> """ Make an ndarray from the given array with the given shape and strides.
<ide> """
<add> # first convert input to array, possibly keeping subclass
<add> x = np.array(x, copy=False, subok=subok)
<ide> interface = dict(x.__array_interface__)
<ide> if shape is not None:
<ide> interface['shape'] = tuple(shape)
<ide> def as_strided(x, shape=None, strides=None, subok=False):
<ide> # Make sure dtype is correct in case of custom dtype
<ide> if array.dtype.kind == 'V':
<ide> array.dtype = x.dtype
<del> if subok and isinstance(x, np.ndarray) and type(x) is not type(array):
<add> if type(x) is not type(array):
<add> # if input was an ndarray subclass and subclasses were OK,
<add> # then view the result as that subclass.
<ide> array = array.view(type=type(x))
<del> # we have done something akin to a view from x, so we should let a
<del> # possible subclass finalize (if it has it implemented)
<del> if callable(getattr(array, '__array_finalize__', None)):
<add> # Since we have done something akin to a view from x, we should let
<add> # the subclass finalize (if it has it implemented, i.e., is not None).
<add> if array.__array_finalize__:
<ide> array.__array_finalize__(x)
<ide> return array
<ide>
<ide><path>numpy/lib/tests/test_stride_tricks.py
<ide> def test_as_strided():
<ide> assert_array_equal(a_view, expected)
<ide>
<ide>
<del>class SimpleSubClass(np.ndarray):
<add>class VerySimpleSubClass(np.ndarray):
<add> def __new__(cls, *args, **kwargs):
<add> kwargs['subok'] = True
<add> return np.array(*args, **kwargs).view(cls)
<add>
<add>
<add>class SimpleSubClass(VerySimpleSubClass):
<ide> def __new__(cls, *args, **kwargs):
<ide> kwargs['subok'] = True
<ide> self = np.array(*args, **kwargs).view(cls)
<ide> def __array_finalize__(self, obj):
<ide>
<ide>
<ide> def test_subclasses():
<del> a = SimpleSubClass([1, 2, 3, 4])
<del> assert_(type(a) is SimpleSubClass)
<add> # test that subclass is preserved only if subok=True
<add> a = VerySimpleSubClass([1, 2, 3, 4])
<add> assert_(type(a) is VerySimpleSubClass)
<ide> a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,))
<ide> assert_(type(a_view) is np.ndarray)
<ide> a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
<del> assert_(a_view.info == 'simple finalized')
<add> assert_(type(a_view) is VerySimpleSubClass)
<add> # test that if a subclass has __array_finalize__, it is used
<add> a = SimpleSubClass([1, 2, 3, 4])
<add> a_view = as_strided(a, shape=(2,), strides=(2 * a.itemsize,), subok=True)
<ide> assert_(type(a_view) is SimpleSubClass)
<add> assert_(a_view.info == 'simple finalized')
<add>
<add> # similar tests for broadcast_arrays
<ide> b = np.arange(len(a)).reshape(-1, 1)
<ide> a_view, b_view = broadcast_arrays(a, b)
<ide> assert_(type(a_view) is np.ndarray) | 2 |
Javascript | Javascript | exclude gyp from markdown link checker | a77f2ea6d436402ef4c197a470fcb3bd3a3037cd | <ide><path>tools/doc/checkLinks.js
<ide> function findMarkdownFilesRecursively(dirPath) {
<ide> entry.name !== 'changelogs' &&
<ide> entry.name !== 'deps' &&
<ide> entry.name !== 'fixtures' &&
<add> entry.name !== 'gyp' &&
<ide> entry.name !== 'node_modules' &&
<ide> entry.name !== 'out' &&
<ide> entry.name !== 'tmp' | 1 |
Ruby | Ruby | remove mocking on save, when not necessary | 3c23f768440659c7c4eb20cea82032f71ef5556d | <ide><path>activerecord/test/cases/autosave_association_test.rb
<ide> def save(*args)
<ide>
<ide> def test_should_save_changed_has_one_changed_object_if_child_is_saved
<ide> @pirate.ship.name = "NewName"
<del> @pirate.ship.expects(:save).once.returns(true)
<del>
<ide> assert @pirate.save
<add> assert_equal "NewName", @pirate.ship.reload.name
<ide> end
<ide>
<ide> def test_should_not_save_changed_has_one_unchanged_object_if_child_is_saved
<ide> @pirate.ship.expects(:save).never
<del>
<ide> assert @pirate.save
<ide> end
<ide> | 1 |
Javascript | Javascript | add message verification on assert.throws | 3e7a414853fda90e6db28d1182ceb8ea61fbb83a | <ide><path>test/parallel/test-assert.js
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/g, /a/g));
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/i, /a/i));
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/m, /a/m));
<ide> assert.doesNotThrow(makeBlock(a.deepEqual, /a/igm, /a/igm));
<del>assert.throws(makeBlock(a.deepEqual, /ab/, /a/));
<del>assert.throws(makeBlock(a.deepEqual, /a/g, /a/));
<del>assert.throws(makeBlock(a.deepEqual, /a/i, /a/));
<del>assert.throws(makeBlock(a.deepEqual, /a/m, /a/));
<del>assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im));
<add>assert.throws(makeBlock(a.deepEqual, /ab/, /a/),
<add> /^AssertionError: \/ab\/ deepEqual \/a\/$/);
<add>assert.throws(makeBlock(a.deepEqual, /a/g, /a/),
<add> /^AssertionError: \/a\/g deepEqual \/a\/$/);
<add>assert.throws(makeBlock(a.deepEqual, /a/i, /a/),
<add> /^AssertionError: \/a\/i deepEqual \/a\/$/);
<add>assert.throws(makeBlock(a.deepEqual, /a/m, /a/),
<add> /^AssertionError: \/a\/m deepEqual \/a\/$/);
<add>assert.throws(makeBlock(a.deepEqual, /a/igm, /a/im),
<add> /^AssertionError: \/a\/gim deepEqual \/a\/im$/);
<ide>
<ide> {
<ide> const re1 = /a/; | 1 |
Mixed | Javascript | support uint8array input to send() | 2dc1053b0a6800ab7baf052017d37eaebf5e5a7e | <ide><path>doc/api/dgram.md
<ide> chained.
<ide> <!-- YAML
<ide> added: v0.1.99
<ide> changes:
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/11985
<add> description: The `msg` parameter can be an Uint8Array now.
<add> - version: REPLACEME
<add> pr-url: https://github.com/nodejs/node/pull/10473
<add> description: The `address` parameter is always optional now.
<ide> - version: v6.0.0
<ide> pr-url: https://github.com/nodejs/node/pull/5929
<ide> description: On success, `callback` will now be called with an `error`
<ide> argument of `null` rather than `0`.
<del> - version: REPLACEME
<del> pr-url: https://github.com/nodejs/node/pull/10473
<del> description: The `address` parameter is always optional now.
<ide> - version: v5.7.0
<ide> pr-url: https://github.com/nodejs/node/pull/4374
<ide> description: The `msg` parameter can be an array now. Also, the `offset`
<ide> and `length` parameters are optional now.
<ide> -->
<ide>
<del>* `msg` {Buffer|string|array} Message to be sent
<add>* `msg` {Buffer|Uint8Array|string|array} Message to be sent
<ide> * `offset` {number} Integer. Optional. Offset in the buffer where the message starts.
<ide> * `length` {number} Integer. Optional. Number of bytes in the message.
<ide> * `port` {number} Integer. Destination port.
<ide> Broadcasts a datagram on the socket. The destination `port` and `address` must
<ide> be specified.
<ide>
<ide> The `msg` argument contains the message to be sent.
<del>Depending on its type, different behavior can apply. If `msg` is a `Buffer`,
<add>Depending on its type, different behavior can apply. If `msg` is a `Buffer`
<add>or `Uint8Array`,
<ide> the `offset` and `length` specify the offset within the `Buffer` where the
<ide> message begins and the number of bytes in the message, respectively.
<ide> If `msg` is a `String`, then it is automatically converted to a `Buffer`
<ide> the error is emitted as an `'error'` event on the `socket` object.
<ide>
<ide> Offset and length are optional, but if you specify one you would need to
<ide> specify the other. Also, they are supported only when the first
<del>argument is a `Buffer`.
<add>argument is a `Buffer` or `Uint8Array`.
<ide>
<ide> Example of sending a UDP packet to a random port on `localhost`;
<ide>
<ide><path>lib/dgram.js
<ide> const UV_UDP_REUSEADDR = process.binding('constants').os.UV_UDP_REUSEADDR;
<ide>
<ide> const UDP = process.binding('udp_wrap').UDP;
<ide> const SendWrap = process.binding('udp_wrap').SendWrap;
<add>const { isUint8Array } = process.binding('util');
<ide>
<ide> const BIND_STATE_UNBOUND = 0;
<ide> const BIND_STATE_BINDING = 1;
<ide> Socket.prototype.sendto = function(buffer,
<ide>
<ide>
<ide> function sliceBuffer(buffer, offset, length) {
<del> if (typeof buffer === 'string')
<add> if (typeof buffer === 'string') {
<ide> buffer = Buffer.from(buffer);
<del> else if (!(buffer instanceof Buffer))
<del> throw new TypeError('First argument must be a buffer or string');
<add> } else if (!isUint8Array(buffer)) {
<add> throw new TypeError('First argument must be a Buffer, ' +
<add> 'Uint8Array or string');
<add> }
<ide>
<ide> offset = offset >>> 0;
<ide> length = length >>> 0;
<ide> function fixBufferList(list) {
<ide> var buf = list[i];
<ide> if (typeof buf === 'string')
<ide> newlist[i] = Buffer.from(buf);
<del> else if (!(buf instanceof Buffer))
<add> else if (!isUint8Array(buf))
<ide> return null;
<ide> else
<ide> newlist[i] = buf;
<ide> Socket.prototype.send = function(buffer,
<ide> if (!Array.isArray(buffer)) {
<ide> if (typeof buffer === 'string') {
<ide> list = [ Buffer.from(buffer) ];
<del> } else if (!(buffer instanceof Buffer)) {
<del> throw new TypeError('First argument must be a buffer or a string');
<add> } else if (!isUint8Array(buffer)) {
<add> throw new TypeError('First argument must be a Buffer, ' +
<add> 'Uint8Array or string');
<ide> } else {
<ide> list = [ buffer ];
<ide> }
<ide><path>test/parallel/test-dgram-send-default-host.js
<ide> const received = [];
<ide>
<ide> client.on('listening', common.mustCall(() => {
<ide> const port = client.address().port;
<add>
<ide> client.send(toSend[0], 0, toSend[0].length, port);
<ide> client.send(toSend[1], port);
<ide> client.send([toSend[2]], port);
<ide> client.send(toSend[3], 0, toSend[3].length, port);
<add>
<add> client.send(new Uint8Array(toSend[0]), 0, toSend[0].length, port);
<add> client.send(new Uint8Array(toSend[1]), port);
<add> client.send([new Uint8Array(toSend[2])], port);
<add> client.send(new Uint8Array(Buffer.from(toSend[3])),
<add> 0, toSend[3].length, port);
<ide> }));
<ide>
<ide> client.on('message', common.mustCall((buf, info) => {
<ide> received.push(buf.toString());
<ide>
<del> if (received.length === toSend.length) {
<add> if (received.length === toSend.length * 2) {
<ide> // The replies may arrive out of order -> sort them before checking.
<ide> received.sort();
<ide>
<del> const expected = toSend.map(String).sort();
<add> const expected = toSend.concat(toSend).map(String).sort();
<ide> assert.deepStrictEqual(received, expected);
<ide> client.close();
<ide> }
<del>}, toSend.length));
<add>}, toSend.length * 2));
<ide>
<ide> client.bind(0); | 3 |
Python | Python | update error messages several keras/utils module | edebe0f3b44714b30b8d3390da4fafa4df878651 | <ide><path>keras/metrics_confusion_matrix_test.py
<ide> def test_weighted_with_thresholds(self):
<ide> def test_threshold_limit(self):
<ide> with self.assertRaisesRegex(
<ide> ValueError,
<del> r'Threshold values must be in \[0, 1\]. Invalid values: \[-1, 2\]'):
<add> r'Threshold values must be in \[0, 1\]. Received: \[-1, 2\]'):
<ide> metrics.FalsePositives(thresholds=[-1, 0.5, 2])
<ide>
<ide> with self.assertRaisesRegex(
<ide> ValueError,
<del> r'Threshold values must be in \[0, 1\]. Invalid values: \[None\]'):
<add> r'Threshold values must be in \[0, 1\]. Received: \[None\]'):
<ide> metrics.FalsePositives(thresholds=[None])
<ide>
<ide>
<ide> def test_invalid_num_thresholds(self):
<ide>
<ide> def test_invalid_curve(self):
<ide> with self.assertRaisesRegex(ValueError,
<del> 'Invalid AUC curve value "Invalid".'):
<add> 'Invalid AUC curve value: "Invalid".'):
<ide> metrics.AUC(curve='Invalid')
<ide>
<ide> def test_invalid_summation_method(self):
<ide> with self.assertRaisesRegex(
<del> ValueError, 'Invalid AUC summation method value "Invalid".'):
<add> ValueError, 'Invalid AUC summation method value: "Invalid".'):
<ide> metrics.AUC(summation_method='Invalid')
<ide>
<ide> def test_extra_dims(self):
<ide><path>keras/utils/control_flow_util.py
<ide> def constant_value(pred): # pylint: disable=invalid-name
<ide> if isinstance(pred, tf.Variable):
<ide> return None
<ide> raise TypeError("`pred` must be a Tensor, or a Python bool, or 1 or 0. "
<del> "Found instead: %s" % type(pred))
<add> f"Received: {type(pred)}")
<ide><path>keras/utils/metrics_utils.py
<ide> def decorated(metric_obj, *args):
<ide> raise RuntimeError(
<ide> 'The output of `metric.result()` can only be a single '
<ide> 'Tensor/Variable, or a dict of Tensors/Variables. '
<del> 'For metric %s, got result %s.' % (metric_obj.name, raw_result))
<add> f'For metric {metric_obj.name}, got result {raw_result}.')
<ide> else:
<ide> # TODO(psv): Test distribution of metrics using different distribution
<ide> # strategies.
<ide> def assert_thresholds_range(thresholds):
<ide> invalid_thresholds = [t for t in thresholds if t is None or t < 0 or t > 1]
<ide> if invalid_thresholds:
<ide> raise ValueError(
<del> 'Threshold values must be in [0, 1]. Invalid values: {}'.format(
<del> invalid_thresholds))
<add> f'Threshold values must be in [0, 1]. Received: {invalid_thresholds}')
<ide>
<ide>
<ide> def parse_init_thresholds(thresholds, default_threshold=0.5):
<ide> def from_str(key):
<ide> elif key in ('roc', 'ROC'):
<ide> return AUCCurve.ROC
<ide> else:
<del> raise ValueError('Invalid AUC curve value "%s".' % key)
<add> raise ValueError(
<add> f'Invalid AUC curve value: "{key}". '
<add> 'Expected values are ["PR", "ROC"]')
<ide>
<ide>
<ide> class AUCSummationMethod(Enum):
<ide> def from_str(key):
<ide> elif key in ('minoring', 'Minoring'):
<ide> return AUCSummationMethod.MINORING
<ide> else:
<del> raise ValueError('Invalid AUC summation method value "%s".' % key)
<add> raise ValueError(
<add> f'Invalid AUC summation method value: "{key}". '
<add> 'Expected values are ["interpolation", "majoring", "minoring"]')
<ide>
<ide>
<ide> def _update_confusion_matrix_variables_optimized(
<ide> def update_confusion_matrix_variables(variables_to_update,
<ide> key for key in variables_to_update if key in list(ConfusionMatrix)):
<ide> raise ValueError(
<ide> 'Please provide at least one valid confusion matrix '
<del> 'variable to update. Valid variable key options are: "{}". '
<del> 'Received: "{}"'.format(
<del> list(ConfusionMatrix), variables_to_update.keys()))
<add> 'variable to update. Valid variable key options are: '
<add> f'"{list(ConfusionMatrix)}". Received: "{variables_to_update.keys()}"')
<ide>
<ide> variable_dtype = list(variables_to_update.values())[0].dtype
<ide>
<ide> def update_confusion_matrix_variables(variables_to_update,
<ide> ]
<ide> if invalid_keys:
<ide> raise ValueError(
<del> 'Invalid keys: {}. Valid variable key options are: "{}"'.format(
<del> invalid_keys, list(ConfusionMatrix)))
<add> f'Invalid keys: "{invalid_keys}". '
<add> f'Valid variable key options are: "{list(ConfusionMatrix)}"')
<ide>
<ide> with tf.control_dependencies([
<ide> tf.compat.v1.assert_greater_equal(
<ide> def ragged_assert_compatible_and_get_flat_values(values, mask=None):
<ide> values = flat_values[0] if to_be_stripped else flat_values
<ide>
<ide> elif is_any_ragged:
<del> raise TypeError('One of the inputs does not have acceptable types.')
<add> raise TypeError('Some of the inputs are not tf.RaggedTensor. '
<add> f'Input received: {values}')
<ide> # values are empty or value are not ragged and mask is ragged.
<ide> elif isinstance(mask, tf.RaggedTensor):
<del> raise TypeError('Ragged mask is not allowed with non-ragged inputs.')
<add> raise TypeError('Ragged mask is not allowed with non-ragged inputs. '
<add> f'Input received: {values}, mask received: {mask}')
<ide>
<ide> return values, mask
<ide>
<ide> def _assert_splits_match(nested_splits_lists):
<ide> Raises:
<ide> ValueError: If the splits are not identical.
<ide> """
<del> error_msg = 'Inputs must have identical ragged splits'
<add> error_msg = ('Inputs must have identical ragged splits. '
<add> f'Input received: {nested_splits_lists}')
<ide> for splits_list in nested_splits_lists:
<ide> if len(splits_list) != len(nested_splits_lists[0]):
<ide> raise ValueError(error_msg)
<ide><path>keras/utils/tf_utils.py
<ide> def get_reachable_from_inputs(inputs, targets=None):
<ide> elif tf.is_tensor(x):
<ide> outputs = x.consumers()
<ide> else:
<del> raise TypeError('Expected Operation, Variable, or Tensor, got ' + str(x))
<add> raise TypeError(
<add> f'Expected tf.Operation, tf.Variable, or tf.Tensor. Received: {x}')
<ide>
<ide> for y in outputs:
<ide> if y not in reachable:
<ide> def map_structure_with_atomic(is_atomic_fn, map_fn, nested):
<ide> # Recursively convert.
<ide> if not tf.nest.is_nested(nested):
<ide> raise ValueError(
<del> 'Received non-atomic and non-sequence element: {}'.format(nested))
<add> f'Received non-atomic and non-sequence element: {nested}')
<ide> if tf.__internal__.nest.is_mapping(nested):
<ide> values = [nested[k] for k in sorted(nested.keys())]
<ide> elif tf.__internal__.nest.is_attrs(nested):
<ide> def assert_no_legacy_layers(layers):
<ide> if legacy_layers:
<ide> layer_str = '\n'.join(' ' + str(l) for l in legacy_layers)
<ide> raise TypeError(
<del> 'The following are legacy tf.layers.Layers:\n{}\nTo use keras as a '
<add> f'The following are legacy tf.layers.Layers:\n{layer_str}\n'
<add> 'To use keras as a '
<ide> 'framework (for instance using the Network, Model, or Sequential '
<ide> 'classes), please use the tf.keras.layers implementation instead. '
<ide> '(Or, if writing custom layers, subclass from tf.keras.layers rather '
<del> 'than tf.layers)'.format(layer_str))
<add> 'than tf.layers)')
<ide>
<ide>
<ide> @tf_contextlib.contextmanager
<ide> def _astuple(attrs):
<ide> cls = type(attrs)
<ide> fields = getattr(cls, '__attrs_attrs__', None)
<ide> if fields is None:
<del> raise ValueError('%r is not an attrs-decorated class.' % cls)
<add> raise ValueError(f'{cls} is not an attrs-decorated class.')
<ide> values = []
<ide> for field in fields:
<ide> values.append(getattr(attrs, field.name))
<ide><path>keras/utils/version_utils.py
<ide> def swap_class(cls, v2_cls, v1_cls, use_v2):
<ide> def disallow_legacy_graph(cls_name, method_name):
<ide> if not tf.compat.v1.executing_eagerly_outside_functions():
<ide> error_msg = (
<del> "Calling `{cls_name}.{method_name}` in graph mode is not supported "
<del> "when the `{cls_name}` instance was constructed with eager mode "
<del> "enabled. Please construct your `{cls_name}` instance in graph mode or"
<del> " call `{cls_name}.{method_name}` with eager mode enabled.")
<del> error_msg = error_msg.format(cls_name=cls_name, method_name=method_name)
<add> f"Calling `{cls_name}.{method_name}` in graph mode is not supported "
<add> f"when the `{cls_name}` instance was constructed with eager mode "
<add> f"enabled. Please construct your `{cls_name}` instance in graph mode or"
<add> f" call `{cls_name}.{method_name}` with eager mode enabled.")
<ide> raise ValueError(error_msg)
<ide>
<ide> | 5 |
Javascript | Javascript | allow function in byproperty configurations | b067bad545c1fe9022cbd13a866493a864b4ea34 | <ide><path>lib/util/cleverMerge.js
<ide> const mergeCache = new WeakMap();
<ide> /** @type {WeakMap<object, Map<string, Map<string|number|boolean, object>>>} */
<ide> const setPropertyCache = new WeakMap();
<ide> const DELETE = Symbol("DELETE");
<add>const DYNAMIC_INFO = Symbol("cleverMerge dynamic info");
<ide>
<ide> /**
<ide> * Merges two given objects and caches the result to avoid computation if same objects passed as arguments again.
<ide> const cachedSetProperty = (obj, property, value) => {
<ide> * @property {Map<string, any>} byValues value depending on selector property, merged with base
<ide> */
<ide>
<del>/** @type {WeakMap<object, Map<string, ObjectParsedPropertyEntry>>} */
<add>/**
<add> * @typedef {Object} ParsedObject
<add> * @property {Map<string, ObjectParsedPropertyEntry>} static static properties (key is property name)
<add> * @property {{ byProperty: string, fn: Function } | undefined} dynamic dynamic part
<add> */
<add>
<add>/** @type {WeakMap<object, ParsedObject>} */
<ide> const parseCache = new WeakMap();
<ide>
<ide> /**
<ide> * @param {object} obj the object
<del> * @returns {Map<string, ObjectParsedPropertyEntry>} parsed properties
<add> * @returns {ParsedObject} parsed object
<ide> */
<ide> const cachedParseObject = obj => {
<ide> const entry = parseCache.get(obj);
<ide> const cachedParseObject = obj => {
<ide>
<ide> /**
<ide> * @param {object} obj the object
<del> * @returns {Map<string, ObjectParsedPropertyEntry>} parsed properties
<add> * @returns {ParsedObject} parsed object
<ide> */
<ide> const parseObject = obj => {
<ide> const info = new Map();
<add> let dynamicInfo;
<ide> const getInfo = p => {
<ide> const entry = info.get(p);
<ide> if (entry !== undefined) return entry;
<ide> const parseObject = obj => {
<ide> if (key.startsWith("by")) {
<ide> const byProperty = key;
<ide> const byObj = obj[byProperty];
<del> for (const byValue of Object.keys(byObj)) {
<del> const obj = byObj[byValue];
<del> for (const key of Object.keys(obj)) {
<del> const entry = getInfo(key);
<del> if (entry.byProperty === undefined) {
<del> entry.byProperty = byProperty;
<del> entry.byValues = new Map();
<del> } else if (entry.byProperty !== byProperty) {
<del> throw new Error(
<del> `${byProperty} and ${entry.byProperty} for a single property is not supported`
<del> );
<del> }
<del> entry.byValues.set(byValue, obj[key]);
<del> if (byValue === "default") {
<del> for (const otherByValue of Object.keys(byObj)) {
<del> if (!entry.byValues.has(otherByValue))
<del> entry.byValues.set(otherByValue, undefined);
<add> if (typeof byObj === "object") {
<add> for (const byValue of Object.keys(byObj)) {
<add> const obj = byObj[byValue];
<add> for (const key of Object.keys(obj)) {
<add> const entry = getInfo(key);
<add> if (entry.byProperty === undefined) {
<add> entry.byProperty = byProperty;
<add> entry.byValues = new Map();
<add> } else if (entry.byProperty !== byProperty) {
<add> throw new Error(
<add> `${byProperty} and ${entry.byProperty} for a single property is not supported`
<add> );
<add> }
<add> entry.byValues.set(byValue, obj[key]);
<add> if (byValue === "default") {
<add> for (const otherByValue of Object.keys(byObj)) {
<add> if (!entry.byValues.has(otherByValue))
<add> entry.byValues.set(otherByValue, undefined);
<add> }
<ide> }
<ide> }
<ide> }
<add> } else if (typeof byObj === "function") {
<add> if (dynamicInfo === undefined) {
<add> dynamicInfo = {
<add> byProperty: key,
<add> fn: byObj
<add> };
<add> } else {
<add> throw new Error(
<add> `${key} and ${dynamicInfo.byProperty} when both are functions is not supported`
<add> );
<add> }
<add> } else {
<add> const entry = getInfo(key);
<add> entry.base = obj[key];
<ide> }
<ide> } else {
<ide> const entry = getInfo(key);
<ide> entry.base = obj[key];
<ide> }
<ide> }
<del> return info;
<add> return {
<add> static: info,
<add> dynamic: dynamicInfo
<add> };
<ide> };
<ide>
<ide> /**
<del> * @param {Map<string, ObjectParsedPropertyEntry>} info property entries
<add> * @param {Map<string, ObjectParsedPropertyEntry>} info static properties (key is property name)
<add> * @param {{ byProperty: string, fn: Function } | undefined} dynamicInfo dynamic part
<ide> * @returns {object} the object
<ide> */
<del>const serializeObject = info => {
<add>const serializeObject = (info, dynamicInfo) => {
<ide> const obj = {};
<ide> // Setup byProperty structure
<ide> for (const entry of info.values()) {
<ide> const serializeObject = info => {
<ide> }
<ide> }
<ide> }
<add> if (dynamicInfo !== undefined) {
<add> obj[dynamicInfo.byProperty] = dynamicInfo.fn;
<add> }
<ide> return obj;
<ide> };
<ide>
<ide> const getValueType = value => {
<ide> const cleverMerge = (first, second, internalCaching = false) => {
<ide> if (second === undefined) return first;
<ide> if (first === undefined) return second;
<del> const firstInfo = internalCaching
<add> const firstObject = internalCaching
<ide> ? cachedParseObject(first)
<ide> : parseObject(first);
<del> const secondInfo = internalCaching
<add> const { static: firstInfo, dynamic: firstDynamicInfo } = firstObject;
<add>
<add> // If the first argument has a dynamic part we modify the dynamic part to merge the second argument
<add> if (firstDynamicInfo !== undefined) {
<add> let { byProperty, fn } = firstDynamicInfo;
<add> const fnInfo = fn[DYNAMIC_INFO];
<add> if (fnInfo) {
<add> second = internalCaching
<add> ? cachedCleverMerge(fnInfo[1], second)
<add> : cleverMerge(fnInfo[1], second, false);
<add> fn = fnInfo[0];
<add> }
<add> const newFn = (...args) => {
<add> const fnResult = fn(...args);
<add> if (typeof fnResult !== "object" || fnResult === null) return fnResult;
<add> return internalCaching
<add> ? cachedCleverMerge(fnResult, second)
<add> : cleverMerge(fnResult, second, false);
<add> };
<add> newFn[DYNAMIC_INFO] = [fn, second];
<add> return serializeObject(firstObject.static, { byProperty, fn: newFn });
<add> }
<add>
<add> // If the first part is static only, we merge the static parts and keep the dynamic part of the second argument
<add> const secondObject = internalCaching
<ide> ? cachedParseObject(second)
<ide> : parseObject(second);
<add> const { static: secondInfo, dynamic: secondDynamicInfo } = secondObject;
<ide> /** @type {Map<string, ObjectParsedPropertyEntry>} */
<del> const result = new Map();
<add> const resultInfo = new Map();
<ide> for (const [key, firstEntry] of firstInfo) {
<ide> const secondEntry = secondInfo.get(key);
<ide> const entry =
<ide> secondEntry !== undefined
<ide> ? mergeEntries(firstEntry, secondEntry, internalCaching)
<ide> : firstEntry;
<del> result.set(key, entry);
<add> resultInfo.set(key, entry);
<ide> }
<ide> for (const [key, secondEntry] of secondInfo) {
<ide> if (!firstInfo.has(key)) {
<del> result.set(key, secondEntry);
<add> resultInfo.set(key, secondEntry);
<ide> }
<ide> }
<del> return serializeObject(result);
<add> return serializeObject(resultInfo, secondDynamicInfo);
<ide> };
<ide>
<ide> /**
<ide> const resolveByProperty = (obj, byProperty, ...values) => {
<ide> return remaining;
<ide> }
<ide> } else if (typeof byValue === "function") {
<del> const result = resolveByProperty(
<del> byValue.apply(null, values),
<del> byProperty,
<del> ...values
<add> const result = byValue.apply(null, values);
<add> if (typeof result !== "object" || result === null) return result;
<add> return cleverMerge(
<add> remaining,
<add> resolveByProperty(result, byProperty, ...values)
<ide> );
<del> return cleverMerge(remaining, result);
<ide> }
<ide> };
<ide>
<ide><path>test/cleverMerge.unittest.js
<ide> const {
<ide> cleverMerge,
<ide> DELETE,
<del> removeOperations
<add> removeOperations,
<add> resolveByProperty
<ide> } = require("../lib/util/cleverMerge");
<ide>
<ide> describe("cleverMerge", () => {
<ide> describe("cleverMerge", () => {
<ide> }
<ide> }
<ide> }
<add> ],
<add> dynamicSecond: [
<add> {
<add> a: 4, // keep
<add> b: 5, // static override
<add> c: 6 // dynamic override
<add> },
<add> {
<add> b: 50,
<add> y: 20,
<add> byArguments: (x, y, z) => ({
<add> c: 60,
<add> x,
<add> y,
<add> z
<add> })
<add> },
<add> {
<add> a: 4,
<add> b: 50,
<add> c: 60,
<add> x: 1,
<add> y: 2,
<add> z: 3
<add> }
<add> ],
<add> dynamicBoth: [
<add> {
<add> a: 4, // keep
<add> b: 5, // static override
<add> c: 6, // dynamic override
<add> byArguments: (x, y, z) => ({
<add> x, // keep
<add> y, // static override
<add> z // dynamic override
<add> })
<add> },
<add> {
<add> b: 50,
<add> y: 20,
<add> byArguments: (x, y, z) => ({
<add> c: 60,
<add> z: z * 10
<add> })
<add> },
<add> {
<add> a: 4,
<add> b: 50,
<add> c: 60,
<add> x: 1,
<add> y: 20,
<add> z: 30
<add> }
<add> ],
<add> dynamicChained: [
<add> cleverMerge(
<add> {
<add> a: 6, // keep
<add> b: 7, // static override
<add> c: 8, // dynamic override
<add> d: 9, // static override (3rd)
<add> e: 10, // dynamic override (3rd)
<add> byArguments: (x, y, z, v, w) => ({
<add> x, // keep
<add> y, // static override
<add> z, // dynamic override
<add> v, // static override (3rd)
<add> w // dynamic override (3rd)
<add> })
<add> },
<add> {
<add> b: 70,
<add> y: 20,
<add> byArguments: (x, y, z) => ({
<add> c: 80,
<add> z: z * 10
<add> })
<add> }
<add> ),
<add> {
<add> d: 90,
<add> v: 40,
<add> byArguments: (x, y, z, v, w) => ({
<add> e: 100,
<add> w: w * 10
<add> })
<add> },
<add> {
<add> a: 6,
<add> b: 70,
<add> c: 80,
<add> d: 90,
<add> e: 100,
<add> x: 1,
<add> y: 20,
<add> z: 30,
<add> v: 40,
<add> w: 50
<add> }
<add> ],
<add> dynamicFalse1: [
<add> {
<add> a: 1,
<add> byArguments: () => false
<add> },
<add> {
<add> b: 2
<add> },
<add> false
<add> ],
<add> dynamicFalse2: [
<add> {
<add> a: 1
<add> },
<add> {
<add> b: 2,
<add> byArguments: () => false
<add> },
<add> false
<add> ],
<add> dynamicFalse3: [
<add> {
<add> a: 1,
<add> byArguments: () => false
<add> },
<add> {
<add> b: 2,
<add> byArguments: () => false
<add> },
<add> false
<ide> ]
<ide> };
<ide> for (const key of Object.keys(cases)) {
<ide> const testCase = cases[key];
<ide> it(`should merge ${key} correctly`, () => {
<del> expect(cleverMerge(testCase[0], testCase[1])).toEqual(testCase[2]);
<add> let merged = cleverMerge(testCase[0], testCase[1]);
<add> merged = resolveByProperty(merged, "byArguments", 1, 2, 3, 4, 5);
<add> expect(merged).toEqual(testCase[2]);
<ide> });
<ide> }
<ide> | 2 |
Python | Python | add tests for template filter methods/decorators | 820d099e82aa8ee01e1e82b85e2c6636d63be98a | <ide><path>flask/testsuite/blueprints.py
<ide> def foo_foo_foo():
<ide> rv = c.get('/py/bar/123')
<ide> assert rv.status_code == 404
<ide>
<add> def test_template_filter(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> @bp.app_template_filter()
<add> def my_reverse(s):
<add> return s[::-1]
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> self.assert_('my_reverse' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
<add>
<add> def test_add_template_filter(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> bp.add_app_template_filter(my_reverse)
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> self.assert_('my_reverse' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
<add>
<add> def test_template_filter_with_name(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> @bp.app_template_filter('strrev')
<add> def my_reverse(s):
<add> return s[::-1]
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> self.assert_('strrev' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
<add>
<add> def test_add_template_filter_with_name(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> bp.add_app_template_filter(my_reverse, 'strrev')
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> self.assert_('strrev' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
<add>
<add> def test_template_filter_with_template(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> @bp.app_template_filter()
<add> def super_reverse(s):
<add> return s[::-1]
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<add> def test_template_filter_after_route_with_template(self):
<add> app = flask.Flask(__name__)
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> bp = flask.Blueprint('bp', __name__)
<add> @bp.app_template_filter()
<add> def super_reverse(s):
<add> return s[::-1]
<add> app.register_blueprint(bp, url_prefix='/py')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<add> def test_add_template_filter_with_template(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> def super_reverse(s):
<add> return s[::-1]
<add> bp.add_app_template_filter(super_reverse)
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<add> def test_template_filter_with_name_and_template(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> @bp.app_template_filter('super_reverse')
<add> def my_reverse(s):
<add> return s[::-1]
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<add> def test_add_template_filter_with_name_and_template(self):
<add> bp = flask.Blueprint('bp', __name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> bp.add_app_template_filter(my_reverse, 'super_reverse')
<add> app = flask.Flask(__name__)
<add> app.register_blueprint(bp, url_prefix='/py')
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<ide>
<ide> def suite():
<ide> suite = unittest.TestSuite()
<ide><path>flask/testsuite/templating.py
<ide> def my_reverse(s):
<ide> self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
<ide> self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
<ide>
<add> def test_add_template_filter(self):
<add> app = flask.Flask(__name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> app.add_template_filter(my_reverse)
<add> self.assert_('my_reverse' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['my_reverse'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['my_reverse']('abcd'), 'dcba')
<add>
<ide> def test_template_filter_with_name(self):
<ide> app = flask.Flask(__name__)
<ide> @app.template_filter('strrev')
<ide> def my_reverse(s):
<ide> self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
<ide> self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
<ide>
<add> def test_add_template_filter_with_name(self):
<add> app = flask.Flask(__name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> app.add_template_filter(my_reverse, 'strrev')
<add> self.assert_('strrev' in app.jinja_env.filters.keys())
<add> self.assert_equal(app.jinja_env.filters['strrev'], my_reverse)
<add> self.assert_equal(app.jinja_env.filters['strrev']('abcd'), 'dcba')
<add>
<ide> def test_template_filter_with_template(self):
<ide> app = flask.Flask(__name__)
<ide> @app.template_filter()
<ide> def index():
<ide> rv = app.test_client().get('/')
<ide> self.assert_equal(rv.data, 'dcba')
<ide>
<add> def test_add_template_filter_with_template(self):
<add> app = flask.Flask(__name__)
<add> def super_reverse(s):
<add> return s[::-1]
<add> app.add_template_filter(super_reverse)
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<ide> def test_template_filter_with_name_and_template(self):
<ide> app = flask.Flask(__name__)
<ide> @app.template_filter('super_reverse')
<ide> def index():
<ide> rv = app.test_client().get('/')
<ide> self.assert_equal(rv.data, 'dcba')
<ide>
<add> def test_add_template_filter_with_name_and_template(self):
<add> app = flask.Flask(__name__)
<add> def my_reverse(s):
<add> return s[::-1]
<add> app.add_template_filter(my_reverse, 'super_reverse')
<add> @app.route('/')
<add> def index():
<add> return flask.render_template('template_filter.html', value='abcd')
<add> rv = app.test_client().get('/')
<add> self.assert_equal(rv.data, 'dcba')
<add>
<ide> def test_custom_template_loader(self):
<ide> class MyFlask(flask.Flask):
<ide> def create_global_jinja_loader(self): | 2 |
PHP | PHP | add missing exceptions docblocks. | 3644e861ef9cbf6529e0e9f54e1636f403070ff2 | <ide><path>src/Illuminate/Broadcasting/Broadcasters/Broadcaster.php
<ide> public function channel($channel, callable $callback)
<ide> * @param \Illuminate\Http\Request $request
<ide> * @param string $channel
<ide> * @return mixed
<add> * @throws \Symfony\Component\HttpKernel\Exception\HttpException
<ide> */
<ide> protected function verifyUserCanAccessChannel($request, $channel)
<ide> {
<ide> protected function resolveExplicitBindingIfPossible($key, $value)
<ide> * @param mixed $value
<ide> * @param array $callbackParameters
<ide> * @return mixed
<add> * @throws \Symfony\Component\HttpKernel\Exception\HttpException
<ide> */
<ide> protected function resolveImplicitBindingIfPossible($key, $value, $callbackParameters)
<ide> {
<ide><path>src/Illuminate/Broadcasting/Broadcasters/PusherBroadcaster.php
<ide> public function __construct(Pusher $pusher)
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @return mixed
<add> * @throws \Symfony\Component\HttpKernel\Exception\HttpException
<ide> */
<ide> public function auth($request)
<ide> {
<ide><path>src/Illuminate/Broadcasting/Broadcasters/RedisBroadcaster.php
<ide> public function __construct(Redis $redis, $connection = null)
<ide> *
<ide> * @param \Illuminate\Http\Request $request
<ide> * @return mixed
<add> * @throws \Symfony\Component\HttpKernel\Exception\HttpException
<ide> */
<ide> public function auth($request)
<ide> { | 3 |
Text | Text | fix typo in docker-context-files/readme.md | 81a977be6cb1fb6b309b6f92a7d248fe77a853e5 | <ide><path>docker-context-files/README.md
<ide> This folder is par of the Docker context.
<ide>
<ide> Most of other folders in Airflow are not part of the context in order to make the context smaller.
<ide>
<del>The Production [Dockerfile](../Dockerfile) copies th [docker-context-files](.) folder to the "build"
<add>The Production [Dockerfile](../Dockerfile) copies the [docker-context-files](.) folder to the "build"
<ide> stage of the production image (it is not used in the CI image) and content of the folder is available
<ide> in the `/docker-context-file` folder inside the build image. You can store constraint files and wheel
<ide> packages there that you want to install as PYPI packages and refer to those packages using | 1 |
PHP | PHP | allow easy addition of custom drivers | 68a4993372525cb154201ed02592e0086dc70877 | <ide><path>src/Illuminate/Notifications/ChannelManager.php
<ide>
<ide> namespace Illuminate\Notifications;
<ide>
<add>use InvalidArgumentException;
<ide> use Illuminate\Support\Manager;
<ide> use Nexmo\Client as NexmoClient;
<ide> use GuzzleHttp\Client as HttpClient;
<ide> protected function createSlackDriver()
<ide> return new Channels\SlackWebhookChannel(new HttpClient);
<ide> }
<ide>
<add> /**
<add> * Create a new driver instance.
<add> *
<add> * @param string $driver
<add> * @return mixed
<add> *
<add> * @throws \InvalidArgumentException
<add> */
<add> protected function createDriver($driver)
<add> {
<add> try {
<add> return parent::createDriver($driver);
<add> } catch (InvalidArgumentException $e) {
<add> if (class_exists($driver)) {
<add> return $this->app->make($driver);
<add> }
<add>
<add> throw $e;
<add> }
<add> }
<add>
<ide> /**
<ide> * Get the default channel driver names.
<ide> * | 1 |
Text | Text | add an article on vue-router | 9d1ce7b83cea43961099e67c33c5ab5450d1f467 | <ide><path>guide/english/vue/router/index.md
<add>---
<add>title: Router
<add>---
<add>
<add>## Introduction
<add>Vue router is the official router for Vue.js. With it you can easily create your Single Page Apps.
<add>
<add>## Basics
<add>If you want to use Vue Router in your app, first you'll need to inject it in your root instance to make your whole application aware of the router.
<add>```javascript
<add>new Vue({
<add> el: '#app',
<add> router,
<add> render: h => h(App)
<add>})
<add>```
<add>Now, to use the power of Vue Router all you need to do is map Vue.js componenets with routes and specify where to render them.
<add>For example, your main template may look like that:
<add>```javascript
<add><template>
<add> <div id="app">
<add> <app-header></app-header>
<add> <router-view></router-view>
<add> <app-footer></app-footer>
<add> </div>
<add></template>
<add>```
<add>Then in `<router-view />` place it will render a component which is specified for this route. We map components to routes in router itself:
<add>```javascript
<add>import Vue from 'vue'
<add>import Router from 'vue-router'
<add>import Home from '@/components/Home'
<add>import Contacts from '@/components/Contacts'
<add>
<add>Vue.use(Router)
<add>
<add>export default new Router({
<add> routes: [
<add> {
<add> path: '/',
<add> name: 'Home',
<add> component: Home
<add> },
<add> {
<add> path: '/contacts',
<add> name: 'Contacts',
<add> component: Contacts
<add> }
<add> ]
<add>})
<add>```
<add>You can add as many routes as you need. It is also possible to use wildcards, aliases, redirects, dynamic route mapping, etc.
<add>
<add>## Read more
<add>- [Vue Router official docs](https://router.vuejs.org/)
<add>- [Vue Router's Github repository](https://github.com/vuejs/vue-router) | 1 |
Text | Text | fix minor version typo | cc358c2cadd16751f4df925b0a14a781de4a0160 | <ide><path>docs/Installation.md
<ide> Uninstallation is documented in the [FAQ](FAQ.md).
<ide>
<ide> <a name="1"><sup>1</sup></a> For 32-bit or PPC support see [Tigerbrew](https://github.com/mistydemeo/tigerbrew).
<ide>
<del><a name="2"><sup>2</sup></a> macOS 11 (Ventura) or higher is best and supported, 10.11 (El Capitan) – 10.14 (Mojave) are unsupported but may work and 10.10 (Yosemite) and older will not run Homebrew at all. For 10.4 (Tiger) – 10.6 (Snow Leopard) see [Tigerbrew](https://github.com/mistydemeo/tigerbrew).
<add><a name="2"><sup>2</sup></a> macOS 11 (Big Sur) or higher is best and supported, 10.11 (El Capitan) – 10.14 (Mojave) are unsupported but may work and 10.10 (Yosemite) and older will not run Homebrew at all. For 10.4 (Tiger) – 10.6 (Snow Leopard) see [Tigerbrew](https://github.com/mistydemeo/tigerbrew).
<ide>
<ide> <a name="3"><sup>3</sup></a> You may need to install Xcode, the CLT, or both depending on the formula, to install a bottle (binary package) which is the only supported configuration. Downloading Xcode may require an Apple Developer account on older versions of Mac OS X. Sign up for free at [Apple's website](https://developer.apple.com/register/index.action).
<ide> | 1 |
Ruby | Ruby | avoid network call in `#initialize` | b54682f7091724fee2537b25a2dcc4d084d6a773 | <ide><path>Library/Homebrew/download_strategy.rb
<ide> def extract_ref(specs)
<ide> end
<ide>
<ide> class AbstractFileDownloadStrategy < AbstractDownloadStrategy
<del> attr_reader :temporary_path
<del>
<del> def initialize(url, name, version, **meta)
<del> super
<del> @temporary_path = Pathname.new("#{cached_location}.incomplete")
<add> def temporary_path
<add> @temporary_path ||= Pathname.new("#{cached_location}.incomplete")
<ide> end
<ide>
<ide> def symlink_location | 1 |
Ruby | Ruby | require xcode 10.2 on macos 10.14 | 01a342550285a92d8eef84e27721389c40029f76 | <ide><path>Library/Homebrew/os/mac/xcode.rb
<ide> def latest_version
<ide>
<ide> def minimum_version
<ide> case MacOS.version
<del> when "10.14" then "10.0"
<add> when "10.14" then "10.2"
<ide> when "10.13" then "9.0"
<ide> when "10.12" then "8.0"
<ide> else "2.0"
<ide><path>Library/Homebrew/requirements/xcode_requirement.rb
<ide> def initialize(tags = [])
<ide>
<ide> def xcode_installed_version
<ide> return false unless MacOS::Xcode.installed?
<del> return false unless xcode_swift_compatability?
<ide> return true unless @version
<ide>
<ide> MacOS::Xcode.version >= @version
<ide> def message
<ide> A full installation of Xcode.app#{version} is required to compile
<ide> this software. Installing just the Command Line Tools is not sufficient.
<ide> EOS
<del> unless xcode_swift_compatability?
<del> message += <<~EOS
<del>
<del> Xcode >=10.2 requires macOS >=10.14.4 to build many formulae.
<del> EOS
<del> end
<ide> if @version && Version.new(MacOS::Xcode.latest_version) < Version.new(@version)
<ide> message + <<~EOS
<ide>
<ide> def message
<ide> def inspect
<ide> "#<#{self.class.name}: #{tags.inspect} version=#{@version.inspect}>"
<ide> end
<del>
<del> private
<del>
<del> # TODO: when 10.14.4 and 10.2 have been around for long enough remove this
<del> # method in favour of requiring 10.14.4 and 10.2.
<del> def xcode_swift_compatability?
<del> return true if MacOS::Xcode.version < "10.2"
<del> return true if MacOS.full_version >= "10.14.4"
<del>
<del> MacOS.full_version < "10.14"
<del> end
<ide> end | 2 |
Text | Text | propose some sentence changes | c64bbfeacd031a5a09e263b85b0d7f51f36211bf | <ide><path>docs/advanced-features/customizing-babel-config.md
<ide> description: Extend the babel preset added by Next.js with your own configs.
<ide> </ul>
<ide> </details>
<ide>
<del>Next.js includes the `next/babel` preset to your app, it includes everything needed to compile React applications and server-side code. But if you want to extend the default Babel configs, it's also possible.
<add>Next.js includes the `next/babel` preset to your app, which includes everything needed to compile React applications and server-side code. But if you want to extend the default Babel configs, it's also possible.
<ide>
<del>To start, you only need to define a `.babelrc` file at the top of your app, if such file is found, we're going to consider it the _source of truth_, therefore it needs to define what Next.js needs as well, which is the `next/babel` preset.
<add>To start, you only need to define a `.babelrc` file at the top of your app. If such a file is found, it will be considered as the _source of truth_, and therefore it needs to define what Next.js needs as well, which is the `next/babel` preset.
<ide>
<ide> Here's an example `.babelrc` file:
<ide> | 1 |
Text | Text | add missing labels to forms doc | e08be27b0c20b06ace289a2c2a4ac875adb4c163 | <ide><path>docs/docs/forms.md
<ide> HTML form elements work a little bit differently from other DOM elements in Reac
<ide>
<ide> ```html
<ide> <form>
<del> Name:
<del> <input type="text" name="name" />
<add> <label>
<add> Name:
<add> <input type="text" name="name" />
<add> </label>
<ide> <input type="submit" value="Submit" />
<ide> </form>
<ide> ```
<ide> class NameForm extends React.Component {
<ide> render() {
<ide> return (
<ide> <form onSubmit={this.handleSubmit}>
<del> Name:
<del> <input type="text" value={this.state.value} onChange={this.handleChange} />
<add> <label>
<add> Name:
<add> <input type="text" value={this.state.value} onChange={this.handleChange} />
<add> </label>
<ide> <input type="submit" value="Submit" />
<ide> </form>
<ide> );
<ide> class EssayForm extends React.Component {
<ide> render() {
<ide> return (
<ide> <form onSubmit={this.handleSubmit}>
<del> Name:
<del> <textarea value={this.state.value} onChange={this.handleChange} />
<add> <label>
<add> Name:
<add> <textarea value={this.state.value} onChange={this.handleChange} />
<add> </label>
<ide> <input type="submit" value="Submit" />
<ide> </form>
<ide> );
<ide> class FlavorForm extends React.Component {
<ide> render() {
<ide> return (
<ide> <form onSubmit={this.handleSubmit}>
<del> Pick your favorite La Croix flavor:
<del> <select value={this.state.value} onChange={this.handleChange}>
<del> <option value="grapefruit">Grapefruit</option>
<del> <option value="lime">Lime</option>
<del> <option value="coconut">Coconut</option>
<del> <option value="mango">Mango</option>
<del> </select>
<add> <label>
<add> Pick your favorite La Croix flavor:
<add> <select value={this.state.value} onChange={this.handleChange}>
<add> <option value="grapefruit">Grapefruit</option>
<add> <option value="lime">Lime</option>
<add> <option value="coconut">Coconut</option>
<add> <option value="mango">Mango</option>
<add> </select>
<add> </label>
<ide> <input type="submit" value="Submit" />
<ide> </form>
<ide> ); | 1 |
Python | Python | add en_parser fixture | 09807addff1519a543af2c5b7b21c94173983e23 | <ide><path>spacy/tests/conftest.py
<ide> def en_vocab():
<ide> return English.Defaults.create_vocab()
<ide>
<ide>
<add>@pytest.fixture
<add>def en_parser():
<add> return English.Defaults.create_parser()
<add>
<add>
<ide> @pytest.fixture
<ide> def de_tokenizer():
<ide> return German.Defaults.create_tokenizer() | 1 |
Python | Python | handle naive datetimes in rest apii | 7478e18ee55eed80a2b8a8f7599b95d0955986c0 | <ide><path>airflow/api_connexion/endpoints/dag_run_endpoint.py
<ide> def post_dag_run(dag_id, session):
<ide> """Trigger a DAG."""
<ide> if not session.query(DagModel).filter(DagModel.dag_id == dag_id).first():
<ide> raise NotFound(title="DAG not found", detail=f"DAG with dag_id: '{dag_id}' not found")
<del>
<del> post_body = dagrun_schema.load(request.json, session=session)
<add> try:
<add> post_body = dagrun_schema.load(request.json, session=session)
<add> except ValidationError as err:
<add> raise BadRequest(detail=str(err))
<ide> dagrun_instance = (
<ide> session.query(DagRun).filter(DagRun.dag_id == dag_id, DagRun.run_id == post_body["run_id"]).first()
<ide> )
<ide><path>airflow/api_connexion/parameters.py
<ide> from airflow.utils import timezone
<ide>
<ide>
<add>def validate_istimezone(value):
<add> """Validates that a datetime is not naive"""
<add> if not value.tzinfo:
<add> raise BadRequest("Invalid datetime format", detail="Naive datetime is disallowed")
<add>
<add>
<ide> def format_datetime(value: str):
<ide> """
<ide> Datetime format parser for args since connexion doesn't parse datetimes
<ide><path>airflow/api_connexion/schemas/dag_run_schema.py
<ide> from marshmallow.schema import Schema
<ide> from marshmallow_sqlalchemy import SQLAlchemySchema, auto_field
<ide>
<add>from airflow.api_connexion.parameters import validate_istimezone
<ide> from airflow.api_connexion.schemas.enum_schemas import DagStateField
<ide> from airflow.models.dagrun import DagRun
<ide> from airflow.utils import timezone
<ide> class Meta:
<ide>
<ide> run_id = auto_field(data_key='dag_run_id')
<ide> dag_id = auto_field(dump_only=True)
<del> execution_date = auto_field()
<add> execution_date = auto_field(validate=validate_istimezone)
<ide> start_date = auto_field(dump_only=True)
<ide> end_date = auto_field(dump_only=True)
<ide> state = DagStateField(dump_only=True)
<ide> class Meta:
<ide> page_offset = fields.Int(missing=0, min=0)
<ide> page_limit = fields.Int(missing=100, min=1)
<ide> dag_ids = fields.List(fields.Str(), missing=None)
<del> execution_date_gte = fields.DateTime(missing=None)
<del> execution_date_lte = fields.DateTime(missing=None)
<del> start_date_gte = fields.DateTime(missing=None)
<del> start_date_lte = fields.DateTime(missing=None)
<del> end_date_gte = fields.DateTime(missing=None)
<del> end_date_lte = fields.DateTime(missing=None)
<add> execution_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> execution_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> start_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> start_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> end_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> end_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<ide>
<ide>
<ide> dagrun_schema = DAGRunSchema()
<ide><path>airflow/api_connexion/schemas/task_instance_schema.py
<ide> from marshmallow import Schema, ValidationError, fields, validate, validates_schema
<ide> from marshmallow.utils import get_value
<ide>
<add>from airflow.api_connexion.parameters import validate_istimezone
<ide> from airflow.api_connexion.schemas.enum_schemas import TaskInstanceStateField
<ide> from airflow.api_connexion.schemas.sla_miss_schema import SlaMissSchema
<ide> from airflow.models import SlaMiss, TaskInstance
<ide> class TaskInstanceSchema(Schema):
<ide>
<ide> task_id = fields.Str()
<ide> dag_id = fields.Str()
<del> execution_date = fields.DateTime()
<del> start_date = fields.DateTime()
<del> end_date = fields.DateTime()
<add> execution_date = fields.DateTime(validate=validate_istimezone)
<add> start_date = fields.DateTime(validate=validate_istimezone)
<add> end_date = fields.DateTime(validate=validate_istimezone)
<ide> duration = fields.Float()
<ide> state = TaskInstanceStateField()
<ide> _try_number = fields.Int(data_key="try_number")
<ide> class TaskInstanceBatchFormSchema(Schema):
<ide> page_offset = fields.Int(missing=0, min=0)
<ide> page_limit = fields.Int(missing=100, min=1)
<ide> dag_ids = fields.List(fields.Str(), missing=None)
<del> execution_date_gte = fields.DateTime(missing=None)
<del> execution_date_lte = fields.DateTime(missing=None)
<del> start_date_gte = fields.DateTime(missing=None)
<del> start_date_lte = fields.DateTime(missing=None)
<del> end_date_gte = fields.DateTime(missing=None)
<del> end_date_lte = fields.DateTime(missing=None)
<add> execution_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> execution_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> start_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> start_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> end_date_gte = fields.DateTime(missing=None, validate=validate_istimezone)
<add> end_date_lte = fields.DateTime(missing=None, validate=validate_istimezone)
<ide> duration_gte = fields.Int(missing=None)
<ide> duration_lte = fields.Int(missing=None)
<ide> state = fields.List(fields.Str(), missing=None)
<ide> class ClearTaskInstanceFormSchema(Schema):
<ide> """Schema for handling the request of clearing task instance of a Dag"""
<ide>
<ide> dry_run = fields.Boolean(default=True)
<del> start_date = fields.DateTime(missing=None)
<del> end_date = fields.DateTime(missing=None)
<add> start_date = fields.DateTime(missing=None, validate=validate_istimezone)
<add> end_date = fields.DateTime(missing=None, validate=validate_istimezone)
<ide> only_failed = fields.Boolean(missing=True)
<ide> only_running = fields.Boolean(missing=False)
<ide> include_subdags = fields.Boolean(missing=False)
<ide> class SetTaskInstanceStateFormSchema(Schema):
<ide>
<ide> dry_run = fields.Boolean(default=True)
<ide> task_id = fields.Str(required=True)
<del> execution_date = fields.DateTime(required=True)
<add> execution_date = fields.DateTime(required=True, validate=validate_istimezone)
<ide> include_upstream = fields.Boolean(required=True)
<ide> include_downstream = fields.Boolean(required=True)
<ide> include_future = fields.Boolean(required=True)
<ide><path>tests/api_connexion/endpoints/test_dag_run_endpoint.py
<ide> def _create_test_dag_run(self, state='running', extra_dag=False, commit=True):
<ide> dag_runs.append(dagrun_model_2)
<ide> if extra_dag:
<ide> for i in range(3, 5):
<del>
<ide> dags.append(DagModel(dag_id='TEST_DAG_ID_' + str(i)))
<ide> dag_runs.append(
<ide> DagRun(
<ide> def _create_dag_runs(self):
<ide> session.add(dag)
<ide> return dag_runs
<ide>
<add> @parameterized.expand(
<add> [
<add> ({"execution_date_gte": '2020-11-09T16:25:56.939143'}, 'Naive datetime is disallowed'),
<add> (
<add> {"start_date_gte": "2020-06-18T16:25:56.939143"},
<add> 'Naive datetime is disallowed',
<add> ),
<add> (
<add> {"start_date_lte": "2020-06-18T18:00:00.564434"},
<add> 'Naive datetime is disallowed',
<add> ),
<add> (
<add> {"start_date_lte": "2020-06-15T18:00:00.653434", "start_date_gte": "2020-06-12T18:00.343534"},
<add> 'Naive datetime is disallowed',
<add> ),
<add> (
<add> {"execution_date_lte": "2020-06-13T18:00:00.353454"},
<add> 'Naive datetime is disallowed',
<add> ),
<add> ({"execution_date_gte": "2020-06-16T18:00:00.676443"}, 'Naive datetime is disallowed'),
<add> ]
<add> )
<add> def test_naive_date_filters_raises_400(self, payload, expected_response):
<add> self._create_dag_runs()
<add>
<add> response = self.client.post(
<add> "api/v1/dags/~/dagRuns/list", json=payload, environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> assert response.status_code == 400
<add> self.assertEqual(response.json['detail'], expected_response)
<add>
<ide> @parameterized.expand(
<ide> [
<ide> (
<ide> def test_should_respond_200(self, name, request_json, session):
<ide> response.json,
<ide> )
<ide>
<add> @parameterized.expand(
<add> [
<add> ({'execution_date': "2020-11-10T08:25:56.939143"}, 'Naive datetime is disallowed'),
<add> ({'execution_date': "2020-11-10T08:25:56P"}, "{'execution_date': ['Not a valid datetime.']}"),
<add> ]
<add> )
<add> @provide_session
<add> def test_should_response_400_for_naive_datetime_and_bad_datetime(self, data, expected, session):
<add> dag_instance = DagModel(dag_id="TEST_DAG_ID")
<add> session.add(dag_instance)
<add> session.commit()
<add> response = self.client.post(
<add> "api/v1/dags/TEST_DAG_ID/dagRuns", json=data, environ_overrides={'REMOTE_USER': "test"}
<add> )
<add> self.assertEqual(response.status_code, 400)
<add> self.assertEqual(response.json['detail'], expected)
<add>
<ide> def test_response_404(self):
<ide> response = self.client.post(
<ide> "api/v1/dags/TEST_DAG_ID/dagRuns",
<ide><path>tests/api_connexion/endpoints/test_task_instance_endpoint.py
<ide> def test_should_raise_403_forbidden(self):
<ide> )
<ide> assert response.status_code == 403
<ide>
<add> @parameterized.expand(
<add> [
<add> ({"end_date_lte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"end_date_gte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"start_date_lte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"start_date_gte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"execution_date_gte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"execution_date_lte": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ]
<add> )
<add> @provide_session
<add> def test_should_raise_400_for_naive_and_bad_datetime(self, payload, expected, session):
<add> self.create_task_instances(session)
<add> response = self.client.post(
<add> "/api/v1/dags/~/dagRuns/~/taskInstances/list",
<add> environ_overrides={'REMOTE_USER': "test"},
<add> json=payload,
<add> )
<add> assert response.status_code == 400
<add> assert response.json['detail'] == expected
<add>
<ide>
<ide> class TestPostClearTaskInstances(TestTaskInstanceEndpoint):
<ide> @parameterized.expand(
<ide> def test_should_raise_403_forbidden(self):
<ide> )
<ide> assert response.status_code == 403
<ide>
<add> @parameterized.expand(
<add> [
<add> ({"end_date": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"end_date": '2020-11-10T12:4po'}, "{'end_date': ['Not a valid datetime.']}"),
<add> ({"start_date": '2020-11-10T12:42:39.442973'}, "Naive datetime is disallowed"),
<add> ({"start_date": '2020-11-10T12:4po'}, "{'start_date': ['Not a valid datetime.']}"),
<add> ]
<add> )
<add> @provide_session
<add> def test_should_raise_400_for_naive_and_bad_datetime(self, payload, expected, session):
<add> task_instances = [
<add> {"execution_date": DEFAULT_DATETIME_1, "state": State.RUNNING},
<add> {
<add> "execution_date": DEFAULT_DATETIME_1 + dt.timedelta(days=1),
<add> "state": State.RUNNING,
<add> },
<add> ]
<add> self.create_task_instances(
<add> session,
<add> dag_id="example_python_operator",
<add> task_instances=task_instances,
<add> update_extras=False,
<add> single_dag_run=False,
<add> )
<add> self.app.dag_bag.sync_to_db() # pylint: disable=no-member
<add> response = self.client.post(
<add> "/api/v1/dags/example_python_operator/clearTaskInstances",
<add> environ_overrides={"REMOTE_USER": "test"},
<add> json=payload,
<add> )
<add> assert response.status_code == 400
<add> self.assertEqual(response.json['detail'], expected)
<add>
<ide>
<ide> class TestPostSetTaskInstanceState(TestTaskInstanceEndpoint):
<ide> @provide_session
<ide> def test_should_raise_404_not_found_task(self):
<ide> },
<ide> )
<ide> assert response.status_code == 404
<add>
<add> @parameterized.expand(
<add> [
<add> (
<add> {
<add> "dry_run": True,
<add> "task_id": "print_the_context",
<add> "execution_date": '2020-11-10T12:42:39.442973',
<add> "include_upstream": True,
<add> "include_downstream": True,
<add> "include_future": True,
<add> "include_past": True,
<add> "new_state": "failed",
<add> },
<add> "Naive datetime is disallowed",
<add> ),
<add> (
<add> {
<add> "dry_run": True,
<add> "task_id": "print_the_context",
<add> "execution_date": '2020-11-10T12:4opfo',
<add> "include_upstream": True,
<add> "include_downstream": True,
<add> "include_future": True,
<add> "include_past": True,
<add> "new_state": "failed",
<add> },
<add> "{'execution_date': ['Not a valid datetime.']}",
<add> ),
<add> ]
<add> )
<add> @provide_session
<add> def test_should_raise_400_for_naive_and_bad_datetime(self, payload, expected, session):
<add> self.create_task_instances(session)
<add> response = self.client.post(
<add> "/api/v1/dags/example_python_operator/updateTaskInstancesState",
<add> environ_overrides={'REMOTE_USER': "test"},
<add> json=payload,
<add> )
<add> assert response.status_code == 400
<add> assert response.json['detail'] == expected
<ide><path>tests/api_connexion/test_parameters.py
<ide> from pendulum.tz.timezone import Timezone
<ide>
<ide> from airflow.api_connexion.exceptions import BadRequest
<del>from airflow.api_connexion.parameters import check_limit, format_datetime, format_parameters
<add>from airflow.api_connexion.parameters import (
<add> check_limit,
<add> format_datetime,
<add> format_parameters,
<add> validate_istimezone,
<add>)
<ide> from airflow.utils import timezone
<ide> from tests.test_utils.config import conf_vars
<ide>
<ide>
<add>class TestValidateIsTimezone(unittest.TestCase):
<add> def setUp(self) -> None:
<add> from datetime import datetime
<add>
<add> self.naive = datetime.now()
<add> self.timezoned = datetime.now(tz=timezone.utc)
<add>
<add> def test_gives_400_for_naive(self):
<add> with self.assertRaises(BadRequest):
<add> validate_istimezone(self.naive)
<add>
<add> def test_timezone_passes(self):
<add> assert validate_istimezone(self.timezoned) is None
<add>
<add>
<ide> class TestDateTimeParser(unittest.TestCase):
<ide> def setUp(self) -> None:
<ide> self.default_time = '2020-06-13T22:44:00+00:00' | 7 |
Ruby | Ruby | improve error reporting | 06fe347de97975dc01e726f87bf07a56a6fb713e | <ide><path>Library/Homebrew/os/mac/ruby_keg.rb
<ide> def change_dylib_id(id, file)
<ide> @require_install_name_tool = true
<ide> puts "Changing dylib ID of #{file}\n from #{file.dylib_id}\n to #{id}" if ARGV.debug?
<ide> MachO::Tools.change_dylib_id(file, id)
<add> rescue MachO::MachOError
<add> onoe <<-EOS.undent
<add> Failed changing dylib ID of #{file}
<add> from #{file.dylib_id}
<add> to #{id}
<add> EOS
<add> raise
<ide> end
<ide>
<ide> def change_install_name(old, new, file)
<ide> @require_install_name_tool = true
<ide> puts "Changing install name in #{file}\n from #{old}\n to #{new}" if ARGV.debug?
<ide> MachO::Tools.change_install_name(file, old, new)
<add> rescue MachO::MachOError
<add> onoe <<-EOS.undent
<add> Failed changing install name in #{file}
<add> from #{old}
<add> to #{new}
<add> EOS
<add> raise
<ide> end
<ide>
<ide> def require_install_name_tool? | 1 |
Mixed | Ruby | fix dependency tracker bug | 4640c346ea6c3a220152ec5749fb479062b273cc | <ide><path>actionview/CHANGELOG.md
<add>* Fixed a dependency tracker bug that caused template dependencies not
<add> count layouts as dependencies for partials.
<add>
<add> *Juho Leinonen*
<add>
<ide> * Extracted `ActionView::Helpers::RecordTagHelper` to external gem
<ide> (`record_tag_helper`) and added removal notices.
<ide>
<ide><path>actionview/lib/action_view/dependency_tracker.rb
<ide> class ERBTracker # :nodoc:
<ide> (?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
<ide> /xm
<ide>
<add> LAYOUT_DEPENDENCY = /\A
<add> (?:\s*\(?\s*) # optional opening paren surrounded by spaces
<add> (?:.*?#{LAYOUT_HASH_KEY}) # check if the line has layout key declaration
<add> (?:#{STRING}|#{VARIABLE_OR_METHOD_CHAIN}) # finally, the dependency name of interest
<add> /xm
<add>
<ide> def self.call(name, template)
<ide> new(name, template).dependencies
<ide> end
<ide> def render_dependencies
<ide> render_calls = source.split(/\brender\b/).drop(1)
<ide>
<ide> render_calls.each do |arguments|
<del> arguments.scan(RENDER_ARGUMENTS) do
<del> add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
<del> add_static_dependency(render_dependencies, Regexp.last_match[:static])
<del> end
<add> add_dependencies(render_dependencies, arguments, LAYOUT_DEPENDENCY)
<add> add_dependencies(render_dependencies, arguments, RENDER_ARGUMENTS)
<ide> end
<ide>
<ide> render_dependencies.uniq
<ide> end
<ide>
<add> def add_dependencies(render_dependencies, arguments, pattern)
<add> arguments.scan(pattern) do
<add> add_dynamic_dependency(render_dependencies, Regexp.last_match[:dynamic])
<add> add_static_dependency(render_dependencies, Regexp.last_match[:static])
<add> end
<add> end
<add>
<ide> def add_dynamic_dependency(dependencies, dependency)
<ide> if dependency
<ide> dependencies << "#{dependency.pluralize}/#{dependency.singularize}"
<ide><path>actionview/test/template/dependency_tracker_test.rb
<ide> def test_dependency_of_erb_template_with_number_in_filename
<ide> end
<ide>
<ide> def test_dependency_of_template_partial_with_layout
<del> skip # FIXME: Needs to be fixed properly, right now we can only match one dependency per line. Need multiple!
<ide> template = FakeTemplate.new("<%# render partial: 'messages/show', layout: 'messages/layout' %>", :erb)
<ide> tracker = make_tracker("multiple/_dependencies", template)
<ide> | 3 |
Text | Text | fix broken link on the upgrading guide | 9bfd45de1530ca55e6f1205d14eb94902c1b27d6 | <ide><path>docs/upgrading.md
<ide> pnpm up next react react-dom eslint-config-next --latest
<ide>
<ide> ## Migrating shared features
<ide>
<del>Next.js 13 introduces a new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals) with new features and conventions. However, upgrading to Next.js 13 does **not** require using the new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals.md#the-app-directory).
<add>Next.js 13 introduces a new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals) with new features and conventions. However, upgrading to Next.js 13 does **not** require using the new [`app` directory](https://beta.nextjs.org/docs/routing/fundamentals#the-app-directory).
<ide>
<ide> You can continue using `pages` with new features that work in both directories, such as the updated [Image component](#image-component), [Link component](#link-component), [Script component](#script-component), and [Font optimization](#font-optimization).
<ide> | 1 |
Ruby | Ruby | add another todo | 5a2ae61e66e517e1688ddcbc7c2ac822d780bbd5 | <ide><path>Library/Homebrew/extend/ENV/shared.rb
<ide> def validate_cc!(formula)
<ide> # selector will be invoked if the formula fails with any version of clang.
<ide> # I think we can safely remove this conditional and always invoke the
<ide> # selector.
<add> # The compiler priority logic in compilers.rb and default_compiler logic in
<add> # os/mac.rb need to be unified somehow.
<ide> if formula.fails_with? Compiler.new(compiler)
<ide> send CompilerSelector.new(formula).compiler
<ide> end | 1 |
Javascript | Javascript | fix reference to $scedelegateprovider | f7c8bcb329eb77b153cd91fcf35c5874a6f9a4b3 | <ide><path>src/ng/sce.js
<ide> function $SceDelegateProvider() {
<ide>
<ide> /**
<ide> * @ngdoc method
<del> * @name sceDelegateProvider#resourceUrlBlacklist
<add> * @name $sceDelegateProvider#resourceUrlBlacklist
<ide> * @function
<ide> *
<ide> * @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value | 1 |
Javascript | Javascript | add todo comment | 5416b92392f38412960f08fc58ea6c75e56efaf4 | <ide><path>src/evaluator.js
<ide> var PartialEvaluator = (function PartialEvaluatorClosure() {
<ide> case 'SA':
<ide> case 'AIS':
<ide> case 'TK':
<add> // TODO implement these operators.
<ide> info('graphic state operator ' + key);
<ide> break;
<ide> default: | 1 |
PHP | PHP | update upgradeshell for app classes | b6040aec5a07f4b3de211cd861077a2dd578c903 | <ide><path>lib/Cake/Console/Command/UpgradeShell.php
<ide> public function locations() {
<ide> }
<ide> }
<ide> }
<add>
<ide> $this->_moveViewFiles();
<add> $this->_moveAppClasses();
<add>
<ide> $sourceDirs = array(
<ide> '.' => array('recursive' => false),
<ide> 'Console',
<ide> protected function _moveViewFiles() {
<ide> }
<ide> }
<ide>
<add>/**
<add> * Move the AppController, and AppModel classes.
<add> *
<add> * @return void
<add> */
<add> protected function _moveAppClasses() {
<add> $files = array(
<add> APP . 'app_controller.php' => APP . 'Controller' . DS . 'AppController.php',
<add> APP . 'controllers' . DS .'app_controller.php' => APP . 'Controller' . DS . 'AppController.php',
<add> APP . 'app_model.php' => APP . 'Model' . DS . 'AppModel.php',
<add> APP . 'models' . DS . 'app_model.php' => APP . 'Model' . DS . 'AppModel.php',
<add> );
<add> foreach ($files as $old => $new) {
<add> if (file_exists($old)) {
<add> $this->out(__d('cake_console', 'Moving %s to %s', $old, $new));
<add>
<add> if ($this->params['dry-run']) {
<add> continue;
<add> }
<add> if ($this->params['git']) {
<add> exec('git mv -f ' . escapeshellarg($old) . ' ' . escapeshellarg($old . '__'));
<add> exec('git mv -f ' . escapeshellarg($old . '__') . ' ' . escapeshellarg($new));
<add> } else {
<add> rename($old, $new);
<add> }
<add> }
<add> }
<add> }
<add>
<ide> /**
<ide> * Move application php files to where they now should be
<ide> * | 1 |
Javascript | Javascript | add test case for checking typeof mgf1hash | 12f5e0f8f84203e5b69c08906a898cea1313019c | <ide><path>test/parallel/test-crypto-keygen.js
<ide> const sec1EncExp = (cipher) => getRegExpForPEM('EC PRIVATE KEY', cipher);
<ide> });
<ide> }
<ide> }
<add>{
<add> // Test RSA-PSS.
<add> common.expectsError(
<add> () => {
<add> generateKeyPair('rsa-pss', {
<add> modulusLength: 512,
<add> saltLength: 16,
<add> hash: 'sha256',
<add> mgf1Hash: undefined
<add> });
<add> },
<add> {
<add> type: TypeError,
<add> code: 'ERR_INVALID_CALLBACK',
<add> message: 'Callback must be a function. Received undefined'
<add> }
<add> );
<add>
<add> for (const mgf1Hash of [null, 0, false, {}, []]) {
<add> common.expectsError(
<add> () => {
<add> generateKeyPair('rsa-pss', {
<add> modulusLength: 512,
<add> saltLength: 16,
<add> hash: 'sha256',
<add> mgf1Hash
<add> });
<add> },
<add> {
<add> type: TypeError,
<add> code: 'ERR_INVALID_OPT_VALUE',
<add> message: `The value "${mgf1Hash}" is invalid for option "mgf1Hash"`
<add> }
<add> );
<add> }
<add>} | 1 |
Javascript | Javascript | add a test for recursive context | 4ba0eb91586c1f9800ced9c73b94568ff906ddb6 | <ide><path>src/renderers/shared/fiber/__tests__/ReactIncremental-test.js
<ide> describe('ReactIncremental', () => {
<ide> 'ShowBoth {"locale":"en"}',
<ide> ]);
<ide> });
<add>
<add> it('does not leak own context into context provider', () => {
<add> var ops = [];
<add> class Recurse extends React.Component {
<add> static contextTypes = {
<add> n: React.PropTypes.number,
<add> };
<add> static childContextTypes = {
<add> n: React.PropTypes.number,
<add> };
<add> getChildContext() {
<add> return {n: (this.context.n || 3) - 1};
<add> }
<add> render() {
<add> ops.push('Recurse ' + JSON.stringify(this.context));
<add> if (this.context.n === 0) {
<add> return null;
<add> }
<add> return <Recurse />;
<add> }
<add> }
<add>
<add> ReactNoop.render(<Recurse />);
<add> ReactNoop.flush();
<add> expect(ops).toEqual([
<add> 'Recurse {}',
<add> 'Recurse {"n":2}',
<add> 'Recurse {"n":1}',
<add> 'Recurse {"n":0}',
<add> ]);
<add> });
<ide> }); | 1 |
Ruby | Ruby | fix minor typo in test name | 17b846004d63f94b09b1a86986d9bfb3d64dda2a | <ide><path>activerecord/test/cases/attributes_test.rb
<ide> def deserialize(*)
<ide> end
<ide>
<ide> if current_adapter?(:PostgreSQLAdapter)
<del> test "arrays types can be specified" do
<add> test "array types can be specified" do
<ide> klass = Class.new(OverloadedType) do
<ide> attribute :my_array, :string, limit: 50, array: true
<ide> attribute :my_int_array, :integer, array: true | 1 |
Java | Java | fix string equality | 5b1341f4b572277c33a8ebf7ade1bfdb5de03437 | <ide><path>spring-expression/src/main/java/org/springframework/expression/spel/ast/Indexer.java
<ide> *
<ide> * @author Andy Clement
<ide> * @author Phillip Webb
<add> * @author Stephane Nicoll
<ide> * @since 3.0
<ide> */
<ide> // TODO support multidimensional arrays
<ide> public void generateCode(MethodVisitor mv, CodeFlow codeflow) {
<ide> }
<ide>
<ide> if (this.indexedType == IndexedType.array) {
<del> if (exitTypeDescriptor == "I") {
<add> if ("I".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[I");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> codeflow.exitCompilationScope();
<ide> mv.visitInsn(IALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "D") {
<add> else if ("D".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[D");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> mv.visitInsn(DALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "J") {
<add> else if ("J".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[J");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> codeflow.exitCompilationScope();
<ide> mv.visitInsn(LALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "F") {
<add> else if ("F".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[F");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> codeflow.exitCompilationScope();
<ide> mv.visitInsn(FALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "S") {
<add> else if ("S".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[S");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> codeflow.exitCompilationScope();
<ide> mv.visitInsn(SALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "B") {
<add> else if ("B".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[B");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope();
<ide> index.generateCode(mv, codeflow);
<ide> codeflow.exitCompilationScope();
<ide> mv.visitInsn(BALOAD);
<ide> }
<del> else if (exitTypeDescriptor == "C") {
<add> else if ("C".equals(exitTypeDescriptor)) {
<ide> mv.visitTypeInsn(CHECKCAST,"[C");
<ide> SpelNodeImpl index = this.children[0];
<ide> codeflow.enterCompilationScope(); | 1 |
Python | Python | create sol5.py (#425) | dd62f1b8023817ae5637812b3fa9acd815e4ef38 | <ide><path>Project Euler/Problem 01/sol5.py
<add>a=3
<add>result=0
<add>while a=<1000:
<add> if(a%3==0 and a%5==0):
<add> result+=a
<add> elif(a%15==0):
<add> result-=a
<add>print(result) | 1 |
Python | Python | initialize low data warning for debug-data parser | 3906785b496e5fa5f735ba5a4a9238623b4d0b63 | <ide><path>spacy/cli/debug_data.py
<ide> def debug_data(
<ide> )
<ide>
<ide> if "parser" in pipeline:
<add> has_low_data_warning = False
<ide> msg.divider("Dependency Parsing")
<ide>
<ide> # profile sentence length | 1 |
Javascript | Javascript | simplify "defaultdisplay" module | c62486fb4cb18fdb7dc5807231c964ed82ee6482 | <ide><path>src/css/defaultDisplay.js
<ide> function defaultDisplay( nodeName ) {
<ide> .appendTo( doc.documentElement );
<ide>
<ide> // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
<del> doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
<add> doc = iframe[ 0 ].contentDocument;
<ide>
<ide> // Support: IE
<ide> doc.write(); | 1 |
Javascript | Javascript | fix typo in app / hello.js template | 503fc854886eea6ae5c99b8efcf256c83687acf3 | <ide><path>packages/create-next-app/templates/app/js/pages/api/hello.js
<del>// Next.js API route support: https://nextjs.org/docs/api-routes/introduction}
<add>// Next.js API route support: https://nextjs.org/docs/api-routes/introduction
<ide>
<ide> export default function handler(req, res) {
<ide> res.status(200).json({ name: 'John Doe' }) | 1 |
Javascript | Javascript | prevent 403 reporting | 4300ce44dbfd29bffd1e8a25d5e623bb16d91b50 | <ide><path>api-server/server/middlewares/sentry-error-handler.js
<ide> export default function sentryErrorHandler() {
<ide> shouldHandleError(err) {
<ide> // CSRF errors have status 403, consider ignoring them once csurf is
<ide> // no longer rejecting people incorrectly.
<del> return (
<del> !isHandledError(err) &&
<del> (!err.status || err.status === 403 || err.status >= 500)
<del> );
<add> return !isHandledError(err) && (!err.status || err.status >= 500);
<ide> }
<ide> });
<ide> } | 1 |
Text | Text | remove usestate import | 125103a9f72e81aa01e30d18618bd7f2d0cef734 | <ide><path>docs/tutorials/quick-start.md
<ide> export default configureStore({
<ide> Now we can use the React-Redux hooks to let React components interact with the Redux store. We can read data from the store with `useSelector`, and dispatch actions using `useDispatch`. Create a `src/features/counter/Counter.js` file with a `<Counter>` component inside, then import that component into `App.js` and render it inside of `<App>`.
<ide>
<ide> ```jsx title="features/counter/Counter.js"
<del>import React, { useState } from 'react'
<add>import React from 'react'
<ide> import { useSelector, useDispatch } from 'react-redux'
<ide> import { decrement, increment } from './counterSlice'
<ide> import styles from './Counter.module.css'
<ide><path>docs/tutorials/typescript.md
<ide> const initialState = {
<ide> In component files, import the pre-typed hooks instead of the standard hooks from React-Redux.
<ide>
<ide> ```tsx title="features/counter/Counter.tsx"
<del>import React, { useState } from 'react'
<add>import React from 'react'
<ide>
<ide> // highlight-next-line
<ide> import { useAppSelector, useAppDispatch } from 'app/hooks' | 2 |
Javascript | Javascript | handle jquery objects of length 0 | 773efd0812097a89944c889c595485a5744326f6 | <ide><path>src/Angular.js
<ide> var
<ide> msie = document.documentMode;
<ide>
<ide>
<del>function isNodeList(obj) {
<del> return typeof obj.length == 'number' &&
<del> typeof obj.item == 'function';
<del>}
<del>
<ide> /**
<ide> * @private
<ide> * @param {*} obj
<ide> function isArrayLike(obj) {
<ide> // `null`, `undefined` and `window` are not array-like
<ide> if (obj == null || isWindow(obj)) return false;
<ide>
<del> // arrays and strings are array like
<del> if (isArray(obj) || isString(obj)) return true;
<add> // arrays, strings and jQuery/jqLite objects are array like
<add> // * jqLite is either the jQuery or jqLite constructor function
<add> // * we have to check the existance of jqLite first as this method is called
<add> // via the forEach method when constructing the jqLite object in the first place
<add> if (isArray(obj) || isString(obj) || (jqLite && obj instanceof jqLite)) return true;
<ide>
<ide> // Support: iOS 8.2 (not reproducible in simulator)
<ide> // "length" in obj used to prevent JIT error (gh-11508)
<ide> var length = "length" in Object(obj) && obj.length;
<ide>
<del> // node lists and objects with suitable length characteristics are array-like
<del> return (isNumber(length) && length >= 0 && (length - 1) in obj) || isNodeList(obj);
<add> // NodeList objects (with `item` method) and
<add> // other objects with suitable length characteristics are array-like
<add> return isNumber(length) &&
<add> (length >= 0 && (length - 1) in obj || typeof obj.item == 'function');
<ide> }
<ide>
<ide> /**
<ide><path>test/AngularSpec.js
<ide> describe('angular', function() {
<ide>
<ide> forEach(jqObject, function(value, key) { log.push(key + ':' + value.innerHTML); });
<ide> expect(log).toEqual(['0:s1', '1:s2']);
<add>
<add> log = [];
<add> jqObject = jqLite("<pane></pane>");
<add> forEach(jqObject.children(), function(value, key) { log.push(key + ':' + value.innerHTML); });
<add> expect(log).toEqual([]);
<ide> });
<ide>
<ide> | 2 |
Python | Python | fix an english typo | af4ad9f368ac14a2745a7440b8ed8b25b6286245 | <ide><path>numpy/ctypeslib.py
<ide> class _ndptr(_ndptr_base):
<ide>
<ide> def _check_retval_(self):
<ide> """This method is called when this class is used as the .restype
<del> asttribute for a shared-library function. It constructs a numpy
<add> attribute for a shared-library function. It constructs a numpy
<ide> array from a void pointer."""
<ide> return array(self)
<ide> | 1 |
Python | Python | add epsilon to the denominator, not to var | 017c93c07dff11a55691dc1a0ddf0f18c91e5267 | <ide><path>keras/backend/cntk_backend.py
<ide> def batch_normalization(x, mean, var, beta, gamma, epsilon=1e-3):
<ide> elif ndim(beta) == ndim(x) and shape(beta)[0] == 1:
<ide> beta = _reshape_dummy_dim(beta, [0])
<ide>
<del> return gamma * ((x - mean) / C.sqrt(var + epsilon)) + beta
<add> return (x - mean) / (C.sqrt(var) + epsilon) * gamma + beta
<ide>
<ide>
<ide> def concatenate(tensors, axis=-1): | 1 |
Ruby | Ruby | raise a better exception for renaming long indexes | 3e92806357543cdbabad813884a591fca69193c2 | <ide><path>activerecord/lib/active_record/connection_adapters/abstract/schema_statements.rb
<ide> def remove_index!(table_name, index_name) #:nodoc:
<ide> # rename_index :people, 'index_people_on_last_name', 'index_users_on_last_name'
<ide> #
<ide> def rename_index(table_name, old_name, new_name)
<add> if new_name.length > allowed_index_name_length
<add> raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
<add> end
<ide> # this is a naive implementation; some DBs may support this more efficiently (Postgres, for instance)
<ide> old_index_def = indexes(table_name).detect { |i| i.name == old_name }
<ide> return unless old_index_def
<ide><path>activerecord/lib/active_record/connection_adapters/postgresql/schema_statements.rb
<ide> def remove_index!(table_name, index_name) #:nodoc:
<ide> end
<ide>
<ide> def rename_index(table_name, old_name, new_name)
<add> if new_name.length > allowed_index_name_length
<add> raise ArgumentError, "Index name '#{new_name}' on table '#{table_name}' is too long; the limit is #{allowed_index_name_length} characters"
<add> end
<ide> execute "ALTER INDEX #{quote_column_name(old_name)} RENAME TO #{quote_table_name(new_name)}"
<ide> end
<ide>
<ide><path>activerecord/test/cases/migration/index_test.rb
<ide> def test_rename_index
<ide> assert connection.index_name_exists?(table_name, 'new_idx', true)
<ide> end
<ide>
<add> def test_rename_index_too_long
<add> too_long_index_name = good_index_name + 'x'
<add> # keep the names short to make Oracle and similar behave
<add> connection.add_index(table_name, [:foo], :name => 'old_idx')
<add> e = assert_raises(ArgumentError) {
<add> connection.rename_index(table_name, 'old_idx', too_long_index_name)
<add> }
<add> assert_match(/too long; the limit is #{connection.allowed_index_name_length} characters/, e.message)
<add>
<add> # if the adapter doesn't support the indexes call, pick defaults that let the test pass
<add> assert connection.index_name_exists?(table_name, 'old_idx', false)
<add> end
<add>
<add>
<ide> def test_double_add_index
<ide> connection.add_index(table_name, [:foo], :name => 'some_idx')
<ide> assert_raises(ArgumentError) { | 3 |
Go | Go | use ms_private instead of ms_slave" | bd263f5b15b51747e3429179fef7fcb425ccbe4a | <ide><path>pkg/libcontainer/nsinit/mount.go
<ide> const defaultMountFlags = syscall.MS_NOEXEC | syscall.MS_NOSUID | syscall.MS_NOD
<ide> // is no longer in use, the mounts will be removed automatically
<ide> func setupNewMountNamespace(rootfs, console string, readonly bool) error {
<ide> // mount as slave so that the new mounts do not propagate to the host
<del> if err := system.Mount("", "/", "", syscall.MS_PRIVATE|syscall.MS_REC, ""); err != nil {
<add> if err := system.Mount("", "/", "", syscall.MS_SLAVE|syscall.MS_REC, ""); err != nil {
<ide> return fmt.Errorf("mounting / as slave %s", err)
<ide> }
<ide> if err := system.Mount(rootfs, rootfs, "bind", syscall.MS_BIND|syscall.MS_REC, ""); err != nil { | 1 |
Ruby | Ruby | convert array extension modules to class reopens | 83fd1ae122cf1ee4ea2c52e0bd963462163516ca | <ide><path>activesupport/lib/active_support/core_ext/array.rb
<del>require 'active_support/core_ext/util'
<ide> require 'active_support/core_ext/array/wrap'
<del>ActiveSupport.core_ext Array, %w(access conversions extract_options grouping random_access)
<add>require 'active_support/core_ext/array/access'
<add>require 'active_support/core_ext/array/conversions'
<add>require 'active_support/core_ext/array/extract_options'
<add>require 'active_support/core_ext/array/grouping'
<add>require 'active_support/core_ext/array/random_access'
<ide><path>activesupport/lib/active_support/core_ext/array/access.rb
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module Array #:nodoc:
<del> # Makes it easier to access parts of an array.
<del> module Access
<del> # Returns the tail of the array from +position+.
<del> #
<del> # %w( a b c d ).from(0) # => %w( a b c d )
<del> # %w( a b c d ).from(2) # => %w( c d )
<del> # %w( a b c d ).from(10) # => nil
<del> # %w().from(0) # => nil
<del> def from(position)
<del> self[position..-1]
<del> end
<del>
<del> # Returns the beginning of the array up to +position+.
<del> #
<del> # %w( a b c d ).to(0) # => %w( a )
<del> # %w( a b c d ).to(2) # => %w( a b c )
<del> # %w( a b c d ).to(10) # => %w( a b c d )
<del> # %w().to(0) # => %w()
<del> def to(position)
<del> self[0..position]
<del> end
<add>class Array
<add> # Returns the tail of the array from +position+.
<add> #
<add> # %w( a b c d ).from(0) # => %w( a b c d )
<add> # %w( a b c d ).from(2) # => %w( c d )
<add> # %w( a b c d ).from(10) # => nil
<add> # %w().from(0) # => nil
<add> def from(position)
<add> self[position..-1]
<add> end
<ide>
<del> # Equal to <tt>self[1]</tt>.
<del> def second
<del> self[1]
<del> end
<add> # Returns the beginning of the array up to +position+.
<add> #
<add> # %w( a b c d ).to(0) # => %w( a )
<add> # %w( a b c d ).to(2) # => %w( a b c )
<add> # %w( a b c d ).to(10) # => %w( a b c d )
<add> # %w().to(0) # => %w()
<add> def to(position)
<add> self[0..position]
<add> end
<ide>
<del> # Equal to <tt>self[2]</tt>.
<del> def third
<del> self[2]
<del> end
<add> # Equal to <tt>self[1]</tt>.
<add> def second
<add> self[1]
<add> end
<ide>
<del> # Equal to <tt>self[3]</tt>.
<del> def fourth
<del> self[3]
<del> end
<add> # Equal to <tt>self[2]</tt>.
<add> def third
<add> self[2]
<add> end
<ide>
<del> # Equal to <tt>self[4]</tt>.
<del> def fifth
<del> self[4]
<del> end
<add> # Equal to <tt>self[3]</tt>.
<add> def fourth
<add> self[3]
<add> end
<add>
<add> # Equal to <tt>self[4]</tt>.
<add> def fifth
<add> self[4]
<add> end
<ide>
<del> # Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
<del> def forty_two
<del> self[41]
<del> end
<del> end
<del> end
<add> # Equal to <tt>self[41]</tt>. Also known as accessing "the reddit".
<add> def forty_two
<add> self[41]
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/array/conversions.rb
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module Array #:nodoc:
<del> module Conversions
<del> # Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
<del> # * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", ")
<del> # * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ")
<del> # * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ")
<del> def to_sentence(options = {})
<del> default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale])
<del> default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale])
<del> default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
<add>class Array
<add> # Converts the array to a comma-separated sentence where the last element is joined by the connector word. Options:
<add> # * <tt>:words_connector</tt> - The sign or word used to join the elements in arrays with two or more elements (default: ", ")
<add> # * <tt>:two_words_connector</tt> - The sign or word used to join the elements in arrays with two elements (default: " and ")
<add> # * <tt>:last_word_connector</tt> - The sign or word used to join the last element in arrays with three or more elements (default: ", and ")
<add> def to_sentence(options = {})
<add> default_words_connector = I18n.translate(:'support.array.words_connector', :locale => options[:locale])
<add> default_two_words_connector = I18n.translate(:'support.array.two_words_connector', :locale => options[:locale])
<add> default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
<ide>
<del> # Try to emulate to_senteces previous to 2.3
<del> if options.has_key?(:connector) || options.has_key?(:skip_last_comma)
<del> ::ActiveSupport::Deprecation.warn(":connector has been deprecated. Use :words_connector instead", caller) if options.has_key? :connector
<del> ::ActiveSupport::Deprecation.warn(":skip_last_comma has been deprecated. Use :last_word_connector instead", caller) if options.has_key? :skip_last_comma
<add> # Try to emulate to_senteces previous to 2.3
<add> if options.has_key?(:connector) || options.has_key?(:skip_last_comma)
<add> ::ActiveSupport::Deprecation.warn(":connector has been deprecated. Use :words_connector instead", caller) if options.has_key? :connector
<add> ::ActiveSupport::Deprecation.warn(":skip_last_comma has been deprecated. Use :last_word_connector instead", caller) if options.has_key? :skip_last_comma
<ide>
<del> skip_last_comma = options.delete :skip_last_comma
<del> if connector = options.delete(:connector)
<del> options[:last_word_connector] ||= skip_last_comma ? connector : ", #{connector}"
<del> else
<del> options[:last_word_connector] ||= skip_last_comma ? default_two_words_connector : default_last_word_connector
<del> end
<del> end
<del>
<del> options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
<del> options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector
<del>
<del> case length
<del> when 0
<del> ""
<del> when 1
<del> self[0].to_s
<del> when 2
<del> "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
<del> else
<del> "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
<del> end
<del> end
<del>
<add> skip_last_comma = options.delete :skip_last_comma
<add> if connector = options.delete(:connector)
<add> options[:last_word_connector] ||= skip_last_comma ? connector : ", #{connector}"
<add> else
<add> options[:last_word_connector] ||= skip_last_comma ? default_two_words_connector : default_last_word_connector
<add> end
<add> end
<ide>
<del> # Calls <tt>to_param</tt> on all its elements and joins the result with
<del> # slashes. This is used by <tt>url_for</tt> in Action Pack.
<del> def to_param
<del> collect { |e| e.to_param }.join '/'
<del> end
<add> options.assert_valid_keys(:words_connector, :two_words_connector, :last_word_connector, :locale)
<add> options.reverse_merge! :words_connector => default_words_connector, :two_words_connector => default_two_words_connector, :last_word_connector => default_last_word_connector
<ide>
<del> # Converts an array into a string suitable for use as a URL query string,
<del> # using the given +key+ as the param name.
<del> #
<del> # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
<del> def to_query(key)
<del> prefix = "#{key}[]"
<del> collect { |value| value.to_query(prefix) }.join '&'
<del> end
<add> case length
<add> when 0
<add> ""
<add> when 1
<add> self[0].to_s
<add> when 2
<add> "#{self[0]}#{options[:two_words_connector]}#{self[1]}"
<add> else
<add> "#{self[0...-1].join(options[:words_connector])}#{options[:last_word_connector]}#{self[-1]}"
<add> end
<add> end
<ide>
<del> def self.included(base) #:nodoc:
<del> base.class_eval do
<del> alias_method :to_default_s, :to_s
<del> alias_method :to_s, :to_formatted_s
<del> end
<del> end
<ide>
<del> # Converts a collection of elements into a formatted string by calling
<del> # <tt>to_s</tt> on all elements and joining them:
<del> #
<del> # Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
<del> #
<del> # Adding in the <tt>:db</tt> argument as the format yields a prettier
<del> # output:
<del> #
<del> # Blog.find(:all).to_formatted_s(:db) # => "First Post,Second Post,Third Post"
<del> def to_formatted_s(format = :default)
<del> case format
<del> when :db
<del> if respond_to?(:empty?) && self.empty?
<del> "null"
<del> else
<del> collect { |element| element.id }.join(",")
<del> end
<del> else
<del> to_default_s
<del> end
<del> end
<add> # Calls <tt>to_param</tt> on all its elements and joins the result with
<add> # slashes. This is used by <tt>url_for</tt> in Action Pack.
<add> def to_param
<add> collect { |e| e.to_param }.join '/'
<add> end
<ide>
<del> # Returns a string that represents this array in XML by sending +to_xml+
<del> # to each element. Active Record collections delegate their representation
<del> # in XML to this method.
<del> #
<del> # All elements are expected to respond to +to_xml+, if any of them does
<del> # not an exception is raised.
<del> #
<del> # The root node reflects the class name of the first element in plural
<del> # if all elements belong to the same type and that's not Hash:
<del> #
<del> # customer.projects.to_xml
<del> #
<del> # <?xml version="1.0" encoding="UTF-8"?>
<del> # <projects type="array">
<del> # <project>
<del> # <amount type="decimal">20000.0</amount>
<del> # <customer-id type="integer">1567</customer-id>
<del> # <deal-date type="date">2008-04-09</deal-date>
<del> # ...
<del> # </project>
<del> # <project>
<del> # <amount type="decimal">57230.0</amount>
<del> # <customer-id type="integer">1567</customer-id>
<del> # <deal-date type="date">2008-04-15</deal-date>
<del> # ...
<del> # </project>
<del> # </projects>
<del> #
<del> # Otherwise the root element is "records":
<del> #
<del> # [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
<del> #
<del> # <?xml version="1.0" encoding="UTF-8"?>
<del> # <records type="array">
<del> # <record>
<del> # <bar type="integer">2</bar>
<del> # <foo type="integer">1</foo>
<del> # </record>
<del> # <record>
<del> # <baz type="integer">3</baz>
<del> # </record>
<del> # </records>
<del> #
<del> # If the collection is empty the root element is "nil-classes" by default:
<del> #
<del> # [].to_xml
<del> #
<del> # <?xml version="1.0" encoding="UTF-8"?>
<del> # <nil-classes type="array"/>
<del> #
<del> # To ensure a meaningful root element use the <tt>:root</tt> option:
<del> #
<del> # customer_with_no_projects.projects.to_xml(:root => "projects")
<del> #
<del> # <?xml version="1.0" encoding="UTF-8"?>
<del> # <projects type="array"/>
<del> #
<del> # By default root children have as node name the one of the root
<del> # singularized. You can change it with the <tt>:children</tt> option.
<del> #
<del> # The +options+ hash is passed downwards:
<del> #
<del> # Message.all.to_xml(:skip_types => true)
<del> #
<del> # <?xml version="1.0" encoding="UTF-8"?>
<del> # <messages>
<del> # <message>
<del> # <created-at>2008-03-07T09:58:18+01:00</created-at>
<del> # <id>1</id>
<del> # <name>1</name>
<del> # <updated-at>2008-03-07T09:58:18+01:00</updated-at>
<del> # <user-id>1</user-id>
<del> # </message>
<del> # </messages>
<del> #
<del> def to_xml(options = {})
<del> raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml }
<del> require 'builder' unless defined?(Builder)
<add> # Converts an array into a string suitable for use as a URL query string,
<add> # using the given +key+ as the param name.
<add> #
<add> # ['Rails', 'coding'].to_query('hobbies') # => "hobbies%5B%5D=Rails&hobbies%5B%5D=coding"
<add> def to_query(key)
<add> prefix = "#{key}[]"
<add> collect { |value| value.to_query(prefix) }.join '&'
<add> end
<ide>
<del> options[:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize : "records"
<del> options[:children] ||= options[:root].singularize
<del> options[:indent] ||= 2
<del> options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
<add> # Converts a collection of elements into a formatted string by calling
<add> # <tt>to_s</tt> on all elements and joining them:
<add> #
<add> # Blog.find(:all).to_formatted_s # => "First PostSecond PostThird Post"
<add> #
<add> # Adding in the <tt>:db</tt> argument as the format yields a prettier
<add> # output:
<add> #
<add> # Blog.find(:all).to_formatted_s(:db) # => "First Post,Second Post,Third Post"
<add> def to_formatted_s(format = :default)
<add> case format
<add> when :db
<add> if respond_to?(:empty?) && self.empty?
<add> "null"
<add> else
<add> collect { |element| element.id }.join(",")
<add> end
<add> else
<add> to_default_s
<add> end
<add> end
<add> alias_method :to_default_s, :to_s
<add> alias_method :to_s, :to_formatted_s
<ide>
<del> root = options.delete(:root).to_s
<del> children = options.delete(:children)
<add> # Returns a string that represents this array in XML by sending +to_xml+
<add> # to each element. Active Record collections delegate their representation
<add> # in XML to this method.
<add> #
<add> # All elements are expected to respond to +to_xml+, if any of them does
<add> # not an exception is raised.
<add> #
<add> # The root node reflects the class name of the first element in plural
<add> # if all elements belong to the same type and that's not Hash:
<add> #
<add> # customer.projects.to_xml
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <projects type="array">
<add> # <project>
<add> # <amount type="decimal">20000.0</amount>
<add> # <customer-id type="integer">1567</customer-id>
<add> # <deal-date type="date">2008-04-09</deal-date>
<add> # ...
<add> # </project>
<add> # <project>
<add> # <amount type="decimal">57230.0</amount>
<add> # <customer-id type="integer">1567</customer-id>
<add> # <deal-date type="date">2008-04-15</deal-date>
<add> # ...
<add> # </project>
<add> # </projects>
<add> #
<add> # Otherwise the root element is "records":
<add> #
<add> # [{:foo => 1, :bar => 2}, {:baz => 3}].to_xml
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <records type="array">
<add> # <record>
<add> # <bar type="integer">2</bar>
<add> # <foo type="integer">1</foo>
<add> # </record>
<add> # <record>
<add> # <baz type="integer">3</baz>
<add> # </record>
<add> # </records>
<add> #
<add> # If the collection is empty the root element is "nil-classes" by default:
<add> #
<add> # [].to_xml
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <nil-classes type="array"/>
<add> #
<add> # To ensure a meaningful root element use the <tt>:root</tt> option:
<add> #
<add> # customer_with_no_projects.projects.to_xml(:root => "projects")
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <projects type="array"/>
<add> #
<add> # By default root children have as node name the one of the root
<add> # singularized. You can change it with the <tt>:children</tt> option.
<add> #
<add> # The +options+ hash is passed downwards:
<add> #
<add> # Message.all.to_xml(:skip_types => true)
<add> #
<add> # <?xml version="1.0" encoding="UTF-8"?>
<add> # <messages>
<add> # <message>
<add> # <created-at>2008-03-07T09:58:18+01:00</created-at>
<add> # <id>1</id>
<add> # <name>1</name>
<add> # <updated-at>2008-03-07T09:58:18+01:00</updated-at>
<add> # <user-id>1</user-id>
<add> # </message>
<add> # </messages>
<add> #
<add> def to_xml(options = {})
<add> raise "Not all elements respond to to_xml" unless all? { |e| e.respond_to? :to_xml }
<add> require 'builder' unless defined?(Builder)
<ide>
<del> if !options.has_key?(:dasherize) || options[:dasherize]
<del> root = root.dasherize
<del> end
<add> options[:root] ||= all? { |e| e.is_a?(first.class) && first.class.to_s != "Hash" } ? first.class.to_s.underscore.pluralize : "records"
<add> options[:children] ||= options[:root].singularize
<add> options[:indent] ||= 2
<add> options[:builder] ||= Builder::XmlMarkup.new(:indent => options[:indent])
<ide>
<del> options[:builder].instruct! unless options.delete(:skip_instruct)
<add> root = options.delete(:root).to_s
<add> children = options.delete(:children)
<ide>
<del> opts = options.merge({ :root => children })
<add> if !options.has_key?(:dasherize) || options[:dasherize]
<add> root = root.dasherize
<add> end
<ide>
<del> xml = options[:builder]
<del> if empty?
<del> xml.tag!(root, options[:skip_types] ? {} : {:type => "array"})
<del> else
<del> xml.tag!(root, options[:skip_types] ? {} : {:type => "array"}) {
<del> yield xml if block_given?
<del> each { |e| e.to_xml(opts.merge({ :skip_instruct => true })) }
<del> }
<del> end
<del> end
<add> options[:builder].instruct! unless options.delete(:skip_instruct)
<ide>
<del> end
<add> opts = options.merge({ :root => children })
<add>
<add> xml = options[:builder]
<add> if empty?
<add> xml.tag!(root, options[:skip_types] ? {} : {:type => "array"})
<add> else
<add> xml.tag!(root, options[:skip_types] ? {} : {:type => "array"}) {
<add> yield xml if block_given?
<add> each { |e| e.to_xml(opts.merge({ :skip_instruct => true })) }
<add> }
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/array/extract_options.rb
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module Array #:nodoc:
<del> module ExtractOptions
<del> # Extracts options from a set of arguments. Removes and returns the last
<del> # element in the array if it's a hash, otherwise returns a blank hash.
<del> #
<del> # def options(*args)
<del> # args.extract_options!
<del> # end
<del> #
<del> # options(1, 2) # => {}
<del> # options(1, 2, :a => :b) # => {:a=>:b}
<del> def extract_options!
<del> last.is_a?(::Hash) ? pop : {}
<del> end
<del> end
<del> end
<add>class Array
<add> # Extracts options from a set of arguments. Removes and returns the last
<add> # element in the array if it's a hash, otherwise returns a blank hash.
<add> #
<add> # def options(*args)
<add> # args.extract_options!
<add> # end
<add> #
<add> # options(1, 2) # => {}
<add> # options(1, 2, :a => :b) # => {:a=>:b}
<add> def extract_options!
<add> last.is_a?(::Hash) ? pop : {}
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/array/grouping.rb
<ide> require 'enumerator'
<ide>
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module Array #:nodoc:
<del> module Grouping
<del> # Splits or iterates over the array in groups of size +number+,
<del> # padding any remaining slots with +fill_with+ unless it is +false+.
<del> #
<del> # %w(1 2 3 4 5 6 7).in_groups_of(3) {|group| p group}
<del> # ["1", "2", "3"]
<del> # ["4", "5", "6"]
<del> # ["7", nil, nil]
<del> #
<del> # %w(1 2 3).in_groups_of(2, ' ') {|group| p group}
<del> # ["1", "2"]
<del> # ["3", " "]
<del> #
<del> # %w(1 2 3).in_groups_of(2, false) {|group| p group}
<del> # ["1", "2"]
<del> # ["3"]
<del> def in_groups_of(number, fill_with = nil)
<del> if fill_with == false
<del> collection = self
<del> else
<del> # size % number gives how many extra we have;
<del> # subtracting from number gives how many to add;
<del> # modulo number ensures we don't add group of just fill.
<del> padding = (number - size % number) % number
<del> collection = dup.concat([fill_with] * padding)
<del> end
<del>
<del> if block_given?
<del> collection.each_slice(number) { |slice| yield(slice) }
<del> else
<del> returning [] do |groups|
<del> collection.each_slice(number) { |group| groups << group }
<del> end
<del> end
<del> end
<add>class Array
<add> # Splits or iterates over the array in groups of size +number+,
<add> # padding any remaining slots with +fill_with+ unless it is +false+.
<add> #
<add> # %w(1 2 3 4 5 6 7).in_groups_of(3) {|group| p group}
<add> # ["1", "2", "3"]
<add> # ["4", "5", "6"]
<add> # ["7", nil, nil]
<add> #
<add> # %w(1 2 3).in_groups_of(2, ' ') {|group| p group}
<add> # ["1", "2"]
<add> # ["3", " "]
<add> #
<add> # %w(1 2 3).in_groups_of(2, false) {|group| p group}
<add> # ["1", "2"]
<add> # ["3"]
<add> def in_groups_of(number, fill_with = nil)
<add> if fill_with == false
<add> collection = self
<add> else
<add> # size % number gives how many extra we have;
<add> # subtracting from number gives how many to add;
<add> # modulo number ensures we don't add group of just fill.
<add> padding = (number - size % number) % number
<add> collection = dup.concat([fill_with] * padding)
<add> end
<ide>
<del> # Splits or iterates over the array in +number+ of groups, padding any
<del> # remaining slots with +fill_with+ unless it is +false+.
<del> #
<del> # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
<del> # ["1", "2", "3", "4"]
<del> # ["5", "6", "7", nil]
<del> # ["8", "9", "10", nil]
<del> #
<del> # %w(1 2 3 4 5 6 7).in_groups(3, ' ') {|group| p group}
<del> # ["1", "2", "3"]
<del> # ["4", "5", " "]
<del> # ["6", "7", " "]
<del> #
<del> # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
<del> # ["1", "2", "3"]
<del> # ["4", "5"]
<del> # ["6", "7"]
<del> def in_groups(number, fill_with = nil)
<del> # size / number gives minor group size;
<del> # size % number gives how many objects need extra accomodation;
<del> # each group hold either division or division + 1 items.
<del> division = size / number
<del> modulo = size % number
<add> if block_given?
<add> collection.each_slice(number) { |slice| yield(slice) }
<add> else
<add> groups = []
<add> collection.each_slice(number) { |group| groups << group }
<add> groups
<add> end
<add> end
<ide>
<del> # create a new array avoiding dup
<del> groups = []
<del> start = 0
<add> # Splits or iterates over the array in +number+ of groups, padding any
<add> # remaining slots with +fill_with+ unless it is +false+.
<add> #
<add> # %w(1 2 3 4 5 6 7 8 9 10).in_groups(3) {|group| p group}
<add> # ["1", "2", "3", "4"]
<add> # ["5", "6", "7", nil]
<add> # ["8", "9", "10", nil]
<add> #
<add> # %w(1 2 3 4 5 6 7).in_groups(3, ' ') {|group| p group}
<add> # ["1", "2", "3"]
<add> # ["4", "5", " "]
<add> # ["6", "7", " "]
<add> #
<add> # %w(1 2 3 4 5 6 7).in_groups(3, false) {|group| p group}
<add> # ["1", "2", "3"]
<add> # ["4", "5"]
<add> # ["6", "7"]
<add> def in_groups(number, fill_with = nil)
<add> # size / number gives minor group size;
<add> # size % number gives how many objects need extra accomodation;
<add> # each group hold either division or division + 1 items.
<add> division = size / number
<add> modulo = size % number
<ide>
<del> number.times do |index|
<del> length = division + (modulo > 0 && modulo > index ? 1 : 0)
<del> padding = fill_with != false &&
<del> modulo > 0 && length == division ? 1 : 0
<del> groups << slice(start, length).concat([fill_with] * padding)
<del> start += length
<del> end
<add> # create a new array avoiding dup
<add> groups = []
<add> start = 0
<ide>
<del> if block_given?
<del> groups.each{|g| yield(g) }
<del> else
<del> groups
<del> end
<del> end
<add> number.times do |index|
<add> length = division + (modulo > 0 && modulo > index ? 1 : 0)
<add> padding = fill_with != false &&
<add> modulo > 0 && length == division ? 1 : 0
<add> groups << slice(start, length).concat([fill_with] * padding)
<add> start += length
<add> end
<ide>
<del> # Divides the array into one or more subarrays based on a delimiting +value+
<del> # or the result of an optional block.
<del> #
<del> # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
<del> # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
<del> def split(value = nil)
<del> using_block = block_given?
<add> if block_given?
<add> groups.each { |g| yield(g) }
<add> else
<add> groups
<add> end
<add> end
<ide>
<del> inject([[]]) do |results, element|
<del> if (using_block && yield(element)) || (value == element)
<del> results << []
<del> else
<del> results.last << element
<del> end
<add> # Divides the array into one or more subarrays based on a delimiting +value+
<add> # or the result of an optional block.
<add> #
<add> # [1, 2, 3, 4, 5].split(3) # => [[1, 2], [4, 5]]
<add> # (1..10).to_a.split { |i| i % 3 == 0 } # => [[1, 2], [4, 5], [7, 8], [10]]
<add> def split(value = nil)
<add> using_block = block_given?
<ide>
<del> results
<del> end
<del> end
<add> inject([[]]) do |results, element|
<add> if (using_block && yield(element)) || (value == element)
<add> results << []
<add> else
<add> results.last << element
<ide> end
<add>
<add> results
<ide> end
<ide> end
<ide> end
<ide><path>activesupport/lib/active_support/core_ext/array/random_access.rb
<del>module ActiveSupport #:nodoc:
<del> module CoreExtensions #:nodoc:
<del> module Array #:nodoc:
<del> module RandomAccess
<del> # Returns a random element from the array.
<del> def rand
<del> self[Kernel.rand(length)]
<del> end
<del> end
<del> end
<add>class Array
<add> # Returns a random element from the array.
<add> def rand
<add> self[Kernel.rand(length)]
<ide> end
<ide> end | 6 |
PHP | PHP | fix issues with postgres | 197c4794141e281cb17b710261933c445f411d64 | <ide><path>src/TestSuite/Fixture/FixtureManager.php
<ide> public function shutDown() {
<ide> $fixture->drop($db);
<ide> }
<ide> }
<del> $db->enableForeignKeys();
<ide> });
<ide> }
<ide> }
<ide><path>tests/Fixture/ArticlesTagFixture.php
<ide> class ArticlesTagFixture extends TestFixture {
<ide> 'article_id' => ['type' => 'integer', 'null' => false],
<ide> 'tag_id' => ['type' => 'integer', 'null' => false],
<ide> '_constraints' => [
<del> 'UNIQUE_TAG2' => ['type' => 'primary', 'columns' => ['article_id', 'tag_id']]
<add> 'unique_tag' => ['type' => 'primary', 'columns' => ['article_id', 'tag_id']],
<add> 'tag_idx' => [
<add> 'type' => 'foreign',
<add> 'columns' => ['tag_id'],
<add> 'references' => ['tags', 'id']
<add> ]
<ide> ]
<ide> );
<ide>
<ide><path>tests/TestCase/Shell/OrmCacheShellTest.php
<ide> class OrmCacheShellTest extends TestCase {
<ide> *
<ide> * @var array
<ide> */
<del> public $fixtures = ['core.article', 'core.tag'];
<add> public $fixtures = ['core.article', 'core.articles_tag', 'core.tag'];
<ide>
<ide> /**
<ide> * setup method | 3 |
Ruby | Ruby | add password warning for pkg uninstall | 94737ef41ddc5352289ed3e3f88f3bd34198197d | <ide><path>Library/Homebrew/cask/artifact/abstract_uninstall.rb
<ide> def uninstall_script(directives, directive_name: :script, force: false, command:
<ide> end
<ide>
<ide> def uninstall_pkgutil(*pkgs, command: nil, **_)
<del> ohai "Uninstalling packages:"
<add> ohai "Uninstalling packages (your password may be necessary):"
<ide> pkgs.each do |regex|
<ide> ::Cask::Pkg.all_matching(regex, command).each do |pkg|
<ide> puts pkg.package_id | 1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.